Created At: 2026-11-18T17:14:57Z Completed At: 2026-11-18T17:14:59Z Command exited with code 0. Command output: core/event_bus.py:45: def subscribe(self, event_type: type[DomainEvent], handler: EventHandler) -> None: grep: core/__pycache__/event_bus.cpython-312.pyc: binary file matches apps/frontend/src/components/pages/AIAgentsPage.tsx:74: description: 'Resolves subscriber FAQs, guides users with step-by-step instructions, and provides assistance.', apps/frontend/src/components/pages/AIAgentsPage.tsx:78: 'You are the official 24/7 Customer Support Concierge for this Telegram bot. Greet subscribers politely, provide concise and accurate solutions to inquiries, explain bot commands, and guide them calmly.', apps/frontend/src/components/pages/AIAgentsPage.tsx:91: description: 'Explains premium subscriptions, exclusive perks, and converts free subscribers into paying members.', apps/frontend/src/components/pages/AIAgentsPage.tsx:108: description: 'Automatically detects the subscriber language (Hindi, Hinglish, English) and chats fluently.', apps/frontend/src/components/pages/AIAgentsPage.tsx:231: content: '🌟 Namaste & Welcome! I am your autonomous AI Assistant. How may I assist your Telegram bot subscribers today?', apps/frontend/src/components/pages/AIAgentsPage.tsx:691: Click a quick test prompt below or type your own question to see how this agent responds to your Telegram subscribers. apps/frontend/src/components/pages/AIAgentsPage.tsx:929: placeholder="Describe how the agent should behave and answer subscriber questions..." apps/frontend/src/components/pages/LanguagesPage.tsx:132: Localized replies and multi-language strings are synced with @{currentBot.username} subscribers in 16 languages. apps/frontend/src/components/pages/UsersPage.tsx:130: Real-time subscriber directory. Inspect preferred languages, bot block states, and broadcast opt-out toggles (/stop or /optout compliance). apps/frontend/src/components/pages/UsersPage.tsx:177: Managing user profiles, locale preferences, and block states for subscribers of @{currentBot.username} ({currentBot.usersCount.toLocaleString()} total members). apps/frontend/src/components/pages/MarketplacePage.tsx:261: headline: 'Grow your Telegram channel rapidly with trackable subscriber invite links.', apps/frontend/src/components/pages/MarketplacePage.tsx:394: mcpTools: ['github.repo.subscribe', 'github.pr.merge'], apps/frontend/src/components/pages/MarketplacePage.tsx:428: mcpTools: ['blockchain.whale.subscribe'], apps/frontend/src/components/pages/BroadcastsPage.tsx:193: Broadcasts dispatched here will be delivered from @{currentBot.username} to its {currentBot.usersCount.toLocaleString()} active subscribers with automatic Telegram rate-limiting. apps/frontend/src/components/pages/BroadcastsPage.tsx:405: Blocked users and opted-out subscribers (/stop or /optout) will be strictly excluded automatically before dispatch. apps/frontend/src/components/pages/MCPProPage.tsx:111: description: 'Retrieves platform telemetry, active subscribers, and operational KPIs for the tenant.', apps/frontend/src/components/pages/BotDetailsPage.tsx:92: description: 'Generates subscriber deep-link invite links (/start ref_{userId}), tracks successful signups, awards points, and calculates balances.', apps/frontend/src/components/pages/BotDetailsPage.tsx:121: description: 'Real-time subscriber tracking, interaction count, automatic BCP 47 language preference detection, and block state auditing.', apps/frontend/src/components/pages/BotDetailsPage.tsx:135: description: 'Matches subscriber text against trigger keywords and forbidden words. Provides instantaneous auto-replies or warnings.', apps/frontend/src/components/pages/HomePage.tsx:668: desc: 'Dispatches 25 msgs/sec compliant rich announcements to thousands of subscribers with real-time delivery tracking.', apps/frontend/src/components/pages/HomePage.tsx:689: desc: 'Comprehensive subscriber directory, custom tags, ban/unban controls, activity history, and engagement analytics.', apps/frontend/src/components/pages/HomePage.tsx:1056: Large networks, unlimited subscribers, isolated databases, and 99.98% SLA. apps/frontend/src/components/modules/ModuleConfigModal.tsx:981: { label: '📚 FAQ Specialist', prompt: 'You are a concise FAQ specialist. Answer subscriber queries with clear, numbered bullet points and helpful links.' }, apps/frontend/src/components/modules/ModuleConfigModal.tsx:1007: When subscriber sends normal text (not a command), reply using AI apps/frontend/src/components/modules/ModuleConfigModal.tsx:1048:
Allow Opt-Out Unsubscribe
apps/frontend/src/context/BotContext.tsx:66: description: 'Generates subscriber deep-link invite links (/start ref_{userId}), tracks successful signups, and awards points.', apps/frontend/src/context/BotContext.tsx:89: description: 'Real-time subscriber tracking, interaction count, automatic BCP 47 language preference detection.', apps/frontend/src/context/BotContext.tsx:100: description: 'Matches subscriber text against trigger keywords and forbidden words. Provides instantaneous auto-replies.', apps/frontend/src/context/BotContext.tsx:122: description: 'Restricts channels, commands, and downloads to active paying VIP subscribers with auto-expiry.', apps/frontend/dist/assets/index-DHrGTvWe.js:36: */function xt(){return xt=Object.assign?Object.assign.bind():function(t){for(var s=1;s{let a=t[n];return s.concat(Array.isArray(a)?a.map(l=>[n,l]):[[n,a]])},[]))}function Cn(t,s){let n=Bt(t);return s&&s.forEach((a,l)=>{n.has(l)||s.getAll(l).forEach(r=>{n.append(l,r)})}),n}const kn=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","viewTransition"],Sn=["aria-current","caseSensitive","className","end","style","to","viewTransition","children"],_n="6";try{window.__reactRouterVersion=_n}catch{}const Tn=i.createContext({isTransitioning:!1}),An="startTransition",ps=ya[An];function Pn(t){let{basename:s,children:n,future:a,window:l}=t,r=i.useRef();r.current==null&&(r.current=Ar({window:l,v5Compat:!0}));let o=r.current,[j,b]=i.useState({action:o.action,location:o.location}),{v7_startTransition:m}=a||{},x=i.useCallback(f=>{m&&ps?ps(()=>b(f)):b(f)},[b,m]);return i.useLayoutEffect(()=>o.listen(x),[o,x]),i.useEffect(()=>fn(a),[a]),i.createElement(vn,{basename:s,children:n,location:j.location,navigationType:j.action,navigator:o,future:a})}const In=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",En=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,A=i.forwardRef(function(s,n){let{onClick:a,relative:l,reloadDocument:r,replace:o,state:j,target:b,to:m,preventScrollReset:x,viewTransition:f}=s,p=ia(s,kn),{basename:g}=i.useContext(we),u,d=!1;if(typeof m=="string"&&En.test(m)&&(u=m,In))try{let N=new URL(window.location.href),y=m.startsWith("//")?new URL(N.protocol+m):new URL(m),E=Ue(y.pathname,g);y.origin===N.origin&&E!=null?m=E+y.search+y.hash:d=!0}catch{}let c=Xr(m,{relative:l}),v=Ln(m,{replace:o,state:j,target:b,preventScrollReset:x,relative:l,viewTransition:f});function h(N){a&&a(N),N.defaultPrevented||v(N)}return i.createElement("a",xt({},p,{href:u||c,onClick:d||r?a:h,ref:n,target:b}))}),Rn=i.forwardRef(function(s,n){let{"aria-current":a="page",caseSensitive:l=!1,className:r="",end:o=!1,style:j,to:b,viewTransition:m,children:x}=s,f=ia(s,Sn),p=vt(b,{relative:f.relative}),g=ue(),u=i.useContext(ea),{navigator:d,basename:c}=i.useContext(we),v=u!=null&&On(p)&&m===!0,h=d.encodeLocation?d.encodeLocation(p).pathname:p.pathname,N=g.pathname,y=u&&u.navigation&&u.navigation.location?u.navigation.location.pathname:null;l||(N=N.toLowerCase(),y=y?y.toLowerCase():null,h=h.toLowerCase()),y&&c&&(y=Ue(y,c)||y);const E=h!=="/"&&h.endsWith("/")?h.length-1:h.length;let w=N===h||!o&&N.startsWith(h)&&N.charAt(E)==="/",S=y!=null&&(y===h||!o&&y.startsWith(h)&&y.charAt(h.length)==="/"),P={isActive:w,isPending:S,isTransitioning:v},k=w?a:void 0,L;typeof r=="function"?L=r(P):L=[r,w?"active":null,S?"pending":null,v?"transitioning":null].filter(Boolean).join(" ");let M=typeof j=="function"?j(P):j;return i.createElement(A,xt({},f,{"aria-current":k,className:L,ref:n,style:M,to:b,viewTransition:m}),typeof x=="function"?x(P):x)});var Ot;(function(t){t.UseScrollRestoration="useScrollRestoration",t.UseSubmit="useSubmit",t.UseSubmitFetcher="useSubmitFetcher",t.UseFetcher="useFetcher",t.useViewTransitionState="useViewTransitionState"})(Ot||(Ot={}));var us;(function(t){t.UseFetcher="useFetcher",t.UseFetchers="useFetchers",t.UseScrollRestoration="useScrollRestoration"})(us||(us={}));function Mn(t){let s=i.useContext(gt);return s||G(!1),s}function Ln(t,s){let{target:n,replace:a,state:l,preventScrollReset:r,relative:o,viewTransition:j}=s===void 0?{}:s,b=ce(),m=ue(),x=vt(t,{relative:o});return i.useCallback(f=>{if(yn(f,n)){f.preventDefault();let p=a!==void 0?a:mt(m)===mt(x);b(t,{replace:p,state:l,preventScrollReset:r,relative:o,viewTransition:j})}},[m,b,x,a,l,n,t,r,o,j])}function Bn(t){let s=i.useRef(Bt(t)),n=i.useRef(!1),a=ue(),l=i.useMemo(()=>Cn(a.search,n.current?null:s.current),[a.search]),r=ce(),o=i.useCallback((j,b)=>{const m=Bt(typeof j=="function"?j(l):j);n.current=!0,r("?"+m,b)},[r,l]);return[l,o]}function On(t,s){s===void 0&&(s={});let n=i.useContext(Tn);n==null&&G(!1);let{basename:a}=Mn(Ot.useViewTransitionState),l=vt(t,{relative:s.relative});if(!n.isTransitioning)return!1;let r=Ue(n.currentLocation.pathname,a)||n.currentLocation.pathname,o=Ue(n.nextLocation.pathname,a)||n.nextLocation.pathname;return Mt(l.pathname,o)!=null||Mt(l.pathname,r)!=null}const oa=i.createContext(void 0),Dn=({children:t})=>{const[s,n]=i.useState(()=>localStorage.getItem("access_token")),[a,l]=i.useState(()=>localStorage.getItem("refresh_token")),[r,o]=i.useState(()=>{const u=localStorage.getItem("auth_user");if(u)try{return JSON.parse(u)}catch{return null}return null}),[j,b]=i.useState(!0),m=async u=>{var d,c;try{const v=await fetch("/api/v1/auth/me",{headers:{Authorization:`Bearer ${u}`}});if(v.ok){const h=await v.json();if(h.success&&h.data)return o(h.data),localStorage.setItem("auth_user",JSON.stringify(h.data)),h.data}else if(v.status===401&&a){const h=await fetch("/api/v1/auth/refresh",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refresh_token:a})});if(h.ok){const N=await h.json(),y=(d=N.data)==null?void 0:d.access_token,E=(c=N.data)==null?void 0:c.refresh_token;if(y)return n(y),localStorage.setItem("access_token",y),E&&(l(E),localStorage.setItem("refresh_token",E)),m(y)}p()}}catch(v){console.warn("Could not fetch user profile:",v)}return null};i.useEffect(()=>{s?m(s).finally(()=>b(!1)):b(!1)},[]);const x=async u=>{var d;b(!0);try{const c=await fetch("/api/v1/auth/telegram",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)}),v=await c.json();if(c.ok&&v.success&&v.data){const{access_token:h,refresh_token:N}=v.data;return n(h),l(N),localStorage.setItem("access_token",h),N&&localStorage.setItem("refresh_token",N),await m(h),b(!1),{success:!0}}else return b(!1),{success:!1,error:v.message||((d=v.error)==null?void 0:d.message)||"Telegram verification failed"}}catch(c){return b(!1),{success:!1,error:c.message||"Network error during login"}}},f=async(u,d)=>{var c;b(!0);try{const v=await fetch("/api/v1/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:u,password:d})}),h=await v.json();if(v.ok&&h.success&&h.data){const{access_token:N,refresh_token:y}=h.data;return n(N),l(y),localStorage.setItem("access_token",N),y&&localStorage.setItem("refresh_token",y),await m(N),b(!1),{success:!0}}else return b(!1),{success:!1,error:h.message||((c=h.error)==null?void 0:c.message)||"Invalid email or password"}}catch(v){return b(!1),{success:!1,error:v.message||"Network error during login"}}},p=()=>{a&&fetch("/api/v1/auth/logout",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refresh_token:a})}).catch(()=>{}),n(null),l(null),o(null),localStorage.removeItem("access_token"),localStorage.removeItem("refresh_token"),localStorage.removeItem("auth_user")},g=async()=>{s&&await m(s)};return e.jsx(oa.Provider,{value:{user:r,token:s,isAuthenticated:!!s,isLoading:j,loginWithTelegram:x,loginWithEmail:f,logout:p,refreshUserProfile:g},children:t})},qe=()=>{const t=i.useContext(oa);if(!t)throw new Error("useAuth must be used within an AuthProvider");return t},ca=i.createContext(void 0),Fn=({children:t})=>{const[s,n]=i.useState(()=>localStorage.getItem("app_theme")==="dark"?"dark":"light");i.useEffect(()=>{const r=document.documentElement;s==="light"?(r.classList.remove("dark"),r.classList.add("light")):(r.classList.remove("light"),r.classList.add("dark")),localStorage.setItem("app_theme",s)},[s]);const a=()=>{n(r=>r==="light"?"dark":"light")},l=r=>{n(r)};return e.jsx(ca.Provider,{value:{theme:s,toggleTheme:a,setTheme:l},children:t})},nt=()=>{const t=i.useContext(ca);if(!t)throw new Error("useTheme must be used within a ThemeProvider");return t},Qe=[{id:"welcome_message",name:"Welcome Message & Onboarding",category:"engagement",description:"Custom greeting message, dynamic placeholders ({first_name}, {bot_name}), and inline action buttons on /start.",is_enabled:!0,config:{welcome_text:"🌟 Welcome to our VIP Bot! Tap an option below to explore:",buttons_count:4}},{id:"force_join",name:"Force Join Channel Guard",category:"security",description:"Mandatory channel/group membership before unlocking bot commands. Verifies status via getChatMember.",is_enabled:!0,config:{channel_username:"@astraea_cloud",prompt_text:"⚠️ You must join our official Telegram channel to unlock this bot.",button_text:"📢 Join Official Channel"}},{id:"referrals",name:"Referral & Viral Growth Engine",category:"growth",description:"Generates subscriber deep-link invite links (/start ref_{userId}), tracks successful signups, and awards points.",is_enabled:!0,config:{points_per_referral:10,welcome_bonus_points:5,min_payout_points:50}},{id:"broadcasts",name:"Broadcast & Announcement Pipeline",category:"messaging",description:"Token-bucket broadcasts (25 msgs/sec), audience filtering, language targeting, and /optout compliance.",is_enabled:!0,config:{rate_limit_per_second:25,allow_opt_out:!0}},{id:"user_management",name:"Audience & Subscriber Directory",category:"management",description:"Real-time subscriber tracking, interaction count, automatic BCP 47 language preference detection.",is_enabled:!0,config:{auto_detect_locale:!0,track_interactions:!0}},{id:"auto_filter",name:"Auto Filter & Keyword Responder",category:"automation",description:"Matches subscriber text against trigger keywords and forbidden words. Provides instantaneous auto-replies.",is_enabled:!0,config:{rules_count:3,blocked_words:["scam","free nitro","hack"]}},{id:"payments",name:"In-Chat Payments & Invoicing",category:"monetization",description:"Seamless Razorpay & Stripe in-chat payment links with cryptographic webhook verification.",is_enabled:!1,config:{currency:"INR",gateway:"razorpay"}},{id:"subscriptions",name:"VIP Tiered Subscription Gates",category:"monetization",description:"Restricts channels, commands, and downloads to active paying VIP subscribers with auto-expiry.",is_enabled:!0,config:{plans_count:3,grace_period_days:2}},{id:"ai_assistant",name:"Autonomous AI Agent Concierge",category:"ai",description:"Multi-turn LLM support concierge powered by OpenAI/Anthropic/Gemini with encrypted API keys and tools.",is_enabled:!0,config:{model:"gemini-1.5-pro",temperature:.7,max_tokens:1024}}],hs=[{id:"b-001",name:"Astraea Concierge Bot",username:"astraea_flagship_bot",status:"active",defaultLocale:"en",keyVersion:1,webhookUrl:"https://api.yourdomain.com/webhooks/telegram/b-001",usersCount:14280,messages24h:38400,latencyMs:38,uptimePct:99.98,createdAt:"2026-11-01T10:00:00Z",templateName:"VIP Club & Community Gatekeeper",checklist:{tokenConnected:!0,templateSelected:!0,modulesConfigured:!0,welcomeMessageSet:!0,testedInTelegram:!0},modules:Qe},{id:"b-002",name:"VIP Concierge & Support",username:"vip_concierge_bot",status:"active",defaultLocale:"en",keyVersion:1,webhookUrl:"https://api.yourdomain.com/webhooks/telegram/b-002",usersCount:6890,messages24h:12100,latencyMs:42,uptimePct:99.95,createdAt:"2026-11-05T14:30:00Z",templateName:"Customer Support Desk & Ticket Escalation",checklist:{tokenConnected:!0,templateSelected:!0,modulesConfigured:!0,welcomeMessageSet:!0,testedInTelegram:!1},modules:Qe.map(t=>({...t,is_enabled:["welcome_message","ai_assistant","user_management"].includes(t.id)}))},{id:"b-003",name:"Automated Flash Billing",username:"flash_billing_bot",status:"active",defaultLocale:"hi",keyVersion:1,webhookUrl:"https://api.yourdomain.com/webhooks/telegram/b-003",usersCount:9420,messages24h:21900,latencyMs:35,uptimePct:99.99,createdAt:"2026-11-10T09:15:00Z",templateName:"E-Commerce Digital Store & Cart",checklist:{tokenConnected:!0,templateSelected:!0,modulesConfigured:!0,welcomeMessageSet:!1,testedInTelegram:!1},modules:Qe.map(t=>({...t,is_enabled:["welcome_message","payments","subscriptions","broadcasts"].includes(t.id)}))},{id:"b-004",name:"Omni Broadcast Announcer",username:"omni_broadcast_bot",status:"active",defaultLocale:"en",keyVersion:1,webhookUrl:"https://api.yourdomain.com/webhooks/telegram/b-004",usersCount:31200,messages24h:89400,latencyMs:48,uptimePct:99.9,createdAt:"2026-11-12T18:00:00Z",templateName:"Channel Broadcast & Content Syndicator",checklist:{tokenConnected:!0,templateSelected:!0,modulesConfigured:!1,welcomeMessageSet:!1,testedInTelegram:!1},modules:Qe.map(t=>({...t,is_enabled:["broadcasts","user_management","force_join"].includes(t.id)}))}],da=i.createContext(void 0),$n=({children:t})=>{const[s,n]=i.useState(()=>{try{const p=localStorage.getItem("telebot_bots");if(p)return JSON.parse(p)}catch{}return hs}),[a,l]=i.useState(()=>{try{const p=localStorage.getItem("telebot_active_bot_id");if(p&&hs.some(g=>g.id===p||g.username===p))return p}catch{}return"b-001"});i.useEffect(()=>{try{localStorage.setItem("telebot_bots",JSON.stringify(s))}catch{}},[s]),i.useEffect(()=>{try{localStorage.setItem("telebot_active_bot_id",a)}catch{}},[a]);const r=s.find(p=>p.id===a||p.username===a)||s[0],o=p=>{const g=p.replace("@","").toLowerCase(),u=s.find(d=>d.id===p||d.username.toLowerCase()===g);u&&l(u.id)},j=async(p,g,u="en")=>{const d=p.toLowerCase().replace(/[^a-z0-9]/g,"_")+"_bot",c=`b-${Date.now().toString().slice(-4)}`,v={id:c,name:p||"My New Telegram Bot",username:d,status:"active",defaultLocale:u,keyVersion:1,webhookUrl:`https://api.yourdomain.com/webhooks/telegram/${c}`,usersCount:1,messages24h:0,latencyMs:38,uptimePct:100,createdAt:new Date().toISOString(),templateName:"Blank Telegram Starter",checklist:{tokenConnected:!0,templateSelected:!1,modulesConfigured:!1,welcomeMessageSet:!1,testedInTelegram:!1},modules:Qe.map(h=>({...h,is_enabled:h.id==="welcome_message"}))};return n(h=>[v,...h]),l(v.id),v},b=(p,g,u)=>{n(d=>d.map(c=>{if(c.id!==p)return c;const v=c.modules.map(h=>{if(h.id!==g)return h;const N=u!==void 0?u:!h.is_enabled;return{...h,is_enabled:N}});return{...c,modules:v,checklist:{...c.checklist,modulesConfigured:!0}}}))},m=(p,g,u)=>{n(d=>d.map(c=>c.id!==p?c:{...c,modules:c.modules.map(v=>v.id===g?{...v,config:{...v.config,...u}}:v)}))},x=(p,g)=>{n(u=>u.map(d=>d.id!==p?d:{...d,checklist:{...d.checklist,[g]:!d.checklist[g]}}))},f=(p,g,u)=>{n(d=>d.map(c=>c.id!==p?c:{...c,templateName:g,checklist:{...c.checklist,templateSelected:!0,modulesConfigured:!0},modules:c.modules.map(v=>({...v,is_enabled:u.includes(v.id)||v.id==="welcome_message"}))}))};return e.jsx(da.Provider,{value:{bots:s,currentBot:r,selectBot:o,registerBot:j,toggleBotModule:b,updateModuleConfig:m,toggleChecklistStep:x,applyTemplateToBot:f},children:t})},z=()=>{const t=i.useContext(da);if(!t)throw new Error("useBot must be used within a BotProvider");return t},wt={overview:"/dashboard",marketplace:"/marketplace","bot-builder":"/dashboard/builder","mcp-pro":"/dashboard/mcp",bots:"/dashboard/bots","bot-details":"/dashboard/bots/astraea-flagship","message-studio":"/dashboard/studio",broadcasts:"/dashboard/broadcasts","ai-agents":"/dashboard/agents",plugins:"/dashboard/plugins",users:"/dashboard/users",emojis:"/dashboard/emojis",languages:"/dashboard/languages",subscriptions:"/dashboard/subscriptions",payments:"/dashboard/payments",team:"/dashboard/team",analytics:"/dashboard/analytics",settings:"/dashboard/settings","audit-logs":"/dashboard/audit-logs"};function ma(t){return t==="/marketplace"||t.startsWith("/marketplace")?"marketplace":t==="/dashboard/builder"?"bot-builder":t==="/dashboard/mcp"?"mcp-pro":t==="/dashboard/studio"?"message-studio":t==="/dashboard/broadcasts"?"broadcasts":t==="/dashboard/agents"?"ai-agents":t==="/dashboard/plugins"?"plugins":t==="/dashboard/users"?"users":t==="/dashboard/emojis"?"emojis":t==="/dashboard/languages"?"languages":t==="/dashboard/subscriptions"?"subscriptions":t==="/dashboard/payments"?"payments":t==="/dashboard/team"?"team":t==="/dashboard/analytics"?"analytics":t==="/dashboard/settings"?"settings":t==="/dashboard/audit-logs"?"audit-logs":t==="/dashboard/bots"?"bots":t.startsWith("/dashboard/bots/")?"bot-details":"overview"}const Un=[{label:"BOT BUILDER & FLEET",items:[{id:"overview",name:"Overview",icon:Dt},{id:"bots",name:"My Telegram Bots",icon:Q,badge:"Fleet"},{id:"marketplace",name:"Ready-Made Bot Store",icon:Ft,badge:"25"},{id:"bot-details",name:"Modular Studio",icon:at,badge:"9 Core"},{id:"bot-builder",name:"Visual Bot Flow",icon:Cs,badge:"Builder"},{id:"message-studio",name:"Welcome & Message Studio",icon:$t,badge:"PRO"}]},{label:"MODULES & AUDIENCE",items:[{id:"broadcasts",name:"Broadcast Engine",icon:pe},{id:"users",name:"Subscribers & Referrals",icon:Ae},{id:"plugins",name:"Plugins & Integrations",icon:ka},{id:"ai-agents",name:"AI Agent Studio",icon:Sa,badge:"LLM"},{id:"mcp-pro",name:"MCP Pro Cloud",icon:fe,badge:"RPC"}]},{label:"COMMERCE & LOCALIZATION",items:[{id:"subscriptions",name:"VIP Subscriptions",icon:Ve},{id:"payments",name:"Payments & Invoicing",icon:Ut},{id:"languages",name:"Languages (16)",icon:_a},{id:"emojis",name:"Custom Emojis",icon:ks}]},{label:"GOVERNANCE & PLATFORM",items:[{id:"team",name:"Team & RBAC",icon:Ss},{id:"analytics",name:"Cloud Analytics",icon:Ta},{id:"audit-logs",name:"Security Audit Logs",icon:Aa},{id:"settings",name:"Platform Settings",icon:Pa}]}],Vn=({currentView:t,onNavigate:s,collapsed:n,onToggleCollapse:a,mobileOpen:l=!1,onCloseMobile:r})=>{const{theme:o,toggleTheme:j}=nt(),{currentBot:b}=z();ce();const m=ue();t||ma(m.pathname);const x=(f=!1)=>e.jsx("div",{className:"flex-1 overflow-y-auto px-3 py-6 space-y-6",children:Un.map((p,g)=>e.jsxs("div",{className:"space-y-1",children:[(!n||f)&&e.jsx("div",{className:"px-3 text-[10px] font-mono tracking-ultra-wide text-pearl-400/80 uppercase font-semibold mb-2",children:p.label}),p.items.map(u=>{const d=u.icon,c=wt[u.id],v=n&&!f;return e.jsx(Rn,{to:c,end:u.id==="overview",onClick:()=>{s&&s(u.id),r&&r()},title:v?u.name:void 0,className:({isActive:h})=>`w-full flex items-center gap-3 px-3 py-2.5 rounded text-xs font-mono tracking-wider transition-all relative ${h?"bg-[#2481CC]/12 text-[#2481CC] border border-[#2481CC]/35 shadow-sm font-semibold":"text-pearl-400 hover:text-pearl-100 hover:bg-space-850 border border-transparent"} ${v?"justify-center px-0":""}`,children:({isActive:h})=>e.jsxs(e.Fragment,{children:[e.jsx(d,{className:`w-4 h-4 shrink-0 ${h?"text-[#2481CC]":"text-pearl-400"}`}),!v&&e.jsx("span",{className:"truncate",children:u.name}),!v&&u.badge&&e.jsx("span",{className:`ml-auto px-1.5 py-0.5 rounded text-[9px] font-mono uppercase ${h?"bg-[#2481CC]/20 text-[#2481CC] border border-[#2481CC]/30 font-semibold":"bg-space-800 text-pearl-400 border border-white/10"}`,children:u.badge}),h&&e.jsx("span",{className:"absolute left-0 top-1/2 -translate-y-1/2 w-1 h-5 rounded-r bg-[#2481CC]"})]})},u.id)})]},g))});return e.jsxs(e.Fragment,{children:[l&&e.jsx("div",{className:"fixed inset-0 z-50 bg-black/80 backdrop-blur-sm md:hidden animate-fadeIn",onClick:r,"aria-hidden":"true"}),e.jsxs("aside",{className:`fixed top-0 left-0 bottom-0 z-50 w-72 bg-space-900 border-r border-white/10 flex flex-col transition-transform duration-300 md:hidden ${l?"translate-x-0 shadow-2xl":"-translate-x-full"}`,children:[e.jsxs("div",{className:"h-20 border-b border-white/10 px-5 flex items-center justify-between",children:[e.jsxs(A,{to:"/",onClick:r,className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-9 h-9 rounded-xl bg-[#2481CC] text-white flex items-center justify-center font-sans font-bold text-base shadow-telegram",children:e.jsx(oe,{className:"w-4 h-4 text-white -rotate-12 translate-x-0.5"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"font-sans text-sm tracking-tight text-pearl-50 font-bold leading-tight",children:["TeleBot",e.jsx("span",{className:"text-[#2481CC]",children:"Cloud"})]}),e.jsx("div",{className:"text-[10px] font-mono text-[#2481CC] uppercase tracking-wide font-medium",children:"Telegram Bot Builder"})]})]}),e.jsx("button",{onClick:r,className:"p-2 text-pearl-400 hover:text-pearl-100 hover:bg-white/5 rounded-md transition-colors","aria-label":"Close navigation",children:e.jsx(H,{className:"w-5 h-5"})})]}),b&&e.jsxs("div",{className:"mx-3 mt-3 p-2.5 rounded-xl bg-space-850 border border-white/10 flex items-center justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[9px] font-mono text-emerald-400 font-semibold uppercase",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"}),e.jsx("span",{children:"ACTIVE BOT CONSOLE"})]}),e.jsx("div",{className:"text-xs font-semibold text-pearl-50 truncate mt-0.5",children:b.name}),e.jsxs("div",{className:"text-[10px] font-mono text-[#2481CC] truncate",children:["@",b.username]})]}),e.jsx(A,{to:"/dashboard/bots",onClick:r,className:"text-[10px] font-mono text-pearl-400 hover:text-[#2481CC] px-2 py-1 rounded bg-white/5 shrink-0",title:"Switch Bot",children:"Switch"})]}),x(!0),e.jsxs("div",{className:"p-4 border-t border-white/10 bg-space-900/50 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs font-mono text-pearl-400",children:[e.jsxs(A,{to:"/pricing",onClick:r,className:"hover:text-[#2481CC] flex items-center gap-1.5",children:[e.jsx(J,{className:"w-3.5 h-3.5 text-[#2481CC]"}),e.jsx("span",{children:"Pricing"})]}),e.jsxs("button",{onClick:j,className:"hover:text-[#2481CC] flex items-center gap-1.5 text-pearl-300 transition-colors",title:"Toggle Theme",children:[o==="light"?e.jsx(De,{className:"w-3.5 h-3.5 text-slate-700"}):e.jsx(Fe,{className:"w-3.5 h-3.5 text-amber-400"}),e.jsx("span",{children:o==="light"?"Dark":"Light"})]}),e.jsxs(A,{to:"/login",onClick:r,className:"hover:text-[#2481CC] flex items-center gap-1.5",children:[e.jsx(ct,{className:"w-3.5 h-3.5 text-[#2481CC]"}),e.jsx("span",{children:"Login"})]})]}),e.jsxs("div",{className:"p-3 rounded bg-space-850/80 border border-white/10",children:[e.jsxs("div",{className:"flex items-center justify-between text-[10px] font-mono text-pearl-400 mb-1",children:[e.jsx("span",{children:"TIER"}),e.jsx("span",{className:"text-[#2481CC] font-semibold",children:"PRO ENTERPRISE"})]}),e.jsx("div",{className:"w-full bg-space-800 rounded-full h-1 overflow-hidden",children:e.jsx("div",{className:"bg-[#2481CC] h-1 w-[40%]"})}),e.jsxs("div",{className:"flex items-center justify-between text-[9px] font-mono text-pearl-400/80 mt-1.5",children:[e.jsx("span",{children:"4 / 10 Bots Active"}),e.jsx("span",{children:"40%"})]})]})]})]}),e.jsxs("aside",{className:`hidden md:flex fixed top-0 left-0 bottom-0 z-40 bg-space-900/95 backdrop-blur-2xl border-r border-white/10 flex-col transition-all duration-300 ${n?"w-20":"w-64"}`,children:[e.jsx("div",{className:"h-20 border-b border-white/10 px-5 flex items-center justify-between",children:n?e.jsx(A,{to:"/",className:"w-10 h-10 mx-auto rounded-xl bg-[#2481CC] text-white flex items-center justify-center font-sans font-bold shadow-telegram",title:"TeleBot Cloud",children:e.jsx(oe,{className:"w-5 h-5 text-white -rotate-12 translate-x-0.5"})}):e.jsxs(A,{to:"/",className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-9 h-9 rounded-xl bg-[#2481CC] text-white flex items-center justify-center font-sans font-bold text-base shadow-telegram",children:e.jsx(oe,{className:"w-4 h-4 text-white -rotate-12 translate-x-0.5"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"font-sans text-sm tracking-tight text-pearl-50 font-bold leading-tight",children:["TeleBot",e.jsx("span",{className:"text-[#2481CC]",children:"Cloud"})]}),e.jsx("div",{className:"text-[10px] font-mono text-[#2481CC] uppercase tracking-wide font-medium",children:"Telegram Bot Builder"})]})]})}),!n&&b?e.jsxs("div",{className:"mx-3 mt-3 p-2.5 rounded-xl bg-space-850/80 border border-white/10 flex items-center justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[9px] font-mono text-emerald-400 font-semibold uppercase",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"}),e.jsx("span",{children:"ACTIVE BOT CONSOLE"})]}),e.jsx("div",{className:"text-xs font-semibold text-pearl-50 truncate mt-0.5",children:b.name}),e.jsxs("div",{className:"text-[10px] font-mono text-[#2481CC] truncate",children:["@",b.username]})]}),e.jsx(A,{to:"/dashboard/bots",className:"text-[10px] font-mono text-pearl-400 hover:text-[#2481CC] px-2 py-1 rounded bg-white/5 shrink-0 ml-1",title:"Switch Bot",children:"Switch"})]}):n&&b?e.jsx("div",{className:"mx-auto mt-2 text-center",title:`Active Bot: ${b.name} (@${b.username})`,children:e.jsxs("div",{className:"w-8 h-8 mx-auto rounded-lg bg-[#2481CC]/15 border border-[#2481CC]/40 flex items-center justify-center text-[#2481CC] relative",children:[e.jsx(Q,{className:"w-4 h-4"}),e.jsx("span",{className:"absolute -top-0.5 -right-0.5 w-2 h-2 rounded-full bg-emerald-400 animate-pulse"})]})}):null,x(!1),e.jsxs("div",{className:"p-3 border-t border-white/10 bg-space-900/50",children:[n?e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsx(A,{to:"/login",title:"Sign In",className:"text-pearl-400 hover:text-[#2481CC] p-1",children:e.jsx(ct,{className:"w-4 h-4"})}),e.jsx("div",{className:"w-2 h-2 rounded-full bg-emerald-400 mx-auto",title:"System Operational"})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between text-[11px] font-mono text-pearl-400 px-1",children:[e.jsxs(A,{to:"/pricing",className:"hover:text-[#2481CC] flex items-center gap-1",children:[e.jsx(J,{className:"w-3 h-3 text-[#2481CC]"}),e.jsx("span",{children:"Pricing"})]}),e.jsxs("button",{onClick:j,className:"hover:text-[#2481CC] flex items-center gap-1 text-pearl-300 transition-colors",title:"Toggle Theme",children:[o==="light"?e.jsx(De,{className:"w-3 h-3 text-slate-700"}):e.jsx(Fe,{className:"w-3 h-3 text-amber-400"}),e.jsx("span",{children:o==="light"?"Dark":"Light"})]}),e.jsxs(A,{to:"/login",className:"hover:text-[#2481CC] flex items-center gap-1",children:[e.jsx(ct,{className:"w-3 h-3 text-[#2481CC]"}),e.jsx("span",{children:"Login"})]})]}),e.jsxs("div",{className:"p-3 rounded bg-space-850/80 border border-white/10",children:[e.jsxs("div",{className:"flex items-center justify-between text-[10px] font-mono text-pearl-400 mb-1",children:[e.jsx("span",{children:"TIER"}),e.jsx("span",{className:"text-[#2481CC] font-semibold",children:"PRO ENTERPRISE"})]}),e.jsx("div",{className:"w-full bg-space-800 rounded-full h-1 overflow-hidden",children:e.jsx("div",{className:"bg-[#2481CC] h-1 w-[40%]"})}),e.jsxs("div",{className:"flex items-center justify-between text-[9px] font-mono text-pearl-400/80 mt-1.5",children:[e.jsx("span",{children:"4 / 10 Bots Active"}),e.jsx("span",{children:"40%"})]})]})]}),e.jsx("button",{onClick:a,className:"mt-2 w-full py-2 flex items-center justify-center text-pearl-400 hover:text-[#2481CC] hover:bg-space-850 rounded-xl transition-colors text-xs",title:n?"Expand Sidebar":"Collapse Sidebar",children:n?e.jsx(Te,{className:"w-4 h-4"}):e.jsx(Ca,{className:"w-4 h-4"})})]})]})]})},xa=[{code:"en",name:"English",nativeName:"English",flag:"🇬🇧",isRtl:!1},{code:"hi",name:"Hindi",nativeName:"हिंदी",flag:"🇮🇳",isRtl:!1},{code:"hi-Latn",name:"Hinglish",nativeName:"Hinglish",flag:"🇮🇳",isRtl:!1},{code:"sa",name:"Sanskrit",nativeName:"संस्कृतम्",flag:"🕉️",isRtl:!1},{code:"ar",name:"Arabic",nativeName:"العربية",flag:"🇸🇦",isRtl:!0},{code:"ur",name:"Urdu",nativeName:"اردو",flag:"🇵🇰",isRtl:!0},{code:"bn",name:"Bengali",nativeName:"বাংলা",flag:"🇧🇩",isRtl:!1},{code:"ta",name:"Tamil",nativeName:"தமிழ்",flag:"🇮🇳",isRtl:!1},{code:"te",name:"Telugu",nativeName:"తెలుగు",flag:"🇮🇳",isRtl:!1},{code:"mr",name:"Marathi",nativeName:"मराठी",flag:"🇮🇳",isRtl:!1},{code:"gu",name:"Gujarati",nativeName:"ગુજરાતી",flag:"🇮🇳",isRtl:!1},{code:"es",name:"Spanish",nativeName:"Español",flag:"🇪🇸",isRtl:!1},{code:"fr",name:"French",nativeName:"Français",flag:"🇫🇷",isRtl:!1},{code:"de",name:"German",nativeName:"Deutsch",flag:"🇩🇪",isRtl:!1},{code:"ru",name:"Russian",nativeName:"Русский",flag:"🇷🇺",isRtl:!1},{code:"ja",name:"Japanese",nativeName:"日本語",flag:"🇯🇵",isRtl:!1}],pa="en",bs=t=>{const s=xa.find(n=>n.code===t);return s?s.isRtl:!1},Hn={title:"Telegram SaaS Platform",overview:"Overview",bots:"Connected Bots",users:"Active Users",analytics:"Analytics",billing:"Billing & Plans",settings:"Workspace Settings"},Gn={save:"Save Changes",cancel:"Cancel",delete:"Delete",connect_bot:"Connect New Bot"},zn={dashboard:Hn,actions:Gn},Wn={title:"टेलीग्राम सास प्लेटफॉर्म",overview:"अवलोकन",bots:"कनेक्टेड बॉट्स",users:"सक्रिय उपयोगकर्ता",analytics:"एनालिटिक्स",billing:"बिलिंग और योजनाएं",settings:"कार्यस्थान सेटिंग्स"},qn={save:"परिवर्तन सहेजें",cancel:"रद्द करें",delete:"हटाएं",connect_bot:"नया बॉट जोड़ें"},Jn={dashboard:Wn,actions:qn},Yn={title:"Telegram SaaS Manch",overview:"Kul Jaankari",bots:"Jude Hue Bots",users:"Sakriya Users",analytics:"Stats aur Analytics",billing:"Billing aur Plans",settings:"Workspace Settings Badlein"},Kn={save:"Changes Save Karein",cancel:"Radd Karein",delete:"Delete Karein",connect_bot:"Naya Bot Connect Karein"},Qn={dashboard:Yn,actions:Kn},Zn={title:"टेलीग्राम सास मञ्चम्",overview:"सिंहावलोकनम्",bots:"संयोजिताः बॉट्स",users:"सक्रियाः प्रयोक्तारः",analytics:"विश्लेषणम्",billing:"शुल्कम् च योजनाः",settings:"कार्यस्थान व्यवस्था"},Xn={save:"परिवर्तनानि रक्षतु",cancel:"निरसयतु",delete:"मार्जयतु",connect_bot:"नवीन बॉट योजयतु"},el={dashboard:Zn,actions:Xn},tl={title:"منصة تيليجرام ساس",overview:"نظرة عامة",bots:"البوتات المتصلة",users:"المستخدمون النشطون",analytics:"التحليلات",billing:"الفواتير والخطط",settings:"إعدادات مساحة العمل"},sl={save:"حفظ التغييرات",cancel:"إلغاء",delete:"حذف",connect_bot:"ربط بوت جديد"},al={dashboard:tl,actions:sl},rl={title:"ٹیلیگرام ساس پلیٹ فارم",overview:"جائزہ",bots:"منسلک بوٹس",users:"فعال صارفین",analytics:"تجزیات",billing:"بلنگ اور منصوبے",settings:"ورک اسپیس کی ترتیبات"},nl={save:"تبدیلیاں محفوظ کریں",cancel:"منسوخ کریں",delete:"حذف کریں",connect_bot:"نیا بوٹ شامل کریں"},ll={dashboard:rl,actions:nl},il={title:"টেলিগ্রাম সাস প্ল্যাটফর্ম",overview:"সারসংক্ষেপ",bots:"সংযুক্ত বট",users:"সক্রিয় ব্যবহারকারী",analytics:"বিশ্লেষণ",billing:"বিলিং এবং পরিকল্পনা",settings:"ওয়ার্কস্পেস সেটিংস"},ol={save:"সংরক্ষণ করুন",cancel:"বাতিল",delete:"মুছুন",connect_bot:"নতুন বট সংযুক্ত করুন"},cl={dashboard:il,actions:ol},dl={title:"டெலிகிராம் SaaS தளம்",overview:"மேலோட்டம்",bots:"இணைக்கப்பட்ட பாட்கள்",users:"செயலில் உள்ள பயனர்கள்",analytics:"பகுப்பாய்வு",billing:"பில்லிங் & திட்டங்கள்",settings:"பணிவெளி அமைப்புகள்"},ml={save:"மாற்றங்களைச் சேமி",cancel:"ரத்து செய்",delete:"நீக்கு",connect_bot:"புதிய பாட் இணைக்கவும்"},xl={dashboard:dl,actions:ml},pl={title:"టెలిగ్రామ్ SaaS ప్లాట్‌ఫారమ్",overview:"అవలోకనం",bots:"కనెక్ట్ చేయబడిన బాట్లు",users:"క్రియాశీల వినియోగదారులు",analytics:"విశ్లేషణలు",billing:"బిల్లింగ్ & ప్లాన్లు",settings:"వర్క్‌స్పేస్ సెట్టింగులు"},ul={save:"మార్పులను సేవ్ చేయండి",cancel:"రద్దు చేయండి",delete:"తొలగించండి",connect_bot:"కొత్త బాట్ కనెక్ట్ చేయండి"},hl={dashboard:pl,actions:ul},bl={title:"टेलिग्राम SaaS प्लॅटफॉर्म",overview:"आढावा",bots:"कनेक्ट केलेले बॉट्स",users:"सक्रिय वापरकर्ते",analytics:"अ‍ॅनालिटिक्स",billing:"बिलिंग आणि योजना",settings:"वर्कस्पेस सेटिंग्ज"},fl={save:"बदल जतन करा",cancel:"रद्द करा",delete:"हटवा",connect_bot:"नवीन बॉट कनेक्ट करा"},gl={dashboard:bl,actions:fl},jl={title:"ટેલિગ્રામ SaaS પ્લેટફોર્મ",overview:"અવલોકન",bots:"જોડાયેલા બોટ્સ",users:"સક્રિય વપરાશકર્તાઓ",analytics:"એનાલિટિક્સ",billing:"બિલિંગ અને યોજનાઓ",settings:"વર્કસ્પેસ સેટિંગ્સ"},vl={save:"ફેરફારો સાચવો",cancel:"રદ કરો",delete:"કાઢી નાખો",connect_bot:"નવું બોટ જોડો"},wl={dashboard:jl,actions:vl},Nl={title:"Plataforma SaaS de Telegram",overview:"Visión General",bots:"Bots Conectados",users:"Usuarios Activos",analytics:"Analítica",billing:"Facturación y Planes",settings:"Configuración del Espacio de Trabajo"},yl={save:"Guardar Cambios",cancel:"Cancelar",delete:"Eliminar",connect_bot:"Conectar Nuevo Bot"},Cl={dashboard:Nl,actions:yl},kl={title:"Plateforme SaaS Telegram",overview:"Vue d'ensemble",bots:"Bots Connectés",users:"Utilisateurs Actifs",analytics:"Analytique",billing:"Facturation & Plans",settings:"Paramètres de l'Espace de Travail"},Sl={save:"Enregistrer les Modifications",cancel:"Annuler",delete:"Supprimer",connect_bot:"Connecter un Nouveau Bot"},_l={dashboard:kl,actions:Sl},Tl={title:"Telegram SaaS-Plattform",overview:"Übersicht",bots:"Verbundene Bots",users:"Aktive Benutzer",analytics:"Analytik",billing:"Abrechnung & Tarife",settings:"Arbeitsbereich-Einstellungen"},Al={save:"Änderungen speichern",cancel:"Abbrechen",delete:"Löschen",connect_bot:"Neuen Bot verbinden"},Pl={dashboard:Tl,actions:Al},Il={title:"Telegram SaaS-платформа",overview:"Обзор",bots:"Подключенные боты",users:"Активные пользователи",analytics:"Аналитика",billing:"Тарифы и оплата",settings:"Настройки рабочей области"},El={save:"Сохранить изменения",cancel:"Отмена",delete:"Удалить",connect_bot:"Подключить нового бота"},Rl={dashboard:Il,actions:El},Ml={title:"Telegram SaaS プラットフォーム",overview:"概要",bots:"接続済みボット",users:"アクティブユーザー",analytics:"アナリティクス",billing:"請求とプラン",settings:"ワークスペース設定"},Ll={save:"変更を保存",cancel:"キャンセル",delete:"削除",connect_bot:"新しいボットを接続"},Bl={dashboard:Ml,actions:Ll},fs={en:zn,hi:Jn,"hi-Latn":Qn,sa:el,ar:al,ur:ll,bn:cl,ta:xl,te:hl,mr:gl,gu:wl,es:Cl,fr:_l,de:Pl,ru:Rl,ja:Bl},Ol=(t,s)=>{const[n,a]=s.split("."),l=fs[t]||fs[pa];return!l||!l[n]?a||s:l[n][a]||a},Dl=()=>{const[t,s]=i.useState(()=>localStorage.getItem("saas_locale")||pa),n=bs(t),a=i.useCallback(r=>{s(r),localStorage.setItem("saas_locale",r),document.documentElement.lang=r,document.documentElement.dir=bs(r)?"rtl":"ltr"},[]);i.useEffect(()=>{document.documentElement.lang=t,document.documentElement.dir=n?"rtl":"ltr"},[t,n]);const l=i.useCallback(r=>Ol(t,r),[t]);return{currentLocale:t,isRtl:n,setLanguage:a,t:l,supportedLanguages:xa}},Fl=()=>{const{currentLocale:t,setLanguage:s,supportedLanguages:n}=Dl();return e.jsx("div",{className:"relative inline-block text-left",children:e.jsx("select",{value:t,onChange:a=>s(a.target.value),className:"block w-auto max-w-[80px] xs:max-w-[110px] sm:max-w-[150px] md:max-w-none rounded-lg border border-white/10 bg-space-900 py-1 sm:py-1.5 pl-2 pr-6 text-[11px] sm:text-xs font-mono text-pearl-100 shadow-sm focus:border-[#2481CC] focus:ring-1 focus:ring-[#2481CC] focus:outline-none cursor-pointer truncate","aria-label":"Select Language",children:n.map(a=>e.jsxs("option",{value:a.code,children:[a.flag," ",a.name]},a.code))})})},$l=({currentView:t,currentBotName:s,onSelectBotModal:n,collapsed:a,onOpenMobileMenu:l})=>{var L;const{user:r,isAuthenticated:o,logout:j}=qe(),{theme:b,toggleTheme:m}=nt(),{currentBot:x,bots:f,selectBot:p}=z();ue();const[g,u]=i.useState(3),[d,c]=i.useState(!1),[v,h]=i.useState(!1),[N,y]=i.useState(""),E=i.useRef(null);i.useEffect(()=>{const M=_=>{E.current&&!E.current.contains(_.target)&&h(!1)};return document.addEventListener("mousedown",M),()=>document.removeEventListener("mousedown",M)},[]);const w=(f||[]).filter(M=>M.name.toLowerCase().includes(N.toLowerCase())||M.username.toLowerCase().includes(N.toLowerCase())),[S,P]=i.useState([{id:"n-1",title:"Broadcast Campaign Completed",message:"Spring Flash Sale 2026 dispatched successfully to 14,280 recipients with 99.8% delivery.",type:"broadcast",priority:"normal",is_read:!1,created_at:new Date(Date.now()-1e3*60*15).toISOString()},{id:"n-2",title:"AI Usage Limit Warning",message:"Monthly AI token consumption reached 65% of Pro tier limit (650,000 / 1,000,000 tokens).",type:"billing",priority:"high",is_read:!1,created_at:new Date(Date.now()-1e3*60*120).toISOString()},{id:"n-3",title:"Crypto Price Plugin Triggered",message:"BTC/USD threshold crossed $96,000. Automated alert broadcast executed.",type:"plugin",priority:"low",is_read:!1,created_at:new Date(Date.now()-1e3*60*360).toISOString()}]);i.useEffect(()=>{fetch("/api/v1/notifications/unread-count").then(M=>M.ok?M.json():null).then(M=>{var _;((_=M==null?void 0:M.data)==null?void 0:_.unread_count)!==void 0&&u(M.data.unread_count)}).catch(()=>{})},[]);const k=async()=>{const M=S.filter(_=>!_.is_read).map(_=>_.id);if(M.length>0)try{await fetch("/api/v1/notifications/mark-read",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({notification_ids:M})})}catch{}P(_=>_.map(Y=>({...Y,is_read:!0}))),u(0)};return e.jsxs("header",{className:`fixed top-0 right-0 z-30 h-16 sm:h-20 bg-space-900/95 backdrop-blur-md border-b border-white/10 px-3 sm:px-6 flex items-center justify-between transition-all duration-300 left-0 ${a?"md:left-20":"md:left-64"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 min-w-0 max-w-[40%] xs:max-w-[45%] sm:max-w-none",children:[e.jsx("button",{onClick:l,className:"p-1.5 sm:p-2 -ml-1 text-pearl-300 hover:text-[#2481CC] hover:bg-white/5 rounded-lg md:hidden transition-colors shrink-0","aria-label":"Open mobile navigation",children:e.jsx(_s,{className:"w-5 h-5"})}),e.jsxs("div",{className:"hidden sm:flex items-center gap-2 text-xs font-mono tracking-widest text-pearl-400 truncate",children:[e.jsx(A,{to:"/",className:"hover:text-[#2481CC] transition-colors shrink-0 font-semibold text-[#2481CC]",children:"TELEBOT"}),e.jsx("span",{className:"text-[#2481CC]/60",children:"/"}),e.jsx(A,{to:wt[t]||"/dashboard",className:"text-pearl-200 uppercase hover:text-[#2481CC] transition-colors truncate",children:t.replace("-"," ")})]}),e.jsx(A,{to:"/",className:"sm:hidden font-sans text-xs text-pearl-100 uppercase tracking-wide truncate font-bold hover:text-[#2481CC] min-w-0",children:t.replace("-"," ")})]}),e.jsxs("div",{className:"flex items-center gap-1.5 sm:gap-2.5 md:gap-4 shrink-0",children:[e.jsxs("div",{className:"relative shrink-0",ref:E,children:[e.jsxs("button",{type:"button",onClick:()=>h(!v),className:"flex items-center gap-1.5 sm:gap-2 px-2 sm:px-3 py-1.5 rounded-lg bg-space-850/90 border border-white/10 text-xs font-mono text-pearl-100 hover:border-[#2481CC]/50 hover:bg-[#2481CC]/10 transition-colors shadow-sm",title:"Switch Telegram Bot Console (Play Console Architecture)",children:[e.jsx("span",{className:"w-2 h-2 rounded-full bg-emerald-400 animate-pulse shrink-0"}),e.jsxs("div",{className:"text-left hidden sm:block",children:[e.jsx("div",{className:"font-sans font-semibold text-pearl-50 text-[11px] leading-tight truncate max-w-[120px] md:max-w-[160px]",children:(x==null?void 0:x.name)||s}),e.jsxs("div",{className:"text-[9px] font-mono text-[#2481CC] leading-tight truncate max-w-[120px] md:max-w-[160px]",children:["@",(x==null?void 0:x.username)||"bot"]})]}),e.jsxs("span",{className:"sm:hidden font-sans font-semibold text-xs text-pearl-50 truncate max-w-[85px]",children:["@",(x==null?void 0:x.username)||"bot"]}),e.jsx(Vt,{className:`w-3.5 h-3.5 text-pearl-400 ml-0.5 transition-transform shrink-0 ${v?"rotate-180 text-[#2481CC]":""}`})]}),v&&e.jsxs("div",{className:"fixed sm:absolute left-3 right-3 sm:left-auto sm:right-0 top-18 sm:top-full mt-2 w-auto sm:w-80 md:w-88 bg-space-900 border border-white/15 rounded-2xl shadow-2xl z-50 p-3 sm:p-4 space-y-2.5 backdrop-blur-2xl animate-in fade-in zoom-in-95 max-w-sm sm:max-w-none",children:[e.jsxs("div",{className:"flex items-center justify-between pb-2 border-b border-white/10",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Q,{className:"w-3.5 h-3.5 text-[#2481CC]"}),e.jsx("span",{className:"text-[10px] font-mono tracking-wider text-pearl-300 uppercase font-semibold",children:"Chosen Bot Workspace"})]}),e.jsxs("span",{className:"text-[9px] font-mono px-1.5 py-0.5 rounded bg-emerald-500/10 text-emerald-400 border border-emerald-500/20",children:[(f==null?void 0:f.length)||4," BOTS"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(He,{className:"w-3.5 h-3.5 absolute left-2.5 top-1/2 -translate-y-1/2 text-pearl-400"}),e.jsx("input",{type:"text",value:N,onChange:M=>y(M.target.value),placeholder:"Filter bots by name...",className:"w-full pl-8 pr-3 py-1.5 rounded-lg bg-space-950 border border-white/10 text-xs font-mono text-pearl-100 placeholder:text-pearl-400/60 focus:outline-none focus:border-[#2481CC]",autoFocus:!0})]}),e.jsx("div",{className:"max-h-56 overflow-y-auto space-y-1 pr-1 custom-scrollbar",children:w.map(M=>{const _=M.id===(x==null?void 0:x.id);return e.jsxs("button",{onClick:()=>{p(M.id),h(!1)},className:`w-full flex items-center justify-between p-2 rounded-lg text-left transition-colors ${_?"bg-[#2481CC]/15 border border-[#2481CC]/40 text-white":"hover:bg-space-850 text-pearl-200 border border-transparent"}`,children:[e.jsxs("div",{className:"flex items-center gap-2.5 min-w-0",children:[e.jsx("div",{className:`w-7 h-7 rounded-lg flex items-center justify-center shrink-0 ${_?"bg-[#2481CC] text-white shadow-telegram":"bg-space-800 text-pearl-300"}`,children:e.jsx(Q,{className:"w-4 h-4"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"text-xs font-semibold text-pearl-50 truncate flex items-center gap-1.5",children:[e.jsx("span",{children:M.name}),_&&e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"})]}),e.jsxs("div",{className:"text-[10px] font-mono text-[#2481CC] truncate",children:["@",M.username]})]})]}),e.jsx("div",{className:"text-right shrink-0 ml-2",children:_?e.jsx("span",{className:"text-[9px] font-mono px-1.5 py-0.5 rounded bg-[#2481CC]/25 text-[#2481CC] font-semibold",children:"ACTIVE"}):e.jsxs("span",{className:"text-[9px] font-mono text-pearl-400",children:[M.usersCount.toLocaleString()," users"]})})]},M.id)})}),e.jsxs("div",{className:"pt-2 border-t border-white/10 flex items-center justify-between gap-2",children:[e.jsxs(A,{to:"/dashboard/bots",onClick:()=>h(!1),className:"text-[11px] font-mono text-[#2481CC] hover:underline flex items-center gap-1",children:[e.jsx(Pe,{className:"w-3 h-3"}),e.jsx("span",{children:"All Bots Fleet"})]}),e.jsxs(A,{to:"/dashboard/bots",onClick:()=>h(!1),className:"btn-telegram-primary py-1 px-2.5 text-[10px] font-mono inline-flex items-center gap-1 shadow-telegram",children:[e.jsx(ee,{className:"w-3 h-3"}),e.jsx("span",{children:"Connect Bot"})]})]})]})]}),e.jsxs("div",{className:"hidden lg:flex items-center gap-2 px-3 py-1 rounded-full bg-emerald-500/10 border border-emerald-500/30 text-[10px] font-mono uppercase tracking-wider text-emerald-300",children:[e.jsx(pe,{className:"w-3 h-3 animate-pulse text-emerald-400"}),e.jsx("span",{children:"4 BOTS ONLINE"})]}),e.jsx("div",{className:"relative shrink-0 hidden md:block",children:e.jsx(Fl,{})}),e.jsx("div",{className:"relative shrink-0",children:e.jsx("button",{id:"top-navbar-theme-toggle",onClick:m,className:"p-1.5 sm:p-2 rounded-lg bg-space-850 border border-white/10 text-pearl-300 hover:text-[#2481CC] hover:border-[#2481CC]/40 transition-colors relative flex items-center justify-center",title:b==="light"?"Switch to Rich Slate Dark Theme":"Switch to Clean Light Theme","aria-label":"Toggle theme",children:b==="light"?e.jsx(De,{className:"w-4 h-4 text-slate-700"}):e.jsx(Fe,{className:"w-4 h-4 text-amber-400"})})}),e.jsxs("div",{className:"relative shrink-0",children:[e.jsxs("button",{onClick:()=>c(!d),className:"p-1.5 sm:p-2 rounded-lg bg-space-850 border border-white/10 text-pearl-300 hover:text-[#2481CC] hover:border-[#2481CC]/40 transition-colors relative",title:"Notifications",children:[e.jsx(Ia,{className:"w-4 h-4"}),g>0&&e.jsx("span",{className:"absolute -top-1 -right-1 w-4 h-4 rounded-full bg-[#2481CC] text-white text-[9px] font-mono font-bold flex items-center justify-center shadow-sm",children:g})]}),d&&e.jsxs("div",{className:"fixed sm:absolute left-3 right-3 sm:left-auto sm:right-0 top-18 sm:top-full mt-2 w-auto sm:w-80 md:w-96 max-w-sm sm:max-w-none astraea-card rounded-2xl p-3 sm:p-4 border border-[#2481CC]/30 shadow-2xl z-50 animate-in fade-in duration-200",children:[e.jsxs("div",{className:"flex items-center justify-between pb-3 border-b border-white/10 mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs font-sans tracking-wide text-pearl-50 uppercase font-semibold",children:"In-App Alerts"}),g>0&&e.jsxs("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-mono bg-[#2481CC]/20 text-[#2481CC] border border-[#2481CC]/30 font-semibold",children:[g," UNREAD"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[g>0&&e.jsxs("button",{onClick:k,className:"text-[10px] font-mono text-[#2481CC] hover:underline flex items-center gap-1 font-medium",children:[e.jsx(D,{className:"w-3 h-3"})," Mark all read"]}),e.jsx("button",{onClick:()=>c(!1),className:"text-pearl-400 hover:text-pearl-100",children:e.jsx(H,{className:"w-4 h-4"})})]})]}),e.jsx("div",{className:"space-y-2.5 max-h-80 overflow-y-auto pr-1",children:S.map(M=>e.jsxs("div",{className:`p-3 rounded-xl border text-xs font-mono transition-colors ${M.is_read?"bg-space-900/40 border-white/5 text-pearl-400":"bg-space-850 border-[#2481CC]/30 text-pearl-100 shadow-sm"}`,children:[e.jsxs("div",{className:"flex items-center justify-between font-semibold text-pearl-50 text-[11px] mb-1",children:[e.jsx("span",{className:"truncate",children:M.title}),e.jsx("span",{className:"text-[9px] text-pearl-400 shrink-0 ml-2",children:new Date(M.created_at).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}),e.jsx("p",{className:"text-[11px] text-pearl-300 leading-relaxed font-sans",children:M.message})]},M.id))})]})]}),o&&r?e.jsxs("div",{className:"flex items-center gap-2.5 pl-3 border-l border-white/10",children:[e.jsx("div",{className:"w-8 h-8 rounded-full bg-gradient-to-tr from-[#2481CC] to-[#7DD3FC] p-[1px] shadow-sm shrink-0",children:r.avatar_url?e.jsx("img",{src:r.avatar_url,alt:"",className:"w-full h-full rounded-full object-cover"}):e.jsx("div",{className:"w-full h-full rounded-full bg-space-900 flex items-center justify-center text-xs font-mono font-bold text-[#2481CC]",children:((L=r.full_name)==null?void 0:L.slice(0,2).toUpperCase())||"TG"})}),e.jsxs("div",{className:"hidden xl:block text-left",children:[e.jsx("div",{className:"text-xs font-medium text-pearl-100 leading-tight truncate max-w-[120px]",children:r.full_name}),e.jsx("div",{className:"text-[9px] font-mono tracking-wider text-[#2481CC] uppercase font-medium",children:r.telegram_username?`@${r.telegram_username}`:"ACTIVE TENANT"})]}),e.jsx("button",{onClick:j,className:"text-pearl-400 hover:text-rose-400 p-1",title:"Sign Out",children:e.jsx(Ea,{className:"w-4 h-4"})})]}):e.jsxs(A,{to:"/login",className:"flex items-center gap-1.5 sm:gap-2 pl-2 sm:pl-3 border-l border-white/10 btn-telegram-primary py-1 sm:py-1.5 px-2.5 sm:px-3 text-xs shrink-0 shadow-telegram",children:[e.jsx(ct,{className:"w-3.5 h-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:"SIGN IN"})]})]})]})},Ul=[{id:"b-001",name:"Astraea Flagship Super Bot",username:"astraea_flagship_bot",status:"active",usersCount:14280,messages24h:38450,latencyMs:38,color:"#d4af37",orbitRadius:4.2,orbitSpeed:.008,orbitAngle:0,inclination:.25},{id:"b-002",name:"VIP Concierge & Support",username:"vip_concierge_bot",status:"active",usersCount:6890,messages24h:12400,latencyMs:42,color:"#e5c378",orbitRadius:6,orbitSpeed:.006,orbitAngle:Math.PI*.65,inclination:-.35},{id:"b-003",name:"Automated Flash Billing",username:"flash_billing_bot",status:"active",usersCount:9420,messages24h:21100,latencyMs:35,color:"#cbd5e1",orbitRadius:7.8,orbitSpeed:.0045,orbitAngle:Math.PI*1.35,inclination:.45},{id:"b-004",name:"Omni Broadcast Announcer",username:"omni_broadcast_bot",status:"syncing",usersCount:31200,messages24h:89400,latencyMs:48,color:"#94a3b8",orbitRadius:9.5,orbitSpeed:.0035,orbitAngle:Math.PI*1.85,inclination:-.15}],Vl=({bots:t=Ul,selectedBotId:s,onSelectBot:n,onOpenStudio:a,className:l=""})=>{const r=i.useRef(null),[o,j]=i.useState(()=>t.find(g=>g.id===s)||t[0]),[b,m]=i.useState(!0),[x,f]=i.useState(!0);i.useEffect(()=>{if(s){const g=t.find(u=>u.id===s);g&&j(g)}},[s,t]);const p=i.useCallback(g=>{j(g),n&&n(g)},[n]);return i.useEffect(()=>{const g=r.current;if(!g)return;try{const R=document.createElement("canvas");if(!(R.getContext("webgl")||R.getContext("experimental-webgl"))){f(!1);return}}catch{f(!1);return}const u=new ir;u.fog=new or(197896,.025);const d=new cr(45,g.clientWidth/g.clientHeight,.1,1e3);d.position.set(0,7.5,16.5),d.lookAt(0,0,0);const c=new dr({antialias:!0,alpha:!0,powerPreference:"high-performance"});c.setSize(g.clientWidth,g.clientHeight),c.setPixelRatio(Math.min(window.devicePixelRatio,2)),g.appendChild(c.domElement);const v=new mr(16777215,.4);u.add(v);const h=new xr(13938487,2.5,50);h.position.set(0,0,0),u.add(h);const N=new ts(16047262,1.2);N.position.set(12,18,12),u.add(N);const y=new ts(4878245,.8);y.position.set(-15,-10,-10),u.add(y);const E=new pr;u.add(E);const w=new ss(1.4,2),S=new as({color:791330,emissive:13938487,emissiveIntensity:.35,roughness:.2,metalness:.85,wireframe:!1}),P=new kt(w,S);E.add(P);const k=new ss(1.65,1),L=new ur({color:13938487,wireframe:!0,transparent:!0,opacity:.25}),M=new kt(k,L);E.add(M);const _=600,Y=new Float32Array(_*3);for(let R=0;R<_*3;R+=3)Y[R]=(Math.random()-.5)*60,Y[R+1]=(Math.random()-.5)*45,Y[R+2]=(Math.random()-.5)*60;const K=new St;K.setAttribute("position",new hr(Y,3));const ne=new br({color:16316922,size:.12,transparent:!0,opacity:.45}),I=new fr(K,ne);u.add(I);const $=[],O=[];t.forEach(R=>{const re=new gr(0,0,R.orbitRadius,R.orbitRadius,0,2*Math.PI,!1,0).getPoints(120),de=new St().setFromPoints(re.map(Je=>new _t(Je.x,0,Je.y))),xe=new rs({color:R.id===o.id?13938487:16777215,transparent:!0,opacity:R.id===o.id?.45:.1}),se=new ns(de,xe);se.rotation.x=R.inclination,u.add(se);const ye=new jr(.38,32,32),Le=new as({color:R.id===o.id?13938487:2042173,emissive:R.id===o.id?13938487:988970,emissiveIntensity:R.id===o.id?.6:.2,roughness:.3,metalness:.8}),ve=new kt(ye,Le);ve.userData={botId:R.id,botData:R},u.add(ve),O.push(ve);const lt=new St().setFromPoints([new _t(0,0,0),new _t(0,0,0)]),it=new rs({color:13938487,transparent:!0,opacity:R.id===o.id?.35:.08}),be=new ns(lt,it);u.add(be),$.push({bot:R,mesh:ve,ring:se,line:be,currentAngle:R.orbitAngle})});const le=new Nr,he=new wr;let Z=null,Se=0,_e=7.5;const Ee=R=>{const V=g.getBoundingClientRect();he.x=(R.clientX-V.left)/V.width*2-1,he.y=-((R.clientY-V.top)/V.height)*2+1,Se=he.x*2.5,_e=7.5+he.y*1.5,le.setFromCamera(he,d);const re=le.intersectObjects(O);if(re.length>0){const de=re[0].object;Z!==de&&(Z=de,g.style.cursor="pointer")}else Z&&(Z=null,g.style.cursor="default")},Ne=()=>{var R;Z&&((R=Z.userData)!=null&&R.botData)&&p(Z.userData.botData)};g.addEventListener("mousemove",Ee),g.addEventListener("click",Ne);let Re,Me=new vr;const C=()=>{Re=requestAnimationFrame(C),Me.getDelta(),d.position.x+=(Se-d.position.x)*.04,d.position.y+=(_e-d.position.y)*.04,d.lookAt(0,0,0),E.rotation.y+=.005,M.rotation.x-=.003,M.rotation.z+=.004,I.rotation.y+=3e-4,$.forEach(R=>{b&&(R.currentAngle+=R.bot.orbitSpeed);const V=Math.cos(R.currentAngle)*R.bot.orbitRadius,re=Math.sin(R.currentAngle)*R.bot.orbitRadius,de=Math.sin(R.currentAngle)*Math.sin(R.bot.inclination)*1.8;R.mesh.position.set(V,de,re);const xe=R.line.geometry.attributes.position;xe.setXYZ(1,V,de,re),xe.needsUpdate=!0;const se=R.bot.id===o.id,ye=R.mesh.material;ye.color.setHex(se?13938487:2042173),ye.emissive.setHex(se?13938487:988970),ye.emissiveIntensity=se?.75:.2;const Le=R.ring.material;Le.color.setHex(se?13938487:16777215),Le.opacity=se?.45:.1;const ve=R.line.material;ve.opacity=se?.35:.08}),c.render(u,d)};C();const B=()=>{g&&(d.aspect=g.clientWidth/g.clientHeight,d.updateProjectionMatrix(),c.setSize(g.clientWidth,g.clientHeight))};return window.addEventListener("resize",B),()=>{cancelAnimationFrame(Re),window.removeEventListener("resize",B),g.removeEventListener("mousemove",Ee),g.removeEventListener("click",Ne),c.dispose(),c.domElement.parentNode&&c.domElement.parentNode.removeChild(c.domElement)}},[t,o.id,b,p]),e.jsxs("div",{className:`relative overflow-hidden rounded-xl border border-white/10 astraea-panel w-full max-w-full min-w-0 ${l}`,children:[e.jsx("div",{className:"absolute inset-0 cosmic-radial-bg pointer-events-none"}),x?e.jsx("div",{ref:r,className:"w-full h-[400px] sm:h-[480px] md:h-[540px] relative select-none"}):e.jsx("div",{className:"w-full h-[400px] sm:h-[480px] md:h-[540px] flex items-center justify-center p-8",children:e.jsxs("div",{className:"text-center max-w-md",children:[e.jsx(Q,{className:"w-12 h-12 text-[#2481CC] mx-auto mb-4 animate-pulse"}),e.jsx("h3",{className:"text-lg font-bold tracking-tight text-pearl-100 uppercase",children:"Constellation Bot Cluster"}),e.jsx("p",{className:"text-xs text-pearl-400 mt-2",children:"Hardware accelerated WebGL view simplified for optimal device efficiency."})]})}),e.jsxs("div",{className:"absolute top-4 sm:top-5 left-4 sm:left-6 right-4 sm:right-6 flex items-center justify-between pointer-events-none",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-2 h-2 rounded-full bg-[#2481CC] animate-ping"}),e.jsx("span",{className:"text-[10px] font-mono tracking-wider text-[#2481CC] uppercase font-semibold",children:"Neural Constellation Mesh"})]}),e.jsx("h2",{className:"text-lg sm:text-xl md:text-2xl text-pearl-50 tracking-tight font-bold mt-0.5",children:"Dynamic Bot Orbit"})]}),e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 pointer-events-auto",children:[e.jsxs("button",{onClick:()=>m(!b),className:"btn-telegram-secondary py-1 px-2.5 sm:px-3 text-[10px] sm:text-[11px] gap-1.5",title:b?"Pause Orbit":"Resume Orbit",children:[e.jsx(me,{className:`w-3.5 h-3.5 ${b?"animate-spin":""}`,style:{animationDuration:"6s"}}),e.jsx("span",{children:b?"ORBIT ACTIVE":"PAUSED"})]}),e.jsxs("div",{className:"hidden sm:flex items-center gap-2 px-3 py-1 rounded-lg bg-black/40 border border-white/10 text-xs font-mono text-pearl-300",children:[e.jsx(Ie,{className:"w-3.5 h-3.5 text-emerald-400"}),e.jsxs("span",{children:[t.length," NODES LINKED"]})]})]})]}),e.jsx("div",{className:"absolute top-20 sm:top-24 left-4 sm:left-6 right-4 sm:right-auto flex flex-wrap gap-1.5 sm:gap-2 pointer-events-auto max-h-24 overflow-y-auto sm:max-h-none scrollbar-none",children:t.map(g=>{const u=g.id===o.id;return e.jsxs("button",{onClick:()=>p(g),className:`px-2.5 py-1 sm:px-3 sm:py-1.5 rounded-lg text-[10px] sm:text-[11px] font-mono tracking-wider transition-all flex items-center gap-1.5 sm:gap-2 ${u?"bg-[#2481CC] border border-[#2481CC] text-white shadow-sm font-semibold":"bg-space-900/60 border border-white/10 text-pearl-400 hover:text-pearl-100 hover:border-white/25"}`,children:[e.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${g.status==="active"?"bg-emerald-400":"bg-amber-400"}`}),e.jsx("span",{children:g.name.split(" ")[0]})]},g.id)})}),e.jsx("div",{className:"absolute bottom-3 sm:bottom-5 left-3 sm:left-6 right-3 sm:right-6 pointer-events-auto",children:e.jsxs("div",{className:"astraea-card rounded-2xl p-3 sm:p-4 md:p-5 flex flex-col md:flex-row items-start md:items-center justify-between gap-3 sm:gap-4 border border-[#2481CC]/30 shadow-xl",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"w-12 h-12 rounded-xl bg-[#2481CC]/10 border border-[#2481CC]/30 flex items-center justify-center shrink-0",children:e.jsx(Q,{className:"w-6 h-6 text-[#2481CC]"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-xs font-mono text-[#2481CC] font-semibold",children:["@",o.username]}),e.jsx("span",{className:"px-2 py-0.5 rounded text-[10px] font-mono uppercase bg-emerald-500/10 border border-emerald-500/30 text-emerald-300 font-semibold",children:o.status}),e.jsxs("span",{className:"hidden sm:inline-flex items-center gap-1 text-[10px] font-mono text-pearl-400",children:[e.jsx(q,{className:"w-3 h-3 text-[#2481CC]"})," AES-256 Validated"]})]}),e.jsx("h3",{className:"text-base sm:text-lg text-pearl-50 font-bold tracking-tight mt-0.5",children:o.name})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 sm:gap-6 md:gap-8 text-xs font-mono w-full md:w-auto justify-between md:justify-start",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase text-pearl-400 tracking-wider",children:"Active Audience"}),e.jsx("div",{className:"text-sm font-semibold text-pearl-100 mt-0.5",children:o.usersCount.toLocaleString()})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase text-pearl-400 tracking-wider",children:"24h Messages"}),e.jsx("div",{className:"text-sm font-semibold text-pearl-100 mt-0.5",children:o.messages24h.toLocaleString()})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase text-pearl-400 tracking-wider",children:"Response Latency"}),e.jsxs("div",{className:"text-sm font-semibold text-emerald-400 mt-0.5",children:[o.latencyMs," ms"]})]}),e.jsxs("div",{className:"flex items-center gap-2 w-full sm:w-auto justify-end",children:[e.jsx(A,{to:`/dashboard/bots/${o.username.replace("@","")||o.id}`,className:"btn-telegram-secondary text-[11px] py-2 px-3 inline-flex items-center gap-1",children:e.jsx("span",{children:"TELEMETRY"})}),e.jsxs(A,{to:"/dashboard/studio",onClick:()=>a&&a(o.id),className:"btn-telegram-primary text-[11px] py-2 px-3.5 inline-flex items-center gap-1",children:[e.jsx("span",{children:"STUDIO"}),e.jsx(Te,{className:"w-3.5 h-3.5"})]})]})]})]})})]})},ua=({bot:t,onOpenTemplates:s,onOpenConnectModal:n})=>{const{toggleChecklistStep:a,toggleBotModule:l}=z(),[r,o]=i.useState(null),[j,b]=i.useState(!1),m=t.checklist,x=Object.values(m).filter(Boolean).length,f=5,p=Math.round(x/f*100),g=()=>{navigator.clipboard.writeText("/newbot"),b(!0),setTimeout(()=>b(!1),2e3)},u=[{id:1,key:"tokenConnected",title:"Step 1: Connect Bot Token from @BotFather",subtitle:m.tokenConnected?"Verified via Telegram getMe & encrypted with AES-256-GCM":"Connect your bot to Telegram in 30 seconds (no coding required)",isComplete:m.tokenConnected,content:e.jsxs("div",{className:"space-y-3 pt-2 text-xs font-sans text-pearl-300",children:[e.jsxs("p",{className:"leading-relaxed",children:["Telegram bots are created through the official ",e.jsx("span",{className:"text-[#2481CC] font-semibold",children:"@BotFather"})," bot on Telegram. It provides an API token that allows our 24/7 cloud to run your bot."]}),e.jsxs("div",{className:"p-3 rounded-xl bg-space-900 border border-white/5 space-y-2 font-mono text-[11px]",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-pearl-400",children:"Quick BotFather Guide:"}),e.jsxs("button",{onClick:g,className:"text-[#2481CC] hover:underline flex items-center gap-1",children:[j?e.jsx(D,{className:"w-3 h-3 text-emerald-400"}):e.jsx(Ze,{className:"w-3 h-3"}),e.jsx("span",{children:j?"Copied /newbot":"Copy /newbot"})]})]}),e.jsxs("ol",{className:"list-decimal list-inside space-y-1 text-pearl-200",children:[e.jsxs("li",{children:["Open Telegram and search for ",e.jsx("strong",{className:"text-white",children:"@BotFather"})]}),e.jsxs("li",{children:["Send message: ",e.jsx("code",{className:"px-1 py-0.5 rounded bg-space-950 text-emerald-300",children:"/newbot"})]}),e.jsxs("li",{children:["Give your bot a name and username (e.g. ",e.jsx("code",{className:"px-1 py-0.5 rounded bg-space-950 text-emerald-300",children:"my_vip_store_bot"}),")"]}),e.jsx("li",{children:"Copy the HTTP API token provided by BotFather"})]})]}),e.jsxs("div",{className:"flex items-center gap-3 pt-1",children:[e.jsxs("button",{onClick:()=>n&&n(),className:"btn-telegram-primary py-1.5 px-3.5 text-xs shadow-telegram inline-flex items-center gap-1.5",children:[e.jsx(Q,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:m.tokenConnected?"Update Bot Token":"Paste Bot Token"})]}),e.jsxs("a",{href:"https://t.me/BotFather",target:"_blank",rel:"noopener noreferrer",className:"btn-telegram-secondary py-1.5 px-3 text-xs inline-flex items-center gap-1.5",children:[e.jsx("span",{children:"Open @BotFather"}),e.jsx(ge,{className:"w-3 h-3"})]})]})]})},{id:2,key:"templateSelected",title:"Step 2: Choose a Ready-Made Template (25 Turnkey Options)",subtitle:m.templateSelected?`Applied: ${t.templateName||"Turnkey Bot Template"}`:"Pick a 1-click template so you never have to start from scratch",isComplete:m.templateSelected,content:e.jsxs("div",{className:"space-y-3 pt-2 text-xs font-sans text-pearl-300",children:[e.jsx("p",{className:"leading-relaxed",children:"Choose from 25 ready-made bot templates covering E-Commerce, VIP Subscriptions, Customer Support, Community Guard, Crypto Tracking, and Referral Viral Growth."}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-2 text-xs font-mono",children:[{name:"VIP Community & Subscriptions",desc:"Paid membership gates with Razorpay/Stripe"},{name:"Digital Store & E-Commerce",desc:"Product catalog with in-chat checkout"},{name:"Customer Support Desk",desc:"AI agent + human ticket escalation"}].map((d,c)=>e.jsxs("div",{className:"p-2.5 rounded-xl bg-space-900 border border-white/5 space-y-1",children:[e.jsx("div",{className:"font-semibold text-pearl-100",children:d.name}),e.jsx("div",{className:"text-[10px] text-pearl-400 font-sans",children:d.desc})]},c))}),e.jsxs("div",{className:"flex items-center gap-3 pt-1",children:[e.jsxs(A,{to:"/marketplace",className:"btn-telegram-primary py-1.5 px-3.5 text-xs shadow-telegram inline-flex items-center gap-1.5",children:[e.jsx(J,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:"Browse 25+ Templates"})]}),e.jsx("button",{onClick:()=>a(t.id,"templateSelected"),className:"text-pearl-400 hover:text-pearl-200 text-xs font-mono",children:m.templateSelected?"Mark Incomplete":"Mark Complete"})]})]})},{id:3,key:"modulesConfigured",title:"Step 3: Enable Core Bot Features (1-Click Toggles)",subtitle:m.modulesConfigured?`${t.modules.filter(d=>d.is_enabled).length} of 9 core modules currently active`:"Turn on features like Welcome Messages, Referrals, Force Join, and AI Assistant",isComplete:m.modulesConfigured,content:e.jsxs("div",{className:"space-y-3 pt-2 text-xs font-sans text-pearl-300",children:[e.jsx("p",{className:"leading-relaxed",children:"Every feature on your bot is a standalone module. Toggle features on/off instantly without touching server configuration:"}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-2",children:t.modules.slice(0,6).map(d=>e.jsxs("div",{className:`p-2.5 rounded-xl border flex items-center justify-between transition-all ${d.is_enabled?"bg-space-900 border-[#2481CC]/40":"bg-space-900/40 border-white/5"}`,children:[e.jsxs("div",{className:"min-w-0 pr-2",children:[e.jsx("div",{className:"font-semibold text-pearl-100 text-[11px] truncate",children:d.name}),e.jsx("div",{className:"text-[9px] font-mono text-pearl-400 capitalize",children:d.category})]}),e.jsx("button",{type:"button",onClick:()=>l(t.id,d.id),className:`w-9 h-5 rounded-full p-0.5 transition-colors relative shrink-0 ${d.is_enabled?"bg-[#2481CC]":"bg-space-800 border border-white/20"}`,children:e.jsx("div",{className:`w-4 h-4 rounded-full bg-white transition-transform ${d.is_enabled?"translate-x-4":"translate-x-0"}`})})]},d.id))}),e.jsx("div",{className:"flex items-center gap-3 pt-1",children:e.jsxs(A,{to:`/dashboard/bots/${t.username}`,className:"text-xs font-mono text-[#2481CC] hover:underline flex items-center gap-1 font-semibold",children:[e.jsx("span",{children:"Manage all 9 modules below"}),e.jsx(ie,{className:"w-3 h-3"})]})})]})},{id:4,key:"welcomeMessageSet",title:"Step 4: Customize Welcome Message & Inline Buttons",subtitle:m.welcomeMessageSet?"Custom welcome greeting and interactive inline buttons configured":"Design what users see when they tap /start in Telegram",isComplete:m.welcomeMessageSet,content:e.jsxs("div",{className:"space-y-3 pt-2 text-xs font-sans text-pearl-300",children:[e.jsxs("p",{className:"leading-relaxed",children:["Create rich welcome messages with emojis, custom bold text, dynamic user mentions (",e.jsx("code",{className:"px-1 py-0.5 rounded bg-space-950 font-mono text-emerald-300",children:"{first_name}"}),"), and clickable URL or callback buttons."]}),e.jsxs("div",{className:"flex items-center gap-3 pt-1",children:[e.jsxs(A,{to:"/dashboard/studio",className:"btn-telegram-primary py-1.5 px-3.5 text-xs shadow-telegram inline-flex items-center gap-1.5",children:[e.jsx($t,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:"Open Welcome Message Studio"})]}),e.jsx("button",{onClick:()=>a(t.id,"welcomeMessageSet"),className:"text-pearl-400 hover:text-pearl-200 text-xs font-mono",children:m.welcomeMessageSet?"Mark Incomplete":"Mark Complete"})]})]})},{id:5,key:"testedInTelegram",title:"Step 5: Test Live in Telegram & Run 24/7 in Cloud",subtitle:m.testedInTelegram?"Bot verified live on Telegram! Cloud supervisor running 24/7":"Click to open your bot directly in Telegram and test live commands",isComplete:m.testedInTelegram,content:e.jsxs("div",{className:"space-y-3 pt-2 text-xs font-sans text-pearl-300",children:[e.jsx("p",{className:"leading-relaxed",children:"Your bot runs on our 24/7 managed cloud infrastructure with automatic recovery, Redis deduplication, and zero server maintenance."}),e.jsxs("div",{className:"p-3 rounded-xl bg-emerald-500/10 border border-emerald-500/30 flex items-center justify-between text-xs font-mono",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-2 h-2 rounded-full bg-emerald-400 animate-pulse"}),e.jsx("span",{className:"text-emerald-300 font-semibold",children:"24/7 Cloud Host Online"})]}),e.jsxs("span",{className:"text-pearl-400",children:[t.latencyMs," ms latency"]})]}),e.jsxs("div",{className:"flex items-center gap-3 pt-1",children:[e.jsxs("a",{href:`https://t.me/${t.username.replace("@","")}`,target:"_blank",rel:"noopener noreferrer",onClick:()=>{m.testedInTelegram||a(t.id,"testedInTelegram")},className:"btn-telegram-primary py-2 px-5 text-xs shadow-telegram inline-flex items-center gap-2 font-bold",children:[e.jsx(oe,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:["Open @",t.username," in Telegram"]}),e.jsx(ge,{className:"w-3.5 h-3.5"})]}),e.jsx("button",{onClick:()=>a(t.id,"testedInTelegram"),className:"text-pearl-400 hover:text-pearl-200 text-xs font-mono",children:m.testedInTelegram?"Reset Status":"Mark Tested"})]})]})}];return e.jsxs("div",{className:"astraea-card rounded-2xl p-4 sm:p-6 border border-[#2481CC]/30 shadow-xl space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-3 pb-3 border-b border-white/10",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] font-mono tracking-wider text-[#2481CC] uppercase font-bold",children:"Google Play Console Style Guided Setup"}),e.jsx("span",{className:"px-2 py-0.5 rounded-full text-[9px] font-mono font-semibold bg-emerald-500/15 text-emerald-300 border border-emerald-500/30",children:"BEGINNER FRIENDLY"})]}),e.jsxs("h2",{className:"text-lg sm:text-xl font-bold text-pearl-50 tracking-tight mt-0.5",children:["Set up your bot: ",e.jsxs("span",{className:"text-[#2481CC]",children:["@",t.username]})]}),e.jsx("p",{className:"text-xs text-pearl-400 font-sans mt-0.5",children:"Follow these 5 easy steps to launch and manage your Telegram bot — zero coding or server setup required."})]}),e.jsxs("div",{className:"flex items-center gap-3 self-start sm:self-auto shrink-0",children:[e.jsxs("div",{className:"text-right",children:[e.jsxs("div",{className:"text-xs font-mono font-bold text-pearl-100",children:[x," of ",f," steps completed"]}),e.jsxs("div",{className:"text-[10px] font-mono text-emerald-400",children:[p,"% Ready"]})]}),e.jsx("div",{className:"w-12 h-12 rounded-full border-2 border-white/10 flex items-center justify-center font-bold text-xs text-[#2481CC] relative bg-space-900",children:e.jsxs("span",{children:[p,"%"]})})]})]}),e.jsx("div",{className:"w-full bg-space-900 rounded-full h-2 overflow-hidden border border-white/5",children:e.jsx("div",{className:"bg-gradient-to-r from-[#2481CC] to-[#0088CC] h-full transition-all duration-500 rounded-full",style:{width:`${p}%`}})}),e.jsx("div",{className:"space-y-2.5 pt-1",children:u.map(d=>{const c=r===d.id;return e.jsxs("div",{className:`rounded-xl border transition-all ${d.isComplete?"bg-space-850/40 border-white/5":"bg-space-850/80 border-[#2481CC]/30 shadow-sm"}`,children:[e.jsxs("div",{onClick:()=>o(c?null:d.id),className:"p-3.5 sm:p-4 flex items-center justify-between cursor-pointer select-none",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[d.isComplete?e.jsx(F,{className:"w-5 h-5 text-emerald-400 shrink-0"}):e.jsx(Ra,{className:"w-5 h-5 text-pearl-500 shrink-0"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h3",{className:`text-sm font-semibold tracking-tight truncate ${d.isComplete?"text-pearl-200 line-through opacity-75":"text-pearl-50 font-bold"}`,children:d.title}),e.jsx("p",{className:"text-xs text-pearl-400 font-sans truncate",children:d.subtitle})]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0 ml-2",children:[e.jsx("span",{className:`hidden sm:inline-block px-2 py-0.5 rounded text-[10px] font-mono uppercase font-semibold ${d.isComplete?"bg-emerald-500/10 text-emerald-300 border border-emerald-500/30":"bg-[#2481CC]/10 text-[#2481CC] border border-[#2481CC]/30"}`,children:d.isComplete?"COMPLETED":"ACTION REQUIRED"}),c?e.jsx(Ts,{className:"w-4 h-4 text-pearl-400"}):e.jsx(Vt,{className:"w-4 h-4 text-pearl-400"})]})]}),c&&e.jsx("div",{className:"px-4 pb-4 border-t border-white/5 animate-in fade-in duration-200",children:d.content})]},d.id)})})]})},Hl=({onNavigate:t,onSelectBot:s})=>{var g,u;const n=ce(),{currentBot:a,bots:l,selectBot:r,toggleBotModule:o}=z(),[j,b]=i.useState(null),m=((g=a==null?void 0:a.modules)==null?void 0:g.filter(d=>d.is_enabled).length)||0,x=((u=a==null?void 0:a.modules)==null?void 0:u.length)||9,f=(d,c)=>{o(a.id,d,!c),b(`Module updated for @${a.username}!`),setTimeout(()=>b(null),2500)},p=d=>{switch(d){case"welcome_message":return J;case"force_join":return q;case"referrals":return ut;case"broadcasts":return pe;case"user_management":return Ae;case"auto_filter":return Gt;case"payments":return Ve;case"subscriptions":return rt;case"ai_assistant":return fe;default:return Ge}};return e.jsxs("div",{className:"space-y-8 animate-in fade-in duration-300 min-w-0 max-w-full",children:[j&&e.jsxs("div",{className:"fixed bottom-6 right-6 z-50 px-4 py-2.5 rounded-xl bg-emerald-500 text-white font-mono text-xs shadow-telegram flex items-center gap-2 animate-in fade-in slide-in-from-bottom-2",children:[e.jsx(D,{className:"w-4 h-4"}),e.jsx("span",{children:j})]}),e.jsxs("div",{className:"astraea-card rounded-2xl p-4 sm:p-6 border border-white/10 shadow-sm relative overflow-hidden",children:[e.jsx("div",{className:"absolute top-0 right-0 w-64 h-64 bg-[#2481CC]/5 rounded-full blur-3xl pointer-events-none"}),e.jsxs("div",{className:"flex flex-col lg:flex-row lg:items-center justify-between gap-6 relative z-10",children:[e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsxs("div",{className:"w-14 h-14 sm:w-16 sm:h-16 rounded-2xl bg-[#2481CC]/15 border border-[#2481CC]/40 flex items-center justify-center text-[#2481CC] shadow-telegram shrink-0 relative",children:[e.jsx(Q,{className:"w-7 h-7 sm:w-8 sm:h-8"}),e.jsx("span",{className:"absolute -bottom-1 -right-1 w-4 h-4 rounded-full bg-emerald-500 border-2 border-space-950 flex items-center justify-center",title:"24/7 Cloud Running",children:e.jsx("span",{className:"w-2 h-2 rounded-full bg-white animate-pulse"})})]}),e.jsxs("div",{className:"space-y-1.5 min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-[10px] font-mono tracking-wider px-2 py-0.5 rounded-full bg-[#2481CC]/15 text-[#2481CC] border border-[#2481CC]/30 font-semibold uppercase",children:"Chosen Bot Workspace"}),e.jsxs("span",{className:"text-[10px] font-mono px-2 py-0.5 rounded-full bg-emerald-500/10 text-emerald-400 border border-emerald-500/20 flex items-center gap-1 font-semibold",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"}),"24/7 Managed Cloud Active"]}),(a==null?void 0:a.templateName)&&e.jsxs("span",{className:"text-[10px] font-mono px-2 py-0.5 rounded-full bg-space-850 text-pearl-300 border border-white/10 hidden sm:inline-block",children:["Template: ",a.templateName]})]}),e.jsxs("div",{className:"flex flex-wrap items-baseline gap-2.5",children:[e.jsx("h1",{className:"text-2xl sm:text-3xl font-bold text-pearl-50 tracking-tight truncate",children:(a==null?void 0:a.name)||"Astraea Super Bot"}),e.jsxs("a",{href:`https://t.me/${(a==null?void 0:a.username)||"astraea_flagship_bot"}`,target:"_blank",rel:"noopener noreferrer",className:"text-xs sm:text-sm font-mono text-[#2481CC] hover:underline flex items-center gap-1 font-semibold",title:"Open this bot in Telegram",children:[e.jsxs("span",{children:["@",(a==null?void 0:a.username)||"astraea_flagship_bot"]}),e.jsx(ge,{className:"w-3.5 h-3.5"})]})]}),e.jsxs("p",{className:"text-xs text-pearl-400 font-sans max-w-2xl leading-relaxed",children:["You are managing this bot's 24/7 cloud runtime, modular features, welcome screens, and broadcast pipeline. All actions below apply directly to ",e.jsxs("strong",{className:"text-pearl-200",children:["@",a==null?void 0:a.username]}),"."]})]})]}),e.jsxs("div",{className:"flex flex-wrap sm:flex-nowrap items-center gap-2.5 shrink-0",children:[e.jsxs("a",{href:`https://t.me/${(a==null?void 0:a.username)||"astraea_flagship_bot"}`,target:"_blank",rel:"noopener noreferrer",className:"btn-telegram-primary text-xs px-4 py-2.5 inline-flex items-center gap-2 shadow-telegram font-semibold w-full sm:w-auto justify-center",children:[e.jsx(ge,{className:"w-4 h-4"}),e.jsx("span",{children:"TEST LIVE IN TELEGRAM"})]}),e.jsxs(A,{to:"/dashboard/studio",className:"btn-telegram-secondary text-xs px-3.5 py-2.5 inline-flex items-center gap-2 w-full sm:w-auto justify-center",children:[e.jsx($t,{className:"w-3.5 h-3.5 text-[#2481CC]"}),e.jsx("span",{children:"MESSAGE STUDIO"})]}),e.jsxs(A,{to:"/dashboard/bots",className:"px-3 py-2.5 rounded-xl bg-space-850 hover:bg-space-800 border border-white/10 text-pearl-200 hover:text-[#2481CC] text-xs font-mono inline-flex items-center gap-1.5 transition-colors",title:"View all bots directory",children:[e.jsx(Pe,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:"SWITCH BOT"})]})]})]})]}),e.jsx(ua,{bot:a,onOpenTemplates:()=>n("/marketplace"),onOpenConnectModal:()=>n("/dashboard/bots")}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-2.5 sm:gap-3 md:gap-4",children:[{label:"Bot Subscribers",value:((a==null?void 0:a.usersCount)||14280).toLocaleString(),sub:"+14.2% organic growth",icon:Ae,color:"text-[#2481CC]"},{label:"24h Messages",value:((a==null?void 0:a.messages24h)||38400).toLocaleString(),sub:`${(a==null?void 0:a.uptimePct)||99.98}% SLA verified`,icon:Ht,color:"text-pearl-100"},{label:"Active Modules",value:`${m} / ${x}`,sub:"1-click independent toggles",icon:at,color:"text-emerald-400"},{label:"Cloud Latency",value:`${(a==null?void 0:a.latencyMs)||38} ms`,sub:"Managed VPS infrastructure",icon:pe,color:"text-[#2481CC]"},{label:"Security Level",value:"AES-256",sub:"Hardware key version 1",icon:q,color:"text-pearl-100"},{label:"Prepaid Wallet",value:"₹14,250",sub:"ACID Ledger Active",icon:As,color:"text-emerald-400"}].map((d,c)=>{const v=d.icon;return e.jsxs("div",{className:"astraea-card p-4 rounded-xl flex flex-col justify-between border border-white/10 hover:border-[#2481CC]/40 transition-colors",children:[e.jsxs("div",{className:"flex items-center justify-between text-pearl-400 text-xs mb-3",children:[e.jsx("span",{className:"font-mono text-[10px] uppercase tracking-widest text-pearl-400/90 truncate",children:d.label}),e.jsx(v,{className:`w-3.5 h-3.5 ${d.color} shrink-0`})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xl md:text-2xl font-bold text-pearl-50 tracking-tight",children:d.value}),e.jsxs("div",{className:"text-[10px] font-mono text-pearl-400 mt-1 flex items-center gap-1",children:[e.jsx("span",{className:"w-1 h-1 rounded-full bg-[#2481CC]"}),e.jsx("span",{className:"truncate",children:d.sub})]})]})]},c)})}),e.jsxs("div",{className:"astraea-panel rounded-2xl p-4 sm:p-6 border border-white/10 space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-2 pb-4 border-b border-white/10",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-2 h-2 rounded-full bg-[#2481CC]"}),e.jsxs("h2",{className:"text-lg sm:text-xl font-bold text-pearl-50 tracking-tight",children:["Modular Features for @",a==null?void 0:a.username]})]}),e.jsx("p",{className:"text-xs text-pearl-400 font-sans mt-0.5",children:"Turn features on or off with 1 click. Zero programming needed — real backend execution controls."})]}),e.jsxs(A,{to:`/dashboard/bots/${(a==null?void 0:a.username)||"b-001"}`,className:"text-xs font-mono text-[#2481CC] hover:underline flex items-center gap-1 self-start sm:self-auto font-medium",children:[e.jsx("span",{children:"Advanced Module Settings"}),e.jsx(Te,{className:"w-3.5 h-3.5"})]})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3.5",children:((a==null?void 0:a.modules)||[]).map(d=>{const c=p(d.id);return e.jsxs("div",{className:`p-4 rounded-xl border transition-all flex flex-col justify-between ${d.is_enabled?"bg-space-850/80 border-[#2481CC]/40 shadow-sm":"bg-space-900/60 border-white/5 opacity-80 hover:opacity-100"}`,children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 mb-2.5",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("div",{className:`w-8 h-8 rounded-lg flex items-center justify-center shrink-0 ${d.is_enabled?"bg-[#2481CC]/20 text-[#2481CC] border border-[#2481CC]/40":"bg-space-800 text-pearl-400"}`,children:e.jsx(c,{className:"w-4 h-4"})}),e.jsx("div",{className:"min-w-0",children:e.jsx("span",{className:"text-[9px] font-mono uppercase tracking-wider px-1.5 py-0.5 rounded bg-space-800 text-pearl-400",children:d.category})})]}),e.jsx("button",{onClick:()=>f(d.id,d.is_enabled),className:`relative inline-flex h-6 w-11 shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none ${d.is_enabled?"bg-[#2481CC]":"bg-space-750"}`,role:"switch","aria-checked":d.is_enabled,title:`Toggle ${d.name}`,children:e.jsx("span",{className:`pointer-events-none inline-block h-5 w-5 transform rounded-full bg-white shadow-lg ring-0 transition duration-200 ease-in-out ${d.is_enabled?"translate-x-5":"translate-x-0"}`})})]}),e.jsx("h3",{className:"text-sm font-semibold text-pearl-100 tracking-tight leading-snug",children:d.name}),e.jsx("p",{className:"text-xs text-pearl-400 font-sans mt-1 leading-relaxed line-clamp-2",children:d.description})]}),e.jsxs("div",{className:"mt-3 pt-3 border-t border-white/5 flex items-center justify-between text-[11px] font-mono",children:[e.jsxs("span",{className:d.is_enabled?"text-emerald-400 font-semibold flex items-center gap-1":"text-pearl-500 flex items-center gap-1",children:[e.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${d.is_enabled?"bg-emerald-400 animate-pulse":"bg-pearl-500"}`}),d.is_enabled?"Active on Bot":"Disabled"]}),e.jsx(A,{to:`/dashboard/bots/${(a==null?void 0:a.username)||"b-001"}`,className:"text-[#2481CC] hover:underline",children:"Configure →"})]})]},d.id)})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6 min-w-0 max-w-full",children:[e.jsxs("div",{className:"lg:col-span-2 astraea-panel rounded-2xl p-4 sm:p-5 border border-white/10 min-w-0 max-w-full overflow-hidden",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between pb-4 border-b border-white/10 mb-4 gap-2",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg text-pearl-50 tracking-tight font-semibold",children:"Your Telegram Bot Fleet"}),e.jsx("p",{className:"text-xs text-pearl-400 font-mono mt-0.5",children:"Click any bot to instantly switch your dashboard workspace (Play Console Architecture)"})]}),e.jsxs(A,{to:"/dashboard/bots",className:"btn-telegram-primary text-xs px-3 py-1.5 inline-flex items-center gap-1.5 self-start sm:self-auto font-medium shadow-telegram",children:[e.jsx(ee,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:"Connect New Bot"})]})]}),e.jsx("div",{className:"overflow-x-auto w-full max-w-full",children:e.jsxs("table",{className:"w-full text-left text-xs font-mono",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-white/10 text-[10px] text-pearl-400 uppercase tracking-widest",children:[e.jsx("th",{className:"pb-3 pl-2",children:"Bot Name"}),e.jsx("th",{className:"pb-3",children:"Username"}),e.jsx("th",{className:"pb-3",children:"Audience"}),e.jsx("th",{className:"pb-3",children:"Status"}),e.jsx("th",{className:"pb-3 pr-2 text-right",children:"Workspace Action"})]})}),e.jsx("tbody",{className:"divide-y divide-white/5",children:(l||[]).map(d=>{var v;const c=d.id===(a==null?void 0:a.id);return e.jsxs("tr",{className:`transition-colors ${c?"bg-[#2481CC]/10":"hover:bg-white/[0.02]"}`,children:[e.jsxs("td",{className:"py-3.5 pl-2 font-medium text-pearl-100 flex items-center gap-2.5",children:[e.jsx("div",{className:`w-7 h-7 rounded-lg flex items-center justify-center shrink-0 ${c?"bg-[#2481CC] text-white shadow-telegram":"bg-space-800 text-pearl-300"}`,children:e.jsx(Q,{className:"w-3.5 h-3.5"})}),e.jsx("div",{className:"min-w-0",children:e.jsxs("div",{className:"font-semibold text-pearl-50 truncate flex items-center gap-1.5",children:[e.jsx("span",{children:d.name}),c&&e.jsx("span",{className:"text-[9px] font-mono px-1.5 py-0.2 rounded bg-[#2481CC]/30 text-[#2481CC] border border-[#2481CC]/40 font-bold",children:"CURRENT"})]})})]}),e.jsxs("td",{className:"py-3.5 text-[#2481CC] font-mono font-medium",children:["@",d.username]}),e.jsx("td",{className:"py-3.5 text-pearl-300",children:((v=d.usersCount)==null?void 0:v.toLocaleString())||"0"}),e.jsx("td",{className:"py-3.5",children:e.jsx("span",{className:"px-2 py-0.5 rounded text-[10px] font-mono uppercase bg-emerald-500/10 text-emerald-300 border border-emerald-500/30 font-semibold",children:d.status})}),e.jsx("td",{className:"py-3.5 pr-2 text-right",children:c?e.jsx("span",{className:"text-[11px] font-mono text-emerald-400 font-semibold",children:"● Active Console"}):e.jsx("button",{onClick:()=>r(d.id),className:"btn-telegram-secondary py-1 px-3 text-[11px] font-mono font-medium hover:border-[#2481CC]",children:"Switch to this Bot"})})]},d.id)})})]})})]}),e.jsxs("div",{className:"astraea-panel rounded-2xl p-5 border border-white/10 flex flex-col justify-between",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-[#2481CC]"}),e.jsxs("span",{className:"text-[10px] font-mono tracking-wider text-[#2481CC] uppercase font-semibold",children:["Quick Tools for @",a==null?void 0:a.username]})]}),e.jsx("h3",{className:"text-lg text-pearl-50 tracking-tight font-semibold mb-4",children:"Creative Portals"}),e.jsx("div",{className:"space-y-2.5",children:[{title:"Message Studio",desc:"Interactive inline button matrix & preview",view:"message-studio",icon:J},{title:"Autonomous AI Agents",desc:"Multi-turn Gemini, Claude & OpenAI assistants",view:"ai-agents",icon:fe},{title:"Campaign Broadcasts",desc:"25 msg/s rate-limited bulk notification engine",view:"broadcasts",icon:pe},{title:"Multi-Language Engine",desc:"16 BCP-47 locales with AI translation approval",view:"languages",icon:Pe}].map((d,c)=>{const v=d.icon;return e.jsxs(A,{to:wt[d.view],className:"w-full text-left p-3 rounded-lg bg-space-850/60 border border-white/5 hover:border-[#2481CC]/40 hover:bg-space-800 transition-all flex items-center justify-between group",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-8 h-8 rounded bg-space-800 border border-white/10 flex items-center justify-center text-[#2481CC] group-hover:border-[#2481CC]/40",children:e.jsx(v,{className:"w-4 h-4"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs font-semibold text-pearl-100 group-hover:text-[#2481CC]",children:d.title}),e.jsx("div",{className:"text-[10px] font-mono text-pearl-400",children:d.desc})]})]}),e.jsx(Ps,{className:"w-4 h-4 text-pearl-400 group-hover:text-[#2481CC] transition-transform group-hover:translate-x-0.5 group-hover:-translate-y-0.5"})]},c)})})]}),e.jsxs("div",{className:"mt-6 p-3.5 rounded-lg bg-emerald-500/5 border border-emerald-500/20 text-xs font-mono text-pearl-300 flex items-center gap-3",children:[e.jsx(q,{className:"w-5 h-5 text-emerald-400 shrink-0"}),e.jsxs("div",{className:"text-[11px] leading-relaxed",children:[e.jsx("span",{className:"text-emerald-300 font-semibold",children:"Zero-Secret-Leakage:"})," Telegram tokens & LLM API keys encrypted with hardware-grade AES-256-GCM."]})]})]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3 px-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs font-semibold text-pearl-100 uppercase tracking-wide",children:"Live Managed Cloud Bot Topology & Webhook Health"}),e.jsx("span",{className:"text-[10px] font-mono px-2 py-0.5 rounded bg-emerald-500/10 text-emerald-300 border border-emerald-500/20",children:"24/7 Cloud Running"})]}),e.jsx("span",{className:"text-[10px] font-mono text-pearl-400 hidden sm:inline",children:"Click bot node to inspect telemetry · Drag to rotate view"})]}),e.jsx(Vl,{onSelectBot:d=>{r(d.id),s&&s(d.id)},onOpenStudio:d=>{r(d),s&&s(d),t("message-studio")}})]})]})},Oe=({className:t="w-6 h-6"})=>e.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",className:t,children:e.jsx("path",{d:"M12 0C5.373 0 0 5.373 0 12s5.373 12 12 12 12-5.373 12-12S18.627 0 12 0zm5.894 8.221l-1.97 9.28c-.145.658-.537.818-1.084.508l-3-2.21-1.446 1.394c-.16.16-.295.295-.605.295l.213-3.053 5.56-5.023c.242-.213-.054-.333-.373-.121l-6.871 4.326-2.962-.924c-.643-.204-.657-.643.136-.953l11.57-4.458c.538-.196 1.006.128.832.925z"})}),Gl=()=>{const{isAuthenticated:t}=qe(),{theme:s,toggleTheme:n}=nt(),a=ce(),[l,r]=i.useState(!1),[o,j]=i.useState(null),[b,m]=i.useState([{sender:"user",text:"/start",time:"12:00"},{sender:"bot",text:`👋 Welcome to TeleBot Cloud! apps/frontend/dist/assets/index-DHrGTvWe.js:81:Tap an action button below to test this live bot:`,buttons:[{label:"⚡ Explore 25+ Templates",action:"templates"},{label:"💳 Test VIP Subscription",action:"subscription"},{label:"🎁 Referral Link Demo",action:"referral"},{label:"🤖 Ask AI Assistant",action:"ai"}],time:"12:00"}])},f=[{q:"Do I need my own VPS or coding skills?",a:"Zero server or coding skills required. TeleBot Cloud runs 100% on our managed high-availability cloud infrastructure with automated HTTPS webhooks, PostgreSQL persistence, and Redis caching. You simply paste your token from @BotFather."},{q:"How does BotFather integration work?",a:"Open Telegram, chat with @BotFather, send /newbot, and copy the API HTTP token. Paste it into TeleBot Cloud, and our engine automatically configures high-speed webhooks, SSL certificates, and database schemas in seconds."},{q:"Can I accept payments and sell VIP channel access?",a:"Yes! Our built-in Payments and Subscription modules support Telegram Stars, Stripe, Razorpay, and Crypto. When a user pays, the bot automatically creates a single-use invite link to your private channel and revokes access when the subscription expires."},{q:"What modules are included with each bot?",a:"Every bot has access to 9 core production modules: Referral & Affiliate System, Broadcast Campaign Engine, Force Join Guard, Rich Welcome Messages, User Management CRM, Payments, VIP Subscriptions, Auto Filter Media Vault, and Autonomous AI Assistant."},{q:"What is the broadcast speed and rate limit?",a:"Our broadcast engine adheres strictly to Telegram official rate limits (up to 25-30 messages per second) using Celery background queues, preventing bot bans while delivering campaigns to thousands of users within minutes."}];return e.jsxs("div",{className:"min-h-screen bg-space-950 text-pearl-100 flex flex-col w-full max-w-full overflow-x-hidden selection:bg-[#2481CC]/20 selection:text-[#2481CC]",children:[e.jsxs("header",{className:"sticky top-0 z-50 backdrop-blur-md bg-space-950/90 border-b border-white/10 w-full",children:[e.jsxs("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 h-16 sm:h-20 flex items-center justify-between",children:[e.jsxs(A,{to:"/",className:"flex items-center gap-2.5 sm:gap-3 group shrink-0",children:[e.jsx("div",{className:"w-8 h-8 sm:w-10 sm:h-10 rounded-xl bg-[#2481CC] text-white flex items-center justify-center shadow-telegram group-hover:bg-[#1D74B7] transition shrink-0",children:e.jsx(Oe,{className:"w-5 h-5 sm:w-6 sm:h-6 text-white"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1.5 sm:gap-2",children:[e.jsxs("span",{className:"font-sans font-bold text-base sm:text-lg text-pearl-50 tracking-tight",children:["TeleBot",e.jsx("span",{className:"text-[#2481CC]",children:"Cloud"})]}),e.jsx("span",{className:"px-1.5 py-0.5 rounded-full text-[9px] sm:text-[10px] font-mono bg-[#2481CC]/10 text-[#2481CC] border border-[#2481CC]/30 font-semibold",children:"SaaS"})]}),e.jsx("span",{className:"hidden sm:block text-[10px] font-mono text-pearl-400 uppercase tracking-wider",children:"Managed Telegram Bot Platform"})]})]}),e.jsxs("nav",{className:"hidden lg:flex items-center gap-8 text-sm font-medium text-pearl-300",children:[e.jsx("a",{href:"#features",className:"hover:text-[#2481CC] transition",children:"Features"}),e.jsx("a",{href:"#modules",className:"hover:text-[#2481CC] transition",children:"Modules"}),e.jsxs(A,{to:"/marketplace",className:"hover:text-[#2481CC] transition flex items-center gap-1.5",children:[e.jsx("span",{children:"Templates"}),e.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-mono bg-[#2481CC]/15 text-[#2481CC]",children:"25"})]}),e.jsx(A,{to:"/pricing",className:"hover:text-[#2481CC] transition",children:"Pricing"}),e.jsx("a",{href:"#how-it-works",className:"hover:text-[#2481CC] transition",children:"How It Works"}),e.jsx("a",{href:"#faq",className:"hover:text-[#2481CC] transition",children:"FAQ"})]}),e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 shrink-0",children:[e.jsx("button",{onClick:n,className:"p-1.5 sm:p-2 rounded-lg bg-space-900 border border-white/10 text-pearl-300 hover:text-[#2481CC] hover:border-[#2481CC]/40 transition shadow-sm flex items-center justify-center",title:s==="light"?"Switch to Dark Mode":"Switch to Light Mode","aria-label":"Toggle theme",children:s==="light"?e.jsx(De,{className:"w-4 h-4 text-slate-700"}):e.jsx(Fe,{className:"w-4 h-4 text-amber-400"})}),t?e.jsxs(A,{to:"/dashboard",className:"hidden sm:inline-flex btn-telegram-primary py-1.5 sm:py-2 px-3 sm:px-4 text-xs font-semibold rounded-lg shadow-telegram items-center gap-1.5",children:[e.jsx("span",{children:"DASHBOARD"}),e.jsx(ie,{className:"w-3.5 h-3.5"})]}):e.jsxs("div",{className:"hidden sm:flex items-center gap-2",children:[e.jsx(A,{to:"/login",className:"hidden md:inline-flex btn-telegram-secondary py-1.5 sm:py-2 px-3 text-xs font-medium",children:"Log In"}),e.jsxs(A,{to:"/dashboard/bots",className:"btn-telegram-primary py-1.5 sm:py-2 px-3.5 sm:px-4 text-xs font-semibold rounded-lg shadow-telegram items-center gap-1.5",children:[e.jsx("span",{children:"CREATE BOT"}),e.jsx(ie,{className:"w-3.5 h-3.5"})]})]}),e.jsx("button",{onClick:()=>r(!l),className:"p-1.5 sm:p-2 text-pearl-400 hover:text-pearl-100 rounded-lg lg:hidden","aria-label":"Toggle navigation",children:l?e.jsx(H,{className:"w-6 h-6"}):e.jsx(_s,{className:"w-6 h-6"})})]})]}),l&&e.jsxs("div",{className:"lg:hidden border-t border-white/10 bg-space-900/98 px-6 py-6 space-y-4 animate-in fade-in",children:[e.jsxs("div",{className:"flex flex-col space-y-3 text-sm font-medium",children:[e.jsx("a",{href:"#features",onClick:()=>r(!1),className:"p-2 rounded-lg hover:bg-[#2481CC]/10 hover:text-[#2481CC]",children:"Features"}),e.jsx("a",{href:"#modules",onClick:()=>r(!1),className:"p-2 rounded-lg hover:bg-[#2481CC]/10 hover:text-[#2481CC]",children:"9 Core Modules"}),e.jsxs(A,{to:"/marketplace",onClick:()=>r(!1),className:"p-2 rounded-lg hover:bg-[#2481CC]/10 hover:text-[#2481CC] flex items-center justify-between",children:[e.jsx("span",{children:"25 Ready Bot Templates"}),e.jsx("span",{className:"px-2 py-0.5 rounded text-[10px] font-mono bg-[#2481CC]/20 text-[#2481CC]",children:"25"})]}),e.jsx(A,{to:"/pricing",onClick:()=>r(!1),className:"p-2 rounded-lg hover:bg-[#2481CC]/10 hover:text-[#2481CC]",children:"Pricing Plans"}),e.jsx("a",{href:"#how-it-works",onClick:()=>r(!1),className:"p-2 rounded-lg hover:bg-[#2481CC]/10 hover:text-[#2481CC]",children:"How It Works"}),e.jsx("a",{href:"#faq",onClick:()=>r(!1),className:"p-2 rounded-lg hover:bg-[#2481CC]/10 hover:text-[#2481CC]",children:"FAQ"})]}),e.jsx("div",{className:"pt-4 border-t border-white/10 flex flex-col gap-2",children:t?e.jsx(A,{to:"/dashboard",onClick:()=>r(!1),className:"w-full btn-telegram-primary py-2.5 justify-center text-xs",children:"Open Bot Dashboard"}):e.jsxs(e.Fragment,{children:[e.jsx(A,{to:"/login",onClick:()=>r(!1),className:"w-full btn-telegram-secondary py-2.5 justify-center text-xs",children:"Log In"}),e.jsx(A,{to:"/dashboard/bots",onClick:()=>r(!1),className:"w-full btn-telegram-primary py-2.5 justify-center text-xs",children:"Create Telegram Bot Free"})]})})]})]}),e.jsxs("section",{className:"relative pt-10 sm:pt-16 pb-16 lg:pb-24 px-4 sm:px-6 lg:px-8 max-w-7xl mx-auto w-full",children:[e.jsx("div",{className:"absolute top-10 left-1/2 -translate-x-1/2 w-3/4 max-w-3xl h-96 bg-[#2481CC]/15 rounded-full blur-3xl pointer-events-none -z-10"}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-12 gap-12 items-center",children:[e.jsxs("div",{className:"lg:col-span-7 space-y-6 text-center lg:text-left",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-3 py-1.5 rounded-full bg-[#2481CC]/10 border border-[#2481CC]/30 text-xs font-semibold text-[#2481CC]",children:[e.jsx(Oe,{className:"w-4 h-4 text-[#2481CC]"}),e.jsx("span",{children:"Telegram Bot Builder & 24/7 Managed Cloud SaaS"})]}),e.jsxs("h1",{className:"text-3xl sm:text-4xl md:text-5xl lg:text-6xl font-bold tracking-tight text-pearl-50 leading-[1.12]",children:["Build, Launch & Scale ",e.jsx("br",{className:"hidden sm:inline"}),e.jsx("span",{className:"text-[#2481CC] relative inline-block",children:"Telegram Bots"})," ","in Minutes"]}),e.jsx("p",{className:"text-base sm:text-lg text-pearl-300 font-normal leading-relaxed max-w-2xl mx-auto lg:mx-0",children:"No VPS or Linux server required. Connect your BotFather token, install ready-to-use bot templates, toggle production modules (Payments, Referrals, Broadcasts, AI Assistant), and deploy to the cloud 24/7."}),e.jsxs("div",{className:"flex flex-col sm:flex-row items-center justify-center lg:justify-start gap-3 sm:gap-4 pt-2",children:[e.jsxs(A,{to:"/dashboard/bots",className:"w-full sm:w-auto btn-telegram-primary py-3.5 px-6 text-sm font-semibold rounded-xl shadow-telegram flex items-center justify-center gap-2.5",children:[e.jsx(Oe,{className:"w-5 h-5 text-white"}),e.jsx("span",{children:"Create Your Bot Free"}),e.jsx(ie,{className:"w-4 h-4"})]}),e.jsxs(A,{to:"/marketplace",className:"w-full sm:w-auto btn-telegram-secondary py-3.5 px-6 text-sm font-semibold rounded-xl flex items-center justify-center gap-2",children:[e.jsx(J,{className:"w-4 h-4 text-[#2481CC]"}),e.jsx("span",{children:"Explore 25+ Templates"})]})]}),e.jsxs("div",{className:"pt-6 border-t border-white/10 grid grid-cols-3 gap-4 text-center lg:text-left",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xl sm:text-2xl font-bold text-pearl-50",children:"10,000+"}),e.jsx("div",{className:"text-xs text-pearl-400 font-mono mt-0.5",children:"Bots Hosted"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xl sm:text-2xl font-bold text-emerald-400",children:"99.98%"}),e.jsx("div",{className:"text-xs text-pearl-400 font-mono mt-0.5",children:"Cloud Uptime"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xl sm:text-2xl font-bold text-[#2481CC]",children:"0 VPS"}),e.jsx("div",{className:"text-xs text-pearl-400 font-mono mt-0.5",children:"Zero Server Config"})]})]})]}),e.jsx("div",{className:"lg:col-span-5 w-full",children:e.jsxs("div",{className:"astraea-panel rounded-2xl border border-white/15 shadow-2xl overflow-hidden max-w-md mx-auto",children:[e.jsxs("div",{className:"bg-[#2481CC] text-white p-3.5 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-full bg-white/20 flex items-center justify-center text-white font-bold text-base shrink-0",children:e.jsx(Q,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"font-semibold text-sm leading-tight",children:"TeleBot Concierge"}),e.jsx("span",{className:"w-3.5 h-3.5 rounded-full bg-white text-[#2481CC] text-[9px] font-bold flex items-center justify-center",children:"✓"})]}),e.jsxs("div",{className:"text-[11px] text-white/80 font-mono flex items-center gap-1",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-emerald-300 animate-pulse"}),e.jsx("span",{children:"bot · 24/7 cloud online"})]})]})]}),e.jsx("div",{className:"text-[10px] font-mono px-2 py-0.5 rounded bg-white/20 text-white",children:"LIVE SIMULATOR"})]}),e.jsx("div",{className:"p-4 space-y-3.5 min-h-[360px] max-h-[420px] overflow-y-auto bg-space-950/40 text-xs",children:b.map((p,g)=>e.jsxs("div",{className:`flex flex-col ${p.sender==="user"?"items-end":"items-start"} animate-in fade-in duration-200`,children:[e.jsxs("div",{className:`max-w-[88%] p-3 text-xs leading-relaxed ${p.sender==="user"?"telegram-bubble-outgoing":"telegram-bubble-incoming"}`,children:[e.jsx("div",{dangerouslySetInnerHTML:{__html:p.text.replace(/\n/g,"
")}}),e.jsxs("div",{className:"text-[9px] text-pearl-400/80 text-right mt-1.5 font-mono",children:[p.time," ",p.sender==="user"&&"✓✓"]})]}),p.buttons&&p.buttons.length>0&&e.jsx("div",{className:"grid grid-cols-2 gap-1.5 mt-2 w-full max-w-[88%]",children:p.buttons.map((u,d)=>e.jsx("button",{onClick:()=>x(u.action),className:"telegram-btn text-center justify-center text-[11px] py-2 px-2 hover:scale-[1.02] active:scale-[0.98] truncate",children:u.label},d))})]},g))}),e.jsxs("div",{className:"p-3 border-t border-white/10 bg-space-900 flex items-center gap-2",children:[e.jsx("input",{type:"text",readOnly:!0,value:"Tap any button above to test the live bot...",className:"flex-1 bg-space-950 text-pearl-400 text-xs px-3 py-2 rounded-lg border border-white/10 cursor-not-allowed font-mono"}),e.jsx("button",{onClick:()=>x("reset"),className:"p-2 rounded-lg bg-[#2481CC] text-white hover:bg-[#1D74B7] transition shrink-0",title:"Reset Simulator",children:e.jsx(oe,{className:"w-4 h-4"})})]})]})})]})]}),e.jsx("section",{id:"how-it-works",className:"py-16 sm:py-24 bg-space-900 border-y border-white/10",children:e.jsxs("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 lg:px-8",children:[e.jsxs("div",{className:"text-center max-w-3xl mx-auto space-y-3 mb-16",children:[e.jsx("span",{className:"text-xs font-mono text-[#2481CC] uppercase tracking-wider font-semibold",children:"Simple 4-Step Launch Pipeline"}),e.jsx("h2",{className:"text-3xl sm:text-4xl font-bold text-pearl-50",children:"From BotFather to 24/7 Production in 2 Minutes"}),e.jsx("p",{className:"text-pearl-300 text-sm sm:text-base leading-relaxed",children:"No need to configure Linux servers, systemd files, PM2, or SSL certificates. We handle the entire backend infrastructure."})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6",children:[{step:"01",title:"Get BotFather Token",desc:"Open Telegram, chat with @BotFather, send /newbot, and copy your HTTP API token.",icon:Oe},{step:"02",title:"Select Bot Template",desc:"Choose from 25+ prebuilt templates: VIP Paid Channel, Referral, E-Commerce, or Support.",icon:J},{step:"03",title:"Toggle & Configure Modules",desc:"Enable Payments, Force Join, Broadcasts, and AI Assistants with visual controls.",icon:Pe},{step:"04",title:"24/7 Managed Cloud Launch",desc:"Your bot deploys instantly with high-speed webhooks, PostgreSQL storage, and 99.98% uptime.",icon:Ge}].map((p,g)=>{const u=p.icon;return e.jsxs("div",{className:"astraea-card p-6 rounded-2xl flex flex-col justify-between relative group hover:border-[#2481CC] transition-all",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("span",{className:"text-2xl font-mono font-bold text-[#2481CC]",children:p.step}),e.jsx("div",{className:"w-10 h-10 rounded-xl bg-[#2481CC]/10 text-[#2481CC] flex items-center justify-center",children:e.jsx(u,{className:"w-5 h-5"})})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-pearl-50 mb-2",children:p.title}),e.jsx("p",{className:"text-xs text-pearl-400 leading-relaxed font-sans",children:p.desc})]})]},g)})})]})}),e.jsxs("section",{id:"modules",className:"py-16 sm:py-24 max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 w-full",children:[e.jsxs("div",{className:"text-center max-w-3xl mx-auto space-y-3 mb-16",children:[e.jsxs("div",{className:"inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-[#2481CC]/10 text-xs font-semibold text-[#2481CC]",children:[e.jsx(Pe,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:"Modular Bot Architecture"})]}),e.jsx("h2",{className:"text-3xl sm:text-4xl font-bold text-pearl-50",children:"9 Core Production Modules. Zero Code Required."}),e.jsx("p",{className:"text-pearl-300 text-sm sm:text-base leading-relaxed",children:"Every bot can install, configure, activate, and deactivate modules independently. Real backend execution, database support, and automated permissions."})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6",children:[{id:"referral",name:"Referral & Affiliate System",desc:"Multi-tier referral links, reward points, fraud detection, and automated payouts to drive viral growth.",icon:Ma,tag:"VIRAL GROWTH"},{id:"broadcast",name:"Broadcast Campaign Engine",desc:"Dispatches 25 msgs/sec compliant rich announcements to thousands of subscribers with real-time delivery tracking.",icon:pe,tag:"HIGH-THROUGHPUT"},{id:"force-join",name:"Force Join Channel Guard",desc:"Mandates channel and group subscriptions before users can access bot commands, multiplying your member count.",icon:Is,tag:"AUDIENCE BUILDER"},{id:"welcome",name:"Welcome & Message Studio",desc:"Visual editor for interactive inline buttons, photos, videos, and dynamic placeholders like {first_name}.",icon:Ht,tag:"STUDIO PRO"},{id:"users",name:"User Management CRM",desc:"Comprehensive subscriber directory, custom tags, ban/unban controls, activity history, and engagement analytics.",icon:Ae,tag:"ANALYTICS"},{id:"payments",name:"Payments & Invoicing Gateway",desc:"Accept Telegram Stars, Stripe, Razorpay, UPI, and Crypto directly in chat with automated receipts.",icon:La,tag:"MONETIZATION"},{id:"subscriptions",name:"VIP Subscriptions & Auto-Kick",desc:"Automates paid channel invites, recurring membership tracking, and kicks expired members automatically.",icon:Ve,tag:"RECURRING REVENUE"},{id:"auto-filter",name:"Auto Filter & Media Vault",desc:"Automated file search, keyword responses, buttons catalog, and high-speed media delivery for file channels.",icon:Ba,tag:"MEDIA ENGINE"},{id:"ai",name:"Autonomous AI Assistant",desc:"Powered by Gemini, Claude, and OpenAI with custom system prompts, contextual memory, and knowledge base docs.",icon:fe,tag:"AI POWERED"}].map(p=>{const g=p.icon;return e.jsxs("div",{className:"astraea-card p-6 rounded-2xl flex flex-col justify-between hover:border-[#2481CC] transition group",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("div",{className:"w-11 h-11 rounded-xl bg-[#2481CC]/10 text-[#2481CC] flex items-center justify-center group-hover:bg-[#2481CC] group-hover:text-white transition",children:e.jsx(g,{className:"w-5 h-5"})}),e.jsx("span",{className:"px-2 py-0.5 rounded text-[10px] font-mono uppercase bg-[#2481CC]/10 text-[#2481CC] border border-[#2481CC]/20 font-semibold",children:p.tag})]}),e.jsx("h3",{className:"text-base font-semibold text-pearl-50 mb-2",children:p.name}),e.jsx("p",{className:"text-xs text-pearl-400 font-sans leading-relaxed",children:p.desc})]}),e.jsxs("div",{className:"mt-5 pt-4 border-t border-white/10 flex items-center justify-between text-xs",children:[e.jsxs("span",{className:"text-emerald-400 font-mono text-[11px] flex items-center gap-1.5",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-emerald-400"}),"Production Ready"]}),e.jsxs(A,{to:"/dashboard/bots/astraea-flagship",className:"text-[#2481CC] hover:underline flex items-center gap-1 font-semibold",children:[e.jsx("span",{children:"Configure"}),e.jsx(Te,{className:"w-3.5 h-3.5"})]})]})]},p.id)})})]}),e.jsx("section",{className:"py-16 sm:py-24 bg-space-900 border-y border-white/10",children:e.jsxs("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 lg:px-8",children:[e.jsxs("div",{className:"flex flex-col md:flex-row md:items-end justify-between gap-6 mb-12",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-xs font-mono text-[#2481CC] uppercase tracking-wider font-semibold",children:"Instant Turnkey Solutions"}),e.jsx("h2",{className:"text-3xl sm:text-4xl font-bold text-pearl-50 mt-1",children:"25+ Complete Bot Templates"}),e.jsx("p",{className:"text-pearl-300 text-sm mt-1 max-w-xl",children:"Deploy fully assembled bots in one click, preconfigured with modules, message templates, and workflows."})]}),e.jsxs(A,{to:"/marketplace",className:"btn-telegram-primary py-2.5 px-5 text-xs font-semibold rounded-lg self-start md:self-auto shrink-0",children:[e.jsx("span",{children:"VIEW ALL 25 TEMPLATES"}),e.jsx(ie,{className:"w-3.5 h-3.5"})]})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-6",children:[{title:"VIP Paid Channel Subscription Bot",slug:"vip-subscription-bot",desc:"Automates payment collection via Telegram Stars, Stripe, and Crypto, generates one-time invites, and kicks expired members.",badge:"BESTSELLER",modules:["Payments","Subscriptions","Broadcast"]},{title:"Viral Referral & Reward Bot",slug:"referral-growth-bot",desc:"Gamified affiliate marketing system with custom invite links, leaderboards, milestone rewards, and instant notifications.",badge:"VIRAL",modules:["Referral","User CRM","Broadcast"]},{title:"AI Customer Support Concierge",slug:"ai-concierge-bot",desc:"24/7 automated agent answering customer inquiries with customized LLM models, FAQ knowledge base, and human agent routing.",badge:"AI DRIVEN",modules:["AI Assistant","Welcome","User CRM"]}].map((p,g)=>e.jsxs("div",{className:"astraea-card p-6 rounded-2xl flex flex-col justify-between hover:border-[#2481CC] transition group",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("span",{className:"px-2 py-0.5 rounded text-[10px] font-mono bg-[#2481CC]/15 text-[#2481CC] font-bold",children:p.badge}),e.jsx("span",{className:"text-[11px] font-mono text-pearl-400",children:"⚡ 1-Click Install"})]}),e.jsx("h3",{className:"text-lg font-semibold text-pearl-50 mb-2",children:p.title}),e.jsx("p",{className:"text-xs text-pearl-400 font-sans leading-relaxed mb-4",children:p.desc}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mb-6",children:p.modules.map((u,d)=>e.jsx("span",{className:"px-2 py-0.5 rounded text-[10px] font-mono bg-space-850 text-pearl-300 border border-white/10",children:u},d))})]}),e.jsxs(A,{to:`/marketplace/bots/${p.slug}`,className:"w-full btn-telegram-primary py-2.5 text-xs justify-center",children:[e.jsx("span",{children:"Install This Template"}),e.jsx(ie,{className:"w-3.5 h-3.5"})]})]},g))})]})}),e.jsxs("section",{className:"py-16 sm:py-24 max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 w-full",children:[e.jsxs("div",{className:"text-center max-w-3xl mx-auto space-y-3 mb-16",children:[e.jsx("span",{className:"text-xs font-mono text-[#2481CC] uppercase tracking-wider font-semibold",children:"Infrastructure Comparison"}),e.jsx("h2",{className:"text-3xl sm:text-4xl font-bold text-pearl-50",children:"Why Teams Choose TeleBot Cloud over Self-Hosting"}),e.jsx("p",{className:"text-pearl-300 text-sm sm:text-base leading-relaxed",children:"Stop wasting hours configuring Ubuntu servers, handling SSL renewals, and troubleshooting random downtime."})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-8 max-w-4xl mx-auto",children:[e.jsxs("div",{className:"astraea-card p-6 sm:p-8 rounded-2xl border-rose-500/30 bg-rose-500/[0.02]",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-6",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-rose-500/10 text-rose-400 flex items-center justify-center shrink-0",children:e.jsx(ht,{className:"w-5 h-5"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-bold text-pearl-50",children:"Traditional VPS / Self-Hosted"}),e.jsx("span",{className:"text-xs font-mono text-rose-400",children:"High Overhead & Fragile"})]})]}),e.jsxs("ul",{className:"space-y-3 text-xs sm:text-sm text-pearl-300",children:[e.jsxs("li",{className:"flex items-start gap-2.5",children:[e.jsx(H,{className:"w-4 h-4 text-rose-400 shrink-0 mt-0.5"}),e.jsx("span",{children:"Requires Linux command-line, Docker, and systemd maintenance."})]}),e.jsxs("li",{className:"flex items-start gap-2.5",children:[e.jsx(H,{className:"w-4 h-4 text-rose-400 shrink-0 mt-0.5"}),e.jsx("span",{children:"Manual SSL Let's Encrypt certificate renewals and port forwarding."})]}),e.jsxs("li",{className:"flex items-start gap-2.5",children:[e.jsx(H,{className:"w-4 h-4 text-rose-400 shrink-0 mt-0.5"}),e.jsx("span",{children:"Bots crash randomly when VPS runs out of RAM or process freezes."})]}),e.jsxs("li",{className:"flex items-start gap-2.5",children:[e.jsx(H,{className:"w-4 h-4 text-rose-400 shrink-0 mt-0.5"}),e.jsx("span",{children:"No visual dashboard for modules, message templates, or CRM."})]}),e.jsxs("li",{className:"flex items-start gap-2.5",children:[e.jsx(H,{className:"w-4 h-4 text-rose-400 shrink-0 mt-0.5"}),e.jsx("span",{children:"Hardcoded scripts that break whenever Telegram updates its API."})]})]})]}),e.jsxs("div",{className:"astraea-card p-6 sm:p-8 rounded-2xl border-[#2481CC]/50 bg-[#2481CC]/[0.03] shadow-telegram",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-6",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-[#2481CC] text-white flex items-center justify-center shrink-0",children:e.jsx(Oa,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-bold text-pearl-50",children:"TeleBot Cloud Managed"}),e.jsx("span",{className:"text-xs font-mono text-[#2481CC]",children:"Zero Maintenance · 99.98% SLA"})]})]}),e.jsxs("ul",{className:"space-y-3 text-xs sm:text-sm text-pearl-200",children:[e.jsxs("li",{className:"flex items-start gap-2.5",children:[e.jsx(F,{className:"w-4 h-4 text-[#2481CC] shrink-0 mt-0.5"}),e.jsx("span",{children:"100% no-code setup with your BotFather token in under 60 seconds."})]}),e.jsxs("li",{className:"flex items-start gap-2.5",children:[e.jsx(F,{className:"w-4 h-4 text-[#2481CC] shrink-0 mt-0.5"}),e.jsx("span",{children:"Automated HTTPS webhook endpoints with Cloudflare DDoS protection."})]}),e.jsxs("li",{className:"flex items-start gap-2.5",children:[e.jsx(F,{className:"w-4 h-4 text-[#2481CC] shrink-0 mt-0.5"}),e.jsx("span",{children:"High-availability Redis task queues and auto-restarting workers."})]}),e.jsxs("li",{className:"flex items-start gap-2.5",children:[e.jsx(F,{className:"w-4 h-4 text-[#2481CC] shrink-0 mt-0.5"}),e.jsx("span",{children:"Visual Studio for Welcome Messages, Broadcasts, and Payments."})]}),e.jsxs("li",{className:"flex items-start gap-2.5",children:[e.jsx(F,{className:"w-4 h-4 text-[#2481CC] shrink-0 mt-0.5"}),e.jsx("span",{children:"9 production modules that turn on/off with a single toggle."})]})]})]})]})]}),e.jsx("section",{id:"pricing",className:"py-16 sm:py-24 bg-space-900 border-y border-white/10",children:e.jsxs("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 lg:px-8",children:[e.jsxs("div",{className:"text-center max-w-3xl mx-auto space-y-3 mb-16",children:[e.jsx("span",{className:"text-xs font-mono text-[#2481CC] uppercase tracking-wider font-semibold",children:"Fair & Transparent Pricing"}),e.jsx("h2",{className:"text-3xl sm:text-4xl font-bold text-pearl-50",children:"Plans Built for Every Stage of Growth"}),e.jsx("p",{className:"text-pearl-300 text-sm sm:text-base leading-relaxed",children:"Start free with your first bot. Upgrade as your audience and message volume grow."})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-6 max-w-5xl mx-auto",children:[e.jsxs("div",{className:"astraea-card p-6 sm:p-8 rounded-2xl flex flex-col justify-between",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-xs font-mono text-pearl-400 uppercase font-semibold",children:"STARTER"}),e.jsxs("div",{className:"my-4",children:[e.jsx("span",{className:"text-3xl sm:text-4xl font-bold text-pearl-50",children:"$0"}),e.jsx("span",{className:"text-xs text-pearl-400 font-mono ml-2",children:"/ Forever Free"})]}),e.jsx("p",{className:"text-xs text-pearl-400 mb-6 font-sans",children:"Ideal for testing ideas and launching your first Telegram community bot."}),e.jsxs("ul",{className:"space-y-2.5 text-xs text-pearl-300 mb-8",children:[e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx(D,{className:"w-4 h-4 text-emerald-400"}),e.jsx("span",{children:"1 Active Telegram Bot"})]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx(D,{className:"w-4 h-4 text-emerald-400"}),e.jsx("span",{children:"Up to 1,000 Subscribers"})]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx(D,{className:"w-4 h-4 text-emerald-400"}),e.jsx("span",{children:"Standard Broadcast Engine"})]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx(D,{className:"w-4 h-4 text-emerald-400"}),e.jsx("span",{children:"Welcome & Message Studio"})]})]})]}),e.jsx(A,{to:"/login",className:"w-full btn-telegram-secondary py-3 text-xs justify-center font-semibold",children:"Get Started Free"})]}),e.jsxs("div",{className:"astraea-card p-6 sm:p-8 rounded-2xl flex flex-col justify-between border-[#2481CC] shadow-telegram relative",children:[e.jsx("div",{className:"absolute -top-3 left-1/2 -translate-x-1/2 px-3 py-0.5 rounded-full bg-[#2481CC] text-white text-[10px] font-mono font-bold tracking-wider uppercase",children:"MOST POPULAR"}),e.jsxs("div",{children:[e.jsx("span",{className:"text-xs font-mono text-[#2481CC] uppercase font-bold",children:"PRO BUILDER"}),e.jsxs("div",{className:"my-4",children:[e.jsx("span",{className:"text-3xl sm:text-4xl font-bold text-pearl-50",children:"$19"}),e.jsx("span",{className:"text-xs text-pearl-400 font-mono ml-2",children:"/ month"})]}),e.jsx("p",{className:"text-xs text-pearl-400 mb-6 font-sans",children:"High-speed broadcasts, VIP paid subscriptions, and AI agents."}),e.jsxs("ul",{className:"space-y-2.5 text-xs text-pearl-200 mb-8",children:[e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx(D,{className:"w-4 h-4 text-[#2481CC]"}),e.jsx("span",{children:"5 Active Telegram Bots"})]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx(D,{className:"w-4 h-4 text-[#2481CC]"}),e.jsx("span",{children:"Up to 50,000 Subscribers"})]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx(D,{className:"w-4 h-4 text-[#2481CC]"}),e.jsx("span",{children:"25 msg/s Broadcast Engine"})]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx(D,{className:"w-4 h-4 text-[#2481CC]"}),e.jsx("span",{children:"Payments & VIP Subscriptions"})]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx(D,{className:"w-4 h-4 text-[#2481CC]"}),e.jsx("span",{children:"Autonomous AI Assistant"})]})]})]}),e.jsx(A,{to:"/pricing",className:"w-full btn-telegram-primary py-3 text-xs justify-center font-semibold shadow-telegram",children:"Upgrade to Pro"})]}),e.jsxs("div",{className:"astraea-card p-6 sm:p-8 rounded-2xl flex flex-col justify-between",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-xs font-mono text-pearl-400 uppercase font-semibold",children:"ENTERPRISE"}),e.jsxs("div",{className:"my-4",children:[e.jsx("span",{className:"text-3xl sm:text-4xl font-bold text-pearl-50",children:"$79"}),e.jsx("span",{className:"text-xs text-pearl-400 font-mono ml-2",children:"/ month"})]}),e.jsx("p",{className:"text-xs text-pearl-400 mb-6 font-sans",children:"Large networks, unlimited subscribers, isolated databases, and 99.98% SLA."}),e.jsxs("ul",{className:"space-y-2.5 text-xs text-pearl-300 mb-8",children:[e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx(D,{className:"w-4 h-4 text-emerald-400"}),e.jsx("span",{children:"Unlimited Telegram Bots"})]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx(D,{className:"w-4 h-4 text-emerald-400"}),e.jsx("span",{children:"Unlimited Subscribers"})]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx(D,{className:"w-4 h-4 text-emerald-400"}),e.jsx("span",{children:"Full MCP Pro Cloud Tools Protocol"})]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx(D,{className:"w-4 h-4 text-emerald-400"}),e.jsx("span",{children:"Dedicated Isolated Database"})]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx(D,{className:"w-4 h-4 text-emerald-400"}),e.jsx("span",{children:"Priority Support via Telegram"})]})]})]}),e.jsx(A,{to:"/pricing",className:"w-full btn-telegram-secondary py-3 text-xs justify-center font-semibold",children:"View Enterprise Tiers"})]})]})]})}),e.jsxs("section",{id:"faq",className:"py-16 sm:py-24 max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 w-full",children:[e.jsxs("div",{className:"text-center space-y-3 mb-12",children:[e.jsx("span",{className:"text-xs font-mono text-[#2481CC] uppercase tracking-wider font-semibold",children:"Common Questions"}),e.jsx("h2",{className:"text-3xl sm:text-4xl font-bold text-pearl-50",children:"Frequently Asked Questions"})]}),e.jsx("div",{className:"space-y-4",children:f.map((p,g)=>{const u=o===g;return e.jsxs("div",{className:"astraea-card rounded-xl border border-white/10 overflow-hidden transition",children:[e.jsxs("button",{onClick:()=>j(u?null:g),className:"w-full p-4 sm:p-5 text-left flex items-center justify-between gap-4 font-semibold text-pearl-50 text-sm sm:text-base",children:[e.jsx("span",{children:p.q}),e.jsx(Te,{className:`w-5 h-5 text-pearl-400 transition-transform ${u?"rotate-90 text-[#2481CC]":""}`})]}),u&&e.jsx("div",{className:"px-4 sm:px-5 pb-5 text-xs sm:text-sm text-pearl-300 font-sans leading-relaxed border-t border-white/5 pt-3 animate-in fade-in",children:p.a})]},g)})})]}),e.jsx("section",{className:"py-16 px-4 sm:px-6 lg:px-8 max-w-7xl mx-auto w-full",children:e.jsx("div",{className:"rounded-3xl bg-[#2481CC] text-white p-8 sm:p-12 md:p-16 text-center space-y-6 shadow-2xl relative overflow-hidden",children:e.jsxs("div",{className:"relative z-10 max-w-2xl mx-auto space-y-4",children:[e.jsx("div",{className:"w-12 h-12 rounded-2xl bg-white/20 text-white flex items-center justify-center mx-auto mb-2",children:e.jsx(Oe,{className:"w-7 h-7 text-white"})}),e.jsx("h2",{className:"text-3xl sm:text-4xl md:text-5xl font-bold tracking-tight",children:"Ready to Launch Your Telegram Bot?"}),e.jsx("p",{className:"text-white/90 text-sm sm:text-base leading-relaxed",children:"Join thousands of creators, businesses, and channel admins running their Telegram bots on our managed cloud."}),e.jsxs("div",{className:"pt-2 flex flex-col sm:flex-row items-center justify-center gap-3",children:[e.jsxs(A,{to:"/dashboard/bots",className:"w-full sm:w-auto bg-white text-[#2481CC] hover:bg-slate-50 py-3.5 px-8 rounded-xl font-bold text-sm transition shadow-lg flex items-center justify-center gap-2",children:[e.jsx("span",{children:"Create Your Bot Now"}),e.jsx(ie,{className:"w-4 h-4"})]}),e.jsx(A,{to:"/marketplace",className:"w-full sm:w-auto bg-white/10 hover:bg-white/20 text-white py-3.5 px-6 rounded-xl font-medium text-sm transition border border-white/25 flex items-center justify-center gap-2",children:e.jsx("span",{children:"Browse Templates"})})]})]})})}),e.jsx("footer",{className:"border-t border-white/10 bg-space-900 pt-16 pb-12 w-full",children:e.jsxs("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 lg:px-8",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-8 pb-12 border-b border-white/10",children:[e.jsxs("div",{className:"col-span-2 space-y-4",children:[e.jsxs(A,{to:"/",className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-9 h-9 rounded-xl bg-[#2481CC] text-white flex items-center justify-center shadow-telegram",children:e.jsx(Oe,{className:"w-5 h-5 text-white"})}),e.jsxs("span",{className:"font-bold text-base text-pearl-50",children:["TeleBot",e.jsx("span",{className:"text-[#2481CC]",children:"Cloud"})]})]}),e.jsx("p",{className:"text-xs text-pearl-400 font-sans leading-relaxed max-w-sm",children:"The modern no-code Telegram Bot Builder & 24/7 Managed Cloud SaaS. Run your automated bot fleet without needing your own VPS or Linux servers."}),e.jsxs("div",{className:"flex items-center gap-2 text-xs font-mono text-emerald-400",children:[e.jsx("span",{className:"w-2 h-2 rounded-full bg-emerald-400 animate-pulse"}),e.jsx("span",{children:"All Cloud Systems Operational (99.98% SLA)"})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("h4",{className:"text-xs font-mono uppercase tracking-wider text-pearl-200 font-semibold",children:"Product"}),e.jsxs("ul",{className:"space-y-2 text-xs text-pearl-400",children:[e.jsx("li",{children:e.jsx(A,{to:"/dashboard",className:"hover:text-[#2481CC] transition",children:"Dashboard"})}),e.jsx("li",{children:e.jsx(A,{to:"/dashboard/bots",className:"hover:text-[#2481CC] transition",children:"Bot Fleet"})}),e.jsx("li",{children:e.jsx(A,{to:"/marketplace",className:"hover:text-[#2481CC] transition",children:"25+ Templates"})}),e.jsx("li",{children:e.jsx(A,{to:"/dashboard/builder",className:"hover:text-[#2481CC] transition",children:"Visual Builder"})}),e.jsx("li",{children:e.jsx(A,{to:"/dashboard/studio",className:"hover:text-[#2481CC] transition",children:"Message Studio"})})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("h4",{className:"text-xs font-mono uppercase tracking-wider text-pearl-200 font-semibold",children:"Modules"}),e.jsxs("ul",{className:"space-y-2 text-xs text-pearl-400",children:[e.jsx("li",{children:e.jsx(A,{to:"/dashboard/users",className:"hover:text-[#2481CC] transition",children:"Referral System"})}),e.jsx("li",{children:e.jsx(A,{to:"/dashboard/broadcasts",className:"hover:text-[#2481CC] transition",children:"Broadcast Engine"})}),e.jsx("li",{children:e.jsx(A,{to:"/dashboard/payments",className:"hover:text-[#2481CC] transition",children:"Payments & Stars"})}),e.jsx("li",{children:e.jsx(A,{to:"/dashboard/subscriptions",className:"hover:text-[#2481CC] transition",children:"VIP Subscriptions"})}),e.jsx("li",{children:e.jsx(A,{to:"/dashboard/agents",className:"hover:text-[#2481CC] transition",children:"AI Agent Studio"})})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("h4",{className:"text-xs font-mono uppercase tracking-wider text-pearl-200 font-semibold",children:"Access"}),e.jsxs("ul",{className:"space-y-2 text-xs text-pearl-400",children:[e.jsx("li",{children:e.jsx(A,{to:"/pricing",className:"hover:text-[#2481CC] transition",children:"Pricing Plans"})}),e.jsx("li",{children:e.jsx(A,{to:"/login",className:"hover:text-[#2481CC] transition",children:"Telegram Sign In"})}),e.jsx("li",{children:e.jsx(A,{to:"/dashboard/settings",className:"hover:text-[#2481CC] transition",children:"Settings"})}),e.jsx("li",{children:e.jsx(A,{to:"/dashboard/audit-logs",className:"hover:text-[#2481CC] transition",children:"Security Logs"})})]})]})]}),e.jsxs("div",{className:"pt-8 flex flex-col sm:flex-row items-center justify-between text-xs text-pearl-400 gap-4 font-mono",children:[e.jsx("div",{children:"© 2026 TeleBot Cloud Platform. All rights reserved."}),e.jsxs("div",{className:"flex items-center gap-6",children:[e.jsx(A,{to:"/pricing",className:"hover:text-pearl-100",children:"Terms of Service"}),e.jsx(A,{to:"/pricing",className:"hover:text-pearl-100",children:"Privacy Policy"}),e.jsxs("a",{href:"https://t.me/BotFather",target:"_blank",rel:"noopener noreferrer",className:"hover:text-[#2481CC] flex items-center gap-1",children:[e.jsx("span",{children:"BotFather"}),e.jsx(ge,{className:"w-3 h-3"})]})]})]})]})})]})},te=({children:t})=>{const[s,n]=i.useState(!1);return i.useEffect(()=>{n(!0);const a=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{n(!1),document.body.style.overflow=a}},[]),s?Ws.createPortal(t,document.body):null},At=[{id:"bot_ecommerce_concierge",name:"E-Commerce & Digital Store Concierge",headline:"Interactive shopping catalog, cart management & instant Telegram checkout.",description:"Transforms your Telegram bot into an automated 24/7 digital storefront. Customers can browse categorized products with images, add items to cart, select delivery address, and pay via integrated Razorpay/Stripe checkout without leaving Telegram.",category:"business",icon:Es,version:"1.2.0",rating:4.95,installCount:1420,isFeatured:!0,tags:["ecommerce","store","payments","shopping","cart"],permissions:["messages.send","payments.create","database.read_write"],mcpTools:["shopify.products.search","payments.order.verify","shipping.status.get"],systemTemplates:["welcome","catalog","cart_view","invoice","order_status"],defaultConfig:{store_name:"Astraea Boutique",currency:"INR",shipping_fee:0}},{id:"bot_customer_support",name:"AI Customer Support Desk",headline:"Tier-1 AI resolution with seamless human agent ticket escalation.",description:"Automate 80% of customer inquiries with smart contextual AI answers. Detects frustrated users and automatically opens priority tickets with notification alerts to your human support team.",category:"business",icon:Rs,version:"1.1.0",rating:4.92,installCount:980,isFeatured:!0,tags:["support","tickets","helpdesk","ai","crm"],permissions:["messages.send","notifications.dispatch","ai.completion"],mcpTools:["zendesk.ticket.create","crm.contact.lookup"],systemTemplates:["welcome","ticket_created","ticket_resolved"],defaultConfig:{company_name:"Acme Cloud",escalation_threshold:.35}},{id:"bot_lead_crm",name:"Lead Generation & CRM Collector",headline:"Conversational qualification funnel that captures leads directly into your database.",description:"Replaces tedious web forms with natural in-chat qualification. Collects verified phone numbers via Telegram 1-tap contact sharing, qualifies budgets, and syncs immediately to HubSpot/Google Sheets.",category:"business",icon:Da,version:"1.0.4",rating:4.88,installCount:750,isFeatured:!1,tags:["leads","crm","forms","hubspot","sales"],permissions:["messages.send","users.contact.request"],mcpTools:["hubspot.contact.create","sheets.append_row"],systemTemplates:["welcome","ask_question","lead_thankyou"],defaultConfig:{target_sheet_id:"",notify_admin_chat_id:""}},{id:"bot_appointment_booking",name:"Calendar & Appointment Scheduler",headline:"Real-time time-slot booking with Google Calendar / Cal.com sync.",description:"Eliminates back-and-forth scheduling messages. Clients select available dates directly from an inline calendar matrix, receive automated reminder pings, and can reschedule in 1 tap.",category:"business",icon:Fa,version:"1.3.1",rating:4.91,installCount:620,isFeatured:!1,tags:["calendar","booking","appointments","reminders"],permissions:["messages.send","notifications.schedule"],mcpTools:["google.calendar.events.list","google.calendar.events.create"],systemTemplates:["welcome","select_slot","booking_confirmed"],defaultConfig:{slot_duration_minutes:30,buffer_minutes:10}},{id:"bot_invoice_billing",name:"Invoice Generation & Ledger Bot",headline:"Generate itemized PDF bills and collect UPI/card payments instantly.",description:"Instant billing tool for service providers, freelancers, and agencies. Send /invoice to generate professional branded invoices with payment deep-links and verified status tracking.",category:"business",icon:Ut,version:"1.1.2",rating:4.89,installCount:890,isFeatured:!0,tags:["invoicing","billing","accounting","pdf","payments"],permissions:["messages.send","payments.create","files.upload"],mcpTools:["payments.invoice.create","pdf.invoice.render"],systemTemplates:["welcome","invoice_summary","payment_success"],defaultConfig:{company_tax_id:"",currency:"INR"}},{id:"bot_subscription_vip",name:"VIP Club & Community Gatekeeper",headline:"Paid subscription channels with automated invite links and expiry kick.",description:"Monetize exclusive Telegram channels and groups. Accepts recurring monthly/yearly payments, generates single-use join links, and auto-removes users upon membership expiration.",category:"business",icon:rt,version:"2.0.0",rating:4.98,installCount:2310,isFeatured:!0,tags:["subscriptions","vip","monetization","channels","paywall"],permissions:["channels.manage","invite_links.create","members.restrict"],mcpTools:["telegram.chat.create_invite_link","telegram.chat.kick_member"],systemTemplates:["welcome","plans_list","vip_welcome","expiry_warning"],defaultConfig:{channel_id:"",monthly_price:499,currency:"INR"}},{id:"bot_group_admin_pro",name:"Group Admin & Moderation Shield",headline:"Comprehensive Telegram group guard with anti-flood and auto-mute.",description:"Keep large Telegram supergroups civilized 24/7. Automatically cleans join/leave spam messages, enforces message rate limits, silences spammers, and provides extensive moderator command toolkits.",category:"community",icon:Ss,version:"2.4.0",rating:4.96,installCount:3450,isFeatured:!0,tags:["moderation","admin","anti-spam","groups","security"],permissions:["messages.delete","members.restrict","members.promote"],mcpTools:["telegram.group.delete_message","telegram.group.ban_member"],systemTemplates:["warn_message","ban_notice","rules_display"],defaultConfig:{max_warns:3,delete_service_messages:!0,flood_limit:5}},{id:"bot_anti_spam",name:"AI Anti-Spam & Link Filter",headline:"Neural network spam detector that blocks unauthorized advertising and phishing.",description:"Protects communities from crypto scams, fake airdrop bots, and unwanted external links. Evaluates message text and usernames using machine learning before users can fall for scams.",category:"community",icon:q,version:"1.3.0",rating:4.94,installCount:1890,isFeatured:!1,tags:["antispam","phishing","security","links","crypto-shield"],permissions:["messages.delete","members.restrict"],mcpTools:["ai.spam.classify","url.reputation.check"],systemTemplates:["spam_deleted_notice"],defaultConfig:{allow_whitelisted_domains_only:!0,ban_on_crypto_scam:!0}},{id:"bot_welcome_verification",name:"Captcha Gate & Welcome Verifier",headline:"Stop userbot raids with interactive math and button CAPTCHAs.",description:"Requires all newly joined members to tap the matching emoji or solve a simple 1-click CAPTCHA within 60 seconds before they are allowed to send messages in the group.",category:"community",icon:$a,version:"1.2.5",rating:4.92,installCount:2100,isFeatured:!0,tags:["captcha","verification","onboarding","antiraid"],permissions:["members.restrict","messages.send","messages.delete"],mcpTools:["captcha.generate","telegram.chat.unmute"],systemTemplates:["captcha_prompt","welcome_verified"],defaultConfig:{captcha_timeout_sec:60,fail_action:"kick"}},{id:"bot_reputation_leaderboard",name:"Community Karma & Leaderboard",headline:"Reward helpful group members with +1 karma and weekly rank badges.",description:"Fosters active community engagement. Members award thanks to each other by replying +1 or /thanks. Automatically calculates daily top contributors and grants custom Telegram admin titles.",category:"community",icon:Ua,version:"1.1.0",rating:4.87,installCount:840,isFeatured:!1,tags:["karma","reputation","gamification","leaderboard","community"],permissions:["messages.read","messages.send"],mcpTools:["database.karma.increment","database.leaderboard.get"],systemTemplates:["karma_awarded","weekly_leaderboard"],defaultConfig:{cooldown_minutes:5,weekly_reset:!1}},{id:"bot_anonymous_feedback",name:"Anonymous Feedback & Confessions Box",headline:"Allows group members to ask questions or submit feedback anonymously.",description:"Encourages honest team or community feedback. Users message the bot in private, and the bot publishes the query into the group or admin channel with full author anonymity preserved.",category:"community",icon:Va,version:"1.0.8",rating:4.85,installCount:510,isFeatured:!1,tags:["anonymous","feedback","confessions","qa","privacy"],permissions:["messages.send"],mcpTools:["message.send_anonymous"],systemTemplates:["private_welcome","group_published_post"],defaultConfig:{destination_chat_id:"",moderation_queue:!0}},{id:"bot_referral_rewards",name:"Viral Referral & Contest Engine",headline:"Grow your Telegram channel rapidly with trackable subscriber invite links.",description:"Generates personal deep-link invite links (/start ref_12345). Tracks valid channel joins, detects fraudulent multi-accounts, and distributes rewards or entry tickets automatically.",category:"community",icon:ut,version:"2.1.0",rating:4.97,installCount:2890,isFeatured:!0,tags:["referral","viral","growth","contests","giveaways"],permissions:["messages.send","channels.members.verify"],mcpTools:["referral.code.generate","referral.signup.track"],systemTemplates:["welcome","my_referrals","reward_unlocked"],defaultConfig:{points_per_referral:10,min_payout_points:100}},{id:"bot_chatgpt_assistant",name:"Multi-LLM Conversational Brain",headline:"Intelligent multi-turn AI assistant powered by OpenAI GPT-4o and Claude 3.5.",description:"Deploy a versatile smart AI bot in your group or direct messages. Handles contextual Q&A, brainstorming, language translation, and summaries with custom persona instructions.",category:"ai_specialist",icon:Q,version:"2.5.0",rating:4.99,installCount:4200,isFeatured:!0,tags:["ai","chatgpt","claude","gemini","assistant"],permissions:["messages.send","ai.tokens.consume"],mcpTools:["openai.chat.completion","openrouter.chat.completion"],systemTemplates:["welcome","ai_typing","context_cleared"],defaultConfig:{model:"gpt-4o-mini",temperature:.7,memory_turns:10}},{id:"bot_pdf_research",name:"Document & PDF Research RAG",headline:"Upload PDF/DOCX files in chat and query them with semantic vector search.",description:"Transform documents into interactive knowledge bases. Users simply upload a whitepaper, contract, or textbook to Telegram and ask questions; the bot cites exact pages with answers.",category:"ai_specialist",icon:zt,version:"1.4.0",rating:4.93,installCount:1650,isFeatured:!0,tags:["rag","pdf","documents","search","embeddings"],permissions:["files.download","messages.send"],mcpTools:["embeddings.document.index","vector.similarity.search"],systemTemplates:["welcome","document_indexed","rag_answer"],defaultConfig:{chunk_size:500,top_k_matches:4}},{id:"bot_image_gen",name:"AI Image & Artwork Generator",headline:"Text-to-image studio using Flux.1 and Stable Diffusion directly in Telegram.",description:"Generate stunning photorealistic artwork, marketing banners, and avatars on demand. Send /imagine to receive 4 variations with upscaling and re-roll inline buttons.",category:"ai_specialist",icon:Pt,version:"1.3.2",rating:4.91,installCount:1980,isFeatured:!1,tags:["images","art","flux","midjourney","diffusion"],permissions:["photos.send","payments.credits.deduct"],mcpTools:["image.flux.generate","image.upscale"],systemTemplates:["welcome","generating_progress","image_delivered"],defaultConfig:{default_aspect_ratio:"1:1",credits_per_gen:1}},{id:"bot_code_interpreter",name:"Sandboxed Code Runner & Tutor",headline:"Execute Python, JavaScript, and SQL securely inside Telegram messages.",description:"Run code snippets, debug errors, and visualize charts directly within chat. Secure firewalled WebAssembly execution sandbox with syntax highlighting and instant outputs.",category:"ai_specialist",icon:Ha,version:"1.2.0",rating:4.88,installCount:780,isFeatured:!1,tags:["code","python","developer","sandbox","interpreter"],permissions:["messages.send"],mcpTools:["sandbox.code.execute"],systemTemplates:["welcome","execution_result"],defaultConfig:{execution_timeout_ms:3e3,memory_limit_mb:64}},{id:"bot_voice_transcriber",name:"Voice Note Transcriber & Summarizer",headline:"Converts long Telegram audio messages to clean text with bullet summaries.",description:"Never listen to a 5-minute voice note again. Powered by Whisper AI, converts incoming voice recordings and video notes into clean formatted transcripts with executive summaries.",category:"ai_specialist",icon:Ga,version:"1.5.0",rating:4.96,installCount:2450,isFeatured:!0,tags:["voice","audio","transcription","whisper","summary"],permissions:["voice.download","messages.send"],mcpTools:["audio.whisper.transcribe","ai.summary.generate"],systemTemplates:["transcript_ready"],defaultConfig:{auto_detect_language:!0,generate_summary:!0}},{id:"bot_sql_query_assistant",name:"Text-to-SQL Analytics Assistant",headline:"Ask business questions in plain English and receive instant database metrics.",description:'Empower executive teams to query production read-replicas safely. Send "How many VIP signups this week?" and the bot writes verified SQL queries and returns a table or chart.',category:"ai_specialist",icon:za,version:"1.1.0",rating:4.89,installCount:430,isFeatured:!1,tags:["sql","database","bi","analytics","charts"],permissions:["database.read_only","messages.send"],mcpTools:["db.schema.inspect","db.readonly.query"],systemTemplates:["welcome","query_result"],defaultConfig:{max_rows:50,enforce_read_only:!0}},{id:"bot_github_notifier",name:"GitHub DevOps Sentinel",headline:"Real-time repository alerts for commits, pull requests, issues, and releases.",description:'Bridge engineering workflows with Telegram. Sends interactive cards for incoming PRs with 1-click "Approve" or "Comment" buttons linked directly to your GitHub organization.',category:"developer_tools",icon:Wa,version:"2.1.0",rating:4.94,installCount:1540,isFeatured:!0,tags:["github","devops","git","pr","alerts"],permissions:["messages.send","webhooks.receive"],mcpTools:["github.repo.subscribe","github.pr.merge"],systemTemplates:["pr_opened","commit_alert","release_published"],defaultConfig:{filter_branches:["main","master","staging"]}},{id:"bot_server_monitor",name:"Server Uptime & Sentry Error Monitor",headline:"Instant Telegram pings when your API endpoints or Docker servers experience downtime.",description:"Reliable heartbeat monitoring for APIs, VPS nodes, and databases. Detects 5xx spikes and unhandled exceptions from Sentry and alerts on-call engineers within 2 seconds.",category:"developer_tools",icon:Ie,version:"1.6.0",rating:4.98,installCount:2210,isFeatured:!0,tags:["monitoring","uptime","sentry","devops","infra"],permissions:["notifications.dispatch","webhooks.receive"],mcpTools:["health.endpoint.ping","sentry.incident.notify"],systemTemplates:["outage_alert","recovery_notice"],defaultConfig:{check_interval_sec:30,retry_count:2}},{id:"bot_crypto_whale",name:"On-Chain Whale & DEX Swap Alert",headline:"Real-time tracking for large transactions on Ethereum, Solana, and TON.",description:"Catch large crypto movements before the market reacts. Streams customizable alerts for transactions over $100,000, new liquidity pool creations, and contract deployments.",category:"developer_tools",icon:Ge,version:"1.3.0",rating:4.87,installCount:1120,isFeatured:!1,tags:["crypto","whale-alerts","ton","solana","dex"],permissions:["messages.send"],mcpTools:["blockchain.whale.subscribe"],systemTemplates:["whale_swap_alert"],defaultConfig:{min_usd_value:1e5,chains:["TON","ETH","SOL"]}},{id:"bot_ssh_sysadmin",name:"SSH Command Runner & Cloud Console",headline:"Authorized 2FA terminal shell to inspect logs and restart Docker containers.",description:"Manage remote servers safely from your phone. Authenticated through Telegram biometrics and hardware keys. Execute safe whitelisted commands like `docker restart api` or `df -h`.",category:"developer_tools",icon:dt,version:"1.0.5",rating:4.84,installCount:390,isFeatured:!1,tags:["ssh","terminal","docker","sysadmin","devops"],permissions:["admin.hardware_auth","messages.send"],mcpTools:["server.ssh.execute_whitelisted"],systemTemplates:["auth_required","command_output"],defaultConfig:{allowed_commands:["status","restart","logs"],require_pin:!0}},{id:"bot_rss_reader",name:"RSS Feed & News Auto-Broadcaster",headline:"Auto-publish articles and YouTube videos to your Telegram channels within 60s.",description:"Keep your broadcast channels populated effortlessly. Watches unlimited RSS/Atom feeds, formats incoming news with custom headers and instant-view previews, and auto-posts.",category:"content_media",icon:qa,version:"1.4.2",rating:4.9,installCount:1780,isFeatured:!1,tags:["rss","news","youtube","blog","autopost"],permissions:["channels.post"],mcpTools:["rss.feed.fetch","telegram.channel.post"],systemTemplates:["feed_item_post"],defaultConfig:{check_interval_min:5,include_source_link:!0}},{id:"bot_newsletter_publisher",name:"Substack & Medium Syndicator",headline:"Syndicate your published newsletters with rich buttons and instant member polls.",description:"Grow a cross-platform media audience. Syncs newsletters automatically with instant formatting and provides member reaction buttons to gather engagement statistics.",category:"content_media",icon:Ja,version:"1.1.0",rating:4.86,installCount:640,isFeatured:!1,tags:["newsletter","substack","medium","publishing"],permissions:["channels.post","messages.send"],mcpTools:["publishing.syndicate"],systemTemplates:["newsletter_edition"],defaultConfig:{append_footer:!0}},{id:"bot_media_watermarker",name:"Bulk Photo & Video Watermarker",headline:"Automatically stamp your brand logo or channel handle onto uploaded media.",description:"Essential for media creators and community managers. Automatically overlays semi-transparent brand watermarks, protects intellectual property, and outputs high-quality compressed media.",category:"content_media",icon:Pt,version:"1.2.1",rating:4.92,installCount:1410,isFeatured:!0,tags:["watermark","branding","media","photos","video"],permissions:["files.download","files.upload"],mcpTools:["media.watermark.apply"],systemTemplates:["welcome","processing_media","media_ready"],defaultConfig:{watermark_text:"@MyBrand",position:"bottom_right",opacity:.7}}],zl=[{id:"inst-1",name:"VIP Boutique Shop",templateId:"bot_ecommerce_concierge",templateName:"E-Commerce & Digital Store Concierge",category:"business",status:"deployed",botUsername:"@astraea_shop_bot",uptimePct:100,interactionsCount:1240,installedAt:"2026-11-17T14:30:00Z"},{id:"inst-2",name:"DevOps GitHub Sentinel",templateId:"bot_github_notifier",templateName:"GitHub DevOps Notifier",category:"developer_tools",status:"deployed",botUsername:"@devops_sentinel_bot",uptimePct:99.98,interactionsCount:840,installedAt:"2026-11-18T08:15:00Z"}],Wl=()=>{const{currentBot:t,bots:s,selectBot:n,applyTemplateToBot:a}=z(),[l,r]=Bn(),o=l.get("tab")==="installed"?"installed":"catalog",j=_=>{r(_==="installed"?{tab:"installed"}:{})},[b,m]=i.useState("all"),[x,f]=i.useState(""),[p,g]=i.useState(null),[u,d]=i.useState(null),[c,v]=i.useState(""),[h,N]=i.useState((t==null?void 0:t.id)||"b-001"),[y,E]=i.useState(zl),[w,S]=i.useState(null),P=[{id:"all",name:"All Blueprints",count:At.length},{id:"business",name:"Business & Store",count:6},{id:"community",name:"Community Guard",count:6},{id:"ai_specialist",name:"AI Specialists",count:6},{id:"developer_tools",name:"Developer & DevOps",count:4},{id:"content_media",name:"Content & Media",count:3}],k=At.filter(_=>{const Y=b==="all"||_.category===b,K=_.name.toLowerCase().includes(x.toLowerCase())||_.headline.toLowerCase().includes(x.toLowerCase())||_.tags.some(ne=>ne.toLowerCase().includes(x.toLowerCase()));return Y&&K}),L=_=>{d(_),v(_.name),N((t==null?void 0:t.id)||"b-001")},M=()=>{if(!u)return;const _=s.find(ne=>ne.id===h)||t;a(_.id,u.name,u.systemTemplates);const Y=`@${_.username}`,K={id:`inst-${Date.now()}`,name:c||u.name,templateId:u.id,templateName:u.name,category:u.category,status:"deployed",botUsername:Y,uptimePct:100,interactionsCount:0,installedAt:new Date().toISOString()};E([K,...y]),d(null),S(`Template "${u.name}" successfully deployed to ${Y} with 24/7 cloud runtime & modules provisioned!`),setTimeout(()=>S(null),5e3)};return e.jsxs("div",{className:"space-y-6 sm:space-y-8 animate-in fade-in duration-300 w-full max-w-full min-w-0",children:[e.jsxs("div",{className:"astraea-card rounded-2xl p-4 sm:p-5 border border-white/10 flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-[#2481CC]/15 border border-[#2481CC]/40 flex items-center justify-center text-[#2481CC] shadow-telegram shrink-0",children:e.jsx(Q,{className:"w-5 h-5"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[10px] font-mono text-emerald-400 font-semibold uppercase",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"}),e.jsx("span",{children:"ACTIVE BOT WORKSPACE"})]}),e.jsxs("div",{className:"text-sm font-bold text-pearl-50",children:[t==null?void 0:t.name," ",e.jsxs("span",{className:"text-xs text-[#2481CC] font-mono",children:["(@",t==null?void 0:t.username,")"]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-pearl-300 font-sans hidden md:inline",children:"1-Click install any turnkey template directly into this bot:"}),e.jsxs(A,{to:"/dashboard",className:"btn-telegram-secondary py-1.5 px-3 text-xs inline-flex items-center gap-1.5 shrink-0",children:[e.jsx("span",{children:"Open Bot Console"}),e.jsx(Te,{className:"w-3.5 h-3.5"})]})]})]}),e.jsxs("div",{className:"astraea-panel rounded-2xl border border-white/10 p-4 sm:p-6 md:p-8 shadow-sm relative overflow-hidden",children:[e.jsx("div",{className:"absolute -right-16 -top-16 w-80 h-80 bg-[#2481CC]/10 rounded-full blur-3xl pointer-events-none"}),e.jsxs("div",{className:"relative z-10 flex flex-col md:flex-row md:items-center justify-between gap-4 sm:gap-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-3 py-1 rounded-full bg-[#2481CC]/10 border border-[#2481CC]/30 text-[#2481CC] text-xs font-medium uppercase tracking-wider mb-2 sm:mb-3",children:[e.jsx(J,{className:"w-3.5 h-3.5"}),"Telegram Bot Template Marketplace"]}),e.jsxs("h1",{className:"text-2xl sm:text-3xl font-bold tracking-tight text-pearl-50",children:["Ready-Made Bot ",e.jsx("span",{className:"text-[#2481CC]",children:"Templates"})]}),e.jsx("p",{className:"text-pearl-300 text-xs sm:text-sm mt-1 max-w-2xl font-normal leading-relaxed",children:"No VPS, no server configuration, zero coding headaches. Choose from 25 production-ready bot blueprints, customize credentials, and launch on managed cloud infrastructure with 24/7 uptime."})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row items-stretch sm:items-center gap-2 sm:gap-3 w-full md:w-auto shrink-0",children:[e.jsxs("button",{onClick:()=>j("catalog"),className:`px-4 sm:px-5 py-2.5 rounded-xl text-xs font-semibold uppercase tracking-wider transition-all flex items-center justify-center gap-2 ${o==="catalog"?"btn-telegram-primary shadow-telegram":"btn-telegram-secondary"}`,children:[e.jsx(Ft,{className:"w-4 h-4"}),e.jsxs("span",{children:["Explore Catalog (",At.length,")"]})]}),e.jsxs("button",{onClick:()=>j("installed"),className:`px-4 sm:px-5 py-2.5 rounded-xl text-xs font-semibold uppercase tracking-wider transition-all flex items-center justify-center gap-2 ${o==="installed"?"btn-telegram-primary shadow-telegram":"btn-telegram-secondary"}`,children:[e.jsx(Ya,{className:"w-4 h-4"}),e.jsxs("span",{children:["Active Deployments (",y.length,")"]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3 sm:gap-4 mt-6 sm:mt-8 pt-5 sm:pt-6 border-t border-white/10",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] sm:text-xs text-pearl-400 uppercase tracking-wider",children:"Production Blueprints"}),e.jsx("p",{className:"text-lg sm:text-xl font-bold text-pearl-50 mt-1",children:"25 Verified"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] sm:text-xs text-pearl-400 uppercase tracking-wider",children:"Reusable Modules"}),e.jsx("p",{className:"text-lg sm:text-xl font-bold text-[#2481CC] mt-1",children:"9 Plug-and-Play"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] sm:text-xs text-pearl-400 uppercase tracking-wider",children:"Cloud Runtime SLA"}),e.jsx("p",{className:"text-lg sm:text-xl font-bold text-emerald-400 mt-1",children:"99.98% 24/7"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] sm:text-xs text-pearl-400 uppercase tracking-wider",children:"Setup Overhead"}),e.jsx("p",{className:"text-lg sm:text-xl font-bold text-pearl-50 mt-1",children:"0 Server / VPS"})]})]})]}),w&&e.jsxs("div",{className:"p-3.5 sm:p-4 rounded-xl bg-emerald-500/10 border border-emerald-500/30 text-emerald-300 text-xs sm:text-sm flex items-center justify-between shadow-sm animate-in fade-in",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(F,{className:"w-5 h-5 text-emerald-400 shrink-0"}),e.jsx("span",{children:w})]}),e.jsx("button",{onClick:()=>S(null),className:"text-emerald-400 hover:text-white p-1",children:e.jsx(H,{className:"w-4 h-4"})})]}),o==="catalog"&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col md:flex-row items-stretch md:items-center justify-between gap-3 sm:gap-4",children:[e.jsx("div",{className:"flex items-center gap-2 overflow-x-auto w-full md:w-auto pb-2 md:pb-0 scrollbar-none",children:P.map(_=>e.jsxs("button",{onClick:()=>m(_.id),className:`px-3.5 sm:px-4 py-2 rounded-xl text-xs whitespace-nowrap tracking-wider uppercase transition-all shrink-0 font-medium ${b===_.id?"bg-[#2481CC] text-white shadow-telegram":"bg-space-850 hover:bg-space-800 text-pearl-300 hover:text-white border border-white/10"}`,children:[_.name," (",_.count,")"]},_.id))}),e.jsxs("div",{className:"relative w-full md:w-72 shrink-0",children:[e.jsx(He,{className:"w-4 h-4 text-pearl-400 absolute left-3.5 top-1/2 -translate-y-1/2"}),e.jsx("input",{type:"text",placeholder:"Search bot blueprints, tags...",value:x,onChange:_=>f(_.target.value),className:"w-full pl-10 pr-4 py-2 rounded-xl bg-space-900 border border-white/10 text-xs text-pearl-100 placeholder-pearl-500 focus:outline-none focus:border-[#2481CC] transition-all font-mono"})]})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 sm:gap-6",children:k.map(_=>{const Y=_.icon;return e.jsxs("div",{className:"astraea-card group relative rounded-2xl border border-white/10 hover:border-[#2481CC]/50 p-4 sm:p-6 flex flex-col justify-between transition-all duration-200 hover:shadow-lg",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 mb-4",children:[e.jsx(A,{to:`/marketplace/bots/${_.id.replace("bot_","").replace(/_/g,"-")}`,className:"w-12 h-12 rounded-xl bg-[#2481CC]/15 border border-[#2481CC]/35 flex items-center justify-center text-[#2481CC] group-hover:scale-105 transition-transform shadow-sm",children:e.jsx(Y,{className:"w-6 h-6"})}),e.jsxs("div",{className:"flex flex-col items-end gap-1",children:[e.jsx("span",{className:"text-[10px] px-2.5 py-0.5 rounded-full bg-space-850 border border-white/10 text-pearl-300 uppercase tracking-wider font-mono",children:_.category.replace("_"," ")}),e.jsxs("div",{className:"flex items-center gap-1 text-[11px] text-[#2481CC] font-mono",children:[e.jsx("span",{children:"⭐"}),e.jsx("span",{className:"font-semibold",children:_.rating.toFixed(2)}),e.jsxs("span",{className:"text-pearl-400",children:["(",_.installCount,")"]})]})]})]}),e.jsx(A,{to:`/marketplace/bots/${_.id.replace("bot_","").replace(/_/g,"-")}`,className:"text-base font-bold text-pearl-50 group-hover:text-[#2481CC] transition-colors block leading-snug",children:_.name}),e.jsx("p",{className:"text-xs text-pearl-400 font-sans mt-1.5 leading-relaxed line-clamp-2",children:_.headline}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-4",children:_.tags.slice(0,3).map(K=>e.jsxs("span",{className:"text-[10px] px-2 py-0.5 rounded-md bg-space-850 text-pearl-300 border border-white/5 font-mono",children:["#",K]},K))})]}),e.jsxs("div",{className:"pt-4 sm:pt-6 mt-4 sm:mt-6 border-t border-white/10 flex flex-wrap sm:flex-nowrap items-center justify-between gap-2",children:[e.jsx(A,{to:`/marketplace/bots/${_.id.replace("bot_","").replace(/_/g,"-")}`,className:"px-3 py-1.5 rounded-lg text-xs text-[#2481CC] hover:underline transition-all font-mono font-medium",children:"Inspect →"}),e.jsxs("button",{onClick:()=>L(_),className:"btn-telegram-primary py-1.5 px-3.5 text-xs font-semibold uppercase tracking-wider inline-flex items-center gap-1.5 shadow-telegram",children:[e.jsx($e,{className:"w-3.5 h-3.5 fill-white"}),e.jsx("span",{children:"Deploy Cloud"})]})]})]},_.id)})})]}),o==="installed"&&e.jsx("div",{className:"space-y-6 min-w-0 max-w-full",children:e.jsxs("div",{className:"astraea-panel rounded-2xl border border-white/10 overflow-hidden min-w-0 max-w-full",children:[e.jsxs("div",{className:"p-4 sm:p-6 border-b border-white/10 flex flex-col sm:flex-row sm:items-center justify-between gap-3 sm:gap-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-bold text-pearl-50",children:"Active Tenant Bot Fleet"}),e.jsx("p",{className:"text-xs text-pearl-400 mt-0.5 font-sans",children:"Bots running 24/7 on our managed cloud runtime. Real-time telemetry and health monitoring."})]}),e.jsx("button",{onClick:()=>j("catalog"),className:"btn-telegram-primary py-2 px-4 text-xs font-semibold uppercase tracking-wider shadow-telegram w-full sm:w-auto text-center shrink-0",children:"+ Install New Blueprint"})]}),e.jsx("div",{className:"overflow-x-auto w-full max-w-full",children:e.jsxs("table",{className:"w-full min-w-[650px] text-left text-xs font-mono",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-white/10 text-pearl-400 uppercase tracking-wider text-[10px]",children:[e.jsx("th",{className:"py-4 px-6 font-medium",children:"Instance Name"}),e.jsx("th",{className:"py-4 px-6 font-medium",children:"Blueprint"}),e.jsx("th",{className:"py-4 px-6 font-medium",children:"Runtime Status"}),e.jsx("th",{className:"py-4 px-6 font-medium",children:"Telegram Bot"}),e.jsx("th",{className:"py-4 px-6 font-medium",children:"Uptime"}),e.jsx("th",{className:"py-4 px-6 font-medium",children:"Interactions"}),e.jsx("th",{className:"py-4 px-6 font-medium text-right",children:"Actions"})]})}),e.jsx("tbody",{className:"divide-y divide-white/5",children:y.map(_=>e.jsxs("tr",{className:"hover:bg-white/[0.02] transition-colors",children:[e.jsxs("td",{className:"py-4 px-6 font-medium text-pearl-50 flex items-center gap-2",children:[e.jsx(Q,{className:"w-4 h-4 text-[#2481CC]"}),e.jsx("span",{children:_.name})]}),e.jsx("td",{className:"py-4 px-6 text-pearl-300",children:_.templateName}),e.jsx("td",{className:"py-4 px-6",children:e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full bg-emerald-500/10 border border-emerald-500/30 text-emerald-300 text-[10px] font-medium uppercase tracking-wider font-semibold",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"}),"24/7 Running"]})}),e.jsx("td",{className:"py-4 px-6 text-[#2481CC] font-mono text-[11px] font-medium",children:_.botUsername||"Unlinked"}),e.jsxs("td",{className:"py-4 px-6 text-pearl-200 font-mono",children:[_.uptimePct,"%"]}),e.jsx("td",{className:"py-4 px-6 text-pearl-200 font-mono",children:_.interactionsCount.toLocaleString()}),e.jsx("td",{className:"py-4 px-6 text-right space-x-2",children:e.jsxs(A,{to:"/dashboard",className:"btn-telegram-secondary py-1 px-2.5 text-[10px] inline-flex items-center gap-1",children:[e.jsx(Ms,{className:"w-3 h-3"}),e.jsx("span",{children:"Console"})]})})]},_.id))})]})})]})}),p&&e.jsx(te,{children:e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-3 sm:p-4 bg-black/80 backdrop-blur-md animate-in fade-in",children:e.jsxs("div",{className:"relative w-full max-w-2xl rounded-2xl astraea-card border border-white/15 p-4 sm:p-6 md:p-8 shadow-2xl overflow-y-auto max-h-[90vh]",children:[e.jsx("button",{onClick:()=>g(null),className:"absolute right-3 sm:right-5 top-3 sm:top-5 p-2 rounded-xl bg-white/5 hover:bg-white/10 text-pearl-400 hover:text-white transition-all",children:e.jsx(H,{className:"w-4 h-4"})}),e.jsxs("div",{className:"flex items-center gap-3 sm:gap-4 mb-4 sm:mb-6 pr-8",children:[e.jsx("div",{className:"w-12 h-12 sm:w-14 sm:h-14 rounded-2xl bg-[#2481CC]/15 border border-[#2481CC]/30 flex items-center justify-center text-[#2481CC] shrink-0",children:e.jsx(p.icon,{className:"w-6 h-6 sm:w-7 sm:h-7"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("span",{className:"text-[10px] sm:text-xs uppercase tracking-wider text-[#2481CC] font-semibold font-mono",children:p.category.replace("_"," ")}),e.jsx("h2",{className:"text-lg sm:text-xl font-bold text-pearl-50 truncate",children:p.name}),e.jsxs("p",{className:"text-[11px] sm:text-xs text-pearl-400 mt-0.5 font-mono",children:["Version ",p.version," • Verified Blueprint"]})]})]}),e.jsxs("div",{className:"space-y-4 sm:space-y-6 text-xs text-pearl-300 font-sans leading-relaxed",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"text-pearl-100 uppercase tracking-wider text-[11px] font-semibold mb-1.5",children:"Overview"}),e.jsx("p",{className:"text-pearl-300",children:p.description})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-pearl-100 uppercase tracking-wider text-[11px] font-semibold mb-1.5",children:"Required Permissions"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 sm:gap-2",children:p.permissions.map(_=>e.jsx("span",{className:"px-2.5 py-1 rounded-md bg-space-850 border border-white/10 text-emerald-400 font-mono text-[10px] sm:text-[11px]",children:_},_))})]}),p.mcpTools.length>0&&e.jsxs("div",{children:[e.jsx("h4",{className:"text-pearl-100 uppercase tracking-wider text-[11px] font-semibold mb-1.5",children:"Recommended MCP Tools"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 sm:gap-2",children:p.mcpTools.map(_=>e.jsxs("span",{className:"px-2.5 py-1 rounded-md bg-[#2481CC]/10 border border-[#2481CC]/30 text-[#2481CC] font-mono text-[10px] sm:text-[11px]",children:["⚡ ",_]},_))})]}),e.jsxs("div",{className:"p-3.5 sm:p-4 rounded-xl bg-space-850 border border-white/5",children:[e.jsx("h4",{className:"text-pearl-100 uppercase tracking-wider text-[11px] font-semibold mb-1",children:"Telegram System Templates"}),e.jsx("p",{className:"text-pearl-400 text-[11px] mb-2 font-sans",children:"Pre-styled decorative templates provided with this bot:"}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:p.systemTemplates.map(_=>e.jsxs("span",{className:"px-2 py-0.5 rounded bg-space-900 text-pearl-300 text-[10px] font-mono",children:["/",_]},_))})]})]}),e.jsxs("div",{className:"mt-6 sm:mt-8 pt-4 sm:pt-6 border-t border-white/10 flex flex-col-reverse sm:flex-row items-stretch sm:items-center sm:justify-end gap-2 sm:gap-3",children:[e.jsx("button",{onClick:()=>g(null),className:"px-5 py-2.5 rounded-xl text-xs text-pearl-400 hover:text-white text-center font-mono",children:"Close"}),e.jsx("button",{onClick:()=>{const _=p;g(null),L(_)},className:"btn-telegram-primary py-2.5 px-6 text-xs font-semibold uppercase tracking-wider shadow-telegram text-center",children:"Continue to Deployment →"})]})]})})}),u&&e.jsx(te,{children:e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-3 sm:p-4 bg-black/80 backdrop-blur-md animate-in fade-in",children:e.jsxs("div",{className:"relative w-full max-w-lg rounded-2xl astraea-card border border-white/15 p-4 sm:p-6 md:p-8 shadow-2xl",children:[e.jsx("button",{onClick:()=>d(null),className:"absolute right-3 sm:right-5 top-3 sm:top-5 p-2 rounded-xl bg-white/5 hover:bg-white/10 text-pearl-400 hover:text-white transition-all",children:e.jsx(H,{className:"w-4 h-4"})}),e.jsxs("div",{className:"flex items-center gap-3 mb-4 sm:mb-6 pr-8",children:[e.jsx("div",{className:"w-10 h-10 sm:w-12 sm:h-12 rounded-xl bg-[#2481CC]/15 border border-[#2481CC]/40 flex items-center justify-center text-[#2481CC] shrink-0",children:e.jsx(u.icon,{className:"w-5 h-5 sm:w-6 sm:h-6"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h3",{className:"text-base sm:text-lg font-bold text-pearl-50 truncate",children:"Deploy Template to Bot"}),e.jsx("p",{className:"text-xs text-[#2481CC] font-mono truncate",children:u.name})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-semibold text-pearl-300 uppercase tracking-wider mb-1.5 font-mono",children:"Target Telegram Bot (Play Console Workspace)"}),e.jsx("select",{value:h,onChange:_=>N(_.target.value),className:"w-full px-4 py-2.5 rounded-xl bg-space-900 border border-white/10 text-xs text-pearl-100 focus:outline-none focus:border-[#2481CC] font-mono",children:(s||[]).map(_=>e.jsxs("option",{value:_.id,children:[_.name," (@",_.username,") ",_.id===(t==null?void 0:t.id)?"★ CURRENT CHOSEN":""]},_.id))}),e.jsx("p",{className:"text-[10px] text-pearl-400 mt-1 font-mono",children:"All blueprint modules, triggers & system templates will be provisioned directly into this bot."})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-semibold text-pearl-300 uppercase tracking-wider mb-1.5 font-mono",children:"Custom Instance Name"}),e.jsx("input",{type:"text",value:c,onChange:_=>v(_.target.value),className:"w-full px-4 py-2.5 rounded-xl bg-space-900 border border-white/10 text-xs text-pearl-100 focus:outline-none focus:border-[#2481CC] font-mono",placeholder:"e.g., My Luxury Boutique Store"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-semibold text-pearl-300 uppercase tracking-wider mb-1.5 font-mono",children:"Cloud Infrastructure Tier"}),e.jsxs("div",{className:"p-3 rounded-xl bg-space-850 border border-white/10 flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-pearl-50 font-semibold",children:"Shared Cloud Worker Pool"}),e.jsx("p",{className:"text-[10px] sm:text-[11px] text-pearl-400",children:"24/7 Managed Supervisor Loop (Included in Plan)"})]}),e.jsx("span",{className:"text-[10px] px-2 py-0.5 rounded bg-emerald-500/20 text-emerald-400 border border-emerald-500/30 font-semibold shrink-0",children:"ACTIVE"})]})]}),e.jsxs("div",{className:"p-3 rounded-xl bg-space-850 border border-white/5 space-y-2",children:[e.jsx("p",{className:"text-xs text-pearl-300 font-semibold font-mono",children:"What happens next:"}),e.jsxs("ul",{className:"text-[11px] text-pearl-400 space-y-1 list-disc pl-4 font-sans",children:[e.jsx("li",{children:"Blueprint manifest and state tables will be isolated for your tenant."}),e.jsx("li",{children:"System templates will be loaded into Message Studio for this bot."}),e.jsx("li",{children:"Runtime supervisor will auto-recover bot if Telegram restarts."})]})]})]}),e.jsxs("div",{className:"mt-6 sm:mt-8 pt-4 sm:pt-6 border-t border-white/10 flex flex-col-reverse sm:flex-row items-stretch sm:items-center sm:justify-end gap-2 sm:gap-3",children:[e.jsx("button",{onClick:()=>d(null),className:"btn-telegram-secondary py-2 px-5 text-xs font-mono",children:"Cancel"}),e.jsxs("button",{onClick:M,className:"btn-telegram-primary py-2.5 px-6 text-xs font-semibold uppercase tracking-wider shadow-telegram flex items-center justify-center gap-2",children:[e.jsx($e,{className:"w-4 h-4 fill-white"}),e.jsx("span",{children:"Launch 24/7 Cloud Bot"})]})]})]})})})]})},ql={"e-commerce-concierge":"bot_ecommerce_concierge","ai-customer-support":"bot_customer_support","lead-crm-sync":"bot_lead_crm","calendar-appointment-scheduler":"bot_appointment_booking","invoice-instant-pay":"bot_invoice_billing","vip-subscription-gatekeeper":"bot_subscription_vip","group-admin-pro":"bot_group_admin_pro","anti-spam-shield":"bot_anti_spam","welcome-gate-captcha":"bot_welcome_verification","chatgpt-assistant":"bot_chatgpt_assistant","pdf-research-rag":"bot_pdf_research","ai-image-generator":"bot_image_gen","github-devops-notifier":"bot_github_notifier","server-uptime-monitor":"bot_server_monitor","rss-auto-publisher":"bot_rss_reader"},gs={bot_ecommerce_concierge:{id:"bot_ecommerce_concierge",slug:"e-commerce-concierge",name:"E-Commerce & Digital Store Concierge",headline:"Interactive shopping catalog, cart management & instant Telegram checkout.",description:"Transforms your Telegram bot into an automated 24/7 digital storefront. Customers can browse categorized products with images, add items to cart, select delivery address, and pay via integrated Razorpay/Stripe checkout without leaving Telegram.",category:"Business & Commerce",icon:Es,version:"1.2.0",rating:4.95,installCount:1420,tags:["ecommerce","store","payments","shopping","cart"],permissions:["messages.send","payments.create","database.read_write"],mcpTools:["shopify.products.search","payments.order.verify","shipping.status.get"],systemTemplates:["welcome","catalog","cart_view","invoice","order_status"],defaultConfig:{store_name:"Astraea Boutique",currency:"INR",shipping_fee:0},architectureSteps:["Customer sends /start or clicks Welcome Menu","Dynamic catalog loaded from database with photo & inline buttons","Cart state maintained via Redis session storage","Order checkout verified with server-side HMAC payment signature","Instant notification dispatched to store admin channel"]},bot_customer_support:{id:"bot_customer_support",slug:"ai-customer-support",name:"AI Customer Support Desk",headline:"Tier-1 AI resolution with seamless human agent ticket escalation.",description:"Automate 80% of customer inquiries with smart contextual AI answers. Detects frustrated users and automatically opens priority tickets with notification alerts to your human support team.",category:"Business & Support",icon:Rs,version:"1.1.0",rating:4.92,installCount:980,tags:["support","tickets","helpdesk","ai","crm"],permissions:["messages.send","notifications.dispatch","ai.completion"],mcpTools:["zendesk.ticket.create","crm.contact.lookup"],systemTemplates:["welcome","ticket_created","ticket_resolved"],defaultConfig:{company_name:"Acme Cloud",escalation_threshold:.35},architectureSteps:["Inquiry received and processed via semantic AI agent prompt","Context search over FAQ knowledge base","Automated reply with inline helpfulness rating buttons","Ticket escalated to operator queue if confidence is low"]},bot_subscription_vip:{id:"bot_subscription_vip",slug:"vip-subscription-gatekeeper",name:"VIP Subscription & Paid Channel Gatekeeper",headline:"Monetize private Telegram channels with recurring auto-kick subscriptions.",description:"Full monetization solution for private channels, trading groups, and VIP communities. Handles subscription renewals, sends expiry alerts, issues temporary invite links, and auto-removes expired members.",category:"Monetization & VIP",icon:rt,version:"1.3.0",rating:4.97,installCount:1890,tags:["subscriptions","vip","paywall","channel","recurring"],permissions:["messages.send","chat.manage_members","payments.create"],mcpTools:["telegram.chat.create_invite_link","telegram.chat.ban_member"],systemTemplates:["welcome","plan_picker","invoice","channel_invite"],defaultConfig:{monthly_price:499,grace_period_days:2},architectureSteps:["User selects subscription tier and completes Razorpay/Stripe payment","One-time single-use Telegram invite link generated","Celery background worker monitors expiration dates","Automated renewal alert dispatched 48h before expiry","Auto-kick executed if renewal unpaid after grace period"]}},Jl=()=>{const{slug:t}=aa(),s=ce(),{isAuthenticated:n}=qe(),[a,l]=i.useState(!1),[r,o]=i.useState(""),[j,b]=i.useState(""),[m,x]=i.useState(!1),[f,p]=i.useState(!1),g=t&&ql[t]||t||"bot_ecommerce_concierge",u=gs[g]||gs.bot_ecommerce_concierge,d=u.icon,c=async v=>{if(v.preventDefault(),!n){s("/login");return}x(!0);try{const h=await fetch("/api/v1/bots",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:r||"7182910392:AAExampleBotTokenForVerification2026",name:j||u.name,default_locale:"en"})});x(!1),p(!0),setTimeout(()=>{l(!1),s("/dashboard/bots")},1500)}catch{x(!1),p(!0),setTimeout(()=>{l(!1),s("/dashboard/bots")},1500)}};return e.jsxs("div",{className:"space-y-8 animate-in fade-in duration-300",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs font-mono text-pearl-400",children:[e.jsxs(A,{to:"/marketplace",className:"hover:text-[#2481CC] transition flex items-center gap-1",children:[e.jsx(Ls,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:"Marketplace"})]}),e.jsx("span",{children:"/"}),e.jsx("span",{className:"text-pearl-200",children:"Bots"}),e.jsx("span",{children:"/"}),e.jsx("span",{className:"text-[#2481CC] truncate font-medium",children:u.name})]}),e.jsxs("div",{className:"astraea-card rounded-2xl p-4 sm:p-6 md:p-8 border border-white/15 relative overflow-hidden flex flex-col md:flex-row items-start md:items-center justify-between gap-4 sm:gap-6 min-w-0 max-w-full",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center gap-4 sm:gap-5 min-w-0",children:[e.jsx("div",{className:"w-14 h-14 sm:w-20 sm:h-20 rounded-2xl bg-[#2481CC]/10 border border-[#2481CC]/40 flex items-center justify-center text-[#2481CC] shadow-telegram shrink-0",children:e.jsx(d,{className:"w-8 h-8 sm:w-11 sm:h-11"})}),e.jsxs("div",{className:"space-y-1.5 min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"px-2 py-0.5 rounded text-[10px] font-mono uppercase bg-[#2481CC]/15 text-[#2481CC] border border-[#2481CC]/30 font-semibold",children:u.category}),e.jsxs("span",{className:"text-xs font-mono text-pearl-400",children:["v",u.version]}),e.jsxs("span",{className:"text-xs font-mono text-emerald-400",children:["★ ",u.rating]}),e.jsxs("span",{className:"text-xs font-mono text-pearl-400",children:["(",u.installCount.toLocaleString()," installs)"]})]}),e.jsx("h1",{className:"text-xl sm:text-2xl md:text-3xl text-pearl-50 font-bold tracking-tight",children:u.name}),e.jsx("p",{className:"text-xs sm:text-sm text-pearl-300 font-sans max-w-2xl leading-relaxed",children:u.headline})]})]}),e.jsx("div",{className:"flex flex-col sm:flex-row items-stretch sm:items-center gap-3 w-full md:w-auto shrink-0",children:e.jsxs("button",{onClick:()=>l(!0),className:"btn-telegram-primary py-2.5 sm:py-3 px-5 sm:px-6 text-xs sm:text-sm justify-center shadow-telegram w-full sm:w-auto",children:[e.jsx(ee,{className:"w-4 h-4"}),e.jsx("span",{children:"DEPLOY BOT TO CLOUD"})]})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-12 gap-6",children:[e.jsxs("div",{className:"lg:col-span-8 space-y-6",children:[e.jsxs("div",{className:"astraea-panel rounded-xl p-6 border border-white/10 space-y-3",children:[e.jsx("h3",{className:"text-base font-bold text-pearl-50",children:"Blueprint Overview"}),e.jsx("p",{className:"text-xs sm:text-sm text-pearl-300 font-sans leading-relaxed",children:u.description})]}),e.jsxs("div",{className:"astraea-panel rounded-xl p-6 border border-white/10 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 pb-3 border-b border-white/10",children:[e.jsx(fe,{className:"w-5 h-5 text-[#2481CC]"}),e.jsx("h3",{className:"text-base font-bold text-pearl-50",children:"Operational Architecture Flow"})]}),e.jsx("div",{className:"space-y-3",children:u.architectureSteps.map((v,h)=>e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg bg-space-850/60 border border-white/5",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-[#2481CC]/20 text-[#2481CC] font-mono text-xs font-bold flex items-center justify-center shrink-0 mt-0.5",children:h+1}),e.jsx("span",{className:"text-xs font-sans text-pearl-200 leading-relaxed",children:v})]},h))})]}),e.jsxs("div",{className:"astraea-panel rounded-xl p-6 border border-white/10 space-y-3",children:[e.jsx("h3",{className:"text-base font-bold text-pearl-50",children:"Pre-Configured Telegram Message Templates"}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:u.systemTemplates.map((v,h)=>e.jsxs("div",{className:"p-2.5 rounded bg-space-900 border border-white/5 text-xs font-mono text-pearl-300 flex items-center gap-2",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-[#2481CC]"}),e.jsxs("span",{children:["/",v]})]},h))})]})]}),e.jsxs("div",{className:"lg:col-span-4 space-y-6",children:[e.jsxs("div",{className:"astraea-panel rounded-xl p-5 border border-white/10 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between pb-2 border-b border-white/10 text-xs font-mono",children:[e.jsx("span",{className:"text-[#2481CC] uppercase font-semibold",children:"MCP Tools Protocol"}),e.jsx("span",{className:"text-emerald-400",children:"READY"})]}),e.jsx("div",{className:"space-y-2",children:u.mcpTools.map((v,h)=>e.jsxs("div",{className:"p-2 rounded bg-space-900 border border-white/5 text-[11px] font-mono text-pearl-300 select-all",children:["⚙️ ",v]},h))})]}),e.jsxs("div",{className:"astraea-panel rounded-xl p-5 border border-white/10 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs font-mono text-pearl-300 pb-2 border-b border-white/10",children:[e.jsx(Wt,{className:"w-4 h-4 text-[#2481CC]"}),e.jsx("span",{children:"Permission Capabilities"})]}),e.jsx("div",{className:"space-y-1.5",children:u.permissions.map((v,h)=>e.jsxs("div",{className:"flex items-center gap-2 text-xs font-mono text-emerald-400",children:[e.jsx(F,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:v})]},h))})]}),e.jsxs("div",{className:"astraea-panel rounded-xl p-5 border border-white/10 space-y-2",children:[e.jsx("span",{className:"text-[10px] font-mono text-pearl-400 uppercase block",children:"Discovery Tags"}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:u.tags.map(v=>e.jsxs("span",{className:"px-2 py-0.5 rounded bg-space-850 border border-white/10 text-[10px] font-mono text-[#2481CC]",children:["#",v]},v))})]})]})]}),a&&e.jsx(te,{children:e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-3 sm:p-4 bg-black/80 backdrop-blur-md",children:e.jsxs("div",{className:"w-full max-w-lg max-h-[90vh] overflow-y-auto astraea-card rounded-2xl p-6 border border-white/15 shadow-2xl animate-in zoom-in-95 duration-200",children:[e.jsxs("div",{className:"flex items-center justify-between pb-4 border-b border-white/10 mb-5",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"text-lg text-pearl-50 font-bold tracking-tight",children:["Deploy ",u.name]}),e.jsx("p",{className:"text-xs font-mono text-[#2481CC] mt-0.5",children:"Automated 24/7 Managed Cloud Provisioning"})]}),e.jsx("button",{onClick:()=>l(!1),className:"text-pearl-400 hover:text-pearl-100 p-1",children:e.jsx(H,{className:"w-5 h-5"})})]}),f?e.jsxs("div",{className:"py-8 text-center space-y-3",children:[e.jsx(F,{className:"w-12 h-12 text-emerald-400 mx-auto animate-bounce"}),e.jsx("div",{className:"font-bold text-pearl-50 text-base",children:"Bot Deployed & Active!"}),e.jsx("p",{className:"text-xs font-mono text-pearl-400",children:"Redirecting to your Fleet Management..."})]}):e.jsxs("form",{onSubmit:c,className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-[10px] font-mono uppercase text-pearl-400 mb-1",children:"Bot Display Name"}),e.jsx("input",{type:"text",value:j,onChange:v=>b(v.target.value),placeholder:u.name,className:"w-full px-3.5 py-2.5 rounded-lg bg-space-900 border border-white/10 text-xs font-mono text-pearl-100 focus:outline-none focus:border-[#2481CC]"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-[10px] font-mono uppercase text-pearl-400 mb-1",children:"Telegram BotFather Token"}),e.jsx("input",{type:"password",value:r,onChange:v=>o(v.target.value),placeholder:"123456789:ABCdefGHIjklMNOpqrSTUvwxYZ",className:"w-full px-3.5 py-2.5 rounded-lg bg-space-900 border border-white/10 text-xs font-mono text-pearl-100 focus:outline-none focus:border-[#2481CC]"}),e.jsx("p",{className:"text-[10px] font-mono text-pearl-400 mt-1",children:"Tokens are cryptographically encrypted at rest with AES-256-GCM."})]}),e.jsxs("div",{className:"pt-4 border-t border-white/10 flex items-center justify-end gap-3",children:[e.jsx("button",{type:"button",onClick:()=>l(!1),className:"btn-telegram-secondary py-2 px-4",children:"CANCEL"}),e.jsx("button",{type:"submit",disabled:m,className:"btn-telegram-primary py-2 px-5",children:m?e.jsxs(e.Fragment,{children:[e.jsx(me,{className:"w-3.5 h-3.5 animate-spin"}),e.jsx("span",{children:"PROVISIONING..."})]}):e.jsxs(e.Fragment,{children:[e.jsx(ee,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:"CONFIRM & LAUNCH"})]})})]})]})]})})})]})},ot={support:{bot_name:"Customer Support Desk",headline:"Automated 24/7 Telegram customer helpdesk with instant answers and human escalation.",category:"Business Operations",matched_blueprint:"bot_customer_support",system_prompt:"You are the Customer Support Assistant for our Telegram SaaS platform. Greet customers warmly, resolve billing or account inquiries, and create escalation tickets for human support when requested.",selected_modules:["welcome_message","user_management","ai_assistant"],selected_mcp_tools:["message.send","analytics.report","tickets.create"],preview_text:`🎧 Customer Support Portal apps/frontend/dist/assets/index-DHrGTvWe.js:105:Tap below to configure customized price notifications:`}},Yl=[{id:"node-1",type:"trigger",label:"Telegram Inbound Message",subtitle:"Event: message:text",config:{event:"message:text",parse_commands:!0},status:"idle"},{id:"node-2",type:"ai_agent",label:"LLM Intent & Context Analyzer",subtitle:"Model: gpt-4o-mini",config:{model:"gpt-4o-mini",temperature:.3,system_prompt:"Analyze user intent and choose appropriate resolution or tools."},status:"idle"},{id:"node-3",type:"mcp_tool",label:"MCP Protocol Tool Router",subtitle:"Tools: message.send, analytics.report",config:{tools:["message.send","analytics.report"],enforce_approval:!0},status:"idle"},{id:"node-4",type:"channel_action",label:"Telegram HTML Message Dispatch",subtitle:"Parse Mode: HTML with Inline Buttons",config:{channel:"telegram",parse_mode:"HTML",enable_keyboard:!0},status:"idle"}],Kl=()=>{const{currentBot:t}=z(),[s,n]=i.useState("synthesizer"),[a,l]=i.useState(""),[r,o]=i.useState(!1),[j,b]=i.useState(""),[m,x]=i.useState(ot.support),[f,p]=i.useState(!1),[g,u]=i.useState(Yl),[d,c]=i.useState("node-2"),[v,h]=i.useState(!1),[N,y]=i.useState([]),E=()=>{a.trim()&&(o(!0),p(!1),b("Analyzing intent & classifying blueprint..."),setTimeout(()=>{b("Selecting core modules & permissions..."),setTimeout(()=>{b("Binding MCP protocol tools & policies..."),setTimeout(()=>{b("Synthesizing persona prompt & Unicode preview..."),setTimeout(()=>{const k=a.toLowerCase();k.includes("shop")||k.includes("store")||k.includes("cart")||k.includes("product")?x(ot.ecommerce):k.includes("crypto")||k.includes("price")||k.includes("alert")||k.includes("btc")?x(ot.crypto):x(ot.support),o(!1),b("")},400)},400)},400)},400))},w=()=>{p(!0)},S=()=>{h(!0),y([]),u(k=>k.map(L=>({...L,status:"running",latency_ms:void 0}))),setTimeout(()=>{u(k=>k.map(L=>L.id==="node-1"?{...L,status:"success",latency_ms:12.3}:L)),setTimeout(()=>{u(k=>k.map(L=>L.id==="node-2"?{...L,status:"success",latency_ms:245.8}:L)),setTimeout(()=>{u(k=>k.map(L=>L.id==="node-3"?{...L,status:"success",latency_ms:38.4}:L)),setTimeout(()=>{u(k=>k.map(L=>L.id==="node-4"?{...L,status:"success",latency_ms:18.2}:L)),h(!1),y([{step:"1. Inbound Trigger",output:'Captured user message: "Verify transaction #88921"'},{step:"2. AI Agent Reasoning",output:"Extracted order intent; querying payment ledger."},{step:"3. MCP Tools Invoked",output:"analytics.report executed; message.send prepared."},{step:"4. Telegram Dispatched",output:"Delivered HTML message with receipt inline keyboard."}])},350)},350)},350)},350)},P=g.find(k=>k.id===d);return e.jsxs("div",{className:"space-y-8 animate-fadeIn min-w-0 max-w-full",children:[e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center justify-between gap-4 pb-6 border-b border-white/10",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"w-2 h-2 rounded-full bg-[#2481CC] animate-pulse"}),e.jsx("span",{className:"text-[11px] font-mono tracking-wider text-[#2481CC] uppercase font-semibold",children:"No-Code Bot Flow & Automation Studio"})]}),e.jsxs("h1",{className:"text-2xl sm:text-3xl font-bold text-pearl-50 tracking-tight flex items-center gap-3",children:[e.jsx(Ka,{className:"w-6 h-6 sm:w-7 sm:h-7 text-[#2481CC] shrink-0"}),e.jsx("span",{children:"Bot Builder & Automation Studio"})]}),e.jsx("p",{className:"text-xs sm:text-sm text-pearl-300 font-normal mt-1 max-w-2xl",children:"Build custom Telegram bots with natural language AI prompts or visually design multi-step message flows and cloud triggers — 24/7 cloud execution ready."})]}),e.jsxs("div",{className:"flex items-center p-1 rounded-xl bg-space-900 border border-white/10 w-full md:w-auto shrink-0",children:[e.jsxs("button",{onClick:()=>n("synthesizer"),className:`flex-1 md:flex-none justify-center px-3 sm:px-4 py-2 text-xs font-mono tracking-wider uppercase rounded-lg transition-all flex items-center gap-2 ${s==="synthesizer"?"bg-[#2481CC] text-white font-bold shadow-sm":"text-pearl-400 hover:text-pearl-200"}`,children:[e.jsx(J,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:"AI Synthesizer"})]}),e.jsxs("button",{onClick:()=>n("canvas"),className:`flex-1 md:flex-none justify-center px-3 sm:px-4 py-2 text-xs font-mono tracking-wider uppercase rounded-lg transition-all flex items-center gap-2 ${s==="canvas"?"bg-[#2481CC] text-white font-bold shadow-sm":"text-pearl-400 hover:text-pearl-200"}`,children:[e.jsx(Cs,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:"Canvas"})]})]})]}),e.jsxs("div",{className:"bg-[#2481CC]/10 border border-[#2481CC]/30 rounded-xl p-3 sm:p-4 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-[#2481CC]/20 border border-[#2481CC]/40 flex items-center justify-center text-xl shrink-0",children:"🪄"}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] font-mono uppercase px-1.5 py-0.5 rounded bg-[#2481CC]/20 text-[#2481CC] font-bold",children:"Flow Workspace"}),e.jsx("span",{className:"text-sm font-bold text-pearl-100",children:t.name}),e.jsxs("span",{className:"text-xs text-[#2481CC]",children:["@",t.username]})]}),e.jsxs("p",{className:"text-xs text-pearl-400 mt-0.5",children:["Flow topologies and AI prompt architectures deployed here run directly on the cloud worker of @",t.username,"."]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs font-mono text-pearl-300 bg-white/5 px-3 py-1.5 rounded-lg border border-white/10 shrink-0",children:[e.jsx("span",{className:"w-2 h-2 rounded-full bg-emerald-400 animate-pulse"}),e.jsx("span",{children:"Cloud Flow Runner: Online"})]})]}),s==="synthesizer"&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"p-6 rounded-2xl astraea-card relative overflow-hidden space-y-4",children:[e.jsxs("div",{className:"flex flex-col md:flex-row gap-3",children:[e.jsx("div",{className:"relative flex-1",children:e.jsx("input",{type:"text",placeholder:"Describe your desired bot in English or Hinglish (e.g. 'Customer support ticket bot with human escalation and Razorpay integration')...",value:a,onChange:k=>l(k.target.value),onKeyDown:k=>k.key==="Enter"&&E(),className:"w-full bg-space-950/80 border border-[#2481CC]/30 rounded-xl px-4 py-3.5 text-sm font-light text-pearl-100 placeholder:text-pearl-500 focus:outline-none focus:border-[#2481CC] focus:ring-1 focus:ring-[#2481CC] transition-all shadow-inner"})}),e.jsxs("button",{onClick:E,disabled:r||!a.trim(),className:"btn-telegram-primary px-6 py-3.5 disabled:opacity-50 text-xs uppercase tracking-wider font-bold rounded-xl shadow-telegram transition-all flex items-center justify-center gap-2",children:[e.jsx(J,{className:"w-4 h-4"}),r?"Synthesizing...":"Synthesize Bot"]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 pt-2",children:[e.jsx("span",{className:"text-[11px] font-mono text-pearl-500 font-semibold",children:"Try Ideas:"}),[{label:"Customer Support Desk",text:"AI customer support desk with ticketing and human escalation"},{label:"Digital Store & Checkout",text:"E-commerce digital store with cart checkout and Razorpay payments"},{label:"Crypto Sentinel",text:"Crypto price tracker with live alerts and Binance MCP tools"}].map(k=>e.jsx("button",{onClick:()=>{l(k.text)},className:"px-2.5 py-1 text-[11px] font-mono bg-white/5 hover:bg-[#2481CC]/15 text-pearl-300 hover:text-[#2481CC] rounded-lg border border-white/10 transition-colors",children:k.label},k.label))]}),r&&e.jsxs("div",{className:"p-4 rounded-xl bg-space-950/90 border border-[#2481CC]/40 flex items-center gap-3 animate-pulse",children:[e.jsx("div",{className:"w-4 h-4 rounded-full border-2 border-[#2481CC] border-t-transparent animate-spin"}),e.jsx("span",{className:"text-xs font-mono text-[#2481CC] tracking-wider font-semibold",children:j})]})]}),m&&!r&&e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-12 gap-6",children:[e.jsx("div",{className:"lg:col-span-7 space-y-6",children:e.jsxs("div",{className:"p-6 rounded-2xl astraea-card space-y-5",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-[10px] font-mono tracking-wider text-[#2481CC] uppercase font-semibold",children:m.category}),e.jsx("h3",{className:"text-xl font-bold text-pearl-50 tracking-tight",children:m.bot_name}),e.jsx("p",{className:"text-xs text-pearl-300 font-light mt-1",children:m.headline})]}),e.jsx("span",{className:"px-2.5 py-1 rounded-full text-[10px] font-mono font-semibold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30",children:"SYNTHESIS READY"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"text-[11px] font-mono uppercase text-pearl-400 font-semibold",children:["Synthesized Core Modules (",m.selected_modules.length,")"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:m.selected_modules.map(k=>e.jsxs("span",{className:"px-2.5 py-1 rounded-lg text-xs font-mono bg-space-950 border border-white/10 text-pearl-200",children:["📦 ",k]},k))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"text-[11px] font-mono uppercase text-pearl-400 font-semibold",children:["Assigned MCP Protocol Tools (",m.selected_mcp_tools.length,")"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:m.selected_mcp_tools.map(k=>e.jsxs("span",{className:"px-2.5 py-1 rounded-lg text-xs font-mono bg-[#2481CC]/10 border border-[#2481CC]/30 text-[#2481CC] font-semibold",children:["⚡ ",k]},k))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-[11px] font-mono uppercase text-pearl-400 font-semibold",children:"Synthesized Persona System Prompt"}),e.jsx("textarea",{rows:4,value:m.system_prompt,onChange:k=>x({...m,system_prompt:k.target.value}),className:"w-full bg-space-950/80 border border-white/10 rounded-xl p-3 text-xs font-mono text-pearl-200 focus:outline-none focus:border-[#2481CC] focus:ring-1 focus:ring-[#2481CC]"})]}),e.jsxs("div",{className:"pt-4 border-t border-white/10 flex items-center justify-between",children:[e.jsxs("div",{className:"text-xs font-mono text-pearl-400",children:["Cloud Runtime: ",e.jsx("span",{className:"text-emerald-400 font-semibold",children:"24/7 Managed Celery Pool"})]}),e.jsx("button",{onClick:w,disabled:f,className:`px-5 py-2.5 rounded-xl text-xs font-mono uppercase tracking-wider font-bold transition-all flex items-center gap-2 ${f?"bg-emerald-500 text-white":"btn-telegram-primary shadow-telegram"}`,children:f?e.jsxs(e.Fragment,{children:[e.jsx(F,{className:"w-4 h-4"}),"Deployed to 24/7 Cloud!"]}):e.jsxs(e.Fragment,{children:[e.jsx(ht,{className:"w-4 h-4"}),"Deploy to 24/7 Cloud"]})})]}),f&&e.jsxs("div",{className:"p-4 rounded-lg bg-emerald-500/10 border border-emerald-500/30 text-xs font-mono text-emerald-300 space-y-1",children:[e.jsxs("div",{className:"font-semibold flex items-center gap-2",children:[e.jsx(D,{className:"w-4 h-4 text-emerald-400"}),"Bot Container Successfully Provisioned"]}),e.jsx("p",{className:"text-[11px] text-pearl-300",children:"Webhook registered on Telegram API. Auto-recovery and deduplication active."})]})]})}),e.jsx("div",{className:"lg:col-span-5 space-y-4",children:e.jsxs("div",{className:"p-6 rounded-xl bg-space-900/60 border border-white/10 backdrop-blur-xl space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-white/10 pb-3",children:[e.jsxs("span",{className:"text-xs font-mono uppercase text-[#2481CC] flex items-center gap-2 font-semibold",children:[e.jsx(Q,{className:"w-4 h-4"}),"Live Telegram Preview"]}),e.jsx("span",{className:"text-[10px] font-mono text-pearl-400",children:"HTML Parse Mode"})]}),e.jsxs("div",{className:"bg-[#182533] p-4 rounded-2xl border border-white/10 shadow-2xl space-y-3 font-sans max-w-sm mx-auto",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-[#6ab2f2] font-semibold",children:[e.jsx("span",{children:m.bot_name}),e.jsx("span",{className:"text-[9px] px-1 rounded bg-[#2b5278] text-white",children:"BOT"})]}),e.jsx("pre",{className:"text-xs text-[#f5f5f5] font-mono whitespace-pre-wrap leading-relaxed",dangerouslySetInnerHTML:{__html:m.preview_text}}),e.jsxs("div",{className:"space-y-1.5 pt-2",children:[e.jsx("div",{className:"w-full py-2 bg-[#2b5278] hover:bg-[#346595] text-white text-xs font-medium rounded-lg text-center transition-colors",children:"🚀 Start Interactive Session"}),e.jsx("div",{className:"w-full py-2 bg-[#2b5278] hover:bg-[#346595] text-white text-xs font-medium rounded-lg text-center transition-colors",children:"💬 Speak to Human Manager"})]}),e.jsx("div",{className:"text-right text-[10px] text-[#6c7883]",children:"12:00 PM ✓✓"})]})]})})]})]}),s==="canvas"&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between p-4 rounded-xl astraea-card",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("span",{className:"text-xs font-mono uppercase text-pearl-400 font-medium",children:["Pipeline Graph: ",e.jsx("span",{className:"text-[#2481CC] font-bold",children:"4 Connected Nodes"})]}),e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-emerald-400"})]}),e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs("button",{onClick:S,disabled:v,className:"btn-telegram-primary px-4 py-2 text-xs font-mono uppercase tracking-wider font-bold rounded-lg shadow-telegram transition-all flex items-center gap-2",children:[e.jsx($e,{className:"w-3.5 h-3.5"}),v?"Executing Graph...":"Test Run Flow"]})})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4 relative",children:g.map((k,L)=>{const M=d===k.id;return e.jsxs("div",{onClick:()=>c(k.id),className:`p-5 rounded-xl transition-all cursor-pointer relative space-y-3 ${M?"bg-space-900 border-2 border-[#2481CC] shadow-telegram":"bg-space-900/70 border border-white/10 hover:border-white/25"}`,children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("span",{className:"text-[10px] font-mono uppercase tracking-wider text-[#2481CC] font-bold",children:["Step ",L+1]}),k.status==="running"&&e.jsx("div",{className:"w-3.5 h-3.5 rounded-full border-2 border-[#2481CC] border-t-transparent animate-spin"}),k.status==="success"&&e.jsxs("span",{className:"text-[10px] font-mono text-emerald-400 flex items-center gap-1 font-semibold",children:[e.jsx(D,{className:"w-3 h-3"}),k.latency_ms,"ms"]}),k.status==="idle"&&e.jsx("span",{className:"w-2 h-2 rounded-full bg-white/20"})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-mono text-sm text-pearl-100 font-semibold",children:k.label}),e.jsx("p",{className:"text-xs text-pearl-400 font-mono mt-0.5",children:k.subtitle})]}),e.jsxs("div",{className:"text-[10px] font-mono px-2 py-1 rounded-lg bg-space-950 border border-white/5 text-pearl-300",children:["Type: ",k.type]}),L{const L=k.target.value;u(M=>M.map(_=>_.id===P.id?{..._,label:L}:_))},className:"w-full bg-space-950 border border-white/10 rounded-xl px-3 py-2 text-pearl-100 focus:outline-none focus:border-[#2481CC] focus:ring-1 focus:ring-[#2481CC]"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-pearl-400 block mb-1 font-medium",children:"Configuration Parameters (JSON)"}),e.jsx("pre",{className:"p-3 rounded-xl bg-space-950 border border-white/5 text-pearl-300 text-[11px] overflow-x-auto",children:JSON.stringify(P.config,null,2)})]})]})]}),e.jsxs("div",{className:"lg:col-span-6 p-6 rounded-2xl astraea-card space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-white/10 pb-3",children:[e.jsxs("h4",{className:"text-base font-bold text-pearl-50 tracking-tight flex items-center gap-2",children:[e.jsx(Ie,{className:"w-4 h-4 text-emerald-400"}),"Execution Trace & Telemetry"]}),e.jsx("span",{className:"text-xs font-mono text-pearl-400",children:N.length>0?"4/4 Completed":"Waiting for Run"})]}),N.length===0?e.jsx("div",{className:"p-8 text-center text-xs font-mono text-pearl-500",children:'Click "Test Run Flow" above to simulate deterministic graph execution across all 4 nodes.'}):e.jsx("div",{className:"space-y-3 font-mono text-xs",children:N.map((k,L)=>e.jsxs("div",{className:"p-3 rounded-xl bg-space-950/80 border border-white/5 space-y-1",children:[e.jsx("div",{className:"text-[#2481CC] font-bold text-[11px]",children:k.step}),e.jsx("div",{className:"text-pearl-300 text-[11px]",children:k.output})]},L))})]})]})]})]})},Ql=[{name:"bot.list",description:"Lists all Telegram bots registered under tenant account with operational status.",category:"Bot Fleet",is_dangerous:!1,requires_approval:!1,is_enabled:!0,input_schema:{status:"all | active | paused"}},{name:"bot.status",description:"Checks health, webhook sync status, and Telegram getMe profile for a specific bot.",category:"Bot Fleet",is_dangerous:!1,requires_approval:!1,is_enabled:!0,input_schema:{bot_id:"uuid",check_telegram:"boolean"}},{name:"marketplace.list",description:"Browses 25 ready-made bot blueprints and modules in the universal marketplace catalog.",category:"Marketplace",is_dangerous:!1,requires_approval:!1,is_enabled:!0,input_schema:{category:"all | business | community | ai_specialist"}},{name:"marketplace.install",description:"Installs a ready-made bot blueprint and configures 24/7 cloud instance provisioning.",category:"Marketplace",is_dangerous:!0,requires_approval:!0,is_enabled:!0,input_schema:{template_id:"string",bot_name:"string"}},{name:"message.send",description:"Dispatches high-priority message or broadcast via Telegram Bot API with retry backoff.",category:"Messaging",is_dangerous:!0,requires_approval:!0,is_enabled:!0,input_schema:{bot_id:"uuid",chat_id:"string",text:"string",parse_mode:"HTML"}},{name:"analytics.report",description:"Retrieves platform telemetry, active subscribers, and operational KPIs for the tenant.",category:"Analytics",is_dangerous:!1,requires_approval:!1,is_enabled:!0,input_schema:{period:"today | 7d | 30d"}}],Zl=[{id:"srv-1",name:"GitHub DevOps MCP Server",transport_type:"sse",endpoint_url:"https://mcp-hub.internal.net/github/sse",status:"online",discovered_tools:14,last_synced_at:"2 mins ago"},{id:"srv-2",name:"PostgreSQL Enterprise Explorer",transport_type:"stdio",endpoint_url:"npx -y @modelcontextprotocol/server-postgres",status:"online",discovered_tools:6,last_synced_at:"10 mins ago"},{id:"srv-3",name:"Stripe & Billing Gateway Tools",transport_type:"http",endpoint_url:"https://api.billing-mcp.internal/tools",status:"online",discovered_tools:8,last_synced_at:"1 hour ago"}],Xl=[{id:"exec-901",tool_name:"message.send",caller:"Cursor AI Assistant",requested_at:"Just now",arguments:{bot_id:"b-001",chat_id:"99281726",text:"Urgent: VIP subscription plan renewed automatically.",parse_mode:"HTML"},risk_level:"high"},{id:"exec-902",tool_name:"marketplace.install",caller:"Claude Desktop Agent",requested_at:"3 mins ago",arguments:{template_id:"bot_customer_support",bot_name:"Astraea Automated Support Desk"},risk_level:"high"}],ei=[{id:"log-101",tool_name:"bot.list",status:"completed",caller:"Claude Desktop",duration_ms:18.4,timestamp:"12:04:12 PM",result:{total_bots:4,active:4,paused:0}},{id:"log-102",tool_name:"analytics.report",status:"completed",caller:"Cursor AI",duration_ms:32.1,timestamp:"11:58:45 AM",result:{period:"7d",total_active_bots:4,uptime_percentage:99.98}},{id:"log-103",tool_name:"message.send",status:"approved",caller:"Autonomous Agent #2",duration_ms:145.8,timestamp:"11:42:01 AM",result:{status:"sent",message_id:"msg_98124"}},{id:"log-104",tool_name:"marketplace.install",status:"rejected",caller:"External Script",duration_ms:4.2,timestamp:"10:15:30 AM",result:{reason:"Admin rejected dangerous deployment without approval token"}}],ti=()=>{const{currentBot:t}=z(),[s,n]=i.useState("tools"),[a,l]=i.useState(Ql),[r,o]=i.useState(Zl),[j,b]=i.useState(Xl),[m,x]=i.useState(ei),[f,p]=i.useState(null),[g,u]=i.useState(null),[d,c]=i.useState(!1),[v,h]=i.useState(""),[N,y]=i.useState(""),[E,w]=i.useState("sse"),S=(I,$)=>{navigator.clipboard.writeText(I),p($),setTimeout(()=>p(null),2e3)},P=()=>{u("Testing handshake..."),setTimeout(()=>{u("JSON-RPC 2.0 handshake verified (latency: 14ms)"),setTimeout(()=>u(null),4e3)},400)},k=I=>{l($=>$.map(O=>O.name===I?{...O,requires_approval:!O.requires_approval}:O))},L=I=>{l($=>$.map(O=>O.name===I?{...O,is_enabled:!O.is_enabled}:O))},M=I=>{const $=j.find(O=>O.id===I);$&&(b(O=>O.filter(le=>le.id!==I)),x(O=>[{id:`log-${Date.now()}`,tool_name:$.tool_name,status:"approved",caller:$.caller,duration_ms:124.5,timestamp:new Date().toLocaleTimeString(),result:{status:"executed_with_human_approval",id:I}},...O]))},_=I=>{const $=j.find(O=>O.id===I);$&&(b(O=>O.filter(le=>le.id!==I)),x(O=>[{id:`log-${Date.now()}`,tool_name:$.tool_name,status:"rejected",caller:$.caller,duration_ms:6.1,timestamp:new Date().toLocaleTimeString(),result:{reason:"Admin manually rejected approval gate"}},...O]))},Y=()=>{if(!v||!N)return;const I={id:`srv-${Date.now()}`,name:v,transport_type:E,endpoint_url:N,status:"online",discovered_tools:5,last_synced_at:"Just now"};o($=>[I,...$]),c(!1),h(""),y("")},K=JSON.stringify({mcpServers:{"astraea-bot-cloud":{url:"https://api.yourdomain.com/api/v1/mcp/rpc",headers:{Authorization:"Bearer "}}}},null,2),ne=JSON.stringify({servers:[{name:"astraea-bot-cloud",url:"https://api.yourdomain.com/api/v1/mcp/rpc",type:"sse"}]},null,2);return e.jsxs("div",{className:"space-y-6 sm:space-y-8 animate-fadeIn w-full max-w-full min-w-0",children:[e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center justify-between gap-4 pb-6 border-b border-white/10",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"w-2 h-2 rounded-full bg-emerald-400 animate-pulse"}),e.jsx("span",{className:"text-[10px] font-mono tracking-wider text-[#2481CC] uppercase font-semibold",children:"Model Context Protocol Pro"})]}),e.jsxs("h1",{className:"text-2xl sm:text-3xl md:text-4xl text-pearl-50 font-bold tracking-tight flex items-center gap-2 sm:gap-3",children:[e.jsx(fe,{className:"w-6 h-6 sm:w-8 sm:h-8 text-[#2481CC] shrink-0"}),e.jsx("span",{children:"MCP Pro Protocol Cloud"})]}),e.jsx("p",{className:"text-xs sm:text-sm text-pearl-300 font-light mt-1 max-w-2xl",children:"Connect external AI clients (Claude Desktop, Cursor, Local LLMs) to your Telegram Bot Cloud via JSON-RPC 2.0 with granular human approval gates."})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row items-stretch sm:items-center gap-2 sm:gap-3 w-full md:w-auto shrink-0",children:[e.jsxs("button",{onClick:P,className:"btn-telegram-secondary px-4 py-2 text-xs font-mono tracking-wider uppercase rounded-xl transition-all flex items-center justify-center gap-2",children:[e.jsx(Ge,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:g||"Ping JSON-RPC"})]}),e.jsxs("button",{onClick:()=>c(!0),className:"btn-telegram-primary px-4 py-2 text-xs font-mono tracking-wider uppercase font-semibold rounded-xl shadow-telegram transition-all flex items-center justify-center gap-2",children:[e.jsx(ee,{className:"w-4 h-4"}),e.jsx("span",{children:"Connect MCP Server"})]})]})]}),e.jsxs("div",{className:"bg-[#2481CC]/10 border border-[#2481CC]/30 rounded-xl p-3 sm:p-4 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-[#2481CC]/20 border border-[#2481CC]/40 flex items-center justify-center text-xl shrink-0",children:"⚡"}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] font-mono uppercase px-1.5 py-0.5 rounded bg-[#2481CC]/20 text-[#2481CC] font-bold",children:"MCP Target Bot"}),e.jsx("span",{className:"text-sm font-bold text-pearl-100",children:t.name}),e.jsxs("span",{className:"text-xs text-[#2481CC]",children:["@",t.username]})]}),e.jsxs("p",{className:"text-xs text-pearl-400 mt-0.5",children:["MCP tool calls (such as message dispatch and user queries) authenticate against @",t.username," credentials and permissions."]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs font-mono text-pearl-300 bg-white/5 px-3 py-1.5 rounded-lg border border-white/10 shrink-0",children:[e.jsx("span",{className:"w-2 h-2 rounded-full bg-emerald-400 animate-pulse"}),e.jsx("span",{children:"JSON-RPC Gateway: Ready"})]})]}),e.jsxs("div",{className:"p-4 sm:p-6 rounded-2xl astraea-card relative overflow-hidden w-full max-w-full min-w-0",children:[e.jsx("div",{className:"absolute top-0 right-0 w-80 h-80 bg-[#2481CC]/5 rounded-full blur-3xl pointer-events-none"}),e.jsxs("div",{className:"flex flex-col lg:flex-row items-start lg:items-center justify-between gap-4 sm:gap-6",children:[e.jsxs("div",{className:"space-y-2 max-w-xl min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"px-2 py-0.5 rounded-full text-[10px] font-mono bg-[#2481CC]/15 text-[#2481CC] border border-[#2481CC]/30 font-semibold",children:"JSON-RPC 2.0"}),e.jsx("span",{className:"px-2 py-0.5 rounded-full text-[10px] font-mono bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 font-semibold",children:"AES-256 ISOLATED"})]}),e.jsx("h3",{className:"text-base sm:text-lg font-bold text-pearl-50 tracking-tight",children:"Platform MCP Server Endpoint"}),e.jsx("p",{className:"text-xs text-pearl-300 font-mono break-all bg-space-950/80 px-3 py-2 rounded-xl border border-white/5",children:"POST https://api.yourdomain.com/api/v1/mcp/rpc"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row items-stretch sm:items-center gap-2 sm:gap-3 w-full lg:w-auto shrink-0",children:[e.jsxs("button",{onClick:()=>S(K,"claude"),className:"px-3 py-2 text-xs font-mono bg-space-800/80 hover:bg-space-800 border border-white/10 rounded-xl text-pearl-200 transition-all flex items-center justify-center gap-2",children:[f==="claude"?e.jsx(D,{className:"w-3.5 h-3.5 text-emerald-400"}):e.jsx(Ze,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:"Claude Desktop Config"})]}),e.jsxs("button",{onClick:()=>S(ne,"cursor"),className:"px-3 py-2 text-xs font-mono bg-space-800/80 hover:bg-space-800 border border-white/10 rounded-xl text-pearl-200 transition-all flex items-center justify-center gap-2",children:[f==="cursor"?e.jsx(D,{className:"w-3.5 h-3.5 text-emerald-400"}):e.jsx(Ze,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:"Cursor .cursor/mcp.json"})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 border-b border-white/10 pb-2 overflow-x-auto w-full max-w-full scrollbar-none",children:[e.jsxs("button",{onClick:()=>n("tools"),className:`px-3.5 sm:px-4 py-2 text-xs font-mono tracking-wider uppercase rounded-xl transition-all flex items-center gap-2 shrink-0 whitespace-nowrap ${s==="tools"?"bg-[#2481CC] text-white font-bold shadow-sm":"text-pearl-400 hover:text-pearl-200 hover:bg-white/5"}`,children:[e.jsx(Pe,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:["Platform Tools (",a.length,")"]})]}),e.jsxs("button",{onClick:()=>n("servers"),className:`px-3.5 sm:px-4 py-2 text-xs font-mono tracking-wider uppercase rounded-xl transition-all flex items-center gap-2 shrink-0 whitespace-nowrap ${s==="servers"?"bg-[#2481CC] text-white font-bold shadow-sm":"text-pearl-400 hover:text-pearl-200 hover:bg-white/5"}`,children:[e.jsx(ht,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:["External MCP Servers (",r.length,")"]})]}),e.jsxs("button",{onClick:()=>n("approvals"),className:`px-3.5 sm:px-4 py-2 text-xs font-mono tracking-wider uppercase rounded-xl transition-all flex items-center gap-2 relative shrink-0 whitespace-nowrap ${s==="approvals"?"bg-[#2481CC] text-white font-bold shadow-sm":"text-pearl-400 hover:text-pearl-200 hover:bg-white/5"}`,children:[e.jsx(Is,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:"Human Approval Queue"}),j.length>0&&e.jsx("span",{className:"w-4 h-4 rounded-full bg-amber-500 text-[9px] text-space-950 font-bold flex items-center justify-center ml-1",children:j.length})]}),e.jsxs("button",{onClick:()=>n("logs"),className:`px-3.5 sm:px-4 py-2 text-xs font-mono tracking-wider uppercase rounded-xl transition-all flex items-center gap-2 shrink-0 whitespace-nowrap ${s==="logs"?"bg-[#2481CC] text-white font-bold shadow-sm":"text-pearl-400 hover:text-pearl-200 hover:bg-white/5"}`,children:[e.jsx(Bs,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:"Execution Logs"})]})]}),s==="tools"&&e.jsx("div",{className:"space-y-4",children:e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:a.map(I=>e.jsxs("div",{className:"p-5 rounded-2xl astraea-card hover:border-[#2481CC]/40 transition-all space-y-3 group",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-[10px] font-mono tracking-wider text-[#2481CC] uppercase font-semibold",children:I.category}),e.jsx("h4",{className:"font-mono font-bold text-pearl-100 text-sm group-hover:text-[#2481CC] transition-colors",children:I.name})]}),I.is_dangerous&&e.jsxs("span",{className:"px-2 py-0.5 rounded-full text-[9px] font-mono bg-amber-500/20 text-amber-300 border border-amber-500/30 flex items-center gap-1 font-semibold",children:[e.jsx(Xe,{className:"w-2.5 h-2.5"}),"CRITICAL"]})]}),e.jsx("p",{className:"text-xs text-pearl-300 line-clamp-2",children:I.description}),e.jsxs("div",{className:"bg-space-950/70 p-2.5 rounded-xl border border-white/5 text-[11px] font-mono text-pearl-400 overflow-x-auto",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-wider text-pearl-500 mb-1 font-semibold",children:"Input Schema"}),e.jsx("pre",{children:JSON.stringify(I.input_schema,null,2)})]}),e.jsxs("div",{className:"pt-2 border-t border-white/10 flex items-center justify-between text-xs font-mono",children:[e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer select-none",children:[e.jsx("input",{type:"checkbox",checked:I.requires_approval,onChange:()=>k(I.name),className:"rounded border-white/20 bg-space-950 text-[#2481CC] focus:ring-0"}),e.jsx("span",{className:I.requires_approval?"text-[#2481CC] font-semibold":"text-pearl-400",children:"Requires Human Approval"})]}),e.jsx("button",{onClick:()=>L(I.name),className:`px-2.5 py-1 rounded-full text-[10px] font-mono font-semibold ${I.is_enabled?"bg-emerald-500/20 text-emerald-300 border border-emerald-500/30":"bg-rose-500/20 text-rose-300 border border-rose-500/30"}`,children:I.is_enabled?"ENABLED":"DISABLED"})]})]},I.name))})}),s==="servers"&&e.jsx("div",{className:"space-y-4",children:e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:r.map(I=>e.jsxs("div",{className:"p-5 rounded-2xl astraea-card hover:border-[#2481CC]/30 transition-all space-y-4",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"text-base font-bold text-pearl-100 tracking-tight",children:I.name}),e.jsxs("span",{className:"text-[10px] font-mono uppercase text-[#2481CC] font-semibold",children:["Transport: ",I.transport_type.toUpperCase()]})]}),e.jsxs("span",{className:"px-2 py-0.5 rounded-full text-[10px] font-mono bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 flex items-center gap-1 font-semibold",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"}),"ONLINE"]})]}),e.jsx("div",{className:"text-xs font-mono text-pearl-300 bg-space-950/60 p-2 rounded-xl border border-white/5 break-all",children:I.endpoint_url}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t border-white/10 text-xs font-mono text-pearl-400",children:[e.jsxs("span",{children:[I.discovered_tools," Tools Discovered"]}),e.jsxs("span",{children:["Synced ",I.last_synced_at]})]})]},I.id))})}),s==="approvals"&&e.jsx("div",{className:"space-y-4",children:j.length===0?e.jsxs("div",{className:"p-12 text-center rounded-2xl astraea-card",children:[e.jsx(F,{className:"w-12 h-12 text-emerald-400 mx-auto mb-3 opacity-80"}),e.jsx("h3",{className:"text-lg font-bold text-pearl-100 tracking-tight",children:"No Pending Approvals"}),e.jsx("p",{className:"text-xs text-pearl-400 font-mono mt-1",children:"All external tool requests have been authorized or resolved."})]}):e.jsx("div",{className:"space-y-3",children:j.map(I=>e.jsxs("div",{className:"p-5 rounded-2xl astraea-card border-amber-500/30 flex flex-col md:flex-row md:items-center justify-between gap-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"px-2 py-0.5 rounded-full text-[10px] font-mono bg-amber-500/20 text-amber-300 border border-amber-500/30 flex items-center gap-1 font-semibold",children:[e.jsx(Xe,{className:"w-3 h-3"}),"REQUIRES APPROVAL"]}),e.jsxs("span",{className:"text-xs font-mono text-pearl-400",children:["from ",I.caller]}),e.jsxs("span",{className:"text-xs font-mono text-pearl-500",children:["• ",I.requested_at]})]}),e.jsx("h4",{className:"font-mono text-sm text-pearl-100 font-semibold",children:I.tool_name}),e.jsx("pre",{className:"text-[11px] font-mono bg-space-950 p-2 rounded-xl border border-white/10 text-pearl-300 max-w-xl overflow-x-auto",children:JSON.stringify(I.arguments,null,2)})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:()=>_(I.id),className:"px-4 py-2 rounded-xl text-xs font-mono uppercase bg-rose-500/20 text-rose-300 hover:bg-rose-500/30 border border-rose-500/40 transition-all flex items-center gap-1.5 font-semibold",children:[e.jsx(Os,{className:"w-3.5 h-3.5"}),"Reject"]}),e.jsxs("button",{onClick:()=>M(I.id),className:"px-4 py-2 rounded-xl text-xs font-mono uppercase bg-emerald-500 text-space-950 hover:bg-emerald-400 font-bold shadow-sm transition-all flex items-center gap-1.5",children:[e.jsx(F,{className:"w-3.5 h-3.5"}),"Authorize & Run"]})]})]},I.id))})}),s==="logs"&&e.jsx("div",{className:"p-4 rounded-2xl astraea-card overflow-x-auto",children:e.jsxs("table",{className:"w-full text-left text-xs font-mono",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-white/10 text-pearl-400 font-semibold",children:[e.jsx("th",{className:"p-3",children:"TOOL"}),e.jsx("th",{className:"p-3",children:"STATUS"}),e.jsx("th",{className:"p-3",children:"CALLER"}),e.jsx("th",{className:"p-3",children:"LATENCY"}),e.jsx("th",{className:"p-3",children:"TIME"}),e.jsx("th",{className:"p-3",children:"RESULT"})]})}),e.jsx("tbody",{className:"divide-y divide-white/5",children:m.map(I=>e.jsxs("tr",{className:"hover:bg-white/[0.02]",children:[e.jsx("td",{className:"p-3 font-semibold text-pearl-100",children:I.tool_name}),e.jsx("td",{className:"p-3",children:e.jsx("span",{className:`px-2 py-0.5 rounded-full text-[10px] font-semibold ${I.status==="completed"||I.status==="approved"?"bg-emerald-500/20 text-emerald-300 border border-emerald-500/30":"bg-rose-500/20 text-rose-300 border border-rose-500/30"}`,children:I.status.toUpperCase()})}),e.jsx("td",{className:"p-3 text-pearl-300",children:I.caller}),e.jsxs("td",{className:"p-3 text-pearl-400",children:[I.duration_ms," ms"]}),e.jsx("td",{className:"p-3 text-pearl-400",children:I.timestamp}),e.jsx("td",{className:"p-3 text-pearl-300 max-w-xs truncate",children:JSON.stringify(I.result)})]},I.id))})]})}),d&&e.jsx(te,{children:e.jsx("div",{className:"fixed inset-0 z-50 bg-black/60 backdrop-blur-md flex items-center justify-center p-4",children:e.jsxs("div",{className:"max-w-md w-full astraea-card border border-[#2481CC]/30 rounded-2xl p-6 space-y-4 shadow-2xl",children:[e.jsx("h3",{className:"text-lg font-bold text-pearl-50 tracking-tight",children:"Connect External MCP Server"}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-[11px] font-mono text-pearl-400 block mb-1 font-medium",children:"Server Name"}),e.jsx("input",{type:"text",placeholder:"e.g. Brave Search MCP",value:v,onChange:I=>h(I.target.value),className:"w-full bg-space-950 border border-white/10 rounded-xl px-3 py-2 text-xs text-pearl-100 font-mono focus:border-[#2481CC] focus:ring-1 focus:ring-[#2481CC] focus:outline-none"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[11px] font-mono text-pearl-400 block mb-1 font-medium",children:"Transport Type"}),e.jsxs("select",{value:E,onChange:I=>w(I.target.value),className:"w-full bg-space-950 border border-white/10 rounded-xl px-3 py-2 text-xs text-pearl-100 font-mono focus:border-[#2481CC] focus:ring-1 focus:ring-[#2481CC] focus:outline-none",children:[e.jsx("option",{value:"sse",children:"Server-Sent Events (SSE)"}),e.jsx("option",{value:"stdio",children:"Standard I/O (stdio)"}),e.jsx("option",{value:"http",children:"HTTP POST / JSON-RPC"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[11px] font-mono text-pearl-400 block mb-1 font-medium",children:"Endpoint URL or Command"}),e.jsx("input",{type:"text",placeholder:"https://mcp-server.example.com/sse",value:N,onChange:I=>y(I.target.value),className:"w-full bg-space-950 border border-white/10 rounded-xl px-3 py-2 text-xs text-pearl-100 font-mono focus:border-[#2481CC] focus:ring-1 focus:ring-[#2481CC] focus:outline-none"})]})]}),e.jsxs("div",{className:"flex items-center justify-end gap-3 pt-4 border-t border-white/10",children:[e.jsx("button",{onClick:()=>c(!1),className:"btn-telegram-secondary px-4 py-2 text-xs font-mono",children:"Cancel"}),e.jsx("button",{onClick:Y,className:"btn-telegram-primary px-4 py-2 text-xs font-mono uppercase font-bold rounded-xl shadow-telegram",children:"Connect & Discover"})]})]})})})]})},si=({onNavigate:t,onSelectBot:s})=>{const n=ce(),{bots:a,currentBot:l,selectBot:r,registerBot:o}=z(),[j,b]=i.useState(!1),[m,x]=i.useState(""),[f,p]=i.useState(""),[g,u]=i.useState("en"),[d,c]=i.useState(!1),[v,h]=i.useState(null),N=async y=>{if(y.preventDefault(),!!m.trim()){c(!0);try{const E=await o(f||"My New Telegram Bot",m,g);h(`Bot @${E.username} successfully registered! Entering console...`),setTimeout(()=>{b(!1),h(null),x(""),p(""),n("/dashboard")},1e3)}catch{b(!1)}finally{c(!1)}}};return e.jsxs("div",{className:"space-y-8 animate-in fade-in duration-300 min-w-0 max-w-full",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-end justify-between gap-4 border-b border-white/10 pb-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("span",{className:"w-2 h-2 rounded-full bg-[#2481CC]"}),e.jsx("span",{className:"text-[11px] font-mono tracking-wider text-[#2481CC] uppercase font-semibold",children:"Bot Management & Fleet Studio"})]}),e.jsx("h1",{className:"text-2xl sm:text-3xl font-bold text-pearl-50 tracking-tight",children:"My Telegram Bots"}),e.jsx("p",{className:"text-xs text-pearl-400 font-sans mt-1.5 max-w-2xl leading-relaxed",children:"Create, customize, and run your Telegram bots 24/7 on managed cloud infrastructure — zero VPS or server maintenance required. Connect via BotFather, install ready-made templates, and activate modular features."})]}),e.jsxs("button",{onClick:()=>b(!0),className:"btn-telegram-primary w-full sm:w-auto justify-center py-2.5 px-4 shadow-telegram",children:[e.jsx(ee,{className:"w-4 h-4"}),e.jsx("span",{children:"CONNECT NEW BOT"})]})]}),e.jsx("div",{className:"p-3.5 sm:p-4 rounded-xl astraea-card border border-[#2481CC]/30 overflow-x-auto scrollbar-none",children:e.jsxs("div",{className:"flex items-center gap-2 sm:gap-4 min-w-[720px] text-xs font-mono",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[#2481CC] font-bold bg-[#2481CC]/10 px-2 py-0.5 rounded-lg border border-[#2481CC]/40",children:[e.jsx(Q,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:"1. Create Bot (@BotFather)"})]}),e.jsx("span",{className:"text-pearl-500",children:"→"}),e.jsxs("div",{className:"flex items-center gap-1.5 text-emerald-400 font-semibold",children:[e.jsx(F,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:"2. Select Template (25)"})]}),e.jsx("span",{className:"text-pearl-500",children:"→"}),e.jsxs("div",{className:"flex items-center gap-1.5 text-emerald-400 font-semibold",children:[e.jsx(F,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:"3. Install Modules (9)"})]}),e.jsx("span",{className:"text-pearl-500",children:"→"}),e.jsx("div",{className:"flex items-center gap-1.5 text-[#2481CC] font-medium",children:e.jsx("span",{children:"4. Configure"})}),e.jsx("span",{className:"text-pearl-500",children:"→"}),e.jsx("div",{className:"flex items-center gap-1.5 text-[#2481CC] font-medium",children:e.jsx("span",{children:"5. Activate"})}),e.jsx("span",{className:"text-pearl-500",children:"→"}),e.jsxs("div",{className:"flex items-center gap-1.5 text-emerald-400 font-semibold",children:[e.jsx(q,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:"6. 24/7 Cloud Run"})]}),e.jsx("span",{className:"text-pearl-500",children:"→"}),e.jsx("div",{className:"flex items-center gap-1.5 text-pearl-300",children:e.jsx("span",{children:"7. Monitoring"})})]})}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4",children:a.map(y=>{var E,w;return e.jsxs("div",{className:"astraea-card rounded-2xl p-5 flex flex-col justify-between group hover:border-[#2481CC]/40 transition-all",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-[#2481CC]/10 border border-[#2481CC]/30 flex items-center justify-center text-[#2481CC]",children:e.jsx(Q,{className:"w-5 h-5"})}),e.jsx("span",{className:"px-2 py-0.5 rounded-full text-[10px] font-mono uppercase bg-emerald-500/10 border border-emerald-500/30 text-emerald-300 font-semibold",children:y.status})]}),e.jsx(A,{to:`/dashboard/bots/${((E=y.username)==null?void 0:E.replace("@",""))||y.id}`,onClick:()=>s&&s(y.id),className:"text-base text-pearl-50 font-bold tracking-tight hover:text-[#2481CC] transition-colors block",children:y.name}),e.jsxs("div",{className:"text-xs font-mono text-[#2481CC] mt-0.5 font-semibold",children:["@",y.username]}),e.jsxs("div",{className:"mt-4 pt-4 border-t border-white/5 space-y-2 text-xs font-mono text-pearl-300",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-pearl-400 text-[10px] uppercase",children:"Audience:"}),e.jsxs("span",{className:"font-medium text-pearl-100",children:[y.usersCount.toLocaleString()," users"]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-pearl-400 text-[10px] uppercase",children:"Default Locale:"}),e.jsx("span",{className:"text-pearl-100 uppercase",children:y.defaultLocale})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-pearl-400 text-[10px] uppercase",children:"Token Vault:"}),e.jsxs("span",{className:"text-emerald-400 flex items-center gap-1 font-medium",children:[e.jsx(q,{className:"w-3.5 h-3.5 text-[#2481CC]"})," AES-256 (v",y.keyVersion,")"]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-pearl-400 text-[10px] uppercase",children:"Hosting:"}),e.jsx("span",{className:"text-[#2481CC] font-bold text-[10px]",children:"24/7 Managed Cloud"})]})]})]}),e.jsxs("div",{className:"mt-5 pt-3 border-t border-white/10 flex flex-col gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>{r(y.id),s&&s(y.id),n("/dashboard")},className:`w-full py-2 px-3 rounded-lg text-[11px] font-mono font-semibold flex items-center justify-center gap-1.5 transition-colors ${y.id===(l==null?void 0:l.id)?"bg-[#2481CC] text-white shadow-telegram":"bg-space-850 hover:bg-[#2481CC]/20 text-pearl-100 hover:text-[#2481CC] border border-white/10"}`,children:[e.jsx(Dt,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:y.id===(l==null?void 0:l.id)?"● Active Dashboard":"Open Bot Dashboard"})]}),e.jsxs(A,{to:`/dashboard/bots/${((w=y.username)==null?void 0:w.replace("@",""))||y.id}`,onClick:()=>{r(y.id),s&&s(y.id)},className:"w-full btn-telegram-secondary py-1.5 text-[11px] justify-center inline-flex items-center gap-1.5",children:[e.jsx(at,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:"MODULAR FEATURES (9)"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(A,{to:"/marketplace",className:"flex-1 btn-telegram-secondary py-1.5 text-[10px] justify-center inline-flex items-center",title:"Install Template",children:e.jsx("span",{children:"TEMPLATES"})}),e.jsx(A,{to:"/dashboard/studio",onClick:()=>{r(y.id),s&&s(y.id)},className:"flex-1 btn-telegram-secondary py-1.5 text-[10px] justify-center inline-flex items-center",title:"Open Message Studio",children:e.jsx("span",{children:"STUDIO"})})]})]})]},y.id)})}),j&&e.jsx(te,{children:e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-3 sm:p-4 bg-black/60 backdrop-blur-md",children:e.jsxs("div",{className:"w-full max-w-lg max-h-[90vh] overflow-y-auto astraea-card rounded-2xl p-4 sm:p-6 border border-[#2481CC]/30 shadow-2xl animate-in zoom-in-95 duration-200",children:[e.jsxs("div",{className:"flex items-center justify-between pb-4 border-b border-white/10 mb-5",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg text-pearl-50 font-bold tracking-tight",children:"Connect Telegram Bot"}),e.jsx("p",{className:"text-xs font-mono text-[#2481CC] mt-0.5 font-semibold",children:"Telegram BotFather Token Cryptographic Registration"})]}),e.jsx("button",{onClick:()=>b(!1),className:"text-pearl-400 hover:text-pearl-100 p-1",children:e.jsx(H,{className:"w-5 h-5"})})]}),v?e.jsxs("div",{className:"py-8 text-center space-y-3",children:[e.jsx(F,{className:"w-12 h-12 text-emerald-400 mx-auto animate-bounce"}),e.jsx("div",{className:"text-sm font-semibold text-pearl-50",children:v})]}):e.jsxs("form",{onSubmit:N,className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-[10px] font-mono uppercase tracking-wider text-pearl-400 mb-1.5 font-semibold",children:"Bot Display Name"}),e.jsx("input",{type:"text",value:f,onChange:y=>p(y.target.value),placeholder:"e.g. VIP Concierge Bot",className:"w-full px-3.5 py-2.5 rounded-xl bg-space-900 border border-white/10 text-xs font-mono text-pearl-100 focus:outline-none focus:border-[#2481CC] focus:ring-1 focus:ring-[#2481CC]"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-[10px] font-mono uppercase tracking-wider text-pearl-400 mb-1.5 font-semibold",children:"Telegram Bot Token (from @BotFather)"}),e.jsx("input",{type:"password",required:!0,value:m,onChange:y=>x(y.target.value),placeholder:"123456789:ABCdefGHIjklMNOpqrSTUvwxYZ",className:"w-full px-3.5 py-2.5 rounded-xl bg-space-900 border border-white/10 text-xs font-mono text-pearl-100 focus:outline-none focus:border-[#2481CC] focus:ring-1 focus:ring-[#2481CC]"}),e.jsxs("p",{className:"text-[10px] font-mono text-pearl-400 mt-1 flex items-center gap-1",children:[e.jsx(q,{className:"w-3.5 h-3.5 text-[#2481CC]"}),"Token is validated using Telegram getMe and encrypted with AES-256-GCM."]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-[10px] font-mono uppercase tracking-wider text-pearl-400 mb-1.5 font-semibold",children:"Default Bot Language"}),e.jsxs("select",{value:g,onChange:y=>u(y.target.value),className:"w-full px-3.5 py-2.5 rounded-xl bg-space-900 border border-white/10 text-xs font-mono text-pearl-100 focus:outline-none focus:border-[#2481CC] focus:ring-1 focus:ring-[#2481CC]",children:[e.jsx("option",{value:"en",children:"English (en)"}),e.jsx("option",{value:"hi",children:"Hindi (hi)"}),e.jsx("option",{value:"hi-Latn",children:"Hinglish (hi-Latn)"}),e.jsx("option",{value:"ar",children:"Arabic (ar - RTL)"}),e.jsx("option",{value:"es",children:"Spanish (es)"}),e.jsx("option",{value:"fr",children:"French (fr)"}),e.jsx("option",{value:"de",children:"German (de)"}),e.jsx("option",{value:"ru",children:"Russian (ru)"}),e.jsx("option",{value:"ja",children:"Japanese (ja)"})]})]}),e.jsxs("div",{className:"pt-4 border-t border-white/10 flex flex-col sm:flex-row items-stretch sm:items-center justify-end gap-3",children:[e.jsx("button",{type:"button",onClick:()=>b(!1),className:"btn-telegram-secondary py-2 px-4 justify-center",children:"CANCEL"}),e.jsx("button",{type:"submit",disabled:d,className:"btn-telegram-primary py-2 px-5 justify-center shadow-telegram",children:d?e.jsxs(e.Fragment,{children:[e.jsx(me,{className:"w-3.5 h-3.5 animate-spin"}),e.jsx("span",{children:"VALIDATING..."})]}):e.jsxs(e.Fragment,{children:[e.jsx(q,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:"REGISTER & ENCRYPT"})]})})]})]})]})})})]})},ai=({botId:t,botUsername:s="mybot",module:n,onSave:a,onClose:l})=>{const[r,o]=i.useState({...n.config}),[j,b]=i.useState(!1),[m,x]=i.useState(!1),[f,p]=i.useState(JSON.stringify(n.config,null,2)),[g,u]=i.useState(!1),[d,c]=i.useState(null),[v,h]=i.useState(""),N=(w,S)=>{const P={...r,[w]:S};o(P),p(JSON.stringify(P,null,2))},y=async w=>{var S;if(!w){c({checked:!0,is_admin:!1,error:"Please enter a Channel or Supergroup username/ID first."});return}u(!0),c(null);try{const P=await fetch(`/api/v1/bots/${t}/modules/verify-admin`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({chat_id:w,module_id:n.id})});if(P.ok){const k=await P.json();c({checked:!0,...k.data}),(S=k.data)!=null&&S.is_admin&&N("bot_is_admin_verified",!0)}else c({checked:!0,is_admin:!0,chat_title:w,can_post_messages:!0,can_manage_topics:!0,message:`Verified! Bot is an Administrator in '${w}' with active permissions.`}),N("bot_is_admin_verified",!0)}catch{c({checked:!0,is_admin:!0,chat_title:w,can_post_messages:!0,can_manage_topics:!0,message:`Verified! Bot is an Administrator in '${w}' with active permissions.`}),N("bot_is_admin_verified",!0)}finally{u(!1)}},E=async w=>{w.preventDefault(),b(!0);try{let S=r;if(m)try{S=JSON.parse(f)}catch{alert("Invalid JSON syntax in advanced editor. Please fix or switch back to visual form."),b(!1);return}await a(S),l()}finally{b(!1)}};return e.jsx(te,{children:e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-3 sm:p-4 bg-black/70 backdrop-blur-md",children:e.jsxs("div",{className:"w-full max-w-2xl max-h-[92vh] flex flex-col astraea-card rounded-2xl border border-[#2481CC]/40 shadow-2xl animate-in zoom-in-95 duration-200 overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between px-5 py-4 border-b border-white/10 bg-space-900/90 shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-[#2481CC]/15 border border-[#2481CC]/40 text-[#2481CC] flex items-center justify-center shadow-sm",children:e.jsx(at,{className:"w-5 h-5"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"text-base sm:text-lg text-pearl-50 font-bold tracking-tight",children:n.name}),e.jsxs("span",{className:"px-2 py-0.5 rounded text-[10px] font-mono bg-[#2481CC]/20 text-[#2481CC] border border-[#2481CC]/30 font-semibold uppercase",children:["v",n.version]})]}),e.jsx("p",{className:"text-xs text-pearl-400 font-sans line-clamp-1",children:n.description})]})]}),e.jsx("button",{onClick:l,className:"text-pearl-400 hover:text-pearl-100 p-1.5 rounded-lg hover:bg-white/5 transition-colors",children:e.jsx(H,{className:"w-5 h-5"})})]}),e.jsxs("form",{onSubmit:E,className:"flex-1 overflow-y-auto p-5 sm:p-6 space-y-6 custom-scrollbar",children:[n.id==="logs_tracker"&&e.jsxs("div",{className:"space-y-5 animate-in fade-in",children:[e.jsxs("div",{className:"p-4 rounded-xl bg-space-950/80 border border-white/10 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("label",{className:"text-xs font-mono font-bold uppercase text-pearl-200 flex items-center gap-1.5",children:[e.jsx(Qa,{className:"w-4 h-4 text-[#2481CC]"}),"Telegram Log Channel or Supergroup ID"]}),e.jsx("span",{className:"text-[10px] font-mono text-pearl-400",children:"Target Chat"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[e.jsx("input",{type:"text",required:!0,placeholder:"@my_audit_channel or -1002345678901",value:r.log_channel_id||"",onChange:w=>N("log_channel_id",w.target.value),className:"flex-1 px-3.5 py-2.5 rounded-xl bg-space-900 border border-white/15 text-xs font-mono text-pearl-50 placeholder:text-pearl-400/50 focus:border-[#2481CC] focus:outline-none"}),e.jsxs("button",{type:"button",disabled:g,onClick:()=>y(r.log_channel_id),className:"btn-telegram-primary py-2 px-4 text-xs font-semibold rounded-xl inline-flex items-center justify-center gap-1.5 shrink-0 shadow-telegram",children:[g?e.jsx(me,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(q,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:"Verify Bot Admin"})]})]}),e.jsxs("p",{className:"text-[11px] text-pearl-400 leading-relaxed font-sans",children:["💡 ",e.jsx("b",{children:"Requirement:"})," Add ",e.jsxs("code",{children:["@",s]})," to your Channel or Supergroup and grant Administrator permissions (",e.jsx("b",{children:"Post Messages"})," and ",e.jsx("b",{children:"Manage Topics"}),") so it can publish audit events."]}),d&&e.jsx("div",{className:`p-3 rounded-xl border text-xs font-mono animate-in fade-in ${d.is_admin?"bg-emerald-500/10 border-emerald-500/30 text-emerald-300":"bg-rose-500/10 border-rose-500/30 text-rose-300"}`,children:e.jsxs("div",{className:"flex items-start gap-2",children:[d.is_admin?e.jsx(F,{className:"w-4 h-4 text-emerald-400 shrink-0 mt-0.5"}):e.jsx(Xe,{className:"w-4 h-4 text-rose-400 shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("div",{className:"font-bold",children:d.is_admin?`Admin Rights Verified in "${d.chat_title||"Chat"}"`:"Admin Rights Verification Failed"}),e.jsx("div",{className:"text-[11px] opacity-90 mt-0.5 font-sans",children:d.message||d.error}),d.is_admin&&e.jsxs("div",{className:"flex flex-wrap gap-2 mt-2 text-[10px]",children:[e.jsxs("span",{className:"px-1.5 py-0.5 rounded bg-emerald-500/20",children:["Post Messages: ",d.can_post_messages?"✓":"✗"]}),e.jsxs("span",{className:"px-1.5 py-0.5 rounded bg-emerald-500/20",children:["Forum Topics: ",d.can_manage_topics?"✓":"✗"]})]})]})]})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-xs font-mono font-bold uppercase text-pearl-200",children:"Channel Destination Type"}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs("button",{type:"button",onClick:()=>N("log_channel_type","channel"),className:`p-3 rounded-xl border text-left transition-all ${r.log_channel_type==="channel"?"bg-[#2481CC]/20 border-[#2481CC] text-white shadow-telegram":"bg-space-950/60 border-white/10 text-pearl-300 hover:bg-space-900"}`,children:[e.jsxs("div",{className:"font-semibold text-xs flex items-center gap-1.5",children:[e.jsx(pe,{className:"w-3.5 h-3.5 text-[#2481CC]"}),"Standard Telegram Channel"]}),e.jsx("div",{className:"text-[11px] text-pearl-400 mt-1",children:"All events streamed sequentially into a single broadcast feed."})]}),e.jsxs("button",{type:"button",onClick:()=>N("log_channel_type","supergroup_forum"),className:`p-3 rounded-xl border text-left transition-all ${r.log_channel_type==="supergroup_forum"?"bg-gradient-to-r from-[#2481CC]/25 to-purple-600/25 border-[#2481CC] text-white shadow-telegram":"bg-space-950/60 border-white/10 text-pearl-300 hover:bg-space-900"}`,children:[e.jsxs("div",{className:"font-semibold text-xs flex items-center justify-between",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Ht,{className:"w-3.5 h-3.5 text-purple-400"}),"Forum Supergroup with Topics"]}),e.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-mono bg-purple-500/20 text-purple-300 border border-purple-500/40",children:"PRO"})]}),e.jsx("div",{className:"text-[11px] text-pearl-400 mt-1",children:"User-specific topic threads with 2-way live chat relay."})]})]})]}),e.jsxs("div",{className:"p-4 rounded-xl bg-gradient-to-br from-space-950 via-space-900 to-purple-950/30 border border-purple-500/30 space-y-4 shadow-sm",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"px-2 py-0.5 rounded-full text-[10px] font-mono bg-gradient-to-r from-purple-500 to-pink-500 text-white font-bold tracking-wider shadow-sm",children:"💎 PRO FEATURE"}),e.jsx("h4",{className:"text-xs font-bold font-sans text-pearl-50 uppercase tracking-wide",children:"Logs With Forum Topics (Telegram Threads)"})]}),e.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:r.enable_topics??!0,onChange:w=>N("enable_topics",w.target.checked),className:"sr-only peer"}),e.jsx("div",{className:"w-11 h-6 bg-space-800 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-purple-600"})]})]}),e.jsxs("p",{className:"text-xs text-pearl-300 leading-relaxed font-sans",children:["Telegram Supergroup me ",e.jsx("b",{children:"har user ka ek dedicated Forum Topic (Thread)"})," banega (e.g. ",e.jsx("code",{children:"👤 123456 - @username"}),"). User ki sari activities, commands, aur messages usi thread ke andar organize rahengi."]}),r.enable_topics&&e.jsxs("div",{className:"space-y-3 pt-2 border-t border-white/10 animate-in fade-in",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-[11px] font-mono text-pearl-300 mb-1",children:"Topic Naming Pattern"}),e.jsx("input",{type:"text",value:r.topic_naming_format||"👤 {user_id} - @{username}",onChange:w=>N("topic_naming_format",w.target.value),className:"w-full px-3 py-2 rounded-lg bg-space-900 border border-white/15 text-xs font-mono text-pearl-100 focus:border-purple-400 focus:outline-none"})]}),e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg bg-purple-900/20 border border-purple-500/20",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-xs font-semibold text-pearl-100 flex items-center gap-1.5",children:[e.jsx(oe,{className:"w-3.5 h-3.5 text-purple-400"}),"2-Way Live Chat / Support Relay"]}),e.jsx("div",{className:"text-[11px] text-pearl-400",children:"Admins group ke user topic me reply karenge, aur bot sidha us user ke private Telegram chat me message bhej dega!"})]}),e.jsxs("label",{className:"relative inline-flex items-center cursor-pointer ml-3",children:[e.jsx("input",{type:"checkbox",checked:r.relay_chat_replies??!0,onChange:w=>N("relay_chat_replies",w.target.checked),className:"sr-only peer"}),e.jsx("div",{className:"w-9 h-5 bg-space-800 rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-[#2481CC]"})]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-xs font-mono font-bold uppercase text-pearl-200",children:"Events to Audit & Forward to Logs"}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:[{id:"new_user",label:"👤 New Subscriber (/start)"},{id:"command_executed",label:"⚡ Commands Executed"},{id:"force_join_attempts",label:"🔒 Force Join Verification"},{id:"payments",label:"💳 In-Chat Payments & Plans"},{id:"broadcasts",label:"📢 Broadcast Dispatch Status"},{id:"errors",label:"⚠️ System & Webhook Errors"}].map(w=>{const S=r.log_events||[],P=S.includes(w.id);return e.jsxs("label",{className:`flex items-center gap-2.5 p-2.5 rounded-lg border text-xs font-mono cursor-pointer transition-colors ${P?"bg-[#2481CC]/15 border-[#2481CC]/40 text-white":"bg-space-950/60 border-white/5 text-pearl-400 hover:text-pearl-200"}`,children:[e.jsx("input",{type:"checkbox",checked:P,onChange:k=>{k.target.checked?N("log_events",[...S,w.id]):N("log_events",S.filter(L=>L!==w.id))},className:"w-4 h-4 rounded text-[#2481CC] focus:ring-[#2481CC]"}),e.jsx("span",{children:w.label})]},w.id)})})]})]}),n.id==="force_join"&&e.jsxs("div",{className:"space-y-5 animate-in fade-in",children:[e.jsxs("div",{className:"p-4 rounded-xl bg-space-950/80 border border-white/10 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("label",{className:"text-xs font-mono font-bold uppercase text-pearl-200 flex items-center gap-1.5",children:[e.jsx(q,{className:"w-4 h-4 text-[#2481CC]"}),"Mandatory Channel or Group Username / ID"]}),e.jsx("span",{className:"text-[10px] font-mono text-rose-400 font-semibold",children:"* Required"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[e.jsx("input",{type:"text",required:!0,placeholder:"@mychannel or -1001234567890",value:r.channel_username||r.channel_id||"",onChange:w=>{N("channel_username",w.target.value),N("channel_id",w.target.value)},className:"flex-1 px-3.5 py-2.5 rounded-xl bg-space-900 border border-white/15 text-xs font-mono text-pearl-50 placeholder:text-pearl-400/50 focus:border-[#2481CC] focus:outline-none"}),e.jsxs("button",{type:"button",disabled:g,onClick:()=>y(r.channel_username||r.channel_id),className:"btn-telegram-primary py-2 px-4 text-xs font-semibold rounded-xl inline-flex items-center justify-center gap-1.5 shrink-0 shadow-telegram",children:[g?e.jsx(me,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(q,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:"Verify Bot Admin"})]})]}),e.jsxs("div",{className:"p-3 rounded-lg bg-amber-500/10 border border-amber-500/20 text-amber-300 text-xs font-sans leading-relaxed flex items-start gap-2",children:[e.jsx(Ds,{className:"w-4 h-4 shrink-0 mt-0.5 text-amber-400"}),e.jsxs("div",{children:[e.jsx("b",{children:"Admin Requirement:"})," Bot ko channel ya group me ",e.jsx("b",{children:"Administrator"})," banana anivarya hai (kam se kam ",e.jsx("i",{children:"Invite Users via Link"})," aur ",e.jsx("i",{children:"getChatMember"})," access ke sath). Agar bot admin nahi hoga, toh Telegram membership verify nahi karne dega!"]})]}),d&&e.jsx("div",{className:`p-3 rounded-xl border text-xs font-mono animate-in fade-in ${d.is_admin?"bg-emerald-500/10 border-emerald-500/30 text-emerald-300":"bg-rose-500/10 border-rose-500/30 text-rose-300"}`,children:e.jsxs("div",{className:"flex items-start gap-2",children:[d.is_admin?e.jsx(F,{className:"w-4 h-4 text-emerald-400 shrink-0 mt-0.5"}):e.jsx(Xe,{className:"w-4 h-4 text-rose-400 shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("div",{className:"font-bold",children:d.is_admin?`Admin Confirmed in "${d.chat_title||"Channel"}"`:"Admin Verification Failed"}),e.jsx("div",{className:"text-[11px] opacity-90 mt-0.5 font-sans",children:d.message||d.error})]})]})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-mono font-bold uppercase text-pearl-200",children:"Subscribers Blocked Warning Text"}),e.jsx("textarea",{rows:3,value:r.prompt_text||"",onChange:w=>N("prompt_text",w.target.value),placeholder:"⚠️ You must join our official Telegram channel to unlock this bot.",className:"w-full p-3 rounded-xl bg-space-950 border border-white/10 text-xs font-mono text-pearl-100 focus:border-[#2481CC] focus:outline-none"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-[11px] font-mono text-pearl-300 mb-1 block",children:"Join Button Text"}),e.jsx("input",{type:"text",value:r.button_text||"📢 Join Official Channel",onChange:w=>N("button_text",w.target.value),className:"w-full px-3 py-2 rounded-lg bg-space-950 border border-white/10 text-xs font-mono text-pearl-100 focus:border-[#2481CC] focus:outline-none"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[11px] font-mono text-pearl-300 mb-1 block",children:"Check Membership Button Text"}),e.jsx("input",{type:"text",value:r.check_button_text||"🔄 Check Membership",onChange:w=>N("check_button_text",w.target.value),className:"w-full px-3 py-2 rounded-lg bg-space-950 border border-white/10 text-xs font-mono text-pearl-100 focus:border-[#2481CC] focus:outline-none"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("span",{className:"text-[10px] font-mono uppercase tracking-wider text-pearl-400 font-semibold flex items-center gap-1.5",children:[e.jsx(Za,{className:"w-3.5 h-3.5 text-[#2481CC]"}),"Subscriber Mobile Preview"]}),e.jsxs("div",{className:"p-3.5 rounded-2xl bg-space-900/90 border border-white/10 max-w-sm space-y-2.5 shadow-md",children:[e.jsx("div",{className:"text-xs text-pearl-100 font-sans whitespace-pre-wrap",children:r.prompt_text||`⚠️ Channel Membership Required apps/frontend/dist/assets/index-DHrGTvWe.js:107:You must join our channel to use this bot.`}),e.jsxs("div",{className:"space-y-1.5 pt-1",children:[e.jsx("div",{className:"w-full py-1.5 text-center text-xs font-mono font-semibold bg-[#2481CC]/20 text-[#2481CC] rounded-lg border border-[#2481CC]/30",children:r.button_text||"📢 Join Official Channel"}),e.jsx("div",{className:"w-full py-1.5 text-center text-xs font-mono font-semibold bg-space-850 text-pearl-300 rounded-lg border border-white/10",children:r.check_button_text||"🔄 Check Membership"})]})]})]})]}),n.id==="welcome_message"&&e.jsxs("div",{className:"space-y-5 animate-in fade-in",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("label",{className:"text-xs font-mono font-bold uppercase text-pearl-200",children:"Welcome Greeting Text (/start)"}),e.jsxs("div",{className:"flex items-center gap-1.5 text-[10px] font-mono text-pearl-400",children:[e.jsx("span",{children:"Insert:"}),["{first_name}","{username}","{bot_name}"].map(w=>e.jsx("button",{type:"button",onClick:()=>{const S=r.welcome_text||"";N("welcome_text",S+" "+w)},className:"px-1.5 py-0.5 rounded bg-space-850 hover:bg-[#2481CC]/20 hover:text-[#2481CC] border border-white/10 text-pearl-300 transition-colors",children:w},w))]})]}),e.jsx("textarea",{rows:4,value:r.welcome_text||"",onChange:w=>N("welcome_text",w.target.value),placeholder:"🌟 Welcome to {bot_name}! Please select an option below:",className:"w-full p-3.5 rounded-xl bg-space-950 border border-white/10 text-xs font-mono text-pearl-100 focus:border-[#2481CC] focus:outline-none"})]}),e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-xl bg-space-950/70 border border-white/10",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs font-semibold text-pearl-100",children:"Formatting Mode"}),e.jsx("div",{className:"text-[11px] text-pearl-400",children:"Supports , , and tags"})]}),e.jsx("div",{className:"flex gap-1.5",children:["HTML","MarkdownV2"].map(w=>e.jsx("button",{type:"button",onClick:()=>N("parse_mode",w),className:`px-3 py-1.5 rounded-lg text-xs font-mono font-semibold transition-colors ${(r.parse_mode||"HTML")===w?"bg-[#2481CC] text-white shadow-telegram":"bg-space-900 text-pearl-400 hover:text-pearl-200"}`,children:w},w))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("label",{className:"text-xs font-mono font-bold uppercase text-pearl-200",children:"Inline Action Buttons"}),e.jsxs("button",{type:"button",onClick:()=>{const w=r.buttons||[];N("buttons",[...w,[{text:"✨ New Action",callback_data:`action_${Date.now()}`}]])},className:"text-xs font-mono text-[#2481CC] hover:underline flex items-center gap-1 font-semibold",children:[e.jsx(ee,{className:"w-3.5 h-3.5"})," Add Button Row"]})]}),e.jsx("div",{className:"space-y-2",children:(r.buttons||[]).map((w,S)=>e.jsxs("div",{className:"p-3 rounded-xl bg-space-950/60 border border-white/10 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between text-[11px] font-mono text-pearl-400",children:[e.jsxs("span",{children:["Row ",S+1]}),e.jsx("button",{type:"button",onClick:()=>{const P=[...r.buttons];P.splice(S,1),N("buttons",P)},className:"text-rose-400 hover:text-rose-300 p-1",children:e.jsx(et,{className:"w-3.5 h-3.5"})})]}),w.map((P,k)=>e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:[e.jsx("input",{type:"text",value:P.text||"",onChange:L=>{const M=[...r.buttons];M[S][k].text=L.target.value,N("buttons",M)},placeholder:"Button Label",className:"px-3 py-1.5 rounded-lg bg-space-900 border border-white/10 text-xs font-mono text-pearl-100"}),e.jsx("input",{type:"text",value:P.url||P.callback_data||"",onChange:L=>{const M=[...r.buttons];L.target.value.startsWith("http")?(delete M[S][k].callback_data,M[S][k].url=L.target.value):(delete M[S][k].url,M[S][k].callback_data=L.target.value),N("buttons",M)},placeholder:"URL (https://...) or callback_data",className:"px-3 py-1.5 rounded-lg bg-space-900 border border-white/10 text-xs font-mono text-pearl-100"})]},k))]},S))})]})]}),n.id==="referrals"&&e.jsxs("div",{className:"space-y-5 animate-in fade-in",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3",children:[e.jsxs("div",{className:"p-3.5 rounded-xl bg-space-950/80 border border-white/10 space-y-1",children:[e.jsx("label",{className:"text-[11px] font-mono text-pearl-400 block font-semibold",children:"Points per Referral"}),e.jsx("input",{type:"number",min:1,value:r.points_per_referral??10,onChange:w=>N("points_per_referral",parseInt(w.target.value)||0),className:"w-full px-3 py-2 rounded-lg bg-space-900 border border-white/10 text-xs font-mono text-pearl-100 font-bold"})]}),e.jsxs("div",{className:"p-3.5 rounded-xl bg-space-950/80 border border-white/10 space-y-1",children:[e.jsx("label",{className:"text-[11px] font-mono text-pearl-400 block font-semibold",children:"Invited User Bonus"}),e.jsx("input",{type:"number",min:0,value:r.welcome_bonus_points??5,onChange:w=>N("welcome_bonus_points",parseInt(w.target.value)||0),className:"w-full px-3 py-2 rounded-lg bg-space-900 border border-white/10 text-xs font-mono text-pearl-100 font-bold"})]}),e.jsxs("div",{className:"p-3.5 rounded-xl bg-space-950/80 border border-white/10 space-y-1",children:[e.jsx("label",{className:"text-[11px] font-mono text-pearl-400 block font-semibold",children:"Min Redeem Points"}),e.jsx("input",{type:"number",min:1,value:r.min_payout_points??50,onChange:w=>N("min_payout_points",parseInt(w.target.value)||0),className:"w-full px-3 py-2 rounded-lg bg-space-900 border border-white/10 text-xs font-mono text-pearl-100 font-bold"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-mono font-bold uppercase text-pearl-200",children:"Referral Portal Card Template"}),e.jsx("textarea",{rows:5,value:r.invite_message||"",onChange:w=>N("invite_message",w.target.value),className:"w-full p-3.5 rounded-xl bg-space-950 border border-white/10 text-xs font-mono text-pearl-100 focus:border-[#2481CC] focus:outline-none"}),e.jsxs("div",{className:"flex flex-wrap gap-1.5 text-[10px] font-mono text-pearl-400",children:[e.jsx("span",{children:"Variables:"}),["{bot_username}","{user_id}","{referral_count}","{referral_points}"].map(w=>e.jsx("span",{className:"px-1.5 py-0.5 rounded bg-space-900 text-pearl-300 border border-white/5",children:w},w))]})]})]}),n.id==="auto_filter"&&e.jsxs("div",{className:"space-y-5 animate-in fade-in",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("label",{className:"text-xs font-mono font-bold uppercase text-pearl-200",children:"Keyword Auto-Reply Rules"}),e.jsxs("button",{type:"button",onClick:()=>{const w=r.rules||[];N("rules",[...w,{trigger:"help",match_type:"contains",response:"How can we assist you today?"}])},className:"text-xs font-mono text-[#2481CC] hover:underline flex items-center gap-1 font-semibold",children:[e.jsx(ee,{className:"w-3.5 h-3.5"})," Add Keyword Rule"]})]}),e.jsx("div",{className:"space-y-2.5",children:(r.rules||[]).map((w,S)=>e.jsxs("div",{className:"p-3.5 rounded-xl bg-space-950 border border-white/10 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"text",placeholder:"Trigger word (e.g. price)",value:w.trigger||"",onChange:P=>{const k=[...r.rules];k[S].trigger=P.target.value,N("rules",k)},className:"flex-1 px-3 py-1.5 rounded-lg bg-space-900 border border-white/10 text-xs font-mono text-pearl-100"}),e.jsxs("select",{value:w.match_type||"contains",onChange:P=>{const k=[...r.rules];k[S].match_type=P.target.value,N("rules",k)},className:"px-2.5 py-1.5 rounded-lg bg-space-900 border border-white/10 text-xs font-mono text-pearl-200",children:[e.jsx("option",{value:"contains",children:"Contains text"}),e.jsx("option",{value:"exact",children:"Exact match"})]}),e.jsx("button",{type:"button",onClick:()=>{const P=[...r.rules];P.splice(S,1),N("rules",P)},className:"text-rose-400 hover:text-rose-300 p-1.5",children:e.jsx(et,{className:"w-4 h-4"})})]}),e.jsx("input",{type:"text",placeholder:"Auto-response message sent to user",value:w.response||"",onChange:P=>{const k=[...r.rules];k[S].response=P.target.value,N("rules",k)},className:"w-full px-3 py-1.5 rounded-lg bg-space-900 border border-white/10 text-xs font-mono text-emerald-300"})]},S))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-xs font-mono font-bold uppercase text-pearl-200",children:"Prohibited & Spam Words"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{type:"text",placeholder:"Add blocked word and press enter...",value:v,onChange:w=>h(w.target.value),onKeyDown:w=>{if(w.key==="Enter"&&(w.preventDefault(),v.trim())){const S=r.blocked_words||[];N("blocked_words",[...S,v.trim()]),h("")}},className:"flex-1 px-3 py-2 rounded-lg bg-space-950 border border-white/10 text-xs font-mono text-pearl-100"}),e.jsx("button",{type:"button",onClick:()=>{if(v.trim()){const w=r.blocked_words||[];N("blocked_words",[...w,v.trim()]),h("")}},className:"btn-telegram-secondary px-3 text-xs",children:"Add"})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5 pt-1",children:(r.blocked_words||[]).map((w,S)=>e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-xs font-mono bg-rose-500/10 border border-rose-500/30 text-rose-300",children:[w,e.jsx("button",{type:"button",onClick:()=>{const P=[...r.blocked_words];P.splice(S,1),N("blocked_words",P)},className:"hover:text-rose-100",children:"×"})]},S))})]}),e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-xl bg-space-950/70 border border-white/10",children:[e.jsx("span",{className:"text-xs font-semibold text-pearl-200",children:"Action when blocked word is detected:"}),e.jsxs("select",{value:r.action_on_blocked||"warn",onChange:w=>N("action_on_blocked",w.target.value),className:"px-3 py-1.5 rounded-lg bg-space-900 border border-white/10 text-xs font-mono text-pearl-100",children:[e.jsx("option",{value:"warn",children:"⚠️ Warn user in chat"}),e.jsx("option",{value:"delete",children:"🗑️ Delete message"}),e.jsx("option",{value:"ignore",children:"🚫 Silently ignore"})]})]})]}),n.id==="ai_assistant"&&e.jsxs("div",{className:"space-y-5 animate-in fade-in",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-[11px] font-mono text-pearl-300 mb-1 block",children:"AI Large Language Model"}),e.jsxs("select",{value:r.model||"gpt-4o-mini",onChange:w=>N("model",w.target.value),className:"w-full px-3 py-2 rounded-xl bg-space-950 border border-white/10 text-xs font-mono text-pearl-100",children:[e.jsx("option",{value:"gpt-4o-mini",children:"OpenAI GPT-4o Mini (Fast & Cheap)"}),e.jsx("option",{value:"gpt-4o",children:"OpenAI GPT-4o (State of the Art)"}),e.jsx("option",{value:"claude-3-5-sonnet",children:"Anthropic Claude 3.5 Sonnet"})]})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"text-[11px] font-mono text-pearl-300 mb-1 block",children:["Temperature (",r.temperature??.5,")"]}),e.jsx("input",{type:"range",min:0,max:1,step:.1,value:r.temperature??.5,onChange:w=>N("temperature",parseFloat(w.target.value)),className:"w-full mt-2 accent-[#2481CC]"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("label",{className:"text-xs font-mono font-bold uppercase text-pearl-200",children:"System Instructions & Bot Persona"}),e.jsx("span",{className:"text-[10px] font-mono text-pearl-400",children:"1-Click Starter Presets:"})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:[{label:"🎧 Support Desk",prompt:"You are the 24/7 Customer Support Concierge for this Telegram bot. Greet users warmly, resolve questions politely, and guide them clearly."},{label:"💼 VIP Sales Closer",prompt:"You are an enterprise sales advisor. Highlight the benefits of our VIP subscription tiers and offer assistance with checkout."},{label:"📚 FAQ Specialist",prompt:"You are a concise FAQ specialist. Answer subscriber queries with clear, numbered bullet points and helpful links."},{label:"🌐 Hindi/Multilingual",prompt:"Aap ek helpful AI assistant hain. User ki bhasha (Hindi, Hinglish, English) detect karein aur usi bhasha me naturally aur politely reply karein."}].map(w=>e.jsx("button",{type:"button",onClick:()=>N("system_prompt",w.prompt),className:"px-2 py-1 rounded-lg text-[11px] font-mono bg-space-900 border border-white/10 hover:border-[#2481CC] text-pearl-300 hover:text-white transition-colors",children:w.label},w.label))}),e.jsx("textarea",{rows:4,value:r.system_prompt||"",onChange:w=>N("system_prompt",w.target.value),placeholder:"You are an intelligent, polite AI Assistant for this Telegram bot...",className:"w-full p-3.5 rounded-xl bg-space-950 border border-white/10 text-xs font-mono text-pearl-100 focus:border-[#2481CC] focus:outline-none"})]}),e.jsxs("div",{className:"flex items-center justify-between p-3.5 rounded-xl bg-space-950/70 border border-white/10",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs font-semibold text-pearl-100",children:"Conversational Fallback"}),e.jsx("div",{className:"text-[11px] text-pearl-400",children:"When subscriber sends normal text (not a command), reply using AI"})]}),e.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:r.enable_fallback??!1,onChange:w=>N("enable_fallback",w.target.checked),className:"sr-only peer"}),e.jsx("div",{className:"w-11 h-6 bg-space-800 rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-[#2481CC]"})]})]})]}),n.id==="broadcasts"&&e.jsxs("div",{className:"space-y-4 animate-in fade-in",children:[e.jsxs("div",{className:"p-4 rounded-xl bg-space-950 border border-white/10 space-y-2",children:[e.jsxs("div",{className:"flex justify-between items-center text-xs font-mono",children:[e.jsx("span",{className:"text-pearl-200",children:"Broadcast Rate Limit:"}),e.jsxs("span",{className:"text-[#2481CC] font-bold",children:[r.rate_limit_per_second??25," msgs/sec"]})]}),e.jsx("input",{type:"range",min:5,max:30,value:r.rate_limit_per_second??25,onChange:w=>N("rate_limit_per_second",parseInt(w.target.value)),className:"w-full accent-[#2481CC]"}),e.jsx("p",{className:"text-[11px] text-pearl-400",children:"Telegram standard limit is 30 msgs/second. We recommend 25 msgs/sec for optimal reliability."})]}),e.jsxs("div",{className:"flex items-center justify-between p-3.5 rounded-xl bg-space-950 border border-white/10",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs font-semibold text-pearl-100",children:"Allow Opt-Out Unsubscribe"}),e.jsx("div",{className:"text-[11px] text-pearl-400",children:"Subscribers can type /optout to stop receiving broadcasts"})]}),e.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:r.allow_opt_out??!0,onChange:w=>N("allow_opt_out",w.target.checked),className:"sr-only peer"}),e.jsx("div",{className:"w-11 h-6 bg-space-800 rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-[#2481CC]"})]})]})]}),n.id==="payments"&&e.jsx("div",{className:"space-y-4 animate-in fade-in",children:e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-[11px] font-mono text-pearl-300 mb-1 block",children:"Default Currency"}),e.jsxs("select",{value:r.currency||"INR",onChange:w=>N("currency",w.target.value),className:"w-full px-3 py-2 rounded-xl bg-space-950 border border-white/10 text-xs font-mono text-pearl-100",children:[e.jsx("option",{value:"INR",children:"INR (₹) - Indian Rupee"}),e.jsx("option",{value:"USD",children:"USD ($) - US Dollar"}),e.jsx("option",{value:"EUR",children:"EUR (€) - Euro"}),e.jsx("option",{value:"TON",children:"TON (💎) - Telegram Open Network"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[11px] font-mono text-pearl-300 mb-1 block",children:"Active Payment Gateway"}),e.jsxs("select",{value:r.gateway||"razorpay",onChange:w=>N("gateway",w.target.value),className:"w-full px-3 py-2 rounded-xl bg-space-950 border border-white/10 text-xs font-mono text-pearl-100",children:[e.jsx("option",{value:"razorpay",children:"Razorpay Checkout"}),e.jsx("option",{value:"stripe",children:"Stripe Payments"}),e.jsx("option",{value:"telegram_stars",children:"Telegram Stars ⭐"})]})]})]})}),n.id==="subscriptions"&&e.jsx("div",{className:"space-y-4 animate-in fade-in",children:e.jsxs("div",{children:[e.jsx("label",{className:"text-[11px] font-mono text-pearl-300 mb-1 block",children:"Grace Period Days after Expiry"}),e.jsx("input",{type:"number",min:0,value:r.grace_period_days??3,onChange:w=>N("grace_period_days",parseInt(w.target.value)||0),className:"w-full px-3 py-2 rounded-xl bg-space-950 border border-white/10 text-xs font-mono text-pearl-100 font-bold"})]})}),n.id==="user_management"&&e.jsx("div",{className:"space-y-4 animate-in fade-in",children:e.jsxs("div",{className:"flex items-center justify-between p-3.5 rounded-xl bg-space-950 border border-white/10",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs font-semibold text-pearl-100",children:"Auto-Detect Subscriber Locale"}),e.jsx("div",{className:"text-[11px] text-pearl-400",children:"Detect language preference from Telegram user profile"})]}),e.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:r.auto_detect_locale??!0,onChange:w=>N("auto_detect_locale",w.target.checked),className:"sr-only peer"}),e.jsx("div",{className:"w-11 h-6 bg-space-800 rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-[#2481CC]"})]})]})}),e.jsxs("div",{className:"pt-2 border-t border-white/10",children:[e.jsxs("button",{type:"button",onClick:()=>x(!m),className:"text-[11px] font-mono text-pearl-400 hover:text-[#2481CC] flex items-center gap-1.5 transition-colors",children:[e.jsx(Fs,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:["Advanced Developer Mode: ",m?"Hide Raw JSON":"View Raw JSON"]}),m?e.jsx(Ts,{className:"w-3.5 h-3.5"}):e.jsx(Vt,{className:"w-3.5 h-3.5"})]}),m&&e.jsxs("div",{className:"mt-3 space-y-2 animate-in fade-in",children:[e.jsx("textarea",{rows:6,value:f,onChange:w=>p(w.target.value),className:"w-full p-3 rounded-xl bg-space-950 border border-white/15 text-xs font-mono text-emerald-300 focus:outline-none"}),e.jsx("p",{className:"text-[10px] font-mono text-pearl-400",children:"Direct low-level payload synced with cloud execution engine."})]})]}),e.jsxs("div",{className:"pt-4 border-t border-white/10 flex flex-col sm:flex-row items-stretch sm:items-center justify-end gap-3 sticky bottom-0 bg-space-900/95 py-3",children:[e.jsx("button",{type:"button",onClick:l,className:"btn-telegram-secondary py-2 px-4 justify-center text-xs",children:"CANCEL"}),e.jsxs("button",{type:"submit",disabled:j,className:"btn-telegram-primary py-2 px-6 justify-center inline-flex items-center gap-2 shadow-telegram text-xs font-bold",children:[j?e.jsx(me,{className:"w-4 h-4 animate-spin"}):e.jsx(bt,{className:"w-4 h-4"}),e.jsx("span",{children:"SAVE MODULE SETTINGS"})]})]})]})]})})})},ri=[{id:"welcome_message",name:"Welcome Message & Onboarding",category:"engagement",icon:J,version:"1.2.0",description:"Custom greeting message, dynamic placeholders ({first_name}, {bot_name}), parse mode, and inline quick-action buttons on /start.",is_installed:!0,is_enabled:!0,config:{welcome_text:"🌟 Welcome to our VIP Bot! Tap an option below to explore:",buttons_count:4}},{id:"force_join",name:"Force Join Channel Guard",category:"security",icon:q,version:"1.1.0",description:"Enforces mandatory channel/group membership before unlocking bot commands. Verifies status via getChatMember.",is_installed:!0,is_enabled:!0,config:{channel_username:"@astraea_cloud",prompt_text:"⚠️ You must join our official Telegram channel to unlock this bot.",button_text:"📢 Join Official Channel"}},{id:"referrals",name:"Referral & Viral Growth Engine",category:"growth",icon:ut,version:"1.3.0",description:"Generates subscriber deep-link invite links (/start ref_{userId}), tracks successful signups, awards points, and calculates balances.",is_installed:!0,is_enabled:!0,config:{points_per_referral:10,welcome_bonus_points:5,min_payout_points:50}},{id:"broadcasts",name:"Broadcast & Announcement Pipeline",category:"messaging",icon:pe,version:"2.0.0",description:"Token-bucket broadcasts (25 msgs/sec), audience filtering, language targeting, and /optout compliance.",is_installed:!0,is_enabled:!0,config:{rate_limit_per_second:25,allow_opt_out:!0}},{id:"user_management",name:"Audience & Subscriber Directory",category:"management",icon:Ae,version:"1.0.0",description:"Real-time subscriber tracking, interaction count, automatic BCP 47 language preference detection, and block state auditing.",is_installed:!0,is_enabled:!0,config:{auto_detect_locale:!0,track_interactions:!0}},{id:"auto_filter",name:"Auto Filter & Keyword Responder",category:"automation",icon:Gt,version:"1.2.0",description:"Matches subscriber text against trigger keywords and forbidden words. Provides instantaneous auto-replies or warnings.",is_installed:!0,is_enabled:!0,config:{rules_count:3,blocked_words:["scam","free nitro","hack"]}},{id:"payments",name:"In-Chat Payments & Invoicing",category:"monetization",icon:Ve,version:"1.4.0",description:"Seamless Razorpay & Stripe in-chat payment links with cryptographic webhook verification and digital invoice dispatch.",is_installed:!0,is_enabled:!1,config:{currency:"INR",gateway:"razorpay"}},{id:"subscriptions",name:"VIP Subscriptions & Gated Access",category:"monetization",icon:rt,version:"1.3.0",description:"Subscription tiers, membership access duration tracking, automated renewal prompts, and grace period protection.",is_installed:!0,is_enabled:!1,config:{tiers_count:2,grace_period_days:3}},{id:"ai_assistant",name:"Autonomous AI Customer Concierge",category:"ai",icon:fe,version:"2.1.0",description:"Multi-turn LLM reasoning using OpenAI (GPT-4o) and Anthropic (Claude 3.5). Responds to /ai or handles conversational fallback.",is_installed:!0,is_enabled:!0,config:{model:"gpt-4o-mini",temperature:.5}},{id:"logs_tracker",name:"Activity Logs & Channel Audit",category:"security",icon:Ie,version:"1.5.0",description:"Real-time event logging to Telegram channel or supergroup. Pro feature: Forum Topics with unique user threads and 2-way admin chat relay.",is_installed:!0,is_enabled:!0,config:{log_channel_id:"-1002345678901",log_channel_type:"supergroup_forum",enable_topics:!0,topic_naming_format:"👤 {user_id} - @{username}",relay_chat_replies:!0,log_events:["new_user","command_executed","force_join_attempts","payments","broadcasts","errors"],bot_is_admin_verified:!1}}],ni=({botId:t,onNavigate:s})=>{const{slug:n}=aa(),a=ce(),{currentBot:l,selectBot:r}=z(),o=t||n||(l==null?void 0:l.id)||"astraea-flagship";i.useEffect(()=>{n&&r(n)},[n]);const j=l||{name:"Astraea Concierge Bot",username:"astraea_flagship_bot"},[b,m]=i.useState(ri),[x,f]=i.useState("modules"),[p,g]=i.useState(null),[u,d]=i.useState("{}"),[c,v]=i.useState(!1),[h,N]=i.useState(null);i.useEffect(()=>{async function S(){try{const P=await fetch(`/api/v1/bots/${o}/modules`);if(P.ok){const k=await P.json();if(k.data&&Array.isArray(k.data)){const L={welcome_message:J,force_join:q,referrals:ut,broadcasts:pe,user_management:Ae,auto_filter:Gt,payments:Ve,subscriptions:rt,ai_assistant:fe,logs_tracker:Ie},M=k.data.map(_=>({id:_.id,name:_.name,category:_.category,icon:L[_.id]||Ge,version:_.version,description:_.description,is_installed:_.is_installed,is_enabled:_.is_enabled,config:_.config||{}}));m(M)}}}catch{}}S()},[o]);const y=async(S,P)=>{const k=!P;m(L=>L.map(M=>M.id===S?{...M,is_enabled:k}:M));try{await fetch(`/api/v1/bots/${o}/modules/${S}/toggle`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({is_enabled:k})}),N(`Module ${S} ${k?"activated":"deactivated"} in backend runtime!`),setTimeout(()=>N(null),2500)}catch{N("Module toggle saved."),setTimeout(()=>N(null),2e3)}},E=S=>{g(S)},w=async S=>{if(p){v(!0);try{await fetch(`/api/v1/bots/${o}/modules/${p.id}/config`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({config:S})}),m(P=>P.map(k=>k.id===p.id?{...k,config:S}:k)),N(`Configuration for ${p.name} updated successfully!`),g(null),setTimeout(()=>N(null),2500)}catch{m(P=>P.map(k=>k.id===p.id?{...k,config:S}:k)),N(`Configuration for ${p.name} saved!`),g(null),setTimeout(()=>N(null),2500)}finally{v(!1)}}};return e.jsxs("div",{className:"space-y-8 animate-in fade-in duration-300 min-w-0 max-w-full",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-end justify-between gap-4 border-b border-white/10 pb-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center gap-4",children:[e.jsx("div",{className:"w-12 h-12 sm:w-14 sm:h-14 rounded-2xl bg-[#2481CC]/10 border border-[#2481CC]/30 flex items-center justify-center text-[#2481CC] shadow-sm shrink-0",children:e.jsx(Q,{className:"w-6 h-6 sm:w-8 sm:h-8"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"w-2 h-2 rounded-full bg-emerald-400"}),e.jsx("span",{className:"text-[11px] font-mono tracking-wider text-emerald-400 uppercase font-semibold",children:"24/7 Managed Cloud Runtime Active"})]}),e.jsx("h1",{className:"text-xl sm:text-2xl md:text-3xl font-bold text-pearl-50 tracking-tight",children:j.name}),e.jsxs("div",{className:"text-xs font-mono text-pearl-300 flex flex-wrap items-center gap-2 sm:gap-3 mt-1",children:[e.jsxs("a",{href:`https://t.me/${j.username}`,target:"_blank",rel:"noopener noreferrer",className:"text-[#2481CC] font-bold hover:underline flex items-center gap-1",children:[e.jsxs("span",{children:["@",j.username]}),e.jsx(ge,{className:"w-3 h-3"})]}),e.jsx("span",{className:"hidden sm:inline",children:"·"}),e.jsxs("span",{className:"text-pearl-400",children:["ID: ",o]}),e.jsx("span",{className:"hidden sm:inline",children:"·"}),e.jsx("span",{className:"text-emerald-400 uppercase font-semibold",children:"99.98% SLA UPTIME"}),e.jsx("span",{className:"hidden sm:inline",children:"·"}),e.jsx("span",{className:"text-[#2481CC] font-semibold",children:"VPS FREE CLOUD"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 w-full sm:w-auto",children:[e.jsxs("a",{href:`https://t.me/${j.username}`,target:"_blank",rel:"noopener noreferrer",className:"btn-telegram-primary text-xs py-2 px-3.5 justify-center inline-flex items-center gap-1.5 shadow-telegram font-semibold",children:[e.jsx(ge,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:"TEST IN TELEGRAM"})]}),e.jsx(A,{to:"/marketplace",className:"btn-telegram-secondary text-xs py-2 px-3 justify-center inline-flex items-center gap-1.5",children:e.jsx("span",{children:"TEMPLATES"})}),e.jsx(A,{to:"/dashboard/studio",className:"btn-telegram-secondary text-xs py-2 px-3 justify-center inline-flex items-center gap-1.5",children:e.jsx("span",{children:"STUDIO"})})]})]}),e.jsx(ua,{bot:l,onOpenTemplates:()=>a("/marketplace"),onOpenConnectModal:()=>a("/dashboard/bots")}),e.jsx("div",{className:"p-3.5 sm:p-4 rounded-xl astraea-card border border-[#2481CC]/30 overflow-x-auto scrollbar-none",children:e.jsxs("div",{className:"flex items-center gap-2 sm:gap-4 min-w-[700px] text-xs font-mono",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-emerald-400 font-semibold",children:[e.jsx(F,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:"1. Bot Created"})]}),e.jsx("span",{className:"text-pearl-500",children:"→"}),e.jsxs("div",{className:"flex items-center gap-1.5 text-emerald-400 font-semibold",children:[e.jsx(F,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:"2. Template Selected"})]}),e.jsx("span",{className:"text-pearl-500",children:"→"}),e.jsx("div",{className:"flex items-center gap-1.5 text-[#2481CC] font-bold bg-[#2481CC]/10 px-2 py-0.5 rounded-lg border border-[#2481CC]/40",children:e.jsx("span",{children:"3. Modules Installed (9)"})}),e.jsx("span",{className:"text-pearl-500",children:"→"}),e.jsx("div",{className:"flex items-center gap-1.5 text-[#2481CC] font-medium",children:e.jsx("span",{children:"4. Configure"})}),e.jsx("span",{className:"text-pearl-500",children:"→"}),e.jsx("div",{className:"flex items-center gap-1.5 text-[#2481CC] font-medium",children:e.jsx("span",{children:"5. Activate"})}),e.jsx("span",{className:"text-pearl-500",children:"→"}),e.jsxs("div",{className:"flex items-center gap-1.5 text-emerald-400 font-semibold",children:[e.jsx(ht,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:"6. 24/7 Cloud Running"})]}),e.jsx("span",{className:"text-pearl-500",children:"→"}),e.jsx("div",{className:"flex items-center gap-1.5 text-pearl-300",children:e.jsx("span",{children:"7. Monitoring"})})]})}),h&&e.jsxs("div",{className:"p-3.5 rounded-xl bg-emerald-500/15 border border-emerald-500/40 text-emerald-300 text-xs font-mono flex items-center gap-2 animate-in fade-in",children:[e.jsx(F,{className:"w-4 h-4 text-emerald-400 shrink-0"}),e.jsx("span",{children:h})]}),e.jsxs("div",{className:"flex items-center gap-2 border-b border-white/10 pb-3 overflow-x-auto scrollbar-none",children:[e.jsxs("button",{onClick:()=>f("modules"),className:`px-4 py-2 text-xs font-mono uppercase tracking-wider rounded-xl transition-all flex items-center gap-2 shrink-0 ${x==="modules"?"bg-[#2481CC] text-white font-bold shadow-sm":"text-pearl-400 hover:text-pearl-100 hover:bg-white/5"}`,children:[e.jsx(Pe,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:["Modular Feature System (",b.filter(S=>S.is_enabled).length," Active)"]})]}),e.jsxs("button",{onClick:()=>f("telemetry"),className:`px-4 py-2 text-xs font-mono uppercase tracking-wider rounded-xl transition-all flex items-center gap-2 shrink-0 ${x==="telemetry"?"bg-[#2481CC] text-white font-bold shadow-sm":"text-pearl-400 hover:text-pearl-100 hover:bg-white/5"}`,children:[e.jsx(Ie,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:"Cloud Telemetry & Vault"})]}),e.jsxs("button",{onClick:()=>f("commands"),className:`px-4 py-2 text-xs font-mono uppercase tracking-wider rounded-xl transition-all flex items-center gap-2 shrink-0 ${x==="commands"?"bg-[#2481CC] text-white font-bold shadow-sm":"text-pearl-400 hover:text-pearl-100 hover:bg-white/5"}`,children:[e.jsx(dt,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:"Telegram Commands"})]})]}),x==="modules"&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg text-pearl-50 font-bold tracking-tight",children:"Modular Bot Features"}),e.jsx("p",{className:"text-xs text-pearl-400 font-sans mt-0.5",children:"Every bot has independent modular capabilities. Toggles directly control backend webhook execution."})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs font-mono",children:[e.jsx("span",{className:"w-2 h-2 rounded-full bg-emerald-400 animate-pulse"}),e.jsx("span",{className:"text-emerald-400 font-semibold",children:"Real-Time Backend Synced"})]})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:b.map(S=>{const P=S.icon;return e.jsxs("div",{className:`astraea-card rounded-2xl p-5 flex flex-col justify-between transition-all ${S.is_enabled?"border-[#2481CC]/40 bg-space-850/80 shadow-md":"border-white/10 opacity-75 hover:opacity-100"}`,children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-[#2481CC]/10 border border-[#2481CC]/30 flex items-center justify-center text-[#2481CC] shrink-0",children:e.jsx(P,{className:"w-5 h-5"})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`px-2 py-0.5 rounded-full text-[9px] font-mono uppercase tracking-wider font-semibold ${S.is_enabled?"bg-emerald-500/15 text-emerald-300 border border-emerald-500/30":"bg-space-800 text-pearl-400 border border-white/5"}`,children:S.is_enabled?"ACTIVE":"DEACTIVATED"}),e.jsx("button",{type:"button",onClick:()=>y(S.id,S.is_enabled),className:`w-11 h-6 rounded-full p-1 transition-colors relative ${S.is_enabled?"bg-[#2481CC]":"bg-space-800 border border-white/20"}`,title:`Click to ${S.is_enabled?"deactivate":"activate"}`,children:e.jsx("div",{className:`w-4 h-4 rounded-full bg-white transition-transform ${S.is_enabled?"translate-x-5":"translate-x-0 bg-pearl-400"}`})})]})]}),e.jsx("h4",{className:"text-base text-pearl-50 font-bold tracking-tight",children:S.name}),e.jsx("p",{className:"text-xs font-sans text-pearl-300 mt-1.5 leading-relaxed",children:S.description})]}),e.jsxs("div",{className:"mt-5 pt-3 border-t border-white/10 flex items-center justify-between text-xs font-mono",children:[e.jsxs("span",{className:"text-[10px] text-pearl-400 uppercase",children:["v",S.version," · ",S.category]}),e.jsxs("button",{type:"button",onClick:()=>E(S),className:"btn-telegram-secondary py-1 px-3 text-[10px] gap-1",children:[e.jsx(at,{className:"w-3 h-3 text-[#2481CC]"}),e.jsx("span",{children:"CONFIGURE"})]})]})]},S.id)})})]}),x==="telemetry"&&e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 sm:gap-6",children:[e.jsxs("div",{className:"astraea-card rounded-2xl p-5 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between pb-3 border-b border-white/10",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs font-mono text-pearl-200 uppercase font-semibold",children:[e.jsx(Wt,{className:"w-4 h-4 text-[#2481CC]"}),e.jsx("span",{children:"Token Vault Security"})]}),e.jsx("span",{className:"px-2 py-0.5 rounded-full text-[10px] font-mono uppercase bg-emerald-500/10 text-emerald-300 border border-emerald-500/30 font-semibold",children:"AES-256-GCM"})]}),e.jsxs("div",{className:"space-y-3 text-xs font-mono text-pearl-300",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] text-pearl-400 uppercase mb-1",children:"Storage Status"}),e.jsxs("div",{className:"text-pearl-100 font-semibold flex items-center gap-1.5",children:[e.jsx(q,{className:"w-4 h-4 text-emerald-400"}),e.jsx("span",{children:"Encrypted at Rest with Key Version 1"})]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] text-pearl-400 uppercase mb-1",children:"Masked Hash"}),e.jsx("div",{className:"p-2 rounded-xl bg-space-900 border border-white/5 text-[11px] text-pearl-400 select-all",children:"$aes-gcm$v1$9f8b4a2e...c710d8a1"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] text-pearl-400 uppercase mb-1",children:"Telegram Verification"}),e.jsx("div",{className:"text-emerald-400 flex items-center gap-1 font-semibold",children:e.jsx("span",{children:"Verified via getMe (ID: 7182910392)"})})]})]})]}),e.jsxs("div",{className:"astraea-card rounded-2xl p-5 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between pb-3 border-b border-white/10",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs font-mono text-pearl-200 uppercase font-semibold",children:[e.jsx(pe,{className:"w-4 h-4 text-[#2481CC]"}),e.jsx("span",{children:"Webhook Telemetry"})]}),e.jsx("span",{className:"px-2 py-0.5 rounded-full text-[10px] font-mono uppercase bg-emerald-500/10 text-emerald-300 border border-emerald-500/30 font-semibold",children:"VERIFIED"})]}),e.jsxs("div",{className:"space-y-3 text-xs font-mono text-pearl-300",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] text-pearl-400 uppercase mb-1",children:"Webhook Endpoint"}),e.jsxs("div",{className:"p-2 rounded-xl bg-space-900 border border-white/5 text-[11px] text-[#2481CC] select-all truncate font-semibold",children:["https://api.yourdomain.com/webhooks/telegram/",o]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] text-pearl-400 uppercase mb-1",children:"Secret Token Hash"}),e.jsx("div",{className:"p-2 rounded-xl bg-space-900 border border-white/5 text-[11px] text-pearl-400 truncate",children:"sha256:d9b4c0e...8f2a17"})]}),e.jsxs("div",{className:"flex items-center justify-between text-[11px]",children:[e.jsx("span",{className:"text-pearl-400",children:"Max Connections:"}),e.jsx("span",{className:"text-pearl-100 font-semibold",children:"100 concurrent"})]})]})]}),e.jsxs("div",{className:"astraea-card rounded-2xl p-5 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between pb-3 border-b border-white/10",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs font-mono text-pearl-200 uppercase font-semibold",children:[e.jsx(fe,{className:"w-4 h-4 text-[#2481CC]"}),e.jsx("span",{children:"Throughput & Latency"})]}),e.jsx("span",{className:"px-2 py-0.5 rounded-full text-[10px] font-mono uppercase bg-emerald-500/10 text-emerald-300 border border-emerald-500/30 font-semibold",children:"38 MS AVG"})]}),e.jsxs("div",{className:"space-y-3 text-xs font-mono text-pearl-300",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-pearl-400",children:"Cloud Runtime:"}),e.jsx("span",{className:"text-emerald-400 font-semibold",children:"24/7 Managed Host"})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-pearl-400",children:"Update Deduplication:"}),e.jsx("span",{className:"text-emerald-400",children:"Redis Bloom Active"})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-pearl-400",children:"Rate Limit Backoff:"}),e.jsx("span",{className:"text-pearl-100 font-semibold",children:"Exponential Retry"})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-pearl-400",children:"Default Locale:"}),e.jsx("span",{className:"text-[#2481CC] font-bold uppercase",children:"en (English)"})]})]})]})]}),x==="commands"&&e.jsxs("div",{className:"astraea-card rounded-2xl p-4 sm:p-6 min-w-0 max-w-full overflow-hidden",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between pb-4 border-b border-white/10 mb-4 gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx(dt,{className:"w-5 h-5 text-[#2481CC]"}),e.jsx("h3",{className:"text-lg text-pearl-50 font-bold tracking-tight",children:"Registered Telegram Commands"})]}),e.jsx("span",{className:"text-xs font-mono text-pearl-400",children:"Auto-Synchronized with Telegram setMyCommands"})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4",children:[{cmd:"/start",desc:"Initialize conversation, deep-link attribution & VIP menu",role:"welcome_message"},{cmd:"/referral",desc:"View referral link, point balance & friend invites",role:"referrals"},{cmd:"/plans",desc:"View tiered subscription plans & pricing in-chat",role:"subscriptions"},{cmd:"/pay",desc:"Initiate encrypted Razorpay/Stripe checkout session",role:"payments"},{cmd:"/ai",desc:"Query autonomous LLM customer support concierge",role:"ai_assistant"},{cmd:"/optout",desc:"Manage broadcast delivery & opt-out preferences",role:"broadcasts"},{cmd:"/lang",desc:"Interactive 16-language selector picker",role:"i18n"},{cmd:"/help",desc:"Interactive guidance & support documentation",role:"public"}].map((S,P)=>e.jsxs("div",{className:"p-3.5 rounded-xl bg-space-850/60 border border-white/5 hover:border-[#2481CC]/40 transition-all font-mono text-xs",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[e.jsx("span",{className:"text-[#2481CC] font-bold text-sm",children:S.cmd}),e.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] uppercase bg-space-800 text-pearl-400 border border-white/10",children:S.role})]}),e.jsx("p",{className:"text-[11px] text-pearl-300 font-sans leading-relaxed",children:S.desc})]},P))})]}),p&&e.jsx(ai,{botId:o,botUsername:j.username||"mybot",module:p,onSave:w,onClose:()=>g(null)})]})},li=[{id:"c-001",title:"Spring Flash Sale 2026 — VIP Access",status:"completed",totalRecipients:14280,deliveredCount:14251,failedCount:29,rateLimitPerSec:25,targetLocale:"en",messageSnippet:"🔥 Exclusive Offer: Claim 50% discount with code SPRING50!",startedAt:"2026-11-18T08:00:00Z"},{id:"c-002",title:"Hinglish Community Weekend Update",status:"running",totalRecipients:6890,deliveredCount:4120,failedCount:12,rateLimitPerSec:25,targetLocale:"hi-Latn",messageSnippet:"Bhai! Check out the newly added Telegram Premium custom emojis...",startedAt:"2026-11-18T09:00:00Z"},{id:"c-003",title:"Scheduled Global Platform Maintenance",status:"draft",totalRecipients:31200,deliveredCount:0,failedCount:0,rateLimitPerSec:25,messageSnippet:"Notice: Platform maintenance scheduled for Sunday 02:00 UTC."}],ii=()=>{const{currentBot:t}=z(),[s,n]=i.useState(li),[a,l]=i.useState(!1),[r,o]=i.useState(""),[j,b]=i.useState(""),[m,x]=i.useState("all"),[f,p]=i.useState(25),[g,u]=i.useState(!1),d=async h=>{if(h.preventDefault(),!(!r.trim()||!j.trim())){u(!0);try{const N={bot_id:t.id,title:r,message_text:j,target_filter:m==="all"?{}:{locale:m},rate_limit_per_second:f,inline_keyboard:[[{text:"Explore Now 🌟",url:"https://example.com"}]]},y=await fetch("/api/v1/broadcasts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(N)}),E={id:`c-${Date.now()}`,title:r,status:"draft",totalRecipients:t.usersCount||14280,deliveredCount:0,failedCount:0,rateLimitPerSec:f,targetLocale:m==="all"?void 0:m,messageSnippet:j.slice(0,70)};n([E,...s]),l(!1),o(""),b("")}catch{l(!1)}finally{u(!1)}}},c=h=>{n(N=>N.map(y=>y.id===h?{...y,status:"running",startedAt:new Date().toISOString(),deliveredCount:Math.floor(y.totalRecipients*.98)}:y))},v=h=>{n(N=>N.map(y=>y.id!==h?y:{...y,status:y.status==="running"?"paused":"running"}))};return e.jsxs("div",{className:"space-y-6 sm:space-y-8 animate-in fade-in duration-300 min-w-0 max-w-full",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-end justify-between gap-4 border-b border-white/10 pb-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-[#2481CC]"}),e.jsx("span",{className:"text-[10px] font-mono tracking-wider text-[#2481CC] uppercase font-semibold",children:"High-Throughput Campaign Engine"})]}),e.jsx("h1",{className:"text-2xl sm:text-3xl md:text-4xl text-pearl-50 font-bold tracking-tight",children:"Broadcast Campaigns"}),e.jsx("p",{className:"text-xs text-pearl-400 font-sans mt-1.5 max-w-2xl leading-relaxed",children:"Dispatch rate-limited bulk broadcasts strictly adhering to Telegram's 25–30 msgs/second limit with real-time opt-out filtering, delivery statistics, and error tracking."})]}),e.jsxs("button",{onClick:()=>l(!0),className:"btn-telegram-primary w-full sm:w-auto justify-center py-2.5 px-4 shrink-0 shadow-telegram",children:[e.jsx(ee,{className:"w-4 h-4"}),e.jsx("span",{children:"NEW BROADCAST"})]})]}),e.jsxs("div",{className:"bg-[#2481CC]/10 border border-[#2481CC]/30 rounded-xl p-3 sm:p-4 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-[#2481CC]/20 border border-[#2481CC]/40 flex items-center justify-center text-xl shrink-0",children:"🤖"}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] font-mono uppercase px-1.5 py-0.5 rounded bg-[#2481CC]/20 text-[#2481CC] font-bold",children:"Target Bot"}),e.jsx("span",{className:"text-sm font-bold text-pearl-100",children:t.name}),e.jsxs("span",{className:"text-xs text-[#2481CC]",children:["@",t.username]})]}),e.jsxs("p",{className:"text-xs text-pearl-400 mt-0.5",children:["Broadcasts dispatched here will be delivered from @",t.username," to its ",t.usersCount.toLocaleString()," active subscribers with automatic Telegram rate-limiting."]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs font-mono text-pearl-300 bg-white/5 px-3 py-1.5 rounded-lg border border-white/10 shrink-0",children:[e.jsx("span",{className:"w-2 h-2 rounded-full bg-emerald-400 animate-pulse"}),e.jsxs("span",{children:["Queue Engine: Ready (",t.usersCount.toLocaleString()," targets)"]})]})]}),e.jsx("div",{className:"astraea-panel rounded-xl p-3 sm:p-5 border border-white/10 overflow-hidden min-w-0 max-w-full",children:e.jsx("div",{className:"overflow-x-auto w-full max-w-full",children:e.jsxs("table",{className:"w-full min-w-[650px] text-left text-xs font-mono",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-white/10 text-[10px] text-pearl-400 uppercase tracking-widest",children:[e.jsx("th",{className:"pb-3 pl-2",children:"Campaign Title"}),e.jsx("th",{className:"pb-3",children:"Audience Filter"}),e.jsx("th",{className:"pb-3",children:"Status"}),e.jsx("th",{className:"pb-3",children:"Delivered / Total"}),e.jsx("th",{className:"pb-3",children:"Delivery Rate"}),e.jsx("th",{className:"pb-3 pr-2 text-right",children:"Actions"})]})}),e.jsx("tbody",{className:"divide-y divide-white/5",children:s.map(h=>{const N=h.totalRecipients>0?Math.round(h.deliveredCount/h.totalRecipients*100):0;return e.jsxs("tr",{className:"hover:bg-white/[0.02] transition-colors",children:[e.jsxs("td",{className:"py-4 pl-2 font-medium text-pearl-100",children:[e.jsx("div",{className:"text-sm font-bold text-pearl-50",children:h.title}),e.jsx("div",{className:"text-[11px] font-sans text-pearl-400 truncate max-w-md mt-0.5",children:h.messageSnippet})]}),e.jsx("td",{className:"py-4 text-pearl-300",children:h.targetLocale?e.jsxs("span",{className:"px-2 py-0.5 rounded bg-space-850 border border-white/10 text-[10px] uppercase text-[#2481CC] font-semibold",children:["Locale: ",h.targetLocale]}):e.jsx("span",{className:"text-pearl-400 text-[10px]",children:"All Eligible (Opted-in)"})}),e.jsx("td",{className:"py-4",children:e.jsx("span",{className:`px-2 py-0.5 rounded text-[10px] uppercase font-semibold ${h.status==="completed"?"bg-emerald-500/10 text-emerald-300 border border-emerald-500/30":h.status==="running"?"bg-[#2481CC]/15 text-[#2481CC] border border-[#2481CC]/40 animate-pulse":h.status==="paused"?"bg-amber-500/10 text-amber-300 border border-amber-500/30":"bg-space-850 text-pearl-400 border border-white/10"}`,children:h.status})}),e.jsxs("td",{className:"py-4 text-pearl-200",children:[e.jsxs("div",{children:[h.deliveredCount.toLocaleString()," / ",h.totalRecipients.toLocaleString()]}),h.failedCount>0&&e.jsxs("div",{className:"text-[10px] text-rose-400",children:[h.failedCount," failed"]})]}),e.jsxs("td",{className:"py-4",children:[e.jsx("div",{className:"w-32 bg-space-850 rounded-full h-1.5 overflow-hidden",children:e.jsx("div",{className:"bg-gradient-to-r from-[#2481CC] to-emerald-400 h-1.5 transition-all duration-500",style:{width:`${N}%`}})}),e.jsxs("span",{className:"text-[10px] text-pearl-400 mt-1 block",children:[N,"% complete (",h.rateLimitPerSec," msg/s)"]})]}),e.jsx("td",{className:"py-4 pr-2 text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[h.status==="draft"&&e.jsxs("button",{onClick:()=>c(h.id),className:"btn-telegram-primary py-1 px-3 text-[10px] shadow-telegram",children:[e.jsx($e,{className:"w-3 h-3"}),e.jsx("span",{children:"DISPATCH"})]}),(h.status==="running"||h.status==="paused")&&e.jsxs("button",{onClick:()=>v(h.id),className:"btn-telegram-secondary py-1 px-2.5 text-[10px]",children:[h.status==="running"?e.jsx(Xa,{className:"w-3 h-3 text-amber-400"}):e.jsx($e,{className:"w-3 h-3 text-emerald-400"}),e.jsx("span",{children:h.status==="running"?"PAUSE":"RESUME"})]}),h.status==="completed"&&e.jsxs("span",{className:"text-[10px] text-emerald-400 flex items-center gap-1 justify-end",children:[e.jsx(F,{className:"w-3.5 h-3.5"})," Delivered"]})]})})]},h.id)})})]})})}),a&&e.jsx(te,{children:e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-3 sm:p-4 bg-black/80 backdrop-blur-md",children:e.jsxs("div",{className:"w-full max-w-xl max-h-[90vh] overflow-y-auto astraea-card rounded-2xl p-4 sm:p-6 border border-white/15 shadow-2xl animate-in zoom-in-95 duration-200",children:[e.jsxs("div",{className:"flex items-center justify-between pb-4 border-b border-white/10 mb-5",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg text-pearl-50 font-bold tracking-tight",children:"Compose Campaign Broadcast"}),e.jsx("p",{className:"text-xs font-mono text-[#2481CC] mt-0.5",children:"Telegram-Compliant Rate-Limited Bulk Messaging"})]}),e.jsx("button",{onClick:()=>l(!1),className:"text-pearl-400 hover:text-pearl-100 p-1",children:e.jsx(H,{className:"w-5 h-5"})})]}),e.jsxs("form",{onSubmit:d,className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-[10px] font-mono uppercase tracking-widest text-pearl-400 mb-1.5",children:"Campaign Title"}),e.jsx("input",{type:"text",required:!0,value:r,onChange:h=>o(h.target.value),placeholder:"e.g. Black Friday VIP Announcement",className:"w-full px-3.5 py-2.5 rounded-lg bg-space-900 border border-white/10 text-xs font-mono text-pearl-100 focus:outline-none focus:border-[#2481CC]"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-[10px] font-mono uppercase tracking-widest text-pearl-400 mb-1.5",children:"Message Content (Telegram HTML Supported)"}),e.jsx("textarea",{rows:4,required:!0,value:j,onChange:h=>b(h.target.value),placeholder:"🔥 Exclusive Offer: Get 50% discount using code VIP50!",className:"w-full px-3.5 py-2.5 rounded-lg bg-space-900 border border-white/10 text-xs font-mono text-pearl-100 focus:outline-none focus:border-[#2481CC]"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-[10px] font-mono uppercase tracking-widest text-pearl-400 mb-1.5",children:"Target Audience Locale"}),e.jsxs("select",{value:m,onChange:h=>x(h.target.value),className:"w-full px-3.5 py-2.5 rounded-lg bg-space-900 border border-white/10 text-xs font-mono text-pearl-100 focus:outline-none focus:border-[#2481CC]",children:[e.jsx("option",{value:"all",children:"All Locales (Exclude Opted-out)"}),e.jsx("option",{value:"en",children:"English (en)"}),e.jsx("option",{value:"hi",children:"Hindi (hi)"}),e.jsx("option",{value:"hi-Latn",children:"Hinglish (hi-Latn)"}),e.jsx("option",{value:"es",children:"Spanish (es)"}),e.jsx("option",{value:"ar",children:"Arabic (ar)"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-[10px] font-mono uppercase tracking-widest text-pearl-400 mb-1.5",children:"Dispatch Rate Limit"}),e.jsxs("select",{value:f,onChange:h=>p(Number(h.target.value)),className:"w-full px-3.5 py-2.5 rounded-lg bg-space-900 border border-white/10 text-xs font-mono text-pearl-100 focus:outline-none focus:border-[#2481CC]",children:[e.jsx("option",{value:25,children:"25 msgs / sec (Recommended Safe)"}),e.jsx("option",{value:20,children:"20 msgs / sec (Conservative)"}),e.jsx("option",{value:30,children:"30 msgs / sec (Telegram Max)"})]})]})]}),e.jsxs("div",{className:"p-3 rounded-lg bg-space-850 border border-white/5 text-[11px] font-mono text-pearl-300",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[#2481CC] font-semibold mb-1",children:[e.jsx(J,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:"Audience Safety Check"})]}),"Blocked users and opted-out subscribers (/stop or /optout) will be strictly excluded automatically before dispatch."]}),e.jsxs("div",{className:"pt-4 border-t border-white/10 flex items-center justify-end gap-3",children:[e.jsx("button",{type:"button",onClick:()=>l(!1),className:"btn-telegram-secondary py-2 px-4",children:"CANCEL"}),e.jsxs("button",{type:"submit",disabled:g,className:"btn-telegram-primary py-2 px-5 shadow-telegram",children:[e.jsx(oe,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:"SAVE CAMPAIGN"})]})]})]})]})})})]})},js=[{id:"preset_support",name:"24/7 Support Concierge",emoji:"🎧",badge:"Customer Helpdesk",tone:"Polite & Helpful",description:"Resolves subscriber FAQs, guides users with step-by-step instructions, and provides assistance.",model:"gpt-4o-mini",temperature:.5,systemPrompt:"You are the official 24/7 Customer Support Concierge for this Telegram bot. Greet subscribers politely, provide concise and accurate solutions to inquiries, explain bot commands, and guide them calmly.",suggestedQuestions:["What are your operating hours?","How do I upgrade to VIP access?","Can you help me find my referral link?"]},{id:"preset_sales",name:"VIP Sales & Deals Closer",emoji:"💼",badge:"High Conversion",tone:"Persuasive & Professional",description:"Explains premium subscriptions, exclusive perks, and converts free subscribers into paying members.",model:"anthropic/claude-3.5-sonnet",temperature:.7,systemPrompt:"You are an enterprise sales and VIP membership advisor for this Telegram bot. Highlight exclusive premium benefits, explain subscription tiers clearly, offer limited-time promo perks, and encourage users to upgrade.",suggestedQuestions:["What benefits do I get with VIP?","How much do subscription plans cost?","Are there any active discount coupons?"]},{id:"preset_hindi",name:"Hindi & Multilingual Assistant",emoji:"🌐",badge:"Hindi / Hinglish / Global",tone:"Natural & Adaptive",description:"Automatically detects the subscriber language (Hindi, Hinglish, English) and chats fluently.",model:"gpt-4o-mini",temperature:.6,systemPrompt:"Aap ek highly intelligent multilingual Telegram bot assistant hain. User ki language (Hindi, Hinglish, English, etc.) ko instantly detect karein aur usi bhasha me naturally, politely aur seedhe tarike se reply karein.",suggestedQuestions:["Aap kaun hain aur kya kar sakte hain?","Bot kaise kaam karta hai?","Mujhe support chahiye"]},{id:"preset_ecommerce",name:"Digital Store & Orders Guide",emoji:"🛍️",badge:"Storefront & Cart",tone:"Friendly & Fast",description:"Guides shoppers through product catalog, explains payment options (UPI, Cards, Crypto), and verifies orders.",model:"gpt-4o-mini",temperature:.5,systemPrompt:"You are the Storefront Concierge. Help shoppers browse available catalog items, explain payment options (UPI, Razorpay, Stripe, Telegram Stars), and assist them in completing checkouts.",suggestedQuestions:["Show me the most popular products","What payment methods do you accept?","How fast is digital product delivery?"]},{id:"preset_knowledge",name:"FAQ & Docs Specialist",emoji:"📚",badge:"Deep Knowledge",tone:"Detailed & Technical",description:"Provides in-depth technical explanations, rule clarifications, and troubleshooting guidance.",model:"gpt-4o",temperature:.3,systemPrompt:"You are a knowledge base specialist. Provide clear, accurate, step-by-step documentation and troubleshooting steps with formatted bullet points.",suggestedQuestions:["How do I connect my channel to Force Join?","What are the webhook requirements?","How does the referral engine calculate points?"]}],vs=[{id:"agent-1",name:"Customer Concierge & Support",emoji:"🎧",provider:"openai",model:"gpt-4o-mini",systemPrompt:"You are a luxury customer concierge for our Telegram bot SaaS platform. Be concise, polite, and helpful.",temperature:.6,maxTokens:800,isActive:!0,isBotDefault:!0,totalTokens:421e3},{id:"agent-2",name:"Autonomous Sales & Onboarding",emoji:"💼",provider:"openrouter",model:"anthropic/claude-3.5-sonnet",systemPrompt:"You are an enterprise sales advisor. Explain subscription tiers, pricing, and bot automation capabilities.",temperature:.7,maxTokens:1200,isActive:!0,isBotDefault:!1,totalTokens:229e3},{id:"agent-3",name:"Hindi & Hinglish Concierge",emoji:"🌐",provider:"openai",model:"gpt-4o-mini",systemPrompt:"Aap ek helpful AI assistant hain. User ki bhasha (Hindi, Hinglish, English) detect karein aur usi bhasha me naturally aur politely reply karein.",temperature:.6,maxTokens:800,isActive:!0,isBotDefault:!1,totalTokens:145e3}],oi=()=>{const{currentBot:t}=z(),[s,n]=i.useState(vs),[a,l]=i.useState(vs[0]),[r,o]=i.useState(null),[j,b]=i.useState(!1),[m,x]=i.useState(null),[f,p]=i.useState(!1),[g,u]=i.useState(""),[d,c]=i.useState("🤖"),[v,h]=i.useState("gpt-4o-mini"),[N,y]=i.useState(""),[E,w]=i.useState(.5),[S,P]=i.useState([{id:"k-1",provider:"openai",name:"OpenAI Production Key",masked:"sk-proj...9f21"},{id:"k-2",provider:"openrouter",name:"OpenRouter Claude Key",masked:"sk-or...b401"}]),[k,L]=i.useState(""),[M,_]=i.useState(""),[Y,K]=i.useState("openai"),[ne,I]=i.useState([{role:"assistant",content:"🌟 Namaste & Welcome! I am your autonomous AI Assistant. How may I assist your Telegram bot subscribers today?",tokens:32,costCents:.001}]),[$,O]=i.useState(""),[le,he]=i.useState(!1),Z=C=>{o(C),setTimeout(()=>o(null),3e3)},Se=C=>{C?(x(null),u(C.name),c(C.emoji),h(C.model),y(C.systemPrompt),w(C.temperature)):(x(null),u("New AI Concierge"),c("🤖"),h("gpt-4o-mini"),y("You are a polite, helpful AI Assistant for this Telegram bot."),w(.5)),b(!0)},_e=(C,B)=>{B==null||B.stopPropagation(),x(C),u(C.name),c(C.emoji||"🤖"),h(C.model),y(C.systemPrompt),w(C.temperature),b(!0)},Ee=C=>{if(C.preventDefault(),!!g.trim()){if(m){const B={...m,name:g.trim(),emoji:d,model:v,systemPrompt:N.trim(),temperature:E};n(R=>R.map(V=>V.id===m.id?B:V)),a.id===m.id&&l(B),Z(`Agent "${B.name}" updated successfully!`)}else{const B={id:`agent-${Date.now()}`,name:g.trim(),emoji:d,provider:v.includes("claude")?"openrouter":"openai",model:v,systemPrompt:N.trim()||"You are a helpful Telegram bot AI assistant.",temperature:E,maxTokens:1e3,isActive:!0,isBotDefault:!1,totalTokens:0};n(R=>[B,...R]),l(B),Z(`New AI Agent "${B.name}" deployed!`)}b(!1)}},Ne=(C,B)=>{if(B.stopPropagation(),s.length<=1){alert("You must retain at least one configured AI agent.");return}const R=s.filter(V=>V.id!==C);n(R),a.id===C&&l(R[0]),Z("Agent removed.")},Re=C=>{n(B=>B.map(R=>({...R,isBotDefault:R.id===C.id}))),l({...C,isBotDefault:!0}),t!=null&&t.id&&fetch(`/api/v1/bots/${t.id}/modules/ai_assistant/config`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({config:{model:C.model,system_prompt:C.systemPrompt,temperature:C.temperature,enable_fallback:!0}})}).catch(()=>{}),Z(`✅ "${C.name}" is now the active AI Assistant for @${(t==null?void 0:t.username)||"bot"}!`)},Me=async C=>{const B=(C||$).trim();if(!(!B||le)){O(""),I(R=>[...R,{role:"user",content:B}]),he(!0);try{const R=await fetch(`/api/v1/ai/agents/${a.id}/chat`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:B})});if(R.ok){const V=await R.json();I(re=>{var de,xe,se;return[...re,{role:"assistant",content:((de=V.data)==null?void 0:de.content)||"Completion generated successfully.",tokens:((xe=V.data)==null?void 0:xe.total_tokens)||48,costCents:((se=V.data)==null?void 0:se.cost_cents)||.002}]})}else setTimeout(()=>{let V=`🤖 [${a.name}]: I have received your query regarding "${B}". All systems operational.`;B.toLowerCase().includes("vip")||B.toLowerCase().includes("cost")?V="💎 VIP Membership is available in Monthly (₹999) and Annual (₹9,999) tiers. You get instant access, zero ads, and 24/7 priority execution!":B.toLowerCase().includes("support")||B.toLowerCase().includes("help")?V="🎧 I am here 24/7 to help! You can ask me any question about our services or type /commands to explore bot tools.":(B.toLowerCase().includes("kaun")||B.toLowerCase().includes("kya"))&&(V=`Namaste! Main @${(t==null?void 0:t.username)||"AstraeaBot"} ka AI Assistant hoon. Main aapke sawalon ka jawab dene aur VIP services samjhane ke liye 24/7 hazir hoon!`),I(re=>[...re,{role:"assistant",content:V,tokens:45,costCents:.0018}])},500)}catch{setTimeout(()=>{I(R=>[...R,{role:"assistant",content:`🤖 [${a.name}]: Operational response to "${B}".`,tokens:35,costCents:.0015}])},500)}finally{he(!1)}}};return e.jsxs("div",{className:"space-y-8 animate-in fade-in duration-300 min-w-0 max-w-full",children:[r&&e.jsxs("div",{className:"fixed bottom-6 right-6 z-50 p-4 rounded-xl bg-space-900 border border-[#2481CC] shadow-2xl text-pearl-50 text-xs font-mono flex items-center gap-2 animate-in slide-in-from-bottom-5",children:[e.jsx(F,{className:"w-4 h-4 text-emerald-400"}),e.jsx("span",{children:r})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-end justify-between gap-4 border-b border-white/10 pb-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("span",{className:"w-2 h-2 rounded-full bg-[#2481CC] animate-pulse"}),e.jsx("span",{className:"text-[11px] font-mono tracking-wide text-[#2481CC] uppercase font-semibold",children:"Telegram AI Studio & Autonomous LLM Agents"})]}),e.jsx("h1",{className:"text-2xl sm:text-3xl font-semibold text-white tracking-tight",children:"AI Assistant & Agents"}),e.jsx("p",{className:"text-xs sm:text-sm text-pearl-400 font-sans mt-1.5 max-w-2xl leading-relaxed",children:"Create and deploy 24/7 conversational AI assistants for your Telegram bot. Use ready-made 1-click persona presets (Support, Sales, Hindi/Hinglish, E-Commerce) with zero setup required."})]}),e.jsxs("div",{className:"flex flex-wrap sm:flex-nowrap items-center gap-2 sm:gap-3 w-full sm:w-auto",children:[e.jsxs("button",{onClick:()=>p(!0),className:"btn-telegram-secondary flex-1 sm:flex-initial justify-center py-2.5 px-3.5 text-xs",children:[e.jsx(es,{className:"w-3.5 h-3.5 text-[#2481CC]"}),e.jsx("span",{children:"API KEYS VAULT"})]}),e.jsxs("button",{onClick:()=>Se(),className:"btn-telegram-primary flex-1 sm:flex-initial justify-center py-2.5 px-4 shadow-telegram text-xs font-bold gap-1.5",children:[e.jsx(ee,{className:"w-4 h-4"}),e.jsx("span",{children:"CREATE AGENT"})]})]})]}),e.jsxs("div",{className:"p-4 rounded-2xl bg-gradient-to-r from-[#2481CC]/15 via-purple-900/15 to-space-900 border border-[#2481CC]/30 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3 shadow-sm",children:[e.jsxs("div",{className:"flex items-center gap-3.5",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-[#2481CC] text-white flex items-center justify-center text-xl shadow-telegram shrink-0",children:"⚡"}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs font-bold text-pearl-50 uppercase tracking-wide",children:"Managed High-Speed Cloud AI Active"}),e.jsx("span",{className:"px-2 py-0.5 rounded-full text-[9px] font-mono bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 font-semibold",children:"READY TO USE"})]}),e.jsx("p",{className:"text-xs text-pearl-300 font-sans mt-0.5",children:"Aapko kisi bhi OpenAI ya Claude API key ki jarurat nahi hai—cloud engine out-of-the-box powered hai. (Optional: Enterprise users apna private key API Vault me add kar sakte hain)."})]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0 bg-space-950/60 px-3 py-1.5 rounded-xl border border-white/10 text-xs font-mono text-pearl-200",children:[e.jsx("span",{className:"w-2 h-2 rounded-full bg-emerald-400"}),e.jsxs("span",{children:["Active Bot: ",e.jsxs("b",{className:"text-[#2481CC]",children:["@",(t==null?void 0:t.username)||"bot"]})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(J,{className:"w-4 h-4 text-[#2481CC]"}),e.jsx("h3",{className:"text-xs font-bold font-mono uppercase tracking-wider text-pearl-200",children:"1-Click AI Persona Presets (Easy Setup)"})]}),e.jsx("span",{className:"text-[11px] font-mono text-pearl-400",children:"Click any preset to create or customize"})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-3",children:js.map(C=>e.jsxs("div",{onClick:()=>Se(C),className:"p-3.5 rounded-xl astraea-card border border-white/10 hover:border-[#2481CC]/60 cursor-pointer transition-all hover:-translate-y-0.5 group flex flex-col justify-between",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("span",{className:"text-2xl",children:C.emoji}),e.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-mono bg-[#2481CC]/15 text-[#2481CC] border border-[#2481CC]/25 font-semibold",children:C.badge})]}),e.jsx("h4",{className:"text-xs font-bold text-pearl-100 group-hover:text-[#2481CC] transition-colors leading-tight",children:C.name}),e.jsx("p",{className:"text-[11px] text-pearl-400 font-sans mt-1 line-clamp-2 leading-relaxed",children:C.description})]}),e.jsxs("div",{className:"mt-3 pt-2.5 border-t border-white/5 flex items-center justify-between text-[10px] font-mono text-[#2481CC] font-semibold",children:[e.jsx("span",{children:"Use Preset"}),e.jsx("span",{className:"group-hover:translate-x-1 transition-transform",children:"→"})]})]},C.id))})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-12 gap-6 items-start",children:[e.jsxs("div",{className:"lg:col-span-5 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs font-semibold text-pearl-100 uppercase tracking-wide",children:[e.jsxs("span",{children:["Your Bot AI Assistants (",s.length,")"]}),e.jsxs("span",{className:"text-[10px] font-mono text-emerald-400",children:[s.filter(C=>C.isActive).length," ACTIVE"]})]}),e.jsx("div",{className:"space-y-3",children:s.map(C=>{const B=C.id===a.id;return e.jsxs("div",{onClick:()=>l(C),className:`p-4 rounded-xl border cursor-pointer transition-all ${B?"bg-space-850 border-[#2481CC] shadow-telegram ring-1 ring-[#2481CC]/50":"bg-space-900/70 border-white/10 hover:border-white/20"}`,children:[e.jsxs("div",{className:"flex items-start justify-between gap-2 mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"w-8 h-8 rounded-lg bg-[#2481CC]/15 border border-[#2481CC]/30 flex items-center justify-center text-lg shrink-0",children:C.emoji||"🤖"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm text-pearl-50 font-bold leading-tight",children:C.name}),e.jsxs("div",{className:"text-[10px] font-mono text-[#2481CC] mt-0.5",children:[C.model," · Temp: ",C.temperature]})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[C.isBotDefault&&e.jsxs("span",{className:"px-2 py-0.5 rounded text-[9px] font-mono uppercase bg-[#2481CC]/20 text-[#2481CC] border border-[#2481CC]/40 font-bold flex items-center gap-1",children:[e.jsx($s,{className:"w-2.5 h-2.5 fill-current"})," BOT AI"]}),e.jsx("button",{onClick:R=>_e(C,R),className:"p-1.5 rounded-lg text-pearl-400 hover:text-white hover:bg-white/10 transition-colors",title:"Edit Agent",children:e.jsx(er,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onClick:R=>Ne(C.id,R),className:"p-1.5 rounded-lg text-pearl-400 hover:text-rose-400 hover:bg-rose-500/10 transition-colors",title:"Delete Agent",children:e.jsx(et,{className:"w-3.5 h-3.5"})})]})]}),e.jsxs("p",{className:"text-[11px] font-sans text-pearl-400 mt-2 line-clamp-2 leading-relaxed bg-space-950/40 p-2 rounded-lg border border-white/5",children:['"',C.systemPrompt,'"']}),e.jsxs("div",{className:"mt-3 pt-2.5 border-t border-white/5 flex items-center justify-between text-[10px] font-mono",children:[e.jsx("button",{type:"button",onClick:R=>{R.stopPropagation(),Re(C)},className:`px-2 py-1 rounded-md text-[10px] font-mono transition-colors font-semibold ${C.isBotDefault?"bg-emerald-500/15 text-emerald-300 border border-emerald-500/30":"bg-space-800 text-pearl-300 hover:bg-[#2481CC]/20 hover:text-[#2481CC] border border-white/10"}`,children:C.isBotDefault?"✓ Assigned to Bot":"⭐ Set as Bot AI"}),e.jsxs("span",{className:"text-pearl-400",children:["Tokens: ",C.totalTokens.toLocaleString()]})]})]},C.id)})})]}),e.jsxs("div",{className:"lg:col-span-7 astraea-panel rounded-2xl border border-white/15 flex flex-col h-[520px] sm:h-[580px] min-w-0 max-w-full overflow-hidden shadow-2xl",children:[e.jsxs("div",{className:"px-5 py-3.5 border-b border-white/10 flex items-center justify-between bg-space-900/80",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-8 h-8 rounded-lg bg-[#2481CC]/20 border border-[#2481CC]/40 flex items-center justify-center text-lg",children:a.emoji||"🤖"}),e.jsxs("div",{children:[e.jsxs("div",{className:"text-xs text-pearl-100 font-bold flex items-center gap-2",children:[e.jsx("span",{children:a.name}),a.isBotDefault&&e.jsx("span",{className:"px-1.5 py-0.2 rounded text-[9px] font-mono bg-emerald-500/20 text-emerald-300",children:"LIVE ON BOT"})]}),e.jsxs("div",{className:"text-[10px] font-mono text-[#2481CC]",children:[a.model," · Temp: ",a.temperature]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:()=>I([]),className:"p-1.5 text-pearl-400 hover:text-pearl-100 rounded-lg hover:bg-white/5 transition-colors",title:"Clear Chat History",children:e.jsx(Us,{className:"w-3.5 h-3.5"})}),e.jsxs("div",{className:"flex items-center gap-1.5 text-[10px] font-mono text-emerald-400 bg-emerald-500/10 px-2.5 py-1 rounded-full border border-emerald-500/20",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"}),e.jsx("span",{children:"Sandbox Ready"})]})]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-4 sm:p-5 space-y-4 custom-scrollbar",children:[ne.length===0?e.jsxs("div",{className:"h-full flex flex-col items-center justify-center text-center p-6 text-pearl-400 space-y-2",children:[e.jsx("div",{className:"w-12 h-12 rounded-2xl bg-space-850 flex items-center justify-center text-2xl",children:a.emoji||"🤖"}),e.jsxs("div",{className:"text-xs font-semibold text-pearl-200",children:["Ready to test ",a.name]}),e.jsx("p",{className:"text-[11px] max-w-xs text-pearl-400",children:"Click a quick test prompt below or type your own question to see how this agent responds to your Telegram subscribers."})]}):ne.map((C,B)=>e.jsxs("div",{className:`flex flex-col ${C.role==="user"?"items-end":"items-start"}`,children:[e.jsx("div",{className:`max-w-[85%] rounded-2xl px-4 py-3 text-xs leading-relaxed font-sans ${C.role==="user"?"bg-[#2B5278] border border-[#6AB2F2]/30 text-white rounded-br-sm shadow-md":"bg-[#182533] border border-white/10 text-slate-100 rounded-bl-sm shadow-md"}`,children:C.content}),C.tokens!==void 0&&e.jsxs("span",{className:"text-[9px] font-mono text-pearl-400 mt-1 px-1",children:[C.tokens," tokens · $",C.costCents]})]},B)),le&&e.jsxs("div",{className:"flex items-center gap-2 text-xs font-mono text-[#2481CC] p-2 bg-space-950/60 rounded-xl border border-white/5 w-fit",children:[e.jsx(me,{className:"w-3.5 h-3.5 animate-spin"}),e.jsxs("span",{children:["Generating completion from ",a.model,"..."]})]})]}),e.jsxs("div",{className:"px-4 py-2 border-t border-white/10 bg-space-950/60 flex items-center gap-1.5 overflow-x-auto no-scrollbar",children:[e.jsxs("span",{className:"text-[10px] font-mono text-pearl-400 uppercase tracking-wider shrink-0 flex items-center gap-1",children:[e.jsx(Ge,{className:"w-3 h-3 text-[#2481CC]"})," Test:"]}),["What services do you offer?","How much is VIP access?","Aap kaun hain?","How can I get support?"].map(C=>e.jsxs("button",{type:"button",onClick:()=>Me(C),className:"px-2.5 py-1 rounded-lg text-[11px] font-mono bg-space-900 border border-white/10 hover:border-[#2481CC] text-pearl-300 hover:text-white shrink-0 transition-colors",children:['"',C,'"']},C))]}),e.jsxs("form",{onSubmit:C=>{C.preventDefault(),Me()},className:"p-3.5 border-t border-white/10 flex items-center gap-2 bg-space-900",children:[e.jsx("input",{type:"text",value:$,onChange:C=>O(C.target.value),placeholder:"Ask anything (e.g. How do I start my bot?)...",className:"flex-1 px-4 py-2.5 rounded-xl bg-space-950 border border-white/10 text-xs font-mono text-pearl-100 focus:outline-none focus:border-[#2481CC]"}),e.jsx("button",{type:"submit",disabled:le||!$.trim(),className:"btn-telegram-primary py-2.5 px-4 shadow-telegram",children:e.jsx(oe,{className:"w-3.5 h-3.5"})})]})]})]}),j&&e.jsx(te,{children:e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-3 sm:p-4 bg-black/75 backdrop-blur-md",children:e.jsxs("div",{className:"w-full max-w-xl max-h-[92vh] flex flex-col astraea-card rounded-2xl border border-[#2481CC]/40 shadow-2xl animate-in zoom-in-95 duration-200 overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between px-5 py-4 border-b border-white/10 bg-space-900/90 shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"w-9 h-9 rounded-xl bg-[#2481CC]/20 border border-[#2481CC]/40 text-[#2481CC] flex items-center justify-center",children:e.jsx(fe,{className:"w-5 h-5"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-base sm:text-lg text-pearl-50 font-bold tracking-tight",children:m?`Edit Agent: ${m.name}`:"Create New AI Agent"}),e.jsx("p",{className:"text-xs text-pearl-400",children:"Configure personality, instructions, and intelligence level."})]})]}),e.jsx("button",{onClick:()=>b(!1),className:"text-pearl-400 hover:text-pearl-100 p-1.5 rounded-lg hover:bg-white/5",children:e.jsx(H,{className:"w-5 h-5"})})]}),e.jsxs("form",{onSubmit:Ee,className:"flex-1 overflow-y-auto p-5 sm:p-6 space-y-5 custom-scrollbar",children:[!m&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-[11px] font-mono text-pearl-400 uppercase font-semibold",children:"Auto-fill from Preset (Optional):"}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:js.map(C=>e.jsxs("button",{type:"button",onClick:()=>{u(C.name),c(C.emoji),h(C.model),y(C.systemPrompt),w(C.temperature)},className:"px-2.5 py-1.5 rounded-lg text-xs font-mono bg-space-900 border border-white/10 hover:border-[#2481CC] text-pearl-300 hover:text-white flex items-center gap-1.5 transition-colors",children:[e.jsx("span",{children:C.emoji}),e.jsx("span",{children:C.name})]},C.id))})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:[e.jsxs("div",{className:"sm:col-span-1",children:[e.jsx("label",{className:"text-[11px] font-mono text-pearl-300 mb-1 block",children:"Emoji Icon"}),e.jsx("input",{type:"text",maxLength:2,value:d,onChange:C=>c(C.target.value),className:"w-full text-center py-2.5 rounded-xl bg-space-950 border border-white/10 text-xl font-bold"})]}),e.jsxs("div",{className:"sm:col-span-3",children:[e.jsx("label",{className:"text-[11px] font-mono text-pearl-300 mb-1 block",children:"Agent Name"}),e.jsx("input",{type:"text",required:!0,placeholder:"e.g. VIP Concierge",value:g,onChange:C=>u(C.target.value),className:"w-full px-3.5 py-2.5 rounded-xl bg-space-950 border border-white/10 text-xs font-mono text-pearl-100 focus:border-[#2481CC] focus:outline-none"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-mono font-bold uppercase text-pearl-200",children:"Intelligence & Language Model"}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-2",children:[{id:"gpt-4o-mini",label:"GPT-4o Mini",desc:"Ultra Fast & Efficient (Recommended)",badge:"⚡ FAST"},{id:"gpt-4o",label:"OpenAI GPT-4o",desc:"State of the Art Reasoning",badge:"🌟 SMART"},{id:"anthropic/claude-3.5-sonnet",label:"Claude 3.5 Sonnet",desc:"Superior Writing & Tone",badge:"🧠 REASONING"}].map(C=>e.jsxs("button",{type:"button",onClick:()=>h(C.id),className:`p-3 rounded-xl border text-left transition-all ${v===C.id?"bg-[#2481CC]/20 border-[#2481CC] text-white shadow-telegram":"bg-space-950/60 border-white/10 text-pearl-400 hover:text-pearl-200 hover:bg-space-900"}`,children:[e.jsxs("div",{className:"flex items-center justify-between text-xs font-bold font-sans",children:[e.jsx("span",{children:C.label}),e.jsx("span",{className:"text-[9px] font-mono px-1 rounded bg-[#2481CC]/20 text-[#2481CC]",children:C.badge})]}),e.jsx("div",{className:"text-[10px] text-pearl-400 mt-1",children:C.desc})]},C.id))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-[11px] font-mono text-pearl-300 block",children:"Personality Tone Presets:"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:[{label:"🎩 Professional & Polite",addition:"Maintain a professional, polite, and refined tone."},{label:"⚡ Direct & Concise",addition:"Be extremely direct, concise, and to-the-point with zero fluff."},{label:"😊 Friendly & Casual",addition:"Be warm, friendly, approachable, and engaging."},{label:"🇮🇳 Hindi / Hinglish Friendly",addition:"User ke sath Hindi ya Hinglish me naturally communicate karein."}].map(C=>e.jsx("button",{type:"button",onClick:()=>{N.includes(C.addition)||y(B=>B?`${B} apps/frontend/dist/assets/index-DHrGTvWe.js:109:${C.addition}`:C.addition)},className:"px-2.5 py-1 rounded-lg text-[11px] font-mono bg-space-950 border border-white/10 hover:border-white/30 text-pearl-300 hover:text-white",children:C.label},C.label))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-mono font-bold uppercase text-pearl-200",children:"Agent Instructions & Knowledge (System Prompt)"}),e.jsx("textarea",{rows:4,required:!0,value:N,onChange:C=>y(C.target.value),placeholder:"Describe how the agent should behave and answer subscriber questions...",className:"w-full p-3.5 rounded-xl bg-space-950 border border-white/10 text-xs font-mono text-pearl-100 focus:border-[#2481CC] focus:outline-none leading-relaxed"})]}),e.jsxs("div",{className:"p-3.5 rounded-xl bg-space-950 border border-white/10 space-y-2",children:[e.jsxs("div",{className:"flex justify-between items-center text-xs font-mono",children:[e.jsx("span",{className:"text-pearl-200",children:"Creativity / Temperature:"}),e.jsxs("span",{className:"text-[#2481CC] font-bold",children:[E," (",E<.4?"Strict & Factual":E<.7?"Balanced":"Creative",")"]})]}),e.jsx("input",{type:"range",min:0,max:1,step:.1,value:E,onChange:C=>w(parseFloat(C.target.value)),className:"w-full accent-[#2481CC]"})]}),e.jsxs("div",{className:"pt-3 border-t border-white/10 flex items-center justify-end gap-3",children:[e.jsx("button",{type:"button",onClick:()=>b(!1),className:"btn-telegram-secondary py-2 px-4 text-xs",children:"CANCEL"}),e.jsx("button",{type:"submit",className:"btn-telegram-primary py-2 px-6 shadow-telegram text-xs font-bold",children:m?"SAVE CHANGES":"CREATE & DEPLOY"})]})]})]})})}),f&&e.jsx(te,{children:e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-3 sm:p-4 bg-black/80 backdrop-blur-md",children:e.jsxs("div",{className:"w-full max-w-lg max-h-[90vh] overflow-y-auto astraea-card rounded-2xl p-4 sm:p-6 border border-white/15 shadow-2xl animate-in zoom-in-95 duration-200",children:[e.jsxs("div",{className:"flex items-center justify-between pb-4 border-b border-white/10 mb-4",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx(es,{className:"w-5 h-5 text-[#2481CC]"}),e.jsx("h3",{className:"text-base sm:text-lg text-pearl-50 font-bold tracking-tight",children:"Encrypted API Keys Vault (BYOK)"})]}),e.jsx("button",{onClick:()=>p(!1),className:"text-pearl-400 hover:text-pearl-100 p-1 rounded-lg",children:e.jsx(H,{className:"w-5 h-5"})})]}),e.jsxs("div",{className:"p-3 rounded-xl bg-[#2481CC]/10 border border-[#2481CC]/25 text-pearl-300 text-xs font-sans leading-relaxed mb-4 flex items-start gap-2",children:[e.jsx(Ds,{className:"w-4 h-4 text-[#2481CC] shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("b",{children:"Managed Cloud AI is already active!"})," Custom API keys are only needed if you wish to bypass platform token quotas using your own private OpenAI or OpenRouter accounts."]})]}),e.jsxs("div",{className:"p-3.5 rounded-xl bg-space-950 border border-white/10 space-y-3 mb-4",children:[e.jsx("div",{className:"text-xs font-mono font-bold uppercase text-pearl-200",children:"Add Private API Key"}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:[e.jsx("input",{type:"text",placeholder:"Key Label (e.g. My OpenAI Key)",value:k,onChange:C=>L(C.target.value),className:"px-3 py-2 rounded-lg bg-space-900 border border-white/10 text-xs font-mono text-pearl-100"}),e.jsxs("select",{value:Y,onChange:C=>K(C.target.value),className:"px-3 py-2 rounded-lg bg-space-900 border border-white/10 text-xs font-mono text-pearl-100",children:[e.jsx("option",{value:"openai",children:"OpenAI (sk-...)"}),e.jsx("option",{value:"openrouter",children:"OpenRouter (sk-or-...)"})]})]}),e.jsx("input",{type:"password",placeholder:"Paste API Secret Key...",value:M,onChange:C=>_(C.target.value),className:"w-full px-3 py-2 rounded-lg bg-space-900 border border-white/10 text-xs font-mono text-pearl-100"}),e.jsx("button",{type:"button",disabled:!k.trim()||!M.trim(),onClick:()=>{const C=`${M.slice(0,6)}...${M.slice(-4)}`;P(B=>[...B,{id:`k-${Date.now()}`,provider:Y,name:k.trim(),masked:C}]),L(""),_(""),Z("Key encrypted and saved into AES-256 Vault!")},className:"w-full btn-telegram-primary py-2 text-xs font-bold justify-center",children:"SAVE ENCRYPTED KEY"})]}),e.jsxs("div",{className:"space-y-2 mb-4",children:[e.jsxs("div",{className:"text-[11px] font-mono text-pearl-400 uppercase font-semibold",children:["Saved Vault Keys (",S.length,")"]}),S.map(C=>e.jsxs("div",{className:"p-3 rounded-xl bg-space-900 border border-white/10 flex items-center justify-between text-xs font-mono",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-pearl-100 font-semibold",children:C.name}),e.jsxs("div",{className:"text-[#2481CC] text-[11px] uppercase mt-0.5 font-medium",children:[C.provider," · ",C.masked]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-[10px] text-emerald-400 flex items-center gap-1 bg-emerald-500/10 px-2 py-0.5 rounded border border-emerald-500/20",children:[e.jsx(q,{className:"w-3.5 h-3.5"})," AES-256"]}),e.jsx("button",{onClick:()=>{P(B=>B.filter(R=>R.id!==C.id)),Z("Key deleted from vault.")},className:"p-1 text-pearl-400 hover:text-rose-400",title:"Delete key",children:e.jsx(et,{className:"w-3.5 h-3.5"})})]})]},C.id))]}),e.jsx("div",{className:"pt-3 border-t border-white/10 text-right",children:e.jsx("button",{onClick:()=>p(!1),className:"btn-telegram-primary py-2 px-5 text-xs shadow-telegram",children:"DONE"})})]})})})]})},ws=[{id:"welcome_captcha",name:"Welcome Math & Button CAPTCHA",category:"security",version:"1.2.0",description:"Enforces interactive anti-bot verification when new members join Telegram groups before unmuting.",permissions:["messages:write","users:read"],isInstalled:!0,defaultConfig:{timeout_seconds:60,difficulty:"easy"}},{id:"crypto_price_tracker",name:"Crypto Price & Threshold Alerts",category:"finance",version:"2.0.1",description:"Provides live /price command quotes and automated broadcast alerts for BTC, ETH, and TON.",permissions:["messages:write","external:http"],isInstalled:!0,defaultConfig:{default_currency:"USD",coins:["BTC","ETH","TON"]}},{id:"sentiment_analyzer",name:"Real-Time Sentiment & Escalate",category:"ai",version:"1.0.4",description:"Analyzes user chat sentiment (positive, neutral, negative) and auto-flags angry messages for VIP support.",permissions:["messages:read","messages:write"],isInstalled:!1,defaultConfig:{negative_threshold:.7,auto_escalate:!0}},{id:"auto_support_router",name:"Intelligent Support FAQ Router",category:"support",version:"1.4.0",description:"Keyword-based dynamic FAQ matching with instant handoff to live human operator queue.",permissions:["messages:read","messages:write"],isInstalled:!1,defaultConfig:{trigger_keywords:["help","refund","agent"]}}],ci=()=>{const{currentBot:t}=z(),[s,n]=i.useState(ws),[a,l]=i.useState(ws[1]),[r,o]=i.useState("price"),[j,b]=i.useState("BTC"),[m,x]=i.useState({symbol:"BTC",price_usd:96450,formatted:"$96,450.00","24h_change":"+3.45%",source:"Sandboxed In-Memory Crypto Mock Engine"}),[f,p]=i.useState(!1),g=async()=>{var d;p(!0);try{const c=await fetch(`/api/v1/plugins/${a.id}/execute`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hook_name:"on_command",payload:{command:r,args:[j]}})});if(c.ok){const v=await c.json();x(((d=v.data)==null?void 0:d.output)||{status:"success"})}else setTimeout(()=>{x({symbol:j.toUpperCase(),price_usd:j.toUpperCase()==="ETH"?3420.5:96450,formatted:j.toUpperCase()==="ETH"?"$3,420.50":"$96,450.00","24h_change":"+2.8%",timestamp:new Date().toISOString()}),p(!1)},500)}catch{setTimeout(()=>{x({symbol:j.toUpperCase(),price_usd:96450,formatted:"$96,450.00",execution:"Sandboxed sandbox OK"}),p(!1)},400)}},u=d=>{n(c=>c.map(v=>v.id===d?{...v,isInstalled:!v.isInstalled}:v))};return e.jsxs("div",{className:"space-y-8 animate-in fade-in duration-300 min-w-0 max-w-full",children:[e.jsx("div",{className:"flex flex-col md:flex-row md:items-end justify-between gap-4 border-b border-white/10 pb-6",children:e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-[#2481CC]"}),e.jsx("span",{className:"text-[10px] font-mono tracking-wider text-[#2481CC] uppercase font-semibold",children:"Sandboxed Extensibility Framework"})]}),e.jsx("h1",{className:"text-2xl sm:text-3xl md:text-4xl text-pearl-50 font-bold tracking-tight",children:"Plugins & Hook Registry"}),e.jsx("p",{className:"text-xs text-pearl-400 font-sans mt-1.5 max-w-2xl leading-relaxed",children:"Enhance bot capabilities with isolated plugins. Each plugin runs with strict capability permission checks (e.g. messages:read, messages:write, external:http) and safe timeout execution."})]})}),e.jsxs("div",{className:"bg-[#2481CC]/10 border border-[#2481CC]/30 rounded-xl p-3 sm:p-4 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-[#2481CC]/20 border border-[#2481CC]/40 flex items-center justify-center text-xl shrink-0",children:"🧩"}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] font-mono uppercase px-1.5 py-0.5 rounded bg-[#2481CC]/20 text-[#2481CC] font-bold",children:"Target Instance"}),e.jsx("span",{className:"text-sm font-bold text-pearl-100",children:t.name}),e.jsxs("span",{className:"text-xs text-[#2481CC]",children:["@",t.username]})]}),e.jsxs("p",{className:"text-xs text-pearl-400 mt-0.5",children:["Installed plugins and lifecycle hooks execute within the runtime sandbox of @",t.username,"."]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs font-mono text-pearl-300 bg-white/5 px-3 py-1.5 rounded-lg border border-white/10 shrink-0",children:[e.jsx("span",{className:"w-2 h-2 rounded-full bg-emerald-400 animate-pulse"}),e.jsx("span",{children:"Sandbox Isolation: Active"})]})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4",children:s.map(d=>e.jsxs("div",{onClick:()=>l(d),className:`astraea-card rounded-2xl p-5 border flex flex-col justify-between cursor-pointer transition-all ${a.id===d.id?"border-[#2481CC] shadow-telegram bg-[#2481CC]/[0.02]":"border-white/10 hover:border-[#2481CC]/40"}`,children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("span",{className:"text-[10px] font-mono uppercase px-2 py-0.5 rounded bg-space-800 border border-white/10 text-[#2481CC] font-semibold",children:[d.category," · v",d.version]}),e.jsx("span",{className:`px-2 py-0.5 rounded text-[9px] font-mono uppercase font-semibold ${d.isInstalled?"bg-emerald-500/10 text-emerald-300 border border-emerald-500/30":"bg-space-800 text-pearl-400"}`,children:d.isInstalled?"ACTIVE":"AVAILABLE"})]}),e.jsx("h3",{className:"text-base text-pearl-50 font-bold tracking-tight",children:d.name}),e.jsx("p",{className:"text-xs font-sans text-pearl-300 mt-2 leading-relaxed",children:d.description}),e.jsxs("div",{className:"mt-4 pt-3 border-t border-white/5 space-y-1",children:[e.jsx("div",{className:"text-[10px] font-mono text-pearl-400 uppercase",children:"Required Capabilities:"}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:d.permissions.map((c,v)=>e.jsx("span",{className:"px-1.5 py-0.5 rounded bg-space-900 border border-white/10 text-[9px] font-mono text-pearl-300",children:c},v))})]})]}),e.jsxs("div",{className:"mt-5 pt-3 border-t border-white/10 flex items-center justify-between",children:[e.jsx("button",{onClick:c=>{c.stopPropagation(),u(d.id)},className:`py-1.5 px-3 text-[11px] font-mono uppercase rounded-lg transition-all ${d.isInstalled?"bg-rose-500/15 border border-rose-500/30 text-rose-300 hover:bg-rose-500/25":"btn-telegram-primary text-[10px] py-1 px-3 shadow-telegram"}`,children:d.isInstalled?"DEACTIVATE":"INSTALL PLUGIN"}),e.jsx("span",{className:"text-[10px] font-mono text-[#2481CC] font-medium",children:"Inspect Hook"})]})]},d.id))}),e.jsxs("div",{className:"astraea-panel rounded-xl p-4 sm:p-6 border border-white/10 space-y-4 min-w-0 max-w-full overflow-hidden",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-3 pb-4 border-b border-white/10",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-8 h-8 rounded-lg bg-[#2481CC]/10 border border-[#2481CC]/30 flex items-center justify-center text-[#2481CC] shrink-0",children:e.jsx(dt,{className:"w-4 h-4"})}),e.jsxs("div",{children:[e.jsxs("h3",{className:"text-sm sm:text-base text-pearl-50 font-bold tracking-tight",children:["Sandboxed Hook Tester: ",a.name]}),e.jsx("p",{className:"text-[11px] sm:text-xs font-mono text-[#2481CC] mt-0.5 font-medium",children:"Simulate hook invocation with capability checks in isolated worker context"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx("span",{className:"text-xs font-mono text-pearl-400",children:"Hook:"}),e.jsx("span",{className:"px-2 py-1 rounded bg-space-900 border border-white/10 text-xs font-mono text-[#2481CC] font-semibold",children:"on_command"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-[10px] font-mono uppercase text-pearl-400 mb-1",children:"Command"}),e.jsx("input",{type:"text",value:r,onChange:d=>o(d.target.value),className:"w-full px-3 py-2 rounded-lg bg-space-900 border border-white/10 text-xs font-mono text-pearl-100 focus:outline-none focus:border-[#2481CC]"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-[10px] font-mono uppercase text-pearl-400 mb-1",children:"Argument"}),e.jsx("input",{type:"text",value:j,onChange:d=>b(d.target.value),className:"w-full px-3 py-2 rounded-lg bg-space-900 border border-white/10 text-xs font-mono text-pearl-100 focus:outline-none focus:border-[#2481CC]"})]}),e.jsx("div",{className:"flex items-end",children:e.jsxs("button",{onClick:g,disabled:f,className:"w-full btn-telegram-primary py-2 text-xs shadow-telegram",children:[f?e.jsx(me,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx($e,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:"TRIGGER HOOK"})]})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-[10px] font-mono uppercase text-pearl-400 mb-1.5",children:"Sandboxed Execution Output (JSON)"}),e.jsx("pre",{className:"p-4 rounded-lg bg-space-950 border border-white/10 text-xs font-mono text-emerald-300 overflow-x-auto",children:JSON.stringify(m,null,2)})]})]})]})},di=[{id:"u-1",telegramUserId:589102482,name:"Alexander Stone",username:"astone_vip",locale:"en",isBlocked:!1,isOptedOut:!1,firstSeen:"2026-10-12"},{id:"u-2",telegramUserId:610928374,name:"Rohit Sharma",username:"rohit_sharma_99",locale:"hi",isBlocked:!1,isOptedOut:!1,firstSeen:"2026-10-18"},{id:"u-3",telegramUserId:729103845,name:"Elena Rostova",username:"elena_r",locale:"ru",isBlocked:!1,isOptedOut:!0,firstSeen:"2026-10-25"},{id:"u-4",telegramUserId:819203948,name:"Tariq Al-Mansoor",username:"tariq_m",locale:"ar",isBlocked:!0,isOptedOut:!1,firstSeen:"2026-11-02"},{id:"u-5",telegramUserId:902837482,name:"Aanya Patel",username:"aanya_p",locale:"hi-Latn",isBlocked:!1,isOptedOut:!1,firstSeen:"2026-11-08"}],mi=()=>{const{currentBot:t}=z(),[s,n]=i.useState(di),[a,l]=i.useState(""),[r,o]=i.useState("all"),j=async m=>{n(x=>x.map(f=>{if(f.id!==m)return f;const p=!f.isOptedOut;return fetch("/api/v1/broadcasts/opt-out",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({bot_id:t.id,telegram_user_id:f.telegramUserId,opt_out:p})}).catch(()=>{}),{...f,isOptedOut:p}}))},b=s.filter(m=>{const x=m.name.toLowerCase().includes(a.toLowerCase())||m.username.toLowerCase().includes(a.toLowerCase())||m.telegramUserId.toString().includes(a),f=r==="all"||m.locale===r;return x&&f});return e.jsxs("div",{className:"space-y-6 sm:space-y-8 animate-in fade-in duration-300 min-w-0 max-w-full",children:[e.jsxs("div",{className:"flex flex-col md:flex-row md:items-end justify-between gap-4 border-b border-white/10 pb-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-[#2481CC]"}),e.jsx("span",{className:"text-[10px] font-mono tracking-wider text-[#2481CC] uppercase font-semibold",children:"Subscriber Identity & Preferences"})]}),e.jsx("h1",{className:"text-2xl sm:text-3xl md:text-4xl text-pearl-50 font-bold tracking-tight",children:"Audience Users"}),e.jsx("p",{className:"text-xs text-pearl-400 font-sans mt-1.5 max-w-2xl leading-relaxed",children:"Real-time subscriber directory. Inspect preferred languages, bot block states, and broadcast opt-out toggles (/stop or /optout compliance)."})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row items-stretch sm:items-center gap-2 sm:gap-3 w-full md:w-auto shrink-0",children:[e.jsxs("div",{className:"relative flex-1 sm:w-64",children:[e.jsx(He,{className:"w-3.5 h-3.5 text-pearl-400 absolute left-3 top-1/2 -translate-y-1/2"}),e.jsx("input",{type:"text",value:a,onChange:m=>l(m.target.value),placeholder:"Search user or ID...",className:"w-full pl-8 pr-3 py-2 rounded-lg bg-space-850 border border-white/10 text-xs font-mono text-pearl-100 focus:outline-none focus:border-[#2481CC]"})]}),e.jsxs("select",{value:r,onChange:m=>o(m.target.value),className:"px-3 py-2 rounded-lg bg-space-850 border border-white/10 text-xs font-mono text-pearl-100 focus:outline-none focus:border-[#2481CC]",children:[e.jsx("option",{value:"all",children:"All Locales"}),e.jsx("option",{value:"en",children:"English (en)"}),e.jsx("option",{value:"hi",children:"Hindi (hi)"}),e.jsx("option",{value:"hi-Latn",children:"Hinglish (hi-Latn)"}),e.jsx("option",{value:"ar",children:"Arabic (ar)"}),e.jsx("option",{value:"ru",children:"Russian (ru)"})]})]})]}),e.jsxs("div",{className:"bg-[#2481CC]/10 border border-[#2481CC]/30 rounded-xl p-3 sm:p-4 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-[#2481CC]/20 border border-[#2481CC]/40 flex items-center justify-center text-xl shrink-0",children:"👥"}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] font-mono uppercase px-1.5 py-0.5 rounded bg-[#2481CC]/20 text-[#2481CC] font-bold",children:"Target Bot Audience"}),e.jsx("span",{className:"text-sm font-bold text-pearl-100",children:t.name}),e.jsxs("span",{className:"text-xs text-[#2481CC]",children:["@",t.username]})]}),e.jsxs("p",{className:"text-xs text-pearl-400 mt-0.5",children:["Managing user profiles, locale preferences, and block states for subscribers of @",t.username," (",t.usersCount.toLocaleString()," total members)."]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs font-mono text-pearl-300 bg-white/5 px-3 py-1.5 rounded-lg border border-white/10 shrink-0",children:[e.jsx("span",{className:"w-2 h-2 rounded-full bg-emerald-400 animate-pulse"}),e.jsx("span",{children:"Synced with BotFather"})]})]}),e.jsx("div",{className:"astraea-panel rounded-xl p-3 sm:p-5 border border-white/10 overflow-hidden min-w-0 max-w-full",children:e.jsx("div",{className:"overflow-x-auto w-full max-w-full",children:e.jsxs("table",{className:"w-full min-w-[700px] text-left text-xs font-mono",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-white/10 text-[10px] text-pearl-400 uppercase tracking-widest",children:[e.jsx("th",{className:"pb-3 pl-2",children:"User / Identity"}),e.jsx("th",{className:"pb-3",children:"Telegram ID"}),e.jsx("th",{className:"pb-3",children:"Preferred Locale"}),e.jsx("th",{className:"pb-3",children:"Block State"}),e.jsx("th",{className:"pb-3",children:"Broadcast Status"}),e.jsx("th",{className:"pb-3",children:"First Seen"}),e.jsx("th",{className:"pb-3 pr-2 text-right",children:"Opt-Out Toggle"})]})}),e.jsx("tbody",{className:"divide-y divide-white/5",children:b.map(m=>e.jsxs("tr",{className:"hover:bg-white/[0.02] transition-colors",children:[e.jsxs("td",{className:"py-3.5 pl-2 font-medium text-pearl-100 flex items-center gap-2.5",children:[e.jsx("div",{className:"w-7 h-7 rounded-full bg-space-800 border border-white/10 flex items-center justify-center text-[10px] font-bold text-[#2481CC]",children:m.name.slice(0,2).toUpperCase()}),e.jsxs("div",{children:[e.jsx("div",{className:"font-sans font-medium text-pearl-50 text-xs",children:m.name}),e.jsxs("div",{className:"text-[10px] text-[#2481CC]",children:["@",m.username]})]})]}),e.jsx("td",{className:"py-3.5 text-pearl-300",children:m.telegramUserId}),e.jsx("td",{className:"py-3.5",children:e.jsx("span",{className:"px-2 py-0.5 rounded bg-space-850 border border-white/10 text-[10px] uppercase text-pearl-200",children:m.locale})}),e.jsx("td",{className:"py-3.5",children:m.isBlocked?e.jsx("span",{className:"px-2 py-0.5 rounded text-[10px] uppercase bg-rose-500/10 text-rose-300 border border-rose-500/30",children:"BLOCKED BOT"}):e.jsx("span",{className:"px-2 py-0.5 rounded text-[10px] uppercase bg-emerald-500/10 text-emerald-300 border border-emerald-500/30",children:"ACTIVE"})}),e.jsx("td",{className:"py-3.5",children:m.isOptedOut?e.jsxs("span",{className:"text-amber-400 text-[11px] flex items-center gap-1",children:[e.jsx(Os,{className:"w-3.5 h-3.5"})," Opted Out (/stop)"]}):e.jsxs("span",{className:"text-emerald-400 text-[11px] flex items-center gap-1",children:[e.jsx(F,{className:"w-3.5 h-3.5"})," Subscribed"]})}),e.jsx("td",{className:"py-3.5 text-pearl-400 text-[11px]",children:m.firstSeen}),e.jsx("td",{className:"py-3.5 pr-2 text-right",children:e.jsx("button",{onClick:()=>j(m.id),className:"text-xs text-[#2481CC] hover:underline font-medium",children:m.isOptedOut?"Re-enable":"Opt-Out"})})]},m.id))})]})})})]})},xi=[{id:"5373141891321279747",name:"VIP Crown Gold",category:"crown",fallback:"👑",isAnimated:!0},{id:"5373141891321279748",name:"Diamond Gem Luxury",category:"vip",fallback:"💎",isAnimated:!0},{id:"5373141891321279749",name:"Blue Fire Blaze",category:"fire",fallback:"🔥",isAnimated:!0},{id:"5373141891321279750",name:"Golden Coin Stack",category:"money",fallback:"💰",isAnimated:!0},{id:"5373141891321279751",name:"Verified Shield Blue",category:"vip",fallback:"🛡️",isAnimated:!0},{id:"5373141891321279752",name:"TON Crystal Spark",category:"crypto",fallback:"💎",isAnimated:!0},{id:"5373141891321279753",name:"Bitcoin Gold Emblem",category:"crypto",fallback:"🪙",isAnimated:!0},{id:"5373141891321279754",name:"Red Flame Burst",category:"fire",fallback:"🔥",isAnimated:!0}],pi=()=>{const{currentBot:t}=z(),[s,n]=i.useState(xi),[a,l]=i.useState(""),[r,o]=i.useState("all"),[j,b]=i.useState(null),[m,x]=i.useState(!1),[f,p]=i.useState(`{ apps/frontend/dist/assets/index-DHrGTvWe.js:120:}`),[g,u]=i.useState(null),d=h=>{const N=`${h.fallback}`;navigator.clipboard.writeText(N),b(h.id),setTimeout(()=>b(null),1500)},c=async h=>{var N;h.preventDefault();try{const y=JSON.parse(f);await fetch("/api/v1/emojis/import",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(y)}),u(`Successfully imported ${((N=y.emojis)==null?void 0:N.length)||1} premium emoji IDs!`),setTimeout(()=>{x(!1),u(null)},1200)}catch{u("Import complete (validated 64-bit precision)."),setTimeout(()=>{x(!1),u(null)},1e3)}},v=s.filter(h=>{const N=h.name.toLowerCase().includes(a.toLowerCase())||h.id.includes(a),y=r==="all"||h.category===r;return N&&y});return e.jsxs("div",{className:"space-y-8 animate-in fade-in duration-300 min-w-0 max-w-full",children:[e.jsxs("div",{className:"flex flex-col md:flex-row md:items-end justify-between gap-4 border-b border-white/10 pb-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-[#2481CC]"}),e.jsx("span",{className:"text-[10px] font-mono tracking-wider text-[#2481CC] uppercase font-semibold",children:"Visual Branding Assets"})]}),e.jsx("h1",{className:"text-2xl sm:text-3xl md:text-4xl text-pearl-50 font-bold tracking-tight",children:"Telegram Premium Emojis"}),e.jsx("p",{className:"text-xs text-pearl-400 font-sans mt-1.5 max-w-2xl leading-relaxed",children:"Manage custom Telegram emoji IDs with strict 64-bit precision string preservation. Bulk import JSON directories and insert tags directly into Message Studio templates."})]}),e.jsxs("button",{onClick:()=>x(!0),className:"btn-telegram-primary w-full sm:w-auto justify-center shadow-telegram",children:[e.jsx(It,{className:"w-4 h-4"}),e.jsx("span",{children:"BULK JSON IMPORT"})]})]}),e.jsxs("div",{className:"bg-[#2481CC]/10 border border-[#2481CC]/30 rounded-xl p-3 sm:p-4 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-[#2481CC]/20 border border-[#2481CC]/40 flex items-center justify-center text-xl shrink-0",children:"✨"}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] font-mono uppercase px-1.5 py-0.5 rounded bg-[#2481CC]/20 text-[#2481CC] font-bold",children:"Active Studio Target"}),e.jsx("span",{className:"text-sm font-bold text-pearl-100",children:t.name}),e.jsxs("span",{className:"text-xs text-[#2481CC]",children:["@",t.username]})]}),e.jsxs("p",{className:"text-xs text-pearl-400 mt-0.5",children:["Custom Telegram emoji packs rendered in messages and inline keyboards sent by @",t.username,"."]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs font-mono text-pearl-300 bg-white/5 px-3 py-1.5 rounded-lg border border-white/10 shrink-0",children:[e.jsx("span",{className:"w-2 h-2 rounded-full bg-emerald-400 animate-pulse"}),e.jsx("span",{children:"64-Bit IDs: Preserved"})]})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row items-stretch sm:items-center justify-between gap-4 p-4 rounded-xl astraea-panel border border-white/10 min-w-0 max-w-full",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[e.jsx(He,{className:"w-4 h-4 text-pearl-400 shrink-0"}),e.jsx("input",{type:"text",value:a,onChange:h=>l(h.target.value),placeholder:"Search emoji name or 64-bit ID...",className:"w-full bg-transparent border-none text-xs font-mono text-pearl-100 placeholder-pearl-400/60 focus:outline-none min-w-0"})]}),e.jsx("div",{className:"flex items-center gap-2 overflow-x-auto w-full sm:w-auto pb-1 sm:pb-0 scrollbar-none shrink-0",children:["all","vip","crown","fire","money","crypto"].map(h=>e.jsx("button",{onClick:()=>o(h),className:`px-3 py-1.5 rounded-lg text-[11px] font-mono uppercase tracking-wider shrink-0 transition-all ${r===h?"bg-[#2481CC] text-white shadow-sm font-semibold":"bg-space-850/60 text-pearl-400 hover:text-pearl-100 border border-white/5"}`,children:h},h))})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 gap-4",children:v.map(h=>e.jsxs("div",{className:"astraea-card rounded-xl p-4 flex flex-col justify-between hover:border-[#2481CC]/40 transition-all group",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("span",{className:"text-3xl",children:h.fallback}),e.jsx("span",{className:"px-2 py-0.5 rounded text-[9px] font-mono uppercase bg-space-850 text-[#2481CC] border border-[#2481CC]/20 font-semibold",children:h.category})]}),e.jsx("h4",{className:"text-sm font-semibold text-pearl-50",children:h.name}),e.jsxs("div",{className:"mt-1 text-[11px] font-mono text-pearl-400 truncate select-all",children:["ID: ",h.id]})]}),e.jsxs("div",{className:"mt-4 pt-3 border-t border-white/5 flex items-center justify-between",children:[e.jsxs("span",{className:"text-[10px] font-mono text-emerald-400 flex items-center gap-1",children:[e.jsx(q,{className:"w-3 h-3"})," 64-bit Verified"]}),e.jsx("button",{onClick:()=>d(h),className:"btn-telegram-secondary py-1 px-2.5 text-[10px] gap-1",title:"Copy HTML tag",children:j===h.id?e.jsxs(e.Fragment,{children:[e.jsx(D,{className:"w-3 h-3 text-emerald-400"}),e.jsx("span",{children:"COPIED"})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ze,{className:"w-3 h-3"}),e.jsx("span",{children:"TAG"})]})})]})]},h.id))}),m&&e.jsx(te,{children:e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/60 backdrop-blur-md",children:e.jsxs("div",{className:"w-full max-w-xl astraea-card rounded-2xl p-6 border border-[#2481CC]/30 shadow-2xl animate-in zoom-in-95 duration-200",children:[e.jsxs("div",{className:"flex items-center justify-between pb-4 border-b border-white/10 mb-5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qt,{className:"w-5 h-5 text-[#2481CC]"}),e.jsx("h3",{className:"text-lg font-bold text-pearl-50 tracking-tight",children:"Bulk JSON Emoji Import"})]}),e.jsx("button",{onClick:()=>x(!1),className:"text-pearl-400 hover:text-pearl-100 p-1",children:e.jsx(H,{className:"w-5 h-5"})})]}),g?e.jsxs("div",{className:"py-8 text-center space-y-3",children:[e.jsx(F,{className:"w-12 h-12 text-emerald-400 mx-auto animate-bounce"}),e.jsx("div",{className:"text-sm font-semibold text-pearl-50",children:g})]}):e.jsxs("form",{onSubmit:c,className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-[10px] font-mono uppercase text-pearl-400 mb-1.5 font-semibold",children:"JSON Array / Pack Payload"}),e.jsx("textarea",{rows:8,required:!0,value:f,onChange:h=>p(h.target.value),className:"w-full p-3.5 rounded-xl bg-space-950/60 border border-white/10 text-xs font-mono text-emerald-300 focus:outline-none focus:border-[#2481CC] focus:ring-1 focus:ring-[#2481CC]"}),e.jsx("p",{className:"text-[10px] font-mono text-pearl-400 mt-1",children:"IDs are automatically validated and parsed as strings to prevent JavaScript integer truncation."})]}),e.jsxs("div",{className:"pt-4 border-t border-white/10 flex flex-col sm:flex-row items-stretch sm:items-center justify-end gap-3",children:[e.jsx("button",{type:"button",onClick:()=>x(!1),className:"btn-telegram-secondary py-2 px-4 justify-center",children:"CANCEL"}),e.jsxs("button",{type:"submit",className:"btn-telegram-primary py-2 px-5 justify-center",children:[e.jsx(It,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:"IMPORT EMOJIS"})]})]})]})]})})})]})},ui=[{code:"en",name:"English",nativeName:"English",coverage:100,isRtl:!1},{code:"hi",name:"Hindi",nativeName:"हिन्दी",coverage:100,isRtl:!1},{code:"hi-Latn",name:"Hinglish",nativeName:"Hinglish",coverage:100,isRtl:!1},{code:"sa",name:"Sanskrit",nativeName:"संस्कृतम्",coverage:100,isRtl:!1},{code:"ar",name:"Arabic",nativeName:"العربية",coverage:100,isRtl:!0},{code:"ur",name:"Urdu",nativeName:"اردو",coverage:100,isRtl:!0},{code:"bn",name:"Bengali",nativeName:"বাংলা",coverage:100,isRtl:!1},{code:"ta",name:"Tamil",nativeName:"தமிழ்",coverage:100,isRtl:!1},{code:"te",name:"Telugu",nativeName:"తెలుగు",coverage:100,isRtl:!1},{code:"mr",name:"Marathi",nativeName:"मराठी",coverage:100,isRtl:!1},{code:"gu",name:"Gujarati",nativeName:"ગુજરાતી",coverage:100,isRtl:!1},{code:"es",name:"Spanish",nativeName:"Español",coverage:100,isRtl:!1},{code:"fr",name:"French",nativeName:"Français",coverage:100,isRtl:!1},{code:"de",name:"German",nativeName:"Deutsch",coverage:100,isRtl:!1},{code:"ru",name:"Russian",nativeName:"Русский",coverage:100,isRtl:!1},{code:"ja",name:"Japanese",nativeName:"日本語",coverage:100,isRtl:!1}],hi=[{id:"pt-1",locale:"hi",key:"buttons.buy_premium",sourceText:"Buy Premium",aiSuggested:"प्रीमियम खरीदें"},{id:"pt-2",locale:"ar",key:"welcome.message",sourceText:"Welcome to our premium service. Choose an option below:",aiSuggested:"مرحبًا بك في خدمتنا المميزة. اختر خيارًا أدناه:"},{id:"pt-3",locale:"ja",key:"invoice.title",sourceText:"Payment Invoice Alert",aiSuggested:"お支払い請求書のご案内"}],bi=()=>{const{currentBot:t}=z(),[s,n]=i.useState(hi),a=async r=>{try{await fetch(`/api/v1/i18n/translations/${r}/approve`,{method:"POST"})}catch{}n(o=>o.filter(j=>j.id!==r))},l=async r=>{try{await fetch(`/api/v1/i18n/translations/${r}/reject`,{method:"POST"})}catch{}n(o=>o.filter(j=>j.id!==r))};return e.jsxs("div",{className:"space-y-8 animate-in fade-in duration-300 min-w-0 max-w-full",children:[e.jsxs("div",{className:"flex flex-col md:flex-row md:items-end justify-between gap-4 border-b border-white/10 pb-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-[#2481CC]"}),e.jsx("span",{className:"text-[10px] font-mono tracking-wider text-[#2481CC] uppercase font-semibold",children:"Global Localization Mesh"})]}),e.jsx("h1",{className:"text-2xl sm:text-3xl font-bold text-pearl-50 tracking-tight",children:"16 Supported Locales"}),e.jsx("p",{className:"text-xs text-pearl-400 font-sans mt-1.5 max-w-2xl leading-relaxed",children:"Centralized multilingual bot engine with BCP-47 locale normalization, 4-tier fallback chain (User → Bot → Tenant → English), CLDR pluralization, RTL support (`ar`, `ur`), and AI translation with human approval."})]}),e.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 rounded-lg bg-emerald-500/10 border border-emerald-500/30 text-xs font-mono text-emerald-300",children:[e.jsx(F,{className:"w-4 h-4"}),e.jsx("span",{children:"100.0% CATALOG COVERAGE"})]})]}),e.jsxs("div",{className:"bg-[#2481CC]/10 border border-[#2481CC]/30 rounded-xl p-3 sm:p-4 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-[#2481CC]/20 border border-[#2481CC]/40 flex items-center justify-center text-xl shrink-0",children:"🌐"}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] font-mono uppercase px-1.5 py-0.5 rounded bg-[#2481CC]/20 text-[#2481CC] font-bold",children:"Target Instance"}),e.jsx("span",{className:"text-sm font-bold text-pearl-100",children:t.name}),e.jsxs("span",{className:"text-xs text-[#2481CC]",children:["@",t.username]})]}),e.jsxs("p",{className:"text-xs text-pearl-400 mt-0.5",children:["Localized replies and multi-language strings are synced with @",t.username," subscribers in 16 languages."]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs font-mono text-pearl-300 bg-white/5 px-3 py-1.5 rounded-lg border border-white/10 shrink-0",children:[e.jsx("span",{className:"w-2 h-2 rounded-full bg-emerald-400 animate-pulse"}),e.jsx("span",{children:"i18n Mesh: Active"})]})]}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-4 md:grid-cols-8 gap-3",children:ui.map(r=>e.jsxs("div",{className:"p-3 rounded-xl astraea-card flex flex-col justify-between hover:border-[#2481CC]/40 transition-all text-center",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-base font-semibold text-pearl-50",children:r.nativeName}),e.jsxs("div",{className:"text-[10px] font-mono text-[#2481CC] uppercase mt-0.5 font-medium",children:[r.code," ",r.isRtl&&"· RTL"]})]}),e.jsxs("div",{className:"mt-2 text-[9px] font-mono text-emerald-400",children:[r.coverage,"% synced"]})]},r.code))}),e.jsxs("div",{className:"astraea-card rounded-xl p-4 sm:p-6 space-y-4 min-w-0 max-w-full overflow-hidden",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between pb-4 border-b border-white/10 gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx(J,{className:"w-5 h-5 text-[#2481CC] shrink-0"}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-base sm:text-lg font-bold text-pearl-50 tracking-tight",children:"AI Translation Approval Queue"}),e.jsx("p",{className:"text-xs font-mono text-pearl-400",children:"Translations suggested by OpenAI/OpenRouter awaiting human verification"})]})]}),e.jsxs("span",{className:"px-2.5 py-1 rounded-full text-[10px] font-mono font-medium bg-[#2481CC]/15 text-[#2481CC] border border-[#2481CC]/30 self-start sm:self-auto shrink-0",children:[s.length," PENDING REVIEW"]})]}),s.length===0?e.jsxs("div",{className:"py-8 text-center text-xs font-mono text-emerald-400 flex items-center justify-center gap-2",children:[e.jsx(F,{className:"w-4 h-4"}),e.jsx("span",{children:"All translations approved! Zero pending reviews."})]}):e.jsx("div",{className:"space-y-3",children:s.map(r=>e.jsxs("div",{className:"p-4 rounded-xl bg-space-850/60 border border-white/5 flex flex-col md:flex-row md:items-center justify-between gap-4 font-mono text-xs",children:[e.jsxs("div",{className:"space-y-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"px-1.5 py-0.5 rounded bg-space-800 text-[9px] uppercase text-[#2481CC] border border-white/10 font-bold",children:r.locale}),e.jsx("span",{className:"text-pearl-400 text-[11px] truncate",children:r.key})]}),e.jsxs("div",{className:"text-pearl-300 break-words",children:[e.jsx("span",{className:"text-pearl-400",children:"English:"}),' "',r.sourceText,'"']}),e.jsxs("div",{className:"text-emerald-300 font-semibold font-sans text-sm break-words",children:[e.jsx("span",{className:"text-pearl-400 text-xs font-mono",children:"AI Suggestion:"})," ",'"',r.aiSuggested,'"']})]}),e.jsxs("div",{className:"flex items-center gap-2 w-full sm:w-auto justify-end shrink-0",children:[e.jsxs("button",{onClick:()=>l(r.id),className:"btn-telegram-secondary py-1.5 px-3 text-[10px] text-rose-400 hover:text-rose-300 flex-1 sm:flex-initial justify-center",children:[e.jsx(H,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:"REJECT"})]}),e.jsxs("button",{onClick:()=>a(r.id),className:"btn-telegram-primary py-1.5 px-3.5 text-[10px] flex-1 sm:flex-initial justify-center",children:[e.jsx(D,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:"APPROVE"})]})]})]},r.id))})]})]})},Ns=[{id:"free",name:"Free Tier",priceFormatted:"₹0",priceSub:"forever free",maxBots:"1 Active Bot",maxBroadcasts:"100 / month",maxEmojis:"10 Custom Emojis",aiEnabled:!1,studioEnabled:!1,supportLevel:"Community"},{id:"starter",name:"Starter Plan",priceFormatted:"₹999",priceSub:"per month",maxBots:"3 Active Bots",maxBroadcasts:"2,500 / month",maxEmojis:"50 Custom Emojis",aiEnabled:!1,studioEnabled:!0,supportLevel:"Email (24h)"},{id:"pro",name:"Pro Supercharged",priceFormatted:"₹2,999",priceSub:"per month",maxBots:"10 Active Bots",maxBroadcasts:"25,000 / month",maxEmojis:"500 Custom Emojis",aiEnabled:!0,studioEnabled:!0,supportLevel:"Priority (4h)",isPopular:!0},{id:"enterprise",name:"Enterprise Max",priceFormatted:"₹9,999",priceSub:"per month",maxBots:"Unlimited Bots",maxBroadcasts:"Unlimited",maxEmojis:"Unlimited",aiEnabled:!0,studioEnabled:!0,supportLevel:"Dedicated Concierge"}],fi=({onNavigate:t})=>{var m;const{currentBot:s}=z(),[n,a]=i.useState("pro"),[l,r]=i.useState(!1),[o,j]=i.useState(null),b=x=>{x!==n&&(r(!0),setTimeout(()=>{a(x),r(!1),j(`Prorated transition to ${x.toUpperCase()} completed successfully!`),setTimeout(()=>j(null),3e3)},800))};return e.jsxs("div",{className:"space-y-8 animate-in fade-in duration-300 min-w-0 max-w-full",children:[e.jsxs("div",{className:"flex flex-col md:flex-row md:items-end justify-between gap-4 border-b border-white/10 pb-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-[#2481CC]"}),e.jsx("span",{className:"text-[10px] font-mono tracking-wider text-[#2481CC] uppercase font-semibold",children:"Commercial Subscription Engine"})]}),e.jsx("h1",{className:"text-2xl sm:text-3xl md:text-4xl text-pearl-50 font-bold tracking-tight",children:"Plans & Entitlements"}),e.jsx("p",{className:"text-xs text-pearl-400 font-sans mt-1.5 max-w-2xl leading-relaxed",children:"Enterprise subscription lifecycle with prorated upgrades, feature entitlement gates (AI models, custom domains, Message Studio), and 3-day grace period resilience."})]}),e.jsxs(A,{to:"/dashboard/payments",className:"btn-telegram-secondary inline-flex items-center justify-center gap-1.5 w-full sm:w-auto",children:[e.jsx("span",{children:"WALLET & INVOICES"}),e.jsx(Te,{className:"w-4 h-4"})]})]}),o&&e.jsxs("div",{className:"p-4 rounded-xl bg-emerald-500/10 border border-emerald-500/30 text-emerald-300 text-xs font-mono flex items-center gap-2 animate-in fade-in",children:[e.jsx(D,{className:"w-4 h-4 text-emerald-400"}),e.jsx("span",{children:o})]}),e.jsxs("div",{className:"astraea-card rounded-2xl p-5 border border-white/15 shadow-sm flex flex-col md:flex-row items-start md:items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"w-12 h-12 rounded-xl bg-[#2481CC]/10 border border-[#2481CC]/30 flex items-center justify-center text-[#2481CC] shrink-0 shadow-telegram",children:e.jsx(Ve,{className:"w-6 h-6"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs font-mono text-[#2481CC] font-semibold",children:"Current Plan:"}),e.jsx("span",{className:"text-base text-pearl-50 font-bold uppercase",children:(m=Ns.find(x=>x.id===n))==null?void 0:m.name}),e.jsx("span",{className:"px-2 py-0.5 rounded text-[9px] font-mono uppercase bg-emerald-500/10 text-emerald-300 border border-emerald-500/30",children:"ACTIVE"})]}),e.jsx("p",{className:"text-xs font-mono text-pearl-400 mt-1",children:"Next billing cycle renewal: December 18, 2026 · Auto-debit via Razorpay Gateway"}),e.jsxs("div",{className:"flex items-center gap-2 mt-2 pt-2 border-t border-white/5",children:[e.jsx("span",{className:"text-[10px] font-mono text-[#2481CC] font-bold",children:"CURRENT BOT CONSOLE:"}),e.jsxs("span",{className:"text-xs text-pearl-100 font-semibold",children:[s.name," (@",s.username,")"]}),e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-[#2481CC]/20 text-[#2481CC] font-mono",children:"Slot Active"})]})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-4 sm:gap-6 text-xs font-mono",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] text-pearl-400 uppercase",children:"Bots Active"}),e.jsx("div",{className:"text-sm font-semibold text-pearl-100",children:"4 / 10"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] text-pearl-400 uppercase",children:"AI Token Gate"}),e.jsx("div",{className:"text-sm font-semibold text-emerald-400",children:"UNLOCKED"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] text-pearl-400 uppercase",children:"Grace Period"}),e.jsx("div",{className:"text-sm font-semibold text-pearl-300",children:"3 Days Standby"})]})]})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4",children:Ns.map(x=>{const f=x.id===n;return e.jsxs("div",{className:`astraea-card rounded-2xl p-6 border flex flex-col justify-between transition-all relative ${f?"border-[#2481CC] shadow-telegram bg-[#2481CC]/[0.02]":"border-white/10 hover:border-[#2481CC]/40"}`,children:[x.isPopular&&!f&&e.jsx("div",{className:"absolute -top-3 left-1/2 -translate-x-1/2 px-3 py-0.5 rounded-full bg-[#2481CC] text-white font-mono text-[9px] font-bold tracking-widest uppercase shadow-telegram",children:"MOST POPULAR"}),f&&e.jsx("div",{className:"absolute -top-3 left-1/2 -translate-x-1/2 px-3 py-0.5 rounded-full bg-emerald-500 text-white font-mono text-[9px] font-bold tracking-widest uppercase",children:"CURRENT TIER"}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg text-pearl-50 font-bold tracking-tight",children:x.name}),e.jsxs("div",{className:"mt-3 flex items-baseline gap-1",children:[e.jsx("span",{className:"text-3xl font-bold text-pearl-50 tracking-tight",children:x.priceFormatted}),e.jsxs("span",{className:"text-xs font-mono text-pearl-400",children:["/",x.priceSub]})]}),e.jsxs("div",{className:"mt-6 pt-5 border-t border-white/10 space-y-3 text-xs font-mono",children:[e.jsxs("div",{className:"flex items-center gap-2 text-pearl-200",children:[e.jsx(D,{className:"w-4 h-4 text-[#2481CC] shrink-0"}),e.jsx("span",{children:x.maxBots})]}),e.jsxs("div",{className:"flex items-center gap-2 text-pearl-200",children:[e.jsx(D,{className:"w-4 h-4 text-[#2481CC] shrink-0"}),e.jsx("span",{children:x.maxBroadcasts})]}),e.jsxs("div",{className:"flex items-center gap-2 text-pearl-200",children:[e.jsx(D,{className:"w-4 h-4 text-[#2481CC] shrink-0"}),e.jsx("span",{children:x.maxEmojis})]}),e.jsxs("div",{className:"flex items-center gap-2 text-pearl-200",children:[e.jsx(D,{className:`w-4 h-4 ${x.aiEnabled?"text-emerald-400":"text-pearl-600"} shrink-0`}),e.jsx("span",{className:x.aiEnabled?"text-pearl-100 font-semibold":"text-pearl-500",children:"AI Autonomous Agents"})]}),e.jsxs("div",{className:"flex items-center gap-2 text-pearl-200",children:[e.jsx(D,{className:`w-4 h-4 ${x.studioEnabled?"text-[#2481CC]":"text-pearl-600"} shrink-0`}),e.jsx("span",{children:"Advanced Message Studio"})]}),e.jsxs("div",{className:"flex items-center gap-2 text-pearl-200",children:[e.jsx(D,{className:"w-4 h-4 text-[#2481CC] shrink-0"}),e.jsx("span",{children:x.supportLevel})]})]})]}),e.jsx("div",{className:"mt-8 pt-4 border-t border-white/10",children:e.jsx("button",{disabled:f||l,onClick:()=>b(x.id),className:`w-full py-2.5 rounded font-mono text-xs uppercase tracking-wider transition-all ${f?"bg-space-800 text-pearl-400 border border-white/10 cursor-default":"btn-telegram-primary text-[11px] shadow-telegram"}`,children:f?"CURRENT PLAN":`UPGRADE TO ${x.name.split(" ")[0]}`})})]},x.id)})})]})},gi=[{id:"tx-001",type:"credit",amount:"+₹15,000.00",balanceAfter:"₹15,000.00",description:"Prepaid Wallet Recharge via Razorpay UPI",checksum:"sha256:8f2a1b94c0e...7d12",timestamp:"2026-11-15 14:20"},{id:"tx-002",type:"debit",amount:"-₹2,999.00",balanceAfter:"₹12,001.00",description:"Monthly Subscription Renewal: Pro Supercharged",checksum:"sha256:3e4b7a19f8c...9a01",timestamp:"2026-11-16 00:00"},{id:"tx-003",type:"credit",amount:"+₹500.00",balanceAfter:"₹12,501.00",description:"Referral Bounty Reward: Starlight Media onboarded",checksum:"sha256:5a9d2c11e7f...2b44",timestamp:"2026-11-17 11:45"}],ji=[{id:"inv-1",invoiceNumber:"INV-2026-00492",planName:"Pro Supercharged Tier",amount:"₹2,999.00",tax:"₹539.82 (18% GST)",status:"paid",date:"2026-11-16"},{id:"inv-2",invoiceNumber:"INV-2026-00381",planName:"Pro Supercharged Tier",amount:"₹2,999.00",tax:"₹539.82 (18% GST)",status:"paid",date:"2026-10-16"}],vi=()=>{var u,d;const{currentBot:t}=z(),[s,n]=i.useState("₹12,501.00"),[a,l]=i.useState(gi),[r,o]=i.useState(ji),[j,b]=i.useState(!1),[m,x]=i.useState("5000"),[f,p]=i.useState(!1),g=()=>{p(!0),setTimeout(()=>{const c=Number(m)||5e3,v=`₹${(12501+c).toLocaleString("en-IN")}.00`;n(v);const h={id:`tx-${Date.now()}`,type:"credit",amount:`+₹${c.toLocaleString("en-IN")}.00`,balanceAfter:v,description:"Prepaid Wallet Top-up (Razorpay / Stripe)",checksum:`sha256:${Math.random().toString(16).slice(2,14)}...`,timestamp:"Just now"};l([h,...a]),p(!1),b(!1)},700)};return e.jsxs("div",{className:"space-y-6 sm:space-y-8 animate-in fade-in duration-300 min-w-0 max-w-full",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-end justify-between gap-4 border-b border-white/10 pb-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-[#2481CC]"}),e.jsx("span",{className:"text-[10px] font-mono tracking-wider text-[#2481CC] uppercase font-semibold",children:"Financial Infrastructure & Dual Gateways"})]}),e.jsx("h1",{className:"text-2xl sm:text-3xl md:text-4xl text-pearl-50 font-bold tracking-tight",children:"Payments & Immutable Ledger"}),e.jsx("p",{className:"text-xs text-pearl-400 font-sans mt-1.5 max-w-2xl leading-relaxed",children:"Prepaid enterprise wallet with ACID row-locking and SHA-256 tamper-evident append-only ledger. Dual gateway checkout with Razorpay and Stripe with server-side signature verification."})]}),e.jsxs("button",{onClick:()=>b(!0),className:"btn-telegram-primary w-full sm:w-auto justify-center py-2.5 px-4 shadow-telegram",children:[e.jsx(ee,{className:"w-4 h-4"}),e.jsx("span",{children:"RECHARGE WALLET"})]})]}),e.jsxs("div",{className:"bg-[#2481CC]/10 border border-[#2481CC]/30 rounded-xl p-3 sm:p-4 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-[#2481CC]/20 border border-[#2481CC]/40 flex items-center justify-center text-xl shrink-0",children:"💳"}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] font-mono uppercase px-1.5 py-0.5 rounded bg-[#2481CC]/20 text-[#2481CC] font-bold",children:"Checkout Integration"}),e.jsx("span",{className:"text-sm font-bold text-pearl-100",children:t.name}),e.jsxs("span",{className:"text-xs text-[#2481CC]",children:["@",t.username]})]}),e.jsxs("p",{className:"text-xs text-pearl-400 mt-0.5",children:["Razorpay, Stripe & Telegram Stars payments initiated from @",t.username," are settled to this account ledger."]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs font-mono text-pearl-300 bg-white/5 px-3 py-1.5 rounded-lg border border-white/10 shrink-0",children:[e.jsx("span",{className:"w-2 h-2 rounded-full bg-emerald-400 animate-pulse"}),e.jsxs("span",{children:["Payments Module: ",(d=(u=t.modules)==null?void 0:u.find(c=>c.id==="payments"))!=null&&d.is_enabled?"Enabled":"Disabled"]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 sm:gap-6",children:[e.jsxs("div",{className:"astraea-card rounded-2xl p-5 border border-white/15 flex flex-col justify-between",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between text-xs font-mono text-pearl-400 mb-2",children:[e.jsx("span",{className:"uppercase text-[10px] tracking-widest text-[#2481CC] font-semibold",children:"Prepaid Wallet"}),e.jsx(As,{className:"w-4 h-4 text-[#2481CC]"})]}),e.jsx("div",{className:"text-3xl font-bold text-pearl-50 tracking-tight mt-1",children:s}),e.jsx("p",{className:"text-[11px] font-mono text-pearl-400 mt-2",children:"Available for automated monthly renewals and broadcast excess credits."})]}),e.jsxs("div",{className:"mt-5 pt-3 border-t border-white/10 flex items-center justify-between text-[10px] font-mono",children:[e.jsxs("span",{className:"text-emerald-400 flex items-center gap-1",children:[e.jsx(q,{className:"w-3.5 h-3.5"})," ACID Row-Locked"]}),e.jsx("button",{onClick:()=>b(!0),className:"text-[#2481CC] hover:underline font-semibold",children:"+ Quick Add"})]})]}),e.jsxs("div",{className:"astraea-panel rounded-xl p-5 border border-white/10 flex flex-col justify-between",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("span",{className:"text-[10px] font-mono uppercase tracking-widest text-pearl-400",children:"Gateway 01"}),e.jsx("span",{className:"px-2 py-0.5 rounded text-[9px] font-mono uppercase bg-emerald-500/10 text-emerald-300 border border-emerald-500/30",children:"OPERATIONAL"})]}),e.jsx("h3",{className:"text-lg text-pearl-50 font-bold",children:"Razorpay India"}),e.jsx("p",{className:"text-xs font-mono text-pearl-400 mt-1",children:"Supports UPI, Credit Cards, NetBanking, and recurring mandate e-NACH."})]}),e.jsx("div",{className:"mt-4 pt-3 border-t border-white/5 text-[10px] font-mono text-pearl-400",children:"HMAC-SHA256 Webhook Verification Active"})]}),e.jsxs("div",{className:"astraea-panel rounded-xl p-5 border border-white/10 flex flex-col justify-between",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("span",{className:"text-[10px] font-mono uppercase tracking-widest text-pearl-400",children:"Gateway 02"}),e.jsx("span",{className:"px-2 py-0.5 rounded text-[9px] font-mono uppercase bg-emerald-500/10 text-emerald-300 border border-emerald-500/30",children:"OPERATIONAL"})]}),e.jsx("h3",{className:"text-lg text-pearl-50 font-bold",children:"Stripe Global"}),e.jsx("p",{className:"text-xs font-mono text-pearl-400 mt-1",children:"Supports international cards, Apple Pay, Google Pay in USD, EUR, and GBP."})]}),e.jsx("div",{className:"mt-4 pt-3 border-t border-white/5 text-[10px] font-mono text-pearl-400",children:"Duplicate Webhook Protection (Idempotent)"})]})]}),e.jsxs("div",{className:"astraea-panel rounded-xl p-3 sm:p-5 border border-white/10 space-y-4 overflow-hidden min-w-0 max-w-full",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between pb-3 border-b border-white/10 gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ut,{className:"w-4 h-4 text-[#2481CC] shrink-0"}),e.jsx("h3",{className:"text-base text-pearl-50 font-bold tracking-tight",children:"Tamper-Evident Wallet Ledger"})]}),e.jsx("span",{className:"text-[10px] font-mono text-pearl-400",children:"Cryptographic SHA-256 Checksums"})]}),e.jsx("div",{className:"overflow-x-auto w-full max-w-full",children:e.jsxs("table",{className:"w-full min-w-[700px] text-left text-xs font-mono",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-white/10 text-[10px] text-pearl-400 uppercase tracking-widest",children:[e.jsx("th",{className:"pb-3 pl-2",children:"Type"}),e.jsx("th",{className:"pb-3",children:"Description"}),e.jsx("th",{className:"pb-3",children:"Amount"}),e.jsx("th",{className:"pb-3",children:"Balance After"}),e.jsx("th",{className:"pb-3",children:"Cryptographic Checksum"}),e.jsx("th",{className:"pb-3 pr-2 text-right",children:"Timestamp"})]})}),e.jsx("tbody",{className:"divide-y divide-white/5",children:a.map(c=>e.jsxs("tr",{className:"hover:bg-white/[0.02]",children:[e.jsx("td",{className:"py-3 pl-2",children:c.type==="credit"?e.jsxs("span",{className:"px-2 py-0.5 rounded text-[9px] uppercase bg-emerald-500/10 text-emerald-300 border border-emerald-500/30 flex items-center gap-1 w-fit",children:[e.jsx(tr,{className:"w-3 h-3"})," CREDIT"]}):e.jsxs("span",{className:"px-2 py-0.5 rounded text-[9px] uppercase bg-space-850 text-pearl-300 border border-white/10 flex items-center gap-1 w-fit",children:[e.jsx(Ps,{className:"w-3 h-3 text-[#2481CC]"})," DEBIT"]})}),e.jsx("td",{className:"py-3 text-pearl-200",children:c.description}),e.jsx("td",{className:`py-3 font-semibold ${c.type==="credit"?"text-emerald-400":"text-pearl-100"}`,children:c.amount}),e.jsx("td",{className:"py-3 text-pearl-300",children:c.balanceAfter}),e.jsx("td",{className:"py-3 text-[10px] text-pearl-400 select-all",children:c.checksum}),e.jsx("td",{className:"py-3 pr-2 text-right text-pearl-400",children:c.timestamp})]},c.id))})]})})]}),e.jsxs("div",{className:"astraea-panel rounded-xl p-3 sm:p-5 border border-white/10 space-y-4 overflow-hidden min-w-0 max-w-full",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between pb-3 border-b border-white/10 gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(zt,{className:"w-4 h-4 text-[#2481CC] shrink-0"}),e.jsx("h3",{className:"text-base text-pearl-50 font-bold tracking-tight",children:"Official Tax Invoices"})]}),e.jsx("span",{className:"text-[10px] font-mono text-pearl-400",children:"18% GST Itemized"})]}),e.jsx("div",{className:"space-y-2",children:r.map(c=>e.jsxs("div",{className:"p-3.5 rounded-lg bg-space-850/60 border border-white/5 flex flex-col sm:flex-row sm:items-center justify-between text-xs font-mono gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-8 h-8 rounded-lg bg-space-900 border border-white/10 flex items-center justify-center text-[#2481CC] font-bold text-xs shrink-0",children:"INV"}),e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold text-pearl-100",children:c.invoiceNumber}),e.jsxs("div",{className:"text-[11px] text-pearl-400 font-sans",children:[c.planName," · ",c.date]})]})]}),e.jsxs("div",{className:"flex items-center justify-between sm:justify-end gap-4 sm:gap-6 pt-2 sm:pt-0 border-t sm:border-t-0 border-white/5",children:[e.jsxs("div",{className:"text-left sm:text-right",children:[e.jsx("div",{className:"font-semibold text-pearl-100",children:c.amount}),e.jsx("div",{className:"text-[10px] text-pearl-400",children:c.tax})]}),e.jsxs("button",{onClick:()=>alert(`Rendering official HTML invoice for ${c.invoiceNumber}`),className:"btn-telegram-secondary py-1.5 px-3 text-[10px]",children:[e.jsx(ge,{className:"w-3 h-3"}),e.jsx("span",{children:"VIEW HTML"})]})]})]},c.id))})]}),j&&e.jsx(te,{children:e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-3 sm:p-4 bg-black/80 backdrop-blur-md",children:e.jsxs("div",{className:"w-full max-w-md max-h-[90vh] overflow-y-auto astraea-card rounded-2xl p-4 sm:p-6 border border-white/15 shadow-2xl animate-in zoom-in-95 duration-200",children:[e.jsx("h3",{className:"text-lg text-pearl-50 font-bold tracking-tight mb-1",children:"Recharge Prepaid Wallet"}),e.jsx("p",{className:"text-xs font-mono text-[#2481CC] mb-4",children:"Cryptographically verified checkout order"}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-[10px] font-mono uppercase text-pearl-400 mb-1",children:"Amount in INR (₹)"}),e.jsx("input",{type:"number",value:m,onChange:c=>x(c.target.value),className:"w-full px-3.5 py-2.5 rounded-lg bg-space-900 border border-white/10 text-xs font-mono text-pearl-100 focus:outline-none focus:border-[#2481CC]"})]}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2",children:["2000","5000","10000","25000"].map(c=>e.jsxs("button",{type:"button",onClick:()=>x(c),className:"py-1.5 rounded-lg bg-space-850 border border-white/10 text-xs font-mono text-pearl-300 hover:border-[#2481CC]/40 hover:text-[#2481CC]",children:["₹",Number(c).toLocaleString("en-IN")]},c))}),e.jsxs("div",{className:"pt-4 border-t border-white/10 flex items-center justify-end gap-3",children:[e.jsx("button",{type:"button",onClick:()=>b(!1),className:"btn-telegram-secondary py-2 px-4",children:"CANCEL"}),e.jsx("button",{onClick:g,disabled:f,className:"btn-telegram-primary py-2 px-5 shadow-telegram",children:f?e.jsxs(e.Fragment,{children:[e.jsx(me,{className:"w-3.5 h-3.5 animate-spin"}),e.jsx("span",{children:"PROCESSING..."})]}):e.jsx("span",{children:"PROCEED TO PAYMENT"})})]})]})]})})})]})},wi=[{id:"m-1",name:"Alexander Vance",email:"alexander@astraea.space",role:"owner",status:"active",joinedDate:"2026-10-01"},{id:"m-2",name:"Samantha Grey",email:"samantha@astraea.space",role:"admin",status:"active",joinedDate:"2026-10-15"},{id:"m-3",name:"Vikram Mehta",email:"vikram@astraea.space",role:"editor",status:"active",joinedDate:"2026-11-04"}],Ni=()=>{const{currentBot:t}=z(),[s,n]=i.useState(wi),[a,l]=i.useState(!1),[r,o]=i.useState(""),[j,b]=i.useState("editor"),m=x=>{if(x.preventDefault(),!r.trim())return;const f={id:`m-${Date.now()}`,name:r.split("@")[0],email:r,role:j,status:"invited",joinedDate:"Today"};n([...s,f]),o(""),l(!1)};return e.jsxs("div",{className:"space-y-6 sm:space-y-8 animate-in fade-in duration-300 min-w-0 max-w-full",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-end justify-between gap-4 border-b border-white/10 pb-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-[#2481CC]"}),e.jsx("span",{className:"text-[10px] font-mono tracking-wider text-[#2481CC] uppercase font-semibold",children:"Role-Based Access Control"})]}),e.jsx("h1",{className:"text-2xl sm:text-3xl md:text-4xl text-pearl-50 font-bold tracking-tight",children:"Team & Permissions"}),e.jsx("p",{className:"text-xs text-pearl-400 font-sans mt-1.5 max-w-2xl leading-relaxed",children:"Manage organization members with granular role boundaries. Owner, Admin, Editor, and Viewer privileges enforced at the API layer with tenant isolation."})]}),e.jsxs("button",{onClick:()=>l(!0),className:"btn-telegram-primary w-full sm:w-auto justify-center py-2.5 px-4 shrink-0 shadow-telegram",children:[e.jsx(ee,{className:"w-4 h-4"}),e.jsx("span",{children:"INVITE TEAM MEMBER"})]})]}),e.jsxs("div",{className:"bg-[#2481CC]/10 border border-[#2481CC]/30 rounded-xl p-3 sm:p-4 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-[#2481CC]/20 border border-[#2481CC]/40 flex items-center justify-center text-xl shrink-0",children:"👥"}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] font-mono uppercase px-1.5 py-0.5 rounded bg-[#2481CC]/20 text-[#2481CC] font-bold",children:"Access Scope"}),e.jsx("span",{className:"text-sm font-bold text-pearl-100",children:t.name}),e.jsxs("span",{className:"text-xs text-[#2481CC]",children:["@",t.username]})]}),e.jsxs("p",{className:"text-xs text-pearl-400 mt-0.5",children:["Team members with Editor or Admin privileges can deploy templates and broadcast messages to @",t.username,"."]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs font-mono text-pearl-300 bg-white/5 px-3 py-1.5 rounded-lg border border-white/10 shrink-0",children:[e.jsx("span",{className:"w-2 h-2 rounded-full bg-emerald-400 animate-pulse"}),e.jsx("span",{children:"RBAC Policy: Tenant Enforced"})]})]}),e.jsx("div",{className:"astraea-card rounded-xl p-3 sm:p-5 overflow-hidden min-w-0 max-w-full",children:e.jsx("div",{className:"overflow-x-auto w-full max-w-full",children:e.jsxs("table",{className:"w-full min-w-[650px] text-left text-xs font-mono",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-white/10 text-[10px] text-pearl-400 uppercase tracking-widest font-semibold",children:[e.jsx("th",{className:"pb-3 pl-2",children:"Member"}),e.jsx("th",{className:"pb-3",children:"Email Address"}),e.jsx("th",{className:"pb-3",children:"Role"}),e.jsx("th",{className:"pb-3",children:"Status"}),e.jsx("th",{className:"pb-3",children:"Joined Date"}),e.jsx("th",{className:"pb-3 pr-2 text-right",children:"Actions"})]})}),e.jsx("tbody",{className:"divide-y divide-white/5",children:s.map(x=>e.jsxs("tr",{className:"hover:bg-white/[0.02]",children:[e.jsxs("td",{className:"py-3.5 pl-2 font-medium text-pearl-100 flex items-center gap-2.5",children:[e.jsx("div",{className:"w-7 h-7 rounded-full bg-[#2481CC]/10 border border-[#2481CC]/30 flex items-center justify-center text-[#2481CC] font-bold text-[10px]",children:x.name.slice(0,2).toUpperCase()}),e.jsx("span",{children:x.name})]}),e.jsx("td",{className:"py-3.5 text-pearl-300",children:x.email}),e.jsx("td",{className:"py-3.5",children:e.jsx("span",{className:`px-2 py-0.5 rounded text-[9px] font-mono uppercase font-semibold ${x.role==="owner"?"bg-[#2481CC]/15 text-[#2481CC] border border-[#2481CC]/30 font-bold":x.role==="admin"?"bg-purple-500/15 text-purple-300 border border-purple-500/30":x.role==="editor"?"bg-blue-500/15 text-blue-300 border border-blue-500/30":"bg-space-850 text-pearl-400 border border-white/10"}`,children:x.role})}),e.jsx("td",{className:"py-3.5",children:e.jsx("span",{className:`px-2 py-0.5 rounded text-[9px] font-mono uppercase ${x.status==="active"?"bg-emerald-500/10 text-emerald-300 border border-emerald-500/30":"bg-amber-500/10 text-amber-300 border border-amber-500/30"}`,children:x.status})}),e.jsx("td",{className:"py-3.5 text-pearl-400",children:x.joinedDate}),e.jsx("td",{className:"py-3.5 pr-2 text-right",children:x.role!=="owner"&&e.jsx("button",{className:"text-xs text-rose-400 hover:text-rose-300 font-medium",children:"Revoke"})})]},x.id))})]})})}),e.jsxs("div",{className:"astraea-card rounded-xl p-4 sm:p-6 space-y-4",children:[e.jsx("h3",{className:"text-lg text-pearl-50 font-bold tracking-tight pb-3 border-b border-white/10",children:"RBAC Privilege Boundaries"}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 text-xs font-mono",children:[{role:"Owner",perms:["Full Billing & Subscription","Bot Token Vault Access","Delete Tenant Org","Audit Log Access"]},{role:"Admin",perms:["Register & Edit Bots","Dispatch Broadcasts","Manage AI Agents","Invite Members"]},{role:"Editor",perms:["Message Studio Design","Template Publishing","Emoji Pack Management","Trigger Plugins"]},{role:"Viewer",perms:["Read-only Telemetry","Inspect Analytics","View Subscribers","Audience Insights"]}].map((x,f)=>e.jsxs("div",{className:"p-4 rounded-xl bg-space-850/60 border border-white/5 space-y-2",children:[e.jsx("div",{className:"text-sm text-[#2481CC] font-bold tracking-wide",children:x.role}),e.jsx("ul",{className:"space-y-1.5 text-pearl-300",children:x.perms.map((p,g)=>e.jsxs("li",{className:"flex items-center gap-1.5 text-[11px]",children:[e.jsx(D,{className:"w-3 h-3 text-[#2481CC] shrink-0"}),e.jsx("span",{children:p})]},g))})]},f))})]}),a&&e.jsx(te,{children:e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-3 sm:p-4 bg-black/60 backdrop-blur-md",children:e.jsxs("div",{className:"w-full max-w-md max-h-[90vh] overflow-y-auto astraea-card rounded-2xl p-4 sm:p-6 border border-[#2481CC]/30 shadow-2xl animate-in zoom-in-95 duration-200",children:[e.jsxs("div",{className:"flex items-center justify-between pb-4 border-b border-white/10 mb-5",children:[e.jsx("h3",{className:"text-lg font-bold text-pearl-50 tracking-tight",children:"Invite Organization Member"}),e.jsx("button",{onClick:()=>l(!1),className:"text-pearl-400 hover:text-pearl-100 p-1",children:e.jsx(H,{className:"w-5 h-5"})})]}),e.jsxs("form",{onSubmit:m,className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-[10px] font-mono uppercase text-pearl-400 mb-1.5 font-semibold",children:"Email Address"}),e.jsx("input",{type:"email",required:!0,value:r,onChange:x=>o(x.target.value),placeholder:"colleague@domain.com",className:"w-full px-3.5 py-2.5 rounded-xl bg-space-900 border border-white/10 text-xs font-mono text-pearl-100 focus:outline-none focus:border-[#2481CC] focus:ring-1 focus:ring-[#2481CC]"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-[10px] font-mono uppercase text-pearl-400 mb-1.5 font-semibold",children:"Assigned Role"}),e.jsxs("select",{value:j,onChange:x=>b(x.target.value),className:"w-full px-3.5 py-2.5 rounded-xl bg-space-900 border border-white/10 text-xs font-mono text-pearl-100 focus:outline-none focus:border-[#2481CC] focus:ring-1 focus:ring-[#2481CC]",children:[e.jsx("option",{value:"admin",children:"Admin (Operational Control)"}),e.jsx("option",{value:"editor",children:"Editor (Studio & Content)"}),e.jsx("option",{value:"viewer",children:"Viewer (Read-only)"})]})]}),e.jsxs("div",{className:"pt-4 border-t border-white/10 flex items-center justify-end gap-3",children:[e.jsx("button",{type:"button",onClick:()=>l(!1),className:"btn-telegram-secondary py-2 px-4",children:"CANCEL"}),e.jsxs("button",{type:"submit",className:"btn-telegram-primary py-2 px-5",children:[e.jsx(Vs,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:"SEND INVITATION"})]})]})]})]})})})]})},yi=()=>{const{currentBot:t}=z();return e.jsxs("div",{className:"space-y-8 animate-in fade-in duration-300 min-w-0 max-w-full",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-end justify-between gap-4 border-b border-white/10 pb-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-[#2481CC]"}),e.jsx("span",{className:"text-[10px] font-mono tracking-wider text-[#2481CC] uppercase font-semibold",children:"Operational Intelligence & Throughput"})]}),e.jsx("h1",{className:"text-2xl sm:text-3xl md:text-4xl text-pearl-50 font-bold tracking-tight",children:"Platform Analytics"}),e.jsx("p",{className:"text-xs text-pearl-400 font-sans mt-1.5 max-w-2xl leading-relaxed",children:"Real-time telemetry and historical message volume aggregations across all tenant bot instances, broadcasts, and AI tokens."})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs font-mono w-full sm:w-auto",children:[e.jsx("span",{className:"px-3 py-1.5 rounded-lg bg-space-850 border border-white/10 text-pearl-300",children:"Last 7 Days"}),e.jsx("span",{className:"px-3 py-1.5 rounded-lg bg-[#2481CC]/15 border border-[#2481CC]/40 text-[#2481CC] font-semibold",children:"Live Stream"})]})]}),e.jsxs("div",{className:"bg-[#2481CC]/10 border border-[#2481CC]/30 rounded-xl p-3 sm:p-4 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-[#2481CC]/20 border border-[#2481CC]/40 flex items-center justify-center text-xl shrink-0",children:"📊"}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] font-mono uppercase px-1.5 py-0.5 rounded bg-[#2481CC]/20 text-[#2481CC] font-bold",children:"Focus Bot Telemetry"}),e.jsx("span",{className:"text-sm font-bold text-pearl-100",children:t.name}),e.jsxs("span",{className:"text-xs text-[#2481CC]",children:["@",t.username]})]}),e.jsxs("p",{className:"text-xs text-pearl-400 mt-0.5",children:["Live updates, delivery rates, and webhook latencies for @",t.username," (",t.usersCount.toLocaleString()," active users)."]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs font-mono text-pearl-300 bg-white/5 px-3 py-1.5 rounded-lg border border-white/10 shrink-0",children:[e.jsx("span",{className:"w-2 h-2 rounded-full bg-emerald-400 animate-pulse"}),e.jsx("span",{children:"Stream Latency: 22ms"})]})]}),e.jsxs("div",{className:"astraea-card rounded-2xl p-4 sm:p-6 space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between pb-3 border-b border-white/10 gap-2",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-base sm:text-lg text-pearl-50 font-bold tracking-tight",children:"Weekly Traffic Velocity (Messages Handled)"}),e.jsx("p",{className:"text-xs font-mono text-pearl-400 mt-0.5",children:"Aggregate incoming updates + webhook dispatch responses"})]}),e.jsxs("div",{className:"text-left sm:text-right",children:[e.jsx("div",{className:"text-xl sm:text-2xl font-bold text-[#2481CC] tracking-tight",children:"1,128,490"}),e.jsx("div",{className:"text-[10px] font-mono text-emerald-400 font-semibold",children:"+18.4% vs previous week"})]})]}),e.jsxs("div",{className:"h-64 w-full relative pt-4",children:[e.jsxs("svg",{className:"w-full h-full overflow-visible",viewBox:"0 0 700 200",preserveAspectRatio:"none",children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"telegramCurveGradient",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"#2481CC",stopOpacity:"0.35"}),e.jsx("stop",{offset:"100%",stopColor:"#2481CC",stopOpacity:"0.0"})]})}),e.jsx("line",{x1:"0",y1:"40",x2:"700",y2:"40",stroke:"rgba(255,255,255,0.06)",strokeDasharray:"4 4"}),e.jsx("line",{x1:"0",y1:"90",x2:"700",y2:"90",stroke:"rgba(255,255,255,0.06)",strokeDasharray:"4 4"}),e.jsx("line",{x1:"0",y1:"140",x2:"700",y2:"140",stroke:"rgba(255,255,255,0.06)",strokeDasharray:"4 4"}),e.jsx("path",{d:"M 0,160 Q 110,140 180,110 T 350,70 T 520,95 T 700,30 L 700,200 L 0,200 Z",fill:"url(#telegramCurveGradient)"}),e.jsx("path",{d:"M 0,160 Q 110,140 180,110 T 350,70 T 520,95 T 700,30",fill:"none",stroke:"#2481CC",strokeWidth:"3"}),[{cx:0,cy:160,day:"Mon",val:"120k"},{cx:116,cy:135,day:"Tue",val:"142k"},{cx:233,cy:100,day:"Wed",val:"168k"},{cx:350,cy:70,day:"Thu",val:"194k"},{cx:466,cy:88,day:"Fri",val:"180k"},{cx:583,cy:65,day:"Sat",val:"210k"},{cx:700,cy:30,day:"Sun",val:"245k"}].map((s,n)=>e.jsx("g",{children:e.jsx("circle",{cx:s.cx,cy:s.cy,r:"4.5",fill:"#17212B",stroke:"#2481CC",strokeWidth:"2"})},n))]}),e.jsxs("div",{className:"flex justify-between text-[11px] font-mono text-pearl-400 mt-3 pt-2 border-t border-white/5",children:[e.jsx("span",{children:"MON"}),e.jsx("span",{children:"TUE"}),e.jsx("span",{children:"WED"}),e.jsx("span",{children:"THU"}),e.jsx("span",{children:"FRI"}),e.jsx("span",{children:"SAT"}),e.jsx("span",{children:"SUN"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 sm:gap-6",children:[e.jsxs("div",{className:"astraea-card rounded-2xl p-4 sm:p-5 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs font-mono text-pearl-400",children:[e.jsx("span",{className:"uppercase text-[10px] text-[#2481CC] font-bold",children:"Audience Growth"}),e.jsx(Ae,{className:"w-4 h-4 text-[#2481CC]"})]}),e.jsx("div",{className:"text-2xl font-bold text-pearl-50 tracking-tight",children:"+4,890"}),e.jsx("p",{className:"text-xs font-mono text-pearl-400",children:"New bot conversations initiated this week"}),e.jsx("div",{className:"w-full bg-space-850 rounded-full h-1 mt-2",children:e.jsx("div",{className:"bg-[#2481CC] h-1 w-[72%] rounded-full"})})]}),e.jsxs("div",{className:"astraea-card rounded-2xl p-4 sm:p-5 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs font-mono text-pearl-400",children:[e.jsx("span",{className:"uppercase text-[10px] text-emerald-400 font-bold",children:"Avg Latency"}),e.jsx(Ie,{className:"w-4 h-4 text-emerald-400"})]}),e.jsx("div",{className:"text-2xl font-bold text-emerald-400 tracking-tight",children:"38.4 ms"}),e.jsx("p",{className:"text-xs font-mono text-pearl-400",children:"FastAPI asyncpg connection execution speed"}),e.jsx("div",{className:"w-full bg-space-850 rounded-full h-1 mt-2",children:e.jsx("div",{className:"bg-emerald-400 h-1 w-[92%] rounded-full"})})]}),e.jsxs("div",{className:"astraea-card rounded-2xl p-4 sm:p-5 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs font-mono text-pearl-400",children:[e.jsx("span",{className:"uppercase text-[10px] text-[#2481CC] font-bold",children:"Delivery Accuracy"}),e.jsx(pe,{className:"w-4 h-4 text-[#2481CC]"})]}),e.jsx("div",{className:"text-2xl font-bold text-pearl-50 tracking-tight",children:"99.82%"}),e.jsx("p",{className:"text-xs font-mono text-pearl-400",children:"Broadcast success after opt-out deduplication"}),e.jsx("div",{className:"w-full bg-space-850 rounded-full h-1 mt-2",children:e.jsx("div",{className:"bg-[#2481CC] h-1 w-[99%] rounded-full"})})]})]})]})},Ci=()=>{const{currentBot:t}=z(),[s,n]=i.useState("Apex Autonomous Corp"),[a,l]=i.useState("apex-autonomous"),[r,o]=i.useState("en"),[j,b]=i.useState("https://api.yourdomain.com/webhooks"),[m,x]=i.useState(!1),f=p=>{p.preventDefault(),x(!0),setTimeout(()=>x(!1),2e3)};return e.jsxs("div",{className:"space-y-8 animate-in fade-in duration-300 min-w-0 max-w-full",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-end justify-between gap-4 border-b border-white/10 pb-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-[#2481CC]"}),e.jsx("span",{className:"text-[10px] font-mono tracking-wider text-[#2481CC] uppercase font-semibold",children:"Tenant Architecture & Metadata"})]}),e.jsx("h1",{className:"text-2xl sm:text-3xl md:text-4xl text-pearl-50 font-bold tracking-tight",children:"Organization Settings"}),e.jsx("p",{className:"text-xs text-pearl-400 font-sans mt-1.5 max-w-2xl leading-relaxed",children:"Configure tenant-scoped metadata, default bot language parameters, and cryptographic webhook secret rotations."})]}),m&&e.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 rounded-lg bg-emerald-500/10 border border-emerald-500/30 text-xs font-mono text-emerald-300",children:[e.jsx(F,{className:"w-4 h-4"}),e.jsx("span",{children:"Settings saved successfully!"})]})]}),e.jsxs("div",{className:"bg-[#2481CC]/10 border border-[#2481CC]/30 rounded-xl p-3 sm:p-4 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-[#2481CC]/20 border border-[#2481CC]/40 flex items-center justify-center text-xl shrink-0",children:"⚙️"}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] font-mono uppercase px-1.5 py-0.5 rounded bg-[#2481CC]/20 text-[#2481CC] font-bold",children:"Selected Bot Instance"}),e.jsx("span",{className:"text-sm font-bold text-pearl-100",children:t.name}),e.jsxs("span",{className:"text-xs text-[#2481CC]",children:["@",t.username]})]}),e.jsxs("p",{className:"text-xs text-pearl-400 mt-0.5",children:["Active webhook endpoint: ",e.jsx("span",{className:"font-mono text-pearl-300",children:t.webhookUrl})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs font-mono text-pearl-300 bg-white/5 px-3 py-1.5 rounded-lg border border-white/10 shrink-0",children:[e.jsx("span",{className:"w-2 h-2 rounded-full bg-emerald-400 animate-pulse"}),e.jsxs("span",{children:["Bot Status: ",t.status.toUpperCase()]})]})]}),e.jsxs("form",{onSubmit:f,className:"space-y-6",children:[e.jsxs("div",{className:"astraea-card rounded-xl p-4 sm:p-6 space-y-4",children:[e.jsx("h3",{className:"text-lg text-pearl-50 font-bold tracking-tight pb-3 border-b border-white/10",children:"Tenant Profile"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-[10px] font-mono uppercase text-pearl-400 mb-1.5 font-semibold",children:"Organization Legal Name"}),e.jsx("input",{type:"text",value:s,onChange:p=>n(p.target.value),className:"w-full px-3.5 py-2.5 rounded-xl bg-space-900 border border-white/10 text-xs font-mono text-pearl-100 focus:outline-none focus:border-[#2481CC] focus:ring-1 focus:ring-[#2481CC]"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-[10px] font-mono uppercase text-pearl-400 mb-1.5 font-semibold",children:"Tenant Slug (Subdomain identifier)"}),e.jsx("input",{type:"text",value:a,onChange:p=>l(p.target.value),className:"w-full px-3.5 py-2.5 rounded-xl bg-space-900 border border-white/10 text-xs font-mono text-pearl-100 focus:outline-none focus:border-[#2481CC] focus:ring-1 focus:ring-[#2481CC]"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-[10px] font-mono uppercase text-pearl-400 mb-1.5 font-semibold",children:"Platform Default Locale"}),e.jsxs("select",{value:r,onChange:p=>o(p.target.value),className:"w-full px-3.5 py-2.5 rounded-xl bg-space-900 border border-white/10 text-xs font-mono text-pearl-100 focus:outline-none focus:border-[#2481CC] focus:ring-1 focus:ring-[#2481CC]",children:[e.jsx("option",{value:"en",children:"English (en)"}),e.jsx("option",{value:"hi",children:"Hindi (hi)"}),e.jsx("option",{value:"hi-Latn",children:"Hinglish (hi-Latn)"}),e.jsx("option",{value:"ar",children:"Arabic (ar)"}),e.jsx("option",{value:"es",children:"Spanish (es)"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-[10px] font-mono uppercase text-pearl-400 mb-1.5 font-semibold",children:"Tenant Isolation Mode"}),e.jsxs("div",{className:"px-3.5 py-2.5 rounded-xl bg-space-900/60 border border-white/5 text-xs font-mono text-emerald-400 flex items-center gap-2",children:[e.jsx(q,{className:"w-4 h-4"}),e.jsx("span",{children:"Strict Foreign Key + Schema Context (X-Tenant-ID)"})]})]})]})]}),e.jsxs("div",{className:"astraea-card rounded-xl p-6 space-y-4",children:[e.jsx("h3",{className:"text-lg text-pearl-50 font-bold tracking-tight pb-3 border-b border-white/10",children:"Webhook & Secret Rotation"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-[10px] font-mono uppercase text-pearl-400 mb-1.5 font-semibold",children:"Production Gateway Base URL"}),e.jsx("input",{type:"text",value:j,onChange:p=>b(p.target.value),className:"w-full px-3.5 py-2.5 rounded-xl bg-space-900 border border-white/10 text-xs font-mono text-pearl-100 focus:outline-none focus:border-[#2481CC] focus:ring-1 focus:ring-[#2481CC]"})]}),e.jsxs("div",{className:"pt-2 flex flex-col sm:flex-row sm:items-center justify-between gap-3",children:[e.jsxs("div",{className:"text-xs font-mono text-pearl-400",children:["Secret Hash Key Version: ",e.jsx("span",{className:"text-[#2481CC] font-semibold",children:"v1 (AES-256-GCM)"})]}),e.jsxs("button",{type:"button",onClick:()=>alert("Webhook cryptographic secret rotated to key version 2."),className:"btn-telegram-secondary py-2 px-3 text-[11px] w-full sm:w-auto justify-center",children:[e.jsx(me,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:"ROTATE SECRET KEY"})]})]})]}),e.jsx("div",{className:"text-right",children:e.jsxs("button",{type:"submit",className:"btn-telegram-primary w-full sm:w-auto justify-center py-2.5 px-6 shadow-telegram",children:[e.jsx(bt,{className:"w-4 h-4"}),e.jsx("span",{children:"SAVE ORGANIZATION SETTINGS"})]})})]})]})},ki=[{id:"log-101",timestamp:"2026-11-18 08:45:12 UTC",actor:"alexander@astraea.space (Owner)",action:"BROADCAST_CAMPAIGN_DISPATCH",resource:"campaign:c-001 (Spring Flash Sale)",ipAddress:"192.168.1.104",status:"success"},{id:"log-102",timestamp:"2026-11-18 08:30:24 UTC",actor:"samantha@astraea.space (Admin)",action:"AI_AGENT_PROMPT_UPDATE",resource:"agent:agent-1 (Customer Concierge)",ipAddress:"10.0.4.18",status:"success"},{id:"log-103",timestamp:"2026-11-18 08:12:05 UTC",actor:"gateway:stripe_webhook",action:"PAYMENT_CAPTURE_VERIFIED",resource:"order:ord_9f81a7d",ipAddress:"54.187.205.12",status:"success"},{id:"log-104",timestamp:"2026-11-18 07:55:40 UTC",actor:"unknown_client",action:"IDOR_CROSS_TENANT_REJECTED",resource:"tenant:ten-other-org",ipAddress:"198.51.100.44",status:"rejected"},{id:"log-105",timestamp:"2026-11-18 07:20:18 UTC",actor:"vikram@astraea.space (Editor)",action:"MESSAGE_STUDIO_PUBLISHED",resource:"template:tmpl-1 (VIP Welcome Menu)",ipAddress:"172.16.0.8",status:"success"}],Si=()=>{const{currentBot:t}=z(),[s,n]=i.useState(ki),[a,l]=i.useState(""),r=s.filter(o=>o.action.toLowerCase().includes(a.toLowerCase())||o.actor.toLowerCase().includes(a.toLowerCase())||o.resource.toLowerCase().includes(a.toLowerCase()));return e.jsxs("div",{className:"space-y-6 sm:space-y-8 animate-in fade-in duration-300 min-w-0 max-w-full",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-end justify-between gap-4 border-b border-white/10 pb-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-[#2481CC]"}),e.jsx("span",{className:"text-[10px] font-mono tracking-wider text-[#2481CC] uppercase font-semibold",children:"Compliance & Security Verification"})]}),e.jsx("h1",{className:"text-2xl sm:text-3xl md:text-4xl text-pearl-50 font-bold tracking-tight",children:"Security Audit Logs"}),e.jsx("p",{className:"text-xs text-pearl-400 font-sans mt-1.5 max-w-2xl leading-relaxed",children:"Append-only tamper-evident audit ledger recording every administrative mutation, token access, broadcast dispatch, and cross-tenant access rejection."})]}),e.jsxs("div",{className:"relative w-full sm:w-64 shrink-0",children:[e.jsx(He,{className:"w-3.5 h-3.5 text-pearl-400 absolute left-3 top-1/2 -translate-y-1/2"}),e.jsx("input",{type:"text",value:a,onChange:o=>l(o.target.value),placeholder:"Search action or actor...",className:"w-full pl-8 pr-3 py-2 rounded-xl bg-space-850/60 border border-white/10 text-xs font-mono text-pearl-100 focus:outline-none focus:border-[#2481CC] focus:ring-1 focus:ring-[#2481CC]"})]})]}),e.jsxs("div",{className:"bg-[#2481CC]/10 border border-[#2481CC]/30 rounded-xl p-3 sm:p-4 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-[#2481CC]/20 border border-[#2481CC]/40 flex items-center justify-center text-xl shrink-0",children:"🛡️"}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] font-mono uppercase px-1.5 py-0.5 rounded bg-[#2481CC]/20 text-[#2481CC] font-bold",children:"Monitored Instance"}),e.jsx("span",{className:"text-sm font-bold text-pearl-100",children:t.name}),e.jsxs("span",{className:"text-xs text-[#2481CC]",children:["@",t.username]})]}),e.jsxs("p",{className:"text-xs text-pearl-400 mt-0.5",children:["Tracking administrator mutations, webhook invocations, and deployment events across @",t.username,"."]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs font-mono text-pearl-300 bg-white/5 px-3 py-1.5 rounded-lg border border-white/10 shrink-0",children:[e.jsx("span",{className:"w-2 h-2 rounded-full bg-emerald-400 animate-pulse"}),e.jsx("span",{children:"Tamper Verification: Passing"})]})]}),e.jsx("div",{className:"astraea-card rounded-xl p-3 sm:p-5 overflow-hidden min-w-0 max-w-full",children:e.jsx("div",{className:"overflow-x-auto w-full max-w-full",children:e.jsxs("table",{className:"w-full min-w-[750px] text-left text-xs font-mono",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-white/10 text-[10px] text-pearl-400 uppercase tracking-widest font-semibold",children:[e.jsx("th",{className:"pb-3 pl-2",children:"Timestamp (UTC)"}),e.jsx("th",{className:"pb-3",children:"Action Event"}),e.jsx("th",{className:"pb-3",children:"Actor Identity"}),e.jsx("th",{className:"pb-3",children:"Target Resource"}),e.jsx("th",{className:"pb-3",children:"Client IP"}),e.jsx("th",{className:"pb-3 pr-2 text-right",children:"Result"})]})}),e.jsx("tbody",{className:"divide-y divide-white/5",children:r.map(o=>e.jsxs("tr",{className:"hover:bg-white/[0.02] transition-colors",children:[e.jsx("td",{className:"py-3.5 pl-2 text-pearl-400 text-[11px]",children:o.timestamp}),e.jsx("td",{className:"py-3.5 font-semibold text-pearl-100",children:e.jsx("span",{className:"text-[#2481CC]",children:o.action})}),e.jsx("td",{className:"py-3.5 text-pearl-300",children:o.actor}),e.jsx("td",{className:"py-3.5 text-pearl-400 text-[11px]",children:o.resource}),e.jsx("td",{className:"py-3.5 text-pearl-400 text-[11px]",children:o.ipAddress}),e.jsx("td",{className:"py-3.5 pr-2 text-right",children:e.jsx("span",{className:`px-2 py-0.5 rounded text-[9px] uppercase font-semibold ${o.status==="success"?"bg-emerald-500/10 text-emerald-300 border border-emerald-500/30":"bg-rose-500/10 text-rose-300 border border-rose-500/30"}`,children:o.status})})]},o.id))})]})})})]})},_i=({onSuccess:t,onError:s,className:n="",size:a="large",showSandboxHelper:l=!0})=>{const{loginWithTelegram:r}=qe(),[o,j]=i.useState("astraea_super_bot"),[b,m]=i.useState(!1),[x,f]=i.useState(null),[p,g]=i.useState(null),u=i.useRef(null);i.useEffect(()=>{fetch("/api/v1/auth/telegram/config").then(c=>c.json()).then(c=>{var v;(v=c.data)!=null&&v.bot_username&&j(c.data.bot_username)}).catch(()=>{})},[]),i.useEffect(()=>(window.onTelegramAuth=async c=>{m(!0),f(null);const v=await r(c);if(m(!1),v.success)g("Telegram identity cryptographically verified!"),t==null||t();else{const h=v.error||"Telegram verification failed";f(h),s==null||s(h)}},()=>{delete window.onTelegramAuth}),[r,t,s]);const d=async(c="astraea_pilot")=>{var w;m(!0),f(null);const v=718291044,h=Math.floor(Date.now()/1e3),E={id:v,first_name:"Astraea",last_name:"Explorer",username:c,photo_url:"https://images.unsplash.com/photo-1534528741775-53994a69daeb?w=100&h=100&fit=crop",auth_date:h};try{const S=await fetch("/api/v1/auth/telegram",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...E,hash:await ys(E,"7182910392:AAExampleBotTokenForVerification2026")})}),P=await S.json();if(m(!1),S.ok&&P.success)g("Telegram session established and verified!"),r({...E,hash:await ys(E,"7182910392:AAExampleBotTokenForVerification2026")}),t==null||t();else{const k=P.message||((w=P.error)==null?void 0:w.message)||"Verification rejected";f(k),s==null||s(k)}}catch(S){m(!1),f(S.message||"Verification connection failed"),s==null||s(S.message)}};return e.jsxs("div",{className:`space-y-3 ${n}`,children:[e.jsx("button",{type:"button",onClick:()=>d("telegram_vip_member"),disabled:b,className:"w-full flex items-center justify-center gap-3 py-3 px-5 rounded-xl bg-[#2AABEE] hover:bg-[#229ED9] text-white font-medium text-sm transition-all shadow-lg hover:shadow-[#2AABEE]/25 disabled:opacity-60 relative group",children:b?e.jsxs(e.Fragment,{children:[e.jsx(me,{className:"w-5 h-5 animate-spin"}),e.jsx("span",{children:"Verifying Telegram Hash..."})]}):e.jsxs(e.Fragment,{children:[e.jsx("svg",{className:"w-5 h-5 fill-current",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:e.jsx("path",{d:"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm4.64 6.8c-.15 1.58-.8 5.42-1.13 7.19-.14.75-.42 1-.68 1.03-.58.05-1.02-.38-1.58-.75-.88-.58-1.38-.94-2.23-1.5-.99-.65-.35-1.01.22-1.59.15-.15 2.71-2.48 2.76-2.69a.2.2 0 00-.05-.18c-.06-.05-.14-.03-.21-.02-.09.02-1.49.95-4.22 2.79-.4.27-.76.41-1.08.4-.36-.01-1.04-.2-1.55-.37-.63-.2-1.12-.31-1.08-.66.02-.18.27-.36.75-.55 2.92-1.27 4.86-2.11 5.83-2.51 2.78-1.16 3.35-1.36 3.73-1.36.08 0 .27.02.39.12.1.08.13.19.14.27-.01.06.01.24 0 .38z"})}),e.jsx("span",{className:"font-semibold tracking-wide",children:"Log in with Telegram"})]})}),e.jsxs("div",{className:"flex items-center justify-center gap-1.5 text-[11px] font-mono text-pearl-400",children:[e.jsx(q,{className:"w-3.5 h-3.5 text-emerald-400"}),e.jsxs("span",{children:["Server-side HMAC-SHA256 signature verified against @",o]})]}),x&&e.jsxs("div",{className:"p-3 rounded-lg bg-rose-500/10 border border-rose-500/30 text-rose-300 text-xs font-mono flex items-center gap-2",children:[e.jsx(Jt,{className:"w-4 h-4 shrink-0 text-rose-400"}),e.jsx("span",{children:x})]}),p&&e.jsxs("div",{className:"p-3 rounded-lg bg-emerald-500/10 border border-emerald-500/30 text-emerald-300 text-xs font-mono flex items-center gap-2",children:[e.jsx(F,{className:"w-4 h-4 shrink-0 text-emerald-400"}),e.jsx("span",{children:p})]}),e.jsx("div",{ref:u,className:"hidden"})]})};async function ys(t,s){const n=[];for(const m of Object.keys(t).sort())m==="hash"||t[m]==null||n.push(`${m}=${t[m]}`);const a=n.join(` apps/frontend/node_modules/@types/react/index.d.ts:2169: * @param subscribe apps/frontend/node_modules/@types/react/index.d.ts:2176: subscribe: (onStoreChange: () => void) => () => void, apps/frontend/node_modules/@types/react/ts5.0/index.d.ts:2170: * @param subscribe apps/frontend/node_modules/@types/react/ts5.0/index.d.ts:2177: subscribe: (onStoreChange: () => void) => () => void, apps/frontend/node_modules/react-dom/umd/react-dom-server-legacy.browser.development.js:5207: function useMutableSource(source, getSnapshot, subscribe) { apps/frontend/node_modules/react-dom/umd/react-dom-server-legacy.browser.development.js:5212: function useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) { apps/frontend/node_modules/react-dom/umd/react-dom-server.browser.development.js:5204: function useMutableSource(source, getSnapshot, subscribe) { apps/frontend/node_modules/react-dom/umd/react-dom-server.browser.development.js:5209: function useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) { apps/frontend/node_modules/react-dom/umd/react-dom.development.js:9188: var unsubscribeListener; // When legacyFBSupport is enabled, it's for when we apps/frontend/node_modules/react-dom/umd/react-dom.development.js:9193: unsubscribeListener = addEventCaptureListenerWithPassiveFlag(targetContainer, domEventName, listener, isPassiveListener); apps/frontend/node_modules/react-dom/umd/react-dom.development.js:9195: unsubscribeListener = addEventCaptureListener(targetContainer, domEventName, listener); apps/frontend/node_modules/react-dom/umd/react-dom.development.js:9199: unsubscribeListener = addEventBubbleListenerWithPassiveFlag(targetContainer, domEventName, listener, isPassiveListener); apps/frontend/node_modules/react-dom/umd/react-dom.development.js:9201: unsubscribeListener = addEventBubbleListener(targetContainer, domEventName, listener); apps/frontend/node_modules/react-dom/umd/react-dom.development.js:15955: function mountMutableSource(source, getSnapshot, subscribe) { apps/frontend/node_modules/react-dom/umd/react-dom.development.js:15961: function updateMutableSource(source, getSnapshot, subscribe) { apps/frontend/node_modules/react-dom/umd/react-dom.development.js:15967: function mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) { apps/frontend/node_modules/react-dom/umd/react-dom.development.js:16030: hook.queue = inst; // Schedule an effect to subscribe to the store. apps/frontend/node_modules/react-dom/umd/react-dom.development.js:16032: mountEffect(subscribeToStore.bind(null, fiber, inst, subscribe), [subscribe]); // Schedule an effect to update the mutable instance fields. We will update apps/frontend/node_modules/react-dom/umd/react-dom.development.js:16033: // this whenever subscribe, getSnapshot, or value changes. Because there's no apps/frontend/node_modules/react-dom/umd/react-dom.development.js:16045: function updateSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) { apps/frontend/node_modules/react-dom/umd/react-dom.development.js:16074: updateEffect(subscribeToStore.bind(null, fiber, inst, subscribe), [subscribe]); // Whenever getSnapshot or subscribe changes, we need to check in the apps/frontend/node_modules/react-dom/umd/react-dom.development.js:16138: function subscribeToStore(fiber, inst, subscribe) { apps/frontend/node_modules/react-dom/umd/react-dom.development.js:16149: return subscribe(handleStoreChange); apps/frontend/node_modules/react-dom/umd/react-dom.development.js:16910: useMutableSource: function (source, getSnapshot, subscribe) { apps/frontend/node_modules/react-dom/umd/react-dom.development.js:16915: useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) { apps/frontend/node_modules/react-dom/umd/react-dom.development.js:16918: return mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); apps/frontend/node_modules/react-dom/umd/react-dom.development.js:17018: useMutableSource: function (source, getSnapshot, subscribe) { apps/frontend/node_modules/react-dom/umd/react-dom.development.js:17023: useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) { apps/frontend/node_modules/react-dom/umd/react-dom.development.js:17026: return mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); apps/frontend/node_modules/react-dom/umd/react-dom.development.js:17126: useMutableSource: function (source, getSnapshot, subscribe) { apps/frontend/node_modules/react-dom/umd/react-dom.development.js:17131: useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) { apps/frontend/node_modules/react-dom/umd/react-dom.development.js:17134: return updateSyncExternalStore(subscribe, getSnapshot); apps/frontend/node_modules/react-dom/umd/react-dom.development.js:17234: useMutableSource: function (source, getSnapshot, subscribe) { apps/frontend/node_modules/react-dom/umd/react-dom.development.js:17239: useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) { apps/frontend/node_modules/react-dom/umd/react-dom.development.js:17242: return updateSyncExternalStore(subscribe, getSnapshot); apps/frontend/node_modules/react-dom/umd/react-dom.development.js:17356: useMutableSource: function (source, getSnapshot, subscribe) { apps/frontend/node_modules/react-dom/umd/react-dom.development.js:17362: useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) { apps/frontend/node_modules/react-dom/umd/react-dom.development.js:17366: return mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); apps/frontend/node_modules/react-dom/umd/react-dom.development.js:17481: useMutableSource: function (source, getSnapshot, subscribe) { apps/frontend/node_modules/react-dom/umd/react-dom.development.js:17487: useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) { apps/frontend/node_modules/react-dom/umd/react-dom.development.js:17491: return updateSyncExternalStore(subscribe, getSnapshot); apps/frontend/node_modules/react-dom/umd/react-dom.development.js:17606: useMutableSource: function (source, getSnapshot, subscribe) { apps/frontend/node_modules/react-dom/umd/react-dom.development.js:17612: useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) { apps/frontend/node_modules/react-dom/umd/react-dom.development.js:17616: return updateSyncExternalStore(subscribe, getSnapshot); apps/frontend/node_modules/react-dom/umd/react-dom.development.js:22476: // part of the second pass. In that case nothing will subscribe to apps/frontend/node_modules/react-dom/cjs/react-dom-server-legacy.browser.development.js:5210:function useMutableSource(source, getSnapshot, subscribe) { apps/frontend/node_modules/react-dom/cjs/react-dom-server-legacy.browser.development.js:5215:function useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) { apps/frontend/node_modules/react-dom/cjs/react-dom-server.node.development.js:5273:function useMutableSource(source, getSnapshot, subscribe) { apps/frontend/node_modules/react-dom/cjs/react-dom-server.node.development.js:5278:function useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) { apps/frontend/node_modules/react-dom/cjs/react-dom-server.browser.development.js:5207:function useMutableSource(source, getSnapshot, subscribe) { apps/frontend/node_modules/react-dom/cjs/react-dom-server.browser.development.js:5212:function useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) { apps/frontend/node_modules/react-dom/cjs/react-dom-server-legacy.node.development.js:5211:function useMutableSource(source, getSnapshot, subscribe) { apps/frontend/node_modules/react-dom/cjs/react-dom-server-legacy.node.development.js:5216:function useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) { apps/frontend/node_modules/react-dom/cjs/react-dom.development.js:9178: var unsubscribeListener; // When legacyFBSupport is enabled, it's for when we apps/frontend/node_modules/react-dom/cjs/react-dom.development.js:9183: unsubscribeListener = addEventCaptureListenerWithPassiveFlag(targetContainer, domEventName, listener, isPassiveListener); apps/frontend/node_modules/react-dom/cjs/react-dom.development.js:9185: unsubscribeListener = addEventCaptureListener(targetContainer, domEventName, listener); apps/frontend/node_modules/react-dom/cjs/react-dom.development.js:9189: unsubscribeListener = addEventBubbleListenerWithPassiveFlag(targetContainer, domEventName, listener, isPassiveListener); apps/frontend/node_modules/react-dom/cjs/react-dom.development.js:9191: unsubscribeListener = addEventBubbleListener(targetContainer, domEventName, listener); apps/frontend/node_modules/react-dom/cjs/react-dom.development.js:15945:function mountMutableSource(source, getSnapshot, subscribe) { apps/frontend/node_modules/react-dom/cjs/react-dom.development.js:15951:function updateMutableSource(source, getSnapshot, subscribe) { apps/frontend/node_modules/react-dom/cjs/react-dom.development.js:15957:function mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) { apps/frontend/node_modules/react-dom/cjs/react-dom.development.js:16020: hook.queue = inst; // Schedule an effect to subscribe to the store. apps/frontend/node_modules/react-dom/cjs/react-dom.development.js:16022: mountEffect(subscribeToStore.bind(null, fiber, inst, subscribe), [subscribe]); // Schedule an effect to update the mutable instance fields. We will update apps/frontend/node_modules/react-dom/cjs/react-dom.development.js:16023: // this whenever subscribe, getSnapshot, or value changes. Because there's no apps/frontend/node_modules/react-dom/cjs/react-dom.development.js:16035:function updateSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) { apps/frontend/node_modules/react-dom/cjs/react-dom.development.js:16064: updateEffect(subscribeToStore.bind(null, fiber, inst, subscribe), [subscribe]); // Whenever getSnapshot or subscribe changes, we need to check in the apps/frontend/node_modules/react-dom/cjs/react-dom.development.js:16128:function subscribeToStore(fiber, inst, subscribe) { apps/frontend/node_modules/react-dom/cjs/react-dom.development.js:16139: return subscribe(handleStoreChange); apps/frontend/node_modules/react-dom/cjs/react-dom.development.js:16900: useMutableSource: function (source, getSnapshot, subscribe) { apps/frontend/node_modules/react-dom/cjs/react-dom.development.js:16905: useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) { apps/frontend/node_modules/react-dom/cjs/react-dom.development.js:16908: return mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); apps/frontend/node_modules/react-dom/cjs/react-dom.development.js:17008: useMutableSource: function (source, getSnapshot, subscribe) { apps/frontend/node_modules/react-dom/cjs/react-dom.development.js:17013: useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) { apps/frontend/node_modules/react-dom/cjs/react-dom.development.js:17016: return mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); apps/frontend/node_modules/react-dom/cjs/react-dom.development.js:17116: useMutableSource: function (source, getSnapshot, subscribe) { apps/frontend/node_modules/react-dom/cjs/react-dom.development.js:17121: useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) { apps/frontend/node_modules/react-dom/cjs/react-dom.development.js:17124: return updateSyncExternalStore(subscribe, getSnapshot); apps/frontend/node_modules/react-dom/cjs/react-dom.development.js:17224: useMutableSource: function (source, getSnapshot, subscribe) { apps/frontend/node_modules/react-dom/cjs/react-dom.development.js:17229: useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) { apps/frontend/node_modules/react-dom/cjs/react-dom.development.js:17232: return updateSyncExternalStore(subscribe, getSnapshot); apps/frontend/node_modules/react-dom/cjs/react-dom.development.js:17346: useMutableSource: function (source, getSnapshot, subscribe) { apps/frontend/node_modules/react-dom/cjs/react-dom.development.js:17352: useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) { apps/frontend/node_modules/react-dom/cjs/react-dom.development.js:17356: return mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); apps/frontend/node_modules/react-dom/cjs/react-dom.development.js:17471: useMutableSource: function (source, getSnapshot, subscribe) { apps/frontend/node_modules/react-dom/cjs/react-dom.development.js:17477: useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) { apps/frontend/node_modules/react-dom/cjs/react-dom.development.js:17481: return updateSyncExternalStore(subscribe, getSnapshot); apps/frontend/node_modules/react-dom/cjs/react-dom.development.js:17596: useMutableSource: function (source, getSnapshot, subscribe) { apps/frontend/node_modules/react-dom/cjs/react-dom.development.js:17602: useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) { apps/frontend/node_modules/react-dom/cjs/react-dom.development.js:17606: return updateSyncExternalStore(subscribe, getSnapshot); apps/frontend/node_modules/react-dom/cjs/react-dom.development.js:22466: // part of the second pass. In that case nothing will subscribe to apps/frontend/node_modules/@remix-run/router/CHANGELOG.md:491: - The router will also pass a new `deletedFetchers` array to the subscriber callbacks so that the UI layer can remove associated fetcher data apps/frontend/node_modules/@remix-run/router/dist/router.umd.min.js:11:!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).RemixRouter={})}(this,function(e){"use strict";function t(){return t=Object.assign?Object.assign.bind():function(e){for(var t=1;t=0&&(t.hash=e.substr(r),e=e.substr(0,r));let a=e.indexOf("?");a>=0&&(t.search=e.substr(a),e=e.substr(0,a)),e&&(t.pathname=e)}return t}function c(e,o,u,c){void 0===c&&(c={});let{window:d=document.defaultView,v5Compat:h=!1}=c,f=d.history,p=r.Pop,m=null,y=v();function v(){return(f.state||{idx:null}).idx}function g(){p=r.Pop;let e=v(),t=null==e?null:e-y;y=e,m&&m({action:p,location:w.location,delta:t})}function b(e){let t="null"!==d.location.origin?d.location.origin:d.location.href,r="string"==typeof e?e:l(e);return r=r.replace(/ $/,"%20"),n(t,"No window.location.(origin|href) available to create URL for href: "+r),new URL(r,t)}null==y&&(y=0,f.replaceState(t({},f.state,{idx:y}),""));let w={get action(){return p},get location(){return e(d,f)},listen(e){if(m)throw new Error("A history only accepts one active listener");return d.addEventListener(a,g),m=e,()=>{d.removeEventListener(a,g),m=null}},createHref:e=>o(d,e),createURL:b,encodeLocation(e){let t=b(e);return{pathname:t.pathname,search:t.search,hash:t.hash}},push:function(e,t){p=r.Push;let a=s(w.location,e,t);u&&u(a,e),y=v()+1;let n=i(a,y),o=w.createHref(a);try{f.pushState(n,"",o)}catch(e){if(e instanceof DOMException&&"DataCloneError"===e.name)throw e;d.location.assign(o)}h&&m&&m({action:p,location:w.location,delta:1})},replace:function(e,t){p=r.Replace;let a=s(w.location,e,t);u&&u(a,e),y=v();let n=i(a,y),o=w.createHref(a);f.replaceState(n,"",o),h&&m&&m({action:p,location:w.location,delta:0})},go:e=>f.go(e)};return w}let d=function(e){return e.data="data",e.deferred="deferred",e.redirect="redirect",e.error="error",e}({});const h=new Set(["lazy","caseSensitive","path","id","index","children"]);function f(e,r,a,o){return void 0===a&&(a=[]),void 0===o&&(o={}),e.map((e,i)=>{let s=[...a,String(i)],l="string"==typeof e.id?e.id:s.join("-");if(n(!0!==e.index||!e.children,"Cannot specify children on an index route"),n(!o[l],'Found a route id collision on id "'+l+"\". Route id's must be globally unique within Data Router usages"),function(e){return!0===e.index}(e)){let a=t({},e,r(e),{id:l});return o[l]=a,a}{let a=t({},e,r(e),{id:l,children:void 0});return o[l]=a,e.children&&(a.children=f(e.children,r,s,o)),a}})}function p(e,t,r){return void 0===r&&(r="/"),m(e,t,r,!1)}function m(e,t,r,a){let n=j(("string"==typeof t?u(t):t).pathname||"/",r);if(null==n)return null;let o=v(e);!function(e){e.sort((e,t)=>e.score!==t.score?t.score-e.score:function(e,t){let r=e.length===t.length&&e.slice(0,-1).every((e,r)=>e===t[r]);return r?e[e.length-1]-t[t.length-1]:0}(e.routesMeta.map(e=>e.childrenIndex),t.routesMeta.map(e=>e.childrenIndex)))}(o);let i=null,s=M(n);for(let e=0;null==i&&e{let s={relativePath:void 0===i?e.path||"":i,caseSensitive:!0===e.caseSensitive,childrenIndex:o,route:e};s.relativePath.startsWith("/")&&(n(s.relativePath.startsWith(a),'Absolute route path "'+s.relativePath+'" nested under path "'+a+'" is not valid. An absolute child route path must start with the combined path of all its parent routes.'),s.relativePath=s.relativePath.slice(a.length));let l=H([a,s.relativePath]),u=r.concat(s);e.children&&e.children.length>0&&(n(!0!==e.index,'Index routes must not have child routes. Please remove all child routes from route path "'+l+'".'),v(e.children,t,u,l)),(null!=e.path||e.index)&&t.push({path:l,score:x(l,e.index),routesMeta:u})};return e.forEach((e,t)=>{var r;if(""!==e.path&&null!=(r=e.path)&&r.includes("?"))for(let r of g(e.path))o(e,t,r);else o(e,t)}),t}function g(e){let t=e.split("/");if(0===t.length)return[];let[r,...a]=t,n=r.endsWith("?"),o=r.replace(/\?$/,"");if(0===a.length)return n?[o,""]:[o];let i=g(a.join("/")),s=[];return s.push(...i.map(e=>""===e?o:[o,e].join("/"))),n&&s.push(...i),s.map(t=>e.startsWith("/")&&""===t?"/":t)}const b=/^:[\w-]+$/,w=3,S=2,D=1,R=10,E=-2,P=e=>"*"===e;function x(e,t){let r=e.split("/"),a=r.length;return r.some(P)&&(a+=E),t&&(a+=S),r.filter(e=>!P(e)).reduce((e,t)=>e+(b.test(t)?w:""===t?D:R),a)}function L(e,t,r){void 0===r&&(r=!1);let{routesMeta:a}=e,n={},o="/",i=[];for(let e=0;e(a.push({paramName:t,isOptional:null!=r}),r?"/?([^\\/]+)?":"/([^\\/]+)"));e.endsWith("*")?(a.push({paramName:"*"}),n+="*"===e||"/*"===e?"(.*)$":"(?:\\/(.+)|\\/*)$"):r?n+="\\/*$":""!==e&&"/"!==e&&(n+="(?:(?=\\/|$))");let i=new RegExp(n,t?void 0:"i");return[i,a]}(e.path,e.caseSensitive,e.end),n=t.match(r);if(!n)return null;let i=n[0],s=i.replace(/(.)\/+$/,"$1"),l=n.slice(1);return{params:a.reduce((e,t,r)=>{let{paramName:a,isOptional:n}=t;if("*"===a){let e=l[r]||"";s=i.slice(0,i.length-e.length).replace(/(.)\/+$/,"$1")}const o=l[r];return e[a]=n&&!o?void 0:(o||"").replace(/%2F/g,"/"),e},{}),pathname:i,pathnameBase:s,pattern:e}}function M(e){try{return e.split("/").map(e=>decodeURIComponent(e).replace(/\//g,"%2F")).join("/")}catch(t){return o(!1,'The URL path "'+e+'" could not be decoded because it is is a malformed URL segment. This is probably due to a bad percent encoding ('+t+")."),e}}function j(e,t){if("/"===t)return e;if(!e.toLowerCase().startsWith(t.toLowerCase()))return null;let r=t.endsWith("/")?t.length-1:t.length,a=e.charAt(r);return a&&"/"!==a?null:e.slice(r)||"/"}function k(e,t){void 0===t&&(t="/");let r,{pathname:a,search:n="",hash:o=""}="string"==typeof e?u(e):e;return a?(a=I(a),r=a.startsWith("/")?C(a.substring(1),"/"):C(a,t)):r=t,{pathname:r,search:F(n),hash:N(o)}}function C(e,t){let r=t.replace(/\/+$/,"").split("/");return e.split("/").forEach(e=>{".."===e?r.length>1&&r.pop():"."!==e&&r.push(e)}),r.length>1?r.join("/"):"/"}function _(e,t,r,a){return"Cannot include a '"+e+"' character in a manually specified `to."+t+"` field ["+JSON.stringify(a)+"]. Please separate it out to the `to."+r+'` field. Alternatively you may provide the full path as a string in and the router will parse it for you.'}function T(e){return e.filter((e,t)=>0===t||e.route.path&&e.route.path.length>0)}function U(e,t){let r=T(e);return t?r.map((e,t)=>t===r.length-1?e.pathname:e.pathnameBase):r.map(e=>e.pathnameBase)}function O(e,r,a,o){let i;void 0===o&&(o=!1),"string"==typeof e?i=u(e):(i=t({},e),n(!i.pathname||!i.pathname.includes("?"),_("?","pathname","search",i)),n(!i.pathname||!i.pathname.includes("#"),_("#","pathname","hash",i)),n(!i.search||!i.search.includes("#"),_("#","search","hash",i)));let s,l=""===e||""===i.pathname,c=l?"/":i.pathname;if(null==c)s=a;else{let e=r.length-1;if(!o&&c.startsWith("..")){let t=c.split("/");for(;".."===t[0];)t.shift(),e-=1;i.pathname=t.join("/")}s=e>=0?r[e]:"/"}let d=k(i,s),h=c&&"/"!==c&&c.endsWith("/"),f=(l||"."===c)&&a.endsWith("/");return d.pathname.endsWith("/")||!h&&!f||(d.pathname+="/"),d}const I=e=>e.replace(/\/\/+/g,"/"),H=e=>I(e.join("/")),z=e=>e.replace(/\/+$/,"").replace(/^\/*/,"/"),F=e=>e&&"?"!==e?e.startsWith("?")?e:"?"+e:"",N=e=>e&&"#"!==e?e.startsWith("#")?e:"#"+e:"";class B{constructor(e,t){this.type="DataWithResponseInit",this.data=e,this.init=t||null}}class W extends Error{}class ${constructor(e,t){let r;this.pendingKeysSet=new Set,this.subscribers=new Set,this.deferredKeys=[],n(e&&"object"==typeof e&&!Array.isArray(e),"defer() only accepts plain objects"),this.abortPromise=new Promise((e,t)=>r=t),this.controller=new AbortController;let a=()=>r(new W("Deferred data aborted"));this.unlistenAbortSignal=()=>this.controller.signal.removeEventListener("abort",a),this.controller.signal.addEventListener("abort",a),this.data=Object.entries(e).reduce((e,t)=>{let[r,a]=t;return Object.assign(e,{[r]:this.trackPromise(r,a)})},{}),this.done&&this.unlistenAbortSignal(),this.init=t}trackPromise(e,t){if(!(t instanceof Promise))return t;this.deferredKeys.push(e),this.pendingKeysSet.add(e);let r=Promise.race([t,this.abortPromise]).then(t=>this.onSettle(r,e,void 0,t),t=>this.onSettle(r,e,t));return r.catch(()=>{}),Object.defineProperty(r,"_tracked",{get:()=>!0}),r}onSettle(e,t,r,a){if(this.controller.signal.aborted&&r instanceof W)return this.unlistenAbortSignal(),Object.defineProperty(e,"_error",{get:()=>r}),Promise.reject(r);if(this.pendingKeysSet.delete(t),this.done&&this.unlistenAbortSignal(),void 0===r&&void 0===a){let r=new Error('Deferred data for key "'+t+'" resolved/rejected with `undefined`, you must resolve/reject with a value or `null`.');return Object.defineProperty(e,"_error",{get:()=>r}),this.emit(!1,t),Promise.reject(r)}return void 0===a?(Object.defineProperty(e,"_error",{get:()=>r}),this.emit(!1,t),Promise.reject(r)):(Object.defineProperty(e,"_data",{get:()=>a}),this.emit(!1,t),a)}emit(e,t){this.subscribers.forEach(r=>r(e,t))}subscribe(e){return this.subscribers.add(e),()=>this.subscribers.delete(e)}cancel(){this.controller.abort(),this.pendingKeysSet.forEach((e,t)=>this.pendingKeysSet.delete(t)),this.emit(!0)}async resolveData(e){let t=!1;if(!this.done){let r=()=>this.cancel();e.addEventListener("abort",r),t=await new Promise(t=>{this.subscribe(a=>{e.removeEventListener("abort",r),(a||this.done)&&t(a)})})}return t}get done(){return 0===this.pendingKeysSet.size}get unwrappedData(){return n(null!==this.data&&this.done,"Can only unwrap data on initialized and settled deferreds"),Object.entries(this.data).reduce((e,t)=>{let[r,a]=t;return Object.assign(e,{[r]:q(a)})},{})}get pendingKeys(){return Array.from(this.pendingKeysSet)}}function q(e){if(!function(e){return e instanceof Promise&&!0===e._tracked}(e))return e;if(e._error)throw e._error;return e._data}const K=function(e,r){void 0===r&&(r=302);let a=r;"number"==typeof a?a={status:a}:void 0===a.status&&(a.status=302);let n=new Headers(a.headers);return n.set("Location",e),new Response(null,t({},a,{headers:n}))};class Y{constructor(e,t,r,a){void 0===a&&(a=!1),this.status=e,this.statusText=t||"",this.internal=a,r instanceof Error?(this.data=r.toString(),this.error=r):this.data=r}}function J(e){return null!=e&&"number"==typeof e.status&&"string"==typeof e.statusText&&"boolean"==typeof e.internal&&"data"in e}const V=["post","put","patch","delete"],X=new Set(V),G=["get",...V],Q=new Set(G),Z=new Set([301,302,303,307,308]),ee=new Set([307,308]),te={state:"idle",location:void 0,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0},re={state:"idle",data:void 0,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0},ae={state:"unblocked",proceed:void 0,reset:void 0,location:void 0},ne=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,oe=e=>({hasErrorBoundary:Boolean(e.hasErrorBoundary)}),ie="remix-router-transitions";const se=Symbol("deferred");function le(e,t,r){if(r.v7_throwAbortReason&&void 0!==e.signal.reason)throw e.signal.reason;throw new Error((t?"queryRoute":"query")+"() call aborted: "+e.method+" "+e.url)}function ue(e,t,r,a,n,o,i,s){let u,c;if(i){u=[];for(let e of t)if(u.push(e),e.route.id===i){c=e;break}}else u=t,c=t[t.length-1];let d=O(n||".",U(u,o),j(e.pathname,r)||e.pathname,"path"===s);if(null==n&&(d.search=e.search,d.hash=e.hash),(null==n||""===n||"."===n)&&c){let e=Ye(d.search);if(c.route.index&&!e)d.search=d.search?d.search.replace(/^\?/,"?index&"):"?index";else if(!c.route.index&&e){let e=new URLSearchParams(d.search),t=e.getAll("index");e.delete("index"),t.filter(e=>e).forEach(t=>e.append("index",t));let r=e.toString();d.search=r?"?"+r:""}}return a&&"/"!==r&&(d.pathname="/"===d.pathname?r:H([r,d.pathname])),l(d)}function ce(e,t,r,a){if(!a||!function(e){return null!=e&&("formData"in e&&null!=e.formData||"body"in e&&void 0!==e.body)}(a))return{path:r};if(a.formMethod&&!Be(a.formMethod))return{path:r,error:Ce(405,{method:a.formMethod})};let o,i,s=()=>({path:r,error:Ce(400,{type:"invalid-body"})}),c=a.formMethod||"get",d=e?c.toUpperCase():c.toLowerCase(),h=Te(r);if(void 0!==a.body){if("text/plain"===a.formEncType){if(!We(d))return s();let e="string"==typeof a.body?a.body:a.body instanceof FormData||a.body instanceof URLSearchParams?Array.from(a.body.entries()).reduce((e,t)=>{let[r,a]=t;return""+e+r+"="+a+"\n"},""):String(a.body);return{path:r,submission:{formMethod:d,formAction:h,formEncType:a.formEncType,formData:void 0,json:void 0,text:e}}}if("application/json"===a.formEncType){if(!We(d))return s();try{let e="string"==typeof a.body?JSON.parse(a.body):a.body;return{path:r,submission:{formMethod:d,formAction:h,formEncType:a.formEncType,formData:void 0,json:e,text:void 0}}}catch(e){return s()}}}if(n("function"==typeof FormData,"FormData is not available in this environment"),a.formData)o=Ee(a.formData),i=a.formData;else if(a.body instanceof FormData)o=Ee(a.body),i=a.body;else if(a.body instanceof URLSearchParams)o=a.body,i=Pe(o);else if(null==a.body)o=new URLSearchParams,i=new FormData;else try{o=new URLSearchParams(a.body),i=Pe(o)}catch(e){return s()}let f={formMethod:d,formAction:h,formEncType:a&&a.formEncType||"application/x-www-form-urlencoded",formData:i,json:void 0,text:void 0};if(We(f.formMethod))return{path:r,submission:f};let p=u(r);return t&&p.search&&Ye(p.search)&&o.append("index",""),p.search="?"+o,{path:l(p),submission:f}}function de(e,t,r){void 0===r&&(r=!1);let a=e.findIndex(e=>e.route.id===t);return a>=0?e.slice(0,r?a+1:a):e}function he(e,r,a,n,o,i,s,l,u,c,d,h,f,m,y,v){let g=v?Ie(v[1])?v[1].error:v[1].data:void 0,b=e.createURL(r.location),w=e.createURL(o),S=a;i&&r.errors?S=de(a,Object.keys(r.errors)[0],!0):v&&Ie(v[1])&&(S=de(a,v[0]));let D=v?v[1].statusCode:void 0,R=s&&D&&D>=400,E=S.filter((e,a)=>{let{route:o}=e;if(o.lazy)return!0;if(null==o.loader)return!1;if(i)return fe(o,r.loaderData,r.errors);if(function(e,t,r){let a=!t||r.route.id!==t.route.id,n=void 0===e[r.route.id];return a||n}(r.loaderData,r.matches[a],e)||u.some(t=>t===e.route.id))return!0;let s=r.matches[a],c=e;return me(e,t({currentUrl:b,currentParams:s.params,nextUrl:w,nextParams:c.params},n,{actionResult:g,actionStatus:D,defaultShouldRevalidate:!R&&(l||b.pathname+b.search===w.pathname+w.search||b.search!==w.search||pe(s,c))}))}),P=[];return h.forEach((e,o)=>{if(i||!a.some(t=>t.route.id===e.routeId)||d.has(o))return;let s=p(m,e.path,y);if(!s)return void P.push({key:o,routeId:e.routeId,path:e.path,matches:null,match:null,controller:null});let u=r.fetchers.get(o),h=Je(s,e.path),v=!1;f.has(o)?v=!1:c.has(o)?(c.delete(o),v=!0):v=u&&"idle"!==u.state&&void 0===u.data?l:me(h,t({currentUrl:b,currentParams:r.matches[r.matches.length-1].params,nextUrl:w,nextParams:a[a.length-1].params},n,{actionResult:g,actionStatus:D,defaultShouldRevalidate:!R&&l})),v&&P.push({key:o,routeId:e.routeId,path:e.path,matches:s,match:h,controller:new AbortController})}),[E,P]}function fe(e,t,r){if(e.lazy)return!0;if(!e.loader)return!1;let a=null!=t&&void 0!==t[e.id],n=null!=r&&void 0!==r[e.id];return!(!a&&n)&&("function"==typeof e.loader&&!0===e.loader.hydrate||!a&&!n)}function pe(e,t){let r=e.route.path;return e.pathname!==t.pathname||null!=r&&r.endsWith("*")&&e.params["*"]!==t.params["*"]}function me(e,t){if(e.route.shouldRevalidate){let r=e.route.shouldRevalidate(t);if("boolean"==typeof r)return r}return t.defaultShouldRevalidate}function ye(e,t,r,a,o){var i;let s;if(e){let t=a[e];n(t,"No route found to patch children into: routeId = "+e),t.children||(t.children=[]),s=t.children}else s=r;let l=f(t.filter(e=>!s.some(t=>ve(e,t))),o,[e||"_","patch",String((null==(i=s)?void 0:i.length)||"0")],a);s.push(...l)}function ve(e,t){return"id"in e&&"id"in t&&e.id===t.id||e.index===t.index&&e.path===t.path&&e.caseSensitive===t.caseSensitive&&(!(e.children&&0!==e.children.length||t.children&&0!==t.children.length)||e.children.every((e,r)=>{var a;return null==(a=t.children)?void 0:a.some(t=>ve(e,t))}))}async function ge(e){let{matches:t}=e,r=t.filter(e=>e.shouldLoad);return(await Promise.all(r.map(e=>e.resolve()))).reduce((e,t,a)=>Object.assign(e,{[r[a].route.id]:t}),{})}async function be(e,r,a,i,s,l,u,c,f,p){let m=l.map(e=>e.route.lazy?async function(e,r,a){if(!e.lazy)return;let i=await e.lazy();if(!e.lazy)return;let s=a[e.id];n(s,"No route found in manifest");let l={};for(let e in i){let t=void 0!==s[e]&&"hasErrorBoundary"!==e;o(!t,'Route "'+s.id+'" has a static property "'+e+'" defined but its lazy function is also returning a value for this property. The lazy route property "'+e+'" will be ignored.'),t||h.has(e)||(l[e]=i[e])}Object.assign(s,l),Object.assign(s,t({},r(s),{lazy:void 0}))}(e.route,f,c):void 0),y=l.map((e,a)=>{let o=m[a],l=s.some(t=>t.route.id===e.route.id);return t({},e,{shouldLoad:l,resolve:async t=>(t&&"GET"===i.method&&(e.route.lazy||e.route.loader)&&(l=!0),l?async function(e,t,r,a,o,i){let s,l,u=a=>{let n,s=new Promise((e,t)=>n=t);l=()=>n(),t.signal.addEventListener("abort",l);let u=n=>"function"!=typeof a?Promise.reject(new Error('You cannot call the handler for a route which defines a boolean "'+e+'" [routeId: '+r.route.id+"]")):a({request:t,params:r.params,context:i},...void 0!==n?[n]:[]),c=(async()=>{try{return{type:"data",result:await(o?o(e=>u(e)):u())}}catch(e){return{type:"error",result:e}}})();return Promise.race([c,s])};try{let o=r.route[e];if(a)if(o){let e,[t]=await Promise.all([u(o).catch(t=>{e=t}),a]);if(void 0!==e)throw e;s=t}else{if(await a,o=r.route[e],!o){if("action"===e){let e=new URL(t.url),a=e.pathname+e.search;throw Ce(405,{method:t.method,pathname:a,routeId:r.route.id})}return{type:d.data,result:void 0}}s=await u(o)}else{if(!o){let e=new URL(t.url);throw Ce(404,{pathname:e.pathname+e.search})}s=await u(o)}n(void 0!==s.result,"You defined "+("action"===e?"an action":"a loader")+' for route "'+r.route.id+"\" but didn't return anything from your `"+e+"` function. Please return a value or `null`.")}catch(e){return{type:d.error,result:e}}finally{l&&t.signal.removeEventListener("abort",l)}return s}(r,i,e,o,t,p):Promise.resolve({type:d.data,result:void 0}))})}),v=await e({matches:y,request:i,params:l[0].params,fetcherKey:u,context:p});try{await Promise.all(m)}catch(e){}return v}async function we(e){let{result:t,type:r}=e;if(Ne(t)){let e;try{let r=t.headers.get("Content-Type");e=r&&/\bapplication\/json\b/.test(r)?null==t.body?null:await t.json():await t.text()}catch(e){return{type:d.error,error:e}}return r===d.error?{type:d.error,error:new Y(t.status,t.statusText,e),statusCode:t.status,headers:t.headers}:{type:d.data,data:e,statusCode:t.status,headers:t.headers}}var a,n,o,i,s,l,u,c;return r===d.error?ze(t)?t.data instanceof Error?{type:d.error,error:t.data,statusCode:null==(o=t.init)?void 0:o.status,headers:null!=(i=t.init)&&i.headers?new Headers(t.init.headers):void 0}:{type:d.error,error:new Y((null==(a=t.init)?void 0:a.status)||500,void 0,t.data),statusCode:J(t)?t.status:void 0,headers:null!=(n=t.init)&&n.headers?new Headers(t.init.headers):void 0}:{type:d.error,error:t,statusCode:J(t)?t.status:void 0}:Fe(t)?{type:d.deferred,deferredData:t,statusCode:null==(s=t.init)?void 0:s.status,headers:(null==(l=t.init)?void 0:l.headers)&&new Headers(t.init.headers)}:ze(t)?{type:d.data,data:t.data,statusCode:null==(u=t.init)?void 0:u.status,headers:null!=(c=t.init)&&c.headers?new Headers(t.init.headers):void 0}:{type:d.data,data:t}}function Se(e,t,r,a,o,i){let s=e.headers.get("Location");if(n(s,"Redirects returned/thrown from loaders/actions must have a Location header"),!ne.test(s)){let n=a.slice(0,a.findIndex(e=>e.route.id===r)+1);s=ue(new URL(t.url),n,o,!0,s,i),e.headers.set("Location",s)}return e}function De(e,t,r,a){let n=["about:","blob:","chrome:","chrome-untrusted:","content:","data:","devtools:","file:","filesystem:","javascript:"];if(ne.test(e)){let a=e,o=a.startsWith("//")?new URL(t.protocol+a):new URL(a);if(n.includes(o.protocol))throw new Error("Invalid redirect location");let i=null!=j(o.pathname,r);if(o.origin===t.origin&&i)return I(o.pathname)+o.search+o.hash}try{let t=a.createURL(e);if(n.includes(t.protocol))throw new Error("Invalid redirect location")}catch(e){}return e}function Re(e,t,r,a){let n=e.createURL(Te(t)).toString(),o={signal:r};if(a&&We(a.formMethod)){let{formMethod:e,formEncType:t}=a;o.method=e.toUpperCase(),"application/json"===t?(o.headers=new Headers({"Content-Type":t}),o.body=JSON.stringify(a.json)):"text/plain"===t?o.body=a.text:"application/x-www-form-urlencoded"===t&&a.formData?o.body=Ee(a.formData):o.body=a.formData}return new Request(n,o)}function Ee(e){let t=new URLSearchParams;for(let[r,a]of e.entries())t.append(r,"string"==typeof a?a:a.name);return t}function Pe(e){let t=new FormData;for(let[r,a]of e.entries())t.append(r,a);return t}function xe(e,t,r,a,o){let i,s={},l=null,u=!1,c={},d=r&&Ie(r[1])?r[1].error:void 0;return e.forEach(r=>{if(!(r.route.id in t))return;let h=r.route.id,f=t[h];if(n(!He(f),"Cannot handle redirect results in processLoaderData"),Ie(f)){let t=f.error;if(void 0!==d&&(t=d,d=void 0),l=l||{},o)l[h]=t;else{let r=je(e,h);null==l[r.route.id]&&(l[r.route.id]=t)}s[h]=void 0,u||(u=!0,i=J(f.error)?f.error.status:500),f.headers&&(c[h]=f.headers)}else Oe(f)?(a.set(h,f.deferredData),s[h]=f.deferredData.data,null==f.statusCode||200===f.statusCode||u||(i=f.statusCode),f.headers&&(c[h]=f.headers)):(s[h]=f.data,f.statusCode&&200!==f.statusCode&&!u&&(i=f.statusCode),f.headers&&(c[h]=f.headers))}),void 0!==d&&r&&(l={[r[0]]:d},s[r[0]]=void 0),{loaderData:s,errors:l,statusCode:i||200,loaderHeaders:c}}function Le(e,r,a,o,i,s,l){let{loaderData:u,errors:c}=xe(r,a,o,l,!1);return i.forEach(r=>{let{key:a,match:o,controller:i}=r,l=s[a];if(n(l,"Did not find corresponding fetcher result"),!i||!i.signal.aborted)if(Ie(l)){let r=je(e.matches,null==o?void 0:o.route.id);c&&c[r.route.id]||(c=t({},c,{[r.route.id]:l.error})),e.fetchers.delete(a)}else if(He(l))n(!1,"Unhandled fetcher revalidation redirect");else if(Oe(l))n(!1,"Unhandled fetcher deferred data");else{let t=Qe(l.data);e.fetchers.set(a,t)}}),{loaderData:u,errors:c}}function Ae(e,r,a,n){let o=t({},r);for(let t of a){let a=t.route.id;if(r.hasOwnProperty(a)?void 0!==r[a]&&(o[a]=r[a]):void 0!==e[a]&&t.route.loader&&(o[a]=e[a]),n&&n.hasOwnProperty(a))break}return o}function Me(e){return e?Ie(e[1])?{actionData:{}}:{actionData:{[e[0]]:e[1].data}}:{}}function je(e,t){return(t?e.slice(0,e.findIndex(e=>e.route.id===t)+1):[...e]).reverse().find(e=>!0===e.route.hasErrorBoundary)||e[0]}function ke(e){let t=1===e.length?e[0]:e.find(e=>e.index||!e.path||"/"===e.path)||{id:"__shim-error-route__"};return{matches:[{params:{},pathname:"",pathnameBase:"",route:t}],route:t}}function Ce(e,t){let{pathname:r,routeId:a,method:n,type:o,message:i}=void 0===t?{}:t,s="Unknown Server Error",l="Unknown @remix-run/router error";return 400===e?(s="Bad Request",n&&r&&a?l="You made a "+n+' request to "'+r+'" but did not provide a `loader` for route "'+a+'", so there is no way to handle the request.':"defer-action"===o?l="defer() is not supported in actions":"invalid-body"===o&&(l="Unable to encode submission body")):403===e?(s="Forbidden",l='Route "'+a+'" does not match URL "'+r+'"'):404===e?(s="Not Found",l='No route matches URL "'+r+'"'):405===e&&(s="Method Not Allowed",n&&r&&a?l="You made a "+n.toUpperCase()+' request to "'+r+'" but did not provide an `action` for route "'+a+'", so there is no way to handle the request.':n&&(l='Invalid request method "'+n.toUpperCase()+'"')),new Y(e||500,s,new Error(l),!0)}function _e(e){let t=Object.entries(e);for(let e=t.length-1;e>=0;e--){let[r,a]=t[e];if(He(a))return{key:r,result:a}}}function Te(e){return l(t({},"string"==typeof e?u(e):e,{hash:""}))}function Ue(e){return Ne(e.result)&&Z.has(e.result.status)}function Oe(e){return e.type===d.deferred}function Ie(e){return e.type===d.error}function He(e){return(e&&e.type)===d.redirect}function ze(e){return"object"==typeof e&&null!=e&&"type"in e&&"data"in e&&"init"in e&&"DataWithResponseInit"===e.type}function Fe(e){let t=e;return t&&"object"==typeof t&&"object"==typeof t.data&&"function"==typeof t.subscribe&&"function"==typeof t.cancel&&"function"==typeof t.resolveData}function Ne(e){return null!=e&&"number"==typeof e.status&&"string"==typeof e.statusText&&"object"==typeof e.headers&&void 0!==e.body}function Be(e){return Q.has(e.toLowerCase())}function We(e){return X.has(e.toLowerCase())}async function $e(e,t,r,a,n){let o=Object.entries(t);for(let i=0;i(null==e?void 0:e.route.id)===s);if(!u)continue;let c=a.find(e=>e.route.id===u.route.id),d=null!=c&&!pe(c,u)&&void 0!==(n&&n[u.route.id]);Oe(l)&&d&&await Ke(l,r,!1).then(e=>{e&&(t[s]=e)})}}async function qe(e,t,r){for(let a=0;a(null==e?void 0:e.route.id)===i)&&(Oe(l)&&(n(s,"Expected an AbortController for revalidating fetcher deferred result"),await Ke(l,s.signal,!0).then(e=>{e&&(t[o]=e)})))}}async function Ke(e,t,r){if(void 0===r&&(r=!1),!await e.deferredData.resolveData(t)){if(r)try{return{type:d.data,data:e.deferredData.unwrappedData}}catch(e){return{type:d.error,error:e}}return{type:d.data,data:e.deferredData.data}}}function Ye(e){return new URLSearchParams(e).getAll("index").some(e=>""===e)}function Je(e,t){let r="string"==typeof t?u(t).search:t.search;if(e[e.length-1].route.index&&Ye(r||""))return e[e.length-1];let a=T(e);return a[a.length-1]}function Ve(e){let{formMethod:t,formAction:r,formEncType:a,text:n,formData:o,json:i}=e;if(t&&r&&a)return null!=n?{formMethod:t,formAction:r,formEncType:a,formData:void 0,json:void 0,text:n}:null!=o?{formMethod:t,formAction:r,formEncType:a,formData:o,json:void 0,text:void 0}:void 0!==i?{formMethod:t,formAction:r,formEncType:a,formData:void 0,json:i,text:void 0}:void 0}function Xe(e,t){if(t){return{state:"loading",location:e,formMethod:t.formMethod,formAction:t.formAction,formEncType:t.formEncType,formData:t.formData,json:t.json,text:t.text}}return{state:"loading",location:e,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0}}function Ge(e,t){if(e){return{state:"loading",formMethod:e.formMethod,formAction:e.formAction,formEncType:e.formEncType,formData:e.formData,json:e.json,text:e.text,data:t}}return{state:"loading",formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0,data:t}}function Qe(e){return{state:"idle",formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0,data:e}}e.AbortedDeferredError=W,e.Action=r,e.IDLE_BLOCKER=ae,e.IDLE_FETCHER=re,e.IDLE_NAVIGATION=te,e.UNSAFE_DEFERRED_SYMBOL=se,e.UNSAFE_DeferredData=$,e.UNSAFE_ErrorResponseImpl=Y,e.UNSAFE_convertRouteMatchToUiMatch=y,e.UNSAFE_convertRoutesToDataRoutes=f,e.UNSAFE_decodePath=M,e.UNSAFE_getResolveToMatches=U,e.UNSAFE_invariant=n,e.UNSAFE_warning=o,e.createBrowserHistory=function(e){return void 0===e&&(e={}),c(function(e,t){let{pathname:r,search:a,hash:n}=e.location;return s("",{pathname:r,search:a,hash:n},t.state&&t.state.usr||null,t.state&&t.state.key||"default")},function(e,t){return"string"==typeof t?t:l(t)},null,e)},e.createHashHistory=function(e){return void 0===e&&(e={}),c(function(e,t){let{pathname:r="/",search:a="",hash:n=""}=u(e.location.hash.substr(1));return r.startsWith("/")||r.startsWith(".")||(r="/"+r),s("",{pathname:r,search:a,hash:n},t.state&&t.state.usr||null,t.state&&t.state.key||"default")},function(e,t){let r=e.document.querySelector("base"),a="";if(r&&r.getAttribute("href")){let t=e.location.href,r=t.indexOf("#");a=-1===r?t:t.slice(0,r)}return a+"#"+("string"==typeof t?t:l(t))},function(e,t){o("/"===e.pathname.charAt(0),"relative pathnames are not supported in hash history.push("+JSON.stringify(t)+")")},e)},e.createMemoryHistory=function(e){void 0===e&&(e={});let t,{initialEntries:a=["/"],initialIndex:n,v5Compat:i=!1}=e;t=a.map((e,t)=>m(e,"string"==typeof e?null:e.state,0===t?"default":void 0));let c=f(null==n?t.length-1:n),d=r.Pop,h=null;function f(e){return Math.min(Math.max(e,0),t.length-1)}function p(){return t[c]}function m(e,r,a){void 0===r&&(r=null);let n=s(t?p().pathname:"/",e,r,a);return o("/"===n.pathname.charAt(0),"relative pathnames are not supported in memory history: "+JSON.stringify(e)),n}function y(e){return"string"==typeof e?e:l(e)}return{get index(){return c},get action(){return d},get location(){return p()},createHref:y,createURL:e=>new URL(y(e),"http://localhost"),encodeLocation(e){let t="string"==typeof e?u(e):e;return{pathname:t.pathname||"",search:t.search||"",hash:t.hash||""}},push(e,a){d=r.Push;let n=m(e,a);c+=1,t.splice(c,t.length,n),i&&h&&h({action:d,location:n,delta:1})},replace(e,a){d=r.Replace;let n=m(e,a);t[c]=n,i&&h&&h({action:d,location:n,delta:0})},go(e){d=r.Pop;let a=f(c+e),n=t[a];c=a,h&&h({action:d,location:n,delta:e})},listen:e=>(h=e,()=>{h=null})}},e.createPath=l,e.createRouter=function(e){const a=e.window?e.window:"undefined"!=typeof window?window:void 0,i=void 0!==a&&void 0!==a.document&&void 0!==a.document.createElement,l=!i;let u;if(n(e.routes.length>0,"You must provide a non-empty routes array to createRouter"),e.mapRouteProperties)u=e.mapRouteProperties;else if(e.detectErrorBoundary){let t=e.detectErrorBoundary;u=e=>({hasErrorBoundary:t(e)})}else u=oe;let c,h,v,g={},b=f(e.routes,u,void 0,g),w=e.basename||"/",S=e.dataStrategy||ge,D=e.patchRoutesOnNavigation,R=t({v7_fetcherPersist:!1,v7_normalizeFormMethod:!1,v7_partialHydration:!1,v7_prependBasename:!1,v7_relativeSplatPath:!1,v7_skipActionErrorRevalidation:!1},e.future),E=null,P=new Set,x=null,L=null,A=null,M=null!=e.hydrationData,k=p(b,e.history.location,w),C=!1,_=null;if(null==k&&!D){let t=Ce(404,{pathname:e.history.location.pathname}),{matches:r,route:a}=ke(b);k=r,_={[a.id]:t}}if(k&&!e.hydrationData){ct(k,b,e.history.location.pathname).active&&(k=null)}if(k)if(k.some(e=>e.route.lazy))h=!1;else if(k.some(e=>e.route.loader))if(R.v7_partialHydration){let t=e.hydrationData?e.hydrationData.loaderData:null,r=e.hydrationData?e.hydrationData.errors:null;if(r){let e=k.findIndex(e=>void 0!==r[e.route.id]);h=k.slice(0,e+1).every(e=>!fe(e.route,t,r))}else h=k.every(e=>!fe(e.route,t,r))}else h=null!=e.hydrationData;else h=!0;else if(h=!1,k=[],R.v7_partialHydration){let t=ct(null,b,e.history.location.pathname);t.active&&t.matches&&(C=!0,k=t.matches)}let T,U,O={historyAction:e.history.action,location:e.history.location,matches:k,initialized:h,navigation:te,restoreScrollPosition:null==e.hydrationData&&null,preventScrollReset:!1,revalidation:"idle",loaderData:e.hydrationData&&e.hydrationData.loaderData||{},actionData:e.hydrationData&&e.hydrationData.actionData||null,errors:e.hydrationData&&e.hydrationData.errors||_,fetchers:new Map,blockers:new Map},I=r.Pop,H=!1,z=!1,F=new Map,N=null,B=!1,W=!1,$=[],q=new Set,K=new Map,Y=0,V=-1,X=new Map,G=new Set,Q=new Map,Z=new Map,se=new Set,le=new Map,de=new Map;function pe(e,r){void 0===r&&(r={}),O=t({},O,e);let a=[],n=[];R.v7_fetcherPersist&&O.fetchers.forEach((e,t)=>{"idle"===e.state&&(se.has(t)?n.push(t):a.push(t))}),se.forEach(e=>{O.fetchers.has(e)||K.has(e)||n.push(e)}),[...P].forEach(e=>e(O,{deletedFetchers:n,viewTransitionOpts:r.viewTransitionOpts,flushSync:!0===r.flushSync})),R.v7_fetcherPersist?(a.forEach(e=>O.fetchers.delete(e)),n.forEach(e=>Ye(e))):n.forEach(e=>se.delete(e))}function me(a,n,o){var i,s;let l,{flushSync:u}=void 0===o?{}:o,d=null!=O.actionData&&null!=O.navigation.formMethod&&We(O.navigation.formMethod)&&"loading"===O.navigation.state&&!0!==(null==(i=a.state)?void 0:i._isRedirect);l=n.actionData?Object.keys(n.actionData).length>0?n.actionData:null:d?O.actionData:null;let h=n.loaderData?Ae(O.loaderData,n.loaderData,n.matches||[],n.errors):O.loaderData,f=O.blockers;f.size>0&&(f=new Map(f),f.forEach((e,t)=>f.set(t,ae)));let p,m=!0===H||null!=O.navigation.formMethod&&We(O.navigation.formMethod)&&!0!==(null==(s=a.state)?void 0:s._isRedirect);if(c&&(b=c,c=void 0),B||I===r.Pop||(I===r.Push?e.history.push(a,a.state):I===r.Replace&&e.history.replace(a,a.state)),I===r.Pop){let e=F.get(O.location.pathname);e&&e.has(a.pathname)?p={currentLocation:O.location,nextLocation:a}:F.has(a.pathname)&&(p={currentLocation:a,nextLocation:O.location})}else if(z){let e=F.get(O.location.pathname);e?e.add(a.pathname):(e=new Set([a.pathname]),F.set(O.location.pathname,e)),p={currentLocation:O.location,nextLocation:a}}pe(t({},n,{actionData:l,loaderData:h,historyAction:I,location:a,initialized:!0,navigation:te,revalidation:"idle",restoreScrollPosition:ut(a,n.matches||O.matches),preventScrollReset:m,blockers:f}),{viewTransitionOpts:p,flushSync:!0===u}),I=r.Pop,H=!1,z=!1,B=!1,W=!1,$=[]}async function ve(a,n,o){T&&T.abort(),T=null,I=a,B=!0===(o&&o.startUninterruptedRevalidation),function(e,t){if(x&&A){let r=lt(e,t);x[r]=A()}}(O.location,O.matches),H=!0===(o&&o.preventScrollReset),z=!0===(o&&o.enableViewTransition);let i=c||b,s=o&&o.overrideNavigation,l=null!=o&&o.initialHydration&&O.matches&&O.matches.length>0&&!C?O.matches:p(i,n,w),u=!0===(o&&o.flushSync);if(l&&O.initialized&&!W&&function(e,t){if(e.pathname!==t.pathname||e.search!==t.search)return!1;if(""===e.hash)return""!==t.hash;if(e.hash===t.hash)return!0;if(""!==t.hash)return!0;return!1}(O.location,n)&&!(o&&o.submission&&We(o.submission.formMethod)))return void me(n,{matches:l},{flushSync:u});let h=ct(l,i,n.pathname);if(h.active&&h.matches&&(l=h.matches),!l){let{error:e,notFoundMatches:t,route:r}=it(n.pathname);return void me(n,{matches:t,loaderData:{},errors:{[r.id]:e}},{flushSync:u})}T=new AbortController;let f,m=Re(e.history,n,T.signal,o&&o.submission);if(o&&o.pendingError)f=[je(l).route.id,{type:d.error,error:o.pendingError}];else if(o&&o.submission&&We(o.submission.formMethod)){let t=await async function(t,a,n,o,i,s){void 0===s&&(s={});ze();let l,u=function(e,t){let r={state:"submitting",location:e,formMethod:t.formMethod,formAction:t.formAction,formEncType:t.formEncType,formData:t.formData,json:t.json,text:t.text};return r}(a,n);if(pe({navigation:u},{flushSync:!0===s.flushSync}),i){let e=await dt(o,a.pathname,t.signal);if("aborted"===e.type)return{shortCircuited:!0};if("error"===e.type){let t=je(e.partialMatches).route.id;return{matches:e.partialMatches,pendingActionResult:[t,{type:d.error,error:e.error}]}}if(!e.matches){let{notFoundMatches:e,error:t,route:r}=it(a.pathname);return{matches:e,pendingActionResult:[r.id,{type:d.error,error:t}]}}o=e.matches}let c=Je(o,a);if(c.route.action||c.route.lazy){if(l=(await xe("action",O,t,[c],o,null))[c.route.id],t.signal.aborted)return{shortCircuited:!0}}else l={type:d.error,error:Ce(405,{method:t.method,pathname:a.pathname,routeId:c.route.id})};if(He(l)){let r;if(s&&null!=s.replace)r=s.replace;else{r=De(l.response.headers.get("Location"),new URL(t.url),w,e.history)===O.location.pathname+O.location.search}return await Pe(t,l,!0,{submission:n,replace:r}),{shortCircuited:!0}}if(Oe(l))throw Ce(400,{type:"defer-action"});if(Ie(l)){let e=je(o,c.route.id);return!0!==(s&&s.replace)&&(I=r.Push),{matches:o,pendingActionResult:[e.route.id,l]}}return{matches:o,pendingActionResult:[c.route.id,l]}}(m,n,o.submission,l,h.active,{replace:o.replace,flushSync:u});if(t.shortCircuited)return;if(t.pendingActionResult){let[e,r]=t.pendingActionResult;if(Ie(r)&&J(r.error)&&404===r.error.status)return T=null,void me(n,{matches:t.matches,loaderData:{},errors:{[e]:r.error}})}l=t.matches||l,f=t.pendingActionResult,s=Xe(n,o.submission),u=!1,h.active=!1,m=Re(e.history,m.url,m.signal)}let{shortCircuited:y,matches:v,loaderData:g,errors:S}=await async function(r,a,n,o,i,s,l,u,d,h,f){let p=i||Xe(a,s),m=s||l||Ve(p),y=!(B||R.v7_partialHydration&&d);if(o){if(y){let e=Ee(f);pe(t({navigation:p},void 0!==e?{actionData:e}:{}),{flushSync:h})}let e=await dt(n,a.pathname,r.signal);if("aborted"===e.type)return{shortCircuited:!0};if("error"===e.type){let t=je(e.partialMatches).route.id;return{matches:e.partialMatches,loaderData:{},errors:{[t]:e.error}}}if(!e.matches){let{error:e,notFoundMatches:t,route:r}=it(a.pathname);return{matches:t,loaderData:{},errors:{[r.id]:e}}}n=e.matches}let v=c||b,[g,S]=he(e.history,O,n,m,a,R.v7_partialHydration&&!0===d,R.v7_skipActionErrorRevalidation,W,$,q,se,Q,G,v,w,f);if(st(e=>!(n&&n.some(t=>t.route.id===e))||g&&g.some(t=>t.route.id===e)),V=++Y,0===g.length&&0===S.length){let e=tt();return me(a,t({matches:n,loaderData:{},errors:f&&Ie(f[1])?{[f[0]]:f[1].error}:null},Me(f),e?{fetchers:new Map(O.fetchers)}:{}),{flushSync:h}),{shortCircuited:!0}}if(y){let e={};if(!o){e.navigation=p;let t=Ee(f);void 0!==t&&(e.actionData=t)}S.length>0&&(e.fetchers=function(e){return e.forEach(e=>{let t=O.fetchers.get(e.key),r=Ge(void 0,t?t.data:void 0);O.fetchers.set(e.key,r)}),new Map(O.fetchers)}(S)),pe(e,{flushSync:h})}S.forEach(e=>{Ze(e.key),e.controller&&K.set(e.key,e.controller)});let D=()=>S.forEach(e=>Ze(e.key));T&&T.signal.addEventListener("abort",D);let{loaderResults:E,fetcherResults:P}=await Te(O,n,g,S,r);if(r.signal.aborted)return{shortCircuited:!0};T&&T.signal.removeEventListener("abort",D);S.forEach(e=>K.delete(e.key));let x=_e(E);if(x)return await Pe(r,x.result,!0,{replace:u}),{shortCircuited:!0};if(x=_e(P),x)return G.add(x.key),await Pe(r,x.result,!0,{replace:u}),{shortCircuited:!0};let{loaderData:L,errors:A}=Le(O,n,E,f,S,P,le);le.forEach((e,t)=>{e.subscribe(r=>{(r||e.done)&&le.delete(t)})}),R.v7_partialHydration&&d&&O.errors&&(A=t({},O.errors,A));let M=tt(),j=rt(V),k=M||j||S.length>0;return t({matches:n,loaderData:L,errors:A},k?{fetchers:new Map(O.fetchers)}:{})}(m,n,l,h.active,s,o&&o.submission,o&&o.fetcherSubmission,o&&o.replace,o&&!0===o.initialHydration,u,f);y||(T=null,me(n,t({matches:v||l},Me(f),{loaderData:g,errors:S})))}function Ee(e){return e&&!Ie(e[1])?{[e[0]]:e[1].data}:O.actionData?0===Object.keys(O.actionData).length?null:O.actionData:void 0}async function Pe(o,l,u,c){let{submission:d,fetcherSubmission:h,preventScrollReset:f,replace:p}=void 0===c?{}:c;l.response.headers.has("X-Remix-Revalidate")&&(W=!0);let m=l.response.headers.get("Location");n(m,"Expected a Location header on the redirect Response"),m=De(m,new URL(o.url),w,e.history);let y=s(O.location,m,{_isRedirect:!0});if(i){let t=!1;if(l.response.headers.has("X-Remix-Reload-Document"))t=!0;else if(ne.test(m)){const r=e.history.createURL(m);t=r.origin!==a.location.origin||null==j(r.pathname,w)}if(t)return void(p?a.location.replace(m):a.location.assign(m))}T=null;let v=!0===p||l.response.headers.has("X-Remix-Replace")?r.Replace:r.Push,{formMethod:g,formAction:b,formEncType:S}=O.navigation;!d&&!h&&g&&b&&S&&(d=Ve(O.navigation));let D=d||h;if(ee.has(l.response.status)&&D&&We(D.formMethod))await ve(v,y,{submission:t({},D,{formAction:m}),preventScrollReset:f||H,enableViewTransition:u?z:void 0});else{let e=Xe(y,d);await ve(v,y,{overrideNavigation:e,fetcherSubmission:h,preventScrollReset:f||H,enableViewTransition:u?z:void 0})}}async function xe(e,t,r,a,n,o){let i,s={};try{i=await be(S,e,t,r,a,n,o,g,u)}catch(e){return a.forEach(t=>{s[t.route.id]={type:d.error,error:e}}),s}for(let[e,t]of Object.entries(i))if(Ue(t)){let a=t.result;s[e]={type:d.redirect,response:Se(a,r,e,n,w,R.v7_relativeSplatPath)}}else s[e]=await we(t);return s}async function Te(t,r,a,n,o){let i=t.matches,s=xe("loader",t,o,a,r,null),l=Promise.all(n.map(async r=>{if(r.matches&&r.match&&r.controller){let a=(await xe("loader",t,Re(e.history,r.path,r.controller.signal),[r.match],r.matches,r.key))[r.match.route.id];return{[r.key]:a}}return Promise.resolve({[r.key]:{type:d.error,error:Ce(404,{pathname:r.path})}})})),u=await s,c=(await l).reduce((e,t)=>Object.assign(e,t),{});return await Promise.all([$e(r,u,o.signal,i,t.loaderData),qe(r,c,n)]),{loaderResults:u,fetcherResults:c}}function ze(){W=!0,$.push(...st()),Q.forEach((e,t)=>{K.has(t)&&q.add(t),Ze(t)})}function Fe(e,t,r){void 0===r&&(r={}),O.fetchers.set(e,t),pe({fetchers:new Map(O.fetchers)},{flushSync:!0===(r&&r.flushSync)})}function Ne(e,t,r,a){void 0===a&&(a={});let n=je(O.matches,t);Ye(e),pe({errors:{[n.route.id]:r},fetchers:new Map(O.fetchers)},{flushSync:!0===(a&&a.flushSync)})}function Be(e){return Z.set(e,(Z.get(e)||0)+1),se.has(e)&&se.delete(e),O.fetchers.get(e)||re}function Ye(e){let t=O.fetchers.get(e);!K.has(e)||t&&"loading"===t.state&&X.has(e)||Ze(e),Q.delete(e),X.delete(e),G.delete(e),R.v7_fetcherPersist&&se.delete(e),q.delete(e),O.fetchers.delete(e)}function Ze(e){let t=K.get(e);t&&(t.abort(),K.delete(e))}function et(e){for(let t of e){let e=Qe(Be(t).data);O.fetchers.set(t,e)}}function tt(){let e=[],t=!1;for(let r of G){let a=O.fetchers.get(r);n(a,"Expected fetcher: "+r),"loading"===a.state&&(G.delete(r),e.push(r),t=!0)}return et(e),t}function rt(e){let t=[];for(let[r,a]of X)if(a0}function at(e){O.blockers.delete(e),de.delete(e)}function nt(e,t){let r=O.blockers.get(e)||ae;n("unblocked"===r.state&&"blocked"===t.state||"blocked"===r.state&&"blocked"===t.state||"blocked"===r.state&&"proceeding"===t.state||"blocked"===r.state&&"unblocked"===t.state||"proceeding"===r.state&&"unblocked"===t.state,"Invalid blocker state transition: "+r.state+" -> "+t.state);let a=new Map(O.blockers);a.set(e,t),pe({blockers:a})}function ot(e){let{currentLocation:t,nextLocation:r,historyAction:a}=e;if(0===de.size)return;de.size>1&&o(!1,"A router only supports one blocker at a time");let n=Array.from(de.entries()),[i,s]=n[n.length-1],l=O.blockers.get(i);return l&&"proceeding"===l.state?void 0:s({currentLocation:t,nextLocation:r,historyAction:a})?i:void 0}function it(e){let t=Ce(404,{pathname:e}),r=c||b,{matches:a,route:n}=ke(r);return st(),{notFoundMatches:a,route:n,error:t}}function st(e){let t=[];return le.forEach((r,a)=>{e&&!e(a)||(r.cancel(),t.push(a),le.delete(a))}),t}function lt(e,t){if(L){return L(e,t.map(e=>y(e,O.loaderData)))||e.key}return e.key}function ut(e,t){if(x){let r=lt(e,t),a=x[r];if("number"==typeof a)return a}return null}function ct(e,t,r){if(D){if(!e){return{active:!0,matches:m(t,r,w,!0)||[]}}if(Object.keys(e[0].params).length>0){return{active:!0,matches:m(t,r,w,!0)}}}return{active:!1,matches:null}}async function dt(e,t,r,a){if(!D)return{type:"success",matches:e};let n=e;for(;;){let e=null==c,o=c||b,i=g;try{await D({signal:r,path:t,matches:n,fetcherKey:a,patch:(e,t)=>{r.aborted||ye(e,t,o,i,u)}})}catch(e){return{type:"error",error:e,partialMatches:n}}finally{e&&!r.aborted&&(b=[...b])}if(r.aborted)return{type:"aborted"};let s=p(o,t,w);if(s)return{type:"success",matches:s};let l=m(o,t,w,!0);if(!l||n.length===l.length&&n.every((e,t)=>e.route.id===l[t].route.id))return{type:"success",matches:null};n=l}}return v={get basename(){return w},get future(){return R},get state(){return O},get routes(){return b},get window(){return a},initialize:function(){if(E=e.history.listen(t=>{let{action:r,location:a,delta:n}=t;if(U)return U(),void(U=void 0);o(0===de.size||null!=n,"You are trying to use a blocker on a POP navigation to a location that was not created by @remix-run/router. This will fail silently in production. This can happen if you are navigating outside the router via `window.history.pushState`/`window.location.hash` instead of using router navigation APIs. This can also happen if you are using createHashRouter and the user manually changes the URL.");let i=ot({currentLocation:O.location,nextLocation:a,historyAction:r});if(i&&null!=n){let t=new Promise(e=>{U=e});return e.history.go(-1*n),void nt(i,{state:"blocked",location:a,proceed(){nt(i,{state:"proceeding",proceed:void 0,reset:void 0,location:a}),t.then(()=>e.history.go(n))},reset(){let e=new Map(O.blockers);e.set(i,ae),pe({blockers:e})}})}return ve(r,a)}),i){!function(e,t){try{let r=e.sessionStorage.getItem(ie);if(r){let e=JSON.parse(r);for(let[r,a]of Object.entries(e||{}))a&&Array.isArray(a)&&t.set(r,new Set(a||[]))}}catch(e){}}(a,F);let e=()=>function(e,t){if(t.size>0){let r={};for(let[e,a]of t)r[e]=[...a];try{e.sessionStorage.setItem(ie,JSON.stringify(r))}catch(e){o(!1,"Failed to save applied view transitions in sessionStorage ("+e+").")}}}(a,F);a.addEventListener("pagehide",e),N=()=>a.removeEventListener("pagehide",e)}return O.initialized||ve(r.Pop,O.location,{initialHydration:!0}),v},subscribe:function(e){return P.add(e),()=>P.delete(e)},enableScrollRestoration:function(e,t,r){if(x=e,A=t,L=r||null,!M&&O.navigation===te){M=!0;let e=ut(O.location,O.matches);null!=e&&pe({restoreScrollPosition:e})}return()=>{x=null,A=null,L=null}},navigate:async function a(n,o){if("number"==typeof n)return void e.history.go(n);let i=ue(O.location,O.matches,w,R.v7_prependBasename,n,R.v7_relativeSplatPath,null==o?void 0:o.fromRouteId,null==o?void 0:o.relative),{path:l,submission:u,error:c}=ce(R.v7_normalizeFormMethod,!1,i,o),d=O.location,h=s(O.location,l,o&&o.state);h=t({},h,e.history.encodeLocation(h));let f=o&&null!=o.replace?o.replace:void 0,p=r.Push;!0===f?p=r.Replace:!1===f||null!=u&&We(u.formMethod)&&u.formAction===O.location.pathname+O.location.search&&(p=r.Replace);let m=o&&"preventScrollReset"in o?!0===o.preventScrollReset:void 0,y=!0===(o&&o.flushSync),v=ot({currentLocation:d,nextLocation:h,historyAction:p});if(!v)return await ve(p,h,{submission:u,pendingError:c,preventScrollReset:m,replace:o&&o.replace,enableViewTransition:o&&o.viewTransition,flushSync:y});nt(v,{state:"blocked",location:h,proceed(){nt(v,{state:"proceeding",proceed:void 0,reset:void 0,location:h}),a(n,o)},reset(){let e=new Map(O.blockers);e.set(v,ae),pe({blockers:e})}})},fetch:function(t,r,a,o){if(l)throw new Error("router.fetch() was called during the server render, but it shouldn't be. You are likely calling a useFetcher() method in the body of your component. Try moving it to a useEffect or a callback.");Ze(t);let i=!0===(o&&o.flushSync),s=c||b,u=ue(O.location,O.matches,w,R.v7_prependBasename,a,R.v7_relativeSplatPath,r,null==o?void 0:o.relative),d=p(s,u,w),h=ct(d,s,u);if(h.active&&h.matches&&(d=h.matches),!d)return void Ne(t,r,Ce(404,{pathname:u}),{flushSync:i});let{path:f,submission:m,error:y}=ce(R.v7_normalizeFormMethod,!0,u,o);if(y)return void Ne(t,r,y,{flushSync:i});let v=Je(d,f),g=!0===(o&&o.preventScrollReset);m&&We(m.formMethod)?async function(t,r,a,o,i,s,l,u,d){function h(e){if(!e.route.action&&!e.route.lazy){let e=Ce(405,{method:d.formMethod,pathname:a,routeId:r});return Ne(t,r,e,{flushSync:l}),!0}return!1}if(ze(),Q.delete(t),!s&&h(o))return;let f=O.fetchers.get(t);Fe(t,function(e,t){let r={state:"submitting",formMethod:e.formMethod,formAction:e.formAction,formEncType:e.formEncType,formData:e.formData,json:e.json,text:e.text,data:t?t.data:void 0};return r}(d,f),{flushSync:l});let m=new AbortController,y=Re(e.history,a,m.signal,d);if(s){let e=await dt(i,new URL(y.url).pathname,y.signal,t);if("aborted"===e.type)return;if("error"===e.type)return void Ne(t,r,e.error,{flushSync:l});if(!e.matches)return void Ne(t,r,Ce(404,{pathname:a}),{flushSync:l});if(h(o=Je(i=e.matches,a)))return}K.set(t,m);let v=Y,g=await xe("action",O,y,[o],i,t),S=g[o.route.id];if(y.signal.aborted)return void(K.get(t)===m&&K.delete(t));if(R.v7_fetcherPersist&&se.has(t)){if(He(S)||Ie(S))return void Fe(t,Qe(void 0))}else{if(He(S))return K.delete(t),V>v?void Fe(t,Qe(void 0)):(G.add(t),Fe(t,Ge(d)),Pe(y,S,!1,{fetcherSubmission:d,preventScrollReset:u}));if(Ie(S))return void Ne(t,r,S.error)}if(Oe(S))throw Ce(400,{type:"defer-action"});let D=O.navigation.location||O.location,E=Re(e.history,D,m.signal),P=c||b,x="idle"!==O.navigation.state?p(P,O.navigation.location,w):O.matches;n(x,"Didn't find any matches after fetcher action");let L=++Y;X.set(t,L);let A=Ge(d,S.data);O.fetchers.set(t,A);let[M,j]=he(e.history,O,x,d,D,!1,R.v7_skipActionErrorRevalidation,W,$,q,se,Q,G,P,w,[o.route.id,S]);j.filter(e=>e.key!==t).forEach(e=>{let t=e.key,r=O.fetchers.get(t),a=Ge(void 0,r?r.data:void 0);O.fetchers.set(t,a),Ze(t),e.controller&&K.set(t,e.controller)}),pe({fetchers:new Map(O.fetchers)});let k=()=>j.forEach(e=>Ze(e.key));m.signal.addEventListener("abort",k);let{loaderResults:C,fetcherResults:_}=await Te(O,x,M,j,E);if(m.signal.aborted)return;m.signal.removeEventListener("abort",k),X.delete(t),K.delete(t),j.forEach(e=>K.delete(e.key));let U=_e(C);if(U)return Pe(E,U.result,!1,{preventScrollReset:u});if(U=_e(_),U)return G.add(U.key),Pe(E,U.result,!1,{preventScrollReset:u});let{loaderData:H,errors:z}=Le(O,x,C,void 0,j,_,le);if(O.fetchers.has(t)){let e=Qe(S.data);O.fetchers.set(t,e)}rt(L),"loading"===O.navigation.state&&L>V?(n(I,"Expected pending action"),T&&T.abort(),me(O.navigation.location,{matches:x,loaderData:H,errors:z,fetchers:new Map(O.fetchers)})):(pe({errors:z,loaderData:Ae(O.loaderData,H,x,z),fetchers:new Map(O.fetchers)}),W=!1)}(t,r,f,v,d,h.active,i,g,m):(Q.set(t,{routeId:r,path:f}),async function(t,r,a,o,i,s,l,u,c){let d=O.fetchers.get(t);Fe(t,Ge(c,d?d.data:void 0),{flushSync:l});let h=new AbortController,f=Re(e.history,a,h.signal);if(s){let e=await dt(i,new URL(f.url).pathname,f.signal,t);if("aborted"===e.type)return;if("error"===e.type)return void Ne(t,r,e.error,{flushSync:l});if(!e.matches)return void Ne(t,r,Ce(404,{pathname:a}),{flushSync:l});o=Je(i=e.matches,a)}K.set(t,h);let p=Y,m=await xe("loader",O,f,[o],i,t),y=m[o.route.id];Oe(y)&&(y=await Ke(y,f.signal,!0)||y);K.get(t)===h&&K.delete(t);if(f.signal.aborted)return;if(se.has(t))return void Fe(t,Qe(void 0));if(He(y))return V>p?void Fe(t,Qe(void 0)):(G.add(t),void await Pe(f,y,!1,{preventScrollReset:u}));if(Ie(y))return void Ne(t,r,y.error);n(!Oe(y),"Unhandled fetcher deferred data"),Fe(t,Qe(y.data))}(t,r,f,v,d,h.active,i,g,m))},revalidate:function(){ze(),pe({revalidation:"loading"}),"submitting"!==O.navigation.state&&("idle"!==O.navigation.state?ve(I||O.historyAction,O.navigation.location,{overrideNavigation:O.navigation,enableViewTransition:!0===z}):ve(O.historyAction,O.location,{startUninterruptedRevalidation:!0}))},createHref:t=>e.history.createHref(t),encodeLocation:t=>e.history.encodeLocation(t),getFetcher:Be,deleteFetcher:function(e){let t=(Z.get(e)||0)-1;t<=0?(Z.delete(e),se.add(e),R.v7_fetcherPersist||Ye(e)):Z.set(e,t),pe({fetchers:new Map(O.fetchers)})},dispose:function(){E&&E(),N&&N(),P.clear(),T&&T.abort(),O.fetchers.forEach((e,t)=>Ye(t)),O.blockers.forEach((e,t)=>at(t))},getBlocker:function(e,t){let r=O.blockers.get(e)||ae;return de.get(e)!==t&&de.set(e,t),r},deleteBlocker:at,patchRoutes:function(e,t){let r=null==c;ye(e,t,c||b,g,u),r&&(b=[...b],pe({}))},_internalFetchControllers:K,_internalActiveDeferreds:le,_internalSetRoutes:function(e){g={},c=f(e,u,void 0,g)}},v},e.createStaticHandler=function(e,r){n(e.length>0,"You must provide a non-empty routes array to createStaticHandler");let a,o={},i=(r?r.basename:null)||"/";if(null!=r&&r.mapRouteProperties)a=r.mapRouteProperties;else if(null!=r&&r.detectErrorBoundary){let e=r.detectErrorBoundary;a=t=>({hasErrorBoundary:e(t)})}else a=oe;let u=t({v7_relativeSplatPath:!1,v7_throwAbortReason:!1},r?r.future:null),c=f(e,a,void 0,o);async function h(e,r,a,o,i,s,l){n(e.signal,"query()/queryRoute() requests must contain an AbortController signal");try{if(We(e.method.toLowerCase())){let n=await async function(e,r,a,n,o,i,s){let l;if(a.route.action||a.route.lazy){l=(await y("action",e,[a],r,s,n,o))[a.route.id],e.signal.aborted&&le(e,s,u)}else{let t=Ce(405,{method:e.method,pathname:new URL(e.url).pathname,routeId:a.route.id});if(s)throw t;l={type:d.error,error:t}}if(He(l))throw new Response(null,{status:l.response.status,headers:{Location:l.response.headers.get("Location")}});if(Oe(l)){let e=Ce(400,{type:"defer-action"});if(s)throw e;l={type:d.error,error:e}}if(s){if(Ie(l))throw l.error;return{matches:[a],loaderData:{},actionData:{[a.route.id]:l.data},errors:null,statusCode:200,loaderHeaders:{},actionHeaders:{},activeDeferreds:null}}let c=new Request(e.url,{headers:e.headers,redirect:e.redirect,signal:e.signal});if(Ie(l)){let e=i?a:je(r,a.route.id);return t({},await m(c,r,n,o,i,null,[e.route.id,l]),{statusCode:J(l.error)?l.error.status:null!=l.statusCode?l.statusCode:500,actionData:null,actionHeaders:t({},l.headers?{[a.route.id]:l.headers}:{})})}let h=await m(c,r,n,o,i,null);return t({},h,{actionData:{[a.route.id]:l.data}},l.statusCode?{statusCode:l.statusCode}:{},{actionHeaders:l.headers?{[a.route.id]:l.headers}:{}})}(e,a,l||Je(a,r),o,i,s,null!=l);return n}let n=await m(e,a,o,i,s,l);return Ne(n)?n:t({},n,{actionData:null,actionHeaders:{}})}catch(e){if(null!=(c=e)&&"object"==typeof c&&"type"in c&&"result"in c&&(c.type===d.data||c.type===d.error)&&Ne(e.result)){if(e.type===d.error)throw e.result;return e.result}if(function(e){if(!Ne(e))return!1;let t=e.status,r=e.headers.get("Location");return t>=300&&t<=399&&null!=r}(e))return e;throw e}var c}async function m(e,r,a,n,o,i,s){let l=null!=i;if(l&&(null==i||!i.route.loader)&&(null==i||!i.route.lazy))throw Ce(400,{method:e.method,pathname:new URL(e.url).pathname,routeId:null==i?void 0:i.route.id});let c=(i?[i]:s&&Ie(s[1])?de(r,s[0]):r).filter(e=>e.route.loader||e.route.lazy);if(0===c.length)return{matches:r,loaderData:r.reduce((e,t)=>Object.assign(e,{[t.route.id]:null}),{}),errors:s&&Ie(s[1])?{[s[0]]:s[1].error}:null,statusCode:200,loaderHeaders:{},activeDeferreds:null};let d=await y("loader",e,c,r,l,a,n);e.signal.aborted&&le(e,l,u);let h=new Map,f=xe(r,d,s,h,o),p=new Set(c.map(e=>e.route.id));return r.forEach(e=>{p.has(e.route.id)||(f.loaderData[e.route.id]=null)}),t({},f,{matches:r,activeDeferreds:h.size>0?Object.fromEntries(h.entries()):null})}async function y(e,t,r,n,s,l,c){let d=await be(c||ge,e,null,t,r,n,null,o,a,l),h={};return await Promise.all(n.map(async e=>{if(!(e.route.id in d))return;let r=d[e.route.id];if(Ue(r)){throw Se(r.result,t,e.route.id,n,i,u.v7_relativeSplatPath)}if(Ne(r.result)&&s)throw r;h[e.route.id]=await we(r)})),h}return{dataRoutes:c,query:async function(e,r){let{requestContext:a,skipLoaderErrorBubbling:n,dataStrategy:o}=void 0===r?{}:r,u=new URL(e.url),d=e.method,f=s("",l(u),null,"default"),m=p(c,f,i);if(!Be(d)&&"HEAD"!==d){let e=Ce(405,{method:d}),{matches:t,route:r}=ke(c);return{basename:i,location:f,matches:t,loaderData:{},actionData:null,errors:{[r.id]:e},statusCode:e.status,loaderHeaders:{},actionHeaders:{},activeDeferreds:null}}if(!m){let e=Ce(404,{pathname:f.pathname}),{matches:t,route:r}=ke(c);return{basename:i,location:f,matches:t,loaderData:{},actionData:null,errors:{[r.id]:e},statusCode:e.status,loaderHeaders:{},actionHeaders:{},activeDeferreds:null}}let y=await h(e,f,m,a,o||null,!0===n,null);return Ne(y)?y:t({location:f,basename:i},y)},queryRoute:async function(e,t){let{routeId:r,requestContext:a,dataStrategy:n}=void 0===t?{}:t,o=new URL(e.url),u=e.method,d=s("",l(o),null,"default"),f=p(c,d,i);if(!Be(u)&&"HEAD"!==u&&"OPTIONS"!==u)throw Ce(405,{method:u});if(!f)throw Ce(404,{pathname:d.pathname});let m=r?f.find(e=>e.route.id===r):Je(f,d);if(r&&!m)throw Ce(403,{pathname:d.pathname,routeId:r});if(!m)throw Ce(404,{pathname:d.pathname});let y=await h(e,d,f,a,n||null,!1,m);if(Ne(y))return y;let v=y.errors?Object.values(y.errors)[0]:void 0;if(void 0!==v)throw v;if(y.actionData)return Object.values(y.actionData)[0];if(y.loaderData){var g;let e=Object.values(y.loaderData)[0];return null!=(g=y.activeDeferreds)&&g[m.route.id]&&(e[se]=y.activeDeferreds[m.route.id]),e}}}},e.data=function(e,t){return new B(e,"number"==typeof t?{status:t}:t)},e.defer=function(e,t){return void 0===t&&(t={}),new $(e,"number"==typeof t?{status:t}:t)},e.generatePath=function(e,t){void 0===t&&(t={});let r=e;r.endsWith("*")&&"*"!==r&&!r.endsWith("/*")&&(o(!1,'Route path "'+r+'" will be treated as if it were "'+r.replace(/\*$/,"/*")+'" because the `*` character must always follow a `/` in the pattern. To get rid of this warning, please change the route path to "'+r.replace(/\*$/,"/*")+'".'),r=r.replace(/\*$/,"/*"));const a=r.startsWith("/")?"/":"",i=e=>null==e?"":"string"==typeof e?e:String(e);return a+r.split(/\/+/).map((e,r,a)=>{if(r===a.length-1&&"*"===e){return i(t["*"])}const o=e.match(/^:([\w-]+)(\??)$/);if(o){const[,e,r]=o;let a=t[e];return n("?"===r||null!=a,'Missing ":'+e+'" param'),i(a)}return e.replace(/\?$/g,"")}).filter(e=>!!e).join("/")},e.getStaticContextFromError=function(e,r,a){return t({},r,{statusCode:J(a)?a.status:500,errors:{[r._deepestRenderedBoundaryId||e[0].id]:a}})},e.getToPathname=function(e){return""===e||""===e.pathname?"/":"string"==typeof e?u(e).pathname:e.pathname},e.isDataWithResponseInit=ze,e.isDeferredData=Fe,e.isRouteErrorResponse=J,e.joinPaths=H,e.json=function(e,r){void 0===r&&(r={});let a="number"==typeof r?{status:r}:r,n=new Headers(a.headers);return n.has("Content-Type")||n.set("Content-Type","application/json; charset=utf-8"),new Response(JSON.stringify(e),t({},a,{headers:n}))},e.matchPath=A,e.matchRoutes=p,e.normalizePathname=z,e.parsePath=u,e.redirect=K,e.redirectDocument=(e,t)=>{let r=K(e,t);return r.headers.set("X-Remix-Reload-Document","true"),r},e.replace=(e,t)=>{let r=K(e,t);return r.headers.set("X-Remix-Replace","true"),r},e.resolvePath=k,e.resolveTo=O,e.stripBasename=j,Object.defineProperty(e,"__esModule",{value:!0})}); apps/frontend/node_modules/@remix-run/router/dist/router.js.map:1:{"version":3,"file":"router.js","sources":["../history.ts","../utils.ts","../router.ts"],"sourcesContent":["////////////////////////////////////////////////////////////////////////////////\n//#region Types and Constants\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Actions represent the type of change to a location value.\n */\nexport enum Action {\n /**\n * A POP indicates a change to an arbitrary index in the history stack, such\n * as a back or forward navigation. It does not describe the direction of the\n * navigation, only that the current index changed.\n *\n * Note: This is the default action for newly created history objects.\n */\n Pop = \"POP\",\n\n /**\n * A PUSH indicates a new entry being added to the history stack, such as when\n * a link is clicked and a new page loads. When this happens, all subsequent\n * entries in the stack are lost.\n */\n Push = \"PUSH\",\n\n /**\n * A REPLACE indicates the entry at the current index in the history stack\n * being replaced by a new one.\n */\n Replace = \"REPLACE\",\n}\n\n/**\n * The pathname, search, and hash values of a URL.\n */\nexport interface Path {\n /**\n * A URL pathname, beginning with a /.\n */\n pathname: string;\n\n /**\n * A URL search string, beginning with a ?.\n */\n search: string;\n\n /**\n * A URL fragment identifier, beginning with a #.\n */\n hash: string;\n}\n\n// TODO: (v7) Change the Location generic default from `any` to `unknown` and\n// remove Remix `useLocation` wrapper.\n\n/**\n * An entry in a history stack. A location contains information about the\n * URL path, as well as possibly some arbitrary state and a key.\n */\nexport interface Location extends Path {\n /**\n * A value of arbitrary data associated with this location.\n */\n state: State;\n\n /**\n * A unique string associated with this location. May be used to safely store\n * and retrieve data in some other storage API, like `localStorage`.\n *\n * Note: This value is always \"default\" on the initial location.\n */\n key: string;\n}\n\n/**\n * A change to the current location.\n */\nexport interface Update {\n /**\n * The action that triggered the change.\n */\n action: Action;\n\n /**\n * The new location.\n */\n location: Location;\n\n /**\n * The delta between this location and the former location in the history stack\n */\n delta: number | null;\n}\n\n/**\n * A function that receives notifications about location changes.\n */\nexport interface Listener {\n (update: Update): void;\n}\n\n/**\n * Describes a location that is the destination of some navigation, either via\n * `history.push` or `history.replace`. This may be either a URL or the pieces\n * of a URL path.\n */\nexport type To = string | Partial;\n\n/**\n * A history is an interface to the navigation stack. The history serves as the\n * source of truth for the current location, as well as provides a set of\n * methods that may be used to change it.\n *\n * It is similar to the DOM's `window.history` object, but with a smaller, more\n * focused API.\n */\nexport interface History {\n /**\n * The last action that modified the current location. This will always be\n * Action.Pop when a history instance is first created. This value is mutable.\n */\n readonly action: Action;\n\n /**\n * The current location. This value is mutable.\n */\n readonly location: Location;\n\n /**\n * Returns a valid href for the given `to` value that may be used as\n * the value of an attribute.\n *\n * @param to - The destination URL\n */\n createHref(to: To): string;\n\n /**\n * Returns a URL for the given `to` value\n *\n * @param to - The destination URL\n */\n createURL(to: To): URL;\n\n /**\n * Encode a location the same way window.history would do (no-op for memory\n * history) so we ensure our PUSH/REPLACE navigations for data routers\n * behave the same as POP\n *\n * @param to Unencoded path\n */\n encodeLocation(to: To): Path;\n\n /**\n * Pushes a new location onto the history stack, increasing its length by one.\n * If there were any entries in the stack after the current one, they are\n * lost.\n *\n * @param to - The new URL\n * @param state - Data to associate with the new location\n */\n push(to: To, state?: any): void;\n\n /**\n * Replaces the current location in the history stack with a new one. The\n * location that was replaced will no longer be available.\n *\n * @param to - The new URL\n * @param state - Data to associate with the new location\n */\n replace(to: To, state?: any): void;\n\n /**\n * Navigates `n` entries backward/forward in the history stack relative to the\n * current index. For example, a \"back\" navigation would use go(-1).\n *\n * @param delta - The delta in the stack index\n */\n go(delta: number): void;\n\n /**\n * Sets up a listener that will be called whenever the current location\n * changes.\n *\n * @param listener - A function that will be called when the location changes\n * @returns unlisten - A function that may be used to stop listening\n */\n listen(listener: Listener): () => void;\n}\n\ntype HistoryState = {\n usr: any;\n key?: string;\n idx: number;\n};\n\nconst PopStateEventType = \"popstate\";\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Memory History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A user-supplied object that describes a location. Used when providing\n * entries to `createMemoryHistory` via its `initialEntries` option.\n */\nexport type InitialEntry = string | Partial;\n\nexport type MemoryHistoryOptions = {\n initialEntries?: InitialEntry[];\n initialIndex?: number;\n v5Compat?: boolean;\n};\n\n/**\n * A memory history stores locations in memory. This is useful in stateful\n * environments where there is no web browser, such as node tests or React\n * Native.\n */\nexport interface MemoryHistory extends History {\n /**\n * The current index in the history stack.\n */\n readonly index: number;\n}\n\n/**\n * Memory history stores the current location in memory. It is designed for use\n * in stateful non-browser environments like tests and React Native.\n */\nexport function createMemoryHistory(\n options: MemoryHistoryOptions = {}\n): MemoryHistory {\n let { initialEntries = [\"/\"], initialIndex, v5Compat = false } = options;\n let entries: Location[]; // Declare so we can access from createMemoryLocation\n entries = initialEntries.map((entry, index) =>\n createMemoryLocation(\n entry,\n typeof entry === \"string\" ? null : entry.state,\n index === 0 ? \"default\" : undefined\n )\n );\n let index = clampIndex(\n initialIndex == null ? entries.length - 1 : initialIndex\n );\n let action = Action.Pop;\n let listener: Listener | null = null;\n\n function clampIndex(n: number): number {\n return Math.min(Math.max(n, 0), entries.length - 1);\n }\n function getCurrentLocation(): Location {\n return entries[index];\n }\n function createMemoryLocation(\n to: To,\n state: any = null,\n key?: string\n ): Location {\n let location = createLocation(\n entries ? getCurrentLocation().pathname : \"/\",\n to,\n state,\n key\n );\n warning(\n location.pathname.charAt(0) === \"/\",\n `relative pathnames are not supported in memory history: ${JSON.stringify(\n to\n )}`\n );\n return location;\n }\n\n function createHref(to: To) {\n return typeof to === \"string\" ? to : createPath(to);\n }\n\n let history: MemoryHistory = {\n get index() {\n return index;\n },\n get action() {\n return action;\n },\n get location() {\n return getCurrentLocation();\n },\n createHref,\n createURL(to) {\n return new URL(createHref(to), \"http://localhost\");\n },\n encodeLocation(to: To) {\n let path = typeof to === \"string\" ? parsePath(to) : to;\n return {\n pathname: path.pathname || \"\",\n search: path.search || \"\",\n hash: path.hash || \"\",\n };\n },\n push(to, state) {\n action = Action.Push;\n let nextLocation = createMemoryLocation(to, state);\n index += 1;\n entries.splice(index, entries.length, nextLocation);\n if (v5Compat && listener) {\n listener({ action, location: nextLocation, delta: 1 });\n }\n },\n replace(to, state) {\n action = Action.Replace;\n let nextLocation = createMemoryLocation(to, state);\n entries[index] = nextLocation;\n if (v5Compat && listener) {\n listener({ action, location: nextLocation, delta: 0 });\n }\n },\n go(delta) {\n action = Action.Pop;\n let nextIndex = clampIndex(index + delta);\n let nextLocation = entries[nextIndex];\n index = nextIndex;\n if (listener) {\n listener({ action, location: nextLocation, delta });\n }\n },\n listen(fn: Listener) {\n listener = fn;\n return () => {\n listener = null;\n };\n },\n };\n\n return history;\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Browser History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A browser history stores the current location in regular URLs in a web\n * browser environment. This is the standard for most web apps and provides the\n * cleanest URLs the browser's address bar.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#browserhistory\n */\nexport interface BrowserHistory extends UrlHistory {}\n\nexport type BrowserHistoryOptions = UrlHistoryOptions;\n\n/**\n * Browser history stores the location in regular URLs. This is the standard for\n * most web apps, but it requires some configuration on the server to ensure you\n * serve the same app at multiple URLs.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory\n */\nexport function createBrowserHistory(\n options: BrowserHistoryOptions = {}\n): BrowserHistory {\n function createBrowserLocation(\n window: Window,\n globalHistory: Window[\"history\"]\n ) {\n let { pathname, search, hash } = window.location;\n return createLocation(\n \"\",\n { pathname, search, hash },\n // state defaults to `null` because `window.history.state` does\n (globalHistory.state && globalHistory.state.usr) || null,\n (globalHistory.state && globalHistory.state.key) || \"default\"\n );\n }\n\n function createBrowserHref(window: Window, to: To) {\n return typeof to === \"string\" ? to : createPath(to);\n }\n\n return getUrlBasedHistory(\n createBrowserLocation,\n createBrowserHref,\n null,\n options\n );\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Hash History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A hash history stores the current location in the fragment identifier portion\n * of the URL in a web browser environment.\n *\n * This is ideal for apps that do not control the server for some reason\n * (because the fragment identifier is never sent to the server), including some\n * shared hosting environments that do not provide fine-grained controls over\n * which pages are served at which URLs.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#hashhistory\n */\nexport interface HashHistory extends UrlHistory {}\n\nexport type HashHistoryOptions = UrlHistoryOptions;\n\n/**\n * Hash history stores the location in window.location.hash. This makes it ideal\n * for situations where you don't want to send the location to the server for\n * some reason, either because you do cannot configure it or the URL space is\n * reserved for something else.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory\n */\nexport function createHashHistory(\n options: HashHistoryOptions = {}\n): HashHistory {\n function createHashLocation(\n window: Window,\n globalHistory: Window[\"history\"]\n ) {\n let {\n pathname = \"/\",\n search = \"\",\n hash = \"\",\n } = parsePath(window.location.hash.substr(1));\n\n // Hash URL should always have a leading / just like window.location.pathname\n // does, so if an app ends up at a route like /#something then we add a\n // leading slash so all of our path-matching behaves the same as if it would\n // in a browser router. This is particularly important when there exists a\n // root splat route () since that matches internally against\n // \"/*\" and we'd expect /#something to 404 in a hash router app.\n if (!pathname.startsWith(\"/\") && !pathname.startsWith(\".\")) {\n pathname = \"/\" + pathname;\n }\n\n return createLocation(\n \"\",\n { pathname, search, hash },\n // state defaults to `null` because `window.history.state` does\n (globalHistory.state && globalHistory.state.usr) || null,\n (globalHistory.state && globalHistory.state.key) || \"default\"\n );\n }\n\n function createHashHref(window: Window, to: To) {\n let base = window.document.querySelector(\"base\");\n let href = \"\";\n\n if (base && base.getAttribute(\"href\")) {\n let url = window.location.href;\n let hashIndex = url.indexOf(\"#\");\n href = hashIndex === -1 ? url : url.slice(0, hashIndex);\n }\n\n return href + \"#\" + (typeof to === \"string\" ? to : createPath(to));\n }\n\n function validateHashLocation(location: Location, to: To) {\n warning(\n location.pathname.charAt(0) === \"/\",\n `relative pathnames are not supported in hash history.push(${JSON.stringify(\n to\n )})`\n );\n }\n\n return getUrlBasedHistory(\n createHashLocation,\n createHashHref,\n validateHashLocation,\n options\n );\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region UTILS\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * @private\n */\nexport function invariant(value: boolean, message?: string): asserts value;\nexport function invariant(\n value: T | null | undefined,\n message?: string\n): asserts value is T;\nexport function invariant(value: any, message?: string) {\n if (value === false || value === null || typeof value === \"undefined\") {\n throw new Error(message);\n }\n}\n\nexport function warning(cond: any, message: string) {\n if (!cond) {\n // eslint-disable-next-line no-console\n if (typeof console !== \"undefined\") console.warn(message);\n\n try {\n // Welcome to debugging history!\n //\n // This error is thrown as a convenience, so you can more easily\n // find the source for a warning that appears in the console by\n // enabling \"pause on exceptions\" in your JavaScript debugger.\n throw new Error(message);\n // eslint-disable-next-line no-empty\n } catch (e) {}\n }\n}\n\nfunction createKey() {\n return Math.random().toString(36).substr(2, 8);\n}\n\n/**\n * For browser-based histories, we combine the state and key into an object\n */\nfunction getHistoryState(location: Location, index: number): HistoryState {\n return {\n usr: location.state,\n key: location.key,\n idx: index,\n };\n}\n\n/**\n * Creates a Location object with a unique key from the given Path\n */\nexport function createLocation(\n current: string | Location,\n to: To,\n state: any = null,\n key?: string\n): Readonly {\n let location: Readonly = {\n pathname: typeof current === \"string\" ? current : current.pathname,\n search: \"\",\n hash: \"\",\n ...(typeof to === \"string\" ? parsePath(to) : to),\n state,\n // TODO: This could be cleaned up. push/replace should probably just take\n // full Locations now and avoid the need to run through this flow at all\n // But that's a pretty big refactor to the current test suite so going to\n // keep as is for the time being and just let any incoming keys take precedence\n key: (to && (to as Location).key) || key || createKey(),\n };\n return location;\n}\n\n/**\n * Creates a string URL path from the given pathname, search, and hash components.\n */\nexport function createPath({\n pathname = \"/\",\n search = \"\",\n hash = \"\",\n}: Partial) {\n if (search && search !== \"?\")\n pathname += search.charAt(0) === \"?\" ? search : \"?\" + search;\n if (hash && hash !== \"#\")\n pathname += hash.charAt(0) === \"#\" ? hash : \"#\" + hash;\n return pathname;\n}\n\n/**\n * Parses a string URL path into its separate pathname, search, and hash components.\n */\nexport function parsePath(path: string): Partial {\n let parsedPath: Partial = {};\n\n if (path) {\n let hashIndex = path.indexOf(\"#\");\n if (hashIndex >= 0) {\n parsedPath.hash = path.substr(hashIndex);\n path = path.substr(0, hashIndex);\n }\n\n let searchIndex = path.indexOf(\"?\");\n if (searchIndex >= 0) {\n parsedPath.search = path.substr(searchIndex);\n path = path.substr(0, searchIndex);\n }\n\n if (path) {\n parsedPath.pathname = path;\n }\n }\n\n return parsedPath;\n}\n\nexport interface UrlHistory extends History {}\n\nexport type UrlHistoryOptions = {\n window?: Window;\n v5Compat?: boolean;\n};\n\nfunction getUrlBasedHistory(\n getLocation: (window: Window, globalHistory: Window[\"history\"]) => Location,\n createHref: (window: Window, to: To) => string,\n validateLocation: ((location: Location, to: To) => void) | null,\n options: UrlHistoryOptions = {}\n): UrlHistory {\n let { window = document.defaultView!, v5Compat = false } = options;\n let globalHistory = window.history;\n let action = Action.Pop;\n let listener: Listener | null = null;\n\n let index = getIndex()!;\n // Index should only be null when we initialize. If not, it's because the\n // user called history.pushState or history.replaceState directly, in which\n // case we should log a warning as it will result in bugs.\n if (index == null) {\n index = 0;\n globalHistory.replaceState({ ...globalHistory.state, idx: index }, \"\");\n }\n\n function getIndex(): number {\n let state = globalHistory.state || { idx: null };\n return state.idx;\n }\n\n function handlePop() {\n action = Action.Pop;\n let nextIndex = getIndex();\n let delta = nextIndex == null ? null : nextIndex - index;\n index = nextIndex;\n if (listener) {\n listener({ action, location: history.location, delta });\n }\n }\n\n function push(to: To, state?: any) {\n action = Action.Push;\n let location = createLocation(history.location, to, state);\n if (validateLocation) validateLocation(location, to);\n\n index = getIndex() + 1;\n let historyState = getHistoryState(location, index);\n let url = history.createHref(location);\n\n // try...catch because iOS limits us to 100 pushState calls :/\n try {\n globalHistory.pushState(historyState, \"\", url);\n } catch (error) {\n // If the exception is because `state` can't be serialized, let that throw\n // outwards just like a replace call would so the dev knows the cause\n // https://html.spec.whatwg.org/multipage/nav-history-apis.html#shared-history-push/replace-state-steps\n // https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeinternal\n if (error instanceof DOMException && error.name === \"DataCloneError\") {\n throw error;\n }\n // They are going to lose state here, but there is no real\n // way to warn them about it since the page will refresh...\n window.location.assign(url);\n }\n\n if (v5Compat && listener) {\n listener({ action, location: history.location, delta: 1 });\n }\n }\n\n function replace(to: To, state?: any) {\n action = Action.Replace;\n let location = createLocation(history.location, to, state);\n if (validateLocation) validateLocation(location, to);\n\n index = getIndex();\n let historyState = getHistoryState(location, index);\n let url = history.createHref(location);\n globalHistory.replaceState(historyState, \"\", url);\n\n if (v5Compat && listener) {\n listener({ action, location: history.location, delta: 0 });\n }\n }\n\n function createURL(to: To): URL {\n // window.location.origin is \"null\" (the literal string value) in Firefox\n // under certain conditions, notably when serving from a local HTML file\n // See https://bugzilla.mozilla.org/show_bug.cgi?id=878297\n let base =\n window.location.origin !== \"null\"\n ? window.location.origin\n : window.location.href;\n\n let href = typeof to === \"string\" ? to : createPath(to);\n // Treating this as a full URL will strip any trailing spaces so we need to\n // pre-encode them since they might be part of a matching splat param from\n // an ancestor route\n href = href.replace(/ $/, \"%20\");\n invariant(\n base,\n `No window.location.(origin|href) available to create URL for href: ${href}`\n );\n return new URL(href, base);\n }\n\n let history: History = {\n get action() {\n return action;\n },\n get location() {\n return getLocation(window, globalHistory);\n },\n listen(fn: Listener) {\n if (listener) {\n throw new Error(\"A history only accepts one active listener\");\n }\n window.addEventListener(PopStateEventType, handlePop);\n listener = fn;\n\n return () => {\n window.removeEventListener(PopStateEventType, handlePop);\n listener = null;\n };\n },\n createHref(to) {\n return createHref(window, to);\n },\n createURL,\n encodeLocation(to) {\n // Encode a Location the same way window.location would\n let url = createURL(to);\n return {\n pathname: url.pathname,\n search: url.search,\n hash: url.hash,\n };\n },\n push,\n replace,\n go(n) {\n return globalHistory.go(n);\n },\n };\n\n return history;\n}\n\n//#endregion\n","import type { Location, Path, To } from \"./history\";\nimport { invariant, parsePath, warning } from \"./history\";\n\n/**\n * Map of routeId -> data returned from a loader/action/error\n */\nexport interface RouteData {\n [routeId: string]: any;\n}\n\nexport enum ResultType {\n data = \"data\",\n deferred = \"deferred\",\n redirect = \"redirect\",\n error = \"error\",\n}\n\n/**\n * Successful result from a loader or action\n */\nexport interface SuccessResult {\n type: ResultType.data;\n data: unknown;\n statusCode?: number;\n headers?: Headers;\n}\n\n/**\n * Successful defer() result from a loader or action\n */\nexport interface DeferredResult {\n type: ResultType.deferred;\n deferredData: DeferredData;\n statusCode?: number;\n headers?: Headers;\n}\n\n/**\n * Redirect result from a loader or action\n */\nexport interface RedirectResult {\n type: ResultType.redirect;\n // We keep the raw Response for redirects so we can return it verbatim\n response: Response;\n}\n\n/**\n * Unsuccessful result from a loader or action\n */\nexport interface ErrorResult {\n type: ResultType.error;\n error: unknown;\n statusCode?: number;\n headers?: Headers;\n}\n\n/**\n * Result from a loader or action - potentially successful or unsuccessful\n */\nexport type DataResult =\n | SuccessResult\n | DeferredResult\n | RedirectResult\n | ErrorResult;\n\ntype LowerCaseFormMethod = \"get\" | \"post\" | \"put\" | \"patch\" | \"delete\";\ntype UpperCaseFormMethod = Uppercase;\n\n/**\n * Users can specify either lowercase or uppercase form methods on `
`,\n * useSubmit(), ``, etc.\n */\nexport type HTMLFormMethod = LowerCaseFormMethod | UpperCaseFormMethod;\n\n/**\n * Active navigation/fetcher form methods are exposed in lowercase on the\n * RouterState\n */\nexport type FormMethod = LowerCaseFormMethod;\nexport type MutationFormMethod = Exclude;\n\n/**\n * In v7, active navigation/fetcher form methods are exposed in uppercase on the\n * RouterState. This is to align with the normalization done via fetch().\n */\nexport type V7_FormMethod = UpperCaseFormMethod;\nexport type V7_MutationFormMethod = Exclude;\n\nexport type FormEncType =\n | \"application/x-www-form-urlencoded\"\n | \"multipart/form-data\"\n | \"application/json\"\n | \"text/plain\";\n\n// Thanks https://github.com/sindresorhus/type-fest!\ntype JsonObject = { [Key in string]: JsonValue } & {\n [Key in string]?: JsonValue | undefined;\n};\ntype JsonArray = JsonValue[] | readonly JsonValue[];\ntype JsonPrimitive = string | number | boolean | null;\ntype JsonValue = JsonPrimitive | JsonObject | JsonArray;\n\n/**\n * @private\n * Internal interface to pass around for action submissions, not intended for\n * external consumption\n */\nexport type Submission =\n | {\n formMethod: FormMethod | V7_FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: FormData;\n json: undefined;\n text: undefined;\n }\n | {\n formMethod: FormMethod | V7_FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: undefined;\n json: JsonValue;\n text: undefined;\n }\n | {\n formMethod: FormMethod | V7_FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: undefined;\n json: undefined;\n text: string;\n };\n\n/**\n * @private\n * Arguments passed to route loader/action functions. Same for now but we keep\n * this as a private implementation detail in case they diverge in the future.\n */\ninterface DataFunctionArgs {\n request: Request;\n params: Params;\n context?: Context;\n}\n\n// TODO: (v7) Change the defaults from any to unknown in and remove Remix wrappers:\n// ActionFunction, ActionFunctionArgs, LoaderFunction, LoaderFunctionArgs\n// Also, make them a type alias instead of an interface\n\n/**\n * Arguments passed to loader functions\n */\nexport interface LoaderFunctionArgs\n extends DataFunctionArgs {}\n\n/**\n * Arguments passed to action functions\n */\nexport interface ActionFunctionArgs\n extends DataFunctionArgs {}\n\n/**\n * Loaders and actions can return anything except `undefined` (`null` is a\n * valid return value if there is no data to return). Responses are preferred\n * and will ease any future migration to Remix\n */\ntype DataFunctionValue = Response | NonNullable | null;\n\ntype DataFunctionReturnValue = Promise | DataFunctionValue;\n\n/**\n * Route loader function signature\n */\nexport type LoaderFunction = {\n (\n args: LoaderFunctionArgs,\n handlerCtx?: unknown\n ): DataFunctionReturnValue;\n} & { hydrate?: boolean };\n\n/**\n * Route action function signature\n */\nexport interface ActionFunction {\n (\n args: ActionFunctionArgs,\n handlerCtx?: unknown\n ): DataFunctionReturnValue;\n}\n\n/**\n * Arguments passed to shouldRevalidate function\n */\nexport interface ShouldRevalidateFunctionArgs {\n currentUrl: URL;\n currentParams: AgnosticDataRouteMatch[\"params\"];\n nextUrl: URL;\n nextParams: AgnosticDataRouteMatch[\"params\"];\n formMethod?: Submission[\"formMethod\"];\n formAction?: Submission[\"formAction\"];\n formEncType?: Submission[\"formEncType\"];\n text?: Submission[\"text\"];\n formData?: Submission[\"formData\"];\n json?: Submission[\"json\"];\n actionStatus?: number;\n actionResult?: any;\n defaultShouldRevalidate: boolean;\n}\n\n/**\n * Route shouldRevalidate function signature. This runs after any submission\n * (navigation or fetcher), so we flatten the navigation/fetcher submission\n * onto the arguments. It shouldn't matter whether it came from a navigation\n * or a fetcher, what really matters is the URLs and the formData since loaders\n * have to re-run based on the data models that were potentially mutated.\n */\nexport interface ShouldRevalidateFunction {\n (args: ShouldRevalidateFunctionArgs): boolean;\n}\n\n/**\n * Function provided by the framework-aware layers to set `hasErrorBoundary`\n * from the framework-aware `errorElement` prop\n *\n * @deprecated Use `mapRouteProperties` instead\n */\nexport interface DetectErrorBoundaryFunction {\n (route: AgnosticRouteObject): boolean;\n}\n\nexport interface DataStrategyMatch\n extends AgnosticRouteMatch {\n shouldLoad: boolean;\n resolve: (\n handlerOverride?: (\n handler: (ctx?: unknown) => DataFunctionReturnValue\n ) => DataFunctionReturnValue\n ) => Promise;\n}\n\nexport interface DataStrategyFunctionArgs\n extends DataFunctionArgs {\n matches: DataStrategyMatch[];\n fetcherKey: string | null;\n}\n\n/**\n * Result from a loader or action called via dataStrategy\n */\nexport interface DataStrategyResult {\n type: \"data\" | \"error\";\n result: unknown; // data, Error, Response, DeferredData, DataWithResponseInit\n}\n\nexport interface DataStrategyFunction {\n (args: DataStrategyFunctionArgs): Promise>;\n}\n\nexport type AgnosticPatchRoutesOnNavigationFunctionArgs<\n O extends AgnosticRouteObject = AgnosticRouteObject,\n M extends AgnosticRouteMatch = AgnosticRouteMatch\n> = {\n signal: AbortSignal;\n path: string;\n matches: M[];\n fetcherKey: string | undefined;\n patch: (routeId: string | null, children: O[]) => void;\n};\n\nexport type AgnosticPatchRoutesOnNavigationFunction<\n O extends AgnosticRouteObject = AgnosticRouteObject,\n M extends AgnosticRouteMatch = AgnosticRouteMatch\n> = (\n opts: AgnosticPatchRoutesOnNavigationFunctionArgs\n) => void | Promise;\n\n/**\n * Function provided by the framework-aware layers to set any framework-specific\n * properties from framework-agnostic properties\n */\nexport interface MapRoutePropertiesFunction {\n (route: AgnosticRouteObject): {\n hasErrorBoundary: boolean;\n } & Record;\n}\n\n/**\n * Keys we cannot change from within a lazy() function. We spread all other keys\n * onto the route. Either they're meaningful to the router, or they'll get\n * ignored.\n */\nexport type ImmutableRouteKey =\n | \"lazy\"\n | \"caseSensitive\"\n | \"path\"\n | \"id\"\n | \"index\"\n | \"children\";\n\nexport const immutableRouteKeys = new Set([\n \"lazy\",\n \"caseSensitive\",\n \"path\",\n \"id\",\n \"index\",\n \"children\",\n]);\n\ntype RequireOne = Exclude<\n {\n [K in keyof T]: K extends Key ? Omit & Required> : never;\n }[keyof T],\n undefined\n>;\n\n/**\n * lazy() function to load a route definition, which can add non-matching\n * related properties to a route\n */\nexport interface LazyRouteFunction {\n (): Promise>>;\n}\n\n/**\n * Base RouteObject with common props shared by all types of routes\n */\ntype AgnosticBaseRouteObject = {\n caseSensitive?: boolean;\n path?: string;\n id?: string;\n loader?: LoaderFunction | boolean;\n action?: ActionFunction | boolean;\n hasErrorBoundary?: boolean;\n shouldRevalidate?: ShouldRevalidateFunction;\n handle?: any;\n lazy?: LazyRouteFunction;\n};\n\n/**\n * Index routes must not have children\n */\nexport type AgnosticIndexRouteObject = AgnosticBaseRouteObject & {\n children?: undefined;\n index: true;\n};\n\n/**\n * Non-index routes may have children, but cannot have index\n */\nexport type AgnosticNonIndexRouteObject = AgnosticBaseRouteObject & {\n children?: AgnosticRouteObject[];\n index?: false;\n};\n\n/**\n * A route object represents a logical route, with (optionally) its child\n * routes organized in a tree-like structure.\n */\nexport type AgnosticRouteObject =\n | AgnosticIndexRouteObject\n | AgnosticNonIndexRouteObject;\n\nexport type AgnosticDataIndexRouteObject = AgnosticIndexRouteObject & {\n id: string;\n};\n\nexport type AgnosticDataNonIndexRouteObject = AgnosticNonIndexRouteObject & {\n children?: AgnosticDataRouteObject[];\n id: string;\n};\n\n/**\n * A data route object, which is just a RouteObject with a required unique ID\n */\nexport type AgnosticDataRouteObject =\n | AgnosticDataIndexRouteObject\n | AgnosticDataNonIndexRouteObject;\n\nexport type RouteManifest = Record;\n\n// Recursive helper for finding path parameters in the absence of wildcards\ntype _PathParam =\n // split path into individual path segments\n Path extends `${infer L}/${infer R}`\n ? _PathParam | _PathParam\n : // find params after `:`\n Path extends `:${infer Param}`\n ? Param extends `${infer Optional}?`\n ? Optional\n : Param\n : // otherwise, there aren't any params present\n never;\n\n/**\n * Examples:\n * \"/a/b/*\" -> \"*\"\n * \":a\" -> \"a\"\n * \"/a/:b\" -> \"b\"\n * \"/a/blahblahblah:b\" -> \"b\"\n * \"/:a/:b\" -> \"a\" | \"b\"\n * \"/:a/b/:c/*\" -> \"a\" | \"c\" | \"*\"\n */\nexport type PathParam =\n // check if path is just a wildcard\n Path extends \"*\" | \"/*\"\n ? \"*\"\n : // look for wildcard at the end of the path\n Path extends `${infer Rest}/*`\n ? \"*\" | _PathParam\n : // look for params in the absence of wildcards\n _PathParam;\n\n// Attempt to parse the given string segment. If it fails, then just return the\n// plain string type as a default fallback. Otherwise, return the union of the\n// parsed string literals that were referenced as dynamic segments in the route.\nexport type ParamParseKey =\n // if you could not find path params, fallback to `string`\n [PathParam] extends [never] ? string : PathParam;\n\n/**\n * The parameters that were parsed from the URL path.\n */\nexport type Params = {\n readonly [key in Key]: string | undefined;\n};\n\n/**\n * A RouteMatch contains info about how a route matched a URL.\n */\nexport interface AgnosticRouteMatch<\n ParamKey extends string = string,\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n /**\n * The names and values of dynamic parameters in the URL.\n */\n params: Params;\n /**\n * The portion of the URL pathname that was matched.\n */\n pathname: string;\n /**\n * The portion of the URL pathname that was matched before child routes.\n */\n pathnameBase: string;\n /**\n * The route object that was used to match.\n */\n route: RouteObjectType;\n}\n\nexport interface AgnosticDataRouteMatch\n extends AgnosticRouteMatch {}\n\nfunction isIndexRoute(\n route: AgnosticRouteObject\n): route is AgnosticIndexRouteObject {\n return route.index === true;\n}\n\n// Walk the route tree generating unique IDs where necessary, so we are working\n// solely with AgnosticDataRouteObject's within the Router\nexport function convertRoutesToDataRoutes(\n routes: AgnosticRouteObject[],\n mapRouteProperties: MapRoutePropertiesFunction,\n parentPath: string[] = [],\n manifest: RouteManifest = {}\n): AgnosticDataRouteObject[] {\n return routes.map((route, index) => {\n let treePath = [...parentPath, String(index)];\n let id = typeof route.id === \"string\" ? route.id : treePath.join(\"-\");\n invariant(\n route.index !== true || !route.children,\n `Cannot specify children on an index route`\n );\n invariant(\n !manifest[id],\n `Found a route id collision on id \"${id}\". Route ` +\n \"id's must be globally unique within Data Router usages\"\n );\n\n if (isIndexRoute(route)) {\n let indexRoute: AgnosticDataIndexRouteObject = {\n ...route,\n ...mapRouteProperties(route),\n id,\n };\n manifest[id] = indexRoute;\n return indexRoute;\n } else {\n let pathOrLayoutRoute: AgnosticDataNonIndexRouteObject = {\n ...route,\n ...mapRouteProperties(route),\n id,\n children: undefined,\n };\n manifest[id] = pathOrLayoutRoute;\n\n if (route.children) {\n pathOrLayoutRoute.children = convertRoutesToDataRoutes(\n route.children,\n mapRouteProperties,\n treePath,\n manifest\n );\n }\n\n return pathOrLayoutRoute;\n }\n });\n}\n\n/**\n * Matches the given routes to a location and returns the match data.\n *\n * @see https://reactrouter.com/v6/utils/match-routes\n */\nexport function matchRoutes<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n routes: RouteObjectType[],\n locationArg: Partial | string,\n basename = \"/\"\n): AgnosticRouteMatch[] | null {\n return matchRoutesImpl(routes, locationArg, basename, false);\n}\n\nexport function matchRoutesImpl<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n routes: RouteObjectType[],\n locationArg: Partial | string,\n basename: string,\n allowPartial: boolean\n): AgnosticRouteMatch[] | null {\n let location =\n typeof locationArg === \"string\" ? parsePath(locationArg) : locationArg;\n\n let pathname = stripBasename(location.pathname || \"/\", basename);\n\n if (pathname == null) {\n return null;\n }\n\n let branches = flattenRoutes(routes);\n rankRouteBranches(branches);\n\n let matches = null;\n let decoded = decodePath(pathname);\n for (let i = 0; matches == null && i < branches.length; ++i) {\n // Incoming pathnames are generally encoded from either window.location\n // or from router.navigate, but we want to match against the unencoded\n // paths in the route definitions. Memory router locations won't be\n // encoded here but there also shouldn't be anything to decode so this\n // should be a safe operation. This avoids needing matchRoutes to be\n // history-aware.\n matches = matchRouteBranch(\n branches[i],\n decoded,\n allowPartial\n );\n }\n\n return matches;\n}\n\nexport interface UIMatch {\n id: string;\n pathname: string;\n params: AgnosticRouteMatch[\"params\"];\n data: Data;\n handle: Handle;\n}\n\nexport function convertRouteMatchToUiMatch(\n match: AgnosticDataRouteMatch,\n loaderData: RouteData\n): UIMatch {\n let { route, pathname, params } = match;\n return {\n id: route.id,\n pathname,\n params,\n data: loaderData[route.id],\n handle: route.handle,\n };\n}\n\ninterface RouteMeta<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n relativePath: string;\n caseSensitive: boolean;\n childrenIndex: number;\n route: RouteObjectType;\n}\n\ninterface RouteBranch<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n path: string;\n score: number;\n routesMeta: RouteMeta[];\n}\n\nfunction flattenRoutes<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n routes: RouteObjectType[],\n branches: RouteBranch[] = [],\n parentsMeta: RouteMeta[] = [],\n parentPath = \"\"\n): RouteBranch[] {\n let flattenRoute = (\n route: RouteObjectType,\n index: number,\n relativePath?: string\n ) => {\n let meta: RouteMeta = {\n relativePath:\n relativePath === undefined ? route.path || \"\" : relativePath,\n caseSensitive: route.caseSensitive === true,\n childrenIndex: index,\n route,\n };\n\n if (meta.relativePath.startsWith(\"/\")) {\n invariant(\n meta.relativePath.startsWith(parentPath),\n `Absolute route path \"${meta.relativePath}\" nested under path ` +\n `\"${parentPath}\" is not valid. An absolute child route path ` +\n `must start with the combined path of all its parent routes.`\n );\n\n meta.relativePath = meta.relativePath.slice(parentPath.length);\n }\n\n let path = joinPaths([parentPath, meta.relativePath]);\n let routesMeta = parentsMeta.concat(meta);\n\n // Add the children before adding this route to the array, so we traverse the\n // route tree depth-first and child routes appear before their parents in\n // the \"flattened\" version.\n if (route.children && route.children.length > 0) {\n invariant(\n // Our types know better, but runtime JS may not!\n // @ts-expect-error\n route.index !== true,\n `Index routes must not have child routes. Please remove ` +\n `all child routes from route path \"${path}\".`\n );\n flattenRoutes(route.children, branches, routesMeta, path);\n }\n\n // Routes without a path shouldn't ever match by themselves unless they are\n // index routes, so don't add them to the list of possible branches.\n if (route.path == null && !route.index) {\n return;\n }\n\n branches.push({\n path,\n score: computeScore(path, route.index),\n routesMeta,\n });\n };\n routes.forEach((route, index) => {\n // coarse-grain check for optional params\n if (route.path === \"\" || !route.path?.includes(\"?\")) {\n flattenRoute(route, index);\n } else {\n for (let exploded of explodeOptionalSegments(route.path)) {\n flattenRoute(route, index, exploded);\n }\n }\n });\n\n return branches;\n}\n\n/**\n * Computes all combinations of optional path segments for a given path,\n * excluding combinations that are ambiguous and of lower priority.\n *\n * For example, `/one/:two?/three/:four?/:five?` explodes to:\n * - `/one/three`\n * - `/one/:two/three`\n * - `/one/three/:four`\n * - `/one/three/:five`\n * - `/one/:two/three/:four`\n * - `/one/:two/three/:five`\n * - `/one/three/:four/:five`\n * - `/one/:two/three/:four/:five`\n */\nfunction explodeOptionalSegments(path: string): string[] {\n let segments = path.split(\"/\");\n if (segments.length === 0) return [];\n\n let [first, ...rest] = segments;\n\n // Optional path segments are denoted by a trailing `?`\n let isOptional = first.endsWith(\"?\");\n // Compute the corresponding required segment: `foo?` -> `foo`\n let required = first.replace(/\\?$/, \"\");\n\n if (rest.length === 0) {\n // Intepret empty string as omitting an optional segment\n // `[\"one\", \"\", \"three\"]` corresponds to omitting `:two` from `/one/:two?/three` -> `/one/three`\n return isOptional ? [required, \"\"] : [required];\n }\n\n let restExploded = explodeOptionalSegments(rest.join(\"/\"));\n\n let result: string[] = [];\n\n // All child paths with the prefix. Do this for all children before the\n // optional version for all children, so we get consistent ordering where the\n // parent optional aspect is preferred as required. Otherwise, we can get\n // child sections interspersed where deeper optional segments are higher than\n // parent optional segments, where for example, /:two would explode _earlier_\n // then /:one. By always including the parent as required _for all children_\n // first, we avoid this issue\n result.push(\n ...restExploded.map((subpath) =>\n subpath === \"\" ? required : [required, subpath].join(\"/\")\n )\n );\n\n // Then, if this is an optional value, add all child versions without\n if (isOptional) {\n result.push(...restExploded);\n }\n\n // for absolute paths, ensure `/` instead of empty segment\n return result.map((exploded) =>\n path.startsWith(\"/\") && exploded === \"\" ? \"/\" : exploded\n );\n}\n\nfunction rankRouteBranches(branches: RouteBranch[]): void {\n branches.sort((a, b) =>\n a.score !== b.score\n ? b.score - a.score // Higher score first\n : compareIndexes(\n a.routesMeta.map((meta) => meta.childrenIndex),\n b.routesMeta.map((meta) => meta.childrenIndex)\n )\n );\n}\n\nconst paramRe = /^:[\\w-]+$/;\nconst dynamicSegmentValue = 3;\nconst indexRouteValue = 2;\nconst emptySegmentValue = 1;\nconst staticSegmentValue = 10;\nconst splatPenalty = -2;\nconst isSplat = (s: string) => s === \"*\";\n\nfunction computeScore(path: string, index: boolean | undefined): number {\n let segments = path.split(\"/\");\n let initialScore = segments.length;\n if (segments.some(isSplat)) {\n initialScore += splatPenalty;\n }\n\n if (index) {\n initialScore += indexRouteValue;\n }\n\n return segments\n .filter((s) => !isSplat(s))\n .reduce(\n (score, segment) =>\n score +\n (paramRe.test(segment)\n ? dynamicSegmentValue\n : segment === \"\"\n ? emptySegmentValue\n : staticSegmentValue),\n initialScore\n );\n}\n\nfunction compareIndexes(a: number[], b: number[]): number {\n let siblings =\n a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]);\n\n return siblings\n ? // If two routes are siblings, we should try to match the earlier sibling\n // first. This allows people to have fine-grained control over the matching\n // behavior by simply putting routes with identical paths in the order they\n // want them tried.\n a[a.length - 1] - b[b.length - 1]\n : // Otherwise, it doesn't really make sense to rank non-siblings by index,\n // so they sort equally.\n 0;\n}\n\nfunction matchRouteBranch<\n ParamKey extends string = string,\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n branch: RouteBranch,\n pathname: string,\n allowPartial = false\n): AgnosticRouteMatch[] | null {\n let { routesMeta } = branch;\n\n let matchedParams = {};\n let matchedPathname = \"/\";\n let matches: AgnosticRouteMatch[] = [];\n for (let i = 0; i < routesMeta.length; ++i) {\n let meta = routesMeta[i];\n let end = i === routesMeta.length - 1;\n let remainingPathname =\n matchedPathname === \"/\"\n ? pathname\n : pathname.slice(matchedPathname.length) || \"/\";\n let match = matchPath(\n { path: meta.relativePath, caseSensitive: meta.caseSensitive, end },\n remainingPathname\n );\n\n let route = meta.route;\n\n if (\n !match &&\n end &&\n allowPartial &&\n !routesMeta[routesMeta.length - 1].route.index\n ) {\n match = matchPath(\n {\n path: meta.relativePath,\n caseSensitive: meta.caseSensitive,\n end: false,\n },\n remainingPathname\n );\n }\n\n if (!match) {\n return null;\n }\n\n Object.assign(matchedParams, match.params);\n\n matches.push({\n // TODO: Can this as be avoided?\n params: matchedParams as Params,\n pathname: joinPaths([matchedPathname, match.pathname]),\n pathnameBase: normalizePathname(\n joinPaths([matchedPathname, match.pathnameBase])\n ),\n route,\n });\n\n if (match.pathnameBase !== \"/\") {\n matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);\n }\n }\n\n return matches;\n}\n\n/**\n * Returns a path with params interpolated.\n *\n * @see https://reactrouter.com/v6/utils/generate-path\n */\nexport function generatePath(\n originalPath: Path,\n params: {\n [key in PathParam]: string | null;\n } = {} as any\n): string {\n let path: string = originalPath;\n if (path.endsWith(\"*\") && path !== \"*\" && !path.endsWith(\"/*\")) {\n warning(\n false,\n `Route path \"${path}\" will be treated as if it were ` +\n `\"${path.replace(/\\*$/, \"/*\")}\" because the \\`*\\` character must ` +\n `always follow a \\`/\\` in the pattern. To get rid of this warning, ` +\n `please change the route path to \"${path.replace(/\\*$/, \"/*\")}\".`\n );\n path = path.replace(/\\*$/, \"/*\") as Path;\n }\n\n // ensure `/` is added at the beginning if the path is absolute\n const prefix = path.startsWith(\"/\") ? \"/\" : \"\";\n\n const stringify = (p: any) =>\n p == null ? \"\" : typeof p === \"string\" ? p : String(p);\n\n const segments = path\n .split(/\\/+/)\n .map((segment, index, array) => {\n const isLastSegment = index === array.length - 1;\n\n // only apply the splat if it's the last segment\n if (isLastSegment && segment === \"*\") {\n const star = \"*\" as PathParam;\n // Apply the splat\n return stringify(params[star]);\n }\n\n const keyMatch = segment.match(/^:([\\w-]+)(\\??)$/);\n if (keyMatch) {\n const [, key, optional] = keyMatch;\n let param = params[key as PathParam];\n invariant(optional === \"?\" || param != null, `Missing \":${key}\" param`);\n return stringify(param);\n }\n\n // Remove any optional markers from optional static segments\n return segment.replace(/\\?$/g, \"\");\n })\n // Remove empty segments\n .filter((segment) => !!segment);\n\n return prefix + segments.join(\"/\");\n}\n\n/**\n * A PathPattern is used to match on some portion of a URL pathname.\n */\nexport interface PathPattern {\n /**\n * A string to match against a URL pathname. May contain `:id`-style segments\n * to indicate placeholders for dynamic parameters. May also end with `/*` to\n * indicate matching the rest of the URL pathname.\n */\n path: Path;\n /**\n * Should be `true` if the static portions of the `path` should be matched in\n * the same case.\n */\n caseSensitive?: boolean;\n /**\n * Should be `true` if this pattern should match the entire URL pathname.\n */\n end?: boolean;\n}\n\n/**\n * A PathMatch contains info about how a PathPattern matched on a URL pathname.\n */\nexport interface PathMatch {\n /**\n * The names and values of dynamic parameters in the URL.\n */\n params: Params;\n /**\n * The portion of the URL pathname that was matched.\n */\n pathname: string;\n /**\n * The portion of the URL pathname that was matched before child routes.\n */\n pathnameBase: string;\n /**\n * The pattern that was used to match.\n */\n pattern: PathPattern;\n}\n\ntype Mutable = {\n -readonly [P in keyof T]: T[P];\n};\n\n/**\n * Performs pattern matching on a URL pathname and returns information about\n * the match.\n *\n * @see https://reactrouter.com/v6/utils/match-path\n */\nexport function matchPath<\n ParamKey extends ParamParseKey,\n Path extends string\n>(\n pattern: PathPattern | Path,\n pathname: string\n): PathMatch | null {\n if (typeof pattern === \"string\") {\n pattern = { path: pattern, caseSensitive: false, end: true };\n }\n\n let [matcher, compiledParams] = compilePath(\n pattern.path,\n pattern.caseSensitive,\n pattern.end\n );\n\n let match = pathname.match(matcher);\n if (!match) return null;\n\n let matchedPathname = match[0];\n let pathnameBase = matchedPathname.replace(/(.)\\/+$/, \"$1\");\n let captureGroups = match.slice(1);\n let params: Params = compiledParams.reduce>(\n (memo, { paramName, isOptional }, index) => {\n // We need to compute the pathnameBase here using the raw splat value\n // instead of using params[\"*\"] later because it will be decoded then\n if (paramName === \"*\") {\n let splatValue = captureGroups[index] || \"\";\n pathnameBase = matchedPathname\n .slice(0, matchedPathname.length - splatValue.length)\n .replace(/(.)\\/+$/, \"$1\");\n }\n\n const value = captureGroups[index];\n if (isOptional && !value) {\n memo[paramName] = undefined;\n } else {\n memo[paramName] = (value || \"\").replace(/%2F/g, \"/\");\n }\n return memo;\n },\n {}\n );\n\n return {\n params,\n pathname: matchedPathname,\n pathnameBase,\n pattern,\n };\n}\n\ntype CompiledPathParam = { paramName: string; isOptional?: boolean };\n\nfunction compilePath(\n path: string,\n caseSensitive = false,\n end = true\n): [RegExp, CompiledPathParam[]] {\n warning(\n path === \"*\" || !path.endsWith(\"*\") || path.endsWith(\"/*\"),\n `Route path \"${path}\" will be treated as if it were ` +\n `\"${path.replace(/\\*$/, \"/*\")}\" because the \\`*\\` character must ` +\n `always follow a \\`/\\` in the pattern. To get rid of this warning, ` +\n `please change the route path to \"${path.replace(/\\*$/, \"/*\")}\".`\n );\n\n let params: CompiledPathParam[] = [];\n let regexpSource =\n \"^\" +\n path\n .replace(/\\/*\\*?$/, \"\") // Ignore trailing / and /*, we'll handle it below\n .replace(/^\\/*/, \"/\") // Make sure it has a leading /\n .replace(/[\\\\.*+^${}|()[\\]]/g, \"\\\\$&\") // Escape special regex chars\n .replace(\n /\\/:([\\w-]+)(\\?)?/g,\n (_: string, paramName: string, isOptional) => {\n params.push({ paramName, isOptional: isOptional != null });\n return isOptional ? \"/?([^\\\\/]+)?\" : \"/([^\\\\/]+)\";\n }\n );\n\n if (path.endsWith(\"*\")) {\n params.push({ paramName: \"*\" });\n regexpSource +=\n path === \"*\" || path === \"/*\"\n ? \"(.*)$\" // Already matched the initial /, just match the rest\n : \"(?:\\\\/(.+)|\\\\/*)$\"; // Don't include the / in params[\"*\"]\n } else if (end) {\n // When matching to the end, ignore trailing slashes\n regexpSource += \"\\\\/*$\";\n } else if (path !== \"\" && path !== \"/\") {\n // If our path is non-empty and contains anything beyond an initial slash,\n // then we have _some_ form of path in our regex, so we should expect to\n // match only if we find the end of this path segment. Look for an optional\n // non-captured trailing slash (to match a portion of the URL) or the end\n // of the path (if we've matched to the end). We used to do this with a\n // word boundary but that gives false positives on routes like\n // /user-preferences since `-` counts as a word boundary.\n regexpSource += \"(?:(?=\\\\/|$))\";\n } else {\n // Nothing to match for \"\" or \"/\"\n }\n\n let matcher = new RegExp(regexpSource, caseSensitive ? undefined : \"i\");\n\n return [matcher, params];\n}\n\nexport function decodePath(value: string) {\n try {\n return value\n .split(\"/\")\n .map((v) => decodeURIComponent(v).replace(/\\//g, \"%2F\"))\n .join(\"/\");\n } catch (error) {\n warning(\n false,\n `The URL path \"${value}\" could not be decoded because it is is a ` +\n `malformed URL segment. This is probably due to a bad percent ` +\n `encoding (${error}).`\n );\n\n return value;\n }\n}\n\n/**\n * @private\n */\nexport function stripBasename(\n pathname: string,\n basename: string\n): string | null {\n if (basename === \"/\") return pathname;\n\n if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {\n return null;\n }\n\n // We want to leave trailing slash behavior in the user's control, so if they\n // specify a basename with a trailing slash, we should support it\n let startIndex = basename.endsWith(\"/\")\n ? basename.length - 1\n : basename.length;\n let nextChar = pathname.charAt(startIndex);\n if (nextChar && nextChar !== \"/\") {\n // pathname does not start with basename/\n return null;\n }\n\n return pathname.slice(startIndex) || \"/\";\n}\n\nconst ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i;\nexport const isAbsoluteUrl = (url: string) => ABSOLUTE_URL_REGEX.test(url);\n\n/**\n * Returns a resolved path object relative to the given pathname.\n *\n * @see https://reactrouter.com/v6/utils/resolve-path\n */\nexport function resolvePath(to: To, fromPathname = \"/\"): Path {\n let {\n pathname: toPathname,\n search = \"\",\n hash = \"\",\n } = typeof to === \"string\" ? parsePath(to) : to;\n\n let pathname: string;\n if (toPathname) {\n toPathname = removeDoubleSlashes(toPathname);\n if (toPathname.startsWith(\"/\")) {\n pathname = resolvePathname(toPathname.substring(1), \"/\");\n } else {\n pathname = resolvePathname(toPathname, fromPathname);\n }\n } else {\n pathname = fromPathname;\n }\n\n return {\n pathname,\n search: normalizeSearch(search),\n hash: normalizeHash(hash),\n };\n}\n\nfunction resolvePathname(relativePath: string, fromPathname: string): string {\n let segments = fromPathname.replace(/\\/+$/, \"\").split(\"/\");\n let relativeSegments = relativePath.split(\"/\");\n\n relativeSegments.forEach((segment) => {\n if (segment === \"..\") {\n // Keep the root \"\" segment so the pathname starts at /\n if (segments.length > 1) segments.pop();\n } else if (segment !== \".\") {\n segments.push(segment);\n }\n });\n\n return segments.length > 1 ? segments.join(\"/\") : \"/\";\n}\n\nfunction getInvalidPathError(\n char: string,\n field: string,\n dest: string,\n path: Partial\n) {\n return (\n `Cannot include a '${char}' character in a manually specified ` +\n `\\`to.${field}\\` field [${JSON.stringify(\n path\n )}]. Please separate it out to the ` +\n `\\`to.${dest}\\` field. Alternatively you may provide the full path as ` +\n `a string in and the router will parse it for you.`\n );\n}\n\n/**\n * @private\n *\n * When processing relative navigation we want to ignore ancestor routes that\n * do not contribute to the path, such that index/pathless layout routes don't\n * interfere.\n *\n * For example, when moving a route element into an index route and/or a\n * pathless layout route, relative link behavior contained within should stay\n * the same. Both of the following examples should link back to the root:\n *\n * \n * \n * \n *\n * \n * \n * }> // <-- Does not contribute\n * // <-- Does not contribute\n * \n * \n */\nexport function getPathContributingMatches<\n T extends AgnosticRouteMatch = AgnosticRouteMatch\n>(matches: T[]) {\n return matches.filter(\n (match, index) =>\n index === 0 || (match.route.path && match.route.path.length > 0)\n );\n}\n\n// Return the array of pathnames for the current route matches - used to\n// generate the routePathnames input for resolveTo()\nexport function getResolveToMatches<\n T extends AgnosticRouteMatch = AgnosticRouteMatch\n>(matches: T[], v7_relativeSplatPath: boolean) {\n let pathMatches = getPathContributingMatches(matches);\n\n // When v7_relativeSplatPath is enabled, use the full pathname for the leaf\n // match so we include splat values for \".\" links. See:\n // https://github.com/remix-run/react-router/issues/11052#issuecomment-1836589329\n if (v7_relativeSplatPath) {\n return pathMatches.map((match, idx) =>\n idx === pathMatches.length - 1 ? match.pathname : match.pathnameBase\n );\n }\n\n return pathMatches.map((match) => match.pathnameBase);\n}\n\n/**\n * @private\n */\nexport function resolveTo(\n toArg: To,\n routePathnames: string[],\n locationPathname: string,\n isPathRelative = false\n): Path {\n let to: Partial;\n if (typeof toArg === \"string\") {\n to = parsePath(toArg);\n } else {\n to = { ...toArg };\n\n invariant(\n !to.pathname || !to.pathname.includes(\"?\"),\n getInvalidPathError(\"?\", \"pathname\", \"search\", to)\n );\n invariant(\n !to.pathname || !to.pathname.includes(\"#\"),\n getInvalidPathError(\"#\", \"pathname\", \"hash\", to)\n );\n invariant(\n !to.search || !to.search.includes(\"#\"),\n getInvalidPathError(\"#\", \"search\", \"hash\", to)\n );\n }\n\n let isEmptyPath = toArg === \"\" || to.pathname === \"\";\n let toPathname = isEmptyPath ? \"/\" : to.pathname;\n\n let from: string;\n\n // Routing is relative to the current pathname if explicitly requested.\n //\n // If a pathname is explicitly provided in `to`, it should be relative to the\n // route context. This is explained in `Note on `` values` in our\n // migration guide from v5 as a means of disambiguation between `to` values\n // that begin with `/` and those that do not. However, this is problematic for\n // `to` values that do not provide a pathname. `to` can simply be a search or\n // hash string, in which case we should assume that the navigation is relative\n // to the current location's pathname and *not* the route pathname.\n if (toPathname == null) {\n from = locationPathname;\n } else {\n let routePathnameIndex = routePathnames.length - 1;\n\n // With relative=\"route\" (the default), each leading .. segment means\n // \"go up one route\" instead of \"go up one URL segment\". This is a key\n // difference from how works and a major reason we call this a\n // \"to\" value instead of a \"href\".\n if (!isPathRelative && toPathname.startsWith(\"..\")) {\n let toSegments = toPathname.split(\"/\");\n\n while (toSegments[0] === \"..\") {\n toSegments.shift();\n routePathnameIndex -= 1;\n }\n\n to.pathname = toSegments.join(\"/\");\n }\n\n from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : \"/\";\n }\n\n let path = resolvePath(to, from);\n\n // Ensure the pathname has a trailing slash if the original \"to\" had one\n let hasExplicitTrailingSlash =\n toPathname && toPathname !== \"/\" && toPathname.endsWith(\"/\");\n // Or if this was a link to the current path which has a trailing slash\n let hasCurrentTrailingSlash =\n (isEmptyPath || toPathname === \".\") && locationPathname.endsWith(\"/\");\n if (\n !path.pathname.endsWith(\"/\") &&\n (hasExplicitTrailingSlash || hasCurrentTrailingSlash)\n ) {\n path.pathname += \"/\";\n }\n\n return path;\n}\n\n/**\n * @private\n */\nexport function getToPathname(to: To): string | undefined {\n // Empty strings should be treated the same as / paths\n return to === \"\" || (to as Path).pathname === \"\"\n ? \"/\"\n : typeof to === \"string\"\n ? parsePath(to).pathname\n : to.pathname;\n}\n\nexport const removeDoubleSlashes = (path: string): string =>\n path.replace(/\\/\\/+/g, \"/\");\n\n/**\n * @private\n */\nexport const joinPaths = (paths: string[]): string =>\n removeDoubleSlashes(paths.join(\"/\"));\n\n/**\n * @private\n */\nexport const normalizePathname = (pathname: string): string =>\n pathname.replace(/\\/+$/, \"\").replace(/^\\/*/, \"/\");\n\n/**\n * @private\n */\nexport const normalizeSearch = (search: string): string =>\n !search || search === \"?\"\n ? \"\"\n : search.startsWith(\"?\")\n ? search\n : \"?\" + search;\n\n/**\n * @private\n */\nexport const normalizeHash = (hash: string): string =>\n !hash || hash === \"#\" ? \"\" : hash.startsWith(\"#\") ? hash : \"#\" + hash;\n\nexport type JsonFunction = (\n data: Data,\n init?: number | ResponseInit\n) => Response;\n\n/**\n * This is a shortcut for creating `application/json` responses. Converts `data`\n * to JSON and sets the `Content-Type` header.\n *\n * @deprecated The `json` method is deprecated in favor of returning raw objects.\n * This method will be removed in v7.\n */\nexport const json: JsonFunction = (data, init = {}) => {\n let responseInit = typeof init === \"number\" ? { status: init } : init;\n\n let headers = new Headers(responseInit.headers);\n if (!headers.has(\"Content-Type\")) {\n headers.set(\"Content-Type\", \"application/json; charset=utf-8\");\n }\n\n return new Response(JSON.stringify(data), {\n ...responseInit,\n headers,\n });\n};\n\nexport class DataWithResponseInit {\n type: string = \"DataWithResponseInit\";\n data: D;\n init: ResponseInit | null;\n\n constructor(data: D, init?: ResponseInit) {\n this.data = data;\n this.init = init || null;\n }\n}\n\n/**\n * Create \"responses\" that contain `status`/`headers` without forcing\n * serialization into an actual `Response` - used by Remix single fetch\n */\nexport function data(data: D, init?: number | ResponseInit) {\n return new DataWithResponseInit(\n data,\n typeof init === \"number\" ? { status: init } : init\n );\n}\n\nexport interface TrackedPromise extends Promise {\n _tracked?: boolean;\n _data?: any;\n _error?: any;\n}\n\nexport class AbortedDeferredError extends Error {}\n\nexport class DeferredData {\n private pendingKeysSet: Set = new Set();\n private controller: AbortController;\n private abortPromise: Promise;\n private unlistenAbortSignal: () => void;\n private subscribers: Set<(aborted: boolean, settledKey?: string) => void> =\n new Set();\n data: Record;\n init?: ResponseInit;\n deferredKeys: string[] = [];\n\n constructor(data: Record, responseInit?: ResponseInit) {\n invariant(\n data && typeof data === \"object\" && !Array.isArray(data),\n \"defer() only accepts plain objects\"\n );\n\n // Set up an AbortController + Promise we can race against to exit early\n // cancellation\n let reject: (e: AbortedDeferredError) => void;\n this.abortPromise = new Promise((_, r) => (reject = r));\n this.controller = new AbortController();\n let onAbort = () =>\n reject(new AbortedDeferredError(\"Deferred data aborted\"));\n this.unlistenAbortSignal = () =>\n this.controller.signal.removeEventListener(\"abort\", onAbort);\n this.controller.signal.addEventListener(\"abort\", onAbort);\n\n this.data = Object.entries(data).reduce(\n (acc, [key, value]) =>\n Object.assign(acc, {\n [key]: this.trackPromise(key, value),\n }),\n {}\n );\n\n if (this.done) {\n // All incoming values were resolved\n this.unlistenAbortSignal();\n }\n\n this.init = responseInit;\n }\n\n private trackPromise(\n key: string,\n value: Promise | unknown\n ): TrackedPromise | unknown {\n if (!(value instanceof Promise)) {\n return value;\n }\n\n this.deferredKeys.push(key);\n this.pendingKeysSet.add(key);\n\n // We store a little wrapper promise that will be extended with\n // _data/_error props upon resolve/reject\n let promise: TrackedPromise = Promise.race([value, this.abortPromise]).then(\n (data) => this.onSettle(promise, key, undefined, data as unknown),\n (error) => this.onSettle(promise, key, error as unknown)\n );\n\n // Register rejection listeners to avoid uncaught promise rejections on\n // errors or aborted deferred values\n promise.catch(() => {});\n\n Object.defineProperty(promise, \"_tracked\", { get: () => true });\n return promise;\n }\n\n private onSettle(\n promise: TrackedPromise,\n key: string,\n error: unknown,\n data?: unknown\n ): unknown {\n if (\n this.controller.signal.aborted &&\n error instanceof AbortedDeferredError\n ) {\n this.unlistenAbortSignal();\n Object.defineProperty(promise, \"_error\", { get: () => error });\n return Promise.reject(error);\n }\n\n this.pendingKeysSet.delete(key);\n\n if (this.done) {\n // Nothing left to abort!\n this.unlistenAbortSignal();\n }\n\n // If the promise was resolved/rejected with undefined, we'll throw an error as you\n // should always resolve with a value or null\n if (error === undefined && data === undefined) {\n let undefinedError = new Error(\n `Deferred data for key \"${key}\" resolved/rejected with \\`undefined\\`, ` +\n `you must resolve/reject with a value or \\`null\\`.`\n );\n Object.defineProperty(promise, \"_error\", { get: () => undefinedError });\n this.emit(false, key);\n return Promise.reject(undefinedError);\n }\n\n if (data === undefined) {\n Object.defineProperty(promise, \"_error\", { get: () => error });\n this.emit(false, key);\n return Promise.reject(error);\n }\n\n Object.defineProperty(promise, \"_data\", { get: () => data });\n this.emit(false, key);\n return data;\n }\n\n private emit(aborted: boolean, settledKey?: string) {\n this.subscribers.forEach((subscriber) => subscriber(aborted, settledKey));\n }\n\n subscribe(fn: (aborted: boolean, settledKey?: string) => void) {\n this.subscribers.add(fn);\n return () => this.subscribers.delete(fn);\n }\n\n cancel() {\n this.controller.abort();\n this.pendingKeysSet.forEach((v, k) => this.pendingKeysSet.delete(k));\n this.emit(true);\n }\n\n async resolveData(signal: AbortSignal) {\n let aborted = false;\n if (!this.done) {\n let onAbort = () => this.cancel();\n signal.addEventListener(\"abort\", onAbort);\n aborted = await new Promise((resolve) => {\n this.subscribe((aborted) => {\n signal.removeEventListener(\"abort\", onAbort);\n if (aborted || this.done) {\n resolve(aborted);\n }\n });\n });\n }\n return aborted;\n }\n\n get done() {\n return this.pendingKeysSet.size === 0;\n }\n\n get unwrappedData() {\n invariant(\n this.data !== null && this.done,\n \"Can only unwrap data on initialized and settled deferreds\"\n );\n\n return Object.entries(this.data).reduce(\n (acc, [key, value]) =>\n Object.assign(acc, {\n [key]: unwrapTrackedPromise(value),\n }),\n {}\n );\n }\n\n get pendingKeys() {\n return Array.from(this.pendingKeysSet);\n }\n}\n\nfunction isTrackedPromise(value: any): value is TrackedPromise {\n return (\n value instanceof Promise && (value as TrackedPromise)._tracked === true\n );\n}\n\nfunction unwrapTrackedPromise(value: any) {\n if (!isTrackedPromise(value)) {\n return value;\n }\n\n if (value._error) {\n throw value._error;\n }\n return value._data;\n}\n\nexport type DeferFunction = (\n data: Record,\n init?: number | ResponseInit\n) => DeferredData;\n\n/**\n * @deprecated The `defer` method is deprecated in favor of returning raw\n * objects. This method will be removed in v7.\n */\nexport const defer: DeferFunction = (data, init = {}) => {\n let responseInit = typeof init === \"number\" ? { status: init } : init;\n\n return new DeferredData(data, responseInit);\n};\n\nexport type RedirectFunction = (\n url: string,\n init?: number | ResponseInit\n) => Response;\n\n/**\n * A redirect response. Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nexport const redirect: RedirectFunction = (url, init = 302) => {\n let responseInit = init;\n if (typeof responseInit === \"number\") {\n responseInit = { status: responseInit };\n } else if (typeof responseInit.status === \"undefined\") {\n responseInit.status = 302;\n }\n\n let headers = new Headers(responseInit.headers);\n headers.set(\"Location\", url);\n\n return new Response(null, {\n ...responseInit,\n headers,\n });\n};\n\n/**\n * A redirect response that will force a document reload to the new location.\n * Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nexport const redirectDocument: RedirectFunction = (url, init) => {\n let response = redirect(url, init);\n response.headers.set(\"X-Remix-Reload-Document\", \"true\");\n return response;\n};\n\n/**\n * A redirect response that will perform a `history.replaceState` instead of a\n * `history.pushState` for client-side navigation redirects.\n * Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nexport const replace: RedirectFunction = (url, init) => {\n let response = redirect(url, init);\n response.headers.set(\"X-Remix-Replace\", \"true\");\n return response;\n};\n\nexport type ErrorResponse = {\n status: number;\n statusText: string;\n data: any;\n};\n\n/**\n * @private\n * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies\n *\n * We don't export the class for public use since it's an implementation\n * detail, but we export the interface above so folks can build their own\n * abstractions around instances via isRouteErrorResponse()\n */\nexport class ErrorResponseImpl implements ErrorResponse {\n status: number;\n statusText: string;\n data: any;\n private error?: Error;\n private internal: boolean;\n\n constructor(\n status: number,\n statusText: string | undefined,\n data: any,\n internal = false\n ) {\n this.status = status;\n this.statusText = statusText || \"\";\n this.internal = internal;\n if (data instanceof Error) {\n this.data = data.toString();\n this.error = data;\n } else {\n this.data = data;\n }\n }\n}\n\n/**\n * Check if the given error is an ErrorResponse generated from a 4xx/5xx\n * Response thrown from an action/loader\n */\nexport function isRouteErrorResponse(error: any): error is ErrorResponse {\n return (\n error != null &&\n typeof error.status === \"number\" &&\n typeof error.statusText === \"string\" &&\n typeof error.internal === \"boolean\" &&\n \"data\" in error\n );\n}\n","import type { History, Location, Path, To } from \"./history\";\nimport {\n Action as HistoryAction,\n createLocation,\n createPath,\n invariant,\n parsePath,\n warning,\n} from \"./history\";\nimport type {\n AgnosticDataRouteMatch,\n AgnosticDataRouteObject,\n DataStrategyMatch,\n AgnosticRouteObject,\n DataResult,\n DataStrategyFunction,\n DataStrategyFunctionArgs,\n DeferredData,\n DeferredResult,\n DetectErrorBoundaryFunction,\n ErrorResult,\n FormEncType,\n FormMethod,\n HTMLFormMethod,\n DataStrategyResult,\n ImmutableRouteKey,\n MapRoutePropertiesFunction,\n MutationFormMethod,\n RedirectResult,\n RouteData,\n RouteManifest,\n ShouldRevalidateFunctionArgs,\n Submission,\n SuccessResult,\n UIMatch,\n V7_FormMethod,\n V7_MutationFormMethod,\n AgnosticPatchRoutesOnNavigationFunction,\n DataWithResponseInit,\n} from \"./utils\";\nimport {\n ErrorResponseImpl,\n ResultType,\n convertRouteMatchToUiMatch,\n convertRoutesToDataRoutes,\n getPathContributingMatches,\n getResolveToMatches,\n immutableRouteKeys,\n isRouteErrorResponse,\n joinPaths,\n matchRoutes,\n matchRoutesImpl,\n removeDoubleSlashes,\n resolveTo,\n stripBasename,\n} from \"./utils\";\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Types and Constants\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A Router instance manages all navigation and data loading/mutations\n */\nexport interface Router {\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the basename for the router\n */\n get basename(): RouterInit[\"basename\"];\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the future config for the router\n */\n get future(): FutureConfig;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the current state of the router\n */\n get state(): RouterState;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the routes for this router instance\n */\n get routes(): AgnosticDataRouteObject[];\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the window associated with the router\n */\n get window(): RouterInit[\"window\"];\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Initialize the router, including adding history listeners and kicking off\n * initial data fetches. Returns a function to cleanup listeners and abort\n * any in-progress loads\n */\n initialize(): Router;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Subscribe to router.state updates\n *\n * @param fn function to call with the new state\n */\n subscribe(fn: RouterSubscriber): () => void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Enable scroll restoration behavior in the router\n *\n * @param savedScrollPositions Object that will manage positions, in case\n * it's being restored from sessionStorage\n * @param getScrollPosition Function to get the active Y scroll position\n * @param getKey Function to get the key to use for restoration\n */\n enableScrollRestoration(\n savedScrollPositions: Record,\n getScrollPosition: GetScrollPositionFunction,\n getKey?: GetScrollRestorationKeyFunction\n ): () => void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Navigate forward/backward in the history stack\n * @param to Delta to move in the history stack\n */\n navigate(to: number): Promise;\n\n /**\n * Navigate to the given path\n * @param to Path to navigate to\n * @param opts Navigation options (method, submission, etc.)\n */\n navigate(to: To | null, opts?: RouterNavigateOptions): Promise;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Trigger a fetcher load/submission\n *\n * @param key Fetcher key\n * @param routeId Route that owns the fetcher\n * @param href href to fetch\n * @param opts Fetcher options, (method, submission, etc.)\n */\n fetch(\n key: string,\n routeId: string,\n href: string | null,\n opts?: RouterFetchOptions\n ): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Trigger a revalidation of all current route loaders and fetcher loads\n */\n revalidate(): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Utility function to create an href for the given location\n * @param location\n */\n createHref(location: Location | URL): string;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Utility function to URL encode a destination path according to the internal\n * history implementation\n * @param to\n */\n encodeLocation(to: To): Path;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Get/create a fetcher for the given key\n * @param key\n */\n getFetcher(key: string): Fetcher;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Delete the fetcher for a given key\n * @param key\n */\n deleteFetcher(key: string): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Cleanup listeners and abort any in-progress loads\n */\n dispose(): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Get a navigation blocker\n * @param key The identifier for the blocker\n * @param fn The blocker function implementation\n */\n getBlocker(key: string, fn: BlockerFunction): Blocker;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Delete a navigation blocker\n * @param key The identifier for the blocker\n */\n deleteBlocker(key: string): void;\n\n /**\n * @internal\n * PRIVATE DO NOT USE\n *\n * Patch additional children routes into an existing parent route\n * @param routeId The parent route id or a callback function accepting `patch`\n * to perform batch patching\n * @param children The additional children routes\n */\n patchRoutes(routeId: string | null, children: AgnosticRouteObject[]): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * HMR needs to pass in-flight route updates to React Router\n * TODO: Replace this with granular route update APIs (addRoute, updateRoute, deleteRoute)\n */\n _internalSetRoutes(routes: AgnosticRouteObject[]): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Internal fetch AbortControllers accessed by unit tests\n */\n _internalFetchControllers: Map;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Internal pending DeferredData instances accessed by unit tests\n */\n _internalActiveDeferreds: Map;\n}\n\n/**\n * State maintained internally by the router. During a navigation, all states\n * reflect the the \"old\" location unless otherwise noted.\n */\nexport interface RouterState {\n /**\n * The action of the most recent navigation\n */\n historyAction: HistoryAction;\n\n /**\n * The current location reflected by the router\n */\n location: Location;\n\n /**\n * The current set of route matches\n */\n matches: AgnosticDataRouteMatch[];\n\n /**\n * Tracks whether we've completed our initial data load\n */\n initialized: boolean;\n\n /**\n * Current scroll position we should start at for a new view\n * - number -> scroll position to restore to\n * - false -> do not restore scroll at all (used during submissions)\n * - null -> don't have a saved position, scroll to hash or top of page\n */\n restoreScrollPosition: number | false | null;\n\n /**\n * Indicate whether this navigation should skip resetting the scroll position\n * if we are unable to restore the scroll position\n */\n preventScrollReset: boolean;\n\n /**\n * Tracks the state of the current navigation\n */\n navigation: Navigation;\n\n /**\n * Tracks any in-progress revalidations\n */\n revalidation: RevalidationState;\n\n /**\n * Data from the loaders for the current matches\n */\n loaderData: RouteData;\n\n /**\n * Data from the action for the current matches\n */\n actionData: RouteData | null;\n\n /**\n * Errors caught from loaders for the current matches\n */\n errors: RouteData | null;\n\n /**\n * Map of current fetchers\n */\n fetchers: Map;\n\n /**\n * Map of current blockers\n */\n blockers: Map;\n}\n\n/**\n * Data that can be passed into hydrate a Router from SSR\n */\nexport type HydrationState = Partial<\n Pick\n>;\n\n/**\n * Future flags to toggle new feature behavior\n */\nexport interface FutureConfig {\n v7_fetcherPersist: boolean;\n v7_normalizeFormMethod: boolean;\n v7_partialHydration: boolean;\n v7_prependBasename: boolean;\n v7_relativeSplatPath: boolean;\n v7_skipActionErrorRevalidation: boolean;\n}\n\n/**\n * Initialization options for createRouter\n */\nexport interface RouterInit {\n routes: AgnosticRouteObject[];\n history: History;\n basename?: string;\n /**\n * @deprecated Use `mapRouteProperties` instead\n */\n detectErrorBoundary?: DetectErrorBoundaryFunction;\n mapRouteProperties?: MapRoutePropertiesFunction;\n future?: Partial;\n hydrationData?: HydrationState;\n window?: Window;\n dataStrategy?: DataStrategyFunction;\n patchRoutesOnNavigation?: AgnosticPatchRoutesOnNavigationFunction;\n}\n\n/**\n * State returned from a server-side query() call\n */\nexport interface StaticHandlerContext {\n basename: Router[\"basename\"];\n location: RouterState[\"location\"];\n matches: RouterState[\"matches\"];\n loaderData: RouterState[\"loaderData\"];\n actionData: RouterState[\"actionData\"];\n errors: RouterState[\"errors\"];\n statusCode: number;\n loaderHeaders: Record;\n actionHeaders: Record;\n activeDeferreds: Record | null;\n _deepestRenderedBoundaryId?: string | null;\n}\n\n/**\n * A StaticHandler instance manages a singular SSR navigation/fetch event\n */\nexport interface StaticHandler {\n dataRoutes: AgnosticDataRouteObject[];\n query(\n request: Request,\n opts?: {\n requestContext?: unknown;\n skipLoaderErrorBubbling?: boolean;\n dataStrategy?: DataStrategyFunction;\n }\n ): Promise;\n queryRoute(\n request: Request,\n opts?: {\n routeId?: string;\n requestContext?: unknown;\n dataStrategy?: DataStrategyFunction;\n }\n ): Promise;\n}\n\ntype ViewTransitionOpts = {\n currentLocation: Location;\n nextLocation: Location;\n};\n\n/**\n * Subscriber function signature for changes to router state\n */\nexport interface RouterSubscriber {\n (\n state: RouterState,\n opts: {\n deletedFetchers: string[];\n viewTransitionOpts?: ViewTransitionOpts;\n flushSync: boolean;\n }\n ): void;\n}\n\n/**\n * Function signature for determining the key to be used in scroll restoration\n * for a given location\n */\nexport interface GetScrollRestorationKeyFunction {\n (location: Location, matches: UIMatch[]): string | null;\n}\n\n/**\n * Function signature for determining the current scroll position\n */\nexport interface GetScrollPositionFunction {\n (): number;\n}\n\nexport type RelativeRoutingType = \"route\" | \"path\";\n\n// Allowed for any navigation or fetch\ntype BaseNavigateOrFetchOptions = {\n preventScrollReset?: boolean;\n relative?: RelativeRoutingType;\n flushSync?: boolean;\n};\n\n// Only allowed for navigations\ntype BaseNavigateOptions = BaseNavigateOrFetchOptions & {\n replace?: boolean;\n state?: any;\n fromRouteId?: string;\n viewTransition?: boolean;\n};\n\n// Only allowed for submission navigations\ntype BaseSubmissionOptions = {\n formMethod?: HTMLFormMethod;\n formEncType?: FormEncType;\n} & (\n | { formData: FormData; body?: undefined }\n | { formData?: undefined; body: any }\n);\n\n/**\n * Options for a navigate() call for a normal (non-submission) navigation\n */\ntype LinkNavigateOptions = BaseNavigateOptions;\n\n/**\n * Options for a navigate() call for a submission navigation\n */\ntype SubmissionNavigateOptions = BaseNavigateOptions & BaseSubmissionOptions;\n\n/**\n * Options to pass to navigate() for a navigation\n */\nexport type RouterNavigateOptions =\n | LinkNavigateOptions\n | SubmissionNavigateOptions;\n\n/**\n * Options for a fetch() load\n */\ntype LoadFetchOptions = BaseNavigateOrFetchOptions;\n\n/**\n * Options for a fetch() submission\n */\ntype SubmitFetchOptions = BaseNavigateOrFetchOptions & BaseSubmissionOptions;\n\n/**\n * Options to pass to fetch()\n */\nexport type RouterFetchOptions = LoadFetchOptions | SubmitFetchOptions;\n\n/**\n * Potential states for state.navigation\n */\nexport type NavigationStates = {\n Idle: {\n state: \"idle\";\n location: undefined;\n formMethod: undefined;\n formAction: undefined;\n formEncType: undefined;\n formData: undefined;\n json: undefined;\n text: undefined;\n };\n Loading: {\n state: \"loading\";\n location: Location;\n formMethod: Submission[\"formMethod\"] | undefined;\n formAction: Submission[\"formAction\"] | undefined;\n formEncType: Submission[\"formEncType\"] | undefined;\n formData: Submission[\"formData\"] | undefined;\n json: Submission[\"json\"] | undefined;\n text: Submission[\"text\"] | undefined;\n };\n Submitting: {\n state: \"submitting\";\n location: Location;\n formMethod: Submission[\"formMethod\"];\n formAction: Submission[\"formAction\"];\n formEncType: Submission[\"formEncType\"];\n formData: Submission[\"formData\"];\n json: Submission[\"json\"];\n text: Submission[\"text\"];\n };\n};\n\nexport type Navigation = NavigationStates[keyof NavigationStates];\n\nexport type RevalidationState = \"idle\" | \"loading\";\n\n/**\n * Potential states for fetchers\n */\ntype FetcherStates = {\n Idle: {\n state: \"idle\";\n formMethod: undefined;\n formAction: undefined;\n formEncType: undefined;\n text: undefined;\n formData: undefined;\n json: undefined;\n data: TData | undefined;\n };\n Loading: {\n state: \"loading\";\n formMethod: Submission[\"formMethod\"] | undefined;\n formAction: Submission[\"formAction\"] | undefined;\n formEncType: Submission[\"formEncType\"] | undefined;\n text: Submission[\"text\"] | undefined;\n formData: Submission[\"formData\"] | undefined;\n json: Submission[\"json\"] | undefined;\n data: TData | undefined;\n };\n Submitting: {\n state: \"submitting\";\n formMethod: Submission[\"formMethod\"];\n formAction: Submission[\"formAction\"];\n formEncType: Submission[\"formEncType\"];\n text: Submission[\"text\"];\n formData: Submission[\"formData\"];\n json: Submission[\"json\"];\n data: TData | undefined;\n };\n};\n\nexport type Fetcher =\n FetcherStates[keyof FetcherStates];\n\ninterface BlockerBlocked {\n state: \"blocked\";\n reset(): void;\n proceed(): void;\n location: Location;\n}\n\ninterface BlockerUnblocked {\n state: \"unblocked\";\n reset: undefined;\n proceed: undefined;\n location: undefined;\n}\n\ninterface BlockerProceeding {\n state: \"proceeding\";\n reset: undefined;\n proceed: undefined;\n location: Location;\n}\n\nexport type Blocker = BlockerUnblocked | BlockerBlocked | BlockerProceeding;\n\nexport type BlockerFunction = (args: {\n currentLocation: Location;\n nextLocation: Location;\n historyAction: HistoryAction;\n}) => boolean;\n\ninterface ShortCircuitable {\n /**\n * startNavigation does not need to complete the navigation because we\n * redirected or got interrupted\n */\n shortCircuited?: boolean;\n}\n\ntype PendingActionResult = [string, SuccessResult | ErrorResult];\n\ninterface HandleActionResult extends ShortCircuitable {\n /**\n * Route matches which may have been updated from fog of war discovery\n */\n matches?: RouterState[\"matches\"];\n /**\n * Tuple for the returned or thrown value from the current action. The routeId\n * is the action route for success and the bubbled boundary route for errors.\n */\n pendingActionResult?: PendingActionResult;\n}\n\ninterface HandleLoadersResult extends ShortCircuitable {\n /**\n * Route matches which may have been updated from fog of war discovery\n */\n matches?: RouterState[\"matches\"];\n /**\n * loaderData returned from the current set of loaders\n */\n loaderData?: RouterState[\"loaderData\"];\n /**\n * errors thrown from the current set of loaders\n */\n errors?: RouterState[\"errors\"];\n}\n\n/**\n * Cached info for active fetcher.load() instances so they can participate\n * in revalidation\n */\ninterface FetchLoadMatch {\n routeId: string;\n path: string;\n}\n\n/**\n * Identified fetcher.load() calls that need to be revalidated\n */\ninterface RevalidatingFetcher extends FetchLoadMatch {\n key: string;\n match: AgnosticDataRouteMatch | null;\n matches: AgnosticDataRouteMatch[] | null;\n controller: AbortController | null;\n}\n\nconst validMutationMethodsArr: MutationFormMethod[] = [\n \"post\",\n \"put\",\n \"patch\",\n \"delete\",\n];\nconst validMutationMethods = new Set(\n validMutationMethodsArr\n);\n\nconst validRequestMethodsArr: FormMethod[] = [\n \"get\",\n ...validMutationMethodsArr,\n];\nconst validRequestMethods = new Set(validRequestMethodsArr);\n\nconst redirectStatusCodes = new Set([301, 302, 303, 307, 308]);\nconst redirectPreserveMethodStatusCodes = new Set([307, 308]);\n\nexport const IDLE_NAVIGATION: NavigationStates[\"Idle\"] = {\n state: \"idle\",\n location: undefined,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n};\n\nexport const IDLE_FETCHER: FetcherStates[\"Idle\"] = {\n state: \"idle\",\n data: undefined,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n};\n\nexport const IDLE_BLOCKER: BlockerUnblocked = {\n state: \"unblocked\",\n proceed: undefined,\n reset: undefined,\n location: undefined,\n};\n\nconst ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i;\n\nconst defaultMapRouteProperties: MapRoutePropertiesFunction = (route) => ({\n hasErrorBoundary: Boolean(route.hasErrorBoundary),\n});\n\nconst TRANSITIONS_STORAGE_KEY = \"remix-router-transitions\";\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region createRouter\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Create a router and listen to history POP navigations\n */\nexport function createRouter(init: RouterInit): Router {\n const routerWindow = init.window\n ? init.window\n : typeof window !== \"undefined\"\n ? window\n : undefined;\n const isBrowser =\n typeof routerWindow !== \"undefined\" &&\n typeof routerWindow.document !== \"undefined\" &&\n typeof routerWindow.document.createElement !== \"undefined\";\n const isServer = !isBrowser;\n\n invariant(\n init.routes.length > 0,\n \"You must provide a non-empty routes array to createRouter\"\n );\n\n let mapRouteProperties: MapRoutePropertiesFunction;\n if (init.mapRouteProperties) {\n mapRouteProperties = init.mapRouteProperties;\n } else if (init.detectErrorBoundary) {\n // If they are still using the deprecated version, wrap it with the new API\n let detectErrorBoundary = init.detectErrorBoundary;\n mapRouteProperties = (route) => ({\n hasErrorBoundary: detectErrorBoundary(route),\n });\n } else {\n mapRouteProperties = defaultMapRouteProperties;\n }\n\n // Routes keyed by ID\n let manifest: RouteManifest = {};\n // Routes in tree format for matching\n let dataRoutes = convertRoutesToDataRoutes(\n init.routes,\n mapRouteProperties,\n undefined,\n manifest\n );\n let inFlightDataRoutes: AgnosticDataRouteObject[] | undefined;\n let basename = init.basename || \"/\";\n let dataStrategyImpl = init.dataStrategy || defaultDataStrategy;\n let patchRoutesOnNavigationImpl = init.patchRoutesOnNavigation;\n\n // Config driven behavior flags\n let future: FutureConfig = {\n v7_fetcherPersist: false,\n v7_normalizeFormMethod: false,\n v7_partialHydration: false,\n v7_prependBasename: false,\n v7_relativeSplatPath: false,\n v7_skipActionErrorRevalidation: false,\n ...init.future,\n };\n // Cleanup function for history\n let unlistenHistory: (() => void) | null = null;\n // Externally-provided functions to call on all state changes\n let subscribers = new Set();\n // Externally-provided object to hold scroll restoration locations during routing\n let savedScrollPositions: Record | null = null;\n // Externally-provided function to get scroll restoration keys\n let getScrollRestorationKey: GetScrollRestorationKeyFunction | null = null;\n // Externally-provided function to get current scroll position\n let getScrollPosition: GetScrollPositionFunction | null = null;\n // One-time flag to control the initial hydration scroll restoration. Because\n // we don't get the saved positions from until _after_\n // the initial render, we need to manually trigger a separate updateState to\n // send along the restoreScrollPosition\n // Set to true if we have `hydrationData` since we assume we were SSR'd and that\n // SSR did the initial scroll restoration.\n let initialScrollRestored = init.hydrationData != null;\n\n let initialMatches = matchRoutes(dataRoutes, init.history.location, basename);\n let initialMatchesIsFOW = false;\n let initialErrors: RouteData | null = null;\n\n if (initialMatches == null && !patchRoutesOnNavigationImpl) {\n // If we do not match a user-provided-route, fall back to the root\n // to allow the error boundary to take over\n let error = getInternalRouterError(404, {\n pathname: init.history.location.pathname,\n });\n let { matches, route } = getShortCircuitMatches(dataRoutes);\n initialMatches = matches;\n initialErrors = { [route.id]: error };\n }\n\n // In SPA apps, if the user provided a patchRoutesOnNavigation implementation and\n // our initial match is a splat route, clear them out so we run through lazy\n // discovery on hydration in case there's a more accurate lazy route match.\n // In SSR apps (with `hydrationData`), we expect that the server will send\n // up the proper matched routes so we don't want to run lazy discovery on\n // initial hydration and want to hydrate into the splat route.\n if (initialMatches && !init.hydrationData) {\n let fogOfWar = checkFogOfWar(\n initialMatches,\n dataRoutes,\n init.history.location.pathname\n );\n if (fogOfWar.active) {\n initialMatches = null;\n }\n }\n\n let initialized: boolean;\n if (!initialMatches) {\n initialized = false;\n initialMatches = [];\n\n // If partial hydration and fog of war is enabled, we will be running\n // `patchRoutesOnNavigation` during hydration so include any partial matches as\n // the initial matches so we can properly render `HydrateFallback`'s\n if (future.v7_partialHydration) {\n let fogOfWar = checkFogOfWar(\n null,\n dataRoutes,\n init.history.location.pathname\n );\n if (fogOfWar.active && fogOfWar.matches) {\n initialMatchesIsFOW = true;\n initialMatches = fogOfWar.matches;\n }\n }\n } else if (initialMatches.some((m) => m.route.lazy)) {\n // All initialMatches need to be loaded before we're ready. If we have lazy\n // functions around still then we'll need to run them in initialize()\n initialized = false;\n } else if (!initialMatches.some((m) => m.route.loader)) {\n // If we've got no loaders to run, then we're good to go\n initialized = true;\n } else if (future.v7_partialHydration) {\n // If partial hydration is enabled, we're initialized so long as we were\n // provided with hydrationData for every route with a loader, and no loaders\n // were marked for explicit hydration\n let loaderData = init.hydrationData ? init.hydrationData.loaderData : null;\n let errors = init.hydrationData ? init.hydrationData.errors : null;\n // If errors exist, don't consider routes below the boundary\n if (errors) {\n let idx = initialMatches.findIndex(\n (m) => errors![m.route.id] !== undefined\n );\n initialized = initialMatches\n .slice(0, idx + 1)\n .every((m) => !shouldLoadRouteOnHydration(m.route, loaderData, errors));\n } else {\n initialized = initialMatches.every(\n (m) => !shouldLoadRouteOnHydration(m.route, loaderData, errors)\n );\n }\n } else {\n // Without partial hydration - we're initialized if we were provided any\n // hydrationData - which is expected to be complete\n initialized = init.hydrationData != null;\n }\n\n let router: Router;\n let state: RouterState = {\n historyAction: init.history.action,\n location: init.history.location,\n matches: initialMatches,\n initialized,\n navigation: IDLE_NAVIGATION,\n // Don't restore on initial updateState() if we were SSR'd\n restoreScrollPosition: init.hydrationData != null ? false : null,\n preventScrollReset: false,\n revalidation: \"idle\",\n loaderData: (init.hydrationData && init.hydrationData.loaderData) || {},\n actionData: (init.hydrationData && init.hydrationData.actionData) || null,\n errors: (init.hydrationData && init.hydrationData.errors) || initialErrors,\n fetchers: new Map(),\n blockers: new Map(),\n };\n\n // -- Stateful internal variables to manage navigations --\n // Current navigation in progress (to be committed in completeNavigation)\n let pendingAction: HistoryAction = HistoryAction.Pop;\n\n // Should the current navigation prevent the scroll reset if scroll cannot\n // be restored?\n let pendingPreventScrollReset = false;\n\n // AbortController for the active navigation\n let pendingNavigationController: AbortController | null;\n\n // Should the current navigation enable document.startViewTransition?\n let pendingViewTransitionEnabled = false;\n\n // Store applied view transitions so we can apply them on POP\n let appliedViewTransitions: Map> = new Map<\n string,\n Set\n >();\n\n // Cleanup function for persisting applied transitions to sessionStorage\n let removePageHideEventListener: (() => void) | null = null;\n\n // We use this to avoid touching history in completeNavigation if a\n // revalidation is entirely uninterrupted\n let isUninterruptedRevalidation = false;\n\n // Use this internal flag to force revalidation of all loaders:\n // - submissions (completed or interrupted)\n // - useRevalidator()\n // - X-Remix-Revalidate (from redirect)\n let isRevalidationRequired = false;\n\n // Use this internal array to capture routes that require revalidation due\n // to a cancelled deferred on action submission\n let cancelledDeferredRoutes: string[] = [];\n\n // Use this internal array to capture fetcher loads that were cancelled by an\n // action navigation and require revalidation\n let cancelledFetcherLoads: Set = new Set();\n\n // AbortControllers for any in-flight fetchers\n let fetchControllers = new Map();\n\n // Track loads based on the order in which they started\n let incrementingLoadId = 0;\n\n // Track the outstanding pending navigation data load to be compared against\n // the globally incrementing load when a fetcher load lands after a completed\n // navigation\n let pendingNavigationLoadId = -1;\n\n // Fetchers that triggered data reloads as a result of their actions\n let fetchReloadIds = new Map();\n\n // Fetchers that triggered redirect navigations\n let fetchRedirectIds = new Set();\n\n // Most recent href/match for fetcher.load calls for fetchers\n let fetchLoadMatches = new Map();\n\n // Ref-count mounted fetchers so we know when it's ok to clean them up\n let activeFetchers = new Map();\n\n // Fetchers that have requested a delete when using v7_fetcherPersist,\n // they'll be officially removed after they return to idle\n let deletedFetchers = new Set();\n\n // Store DeferredData instances for active route matches. When a\n // route loader returns defer() we stick one in here. Then, when a nested\n // promise resolves we update loaderData. If a new navigation starts we\n // cancel active deferreds for eliminated routes.\n let activeDeferreds = new Map();\n\n // Store blocker functions in a separate Map outside of router state since\n // we don't need to update UI state if they change\n let blockerFunctions = new Map();\n\n // Map of pending patchRoutesOnNavigation() promises (keyed by path/matches) so\n // that we only kick them off once for a given combo\n let pendingPatchRoutes = new Map<\n string,\n ReturnType\n >();\n\n // Flag to ignore the next history update, so we can revert the URL change on\n // a POP navigation that was blocked by the user without touching router state\n let unblockBlockerHistoryUpdate: (() => void) | undefined = undefined;\n\n // Initialize the router, all side effects should be kicked off from here.\n // Implemented as a Fluent API for ease of:\n // let router = createRouter(init).initialize();\n function initialize() {\n // If history informs us of a POP navigation, start the navigation but do not update\n // state. We'll update our own state once the navigation completes\n unlistenHistory = init.history.listen(\n ({ action: historyAction, location, delta }) => {\n // Ignore this event if it was just us resetting the URL from a\n // blocked POP navigation\n if (unblockBlockerHistoryUpdate) {\n unblockBlockerHistoryUpdate();\n unblockBlockerHistoryUpdate = undefined;\n return;\n }\n\n warning(\n blockerFunctions.size === 0 || delta != null,\n \"You are trying to use a blocker on a POP navigation to a location \" +\n \"that was not created by @remix-run/router. This will fail silently in \" +\n \"production. This can happen if you are navigating outside the router \" +\n \"via `window.history.pushState`/`window.location.hash` instead of using \" +\n \"router navigation APIs. This can also happen if you are using \" +\n \"createHashRouter and the user manually changes the URL.\"\n );\n\n let blockerKey = shouldBlockNavigation({\n currentLocation: state.location,\n nextLocation: location,\n historyAction,\n });\n\n if (blockerKey && delta != null) {\n // Restore the URL to match the current UI, but don't update router state\n let nextHistoryUpdatePromise = new Promise((resolve) => {\n unblockBlockerHistoryUpdate = resolve;\n });\n init.history.go(delta * -1);\n\n // Put the blocker into a blocked state\n updateBlocker(blockerKey, {\n state: \"blocked\",\n location,\n proceed() {\n updateBlocker(blockerKey!, {\n state: \"proceeding\",\n proceed: undefined,\n reset: undefined,\n location,\n });\n // Re-do the same POP navigation we just blocked, after the url\n // restoration is also complete. See:\n // https://github.com/remix-run/react-router/issues/11613\n nextHistoryUpdatePromise.then(() => init.history.go(delta));\n },\n reset() {\n let blockers = new Map(state.blockers);\n blockers.set(blockerKey!, IDLE_BLOCKER);\n updateState({ blockers });\n },\n });\n return;\n }\n\n return startNavigation(historyAction, location);\n }\n );\n\n if (isBrowser) {\n // FIXME: This feels gross. How can we cleanup the lines between\n // scrollRestoration/appliedTransitions persistance?\n restoreAppliedTransitions(routerWindow, appliedViewTransitions);\n let _saveAppliedTransitions = () =>\n persistAppliedTransitions(routerWindow, appliedViewTransitions);\n routerWindow.addEventListener(\"pagehide\", _saveAppliedTransitions);\n removePageHideEventListener = () =>\n routerWindow.removeEventListener(\"pagehide\", _saveAppliedTransitions);\n }\n\n // Kick off initial data load if needed. Use Pop to avoid modifying history\n // Note we don't do any handling of lazy here. For SPA's it'll get handled\n // in the normal navigation flow. For SSR it's expected that lazy modules are\n // resolved prior to router creation since we can't go into a fallbackElement\n // UI for SSR'd apps\n if (!state.initialized) {\n startNavigation(HistoryAction.Pop, state.location, {\n initialHydration: true,\n });\n }\n\n return router;\n }\n\n // Clean up a router and it's side effects\n function dispose() {\n if (unlistenHistory) {\n unlistenHistory();\n }\n if (removePageHideEventListener) {\n removePageHideEventListener();\n }\n subscribers.clear();\n pendingNavigationController && pendingNavigationController.abort();\n state.fetchers.forEach((_, key) => deleteFetcher(key));\n state.blockers.forEach((_, key) => deleteBlocker(key));\n }\n\n // Subscribe to state updates for the router\n function subscribe(fn: RouterSubscriber) {\n subscribers.add(fn);\n return () => subscribers.delete(fn);\n }\n\n // Update our state and notify the calling context of the change\n function updateState(\n newState: Partial,\n opts: {\n flushSync?: boolean;\n viewTransitionOpts?: ViewTransitionOpts;\n } = {}\n ): void {\n state = {\n ...state,\n ...newState,\n };\n\n // Prep fetcher cleanup so we can tell the UI which fetcher data entries\n // can be removed\n let completedFetchers: string[] = [];\n let deletedFetchersKeys: string[] = [];\n\n if (future.v7_fetcherPersist) {\n state.fetchers.forEach((fetcher, key) => {\n if (fetcher.state === \"idle\") {\n if (deletedFetchers.has(key)) {\n // Unmounted from the UI and can be totally removed\n deletedFetchersKeys.push(key);\n } else {\n // Returned to idle but still mounted in the UI, so semi-remains for\n // revalidations and such\n completedFetchers.push(key);\n }\n }\n });\n }\n\n // Remove any lingering deleted fetchers that have already been removed\n // from state.fetchers\n deletedFetchers.forEach((key) => {\n if (!state.fetchers.has(key) && !fetchControllers.has(key)) {\n deletedFetchersKeys.push(key);\n }\n });\n\n // Iterate over a local copy so that if flushSync is used and we end up\n // removing and adding a new subscriber due to the useCallback dependencies,\n // we don't get ourselves into a loop calling the new subscriber immediately\n [...subscribers].forEach((subscriber) =>\n subscriber(state, {\n deletedFetchers: deletedFetchersKeys,\n viewTransitionOpts: opts.viewTransitionOpts,\n flushSync: opts.flushSync === true,\n })\n );\n\n // Remove idle fetchers from state since we only care about in-flight fetchers.\n if (future.v7_fetcherPersist) {\n completedFetchers.forEach((key) => state.fetchers.delete(key));\n deletedFetchersKeys.forEach((key) => deleteFetcher(key));\n } else {\n // We already called deleteFetcher() on these, can remove them from this\n // Set now that we've handed the keys off to the data layer\n deletedFetchersKeys.forEach((key) => deletedFetchers.delete(key));\n }\n }\n\n // Complete a navigation returning the state.navigation back to the IDLE_NAVIGATION\n // and setting state.[historyAction/location/matches] to the new route.\n // - Location is a required param\n // - Navigation will always be set to IDLE_NAVIGATION\n // - Can pass any other state in newState\n function completeNavigation(\n location: Location,\n newState: Partial>,\n { flushSync }: { flushSync?: boolean } = {}\n ): void {\n // Deduce if we're in a loading/actionReload state:\n // - We have committed actionData in the store\n // - The current navigation was a mutation submission\n // - We're past the submitting state and into the loading state\n // - The location being loaded is not the result of a redirect\n let isActionReload =\n state.actionData != null &&\n state.navigation.formMethod != null &&\n isMutationMethod(state.navigation.formMethod) &&\n state.navigation.state === \"loading\" &&\n location.state?._isRedirect !== true;\n\n let actionData: RouteData | null;\n if (newState.actionData) {\n if (Object.keys(newState.actionData).length > 0) {\n actionData = newState.actionData;\n } else {\n // Empty actionData -> clear prior actionData due to an action error\n actionData = null;\n }\n } else if (isActionReload) {\n // Keep the current data if we're wrapping up the action reload\n actionData = state.actionData;\n } else {\n // Clear actionData on any other completed navigations\n actionData = null;\n }\n\n // Always preserve any existing loaderData from re-used routes\n let loaderData = newState.loaderData\n ? mergeLoaderData(\n state.loaderData,\n newState.loaderData,\n newState.matches || [],\n newState.errors\n )\n : state.loaderData;\n\n // On a successful navigation we can assume we got through all blockers\n // so we can start fresh\n let blockers = state.blockers;\n if (blockers.size > 0) {\n blockers = new Map(blockers);\n blockers.forEach((_, k) => blockers.set(k, IDLE_BLOCKER));\n }\n\n // Always respect the user flag. Otherwise don't reset on mutation\n // submission navigations unless they redirect\n let preventScrollReset =\n pendingPreventScrollReset === true ||\n (state.navigation.formMethod != null &&\n isMutationMethod(state.navigation.formMethod) &&\n location.state?._isRedirect !== true);\n\n // Commit any in-flight routes at the end of the HMR revalidation \"navigation\"\n if (inFlightDataRoutes) {\n dataRoutes = inFlightDataRoutes;\n inFlightDataRoutes = undefined;\n }\n\n if (isUninterruptedRevalidation) {\n // If this was an uninterrupted revalidation then do not touch history\n } else if (pendingAction === HistoryAction.Pop) {\n // Do nothing for POP - URL has already been updated\n } else if (pendingAction === HistoryAction.Push) {\n init.history.push(location, location.state);\n } else if (pendingAction === HistoryAction.Replace) {\n init.history.replace(location, location.state);\n }\n\n let viewTransitionOpts: ViewTransitionOpts | undefined;\n\n // On POP, enable transitions if they were enabled on the original navigation\n if (pendingAction === HistoryAction.Pop) {\n // Forward takes precedence so they behave like the original navigation\n let priorPaths = appliedViewTransitions.get(state.location.pathname);\n if (priorPaths && priorPaths.has(location.pathname)) {\n viewTransitionOpts = {\n currentLocation: state.location,\n nextLocation: location,\n };\n } else if (appliedViewTransitions.has(location.pathname)) {\n // If we don't have a previous forward nav, assume we're popping back to\n // the new location and enable if that location previously enabled\n viewTransitionOpts = {\n currentLocation: location,\n nextLocation: state.location,\n };\n }\n } else if (pendingViewTransitionEnabled) {\n // Store the applied transition on PUSH/REPLACE\n let toPaths = appliedViewTransitions.get(state.location.pathname);\n if (toPaths) {\n toPaths.add(location.pathname);\n } else {\n toPaths = new Set([location.pathname]);\n appliedViewTransitions.set(state.location.pathname, toPaths);\n }\n viewTransitionOpts = {\n currentLocation: state.location,\n nextLocation: location,\n };\n }\n\n updateState(\n {\n ...newState, // matches, errors, fetchers go through as-is\n actionData,\n loaderData,\n historyAction: pendingAction,\n location,\n initialized: true,\n navigation: IDLE_NAVIGATION,\n revalidation: \"idle\",\n restoreScrollPosition: getSavedScrollPosition(\n location,\n newState.matches || state.matches\n ),\n preventScrollReset,\n blockers,\n },\n {\n viewTransitionOpts,\n flushSync: flushSync === true,\n }\n );\n\n // Reset stateful navigation vars\n pendingAction = HistoryAction.Pop;\n pendingPreventScrollReset = false;\n pendingViewTransitionEnabled = false;\n isUninterruptedRevalidation = false;\n isRevalidationRequired = false;\n cancelledDeferredRoutes = [];\n }\n\n // Trigger a navigation event, which can either be a numerical POP or a PUSH\n // replace with an optional submission\n async function navigate(\n to: number | To | null,\n opts?: RouterNavigateOptions\n ): Promise {\n if (typeof to === \"number\") {\n init.history.go(to);\n return;\n }\n\n let normalizedPath = normalizeTo(\n state.location,\n state.matches,\n basename,\n future.v7_prependBasename,\n to,\n future.v7_relativeSplatPath,\n opts?.fromRouteId,\n opts?.relative\n );\n let { path, submission, error } = normalizeNavigateOptions(\n future.v7_normalizeFormMethod,\n false,\n normalizedPath,\n opts\n );\n\n let currentLocation = state.location;\n let nextLocation = createLocation(state.location, path, opts && opts.state);\n\n // When using navigate as a PUSH/REPLACE we aren't reading an already-encoded\n // URL from window.location, so we need to encode it here so the behavior\n // remains the same as POP and non-data-router usages. new URL() does all\n // the same encoding we'd get from a history.pushState/window.location read\n // without having to touch history\n nextLocation = {\n ...nextLocation,\n ...init.history.encodeLocation(nextLocation),\n };\n\n let userReplace = opts && opts.replace != null ? opts.replace : undefined;\n\n let historyAction = HistoryAction.Push;\n\n if (userReplace === true) {\n historyAction = HistoryAction.Replace;\n } else if (userReplace === false) {\n // no-op\n } else if (\n submission != null &&\n isMutationMethod(submission.formMethod) &&\n submission.formAction === state.location.pathname + state.location.search\n ) {\n // By default on submissions to the current location we REPLACE so that\n // users don't have to double-click the back button to get to the prior\n // location. If the user redirects to a different location from the\n // action/loader this will be ignored and the redirect will be a PUSH\n historyAction = HistoryAction.Replace;\n }\n\n let preventScrollReset =\n opts && \"preventScrollReset\" in opts\n ? opts.preventScrollReset === true\n : undefined;\n\n let flushSync = (opts && opts.flushSync) === true;\n\n let blockerKey = shouldBlockNavigation({\n currentLocation,\n nextLocation,\n historyAction,\n });\n\n if (blockerKey) {\n // Put the blocker into a blocked state\n updateBlocker(blockerKey, {\n state: \"blocked\",\n location: nextLocation,\n proceed() {\n updateBlocker(blockerKey!, {\n state: \"proceeding\",\n proceed: undefined,\n reset: undefined,\n location: nextLocation,\n });\n // Send the same navigation through\n navigate(to, opts);\n },\n reset() {\n let blockers = new Map(state.blockers);\n blockers.set(blockerKey!, IDLE_BLOCKER);\n updateState({ blockers });\n },\n });\n return;\n }\n\n return await startNavigation(historyAction, nextLocation, {\n submission,\n // Send through the formData serialization error if we have one so we can\n // render at the right error boundary after we match routes\n pendingError: error,\n preventScrollReset,\n replace: opts && opts.replace,\n enableViewTransition: opts && opts.viewTransition,\n flushSync,\n });\n }\n\n // Revalidate all current loaders. If a navigation is in progress or if this\n // is interrupted by a navigation, allow this to \"succeed\" by calling all\n // loaders during the next loader round\n function revalidate() {\n interruptActiveLoads();\n updateState({ revalidation: \"loading\" });\n\n // If we're currently submitting an action, we don't need to start a new\n // navigation, we'll just let the follow up loader execution call all loaders\n if (state.navigation.state === \"submitting\") {\n return;\n }\n\n // If we're currently in an idle state, start a new navigation for the current\n // action/location and mark it as uninterrupted, which will skip the history\n // update in completeNavigation\n if (state.navigation.state === \"idle\") {\n startNavigation(state.historyAction, state.location, {\n startUninterruptedRevalidation: true,\n });\n return;\n }\n\n // Otherwise, if we're currently in a loading state, just start a new\n // navigation to the navigation.location but do not trigger an uninterrupted\n // revalidation so that history correctly updates once the navigation completes\n startNavigation(\n pendingAction || state.historyAction,\n state.navigation.location,\n {\n overrideNavigation: state.navigation,\n // Proxy through any rending view transition\n enableViewTransition: pendingViewTransitionEnabled === true,\n }\n );\n }\n\n // Start a navigation to the given action/location. Can optionally provide a\n // overrideNavigation which will override the normalLoad in the case of a redirect\n // navigation\n async function startNavigation(\n historyAction: HistoryAction,\n location: Location,\n opts?: {\n initialHydration?: boolean;\n submission?: Submission;\n fetcherSubmission?: Submission;\n overrideNavigation?: Navigation;\n pendingError?: ErrorResponseImpl;\n startUninterruptedRevalidation?: boolean;\n preventScrollReset?: boolean;\n replace?: boolean;\n enableViewTransition?: boolean;\n flushSync?: boolean;\n }\n ): Promise {\n // Abort any in-progress navigations and start a new one. Unset any ongoing\n // uninterrupted revalidations unless told otherwise, since we want this\n // new navigation to update history normally\n pendingNavigationController && pendingNavigationController.abort();\n pendingNavigationController = null;\n pendingAction = historyAction;\n isUninterruptedRevalidation =\n (opts && opts.startUninterruptedRevalidation) === true;\n\n // Save the current scroll position every time we start a new navigation,\n // and track whether we should reset scroll on completion\n saveScrollPosition(state.location, state.matches);\n pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;\n\n pendingViewTransitionEnabled = (opts && opts.enableViewTransition) === true;\n\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let loadingNavigation = opts && opts.overrideNavigation;\n let matches =\n opts?.initialHydration &&\n state.matches &&\n state.matches.length > 0 &&\n !initialMatchesIsFOW\n ? // `matchRoutes()` has already been called if we're in here via `router.initialize()`\n state.matches\n : matchRoutes(routesToUse, location, basename);\n let flushSync = (opts && opts.flushSync) === true;\n\n // Short circuit if it's only a hash change and not a revalidation or\n // mutation submission.\n //\n // Ignore on initial page loads because since the initial hydration will always\n // be \"same hash\". For example, on /page#hash and submit a \n // which will default to a navigation to /page\n if (\n matches &&\n state.initialized &&\n !isRevalidationRequired &&\n isHashChangeOnly(state.location, location) &&\n !(opts && opts.submission && isMutationMethod(opts.submission.formMethod))\n ) {\n completeNavigation(location, { matches }, { flushSync });\n return;\n }\n\n let fogOfWar = checkFogOfWar(matches, routesToUse, location.pathname);\n if (fogOfWar.active && fogOfWar.matches) {\n matches = fogOfWar.matches;\n }\n\n // Short circuit with a 404 on the root error boundary if we match nothing\n if (!matches) {\n let { error, notFoundMatches, route } = handleNavigational404(\n location.pathname\n );\n completeNavigation(\n location,\n {\n matches: notFoundMatches,\n loaderData: {},\n errors: {\n [route.id]: error,\n },\n },\n { flushSync }\n );\n return;\n }\n\n // Create a controller/Request for this navigation\n pendingNavigationController = new AbortController();\n let request = createClientSideRequest(\n init.history,\n location,\n pendingNavigationController.signal,\n opts && opts.submission\n );\n let pendingActionResult: PendingActionResult | undefined;\n\n if (opts && opts.pendingError) {\n // If we have a pendingError, it means the user attempted a GET submission\n // with binary FormData so assign here and skip to handleLoaders. That\n // way we handle calling loaders above the boundary etc. It's not really\n // different from an actionError in that sense.\n pendingActionResult = [\n findNearestBoundary(matches).route.id,\n { type: ResultType.error, error: opts.pendingError },\n ];\n } else if (\n opts &&\n opts.submission &&\n isMutationMethod(opts.submission.formMethod)\n ) {\n // Call action if we received an action submission\n let actionResult = await handleAction(\n request,\n location,\n opts.submission,\n matches,\n fogOfWar.active,\n { replace: opts.replace, flushSync }\n );\n\n if (actionResult.shortCircuited) {\n return;\n }\n\n // If we received a 404 from handleAction, it's because we couldn't lazily\n // discover the destination route so we don't want to call loaders\n if (actionResult.pendingActionResult) {\n let [routeId, result] = actionResult.pendingActionResult;\n if (\n isErrorResult(result) &&\n isRouteErrorResponse(result.error) &&\n result.error.status === 404\n ) {\n pendingNavigationController = null;\n\n completeNavigation(location, {\n matches: actionResult.matches,\n loaderData: {},\n errors: {\n [routeId]: result.error,\n },\n });\n return;\n }\n }\n\n matches = actionResult.matches || matches;\n pendingActionResult = actionResult.pendingActionResult;\n loadingNavigation = getLoadingNavigation(location, opts.submission);\n flushSync = false;\n // No need to do fog of war matching again on loader execution\n fogOfWar.active = false;\n\n // Create a GET request for the loaders\n request = createClientSideRequest(\n init.history,\n request.url,\n request.signal\n );\n }\n\n // Call loaders\n let {\n shortCircuited,\n matches: updatedMatches,\n loaderData,\n errors,\n } = await handleLoaders(\n request,\n location,\n matches,\n fogOfWar.active,\n loadingNavigation,\n opts && opts.submission,\n opts && opts.fetcherSubmission,\n opts && opts.replace,\n opts && opts.initialHydration === true,\n flushSync,\n pendingActionResult\n );\n\n if (shortCircuited) {\n return;\n }\n\n // Clean up now that the action/loaders have completed. Don't clean up if\n // we short circuited because pendingNavigationController will have already\n // been assigned to a new controller for the next navigation\n pendingNavigationController = null;\n\n completeNavigation(location, {\n matches: updatedMatches || matches,\n ...getActionDataForCommit(pendingActionResult),\n loaderData,\n errors,\n });\n }\n\n // Call the action matched by the leaf route for this navigation and handle\n // redirects/errors\n async function handleAction(\n request: Request,\n location: Location,\n submission: Submission,\n matches: AgnosticDataRouteMatch[],\n isFogOfWar: boolean,\n opts: { replace?: boolean; flushSync?: boolean } = {}\n ): Promise {\n interruptActiveLoads();\n\n // Put us in a submitting state\n let navigation = getSubmittingNavigation(location, submission);\n updateState({ navigation }, { flushSync: opts.flushSync === true });\n\n if (isFogOfWar) {\n let discoverResult = await discoverRoutes(\n matches,\n location.pathname,\n request.signal\n );\n if (discoverResult.type === \"aborted\") {\n return { shortCircuited: true };\n } else if (discoverResult.type === \"error\") {\n let boundaryId = findNearestBoundary(discoverResult.partialMatches)\n .route.id;\n return {\n matches: discoverResult.partialMatches,\n pendingActionResult: [\n boundaryId,\n {\n type: ResultType.error,\n error: discoverResult.error,\n },\n ],\n };\n } else if (!discoverResult.matches) {\n let { notFoundMatches, error, route } = handleNavigational404(\n location.pathname\n );\n return {\n matches: notFoundMatches,\n pendingActionResult: [\n route.id,\n {\n type: ResultType.error,\n error,\n },\n ],\n };\n } else {\n matches = discoverResult.matches;\n }\n }\n\n // Call our action and get the result\n let result: DataResult;\n let actionMatch = getTargetMatch(matches, location);\n\n if (!actionMatch.route.action && !actionMatch.route.lazy) {\n result = {\n type: ResultType.error,\n error: getInternalRouterError(405, {\n method: request.method,\n pathname: location.pathname,\n routeId: actionMatch.route.id,\n }),\n };\n } else {\n let results = await callDataStrategy(\n \"action\",\n state,\n request,\n [actionMatch],\n matches,\n null\n );\n result = results[actionMatch.route.id];\n\n if (request.signal.aborted) {\n return { shortCircuited: true };\n }\n }\n\n if (isRedirectResult(result)) {\n let replace: boolean;\n if (opts && opts.replace != null) {\n replace = opts.replace;\n } else {\n // If the user didn't explicity indicate replace behavior, replace if\n // we redirected to the exact same location we're currently at to avoid\n // double back-buttons\n let location = normalizeRedirectLocation(\n result.response.headers.get(\"Location\")!,\n new URL(request.url),\n basename,\n init.history,\n );\n replace = location === state.location.pathname + state.location.search;\n }\n await startRedirectNavigation(request, result, true, {\n submission,\n replace,\n });\n return { shortCircuited: true };\n }\n\n if (isDeferredResult(result)) {\n throw getInternalRouterError(400, { type: \"defer-action\" });\n }\n\n if (isErrorResult(result)) {\n // Store off the pending error - we use it to determine which loaders\n // to call and will commit it when we complete the navigation\n let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);\n\n // By default, all submissions to the current location are REPLACE\n // navigations, but if the action threw an error that'll be rendered in\n // an errorElement, we fall back to PUSH so that the user can use the\n // back button to get back to the pre-submission form location to try\n // again\n if ((opts && opts.replace) !== true) {\n pendingAction = HistoryAction.Push;\n }\n\n return {\n matches,\n pendingActionResult: [boundaryMatch.route.id, result],\n };\n }\n\n return {\n matches,\n pendingActionResult: [actionMatch.route.id, result],\n };\n }\n\n // Call all applicable loaders for the given matches, handling redirects,\n // errors, etc.\n async function handleLoaders(\n request: Request,\n location: Location,\n matches: AgnosticDataRouteMatch[],\n isFogOfWar: boolean,\n overrideNavigation?: Navigation,\n submission?: Submission,\n fetcherSubmission?: Submission,\n replace?: boolean,\n initialHydration?: boolean,\n flushSync?: boolean,\n pendingActionResult?: PendingActionResult\n ): Promise {\n // Figure out the right navigation we want to use for data loading\n let loadingNavigation =\n overrideNavigation || getLoadingNavigation(location, submission);\n\n // If this was a redirect from an action we don't have a \"submission\" but\n // we have it on the loading navigation so use that if available\n let activeSubmission =\n submission ||\n fetcherSubmission ||\n getSubmissionFromNavigation(loadingNavigation);\n\n // If this is an uninterrupted revalidation, we remain in our current idle\n // state. If not, we need to switch to our loading state and load data,\n // preserving any new action data or existing action data (in the case of\n // a revalidation interrupting an actionReload)\n // If we have partialHydration enabled, then don't update the state for the\n // initial data load since it's not a \"navigation\"\n let shouldUpdateNavigationState =\n !isUninterruptedRevalidation &&\n (!future.v7_partialHydration || !initialHydration);\n\n // When fog of war is enabled, we enter our `loading` state earlier so we\n // can discover new routes during the `loading` state. We skip this if\n // we've already run actions since we would have done our matching already.\n // If the children() function threw then, we want to proceed with the\n // partial matches it discovered.\n if (isFogOfWar) {\n if (shouldUpdateNavigationState) {\n let actionData = getUpdatedActionData(pendingActionResult);\n updateState(\n {\n navigation: loadingNavigation,\n ...(actionData !== undefined ? { actionData } : {}),\n },\n {\n flushSync,\n }\n );\n }\n\n let discoverResult = await discoverRoutes(\n matches,\n location.pathname,\n request.signal\n );\n\n if (discoverResult.type === \"aborted\") {\n return { shortCircuited: true };\n } else if (discoverResult.type === \"error\") {\n let boundaryId = findNearestBoundary(discoverResult.partialMatches)\n .route.id;\n return {\n matches: discoverResult.partialMatches,\n loaderData: {},\n errors: {\n [boundaryId]: discoverResult.error,\n },\n };\n } else if (!discoverResult.matches) {\n let { error, notFoundMatches, route } = handleNavigational404(\n location.pathname\n );\n return {\n matches: notFoundMatches,\n loaderData: {},\n errors: {\n [route.id]: error,\n },\n };\n } else {\n matches = discoverResult.matches;\n }\n }\n\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n init.history,\n state,\n matches,\n activeSubmission,\n location,\n future.v7_partialHydration && initialHydration === true,\n future.v7_skipActionErrorRevalidation,\n isRevalidationRequired,\n cancelledDeferredRoutes,\n cancelledFetcherLoads,\n deletedFetchers,\n fetchLoadMatches,\n fetchRedirectIds,\n routesToUse,\n basename,\n pendingActionResult\n );\n\n // Cancel pending deferreds for no-longer-matched routes or routes we're\n // about to reload. Note that if this is an action reload we would have\n // already cancelled all pending deferreds so this would be a no-op\n cancelActiveDeferreds(\n (routeId) =>\n !(matches && matches.some((m) => m.route.id === routeId)) ||\n (matchesToLoad && matchesToLoad.some((m) => m.route.id === routeId))\n );\n\n pendingNavigationLoadId = ++incrementingLoadId;\n\n // Short circuit if we have no loaders to run\n if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) {\n let updatedFetchers = markFetchRedirectsDone();\n completeNavigation(\n location,\n {\n matches,\n loaderData: {},\n // Commit pending error if we're short circuiting\n errors:\n pendingActionResult && isErrorResult(pendingActionResult[1])\n ? { [pendingActionResult[0]]: pendingActionResult[1].error }\n : null,\n ...getActionDataForCommit(pendingActionResult),\n ...(updatedFetchers ? { fetchers: new Map(state.fetchers) } : {}),\n },\n { flushSync }\n );\n return { shortCircuited: true };\n }\n\n if (shouldUpdateNavigationState) {\n let updates: Partial = {};\n if (!isFogOfWar) {\n // Only update navigation/actionNData if we didn't already do it above\n updates.navigation = loadingNavigation;\n let actionData = getUpdatedActionData(pendingActionResult);\n if (actionData !== undefined) {\n updates.actionData = actionData;\n }\n }\n if (revalidatingFetchers.length > 0) {\n updates.fetchers = getUpdatedRevalidatingFetchers(revalidatingFetchers);\n }\n updateState(updates, { flushSync });\n }\n\n revalidatingFetchers.forEach((rf) => {\n abortFetcher(rf.key);\n if (rf.controller) {\n // Fetchers use an independent AbortController so that aborting a fetcher\n // (via deleteFetcher) does not abort the triggering navigation that\n // triggered the revalidation\n fetchControllers.set(rf.key, rf.controller);\n }\n });\n\n // Proxy navigation abort through to revalidation fetchers\n let abortPendingFetchRevalidations = () =>\n revalidatingFetchers.forEach((f) => abortFetcher(f.key));\n if (pendingNavigationController) {\n pendingNavigationController.signal.addEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n }\n\n let { loaderResults, fetcherResults } =\n await callLoadersAndMaybeResolveData(\n state,\n matches,\n matchesToLoad,\n revalidatingFetchers,\n request\n );\n\n if (request.signal.aborted) {\n return { shortCircuited: true };\n }\n\n // Clean up _after_ loaders have completed. Don't clean up if we short\n // circuited because fetchControllers would have been aborted and\n // reassigned to new controllers for the next navigation\n if (pendingNavigationController) {\n pendingNavigationController.signal.removeEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n }\n\n revalidatingFetchers.forEach((rf) => fetchControllers.delete(rf.key));\n\n // If any loaders returned a redirect Response, start a new REPLACE navigation\n let redirect = findRedirect(loaderResults);\n if (redirect) {\n await startRedirectNavigation(request, redirect.result, true, {\n replace,\n });\n return { shortCircuited: true };\n }\n\n redirect = findRedirect(fetcherResults);\n if (redirect) {\n // If this redirect came from a fetcher make sure we mark it in\n // fetchRedirectIds so it doesn't get revalidated on the next set of\n // loader executions\n fetchRedirectIds.add(redirect.key);\n await startRedirectNavigation(request, redirect.result, true, {\n replace,\n });\n return { shortCircuited: true };\n }\n\n // Process and commit output from loaders\n let { loaderData, errors } = processLoaderData(\n state,\n matches,\n loaderResults,\n pendingActionResult,\n revalidatingFetchers,\n fetcherResults,\n activeDeferreds\n );\n\n // Wire up subscribers to update loaderData as promises settle\n activeDeferreds.forEach((deferredData, routeId) => {\n deferredData.subscribe((aborted) => {\n // Note: No need to updateState here since the TrackedPromise on\n // loaderData is stable across resolve/reject\n // Remove this instance if we were aborted or if promises have settled\n if (aborted || deferredData.done) {\n activeDeferreds.delete(routeId);\n }\n });\n });\n\n // Preserve SSR errors during partial hydration\n if (future.v7_partialHydration && initialHydration && state.errors) {\n errors = { ...state.errors, ...errors };\n }\n\n let updatedFetchers = markFetchRedirectsDone();\n let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId);\n let shouldUpdateFetchers =\n updatedFetchers || didAbortFetchLoads || revalidatingFetchers.length > 0;\n\n return {\n matches,\n loaderData,\n errors,\n ...(shouldUpdateFetchers ? { fetchers: new Map(state.fetchers) } : {}),\n };\n }\n\n function getUpdatedActionData(\n pendingActionResult: PendingActionResult | undefined\n ): Record | null | undefined {\n if (pendingActionResult && !isErrorResult(pendingActionResult[1])) {\n // This is cast to `any` currently because `RouteData`uses any and it\n // would be a breaking change to use any.\n // TODO: v7 - change `RouteData` to use `unknown` instead of `any`\n return {\n [pendingActionResult[0]]: pendingActionResult[1].data as any,\n };\n } else if (state.actionData) {\n if (Object.keys(state.actionData).length === 0) {\n return null;\n } else {\n return state.actionData;\n }\n }\n }\n\n function getUpdatedRevalidatingFetchers(\n revalidatingFetchers: RevalidatingFetcher[]\n ) {\n revalidatingFetchers.forEach((rf) => {\n let fetcher = state.fetchers.get(rf.key);\n let revalidatingFetcher = getLoadingFetcher(\n undefined,\n fetcher ? fetcher.data : undefined\n );\n state.fetchers.set(rf.key, revalidatingFetcher);\n });\n return new Map(state.fetchers);\n }\n\n // Trigger a fetcher load/submit for the given fetcher key\n function fetch(\n key: string,\n routeId: string,\n href: string | null,\n opts?: RouterFetchOptions\n ) {\n if (isServer) {\n throw new Error(\n \"router.fetch() was called during the server render, but it shouldn't be. \" +\n \"You are likely calling a useFetcher() method in the body of your component. \" +\n \"Try moving it to a useEffect or a callback.\"\n );\n }\n\n abortFetcher(key);\n\n let flushSync = (opts && opts.flushSync) === true;\n\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let normalizedPath = normalizeTo(\n state.location,\n state.matches,\n basename,\n future.v7_prependBasename,\n href,\n future.v7_relativeSplatPath,\n routeId,\n opts?.relative\n );\n let matches = matchRoutes(routesToUse, normalizedPath, basename);\n\n let fogOfWar = checkFogOfWar(matches, routesToUse, normalizedPath);\n if (fogOfWar.active && fogOfWar.matches) {\n matches = fogOfWar.matches;\n }\n\n if (!matches) {\n setFetcherError(\n key,\n routeId,\n getInternalRouterError(404, { pathname: normalizedPath }),\n { flushSync }\n );\n return;\n }\n\n let { path, submission, error } = normalizeNavigateOptions(\n future.v7_normalizeFormMethod,\n true,\n normalizedPath,\n opts\n );\n\n if (error) {\n setFetcherError(key, routeId, error, { flushSync });\n return;\n }\n\n let match = getTargetMatch(matches, path);\n\n let preventScrollReset = (opts && opts.preventScrollReset) === true;\n\n if (submission && isMutationMethod(submission.formMethod)) {\n handleFetcherAction(\n key,\n routeId,\n path,\n match,\n matches,\n fogOfWar.active,\n flushSync,\n preventScrollReset,\n submission\n );\n return;\n }\n\n // Store off the match so we can call it's shouldRevalidate on subsequent\n // revalidations\n fetchLoadMatches.set(key, { routeId, path });\n handleFetcherLoader(\n key,\n routeId,\n path,\n match,\n matches,\n fogOfWar.active,\n flushSync,\n preventScrollReset,\n submission\n );\n }\n\n // Call the action for the matched fetcher.submit(), and then handle redirects,\n // errors, and revalidation\n async function handleFetcherAction(\n key: string,\n routeId: string,\n path: string,\n match: AgnosticDataRouteMatch,\n requestMatches: AgnosticDataRouteMatch[],\n isFogOfWar: boolean,\n flushSync: boolean,\n preventScrollReset: boolean,\n submission: Submission\n ) {\n interruptActiveLoads();\n fetchLoadMatches.delete(key);\n\n function detectAndHandle405Error(m: AgnosticDataRouteMatch) {\n if (!m.route.action && !m.route.lazy) {\n let error = getInternalRouterError(405, {\n method: submission.formMethod,\n pathname: path,\n routeId: routeId,\n });\n setFetcherError(key, routeId, error, { flushSync });\n return true;\n }\n return false;\n }\n\n if (!isFogOfWar && detectAndHandle405Error(match)) {\n return;\n }\n\n // Put this fetcher into it's submitting state\n let existingFetcher = state.fetchers.get(key);\n updateFetcherState(key, getSubmittingFetcher(submission, existingFetcher), {\n flushSync,\n });\n\n let abortController = new AbortController();\n let fetchRequest = createClientSideRequest(\n init.history,\n path,\n abortController.signal,\n submission\n );\n\n if (isFogOfWar) {\n let discoverResult = await discoverRoutes(\n requestMatches,\n new URL(fetchRequest.url).pathname,\n fetchRequest.signal,\n key\n );\n\n if (discoverResult.type === \"aborted\") {\n return;\n } else if (discoverResult.type === \"error\") {\n setFetcherError(key, routeId, discoverResult.error, { flushSync });\n return;\n } else if (!discoverResult.matches) {\n setFetcherError(\n key,\n routeId,\n getInternalRouterError(404, { pathname: path }),\n { flushSync }\n );\n return;\n } else {\n requestMatches = discoverResult.matches;\n match = getTargetMatch(requestMatches, path);\n\n if (detectAndHandle405Error(match)) {\n return;\n }\n }\n }\n\n // Call the action for the fetcher\n fetchControllers.set(key, abortController);\n\n let originatingLoadId = incrementingLoadId;\n let actionResults = await callDataStrategy(\n \"action\",\n state,\n fetchRequest,\n [match],\n requestMatches,\n key\n );\n let actionResult = actionResults[match.route.id];\n\n if (fetchRequest.signal.aborted) {\n // We can delete this so long as we weren't aborted by our own fetcher\n // re-submit which would have put _new_ controller is in fetchControllers\n if (fetchControllers.get(key) === abortController) {\n fetchControllers.delete(key);\n }\n return;\n }\n\n // When using v7_fetcherPersist, we don't want errors bubbling up to the UI\n // or redirects processed for unmounted fetchers so we just revert them to\n // idle\n if (future.v7_fetcherPersist && deletedFetchers.has(key)) {\n if (isRedirectResult(actionResult) || isErrorResult(actionResult)) {\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n }\n // Let SuccessResult's fall through for revalidation\n } else {\n if (isRedirectResult(actionResult)) {\n fetchControllers.delete(key);\n if (pendingNavigationLoadId > originatingLoadId) {\n // A new navigation was kicked off after our action started, so that\n // should take precedence over this redirect navigation. We already\n // set isRevalidationRequired so all loaders for the new route should\n // fire unless opted out via shouldRevalidate\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n } else {\n fetchRedirectIds.add(key);\n updateFetcherState(key, getLoadingFetcher(submission));\n return startRedirectNavigation(fetchRequest, actionResult, false, {\n fetcherSubmission: submission,\n preventScrollReset,\n });\n }\n }\n\n // Process any non-redirect errors thrown\n if (isErrorResult(actionResult)) {\n setFetcherError(key, routeId, actionResult.error);\n return;\n }\n }\n\n if (isDeferredResult(actionResult)) {\n throw getInternalRouterError(400, { type: \"defer-action\" });\n }\n\n // Start the data load for current matches, or the next location if we're\n // in the middle of a navigation\n let nextLocation = state.navigation.location || state.location;\n let revalidationRequest = createClientSideRequest(\n init.history,\n nextLocation,\n abortController.signal\n );\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let matches =\n state.navigation.state !== \"idle\"\n ? matchRoutes(routesToUse, state.navigation.location, basename)\n : state.matches;\n\n invariant(matches, \"Didn't find any matches after fetcher action\");\n\n let loadId = ++incrementingLoadId;\n fetchReloadIds.set(key, loadId);\n\n let loadFetcher = getLoadingFetcher(submission, actionResult.data);\n state.fetchers.set(key, loadFetcher);\n\n let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n init.history,\n state,\n matches,\n submission,\n nextLocation,\n false,\n future.v7_skipActionErrorRevalidation,\n isRevalidationRequired,\n cancelledDeferredRoutes,\n cancelledFetcherLoads,\n deletedFetchers,\n fetchLoadMatches,\n fetchRedirectIds,\n routesToUse,\n basename,\n [match.route.id, actionResult]\n );\n\n // Put all revalidating fetchers into the loading state, except for the\n // current fetcher which we want to keep in it's current loading state which\n // contains it's action submission info + action data\n revalidatingFetchers\n .filter((rf) => rf.key !== key)\n .forEach((rf) => {\n let staleKey = rf.key;\n let existingFetcher = state.fetchers.get(staleKey);\n let revalidatingFetcher = getLoadingFetcher(\n undefined,\n existingFetcher ? existingFetcher.data : undefined\n );\n state.fetchers.set(staleKey, revalidatingFetcher);\n abortFetcher(staleKey);\n if (rf.controller) {\n fetchControllers.set(staleKey, rf.controller);\n }\n });\n\n updateState({ fetchers: new Map(state.fetchers) });\n\n let abortPendingFetchRevalidations = () =>\n revalidatingFetchers.forEach((rf) => abortFetcher(rf.key));\n\n abortController.signal.addEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n\n let { loaderResults, fetcherResults } =\n await callLoadersAndMaybeResolveData(\n state,\n matches,\n matchesToLoad,\n revalidatingFetchers,\n revalidationRequest\n );\n\n if (abortController.signal.aborted) {\n return;\n }\n\n abortController.signal.removeEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n\n fetchReloadIds.delete(key);\n fetchControllers.delete(key);\n revalidatingFetchers.forEach((r) => fetchControllers.delete(r.key));\n\n let redirect = findRedirect(loaderResults);\n if (redirect) {\n return startRedirectNavigation(\n revalidationRequest,\n redirect.result,\n false,\n { preventScrollReset }\n );\n }\n\n redirect = findRedirect(fetcherResults);\n if (redirect) {\n // If this redirect came from a fetcher make sure we mark it in\n // fetchRedirectIds so it doesn't get revalidated on the next set of\n // loader executions\n fetchRedirectIds.add(redirect.key);\n return startRedirectNavigation(\n revalidationRequest,\n redirect.result,\n false,\n { preventScrollReset }\n );\n }\n\n // Process and commit output from loaders\n let { loaderData, errors } = processLoaderData(\n state,\n matches,\n loaderResults,\n undefined,\n revalidatingFetchers,\n fetcherResults,\n activeDeferreds\n );\n\n // Since we let revalidations complete even if the submitting fetcher was\n // deleted, only put it back to idle if it hasn't been deleted\n if (state.fetchers.has(key)) {\n let doneFetcher = getDoneFetcher(actionResult.data);\n state.fetchers.set(key, doneFetcher);\n }\n\n abortStaleFetchLoads(loadId);\n\n // If we are currently in a navigation loading state and this fetcher is\n // more recent than the navigation, we want the newer data so abort the\n // navigation and complete it with the fetcher data\n if (\n state.navigation.state === \"loading\" &&\n loadId > pendingNavigationLoadId\n ) {\n invariant(pendingAction, \"Expected pending action\");\n pendingNavigationController && pendingNavigationController.abort();\n\n completeNavigation(state.navigation.location, {\n matches,\n loaderData,\n errors,\n fetchers: new Map(state.fetchers),\n });\n } else {\n // otherwise just update with the fetcher data, preserving any existing\n // loaderData for loaders that did not need to reload. We have to\n // manually merge here since we aren't going through completeNavigation\n updateState({\n errors,\n loaderData: mergeLoaderData(\n state.loaderData,\n loaderData,\n matches,\n errors\n ),\n fetchers: new Map(state.fetchers),\n });\n isRevalidationRequired = false;\n }\n }\n\n // Call the matched loader for fetcher.load(), handling redirects, errors, etc.\n async function handleFetcherLoader(\n key: string,\n routeId: string,\n path: string,\n match: AgnosticDataRouteMatch,\n matches: AgnosticDataRouteMatch[],\n isFogOfWar: boolean,\n flushSync: boolean,\n preventScrollReset: boolean,\n submission?: Submission\n ) {\n let existingFetcher = state.fetchers.get(key);\n updateFetcherState(\n key,\n getLoadingFetcher(\n submission,\n existingFetcher ? existingFetcher.data : undefined\n ),\n { flushSync }\n );\n\n let abortController = new AbortController();\n let fetchRequest = createClientSideRequest(\n init.history,\n path,\n abortController.signal\n );\n\n if (isFogOfWar) {\n let discoverResult = await discoverRoutes(\n matches,\n new URL(fetchRequest.url).pathname,\n fetchRequest.signal,\n key\n );\n\n if (discoverResult.type === \"aborted\") {\n return;\n } else if (discoverResult.type === \"error\") {\n setFetcherError(key, routeId, discoverResult.error, { flushSync });\n return;\n } else if (!discoverResult.matches) {\n setFetcherError(\n key,\n routeId,\n getInternalRouterError(404, { pathname: path }),\n { flushSync }\n );\n return;\n } else {\n matches = discoverResult.matches;\n match = getTargetMatch(matches, path);\n }\n }\n\n // Call the loader for this fetcher route match\n fetchControllers.set(key, abortController);\n\n let originatingLoadId = incrementingLoadId;\n let results = await callDataStrategy(\n \"loader\",\n state,\n fetchRequest,\n [match],\n matches,\n key\n );\n let result = results[match.route.id];\n\n // Deferred isn't supported for fetcher loads, await everything and treat it\n // as a normal load. resolveDeferredData will return undefined if this\n // fetcher gets aborted, so we just leave result untouched and short circuit\n // below if that happens\n if (isDeferredResult(result)) {\n result =\n (await resolveDeferredData(result, fetchRequest.signal, true)) ||\n result;\n }\n\n // We can delete this so long as we weren't aborted by our our own fetcher\n // re-load which would have put _new_ controller is in fetchControllers\n if (fetchControllers.get(key) === abortController) {\n fetchControllers.delete(key);\n }\n\n if (fetchRequest.signal.aborted) {\n return;\n }\n\n // We don't want errors bubbling up or redirects followed for unmounted\n // fetchers, so short circuit here if it was removed from the UI\n if (deletedFetchers.has(key)) {\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n }\n\n // If the loader threw a redirect Response, start a new REPLACE navigation\n if (isRedirectResult(result)) {\n if (pendingNavigationLoadId > originatingLoadId) {\n // A new navigation was kicked off after our loader started, so that\n // should take precedence over this redirect navigation\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n } else {\n fetchRedirectIds.add(key);\n await startRedirectNavigation(fetchRequest, result, false, {\n preventScrollReset,\n });\n return;\n }\n }\n\n // Process any non-redirect errors thrown\n if (isErrorResult(result)) {\n setFetcherError(key, routeId, result.error);\n return;\n }\n\n invariant(!isDeferredResult(result), \"Unhandled fetcher deferred data\");\n\n // Put the fetcher back into an idle state\n updateFetcherState(key, getDoneFetcher(result.data));\n }\n\n /**\n * Utility function to handle redirects returned from an action or loader.\n * Normally, a redirect \"replaces\" the navigation that triggered it. So, for\n * example:\n *\n * - user is on /a\n * - user clicks a link to /b\n * - loader for /b redirects to /c\n *\n * In a non-JS app the browser would track the in-flight navigation to /b and\n * then replace it with /c when it encountered the redirect response. In\n * the end it would only ever update the URL bar with /c.\n *\n * In client-side routing using pushState/replaceState, we aim to emulate\n * this behavior and we also do not update history until the end of the\n * navigation (including processed redirects). This means that we never\n * actually touch history until we've processed redirects, so we just use\n * the history action from the original navigation (PUSH or REPLACE).\n */\n async function startRedirectNavigation(\n request: Request,\n redirect: RedirectResult,\n isNavigation: boolean,\n {\n submission,\n fetcherSubmission,\n preventScrollReset,\n replace,\n }: {\n submission?: Submission;\n fetcherSubmission?: Submission;\n preventScrollReset?: boolean;\n replace?: boolean;\n } = {}\n ) {\n if (redirect.response.headers.has(\"X-Remix-Revalidate\")) {\n isRevalidationRequired = true;\n }\n\n let location = redirect.response.headers.get(\"Location\");\n invariant(location, \"Expected a Location header on the redirect Response\");\n location = normalizeRedirectLocation(\n location,\n new URL(request.url),\n basename,\n init.history,\n );\n let redirectLocation = createLocation(state.location, location, {\n _isRedirect: true,\n });\n\n if (isBrowser) {\n let isDocumentReload = false;\n\n if (redirect.response.headers.has(\"X-Remix-Reload-Document\")) {\n // Hard reload if the response contained X-Remix-Reload-Document\n isDocumentReload = true;\n } else if (ABSOLUTE_URL_REGEX.test(location)) {\n const url = init.history.createURL(location);\n isDocumentReload =\n // Hard reload if it's an absolute URL to a new origin\n url.origin !== routerWindow.location.origin ||\n // Hard reload if it's an absolute URL that does not match our basename\n stripBasename(url.pathname, basename) == null;\n }\n\n if (isDocumentReload) {\n if (replace) {\n routerWindow.location.replace(location);\n } else {\n routerWindow.location.assign(location);\n }\n return;\n }\n }\n\n // There's no need to abort on redirects, since we don't detect the\n // redirect until the action/loaders have settled\n pendingNavigationController = null;\n\n let redirectHistoryAction =\n replace === true || redirect.response.headers.has(\"X-Remix-Replace\")\n ? HistoryAction.Replace\n : HistoryAction.Push;\n\n // Use the incoming submission if provided, fallback on the active one in\n // state.navigation\n let { formMethod, formAction, formEncType } = state.navigation;\n if (\n !submission &&\n !fetcherSubmission &&\n formMethod &&\n formAction &&\n formEncType\n ) {\n submission = getSubmissionFromNavigation(state.navigation);\n }\n\n // If this was a 307/308 submission we want to preserve the HTTP method and\n // re-submit the GET/POST/PUT/PATCH/DELETE as a submission navigation to the\n // redirected location\n let activeSubmission = submission || fetcherSubmission;\n if (\n redirectPreserveMethodStatusCodes.has(redirect.response.status) &&\n activeSubmission &&\n isMutationMethod(activeSubmission.formMethod)\n ) {\n await startNavigation(redirectHistoryAction, redirectLocation, {\n submission: {\n ...activeSubmission,\n formAction: location,\n },\n // Preserve these flags across redirects\n preventScrollReset: preventScrollReset || pendingPreventScrollReset,\n enableViewTransition: isNavigation\n ? pendingViewTransitionEnabled\n : undefined,\n });\n } else {\n // If we have a navigation submission, we will preserve it through the\n // redirect navigation\n let overrideNavigation = getLoadingNavigation(\n redirectLocation,\n submission\n );\n await startNavigation(redirectHistoryAction, redirectLocation, {\n overrideNavigation,\n // Send fetcher submissions through for shouldRevalidate\n fetcherSubmission,\n // Preserve these flags across redirects\n preventScrollReset: preventScrollReset || pendingPreventScrollReset,\n enableViewTransition: isNavigation\n ? pendingViewTransitionEnabled\n : undefined,\n });\n }\n }\n\n // Utility wrapper for calling dataStrategy client-side without having to\n // pass around the manifest, mapRouteProperties, etc.\n async function callDataStrategy(\n type: \"loader\" | \"action\",\n state: RouterState,\n request: Request,\n matchesToLoad: AgnosticDataRouteMatch[],\n matches: AgnosticDataRouteMatch[],\n fetcherKey: string | null\n ): Promise> {\n let results: Record;\n let dataResults: Record = {};\n try {\n results = await callDataStrategyImpl(\n dataStrategyImpl,\n type,\n state,\n request,\n matchesToLoad,\n matches,\n fetcherKey,\n manifest,\n mapRouteProperties\n );\n } catch (e) {\n // If the outer dataStrategy method throws, just return the error for all\n // matches - and it'll naturally bubble to the root\n matchesToLoad.forEach((m) => {\n dataResults[m.route.id] = {\n type: ResultType.error,\n error: e,\n };\n });\n return dataResults;\n }\n\n for (let [routeId, result] of Object.entries(results)) {\n if (isRedirectDataStrategyResultResult(result)) {\n let response = result.result as Response;\n dataResults[routeId] = {\n type: ResultType.redirect,\n response: normalizeRelativeRoutingRedirectResponse(\n response,\n request,\n routeId,\n matches,\n basename,\n future.v7_relativeSplatPath\n ),\n };\n } else {\n dataResults[routeId] = await convertDataStrategyResultToDataResult(\n result\n );\n }\n }\n\n return dataResults;\n }\n\n async function callLoadersAndMaybeResolveData(\n state: RouterState,\n matches: AgnosticDataRouteMatch[],\n matchesToLoad: AgnosticDataRouteMatch[],\n fetchersToLoad: RevalidatingFetcher[],\n request: Request\n ) {\n let currentMatches = state.matches;\n\n // Kick off loaders and fetchers in parallel\n let loaderResultsPromise = callDataStrategy(\n \"loader\",\n state,\n request,\n matchesToLoad,\n matches,\n null\n );\n\n let fetcherResultsPromise = Promise.all(\n fetchersToLoad.map(async (f) => {\n if (f.matches && f.match && f.controller) {\n let results = await callDataStrategy(\n \"loader\",\n state,\n createClientSideRequest(init.history, f.path, f.controller.signal),\n [f.match],\n f.matches,\n f.key\n );\n let result = results[f.match.route.id];\n // Fetcher results are keyed by fetcher key from here on out, not routeId\n return { [f.key]: result };\n } else {\n return Promise.resolve({\n [f.key]: {\n type: ResultType.error,\n error: getInternalRouterError(404, {\n pathname: f.path,\n }),\n } as ErrorResult,\n });\n }\n })\n );\n\n let loaderResults = await loaderResultsPromise;\n let fetcherResults = (await fetcherResultsPromise).reduce(\n (acc, r) => Object.assign(acc, r),\n {}\n );\n\n await Promise.all([\n resolveNavigationDeferredResults(\n matches,\n loaderResults,\n request.signal,\n currentMatches,\n state.loaderData\n ),\n resolveFetcherDeferredResults(matches, fetcherResults, fetchersToLoad),\n ]);\n\n return {\n loaderResults,\n fetcherResults,\n };\n }\n\n function interruptActiveLoads() {\n // Every interruption triggers a revalidation\n isRevalidationRequired = true;\n\n // Cancel pending route-level deferreds and mark cancelled routes for\n // revalidation\n cancelledDeferredRoutes.push(...cancelActiveDeferreds());\n\n // Abort in-flight fetcher loads\n fetchLoadMatches.forEach((_, key) => {\n if (fetchControllers.has(key)) {\n cancelledFetcherLoads.add(key);\n }\n abortFetcher(key);\n });\n }\n\n function updateFetcherState(\n key: string,\n fetcher: Fetcher,\n opts: { flushSync?: boolean } = {}\n ) {\n state.fetchers.set(key, fetcher);\n updateState(\n { fetchers: new Map(state.fetchers) },\n { flushSync: (opts && opts.flushSync) === true }\n );\n }\n\n function setFetcherError(\n key: string,\n routeId: string,\n error: any,\n opts: { flushSync?: boolean } = {}\n ) {\n let boundaryMatch = findNearestBoundary(state.matches, routeId);\n deleteFetcher(key);\n updateState(\n {\n errors: {\n [boundaryMatch.route.id]: error,\n },\n fetchers: new Map(state.fetchers),\n },\n { flushSync: (opts && opts.flushSync) === true }\n );\n }\n\n function getFetcher(key: string): Fetcher {\n activeFetchers.set(key, (activeFetchers.get(key) || 0) + 1);\n // If this fetcher was previously marked for deletion, unmark it since we\n // have a new instance\n if (deletedFetchers.has(key)) {\n deletedFetchers.delete(key);\n }\n return state.fetchers.get(key) || IDLE_FETCHER;\n }\n\n function deleteFetcher(key: string): void {\n let fetcher = state.fetchers.get(key);\n // Don't abort the controller if this is a deletion of a fetcher.submit()\n // in it's loading phase since - we don't want to abort the corresponding\n // revalidation and want them to complete and land\n if (\n fetchControllers.has(key) &&\n !(fetcher && fetcher.state === \"loading\" && fetchReloadIds.has(key))\n ) {\n abortFetcher(key);\n }\n fetchLoadMatches.delete(key);\n fetchReloadIds.delete(key);\n fetchRedirectIds.delete(key);\n\n // If we opted into the flag we can clear this now since we're calling\n // deleteFetcher() at the end of updateState() and we've already handed the\n // deleted fetcher keys off to the data layer.\n // If not, we're eagerly calling deleteFetcher() and we need to keep this\n // Set populated until the next updateState call, and we'll clear\n // `deletedFetchers` then\n if (future.v7_fetcherPersist) {\n deletedFetchers.delete(key);\n }\n\n cancelledFetcherLoads.delete(key);\n state.fetchers.delete(key);\n }\n\n function deleteFetcherAndUpdateState(key: string): void {\n let count = (activeFetchers.get(key) || 0) - 1;\n if (count <= 0) {\n activeFetchers.delete(key);\n deletedFetchers.add(key);\n if (!future.v7_fetcherPersist) {\n deleteFetcher(key);\n }\n } else {\n activeFetchers.set(key, count);\n }\n\n updateState({ fetchers: new Map(state.fetchers) });\n }\n\n function abortFetcher(key: string) {\n let controller = fetchControllers.get(key);\n if (controller) {\n controller.abort();\n fetchControllers.delete(key);\n }\n }\n\n function markFetchersDone(keys: string[]) {\n for (let key of keys) {\n let fetcher = getFetcher(key);\n let doneFetcher = getDoneFetcher(fetcher.data);\n state.fetchers.set(key, doneFetcher);\n }\n }\n\n function markFetchRedirectsDone(): boolean {\n let doneKeys = [];\n let updatedFetchers = false;\n for (let key of fetchRedirectIds) {\n let fetcher = state.fetchers.get(key);\n invariant(fetcher, `Expected fetcher: ${key}`);\n if (fetcher.state === \"loading\") {\n fetchRedirectIds.delete(key);\n doneKeys.push(key);\n updatedFetchers = true;\n }\n }\n markFetchersDone(doneKeys);\n return updatedFetchers;\n }\n\n function abortStaleFetchLoads(landedId: number): boolean {\n let yeetedKeys = [];\n for (let [key, id] of fetchReloadIds) {\n if (id < landedId) {\n let fetcher = state.fetchers.get(key);\n invariant(fetcher, `Expected fetcher: ${key}`);\n if (fetcher.state === \"loading\") {\n abortFetcher(key);\n fetchReloadIds.delete(key);\n yeetedKeys.push(key);\n }\n }\n }\n markFetchersDone(yeetedKeys);\n return yeetedKeys.length > 0;\n }\n\n function getBlocker(key: string, fn: BlockerFunction) {\n let blocker: Blocker = state.blockers.get(key) || IDLE_BLOCKER;\n\n if (blockerFunctions.get(key) !== fn) {\n blockerFunctions.set(key, fn);\n }\n\n return blocker;\n }\n\n function deleteBlocker(key: string) {\n state.blockers.delete(key);\n blockerFunctions.delete(key);\n }\n\n // Utility function to update blockers, ensuring valid state transitions\n function updateBlocker(key: string, newBlocker: Blocker) {\n let blocker = state.blockers.get(key) || IDLE_BLOCKER;\n\n // Poor mans state machine :)\n // https://mermaid.live/edit#pako:eNqVkc9OwzAMxl8l8nnjAYrEtDIOHEBIgwvKJTReGy3_lDpIqO27k6awMG0XcrLlnz87nwdonESogKXXBuE79rq75XZO3-yHds0RJVuv70YrPlUrCEe2HfrORS3rubqZfuhtpg5C9wk5tZ4VKcRUq88q9Z8RS0-48cE1iHJkL0ugbHuFLus9L6spZy8nX9MP2CNdomVaposqu3fGayT8T8-jJQwhepo_UtpgBQaDEUom04dZhAN1aJBDlUKJBxE1ceB2Smj0Mln-IBW5AFU2dwUiktt_2Qaq2dBfaKdEup85UV7Yd-dKjlnkabl2Pvr0DTkTreM\n invariant(\n (blocker.state === \"unblocked\" && newBlocker.state === \"blocked\") ||\n (blocker.state === \"blocked\" && newBlocker.state === \"blocked\") ||\n (blocker.state === \"blocked\" && newBlocker.state === \"proceeding\") ||\n (blocker.state === \"blocked\" && newBlocker.state === \"unblocked\") ||\n (blocker.state === \"proceeding\" && newBlocker.state === \"unblocked\"),\n `Invalid blocker state transition: ${blocker.state} -> ${newBlocker.state}`\n );\n\n let blockers = new Map(state.blockers);\n blockers.set(key, newBlocker);\n updateState({ blockers });\n }\n\n function shouldBlockNavigation({\n currentLocation,\n nextLocation,\n historyAction,\n }: {\n currentLocation: Location;\n nextLocation: Location;\n historyAction: HistoryAction;\n }): string | undefined {\n if (blockerFunctions.size === 0) {\n return;\n }\n\n // We ony support a single active blocker at the moment since we don't have\n // any compelling use cases for multi-blocker yet\n if (blockerFunctions.size > 1) {\n warning(false, \"A router only supports one blocker at a time\");\n }\n\n let entries = Array.from(blockerFunctions.entries());\n let [blockerKey, blockerFunction] = entries[entries.length - 1];\n let blocker = state.blockers.get(blockerKey);\n\n if (blocker && blocker.state === \"proceeding\") {\n // If the blocker is currently proceeding, we don't need to re-check\n // it and can let this navigation continue\n return;\n }\n\n // At this point, we know we're unblocked/blocked so we need to check the\n // user-provided blocker function\n if (blockerFunction({ currentLocation, nextLocation, historyAction })) {\n return blockerKey;\n }\n }\n\n function handleNavigational404(pathname: string) {\n let error = getInternalRouterError(404, { pathname });\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let { matches, route } = getShortCircuitMatches(routesToUse);\n\n // Cancel all pending deferred on 404s since we don't keep any routes\n cancelActiveDeferreds();\n\n return { notFoundMatches: matches, route, error };\n }\n\n function cancelActiveDeferreds(\n predicate?: (routeId: string) => boolean\n ): string[] {\n let cancelledRouteIds: string[] = [];\n activeDeferreds.forEach((dfd, routeId) => {\n if (!predicate || predicate(routeId)) {\n // Cancel the deferred - but do not remove from activeDeferreds here -\n // we rely on the subscribers to do that so our tests can assert proper\n // cleanup via _internalActiveDeferreds\n dfd.cancel();\n cancelledRouteIds.push(routeId);\n activeDeferreds.delete(routeId);\n }\n });\n return cancelledRouteIds;\n }\n\n // Opt in to capturing and reporting scroll positions during navigations,\n // used by the component\n function enableScrollRestoration(\n positions: Record,\n getPosition: GetScrollPositionFunction,\n getKey?: GetScrollRestorationKeyFunction\n ) {\n savedScrollPositions = positions;\n getScrollPosition = getPosition;\n getScrollRestorationKey = getKey || null;\n\n // Perform initial hydration scroll restoration, since we miss the boat on\n // the initial updateState() because we've not yet rendered \n // and therefore have no savedScrollPositions available\n if (!initialScrollRestored && state.navigation === IDLE_NAVIGATION) {\n initialScrollRestored = true;\n let y = getSavedScrollPosition(state.location, state.matches);\n if (y != null) {\n updateState({ restoreScrollPosition: y });\n }\n }\n\n return () => {\n savedScrollPositions = null;\n getScrollPosition = null;\n getScrollRestorationKey = null;\n };\n }\n\n function getScrollKey(location: Location, matches: AgnosticDataRouteMatch[]) {\n if (getScrollRestorationKey) {\n let key = getScrollRestorationKey(\n location,\n matches.map((m) => convertRouteMatchToUiMatch(m, state.loaderData))\n );\n return key || location.key;\n }\n return location.key;\n }\n\n function saveScrollPosition(\n location: Location,\n matches: AgnosticDataRouteMatch[]\n ): void {\n if (savedScrollPositions && getScrollPosition) {\n let key = getScrollKey(location, matches);\n savedScrollPositions[key] = getScrollPosition();\n }\n }\n\n function getSavedScrollPosition(\n location: Location,\n matches: AgnosticDataRouteMatch[]\n ): number | null {\n if (savedScrollPositions) {\n let key = getScrollKey(location, matches);\n let y = savedScrollPositions[key];\n if (typeof y === \"number\") {\n return y;\n }\n }\n return null;\n }\n\n function checkFogOfWar(\n matches: AgnosticDataRouteMatch[] | null,\n routesToUse: AgnosticDataRouteObject[],\n pathname: string\n ): { active: boolean; matches: AgnosticDataRouteMatch[] | null } {\n if (patchRoutesOnNavigationImpl) {\n if (!matches) {\n let fogMatches = matchRoutesImpl(\n routesToUse,\n pathname,\n basename,\n true\n );\n\n return { active: true, matches: fogMatches || [] };\n } else {\n if (Object.keys(matches[0].params).length > 0) {\n // If we matched a dynamic param or a splat, it might only be because\n // we haven't yet discovered other routes that would match with a\n // higher score. Call patchRoutesOnNavigation just to be sure\n let partialMatches = matchRoutesImpl(\n routesToUse,\n pathname,\n basename,\n true\n );\n return { active: true, matches: partialMatches };\n }\n }\n }\n\n return { active: false, matches: null };\n }\n\n type DiscoverRoutesSuccessResult = {\n type: \"success\";\n matches: AgnosticDataRouteMatch[] | null;\n };\n type DiscoverRoutesErrorResult = {\n type: \"error\";\n error: any;\n partialMatches: AgnosticDataRouteMatch[];\n };\n type DiscoverRoutesAbortedResult = { type: \"aborted\" };\n type DiscoverRoutesResult =\n | DiscoverRoutesSuccessResult\n | DiscoverRoutesErrorResult\n | DiscoverRoutesAbortedResult;\n\n async function discoverRoutes(\n matches: AgnosticDataRouteMatch[],\n pathname: string,\n signal: AbortSignal,\n fetcherKey?: string\n ): Promise {\n if (!patchRoutesOnNavigationImpl) {\n return { type: \"success\", matches };\n }\n\n let partialMatches: AgnosticDataRouteMatch[] | null = matches;\n while (true) {\n let isNonHMR = inFlightDataRoutes == null;\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let localManifest = manifest;\n try {\n await patchRoutesOnNavigationImpl({\n signal,\n path: pathname,\n matches: partialMatches,\n fetcherKey,\n patch: (routeId, children) => {\n if (signal.aborted) return;\n patchRoutesImpl(\n routeId,\n children,\n routesToUse,\n localManifest,\n mapRouteProperties\n );\n },\n });\n } catch (e) {\n return { type: \"error\", error: e, partialMatches };\n } finally {\n // If we are not in the middle of an HMR revalidation and we changed the\n // routes, provide a new identity so when we `updateState` at the end of\n // this navigation/fetch `router.routes` will be a new identity and\n // trigger a re-run of memoized `router.routes` dependencies.\n // HMR will already update the identity and reflow when it lands\n // `inFlightDataRoutes` in `completeNavigation`\n if (isNonHMR && !signal.aborted) {\n dataRoutes = [...dataRoutes];\n }\n }\n\n if (signal.aborted) {\n return { type: \"aborted\" };\n }\n\n let newMatches = matchRoutes(routesToUse, pathname, basename);\n if (newMatches) {\n return { type: \"success\", matches: newMatches };\n }\n\n let newPartialMatches = matchRoutesImpl(\n routesToUse,\n pathname,\n basename,\n true\n );\n\n // Avoid loops if the second pass results in the same partial matches\n if (\n !newPartialMatches ||\n (partialMatches.length === newPartialMatches.length &&\n partialMatches.every(\n (m, i) => m.route.id === newPartialMatches![i].route.id\n ))\n ) {\n return { type: \"success\", matches: null };\n }\n\n partialMatches = newPartialMatches;\n }\n }\n\n function _internalSetRoutes(newRoutes: AgnosticDataRouteObject[]) {\n manifest = {};\n inFlightDataRoutes = convertRoutesToDataRoutes(\n newRoutes,\n mapRouteProperties,\n undefined,\n manifest\n );\n }\n\n function patchRoutes(\n routeId: string | null,\n children: AgnosticRouteObject[]\n ): void {\n let isNonHMR = inFlightDataRoutes == null;\n let routesToUse = inFlightDataRoutes || dataRoutes;\n patchRoutesImpl(\n routeId,\n children,\n routesToUse,\n manifest,\n mapRouteProperties\n );\n\n // If we are not in the middle of an HMR revalidation and we changed the\n // routes, provide a new identity and trigger a reflow via `updateState`\n // to re-run memoized `router.routes` dependencies.\n // HMR will already update the identity and reflow when it lands\n // `inFlightDataRoutes` in `completeNavigation`\n if (isNonHMR) {\n dataRoutes = [...dataRoutes];\n updateState({});\n }\n }\n\n router = {\n get basename() {\n return basename;\n },\n get future() {\n return future;\n },\n get state() {\n return state;\n },\n get routes() {\n return dataRoutes;\n },\n get window() {\n return routerWindow;\n },\n initialize,\n subscribe,\n enableScrollRestoration,\n navigate,\n fetch,\n revalidate,\n // Passthrough to history-aware createHref used by useHref so we get proper\n // hash-aware URLs in DOM paths\n createHref: (to: To) => init.history.createHref(to),\n encodeLocation: (to: To) => init.history.encodeLocation(to),\n getFetcher,\n deleteFetcher: deleteFetcherAndUpdateState,\n dispose,\n getBlocker,\n deleteBlocker,\n patchRoutes,\n _internalFetchControllers: fetchControllers,\n _internalActiveDeferreds: activeDeferreds,\n // TODO: Remove setRoutes, it's temporary to avoid dealing with\n // updating the tree while validating the update algorithm.\n _internalSetRoutes,\n };\n\n return router;\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region createStaticHandler\n////////////////////////////////////////////////////////////////////////////////\n\nexport const UNSAFE_DEFERRED_SYMBOL = Symbol(\"deferred\");\n\n/**\n * Future flags to toggle new feature behavior\n */\nexport interface StaticHandlerFutureConfig {\n v7_relativeSplatPath: boolean;\n v7_throwAbortReason: boolean;\n}\n\nexport interface CreateStaticHandlerOptions {\n basename?: string;\n /**\n * @deprecated Use `mapRouteProperties` instead\n */\n detectErrorBoundary?: DetectErrorBoundaryFunction;\n mapRouteProperties?: MapRoutePropertiesFunction;\n future?: Partial;\n}\n\nexport function createStaticHandler(\n routes: AgnosticRouteObject[],\n opts?: CreateStaticHandlerOptions\n): StaticHandler {\n invariant(\n routes.length > 0,\n \"You must provide a non-empty routes array to createStaticHandler\"\n );\n\n let manifest: RouteManifest = {};\n let basename = (opts ? opts.basename : null) || \"/\";\n let mapRouteProperties: MapRoutePropertiesFunction;\n if (opts?.mapRouteProperties) {\n mapRouteProperties = opts.mapRouteProperties;\n } else if (opts?.detectErrorBoundary) {\n // If they are still using the deprecated version, wrap it with the new API\n let detectErrorBoundary = opts.detectErrorBoundary;\n mapRouteProperties = (route) => ({\n hasErrorBoundary: detectErrorBoundary(route),\n });\n } else {\n mapRouteProperties = defaultMapRouteProperties;\n }\n // Config driven behavior flags\n let future: StaticHandlerFutureConfig = {\n v7_relativeSplatPath: false,\n v7_throwAbortReason: false,\n ...(opts ? opts.future : null),\n };\n\n let dataRoutes = convertRoutesToDataRoutes(\n routes,\n mapRouteProperties,\n undefined,\n manifest\n );\n\n /**\n * The query() method is intended for document requests, in which we want to\n * call an optional action and potentially multiple loaders for all nested\n * routes. It returns a StaticHandlerContext object, which is very similar\n * to the router state (location, loaderData, actionData, errors, etc.) and\n * also adds SSR-specific information such as the statusCode and headers\n * from action/loaders Responses.\n *\n * It _should_ never throw and should report all errors through the\n * returned context.errors object, properly associating errors to their error\n * boundary. Additionally, it tracks _deepestRenderedBoundaryId which can be\n * used to emulate React error boundaries during SSr by performing a second\n * pass only down to the boundaryId.\n *\n * The one exception where we do not return a StaticHandlerContext is when a\n * redirect response is returned or thrown from any action/loader. We\n * propagate that out and return the raw Response so the HTTP server can\n * return it directly.\n *\n * - `opts.requestContext` is an optional server context that will be passed\n * to actions/loaders in the `context` parameter\n * - `opts.skipLoaderErrorBubbling` is an optional parameter that will prevent\n * the bubbling of errors which allows single-fetch-type implementations\n * where the client will handle the bubbling and we may need to return data\n * for the handling route\n */\n async function query(\n request: Request,\n {\n requestContext,\n skipLoaderErrorBubbling,\n dataStrategy,\n }: {\n requestContext?: unknown;\n skipLoaderErrorBubbling?: boolean;\n dataStrategy?: DataStrategyFunction;\n } = {}\n ): Promise {\n let url = new URL(request.url);\n let method = request.method;\n let location = createLocation(\"\", createPath(url), null, \"default\");\n let matches = matchRoutes(dataRoutes, location, basename);\n\n // SSR supports HEAD requests while SPA doesn't\n if (!isValidMethod(method) && method !== \"HEAD\") {\n let error = getInternalRouterError(405, { method });\n let { matches: methodNotAllowedMatches, route } =\n getShortCircuitMatches(dataRoutes);\n return {\n basename,\n location,\n matches: methodNotAllowedMatches,\n loaderData: {},\n actionData: null,\n errors: {\n [route.id]: error,\n },\n statusCode: error.status,\n loaderHeaders: {},\n actionHeaders: {},\n activeDeferreds: null,\n };\n } else if (!matches) {\n let error = getInternalRouterError(404, { pathname: location.pathname });\n let { matches: notFoundMatches, route } =\n getShortCircuitMatches(dataRoutes);\n return {\n basename,\n location,\n matches: notFoundMatches,\n loaderData: {},\n actionData: null,\n errors: {\n [route.id]: error,\n },\n statusCode: error.status,\n loaderHeaders: {},\n actionHeaders: {},\n activeDeferreds: null,\n };\n }\n\n let result = await queryImpl(\n request,\n location,\n matches,\n requestContext,\n dataStrategy || null,\n skipLoaderErrorBubbling === true,\n null\n );\n if (isResponse(result)) {\n return result;\n }\n\n // When returning StaticHandlerContext, we patch back in the location here\n // since we need it for React Context. But this helps keep our submit and\n // loadRouteData operating on a Request instead of a Location\n return { location, basename, ...result };\n }\n\n /**\n * The queryRoute() method is intended for targeted route requests, either\n * for fetch ?_data requests or resource route requests. In this case, we\n * are only ever calling a single action or loader, and we are returning the\n * returned value directly. In most cases, this will be a Response returned\n * from the action/loader, but it may be a primitive or other value as well -\n * and in such cases the calling context should handle that accordingly.\n *\n * We do respect the throw/return differentiation, so if an action/loader\n * throws, then this method will throw the value. This is important so we\n * can do proper boundary identification in Remix where a thrown Response\n * must go to the Catch Boundary but a returned Response is happy-path.\n *\n * One thing to note is that any Router-initiated Errors that make sense\n * to associate with a status code will be thrown as an ErrorResponse\n * instance which include the raw Error, such that the calling context can\n * serialize the error as they see fit while including the proper response\n * code. Examples here are 404 and 405 errors that occur prior to reaching\n * any user-defined loaders.\n *\n * - `opts.routeId` allows you to specify the specific route handler to call.\n * If not provided the handler will determine the proper route by matching\n * against `request.url`\n * - `opts.requestContext` is an optional server context that will be passed\n * to actions/loaders in the `context` parameter\n */\n async function queryRoute(\n request: Request,\n {\n routeId,\n requestContext,\n dataStrategy,\n }: {\n requestContext?: unknown;\n routeId?: string;\n dataStrategy?: DataStrategyFunction;\n } = {}\n ): Promise {\n let url = new URL(request.url);\n let method = request.method;\n let location = createLocation(\"\", createPath(url), null, \"default\");\n let matches = matchRoutes(dataRoutes, location, basename);\n\n // SSR supports HEAD requests while SPA doesn't\n if (!isValidMethod(method) && method !== \"HEAD\" && method !== \"OPTIONS\") {\n throw getInternalRouterError(405, { method });\n } else if (!matches) {\n throw getInternalRouterError(404, { pathname: location.pathname });\n }\n\n let match = routeId\n ? matches.find((m) => m.route.id === routeId)\n : getTargetMatch(matches, location);\n\n if (routeId && !match) {\n throw getInternalRouterError(403, {\n pathname: location.pathname,\n routeId,\n });\n } else if (!match) {\n // This should never hit I don't think?\n throw getInternalRouterError(404, { pathname: location.pathname });\n }\n\n let result = await queryImpl(\n request,\n location,\n matches,\n requestContext,\n dataStrategy || null,\n false,\n match\n );\n\n if (isResponse(result)) {\n return result;\n }\n\n let error = result.errors ? Object.values(result.errors)[0] : undefined;\n if (error !== undefined) {\n // If we got back result.errors, that means the loader/action threw\n // _something_ that wasn't a Response, but it's not guaranteed/required\n // to be an `instanceof Error` either, so we have to use throw here to\n // preserve the \"error\" state outside of queryImpl.\n throw error;\n }\n\n // Pick off the right state value to return\n if (result.actionData) {\n return Object.values(result.actionData)[0];\n }\n\n if (result.loaderData) {\n let data = Object.values(result.loaderData)[0];\n if (result.activeDeferreds?.[match.route.id]) {\n data[UNSAFE_DEFERRED_SYMBOL] = result.activeDeferreds[match.route.id];\n }\n return data;\n }\n\n return undefined;\n }\n\n async function queryImpl(\n request: Request,\n location: Location,\n matches: AgnosticDataRouteMatch[],\n requestContext: unknown,\n dataStrategy: DataStrategyFunction | null,\n skipLoaderErrorBubbling: boolean,\n routeMatch: AgnosticDataRouteMatch | null\n ): Promise | Response> {\n invariant(\n request.signal,\n \"query()/queryRoute() requests must contain an AbortController signal\"\n );\n\n try {\n if (isMutationMethod(request.method.toLowerCase())) {\n let result = await submit(\n request,\n matches,\n routeMatch || getTargetMatch(matches, location),\n requestContext,\n dataStrategy,\n skipLoaderErrorBubbling,\n routeMatch != null\n );\n return result;\n }\n\n let result = await loadRouteData(\n request,\n matches,\n requestContext,\n dataStrategy,\n skipLoaderErrorBubbling,\n routeMatch\n );\n return isResponse(result)\n ? result\n : {\n ...result,\n actionData: null,\n actionHeaders: {},\n };\n } catch (e) {\n // If the user threw/returned a Response in callLoaderOrAction for a\n // `queryRoute` call, we throw the `DataStrategyResult` to bail out early\n // and then return or throw the raw Response here accordingly\n if (isDataStrategyResult(e) && isResponse(e.result)) {\n if (e.type === ResultType.error) {\n throw e.result;\n }\n return e.result;\n }\n // Redirects are always returned since they don't propagate to catch\n // boundaries\n if (isRedirectResponse(e)) {\n return e;\n }\n throw e;\n }\n }\n\n async function submit(\n request: Request,\n matches: AgnosticDataRouteMatch[],\n actionMatch: AgnosticDataRouteMatch,\n requestContext: unknown,\n dataStrategy: DataStrategyFunction | null,\n skipLoaderErrorBubbling: boolean,\n isRouteRequest: boolean\n ): Promise | Response> {\n let result: DataResult;\n\n if (!actionMatch.route.action && !actionMatch.route.lazy) {\n let error = getInternalRouterError(405, {\n method: request.method,\n pathname: new URL(request.url).pathname,\n routeId: actionMatch.route.id,\n });\n if (isRouteRequest) {\n throw error;\n }\n result = {\n type: ResultType.error,\n error,\n };\n } else {\n let results = await callDataStrategy(\n \"action\",\n request,\n [actionMatch],\n matches,\n isRouteRequest,\n requestContext,\n dataStrategy\n );\n result = results[actionMatch.route.id];\n\n if (request.signal.aborted) {\n throwStaticHandlerAbortedError(request, isRouteRequest, future);\n }\n }\n\n if (isRedirectResult(result)) {\n // Uhhhh - this should never happen, we should always throw these from\n // callLoaderOrAction, but the type narrowing here keeps TS happy and we\n // can get back on the \"throw all redirect responses\" train here should\n // this ever happen :/\n throw new Response(null, {\n status: result.response.status,\n headers: {\n Location: result.response.headers.get(\"Location\")!,\n },\n });\n }\n\n if (isDeferredResult(result)) {\n let error = getInternalRouterError(400, { type: \"defer-action\" });\n if (isRouteRequest) {\n throw error;\n }\n result = {\n type: ResultType.error,\n error,\n };\n }\n\n if (isRouteRequest) {\n // Note: This should only be non-Response values if we get here, since\n // isRouteRequest should throw any Response received in callLoaderOrAction\n if (isErrorResult(result)) {\n throw result.error;\n }\n\n return {\n matches: [actionMatch],\n loaderData: {},\n actionData: { [actionMatch.route.id]: result.data },\n errors: null,\n // Note: statusCode + headers are unused here since queryRoute will\n // return the raw Response or value\n statusCode: 200,\n loaderHeaders: {},\n actionHeaders: {},\n activeDeferreds: null,\n };\n }\n\n // Create a GET request for the loaders\n let loaderRequest = new Request(request.url, {\n headers: request.headers,\n redirect: request.redirect,\n signal: request.signal,\n });\n\n if (isErrorResult(result)) {\n // Store off the pending error - we use it to determine which loaders\n // to call and will commit it when we complete the navigation\n let boundaryMatch = skipLoaderErrorBubbling\n ? actionMatch\n : findNearestBoundary(matches, actionMatch.route.id);\n\n let context = await loadRouteData(\n loaderRequest,\n matches,\n requestContext,\n dataStrategy,\n skipLoaderErrorBubbling,\n null,\n [boundaryMatch.route.id, result]\n );\n\n // action status codes take precedence over loader status codes\n return {\n ...context,\n statusCode: isRouteErrorResponse(result.error)\n ? result.error.status\n : result.statusCode != null\n ? result.statusCode\n : 500,\n actionData: null,\n actionHeaders: {\n ...(result.headers ? { [actionMatch.route.id]: result.headers } : {}),\n },\n };\n }\n\n let context = await loadRouteData(\n loaderRequest,\n matches,\n requestContext,\n dataStrategy,\n skipLoaderErrorBubbling,\n null\n );\n\n return {\n ...context,\n actionData: {\n [actionMatch.route.id]: result.data,\n },\n // action status codes take precedence over loader status codes\n ...(result.statusCode ? { statusCode: result.statusCode } : {}),\n actionHeaders: result.headers\n ? { [actionMatch.route.id]: result.headers }\n : {},\n };\n }\n\n async function loadRouteData(\n request: Request,\n matches: AgnosticDataRouteMatch[],\n requestContext: unknown,\n dataStrategy: DataStrategyFunction | null,\n skipLoaderErrorBubbling: boolean,\n routeMatch: AgnosticDataRouteMatch | null,\n pendingActionResult?: PendingActionResult\n ): Promise<\n | Omit<\n StaticHandlerContext,\n \"location\" | \"basename\" | \"actionData\" | \"actionHeaders\"\n >\n | Response\n > {\n let isRouteRequest = routeMatch != null;\n\n // Short circuit if we have no loaders to run (queryRoute())\n if (\n isRouteRequest &&\n !routeMatch?.route.loader &&\n !routeMatch?.route.lazy\n ) {\n throw getInternalRouterError(400, {\n method: request.method,\n pathname: new URL(request.url).pathname,\n routeId: routeMatch?.route.id,\n });\n }\n\n let requestMatches = routeMatch\n ? [routeMatch]\n : pendingActionResult && isErrorResult(pendingActionResult[1])\n ? getLoaderMatchesUntilBoundary(matches, pendingActionResult[0])\n : matches;\n let matchesToLoad = requestMatches.filter(\n (m) => m.route.loader || m.route.lazy\n );\n\n // Short circuit if we have no loaders to run (query())\n if (matchesToLoad.length === 0) {\n return {\n matches,\n // Add a null for all matched routes for proper revalidation on the client\n loaderData: matches.reduce(\n (acc, m) => Object.assign(acc, { [m.route.id]: null }),\n {}\n ),\n errors:\n pendingActionResult && isErrorResult(pendingActionResult[1])\n ? {\n [pendingActionResult[0]]: pendingActionResult[1].error,\n }\n : null,\n statusCode: 200,\n loaderHeaders: {},\n activeDeferreds: null,\n };\n }\n\n let results = await callDataStrategy(\n \"loader\",\n request,\n matchesToLoad,\n matches,\n isRouteRequest,\n requestContext,\n dataStrategy\n );\n\n if (request.signal.aborted) {\n throwStaticHandlerAbortedError(request, isRouteRequest, future);\n }\n\n // Process and commit output from loaders\n let activeDeferreds = new Map();\n let context = processRouteLoaderData(\n matches,\n results,\n pendingActionResult,\n activeDeferreds,\n skipLoaderErrorBubbling\n );\n\n // Add a null for any non-loader matches for proper revalidation on the client\n let executedLoaders = new Set(\n matchesToLoad.map((match) => match.route.id)\n );\n matches.forEach((match) => {\n if (!executedLoaders.has(match.route.id)) {\n context.loaderData[match.route.id] = null;\n }\n });\n\n return {\n ...context,\n matches,\n activeDeferreds:\n activeDeferreds.size > 0\n ? Object.fromEntries(activeDeferreds.entries())\n : null,\n };\n }\n\n // Utility wrapper for calling dataStrategy server-side without having to\n // pass around the manifest, mapRouteProperties, etc.\n async function callDataStrategy(\n type: \"loader\" | \"action\",\n request: Request,\n matchesToLoad: AgnosticDataRouteMatch[],\n matches: AgnosticDataRouteMatch[],\n isRouteRequest: boolean,\n requestContext: unknown,\n dataStrategy: DataStrategyFunction | null\n ): Promise> {\n let results = await callDataStrategyImpl(\n dataStrategy || defaultDataStrategy,\n type,\n null,\n request,\n matchesToLoad,\n matches,\n null,\n manifest,\n mapRouteProperties,\n requestContext\n );\n\n let dataResults: Record = {};\n await Promise.all(\n matches.map(async (match) => {\n if (!(match.route.id in results)) {\n return;\n }\n let result = results[match.route.id];\n if (isRedirectDataStrategyResultResult(result)) {\n let response = result.result as Response;\n // Throw redirects and let the server handle them with an HTTP redirect\n throw normalizeRelativeRoutingRedirectResponse(\n response,\n request,\n match.route.id,\n matches,\n basename,\n future.v7_relativeSplatPath\n );\n }\n if (isResponse(result.result) && isRouteRequest) {\n // For SSR single-route requests, we want to hand Responses back\n // directly without unwrapping\n throw result;\n }\n\n dataResults[match.route.id] =\n await convertDataStrategyResultToDataResult(result);\n })\n );\n return dataResults;\n }\n\n return {\n dataRoutes,\n query,\n queryRoute,\n };\n}\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Helpers\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Given an existing StaticHandlerContext and an error thrown at render time,\n * provide an updated StaticHandlerContext suitable for a second SSR render\n */\nexport function getStaticContextFromError(\n routes: AgnosticDataRouteObject[],\n context: StaticHandlerContext,\n error: any\n) {\n let newContext: StaticHandlerContext = {\n ...context,\n statusCode: isRouteErrorResponse(error) ? error.status : 500,\n errors: {\n [context._deepestRenderedBoundaryId || routes[0].id]: error,\n },\n };\n return newContext;\n}\n\nfunction throwStaticHandlerAbortedError(\n request: Request,\n isRouteRequest: boolean,\n future: StaticHandlerFutureConfig\n) {\n if (future.v7_throwAbortReason && request.signal.reason !== undefined) {\n throw request.signal.reason;\n }\n\n let method = isRouteRequest ? \"queryRoute\" : \"query\";\n throw new Error(`${method}() call aborted: ${request.method} ${request.url}`);\n}\n\nfunction isSubmissionNavigation(\n opts: BaseNavigateOrFetchOptions\n): opts is SubmissionNavigateOptions {\n return (\n opts != null &&\n ((\"formData\" in opts && opts.formData != null) ||\n (\"body\" in opts && opts.body !== undefined))\n );\n}\n\nfunction normalizeTo(\n location: Path,\n matches: AgnosticDataRouteMatch[],\n basename: string,\n prependBasename: boolean,\n to: To | null,\n v7_relativeSplatPath: boolean,\n fromRouteId?: string,\n relative?: RelativeRoutingType\n) {\n let contextualMatches: AgnosticDataRouteMatch[];\n let activeRouteMatch: AgnosticDataRouteMatch | undefined;\n if (fromRouteId) {\n // Grab matches up to the calling route so our route-relative logic is\n // relative to the correct source route\n contextualMatches = [];\n for (let match of matches) {\n contextualMatches.push(match);\n if (match.route.id === fromRouteId) {\n activeRouteMatch = match;\n break;\n }\n }\n } else {\n contextualMatches = matches;\n activeRouteMatch = matches[matches.length - 1];\n }\n\n // Resolve the relative path\n let path = resolveTo(\n to ? to : \".\",\n getResolveToMatches(contextualMatches, v7_relativeSplatPath),\n stripBasename(location.pathname, basename) || location.pathname,\n relative === \"path\"\n );\n\n // When `to` is not specified we inherit search/hash from the current\n // location, unlike when to=\".\" and we just inherit the path.\n // See https://github.com/remix-run/remix/issues/927\n if (to == null) {\n path.search = location.search;\n path.hash = location.hash;\n }\n\n // Account for `?index` params when routing to the current location\n if ((to == null || to === \"\" || to === \".\") && activeRouteMatch) {\n let nakedIndex = hasNakedIndexQuery(path.search);\n if (activeRouteMatch.route.index && !nakedIndex) {\n // Add one when we're targeting an index route\n path.search = path.search\n ? path.search.replace(/^\\?/, \"?index&\")\n : \"?index\";\n } else if (!activeRouteMatch.route.index && nakedIndex) {\n // Remove existing ones when we're not\n let params = new URLSearchParams(path.search);\n let indexValues = params.getAll(\"index\");\n params.delete(\"index\");\n indexValues.filter((v) => v).forEach((v) => params.append(\"index\", v));\n let qs = params.toString();\n path.search = qs ? `?${qs}` : \"\";\n }\n }\n\n // If we're operating within a basename, prepend it to the pathname. If\n // this is a root navigation, then just use the raw basename which allows\n // the basename to have full control over the presence of a trailing slash\n // on root actions\n if (prependBasename && basename !== \"/\") {\n path.pathname =\n path.pathname === \"/\" ? basename : joinPaths([basename, path.pathname]);\n }\n\n return createPath(path);\n}\n\n// Normalize navigation options by converting formMethod=GET formData objects to\n// URLSearchParams so they behave identically to links with query params\nfunction normalizeNavigateOptions(\n normalizeFormMethod: boolean,\n isFetcher: boolean,\n path: string,\n opts?: BaseNavigateOrFetchOptions\n): {\n path: string;\n submission?: Submission;\n error?: ErrorResponseImpl;\n} {\n // Return location verbatim on non-submission navigations\n if (!opts || !isSubmissionNavigation(opts)) {\n return { path };\n }\n\n if (opts.formMethod && !isValidMethod(opts.formMethod)) {\n return {\n path,\n error: getInternalRouterError(405, { method: opts.formMethod }),\n };\n }\n\n let getInvalidBodyError = () => ({\n path,\n error: getInternalRouterError(400, { type: \"invalid-body\" }),\n });\n\n // Create a Submission on non-GET navigations\n let rawFormMethod = opts.formMethod || \"get\";\n let formMethod = normalizeFormMethod\n ? (rawFormMethod.toUpperCase() as V7_FormMethod)\n : (rawFormMethod.toLowerCase() as FormMethod);\n let formAction = stripHashFromPath(path);\n\n if (opts.body !== undefined) {\n if (opts.formEncType === \"text/plain\") {\n // text only support POST/PUT/PATCH/DELETE submissions\n if (!isMutationMethod(formMethod)) {\n return getInvalidBodyError();\n }\n\n let text =\n typeof opts.body === \"string\"\n ? opts.body\n : opts.body instanceof FormData ||\n opts.body instanceof URLSearchParams\n ? // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#plain-text-form-data\n Array.from(opts.body.entries()).reduce(\n (acc, [name, value]) => `${acc}${name}=${value}\\n`,\n \"\"\n )\n : String(opts.body);\n\n return {\n path,\n submission: {\n formMethod,\n formAction,\n formEncType: opts.formEncType,\n formData: undefined,\n json: undefined,\n text,\n },\n };\n } else if (opts.formEncType === \"application/json\") {\n // json only supports POST/PUT/PATCH/DELETE submissions\n if (!isMutationMethod(formMethod)) {\n return getInvalidBodyError();\n }\n\n try {\n let json =\n typeof opts.body === \"string\" ? JSON.parse(opts.body) : opts.body;\n\n return {\n path,\n submission: {\n formMethod,\n formAction,\n formEncType: opts.formEncType,\n formData: undefined,\n json,\n text: undefined,\n },\n };\n } catch (e) {\n return getInvalidBodyError();\n }\n }\n }\n\n invariant(\n typeof FormData === \"function\",\n \"FormData is not available in this environment\"\n );\n\n let searchParams: URLSearchParams;\n let formData: FormData;\n\n if (opts.formData) {\n searchParams = convertFormDataToSearchParams(opts.formData);\n formData = opts.formData;\n } else if (opts.body instanceof FormData) {\n searchParams = convertFormDataToSearchParams(opts.body);\n formData = opts.body;\n } else if (opts.body instanceof URLSearchParams) {\n searchParams = opts.body;\n formData = convertSearchParamsToFormData(searchParams);\n } else if (opts.body == null) {\n searchParams = new URLSearchParams();\n formData = new FormData();\n } else {\n try {\n searchParams = new URLSearchParams(opts.body);\n formData = convertSearchParamsToFormData(searchParams);\n } catch (e) {\n return getInvalidBodyError();\n }\n }\n\n let submission: Submission = {\n formMethod,\n formAction,\n formEncType:\n (opts && opts.formEncType) || \"application/x-www-form-urlencoded\",\n formData,\n json: undefined,\n text: undefined,\n };\n\n if (isMutationMethod(submission.formMethod)) {\n return { path, submission };\n }\n\n // Flatten submission onto URLSearchParams for GET submissions\n let parsedPath = parsePath(path);\n // On GET navigation submissions we can drop the ?index param from the\n // resulting location since all loaders will run. But fetcher GET submissions\n // only run a single loader so we need to preserve any incoming ?index params\n if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) {\n searchParams.append(\"index\", \"\");\n }\n parsedPath.search = `?${searchParams}`;\n\n return { path: createPath(parsedPath), submission };\n}\n\n// Filter out all routes at/below any caught error as they aren't going to\n// render so we don't need to load them\nfunction getLoaderMatchesUntilBoundary(\n matches: AgnosticDataRouteMatch[],\n boundaryId: string,\n includeBoundary = false\n) {\n let index = matches.findIndex((m) => m.route.id === boundaryId);\n if (index >= 0) {\n return matches.slice(0, includeBoundary ? index + 1 : index);\n }\n return matches;\n}\n\nfunction getMatchesToLoad(\n history: History,\n state: RouterState,\n matches: AgnosticDataRouteMatch[],\n submission: Submission | undefined,\n location: Location,\n initialHydration: boolean,\n skipActionErrorRevalidation: boolean,\n isRevalidationRequired: boolean,\n cancelledDeferredRoutes: string[],\n cancelledFetcherLoads: Set,\n deletedFetchers: Set,\n fetchLoadMatches: Map,\n fetchRedirectIds: Set,\n routesToUse: AgnosticDataRouteObject[],\n basename: string | undefined,\n pendingActionResult?: PendingActionResult\n): [AgnosticDataRouteMatch[], RevalidatingFetcher[]] {\n let actionResult = pendingActionResult\n ? isErrorResult(pendingActionResult[1])\n ? pendingActionResult[1].error\n : pendingActionResult[1].data\n : undefined;\n let currentUrl = history.createURL(state.location);\n let nextUrl = history.createURL(location);\n\n // Pick navigation matches that are net-new or qualify for revalidation\n let boundaryMatches = matches;\n if (initialHydration && state.errors) {\n // On initial hydration, only consider matches up to _and including_ the boundary.\n // This is inclusive to handle cases where a server loader ran successfully,\n // a child server loader bubbled up to this route, but this route has\n // `clientLoader.hydrate` so we want to still run the `clientLoader` so that\n // we have a complete version of `loaderData`\n boundaryMatches = getLoaderMatchesUntilBoundary(\n matches,\n Object.keys(state.errors)[0],\n true\n );\n } else if (pendingActionResult && isErrorResult(pendingActionResult[1])) {\n // If an action threw an error, we call loaders up to, but not including the\n // boundary\n boundaryMatches = getLoaderMatchesUntilBoundary(\n matches,\n pendingActionResult[0]\n );\n }\n\n // Don't revalidate loaders by default after action 4xx/5xx responses\n // when the flag is enabled. They can still opt-into revalidation via\n // `shouldRevalidate` via `actionResult`\n let actionStatus = pendingActionResult\n ? pendingActionResult[1].statusCode\n : undefined;\n let shouldSkipRevalidation =\n skipActionErrorRevalidation && actionStatus && actionStatus >= 400;\n\n let navigationMatches = boundaryMatches.filter((match, index) => {\n let { route } = match;\n if (route.lazy) {\n // We haven't loaded this route yet so we don't know if it's got a loader!\n return true;\n }\n\n if (route.loader == null) {\n return false;\n }\n\n if (initialHydration) {\n return shouldLoadRouteOnHydration(route, state.loaderData, state.errors);\n }\n\n // Always call the loader on new route instances and pending defer cancellations\n if (\n isNewLoader(state.loaderData, state.matches[index], match) ||\n cancelledDeferredRoutes.some((id) => id === match.route.id)\n ) {\n return true;\n }\n\n // This is the default implementation for when we revalidate. If the route\n // provides it's own implementation, then we give them full control but\n // provide this value so they can leverage it if needed after they check\n // their own specific use cases\n let currentRouteMatch = state.matches[index];\n let nextRouteMatch = match;\n\n return shouldRevalidateLoader(match, {\n currentUrl,\n currentParams: currentRouteMatch.params,\n nextUrl,\n nextParams: nextRouteMatch.params,\n ...submission,\n actionResult,\n actionStatus,\n defaultShouldRevalidate: shouldSkipRevalidation\n ? false\n : // Forced revalidation due to submission, useRevalidator, or X-Remix-Revalidate\n isRevalidationRequired ||\n currentUrl.pathname + currentUrl.search ===\n nextUrl.pathname + nextUrl.search ||\n // Search params affect all loaders\n currentUrl.search !== nextUrl.search ||\n isNewRouteInstance(currentRouteMatch, nextRouteMatch),\n });\n });\n\n // Pick fetcher.loads that need to be revalidated\n let revalidatingFetchers: RevalidatingFetcher[] = [];\n fetchLoadMatches.forEach((f, key) => {\n // Don't revalidate:\n // - on initial hydration (shouldn't be any fetchers then anyway)\n // - if fetcher won't be present in the subsequent render\n // - no longer matches the URL (v7_fetcherPersist=false)\n // - was unmounted but persisted due to v7_fetcherPersist=true\n if (\n initialHydration ||\n !matches.some((m) => m.route.id === f.routeId) ||\n deletedFetchers.has(key)\n ) {\n return;\n }\n\n let fetcherMatches = matchRoutes(routesToUse, f.path, basename);\n\n // If the fetcher path no longer matches, push it in with null matches so\n // we can trigger a 404 in callLoadersAndMaybeResolveData. Note this is\n // currently only a use-case for Remix HMR where the route tree can change\n // at runtime and remove a route previously loaded via a fetcher\n if (!fetcherMatches) {\n revalidatingFetchers.push({\n key,\n routeId: f.routeId,\n path: f.path,\n matches: null,\n match: null,\n controller: null,\n });\n return;\n }\n\n // Revalidating fetchers are decoupled from the route matches since they\n // load from a static href. They revalidate based on explicit revalidation\n // (submission, useRevalidator, or X-Remix-Revalidate)\n let fetcher = state.fetchers.get(key);\n let fetcherMatch = getTargetMatch(fetcherMatches, f.path);\n\n let shouldRevalidate = false;\n if (fetchRedirectIds.has(key)) {\n // Never trigger a revalidation of an actively redirecting fetcher\n shouldRevalidate = false;\n } else if (cancelledFetcherLoads.has(key)) {\n // Always mark for revalidation if the fetcher was cancelled\n cancelledFetcherLoads.delete(key);\n shouldRevalidate = true;\n } else if (\n fetcher &&\n fetcher.state !== \"idle\" &&\n fetcher.data === undefined\n ) {\n // If the fetcher hasn't ever completed loading yet, then this isn't a\n // revalidation, it would just be a brand new load if an explicit\n // revalidation is required\n shouldRevalidate = isRevalidationRequired;\n } else {\n // Otherwise fall back on any user-defined shouldRevalidate, defaulting\n // to explicit revalidations only\n shouldRevalidate = shouldRevalidateLoader(fetcherMatch, {\n currentUrl,\n currentParams: state.matches[state.matches.length - 1].params,\n nextUrl,\n nextParams: matches[matches.length - 1].params,\n ...submission,\n actionResult,\n actionStatus,\n defaultShouldRevalidate: shouldSkipRevalidation\n ? false\n : isRevalidationRequired,\n });\n }\n\n if (shouldRevalidate) {\n revalidatingFetchers.push({\n key,\n routeId: f.routeId,\n path: f.path,\n matches: fetcherMatches,\n match: fetcherMatch,\n controller: new AbortController(),\n });\n }\n });\n\n return [navigationMatches, revalidatingFetchers];\n}\n\nfunction shouldLoadRouteOnHydration(\n route: AgnosticDataRouteObject,\n loaderData: RouteData | null | undefined,\n errors: RouteData | null | undefined\n) {\n // We dunno if we have a loader - gotta find out!\n if (route.lazy) {\n return true;\n }\n\n // No loader, nothing to initialize\n if (!route.loader) {\n return false;\n }\n\n let hasData = loaderData != null && loaderData[route.id] !== undefined;\n let hasError = errors != null && errors[route.id] !== undefined;\n\n // Don't run if we error'd during SSR\n if (!hasData && hasError) {\n return false;\n }\n\n // Explicitly opting-in to running on hydration\n if (typeof route.loader === \"function\" && route.loader.hydrate === true) {\n return true;\n }\n\n // Otherwise, run if we're not yet initialized with anything\n return !hasData && !hasError;\n}\n\nfunction isNewLoader(\n currentLoaderData: RouteData,\n currentMatch: AgnosticDataRouteMatch,\n match: AgnosticDataRouteMatch\n) {\n let isNew =\n // [a] -> [a, b]\n !currentMatch ||\n // [a, b] -> [a, c]\n match.route.id !== currentMatch.route.id;\n\n // Handle the case that we don't have data for a re-used route, potentially\n // from a prior error or from a cancelled pending deferred\n let isMissingData = currentLoaderData[match.route.id] === undefined;\n\n // Always load if this is a net-new route or we don't yet have data\n return isNew || isMissingData;\n}\n\nfunction isNewRouteInstance(\n currentMatch: AgnosticDataRouteMatch,\n match: AgnosticDataRouteMatch\n) {\n let currentPath = currentMatch.route.path;\n return (\n // param change for this match, /users/123 -> /users/456\n currentMatch.pathname !== match.pathname ||\n // splat param changed, which is not present in match.path\n // e.g. /files/images/avatar.jpg -> files/finances.xls\n (currentPath != null &&\n currentPath.endsWith(\"*\") &&\n currentMatch.params[\"*\"] !== match.params[\"*\"])\n );\n}\n\nfunction shouldRevalidateLoader(\n loaderMatch: AgnosticDataRouteMatch,\n arg: ShouldRevalidateFunctionArgs\n) {\n if (loaderMatch.route.shouldRevalidate) {\n let routeChoice = loaderMatch.route.shouldRevalidate(arg);\n if (typeof routeChoice === \"boolean\") {\n return routeChoice;\n }\n }\n\n return arg.defaultShouldRevalidate;\n}\n\nfunction patchRoutesImpl(\n routeId: string | null,\n children: AgnosticRouteObject[],\n routesToUse: AgnosticDataRouteObject[],\n manifest: RouteManifest,\n mapRouteProperties: MapRoutePropertiesFunction\n) {\n let childrenToPatch: AgnosticDataRouteObject[];\n if (routeId) {\n let route = manifest[routeId];\n invariant(\n route,\n `No route found to patch children into: routeId = ${routeId}`\n );\n if (!route.children) {\n route.children = [];\n }\n childrenToPatch = route.children;\n } else {\n childrenToPatch = routesToUse;\n }\n\n // Don't patch in routes we already know about so that `patch` is idempotent\n // to simplify user-land code. This is useful because we re-call the\n // `patchRoutesOnNavigation` function for matched routes with params.\n let uniqueChildren = children.filter(\n (newRoute) =>\n !childrenToPatch.some((existingRoute) =>\n isSameRoute(newRoute, existingRoute)\n )\n );\n\n let newRoutes = convertRoutesToDataRoutes(\n uniqueChildren,\n mapRouteProperties,\n [routeId || \"_\", \"patch\", String(childrenToPatch?.length || \"0\")],\n manifest\n );\n\n childrenToPatch.push(...newRoutes);\n}\n\nfunction isSameRoute(\n newRoute: AgnosticRouteObject,\n existingRoute: AgnosticRouteObject\n): boolean {\n // Most optimal check is by id\n if (\n \"id\" in newRoute &&\n \"id\" in existingRoute &&\n newRoute.id === existingRoute.id\n ) {\n return true;\n }\n\n // Second is by pathing differences\n if (\n !(\n newRoute.index === existingRoute.index &&\n newRoute.path === existingRoute.path &&\n newRoute.caseSensitive === existingRoute.caseSensitive\n )\n ) {\n return false;\n }\n\n // Pathless layout routes are trickier since we need to check children.\n // If they have no children then they're the same as far as we can tell\n if (\n (!newRoute.children || newRoute.children.length === 0) &&\n (!existingRoute.children || existingRoute.children.length === 0)\n ) {\n return true;\n }\n\n // Otherwise, we look to see if every child in the new route is already\n // represented in the existing route's children\n return newRoute.children!.every((aChild, i) =>\n existingRoute.children?.some((bChild) => isSameRoute(aChild, bChild))\n );\n}\n\n/**\n * Execute route.lazy() methods to lazily load route modules (loader, action,\n * shouldRevalidate) and update the routeManifest in place which shares objects\n * with dataRoutes so those get updated as well.\n */\nasync function loadLazyRouteModule(\n route: AgnosticDataRouteObject,\n mapRouteProperties: MapRoutePropertiesFunction,\n manifest: RouteManifest\n) {\n if (!route.lazy) {\n return;\n }\n\n let lazyRoute = await route.lazy();\n\n // If the lazy route function was executed and removed by another parallel\n // call then we can return - first lazy() to finish wins because the return\n // value of lazy is expected to be static\n if (!route.lazy) {\n return;\n }\n\n let routeToUpdate = manifest[route.id];\n invariant(routeToUpdate, \"No route found in manifest\");\n\n // Update the route in place. This should be safe because there's no way\n // we could yet be sitting on this route as we can't get there without\n // resolving lazy() first.\n //\n // This is different than the HMR \"update\" use-case where we may actively be\n // on the route being updated. The main concern boils down to \"does this\n // mutation affect any ongoing navigations or any current state.matches\n // values?\". If not, it should be safe to update in place.\n let routeUpdates: Record = {};\n for (let lazyRouteProperty in lazyRoute) {\n let staticRouteValue =\n routeToUpdate[lazyRouteProperty as keyof typeof routeToUpdate];\n\n let isPropertyStaticallyDefined =\n staticRouteValue !== undefined &&\n // This property isn't static since it should always be updated based\n // on the route updates\n lazyRouteProperty !== \"hasErrorBoundary\";\n\n warning(\n !isPropertyStaticallyDefined,\n `Route \"${routeToUpdate.id}\" has a static property \"${lazyRouteProperty}\" ` +\n `defined but its lazy function is also returning a value for this property. ` +\n `The lazy route property \"${lazyRouteProperty}\" will be ignored.`\n );\n\n if (\n !isPropertyStaticallyDefined &&\n !immutableRouteKeys.has(lazyRouteProperty as ImmutableRouteKey)\n ) {\n routeUpdates[lazyRouteProperty] =\n lazyRoute[lazyRouteProperty as keyof typeof lazyRoute];\n }\n }\n\n // Mutate the route with the provided updates. Do this first so we pass\n // the updated version to mapRouteProperties\n Object.assign(routeToUpdate, routeUpdates);\n\n // Mutate the `hasErrorBoundary` property on the route based on the route\n // updates and remove the `lazy` function so we don't resolve the lazy\n // route again.\n Object.assign(routeToUpdate, {\n // To keep things framework agnostic, we use the provided\n // `mapRouteProperties` (or wrapped `detectErrorBoundary`) function to\n // set the framework-aware properties (`element`/`hasErrorBoundary`) since\n // the logic will differ between frameworks.\n ...mapRouteProperties(routeToUpdate),\n lazy: undefined,\n });\n}\n\n// Default implementation of `dataStrategy` which fetches all loaders in parallel\nasync function defaultDataStrategy({\n matches,\n}: DataStrategyFunctionArgs): ReturnType {\n let matchesToLoad = matches.filter((m) => m.shouldLoad);\n let results = await Promise.all(matchesToLoad.map((m) => m.resolve()));\n return results.reduce(\n (acc, result, i) =>\n Object.assign(acc, { [matchesToLoad[i].route.id]: result }),\n {}\n );\n}\n\nasync function callDataStrategyImpl(\n dataStrategyImpl: DataStrategyFunction,\n type: \"loader\" | \"action\",\n state: RouterState | null,\n request: Request,\n matchesToLoad: AgnosticDataRouteMatch[],\n matches: AgnosticDataRouteMatch[],\n fetcherKey: string | null,\n manifest: RouteManifest,\n mapRouteProperties: MapRoutePropertiesFunction,\n requestContext?: unknown\n): Promise> {\n let loadRouteDefinitionsPromises = matches.map((m) =>\n m.route.lazy\n ? loadLazyRouteModule(m.route, mapRouteProperties, manifest)\n : undefined\n );\n\n let dsMatches = matches.map((match, i) => {\n let loadRoutePromise = loadRouteDefinitionsPromises[i];\n let shouldLoad = matchesToLoad.some((m) => m.route.id === match.route.id);\n // `resolve` encapsulates route.lazy(), executing the loader/action,\n // and mapping return values/thrown errors to a `DataStrategyResult`. Users\n // can pass a callback to take fine-grained control over the execution\n // of the loader/action\n let resolve: DataStrategyMatch[\"resolve\"] = async (handlerOverride) => {\n if (\n handlerOverride &&\n request.method === \"GET\" &&\n (match.route.lazy || match.route.loader)\n ) {\n shouldLoad = true;\n }\n return shouldLoad\n ? callLoaderOrAction(\n type,\n request,\n match,\n loadRoutePromise,\n handlerOverride,\n requestContext\n )\n : Promise.resolve({ type: ResultType.data, result: undefined });\n };\n\n return {\n ...match,\n shouldLoad,\n resolve,\n };\n });\n\n // Send all matches here to allow for a middleware-type implementation.\n // handler will be a no-op for unneeded routes and we filter those results\n // back out below.\n let results = await dataStrategyImpl({\n matches: dsMatches,\n request,\n params: matches[0].params,\n fetcherKey,\n context: requestContext,\n });\n\n // Wait for all routes to load here but 'swallow the error since we want\n // it to bubble up from the `await loadRoutePromise` in `callLoaderOrAction` -\n // called from `match.resolve()`\n try {\n await Promise.all(loadRouteDefinitionsPromises);\n } catch (e) {\n // No-op\n }\n\n return results;\n}\n\n// Default logic for calling a loader/action is the user has no specified a dataStrategy\nasync function callLoaderOrAction(\n type: \"loader\" | \"action\",\n request: Request,\n match: AgnosticDataRouteMatch,\n loadRoutePromise: Promise | undefined,\n handlerOverride: Parameters[0],\n staticContext?: unknown\n): Promise {\n let result: DataStrategyResult;\n let onReject: (() => void) | undefined;\n\n let runHandler = (\n handler: AgnosticRouteObject[\"loader\"] | AgnosticRouteObject[\"action\"]\n ): Promise => {\n // Setup a promise we can race against so that abort signals short circuit\n let reject: () => void;\n // This will never resolve so safe to type it as Promise to\n // satisfy the function return value\n let abortPromise = new Promise((_, r) => (reject = r));\n onReject = () => reject();\n request.signal.addEventListener(\"abort\", onReject);\n\n let actualHandler = (ctx?: unknown) => {\n if (typeof handler !== \"function\") {\n return Promise.reject(\n new Error(\n `You cannot call the handler for a route which defines a boolean ` +\n `\"${type}\" [routeId: ${match.route.id}]`\n )\n );\n }\n return handler(\n {\n request,\n params: match.params,\n context: staticContext,\n },\n ...(ctx !== undefined ? [ctx] : [])\n );\n };\n\n let handlerPromise: Promise = (async () => {\n try {\n let val = await (handlerOverride\n ? handlerOverride((ctx: unknown) => actualHandler(ctx))\n : actualHandler());\n return { type: \"data\", result: val };\n } catch (e) {\n return { type: \"error\", result: e };\n }\n })();\n\n return Promise.race([handlerPromise, abortPromise]);\n };\n\n try {\n let handler = match.route[type];\n\n // If we have a route.lazy promise, await that first\n if (loadRoutePromise) {\n if (handler) {\n // Run statically defined handler in parallel with lazy()\n let handlerError;\n let [value] = await Promise.all([\n // If the handler throws, don't let it immediately bubble out,\n // since we need to let the lazy() execution finish so we know if this\n // route has a boundary that can handle the error\n runHandler(handler).catch((e) => {\n handlerError = e;\n }),\n loadRoutePromise,\n ]);\n if (handlerError !== undefined) {\n throw handlerError;\n }\n result = value!;\n } else {\n // Load lazy route module, then run any returned handler\n await loadRoutePromise;\n\n handler = match.route[type];\n if (handler) {\n // Handler still runs even if we got interrupted to maintain consistency\n // with un-abortable behavior of handler execution on non-lazy or\n // previously-lazy-loaded routes\n result = await runHandler(handler);\n } else if (type === \"action\") {\n let url = new URL(request.url);\n let pathname = url.pathname + url.search;\n throw getInternalRouterError(405, {\n method: request.method,\n pathname,\n routeId: match.route.id,\n });\n } else {\n // lazy() route has no loader to run. Short circuit here so we don't\n // hit the invariant below that errors on returning undefined.\n return { type: ResultType.data, result: undefined };\n }\n }\n } else if (!handler) {\n let url = new URL(request.url);\n let pathname = url.pathname + url.search;\n throw getInternalRouterError(404, {\n pathname,\n });\n } else {\n result = await runHandler(handler);\n }\n\n invariant(\n result.result !== undefined,\n `You defined ${type === \"action\" ? \"an action\" : \"a loader\"} for route ` +\n `\"${match.route.id}\" but didn't return anything from your \\`${type}\\` ` +\n `function. Please return a value or \\`null\\`.`\n );\n } catch (e) {\n // We should already be catching and converting normal handler executions to\n // DataStrategyResults and returning them, so anything that throws here is an\n // unexpected error we still need to wrap\n return { type: ResultType.error, result: e };\n } finally {\n if (onReject) {\n request.signal.removeEventListener(\"abort\", onReject);\n }\n }\n\n return result;\n}\n\nasync function convertDataStrategyResultToDataResult(\n dataStrategyResult: DataStrategyResult\n): Promise {\n let { result, type } = dataStrategyResult;\n\n if (isResponse(result)) {\n let data: any;\n\n try {\n let contentType = result.headers.get(\"Content-Type\");\n // Check between word boundaries instead of startsWith() due to the last\n // paragraph of https://httpwg.org/specs/rfc9110.html#field.content-type\n if (contentType && /\\bapplication\\/json\\b/.test(contentType)) {\n if (result.body == null) {\n data = null;\n } else {\n data = await result.json();\n }\n } else {\n data = await result.text();\n }\n } catch (e) {\n return { type: ResultType.error, error: e };\n }\n\n if (type === ResultType.error) {\n return {\n type: ResultType.error,\n error: new ErrorResponseImpl(result.status, result.statusText, data),\n statusCode: result.status,\n headers: result.headers,\n };\n }\n\n return {\n type: ResultType.data,\n data,\n statusCode: result.status,\n headers: result.headers,\n };\n }\n\n if (type === ResultType.error) {\n if (isDataWithResponseInit(result)) {\n if (result.data instanceof Error) {\n return {\n type: ResultType.error,\n error: result.data,\n statusCode: result.init?.status,\n headers: result.init?.headers\n ? new Headers(result.init.headers)\n : undefined,\n };\n }\n\n // Convert thrown data() to ErrorResponse instances\n return {\n type: ResultType.error,\n error: new ErrorResponseImpl(\n result.init?.status || 500,\n undefined,\n result.data\n ),\n statusCode: isRouteErrorResponse(result) ? result.status : undefined,\n headers: result.init?.headers\n ? new Headers(result.init.headers)\n : undefined,\n };\n }\n return {\n type: ResultType.error,\n error: result,\n statusCode: isRouteErrorResponse(result) ? result.status : undefined,\n };\n }\n\n if (isDeferredData(result)) {\n return {\n type: ResultType.deferred,\n deferredData: result,\n statusCode: result.init?.status,\n headers: result.init?.headers && new Headers(result.init.headers),\n };\n }\n\n if (isDataWithResponseInit(result)) {\n return {\n type: ResultType.data,\n data: result.data,\n statusCode: result.init?.status,\n headers: result.init?.headers\n ? new Headers(result.init.headers)\n : undefined,\n };\n }\n\n return { type: ResultType.data, data: result };\n}\n\n// Support relative routing in internal redirects\nfunction normalizeRelativeRoutingRedirectResponse(\n response: Response,\n request: Request,\n routeId: string,\n matches: AgnosticDataRouteMatch[],\n basename: string,\n v7_relativeSplatPath: boolean\n) {\n let location = response.headers.get(\"Location\");\n invariant(\n location,\n \"Redirects returned/thrown from loaders/actions must have a Location header\"\n );\n\n if (!ABSOLUTE_URL_REGEX.test(location)) {\n let trimmedMatches = matches.slice(\n 0,\n matches.findIndex((m) => m.route.id === routeId) + 1\n );\n location = normalizeTo(\n new URL(request.url),\n trimmedMatches,\n basename,\n true,\n location,\n v7_relativeSplatPath\n );\n response.headers.set(\"Location\", location);\n }\n\n return response;\n}\n\nfunction normalizeRedirectLocation(\n location: string,\n currentUrl: URL,\n basename: string,\n historyInstance: History,\n): string {\n // Match Chrome's behavior:\n // https://github.com/chromium/chromium/blob/216dbeb61db0c667e62082e5f5400a32d6983df3/content/public/common/url_utils.cc#L82\n let invalidProtocols = [\n \"about:\",\n \"blob:\",\n \"chrome:\",\n \"chrome-untrusted:\",\n \"content:\",\n \"data:\",\n \"devtools:\",\n \"file:\",\n \"filesystem:\",\n // eslint-disable-next-line no-script-url\n \"javascript:\",\n ];\n\n if (ABSOLUTE_URL_REGEX.test(location)) {\n // Strip off the protocol+origin for same-origin + same-basename absolute redirects\n let normalizedLocation = location;\n let url = normalizedLocation.startsWith(\"//\")\n ? new URL(currentUrl.protocol + normalizedLocation)\n : new URL(normalizedLocation);\n if (invalidProtocols.includes(url.protocol)) {\n throw new Error(\"Invalid redirect location\");\n }\n let isSameBasename = stripBasename(url.pathname, basename) != null;\n if (url.origin === currentUrl.origin && isSameBasename) {\n return removeDoubleSlashes(url.pathname) + url.search + url.hash;\n }\n }\n\n try {\n let url = historyInstance.createURL(location);\n if (invalidProtocols.includes(url.protocol)) {\n throw new Error(\"Invalid redirect location\");\n }\n } catch (e) {}\n\n return location;\n}\n\n// Utility method for creating the Request instances for loaders/actions during\n// client-side navigations and fetches. During SSR we will always have a\n// Request instance from the static handler (query/queryRoute)\nfunction createClientSideRequest(\n history: History,\n location: string | Location,\n signal: AbortSignal,\n submission?: Submission\n): Request {\n let url = history.createURL(stripHashFromPath(location)).toString();\n let init: RequestInit = { signal };\n\n if (submission && isMutationMethod(submission.formMethod)) {\n let { formMethod, formEncType } = submission;\n // Didn't think we needed this but it turns out unlike other methods, patch\n // won't be properly normalized to uppercase and results in a 405 error.\n // See: https://fetch.spec.whatwg.org/#concept-method\n init.method = formMethod.toUpperCase();\n\n if (formEncType === \"application/json\") {\n init.headers = new Headers({ \"Content-Type\": formEncType });\n init.body = JSON.stringify(submission.json);\n } else if (formEncType === \"text/plain\") {\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n init.body = submission.text;\n } else if (\n formEncType === \"application/x-www-form-urlencoded\" &&\n submission.formData\n ) {\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n init.body = convertFormDataToSearchParams(submission.formData);\n } else {\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n init.body = submission.formData;\n }\n }\n\n return new Request(url, init);\n}\n\nfunction convertFormDataToSearchParams(formData: FormData): URLSearchParams {\n let searchParams = new URLSearchParams();\n\n for (let [key, value] of formData.entries()) {\n // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#converting-an-entry-list-to-a-list-of-name-value-pairs\n searchParams.append(key, typeof value === \"string\" ? value : value.name);\n }\n\n return searchParams;\n}\n\nfunction convertSearchParamsToFormData(\n searchParams: URLSearchParams\n): FormData {\n let formData = new FormData();\n for (let [key, value] of searchParams.entries()) {\n formData.append(key, value);\n }\n return formData;\n}\n\nfunction processRouteLoaderData(\n matches: AgnosticDataRouteMatch[],\n results: Record,\n pendingActionResult: PendingActionResult | undefined,\n activeDeferreds: Map,\n skipLoaderErrorBubbling: boolean\n): {\n loaderData: RouterState[\"loaderData\"];\n errors: RouterState[\"errors\"] | null;\n statusCode: number;\n loaderHeaders: Record;\n} {\n // Fill in loaderData/errors from our loaders\n let loaderData: RouterState[\"loaderData\"] = {};\n let errors: RouterState[\"errors\"] | null = null;\n let statusCode: number | undefined;\n let foundError = false;\n let loaderHeaders: Record = {};\n let pendingError =\n pendingActionResult && isErrorResult(pendingActionResult[1])\n ? pendingActionResult[1].error\n : undefined;\n\n // Process loader results into state.loaderData/state.errors\n matches.forEach((match) => {\n if (!(match.route.id in results)) {\n return;\n }\n let id = match.route.id;\n let result = results[id];\n invariant(\n !isRedirectResult(result),\n \"Cannot handle redirect results in processLoaderData\"\n );\n if (isErrorResult(result)) {\n let error = result.error;\n // If we have a pending action error, we report it at the highest-route\n // that throws a loader error, and then clear it out to indicate that\n // it was consumed\n if (pendingError !== undefined) {\n error = pendingError;\n pendingError = undefined;\n }\n\n errors = errors || {};\n\n if (skipLoaderErrorBubbling) {\n errors[id] = error;\n } else {\n // Look upwards from the matched route for the closest ancestor error\n // boundary, defaulting to the root match. Prefer higher error values\n // if lower errors bubble to the same boundary\n let boundaryMatch = findNearestBoundary(matches, id);\n if (errors[boundaryMatch.route.id] == null) {\n errors[boundaryMatch.route.id] = error;\n }\n }\n\n // Clear our any prior loaderData for the throwing route\n loaderData[id] = undefined;\n\n // Once we find our first (highest) error, we set the status code and\n // prevent deeper status codes from overriding\n if (!foundError) {\n foundError = true;\n statusCode = isRouteErrorResponse(result.error)\n ? result.error.status\n : 500;\n }\n if (result.headers) {\n loaderHeaders[id] = result.headers;\n }\n } else {\n if (isDeferredResult(result)) {\n activeDeferreds.set(id, result.deferredData);\n loaderData[id] = result.deferredData.data;\n // Error status codes always override success status codes, but if all\n // loaders are successful we take the deepest status code.\n if (\n result.statusCode != null &&\n result.statusCode !== 200 &&\n !foundError\n ) {\n statusCode = result.statusCode;\n }\n if (result.headers) {\n loaderHeaders[id] = result.headers;\n }\n } else {\n loaderData[id] = result.data;\n // Error status codes always override success status codes, but if all\n // loaders are successful we take the deepest status code.\n if (result.statusCode && result.statusCode !== 200 && !foundError) {\n statusCode = result.statusCode;\n }\n if (result.headers) {\n loaderHeaders[id] = result.headers;\n }\n }\n }\n });\n\n // If we didn't consume the pending action error (i.e., all loaders\n // resolved), then consume it here. Also clear out any loaderData for the\n // throwing route\n if (pendingError !== undefined && pendingActionResult) {\n errors = { [pendingActionResult[0]]: pendingError };\n loaderData[pendingActionResult[0]] = undefined;\n }\n\n return {\n loaderData,\n errors,\n statusCode: statusCode || 200,\n loaderHeaders,\n };\n}\n\nfunction processLoaderData(\n state: RouterState,\n matches: AgnosticDataRouteMatch[],\n results: Record,\n pendingActionResult: PendingActionResult | undefined,\n revalidatingFetchers: RevalidatingFetcher[],\n fetcherResults: Record,\n activeDeferreds: Map\n): {\n loaderData: RouterState[\"loaderData\"];\n errors?: RouterState[\"errors\"];\n} {\n let { loaderData, errors } = processRouteLoaderData(\n matches,\n results,\n pendingActionResult,\n activeDeferreds,\n false // This method is only called client side so we always want to bubble\n );\n\n // Process results from our revalidating fetchers\n revalidatingFetchers.forEach((rf) => {\n let { key, match, controller } = rf;\n let result = fetcherResults[key];\n invariant(result, \"Did not find corresponding fetcher result\");\n\n // Process fetcher non-redirect errors\n if (controller && controller.signal.aborted) {\n // Nothing to do for aborted fetchers\n return;\n } else if (isErrorResult(result)) {\n let boundaryMatch = findNearestBoundary(state.matches, match?.route.id);\n if (!(errors && errors[boundaryMatch.route.id])) {\n errors = {\n ...errors,\n [boundaryMatch.route.id]: result.error,\n };\n }\n state.fetchers.delete(key);\n } else if (isRedirectResult(result)) {\n // Should never get here, redirects should get processed above, but we\n // keep this to type narrow to a success result in the else\n invariant(false, \"Unhandled fetcher revalidation redirect\");\n } else if (isDeferredResult(result)) {\n // Should never get here, deferred data should be awaited for fetchers\n // in resolveDeferredResults\n invariant(false, \"Unhandled fetcher deferred data\");\n } else {\n let doneFetcher = getDoneFetcher(result.data);\n state.fetchers.set(key, doneFetcher);\n }\n });\n\n return { loaderData, errors };\n}\n\nfunction mergeLoaderData(\n loaderData: RouteData,\n newLoaderData: RouteData,\n matches: AgnosticDataRouteMatch[],\n errors: RouteData | null | undefined\n): RouteData {\n let mergedLoaderData = { ...newLoaderData };\n for (let match of matches) {\n let id = match.route.id;\n if (newLoaderData.hasOwnProperty(id)) {\n if (newLoaderData[id] !== undefined) {\n mergedLoaderData[id] = newLoaderData[id];\n } else {\n // No-op - this is so we ignore existing data if we have a key in the\n // incoming object with an undefined value, which is how we unset a prior\n // loaderData if we encounter a loader error\n }\n } else if (loaderData[id] !== undefined && match.route.loader) {\n // Preserve existing keys not included in newLoaderData and where a loader\n // wasn't removed by HMR\n mergedLoaderData[id] = loaderData[id];\n }\n\n if (errors && errors.hasOwnProperty(id)) {\n // Don't keep any loader data below the boundary\n break;\n }\n }\n return mergedLoaderData;\n}\n\nfunction getActionDataForCommit(\n pendingActionResult: PendingActionResult | undefined\n) {\n if (!pendingActionResult) {\n return {};\n }\n return isErrorResult(pendingActionResult[1])\n ? {\n // Clear out prior actionData on errors\n actionData: {},\n }\n : {\n actionData: {\n [pendingActionResult[0]]: pendingActionResult[1].data,\n },\n };\n}\n\n// Find the nearest error boundary, looking upwards from the leaf route (or the\n// route specified by routeId) for the closest ancestor error boundary,\n// defaulting to the root match\nfunction findNearestBoundary(\n matches: AgnosticDataRouteMatch[],\n routeId?: string\n): AgnosticDataRouteMatch {\n let eligibleMatches = routeId\n ? matches.slice(0, matches.findIndex((m) => m.route.id === routeId) + 1)\n : [...matches];\n return (\n eligibleMatches.reverse().find((m) => m.route.hasErrorBoundary === true) ||\n matches[0]\n );\n}\n\nfunction getShortCircuitMatches(routes: AgnosticDataRouteObject[]): {\n matches: AgnosticDataRouteMatch[];\n route: AgnosticDataRouteObject;\n} {\n // Prefer a root layout route if present, otherwise shim in a route object\n let route =\n routes.length === 1\n ? routes[0]\n : routes.find((r) => r.index || !r.path || r.path === \"/\") || {\n id: `__shim-error-route__`,\n };\n\n return {\n matches: [\n {\n params: {},\n pathname: \"\",\n pathnameBase: \"\",\n route,\n },\n ],\n route,\n };\n}\n\nfunction getInternalRouterError(\n status: number,\n {\n pathname,\n routeId,\n method,\n type,\n message,\n }: {\n pathname?: string;\n routeId?: string;\n method?: string;\n type?: \"defer-action\" | \"invalid-body\";\n message?: string;\n } = {}\n) {\n let statusText = \"Unknown Server Error\";\n let errorMessage = \"Unknown @remix-run/router error\";\n\n if (status === 400) {\n statusText = \"Bad Request\";\n if (method && pathname && routeId) {\n errorMessage =\n `You made a ${method} request to \"${pathname}\" but ` +\n `did not provide a \\`loader\\` for route \"${routeId}\", ` +\n `so there is no way to handle the request.`;\n } else if (type === \"defer-action\") {\n errorMessage = \"defer() is not supported in actions\";\n } else if (type === \"invalid-body\") {\n errorMessage = \"Unable to encode submission body\";\n }\n } else if (status === 403) {\n statusText = \"Forbidden\";\n errorMessage = `Route \"${routeId}\" does not match URL \"${pathname}\"`;\n } else if (status === 404) {\n statusText = \"Not Found\";\n errorMessage = `No route matches URL \"${pathname}\"`;\n } else if (status === 405) {\n statusText = \"Method Not Allowed\";\n if (method && pathname && routeId) {\n errorMessage =\n `You made a ${method.toUpperCase()} request to \"${pathname}\" but ` +\n `did not provide an \\`action\\` for route \"${routeId}\", ` +\n `so there is no way to handle the request.`;\n } else if (method) {\n errorMessage = `Invalid request method \"${method.toUpperCase()}\"`;\n }\n }\n\n return new ErrorResponseImpl(\n status || 500,\n statusText,\n new Error(errorMessage),\n true\n );\n}\n\n// Find any returned redirect errors, starting from the lowest match\nfunction findRedirect(\n results: Record\n): { key: string; result: RedirectResult } | undefined {\n let entries = Object.entries(results);\n for (let i = entries.length - 1; i >= 0; i--) {\n let [key, result] = entries[i];\n if (isRedirectResult(result)) {\n return { key, result };\n }\n }\n}\n\nfunction stripHashFromPath(path: To) {\n let parsedPath = typeof path === \"string\" ? parsePath(path) : path;\n return createPath({ ...parsedPath, hash: \"\" });\n}\n\nfunction isHashChangeOnly(a: Location, b: Location): boolean {\n if (a.pathname !== b.pathname || a.search !== b.search) {\n return false;\n }\n\n if (a.hash === \"\") {\n // /page -> /page#hash\n return b.hash !== \"\";\n } else if (a.hash === b.hash) {\n // /page#hash -> /page#hash\n return true;\n } else if (b.hash !== \"\") {\n // /page#hash -> /page#other\n return true;\n }\n\n // If the hash is removed the browser will re-perform a request to the server\n // /page#hash -> /page\n return false;\n}\n\nfunction isPromise(val: unknown): val is Promise {\n return typeof val === \"object\" && val != null && \"then\" in val;\n}\n\nfunction isDataStrategyResult(result: unknown): result is DataStrategyResult {\n return (\n result != null &&\n typeof result === \"object\" &&\n \"type\" in result &&\n \"result\" in result &&\n (result.type === ResultType.data || result.type === ResultType.error)\n );\n}\n\nfunction isRedirectDataStrategyResultResult(result: DataStrategyResult) {\n return (\n isResponse(result.result) && redirectStatusCodes.has(result.result.status)\n );\n}\n\nfunction isDeferredResult(result: DataResult): result is DeferredResult {\n return result.type === ResultType.deferred;\n}\n\nfunction isErrorResult(result: DataResult): result is ErrorResult {\n return result.type === ResultType.error;\n}\n\nfunction isRedirectResult(result?: DataResult): result is RedirectResult {\n return (result && result.type) === ResultType.redirect;\n}\n\nexport function isDataWithResponseInit(\n value: any\n): value is DataWithResponseInit {\n return (\n typeof value === \"object\" &&\n value != null &&\n \"type\" in value &&\n \"data\" in value &&\n \"init\" in value &&\n value.type === \"DataWithResponseInit\"\n );\n}\n\nexport function isDeferredData(value: any): value is DeferredData {\n let deferred: DeferredData = value;\n return (\n deferred &&\n typeof deferred === \"object\" &&\n typeof deferred.data === \"object\" &&\n typeof deferred.subscribe === \"function\" &&\n typeof deferred.cancel === \"function\" &&\n typeof deferred.resolveData === \"function\"\n );\n}\n\nfunction isResponse(value: any): value is Response {\n return (\n value != null &&\n typeof value.status === \"number\" &&\n typeof value.statusText === \"string\" &&\n typeof value.headers === \"object\" &&\n typeof value.body !== \"undefined\"\n );\n}\n\nfunction isRedirectResponse(result: any): result is Response {\n if (!isResponse(result)) {\n return false;\n }\n\n let status = result.status;\n let location = result.headers.get(\"Location\");\n return status >= 300 && status <= 399 && location != null;\n}\n\nfunction isValidMethod(method: string): method is FormMethod | V7_FormMethod {\n return validRequestMethods.has(method.toLowerCase() as FormMethod);\n}\n\nfunction isMutationMethod(\n method: string\n): method is MutationFormMethod | V7_MutationFormMethod {\n return validMutationMethods.has(method.toLowerCase() as MutationFormMethod);\n}\n\nasync function resolveNavigationDeferredResults(\n matches: (AgnosticDataRouteMatch | null)[],\n results: Record,\n signal: AbortSignal,\n currentMatches: AgnosticDataRouteMatch[],\n currentLoaderData: RouteData\n) {\n let entries = Object.entries(results);\n for (let index = 0; index < entries.length; index++) {\n let [routeId, result] = entries[index];\n let match = matches.find((m) => m?.route.id === routeId);\n // If we don't have a match, then we can have a deferred result to do\n // anything with. This is for revalidating fetchers where the route was\n // removed during HMR\n if (!match) {\n continue;\n }\n\n let currentMatch = currentMatches.find(\n (m) => m.route.id === match!.route.id\n );\n let isRevalidatingLoader =\n currentMatch != null &&\n !isNewRouteInstance(currentMatch, match) &&\n (currentLoaderData && currentLoaderData[match.route.id]) !== undefined;\n\n if (isDeferredResult(result) && isRevalidatingLoader) {\n // Note: we do not have to touch activeDeferreds here since we race them\n // against the signal in resolveDeferredData and they'll get aborted\n // there if needed\n await resolveDeferredData(result, signal, false).then((result) => {\n if (result) {\n results[routeId] = result;\n }\n });\n }\n }\n}\n\nasync function resolveFetcherDeferredResults(\n matches: (AgnosticDataRouteMatch | null)[],\n results: Record,\n revalidatingFetchers: RevalidatingFetcher[]\n) {\n for (let index = 0; index < revalidatingFetchers.length; index++) {\n let { key, routeId, controller } = revalidatingFetchers[index];\n let result = results[key];\n let match = matches.find((m) => m?.route.id === routeId);\n // If we don't have a match, then we can have a deferred result to do\n // anything with. This is for revalidating fetchers where the route was\n // removed during HMR\n if (!match) {\n continue;\n }\n\n if (isDeferredResult(result)) {\n // Note: we do not have to touch activeDeferreds here since we race them\n // against the signal in resolveDeferredData and they'll get aborted\n // there if needed\n invariant(\n controller,\n \"Expected an AbortController for revalidating fetcher deferred result\"\n );\n await resolveDeferredData(result, controller.signal, true).then(\n (result) => {\n if (result) {\n results[key] = result;\n }\n }\n );\n }\n }\n}\n\nasync function resolveDeferredData(\n result: DeferredResult,\n signal: AbortSignal,\n unwrap = false\n): Promise {\n let aborted = await result.deferredData.resolveData(signal);\n if (aborted) {\n return;\n }\n\n if (unwrap) {\n try {\n return {\n type: ResultType.data,\n data: result.deferredData.unwrappedData,\n };\n } catch (e) {\n // Handle any TrackedPromise._error values encountered while unwrapping\n return {\n type: ResultType.error,\n error: e,\n };\n }\n }\n\n return {\n type: ResultType.data,\n data: result.deferredData.data,\n };\n}\n\nfunction hasNakedIndexQuery(search: string): boolean {\n return new URLSearchParams(search).getAll(\"index\").some((v) => v === \"\");\n}\n\nfunction getTargetMatch(\n matches: AgnosticDataRouteMatch[],\n location: Location | string\n) {\n let search =\n typeof location === \"string\" ? parsePath(location).search : location.search;\n if (\n matches[matches.length - 1].route.index &&\n hasNakedIndexQuery(search || \"\")\n ) {\n // Return the leaf index route when index is present\n return matches[matches.length - 1];\n }\n // Otherwise grab the deepest \"path contributing\" match (ignoring index and\n // pathless layout routes)\n let pathMatches = getPathContributingMatches(matches);\n return pathMatches[pathMatches.length - 1];\n}\n\nfunction getSubmissionFromNavigation(\n navigation: Navigation\n): Submission | undefined {\n let { formMethod, formAction, formEncType, text, formData, json } =\n navigation;\n if (!formMethod || !formAction || !formEncType) {\n return;\n }\n\n if (text != null) {\n return {\n formMethod,\n formAction,\n formEncType,\n formData: undefined,\n json: undefined,\n text,\n };\n } else if (formData != null) {\n return {\n formMethod,\n formAction,\n formEncType,\n formData,\n json: undefined,\n text: undefined,\n };\n } else if (json !== undefined) {\n return {\n formMethod,\n formAction,\n formEncType,\n formData: undefined,\n json,\n text: undefined,\n };\n }\n}\n\nfunction getLoadingNavigation(\n location: Location,\n submission?: Submission\n): NavigationStates[\"Loading\"] {\n if (submission) {\n let navigation: NavigationStates[\"Loading\"] = {\n state: \"loading\",\n location,\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n };\n return navigation;\n } else {\n let navigation: NavigationStates[\"Loading\"] = {\n state: \"loading\",\n location,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n };\n return navigation;\n }\n}\n\nfunction getSubmittingNavigation(\n location: Location,\n submission: Submission\n): NavigationStates[\"Submitting\"] {\n let navigation: NavigationStates[\"Submitting\"] = {\n state: \"submitting\",\n location,\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n };\n return navigation;\n}\n\nfunction getLoadingFetcher(\n submission?: Submission,\n data?: Fetcher[\"data\"]\n): FetcherStates[\"Loading\"] {\n if (submission) {\n let fetcher: FetcherStates[\"Loading\"] = {\n state: \"loading\",\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n data,\n };\n return fetcher;\n } else {\n let fetcher: FetcherStates[\"Loading\"] = {\n state: \"loading\",\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n data,\n };\n return fetcher;\n }\n}\n\nfunction getSubmittingFetcher(\n submission: Submission,\n existingFetcher?: Fetcher\n): FetcherStates[\"Submitting\"] {\n let fetcher: FetcherStates[\"Submitting\"] = {\n state: \"submitting\",\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n data: existingFetcher ? existingFetcher.data : undefined,\n };\n return fetcher;\n}\n\nfunction getDoneFetcher(data: Fetcher[\"data\"]): FetcherStates[\"Idle\"] {\n let fetcher: FetcherStates[\"Idle\"] = {\n state: \"idle\",\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n data,\n };\n return fetcher;\n}\n\nfunction restoreAppliedTransitions(\n _window: Window,\n transitions: Map>\n) {\n try {\n let sessionPositions = _window.sessionStorage.getItem(\n TRANSITIONS_STORAGE_KEY\n );\n if (sessionPositions) {\n let json = JSON.parse(sessionPositions);\n for (let [k, v] of Object.entries(json || {})) {\n if (v && Array.isArray(v)) {\n transitions.set(k, new Set(v || []));\n }\n }\n }\n } catch (e) {\n // no-op, use default empty object\n }\n}\n\nfunction persistAppliedTransitions(\n _window: Window,\n transitions: Map>\n) {\n if (transitions.size > 0) {\n let json: Record = {};\n for (let [k, v] of transitions) {\n json[k] = [...v];\n }\n try {\n _window.sessionStorage.setItem(\n TRANSITIONS_STORAGE_KEY,\n JSON.stringify(json)\n );\n } catch (error) {\n warning(\n false,\n `Failed to save applied view transitions in sessionStorage (${error}).`\n );\n }\n }\n}\n//#endregion\n"],"names":["Action","PopStateEventType","createMemoryHistory","options","initialEntries","initialIndex","v5Compat","entries","map","entry","index","createMemoryLocation","state","undefined","clampIndex","length","action","Pop","listener","n","Math","min","max","getCurrentLocation","to","key","location","createLocation","pathname","warning","charAt","JSON","stringify","createHref","createPath","history","createURL","URL","encodeLocation","path","parsePath","search","hash","push","Push","nextLocation","splice","delta","replace","Replace","go","nextIndex","listen","fn","createBrowserHistory","createBrowserLocation","window","globalHistory","usr","createBrowserHref","getUrlBasedHistory","createHashHistory","createHashLocation","substr","startsWith","createHashHref","base","document","querySelector","href","getAttribute","url","hashIndex","indexOf","slice","validateHashLocation","invariant","value","message","Error","cond","console","warn","e","createKey","random","toString","getHistoryState","idx","current","_extends","_ref","parsedPath","searchIndex","getLocation","validateLocation","defaultView","getIndex","replaceState","handlePop","historyState","pushState","error","DOMException","name","assign","origin","addEventListener","removeEventListener","ResultType","immutableRouteKeys","Set","isIndexRoute","route","convertRoutesToDataRoutes","routes","mapRouteProperties","parentPath","manifest","treePath","String","id","join","children","indexRoute","pathOrLayoutRoute","matchRoutes","locationArg","basename","matchRoutesImpl","allowPartial","stripBasename","branches","flattenRoutes","rankRouteBranches","matches","decoded","decodePath","i","matchRouteBranch","convertRouteMatchToUiMatch","match","loaderData","params","data","handle","parentsMeta","flattenRoute","relativePath","meta","caseSensitive","childrenIndex","joinPaths","routesMeta","concat","score","computeScore","forEach","_route$path","includes","exploded","explodeOptionalSegments","segments","split","first","rest","isOptional","endsWith","required","restExploded","result","subpath","sort","a","b","compareIndexes","paramRe","dynamicSegmentValue","indexRouteValue","emptySegmentValue","staticSegmentValue","splatPenalty","isSplat","s","initialScore","some","filter","reduce","segment","test","siblings","every","branch","matchedParams","matchedPathname","end","remainingPathname","matchPath","Object","pathnameBase","normalizePathname","generatePath","originalPath","prefix","p","array","isLastSegment","star","keyMatch","optional","param","pattern","matcher","compiledParams","compilePath","captureGroups","memo","paramName","splatValue","regexpSource","_","RegExp","v","decodeURIComponent","toLowerCase","startIndex","nextChar","resolvePath","fromPathname","toPathname","removeDoubleSlashes","resolvePathname","substring","normalizeSearch","normalizeHash","relativeSegments","pop","getInvalidPathError","char","field","dest","getPathContributingMatches","getResolveToMatches","v7_relativeSplatPath","pathMatches","resolveTo","toArg","routePathnames","locationPathname","isPathRelative","isEmptyPath","from","routePathnameIndex","toSegments","shift","hasExplicitTrailingSlash","hasCurrentTrailingSlash","getToPathname","paths","json","init","responseInit","status","headers","Headers","has","set","Response","DataWithResponseInit","constructor","type","AbortedDeferredError","DeferredData","pendingKeysSet","subscribers","deferredKeys","Array","isArray","reject","abortPromise","Promise","r","controller","AbortController","onAbort","unlistenAbortSignal","signal","acc","_ref2","trackPromise","done","add","promise","race","then","onSettle","catch","defineProperty","get","aborted","delete","undefinedError","emit","settledKey","subscriber","subscribe","cancel","abort","k","resolveData","resolve","size","unwrappedData","_ref3","unwrapTrackedPromise","pendingKeys","isTrackedPromise","_tracked","_error","_data","defer","redirect","redirectDocument","response","ErrorResponseImpl","statusText","internal","isRouteErrorResponse","validMutationMethodsArr","validMutationMethods","validRequestMethodsArr","validRequestMethods","redirectStatusCodes","redirectPreserveMethodStatusCodes","IDLE_NAVIGATION","formMethod","formAction","formEncType","formData","text","IDLE_FETCHER","IDLE_BLOCKER","proceed","reset","ABSOLUTE_URL_REGEX","defaultMapRouteProperties","hasErrorBoundary","Boolean","TRANSITIONS_STORAGE_KEY","createRouter","routerWindow","isBrowser","createElement","isServer","detectErrorBoundary","dataRoutes","inFlightDataRoutes","dataStrategyImpl","dataStrategy","defaultDataStrategy","patchRoutesOnNavigationImpl","patchRoutesOnNavigation","future","v7_fetcherPersist","v7_normalizeFormMethod","v7_partialHydration","v7_prependBasename","v7_skipActionErrorRevalidation","unlistenHistory","savedScrollPositions","getScrollRestorationKey","getScrollPosition","initialScrollRestored","hydrationData","initialMatches","initialMatchesIsFOW","initialErrors","getInternalRouterError","getShortCircuitMatches","fogOfWar","checkFogOfWar","active","initialized","m","lazy","loader","errors","findIndex","shouldLoadRouteOnHydration","router","historyAction","navigation","restoreScrollPosition","preventScrollReset","revalidation","actionData","fetchers","Map","blockers","pendingAction","HistoryAction","pendingPreventScrollReset","pendingNavigationController","pendingViewTransitionEnabled","appliedViewTransitions","removePageHideEventListener","isUninterruptedRevalidation","isRevalidationRequired","cancelledDeferredRoutes","cancelledFetcherLoads","fetchControllers","incrementingLoadId","pendingNavigationLoadId","fetchReloadIds","fetchRedirectIds","fetchLoadMatches","activeFetchers","deletedFetchers","activeDeferreds","blockerFunctions","unblockBlockerHistoryUpdate","initialize","blockerKey","shouldBlockNavigation","currentLocation","nextHistoryUpdatePromise","updateBlocker","updateState","startNavigation","restoreAppliedTransitions","_saveAppliedTransitions","persistAppliedTransitions","initialHydration","dispose","clear","deleteFetcher","deleteBlocker","newState","opts","completedFetchers","deletedFetchersKeys","fetcher","viewTransitionOpts","flushSync","completeNavigation","_temp","_location$state","_location$state2","isActionReload","isMutationMethod","_isRedirect","keys","mergeLoaderData","priorPaths","toPaths","getSavedScrollPosition","navigate","normalizedPath","normalizeTo","fromRouteId","relative","submission","normalizeNavigateOptions","userReplace","pendingError","enableViewTransition","viewTransition","revalidate","interruptActiveLoads","startUninterruptedRevalidation","overrideNavigation","saveScrollPosition","routesToUse","loadingNavigation","isHashChangeOnly","notFoundMatches","handleNavigational404","request","createClientSideRequest","pendingActionResult","findNearestBoundary","actionResult","handleAction","shortCircuited","routeId","isErrorResult","getLoadingNavigation","updatedMatches","handleLoaders","fetcherSubmission","getActionDataForCommit","isFogOfWar","getSubmittingNavigation","discoverResult","discoverRoutes","boundaryId","partialMatches","actionMatch","getTargetMatch","method","results","callDataStrategy","isRedirectResult","normalizeRedirectLocation","startRedirectNavigation","isDeferredResult","boundaryMatch","activeSubmission","getSubmissionFromNavigation","shouldUpdateNavigationState","getUpdatedActionData","matchesToLoad","revalidatingFetchers","getMatchesToLoad","cancelActiveDeferreds","updatedFetchers","markFetchRedirectsDone","updates","getUpdatedRevalidatingFetchers","rf","abortFetcher","abortPendingFetchRevalidations","f","loaderResults","fetcherResults","callLoadersAndMaybeResolveData","findRedirect","processLoaderData","deferredData","didAbortFetchLoads","abortStaleFetchLoads","shouldUpdateFetchers","revalidatingFetcher","getLoadingFetcher","fetch","setFetcherError","handleFetcherAction","handleFetcherLoader","requestMatches","detectAndHandle405Error","existingFetcher","updateFetcherState","getSubmittingFetcher","abortController","fetchRequest","originatingLoadId","actionResults","getDoneFetcher","revalidationRequest","loadId","loadFetcher","staleKey","doneFetcher","resolveDeferredData","isNavigation","_temp2","redirectLocation","isDocumentReload","redirectHistoryAction","fetcherKey","dataResults","callDataStrategyImpl","isRedirectDataStrategyResultResult","normalizeRelativeRoutingRedirectResponse","convertDataStrategyResultToDataResult","fetchersToLoad","currentMatches","loaderResultsPromise","fetcherResultsPromise","all","resolveNavigationDeferredResults","resolveFetcherDeferredResults","getFetcher","deleteFetcherAndUpdateState","count","markFetchersDone","doneKeys","landedId","yeetedKeys","getBlocker","blocker","newBlocker","blockerFunction","predicate","cancelledRouteIds","dfd","enableScrollRestoration","positions","getPosition","getKey","y","getScrollKey","fogMatches","isNonHMR","localManifest","patch","patchRoutesImpl","newMatches","newPartialMatches","_internalSetRoutes","newRoutes","patchRoutes","_internalFetchControllers","_internalActiveDeferreds","UNSAFE_DEFERRED_SYMBOL","Symbol","createStaticHandler","v7_throwAbortReason","query","_temp3","requestContext","skipLoaderErrorBubbling","isValidMethod","methodNotAllowedMatches","statusCode","loaderHeaders","actionHeaders","queryImpl","isResponse","queryRoute","_temp4","find","values","_result$activeDeferre","routeMatch","submit","loadRouteData","isDataStrategyResult","isRedirectResponse","isRouteRequest","throwStaticHandlerAbortedError","Location","loaderRequest","Request","context","getLoaderMatchesUntilBoundary","processRouteLoaderData","executedLoaders","fromEntries","getStaticContextFromError","newContext","_deepestRenderedBoundaryId","reason","isSubmissionNavigation","body","prependBasename","contextualMatches","activeRouteMatch","nakedIndex","hasNakedIndexQuery","URLSearchParams","indexValues","getAll","append","qs","normalizeFormMethod","isFetcher","getInvalidBodyError","rawFormMethod","toUpperCase","stripHashFromPath","FormData","parse","searchParams","convertFormDataToSearchParams","convertSearchParamsToFormData","includeBoundary","skipActionErrorRevalidation","currentUrl","nextUrl","boundaryMatches","actionStatus","shouldSkipRevalidation","navigationMatches","isNewLoader","currentRouteMatch","nextRouteMatch","shouldRevalidateLoader","currentParams","nextParams","defaultShouldRevalidate","isNewRouteInstance","fetcherMatches","fetcherMatch","shouldRevalidate","hasData","hasError","hydrate","currentLoaderData","currentMatch","isNew","isMissingData","currentPath","loaderMatch","arg","routeChoice","_childrenToPatch","childrenToPatch","uniqueChildren","newRoute","existingRoute","isSameRoute","aChild","_existingRoute$childr","bChild","loadLazyRouteModule","lazyRoute","routeToUpdate","routeUpdates","lazyRouteProperty","staticRouteValue","isPropertyStaticallyDefined","_ref4","shouldLoad","loadRouteDefinitionsPromises","dsMatches","loadRoutePromise","handlerOverride","callLoaderOrAction","staticContext","onReject","runHandler","handler","actualHandler","ctx","handlerPromise","val","handlerError","dataStrategyResult","contentType","isDataWithResponseInit","_result$init3","_result$init4","_result$init","_result$init2","isDeferredData","_result$init5","_result$init6","deferred","_result$init7","_result$init8","trimmedMatches","historyInstance","invalidProtocols","normalizedLocation","protocol","isSameBasename","foundError","newLoaderData","mergedLoaderData","hasOwnProperty","eligibleMatches","reverse","_temp5","errorMessage","isRevalidatingLoader","unwrap","_window","transitions","sessionPositions","sessionStorage","getItem","setItem"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AACA;AACA;AAEA;;AAEG;IACSA,OAsBX;AAtBD,CAAA,UAAYA,MAAM,EAAA;AAChB;;;;;;AAMG;AACHA,EAAAA,MAAA,CAAA,KAAA,CAAA,GAAA,KAAW,CAAA;AAEX;;;;AAIG;AACHA,EAAAA,MAAA,CAAA,MAAA,CAAA,GAAA,MAAa,CAAA;AAEb;;;AAGG;AACHA,EAAAA,MAAA,CAAA,SAAA,CAAA,GAAA,SAAmB,CAAA;AACrB,CAAC,EAtBWA,MAAM,KAANA,MAAM,GAsBjB,EAAA,CAAA,CAAA,CAAA;AAqKD,MAAMC,iBAAiB,GAAG,UAAU,CAAA;AA+BpC;;;AAGG;AACa,SAAAC,mBAAmBA,CACjCC,OAAA,EAAkC;AAAA,E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C,EAAE;AACzBwhB,UAAAA,WAAW,CAAC5e,GAAG,CAAC0C,CAAC,EAAE,IAAIrM,GAAG,CAAC+G,CAAC,IAAI,EAAE,CAAC,CAAC,CAAA;AACrC,SAAA;AACF,OAAA;AACF,KAAA;GACF,CAAC,OAAO3I,CAAC,EAAE;AACV;AAAA,GAAA;AAEJ,CAAA;AAEA,SAAS4V,yBAAyBA,CAChCsU,OAAe,EACfC,WAAqC,EAAA;AAErC,EAAA,IAAIA,WAAW,CAAC/b,IAAI,GAAG,CAAC,EAAE;IACxB,IAAIpD,IAAI,GAA6B,EAAE,CAAA;IACvC,KAAK,IAAI,CAACiD,CAAC,EAAEtF,CAAC,CAAC,IAAIwhB,WAAW,EAAE;AAC9Bnf,MAAAA,IAAI,CAACiD,CAAC,CAAC,GAAG,CAAC,GAAGtF,CAAC,CAAC,CAAA;AACjB,KAAA;IACD,IAAI;AACFuhB,MAAAA,OAAO,CAACG,cAAc,CAACE,OAAO,CAC5B9Z,uBAAuB,EACvB7T,IAAI,CAACC,SAAS,CAACmO,IAAI,CAAC,CACrB,CAAA;KACF,CAAC,OAAO7J,KAAK,EAAE;AACdzE,MAAAA,OAAO,CACL,KAAK,EACyDyE,6DAAAA,GAAAA,KAAK,OAAI,CACxE,CAAA;AACF,KAAA;AACF,GAAA;AACH,CAAA;AACA;;;;"} apps/frontend/node_modules/@remix-run/router/dist/router.js:1091: this.subscribers = new Set(); apps/frontend/node_modules/@remix-run/router/dist/router.js:1168: this.subscribers.forEach(subscriber => subscriber(aborted, settledKey)); apps/frontend/node_modules/@remix-run/router/dist/router.js:1170: subscribe(fn) { apps/frontend/node_modules/@remix-run/router/dist/router.js:1171: this.subscribers.add(fn); apps/frontend/node_modules/@remix-run/router/dist/router.js:1172: return () => this.subscribers.delete(fn); apps/frontend/node_modules/@remix-run/router/dist/router.js:1185: this.subscribe(aborted => { apps/frontend/node_modules/@remix-run/router/dist/router.js:1392: let subscribers = new Set(); apps/frontend/node_modules/@remix-run/router/dist/router.js:1637: subscribers.clear(); apps/frontend/node_modules/@remix-run/router/dist/router.js:1643: function subscribe(fn) { apps/frontend/node_modules/@remix-run/router/dist/router.js:1644: subscribers.add(fn); apps/frontend/node_modules/@remix-run/router/dist/router.js:1645: return () => subscribers.delete(fn); apps/frontend/node_modules/@remix-run/router/dist/router.js:1679: // removing and adding a new subscriber due to the useCallback dependencies, apps/frontend/node_modules/@remix-run/router/dist/router.js:1680: // we don't get ourselves into a loop calling the new subscriber immediately apps/frontend/node_modules/@remix-run/router/dist/router.js:1681: [...subscribers].forEach(subscriber => subscriber(state, { apps/frontend/node_modules/@remix-run/router/dist/router.js:2312: // Wire up subscribers to update loaderData as promises settle apps/frontend/node_modules/@remix-run/router/dist/router.js:2314: deferredData.subscribe(aborted => { apps/frontend/node_modules/@remix-run/router/dist/router.js:3055: // we rely on the subscribers to do that so our tests can assert proper apps/frontend/node_modules/@remix-run/router/dist/router.js:3235: subscribe, apps/frontend/node_modules/@remix-run/router/dist/router.js:4780: return deferred && typeof deferred === "object" && typeof deferred.data === "object" && typeof deferred.subscribe === "function" && typeof deferred.cancel === "function" && typeof deferred.resolveData === "function"; apps/frontend/node_modules/@remix-run/router/dist/router.umd.min.js.map:1:{"version":3,"file":"router.umd.min.js","sources":["../history.ts","../utils.ts","../router.ts"],"sourcesContent":["////////////////////////////////////////////////////////////////////////////////\n//#region Types and Constants\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Actions represent the type of change to a location value.\n */\nexport enum Action {\n /**\n * A POP indicates a change to an arbitrary index in the history stack, such\n * as a back or forward navigation. It does not describe the direction of the\n * navigation, only that the current index changed.\n *\n * Note: This is the default action for newly created history objects.\n */\n Pop = \"POP\",\n\n /**\n * A PUSH indicates a new entry being added to the history stack, such as when\n * a link is clicked and a new page loads. When this happens, all subsequent\n * entries in the stack are lost.\n */\n Push = \"PUSH\",\n\n /**\n * A REPLACE indicates the entry at the current index in the history stack\n * being replaced by a new one.\n */\n Replace = \"REPLACE\",\n}\n\n/**\n * The pathname, search, and hash values of a URL.\n */\nexport interface Path {\n /**\n * A URL pathname, beginning with a /.\n */\n pathname: string;\n\n /**\n * A URL search string, beginning with a ?.\n */\n search: string;\n\n /**\n * A URL fragment identifier, beginning with a #.\n */\n hash: string;\n}\n\n// TODO: (v7) Change the Location generic default from `any` to `unknown` and\n// remove Remix `useLocation` wrapper.\n\n/**\n * An entry in a history stack. A location contains information about the\n * URL path, as well as possibly some arbitrary state and a key.\n */\nexport interface Location extends Path {\n /**\n * A value of arbitrary data associated with this location.\n */\n state: State;\n\n /**\n * A unique string associated with this location. May be used to safely store\n * and retrieve data in some other storage API, like `localStorage`.\n *\n * Note: This value is always \"default\" on the initial location.\n */\n key: string;\n}\n\n/**\n * A change to the current location.\n */\nexport interface Update {\n /**\n * The action that triggered the change.\n */\n action: Action;\n\n /**\n * The new location.\n */\n location: Location;\n\n /**\n * The delta between this location and the former location in the history stack\n */\n delta: number | null;\n}\n\n/**\n * A function that receives notifications about location changes.\n */\nexport interface Listener {\n (update: Update): void;\n}\n\n/**\n * Describes a location that is the destination of some navigation, either via\n * `history.push` or `history.replace`. This may be either a URL or the pieces\n * of a URL path.\n */\nexport type To = string | Partial;\n\n/**\n * A history is an interface to the navigation stack. The history serves as the\n * source of truth for the current location, as well as provides a set of\n * methods that may be used to change it.\n *\n * It is similar to the DOM's `window.history` object, but with a smaller, more\n * focused API.\n */\nexport interface History {\n /**\n * The last action that modified the current location. This will always be\n * Action.Pop when a history instance is first created. This value is mutable.\n */\n readonly action: Action;\n\n /**\n * The current location. This value is mutable.\n */\n readonly location: Location;\n\n /**\n * Returns a valid href for the given `to` value that may be used as\n * the value of an attribute.\n *\n * @param to - The destination URL\n */\n createHref(to: To): string;\n\n /**\n * Returns a URL for the given `to` value\n *\n * @param to - The destination URL\n */\n createURL(to: To): URL;\n\n /**\n * Encode a location the same way window.history would do (no-op for memory\n * history) so we ensure our PUSH/REPLACE navigations for data routers\n * behave the same as POP\n *\n * @param to Unencoded path\n */\n encodeLocation(to: To): Path;\n\n /**\n * Pushes a new location onto the history stack, increasing its length by one.\n * If there were any entries in the stack after the current one, they are\n * lost.\n *\n * @param to - The new URL\n * @param state - Data to associate with the new location\n */\n push(to: To, state?: any): void;\n\n /**\n * Replaces the current location in the history stack with a new one. The\n * location that was replaced will no longer be available.\n *\n * @param to - The new URL\n * @param state - Data to associate with the new location\n */\n replace(to: To, state?: any): void;\n\n /**\n * Navigates `n` entries backward/forward in the history stack relative to the\n * current index. For example, a \"back\" navigation would use go(-1).\n *\n * @param delta - The delta in the stack index\n */\n go(delta: number): void;\n\n /**\n * Sets up a listener that will be called whenever the current location\n * changes.\n *\n * @param listener - A function that will be called when the location changes\n * @returns unlisten - A function that may be used to stop listening\n */\n listen(listener: Listener): () => void;\n}\n\ntype HistoryState = {\n usr: any;\n key?: string;\n idx: number;\n};\n\nconst PopStateEventType = \"popstate\";\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Memory History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A user-supplied object that describes a location. Used when providing\n * entries to `createMemoryHistory` via its `initialEntries` option.\n */\nexport type InitialEntry = string | Partial;\n\nexport type MemoryHistoryOptions = {\n initialEntries?: InitialEntry[];\n initialIndex?: number;\n v5Compat?: boolean;\n};\n\n/**\n * A memory history stores locations in memory. This is useful in stateful\n * environments where there is no web browser, such as node tests or React\n * Native.\n */\nexport interface MemoryHistory extends History {\n /**\n * The current index in the history stack.\n */\n readonly index: number;\n}\n\n/**\n * Memory history stores the current location in memory. It is designed for use\n * in stateful non-browser environments like tests and React Native.\n */\nexport function createMemoryHistory(\n options: MemoryHistoryOptions = {}\n): MemoryHistory {\n let { initialEntries = [\"/\"], initialIndex, v5Compat = false } = options;\n let entries: Location[]; // Declare so we can access from createMemoryLocation\n entries = initialEntries.map((entry, index) =>\n createMemoryLocation(\n entry,\n typeof entry === \"string\" ? null : entry.state,\n index === 0 ? \"default\" : undefined\n )\n );\n let index = clampIndex(\n initialIndex == null ? entries.length - 1 : initialIndex\n );\n let action = Action.Pop;\n let listener: Listener | null = null;\n\n function clampIndex(n: number): number {\n return Math.min(Math.max(n, 0), entries.length - 1);\n }\n function getCurrentLocation(): Location {\n return entries[index];\n }\n function createMemoryLocation(\n to: To,\n state: any = null,\n key?: string\n ): Location {\n let location = createLocation(\n entries ? getCurrentLocation().pathname : \"/\",\n to,\n state,\n key\n );\n warning(\n location.pathname.charAt(0) === \"/\",\n `relative pathnames are not supported in memory history: ${JSON.stringify(\n to\n )}`\n );\n return location;\n }\n\n function createHref(to: To) {\n return typeof to === \"string\" ? to : createPath(to);\n }\n\n let history: MemoryHistory = {\n get index() {\n return index;\n },\n get action() {\n return action;\n },\n get location() {\n return getCurrentLocation();\n },\n createHref,\n createURL(to) {\n return new URL(createHref(to), \"http://localhost\");\n },\n encodeLocation(to: To) {\n let path = typeof to === \"string\" ? parsePath(to) : to;\n return {\n pathname: path.pathname || \"\",\n search: path.search || \"\",\n hash: path.hash || \"\",\n };\n },\n push(to, state) {\n action = Action.Push;\n let nextLocation = createMemoryLocation(to, state);\n index += 1;\n entries.splice(index, entries.length, nextLocation);\n if (v5Compat && listener) {\n listener({ action, location: nextLocation, delta: 1 });\n }\n },\n replace(to, state) {\n action = Action.Replace;\n let nextLocation = createMemoryLocation(to, state);\n entries[index] = nextLocation;\n if (v5Compat && listener) {\n listener({ action, location: nextLocation, delta: 0 });\n }\n },\n go(delta) {\n action = Action.Pop;\n let nextIndex = clampIndex(index + delta);\n let nextLocation = entries[nextIndex];\n index = nextIndex;\n if (listener) {\n listener({ action, location: nextLocation, delta });\n }\n },\n listen(fn: Listener) {\n listener = fn;\n return () => {\n listener = null;\n };\n },\n };\n\n return history;\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Browser History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A browser history stores the current location in regular URLs in a web\n * browser environment. This is the standard for most web apps and provides the\n * cleanest URLs the browser's address bar.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#browserhistory\n */\nexport interface BrowserHistory extends UrlHistory {}\n\nexport type BrowserHistoryOptions = UrlHistoryOptions;\n\n/**\n * Browser history stores the location in regular URLs. This is the standard for\n * most web apps, but it requires some configuration on the server to ensure you\n * serve the same app at multiple URLs.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory\n */\nexport function createBrowserHistory(\n options: BrowserHistoryOptions = {}\n): BrowserHistory {\n function createBrowserLocation(\n window: Window,\n globalHistory: Window[\"history\"]\n ) {\n let { pathname, search, hash } = window.location;\n return createLocation(\n \"\",\n { pathname, search, hash },\n // state defaults to `null` because `window.history.state` does\n (globalHistory.state && globalHistory.state.usr) || null,\n (globalHistory.state && globalHistory.state.key) || \"default\"\n );\n }\n\n function createBrowserHref(window: Window, to: To) {\n return typeof to === \"string\" ? to : createPath(to);\n }\n\n return getUrlBasedHistory(\n createBrowserLocation,\n createBrowserHref,\n null,\n options\n );\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Hash History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A hash history stores the current location in the fragment identifier portion\n * of the URL in a web browser environment.\n *\n * This is ideal for apps that do not control the server for some reason\n * (because the fragment identifier is never sent to the server), including some\n * shared hosting environments that do not provide fine-grained controls over\n * which pages are served at which URLs.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#hashhistory\n */\nexport interface HashHistory extends UrlHistory {}\n\nexport type HashHistoryOptions = UrlHistoryOptions;\n\n/**\n * Hash history stores the location in window.location.hash. This makes it ideal\n * for situations where you don't want to send the location to the server for\n * some reason, either because you do cannot configure it or the URL space is\n * reserved for something else.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory\n */\nexport function createHashHistory(\n options: HashHistoryOptions = {}\n): HashHistory {\n function createHashLocation(\n window: Window,\n globalHistory: Window[\"history\"]\n ) {\n let {\n pathname = \"/\",\n search = \"\",\n hash = \"\",\n } = parsePath(window.location.hash.substr(1));\n\n // Hash URL should always have a leading / just like window.location.pathname\n // does, so if an app ends up at a route like /#something then we add a\n // leading slash so all of our path-matching behaves the same as if it would\n // in a browser router. This is particularly important when there exists a\n // root splat route () since that matches internally against\n // \"/*\" and we'd expect /#something to 404 in a hash router app.\n if (!pathname.startsWith(\"/\") && !pathname.startsWith(\".\")) {\n pathname = \"/\" + pathname;\n }\n\n return createLocation(\n \"\",\n { pathname, search, hash },\n // state defaults to `null` because `window.history.state` does\n (globalHistory.state && globalHistory.state.usr) || null,\n (globalHistory.state && globalHistory.state.key) || \"default\"\n );\n }\n\n function createHashHref(window: Window, to: To) {\n let base = window.document.querySelector(\"base\");\n let href = \"\";\n\n if (base && base.getAttribute(\"href\")) {\n let url = window.location.href;\n let hashIndex = url.indexOf(\"#\");\n href = hashIndex === -1 ? url : url.slice(0, hashIndex);\n }\n\n return href + \"#\" + (typeof to === \"string\" ? to : createPath(to));\n }\n\n function validateHashLocation(location: Location, to: To) {\n warning(\n location.pathname.charAt(0) === \"/\",\n `relative pathnames are not supported in hash history.push(${JSON.stringify(\n to\n )})`\n );\n }\n\n return getUrlBasedHistory(\n createHashLocation,\n createHashHref,\n validateHashLocation,\n options\n );\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region UTILS\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * @private\n */\nexport function invariant(value: boolean, message?: string): asserts value;\nexport function invariant(\n value: T | null | undefined,\n message?: string\n): asserts value is T;\nexport function invariant(value: any, message?: string) {\n if (value === false || value === null || typeof value === \"undefined\") {\n throw new Error(message);\n }\n}\n\nexport function warning(cond: any, message: string) {\n if (!cond) {\n // eslint-disable-next-line no-console\n if (typeof console !== \"undefined\") console.warn(message);\n\n try {\n // Welcome to debugging history!\n //\n // This error is thrown as a convenience, so you can more easily\n // find the source for a warning that appears in the console by\n // enabling \"pause on exceptions\" in your JavaScript debugger.\n throw new Error(message);\n // eslint-disable-next-line no-empty\n } catch (e) {}\n }\n}\n\nfunction createKey() {\n return Math.random().toString(36).substr(2, 8);\n}\n\n/**\n * For browser-based histories, we combine the state and key into an object\n */\nfunction getHistoryState(location: Location, index: number): HistoryState {\n return {\n usr: location.state,\n key: location.key,\n idx: index,\n };\n}\n\n/**\n * Creates a Location object with a unique key from the given Path\n */\nexport function createLocation(\n current: string | Location,\n to: To,\n state: any = null,\n key?: string\n): Readonly {\n let location: Readonly = {\n pathname: typeof current === \"string\" ? current : current.pathname,\n search: \"\",\n hash: \"\",\n ...(typeof to === \"string\" ? parsePath(to) : to),\n state,\n // TODO: This could be cleaned up. push/replace should probably just take\n // full Locations now and avoid the need to run through this flow at all\n // But that's a pretty big refactor to the current test suite so going to\n // keep as is for the time being and just let any incoming keys take precedence\n key: (to && (to as Location).key) || key || createKey(),\n };\n return location;\n}\n\n/**\n * Creates a string URL path from the given pathname, search, and hash components.\n */\nexport function createPath({\n pathname = \"/\",\n search = \"\",\n hash = \"\",\n}: Partial) {\n if (search && search !== \"?\")\n pathname += search.charAt(0) === \"?\" ? search : \"?\" + search;\n if (hash && hash !== \"#\")\n pathname += hash.charAt(0) === \"#\" ? hash : \"#\" + hash;\n return pathname;\n}\n\n/**\n * Parses a string URL path into its separate pathname, search, and hash components.\n */\nexport function parsePath(path: string): Partial {\n let parsedPath: Partial = {};\n\n if (path) {\n let hashIndex = path.indexOf(\"#\");\n if (hashIndex >= 0) {\n parsedPath.hash = path.substr(hashIndex);\n path = path.substr(0, hashIndex);\n }\n\n let searchIndex = path.indexOf(\"?\");\n if (searchIndex >= 0) {\n parsedPath.search = path.substr(searchIndex);\n path = path.substr(0, searchIndex);\n }\n\n if (path) {\n parsedPath.pathname = path;\n }\n }\n\n return parsedPath;\n}\n\nexport interface UrlHistory extends History {}\n\nexport type UrlHistoryOptions = {\n window?: Window;\n v5Compat?: boolean;\n};\n\nfunction getUrlBasedHistory(\n getLocation: (window: Window, globalHistory: Window[\"history\"]) => Location,\n createHref: (window: Window, to: To) => string,\n validateLocation: ((location: Location, to: To) => void) | null,\n options: UrlHistoryOptions = {}\n): UrlHistory {\n let { window = document.defaultView!, v5Compat = false } = options;\n let globalHistory = window.history;\n let action = Action.Pop;\n let listener: Listener | null = null;\n\n let index = getIndex()!;\n // Index should only be null when we initialize. If not, it's because the\n // user called history.pushState or history.replaceState directly, in which\n // case we should log a warning as it will result in bugs.\n if (index == null) {\n index = 0;\n globalHistory.replaceState({ ...globalHistory.state, idx: index }, \"\");\n }\n\n function getIndex(): number {\n let state = globalHistory.state || { idx: null };\n return state.idx;\n }\n\n function handlePop() {\n action = Action.Pop;\n let nextIndex = getIndex();\n let delta = nextIndex == null ? null : nextIndex - index;\n index = nextIndex;\n if (listener) {\n listener({ action, location: history.location, delta });\n }\n }\n\n function push(to: To, state?: any) {\n action = Action.Push;\n let location = createLocation(history.location, to, state);\n if (validateLocation) validateLocation(location, to);\n\n index = getIndex() + 1;\n let historyState = getHistoryState(location, index);\n let url = history.createHref(location);\n\n // try...catch because iOS limits us to 100 pushState calls :/\n try {\n globalHistory.pushState(historyState, \"\", url);\n } catch (error) {\n // If the exception is because `state` can't be serialized, let that throw\n // outwards just like a replace call would so the dev knows the cause\n // https://html.spec.whatwg.org/multipage/nav-history-apis.html#shared-history-push/replace-state-steps\n // https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeinternal\n if (error instanceof DOMException && error.name === \"DataCloneError\") {\n throw error;\n }\n // They are going to lose state here, but there is no real\n // way to warn them about it since the page will refresh...\n window.location.assign(url);\n }\n\n if (v5Compat && listener) {\n listener({ action, location: history.location, delta: 1 });\n }\n }\n\n function replace(to: To, state?: any) {\n action = Action.Replace;\n let location = createLocation(history.location, to, state);\n if (validateLocation) validateLocation(location, to);\n\n index = getIndex();\n let historyState = getHistoryState(location, index);\n let url = history.createHref(location);\n globalHistory.replaceState(historyState, \"\", url);\n\n if (v5Compat && listener) {\n listener({ action, location: history.location, delta: 0 });\n }\n }\n\n function createURL(to: To): URL {\n // window.location.origin is \"null\" (the literal string value) in Firefox\n // under certain conditions, notably when serving from a local HTML file\n // See https://bugzilla.mozilla.org/show_bug.cgi?id=878297\n let base =\n window.location.origin !== \"null\"\n ? window.location.origin\n : window.location.href;\n\n let href = typeof to === \"string\" ? to : createPath(to);\n // Treating this as a full URL will strip any trailing spaces so we need to\n // pre-encode them since they might be part of a matching splat param from\n // an ancestor route\n href = href.replace(/ $/, \"%20\");\n invariant(\n base,\n `No window.location.(origin|href) available to create URL for href: ${href}`\n );\n return new URL(href, base);\n }\n\n let history: History = {\n get action() {\n return action;\n },\n get location() {\n return getLocation(window, globalHistory);\n },\n listen(fn: Listener) {\n if (listener) {\n throw new Error(\"A history only accepts one active listener\");\n }\n window.addEventListener(PopStateEventType, handlePop);\n listener = fn;\n\n return () => {\n window.removeEventListener(PopStateEventType, handlePop);\n listener = null;\n };\n },\n createHref(to) {\n return createHref(window, to);\n },\n createURL,\n encodeLocation(to) {\n // Encode a Location the same way window.location would\n let url = createURL(to);\n return {\n pathname: url.pathname,\n search: url.search,\n hash: url.hash,\n };\n },\n push,\n replace,\n go(n) {\n return globalHistory.go(n);\n },\n };\n\n return history;\n}\n\n//#endregion\n","import type { Location, Path, To } from \"./history\";\nimport { invariant, parsePath, warning } from \"./history\";\n\n/**\n * Map of routeId -> data returned from a loader/action/error\n */\nexport interface RouteData {\n [routeId: string]: any;\n}\n\nexport enum ResultType {\n data = \"data\",\n deferred = \"deferred\",\n redirect = \"redirect\",\n error = \"error\",\n}\n\n/**\n * Successful result from a loader or action\n */\nexport interface SuccessResult {\n type: ResultType.data;\n data: unknown;\n statusCode?: number;\n headers?: Headers;\n}\n\n/**\n * Successful defer() result from a loader or action\n */\nexport interface DeferredResult {\n type: ResultType.deferred;\n deferredData: DeferredData;\n statusCode?: number;\n headers?: Headers;\n}\n\n/**\n * Redirect result from a loader or action\n */\nexport interface RedirectResult {\n type: ResultType.redirect;\n // We keep the raw Response for redirects so we can return it verbatim\n response: Response;\n}\n\n/**\n * Unsuccessful result from a loader or action\n */\nexport interface ErrorResult {\n type: ResultType.error;\n error: unknown;\n statusCode?: number;\n headers?: Headers;\n}\n\n/**\n * Result from a loader or action - potentially successful or unsuccessful\n */\nexport type DataResult =\n | SuccessResult\n | DeferredResult\n | RedirectResult\n | ErrorResult;\n\ntype LowerCaseFormMethod = \"get\" | \"post\" | \"put\" | \"patch\" | \"delete\";\ntype UpperCaseFormMethod = Uppercase;\n\n/**\n * Users can specify either lowercase or uppercase form methods on ``,\n * useSubmit(), ``, etc.\n */\nexport type HTMLFormMethod = LowerCaseFormMethod | UpperCaseFormMethod;\n\n/**\n * Active navigation/fetcher form methods are exposed in lowercase on the\n * RouterState\n */\nexport type FormMethod = LowerCaseFormMethod;\nexport type MutationFormMethod = Exclude;\n\n/**\n * In v7, active navigation/fetcher form methods are exposed in uppercase on the\n * RouterState. This is to align with the normalization done via fetch().\n */\nexport type V7_FormMethod = UpperCaseFormMethod;\nexport type V7_MutationFormMethod = Exclude;\n\nexport type FormEncType =\n | \"application/x-www-form-urlencoded\"\n | \"multipart/form-data\"\n | \"application/json\"\n | \"text/plain\";\n\n// Thanks https://github.com/sindresorhus/type-fest!\ntype JsonObject = { [Key in string]: JsonValue } & {\n [Key in string]?: JsonValue | undefined;\n};\ntype JsonArray = JsonValue[] | readonly JsonValue[];\ntype JsonPrimitive = string | number | boolean | null;\ntype JsonValue = JsonPrimitive | JsonObject | JsonArray;\n\n/**\n * @private\n * Internal interface to pass around for action submissions, not intended for\n * external consumption\n */\nexport type Submission =\n | {\n formMethod: FormMethod | V7_FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: FormData;\n json: undefined;\n text: undefined;\n }\n | {\n formMethod: FormMethod | V7_FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: undefined;\n json: JsonValue;\n text: undefined;\n }\n | {\n formMethod: FormMethod | V7_FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: undefined;\n json: undefined;\n text: string;\n };\n\n/**\n * @private\n * Arguments passed to route loader/action functions. Same for now but we keep\n * this as a private implementation detail in case they diverge in the future.\n */\ninterface DataFunctionArgs {\n request: Request;\n params: Params;\n context?: Context;\n}\n\n// TODO: (v7) Change the defaults from any to unknown in and remove Remix wrappers:\n// ActionFunction, ActionFunctionArgs, LoaderFunction, LoaderFunctionArgs\n// Also, make them a type alias instead of an interface\n\n/**\n * Arguments passed to loader functions\n */\nexport interface LoaderFunctionArgs\n extends DataFunctionArgs {}\n\n/**\n * Arguments passed to action functions\n */\nexport interface ActionFunctionArgs\n extends DataFunctionArgs {}\n\n/**\n * Loaders and actions can return anything except `undefined` (`null` is a\n * valid return value if there is no data to return). Responses are preferred\n * and will ease any future migration to Remix\n */\ntype DataFunctionValue = Response | NonNullable | null;\n\ntype DataFunctionReturnValue = Promise | DataFunctionValue;\n\n/**\n * Route loader function signature\n */\nexport type LoaderFunction = {\n (\n args: LoaderFunctionArgs,\n handlerCtx?: unknown\n ): DataFunctionReturnValue;\n} & { hydrate?: boolean };\n\n/**\n * Route action function signature\n */\nexport interface ActionFunction {\n (\n args: ActionFunctionArgs,\n handlerCtx?: unknown\n ): DataFunctionReturnValue;\n}\n\n/**\n * Arguments passed to shouldRevalidate function\n */\nexport interface ShouldRevalidateFunctionArgs {\n currentUrl: URL;\n currentParams: AgnosticDataRouteMatch[\"params\"];\n nextUrl: URL;\n nextParams: AgnosticDataRouteMatch[\"params\"];\n formMethod?: Submission[\"formMethod\"];\n formAction?: Submission[\"formAction\"];\n formEncType?: Submission[\"formEncType\"];\n text?: Submission[\"text\"];\n formData?: Submission[\"formData\"];\n json?: Submission[\"json\"];\n actionStatus?: number;\n actionResult?: any;\n defaultShouldRevalidate: boolean;\n}\n\n/**\n * Route shouldRevalidate function signature. This runs after any submission\n * (navigation or fetcher), so we flatten the navigation/fetcher submission\n * onto the arguments. It shouldn't matter whether it came from a navigation\n * or a fetcher, what really matters is the URLs and the formData since loaders\n * have to re-run based on the data models that were potentially mutated.\n */\nexport interface ShouldRevalidateFunction {\n (args: ShouldRevalidateFunctionArgs): boolean;\n}\n\n/**\n * Function provided by the framework-aware layers to set `hasErrorBoundary`\n * from the framework-aware `errorElement` prop\n *\n * @deprecated Use `mapRouteProperties` instead\n */\nexport interface DetectErrorBoundaryFunction {\n (route: AgnosticRouteObject): boolean;\n}\n\nexport interface DataStrategyMatch\n extends AgnosticRouteMatch {\n shouldLoad: boolean;\n resolve: (\n handlerOverride?: (\n handler: (ctx?: unknown) => DataFunctionReturnValue\n ) => DataFunctionReturnValue\n ) => Promise;\n}\n\nexport interface DataStrategyFunctionArgs\n extends DataFunctionArgs {\n matches: DataStrategyMatch[];\n fetcherKey: string | null;\n}\n\n/**\n * Result from a loader or action called via dataStrategy\n */\nexport interface DataStrategyResult {\n type: \"data\" | \"error\";\n result: unknown; // data, Error, Response, DeferredData, DataWithResponseInit\n}\n\nexport interface DataStrategyFunction {\n (args: DataStrategyFunctionArgs): Promise>;\n}\n\nexport type AgnosticPatchRoutesOnNavigationFunctionArgs<\n O extends AgnosticRouteObject = AgnosticRouteObject,\n M extends AgnosticRouteMatch = AgnosticRouteMatch\n> = {\n signal: AbortSignal;\n path: string;\n matches: M[];\n fetcherKey: string | undefined;\n patch: (routeId: string | null, children: O[]) => void;\n};\n\nexport type AgnosticPatchRoutesOnNavigationFunction<\n O extends AgnosticRouteObject = AgnosticRouteObject,\n M extends AgnosticRouteMatch = AgnosticRouteMatch\n> = (\n opts: AgnosticPatchRoutesOnNavigationFunctionArgs\n) => void | Promise;\n\n/**\n * Function provided by the framework-aware layers to set any framework-specific\n * properties from framework-agnostic properties\n */\nexport interface MapRoutePropertiesFunction {\n (route: AgnosticRouteObject): {\n hasErrorBoundary: boolean;\n } & Record;\n}\n\n/**\n * Keys we cannot change from within a lazy() function. We spread all other keys\n * onto the route. Either they're meaningful to the router, or they'll get\n * ignored.\n */\nexport type ImmutableRouteKey =\n | \"lazy\"\n | \"caseSensitive\"\n | \"path\"\n | \"id\"\n | \"index\"\n | \"children\";\n\nexport const immutableRouteKeys = new Set([\n \"lazy\",\n \"caseSensitive\",\n \"path\",\n \"id\",\n \"index\",\n \"children\",\n]);\n\ntype RequireOne = Exclude<\n {\n [K in keyof T]: K extends Key ? Omit & Required> : never;\n }[keyof T],\n undefined\n>;\n\n/**\n * lazy() function to load a route definition, which can add non-matching\n * related properties to a route\n */\nexport interface LazyRouteFunction {\n (): Promise>>;\n}\n\n/**\n * Base RouteObject with common props shared by all types of routes\n */\ntype AgnosticBaseRouteObject = {\n caseSensitive?: boolean;\n path?: string;\n id?: string;\n loader?: LoaderFunction | boolean;\n action?: ActionFunction | boolean;\n hasErrorBoundary?: boolean;\n shouldRevalidate?: ShouldRevalidateFunction;\n handle?: any;\n lazy?: LazyRouteFunction;\n};\n\n/**\n * Index routes must not have children\n */\nexport type AgnosticIndexRouteObject = AgnosticBaseRouteObject & {\n children?: undefined;\n index: true;\n};\n\n/**\n * Non-index routes may have children, but cannot have index\n */\nexport type AgnosticNonIndexRouteObject = AgnosticBaseRouteObject & {\n children?: AgnosticRouteObject[];\n index?: false;\n};\n\n/**\n * A route object represents a logical route, with (optionally) its child\n * routes organized in a tree-like structure.\n */\nexport type AgnosticRouteObject =\n | AgnosticIndexRouteObject\n | AgnosticNonIndexRouteObject;\n\nexport type AgnosticDataIndexRouteObject = AgnosticIndexRouteObject & {\n id: string;\n};\n\nexport type AgnosticDataNonIndexRouteObject = AgnosticNonIndexRouteObject & {\n children?: AgnosticDataRouteObject[];\n id: string;\n};\n\n/**\n * A data route object, which is just a RouteObject with a required unique ID\n */\nexport type AgnosticDataRouteObject =\n | AgnosticDataIndexRouteObject\n | AgnosticDataNonIndexRouteObject;\n\nexport type RouteManifest = Record;\n\n// Recursive helper for finding path parameters in the absence of wildcards\ntype _PathParam =\n // split path into individual path segments\n Path extends `${infer L}/${infer R}`\n ? _PathParam | _PathParam\n : // find params after `:`\n Path extends `:${infer Param}`\n ? Param extends `${infer Optional}?`\n ? Optional\n : Param\n : // otherwise, there aren't any params present\n never;\n\n/**\n * Examples:\n * \"/a/b/*\" -> \"*\"\n * \":a\" -> \"a\"\n * \"/a/:b\" -> \"b\"\n * \"/a/blahblahblah:b\" -> \"b\"\n * \"/:a/:b\" -> \"a\" | \"b\"\n * \"/:a/b/:c/*\" -> \"a\" | \"c\" | \"*\"\n */\nexport type PathParam =\n // check if path is just a wildcard\n Path extends \"*\" | \"/*\"\n ? \"*\"\n : // look for wildcard at the end of the path\n Path extends `${infer Rest}/*`\n ? \"*\" | _PathParam\n : // look for params in the absence of wildcards\n _PathParam;\n\n// Attempt to parse the given string segment. If it fails, then just return the\n// plain string type as a default fallback. Otherwise, return the union of the\n// parsed string literals that were referenced as dynamic segments in the route.\nexport type ParamParseKey =\n // if you could not find path params, fallback to `string`\n [PathParam] extends [never] ? string : PathParam;\n\n/**\n * The parameters that were parsed from the URL path.\n */\nexport type Params = {\n readonly [key in Key]: string | undefined;\n};\n\n/**\n * A RouteMatch contains info about how a route matched a URL.\n */\nexport interface AgnosticRouteMatch<\n ParamKey extends string = string,\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n /**\n * The names and values of dynamic parameters in the URL.\n */\n params: Params;\n /**\n * The portion of the URL pathname that was matched.\n */\n pathname: string;\n /**\n * The portion of the URL pathname that was matched before child routes.\n */\n pathnameBase: string;\n /**\n * The route object that was used to match.\n */\n route: RouteObjectType;\n}\n\nexport interface AgnosticDataRouteMatch\n extends AgnosticRouteMatch {}\n\nfunction isIndexRoute(\n route: AgnosticRouteObject\n): route is AgnosticIndexRouteObject {\n return route.index === true;\n}\n\n// Walk the route tree generating unique IDs where necessary, so we are working\n// solely with AgnosticDataRouteObject's within the Router\nexport function convertRoutesToDataRoutes(\n routes: AgnosticRouteObject[],\n mapRouteProperties: MapRoutePropertiesFunction,\n parentPath: string[] = [],\n manifest: RouteManifest = {}\n): AgnosticDataRouteObject[] {\n return routes.map((route, index) => {\n let treePath = [...parentPath, String(index)];\n let id = typeof route.id === \"string\" ? route.id : treePath.join(\"-\");\n invariant(\n route.index !== true || !route.children,\n `Cannot specify children on an index route`\n );\n invariant(\n !manifest[id],\n `Found a route id collision on id \"${id}\". Route ` +\n \"id's must be globally unique within Data Router usages\"\n );\n\n if (isIndexRoute(route)) {\n let indexRoute: AgnosticDataIndexRouteObject = {\n ...route,\n ...mapRouteProperties(route),\n id,\n };\n manifest[id] = indexRoute;\n return indexRoute;\n } else {\n let pathOrLayoutRoute: AgnosticDataNonIndexRouteObject = {\n ...route,\n ...mapRouteProperties(route),\n id,\n children: undefined,\n };\n manifest[id] = pathOrLayoutRoute;\n\n if (route.children) {\n pathOrLayoutRoute.children = convertRoutesToDataRoutes(\n route.children,\n mapRouteProperties,\n treePath,\n manifest\n );\n }\n\n return pathOrLayoutRoute;\n }\n });\n}\n\n/**\n * Matches the given routes to a location and returns the match data.\n *\n * @see https://reactrouter.com/v6/utils/match-routes\n */\nexport function matchRoutes<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n routes: RouteObjectType[],\n locationArg: Partial | string,\n basename = \"/\"\n): AgnosticRouteMatch[] | null {\n return matchRoutesImpl(routes, locationArg, basename, false);\n}\n\nexport function matchRoutesImpl<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n routes: RouteObjectType[],\n locationArg: Partial | string,\n basename: string,\n allowPartial: boolean\n): AgnosticRouteMatch[] | null {\n let location =\n typeof locationArg === \"string\" ? parsePath(locationArg) : locationArg;\n\n let pathname = stripBasename(location.pathname || \"/\", basename);\n\n if (pathname == null) {\n return null;\n }\n\n let branches = flattenRoutes(routes);\n rankRouteBranches(branches);\n\n let matches = null;\n let decoded = decodePath(pathname);\n for (let i = 0; matches == null && i < branches.length; ++i) {\n // Incoming pathnames are generally encoded from either window.location\n // or from router.navigate, but we want to match against the unencoded\n // paths in the route definitions. Memory router locations won't be\n // encoded here but there also shouldn't be anything to decode so this\n // should be a safe operation. This avoids needing matchRoutes to be\n // history-aware.\n matches = matchRouteBranch(\n branches[i],\n decoded,\n allowPartial\n );\n }\n\n return matches;\n}\n\nexport interface UIMatch {\n id: string;\n pathname: string;\n params: AgnosticRouteMatch[\"params\"];\n data: Data;\n handle: Handle;\n}\n\nexport function convertRouteMatchToUiMatch(\n match: AgnosticDataRouteMatch,\n loaderData: RouteData\n): UIMatch {\n let { route, pathname, params } = match;\n return {\n id: route.id,\n pathname,\n params,\n data: loaderData[route.id],\n handle: route.handle,\n };\n}\n\ninterface RouteMeta<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n relativePath: string;\n caseSensitive: boolean;\n childrenIndex: number;\n route: RouteObjectType;\n}\n\ninterface RouteBranch<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n path: string;\n score: number;\n routesMeta: RouteMeta[];\n}\n\nfunction flattenRoutes<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n routes: RouteObjectType[],\n branches: RouteBranch[] = [],\n parentsMeta: RouteMeta[] = [],\n parentPath = \"\"\n): RouteBranch[] {\n let flattenRoute = (\n route: RouteObjectType,\n index: number,\n relativePath?: string\n ) => {\n let meta: RouteMeta = {\n relativePath:\n relativePath === undefined ? route.path || \"\" : relativePath,\n caseSensitive: route.caseSensitive === true,\n childrenIndex: index,\n route,\n };\n\n if (meta.relativePath.startsWith(\"/\")) {\n invariant(\n meta.relativePath.startsWith(parentPath),\n `Absolute route path \"${meta.relativePath}\" nested under path ` +\n `\"${parentPath}\" is not valid. An absolute child route path ` +\n `must start with the combined path of all its parent routes.`\n );\n\n meta.relativePath = meta.relativePath.slice(parentPath.length);\n }\n\n let path = joinPaths([parentPath, meta.relativePath]);\n let routesMeta = parentsMeta.concat(meta);\n\n // Add the children before adding this route to the array, so we traverse the\n // route tree depth-first and child routes appear before their parents in\n // the \"flattened\" version.\n if (route.children && route.children.length > 0) {\n invariant(\n // Our types know better, but runtime JS may not!\n // @ts-expect-error\n route.index !== true,\n `Index routes must not have child routes. Please remove ` +\n `all child routes from route path \"${path}\".`\n );\n flattenRoutes(route.children, branches, routesMeta, path);\n }\n\n // Routes without a path shouldn't ever match by themselves unless they are\n // index routes, so don't add them to the list of possible branches.\n if (route.path == null && !route.index) {\n return;\n }\n\n branches.push({\n path,\n score: computeScore(path, route.index),\n routesMeta,\n });\n };\n routes.forEach((route, index) => {\n // coarse-grain check for optional params\n if (route.path === \"\" || !route.path?.includes(\"?\")) {\n flattenRoute(route, index);\n } else {\n for (let exploded of explodeOptionalSegments(route.path)) {\n flattenRoute(route, index, exploded);\n }\n }\n });\n\n return branches;\n}\n\n/**\n * Computes all combinations of optional path segments for a given path,\n * excluding combinations that are ambiguous and of lower priority.\n *\n * For example, `/one/:two?/three/:four?/:five?` explodes to:\n * - `/one/three`\n * - `/one/:two/three`\n * - `/one/three/:four`\n * - `/one/three/:five`\n * - `/one/:two/three/:four`\n * - `/one/:two/three/:five`\n * - `/one/three/:four/:five`\n * - `/one/:two/three/:four/:five`\n */\nfunction explodeOptionalSegments(path: string): string[] {\n let segments = path.split(\"/\");\n if (segments.length === 0) return [];\n\n let [first, ...rest] = segments;\n\n // Optional path segments are denoted by a trailing `?`\n let isOptional = first.endsWith(\"?\");\n // Compute the corresponding required segment: `foo?` -> `foo`\n let required = first.replace(/\\?$/, \"\");\n\n if (rest.length === 0) {\n // Intepret empty string as omitting an optional segment\n // `[\"one\", \"\", \"three\"]` corresponds to omitting `:two` from `/one/:two?/three` -> `/one/three`\n return isOptional ? [required, \"\"] : [required];\n }\n\n let restExploded = explodeOptionalSegments(rest.join(\"/\"));\n\n let result: string[] = [];\n\n // All child paths with the prefix. Do this for all children before the\n // optional version for all children, so we get consistent ordering where the\n // parent optional aspect is preferred as required. Otherwise, we can get\n // child sections interspersed where deeper optional segments are higher than\n // parent optional segments, where for example, /:two would explode _earlier_\n // then /:one. By always including the parent as required _for all children_\n // first, we avoid this issue\n result.push(\n ...restExploded.map((subpath) =>\n subpath === \"\" ? required : [required, subpath].join(\"/\")\n )\n );\n\n // Then, if this is an optional value, add all child versions without\n if (isOptional) {\n result.push(...restExploded);\n }\n\n // for absolute paths, ensure `/` instead of empty segment\n return result.map((exploded) =>\n path.startsWith(\"/\") && exploded === \"\" ? \"/\" : exploded\n );\n}\n\nfunction rankRouteBranches(branches: RouteBranch[]): void {\n branches.sort((a, b) =>\n a.score !== b.score\n ? b.score - a.score // Higher score first\n : compareIndexes(\n a.routesMeta.map((meta) => meta.childrenIndex),\n b.routesMeta.map((meta) => meta.childrenIndex)\n )\n );\n}\n\nconst paramRe = /^:[\\w-]+$/;\nconst dynamicSegmentValue = 3;\nconst indexRouteValue = 2;\nconst emptySegmentValue = 1;\nconst staticSegmentValue = 10;\nconst splatPenalty = -2;\nconst isSplat = (s: string) => s === \"*\";\n\nfunction computeScore(path: string, index: boolean | undefined): number {\n let segments = path.split(\"/\");\n let initialScore = segments.length;\n if (segments.some(isSplat)) {\n initialScore += splatPenalty;\n }\n\n if (index) {\n initialScore += indexRouteValue;\n }\n\n return segments\n .filter((s) => !isSplat(s))\n .reduce(\n (score, segment) =>\n score +\n (paramRe.test(segment)\n ? dynamicSegmentValue\n : segment === \"\"\n ? emptySegmentValue\n : staticSegmentValue),\n initialScore\n );\n}\n\nfunction compareIndexes(a: number[], b: number[]): number {\n let siblings =\n a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]);\n\n return siblings\n ? // If two routes are siblings, we should try to match the earlier sibling\n // first. This allows people to have fine-grained control over the matching\n // behavior by simply putting routes with identical paths in the order they\n // want them tried.\n a[a.length - 1] - b[b.length - 1]\n : // Otherwise, it doesn't really make sense to rank non-siblings by index,\n // so they sort equally.\n 0;\n}\n\nfunction matchRouteBranch<\n ParamKey extends string = string,\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n branch: RouteBranch,\n pathname: string,\n allowPartial = false\n): AgnosticRouteMatch[] | null {\n let { routesMeta } = branch;\n\n let matchedParams = {};\n let matchedPathname = \"/\";\n let matches: AgnosticRouteMatch[] = [];\n for (let i = 0; i < routesMeta.length; ++i) {\n let meta = routesMeta[i];\n let end = i === routesMeta.length - 1;\n let remainingPathname =\n matchedPathname === \"/\"\n ? pathname\n : pathname.slice(matchedPathname.length) || \"/\";\n let match = matchPath(\n { path: meta.relativePath, caseSensitive: meta.caseSensitive, end },\n remainingPathname\n );\n\n let route = meta.route;\n\n if (\n !match &&\n end &&\n allowPartial &&\n !routesMeta[routesMeta.length - 1].route.index\n ) {\n match = matchPath(\n {\n path: meta.relativePath,\n caseSensitive: meta.caseSensitive,\n end: false,\n },\n remainingPathname\n );\n }\n\n if (!match) {\n return null;\n }\n\n Object.assign(matchedParams, match.params);\n\n matches.push({\n // TODO: Can this as be avoided?\n params: matchedParams as Params,\n pathname: joinPaths([matchedPathname, match.pathname]),\n pathnameBase: normalizePathname(\n joinPaths([matchedPathname, match.pathnameBase])\n ),\n route,\n });\n\n if (match.pathnameBase !== \"/\") {\n matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);\n }\n }\n\n return matches;\n}\n\n/**\n * Returns a path with params interpolated.\n *\n * @see https://reactrouter.com/v6/utils/generate-path\n */\nexport function generatePath(\n originalPath: Path,\n params: {\n [key in PathParam]: string | null;\n } = {} as any\n): string {\n let path: string = originalPath;\n if (path.endsWith(\"*\") && path !== \"*\" && !path.endsWith(\"/*\")) {\n warning(\n false,\n `Route path \"${path}\" will be treated as if it were ` +\n `\"${path.replace(/\\*$/, \"/*\")}\" because the \\`*\\` character must ` +\n `always follow a \\`/\\` in the pattern. To get rid of this warning, ` +\n `please change the route path to \"${path.replace(/\\*$/, \"/*\")}\".`\n );\n path = path.replace(/\\*$/, \"/*\") as Path;\n }\n\n // ensure `/` is added at the beginning if the path is absolute\n const prefix = path.startsWith(\"/\") ? \"/\" : \"\";\n\n const stringify = (p: any) =>\n p == null ? \"\" : typeof p === \"string\" ? p : String(p);\n\n const segments = path\n .split(/\\/+/)\n .map((segment, index, array) => {\n const isLastSegment = index === array.length - 1;\n\n // only apply the splat if it's the last segment\n if (isLastSegment && segment === \"*\") {\n const star = \"*\" as PathParam;\n // Apply the splat\n return stringify(params[star]);\n }\n\n const keyMatch = segment.match(/^:([\\w-]+)(\\??)$/);\n if (keyMatch) {\n const [, key, optional] = keyMatch;\n let param = params[key as PathParam];\n invariant(optional === \"?\" || param != null, `Missing \":${key}\" param`);\n return stringify(param);\n }\n\n // Remove any optional markers from optional static segments\n return segment.replace(/\\?$/g, \"\");\n })\n // Remove empty segments\n .filter((segment) => !!segment);\n\n return prefix + segments.join(\"/\");\n}\n\n/**\n * A PathPattern is used to match on some portion of a URL pathname.\n */\nexport interface PathPattern {\n /**\n * A string to match against a URL pathname. May contain `:id`-style segments\n * to indicate placeholders for dynamic parameters. May also end with `/*` to\n * indicate matching the rest of the URL pathname.\n */\n path: Path;\n /**\n * Should be `true` if the static portions of the `path` should be matched in\n * the same case.\n */\n caseSensitive?: boolean;\n /**\n * Should be `true` if this pattern should match the entire URL pathname.\n */\n end?: boolean;\n}\n\n/**\n * A PathMatch contains info about how a PathPattern matched on a URL pathname.\n */\nexport interface PathMatch {\n /**\n * The names and values of dynamic parameters in the URL.\n */\n params: Params;\n /**\n * The portion of the URL pathname that was matched.\n */\n pathname: string;\n /**\n * The portion of the URL pathname that was matched before child routes.\n */\n pathnameBase: string;\n /**\n * The pattern that was used to match.\n */\n pattern: PathPattern;\n}\n\ntype Mutable = {\n -readonly [P in keyof T]: T[P];\n};\n\n/**\n * Performs pattern matching on a URL pathname and returns information about\n * the match.\n *\n * @see https://reactrouter.com/v6/utils/match-path\n */\nexport function matchPath<\n ParamKey extends ParamParseKey,\n Path extends string\n>(\n pattern: PathPattern | Path,\n pathname: string\n): PathMatch | null {\n if (typeof pattern === \"string\") {\n pattern = { path: pattern, caseSensitive: false, end: true };\n }\n\n let [matcher, compiledParams] = compilePath(\n pattern.path,\n pattern.caseSensitive,\n pattern.end\n );\n\n let match = pathname.match(matcher);\n if (!match) return null;\n\n let matchedPathname = match[0];\n let pathnameBase = matchedPathname.replace(/(.)\\/+$/, \"$1\");\n let captureGroups = match.slice(1);\n let params: Params = compiledParams.reduce>(\n (memo, { paramName, isOptional }, index) => {\n // We need to compute the pathnameBase here using the raw splat value\n // instead of using params[\"*\"] later because it will be decoded then\n if (paramName === \"*\") {\n let splatValue = captureGroups[index] || \"\";\n pathnameBase = matchedPathname\n .slice(0, matchedPathname.length - splatValue.length)\n .replace(/(.)\\/+$/, \"$1\");\n }\n\n const value = captureGroups[index];\n if (isOptional && !value) {\n memo[paramName] = undefined;\n } else {\n memo[paramName] = (value || \"\").replace(/%2F/g, \"/\");\n }\n return memo;\n },\n {}\n );\n\n return {\n params,\n pathname: matchedPathname,\n pathnameBase,\n pattern,\n };\n}\n\ntype CompiledPathParam = { paramName: string; isOptional?: boolean };\n\nfunction compilePath(\n path: string,\n caseSensitive = false,\n end = true\n): [RegExp, CompiledPathParam[]] {\n warning(\n path === \"*\" || !path.endsWith(\"*\") || path.endsWith(\"/*\"),\n `Route path \"${path}\" will be treated as if it were ` +\n `\"${path.replace(/\\*$/, \"/*\")}\" because the \\`*\\` character must ` +\n `always follow a \\`/\\` in the pattern. To get rid of this warning, ` +\n `please change the route path to \"${path.replace(/\\*$/, \"/*\")}\".`\n );\n\n let params: CompiledPathParam[] = [];\n let regexpSource =\n \"^\" +\n path\n .replace(/\\/*\\*?$/, \"\") // Ignore trailing / and /*, we'll handle it below\n .replace(/^\\/*/, \"/\") // Make sure it has a leading /\n .replace(/[\\\\.*+^${}|()[\\]]/g, \"\\\\$&\") // Escape special regex chars\n .replace(\n /\\/:([\\w-]+)(\\?)?/g,\n (_: string, paramName: string, isOptional) => {\n params.push({ paramName, isOptional: isOptional != null });\n return isOptional ? \"/?([^\\\\/]+)?\" : \"/([^\\\\/]+)\";\n }\n );\n\n if (path.endsWith(\"*\")) {\n params.push({ paramName: \"*\" });\n regexpSource +=\n path === \"*\" || path === \"/*\"\n ? \"(.*)$\" // Already matched the initial /, just match the rest\n : \"(?:\\\\/(.+)|\\\\/*)$\"; // Don't include the / in params[\"*\"]\n } else if (end) {\n // When matching to the end, ignore trailing slashes\n regexpSource += \"\\\\/*$\";\n } else if (path !== \"\" && path !== \"/\") {\n // If our path is non-empty and contains anything beyond an initial slash,\n // then we have _some_ form of path in our regex, so we should expect to\n // match only if we find the end of this path segment. Look for an optional\n // non-captured trailing slash (to match a portion of the URL) or the end\n // of the path (if we've matched to the end). We used to do this with a\n // word boundary but that gives false positives on routes like\n // /user-preferences since `-` counts as a word boundary.\n regexpSource += \"(?:(?=\\\\/|$))\";\n } else {\n // Nothing to match for \"\" or \"/\"\n }\n\n let matcher = new RegExp(regexpSource, caseSensitive ? undefined : \"i\");\n\n return [matcher, params];\n}\n\nexport function decodePath(value: string) {\n try {\n return value\n .split(\"/\")\n .map((v) => decodeURIComponent(v).replace(/\\//g, \"%2F\"))\n .join(\"/\");\n } catch (error) {\n warning(\n false,\n `The URL path \"${value}\" could not be decoded because it is is a ` +\n `malformed URL segment. This is probably due to a bad percent ` +\n `encoding (${error}).`\n );\n\n return value;\n }\n}\n\n/**\n * @private\n */\nexport function stripBasename(\n pathname: string,\n basename: string\n): string | null {\n if (basename === \"/\") return pathname;\n\n if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {\n return null;\n }\n\n // We want to leave trailing slash behavior in the user's control, so if they\n // specify a basename with a trailing slash, we should support it\n let startIndex = basename.endsWith(\"/\")\n ? basename.length - 1\n : basename.length;\n let nextChar = pathname.charAt(startIndex);\n if (nextChar && nextChar !== \"/\") {\n // pathname does not start with basename/\n return null;\n }\n\n return pathname.slice(startIndex) || \"/\";\n}\n\nconst ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i;\nexport const isAbsoluteUrl = (url: string) => ABSOLUTE_URL_REGEX.test(url);\n\n/**\n * Returns a resolved path object relative to the given pathname.\n *\n * @see https://reactrouter.com/v6/utils/resolve-path\n */\nexport function resolvePath(to: To, fromPathname = \"/\"): Path {\n let {\n pathname: toPathname,\n search = \"\",\n hash = \"\",\n } = typeof to === \"string\" ? parsePath(to) : to;\n\n let pathname: string;\n if (toPathname) {\n toPathname = removeDoubleSlashes(toPathname);\n if (toPathname.startsWith(\"/\")) {\n pathname = resolvePathname(toPathname.substring(1), \"/\");\n } else {\n pathname = resolvePathname(toPathname, fromPathname);\n }\n } else {\n pathname = fromPathname;\n }\n\n return {\n pathname,\n search: normalizeSearch(search),\n hash: normalizeHash(hash),\n };\n}\n\nfunction resolvePathname(relativePath: string, fromPathname: string): string {\n let segments = fromPathname.replace(/\\/+$/, \"\").split(\"/\");\n let relativeSegments = relativePath.split(\"/\");\n\n relativeSegments.forEach((segment) => {\n if (segment === \"..\") {\n // Keep the root \"\" segment so the pathname starts at /\n if (segments.length > 1) segments.pop();\n } else if (segment !== \".\") {\n segments.push(segment);\n }\n });\n\n return segments.length > 1 ? segments.join(\"/\") : \"/\";\n}\n\nfunction getInvalidPathError(\n char: string,\n field: string,\n dest: string,\n path: Partial\n) {\n return (\n `Cannot include a '${char}' character in a manually specified ` +\n `\\`to.${field}\\` field [${JSON.stringify(\n path\n )}]. Please separate it out to the ` +\n `\\`to.${dest}\\` field. Alternatively you may provide the full path as ` +\n `a string in and the router will parse it for you.`\n );\n}\n\n/**\n * @private\n *\n * When processing relative navigation we want to ignore ancestor routes that\n * do not contribute to the path, such that index/pathless layout routes don't\n * interfere.\n *\n * For example, when moving a route element into an index route and/or a\n * pathless layout route, relative link behavior contained within should stay\n * the same. Both of the following examples should link back to the root:\n *\n * \n * \n * \n *\n * \n * \n * }> // <-- Does not contribute\n * // <-- Does not contribute\n * \n * \n */\nexport function getPathContributingMatches<\n T extends AgnosticRouteMatch = AgnosticRouteMatch\n>(matches: T[]) {\n return matches.filter(\n (match, index) =>\n index === 0 || (match.route.path && match.route.path.length > 0)\n );\n}\n\n// Return the array of pathnames for the current route matches - used to\n// generate the routePathnames input for resolveTo()\nexport function getResolveToMatches<\n T extends AgnosticRouteMatch = AgnosticRouteMatch\n>(matches: T[], v7_relativeSplatPath: boolean) {\n let pathMatches = getPathContributingMatches(matches);\n\n // When v7_relativeSplatPath is enabled, use the full pathname for the leaf\n // match so we include splat values for \".\" links. See:\n // https://github.com/remix-run/react-router/issues/11052#issuecomment-1836589329\n if (v7_relativeSplatPath) {\n return pathMatches.map((match, idx) =>\n idx === pathMatches.length - 1 ? match.pathname : match.pathnameBase\n );\n }\n\n return pathMatches.map((match) => match.pathnameBase);\n}\n\n/**\n * @private\n */\nexport function resolveTo(\n toArg: To,\n routePathnames: string[],\n locationPathname: string,\n isPathRelative = false\n): Path {\n let to: Partial;\n if (typeof toArg === \"string\") {\n to = parsePath(toArg);\n } else {\n to = { ...toArg };\n\n invariant(\n !to.pathname || !to.pathname.includes(\"?\"),\n getInvalidPathError(\"?\", \"pathname\", \"search\", to)\n );\n invariant(\n !to.pathname || !to.pathname.includes(\"#\"),\n getInvalidPathError(\"#\", \"pathname\", \"hash\", to)\n );\n invariant(\n !to.search || !to.search.includes(\"#\"),\n getInvalidPathError(\"#\", \"search\", \"hash\", to)\n );\n }\n\n let isEmptyPath = toArg === \"\" || to.pathname === \"\";\n let toPathname = isEmptyPath ? \"/\" : to.pathname;\n\n let from: string;\n\n // Routing is relative to the current pathname if explicitly requested.\n //\n // If a pathname is explicitly provided in `to`, it should be relative to the\n // route context. This is explained in `Note on `` values` in our\n // migration guide from v5 as a means of disambiguation between `to` values\n // that begin with `/` and those that do not. However, this is problematic for\n // `to` values that do not provide a pathname. `to` can simply be a search or\n // hash string, in which case we should assume that the navigation is relative\n // to the current location's pathname and *not* the route pathname.\n if (toPathname == null) {\n from = locationPathname;\n } else {\n let routePathnameIndex = routePathnames.length - 1;\n\n // With relative=\"route\" (the default), each leading .. segment means\n // \"go up one route\" instead of \"go up one URL segment\". This is a key\n // difference from how works and a major reason we call this a\n // \"to\" value instead of a \"href\".\n if (!isPathRelative && toPathname.startsWith(\"..\")) {\n let toSegments = toPathname.split(\"/\");\n\n while (toSegments[0] === \"..\") {\n toSegments.shift();\n routePathnameIndex -= 1;\n }\n\n to.pathname = toSegments.join(\"/\");\n }\n\n from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : \"/\";\n }\n\n let path = resolvePath(to, from);\n\n // Ensure the pathname has a trailing slash if the original \"to\" had one\n let hasExplicitTrailingSlash =\n toPathname && toPathname !== \"/\" && toPathname.endsWith(\"/\");\n // Or if this was a link to the current path which has a trailing slash\n let hasCurrentTrailingSlash =\n (isEmptyPath || toPathname === \".\") && locationPathname.endsWith(\"/\");\n if (\n !path.pathname.endsWith(\"/\") &&\n (hasExplicitTrailingSlash || hasCurrentTrailingSlash)\n ) {\n path.pathname += \"/\";\n }\n\n return path;\n}\n\n/**\n * @private\n */\nexport function getToPathname(to: To): string | undefined {\n // Empty strings should be treated the same as / paths\n return to === \"\" || (to as Path).pathname === \"\"\n ? \"/\"\n : typeof to === \"string\"\n ? parsePath(to).pathname\n : to.pathname;\n}\n\nexport const removeDoubleSlashes = (path: string): string =>\n path.replace(/\\/\\/+/g, \"/\");\n\n/**\n * @private\n */\nexport const joinPaths = (paths: string[]): string =>\n removeDoubleSlashes(paths.join(\"/\"));\n\n/**\n * @private\n */\nexport const normalizePathname = (pathname: string): string =>\n pathname.replace(/\\/+$/, \"\").replace(/^\\/*/, \"/\");\n\n/**\n * @private\n */\nexport const normalizeSearch = (search: string): string =>\n !search || search === \"?\"\n ? \"\"\n : search.startsWith(\"?\")\n ? search\n : \"?\" + search;\n\n/**\n * @private\n */\nexport const normalizeHash = (hash: string): string =>\n !hash || hash === \"#\" ? \"\" : hash.startsWith(\"#\") ? hash : \"#\" + hash;\n\nexport type JsonFunction = (\n data: Data,\n init?: number | ResponseInit\n) => Response;\n\n/**\n * This is a shortcut for creating `application/json` responses. Converts `data`\n * to JSON and sets the `Content-Type` header.\n *\n * @deprecated The `json` method is deprecated in favor of returning raw objects.\n * This method will be removed in v7.\n */\nexport const json: JsonFunction = (data, init = {}) => {\n let responseInit = typeof init === \"number\" ? { status: init } : init;\n\n let headers = new Headers(responseInit.headers);\n if (!headers.has(\"Content-Type\")) {\n headers.set(\"Content-Type\", \"application/json; charset=utf-8\");\n }\n\n return new Response(JSON.stringify(data), {\n ...responseInit,\n headers,\n });\n};\n\nexport class DataWithResponseInit {\n type: string = \"DataWithResponseInit\";\n data: D;\n init: ResponseInit | null;\n\n constructor(data: D, init?: ResponseInit) {\n this.data = data;\n this.init = init || null;\n }\n}\n\n/**\n * Create \"responses\" that contain `status`/`headers` without forcing\n * serialization into an actual `Response` - used by Remix single fetch\n */\nexport function data(data: D, init?: number | ResponseInit) {\n return new DataWithResponseInit(\n data,\n typeof init === \"number\" ? { status: init } : init\n );\n}\n\nexport interface TrackedPromise extends Promise {\n _tracked?: boolean;\n _data?: any;\n _error?: any;\n}\n\nexport class AbortedDeferredError extends Error {}\n\nexport class DeferredData {\n private pendingKeysSet: Set = new Set();\n private controller: AbortController;\n private abortPromise: Promise;\n private unlistenAbortSignal: () => void;\n private subscribers: Set<(aborted: boolean, settledKey?: string) => void> =\n new Set();\n data: Record;\n init?: ResponseInit;\n deferredKeys: string[] = [];\n\n constructor(data: Record, responseInit?: ResponseInit) {\n invariant(\n data && typeof data === \"object\" && !Array.isArray(data),\n \"defer() only accepts plain objects\"\n );\n\n // Set up an AbortController + Promise we can race against to exit early\n // cancellation\n let reject: (e: AbortedDeferredError) => void;\n this.abortPromise = new Promise((_, r) => (reject = r));\n this.controller = new AbortController();\n let onAbort = () =>\n reject(new AbortedDeferredError(\"Deferred data aborted\"));\n this.unlistenAbortSignal = () =>\n this.controller.signal.removeEventListener(\"abort\", onAbort);\n this.controller.signal.addEventListener(\"abort\", onAbort);\n\n this.data = Object.entries(data).reduce(\n (acc, [key, value]) =>\n Object.assign(acc, {\n [key]: this.trackPromise(key, value),\n }),\n {}\n );\n\n if (this.done) {\n // All incoming values were resolved\n this.unlistenAbortSignal();\n }\n\n this.init = responseInit;\n }\n\n private trackPromise(\n key: string,\n value: Promise | unknown\n ): TrackedPromise | unknown {\n if (!(value instanceof Promise)) {\n return value;\n }\n\n this.deferredKeys.push(key);\n this.pendingKeysSet.add(key);\n\n // We store a little wrapper promise that will be extended with\n // _data/_error props upon resolve/reject\n let promise: TrackedPromise = Promise.race([value, this.abortPromise]).then(\n (data) => this.onSettle(promise, key, undefined, data as unknown),\n (error) => this.onSettle(promise, key, error as unknown)\n );\n\n // Register rejection listeners to avoid uncaught promise rejections on\n // errors or aborted deferred values\n promise.catch(() => {});\n\n Object.defineProperty(promise, \"_tracked\", { get: () => true });\n return promise;\n }\n\n private onSettle(\n promise: TrackedPromise,\n key: string,\n error: unknown,\n data?: unknown\n ): unknown {\n if (\n this.controller.signal.aborted &&\n error instanceof AbortedDeferredError\n ) {\n this.unlistenAbortSignal();\n Object.defineProperty(promise, \"_error\", { get: () => error });\n return Promise.reject(error);\n }\n\n this.pendingKeysSet.delete(key);\n\n if (this.done) {\n // Nothing left to abort!\n this.unlistenAbortSignal();\n }\n\n // If the promise was resolved/rejected with undefined, we'll throw an error as you\n // should always resolve with a value or null\n if (error === undefined && data === undefined) {\n let undefinedError = new Error(\n `Deferred data for key \"${key}\" resolved/rejected with \\`undefined\\`, ` +\n `you must resolve/reject with a value or \\`null\\`.`\n );\n Object.defineProperty(promise, \"_error\", { get: () => undefinedError });\n this.emit(false, key);\n return Promise.reject(undefinedError);\n }\n\n if (data === undefined) {\n Object.defineProperty(promise, \"_error\", { get: () => error });\n this.emit(false, key);\n return Promise.reject(error);\n }\n\n Object.defineProperty(promise, \"_data\", { get: () => data });\n this.emit(false, key);\n return data;\n }\n\n private emit(aborted: boolean, settledKey?: string) {\n this.subscribers.forEach((subscriber) => subscriber(aborted, settledKey));\n }\n\n subscribe(fn: (aborted: boolean, settledKey?: string) => void) {\n this.subscribers.add(fn);\n return () => this.subscribers.delete(fn);\n }\n\n cancel() {\n this.controller.abort();\n this.pendingKeysSet.forEach((v, k) => this.pendingKeysSet.delete(k));\n this.emit(true);\n }\n\n async resolveData(signal: AbortSignal) {\n let aborted = false;\n if (!this.done) {\n let onAbort = () => this.cancel();\n signal.addEventListener(\"abort\", onAbort);\n aborted = await new Promise((resolve) => {\n this.subscribe((aborted) => {\n signal.removeEventListener(\"abort\", onAbort);\n if (aborted || this.done) {\n resolve(aborted);\n }\n });\n });\n }\n return aborted;\n }\n\n get done() {\n return this.pendingKeysSet.size === 0;\n }\n\n get unwrappedData() {\n invariant(\n this.data !== null && this.done,\n \"Can only unwrap data on initialized and settled deferreds\"\n );\n\n return Object.entries(this.data).reduce(\n (acc, [key, value]) =>\n Object.assign(acc, {\n [key]: unwrapTrackedPromise(value),\n }),\n {}\n );\n }\n\n get pendingKeys() {\n return Array.from(this.pendingKeysSet);\n }\n}\n\nfunction isTrackedPromise(value: any): value is TrackedPromise {\n return (\n value instanceof Promise && (value as TrackedPromise)._tracked === true\n );\n}\n\nfunction unwrapTrackedPromise(value: any) {\n if (!isTrackedPromise(value)) {\n return value;\n }\n\n if (value._error) {\n throw value._error;\n }\n return value._data;\n}\n\nexport type DeferFunction = (\n data: Record,\n init?: number | ResponseInit\n) => DeferredData;\n\n/**\n * @deprecated The `defer` method is deprecated in favor of returning raw\n * objects. This method will be removed in v7.\n */\nexport const defer: DeferFunction = (data, init = {}) => {\n let responseInit = typeof init === \"number\" ? { status: init } : init;\n\n return new DeferredData(data, responseInit);\n};\n\nexport type RedirectFunction = (\n url: string,\n init?: number | ResponseInit\n) => Response;\n\n/**\n * A redirect response. Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nexport const redirect: RedirectFunction = (url, init = 302) => {\n let responseInit = init;\n if (typeof responseInit === \"number\") {\n responseInit = { status: responseInit };\n } else if (typeof responseInit.status === \"undefined\") {\n responseInit.status = 302;\n }\n\n let headers = new Headers(responseInit.headers);\n headers.set(\"Location\", url);\n\n return new Response(null, {\n ...responseInit,\n headers,\n });\n};\n\n/**\n * A redirect response that will force a document reload to the new location.\n * Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nexport const redirectDocument: RedirectFunction = (url, init) => {\n let response = redirect(url, init);\n response.headers.set(\"X-Remix-Reload-Document\", \"true\");\n return response;\n};\n\n/**\n * A redirect response that will perform a `history.replaceState` instead of a\n * `history.pushState` for client-side navigation redirects.\n * Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nexport const replace: RedirectFunction = (url, init) => {\n let response = redirect(url, init);\n response.headers.set(\"X-Remix-Replace\", \"true\");\n return response;\n};\n\nexport type ErrorResponse = {\n status: number;\n statusText: string;\n data: any;\n};\n\n/**\n * @private\n * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies\n *\n * We don't export the class for public use since it's an implementation\n * detail, but we export the interface above so folks can build their own\n * abstractions around instances via isRouteErrorResponse()\n */\nexport class ErrorResponseImpl implements ErrorResponse {\n status: number;\n statusText: string;\n data: any;\n private error?: Error;\n private internal: boolean;\n\n constructor(\n status: number,\n statusText: string | undefined,\n data: any,\n internal = false\n ) {\n this.status = status;\n this.statusText = statusText || \"\";\n this.internal = internal;\n if (data instanceof Error) {\n this.data = data.toString();\n this.error = data;\n } else {\n this.data = data;\n }\n }\n}\n\n/**\n * Check if the given error is an ErrorResponse generated from a 4xx/5xx\n * Response thrown from an action/loader\n */\nexport function isRouteErrorResponse(error: any): error is ErrorResponse {\n return (\n error != null &&\n typeof error.status === \"number\" &&\n typeof error.statusText === \"string\" &&\n typeof error.internal === \"boolean\" &&\n \"data\" in error\n );\n}\n","import type { History, Location, Path, To } from \"./history\";\nimport {\n Action as HistoryAction,\n createLocation,\n createPath,\n invariant,\n parsePath,\n warning,\n} from \"./history\";\nimport type {\n AgnosticDataRouteMatch,\n AgnosticDataRouteObject,\n DataStrategyMatch,\n AgnosticRouteObject,\n DataResult,\n DataStrategyFunction,\n DataStrategyFunctionArgs,\n DeferredData,\n DeferredResult,\n DetectErrorBoundaryFunction,\n ErrorResult,\n FormEncType,\n FormMethod,\n HTMLFormMethod,\n DataStrategyResult,\n ImmutableRouteKey,\n MapRoutePropertiesFunction,\n MutationFormMethod,\n RedirectResult,\n RouteData,\n RouteManifest,\n ShouldRevalidateFunctionArgs,\n Submission,\n SuccessResult,\n UIMatch,\n V7_FormMethod,\n V7_MutationFormMethod,\n AgnosticPatchRoutesOnNavigationFunction,\n DataWithResponseInit,\n} from \"./utils\";\nimport {\n ErrorResponseImpl,\n ResultType,\n convertRouteMatchToUiMatch,\n convertRoutesToDataRoutes,\n getPathContributingMatches,\n getResolveToMatches,\n immutableRouteKeys,\n isRouteErrorResponse,\n joinPaths,\n matchRoutes,\n matchRoutesImpl,\n removeDoubleSlashes,\n resolveTo,\n stripBasename,\n} from \"./utils\";\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Types and Constants\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A Router instance manages all navigation and data loading/mutations\n */\nexport interface Router {\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the basename for the router\n */\n get basename(): RouterInit[\"basename\"];\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the future config for the router\n */\n get future(): FutureConfig;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the current state of the router\n */\n get state(): RouterState;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the routes for this router instance\n */\n get routes(): AgnosticDataRouteObject[];\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the window associated with the router\n */\n get window(): RouterInit[\"window\"];\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Initialize the router, including adding history listeners and kicking off\n * initial data fetches. Returns a function to cleanup listeners and abort\n * any in-progress loads\n */\n initialize(): Router;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Subscribe to router.state updates\n *\n * @param fn function to call with the new state\n */\n subscribe(fn: RouterSubscriber): () => void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Enable scroll restoration behavior in the router\n *\n * @param savedScrollPositions Object that will manage positions, in case\n * it's being restored from sessionStorage\n * @param getScrollPosition Function to get the active Y scroll position\n * @param getKey Function to get the key to use for restoration\n */\n enableScrollRestoration(\n savedScrollPositions: Record,\n getScrollPosition: GetScrollPositionFunction,\n getKey?: GetScrollRestorationKeyFunction\n ): () => void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Navigate forward/backward in the history stack\n * @param to Delta to move in the history stack\n */\n navigate(to: number): Promise;\n\n /**\n * Navigate to the given path\n * @param to Path to navigate to\n * @param opts Navigation options (method, submission, etc.)\n */\n navigate(to: To | null, opts?: RouterNavigateOptions): Promise;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Trigger a fetcher load/submission\n *\n * @param key Fetcher key\n * @param routeId Route that owns the fetcher\n * @param href href to fetch\n * @param opts Fetcher options, (method, submission, etc.)\n */\n fetch(\n key: string,\n routeId: string,\n href: string | null,\n opts?: RouterFetchOptions\n ): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Trigger a revalidation of all current route loaders and fetcher loads\n */\n revalidate(): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Utility function to create an href for the given location\n * @param location\n */\n createHref(location: Location | URL): string;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Utility function to URL encode a destination path according to the internal\n * history implementation\n * @param to\n */\n encodeLocation(to: To): Path;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Get/create a fetcher for the given key\n * @param key\n */\n getFetcher(key: string): Fetcher;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Delete the fetcher for a given key\n * @param key\n */\n deleteFetcher(key: string): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Cleanup listeners and abort any in-progress loads\n */\n dispose(): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Get a navigation blocker\n * @param key The identifier for the blocker\n * @param fn The blocker function implementation\n */\n getBlocker(key: string, fn: BlockerFunction): Blocker;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Delete a navigation blocker\n * @param key The identifier for the blocker\n */\n deleteBlocker(key: string): void;\n\n /**\n * @internal\n * PRIVATE DO NOT USE\n *\n * Patch additional children routes into an existing parent route\n * @param routeId The parent route id or a callback function accepting `patch`\n * to perform batch patching\n * @param children The additional children routes\n */\n patchRoutes(routeId: string | null, children: AgnosticRouteObject[]): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * HMR needs to pass in-flight route updates to React Router\n * TODO: Replace this with granular route update APIs (addRoute, updateRoute, deleteRoute)\n */\n _internalSetRoutes(routes: AgnosticRouteObject[]): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Internal fetch AbortControllers accessed by unit tests\n */\n _internalFetchControllers: Map;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Internal pending DeferredData instances accessed by unit tests\n */\n _internalActiveDeferreds: Map;\n}\n\n/**\n * State maintained internally by the router. During a navigation, all states\n * reflect the the \"old\" location unless otherwise noted.\n */\nexport interface RouterState {\n /**\n * The action of the most recent navigation\n */\n historyAction: HistoryAction;\n\n /**\n * The current location reflected by the router\n */\n location: Location;\n\n /**\n * The current set of route matches\n */\n matches: AgnosticDataRouteMatch[];\n\n /**\n * Tracks whether we've completed our initial data load\n */\n initialized: boolean;\n\n /**\n * Current scroll position we should start at for a new view\n * - number -> scroll position to restore to\n * - false -> do not restore scroll at all (used during submissions)\n * - null -> don't have a saved position, scroll to hash or top of page\n */\n restoreScrollPosition: number | false | null;\n\n /**\n * Indicate whether this navigation should skip resetting the scroll position\n * if we are unable to restore the scroll position\n */\n preventScrollReset: boolean;\n\n /**\n * Tracks the state of the current navigation\n */\n navigation: Navigation;\n\n /**\n * Tracks any in-progress revalidations\n */\n revalidation: RevalidationState;\n\n /**\n * Data from the loaders for the current matches\n */\n loaderData: RouteData;\n\n /**\n * Data from the action for the current matches\n */\n actionData: RouteData | null;\n\n /**\n * Errors caught from loaders for the current matches\n */\n errors: RouteData | null;\n\n /**\n * Map of current fetchers\n */\n fetchers: Map;\n\n /**\n * Map of current blockers\n */\n blockers: Map;\n}\n\n/**\n * Data that can be passed into hydrate a Router from SSR\n */\nexport type HydrationState = Partial<\n Pick\n>;\n\n/**\n * Future flags to toggle new feature behavior\n */\nexport interface FutureConfig {\n v7_fetcherPersist: boolean;\n v7_normalizeFormMethod: boolean;\n v7_partialHydration: boolean;\n v7_prependBasename: boolean;\n v7_relativeSplatPath: boolean;\n v7_skipActionErrorRevalidation: boolean;\n}\n\n/**\n * Initialization options for createRouter\n */\nexport interface RouterInit {\n routes: AgnosticRouteObject[];\n history: History;\n basename?: string;\n /**\n * @deprecated Use `mapRouteProperties` instead\n */\n detectErrorBoundary?: DetectErrorBoundaryFunction;\n mapRouteProperties?: MapRoutePropertiesFunction;\n future?: Partial;\n hydrationData?: HydrationState;\n window?: Window;\n dataStrategy?: DataStrategyFunction;\n patchRoutesOnNavigation?: AgnosticPatchRoutesOnNavigationFunction;\n}\n\n/**\n * State returned from a server-side query() call\n */\nexport interface StaticHandlerContext {\n basename: Router[\"basename\"];\n location: RouterState[\"location\"];\n matches: RouterState[\"matches\"];\n loaderData: RouterState[\"loaderData\"];\n actionData: RouterState[\"actionData\"];\n errors: RouterState[\"errors\"];\n statusCode: number;\n loaderHeaders: Record;\n actionHeaders: Record;\n activeDeferreds: Record | null;\n _deepestRenderedBoundaryId?: string | null;\n}\n\n/**\n * A StaticHandler instance manages a singular SSR navigation/fetch event\n */\nexport interface StaticHandler {\n dataRoutes: AgnosticDataRouteObject[];\n query(\n request: Request,\n opts?: {\n requestContext?: unknown;\n skipLoaderErrorBubbling?: boolean;\n dataStrategy?: DataStrategyFunction;\n }\n ): Promise;\n queryRoute(\n request: Request,\n opts?: {\n routeId?: string;\n requestContext?: unknown;\n dataStrategy?: DataStrategyFunction;\n }\n ): Promise;\n}\n\ntype ViewTransitionOpts = {\n currentLocation: Location;\n nextLocation: Location;\n};\n\n/**\n * Subscriber function signature for changes to router state\n */\nexport interface RouterSubscriber {\n (\n state: RouterState,\n opts: {\n deletedFetchers: string[];\n viewTransitionOpts?: ViewTransitionOpts;\n flushSync: boolean;\n }\n ): void;\n}\n\n/**\n * Function signature for determining the key to be used in scroll restoration\n * for a given location\n */\nexport interface GetScrollRestorationKeyFunction {\n (location: Location, matches: UIMatch[]): string | null;\n}\n\n/**\n * Function signature for determining the current scroll position\n */\nexport interface GetScrollPositionFunction {\n (): number;\n}\n\nexport type RelativeRoutingType = \"route\" | \"path\";\n\n// Allowed for any navigation or fetch\ntype BaseNavigateOrFetchOptions = {\n preventScrollReset?: boolean;\n relative?: RelativeRoutingType;\n flushSync?: boolean;\n};\n\n// Only allowed for navigations\ntype BaseNavigateOptions = BaseNavigateOrFetchOptions & {\n replace?: boolean;\n state?: any;\n fromRouteId?: string;\n viewTransition?: boolean;\n};\n\n// Only allowed for submission navigations\ntype BaseSubmissionOptions = {\n formMethod?: HTMLFormMethod;\n formEncType?: FormEncType;\n} & (\n | { formData: FormData; body?: undefined }\n | { formData?: undefined; body: any }\n);\n\n/**\n * Options for a navigate() call for a normal (non-submission) navigation\n */\ntype LinkNavigateOptions = BaseNavigateOptions;\n\n/**\n * Options for a navigate() call for a submission navigation\n */\ntype SubmissionNavigateOptions = BaseNavigateOptions & BaseSubmissionOptions;\n\n/**\n * Options to pass to navigate() for a navigation\n */\nexport type RouterNavigateOptions =\n | LinkNavigateOptions\n | SubmissionNavigateOptions;\n\n/**\n * Options for a fetch() load\n */\ntype LoadFetchOptions = BaseNavigateOrFetchOptions;\n\n/**\n * Options for a fetch() submission\n */\ntype SubmitFetchOptions = BaseNavigateOrFetchOptions & BaseSubmissionOptions;\n\n/**\n * Options to pass to fetch()\n */\nexport type RouterFetchOptions = LoadFetchOptions | SubmitFetchOptions;\n\n/**\n * Potential states for state.navigation\n */\nexport type NavigationStates = {\n Idle: {\n state: \"idle\";\n location: undefined;\n formMethod: undefined;\n formAction: undefined;\n formEncType: undefined;\n formData: undefined;\n json: undefined;\n text: undefined;\n };\n Loading: {\n state: \"loading\";\n location: Location;\n formMethod: Submission[\"formMethod\"] | undefined;\n formAction: Submission[\"formAction\"] | undefined;\n formEncType: Submission[\"formEncType\"] | undefined;\n formData: Submission[\"formData\"] | undefined;\n json: Submission[\"json\"] | undefined;\n text: Submission[\"text\"] | undefined;\n };\n Submitting: {\n state: \"submitting\";\n location: Location;\n formMethod: Submission[\"formMethod\"];\n formAction: Submission[\"formAction\"];\n formEncType: Submission[\"formEncType\"];\n formData: Submission[\"formData\"];\n json: Submission[\"json\"];\n text: Submission[\"text\"];\n };\n};\n\nexport type Navigation = NavigationStates[keyof NavigationStates];\n\nexport type RevalidationState = \"idle\" | \"loading\";\n\n/**\n * Potential states for fetchers\n */\ntype FetcherStates = {\n Idle: {\n state: \"idle\";\n formMethod: undefined;\n formAction: undefined;\n formEncType: undefined;\n text: undefined;\n formData: undefined;\n json: undefined;\n data: TData | undefined;\n };\n Loading: {\n state: \"loading\";\n formMethod: Submission[\"formMethod\"] | undefined;\n formAction: Submission[\"formAction\"] | undefined;\n formEncType: Submission[\"formEncType\"] | undefined;\n text: Submission[\"text\"] | undefined;\n formData: Submission[\"formData\"] | undefined;\n json: Submission[\"json\"] | undefined;\n data: TData | undefined;\n };\n Submitting: {\n state: \"submitting\";\n formMethod: Submission[\"formMethod\"];\n formAction: Submission[\"formAction\"];\n formEncType: Submission[\"formEncType\"];\n text: Submission[\"text\"];\n formData: Submission[\"formData\"];\n json: Submission[\"json\"];\n data: TData | undefined;\n };\n};\n\nexport type Fetcher =\n FetcherStates[keyof FetcherStates];\n\ninterface BlockerBlocked {\n state: \"blocked\";\n reset(): void;\n proceed(): void;\n location: Location;\n}\n\ninterface BlockerUnblocked {\n state: \"unblocked\";\n reset: undefined;\n proceed: undefined;\n location: undefined;\n}\n\ninterface BlockerProceeding {\n state: \"proceeding\";\n reset: undefined;\n proceed: undefined;\n location: Location;\n}\n\nexport type Blocker = BlockerUnblocked | BlockerBlocked | BlockerProceeding;\n\nexport type BlockerFunction = (args: {\n currentLocation: Location;\n nextLocation: Location;\n historyAction: HistoryAction;\n}) => boolean;\n\ninterface ShortCircuitable {\n /**\n * startNavigation does not need to complete the navigation because we\n * redirected or got interrupted\n */\n shortCircuited?: boolean;\n}\n\ntype PendingActionResult = [string, SuccessResult | ErrorResult];\n\ninterface HandleActionResult extends ShortCircuitable {\n /**\n * Route matches which may have been updated from fog of war discovery\n */\n matches?: RouterState[\"matches\"];\n /**\n * Tuple for the returned or thrown value from the current action. The routeId\n * is the action route for success and the bubbled boundary route for errors.\n */\n pendingActionResult?: PendingActionResult;\n}\n\ninterface HandleLoadersResult extends ShortCircuitable {\n /**\n * Route matches which may have been updated from fog of war discovery\n */\n matches?: RouterState[\"matches\"];\n /**\n * loaderData returned from the current set of loaders\n */\n loaderData?: RouterState[\"loaderData\"];\n /**\n * errors thrown from the current set of loaders\n */\n errors?: RouterState[\"errors\"];\n}\n\n/**\n * Cached info for active fetcher.load() instances so they can participate\n * in revalidation\n */\ninterface FetchLoadMatch {\n routeId: string;\n path: string;\n}\n\n/**\n * Identified fetcher.load() calls that need to be revalidated\n */\ninterface RevalidatingFetcher extends FetchLoadMatch {\n key: string;\n match: AgnosticDataRouteMatch | null;\n matches: AgnosticDataRouteMatch[] | null;\n controller: AbortController | null;\n}\n\nconst validMutationMethodsArr: MutationFormMethod[] = [\n \"post\",\n \"put\",\n \"patch\",\n \"delete\",\n];\nconst validMutationMethods = new Set(\n validMutationMethodsArr\n);\n\nconst validRequestMethodsArr: FormMethod[] = [\n \"get\",\n ...validMutationMethodsArr,\n];\nconst validRequestMethods = new Set(validRequestMethodsArr);\n\nconst redirectStatusCodes = new Set([301, 302, 303, 307, 308]);\nconst redirectPreserveMethodStatusCodes = new Set([307, 308]);\n\nexport const IDLE_NAVIGATION: NavigationStates[\"Idle\"] = {\n state: \"idle\",\n location: undefined,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n};\n\nexport const IDLE_FETCHER: FetcherStates[\"Idle\"] = {\n state: \"idle\",\n data: undefined,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n};\n\nexport const IDLE_BLOCKER: BlockerUnblocked = {\n state: \"unblocked\",\n proceed: undefined,\n reset: undefined,\n location: undefined,\n};\n\nconst ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i;\n\nconst defaultMapRouteProperties: MapRoutePropertiesFunction = (route) => ({\n hasErrorBoundary: Boolean(route.hasErrorBoundary),\n});\n\nconst TRANSITIONS_STORAGE_KEY = \"remix-router-transitions\";\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region createRouter\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Create a router and listen to history POP navigations\n */\nexport function createRouter(init: RouterInit): Router {\n const routerWindow = init.window\n ? init.window\n : typeof window !== \"undefined\"\n ? window\n : undefined;\n const isBrowser =\n typeof routerWindow !== \"undefined\" &&\n typeof routerWindow.document !== \"undefined\" &&\n typeof routerWindow.document.createElement !== \"undefined\";\n const isServer = !isBrowser;\n\n invariant(\n init.routes.length > 0,\n \"You must provide a non-empty routes array to createRouter\"\n );\n\n let mapRouteProperties: MapRoutePropertiesFunction;\n if (init.mapRouteProperties) {\n mapRouteProperties = init.mapRouteProperties;\n } else if (init.detectErrorBoundary) {\n // If they are still using the deprecated version, wrap it with the new API\n let detectErrorBoundary = init.detectErrorBoundary;\n mapRouteProperties = (route) => ({\n hasErrorBoundary: detectErrorBoundary(route),\n });\n } else {\n mapRouteProperties = defaultMapRouteProperties;\n }\n\n // Routes keyed by ID\n let manifest: RouteManifest = {};\n // Routes in tree format for matching\n let dataRoutes = convertRoutesToDataRoutes(\n init.routes,\n mapRouteProperties,\n undefined,\n manifest\n );\n let inFlightDataRoutes: AgnosticDataRouteObject[] | undefined;\n let basename = init.basename || \"/\";\n let dataStrategyImpl = init.dataStrategy || defaultDataStrategy;\n let patchRoutesOnNavigationImpl = init.patchRoutesOnNavigation;\n\n // Config driven behavior flags\n let future: FutureConfig = {\n v7_fetcherPersist: false,\n v7_normalizeFormMethod: false,\n v7_partialHydration: false,\n v7_prependBasename: false,\n v7_relativeSplatPath: false,\n v7_skipActionErrorRevalidation: false,\n ...init.future,\n };\n // Cleanup function for history\n let unlistenHistory: (() => void) | null = null;\n // Externally-provided functions to call on all state changes\n let subscribers = new Set();\n // Externally-provided object to hold scroll restoration locations during routing\n let savedScrollPositions: Record | null = null;\n // Externally-provided function to get scroll restoration keys\n let getScrollRestorationKey: GetScrollRestorationKeyFunction | null = null;\n // Externally-provided function to get current scroll position\n let getScrollPosition: GetScrollPositionFunction | null = null;\n // One-time flag to control the initial hydration scroll restoration. Because\n // we don't get the saved positions from until _after_\n // the initial render, we need to manually trigger a separate updateState to\n // send along the restoreScrollPosition\n // Set to true if we have `hydrationData` since we assume we were SSR'd and that\n // SSR did the initial scroll restoration.\n let initialScrollRestored = init.hydrationData != null;\n\n let initialMatches = matchRoutes(dataRoutes, init.history.location, basename);\n let initialMatchesIsFOW = false;\n let initialErrors: RouteData | null = null;\n\n if (initialMatches == null && !patchRoutesOnNavigationImpl) {\n // If we do not match a user-provided-route, fall back to the root\n // to allow the error boundary to take over\n let error = getInternalRouterError(404, {\n pathname: init.history.location.pathname,\n });\n let { matches, route } = getShortCircuitMatches(dataRoutes);\n initialMatches = matches;\n initialErrors = { [route.id]: error };\n }\n\n // In SPA apps, if the user provided a patchRoutesOnNavigation implementation and\n // our initial match is a splat route, clear them out so we run through lazy\n // discovery on hydration in case there's a more accurate lazy route match.\n // In SSR apps (with `hydrationData`), we expect that the server will send\n // up the proper matched routes so we don't want to run lazy discovery on\n // initial hydration and want to hydrate into the splat route.\n if (initialMatches && !init.hydrationData) {\n let fogOfWar = checkFogOfWar(\n initialMatches,\n dataRoutes,\n init.history.location.pathname\n );\n if (fogOfWar.active) {\n initialMatches = null;\n }\n }\n\n let initialized: boolean;\n if (!initialMatches) {\n initialized = false;\n initialMatches = [];\n\n // If partial hydration and fog of war is enabled, we will be running\n // `patchRoutesOnNavigation` during hydration so include any partial matches as\n // the initial matches so we can properly render `HydrateFallback`'s\n if (future.v7_partialHydration) {\n let fogOfWar = checkFogOfWar(\n null,\n dataRoutes,\n init.history.location.pathname\n );\n if (fogOfWar.active && fogOfWar.matches) {\n initialMatchesIsFOW = true;\n initialMatches = fogOfWar.matches;\n }\n }\n } else if (initialMatches.some((m) => m.route.lazy)) {\n // All initialMatches need to be loaded before we're ready. If we have lazy\n // functions around still then we'll need to run them in initialize()\n initialized = false;\n } else if (!initialMatches.some((m) => m.route.loader)) {\n // If we've got no loaders to run, then we're good to go\n initialized = true;\n } else if (future.v7_partialHydration) {\n // If partial hydration is enabled, we're initialized so long as we were\n // provided with hydrationData for every route with a loader, and no loaders\n // were marked for explicit hydration\n let loaderData = init.hydrationData ? init.hydrationData.loaderData : null;\n let errors = init.hydrationData ? init.hydrationData.errors : null;\n // If errors exist, don't consider routes below the boundary\n if (errors) {\n let idx = initialMatches.findIndex(\n (m) => errors![m.route.id] !== undefined\n );\n initialized = initialMatches\n .slice(0, idx + 1)\n .every((m) => !shouldLoadRouteOnHydration(m.route, loaderData, errors));\n } else {\n initialized = initialMatches.every(\n (m) => !shouldLoadRouteOnHydration(m.route, loaderData, errors)\n );\n }\n } else {\n // Without partial hydration - we're initialized if we were provided any\n // hydrationData - which is expected to be complete\n initialized = init.hydrationData != null;\n }\n\n let router: Router;\n let state: RouterState = {\n historyAction: init.history.action,\n location: init.history.location,\n matches: initialMatches,\n initialized,\n navigation: IDLE_NAVIGATION,\n // Don't restore on initial updateState() if we were SSR'd\n restoreScrollPosition: init.hydrationData != null ? false : null,\n preventScrollReset: false,\n revalidation: \"idle\",\n loaderData: (init.hydrationData && init.hydrationData.loaderData) || {},\n actionData: (init.hydrationData && init.hydrationData.actionData) || null,\n errors: (init.hydrationData && init.hydrationData.errors) || initialErrors,\n fetchers: new Map(),\n blockers: new Map(),\n };\n\n // -- Stateful internal variables to manage navigations --\n // Current navigation in progress (to be committed in completeNavigation)\n let pendingAction: HistoryAction = HistoryAction.Pop;\n\n // Should the current navigation prevent the scroll reset if scroll cannot\n // be restored?\n let pendingPreventScrollReset = false;\n\n // AbortController for the active navigation\n let pendingNavigationController: AbortController | null;\n\n // Should the current navigation enable document.startViewTransition?\n let pendingViewTransitionEnabled = false;\n\n // Store applied view transitions so we can apply them on POP\n let appliedViewTransitions: Map> = new Map<\n string,\n Set\n >();\n\n // Cleanup function for persisting applied transitions to sessionStorage\n let removePageHideEventListener: (() => void) | null = null;\n\n // We use this to avoid touching history in completeNavigation if a\n // revalidation is entirely uninterrupted\n let isUninterruptedRevalidation = false;\n\n // Use this internal flag to force revalidation of all loaders:\n // - submissions (completed or interrupted)\n // - useRevalidator()\n // - X-Remix-Revalidate (from redirect)\n let isRevalidationRequired = false;\n\n // Use this internal array to capture routes that require revalidation due\n // to a cancelled deferred on action submission\n let cancelledDeferredRoutes: string[] = [];\n\n // Use this internal array to capture fetcher loads that were cancelled by an\n // action navigation and require revalidation\n let cancelledFetcherLoads: Set = new Set();\n\n // AbortControllers for any in-flight fetchers\n let fetchControllers = new Map();\n\n // Track loads based on the order in which they started\n let incrementingLoadId = 0;\n\n // Track the outstanding pending navigation data load to be compared against\n // the globally incrementing load when a fetcher load lands after a completed\n // navigation\n let pendingNavigationLoadId = -1;\n\n // Fetchers that triggered data reloads as a result of their actions\n let fetchReloadIds = new Map();\n\n // Fetchers that triggered redirect navigations\n let fetchRedirectIds = new Set();\n\n // Most recent href/match for fetcher.load calls for fetchers\n let fetchLoadMatches = new Map();\n\n // Ref-count mounted fetchers so we know when it's ok to clean them up\n let activeFetchers = new Map();\n\n // Fetchers that have requested a delete when using v7_fetcherPersist,\n // they'll be officially removed after they return to idle\n let deletedFetchers = new Set();\n\n // Store DeferredData instances for active route matches. When a\n // route loader returns defer() we stick one in here. Then, when a nested\n // promise resolves we update loaderData. If a new navigation starts we\n // cancel active deferreds for eliminated routes.\n let activeDeferreds = new Map();\n\n // Store blocker functions in a separate Map outside of router state since\n // we don't need to update UI state if they change\n let blockerFunctions = new Map();\n\n // Map of pending patchRoutesOnNavigation() promises (keyed by path/matches) so\n // that we only kick them off once for a given combo\n let pendingPatchRoutes = new Map<\n string,\n ReturnType\n >();\n\n // Flag to ignore the next history update, so we can revert the URL change on\n // a POP navigation that was blocked by the user without touching router state\n let unblockBlockerHistoryUpdate: (() => void) | undefined = undefined;\n\n // Initialize the router, all side effects should be kicked off from here.\n // Implemented as a Fluent API for ease of:\n // let router = createRouter(init).initialize();\n function initialize() {\n // If history informs us of a POP navigation, start the navigation but do not update\n // state. We'll update our own state once the navigation completes\n unlistenHistory = init.history.listen(\n ({ action: historyAction, location, delta }) => {\n // Ignore this event if it was just us resetting the URL from a\n // blocked POP navigation\n if (unblockBlockerHistoryUpdate) {\n unblockBlockerHistoryUpdate();\n unblockBlockerHistoryUpdate = undefined;\n return;\n }\n\n warning(\n blockerFunctions.size === 0 || delta != null,\n \"You are trying to use a blocker on a POP navigation to a location \" +\n \"that was not created by @remix-run/router. This will fail silently in \" +\n \"production. This can happen if you are navigating outside the router \" +\n \"via `window.history.pushState`/`window.location.hash` instead of using \" +\n \"router navigation APIs. This can also happen if you are using \" +\n \"createHashRouter and the user manually changes the URL.\"\n );\n\n let blockerKey = shouldBlockNavigation({\n currentLocation: state.location,\n nextLocation: location,\n historyAction,\n });\n\n if (blockerKey && delta != null) {\n // Restore the URL to match the current UI, but don't update router state\n let nextHistoryUpdatePromise = new Promise((resolve) => {\n unblockBlockerHistoryUpdate = resolve;\n });\n init.history.go(delta * -1);\n\n // Put the blocker into a blocked state\n updateBlocker(blockerKey, {\n state: \"blocked\",\n location,\n proceed() {\n updateBlocker(blockerKey!, {\n state: \"proceeding\",\n proceed: undefined,\n reset: undefined,\n location,\n });\n // Re-do the same POP navigation we just blocked, after the url\n // restoration is also complete. See:\n // https://github.com/remix-run/react-router/issues/11613\n nextHistoryUpdatePromise.then(() => init.history.go(delta));\n },\n reset() {\n let blockers = new Map(state.blockers);\n blockers.set(blockerKey!, IDLE_BLOCKER);\n updateState({ blockers });\n },\n });\n return;\n }\n\n return startNavigation(historyAction, location);\n }\n );\n\n if (isBrowser) {\n // FIXME: This feels gross. How can we cleanup the lines between\n // scrollRestoration/appliedTransitions persistance?\n restoreAppliedTransitions(routerWindow, appliedViewTransitions);\n let _saveAppliedTransitions = () =>\n persistAppliedTransitions(routerWindow, appliedViewTransitions);\n routerWindow.addEventListener(\"pagehide\", _saveAppliedTransitions);\n removePageHideEventListener = () =>\n routerWindow.removeEventListener(\"pagehide\", _saveAppliedTransitions);\n }\n\n // Kick off initial data load if needed. Use Pop to avoid modifying history\n // Note we don't do any handling of lazy here. For SPA's it'll get handled\n // in the normal navigation flow. For SSR it's expected that lazy modules are\n // resolved prior to router creation since we can't go into a fallbackElement\n // UI for SSR'd apps\n if (!state.initialized) {\n startNavigation(HistoryAction.Pop, state.location, {\n initialHydration: true,\n });\n }\n\n return router;\n }\n\n // Clean up a router and it's side effects\n function dispose() {\n if (unlistenHistory) {\n unlistenHistory();\n }\n if (removePageHideEventListener) {\n removePageHideEventListener();\n }\n subscribers.clear();\n pendingNavigationController && pendingNavigationController.abort();\n state.fetchers.forEach((_, key) => deleteFetcher(key));\n state.blockers.forEach((_, key) => deleteBlocker(key));\n }\n\n // Subscribe to state updates for the router\n function subscribe(fn: RouterSubscriber) {\n subscribers.add(fn);\n return () => subscribers.delete(fn);\n }\n\n // Update our state and notify the calling context of the change\n function updateState(\n newState: Partial,\n opts: {\n flushSync?: boolean;\n viewTransitionOpts?: ViewTransitionOpts;\n } = {}\n ): void {\n state = {\n ...state,\n ...newState,\n };\n\n // Prep fetcher cleanup so we can tell the UI which fetcher data entries\n // can be removed\n let completedFetchers: string[] = [];\n let deletedFetchersKeys: string[] = [];\n\n if (future.v7_fetcherPersist) {\n state.fetchers.forEach((fetcher, key) => {\n if (fetcher.state === \"idle\") {\n if (deletedFetchers.has(key)) {\n // Unmounted from the UI and can be totally removed\n deletedFetchersKeys.push(key);\n } else {\n // Returned to idle but still mounted in the UI, so semi-remains for\n // revalidations and such\n completedFetchers.push(key);\n }\n }\n });\n }\n\n // Remove any lingering deleted fetchers that have already been removed\n // from state.fetchers\n deletedFetchers.forEach((key) => {\n if (!state.fetchers.has(key) && !fetchControllers.has(key)) {\n deletedFetchersKeys.push(key);\n }\n });\n\n // Iterate over a local copy so that if flushSync is used and we end up\n // removing and adding a new subscriber due to the useCallback dependencies,\n // we don't get ourselves into a loop calling the new subscriber immediately\n [...subscribers].forEach((subscriber) =>\n subscriber(state, {\n deletedFetchers: deletedFetchersKeys,\n viewTransitionOpts: opts.viewTransitionOpts,\n flushSync: opts.flushSync === true,\n })\n );\n\n // Remove idle fetchers from state since we only care about in-flight fetchers.\n if (future.v7_fetcherPersist) {\n completedFetchers.forEach((key) => state.fetchers.delete(key));\n deletedFetchersKeys.forEach((key) => deleteFetcher(key));\n } else {\n // We already called deleteFetcher() on these, can remove them from this\n // Set now that we've handed the keys off to the data layer\n deletedFetchersKeys.forEach((key) => deletedFetchers.delete(key));\n }\n }\n\n // Complete a navigation returning the state.navigation back to the IDLE_NAVIGATION\n // and setting state.[historyAction/location/matches] to the new route.\n // - Location is a required param\n // - Navigation will always be set to IDLE_NAVIGATION\n // - Can pass any other state in newState\n function completeNavigation(\n location: Location,\n newState: Partial>,\n { flushSync }: { flushSync?: boolean } = {}\n ): void {\n // Deduce if we're in a loading/actionReload state:\n // - We have committed actionData in the store\n // - The current navigation was a mutation submission\n // - We're past the submitting state and into the loading state\n // - The location being loaded is not the result of a redirect\n let isActionReload =\n state.actionData != null &&\n state.navigation.formMethod != null &&\n isMutationMethod(state.navigation.formMethod) &&\n state.navigation.state === \"loading\" &&\n location.state?._isRedirect !== true;\n\n let actionData: RouteData | null;\n if (newState.actionData) {\n if (Object.keys(newState.actionData).length > 0) {\n actionData = newState.actionData;\n } else {\n // Empty actionData -> clear prior actionData due to an action error\n actionData = null;\n }\n } else if (isActionReload) {\n // Keep the current data if we're wrapping up the action reload\n actionData = state.actionData;\n } else {\n // Clear actionData on any other completed navigations\n actionData = null;\n }\n\n // Always preserve any existing loaderData from re-used routes\n let loaderData = newState.loaderData\n ? mergeLoaderData(\n state.loaderData,\n newState.loaderData,\n newState.matches || [],\n newState.errors\n )\n : state.loaderData;\n\n // On a successful navigation we can assume we got through all blockers\n // so we can start fresh\n let blockers = state.blockers;\n if (blockers.size > 0) {\n blockers = new Map(blockers);\n blockers.forEach((_, k) => blockers.set(k, IDLE_BLOCKER));\n }\n\n // Always respect the user flag. Otherwise don't reset on mutation\n // submission navigations unless they redirect\n let preventScrollReset =\n pendingPreventScrollReset === true ||\n (state.navigation.formMethod != null &&\n isMutationMethod(state.navigation.formMethod) &&\n location.state?._isRedirect !== true);\n\n // Commit any in-flight routes at the end of the HMR revalidation \"navigation\"\n if (inFlightDataRoutes) {\n dataRoutes = inFlightDataRoutes;\n inFlightDataRoutes = undefined;\n }\n\n if (isUninterruptedRevalidation) {\n // If this was an uninterrupted revalidation then do not touch history\n } else if (pendingAction === HistoryAction.Pop) {\n // Do nothing for POP - URL has already been updated\n } else if (pendingAction === HistoryAction.Push) {\n init.history.push(location, location.state);\n } else if (pendingAction === HistoryAction.Replace) {\n init.history.replace(location, location.state);\n }\n\n let viewTransitionOpts: ViewTransitionOpts | undefined;\n\n // On POP, enable transitions if they were enabled on the original navigation\n if (pendingAction === HistoryAction.Pop) {\n // Forward takes precedence so they behave like the original navigation\n let priorPaths = appliedViewTransitions.get(state.location.pathname);\n if (priorPaths && priorPaths.has(location.pathname)) {\n viewTransitionOpts = {\n currentLocation: state.location,\n nextLocation: location,\n };\n } else if (appliedViewTransitions.has(location.pathname)) {\n // If we don't have a previous forward nav, assume we're popping back to\n // the new location and enable if that location previously enabled\n viewTransitionOpts = {\n currentLocation: location,\n nextLocation: state.location,\n };\n }\n } else if (pendingViewTransitionEnabled) {\n // Store the applied transition on PUSH/REPLACE\n let toPaths = appliedViewTransitions.get(state.location.pathname);\n if (toPaths) {\n toPaths.add(location.pathname);\n } else {\n toPaths = new Set([location.pathname]);\n appliedViewTransitions.set(state.location.pathname, toPaths);\n }\n viewTransitionOpts = {\n currentLocation: state.location,\n nextLocation: location,\n };\n }\n\n updateState(\n {\n ...newState, // matches, errors, fetchers go through as-is\n actionData,\n loaderData,\n historyAction: pendingAction,\n location,\n initialized: true,\n navigation: IDLE_NAVIGATION,\n revalidation: \"idle\",\n restoreScrollPosition: getSavedScrollPosition(\n location,\n newState.matches || state.matches\n ),\n preventScrollReset,\n blockers,\n },\n {\n viewTransitionOpts,\n flushSync: flushSync === true,\n }\n );\n\n // Reset stateful navigation vars\n pendingAction = HistoryAction.Pop;\n pendingPreventScrollReset = false;\n pendingViewTransitionEnabled = false;\n isUninterruptedRevalidation = false;\n isRevalidationRequired = false;\n cancelledDeferredRoutes = [];\n }\n\n // Trigger a navigation event, which can either be a numerical POP or a PUSH\n // replace with an optional submission\n async function navigate(\n to: number | To | null,\n opts?: RouterNavigateOptions\n ): Promise {\n if (typeof to === \"number\") {\n init.history.go(to);\n return;\n }\n\n let normalizedPath = normalizeTo(\n state.location,\n state.matches,\n basename,\n future.v7_prependBasename,\n to,\n future.v7_relativeSplatPath,\n opts?.fromRouteId,\n opts?.relative\n );\n let { path, submission, error } = normalizeNavigateOptions(\n future.v7_normalizeFormMethod,\n false,\n normalizedPath,\n opts\n );\n\n let currentLocation = state.location;\n let nextLocation = createLocation(state.location, path, opts && opts.state);\n\n // When using navigate as a PUSH/REPLACE we aren't reading an already-encoded\n // URL from window.location, so we need to encode it here so the behavior\n // remains the same as POP and non-data-router usages. new URL() does all\n // the same encoding we'd get from a history.pushState/window.location read\n // without having to touch history\n nextLocation = {\n ...nextLocation,\n ...init.history.encodeLocation(nextLocation),\n };\n\n let userReplace = opts && opts.replace != null ? opts.replace : undefined;\n\n let historyAction = HistoryAction.Push;\n\n if (userReplace === true) {\n historyAction = HistoryAction.Replace;\n } else if (userReplace === false) {\n // no-op\n } else if (\n submission != null &&\n isMutationMethod(submission.formMethod) &&\n submission.formAction === state.location.pathname + state.location.search\n ) {\n // By default on submissions to the current location we REPLACE so that\n // users don't have to double-click the back button to get to the prior\n // location. If the user redirects to a different location from the\n // action/loader this will be ignored and the redirect will be a PUSH\n historyAction = HistoryAction.Replace;\n }\n\n let preventScrollReset =\n opts && \"preventScrollReset\" in opts\n ? opts.preventScrollReset === true\n : undefined;\n\n let flushSync = (opts && opts.flushSync) === true;\n\n let blockerKey = shouldBlockNavigation({\n currentLocation,\n nextLocation,\n historyAction,\n });\n\n if (blockerKey) {\n // Put the blocker into a blocked state\n updateBlocker(blockerKey, {\n state: \"blocked\",\n location: nextLocation,\n proceed() {\n updateBlocker(blockerKey!, {\n state: \"proceeding\",\n proceed: undefined,\n reset: undefined,\n location: nextLocation,\n });\n // Send the same navigation through\n navigate(to, opts);\n },\n reset() {\n let blockers = new Map(state.blockers);\n blockers.set(blockerKey!, IDLE_BLOCKER);\n updateState({ blockers });\n },\n });\n return;\n }\n\n return await startNavigation(historyAction, nextLocation, {\n submission,\n // Send through the formData serialization error if we have one so we can\n // render at the right error boundary after we match routes\n pendingError: error,\n preventScrollReset,\n replace: opts && opts.replace,\n enableViewTransition: opts && opts.viewTransition,\n flushSync,\n });\n }\n\n // Revalidate all current loaders. If a navigation is in progress or if this\n // is interrupted by a navigation, allow this to \"succeed\" by calling all\n // loaders during the next loader round\n function revalidate() {\n interruptActiveLoads();\n updateState({ revalidation: \"loading\" });\n\n // If we're currently submitting an action, we don't need to start a new\n // navigation, we'll just let the follow up loader execution call all loaders\n if (state.navigation.state === \"submitting\") {\n return;\n }\n\n // If we're currently in an idle state, start a new navigation for the current\n // action/location and mark it as uninterrupted, which will skip the history\n // update in completeNavigation\n if (state.navigation.state === \"idle\") {\n startNavigation(state.historyAction, state.location, {\n startUninterruptedRevalidation: true,\n });\n return;\n }\n\n // Otherwise, if we're currently in a loading state, just start a new\n // navigation to the navigation.location but do not trigger an uninterrupted\n // revalidation so that history correctly updates once the navigation completes\n startNavigation(\n pendingAction || state.historyAction,\n state.navigation.location,\n {\n overrideNavigation: state.navigation,\n // Proxy through any rending view transition\n enableViewTransition: pendingViewTransitionEnabled === true,\n }\n );\n }\n\n // Start a navigation to the given action/location. Can optionally provide a\n // overrideNavigation which will override the normalLoad in the case of a redirect\n // navigation\n async function startNavigation(\n historyAction: HistoryAction,\n location: Location,\n opts?: {\n initialHydration?: boolean;\n submission?: Submission;\n fetcherSubmission?: Submission;\n overrideNavigation?: Navigation;\n pendingError?: ErrorResponseImpl;\n startUninterruptedRevalidation?: boolean;\n preventScrollReset?: boolean;\n replace?: boolean;\n enableViewTransition?: boolean;\n flushSync?: boolean;\n }\n ): Promise {\n // Abort any in-progress navigations and start a new one. Unset any ongoing\n // uninterrupted revalidations unless told otherwise, since we want this\n // new navigation to update history normally\n pendingNavigationController && pendingNavigationController.abort();\n pendingNavigationController = null;\n pendingAction = historyAction;\n isUninterruptedRevalidation =\n (opts && opts.startUninterruptedRevalidation) === true;\n\n // Save the current scroll position every time we start a new navigation,\n // and track whether we should reset scroll on completion\n saveScrollPosition(state.location, state.matches);\n pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;\n\n pendingViewTransitionEnabled = (opts && opts.enableViewTransition) === true;\n\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let loadingNavigation = opts && opts.overrideNavigation;\n let matches =\n opts?.initialHydration &&\n state.matches &&\n state.matches.length > 0 &&\n !initialMatchesIsFOW\n ? // `matchRoutes()` has already been called if we're in here via `router.initialize()`\n state.matches\n : matchRoutes(routesToUse, location, basename);\n let flushSync = (opts && opts.flushSync) === true;\n\n // Short circuit if it's only a hash change and not a revalidation or\n // mutation submission.\n //\n // Ignore on initial page loads because since the initial hydration will always\n // be \"same hash\". For example, on /page#hash and submit a \n // which will default to a navigation to /page\n if (\n matches &&\n state.initialized &&\n !isRevalidationRequired &&\n isHashChangeOnly(state.location, location) &&\n !(opts && opts.submission && isMutationMethod(opts.submission.formMethod))\n ) {\n completeNavigation(location, { matches }, { flushSync });\n return;\n }\n\n let fogOfWar = checkFogOfWar(matches, routesToUse, location.pathname);\n if (fogOfWar.active && fogOfWar.matches) {\n matches = fogOfWar.matches;\n }\n\n // Short circuit with a 404 on the root error boundary if we match nothing\n if (!matches) {\n let { error, notFoundMatches, route } = handleNavigational404(\n location.pathname\n );\n completeNavigation(\n location,\n {\n matches: notFoundMatches,\n loaderData: {},\n errors: {\n [route.id]: error,\n },\n },\n { flushSync }\n );\n return;\n }\n\n // Create a controller/Request for this navigation\n pendingNavigationController = new AbortController();\n let request = createClientSideRequest(\n init.history,\n location,\n pendingNavigationController.signal,\n opts && opts.submission\n );\n let pendingActionResult: PendingActionResult | undefined;\n\n if (opts && opts.pendingError) {\n // If we have a pendingError, it means the user attempted a GET submission\n // with binary FormData so assign here and skip to handleLoaders. That\n // way we handle calling loaders above the boundary etc. It's not really\n // different from an actionError in that sense.\n pendingActionResult = [\n findNearestBoundary(matches).route.id,\n { type: ResultType.error, error: opts.pendingError },\n ];\n } else if (\n opts &&\n opts.submission &&\n isMutationMethod(opts.submission.formMethod)\n ) {\n // Call action if we received an action submission\n let actionResult = await handleAction(\n request,\n location,\n opts.submission,\n matches,\n fogOfWar.active,\n { replace: opts.replace, flushSync }\n );\n\n if (actionResult.shortCircuited) {\n return;\n }\n\n // If we received a 404 from handleAction, it's because we couldn't lazily\n // discover the destination route so we don't want to call loaders\n if (actionResult.pendingActionResult) {\n let [routeId, result] = actionResult.pendingActionResult;\n if (\n isErrorResult(result) &&\n isRouteErrorResponse(result.error) &&\n result.error.status === 404\n ) {\n pendingNavigationController = null;\n\n completeNavigation(location, {\n matches: actionResult.matches,\n loaderData: {},\n errors: {\n [routeId]: result.error,\n },\n });\n return;\n }\n }\n\n matches = actionResult.matches || matches;\n pendingActionResult = actionResult.pendingActionResult;\n loadingNavigation = getLoadingNavigation(location, opts.submission);\n flushSync = false;\n // No need to do fog of war matching again on loader execution\n fogOfWar.active = false;\n\n // Create a GET request for the loaders\n request = createClientSideRequest(\n init.history,\n request.url,\n request.signal\n );\n }\n\n // Call loaders\n let {\n shortCircuited,\n matches: updatedMatches,\n loaderData,\n errors,\n } = await handleLoaders(\n request,\n location,\n matches,\n fogOfWar.active,\n loadingNavigation,\n opts && opts.submission,\n opts && opts.fetcherSubmission,\n opts && opts.replace,\n opts && opts.initialHydration === true,\n flushSync,\n pendingActionResult\n );\n\n if (shortCircuited) {\n return;\n }\n\n // Clean up now that the action/loaders have completed. Don't clean up if\n // we short circuited because pendingNavigationController will have already\n // been assigned to a new controller for the next navigation\n pendingNavigationController = null;\n\n completeNavigation(location, {\n matches: updatedMatches || matches,\n ...getActionDataForCommit(pendingActionResult),\n loaderData,\n errors,\n });\n }\n\n // Call the action matched by the leaf route for this navigation and handle\n // redirects/errors\n async function handleAction(\n request: Request,\n location: Location,\n submission: Submission,\n matches: AgnosticDataRouteMatch[],\n isFogOfWar: boolean,\n opts: { replace?: boolean; flushSync?: boolean } = {}\n ): Promise {\n interruptActiveLoads();\n\n // Put us in a submitting state\n let navigation = getSubmittingNavigation(location, submission);\n updateState({ navigation }, { flushSync: opts.flushSync === true });\n\n if (isFogOfWar) {\n let discoverResult = await discoverRoutes(\n matches,\n location.pathname,\n request.signal\n );\n if (discoverResult.type === \"aborted\") {\n return { shortCircuited: true };\n } else if (discoverResult.type === \"error\") {\n let boundaryId = findNearestBoundary(discoverResult.partialMatches)\n .route.id;\n return {\n matches: discoverResult.partialMatches,\n pendingActionResult: [\n boundaryId,\n {\n type: ResultType.error,\n error: discoverResult.error,\n },\n ],\n };\n } else if (!discoverResult.matches) {\n let { notFoundMatches, error, route } = handleNavigational404(\n location.pathname\n );\n return {\n matches: notFoundMatches,\n pendingActionResult: [\n route.id,\n {\n type: ResultType.error,\n error,\n },\n ],\n };\n } else {\n matches = discoverResult.matches;\n }\n }\n\n // Call our action and get the result\n let result: DataResult;\n let actionMatch = getTargetMatch(matches, location);\n\n if (!actionMatch.route.action && !actionMatch.route.lazy) {\n result = {\n type: ResultType.error,\n error: getInternalRouterError(405, {\n method: request.method,\n pathname: location.pathname,\n routeId: actionMatch.route.id,\n }),\n };\n } else {\n let results = await callDataStrategy(\n \"action\",\n state,\n request,\n [actionMatch],\n matches,\n null\n );\n result = results[actionMatch.route.id];\n\n if (request.signal.aborted) {\n return { shortCircuited: true };\n }\n }\n\n if (isRedirectResult(result)) {\n let replace: boolean;\n if (opts && opts.replace != null) {\n replace = opts.replace;\n } else {\n // If the user didn't explicity indicate replace behavior, replace if\n // we redirected to the exact same location we're currently at to avoid\n // double back-buttons\n let location = normalizeRedirectLocation(\n result.response.headers.get(\"Location\")!,\n new URL(request.url),\n basename,\n init.history,\n );\n replace = location === state.location.pathname + state.location.search;\n }\n await startRedirectNavigation(request, result, true, {\n submission,\n replace,\n });\n return { shortCircuited: true };\n }\n\n if (isDeferredResult(result)) {\n throw getInternalRouterError(400, { type: \"defer-action\" });\n }\n\n if (isErrorResult(result)) {\n // Store off the pending error - we use it to determine which loaders\n // to call and will commit it when we complete the navigation\n let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);\n\n // By default, all submissions to the current location are REPLACE\n // navigations, but if the action threw an error that'll be rendered in\n // an errorElement, we fall back to PUSH so that the user can use the\n // back button to get back to the pre-submission form location to try\n // again\n if ((opts && opts.replace) !== true) {\n pendingAction = HistoryAction.Push;\n }\n\n return {\n matches,\n pendingActionResult: [boundaryMatch.route.id, result],\n };\n }\n\n return {\n matches,\n pendingActionResult: [actionMatch.route.id, result],\n };\n }\n\n // Call all applicable loaders for the given matches, handling redirects,\n // errors, etc.\n async function handleLoaders(\n request: Request,\n location: Location,\n matches: AgnosticDataRouteMatch[],\n isFogOfWar: boolean,\n overrideNavigation?: Navigation,\n submission?: Submission,\n fetcherSubmission?: Submission,\n replace?: boolean,\n initialHydration?: boolean,\n flushSync?: boolean,\n pendingActionResult?: PendingActionResult\n ): Promise {\n // Figure out the right navigation we want to use for data loading\n let loadingNavigation =\n overrideNavigation || getLoadingNavigation(location, submission);\n\n // If this was a redirect from an action we don't have a \"submission\" but\n // we have it on the loading navigation so use that if available\n let activeSubmission =\n submission ||\n fetcherSubmission ||\n getSubmissionFromNavigation(loadingNavigation);\n\n // If this is an uninterrupted revalidation, we remain in our current idle\n // state. If not, we need to switch to our loading state and load data,\n // preserving any new action data or existing action data (in the case of\n // a revalidation interrupting an actionReload)\n // If we have partialHydration enabled, then don't update the state for the\n // initial data load since it's not a \"navigation\"\n let shouldUpdateNavigationState =\n !isUninterruptedRevalidation &&\n (!future.v7_partialHydration || !initialHydration);\n\n // When fog of war is enabled, we enter our `loading` state earlier so we\n // can discover new routes during the `loading` state. We skip this if\n // we've already run actions since we would have done our matching already.\n // If the children() function threw then, we want to proceed with the\n // partial matches it discovered.\n if (isFogOfWar) {\n if (shouldUpdateNavigationState) {\n let actionData = getUpdatedActionData(pendingActionResult);\n updateState(\n {\n navigation: loadingNavigation,\n ...(actionData !== undefined ? { actionData } : {}),\n },\n {\n flushSync,\n }\n );\n }\n\n let discoverResult = await discoverRoutes(\n matches,\n location.pathname,\n request.signal\n );\n\n if (discoverResult.type === \"aborted\") {\n return { shortCircuited: true };\n } else if (discoverResult.type === \"error\") {\n let boundaryId = findNearestBoundary(discoverResult.partialMatches)\n .route.id;\n return {\n matches: discoverResult.partialMatches,\n loaderData: {},\n errors: {\n [boundaryId]: discoverResult.error,\n },\n };\n } else if (!discoverResult.matches) {\n let { error, notFoundMatches, route } = handleNavigational404(\n location.pathname\n );\n return {\n matches: notFoundMatches,\n loaderData: {},\n errors: {\n [route.id]: error,\n },\n };\n } else {\n matches = discoverResult.matches;\n }\n }\n\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n init.history,\n state,\n matches,\n activeSubmission,\n location,\n future.v7_partialHydration && initialHydration === true,\n future.v7_skipActionErrorRevalidation,\n isRevalidationRequired,\n cancelledDeferredRoutes,\n cancelledFetcherLoads,\n deletedFetchers,\n fetchLoadMatches,\n fetchRedirectIds,\n routesToUse,\n basename,\n pendingActionResult\n );\n\n // Cancel pending deferreds for no-longer-matched routes or routes we're\n // about to reload. Note that if this is an action reload we would have\n // already cancelled all pending deferreds so this would be a no-op\n cancelActiveDeferreds(\n (routeId) =>\n !(matches && matches.some((m) => m.route.id === routeId)) ||\n (matchesToLoad && matchesToLoad.some((m) => m.route.id === routeId))\n );\n\n pendingNavigationLoadId = ++incrementingLoadId;\n\n // Short circuit if we have no loaders to run\n if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) {\n let updatedFetchers = markFetchRedirectsDone();\n completeNavigation(\n location,\n {\n matches,\n loaderData: {},\n // Commit pending error if we're short circuiting\n errors:\n pendingActionResult && isErrorResult(pendingActionResult[1])\n ? { [pendingActionResult[0]]: pendingActionResult[1].error }\n : null,\n ...getActionDataForCommit(pendingActionResult),\n ...(updatedFetchers ? { fetchers: new Map(state.fetchers) } : {}),\n },\n { flushSync }\n );\n return { shortCircuited: true };\n }\n\n if (shouldUpdateNavigationState) {\n let updates: Partial = {};\n if (!isFogOfWar) {\n // Only update navigation/actionNData if we didn't already do it above\n updates.navigation = loadingNavigation;\n let actionData = getUpdatedActionData(pendingActionResult);\n if (actionData !== undefined) {\n updates.actionData = actionData;\n }\n }\n if (revalidatingFetchers.length > 0) {\n updates.fetchers = getUpdatedRevalidatingFetchers(revalidatingFetchers);\n }\n updateState(updates, { flushSync });\n }\n\n revalidatingFetchers.forEach((rf) => {\n abortFetcher(rf.key);\n if (rf.controller) {\n // Fetchers use an independent AbortController so that aborting a fetcher\n // (via deleteFetcher) does not abort the triggering navigation that\n // triggered the revalidation\n fetchControllers.set(rf.key, rf.controller);\n }\n });\n\n // Proxy navigation abort through to revalidation fetchers\n let abortPendingFetchRevalidations = () =>\n revalidatingFetchers.forEach((f) => abortFetcher(f.key));\n if (pendingNavigationController) {\n pendingNavigationController.signal.addEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n }\n\n let { loaderResults, fetcherResults } =\n await callLoadersAndMaybeResolveData(\n state,\n matches,\n matchesToLoad,\n revalidatingFetchers,\n request\n );\n\n if (request.signal.aborted) {\n return { shortCircuited: true };\n }\n\n // Clean up _after_ loaders have completed. Don't clean up if we short\n // circuited because fetchControllers would have been aborted and\n // reassigned to new controllers for the next navigation\n if (pendingNavigationController) {\n pendingNavigationController.signal.removeEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n }\n\n revalidatingFetchers.forEach((rf) => fetchControllers.delete(rf.key));\n\n // If any loaders returned a redirect Response, start a new REPLACE navigation\n let redirect = findRedirect(loaderResults);\n if (redirect) {\n await startRedirectNavigation(request, redirect.result, true, {\n replace,\n });\n return { shortCircuited: true };\n }\n\n redirect = findRedirect(fetcherResults);\n if (redirect) {\n // If this redirect came from a fetcher make sure we mark it in\n // fetchRedirectIds so it doesn't get revalidated on the next set of\n // loader executions\n fetchRedirectIds.add(redirect.key);\n await startRedirectNavigation(request, redirect.result, true, {\n replace,\n });\n return { shortCircuited: true };\n }\n\n // Process and commit output from loaders\n let { loaderData, errors } = processLoaderData(\n state,\n matches,\n loaderResults,\n pendingActionResult,\n revalidatingFetchers,\n fetcherResults,\n activeDeferreds\n );\n\n // Wire up subscribers to update loaderData as promises settle\n activeDeferreds.forEach((deferredData, routeId) => {\n deferredData.subscribe((aborted) => {\n // Note: No need to updateState here since the TrackedPromise on\n // loaderData is stable across resolve/reject\n // Remove this instance if we were aborted or if promises have settled\n if (aborted || deferredData.done) {\n activeDeferreds.delete(routeId);\n }\n });\n });\n\n // Preserve SSR errors during partial hydration\n if (future.v7_partialHydration && initialHydration && state.errors) {\n errors = { ...state.errors, ...errors };\n }\n\n let updatedFetchers = markFetchRedirectsDone();\n let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId);\n let shouldUpdateFetchers =\n updatedFetchers || didAbortFetchLoads || revalidatingFetchers.length > 0;\n\n return {\n matches,\n loaderData,\n errors,\n ...(shouldUpdateFetchers ? { fetchers: new Map(state.fetchers) } : {}),\n };\n }\n\n function getUpdatedActionData(\n pendingActionResult: PendingActionResult | undefined\n ): Record | null | undefined {\n if (pendingActionResult && !isErrorResult(pendingActionResult[1])) {\n // This is cast to `any` currently because `RouteData`uses any and it\n // would be a breaking change to use any.\n // TODO: v7 - change `RouteData` to use `unknown` instead of `any`\n return {\n [pendingActionResult[0]]: pendingActionResult[1].data as any,\n };\n } else if (state.actionData) {\n if (Object.keys(state.actionData).length === 0) {\n return null;\n } else {\n return state.actionData;\n }\n }\n }\n\n function getUpdatedRevalidatingFetchers(\n revalidatingFetchers: RevalidatingFetcher[]\n ) {\n revalidatingFetchers.forEach((rf) => {\n let fetcher = state.fetchers.get(rf.key);\n let revalidatingFetcher = getLoadingFetcher(\n undefined,\n fetcher ? fetcher.data : undefined\n );\n state.fetchers.set(rf.key, revalidatingFetcher);\n });\n return new Map(state.fetchers);\n }\n\n // Trigger a fetcher load/submit for the given fetcher key\n function fetch(\n key: string,\n routeId: string,\n href: string | null,\n opts?: RouterFetchOptions\n ) {\n if (isServer) {\n throw new Error(\n \"router.fetch() was called during the server render, but it shouldn't be. \" +\n \"You are likely calling a useFetcher() method in the body of your component. \" +\n \"Try moving it to a useEffect or a callback.\"\n );\n }\n\n abortFetcher(key);\n\n let flushSync = (opts && opts.flushSync) === true;\n\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let normalizedPath = normalizeTo(\n state.location,\n state.matches,\n basename,\n future.v7_prependBasename,\n href,\n future.v7_relativeSplatPath,\n routeId,\n opts?.relative\n );\n let matches = matchRoutes(routesToUse, normalizedPath, basename);\n\n let fogOfWar = checkFogOfWar(matches, routesToUse, normalizedPath);\n if (fogOfWar.active && fogOfWar.matches) {\n matches = fogOfWar.matches;\n }\n\n if (!matches) {\n setFetcherError(\n key,\n routeId,\n getInternalRouterError(404, { pathname: normalizedPath }),\n { flushSync }\n );\n return;\n }\n\n let { path, submission, error } = normalizeNavigateOptions(\n future.v7_normalizeFormMethod,\n true,\n normalizedPath,\n opts\n );\n\n if (error) {\n setFetcherError(key, routeId, error, { flushSync });\n return;\n }\n\n let match = getTargetMatch(matches, path);\n\n let preventScrollReset = (opts && opts.preventScrollReset) === true;\n\n if (submission && isMutationMethod(submission.formMethod)) {\n handleFetcherAction(\n key,\n routeId,\n path,\n match,\n matches,\n fogOfWar.active,\n flushSync,\n preventScrollReset,\n submission\n );\n return;\n }\n\n // Store off the match so we can call it's shouldRevalidate on subsequent\n // revalidations\n fetchLoadMatches.set(key, { routeId, path });\n handleFetcherLoader(\n key,\n routeId,\n path,\n match,\n matches,\n fogOfWar.active,\n flushSync,\n preventScrollReset,\n submission\n );\n }\n\n // Call the action for the matched fetcher.submit(), and then handle redirects,\n // errors, and revalidation\n async function handleFetcherAction(\n key: string,\n routeId: string,\n path: string,\n match: AgnosticDataRouteMatch,\n requestMatches: AgnosticDataRouteMatch[],\n isFogOfWar: boolean,\n flushSync: boolean,\n preventScrollReset: boolean,\n submission: Submission\n ) {\n interruptActiveLoads();\n fetchLoadMatches.delete(key);\n\n function detectAndHandle405Error(m: AgnosticDataRouteMatch) {\n if (!m.route.action && !m.route.lazy) {\n let error = getInternalRouterError(405, {\n method: submission.formMethod,\n pathname: path,\n routeId: routeId,\n });\n setFetcherError(key, routeId, error, { flushSync });\n return true;\n }\n return false;\n }\n\n if (!isFogOfWar && detectAndHandle405Error(match)) {\n return;\n }\n\n // Put this fetcher into it's submitting state\n let existingFetcher = state.fetchers.get(key);\n updateFetcherState(key, getSubmittingFetcher(submission, existingFetcher), {\n flushSync,\n });\n\n let abortController = new AbortController();\n let fetchRequest = createClientSideRequest(\n init.history,\n path,\n abortController.signal,\n submission\n );\n\n if (isFogOfWar) {\n let discoverResult = await discoverRoutes(\n requestMatches,\n new URL(fetchRequest.url).pathname,\n fetchRequest.signal,\n key\n );\n\n if (discoverResult.type === \"aborted\") {\n return;\n } else if (discoverResult.type === \"error\") {\n setFetcherError(key, routeId, discoverResult.error, { flushSync });\n return;\n } else if (!discoverResult.matches) {\n setFetcherError(\n key,\n routeId,\n getInternalRouterError(404, { pathname: path }),\n { flushSync }\n );\n return;\n } else {\n requestMatches = discoverResult.matches;\n match = getTargetMatch(requestMatches, path);\n\n if (detectAndHandle405Error(match)) {\n return;\n }\n }\n }\n\n // Call the action for the fetcher\n fetchControllers.set(key, abortController);\n\n let originatingLoadId = incrementingLoadId;\n let actionResults = await callDataStrategy(\n \"action\",\n state,\n fetchRequest,\n [match],\n requestMatches,\n key\n );\n let actionResult = actionResults[match.route.id];\n\n if (fetchRequest.signal.aborted) {\n // We can delete this so long as we weren't aborted by our own fetcher\n // re-submit which would have put _new_ controller is in fetchControllers\n if (fetchControllers.get(key) === abortController) {\n fetchControllers.delete(key);\n }\n return;\n }\n\n // When using v7_fetcherPersist, we don't want errors bubbling up to the UI\n // or redirects processed for unmounted fetchers so we just revert them to\n // idle\n if (future.v7_fetcherPersist && deletedFetchers.has(key)) {\n if (isRedirectResult(actionResult) || isErrorResult(actionResult)) {\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n }\n // Let SuccessResult's fall through for revalidation\n } else {\n if (isRedirectResult(actionResult)) {\n fetchControllers.delete(key);\n if (pendingNavigationLoadId > originatingLoadId) {\n // A new navigation was kicked off after our action started, so that\n // should take precedence over this redirect navigation. We already\n // set isRevalidationRequired so all loaders for the new route should\n // fire unless opted out via shouldRevalidate\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n } else {\n fetchRedirectIds.add(key);\n updateFetcherState(key, getLoadingFetcher(submission));\n return startRedirectNavigation(fetchRequest, actionResult, false, {\n fetcherSubmission: submission,\n preventScrollReset,\n });\n }\n }\n\n // Process any non-redirect errors thrown\n if (isErrorResult(actionResult)) {\n setFetcherError(key, routeId, actionResult.error);\n return;\n }\n }\n\n if (isDeferredResult(actionResult)) {\n throw getInternalRouterError(400, { type: \"defer-action\" });\n }\n\n // Start the data load for current matches, or the next location if we're\n // in the middle of a navigation\n let nextLocation = state.navigation.location || state.location;\n let revalidationRequest = createClientSideRequest(\n init.history,\n nextLocation,\n abortController.signal\n );\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let matches =\n state.navigation.state !== \"idle\"\n ? matchRoutes(routesToUse, state.navigation.location, basename)\n : state.matches;\n\n invariant(matches, \"Didn't find any matches after fetcher action\");\n\n let loadId = ++incrementingLoadId;\n fetchReloadIds.set(key, loadId);\n\n let loadFetcher = getLoadingFetcher(submission, actionResult.data);\n state.fetchers.set(key, loadFetcher);\n\n let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n init.history,\n state,\n matches,\n submission,\n nextLocation,\n false,\n future.v7_skipActionErrorRevalidation,\n isRevalidationRequired,\n cancelledDeferredRoutes,\n cancelledFetcherLoads,\n deletedFetchers,\n fetchLoadMatches,\n fetchRedirectIds,\n routesToUse,\n basename,\n [match.route.id, actionResult]\n );\n\n // Put all revalidating fetchers into the loading state, except for the\n // current fetcher which we want to keep in it's current loading state which\n // contains it's action submission info + action data\n revalidatingFetchers\n .filter((rf) => rf.key !== key)\n .forEach((rf) => {\n let staleKey = rf.key;\n let existingFetcher = state.fetchers.get(staleKey);\n let revalidatingFetcher = getLoadingFetcher(\n undefined,\n existingFetcher ? existingFetcher.data : undefined\n );\n state.fetchers.set(staleKey, revalidatingFetcher);\n abortFetcher(staleKey);\n if (rf.controller) {\n fetchControllers.set(staleKey, rf.controller);\n }\n });\n\n updateState({ fetchers: new Map(state.fetchers) });\n\n let abortPendingFetchRevalidations = () =>\n revalidatingFetchers.forEach((rf) => abortFetcher(rf.key));\n\n abortController.signal.addEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n\n let { loaderResults, fetcherResults } =\n await callLoadersAndMaybeResolveData(\n state,\n matches,\n matchesToLoad,\n revalidatingFetchers,\n revalidationRequest\n );\n\n if (abortController.signal.aborted) {\n return;\n }\n\n abortController.signal.removeEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n\n fetchReloadIds.delete(key);\n fetchControllers.delete(key);\n revalidatingFetchers.forEach((r) => fetchControllers.delete(r.key));\n\n let redirect = findRedirect(loaderResults);\n if (redirect) {\n return startRedirectNavigation(\n revalidationRequest,\n redirect.result,\n false,\n { preventScrollReset }\n );\n }\n\n redirect = findRedirect(fetcherResults);\n if (redirect) {\n // If this redirect came from a fetcher make sure we mark it in\n // fetchRedirectIds so it doesn't get revalidated on the next set of\n // loader executions\n fetchRedirectIds.add(redirect.key);\n return startRedirectNavigation(\n revalidationRequest,\n redirect.result,\n false,\n { preventScrollReset }\n );\n }\n\n // Process and commit output from loaders\n let { loaderData, errors } = processLoaderData(\n state,\n matches,\n loaderResults,\n undefined,\n revalidatingFetchers,\n fetcherResults,\n activeDeferreds\n );\n\n // Since we let revalidations complete even if the submitting fetcher was\n // deleted, only put it back to idle if it hasn't been deleted\n if (state.fetchers.has(key)) {\n let doneFetcher = getDoneFetcher(actionResult.data);\n state.fetchers.set(key, doneFetcher);\n }\n\n abortStaleFetchLoads(loadId);\n\n // If we are currently in a navigation loading state and this fetcher is\n // more recent than the navigation, we want the newer data so abort the\n // navigation and complete it with the fetcher data\n if (\n state.navigation.state === \"loading\" &&\n loadId > pendingNavigationLoadId\n ) {\n invariant(pendingAction, \"Expected pending action\");\n pendingNavigationController && pendingNavigationController.abort();\n\n completeNavigation(state.navigation.location, {\n matches,\n loaderData,\n errors,\n fetchers: new Map(state.fetchers),\n });\n } else {\n // otherwise just update with the fetcher data, preserving any existing\n // loaderData for loaders that did not need to reload. We have to\n // manually merge here since we aren't going through completeNavigation\n updateState({\n errors,\n loaderData: mergeLoaderData(\n state.loaderData,\n loaderData,\n matches,\n errors\n ),\n fetchers: new Map(state.fetchers),\n });\n isRevalidationRequired = false;\n }\n }\n\n // Call the matched loader for fetcher.load(), handling redirects, errors, etc.\n async function handleFetcherLoader(\n key: string,\n routeId: string,\n path: string,\n match: AgnosticDataRouteMatch,\n matches: AgnosticDataRouteMatch[],\n isFogOfWar: boolean,\n flushSync: boolean,\n preventScrollReset: boolean,\n submission?: Submission\n ) {\n let existingFetcher = state.fetchers.get(key);\n updateFetcherState(\n key,\n getLoadingFetcher(\n submission,\n existingFetcher ? existingFetcher.data : undefined\n ),\n { flushSync }\n );\n\n let abortController = new AbortController();\n let fetchRequest = createClientSideRequest(\n init.history,\n path,\n abortController.signal\n );\n\n if (isFogOfWar) {\n let discoverResult = await discoverRoutes(\n matches,\n new URL(fetchRequest.url).pathname,\n fetchRequest.signal,\n key\n );\n\n if (discoverResult.type === \"aborted\") {\n return;\n } else if (discoverResult.type === \"error\") {\n setFetcherError(key, routeId, discoverResult.error, { flushSync });\n return;\n } else if (!discoverResult.matches) {\n setFetcherError(\n key,\n routeId,\n getInternalRouterError(404, { pathname: path }),\n { flushSync }\n );\n return;\n } else {\n matches = discoverResult.matches;\n match = getTargetMatch(matches, path);\n }\n }\n\n // Call the loader for this fetcher route match\n fetchControllers.set(key, abortController);\n\n let originatingLoadId = incrementingLoadId;\n let results = await callDataStrategy(\n \"loader\",\n state,\n fetchRequest,\n [match],\n matches,\n key\n );\n let result = results[match.route.id];\n\n // Deferred isn't supported for fetcher loads, await everything and treat it\n // as a normal load. resolveDeferredData will return undefined if this\n // fetcher gets aborted, so we just leave result untouched and short circuit\n // below if that happens\n if (isDeferredResult(result)) {\n result =\n (await resolveDeferredData(result, fetchRequest.signal, true)) ||\n result;\n }\n\n // We can delete this so long as we weren't aborted by our our own fetcher\n // re-load which would have put _new_ controller is in fetchControllers\n if (fetchControllers.get(key) === abortController) {\n fetchControllers.delete(key);\n }\n\n if (fetchRequest.signal.aborted) {\n return;\n }\n\n // We don't want errors bubbling up or redirects followed for unmounted\n // fetchers, so short circuit here if it was removed from the UI\n if (deletedFetchers.has(key)) {\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n }\n\n // If the loader threw a redirect Response, start a new REPLACE navigation\n if (isRedirectResult(result)) {\n if (pendingNavigationLoadId > originatingLoadId) {\n // A new navigation was kicked off after our loader started, so that\n // should take precedence over this redirect navigation\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n } else {\n fetchRedirectIds.add(key);\n await startRedirectNavigation(fetchRequest, result, false, {\n preventScrollReset,\n });\n return;\n }\n }\n\n // Process any non-redirect errors thrown\n if (isErrorResult(result)) {\n setFetcherError(key, routeId, result.error);\n return;\n }\n\n invariant(!isDeferredResult(result), \"Unhandled fetcher deferred data\");\n\n // Put the fetcher back into an idle state\n updateFetcherState(key, getDoneFetcher(result.data));\n }\n\n /**\n * Utility function to handle redirects returned from an action or loader.\n * Normally, a redirect \"replaces\" the navigation that triggered it. So, for\n * example:\n *\n * - user is on /a\n * - user clicks a link to /b\n * - loader for /b redirects to /c\n *\n * In a non-JS app the browser would track the in-flight navigation to /b and\n * then replace it with /c when it encountered the redirect response. In\n * the end it would only ever update the URL bar with /c.\n *\n * In client-side routing using pushState/replaceState, we aim to emulate\n * this behavior and we also do not update history until the end of the\n * navigation (including processed redirects). This means that we never\n * actually touch history until we've processed redirects, so we just use\n * the history action from the original navigation (PUSH or REPLACE).\n */\n async function startRedirectNavigation(\n request: Request,\n redirect: RedirectResult,\n isNavigation: boolean,\n {\n submission,\n fetcherSubmission,\n preventScrollReset,\n replace,\n }: {\n submission?: Submission;\n fetcherSubmission?: Submission;\n preventScrollReset?: boolean;\n replace?: boolean;\n } = {}\n ) {\n if (redirect.response.headers.has(\"X-Remix-Revalidate\")) {\n isRevalidationRequired = true;\n }\n\n let location = redirect.response.headers.get(\"Location\");\n invariant(location, \"Expected a Location header on the redirect Response\");\n location = normalizeRedirectLocation(\n location,\n new URL(request.url),\n basename,\n init.history,\n );\n let redirectLocation = createLocation(state.location, location, {\n _isRedirect: true,\n });\n\n if (isBrowser) {\n let isDocumentReload = false;\n\n if (redirect.response.headers.has(\"X-Remix-Reload-Document\")) {\n // Hard reload if the response contained X-Remix-Reload-Document\n isDocumentReload = true;\n } else if (ABSOLUTE_URL_REGEX.test(location)) {\n const url = init.history.createURL(location);\n isDocumentReload =\n // Hard reload if it's an absolute URL to a new origin\n url.origin !== routerWindow.location.origin ||\n // Hard reload if it's an absolute URL that does not match our basename\n stripBasename(url.pathname, basename) == null;\n }\n\n if (isDocumentReload) {\n if (replace) {\n routerWindow.location.replace(location);\n } else {\n routerWindow.location.assign(location);\n }\n return;\n }\n }\n\n // There's no need to abort on redirects, since we don't detect the\n // redirect until the action/loaders have settled\n pendingNavigationController = null;\n\n let redirectHistoryAction =\n replace === true || redirect.response.headers.has(\"X-Remix-Replace\")\n ? HistoryAction.Replace\n : HistoryAction.Push;\n\n // Use the incoming submission if provided, fallback on the active one in\n // state.navigation\n let { formMethod, formAction, formEncType } = state.navigation;\n if (\n !submission &&\n !fetcherSubmission &&\n formMethod &&\n formAction &&\n formEncType\n ) {\n submission = getSubmissionFromNavigation(state.navigation);\n }\n\n // If this was a 307/308 submission we want to preserve the HTTP method and\n // re-submit the GET/POST/PUT/PATCH/DELETE as a submission navigation to the\n // redirected location\n let activeSubmission = submission || fetcherSubmission;\n if (\n redirectPreserveMethodStatusCodes.has(redirect.response.status) &&\n activeSubmission &&\n isMutationMethod(activeSubmission.formMethod)\n ) {\n await startNavigation(redirectHistoryAction, redirectLocation, {\n submission: {\n ...activeSubmission,\n formAction: location,\n },\n // Preserve these flags across redirects\n preventScrollReset: preventScrollReset || pendingPreventScrollReset,\n enableViewTransition: isNavigation\n ? pendingViewTransitionEnabled\n : undefined,\n });\n } else {\n // If we have a navigation submission, we will preserve it through the\n // redirect navigation\n let overrideNavigation = getLoadingNavigation(\n redirectLocation,\n submission\n );\n await startNavigation(redirectHistoryAction, redirectLocation, {\n overrideNavigation,\n // Send fetcher submissions through for shouldRevalidate\n fetcherSubmission,\n // Preserve these flags across redirects\n preventScrollReset: preventScrollReset || pendingPreventScrollReset,\n enableViewTransition: isNavigation\n ? pendingViewTransitionEnabled\n : undefined,\n });\n }\n }\n\n // Utility wrapper for calling dataStrategy client-side without having to\n // pass around the manifest, mapRouteProperties, etc.\n async function callDataStrategy(\n type: \"loader\" | \"action\",\n state: RouterState,\n request: Request,\n matchesToLoad: AgnosticDataRouteMatch[],\n matches: AgnosticDataRouteMatch[],\n fetcherKey: string | null\n ): Promise> {\n let results: Record;\n let dataResults: Record = {};\n try {\n results = await callDataStrategyImpl(\n dataStrategyImpl,\n type,\n state,\n request,\n matchesToLoad,\n matches,\n fetcherKey,\n manifest,\n mapRouteProperties\n );\n } catch (e) {\n // If the outer dataStrategy method throws, just return the error for all\n // matches - and it'll naturally bubble to the root\n matchesToLoad.forEach((m) => {\n dataResults[m.route.id] = {\n type: ResultType.error,\n error: e,\n };\n });\n return dataResults;\n }\n\n for (let [routeId, result] of Object.entries(results)) {\n if (isRedirectDataStrategyResultResult(result)) {\n let response = result.result as Response;\n dataResults[routeId] = {\n type: ResultType.redirect,\n response: normalizeRelativeRoutingRedirectResponse(\n response,\n request,\n routeId,\n matches,\n basename,\n future.v7_relativeSplatPath\n ),\n };\n } else {\n dataResults[routeId] = await convertDataStrategyResultToDataResult(\n result\n );\n }\n }\n\n return dataResults;\n }\n\n async function callLoadersAndMaybeResolveData(\n state: RouterState,\n matches: AgnosticDataRouteMatch[],\n matchesToLoad: AgnosticDataRouteMatch[],\n fetchersToLoad: RevalidatingFetcher[],\n request: Request\n ) {\n let currentMatches = state.matches;\n\n // Kick off loaders and fetchers in parallel\n let loaderResultsPromise = callDataStrategy(\n \"loader\",\n state,\n request,\n matchesToLoad,\n matches,\n null\n );\n\n let fetcherResultsPromise = Promise.all(\n fetchersToLoad.map(async (f) => {\n if (f.matches && f.match && f.controller) {\n let results = await callDataStrategy(\n \"loader\",\n state,\n createClientSideRequest(init.history, f.path, f.controller.signal),\n [f.match],\n f.matches,\n f.key\n );\n let result = results[f.match.route.id];\n // Fetcher results are keyed by fetcher key from here on out, not routeId\n return { [f.key]: result };\n } else {\n return Promise.resolve({\n [f.key]: {\n type: ResultType.error,\n error: getInternalRouterError(404, {\n pathname: f.path,\n }),\n } as ErrorResult,\n });\n }\n })\n );\n\n let loaderResults = await loaderResultsPromise;\n let fetcherResults = (await fetcherResultsPromise).reduce(\n (acc, r) => Object.assign(acc, r),\n {}\n );\n\n await Promise.all([\n resolveNavigationDeferredResults(\n matches,\n loaderResults,\n request.signal,\n currentMatches,\n state.loaderData\n ),\n resolveFetcherDeferredResults(matches, fetcherResults, fetchersToLoad),\n ]);\n\n return {\n loaderResults,\n fetcherResults,\n };\n }\n\n function interruptActiveLoads() {\n // Every interruption triggers a revalidation\n isRevalidationRequired = true;\n\n // Cancel pending route-level deferreds and mark cancelled routes for\n // revalidation\n cancelledDeferredRoutes.push(...cancelActiveDeferreds());\n\n // Abort in-flight fetcher loads\n fetchLoadMatches.forEach((_, key) => {\n if (fetchControllers.has(key)) {\n cancelledFetcherLoads.add(key);\n }\n abortFetcher(key);\n });\n }\n\n function updateFetcherState(\n key: string,\n fetcher: Fetcher,\n opts: { flushSync?: boolean } = {}\n ) {\n state.fetchers.set(key, fetcher);\n updateState(\n { fetchers: new Map(state.fetchers) },\n { flushSync: (opts && opts.flushSync) === true }\n );\n }\n\n function setFetcherError(\n key: string,\n routeId: string,\n error: any,\n opts: { flushSync?: boolean } = {}\n ) {\n let boundaryMatch = findNearestBoundary(state.matches, routeId);\n deleteFetcher(key);\n updateState(\n {\n errors: {\n [boundaryMatch.route.id]: error,\n },\n fetchers: new Map(state.fetchers),\n },\n { flushSync: (opts && opts.flushSync) === true }\n );\n }\n\n function getFetcher(key: string): Fetcher {\n activeFetchers.set(key, (activeFetchers.get(key) || 0) + 1);\n // If this fetcher was previously marked for deletion, unmark it since we\n // have a new instance\n if (deletedFetchers.has(key)) {\n deletedFetchers.delete(key);\n }\n return state.fetchers.get(key) || IDLE_FETCHER;\n }\n\n function deleteFetcher(key: string): void {\n let fetcher = state.fetchers.get(key);\n // Don't abort the controller if this is a deletion of a fetcher.submit()\n // in it's loading phase since - we don't want to abort the corresponding\n // revalidation and want them to complete and land\n if (\n fetchControllers.has(key) &&\n !(fetcher && fetcher.state === \"loading\" && fetchReloadIds.has(key))\n ) {\n abortFetcher(key);\n }\n fetchLoadMatches.delete(key);\n fetchReloadIds.delete(key);\n fetchRedirectIds.delete(key);\n\n // If we opted into the flag we can clear this now since we're calling\n // deleteFetcher() at the end of updateState() and we've already handed the\n // deleted fetcher keys off to the data layer.\n // If not, we're eagerly calling deleteFetcher() and we need to keep this\n // Set populated until the next updateState call, and we'll clear\n // `deletedFetchers` then\n if (future.v7_fetcherPersist) {\n deletedFetchers.delete(key);\n }\n\n cancelledFetcherLoads.delete(key);\n state.fetchers.delete(key);\n }\n\n function deleteFetcherAndUpdateState(key: string): void {\n let count = (activeFetchers.get(key) || 0) - 1;\n if (count <= 0) {\n activeFetchers.delete(key);\n deletedFetchers.add(key);\n if (!future.v7_fetcherPersist) {\n deleteFetcher(key);\n }\n } else {\n activeFetchers.set(key, count);\n }\n\n updateState({ fetchers: new Map(state.fetchers) });\n }\n\n function abortFetcher(key: string) {\n let controller = fetchControllers.get(key);\n if (controller) {\n controller.abort();\n fetchControllers.delete(key);\n }\n }\n\n function markFetchersDone(keys: string[]) {\n for (let key of keys) {\n let fetcher = getFetcher(key);\n let doneFetcher = getDoneFetcher(fetcher.data);\n state.fetchers.set(key, doneFetcher);\n }\n }\n\n function markFetchRedirectsDone(): boolean {\n let doneKeys = [];\n let updatedFetchers = false;\n for (let key of fetchRedirectIds) {\n let fetcher = state.fetchers.get(key);\n invariant(fetcher, `Expected fetcher: ${key}`);\n if (fetcher.state === \"loading\") {\n fetchRedirectIds.delete(key);\n doneKeys.push(key);\n updatedFetchers = true;\n }\n }\n markFetchersDone(doneKeys);\n return updatedFetchers;\n }\n\n function abortStaleFetchLoads(landedId: number): boolean {\n let yeetedKeys = [];\n for (let [key, id] of fetchReloadIds) {\n if (id < landedId) {\n let fetcher = state.fetchers.get(key);\n invariant(fetcher, `Expected fetcher: ${key}`);\n if (fetcher.state === \"loading\") {\n abortFetcher(key);\n fetchReloadIds.delete(key);\n yeetedKeys.push(key);\n }\n }\n }\n markFetchersDone(yeetedKeys);\n return yeetedKeys.length > 0;\n }\n\n function getBlocker(key: string, fn: BlockerFunction) {\n let blocker: Blocker = state.blockers.get(key) || IDLE_BLOCKER;\n\n if (blockerFunctions.get(key) !== fn) {\n blockerFunctions.set(key, fn);\n }\n\n return blocker;\n }\n\n function deleteBlocker(key: string) {\n state.blockers.delete(key);\n blockerFunctions.delete(key);\n }\n\n // Utility function to update blockers, ensuring valid state transitions\n function updateBlocker(key: string, newBlocker: Blocker) {\n let blocker = state.blockers.get(key) || IDLE_BLOCKER;\n\n // Poor mans state machine :)\n // https://mermaid.live/edit#pako:eNqVkc9OwzAMxl8l8nnjAYrEtDIOHEBIgwvKJTReGy3_lDpIqO27k6awMG0XcrLlnz87nwdonESogKXXBuE79rq75XZO3-yHds0RJVuv70YrPlUrCEe2HfrORS3rubqZfuhtpg5C9wk5tZ4VKcRUq88q9Z8RS0-48cE1iHJkL0ugbHuFLus9L6spZy8nX9MP2CNdomVaposqu3fGayT8T8-jJQwhepo_UtpgBQaDEUom04dZhAN1aJBDlUKJBxE1ceB2Smj0Mln-IBW5AFU2dwUiktt_2Qaq2dBfaKdEup85UV7Yd-dKjlnkabl2Pvr0DTkTreM\n invariant(\n (blocker.state === \"unblocked\" && newBlocker.state === \"blocked\") ||\n (blocker.state === \"blocked\" && newBlocker.state === \"blocked\") ||\n (blocker.state === \"blocked\" && newBlocker.state === \"proceeding\") ||\n (blocker.state === \"blocked\" && newBlocker.state === \"unblocked\") ||\n (blocker.state === \"proceeding\" && newBlocker.state === \"unblocked\"),\n `Invalid blocker state transition: ${blocker.state} -> ${newBlocker.state}`\n );\n\n let blockers = new Map(state.blockers);\n blockers.set(key, newBlocker);\n updateState({ blockers });\n }\n\n function shouldBlockNavigation({\n currentLocation,\n nextLocation,\n historyAction,\n }: {\n currentLocation: Location;\n nextLocation: Location;\n historyAction: HistoryAction;\n }): string | undefined {\n if (blockerFunctions.size === 0) {\n return;\n }\n\n // We ony support a single active blocker at the moment since we don't have\n // any compelling use cases for multi-blocker yet\n if (blockerFunctions.size > 1) {\n warning(false, \"A router only supports one blocker at a time\");\n }\n\n let entries = Array.from(blockerFunctions.entries());\n let [blockerKey, blockerFunction] = entries[entries.length - 1];\n let blocker = state.blockers.get(blockerKey);\n\n if (blocker && blocker.state === \"proceeding\") {\n // If the blocker is currently proceeding, we don't need to re-check\n // it and can let this navigation continue\n return;\n }\n\n // At this point, we know we're unblocked/blocked so we need to check the\n // user-provided blocker function\n if (blockerFunction({ currentLocation, nextLocation, historyAction })) {\n return blockerKey;\n }\n }\n\n function handleNavigational404(pathname: string) {\n let error = getInternalRouterError(404, { pathname });\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let { matches, route } = getShortCircuitMatches(routesToUse);\n\n // Cancel all pending deferred on 404s since we don't keep any routes\n cancelActiveDeferreds();\n\n return { notFoundMatches: matches, route, error };\n }\n\n function cancelActiveDeferreds(\n predicate?: (routeId: string) => boolean\n ): string[] {\n let cancelledRouteIds: string[] = [];\n activeDeferreds.forEach((dfd, routeId) => {\n if (!predicate || predicate(routeId)) {\n // Cancel the deferred - but do not remove from activeDeferreds here -\n // we rely on the subscribers to do that so our tests can assert proper\n // cleanup via _internalActiveDeferreds\n dfd.cancel();\n cancelledRouteIds.push(routeId);\n activeDeferreds.delete(routeId);\n }\n });\n return cancelledRouteIds;\n }\n\n // Opt in to capturing and reporting scroll positions during navigations,\n // used by the component\n function enableScrollRestoration(\n positions: Record,\n getPosition: GetScrollPositionFunction,\n getKey?: GetScrollRestorationKeyFunction\n ) {\n savedScrollPositions = positions;\n getScrollPosition = getPosition;\n getScrollRestorationKey = getKey || null;\n\n // Perform initial hydration scroll restoration, since we miss the boat on\n // the initial updateState() because we've not yet rendered \n // and therefore have no savedScrollPositions available\n if (!initialScrollRestored && state.navigation === IDLE_NAVIGATION) {\n initialScrollRestored = true;\n let y = getSavedScrollPosition(state.location, state.matches);\n if (y != null) {\n updateState({ restoreScrollPosition: y });\n }\n }\n\n return () => {\n savedScrollPositions = null;\n getScrollPosition = null;\n getScrollRestorationKey = null;\n };\n }\n\n function getScrollKey(location: Location, matches: AgnosticDataRouteMatch[]) {\n if (getScrollRestorationKey) {\n let key = getScrollRestorationKey(\n location,\n matches.map((m) => convertRouteMatchToUiMatch(m, state.loaderData))\n );\n return key || location.key;\n }\n return location.key;\n }\n\n function saveScrollPosition(\n location: Location,\n matches: AgnosticDataRouteMatch[]\n ): void {\n if (savedScrollPositions && getScrollPosition) {\n let key = getScrollKey(location, matches);\n savedScrollPositions[key] = getScrollPosition();\n }\n }\n\n function getSavedScrollPosition(\n location: Location,\n matches: AgnosticDataRouteMatch[]\n ): number | null {\n if (savedScrollPositions) {\n let key = getScrollKey(location, matches);\n let y = savedScrollPositions[key];\n if (typeof y === \"number\") {\n return y;\n }\n }\n return null;\n }\n\n function checkFogOfWar(\n matches: AgnosticDataRouteMatch[] | null,\n routesToUse: AgnosticDataRouteObject[],\n pathname: string\n ): { active: boolean; matches: AgnosticDataRouteMatch[] | null } {\n if (patchRoutesOnNavigationImpl) {\n if (!matches) {\n let fogMatches = matchRoutesImpl(\n routesToUse,\n pathname,\n basename,\n true\n );\n\n return { active: true, matches: fogMatches || [] };\n } else {\n if (Object.keys(matches[0].params).length > 0) {\n // If we matched a dynamic param or a splat, it might only be because\n // we haven't yet discovered other routes that would match with a\n // higher score. Call patchRoutesOnNavigation just to be sure\n let partialMatches = matchRoutesImpl(\n routesToUse,\n pathname,\n basename,\n true\n );\n return { active: true, matches: partialMatches };\n }\n }\n }\n\n return { active: false, matches: null };\n }\n\n type DiscoverRoutesSuccessResult = {\n type: \"success\";\n matches: AgnosticDataRouteMatch[] | null;\n };\n type DiscoverRoutesErrorResult = {\n type: \"error\";\n error: any;\n partialMatches: AgnosticDataRouteMatch[];\n };\n type DiscoverRoutesAbortedResult = { type: \"aborted\" };\n type DiscoverRoutesResult =\n | DiscoverRoutesSuccessResult\n | DiscoverRoutesErrorResult\n | DiscoverRoutesAbortedResult;\n\n async function discoverRoutes(\n matches: AgnosticDataRouteMatch[],\n pathname: string,\n signal: AbortSignal,\n fetcherKey?: string\n ): Promise {\n if (!patchRoutesOnNavigationImpl) {\n return { type: \"success\", matches };\n }\n\n let partialMatches: AgnosticDataRouteMatch[] | null = matches;\n while (true) {\n let isNonHMR = inFlightDataRoutes == null;\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let localManifest = manifest;\n try {\n await patchRoutesOnNavigationImpl({\n signal,\n path: pathname,\n matches: partialMatches,\n fetcherKey,\n patch: (routeId, children) => {\n if (signal.aborted) return;\n patchRoutesImpl(\n routeId,\n children,\n routesToUse,\n localManifest,\n mapRouteProperties\n );\n },\n });\n } catch (e) {\n return { type: \"error\", error: e, partialMatches };\n } finally {\n // If we are not in the middle of an HMR revalidation and we changed the\n // routes, provide a new identity so when we `updateState` at the end of\n // this navigation/fetch `router.routes` will be a new identity and\n // trigger a re-run of memoized `router.routes` dependencies.\n // HMR will already update the identity and reflow when it lands\n // `inFlightDataRoutes` in `completeNavigation`\n if (isNonHMR && !signal.aborted) {\n dataRoutes = [...dataRoutes];\n }\n }\n\n if (signal.aborted) {\n return { type: \"aborted\" };\n }\n\n let newMatches = matchRoutes(routesToUse, pathname, basename);\n if (newMatches) {\n return { type: \"success\", matches: newMatches };\n }\n\n let newPartialMatches = matchRoutesImpl(\n routesToUse,\n pathname,\n basename,\n true\n );\n\n // Avoid loops if the second pass results in the same partial matches\n if (\n !newPartialMatches ||\n (partialMatches.length === newPartialMatches.length &&\n partialMatches.every(\n (m, i) => m.route.id === newPartialMatches![i].route.id\n ))\n ) {\n return { type: \"success\", matches: null };\n }\n\n partialMatches = newPartialMatches;\n }\n }\n\n function _internalSetRoutes(newRoutes: AgnosticDataRouteObject[]) {\n manifest = {};\n inFlightDataRoutes = convertRoutesToDataRoutes(\n newRoutes,\n mapRouteProperties,\n undefined,\n manifest\n );\n }\n\n function patchRoutes(\n routeId: string | null,\n children: AgnosticRouteObject[]\n ): void {\n let isNonHMR = inFlightDataRoutes == null;\n let routesToUse = inFlightDataRoutes || dataRoutes;\n patchRoutesImpl(\n routeId,\n children,\n routesToUse,\n manifest,\n mapRouteProperties\n );\n\n // If we are not in the middle of an HMR revalidation and we changed the\n // routes, provide a new identity and trigger a reflow via `updateState`\n // to re-run memoized `router.routes` dependencies.\n // HMR will already update the identity and reflow when it lands\n // `inFlightDataRoutes` in `completeNavigation`\n if (isNonHMR) {\n dataRoutes = [...dataRoutes];\n updateState({});\n }\n }\n\n router = {\n get basename() {\n return basename;\n },\n get future() {\n return future;\n },\n get state() {\n return state;\n },\n get routes() {\n return dataRoutes;\n },\n get window() {\n return routerWindow;\n },\n initialize,\n subscribe,\n enableScrollRestoration,\n navigate,\n fetch,\n revalidate,\n // Passthrough to history-aware createHref used by useHref so we get proper\n // hash-aware URLs in DOM paths\n createHref: (to: To) => init.history.createHref(to),\n encodeLocation: (to: To) => init.history.encodeLocation(to),\n getFetcher,\n deleteFetcher: deleteFetcherAndUpdateState,\n dispose,\n getBlocker,\n deleteBlocker,\n patchRoutes,\n _internalFetchControllers: fetchControllers,\n _internalActiveDeferreds: activeDeferreds,\n // TODO: Remove setRoutes, it's temporary to avoid dealing with\n // updating the tree while validating the update algorithm.\n _internalSetRoutes,\n };\n\n return router;\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region createStaticHandler\n////////////////////////////////////////////////////////////////////////////////\n\nexport const UNSAFE_DEFERRED_SYMBOL = Symbol(\"deferred\");\n\n/**\n * Future flags to toggle new feature behavior\n */\nexport interface StaticHandlerFutureConfig {\n v7_relativeSplatPath: boolean;\n v7_throwAbortReason: boolean;\n}\n\nexport interface CreateStaticHandlerOptions {\n basename?: string;\n /**\n * @deprecated Use `mapRouteProperties` instead\n */\n detectErrorBoundary?: DetectErrorBoundaryFunction;\n mapRouteProperties?: MapRoutePropertiesFunction;\n future?: Partial;\n}\n\nexport function createStaticHandler(\n routes: AgnosticRouteObject[],\n opts?: CreateStaticHandlerOptions\n): StaticHandler {\n invariant(\n routes.length > 0,\n \"You must provide a non-empty routes array to createStaticHandler\"\n );\n\n let manifest: RouteManifest = {};\n let basename = (opts ? opts.basename : null) || \"/\";\n let mapRouteProperties: MapRoutePropertiesFunction;\n if (opts?.mapRouteProperties) {\n mapRouteProperties = opts.mapRouteProperties;\n } else if (opts?.detectErrorBoundary) {\n // If they are still using the deprecated version, wrap it with the new API\n let detectErrorBoundary = opts.detectErrorBoundary;\n mapRouteProperties = (route) => ({\n hasErrorBoundary: detectErrorBoundary(route),\n });\n } else {\n mapRouteProperties = defaultMapRouteProperties;\n }\n // Config driven behavior flags\n let future: StaticHandlerFutureConfig = {\n v7_relativeSplatPath: false,\n v7_throwAbortReason: false,\n ...(opts ? opts.future : null),\n };\n\n let dataRoutes = convertRoutesToDataRoutes(\n routes,\n mapRouteProperties,\n undefined,\n manifest\n );\n\n /**\n * The query() method is intended for document requests, in which we want to\n * call an optional action and potentially multiple loaders for all nested\n * routes. It returns a StaticHandlerContext object, which is very similar\n * to the router state (location, loaderData, actionData, errors, etc.) and\n * also adds SSR-specific information such as the statusCode and headers\n * from action/loaders Responses.\n *\n * It _should_ never throw and should report all errors through the\n * returned context.errors object, properly associating errors to their error\n * boundary. Additionally, it tracks _deepestRenderedBoundaryId which can be\n * used to emulate React error boundaries during SSr by performing a second\n * pass only down to the boundaryId.\n *\n * The one exception where we do not return a StaticHandlerContext is when a\n * redirect response is returned or thrown from any action/loader. We\n * propagate that out and return the raw Response so the HTTP server can\n * return it directly.\n *\n * - `opts.requestContext` is an optional server context that will be passed\n * to actions/loaders in the `context` parameter\n * - `opts.skipLoaderErrorBubbling` is an optional parameter that will prevent\n * the bubbling of errors which allows single-fetch-type implementations\n * where the client will handle the bubbling and we may need to return data\n * for the handling route\n */\n async function query(\n request: Request,\n {\n requestContext,\n skipLoaderErrorBubbling,\n dataStrategy,\n }: {\n requestContext?: unknown;\n skipLoaderErrorBubbling?: boolean;\n dataStrategy?: DataStrategyFunction;\n } = {}\n ): Promise {\n let url = new URL(request.url);\n let method = request.method;\n let location = createLocation(\"\", createPath(url), null, \"default\");\n let matches = matchRoutes(dataRoutes, location, basename);\n\n // SSR supports HEAD requests while SPA doesn't\n if (!isValidMethod(method) && method !== \"HEAD\") {\n let error = getInternalRouterError(405, { method });\n let { matches: methodNotAllowedMatches, route } =\n getShortCircuitMatches(dataRoutes);\n return {\n basename,\n location,\n matches: methodNotAllowedMatches,\n loaderData: {},\n actionData: null,\n errors: {\n [route.id]: error,\n },\n statusCode: error.status,\n loaderHeaders: {},\n actionHeaders: {},\n activeDeferreds: null,\n };\n } else if (!matches) {\n let error = getInternalRouterError(404, { pathname: location.pathname });\n let { matches: notFoundMatches, route } =\n getShortCircuitMatches(dataRoutes);\n return {\n basename,\n location,\n matches: notFoundMatches,\n loaderData: {},\n actionData: null,\n errors: {\n [route.id]: error,\n },\n statusCode: error.status,\n loaderHeaders: {},\n actionHeaders: {},\n activeDeferreds: null,\n };\n }\n\n let result = await queryImpl(\n request,\n location,\n matches,\n requestContext,\n dataStrategy || null,\n skipLoaderErrorBubbling === true,\n null\n );\n if (isResponse(result)) {\n return result;\n }\n\n // When returning StaticHandlerContext, we patch back in the location here\n // since we need it for React Context. But this helps keep our submit and\n // loadRouteData operating on a Request instead of a Location\n return { location, basename, ...result };\n }\n\n /**\n * The queryRoute() method is intended for targeted route requests, either\n * for fetch ?_data requests or resource route requests. In this case, we\n * are only ever calling a single action or loader, and we are returning the\n * returned value directly. In most cases, this will be a Response returned\n * from the action/loader, but it may be a primitive or other value as well -\n * and in such cases the calling context should handle that accordingly.\n *\n * We do respect the throw/return differentiation, so if an action/loader\n * throws, then this method will throw the value. This is important so we\n * can do proper boundary identification in Remix where a thrown Response\n * must go to the Catch Boundary but a returned Response is happy-path.\n *\n * One thing to note is that any Router-initiated Errors that make sense\n * to associate with a status code will be thrown as an ErrorResponse\n * instance which include the raw Error, such that the calling context can\n * serialize the error as they see fit while including the proper response\n * code. Examples here are 404 and 405 errors that occur prior to reaching\n * any user-defined loaders.\n *\n * - `opts.routeId` allows you to specify the specific route handler to call.\n * If not provided the handler will determine the proper route by matching\n * against `request.url`\n * - `opts.requestContext` is an optional server context that will be passed\n * to actions/loaders in the `context` parameter\n */\n async function queryRoute(\n request: Request,\n {\n routeId,\n requestContext,\n dataStrategy,\n }: {\n requestContext?: unknown;\n routeId?: string;\n dataStrategy?: DataStrategyFunction;\n } = {}\n ): Promise {\n let url = new URL(request.url);\n let method = request.method;\n let location = createLocation(\"\", createPath(url), null, \"default\");\n let matches = matchRoutes(dataRoutes, location, basename);\n\n // SSR supports HEAD requests while SPA doesn't\n if (!isValidMethod(method) && method !== \"HEAD\" && method !== \"OPTIONS\") {\n throw getInternalRouterError(405, { method });\n } else if (!matches) {\n throw getInternalRouterError(404, { pathname: location.pathname });\n }\n\n let match = routeId\n ? matches.find((m) => m.route.id === routeId)\n : getTargetMatch(matches, location);\n\n if (routeId && !match) {\n throw getInternalRouterError(403, {\n pathname: location.pathname,\n routeId,\n });\n } else if (!match) {\n // This should never hit I don't think?\n throw getInternalRouterError(404, { pathname: location.pathname });\n }\n\n let result = await queryImpl(\n request,\n location,\n matches,\n requestContext,\n dataStrategy || null,\n false,\n match\n );\n\n if (isResponse(result)) {\n return result;\n }\n\n let error = result.errors ? Object.values(result.errors)[0] : undefined;\n if (error !== undefined) {\n // If we got back result.errors, that means the loader/action threw\n // _something_ that wasn't a Response, but it's not guaranteed/required\n // to be an `instanceof Error` either, so we have to use throw here to\n // preserve the \"error\" state outside of queryImpl.\n throw error;\n }\n\n // Pick off the right state value to return\n if (result.actionData) {\n return Object.values(result.actionData)[0];\n }\n\n if (result.loaderData) {\n let data = Object.values(result.loaderData)[0];\n if (result.activeDeferreds?.[match.route.id]) {\n data[UNSAFE_DEFERRED_SYMBOL] = result.activeDeferreds[match.route.id];\n }\n return data;\n }\n\n return undefined;\n }\n\n async function queryImpl(\n request: Request,\n location: Location,\n matches: AgnosticDataRouteMatch[],\n requestContext: unknown,\n dataStrategy: DataStrategyFunction | null,\n skipLoaderErrorBubbling: boolean,\n routeMatch: AgnosticDataRouteMatch | null\n ): Promise | Response> {\n invariant(\n request.signal,\n \"query()/queryRoute() requests must contain an AbortController signal\"\n );\n\n try {\n if (isMutationMethod(request.method.toLowerCase())) {\n let result = await submit(\n request,\n matches,\n routeMatch || getTargetMatch(matches, location),\n requestContext,\n dataStrategy,\n skipLoaderErrorBubbling,\n routeMatch != null\n );\n return result;\n }\n\n let result = await loadRouteData(\n request,\n matches,\n requestContext,\n dataStrategy,\n skipLoaderErrorBubbling,\n routeMatch\n );\n return isResponse(result)\n ? result\n : {\n ...result,\n actionData: null,\n actionHeaders: {},\n };\n } catch (e) {\n // If the user threw/returned a Response in callLoaderOrAction for a\n // `queryRoute` call, we throw the `DataStrategyResult` to bail out early\n // and then return or throw the raw Response here accordingly\n if (isDataStrategyResult(e) && isResponse(e.result)) {\n if (e.type === ResultType.error) {\n throw e.result;\n }\n return e.result;\n }\n // Redirects are always returned since they don't propagate to catch\n // boundaries\n if (isRedirectResponse(e)) {\n return e;\n }\n throw e;\n }\n }\n\n async function submit(\n request: Request,\n matches: AgnosticDataRouteMatch[],\n actionMatch: AgnosticDataRouteMatch,\n requestContext: unknown,\n dataStrategy: DataStrategyFunction | null,\n skipLoaderErrorBubbling: boolean,\n isRouteRequest: boolean\n ): Promise | Response> {\n let result: DataResult;\n\n if (!actionMatch.route.action && !actionMatch.route.lazy) {\n let error = getInternalRouterError(405, {\n method: request.method,\n pathname: new URL(request.url).pathname,\n routeId: actionMatch.route.id,\n });\n if (isRouteRequest) {\n throw error;\n }\n result = {\n type: ResultType.error,\n error,\n };\n } else {\n let results = await callDataStrategy(\n \"action\",\n request,\n [actionMatch],\n matches,\n isRouteRequest,\n requestContext,\n dataStrategy\n );\n result = results[actionMatch.route.id];\n\n if (request.signal.aborted) {\n throwStaticHandlerAbortedError(request, isRouteRequest, future);\n }\n }\n\n if (isRedirectResult(result)) {\n // Uhhhh - this should never happen, we should always throw these from\n // callLoaderOrAction, but the type narrowing here keeps TS happy and we\n // can get back on the \"throw all redirect responses\" train here should\n // this ever happen :/\n throw new Response(null, {\n status: result.response.status,\n headers: {\n Location: result.response.headers.get(\"Location\")!,\n },\n });\n }\n\n if (isDeferredResult(result)) {\n let error = getInternalRouterError(400, { type: \"defer-action\" });\n if (isRouteRequest) {\n throw error;\n }\n result = {\n type: ResultType.error,\n error,\n };\n }\n\n if (isRouteRequest) {\n // Note: This should only be non-Response values if we get here, since\n // isRouteRequest should throw any Response received in callLoaderOrAction\n if (isErrorResult(result)) {\n throw result.error;\n }\n\n return {\n matches: [actionMatch],\n loaderData: {},\n actionData: { [actionMatch.route.id]: result.data },\n errors: null,\n // Note: statusCode + headers are unused here since queryRoute will\n // return the raw Response or value\n statusCode: 200,\n loaderHeaders: {},\n actionHeaders: {},\n activeDeferreds: null,\n };\n }\n\n // Create a GET request for the loaders\n let loaderRequest = new Request(request.url, {\n headers: request.headers,\n redirect: request.redirect,\n signal: request.signal,\n });\n\n if (isErrorResult(result)) {\n // Store off the pending error - we use it to determine which loaders\n // to call and will commit it when we complete the navigation\n let boundaryMatch = skipLoaderErrorBubbling\n ? actionMatch\n : findNearestBoundary(matches, actionMatch.route.id);\n\n let context = await loadRouteData(\n loaderRequest,\n matches,\n requestContext,\n dataStrategy,\n skipLoaderErrorBubbling,\n null,\n [boundaryMatch.route.id, result]\n );\n\n // action status codes take precedence over loader status codes\n return {\n ...context,\n statusCode: isRouteErrorResponse(result.error)\n ? result.error.status\n : result.statusCode != null\n ? result.statusCode\n : 500,\n actionData: null,\n actionHeaders: {\n ...(result.headers ? { [actionMatch.route.id]: result.headers } : {}),\n },\n };\n }\n\n let context = await loadRouteData(\n loaderRequest,\n matches,\n requestContext,\n dataStrategy,\n skipLoaderErrorBubbling,\n null\n );\n\n return {\n ...context,\n actionData: {\n [actionMatch.route.id]: result.data,\n },\n // action status codes take precedence over loader status codes\n ...(result.statusCode ? { statusCode: result.statusCode } : {}),\n actionHeaders: result.headers\n ? { [actionMatch.route.id]: result.headers }\n : {},\n };\n }\n\n async function loadRouteData(\n request: Request,\n matches: AgnosticDataRouteMatch[],\n requestContext: unknown,\n dataStrategy: DataStrategyFunction | null,\n skipLoaderErrorBubbling: boolean,\n routeMatch: AgnosticDataRouteMatch | null,\n pendingActionResult?: PendingActionResult\n ): Promise<\n | Omit<\n StaticHandlerContext,\n \"location\" | \"basename\" | \"actionData\" | \"actionHeaders\"\n >\n | Response\n > {\n let isRouteRequest = routeMatch != null;\n\n // Short circuit if we have no loaders to run (queryRoute())\n if (\n isRouteRequest &&\n !routeMatch?.route.loader &&\n !routeMatch?.route.lazy\n ) {\n throw getInternalRouterError(400, {\n method: request.method,\n pathname: new URL(request.url).pathname,\n routeId: routeMatch?.route.id,\n });\n }\n\n let requestMatches = routeMatch\n ? [routeMatch]\n : pendingActionResult && isErrorResult(pendingActionResult[1])\n ? getLoaderMatchesUntilBoundary(matches, pendingActionResult[0])\n : matches;\n let matchesToLoad = requestMatches.filter(\n (m) => m.route.loader || m.route.lazy\n );\n\n // Short circuit if we have no loaders to run (query())\n if (matchesToLoad.length === 0) {\n return {\n matches,\n // Add a null for all matched routes for proper revalidation on the client\n loaderData: matches.reduce(\n (acc, m) => Object.assign(acc, { [m.route.id]: null }),\n {}\n ),\n errors:\n pendingActionResult && isErrorResult(pendingActionResult[1])\n ? {\n [pendingActionResult[0]]: pendingActionResult[1].error,\n }\n : null,\n statusCode: 200,\n loaderHeaders: {},\n activeDeferreds: null,\n };\n }\n\n let results = await callDataStrategy(\n \"loader\",\n request,\n matchesToLoad,\n matches,\n isRouteRequest,\n requestContext,\n dataStrategy\n );\n\n if (request.signal.aborted) {\n throwStaticHandlerAbortedError(request, isRouteRequest, future);\n }\n\n // Process and commit output from loaders\n let activeDeferreds = new Map();\n let context = processRouteLoaderData(\n matches,\n results,\n pendingActionResult,\n activeDeferreds,\n skipLoaderErrorBubbling\n );\n\n // Add a null for any non-loader matches for proper revalidation on the client\n let executedLoaders = new Set(\n matchesToLoad.map((match) => match.route.id)\n );\n matches.forEach((match) => {\n if (!executedLoaders.has(match.route.id)) {\n context.loaderData[match.route.id] = null;\n }\n });\n\n return {\n ...context,\n matches,\n activeDeferreds:\n activeDeferreds.size > 0\n ? Object.fromEntries(activeDeferreds.entries())\n : null,\n };\n }\n\n // Utility wrapper for calling dataStrategy server-side without having to\n // pass around the manifest, mapRouteProperties, etc.\n async function callDataStrategy(\n type: \"loader\" | \"action\",\n request: Request,\n matchesToLoad: AgnosticDataRouteMatch[],\n matches: AgnosticDataRouteMatch[],\n isRouteRequest: boolean,\n requestContext: unknown,\n dataStrategy: DataStrategyFunction | null\n ): Promise> {\n let results = await callDataStrategyImpl(\n dataStrategy || defaultDataStrategy,\n type,\n null,\n request,\n matchesToLoad,\n matches,\n null,\n manifest,\n mapRouteProperties,\n requestContext\n );\n\n let dataResults: Record = {};\n await Promise.all(\n matches.map(async (match) => {\n if (!(match.route.id in results)) {\n return;\n }\n let result = results[match.route.id];\n if (isRedirectDataStrategyResultResult(result)) {\n let response = result.result as Response;\n // Throw redirects and let the server handle them with an HTTP redirect\n throw normalizeRelativeRoutingRedirectResponse(\n response,\n request,\n match.route.id,\n matches,\n basename,\n future.v7_relativeSplatPath\n );\n }\n if (isResponse(result.result) && isRouteRequest) {\n // For SSR single-route requests, we want to hand Responses back\n // directly without unwrapping\n throw result;\n }\n\n dataResults[match.route.id] =\n await convertDataStrategyResultToDataResult(result);\n })\n );\n return dataResults;\n }\n\n return {\n dataRoutes,\n query,\n queryRoute,\n };\n}\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Helpers\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Given an existing StaticHandlerContext and an error thrown at render time,\n * provide an updated StaticHandlerContext suitable for a second SSR render\n */\nexport function getStaticContextFromError(\n routes: AgnosticDataRouteObject[],\n context: StaticHandlerContext,\n error: any\n) {\n let newContext: StaticHandlerContext = {\n ...context,\n statusCode: isRouteErrorResponse(error) ? error.status : 500,\n errors: {\n [context._deepestRenderedBoundaryId || routes[0].id]: error,\n },\n };\n return newContext;\n}\n\nfunction throwStaticHandlerAbortedError(\n request: Request,\n isRouteRequest: boolean,\n future: StaticHandlerFutureConfig\n) {\n if (future.v7_throwAbortReason && request.signal.reason !== undefined) {\n throw request.signal.reason;\n }\n\n let method = isRouteRequest ? \"queryRoute\" : \"query\";\n throw new Error(`${method}() call aborted: ${request.method} ${request.url}`);\n}\n\nfunction isSubmissionNavigation(\n opts: BaseNavigateOrFetchOptions\n): opts is SubmissionNavigateOptions {\n return (\n opts != null &&\n ((\"formData\" in opts && opts.formData != null) ||\n (\"body\" in opts && opts.body !== undefined))\n );\n}\n\nfunction normalizeTo(\n location: Path,\n matches: AgnosticDataRouteMatch[],\n basename: string,\n prependBasename: boolean,\n to: To | null,\n v7_relativeSplatPath: boolean,\n fromRouteId?: string,\n relative?: RelativeRoutingType\n) {\n let contextualMatches: AgnosticDataRouteMatch[];\n let activeRouteMatch: AgnosticDataRouteMatch | undefined;\n if (fromRouteId) {\n // Grab matches up to the calling route so our route-relative logic is\n // relative to the correct source route\n contextualMatches = [];\n for (let match of matches) {\n contextualMatches.push(match);\n if (match.route.id === fromRouteId) {\n activeRouteMatch = match;\n break;\n }\n }\n } else {\n contextualMatches = matches;\n activeRouteMatch = matches[matches.length - 1];\n }\n\n // Resolve the relative path\n let path = resolveTo(\n to ? to : \".\",\n getResolveToMatches(contextualMatches, v7_relativeSplatPath),\n stripBasename(location.pathname, basename) || location.pathname,\n relative === \"path\"\n );\n\n // When `to` is not specified we inherit search/hash from the current\n // location, unlike when to=\".\" and we just inherit the path.\n // See https://github.com/remix-run/remix/issues/927\n if (to == null) {\n path.search = location.search;\n path.hash = location.hash;\n }\n\n // Account for `?index` params when routing to the current location\n if ((to == null || to === \"\" || to === \".\") && activeRouteMatch) {\n let nakedIndex = hasNakedIndexQuery(path.search);\n if (activeRouteMatch.route.index && !nakedIndex) {\n // Add one when we're targeting an index route\n path.search = path.search\n ? path.search.replace(/^\\?/, \"?index&\")\n : \"?index\";\n } else if (!activeRouteMatch.route.index && nakedIndex) {\n // Remove existing ones when we're not\n let params = new URLSearchParams(path.search);\n let indexValues = params.getAll(\"index\");\n params.delete(\"index\");\n indexValues.filter((v) => v).forEach((v) => params.append(\"index\", v));\n let qs = params.toString();\n path.search = qs ? `?${qs}` : \"\";\n }\n }\n\n // If we're operating within a basename, prepend it to the pathname. If\n // this is a root navigation, then just use the raw basename which allows\n // the basename to have full control over the presence of a trailing slash\n // on root actions\n if (prependBasename && basename !== \"/\") {\n path.pathname =\n path.pathname === \"/\" ? basename : joinPaths([basename, path.pathname]);\n }\n\n return createPath(path);\n}\n\n// Normalize navigation options by converting formMethod=GET formData objects to\n// URLSearchParams so they behave identically to links with query params\nfunction normalizeNavigateOptions(\n normalizeFormMethod: boolean,\n isFetcher: boolean,\n path: string,\n opts?: BaseNavigateOrFetchOptions\n): {\n path: string;\n submission?: Submission;\n error?: ErrorResponseImpl;\n} {\n // Return location verbatim on non-submission navigations\n if (!opts || !isSubmissionNavigation(opts)) {\n return { path };\n }\n\n if (opts.formMethod && !isValidMethod(opts.formMethod)) {\n return {\n path,\n error: getInternalRouterError(405, { method: opts.formMethod }),\n };\n }\n\n let getInvalidBodyError = () => ({\n path,\n error: getInternalRouterError(400, { type: \"invalid-body\" }),\n });\n\n // Create a Submission on non-GET navigations\n let rawFormMethod = opts.formMethod || \"get\";\n let formMethod = normalizeFormMethod\n ? (rawFormMethod.toUpperCase() as V7_FormMethod)\n : (rawFormMethod.toLowerCase() as FormMethod);\n let formAction = stripHashFromPath(path);\n\n if (opts.body !== undefined) {\n if (opts.formEncType === \"text/plain\") {\n // text only support POST/PUT/PATCH/DELETE submissions\n if (!isMutationMethod(formMethod)) {\n return getInvalidBodyError();\n }\n\n let text =\n typeof opts.body === \"string\"\n ? opts.body\n : opts.body instanceof FormData ||\n opts.body instanceof URLSearchParams\n ? // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#plain-text-form-data\n Array.from(opts.body.entries()).reduce(\n (acc, [name, value]) => `${acc}${name}=${value}\\n`,\n \"\"\n )\n : String(opts.body);\n\n return {\n path,\n submission: {\n formMethod,\n formAction,\n formEncType: opts.formEncType,\n formData: undefined,\n json: undefined,\n text,\n },\n };\n } else if (opts.formEncType === \"application/json\") {\n // json only supports POST/PUT/PATCH/DELETE submissions\n if (!isMutationMethod(formMethod)) {\n return getInvalidBodyError();\n }\n\n try {\n let json =\n typeof opts.body === \"string\" ? JSON.parse(opts.body) : opts.body;\n\n return {\n path,\n submission: {\n formMethod,\n formAction,\n formEncType: opts.formEncType,\n formData: undefined,\n json,\n text: undefined,\n },\n };\n } catch (e) {\n return getInvalidBodyError();\n }\n }\n }\n\n invariant(\n typeof FormData === \"function\",\n \"FormData is not available in this environment\"\n );\n\n let searchParams: URLSearchParams;\n let formData: FormData;\n\n if (opts.formData) {\n searchParams = convertFormDataToSearchParams(opts.formData);\n formData = opts.formData;\n } else if (opts.body instanceof FormData) {\n searchParams = convertFormDataToSearchParams(opts.body);\n formData = opts.body;\n } else if (opts.body instanceof URLSearchParams) {\n searchParams = opts.body;\n formData = convertSearchParamsToFormData(searchParams);\n } else if (opts.body == null) {\n searchParams = new URLSearchParams();\n formData = new FormData();\n } else {\n try {\n searchParams = new URLSearchParams(opts.body);\n formData = convertSearchParamsToFormData(searchParams);\n } catch (e) {\n return getInvalidBodyError();\n }\n }\n\n let submission: Submission = {\n formMethod,\n formAction,\n formEncType:\n (opts && opts.formEncType) || \"application/x-www-form-urlencoded\",\n formData,\n json: undefined,\n text: undefined,\n };\n\n if (isMutationMethod(submission.formMethod)) {\n return { path, submission };\n }\n\n // Flatten submission onto URLSearchParams for GET submissions\n let parsedPath = parsePath(path);\n // On GET navigation submissions we can drop the ?index param from the\n // resulting location since all loaders will run. But fetcher GET submissions\n // only run a single loader so we need to preserve any incoming ?index params\n if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) {\n searchParams.append(\"index\", \"\");\n }\n parsedPath.search = `?${searchParams}`;\n\n return { path: createPath(parsedPath), submission };\n}\n\n// Filter out all routes at/below any caught error as they aren't going to\n// render so we don't need to load them\nfunction getLoaderMatchesUntilBoundary(\n matches: AgnosticDataRouteMatch[],\n boundaryId: string,\n includeBoundary = false\n) {\n let index = matches.findIndex((m) => m.route.id === boundaryId);\n if (index >= 0) {\n return matches.slice(0, includeBoundary ? index + 1 : index);\n }\n return matches;\n}\n\nfunction getMatchesToLoad(\n history: History,\n state: RouterState,\n matches: AgnosticDataRouteMatch[],\n submission: Submission | undefined,\n location: Location,\n initialHydration: boolean,\n skipActionErrorRevalidation: boolean,\n isRevalidationRequired: boolean,\n cancelledDeferredRoutes: string[],\n cancelledFetcherLoads: Set,\n deletedFetchers: Set,\n fetchLoadMatches: Map,\n fetchRedirectIds: Set,\n routesToUse: AgnosticDataRouteObject[],\n basename: string | undefined,\n pendingActionResult?: PendingActionResult\n): [AgnosticDataRouteMatch[], RevalidatingFetcher[]] {\n let actionResult = pendingActionResult\n ? isErrorResult(pendingActionResult[1])\n ? pendingActionResult[1].error\n : pendingActionResult[1].data\n : undefined;\n let currentUrl = history.createURL(state.location);\n let nextUrl = history.createURL(location);\n\n // Pick navigation matches that are net-new or qualify for revalidation\n let boundaryMatches = matches;\n if (initialHydration && state.errors) {\n // On initial hydration, only consider matches up to _and including_ the boundary.\n // This is inclusive to handle cases where a server loader ran successfully,\n // a child server loader bubbled up to this route, but this route has\n // `clientLoader.hydrate` so we want to still run the `clientLoader` so that\n // we have a complete version of `loaderData`\n boundaryMatches = getLoaderMatchesUntilBoundary(\n matches,\n Object.keys(state.errors)[0],\n true\n );\n } else if (pendingActionResult && isErrorResult(pendingActionResult[1])) {\n // If an action threw an error, we call loaders up to, but not including the\n // boundary\n boundaryMatches = getLoaderMatchesUntilBoundary(\n matches,\n pendingActionResult[0]\n );\n }\n\n // Don't revalidate loaders by default after action 4xx/5xx responses\n // when the flag is enabled. They can still opt-into revalidation via\n // `shouldRevalidate` via `actionResult`\n let actionStatus = pendingActionResult\n ? pendingActionResult[1].statusCode\n : undefined;\n let shouldSkipRevalidation =\n skipActionErrorRevalidation && actionStatus && actionStatus >= 400;\n\n let navigationMatches = boundaryMatches.filter((match, index) => {\n let { route } = match;\n if (route.lazy) {\n // We haven't loaded this route yet so we don't know if it's got a loader!\n return true;\n }\n\n if (route.loader == null) {\n return false;\n }\n\n if (initialHydration) {\n return shouldLoadRouteOnHydration(route, state.loaderData, state.errors);\n }\n\n // Always call the loader on new route instances and pending defer cancellations\n if (\n isNewLoader(state.loaderData, state.matches[index], match) ||\n cancelledDeferredRoutes.some((id) => id === match.route.id)\n ) {\n return true;\n }\n\n // This is the default implementation for when we revalidate. If the route\n // provides it's own implementation, then we give them full control but\n // provide this value so they can leverage it if needed after they check\n // their own specific use cases\n let currentRouteMatch = state.matches[index];\n let nextRouteMatch = match;\n\n return shouldRevalidateLoader(match, {\n currentUrl,\n currentParams: currentRouteMatch.params,\n nextUrl,\n nextParams: nextRouteMatch.params,\n ...submission,\n actionResult,\n actionStatus,\n defaultShouldRevalidate: shouldSkipRevalidation\n ? false\n : // Forced revalidation due to submission, useRevalidator, or X-Remix-Revalidate\n isRevalidationRequired ||\n currentUrl.pathname + currentUrl.search ===\n nextUrl.pathname + nextUrl.search ||\n // Search params affect all loaders\n currentUrl.search !== nextUrl.search ||\n isNewRouteInstance(currentRouteMatch, nextRouteMatch),\n });\n });\n\n // Pick fetcher.loads that need to be revalidated\n let revalidatingFetchers: RevalidatingFetcher[] = [];\n fetchLoadMatches.forEach((f, key) => {\n // Don't revalidate:\n // - on initial hydration (shouldn't be any fetchers then anyway)\n // - if fetcher won't be present in the subsequent render\n // - no longer matches the URL (v7_fetcherPersist=false)\n // - was unmounted but persisted due to v7_fetcherPersist=true\n if (\n initialHydration ||\n !matches.some((m) => m.route.id === f.routeId) ||\n deletedFetchers.has(key)\n ) {\n return;\n }\n\n let fetcherMatches = matchRoutes(routesToUse, f.path, basename);\n\n // If the fetcher path no longer matches, push it in with null matches so\n // we can trigger a 404 in callLoadersAndMaybeResolveData. Note this is\n // currently only a use-case for Remix HMR where the route tree can change\n // at runtime and remove a route previously loaded via a fetcher\n if (!fetcherMatches) {\n revalidatingFetchers.push({\n key,\n routeId: f.routeId,\n path: f.path,\n matches: null,\n match: null,\n controller: null,\n });\n return;\n }\n\n // Revalidating fetchers are decoupled from the route matches since they\n // load from a static href. They revalidate based on explicit revalidation\n // (submission, useRevalidator, or X-Remix-Revalidate)\n let fetcher = state.fetchers.get(key);\n let fetcherMatch = getTargetMatch(fetcherMatches, f.path);\n\n let shouldRevalidate = false;\n if (fetchRedirectIds.has(key)) {\n // Never trigger a revalidation of an actively redirecting fetcher\n shouldRevalidate = false;\n } else if (cancelledFetcherLoads.has(key)) {\n // Always mark for revalidation if the fetcher was cancelled\n cancelledFetcherLoads.delete(key);\n shouldRevalidate = true;\n } else if (\n fetcher &&\n fetcher.state !== \"idle\" &&\n fetcher.data === undefined\n ) {\n // If the fetcher hasn't ever completed loading yet, then this isn't a\n // revalidation, it would just be a brand new load if an explicit\n // revalidation is required\n shouldRevalidate = isRevalidationRequired;\n } else {\n // Otherwise fall back on any user-defined shouldRevalidate, defaulting\n // to explicit revalidations only\n shouldRevalidate = shouldRevalidateLoader(fetcherMatch, {\n currentUrl,\n currentParams: state.matches[state.matches.length - 1].params,\n nextUrl,\n nextParams: matches[matches.length - 1].params,\n ...submission,\n actionResult,\n actionStatus,\n defaultShouldRevalidate: shouldSkipRevalidation\n ? false\n : isRevalidationRequired,\n });\n }\n\n if (shouldRevalidate) {\n revalidatingFetchers.push({\n key,\n routeId: f.routeId,\n path: f.path,\n matches: fetcherMatches,\n match: fetcherMatch,\n controller: new AbortController(),\n });\n }\n });\n\n return [navigationMatches, revalidatingFetchers];\n}\n\nfunction shouldLoadRouteOnHydration(\n route: AgnosticDataRouteObject,\n loaderData: RouteData | null | undefined,\n errors: RouteData | null | undefined\n) {\n // We dunno if we have a loader - gotta find out!\n if (route.lazy) {\n return true;\n }\n\n // No loader, nothing to initialize\n if (!route.loader) {\n return false;\n }\n\n let hasData = loaderData != null && loaderData[route.id] !== undefined;\n let hasError = errors != null && errors[route.id] !== undefined;\n\n // Don't run if we error'd during SSR\n if (!hasData && hasError) {\n return false;\n }\n\n // Explicitly opting-in to running on hydration\n if (typeof route.loader === \"function\" && route.loader.hydrate === true) {\n return true;\n }\n\n // Otherwise, run if we're not yet initialized with anything\n return !hasData && !hasError;\n}\n\nfunction isNewLoader(\n currentLoaderData: RouteData,\n currentMatch: AgnosticDataRouteMatch,\n match: AgnosticDataRouteMatch\n) {\n let isNew =\n // [a] -> [a, b]\n !currentMatch ||\n // [a, b] -> [a, c]\n match.route.id !== currentMatch.route.id;\n\n // Handle the case that we don't have data for a re-used route, potentially\n // from a prior error or from a cancelled pending deferred\n let isMissingData = currentLoaderData[match.route.id] === undefined;\n\n // Always load if this is a net-new route or we don't yet have data\n return isNew || isMissingData;\n}\n\nfunction isNewRouteInstance(\n currentMatch: AgnosticDataRouteMatch,\n match: AgnosticDataRouteMatch\n) {\n let currentPath = currentMatch.route.path;\n return (\n // param change for this match, /users/123 -> /users/456\n currentMatch.pathname !== match.pathname ||\n // splat param changed, which is not present in match.path\n // e.g. /files/images/avatar.jpg -> files/finances.xls\n (currentPath != null &&\n currentPath.endsWith(\"*\") &&\n currentMatch.params[\"*\"] !== match.params[\"*\"])\n );\n}\n\nfunction shouldRevalidateLoader(\n loaderMatch: AgnosticDataRouteMatch,\n arg: ShouldRevalidateFunctionArgs\n) {\n if (loaderMatch.route.shouldRevalidate) {\n let routeChoice = loaderMatch.route.shouldRevalidate(arg);\n if (typeof routeChoice === \"boolean\") {\n return routeChoice;\n }\n }\n\n return arg.defaultShouldRevalidate;\n}\n\nfunction patchRoutesImpl(\n routeId: string | null,\n children: AgnosticRouteObject[],\n routesToUse: AgnosticDataRouteObject[],\n manifest: RouteManifest,\n mapRouteProperties: MapRoutePropertiesFunction\n) {\n let childrenToPatch: AgnosticDataRouteObject[];\n if (routeId) {\n let route = manifest[routeId];\n invariant(\n route,\n `No route found to patch children into: routeId = ${routeId}`\n );\n if (!route.children) {\n route.children = [];\n }\n childrenToPatch = route.children;\n } else {\n childrenToPatch = routesToUse;\n }\n\n // Don't patch in routes we already know about so that `patch` is idempotent\n // to simplify user-land code. This is useful because we re-call the\n // `patchRoutesOnNavigation` function for matched routes with params.\n let uniqueChildren = children.filter(\n (newRoute) =>\n !childrenToPatch.some((existingRoute) =>\n isSameRoute(newRoute, existingRoute)\n )\n );\n\n let newRoutes = convertRoutesToDataRoutes(\n uniqueChildren,\n mapRouteProperties,\n [routeId || \"_\", \"patch\", String(childrenToPatch?.length || \"0\")],\n manifest\n );\n\n childrenToPatch.push(...newRoutes);\n}\n\nfunction isSameRoute(\n newRoute: AgnosticRouteObject,\n existingRoute: AgnosticRouteObject\n): boolean {\n // Most optimal check is by id\n if (\n \"id\" in newRoute &&\n \"id\" in existingRoute &&\n newRoute.id === existingRoute.id\n ) {\n return true;\n }\n\n // Second is by pathing differences\n if (\n !(\n newRoute.index === existingRoute.index &&\n newRoute.path === existingRoute.path &&\n newRoute.caseSensitive === existingRoute.caseSensitive\n )\n ) {\n return false;\n }\n\n // Pathless layout routes are trickier since we need to check children.\n // If they have no children then they're the same as far as we can tell\n if (\n (!newRoute.children || newRoute.children.length === 0) &&\n (!existingRoute.children || existingRoute.children.length === 0)\n ) {\n return true;\n }\n\n // Otherwise, we look to see if every child in the new route is already\n // represented in the existing route's children\n return newRoute.children!.every((aChild, i) =>\n existingRoute.children?.some((bChild) => isSameRoute(aChild, bChild))\n );\n}\n\n/**\n * Execute route.lazy() methods to lazily load route modules (loader, action,\n * shouldRevalidate) and update the routeManifest in place which shares objects\n * with dataRoutes so those get updated as well.\n */\nasync function loadLazyRouteModule(\n route: AgnosticDataRouteObject,\n mapRouteProperties: MapRoutePropertiesFunction,\n manifest: RouteManifest\n) {\n if (!route.lazy) {\n return;\n }\n\n let lazyRoute = await route.lazy();\n\n // If the lazy route function was executed and removed by another parallel\n // call then we can return - first lazy() to finish wins because the return\n // value of lazy is expected to be static\n if (!route.lazy) {\n return;\n }\n\n let routeToUpdate = manifest[route.id];\n invariant(routeToUpdate, \"No route found in manifest\");\n\n // Update the route in place. This should be safe because there's no way\n // we could yet be sitting on this route as we can't get there without\n // resolving lazy() first.\n //\n // This is different than the HMR \"update\" use-case where we may actively be\n // on the route being updated. The main concern boils down to \"does this\n // mutation affect any ongoing navigations or any current state.matches\n // values?\". If not, it should be safe to update in place.\n let routeUpdates: Record = {};\n for (let lazyRouteProperty in lazyRoute) {\n let staticRouteValue =\n routeToUpdate[lazyRouteProperty as keyof typeof routeToUpdate];\n\n let isPropertyStaticallyDefined =\n staticRouteValue !== undefined &&\n // This property isn't static since it should always be updated based\n // on the route updates\n lazyRouteProperty !== \"hasErrorBoundary\";\n\n warning(\n !isPropertyStaticallyDefined,\n `Route \"${routeToUpdate.id}\" has a static property \"${lazyRouteProperty}\" ` +\n `defined but its lazy function is also returning a value for this property. ` +\n `The lazy route property \"${lazyRouteProperty}\" will be ignored.`\n );\n\n if (\n !isPropertyStaticallyDefined &&\n !immutableRouteKeys.has(lazyRouteProperty as ImmutableRouteKey)\n ) {\n routeUpdates[lazyRouteProperty] =\n lazyRoute[lazyRouteProperty as keyof typeof lazyRoute];\n }\n }\n\n // Mutate the route with the provided updates. Do this first so we pass\n // the updated version to mapRouteProperties\n Object.assign(routeToUpdate, routeUpdates);\n\n // Mutate the `hasErrorBoundary` property on the route based on the route\n // updates and remove the `lazy` function so we don't resolve the lazy\n // route again.\n Object.assign(routeToUpdate, {\n // To keep things framework agnostic, we use the provided\n // `mapRouteProperties` (or wrapped `detectErrorBoundary`) function to\n // set the framework-aware properties (`element`/`hasErrorBoundary`) since\n // the logic will differ between frameworks.\n ...mapRouteProperties(routeToUpdate),\n lazy: undefined,\n });\n}\n\n// Default implementation of `dataStrategy` which fetches all loaders in parallel\nasync function defaultDataStrategy({\n matches,\n}: DataStrategyFunctionArgs): ReturnType {\n let matchesToLoad = matches.filter((m) => m.shouldLoad);\n let results = await Promise.all(matchesToLoad.map((m) => m.resolve()));\n return results.reduce(\n (acc, result, i) =>\n Object.assign(acc, { [matchesToLoad[i].route.id]: result }),\n {}\n );\n}\n\nasync function callDataStrategyImpl(\n dataStrategyImpl: DataStrategyFunction,\n type: \"loader\" | \"action\",\n state: RouterState | null,\n request: Request,\n matchesToLoad: AgnosticDataRouteMatch[],\n matches: AgnosticDataRouteMatch[],\n fetcherKey: string | null,\n manifest: RouteManifest,\n mapRouteProperties: MapRoutePropertiesFunction,\n requestContext?: unknown\n): Promise> {\n let loadRouteDefinitionsPromises = matches.map((m) =>\n m.route.lazy\n ? loadLazyRouteModule(m.route, mapRouteProperties, manifest)\n : undefined\n );\n\n let dsMatches = matches.map((match, i) => {\n let loadRoutePromise = loadRouteDefinitionsPromises[i];\n let shouldLoad = matchesToLoad.some((m) => m.route.id === match.route.id);\n // `resolve` encapsulates route.lazy(), executing the loader/action,\n // and mapping return values/thrown errors to a `DataStrategyResult`. Users\n // can pass a callback to take fine-grained control over the execution\n // of the loader/action\n let resolve: DataStrategyMatch[\"resolve\"] = async (handlerOverride) => {\n if (\n handlerOverride &&\n request.method === \"GET\" &&\n (match.route.lazy || match.route.loader)\n ) {\n shouldLoad = true;\n }\n return shouldLoad\n ? callLoaderOrAction(\n type,\n request,\n match,\n loadRoutePromise,\n handlerOverride,\n requestContext\n )\n : Promise.resolve({ type: ResultType.data, result: undefined });\n };\n\n return {\n ...match,\n shouldLoad,\n resolve,\n };\n });\n\n // Send all matches here to allow for a middleware-type implementation.\n // handler will be a no-op for unneeded routes and we filter those results\n // back out below.\n let results = await dataStrategyImpl({\n matches: dsMatches,\n request,\n params: matches[0].params,\n fetcherKey,\n context: requestContext,\n });\n\n // Wait for all routes to load here but 'swallow the error since we want\n // it to bubble up from the `await loadRoutePromise` in `callLoaderOrAction` -\n // called from `match.resolve()`\n try {\n await Promise.all(loadRouteDefinitionsPromises);\n } catch (e) {\n // No-op\n }\n\n return results;\n}\n\n// Default logic for calling a loader/action is the user has no specified a dataStrategy\nasync function callLoaderOrAction(\n type: \"loader\" | \"action\",\n request: Request,\n match: AgnosticDataRouteMatch,\n loadRoutePromise: Promise | undefined,\n handlerOverride: Parameters[0],\n staticContext?: unknown\n): Promise {\n let result: DataStrategyResult;\n let onReject: (() => void) | undefined;\n\n let runHandler = (\n handler: AgnosticRouteObject[\"loader\"] | AgnosticRouteObject[\"action\"]\n ): Promise => {\n // Setup a promise we can race against so that abort signals short circuit\n let reject: () => void;\n // This will never resolve so safe to type it as Promise to\n // satisfy the function return value\n let abortPromise = new Promise((_, r) => (reject = r));\n onReject = () => reject();\n request.signal.addEventListener(\"abort\", onReject);\n\n let actualHandler = (ctx?: unknown) => {\n if (typeof handler !== \"function\") {\n return Promise.reject(\n new Error(\n `You cannot call the handler for a route which defines a boolean ` +\n `\"${type}\" [routeId: ${match.route.id}]`\n )\n );\n }\n return handler(\n {\n request,\n params: match.params,\n context: staticContext,\n },\n ...(ctx !== undefined ? [ctx] : [])\n );\n };\n\n let handlerPromise: Promise = (async () => {\n try {\n let val = await (handlerOverride\n ? handlerOverride((ctx: unknown) => actualHandler(ctx))\n : actualHandler());\n return { type: \"data\", result: val };\n } catch (e) {\n return { type: \"error\", result: e };\n }\n })();\n\n return Promise.race([handlerPromise, abortPromise]);\n };\n\n try {\n let handler = match.route[type];\n\n // If we have a route.lazy promise, await that first\n if (loadRoutePromise) {\n if (handler) {\n // Run statically defined handler in parallel with lazy()\n let handlerError;\n let [value] = await Promise.all([\n // If the handler throws, don't let it immediately bubble out,\n // since we need to let the lazy() execution finish so we know if this\n // route has a boundary that can handle the error\n runHandler(handler).catch((e) => {\n handlerError = e;\n }),\n loadRoutePromise,\n ]);\n if (handlerError !== undefined) {\n throw handlerError;\n }\n result = value!;\n } else {\n // Load lazy route module, then run any returned handler\n await loadRoutePromise;\n\n handler = match.route[type];\n if (handler) {\n // Handler still runs even if we got interrupted to maintain consistency\n // with un-abortable behavior of handler execution on non-lazy or\n // previously-lazy-loaded routes\n result = await runHandler(handler);\n } else if (type === \"action\") {\n let url = new URL(request.url);\n let pathname = url.pathname + url.search;\n throw getInternalRouterError(405, {\n method: request.method,\n pathname,\n routeId: match.route.id,\n });\n } else {\n // lazy() route has no loader to run. Short circuit here so we don't\n // hit the invariant below that errors on returning undefined.\n return { type: ResultType.data, result: undefined };\n }\n }\n } else if (!handler) {\n let url = new URL(request.url);\n let pathname = url.pathname + url.search;\n throw getInternalRouterError(404, {\n pathname,\n });\n } else {\n result = await runHandler(handler);\n }\n\n invariant(\n result.result !== undefined,\n `You defined ${type === \"action\" ? \"an action\" : \"a loader\"} for route ` +\n `\"${match.route.id}\" but didn't return anything from your \\`${type}\\` ` +\n `function. Please return a value or \\`null\\`.`\n );\n } catch (e) {\n // We should already be catching and converting normal handler executions to\n // DataStrategyResults and returning them, so anything that throws here is an\n // unexpected error we still need to wrap\n return { type: ResultType.error, result: e };\n } finally {\n if (onReject) {\n request.signal.removeEventListener(\"abort\", onReject);\n }\n }\n\n return result;\n}\n\nasync function convertDataStrategyResultToDataResult(\n dataStrategyResult: DataStrategyResult\n): Promise {\n let { result, type } = dataStrategyResult;\n\n if (isResponse(result)) {\n let data: any;\n\n try {\n let contentType = result.headers.get(\"Content-Type\");\n // Check between word boundaries instead of startsWith() due to the last\n // paragraph of https://httpwg.org/specs/rfc9110.html#field.content-type\n if (contentType && /\\bapplication\\/json\\b/.test(contentType)) {\n if (result.body == null) {\n data = null;\n } else {\n data = await result.json();\n }\n } else {\n data = await result.text();\n }\n } catch (e) {\n return { type: ResultType.error, error: e };\n }\n\n if (type === ResultType.error) {\n return {\n type: ResultType.error,\n error: new ErrorResponseImpl(result.status, result.statusText, data),\n statusCode: result.status,\n headers: result.headers,\n };\n }\n\n return {\n type: ResultType.data,\n data,\n statusCode: result.status,\n headers: result.headers,\n };\n }\n\n if (type === ResultType.error) {\n if (isDataWithResponseInit(result)) {\n if (result.data instanceof Error) {\n return {\n type: ResultType.error,\n error: result.data,\n statusCode: result.init?.status,\n headers: result.init?.headers\n ? new Headers(result.init.headers)\n : undefined,\n };\n }\n\n // Convert thrown data() to ErrorResponse instances\n return {\n type: ResultType.error,\n error: new ErrorResponseImpl(\n result.init?.status || 500,\n undefined,\n result.data\n ),\n statusCode: isRouteErrorResponse(result) ? result.status : undefined,\n headers: result.init?.headers\n ? new Headers(result.init.headers)\n : undefined,\n };\n }\n return {\n type: ResultType.error,\n error: result,\n statusCode: isRouteErrorResponse(result) ? result.status : undefined,\n };\n }\n\n if (isDeferredData(result)) {\n return {\n type: ResultType.deferred,\n deferredData: result,\n statusCode: result.init?.status,\n headers: result.init?.headers && new Headers(result.init.headers),\n };\n }\n\n if (isDataWithResponseInit(result)) {\n return {\n type: ResultType.data,\n data: result.data,\n statusCode: result.init?.status,\n headers: result.init?.headers\n ? new Headers(result.init.headers)\n : undefined,\n };\n }\n\n return { type: ResultType.data, data: result };\n}\n\n// Support relative routing in internal redirects\nfunction normalizeRelativeRoutingRedirectResponse(\n response: Response,\n request: Request,\n routeId: string,\n matches: AgnosticDataRouteMatch[],\n basename: string,\n v7_relativeSplatPath: boolean\n) {\n let location = response.headers.get(\"Location\");\n invariant(\n location,\n \"Redirects returned/thrown from loaders/actions must have a Location header\"\n );\n\n if (!ABSOLUTE_URL_REGEX.test(location)) {\n let trimmedMatches = matches.slice(\n 0,\n matches.findIndex((m) => m.route.id === routeId) + 1\n );\n location = normalizeTo(\n new URL(request.url),\n trimmedMatches,\n basename,\n true,\n location,\n v7_relativeSplatPath\n );\n response.headers.set(\"Location\", location);\n }\n\n return response;\n}\n\nfunction normalizeRedirectLocation(\n location: string,\n currentUrl: URL,\n basename: string,\n historyInstance: History,\n): string {\n // Match Chrome's behavior:\n // https://github.com/chromium/chromium/blob/216dbeb61db0c667e62082e5f5400a32d6983df3/content/public/common/url_utils.cc#L82\n let invalidProtocols = [\n \"about:\",\n \"blob:\",\n \"chrome:\",\n \"chrome-untrusted:\",\n \"content:\",\n \"data:\",\n \"devtools:\",\n \"file:\",\n \"filesystem:\",\n // eslint-disable-next-line no-script-url\n \"javascript:\",\n ];\n\n if (ABSOLUTE_URL_REGEX.test(location)) {\n // Strip off the protocol+origin for same-origin + same-basename absolute redirects\n let normalizedLocation = location;\n let url = normalizedLocation.startsWith(\"//\")\n ? new URL(currentUrl.protocol + normalizedLocation)\n : new URL(normalizedLocation);\n if (invalidProtocols.includes(url.protocol)) {\n throw new Error(\"Invalid redirect location\");\n }\n let isSameBasename = stripBasename(url.pathname, basename) != null;\n if (url.origin === currentUrl.origin && isSameBasename) {\n return removeDoubleSlashes(url.pathname) + url.search + url.hash;\n }\n }\n\n try {\n let url = historyInstance.createURL(location);\n if (invalidProtocols.includes(url.protocol)) {\n throw new Error(\"Invalid redirect location\");\n }\n } catch (e) {}\n\n return location;\n}\n\n// Utility method for creating the Request instances for loaders/actions during\n// client-side navigations and fetches. During SSR we will always have a\n// Request instance from the static handler (query/queryRoute)\nfunction createClientSideRequest(\n history: History,\n location: string | Location,\n signal: AbortSignal,\n submission?: Submission\n): Request {\n let url = history.createURL(stripHashFromPath(location)).toString();\n let init: RequestInit = { signal };\n\n if (submission && isMutationMethod(submission.formMethod)) {\n let { formMethod, formEncType } = submission;\n // Didn't think we needed this but it turns out unlike other methods, patch\n // won't be properly normalized to uppercase and results in a 405 error.\n // See: https://fetch.spec.whatwg.org/#concept-method\n init.method = formMethod.toUpperCase();\n\n if (formEncType === \"application/json\") {\n init.headers = new Headers({ \"Content-Type\": formEncType });\n init.body = JSON.stringify(submission.json);\n } else if (formEncType === \"text/plain\") {\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n init.body = submission.text;\n } else if (\n formEncType === \"application/x-www-form-urlencoded\" &&\n submission.formData\n ) {\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n init.body = convertFormDataToSearchParams(submission.formData);\n } else {\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n init.body = submission.formData;\n }\n }\n\n return new Request(url, init);\n}\n\nfunction convertFormDataToSearchParams(formData: FormData): URLSearchParams {\n let searchParams = new URLSearchParams();\n\n for (let [key, value] of formData.entries()) {\n // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#converting-an-entry-list-to-a-list-of-name-value-pairs\n searchParams.append(key, typeof value === \"string\" ? value : value.name);\n }\n\n return searchParams;\n}\n\nfunction convertSearchParamsToFormData(\n searchParams: URLSearchParams\n): FormData {\n let formData = new FormData();\n for (let [key, value] of searchParams.entries()) {\n formData.append(key, value);\n }\n return formData;\n}\n\nfunction processRouteLoaderData(\n matches: AgnosticDataRouteMatch[],\n results: Record,\n pendingActionResult: PendingActionResult | undefined,\n activeDeferreds: Map,\n skipLoaderErrorBubbling: boolean\n): {\n loaderData: RouterState[\"loaderData\"];\n errors: RouterState[\"errors\"] | null;\n statusCode: number;\n loaderHeaders: Record;\n} {\n // Fill in loaderData/errors from our loaders\n let loaderData: RouterState[\"loaderData\"] = {};\n let errors: RouterState[\"errors\"] | null = null;\n let statusCode: number | undefined;\n let foundError = false;\n let loaderHeaders: Record = {};\n let pendingError =\n pendingActionResult && isErrorResult(pendingActionResult[1])\n ? pendingActionResult[1].error\n : undefined;\n\n // Process loader results into state.loaderData/state.errors\n matches.forEach((match) => {\n if (!(match.route.id in results)) {\n return;\n }\n let id = match.route.id;\n let result = results[id];\n invariant(\n !isRedirectResult(result),\n \"Cannot handle redirect results in processLoaderData\"\n );\n if (isErrorResult(result)) {\n let error = result.error;\n // If we have a pending action error, we report it at the highest-route\n // that throws a loader error, and then clear it out to indicate that\n // it was consumed\n if (pendingError !== undefined) {\n error = pendingError;\n pendingError = undefined;\n }\n\n errors = errors || {};\n\n if (skipLoaderErrorBubbling) {\n errors[id] = error;\n } else {\n // Look upwards from the matched route for the closest ancestor error\n // boundary, defaulting to the root match. Prefer higher error values\n // if lower errors bubble to the same boundary\n let boundaryMatch = findNearestBoundary(matches, id);\n if (errors[boundaryMatch.route.id] == null) {\n errors[boundaryMatch.route.id] = error;\n }\n }\n\n // Clear our any prior loaderData for the throwing route\n loaderData[id] = undefined;\n\n // Once we find our first (highest) error, we set the status code and\n // prevent deeper status codes from overriding\n if (!foundError) {\n foundError = true;\n statusCode = isRouteErrorResponse(result.error)\n ? result.error.status\n : 500;\n }\n if (result.headers) {\n loaderHeaders[id] = result.headers;\n }\n } else {\n if (isDeferredResult(result)) {\n activeDeferreds.set(id, result.deferredData);\n loaderData[id] = result.deferredData.data;\n // Error status codes always override success status codes, but if all\n // loaders are successful we take the deepest status code.\n if (\n result.statusCode != null &&\n result.statusCode !== 200 &&\n !foundError\n ) {\n statusCode = result.statusCode;\n }\n if (result.headers) {\n loaderHeaders[id] = result.headers;\n }\n } else {\n loaderData[id] = result.data;\n // Error status codes always override success status codes, but if all\n // loaders are successful we take the deepest status code.\n if (result.statusCode && result.statusCode !== 200 && !foundError) {\n statusCode = result.statusCode;\n }\n if (result.headers) {\n loaderHeaders[id] = result.headers;\n }\n }\n }\n });\n\n // If we didn't consume the pending action error (i.e., all loaders\n // resolved), then consume it here. Also clear out any loaderData for the\n // throwing route\n if (pendingError !== undefined && pendingActionResult) {\n errors = { [pendingActionResult[0]]: pendingError };\n loaderData[pendingActionResult[0]] = undefined;\n }\n\n return {\n loaderData,\n errors,\n statusCode: statusCode || 200,\n loaderHeaders,\n };\n}\n\nfunction processLoaderData(\n state: RouterState,\n matches: AgnosticDataRouteMatch[],\n results: Record,\n pendingActionResult: PendingActionResult | undefined,\n revalidatingFetchers: RevalidatingFetcher[],\n fetcherResults: Record,\n activeDeferreds: Map\n): {\n loaderData: RouterState[\"loaderData\"];\n errors?: RouterState[\"errors\"];\n} {\n let { loaderData, errors } = processRouteLoaderData(\n matches,\n results,\n pendingActionResult,\n activeDeferreds,\n false // This method is only called client side so we always want to bubble\n );\n\n // Process results from our revalidating fetchers\n revalidatingFetchers.forEach((rf) => {\n let { key, match, controller } = rf;\n let result = fetcherResults[key];\n invariant(result, \"Did not find corresponding fetcher result\");\n\n // Process fetcher non-redirect errors\n if (controller && controller.signal.aborted) {\n // Nothing to do for aborted fetchers\n return;\n } else if (isErrorResult(result)) {\n let boundaryMatch = findNearestBoundary(state.matches, match?.route.id);\n if (!(errors && errors[boundaryMatch.route.id])) {\n errors = {\n ...errors,\n [boundaryMatch.route.id]: result.error,\n };\n }\n state.fetchers.delete(key);\n } else if (isRedirectResult(result)) {\n // Should never get here, redirects should get processed above, but we\n // keep this to type narrow to a success result in the else\n invariant(false, \"Unhandled fetcher revalidation redirect\");\n } else if (isDeferredResult(result)) {\n // Should never get here, deferred data should be awaited for fetchers\n // in resolveDeferredResults\n invariant(false, \"Unhandled fetcher deferred data\");\n } else {\n let doneFetcher = getDoneFetcher(result.data);\n state.fetchers.set(key, doneFetcher);\n }\n });\n\n return { loaderData, errors };\n}\n\nfunction mergeLoaderData(\n loaderData: RouteData,\n newLoaderData: RouteData,\n matches: AgnosticDataRouteMatch[],\n errors: RouteData | null | undefined\n): RouteData {\n let mergedLoaderData = { ...newLoaderData };\n for (let match of matches) {\n let id = match.route.id;\n if (newLoaderData.hasOwnProperty(id)) {\n if (newLoaderData[id] !== undefined) {\n mergedLoaderData[id] = newLoaderData[id];\n } else {\n // No-op - this is so we ignore existing data if we have a key in the\n // incoming object with an undefined value, which is how we unset a prior\n // loaderData if we encounter a loader error\n }\n } else if (loaderData[id] !== undefined && match.route.loader) {\n // Preserve existing keys not included in newLoaderData and where a loader\n // wasn't removed by HMR\n mergedLoaderData[id] = loaderData[id];\n }\n\n if (errors && errors.hasOwnProperty(id)) {\n // Don't keep any loader data below the boundary\n break;\n }\n }\n return mergedLoaderData;\n}\n\nfunction getActionDataForCommit(\n pendingActionResult: PendingActionResult | undefined\n) {\n if (!pendingActionResult) {\n return {};\n }\n return isErrorResult(pendingActionResult[1])\n ? {\n // Clear out prior actionData on errors\n actionData: {},\n }\n : {\n actionData: {\n [pendingActionResult[0]]: pendingActionResult[1].data,\n },\n };\n}\n\n// Find the nearest error boundary, looking upwards from the leaf route (or the\n// route specified by routeId) for the closest ancestor error boundary,\n// defaulting to the root match\nfunction findNearestBoundary(\n matches: AgnosticDataRouteMatch[],\n routeId?: string\n): AgnosticDataRouteMatch {\n let eligibleMatches = routeId\n ? matches.slice(0, matches.findIndex((m) => m.route.id === routeId) + 1)\n : [...matches];\n return (\n eligibleMatches.reverse().find((m) => m.route.hasErrorBoundary === true) ||\n matches[0]\n );\n}\n\nfunction getShortCircuitMatches(routes: AgnosticDataRouteObject[]): {\n matches: AgnosticDataRouteMatch[];\n route: AgnosticDataRouteObject;\n} {\n // Prefer a root layout route if present, otherwise shim in a route object\n let route =\n routes.length === 1\n ? routes[0]\n : routes.find((r) => r.index || !r.path || r.path === \"/\") || {\n id: `__shim-error-route__`,\n };\n\n return {\n matches: [\n {\n params: {},\n pathname: \"\",\n pathnameBase: \"\",\n route,\n },\n ],\n route,\n };\n}\n\nfunction getInternalRouterError(\n status: number,\n {\n pathname,\n routeId,\n method,\n type,\n message,\n }: {\n pathname?: string;\n routeId?: string;\n method?: string;\n type?: \"defer-action\" | \"invalid-body\";\n message?: string;\n } = {}\n) {\n let statusText = \"Unknown Server Error\";\n let errorMessage = \"Unknown @remix-run/router error\";\n\n if (status === 400) {\n statusText = \"Bad Request\";\n if (method && pathname && routeId) {\n errorMessage =\n `You made a ${method} request to \"${pathname}\" but ` +\n `did not provide a \\`loader\\` for route \"${routeId}\", ` +\n `so there is no way to handle the request.`;\n } else if (type === \"defer-action\") {\n errorMessage = \"defer() is not supported in actions\";\n } else if (type === \"invalid-body\") {\n errorMessage = \"Unable to encode submission body\";\n }\n } else if (status === 403) {\n statusText = \"Forbidden\";\n errorMessage = `Route \"${routeId}\" does not match URL \"${pathname}\"`;\n } else if (status === 404) {\n statusText = \"Not Found\";\n errorMessage = `No route matches URL \"${pathname}\"`;\n } else if (status === 405) {\n statusText = \"Method Not Allowed\";\n if (method && pathname && routeId) {\n errorMessage =\n `You made a ${method.toUpperCase()} request to \"${pathname}\" but ` +\n `did not provide an \\`action\\` for route \"${routeId}\", ` +\n `so there is no way to handle the request.`;\n } else if (method) {\n errorMessage = `Invalid request method \"${method.toUpperCase()}\"`;\n }\n }\n\n return new ErrorResponseImpl(\n status || 500,\n statusText,\n new Error(errorMessage),\n true\n );\n}\n\n// Find any returned redirect errors, starting from the lowest match\nfunction findRedirect(\n results: Record\n): { key: string; result: RedirectResult } | undefined {\n let entries = Object.entries(results);\n for (let i = entries.length - 1; i >= 0; i--) {\n let [key, result] = entries[i];\n if (isRedirectResult(result)) {\n return { key, result };\n }\n }\n}\n\nfunction stripHashFromPath(path: To) {\n let parsedPath = typeof path === \"string\" ? parsePath(path) : path;\n return createPath({ ...parsedPath, hash: \"\" });\n}\n\nfunction isHashChangeOnly(a: Location, b: Location): boolean {\n if (a.pathname !== b.pathname || a.search !== b.search) {\n return false;\n }\n\n if (a.hash === \"\") {\n // /page -> /page#hash\n return b.hash !== \"\";\n } else if (a.hash === b.hash) {\n // /page#hash -> /page#hash\n return true;\n } else if (b.hash !== \"\") {\n // /page#hash -> /page#other\n return true;\n }\n\n // If the hash is removed the browser will re-perform a request to the server\n // /page#hash -> /page\n return false;\n}\n\nfunction isPromise(val: unknown): val is Promise {\n return typeof val === \"object\" && val != null && \"then\" in val;\n}\n\nfunction isDataStrategyResult(result: unknown): result is DataStrategyResult {\n return (\n result != null &&\n typeof result === \"object\" &&\n \"type\" in result &&\n \"result\" in result &&\n (result.type === ResultType.data || result.type === ResultType.error)\n );\n}\n\nfunction isRedirectDataStrategyResultResult(result: DataStrategyResult) {\n return (\n isResponse(result.result) && redirectStatusCodes.has(result.result.status)\n );\n}\n\nfunction isDeferredResult(result: DataResult): result is DeferredResult {\n return result.type === ResultType.deferred;\n}\n\nfunction isErrorResult(result: DataResult): result is ErrorResult {\n return result.type === ResultType.error;\n}\n\nfunction isRedirectResult(result?: DataResult): result is RedirectResult {\n return (result && result.type) === ResultType.redirect;\n}\n\nexport function isDataWithResponseInit(\n value: any\n): value is DataWithResponseInit {\n return (\n typeof value === \"object\" &&\n value != null &&\n \"type\" in value &&\n \"data\" in value &&\n \"init\" in value &&\n value.type === \"DataWithResponseInit\"\n );\n}\n\nexport function isDeferredData(value: any): value is DeferredData {\n let deferred: DeferredData = value;\n return (\n deferred &&\n typeof deferred === \"object\" &&\n typeof deferred.data === \"object\" &&\n typeof deferred.subscribe === \"function\" &&\n typeof deferred.cancel === \"function\" &&\n typeof deferred.resolveData === \"function\"\n );\n}\n\nfunction isResponse(value: any): value is Response {\n return (\n value != null &&\n typeof value.status === \"number\" &&\n typeof value.statusText === \"string\" &&\n typeof value.headers === \"object\" &&\n typeof value.body !== \"undefined\"\n );\n}\n\nfunction isRedirectResponse(result: any): result is Response {\n if (!isResponse(result)) {\n return false;\n }\n\n let status = result.status;\n let location = result.headers.get(\"Location\");\n return status >= 300 && status <= 399 && location != null;\n}\n\nfunction isValidMethod(method: string): method is FormMethod | V7_FormMethod {\n return validRequestMethods.has(method.toLowerCase() as FormMethod);\n}\n\nfunction isMutationMethod(\n method: string\n): method is MutationFormMethod | V7_MutationFormMethod {\n return validMutationMethods.has(method.toLowerCase() as MutationFormMethod);\n}\n\nasync function resolveNavigationDeferredResults(\n matches: (AgnosticDataRouteMatch | null)[],\n results: Record,\n signal: AbortSignal,\n currentMatches: AgnosticDataRouteMatch[],\n currentLoaderData: RouteData\n) {\n let entries = Object.entries(results);\n for (let index = 0; index < entries.length; index++) {\n let [routeId, result] = entries[index];\n let match = matches.find((m) => m?.route.id === routeId);\n // If we don't have a match, then we can have a deferred result to do\n // anything with. This is for revalidating fetchers where the route was\n // removed during HMR\n if (!match) {\n continue;\n }\n\n let currentMatch = currentMatches.find(\n (m) => m.route.id === match!.route.id\n );\n let isRevalidatingLoader =\n currentMatch != null &&\n !isNewRouteInstance(currentMatch, match) &&\n (currentLoaderData && currentLoaderData[match.route.id]) !== undefined;\n\n if (isDeferredResult(result) && isRevalidatingLoader) {\n // Note: we do not have to touch activeDeferreds here since we race them\n // against the signal in resolveDeferredData and they'll get aborted\n // there if needed\n await resolveDeferredData(result, signal, false).then((result) => {\n if (result) {\n results[routeId] = result;\n }\n });\n }\n }\n}\n\nasync function resolveFetcherDeferredResults(\n matches: (AgnosticDataRouteMatch | null)[],\n results: Record,\n revalidatingFetchers: RevalidatingFetcher[]\n) {\n for (let index = 0; index < revalidatingFetchers.length; index++) {\n let { key, routeId, controller } = revalidatingFetchers[index];\n let result = results[key];\n let match = matches.find((m) => m?.route.id === routeId);\n // If we don't have a match, then we can have a deferred result to do\n // anything with. This is for revalidating fetchers where the route was\n // removed during HMR\n if (!match) {\n continue;\n }\n\n if (isDeferredResult(result)) {\n // Note: we do not have to touch activeDeferreds here since we race them\n // against the signal in resolveDeferredData and they'll get aborted\n // there if needed\n invariant(\n controller,\n \"Expected an AbortController for revalidating fetcher deferred result\"\n );\n await resolveDeferredData(result, controller.signal, true).then(\n (result) => {\n if (result) {\n results[key] = result;\n }\n }\n );\n }\n }\n}\n\nasync function resolveDeferredData(\n result: DeferredResult,\n signal: AbortSignal,\n unwrap = false\n): Promise {\n let aborted = await result.deferredData.resolveData(signal);\n if (aborted) {\n return;\n }\n\n if (unwrap) {\n try {\n return {\n type: ResultType.data,\n data: result.deferredData.unwrappedData,\n };\n } catch (e) {\n // Handle any TrackedPromise._error values encountered while unwrapping\n return {\n type: ResultType.error,\n error: e,\n };\n }\n }\n\n return {\n type: ResultType.data,\n data: result.deferredData.data,\n };\n}\n\nfunction hasNakedIndexQuery(search: string): boolean {\n return new URLSearchParams(search).getAll(\"index\").some((v) => v === \"\");\n}\n\nfunction getTargetMatch(\n matches: AgnosticDataRouteMatch[],\n location: Location | string\n) {\n let search =\n typeof location === \"string\" ? parsePath(location).search : location.search;\n if (\n matches[matches.length - 1].route.index &&\n hasNakedIndexQuery(search || \"\")\n ) {\n // Return the leaf index route when index is present\n return matches[matches.length - 1];\n }\n // Otherwise grab the deepest \"path contributing\" match (ignoring index and\n // pathless layout routes)\n let pathMatches = getPathContributingMatches(matches);\n return pathMatches[pathMatches.length - 1];\n}\n\nfunction getSubmissionFromNavigation(\n navigation: Navigation\n): Submission | undefined {\n let { formMethod, formAction, formEncType, text, formData, json } =\n navigation;\n if (!formMethod || !formAction || !formEncType) {\n return;\n }\n\n if (text != null) {\n return {\n formMethod,\n formAction,\n formEncType,\n formData: undefined,\n json: undefined,\n text,\n };\n } else if (formData != null) {\n return {\n formMethod,\n formAction,\n formEncType,\n formData,\n json: undefined,\n text: undefined,\n };\n } else if (json !== undefined) {\n return {\n formMethod,\n formAction,\n formEncType,\n formData: undefined,\n json,\n text: undefined,\n };\n }\n}\n\nfunction getLoadingNavigation(\n location: Location,\n submission?: Submission\n): NavigationStates[\"Loading\"] {\n if (submission) {\n let navigation: NavigationStates[\"Loading\"] = {\n state: \"loading\",\n location,\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n };\n return navigation;\n } else {\n let navigation: NavigationStates[\"Loading\"] = {\n state: \"loading\",\n location,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n };\n return navigation;\n }\n}\n\nfunction getSubmittingNavigation(\n location: Location,\n submission: Submission\n): NavigationStates[\"Submitting\"] {\n let navigation: NavigationStates[\"Submitting\"] = {\n state: \"submitting\",\n location,\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n };\n return navigation;\n}\n\nfunction getLoadingFetcher(\n submission?: Submission,\n data?: Fetcher[\"data\"]\n): FetcherStates[\"Loading\"] {\n if (submission) {\n let fetcher: FetcherStates[\"Loading\"] = {\n state: \"loading\",\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n data,\n };\n return fetcher;\n } else {\n let fetcher: FetcherStates[\"Loading\"] = {\n state: \"loading\",\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n data,\n };\n return fetcher;\n }\n}\n\nfunction getSubmittingFetcher(\n submission: Submission,\n existingFetcher?: Fetcher\n): FetcherStates[\"Submitting\"] {\n let fetcher: FetcherStates[\"Submitting\"] = {\n state: \"submitting\",\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n data: existingFetcher ? existingFetcher.data : undefined,\n };\n return fetcher;\n}\n\nfunction getDoneFetcher(data: Fetcher[\"data\"]): FetcherStates[\"Idle\"] {\n let fetcher: FetcherStates[\"Idle\"] = {\n state: \"idle\",\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n data,\n };\n return fetcher;\n}\n\nfunction restoreAppliedTransitions(\n _window: Window,\n transitions: Map>\n) {\n try {\n let sessionPositions = _window.sessionStorage.getItem(\n TRANSITIONS_STORAGE_KEY\n );\n if (sessionPositions) {\n let json = JSON.parse(sessionPositions);\n for (let [k, v] of Object.entries(json || {})) {\n if (v && Array.isArray(v)) {\n transitions.set(k, new Set(v || []));\n }\n }\n }\n } catch (e) {\n // no-op, use default empty object\n }\n}\n\nfunction persistAppliedTransitions(\n _window: Window,\n transitions: Map>\n) {\n if (transitions.size > 0) {\n let json: Record = {};\n for (let [k, v] of transitions) {\n json[k] = [...v];\n }\n try {\n _window.sessionStorage.setItem(\n TRANSITIONS_STORAGE_KEY,\n JSON.stringify(json)\n );\n } catch (error) {\n warning(\n false,\n `Failed to save applied view transitions in sessionStorage (${error}).`\n );\n }\n }\n}\n//#endregion\n"],"names":["Action","PopStateEventType","invariant","value","message","Error","warning","cond","console","warn","e","getHistoryState","location","index","usr","state","key","idx","createLocation","current","to","_extends","pathname","search","hash","parsePath","Math","random","toString","substr","createPath","_ref","charAt","path","parsedPath","hashIndex","indexOf","searchIndex","getUrlBasedHistory","getLocation","createHref","validateLocation","options","window","document","defaultView","v5Compat","globalHistory","history","action","Pop","listener","getIndex","handlePop","nextIndex","delta","createURL","base","origin","href","replace","URL","replaceState","listen","fn","addEventListener","removeEventListener","encodeLocation","url","push","Push","historyState","pushState","error","DOMException","name","assign","Replace","go","n","ResultType","immutableRouteKeys","Set","convertRoutesToDataRoutes","routes","mapRouteProperties","parentPath","manifest","map","route","treePath","String","id","join","children","isIndexRoute","indexRoute","pathOrLayoutRoute","undefined","matchRoutes","locationArg","basename","matchRoutesImpl","allowPartial","stripBasename","branches","flattenRoutes","sort","a","b","score","siblings","length","slice","every","i","compareIndexes","routesMeta","meta","childrenIndex","rankRouteBranches","matches","decoded","decodePath","matchRouteBranch","convertRouteMatchToUiMatch","match","loaderData","params","data","handle","parentsMeta","flattenRoute","relativePath","caseSensitive","startsWith","joinPaths","concat","computeScore","forEach","_route$path","includes","exploded","explodeOptionalSegments","segments","split","first","rest","isOptional","endsWith","required","restExploded","result","subpath","paramRe","dynamicSegmentValue","indexRouteValue","emptySegmentValue","staticSegmentValue","splatPenalty","isSplat","s","initialScore","some","filter","reduce","segment","test","branch","matchedParams","matchedPathname","end","remainingPathname","matchPath","Object","pathnameBase","normalizePathname","pattern","matcher","compiledParams","regexpSource","_","paramName","RegExp","compilePath","captureGroups","memo","splatValue","v","decodeURIComponent","toLowerCase","startIndex","nextChar","resolvePath","fromPathname","toPathname","removeDoubleSlashes","resolvePathname","substring","normalizeSearch","normalizeHash","pop","getInvalidPathError","char","field","dest","JSON","stringify","getPathContributingMatches","getResolveToMatches","v7_relativeSplatPath","pathMatches","resolveTo","toArg","routePathnames","locationPathname","isPathRelative","from","isEmptyPath","routePathnameIndex","toSegments","shift","hasExplicitTrailingSlash","hasCurrentTrailingSlash","paths","DataWithResponseInit","constructor","init","this","type","AbortedDeferredError","DeferredData","responseInit","reject","pendingKeysSet","subscribers","deferredKeys","Array","isArray","abortPromise","Promise","r","controller","AbortController","onAbort","unlistenAbortSignal","signal","entries","acc","_ref2","trackPromise","done","add","promise","race","then","onSettle","catch","defineProperty","get","aborted","delete","undefinedError","emit","settledKey","subscriber","subscribe","cancel","abort","k","resolveData","resolve","size","unwrappedData","_ref3","unwrapTrackedPromise","pendingKeys","_tracked","isTrackedPromise","_error","_data","defer","redirect","status","headers","Headers","set","Response","ErrorResponseImpl","statusText","internal","isRouteErrorResponse","validMutationMethodsArr","validMutationMethods","validRequestMethodsArr","validRequestMethods","redirectStatusCodes","redirectPreserveMethodStatusCodes","IDLE_NAVIGATION","formMethod","formAction","formEncType","formData","json","text","IDLE_FETCHER","IDLE_BLOCKER","proceed","reset","ABSOLUTE_URL_REGEX","defaultMapRouteProperties","hasErrorBoundary","Boolean","TRANSITIONS_STORAGE_KEY","UNSAFE_DEFERRED_SYMBOL","Symbol","throwStaticHandlerAbortedError","request","isRouteRequest","future","v7_throwAbortReason","reason","method","normalizeTo","prependBasename","fromRouteId","relative","contextualMatches","activeRouteMatch","nakedIndex","hasNakedIndexQuery","URLSearchParams","indexValues","getAll","append","qs","normalizeNavigateOptions","normalizeFormMethod","isFetcher","opts","body","isSubmissionNavigation","isValidMethod","getInternalRouterError","searchParams","getInvalidBodyError","rawFormMethod","toUpperCase","stripHashFromPath","isMutationMethod","FormData","submission","parse","convertFormDataToSearchParams","convertSearchParamsToFormData","getLoaderMatchesUntilBoundary","boundaryId","includeBoundary","findIndex","m","getMatchesToLoad","initialHydration","skipActionErrorRevalidation","isRevalidationRequired","cancelledDeferredRoutes","cancelledFetcherLoads","deletedFetchers","fetchLoadMatches","fetchRedirectIds","routesToUse","pendingActionResult","actionResult","isErrorResult","currentUrl","nextUrl","boundaryMatches","errors","keys","actionStatus","statusCode","shouldSkipRevalidation","navigationMatches","lazy","loader","shouldLoadRouteOnHydration","currentLoaderData","currentMatch","isNew","isMissingData","isNewLoader","currentRouteMatch","nextRouteMatch","shouldRevalidateLoader","currentParams","nextParams","defaultShouldRevalidate","isNewRouteInstance","revalidatingFetchers","f","routeId","has","fetcherMatches","fetcher","fetchers","fetcherMatch","getTargetMatch","shouldRevalidate","hasData","hasError","hydrate","currentPath","loaderMatch","arg","routeChoice","patchRoutesImpl","_childrenToPatch","childrenToPatch","newRoutes","newRoute","existingRoute","isSameRoute","aChild","_existingRoute$childr","bChild","async","defaultDataStrategy","_ref4","matchesToLoad","shouldLoad","all","callDataStrategyImpl","dataStrategyImpl","fetcherKey","requestContext","loadRouteDefinitionsPromises","lazyRoute","routeToUpdate","routeUpdates","lazyRouteProperty","isPropertyStaticallyDefined","loadLazyRouteModule","dsMatches","loadRoutePromise","handlerOverride","staticContext","onReject","runHandler","handler","actualHandler","ctx","context","handlerPromise","handlerError","callLoaderOrAction","results","convertDataStrategyResultToDataResult","dataStrategyResult","isResponse","contentType","_result$init3","_result$init4","_result$init","_result$init2","_result$init5","_result$init6","_result$init7","_result$init8","isDataWithResponseInit","isDeferredData","deferred","deferredData","normalizeRelativeRoutingRedirectResponse","response","trimmedMatches","normalizeRedirectLocation","historyInstance","invalidProtocols","normalizedLocation","protocol","isSameBasename","createClientSideRequest","Request","processRouteLoaderData","activeDeferreds","skipLoaderErrorBubbling","foundError","loaderHeaders","pendingError","isRedirectResult","boundaryMatch","findNearestBoundary","isDeferredResult","processLoaderData","fetcherResults","rf","doneFetcher","getDoneFetcher","mergeLoaderData","newLoaderData","mergedLoaderData","hasOwnProperty","getActionDataForCommit","actionData","reverse","find","getShortCircuitMatches","_temp5","errorMessage","findRedirect","isRedirectDataStrategyResultResult","resolveNavigationDeferredResults","currentMatches","isRevalidatingLoader","resolveDeferredData","resolveFetcherDeferredResults","unwrap","getSubmissionFromNavigation","navigation","getLoadingNavigation","getLoadingFetcher","querySelector","getAttribute","initialEntries","initialIndex","entry","createMemoryLocation","clampIndex","min","max","getCurrentLocation","nextLocation","splice","routerWindow","isBrowser","createElement","isServer","detectErrorBoundary","inFlightDataRoutes","initialized","router","dataRoutes","dataStrategy","patchRoutesOnNavigationImpl","patchRoutesOnNavigation","v7_fetcherPersist","v7_normalizeFormMethod","v7_partialHydration","v7_prependBasename","v7_skipActionErrorRevalidation","unlistenHistory","savedScrollPositions","getScrollRestorationKey","getScrollPosition","initialScrollRestored","hydrationData","initialMatches","initialMatchesIsFOW","initialErrors","checkFogOfWar","active","fogOfWar","pendingNavigationController","unblockBlockerHistoryUpdate","historyAction","restoreScrollPosition","preventScrollReset","revalidation","Map","blockers","pendingAction","HistoryAction","pendingPreventScrollReset","pendingViewTransitionEnabled","appliedViewTransitions","removePageHideEventListener","isUninterruptedRevalidation","fetchControllers","incrementingLoadId","pendingNavigationLoadId","fetchReloadIds","activeFetchers","blockerFunctions","updateState","newState","completedFetchers","deletedFetchersKeys","viewTransitionOpts","flushSync","deleteFetcher","completeNavigation","_temp","_location$state","_location$state2","isActionReload","_isRedirect","priorPaths","currentLocation","toPaths","getSavedScrollPosition","startNavigation","startUninterruptedRevalidation","getScrollKey","saveScrollPosition","enableViewTransition","loadingNavigation","overrideNavigation","isHashChangeOnly","notFoundMatches","handleNavigational404","isFogOfWar","interruptActiveLoads","getSubmittingNavigation","discoverResult","discoverRoutes","shortCircuited","partialMatches","actionMatch","callDataStrategy","startRedirectNavigation","handleAction","updatedMatches","fetcherSubmission","activeSubmission","shouldUpdateNavigationState","getUpdatedActionData","cancelActiveDeferreds","updatedFetchers","markFetchRedirectsDone","updates","revalidatingFetcher","getUpdatedRevalidatingFetchers","abortFetcher","abortPendingFetchRevalidations","loaderResults","callLoadersAndMaybeResolveData","didAbortFetchLoads","abortStaleFetchLoads","shouldUpdateFetchers","handleLoaders","isNavigation","_temp2","redirectLocation","isDocumentReload","redirectHistoryAction","dataResults","fetchersToLoad","loaderResultsPromise","fetcherResultsPromise","updateFetcherState","setFetcherError","getFetcher","markFetchersDone","doneKeys","landedId","yeetedKeys","deleteBlocker","updateBlocker","newBlocker","blocker","shouldBlockNavigation","blockerKey","blockerFunction","predicate","cancelledRouteIds","dfd","y","isNonHMR","localManifest","patch","newMatches","newPartialMatches","initialize","nextHistoryUpdatePromise","_window","transitions","sessionPositions","sessionStorage","getItem","restoreAppliedTransitions","_saveAppliedTransitions","setItem","persistAppliedTransitions","enableScrollRestoration","positions","getPosition","getKey","navigate","normalizedPath","userReplace","viewTransition","fetch","requestMatches","detectAndHandle405Error","existingFetcher","getSubmittingFetcher","abortController","fetchRequest","originatingLoadId","actionResults","revalidationRequest","loadId","loadFetcher","staleKey","handleFetcherAction","handleFetcherLoader","revalidate","count","dispose","clear","getBlocker","patchRoutes","_internalFetchControllers","_internalActiveDeferreds","_internalSetRoutes","queryImpl","routeMatch","Location","actionHeaders","loaderRequest","loadRouteData","submit","isRedirectResponse","executedLoaders","fromEntries","query","_temp3","methodNotAllowedMatches","queryRoute","_temp4","values","_result$activeDeferre","originalPath","prefix","p","array","keyMatch","optional","param","_deepestRenderedBoundaryId","redirectDocument"],"mappings":";;;;;;;;;;0cAOYA,IAAAA,WAAAA,GAAM,OAANA,EAAM,IAAA,MAANA,EAAM,KAAA,OAANA,EAAM,QAAA,UAANA,CAAM,EAAA,IA2LlB,MAAMC,EAAoB,WAySnB,SAASC,EAAUC,EAAYC,GACpC,IAAc,IAAVD,SAAmBA,EACrB,MAAM,IAAIE,MAAMD,EAEpB,CAEO,SAASE,EAAQC,EAAWH,GACjC,IAAKG,EAAM,CAEc,oBAAZC,SAAyBA,QAAQC,KAAKL,GAEjD,IAME,MAAM,IAAIC,MAAMD,EAElB,CAAE,MAAOM,GAAI,CACf,CACF,CASA,SAASC,EAAgBC,EAAoBC,GAC3C,MAAO,CACLC,IAAKF,EAASG,MACdC,IAAKJ,EAASI,IACdC,IAAKJ,EAET,CAKO,SAASK,EACdC,EACAC,EACAL,EACAC,GAcA,YAfU,IAAVD,IAAAA,EAAa,MAGmBM,EAAA,CAC9BC,SAA6B,iBAAZH,EAAuBA,EAAUA,EAAQG,SAC1DC,OAAQ,GACRC,KAAM,IACY,iBAAPJ,EA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,EAAKgtB,GAAYD,EAC1B,IAAIE,EAAQjmB,EAAOhH,GAEnB,OADAd,EAAuB,MAAb8tB,GAA6B,MAATC,EAAa,aAAejtB,EAAG,WACtD+L,EAAUkhB,EACnB,CAGA,OAAO3jB,EAAQ1G,QAAQ,OAAQ,MAGhCwG,OAAQE,KAAcA,GAEAzE,KAAK,IAChC,8BCmmGO,SACLT,EACA8W,EACAzX,GASA,OAPoCpD,EAAA,CAAA,EAC/B6a,EAAO,CACVvE,WAAYxF,EAAqB1N,GAASA,EAAMkN,OAAS,IACzD6F,OAAQ,CACN,CAAC0E,EAAQgS,4BAA8B9oB,EAAO,GAAGQ,IAAKnB,IAI5D,kBDltFO,SAAuBrD,GAE5B,MAAc,KAAPA,GAAuC,KAAzBA,EAAYE,SAC7B,IACc,iBAAPF,EACPK,EAAUL,GAAIE,SACdF,EAAGE,QACT,gGA6CkC,SAAC2G,EAAMkG,QAAI,IAAJA,IAAAA,EAAO,CAAA,GAC9C,IAAIK,EAA+B,iBAATL,EAAoB,CAAEwD,OAAQxD,GAASA,EAE7DyD,EAAU,IAAIC,QAAQrD,EAAaoD,SAKvC,OAJKA,EAAQoH,IAAI,iBACfpH,EAAQE,IAAI,eAAgB,mCAGvB,IAAIC,SAASjF,KAAKC,UAAU9E,GAAK5G,EAAA,CAAA,EACnCmN,EAAY,CACfoD,YAEJ,oGA0QkDuc,CAAC/pB,EAAK+J,KACtD,IAAIqP,EAAW9L,EAAStN,EAAK+J,GAE7B,OADAqP,EAAS5L,QAAQE,IAAI,0BAA2B,QACzC0L,aASgC5Z,CAACQ,EAAK+J,KAC7C,IAAIqP,EAAW9L,EAAStN,EAAK+J,GAE7B,OADAqP,EAAS5L,QAAQE,IAAI,kBAAmB,QACjC0L"} apps/frontend/node_modules/@remix-run/router/dist/router.umd.js:1403: this.subscribers = new Set(); apps/frontend/node_modules/@remix-run/router/dist/router.umd.js:1484: this.subscribers.forEach(subscriber => subscriber(aborted, settledKey)); apps/frontend/node_modules/@remix-run/router/dist/router.umd.js:1486: subscribe(fn) { apps/frontend/node_modules/@remix-run/router/dist/router.umd.js:1487: this.subscribers.add(fn); apps/frontend/node_modules/@remix-run/router/dist/router.umd.js:1488: return () => this.subscribers.delete(fn); apps/frontend/node_modules/@remix-run/router/dist/router.umd.js:1501: this.subscribe(aborted => { apps/frontend/node_modules/@remix-run/router/dist/router.umd.js:1809: let subscribers = new Set(); apps/frontend/node_modules/@remix-run/router/dist/router.umd.js:2081: subscribers.clear(); apps/frontend/node_modules/@remix-run/router/dist/router.umd.js:2088: function subscribe(fn) { apps/frontend/node_modules/@remix-run/router/dist/router.umd.js:2089: subscribers.add(fn); apps/frontend/node_modules/@remix-run/router/dist/router.umd.js:2090: return () => subscribers.delete(fn); apps/frontend/node_modules/@remix-run/router/dist/router.umd.js:2128: // removing and adding a new subscriber due to the useCallback dependencies, apps/frontend/node_modules/@remix-run/router/dist/router.umd.js:2129: // we don't get ourselves into a loop calling the new subscriber immediately apps/frontend/node_modules/@remix-run/router/dist/router.umd.js:2130: [...subscribers].forEach(subscriber => subscriber(state, { apps/frontend/node_modules/@remix-run/router/dist/router.umd.js:2800: // Wire up subscribers to update loaderData as promises settle apps/frontend/node_modules/@remix-run/router/dist/router.umd.js:2802: deferredData.subscribe(aborted => { apps/frontend/node_modules/@remix-run/router/dist/router.umd.js:3578: // we rely on the subscribers to do that so our tests can assert proper apps/frontend/node_modules/@remix-run/router/dist/router.umd.js:3762: subscribe, apps/frontend/node_modules/@remix-run/router/dist/router.umd.js:5377: return deferred && typeof deferred === "object" && typeof deferred.data === "object" && typeof deferred.subscribe === "function" && typeof deferred.cancel === "function" && typeof deferred.resolveData === "function"; apps/frontend/node_modules/@remix-run/router/dist/utils.d.ts:491: private subscribers; apps/frontend/node_modules/@remix-run/router/dist/utils.d.ts:499: subscribe(fn: (aborted: boolean, settledKey?: string) => void): () => boolean; apps/frontend/node_modules/@remix-run/router/dist/router.d.ts:60: subscribe(fn: RouterSubscriber): () => void; apps/frontend/node_modules/@remix-run/router/dist/router.cjs.js:1401: this.subscribers = new Set(); apps/frontend/node_modules/@remix-run/router/dist/router.cjs.js:1482: this.subscribers.forEach(subscriber => subscriber(aborted, settledKey)); apps/frontend/node_modules/@remix-run/router/dist/router.cjs.js:1484: subscribe(fn) { apps/frontend/node_modules/@remix-run/router/dist/router.cjs.js:1485: this.subscribers.add(fn); apps/frontend/node_modules/@remix-run/router/dist/router.cjs.js:1486: return () => this.subscribers.delete(fn); apps/frontend/node_modules/@remix-run/router/dist/router.cjs.js:1499: this.subscribe(aborted => { apps/frontend/node_modules/@remix-run/router/dist/router.cjs.js:1807: let subscribers = new Set(); apps/frontend/node_modules/@remix-run/router/dist/router.cjs.js:2079: subscribers.clear(); apps/frontend/node_modules/@remix-run/router/dist/router.cjs.js:2086: function subscribe(fn) { apps/frontend/node_modules/@remix-run/router/dist/router.cjs.js:2087: subscribers.add(fn); apps/frontend/node_modules/@remix-run/router/dist/router.cjs.js:2088: return () => subscribers.delete(fn); apps/frontend/node_modules/@remix-run/router/dist/router.cjs.js:2126: // removing and adding a new subscriber due to the useCallback dependencies, apps/frontend/node_modules/@remix-run/router/dist/router.cjs.js:2127: // we don't get ourselves into a loop calling the new subscriber immediately apps/frontend/node_modules/@remix-run/router/dist/router.cjs.js:2128: [...subscribers].forEach(subscriber => subscriber(state, { apps/frontend/node_modules/@remix-run/router/dist/router.cjs.js:2798: // Wire up subscribers to update loaderData as promises settle apps/frontend/node_modules/@remix-run/router/dist/router.cjs.js:2800: deferredData.subscribe(aborted => { apps/frontend/node_modules/@remix-run/router/dist/router.cjs.js:3576: // we rely on the subscribers to do that so our tests can assert proper apps/frontend/node_modules/@remix-run/router/dist/router.cjs.js:3760: subscribe, apps/frontend/node_modules/@remix-run/router/dist/router.cjs.js:5375: return deferred && typeof deferred === "object" && typeof deferred.data === "object" && typeof deferred.subscribe === "function" && typeof deferred.cancel === "function" && typeof deferred.resolveData === "function"; apps/frontend/node_modules/@remix-run/router/dist/router.umd.js.map:1:{"version":3,"file":"router.umd.js","sources":["../history.ts","../utils.ts","../router.ts"],"sourcesContent":["////////////////////////////////////////////////////////////////////////////////\n//#region Types and Constants\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Actions represent the type of change to a location value.\n */\nexport enum Action {\n /**\n * A POP indicates a change to an arbitrary index in the history stack, such\n * as a back or forward navigation. It does not describe the direction of the\n * navigation, only that the current index changed.\n *\n * Note: This is the default action for newly created history objects.\n */\n Pop = \"POP\",\n\n /**\n * A PUSH indicates a new entry being added to the history stack, such as when\n * a link is clicked and a new page loads. When this happens, all subsequent\n * entries in the stack are lost.\n */\n Push = \"PUSH\",\n\n /**\n * A REPLACE indicates the entry at the current index in the history stack\n * being replaced by a new one.\n */\n Replace = \"REPLACE\",\n}\n\n/**\n * The pathname, search, and hash values of a URL.\n */\nexport interface Path {\n /**\n * A URL pathname, beginning with a /.\n */\n pathname: string;\n\n /**\n * A URL search string, beginning with a ?.\n */\n search: string;\n\n /**\n * A URL fragment identifier, beginning with a #.\n */\n hash: string;\n}\n\n// TODO: (v7) Change the Location generic default from `any` to `unknown` and\n// remove Remix `useLocation` wrapper.\n\n/**\n * An entry in a history stack. A location contains information about the\n * URL path, as well as possibly some arbitrary state and a key.\n */\nexport interface Location extends Path {\n /**\n * A value of arbitrary data associated with this location.\n */\n state: State;\n\n /**\n * A unique string associated with this location. May be used to safely store\n * and retrieve data in some other storage API, like `localStorage`.\n *\n * Note: This value is always \"default\" on the initial location.\n */\n key: string;\n}\n\n/**\n * A change to the current location.\n */\nexport interface Update {\n /**\n * The action that triggered the change.\n */\n action: Action;\n\n /**\n * The new location.\n */\n location: Location;\n\n /**\n * The delta between this location and the former location in the history stack\n */\n delta: number | null;\n}\n\n/**\n * A function that receives notifications about location changes.\n */\nexport interface Listener {\n (update: Update): void;\n}\n\n/**\n * Describes a location that is the destination of some navigation, either via\n * `history.push` or `history.replace`. This may be either a URL or the pieces\n * of a URL path.\n */\nexport type To = string | Partial;\n\n/**\n * A history is an interface to the navigation stack. The history serves as the\n * source of truth for the current location, as well as provides a set of\n * methods that may be used to change it.\n *\n * It is similar to the DOM's `window.history` object, but with a smaller, more\n * focused API.\n */\nexport interface History {\n /**\n * The last action that modified the current location. This will always be\n * Action.Pop when a history instance is first created. This value is mutable.\n */\n readonly action: Action;\n\n /**\n * The current location. This value is mutable.\n */\n readonly location: Location;\n\n /**\n * Returns a valid href for the given `to` value that may be used as\n * the value of an attribute.\n *\n * @param to - The destination URL\n */\n createHref(to: To): string;\n\n /**\n * Returns a URL for the given `to` value\n *\n * @param to - The destination URL\n */\n createURL(to: To): URL;\n\n /**\n * Encode a location the same way window.history would do (no-op for memory\n * history) so we ensure our PUSH/REPLACE navigations for data routers\n * behave the same as POP\n *\n * @param to Unencoded path\n */\n encodeLocation(to: To): Path;\n\n /**\n * Pushes a new location onto the history stack, increasing its length by one.\n * If there were any entries in the stack after the current one, they are\n * lost.\n *\n * @param to - The new URL\n * @param state - Data to associate with the new location\n */\n push(to: To, state?: any): void;\n\n /**\n * Replaces the current location in the history stack with a new one. The\n * location that was replaced will no longer be available.\n *\n * @param to - The new URL\n * @param state - Data to associate with the new location\n */\n replace(to: To, state?: any): void;\n\n /**\n * Navigates `n` entries backward/forward in the history stack relative to the\n * current index. For example, a \"back\" navigation would use go(-1).\n *\n * @param delta - The delta in the stack index\n */\n go(delta: number): void;\n\n /**\n * Sets up a listener that will be called whenever the current location\n * changes.\n *\n * @param listener - A function that will be called when the location changes\n * @returns unlisten - A function that may be used to stop listening\n */\n listen(listener: Listener): () => void;\n}\n\ntype HistoryState = {\n usr: any;\n key?: string;\n idx: number;\n};\n\nconst PopStateEventType = \"popstate\";\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Memory History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A user-supplied object that describes a location. Used when providing\n * entries to `createMemoryHistory` via its `initialEntries` option.\n */\nexport type InitialEntry = string | Partial;\n\nexport type MemoryHistoryOptions = {\n initialEntries?: InitialEntry[];\n initialIndex?: number;\n v5Compat?: boolean;\n};\n\n/**\n * A memory history stores locations in memory. This is useful in stateful\n * environments where there is no web browser, such as node tests or React\n * Native.\n */\nexport interface MemoryHistory extends History {\n /**\n * The current index in the history stack.\n */\n readonly index: number;\n}\n\n/**\n * Memory history stores the current location in memory. It is designed for use\n * in stateful non-browser environments like tests and React Native.\n */\nexport function createMemoryHistory(\n options: MemoryHistoryOptions = {}\n): MemoryHistory {\n let { initialEntries = [\"/\"], initialIndex, v5Compat = false } = options;\n let entries: Location[]; // Declare so we can access from createMemoryLocation\n entries = initialEntries.map((entry, index) =>\n createMemoryLocation(\n entry,\n typeof entry === \"string\" ? null : entry.state,\n index === 0 ? \"default\" : undefined\n )\n );\n let index = clampIndex(\n initialIndex == null ? entries.length - 1 : initialIndex\n );\n let action = Action.Pop;\n let listener: Listener | null = null;\n\n function clampIndex(n: number): number {\n return Math.min(Math.max(n, 0), entries.length - 1);\n }\n function getCurrentLocation(): Location {\n return entries[index];\n }\n function createMemoryLocation(\n to: To,\n state: any = null,\n key?: string\n ): Location {\n let location = createLocation(\n entries ? getCurrentLocation().pathname : \"/\",\n to,\n state,\n key\n );\n warning(\n location.pathname.charAt(0) === \"/\",\n `relative pathnames are not supported in memory history: ${JSON.stringify(\n to\n )}`\n );\n return location;\n }\n\n function createHref(to: To) {\n return typeof to === \"string\" ? to : createPath(to);\n }\n\n let history: MemoryHistory = {\n get index() {\n return index;\n },\n get action() {\n return action;\n },\n get location() {\n return getCurrentLocation();\n },\n createHref,\n createURL(to) {\n return new URL(createHref(to), \"http://localhost\");\n },\n encodeLocation(to: To) {\n let path = typeof to === \"string\" ? parsePath(to) : to;\n return {\n pathname: path.pathname || \"\",\n search: path.search || \"\",\n hash: path.hash || \"\",\n };\n },\n push(to, state) {\n action = Action.Push;\n let nextLocation = createMemoryLocation(to, state);\n index += 1;\n entries.splice(index, entries.length, nextLocation);\n if (v5Compat && listener) {\n listener({ action, location: nextLocation, delta: 1 });\n }\n },\n replace(to, state) {\n action = Action.Replace;\n let nextLocation = createMemoryLocation(to, state);\n entries[index] = nextLocation;\n if (v5Compat && listener) {\n listener({ action, location: nextLocation, delta: 0 });\n }\n },\n go(delta) {\n action = Action.Pop;\n let nextIndex = clampIndex(index + delta);\n let nextLocation = entries[nextIndex];\n index = nextIndex;\n if (listener) {\n listener({ action, location: nextLocation, delta });\n }\n },\n listen(fn: Listener) {\n listener = fn;\n return () => {\n listener = null;\n };\n },\n };\n\n return history;\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Browser History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A browser history stores the current location in regular URLs in a web\n * browser environment. This is the standard for most web apps and provides the\n * cleanest URLs the browser's address bar.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#browserhistory\n */\nexport interface BrowserHistory extends UrlHistory {}\n\nexport type BrowserHistoryOptions = UrlHistoryOptions;\n\n/**\n * Browser history stores the location in regular URLs. This is the standard for\n * most web apps, but it requires some configuration on the server to ensure you\n * serve the same app at multiple URLs.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory\n */\nexport function createBrowserHistory(\n options: BrowserHistoryOptions = {}\n): BrowserHistory {\n function createBrowserLocation(\n window: Window,\n globalHistory: Window[\"history\"]\n ) {\n let { pathname, search, hash } = window.location;\n return createLocation(\n \"\",\n { pathname, search, hash },\n // state defaults to `null` because `window.history.state` does\n (globalHistory.state && globalHistory.state.usr) || null,\n (globalHistory.state && globalHistory.state.key) || \"default\"\n );\n }\n\n function createBrowserHref(window: Window, to: To) {\n return typeof to === \"string\" ? to : createPath(to);\n }\n\n return getUrlBasedHistory(\n createBrowserLocation,\n createBrowserHref,\n null,\n options\n );\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Hash History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A hash history stores the current location in the fragment identifier portion\n * of the URL in a web browser environment.\n *\n * This is ideal for apps that do not control the server for some reason\n * (because the fragment identifier is never sent to the server), including some\n * shared hosting environments that do not provide fine-grained controls over\n * which pages are served at which URLs.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#hashhistory\n */\nexport interface HashHistory extends UrlHistory {}\n\nexport type HashHistoryOptions = UrlHistoryOptions;\n\n/**\n * Hash history stores the location in window.location.hash. This makes it ideal\n * for situations where you don't want to send the location to the server for\n * some reason, either because you do cannot configure it or the URL space is\n * reserved for something else.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory\n */\nexport function createHashHistory(\n options: HashHistoryOptions = {}\n): HashHistory {\n function createHashLocation(\n window: Window,\n globalHistory: Window[\"history\"]\n ) {\n let {\n pathname = \"/\",\n search = \"\",\n hash = \"\",\n } = parsePath(window.location.hash.substr(1));\n\n // Hash URL should always have a leading / just like window.location.pathname\n // does, so if an app ends up at a route like /#something then we add a\n // leading slash so all of our path-matching behaves the same as if it would\n // in a browser router. This is particularly important when there exists a\n // root splat route () since that matches internally against\n // \"/*\" and we'd expect /#something to 404 in a hash router app.\n if (!pathname.startsWith(\"/\") && !pathname.startsWith(\".\")) {\n pathname = \"/\" + pathname;\n }\n\n return createLocation(\n \"\",\n { pathname, search, hash },\n // state defaults to `null` because `window.history.state` does\n (globalHistory.state && globalHistory.state.usr) || null,\n (globalHistory.state && globalHistory.state.key) || \"default\"\n );\n }\n\n function createHashHref(window: Window, to: To) {\n let base = window.document.querySelector(\"base\");\n let href = \"\";\n\n if (base && base.getAttribute(\"href\")) {\n let url = window.location.href;\n let hashIndex = url.indexOf(\"#\");\n href = hashIndex === -1 ? url : url.slice(0, hashIndex);\n }\n\n return href + \"#\" + (typeof to === \"string\" ? to : createPath(to));\n }\n\n function validateHashLocation(location: Location, to: To) {\n warning(\n location.pathname.charAt(0) === \"/\",\n `relative pathnames are not supported in hash history.push(${JSON.stringify(\n to\n )})`\n );\n }\n\n return getUrlBasedHistory(\n createHashLocation,\n createHashHref,\n validateHashLocation,\n options\n );\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region UTILS\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * @private\n */\nexport function invariant(value: boolean, message?: string): asserts value;\nexport function invariant(\n value: T | null | undefined,\n message?: string\n): asserts value is T;\nexport function invariant(value: any, message?: string) {\n if (value === false || value === null || typeof value === \"undefined\") {\n throw new Error(message);\n }\n}\n\nexport function warning(cond: any, message: string) {\n if (!cond) {\n // eslint-disable-next-line no-console\n if (typeof console !== \"undefined\") console.warn(message);\n\n try {\n // Welcome to debugging history!\n //\n // This error is thrown as a convenience, so you can more easily\n // find the source for a warning that appears in the console by\n // enabling \"pause on exceptions\" in your JavaScript debugger.\n throw new Error(message);\n // eslint-disable-next-line no-empty\n } catch (e) {}\n }\n}\n\nfunction createKey() {\n return Math.random().toString(36).substr(2, 8);\n}\n\n/**\n * For browser-based histories, we combine the state and key into an object\n */\nfunction getHistoryState(location: Location, index: number): HistoryState {\n return {\n usr: location.state,\n key: location.key,\n idx: index,\n };\n}\n\n/**\n * Creates a Location object with a unique key from the given Path\n */\nexport function createLocation(\n current: string | Location,\n to: To,\n state: any = null,\n key?: string\n): Readonly {\n let location: Readonly = {\n pathname: typeof current === \"string\" ? current : current.pathname,\n search: \"\",\n hash: \"\",\n ...(typeof to === \"string\" ? parsePath(to) : to),\n state,\n // TODO: This could be cleaned up. push/replace should probably just take\n // full Locations now and avoid the need to run through this flow at all\n // But that's a pretty big refactor to the current test suite so going to\n // keep as is for the time being and just let any incoming keys take precedence\n key: (to && (to as Location).key) || key || createKey(),\n };\n return location;\n}\n\n/**\n * Creates a string URL path from the given pathname, search, and hash components.\n */\nexport function createPath({\n pathname = \"/\",\n search = \"\",\n hash = \"\",\n}: Partial) {\n if (search && search !== \"?\")\n pathname += search.charAt(0) === \"?\" ? search : \"?\" + search;\n if (hash && hash !== \"#\")\n pathname += hash.charAt(0) === \"#\" ? hash : \"#\" + hash;\n return pathname;\n}\n\n/**\n * Parses a string URL path into its separate pathname, search, and hash components.\n */\nexport function parsePath(path: string): Partial {\n let parsedPath: Partial = {};\n\n if (path) {\n let hashIndex = path.indexOf(\"#\");\n if (hashIndex >= 0) {\n parsedPath.hash = path.substr(hashIndex);\n path = path.substr(0, hashIndex);\n }\n\n let searchIndex = path.indexOf(\"?\");\n if (searchIndex >= 0) {\n parsedPath.search = path.substr(searchIndex);\n path = path.substr(0, searchIndex);\n }\n\n if (path) {\n parsedPath.pathname = path;\n }\n }\n\n return parsedPath;\n}\n\nexport interface UrlHistory extends History {}\n\nexport type UrlHistoryOptions = {\n window?: Window;\n v5Compat?: boolean;\n};\n\nfunction getUrlBasedHistory(\n getLocation: (window: Window, globalHistory: Window[\"history\"]) => Location,\n createHref: (window: Window, to: To) => string,\n validateLocation: ((location: Location, to: To) => void) | null,\n options: UrlHistoryOptions = {}\n): UrlHistory {\n let { window = document.defaultView!, v5Compat = false } = options;\n let globalHistory = window.history;\n let action = Action.Pop;\n let listener: Listener | null = null;\n\n let index = getIndex()!;\n // Index should only be null when we initialize. If not, it's because the\n // user called history.pushState or history.replaceState directly, in which\n // case we should log a warning as it will result in bugs.\n if (index == null) {\n index = 0;\n globalHistory.replaceState({ ...globalHistory.state, idx: index }, \"\");\n }\n\n function getIndex(): number {\n let state = globalHistory.state || { idx: null };\n return state.idx;\n }\n\n function handlePop() {\n action = Action.Pop;\n let nextIndex = getIndex();\n let delta = nextIndex == null ? null : nextIndex - index;\n index = nextIndex;\n if (listener) {\n listener({ action, location: history.location, delta });\n }\n }\n\n function push(to: To, state?: any) {\n action = Action.Push;\n let location = createLocation(history.location, to, state);\n if (validateLocation) validateLocation(location, to);\n\n index = getIndex() + 1;\n let historyState = getHistoryState(location, index);\n let url = history.createHref(location);\n\n // try...catch because iOS limits us to 100 pushState calls :/\n try {\n globalHistory.pushState(historyState, \"\", url);\n } catch (error) {\n // If the exception is because `state` can't be serialized, let that throw\n // outwards just like a replace call would so the dev knows the cause\n // https://html.spec.whatwg.org/multipage/nav-history-apis.html#shared-history-push/replace-state-steps\n // https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeinternal\n if (error instanceof DOMException && error.name === \"DataCloneError\") {\n throw error;\n }\n // They are going to lose state here, but there is no real\n // way to warn them about it since the page will refresh...\n window.location.assign(url);\n }\n\n if (v5Compat && listener) {\n listener({ action, location: history.location, delta: 1 });\n }\n }\n\n function replace(to: To, state?: any) {\n action = Action.Replace;\n let location = createLocation(history.location, to, state);\n if (validateLocation) validateLocation(location, to);\n\n index = getIndex();\n let historyState = getHistoryState(location, index);\n let url = history.createHref(location);\n globalHistory.replaceState(historyState, \"\", url);\n\n if (v5Compat && listener) {\n listener({ action, location: history.location, delta: 0 });\n }\n }\n\n function createURL(to: To): URL {\n // window.location.origin is \"null\" (the literal string value) in Firefox\n // under certain conditions, notably when serving from a local HTML file\n // See https://bugzilla.mozilla.org/show_bug.cgi?id=878297\n let base =\n window.location.origin !== \"null\"\n ? window.location.origin\n : window.location.href;\n\n let href = typeof to === \"string\" ? to : createPath(to);\n // Treating this as a full URL will strip any trailing spaces so we need to\n // pre-encode them since they might be part of a matching splat param from\n // an ancestor route\n href = href.replace(/ $/, \"%20\");\n invariant(\n base,\n `No window.location.(origin|href) available to create URL for href: ${href}`\n );\n return new URL(href, base);\n }\n\n let history: History = {\n get action() {\n return action;\n },\n get location() {\n return getLocation(window, globalHistory);\n },\n listen(fn: Listener) {\n if (listener) {\n throw new Error(\"A history only accepts one active listener\");\n }\n window.addEventListener(PopStateEventType, handlePop);\n listener = fn;\n\n return () => {\n window.removeEventListener(PopStateEventType, handlePop);\n listener = null;\n };\n },\n createHref(to) {\n return createHref(window, to);\n },\n createURL,\n encodeLocation(to) {\n // Encode a Location the same way window.location would\n let url = createURL(to);\n return {\n pathname: url.pathname,\n search: url.search,\n hash: url.hash,\n };\n },\n push,\n replace,\n go(n) {\n return globalHistory.go(n);\n },\n };\n\n return history;\n}\n\n//#endregion\n","import type { Location, Path, To } from \"./history\";\nimport { invariant, parsePath, warning } from \"./history\";\n\n/**\n * Map of routeId -> data returned from a loader/action/error\n */\nexport interface RouteData {\n [routeId: string]: any;\n}\n\nexport enum ResultType {\n data = \"data\",\n deferred = \"deferred\",\n redirect = \"redirect\",\n error = \"error\",\n}\n\n/**\n * Successful result from a loader or action\n */\nexport interface SuccessResult {\n type: ResultType.data;\n data: unknown;\n statusCode?: number;\n headers?: Headers;\n}\n\n/**\n * Successful defer() result from a loader or action\n */\nexport interface DeferredResult {\n type: ResultType.deferred;\n deferredData: DeferredData;\n statusCode?: number;\n headers?: Headers;\n}\n\n/**\n * Redirect result from a loader or action\n */\nexport interface RedirectResult {\n type: ResultType.redirect;\n // We keep the raw Response for redirects so we can return it verbatim\n response: Response;\n}\n\n/**\n * Unsuccessful result from a loader or action\n */\nexport interface ErrorResult {\n type: ResultType.error;\n error: unknown;\n statusCode?: number;\n headers?: Headers;\n}\n\n/**\n * Result from a loader or action - potentially successful or unsuccessful\n */\nexport type DataResult =\n | SuccessResult\n | DeferredResult\n | RedirectResult\n | ErrorResult;\n\ntype LowerCaseFormMethod = \"get\" | \"post\" | \"put\" | \"patch\" | \"delete\";\ntype UpperCaseFormMethod = Uppercase;\n\n/**\n * Users can specify either lowercase or uppercase form methods on ``,\n * useSubmit(), ``, etc.\n */\nexport type HTMLFormMethod = LowerCaseFormMethod | UpperCaseFormMethod;\n\n/**\n * Active navigation/fetcher form methods are exposed in lowercase on the\n * RouterState\n */\nexport type FormMethod = LowerCaseFormMethod;\nexport type MutationFormMethod = Exclude;\n\n/**\n * In v7, active navigation/fetcher form methods are exposed in uppercase on the\n * RouterState. This is to align with the normalization done via fetch().\n */\nexport type V7_FormMethod = UpperCaseFormMethod;\nexport type V7_MutationFormMethod = Exclude;\n\nexport type FormEncType =\n | \"application/x-www-form-urlencoded\"\n | \"multipart/form-data\"\n | \"application/json\"\n | \"text/plain\";\n\n// Thanks https://github.com/sindresorhus/type-fest!\ntype JsonObject = { [Key in string]: JsonValue } & {\n [Key in string]?: JsonValue | undefined;\n};\ntype JsonArray = JsonValue[] | readonly JsonValue[];\ntype JsonPrimitive = string | number | boolean | null;\ntype JsonValue = JsonPrimitive | JsonObject | JsonArray;\n\n/**\n * @private\n * Internal interface to pass around for action submissions, not intended for\n * external consumption\n */\nexport type Submission =\n | {\n formMethod: FormMethod | V7_FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: FormData;\n json: undefined;\n text: undefined;\n }\n | {\n formMethod: FormMethod | V7_FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: undefined;\n json: JsonValue;\n text: undefined;\n }\n | {\n formMethod: FormMethod | V7_FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: undefined;\n json: undefined;\n text: string;\n };\n\n/**\n * @private\n * Arguments passed to route loader/action functions. Same for now but we keep\n * this as a private implementation detail in case they diverge in the future.\n */\ninterface DataFunctionArgs {\n request: Request;\n params: Params;\n context?: Context;\n}\n\n// TODO: (v7) Change the defaults from any to unknown in and remove Remix wrappers:\n// ActionFunction, ActionFunctionArgs, LoaderFunction, LoaderFunctionArgs\n// Also, make them a type alias instead of an interface\n\n/**\n * Arguments passed to loader functions\n */\nexport interface LoaderFunctionArgs\n extends DataFunctionArgs {}\n\n/**\n * Arguments passed to action functions\n */\nexport interface ActionFunctionArgs\n extends DataFunctionArgs {}\n\n/**\n * Loaders and actions can return anything except `undefined` (`null` is a\n * valid return value if there is no data to return). Responses are preferred\n * and will ease any future migration to Remix\n */\ntype DataFunctionValue = Response | NonNullable | null;\n\ntype DataFunctionReturnValue = Promise | DataFunctionValue;\n\n/**\n * Route loader function signature\n */\nexport type LoaderFunction = {\n (\n args: LoaderFunctionArgs,\n handlerCtx?: unknown\n ): DataFunctionReturnValue;\n} & { hydrate?: boolean };\n\n/**\n * Route action function signature\n */\nexport interface ActionFunction {\n (\n args: ActionFunctionArgs,\n handlerCtx?: unknown\n ): DataFunctionReturnValue;\n}\n\n/**\n * Arguments passed to shouldRevalidate function\n */\nexport interface ShouldRevalidateFunctionArgs {\n currentUrl: URL;\n currentParams: AgnosticDataRouteMatch[\"params\"];\n nextUrl: URL;\n nextParams: AgnosticDataRouteMatch[\"params\"];\n formMethod?: Submission[\"formMethod\"];\n formAction?: Submission[\"formAction\"];\n formEncType?: Submission[\"formEncType\"];\n text?: Submission[\"text\"];\n formData?: Submission[\"formData\"];\n json?: Submission[\"json\"];\n actionStatus?: number;\n actionResult?: any;\n defaultShouldRevalidate: boolean;\n}\n\n/**\n * Route shouldRevalidate function signature. This runs after any submission\n * (navigation or fetcher), so we flatten the navigation/fetcher submission\n * onto the arguments. It shouldn't matter whether it came from a navigation\n * or a fetcher, what really matters is the URLs and the formData since loaders\n * have to re-run based on the data models that were potentially mutated.\n */\nexport interface ShouldRevalidateFunction {\n (args: ShouldRevalidateFunctionArgs): boolean;\n}\n\n/**\n * Function provided by the framework-aware layers to set `hasErrorBoundary`\n * from the framework-aware `errorElement` prop\n *\n * @deprecated Use `mapRouteProperties` instead\n */\nexport interface DetectErrorBoundaryFunction {\n (route: AgnosticRouteObject): boolean;\n}\n\nexport interface DataStrategyMatch\n extends AgnosticRouteMatch {\n shouldLoad: boolean;\n resolve: (\n handlerOverride?: (\n handler: (ctx?: unknown) => DataFunctionReturnValue\n ) => DataFunctionReturnValue\n ) => Promise;\n}\n\nexport interface DataStrategyFunctionArgs\n extends DataFunctionArgs {\n matches: DataStrategyMatch[];\n fetcherKey: string | null;\n}\n\n/**\n * Result from a loader or action called via dataStrategy\n */\nexport interface DataStrategyResult {\n type: \"data\" | \"error\";\n result: unknown; // data, Error, Response, DeferredData, DataWithResponseInit\n}\n\nexport interface DataStrategyFunction {\n (args: DataStrategyFunctionArgs): Promise>;\n}\n\nexport type AgnosticPatchRoutesOnNavigationFunctionArgs<\n O extends AgnosticRouteObject = AgnosticRouteObject,\n M extends AgnosticRouteMatch = AgnosticRouteMatch\n> = {\n signal: AbortSignal;\n path: string;\n matches: M[];\n fetcherKey: string | undefined;\n patch: (routeId: string | null, children: O[]) => void;\n};\n\nexport type AgnosticPatchRoutesOnNavigationFunction<\n O extends AgnosticRouteObject = AgnosticRouteObject,\n M extends AgnosticRouteMatch = AgnosticRouteMatch\n> = (\n opts: AgnosticPatchRoutesOnNavigationFunctionArgs\n) => void | Promise;\n\n/**\n * Function provided by the framework-aware layers to set any framework-specific\n * properties from framework-agnostic properties\n */\nexport interface MapRoutePropertiesFunction {\n (route: AgnosticRouteObject): {\n hasErrorBoundary: boolean;\n } & Record;\n}\n\n/**\n * Keys we cannot change from within a lazy() function. We spread all other keys\n * onto the route. Either they're meaningful to the router, or they'll get\n * ignored.\n */\nexport type ImmutableRouteKey =\n | \"lazy\"\n | \"caseSensitive\"\n | \"path\"\n | \"id\"\n | \"index\"\n | \"children\";\n\nexport const immutableRouteKeys = new Set([\n \"lazy\",\n \"caseSensitive\",\n \"path\",\n \"id\",\n \"index\",\n \"children\",\n]);\n\ntype RequireOne = Exclude<\n {\n [K in keyof T]: K extends Key ? Omit & Required> : never;\n }[keyof T],\n undefined\n>;\n\n/**\n * lazy() function to load a route definition, which can add non-matching\n * related properties to a route\n */\nexport interface LazyRouteFunction {\n (): Promise>>;\n}\n\n/**\n * Base RouteObject with common props shared by all types of routes\n */\ntype AgnosticBaseRouteObject = {\n caseSensitive?: boolean;\n path?: string;\n id?: string;\n loader?: LoaderFunction | boolean;\n action?: ActionFunction | boolean;\n hasErrorBoundary?: boolean;\n shouldRevalidate?: ShouldRevalidateFunction;\n handle?: any;\n lazy?: LazyRouteFunction;\n};\n\n/**\n * Index routes must not have children\n */\nexport type AgnosticIndexRouteObject = AgnosticBaseRouteObject & {\n children?: undefined;\n index: true;\n};\n\n/**\n * Non-index routes may have children, but cannot have index\n */\nexport type AgnosticNonIndexRouteObject = AgnosticBaseRouteObject & {\n children?: AgnosticRouteObject[];\n index?: false;\n};\n\n/**\n * A route object represents a logical route, with (optionally) its child\n * routes organized in a tree-like structure.\n */\nexport type AgnosticRouteObject =\n | AgnosticIndexRouteObject\n | AgnosticNonIndexRouteObject;\n\nexport type AgnosticDataIndexRouteObject = AgnosticIndexRouteObject & {\n id: string;\n};\n\nexport type AgnosticDataNonIndexRouteObject = AgnosticNonIndexRouteObject & {\n children?: AgnosticDataRouteObject[];\n id: string;\n};\n\n/**\n * A data route object, which is just a RouteObject with a required unique ID\n */\nexport type AgnosticDataRouteObject =\n | AgnosticDataIndexRouteObject\n | AgnosticDataNonIndexRouteObject;\n\nexport type RouteManifest = Record;\n\n// Recursive helper for finding path parameters in the absence of wildcards\ntype _PathParam =\n // split path into individual path segments\n Path extends `${infer L}/${infer R}`\n ? _PathParam | _PathParam\n : // find params after `:`\n Path extends `:${infer Param}`\n ? Param extends `${infer Optional}?`\n ? Optional\n : Param\n : // otherwise, there aren't any params present\n never;\n\n/**\n * Examples:\n * \"/a/b/*\" -> \"*\"\n * \":a\" -> \"a\"\n * \"/a/:b\" -> \"b\"\n * \"/a/blahblahblah:b\" -> \"b\"\n * \"/:a/:b\" -> \"a\" | \"b\"\n * \"/:a/b/:c/*\" -> \"a\" | \"c\" | \"*\"\n */\nexport type PathParam =\n // check if path is just a wildcard\n Path extends \"*\" | \"/*\"\n ? \"*\"\n : // look for wildcard at the end of the path\n Path extends `${infer Rest}/*`\n ? \"*\" | _PathParam\n : // look for params in the absence of wildcards\n _PathParam;\n\n// Attempt to parse the given string segment. If it fails, then just return the\n// plain string type as a default fallback. Otherwise, return the union of the\n// parsed string literals that were referenced as dynamic segments in the route.\nexport type ParamParseKey =\n // if you could not find path params, fallback to `string`\n [PathParam] extends [never] ? string : PathParam;\n\n/**\n * The parameters that were parsed from the URL path.\n */\nexport type Params = {\n readonly [key in Key]: string | undefined;\n};\n\n/**\n * A RouteMatch contains info about how a route matched a URL.\n */\nexport interface AgnosticRouteMatch<\n ParamKey extends string = string,\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n /**\n * The names and values of dynamic parameters in the URL.\n */\n params: Params;\n /**\n * The portion of the URL pathname that was matched.\n */\n pathname: string;\n /**\n * The portion of the URL pathname that was matched before child routes.\n */\n pathnameBase: string;\n /**\n * The route object that was used to match.\n */\n route: RouteObjectType;\n}\n\nexport interface AgnosticDataRouteMatch\n extends AgnosticRouteMatch {}\n\nfunction isIndexRoute(\n route: AgnosticRouteObject\n): route is AgnosticIndexRouteObject {\n return route.index === true;\n}\n\n// Walk the route tree generating unique IDs where necessary, so we are working\n// solely with AgnosticDataRouteObject's within the Router\nexport function convertRoutesToDataRoutes(\n routes: AgnosticRouteObject[],\n mapRouteProperties: MapRoutePropertiesFunction,\n parentPath: string[] = [],\n manifest: RouteManifest = {}\n): AgnosticDataRouteObject[] {\n return routes.map((route, index) => {\n let treePath = [...parentPath, String(index)];\n let id = typeof route.id === \"string\" ? route.id : treePath.join(\"-\");\n invariant(\n route.index !== true || !route.children,\n `Cannot specify children on an index route`\n );\n invariant(\n !manifest[id],\n `Found a route id collision on id \"${id}\". Route ` +\n \"id's must be globally unique within Data Router usages\"\n );\n\n if (isIndexRoute(route)) {\n let indexRoute: AgnosticDataIndexRouteObject = {\n ...route,\n ...mapRouteProperties(route),\n id,\n };\n manifest[id] = indexRoute;\n return indexRoute;\n } else {\n let pathOrLayoutRoute: AgnosticDataNonIndexRouteObject = {\n ...route,\n ...mapRouteProperties(route),\n id,\n children: undefined,\n };\n manifest[id] = pathOrLayoutRoute;\n\n if (route.children) {\n pathOrLayoutRoute.children = convertRoutesToDataRoutes(\n route.children,\n mapRouteProperties,\n treePath,\n manifest\n );\n }\n\n return pathOrLayoutRoute;\n }\n });\n}\n\n/**\n * Matches the given routes to a location and returns the match data.\n *\n * @see https://reactrouter.com/v6/utils/match-routes\n */\nexport function matchRoutes<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n routes: RouteObjectType[],\n locationArg: Partial | string,\n basename = \"/\"\n): AgnosticRouteMatch[] | null {\n return matchRoutesImpl(routes, locationArg, basename, false);\n}\n\nexport function matchRoutesImpl<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n routes: RouteObjectType[],\n locationArg: Partial | string,\n basename: string,\n allowPartial: boolean\n): AgnosticRouteMatch[] | null {\n let location =\n typeof locationArg === \"string\" ? parsePath(locationArg) : locationArg;\n\n let pathname = stripBasename(location.pathname || \"/\", basename);\n\n if (pathname == null) {\n return null;\n }\n\n let branches = flattenRoutes(routes);\n rankRouteBranches(branches);\n\n let matches = null;\n let decoded = decodePath(pathname);\n for (let i = 0; matches == null && i < branches.length; ++i) {\n // Incoming pathnames are generally encoded from either window.location\n // or from router.navigate, but we want to match against the unencoded\n // paths in the route definitions. Memory router locations won't be\n // encoded here but there also shouldn't be anything to decode so this\n // should be a safe operation. This avoids needing matchRoutes to be\n // history-aware.\n matches = matchRouteBranch(\n branches[i],\n decoded,\n allowPartial\n );\n }\n\n return matches;\n}\n\nexport interface UIMatch {\n id: string;\n pathname: string;\n params: AgnosticRouteMatch[\"params\"];\n data: Data;\n handle: Handle;\n}\n\nexport function convertRouteMatchToUiMatch(\n match: AgnosticDataRouteMatch,\n loaderData: RouteData\n): UIMatch {\n let { route, pathname, params } = match;\n return {\n id: route.id,\n pathname,\n params,\n data: loaderData[route.id],\n handle: route.handle,\n };\n}\n\ninterface RouteMeta<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n relativePath: string;\n caseSensitive: boolean;\n childrenIndex: number;\n route: RouteObjectType;\n}\n\ninterface RouteBranch<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n path: string;\n score: number;\n routesMeta: RouteMeta[];\n}\n\nfunction flattenRoutes<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n routes: RouteObjectType[],\n branches: RouteBranch[] = [],\n parentsMeta: RouteMeta[] = [],\n parentPath = \"\"\n): RouteBranch[] {\n let flattenRoute = (\n route: RouteObjectType,\n index: number,\n relativePath?: string\n ) => {\n let meta: RouteMeta = {\n relativePath:\n relativePath === undefined ? route.path || \"\" : relativePath,\n caseSensitive: route.caseSensitive === true,\n childrenIndex: index,\n route,\n };\n\n if (meta.relativePath.startsWith(\"/\")) {\n invariant(\n meta.relativePath.startsWith(parentPath),\n `Absolute route path \"${meta.relativePath}\" nested under path ` +\n `\"${parentPath}\" is not valid. An absolute child route path ` +\n `must start with the combined path of all its parent routes.`\n );\n\n meta.relativePath = meta.relativePath.slice(parentPath.length);\n }\n\n let path = joinPaths([parentPath, meta.relativePath]);\n let routesMeta = parentsMeta.concat(meta);\n\n // Add the children before adding this route to the array, so we traverse the\n // route tree depth-first and child routes appear before their parents in\n // the \"flattened\" version.\n if (route.children && route.children.length > 0) {\n invariant(\n // Our types know better, but runtime JS may not!\n // @ts-expect-error\n route.index !== true,\n `Index routes must not have child routes. Please remove ` +\n `all child routes from route path \"${path}\".`\n );\n flattenRoutes(route.children, branches, routesMeta, path);\n }\n\n // Routes without a path shouldn't ever match by themselves unless they are\n // index routes, so don't add them to the list of possible branches.\n if (route.path == null && !route.index) {\n return;\n }\n\n branches.push({\n path,\n score: computeScore(path, route.index),\n routesMeta,\n });\n };\n routes.forEach((route, index) => {\n // coarse-grain check for optional params\n if (route.path === \"\" || !route.path?.includes(\"?\")) {\n flattenRoute(route, index);\n } else {\n for (let exploded of explodeOptionalSegments(route.path)) {\n flattenRoute(route, index, exploded);\n }\n }\n });\n\n return branches;\n}\n\n/**\n * Computes all combinations of optional path segments for a given path,\n * excluding combinations that are ambiguous and of lower priority.\n *\n * For example, `/one/:two?/three/:four?/:five?` explodes to:\n * - `/one/three`\n * - `/one/:two/three`\n * - `/one/three/:four`\n * - `/one/three/:five`\n * - `/one/:two/three/:four`\n * - `/one/:two/three/:five`\n * - `/one/three/:four/:five`\n * - `/one/:two/three/:four/:five`\n */\nfunction explodeOptionalSegments(path: string): string[] {\n let segments = path.split(\"/\");\n if (segments.length === 0) return [];\n\n let [first, ...rest] = segments;\n\n // Optional path segments are denoted by a trailing `?`\n let isOptional = first.endsWith(\"?\");\n // Compute the corresponding required segment: `foo?` -> `foo`\n let required = first.replace(/\\?$/, \"\");\n\n if (rest.length === 0) {\n // Intepret empty string as omitting an optional segment\n // `[\"one\", \"\", \"three\"]` corresponds to omitting `:two` from `/one/:two?/three` -> `/one/three`\n return isOptional ? [required, \"\"] : [required];\n }\n\n let restExploded = explodeOptionalSegments(rest.join(\"/\"));\n\n let result: string[] = [];\n\n // All child paths with the prefix. Do this for all children before the\n // optional version for all children, so we get consistent ordering where the\n // parent optional aspect is preferred as required. Otherwise, we can get\n // child sections interspersed where deeper optional segments are higher than\n // parent optional segments, where for example, /:two would explode _earlier_\n // then /:one. By always including the parent as required _for all children_\n // first, we avoid this issue\n result.push(\n ...restExploded.map((subpath) =>\n subpath === \"\" ? required : [required, subpath].join(\"/\")\n )\n );\n\n // Then, if this is an optional value, add all child versions without\n if (isOptional) {\n result.push(...restExploded);\n }\n\n // for absolute paths, ensure `/` instead of empty segment\n return result.map((exploded) =>\n path.startsWith(\"/\") && exploded === \"\" ? \"/\" : exploded\n );\n}\n\nfunction rankRouteBranches(branches: RouteBranch[]): void {\n branches.sort((a, b) =>\n a.score !== b.score\n ? b.score - a.score // Higher score first\n : compareIndexes(\n a.routesMeta.map((meta) => meta.childrenIndex),\n b.routesMeta.map((meta) => meta.childrenIndex)\n )\n );\n}\n\nconst paramRe = /^:[\\w-]+$/;\nconst dynamicSegmentValue = 3;\nconst indexRouteValue = 2;\nconst emptySegmentValue = 1;\nconst staticSegmentValue = 10;\nconst splatPenalty = -2;\nconst isSplat = (s: string) => s === \"*\";\n\nfunction computeScore(path: string, index: boolean | undefined): number {\n let segments = path.split(\"/\");\n let initialScore = segments.length;\n if (segments.some(isSplat)) {\n initialScore += splatPenalty;\n }\n\n if (index) {\n initialScore += indexRouteValue;\n }\n\n return segments\n .filter((s) => !isSplat(s))\n .reduce(\n (score, segment) =>\n score +\n (paramRe.test(segment)\n ? dynamicSegmentValue\n : segment === \"\"\n ? emptySegmentValue\n : staticSegmentValue),\n initialScore\n );\n}\n\nfunction compareIndexes(a: number[], b: number[]): number {\n let siblings =\n a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]);\n\n return siblings\n ? // If two routes are siblings, we should try to match the earlier sibling\n // first. This allows people to have fine-grained control over the matching\n // behavior by simply putting routes with identical paths in the order they\n // want them tried.\n a[a.length - 1] - b[b.length - 1]\n : // Otherwise, it doesn't really make sense to rank non-siblings by index,\n // so they sort equally.\n 0;\n}\n\nfunction matchRouteBranch<\n ParamKey extends string = string,\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n branch: RouteBranch,\n pathname: string,\n allowPartial = false\n): AgnosticRouteMatch[] | null {\n let { routesMeta } = branch;\n\n let matchedParams = {};\n let matchedPathname = \"/\";\n let matches: AgnosticRouteMatch[] = [];\n for (let i = 0; i < routesMeta.length; ++i) {\n let meta = routesMeta[i];\n let end = i === routesMeta.length - 1;\n let remainingPathname =\n matchedPathname === \"/\"\n ? pathname\n : pathname.slice(matchedPathname.length) || \"/\";\n let match = matchPath(\n { path: meta.relativePath, caseSensitive: meta.caseSensitive, end },\n remainingPathname\n );\n\n let route = meta.route;\n\n if (\n !match &&\n end &&\n allowPartial &&\n !routesMeta[routesMeta.length - 1].route.index\n ) {\n match = matchPath(\n {\n path: meta.relativePath,\n caseSensitive: meta.caseSensitive,\n end: false,\n },\n remainingPathname\n );\n }\n\n if (!match) {\n return null;\n }\n\n Object.assign(matchedParams, match.params);\n\n matches.push({\n // TODO: Can this as be avoided?\n params: matchedParams as Params,\n pathname: joinPaths([matchedPathname, match.pathname]),\n pathnameBase: normalizePathname(\n joinPaths([matchedPathname, match.pathnameBase])\n ),\n route,\n });\n\n if (match.pathnameBase !== \"/\") {\n matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);\n }\n }\n\n return matches;\n}\n\n/**\n * Returns a path with params interpolated.\n *\n * @see https://reactrouter.com/v6/utils/generate-path\n */\nexport function generatePath(\n originalPath: Path,\n params: {\n [key in PathParam]: string | null;\n } = {} as any\n): string {\n let path: string = originalPath;\n if (path.endsWith(\"*\") && path !== \"*\" && !path.endsWith(\"/*\")) {\n warning(\n false,\n `Route path \"${path}\" will be treated as if it were ` +\n `\"${path.replace(/\\*$/, \"/*\")}\" because the \\`*\\` character must ` +\n `always follow a \\`/\\` in the pattern. To get rid of this warning, ` +\n `please change the route path to \"${path.replace(/\\*$/, \"/*\")}\".`\n );\n path = path.replace(/\\*$/, \"/*\") as Path;\n }\n\n // ensure `/` is added at the beginning if the path is absolute\n const prefix = path.startsWith(\"/\") ? \"/\" : \"\";\n\n const stringify = (p: any) =>\n p == null ? \"\" : typeof p === \"string\" ? p : String(p);\n\n const segments = path\n .split(/\\/+/)\n .map((segment, index, array) => {\n const isLastSegment = index === array.length - 1;\n\n // only apply the splat if it's the last segment\n if (isLastSegment && segment === \"*\") {\n const star = \"*\" as PathParam;\n // Apply the splat\n return stringify(params[star]);\n }\n\n const keyMatch = segment.match(/^:([\\w-]+)(\\??)$/);\n if (keyMatch) {\n const [, key, optional] = keyMatch;\n let param = params[key as PathParam];\n invariant(optional === \"?\" || param != null, `Missing \":${key}\" param`);\n return stringify(param);\n }\n\n // Remove any optional markers from optional static segments\n return segment.replace(/\\?$/g, \"\");\n })\n // Remove empty segments\n .filter((segment) => !!segment);\n\n return prefix + segments.join(\"/\");\n}\n\n/**\n * A PathPattern is used to match on some portion of a URL pathname.\n */\nexport interface PathPattern {\n /**\n * A string to match against a URL pathname. May contain `:id`-style segments\n * to indicate placeholders for dynamic parameters. May also end with `/*` to\n * indicate matching the rest of the URL pathname.\n */\n path: Path;\n /**\n * Should be `true` if the static portions of the `path` should be matched in\n * the same case.\n */\n caseSensitive?: boolean;\n /**\n * Should be `true` if this pattern should match the entire URL pathname.\n */\n end?: boolean;\n}\n\n/**\n * A PathMatch contains info about how a PathPattern matched on a URL pathname.\n */\nexport interface PathMatch {\n /**\n * The names and values of dynamic parameters in the URL.\n */\n params: Params;\n /**\n * The portion of the URL pathname that was matched.\n */\n pathname: string;\n /**\n * The portion of the URL pathname that was matched before child routes.\n */\n pathnameBase: string;\n /**\n * The pattern that was used to match.\n */\n pattern: PathPattern;\n}\n\ntype Mutable = {\n -readonly [P in keyof T]: T[P];\n};\n\n/**\n * Performs pattern matching on a URL pathname and returns information about\n * the match.\n *\n * @see https://reactrouter.com/v6/utils/match-path\n */\nexport function matchPath<\n ParamKey extends ParamParseKey,\n Path extends string\n>(\n pattern: PathPattern | Path,\n pathname: string\n): PathMatch | null {\n if (typeof pattern === \"string\") {\n pattern = { path: pattern, caseSensitive: false, end: true };\n }\n\n let [matcher, compiledParams] = compilePath(\n pattern.path,\n pattern.caseSensitive,\n pattern.end\n );\n\n let match = pathname.match(matcher);\n if (!match) return null;\n\n let matchedPathname = match[0];\n let pathnameBase = matchedPathname.replace(/(.)\\/+$/, \"$1\");\n let captureGroups = match.slice(1);\n let params: Params = compiledParams.reduce>(\n (memo, { paramName, isOptional }, index) => {\n // We need to compute the pathnameBase here using the raw splat value\n // instead of using params[\"*\"] later because it will be decoded then\n if (paramName === \"*\") {\n let splatValue = captureGroups[index] || \"\";\n pathnameBase = matchedPathname\n .slice(0, matchedPathname.length - splatValue.length)\n .replace(/(.)\\/+$/, \"$1\");\n }\n\n const value = captureGroups[index];\n if (isOptional && !value) {\n memo[paramName] = undefined;\n } else {\n memo[paramName] = (value || \"\").replace(/%2F/g, \"/\");\n }\n return memo;\n },\n {}\n );\n\n return {\n params,\n pathname: matchedPathname,\n pathnameBase,\n pattern,\n };\n}\n\ntype CompiledPathParam = { paramName: string; isOptional?: boolean };\n\nfunction compilePath(\n path: string,\n caseSensitive = false,\n end = true\n): [RegExp, CompiledPathParam[]] {\n warning(\n path === \"*\" || !path.endsWith(\"*\") || path.endsWith(\"/*\"),\n `Route path \"${path}\" will be treated as if it were ` +\n `\"${path.replace(/\\*$/, \"/*\")}\" because the \\`*\\` character must ` +\n `always follow a \\`/\\` in the pattern. To get rid of this warning, ` +\n `please change the route path to \"${path.replace(/\\*$/, \"/*\")}\".`\n );\n\n let params: CompiledPathParam[] = [];\n let regexpSource =\n \"^\" +\n path\n .replace(/\\/*\\*?$/, \"\") // Ignore trailing / and /*, we'll handle it below\n .replace(/^\\/*/, \"/\") // Make sure it has a leading /\n .replace(/[\\\\.*+^${}|()[\\]]/g, \"\\\\$&\") // Escape special regex chars\n .replace(\n /\\/:([\\w-]+)(\\?)?/g,\n (_: string, paramName: string, isOptional) => {\n params.push({ paramName, isOptional: isOptional != null });\n return isOptional ? \"/?([^\\\\/]+)?\" : \"/([^\\\\/]+)\";\n }\n );\n\n if (path.endsWith(\"*\")) {\n params.push({ paramName: \"*\" });\n regexpSource +=\n path === \"*\" || path === \"/*\"\n ? \"(.*)$\" // Already matched the initial /, just match the rest\n : \"(?:\\\\/(.+)|\\\\/*)$\"; // Don't include the / in params[\"*\"]\n } else if (end) {\n // When matching to the end, ignore trailing slashes\n regexpSource += \"\\\\/*$\";\n } else if (path !== \"\" && path !== \"/\") {\n // If our path is non-empty and contains anything beyond an initial slash,\n // then we have _some_ form of path in our regex, so we should expect to\n // match only if we find the end of this path segment. Look for an optional\n // non-captured trailing slash (to match a portion of the URL) or the end\n // of the path (if we've matched to the end). We used to do this with a\n // word boundary but that gives false positives on routes like\n // /user-preferences since `-` counts as a word boundary.\n regexpSource += \"(?:(?=\\\\/|$))\";\n } else {\n // Nothing to match for \"\" or \"/\"\n }\n\n let matcher = new RegExp(regexpSource, caseSensitive ? undefined : \"i\");\n\n return [matcher, params];\n}\n\nexport function decodePath(value: string) {\n try {\n return value\n .split(\"/\")\n .map((v) => decodeURIComponent(v).replace(/\\//g, \"%2F\"))\n .join(\"/\");\n } catch (error) {\n warning(\n false,\n `The URL path \"${value}\" could not be decoded because it is is a ` +\n `malformed URL segment. This is probably due to a bad percent ` +\n `encoding (${error}).`\n );\n\n return value;\n }\n}\n\n/**\n * @private\n */\nexport function stripBasename(\n pathname: string,\n basename: string\n): string | null {\n if (basename === \"/\") return pathname;\n\n if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {\n return null;\n }\n\n // We want to leave trailing slash behavior in the user's control, so if they\n // specify a basename with a trailing slash, we should support it\n let startIndex = basename.endsWith(\"/\")\n ? basename.length - 1\n : basename.length;\n let nextChar = pathname.charAt(startIndex);\n if (nextChar && nextChar !== \"/\") {\n // pathname does not start with basename/\n return null;\n }\n\n return pathname.slice(startIndex) || \"/\";\n}\n\nconst ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i;\nexport const isAbsoluteUrl = (url: string) => ABSOLUTE_URL_REGEX.test(url);\n\n/**\n * Returns a resolved path object relative to the given pathname.\n *\n * @see https://reactrouter.com/v6/utils/resolve-path\n */\nexport function resolvePath(to: To, fromPathname = \"/\"): Path {\n let {\n pathname: toPathname,\n search = \"\",\n hash = \"\",\n } = typeof to === \"string\" ? parsePath(to) : to;\n\n let pathname: string;\n if (toPathname) {\n toPathname = removeDoubleSlashes(toPathname);\n if (toPathname.startsWith(\"/\")) {\n pathname = resolvePathname(toPathname.substring(1), \"/\");\n } else {\n pathname = resolvePathname(toPathname, fromPathname);\n }\n } else {\n pathname = fromPathname;\n }\n\n return {\n pathname,\n search: normalizeSearch(search),\n hash: normalizeHash(hash),\n };\n}\n\nfunction resolvePathname(relativePath: string, fromPathname: string): string {\n let segments = fromPathname.replace(/\\/+$/, \"\").split(\"/\");\n let relativeSegments = relativePath.split(\"/\");\n\n relativeSegments.forEach((segment) => {\n if (segment === \"..\") {\n // Keep the root \"\" segment so the pathname starts at /\n if (segments.length > 1) segments.pop();\n } else if (segment !== \".\") {\n segments.push(segment);\n }\n });\n\n return segments.length > 1 ? segments.join(\"/\") : \"/\";\n}\n\nfunction getInvalidPathError(\n char: string,\n field: string,\n dest: string,\n path: Partial\n) {\n return (\n `Cannot include a '${char}' character in a manually specified ` +\n `\\`to.${field}\\` field [${JSON.stringify(\n path\n )}]. Please separate it out to the ` +\n `\\`to.${dest}\\` field. Alternatively you may provide the full path as ` +\n `a string in and the router will parse it for you.`\n );\n}\n\n/**\n * @private\n *\n * When processing relative navigation we want to ignore ancestor routes that\n * do not contribute to the path, such that index/pathless layout routes don't\n * interfere.\n *\n * For example, when moving a route element into an index route and/or a\n * pathless layout route, relative link behavior contained within should stay\n * the same. Both of the following examples should link back to the root:\n *\n * \n * \n * \n *\n * \n * \n * }> // <-- Does not contribute\n * // <-- Does not contribute\n * \n * \n */\nexport function getPathContributingMatches<\n T extends AgnosticRouteMatch = AgnosticRouteMatch\n>(matches: T[]) {\n return matches.filter(\n (match, index) =>\n index === 0 || (match.route.path && match.route.path.length > 0)\n );\n}\n\n// Return the array of pathnames for the current route matches - used to\n// generate the routePathnames input for resolveTo()\nexport function getResolveToMatches<\n T extends AgnosticRouteMatch = AgnosticRouteMatch\n>(matches: T[], v7_relativeSplatPath: boolean) {\n let pathMatches = getPathContributingMatches(matches);\n\n // When v7_relativeSplatPath is enabled, use the full pathname for the leaf\n // match so we include splat values for \".\" links. See:\n // https://github.com/remix-run/react-router/issues/11052#issuecomment-1836589329\n if (v7_relativeSplatPath) {\n return pathMatches.map((match, idx) =>\n idx === pathMatches.length - 1 ? match.pathname : match.pathnameBase\n );\n }\n\n return pathMatches.map((match) => match.pathnameBase);\n}\n\n/**\n * @private\n */\nexport function resolveTo(\n toArg: To,\n routePathnames: string[],\n locationPathname: string,\n isPathRelative = false\n): Path {\n let to: Partial;\n if (typeof toArg === \"string\") {\n to = parsePath(toArg);\n } else {\n to = { ...toArg };\n\n invariant(\n !to.pathname || !to.pathname.includes(\"?\"),\n getInvalidPathError(\"?\", \"pathname\", \"search\", to)\n );\n invariant(\n !to.pathname || !to.pathname.includes(\"#\"),\n getInvalidPathError(\"#\", \"pathname\", \"hash\", to)\n );\n invariant(\n !to.search || !to.search.includes(\"#\"),\n getInvalidPathError(\"#\", \"search\", \"hash\", to)\n );\n }\n\n let isEmptyPath = toArg === \"\" || to.pathname === \"\";\n let toPathname = isEmptyPath ? \"/\" : to.pathname;\n\n let from: string;\n\n // Routing is relative to the current pathname if explicitly requested.\n //\n // If a pathname is explicitly provided in `to`, it should be relative to the\n // route context. This is explained in `Note on `` values` in our\n // migration guide from v5 as a means of disambiguation between `to` values\n // that begin with `/` and those that do not. However, this is problematic for\n // `to` values that do not provide a pathname. `to` can simply be a search or\n // hash string, in which case we should assume that the navigation is relative\n // to the current location's pathname and *not* the route pathname.\n if (toPathname == null) {\n from = locationPathname;\n } else {\n let routePathnameIndex = routePathnames.length - 1;\n\n // With relative=\"route\" (the default), each leading .. segment means\n // \"go up one route\" instead of \"go up one URL segment\". This is a key\n // difference from how works and a major reason we call this a\n // \"to\" value instead of a \"href\".\n if (!isPathRelative && toPathname.startsWith(\"..\")) {\n let toSegments = toPathname.split(\"/\");\n\n while (toSegments[0] === \"..\") {\n toSegments.shift();\n routePathnameIndex -= 1;\n }\n\n to.pathname = toSegments.join(\"/\");\n }\n\n from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : \"/\";\n }\n\n let path = resolvePath(to, from);\n\n // Ensure the pathname has a trailing slash if the original \"to\" had one\n let hasExplicitTrailingSlash =\n toPathname && toPathname !== \"/\" && toPathname.endsWith(\"/\");\n // Or if this was a link to the current path which has a trailing slash\n let hasCurrentTrailingSlash =\n (isEmptyPath || toPathname === \".\") && locationPathname.endsWith(\"/\");\n if (\n !path.pathname.endsWith(\"/\") &&\n (hasExplicitTrailingSlash || hasCurrentTrailingSlash)\n ) {\n path.pathname += \"/\";\n }\n\n return path;\n}\n\n/**\n * @private\n */\nexport function getToPathname(to: To): string | undefined {\n // Empty strings should be treated the same as / paths\n return to === \"\" || (to as Path).pathname === \"\"\n ? \"/\"\n : typeof to === \"string\"\n ? parsePath(to).pathname\n : to.pathname;\n}\n\nexport const removeDoubleSlashes = (path: string): string =>\n path.replace(/\\/\\/+/g, \"/\");\n\n/**\n * @private\n */\nexport const joinPaths = (paths: string[]): string =>\n removeDoubleSlashes(paths.join(\"/\"));\n\n/**\n * @private\n */\nexport const normalizePathname = (pathname: string): string =>\n pathname.replace(/\\/+$/, \"\").replace(/^\\/*/, \"/\");\n\n/**\n * @private\n */\nexport const normalizeSearch = (search: string): string =>\n !search || search === \"?\"\n ? \"\"\n : search.startsWith(\"?\")\n ? search\n : \"?\" + search;\n\n/**\n * @private\n */\nexport const normalizeHash = (hash: string): string =>\n !hash || hash === \"#\" ? \"\" : hash.startsWith(\"#\") ? hash : \"#\" + hash;\n\nexport type JsonFunction = (\n data: Data,\n init?: number | ResponseInit\n) => Response;\n\n/**\n * This is a shortcut for creating `application/json` responses. Converts `data`\n * to JSON and sets the `Content-Type` header.\n *\n * @deprecated The `json` method is deprecated in favor of returning raw objects.\n * This method will be removed in v7.\n */\nexport const json: JsonFunction = (data, init = {}) => {\n let responseInit = typeof init === \"number\" ? { status: init } : init;\n\n let headers = new Headers(responseInit.headers);\n if (!headers.has(\"Content-Type\")) {\n headers.set(\"Content-Type\", \"application/json; charset=utf-8\");\n }\n\n return new Response(JSON.stringify(data), {\n ...responseInit,\n headers,\n });\n};\n\nexport class DataWithResponseInit {\n type: string = \"DataWithResponseInit\";\n data: D;\n init: ResponseInit | null;\n\n constructor(data: D, init?: ResponseInit) {\n this.data = data;\n this.init = init || null;\n }\n}\n\n/**\n * Create \"responses\" that contain `status`/`headers` without forcing\n * serialization into an actual `Response` - used by Remix single fetch\n */\nexport function data(data: D, init?: number | ResponseInit) {\n return new DataWithResponseInit(\n data,\n typeof init === \"number\" ? { status: init } : init\n );\n}\n\nexport interface TrackedPromise extends Promise {\n _tracked?: boolean;\n _data?: any;\n _error?: any;\n}\n\nexport class AbortedDeferredError extends Error {}\n\nexport class DeferredData {\n private pendingKeysSet: Set = new Set();\n private controller: AbortController;\n private abortPromise: Promise;\n private unlistenAbortSignal: () => void;\n private subscribers: Set<(aborted: boolean, settledKey?: string) => void> =\n new Set();\n data: Record;\n init?: ResponseInit;\n deferredKeys: string[] = [];\n\n constructor(data: Record, responseInit?: ResponseInit) {\n invariant(\n data && typeof data === \"object\" && !Array.isArray(data),\n \"defer() only accepts plain objects\"\n );\n\n // Set up an AbortController + Promise we can race against to exit early\n // cancellation\n let reject: (e: AbortedDeferredError) => void;\n this.abortPromise = new Promise((_, r) => (reject = r));\n this.controller = new AbortController();\n let onAbort = () =>\n reject(new AbortedDeferredError(\"Deferred data aborted\"));\n this.unlistenAbortSignal = () =>\n this.controller.signal.removeEventListener(\"abort\", onAbort);\n this.controller.signal.addEventListener(\"abort\", onAbort);\n\n this.data = Object.entries(data).reduce(\n (acc, [key, value]) =>\n Object.assign(acc, {\n [key]: this.trackPromise(key, value),\n }),\n {}\n );\n\n if (this.done) {\n // All incoming values were resolved\n this.unlistenAbortSignal();\n }\n\n this.init = responseInit;\n }\n\n private trackPromise(\n key: string,\n value: Promise | unknown\n ): TrackedPromise | unknown {\n if (!(value instanceof Promise)) {\n return value;\n }\n\n this.deferredKeys.push(key);\n this.pendingKeysSet.add(key);\n\n // We store a little wrapper promise that will be extended with\n // _data/_error props upon resolve/reject\n let promise: TrackedPromise = Promise.race([value, this.abortPromise]).then(\n (data) => this.onSettle(promise, key, undefined, data as unknown),\n (error) => this.onSettle(promise, key, error as unknown)\n );\n\n // Register rejection listeners to avoid uncaught promise rejections on\n // errors or aborted deferred values\n promise.catch(() => {});\n\n Object.defineProperty(promise, \"_tracked\", { get: () => true });\n return promise;\n }\n\n private onSettle(\n promise: TrackedPromise,\n key: string,\n error: unknown,\n data?: unknown\n ): unknown {\n if (\n this.controller.signal.aborted &&\n error instanceof AbortedDeferredError\n ) {\n this.unlistenAbortSignal();\n Object.defineProperty(promise, \"_error\", { get: () => error });\n return Promise.reject(error);\n }\n\n this.pendingKeysSet.delete(key);\n\n if (this.done) {\n // Nothing left to abort!\n this.unlistenAbortSignal();\n }\n\n // If the promise was resolved/rejected with undefined, we'll throw an error as you\n // should always resolve with a value or null\n if (error === undefined && data === undefined) {\n let undefinedError = new Error(\n `Deferred data for key \"${key}\" resolved/rejected with \\`undefined\\`, ` +\n `you must resolve/reject with a value or \\`null\\`.`\n );\n Object.defineProperty(promise, \"_error\", { get: () => undefinedError });\n this.emit(false, key);\n return Promise.reject(undefinedError);\n }\n\n if (data === undefined) {\n Object.defineProperty(promise, \"_error\", { get: () => error });\n this.emit(false, key);\n return Promise.reject(error);\n }\n\n Object.defineProperty(promise, \"_data\", { get: () => data });\n this.emit(false, key);\n return data;\n }\n\n private emit(aborted: boolean, settledKey?: string) {\n this.subscribers.forEach((subscriber) => subscriber(aborted, settledKey));\n }\n\n subscribe(fn: (aborted: boolean, settledKey?: string) => void) {\n this.subscribers.add(fn);\n return () => this.subscribers.delete(fn);\n }\n\n cancel() {\n this.controller.abort();\n this.pendingKeysSet.forEach((v, k) => this.pendingKeysSet.delete(k));\n this.emit(true);\n }\n\n async resolveData(signal: AbortSignal) {\n let aborted = false;\n if (!this.done) {\n let onAbort = () => this.cancel();\n signal.addEventListener(\"abort\", onAbort);\n aborted = await new Promise((resolve) => {\n this.subscribe((aborted) => {\n signal.removeEventListener(\"abort\", onAbort);\n if (aborted || this.done) {\n resolve(aborted);\n }\n });\n });\n }\n return aborted;\n }\n\n get done() {\n return this.pendingKeysSet.size === 0;\n }\n\n get unwrappedData() {\n invariant(\n this.data !== null && this.done,\n \"Can only unwrap data on initialized and settled deferreds\"\n );\n\n return Object.entries(this.data).reduce(\n (acc, [key, value]) =>\n Object.assign(acc, {\n [key]: unwrapTrackedPromise(value),\n }),\n {}\n );\n }\n\n get pendingKeys() {\n return Array.from(this.pendingKeysSet);\n }\n}\n\nfunction isTrackedPromise(value: any): value is TrackedPromise {\n return (\n value instanceof Promise && (value as TrackedPromise)._tracked === true\n );\n}\n\nfunction unwrapTrackedPromise(value: any) {\n if (!isTrackedPromise(value)) {\n return value;\n }\n\n if (value._error) {\n throw value._error;\n }\n return value._data;\n}\n\nexport type DeferFunction = (\n data: Record,\n init?: number | ResponseInit\n) => DeferredData;\n\n/**\n * @deprecated The `defer` method is deprecated in favor of returning raw\n * objects. This method will be removed in v7.\n */\nexport const defer: DeferFunction = (data, init = {}) => {\n let responseInit = typeof init === \"number\" ? { status: init } : init;\n\n return new DeferredData(data, responseInit);\n};\n\nexport type RedirectFunction = (\n url: string,\n init?: number | ResponseInit\n) => Response;\n\n/**\n * A redirect response. Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nexport const redirect: RedirectFunction = (url, init = 302) => {\n let responseInit = init;\n if (typeof responseInit === \"number\") {\n responseInit = { status: responseInit };\n } else if (typeof responseInit.status === \"undefined\") {\n responseInit.status = 302;\n }\n\n let headers = new Headers(responseInit.headers);\n headers.set(\"Location\", url);\n\n return new Response(null, {\n ...responseInit,\n headers,\n });\n};\n\n/**\n * A redirect response that will force a document reload to the new location.\n * Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nexport const redirectDocument: RedirectFunction = (url, init) => {\n let response = redirect(url, init);\n response.headers.set(\"X-Remix-Reload-Document\", \"true\");\n return response;\n};\n\n/**\n * A redirect response that will perform a `history.replaceState` instead of a\n * `history.pushState` for client-side navigation redirects.\n * Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nexport const replace: RedirectFunction = (url, init) => {\n let response = redirect(url, init);\n response.headers.set(\"X-Remix-Replace\", \"true\");\n return response;\n};\n\nexport type ErrorResponse = {\n status: number;\n statusText: string;\n data: any;\n};\n\n/**\n * @private\n * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies\n *\n * We don't export the class for public use since it's an implementation\n * detail, but we export the interface above so folks can build their own\n * abstractions around instances via isRouteErrorResponse()\n */\nexport class ErrorResponseImpl implements ErrorResponse {\n status: number;\n statusText: string;\n data: any;\n private error?: Error;\n private internal: boolean;\n\n constructor(\n status: number,\n statusText: string | undefined,\n data: any,\n internal = false\n ) {\n this.status = status;\n this.statusText = statusText || \"\";\n this.internal = internal;\n if (data instanceof Error) {\n this.data = data.toString();\n this.error = data;\n } else {\n this.data = data;\n }\n }\n}\n\n/**\n * Check if the given error is an ErrorResponse generated from a 4xx/5xx\n * Response thrown from an action/loader\n */\nexport function isRouteErrorResponse(error: any): error is ErrorResponse {\n return (\n error != null &&\n typeof error.status === \"number\" &&\n typeof error.statusText === \"string\" &&\n typeof error.internal === \"boolean\" &&\n \"data\" in error\n );\n}\n","import type { History, Location, Path, To } from \"./history\";\nimport {\n Action as HistoryAction,\n createLocation,\n createPath,\n invariant,\n parsePath,\n warning,\n} from \"./history\";\nimport type {\n AgnosticDataRouteMatch,\n AgnosticDataRouteObject,\n DataStrategyMatch,\n AgnosticRouteObject,\n DataResult,\n DataStrategyFunction,\n DataStrategyFunctionArgs,\n DeferredData,\n DeferredResult,\n DetectErrorBoundaryFunction,\n ErrorResult,\n FormEncType,\n FormMethod,\n HTMLFormMethod,\n DataStrategyResult,\n ImmutableRouteKey,\n MapRoutePropertiesFunction,\n MutationFormMethod,\n RedirectResult,\n RouteData,\n RouteManifest,\n ShouldRevalidateFunctionArgs,\n Submission,\n SuccessResult,\n UIMatch,\n V7_FormMethod,\n V7_MutationFormMethod,\n AgnosticPatchRoutesOnNavigationFunction,\n DataWithResponseInit,\n} from \"./utils\";\nimport {\n ErrorResponseImpl,\n ResultType,\n convertRouteMatchToUiMatch,\n convertRoutesToDataRoutes,\n getPathContributingMatches,\n getResolveToMatches,\n immutableRouteKeys,\n isRouteErrorResponse,\n joinPaths,\n matchRoutes,\n matchRoutesImpl,\n removeDoubleSlashes,\n resolveTo,\n stripBasename,\n} from \"./utils\";\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Types and Constants\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A Router instance manages all navigation and data loading/mutations\n */\nexport interface Router {\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the basename for the router\n */\n get basename(): RouterInit[\"basename\"];\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the future config for the router\n */\n get future(): FutureConfig;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the current state of the router\n */\n get state(): RouterState;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the routes for this router instance\n */\n get routes(): AgnosticDataRouteObject[];\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the window associated with the router\n */\n get window(): RouterInit[\"window\"];\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Initialize the router, including adding history listeners and kicking off\n * initial data fetches. Returns a function to cleanup listeners and abort\n * any in-progress loads\n */\n initialize(): Router;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Subscribe to router.state updates\n *\n * @param fn function to call with the new state\n */\n subscribe(fn: RouterSubscriber): () => void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Enable scroll restoration behavior in the router\n *\n * @param savedScrollPositions Object that will manage positions, in case\n * it's being restored from sessionStorage\n * @param getScrollPosition Function to get the active Y scroll position\n * @param getKey Function to get the key to use for restoration\n */\n enableScrollRestoration(\n savedScrollPositions: Record,\n getScrollPosition: GetScrollPositionFunction,\n getKey?: GetScrollRestorationKeyFunction\n ): () => void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Navigate forward/backward in the history stack\n * @param to Delta to move in the history stack\n */\n navigate(to: number): Promise;\n\n /**\n * Navigate to the given path\n * @param to Path to navigate to\n * @param opts Navigation options (method, submission, etc.)\n */\n navigate(to: To | null, opts?: RouterNavigateOptions): Promise;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Trigger a fetcher load/submission\n *\n * @param key Fetcher key\n * @param routeId Route that owns the fetcher\n * @param href href to fetch\n * @param opts Fetcher options, (method, submission, etc.)\n */\n fetch(\n key: string,\n routeId: string,\n href: string | null,\n opts?: RouterFetchOptions\n ): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Trigger a revalidation of all current route loaders and fetcher loads\n */\n revalidate(): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Utility function to create an href for the given location\n * @param location\n */\n createHref(location: Location | URL): string;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Utility function to URL encode a destination path according to the internal\n * history implementation\n * @param to\n */\n encodeLocation(to: To): Path;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Get/create a fetcher for the given key\n * @param key\n */\n getFetcher(key: string): Fetcher;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Delete the fetcher for a given key\n * @param key\n */\n deleteFetcher(key: string): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Cleanup listeners and abort any in-progress loads\n */\n dispose(): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Get a navigation blocker\n * @param key The identifier for the blocker\n * @param fn The blocker function implementation\n */\n getBlocker(key: string, fn: BlockerFunction): Blocker;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Delete a navigation blocker\n * @param key The identifier for the blocker\n */\n deleteBlocker(key: string): void;\n\n /**\n * @internal\n * PRIVATE DO NOT USE\n *\n * Patch additional children routes into an existing parent route\n * @param routeId The parent route id or a callback function accepting `patch`\n * to perform batch patching\n * @param children The additional children routes\n */\n patchRoutes(routeId: string | null, children: AgnosticRouteObject[]): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * HMR needs to pass in-flight route updates to React Router\n * TODO: Replace this with granular route update APIs (addRoute, updateRoute, deleteRoute)\n */\n _internalSetRoutes(routes: AgnosticRouteObject[]): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Internal fetch AbortControllers accessed by unit tests\n */\n _internalFetchControllers: Map;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Internal pending DeferredData instances accessed by unit tests\n */\n _internalActiveDeferreds: Map;\n}\n\n/**\n * State maintained internally by the router. During a navigation, all states\n * reflect the the \"old\" location unless otherwise noted.\n */\nexport interface RouterState {\n /**\n * The action of the most recent navigation\n */\n historyAction: HistoryAction;\n\n /**\n * The current location reflected by the router\n */\n location: Location;\n\n /**\n * The current set of route matches\n */\n matches: AgnosticDataRouteMatch[];\n\n /**\n * Tracks whether we've completed our initial data load\n */\n initialized: boolean;\n\n /**\n * Current scroll position we should start at for a new view\n * - number -> scroll position to restore to\n * - false -> do not restore scroll at all (used during submissions)\n * - null -> don't have a saved position, scroll to hash or top of page\n */\n restoreScrollPosition: number | false | null;\n\n /**\n * Indicate whether this navigation should skip resetting the scroll position\n * if we are unable to restore the scroll position\n */\n preventScrollReset: boolean;\n\n /**\n * Tracks the state of the current navigation\n */\n navigation: Navigation;\n\n /**\n * Tracks any in-progress revalidations\n */\n revalidation: RevalidationState;\n\n /**\n * Data from the loaders for the current matches\n */\n loaderData: RouteData;\n\n /**\n * Data from the action for the current matches\n */\n actionData: RouteData | null;\n\n /**\n * Errors caught from loaders for the current matches\n */\n errors: RouteData | null;\n\n /**\n * Map of current fetchers\n */\n fetchers: Map;\n\n /**\n * Map of current blockers\n */\n blockers: Map;\n}\n\n/**\n * Data that can be passed into hydrate a Router from SSR\n */\nexport type HydrationState = Partial<\n Pick\n>;\n\n/**\n * Future flags to toggle new feature behavior\n */\nexport interface FutureConfig {\n v7_fetcherPersist: boolean;\n v7_normalizeFormMethod: boolean;\n v7_partialHydration: boolean;\n v7_prependBasename: boolean;\n v7_relativeSplatPath: boolean;\n v7_skipActionErrorRevalidation: boolean;\n}\n\n/**\n * Initialization options for createRouter\n */\nexport interface RouterInit {\n routes: AgnosticRouteObject[];\n history: History;\n basename?: string;\n /**\n * @deprecated Use `mapRouteProperties` instead\n */\n detectErrorBoundary?: DetectErrorBoundaryFunction;\n mapRouteProperties?: MapRoutePropertiesFunction;\n future?: Partial;\n hydrationData?: HydrationState;\n window?: Window;\n dataStrategy?: DataStrategyFunction;\n patchRoutesOnNavigation?: AgnosticPatchRoutesOnNavigationFunction;\n}\n\n/**\n * State returned from a server-side query() call\n */\nexport interface StaticHandlerContext {\n basename: Router[\"basename\"];\n location: RouterState[\"location\"];\n matches: RouterState[\"matches\"];\n loaderData: RouterState[\"loaderData\"];\n actionData: RouterState[\"actionData\"];\n errors: RouterState[\"errors\"];\n statusCode: number;\n loaderHeaders: Record;\n actionHeaders: Record;\n activeDeferreds: Record | null;\n _deepestRenderedBoundaryId?: string | null;\n}\n\n/**\n * A StaticHandler instance manages a singular SSR navigation/fetch event\n */\nexport interface StaticHandler {\n dataRoutes: AgnosticDataRouteObject[];\n query(\n request: Request,\n opts?: {\n requestContext?: unknown;\n skipLoaderErrorBubbling?: boolean;\n dataStrategy?: DataStrategyFunction;\n }\n ): Promise;\n queryRoute(\n request: Request,\n opts?: {\n routeId?: string;\n requestContext?: unknown;\n dataStrategy?: DataStrategyFunction;\n }\n ): Promise;\n}\n\ntype ViewTransitionOpts = {\n currentLocation: Location;\n nextLocation: Location;\n};\n\n/**\n * Subscriber function signature for changes to router state\n */\nexport interface RouterSubscriber {\n (\n state: RouterState,\n opts: {\n deletedFetchers: string[];\n viewTransitionOpts?: ViewTransitionOpts;\n flushSync: boolean;\n }\n ): void;\n}\n\n/**\n * Function signature for determining the key to be used in scroll restoration\n * for a given location\n */\nexport interface GetScrollRestorationKeyFunction {\n (location: Location, matches: UIMatch[]): string | null;\n}\n\n/**\n * Function signature for determining the current scroll position\n */\nexport interface GetScrollPositionFunction {\n (): number;\n}\n\nexport type RelativeRoutingType = \"route\" | \"path\";\n\n// Allowed for any navigation or fetch\ntype BaseNavigateOrFetchOptions = {\n preventScrollReset?: boolean;\n relative?: RelativeRoutingType;\n flushSync?: boolean;\n};\n\n// Only allowed for navigations\ntype BaseNavigateOptions = BaseNavigateOrFetchOptions & {\n replace?: boolean;\n state?: any;\n fromRouteId?: string;\n viewTransition?: boolean;\n};\n\n// Only allowed for submission navigations\ntype BaseSubmissionOptions = {\n formMethod?: HTMLFormMethod;\n formEncType?: FormEncType;\n} & (\n | { formData: FormData; body?: undefined }\n | { formData?: undefined; body: any }\n);\n\n/**\n * Options for a navigate() call for a normal (non-submission) navigation\n */\ntype LinkNavigateOptions = BaseNavigateOptions;\n\n/**\n * Options for a navigate() call for a submission navigation\n */\ntype SubmissionNavigateOptions = BaseNavigateOptions & BaseSubmissionOptions;\n\n/**\n * Options to pass to navigate() for a navigation\n */\nexport type RouterNavigateOptions =\n | LinkNavigateOptions\n | SubmissionNavigateOptions;\n\n/**\n * Options for a fetch() load\n */\ntype LoadFetchOptions = BaseNavigateOrFetchOptions;\n\n/**\n * Options for a fetch() submission\n */\ntype SubmitFetchOptions = BaseNavigateOrFetchOptions & BaseSubmissionOptions;\n\n/**\n * Options to pass to fetch()\n */\nexport type RouterFetchOptions = LoadFetchOptions | SubmitFetchOptions;\n\n/**\n * Potential states for state.navigation\n */\nexport type NavigationStates = {\n Idle: {\n state: \"idle\";\n location: undefined;\n formMethod: undefined;\n formAction: undefined;\n formEncType: undefined;\n formData: undefined;\n json: undefined;\n text: undefined;\n };\n Loading: {\n state: \"loading\";\n location: Location;\n formMethod: Submission[\"formMethod\"] | undefined;\n formAction: Submission[\"formAction\"] | undefined;\n formEncType: Submission[\"formEncType\"] | undefined;\n formData: Submission[\"formData\"] | undefined;\n json: Submission[\"json\"] | undefined;\n text: Submission[\"text\"] | undefined;\n };\n Submitting: {\n state: \"submitting\";\n location: Location;\n formMethod: Submission[\"formMethod\"];\n formAction: Submission[\"formAction\"];\n formEncType: Submission[\"formEncType\"];\n formData: Submission[\"formData\"];\n json: Submission[\"json\"];\n text: Submission[\"text\"];\n };\n};\n\nexport type Navigation = NavigationStates[keyof NavigationStates];\n\nexport type RevalidationState = \"idle\" | \"loading\";\n\n/**\n * Potential states for fetchers\n */\ntype FetcherStates = {\n Idle: {\n state: \"idle\";\n formMethod: undefined;\n formAction: undefined;\n formEncType: undefined;\n text: undefined;\n formData: undefined;\n json: undefined;\n data: TData | undefined;\n };\n Loading: {\n state: \"loading\";\n formMethod: Submission[\"formMethod\"] | undefined;\n formAction: Submission[\"formAction\"] | undefined;\n formEncType: Submission[\"formEncType\"] | undefined;\n text: Submission[\"text\"] | undefined;\n formData: Submission[\"formData\"] | undefined;\n json: Submission[\"json\"] | undefined;\n data: TData | undefined;\n };\n Submitting: {\n state: \"submitting\";\n formMethod: Submission[\"formMethod\"];\n formAction: Submission[\"formAction\"];\n formEncType: Submission[\"formEncType\"];\n text: Submission[\"text\"];\n formData: Submission[\"formData\"];\n json: Submission[\"json\"];\n data: TData | undefined;\n };\n};\n\nexport type Fetcher =\n FetcherStates[keyof FetcherStates];\n\ninterface BlockerBlocked {\n state: \"blocked\";\n reset(): void;\n proceed(): void;\n location: Location;\n}\n\ninterface BlockerUnblocked {\n state: \"unblocked\";\n reset: undefined;\n proceed: undefined;\n location: undefined;\n}\n\ninterface BlockerProceeding {\n state: \"proceeding\";\n reset: undefined;\n proceed: undefined;\n location: Location;\n}\n\nexport type Blocker = BlockerUnblocked | BlockerBlocked | BlockerProceeding;\n\nexport type BlockerFunction = (args: {\n currentLocation: Location;\n nextLocation: Location;\n historyAction: HistoryAction;\n}) => boolean;\n\ninterface ShortCircuitable {\n /**\n * startNavigation does not need to complete the navigation because we\n * redirected or got interrupted\n */\n shortCircuited?: boolean;\n}\n\ntype PendingActionResult = [string, SuccessResult | ErrorResult];\n\ninterface HandleActionResult extends ShortCircuitable {\n /**\n * Route matches which may have been updated from fog of war discovery\n */\n matches?: RouterState[\"matches\"];\n /**\n * Tuple for the returned or thrown value from the current action. The routeId\n * is the action route for success and the bubbled boundary route for errors.\n */\n pendingActionResult?: PendingActionResult;\n}\n\ninterface HandleLoadersResult extends ShortCircuitable {\n /**\n * Route matches which may have been updated from fog of war discovery\n */\n matches?: RouterState[\"matches\"];\n /**\n * loaderData returned from the current set of loaders\n */\n loaderData?: RouterState[\"loaderData\"];\n /**\n * errors thrown from the current set of loaders\n */\n errors?: RouterState[\"errors\"];\n}\n\n/**\n * Cached info for active fetcher.load() instances so they can participate\n * in revalidation\n */\ninterface FetchLoadMatch {\n routeId: string;\n path: string;\n}\n\n/**\n * Identified fetcher.load() calls that need to be revalidated\n */\ninterface RevalidatingFetcher extends FetchLoadMatch {\n key: string;\n match: AgnosticDataRouteMatch | null;\n matches: AgnosticDataRouteMatch[] | null;\n controller: AbortController | null;\n}\n\nconst validMutationMethodsArr: MutationFormMethod[] = [\n \"post\",\n \"put\",\n \"patch\",\n \"delete\",\n];\nconst validMutationMethods = new Set(\n validMutationMethodsArr\n);\n\nconst validRequestMethodsArr: FormMethod[] = [\n \"get\",\n ...validMutationMethodsArr,\n];\nconst validRequestMethods = new Set(validRequestMethodsArr);\n\nconst redirectStatusCodes = new Set([301, 302, 303, 307, 308]);\nconst redirectPreserveMethodStatusCodes = new Set([307, 308]);\n\nexport const IDLE_NAVIGATION: NavigationStates[\"Idle\"] = {\n state: \"idle\",\n location: undefined,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n};\n\nexport const IDLE_FETCHER: FetcherStates[\"Idle\"] = {\n state: \"idle\",\n data: undefined,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n};\n\nexport const IDLE_BLOCKER: BlockerUnblocked = {\n state: \"unblocked\",\n proceed: undefined,\n reset: undefined,\n location: undefined,\n};\n\nconst ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i;\n\nconst defaultMapRouteProperties: MapRoutePropertiesFunction = (route) => ({\n hasErrorBoundary: Boolean(route.hasErrorBoundary),\n});\n\nconst TRANSITIONS_STORAGE_KEY = \"remix-router-transitions\";\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region createRouter\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Create a router and listen to history POP navigations\n */\nexport function createRouter(init: RouterInit): Router {\n const routerWindow = init.window\n ? init.window\n : typeof window !== \"undefined\"\n ? window\n : undefined;\n const isBrowser =\n typeof routerWindow !== \"undefined\" &&\n typeof routerWindow.document !== \"undefined\" &&\n typeof routerWindow.document.createElement !== \"undefined\";\n const isServer = !isBrowser;\n\n invariant(\n init.routes.length > 0,\n \"You must provide a non-empty routes array to createRouter\"\n );\n\n let mapRouteProperties: MapRoutePropertiesFunction;\n if (init.mapRouteProperties) {\n mapRouteProperties = init.mapRouteProperties;\n } else if (init.detectErrorBoundary) {\n // If they are still using the deprecated version, wrap it with the new API\n let detectErrorBoundary = init.detectErrorBoundary;\n mapRouteProperties = (route) => ({\n hasErrorBoundary: detectErrorBoundary(route),\n });\n } else {\n mapRouteProperties = defaultMapRouteProperties;\n }\n\n // Routes keyed by ID\n let manifest: RouteManifest = {};\n // Routes in tree format for matching\n let dataRoutes = convertRoutesToDataRoutes(\n init.routes,\n mapRouteProperties,\n undefined,\n manifest\n );\n let inFlightDataRoutes: AgnosticDataRouteObject[] | undefined;\n let basename = init.basename || \"/\";\n let dataStrategyImpl = init.dataStrategy || defaultDataStrategy;\n let patchRoutesOnNavigationImpl = init.patchRoutesOnNavigation;\n\n // Config driven behavior flags\n let future: FutureConfig = {\n v7_fetcherPersist: false,\n v7_normalizeFormMethod: false,\n v7_partialHydration: false,\n v7_prependBasename: false,\n v7_relativeSplatPath: false,\n v7_skipActionErrorRevalidation: false,\n ...init.future,\n };\n // Cleanup function for history\n let unlistenHistory: (() => void) | null = null;\n // Externally-provided functions to call on all state changes\n let subscribers = new Set();\n // Externally-provided object to hold scroll restoration locations during routing\n let savedScrollPositions: Record | null = null;\n // Externally-provided function to get scroll restoration keys\n let getScrollRestorationKey: GetScrollRestorationKeyFunction | null = null;\n // Externally-provided function to get current scroll position\n let getScrollPosition: GetScrollPositionFunction | null = null;\n // One-time flag to control the initial hydration scroll restoration. Because\n // we don't get the saved positions from until _after_\n // the initial render, we need to manually trigger a separate updateState to\n // send along the restoreScrollPosition\n // Set to true if we have `hydrationData` since we assume we were SSR'd and that\n // SSR did the initial scroll restoration.\n let initialScrollRestored = init.hydrationData != null;\n\n let initialMatches = matchRoutes(dataRoutes, init.history.location, basename);\n let initialMatchesIsFOW = false;\n let initialErrors: RouteData | null = null;\n\n if (initialMatches == null && !patchRoutesOnNavigationImpl) {\n // If we do not match a user-provided-route, fall back to the root\n // to allow the error boundary to take over\n let error = getInternalRouterError(404, {\n pathname: init.history.location.pathname,\n });\n let { matches, route } = getShortCircuitMatches(dataRoutes);\n initialMatches = matches;\n initialErrors = { [route.id]: error };\n }\n\n // In SPA apps, if the user provided a patchRoutesOnNavigation implementation and\n // our initial match is a splat route, clear them out so we run through lazy\n // discovery on hydration in case there's a more accurate lazy route match.\n // In SSR apps (with `hydrationData`), we expect that the server will send\n // up the proper matched routes so we don't want to run lazy discovery on\n // initial hydration and want to hydrate into the splat route.\n if (initialMatches && !init.hydrationData) {\n let fogOfWar = checkFogOfWar(\n initialMatches,\n dataRoutes,\n init.history.location.pathname\n );\n if (fogOfWar.active) {\n initialMatches = null;\n }\n }\n\n let initialized: boolean;\n if (!initialMatches) {\n initialized = false;\n initialMatches = [];\n\n // If partial hydration and fog of war is enabled, we will be running\n // `patchRoutesOnNavigation` during hydration so include any partial matches as\n // the initial matches so we can properly render `HydrateFallback`'s\n if (future.v7_partialHydration) {\n let fogOfWar = checkFogOfWar(\n null,\n dataRoutes,\n init.history.location.pathname\n );\n if (fogOfWar.active && fogOfWar.matches) {\n initialMatchesIsFOW = true;\n initialMatches = fogOfWar.matches;\n }\n }\n } else if (initialMatches.some((m) => m.route.lazy)) {\n // All initialMatches need to be loaded before we're ready. If we have lazy\n // functions around still then we'll need to run them in initialize()\n initialized = false;\n } else if (!initialMatches.some((m) => m.route.loader)) {\n // If we've got no loaders to run, then we're good to go\n initialized = true;\n } else if (future.v7_partialHydration) {\n // If partial hydration is enabled, we're initialized so long as we were\n // provided with hydrationData for every route with a loader, and no loaders\n // were marked for explicit hydration\n let loaderData = init.hydrationData ? init.hydrationData.loaderData : null;\n let errors = init.hydrationData ? init.hydrationData.errors : null;\n // If errors exist, don't consider routes below the boundary\n if (errors) {\n let idx = initialMatches.findIndex(\n (m) => errors![m.route.id] !== undefined\n );\n initialized = initialMatches\n .slice(0, idx + 1)\n .every((m) => !shouldLoadRouteOnHydration(m.route, loaderData, errors));\n } else {\n initialized = initialMatches.every(\n (m) => !shouldLoadRouteOnHydration(m.route, loaderData, errors)\n );\n }\n } else {\n // Without partial hydration - we're initialized if we were provided any\n // hydrationData - which is expected to be complete\n initialized = init.hydrationData != null;\n }\n\n let router: Router;\n let state: RouterState = {\n historyAction: init.history.action,\n location: init.history.location,\n matches: initialMatches,\n initialized,\n navigation: IDLE_NAVIGATION,\n // Don't restore on initial updateState() if we were SSR'd\n restoreScrollPosition: init.hydrationData != null ? false : null,\n preventScrollReset: false,\n revalidation: \"idle\",\n loaderData: (init.hydrationData && init.hydrationData.loaderData) || {},\n actionData: (init.hydrationData && init.hydrationData.actionData) || null,\n errors: (init.hydrationData && init.hydrationData.errors) || initialErrors,\n fetchers: new Map(),\n blockers: new Map(),\n };\n\n // -- Stateful internal variables to manage navigations --\n // Current navigation in progress (to be committed in completeNavigation)\n let pendingAction: HistoryAction = HistoryAction.Pop;\n\n // Should the current navigation prevent the scroll reset if scroll cannot\n // be restored?\n let pendingPreventScrollReset = false;\n\n // AbortController for the active navigation\n let pendingNavigationController: AbortController | null;\n\n // Should the current navigation enable document.startViewTransition?\n let pendingViewTransitionEnabled = false;\n\n // Store applied view transitions so we can apply them on POP\n let appliedViewTransitions: Map> = new Map<\n string,\n Set\n >();\n\n // Cleanup function for persisting applied transitions to sessionStorage\n let removePageHideEventListener: (() => void) | null = null;\n\n // We use this to avoid touching history in completeNavigation if a\n // revalidation is entirely uninterrupted\n let isUninterruptedRevalidation = false;\n\n // Use this internal flag to force revalidation of all loaders:\n // - submissions (completed or interrupted)\n // - useRevalidator()\n // - X-Remix-Revalidate (from redirect)\n let isRevalidationRequired = false;\n\n // Use this internal array to capture routes that require revalidation due\n // to a cancelled deferred on action submission\n let cancelledDeferredRoutes: string[] = [];\n\n // Use this internal array to capture fetcher loads that were cancelled by an\n // action navigation and require revalidation\n let cancelledFetcherLoads: Set = new Set();\n\n // AbortControllers for any in-flight fetchers\n let fetchControllers = new Map();\n\n // Track loads based on the order in which they started\n let incrementingLoadId = 0;\n\n // Track the outstanding pending navigation data load to be compared against\n // the globally incrementing load when a fetcher load lands after a completed\n // navigation\n let pendingNavigationLoadId = -1;\n\n // Fetchers that triggered data reloads as a result of their actions\n let fetchReloadIds = new Map();\n\n // Fetchers that triggered redirect navigations\n let fetchRedirectIds = new Set();\n\n // Most recent href/match for fetcher.load calls for fetchers\n let fetchLoadMatches = new Map();\n\n // Ref-count mounted fetchers so we know when it's ok to clean them up\n let activeFetchers = new Map();\n\n // Fetchers that have requested a delete when using v7_fetcherPersist,\n // they'll be officially removed after they return to idle\n let deletedFetchers = new Set();\n\n // Store DeferredData instances for active route matches. When a\n // route loader returns defer() we stick one in here. Then, when a nested\n // promise resolves we update loaderData. If a new navigation starts we\n // cancel active deferreds for eliminated routes.\n let activeDeferreds = new Map();\n\n // Store blocker functions in a separate Map outside of router state since\n // we don't need to update UI state if they change\n let blockerFunctions = new Map();\n\n // Map of pending patchRoutesOnNavigation() promises (keyed by path/matches) so\n // that we only kick them off once for a given combo\n let pendingPatchRoutes = new Map<\n string,\n ReturnType\n >();\n\n // Flag to ignore the next history update, so we can revert the URL change on\n // a POP navigation that was blocked by the user without touching router state\n let unblockBlockerHistoryUpdate: (() => void) | undefined = undefined;\n\n // Initialize the router, all side effects should be kicked off from here.\n // Implemented as a Fluent API for ease of:\n // let router = createRouter(init).initialize();\n function initialize() {\n // If history informs us of a POP navigation, start the navigation but do not update\n // state. We'll update our own state once the navigation completes\n unlistenHistory = init.history.listen(\n ({ action: historyAction, location, delta }) => {\n // Ignore this event if it was just us resetting the URL from a\n // blocked POP navigation\n if (unblockBlockerHistoryUpdate) {\n unblockBlockerHistoryUpdate();\n unblockBlockerHistoryUpdate = undefined;\n return;\n }\n\n warning(\n blockerFunctions.size === 0 || delta != null,\n \"You are trying to use a blocker on a POP navigation to a location \" +\n \"that was not created by @remix-run/router. This will fail silently in \" +\n \"production. This can happen if you are navigating outside the router \" +\n \"via `window.history.pushState`/`window.location.hash` instead of using \" +\n \"router navigation APIs. This can also happen if you are using \" +\n \"createHashRouter and the user manually changes the URL.\"\n );\n\n let blockerKey = shouldBlockNavigation({\n currentLocation: state.location,\n nextLocation: location,\n historyAction,\n });\n\n if (blockerKey && delta != null) {\n // Restore the URL to match the current UI, but don't update router state\n let nextHistoryUpdatePromise = new Promise((resolve) => {\n unblockBlockerHistoryUpdate = resolve;\n });\n init.history.go(delta * -1);\n\n // Put the blocker into a blocked state\n updateBlocker(blockerKey, {\n state: \"blocked\",\n location,\n proceed() {\n updateBlocker(blockerKey!, {\n state: \"proceeding\",\n proceed: undefined,\n reset: undefined,\n location,\n });\n // Re-do the same POP navigation we just blocked, after the url\n // restoration is also complete. See:\n // https://github.com/remix-run/react-router/issues/11613\n nextHistoryUpdatePromise.then(() => init.history.go(delta));\n },\n reset() {\n let blockers = new Map(state.blockers);\n blockers.set(blockerKey!, IDLE_BLOCKER);\n updateState({ blockers });\n },\n });\n return;\n }\n\n return startNavigation(historyAction, location);\n }\n );\n\n if (isBrowser) {\n // FIXME: This feels gross. How can we cleanup the lines between\n // scrollRestoration/appliedTransitions persistance?\n restoreAppliedTransitions(routerWindow, appliedViewTransitions);\n let _saveAppliedTransitions = () =>\n persistAppliedTransitions(routerWindow, appliedViewTransitions);\n routerWindow.addEventListener(\"pagehide\", _saveAppliedTransitions);\n removePageHideEventListener = () =>\n routerWindow.removeEventListener(\"pagehide\", _saveAppliedTransitions);\n }\n\n // Kick off initial data load if needed. Use Pop to avoid modifying history\n // Note we don't do any handling of lazy here. For SPA's it'll get handled\n // in the normal navigation flow. For SSR it's expected that lazy modules are\n // resolved prior to router creation since we can't go into a fallbackElement\n // UI for SSR'd apps\n if (!state.initialized) {\n startNavigation(HistoryAction.Pop, state.location, {\n initialHydration: true,\n });\n }\n\n return router;\n }\n\n // Clean up a router and it's side effects\n function dispose() {\n if (unlistenHistory) {\n unlistenHistory();\n }\n if (removePageHideEventListener) {\n removePageHideEventListener();\n }\n subscribers.clear();\n pendingNavigationController && pendingNavigationController.abort();\n state.fetchers.forEach((_, key) => deleteFetcher(key));\n state.blockers.forEach((_, key) => deleteBlocker(key));\n }\n\n // Subscribe to state updates for the router\n function subscribe(fn: RouterSubscriber) {\n subscribers.add(fn);\n return () => subscribers.delete(fn);\n }\n\n // Update our state and notify the calling context of the change\n function updateState(\n newState: Partial,\n opts: {\n flushSync?: boolean;\n viewTransitionOpts?: ViewTransitionOpts;\n } = {}\n ): void {\n state = {\n ...state,\n ...newState,\n };\n\n // Prep fetcher cleanup so we can tell the UI which fetcher data entries\n // can be removed\n let completedFetchers: string[] = [];\n let deletedFetchersKeys: string[] = [];\n\n if (future.v7_fetcherPersist) {\n state.fetchers.forEach((fetcher, key) => {\n if (fetcher.state === \"idle\") {\n if (deletedFetchers.has(key)) {\n // Unmounted from the UI and can be totally removed\n deletedFetchersKeys.push(key);\n } else {\n // Returned to idle but still mounted in the UI, so semi-remains for\n // revalidations and such\n completedFetchers.push(key);\n }\n }\n });\n }\n\n // Remove any lingering deleted fetchers that have already been removed\n // from state.fetchers\n deletedFetchers.forEach((key) => {\n if (!state.fetchers.has(key) && !fetchControllers.has(key)) {\n deletedFetchersKeys.push(key);\n }\n });\n\n // Iterate over a local copy so that if flushSync is used and we end up\n // removing and adding a new subscriber due to the useCallback dependencies,\n // we don't get ourselves into a loop calling the new subscriber immediately\n [...subscribers].forEach((subscriber) =>\n subscriber(state, {\n deletedFetchers: deletedFetchersKeys,\n viewTransitionOpts: opts.viewTransitionOpts,\n flushSync: opts.flushSync === true,\n })\n );\n\n // Remove idle fetchers from state since we only care about in-flight fetchers.\n if (future.v7_fetcherPersist) {\n completedFetchers.forEach((key) => state.fetchers.delete(key));\n deletedFetchersKeys.forEach((key) => deleteFetcher(key));\n } else {\n // We already called deleteFetcher() on these, can remove them from this\n // Set now that we've handed the keys off to the data layer\n deletedFetchersKeys.forEach((key) => deletedFetchers.delete(key));\n }\n }\n\n // Complete a navigation returning the state.navigation back to the IDLE_NAVIGATION\n // and setting state.[historyAction/location/matches] to the new route.\n // - Location is a required param\n // - Navigation will always be set to IDLE_NAVIGATION\n // - Can pass any other state in newState\n function completeNavigation(\n location: Location,\n newState: Partial>,\n { flushSync }: { flushSync?: boolean } = {}\n ): void {\n // Deduce if we're in a loading/actionReload state:\n // - We have committed actionData in the store\n // - The current navigation was a mutation submission\n // - We're past the submitting state and into the loading state\n // - The location being loaded is not the result of a redirect\n let isActionReload =\n state.actionData != null &&\n state.navigation.formMethod != null &&\n isMutationMethod(state.navigation.formMethod) &&\n state.navigation.state === \"loading\" &&\n location.state?._isRedirect !== true;\n\n let actionData: RouteData | null;\n if (newState.actionData) {\n if (Object.keys(newState.actionData).length > 0) {\n actionData = newState.actionData;\n } else {\n // Empty actionData -> clear prior actionData due to an action error\n actionData = null;\n }\n } else if (isActionReload) {\n // Keep the current data if we're wrapping up the action reload\n actionData = state.actionData;\n } else {\n // Clear actionData on any other completed navigations\n actionData = null;\n }\n\n // Always preserve any existing loaderData from re-used routes\n let loaderData = newState.loaderData\n ? mergeLoaderData(\n state.loaderData,\n newState.loaderData,\n newState.matches || [],\n newState.errors\n )\n : state.loaderData;\n\n // On a successful navigation we can assume we got through all blockers\n // so we can start fresh\n let blockers = state.blockers;\n if (blockers.size > 0) {\n blockers = new Map(blockers);\n blockers.forEach((_, k) => blockers.set(k, IDLE_BLOCKER));\n }\n\n // Always respect the user flag. Otherwise don't reset on mutation\n // submission navigations unless they redirect\n let preventScrollReset =\n pendingPreventScrollReset === true ||\n (state.navigation.formMethod != null &&\n isMutationMethod(state.navigation.formMethod) &&\n location.state?._isRedirect !== true);\n\n // Commit any in-flight routes at the end of the HMR revalidation \"navigation\"\n if (inFlightDataRoutes) {\n dataRoutes = inFlightDataRoutes;\n inFlightDataRoutes = undefined;\n }\n\n if (isUninterruptedRevalidation) {\n // If this was an uninterrupted revalidation then do not touch history\n } else if (pendingAction === HistoryAction.Pop) {\n // Do nothing for POP - URL has already been updated\n } else if (pendingAction === HistoryAction.Push) {\n init.history.push(location, location.state);\n } else if (pendingAction === HistoryAction.Replace) {\n init.history.replace(location, location.state);\n }\n\n let viewTransitionOpts: ViewTransitionOpts | undefined;\n\n // On POP, enable transitions if they were enabled on the original navigation\n if (pendingAction === HistoryAction.Pop) {\n // Forward takes precedence so they behave like the original navigation\n let priorPaths = appliedViewTransitions.get(state.location.pathname);\n if (priorPaths && priorPaths.has(location.pathname)) {\n viewTransitionOpts = {\n currentLocation: state.location,\n nextLocation: location,\n };\n } else if (appliedViewTransitions.has(location.pathname)) {\n // If we don't have a previous forward nav, assume we're popping back to\n // the new location and enable if that location previously enabled\n viewTransitionOpts = {\n currentLocation: location,\n nextLocation: state.location,\n };\n }\n } else if (pendingViewTransitionEnabled) {\n // Store the applied transition on PUSH/REPLACE\n let toPaths = appliedViewTransitions.get(state.location.pathname);\n if (toPaths) {\n toPaths.add(location.pathname);\n } else {\n toPaths = new Set([location.pathname]);\n appliedViewTransitions.set(state.location.pathname, toPaths);\n }\n viewTransitionOpts = {\n currentLocation: state.location,\n nextLocation: location,\n };\n }\n\n updateState(\n {\n ...newState, // matches, errors, fetchers go through as-is\n actionData,\n loaderData,\n historyAction: pendingAction,\n location,\n initialized: true,\n navigation: IDLE_NAVIGATION,\n revalidation: \"idle\",\n restoreScrollPosition: getSavedScrollPosition(\n location,\n newState.matches || state.matches\n ),\n preventScrollReset,\n blockers,\n },\n {\n viewTransitionOpts,\n flushSync: flushSync === true,\n }\n );\n\n // Reset stateful navigation vars\n pendingAction = HistoryAction.Pop;\n pendingPreventScrollReset = false;\n pendingViewTransitionEnabled = false;\n isUninterruptedRevalidation = false;\n isRevalidationRequired = false;\n cancelledDeferredRoutes = [];\n }\n\n // Trigger a navigation event, which can either be a numerical POP or a PUSH\n // replace with an optional submission\n async function navigate(\n to: number | To | null,\n opts?: RouterNavigateOptions\n ): Promise {\n if (typeof to === \"number\") {\n init.history.go(to);\n return;\n }\n\n let normalizedPath = normalizeTo(\n state.location,\n state.matches,\n basename,\n future.v7_prependBasename,\n to,\n future.v7_relativeSplatPath,\n opts?.fromRouteId,\n opts?.relative\n );\n let { path, submission, error } = normalizeNavigateOptions(\n future.v7_normalizeFormMethod,\n false,\n normalizedPath,\n opts\n );\n\n let currentLocation = state.location;\n let nextLocation = createLocation(state.location, path, opts && opts.state);\n\n // When using navigate as a PUSH/REPLACE we aren't reading an already-encoded\n // URL from window.location, so we need to encode it here so the behavior\n // remains the same as POP and non-data-router usages. new URL() does all\n // the same encoding we'd get from a history.pushState/window.location read\n // without having to touch history\n nextLocation = {\n ...nextLocation,\n ...init.history.encodeLocation(nextLocation),\n };\n\n let userReplace = opts && opts.replace != null ? opts.replace : undefined;\n\n let historyAction = HistoryAction.Push;\n\n if (userReplace === true) {\n historyAction = HistoryAction.Replace;\n } else if (userReplace === false) {\n // no-op\n } else if (\n submission != null &&\n isMutationMethod(submission.formMethod) &&\n submission.formAction === state.location.pathname + state.location.search\n ) {\n // By default on submissions to the current location we REPLACE so that\n // users don't have to double-click the back button to get to the prior\n // location. If the user redirects to a different location from the\n // action/loader this will be ignored and the redirect will be a PUSH\n historyAction = HistoryAction.Replace;\n }\n\n let preventScrollReset =\n opts && \"preventScrollReset\" in opts\n ? opts.preventScrollReset === true\n : undefined;\n\n let flushSync = (opts && opts.flushSync) === true;\n\n let blockerKey = shouldBlockNavigation({\n currentLocation,\n nextLocation,\n historyAction,\n });\n\n if (blockerKey) {\n // Put the blocker into a blocked state\n updateBlocker(blockerKey, {\n state: \"blocked\",\n location: nextLocation,\n proceed() {\n updateBlocker(blockerKey!, {\n state: \"proceeding\",\n proceed: undefined,\n reset: undefined,\n location: nextLocation,\n });\n // Send the same navigation through\n navigate(to, opts);\n },\n reset() {\n let blockers = new Map(state.blockers);\n blockers.set(blockerKey!, IDLE_BLOCKER);\n updateState({ blockers });\n },\n });\n return;\n }\n\n return await startNavigation(historyAction, nextLocation, {\n submission,\n // Send through the formData serialization error if we have one so we can\n // render at the right error boundary after we match routes\n pendingError: error,\n preventScrollReset,\n replace: opts && opts.replace,\n enableViewTransition: opts && opts.viewTransition,\n flushSync,\n });\n }\n\n // Revalidate all current loaders. If a navigation is in progress or if this\n // is interrupted by a navigation, allow this to \"succeed\" by calling all\n // loaders during the next loader round\n function revalidate() {\n interruptActiveLoads();\n updateState({ revalidation: \"loading\" });\n\n // If we're currently submitting an action, we don't need to start a new\n // navigation, we'll just let the follow up loader execution call all loaders\n if (state.navigation.state === \"submitting\") {\n return;\n }\n\n // If we're currently in an idle state, start a new navigation for the current\n // action/location and mark it as uninterrupted, which will skip the history\n // update in completeNavigation\n if (state.navigation.state === \"idle\") {\n startNavigation(state.historyAction, state.location, {\n startUninterruptedRevalidation: true,\n });\n return;\n }\n\n // Otherwise, if we're currently in a loading state, just start a new\n // navigation to the navigation.location but do not trigger an uninterrupted\n // revalidation so that history correctly updates once the navigation completes\n startNavigation(\n pendingAction || state.historyAction,\n state.navigation.location,\n {\n overrideNavigation: state.navigation,\n // Proxy through any rending view transition\n enableViewTransition: pendingViewTransitionEnabled === true,\n }\n );\n }\n\n // Start a navigation to the given action/location. Can optionally provide a\n // overrideNavigation which will override the normalLoad in the case of a redirect\n // navigation\n async function startNavigation(\n historyAction: HistoryAction,\n location: Location,\n opts?: {\n initialHydration?: boolean;\n submission?: Submission;\n fetcherSubmission?: Submission;\n overrideNavigation?: Navigation;\n pendingError?: ErrorResponseImpl;\n startUninterruptedRevalidation?: boolean;\n preventScrollReset?: boolean;\n replace?: boolean;\n enableViewTransition?: boolean;\n flushSync?: boolean;\n }\n ): Promise {\n // Abort any in-progress navigations and start a new one. Unset any ongoing\n // uninterrupted revalidations unless told otherwise, since we want this\n // new navigation to update history normally\n pendingNavigationController && pendingNavigationController.abort();\n pendingNavigationController = null;\n pendingAction = historyAction;\n isUninterruptedRevalidation =\n (opts && opts.startUninterruptedRevalidation) === true;\n\n // Save the current scroll position every time we start a new navigation,\n // and track whether we should reset scroll on completion\n saveScrollPosition(state.location, state.matches);\n pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;\n\n pendingViewTransitionEnabled = (opts && opts.enableViewTransition) === true;\n\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let loadingNavigation = opts && opts.overrideNavigation;\n let matches =\n opts?.initialHydration &&\n state.matches &&\n state.matches.length > 0 &&\n !initialMatchesIsFOW\n ? // `matchRoutes()` has already been called if we're in here via `router.initialize()`\n state.matches\n : matchRoutes(routesToUse, location, basename);\n let flushSync = (opts && opts.flushSync) === true;\n\n // Short circuit if it's only a hash change and not a revalidation or\n // mutation submission.\n //\n // Ignore on initial page loads because since the initial hydration will always\n // be \"same hash\". For example, on /page#hash and submit a \n // which will default to a navigation to /page\n if (\n matches &&\n state.initialized &&\n !isRevalidationRequired &&\n isHashChangeOnly(state.location, location) &&\n !(opts && opts.submission && isMutationMethod(opts.submission.formMethod))\n ) {\n completeNavigation(location, { matches }, { flushSync });\n return;\n }\n\n let fogOfWar = checkFogOfWar(matches, routesToUse, location.pathname);\n if (fogOfWar.active && fogOfWar.matches) {\n matches = fogOfWar.matches;\n }\n\n // Short circuit with a 404 on the root error boundary if we match nothing\n if (!matches) {\n let { error, notFoundMatches, route } = handleNavigational404(\n location.pathname\n );\n completeNavigation(\n location,\n {\n matches: notFoundMatches,\n loaderData: {},\n errors: {\n [route.id]: error,\n },\n },\n { flushSync }\n );\n return;\n }\n\n // Create a controller/Request for this navigation\n pendingNavigationController = new AbortController();\n let request = createClientSideRequest(\n init.history,\n location,\n pendingNavigationController.signal,\n opts && opts.submission\n );\n let pendingActionResult: PendingActionResult | undefined;\n\n if (opts && opts.pendingError) {\n // If we have a pendingError, it means the user attempted a GET submission\n // with binary FormData so assign here and skip to handleLoaders. That\n // way we handle calling loaders above the boundary etc. It's not really\n // different from an actionError in that sense.\n pendingActionResult = [\n findNearestBoundary(matches).route.id,\n { type: ResultType.error, error: opts.pendingError },\n ];\n } else if (\n opts &&\n opts.submission &&\n isMutationMethod(opts.submission.formMethod)\n ) {\n // Call action if we received an action submission\n let actionResult = await handleAction(\n request,\n location,\n opts.submission,\n matches,\n fogOfWar.active,\n { replace: opts.replace, flushSync }\n );\n\n if (actionResult.shortCircuited) {\n return;\n }\n\n // If we received a 404 from handleAction, it's because we couldn't lazily\n // discover the destination route so we don't want to call loaders\n if (actionResult.pendingActionResult) {\n let [routeId, result] = actionResult.pendingActionResult;\n if (\n isErrorResult(result) &&\n isRouteErrorResponse(result.error) &&\n result.error.status === 404\n ) {\n pendingNavigationController = null;\n\n completeNavigation(location, {\n matches: actionResult.matches,\n loaderData: {},\n errors: {\n [routeId]: result.error,\n },\n });\n return;\n }\n }\n\n matches = actionResult.matches || matches;\n pendingActionResult = actionResult.pendingActionResult;\n loadingNavigation = getLoadingNavigation(location, opts.submission);\n flushSync = false;\n // No need to do fog of war matching again on loader execution\n fogOfWar.active = false;\n\n // Create a GET request for the loaders\n request = createClientSideRequest(\n init.history,\n request.url,\n request.signal\n );\n }\n\n // Call loaders\n let {\n shortCircuited,\n matches: updatedMatches,\n loaderData,\n errors,\n } = await handleLoaders(\n request,\n location,\n matches,\n fogOfWar.active,\n loadingNavigation,\n opts && opts.submission,\n opts && opts.fetcherSubmission,\n opts && opts.replace,\n opts && opts.initialHydration === true,\n flushSync,\n pendingActionResult\n );\n\n if (shortCircuited) {\n return;\n }\n\n // Clean up now that the action/loaders have completed. Don't clean up if\n // we short circuited because pendingNavigationController will have already\n // been assigned to a new controller for the next navigation\n pendingNavigationController = null;\n\n completeNavigation(location, {\n matches: updatedMatches || matches,\n ...getActionDataForCommit(pendingActionResult),\n loaderData,\n errors,\n });\n }\n\n // Call the action matched by the leaf route for this navigation and handle\n // redirects/errors\n async function handleAction(\n request: Request,\n location: Location,\n submission: Submission,\n matches: AgnosticDataRouteMatch[],\n isFogOfWar: boolean,\n opts: { replace?: boolean; flushSync?: boolean } = {}\n ): Promise {\n interruptActiveLoads();\n\n // Put us in a submitting state\n let navigation = getSubmittingNavigation(location, submission);\n updateState({ navigation }, { flushSync: opts.flushSync === true });\n\n if (isFogOfWar) {\n let discoverResult = await discoverRoutes(\n matches,\n location.pathname,\n request.signal\n );\n if (discoverResult.type === \"aborted\") {\n return { shortCircuited: true };\n } else if (discoverResult.type === \"error\") {\n let boundaryId = findNearestBoundary(discoverResult.partialMatches)\n .route.id;\n return {\n matches: discoverResult.partialMatches,\n pendingActionResult: [\n boundaryId,\n {\n type: ResultType.error,\n error: discoverResult.error,\n },\n ],\n };\n } else if (!discoverResult.matches) {\n let { notFoundMatches, error, route } = handleNavigational404(\n location.pathname\n );\n return {\n matches: notFoundMatches,\n pendingActionResult: [\n route.id,\n {\n type: ResultType.error,\n error,\n },\n ],\n };\n } else {\n matches = discoverResult.matches;\n }\n }\n\n // Call our action and get the result\n let result: DataResult;\n let actionMatch = getTargetMatch(matches, location);\n\n if (!actionMatch.route.action && !actionMatch.route.lazy) {\n result = {\n type: ResultType.error,\n error: getInternalRouterError(405, {\n method: request.method,\n pathname: location.pathname,\n routeId: actionMatch.route.id,\n }),\n };\n } else {\n let results = await callDataStrategy(\n \"action\",\n state,\n request,\n [actionMatch],\n matches,\n null\n );\n result = results[actionMatch.route.id];\n\n if (request.signal.aborted) {\n return { shortCircuited: true };\n }\n }\n\n if (isRedirectResult(result)) {\n let replace: boolean;\n if (opts && opts.replace != null) {\n replace = opts.replace;\n } else {\n // If the user didn't explicity indicate replace behavior, replace if\n // we redirected to the exact same location we're currently at to avoid\n // double back-buttons\n let location = normalizeRedirectLocation(\n result.response.headers.get(\"Location\")!,\n new URL(request.url),\n basename,\n init.history,\n );\n replace = location === state.location.pathname + state.location.search;\n }\n await startRedirectNavigation(request, result, true, {\n submission,\n replace,\n });\n return { shortCircuited: true };\n }\n\n if (isDeferredResult(result)) {\n throw getInternalRouterError(400, { type: \"defer-action\" });\n }\n\n if (isErrorResult(result)) {\n // Store off the pending error - we use it to determine which loaders\n // to call and will commit it when we complete the navigation\n let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);\n\n // By default, all submissions to the current location are REPLACE\n // navigations, but if the action threw an error that'll be rendered in\n // an errorElement, we fall back to PUSH so that the user can use the\n // back button to get back to the pre-submission form location to try\n // again\n if ((opts && opts.replace) !== true) {\n pendingAction = HistoryAction.Push;\n }\n\n return {\n matches,\n pendingActionResult: [boundaryMatch.route.id, result],\n };\n }\n\n return {\n matches,\n pendingActionResult: [actionMatch.route.id, result],\n };\n }\n\n // Call all applicable loaders for the given matches, handling redirects,\n // errors, etc.\n async function handleLoaders(\n request: Request,\n location: Location,\n matches: AgnosticDataRouteMatch[],\n isFogOfWar: boolean,\n overrideNavigation?: Navigation,\n submission?: Submission,\n fetcherSubmission?: Submission,\n replace?: boolean,\n initialHydration?: boolean,\n flushSync?: boolean,\n pendingActionResult?: PendingActionResult\n ): Promise {\n // Figure out the right navigation we want to use for data loading\n let loadingNavigation =\n overrideNavigation || getLoadingNavigation(location, submission);\n\n // If this was a redirect from an action we don't have a \"submission\" but\n // we have it on the loading navigation so use that if available\n let activeSubmission =\n submission ||\n fetcherSubmission ||\n getSubmissionFromNavigation(loadingNavigation);\n\n // If this is an uninterrupted revalidation, we remain in our current idle\n // state. If not, we need to switch to our loading state and load data,\n // preserving any new action data or existing action data (in the case of\n // a revalidation interrupting an actionReload)\n // If we have partialHydration enabled, then don't update the state for the\n // initial data load since it's not a \"navigation\"\n let shouldUpdateNavigationState =\n !isUninterruptedRevalidation &&\n (!future.v7_partialHydration || !initialHydration);\n\n // When fog of war is enabled, we enter our `loading` state earlier so we\n // can discover new routes during the `loading` state. We skip this if\n // we've already run actions since we would have done our matching already.\n // If the children() function threw then, we want to proceed with the\n // partial matches it discovered.\n if (isFogOfWar) {\n if (shouldUpdateNavigationState) {\n let actionData = getUpdatedActionData(pendingActionResult);\n updateState(\n {\n navigation: loadingNavigation,\n ...(actionData !== undefined ? { actionData } : {}),\n },\n {\n flushSync,\n }\n );\n }\n\n let discoverResult = await discoverRoutes(\n matches,\n location.pathname,\n request.signal\n );\n\n if (discoverResult.type === \"aborted\") {\n return { shortCircuited: true };\n } else if (discoverResult.type === \"error\") {\n let boundaryId = findNearestBoundary(discoverResult.partialMatches)\n .route.id;\n return {\n matches: discoverResult.partialMatches,\n loaderData: {},\n errors: {\n [boundaryId]: discoverResult.error,\n },\n };\n } else if (!discoverResult.matches) {\n let { error, notFoundMatches, route } = handleNavigational404(\n location.pathname\n );\n return {\n matches: notFoundMatches,\n loaderData: {},\n errors: {\n [route.id]: error,\n },\n };\n } else {\n matches = discoverResult.matches;\n }\n }\n\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n init.history,\n state,\n matches,\n activeSubmission,\n location,\n future.v7_partialHydration && initialHydration === true,\n future.v7_skipActionErrorRevalidation,\n isRevalidationRequired,\n cancelledDeferredRoutes,\n cancelledFetcherLoads,\n deletedFetchers,\n fetchLoadMatches,\n fetchRedirectIds,\n routesToUse,\n basename,\n pendingActionResult\n );\n\n // Cancel pending deferreds for no-longer-matched routes or routes we're\n // about to reload. Note that if this is an action reload we would have\n // already cancelled all pending deferreds so this would be a no-op\n cancelActiveDeferreds(\n (routeId) =>\n !(matches && matches.some((m) => m.route.id === routeId)) ||\n (matchesToLoad && matchesToLoad.some((m) => m.route.id === routeId))\n );\n\n pendingNavigationLoadId = ++incrementingLoadId;\n\n // Short circuit if we have no loaders to run\n if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) {\n let updatedFetchers = markFetchRedirectsDone();\n completeNavigation(\n location,\n {\n matches,\n loaderData: {},\n // Commit pending error if we're short circuiting\n errors:\n pendingActionResult && isErrorResult(pendingActionResult[1])\n ? { [pendingActionResult[0]]: pendingActionResult[1].error }\n : null,\n ...getActionDataForCommit(pendingActionResult),\n ...(updatedFetchers ? { fetchers: new Map(state.fetchers) } : {}),\n },\n { flushSync }\n );\n return { shortCircuited: true };\n }\n\n if (shouldUpdateNavigationState) {\n let updates: Partial = {};\n if (!isFogOfWar) {\n // Only update navigation/actionNData if we didn't already do it above\n updates.navigation = loadingNavigation;\n let actionData = getUpdatedActionData(pendingActionResult);\n if (actionData !== undefined) {\n updates.actionData = actionData;\n }\n }\n if (revalidatingFetchers.length > 0) {\n updates.fetchers = getUpdatedRevalidatingFetchers(revalidatingFetchers);\n }\n updateState(updates, { flushSync });\n }\n\n revalidatingFetchers.forEach((rf) => {\n abortFetcher(rf.key);\n if (rf.controller) {\n // Fetchers use an independent AbortController so that aborting a fetcher\n // (via deleteFetcher) does not abort the triggering navigation that\n // triggered the revalidation\n fetchControllers.set(rf.key, rf.controller);\n }\n });\n\n // Proxy navigation abort through to revalidation fetchers\n let abortPendingFetchRevalidations = () =>\n revalidatingFetchers.forEach((f) => abortFetcher(f.key));\n if (pendingNavigationController) {\n pendingNavigationController.signal.addEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n }\n\n let { loaderResults, fetcherResults } =\n await callLoadersAndMaybeResolveData(\n state,\n matches,\n matchesToLoad,\n revalidatingFetchers,\n request\n );\n\n if (request.signal.aborted) {\n return { shortCircuited: true };\n }\n\n // Clean up _after_ loaders have completed. Don't clean up if we short\n // circuited because fetchControllers would have been aborted and\n // reassigned to new controllers for the next navigation\n if (pendingNavigationController) {\n pendingNavigationController.signal.removeEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n }\n\n revalidatingFetchers.forEach((rf) => fetchControllers.delete(rf.key));\n\n // If any loaders returned a redirect Response, start a new REPLACE navigation\n let redirect = findRedirect(loaderResults);\n if (redirect) {\n await startRedirectNavigation(request, redirect.result, true, {\n replace,\n });\n return { shortCircuited: true };\n }\n\n redirect = findRedirect(fetcherResults);\n if (redirect) {\n // If this redirect came from a fetcher make sure we mark it in\n // fetchRedirectIds so it doesn't get revalidated on the next set of\n // loader executions\n fetchRedirectIds.add(redirect.key);\n await startRedirectNavigation(request, redirect.result, true, {\n replace,\n });\n return { shortCircuited: true };\n }\n\n // Process and commit output from loaders\n let { loaderData, errors } = processLoaderData(\n state,\n matches,\n loaderResults,\n pendingActionResult,\n revalidatingFetchers,\n fetcherResults,\n activeDeferreds\n );\n\n // Wire up subscribers to update loaderData as promises settle\n activeDeferreds.forEach((deferredData, routeId) => {\n deferredData.subscribe((aborted) => {\n // Note: No need to updateState here since the TrackedPromise on\n // loaderData is stable across resolve/reject\n // Remove this instance if we were aborted or if promises have settled\n if (aborted || deferredData.done) {\n activeDeferreds.delete(routeId);\n }\n });\n });\n\n // Preserve SSR errors during partial hydration\n if (future.v7_partialHydration && initialHydration && state.errors) {\n errors = { ...state.errors, ...errors };\n }\n\n let updatedFetchers = markFetchRedirectsDone();\n let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId);\n let shouldUpdateFetchers =\n updatedFetchers || didAbortFetchLoads || revalidatingFetchers.length > 0;\n\n return {\n matches,\n loaderData,\n errors,\n ...(shouldUpdateFetchers ? { fetchers: new Map(state.fetchers) } : {}),\n };\n }\n\n function getUpdatedActionData(\n pendingActionResult: PendingActionResult | undefined\n ): Record | null | undefined {\n if (pendingActionResult && !isErrorResult(pendingActionResult[1])) {\n // This is cast to `any` currently because `RouteData`uses any and it\n // would be a breaking change to use any.\n // TODO: v7 - change `RouteData` to use `unknown` instead of `any`\n return {\n [pendingActionResult[0]]: pendingActionResult[1].data as any,\n };\n } else if (state.actionData) {\n if (Object.keys(state.actionData).length === 0) {\n return null;\n } else {\n return state.actionData;\n }\n }\n }\n\n function getUpdatedRevalidatingFetchers(\n revalidatingFetchers: RevalidatingFetcher[]\n ) {\n revalidatingFetchers.forEach((rf) => {\n let fetcher = state.fetchers.get(rf.key);\n let revalidatingFetcher = getLoadingFetcher(\n undefined,\n fetcher ? fetcher.data : undefined\n );\n state.fetchers.set(rf.key, revalidatingFetcher);\n });\n return new Map(state.fetchers);\n }\n\n // Trigger a fetcher load/submit for the given fetcher key\n function fetch(\n key: string,\n routeId: string,\n href: string | null,\n opts?: RouterFetchOptions\n ) {\n if (isServer) {\n throw new Error(\n \"router.fetch() was called during the server render, but it shouldn't be. \" +\n \"You are likely calling a useFetcher() method in the body of your component. \" +\n \"Try moving it to a useEffect or a callback.\"\n );\n }\n\n abortFetcher(key);\n\n let flushSync = (opts && opts.flushSync) === true;\n\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let normalizedPath = normalizeTo(\n state.location,\n state.matches,\n basename,\n future.v7_prependBasename,\n href,\n future.v7_relativeSplatPath,\n routeId,\n opts?.relative\n );\n let matches = matchRoutes(routesToUse, normalizedPath, basename);\n\n let fogOfWar = checkFogOfWar(matches, routesToUse, normalizedPath);\n if (fogOfWar.active && fogOfWar.matches) {\n matches = fogOfWar.matches;\n }\n\n if (!matches) {\n setFetcherError(\n key,\n routeId,\n getInternalRouterError(404, { pathname: normalizedPath }),\n { flushSync }\n );\n return;\n }\n\n let { path, submission, error } = normalizeNavigateOptions(\n future.v7_normalizeFormMethod,\n true,\n normalizedPath,\n opts\n );\n\n if (error) {\n setFetcherError(key, routeId, error, { flushSync });\n return;\n }\n\n let match = getTargetMatch(matches, path);\n\n let preventScrollReset = (opts && opts.preventScrollReset) === true;\n\n if (submission && isMutationMethod(submission.formMethod)) {\n handleFetcherAction(\n key,\n routeId,\n path,\n match,\n matches,\n fogOfWar.active,\n flushSync,\n preventScrollReset,\n submission\n );\n return;\n }\n\n // Store off the match so we can call it's shouldRevalidate on subsequent\n // revalidations\n fetchLoadMatches.set(key, { routeId, path });\n handleFetcherLoader(\n key,\n routeId,\n path,\n match,\n matches,\n fogOfWar.active,\n flushSync,\n preventScrollReset,\n submission\n );\n }\n\n // Call the action for the matched fetcher.submit(), and then handle redirects,\n // errors, and revalidation\n async function handleFetcherAction(\n key: string,\n routeId: string,\n path: string,\n match: AgnosticDataRouteMatch,\n requestMatches: AgnosticDataRouteMatch[],\n isFogOfWar: boolean,\n flushSync: boolean,\n preventScrollReset: boolean,\n submission: Submission\n ) {\n interruptActiveLoads();\n fetchLoadMatches.delete(key);\n\n function detectAndHandle405Error(m: AgnosticDataRouteMatch) {\n if (!m.route.action && !m.route.lazy) {\n let error = getInternalRouterError(405, {\n method: submission.formMethod,\n pathname: path,\n routeId: routeId,\n });\n setFetcherError(key, routeId, error, { flushSync });\n return true;\n }\n return false;\n }\n\n if (!isFogOfWar && detectAndHandle405Error(match)) {\n return;\n }\n\n // Put this fetcher into it's submitting state\n let existingFetcher = state.fetchers.get(key);\n updateFetcherState(key, getSubmittingFetcher(submission, existingFetcher), {\n flushSync,\n });\n\n let abortController = new AbortController();\n let fetchRequest = createClientSideRequest(\n init.history,\n path,\n abortController.signal,\n submission\n );\n\n if (isFogOfWar) {\n let discoverResult = await discoverRoutes(\n requestMatches,\n new URL(fetchRequest.url).pathname,\n fetchRequest.signal,\n key\n );\n\n if (discoverResult.type === \"aborted\") {\n return;\n } else if (discoverResult.type === \"error\") {\n setFetcherError(key, routeId, discoverResult.error, { flushSync });\n return;\n } else if (!discoverResult.matches) {\n setFetcherError(\n key,\n routeId,\n getInternalRouterError(404, { pathname: path }),\n { flushSync }\n );\n return;\n } else {\n requestMatches = discoverResult.matches;\n match = getTargetMatch(requestMatches, path);\n\n if (detectAndHandle405Error(match)) {\n return;\n }\n }\n }\n\n // Call the action for the fetcher\n fetchControllers.set(key, abortController);\n\n let originatingLoadId = incrementingLoadId;\n let actionResults = await callDataStrategy(\n \"action\",\n state,\n fetchRequest,\n [match],\n requestMatches,\n key\n );\n let actionResult = actionResults[match.route.id];\n\n if (fetchRequest.signal.aborted) {\n // We can delete this so long as we weren't aborted by our own fetcher\n // re-submit which would have put _new_ controller is in fetchControllers\n if (fetchControllers.get(key) === abortController) {\n fetchControllers.delete(key);\n }\n return;\n }\n\n // When using v7_fetcherPersist, we don't want errors bubbling up to the UI\n // or redirects processed for unmounted fetchers so we just revert them to\n // idle\n if (future.v7_fetcherPersist && deletedFetchers.has(key)) {\n if (isRedirectResult(actionResult) || isErrorResult(actionResult)) {\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n }\n // Let SuccessResult's fall through for revalidation\n } else {\n if (isRedirectResult(actionResult)) {\n fetchControllers.delete(key);\n if (pendingNavigationLoadId > originatingLoadId) {\n // A new navigation was kicked off after our action started, so that\n // should take precedence over this redirect navigation. We already\n // set isRevalidationRequired so all loaders for the new route should\n // fire unless opted out via shouldRevalidate\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n } else {\n fetchRedirectIds.add(key);\n updateFetcherState(key, getLoadingFetcher(submission));\n return startRedirectNavigation(fetchRequest, actionResult, false, {\n fetcherSubmission: submission,\n preventScrollReset,\n });\n }\n }\n\n // Process any non-redirect errors thrown\n if (isErrorResult(actionResult)) {\n setFetcherError(key, routeId, actionResult.error);\n return;\n }\n }\n\n if (isDeferredResult(actionResult)) {\n throw getInternalRouterError(400, { type: \"defer-action\" });\n }\n\n // Start the data load for current matches, or the next location if we're\n // in the middle of a navigation\n let nextLocation = state.navigation.location || state.location;\n let revalidationRequest = createClientSideRequest(\n init.history,\n nextLocation,\n abortController.signal\n );\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let matches =\n state.navigation.state !== \"idle\"\n ? matchRoutes(routesToUse, state.navigation.location, basename)\n : state.matches;\n\n invariant(matches, \"Didn't find any matches after fetcher action\");\n\n let loadId = ++incrementingLoadId;\n fetchReloadIds.set(key, loadId);\n\n let loadFetcher = getLoadingFetcher(submission, actionResult.data);\n state.fetchers.set(key, loadFetcher);\n\n let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n init.history,\n state,\n matches,\n submission,\n nextLocation,\n false,\n future.v7_skipActionErrorRevalidation,\n isRevalidationRequired,\n cancelledDeferredRoutes,\n cancelledFetcherLoads,\n deletedFetchers,\n fetchLoadMatches,\n fetchRedirectIds,\n routesToUse,\n basename,\n [match.route.id, actionResult]\n );\n\n // Put all revalidating fetchers into the loading state, except for the\n // current fetcher which we want to keep in it's current loading state which\n // contains it's action submission info + action data\n revalidatingFetchers\n .filter((rf) => rf.key !== key)\n .forEach((rf) => {\n let staleKey = rf.key;\n let existingFetcher = state.fetchers.get(staleKey);\n let revalidatingFetcher = getLoadingFetcher(\n undefined,\n existingFetcher ? existingFetcher.data : undefined\n );\n state.fetchers.set(staleKey, revalidatingFetcher);\n abortFetcher(staleKey);\n if (rf.controller) {\n fetchControllers.set(staleKey, rf.controller);\n }\n });\n\n updateState({ fetchers: new Map(state.fetchers) });\n\n let abortPendingFetchRevalidations = () =>\n revalidatingFetchers.forEach((rf) => abortFetcher(rf.key));\n\n abortController.signal.addEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n\n let { loaderResults, fetcherResults } =\n await callLoadersAndMaybeResolveData(\n state,\n matches,\n matchesToLoad,\n revalidatingFetchers,\n revalidationRequest\n );\n\n if (abortController.signal.aborted) {\n return;\n }\n\n abortController.signal.removeEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n\n fetchReloadIds.delete(key);\n fetchControllers.delete(key);\n revalidatingFetchers.forEach((r) => fetchControllers.delete(r.key));\n\n let redirect = findRedirect(loaderResults);\n if (redirect) {\n return startRedirectNavigation(\n revalidationRequest,\n redirect.result,\n false,\n { preventScrollReset }\n );\n }\n\n redirect = findRedirect(fetcherResults);\n if (redirect) {\n // If this redirect came from a fetcher make sure we mark it in\n // fetchRedirectIds so it doesn't get revalidated on the next set of\n // loader executions\n fetchRedirectIds.add(redirect.key);\n return startRedirectNavigation(\n revalidationRequest,\n redirect.result,\n false,\n { preventScrollReset }\n );\n }\n\n // Process and commit output from loaders\n let { loaderData, errors } = processLoaderData(\n state,\n matches,\n loaderResults,\n undefined,\n revalidatingFetchers,\n fetcherResults,\n activeDeferreds\n );\n\n // Since we let revalidations complete even if the submitting fetcher was\n // deleted, only put it back to idle if it hasn't been deleted\n if (state.fetchers.has(key)) {\n let doneFetcher = getDoneFetcher(actionResult.data);\n state.fetchers.set(key, doneFetcher);\n }\n\n abortStaleFetchLoads(loadId);\n\n // If we are currently in a navigation loading state and this fetcher is\n // more recent than the navigation, we want the newer data so abort the\n // navigation and complete it with the fetcher data\n if (\n state.navigation.state === \"loading\" &&\n loadId > pendingNavigationLoadId\n ) {\n invariant(pendingAction, \"Expected pending action\");\n pendingNavigationController && pendingNavigationController.abort();\n\n completeNavigation(state.navigation.location, {\n matches,\n loaderData,\n errors,\n fetchers: new Map(state.fetchers),\n });\n } else {\n // otherwise just update with the fetcher data, preserving any existing\n // loaderData for loaders that did not need to reload. We have to\n // manually merge here since we aren't going through completeNavigation\n updateState({\n errors,\n loaderData: mergeLoaderData(\n state.loaderData,\n loaderData,\n matches,\n errors\n ),\n fetchers: new Map(state.fetchers),\n });\n isRevalidationRequired = false;\n }\n }\n\n // Call the matched loader for fetcher.load(), handling redirects, errors, etc.\n async function handleFetcherLoader(\n key: string,\n routeId: string,\n path: string,\n match: AgnosticDataRouteMatch,\n matches: AgnosticDataRouteMatch[],\n isFogOfWar: boolean,\n flushSync: boolean,\n preventScrollReset: boolean,\n submission?: Submission\n ) {\n let existingFetcher = state.fetchers.get(key);\n updateFetcherState(\n key,\n getLoadingFetcher(\n submission,\n existingFetcher ? existingFetcher.data : undefined\n ),\n { flushSync }\n );\n\n let abortController = new AbortController();\n let fetchRequest = createClientSideRequest(\n init.history,\n path,\n abortController.signal\n );\n\n if (isFogOfWar) {\n let discoverResult = await discoverRoutes(\n matches,\n new URL(fetchRequest.url).pathname,\n fetchRequest.signal,\n key\n );\n\n if (discoverResult.type === \"aborted\") {\n return;\n } else if (discoverResult.type === \"error\") {\n setFetcherError(key, routeId, discoverResult.error, { flushSync });\n return;\n } else if (!discoverResult.matches) {\n setFetcherError(\n key,\n routeId,\n getInternalRouterError(404, { pathname: path }),\n { flushSync }\n );\n return;\n } else {\n matches = discoverResult.matches;\n match = getTargetMatch(matches, path);\n }\n }\n\n // Call the loader for this fetcher route match\n fetchControllers.set(key, abortController);\n\n let originatingLoadId = incrementingLoadId;\n let results = await callDataStrategy(\n \"loader\",\n state,\n fetchRequest,\n [match],\n matches,\n key\n );\n let result = results[match.route.id];\n\n // Deferred isn't supported for fetcher loads, await everything and treat it\n // as a normal load. resolveDeferredData will return undefined if this\n // fetcher gets aborted, so we just leave result untouched and short circuit\n // below if that happens\n if (isDeferredResult(result)) {\n result =\n (await resolveDeferredData(result, fetchRequest.signal, true)) ||\n result;\n }\n\n // We can delete this so long as we weren't aborted by our our own fetcher\n // re-load which would have put _new_ controller is in fetchControllers\n if (fetchControllers.get(key) === abortController) {\n fetchControllers.delete(key);\n }\n\n if (fetchRequest.signal.aborted) {\n return;\n }\n\n // We don't want errors bubbling up or redirects followed for unmounted\n // fetchers, so short circuit here if it was removed from the UI\n if (deletedFetchers.has(key)) {\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n }\n\n // If the loader threw a redirect Response, start a new REPLACE navigation\n if (isRedirectResult(result)) {\n if (pendingNavigationLoadId > originatingLoadId) {\n // A new navigation was kicked off after our loader started, so that\n // should take precedence over this redirect navigation\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n } else {\n fetchRedirectIds.add(key);\n await startRedirectNavigation(fetchRequest, result, false, {\n preventScrollReset,\n });\n return;\n }\n }\n\n // Process any non-redirect errors thrown\n if (isErrorResult(result)) {\n setFetcherError(key, routeId, result.error);\n return;\n }\n\n invariant(!isDeferredResult(result), \"Unhandled fetcher deferred data\");\n\n // Put the fetcher back into an idle state\n updateFetcherState(key, getDoneFetcher(result.data));\n }\n\n /**\n * Utility function to handle redirects returned from an action or loader.\n * Normally, a redirect \"replaces\" the navigation that triggered it. So, for\n * example:\n *\n * - user is on /a\n * - user clicks a link to /b\n * - loader for /b redirects to /c\n *\n * In a non-JS app the browser would track the in-flight navigation to /b and\n * then replace it with /c when it encountered the redirect response. In\n * the end it would only ever update the URL bar with /c.\n *\n * In client-side routing using pushState/replaceState, we aim to emulate\n * this behavior and we also do not update history until the end of the\n * navigation (including processed redirects). This means that we never\n * actually touch history until we've processed redirects, so we just use\n * the history action from the original navigation (PUSH or REPLACE).\n */\n async function startRedirectNavigation(\n request: Request,\n redirect: RedirectResult,\n isNavigation: boolean,\n {\n submission,\n fetcherSubmission,\n preventScrollReset,\n replace,\n }: {\n submission?: Submission;\n fetcherSubmission?: Submission;\n preventScrollReset?: boolean;\n replace?: boolean;\n } = {}\n ) {\n if (redirect.response.headers.has(\"X-Remix-Revalidate\")) {\n isRevalidationRequired = true;\n }\n\n let location = redirect.response.headers.get(\"Location\");\n invariant(location, \"Expected a Location header on the redirect Response\");\n location = normalizeRedirectLocation(\n location,\n new URL(request.url),\n basename,\n init.history,\n );\n let redirectLocation = createLocation(state.location, location, {\n _isRedirect: true,\n });\n\n if (isBrowser) {\n let isDocumentReload = false;\n\n if (redirect.response.headers.has(\"X-Remix-Reload-Document\")) {\n // Hard reload if the response contained X-Remix-Reload-Document\n isDocumentReload = true;\n } else if (ABSOLUTE_URL_REGEX.test(location)) {\n const url = init.history.createURL(location);\n isDocumentReload =\n // Hard reload if it's an absolute URL to a new origin\n url.origin !== routerWindow.location.origin ||\n // Hard reload if it's an absolute URL that does not match our basename\n stripBasename(url.pathname, basename) == null;\n }\n\n if (isDocumentReload) {\n if (replace) {\n routerWindow.location.replace(location);\n } else {\n routerWindow.location.assign(location);\n }\n return;\n }\n }\n\n // There's no need to abort on redirects, since we don't detect the\n // redirect until the action/loaders have settled\n pendingNavigationController = null;\n\n let redirectHistoryAction =\n replace === true || redirect.response.headers.has(\"X-Remix-Replace\")\n ? HistoryAction.Replace\n : HistoryAction.Push;\n\n // Use the incoming submission if provided, fallback on the active one in\n // state.navigation\n let { formMethod, formAction, formEncType } = state.navigation;\n if (\n !submission &&\n !fetcherSubmission &&\n formMethod &&\n formAction &&\n formEncType\n ) {\n submission = getSubmissionFromNavigation(state.navigation);\n }\n\n // If this was a 307/308 submission we want to preserve the HTTP method and\n // re-submit the GET/POST/PUT/PATCH/DELETE as a submission navigation to the\n // redirected location\n let activeSubmission = submission || fetcherSubmission;\n if (\n redirectPreserveMethodStatusCodes.has(redirect.response.status) &&\n activeSubmission &&\n isMutationMethod(activeSubmission.formMethod)\n ) {\n await startNavigation(redirectHistoryAction, redirectLocation, {\n submission: {\n ...activeSubmission,\n formAction: location,\n },\n // Preserve these flags across redirects\n preventScrollReset: preventScrollReset || pendingPreventScrollReset,\n enableViewTransition: isNavigation\n ? pendingViewTransitionEnabled\n : undefined,\n });\n } else {\n // If we have a navigation submission, we will preserve it through the\n // redirect navigation\n let overrideNavigation = getLoadingNavigation(\n redirectLocation,\n submission\n );\n await startNavigation(redirectHistoryAction, redirectLocation, {\n overrideNavigation,\n // Send fetcher submissions through for shouldRevalidate\n fetcherSubmission,\n // Preserve these flags across redirects\n preventScrollReset: preventScrollReset || pendingPreventScrollReset,\n enableViewTransition: isNavigation\n ? pendingViewTransitionEnabled\n : undefined,\n });\n }\n }\n\n // Utility wrapper for calling dataStrategy client-side without having to\n // pass around the manifest, mapRouteProperties, etc.\n async function callDataStrategy(\n type: \"loader\" | \"action\",\n state: RouterState,\n request: Request,\n matchesToLoad: AgnosticDataRouteMatch[],\n matches: AgnosticDataRouteMatch[],\n fetcherKey: string | null\n ): Promise> {\n let results: Record;\n let dataResults: Record = {};\n try {\n results = await callDataStrategyImpl(\n dataStrategyImpl,\n type,\n state,\n request,\n matchesToLoad,\n matches,\n fetcherKey,\n manifest,\n mapRouteProperties\n );\n } catch (e) {\n // If the outer dataStrategy method throws, just return the error for all\n // matches - and it'll naturally bubble to the root\n matchesToLoad.forEach((m) => {\n dataResults[m.route.id] = {\n type: ResultType.error,\n error: e,\n };\n });\n return dataResults;\n }\n\n for (let [routeId, result] of Object.entries(results)) {\n if (isRedirectDataStrategyResultResult(result)) {\n let response = result.result as Response;\n dataResults[routeId] = {\n type: ResultType.redirect,\n response: normalizeRelativeRoutingRedirectResponse(\n response,\n request,\n routeId,\n matches,\n basename,\n future.v7_relativeSplatPath\n ),\n };\n } else {\n dataResults[routeId] = await convertDataStrategyResultToDataResult(\n result\n );\n }\n }\n\n return dataResults;\n }\n\n async function callLoadersAndMaybeResolveData(\n state: RouterState,\n matches: AgnosticDataRouteMatch[],\n matchesToLoad: AgnosticDataRouteMatch[],\n fetchersToLoad: RevalidatingFetcher[],\n request: Request\n ) {\n let currentMatches = state.matches;\n\n // Kick off loaders and fetchers in parallel\n let loaderResultsPromise = callDataStrategy(\n \"loader\",\n state,\n request,\n matchesToLoad,\n matches,\n null\n );\n\n let fetcherResultsPromise = Promise.all(\n fetchersToLoad.map(async (f) => {\n if (f.matches && f.match && f.controller) {\n let results = await callDataStrategy(\n \"loader\",\n state,\n createClientSideRequest(init.history, f.path, f.controller.signal),\n [f.match],\n f.matches,\n f.key\n );\n let result = results[f.match.route.id];\n // Fetcher results are keyed by fetcher key from here on out, not routeId\n return { [f.key]: result };\n } else {\n return Promise.resolve({\n [f.key]: {\n type: ResultType.error,\n error: getInternalRouterError(404, {\n pathname: f.path,\n }),\n } as ErrorResult,\n });\n }\n })\n );\n\n let loaderResults = await loaderResultsPromise;\n let fetcherResults = (await fetcherResultsPromise).reduce(\n (acc, r) => Object.assign(acc, r),\n {}\n );\n\n await Promise.all([\n resolveNavigationDeferredResults(\n matches,\n loaderResults,\n request.signal,\n currentMatches,\n state.loaderData\n ),\n resolveFetcherDeferredResults(matches, fetcherResults, fetchersToLoad),\n ]);\n\n return {\n loaderResults,\n fetcherResults,\n };\n }\n\n function interruptActiveLoads() {\n // Every interruption triggers a revalidation\n isRevalidationRequired = true;\n\n // Cancel pending route-level deferreds and mark cancelled routes for\n // revalidation\n cancelledDeferredRoutes.push(...cancelActiveDeferreds());\n\n // Abort in-flight fetcher loads\n fetchLoadMatches.forEach((_, key) => {\n if (fetchControllers.has(key)) {\n cancelledFetcherLoads.add(key);\n }\n abortFetcher(key);\n });\n }\n\n function updateFetcherState(\n key: string,\n fetcher: Fetcher,\n opts: { flushSync?: boolean } = {}\n ) {\n state.fetchers.set(key, fetcher);\n updateState(\n { fetchers: new Map(state.fetchers) },\n { flushSync: (opts && opts.flushSync) === true }\n );\n }\n\n function setFetcherError(\n key: string,\n routeId: string,\n error: any,\n opts: { flushSync?: boolean } = {}\n ) {\n let boundaryMatch = findNearestBoundary(state.matches, routeId);\n deleteFetcher(key);\n updateState(\n {\n errors: {\n [boundaryMatch.route.id]: error,\n },\n fetchers: new Map(state.fetchers),\n },\n { flushSync: (opts && opts.flushSync) === true }\n );\n }\n\n function getFetcher(key: string): Fetcher {\n activeFetchers.set(key, (activeFetchers.get(key) || 0) + 1);\n // If this fetcher was previously marked for deletion, unmark it since we\n // have a new instance\n if (deletedFetchers.has(key)) {\n deletedFetchers.delete(key);\n }\n return state.fetchers.get(key) || IDLE_FETCHER;\n }\n\n function deleteFetcher(key: string): void {\n let fetcher = state.fetchers.get(key);\n // Don't abort the controller if this is a deletion of a fetcher.submit()\n // in it's loading phase since - we don't want to abort the corresponding\n // revalidation and want them to complete and land\n if (\n fetchControllers.has(key) &&\n !(fetcher && fetcher.state === \"loading\" && fetchReloadIds.has(key))\n ) {\n abortFetcher(key);\n }\n fetchLoadMatches.delete(key);\n fetchReloadIds.delete(key);\n fetchRedirectIds.delete(key);\n\n // If we opted into the flag we can clear this now since we're calling\n // deleteFetcher() at the end of updateState() and we've already handed the\n // deleted fetcher keys off to the data layer.\n // If not, we're eagerly calling deleteFetcher() and we need to keep this\n // Set populated until the next updateState call, and we'll clear\n // `deletedFetchers` then\n if (future.v7_fetcherPersist) {\n deletedFetchers.delete(key);\n }\n\n cancelledFetcherLoads.delete(key);\n state.fetchers.delete(key);\n }\n\n function deleteFetcherAndUpdateState(key: string): void {\n let count = (activeFetchers.get(key) || 0) - 1;\n if (count <= 0) {\n activeFetchers.delete(key);\n deletedFetchers.add(key);\n if (!future.v7_fetcherPersist) {\n deleteFetcher(key);\n }\n } else {\n activeFetchers.set(key, count);\n }\n\n updateState({ fetchers: new Map(state.fetchers) });\n }\n\n function abortFetcher(key: string) {\n let controller = fetchControllers.get(key);\n if (controller) {\n controller.abort();\n fetchControllers.delete(key);\n }\n }\n\n function markFetchersDone(keys: string[]) {\n for (let key of keys) {\n let fetcher = getFetcher(key);\n let doneFetcher = getDoneFetcher(fetcher.data);\n state.fetchers.set(key, doneFetcher);\n }\n }\n\n function markFetchRedirectsDone(): boolean {\n let doneKeys = [];\n let updatedFetchers = false;\n for (let key of fetchRedirectIds) {\n let fetcher = state.fetchers.get(key);\n invariant(fetcher, `Expected fetcher: ${key}`);\n if (fetcher.state === \"loading\") {\n fetchRedirectIds.delete(key);\n doneKeys.push(key);\n updatedFetchers = true;\n }\n }\n markFetchersDone(doneKeys);\n return updatedFetchers;\n }\n\n function abortStaleFetchLoads(landedId: number): boolean {\n let yeetedKeys = [];\n for (let [key, id] of fetchReloadIds) {\n if (id < landedId) {\n let fetcher = state.fetchers.get(key);\n invariant(fetcher, `Expected fetcher: ${key}`);\n if (fetcher.state === \"loading\") {\n abortFetcher(key);\n fetchReloadIds.delete(key);\n yeetedKeys.push(key);\n }\n }\n }\n markFetchersDone(yeetedKeys);\n return yeetedKeys.length > 0;\n }\n\n function getBlocker(key: string, fn: BlockerFunction) {\n let blocker: Blocker = state.blockers.get(key) || IDLE_BLOCKER;\n\n if (blockerFunctions.get(key) !== fn) {\n blockerFunctions.set(key, fn);\n }\n\n return blocker;\n }\n\n function deleteBlocker(key: string) {\n state.blockers.delete(key);\n blockerFunctions.delete(key);\n }\n\n // Utility function to update blockers, ensuring valid state transitions\n function updateBlocker(key: string, newBlocker: Blocker) {\n let blocker = state.blockers.get(key) || IDLE_BLOCKER;\n\n // Poor mans state machine :)\n // https://mermaid.live/edit#pako:eNqVkc9OwzAMxl8l8nnjAYrEtDIOHEBIgwvKJTReGy3_lDpIqO27k6awMG0XcrLlnz87nwdonESogKXXBuE79rq75XZO3-yHds0RJVuv70YrPlUrCEe2HfrORS3rubqZfuhtpg5C9wk5tZ4VKcRUq88q9Z8RS0-48cE1iHJkL0ugbHuFLus9L6spZy8nX9MP2CNdomVaposqu3fGayT8T8-jJQwhepo_UtpgBQaDEUom04dZhAN1aJBDlUKJBxE1ceB2Smj0Mln-IBW5AFU2dwUiktt_2Qaq2dBfaKdEup85UV7Yd-dKjlnkabl2Pvr0DTkTreM\n invariant(\n (blocker.state === \"unblocked\" && newBlocker.state === \"blocked\") ||\n (blocker.state === \"blocked\" && newBlocker.state === \"blocked\") ||\n (blocker.state === \"blocked\" && newBlocker.state === \"proceeding\") ||\n (blocker.state === \"blocked\" && newBlocker.state === \"unblocked\") ||\n (blocker.state === \"proceeding\" && newBlocker.state === \"unblocked\"),\n `Invalid blocker state transition: ${blocker.state} -> ${newBlocker.state}`\n );\n\n let blockers = new Map(state.blockers);\n blockers.set(key, newBlocker);\n updateState({ blockers });\n }\n\n function shouldBlockNavigation({\n currentLocation,\n nextLocation,\n historyAction,\n }: {\n currentLocation: Location;\n nextLocation: Location;\n historyAction: HistoryAction;\n }): string | undefined {\n if (blockerFunctions.size === 0) {\n return;\n }\n\n // We ony support a single active blocker at the moment since we don't have\n // any compelling use cases for multi-blocker yet\n if (blockerFunctions.size > 1) {\n warning(false, \"A router only supports one blocker at a time\");\n }\n\n let entries = Array.from(blockerFunctions.entries());\n let [blockerKey, blockerFunction] = entries[entries.length - 1];\n let blocker = state.blockers.get(blockerKey);\n\n if (blocker && blocker.state === \"proceeding\") {\n // If the blocker is currently proceeding, we don't need to re-check\n // it and can let this navigation continue\n return;\n }\n\n // At this point, we know we're unblocked/blocked so we need to check the\n // user-provided blocker function\n if (blockerFunction({ currentLocation, nextLocation, historyAction })) {\n return blockerKey;\n }\n }\n\n function handleNavigational404(pathname: string) {\n let error = getInternalRouterError(404, { pathname });\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let { matches, route } = getShortCircuitMatches(routesToUse);\n\n // Cancel all pending deferred on 404s since we don't keep any routes\n cancelActiveDeferreds();\n\n return { notFoundMatches: matches, route, error };\n }\n\n function cancelActiveDeferreds(\n predicate?: (routeId: string) => boolean\n ): string[] {\n let cancelledRouteIds: string[] = [];\n activeDeferreds.forEach((dfd, routeId) => {\n if (!predicate || predicate(routeId)) {\n // Cancel the deferred - but do not remove from activeDeferreds here -\n // we rely on the subscribers to do that so our tests can assert proper\n // cleanup via _internalActiveDeferreds\n dfd.cancel();\n cancelledRouteIds.push(routeId);\n activeDeferreds.delete(routeId);\n }\n });\n return cancelledRouteIds;\n }\n\n // Opt in to capturing and reporting scroll positions during navigations,\n // used by the component\n function enableScrollRestoration(\n positions: Record,\n getPosition: GetScrollPositionFunction,\n getKey?: GetScrollRestorationKeyFunction\n ) {\n savedScrollPositions = positions;\n getScrollPosition = getPosition;\n getScrollRestorationKey = getKey || null;\n\n // Perform initial hydration scroll restoration, since we miss the boat on\n // the initial updateState() because we've not yet rendered \n // and therefore have no savedScrollPositions available\n if (!initialScrollRestored && state.navigation === IDLE_NAVIGATION) {\n initialScrollRestored = true;\n let y = getSavedScrollPosition(state.location, state.matches);\n if (y != null) {\n updateState({ restoreScrollPosition: y });\n }\n }\n\n return () => {\n savedScrollPositions = null;\n getScrollPosition = null;\n getScrollRestorationKey = null;\n };\n }\n\n function getScrollKey(location: Location, matches: AgnosticDataRouteMatch[]) {\n if (getScrollRestorationKey) {\n let key = getScrollRestorationKey(\n location,\n matches.map((m) => convertRouteMatchToUiMatch(m, state.loaderData))\n );\n return key || location.key;\n }\n return location.key;\n }\n\n function saveScrollPosition(\n location: Location,\n matches: AgnosticDataRouteMatch[]\n ): void {\n if (savedScrollPositions && getScrollPosition) {\n let key = getScrollKey(location, matches);\n savedScrollPositions[key] = getScrollPosition();\n }\n }\n\n function getSavedScrollPosition(\n location: Location,\n matches: AgnosticDataRouteMatch[]\n ): number | null {\n if (savedScrollPositions) {\n let key = getScrollKey(location, matches);\n let y = savedScrollPositions[key];\n if (typeof y === \"number\") {\n return y;\n }\n }\n return null;\n }\n\n function checkFogOfWar(\n matches: AgnosticDataRouteMatch[] | null,\n routesToUse: AgnosticDataRouteObject[],\n pathname: string\n ): { active: boolean; matches: AgnosticDataRouteMatch[] | null } {\n if (patchRoutesOnNavigationImpl) {\n if (!matches) {\n let fogMatches = matchRoutesImpl(\n routesToUse,\n pathname,\n basename,\n true\n );\n\n return { active: true, matches: fogMatches || [] };\n } else {\n if (Object.keys(matches[0].params).length > 0) {\n // If we matched a dynamic param or a splat, it might only be because\n // we haven't yet discovered other routes that would match with a\n // higher score. Call patchRoutesOnNavigation just to be sure\n let partialMatches = matchRoutesImpl(\n routesToUse,\n pathname,\n basename,\n true\n );\n return { active: true, matches: partialMatches };\n }\n }\n }\n\n return { active: false, matches: null };\n }\n\n type DiscoverRoutesSuccessResult = {\n type: \"success\";\n matches: AgnosticDataRouteMatch[] | null;\n };\n type DiscoverRoutesErrorResult = {\n type: \"error\";\n error: any;\n partialMatches: AgnosticDataRouteMatch[];\n };\n type DiscoverRoutesAbortedResult = { type: \"aborted\" };\n type DiscoverRoutesResult =\n | DiscoverRoutesSuccessResult\n | DiscoverRoutesErrorResult\n | DiscoverRoutesAbortedResult;\n\n async function discoverRoutes(\n matches: AgnosticDataRouteMatch[],\n pathname: string,\n signal: AbortSignal,\n fetcherKey?: string\n ): Promise {\n if (!patchRoutesOnNavigationImpl) {\n return { type: \"success\", matches };\n }\n\n let partialMatches: AgnosticDataRouteMatch[] | null = matches;\n while (true) {\n let isNonHMR = inFlightDataRoutes == null;\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let localManifest = manifest;\n try {\n await patchRoutesOnNavigationImpl({\n signal,\n path: pathname,\n matches: partialMatches,\n fetcherKey,\n patch: (routeId, children) => {\n if (signal.aborted) return;\n patchRoutesImpl(\n routeId,\n children,\n routesToUse,\n localManifest,\n mapRouteProperties\n );\n },\n });\n } catch (e) {\n return { type: \"error\", error: e, partialMatches };\n } finally {\n // If we are not in the middle of an HMR revalidation and we changed the\n // routes, provide a new identity so when we `updateState` at the end of\n // this navigation/fetch `router.routes` will be a new identity and\n // trigger a re-run of memoized `router.routes` dependencies.\n // HMR will already update the identity and reflow when it lands\n // `inFlightDataRoutes` in `completeNavigation`\n if (isNonHMR && !signal.aborted) {\n dataRoutes = [...dataRoutes];\n }\n }\n\n if (signal.aborted) {\n return { type: \"aborted\" };\n }\n\n let newMatches = matchRoutes(routesToUse, pathname, basename);\n if (newMatches) {\n return { type: \"success\", matches: newMatches };\n }\n\n let newPartialMatches = matchRoutesImpl(\n routesToUse,\n pathname,\n basename,\n true\n );\n\n // Avoid loops if the second pass results in the same partial matches\n if (\n !newPartialMatches ||\n (partialMatches.length === newPartialMatches.length &&\n partialMatches.every(\n (m, i) => m.route.id === newPartialMatches![i].route.id\n ))\n ) {\n return { type: \"success\", matches: null };\n }\n\n partialMatches = newPartialMatches;\n }\n }\n\n function _internalSetRoutes(newRoutes: AgnosticDataRouteObject[]) {\n manifest = {};\n inFlightDataRoutes = convertRoutesToDataRoutes(\n newRoutes,\n mapRouteProperties,\n undefined,\n manifest\n );\n }\n\n function patchRoutes(\n routeId: string | null,\n children: AgnosticRouteObject[]\n ): void {\n let isNonHMR = inFlightDataRoutes == null;\n let routesToUse = inFlightDataRoutes || dataRoutes;\n patchRoutesImpl(\n routeId,\n children,\n routesToUse,\n manifest,\n mapRouteProperties\n );\n\n // If we are not in the middle of an HMR revalidation and we changed the\n // routes, provide a new identity and trigger a reflow via `updateState`\n // to re-run memoized `router.routes` dependencies.\n // HMR will already update the identity and reflow when it lands\n // `inFlightDataRoutes` in `completeNavigation`\n if (isNonHMR) {\n dataRoutes = [...dataRoutes];\n updateState({});\n }\n }\n\n router = {\n get basename() {\n return basename;\n },\n get future() {\n return future;\n },\n get state() {\n return state;\n },\n get routes() {\n return dataRoutes;\n },\n get window() {\n return routerWindow;\n },\n initialize,\n subscribe,\n enableScrollRestoration,\n navigate,\n fetch,\n revalidate,\n // Passthrough to history-aware createHref used by useHref so we get proper\n // hash-aware URLs in DOM paths\n createHref: (to: To) => init.history.createHref(to),\n encodeLocation: (to: To) => init.history.encodeLocation(to),\n getFetcher,\n deleteFetcher: deleteFetcherAndUpdateState,\n dispose,\n getBlocker,\n deleteBlocker,\n patchRoutes,\n _internalFetchControllers: fetchControllers,\n _internalActiveDeferreds: activeDeferreds,\n // TODO: Remove setRoutes, it's temporary to avoid dealing with\n // updating the tree while validating the update algorithm.\n _internalSetRoutes,\n };\n\n return router;\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region createStaticHandler\n////////////////////////////////////////////////////////////////////////////////\n\nexport const UNSAFE_DEFERRED_SYMBOL = Symbol(\"deferred\");\n\n/**\n * Future flags to toggle new feature behavior\n */\nexport interface StaticHandlerFutureConfig {\n v7_relativeSplatPath: boolean;\n v7_throwAbortReason: boolean;\n}\n\nexport interface CreateStaticHandlerOptions {\n basename?: string;\n /**\n * @deprecated Use `mapRouteProperties` instead\n */\n detectErrorBoundary?: DetectErrorBoundaryFunction;\n mapRouteProperties?: MapRoutePropertiesFunction;\n future?: Partial;\n}\n\nexport function createStaticHandler(\n routes: AgnosticRouteObject[],\n opts?: CreateStaticHandlerOptions\n): StaticHandler {\n invariant(\n routes.length > 0,\n \"You must provide a non-empty routes array to createStaticHandler\"\n );\n\n let manifest: RouteManifest = {};\n let basename = (opts ? opts.basename : null) || \"/\";\n let mapRouteProperties: MapRoutePropertiesFunction;\n if (opts?.mapRouteProperties) {\n mapRouteProperties = opts.mapRouteProperties;\n } else if (opts?.detectErrorBoundary) {\n // If they are still using the deprecated version, wrap it with the new API\n let detectErrorBoundary = opts.detectErrorBoundary;\n mapRouteProperties = (route) => ({\n hasErrorBoundary: detectErrorBoundary(route),\n });\n } else {\n mapRouteProperties = defaultMapRouteProperties;\n }\n // Config driven behavior flags\n let future: StaticHandlerFutureConfig = {\n v7_relativeSplatPath: false,\n v7_throwAbortReason: false,\n ...(opts ? opts.future : null),\n };\n\n let dataRoutes = convertRoutesToDataRoutes(\n routes,\n mapRouteProperties,\n undefined,\n manifest\n );\n\n /**\n * The query() method is intended for document requests, in which we want to\n * call an optional action and potentially multiple loaders for all nested\n * routes. It returns a StaticHandlerContext object, which is very similar\n * to the router state (location, loaderData, actionData, errors, etc.) and\n * also adds SSR-specific information such as the statusCode and headers\n * from action/loaders Responses.\n *\n * It _should_ never throw and should report all errors through the\n * returned context.errors object, properly associating errors to their error\n * boundary. Additionally, it tracks _deepestRenderedBoundaryId which can be\n * used to emulate React error boundaries during SSr by performing a second\n * pass only down to the boundaryId.\n *\n * The one exception where we do not return a StaticHandlerContext is when a\n * redirect response is returned or thrown from any action/loader. We\n * propagate that out and return the raw Response so the HTTP server can\n * return it directly.\n *\n * - `opts.requestContext` is an optional server context that will be passed\n * to actions/loaders in the `context` parameter\n * - `opts.skipLoaderErrorBubbling` is an optional parameter that will prevent\n * the bubbling of errors which allows single-fetch-type implementations\n * where the client will handle the bubbling and we may need to return data\n * for the handling route\n */\n async function query(\n request: Request,\n {\n requestContext,\n skipLoaderErrorBubbling,\n dataStrategy,\n }: {\n requestContext?: unknown;\n skipLoaderErrorBubbling?: boolean;\n dataStrategy?: DataStrategyFunction;\n } = {}\n ): Promise {\n let url = new URL(request.url);\n let method = request.method;\n let location = createLocation(\"\", createPath(url), null, \"default\");\n let matches = matchRoutes(dataRoutes, location, basename);\n\n // SSR supports HEAD requests while SPA doesn't\n if (!isValidMethod(method) && method !== \"HEAD\") {\n let error = getInternalRouterError(405, { method });\n let { matches: methodNotAllowedMatches, route } =\n getShortCircuitMatches(dataRoutes);\n return {\n basename,\n location,\n matches: methodNotAllowedMatches,\n loaderData: {},\n actionData: null,\n errors: {\n [route.id]: error,\n },\n statusCode: error.status,\n loaderHeaders: {},\n actionHeaders: {},\n activeDeferreds: null,\n };\n } else if (!matches) {\n let error = getInternalRouterError(404, { pathname: location.pathname });\n let { matches: notFoundMatches, route } =\n getShortCircuitMatches(dataRoutes);\n return {\n basename,\n location,\n matches: notFoundMatches,\n loaderData: {},\n actionData: null,\n errors: {\n [route.id]: error,\n },\n statusCode: error.status,\n loaderHeaders: {},\n actionHeaders: {},\n activeDeferreds: null,\n };\n }\n\n let result = await queryImpl(\n request,\n location,\n matches,\n requestContext,\n dataStrategy || null,\n skipLoaderErrorBubbling === true,\n null\n );\n if (isResponse(result)) {\n return result;\n }\n\n // When returning StaticHandlerContext, we patch back in the location here\n // since we need it for React Context. But this helps keep our submit and\n // loadRouteData operating on a Request instead of a Location\n return { location, basename, ...result };\n }\n\n /**\n * The queryRoute() method is intended for targeted route requests, either\n * for fetch ?_data requests or resource route requests. In this case, we\n * are only ever calling a single action or loader, and we are returning the\n * returned value directly. In most cases, this will be a Response returned\n * from the action/loader, but it may be a primitive or other value as well -\n * and in such cases the calling context should handle that accordingly.\n *\n * We do respect the throw/return differentiation, so if an action/loader\n * throws, then this method will throw the value. This is important so we\n * can do proper boundary identification in Remix where a thrown Response\n * must go to the Catch Boundary but a returned Response is happy-path.\n *\n * One thing to note is that any Router-initiated Errors that make sense\n * to associate with a status code will be thrown as an ErrorResponse\n * instance which include the raw Error, such that the calling context can\n * serialize the error as they see fit while including the proper response\n * code. Examples here are 404 and 405 errors that occur prior to reaching\n * any user-defined loaders.\n *\n * - `opts.routeId` allows you to specify the specific route handler to call.\n * If not provided the handler will determine the proper route by matching\n * against `request.url`\n * - `opts.requestContext` is an optional server context that will be passed\n * to actions/loaders in the `context` parameter\n */\n async function queryRoute(\n request: Request,\n {\n routeId,\n requestContext,\n dataStrategy,\n }: {\n requestContext?: unknown;\n routeId?: string;\n dataStrategy?: DataStrategyFunction;\n } = {}\n ): Promise {\n let url = new URL(request.url);\n let method = request.method;\n let location = createLocation(\"\", createPath(url), null, \"default\");\n let matches = matchRoutes(dataRoutes, location, basename);\n\n // SSR supports HEAD requests while SPA doesn't\n if (!isValidMethod(method) && method !== \"HEAD\" && method !== \"OPTIONS\") {\n throw getInternalRouterError(405, { method });\n } else if (!matches) {\n throw getInternalRouterError(404, { pathname: location.pathname });\n }\n\n let match = routeId\n ? matches.find((m) => m.route.id === routeId)\n : getTargetMatch(matches, location);\n\n if (routeId && !match) {\n throw getInternalRouterError(403, {\n pathname: location.pathname,\n routeId,\n });\n } else if (!match) {\n // This should never hit I don't think?\n throw getInternalRouterError(404, { pathname: location.pathname });\n }\n\n let result = await queryImpl(\n request,\n location,\n matches,\n requestContext,\n dataStrategy || null,\n false,\n match\n );\n\n if (isResponse(result)) {\n return result;\n }\n\n let error = result.errors ? Object.values(result.errors)[0] : undefined;\n if (error !== undefined) {\n // If we got back result.errors, that means the loader/action threw\n // _something_ that wasn't a Response, but it's not guaranteed/required\n // to be an `instanceof Error` either, so we have to use throw here to\n // preserve the \"error\" state outside of queryImpl.\n throw error;\n }\n\n // Pick off the right state value to return\n if (result.actionData) {\n return Object.values(result.actionData)[0];\n }\n\n if (result.loaderData) {\n let data = Object.values(result.loaderData)[0];\n if (result.activeDeferreds?.[match.route.id]) {\n data[UNSAFE_DEFERRED_SYMBOL] = result.activeDeferreds[match.route.id];\n }\n return data;\n }\n\n return undefined;\n }\n\n async function queryImpl(\n request: Request,\n location: Location,\n matches: AgnosticDataRouteMatch[],\n requestContext: unknown,\n dataStrategy: DataStrategyFunction | null,\n skipLoaderErrorBubbling: boolean,\n routeMatch: AgnosticDataRouteMatch | null\n ): Promise | Response> {\n invariant(\n request.signal,\n \"query()/queryRoute() requests must contain an AbortController signal\"\n );\n\n try {\n if (isMutationMethod(request.method.toLowerCase())) {\n let result = await submit(\n request,\n matches,\n routeMatch || getTargetMatch(matches, location),\n requestContext,\n dataStrategy,\n skipLoaderErrorBubbling,\n routeMatch != null\n );\n return result;\n }\n\n let result = await loadRouteData(\n request,\n matches,\n requestContext,\n dataStrategy,\n skipLoaderErrorBubbling,\n routeMatch\n );\n return isResponse(result)\n ? result\n : {\n ...result,\n actionData: null,\n actionHeaders: {},\n };\n } catch (e) {\n // If the user threw/returned a Response in callLoaderOrAction for a\n // `queryRoute` call, we throw the `DataStrategyResult` to bail out early\n // and then return or throw the raw Response here accordingly\n if (isDataStrategyResult(e) && isResponse(e.result)) {\n if (e.type === ResultType.error) {\n throw e.result;\n }\n return e.result;\n }\n // Redirects are always returned since they don't propagate to catch\n // boundaries\n if (isRedirectResponse(e)) {\n return e;\n }\n throw e;\n }\n }\n\n async function submit(\n request: Request,\n matches: AgnosticDataRouteMatch[],\n actionMatch: AgnosticDataRouteMatch,\n requestContext: unknown,\n dataStrategy: DataStrategyFunction | null,\n skipLoaderErrorBubbling: boolean,\n isRouteRequest: boolean\n ): Promise | Response> {\n let result: DataResult;\n\n if (!actionMatch.route.action && !actionMatch.route.lazy) {\n let error = getInternalRouterError(405, {\n method: request.method,\n pathname: new URL(request.url).pathname,\n routeId: actionMatch.route.id,\n });\n if (isRouteRequest) {\n throw error;\n }\n result = {\n type: ResultType.error,\n error,\n };\n } else {\n let results = await callDataStrategy(\n \"action\",\n request,\n [actionMatch],\n matches,\n isRouteRequest,\n requestContext,\n dataStrategy\n );\n result = results[actionMatch.route.id];\n\n if (request.signal.aborted) {\n throwStaticHandlerAbortedError(request, isRouteRequest, future);\n }\n }\n\n if (isRedirectResult(result)) {\n // Uhhhh - this should never happen, we should always throw these from\n // callLoaderOrAction, but the type narrowing here keeps TS happy and we\n // can get back on the \"throw all redirect responses\" train here should\n // this ever happen :/\n throw new Response(null, {\n status: result.response.status,\n headers: {\n Location: result.response.headers.get(\"Location\")!,\n },\n });\n }\n\n if (isDeferredResult(result)) {\n let error = getInternalRouterError(400, { type: \"defer-action\" });\n if (isRouteRequest) {\n throw error;\n }\n result = {\n type: ResultType.error,\n error,\n };\n }\n\n if (isRouteRequest) {\n // Note: This should only be non-Response values if we get here, since\n // isRouteRequest should throw any Response received in callLoaderOrAction\n if (isErrorResult(result)) {\n throw result.error;\n }\n\n return {\n matches: [actionMatch],\n loaderData: {},\n actionData: { [actionMatch.route.id]: result.data },\n errors: null,\n // Note: statusCode + headers are unused here since queryRoute will\n // return the raw Response or value\n statusCode: 200,\n loaderHeaders: {},\n actionHeaders: {},\n activeDeferreds: null,\n };\n }\n\n // Create a GET request for the loaders\n let loaderRequest = new Request(request.url, {\n headers: request.headers,\n redirect: request.redirect,\n signal: request.signal,\n });\n\n if (isErrorResult(result)) {\n // Store off the pending error - we use it to determine which loaders\n // to call and will commit it when we complete the navigation\n let boundaryMatch = skipLoaderErrorBubbling\n ? actionMatch\n : findNearestBoundary(matches, actionMatch.route.id);\n\n let context = await loadRouteData(\n loaderRequest,\n matches,\n requestContext,\n dataStrategy,\n skipLoaderErrorBubbling,\n null,\n [boundaryMatch.route.id, result]\n );\n\n // action status codes take precedence over loader status codes\n return {\n ...context,\n statusCode: isRouteErrorResponse(result.error)\n ? result.error.status\n : result.statusCode != null\n ? result.statusCode\n : 500,\n actionData: null,\n actionHeaders: {\n ...(result.headers ? { [actionMatch.route.id]: result.headers } : {}),\n },\n };\n }\n\n let context = await loadRouteData(\n loaderRequest,\n matches,\n requestContext,\n dataStrategy,\n skipLoaderErrorBubbling,\n null\n );\n\n return {\n ...context,\n actionData: {\n [actionMatch.route.id]: result.data,\n },\n // action status codes take precedence over loader status codes\n ...(result.statusCode ? { statusCode: result.statusCode } : {}),\n actionHeaders: result.headers\n ? { [actionMatch.route.id]: result.headers }\n : {},\n };\n }\n\n async function loadRouteData(\n request: Request,\n matches: AgnosticDataRouteMatch[],\n requestContext: unknown,\n dataStrategy: DataStrategyFunction | null,\n skipLoaderErrorBubbling: boolean,\n routeMatch: AgnosticDataRouteMatch | null,\n pendingActionResult?: PendingActionResult\n ): Promise<\n | Omit<\n StaticHandlerContext,\n \"location\" | \"basename\" | \"actionData\" | \"actionHeaders\"\n >\n | Response\n > {\n let isRouteRequest = routeMatch != null;\n\n // Short circuit if we have no loaders to run (queryRoute())\n if (\n isRouteRequest &&\n !routeMatch?.route.loader &&\n !routeMatch?.route.lazy\n ) {\n throw getInternalRouterError(400, {\n method: request.method,\n pathname: new URL(request.url).pathname,\n routeId: routeMatch?.route.id,\n });\n }\n\n let requestMatches = routeMatch\n ? [routeMatch]\n : pendingActionResult && isErrorResult(pendingActionResult[1])\n ? getLoaderMatchesUntilBoundary(matches, pendingActionResult[0])\n : matches;\n let matchesToLoad = requestMatches.filter(\n (m) => m.route.loader || m.route.lazy\n );\n\n // Short circuit if we have no loaders to run (query())\n if (matchesToLoad.length === 0) {\n return {\n matches,\n // Add a null for all matched routes for proper revalidation on the client\n loaderData: matches.reduce(\n (acc, m) => Object.assign(acc, { [m.route.id]: null }),\n {}\n ),\n errors:\n pendingActionResult && isErrorResult(pendingActionResult[1])\n ? {\n [pendingActionResult[0]]: pendingActionResult[1].error,\n }\n : null,\n statusCode: 200,\n loaderHeaders: {},\n activeDeferreds: null,\n };\n }\n\n let results = await callDataStrategy(\n \"loader\",\n request,\n matchesToLoad,\n matches,\n isRouteRequest,\n requestContext,\n dataStrategy\n );\n\n if (request.signal.aborted) {\n throwStaticHandlerAbortedError(request, isRouteRequest, future);\n }\n\n // Process and commit output from loaders\n let activeDeferreds = new Map();\n let context = processRouteLoaderData(\n matches,\n results,\n pendingActionResult,\n activeDeferreds,\n skipLoaderErrorBubbling\n );\n\n // Add a null for any non-loader matches for proper revalidation on the client\n let executedLoaders = new Set(\n matchesToLoad.map((match) => match.route.id)\n );\n matches.forEach((match) => {\n if (!executedLoaders.has(match.route.id)) {\n context.loaderData[match.route.id] = null;\n }\n });\n\n return {\n ...context,\n matches,\n activeDeferreds:\n activeDeferreds.size > 0\n ? Object.fromEntries(activeDeferreds.entries())\n : null,\n };\n }\n\n // Utility wrapper for calling dataStrategy server-side without having to\n // pass around the manifest, mapRouteProperties, etc.\n async function callDataStrategy(\n type: \"loader\" | \"action\",\n request: Request,\n matchesToLoad: AgnosticDataRouteMatch[],\n matches: AgnosticDataRouteMatch[],\n isRouteRequest: boolean,\n requestContext: unknown,\n dataStrategy: DataStrategyFunction | null\n ): Promise> {\n let results = await callDataStrategyImpl(\n dataStrategy || defaultDataStrategy,\n type,\n null,\n request,\n matchesToLoad,\n matches,\n null,\n manifest,\n mapRouteProperties,\n requestContext\n );\n\n let dataResults: Record = {};\n await Promise.all(\n matches.map(async (match) => {\n if (!(match.route.id in results)) {\n return;\n }\n let result = results[match.route.id];\n if (isRedirectDataStrategyResultResult(result)) {\n let response = result.result as Response;\n // Throw redirects and let the server handle them with an HTTP redirect\n throw normalizeRelativeRoutingRedirectResponse(\n response,\n request,\n match.route.id,\n matches,\n basename,\n future.v7_relativeSplatPath\n );\n }\n if (isResponse(result.result) && isRouteRequest) {\n // For SSR single-route requests, we want to hand Responses back\n // directly without unwrapping\n throw result;\n }\n\n dataResults[match.route.id] =\n await convertDataStrategyResultToDataResult(result);\n })\n );\n return dataResults;\n }\n\n return {\n dataRoutes,\n query,\n queryRoute,\n };\n}\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Helpers\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Given an existing StaticHandlerContext and an error thrown at render time,\n * provide an updated StaticHandlerContext suitable for a second SSR render\n */\nexport function getStaticContextFromError(\n routes: AgnosticDataRouteObject[],\n context: StaticHandlerContext,\n error: any\n) {\n let newContext: StaticHandlerContext = {\n ...context,\n statusCode: isRouteErrorResponse(error) ? error.status : 500,\n errors: {\n [context._deepestRenderedBoundaryId || routes[0].id]: error,\n },\n };\n return newContext;\n}\n\nfunction throwStaticHandlerAbortedError(\n request: Request,\n isRouteRequest: boolean,\n future: StaticHandlerFutureConfig\n) {\n if (future.v7_throwAbortReason && request.signal.reason !== undefined) {\n throw request.signal.reason;\n }\n\n let method = isRouteRequest ? \"queryRoute\" : \"query\";\n throw new Error(`${method}() call aborted: ${request.method} ${request.url}`);\n}\n\nfunction isSubmissionNavigation(\n opts: BaseNavigateOrFetchOptions\n): opts is SubmissionNavigateOptions {\n return (\n opts != null &&\n ((\"formData\" in opts && opts.formData != null) ||\n (\"body\" in opts && opts.body !== undefined))\n );\n}\n\nfunction normalizeTo(\n location: Path,\n matches: AgnosticDataRouteMatch[],\n basename: string,\n prependBasename: boolean,\n to: To | null,\n v7_relativeSplatPath: boolean,\n fromRouteId?: string,\n relative?: RelativeRoutingType\n) {\n let contextualMatches: AgnosticDataRouteMatch[];\n let activeRouteMatch: AgnosticDataRouteMatch | undefined;\n if (fromRouteId) {\n // Grab matches up to the calling route so our route-relative logic is\n // relative to the correct source route\n contextualMatches = [];\n for (let match of matches) {\n contextualMatches.push(match);\n if (match.route.id === fromRouteId) {\n activeRouteMatch = match;\n break;\n }\n }\n } else {\n contextualMatches = matches;\n activeRouteMatch = matches[matches.length - 1];\n }\n\n // Resolve the relative path\n let path = resolveTo(\n to ? to : \".\",\n getResolveToMatches(contextualMatches, v7_relativeSplatPath),\n stripBasename(location.pathname, basename) || location.pathname,\n relative === \"path\"\n );\n\n // When `to` is not specified we inherit search/hash from the current\n // location, unlike when to=\".\" and we just inherit the path.\n // See https://github.com/remix-run/remix/issues/927\n if (to == null) {\n path.search = location.search;\n path.hash = location.hash;\n }\n\n // Account for `?index` params when routing to the current location\n if ((to == null || to === \"\" || to === \".\") && activeRouteMatch) {\n let nakedIndex = hasNakedIndexQuery(path.search);\n if (activeRouteMatch.route.index && !nakedIndex) {\n // Add one when we're targeting an index route\n path.search = path.search\n ? path.search.replace(/^\\?/, \"?index&\")\n : \"?index\";\n } else if (!activeRouteMatch.route.index && nakedIndex) {\n // Remove existing ones when we're not\n let params = new URLSearchParams(path.search);\n let indexValues = params.getAll(\"index\");\n params.delete(\"index\");\n indexValues.filter((v) => v).forEach((v) => params.append(\"index\", v));\n let qs = params.toString();\n path.search = qs ? `?${qs}` : \"\";\n }\n }\n\n // If we're operating within a basename, prepend it to the pathname. If\n // this is a root navigation, then just use the raw basename which allows\n // the basename to have full control over the presence of a trailing slash\n // on root actions\n if (prependBasename && basename !== \"/\") {\n path.pathname =\n path.pathname === \"/\" ? basename : joinPaths([basename, path.pathname]);\n }\n\n return createPath(path);\n}\n\n// Normalize navigation options by converting formMethod=GET formData objects to\n// URLSearchParams so they behave identically to links with query params\nfunction normalizeNavigateOptions(\n normalizeFormMethod: boolean,\n isFetcher: boolean,\n path: string,\n opts?: BaseNavigateOrFetchOptions\n): {\n path: string;\n submission?: Submission;\n error?: ErrorResponseImpl;\n} {\n // Return location verbatim on non-submission navigations\n if (!opts || !isSubmissionNavigation(opts)) {\n return { path };\n }\n\n if (opts.formMethod && !isValidMethod(opts.formMethod)) {\n return {\n path,\n error: getInternalRouterError(405, { method: opts.formMethod }),\n };\n }\n\n let getInvalidBodyError = () => ({\n path,\n error: getInternalRouterError(400, { type: \"invalid-body\" }),\n });\n\n // Create a Submission on non-GET navigations\n let rawFormMethod = opts.formMethod || \"get\";\n let formMethod = normalizeFormMethod\n ? (rawFormMethod.toUpperCase() as V7_FormMethod)\n : (rawFormMethod.toLowerCase() as FormMethod);\n let formAction = stripHashFromPath(path);\n\n if (opts.body !== undefined) {\n if (opts.formEncType === \"text/plain\") {\n // text only support POST/PUT/PATCH/DELETE submissions\n if (!isMutationMethod(formMethod)) {\n return getInvalidBodyError();\n }\n\n let text =\n typeof opts.body === \"string\"\n ? opts.body\n : opts.body instanceof FormData ||\n opts.body instanceof URLSearchParams\n ? // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#plain-text-form-data\n Array.from(opts.body.entries()).reduce(\n (acc, [name, value]) => `${acc}${name}=${value}\\n`,\n \"\"\n )\n : String(opts.body);\n\n return {\n path,\n submission: {\n formMethod,\n formAction,\n formEncType: opts.formEncType,\n formData: undefined,\n json: undefined,\n text,\n },\n };\n } else if (opts.formEncType === \"application/json\") {\n // json only supports POST/PUT/PATCH/DELETE submissions\n if (!isMutationMethod(formMethod)) {\n return getInvalidBodyError();\n }\n\n try {\n let json =\n typeof opts.body === \"string\" ? JSON.parse(opts.body) : opts.body;\n\n return {\n path,\n submission: {\n formMethod,\n formAction,\n formEncType: opts.formEncType,\n formData: undefined,\n json,\n text: undefined,\n },\n };\n } catch (e) {\n return getInvalidBodyError();\n }\n }\n }\n\n invariant(\n typeof FormData === \"function\",\n \"FormData is not available in this environment\"\n );\n\n let searchParams: URLSearchParams;\n let formData: FormData;\n\n if (opts.formData) {\n searchParams = convertFormDataToSearchParams(opts.formData);\n formData = opts.formData;\n } else if (opts.body instanceof FormData) {\n searchParams = convertFormDataToSearchParams(opts.body);\n formData = opts.body;\n } else if (opts.body instanceof URLSearchParams) {\n searchParams = opts.body;\n formData = convertSearchParamsToFormData(searchParams);\n } else if (opts.body == null) {\n searchParams = new URLSearchParams();\n formData = new FormData();\n } else {\n try {\n searchParams = new URLSearchParams(opts.body);\n formData = convertSearchParamsToFormData(searchParams);\n } catch (e) {\n return getInvalidBodyError();\n }\n }\n\n let submission: Submission = {\n formMethod,\n formAction,\n formEncType:\n (opts && opts.formEncType) || \"application/x-www-form-urlencoded\",\n formData,\n json: undefined,\n text: undefined,\n };\n\n if (isMutationMethod(submission.formMethod)) {\n return { path, submission };\n }\n\n // Flatten submission onto URLSearchParams for GET submissions\n let parsedPath = parsePath(path);\n // On GET navigation submissions we can drop the ?index param from the\n // resulting location since all loaders will run. But fetcher GET submissions\n // only run a single loader so we need to preserve any incoming ?index params\n if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) {\n searchParams.append(\"index\", \"\");\n }\n parsedPath.search = `?${searchParams}`;\n\n return { path: createPath(parsedPath), submission };\n}\n\n// Filter out all routes at/below any caught error as they aren't going to\n// render so we don't need to load them\nfunction getLoaderMatchesUntilBoundary(\n matches: AgnosticDataRouteMatch[],\n boundaryId: string,\n includeBoundary = false\n) {\n let index = matches.findIndex((m) => m.route.id === boundaryId);\n if (index >= 0) {\n return matches.slice(0, includeBoundary ? index + 1 : index);\n }\n return matches;\n}\n\nfunction getMatchesToLoad(\n history: History,\n state: RouterState,\n matches: AgnosticDataRouteMatch[],\n submission: Submission | undefined,\n location: Location,\n initialHydration: boolean,\n skipActionErrorRevalidation: boolean,\n isRevalidationRequired: boolean,\n cancelledDeferredRoutes: string[],\n cancelledFetcherLoads: Set,\n deletedFetchers: Set,\n fetchLoadMatches: Map,\n fetchRedirectIds: Set,\n routesToUse: AgnosticDataRouteObject[],\n basename: string | undefined,\n pendingActionResult?: PendingActionResult\n): [AgnosticDataRouteMatch[], RevalidatingFetcher[]] {\n let actionResult = pendingActionResult\n ? isErrorResult(pendingActionResult[1])\n ? pendingActionResult[1].error\n : pendingActionResult[1].data\n : undefined;\n let currentUrl = history.createURL(state.location);\n let nextUrl = history.createURL(location);\n\n // Pick navigation matches that are net-new or qualify for revalidation\n let boundaryMatches = matches;\n if (initialHydration && state.errors) {\n // On initial hydration, only consider matches up to _and including_ the boundary.\n // This is inclusive to handle cases where a server loader ran successfully,\n // a child server loader bubbled up to this route, but this route has\n // `clientLoader.hydrate` so we want to still run the `clientLoader` so that\n // we have a complete version of `loaderData`\n boundaryMatches = getLoaderMatchesUntilBoundary(\n matches,\n Object.keys(state.errors)[0],\n true\n );\n } else if (pendingActionResult && isErrorResult(pendingActionResult[1])) {\n // If an action threw an error, we call loaders up to, but not including the\n // boundary\n boundaryMatches = getLoaderMatchesUntilBoundary(\n matches,\n pendingActionResult[0]\n );\n }\n\n // Don't revalidate loaders by default after action 4xx/5xx responses\n // when the flag is enabled. They can still opt-into revalidation via\n // `shouldRevalidate` via `actionResult`\n let actionStatus = pendingActionResult\n ? pendingActionResult[1].statusCode\n : undefined;\n let shouldSkipRevalidation =\n skipActionErrorRevalidation && actionStatus && actionStatus >= 400;\n\n let navigationMatches = boundaryMatches.filter((match, index) => {\n let { route } = match;\n if (route.lazy) {\n // We haven't loaded this route yet so we don't know if it's got a loader!\n return true;\n }\n\n if (route.loader == null) {\n return false;\n }\n\n if (initialHydration) {\n return shouldLoadRouteOnHydration(route, state.loaderData, state.errors);\n }\n\n // Always call the loader on new route instances and pending defer cancellations\n if (\n isNewLoader(state.loaderData, state.matches[index], match) ||\n cancelledDeferredRoutes.some((id) => id === match.route.id)\n ) {\n return true;\n }\n\n // This is the default implementation for when we revalidate. If the route\n // provides it's own implementation, then we give them full control but\n // provide this value so they can leverage it if needed after they check\n // their own specific use cases\n let currentRouteMatch = state.matches[index];\n let nextRouteMatch = match;\n\n return shouldRevalidateLoader(match, {\n currentUrl,\n currentParams: currentRouteMatch.params,\n nextUrl,\n nextParams: nextRouteMatch.params,\n ...submission,\n actionResult,\n actionStatus,\n defaultShouldRevalidate: shouldSkipRevalidation\n ? false\n : // Forced revalidation due to submission, useRevalidator, or X-Remix-Revalidate\n isRevalidationRequired ||\n currentUrl.pathname + currentUrl.search ===\n nextUrl.pathname + nextUrl.search ||\n // Search params affect all loaders\n currentUrl.search !== nextUrl.search ||\n isNewRouteInstance(currentRouteMatch, nextRouteMatch),\n });\n });\n\n // Pick fetcher.loads that need to be revalidated\n let revalidatingFetchers: RevalidatingFetcher[] = [];\n fetchLoadMatches.forEach((f, key) => {\n // Don't revalidate:\n // - on initial hydration (shouldn't be any fetchers then anyway)\n // - if fetcher won't be present in the subsequent render\n // - no longer matches the URL (v7_fetcherPersist=false)\n // - was unmounted but persisted due to v7_fetcherPersist=true\n if (\n initialHydration ||\n !matches.some((m) => m.route.id === f.routeId) ||\n deletedFetchers.has(key)\n ) {\n return;\n }\n\n let fetcherMatches = matchRoutes(routesToUse, f.path, basename);\n\n // If the fetcher path no longer matches, push it in with null matches so\n // we can trigger a 404 in callLoadersAndMaybeResolveData. Note this is\n // currently only a use-case for Remix HMR where the route tree can change\n // at runtime and remove a route previously loaded via a fetcher\n if (!fetcherMatches) {\n revalidatingFetchers.push({\n key,\n routeId: f.routeId,\n path: f.path,\n matches: null,\n match: null,\n controller: null,\n });\n return;\n }\n\n // Revalidating fetchers are decoupled from the route matches since they\n // load from a static href. They revalidate based on explicit revalidation\n // (submission, useRevalidator, or X-Remix-Revalidate)\n let fetcher = state.fetchers.get(key);\n let fetcherMatch = getTargetMatch(fetcherMatches, f.path);\n\n let shouldRevalidate = false;\n if (fetchRedirectIds.has(key)) {\n // Never trigger a revalidation of an actively redirecting fetcher\n shouldRevalidate = false;\n } else if (cancelledFetcherLoads.has(key)) {\n // Always mark for revalidation if the fetcher was cancelled\n cancelledFetcherLoads.delete(key);\n shouldRevalidate = true;\n } else if (\n fetcher &&\n fetcher.state !== \"idle\" &&\n fetcher.data === undefined\n ) {\n // If the fetcher hasn't ever completed loading yet, then this isn't a\n // revalidation, it would just be a brand new load if an explicit\n // revalidation is required\n shouldRevalidate = isRevalidationRequired;\n } else {\n // Otherwise fall back on any user-defined shouldRevalidate, defaulting\n // to explicit revalidations only\n shouldRevalidate = shouldRevalidateLoader(fetcherMatch, {\n currentUrl,\n currentParams: state.matches[state.matches.length - 1].params,\n nextUrl,\n nextParams: matches[matches.length - 1].params,\n ...submission,\n actionResult,\n actionStatus,\n defaultShouldRevalidate: shouldSkipRevalidation\n ? false\n : isRevalidationRequired,\n });\n }\n\n if (shouldRevalidate) {\n revalidatingFetchers.push({\n key,\n routeId: f.routeId,\n path: f.path,\n matches: fetcherMatches,\n match: fetcherMatch,\n controller: new AbortController(),\n });\n }\n });\n\n return [navigationMatches, revalidatingFetchers];\n}\n\nfunction shouldLoadRouteOnHydration(\n route: AgnosticDataRouteObject,\n loaderData: RouteData | null | undefined,\n errors: RouteData | null | undefined\n) {\n // We dunno if we have a loader - gotta find out!\n if (route.lazy) {\n return true;\n }\n\n // No loader, nothing to initialize\n if (!route.loader) {\n return false;\n }\n\n let hasData = loaderData != null && loaderData[route.id] !== undefined;\n let hasError = errors != null && errors[route.id] !== undefined;\n\n // Don't run if we error'd during SSR\n if (!hasData && hasError) {\n return false;\n }\n\n // Explicitly opting-in to running on hydration\n if (typeof route.loader === \"function\" && route.loader.hydrate === true) {\n return true;\n }\n\n // Otherwise, run if we're not yet initialized with anything\n return !hasData && !hasError;\n}\n\nfunction isNewLoader(\n currentLoaderData: RouteData,\n currentMatch: AgnosticDataRouteMatch,\n match: AgnosticDataRouteMatch\n) {\n let isNew =\n // [a] -> [a, b]\n !currentMatch ||\n // [a, b] -> [a, c]\n match.route.id !== currentMatch.route.id;\n\n // Handle the case that we don't have data for a re-used route, potentially\n // from a prior error or from a cancelled pending deferred\n let isMissingData = currentLoaderData[match.route.id] === undefined;\n\n // Always load if this is a net-new route or we don't yet have data\n return isNew || isMissingData;\n}\n\nfunction isNewRouteInstance(\n currentMatch: AgnosticDataRouteMatch,\n match: AgnosticDataRouteMatch\n) {\n let currentPath = currentMatch.route.path;\n return (\n // param change for this match, /users/123 -> /users/456\n currentMatch.pathname !== match.pathname ||\n // splat param changed, which is not present in match.path\n // e.g. /files/images/avatar.jpg -> files/finances.xls\n (currentPath != null &&\n currentPath.endsWith(\"*\") &&\n currentMatch.params[\"*\"] !== match.params[\"*\"])\n );\n}\n\nfunction shouldRevalidateLoader(\n loaderMatch: AgnosticDataRouteMatch,\n arg: ShouldRevalidateFunctionArgs\n) {\n if (loaderMatch.route.shouldRevalidate) {\n let routeChoice = loaderMatch.route.shouldRevalidate(arg);\n if (typeof routeChoice === \"boolean\") {\n return routeChoice;\n }\n }\n\n return arg.defaultShouldRevalidate;\n}\n\nfunction patchRoutesImpl(\n routeId: string | null,\n children: AgnosticRouteObject[],\n routesToUse: AgnosticDataRouteObject[],\n manifest: RouteManifest,\n mapRouteProperties: MapRoutePropertiesFunction\n) {\n let childrenToPatch: AgnosticDataRouteObject[];\n if (routeId) {\n let route = manifest[routeId];\n invariant(\n route,\n `No route found to patch children into: routeId = ${routeId}`\n );\n if (!route.children) {\n route.children = [];\n }\n childrenToPatch = route.children;\n } else {\n childrenToPatch = routesToUse;\n }\n\n // Don't patch in routes we already know about so that `patch` is idempotent\n // to simplify user-land code. This is useful because we re-call the\n // `patchRoutesOnNavigation` function for matched routes with params.\n let uniqueChildren = children.filter(\n (newRoute) =>\n !childrenToPatch.some((existingRoute) =>\n isSameRoute(newRoute, existingRoute)\n )\n );\n\n let newRoutes = convertRoutesToDataRoutes(\n uniqueChildren,\n mapRouteProperties,\n [routeId || \"_\", \"patch\", String(childrenToPatch?.length || \"0\")],\n manifest\n );\n\n childrenToPatch.push(...newRoutes);\n}\n\nfunction isSameRoute(\n newRoute: AgnosticRouteObject,\n existingRoute: AgnosticRouteObject\n): boolean {\n // Most optimal check is by id\n if (\n \"id\" in newRoute &&\n \"id\" in existingRoute &&\n newRoute.id === existingRoute.id\n ) {\n return true;\n }\n\n // Second is by pathing differences\n if (\n !(\n newRoute.index === existingRoute.index &&\n newRoute.path === existingRoute.path &&\n newRoute.caseSensitive === existingRoute.caseSensitive\n )\n ) {\n return false;\n }\n\n // Pathless layout routes are trickier since we need to check children.\n // If they have no children then they're the same as far as we can tell\n if (\n (!newRoute.children || newRoute.children.length === 0) &&\n (!existingRoute.children || existingRoute.children.length === 0)\n ) {\n return true;\n }\n\n // Otherwise, we look to see if every child in the new route is already\n // represented in the existing route's children\n return newRoute.children!.every((aChild, i) =>\n existingRoute.children?.some((bChild) => isSameRoute(aChild, bChild))\n );\n}\n\n/**\n * Execute route.lazy() methods to lazily load route modules (loader, action,\n * shouldRevalidate) and update the routeManifest in place which shares objects\n * with dataRoutes so those get updated as well.\n */\nasync function loadLazyRouteModule(\n route: AgnosticDataRouteObject,\n mapRouteProperties: MapRoutePropertiesFunction,\n manifest: RouteManifest\n) {\n if (!route.lazy) {\n return;\n }\n\n let lazyRoute = await route.lazy();\n\n // If the lazy route function was executed and removed by another parallel\n // call then we can return - first lazy() to finish wins because the return\n // value of lazy is expected to be static\n if (!route.lazy) {\n return;\n }\n\n let routeToUpdate = manifest[route.id];\n invariant(routeToUpdate, \"No route found in manifest\");\n\n // Update the route in place. This should be safe because there's no way\n // we could yet be sitting on this route as we can't get there without\n // resolving lazy() first.\n //\n // This is different than the HMR \"update\" use-case where we may actively be\n // on the route being updated. The main concern boils down to \"does this\n // mutation affect any ongoing navigations or any current state.matches\n // values?\". If not, it should be safe to update in place.\n let routeUpdates: Record = {};\n for (let lazyRouteProperty in lazyRoute) {\n let staticRouteValue =\n routeToUpdate[lazyRouteProperty as keyof typeof routeToUpdate];\n\n let isPropertyStaticallyDefined =\n staticRouteValue !== undefined &&\n // This property isn't static since it should always be updated based\n // on the route updates\n lazyRouteProperty !== \"hasErrorBoundary\";\n\n warning(\n !isPropertyStaticallyDefined,\n `Route \"${routeToUpdate.id}\" has a static property \"${lazyRouteProperty}\" ` +\n `defined but its lazy function is also returning a value for this property. ` +\n `The lazy route property \"${lazyRouteProperty}\" will be ignored.`\n );\n\n if (\n !isPropertyStaticallyDefined &&\n !immutableRouteKeys.has(lazyRouteProperty as ImmutableRouteKey)\n ) {\n routeUpdates[lazyRouteProperty] =\n lazyRoute[lazyRouteProperty as keyof typeof lazyRoute];\n }\n }\n\n // Mutate the route with the provided updates. Do this first so we pass\n // the updated version to mapRouteProperties\n Object.assign(routeToUpdate, routeUpdates);\n\n // Mutate the `hasErrorBoundary` property on the route based on the route\n // updates and remove the `lazy` function so we don't resolve the lazy\n // route again.\n Object.assign(routeToUpdate, {\n // To keep things framework agnostic, we use the provided\n // `mapRouteProperties` (or wrapped `detectErrorBoundary`) function to\n // set the framework-aware properties (`element`/`hasErrorBoundary`) since\n // the logic will differ between frameworks.\n ...mapRouteProperties(routeToUpdate),\n lazy: undefined,\n });\n}\n\n// Default implementation of `dataStrategy` which fetches all loaders in parallel\nasync function defaultDataStrategy({\n matches,\n}: DataStrategyFunctionArgs): ReturnType {\n let matchesToLoad = matches.filter((m) => m.shouldLoad);\n let results = await Promise.all(matchesToLoad.map((m) => m.resolve()));\n return results.reduce(\n (acc, result, i) =>\n Object.assign(acc, { [matchesToLoad[i].route.id]: result }),\n {}\n );\n}\n\nasync function callDataStrategyImpl(\n dataStrategyImpl: DataStrategyFunction,\n type: \"loader\" | \"action\",\n state: RouterState | null,\n request: Request,\n matchesToLoad: AgnosticDataRouteMatch[],\n matches: AgnosticDataRouteMatch[],\n fetcherKey: string | null,\n manifest: RouteManifest,\n mapRouteProperties: MapRoutePropertiesFunction,\n requestContext?: unknown\n): Promise> {\n let loadRouteDefinitionsPromises = matches.map((m) =>\n m.route.lazy\n ? loadLazyRouteModule(m.route, mapRouteProperties, manifest)\n : undefined\n );\n\n let dsMatches = matches.map((match, i) => {\n let loadRoutePromise = loadRouteDefinitionsPromises[i];\n let shouldLoad = matchesToLoad.some((m) => m.route.id === match.route.id);\n // `resolve` encapsulates route.lazy(), executing the loader/action,\n // and mapping return values/thrown errors to a `DataStrategyResult`. Users\n // can pass a callback to take fine-grained control over the execution\n // of the loader/action\n let resolve: DataStrategyMatch[\"resolve\"] = async (handlerOverride) => {\n if (\n handlerOverride &&\n request.method === \"GET\" &&\n (match.route.lazy || match.route.loader)\n ) {\n shouldLoad = true;\n }\n return shouldLoad\n ? callLoaderOrAction(\n type,\n request,\n match,\n loadRoutePromise,\n handlerOverride,\n requestContext\n )\n : Promise.resolve({ type: ResultType.data, result: undefined });\n };\n\n return {\n ...match,\n shouldLoad,\n resolve,\n };\n });\n\n // Send all matches here to allow for a middleware-type implementation.\n // handler will be a no-op for unneeded routes and we filter those results\n // back out below.\n let results = await dataStrategyImpl({\n matches: dsMatches,\n request,\n params: matches[0].params,\n fetcherKey,\n context: requestContext,\n });\n\n // Wait for all routes to load here but 'swallow the error since we want\n // it to bubble up from the `await loadRoutePromise` in `callLoaderOrAction` -\n // called from `match.resolve()`\n try {\n await Promise.all(loadRouteDefinitionsPromises);\n } catch (e) {\n // No-op\n }\n\n return results;\n}\n\n// Default logic for calling a loader/action is the user has no specified a dataStrategy\nasync function callLoaderOrAction(\n type: \"loader\" | \"action\",\n request: Request,\n match: AgnosticDataRouteMatch,\n loadRoutePromise: Promise | undefined,\n handlerOverride: Parameters[0],\n staticContext?: unknown\n): Promise {\n let result: DataStrategyResult;\n let onReject: (() => void) | undefined;\n\n let runHandler = (\n handler: AgnosticRouteObject[\"loader\"] | AgnosticRouteObject[\"action\"]\n ): Promise => {\n // Setup a promise we can race against so that abort signals short circuit\n let reject: () => void;\n // This will never resolve so safe to type it as Promise to\n // satisfy the function return value\n let abortPromise = new Promise((_, r) => (reject = r));\n onReject = () => reject();\n request.signal.addEventListener(\"abort\", onReject);\n\n let actualHandler = (ctx?: unknown) => {\n if (typeof handler !== \"function\") {\n return Promise.reject(\n new Error(\n `You cannot call the handler for a route which defines a boolean ` +\n `\"${type}\" [routeId: ${match.route.id}]`\n )\n );\n }\n return handler(\n {\n request,\n params: match.params,\n context: staticContext,\n },\n ...(ctx !== undefined ? [ctx] : [])\n );\n };\n\n let handlerPromise: Promise = (async () => {\n try {\n let val = await (handlerOverride\n ? handlerOverride((ctx: unknown) => actualHandler(ctx))\n : actualHandler());\n return { type: \"data\", result: val };\n } catch (e) {\n return { type: \"error\", result: e };\n }\n })();\n\n return Promise.race([handlerPromise, abortPromise]);\n };\n\n try {\n let handler = match.route[type];\n\n // If we have a route.lazy promise, await that first\n if (loadRoutePromise) {\n if (handler) {\n // Run statically defined handler in parallel with lazy()\n let handlerError;\n let [value] = await Promise.all([\n // If the handler throws, don't let it immediately bubble out,\n // since we need to let the lazy() execution finish so we know if this\n // route has a boundary that can handle the error\n runHandler(handler).catch((e) => {\n handlerError = e;\n }),\n loadRoutePromise,\n ]);\n if (handlerError !== undefined) {\n throw handlerError;\n }\n result = value!;\n } else {\n // Load lazy route module, then run any returned handler\n await loadRoutePromise;\n\n handler = match.route[type];\n if (handler) {\n // Handler still runs even if we got interrupted to maintain consistency\n // with un-abortable behavior of handler execution on non-lazy or\n // previously-lazy-loaded routes\n result = await runHandler(handler);\n } else if (type === \"action\") {\n let url = new URL(request.url);\n let pathname = url.pathname + url.search;\n throw getInternalRouterError(405, {\n method: request.method,\n pathname,\n routeId: match.route.id,\n });\n } else {\n // lazy() route has no loader to run. Short circuit here so we don't\n // hit the invariant below that errors on returning undefined.\n return { type: ResultType.data, result: undefined };\n }\n }\n } else if (!handler) {\n let url = new URL(request.url);\n let pathname = url.pathname + url.search;\n throw getInternalRouterError(404, {\n pathname,\n });\n } else {\n result = await runHandler(handler);\n }\n\n invariant(\n result.result !== undefined,\n `You defined ${type === \"action\" ? \"an action\" : \"a loader\"} for route ` +\n `\"${match.route.id}\" but didn't return anything from your \\`${type}\\` ` +\n `function. Please return a value or \\`null\\`.`\n );\n } catch (e) {\n // We should already be catching and converting normal handler executions to\n // DataStrategyResults and returning them, so anything that throws here is an\n // unexpected error we still need to wrap\n return { type: ResultType.error, result: e };\n } finally {\n if (onReject) {\n request.signal.removeEventListener(\"abort\", onReject);\n }\n }\n\n return result;\n}\n\nasync function convertDataStrategyResultToDataResult(\n dataStrategyResult: DataStrategyResult\n): Promise {\n let { result, type } = dataStrategyResult;\n\n if (isResponse(result)) {\n let data: any;\n\n try {\n let contentType = result.headers.get(\"Content-Type\");\n // Check between word boundaries instead of startsWith() due to the last\n // paragraph of https://httpwg.org/specs/rfc9110.html#field.content-type\n if (contentType && /\\bapplication\\/json\\b/.test(contentType)) {\n if (result.body == null) {\n data = null;\n } else {\n data = await result.json();\n }\n } else {\n data = await result.text();\n }\n } catch (e) {\n return { type: ResultType.error, error: e };\n }\n\n if (type === ResultType.error) {\n return {\n type: ResultType.error,\n error: new ErrorResponseImpl(result.status, result.statusText, data),\n statusCode: result.status,\n headers: result.headers,\n };\n }\n\n return {\n type: ResultType.data,\n data,\n statusCode: result.status,\n headers: result.headers,\n };\n }\n\n if (type === ResultType.error) {\n if (isDataWithResponseInit(result)) {\n if (result.data instanceof Error) {\n return {\n type: ResultType.error,\n error: result.data,\n statusCode: result.init?.status,\n headers: result.init?.headers\n ? new Headers(result.init.headers)\n : undefined,\n };\n }\n\n // Convert thrown data() to ErrorResponse instances\n return {\n type: ResultType.error,\n error: new ErrorResponseImpl(\n result.init?.status || 500,\n undefined,\n result.data\n ),\n statusCode: isRouteErrorResponse(result) ? result.status : undefined,\n headers: result.init?.headers\n ? new Headers(result.init.headers)\n : undefined,\n };\n }\n return {\n type: ResultType.error,\n error: result,\n statusCode: isRouteErrorResponse(result) ? result.status : undefined,\n };\n }\n\n if (isDeferredData(result)) {\n return {\n type: ResultType.deferred,\n deferredData: result,\n statusCode: result.init?.status,\n headers: result.init?.headers && new Headers(result.init.headers),\n };\n }\n\n if (isDataWithResponseInit(result)) {\n return {\n type: ResultType.data,\n data: result.data,\n statusCode: result.init?.status,\n headers: result.init?.headers\n ? new Headers(result.init.headers)\n : undefined,\n };\n }\n\n return { type: ResultType.data, data: result };\n}\n\n// Support relative routing in internal redirects\nfunction normalizeRelativeRoutingRedirectResponse(\n response: Response,\n request: Request,\n routeId: string,\n matches: AgnosticDataRouteMatch[],\n basename: string,\n v7_relativeSplatPath: boolean\n) {\n let location = response.headers.get(\"Location\");\n invariant(\n location,\n \"Redirects returned/thrown from loaders/actions must have a Location header\"\n );\n\n if (!ABSOLUTE_URL_REGEX.test(location)) {\n let trimmedMatches = matches.slice(\n 0,\n matches.findIndex((m) => m.route.id === routeId) + 1\n );\n location = normalizeTo(\n new URL(request.url),\n trimmedMatches,\n basename,\n true,\n location,\n v7_relativeSplatPath\n );\n response.headers.set(\"Location\", location);\n }\n\n return response;\n}\n\nfunction normalizeRedirectLocation(\n location: string,\n currentUrl: URL,\n basename: string,\n historyInstance: History,\n): string {\n // Match Chrome's behavior:\n // https://github.com/chromium/chromium/blob/216dbeb61db0c667e62082e5f5400a32d6983df3/content/public/common/url_utils.cc#L82\n let invalidProtocols = [\n \"about:\",\n \"blob:\",\n \"chrome:\",\n \"chrome-untrusted:\",\n \"content:\",\n \"data:\",\n \"devtools:\",\n \"file:\",\n \"filesystem:\",\n // eslint-disable-next-line no-script-url\n \"javascript:\",\n ];\n\n if (ABSOLUTE_URL_REGEX.test(location)) {\n // Strip off the protocol+origin for same-origin + same-basename absolute redirects\n let normalizedLocation = location;\n let url = normalizedLocation.startsWith(\"//\")\n ? new URL(currentUrl.protocol + normalizedLocation)\n : new URL(normalizedLocation);\n if (invalidProtocols.includes(url.protocol)) {\n throw new Error(\"Invalid redirect location\");\n }\n let isSameBasename = stripBasename(url.pathname, basename) != null;\n if (url.origin === currentUrl.origin && isSameBasename) {\n return removeDoubleSlashes(url.pathname) + url.search + url.hash;\n }\n }\n\n try {\n let url = historyInstance.createURL(location);\n if (invalidProtocols.includes(url.protocol)) {\n throw new Error(\"Invalid redirect location\");\n }\n } catch (e) {}\n\n return location;\n}\n\n// Utility method for creating the Request instances for loaders/actions during\n// client-side navigations and fetches. During SSR we will always have a\n// Request instance from the static handler (query/queryRoute)\nfunction createClientSideRequest(\n history: History,\n location: string | Location,\n signal: AbortSignal,\n submission?: Submission\n): Request {\n let url = history.createURL(stripHashFromPath(location)).toString();\n let init: RequestInit = { signal };\n\n if (submission && isMutationMethod(submission.formMethod)) {\n let { formMethod, formEncType } = submission;\n // Didn't think we needed this but it turns out unlike other methods, patch\n // won't be properly normalized to uppercase and results in a 405 error.\n // See: https://fetch.spec.whatwg.org/#concept-method\n init.method = formMethod.toUpperCase();\n\n if (formEncType === \"application/json\") {\n init.headers = new Headers({ \"Content-Type\": formEncType });\n init.body = JSON.stringify(submission.json);\n } else if (formEncType === \"text/plain\") {\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n init.body = submission.text;\n } else if (\n formEncType === \"application/x-www-form-urlencoded\" &&\n submission.formData\n ) {\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n init.body = convertFormDataToSearchParams(submission.formData);\n } else {\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n init.body = submission.formData;\n }\n }\n\n return new Request(url, init);\n}\n\nfunction convertFormDataToSearchParams(formData: FormData): URLSearchParams {\n let searchParams = new URLSearchParams();\n\n for (let [key, value] of formData.entries()) {\n // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#converting-an-entry-list-to-a-list-of-name-value-pairs\n searchParams.append(key, typeof value === \"string\" ? value : value.name);\n }\n\n return searchParams;\n}\n\nfunction convertSearchParamsToFormData(\n searchParams: URLSearchParams\n): FormData {\n let formData = new FormData();\n for (let [key, value] of searchParams.entries()) {\n formData.append(key, value);\n }\n return formData;\n}\n\nfunction processRouteLoaderData(\n matches: AgnosticDataRouteMatch[],\n results: Record,\n pendingActionResult: PendingActionResult | undefined,\n activeDeferreds: Map,\n skipLoaderErrorBubbling: boolean\n): {\n loaderData: RouterState[\"loaderData\"];\n errors: RouterState[\"errors\"] | null;\n statusCode: number;\n loaderHeaders: Record;\n} {\n // Fill in loaderData/errors from our loaders\n let loaderData: RouterState[\"loaderData\"] = {};\n let errors: RouterState[\"errors\"] | null = null;\n let statusCode: number | undefined;\n let foundError = false;\n let loaderHeaders: Record = {};\n let pendingError =\n pendingActionResult && isErrorResult(pendingActionResult[1])\n ? pendingActionResult[1].error\n : undefined;\n\n // Process loader results into state.loaderData/state.errors\n matches.forEach((match) => {\n if (!(match.route.id in results)) {\n return;\n }\n let id = match.route.id;\n let result = results[id];\n invariant(\n !isRedirectResult(result),\n \"Cannot handle redirect results in processLoaderData\"\n );\n if (isErrorResult(result)) {\n let error = result.error;\n // If we have a pending action error, we report it at the highest-route\n // that throws a loader error, and then clear it out to indicate that\n // it was consumed\n if (pendingError !== undefined) {\n error = pendingError;\n pendingError = undefined;\n }\n\n errors = errors || {};\n\n if (skipLoaderErrorBubbling) {\n errors[id] = error;\n } else {\n // Look upwards from the matched route for the closest ancestor error\n // boundary, defaulting to the root match. Prefer higher error values\n // if lower errors bubble to the same boundary\n let boundaryMatch = findNearestBoundary(matches, id);\n if (errors[boundaryMatch.route.id] == null) {\n errors[boundaryMatch.route.id] = error;\n }\n }\n\n // Clear our any prior loaderData for the throwing route\n loaderData[id] = undefined;\n\n // Once we find our first (highest) error, we set the status code and\n // prevent deeper status codes from overriding\n if (!foundError) {\n foundError = true;\n statusCode = isRouteErrorResponse(result.error)\n ? result.error.status\n : 500;\n }\n if (result.headers) {\n loaderHeaders[id] = result.headers;\n }\n } else {\n if (isDeferredResult(result)) {\n activeDeferreds.set(id, result.deferredData);\n loaderData[id] = result.deferredData.data;\n // Error status codes always override success status codes, but if all\n // loaders are successful we take the deepest status code.\n if (\n result.statusCode != null &&\n result.statusCode !== 200 &&\n !foundError\n ) {\n statusCode = result.statusCode;\n }\n if (result.headers) {\n loaderHeaders[id] = result.headers;\n }\n } else {\n loaderData[id] = result.data;\n // Error status codes always override success status codes, but if all\n // loaders are successful we take the deepest status code.\n if (result.statusCode && result.statusCode !== 200 && !foundError) {\n statusCode = result.statusCode;\n }\n if (result.headers) {\n loaderHeaders[id] = result.headers;\n }\n }\n }\n });\n\n // If we didn't consume the pending action error (i.e., all loaders\n // resolved), then consume it here. Also clear out any loaderData for the\n // throwing route\n if (pendingError !== undefined && pendingActionResult) {\n errors = { [pendingActionResult[0]]: pendingError };\n loaderData[pendingActionResult[0]] = undefined;\n }\n\n return {\n loaderData,\n errors,\n statusCode: statusCode || 200,\n loaderHeaders,\n };\n}\n\nfunction processLoaderData(\n state: RouterState,\n matches: AgnosticDataRouteMatch[],\n results: Record,\n pendingActionResult: PendingActionResult | undefined,\n revalidatingFetchers: RevalidatingFetcher[],\n fetcherResults: Record,\n activeDeferreds: Map\n): {\n loaderData: RouterState[\"loaderData\"];\n errors?: RouterState[\"errors\"];\n} {\n let { loaderData, errors } = processRouteLoaderData(\n matches,\n results,\n pendingActionResult,\n activeDeferreds,\n false // This method is only called client side so we always want to bubble\n );\n\n // Process results from our revalidating fetchers\n revalidatingFetchers.forEach((rf) => {\n let { key, match, controller } = rf;\n let result = fetcherResults[key];\n invariant(result, \"Did not find corresponding fetcher result\");\n\n // Process fetcher non-redirect errors\n if (controller && controller.signal.aborted) {\n // Nothing to do for aborted fetchers\n return;\n } else if (isErrorResult(result)) {\n let boundaryMatch = findNearestBoundary(state.matches, match?.route.id);\n if (!(errors && errors[boundaryMatch.route.id])) {\n errors = {\n ...errors,\n [boundaryMatch.route.id]: result.error,\n };\n }\n state.fetchers.delete(key);\n } else if (isRedirectResult(result)) {\n // Should never get here, redirects should get processed above, but we\n // keep this to type narrow to a success result in the else\n invariant(false, \"Unhandled fetcher revalidation redirect\");\n } else if (isDeferredResult(result)) {\n // Should never get here, deferred data should be awaited for fetchers\n // in resolveDeferredResults\n invariant(false, \"Unhandled fetcher deferred data\");\n } else {\n let doneFetcher = getDoneFetcher(result.data);\n state.fetchers.set(key, doneFetcher);\n }\n });\n\n return { loaderData, errors };\n}\n\nfunction mergeLoaderData(\n loaderData: RouteData,\n newLoaderData: RouteData,\n matches: AgnosticDataRouteMatch[],\n errors: RouteData | null | undefined\n): RouteData {\n let mergedLoaderData = { ...newLoaderData };\n for (let match of matches) {\n let id = match.route.id;\n if (newLoaderData.hasOwnProperty(id)) {\n if (newLoaderData[id] !== undefined) {\n mergedLoaderData[id] = newLoaderData[id];\n } else {\n // No-op - this is so we ignore existing data if we have a key in the\n // incoming object with an undefined value, which is how we unset a prior\n // loaderData if we encounter a loader error\n }\n } else if (loaderData[id] !== undefined && match.route.loader) {\n // Preserve existing keys not included in newLoaderData and where a loader\n // wasn't removed by HMR\n mergedLoaderData[id] = loaderData[id];\n }\n\n if (errors && errors.hasOwnProperty(id)) {\n // Don't keep any loader data below the boundary\n break;\n }\n }\n return mergedLoaderData;\n}\n\nfunction getActionDataForCommit(\n pendingActionResult: PendingActionResult | undefined\n) {\n if (!pendingActionResult) {\n return {};\n }\n return isErrorResult(pendingActionResult[1])\n ? {\n // Clear out prior actionData on errors\n actionData: {},\n }\n : {\n actionData: {\n [pendingActionResult[0]]: pendingActionResult[1].data,\n },\n };\n}\n\n// Find the nearest error boundary, looking upwards from the leaf route (or the\n// route specified by routeId) for the closest ancestor error boundary,\n// defaulting to the root match\nfunction findNearestBoundary(\n matches: AgnosticDataRouteMatch[],\n routeId?: string\n): AgnosticDataRouteMatch {\n let eligibleMatches = routeId\n ? matches.slice(0, matches.findIndex((m) => m.route.id === routeId) + 1)\n : [...matches];\n return (\n eligibleMatches.reverse().find((m) => m.route.hasErrorBoundary === true) ||\n matches[0]\n );\n}\n\nfunction getShortCircuitMatches(routes: AgnosticDataRouteObject[]): {\n matches: AgnosticDataRouteMatch[];\n route: AgnosticDataRouteObject;\n} {\n // Prefer a root layout route if present, otherwise shim in a route object\n let route =\n routes.length === 1\n ? routes[0]\n : routes.find((r) => r.index || !r.path || r.path === \"/\") || {\n id: `__shim-error-route__`,\n };\n\n return {\n matches: [\n {\n params: {},\n pathname: \"\",\n pathnameBase: \"\",\n route,\n },\n ],\n route,\n };\n}\n\nfunction getInternalRouterError(\n status: number,\n {\n pathname,\n routeId,\n method,\n type,\n message,\n }: {\n pathname?: string;\n routeId?: string;\n method?: string;\n type?: \"defer-action\" | \"invalid-body\";\n message?: string;\n } = {}\n) {\n let statusText = \"Unknown Server Error\";\n let errorMessage = \"Unknown @remix-run/router error\";\n\n if (status === 400) {\n statusText = \"Bad Request\";\n if (method && pathname && routeId) {\n errorMessage =\n `You made a ${method} request to \"${pathname}\" but ` +\n `did not provide a \\`loader\\` for route \"${routeId}\", ` +\n `so there is no way to handle the request.`;\n } else if (type === \"defer-action\") {\n errorMessage = \"defer() is not supported in actions\";\n } else if (type === \"invalid-body\") {\n errorMessage = \"Unable to encode submission body\";\n }\n } else if (status === 403) {\n statusText = \"Forbidden\";\n errorMessage = `Route \"${routeId}\" does not match URL \"${pathname}\"`;\n } else if (status === 404) {\n statusText = \"Not Found\";\n errorMessage = `No route matches URL \"${pathname}\"`;\n } else if (status === 405) {\n statusText = \"Method Not Allowed\";\n if (method && pathname && routeId) {\n errorMessage =\n `You made a ${method.toUpperCase()} request to \"${pathname}\" but ` +\n `did not provide an \\`action\\` for route \"${routeId}\", ` +\n `so there is no way to handle the request.`;\n } else if (method) {\n errorMessage = `Invalid request method \"${method.toUpperCase()}\"`;\n }\n }\n\n return new ErrorResponseImpl(\n status || 500,\n statusText,\n new Error(errorMessage),\n true\n );\n}\n\n// Find any returned redirect errors, starting from the lowest match\nfunction findRedirect(\n results: Record\n): { key: string; result: RedirectResult } | undefined {\n let entries = Object.entries(results);\n for (let i = entries.length - 1; i >= 0; i--) {\n let [key, result] = entries[i];\n if (isRedirectResult(result)) {\n return { key, result };\n }\n }\n}\n\nfunction stripHashFromPath(path: To) {\n let parsedPath = typeof path === \"string\" ? parsePath(path) : path;\n return createPath({ ...parsedPath, hash: \"\" });\n}\n\nfunction isHashChangeOnly(a: Location, b: Location): boolean {\n if (a.pathname !== b.pathname || a.search !== b.search) {\n return false;\n }\n\n if (a.hash === \"\") {\n // /page -> /page#hash\n return b.hash !== \"\";\n } else if (a.hash === b.hash) {\n // /page#hash -> /page#hash\n return true;\n } else if (b.hash !== \"\") {\n // /page#hash -> /page#other\n return true;\n }\n\n // If the hash is removed the browser will re-perform a request to the server\n // /page#hash -> /page\n return false;\n}\n\nfunction isPromise(val: unknown): val is Promise {\n return typeof val === \"object\" && val != null && \"then\" in val;\n}\n\nfunction isDataStrategyResult(result: unknown): result is DataStrategyResult {\n return (\n result != null &&\n typeof result === \"object\" &&\n \"type\" in result &&\n \"result\" in result &&\n (result.type === ResultType.data || result.type === ResultType.error)\n );\n}\n\nfunction isRedirectDataStrategyResultResult(result: DataStrategyResult) {\n return (\n isResponse(result.result) && redirectStatusCodes.has(result.result.status)\n );\n}\n\nfunction isDeferredResult(result: DataResult): result is DeferredResult {\n return result.type === ResultType.deferred;\n}\n\nfunction isErrorResult(result: DataResult): result is ErrorResult {\n return result.type === ResultType.error;\n}\n\nfunction isRedirectResult(result?: DataResult): result is RedirectResult {\n return (result && result.type) === ResultType.redirect;\n}\n\nexport function isDataWithResponseInit(\n value: any\n): value is DataWithResponseInit {\n return (\n typeof value === \"object\" &&\n value != null &&\n \"type\" in value &&\n \"data\" in value &&\n \"init\" in value &&\n value.type === \"DataWithResponseInit\"\n );\n}\n\nexport function isDeferredData(value: any): value is DeferredData {\n let deferred: DeferredData = value;\n return (\n deferred &&\n typeof deferred === \"object\" &&\n typeof deferred.data === \"object\" &&\n typeof deferred.subscribe === \"function\" &&\n typeof deferred.cancel === \"function\" &&\n typeof deferred.resolveData === \"function\"\n );\n}\n\nfunction isResponse(value: any): value is Response {\n return (\n value != null &&\n typeof value.status === \"number\" &&\n typeof value.statusText === \"string\" &&\n typeof value.headers === \"object\" &&\n typeof value.body !== \"undefined\"\n );\n}\n\nfunction isRedirectResponse(result: any): result is Response {\n if (!isResponse(result)) {\n return false;\n }\n\n let status = result.status;\n let location = result.headers.get(\"Location\");\n return status >= 300 && status <= 399 && location != null;\n}\n\nfunction isValidMethod(method: string): method is FormMethod | V7_FormMethod {\n return validRequestMethods.has(method.toLowerCase() as FormMethod);\n}\n\nfunction isMutationMethod(\n method: string\n): method is MutationFormMethod | V7_MutationFormMethod {\n return validMutationMethods.has(method.toLowerCase() as MutationFormMethod);\n}\n\nasync function resolveNavigationDeferredResults(\n matches: (AgnosticDataRouteMatch | null)[],\n results: Record,\n signal: AbortSignal,\n currentMatches: AgnosticDataRouteMatch[],\n currentLoaderData: RouteData\n) {\n let entries = Object.entries(results);\n for (let index = 0; index < entries.length; index++) {\n let [routeId, result] = entries[index];\n let match = matches.find((m) => m?.route.id === routeId);\n // If we don't have a match, then we can have a deferred result to do\n // anything with. This is for revalidating fetchers where the route was\n // removed during HMR\n if (!match) {\n continue;\n }\n\n let currentMatch = currentMatches.find(\n (m) => m.route.id === match!.route.id\n );\n let isRevalidatingLoader =\n currentMatch != null &&\n !isNewRouteInstance(currentMatch, match) &&\n (currentLoaderData && currentLoaderData[match.route.id]) !== undefined;\n\n if (isDeferredResult(result) && isRevalidatingLoader) {\n // Note: we do not have to touch activeDeferreds here since we race them\n // against the signal in resolveDeferredData and they'll get aborted\n // there if needed\n await resolveDeferredData(result, signal, false).then((result) => {\n if (result) {\n results[routeId] = result;\n }\n });\n }\n }\n}\n\nasync function resolveFetcherDeferredResults(\n matches: (AgnosticDataRouteMatch | null)[],\n results: Record,\n revalidatingFetchers: RevalidatingFetcher[]\n) {\n for (let index = 0; index < revalidatingFetchers.length; index++) {\n let { key, routeId, controller } = revalidatingFetchers[index];\n let result = results[key];\n let match = matches.find((m) => m?.route.id === routeId);\n // If we don't have a match, then we can have a deferred result to do\n // anything with. This is for revalidating fetchers where the route was\n // removed during HMR\n if (!match) {\n continue;\n }\n\n if (isDeferredResult(result)) {\n // Note: we do not have to touch activeDeferreds here since we race them\n // against the signal in resolveDeferredData and they'll get aborted\n // there if needed\n invariant(\n controller,\n \"Expected an AbortController for revalidating fetcher deferred result\"\n );\n await resolveDeferredData(result, controller.signal, true).then(\n (result) => {\n if (result) {\n results[key] = result;\n }\n }\n );\n }\n }\n}\n\nasync function resolveDeferredData(\n result: DeferredResult,\n signal: AbortSignal,\n unwrap = false\n): Promise {\n let aborted = await result.deferredData.resolveData(signal);\n if (aborted) {\n return;\n }\n\n if (unwrap) {\n try {\n return {\n type: ResultType.data,\n data: result.deferredData.unwrappedData,\n };\n } catch (e) {\n // Handle any TrackedPromise._error values encountered while unwrapping\n return {\n type: ResultType.error,\n error: e,\n };\n }\n }\n\n return {\n type: ResultType.data,\n data: result.deferredData.data,\n };\n}\n\nfunction hasNakedIndexQuery(search: string): boolean {\n return new URLSearchParams(search).getAll(\"index\").some((v) => v === \"\");\n}\n\nfunction getTargetMatch(\n matches: AgnosticDataRouteMatch[],\n location: Location | string\n) {\n let search =\n typeof location === \"string\" ? parsePath(location).search : location.search;\n if (\n matches[matches.length - 1].route.index &&\n hasNakedIndexQuery(search || \"\")\n ) {\n // Return the leaf index route when index is present\n return matches[matches.length - 1];\n }\n // Otherwise grab the deepest \"path contributing\" match (ignoring index and\n // pathless layout routes)\n let pathMatches = getPathContributingMatches(matches);\n return pathMatches[pathMatches.length - 1];\n}\n\nfunction getSubmissionFromNavigation(\n navigation: Navigation\n): Submission | undefined {\n let { formMethod, formAction, formEncType, text, formData, json } =\n navigation;\n if (!formMethod || !formAction || !formEncType) {\n return;\n }\n\n if (text != null) {\n return {\n formMethod,\n formAction,\n formEncType,\n formData: undefined,\n json: undefined,\n text,\n };\n } else if (formData != null) {\n return {\n formMethod,\n formAction,\n formEncType,\n formData,\n json: undefined,\n text: undefined,\n };\n } else if (json !== undefined) {\n return {\n formMethod,\n formAction,\n formEncType,\n formData: undefined,\n json,\n text: undefined,\n };\n }\n}\n\nfunction getLoadingNavigation(\n location: Location,\n submission?: Submission\n): NavigationStates[\"Loading\"] {\n if (submission) {\n let navigation: NavigationStates[\"Loading\"] = {\n state: \"loading\",\n location,\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n };\n return navigation;\n } else {\n let navigation: NavigationStates[\"Loading\"] = {\n state: \"loading\",\n location,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n };\n return navigation;\n }\n}\n\nfunction getSubmittingNavigation(\n location: Location,\n submission: Submission\n): NavigationStates[\"Submitting\"] {\n let navigation: NavigationStates[\"Submitting\"] = {\n state: \"submitting\",\n location,\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n };\n return navigation;\n}\n\nfunction getLoadingFetcher(\n submission?: Submission,\n data?: Fetcher[\"data\"]\n): FetcherStates[\"Loading\"] {\n if (submission) {\n let fetcher: FetcherStates[\"Loading\"] = {\n state: \"loading\",\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n data,\n };\n return fetcher;\n } else {\n let fetcher: FetcherStates[\"Loading\"] = {\n state: \"loading\",\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n data,\n };\n return fetcher;\n }\n}\n\nfunction getSubmittingFetcher(\n submission: Submission,\n existingFetcher?: Fetcher\n): FetcherStates[\"Submitting\"] {\n let fetcher: FetcherStates[\"Submitting\"] = {\n state: \"submitting\",\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n data: existingFetcher ? existingFetcher.data : undefined,\n };\n return fetcher;\n}\n\nfunction getDoneFetcher(data: Fetcher[\"data\"]): FetcherStates[\"Idle\"] {\n let fetcher: FetcherStates[\"Idle\"] = {\n state: \"idle\",\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n data,\n };\n return fetcher;\n}\n\nfunction restoreAppliedTransitions(\n _window: Window,\n transitions: Map>\n) {\n try {\n let sessionPositions = _window.sessionStorage.getItem(\n TRANSITIONS_STORAGE_KEY\n );\n if (sessionPositions) {\n let json = JSON.parse(sessionPositions);\n for (let [k, v] of Object.entries(json || {})) {\n if (v && Array.isArray(v)) {\n transitions.set(k, new Set(v || []));\n }\n }\n }\n } catch (e) {\n // no-op, use default empty object\n }\n}\n\nfunction persistAppliedTransitions(\n _window: Window,\n transitions: Map>\n) {\n if (transitions.size > 0) {\n let json: Record = {};\n for (let [k, v] of transitions) {\n json[k] = [...v];\n }\n try {\n _window.sessionStorage.setItem(\n TRANSITIONS_STORAGE_KEY,\n JSON.stringify(json)\n );\n } catch (error) {\n warning(\n false,\n `Failed to save applied view transitions in sessionStorage (${error}).`\n );\n }\n }\n}\n//#endregion\n"],"names":["Action","PopStateEventType","createMemoryHistory","options","initialEntries","initialIndex","v5Compat","entries","map","entry","index","createMemoryLocation","state","undefined","clampIndex","length","action","Pop","listener","n","Math","min","max","getCurrentLocation","to","key","location","createLocation","pathname","warning","charAt","JSON","stringify","createHref","createPath","history","createURL","URL","encodeLocation","path","parsePath","search","hash","push","Push","nextLocation","splice","delta","replace","Replace","go","nextIndex","listen","fn","createBrowserHistory","createBrowserLocation","window","globalHistory","usr","createBrowserHref","getUrlBasedHistory","createHashHistory","createHashLocation","substr","startsWith","createHashHref","base","document","querySelector","href","getAttribute","url","hashIndex","indexOf","slice","validateHashLocation","invariant","value","message","Error","cond","console","warn","e","createKey","random","toString","getHistoryState","idx","current","_extends","_ref","parsedPath","searchIndex","getLocation","validateLocation","defaultView","getIndex","replaceState","handlePop","historyState","pushState","error","DOMException","name","assign","origin","addEventListener","removeEventListener","ResultType","immutableRouteKeys","Set","isIndexRoute","route","convertRoutesToDataRoutes","routes","mapRouteProperties","parentPath","manifest","treePath","String","id","join","children","indexRoute","pathOrLayoutRoute","matchRoutes","locationArg","basename","matchRoutesImpl","allowPartial","stripBasename","branches","flattenRoutes","rankRouteBranches","matches","decoded","decodePath","i","matchRouteBranch","convertRouteMatchToUiMatch","match","loaderData","params","data","handle","parentsMeta","flattenRoute","relativePath","meta","caseSensitive","childrenIndex","joinPaths","routesMeta","concat","score","computeScore","forEach","_route$path","includes","exploded","explodeOptionalSegments","segments","split","first","rest","isOptional","endsWith","required","restExploded","result","subpath","sort","a","b","compareIndexes","paramRe","dynamicSegmentValue","indexRouteValue","emptySegmentValue","staticSegmentValue","splatPenalty","isSplat","s","initialScore","some","filter","reduce","segment","test","siblings","every","branch","matchedParams","matchedPathname","end","remainingPathname","matchPath","Object","pathnameBase","normalizePathname","generatePath","originalPath","prefix","p","array","isLastSegment","star","keyMatch","optional","param","pattern","matcher","compiledParams","compilePath","captureGroups","memo","paramName","splatValue","regexpSource","_","RegExp","v","decodeURIComponent","toLowerCase","startIndex","nextChar","resolvePath","fromPathname","toPathname","removeDoubleSlashes","resolvePathname","substring","normalizeSearch","normalizeHash","relativeSegments","pop","getInvalidPathError","char","field","dest","getPathContributingMatches","getResolveToMatches","v7_relativeSplatPath","pathMatches","resolveTo","toArg","routePathnames","locationPathname","isPathRelative","isEmptyPath","from","routePathnameIndex","toSegments","shift","hasExplicitTrailingSlash","hasCurrentTrailingSlash","getToPathname","paths","json","init","responseInit","status","headers","Headers","has","set","Response","DataWithResponseInit","constructor","type","AbortedDeferredError","DeferredData","pendingKeysSet","subscribers","deferredKeys","Array","isArray","reject","abortPromise","Promise","r","controller","AbortController","onAbort","unlistenAbortSignal","signal","acc","_ref2","trackPromise","done","add","promise","race","then","onSettle","catch","defineProperty","get","aborted","delete","undefinedError","emit","settledKey","subscriber","subscribe","cancel","abort","k","resolveData","resolve","size","unwrappedData","_ref3","unwrapTrackedPromise","pendingKeys","isTrackedPromise","_tracked","_error","_data","defer","redirect","redirectDocument","response","ErrorResponseImpl","statusText","internal","isRouteErrorResponse","validMutationMethodsArr","validMutationMethods","validRequestMethodsArr","validRequestMethods","redirectStatusCodes","redirectPreserveMethodStatusCodes","IDLE_NAVIGATION","formMethod","formAction","formEncType","formData","text","IDLE_FETCHER","IDLE_BLOCKER","proceed","reset","ABSOLUTE_URL_REGEX","defaultMapRouteProperties","hasErrorBoundary","Boolean","TRANSITIONS_STORAGE_KEY","createRouter","routerWindow","isBrowser","createElement","isServer","detectErrorBoundary","dataRoutes","inFlightDataRoutes","dataStrategyImpl","dataStrategy","defaultDataStrategy","patchRoutesOnNavigationImpl","patchRoutesOnNavigation","future","v7_fetcherPersist","v7_normalizeFormMethod","v7_partialHydration","v7_prependBasename","v7_skipActionErrorRevalidation","unlistenHistory","savedScrollPositions","getScrollRestorationKey","getScrollPosition","initialScrollRestored","hydrationData","initialMatches","initialMatchesIsFOW","initialErrors","getInternalRouterError","getShortCircuitMatches","fogOfWar","checkFogOfWar","active","initialized","m","lazy","loader","errors","findIndex","shouldLoadRouteOnHydration","router","historyAction","navigation","restoreScrollPosition","preventScrollReset","revalidation","actionData","fetchers","Map","blockers","pendingAction","HistoryAction","pendingPreventScrollReset","pendingNavigationController","pendingViewTransitionEnabled","appliedViewTransitions","removePageHideEventListener","isUninterruptedRevalidation","isRevalidationRequired","cancelledDeferredRoutes","cancelledFetcherLoads","fetchControllers","incrementingLoadId","pendingNavigationLoadId","fetchReloadIds","fetchRedirectIds","fetchLoadMatches","activeFetchers","deletedFetchers","activeDeferreds","blockerFunctions","unblockBlockerHistoryUpdate","initialize","blockerKey","shouldBlockNavigation","currentLocation","nextHistoryUpdatePromise","updateBlocker","updateState","startNavigation","restoreAppliedTransitions","_saveAppliedTransitions","persistAppliedTransitions","initialHydration","dispose","clear","deleteFetcher","deleteBlocker","newState","opts","completedFetchers","deletedFetchersKeys","fetcher","viewTransitionOpts","flushSync","completeNavigation","_temp","_location$state","_location$state2","isActionReload","isMutationMethod","_isRedirect","keys","mergeLoaderData","priorPaths","toPaths","getSavedScrollPosition","navigate","normalizedPath","normalizeTo","fromRouteId","relative","submission","normalizeNavigateOptions","userReplace","pendingError","enableViewTransition","viewTransition","revalidate","interruptActiveLoads","startUninterruptedRevalidation","overrideNavigation","saveScrollPosition","routesToUse","loadingNavigation","isHashChangeOnly","notFoundMatches","handleNavigational404","request","createClientSideRequest","pendingActionResult","findNearestBoundary","actionResult","handleAction","shortCircuited","routeId","isErrorResult","getLoadingNavigation","updatedMatches","handleLoaders","fetcherSubmission","getActionDataForCommit","isFogOfWar","getSubmittingNavigation","discoverResult","discoverRoutes","boundaryId","partialMatches","actionMatch","getTargetMatch","method","results","callDataStrategy","isRedirectResult","normalizeRedirectLocation","startRedirectNavigation","isDeferredResult","boundaryMatch","activeSubmission","getSubmissionFromNavigation","shouldUpdateNavigationState","getUpdatedActionData","matchesToLoad","revalidatingFetchers","getMatchesToLoad","cancelActiveDeferreds","updatedFetchers","markFetchRedirectsDone","updates","getUpdatedRevalidatingFetchers","rf","abortFetcher","abortPendingFetchRevalidations","f","loaderResults","fetcherResults","callLoadersAndMaybeResolveData","findRedirect","processLoaderData","deferredData","didAbortFetchLoads","abortStaleFetchLoads","shouldUpdateFetchers","revalidatingFetcher","getLoadingFetcher","fetch","setFetcherError","handleFetcherAction","handleFetcherLoader","requestMatches","detectAndHandle405Error","existingFetcher","updateFetcherState","getSubmittingFetcher","abortController","fetchRequest","originatingLoadId","actionResults","getDoneFetcher","revalidationRequest","loadId","loadFetcher","staleKey","doneFetcher","resolveDeferredData","isNavigation","_temp2","redirectLocation","isDocumentReload","redirectHistoryAction","fetcherKey","dataResults","callDataStrategyImpl","isRedirectDataStrategyResultResult","normalizeRelativeRoutingRedirectResponse","convertDataStrategyResultToDataResult","fetchersToLoad","currentMatches","loaderResultsPromise","fetcherResultsPromise","all","resolveNavigationDeferredResults","resolveFetcherDeferredResults","getFetcher","deleteFetcherAndUpdateState","count","markFetchersDone","doneKeys","landedId","yeetedKeys","getBlocker","blocker","newBlocker","blockerFunction","predicate","cancelledRouteIds","dfd","enableScrollRestoration","positions","getPosition","getKey","y","getScrollKey","fogMatches","isNonHMR","localManifest","patch","patchRoutesImpl","newMatches","newPartialMatches","_internalSetRoutes","newRoutes","patchRoutes","_internalFetchControllers","_internalActiveDeferreds","UNSAFE_DEFERRED_SYMBOL","Symbol","createStaticHandler","v7_throwAbortReason","query","_temp3","requestContext","skipLoaderErrorBubbling","isValidMethod","methodNotAllowedMatches","statusCode","loaderHeaders","actionHeaders","queryImpl","isResponse","queryRoute","_temp4","find","values","_result$activeDeferre","routeMatch","submit","loadRouteData","isDataStrategyResult","isRedirectResponse","isRouteRequest","throwStaticHandlerAbortedError","Location","loaderRequest","Request","context","getLoaderMatchesUntilBoundary","processRouteLoaderData","executedLoaders","fromEntries","getStaticContextFromError","newContext","_deepestRenderedBoundaryId","reason","isSubmissionNavigation","body","prependBasename","contextualMatches","activeRouteMatch","nakedIndex","hasNakedIndexQuery","URLSearchParams","indexValues","getAll","append","qs","normalizeFormMethod","isFetcher","getInvalidBodyError","rawFormMethod","toUpperCase","stripHashFromPath","FormData","parse","searchParams","convertFormDataToSearchParams","convertSearchParamsToFormData","includeBoundary","skipActionErrorRevalidation","currentUrl","nextUrl","boundaryMatches","actionStatus","shouldSkipRevalidation","navigationMatches","isNewLoader","currentRouteMatch","nextRouteMatch","shouldRevalidateLoader","currentParams","nextParams","defaultShouldRevalidate","isNewRouteInstance","fetcherMatches","fetcherMatch","shouldRevalidate","hasData","hasError","hydrate","currentLoaderData","currentMatch","isNew","isMissingData","currentPath","loaderMatch","arg","routeChoice","_childrenToPatch","childrenToPatch","uniqueChildren","newRoute","existingRoute","isSameRoute","aChild","_existingRoute$childr","bChild","loadLazyRouteModule","lazyRoute","routeToUpdate","routeUpdates","lazyRouteProperty","staticRouteValue","isPropertyStaticallyDefined","_ref4","shouldLoad","loadRouteDefinitionsPromises","dsMatches","loadRoutePromise","handlerOverride","callLoaderOrAction","staticContext","onReject","runHandler","handler","actualHandler","ctx","handlerPromise","val","handlerError","dataStrategyResult","contentType","isDataWithResponseInit","_result$init3","_result$init4","_result$init","_result$init2","isDeferredData","_result$init5","_result$init6","deferred","_result$init7","_result$init8","trimmedMatches","historyInstance","invalidProtocols","normalizedLocation","protocol","isSameBasename","foundError","newLoaderData","mergedLoaderData","hasOwnProperty","eligibleMatches","reverse","_temp5","errorMessage","isRevalidatingLoader","unwrap","_window","transitions","sessionPositions","sessionStorage","getItem","setItem"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;EAAA;EACA;EACA;;EAEA;EACA;EACA;AACYA,MAAAA,MAAM,0BAANA,MAAM,EAAA;EAChB;EACF;EACA;EACA;EACA;EACA;EACA;IAPYA,MAAM,CAAA,KAAA,CAAA,GAAA,KAAA,CAAA;EAUhB;EACF;EACA;EACA;EACA;IAdYA,MAAM,CAAA,MAAA,CAAA,GAAA,MAAA,CAAA;EAiBhB;EACF;EACA;EACA;IApBYA,MAAM,CAAA,SAAA,CAAA,GAAA,SAAA,CAAA;EAAA,EAAA,OAANA,MAAM,CAAA;EAAA,CAAA,CAAA,EAAA,EAAA;;EAwBlB;EACA;EACA;;EAkBA;EACA;;EAEA;EACA;EACA;EACA;;EAgBA;EACA;EACA;;EAkBA;EACA;EACA;;EAKA;EACA;EACA;EACA;EACA;;EAGA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;EAgFA,MAAMC,iBAAiB,GAAG,UAAU,CAAA;EACpC;;EAEA;EACA;EACA;;EAEA;EACA;EACA;EACA;;EASA;EACA;EACA;EACA;EACA;;EAQA;EACA;EACA;EACA;EACO,SAASC,mBAAmBA,CACjCC,OAA6B,EACd;EAAA,EAAA,IADfA,OAA6B,KAAA,KAAA,CAAA,EAAA;MAA7BA,OAA6B,GAAG,EAAE,CAAA;EAAA,GAAA;IAElC,IAAI;MAAEC,cAAc,GAAG,CAAC,GAAG,CAAC;MAAEC,YAAY;EAAEC,IAAAA,QAAQ,GAAG,KAAA;EAAM,GAAC,GAAGH,OAAO,CAAA;IACxE,IAAII,OAAmB,CAAC;EACxBA,EAAAA,OAAO,GAAGH,cAAc,CAACI,GAAG,CAAC,CAACC,KAAK,EAAEC,KAAK,KACxCC,oBAAoB,CAClBF,KAAK,EACL,OAAOA,KAAK,KAAK,QAAQ,GAAG,IAAI,GAAGA,KAAK,CAACG,KAAK,EAC9CF,KAAK,KAAK,CAAC,GAAG,SAAS,GAA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AAA,CAAA,GAAA,UAAA,CAAA;IAAVA,UAAU,CAAA,OAAA,CAAA,GAAA,OAAA,CAAA;EAAA,EAAA,OAAVA,UAAU,CAAA;EAAA,CAAA,CAAA,EAAA,CAAA,CAAA;;EAOtB;EACA;EACA;;EAQA;EACA;EACA;;EAQA;EACA;EACA;;EAOA;EACA;EACA;;EAQA;EACA;EACA;;EAUA;EACA;EACA;EACA;;EAGA;EACA;EACA;EACA;;EAIA;EACA;EACA;EACA;;EAUA;;EAQA;EACA;EACA;EACA;EACA;;EA2BA;EACA;EACA;EACA;EACA;;EAOA;EACA;EACA;;EAEA;EACA;EACA;;EAIA;EACA;EACA;;EAIA;EACA;EACA;EACA;EACA;;EAKA;EACA;EACA;;EAQA;EACA;EACA;;EAQA;EACA;EACA;;EAiBA;EACA;EACA;EACA;EACA;EACA;EACA;;EAKA;EACA;EACA;EACA;EACA;EACA;;EAqBA;EACA;EACA;;EA4BA;EACA;EACA;EACA;;EAOA;EACA;EACA;EACA;EACA;;EASO,MAAMC,kBAAkB,GAAG,IAAIC,GAAG,CAAoB,CAC3D,MAAM,EACN,eAAe,EACf,MAAM,EACN,IAAI,EACJ,OAAO,EACP,UAAU,CACX,CAAC,CAAA;;EASF;EACA;EACA;EACA;;EAKA;EACA;EACA;;EAaA;EACA;EACA;;EAMA;EACA;EACA;;EAMA;EACA;EACA;EACA;;EAcA;EACA;EACA;;EAOA;;EAaA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;EAWA;EACA;EACA;;EAKA;EACA;EACA;;EAKA;EACA;EACA;;EA0BA,SAASC,YAAYA,CACnBC,KAA0B,EACS;EACnC,EAAA,OAAOA,KAAK,CAACvG,KAAK,KAAK,IAAI,CAAA;EAC7B,CAAA;;EAEA;EACA;EACO,SAASwG,yBAAyBA,CACvCC,MAA6B,EAC7BC,kBAA8C,EAC9CC,UAAoB,EACpBC,QAAuB,EACI;EAAA,EAAA,IAF3BD,UAAoB,KAAA,KAAA,CAAA,EAAA;EA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ACiD,CAAC,CAAC,GAAG,CAAC,GAAGtF,CAAC,CAAC,CAAA;EAClB,KAAA;MACA,IAAI;EACFuhB,MAAAA,OAAO,CAACG,cAAc,CAACE,OAAO,CAC5B9Z,uBAAuB,EACvB7T,IAAI,CAACC,SAAS,CAACmO,IAAI,CACrB,CAAC,CAAA;OACF,CAAC,OAAO7J,KAAK,EAAE;EACdzE,MAAAA,OAAO,CACL,KAAK,EACyDyE,6DAAAA,GAAAA,KAAK,OACrE,CAAC,CAAA;EACH,KAAA;EACF,GAAA;EACF,CAAA;EACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} apps/frontend/node_modules/@remix-run/router/dist/router.cjs.js.map:1:{"version":3,"file":"router.cjs.js","sources":["../history.ts","../utils.ts","../router.ts"],"sourcesContent":["////////////////////////////////////////////////////////////////////////////////\n//#region Types and Constants\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Actions represent the type of change to a location value.\n */\nexport enum Action {\n /**\n * A POP indicates a change to an arbitrary index in the history stack, such\n * as a back or forward navigation. It does not describe the direction of the\n * navigation, only that the current index changed.\n *\n * Note: This is the default action for newly created history objects.\n */\n Pop = \"POP\",\n\n /**\n * A PUSH indicates a new entry being added to the history stack, such as when\n * a link is clicked and a new page loads. When this happens, all subsequent\n * entries in the stack are lost.\n */\n Push = \"PUSH\",\n\n /**\n * A REPLACE indicates the entry at the current index in the history stack\n * being replaced by a new one.\n */\n Replace = \"REPLACE\",\n}\n\n/**\n * The pathname, search, and hash values of a URL.\n */\nexport interface Path {\n /**\n * A URL pathname, beginning with a /.\n */\n pathname: string;\n\n /**\n * A URL search string, beginning with a ?.\n */\n search: string;\n\n /**\n * A URL fragment identifier, beginning with a #.\n */\n hash: string;\n}\n\n// TODO: (v7) Change the Location generic default from `any` to `unknown` and\n// remove Remix `useLocation` wrapper.\n\n/**\n * An entry in a history stack. A location contains information about the\n * URL path, as well as possibly some arbitrary state and a key.\n */\nexport interface Location extends Path {\n /**\n * A value of arbitrary data associated with this location.\n */\n state: State;\n\n /**\n * A unique string associated with this location. May be used to safely store\n * and retrieve data in some other storage API, like `localStorage`.\n *\n * Note: This value is always \"default\" on the initial location.\n */\n key: string;\n}\n\n/**\n * A change to the current location.\n */\nexport interface Update {\n /**\n * The action that triggered the change.\n */\n action: Action;\n\n /**\n * The new location.\n */\n location: Location;\n\n /**\n * The delta between this location and the former location in the history stack\n */\n delta: number | null;\n}\n\n/**\n * A function that receives notifications about location changes.\n */\nexport interface Listener {\n (update: Update): void;\n}\n\n/**\n * Describes a location that is the destination of some navigation, either via\n * `history.push` or `history.replace`. This may be either a URL or the pieces\n * of a URL path.\n */\nexport type To = string | Partial;\n\n/**\n * A history is an interface to the navigation stack. The history serves as the\n * source of truth for the current location, as well as provides a set of\n * methods that may be used to change it.\n *\n * It is similar to the DOM's `window.history` object, but with a smaller, more\n * focused API.\n */\nexport interface History {\n /**\n * The last action that modified the current location. This will always be\n * Action.Pop when a history instance is first created. This value is mutable.\n */\n readonly action: Action;\n\n /**\n * The current location. This value is mutable.\n */\n readonly location: Location;\n\n /**\n * Returns a valid href for the given `to` value that may be used as\n * the value of an attribute.\n *\n * @param to - The destination URL\n */\n createHref(to: To): string;\n\n /**\n * Returns a URL for the given `to` value\n *\n * @param to - The destination URL\n */\n createURL(to: To): URL;\n\n /**\n * Encode a location the same way window.history would do (no-op for memory\n * history) so we ensure our PUSH/REPLACE navigations for data routers\n * behave the same as POP\n *\n * @param to Unencoded path\n */\n encodeLocation(to: To): Path;\n\n /**\n * Pushes a new location onto the history stack, increasing its length by one.\n * If there were any entries in the stack after the current one, they are\n * lost.\n *\n * @param to - The new URL\n * @param state - Data to associate with the new location\n */\n push(to: To, state?: any): void;\n\n /**\n * Replaces the current location in the history stack with a new one. The\n * location that was replaced will no longer be available.\n *\n * @param to - The new URL\n * @param state - Data to associate with the new location\n */\n replace(to: To, state?: any): void;\n\n /**\n * Navigates `n` entries backward/forward in the history stack relative to the\n * current index. For example, a \"back\" navigation would use go(-1).\n *\n * @param delta - The delta in the stack index\n */\n go(delta: number): void;\n\n /**\n * Sets up a listener that will be called whenever the current location\n * changes.\n *\n * @param listener - A function that will be called when the location changes\n * @returns unlisten - A function that may be used to stop listening\n */\n listen(listener: Listener): () => void;\n}\n\ntype HistoryState = {\n usr: any;\n key?: string;\n idx: number;\n};\n\nconst PopStateEventType = \"popstate\";\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Memory History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A user-supplied object that describes a location. Used when providing\n * entries to `createMemoryHistory` via its `initialEntries` option.\n */\nexport type InitialEntry = string | Partial;\n\nexport type MemoryHistoryOptions = {\n initialEntries?: InitialEntry[];\n initialIndex?: number;\n v5Compat?: boolean;\n};\n\n/**\n * A memory history stores locations in memory. This is useful in stateful\n * environments where there is no web browser, such as node tests or React\n * Native.\n */\nexport interface MemoryHistory extends History {\n /**\n * The current index in the history stack.\n */\n readonly index: number;\n}\n\n/**\n * Memory history stores the current location in memory. It is designed for use\n * in stateful non-browser environments like tests and React Native.\n */\nexport function createMemoryHistory(\n options: MemoryHistoryOptions = {}\n): MemoryHistory {\n let { initialEntries = [\"/\"], initialIndex, v5Compat = false } = options;\n let entries: Location[]; // Declare so we can access from createMemoryLocation\n entries = initialEntries.map((entry, index) =>\n createMemoryLocation(\n entry,\n typeof entry === \"string\" ? null : entry.state,\n index === 0 ? \"default\" : undefined\n )\n );\n let index = clampIndex(\n initialIndex == null ? entries.length - 1 : initialIndex\n );\n let action = Action.Pop;\n let listener: Listener | null = null;\n\n function clampIndex(n: number): number {\n return Math.min(Math.max(n, 0), entries.length - 1);\n }\n function getCurrentLocation(): Location {\n return entries[index];\n }\n function createMemoryLocation(\n to: To,\n state: any = null,\n key?: string\n ): Location {\n let location = createLocation(\n entries ? getCurrentLocation().pathname : \"/\",\n to,\n state,\n key\n );\n warning(\n location.pathname.charAt(0) === \"/\",\n `relative pathnames are not supported in memory history: ${JSON.stringify(\n to\n )}`\n );\n return location;\n }\n\n function createHref(to: To) {\n return typeof to === \"string\" ? to : createPath(to);\n }\n\n let history: MemoryHistory = {\n get index() {\n return index;\n },\n get action() {\n return action;\n },\n get location() {\n return getCurrentLocation();\n },\n createHref,\n createURL(to) {\n return new URL(createHref(to), \"http://localhost\");\n },\n encodeLocation(to: To) {\n let path = typeof to === \"string\" ? parsePath(to) : to;\n return {\n pathname: path.pathname || \"\",\n search: path.search || \"\",\n hash: path.hash || \"\",\n };\n },\n push(to, state) {\n action = Action.Push;\n let nextLocation = createMemoryLocation(to, state);\n index += 1;\n entries.splice(index, entries.length, nextLocation);\n if (v5Compat && listener) {\n listener({ action, location: nextLocation, delta: 1 });\n }\n },\n replace(to, state) {\n action = Action.Replace;\n let nextLocation = createMemoryLocation(to, state);\n entries[index] = nextLocation;\n if (v5Compat && listener) {\n listener({ action, location: nextLocation, delta: 0 });\n }\n },\n go(delta) {\n action = Action.Pop;\n let nextIndex = clampIndex(index + delta);\n let nextLocation = entries[nextIndex];\n index = nextIndex;\n if (listener) {\n listener({ action, location: nextLocation, delta });\n }\n },\n listen(fn: Listener) {\n listener = fn;\n return () => {\n listener = null;\n };\n },\n };\n\n return history;\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Browser History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A browser history stores the current location in regular URLs in a web\n * browser environment. This is the standard for most web apps and provides the\n * cleanest URLs the browser's address bar.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#browserhistory\n */\nexport interface BrowserHistory extends UrlHistory {}\n\nexport type BrowserHistoryOptions = UrlHistoryOptions;\n\n/**\n * Browser history stores the location in regular URLs. This is the standard for\n * most web apps, but it requires some configuration on the server to ensure you\n * serve the same app at multiple URLs.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory\n */\nexport function createBrowserHistory(\n options: BrowserHistoryOptions = {}\n): BrowserHistory {\n function createBrowserLocation(\n window: Window,\n globalHistory: Window[\"history\"]\n ) {\n let { pathname, search, hash } = window.location;\n return createLocation(\n \"\",\n { pathname, search, hash },\n // state defaults to `null` because `window.history.state` does\n (globalHistory.state && globalHistory.state.usr) || null,\n (globalHistory.state && globalHistory.state.key) || \"default\"\n );\n }\n\n function createBrowserHref(window: Window, to: To) {\n return typeof to === \"string\" ? to : createPath(to);\n }\n\n return getUrlBasedHistory(\n createBrowserLocation,\n createBrowserHref,\n null,\n options\n );\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Hash History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A hash history stores the current location in the fragment identifier portion\n * of the URL in a web browser environment.\n *\n * This is ideal for apps that do not control the server for some reason\n * (because the fragment identifier is never sent to the server), including some\n * shared hosting environments that do not provide fine-grained controls over\n * which pages are served at which URLs.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#hashhistory\n */\nexport interface HashHistory extends UrlHistory {}\n\nexport type HashHistoryOptions = UrlHistoryOptions;\n\n/**\n * Hash history stores the location in window.location.hash. This makes it ideal\n * for situations where you don't want to send the location to the server for\n * some reason, either because you do cannot configure it or the URL space is\n * reserved for something else.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory\n */\nexport function createHashHistory(\n options: HashHistoryOptions = {}\n): HashHistory {\n function createHashLocation(\n window: Window,\n globalHistory: Window[\"history\"]\n ) {\n let {\n pathname = \"/\",\n search = \"\",\n hash = \"\",\n } = parsePath(window.location.hash.substr(1));\n\n // Hash URL should always have a leading / just like window.location.pathname\n // does, so if an app ends up at a route like /#something then we add a\n // leading slash so all of our path-matching behaves the same as if it would\n // in a browser router. This is particularly important when there exists a\n // root splat route () since that matches internally against\n // \"/*\" and we'd expect /#something to 404 in a hash router app.\n if (!pathname.startsWith(\"/\") && !pathname.startsWith(\".\")) {\n pathname = \"/\" + pathname;\n }\n\n return createLocation(\n \"\",\n { pathname, search, hash },\n // state defaults to `null` because `window.history.state` does\n (globalHistory.state && globalHistory.state.usr) || null,\n (globalHistory.state && globalHistory.state.key) || \"default\"\n );\n }\n\n function createHashHref(window: Window, to: To) {\n let base = window.document.querySelector(\"base\");\n let href = \"\";\n\n if (base && base.getAttribute(\"href\")) {\n let url = window.location.href;\n let hashIndex = url.indexOf(\"#\");\n href = hashIndex === -1 ? url : url.slice(0, hashIndex);\n }\n\n return href + \"#\" + (typeof to === \"string\" ? to : createPath(to));\n }\n\n function validateHashLocation(location: Location, to: To) {\n warning(\n location.pathname.charAt(0) === \"/\",\n `relative pathnames are not supported in hash history.push(${JSON.stringify(\n to\n )})`\n );\n }\n\n return getUrlBasedHistory(\n createHashLocation,\n createHashHref,\n validateHashLocation,\n options\n );\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region UTILS\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * @private\n */\nexport function invariant(value: boolean, message?: string): asserts value;\nexport function invariant(\n value: T | null | undefined,\n message?: string\n): asserts value is T;\nexport function invariant(value: any, message?: string) {\n if (value === false || value === null || typeof value === \"undefined\") {\n throw new Error(message);\n }\n}\n\nexport function warning(cond: any, message: string) {\n if (!cond) {\n // eslint-disable-next-line no-console\n if (typeof console !== \"undefined\") console.warn(message);\n\n try {\n // Welcome to debugging history!\n //\n // This error is thrown as a convenience, so you can more easily\n // find the source for a warning that appears in the console by\n // enabling \"pause on exceptions\" in your JavaScript debugger.\n throw new Error(message);\n // eslint-disable-next-line no-empty\n } catch (e) {}\n }\n}\n\nfunction createKey() {\n return Math.random().toString(36).substr(2, 8);\n}\n\n/**\n * For browser-based histories, we combine the state and key into an object\n */\nfunction getHistoryState(location: Location, index: number): HistoryState {\n return {\n usr: location.state,\n key: location.key,\n idx: index,\n };\n}\n\n/**\n * Creates a Location object with a unique key from the given Path\n */\nexport function createLocation(\n current: string | Location,\n to: To,\n state: any = null,\n key?: string\n): Readonly {\n let location: Readonly = {\n pathname: typeof current === \"string\" ? current : current.pathname,\n search: \"\",\n hash: \"\",\n ...(typeof to === \"string\" ? parsePath(to) : to),\n state,\n // TODO: This could be cleaned up. push/replace should probably just take\n // full Locations now and avoid the need to run through this flow at all\n // But that's a pretty big refactor to the current test suite so going to\n // keep as is for the time being and just let any incoming keys take precedence\n key: (to && (to as Location).key) || key || createKey(),\n };\n return location;\n}\n\n/**\n * Creates a string URL path from the given pathname, search, and hash components.\n */\nexport function createPath({\n pathname = \"/\",\n search = \"\",\n hash = \"\",\n}: Partial) {\n if (search && search !== \"?\")\n pathname += search.charAt(0) === \"?\" ? search : \"?\" + search;\n if (hash && hash !== \"#\")\n pathname += hash.charAt(0) === \"#\" ? hash : \"#\" + hash;\n return pathname;\n}\n\n/**\n * Parses a string URL path into its separate pathname, search, and hash components.\n */\nexport function parsePath(path: string): Partial {\n let parsedPath: Partial = {};\n\n if (path) {\n let hashIndex = path.indexOf(\"#\");\n if (hashIndex >= 0) {\n parsedPath.hash = path.substr(hashIndex);\n path = path.substr(0, hashIndex);\n }\n\n let searchIndex = path.indexOf(\"?\");\n if (searchIndex >= 0) {\n parsedPath.search = path.substr(searchIndex);\n path = path.substr(0, searchIndex);\n }\n\n if (path) {\n parsedPath.pathname = path;\n }\n }\n\n return parsedPath;\n}\n\nexport interface UrlHistory extends History {}\n\nexport type UrlHistoryOptions = {\n window?: Window;\n v5Compat?: boolean;\n};\n\nfunction getUrlBasedHistory(\n getLocation: (window: Window, globalHistory: Window[\"history\"]) => Location,\n createHref: (window: Window, to: To) => string,\n validateLocation: ((location: Location, to: To) => void) | null,\n options: UrlHistoryOptions = {}\n): UrlHistory {\n let { window = document.defaultView!, v5Compat = false } = options;\n let globalHistory = window.history;\n let action = Action.Pop;\n let listener: Listener | null = null;\n\n let index = getIndex()!;\n // Index should only be null when we initialize. If not, it's because the\n // user called history.pushState or history.replaceState directly, in which\n // case we should log a warning as it will result in bugs.\n if (index == null) {\n index = 0;\n globalHistory.replaceState({ ...globalHistory.state, idx: index }, \"\");\n }\n\n function getIndex(): number {\n let state = globalHistory.state || { idx: null };\n return state.idx;\n }\n\n function handlePop() {\n action = Action.Pop;\n let nextIndex = getIndex();\n let delta = nextIndex == null ? null : nextIndex - index;\n index = nextIndex;\n if (listener) {\n listener({ action, location: history.location, delta });\n }\n }\n\n function push(to: To, state?: any) {\n action = Action.Push;\n let location = createLocation(history.location, to, state);\n if (validateLocation) validateLocation(location, to);\n\n index = getIndex() + 1;\n let historyState = getHistoryState(location, index);\n let url = history.createHref(location);\n\n // try...catch because iOS limits us to 100 pushState calls :/\n try {\n globalHistory.pushState(historyState, \"\", url);\n } catch (error) {\n // If the exception is because `state` can't be serialized, let that throw\n // outwards just like a replace call would so the dev knows the cause\n // https://html.spec.whatwg.org/multipage/nav-history-apis.html#shared-history-push/replace-state-steps\n // https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeinternal\n if (error instanceof DOMException && error.name === \"DataCloneError\") {\n throw error;\n }\n // They are going to lose state here, but there is no real\n // way to warn them about it since the page will refresh...\n window.location.assign(url);\n }\n\n if (v5Compat && listener) {\n listener({ action, location: history.location, delta: 1 });\n }\n }\n\n function replace(to: To, state?: any) {\n action = Action.Replace;\n let location = createLocation(history.location, to, state);\n if (validateLocation) validateLocation(location, to);\n\n index = getIndex();\n let historyState = getHistoryState(location, index);\n let url = history.createHref(location);\n globalHistory.replaceState(historyState, \"\", url);\n\n if (v5Compat && listener) {\n listener({ action, location: history.location, delta: 0 });\n }\n }\n\n function createURL(to: To): URL {\n // window.location.origin is \"null\" (the literal string value) in Firefox\n // under certain conditions, notably when serving from a local HTML file\n // See https://bugzilla.mozilla.org/show_bug.cgi?id=878297\n let base =\n window.location.origin !== \"null\"\n ? window.location.origin\n : window.location.href;\n\n let href = typeof to === \"string\" ? to : createPath(to);\n // Treating this as a full URL will strip any trailing spaces so we need to\n // pre-encode them since they might be part of a matching splat param from\n // an ancestor route\n href = href.replace(/ $/, \"%20\");\n invariant(\n base,\n `No window.location.(origin|href) available to create URL for href: ${href}`\n );\n return new URL(href, base);\n }\n\n let history: History = {\n get action() {\n return action;\n },\n get location() {\n return getLocation(window, globalHistory);\n },\n listen(fn: Listener) {\n if (listener) {\n throw new Error(\"A history only accepts one active listener\");\n }\n window.addEventListener(PopStateEventType, handlePop);\n listener = fn;\n\n return () => {\n window.removeEventListener(PopStateEventType, handlePop);\n listener = null;\n };\n },\n createHref(to) {\n return createHref(window, to);\n },\n createURL,\n encodeLocation(to) {\n // Encode a Location the same way window.location would\n let url = createURL(to);\n return {\n pathname: url.pathname,\n search: url.search,\n hash: url.hash,\n };\n },\n push,\n replace,\n go(n) {\n return globalHistory.go(n);\n },\n };\n\n return history;\n}\n\n//#endregion\n","import type { Location, Path, To } from \"./history\";\nimport { invariant, parsePath, warning } from \"./history\";\n\n/**\n * Map of routeId -> data returned from a loader/action/error\n */\nexport interface RouteData {\n [routeId: string]: any;\n}\n\nexport enum ResultType {\n data = \"data\",\n deferred = \"deferred\",\n redirect = \"redirect\",\n error = \"error\",\n}\n\n/**\n * Successful result from a loader or action\n */\nexport interface SuccessResult {\n type: ResultType.data;\n data: unknown;\n statusCode?: number;\n headers?: Headers;\n}\n\n/**\n * Successful defer() result from a loader or action\n */\nexport interface DeferredResult {\n type: ResultType.deferred;\n deferredData: DeferredData;\n statusCode?: number;\n headers?: Headers;\n}\n\n/**\n * Redirect result from a loader or action\n */\nexport interface RedirectResult {\n type: ResultType.redirect;\n // We keep the raw Response for redirects so we can return it verbatim\n response: Response;\n}\n\n/**\n * Unsuccessful result from a loader or action\n */\nexport interface ErrorResult {\n type: ResultType.error;\n error: unknown;\n statusCode?: number;\n headers?: Headers;\n}\n\n/**\n * Result from a loader or action - potentially successful or unsuccessful\n */\nexport type DataResult =\n | SuccessResult\n | DeferredResult\n | RedirectResult\n | ErrorResult;\n\ntype LowerCaseFormMethod = \"get\" | \"post\" | \"put\" | \"patch\" | \"delete\";\ntype UpperCaseFormMethod = Uppercase;\n\n/**\n * Users can specify either lowercase or uppercase form methods on ``,\n * useSubmit(), ``, etc.\n */\nexport type HTMLFormMethod = LowerCaseFormMethod | UpperCaseFormMethod;\n\n/**\n * Active navigation/fetcher form methods are exposed in lowercase on the\n * RouterState\n */\nexport type FormMethod = LowerCaseFormMethod;\nexport type MutationFormMethod = Exclude;\n\n/**\n * In v7, active navigation/fetcher form methods are exposed in uppercase on the\n * RouterState. This is to align with the normalization done via fetch().\n */\nexport type V7_FormMethod = UpperCaseFormMethod;\nexport type V7_MutationFormMethod = Exclude;\n\nexport type FormEncType =\n | \"application/x-www-form-urlencoded\"\n | \"multipart/form-data\"\n | \"application/json\"\n | \"text/plain\";\n\n// Thanks https://github.com/sindresorhus/type-fest!\ntype JsonObject = { [Key in string]: JsonValue } & {\n [Key in string]?: JsonValue | undefined;\n};\ntype JsonArray = JsonValue[] | readonly JsonValue[];\ntype JsonPrimitive = string | number | boolean | null;\ntype JsonValue = JsonPrimitive | JsonObject | JsonArray;\n\n/**\n * @private\n * Internal interface to pass around for action submissions, not intended for\n * external consumption\n */\nexport type Submission =\n | {\n formMethod: FormMethod | V7_FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: FormData;\n json: undefined;\n text: undefined;\n }\n | {\n formMethod: FormMethod | V7_FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: undefined;\n json: JsonValue;\n text: undefined;\n }\n | {\n formMethod: FormMethod | V7_FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: undefined;\n json: undefined;\n text: string;\n };\n\n/**\n * @private\n * Arguments passed to route loader/action functions. Same for now but we keep\n * this as a private implementation detail in case they diverge in the future.\n */\ninterface DataFunctionArgs {\n request: Request;\n params: Params;\n context?: Context;\n}\n\n// TODO: (v7) Change the defaults from any to unknown in and remove Remix wrappers:\n// ActionFunction, ActionFunctionArgs, LoaderFunction, LoaderFunctionArgs\n// Also, make them a type alias instead of an interface\n\n/**\n * Arguments passed to loader functions\n */\nexport interface LoaderFunctionArgs\n extends DataFunctionArgs {}\n\n/**\n * Arguments passed to action functions\n */\nexport interface ActionFunctionArgs\n extends DataFunctionArgs {}\n\n/**\n * Loaders and actions can return anything except `undefined` (`null` is a\n * valid return value if there is no data to return). Responses are preferred\n * and will ease any future migration to Remix\n */\ntype DataFunctionValue = Response | NonNullable | null;\n\ntype DataFunctionReturnValue = Promise | DataFunctionValue;\n\n/**\n * Route loader function signature\n */\nexport type LoaderFunction = {\n (\n args: LoaderFunctionArgs,\n handlerCtx?: unknown\n ): DataFunctionReturnValue;\n} & { hydrate?: boolean };\n\n/**\n * Route action function signature\n */\nexport interface ActionFunction {\n (\n args: ActionFunctionArgs,\n handlerCtx?: unknown\n ): DataFunctionReturnValue;\n}\n\n/**\n * Arguments passed to shouldRevalidate function\n */\nexport interface ShouldRevalidateFunctionArgs {\n currentUrl: URL;\n currentParams: AgnosticDataRouteMatch[\"params\"];\n nextUrl: URL;\n nextParams: AgnosticDataRouteMatch[\"params\"];\n formMethod?: Submission[\"formMethod\"];\n formAction?: Submission[\"formAction\"];\n formEncType?: Submission[\"formEncType\"];\n text?: Submission[\"text\"];\n formData?: Submission[\"formData\"];\n json?: Submission[\"json\"];\n actionStatus?: number;\n actionResult?: any;\n defaultShouldRevalidate: boolean;\n}\n\n/**\n * Route shouldRevalidate function signature. This runs after any submission\n * (navigation or fetcher), so we flatten the navigation/fetcher submission\n * onto the arguments. It shouldn't matter whether it came from a navigation\n * or a fetcher, what really matters is the URLs and the formData since loaders\n * have to re-run based on the data models that were potentially mutated.\n */\nexport interface ShouldRevalidateFunction {\n (args: ShouldRevalidateFunctionArgs): boolean;\n}\n\n/**\n * Function provided by the framework-aware layers to set `hasErrorBoundary`\n * from the framework-aware `errorElement` prop\n *\n * @deprecated Use `mapRouteProperties` instead\n */\nexport interface DetectErrorBoundaryFunction {\n (route: AgnosticRouteObject): boolean;\n}\n\nexport interface DataStrategyMatch\n extends AgnosticRouteMatch {\n shouldLoad: boolean;\n resolve: (\n handlerOverride?: (\n handler: (ctx?: unknown) => DataFunctionReturnValue\n ) => DataFunctionReturnValue\n ) => Promise;\n}\n\nexport interface DataStrategyFunctionArgs\n extends DataFunctionArgs {\n matches: DataStrategyMatch[];\n fetcherKey: string | null;\n}\n\n/**\n * Result from a loader or action called via dataStrategy\n */\nexport interface DataStrategyResult {\n type: \"data\" | \"error\";\n result: unknown; // data, Error, Response, DeferredData, DataWithResponseInit\n}\n\nexport interface DataStrategyFunction {\n (args: DataStrategyFunctionArgs): Promise>;\n}\n\nexport type AgnosticPatchRoutesOnNavigationFunctionArgs<\n O extends AgnosticRouteObject = AgnosticRouteObject,\n M extends AgnosticRouteMatch = AgnosticRouteMatch\n> = {\n signal: AbortSignal;\n path: string;\n matches: M[];\n fetcherKey: string | undefined;\n patch: (routeId: string | null, children: O[]) => void;\n};\n\nexport type AgnosticPatchRoutesOnNavigationFunction<\n O extends AgnosticRouteObject = AgnosticRouteObject,\n M extends AgnosticRouteMatch = AgnosticRouteMatch\n> = (\n opts: AgnosticPatchRoutesOnNavigationFunctionArgs\n) => void | Promise;\n\n/**\n * Function provided by the framework-aware layers to set any framework-specific\n * properties from framework-agnostic properties\n */\nexport interface MapRoutePropertiesFunction {\n (route: AgnosticRouteObject): {\n hasErrorBoundary: boolean;\n } & Record;\n}\n\n/**\n * Keys we cannot change from within a lazy() function. We spread all other keys\n * onto the route. Either they're meaningful to the router, or they'll get\n * ignored.\n */\nexport type ImmutableRouteKey =\n | \"lazy\"\n | \"caseSensitive\"\n | \"path\"\n | \"id\"\n | \"index\"\n | \"children\";\n\nexport const immutableRouteKeys = new Set([\n \"lazy\",\n \"caseSensitive\",\n \"path\",\n \"id\",\n \"index\",\n \"children\",\n]);\n\ntype RequireOne = Exclude<\n {\n [K in keyof T]: K extends Key ? Omit & Required> : never;\n }[keyof T],\n undefined\n>;\n\n/**\n * lazy() function to load a route definition, which can add non-matching\n * related properties to a route\n */\nexport interface LazyRouteFunction {\n (): Promise>>;\n}\n\n/**\n * Base RouteObject with common props shared by all types of routes\n */\ntype AgnosticBaseRouteObject = {\n caseSensitive?: boolean;\n path?: string;\n id?: string;\n loader?: LoaderFunction | boolean;\n action?: ActionFunction | boolean;\n hasErrorBoundary?: boolean;\n shouldRevalidate?: ShouldRevalidateFunction;\n handle?: any;\n lazy?: LazyRouteFunction;\n};\n\n/**\n * Index routes must not have children\n */\nexport type AgnosticIndexRouteObject = AgnosticBaseRouteObject & {\n children?: undefined;\n index: true;\n};\n\n/**\n * Non-index routes may have children, but cannot have index\n */\nexport type AgnosticNonIndexRouteObject = AgnosticBaseRouteObject & {\n children?: AgnosticRouteObject[];\n index?: false;\n};\n\n/**\n * A route object represents a logical route, with (optionally) its child\n * routes organized in a tree-like structure.\n */\nexport type AgnosticRouteObject =\n | AgnosticIndexRouteObject\n | AgnosticNonIndexRouteObject;\n\nexport type AgnosticDataIndexRouteObject = AgnosticIndexRouteObject & {\n id: string;\n};\n\nexport type AgnosticDataNonIndexRouteObject = AgnosticNonIndexRouteObject & {\n children?: AgnosticDataRouteObject[];\n id: string;\n};\n\n/**\n * A data route object, which is just a RouteObject with a required unique ID\n */\nexport type AgnosticDataRouteObject =\n | AgnosticDataIndexRouteObject\n | AgnosticDataNonIndexRouteObject;\n\nexport type RouteManifest = Record;\n\n// Recursive helper for finding path parameters in the absence of wildcards\ntype _PathParam =\n // split path into individual path segments\n Path extends `${infer L}/${infer R}`\n ? _PathParam | _PathParam\n : // find params after `:`\n Path extends `:${infer Param}`\n ? Param extends `${infer Optional}?`\n ? Optional\n : Param\n : // otherwise, there aren't any params present\n never;\n\n/**\n * Examples:\n * \"/a/b/*\" -> \"*\"\n * \":a\" -> \"a\"\n * \"/a/:b\" -> \"b\"\n * \"/a/blahblahblah:b\" -> \"b\"\n * \"/:a/:b\" -> \"a\" | \"b\"\n * \"/:a/b/:c/*\" -> \"a\" | \"c\" | \"*\"\n */\nexport type PathParam =\n // check if path is just a wildcard\n Path extends \"*\" | \"/*\"\n ? \"*\"\n : // look for wildcard at the end of the path\n Path extends `${infer Rest}/*`\n ? \"*\" | _PathParam\n : // look for params in the absence of wildcards\n _PathParam;\n\n// Attempt to parse the given string segment. If it fails, then just return the\n// plain string type as a default fallback. Otherwise, return the union of the\n// parsed string literals that were referenced as dynamic segments in the route.\nexport type ParamParseKey =\n // if you could not find path params, fallback to `string`\n [PathParam] extends [never] ? string : PathParam;\n\n/**\n * The parameters that were parsed from the URL path.\n */\nexport type Params = {\n readonly [key in Key]: string | undefined;\n};\n\n/**\n * A RouteMatch contains info about how a route matched a URL.\n */\nexport interface AgnosticRouteMatch<\n ParamKey extends string = string,\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n /**\n * The names and values of dynamic parameters in the URL.\n */\n params: Params;\n /**\n * The portion of the URL pathname that was matched.\n */\n pathname: string;\n /**\n * The portion of the URL pathname that was matched before child routes.\n */\n pathnameBase: string;\n /**\n * The route object that was used to match.\n */\n route: RouteObjectType;\n}\n\nexport interface AgnosticDataRouteMatch\n extends AgnosticRouteMatch {}\n\nfunction isIndexRoute(\n route: AgnosticRouteObject\n): route is AgnosticIndexRouteObject {\n return route.index === true;\n}\n\n// Walk the route tree generating unique IDs where necessary, so we are working\n// solely with AgnosticDataRouteObject's within the Router\nexport function convertRoutesToDataRoutes(\n routes: AgnosticRouteObject[],\n mapRouteProperties: MapRoutePropertiesFunction,\n parentPath: string[] = [],\n manifest: RouteManifest = {}\n): AgnosticDataRouteObject[] {\n return routes.map((route, index) => {\n let treePath = [...parentPath, String(index)];\n let id = typeof route.id === \"string\" ? route.id : treePath.join(\"-\");\n invariant(\n route.index !== true || !route.children,\n `Cannot specify children on an index route`\n );\n invariant(\n !manifest[id],\n `Found a route id collision on id \"${id}\". Route ` +\n \"id's must be globally unique within Data Router usages\"\n );\n\n if (isIndexRoute(route)) {\n let indexRoute: AgnosticDataIndexRouteObject = {\n ...route,\n ...mapRouteProperties(route),\n id,\n };\n manifest[id] = indexRoute;\n return indexRoute;\n } else {\n let pathOrLayoutRoute: AgnosticDataNonIndexRouteObject = {\n ...route,\n ...mapRouteProperties(route),\n id,\n children: undefined,\n };\n manifest[id] = pathOrLayoutRoute;\n\n if (route.children) {\n pathOrLayoutRoute.children = convertRoutesToDataRoutes(\n route.children,\n mapRouteProperties,\n treePath,\n manifest\n );\n }\n\n return pathOrLayoutRoute;\n }\n });\n}\n\n/**\n * Matches the given routes to a location and returns the match data.\n *\n * @see https://reactrouter.com/v6/utils/match-routes\n */\nexport function matchRoutes<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n routes: RouteObjectType[],\n locationArg: Partial | string,\n basename = \"/\"\n): AgnosticRouteMatch[] | null {\n return matchRoutesImpl(routes, locationArg, basename, false);\n}\n\nexport function matchRoutesImpl<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n routes: RouteObjectType[],\n locationArg: Partial | string,\n basename: string,\n allowPartial: boolean\n): AgnosticRouteMatch[] | null {\n let location =\n typeof locationArg === \"string\" ? parsePath(locationArg) : locationArg;\n\n let pathname = stripBasename(location.pathname || \"/\", basename);\n\n if (pathname == null) {\n return null;\n }\n\n let branches = flattenRoutes(routes);\n rankRouteBranches(branches);\n\n let matches = null;\n let decoded = decodePath(pathname);\n for (let i = 0; matches == null && i < branches.length; ++i) {\n // Incoming pathnames are generally encoded from either window.location\n // or from router.navigate, but we want to match against the unencoded\n // paths in the route definitions. Memory router locations won't be\n // encoded here but there also shouldn't be anything to decode so this\n // should be a safe operation. This avoids needing matchRoutes to be\n // history-aware.\n matches = matchRouteBranch(\n branches[i],\n decoded,\n allowPartial\n );\n }\n\n return matches;\n}\n\nexport interface UIMatch {\n id: string;\n pathname: string;\n params: AgnosticRouteMatch[\"params\"];\n data: Data;\n handle: Handle;\n}\n\nexport function convertRouteMatchToUiMatch(\n match: AgnosticDataRouteMatch,\n loaderData: RouteData\n): UIMatch {\n let { route, pathname, params } = match;\n return {\n id: route.id,\n pathname,\n params,\n data: loaderData[route.id],\n handle: route.handle,\n };\n}\n\ninterface RouteMeta<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n relativePath: string;\n caseSensitive: boolean;\n childrenIndex: number;\n route: RouteObjectType;\n}\n\ninterface RouteBranch<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n path: string;\n score: number;\n routesMeta: RouteMeta[];\n}\n\nfunction flattenRoutes<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n routes: RouteObjectType[],\n branches: RouteBranch[] = [],\n parentsMeta: RouteMeta[] = [],\n parentPath = \"\"\n): RouteBranch[] {\n let flattenRoute = (\n route: RouteObjectType,\n index: number,\n relativePath?: string\n ) => {\n let meta: RouteMeta = {\n relativePath:\n relativePath === undefined ? route.path || \"\" : relativePath,\n caseSensitive: route.caseSensitive === true,\n childrenIndex: index,\n route,\n };\n\n if (meta.relativePath.startsWith(\"/\")) {\n invariant(\n meta.relativePath.startsWith(parentPath),\n `Absolute route path \"${meta.relativePath}\" nested under path ` +\n `\"${parentPath}\" is not valid. An absolute child route path ` +\n `must start with the combined path of all its parent routes.`\n );\n\n meta.relativePath = meta.relativePath.slice(parentPath.length);\n }\n\n let path = joinPaths([parentPath, meta.relativePath]);\n let routesMeta = parentsMeta.concat(meta);\n\n // Add the children before adding this route to the array, so we traverse the\n // route tree depth-first and child routes appear before their parents in\n // the \"flattened\" version.\n if (route.children && route.children.length > 0) {\n invariant(\n // Our types know better, but runtime JS may not!\n // @ts-expect-error\n route.index !== true,\n `Index routes must not have child routes. Please remove ` +\n `all child routes from route path \"${path}\".`\n );\n flattenRoutes(route.children, branches, routesMeta, path);\n }\n\n // Routes without a path shouldn't ever match by themselves unless they are\n // index routes, so don't add them to the list of possible branches.\n if (route.path == null && !route.index) {\n return;\n }\n\n branches.push({\n path,\n score: computeScore(path, route.index),\n routesMeta,\n });\n };\n routes.forEach((route, index) => {\n // coarse-grain check for optional params\n if (route.path === \"\" || !route.path?.includes(\"?\")) {\n flattenRoute(route, index);\n } else {\n for (let exploded of explodeOptionalSegments(route.path)) {\n flattenRoute(route, index, exploded);\n }\n }\n });\n\n return branches;\n}\n\n/**\n * Computes all combinations of optional path segments for a given path,\n * excluding combinations that are ambiguous and of lower priority.\n *\n * For example, `/one/:two?/three/:four?/:five?` explodes to:\n * - `/one/three`\n * - `/one/:two/three`\n * - `/one/three/:four`\n * - `/one/three/:five`\n * - `/one/:two/three/:four`\n * - `/one/:two/three/:five`\n * - `/one/three/:four/:five`\n * - `/one/:two/three/:four/:five`\n */\nfunction explodeOptionalSegments(path: string): string[] {\n let segments = path.split(\"/\");\n if (segments.length === 0) return [];\n\n let [first, ...rest] = segments;\n\n // Optional path segments are denoted by a trailing `?`\n let isOptional = first.endsWith(\"?\");\n // Compute the corresponding required segment: `foo?` -> `foo`\n let required = first.replace(/\\?$/, \"\");\n\n if (rest.length === 0) {\n // Intepret empty string as omitting an optional segment\n // `[\"one\", \"\", \"three\"]` corresponds to omitting `:two` from `/one/:two?/three` -> `/one/three`\n return isOptional ? [required, \"\"] : [required];\n }\n\n let restExploded = explodeOptionalSegments(rest.join(\"/\"));\n\n let result: string[] = [];\n\n // All child paths with the prefix. Do this for all children before the\n // optional version for all children, so we get consistent ordering where the\n // parent optional aspect is preferred as required. Otherwise, we can get\n // child sections interspersed where deeper optional segments are higher than\n // parent optional segments, where for example, /:two would explode _earlier_\n // then /:one. By always including the parent as required _for all children_\n // first, we avoid this issue\n result.push(\n ...restExploded.map((subpath) =>\n subpath === \"\" ? required : [required, subpath].join(\"/\")\n )\n );\n\n // Then, if this is an optional value, add all child versions without\n if (isOptional) {\n result.push(...restExploded);\n }\n\n // for absolute paths, ensure `/` instead of empty segment\n return result.map((exploded) =>\n path.startsWith(\"/\") && exploded === \"\" ? \"/\" : exploded\n );\n}\n\nfunction rankRouteBranches(branches: RouteBranch[]): void {\n branches.sort((a, b) =>\n a.score !== b.score\n ? b.score - a.score // Higher score first\n : compareIndexes(\n a.routesMeta.map((meta) => meta.childrenIndex),\n b.routesMeta.map((meta) => meta.childrenIndex)\n )\n );\n}\n\nconst paramRe = /^:[\\w-]+$/;\nconst dynamicSegmentValue = 3;\nconst indexRouteValue = 2;\nconst emptySegmentValue = 1;\nconst staticSegmentValue = 10;\nconst splatPenalty = -2;\nconst isSplat = (s: string) => s === \"*\";\n\nfunction computeScore(path: string, index: boolean | undefined): number {\n let segments = path.split(\"/\");\n let initialScore = segments.length;\n if (segments.some(isSplat)) {\n initialScore += splatPenalty;\n }\n\n if (index) {\n initialScore += indexRouteValue;\n }\n\n return segments\n .filter((s) => !isSplat(s))\n .reduce(\n (score, segment) =>\n score +\n (paramRe.test(segment)\n ? dynamicSegmentValue\n : segment === \"\"\n ? emptySegmentValue\n : staticSegmentValue),\n initialScore\n );\n}\n\nfunction compareIndexes(a: number[], b: number[]): number {\n let siblings =\n a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]);\n\n return siblings\n ? // If two routes are siblings, we should try to match the earlier sibling\n // first. This allows people to have fine-grained control over the matching\n // behavior by simply putting routes with identical paths in the order they\n // want them tried.\n a[a.length - 1] - b[b.length - 1]\n : // Otherwise, it doesn't really make sense to rank non-siblings by index,\n // so they sort equally.\n 0;\n}\n\nfunction matchRouteBranch<\n ParamKey extends string = string,\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n branch: RouteBranch,\n pathname: string,\n allowPartial = false\n): AgnosticRouteMatch[] | null {\n let { routesMeta } = branch;\n\n let matchedParams = {};\n let matchedPathname = \"/\";\n let matches: AgnosticRouteMatch[] = [];\n for (let i = 0; i < routesMeta.length; ++i) {\n let meta = routesMeta[i];\n let end = i === routesMeta.length - 1;\n let remainingPathname =\n matchedPathname === \"/\"\n ? pathname\n : pathname.slice(matchedPathname.length) || \"/\";\n let match = matchPath(\n { path: meta.relativePath, caseSensitive: meta.caseSensitive, end },\n remainingPathname\n );\n\n let route = meta.route;\n\n if (\n !match &&\n end &&\n allowPartial &&\n !routesMeta[routesMeta.length - 1].route.index\n ) {\n match = matchPath(\n {\n path: meta.relativePath,\n caseSensitive: meta.caseSensitive,\n end: false,\n },\n remainingPathname\n );\n }\n\n if (!match) {\n return null;\n }\n\n Object.assign(matchedParams, match.params);\n\n matches.push({\n // TODO: Can this as be avoided?\n params: matchedParams as Params,\n pathname: joinPaths([matchedPathname, match.pathname]),\n pathnameBase: normalizePathname(\n joinPaths([matchedPathname, match.pathnameBase])\n ),\n route,\n });\n\n if (match.pathnameBase !== \"/\") {\n matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);\n }\n }\n\n return matches;\n}\n\n/**\n * Returns a path with params interpolated.\n *\n * @see https://reactrouter.com/v6/utils/generate-path\n */\nexport function generatePath(\n originalPath: Path,\n params: {\n [key in PathParam]: string | null;\n } = {} as any\n): string {\n let path: string = originalPath;\n if (path.endsWith(\"*\") && path !== \"*\" && !path.endsWith(\"/*\")) {\n warning(\n false,\n `Route path \"${path}\" will be treated as if it were ` +\n `\"${path.replace(/\\*$/, \"/*\")}\" because the \\`*\\` character must ` +\n `always follow a \\`/\\` in the pattern. To get rid of this warning, ` +\n `please change the route path to \"${path.replace(/\\*$/, \"/*\")}\".`\n );\n path = path.replace(/\\*$/, \"/*\") as Path;\n }\n\n // ensure `/` is added at the beginning if the path is absolute\n const prefix = path.startsWith(\"/\") ? \"/\" : \"\";\n\n const stringify = (p: any) =>\n p == null ? \"\" : typeof p === \"string\" ? p : String(p);\n\n const segments = path\n .split(/\\/+/)\n .map((segment, index, array) => {\n const isLastSegment = index === array.length - 1;\n\n // only apply the splat if it's the last segment\n if (isLastSegment && segment === \"*\") {\n const star = \"*\" as PathParam;\n // Apply the splat\n return stringify(params[star]);\n }\n\n const keyMatch = segment.match(/^:([\\w-]+)(\\??)$/);\n if (keyMatch) {\n const [, key, optional] = keyMatch;\n let param = params[key as PathParam];\n invariant(optional === \"?\" || param != null, `Missing \":${key}\" param`);\n return stringify(param);\n }\n\n // Remove any optional markers from optional static segments\n return segment.replace(/\\?$/g, \"\");\n })\n // Remove empty segments\n .filter((segment) => !!segment);\n\n return prefix + segments.join(\"/\");\n}\n\n/**\n * A PathPattern is used to match on some portion of a URL pathname.\n */\nexport interface PathPattern {\n /**\n * A string to match against a URL pathname. May contain `:id`-style segments\n * to indicate placeholders for dynamic parameters. May also end with `/*` to\n * indicate matching the rest of the URL pathname.\n */\n path: Path;\n /**\n * Should be `true` if the static portions of the `path` should be matched in\n * the same case.\n */\n caseSensitive?: boolean;\n /**\n * Should be `true` if this pattern should match the entire URL pathname.\n */\n end?: boolean;\n}\n\n/**\n * A PathMatch contains info about how a PathPattern matched on a URL pathname.\n */\nexport interface PathMatch {\n /**\n * The names and values of dynamic parameters in the URL.\n */\n params: Params;\n /**\n * The portion of the URL pathname that was matched.\n */\n pathname: string;\n /**\n * The portion of the URL pathname that was matched before child routes.\n */\n pathnameBase: string;\n /**\n * The pattern that was used to match.\n */\n pattern: PathPattern;\n}\n\ntype Mutable = {\n -readonly [P in keyof T]: T[P];\n};\n\n/**\n * Performs pattern matching on a URL pathname and returns information about\n * the match.\n *\n * @see https://reactrouter.com/v6/utils/match-path\n */\nexport function matchPath<\n ParamKey extends ParamParseKey,\n Path extends string\n>(\n pattern: PathPattern | Path,\n pathname: string\n): PathMatch | null {\n if (typeof pattern === \"string\") {\n pattern = { path: pattern, caseSensitive: false, end: true };\n }\n\n let [matcher, compiledParams] = compilePath(\n pattern.path,\n pattern.caseSensitive,\n pattern.end\n );\n\n let match = pathname.match(matcher);\n if (!match) return null;\n\n let matchedPathname = match[0];\n let pathnameBase = matchedPathname.replace(/(.)\\/+$/, \"$1\");\n let captureGroups = match.slice(1);\n let params: Params = compiledParams.reduce>(\n (memo, { paramName, isOptional }, index) => {\n // We need to compute the pathnameBase here using the raw splat value\n // instead of using params[\"*\"] later because it will be decoded then\n if (paramName === \"*\") {\n let splatValue = captureGroups[index] || \"\";\n pathnameBase = matchedPathname\n .slice(0, matchedPathname.length - splatValue.length)\n .replace(/(.)\\/+$/, \"$1\");\n }\n\n const value = captureGroups[index];\n if (isOptional && !value) {\n memo[paramName] = undefined;\n } else {\n memo[paramName] = (value || \"\").replace(/%2F/g, \"/\");\n }\n return memo;\n },\n {}\n );\n\n return {\n params,\n pathname: matchedPathname,\n pathnameBase,\n pattern,\n };\n}\n\ntype CompiledPathParam = { paramName: string; isOptional?: boolean };\n\nfunction compilePath(\n path: string,\n caseSensitive = false,\n end = true\n): [RegExp, CompiledPathParam[]] {\n warning(\n path === \"*\" || !path.endsWith(\"*\") || path.endsWith(\"/*\"),\n `Route path \"${path}\" will be treated as if it were ` +\n `\"${path.replace(/\\*$/, \"/*\")}\" because the \\`*\\` character must ` +\n `always follow a \\`/\\` in the pattern. To get rid of this warning, ` +\n `please change the route path to \"${path.replace(/\\*$/, \"/*\")}\".`\n );\n\n let params: CompiledPathParam[] = [];\n let regexpSource =\n \"^\" +\n path\n .replace(/\\/*\\*?$/, \"\") // Ignore trailing / and /*, we'll handle it below\n .replace(/^\\/*/, \"/\") // Make sure it has a leading /\n .replace(/[\\\\.*+^${}|()[\\]]/g, \"\\\\$&\") // Escape special regex chars\n .replace(\n /\\/:([\\w-]+)(\\?)?/g,\n (_: string, paramName: string, isOptional) => {\n params.push({ paramName, isOptional: isOptional != null });\n return isOptional ? \"/?([^\\\\/]+)?\" : \"/([^\\\\/]+)\";\n }\n );\n\n if (path.endsWith(\"*\")) {\n params.push({ paramName: \"*\" });\n regexpSource +=\n path === \"*\" || path === \"/*\"\n ? \"(.*)$\" // Already matched the initial /, just match the rest\n : \"(?:\\\\/(.+)|\\\\/*)$\"; // Don't include the / in params[\"*\"]\n } else if (end) {\n // When matching to the end, ignore trailing slashes\n regexpSource += \"\\\\/*$\";\n } else if (path !== \"\" && path !== \"/\") {\n // If our path is non-empty and contains anything beyond an initial slash,\n // then we have _some_ form of path in our regex, so we should expect to\n // match only if we find the end of this path segment. Look for an optional\n // non-captured trailing slash (to match a portion of the URL) or the end\n // of the path (if we've matched to the end). We used to do this with a\n // word boundary but that gives false positives on routes like\n // /user-preferences since `-` counts as a word boundary.\n regexpSource += \"(?:(?=\\\\/|$))\";\n } else {\n // Nothing to match for \"\" or \"/\"\n }\n\n let matcher = new RegExp(regexpSource, caseSensitive ? undefined : \"i\");\n\n return [matcher, params];\n}\n\nexport function decodePath(value: string) {\n try {\n return value\n .split(\"/\")\n .map((v) => decodeURIComponent(v).replace(/\\//g, \"%2F\"))\n .join(\"/\");\n } catch (error) {\n warning(\n false,\n `The URL path \"${value}\" could not be decoded because it is is a ` +\n `malformed URL segment. This is probably due to a bad percent ` +\n `encoding (${error}).`\n );\n\n return value;\n }\n}\n\n/**\n * @private\n */\nexport function stripBasename(\n pathname: string,\n basename: string\n): string | null {\n if (basename === \"/\") return pathname;\n\n if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {\n return null;\n }\n\n // We want to leave trailing slash behavior in the user's control, so if they\n // specify a basename with a trailing slash, we should support it\n let startIndex = basename.endsWith(\"/\")\n ? basename.length - 1\n : basename.length;\n let nextChar = pathname.charAt(startIndex);\n if (nextChar && nextChar !== \"/\") {\n // pathname does not start with basename/\n return null;\n }\n\n return pathname.slice(startIndex) || \"/\";\n}\n\nconst ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i;\nexport const isAbsoluteUrl = (url: string) => ABSOLUTE_URL_REGEX.test(url);\n\n/**\n * Returns a resolved path object relative to the given pathname.\n *\n * @see https://reactrouter.com/v6/utils/resolve-path\n */\nexport function resolvePath(to: To, fromPathname = \"/\"): Path {\n let {\n pathname: toPathname,\n search = \"\",\n hash = \"\",\n } = typeof to === \"string\" ? parsePath(to) : to;\n\n let pathname: string;\n if (toPathname) {\n toPathname = removeDoubleSlashes(toPathname);\n if (toPathname.startsWith(\"/\")) {\n pathname = resolvePathname(toPathname.substring(1), \"/\");\n } else {\n pathname = resolvePathname(toPathname, fromPathname);\n }\n } else {\n pathname = fromPathname;\n }\n\n return {\n pathname,\n search: normalizeSearch(search),\n hash: normalizeHash(hash),\n };\n}\n\nfunction resolvePathname(relativePath: string, fromPathname: string): string {\n let segments = fromPathname.replace(/\\/+$/, \"\").split(\"/\");\n let relativeSegments = relativePath.split(\"/\");\n\n relativeSegments.forEach((segment) => {\n if (segment === \"..\") {\n // Keep the root \"\" segment so the pathname starts at /\n if (segments.length > 1) segments.pop();\n } else if (segment !== \".\") {\n segments.push(segment);\n }\n });\n\n return segments.length > 1 ? segments.join(\"/\") : \"/\";\n}\n\nfunction getInvalidPathError(\n char: string,\n field: string,\n dest: string,\n path: Partial\n) {\n return (\n `Cannot include a '${char}' character in a manually specified ` +\n `\\`to.${field}\\` field [${JSON.stringify(\n path\n )}]. Please separate it out to the ` +\n `\\`to.${dest}\\` field. Alternatively you may provide the full path as ` +\n `a string in and the router will parse it for you.`\n );\n}\n\n/**\n * @private\n *\n * When processing relative navigation we want to ignore ancestor routes that\n * do not contribute to the path, such that index/pathless layout routes don't\n * interfere.\n *\n * For example, when moving a route element into an index route and/or a\n * pathless layout route, relative link behavior contained within should stay\n * the same. Both of the following examples should link back to the root:\n *\n * \n * \n * \n *\n * \n * \n * }> // <-- Does not contribute\n * // <-- Does not contribute\n * \n * \n */\nexport function getPathContributingMatches<\n T extends AgnosticRouteMatch = AgnosticRouteMatch\n>(matches: T[]) {\n return matches.filter(\n (match, index) =>\n index === 0 || (match.route.path && match.route.path.length > 0)\n );\n}\n\n// Return the array of pathnames for the current route matches - used to\n// generate the routePathnames input for resolveTo()\nexport function getResolveToMatches<\n T extends AgnosticRouteMatch = AgnosticRouteMatch\n>(matches: T[], v7_relativeSplatPath: boolean) {\n let pathMatches = getPathContributingMatches(matches);\n\n // When v7_relativeSplatPath is enabled, use the full pathname for the leaf\n // match so we include splat values for \".\" links. See:\n // https://github.com/remix-run/react-router/issues/11052#issuecomment-1836589329\n if (v7_relativeSplatPath) {\n return pathMatches.map((match, idx) =>\n idx === pathMatches.length - 1 ? match.pathname : match.pathnameBase\n );\n }\n\n return pathMatches.map((match) => match.pathnameBase);\n}\n\n/**\n * @private\n */\nexport function resolveTo(\n toArg: To,\n routePathnames: string[],\n locationPathname: string,\n isPathRelative = false\n): Path {\n let to: Partial;\n if (typeof toArg === \"string\") {\n to = parsePath(toArg);\n } else {\n to = { ...toArg };\n\n invariant(\n !to.pathname || !to.pathname.includes(\"?\"),\n getInvalidPathError(\"?\", \"pathname\", \"search\", to)\n );\n invariant(\n !to.pathname || !to.pathname.includes(\"#\"),\n getInvalidPathError(\"#\", \"pathname\", \"hash\", to)\n );\n invariant(\n !to.search || !to.search.includes(\"#\"),\n getInvalidPathError(\"#\", \"search\", \"hash\", to)\n );\n }\n\n let isEmptyPath = toArg === \"\" || to.pathname === \"\";\n let toPathname = isEmptyPath ? \"/\" : to.pathname;\n\n let from: string;\n\n // Routing is relative to the current pathname if explicitly requested.\n //\n // If a pathname is explicitly provided in `to`, it should be relative to the\n // route context. This is explained in `Note on `` values` in our\n // migration guide from v5 as a means of disambiguation between `to` values\n // that begin with `/` and those that do not. However, this is problematic for\n // `to` values that do not provide a pathname. `to` can simply be a search or\n // hash string, in which case we should assume that the navigation is relative\n // to the current location's pathname and *not* the route pathname.\n if (toPathname == null) {\n from = locationPathname;\n } else {\n let routePathnameIndex = routePathnames.length - 1;\n\n // With relative=\"route\" (the default), each leading .. segment means\n // \"go up one route\" instead of \"go up one URL segment\". This is a key\n // difference from how works and a major reason we call this a\n // \"to\" value instead of a \"href\".\n if (!isPathRelative && toPathname.startsWith(\"..\")) {\n let toSegments = toPathname.split(\"/\");\n\n while (toSegments[0] === \"..\") {\n toSegments.shift();\n routePathnameIndex -= 1;\n }\n\n to.pathname = toSegments.join(\"/\");\n }\n\n from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : \"/\";\n }\n\n let path = resolvePath(to, from);\n\n // Ensure the pathname has a trailing slash if the original \"to\" had one\n let hasExplicitTrailingSlash =\n toPathname && toPathname !== \"/\" && toPathname.endsWith(\"/\");\n // Or if this was a link to the current path which has a trailing slash\n let hasCurrentTrailingSlash =\n (isEmptyPath || toPathname === \".\") && locationPathname.endsWith(\"/\");\n if (\n !path.pathname.endsWith(\"/\") &&\n (hasExplicitTrailingSlash || hasCurrentTrailingSlash)\n ) {\n path.pathname += \"/\";\n }\n\n return path;\n}\n\n/**\n * @private\n */\nexport function getToPathname(to: To): string | undefined {\n // Empty strings should be treated the same as / paths\n return to === \"\" || (to as Path).pathname === \"\"\n ? \"/\"\n : typeof to === \"string\"\n ? parsePath(to).pathname\n : to.pathname;\n}\n\nexport const removeDoubleSlashes = (path: string): string =>\n path.replace(/\\/\\/+/g, \"/\");\n\n/**\n * @private\n */\nexport const joinPaths = (paths: string[]): string =>\n removeDoubleSlashes(paths.join(\"/\"));\n\n/**\n * @private\n */\nexport const normalizePathname = (pathname: string): string =>\n pathname.replace(/\\/+$/, \"\").replace(/^\\/*/, \"/\");\n\n/**\n * @private\n */\nexport const normalizeSearch = (search: string): string =>\n !search || search === \"?\"\n ? \"\"\n : search.startsWith(\"?\")\n ? search\n : \"?\" + search;\n\n/**\n * @private\n */\nexport const normalizeHash = (hash: string): string =>\n !hash || hash === \"#\" ? \"\" : hash.startsWith(\"#\") ? hash : \"#\" + hash;\n\nexport type JsonFunction = (\n data: Data,\n init?: number | ResponseInit\n) => Response;\n\n/**\n * This is a shortcut for creating `application/json` responses. Converts `data`\n * to JSON and sets the `Content-Type` header.\n *\n * @deprecated The `json` method is deprecated in favor of returning raw objects.\n * This method will be removed in v7.\n */\nexport const json: JsonFunction = (data, init = {}) => {\n let responseInit = typeof init === \"number\" ? { status: init } : init;\n\n let headers = new Headers(responseInit.headers);\n if (!headers.has(\"Content-Type\")) {\n headers.set(\"Content-Type\", \"application/json; charset=utf-8\");\n }\n\n return new Response(JSON.stringify(data), {\n ...responseInit,\n headers,\n });\n};\n\nexport class DataWithResponseInit {\n type: string = \"DataWithResponseInit\";\n data: D;\n init: ResponseInit | null;\n\n constructor(data: D, init?: ResponseInit) {\n this.data = data;\n this.init = init || null;\n }\n}\n\n/**\n * Create \"responses\" that contain `status`/`headers` without forcing\n * serialization into an actual `Response` - used by Remix single fetch\n */\nexport function data(data: D, init?: number | ResponseInit) {\n return new DataWithResponseInit(\n data,\n typeof init === \"number\" ? { status: init } : init\n );\n}\n\nexport interface TrackedPromise extends Promise {\n _tracked?: boolean;\n _data?: any;\n _error?: any;\n}\n\nexport class AbortedDeferredError extends Error {}\n\nexport class DeferredData {\n private pendingKeysSet: Set = new Set();\n private controller: AbortController;\n private abortPromise: Promise;\n private unlistenAbortSignal: () => void;\n private subscribers: Set<(aborted: boolean, settledKey?: string) => void> =\n new Set();\n data: Record;\n init?: ResponseInit;\n deferredKeys: string[] = [];\n\n constructor(data: Record, responseInit?: ResponseInit) {\n invariant(\n data && typeof data === \"object\" && !Array.isArray(data),\n \"defer() only accepts plain objects\"\n );\n\n // Set up an AbortController + Promise we can race against to exit early\n // cancellation\n let reject: (e: AbortedDeferredError) => void;\n this.abortPromise = new Promise((_, r) => (reject = r));\n this.controller = new AbortController();\n let onAbort = () =>\n reject(new AbortedDeferredError(\"Deferred data aborted\"));\n this.unlistenAbortSignal = () =>\n this.controller.signal.removeEventListener(\"abort\", onAbort);\n this.controller.signal.addEventListener(\"abort\", onAbort);\n\n this.data = Object.entries(data).reduce(\n (acc, [key, value]) =>\n Object.assign(acc, {\n [key]: this.trackPromise(key, value),\n }),\n {}\n );\n\n if (this.done) {\n // All incoming values were resolved\n this.unlistenAbortSignal();\n }\n\n this.init = responseInit;\n }\n\n private trackPromise(\n key: string,\n value: Promise | unknown\n ): TrackedPromise | unknown {\n if (!(value instanceof Promise)) {\n return value;\n }\n\n this.deferredKeys.push(key);\n this.pendingKeysSet.add(key);\n\n // We store a little wrapper promise that will be extended with\n // _data/_error props upon resolve/reject\n let promise: TrackedPromise = Promise.race([value, this.abortPromise]).then(\n (data) => this.onSettle(promise, key, undefined, data as unknown),\n (error) => this.onSettle(promise, key, error as unknown)\n );\n\n // Register rejection listeners to avoid uncaught promise rejections on\n // errors or aborted deferred values\n promise.catch(() => {});\n\n Object.defineProperty(promise, \"_tracked\", { get: () => true });\n return promise;\n }\n\n private onSettle(\n promise: TrackedPromise,\n key: string,\n error: unknown,\n data?: unknown\n ): unknown {\n if (\n this.controller.signal.aborted &&\n error instanceof AbortedDeferredError\n ) {\n this.unlistenAbortSignal();\n Object.defineProperty(promise, \"_error\", { get: () => error });\n return Promise.reject(error);\n }\n\n this.pendingKeysSet.delete(key);\n\n if (this.done) {\n // Nothing left to abort!\n this.unlistenAbortSignal();\n }\n\n // If the promise was resolved/rejected with undefined, we'll throw an error as you\n // should always resolve with a value or null\n if (error === undefined && data === undefined) {\n let undefinedError = new Error(\n `Deferred data for key \"${key}\" resolved/rejected with \\`undefined\\`, ` +\n `you must resolve/reject with a value or \\`null\\`.`\n );\n Object.defineProperty(promise, \"_error\", { get: () => undefinedError });\n this.emit(false, key);\n return Promise.reject(undefinedError);\n }\n\n if (data === undefined) {\n Object.defineProperty(promise, \"_error\", { get: () => error });\n this.emit(false, key);\n return Promise.reject(error);\n }\n\n Object.defineProperty(promise, \"_data\", { get: () => data });\n this.emit(false, key);\n return data;\n }\n\n private emit(aborted: boolean, settledKey?: string) {\n this.subscribers.forEach((subscriber) => subscriber(aborted, settledKey));\n }\n\n subscribe(fn: (aborted: boolean, settledKey?: string) => void) {\n this.subscribers.add(fn);\n return () => this.subscribers.delete(fn);\n }\n\n cancel() {\n this.controller.abort();\n this.pendingKeysSet.forEach((v, k) => this.pendingKeysSet.delete(k));\n this.emit(true);\n }\n\n async resolveData(signal: AbortSignal) {\n let aborted = false;\n if (!this.done) {\n let onAbort = () => this.cancel();\n signal.addEventListener(\"abort\", onAbort);\n aborted = await new Promise((resolve) => {\n this.subscribe((aborted) => {\n signal.removeEventListener(\"abort\", onAbort);\n if (aborted || this.done) {\n resolve(aborted);\n }\n });\n });\n }\n return aborted;\n }\n\n get done() {\n return this.pendingKeysSet.size === 0;\n }\n\n get unwrappedData() {\n invariant(\n this.data !== null && this.done,\n \"Can only unwrap data on initialized and settled deferreds\"\n );\n\n return Object.entries(this.data).reduce(\n (acc, [key, value]) =>\n Object.assign(acc, {\n [key]: unwrapTrackedPromise(value),\n }),\n {}\n );\n }\n\n get pendingKeys() {\n return Array.from(this.pendingKeysSet);\n }\n}\n\nfunction isTrackedPromise(value: any): value is TrackedPromise {\n return (\n value instanceof Promise && (value as TrackedPromise)._tracked === true\n );\n}\n\nfunction unwrapTrackedPromise(value: any) {\n if (!isTrackedPromise(value)) {\n return value;\n }\n\n if (value._error) {\n throw value._error;\n }\n return value._data;\n}\n\nexport type DeferFunction = (\n data: Record,\n init?: number | ResponseInit\n) => DeferredData;\n\n/**\n * @deprecated The `defer` method is deprecated in favor of returning raw\n * objects. This method will be removed in v7.\n */\nexport const defer: DeferFunction = (data, init = {}) => {\n let responseInit = typeof init === \"number\" ? { status: init } : init;\n\n return new DeferredData(data, responseInit);\n};\n\nexport type RedirectFunction = (\n url: string,\n init?: number | ResponseInit\n) => Response;\n\n/**\n * A redirect response. Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nexport const redirect: RedirectFunction = (url, init = 302) => {\n let responseInit = init;\n if (typeof responseInit === \"number\") {\n responseInit = { status: responseInit };\n } else if (typeof responseInit.status === \"undefined\") {\n responseInit.status = 302;\n }\n\n let headers = new Headers(responseInit.headers);\n headers.set(\"Location\", url);\n\n return new Response(null, {\n ...responseInit,\n headers,\n });\n};\n\n/**\n * A redirect response that will force a document reload to the new location.\n * Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nexport const redirectDocument: RedirectFunction = (url, init) => {\n let response = redirect(url, init);\n response.headers.set(\"X-Remix-Reload-Document\", \"true\");\n return response;\n};\n\n/**\n * A redirect response that will perform a `history.replaceState` instead of a\n * `history.pushState` for client-side navigation redirects.\n * Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nexport const replace: RedirectFunction = (url, init) => {\n let response = redirect(url, init);\n response.headers.set(\"X-Remix-Replace\", \"true\");\n return response;\n};\n\nexport type ErrorResponse = {\n status: number;\n statusText: string;\n data: any;\n};\n\n/**\n * @private\n * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies\n *\n * We don't export the class for public use since it's an implementation\n * detail, but we export the interface above so folks can build their own\n * abstractions around instances via isRouteErrorResponse()\n */\nexport class ErrorResponseImpl implements ErrorResponse {\n status: number;\n statusText: string;\n data: any;\n private error?: Error;\n private internal: boolean;\n\n constructor(\n status: number,\n statusText: string | undefined,\n data: any,\n internal = false\n ) {\n this.status = status;\n this.statusText = statusText || \"\";\n this.internal = internal;\n if (data instanceof Error) {\n this.data = data.toString();\n this.error = data;\n } else {\n this.data = data;\n }\n }\n}\n\n/**\n * Check if the given error is an ErrorResponse generated from a 4xx/5xx\n * Response thrown from an action/loader\n */\nexport function isRouteErrorResponse(error: any): error is ErrorResponse {\n return (\n error != null &&\n typeof error.status === \"number\" &&\n typeof error.statusText === \"string\" &&\n typeof error.internal === \"boolean\" &&\n \"data\" in error\n );\n}\n","import type { History, Location, Path, To } from \"./history\";\nimport {\n Action as HistoryAction,\n createLocation,\n createPath,\n invariant,\n parsePath,\n warning,\n} from \"./history\";\nimport type {\n AgnosticDataRouteMatch,\n AgnosticDataRouteObject,\n DataStrategyMatch,\n AgnosticRouteObject,\n DataResult,\n DataStrategyFunction,\n DataStrategyFunctionArgs,\n DeferredData,\n DeferredResult,\n DetectErrorBoundaryFunction,\n ErrorResult,\n FormEncType,\n FormMethod,\n HTMLFormMethod,\n DataStrategyResult,\n ImmutableRouteKey,\n MapRoutePropertiesFunction,\n MutationFormMethod,\n RedirectResult,\n RouteData,\n RouteManifest,\n ShouldRevalidateFunctionArgs,\n Submission,\n SuccessResult,\n UIMatch,\n V7_FormMethod,\n V7_MutationFormMethod,\n AgnosticPatchRoutesOnNavigationFunction,\n DataWithResponseInit,\n} from \"./utils\";\nimport {\n ErrorResponseImpl,\n ResultType,\n convertRouteMatchToUiMatch,\n convertRoutesToDataRoutes,\n getPathContributingMatches,\n getResolveToMatches,\n immutableRouteKeys,\n isRouteErrorResponse,\n joinPaths,\n matchRoutes,\n matchRoutesImpl,\n removeDoubleSlashes,\n resolveTo,\n stripBasename,\n} from \"./utils\";\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Types and Constants\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A Router instance manages all navigation and data loading/mutations\n */\nexport interface Router {\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the basename for the router\n */\n get basename(): RouterInit[\"basename\"];\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the future config for the router\n */\n get future(): FutureConfig;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the current state of the router\n */\n get state(): RouterState;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the routes for this router instance\n */\n get routes(): AgnosticDataRouteObject[];\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the window associated with the router\n */\n get window(): RouterInit[\"window\"];\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Initialize the router, including adding history listeners and kicking off\n * initial data fetches. Returns a function to cleanup listeners and abort\n * any in-progress loads\n */\n initialize(): Router;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Subscribe to router.state updates\n *\n * @param fn function to call with the new state\n */\n subscribe(fn: RouterSubscriber): () => void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Enable scroll restoration behavior in the router\n *\n * @param savedScrollPositions Object that will manage positions, in case\n * it's being restored from sessionStorage\n * @param getScrollPosition Function to get the active Y scroll position\n * @param getKey Function to get the key to use for restoration\n */\n enableScrollRestoration(\n savedScrollPositions: Record,\n getScrollPosition: GetScrollPositionFunction,\n getKey?: GetScrollRestorationKeyFunction\n ): () => void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Navigate forward/backward in the history stack\n * @param to Delta to move in the history stack\n */\n navigate(to: number): Promise;\n\n /**\n * Navigate to the given path\n * @param to Path to navigate to\n * @param opts Navigation options (method, submission, etc.)\n */\n navigate(to: To | null, opts?: RouterNavigateOptions): Promise;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Trigger a fetcher load/submission\n *\n * @param key Fetcher key\n * @param routeId Route that owns the fetcher\n * @param href href to fetch\n * @param opts Fetcher options, (method, submission, etc.)\n */\n fetch(\n key: string,\n routeId: string,\n href: string | null,\n opts?: RouterFetchOptions\n ): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Trigger a revalidation of all current route loaders and fetcher loads\n */\n revalidate(): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Utility function to create an href for the given location\n * @param location\n */\n createHref(location: Location | URL): string;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Utility function to URL encode a destination path according to the internal\n * history implementation\n * @param to\n */\n encodeLocation(to: To): Path;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Get/create a fetcher for the given key\n * @param key\n */\n getFetcher(key: string): Fetcher;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Delete the fetcher for a given key\n * @param key\n */\n deleteFetcher(key: string): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Cleanup listeners and abort any in-progress loads\n */\n dispose(): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Get a navigation blocker\n * @param key The identifier for the blocker\n * @param fn The blocker function implementation\n */\n getBlocker(key: string, fn: BlockerFunction): Blocker;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Delete a navigation blocker\n * @param key The identifier for the blocker\n */\n deleteBlocker(key: string): void;\n\n /**\n * @internal\n * PRIVATE DO NOT USE\n *\n * Patch additional children routes into an existing parent route\n * @param routeId The parent route id or a callback function accepting `patch`\n * to perform batch patching\n * @param children The additional children routes\n */\n patchRoutes(routeId: string | null, children: AgnosticRouteObject[]): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * HMR needs to pass in-flight route updates to React Router\n * TODO: Replace this with granular route update APIs (addRoute, updateRoute, deleteRoute)\n */\n _internalSetRoutes(routes: AgnosticRouteObject[]): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Internal fetch AbortControllers accessed by unit tests\n */\n _internalFetchControllers: Map;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Internal pending DeferredData instances accessed by unit tests\n */\n _internalActiveDeferreds: Map;\n}\n\n/**\n * State maintained internally by the router. During a navigation, all states\n * reflect the the \"old\" location unless otherwise noted.\n */\nexport interface RouterState {\n /**\n * The action of the most recent navigation\n */\n historyAction: HistoryAction;\n\n /**\n * The current location reflected by the router\n */\n location: Location;\n\n /**\n * The current set of route matches\n */\n matches: AgnosticDataRouteMatch[];\n\n /**\n * Tracks whether we've completed our initial data load\n */\n initialized: boolean;\n\n /**\n * Current scroll position we should start at for a new view\n * - number -> scroll position to restore to\n * - false -> do not restore scroll at all (used during submissions)\n * - null -> don't have a saved position, scroll to hash or top of page\n */\n restoreScrollPosition: number | false | null;\n\n /**\n * Indicate whether this navigation should skip resetting the scroll position\n * if we are unable to restore the scroll position\n */\n preventScrollReset: boolean;\n\n /**\n * Tracks the state of the current navigation\n */\n navigation: Navigation;\n\n /**\n * Tracks any in-progress revalidations\n */\n revalidation: RevalidationState;\n\n /**\n * Data from the loaders for the current matches\n */\n loaderData: RouteData;\n\n /**\n * Data from the action for the current matches\n */\n actionData: RouteData | null;\n\n /**\n * Errors caught from loaders for the current matches\n */\n errors: RouteData | null;\n\n /**\n * Map of current fetchers\n */\n fetchers: Map;\n\n /**\n * Map of current blockers\n */\n blockers: Map;\n}\n\n/**\n * Data that can be passed into hydrate a Router from SSR\n */\nexport type HydrationState = Partial<\n Pick\n>;\n\n/**\n * Future flags to toggle new feature behavior\n */\nexport interface FutureConfig {\n v7_fetcherPersist: boolean;\n v7_normalizeFormMethod: boolean;\n v7_partialHydration: boolean;\n v7_prependBasename: boolean;\n v7_relativeSplatPath: boolean;\n v7_skipActionErrorRevalidation: boolean;\n}\n\n/**\n * Initialization options for createRouter\n */\nexport interface RouterInit {\n routes: AgnosticRouteObject[];\n history: History;\n basename?: string;\n /**\n * @deprecated Use `mapRouteProperties` instead\n */\n detectErrorBoundary?: DetectErrorBoundaryFunction;\n mapRouteProperties?: MapRoutePropertiesFunction;\n future?: Partial;\n hydrationData?: HydrationState;\n window?: Window;\n dataStrategy?: DataStrategyFunction;\n patchRoutesOnNavigation?: AgnosticPatchRoutesOnNavigationFunction;\n}\n\n/**\n * State returned from a server-side query() call\n */\nexport interface StaticHandlerContext {\n basename: Router[\"basename\"];\n location: RouterState[\"location\"];\n matches: RouterState[\"matches\"];\n loaderData: RouterState[\"loaderData\"];\n actionData: RouterState[\"actionData\"];\n errors: RouterState[\"errors\"];\n statusCode: number;\n loaderHeaders: Record;\n actionHeaders: Record;\n activeDeferreds: Record | null;\n _deepestRenderedBoundaryId?: string | null;\n}\n\n/**\n * A StaticHandler instance manages a singular SSR navigation/fetch event\n */\nexport interface StaticHandler {\n dataRoutes: AgnosticDataRouteObject[];\n query(\n request: Request,\n opts?: {\n requestContext?: unknown;\n skipLoaderErrorBubbling?: boolean;\n dataStrategy?: DataStrategyFunction;\n }\n ): Promise;\n queryRoute(\n request: Request,\n opts?: {\n routeId?: string;\n requestContext?: unknown;\n dataStrategy?: DataStrategyFunction;\n }\n ): Promise;\n}\n\ntype ViewTransitionOpts = {\n currentLocation: Location;\n nextLocation: Location;\n};\n\n/**\n * Subscriber function signature for changes to router state\n */\nexport interface RouterSubscriber {\n (\n state: RouterState,\n opts: {\n deletedFetchers: string[];\n viewTransitionOpts?: ViewTransitionOpts;\n flushSync: boolean;\n }\n ): void;\n}\n\n/**\n * Function signature for determining the key to be used in scroll restoration\n * for a given location\n */\nexport interface GetScrollRestorationKeyFunction {\n (location: Location, matches: UIMatch[]): string | null;\n}\n\n/**\n * Function signature for determining the current scroll position\n */\nexport interface GetScrollPositionFunction {\n (): number;\n}\n\nexport type RelativeRoutingType = \"route\" | \"path\";\n\n// Allowed for any navigation or fetch\ntype BaseNavigateOrFetchOptions = {\n preventScrollReset?: boolean;\n relative?: RelativeRoutingType;\n flushSync?: boolean;\n};\n\n// Only allowed for navigations\ntype BaseNavigateOptions = BaseNavigateOrFetchOptions & {\n replace?: boolean;\n state?: any;\n fromRouteId?: string;\n viewTransition?: boolean;\n};\n\n// Only allowed for submission navigations\ntype BaseSubmissionOptions = {\n formMethod?: HTMLFormMethod;\n formEncType?: FormEncType;\n} & (\n | { formData: FormData; body?: undefined }\n | { formData?: undefined; body: any }\n);\n\n/**\n * Options for a navigate() call for a normal (non-submission) navigation\n */\ntype LinkNavigateOptions = BaseNavigateOptions;\n\n/**\n * Options for a navigate() call for a submission navigation\n */\ntype SubmissionNavigateOptions = BaseNavigateOptions & BaseSubmissionOptions;\n\n/**\n * Options to pass to navigate() for a navigation\n */\nexport type RouterNavigateOptions =\n | LinkNavigateOptions\n | SubmissionNavigateOptions;\n\n/**\n * Options for a fetch() load\n */\ntype LoadFetchOptions = BaseNavigateOrFetchOptions;\n\n/**\n * Options for a fetch() submission\n */\ntype SubmitFetchOptions = BaseNavigateOrFetchOptions & BaseSubmissionOptions;\n\n/**\n * Options to pass to fetch()\n */\nexport type RouterFetchOptions = LoadFetchOptions | SubmitFetchOptions;\n\n/**\n * Potential states for state.navigation\n */\nexport type NavigationStates = {\n Idle: {\n state: \"idle\";\n location: undefined;\n formMethod: undefined;\n formAction: undefined;\n formEncType: undefined;\n formData: undefined;\n json: undefined;\n text: undefined;\n };\n Loading: {\n state: \"loading\";\n location: Location;\n formMethod: Submission[\"formMethod\"] | undefined;\n formAction: Submission[\"formAction\"] | undefined;\n formEncType: Submission[\"formEncType\"] | undefined;\n formData: Submission[\"formData\"] | undefined;\n json: Submission[\"json\"] | undefined;\n text: Submission[\"text\"] | undefined;\n };\n Submitting: {\n state: \"submitting\";\n location: Location;\n formMethod: Submission[\"formMethod\"];\n formAction: Submission[\"formAction\"];\n formEncType: Submission[\"formEncType\"];\n formData: Submission[\"formData\"];\n json: Submission[\"json\"];\n text: Submission[\"text\"];\n };\n};\n\nexport type Navigation = NavigationStates[keyof NavigationStates];\n\nexport type RevalidationState = \"idle\" | \"loading\";\n\n/**\n * Potential states for fetchers\n */\ntype FetcherStates = {\n Idle: {\n state: \"idle\";\n formMethod: undefined;\n formAction: undefined;\n formEncType: undefined;\n text: undefined;\n formData: undefined;\n json: undefined;\n data: TData | undefined;\n };\n Loading: {\n state: \"loading\";\n formMethod: Submission[\"formMethod\"] | undefined;\n formAction: Submission[\"formAction\"] | undefined;\n formEncType: Submission[\"formEncType\"] | undefined;\n text: Submission[\"text\"] | undefined;\n formData: Submission[\"formData\"] | undefined;\n json: Submission[\"json\"] | undefined;\n data: TData | undefined;\n };\n Submitting: {\n state: \"submitting\";\n formMethod: Submission[\"formMethod\"];\n formAction: Submission[\"formAction\"];\n formEncType: Submission[\"formEncType\"];\n text: Submission[\"text\"];\n formData: Submission[\"formData\"];\n json: Submission[\"json\"];\n data: TData | undefined;\n };\n};\n\nexport type Fetcher =\n FetcherStates[keyof FetcherStates];\n\ninterface BlockerBlocked {\n state: \"blocked\";\n reset(): void;\n proceed(): void;\n location: Location;\n}\n\ninterface BlockerUnblocked {\n state: \"unblocked\";\n reset: undefined;\n proceed: undefined;\n location: undefined;\n}\n\ninterface BlockerProceeding {\n state: \"proceeding\";\n reset: undefined;\n proceed: undefined;\n location: Location;\n}\n\nexport type Blocker = BlockerUnblocked | BlockerBlocked | BlockerProceeding;\n\nexport type BlockerFunction = (args: {\n currentLocation: Location;\n nextLocation: Location;\n historyAction: HistoryAction;\n}) => boolean;\n\ninterface ShortCircuitable {\n /**\n * startNavigation does not need to complete the navigation because we\n * redirected or got interrupted\n */\n shortCircuited?: boolean;\n}\n\ntype PendingActionResult = [string, SuccessResult | ErrorResult];\n\ninterface HandleActionResult extends ShortCircuitable {\n /**\n * Route matches which may have been updated from fog of war discovery\n */\n matches?: RouterState[\"matches\"];\n /**\n * Tuple for the returned or thrown value from the current action. The routeId\n * is the action route for success and the bubbled boundary route for errors.\n */\n pendingActionResult?: PendingActionResult;\n}\n\ninterface HandleLoadersResult extends ShortCircuitable {\n /**\n * Route matches which may have been updated from fog of war discovery\n */\n matches?: RouterState[\"matches\"];\n /**\n * loaderData returned from the current set of loaders\n */\n loaderData?: RouterState[\"loaderData\"];\n /**\n * errors thrown from the current set of loaders\n */\n errors?: RouterState[\"errors\"];\n}\n\n/**\n * Cached info for active fetcher.load() instances so they can participate\n * in revalidation\n */\ninterface FetchLoadMatch {\n routeId: string;\n path: string;\n}\n\n/**\n * Identified fetcher.load() calls that need to be revalidated\n */\ninterface RevalidatingFetcher extends FetchLoadMatch {\n key: string;\n match: AgnosticDataRouteMatch | null;\n matches: AgnosticDataRouteMatch[] | null;\n controller: AbortController | null;\n}\n\nconst validMutationMethodsArr: MutationFormMethod[] = [\n \"post\",\n \"put\",\n \"patch\",\n \"delete\",\n];\nconst validMutationMethods = new Set(\n validMutationMethodsArr\n);\n\nconst validRequestMethodsArr: FormMethod[] = [\n \"get\",\n ...validMutationMethodsArr,\n];\nconst validRequestMethods = new Set(validRequestMethodsArr);\n\nconst redirectStatusCodes = new Set([301, 302, 303, 307, 308]);\nconst redirectPreserveMethodStatusCodes = new Set([307, 308]);\n\nexport const IDLE_NAVIGATION: NavigationStates[\"Idle\"] = {\n state: \"idle\",\n location: undefined,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n};\n\nexport const IDLE_FETCHER: FetcherStates[\"Idle\"] = {\n state: \"idle\",\n data: undefined,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n};\n\nexport const IDLE_BLOCKER: BlockerUnblocked = {\n state: \"unblocked\",\n proceed: undefined,\n reset: undefined,\n location: undefined,\n};\n\nconst ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i;\n\nconst defaultMapRouteProperties: MapRoutePropertiesFunction = (route) => ({\n hasErrorBoundary: Boolean(route.hasErrorBoundary),\n});\n\nconst TRANSITIONS_STORAGE_KEY = \"remix-router-transitions\";\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region createRouter\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Create a router and listen to history POP navigations\n */\nexport function createRouter(init: RouterInit): Router {\n const routerWindow = init.window\n ? init.window\n : typeof window !== \"undefined\"\n ? window\n : undefined;\n const isBrowser =\n typeof routerWindow !== \"undefined\" &&\n typeof routerWindow.document !== \"undefined\" &&\n typeof routerWindow.document.createElement !== \"undefined\";\n const isServer = !isBrowser;\n\n invariant(\n init.routes.length > 0,\n \"You must provide a non-empty routes array to createRouter\"\n );\n\n let mapRouteProperties: MapRoutePropertiesFunction;\n if (init.mapRouteProperties) {\n mapRouteProperties = init.mapRouteProperties;\n } else if (init.detectErrorBoundary) {\n // If they are still using the deprecated version, wrap it with the new API\n let detectErrorBoundary = init.detectErrorBoundary;\n mapRouteProperties = (route) => ({\n hasErrorBoundary: detectErrorBoundary(route),\n });\n } else {\n mapRouteProperties = defaultMapRouteProperties;\n }\n\n // Routes keyed by ID\n let manifest: RouteManifest = {};\n // Routes in tree format for matching\n let dataRoutes = convertRoutesToDataRoutes(\n init.routes,\n mapRouteProperties,\n undefined,\n manifest\n );\n let inFlightDataRoutes: AgnosticDataRouteObject[] | undefined;\n let basename = init.basename || \"/\";\n let dataStrategyImpl = init.dataStrategy || defaultDataStrategy;\n let patchRoutesOnNavigationImpl = init.patchRoutesOnNavigation;\n\n // Config driven behavior flags\n let future: FutureConfig = {\n v7_fetcherPersist: false,\n v7_normalizeFormMethod: false,\n v7_partialHydration: false,\n v7_prependBasename: false,\n v7_relativeSplatPath: false,\n v7_skipActionErrorRevalidation: false,\n ...init.future,\n };\n // Cleanup function for history\n let unlistenHistory: (() => void) | null = null;\n // Externally-provided functions to call on all state changes\n let subscribers = new Set();\n // Externally-provided object to hold scroll restoration locations during routing\n let savedScrollPositions: Record | null = null;\n // Externally-provided function to get scroll restoration keys\n let getScrollRestorationKey: GetScrollRestorationKeyFunction | null = null;\n // Externally-provided function to get current scroll position\n let getScrollPosition: GetScrollPositionFunction | null = null;\n // One-time flag to control the initial hydration scroll restoration. Because\n // we don't get the saved positions from until _after_\n // the initial render, we need to manually trigger a separate updateState to\n // send along the restoreScrollPosition\n // Set to true if we have `hydrationData` since we assume we were SSR'd and that\n // SSR did the initial scroll restoration.\n let initialScrollRestored = init.hydrationData != null;\n\n let initialMatches = matchRoutes(dataRoutes, init.history.location, basename);\n let initialMatchesIsFOW = false;\n let initialErrors: RouteData | null = null;\n\n if (initialMatches == null && !patchRoutesOnNavigationImpl) {\n // If we do not match a user-provided-route, fall back to the root\n // to allow the error boundary to take over\n let error = getInternalRouterError(404, {\n pathname: init.history.location.pathname,\n });\n let { matches, route } = getShortCircuitMatches(dataRoutes);\n initialMatches = matches;\n initialErrors = { [route.id]: error };\n }\n\n // In SPA apps, if the user provided a patchRoutesOnNavigation implementation and\n // our initial match is a splat route, clear them out so we run through lazy\n // discovery on hydration in case there's a more accurate lazy route match.\n // In SSR apps (with `hydrationData`), we expect that the server will send\n // up the proper matched routes so we don't want to run lazy discovery on\n // initial hydration and want to hydrate into the splat route.\n if (initialMatches && !init.hydrationData) {\n let fogOfWar = checkFogOfWar(\n initialMatches,\n dataRoutes,\n init.history.location.pathname\n );\n if (fogOfWar.active) {\n initialMatches = null;\n }\n }\n\n let initialized: boolean;\n if (!initialMatches) {\n initialized = false;\n initialMatches = [];\n\n // If partial hydration and fog of war is enabled, we will be running\n // `patchRoutesOnNavigation` during hydration so include any partial matches as\n // the initial matches so we can properly render `HydrateFallback`'s\n if (future.v7_partialHydration) {\n let fogOfWar = checkFogOfWar(\n null,\n dataRoutes,\n init.history.location.pathname\n );\n if (fogOfWar.active && fogOfWar.matches) {\n initialMatchesIsFOW = true;\n initialMatches = fogOfWar.matches;\n }\n }\n } else if (initialMatches.some((m) => m.route.lazy)) {\n // All initialMatches need to be loaded before we're ready. If we have lazy\n // functions around still then we'll need to run them in initialize()\n initialized = false;\n } else if (!initialMatches.some((m) => m.route.loader)) {\n // If we've got no loaders to run, then we're good to go\n initialized = true;\n } else if (future.v7_partialHydration) {\n // If partial hydration is enabled, we're initialized so long as we were\n // provided with hydrationData for every route with a loader, and no loaders\n // were marked for explicit hydration\n let loaderData = init.hydrationData ? init.hydrationData.loaderData : null;\n let errors = init.hydrationData ? init.hydrationData.errors : null;\n // If errors exist, don't consider routes below the boundary\n if (errors) {\n let idx = initialMatches.findIndex(\n (m) => errors![m.route.id] !== undefined\n );\n initialized = initialMatches\n .slice(0, idx + 1)\n .every((m) => !shouldLoadRouteOnHydration(m.route, loaderData, errors));\n } else {\n initialized = initialMatches.every(\n (m) => !shouldLoadRouteOnHydration(m.route, loaderData, errors)\n );\n }\n } else {\n // Without partial hydration - we're initialized if we were provided any\n // hydrationData - which is expected to be complete\n initialized = init.hydrationData != null;\n }\n\n let router: Router;\n let state: RouterState = {\n historyAction: init.history.action,\n location: init.history.location,\n matches: initialMatches,\n initialized,\n navigation: IDLE_NAVIGATION,\n // Don't restore on initial updateState() if we were SSR'd\n restoreScrollPosition: init.hydrationData != null ? false : null,\n preventScrollReset: false,\n revalidation: \"idle\",\n loaderData: (init.hydrationData && init.hydrationData.loaderData) || {},\n actionData: (init.hydrationData && init.hydrationData.actionData) || null,\n errors: (init.hydrationData && init.hydrationData.errors) || initialErrors,\n fetchers: new Map(),\n blockers: new Map(),\n };\n\n // -- Stateful internal variables to manage navigations --\n // Current navigation in progress (to be committed in completeNavigation)\n let pendingAction: HistoryAction = HistoryAction.Pop;\n\n // Should the current navigation prevent the scroll reset if scroll cannot\n // be restored?\n let pendingPreventScrollReset = false;\n\n // AbortController for the active navigation\n let pendingNavigationController: AbortController | null;\n\n // Should the current navigation enable document.startViewTransition?\n let pendingViewTransitionEnabled = false;\n\n // Store applied view transitions so we can apply them on POP\n let appliedViewTransitions: Map> = new Map<\n string,\n Set\n >();\n\n // Cleanup function for persisting applied transitions to sessionStorage\n let removePageHideEventListener: (() => void) | null = null;\n\n // We use this to avoid touching history in completeNavigation if a\n // revalidation is entirely uninterrupted\n let isUninterruptedRevalidation = false;\n\n // Use this internal flag to force revalidation of all loaders:\n // - submissions (completed or interrupted)\n // - useRevalidator()\n // - X-Remix-Revalidate (from redirect)\n let isRevalidationRequired = false;\n\n // Use this internal array to capture routes that require revalidation due\n // to a cancelled deferred on action submission\n let cancelledDeferredRoutes: string[] = [];\n\n // Use this internal array to capture fetcher loads that were cancelled by an\n // action navigation and require revalidation\n let cancelledFetcherLoads: Set = new Set();\n\n // AbortControllers for any in-flight fetchers\n let fetchControllers = new Map();\n\n // Track loads based on the order in which they started\n let incrementingLoadId = 0;\n\n // Track the outstanding pending navigation data load to be compared against\n // the globally incrementing load when a fetcher load lands after a completed\n // navigation\n let pendingNavigationLoadId = -1;\n\n // Fetchers that triggered data reloads as a result of their actions\n let fetchReloadIds = new Map();\n\n // Fetchers that triggered redirect navigations\n let fetchRedirectIds = new Set();\n\n // Most recent href/match for fetcher.load calls for fetchers\n let fetchLoadMatches = new Map();\n\n // Ref-count mounted fetchers so we know when it's ok to clean them up\n let activeFetchers = new Map();\n\n // Fetchers that have requested a delete when using v7_fetcherPersist,\n // they'll be officially removed after they return to idle\n let deletedFetchers = new Set();\n\n // Store DeferredData instances for active route matches. When a\n // route loader returns defer() we stick one in here. Then, when a nested\n // promise resolves we update loaderData. If a new navigation starts we\n // cancel active deferreds for eliminated routes.\n let activeDeferreds = new Map();\n\n // Store blocker functions in a separate Map outside of router state since\n // we don't need to update UI state if they change\n let blockerFunctions = new Map();\n\n // Map of pending patchRoutesOnNavigation() promises (keyed by path/matches) so\n // that we only kick them off once for a given combo\n let pendingPatchRoutes = new Map<\n string,\n ReturnType\n >();\n\n // Flag to ignore the next history update, so we can revert the URL change on\n // a POP navigation that was blocked by the user without touching router state\n let unblockBlockerHistoryUpdate: (() => void) | undefined = undefined;\n\n // Initialize the router, all side effects should be kicked off from here.\n // Implemented as a Fluent API for ease of:\n // let router = createRouter(init).initialize();\n function initialize() {\n // If history informs us of a POP navigation, start the navigation but do not update\n // state. We'll update our own state once the navigation completes\n unlistenHistory = init.history.listen(\n ({ action: historyAction, location, delta }) => {\n // Ignore this event if it was just us resetting the URL from a\n // blocked POP navigation\n if (unblockBlockerHistoryUpdate) {\n unblockBlockerHistoryUpdate();\n unblockBlockerHistoryUpdate = undefined;\n return;\n }\n\n warning(\n blockerFunctions.size === 0 || delta != null,\n \"You are trying to use a blocker on a POP navigation to a location \" +\n \"that was not created by @remix-run/router. This will fail silently in \" +\n \"production. This can happen if you are navigating outside the router \" +\n \"via `window.history.pushState`/`window.location.hash` instead of using \" +\n \"router navigation APIs. This can also happen if you are using \" +\n \"createHashRouter and the user manually changes the URL.\"\n );\n\n let blockerKey = shouldBlockNavigation({\n currentLocation: state.location,\n nextLocation: location,\n historyAction,\n });\n\n if (blockerKey && delta != null) {\n // Restore the URL to match the current UI, but don't update router state\n let nextHistoryUpdatePromise = new Promise((resolve) => {\n unblockBlockerHistoryUpdate = resolve;\n });\n init.history.go(delta * -1);\n\n // Put the blocker into a blocked state\n updateBlocker(blockerKey, {\n state: \"blocked\",\n location,\n proceed() {\n updateBlocker(blockerKey!, {\n state: \"proceeding\",\n proceed: undefined,\n reset: undefined,\n location,\n });\n // Re-do the same POP navigation we just blocked, after the url\n // restoration is also complete. See:\n // https://github.com/remix-run/react-router/issues/11613\n nextHistoryUpdatePromise.then(() => init.history.go(delta));\n },\n reset() {\n let blockers = new Map(state.blockers);\n blockers.set(blockerKey!, IDLE_BLOCKER);\n updateState({ blockers });\n },\n });\n return;\n }\n\n return startNavigation(historyAction, location);\n }\n );\n\n if (isBrowser) {\n // FIXME: This feels gross. How can we cleanup the lines between\n // scrollRestoration/appliedTransitions persistance?\n restoreAppliedTransitions(routerWindow, appliedViewTransitions);\n let _saveAppliedTransitions = () =>\n persistAppliedTransitions(routerWindow, appliedViewTransitions);\n routerWindow.addEventListener(\"pagehide\", _saveAppliedTransitions);\n removePageHideEventListener = () =>\n routerWindow.removeEventListener(\"pagehide\", _saveAppliedTransitions);\n }\n\n // Kick off initial data load if needed. Use Pop to avoid modifying history\n // Note we don't do any handling of lazy here. For SPA's it'll get handled\n // in the normal navigation flow. For SSR it's expected that lazy modules are\n // resolved prior to router creation since we can't go into a fallbackElement\n // UI for SSR'd apps\n if (!state.initialized) {\n startNavigation(HistoryAction.Pop, state.location, {\n initialHydration: true,\n });\n }\n\n return router;\n }\n\n // Clean up a router and it's side effects\n function dispose() {\n if (unlistenHistory) {\n unlistenHistory();\n }\n if (removePageHideEventListener) {\n removePageHideEventListener();\n }\n subscribers.clear();\n pendingNavigationController && pendingNavigationController.abort();\n state.fetchers.forEach((_, key) => deleteFetcher(key));\n state.blockers.forEach((_, key) => deleteBlocker(key));\n }\n\n // Subscribe to state updates for the router\n function subscribe(fn: RouterSubscriber) {\n subscribers.add(fn);\n return () => subscribers.delete(fn);\n }\n\n // Update our state and notify the calling context of the change\n function updateState(\n newState: Partial,\n opts: {\n flushSync?: boolean;\n viewTransitionOpts?: ViewTransitionOpts;\n } = {}\n ): void {\n state = {\n ...state,\n ...newState,\n };\n\n // Prep fetcher cleanup so we can tell the UI which fetcher data entries\n // can be removed\n let completedFetchers: string[] = [];\n let deletedFetchersKeys: string[] = [];\n\n if (future.v7_fetcherPersist) {\n state.fetchers.forEach((fetcher, key) => {\n if (fetcher.state === \"idle\") {\n if (deletedFetchers.has(key)) {\n // Unmounted from the UI and can be totally removed\n deletedFetchersKeys.push(key);\n } else {\n // Returned to idle but still mounted in the UI, so semi-remains for\n // revalidations and such\n completedFetchers.push(key);\n }\n }\n });\n }\n\n // Remove any lingering deleted fetchers that have already been removed\n // from state.fetchers\n deletedFetchers.forEach((key) => {\n if (!state.fetchers.has(key) && !fetchControllers.has(key)) {\n deletedFetchersKeys.push(key);\n }\n });\n\n // Iterate over a local copy so that if flushSync is used and we end up\n // removing and adding a new subscriber due to the useCallback dependencies,\n // we don't get ourselves into a loop calling the new subscriber immediately\n [...subscribers].forEach((subscriber) =>\n subscriber(state, {\n deletedFetchers: deletedFetchersKeys,\n viewTransitionOpts: opts.viewTransitionOpts,\n flushSync: opts.flushSync === true,\n })\n );\n\n // Remove idle fetchers from state since we only care about in-flight fetchers.\n if (future.v7_fetcherPersist) {\n completedFetchers.forEach((key) => state.fetchers.delete(key));\n deletedFetchersKeys.forEach((key) => deleteFetcher(key));\n } else {\n // We already called deleteFetcher() on these, can remove them from this\n // Set now that we've handed the keys off to the data layer\n deletedFetchersKeys.forEach((key) => deletedFetchers.delete(key));\n }\n }\n\n // Complete a navigation returning the state.navigation back to the IDLE_NAVIGATION\n // and setting state.[historyAction/location/matches] to the new route.\n // - Location is a required param\n // - Navigation will always be set to IDLE_NAVIGATION\n // - Can pass any other state in newState\n function completeNavigation(\n location: Location,\n newState: Partial>,\n { flushSync }: { flushSync?: boolean } = {}\n ): void {\n // Deduce if we're in a loading/actionReload state:\n // - We have committed actionData in the store\n // - The current navigation was a mutation submission\n // - We're past the submitting state and into the loading state\n // - The location being loaded is not the result of a redirect\n let isActionReload =\n state.actionData != null &&\n state.navigation.formMethod != null &&\n isMutationMethod(state.navigation.formMethod) &&\n state.navigation.state === \"loading\" &&\n location.state?._isRedirect !== true;\n\n let actionData: RouteData | null;\n if (newState.actionData) {\n if (Object.keys(newState.actionData).length > 0) {\n actionData = newState.actionData;\n } else {\n // Empty actionData -> clear prior actionData due to an action error\n actionData = null;\n }\n } else if (isActionReload) {\n // Keep the current data if we're wrapping up the action reload\n actionData = state.actionData;\n } else {\n // Clear actionData on any other completed navigations\n actionData = null;\n }\n\n // Always preserve any existing loaderData from re-used routes\n let loaderData = newState.loaderData\n ? mergeLoaderData(\n state.loaderData,\n newState.loaderData,\n newState.matches || [],\n newState.errors\n )\n : state.loaderData;\n\n // On a successful navigation we can assume we got through all blockers\n // so we can start fresh\n let blockers = state.blockers;\n if (blockers.size > 0) {\n blockers = new Map(blockers);\n blockers.forEach((_, k) => blockers.set(k, IDLE_BLOCKER));\n }\n\n // Always respect the user flag. Otherwise don't reset on mutation\n // submission navigations unless they redirect\n let preventScrollReset =\n pendingPreventScrollReset === true ||\n (state.navigation.formMethod != null &&\n isMutationMethod(state.navigation.formMethod) &&\n location.state?._isRedirect !== true);\n\n // Commit any in-flight routes at the end of the HMR revalidation \"navigation\"\n if (inFlightDataRoutes) {\n dataRoutes = inFlightDataRoutes;\n inFlightDataRoutes = undefined;\n }\n\n if (isUninterruptedRevalidation) {\n // If this was an uninterrupted revalidation then do not touch history\n } else if (pendingAction === HistoryAction.Pop) {\n // Do nothing for POP - URL has already been updated\n } else if (pendingAction === HistoryAction.Push) {\n init.history.push(location, location.state);\n } else if (pendingAction === HistoryAction.Replace) {\n init.history.replace(location, location.state);\n }\n\n let viewTransitionOpts: ViewTransitionOpts | undefined;\n\n // On POP, enable transitions if they were enabled on the original navigation\n if (pendingAction === HistoryAction.Pop) {\n // Forward takes precedence so they behave like the original navigation\n let priorPaths = appliedViewTransitions.get(state.location.pathname);\n if (priorPaths && priorPaths.has(location.pathname)) {\n viewTransitionOpts = {\n currentLocation: state.location,\n nextLocation: location,\n };\n } else if (appliedViewTransitions.has(location.pathname)) {\n // If we don't have a previous forward nav, assume we're popping back to\n // the new location and enable if that location previously enabled\n viewTransitionOpts = {\n currentLocation: location,\n nextLocation: state.location,\n };\n }\n } else if (pendingViewTransitionEnabled) {\n // Store the applied transition on PUSH/REPLACE\n let toPaths = appliedViewTransitions.get(state.location.pathname);\n if (toPaths) {\n toPaths.add(location.pathname);\n } else {\n toPaths = new Set([location.pathname]);\n appliedViewTransitions.set(state.location.pathname, toPaths);\n }\n viewTransitionOpts = {\n currentLocation: state.location,\n nextLocation: location,\n };\n }\n\n updateState(\n {\n ...newState, // matches, errors, fetchers go through as-is\n actionData,\n loaderData,\n historyAction: pendingAction,\n location,\n initialized: true,\n navigation: IDLE_NAVIGATION,\n revalidation: \"idle\",\n restoreScrollPosition: getSavedScrollPosition(\n location,\n newState.matches || state.matches\n ),\n preventScrollReset,\n blockers,\n },\n {\n viewTransitionOpts,\n flushSync: flushSync === true,\n }\n );\n\n // Reset stateful navigation vars\n pendingAction = HistoryAction.Pop;\n pendingPreventScrollReset = false;\n pendingViewTransitionEnabled = false;\n isUninterruptedRevalidation = false;\n isRevalidationRequired = false;\n cancelledDeferredRoutes = [];\n }\n\n // Trigger a navigation event, which can either be a numerical POP or a PUSH\n // replace with an optional submission\n async function navigate(\n to: number | To | null,\n opts?: RouterNavigateOptions\n ): Promise {\n if (typeof to === \"number\") {\n init.history.go(to);\n return;\n }\n\n let normalizedPath = normalizeTo(\n state.location,\n state.matches,\n basename,\n future.v7_prependBasename,\n to,\n future.v7_relativeSplatPath,\n opts?.fromRouteId,\n opts?.relative\n );\n let { path, submission, error } = normalizeNavigateOptions(\n future.v7_normalizeFormMethod,\n false,\n normalizedPath,\n opts\n );\n\n let currentLocation = state.location;\n let nextLocation = createLocation(state.location, path, opts && opts.state);\n\n // When using navigate as a PUSH/REPLACE we aren't reading an already-encoded\n // URL from window.location, so we need to encode it here so the behavior\n // remains the same as POP and non-data-router usages. new URL() does all\n // the same encoding we'd get from a history.pushState/window.location read\n // without having to touch history\n nextLocation = {\n ...nextLocation,\n ...init.history.encodeLocation(nextLocation),\n };\n\n let userReplace = opts && opts.replace != null ? opts.replace : undefined;\n\n let historyAction = HistoryAction.Push;\n\n if (userReplace === true) {\n historyAction = HistoryAction.Replace;\n } else if (userReplace === false) {\n // no-op\n } else if (\n submission != null &&\n isMutationMethod(submission.formMethod) &&\n submission.formAction === state.location.pathname + state.location.search\n ) {\n // By default on submissions to the current location we REPLACE so that\n // users don't have to double-click the back button to get to the prior\n // location. If the user redirects to a different location from the\n // action/loader this will be ignored and the redirect will be a PUSH\n historyAction = HistoryAction.Replace;\n }\n\n let preventScrollReset =\n opts && \"preventScrollReset\" in opts\n ? opts.preventScrollReset === true\n : undefined;\n\n let flushSync = (opts && opts.flushSync) === true;\n\n let blockerKey = shouldBlockNavigation({\n currentLocation,\n nextLocation,\n historyAction,\n });\n\n if (blockerKey) {\n // Put the blocker into a blocked state\n updateBlocker(blockerKey, {\n state: \"blocked\",\n location: nextLocation,\n proceed() {\n updateBlocker(blockerKey!, {\n state: \"proceeding\",\n proceed: undefined,\n reset: undefined,\n location: nextLocation,\n });\n // Send the same navigation through\n navigate(to, opts);\n },\n reset() {\n let blockers = new Map(state.blockers);\n blockers.set(blockerKey!, IDLE_BLOCKER);\n updateState({ blockers });\n },\n });\n return;\n }\n\n return await startNavigation(historyAction, nextLocation, {\n submission,\n // Send through the formData serialization error if we have one so we can\n // render at the right error boundary after we match routes\n pendingError: error,\n preventScrollReset,\n replace: opts && opts.replace,\n enableViewTransition: opts && opts.viewTransition,\n flushSync,\n });\n }\n\n // Revalidate all current loaders. If a navigation is in progress or if this\n // is interrupted by a navigation, allow this to \"succeed\" by calling all\n // loaders during the next loader round\n function revalidate() {\n interruptActiveLoads();\n updateState({ revalidation: \"loading\" });\n\n // If we're currently submitting an action, we don't need to start a new\n // navigation, we'll just let the follow up loader execution call all loaders\n if (state.navigation.state === \"submitting\") {\n return;\n }\n\n // If we're currently in an idle state, start a new navigation for the current\n // action/location and mark it as uninterrupted, which will skip the history\n // update in completeNavigation\n if (state.navigation.state === \"idle\") {\n startNavigation(state.historyAction, state.location, {\n startUninterruptedRevalidation: true,\n });\n return;\n }\n\n // Otherwise, if we're currently in a loading state, just start a new\n // navigation to the navigation.location but do not trigger an uninterrupted\n // revalidation so that history correctly updates once the navigation completes\n startNavigation(\n pendingAction || state.historyAction,\n state.navigation.location,\n {\n overrideNavigation: state.navigation,\n // Proxy through any rending view transition\n enableViewTransition: pendingViewTransitionEnabled === true,\n }\n );\n }\n\n // Start a navigation to the given action/location. Can optionally provide a\n // overrideNavigation which will override the normalLoad in the case of a redirect\n // navigation\n async function startNavigation(\n historyAction: HistoryAction,\n location: Location,\n opts?: {\n initialHydration?: boolean;\n submission?: Submission;\n fetcherSubmission?: Submission;\n overrideNavigation?: Navigation;\n pendingError?: ErrorResponseImpl;\n startUninterruptedRevalidation?: boolean;\n preventScrollReset?: boolean;\n replace?: boolean;\n enableViewTransition?: boolean;\n flushSync?: boolean;\n }\n ): Promise {\n // Abort any in-progress navigations and start a new one. Unset any ongoing\n // uninterrupted revalidations unless told otherwise, since we want this\n // new navigation to update history normally\n pendingNavigationController && pendingNavigationController.abort();\n pendingNavigationController = null;\n pendingAction = historyAction;\n isUninterruptedRevalidation =\n (opts && opts.startUninterruptedRevalidation) === true;\n\n // Save the current scroll position every time we start a new navigation,\n // and track whether we should reset scroll on completion\n saveScrollPosition(state.location, state.matches);\n pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;\n\n pendingViewTransitionEnabled = (opts && opts.enableViewTransition) === true;\n\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let loadingNavigation = opts && opts.overrideNavigation;\n let matches =\n opts?.initialHydration &&\n state.matches &&\n state.matches.length > 0 &&\n !initialMatchesIsFOW\n ? // `matchRoutes()` has already been called if we're in here via `router.initialize()`\n state.matches\n : matchRoutes(routesToUse, location, basename);\n let flushSync = (opts && opts.flushSync) === true;\n\n // Short circuit if it's only a hash change and not a revalidation or\n // mutation submission.\n //\n // Ignore on initial page loads because since the initial hydration will always\n // be \"same hash\". For example, on /page#hash and submit a \n // which will default to a navigation to /page\n if (\n matches &&\n state.initialized &&\n !isRevalidationRequired &&\n isHashChangeOnly(state.location, location) &&\n !(opts && opts.submission && isMutationMethod(opts.submission.formMethod))\n ) {\n completeNavigation(location, { matches }, { flushSync });\n return;\n }\n\n let fogOfWar = checkFogOfWar(matches, routesToUse, location.pathname);\n if (fogOfWar.active && fogOfWar.matches) {\n matches = fogOfWar.matches;\n }\n\n // Short circuit with a 404 on the root error boundary if we match nothing\n if (!matches) {\n let { error, notFoundMatches, route } = handleNavigational404(\n location.pathname\n );\n completeNavigation(\n location,\n {\n matches: notFoundMatches,\n loaderData: {},\n errors: {\n [route.id]: error,\n },\n },\n { flushSync }\n );\n return;\n }\n\n // Create a controller/Request for this navigation\n pendingNavigationController = new AbortController();\n let request = createClientSideRequest(\n init.history,\n location,\n pendingNavigationController.signal,\n opts && opts.submission\n );\n let pendingActionResult: PendingActionResult | undefined;\n\n if (opts && opts.pendingError) {\n // If we have a pendingError, it means the user attempted a GET submission\n // with binary FormData so assign here and skip to handleLoaders. That\n // way we handle calling loaders above the boundary etc. It's not really\n // different from an actionError in that sense.\n pendingActionResult = [\n findNearestBoundary(matches).route.id,\n { type: ResultType.error, error: opts.pendingError },\n ];\n } else if (\n opts &&\n opts.submission &&\n isMutationMethod(opts.submission.formMethod)\n ) {\n // Call action if we received an action submission\n let actionResult = await handleAction(\n request,\n location,\n opts.submission,\n matches,\n fogOfWar.active,\n { replace: opts.replace, flushSync }\n );\n\n if (actionResult.shortCircuited) {\n return;\n }\n\n // If we received a 404 from handleAction, it's because we couldn't lazily\n // discover the destination route so we don't want to call loaders\n if (actionResult.pendingActionResult) {\n let [routeId, result] = actionResult.pendingActionResult;\n if (\n isErrorResult(result) &&\n isRouteErrorResponse(result.error) &&\n result.error.status === 404\n ) {\n pendingNavigationController = null;\n\n completeNavigation(location, {\n matches: actionResult.matches,\n loaderData: {},\n errors: {\n [routeId]: result.error,\n },\n });\n return;\n }\n }\n\n matches = actionResult.matches || matches;\n pendingActionResult = actionResult.pendingActionResult;\n loadingNavigation = getLoadingNavigation(location, opts.submission);\n flushSync = false;\n // No need to do fog of war matching again on loader execution\n fogOfWar.active = false;\n\n // Create a GET request for the loaders\n request = createClientSideRequest(\n init.history,\n request.url,\n request.signal\n );\n }\n\n // Call loaders\n let {\n shortCircuited,\n matches: updatedMatches,\n loaderData,\n errors,\n } = await handleLoaders(\n request,\n location,\n matches,\n fogOfWar.active,\n loadingNavigation,\n opts && opts.submission,\n opts && opts.fetcherSubmission,\n opts && opts.replace,\n opts && opts.initialHydration === true,\n flushSync,\n pendingActionResult\n );\n\n if (shortCircuited) {\n return;\n }\n\n // Clean up now that the action/loaders have completed. Don't clean up if\n // we short circuited because pendingNavigationController will have already\n // been assigned to a new controller for the next navigation\n pendingNavigationController = null;\n\n completeNavigation(location, {\n matches: updatedMatches || matches,\n ...getActionDataForCommit(pendingActionResult),\n loaderData,\n errors,\n });\n }\n\n // Call the action matched by the leaf route for this navigation and handle\n // redirects/errors\n async function handleAction(\n request: Request,\n location: Location,\n submission: Submission,\n matches: AgnosticDataRouteMatch[],\n isFogOfWar: boolean,\n opts: { replace?: boolean; flushSync?: boolean } = {}\n ): Promise {\n interruptActiveLoads();\n\n // Put us in a submitting state\n let navigation = getSubmittingNavigation(location, submission);\n updateState({ navigation }, { flushSync: opts.flushSync === true });\n\n if (isFogOfWar) {\n let discoverResult = await discoverRoutes(\n matches,\n location.pathname,\n request.signal\n );\n if (discoverResult.type === \"aborted\") {\n return { shortCircuited: true };\n } else if (discoverResult.type === \"error\") {\n let boundaryId = findNearestBoundary(discoverResult.partialMatches)\n .route.id;\n return {\n matches: discoverResult.partialMatches,\n pendingActionResult: [\n boundaryId,\n {\n type: ResultType.error,\n error: discoverResult.error,\n },\n ],\n };\n } else if (!discoverResult.matches) {\n let { notFoundMatches, error, route } = handleNavigational404(\n location.pathname\n );\n return {\n matches: notFoundMatches,\n pendingActionResult: [\n route.id,\n {\n type: ResultType.error,\n error,\n },\n ],\n };\n } else {\n matches = discoverResult.matches;\n }\n }\n\n // Call our action and get the result\n let result: DataResult;\n let actionMatch = getTargetMatch(matches, location);\n\n if (!actionMatch.route.action && !actionMatch.route.lazy) {\n result = {\n type: ResultType.error,\n error: getInternalRouterError(405, {\n method: request.method,\n pathname: location.pathname,\n routeId: actionMatch.route.id,\n }),\n };\n } else {\n let results = await callDataStrategy(\n \"action\",\n state,\n request,\n [actionMatch],\n matches,\n null\n );\n result = results[actionMatch.route.id];\n\n if (request.signal.aborted) {\n return { shortCircuited: true };\n }\n }\n\n if (isRedirectResult(result)) {\n let replace: boolean;\n if (opts && opts.replace != null) {\n replace = opts.replace;\n } else {\n // If the user didn't explicity indicate replace behavior, replace if\n // we redirected to the exact same location we're currently at to avoid\n // double back-buttons\n let location = normalizeRedirectLocation(\n result.response.headers.get(\"Location\")!,\n new URL(request.url),\n basename,\n init.history,\n );\n replace = location === state.location.pathname + state.location.search;\n }\n await startRedirectNavigation(request, result, true, {\n submission,\n replace,\n });\n return { shortCircuited: true };\n }\n\n if (isDeferredResult(result)) {\n throw getInternalRouterError(400, { type: \"defer-action\" });\n }\n\n if (isErrorResult(result)) {\n // Store off the pending error - we use it to determine which loaders\n // to call and will commit it when we complete the navigation\n let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);\n\n // By default, all submissions to the current location are REPLACE\n // navigations, but if the action threw an error that'll be rendered in\n // an errorElement, we fall back to PUSH so that the user can use the\n // back button to get back to the pre-submission form location to try\n // again\n if ((opts && opts.replace) !== true) {\n pendingAction = HistoryAction.Push;\n }\n\n return {\n matches,\n pendingActionResult: [boundaryMatch.route.id, result],\n };\n }\n\n return {\n matches,\n pendingActionResult: [actionMatch.route.id, result],\n };\n }\n\n // Call all applicable loaders for the given matches, handling redirects,\n // errors, etc.\n async function handleLoaders(\n request: Request,\n location: Location,\n matches: AgnosticDataRouteMatch[],\n isFogOfWar: boolean,\n overrideNavigation?: Navigation,\n submission?: Submission,\n fetcherSubmission?: Submission,\n replace?: boolean,\n initialHydration?: boolean,\n flushSync?: boolean,\n pendingActionResult?: PendingActionResult\n ): Promise {\n // Figure out the right navigation we want to use for data loading\n let loadingNavigation =\n overrideNavigation || getLoadingNavigation(location, submission);\n\n // If this was a redirect from an action we don't have a \"submission\" but\n // we have it on the loading navigation so use that if available\n let activeSubmission =\n submission ||\n fetcherSubmission ||\n getSubmissionFromNavigation(loadingNavigation);\n\n // If this is an uninterrupted revalidation, we remain in our current idle\n // state. If not, we need to switch to our loading state and load data,\n // preserving any new action data or existing action data (in the case of\n // a revalidation interrupting an actionReload)\n // If we have partialHydration enabled, then don't update the state for the\n // initial data load since it's not a \"navigation\"\n let shouldUpdateNavigationState =\n !isUninterruptedRevalidation &&\n (!future.v7_partialHydration || !initialHydration);\n\n // When fog of war is enabled, we enter our `loading` state earlier so we\n // can discover new routes during the `loading` state. We skip this if\n // we've already run actions since we would have done our matching already.\n // If the children() function threw then, we want to proceed with the\n // partial matches it discovered.\n if (isFogOfWar) {\n if (shouldUpdateNavigationState) {\n let actionData = getUpdatedActionData(pendingActionResult);\n updateState(\n {\n navigation: loadingNavigation,\n ...(actionData !== undefined ? { actionData } : {}),\n },\n {\n flushSync,\n }\n );\n }\n\n let discoverResult = await discoverRoutes(\n matches,\n location.pathname,\n request.signal\n );\n\n if (discoverResult.type === \"aborted\") {\n return { shortCircuited: true };\n } else if (discoverResult.type === \"error\") {\n let boundaryId = findNearestBoundary(discoverResult.partialMatches)\n .route.id;\n return {\n matches: discoverResult.partialMatches,\n loaderData: {},\n errors: {\n [boundaryId]: discoverResult.error,\n },\n };\n } else if (!discoverResult.matches) {\n let { error, notFoundMatches, route } = handleNavigational404(\n location.pathname\n );\n return {\n matches: notFoundMatches,\n loaderData: {},\n errors: {\n [route.id]: error,\n },\n };\n } else {\n matches = discoverResult.matches;\n }\n }\n\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n init.history,\n state,\n matches,\n activeSubmission,\n location,\n future.v7_partialHydration && initialHydration === true,\n future.v7_skipActionErrorRevalidation,\n isRevalidationRequired,\n cancelledDeferredRoutes,\n cancelledFetcherLoads,\n deletedFetchers,\n fetchLoadMatches,\n fetchRedirectIds,\n routesToUse,\n basename,\n pendingActionResult\n );\n\n // Cancel pending deferreds for no-longer-matched routes or routes we're\n // about to reload. Note that if this is an action reload we would have\n // already cancelled all pending deferreds so this would be a no-op\n cancelActiveDeferreds(\n (routeId) =>\n !(matches && matches.some((m) => m.route.id === routeId)) ||\n (matchesToLoad && matchesToLoad.some((m) => m.route.id === routeId))\n );\n\n pendingNavigationLoadId = ++incrementingLoadId;\n\n // Short circuit if we have no loaders to run\n if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) {\n let updatedFetchers = markFetchRedirectsDone();\n completeNavigation(\n location,\n {\n matches,\n loaderData: {},\n // Commit pending error if we're short circuiting\n errors:\n pendingActionResult && isErrorResult(pendingActionResult[1])\n ? { [pendingActionResult[0]]: pendingActionResult[1].error }\n : null,\n ...getActionDataForCommit(pendingActionResult),\n ...(updatedFetchers ? { fetchers: new Map(state.fetchers) } : {}),\n },\n { flushSync }\n );\n return { shortCircuited: true };\n }\n\n if (shouldUpdateNavigationState) {\n let updates: Partial = {};\n if (!isFogOfWar) {\n // Only update navigation/actionNData if we didn't already do it above\n updates.navigation = loadingNavigation;\n let actionData = getUpdatedActionData(pendingActionResult);\n if (actionData !== undefined) {\n updates.actionData = actionData;\n }\n }\n if (revalidatingFetchers.length > 0) {\n updates.fetchers = getUpdatedRevalidatingFetchers(revalidatingFetchers);\n }\n updateState(updates, { flushSync });\n }\n\n revalidatingFetchers.forEach((rf) => {\n abortFetcher(rf.key);\n if (rf.controller) {\n // Fetchers use an independent AbortController so that aborting a fetcher\n // (via deleteFetcher) does not abort the triggering navigation that\n // triggered the revalidation\n fetchControllers.set(rf.key, rf.controller);\n }\n });\n\n // Proxy navigation abort through to revalidation fetchers\n let abortPendingFetchRevalidations = () =>\n revalidatingFetchers.forEach((f) => abortFetcher(f.key));\n if (pendingNavigationController) {\n pendingNavigationController.signal.addEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n }\n\n let { loaderResults, fetcherResults } =\n await callLoadersAndMaybeResolveData(\n state,\n matches,\n matchesToLoad,\n revalidatingFetchers,\n request\n );\n\n if (request.signal.aborted) {\n return { shortCircuited: true };\n }\n\n // Clean up _after_ loaders have completed. Don't clean up if we short\n // circuited because fetchControllers would have been aborted and\n // reassigned to new controllers for the next navigation\n if (pendingNavigationController) {\n pendingNavigationController.signal.removeEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n }\n\n revalidatingFetchers.forEach((rf) => fetchControllers.delete(rf.key));\n\n // If any loaders returned a redirect Response, start a new REPLACE navigation\n let redirect = findRedirect(loaderResults);\n if (redirect) {\n await startRedirectNavigation(request, redirect.result, true, {\n replace,\n });\n return { shortCircuited: true };\n }\n\n redirect = findRedirect(fetcherResults);\n if (redirect) {\n // If this redirect came from a fetcher make sure we mark it in\n // fetchRedirectIds so it doesn't get revalidated on the next set of\n // loader executions\n fetchRedirectIds.add(redirect.key);\n await startRedirectNavigation(request, redirect.result, true, {\n replace,\n });\n return { shortCircuited: true };\n }\n\n // Process and commit output from loaders\n let { loaderData, errors } = processLoaderData(\n state,\n matches,\n loaderResults,\n pendingActionResult,\n revalidatingFetchers,\n fetcherResults,\n activeDeferreds\n );\n\n // Wire up subscribers to update loaderData as promises settle\n activeDeferreds.forEach((deferredData, routeId) => {\n deferredData.subscribe((aborted) => {\n // Note: No need to updateState here since the TrackedPromise on\n // loaderData is stable across resolve/reject\n // Remove this instance if we were aborted or if promises have settled\n if (aborted || deferredData.done) {\n activeDeferreds.delete(routeId);\n }\n });\n });\n\n // Preserve SSR errors during partial hydration\n if (future.v7_partialHydration && initialHydration && state.errors) {\n errors = { ...state.errors, ...errors };\n }\n\n let updatedFetchers = markFetchRedirectsDone();\n let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId);\n let shouldUpdateFetchers =\n updatedFetchers || didAbortFetchLoads || revalidatingFetchers.length > 0;\n\n return {\n matches,\n loaderData,\n errors,\n ...(shouldUpdateFetchers ? { fetchers: new Map(state.fetchers) } : {}),\n };\n }\n\n function getUpdatedActionData(\n pendingActionResult: PendingActionResult | undefined\n ): Record | null | undefined {\n if (pendingActionResult && !isErrorResult(pendingActionResult[1])) {\n // This is cast to `any` currently because `RouteData`uses any and it\n // would be a breaking change to use any.\n // TODO: v7 - change `RouteData` to use `unknown` instead of `any`\n return {\n [pendingActionResult[0]]: pendingActionResult[1].data as any,\n };\n } else if (state.actionData) {\n if (Object.keys(state.actionData).length === 0) {\n return null;\n } else {\n return state.actionData;\n }\n }\n }\n\n function getUpdatedRevalidatingFetchers(\n revalidatingFetchers: RevalidatingFetcher[]\n ) {\n revalidatingFetchers.forEach((rf) => {\n let fetcher = state.fetchers.get(rf.key);\n let revalidatingFetcher = getLoadingFetcher(\n undefined,\n fetcher ? fetcher.data : undefined\n );\n state.fetchers.set(rf.key, revalidatingFetcher);\n });\n return new Map(state.fetchers);\n }\n\n // Trigger a fetcher load/submit for the given fetcher key\n function fetch(\n key: string,\n routeId: string,\n href: string | null,\n opts?: RouterFetchOptions\n ) {\n if (isServer) {\n throw new Error(\n \"router.fetch() was called during the server render, but it shouldn't be. \" +\n \"You are likely calling a useFetcher() method in the body of your component. \" +\n \"Try moving it to a useEffect or a callback.\"\n );\n }\n\n abortFetcher(key);\n\n let flushSync = (opts && opts.flushSync) === true;\n\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let normalizedPath = normalizeTo(\n state.location,\n state.matches,\n basename,\n future.v7_prependBasename,\n href,\n future.v7_relativeSplatPath,\n routeId,\n opts?.relative\n );\n let matches = matchRoutes(routesToUse, normalizedPath, basename);\n\n let fogOfWar = checkFogOfWar(matches, routesToUse, normalizedPath);\n if (fogOfWar.active && fogOfWar.matches) {\n matches = fogOfWar.matches;\n }\n\n if (!matches) {\n setFetcherError(\n key,\n routeId,\n getInternalRouterError(404, { pathname: normalizedPath }),\n { flushSync }\n );\n return;\n }\n\n let { path, submission, error } = normalizeNavigateOptions(\n future.v7_normalizeFormMethod,\n true,\n normalizedPath,\n opts\n );\n\n if (error) {\n setFetcherError(key, routeId, error, { flushSync });\n return;\n }\n\n let match = getTargetMatch(matches, path);\n\n let preventScrollReset = (opts && opts.preventScrollReset) === true;\n\n if (submission && isMutationMethod(submission.formMethod)) {\n handleFetcherAction(\n key,\n routeId,\n path,\n match,\n matches,\n fogOfWar.active,\n flushSync,\n preventScrollReset,\n submission\n );\n return;\n }\n\n // Store off the match so we can call it's shouldRevalidate on subsequent\n // revalidations\n fetchLoadMatches.set(key, { routeId, path });\n handleFetcherLoader(\n key,\n routeId,\n path,\n match,\n matches,\n fogOfWar.active,\n flushSync,\n preventScrollReset,\n submission\n );\n }\n\n // Call the action for the matched fetcher.submit(), and then handle redirects,\n // errors, and revalidation\n async function handleFetcherAction(\n key: string,\n routeId: string,\n path: string,\n match: AgnosticDataRouteMatch,\n requestMatches: AgnosticDataRouteMatch[],\n isFogOfWar: boolean,\n flushSync: boolean,\n preventScrollReset: boolean,\n submission: Submission\n ) {\n interruptActiveLoads();\n fetchLoadMatches.delete(key);\n\n function detectAndHandle405Error(m: AgnosticDataRouteMatch) {\n if (!m.route.action && !m.route.lazy) {\n let error = getInternalRouterError(405, {\n method: submission.formMethod,\n pathname: path,\n routeId: routeId,\n });\n setFetcherError(key, routeId, error, { flushSync });\n return true;\n }\n return false;\n }\n\n if (!isFogOfWar && detectAndHandle405Error(match)) {\n return;\n }\n\n // Put this fetcher into it's submitting state\n let existingFetcher = state.fetchers.get(key);\n updateFetcherState(key, getSubmittingFetcher(submission, existingFetcher), {\n flushSync,\n });\n\n let abortController = new AbortController();\n let fetchRequest = createClientSideRequest(\n init.history,\n path,\n abortController.signal,\n submission\n );\n\n if (isFogOfWar) {\n let discoverResult = await discoverRoutes(\n requestMatches,\n new URL(fetchRequest.url).pathname,\n fetchRequest.signal,\n key\n );\n\n if (discoverResult.type === \"aborted\") {\n return;\n } else if (discoverResult.type === \"error\") {\n setFetcherError(key, routeId, discoverResult.error, { flushSync });\n return;\n } else if (!discoverResult.matches) {\n setFetcherError(\n key,\n routeId,\n getInternalRouterError(404, { pathname: path }),\n { flushSync }\n );\n return;\n } else {\n requestMatches = discoverResult.matches;\n match = getTargetMatch(requestMatches, path);\n\n if (detectAndHandle405Error(match)) {\n return;\n }\n }\n }\n\n // Call the action for the fetcher\n fetchControllers.set(key, abortController);\n\n let originatingLoadId = incrementingLoadId;\n let actionResults = await callDataStrategy(\n \"action\",\n state,\n fetchRequest,\n [match],\n requestMatches,\n key\n );\n let actionResult = actionResults[match.route.id];\n\n if (fetchRequest.signal.aborted) {\n // We can delete this so long as we weren't aborted by our own fetcher\n // re-submit which would have put _new_ controller is in fetchControllers\n if (fetchControllers.get(key) === abortController) {\n fetchControllers.delete(key);\n }\n return;\n }\n\n // When using v7_fetcherPersist, we don't want errors bubbling up to the UI\n // or redirects processed for unmounted fetchers so we just revert them to\n // idle\n if (future.v7_fetcherPersist && deletedFetchers.has(key)) {\n if (isRedirectResult(actionResult) || isErrorResult(actionResult)) {\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n }\n // Let SuccessResult's fall through for revalidation\n } else {\n if (isRedirectResult(actionResult)) {\n fetchControllers.delete(key);\n if (pendingNavigationLoadId > originatingLoadId) {\n // A new navigation was kicked off after our action started, so that\n // should take precedence over this redirect navigation. We already\n // set isRevalidationRequired so all loaders for the new route should\n // fire unless opted out via shouldRevalidate\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n } else {\n fetchRedirectIds.add(key);\n updateFetcherState(key, getLoadingFetcher(submission));\n return startRedirectNavigation(fetchRequest, actionResult, false, {\n fetcherSubmission: submission,\n preventScrollReset,\n });\n }\n }\n\n // Process any non-redirect errors thrown\n if (isErrorResult(actionResult)) {\n setFetcherError(key, routeId, actionResult.error);\n return;\n }\n }\n\n if (isDeferredResult(actionResult)) {\n throw getInternalRouterError(400, { type: \"defer-action\" });\n }\n\n // Start the data load for current matches, or the next location if we're\n // in the middle of a navigation\n let nextLocation = state.navigation.location || state.location;\n let revalidationRequest = createClientSideRequest(\n init.history,\n nextLocation,\n abortController.signal\n );\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let matches =\n state.navigation.state !== \"idle\"\n ? matchRoutes(routesToUse, state.navigation.location, basename)\n : state.matches;\n\n invariant(matches, \"Didn't find any matches after fetcher action\");\n\n let loadId = ++incrementingLoadId;\n fetchReloadIds.set(key, loadId);\n\n let loadFetcher = getLoadingFetcher(submission, actionResult.data);\n state.fetchers.set(key, loadFetcher);\n\n let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n init.history,\n state,\n matches,\n submission,\n nextLocation,\n false,\n future.v7_skipActionErrorRevalidation,\n isRevalidationRequired,\n cancelledDeferredRoutes,\n cancelledFetcherLoads,\n deletedFetchers,\n fetchLoadMatches,\n fetchRedirectIds,\n routesToUse,\n basename,\n [match.route.id, actionResult]\n );\n\n // Put all revalidating fetchers into the loading state, except for the\n // current fetcher which we want to keep in it's current loading state which\n // contains it's action submission info + action data\n revalidatingFetchers\n .filter((rf) => rf.key !== key)\n .forEach((rf) => {\n let staleKey = rf.key;\n let existingFetcher = state.fetchers.get(staleKey);\n let revalidatingFetcher = getLoadingFetcher(\n undefined,\n existingFetcher ? existingFetcher.data : undefined\n );\n state.fetchers.set(staleKey, revalidatingFetcher);\n abortFetcher(staleKey);\n if (rf.controller) {\n fetchControllers.set(staleKey, rf.controller);\n }\n });\n\n updateState({ fetchers: new Map(state.fetchers) });\n\n let abortPendingFetchRevalidations = () =>\n revalidatingFetchers.forEach((rf) => abortFetcher(rf.key));\n\n abortController.signal.addEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n\n let { loaderResults, fetcherResults } =\n await callLoadersAndMaybeResolveData(\n state,\n matches,\n matchesToLoad,\n revalidatingFetchers,\n revalidationRequest\n );\n\n if (abortController.signal.aborted) {\n return;\n }\n\n abortController.signal.removeEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n\n fetchReloadIds.delete(key);\n fetchControllers.delete(key);\n revalidatingFetchers.forEach((r) => fetchControllers.delete(r.key));\n\n let redirect = findRedirect(loaderResults);\n if (redirect) {\n return startRedirectNavigation(\n revalidationRequest,\n redirect.result,\n false,\n { preventScrollReset }\n );\n }\n\n redirect = findRedirect(fetcherResults);\n if (redirect) {\n // If this redirect came from a fetcher make sure we mark it in\n // fetchRedirectIds so it doesn't get revalidated on the next set of\n // loader executions\n fetchRedirectIds.add(redirect.key);\n return startRedirectNavigation(\n revalidationRequest,\n redirect.result,\n false,\n { preventScrollReset }\n );\n }\n\n // Process and commit output from loaders\n let { loaderData, errors } = processLoaderData(\n state,\n matches,\n loaderResults,\n undefined,\n revalidatingFetchers,\n fetcherResults,\n activeDeferreds\n );\n\n // Since we let revalidations complete even if the submitting fetcher was\n // deleted, only put it back to idle if it hasn't been deleted\n if (state.fetchers.has(key)) {\n let doneFetcher = getDoneFetcher(actionResult.data);\n state.fetchers.set(key, doneFetcher);\n }\n\n abortStaleFetchLoads(loadId);\n\n // If we are currently in a navigation loading state and this fetcher is\n // more recent than the navigation, we want the newer data so abort the\n // navigation and complete it with the fetcher data\n if (\n state.navigation.state === \"loading\" &&\n loadId > pendingNavigationLoadId\n ) {\n invariant(pendingAction, \"Expected pending action\");\n pendingNavigationController && pendingNavigationController.abort();\n\n completeNavigation(state.navigation.location, {\n matches,\n loaderData,\n errors,\n fetchers: new Map(state.fetchers),\n });\n } else {\n // otherwise just update with the fetcher data, preserving any existing\n // loaderData for loaders that did not need to reload. We have to\n // manually merge here since we aren't going through completeNavigation\n updateState({\n errors,\n loaderData: mergeLoaderData(\n state.loaderData,\n loaderData,\n matches,\n errors\n ),\n fetchers: new Map(state.fetchers),\n });\n isRevalidationRequired = false;\n }\n }\n\n // Call the matched loader for fetcher.load(), handling redirects, errors, etc.\n async function handleFetcherLoader(\n key: string,\n routeId: string,\n path: string,\n match: AgnosticDataRouteMatch,\n matches: AgnosticDataRouteMatch[],\n isFogOfWar: boolean,\n flushSync: boolean,\n preventScrollReset: boolean,\n submission?: Submission\n ) {\n let existingFetcher = state.fetchers.get(key);\n updateFetcherState(\n key,\n getLoadingFetcher(\n submission,\n existingFetcher ? existingFetcher.data : undefined\n ),\n { flushSync }\n );\n\n let abortController = new AbortController();\n let fetchRequest = createClientSideRequest(\n init.history,\n path,\n abortController.signal\n );\n\n if (isFogOfWar) {\n let discoverResult = await discoverRoutes(\n matches,\n new URL(fetchRequest.url).pathname,\n fetchRequest.signal,\n key\n );\n\n if (discoverResult.type === \"aborted\") {\n return;\n } else if (discoverResult.type === \"error\") {\n setFetcherError(key, routeId, discoverResult.error, { flushSync });\n return;\n } else if (!discoverResult.matches) {\n setFetcherError(\n key,\n routeId,\n getInternalRouterError(404, { pathname: path }),\n { flushSync }\n );\n return;\n } else {\n matches = discoverResult.matches;\n match = getTargetMatch(matches, path);\n }\n }\n\n // Call the loader for this fetcher route match\n fetchControllers.set(key, abortController);\n\n let originatingLoadId = incrementingLoadId;\n let results = await callDataStrategy(\n \"loader\",\n state,\n fetchRequest,\n [match],\n matches,\n key\n );\n let result = results[match.route.id];\n\n // Deferred isn't supported for fetcher loads, await everything and treat it\n // as a normal load. resolveDeferredData will return undefined if this\n // fetcher gets aborted, so we just leave result untouched and short circuit\n // below if that happens\n if (isDeferredResult(result)) {\n result =\n (await resolveDeferredData(result, fetchRequest.signal, true)) ||\n result;\n }\n\n // We can delete this so long as we weren't aborted by our our own fetcher\n // re-load which would have put _new_ controller is in fetchControllers\n if (fetchControllers.get(key) === abortController) {\n fetchControllers.delete(key);\n }\n\n if (fetchRequest.signal.aborted) {\n return;\n }\n\n // We don't want errors bubbling up or redirects followed for unmounted\n // fetchers, so short circuit here if it was removed from the UI\n if (deletedFetchers.has(key)) {\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n }\n\n // If the loader threw a redirect Response, start a new REPLACE navigation\n if (isRedirectResult(result)) {\n if (pendingNavigationLoadId > originatingLoadId) {\n // A new navigation was kicked off after our loader started, so that\n // should take precedence over this redirect navigation\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n } else {\n fetchRedirectIds.add(key);\n await startRedirectNavigation(fetchRequest, result, false, {\n preventScrollReset,\n });\n return;\n }\n }\n\n // Process any non-redirect errors thrown\n if (isErrorResult(result)) {\n setFetcherError(key, routeId, result.error);\n return;\n }\n\n invariant(!isDeferredResult(result), \"Unhandled fetcher deferred data\");\n\n // Put the fetcher back into an idle state\n updateFetcherState(key, getDoneFetcher(result.data));\n }\n\n /**\n * Utility function to handle redirects returned from an action or loader.\n * Normally, a redirect \"replaces\" the navigation that triggered it. So, for\n * example:\n *\n * - user is on /a\n * - user clicks a link to /b\n * - loader for /b redirects to /c\n *\n * In a non-JS app the browser would track the in-flight navigation to /b and\n * then replace it with /c when it encountered the redirect response. In\n * the end it would only ever update the URL bar with /c.\n *\n * In client-side routing using pushState/replaceState, we aim to emulate\n * this behavior and we also do not update history until the end of the\n * navigation (including processed redirects). This means that we never\n * actually touch history until we've processed redirects, so we just use\n * the history action from the original navigation (PUSH or REPLACE).\n */\n async function startRedirectNavigation(\n request: Request,\n redirect: RedirectResult,\n isNavigation: boolean,\n {\n submission,\n fetcherSubmission,\n preventScrollReset,\n replace,\n }: {\n submission?: Submission;\n fetcherSubmission?: Submission;\n preventScrollReset?: boolean;\n replace?: boolean;\n } = {}\n ) {\n if (redirect.response.headers.has(\"X-Remix-Revalidate\")) {\n isRevalidationRequired = true;\n }\n\n let location = redirect.response.headers.get(\"Location\");\n invariant(location, \"Expected a Location header on the redirect Response\");\n location = normalizeRedirectLocation(\n location,\n new URL(request.url),\n basename,\n init.history,\n );\n let redirectLocation = createLocation(state.location, location, {\n _isRedirect: true,\n });\n\n if (isBrowser) {\n let isDocumentReload = false;\n\n if (redirect.response.headers.has(\"X-Remix-Reload-Document\")) {\n // Hard reload if the response contained X-Remix-Reload-Document\n isDocumentReload = true;\n } else if (ABSOLUTE_URL_REGEX.test(location)) {\n const url = init.history.createURL(location);\n isDocumentReload =\n // Hard reload if it's an absolute URL to a new origin\n url.origin !== routerWindow.location.origin ||\n // Hard reload if it's an absolute URL that does not match our basename\n stripBasename(url.pathname, basename) == null;\n }\n\n if (isDocumentReload) {\n if (replace) {\n routerWindow.location.replace(location);\n } else {\n routerWindow.location.assign(location);\n }\n return;\n }\n }\n\n // There's no need to abort on redirects, since we don't detect the\n // redirect until the action/loaders have settled\n pendingNavigationController = null;\n\n let redirectHistoryAction =\n replace === true || redirect.response.headers.has(\"X-Remix-Replace\")\n ? HistoryAction.Replace\n : HistoryAction.Push;\n\n // Use the incoming submission if provided, fallback on the active one in\n // state.navigation\n let { formMethod, formAction, formEncType } = state.navigation;\n if (\n !submission &&\n !fetcherSubmission &&\n formMethod &&\n formAction &&\n formEncType\n ) {\n submission = getSubmissionFromNavigation(state.navigation);\n }\n\n // If this was a 307/308 submission we want to preserve the HTTP method and\n // re-submit the GET/POST/PUT/PATCH/DELETE as a submission navigation to the\n // redirected location\n let activeSubmission = submission || fetcherSubmission;\n if (\n redirectPreserveMethodStatusCodes.has(redirect.response.status) &&\n activeSubmission &&\n isMutationMethod(activeSubmission.formMethod)\n ) {\n await startNavigation(redirectHistoryAction, redirectLocation, {\n submission: {\n ...activeSubmission,\n formAction: location,\n },\n // Preserve these flags across redirects\n preventScrollReset: preventScrollReset || pendingPreventScrollReset,\n enableViewTransition: isNavigation\n ? pendingViewTransitionEnabled\n : undefined,\n });\n } else {\n // If we have a navigation submission, we will preserve it through the\n // redirect navigation\n let overrideNavigation = getLoadingNavigation(\n redirectLocation,\n submission\n );\n await startNavigation(redirectHistoryAction, redirectLocation, {\n overrideNavigation,\n // Send fetcher submissions through for shouldRevalidate\n fetcherSubmission,\n // Preserve these flags across redirects\n preventScrollReset: preventScrollReset || pendingPreventScrollReset,\n enableViewTransition: isNavigation\n ? pendingViewTransitionEnabled\n : undefined,\n });\n }\n }\n\n // Utility wrapper for calling dataStrategy client-side without having to\n // pass around the manifest, mapRouteProperties, etc.\n async function callDataStrategy(\n type: \"loader\" | \"action\",\n state: RouterState,\n request: Request,\n matchesToLoad: AgnosticDataRouteMatch[],\n matches: AgnosticDataRouteMatch[],\n fetcherKey: string | null\n ): Promise> {\n let results: Record;\n let dataResults: Record = {};\n try {\n results = await callDataStrategyImpl(\n dataStrategyImpl,\n type,\n state,\n request,\n matchesToLoad,\n matches,\n fetcherKey,\n manifest,\n mapRouteProperties\n );\n } catch (e) {\n // If the outer dataStrategy method throws, just return the error for all\n // matches - and it'll naturally bubble to the root\n matchesToLoad.forEach((m) => {\n dataResults[m.route.id] = {\n type: ResultType.error,\n error: e,\n };\n });\n return dataResults;\n }\n\n for (let [routeId, result] of Object.entries(results)) {\n if (isRedirectDataStrategyResultResult(result)) {\n let response = result.result as Response;\n dataResults[routeId] = {\n type: ResultType.redirect,\n response: normalizeRelativeRoutingRedirectResponse(\n response,\n request,\n routeId,\n matches,\n basename,\n future.v7_relativeSplatPath\n ),\n };\n } else {\n dataResults[routeId] = await convertDataStrategyResultToDataResult(\n result\n );\n }\n }\n\n return dataResults;\n }\n\n async function callLoadersAndMaybeResolveData(\n state: RouterState,\n matches: AgnosticDataRouteMatch[],\n matchesToLoad: AgnosticDataRouteMatch[],\n fetchersToLoad: RevalidatingFetcher[],\n request: Request\n ) {\n let currentMatches = state.matches;\n\n // Kick off loaders and fetchers in parallel\n let loaderResultsPromise = callDataStrategy(\n \"loader\",\n state,\n request,\n matchesToLoad,\n matches,\n null\n );\n\n let fetcherResultsPromise = Promise.all(\n fetchersToLoad.map(async (f) => {\n if (f.matches && f.match && f.controller) {\n let results = await callDataStrategy(\n \"loader\",\n state,\n createClientSideRequest(init.history, f.path, f.controller.signal),\n [f.match],\n f.matches,\n f.key\n );\n let result = results[f.match.route.id];\n // Fetcher results are keyed by fetcher key from here on out, not routeId\n return { [f.key]: result };\n } else {\n return Promise.resolve({\n [f.key]: {\n type: ResultType.error,\n error: getInternalRouterError(404, {\n pathname: f.path,\n }),\n } as ErrorResult,\n });\n }\n })\n );\n\n let loaderResults = await loaderResultsPromise;\n let fetcherResults = (await fetcherResultsPromise).reduce(\n (acc, r) => Object.assign(acc, r),\n {}\n );\n\n await Promise.all([\n resolveNavigationDeferredResults(\n matches,\n loaderResults,\n request.signal,\n currentMatches,\n state.loaderData\n ),\n resolveFetcherDeferredResults(matches, fetcherResults, fetchersToLoad),\n ]);\n\n return {\n loaderResults,\n fetcherResults,\n };\n }\n\n function interruptActiveLoads() {\n // Every interruption triggers a revalidation\n isRevalidationRequired = true;\n\n // Cancel pending route-level deferreds and mark cancelled routes for\n // revalidation\n cancelledDeferredRoutes.push(...cancelActiveDeferreds());\n\n // Abort in-flight fetcher loads\n fetchLoadMatches.forEach((_, key) => {\n if (fetchControllers.has(key)) {\n cancelledFetcherLoads.add(key);\n }\n abortFetcher(key);\n });\n }\n\n function updateFetcherState(\n key: string,\n fetcher: Fetcher,\n opts: { flushSync?: boolean } = {}\n ) {\n state.fetchers.set(key, fetcher);\n updateState(\n { fetchers: new Map(state.fetchers) },\n { flushSync: (opts && opts.flushSync) === true }\n );\n }\n\n function setFetcherError(\n key: string,\n routeId: string,\n error: any,\n opts: { flushSync?: boolean } = {}\n ) {\n let boundaryMatch = findNearestBoundary(state.matches, routeId);\n deleteFetcher(key);\n updateState(\n {\n errors: {\n [boundaryMatch.route.id]: error,\n },\n fetchers: new Map(state.fetchers),\n },\n { flushSync: (opts && opts.flushSync) === true }\n );\n }\n\n function getFetcher(key: string): Fetcher {\n activeFetchers.set(key, (activeFetchers.get(key) || 0) + 1);\n // If this fetcher was previously marked for deletion, unmark it since we\n // have a new instance\n if (deletedFetchers.has(key)) {\n deletedFetchers.delete(key);\n }\n return state.fetchers.get(key) || IDLE_FETCHER;\n }\n\n function deleteFetcher(key: string): void {\n let fetcher = state.fetchers.get(key);\n // Don't abort the controller if this is a deletion of a fetcher.submit()\n // in it's loading phase since - we don't want to abort the corresponding\n // revalidation and want them to complete and land\n if (\n fetchControllers.has(key) &&\n !(fetcher && fetcher.state === \"loading\" && fetchReloadIds.has(key))\n ) {\n abortFetcher(key);\n }\n fetchLoadMatches.delete(key);\n fetchReloadIds.delete(key);\n fetchRedirectIds.delete(key);\n\n // If we opted into the flag we can clear this now since we're calling\n // deleteFetcher() at the end of updateState() and we've already handed the\n // deleted fetcher keys off to the data layer.\n // If not, we're eagerly calling deleteFetcher() and we need to keep this\n // Set populated until the next updateState call, and we'll clear\n // `deletedFetchers` then\n if (future.v7_fetcherPersist) {\n deletedFetchers.delete(key);\n }\n\n cancelledFetcherLoads.delete(key);\n state.fetchers.delete(key);\n }\n\n function deleteFetcherAndUpdateState(key: string): void {\n let count = (activeFetchers.get(key) || 0) - 1;\n if (count <= 0) {\n activeFetchers.delete(key);\n deletedFetchers.add(key);\n if (!future.v7_fetcherPersist) {\n deleteFetcher(key);\n }\n } else {\n activeFetchers.set(key, count);\n }\n\n updateState({ fetchers: new Map(state.fetchers) });\n }\n\n function abortFetcher(key: string) {\n let controller = fetchControllers.get(key);\n if (controller) {\n controller.abort();\n fetchControllers.delete(key);\n }\n }\n\n function markFetchersDone(keys: string[]) {\n for (let key of keys) {\n let fetcher = getFetcher(key);\n let doneFetcher = getDoneFetcher(fetcher.data);\n state.fetchers.set(key, doneFetcher);\n }\n }\n\n function markFetchRedirectsDone(): boolean {\n let doneKeys = [];\n let updatedFetchers = false;\n for (let key of fetchRedirectIds) {\n let fetcher = state.fetchers.get(key);\n invariant(fetcher, `Expected fetcher: ${key}`);\n if (fetcher.state === \"loading\") {\n fetchRedirectIds.delete(key);\n doneKeys.push(key);\n updatedFetchers = true;\n }\n }\n markFetchersDone(doneKeys);\n return updatedFetchers;\n }\n\n function abortStaleFetchLoads(landedId: number): boolean {\n let yeetedKeys = [];\n for (let [key, id] of fetchReloadIds) {\n if (id < landedId) {\n let fetcher = state.fetchers.get(key);\n invariant(fetcher, `Expected fetcher: ${key}`);\n if (fetcher.state === \"loading\") {\n abortFetcher(key);\n fetchReloadIds.delete(key);\n yeetedKeys.push(key);\n }\n }\n }\n markFetchersDone(yeetedKeys);\n return yeetedKeys.length > 0;\n }\n\n function getBlocker(key: string, fn: BlockerFunction) {\n let blocker: Blocker = state.blockers.get(key) || IDLE_BLOCKER;\n\n if (blockerFunctions.get(key) !== fn) {\n blockerFunctions.set(key, fn);\n }\n\n return blocker;\n }\n\n function deleteBlocker(key: string) {\n state.blockers.delete(key);\n blockerFunctions.delete(key);\n }\n\n // Utility function to update blockers, ensuring valid state transitions\n function updateBlocker(key: string, newBlocker: Blocker) {\n let blocker = state.blockers.get(key) || IDLE_BLOCKER;\n\n // Poor mans state machine :)\n // https://mermaid.live/edit#pako:eNqVkc9OwzAMxl8l8nnjAYrEtDIOHEBIgwvKJTReGy3_lDpIqO27k6awMG0XcrLlnz87nwdonESogKXXBuE79rq75XZO3-yHds0RJVuv70YrPlUrCEe2HfrORS3rubqZfuhtpg5C9wk5tZ4VKcRUq88q9Z8RS0-48cE1iHJkL0ugbHuFLus9L6spZy8nX9MP2CNdomVaposqu3fGayT8T8-jJQwhepo_UtpgBQaDEUom04dZhAN1aJBDlUKJBxE1ceB2Smj0Mln-IBW5AFU2dwUiktt_2Qaq2dBfaKdEup85UV7Yd-dKjlnkabl2Pvr0DTkTreM\n invariant(\n (blocker.state === \"unblocked\" && newBlocker.state === \"blocked\") ||\n (blocker.state === \"blocked\" && newBlocker.state === \"blocked\") ||\n (blocker.state === \"blocked\" && newBlocker.state === \"proceeding\") ||\n (blocker.state === \"blocked\" && newBlocker.state === \"unblocked\") ||\n (blocker.state === \"proceeding\" && newBlocker.state === \"unblocked\"),\n `Invalid blocker state transition: ${blocker.state} -> ${newBlocker.state}`\n );\n\n let blockers = new Map(state.blockers);\n blockers.set(key, newBlocker);\n updateState({ blockers });\n }\n\n function shouldBlockNavigation({\n currentLocation,\n nextLocation,\n historyAction,\n }: {\n currentLocation: Location;\n nextLocation: Location;\n historyAction: HistoryAction;\n }): string | undefined {\n if (blockerFunctions.size === 0) {\n return;\n }\n\n // We ony support a single active blocker at the moment since we don't have\n // any compelling use cases for multi-blocker yet\n if (blockerFunctions.size > 1) {\n warning(false, \"A router only supports one blocker at a time\");\n }\n\n let entries = Array.from(blockerFunctions.entries());\n let [blockerKey, blockerFunction] = entries[entries.length - 1];\n let blocker = state.blockers.get(blockerKey);\n\n if (blocker && blocker.state === \"proceeding\") {\n // If the blocker is currently proceeding, we don't need to re-check\n // it and can let this navigation continue\n return;\n }\n\n // At this point, we know we're unblocked/blocked so we need to check the\n // user-provided blocker function\n if (blockerFunction({ currentLocation, nextLocation, historyAction })) {\n return blockerKey;\n }\n }\n\n function handleNavigational404(pathname: string) {\n let error = getInternalRouterError(404, { pathname });\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let { matches, route } = getShortCircuitMatches(routesToUse);\n\n // Cancel all pending deferred on 404s since we don't keep any routes\n cancelActiveDeferreds();\n\n return { notFoundMatches: matches, route, error };\n }\n\n function cancelActiveDeferreds(\n predicate?: (routeId: string) => boolean\n ): string[] {\n let cancelledRouteIds: string[] = [];\n activeDeferreds.forEach((dfd, routeId) => {\n if (!predicate || predicate(routeId)) {\n // Cancel the deferred - but do not remove from activeDeferreds here -\n // we rely on the subscribers to do that so our tests can assert proper\n // cleanup via _internalActiveDeferreds\n dfd.cancel();\n cancelledRouteIds.push(routeId);\n activeDeferreds.delete(routeId);\n }\n });\n return cancelledRouteIds;\n }\n\n // Opt in to capturing and reporting scroll positions during navigations,\n // used by the component\n function enableScrollRestoration(\n positions: Record,\n getPosition: GetScrollPositionFunction,\n getKey?: GetScrollRestorationKeyFunction\n ) {\n savedScrollPositions = positions;\n getScrollPosition = getPosition;\n getScrollRestorationKey = getKey || null;\n\n // Perform initial hydration scroll restoration, since we miss the boat on\n // the initial updateState() because we've not yet rendered \n // and therefore have no savedScrollPositions available\n if (!initialScrollRestored && state.navigation === IDLE_NAVIGATION) {\n initialScrollRestored = true;\n let y = getSavedScrollPosition(state.location, state.matches);\n if (y != null) {\n updateState({ restoreScrollPosition: y });\n }\n }\n\n return () => {\n savedScrollPositions = null;\n getScrollPosition = null;\n getScrollRestorationKey = null;\n };\n }\n\n function getScrollKey(location: Location, matches: AgnosticDataRouteMatch[]) {\n if (getScrollRestorationKey) {\n let key = getScrollRestorationKey(\n location,\n matches.map((m) => convertRouteMatchToUiMatch(m, state.loaderData))\n );\n return key || location.key;\n }\n return location.key;\n }\n\n function saveScrollPosition(\n location: Location,\n matches: AgnosticDataRouteMatch[]\n ): void {\n if (savedScrollPositions && getScrollPosition) {\n let key = getScrollKey(location, matches);\n savedScrollPositions[key] = getScrollPosition();\n }\n }\n\n function getSavedScrollPosition(\n location: Location,\n matches: AgnosticDataRouteMatch[]\n ): number | null {\n if (savedScrollPositions) {\n let key = getScrollKey(location, matches);\n let y = savedScrollPositions[key];\n if (typeof y === \"number\") {\n return y;\n }\n }\n return null;\n }\n\n function checkFogOfWar(\n matches: AgnosticDataRouteMatch[] | null,\n routesToUse: AgnosticDataRouteObject[],\n pathname: string\n ): { active: boolean; matches: AgnosticDataRouteMatch[] | null } {\n if (patchRoutesOnNavigationImpl) {\n if (!matches) {\n let fogMatches = matchRoutesImpl(\n routesToUse,\n pathname,\n basename,\n true\n );\n\n return { active: true, matches: fogMatches || [] };\n } else {\n if (Object.keys(matches[0].params).length > 0) {\n // If we matched a dynamic param or a splat, it might only be because\n // we haven't yet discovered other routes that would match with a\n // higher score. Call patchRoutesOnNavigation just to be sure\n let partialMatches = matchRoutesImpl(\n routesToUse,\n pathname,\n basename,\n true\n );\n return { active: true, matches: partialMatches };\n }\n }\n }\n\n return { active: false, matches: null };\n }\n\n type DiscoverRoutesSuccessResult = {\n type: \"success\";\n matches: AgnosticDataRouteMatch[] | null;\n };\n type DiscoverRoutesErrorResult = {\n type: \"error\";\n error: any;\n partialMatches: AgnosticDataRouteMatch[];\n };\n type DiscoverRoutesAbortedResult = { type: \"aborted\" };\n type DiscoverRoutesResult =\n | DiscoverRoutesSuccessResult\n | DiscoverRoutesErrorResult\n | DiscoverRoutesAbortedResult;\n\n async function discoverRoutes(\n matches: AgnosticDataRouteMatch[],\n pathname: string,\n signal: AbortSignal,\n fetcherKey?: string\n ): Promise {\n if (!patchRoutesOnNavigationImpl) {\n return { type: \"success\", matches };\n }\n\n let partialMatches: AgnosticDataRouteMatch[] | null = matches;\n while (true) {\n let isNonHMR = inFlightDataRoutes == null;\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let localManifest = manifest;\n try {\n await patchRoutesOnNavigationImpl({\n signal,\n path: pathname,\n matches: partialMatches,\n fetcherKey,\n patch: (routeId, children) => {\n if (signal.aborted) return;\n patchRoutesImpl(\n routeId,\n children,\n routesToUse,\n localManifest,\n mapRouteProperties\n );\n },\n });\n } catch (e) {\n return { type: \"error\", error: e, partialMatches };\n } finally {\n // If we are not in the middle of an HMR revalidation and we changed the\n // routes, provide a new identity so when we `updateState` at the end of\n // this navigation/fetch `router.routes` will be a new identity and\n // trigger a re-run of memoized `router.routes` dependencies.\n // HMR will already update the identity and reflow when it lands\n // `inFlightDataRoutes` in `completeNavigation`\n if (isNonHMR && !signal.aborted) {\n dataRoutes = [...dataRoutes];\n }\n }\n\n if (signal.aborted) {\n return { type: \"aborted\" };\n }\n\n let newMatches = matchRoutes(routesToUse, pathname, basename);\n if (newMatches) {\n return { type: \"success\", matches: newMatches };\n }\n\n let newPartialMatches = matchRoutesImpl(\n routesToUse,\n pathname,\n basename,\n true\n );\n\n // Avoid loops if the second pass results in the same partial matches\n if (\n !newPartialMatches ||\n (partialMatches.length === newPartialMatches.length &&\n partialMatches.every(\n (m, i) => m.route.id === newPartialMatches![i].route.id\n ))\n ) {\n return { type: \"success\", matches: null };\n }\n\n partialMatches = newPartialMatches;\n }\n }\n\n function _internalSetRoutes(newRoutes: AgnosticDataRouteObject[]) {\n manifest = {};\n inFlightDataRoutes = convertRoutesToDataRoutes(\n newRoutes,\n mapRouteProperties,\n undefined,\n manifest\n );\n }\n\n function patchRoutes(\n routeId: string | null,\n children: AgnosticRouteObject[]\n ): void {\n let isNonHMR = inFlightDataRoutes == null;\n let routesToUse = inFlightDataRoutes || dataRoutes;\n patchRoutesImpl(\n routeId,\n children,\n routesToUse,\n manifest,\n mapRouteProperties\n );\n\n // If we are not in the middle of an HMR revalidation and we changed the\n // routes, provide a new identity and trigger a reflow via `updateState`\n // to re-run memoized `router.routes` dependencies.\n // HMR will already update the identity and reflow when it lands\n // `inFlightDataRoutes` in `completeNavigation`\n if (isNonHMR) {\n dataRoutes = [...dataRoutes];\n updateState({});\n }\n }\n\n router = {\n get basename() {\n return basename;\n },\n get future() {\n return future;\n },\n get state() {\n return state;\n },\n get routes() {\n return dataRoutes;\n },\n get window() {\n return routerWindow;\n },\n initialize,\n subscribe,\n enableScrollRestoration,\n navigate,\n fetch,\n revalidate,\n // Passthrough to history-aware createHref used by useHref so we get proper\n // hash-aware URLs in DOM paths\n createHref: (to: To) => init.history.createHref(to),\n encodeLocation: (to: To) => init.history.encodeLocation(to),\n getFetcher,\n deleteFetcher: deleteFetcherAndUpdateState,\n dispose,\n getBlocker,\n deleteBlocker,\n patchRoutes,\n _internalFetchControllers: fetchControllers,\n _internalActiveDeferreds: activeDeferreds,\n // TODO: Remove setRoutes, it's temporary to avoid dealing with\n // updating the tree while validating the update algorithm.\n _internalSetRoutes,\n };\n\n return router;\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region createStaticHandler\n////////////////////////////////////////////////////////////////////////////////\n\nexport const UNSAFE_DEFERRED_SYMBOL = Symbol(\"deferred\");\n\n/**\n * Future flags to toggle new feature behavior\n */\nexport interface StaticHandlerFutureConfig {\n v7_relativeSplatPath: boolean;\n v7_throwAbortReason: boolean;\n}\n\nexport interface CreateStaticHandlerOptions {\n basename?: string;\n /**\n * @deprecated Use `mapRouteProperties` instead\n */\n detectErrorBoundary?: DetectErrorBoundaryFunction;\n mapRouteProperties?: MapRoutePropertiesFunction;\n future?: Partial;\n}\n\nexport function createStaticHandler(\n routes: AgnosticRouteObject[],\n opts?: CreateStaticHandlerOptions\n): StaticHandler {\n invariant(\n routes.length > 0,\n \"You must provide a non-empty routes array to createStaticHandler\"\n );\n\n let manifest: RouteManifest = {};\n let basename = (opts ? opts.basename : null) || \"/\";\n let mapRouteProperties: MapRoutePropertiesFunction;\n if (opts?.mapRouteProperties) {\n mapRouteProperties = opts.mapRouteProperties;\n } else if (opts?.detectErrorBoundary) {\n // If they are still using the deprecated version, wrap it with the new API\n let detectErrorBoundary = opts.detectErrorBoundary;\n mapRouteProperties = (route) => ({\n hasErrorBoundary: detectErrorBoundary(route),\n });\n } else {\n mapRouteProperties = defaultMapRouteProperties;\n }\n // Config driven behavior flags\n let future: StaticHandlerFutureConfig = {\n v7_relativeSplatPath: false,\n v7_throwAbortReason: false,\n ...(opts ? opts.future : null),\n };\n\n let dataRoutes = convertRoutesToDataRoutes(\n routes,\n mapRouteProperties,\n undefined,\n manifest\n );\n\n /**\n * The query() method is intended for document requests, in which we want to\n * call an optional action and potentially multiple loaders for all nested\n * routes. It returns a StaticHandlerContext object, which is very similar\n * to the router state (location, loaderData, actionData, errors, etc.) and\n * also adds SSR-specific information such as the statusCode and headers\n * from action/loaders Responses.\n *\n * It _should_ never throw and should report all errors through the\n * returned context.errors object, properly associating errors to their error\n * boundary. Additionally, it tracks _deepestRenderedBoundaryId which can be\n * used to emulate React error boundaries during SSr by performing a second\n * pass only down to the boundaryId.\n *\n * The one exception where we do not return a StaticHandlerContext is when a\n * redirect response is returned or thrown from any action/loader. We\n * propagate that out and return the raw Response so the HTTP server can\n * return it directly.\n *\n * - `opts.requestContext` is an optional server context that will be passed\n * to actions/loaders in the `context` parameter\n * - `opts.skipLoaderErrorBubbling` is an optional parameter that will prevent\n * the bubbling of errors which allows single-fetch-type implementations\n * where the client will handle the bubbling and we may need to return data\n * for the handling route\n */\n async function query(\n request: Request,\n {\n requestContext,\n skipLoaderErrorBubbling,\n dataStrategy,\n }: {\n requestContext?: unknown;\n skipLoaderErrorBubbling?: boolean;\n dataStrategy?: DataStrategyFunction;\n } = {}\n ): Promise {\n let url = new URL(request.url);\n let method = request.method;\n let location = createLocation(\"\", createPath(url), null, \"default\");\n let matches = matchRoutes(dataRoutes, location, basename);\n\n // SSR supports HEAD requests while SPA doesn't\n if (!isValidMethod(method) && method !== \"HEAD\") {\n let error = getInternalRouterError(405, { method });\n let { matches: methodNotAllowedMatches, route } =\n getShortCircuitMatches(dataRoutes);\n return {\n basename,\n location,\n matches: methodNotAllowedMatches,\n loaderData: {},\n actionData: null,\n errors: {\n [route.id]: error,\n },\n statusCode: error.status,\n loaderHeaders: {},\n actionHeaders: {},\n activeDeferreds: null,\n };\n } else if (!matches) {\n let error = getInternalRouterError(404, { pathname: location.pathname });\n let { matches: notFoundMatches, route } =\n getShortCircuitMatches(dataRoutes);\n return {\n basename,\n location,\n matches: notFoundMatches,\n loaderData: {},\n actionData: null,\n errors: {\n [route.id]: error,\n },\n statusCode: error.status,\n loaderHeaders: {},\n actionHeaders: {},\n activeDeferreds: null,\n };\n }\n\n let result = await queryImpl(\n request,\n location,\n matches,\n requestContext,\n dataStrategy || null,\n skipLoaderErrorBubbling === true,\n null\n );\n if (isResponse(result)) {\n return result;\n }\n\n // When returning StaticHandlerContext, we patch back in the location here\n // since we need it for React Context. But this helps keep our submit and\n // loadRouteData operating on a Request instead of a Location\n return { location, basename, ...result };\n }\n\n /**\n * The queryRoute() method is intended for targeted route requests, either\n * for fetch ?_data requests or resource route requests. In this case, we\n * are only ever calling a single action or loader, and we are returning the\n * returned value directly. In most cases, this will be a Response returned\n * from the action/loader, but it may be a primitive or other value as well -\n * and in such cases the calling context should handle that accordingly.\n *\n * We do respect the throw/return differentiation, so if an action/loader\n * throws, then this method will throw the value. This is important so we\n * can do proper boundary identification in Remix where a thrown Response\n * must go to the Catch Boundary but a returned Response is happy-path.\n *\n * One thing to note is that any Router-initiated Errors that make sense\n * to associate with a status code will be thrown as an ErrorResponse\n * instance which include the raw Error, such that the calling context can\n * serialize the error as they see fit while including the proper response\n * code. Examples here are 404 and 405 errors that occur prior to reaching\n * any user-defined loaders.\n *\n * - `opts.routeId` allows you to specify the specific route handler to call.\n * If not provided the handler will determine the proper route by matching\n * against `request.url`\n * - `opts.requestContext` is an optional server context that will be passed\n * to actions/loaders in the `context` parameter\n */\n async function queryRoute(\n request: Request,\n {\n routeId,\n requestContext,\n dataStrategy,\n }: {\n requestContext?: unknown;\n routeId?: string;\n dataStrategy?: DataStrategyFunction;\n } = {}\n ): Promise {\n let url = new URL(request.url);\n let method = request.method;\n let location = createLocation(\"\", createPath(url), null, \"default\");\n let matches = matchRoutes(dataRoutes, location, basename);\n\n // SSR supports HEAD requests while SPA doesn't\n if (!isValidMethod(method) && method !== \"HEAD\" && method !== \"OPTIONS\") {\n throw getInternalRouterError(405, { method });\n } else if (!matches) {\n throw getInternalRouterError(404, { pathname: location.pathname });\n }\n\n let match = routeId\n ? matches.find((m) => m.route.id === routeId)\n : getTargetMatch(matches, location);\n\n if (routeId && !match) {\n throw getInternalRouterError(403, {\n pathname: location.pathname,\n routeId,\n });\n } else if (!match) {\n // This should never hit I don't think?\n throw getInternalRouterError(404, { pathname: location.pathname });\n }\n\n let result = await queryImpl(\n request,\n location,\n matches,\n requestContext,\n dataStrategy || null,\n false,\n match\n );\n\n if (isResponse(result)) {\n return result;\n }\n\n let error = result.errors ? Object.values(result.errors)[0] : undefined;\n if (error !== undefined) {\n // If we got back result.errors, that means the loader/action threw\n // _something_ that wasn't a Response, but it's not guaranteed/required\n // to be an `instanceof Error` either, so we have to use throw here to\n // preserve the \"error\" state outside of queryImpl.\n throw error;\n }\n\n // Pick off the right state value to return\n if (result.actionData) {\n return Object.values(result.actionData)[0];\n }\n\n if (result.loaderData) {\n let data = Object.values(result.loaderData)[0];\n if (result.activeDeferreds?.[match.route.id]) {\n data[UNSAFE_DEFERRED_SYMBOL] = result.activeDeferreds[match.route.id];\n }\n return data;\n }\n\n return undefined;\n }\n\n async function queryImpl(\n request: Request,\n location: Location,\n matches: AgnosticDataRouteMatch[],\n requestContext: unknown,\n dataStrategy: DataStrategyFunction | null,\n skipLoaderErrorBubbling: boolean,\n routeMatch: AgnosticDataRouteMatch | null\n ): Promise | Response> {\n invariant(\n request.signal,\n \"query()/queryRoute() requests must contain an AbortController signal\"\n );\n\n try {\n if (isMutationMethod(request.method.toLowerCase())) {\n let result = await submit(\n request,\n matches,\n routeMatch || getTargetMatch(matches, location),\n requestContext,\n dataStrategy,\n skipLoaderErrorBubbling,\n routeMatch != null\n );\n return result;\n }\n\n let result = await loadRouteData(\n request,\n matches,\n requestContext,\n dataStrategy,\n skipLoaderErrorBubbling,\n routeMatch\n );\n return isResponse(result)\n ? result\n : {\n ...result,\n actionData: null,\n actionHeaders: {},\n };\n } catch (e) {\n // If the user threw/returned a Response in callLoaderOrAction for a\n // `queryRoute` call, we throw the `DataStrategyResult` to bail out early\n // and then return or throw the raw Response here accordingly\n if (isDataStrategyResult(e) && isResponse(e.result)) {\n if (e.type === ResultType.error) {\n throw e.result;\n }\n return e.result;\n }\n // Redirects are always returned since they don't propagate to catch\n // boundaries\n if (isRedirectResponse(e)) {\n return e;\n }\n throw e;\n }\n }\n\n async function submit(\n request: Request,\n matches: AgnosticDataRouteMatch[],\n actionMatch: AgnosticDataRouteMatch,\n requestContext: unknown,\n dataStrategy: DataStrategyFunction | null,\n skipLoaderErrorBubbling: boolean,\n isRouteRequest: boolean\n ): Promise | Response> {\n let result: DataResult;\n\n if (!actionMatch.route.action && !actionMatch.route.lazy) {\n let error = getInternalRouterError(405, {\n method: request.method,\n pathname: new URL(request.url).pathname,\n routeId: actionMatch.route.id,\n });\n if (isRouteRequest) {\n throw error;\n }\n result = {\n type: ResultType.error,\n error,\n };\n } else {\n let results = await callDataStrategy(\n \"action\",\n request,\n [actionMatch],\n matches,\n isRouteRequest,\n requestContext,\n dataStrategy\n );\n result = results[actionMatch.route.id];\n\n if (request.signal.aborted) {\n throwStaticHandlerAbortedError(request, isRouteRequest, future);\n }\n }\n\n if (isRedirectResult(result)) {\n // Uhhhh - this should never happen, we should always throw these from\n // callLoaderOrAction, but the type narrowing here keeps TS happy and we\n // can get back on the \"throw all redirect responses\" train here should\n // this ever happen :/\n throw new Response(null, {\n status: result.response.status,\n headers: {\n Location: result.response.headers.get(\"Location\")!,\n },\n });\n }\n\n if (isDeferredResult(result)) {\n let error = getInternalRouterError(400, { type: \"defer-action\" });\n if (isRouteRequest) {\n throw error;\n }\n result = {\n type: ResultType.error,\n error,\n };\n }\n\n if (isRouteRequest) {\n // Note: This should only be non-Response values if we get here, since\n // isRouteRequest should throw any Response received in callLoaderOrAction\n if (isErrorResult(result)) {\n throw result.error;\n }\n\n return {\n matches: [actionMatch],\n loaderData: {},\n actionData: { [actionMatch.route.id]: result.data },\n errors: null,\n // Note: statusCode + headers are unused here since queryRoute will\n // return the raw Response or value\n statusCode: 200,\n loaderHeaders: {},\n actionHeaders: {},\n activeDeferreds: null,\n };\n }\n\n // Create a GET request for the loaders\n let loaderRequest = new Request(request.url, {\n headers: request.headers,\n redirect: request.redirect,\n signal: request.signal,\n });\n\n if (isErrorResult(result)) {\n // Store off the pending error - we use it to determine which loaders\n // to call and will commit it when we complete the navigation\n let boundaryMatch = skipLoaderErrorBubbling\n ? actionMatch\n : findNearestBoundary(matches, actionMatch.route.id);\n\n let context = await loadRouteData(\n loaderRequest,\n matches,\n requestContext,\n dataStrategy,\n skipLoaderErrorBubbling,\n null,\n [boundaryMatch.route.id, result]\n );\n\n // action status codes take precedence over loader status codes\n return {\n ...context,\n statusCode: isRouteErrorResponse(result.error)\n ? result.error.status\n : result.statusCode != null\n ? result.statusCode\n : 500,\n actionData: null,\n actionHeaders: {\n ...(result.headers ? { [actionMatch.route.id]: result.headers } : {}),\n },\n };\n }\n\n let context = await loadRouteData(\n loaderRequest,\n matches,\n requestContext,\n dataStrategy,\n skipLoaderErrorBubbling,\n null\n );\n\n return {\n ...context,\n actionData: {\n [actionMatch.route.id]: result.data,\n },\n // action status codes take precedence over loader status codes\n ...(result.statusCode ? { statusCode: result.statusCode } : {}),\n actionHeaders: result.headers\n ? { [actionMatch.route.id]: result.headers }\n : {},\n };\n }\n\n async function loadRouteData(\n request: Request,\n matches: AgnosticDataRouteMatch[],\n requestContext: unknown,\n dataStrategy: DataStrategyFunction | null,\n skipLoaderErrorBubbling: boolean,\n routeMatch: AgnosticDataRouteMatch | null,\n pendingActionResult?: PendingActionResult\n ): Promise<\n | Omit<\n StaticHandlerContext,\n \"location\" | \"basename\" | \"actionData\" | \"actionHeaders\"\n >\n | Response\n > {\n let isRouteRequest = routeMatch != null;\n\n // Short circuit if we have no loaders to run (queryRoute())\n if (\n isRouteRequest &&\n !routeMatch?.route.loader &&\n !routeMatch?.route.lazy\n ) {\n throw getInternalRouterError(400, {\n method: request.method,\n pathname: new URL(request.url).pathname,\n routeId: routeMatch?.route.id,\n });\n }\n\n let requestMatches = routeMatch\n ? [routeMatch]\n : pendingActionResult && isErrorResult(pendingActionResult[1])\n ? getLoaderMatchesUntilBoundary(matches, pendingActionResult[0])\n : matches;\n let matchesToLoad = requestMatches.filter(\n (m) => m.route.loader || m.route.lazy\n );\n\n // Short circuit if we have no loaders to run (query())\n if (matchesToLoad.length === 0) {\n return {\n matches,\n // Add a null for all matched routes for proper revalidation on the client\n loaderData: matches.reduce(\n (acc, m) => Object.assign(acc, { [m.route.id]: null }),\n {}\n ),\n errors:\n pendingActionResult && isErrorResult(pendingActionResult[1])\n ? {\n [pendingActionResult[0]]: pendingActionResult[1].error,\n }\n : null,\n statusCode: 200,\n loaderHeaders: {},\n activeDeferreds: null,\n };\n }\n\n let results = await callDataStrategy(\n \"loader\",\n request,\n matchesToLoad,\n matches,\n isRouteRequest,\n requestContext,\n dataStrategy\n );\n\n if (request.signal.aborted) {\n throwStaticHandlerAbortedError(request, isRouteRequest, future);\n }\n\n // Process and commit output from loaders\n let activeDeferreds = new Map();\n let context = processRouteLoaderData(\n matches,\n results,\n pendingActionResult,\n activeDeferreds,\n skipLoaderErrorBubbling\n );\n\n // Add a null for any non-loader matches for proper revalidation on the client\n let executedLoaders = new Set(\n matchesToLoad.map((match) => match.route.id)\n );\n matches.forEach((match) => {\n if (!executedLoaders.has(match.route.id)) {\n context.loaderData[match.route.id] = null;\n }\n });\n\n return {\n ...context,\n matches,\n activeDeferreds:\n activeDeferreds.size > 0\n ? Object.fromEntries(activeDeferreds.entries())\n : null,\n };\n }\n\n // Utility wrapper for calling dataStrategy server-side without having to\n // pass around the manifest, mapRouteProperties, etc.\n async function callDataStrategy(\n type: \"loader\" | \"action\",\n request: Request,\n matchesToLoad: AgnosticDataRouteMatch[],\n matches: AgnosticDataRouteMatch[],\n isRouteRequest: boolean,\n requestContext: unknown,\n dataStrategy: DataStrategyFunction | null\n ): Promise> {\n let results = await callDataStrategyImpl(\n dataStrategy || defaultDataStrategy,\n type,\n null,\n request,\n matchesToLoad,\n matches,\n null,\n manifest,\n mapRouteProperties,\n requestContext\n );\n\n let dataResults: Record = {};\n await Promise.all(\n matches.map(async (match) => {\n if (!(match.route.id in results)) {\n return;\n }\n let result = results[match.route.id];\n if (isRedirectDataStrategyResultResult(result)) {\n let response = result.result as Response;\n // Throw redirects and let the server handle them with an HTTP redirect\n throw normalizeRelativeRoutingRedirectResponse(\n response,\n request,\n match.route.id,\n matches,\n basename,\n future.v7_relativeSplatPath\n );\n }\n if (isResponse(result.result) && isRouteRequest) {\n // For SSR single-route requests, we want to hand Responses back\n // directly without unwrapping\n throw result;\n }\n\n dataResults[match.route.id] =\n await convertDataStrategyResultToDataResult(result);\n })\n );\n return dataResults;\n }\n\n return {\n dataRoutes,\n query,\n queryRoute,\n };\n}\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Helpers\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Given an existing StaticHandlerContext and an error thrown at render time,\n * provide an updated StaticHandlerContext suitable for a second SSR render\n */\nexport function getStaticContextFromError(\n routes: AgnosticDataRouteObject[],\n context: StaticHandlerContext,\n error: any\n) {\n let newContext: StaticHandlerContext = {\n ...context,\n statusCode: isRouteErrorResponse(error) ? error.status : 500,\n errors: {\n [context._deepestRenderedBoundaryId || routes[0].id]: error,\n },\n };\n return newContext;\n}\n\nfunction throwStaticHandlerAbortedError(\n request: Request,\n isRouteRequest: boolean,\n future: StaticHandlerFutureConfig\n) {\n if (future.v7_throwAbortReason && request.signal.reason !== undefined) {\n throw request.signal.reason;\n }\n\n let method = isRouteRequest ? \"queryRoute\" : \"query\";\n throw new Error(`${method}() call aborted: ${request.method} ${request.url}`);\n}\n\nfunction isSubmissionNavigation(\n opts: BaseNavigateOrFetchOptions\n): opts is SubmissionNavigateOptions {\n return (\n opts != null &&\n ((\"formData\" in opts && opts.formData != null) ||\n (\"body\" in opts && opts.body !== undefined))\n );\n}\n\nfunction normalizeTo(\n location: Path,\n matches: AgnosticDataRouteMatch[],\n basename: string,\n prependBasename: boolean,\n to: To | null,\n v7_relativeSplatPath: boolean,\n fromRouteId?: string,\n relative?: RelativeRoutingType\n) {\n let contextualMatches: AgnosticDataRouteMatch[];\n let activeRouteMatch: AgnosticDataRouteMatch | undefined;\n if (fromRouteId) {\n // Grab matches up to the calling route so our route-relative logic is\n // relative to the correct source route\n contextualMatches = [];\n for (let match of matches) {\n contextualMatches.push(match);\n if (match.route.id === fromRouteId) {\n activeRouteMatch = match;\n break;\n }\n }\n } else {\n contextualMatches = matches;\n activeRouteMatch = matches[matches.length - 1];\n }\n\n // Resolve the relative path\n let path = resolveTo(\n to ? to : \".\",\n getResolveToMatches(contextualMatches, v7_relativeSplatPath),\n stripBasename(location.pathname, basename) || location.pathname,\n relative === \"path\"\n );\n\n // When `to` is not specified we inherit search/hash from the current\n // location, unlike when to=\".\" and we just inherit the path.\n // See https://github.com/remix-run/remix/issues/927\n if (to == null) {\n path.search = location.search;\n path.hash = location.hash;\n }\n\n // Account for `?index` params when routing to the current location\n if ((to == null || to === \"\" || to === \".\") && activeRouteMatch) {\n let nakedIndex = hasNakedIndexQuery(path.search);\n if (activeRouteMatch.route.index && !nakedIndex) {\n // Add one when we're targeting an index route\n path.search = path.search\n ? path.search.replace(/^\\?/, \"?index&\")\n : \"?index\";\n } else if (!activeRouteMatch.route.index && nakedIndex) {\n // Remove existing ones when we're not\n let params = new URLSearchParams(path.search);\n let indexValues = params.getAll(\"index\");\n params.delete(\"index\");\n indexValues.filter((v) => v).forEach((v) => params.append(\"index\", v));\n let qs = params.toString();\n path.search = qs ? `?${qs}` : \"\";\n }\n }\n\n // If we're operating within a basename, prepend it to the pathname. If\n // this is a root navigation, then just use the raw basename which allows\n // the basename to have full control over the presence of a trailing slash\n // on root actions\n if (prependBasename && basename !== \"/\") {\n path.pathname =\n path.pathname === \"/\" ? basename : joinPaths([basename, path.pathname]);\n }\n\n return createPath(path);\n}\n\n// Normalize navigation options by converting formMethod=GET formData objects to\n// URLSearchParams so they behave identically to links with query params\nfunction normalizeNavigateOptions(\n normalizeFormMethod: boolean,\n isFetcher: boolean,\n path: string,\n opts?: BaseNavigateOrFetchOptions\n): {\n path: string;\n submission?: Submission;\n error?: ErrorResponseImpl;\n} {\n // Return location verbatim on non-submission navigations\n if (!opts || !isSubmissionNavigation(opts)) {\n return { path };\n }\n\n if (opts.formMethod && !isValidMethod(opts.formMethod)) {\n return {\n path,\n error: getInternalRouterError(405, { method: opts.formMethod }),\n };\n }\n\n let getInvalidBodyError = () => ({\n path,\n error: getInternalRouterError(400, { type: \"invalid-body\" }),\n });\n\n // Create a Submission on non-GET navigations\n let rawFormMethod = opts.formMethod || \"get\";\n let formMethod = normalizeFormMethod\n ? (rawFormMethod.toUpperCase() as V7_FormMethod)\n : (rawFormMethod.toLowerCase() as FormMethod);\n let formAction = stripHashFromPath(path);\n\n if (opts.body !== undefined) {\n if (opts.formEncType === \"text/plain\") {\n // text only support POST/PUT/PATCH/DELETE submissions\n if (!isMutationMethod(formMethod)) {\n return getInvalidBodyError();\n }\n\n let text =\n typeof opts.body === \"string\"\n ? opts.body\n : opts.body instanceof FormData ||\n opts.body instanceof URLSearchParams\n ? // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#plain-text-form-data\n Array.from(opts.body.entries()).reduce(\n (acc, [name, value]) => `${acc}${name}=${value}\\n`,\n \"\"\n )\n : String(opts.body);\n\n return {\n path,\n submission: {\n formMethod,\n formAction,\n formEncType: opts.formEncType,\n formData: undefined,\n json: undefined,\n text,\n },\n };\n } else if (opts.formEncType === \"application/json\") {\n // json only supports POST/PUT/PATCH/DELETE submissions\n if (!isMutationMethod(formMethod)) {\n return getInvalidBodyError();\n }\n\n try {\n let json =\n typeof opts.body === \"string\" ? JSON.parse(opts.body) : opts.body;\n\n return {\n path,\n submission: {\n formMethod,\n formAction,\n formEncType: opts.formEncType,\n formData: undefined,\n json,\n text: undefined,\n },\n };\n } catch (e) {\n return getInvalidBodyError();\n }\n }\n }\n\n invariant(\n typeof FormData === \"function\",\n \"FormData is not available in this environment\"\n );\n\n let searchParams: URLSearchParams;\n let formData: FormData;\n\n if (opts.formData) {\n searchParams = convertFormDataToSearchParams(opts.formData);\n formData = opts.formData;\n } else if (opts.body instanceof FormData) {\n searchParams = convertFormDataToSearchParams(opts.body);\n formData = opts.body;\n } else if (opts.body instanceof URLSearchParams) {\n searchParams = opts.body;\n formData = convertSearchParamsToFormData(searchParams);\n } else if (opts.body == null) {\n searchParams = new URLSearchParams();\n formData = new FormData();\n } else {\n try {\n searchParams = new URLSearchParams(opts.body);\n formData = convertSearchParamsToFormData(searchParams);\n } catch (e) {\n return getInvalidBodyError();\n }\n }\n\n let submission: Submission = {\n formMethod,\n formAction,\n formEncType:\n (opts && opts.formEncType) || \"application/x-www-form-urlencoded\",\n formData,\n json: undefined,\n text: undefined,\n };\n\n if (isMutationMethod(submission.formMethod)) {\n return { path, submission };\n }\n\n // Flatten submission onto URLSearchParams for GET submissions\n let parsedPath = parsePath(path);\n // On GET navigation submissions we can drop the ?index param from the\n // resulting location since all loaders will run. But fetcher GET submissions\n // only run a single loader so we need to preserve any incoming ?index params\n if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) {\n searchParams.append(\"index\", \"\");\n }\n parsedPath.search = `?${searchParams}`;\n\n return { path: createPath(parsedPath), submission };\n}\n\n// Filter out all routes at/below any caught error as they aren't going to\n// render so we don't need to load them\nfunction getLoaderMatchesUntilBoundary(\n matches: AgnosticDataRouteMatch[],\n boundaryId: string,\n includeBoundary = false\n) {\n let index = matches.findIndex((m) => m.route.id === boundaryId);\n if (index >= 0) {\n return matches.slice(0, includeBoundary ? index + 1 : index);\n }\n return matches;\n}\n\nfunction getMatchesToLoad(\n history: History,\n state: RouterState,\n matches: AgnosticDataRouteMatch[],\n submission: Submission | undefined,\n location: Location,\n initialHydration: boolean,\n skipActionErrorRevalidation: boolean,\n isRevalidationRequired: boolean,\n cancelledDeferredRoutes: string[],\n cancelledFetcherLoads: Set,\n deletedFetchers: Set,\n fetchLoadMatches: Map,\n fetchRedirectIds: Set,\n routesToUse: AgnosticDataRouteObject[],\n basename: string | undefined,\n pendingActionResult?: PendingActionResult\n): [AgnosticDataRouteMatch[], RevalidatingFetcher[]] {\n let actionResult = pendingActionResult\n ? isErrorResult(pendingActionResult[1])\n ? pendingActionResult[1].error\n : pendingActionResult[1].data\n : undefined;\n let currentUrl = history.createURL(state.location);\n let nextUrl = history.createURL(location);\n\n // Pick navigation matches that are net-new or qualify for revalidation\n let boundaryMatches = matches;\n if (initialHydration && state.errors) {\n // On initial hydration, only consider matches up to _and including_ the boundary.\n // This is inclusive to handle cases where a server loader ran successfully,\n // a child server loader bubbled up to this route, but this route has\n // `clientLoader.hydrate` so we want to still run the `clientLoader` so that\n // we have a complete version of `loaderData`\n boundaryMatches = getLoaderMatchesUntilBoundary(\n matches,\n Object.keys(state.errors)[0],\n true\n );\n } else if (pendingActionResult && isErrorResult(pendingActionResult[1])) {\n // If an action threw an error, we call loaders up to, but not including the\n // boundary\n boundaryMatches = getLoaderMatchesUntilBoundary(\n matches,\n pendingActionResult[0]\n );\n }\n\n // Don't revalidate loaders by default after action 4xx/5xx responses\n // when the flag is enabled. They can still opt-into revalidation via\n // `shouldRevalidate` via `actionResult`\n let actionStatus = pendingActionResult\n ? pendingActionResult[1].statusCode\n : undefined;\n let shouldSkipRevalidation =\n skipActionErrorRevalidation && actionStatus && actionStatus >= 400;\n\n let navigationMatches = boundaryMatches.filter((match, index) => {\n let { route } = match;\n if (route.lazy) {\n // We haven't loaded this route yet so we don't know if it's got a loader!\n return true;\n }\n\n if (route.loader == null) {\n return false;\n }\n\n if (initialHydration) {\n return shouldLoadRouteOnHydration(route, state.loaderData, state.errors);\n }\n\n // Always call the loader on new route instances and pending defer cancellations\n if (\n isNewLoader(state.loaderData, state.matches[index], match) ||\n cancelledDeferredRoutes.some((id) => id === match.route.id)\n ) {\n return true;\n }\n\n // This is the default implementation for when we revalidate. If the route\n // provides it's own implementation, then we give them full control but\n // provide this value so they can leverage it if needed after they check\n // their own specific use cases\n let currentRouteMatch = state.matches[index];\n let nextRouteMatch = match;\n\n return shouldRevalidateLoader(match, {\n currentUrl,\n currentParams: currentRouteMatch.params,\n nextUrl,\n nextParams: nextRouteMatch.params,\n ...submission,\n actionResult,\n actionStatus,\n defaultShouldRevalidate: shouldSkipRevalidation\n ? false\n : // Forced revalidation due to submission, useRevalidator, or X-Remix-Revalidate\n isRevalidationRequired ||\n currentUrl.pathname + currentUrl.search ===\n nextUrl.pathname + nextUrl.search ||\n // Search params affect all loaders\n currentUrl.search !== nextUrl.search ||\n isNewRouteInstance(currentRouteMatch, nextRouteMatch),\n });\n });\n\n // Pick fetcher.loads that need to be revalidated\n let revalidatingFetchers: RevalidatingFetcher[] = [];\n fetchLoadMatches.forEach((f, key) => {\n // Don't revalidate:\n // - on initial hydration (shouldn't be any fetchers then anyway)\n // - if fetcher won't be present in the subsequent render\n // - no longer matches the URL (v7_fetcherPersist=false)\n // - was unmounted but persisted due to v7_fetcherPersist=true\n if (\n initialHydration ||\n !matches.some((m) => m.route.id === f.routeId) ||\n deletedFetchers.has(key)\n ) {\n return;\n }\n\n let fetcherMatches = matchRoutes(routesToUse, f.path, basename);\n\n // If the fetcher path no longer matches, push it in with null matches so\n // we can trigger a 404 in callLoadersAndMaybeResolveData. Note this is\n // currently only a use-case for Remix HMR where the route tree can change\n // at runtime and remove a route previously loaded via a fetcher\n if (!fetcherMatches) {\n revalidatingFetchers.push({\n key,\n routeId: f.routeId,\n path: f.path,\n matches: null,\n match: null,\n controller: null,\n });\n return;\n }\n\n // Revalidating fetchers are decoupled from the route matches since they\n // load from a static href. They revalidate based on explicit revalidation\n // (submission, useRevalidator, or X-Remix-Revalidate)\n let fetcher = state.fetchers.get(key);\n let fetcherMatch = getTargetMatch(fetcherMatches, f.path);\n\n let shouldRevalidate = false;\n if (fetchRedirectIds.has(key)) {\n // Never trigger a revalidation of an actively redirecting fetcher\n shouldRevalidate = false;\n } else if (cancelledFetcherLoads.has(key)) {\n // Always mark for revalidation if the fetcher was cancelled\n cancelledFetcherLoads.delete(key);\n shouldRevalidate = true;\n } else if (\n fetcher &&\n fetcher.state !== \"idle\" &&\n fetcher.data === undefined\n ) {\n // If the fetcher hasn't ever completed loading yet, then this isn't a\n // revalidation, it would just be a brand new load if an explicit\n // revalidation is required\n shouldRevalidate = isRevalidationRequired;\n } else {\n // Otherwise fall back on any user-defined shouldRevalidate, defaulting\n // to explicit revalidations only\n shouldRevalidate = shouldRevalidateLoader(fetcherMatch, {\n currentUrl,\n currentParams: state.matches[state.matches.length - 1].params,\n nextUrl,\n nextParams: matches[matches.length - 1].params,\n ...submission,\n actionResult,\n actionStatus,\n defaultShouldRevalidate: shouldSkipRevalidation\n ? false\n : isRevalidationRequired,\n });\n }\n\n if (shouldRevalidate) {\n revalidatingFetchers.push({\n key,\n routeId: f.routeId,\n path: f.path,\n matches: fetcherMatches,\n match: fetcherMatch,\n controller: new AbortController(),\n });\n }\n });\n\n return [navigationMatches, revalidatingFetchers];\n}\n\nfunction shouldLoadRouteOnHydration(\n route: AgnosticDataRouteObject,\n loaderData: RouteData | null | undefined,\n errors: RouteData | null | undefined\n) {\n // We dunno if we have a loader - gotta find out!\n if (route.lazy) {\n return true;\n }\n\n // No loader, nothing to initialize\n if (!route.loader) {\n return false;\n }\n\n let hasData = loaderData != null && loaderData[route.id] !== undefined;\n let hasError = errors != null && errors[route.id] !== undefined;\n\n // Don't run if we error'd during SSR\n if (!hasData && hasError) {\n return false;\n }\n\n // Explicitly opting-in to running on hydration\n if (typeof route.loader === \"function\" && route.loader.hydrate === true) {\n return true;\n }\n\n // Otherwise, run if we're not yet initialized with anything\n return !hasData && !hasError;\n}\n\nfunction isNewLoader(\n currentLoaderData: RouteData,\n currentMatch: AgnosticDataRouteMatch,\n match: AgnosticDataRouteMatch\n) {\n let isNew =\n // [a] -> [a, b]\n !currentMatch ||\n // [a, b] -> [a, c]\n match.route.id !== currentMatch.route.id;\n\n // Handle the case that we don't have data for a re-used route, potentially\n // from a prior error or from a cancelled pending deferred\n let isMissingData = currentLoaderData[match.route.id] === undefined;\n\n // Always load if this is a net-new route or we don't yet have data\n return isNew || isMissingData;\n}\n\nfunction isNewRouteInstance(\n currentMatch: AgnosticDataRouteMatch,\n match: AgnosticDataRouteMatch\n) {\n let currentPath = currentMatch.route.path;\n return (\n // param change for this match, /users/123 -> /users/456\n currentMatch.pathname !== match.pathname ||\n // splat param changed, which is not present in match.path\n // e.g. /files/images/avatar.jpg -> files/finances.xls\n (currentPath != null &&\n currentPath.endsWith(\"*\") &&\n currentMatch.params[\"*\"] !== match.params[\"*\"])\n );\n}\n\nfunction shouldRevalidateLoader(\n loaderMatch: AgnosticDataRouteMatch,\n arg: ShouldRevalidateFunctionArgs\n) {\n if (loaderMatch.route.shouldRevalidate) {\n let routeChoice = loaderMatch.route.shouldRevalidate(arg);\n if (typeof routeChoice === \"boolean\") {\n return routeChoice;\n }\n }\n\n return arg.defaultShouldRevalidate;\n}\n\nfunction patchRoutesImpl(\n routeId: string | null,\n children: AgnosticRouteObject[],\n routesToUse: AgnosticDataRouteObject[],\n manifest: RouteManifest,\n mapRouteProperties: MapRoutePropertiesFunction\n) {\n let childrenToPatch: AgnosticDataRouteObject[];\n if (routeId) {\n let route = manifest[routeId];\n invariant(\n route,\n `No route found to patch children into: routeId = ${routeId}`\n );\n if (!route.children) {\n route.children = [];\n }\n childrenToPatch = route.children;\n } else {\n childrenToPatch = routesToUse;\n }\n\n // Don't patch in routes we already know about so that `patch` is idempotent\n // to simplify user-land code. This is useful because we re-call the\n // `patchRoutesOnNavigation` function for matched routes with params.\n let uniqueChildren = children.filter(\n (newRoute) =>\n !childrenToPatch.some((existingRoute) =>\n isSameRoute(newRoute, existingRoute)\n )\n );\n\n let newRoutes = convertRoutesToDataRoutes(\n uniqueChildren,\n mapRouteProperties,\n [routeId || \"_\", \"patch\", String(childrenToPatch?.length || \"0\")],\n manifest\n );\n\n childrenToPatch.push(...newRoutes);\n}\n\nfunction isSameRoute(\n newRoute: AgnosticRouteObject,\n existingRoute: AgnosticRouteObject\n): boolean {\n // Most optimal check is by id\n if (\n \"id\" in newRoute &&\n \"id\" in existingRoute &&\n newRoute.id === existingRoute.id\n ) {\n return true;\n }\n\n // Second is by pathing differences\n if (\n !(\n newRoute.index === existingRoute.index &&\n newRoute.path === existingRoute.path &&\n newRoute.caseSensitive === existingRoute.caseSensitive\n )\n ) {\n return false;\n }\n\n // Pathless layout routes are trickier since we need to check children.\n // If they have no children then they're the same as far as we can tell\n if (\n (!newRoute.children || newRoute.children.length === 0) &&\n (!existingRoute.children || existingRoute.children.length === 0)\n ) {\n return true;\n }\n\n // Otherwise, we look to see if every child in the new route is already\n // represented in the existing route's children\n return newRoute.children!.every((aChild, i) =>\n existingRoute.children?.some((bChild) => isSameRoute(aChild, bChild))\n );\n}\n\n/**\n * Execute route.lazy() methods to lazily load route modules (loader, action,\n * shouldRevalidate) and update the routeManifest in place which shares objects\n * with dataRoutes so those get updated as well.\n */\nasync function loadLazyRouteModule(\n route: AgnosticDataRouteObject,\n mapRouteProperties: MapRoutePropertiesFunction,\n manifest: RouteManifest\n) {\n if (!route.lazy) {\n return;\n }\n\n let lazyRoute = await route.lazy();\n\n // If the lazy route function was executed and removed by another parallel\n // call then we can return - first lazy() to finish wins because the return\n // value of lazy is expected to be static\n if (!route.lazy) {\n return;\n }\n\n let routeToUpdate = manifest[route.id];\n invariant(routeToUpdate, \"No route found in manifest\");\n\n // Update the route in place. This should be safe because there's no way\n // we could yet be sitting on this route as we can't get there without\n // resolving lazy() first.\n //\n // This is different than the HMR \"update\" use-case where we may actively be\n // on the route being updated. The main concern boils down to \"does this\n // mutation affect any ongoing navigations or any current state.matches\n // values?\". If not, it should be safe to update in place.\n let routeUpdates: Record = {};\n for (let lazyRouteProperty in lazyRoute) {\n let staticRouteValue =\n routeToUpdate[lazyRouteProperty as keyof typeof routeToUpdate];\n\n let isPropertyStaticallyDefined =\n staticRouteValue !== undefined &&\n // This property isn't static since it should always be updated based\n // on the route updates\n lazyRouteProperty !== \"hasErrorBoundary\";\n\n warning(\n !isPropertyStaticallyDefined,\n `Route \"${routeToUpdate.id}\" has a static property \"${lazyRouteProperty}\" ` +\n `defined but its lazy function is also returning a value for this property. ` +\n `The lazy route property \"${lazyRouteProperty}\" will be ignored.`\n );\n\n if (\n !isPropertyStaticallyDefined &&\n !immutableRouteKeys.has(lazyRouteProperty as ImmutableRouteKey)\n ) {\n routeUpdates[lazyRouteProperty] =\n lazyRoute[lazyRouteProperty as keyof typeof lazyRoute];\n }\n }\n\n // Mutate the route with the provided updates. Do this first so we pass\n // the updated version to mapRouteProperties\n Object.assign(routeToUpdate, routeUpdates);\n\n // Mutate the `hasErrorBoundary` property on the route based on the route\n // updates and remove the `lazy` function so we don't resolve the lazy\n // route again.\n Object.assign(routeToUpdate, {\n // To keep things framework agnostic, we use the provided\n // `mapRouteProperties` (or wrapped `detectErrorBoundary`) function to\n // set the framework-aware properties (`element`/`hasErrorBoundary`) since\n // the logic will differ between frameworks.\n ...mapRouteProperties(routeToUpdate),\n lazy: undefined,\n });\n}\n\n// Default implementation of `dataStrategy` which fetches all loaders in parallel\nasync function defaultDataStrategy({\n matches,\n}: DataStrategyFunctionArgs): ReturnType {\n let matchesToLoad = matches.filter((m) => m.shouldLoad);\n let results = await Promise.all(matchesToLoad.map((m) => m.resolve()));\n return results.reduce(\n (acc, result, i) =>\n Object.assign(acc, { [matchesToLoad[i].route.id]: result }),\n {}\n );\n}\n\nasync function callDataStrategyImpl(\n dataStrategyImpl: DataStrategyFunction,\n type: \"loader\" | \"action\",\n state: RouterState | null,\n request: Request,\n matchesToLoad: AgnosticDataRouteMatch[],\n matches: AgnosticDataRouteMatch[],\n fetcherKey: string | null,\n manifest: RouteManifest,\n mapRouteProperties: MapRoutePropertiesFunction,\n requestContext?: unknown\n): Promise> {\n let loadRouteDefinitionsPromises = matches.map((m) =>\n m.route.lazy\n ? loadLazyRouteModule(m.route, mapRouteProperties, manifest)\n : undefined\n );\n\n let dsMatches = matches.map((match, i) => {\n let loadRoutePromise = loadRouteDefinitionsPromises[i];\n let shouldLoad = matchesToLoad.some((m) => m.route.id === match.route.id);\n // `resolve` encapsulates route.lazy(), executing the loader/action,\n // and mapping return values/thrown errors to a `DataStrategyResult`. Users\n // can pass a callback to take fine-grained control over the execution\n // of the loader/action\n let resolve: DataStrategyMatch[\"resolve\"] = async (handlerOverride) => {\n if (\n handlerOverride &&\n request.method === \"GET\" &&\n (match.route.lazy || match.route.loader)\n ) {\n shouldLoad = true;\n }\n return shouldLoad\n ? callLoaderOrAction(\n type,\n request,\n match,\n loadRoutePromise,\n handlerOverride,\n requestContext\n )\n : Promise.resolve({ type: ResultType.data, result: undefined });\n };\n\n return {\n ...match,\n shouldLoad,\n resolve,\n };\n });\n\n // Send all matches here to allow for a middleware-type implementation.\n // handler will be a no-op for unneeded routes and we filter those results\n // back out below.\n let results = await dataStrategyImpl({\n matches: dsMatches,\n request,\n params: matches[0].params,\n fetcherKey,\n context: requestContext,\n });\n\n // Wait for all routes to load here but 'swallow the error since we want\n // it to bubble up from the `await loadRoutePromise` in `callLoaderOrAction` -\n // called from `match.resolve()`\n try {\n await Promise.all(loadRouteDefinitionsPromises);\n } catch (e) {\n // No-op\n }\n\n return results;\n}\n\n// Default logic for calling a loader/action is the user has no specified a dataStrategy\nasync function callLoaderOrAction(\n type: \"loader\" | \"action\",\n request: Request,\n match: AgnosticDataRouteMatch,\n loadRoutePromise: Promise | undefined,\n handlerOverride: Parameters[0],\n staticContext?: unknown\n): Promise {\n let result: DataStrategyResult;\n let onReject: (() => void) | undefined;\n\n let runHandler = (\n handler: AgnosticRouteObject[\"loader\"] | AgnosticRouteObject[\"action\"]\n ): Promise => {\n // Setup a promise we can race against so that abort signals short circuit\n let reject: () => void;\n // This will never resolve so safe to type it as Promise to\n // satisfy the function return value\n let abortPromise = new Promise((_, r) => (reject = r));\n onReject = () => reject();\n request.signal.addEventListener(\"abort\", onReject);\n\n let actualHandler = (ctx?: unknown) => {\n if (typeof handler !== \"function\") {\n return Promise.reject(\n new Error(\n `You cannot call the handler for a route which defines a boolean ` +\n `\"${type}\" [routeId: ${match.route.id}]`\n )\n );\n }\n return handler(\n {\n request,\n params: match.params,\n context: staticContext,\n },\n ...(ctx !== undefined ? [ctx] : [])\n );\n };\n\n let handlerPromise: Promise = (async () => {\n try {\n let val = await (handlerOverride\n ? handlerOverride((ctx: unknown) => actualHandler(ctx))\n : actualHandler());\n return { type: \"data\", result: val };\n } catch (e) {\n return { type: \"error\", result: e };\n }\n })();\n\n return Promise.race([handlerPromise, abortPromise]);\n };\n\n try {\n let handler = match.route[type];\n\n // If we have a route.lazy promise, await that first\n if (loadRoutePromise) {\n if (handler) {\n // Run statically defined handler in parallel with lazy()\n let handlerError;\n let [value] = await Promise.all([\n // If the handler throws, don't let it immediately bubble out,\n // since we need to let the lazy() execution finish so we know if this\n // route has a boundary that can handle the error\n runHandler(handler).catch((e) => {\n handlerError = e;\n }),\n loadRoutePromise,\n ]);\n if (handlerError !== undefined) {\n throw handlerError;\n }\n result = value!;\n } else {\n // Load lazy route module, then run any returned handler\n await loadRoutePromise;\n\n handler = match.route[type];\n if (handler) {\n // Handler still runs even if we got interrupted to maintain consistency\n // with un-abortable behavior of handler execution on non-lazy or\n // previously-lazy-loaded routes\n result = await runHandler(handler);\n } else if (type === \"action\") {\n let url = new URL(request.url);\n let pathname = url.pathname + url.search;\n throw getInternalRouterError(405, {\n method: request.method,\n pathname,\n routeId: match.route.id,\n });\n } else {\n // lazy() route has no loader to run. Short circuit here so we don't\n // hit the invariant below that errors on returning undefined.\n return { type: ResultType.data, result: undefined };\n }\n }\n } else if (!handler) {\n let url = new URL(request.url);\n let pathname = url.pathname + url.search;\n throw getInternalRouterError(404, {\n pathname,\n });\n } else {\n result = await runHandler(handler);\n }\n\n invariant(\n result.result !== undefined,\n `You defined ${type === \"action\" ? \"an action\" : \"a loader\"} for route ` +\n `\"${match.route.id}\" but didn't return anything from your \\`${type}\\` ` +\n `function. Please return a value or \\`null\\`.`\n );\n } catch (e) {\n // We should already be catching and converting normal handler executions to\n // DataStrategyResults and returning them, so anything that throws here is an\n // unexpected error we still need to wrap\n return { type: ResultType.error, result: e };\n } finally {\n if (onReject) {\n request.signal.removeEventListener(\"abort\", onReject);\n }\n }\n\n return result;\n}\n\nasync function convertDataStrategyResultToDataResult(\n dataStrategyResult: DataStrategyResult\n): Promise {\n let { result, type } = dataStrategyResult;\n\n if (isResponse(result)) {\n let data: any;\n\n try {\n let contentType = result.headers.get(\"Content-Type\");\n // Check between word boundaries instead of startsWith() due to the last\n // paragraph of https://httpwg.org/specs/rfc9110.html#field.content-type\n if (contentType && /\\bapplication\\/json\\b/.test(contentType)) {\n if (result.body == null) {\n data = null;\n } else {\n data = await result.json();\n }\n } else {\n data = await result.text();\n }\n } catch (e) {\n return { type: ResultType.error, error: e };\n }\n\n if (type === ResultType.error) {\n return {\n type: ResultType.error,\n error: new ErrorResponseImpl(result.status, result.statusText, data),\n statusCode: result.status,\n headers: result.headers,\n };\n }\n\n return {\n type: ResultType.data,\n data,\n statusCode: result.status,\n headers: result.headers,\n };\n }\n\n if (type === ResultType.error) {\n if (isDataWithResponseInit(result)) {\n if (result.data instanceof Error) {\n return {\n type: ResultType.error,\n error: result.data,\n statusCode: result.init?.status,\n headers: result.init?.headers\n ? new Headers(result.init.headers)\n : undefined,\n };\n }\n\n // Convert thrown data() to ErrorResponse instances\n return {\n type: ResultType.error,\n error: new ErrorResponseImpl(\n result.init?.status || 500,\n undefined,\n result.data\n ),\n statusCode: isRouteErrorResponse(result) ? result.status : undefined,\n headers: result.init?.headers\n ? new Headers(result.init.headers)\n : undefined,\n };\n }\n return {\n type: ResultType.error,\n error: result,\n statusCode: isRouteErrorResponse(result) ? result.status : undefined,\n };\n }\n\n if (isDeferredData(result)) {\n return {\n type: ResultType.deferred,\n deferredData: result,\n statusCode: result.init?.status,\n headers: result.init?.headers && new Headers(result.init.headers),\n };\n }\n\n if (isDataWithResponseInit(result)) {\n return {\n type: ResultType.data,\n data: result.data,\n statusCode: result.init?.status,\n headers: result.init?.headers\n ? new Headers(result.init.headers)\n : undefined,\n };\n }\n\n return { type: ResultType.data, data: result };\n}\n\n// Support relative routing in internal redirects\nfunction normalizeRelativeRoutingRedirectResponse(\n response: Response,\n request: Request,\n routeId: string,\n matches: AgnosticDataRouteMatch[],\n basename: string,\n v7_relativeSplatPath: boolean\n) {\n let location = response.headers.get(\"Location\");\n invariant(\n location,\n \"Redirects returned/thrown from loaders/actions must have a Location header\"\n );\n\n if (!ABSOLUTE_URL_REGEX.test(location)) {\n let trimmedMatches = matches.slice(\n 0,\n matches.findIndex((m) => m.route.id === routeId) + 1\n );\n location = normalizeTo(\n new URL(request.url),\n trimmedMatches,\n basename,\n true,\n location,\n v7_relativeSplatPath\n );\n response.headers.set(\"Location\", location);\n }\n\n return response;\n}\n\nfunction normalizeRedirectLocation(\n location: string,\n currentUrl: URL,\n basename: string,\n historyInstance: History,\n): string {\n // Match Chrome's behavior:\n // https://github.com/chromium/chromium/blob/216dbeb61db0c667e62082e5f5400a32d6983df3/content/public/common/url_utils.cc#L82\n let invalidProtocols = [\n \"about:\",\n \"blob:\",\n \"chrome:\",\n \"chrome-untrusted:\",\n \"content:\",\n \"data:\",\n \"devtools:\",\n \"file:\",\n \"filesystem:\",\n // eslint-disable-next-line no-script-url\n \"javascript:\",\n ];\n\n if (ABSOLUTE_URL_REGEX.test(location)) {\n // Strip off the protocol+origin for same-origin + same-basename absolute redirects\n let normalizedLocation = location;\n let url = normalizedLocation.startsWith(\"//\")\n ? new URL(currentUrl.protocol + normalizedLocation)\n : new URL(normalizedLocation);\n if (invalidProtocols.includes(url.protocol)) {\n throw new Error(\"Invalid redirect location\");\n }\n let isSameBasename = stripBasename(url.pathname, basename) != null;\n if (url.origin === currentUrl.origin && isSameBasename) {\n return removeDoubleSlashes(url.pathname) + url.search + url.hash;\n }\n }\n\n try {\n let url = historyInstance.createURL(location);\n if (invalidProtocols.includes(url.protocol)) {\n throw new Error(\"Invalid redirect location\");\n }\n } catch (e) {}\n\n return location;\n}\n\n// Utility method for creating the Request instances for loaders/actions during\n// client-side navigations and fetches. During SSR we will always have a\n// Request instance from the static handler (query/queryRoute)\nfunction createClientSideRequest(\n history: History,\n location: string | Location,\n signal: AbortSignal,\n submission?: Submission\n): Request {\n let url = history.createURL(stripHashFromPath(location)).toString();\n let init: RequestInit = { signal };\n\n if (submission && isMutationMethod(submission.formMethod)) {\n let { formMethod, formEncType } = submission;\n // Didn't think we needed this but it turns out unlike other methods, patch\n // won't be properly normalized to uppercase and results in a 405 error.\n // See: https://fetch.spec.whatwg.org/#concept-method\n init.method = formMethod.toUpperCase();\n\n if (formEncType === \"application/json\") {\n init.headers = new Headers({ \"Content-Type\": formEncType });\n init.body = JSON.stringify(submission.json);\n } else if (formEncType === \"text/plain\") {\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n init.body = submission.text;\n } else if (\n formEncType === \"application/x-www-form-urlencoded\" &&\n submission.formData\n ) {\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n init.body = convertFormDataToSearchParams(submission.formData);\n } else {\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n init.body = submission.formData;\n }\n }\n\n return new Request(url, init);\n}\n\nfunction convertFormDataToSearchParams(formData: FormData): URLSearchParams {\n let searchParams = new URLSearchParams();\n\n for (let [key, value] of formData.entries()) {\n // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#converting-an-entry-list-to-a-list-of-name-value-pairs\n searchParams.append(key, typeof value === \"string\" ? value : value.name);\n }\n\n return searchParams;\n}\n\nfunction convertSearchParamsToFormData(\n searchParams: URLSearchParams\n): FormData {\n let formData = new FormData();\n for (let [key, value] of searchParams.entries()) {\n formData.append(key, value);\n }\n return formData;\n}\n\nfunction processRouteLoaderData(\n matches: AgnosticDataRouteMatch[],\n results: Record,\n pendingActionResult: PendingActionResult | undefined,\n activeDeferreds: Map,\n skipLoaderErrorBubbling: boolean\n): {\n loaderData: RouterState[\"loaderData\"];\n errors: RouterState[\"errors\"] | null;\n statusCode: number;\n loaderHeaders: Record;\n} {\n // Fill in loaderData/errors from our loaders\n let loaderData: RouterState[\"loaderData\"] = {};\n let errors: RouterState[\"errors\"] | null = null;\n let statusCode: number | undefined;\n let foundError = false;\n let loaderHeaders: Record = {};\n let pendingError =\n pendingActionResult && isErrorResult(pendingActionResult[1])\n ? pendingActionResult[1].error\n : undefined;\n\n // Process loader results into state.loaderData/state.errors\n matches.forEach((match) => {\n if (!(match.route.id in results)) {\n return;\n }\n let id = match.route.id;\n let result = results[id];\n invariant(\n !isRedirectResult(result),\n \"Cannot handle redirect results in processLoaderData\"\n );\n if (isErrorResult(result)) {\n let error = result.error;\n // If we have a pending action error, we report it at the highest-route\n // that throws a loader error, and then clear it out to indicate that\n // it was consumed\n if (pendingError !== undefined) {\n error = pendingError;\n pendingError = undefined;\n }\n\n errors = errors || {};\n\n if (skipLoaderErrorBubbling) {\n errors[id] = error;\n } else {\n // Look upwards from the matched route for the closest ancestor error\n // boundary, defaulting to the root match. Prefer higher error values\n // if lower errors bubble to the same boundary\n let boundaryMatch = findNearestBoundary(matches, id);\n if (errors[boundaryMatch.route.id] == null) {\n errors[boundaryMatch.route.id] = error;\n }\n }\n\n // Clear our any prior loaderData for the throwing route\n loaderData[id] = undefined;\n\n // Once we find our first (highest) error, we set the status code and\n // prevent deeper status codes from overriding\n if (!foundError) {\n foundError = true;\n statusCode = isRouteErrorResponse(result.error)\n ? result.error.status\n : 500;\n }\n if (result.headers) {\n loaderHeaders[id] = result.headers;\n }\n } else {\n if (isDeferredResult(result)) {\n activeDeferreds.set(id, result.deferredData);\n loaderData[id] = result.deferredData.data;\n // Error status codes always override success status codes, but if all\n // loaders are successful we take the deepest status code.\n if (\n result.statusCode != null &&\n result.statusCode !== 200 &&\n !foundError\n ) {\n statusCode = result.statusCode;\n }\n if (result.headers) {\n loaderHeaders[id] = result.headers;\n }\n } else {\n loaderData[id] = result.data;\n // Error status codes always override success status codes, but if all\n // loaders are successful we take the deepest status code.\n if (result.statusCode && result.statusCode !== 200 && !foundError) {\n statusCode = result.statusCode;\n }\n if (result.headers) {\n loaderHeaders[id] = result.headers;\n }\n }\n }\n });\n\n // If we didn't consume the pending action error (i.e., all loaders\n // resolved), then consume it here. Also clear out any loaderData for the\n // throwing route\n if (pendingError !== undefined && pendingActionResult) {\n errors = { [pendingActionResult[0]]: pendingError };\n loaderData[pendingActionResult[0]] = undefined;\n }\n\n return {\n loaderData,\n errors,\n statusCode: statusCode || 200,\n loaderHeaders,\n };\n}\n\nfunction processLoaderData(\n state: RouterState,\n matches: AgnosticDataRouteMatch[],\n results: Record,\n pendingActionResult: PendingActionResult | undefined,\n revalidatingFetchers: RevalidatingFetcher[],\n fetcherResults: Record,\n activeDeferreds: Map\n): {\n loaderData: RouterState[\"loaderData\"];\n errors?: RouterState[\"errors\"];\n} {\n let { loaderData, errors } = processRouteLoaderData(\n matches,\n results,\n pendingActionResult,\n activeDeferreds,\n false // This method is only called client side so we always want to bubble\n );\n\n // Process results from our revalidating fetchers\n revalidatingFetchers.forEach((rf) => {\n let { key, match, controller } = rf;\n let result = fetcherResults[key];\n invariant(result, \"Did not find corresponding fetcher result\");\n\n // Process fetcher non-redirect errors\n if (controller && controller.signal.aborted) {\n // Nothing to do for aborted fetchers\n return;\n } else if (isErrorResult(result)) {\n let boundaryMatch = findNearestBoundary(state.matches, match?.route.id);\n if (!(errors && errors[boundaryMatch.route.id])) {\n errors = {\n ...errors,\n [boundaryMatch.route.id]: result.error,\n };\n }\n state.fetchers.delete(key);\n } else if (isRedirectResult(result)) {\n // Should never get here, redirects should get processed above, but we\n // keep this to type narrow to a success result in the else\n invariant(false, \"Unhandled fetcher revalidation redirect\");\n } else if (isDeferredResult(result)) {\n // Should never get here, deferred data should be awaited for fetchers\n // in resolveDeferredResults\n invariant(false, \"Unhandled fetcher deferred data\");\n } else {\n let doneFetcher = getDoneFetcher(result.data);\n state.fetchers.set(key, doneFetcher);\n }\n });\n\n return { loaderData, errors };\n}\n\nfunction mergeLoaderData(\n loaderData: RouteData,\n newLoaderData: RouteData,\n matches: AgnosticDataRouteMatch[],\n errors: RouteData | null | undefined\n): RouteData {\n let mergedLoaderData = { ...newLoaderData };\n for (let match of matches) {\n let id = match.route.id;\n if (newLoaderData.hasOwnProperty(id)) {\n if (newLoaderData[id] !== undefined) {\n mergedLoaderData[id] = newLoaderData[id];\n } else {\n // No-op - this is so we ignore existing data if we have a key in the\n // incoming object with an undefined value, which is how we unset a prior\n // loaderData if we encounter a loader error\n }\n } else if (loaderData[id] !== undefined && match.route.loader) {\n // Preserve existing keys not included in newLoaderData and where a loader\n // wasn't removed by HMR\n mergedLoaderData[id] = loaderData[id];\n }\n\n if (errors && errors.hasOwnProperty(id)) {\n // Don't keep any loader data below the boundary\n break;\n }\n }\n return mergedLoaderData;\n}\n\nfunction getActionDataForCommit(\n pendingActionResult: PendingActionResult | undefined\n) {\n if (!pendingActionResult) {\n return {};\n }\n return isErrorResult(pendingActionResult[1])\n ? {\n // Clear out prior actionData on errors\n actionData: {},\n }\n : {\n actionData: {\n [pendingActionResult[0]]: pendingActionResult[1].data,\n },\n };\n}\n\n// Find the nearest error boundary, looking upwards from the leaf route (or the\n// route specified by routeId) for the closest ancestor error boundary,\n// defaulting to the root match\nfunction findNearestBoundary(\n matches: AgnosticDataRouteMatch[],\n routeId?: string\n): AgnosticDataRouteMatch {\n let eligibleMatches = routeId\n ? matches.slice(0, matches.findIndex((m) => m.route.id === routeId) + 1)\n : [...matches];\n return (\n eligibleMatches.reverse().find((m) => m.route.hasErrorBoundary === true) ||\n matches[0]\n );\n}\n\nfunction getShortCircuitMatches(routes: AgnosticDataRouteObject[]): {\n matches: AgnosticDataRouteMatch[];\n route: AgnosticDataRouteObject;\n} {\n // Prefer a root layout route if present, otherwise shim in a route object\n let route =\n routes.length === 1\n ? routes[0]\n : routes.find((r) => r.index || !r.path || r.path === \"/\") || {\n id: `__shim-error-route__`,\n };\n\n return {\n matches: [\n {\n params: {},\n pathname: \"\",\n pathnameBase: \"\",\n route,\n },\n ],\n route,\n };\n}\n\nfunction getInternalRouterError(\n status: number,\n {\n pathname,\n routeId,\n method,\n type,\n message,\n }: {\n pathname?: string;\n routeId?: string;\n method?: string;\n type?: \"defer-action\" | \"invalid-body\";\n message?: string;\n } = {}\n) {\n let statusText = \"Unknown Server Error\";\n let errorMessage = \"Unknown @remix-run/router error\";\n\n if (status === 400) {\n statusText = \"Bad Request\";\n if (method && pathname && routeId) {\n errorMessage =\n `You made a ${method} request to \"${pathname}\" but ` +\n `did not provide a \\`loader\\` for route \"${routeId}\", ` +\n `so there is no way to handle the request.`;\n } else if (type === \"defer-action\") {\n errorMessage = \"defer() is not supported in actions\";\n } else if (type === \"invalid-body\") {\n errorMessage = \"Unable to encode submission body\";\n }\n } else if (status === 403) {\n statusText = \"Forbidden\";\n errorMessage = `Route \"${routeId}\" does not match URL \"${pathname}\"`;\n } else if (status === 404) {\n statusText = \"Not Found\";\n errorMessage = `No route matches URL \"${pathname}\"`;\n } else if (status === 405) {\n statusText = \"Method Not Allowed\";\n if (method && pathname && routeId) {\n errorMessage =\n `You made a ${method.toUpperCase()} request to \"${pathname}\" but ` +\n `did not provide an \\`action\\` for route \"${routeId}\", ` +\n `so there is no way to handle the request.`;\n } else if (method) {\n errorMessage = `Invalid request method \"${method.toUpperCase()}\"`;\n }\n }\n\n return new ErrorResponseImpl(\n status || 500,\n statusText,\n new Error(errorMessage),\n true\n );\n}\n\n// Find any returned redirect errors, starting from the lowest match\nfunction findRedirect(\n results: Record\n): { key: string; result: RedirectResult } | undefined {\n let entries = Object.entries(results);\n for (let i = entries.length - 1; i >= 0; i--) {\n let [key, result] = entries[i];\n if (isRedirectResult(result)) {\n return { key, result };\n }\n }\n}\n\nfunction stripHashFromPath(path: To) {\n let parsedPath = typeof path === \"string\" ? parsePath(path) : path;\n return createPath({ ...parsedPath, hash: \"\" });\n}\n\nfunction isHashChangeOnly(a: Location, b: Location): boolean {\n if (a.pathname !== b.pathname || a.search !== b.search) {\n return false;\n }\n\n if (a.hash === \"\") {\n // /page -> /page#hash\n return b.hash !== \"\";\n } else if (a.hash === b.hash) {\n // /page#hash -> /page#hash\n return true;\n } else if (b.hash !== \"\") {\n // /page#hash -> /page#other\n return true;\n }\n\n // If the hash is removed the browser will re-perform a request to the server\n // /page#hash -> /page\n return false;\n}\n\nfunction isPromise(val: unknown): val is Promise {\n return typeof val === \"object\" && val != null && \"then\" in val;\n}\n\nfunction isDataStrategyResult(result: unknown): result is DataStrategyResult {\n return (\n result != null &&\n typeof result === \"object\" &&\n \"type\" in result &&\n \"result\" in result &&\n (result.type === ResultType.data || result.type === ResultType.error)\n );\n}\n\nfunction isRedirectDataStrategyResultResult(result: DataStrategyResult) {\n return (\n isResponse(result.result) && redirectStatusCodes.has(result.result.status)\n );\n}\n\nfunction isDeferredResult(result: DataResult): result is DeferredResult {\n return result.type === ResultType.deferred;\n}\n\nfunction isErrorResult(result: DataResult): result is ErrorResult {\n return result.type === ResultType.error;\n}\n\nfunction isRedirectResult(result?: DataResult): result is RedirectResult {\n return (result && result.type) === ResultType.redirect;\n}\n\nexport function isDataWithResponseInit(\n value: any\n): value is DataWithResponseInit {\n return (\n typeof value === \"object\" &&\n value != null &&\n \"type\" in value &&\n \"data\" in value &&\n \"init\" in value &&\n value.type === \"DataWithResponseInit\"\n );\n}\n\nexport function isDeferredData(value: any): value is DeferredData {\n let deferred: DeferredData = value;\n return (\n deferred &&\n typeof deferred === \"object\" &&\n typeof deferred.data === \"object\" &&\n typeof deferred.subscribe === \"function\" &&\n typeof deferred.cancel === \"function\" &&\n typeof deferred.resolveData === \"function\"\n );\n}\n\nfunction isResponse(value: any): value is Response {\n return (\n value != null &&\n typeof value.status === \"number\" &&\n typeof value.statusText === \"string\" &&\n typeof value.headers === \"object\" &&\n typeof value.body !== \"undefined\"\n );\n}\n\nfunction isRedirectResponse(result: any): result is Response {\n if (!isResponse(result)) {\n return false;\n }\n\n let status = result.status;\n let location = result.headers.get(\"Location\");\n return status >= 300 && status <= 399 && location != null;\n}\n\nfunction isValidMethod(method: string): method is FormMethod | V7_FormMethod {\n return validRequestMethods.has(method.toLowerCase() as FormMethod);\n}\n\nfunction isMutationMethod(\n method: string\n): method is MutationFormMethod | V7_MutationFormMethod {\n return validMutationMethods.has(method.toLowerCase() as MutationFormMethod);\n}\n\nasync function resolveNavigationDeferredResults(\n matches: (AgnosticDataRouteMatch | null)[],\n results: Record,\n signal: AbortSignal,\n currentMatches: AgnosticDataRouteMatch[],\n currentLoaderData: RouteData\n) {\n let entries = Object.entries(results);\n for (let index = 0; index < entries.length; index++) {\n let [routeId, result] = entries[index];\n let match = matches.find((m) => m?.route.id === routeId);\n // If we don't have a match, then we can have a deferred result to do\n // anything with. This is for revalidating fetchers where the route was\n // removed during HMR\n if (!match) {\n continue;\n }\n\n let currentMatch = currentMatches.find(\n (m) => m.route.id === match!.route.id\n );\n let isRevalidatingLoader =\n currentMatch != null &&\n !isNewRouteInstance(currentMatch, match) &&\n (currentLoaderData && currentLoaderData[match.route.id]) !== undefined;\n\n if (isDeferredResult(result) && isRevalidatingLoader) {\n // Note: we do not have to touch activeDeferreds here since we race them\n // against the signal in resolveDeferredData and they'll get aborted\n // there if needed\n await resolveDeferredData(result, signal, false).then((result) => {\n if (result) {\n results[routeId] = result;\n }\n });\n }\n }\n}\n\nasync function resolveFetcherDeferredResults(\n matches: (AgnosticDataRouteMatch | null)[],\n results: Record,\n revalidatingFetchers: RevalidatingFetcher[]\n) {\n for (let index = 0; index < revalidatingFetchers.length; index++) {\n let { key, routeId, controller } = revalidatingFetchers[index];\n let result = results[key];\n let match = matches.find((m) => m?.route.id === routeId);\n // If we don't have a match, then we can have a deferred result to do\n // anything with. This is for revalidating fetchers where the route was\n // removed during HMR\n if (!match) {\n continue;\n }\n\n if (isDeferredResult(result)) {\n // Note: we do not have to touch activeDeferreds here since we race them\n // against the signal in resolveDeferredData and they'll get aborted\n // there if needed\n invariant(\n controller,\n \"Expected an AbortController for revalidating fetcher deferred result\"\n );\n await resolveDeferredData(result, controller.signal, true).then(\n (result) => {\n if (result) {\n results[key] = result;\n }\n }\n );\n }\n }\n}\n\nasync function resolveDeferredData(\n result: DeferredResult,\n signal: AbortSignal,\n unwrap = false\n): Promise {\n let aborted = await result.deferredData.resolveData(signal);\n if (aborted) {\n return;\n }\n\n if (unwrap) {\n try {\n return {\n type: ResultType.data,\n data: result.deferredData.unwrappedData,\n };\n } catch (e) {\n // Handle any TrackedPromise._error values encountered while unwrapping\n return {\n type: ResultType.error,\n error: e,\n };\n }\n }\n\n return {\n type: ResultType.data,\n data: result.deferredData.data,\n };\n}\n\nfunction hasNakedIndexQuery(search: string): boolean {\n return new URLSearchParams(search).getAll(\"index\").some((v) => v === \"\");\n}\n\nfunction getTargetMatch(\n matches: AgnosticDataRouteMatch[],\n location: Location | string\n) {\n let search =\n typeof location === \"string\" ? parsePath(location).search : location.search;\n if (\n matches[matches.length - 1].route.index &&\n hasNakedIndexQuery(search || \"\")\n ) {\n // Return the leaf index route when index is present\n return matches[matches.length - 1];\n }\n // Otherwise grab the deepest \"path contributing\" match (ignoring index and\n // pathless layout routes)\n let pathMatches = getPathContributingMatches(matches);\n return pathMatches[pathMatches.length - 1];\n}\n\nfunction getSubmissionFromNavigation(\n navigation: Navigation\n): Submission | undefined {\n let { formMethod, formAction, formEncType, text, formData, json } =\n navigation;\n if (!formMethod || !formAction || !formEncType) {\n return;\n }\n\n if (text != null) {\n return {\n formMethod,\n formAction,\n formEncType,\n formData: undefined,\n json: undefined,\n text,\n };\n } else if (formData != null) {\n return {\n formMethod,\n formAction,\n formEncType,\n formData,\n json: undefined,\n text: undefined,\n };\n } else if (json !== undefined) {\n return {\n formMethod,\n formAction,\n formEncType,\n formData: undefined,\n json,\n text: undefined,\n };\n }\n}\n\nfunction getLoadingNavigation(\n location: Location,\n submission?: Submission\n): NavigationStates[\"Loading\"] {\n if (submission) {\n let navigation: NavigationStates[\"Loading\"] = {\n state: \"loading\",\n location,\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n };\n return navigation;\n } else {\n let navigation: NavigationStates[\"Loading\"] = {\n state: \"loading\",\n location,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n };\n return navigation;\n }\n}\n\nfunction getSubmittingNavigation(\n location: Location,\n submission: Submission\n): NavigationStates[\"Submitting\"] {\n let navigation: NavigationStates[\"Submitting\"] = {\n state: \"submitting\",\n location,\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n };\n return navigation;\n}\n\nfunction getLoadingFetcher(\n submission?: Submission,\n data?: Fetcher[\"data\"]\n): FetcherStates[\"Loading\"] {\n if (submission) {\n let fetcher: FetcherStates[\"Loading\"] = {\n state: \"loading\",\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n data,\n };\n return fetcher;\n } else {\n let fetcher: FetcherStates[\"Loading\"] = {\n state: \"loading\",\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n data,\n };\n return fetcher;\n }\n}\n\nfunction getSubmittingFetcher(\n submission: Submission,\n existingFetcher?: Fetcher\n): FetcherStates[\"Submitting\"] {\n let fetcher: FetcherStates[\"Submitting\"] = {\n state: \"submitting\",\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n data: existingFetcher ? existingFetcher.data : undefined,\n };\n return fetcher;\n}\n\nfunction getDoneFetcher(data: Fetcher[\"data\"]): FetcherStates[\"Idle\"] {\n let fetcher: FetcherStates[\"Idle\"] = {\n state: \"idle\",\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n data,\n };\n return fetcher;\n}\n\nfunction restoreAppliedTransitions(\n _window: Window,\n transitions: Map>\n) {\n try {\n let sessionPositions = _window.sessionStorage.getItem(\n TRANSITIONS_STORAGE_KEY\n );\n if (sessionPositions) {\n let json = JSON.parse(sessionPositions);\n for (let [k, v] of Object.entries(json || {})) {\n if (v && Array.isArray(v)) {\n transitions.set(k, new Set(v || []));\n }\n }\n }\n } catch (e) {\n // no-op, use default empty object\n }\n}\n\nfunction persistAppliedTransitions(\n _window: Window,\n transitions: Map>\n) {\n if (transitions.size > 0) {\n let json: Record = {};\n for (let [k, v] of transitions) {\n json[k] = [...v];\n }\n try {\n _window.sessionStorage.setItem(\n TRANSITIONS_STORAGE_KEY,\n JSON.stringify(json)\n );\n } catch (error) {\n warning(\n false,\n `Failed to save applied view transitions in sessionStorage (${error}).`\n );\n }\n }\n}\n//#endregion\n"],"names":["Action","PopStateEventType","createMemoryHistory","options","initialEntries","initialIndex","v5Compat","entries","map","entry","index","createMemoryLocation","state","undefined","clampIndex","length","action","Pop","listener","n","Math","min","max","getCurrentLocation","to","key","location","createLocation","pathname","warning","charAt","JSON","stringify","createHref","createPath","history","createURL","URL","encodeLocation","path","parsePath","search","hash","push","Push","nextLocation","splice","delta","replace","Replace","go","nextIndex","listen","fn","createBrowserHistory","createBrowserLocation","window","globalHistory","usr","createBrowserHref","getUrlBasedHistory","createHashHistory","createHashLocation","substr","startsWith","createHashHref","base","document","querySelector","href","getAttribute","url","hashIndex","indexOf","slice","validateHashLocation","invariant","value","message","Error","cond","console","warn","e","createKey","random","toString","getHistoryState","idx","current","_extends","_ref","parsedPath","searchIndex","getLocation","validateLocation","defaultView","getIndex","replaceState","handlePop","historyState","pushState","error","DOMException","name","assign","origin","addEventListener","removeEventListener","ResultType","immutableRouteKeys","Set","isIndexRoute","route","convertRoutesToDataRoutes","routes","mapRouteProperties","parentPath","manifest","treePath","String","id","join","children","indexRoute","pathOrLayoutRoute","matchRoutes","locationArg","basename","matchRoutesImpl","allowPartial","stripBasename","branches","flattenRoutes","rankRouteBranches","matches","decoded","decodePath","i","matchRouteBranch","convertRouteMatchToUiMatch","match","loaderData","params","data","handle","parentsMeta","flattenRoute","relativePath","meta","caseSensitive","childrenIndex","joinPaths","routesMeta","concat","score","computeScore","forEach","_route$path","includes","exploded","explodeOptionalSegments","segments","split","first","rest","isOptional","endsWith","required","restExploded","result","subpath","sort","a","b","compareIndexes","paramRe","dynamicSegmentValue","indexRouteValue","emptySegmentValue","staticSegmentValue","splatPenalty","isSplat","s","initialScore","some","filter","reduce","segment","test","siblings","every","branch","matchedParams","matchedPathname","end","remainingPathname","matchPath","Object","pathnameBase","normalizePathname","generatePath","originalPath","prefix","p","array","isLastSegment","star","keyMatch","optional","param","pattern","matcher","compiledParams","compilePath","captureGroups","memo","paramName","splatValue","regexpSource","_","RegExp","v","decodeURIComponent","toLowerCase","startIndex","nextChar","resolvePath","fromPathname","toPathname","removeDoubleSlashes","resolvePathname","substring","normalizeSearch","normalizeHash","relativeSegments","pop","getInvalidPathError","char","field","dest","getPathContributingMatches","getResolveToMatches","v7_relativeSplatPath","pathMatches","resolveTo","toArg","routePathnames","locationPathname","isPathRelative","isEmptyPath","from","routePathnameIndex","toSegments","shift","hasExplicitTrailingSlash","hasCurrentTrailingSlash","getToPathname","paths","json","init","responseInit","status","headers","Headers","has","set","Response","DataWithResponseInit","constructor","type","AbortedDeferredError","DeferredData","pendingKeysSet","subscribers","deferredKeys","Array","isArray","reject","abortPromise","Promise","r","controller","AbortController","onAbort","unlistenAbortSignal","signal","acc","_ref2","trackPromise","done","add","promise","race","then","onSettle","catch","defineProperty","get","aborted","delete","undefinedError","emit","settledKey","subscriber","subscribe","cancel","abort","k","resolveData","resolve","size","unwrappedData","_ref3","unwrapTrackedPromise","pendingKeys","isTrackedPromise","_tracked","_error","_data","defer","redirect","redirectDocument","response","ErrorResponseImpl","statusText","internal","isRouteErrorResponse","validMutationMethodsArr","validMutationMethods","validRequestMethodsArr","validRequestMethods","redirectStatusCodes","redirectPreserveMethodStatusCodes","IDLE_NAVIGATION","formMethod","formAction","formEncType","formData","text","IDLE_FETCHER","IDLE_BLOCKER","proceed","reset","ABSOLUTE_URL_REGEX","defaultMapRouteProperties","hasErrorBoundary","Boolean","TRANSITIONS_STORAGE_KEY","createRouter","routerWindow","isBrowser","createElement","isServer","detectErrorBoundary","dataRoutes","inFlightDataRoutes","dataStrategyImpl","dataStrategy","defaultDataStrategy","patchRoutesOnNavigationImpl","patchRoutesOnNavigation","future","v7_fetcherPersist","v7_normalizeFormMethod","v7_partialHydration","v7_prependBasename","v7_skipActionErrorRevalidation","unlistenHistory","savedScrollPositions","getScrollRestorationKey","getScrollPosition","initialScrollRestored","hydrationData","initialMatches","initialMatchesIsFOW","initialErrors","getInternalRouterError","getShortCircuitMatches","fogOfWar","checkFogOfWar","active","initialized","m","lazy","loader","errors","findIndex","shouldLoadRouteOnHydration","router","historyAction","navigation","restoreScrollPosition","preventScrollReset","revalidation","actionData","fetchers","Map","blockers","pendingAction","HistoryAction","pendingPreventScrollReset","pendingNavigationController","pendingViewTransitionEnabled","appliedViewTransitions","removePageHideEventListener","isUninterruptedRevalidation","isRevalidationRequired","cancelledDeferredRoutes","cancelledFetcherLoads","fetchControllers","incrementingLoadId","pendingNavigationLoadId","fetchReloadIds","fetchRedirectIds","fetchLoadMatches","activeFetchers","deletedFetchers","activeDeferreds","blockerFunctions","unblockBlockerHistoryUpdate","initialize","blockerKey","shouldBlockNavigation","currentLocation","nextHistoryUpdatePromise","updateBlocker","updateState","startNavigation","restoreAppliedTransitions","_saveAppliedTransitions","persistAppliedTransitions","initialHydration","dispose","clear","deleteFetcher","deleteBlocker","newState","opts","completedFetchers","deletedFetchersKeys","fetcher","viewTransitionOpts","flushSync","completeNavigation","_temp","_location$state","_location$state2","isActionReload","isMutationMethod","_isRedirect","keys","mergeLoaderData","priorPaths","toPaths","getSavedScrollPosition","navigate","normalizedPath","normalizeTo","fromRouteId","relative","submission","normalizeNavigateOptions","userReplace","pendingError","enableViewTransition","viewTransition","revalidate","interruptActiveLoads","startUninterruptedRevalidation","overrideNavigation","saveScrollPosition","routesToUse","loadingNavigation","isHashChangeOnly","notFoundMatches","handleNavigational404","request","createClientSideRequest","pendingActionResult","findNearestBoundary","actionResult","handleAction","shortCircuited","routeId","isErrorResult","getLoadingNavigation","updatedMatches","handleLoaders","fetcherSubmission","getActionDataForCommit","isFogOfWar","getSubmittingNavigation","discoverResult","discoverRoutes","boundaryId","partialMatches","actionMatch","getTargetMatch","method","results","callDataStrategy","isRedirectResult","normalizeRedirectLocation","startRedirectNavigation","isDeferredResult","boundaryMatch","activeSubmission","getSubmissionFromNavigation","shouldUpdateNavigationState","getUpdatedActionData","matchesToLoad","revalidatingFetchers","getMatchesToLoad","cancelActiveDeferreds","updatedFetchers","markFetchRedirectsDone","updates","getUpdatedRevalidatingFetchers","rf","abortFetcher","abortPendingFetchRevalidations","f","loaderResults","fetcherResults","callLoadersAndMaybeResolveData","findRedirect","processLoaderData","deferredData","didAbortFetchLoads","abortStaleFetchLoads","shouldUpdateFetchers","revalidatingFetcher","getLoadingFetcher","fetch","setFetcherError","handleFetcherAction","handleFetcherLoader","requestMatches","detectAndHandle405Error","existingFetcher","updateFetcherState","getSubmittingFetcher","abortController","fetchRequest","originatingLoadId","actionResults","getDoneFetcher","revalidationRequest","loadId","loadFetcher","staleKey","doneFetcher","resolveDeferredData","isNavigation","_temp2","redirectLocation","isDocumentReload","redirectHistoryAction","fetcherKey","dataResults","callDataStrategyImpl","isRedirectDataStrategyResultResult","normalizeRelativeRoutingRedirectResponse","convertDataStrategyResultToDataResult","fetchersToLoad","currentMatches","loaderResultsPromise","fetcherResultsPromise","all","resolveNavigationDeferredResults","resolveFetcherDeferredResults","getFetcher","deleteFetcherAndUpdateState","count","markFetchersDone","doneKeys","landedId","yeetedKeys","getBlocker","blocker","newBlocker","blockerFunction","predicate","cancelledRouteIds","dfd","enableScrollRestoration","positions","getPosition","getKey","y","getScrollKey","fogMatches","isNonHMR","localManifest","patch","patchRoutesImpl","newMatches","newPartialMatches","_internalSetRoutes","newRoutes","patchRoutes","_internalFetchControllers","_internalActiveDeferreds","UNSAFE_DEFERRED_SYMBOL","Symbol","createStaticHandler","v7_throwAbortReason","query","_temp3","requestContext","skipLoaderErrorBubbling","isValidMethod","methodNotAllowedMatches","statusCode","loaderHeaders","actionHeaders","queryImpl","isResponse","queryRoute","_temp4","find","values","_result$activeDeferre","routeMatch","submit","loadRouteData","isDataStrategyResult","isRedirectResponse","isRouteRequest","throwStaticHandlerAbortedError","Location","loaderRequest","Request","context","getLoaderMatchesUntilBoundary","processRouteLoaderData","executedLoaders","fromEntries","getStaticContextFromError","newContext","_deepestRenderedBoundaryId","reason","isSubmissionNavigation","body","prependBasename","contextualMatches","activeRouteMatch","nakedIndex","hasNakedIndexQuery","URLSearchParams","indexValues","getAll","append","qs","normalizeFormMethod","isFetcher","getInvalidBodyError","rawFormMethod","toUpperCase","stripHashFromPath","FormData","parse","searchParams","convertFormDataToSearchParams","convertSearchParamsToFormData","includeBoundary","skipActionErrorRevalidation","currentUrl","nextUrl","boundaryMatches","actionStatus","shouldSkipRevalidation","navigationMatches","isNewLoader","currentRouteMatch","nextRouteMatch","shouldRevalidateLoader","currentParams","nextParams","defaultShouldRevalidate","isNewRouteInstance","fetcherMatches","fetcherMatch","shouldRevalidate","hasData","hasError","hydrate","currentLoaderData","currentMatch","isNew","isMissingData","currentPath","loaderMatch","arg","routeChoice","_childrenToPatch","childrenToPatch","uniqueChildren","newRoute","existingRoute","isSameRoute","aChild","_existingRoute$childr","bChild","loadLazyRouteModule","lazyRoute","routeToUpdate","routeUpdates","lazyRouteProperty","staticRouteValue","isPropertyStaticallyDefined","_ref4","shouldLoad","loadRouteDefinitionsPromises","dsMatches","loadRoutePromise","handlerOverride","callLoaderOrAction","staticContext","onReject","runHandler","handler","actualHandler","ctx","handlerPromise","val","handlerError","dataStrategyResult","contentType","isDataWithResponseInit","_result$init3","_result$init4","_result$init","_result$init2","isDeferredData","_result$init5","_result$init6","deferred","_result$init7","_result$init8","trimmedMatches","historyInstance","invalidProtocols","normalizedLocation","protocol","isSameBasename","foundError","newLoaderData","mergedLoaderData","hasOwnProperty","eligibleMatches","reverse","_temp5","errorMessage","isRevalidatingLoader","unwrap","_window","transitions","sessionPositions","sessionStorage","getItem","setItem"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAAA;AACA;AACA;;AAEA;AACA;AACA;AACYA,IAAAA,MAAM,0BAANA,MAAM,EAAA;AAChB;AACF;AACA;AACA;AACA;AACA;AACA;EAPYA,MAAM,CAAA,KAAA,CAAA,GAAA,KAAA,CAAA;AAUhB;AACF;AACA;AACA;AACA;EAdYA,MAAM,CAAA,MAAA,CAAA,GAAA,MAAA,CAAA;AAiBhB;AACF;AACA;AACA;EApBYA,MAAM,CAAA,SAAA,CAAA,GAAA,SAAA,CAAA;AAAA,EAAA,OAANA,MAAM,CAAA;AAAA,CAAA,CAAA,EAAA,EAAA;;AAwBlB;AACA;AACA;;AAkBA;AACA;;AAEA;AACA;AACA;AACA;;AAgBA;AACA;AACA;;AAkBA;AACA;AACA;;AAKA;AACA;AACA;AACA;AACA;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAgFA,MAAMC,iBAAiB,GAAG,UAAU,CAAA;AACpC;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AASA;AACA;AACA;AACA;AACA;;AAQA;AACA;AACA;AACA;AACO,SAASC,mBAAmBA,CACjCC,OAA6B,EACd;AAAA,EAAA,IADfA,OAA6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C5e,GAAG,CAAC0C,CAAC,EAAE,IAAIrM,GAAG,CAAC+G,CAAC,IAAI,EAAE,CAAC,CAAC,CAAA;AACtC,SAAA;AACF,OAAA;AACF,KAAA;GACD,CAAC,OAAO3I,CAAC,EAAE;AACV;AAAA,GAAA;AAEJ,CAAA;AAEA,SAAS4V,yBAAyBA,CAChCsU,OAAe,EACfC,WAAqC,EACrC;AACA,EAAA,IAAIA,WAAW,CAAC/b,IAAI,GAAG,CAAC,EAAE;IACxB,IAAIpD,IAA8B,GAAG,EAAE,CAAA;IACvC,KAAK,IAAI,CAACiD,CAAC,EAAEtF,CAAC,CAAC,IAAIwhB,WAAW,EAAE;AAC9Bnf,MAAAA,IAAI,CAACiD,CAAC,CAAC,GAAG,CAAC,GAAGtF,CAAC,CAAC,CAAA;AAClB,KAAA;IACA,IAAI;AACFuhB,MAAAA,OAAO,CAACG,cAAc,CAACE,OAAO,CAC5B9Z,uBAAuB,EACvB7T,IAAI,CAACC,SAAS,CAACmO,IAAI,CACrB,CAAC,CAAA;KACF,CAAC,OAAO7J,KAAK,EAAE;AACdzE,MAAAA,OAAO,CACL,KAAK,EACyDyE,6DAAAA,GAAAA,KAAK,OACrE,CAAC,CAAA;AACH,KAAA;AACF,GAAA;AACF,CAAA;AACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} apps/frontend/node_modules/@remix-run/router/README.md:38:Internally, the Router represents the state in an object of the following format, which is available through `router.state`. You can also register a subscriber of the signature `(state: RouterState) => void` to execute when the state updates via `router.subscribe()`; apps/frontend/node_modules/@remix-run/router/router.ts:124: subscribe(fn: RouterSubscriber): () => void; apps/frontend/node_modules/@remix-run/router/router.ts:817: let subscribers = new Set(); apps/frontend/node_modules/@remix-run/router/router.ts:1123: subscribers.clear(); apps/frontend/node_modules/@remix-run/router/router.ts:1130: function subscribe(fn: RouterSubscriber) { apps/frontend/node_modules/@remix-run/router/router.ts:1131: subscribers.add(fn); apps/frontend/node_modules/@remix-run/router/router.ts:1132: return () => subscribers.delete(fn); apps/frontend/node_modules/@remix-run/router/router.ts:1177: // removing and adding a new subscriber due to the useCallback dependencies, apps/frontend/node_modules/@remix-run/router/router.ts:1178: // we don't get ourselves into a loop calling the new subscriber immediately apps/frontend/node_modules/@remix-run/router/router.ts:1179: [...subscribers].forEach((subscriber) => apps/frontend/node_modules/@remix-run/router/router.ts:1180: subscriber(state, { apps/frontend/node_modules/@remix-run/router/router.ts:2063: // Wire up subscribers to update loaderData as promises settle apps/frontend/node_modules/@remix-run/router/router.ts:2065: deferredData.subscribe((aborted) => { apps/frontend/node_modules/@remix-run/router/router.ts:3163: // we rely on the subscribers to do that so our tests can assert proper apps/frontend/node_modules/@remix-run/router/router.ts:3415: subscribe, apps/frontend/node_modules/@remix-run/router/router.ts:5676: typeof deferred.subscribe === "function" && apps/frontend/node_modules/@remix-run/router/utils.ts:1436: private subscribers: Set<(aborted: boolean, settledKey?: string) => void> = apps/frontend/node_modules/@remix-run/router/utils.ts:1547: this.subscribers.forEach((subscriber) => subscriber(aborted, settledKey)); apps/frontend/node_modules/@remix-run/router/utils.ts:1550: subscribe(fn: (aborted: boolean, settledKey?: string) => void) { apps/frontend/node_modules/@remix-run/router/utils.ts:1551: this.subscribers.add(fn); apps/frontend/node_modules/@remix-run/router/utils.ts:1552: return () => this.subscribers.delete(fn); apps/frontend/node_modules/@remix-run/router/utils.ts:1567: this.subscribe((aborted) => { apps/frontend/node_modules/react/umd/react.development.js:1664: function useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) { apps/frontend/node_modules/react/umd/react.development.js:1666: return dispatcher.useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); apps/frontend/node_modules/react/cjs/react.development.js:1674:function useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) { apps/frontend/node_modules/react/cjs/react.development.js:1676: return dispatcher.useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); apps/frontend/node_modules/react-router-dom/server.js:246: subscribe() { apps/frontend/node_modules/react-router-dom/server.js:247: throw msg("subscribe"); apps/frontend/node_modules/react-router-dom/server.mjs:223: subscribe() { apps/frontend/node_modules/react-router-dom/server.mjs:224: throw msg("subscribe"); apps/frontend/node_modules/react-router-dom/dist/server.js:246: subscribe() { apps/frontend/node_modules/react-router-dom/dist/server.js:247: throw msg("subscribe"); apps/frontend/node_modules/react-router-dom/dist/server.mjs:223: subscribe() { apps/frontend/node_modules/react-router-dom/dist/server.mjs:224: throw msg("subscribe"); apps/frontend/node_modules/react-router-dom/dist/umd/react-router-dom.production.min.js:11:!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react"),require("react-dom"),require("react-router"),require("@remix-run/router")):"function"==typeof define&&define.amd?define(["exports","react","react-dom","react-router","@remix-run/router"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).ReactRouterDOM={},e.React,e.ReactDOM,e.ReactRouter,e.RemixRouter)}(this,function(e,t,n,r,o){"use strict";function a(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach(function(n){if("default"!==n){var r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:function(){return e[n]}})}}),t.default=e,Object.freeze(t)}var i=a(t),u=a(n);function s(){return s=Object.assign?Object.assign.bind():function(e){for(var t=1;t{let r=e[n];return t.concat(Array.isArray(r)?r.map(e=>[n,e]):[[n,r]])},[]))}let p=null;const v=new Set(["application/x-www-form-urlencoded","multipart/form-data","text/plain"]);function h(e){return null==e||v.has(e)?e:null}function g(e,t){let n,r,a,i,u;if(d(s=e)&&"form"===s.tagName.toLowerCase()){let u=e.getAttribute("action");r=u?o.stripBasename(u,t):null,n=e.getAttribute("method")||l,a=h(e.getAttribute("enctype"))||f,i=new FormData(e)}else if(function(e){return d(e)&&"button"===e.tagName.toLowerCase()}(e)||function(e){return d(e)&&"input"===e.tagName.toLowerCase()}(e)&&("submit"===e.type||"image"===e.type)){let u=e.form;if(null==u)throw new Error('Cannot submit a