@eloquentai/chat-sdk 0.33.13-dev → 0.33.14-dev
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/components/chat/chat.d.ts +22 -0
- package/dist/components/chat/{chat.hook.d.ts → hooks/use-chat.d.ts} +3 -3
- package/dist/components/chat/{interface-props.hook.d.ts → hooks/use-interface-props.d.ts} +2 -2
- package/dist/components/chat/{message-events.hook.d.ts → hooks/use-message-events.d.ts} +2 -2
- package/dist/components/chat/{persistence.hook.d.ts → hooks/use-persistence.d.ts} +1 -1
- package/dist/components/chat/{realtime-socket.hook.d.ts → hooks/use-realtime-socket.d.ts} +3 -3
- package/dist/components/chat/{sdk-initialization.hook.d.ts → hooks/use-sdk-initialization.d.ts} +2 -2
- package/dist/components/chat/index.d.ts +1 -22
- package/dist/components/chat/message-mapping.d.ts +17 -0
- package/dist/components/chat-interface/chat-interface.d.ts +2 -0
- package/dist/components/chat-interface/context.d.ts +1 -1
- package/dist/components/chat-interface/index.d.ts +2 -57
- package/dist/components/chat-interface/message-bubble/message-action-buttons.d.ts +6 -0
- package/dist/components/chat-interface/message-bubble/message-animation-state.d.ts +2 -0
- package/dist/components/chat-interface/message-bubble/message-bubble-item.d.ts +7 -0
- package/dist/components/{chat-message-bubble.d.ts → chat-interface/message-bubble/message-bubble.d.ts} +1 -1
- package/dist/components/chat-interface/types.d.ts +56 -0
- package/dist/components/{render-chat.d.ts → embed/render-chat.d.ts} +1 -1
- package/dist/components/index.d.ts +2 -2
- package/dist/contexts/{agent-cognition-context-definition.d.ts → agent-cognition/agent-cognition-context.d.ts} +1 -1
- package/dist/contexts/{error-handling.utils.d.ts → error-handling/error-context.d.ts} +1 -1
- package/dist/contexts/{constants.d.ts → error-handling/error-messages.d.ts} +1 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.mjs +280 -256
- package/dist/index.mjs.map +1 -1
- package/dist/lib/cookies.d.ts +13 -0
- package/dist/lib/utils.d.ts +0 -20
- package/dist/lib/wrap-promise.d.ts +7 -0
- package/dist/{skeleton-XUmC-tbr.js → skeleton-CjGZA_5X.js} +1570 -1584
- package/dist/skeleton-CjGZA_5X.js.map +1 -0
- package/dist/ui.d.ts +3 -3
- package/dist/ui.mjs +1 -1
- package/package.json +1 -1
- package/dist/contexts/utils.d.ts +0 -2
- package/dist/skeleton-XUmC-tbr.js.map +0 -1
- /package/dist/components/chat/{keyboard-inset.hook.d.ts → hooks/use-keyboard-inset.d.ts} +0 -0
- /package/dist/components/chat/{scroll-lock.hook.d.ts → hooks/use-scroll-lock.d.ts} +0 -0
- /package/dist/components/chat/{ui-initialization.hook.d.ts → hooks/use-ui-initialization.d.ts} +0 -0
- /package/dist/components/chat/{user-identity.hook.d.ts → hooks/use-user-identity.d.ts} +0 -0
- /package/dist/components/{chat-rating-bubble.d.ts → chat-interface/rating-message-bubble.d.ts} +0 -0
- /package/dist/components/{chat-bubble.d.ts → embed/chat-bubble.d.ts} +0 -0
- /package/dist/components/{iframe.d.ts → embed/iframe.d.ts} +0 -0
- /package/dist/components/{portal.d.ts → embed/portal.d.ts} +0 -0
- /package/dist/components/{chat → embed}/proactive-message.d.ts +0 -0
- /package/dist/contexts/{agent-cognition.context.d.ts → agent-cognition/agent-cognition-provider.d.ts} +0 -0
- /package/dist/{hooks → contexts/agent-cognition}/use-agent-cognition-context.d.ts +0 -0
- /package/dist/{hooks → contexts/agent-cognition}/use-agent-cognition.d.ts +0 -0
- /package/dist/contexts/{error-handling.context.d.ts → error-handling/error-provider.d.ts} +0 -0
- /package/dist/hooks/{useFetch.d.ts → use-fetch.d.ts} +0 -0
- /package/dist/{type.d.ts → types/message.d.ts} +0 -0
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","sources":["../src/instrumentation.ts","../src/components/chat-bubble.tsx","../src/components/iframe.tsx","../src/components/portal.tsx","../src/components/chat/proactive-message.tsx","../src/components/chat/interface-props.hook.ts","../src/hooks/use-latest-ref.ts","../src/lib/http.ts","../src/lib/url-params.ts","../src/components/chat/persistence.hook.ts","../src/lib/appsync-events-client.ts","../node_modules/zod/v4/core/core.js","../node_modules/zod/v4/core/util.js","../node_modules/zod/v4/core/errors.js","../node_modules/zod/v4/core/parse.js","../node_modules/zod/v4/core/regexes.js","../node_modules/zod/v4/core/versions.js","../node_modules/zod/v4/core/schemas.js","../node_modules/zod/v4/core/api.js","../node_modules/zod/v4/mini/schemas.js","../src/components/chat/validations.ts","../src/components/chat/realtime-socket.hook.ts","../src/components/chat/message-events.hook.ts","../src/lib/config.ts","../src/lib/eloquent-ai-api-client.ts","../src/lib/retry.ts","../src/hooks/useFetch.ts","../src/components/chat/user-identity.hook.ts","../src/components/chat/sdk-initialization.hook.ts","../src/components/chat/ui-initialization.hook.ts","../src/components/chat/chat.hook.ts","../src/components/chat/keyboard-inset.hook.ts","../src/components/chat/scroll-lock.hook.ts","../src/hooks/use-agent-cognition.ts","../src/contexts/agent-cognition.context.tsx","../src/contexts/error-handling.context.tsx","../src/components/chat/index.tsx","../src/components/render-chat.tsx"],"sourcesContent":["// Only initialize Sentry on the client side\nif (typeof window !== \"undefined\") {\n // Transform Vite environment values to Sentry format\n // Access import.meta.env only on the client side to avoid SSR issues\n const viteEnv = import.meta.env.VITE_ENVIRONMENT as string | undefined;\n const environment = viteEnv === \"prod\" ? \"production\" : \"development\";\n const isLocal = viteEnv === \"local\";\n\n // Dynamically import Sentry to avoid SSR issues. Destructure only `init`:\n // holding the whole namespace would keep every barrel export (replay,\n // feedback, canvas integrations — hundreds of KB) alive in the bundle.\n import(\"@sentry/react\").then(({ init }) => {\n init({\n dsn: import.meta.env.VITE_SENTRY_DSN,\n environment,\n sendDefaultPii: false,\n debug: false,\n enabled: !isLocal,\n beforeSend(event) {\n const sensitiveHeaders = new Set([\n \"authorization\",\n \"cookie\",\n \"x-api-key\",\n \"x-auth-token\",\n ]);\n const headers = event.request?.headers as\n | Record<string, string>\n | undefined;\n if (headers) {\n for (const key of Object.keys(headers)) {\n if (sensitiveHeaders.has(key.toLowerCase())) {\n headers[key] = \"[Filtered]\";\n }\n }\n }\n if (event.request) {\n event.request.data = \"[Filtered]\";\n }\n return event;\n },\n });\n });\n}\n","\"use client\";\n\nimport { cn } from \"@/lib/utils\";\n\nimport { Logo } from \"@/components/logo\";\n\nexport function ChatBubble({\n toggleBubble,\n isDarkMode = false,\n}: {\n isOpen: boolean;\n toggleBubble: () => void;\n /** Renders in its own iframe (no `.dark` ancestor), so the mode arrives as a prop. */\n isDarkMode?: boolean;\n}) {\n const bubbleBackground = isDarkMode ? \"#fff\" : \"#000\";\n const logoForeground = isDarkMode ? \"#000000\" : \"#ffffff\";\n\n return (\n <div className=\"eloq:absolute eloq:inset-0 eloq:m-auto eloq:flex eloq:items-center eloq:justify-center eloq:overflow-hidden\">\n <div\n className={cn(\n \"eloq:chat-bubble eloq:relative eloq:flex eloq:items-center eloq:justify-center eloq:w-12 eloq:h-12 eloq:rounded-full eloq:cursor-pointer\",\n // Inverted in dark mode: a black launcher disappears on dark pages.\n isDarkMode\n ? \"eloq:bg-[#fff] eloq:text-[#000]\"\n : \"eloq:bg-[#000] eloq:text-[#fff]\",\n )}\n onClick={toggleBubble}\n >\n <div className=\"eloq:absolute eloq:inset-0 eloq:flex eloq:justify-center eloq:items-center eloq:m-auto\">\n <Logo bgColor={bubbleBackground} fgColor={logoForeground} />\n </div>\n </div>\n </div>\n );\n}\n","import { HTMLAttributes, PropsWithChildren, ReactNode, useState } from \"react\";\nimport { createPortal } from \"react-dom\";\n\ntype IframeProps = PropsWithChildren<HTMLAttributes<HTMLIFrameElement>> & {\n head: ReactNode;\n};\n\nexport function Iframe({ children, head, ...props }: IframeProps) {\n const [contentRef, setContentRef] = useState<HTMLIFrameElement | null>(null);\n const headNode = contentRef?.contentWindow?.document?.head;\n const bodyNode = contentRef?.contentWindow?.document?.body;\n return (\n <iframe {...props} ref={setContentRef}>\n {headNode && createPortal(head, headNode)}\n {bodyNode && createPortal(children, bodyNode)}\n </iframe>\n );\n}\n","\"use client\";\n\nimport type { ReactNode } from \"react\";\nimport { createPortal } from \"react-dom\";\n\ninterface PortalProps {\n children: ReactNode;\n container: HTMLElement;\n}\n\nexport function Portal({ children, container }: PortalProps) {\n return createPortal(children, container);\n}\n","\"use client\";\n\nimport { useEffect, useState } from \"react\";\nimport { X } from \"lucide-react\";\n\nimport { getContrastingTextColor } from \"@/lib/color-contrast\";\nimport { cn } from \"@/lib/utils\";\nimport { useTheme } from \"@/contexts/theme.context\";\n\nexport interface ProactiveMessageProps {\n message: string;\n isVisible: boolean;\n onDismiss: () => void;\n onMessageClick?: () => void;\n autoHideDelay?: number;\n}\n\nexport function ProactiveMessage({\n message,\n isVisible,\n onDismiss,\n onMessageClick,\n autoHideDelay,\n}: ProactiveMessageProps) {\n const [shouldRender, setShouldRender] = useState(false);\n const [animationState, setAnimationState] = useState<\n \"entering\" | \"visible\" | \"exiting\"\n >(\"entering\");\n const theme = useTheme();\n\n useEffect(() => {\n if (isVisible) {\n setShouldRender(true);\n setAnimationState(\"entering\");\n\n // Start entrance animation\n const enterTimer = setTimeout(() => {\n setAnimationState(\"visible\");\n }, 50);\n\n const hideTimer = setTimeout(() => {\n setAnimationState(\"exiting\");\n // Start exit animation\n setTimeout(() => {\n onDismiss();\n }, 300);\n }, autoHideDelay);\n\n return () => {\n clearTimeout(enterTimer);\n clearTimeout(hideTimer);\n };\n } else {\n setAnimationState(\"exiting\");\n // Delay hiding to allow for exit animation\n const timer = setTimeout(() => {\n setShouldRender(false);\n setAnimationState(\"entering\"); // Reset for next time\n }, 300);\n\n return () => clearTimeout(timer);\n }\n }, [isVisible, onDismiss, autoHideDelay]);\n\n if (!shouldRender) {\n return null;\n }\n\n return (\n <div\n className={cn(\n // right-16 leaves a ~7px gap between the tail tip and the launcher\n // circle's edge — the tail points at it without sliding underneath.\n \"eloq:absolute eloq:right-16 eloq:bottom-0 eloq:max-w-xs eloq:transform eloq:transition-all eloq:duration-500 eloq:ease-out\",\n animationState === \"entering\" &&\n \"eloq:translate-x-8 eloq:opacity-0 eloq:scale-95\",\n animationState === \"visible\" &&\n \"eloq:translate-x-0 eloq:opacity-100 eloq:scale-100\",\n animationState === \"exiting\" &&\n \"eloq:translate-x-8 eloq:opacity-0 eloq:scale-95\",\n )}\n >\n {/* drop-shadow (not box-shadow) so the shadow follows the combined\n silhouette of the bubble AND its tail as one continuous shape. */}\n <div className=\"eloq:relative eloq:drop-shadow-lg eloq:hover:drop-shadow-xl eloq:transition-all eloq:duration-300\">\n {/* Message bubble */}\n <div\n className=\"eloq:relative eloq:rounded-lg eloq:border eloq:p-3 eloq:cursor-pointer\"\n style={{\n backgroundColor: theme.botBubbleColor,\n }}\n onClick={onMessageClick}\n >\n {/* Tail: the original curved wedge, stroked so it carries the same\n 1px outline as the bubble (vector-effect keeps the stroke at\n real 1px despite the viewBox scaling). The cover rect hides the\n stroke along the attachment edge inside the bubble, so tail and\n bubble outlines merge into one shape. The SVG is mirrored\n (-scale-x-100), so low viewBox x is the outward tip and high x\n the attachment side. */}\n <svg\n aria-hidden\n className=\"eloq:absolute eloq:bottom-1 eloq:-right-[9px] eloq:h-4 eloq:w-4 eloq:-scale-x-100\"\n viewBox=\"0 0 10.54 11.14\"\n >\n {/* strokeWidth 2, not 1: SVG strokes are centered on the path, so\n half sits under the fill — 2 leaves exactly 1px visible\n outside, matching the bubble's 1px CSS border. */}\n <path\n d=\"M5.75,0s0,.36,0,.51c-.09,4.52-5.74,10.64-5.74,10.64,8.19.02,10.54-2.26,10.54-2.26h0c-1.6-2.96-3.19-5.92-4.79-8.88Z\"\n fill={theme.botBubbleColor}\n strokeWidth={2}\n vectorEffect=\"non-scaling-stroke\"\n style={{ stroke: \"hsl(var(--border))\" }}\n />\n <rect\n x=\"6.2\"\n y=\"-1\"\n width=\"6\"\n height=\"14\"\n fill={theme.botBubbleColor}\n />\n </svg>\n {/* The corner-pinned X is absolutely positioned and ignores the\n text flow entirely; pr-4 (16px, on top of the bubble's own\n 12px padding) keeps the text clear of the X's glyph. */}\n <p\n className=\"eloq:text-sm eloq:leading-relaxed eloq:pr-4\"\n style={{\n color:\n theme.botBubbleTextColor ||\n getContrastingTextColor(theme.botBubbleColor),\n }}\n >\n {message}\n </p>\n <button\n aria-label=\"Dismiss message\"\n onClick={(e) => {\n e.stopPropagation();\n onDismiss();\n }}\n // Pinned to the bubble's top-right corner, outside the text\n // flow — a flex-row placement can't tuck the glyph into the\n // padding area. p-1.5 keeps a 24px hit area around the 12px\n // icon; top/right-0.5 leaves the glyph ~8px from the edges.\n className=\"eloq:absolute eloq:top-0.5 eloq:right-0.5 eloq:p-1.5 eloq:opacity-50 eloq:hover:opacity-100 eloq:hover:bg-black/5 eloq:dark:hover:bg-white/10 eloq:rounded-full eloq:transition-all eloq:duration-200\"\n style={{\n // Follows the bubble's computed text colour, so the X blends\n // with the message on any bubble background (and dark mode).\n color:\n theme.botBubbleTextColor ||\n getContrastingTextColor(theme.botBubbleColor),\n }}\n >\n <X className=\"eloq:w-2.5 eloq:h-2.5\" strokeWidth={1.75} />\n </button>\n </div>\n </div>\n </div>\n );\n}\n","\"use client\";\n\nimport { useMemo } from \"react\";\n\nimport type { BootResponse } from \"@/lib/eloquent-ai-api-client\";\n\nimport { ChatInterfaceProps } from \"@/components/chat-interface\";\n\nexport interface UseInterfacePropsParams {\n chatProps?: Partial<ChatInterfaceProps>;\n chatSettings: BootResponse[\"chat_settings\"] | null;\n}\n\n/**\n * Hook to handle chat interface properties generation\n * Combines user-provided props with server-provided settings\n */\nexport function useInterfaceProps({\n chatProps,\n chatSettings,\n}: UseInterfacePropsParams): Partial<ChatInterfaceProps> {\n const chatInterfaceProps = useMemo(() => {\n if (!chatSettings) return chatProps as Partial<ChatInterfaceProps>;\n\n return {\n assistantName: chatSettings.agent_name,\n assistantLogo: chatSettings.avatar_url || undefined,\n theme: {\n ...chatProps?.theme,\n mode: chatSettings.theme ?? \"light\",\n userBubbleColor:\n chatSettings.user_bubble_color || chatProps?.theme?.userBubbleColor,\n botBubbleColor:\n chatSettings.bot_bubble_color || chatProps?.theme?.botBubbleColor,\n suggestedMessageBubbleColor:\n chatSettings.suggested_message_bubble_color ||\n chatProps?.theme?.suggestedMessageBubbleColor,\n userBubbleTextColor:\n chatSettings.user_bubble_text_color ||\n chatProps?.theme?.userBubbleTextColor,\n botBubbleTextColor:\n chatSettings.bot_bubble_text_color ||\n chatProps?.theme?.botBubbleTextColor,\n suggestedMessageBubbleTextColor:\n chatSettings.suggested_message_bubble_text_color ||\n chatProps?.theme?.suggestedMessageBubbleTextColor,\n },\n welcomeMessage: chatSettings.welcome_message || undefined,\n legalText: chatSettings.footer_html || undefined,\n suggestedMessages: chatSettings.suggested_messages,\n suggestedMessageTexts: chatSettings.suggested_message_texts ?? undefined,\n // Boot value wins when the server sends one (?? so an explicit false\n // still wins); the host-app prop is the fallback.\n hasSuggestedMessageAura:\n chatSettings.suggested_message_aura ??\n chatProps?.hasSuggestedMessageAura,\n hasSuggestedMessageShine:\n chatSettings.suggested_message_shine ??\n chatProps?.hasSuggestedMessageShine,\n displayWelcomeMessages: chatSettings.auto_display_welcome_message,\n collectUserFeedback: chatSettings.collect_user_feedback,\n title: chatSettings.title || \"responds instantly\",\n subtitle: chatSettings.subtitle || \"Ask me anything\",\n };\n }, [chatProps, chatSettings]);\n\n return chatInterfaceProps;\n}\n","import { useEffect, useRef } from \"react\";\n\n/**\n * Returns a ref that always holds the latest `value`, updated after every\n * render. The \"latest ref\" pattern: long-lived closures (timers, socket\n * subscriptions) read `ref.current` at call time instead of capturing a\n * stale value, without needing the value in any dependency array.\n */\nexport function useLatestRef<Type>(value: Type): { readonly current: Type } {\n const reference = useRef(value);\n\n useEffect(() => {\n reference.current = value;\n });\n\n return reference;\n}\n","// Custom error class for network errors (CORS, fetch failures)\nexport class NetworkError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"NetworkError\";\n }\n}\n\n// Custom error class for server errors\nexport class ServerError extends Error {\n status: number;\n response: Record<string, Record<string, string | number>[]>;\n\n constructor(\n status: number,\n message: string,\n response: Record<string, Record<string, string | number>[]>,\n ) {\n super(message);\n this.name = \"ServerError\";\n this.status = status;\n this.response = response;\n }\n}\n\nexport interface HttpClientConfig {\n baseURL: string;\n appId: string;\n userId?: string;\n}\n\nconst CHAT_TOKEN_HEADER = \"x-elo-chat-token\";\nconst CHAT_TOKEN_RENEWED_HEADER = \"x-elo-chat-token-renewed\";\n\nexport class HttpClient {\n private baseURL: string;\n private headers: HeadersInit;\n private region: string | null = null;\n private chatToken: string | null = null;\n\n constructor(config: HttpClientConfig) {\n this.baseURL = config.baseURL;\n\n this.headers = {\n \"Content-Type\": \"application/json\",\n \"ELO-APP-ID\": config.appId,\n Origin: typeof window !== \"undefined\" ? window.location.origin : \"\",\n };\n }\n\n setRegion(region: string): void {\n this.region = region;\n }\n\n setChatToken(token: string | null): void {\n this.chatToken = token;\n }\n\n getChatToken(): string | null {\n return this.chatToken;\n }\n\n private async request<T>(url: string, options: RequestInit = {}): Promise<T> {\n const regionHeader: Record<string, string> = this.region\n ? { \"X-Region\": this.region }\n : {};\n const chatTokenHeader: Record<string, string> = this.chatToken\n ? { [CHAT_TOKEN_HEADER]: this.chatToken }\n : {};\n\n let response: Response;\n try {\n response = await fetch(`${this.baseURL}${url}`, {\n ...options,\n headers: {\n ...this.headers,\n ...regionHeader,\n ...chatTokenHeader,\n ...options.headers,\n },\n });\n } catch (error) {\n if (error instanceof TypeError) {\n throw new NetworkError(error.message);\n }\n throw error;\n }\n\n const renewedToken = response.headers.get(CHAT_TOKEN_RENEWED_HEADER);\n if (renewedToken) {\n this.chatToken = renewedToken;\n }\n\n let responseData;\n try {\n responseData = await response.json();\n } catch (e) {\n console.error(\"Error parsing JSON response:\", e);\n }\n\n if (!response.ok) {\n // Check for server errors (500 range)\n if (response.status >= 500) {\n throw new ServerError(response.status, \"API error\", responseData);\n }\n throw new ServerError(response.status, \"HTTP error\", responseData);\n }\n\n return responseData;\n }\n\n async get<T>(url: string) {\n return this.request<T>(url, { method: \"GET\" });\n }\n\n async post<T, D>(url: string, data: D): Promise<T> {\n return this.request<T>(url, {\n method: \"POST\",\n body: JSON.stringify(data),\n });\n }\n\n async put<T, D>(url: string, data: D): Promise<T> {\n return this.request<T>(url, {\n method: \"PUT\",\n body: JSON.stringify(data),\n });\n }\n\n /**\n * External GET request without default headers or credentials\n * Used for cross-origin requests that don't need authentication\n */\n async getExternal<T>(url: string): Promise<T> {\n const response = await fetch(url, {\n method: \"GET\",\n credentials: \"omit\",\n });\n\n let responseData;\n try {\n responseData = await response.json();\n } catch (e) {\n console.error(\"Error parsing JSON response:\", e);\n }\n\n if (!response.ok) {\n // Check for server errors (500 range)\n if (response.status >= 500) {\n throw new ServerError(response.status, \"API error\", responseData);\n }\n throw new ServerError(response.status, \"HTTP error\", responseData);\n }\n\n return responseData;\n }\n}\n","/**\n * Reads the current page URL search params from the host website.\n * Returns an empty object during SSR or when there are no query params.\n */\nexport function getCurrentUrlSearchParams(): Record<string, string> {\n if (typeof window === \"undefined\") {\n return {};\n }\n\n const params = new URLSearchParams(window.location.search);\n const result: Record<string, string> = {};\n\n params.forEach((value, key) => {\n result[key] = value;\n });\n\n return result;\n}\n","\"use client\";\n\nimport { useCallback, useMemo } from \"react\";\n\nimport { Message } from \"@/type\";\n\n// Single key for localStorage\nconst STORAGE_NAMESPACE = \"eloquent-ai::conversation-data\";\n\nconst isClient = typeof window !== \"undefined\";\n\n// 30 minutes in milliseconds\nconst CHAT_EXPIRY_TIME = 30 * 60 * 1000;\n\nexport interface ChatData {\n conversationId: string | null;\n userId: string | null;\n externalId?: string | null;\n deviceId: string | null;\n messages: Message[];\n lastActivity?: number;\n isChatClosed?: boolean;\n chatToken?: string | null;\n}\n\n/**\n * Hook to manage persistence of chat data, including conversation ID, user ID, last activity time, and messages.\n * @returns An object containing the conversation data and functions to set and clear the data.\n */\nexport function usePersistence({ appId }: { appId: string }) {\n const STORAGE_KEY = useMemo(() => `${STORAGE_NAMESPACE}-${appId}`, [appId]);\n const defaultObject = useMemo(\n () => ({\n conversationId: null,\n userId: null,\n deviceId: null,\n messages: [],\n }),\n [],\n );\n\n /**\n * Get saved conversation data from localStorage\n */\n const getSavedChatData = useCallback((): ChatData => {\n try {\n if (!isClient) return defaultObject;\n const storedData = localStorage.getItem(STORAGE_KEY);\n if (!storedData) {\n return defaultObject;\n }\n return JSON.parse(storedData) as ChatData;\n } catch (error) {\n console.error(\n \"Error retrieving conversation data from localStorage:\",\n error,\n );\n return defaultObject;\n }\n }, [STORAGE_KEY, defaultObject]);\n\n /**\n * Check if the current conversation has expired (inactive for more than 30 minutes)\n */\n const isChatExpired = useCallback((): boolean => {\n try {\n const data = getSavedChatData();\n if (!data.lastActivity) return true;\n\n const currentTime = Date.now();\n return currentTime - data.lastActivity > CHAT_EXPIRY_TIME;\n } catch (error) {\n console.error(\"Error checking conversation expiration:\", error);\n return true;\n }\n }, [getSavedChatData]);\n\n /**\n * Save conversation data to localStorage\n */\n const saveChatData = useCallback(\n (\n conversationId: string,\n userId: string,\n messages: Message[],\n deviceId: string,\n chatToken?: string | null,\n ) => {\n try {\n if (!isClient) return;\n const chatData: ChatData = {\n conversationId,\n userId,\n deviceId,\n messages,\n lastActivity: Date.now(),\n chatToken,\n };\n\n localStorage.setItem(STORAGE_KEY, JSON.stringify(chatData));\n } catch (error) {\n console.error(\"Error saving conversation data to localStorage:\", error);\n }\n },\n [STORAGE_KEY],\n );\n\n /**\n * Mark the current conversation as closed, so a page refresh still shows\n * the \"Start a new conversation\" screen instead of resetting it.\n */\n const markChatClosed = useCallback(() => {\n try {\n if (!isClient) return;\n const data = getSavedChatData();\n localStorage.setItem(\n STORAGE_KEY,\n JSON.stringify({ ...data, isChatClosed: true }),\n );\n } catch (error) {\n console.error(\n \"Error marking conversation as closed in localStorage:\",\n error,\n );\n }\n }, [STORAGE_KEY, getSavedChatData]);\n\n /**\n * Clear only conversationId, messages, and lastActivity from localStorage, preserving userId and deviceId\n */\n const clearChatData = useCallback(() => {\n try {\n if (!isClient) return;\n const stored = localStorage.getItem(STORAGE_KEY);\n if (stored) {\n const data = JSON.parse(stored);\n localStorage.setItem(\n STORAGE_KEY,\n JSON.stringify({\n ...defaultObject,\n deviceId: data.deviceId,\n userId: data.userId,\n }),\n );\n }\n } catch (error) {\n console.error(\n \"Error clearing conversation data from localStorage:\",\n error,\n );\n }\n }, [STORAGE_KEY, defaultObject]);\n\n /**\n * Update the last activity timestamp\n */\n const updateLastActivity = useCallback(() => {\n try {\n if (!isClient) return;\n const data = getSavedChatData();\n if (data.conversationId) {\n data.lastActivity = Date.now();\n localStorage.setItem(STORAGE_KEY, JSON.stringify(data));\n }\n } catch (error) {\n console.error(\"Error updating last activity timestamp:\", error);\n }\n }, [getSavedChatData, STORAGE_KEY]);\n\n return {\n isChatExpired,\n saveChatData,\n clearChatData,\n getSavedChatData,\n updateLastActivity,\n markChatClosed,\n };\n}\n","// Minimal AWS AppSync Events API real-time client — a hand-rolled\n// replacement for aws-amplify's `events.connect`, which carried ~160KB of\n// dependencies (amplify core, rxjs, graphql) for the tiny surface this SDK\n// uses: subscribe to one channel, deliver events, detect disconnects.\n//\n// Protocol reference: AWS \"Event API WebSocket protocol\" docs, cross-checked\n// against @aws-amplify/api-graphql's AWSAppSyncEventsProvider implementation\n// (subprotocol names, header encoding, keep-alive semantics, timeouts).\n//\n// Wire flow:\n// 1. Open a WebSocket to the realtime endpoint with two subprotocols:\n// \"aws-appsync-event-ws\" and \"header-<base64url(auth JSON)>\"\n// 2. Send {\"type\":\"connection_init\"}, await connection_ack (carries\n// connectionTimeoutMs — the keep-alive death window)\n// 3. Send subscribe with the SAME authorization embedded in the message\n// (per-operation auth is required by the protocol, not just per-connect)\n// 4. Receive {\"type\":\"data\", \"event\":\"<JSON string>\"} per published event\n// 5. Server sends {\"type\":\"ka\"} every ~60s; if neither ka nor data arrives\n// within connectionTimeoutMs, the connection is dead.\n\n/** Lambda-authorizer token (the chat token) or the API key fallback. */\nexport type AppSyncEventsAuth =\n | { authorizationToken: string }\n | { apiKey: string };\n\nexport type AppSyncEventsConnection = {\n /** Sends unsubscribe, closes the socket, and suppresses onDisconnect. */\n close: () => void;\n};\n\nexport type WebSocketLike = {\n readyState: number;\n send: (data: string) => void;\n close: () => void;\n addEventListener: (\n type: \"open\" | \"message\" | \"close\" | \"error\",\n listener: (event: { data?: unknown }) => void,\n ) => void;\n};\n\nexport type ConnectAppSyncEventsOptions = {\n /** The HTTP Events endpoint from boot settings (chat_settings.app_sync_url). */\n httpEndpoint: string;\n auth: AppSyncEventsAuth;\n /** Channel path, e.g. \"/default/chat/<chatId>\". */\n channel: string;\n /** Called once per published event, with the payload already JSON-parsed. */\n onEvent: (event: unknown) => void;\n /**\n * Called exactly once when an established connection dies (server close,\n * network drop, keep-alive timeout). NOT called after close(), and not\n * called for connections that never established (connect() rejects there).\n */\n onDisconnect: (reason: string) => void;\n /** Injectable for tests; defaults to the global WebSocket constructor. */\n createWebSocket?: (url: string, protocols: string[]) => WebSocketLike;\n};\n\nexport const APPSYNC_EVENTS_SUBPROTOCOL = \"aws-appsync-event-ws\";\n\n/** connection_init → connection_ack and subscribe → subscribe_success wait. */\nexport const HANDSHAKE_TIMEOUT_MILLISECONDS = 15000;\n/** Fallback keep-alive death window when the ack doesn't carry one. */\nexport const DEFAULT_CONNECTION_TIMEOUT_MILLISECONDS = 300000;\n/** How often the keep-alive clock is checked. */\nexport const KEEP_ALIVE_CHECK_INTERVAL_MILLISECONDS = 5000;\n\nconst WEB_SOCKET_OPEN_STATE = 1;\n\n/**\n * Derives the realtime WebSocket URL from the HTTP Events endpoint.\n * Standard AWS domains swap the service subdomain; custom domains keep the\n * host and only append the path.\n * https://xxx.appsync-api.us-east-1.amazonaws.com/event\n * → wss://xxx.appsync-realtime-api.us-east-1.amazonaws.com/event/realtime\n * https://events.example.com/event\n * → wss://events.example.com/event/realtime\n */\nexport function deriveRealtimeUrl(httpEndpoint: string): string {\n const url = new URL(httpEndpoint);\n const isStandardAwsDomain =\n /\\.appsync-api\\.[\\w-]+\\.amazonaws\\.com(\\.cn)?$/.test(url.hostname);\n if (isStandardAwsDomain) {\n url.hostname = url.hostname.replace(\n \".appsync-api.\",\n \".appsync-realtime-api.\",\n );\n }\n url.protocol = \"wss:\";\n url.pathname = `${url.pathname.replace(/\\/$/, \"\")}/realtime`;\n return url.toString();\n}\n\n/**\n * The authorization object embedded both in the connect subprotocol header\n * and in every subscribe message. `host` is always the HTTP endpoint's host\n * (not the realtime host), per the protocol.\n */\nexport function buildAuthorization(\n httpEndpoint: string,\n auth: AppSyncEventsAuth,\n): Record<string, string> {\n const host = new URL(httpEndpoint).host;\n if (\"authorizationToken\" in auth) {\n return { Authorization: auth.authorizationToken, host };\n }\n return { \"x-api-key\": auth.apiKey, host };\n}\n\n/**\n * Encodes the authorization object into the `header-…` subprotocol value:\n * base64url (`+`→`-`, `/`→`_`) with padding stripped — `=` is not a legal\n * character in a Sec-WebSocket-Protocol token and fails the handshake.\n */\nexport function encodeAuthProtocol(\n authorization: Record<string, string>,\n): string {\n const base64 = btoa(JSON.stringify(authorization));\n return `header-${base64.replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\")}`;\n}\n\ntype ServerMessage = {\n type?: string;\n id?: string;\n event?: unknown;\n connectionTimeoutMs?: number;\n errors?: { errorType?: string; message?: string }[];\n};\n\nfunction formatErrors(errors: ServerMessage[\"errors\"]): string {\n if (!errors || errors.length === 0) return \"unknown error\";\n return errors\n .map((error) => `${error.errorType ?? \"Error\"}: ${error.message ?? \"\"}`)\n .join(\"; \");\n}\n\n/**\n * Opens a connection and subscribes to one channel. Resolves once the\n * subscription is confirmed; rejects if any handshake step fails or times\n * out (the socket is closed in that case). After resolution, connection\n * death is reported via onDisconnect exactly once.\n */\nexport function connectAppSyncEvents(\n options: ConnectAppSyncEventsOptions,\n): Promise<AppSyncEventsConnection> {\n const {\n httpEndpoint,\n auth,\n channel,\n onEvent,\n onDisconnect,\n createWebSocket = (url, protocols) =>\n new WebSocket(url, protocols) as WebSocketLike,\n } = options;\n\n const authorization = buildAuthorization(httpEndpoint, auth);\n const realtimeUrl = deriveRealtimeUrl(httpEndpoint);\n const subscriptionId = crypto.randomUUID();\n\n return new Promise<AppSyncEventsConnection>((resolve, reject) => {\n let socket: WebSocketLike;\n try {\n socket = createWebSocket(realtimeUrl, [\n APPSYNC_EVENTS_SUBPROTOCOL,\n encodeAuthProtocol(authorization),\n ]);\n } catch (error) {\n reject(error instanceof Error ? error : new Error(String(error)));\n return;\n }\n\n let phase: \"connecting\" | \"subscribing\" | \"established\" | \"closed\" =\n \"connecting\";\n let isClosedByClient = false;\n let connectionTimeoutMilliseconds = DEFAULT_CONNECTION_TIMEOUT_MILLISECONDS;\n let lastLivenessTimestamp = Date.now();\n\n let handshakeTimer: ReturnType<typeof setTimeout> | null = null;\n let keepAliveTimer: ReturnType<typeof setInterval> | null = null;\n\n const clearTimers = () => {\n if (handshakeTimer) {\n clearTimeout(handshakeTimer);\n handshakeTimer = null;\n }\n if (keepAliveTimer) {\n clearInterval(keepAliveTimer);\n keepAliveTimer = null;\n }\n };\n\n /** Single funnel for connection death, in any phase. */\n const terminate = (reason: string) => {\n if (phase === \"closed\") return;\n const wasEstablished = phase === \"established\";\n phase = \"closed\";\n clearTimers();\n try {\n socket.close();\n } catch {\n // Already closed/closing.\n }\n if (isClosedByClient) return;\n if (wasEstablished) {\n onDisconnect(reason);\n } else {\n reject(new Error(reason));\n }\n };\n\n const send = (message: Record<string, unknown>) => {\n if (socket.readyState !== WEB_SOCKET_OPEN_STATE) return;\n socket.send(JSON.stringify(message));\n };\n\n const startHandshakeTimer = (step: string) => {\n if (handshakeTimer) clearTimeout(handshakeTimer);\n handshakeTimer = setTimeout(() => {\n terminate(`Timed out waiting for ${step}`);\n }, HANDSHAKE_TIMEOUT_MILLISECONDS);\n };\n\n socket.addEventListener(\"open\", () => {\n if (phase === \"closed\") return;\n send({ type: \"connection_init\" });\n startHandshakeTimer(\"connection_ack\");\n });\n\n socket.addEventListener(\"message\", (event) => {\n if (phase === \"closed\") return;\n\n let message: ServerMessage;\n try {\n message = JSON.parse(String(event.data)) as ServerMessage;\n } catch {\n console.warn(\"[EloquentChatSDK] Unparseable realtime frame ignored\");\n return;\n }\n\n switch (message.type) {\n case \"connection_ack\": {\n if (phase !== \"connecting\") return;\n phase = \"subscribing\";\n if (typeof message.connectionTimeoutMs === \"number\") {\n connectionTimeoutMilliseconds = message.connectionTimeoutMs;\n }\n send({\n type: \"subscribe\",\n id: subscriptionId,\n channel,\n authorization,\n });\n startHandshakeTimer(\"subscribe_success\");\n return;\n }\n case \"connection_error\": {\n terminate(`Connection error: ${formatErrors(message.errors)}`);\n return;\n }\n case \"subscribe_success\": {\n if (phase !== \"subscribing\" || message.id !== subscriptionId) return;\n phase = \"established\";\n if (handshakeTimer) {\n clearTimeout(handshakeTimer);\n handshakeTimer = null;\n }\n lastLivenessTimestamp = Date.now();\n keepAliveTimer = setInterval(() => {\n if (\n Date.now() - lastLivenessTimestamp >\n connectionTimeoutMilliseconds\n ) {\n terminate(\"Keep-alive timeout\");\n }\n }, KEEP_ALIVE_CHECK_INTERVAL_MILLISECONDS);\n resolve({\n close: () => {\n isClosedByClient = true;\n send({ type: \"unsubscribe\", id: subscriptionId });\n terminate(\"Closed by client\");\n },\n });\n return;\n }\n case \"subscribe_error\": {\n if (message.id !== subscriptionId) return;\n terminate(`Subscribe error: ${formatErrors(message.errors)}`);\n return;\n }\n case \"ka\": {\n lastLivenessTimestamp = Date.now();\n return;\n }\n case \"data\": {\n if (message.id !== subscriptionId) return;\n // A busy channel can delay ka frames; data proves liveness too\n // (mirrors the amplify client).\n lastLivenessTimestamp = Date.now();\n // The event field is a JSON *string* per the protocol.\n let payload: unknown = message.event;\n if (typeof payload === \"string\") {\n try {\n payload = JSON.parse(payload);\n } catch {\n console.warn(\n \"[EloquentChatSDK] Unparseable realtime event ignored\",\n );\n return;\n }\n }\n onEvent(payload);\n return;\n }\n case \"broadcast_error\": {\n console.warn(\n \"[EloquentChatSDK] Realtime broadcast error:\",\n formatErrors(message.errors),\n );\n return;\n }\n default:\n // unsubscribe_success and unknown/future frame types.\n return;\n }\n });\n\n socket.addEventListener(\"close\", () => {\n terminate(\"WebSocket closed\");\n });\n\n socket.addEventListener(\"error\", () => {\n // A close event follows an error; terminate here anyway so failures\n // that never fire close (some environments) still reject/notify.\n terminate(\"WebSocket error\");\n });\n });\n}\n","var _a;\n/** A special constant with type `never` */\nexport const NEVER = /*@__PURE__*/ Object.freeze({\n status: \"aborted\",\n});\nexport /*@__NO_SIDE_EFFECTS__*/ function $constructor(name, initializer, params) {\n function init(inst, def) {\n if (!inst._zod) {\n Object.defineProperty(inst, \"_zod\", {\n value: {\n def,\n constr: _,\n traits: new Set(),\n },\n enumerable: false,\n });\n }\n if (inst._zod.traits.has(name)) {\n return;\n }\n inst._zod.traits.add(name);\n initializer(inst, def);\n // support prototype modifications\n const proto = _.prototype;\n const keys = Object.keys(proto);\n for (let i = 0; i < keys.length; i++) {\n const k = keys[i];\n if (!(k in inst)) {\n inst[k] = proto[k].bind(inst);\n }\n }\n }\n // doesn't work if Parent has a constructor with arguments\n const Parent = params?.Parent ?? Object;\n class Definition extends Parent {\n }\n Object.defineProperty(Definition, \"name\", { value: name });\n function _(def) {\n var _a;\n const inst = params?.Parent ? new Definition() : this;\n init(inst, def);\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n for (const fn of inst._zod.deferred) {\n fn();\n }\n return inst;\n }\n Object.defineProperty(_, \"init\", { value: init });\n Object.defineProperty(_, Symbol.hasInstance, {\n value: (inst) => {\n if (params?.Parent && inst instanceof params.Parent)\n return true;\n return inst?._zod?.traits?.has(name);\n },\n });\n Object.defineProperty(_, \"name\", { value: name });\n return _;\n}\n////////////////////////////// UTILITIES ///////////////////////////////////////\nexport const $brand = Symbol(\"zod_brand\");\nexport class $ZodAsyncError extends Error {\n constructor() {\n super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);\n }\n}\nexport class $ZodEncodeError extends Error {\n constructor(name) {\n super(`Encountered unidirectional transform during encode: ${name}`);\n this.name = \"ZodEncodeError\";\n }\n}\n(_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {});\nexport const globalConfig = globalThis.__zod_globalConfig;\nexport function config(newConfig) {\n if (newConfig)\n Object.assign(globalConfig, newConfig);\n return globalConfig;\n}\n","import { globalConfig } from \"./core.js\";\n// functions\nexport function assertEqual(val) {\n return val;\n}\nexport function assertNotEqual(val) {\n return val;\n}\nexport function assertIs(_arg) { }\nexport function assertNever(_x) {\n throw new Error(\"Unexpected value in exhaustive check\");\n}\nexport function assert(_) { }\nexport function getEnumValues(entries) {\n const numericValues = Object.values(entries).filter((v) => typeof v === \"number\");\n const values = Object.entries(entries)\n .filter(([k, _]) => numericValues.indexOf(+k) === -1)\n .map(([_, v]) => v);\n return values;\n}\nexport function joinValues(array, separator = \"|\") {\n return array.map((val) => stringifyPrimitive(val)).join(separator);\n}\nexport function jsonStringifyReplacer(_, value) {\n if (typeof value === \"bigint\")\n return value.toString();\n return value;\n}\nexport function cached(getter) {\n const set = false;\n return {\n get value() {\n if (!set) {\n const value = getter();\n Object.defineProperty(this, \"value\", { value });\n return value;\n }\n throw new Error(\"cached value already set\");\n },\n };\n}\nexport function nullish(input) {\n return input === null || input === undefined;\n}\nexport function cleanRegex(source) {\n const start = source.startsWith(\"^\") ? 1 : 0;\n const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n return source.slice(start, end);\n}\nexport function floatSafeRemainder(val, step) {\n const ratio = val / step;\n const roundedRatio = Math.round(ratio);\n // Use a relative epsilon scaled to the magnitude of the result\n const tolerance = Number.EPSILON * Math.max(Math.abs(ratio), 1);\n if (Math.abs(ratio - roundedRatio) < tolerance)\n return 0;\n return ratio - roundedRatio;\n}\nconst EVALUATING = /* @__PURE__*/ Symbol(\"evaluating\");\nexport function defineLazy(object, key, getter) {\n let value = undefined;\n Object.defineProperty(object, key, {\n get() {\n if (value === EVALUATING) {\n // Circular reference detected, return undefined to break the cycle\n return undefined;\n }\n if (value === undefined) {\n value = EVALUATING;\n value = getter();\n }\n return value;\n },\n set(v) {\n Object.defineProperty(object, key, {\n value: v,\n // configurable: true,\n });\n // object[key] = v;\n },\n configurable: true,\n });\n}\nexport function objectClone(obj) {\n return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));\n}\nexport function assignProp(target, prop, value) {\n Object.defineProperty(target, prop, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n}\nexport function mergeDefs(...defs) {\n const mergedDescriptors = {};\n for (const def of defs) {\n const descriptors = Object.getOwnPropertyDescriptors(def);\n Object.assign(mergedDescriptors, descriptors);\n }\n return Object.defineProperties({}, mergedDescriptors);\n}\nexport function cloneDef(schema) {\n return mergeDefs(schema._zod.def);\n}\nexport function getElementAtPath(obj, path) {\n if (!path)\n return obj;\n return path.reduce((acc, key) => acc?.[key], obj);\n}\nexport function promiseAllObject(promisesObj) {\n const keys = Object.keys(promisesObj);\n const promises = keys.map((key) => promisesObj[key]);\n return Promise.all(promises).then((results) => {\n const resolvedObj = {};\n for (let i = 0; i < keys.length; i++) {\n resolvedObj[keys[i]] = results[i];\n }\n return resolvedObj;\n });\n}\nexport function randomString(length = 10) {\n const chars = \"abcdefghijklmnopqrstuvwxyz\";\n let str = \"\";\n for (let i = 0; i < length; i++) {\n str += chars[Math.floor(Math.random() * chars.length)];\n }\n return str;\n}\nexport function esc(str) {\n return JSON.stringify(str);\n}\nexport function slugify(input) {\n return input\n .toLowerCase()\n .trim()\n .replace(/[^\\w\\s-]/g, \"\")\n .replace(/[\\s_-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n}\nexport const captureStackTrace = (\"captureStackTrace\" in Error ? Error.captureStackTrace : (..._args) => { });\nexport function isObject(data) {\n return typeof data === \"object\" && data !== null && !Array.isArray(data);\n}\nexport const allowsEval = /* @__PURE__*/ cached(() => {\n // Skip the probe under `jitless`: strict CSPs report the caught `new Function`\n // as a `securitypolicyviolation` even though the throw is swallowed.\n if (globalConfig.jitless) {\n return false;\n }\n // @ts-ignore\n if (typeof navigator !== \"undefined\" && navigator?.userAgent?.includes(\"Cloudflare\")) {\n return false;\n }\n try {\n const F = Function;\n new F(\"\");\n return true;\n }\n catch (_) {\n return false;\n }\n});\nexport function isPlainObject(o) {\n if (isObject(o) === false)\n return false;\n // modified constructor\n const ctor = o.constructor;\n if (ctor === undefined)\n return true;\n if (typeof ctor !== \"function\")\n return true;\n // modified prototype\n const prot = ctor.prototype;\n if (isObject(prot) === false)\n return false;\n // ctor doesn't have static `isPrototypeOf`\n if (Object.prototype.hasOwnProperty.call(prot, \"isPrototypeOf\") === false) {\n return false;\n }\n return true;\n}\nexport function shallowClone(o) {\n if (isPlainObject(o))\n return { ...o };\n if (Array.isArray(o))\n return [...o];\n if (o instanceof Map)\n return new Map(o);\n if (o instanceof Set)\n return new Set(o);\n return o;\n}\nexport function numKeys(data) {\n let keyCount = 0;\n for (const key in data) {\n if (Object.prototype.hasOwnProperty.call(data, key)) {\n keyCount++;\n }\n }\n return keyCount;\n}\nexport const getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case \"undefined\":\n return \"undefined\";\n case \"string\":\n return \"string\";\n case \"number\":\n return Number.isNaN(data) ? \"nan\" : \"number\";\n case \"boolean\":\n return \"boolean\";\n case \"function\":\n return \"function\";\n case \"bigint\":\n return \"bigint\";\n case \"symbol\":\n return \"symbol\";\n case \"object\":\n if (Array.isArray(data)) {\n return \"array\";\n }\n if (data === null) {\n return \"null\";\n }\n if (data.then && typeof data.then === \"function\" && data.catch && typeof data.catch === \"function\") {\n return \"promise\";\n }\n if (typeof Map !== \"undefined\" && data instanceof Map) {\n return \"map\";\n }\n if (typeof Set !== \"undefined\" && data instanceof Set) {\n return \"set\";\n }\n if (typeof Date !== \"undefined\" && data instanceof Date) {\n return \"date\";\n }\n // @ts-ignore\n if (typeof File !== \"undefined\" && data instanceof File) {\n return \"file\";\n }\n return \"object\";\n default:\n throw new Error(`Unknown data type: ${t}`);\n }\n};\nexport const propertyKeyTypes = /* @__PURE__*/ new Set([\"string\", \"number\", \"symbol\"]);\nexport const primitiveTypes = /* @__PURE__*/ new Set([\n \"string\",\n \"number\",\n \"bigint\",\n \"boolean\",\n \"symbol\",\n \"undefined\",\n]);\nexport function escapeRegex(str) {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n// zod-specific utils\nexport function clone(inst, def, params) {\n const cl = new inst._zod.constr(def ?? inst._zod.def);\n if (!def || params?.parent)\n cl._zod.parent = inst;\n return cl;\n}\nexport function normalizeParams(_params) {\n const params = _params;\n if (!params)\n return {};\n if (typeof params === \"string\")\n return { error: () => params };\n if (params?.message !== undefined) {\n if (params?.error !== undefined)\n throw new Error(\"Cannot specify both `message` and `error` params\");\n params.error = params.message;\n }\n delete params.message;\n if (typeof params.error === \"string\")\n return { ...params, error: () => params.error };\n return params;\n}\nexport function createTransparentProxy(getter) {\n let target;\n return new Proxy({}, {\n get(_, prop, receiver) {\n target ?? (target = getter());\n return Reflect.get(target, prop, receiver);\n },\n set(_, prop, value, receiver) {\n target ?? (target = getter());\n return Reflect.set(target, prop, value, receiver);\n },\n has(_, prop) {\n target ?? (target = getter());\n return Reflect.has(target, prop);\n },\n deleteProperty(_, prop) {\n target ?? (target = getter());\n return Reflect.deleteProperty(target, prop);\n },\n ownKeys(_) {\n target ?? (target = getter());\n return Reflect.ownKeys(target);\n },\n getOwnPropertyDescriptor(_, prop) {\n target ?? (target = getter());\n return Reflect.getOwnPropertyDescriptor(target, prop);\n },\n defineProperty(_, prop, descriptor) {\n target ?? (target = getter());\n return Reflect.defineProperty(target, prop, descriptor);\n },\n });\n}\nexport function stringifyPrimitive(value) {\n if (typeof value === \"bigint\")\n return value.toString() + \"n\";\n if (typeof value === \"string\")\n return `\"${value}\"`;\n return `${value}`;\n}\nexport function optionalKeys(shape) {\n return Object.keys(shape).filter((k) => {\n return shape[k]._zod.optin === \"optional\" && shape[k]._zod.optout === \"optional\";\n });\n}\nexport const NUMBER_FORMAT_RANGES = {\n safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],\n int32: [-2147483648, 2147483647],\n uint32: [0, 4294967295],\n float32: [-3.4028234663852886e38, 3.4028234663852886e38],\n float64: [-Number.MAX_VALUE, Number.MAX_VALUE],\n};\nexport const BIGINT_FORMAT_RANGES = {\n int64: [/* @__PURE__*/ BigInt(\"-9223372036854775808\"), /* @__PURE__*/ BigInt(\"9223372036854775807\")],\n uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt(\"18446744073709551615\")],\n};\nexport function pick(schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".pick() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const newShape = {};\n for (const key in mask) {\n if (!(key in currDef.shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n newShape[key] = currDef.shape[key];\n }\n assignProp(this, \"shape\", newShape); // self-caching\n return newShape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function omit(schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".omit() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const newShape = { ...schema._zod.def.shape };\n for (const key in mask) {\n if (!(key in currDef.shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n delete newShape[key];\n }\n assignProp(this, \"shape\", newShape); // self-caching\n return newShape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function extend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to extend: expected a plain object\");\n }\n const checks = schema._zod.def.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n // Only throw if new shape overlaps with existing shape\n // Use getOwnPropertyDescriptor to check key existence without accessing values\n const existingShape = schema._zod.def.shape;\n for (const key in shape) {\n if (Object.getOwnPropertyDescriptor(existingShape, key) !== undefined) {\n throw new Error(\"Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.\");\n }\n }\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const _shape = { ...schema._zod.def.shape, ...shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n });\n return clone(schema, def);\n}\nexport function safeExtend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to safeExtend: expected a plain object\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const _shape = { ...schema._zod.def.shape, ...shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n });\n return clone(schema, def);\n}\nexport function merge(a, b) {\n if (a._zod.def.checks?.length) {\n throw new Error(\".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.\");\n }\n const def = mergeDefs(a._zod.def, {\n get shape() {\n const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n get catchall() {\n return b._zod.def.catchall;\n },\n checks: b._zod.def.checks ?? [],\n });\n return clone(a, def);\n}\nexport function partial(Class, schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".partial() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const oldShape = schema._zod.def.shape;\n const shape = { ...oldShape };\n if (mask) {\n for (const key in mask) {\n if (!(key in oldShape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n // if (oldShape[key]!._zod.optin === \"optional\") continue;\n shape[key] = Class\n ? new Class({\n type: \"optional\",\n innerType: oldShape[key],\n })\n : oldShape[key];\n }\n }\n else {\n for (const key in oldShape) {\n // if (oldShape[key]!._zod.optin === \"optional\") continue;\n shape[key] = Class\n ? new Class({\n type: \"optional\",\n innerType: oldShape[key],\n })\n : oldShape[key];\n }\n }\n assignProp(this, \"shape\", shape); // self-caching\n return shape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function required(Class, schema, mask) {\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const oldShape = schema._zod.def.shape;\n const shape = { ...oldShape };\n if (mask) {\n for (const key in mask) {\n if (!(key in shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n // overwrite with non-optional\n shape[key] = new Class({\n type: \"nonoptional\",\n innerType: oldShape[key],\n });\n }\n }\n else {\n for (const key in oldShape) {\n // overwrite with non-optional\n shape[key] = new Class({\n type: \"nonoptional\",\n innerType: oldShape[key],\n });\n }\n }\n assignProp(this, \"shape\", shape); // self-caching\n return shape;\n },\n });\n return clone(schema, def);\n}\n// invalid_type | too_big | too_small | invalid_format | not_multiple_of | unrecognized_keys | invalid_union | invalid_key | invalid_element | invalid_value | custom\nexport function aborted(x, startIndex = 0) {\n if (x.aborted === true)\n return true;\n for (let i = startIndex; i < x.issues.length; i++) {\n if (x.issues[i]?.continue !== true) {\n return true;\n }\n }\n return false;\n}\n// Checks for explicit abort (continue === false), as opposed to implicit abort (continue === undefined).\n// Used to respect `abort: true` in .refine() even for checks that have a `when` function.\nexport function explicitlyAborted(x, startIndex = 0) {\n if (x.aborted === true)\n return true;\n for (let i = startIndex; i < x.issues.length; i++) {\n if (x.issues[i]?.continue === false) {\n return true;\n }\n }\n return false;\n}\nexport function prefixIssues(path, issues) {\n return issues.map((iss) => {\n var _a;\n (_a = iss).path ?? (_a.path = []);\n iss.path.unshift(path);\n return iss;\n });\n}\nexport function unwrapMessage(message) {\n return typeof message === \"string\" ? message : message?.message;\n}\nexport function finalizeIssue(iss, ctx, config) {\n const message = iss.message\n ? iss.message\n : (unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ??\n unwrapMessage(ctx?.error?.(iss)) ??\n unwrapMessage(config.customError?.(iss)) ??\n unwrapMessage(config.localeError?.(iss)) ??\n \"Invalid input\");\n const { inst: _inst, continue: _continue, input: _input, ...rest } = iss;\n rest.path ?? (rest.path = []);\n rest.message = message;\n if (ctx?.reportInput) {\n rest.input = _input;\n }\n return rest;\n}\nexport function getSizableOrigin(input) {\n if (input instanceof Set)\n return \"set\";\n if (input instanceof Map)\n return \"map\";\n // @ts-ignore\n if (input instanceof File)\n return \"file\";\n return \"unknown\";\n}\nexport function getLengthableOrigin(input) {\n if (Array.isArray(input))\n return \"array\";\n if (typeof input === \"string\")\n return \"string\";\n return \"unknown\";\n}\nexport function parsedType(data) {\n const t = typeof data;\n switch (t) {\n case \"number\": {\n return Number.isNaN(data) ? \"nan\" : \"number\";\n }\n case \"object\": {\n if (data === null) {\n return \"null\";\n }\n if (Array.isArray(data)) {\n return \"array\";\n }\n const obj = data;\n if (obj && Object.getPrototypeOf(obj) !== Object.prototype && \"constructor\" in obj && obj.constructor) {\n return obj.constructor.name;\n }\n }\n }\n return t;\n}\nexport function issue(...args) {\n const [iss, input, inst] = args;\n if (typeof iss === \"string\") {\n return {\n message: iss,\n code: \"custom\",\n input,\n inst,\n };\n }\n return { ...iss };\n}\nexport function cleanEnum(obj) {\n return Object.entries(obj)\n .filter(([k, _]) => {\n // return true if NaN, meaning it's not a number, thus a string key\n return Number.isNaN(Number.parseInt(k, 10));\n })\n .map((el) => el[1]);\n}\n// Codec utility functions\nexport function base64ToUint8Array(base64) {\n const binaryString = atob(base64);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n return bytes;\n}\nexport function uint8ArrayToBase64(bytes) {\n let binaryString = \"\";\n for (let i = 0; i < bytes.length; i++) {\n binaryString += String.fromCharCode(bytes[i]);\n }\n return btoa(binaryString);\n}\nexport function base64urlToUint8Array(base64url) {\n const base64 = base64url.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padding = \"=\".repeat((4 - (base64.length % 4)) % 4);\n return base64ToUint8Array(base64 + padding);\n}\nexport function uint8ArrayToBase64url(bytes) {\n return uint8ArrayToBase64(bytes).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=/g, \"\");\n}\nexport function hexToUint8Array(hex) {\n const cleanHex = hex.replace(/^0x/, \"\");\n if (cleanHex.length % 2 !== 0) {\n throw new Error(\"Invalid hex string length\");\n }\n const bytes = new Uint8Array(cleanHex.length / 2);\n for (let i = 0; i < cleanHex.length; i += 2) {\n bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16);\n }\n return bytes;\n}\nexport function uint8ArrayToHex(bytes) {\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n// instanceof\nexport class Class {\n constructor(..._args) { }\n}\n","import { $constructor } from \"./core.js\";\nimport * as util from \"./util.js\";\nconst initializer = (inst, def) => {\n inst.name = \"$ZodError\";\n Object.defineProperty(inst, \"_zod\", {\n value: inst._zod,\n enumerable: false,\n });\n Object.defineProperty(inst, \"issues\", {\n value: def,\n enumerable: false,\n });\n inst.message = JSON.stringify(def, util.jsonStringifyReplacer, 2);\n Object.defineProperty(inst, \"toString\", {\n value: () => inst.message,\n enumerable: false,\n });\n};\nexport const $ZodError = $constructor(\"$ZodError\", initializer);\nexport const $ZodRealError = $constructor(\"$ZodError\", initializer, { Parent: Error });\nexport function flattenError(error, mapper = (issue) => issue.message) {\n const fieldErrors = {};\n const formErrors = [];\n for (const sub of error.issues) {\n if (sub.path.length > 0) {\n fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];\n fieldErrors[sub.path[0]].push(mapper(sub));\n }\n else {\n formErrors.push(mapper(sub));\n }\n }\n return { formErrors, fieldErrors };\n}\nexport function formatError(error, mapper = (issue) => issue.message) {\n const fieldErrors = { _errors: [] };\n const processError = (error, path = []) => {\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path]));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else {\n const fullpath = [...path, ...issue.path];\n if (fullpath.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n }\n else {\n let curr = fieldErrors;\n let i = 0;\n while (i < fullpath.length) {\n const el = fullpath[i];\n const terminal = i === fullpath.length - 1;\n if (!terminal) {\n curr[el] = curr[el] || { _errors: [] };\n }\n else {\n curr[el] = curr[el] || { _errors: [] };\n curr[el]._errors.push(mapper(issue));\n }\n curr = curr[el];\n i++;\n }\n }\n }\n }\n };\n processError(error);\n return fieldErrors;\n}\nexport function treeifyError(error, mapper = (issue) => issue.message) {\n const result = { errors: [] };\n const processError = (error, path = []) => {\n var _a, _b;\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n // regular union error\n issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path]));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else {\n const fullpath = [...path, ...issue.path];\n if (fullpath.length === 0) {\n result.errors.push(mapper(issue));\n continue;\n }\n let curr = result;\n let i = 0;\n while (i < fullpath.length) {\n const el = fullpath[i];\n const terminal = i === fullpath.length - 1;\n if (typeof el === \"string\") {\n curr.properties ?? (curr.properties = {});\n (_a = curr.properties)[el] ?? (_a[el] = { errors: [] });\n curr = curr.properties[el];\n }\n else {\n curr.items ?? (curr.items = []);\n (_b = curr.items)[el] ?? (_b[el] = { errors: [] });\n curr = curr.items[el];\n }\n if (terminal) {\n curr.errors.push(mapper(issue));\n }\n i++;\n }\n }\n }\n };\n processError(error);\n return result;\n}\n/** Format a ZodError as a human-readable string in the following form.\n *\n * From\n *\n * ```ts\n * ZodError {\n * issues: [\n * {\n * expected: 'string',\n * code: 'invalid_type',\n * path: [ 'username' ],\n * message: 'Invalid input: expected string'\n * },\n * {\n * expected: 'number',\n * code: 'invalid_type',\n * path: [ 'favoriteNumbers', 1 ],\n * message: 'Invalid input: expected number'\n * }\n * ];\n * }\n * ```\n *\n * to\n *\n * ```\n * username\n * ✖ Expected number, received string at \"username\n * favoriteNumbers[0]\n * ✖ Invalid input: expected number\n * ```\n */\nexport function toDotPath(_path) {\n const segs = [];\n const path = _path.map((seg) => (typeof seg === \"object\" ? seg.key : seg));\n for (const seg of path) {\n if (typeof seg === \"number\")\n segs.push(`[${seg}]`);\n else if (typeof seg === \"symbol\")\n segs.push(`[${JSON.stringify(String(seg))}]`);\n else if (/[^\\w$]/.test(seg))\n segs.push(`[${JSON.stringify(seg)}]`);\n else {\n if (segs.length)\n segs.push(\".\");\n segs.push(seg);\n }\n }\n return segs.join(\"\");\n}\nexport function prettifyError(error) {\n const lines = [];\n // sort by path length\n const issues = [...error.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length);\n // Process each issue\n for (const issue of issues) {\n lines.push(`✖ ${issue.message}`);\n if (issue.path?.length)\n lines.push(` → at ${toDotPath(issue.path)}`);\n }\n // Convert Map to formatted string\n return lines.join(\"\\n\");\n}\n","import * as core from \"./core.js\";\nimport * as errors from \"./errors.js\";\nimport * as util from \"./util.js\";\nexport const _parse = (_Err) => (schema, value, _ctx, _params) => {\n const ctx = _ctx ? { ..._ctx, async: false } : { async: false };\n const result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n if (result.issues.length) {\n const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n util.captureStackTrace(e, _params?.callee);\n throw e;\n }\n return result.value;\n};\nexport const parse = /* @__PURE__*/ _parse(errors.$ZodRealError);\nexport const _parseAsync = (_Err) => async (schema, value, _ctx, params) => {\n const ctx = _ctx ? { ..._ctx, async: true } : { async: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n if (result.issues.length) {\n const e = new (params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n util.captureStackTrace(e, params?.callee);\n throw e;\n }\n return result.value;\n};\nexport const parseAsync = /* @__PURE__*/ _parseAsync(errors.$ZodRealError);\nexport const _safeParse = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, async: false } : { async: false };\n const result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n return result.issues.length\n ? {\n success: false,\n error: new (_Err ?? errors.$ZodError)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n }\n : { success: true, data: result.value };\n};\nexport const safeParse = /* @__PURE__*/ _safeParse(errors.$ZodRealError);\nexport const _safeParseAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, async: true } : { async: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n return result.issues.length\n ? {\n success: false,\n error: new _Err(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n }\n : { success: true, data: result.value };\n};\nexport const safeParseAsync = /* @__PURE__*/ _safeParseAsync(errors.$ZodRealError);\nexport const _encode = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return _parse(_Err)(schema, value, ctx);\n};\nexport const encode = /* @__PURE__*/ _encode(errors.$ZodRealError);\nexport const _decode = (_Err) => (schema, value, _ctx) => {\n return _parse(_Err)(schema, value, _ctx);\n};\nexport const decode = /* @__PURE__*/ _decode(errors.$ZodRealError);\nexport const _encodeAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return _parseAsync(_Err)(schema, value, ctx);\n};\nexport const encodeAsync = /* @__PURE__*/ _encodeAsync(errors.$ZodRealError);\nexport const _decodeAsync = (_Err) => async (schema, value, _ctx) => {\n return _parseAsync(_Err)(schema, value, _ctx);\n};\nexport const decodeAsync = /* @__PURE__*/ _decodeAsync(errors.$ZodRealError);\nexport const _safeEncode = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return _safeParse(_Err)(schema, value, ctx);\n};\nexport const safeEncode = /* @__PURE__*/ _safeEncode(errors.$ZodRealError);\nexport const _safeDecode = (_Err) => (schema, value, _ctx) => {\n return _safeParse(_Err)(schema, value, _ctx);\n};\nexport const safeDecode = /* @__PURE__*/ _safeDecode(errors.$ZodRealError);\nexport const _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return _safeParseAsync(_Err)(schema, value, ctx);\n};\nexport const safeEncodeAsync = /* @__PURE__*/ _safeEncodeAsync(errors.$ZodRealError);\nexport const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => {\n return _safeParseAsync(_Err)(schema, value, _ctx);\n};\nexport const safeDecodeAsync = /* @__PURE__*/ _safeDecodeAsync(errors.$ZodRealError);\n","import * as util from \"./util.js\";\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link cuid2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const cuid = /^[cC][0-9a-z]{6,}$/;\nexport const cuid2 = /^[0-9a-z]+$/;\nexport const ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;\nexport const xid = /^[0-9a-vA-V]{20}$/;\nexport const ksuid = /^[A-Za-z0-9]{27}$/;\nexport const nanoid = /^[a-zA-Z0-9_-]{21}$/;\n/** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */\nexport const duration = /^P(?:(\\d+W)|(?!.*W)(?=\\d|T\\d)(\\d+Y)?(\\d+M)?(\\d+D)?(T(?=\\d)(\\d+H)?(\\d+M)?(\\d+([.,]\\d+)?S)?)?)$/;\n/** Implements ISO 8601-2 extensions like explicit +- prefixes, mixing weeks with other units, and fractional/negative components. */\nexport const extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\\d+Y)|(?:[-+]?\\d+[.,]\\d+Y$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:(?:[-+]?\\d+W)|(?:[-+]?\\d+[.,]\\d+W$))?(?:(?:[-+]?\\d+D)|(?:[-+]?\\d+[.,]\\d+D$))?(?:T(?=[\\d+-])(?:(?:[-+]?\\d+H)|(?:[-+]?\\d+[.,]\\d+H$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:[-+]?\\d+(?:[.,]\\d+)?S)?)??$/;\n/** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */\nexport const guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;\n/** Returns a regex for validating an RFC 9562/4122 UUID.\n *\n * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */\nexport const uuid = (version) => {\n if (!version)\n return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;\n return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);\n};\nexport const uuid4 = /*@__PURE__*/ uuid(4);\nexport const uuid6 = /*@__PURE__*/ uuid(6);\nexport const uuid7 = /*@__PURE__*/ uuid(7);\n/** Practical email validation */\nexport const email = /^(?!\\.)(?!.*\\.\\.)([A-Za-z0-9_'+\\-\\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$/;\n/** Equivalent to the HTML5 input[type=email] validation implemented by browsers. Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email */\nexport const html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n/** The classic emailregex.com regex for RFC 5322-compliant emails */\nexport const rfc5322Email = /^(([^<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/;\n/** A loose regex that allows Unicode characters, enforces length limits, and that's about it. */\nexport const unicodeEmail = /^[^\\s@\"]{1,64}@[^\\s@]{1,255}$/u;\nexport const idnEmail = unicodeEmail;\nexport const browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression\nconst _emoji = `^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$`;\nexport function emoji() {\n return new RegExp(_emoji, \"u\");\n}\nexport const ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;\nexport const ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;\nexport const mac = (delimiter) => {\n const escapedDelim = util.escapeRegex(delimiter ?? \":\");\n return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`);\n};\nexport const cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/([0-9]|[1-2][0-9]|3[0-2])$/;\nexport const cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;\n// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript\nexport const base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;\nexport const base64url = /^[A-Za-z0-9_-]*$/;\n// based on https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address\n// export const hostname: RegExp = /^([a-zA-Z0-9-]+\\.)*[a-zA-Z0-9-]+$/;\nexport const hostname = /^(?=.{1,253}\\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\\.?$/;\nexport const domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,}$/;\nexport const httpProtocol = /^https?$/;\n// https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces)\n// E.164: leading digit must be 1-9; total digits (excluding '+') between 7-15\nexport const e164 = /^\\+[1-9]\\d{6,14}$/;\n// const dateSource = `((\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\\\d|30)|(02)-(0[1-9]|1\\\\d|2[0-8])))`;\nconst dateSource = `(?:(?:\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\\\d|30)|(?:02)-(?:0[1-9]|1\\\\d|2[0-8])))`;\nexport const date = /*@__PURE__*/ new RegExp(`^${dateSource}$`);\nfunction timeSource(args) {\n const hhmm = `(?:[01]\\\\d|2[0-3]):[0-5]\\\\d`;\n const regex = typeof args.precision === \"number\"\n ? args.precision === -1\n ? `${hhmm}`\n : args.precision === 0\n ? `${hhmm}:[0-5]\\\\d`\n : `${hhmm}:[0-5]\\\\d\\\\.\\\\d{${args.precision}}`\n : `${hhmm}(?::[0-5]\\\\d(?:\\\\.\\\\d+)?)?`;\n return regex;\n}\nexport function time(args) {\n return new RegExp(`^${timeSource(args)}$`);\n}\n// Adapted from https://stackoverflow.com/a/3143231\nexport function datetime(args) {\n const time = timeSource({ precision: args.precision });\n const opts = [\"Z\"];\n if (args.local)\n opts.push(\"\");\n // if (args.offset) opts.push(`([+-]\\\\d{2}:\\\\d{2})`);\n if (args.offset)\n opts.push(`([+-](?:[01]\\\\d|2[0-3]):[0-5]\\\\d)`);\n const timeRegex = `${time}(?:${opts.join(\"|\")})`;\n return new RegExp(`^${dateSource}T(?:${timeRegex})$`);\n}\nexport const string = (params) => {\n const regex = params ? `[\\\\s\\\\S]{${params?.minimum ?? 0},${params?.maximum ?? \"\"}}` : `[\\\\s\\\\S]*`;\n return new RegExp(`^${regex}$`);\n};\nexport const bigint = /^-?\\d+n?$/;\nexport const integer = /^-?\\d+$/;\nexport const number = /^-?\\d+(?:\\.\\d+)?$/;\nexport const boolean = /^(?:true|false)$/i;\nconst _null = /^null$/i;\nexport { _null as null };\nconst _undefined = /^undefined$/i;\nexport { _undefined as undefined };\n// regex for string with no uppercase letters\nexport const lowercase = /^[^A-Z]*$/;\n// regex for string with no lowercase letters\nexport const uppercase = /^[^a-z]*$/;\n// regex for hexadecimal strings (any length)\nexport const hex = /^[0-9a-fA-F]*$/;\n// Hash regexes for different algorithms and encodings\n// Helper function to create base64 regex with exact length and padding\nfunction fixedBase64(bodyLength, padding) {\n return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`);\n}\n// Helper function to create base64url regex with exact length (no padding)\nfunction fixedBase64url(length) {\n return new RegExp(`^[A-Za-z0-9_-]{${length}}$`);\n}\n// MD5 (16 bytes): base64 = 24 chars total (22 + \"==\")\nexport const md5_hex = /^[0-9a-fA-F]{32}$/;\nexport const md5_base64 = /*@__PURE__*/ fixedBase64(22, \"==\");\nexport const md5_base64url = /*@__PURE__*/ fixedBase64url(22);\n// SHA1 (20 bytes): base64 = 28 chars total (27 + \"=\")\nexport const sha1_hex = /^[0-9a-fA-F]{40}$/;\nexport const sha1_base64 = /*@__PURE__*/ fixedBase64(27, \"=\");\nexport const sha1_base64url = /*@__PURE__*/ fixedBase64url(27);\n// SHA256 (32 bytes): base64 = 44 chars total (43 + \"=\")\nexport const sha256_hex = /^[0-9a-fA-F]{64}$/;\nexport const sha256_base64 = /*@__PURE__*/ fixedBase64(43, \"=\");\nexport const sha256_base64url = /*@__PURE__*/ fixedBase64url(43);\n// SHA384 (48 bytes): base64 = 64 chars total (no padding)\nexport const sha384_hex = /^[0-9a-fA-F]{96}$/;\nexport const sha384_base64 = /*@__PURE__*/ fixedBase64(64, \"\");\nexport const sha384_base64url = /*@__PURE__*/ fixedBase64url(64);\n// SHA512 (64 bytes): base64 = 88 chars total (86 + \"==\")\nexport const sha512_hex = /^[0-9a-fA-F]{128}$/;\nexport const sha512_base64 = /*@__PURE__*/ fixedBase64(86, \"==\");\nexport const sha512_base64url = /*@__PURE__*/ fixedBase64url(86);\n","export const version = {\n major: 4,\n minor: 4,\n patch: 3,\n};\n","import * as checks from \"./checks.js\";\nimport * as core from \"./core.js\";\nimport { Doc } from \"./doc.js\";\nimport { parse, parseAsync, safeParse, safeParseAsync } from \"./parse.js\";\nimport * as regexes from \"./regexes.js\";\nimport * as util from \"./util.js\";\nimport { version } from \"./versions.js\";\nexport const $ZodType = /*@__PURE__*/ core.$constructor(\"$ZodType\", (inst, def) => {\n var _a;\n inst ?? (inst = {});\n inst._zod.def = def; // set _def property\n inst._zod.bag = inst._zod.bag || {}; // initialize _bag object\n inst._zod.version = version;\n const checks = [...(inst._zod.def.checks ?? [])];\n // if inst is itself a checks.$ZodCheck, run it as a check\n if (inst._zod.traits.has(\"$ZodCheck\")) {\n checks.unshift(inst);\n }\n for (const ch of checks) {\n for (const fn of ch._zod.onattach) {\n fn(inst);\n }\n }\n if (checks.length === 0) {\n // deferred initializer\n // inst._zod.parse is not yet defined\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n inst._zod.deferred?.push(() => {\n inst._zod.run = inst._zod.parse;\n });\n }\n else {\n const runChecks = (payload, checks, ctx) => {\n let isAborted = util.aborted(payload);\n let asyncResult;\n for (const ch of checks) {\n if (ch._zod.def.when) {\n if (util.explicitlyAborted(payload))\n continue;\n const shouldRun = ch._zod.def.when(payload);\n if (!shouldRun)\n continue;\n }\n else if (isAborted) {\n continue;\n }\n const currLen = payload.issues.length;\n const _ = ch._zod.check(payload);\n if (_ instanceof Promise && ctx?.async === false) {\n throw new core.$ZodAsyncError();\n }\n if (asyncResult || _ instanceof Promise) {\n asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {\n await _;\n const nextLen = payload.issues.length;\n if (nextLen === currLen)\n return;\n if (!isAborted)\n isAborted = util.aborted(payload, currLen);\n });\n }\n else {\n const nextLen = payload.issues.length;\n if (nextLen === currLen)\n continue;\n if (!isAborted)\n isAborted = util.aborted(payload, currLen);\n }\n }\n if (asyncResult) {\n return asyncResult.then(() => {\n return payload;\n });\n }\n return payload;\n };\n const handleCanaryResult = (canary, payload, ctx) => {\n // abort if the canary is aborted\n if (util.aborted(canary)) {\n canary.aborted = true;\n return canary;\n }\n // run checks first, then\n const checkResult = runChecks(payload, checks, ctx);\n if (checkResult instanceof Promise) {\n if (ctx.async === false)\n throw new core.$ZodAsyncError();\n return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx));\n }\n return inst._zod.parse(checkResult, ctx);\n };\n inst._zod.run = (payload, ctx) => {\n if (ctx.skipChecks) {\n return inst._zod.parse(payload, ctx);\n }\n if (ctx.direction === \"backward\") {\n // run canary\n // initial pass (no checks)\n const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true });\n if (canary instanceof Promise) {\n return canary.then((canary) => {\n return handleCanaryResult(canary, payload, ctx);\n });\n }\n return handleCanaryResult(canary, payload, ctx);\n }\n // forward\n const result = inst._zod.parse(payload, ctx);\n if (result instanceof Promise) {\n if (ctx.async === false)\n throw new core.$ZodAsyncError();\n return result.then((result) => runChecks(result, checks, ctx));\n }\n return runChecks(result, checks, ctx);\n };\n }\n // Lazy initialize ~standard to avoid creating objects for every schema\n util.defineLazy(inst, \"~standard\", () => ({\n validate: (value) => {\n try {\n const r = safeParse(inst, value);\n return r.success ? { value: r.data } : { issues: r.error?.issues };\n }\n catch (_) {\n return safeParseAsync(inst, value).then((r) => (r.success ? { value: r.data } : { issues: r.error?.issues }));\n }\n },\n vendor: \"zod\",\n version: 1,\n }));\n});\nexport { clone } from \"./util.js\";\nexport const $ZodString = /*@__PURE__*/ core.$constructor(\"$ZodString\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = [...(inst?._zod.bag?.patterns ?? [])].pop() ?? regexes.string(inst._zod.bag);\n inst._zod.parse = (payload, _) => {\n if (def.coerce)\n try {\n payload.value = String(payload.value);\n }\n catch (_) { }\n if (typeof payload.value === \"string\")\n return payload;\n payload.issues.push({\n expected: \"string\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodStringFormat\", (inst, def) => {\n // check initialization must come first\n checks.$ZodCheckStringFormat.init(inst, def);\n $ZodString.init(inst, def);\n});\nexport const $ZodGUID = /*@__PURE__*/ core.$constructor(\"$ZodGUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.guid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodUUID = /*@__PURE__*/ core.$constructor(\"$ZodUUID\", (inst, def) => {\n if (def.version) {\n const versionMap = {\n v1: 1,\n v2: 2,\n v3: 3,\n v4: 4,\n v5: 5,\n v6: 6,\n v7: 7,\n v8: 8,\n };\n const v = versionMap[def.version];\n if (v === undefined)\n throw new Error(`Invalid UUID version: \"${def.version}\"`);\n def.pattern ?? (def.pattern = regexes.uuid(v));\n }\n else\n def.pattern ?? (def.pattern = regexes.uuid());\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodEmail = /*@__PURE__*/ core.$constructor(\"$ZodEmail\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.email);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodURL = /*@__PURE__*/ core.$constructor(\"$ZodURL\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n try {\n // Trim whitespace from input\n const trimmed = payload.value.trim();\n // When normalize is off, require :// for http/https URLs\n // This prevents strings like \"http:example.com\" or \"https:/path\" from being silently accepted\n if (!def.normalize && def.protocol?.source === regexes.httpProtocol.source) {\n if (!/^https?:\\/\\//i.test(trimmed)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid URL format\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n return;\n }\n }\n // @ts-ignore\n const url = new URL(trimmed);\n if (def.hostname) {\n def.hostname.lastIndex = 0;\n if (!def.hostname.test(url.hostname)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid hostname\",\n pattern: def.hostname.source,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n }\n if (def.protocol) {\n def.protocol.lastIndex = 0;\n if (!def.protocol.test(url.protocol.endsWith(\":\") ? url.protocol.slice(0, -1) : url.protocol)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid protocol\",\n pattern: def.protocol.source,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n }\n // Set the output value based on normalize flag\n if (def.normalize) {\n // Use normalized URL\n payload.value = url.href;\n }\n else {\n // Preserve the original input (trimmed)\n payload.value = trimmed;\n }\n return;\n }\n catch (_) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodEmoji = /*@__PURE__*/ core.$constructor(\"$ZodEmoji\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.emoji());\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodNanoID = /*@__PURE__*/ core.$constructor(\"$ZodNanoID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.nanoid);\n $ZodStringFormat.init(inst, def);\n});\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link $ZodCUID2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const $ZodCUID = /*@__PURE__*/ core.$constructor(\"$ZodCUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cuid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCUID2 = /*@__PURE__*/ core.$constructor(\"$ZodCUID2\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cuid2);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodULID = /*@__PURE__*/ core.$constructor(\"$ZodULID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ulid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodXID = /*@__PURE__*/ core.$constructor(\"$ZodXID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.xid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodKSUID = /*@__PURE__*/ core.$constructor(\"$ZodKSUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ksuid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODateTime = /*@__PURE__*/ core.$constructor(\"$ZodISODateTime\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.datetime(def));\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODate = /*@__PURE__*/ core.$constructor(\"$ZodISODate\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.date);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISOTime = /*@__PURE__*/ core.$constructor(\"$ZodISOTime\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.time(def));\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODuration = /*@__PURE__*/ core.$constructor(\"$ZodISODuration\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.duration);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodIPv4 = /*@__PURE__*/ core.$constructor(\"$ZodIPv4\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ipv4);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.format = `ipv4`;\n});\nexport const $ZodIPv6 = /*@__PURE__*/ core.$constructor(\"$ZodIPv6\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ipv6);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.format = `ipv6`;\n inst._zod.check = (payload) => {\n try {\n // @ts-ignore\n new URL(`http://[${payload.value}]`);\n // return;\n }\n catch {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"ipv6\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodMAC = /*@__PURE__*/ core.$constructor(\"$ZodMAC\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.mac(def.delimiter));\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.format = `mac`;\n});\nexport const $ZodCIDRv4 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv4\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cidrv4);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCIDRv6 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv6\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cidrv6); // not used for validation\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n const parts = payload.value.split(\"/\");\n try {\n if (parts.length !== 2)\n throw new Error();\n const [address, prefix] = parts;\n if (!prefix)\n throw new Error();\n const prefixNum = Number(prefix);\n if (`${prefixNum}` !== prefix)\n throw new Error();\n if (prefixNum < 0 || prefixNum > 128)\n throw new Error();\n // @ts-ignore\n new URL(`http://[${address}]`);\n }\n catch {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"cidrv6\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\n////////////////////////////// ZodBase64 //////////////////////////////\nexport function isValidBase64(data) {\n if (data === \"\")\n return true;\n // atob ignores whitespace, so reject it up front.\n if (/\\s/.test(data))\n return false;\n if (data.length % 4 !== 0)\n return false;\n try {\n // @ts-ignore\n atob(data);\n return true;\n }\n catch {\n return false;\n }\n}\nexport const $ZodBase64 = /*@__PURE__*/ core.$constructor(\"$ZodBase64\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.base64);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.contentEncoding = \"base64\";\n inst._zod.check = (payload) => {\n if (isValidBase64(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"base64\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n////////////////////////////// ZodBase64 //////////////////////////////\nexport function isValidBase64URL(data) {\n if (!regexes.base64url.test(data))\n return false;\n const base64 = data.replace(/[-_]/g, (c) => (c === \"-\" ? \"+\" : \"/\"));\n const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, \"=\");\n return isValidBase64(padded);\n}\nexport const $ZodBase64URL = /*@__PURE__*/ core.$constructor(\"$ZodBase64URL\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.base64url);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.contentEncoding = \"base64url\";\n inst._zod.check = (payload) => {\n if (isValidBase64URL(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"base64url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodE164 = /*@__PURE__*/ core.$constructor(\"$ZodE164\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.e164);\n $ZodStringFormat.init(inst, def);\n});\n////////////////////////////// ZodJWT //////////////////////////////\nexport function isValidJWT(token, algorithm = null) {\n try {\n const tokensParts = token.split(\".\");\n if (tokensParts.length !== 3)\n return false;\n const [header] = tokensParts;\n if (!header)\n return false;\n // @ts-ignore\n const parsedHeader = JSON.parse(atob(header));\n if (\"typ\" in parsedHeader && parsedHeader?.typ !== \"JWT\")\n return false;\n if (!parsedHeader.alg)\n return false;\n if (algorithm && (!(\"alg\" in parsedHeader) || parsedHeader.alg !== algorithm))\n return false;\n return true;\n }\n catch {\n return false;\n }\n}\nexport const $ZodJWT = /*@__PURE__*/ core.$constructor(\"$ZodJWT\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidJWT(payload.value, def.alg))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"jwt\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCustomStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodCustomStringFormat\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (def.fn(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: def.format,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodNumber = /*@__PURE__*/ core.$constructor(\"$ZodNumber\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = inst._zod.bag.pattern ?? regexes.number;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = Number(payload.value);\n }\n catch (_) { }\n const input = payload.value;\n if (typeof input === \"number\" && !Number.isNaN(input) && Number.isFinite(input)) {\n return payload;\n }\n const received = typeof input === \"number\"\n ? Number.isNaN(input)\n ? \"NaN\"\n : !Number.isFinite(input)\n ? \"Infinity\"\n : undefined\n : undefined;\n payload.issues.push({\n expected: \"number\",\n code: \"invalid_type\",\n input,\n inst,\n ...(received ? { received } : {}),\n });\n return payload;\n };\n});\nexport const $ZodNumberFormat = /*@__PURE__*/ core.$constructor(\"$ZodNumberFormat\", (inst, def) => {\n checks.$ZodCheckNumberFormat.init(inst, def);\n $ZodNumber.init(inst, def); // no format checks\n});\nexport const $ZodBoolean = /*@__PURE__*/ core.$constructor(\"$ZodBoolean\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.boolean;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = Boolean(payload.value);\n }\n catch (_) { }\n const input = payload.value;\n if (typeof input === \"boolean\")\n return payload;\n payload.issues.push({\n expected: \"boolean\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodBigInt = /*@__PURE__*/ core.$constructor(\"$ZodBigInt\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.bigint;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = BigInt(payload.value);\n }\n catch (_) { }\n if (typeof payload.value === \"bigint\")\n return payload;\n payload.issues.push({\n expected: \"bigint\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodBigIntFormat = /*@__PURE__*/ core.$constructor(\"$ZodBigIntFormat\", (inst, def) => {\n checks.$ZodCheckBigIntFormat.init(inst, def);\n $ZodBigInt.init(inst, def); // no format checks\n});\nexport const $ZodSymbol = /*@__PURE__*/ core.$constructor(\"$ZodSymbol\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"symbol\")\n return payload;\n payload.issues.push({\n expected: \"symbol\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodUndefined = /*@__PURE__*/ core.$constructor(\"$ZodUndefined\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.undefined;\n inst._zod.values = new Set([undefined]);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"undefined\")\n return payload;\n payload.issues.push({\n expected: \"undefined\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodNull = /*@__PURE__*/ core.$constructor(\"$ZodNull\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.null;\n inst._zod.values = new Set([null]);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (input === null)\n return payload;\n payload.issues.push({\n expected: \"null\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodAny = /*@__PURE__*/ core.$constructor(\"$ZodAny\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload) => payload;\n});\nexport const $ZodUnknown = /*@__PURE__*/ core.$constructor(\"$ZodUnknown\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload) => payload;\n});\nexport const $ZodNever = /*@__PURE__*/ core.$constructor(\"$ZodNever\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n payload.issues.push({\n expected: \"never\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodVoid = /*@__PURE__*/ core.$constructor(\"$ZodVoid\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"undefined\")\n return payload;\n payload.issues.push({\n expected: \"void\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodDate = /*@__PURE__*/ core.$constructor(\"$ZodDate\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce) {\n try {\n payload.value = new Date(payload.value);\n }\n catch (_err) { }\n }\n const input = payload.value;\n const isDate = input instanceof Date;\n const isValidDate = isDate && !Number.isNaN(input.getTime());\n if (isValidDate)\n return payload;\n payload.issues.push({\n expected: \"date\",\n code: \"invalid_type\",\n input,\n ...(isDate ? { received: \"Invalid Date\" } : {}),\n inst,\n });\n return payload;\n };\n});\nfunction handleArrayResult(result, final, index) {\n if (result.issues.length) {\n final.issues.push(...util.prefixIssues(index, result.issues));\n }\n final.value[index] = result.value;\n}\nexport const $ZodArray = /*@__PURE__*/ core.$constructor(\"$ZodArray\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!Array.isArray(input)) {\n payload.issues.push({\n expected: \"array\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n payload.value = Array(input.length);\n const proms = [];\n for (let i = 0; i < input.length; i++) {\n const item = input[i];\n const result = def.element._zod.run({\n value: item,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleArrayResult(result, payload, i)));\n }\n else {\n handleArrayResult(result, payload, i);\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => payload);\n }\n return payload; //handleArrayResultsAsync(parseResults, final);\n };\n});\nfunction handlePropertyResult(result, final, key, input, isOptionalIn, isOptionalOut) {\n const isPresent = key in input;\n if (result.issues.length) {\n // For optional-in/out schemas, ignore errors on absent keys.\n if (isOptionalIn && isOptionalOut && !isPresent) {\n return;\n }\n final.issues.push(...util.prefixIssues(key, result.issues));\n }\n if (!isPresent && !isOptionalIn) {\n if (!result.issues.length) {\n final.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: undefined,\n path: [key],\n });\n }\n return;\n }\n if (result.value === undefined) {\n if (isPresent) {\n final.value[key] = undefined;\n }\n }\n else {\n final.value[key] = result.value;\n }\n}\nfunction normalizeDef(def) {\n const keys = Object.keys(def.shape);\n for (const k of keys) {\n if (!def.shape?.[k]?._zod?.traits?.has(\"$ZodType\")) {\n throw new Error(`Invalid element at key \"${k}\": expected a Zod schema`);\n }\n }\n const okeys = util.optionalKeys(def.shape);\n return {\n ...def,\n keys,\n keySet: new Set(keys),\n numKeys: keys.length,\n optionalKeys: new Set(okeys),\n };\n}\nfunction handleCatchall(proms, input, payload, ctx, def, inst) {\n const unrecognized = [];\n const keySet = def.keySet;\n const _catchall = def.catchall._zod;\n const t = _catchall.def.type;\n const isOptionalIn = _catchall.optin === \"optional\";\n const isOptionalOut = _catchall.optout === \"optional\";\n for (const key in input) {\n // skip __proto__ so it can't replace the result prototype via the\n // assignment setter on the plain {} we build into\n if (key === \"__proto__\")\n continue;\n if (keySet.has(key))\n continue;\n if (t === \"never\") {\n unrecognized.push(key);\n continue;\n }\n const r = _catchall.run({ value: input[key], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut)));\n }\n else {\n handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut);\n }\n }\n if (unrecognized.length) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n keys: unrecognized,\n input,\n inst,\n });\n }\n if (!proms.length)\n return payload;\n return Promise.all(proms).then(() => {\n return payload;\n });\n}\nexport const $ZodObject = /*@__PURE__*/ core.$constructor(\"$ZodObject\", (inst, def) => {\n // requires cast because technically $ZodObject doesn't extend\n $ZodType.init(inst, def);\n // const sh = def.shape;\n const desc = Object.getOwnPropertyDescriptor(def, \"shape\");\n if (!desc?.get) {\n const sh = def.shape;\n Object.defineProperty(def, \"shape\", {\n get: () => {\n const newSh = { ...sh };\n Object.defineProperty(def, \"shape\", {\n value: newSh,\n });\n return newSh;\n },\n });\n }\n const _normalized = util.cached(() => normalizeDef(def));\n util.defineLazy(inst._zod, \"propValues\", () => {\n const shape = def.shape;\n const propValues = {};\n for (const key in shape) {\n const field = shape[key]._zod;\n if (field.values) {\n propValues[key] ?? (propValues[key] = new Set());\n for (const v of field.values)\n propValues[key].add(v);\n }\n }\n return propValues;\n });\n const isObject = util.isObject;\n const catchall = def.catchall;\n let value;\n inst._zod.parse = (payload, ctx) => {\n value ?? (value = _normalized.value);\n const input = payload.value;\n if (!isObject(input)) {\n payload.issues.push({\n expected: \"object\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n payload.value = {};\n const proms = [];\n const shape = value.shape;\n for (const key of value.keys) {\n const el = shape[key];\n const isOptionalIn = el._zod.optin === \"optional\";\n const isOptionalOut = el._zod.optout === \"optional\";\n const r = el._zod.run({ value: input[key], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut)));\n }\n else {\n handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut);\n }\n }\n if (!catchall) {\n return proms.length ? Promise.all(proms).then(() => payload) : payload;\n }\n return handleCatchall(proms, input, payload, ctx, _normalized.value, inst);\n };\n});\nexport const $ZodObjectJIT = /*@__PURE__*/ core.$constructor(\"$ZodObjectJIT\", (inst, def) => {\n // requires cast because technically $ZodObject doesn't extend\n $ZodObject.init(inst, def);\n const superParse = inst._zod.parse;\n const _normalized = util.cached(() => normalizeDef(def));\n const generateFastpass = (shape) => {\n const doc = new Doc([\"shape\", \"payload\", \"ctx\"]);\n const normalized = _normalized.value;\n const parseStr = (key) => {\n const k = util.esc(key);\n return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;\n };\n doc.write(`const input = payload.value;`);\n const ids = Object.create(null);\n let counter = 0;\n for (const key of normalized.keys) {\n ids[key] = `key_${counter++}`;\n }\n // A: preserve key order {\n doc.write(`const newResult = {};`);\n for (const key of normalized.keys) {\n const id = ids[key];\n const k = util.esc(key);\n const schema = shape[key];\n const isOptionalIn = schema?._zod?.optin === \"optional\";\n const isOptionalOut = schema?._zod?.optout === \"optional\";\n doc.write(`const ${id} = ${parseStr(key)};`);\n if (isOptionalIn && isOptionalOut) {\n // For optional-in/out schemas, ignore errors on absent keys\n doc.write(`\n if (${id}.issues.length) {\n if (${k} in input) {\n payload.issues = payload.issues.concat(${id}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${k}, ...iss.path] : [${k}]\n })));\n }\n }\n \n if (${id}.value === undefined) {\n if (${k} in input) {\n newResult[${k}] = undefined;\n }\n } else {\n newResult[${k}] = ${id}.value;\n }\n \n `);\n }\n else if (!isOptionalIn) {\n doc.write(`\n const ${id}_present = ${k} in input;\n if (${id}.issues.length) {\n payload.issues = payload.issues.concat(${id}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${k}, ...iss.path] : [${k}]\n })));\n }\n if (!${id}_present && !${id}.issues.length) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: undefined,\n path: [${k}]\n });\n }\n\n if (${id}_present) {\n if (${id}.value === undefined) {\n newResult[${k}] = undefined;\n } else {\n newResult[${k}] = ${id}.value;\n }\n }\n\n `);\n }\n else {\n doc.write(`\n if (${id}.issues.length) {\n payload.issues = payload.issues.concat(${id}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${k}, ...iss.path] : [${k}]\n })));\n }\n \n if (${id}.value === undefined) {\n if (${k} in input) {\n newResult[${k}] = undefined;\n }\n } else {\n newResult[${k}] = ${id}.value;\n }\n \n `);\n }\n }\n doc.write(`payload.value = newResult;`);\n doc.write(`return payload;`);\n const fn = doc.compile();\n return (payload, ctx) => fn(shape, payload, ctx);\n };\n let fastpass;\n const isObject = util.isObject;\n const jit = !core.globalConfig.jitless;\n const allowsEval = util.allowsEval;\n const fastEnabled = jit && allowsEval.value; // && !def.catchall;\n const catchall = def.catchall;\n let value;\n inst._zod.parse = (payload, ctx) => {\n value ?? (value = _normalized.value);\n const input = payload.value;\n if (!isObject(input)) {\n payload.issues.push({\n expected: \"object\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {\n // always synchronous\n if (!fastpass)\n fastpass = generateFastpass(def.shape);\n payload = fastpass(payload, ctx);\n if (!catchall)\n return payload;\n return handleCatchall([], input, payload, ctx, value, inst);\n }\n return superParse(payload, ctx);\n };\n});\nfunction handleUnionResults(results, final, inst, ctx) {\n for (const result of results) {\n if (result.issues.length === 0) {\n final.value = result.value;\n return final;\n }\n }\n const nonaborted = results.filter((r) => !util.aborted(r));\n if (nonaborted.length === 1) {\n final.value = nonaborted[0].value;\n return nonaborted[0];\n }\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n });\n return final;\n}\nexport const $ZodUnion = /*@__PURE__*/ core.$constructor(\"$ZodUnion\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"optin\", () => def.options.some((o) => o._zod.optin === \"optional\") ? \"optional\" : undefined);\n util.defineLazy(inst._zod, \"optout\", () => def.options.some((o) => o._zod.optout === \"optional\") ? \"optional\" : undefined);\n util.defineLazy(inst._zod, \"values\", () => {\n if (def.options.every((o) => o._zod.values)) {\n return new Set(def.options.flatMap((option) => Array.from(option._zod.values)));\n }\n return undefined;\n });\n util.defineLazy(inst._zod, \"pattern\", () => {\n if (def.options.every((o) => o._zod.pattern)) {\n const patterns = def.options.map((o) => o._zod.pattern);\n return new RegExp(`^(${patterns.map((p) => util.cleanRegex(p.source)).join(\"|\")})$`);\n }\n return undefined;\n });\n const first = def.options.length === 1 ? def.options[0]._zod.run : null;\n inst._zod.parse = (payload, ctx) => {\n if (first) {\n return first(payload, ctx);\n }\n let async = false;\n const results = [];\n for (const option of def.options) {\n const result = option._zod.run({\n value: payload.value,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n results.push(result);\n async = true;\n }\n else {\n if (result.issues.length === 0)\n return result;\n results.push(result);\n }\n }\n if (!async)\n return handleUnionResults(results, payload, inst, ctx);\n return Promise.all(results).then((results) => {\n return handleUnionResults(results, payload, inst, ctx);\n });\n };\n});\nfunction handleExclusiveUnionResults(results, final, inst, ctx) {\n const successes = results.filter((r) => r.issues.length === 0);\n if (successes.length === 1) {\n final.value = successes[0].value;\n return final;\n }\n if (successes.length === 0) {\n // No matches - same as regular union\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n });\n }\n else {\n // Multiple matches - exclusive union failure\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: [],\n inclusive: false,\n });\n }\n return final;\n}\nexport const $ZodXor = /*@__PURE__*/ core.$constructor(\"$ZodXor\", (inst, def) => {\n $ZodUnion.init(inst, def);\n def.inclusive = false;\n const first = def.options.length === 1 ? def.options[0]._zod.run : null;\n inst._zod.parse = (payload, ctx) => {\n if (first) {\n return first(payload, ctx);\n }\n let async = false;\n const results = [];\n for (const option of def.options) {\n const result = option._zod.run({\n value: payload.value,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n results.push(result);\n async = true;\n }\n else {\n results.push(result);\n }\n }\n if (!async)\n return handleExclusiveUnionResults(results, payload, inst, ctx);\n return Promise.all(results).then((results) => {\n return handleExclusiveUnionResults(results, payload, inst, ctx);\n });\n };\n});\nexport const $ZodDiscriminatedUnion = \n/*@__PURE__*/\ncore.$constructor(\"$ZodDiscriminatedUnion\", (inst, def) => {\n def.inclusive = false;\n $ZodUnion.init(inst, def);\n const _super = inst._zod.parse;\n util.defineLazy(inst._zod, \"propValues\", () => {\n const propValues = {};\n for (const option of def.options) {\n const pv = option._zod.propValues;\n if (!pv || Object.keys(pv).length === 0)\n throw new Error(`Invalid discriminated union option at index \"${def.options.indexOf(option)}\"`);\n for (const [k, v] of Object.entries(pv)) {\n if (!propValues[k])\n propValues[k] = new Set();\n for (const val of v) {\n propValues[k].add(val);\n }\n }\n }\n return propValues;\n });\n const disc = util.cached(() => {\n const opts = def.options;\n const map = new Map();\n for (const o of opts) {\n const values = o._zod.propValues?.[def.discriminator];\n if (!values || values.size === 0)\n throw new Error(`Invalid discriminated union option at index \"${def.options.indexOf(o)}\"`);\n for (const v of values) {\n if (map.has(v)) {\n throw new Error(`Duplicate discriminator value \"${String(v)}\"`);\n }\n map.set(v, o);\n }\n }\n return map;\n });\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!util.isObject(input)) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"object\",\n input,\n inst,\n });\n return payload;\n }\n const opt = disc.value.get(input?.[def.discriminator]);\n if (opt) {\n return opt._zod.run(payload, ctx);\n }\n // Fall back to union matching when the fast discriminator path fails:\n // - explicitly enabled via unionFallback, or\n // - during backward direction (encode), since codec-based discriminators\n // have different values in forward vs backward directions\n if (def.unionFallback || ctx.direction === \"backward\") {\n return _super(payload, ctx);\n }\n // no matching discriminator\n payload.issues.push({\n code: \"invalid_union\",\n errors: [],\n note: \"No matching discriminator\",\n discriminator: def.discriminator,\n options: Array.from(disc.value.keys()),\n input,\n path: [def.discriminator],\n inst,\n });\n return payload;\n };\n});\nexport const $ZodIntersection = /*@__PURE__*/ core.$constructor(\"$ZodIntersection\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n const left = def.left._zod.run({ value: input, issues: [] }, ctx);\n const right = def.right._zod.run({ value: input, issues: [] }, ctx);\n const async = left instanceof Promise || right instanceof Promise;\n if (async) {\n return Promise.all([left, right]).then(([left, right]) => {\n return handleIntersectionResults(payload, left, right);\n });\n }\n return handleIntersectionResults(payload, left, right);\n };\n});\nfunction mergeValues(a, b) {\n // const aType = parse.t(a);\n // const bType = parse.t(b);\n if (a === b) {\n return { valid: true, data: a };\n }\n if (a instanceof Date && b instanceof Date && +a === +b) {\n return { valid: true, data: a };\n }\n if (util.isPlainObject(a) && util.isPlainObject(b)) {\n const bKeys = Object.keys(b);\n const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);\n const newObj = { ...a, ...b };\n for (const key of sharedKeys) {\n const sharedValue = mergeValues(a[key], b[key]);\n if (!sharedValue.valid) {\n return {\n valid: false,\n mergeErrorPath: [key, ...sharedValue.mergeErrorPath],\n };\n }\n newObj[key] = sharedValue.data;\n }\n return { valid: true, data: newObj };\n }\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) {\n return { valid: false, mergeErrorPath: [] };\n }\n const newArray = [];\n for (let index = 0; index < a.length; index++) {\n const itemA = a[index];\n const itemB = b[index];\n const sharedValue = mergeValues(itemA, itemB);\n if (!sharedValue.valid) {\n return {\n valid: false,\n mergeErrorPath: [index, ...sharedValue.mergeErrorPath],\n };\n }\n newArray.push(sharedValue.data);\n }\n return { valid: true, data: newArray };\n }\n return { valid: false, mergeErrorPath: [] };\n}\nfunction handleIntersectionResults(result, left, right) {\n // Track which side(s) report each key as unrecognized\n const unrecKeys = new Map();\n let unrecIssue;\n for (const iss of left.issues) {\n if (iss.code === \"unrecognized_keys\") {\n unrecIssue ?? (unrecIssue = iss);\n for (const k of iss.keys) {\n if (!unrecKeys.has(k))\n unrecKeys.set(k, {});\n unrecKeys.get(k).l = true;\n }\n }\n else {\n result.issues.push(iss);\n }\n }\n for (const iss of right.issues) {\n if (iss.code === \"unrecognized_keys\") {\n for (const k of iss.keys) {\n if (!unrecKeys.has(k))\n unrecKeys.set(k, {});\n unrecKeys.get(k).r = true;\n }\n }\n else {\n result.issues.push(iss);\n }\n }\n // Report only keys unrecognized by BOTH sides\n const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k);\n if (bothKeys.length && unrecIssue) {\n result.issues.push({ ...unrecIssue, keys: bothKeys });\n }\n if (util.aborted(result))\n return result;\n const merged = mergeValues(left.value, right.value);\n if (!merged.valid) {\n throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`);\n }\n result.value = merged.data;\n return result;\n}\nexport const $ZodTuple = /*@__PURE__*/ core.$constructor(\"$ZodTuple\", (inst, def) => {\n $ZodType.init(inst, def);\n const items = def.items;\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!Array.isArray(input)) {\n payload.issues.push({\n input,\n inst,\n expected: \"tuple\",\n code: \"invalid_type\",\n });\n return payload;\n }\n payload.value = [];\n const proms = [];\n const optinStart = getTupleOptStart(items, \"optin\");\n const optoutStart = getTupleOptStart(items, \"optout\");\n if (!def.rest) {\n if (input.length < optinStart) {\n payload.issues.push({\n code: \"too_small\",\n minimum: optinStart,\n inclusive: true,\n input,\n inst,\n origin: \"array\",\n });\n return payload;\n }\n if (input.length > items.length) {\n payload.issues.push({\n code: \"too_big\",\n maximum: items.length,\n inclusive: true,\n input,\n inst,\n origin: \"array\",\n });\n }\n }\n // Run every item in parallel, collecting results into an indexed\n // array. The post-processing in `handleTupleResults` walks them in\n // order so it can decide whether an absent optional-output error can\n // truncate the tail or must be reported to preserve required output.\n const itemResults = new Array(items.length);\n for (let i = 0; i < items.length; i++) {\n const r = items[i]._zod.run({ value: input[i], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((rr) => {\n itemResults[i] = rr;\n }));\n }\n else {\n itemResults[i] = r;\n }\n }\n if (def.rest) {\n let i = items.length - 1;\n const rest = input.slice(items.length);\n for (const el of rest) {\n i++;\n const result = def.rest._zod.run({ value: el, issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((r) => handleTupleResult(r, payload, i)));\n }\n else {\n handleTupleResult(result, payload, i);\n }\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input, optoutStart));\n }\n return handleTupleResults(itemResults, payload, items, input, optoutStart);\n };\n});\nfunction getTupleOptStart(items, key) {\n for (let i = items.length - 1; i >= 0; i--) {\n if (items[i]._zod[key] !== \"optional\")\n return i + 1;\n }\n return 0;\n}\nfunction handleTupleResult(result, final, index) {\n if (result.issues.length) {\n final.issues.push(...util.prefixIssues(index, result.issues));\n }\n final.value[index] = result.value;\n}\nfunction handleTupleResults(itemResults, final, items, input, optoutStart) {\n // Walk results in order. Mirror $ZodObject's swallow-on-absent-optional\n // rule, but only after `optoutStart`: the first index where the output\n // tuple tail can be absent.\n for (let i = 0; i < items.length; i++) {\n const r = itemResults[i];\n const isPresent = i < input.length;\n if (r.issues.length) {\n if (!isPresent && i >= optoutStart) {\n final.value.length = i;\n break;\n }\n final.issues.push(...util.prefixIssues(i, r.issues));\n }\n final.value[i] = r.value;\n }\n // Drop trailing slots that produced `undefined` for absent input\n // (the array analog of an absent optional key on an object). The\n // `i >= input.length` floor is critical: an explicit `undefined`\n // *inside* the input must be preserved even when the schema is\n // optional-out (e.g. `z.string().or(z.undefined())` accepting an\n // explicit undefined value).\n for (let i = final.value.length - 1; i >= input.length; i--) {\n if (items[i]._zod.optout === \"optional\" && final.value[i] === undefined) {\n final.value.length = i;\n }\n else {\n break;\n }\n }\n return final;\n}\nexport const $ZodRecord = /*@__PURE__*/ core.$constructor(\"$ZodRecord\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!util.isPlainObject(input)) {\n payload.issues.push({\n expected: \"record\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n const proms = [];\n const values = def.keyType._zod.values;\n if (values) {\n payload.value = {};\n const recordKeys = new Set();\n for (const key of values) {\n if (typeof key === \"string\" || typeof key === \"number\" || typeof key === \"symbol\") {\n recordKeys.add(typeof key === \"number\" ? key.toString() : key);\n const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n if (keyResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n if (keyResult.issues.length) {\n payload.issues.push({\n code: \"invalid_key\",\n origin: \"record\",\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n input: key,\n path: [key],\n inst,\n });\n continue;\n }\n const outKey = keyResult.value;\n const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[outKey] = result.value;\n }));\n }\n else {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[outKey] = result.value;\n }\n }\n }\n let unrecognized;\n for (const key in input) {\n if (!recordKeys.has(key)) {\n unrecognized = unrecognized ?? [];\n unrecognized.push(key);\n }\n }\n if (unrecognized && unrecognized.length > 0) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n input,\n inst,\n keys: unrecognized,\n });\n }\n }\n else {\n payload.value = {};\n // Reflect.ownKeys for Symbol-key support; filter non-enumerable to match z.object()\n for (const key of Reflect.ownKeys(input)) {\n if (key === \"__proto__\")\n continue;\n if (!Object.prototype.propertyIsEnumerable.call(input, key))\n continue;\n let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n if (keyResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n // Numeric string fallback: if key is a numeric string and failed, retry with Number(key)\n // This handles z.number(), z.literal([1, 2, 3]), and unions containing numeric literals\n const checkNumericKey = typeof key === \"string\" && regexes.number.test(key) && keyResult.issues.length;\n if (checkNumericKey) {\n const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx);\n if (retryResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n if (retryResult.issues.length === 0) {\n keyResult = retryResult;\n }\n }\n if (keyResult.issues.length) {\n if (def.mode === \"loose\") {\n // Pass through unchanged\n payload.value[key] = input[key];\n }\n else {\n // Default \"strict\" behavior: error on invalid key\n payload.issues.push({\n code: \"invalid_key\",\n origin: \"record\",\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n input: key,\n path: [key],\n inst,\n });\n }\n continue;\n }\n const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[keyResult.value] = result.value;\n }));\n }\n else {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[keyResult.value] = result.value;\n }\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => payload);\n }\n return payload;\n };\n});\nexport const $ZodMap = /*@__PURE__*/ core.$constructor(\"$ZodMap\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!(input instanceof Map)) {\n payload.issues.push({\n expected: \"map\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n const proms = [];\n payload.value = new Map();\n for (const [key, value] of input) {\n const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n const valueResult = def.valueType._zod.run({ value: value, issues: [] }, ctx);\n if (keyResult instanceof Promise || valueResult instanceof Promise) {\n proms.push(Promise.all([keyResult, valueResult]).then(([keyResult, valueResult]) => {\n handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);\n }));\n }\n else {\n handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);\n }\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\n});\nfunction handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) {\n if (keyResult.issues.length) {\n if (util.propertyKeyTypes.has(typeof key)) {\n final.issues.push(...util.prefixIssues(key, keyResult.issues));\n }\n else {\n final.issues.push({\n code: \"invalid_key\",\n origin: \"map\",\n input,\n inst,\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n });\n }\n }\n if (valueResult.issues.length) {\n if (util.propertyKeyTypes.has(typeof key)) {\n final.issues.push(...util.prefixIssues(key, valueResult.issues));\n }\n else {\n final.issues.push({\n origin: \"map\",\n code: \"invalid_element\",\n input,\n inst,\n key: key,\n issues: valueResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n });\n }\n }\n final.value.set(keyResult.value, valueResult.value);\n}\nexport const $ZodSet = /*@__PURE__*/ core.$constructor(\"$ZodSet\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!(input instanceof Set)) {\n payload.issues.push({\n input,\n inst,\n expected: \"set\",\n code: \"invalid_type\",\n });\n return payload;\n }\n const proms = [];\n payload.value = new Set();\n for (const item of input) {\n const result = def.valueType._zod.run({ value: item, issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleSetResult(result, payload)));\n }\n else\n handleSetResult(result, payload);\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\n});\nfunction handleSetResult(result, final) {\n if (result.issues.length) {\n final.issues.push(...result.issues);\n }\n final.value.add(result.value);\n}\nexport const $ZodEnum = /*@__PURE__*/ core.$constructor(\"$ZodEnum\", (inst, def) => {\n $ZodType.init(inst, def);\n const values = util.getEnumValues(def.entries);\n const valuesSet = new Set(values);\n inst._zod.values = valuesSet;\n inst._zod.pattern = new RegExp(`^(${values\n .filter((k) => util.propertyKeyTypes.has(typeof k))\n .map((o) => (typeof o === \"string\" ? util.escapeRegex(o) : o.toString()))\n .join(\"|\")})$`);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (valuesSet.has(input)) {\n return payload;\n }\n payload.issues.push({\n code: \"invalid_value\",\n values,\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodLiteral = /*@__PURE__*/ core.$constructor(\"$ZodLiteral\", (inst, def) => {\n $ZodType.init(inst, def);\n if (def.values.length === 0) {\n throw new Error(\"Cannot create literal schema with no valid values\");\n }\n const values = new Set(def.values);\n inst._zod.values = values;\n inst._zod.pattern = new RegExp(`^(${def.values\n .map((o) => (typeof o === \"string\" ? util.escapeRegex(o) : o ? util.escapeRegex(o.toString()) : String(o)))\n .join(\"|\")})$`);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (values.has(input)) {\n return payload;\n }\n payload.issues.push({\n code: \"invalid_value\",\n values: def.values,\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodFile = /*@__PURE__*/ core.$constructor(\"$ZodFile\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n // @ts-ignore\n if (input instanceof File)\n return payload;\n payload.issues.push({\n expected: \"file\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodTransform = /*@__PURE__*/ core.$constructor(\"$ZodTransform\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(inst.constructor.name);\n }\n const _out = def.transform(payload.value, payload);\n if (ctx.async) {\n const output = _out instanceof Promise ? _out : Promise.resolve(_out);\n return output.then((output) => {\n payload.value = output;\n payload.fallback = true;\n return payload;\n });\n }\n if (_out instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n payload.value = _out;\n payload.fallback = true;\n return payload;\n };\n});\nfunction handleOptionalResult(result, input) {\n if (input === undefined && (result.issues.length || result.fallback)) {\n return { issues: [], value: undefined };\n }\n return result;\n}\nexport const $ZodOptional = /*@__PURE__*/ core.$constructor(\"$ZodOptional\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n inst._zod.optout = \"optional\";\n util.defineLazy(inst._zod, \"values\", () => {\n return def.innerType._zod.values ? new Set([...def.innerType._zod.values, undefined]) : undefined;\n });\n util.defineLazy(inst._zod, \"pattern\", () => {\n const pattern = def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)})?$`) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n if (def.innerType._zod.optin === \"optional\") {\n const input = payload.value;\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise)\n return result.then((r) => handleOptionalResult(r, input));\n return handleOptionalResult(result, input);\n }\n if (payload.value === undefined) {\n return payload;\n }\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodExactOptional = /*@__PURE__*/ core.$constructor(\"$ZodExactOptional\", (inst, def) => {\n // Call parent init - inherits optin/optout = \"optional\"\n $ZodOptional.init(inst, def);\n // Override values/pattern to NOT add undefined\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n util.defineLazy(inst._zod, \"pattern\", () => def.innerType._zod.pattern);\n // Override parse to just delegate (no undefined handling)\n inst._zod.parse = (payload, ctx) => {\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodNullable = /*@__PURE__*/ core.$constructor(\"$ZodNullable\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"optin\", () => def.innerType._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.innerType._zod.optout);\n util.defineLazy(inst._zod, \"pattern\", () => {\n const pattern = def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)}|null)$`) : undefined;\n });\n util.defineLazy(inst._zod, \"values\", () => {\n return def.innerType._zod.values ? new Set([...def.innerType._zod.values, null]) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n // Forward direction (decode): allow null to pass through\n if (payload.value === null)\n return payload;\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodDefault = /*@__PURE__*/ core.$constructor(\"$ZodDefault\", (inst, def) => {\n $ZodType.init(inst, def);\n // inst._zod.qin = \"true\";\n inst._zod.optin = \"optional\";\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply defaults for undefined input\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n /**\n * $ZodDefault returns the default value immediately in forward direction.\n * It doesn't pass the default value into the validator (\"prefault\"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a \"prefault\" for the pipe. */\n return payload;\n }\n // Forward direction: continue with default handling\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleDefaultResult(result, def));\n }\n return handleDefaultResult(result, def);\n };\n});\nfunction handleDefaultResult(payload, def) {\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n }\n return payload;\n}\nexport const $ZodPrefault = /*@__PURE__*/ core.$constructor(\"$ZodPrefault\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply prefault for undefined input\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n }\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodNonOptional = /*@__PURE__*/ core.$constructor(\"$ZodNonOptional\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"values\", () => {\n const v = def.innerType._zod.values;\n return v ? new Set([...v].filter((x) => x !== undefined)) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleNonOptionalResult(result, inst));\n }\n return handleNonOptionalResult(result, inst);\n };\n});\nfunction handleNonOptionalResult(payload, inst) {\n if (!payload.issues.length && payload.value === undefined) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: payload.value,\n inst,\n });\n }\n return payload;\n}\nexport const $ZodSuccess = /*@__PURE__*/ core.$constructor(\"$ZodSuccess\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(\"ZodSuccess\");\n }\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => {\n payload.value = result.issues.length === 0;\n return payload;\n });\n }\n payload.value = result.issues.length === 0;\n return payload;\n };\n});\nexport const $ZodCatch = /*@__PURE__*/ core.$constructor(\"$ZodCatch\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n util.defineLazy(inst._zod, \"optout\", () => def.innerType._zod.optout);\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply catch logic\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => {\n payload.value = result.value;\n if (result.issues.length) {\n payload.value = def.catchValue({\n ...payload,\n error: {\n issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n },\n input: payload.value,\n });\n payload.issues = [];\n payload.fallback = true;\n }\n return payload;\n });\n }\n payload.value = result.value;\n if (result.issues.length) {\n payload.value = def.catchValue({\n ...payload,\n error: {\n issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n },\n input: payload.value,\n });\n payload.issues = [];\n payload.fallback = true;\n }\n return payload;\n };\n});\nexport const $ZodNaN = /*@__PURE__*/ core.$constructor(\"$ZodNaN\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"number\" || !Number.isNaN(payload.value)) {\n payload.issues.push({\n input: payload.value,\n inst,\n expected: \"nan\",\n code: \"invalid_type\",\n });\n return payload;\n }\n return payload;\n };\n});\nexport const $ZodPipe = /*@__PURE__*/ core.$constructor(\"$ZodPipe\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"values\", () => def.in._zod.values);\n util.defineLazy(inst._zod, \"optin\", () => def.in._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.out._zod.optout);\n util.defineLazy(inst._zod, \"propValues\", () => def.in._zod.propValues);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n const right = def.out._zod.run(payload, ctx);\n if (right instanceof Promise) {\n return right.then((right) => handlePipeResult(right, def.in, ctx));\n }\n return handlePipeResult(right, def.in, ctx);\n }\n const left = def.in._zod.run(payload, ctx);\n if (left instanceof Promise) {\n return left.then((left) => handlePipeResult(left, def.out, ctx));\n }\n return handlePipeResult(left, def.out, ctx);\n };\n});\nfunction handlePipeResult(left, next, ctx) {\n if (left.issues.length) {\n // prevent further checks\n left.aborted = true;\n return left;\n }\n return next._zod.run({ value: left.value, issues: left.issues, fallback: left.fallback }, ctx);\n}\nexport const $ZodCodec = /*@__PURE__*/ core.$constructor(\"$ZodCodec\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"values\", () => def.in._zod.values);\n util.defineLazy(inst._zod, \"optin\", () => def.in._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.out._zod.optout);\n util.defineLazy(inst._zod, \"propValues\", () => def.in._zod.propValues);\n inst._zod.parse = (payload, ctx) => {\n const direction = ctx.direction || \"forward\";\n if (direction === \"forward\") {\n const left = def.in._zod.run(payload, ctx);\n if (left instanceof Promise) {\n return left.then((left) => handleCodecAResult(left, def, ctx));\n }\n return handleCodecAResult(left, def, ctx);\n }\n else {\n const right = def.out._zod.run(payload, ctx);\n if (right instanceof Promise) {\n return right.then((right) => handleCodecAResult(right, def, ctx));\n }\n return handleCodecAResult(right, def, ctx);\n }\n };\n});\nfunction handleCodecAResult(result, def, ctx) {\n if (result.issues.length) {\n // prevent further checks\n result.aborted = true;\n return result;\n }\n const direction = ctx.direction || \"forward\";\n if (direction === \"forward\") {\n const transformed = def.transform(result.value, result);\n if (transformed instanceof Promise) {\n return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx));\n }\n return handleCodecTxResult(result, transformed, def.out, ctx);\n }\n else {\n const transformed = def.reverseTransform(result.value, result);\n if (transformed instanceof Promise) {\n return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx));\n }\n return handleCodecTxResult(result, transformed, def.in, ctx);\n }\n}\nfunction handleCodecTxResult(left, value, nextSchema, ctx) {\n // Check if transform added any issues\n if (left.issues.length) {\n left.aborted = true;\n return left;\n }\n return nextSchema._zod.run({ value, issues: left.issues }, ctx);\n}\nexport const $ZodPreprocess = /*@__PURE__*/ core.$constructor(\"$ZodPreprocess\", (inst, def) => {\n $ZodPipe.init(inst, def);\n});\nexport const $ZodReadonly = /*@__PURE__*/ core.$constructor(\"$ZodReadonly\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"propValues\", () => def.innerType._zod.propValues);\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n util.defineLazy(inst._zod, \"optin\", () => def.innerType?._zod?.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.innerType?._zod?.optout);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then(handleReadonlyResult);\n }\n return handleReadonlyResult(result);\n };\n});\nfunction handleReadonlyResult(payload) {\n payload.value = Object.freeze(payload.value);\n return payload;\n}\nexport const $ZodTemplateLiteral = /*@__PURE__*/ core.$constructor(\"$ZodTemplateLiteral\", (inst, def) => {\n $ZodType.init(inst, def);\n const regexParts = [];\n for (const part of def.parts) {\n if (typeof part === \"object\" && part !== null) {\n // is Zod schema\n if (!part._zod.pattern) {\n // if (!source)\n throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`);\n }\n const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern;\n if (!source)\n throw new Error(`Invalid template literal part: ${part._zod.traits}`);\n const start = source.startsWith(\"^\") ? 1 : 0;\n const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n regexParts.push(source.slice(start, end));\n }\n else if (part === null || util.primitiveTypes.has(typeof part)) {\n regexParts.push(util.escapeRegex(`${part}`));\n }\n else {\n throw new Error(`Invalid template literal part: ${part}`);\n }\n }\n inst._zod.pattern = new RegExp(`^${regexParts.join(\"\")}$`);\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"string\") {\n payload.issues.push({\n input: payload.value,\n inst,\n expected: \"string\",\n code: \"invalid_type\",\n });\n return payload;\n }\n inst._zod.pattern.lastIndex = 0;\n if (!inst._zod.pattern.test(payload.value)) {\n payload.issues.push({\n input: payload.value,\n inst,\n code: \"invalid_format\",\n format: def.format ?? \"template_literal\",\n pattern: inst._zod.pattern.source,\n });\n return payload;\n }\n return payload;\n };\n});\nexport const $ZodFunction = /*@__PURE__*/ core.$constructor(\"$ZodFunction\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._def = def;\n inst._zod.def = def;\n inst.implement = (func) => {\n if (typeof func !== \"function\") {\n throw new Error(\"implement() must be called with a function\");\n }\n return function (...args) {\n const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args;\n const result = Reflect.apply(func, this, parsedArgs);\n if (inst._def.output) {\n return parse(inst._def.output, result);\n }\n return result;\n };\n };\n inst.implementAsync = (func) => {\n if (typeof func !== \"function\") {\n throw new Error(\"implementAsync() must be called with a function\");\n }\n return async function (...args) {\n const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args;\n const result = await Reflect.apply(func, this, parsedArgs);\n if (inst._def.output) {\n return await parseAsync(inst._def.output, result);\n }\n return result;\n };\n };\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"function\") {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"function\",\n input: payload.value,\n inst,\n });\n return payload;\n }\n // Check if output is a promise type to determine if we should use async implementation\n const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === \"promise\";\n if (hasPromiseOutput) {\n payload.value = inst.implementAsync(payload.value);\n }\n else {\n payload.value = inst.implement(payload.value);\n }\n return payload;\n };\n inst.input = (...args) => {\n const F = inst.constructor;\n if (Array.isArray(args[0])) {\n return new F({\n type: \"function\",\n input: new $ZodTuple({\n type: \"tuple\",\n items: args[0],\n rest: args[1],\n }),\n output: inst._def.output,\n });\n }\n return new F({\n type: \"function\",\n input: args[0],\n output: inst._def.output,\n });\n };\n inst.output = (output) => {\n const F = inst.constructor;\n return new F({\n type: \"function\",\n input: inst._def.input,\n output,\n });\n };\n return inst;\n});\nexport const $ZodPromise = /*@__PURE__*/ core.$constructor(\"$ZodPromise\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx));\n };\n});\nexport const $ZodLazy = /*@__PURE__*/ core.$constructor(\"$ZodLazy\", (inst, def) => {\n $ZodType.init(inst, def);\n // Cache the resolved inner type on the shared `def` so all clones of this\n // lazy (e.g. via `.describe()`/`.meta()`) share the same inner instance,\n // preserving identity for cycle detection on recursive schemas.\n util.defineLazy(inst._zod, \"innerType\", () => {\n const d = def;\n if (!d._cachedInner)\n d._cachedInner = def.getter();\n return d._cachedInner;\n });\n util.defineLazy(inst._zod, \"pattern\", () => inst._zod.innerType?._zod?.pattern);\n util.defineLazy(inst._zod, \"propValues\", () => inst._zod.innerType?._zod?.propValues);\n util.defineLazy(inst._zod, \"optin\", () => inst._zod.innerType?._zod?.optin ?? undefined);\n util.defineLazy(inst._zod, \"optout\", () => inst._zod.innerType?._zod?.optout ?? undefined);\n inst._zod.parse = (payload, ctx) => {\n const inner = inst._zod.innerType;\n return inner._zod.run(payload, ctx);\n };\n});\nexport const $ZodCustom = /*@__PURE__*/ core.$constructor(\"$ZodCustom\", (inst, def) => {\n checks.$ZodCheck.init(inst, def);\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _) => {\n return payload;\n };\n inst._zod.check = (payload) => {\n const input = payload.value;\n const r = def.fn(input);\n if (r instanceof Promise) {\n return r.then((r) => handleRefineResult(r, payload, input, inst));\n }\n handleRefineResult(r, payload, input, inst);\n return;\n };\n});\nfunction handleRefineResult(result, payload, input, inst) {\n if (!result) {\n const _iss = {\n code: \"custom\",\n input,\n inst, // incorporates params.error into issue reporting\n path: [...(inst._zod.def.path ?? [])], // incorporates params.error into issue reporting\n continue: !inst._zod.def.abort,\n // params: inst._zod.def.params,\n };\n if (inst._zod.def.params)\n _iss.params = inst._zod.def.params;\n payload.issues.push(util.issue(_iss));\n }\n}\n","import * as checks from \"./checks.js\";\nimport * as registries from \"./registries.js\";\nimport * as schemas from \"./schemas.js\";\nimport * as util from \"./util.js\";\n// @__NO_SIDE_EFFECTS__\nexport function _string(Class, params) {\n return new Class({\n type: \"string\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedString(Class, params) {\n return new Class({\n type: \"string\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _email(Class, params) {\n return new Class({\n type: \"string\",\n format: \"email\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _guid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"guid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v4\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v6\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv7(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v7\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _url(Class, params) {\n return new Class({\n type: \"string\",\n format: \"url\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _emoji(Class, params) {\n return new Class({\n type: \"string\",\n format: \"emoji\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nanoid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"nanoid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link _cuid2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\n// @__NO_SIDE_EFFECTS__\nexport function _cuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cuid2(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cuid2\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ulid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ulid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _xid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"xid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ksuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ksuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ipv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ipv4\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ipv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ipv6\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _mac(Class, params) {\n return new Class({\n type: \"string\",\n format: \"mac\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cidrv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cidrv4\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cidrv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cidrv6\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _base64(Class, params) {\n return new Class({\n type: \"string\",\n format: \"base64\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _base64url(Class, params) {\n return new Class({\n type: \"string\",\n format: \"base64url\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _e164(Class, params) {\n return new Class({\n type: \"string\",\n format: \"e164\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _jwt(Class, params) {\n return new Class({\n type: \"string\",\n format: \"jwt\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport const TimePrecision = {\n Any: null,\n Minute: -1,\n Second: 0,\n Millisecond: 3,\n Microsecond: 6,\n};\n// @__NO_SIDE_EFFECTS__\nexport function _isoDateTime(Class, params) {\n return new Class({\n type: \"string\",\n format: \"datetime\",\n check: \"string_format\",\n offset: false,\n local: false,\n precision: null,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoDate(Class, params) {\n return new Class({\n type: \"string\",\n format: \"date\",\n check: \"string_format\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoTime(Class, params) {\n return new Class({\n type: \"string\",\n format: \"time\",\n check: \"string_format\",\n precision: null,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoDuration(Class, params) {\n return new Class({\n type: \"string\",\n format: \"duration\",\n check: \"string_format\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _number(Class, params) {\n return new Class({\n type: \"number\",\n checks: [],\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedNumber(Class, params) {\n return new Class({\n type: \"number\",\n coerce: true,\n checks: [],\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"safeint\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _float32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"float32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _float64(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"float64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"int32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uint32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"uint32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _boolean(Class, params) {\n return new Class({\n type: \"boolean\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedBoolean(Class, params) {\n return new Class({\n type: \"boolean\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _bigint(Class, params) {\n return new Class({\n type: \"bigint\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedBigint(Class, params) {\n return new Class({\n type: \"bigint\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int64(Class, params) {\n return new Class({\n type: \"bigint\",\n check: \"bigint_format\",\n abort: false,\n format: \"int64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uint64(Class, params) {\n return new Class({\n type: \"bigint\",\n check: \"bigint_format\",\n abort: false,\n format: \"uint64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _symbol(Class, params) {\n return new Class({\n type: \"symbol\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _undefined(Class, params) {\n return new Class({\n type: \"undefined\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _null(Class, params) {\n return new Class({\n type: \"null\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _any(Class) {\n return new Class({\n type: \"any\",\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _unknown(Class) {\n return new Class({\n type: \"unknown\",\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _never(Class, params) {\n return new Class({\n type: \"never\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _void(Class, params) {\n return new Class({\n type: \"void\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _date(Class, params) {\n return new Class({\n type: \"date\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedDate(Class, params) {\n return new Class({\n type: \"date\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nan(Class, params) {\n return new Class({\n type: \"nan\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lt(value, params) {\n return new checks.$ZodCheckLessThan({\n check: \"less_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: false,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lte(value, params) {\n return new checks.$ZodCheckLessThan({\n check: \"less_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: true,\n });\n}\nexport { \n/** @deprecated Use `z.lte()` instead. */\n_lte as _max, };\n// @__NO_SIDE_EFFECTS__\nexport function _gt(value, params) {\n return new checks.$ZodCheckGreaterThan({\n check: \"greater_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: false,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _gte(value, params) {\n return new checks.$ZodCheckGreaterThan({\n check: \"greater_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: true,\n });\n}\nexport { \n/** @deprecated Use `z.gte()` instead. */\n_gte as _min, };\n// @__NO_SIDE_EFFECTS__\nexport function _positive(params) {\n return _gt(0, params);\n}\n// negative\n// @__NO_SIDE_EFFECTS__\nexport function _negative(params) {\n return _lt(0, params);\n}\n// nonpositive\n// @__NO_SIDE_EFFECTS__\nexport function _nonpositive(params) {\n return _lte(0, params);\n}\n// nonnegative\n// @__NO_SIDE_EFFECTS__\nexport function _nonnegative(params) {\n return _gte(0, params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function _multipleOf(value, params) {\n return new checks.$ZodCheckMultipleOf({\n check: \"multiple_of\",\n ...util.normalizeParams(params),\n value,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _maxSize(maximum, params) {\n return new checks.$ZodCheckMaxSize({\n check: \"max_size\",\n ...util.normalizeParams(params),\n maximum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _minSize(minimum, params) {\n return new checks.$ZodCheckMinSize({\n check: \"min_size\",\n ...util.normalizeParams(params),\n minimum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _size(size, params) {\n return new checks.$ZodCheckSizeEquals({\n check: \"size_equals\",\n ...util.normalizeParams(params),\n size,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _maxLength(maximum, params) {\n const ch = new checks.$ZodCheckMaxLength({\n check: \"max_length\",\n ...util.normalizeParams(params),\n maximum,\n });\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _minLength(minimum, params) {\n return new checks.$ZodCheckMinLength({\n check: \"min_length\",\n ...util.normalizeParams(params),\n minimum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _length(length, params) {\n return new checks.$ZodCheckLengthEquals({\n check: \"length_equals\",\n ...util.normalizeParams(params),\n length,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _regex(pattern, params) {\n return new checks.$ZodCheckRegex({\n check: \"string_format\",\n format: \"regex\",\n ...util.normalizeParams(params),\n pattern,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lowercase(params) {\n return new checks.$ZodCheckLowerCase({\n check: \"string_format\",\n format: \"lowercase\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uppercase(params) {\n return new checks.$ZodCheckUpperCase({\n check: \"string_format\",\n format: \"uppercase\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _includes(includes, params) {\n return new checks.$ZodCheckIncludes({\n check: \"string_format\",\n format: \"includes\",\n ...util.normalizeParams(params),\n includes,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _startsWith(prefix, params) {\n return new checks.$ZodCheckStartsWith({\n check: \"string_format\",\n format: \"starts_with\",\n ...util.normalizeParams(params),\n prefix,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _endsWith(suffix, params) {\n return new checks.$ZodCheckEndsWith({\n check: \"string_format\",\n format: \"ends_with\",\n ...util.normalizeParams(params),\n suffix,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _property(property, schema, params) {\n return new checks.$ZodCheckProperty({\n check: \"property\",\n property,\n schema,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _mime(types, params) {\n return new checks.$ZodCheckMimeType({\n check: \"mime_type\",\n mime: types,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _overwrite(tx) {\n return new checks.$ZodCheckOverwrite({\n check: \"overwrite\",\n tx,\n });\n}\n// normalize\n// @__NO_SIDE_EFFECTS__\nexport function _normalize(form) {\n return _overwrite((input) => input.normalize(form));\n}\n// trim\n// @__NO_SIDE_EFFECTS__\nexport function _trim() {\n return _overwrite((input) => input.trim());\n}\n// toLowerCase\n// @__NO_SIDE_EFFECTS__\nexport function _toLowerCase() {\n return _overwrite((input) => input.toLowerCase());\n}\n// toUpperCase\n// @__NO_SIDE_EFFECTS__\nexport function _toUpperCase() {\n return _overwrite((input) => input.toUpperCase());\n}\n// slugify\n// @__NO_SIDE_EFFECTS__\nexport function _slugify() {\n return _overwrite((input) => util.slugify(input));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _array(Class, element, params) {\n return new Class({\n type: \"array\",\n element,\n // get element() {\n // return element;\n // },\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _union(Class, options, params) {\n return new Class({\n type: \"union\",\n options,\n ...util.normalizeParams(params),\n });\n}\nexport function _xor(Class, options, params) {\n return new Class({\n type: \"union\",\n options,\n inclusive: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _discriminatedUnion(Class, discriminator, options, params) {\n return new Class({\n type: \"union\",\n options,\n discriminator,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _intersection(Class, left, right) {\n return new Class({\n type: \"intersection\",\n left,\n right,\n });\n}\n// export function _tuple(\n// Class: util.SchemaClass<schemas.$ZodTuple>,\n// items: [],\n// params?: string | $ZodTupleParams\n// ): schemas.$ZodTuple<[], null>;\n// @__NO_SIDE_EFFECTS__\nexport function _tuple(Class, items, _paramsOrRest, _params) {\n const hasRest = _paramsOrRest instanceof schemas.$ZodType;\n const params = hasRest ? _params : _paramsOrRest;\n const rest = hasRest ? _paramsOrRest : null;\n return new Class({\n type: \"tuple\",\n items,\n rest,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _record(Class, keyType, valueType, params) {\n return new Class({\n type: \"record\",\n keyType,\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _map(Class, keyType, valueType, params) {\n return new Class({\n type: \"map\",\n keyType,\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _set(Class, valueType, params) {\n return new Class({\n type: \"set\",\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _enum(Class, values, params) {\n const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;\n // if (Array.isArray(values)) {\n // for (const value of values) {\n // entries[value] = value;\n // }\n // } else {\n // Object.assign(entries, values);\n // }\n // const entries: util.EnumLike = {};\n // for (const val of values) {\n // entries[val] = val;\n // }\n return new Class({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\n/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.\n *\n * ```ts\n * enum Colors { red, green, blue }\n * z.enum(Colors);\n * ```\n */\nexport function _nativeEnum(Class, entries, params) {\n return new Class({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _literal(Class, value, params) {\n return new Class({\n type: \"literal\",\n values: Array.isArray(value) ? value : [value],\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _file(Class, params) {\n return new Class({\n type: \"file\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _transform(Class, fn) {\n return new Class({\n type: \"transform\",\n transform: fn,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _optional(Class, innerType) {\n return new Class({\n type: \"optional\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nullable(Class, innerType) {\n return new Class({\n type: \"nullable\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _default(Class, innerType, defaultValue) {\n return new Class({\n type: \"default\",\n innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nonoptional(Class, innerType, params) {\n return new Class({\n type: \"nonoptional\",\n innerType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _success(Class, innerType) {\n return new Class({\n type: \"success\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _catch(Class, innerType, catchValue) {\n return new Class({\n type: \"catch\",\n innerType,\n catchValue: (typeof catchValue === \"function\" ? catchValue : () => catchValue),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _pipe(Class, in_, out) {\n return new Class({\n type: \"pipe\",\n in: in_,\n out,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _readonly(Class, innerType) {\n return new Class({\n type: \"readonly\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _templateLiteral(Class, parts, params) {\n return new Class({\n type: \"template_literal\",\n parts,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lazy(Class, getter) {\n return new Class({\n type: \"lazy\",\n getter,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _promise(Class, innerType) {\n return new Class({\n type: \"promise\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _custom(Class, fn, _params) {\n const norm = util.normalizeParams(_params);\n norm.abort ?? (norm.abort = true); // default to abort:false\n const schema = new Class({\n type: \"custom\",\n check: \"custom\",\n fn: fn,\n ...norm,\n });\n return schema;\n}\n// same as _custom but defaults to abort:false\n// @__NO_SIDE_EFFECTS__\nexport function _refine(Class, fn, _params) {\n const schema = new Class({\n type: \"custom\",\n check: \"custom\",\n fn: fn,\n ...util.normalizeParams(_params),\n });\n return schema;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _superRefine(fn, params) {\n const ch = _check((payload) => {\n payload.addIssue = (issue) => {\n if (typeof issue === \"string\") {\n payload.issues.push(util.issue(issue, payload.value, ch._zod.def));\n }\n else {\n // for Zod 3 backwards compatibility\n const _issue = issue;\n if (_issue.fatal)\n _issue.continue = false;\n _issue.code ?? (_issue.code = \"custom\");\n _issue.input ?? (_issue.input = payload.value);\n _issue.inst ?? (_issue.inst = ch);\n _issue.continue ?? (_issue.continue = !ch._zod.def.abort); // abort is always undefined, so this is always true...\n payload.issues.push(util.issue(_issue));\n }\n };\n return fn(payload.value, payload);\n }, params);\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _check(fn, params) {\n const ch = new checks.$ZodCheck({\n check: \"custom\",\n ...util.normalizeParams(params),\n });\n ch._zod.check = fn;\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function describe(description) {\n const ch = new checks.$ZodCheck({ check: \"describe\" });\n ch._zod.onattach = [\n (inst) => {\n const existing = registries.globalRegistry.get(inst) ?? {};\n registries.globalRegistry.add(inst, { ...existing, description });\n },\n ];\n ch._zod.check = () => { }; // no-op check\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function meta(metadata) {\n const ch = new checks.$ZodCheck({ check: \"meta\" });\n ch._zod.onattach = [\n (inst) => {\n const existing = registries.globalRegistry.get(inst) ?? {};\n registries.globalRegistry.add(inst, { ...existing, ...metadata });\n },\n ];\n ch._zod.check = () => { }; // no-op check\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _stringbool(Classes, _params) {\n const params = util.normalizeParams(_params);\n let truthyArray = params.truthy ?? [\"true\", \"1\", \"yes\", \"on\", \"y\", \"enabled\"];\n let falsyArray = params.falsy ?? [\"false\", \"0\", \"no\", \"off\", \"n\", \"disabled\"];\n if (params.case !== \"sensitive\") {\n truthyArray = truthyArray.map((v) => (typeof v === \"string\" ? v.toLowerCase() : v));\n falsyArray = falsyArray.map((v) => (typeof v === \"string\" ? v.toLowerCase() : v));\n }\n const truthySet = new Set(truthyArray);\n const falsySet = new Set(falsyArray);\n const _Codec = Classes.Codec ?? schemas.$ZodCodec;\n const _Boolean = Classes.Boolean ?? schemas.$ZodBoolean;\n const _String = Classes.String ?? schemas.$ZodString;\n const stringSchema = new _String({ type: \"string\", error: params.error });\n const booleanSchema = new _Boolean({ type: \"boolean\", error: params.error });\n const codec = new _Codec({\n type: \"pipe\",\n in: stringSchema,\n out: booleanSchema,\n transform: ((input, payload) => {\n let data = input;\n if (params.case !== \"sensitive\")\n data = data.toLowerCase();\n if (truthySet.has(data)) {\n return true;\n }\n else if (falsySet.has(data)) {\n return false;\n }\n else {\n payload.issues.push({\n code: \"invalid_value\",\n expected: \"stringbool\",\n values: [...truthySet, ...falsySet],\n input: payload.value,\n inst: codec,\n continue: false,\n });\n return {};\n }\n }),\n reverseTransform: ((input, _payload) => {\n if (input === true) {\n return truthyArray[0] || \"true\";\n }\n else {\n return falsyArray[0] || \"false\";\n }\n }),\n error: params.error,\n });\n return codec;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _stringFormat(Class, format, fnOrRegex, _params = {}) {\n const params = util.normalizeParams(_params);\n const def = {\n ...util.normalizeParams(_params),\n check: \"string_format\",\n type: \"string\",\n format,\n fn: typeof fnOrRegex === \"function\" ? fnOrRegex : (val) => fnOrRegex.test(val),\n ...params,\n };\n if (fnOrRegex instanceof RegExp) {\n def.pattern = fnOrRegex;\n }\n const inst = new Class(def);\n return inst;\n}\n","import * as core from \"../core/index.js\";\nimport * as util from \"../core/util.js\";\nimport * as parse from \"./parse.js\";\nexport const ZodMiniType = /*@__PURE__*/ core.$constructor(\"ZodMiniType\", (inst, def) => {\n if (!inst._zod)\n throw new Error(\"Uninitialized schema in ZodMiniType.\");\n core.$ZodType.init(inst, def);\n inst.def = def;\n inst.type = def.type;\n inst.parse = (data, params) => parse.parse(inst, data, params, { callee: inst.parse });\n inst.safeParse = (data, params) => parse.safeParse(inst, data, params);\n inst.parseAsync = async (data, params) => parse.parseAsync(inst, data, params, { callee: inst.parseAsync });\n inst.safeParseAsync = async (data, params) => parse.safeParseAsync(inst, data, params);\n inst.check = (...checks) => {\n return inst.clone({\n ...def,\n checks: [\n ...(def.checks ?? []),\n ...checks.map((ch) => typeof ch === \"function\"\n ? {\n _zod: { check: ch, def: { check: \"custom\" }, onattach: [] },\n }\n : ch),\n ],\n }, { parent: true });\n };\n inst.with = inst.check;\n inst.clone = (_def, params) => core.clone(inst, _def, params);\n inst.brand = () => inst;\n inst.register = ((reg, meta) => {\n reg.add(inst, meta);\n return inst;\n });\n inst.apply = (fn) => fn(inst);\n});\nexport const ZodMiniString = /*@__PURE__*/ core.$constructor(\"ZodMiniString\", (inst, def) => {\n core.$ZodString.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function string(params) {\n return core._string(ZodMiniString, params);\n}\nexport const ZodMiniStringFormat = /*@__PURE__*/ core.$constructor(\"ZodMiniStringFormat\", (inst, def) => {\n core.$ZodStringFormat.init(inst, def);\n ZodMiniString.init(inst, def);\n});\nexport const ZodMiniEmail = /*@__PURE__*/ core.$constructor(\"ZodMiniEmail\", (inst, def) => {\n core.$ZodEmail.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function email(params) {\n return core._email(ZodMiniEmail, params);\n}\nexport const ZodMiniGUID = /*@__PURE__*/ core.$constructor(\"ZodMiniGUID\", (inst, def) => {\n core.$ZodGUID.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function guid(params) {\n return core._guid(ZodMiniGUID, params);\n}\nexport const ZodMiniUUID = /*@__PURE__*/ core.$constructor(\"ZodMiniUUID\", (inst, def) => {\n core.$ZodUUID.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function uuid(params) {\n return core._uuid(ZodMiniUUID, params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function uuidv4(params) {\n return core._uuidv4(ZodMiniUUID, params);\n}\n// ZodMiniUUIDv6\n// @__NO_SIDE_EFFECTS__\nexport function uuidv6(params) {\n return core._uuidv6(ZodMiniUUID, params);\n}\n// ZodMiniUUIDv7\n// @__NO_SIDE_EFFECTS__\nexport function uuidv7(params) {\n return core._uuidv7(ZodMiniUUID, params);\n}\nexport const ZodMiniURL = /*@__PURE__*/ core.$constructor(\"ZodMiniURL\", (inst, def) => {\n core.$ZodURL.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function url(params) {\n return core._url(ZodMiniURL, params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function httpUrl(params) {\n return core._url(ZodMiniURL, {\n protocol: core.regexes.httpProtocol,\n hostname: core.regexes.domain,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniEmoji = /*@__PURE__*/ core.$constructor(\"ZodMiniEmoji\", (inst, def) => {\n core.$ZodEmoji.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function emoji(params) {\n return core._emoji(ZodMiniEmoji, params);\n}\nexport const ZodMiniNanoID = /*@__PURE__*/ core.$constructor(\"ZodMiniNanoID\", (inst, def) => {\n core.$ZodNanoID.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function nanoid(params) {\n return core._nanoid(ZodMiniNanoID, params);\n}\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link ZodMiniCUID2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const ZodMiniCUID = /*@__PURE__*/ core.$constructor(\"ZodMiniCUID\", (inst, def) => {\n core.$ZodCUID.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n/**\n * Validates a CUID v1 string.\n *\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link cuid2 | `z.cuid2()`} instead.\n * See https://github.com/paralleldrive/cuid.\n */\n// @__NO_SIDE_EFFECTS__\nexport function cuid(params) {\n return core._cuid(ZodMiniCUID, params);\n}\nexport const ZodMiniCUID2 = /*@__PURE__*/ core.$constructor(\"ZodMiniCUID2\", (inst, def) => {\n core.$ZodCUID2.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function cuid2(params) {\n return core._cuid2(ZodMiniCUID2, params);\n}\nexport const ZodMiniULID = /*@__PURE__*/ core.$constructor(\"ZodMiniULID\", (inst, def) => {\n core.$ZodULID.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function ulid(params) {\n return core._ulid(ZodMiniULID, params);\n}\nexport const ZodMiniXID = /*@__PURE__*/ core.$constructor(\"ZodMiniXID\", (inst, def) => {\n core.$ZodXID.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function xid(params) {\n return core._xid(ZodMiniXID, params);\n}\nexport const ZodMiniKSUID = /*@__PURE__*/ core.$constructor(\"ZodMiniKSUID\", (inst, def) => {\n core.$ZodKSUID.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function ksuid(params) {\n return core._ksuid(ZodMiniKSUID, params);\n}\nexport const ZodMiniIPv4 = /*@__PURE__*/ core.$constructor(\"ZodMiniIPv4\", (inst, def) => {\n core.$ZodIPv4.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function ipv4(params) {\n return core._ipv4(ZodMiniIPv4, params);\n}\nexport const ZodMiniIPv6 = /*@__PURE__*/ core.$constructor(\"ZodMiniIPv6\", (inst, def) => {\n core.$ZodIPv6.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function ipv6(params) {\n return core._ipv6(ZodMiniIPv6, params);\n}\nexport const ZodMiniCIDRv4 = /*@__PURE__*/ core.$constructor(\"ZodMiniCIDRv4\", (inst, def) => {\n core.$ZodCIDRv4.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function cidrv4(params) {\n return core._cidrv4(ZodMiniCIDRv4, params);\n}\nexport const ZodMiniCIDRv6 = /*@__PURE__*/ core.$constructor(\"ZodMiniCIDRv6\", (inst, def) => {\n core.$ZodCIDRv6.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function cidrv6(params) {\n return core._cidrv6(ZodMiniCIDRv6, params);\n}\nexport const ZodMiniMAC = /*@__PURE__*/ core.$constructor(\"ZodMiniMAC\", (inst, def) => {\n core.$ZodMAC.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function mac(params) {\n return core._mac(ZodMiniMAC, params);\n}\nexport const ZodMiniBase64 = /*@__PURE__*/ core.$constructor(\"ZodMiniBase64\", (inst, def) => {\n core.$ZodBase64.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function base64(params) {\n return core._base64(ZodMiniBase64, params);\n}\nexport const ZodMiniBase64URL = /*@__PURE__*/ core.$constructor(\"ZodMiniBase64URL\", (inst, def) => {\n core.$ZodBase64URL.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function base64url(params) {\n return core._base64url(ZodMiniBase64URL, params);\n}\nexport const ZodMiniE164 = /*@__PURE__*/ core.$constructor(\"ZodMiniE164\", (inst, def) => {\n core.$ZodE164.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function e164(params) {\n return core._e164(ZodMiniE164, params);\n}\nexport const ZodMiniJWT = /*@__PURE__*/ core.$constructor(\"ZodMiniJWT\", (inst, def) => {\n core.$ZodJWT.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function jwt(params) {\n return core._jwt(ZodMiniJWT, params);\n}\nexport const ZodMiniCustomStringFormat = /*@__PURE__*/ core.$constructor(\"ZodMiniCustomStringFormat\", (inst, def) => {\n core.$ZodCustomStringFormat.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function stringFormat(format, fnOrRegex, _params = {}) {\n return core._stringFormat(ZodMiniCustomStringFormat, format, fnOrRegex, _params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function hostname(_params) {\n return core._stringFormat(ZodMiniCustomStringFormat, \"hostname\", core.regexes.hostname, _params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function hex(_params) {\n return core._stringFormat(ZodMiniCustomStringFormat, \"hex\", core.regexes.hex, _params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function hash(alg, params) {\n const enc = params?.enc ?? \"hex\";\n const format = `${alg}_${enc}`;\n const regex = core.regexes[format];\n // check for unrecognized format\n if (!regex)\n throw new Error(`Unrecognized hash format: ${format}`);\n return core._stringFormat(ZodMiniCustomStringFormat, format, regex, params);\n}\nexport const ZodMiniNumber = /*@__PURE__*/ core.$constructor(\"ZodMiniNumber\", (inst, def) => {\n core.$ZodNumber.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function number(params) {\n return core._number(ZodMiniNumber, params);\n}\nexport const ZodMiniNumberFormat = /*@__PURE__*/ core.$constructor(\"ZodMiniNumberFormat\", (inst, def) => {\n core.$ZodNumberFormat.init(inst, def);\n ZodMiniNumber.init(inst, def);\n});\n// int\n// @__NO_SIDE_EFFECTS__\nexport function int(params) {\n return core._int(ZodMiniNumberFormat, params);\n}\n// float32\n// @__NO_SIDE_EFFECTS__\nexport function float32(params) {\n return core._float32(ZodMiniNumberFormat, params);\n}\n// float64\n// @__NO_SIDE_EFFECTS__\nexport function float64(params) {\n return core._float64(ZodMiniNumberFormat, params);\n}\n// int32\n// @__NO_SIDE_EFFECTS__\nexport function int32(params) {\n return core._int32(ZodMiniNumberFormat, params);\n}\n// uint32\n// @__NO_SIDE_EFFECTS__\nexport function uint32(params) {\n return core._uint32(ZodMiniNumberFormat, params);\n}\nexport const ZodMiniBoolean = /*@__PURE__*/ core.$constructor(\"ZodMiniBoolean\", (inst, def) => {\n core.$ZodBoolean.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function boolean(params) {\n return core._boolean(ZodMiniBoolean, params);\n}\nexport const ZodMiniBigInt = /*@__PURE__*/ core.$constructor(\"ZodMiniBigInt\", (inst, def) => {\n core.$ZodBigInt.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function bigint(params) {\n return core._bigint(ZodMiniBigInt, params);\n}\nexport const ZodMiniBigIntFormat = /*@__PURE__*/ core.$constructor(\"ZodMiniBigIntFormat\", (inst, def) => {\n core.$ZodBigIntFormat.init(inst, def);\n ZodMiniBigInt.init(inst, def);\n});\n// int64\n// @__NO_SIDE_EFFECTS__\nexport function int64(params) {\n return core._int64(ZodMiniBigIntFormat, params);\n}\n// uint64\n// @__NO_SIDE_EFFECTS__\nexport function uint64(params) {\n return core._uint64(ZodMiniBigIntFormat, params);\n}\nexport const ZodMiniSymbol = /*@__PURE__*/ core.$constructor(\"ZodMiniSymbol\", (inst, def) => {\n core.$ZodSymbol.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function symbol(params) {\n return core._symbol(ZodMiniSymbol, params);\n}\nexport const ZodMiniUndefined = /*@__PURE__*/ core.$constructor(\"ZodMiniUndefined\", (inst, def) => {\n core.$ZodUndefined.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nfunction _undefined(params) {\n return core._undefined(ZodMiniUndefined, params);\n}\nexport { _undefined as undefined };\nexport const ZodMiniNull = /*@__PURE__*/ core.$constructor(\"ZodMiniNull\", (inst, def) => {\n core.$ZodNull.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nfunction _null(params) {\n return core._null(ZodMiniNull, params);\n}\nexport { _null as null };\nexport const ZodMiniAny = /*@__PURE__*/ core.$constructor(\"ZodMiniAny\", (inst, def) => {\n core.$ZodAny.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function any() {\n return core._any(ZodMiniAny);\n}\nexport const ZodMiniUnknown = /*@__PURE__*/ core.$constructor(\"ZodMiniUnknown\", (inst, def) => {\n core.$ZodUnknown.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function unknown() {\n return core._unknown(ZodMiniUnknown);\n}\nexport const ZodMiniNever = /*@__PURE__*/ core.$constructor(\"ZodMiniNever\", (inst, def) => {\n core.$ZodNever.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function never(params) {\n return core._never(ZodMiniNever, params);\n}\nexport const ZodMiniVoid = /*@__PURE__*/ core.$constructor(\"ZodMiniVoid\", (inst, def) => {\n core.$ZodVoid.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nfunction _void(params) {\n return core._void(ZodMiniVoid, params);\n}\nexport { _void as void };\nexport const ZodMiniDate = /*@__PURE__*/ core.$constructor(\"ZodMiniDate\", (inst, def) => {\n core.$ZodDate.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function date(params) {\n return core._date(ZodMiniDate, params);\n}\nexport const ZodMiniArray = /*@__PURE__*/ core.$constructor(\"ZodMiniArray\", (inst, def) => {\n core.$ZodArray.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function array(element, params) {\n return new ZodMiniArray({\n type: \"array\",\n element: element,\n ...util.normalizeParams(params),\n });\n}\n// .keyof\n// @__NO_SIDE_EFFECTS__\nexport function keyof(schema) {\n const shape = schema._zod.def.shape;\n return _enum(Object.keys(shape));\n}\nexport const ZodMiniObject = /*@__PURE__*/ core.$constructor(\"ZodMiniObject\", (inst, def) => {\n core.$ZodObject.init(inst, def);\n ZodMiniType.init(inst, def);\n util.defineLazy(inst, \"shape\", () => def.shape);\n});\n// @__NO_SIDE_EFFECTS__\nexport function object(shape, params) {\n const def = {\n type: \"object\",\n shape: shape ?? {},\n ...util.normalizeParams(params),\n };\n return new ZodMiniObject(def);\n}\n// strictObject\n// @__NO_SIDE_EFFECTS__\nexport function strictObject(shape, params) {\n return new ZodMiniObject({\n type: \"object\",\n shape,\n catchall: never(),\n ...util.normalizeParams(params),\n });\n}\n// looseObject\n// @__NO_SIDE_EFFECTS__\nexport function looseObject(shape, params) {\n return new ZodMiniObject({\n type: \"object\",\n shape,\n catchall: unknown(),\n ...util.normalizeParams(params),\n });\n}\n// object methods\n// @__NO_SIDE_EFFECTS__\nexport function extend(schema, shape) {\n return util.extend(schema, shape);\n}\n// @__NO_SIDE_EFFECTS__\nexport function safeExtend(schema, shape) {\n return util.safeExtend(schema, shape);\n}\n// @__NO_SIDE_EFFECTS__\nexport function merge(schema, shape) {\n return util.extend(schema, shape);\n}\n// @__NO_SIDE_EFFECTS__\nexport function pick(schema, mask) {\n return util.pick(schema, mask);\n}\n// .omit\n// @__NO_SIDE_EFFECTS__\nexport function omit(schema, mask) {\n return util.omit(schema, mask);\n}\n// @__NO_SIDE_EFFECTS__\nexport function partial(schema, mask) {\n return util.partial(ZodMiniOptional, schema, mask);\n}\n// @__NO_SIDE_EFFECTS__\nexport function required(schema, mask) {\n return util.required(ZodMiniNonOptional, schema, mask);\n}\n// @__NO_SIDE_EFFECTS__\nexport function catchall(inst, catchall) {\n return inst.clone({ ...inst._zod.def, catchall: catchall });\n}\nexport const ZodMiniUnion = /*@__PURE__*/ core.$constructor(\"ZodMiniUnion\", (inst, def) => {\n core.$ZodUnion.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function union(options, params) {\n return new ZodMiniUnion({\n type: \"union\",\n options: options,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniXor = /*@__PURE__*/ core.$constructor(\"ZodMiniXor\", (inst, def) => {\n ZodMiniUnion.init(inst, def);\n core.$ZodXor.init(inst, def);\n});\n/** Creates an exclusive union (XOR) where exactly one option must match.\n * Unlike regular unions that succeed when any option matches, xor fails if\n * zero or more than one option matches the input. */\nexport function xor(options, params) {\n return new ZodMiniXor({\n type: \"union\",\n options: options,\n inclusive: false,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniDiscriminatedUnion = /*@__PURE__*/ core.$constructor(\"ZodMiniDiscriminatedUnion\", (inst, def) => {\n core.$ZodDiscriminatedUnion.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function discriminatedUnion(discriminator, options, params) {\n return new ZodMiniDiscriminatedUnion({\n type: \"union\",\n options,\n discriminator,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniIntersection = /*@__PURE__*/ core.$constructor(\"ZodMiniIntersection\", (inst, def) => {\n core.$ZodIntersection.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function intersection(left, right) {\n return new ZodMiniIntersection({\n type: \"intersection\",\n left: left,\n right: right,\n });\n}\nexport const ZodMiniTuple = /*@__PURE__*/ core.$constructor(\"ZodMiniTuple\", (inst, def) => {\n core.$ZodTuple.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function tuple(items, _paramsOrRest, _params) {\n const hasRest = _paramsOrRest instanceof core.$ZodType;\n const params = hasRest ? _params : _paramsOrRest;\n const rest = hasRest ? _paramsOrRest : null;\n return new ZodMiniTuple({\n type: \"tuple\",\n items: items,\n rest,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniRecord = /*@__PURE__*/ core.$constructor(\"ZodMiniRecord\", (inst, def) => {\n core.$ZodRecord.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function record(keyType, valueType, params) {\n // v3-compat: z.record(valueType, params?) — defaults keyType to z.string()\n if (!valueType || !valueType._zod) {\n return new ZodMiniRecord({\n type: \"record\",\n keyType: string(),\n valueType: keyType,\n ...util.normalizeParams(valueType),\n });\n }\n return new ZodMiniRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function partialRecord(keyType, valueType, params) {\n const k = core.clone(keyType);\n k._zod.values = undefined;\n return new ZodMiniRecord({\n type: \"record\",\n keyType: k,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport function looseRecord(keyType, valueType, params) {\n return new ZodMiniRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n mode: \"loose\",\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniMap = /*@__PURE__*/ core.$constructor(\"ZodMiniMap\", (inst, def) => {\n core.$ZodMap.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function map(keyType, valueType, params) {\n return new ZodMiniMap({\n type: \"map\",\n keyType: keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniSet = /*@__PURE__*/ core.$constructor(\"ZodMiniSet\", (inst, def) => {\n core.$ZodSet.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function set(valueType, params) {\n return new ZodMiniSet({\n type: \"set\",\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniEnum = /*@__PURE__*/ core.$constructor(\"ZodMiniEnum\", (inst, def) => {\n core.$ZodEnum.init(inst, def);\n ZodMiniType.init(inst, def);\n inst.options = Object.values(def.entries);\n});\n// @__NO_SIDE_EFFECTS__\nfunction _enum(values, params) {\n const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;\n return new ZodMiniEnum({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\nexport { _enum as enum };\n// @__NO_SIDE_EFFECTS__\n/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.\n *\n * ```ts\n * enum Colors { red, green, blue }\n * z.enum(Colors);\n * ```\n */\nexport function nativeEnum(entries, params) {\n return new ZodMiniEnum({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniLiteral = /*@__PURE__*/ core.$constructor(\"ZodMiniLiteral\", (inst, def) => {\n core.$ZodLiteral.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function literal(value, params) {\n return new ZodMiniLiteral({\n type: \"literal\",\n values: Array.isArray(value) ? value : [value],\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniFile = /*@__PURE__*/ core.$constructor(\"ZodMiniFile\", (inst, def) => {\n core.$ZodFile.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function file(params) {\n return core._file(ZodMiniFile, params);\n}\nexport const ZodMiniTransform = /*@__PURE__*/ core.$constructor(\"ZodMiniTransform\", (inst, def) => {\n core.$ZodTransform.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function transform(fn) {\n return new ZodMiniTransform({\n type: \"transform\",\n transform: fn,\n });\n}\nexport const ZodMiniOptional = /*@__PURE__*/ core.$constructor(\"ZodMiniOptional\", (inst, def) => {\n core.$ZodOptional.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function optional(innerType) {\n return new ZodMiniOptional({\n type: \"optional\",\n innerType: innerType,\n });\n}\nexport const ZodMiniExactOptional = /*@__PURE__*/ core.$constructor(\"ZodMiniExactOptional\", (inst, def) => {\n core.$ZodExactOptional.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function exactOptional(innerType) {\n return new ZodMiniExactOptional({\n type: \"optional\",\n innerType: innerType,\n });\n}\nexport const ZodMiniNullable = /*@__PURE__*/ core.$constructor(\"ZodMiniNullable\", (inst, def) => {\n core.$ZodNullable.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function nullable(innerType) {\n return new ZodMiniNullable({\n type: \"nullable\",\n innerType: innerType,\n });\n}\n// nullish\n// @__NO_SIDE_EFFECTS__\nexport function nullish(innerType) {\n return optional(nullable(innerType));\n}\nexport const ZodMiniDefault = /*@__PURE__*/ core.$constructor(\"ZodMiniDefault\", (inst, def) => {\n core.$ZodDefault.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function _default(innerType, defaultValue) {\n return new ZodMiniDefault({\n type: \"default\",\n innerType: innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\nexport const ZodMiniPrefault = /*@__PURE__*/ core.$constructor(\"ZodMiniPrefault\", (inst, def) => {\n core.$ZodPrefault.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function prefault(innerType, defaultValue) {\n return new ZodMiniPrefault({\n type: \"prefault\",\n innerType: innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\nexport const ZodMiniNonOptional = /*@__PURE__*/ core.$constructor(\"ZodMiniNonOptional\", (inst, def) => {\n core.$ZodNonOptional.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function nonoptional(innerType, params) {\n return new ZodMiniNonOptional({\n type: \"nonoptional\",\n innerType: innerType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniSuccess = /*@__PURE__*/ core.$constructor(\"ZodMiniSuccess\", (inst, def) => {\n core.$ZodSuccess.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function success(innerType) {\n return new ZodMiniSuccess({\n type: \"success\",\n innerType: innerType,\n });\n}\nexport const ZodMiniCatch = /*@__PURE__*/ core.$constructor(\"ZodMiniCatch\", (inst, def) => {\n core.$ZodCatch.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nfunction _catch(innerType, catchValue) {\n return new ZodMiniCatch({\n type: \"catch\",\n innerType: innerType,\n catchValue: (typeof catchValue === \"function\" ? catchValue : () => catchValue),\n });\n}\nexport { _catch as catch };\nexport const ZodMiniNaN = /*@__PURE__*/ core.$constructor(\"ZodMiniNaN\", (inst, def) => {\n core.$ZodNaN.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function nan(params) {\n return core._nan(ZodMiniNaN, params);\n}\nexport const ZodMiniPipe = /*@__PURE__*/ core.$constructor(\"ZodMiniPipe\", (inst, def) => {\n core.$ZodPipe.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function pipe(in_, out) {\n return new ZodMiniPipe({\n type: \"pipe\",\n in: in_,\n out: out,\n });\n}\nexport const ZodMiniCodec = /*@__PURE__*/ core.$constructor(\"ZodMiniCodec\", (inst, def) => {\n ZodMiniPipe.init(inst, def);\n core.$ZodCodec.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function codec(in_, out, params) {\n return new ZodMiniCodec({\n type: \"pipe\",\n in: in_,\n out: out,\n transform: params.decode,\n reverseTransform: params.encode,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function invertCodec(codec) {\n const def = codec._zod.def;\n return new ZodMiniCodec({\n type: \"pipe\",\n in: def.out,\n out: def.in,\n transform: def.reverseTransform,\n reverseTransform: def.transform,\n });\n}\nexport const ZodMiniReadonly = /*@__PURE__*/ core.$constructor(\"ZodMiniReadonly\", (inst, def) => {\n core.$ZodReadonly.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function readonly(innerType) {\n return new ZodMiniReadonly({\n type: \"readonly\",\n innerType: innerType,\n });\n}\nexport const ZodMiniTemplateLiteral = /*@__PURE__*/ core.$constructor(\"ZodMiniTemplateLiteral\", (inst, def) => {\n core.$ZodTemplateLiteral.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function templateLiteral(parts, params) {\n return new ZodMiniTemplateLiteral({\n type: \"template_literal\",\n parts,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniLazy = /*@__PURE__*/ core.$constructor(\"ZodMiniLazy\", (inst, def) => {\n core.$ZodLazy.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// export function lazy<T extends object>(getter: () => T): T {\n// return util.createTransparentProxy<T>(getter);\n// }\n// @__NO_SIDE_EFFECTS__\nfunction _lazy(getter) {\n return new ZodMiniLazy({\n type: \"lazy\",\n getter: getter,\n });\n}\nexport { _lazy as lazy };\nexport const ZodMiniPromise = /*@__PURE__*/ core.$constructor(\"ZodMiniPromise\", (inst, def) => {\n core.$ZodPromise.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function promise(innerType) {\n return new ZodMiniPromise({\n type: \"promise\",\n innerType: innerType,\n });\n}\nexport const ZodMiniCustom = /*@__PURE__*/ core.$constructor(\"ZodMiniCustom\", (inst, def) => {\n core.$ZodCustom.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// custom checks\n// @__NO_SIDE_EFFECTS__\nexport function check(fn, params) {\n const ch = new core.$ZodCheck({\n check: \"custom\",\n ...util.normalizeParams(params),\n });\n ch._zod.check = fn;\n return ch;\n}\n// ZodCustom\n// custom schema\n// @__NO_SIDE_EFFECTS__\nexport function custom(fn, _params) {\n return core._custom(ZodMiniCustom, fn ?? (() => true), _params);\n}\n// refine\n// @__NO_SIDE_EFFECTS__\nexport function refine(fn, _params = {}) {\n return core._refine(ZodMiniCustom, fn, _params);\n}\n// superRefine\n// @__NO_SIDE_EFFECTS__\nexport function superRefine(fn, params) {\n return core._superRefine(fn, params);\n}\n// Re-export describe and meta from core\nexport const describe = core.describe;\nexport const meta = core.meta;\n// instanceof\nclass Class {\n constructor(..._args) { }\n}\n// @__NO_SIDE_EFFECTS__\nfunction _instanceof(cls, params = {}) {\n const inst = custom((data) => data instanceof cls, params);\n inst._zod.bag.Class = cls;\n // Override check to emit invalid_type instead of custom\n inst._zod.check = (payload) => {\n if (!(payload.value instanceof cls)) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: cls.name,\n input: payload.value,\n inst,\n path: [...(inst._zod.def.path ?? [])],\n });\n }\n };\n return inst;\n}\nexport { _instanceof as instanceof };\n// stringbool\nexport const stringbool = (...args) => core._stringbool({\n Codec: ZodMiniCodec,\n Boolean: ZodMiniBoolean,\n String: ZodMiniString,\n}, ...args);\n// @__NO_SIDE_EFFECTS__\nexport function json() {\n const jsonSchema = _lazy(() => {\n return union([string(), number(), boolean(), _null(), array(jsonSchema), record(string(), jsonSchema)]);\n });\n return jsonSchema;\n}\nexport const ZodMiniFunction = /*@__PURE__*/ core.$constructor(\"ZodMiniFunction\", (inst, def) => {\n core.$ZodFunction.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function _function(params) {\n return new ZodMiniFunction({\n type: \"function\",\n input: Array.isArray(params?.input) ? tuple(params?.input) : (params?.input ?? array(unknown())),\n output: params?.output ?? unknown(),\n });\n}\nexport { _function as function };\n","// `zod/mini` (tree-shakable functional API) instead of the full `zod` entry:\n// the widget only needs object/string/literal/union/nullable, and the mini\n// build keeps roughly 40KB of parser/refinement code out of the bundle.\nimport * as z from \"zod/mini\";\nimport { config as zodConfig } from \"zod/v4/core\";\n\n// Disable Zod's JIT-compiled fast path: it probes `Function(\"\")` at runtime,\n// which host pages with a strict Content-Security-Policy (no 'unsafe-eval')\n// block and report as a CSP violation on every widget load. Validation\n// behaves identically in jitless mode, just without eval-based codegen.\nzodConfig({ jitless: true });\n\nconst utteranceSchema = z.object({\n type: z.literal(\"utterance\"),\n content: z.string(),\n role: z.string(),\n});\n\nconst agentCognitionSchema = z.object({\n type: z.literal(\"agent_cognition\"),\n content: z.string(),\n});\n\nconst chatClosedExpiredSchema = z.object({\n type: z.literal(\"chat_closed_expired\"),\n content: z.string(),\n});\n\nconst agentCapturedUrlSchema = z.object({\n type: z.literal(\"agent_captured_url\"),\n content: z.string(),\n});\n\nconst agentTopicSchema = z.object({\n type: z.literal(\"agent_topic\"),\n content: z.string(),\n});\n\nconst agentSummarySchema = z.object({\n type: z.literal(\"agent_summary\"),\n content: z.string(),\n});\n\nconst chatRatingSchema = z.object({\n type: z.literal(\"chat_rating\"),\n content: z.string(),\n});\n\nconst breadcrumbSchema = z.object({\n type: z.literal(\"breadcrumb\"),\n content: z.string(),\n});\n\nconst chatEscalatedSchema = z.object({\n type: z.literal(\"chat_escalated\"),\n content: z.null(),\n});\n\nconst errorSchema = z.object({\n type: z.literal(\"error\"),\n code: z.string(),\n});\n\nconst utteranceApiResponseSchema = z.object({\n message_id: z.nullable(z.string()),\n created_at: z.string(),\n data: utteranceSchema,\n});\n\nconst errorApiResponseSchema = z.object({\n created_at: z.string(),\n data: errorSchema,\n});\n\nconst agentCognitionApiResponseSchema = z.object({\n created_at: z.string(),\n data: agentCognitionSchema,\n});\n\nconst chatClosedExpiredApiResponseSchema = z.object({\n message_id: z.nullable(z.string()),\n created_at: z.string(),\n data: chatClosedExpiredSchema,\n});\n\nconst agentCapturedUrlApiResponseSchema = z.object({\n created_at: z.string(),\n data: agentCapturedUrlSchema,\n});\n\nconst agentTopicApiResponseSchema = z.object({\n created_at: z.string(),\n data: agentTopicSchema,\n});\n\nconst agentSummaryApiResponseSchema = z.object({\n created_at: z.string(),\n data: agentSummarySchema,\n});\n\nconst chatRatingApiResponseSchema = z.object({\n created_at: z.string(),\n data: chatRatingSchema,\n});\n\nconst breadcrumbApiResponseSchema = z.object({\n created_at: z.string(),\n data: breadcrumbSchema,\n});\n\nconst chatEscalatedApiResponseSchema = z.object({\n message_id: z.nullable(z.string()),\n created_at: z.string(),\n data: chatEscalatedSchema,\n});\n\nexport const chatResponseApiSchema = z.union([\n utteranceApiResponseSchema,\n errorApiResponseSchema,\n agentCognitionApiResponseSchema,\n agentCapturedUrlApiResponseSchema,\n agentTopicApiResponseSchema,\n agentSummaryApiResponseSchema,\n chatClosedExpiredApiResponseSchema,\n chatRatingApiResponseSchema,\n breadcrumbApiResponseSchema,\n chatEscalatedApiResponseSchema,\n]);\n\nexport type ChatResponseApi = z.infer<typeof chatResponseApiSchema>;\n\ntype NotificationData = ChatResponseApi[\"data\"];\n\nexport type UtteranceNotification = {\n message_id: string | null;\n created_at: string;\n data: Extract<NotificationData, { type: \"utterance\" }>;\n};\n\nexport type ErrorNotification = {\n created_at: string;\n data: Extract<NotificationData, { type: \"error\" }>;\n};\n\nexport type AgentCognitionNotification = {\n created_at: string;\n data: Extract<NotificationData, { type: \"agent_cognition\" }>;\n};\n\nexport type AgentCapturedUrlNotification = {\n created_at: string;\n data: Extract<NotificationData, { type: \"agent_captured_url\" }>;\n};\n\nexport type AgentTopicNotification = {\n created_at: string;\n data: Extract<NotificationData, { type: \"agent_topic\" }>;\n};\n\nexport type AgentSummaryNotification = {\n created_at: string;\n data: Extract<NotificationData, { type: \"agent_summary\" }>;\n};\n\nexport const chatResponseSchema = z.object({\n message_id: z.string(), // message_id from api schema\n response: z.object({\n id: z.string(), // message_id from api schema\n type: z.string(),\n content: z.string(),\n }),\n});\n\nexport type ChatResponse = z.infer<typeof chatResponseSchema>;\n","import { useCallback, useEffect, useRef } from \"react\";\n\nimport { useErrorContext } from \"@/contexts/error-handling.utils\";\nimport { getErrorMessage } from \"@/contexts/utils\";\nimport { useLatestRef } from \"@/hooks/use-latest-ref\";\nimport {\n connectAppSyncEvents,\n type AppSyncEventsConnection,\n} from \"@/lib/appsync-events-client\";\nimport { BootResponse, MessageResponse } from \"@/lib/eloquent-ai-api-client\";\nimport { Message } from \"@/type\";\n\nimport {\n AgentCapturedUrlNotification,\n AgentCognitionNotification,\n AgentSummaryNotification,\n AgentTopicNotification,\n ChatResponse,\n chatResponseApiSchema,\n ErrorNotification,\n UtteranceNotification,\n} from \"./validations\";\n\nconst INITIAL_RECONNECT_DELAY_MS = 500;\nconst MAX_RECONNECT_DELAY_MS = 30000;\nconst DEFAULT_BACKUP_POLL_INTERVAL_MS = 60000;\n\nexport type UseRealtimeSocketOptions = {\n chatSettings: BootResponse[\"chat_settings\"] | null;\n chatId: string | null;\n messages: Message[];\n onMessage: (response: ChatResponse, chatId: string) => void;\n onCognition: (content: string) => void;\n onCognitionComplete: () => void;\n onError?: () => void;\n onChatClosed?: () => void;\n onAgentCapturedUrl?: (content: string) => void;\n onAgentTopic?: (content: string) => void;\n onAgentSummary?: (content: string) => void;\n onRatingRequest?: () => void;\n onBreadcrumb?: () => void;\n fetchHistory: (chatId: string) => Promise<MessageResponse[]>;\n getChatToken: () => string | null;\n backupPollingInterval?: number;\n};\n\nexport type UseRealtimeSocketReturn = {\n connect: (chatId: string) => Promise<void>;\n disconnect: () => void;\n clearProcessedIds: () => void;\n};\n\nexport function useRealtimeSocket({\n chatSettings,\n chatId,\n messages,\n onMessage,\n onCognition,\n onCognitionComplete,\n onError,\n onChatClosed,\n onAgentCapturedUrl,\n onAgentTopic,\n onAgentSummary,\n onRatingRequest,\n onBreadcrumb,\n fetchHistory,\n getChatToken,\n backupPollingInterval = DEFAULT_BACKUP_POLL_INTERVAL_MS,\n}: UseRealtimeSocketOptions): UseRealtimeSocketReturn {\n const processedIdsRef = useRef<Set<string>>(new Set());\n\n useEffect(() => {\n for (const msg of messages) {\n if (msg.id) processedIdsRef.current.add(msg.id);\n }\n }, [messages]);\n\n const eventChannelRef = useRef<AppSyncEventsConnection | null>(null);\n const activeChatIdRef = useRef<string | null>(null);\n const reconnectAttemptsRef = useRef(0);\n const reconnectTimerRef = useRef<NodeJS.Timeout | null>(null);\n const backupPollIntervalRef = useRef<NodeJS.Timeout | null>(null);\n const shouldReconnectRef = useRef(false);\n const isReconnectingRef = useRef(false);\n\n // Keep all mutable callbacks as latest-refs to avoid stale closures in\n // timers/intervals and the long-lived socket subscription.\n const onMessageRef = useLatestRef(onMessage);\n const onCognitionRef = useLatestRef(onCognition);\n const onCognitionCompleteRef = useLatestRef(onCognitionComplete);\n const onErrorRef = useLatestRef(onError);\n const onChatClosedRef = useLatestRef(onChatClosed);\n const onAgentCapturedUrlRef = useLatestRef(onAgentCapturedUrl);\n const onAgentTopicRef = useLatestRef(onAgentTopic);\n const onAgentSummaryRef = useLatestRef(onAgentSummary);\n const onRatingRequestRef = useLatestRef(onRatingRequest);\n const onBreadcrumbRef = useLatestRef(onBreadcrumb);\n const fetchHistoryRef = useLatestRef(fetchHistory);\n const getChatTokenRef = useLatestRef(getChatToken);\n\n const { publishError } = useErrorContext();\n\n const appSyncUrl = chatSettings?.app_sync_url;\n const appSyncApiKey = chatSettings?.app_sync_api_key;\n // The client is configuration-free (no Amplify.configure singleton) —\n // connections are ready as soon as boot settings provide the endpoint.\n const isSocketConfigReady = Boolean(appSyncUrl && appSyncApiKey);\n const appSyncUrlRef = useLatestRef(appSyncUrl);\n const appSyncApiKeyRef = useLatestRef(appSyncApiKey);\n\n const closeChannel = useCallback(() => {\n if (eventChannelRef.current) {\n eventChannelRef.current.close();\n eventChannelRef.current = null;\n }\n }, []);\n\n const stopBackupPoll = useCallback(() => {\n if (backupPollIntervalRef.current) {\n clearInterval(backupPollIntervalRef.current);\n backupPollIntervalRef.current = null;\n }\n }, []);\n\n const clearReconnectTimer = useCallback(() => {\n if (reconnectTimerRef.current) {\n clearTimeout(reconnectTimerRef.current);\n reconnectTimerRef.current = null;\n }\n }, []);\n\n // Forward-declared: connectChannel's onDisconnect needs scheduleReconnect,\n // which itself needs connectChannel — the ref breaks the cycle. Synced to\n // the latest scheduleReconnect below.\n const scheduleReconnectRef = useRef<() => void>(() => {});\n\n // Opens an AppSync Events channel and subscribes to real-time events\n const connectChannel = useCallback(\n async (chatIdToConnect: string): Promise<void> => {\n closeChannel();\n const httpEndpoint = appSyncUrlRef.current;\n const apiKey = appSyncApiKeyRef.current;\n if (!httpEndpoint || !apiKey) {\n throw new Error(\"Cannot connect: AppSync settings not available\");\n }\n const chatToken = getChatTokenRef.current();\n\n const connection = await connectAppSyncEvents({\n httpEndpoint,\n auth: chatToken ? { authorizationToken: chatToken } : { apiKey },\n channel: `/default/chat/${chatIdToConnect}`,\n onDisconnect: () => {\n eventChannelRef.current = null;\n scheduleReconnectRef.current();\n },\n onEvent: (event) => {\n const parseResult = chatResponseApiSchema.safeParse(event);\n if (!parseResult.success) {\n console.error(\"Invalid conversation response:\", parseResult.error);\n return;\n }\n\n const notification = parseResult.data;\n switch (notification.data.type) {\n case \"utterance\": {\n const utterance = notification as UtteranceNotification;\n const messageId = utterance.message_id ?? crypto.randomUUID();\n if (processedIdsRef.current.has(messageId)) {\n return;\n }\n processedIdsRef.current.add(messageId);\n onCognitionCompleteRef.current();\n onMessageRef.current(\n {\n message_id: messageId,\n response: {\n id: messageId,\n type: utterance.data.type,\n content: utterance.data.content,\n },\n },\n chatIdToConnect,\n );\n return;\n }\n case \"error\": {\n const errorNotif = notification as ErrorNotification;\n const code = parseInt(errorNotif.data.code);\n publishError({ code, message: getErrorMessage(code) });\n onErrorRef.current?.();\n return;\n }\n case \"agent_cognition\": {\n const cognition = notification as AgentCognitionNotification;\n onCognitionRef.current(cognition.data.content);\n return;\n }\n case \"agent_captured_url\": {\n const capturedUrl = notification as AgentCapturedUrlNotification;\n onAgentCapturedUrlRef.current?.(capturedUrl.data.content);\n return;\n }\n case \"agent_topic\": {\n const topic = notification as AgentTopicNotification;\n onAgentTopicRef.current?.(topic.data.content);\n return;\n }\n case \"agent_summary\": {\n const summary = notification as AgentSummaryNotification;\n onAgentSummaryRef.current?.(summary.data.content);\n return;\n }\n case \"chat_closed_expired\": {\n onChatClosedRef.current?.();\n onRatingRequestRef.current?.();\n return;\n }\n case \"chat_rating\": {\n onRatingRequestRef.current?.();\n return;\n }\n case \"breadcrumb\": {\n onBreadcrumbRef.current?.();\n return;\n }\n case \"chat_escalated\": {\n onChatClosedRef.current?.();\n onRatingRequestRef.current?.();\n return;\n }\n default:\n console.warn(\n \"Unknown notification type:\",\n (notification as { data: { type: string } }).data.type,\n );\n }\n },\n });\n\n eventChannelRef.current = connection;\n },\n // The *Ref entries are latest-refs (stable identities); listed to satisfy\n // exhaustive-deps, which can't see that useLatestRef returns a ref.\n [\n closeChannel,\n publishError,\n appSyncUrlRef,\n appSyncApiKeyRef,\n getChatTokenRef,\n onMessageRef,\n onCognitionRef,\n onCognitionCompleteRef,\n onErrorRef,\n onChatClosedRef,\n onAgentCapturedUrlRef,\n onAgentTopicRef,\n onAgentSummaryRef,\n onRatingRequestRef,\n onBreadcrumbRef,\n ],\n );\n\n // Fetches history and delivers any unseen assistant messages via onMessage\n const runBackupPoll = useCallback(\n async (chatIdToPoll: string) => {\n try {\n const history = await fetchHistoryRef.current(chatIdToPoll);\n for (const msg of history) {\n if (\n msg.role !== \"assistant\" ||\n !msg.message_id ||\n processedIdsRef.current.has(msg.message_id)\n ) {\n continue;\n }\n processedIdsRef.current.add(msg.message_id);\n onMessageRef.current(\n { message_id: msg.message_id, response: msg.response },\n chatIdToPoll,\n );\n }\n } catch (err) {\n console.warn(\"Backup poll failed:\", err);\n }\n },\n [fetchHistoryRef, onMessageRef],\n );\n\n const startBackupPoll = useCallback(\n (chatIdToPoll: string) => {\n stopBackupPoll();\n backupPollIntervalRef.current = setInterval(\n () => runBackupPoll(chatIdToPoll),\n backupPollingInterval,\n );\n },\n [stopBackupPoll, runBackupPoll, backupPollingInterval],\n );\n\n // Named function expression so the setTimeout callback can re-schedule\n // itself on failure without a circular ref dependency.\n const scheduleReconnect = useCallback(\n function scheduleReconnectSelf() {\n if (\n !shouldReconnectRef.current ||\n isReconnectingRef.current ||\n reconnectTimerRef.current\n ) {\n return;\n }\n const chatIdToReconnect = activeChatIdRef.current;\n if (!chatIdToReconnect) return;\n\n const delay = Math.min(\n INITIAL_RECONNECT_DELAY_MS * Math.pow(2, reconnectAttemptsRef.current),\n MAX_RECONNECT_DELAY_MS,\n );\n reconnectAttemptsRef.current += 1;\n\n reconnectTimerRef.current = setTimeout(async () => {\n reconnectTimerRef.current = null;\n isReconnectingRef.current = true;\n try {\n await connectChannel(chatIdToReconnect);\n reconnectAttemptsRef.current = 0;\n isReconnectingRef.current = false;\n await runBackupPoll(chatIdToReconnect);\n } catch {\n isReconnectingRef.current = false;\n scheduleReconnectSelf();\n }\n }, delay);\n },\n [connectChannel, runBackupPoll],\n );\n\n // Keep the forward-declared ref pointing at the latest scheduleReconnect\n // (same semantics as useLatestRef, but the ref had to exist earlier for\n // connectChannel's onDisconnect).\n useEffect(() => {\n scheduleReconnectRef.current = scheduleReconnect;\n });\n\n const connect = useCallback(\n async (chatIdToConnect: string): Promise<void> => {\n if (!isSocketConfigReady || !chatIdToConnect) {\n throw new Error(\n \"Cannot connect: AppSync settings not ready or missing chatId\",\n );\n }\n clearReconnectTimer();\n shouldReconnectRef.current = true;\n activeChatIdRef.current = chatIdToConnect;\n reconnectAttemptsRef.current = 0;\n // Start polling before the socket connect attempt, not after — if\n // connectChannel throws (e.g. the AppSync channel is unreachable),\n // polling must still run so messages keep arriving via history\n // instead of being lost entirely until a reconnect succeeds.\n startBackupPoll(chatIdToConnect);\n await connectChannel(chatIdToConnect);\n },\n [isSocketConfigReady, clearReconnectTimer, connectChannel, startBackupPoll],\n );\n\n const disconnect = useCallback((): void => {\n shouldReconnectRef.current = false;\n activeChatIdRef.current = null;\n reconnectAttemptsRef.current = 0;\n clearReconnectTimer();\n stopBackupPoll();\n closeChannel();\n }, [clearReconnectTimer, stopBackupPoll, closeChannel]);\n\n const clearProcessedIds = useCallback(() => {\n processedIdsRef.current.clear();\n }, []);\n\n // Eagerly connect when chatId becomes available (e.g., restored from localStorage on mount)\n useEffect(() => {\n if (!chatId || !isSocketConfigReady || activeChatIdRef.current === chatId)\n return;\n\n connect(chatId).catch((err) => {\n console.error(\"Failed to eagerly connect:\", err);\n activeChatIdRef.current = chatId;\n shouldReconnectRef.current = true;\n scheduleReconnectRef.current();\n });\n }, [chatId, isSocketConfigReady, connect]);\n\n // Disconnect detection lives inside connectAppSyncEvents (socket close and\n // keep-alive timeout both invoke connectChannel's onDisconnect), replacing\n // the amplify Hub connection-state listener.\n\n useEffect(() => {\n return () => {\n disconnect();\n };\n }, [disconnect]);\n\n return { connect, disconnect, clearProcessedIds };\n}\n","\"use client\";\nimport {\n useCallback,\n useEffect,\n type Dispatch,\n type SetStateAction,\n} from \"react\";\n\nimport { Message, MessageData } from \"@/type\";\n\nimport {\n BootResponse,\n EloquentAiApiClient,\n} from \"@/lib/eloquent-ai-api-client\";\n\nimport { useErrorContext } from \"@/contexts/error-handling.utils\";\nimport { useAgentCognitionContext } from \"@/hooks/use-agent-cognition-context\";\nimport { useLatestRef } from \"@/hooks/use-latest-ref\";\nimport { NetworkError, ServerError } from \"@/lib/http\";\nimport { getCurrentUrlSearchParams } from \"@/lib/url-params\";\nimport { usePersistence } from \"./persistence.hook\";\nimport { useRealtimeSocket } from \"./realtime-socket.hook\";\nimport { ChatResponse } from \"./validations\";\n\nexport interface UseMessageEventsProps {\n appId: string;\n userId: string;\n userName?: string;\n userData?: Record<string, string | number | boolean>;\n externalId?: string | null;\n deviceId: string;\n apiClient: EloquentAiApiClient | null;\n chatSettings: BootResponse[\"chat_settings\"] | null;\n messages: Message[];\n setMessages: Dispatch<SetStateAction<Message[]>>;\n currentChat: { id: string } | null;\n setCurrentChat: Dispatch<SetStateAction<{ id: string } | null>>;\n onChatClosed?: () => void;\n isChatClosed?: boolean;\n}\n\nexport interface UseMessageEventsReturn {\n onCleanMessages: () => void;\n onSendMessage: (data: MessageData) => Promise<void>;\n onRateChat: (rating: number) => Promise<void>;\n}\n\n/**\n * Hook to handle message events like sending and cleaning\n */\nexport function useMessageEvents({\n appId,\n userId,\n userName,\n userData,\n externalId,\n deviceId,\n apiClient,\n chatSettings,\n messages,\n setMessages,\n currentChat,\n setCurrentChat,\n onChatClosed,\n isChatClosed,\n}: UseMessageEventsProps): UseMessageEventsReturn {\n const { saveChatData, clearChatData, updateLastActivity, markChatClosed } =\n usePersistence({\n appId,\n });\n\n const { publishApiError, publishNetworkError } = useErrorContext();\n const { showCognition, hideCognition } = useAgentCognitionContext();\n\n // Keep apiClient in a ref so stable callbacks always use the latest instance\n const apiClientRef = useLatestRef(apiClient);\n\n /**\n * Handles receiving messages from the server.\n * Called by the WebSocket and backup poll — deduplication\n * is handled inside useRealtimeSocket via processedIds.\n */\n const onReceiveMessage = useCallback(\n (response: ChatResponse, chatId: string) => {\n if (!response.response.content) return;\n\n setMessages((prev) => {\n if (prev.some((msg) => msg.isRatingRequest)) return prev;\n // Ignore the message if it matches the configured welcome message\n if (\n chatSettings?.welcome_message &&\n response.response.content === chatSettings.welcome_message\n )\n return prev;\n const filteredMessages = prev.filter((msg) => !msg.isThinking);\n const updatedMessages: Message[] = [\n ...filteredMessages,\n {\n id: response.message_id,\n content: response.response.content ?? \"\",\n sender: \"assistant\" as const,\n timestamp: new Date().toISOString(),\n },\n ];\n saveChatData(\n chatId,\n userId,\n updatedMessages,\n deviceId,\n apiClientRef.current?.getChatToken(),\n );\n return updatedMessages;\n });\n },\n [chatSettings, deviceId, saveChatData, setMessages, userId, apiClientRef],\n );\n\n const handleRealTimeError = useCallback(() => {\n hideCognition();\n setMessages((prev) => prev.filter((msg) => !msg.isThinking));\n }, [setMessages, hideCognition]);\n\n const handleRatingRequest = useCallback(() => {\n setMessages((prev) => {\n const filtered = prev.filter((msg) => !msg.isRatingRequest);\n return [\n ...filtered,\n {\n id: crypto.randomUUID(),\n content: \"\",\n sender: \"assistant\" as const,\n timestamp: new Date().toISOString(),\n isRatingRequest: true,\n },\n ];\n });\n }, [setMessages]);\n\n useEffect(() => {\n if (import.meta.env.DEV) {\n const w = window as unknown as Record<string, unknown>;\n w.EloquentAI_TriggerChatRating = handleRatingRequest;\n return () => {\n delete w.EloquentAI_TriggerChatRating;\n };\n }\n }, [handleRatingRequest]);\n\n const fetchHistory = useCallback(\n (chatId: string) => {\n if (!apiClientRef.current) return Promise.resolve([]);\n return apiClientRef.current.getChatHistory(chatId);\n },\n [apiClientRef],\n );\n\n const getChatToken = useCallback(() => {\n return apiClientRef.current?.getChatToken() ?? null;\n }, [apiClientRef]);\n\n const handleChatClosed = useCallback(() => {\n markChatClosed();\n onChatClosed?.();\n }, [markChatClosed, onChatClosed]);\n\n const { connect, disconnect, clearProcessedIds } = useRealtimeSocket({\n chatSettings,\n chatId: currentChat?.id ?? null,\n messages,\n onMessage: onReceiveMessage,\n onCognition: showCognition,\n onCognitionComplete: hideCognition,\n onError: handleRealTimeError,\n onChatClosed: handleChatClosed,\n onRatingRequest: handleRatingRequest,\n onBreadcrumb: handleChatClosed,\n fetchHistory,\n getChatToken,\n });\n\n const onCleanMessages = useCallback(() => {\n hideCognition();\n disconnect();\n clearProcessedIds();\n setMessages((prev) =>\n prev.filter((message) => {\n if (Array.isArray(message)) return false;\n return message.isWelcomeMessage;\n }),\n );\n clearChatData();\n setCurrentChat(null);\n }, [\n hideCognition,\n disconnect,\n clearProcessedIds,\n clearChatData,\n setMessages,\n setCurrentChat,\n ]);\n\n /**\n * Handles sending messages to the server\n */\n const onSendMessage = useCallback(\n async (message: MessageData) => {\n if (!apiClient) return;\n\n if (messages.some((msg) => msg.isRatingRequest)) return;\n\n if (isChatClosed) {\n setMessages((prev) => [\n ...prev,\n {\n id: crypto.randomUUID(),\n content: \"This conversation is closed, please start a new chat.\",\n sender: \"assistant\" as const,\n timestamp: new Date().toISOString(),\n },\n ]);\n return;\n }\n\n const userMessage = {\n ...message,\n id: crypto.randomUUID(),\n isNew: true,\n };\n\n showCognition();\n const newMessages = [...messages, userMessage];\n setMessages(newMessages);\n updateLastActivity();\n\n try {\n let chatId = currentChat?.id;\n if (!chatId) {\n const response = await apiClient.createConversation({\n userId: externalId || userId,\n deviceId,\n userName,\n userData,\n externalMetadata: {\n searchParams: getCurrentUrlSearchParams(),\n },\n });\n chatId = response.chat_id;\n setCurrentChat({ id: chatId });\n try {\n await connect(chatId);\n } catch (connectError) {\n console.warn(\n \"Failed to connect realtime channel, continuing with REST-only delivery:\",\n connectError,\n );\n }\n }\n\n const response = await apiClient.replyToConversation({\n text: message.content,\n conversationId: chatId,\n userId: externalId || userId,\n deviceId,\n userName,\n userData,\n });\n\n // Update user message with real server ID\n setMessages((prev) =>\n prev.map((msg) =>\n msg.id === userMessage.id\n ? { ...msg, id: response.message_id, isNew: false }\n : msg,\n ),\n );\n } catch (error) {\n hideCognition();\n\n setMessages((prev) => prev.filter((msg) => !msg.isThinking));\n\n if (\n error instanceof NetworkError ||\n (error instanceof ServerError && error.status === 403)\n ) {\n publishNetworkError();\n throw error;\n }\n\n publishApiError(error as ServerError);\n\n if (\n error instanceof ServerError &&\n // A 401 here means the chat's session token is invalid/expired\n // (or the chat closed) — treat it the same as a client-side\n // expired chat: drop the stale session and let the next send\n // start a fresh one, instead of surfacing an error.\n (error.status >= 500 || error.status === 401)\n ) {\n setCurrentChat(null);\n clearChatData();\n setMessages((prev) => prev.slice(0, -1));\n apiClient.reset();\n } else {\n // Mark the user message as failed\n setMessages((prev) =>\n prev.map((msg) =>\n msg.id === userMessage.id ? { ...msg, isFailed: true } : msg,\n ),\n );\n }\n\n throw error;\n }\n },\n [\n apiClient,\n isChatClosed,\n showCognition,\n messages,\n setMessages,\n updateLastActivity,\n currentChat?.id,\n externalId,\n userId,\n deviceId,\n setCurrentChat,\n connect,\n hideCognition,\n publishApiError,\n publishNetworkError,\n clearChatData,\n userName,\n userData,\n ],\n );\n\n const onRateChat = useCallback(\n async (rating: number) => {\n const chatId = currentChat?.id;\n if (!apiClientRef.current || !chatId) return;\n await apiClientRef.current.addRating(chatId, rating);\n },\n [currentChat?.id, apiClientRef],\n );\n\n return {\n onCleanMessages,\n onSendMessage,\n onRateChat,\n };\n}\n","// Helper to safely access import.meta.env in SSR environments\nfunction getEnvVariable(key: string): string {\n // Check if we're in a browser or if import.meta is available\n if (typeof window === \"undefined\" || typeof import.meta === \"undefined\") {\n return \"\";\n }\n return (import.meta.env[key] as string) || \"\";\n}\n\n// Define environment-specific constants that will be replaced during build\nconst ENV_API_URL = getEnvVariable(\"VITE_API_URL\");\nconst ENV_REGION_API_URL = getEnvVariable(\"VITE_REGION_API_URL\");\n\n/**\n * Returns the API URL based on the provided custom URL or the default API URL.\n * @returns The API URL.\n */\nexport function getApiUrl(): string {\n return ENV_API_URL || \"\";\n}\n\n/**\n * Returns the Region API URL based on the environment.\n * @returns The Region API URL.\n */\nexport function getRegionApiUrl(): string {\n return ENV_REGION_API_URL || \"\";\n}\n","import { getRegionApiUrl } from \"./config\";\nimport { HttpClient, HttpClientConfig } from \"./http\";\n\ninterface UserData {\n device_id: string;\n user_id?: string;\n user_name?: string;\n external_id?: string;\n user_data?: Record<string, string | number | boolean>;\n}\n\ninterface Message {\n text: string;\n user_data: UserData;\n}\n\nexport interface ConversationApiResponse {\n chat_id: string;\n message_id: string;\n response: {\n id: string;\n type: string;\n content: string;\n };\n}\n\nexport interface CreateConversationApiResponse {\n chat_id: string;\n chat_token: string;\n}\n\nexport interface IdentifyUserApiResponse {\n result: string;\n}\n\nexport interface MessageResponse {\n response: {\n id: string;\n type: string;\n content: string;\n };\n message_id: string;\n message_number: number;\n created_at: string;\n previousMessage?: MessageResponse;\n role: \"user\" | \"assistant\" | \"system\";\n}\n\nexport interface AddRatingApiResponse {\n result: string;\n}\n\nexport interface OrganizationResponse {\n region: string;\n}\n\nexport interface ExternalMetadata {\n [key: string]: string | ExternalMetadata;\n}\n\nexport interface BootResponse {\n chat_settings: {\n agent_name: string;\n welcome_message?: string | null;\n footer_html?: string | null;\n suggested_messages: boolean;\n suggested_message_texts?: string[] | null;\n suggested_message_aura?: boolean | null;\n suggested_message_shine?: boolean | null;\n auto_display_welcome_message: boolean;\n collect_user_feedback: boolean;\n theme: \"light\" | \"dark\";\n avatar_url?: string | null;\n user_bubble_color?: string | null;\n bot_bubble_color?: string | null;\n suggested_message_bubble_color?: string | null;\n user_bubble_text_color?: string | null;\n bot_bubble_text_color?: string | null;\n suggested_message_bubble_text_color?: string | null;\n app_sync_api_key: string;\n app_sync_url: string;\n app_sync_region: string;\n title?: string;\n subtitle?: string;\n is_active?: boolean;\n /** Open the chat window on load (desktop only). Wins over the isInitiallyOpen prop, but a `true` here never overrides the user's closed-cookie. */\n initial_open?: boolean | null;\n /** Show the close (X) button in the chat header. Always wins over the hasCloseButton prop. */\n close_button?: boolean | null;\n /** Show the clear-conversation button in the chat header. Always wins over the hasCleanChatButton prop. */\n clean_chat_button?: boolean | null;\n /** Auto-hide delay for the proactive message, in milliseconds. Always wins over the proactiveMessageHideDelay prop. */\n proactive_message_hide_delay?: number | null;\n };\n}\n\nexport class EloquentAiApiClient {\n private httpClient: HttpClient;\n private userId: string | null = null;\n private conversationId: string | null = null;\n\n constructor(config: HttpClientConfig) {\n this.userId = config.userId || null;\n this.httpClient = new HttpClient(config);\n }\n\n getUserData() {\n return {\n userId: this.userId,\n conversationId: this.conversationId,\n };\n }\n\n /**\n * Reset API client by clearing all stored state\n */\n reset() {\n this.conversationId = null;\n this.httpClient.setChatToken(null);\n }\n\n setRegion(region: string): void {\n this.httpClient.setRegion(region);\n }\n\n getChatToken(): string | null {\n return this.httpClient.getChatToken();\n }\n\n setChatToken(token: string | null): void {\n this.httpClient.setChatToken(token);\n }\n\n /**\n * Get organization data by app ID\n */\n async getOrganizationByAppId(appId: string) {\n const regionApiUrl = getRegionApiUrl();\n const response = await this.httpClient.getExternal<OrganizationResponse>(\n `${regionApiUrl}/by-app-id/${appId}`,\n );\n return response;\n }\n\n async boot() {\n const response = await this.httpClient.get<{ data: BootResponse }>(\n \"/v1/sdk/boot\",\n );\n return response.data;\n }\n\n async addRating(chatId: string, rating: number) {\n const response = await this.httpClient.put<\n { data: AddRatingApiResponse },\n { rating: number }\n >(`/v1/chat/${chatId}/rating`, { rating: rating });\n return response.data;\n }\n\n async createConversation(options: {\n userId: string;\n deviceId: string;\n userName?: string;\n externalId?: string;\n userData?: Record<string, string | number | boolean>;\n externalMetadata?: ExternalMetadata;\n }) {\n const response = await this.httpClient.post<\n { data: CreateConversationApiResponse },\n { user_data: UserData; external_metadata?: ExternalMetadata }\n >(\"/v2/chat\", {\n user_data: {\n user_id: options.userId,\n device_id: options.deviceId,\n user_name: options.userName,\n external_id: options.externalId,\n user_data: options.userData,\n },\n ...(options.externalMetadata &&\n Object.keys(options.externalMetadata).length > 0\n ? { external_metadata: options.externalMetadata }\n : {}),\n });\n\n const { data } = response;\n this.httpClient.setChatToken(data.chat_token);\n\n return data;\n }\n\n async replyToConversation(options: {\n text: string;\n conversationId: string;\n userId: string;\n deviceId: string;\n userName?: string;\n userData?: Record<string, string | number | boolean>;\n }) {\n const message: Message = {\n text: options.text,\n user_data: {\n device_id: options.deviceId,\n user_id: options.userId,\n user_name: options.userName,\n user_data: options.userData,\n },\n };\n\n const { data } = await this.httpClient.post<\n { data: ConversationApiResponse },\n Message\n >(`/v3/chat/${options.conversationId}`, message);\n\n return data;\n }\n\n async identifyUser(options: {\n conversationId: string;\n userId: string;\n deviceId: string;\n userName?: string;\n externalId?: string;\n userData?: Record<string, string | number | boolean>;\n }) {\n const message: UserData = {\n device_id: options.deviceId,\n user_id: options.userId,\n user_name: options.userName,\n external_id: options.externalId,\n user_data: options.userData,\n };\n\n const { data } = await this.httpClient.post<\n { data: IdentifyUserApiResponse },\n UserData\n >(`/v1/chat/${options.conversationId}/identify`, message);\n\n return data;\n }\n\n async getChatHistory(conversationId: string) {\n const response = await this.httpClient.get<{ data: MessageResponse[] }>(\n `/v1/chat/${conversationId}/history`,\n );\n return response.data;\n }\n}\n","import { NetworkError, ServerError } from \"./http\";\n\ninterface WithRetryOptions {\n retries?: number;\n minDelayMs?: number;\n maxDelayMs?: number;\n factor?: number;\n}\n\nconst DEFAULT_OPTIONS: Required<WithRetryOptions> = {\n retries: 3,\n minDelayMs: 200,\n maxDelayMs: 1_000,\n factor: 2,\n};\n\n/** Retries on network errors and 5xx/429 responses; other errors bail immediately. */\nexport function isRetryableError(error: unknown): boolean {\n if (error instanceof NetworkError) return true;\n if (error instanceof ServerError) {\n return error.status === 429 || error.status >= 500;\n }\n return false;\n}\n\n/** Exponential backoff with full jitter, mirroring the retry shape used in chat-api's http-retry.util.ts. */\nfunction getDelayMs(\n attempt: number,\n options: Required<WithRetryOptions>,\n): number {\n const exponentialDelay = options.minDelayMs * options.factor ** attempt;\n const cappedDelay = Math.min(exponentialDelay, options.maxDelayMs);\n return Math.random() * cappedDelay;\n}\n\nexport async function withRetry<T>(\n operation: () => Promise<T>,\n options: WithRetryOptions = {},\n): Promise<T> {\n const opts = { ...DEFAULT_OPTIONS, ...options };\n\n for (let attempt = 0; ; attempt++) {\n try {\n return await operation();\n } catch (error) {\n if (attempt >= opts.retries || !isRetryableError(error)) {\n throw error;\n }\n await new Promise((resolve) =>\n setTimeout(resolve, getDelayMs(attempt, opts)),\n );\n }\n }\n}\n","import { useErrorContext } from \"@/contexts/error-handling.utils\";\nimport { NetworkError, ServerError } from \"@/lib/http\";\nimport { useCallback, useRef, useState } from \"react\";\n\n// Module-level cache and in-flight promise tracker\nconst cache = new Map<string, unknown>();\nconst inflight = new Map<string, Promise<unknown>>();\n\ninterface UseFetchOptions {\n dedupe?: boolean;\n}\n\ninterface UseFetchResult<T, E> {\n data: T | undefined;\n error: E | undefined;\n isLoading: boolean;\n fetch: () => Promise<T>;\n}\n\n/**\n * useFetch hook that deduplicates requests and prevents double-fetching.\n * Fetch is triggered by calling the returned fetch function, not automatically.\n * @param key Unique key for the resource (should uniquely identify the request)\n * @param fetcher Function that returns a promise for the data\n * @param options Options object (dedupe: boolean)\n */\nexport function useFetch<T, E = Error>(\n key: string,\n fetcher: () => Promise<T | undefined>,\n options?: UseFetchOptions,\n): UseFetchResult<T, E> {\n const dedupe = options?.dedupe !== false; // default to true\n const [data, setData] = useState<T | undefined>(\n () => cache.get(key) as T | undefined,\n );\n const { publishApiError, publishNetworkError } = useErrorContext();\n\n const [error, setError] = useState<E | undefined>(undefined);\n const [isLoading, setIsLoading] = useState<boolean>(false);\n const mountedRef = useRef(true);\n\n // Clean up on unmount\n useRef(() => {\n mountedRef.current = true;\n return () => {\n mountedRef.current = false;\n };\n });\n\n const fetch = useCallback(async (): Promise<T> => {\n if (cache.has(key)) {\n const cachedData = cache.get(key) as T;\n setData(cachedData);\n return cachedData;\n }\n\n setIsLoading(true);\n setError(undefined);\n\n try {\n // If we have an in-flight request and dedupe is enabled, use that\n if (dedupe && inflight.has(key)) {\n return (await inflight.get(key)) as Promise<T>;\n }\n\n // Otherwise, create a new request\n const promise = fetcher();\n\n // Track it if deduplication is enabled\n if (dedupe) {\n inflight.set(key, promise);\n }\n\n // Await the result directly\n const result = await promise;\n\n // Update cache and state\n cache.set(key, result);\n if (mountedRef.current) {\n setData(result);\n }\n\n return result as T;\n } catch (err) {\n if (\n err instanceof NetworkError ||\n (err instanceof ServerError && err.status === 403)\n ) {\n publishNetworkError();\n } else {\n publishApiError(err as ServerError);\n }\n if (mountedRef.current) {\n setError(err as E);\n }\n throw err;\n } finally {\n // Clean up\n if (dedupe) {\n inflight.delete(key);\n }\n if (mountedRef.current) {\n setIsLoading(false);\n }\n }\n }, [key, dedupe, fetcher, publishApiError, publishNetworkError]);\n\n return { data, error, isLoading, fetch };\n}\n","import { useState } from \"react\";\nimport { usePersistence, type ChatData } from \"./persistence.hook\";\n\ntype UserIdentityOptions = { appId: string; initialUserId?: string };\n\ntype UserIdentityReturn = {\n userId: string;\n deviceId: string;\n isReady: boolean;\n externalId?: string | null;\n};\n\ntype ResolvedIdentity = {\n userId: string;\n deviceId: string;\n externalId?: string | null;\n};\n\nfunction resolveUserIdentity(\n savedData: ChatData,\n initialUserId?: string,\n): ResolvedIdentity {\n const deviceId = savedData?.deviceId || crypto.randomUUID();\n\n if (!savedData?.userId) {\n if (initialUserId) {\n // TODO should we have an internal userId and a different externalId?\n return { userId: initialUserId, externalId: initialUserId, deviceId };\n }\n return { userId: crypto.randomUUID(), externalId: null, deviceId };\n }\n if (savedData.externalId !== initialUserId) {\n // If the externalId is the same as the initialUserId, we can use the saved userId\n return { userId: savedData.userId, externalId: initialUserId, deviceId };\n }\n return {\n userId: savedData.userId,\n externalId: savedData.externalId,\n deviceId,\n };\n}\n\n/**\n * Hook that manage to generate the userId and deviceId, this should be the source of truth when dealing with user identity\n * @returns\n */\nexport function useUserIdentity(\n options: UserIdentityOptions,\n): UserIdentityReturn {\n const { appId, initialUserId } = options;\n\n const { getSavedChatData } = usePersistence({ appId });\n\n // Resolved synchronously (localStorage reads are synchronous) so dependents\n // — the SDK boot effect — can start on the first commit instead of waiting\n // an extra render for a mount effect to fill the identity in.\n const [identity, setIdentity] = useState<ResolvedIdentity>(() =>\n resolveUserIdentity(getSavedChatData(), initialUserId),\n );\n\n // Host apps may pass `userId` late (e.g. after an async login). Re-resolve\n // during render (React's alternative to a mirror effect).\n const [prevInitialUserId, setPrevInitialUserId] = useState(initialUserId);\n if (prevInitialUserId !== initialUserId) {\n setPrevInitialUserId(initialUserId);\n setIdentity(resolveUserIdentity(getSavedChatData(), initialUserId));\n }\n\n return {\n // Identity is available synchronously; kept in the contract because\n // consumers (SDK boot) still key off it.\n isReady: true,\n userId: identity.userId,\n deviceId: identity.deviceId,\n externalId: identity.externalId,\n };\n}\n","\"use client\";\n\nimport { useEffect, useRef, useState } from \"react\";\n\nimport { Message } from \"@/type\";\n\nimport { getApiUrl } from \"@/lib/config\";\nimport {\n BootResponse,\n EloquentAiApiClient,\n} from \"@/lib/eloquent-ai-api-client\";\nimport { wrapPromise } from \"@/lib/utils\";\nimport { withRetry } from \"@/lib/retry\";\n\nimport { useFetch } from \"@/hooks/useFetch\";\n\nimport { usePersistence } from \"./persistence.hook\";\nimport { useUserIdentity } from \"./user-identity.hook\";\n\nexport interface UseSdkInitializationProps {\n environment: \"test\" | \"live\";\n apiUrl?: string;\n appId: string;\n initialUserId?: string;\n userName?: string;\n userData?: Record<string, string | number | boolean>;\n}\n\nexport interface UseSdkInitializationReturn {\n userId: string;\n userName?: string;\n userData?: Record<string, string | number | boolean>;\n externalId?: string | null;\n deviceId: string;\n apiClient: EloquentAiApiClient | null;\n chatSettings: BootResponse[\"chat_settings\"] | null;\n currentChat: { id: string } | null;\n messages: Message[];\n isReady: boolean;\n isChatClosed: boolean;\n isChatActive: boolean;\n}\n\n/**\n * Hook to handle SDK initialization for the EloquentAI Chat SDK\n * Handles API client initialization, saved conversation restoration, and SDK boot\n */\nexport function useSdkInitialization({\n apiUrl: apiUrlOverride,\n appId,\n initialUserId,\n userName,\n userData,\n}: UseSdkInitializationProps): UseSdkInitializationReturn {\n // Get a pair of userId and deviceId\n const {\n userId,\n externalId,\n deviceId,\n isReady: isUserIdentityReady,\n } = useUserIdentity({ appId, initialUserId });\n\n const { isChatExpired, clearChatData, getSavedChatData } = usePersistence({\n appId,\n });\n\n const { current: apiUrl } = useRef(apiUrlOverride || getApiUrl());\n const [apiClient] = useState<EloquentAiApiClient>(\n new EloquentAiApiClient({\n baseURL: apiUrl,\n appId: appId,\n }),\n );\n const [chatSettings, setChatSettings] = useState<\n BootResponse[\"chat_settings\"] | null\n >(null);\n const [currentChat, setCurrentChat] = useState<{\n id: string;\n } | null>(null);\n const [messages, setMessages] = useState<Message[]>([]);\n const [isReady, setIsReady] = useState(false);\n const [isChatClosed, setIsChatClosed] = useState(false);\n const [isChatActive, setIsChatActive] = useState(true);\n\n // Use a unique key to differentiate between Chat SDK instances with different appIds\n const sdkBoot = useFetch(`sdk-boot-${appId}`, () => apiClient.boot());\n const sdkBootFetch = sdkBoot.fetch;\n\n // Initialize API client on the client side only\n useEffect(() => {\n // Check if there's an existing conversation and if it's not expired\n if (!isChatExpired()) {\n const {\n conversationId: chatId,\n userId,\n messages: savedMessages,\n isChatClosed: savedIsChatClosed,\n chatToken: savedChatToken,\n } = getSavedChatData();\n\n if (chatId && userId) {\n setCurrentChat({\n id: chatId,\n });\n apiClient.setChatToken(savedChatToken ?? null);\n\n // If we have saved messages, use them\n if (savedMessages && savedMessages.length > 0) {\n setMessages(savedMessages);\n }\n\n if (savedIsChatClosed) {\n setIsChatClosed(true);\n }\n }\n } else {\n // Clear expired conversation data\n clearChatData();\n // The next API call will automatically generate a new device ID\n }\n }, [getSavedChatData, isChatExpired, clearChatData, apiClient]);\n\n // Boot the SDK exactly once, when the user identity becomes available. The\n // ref guard (rather than deps alone) keeps re-renders from re-firing the\n // org + boot requests: sdkBootFetch gets a new identity every render, so\n // without the guard the effect would re-run constantly.\n const hasBootedRef = useRef(false);\n useEffect(() => {\n if (!isUserIdentityReady || hasBootedRef.current) return;\n hasBootedRef.current = true;\n\n const bootSDK = async () => {\n // Step 1: Fetch organization data to get region\n const [orgResponse, orgError] = await wrapPromise(\n withRetry(() => apiClient.getOrganizationByAppId(appId)),\n );\n\n if (orgError) {\n console.error(\"Failed to fetch organization data:\", orgError);\n setIsChatActive(false);\n setIsReady(true);\n return;\n }\n\n // Step 2: Store region for subsequent API calls\n apiClient.setRegion(orgResponse.region);\n\n // Step 3: Now call boot endpoint\n const [response, error] = await wrapPromise(withRetry(sdkBootFetch));\n\n if (error) {\n setIsChatActive(false);\n setIsReady(true);\n return;\n }\n\n const welcomeMessage = response.chat_settings.welcome_message;\n\n setChatSettings(response.chat_settings);\n setIsChatActive(response.chat_settings.is_active ?? true);\n\n // Only set welcome message if we don't already have one (functional update to avoid race conditions)\n if (welcomeMessage) {\n setMessages((prev) => {\n if (prev.length > 0 || prev.some((m) => m.isWelcomeMessage))\n return prev;\n return [\n {\n id: crypto.randomUUID(),\n content: welcomeMessage,\n sender: \"assistant\" as const,\n timestamp: new Date().toISOString(),\n isWelcomeMessage: true,\n },\n ];\n });\n }\n\n setIsReady(true);\n };\n\n bootSDK();\n }, [isUserIdentityReady, apiClient, appId, sdkBootFetch]);\n\n return {\n userId,\n userName,\n userData,\n externalId,\n deviceId,\n apiClient,\n chatSettings,\n currentChat,\n messages,\n isReady,\n isChatClosed,\n isChatActive,\n };\n}\n","\"use client\";\n\nimport { useEffect, useState } from \"react\";\n\n// Matches Tailwind's `sm` breakpoint; kept in sync with the mobile-only CSS rules.\nconst MOBILE_MEDIA_QUERY = \"(max-width: 640px)\";\n\n// matchMedia (not window.innerWidth) so the check reflects the actual visual\n// viewport used for layout on mobile browsers (browser chrome, pinch-zoom,\n// display-zoom accessibility settings), and computed lazily so the very first\n// render already reflects the real device instead of defaulting to desktop.\nfunction getIsMobileScreen(): boolean {\n if (typeof window === \"undefined\") return false;\n return window.matchMedia(MOBILE_MEDIA_QUERY).matches;\n}\n\n/**\n * Hook to handle UI initialization for the chat component\n * Handles mobile detection and portal container creation\n */\nexport function useUiInitialization(propIsMobile?: boolean): {\n isMobileScreen: boolean;\n isMobile: boolean;\n portalContainer: HTMLElement | null;\n} {\n const [isMobileScreen, setIsMobileScreen] = useState(getIsMobileScreen);\n const [portalContainer, setPortalContainer] = useState<HTMLElement | null>(\n null,\n );\n\n // Determine if mobile based on prop or screen size\n const isMobile = propIsMobile ?? isMobileScreen;\n\n const isSSR = typeof window === \"undefined\";\n\n // Check if the screen is mobile, and keep it in sync as the viewport changes\n useEffect(() => {\n if (isSSR) return;\n\n const mediaQueryList = window.matchMedia(MOBILE_MEDIA_QUERY);\n const handleChange = (event: MediaQueryList | MediaQueryListEvent) => {\n setIsMobileScreen(event.matches);\n };\n\n handleChange(mediaQueryList);\n mediaQueryList.addEventListener(\"change\", handleChange);\n return () => mediaQueryList.removeEventListener(\"change\", handleChange);\n }, [isSSR]);\n\n // Create a container for the chat interface\n useEffect(() => {\n if (isSSR) return;\n\n const container = document.createElement(\"div\");\n container.className = \"eloquent-ai-chat-portal\";\n container.style.position = \"relative\";\n container.style.zIndex = \"30\";\n document.body.appendChild(container);\n setPortalContainer(container);\n\n return () => {\n if (container.parentElement) {\n container.parentElement.removeChild(container);\n }\n };\n }, [isSSR]);\n\n return {\n isMobileScreen,\n isMobile,\n portalContainer,\n };\n}\n","\"use client\";\n\nimport { useDebounce } from \"@/hooks/use-debounce\";\nimport { useCallback, useEffect, useRef, useState } from \"react\";\n\nimport { Message, MessageData } from \"@/type\";\n\nimport { ThemeContextType } from \"@/contexts/theme.context\";\n\nimport { ChatInterfaceProps } from \"@/components/chat-interface\";\n\nimport { deleteCookie, getCookie, setCookie } from \"@/lib/utils\";\n\nimport { useInterfaceProps } from \"./interface-props.hook\";\nimport { useMessageEvents } from \"./message-events.hook\";\nimport { useSdkInitialization } from \"./sdk-initialization.hook\";\nimport { useUiInitialization } from \"./ui-initialization.hook\";\n\n// How long we remember that the user closed the chat widget\nconst CHAT_CLOSED_COOKIE_TTL_HOURS = 2;\nconst getChatClosedCookieName = (appId: string) =>\n `eloquent-ai:chat-widget-closed-${appId}`;\n\nexport interface UseChatProps {\n appId: string;\n userId?: string;\n userName?: string;\n userData?: Record<string, string | number | boolean>;\n theme?: Partial<ThemeContextType>;\n chatProps?: Partial<ChatInterfaceProps>;\n isMobile?: boolean;\n /** Show the close (X) button in the chat header. */\n hasCloseButton?: boolean;\n /** Show the clear-conversation button in the chat header. */\n hasCleanChatButton?: boolean;\n /** Open the chat window on load (desktop only). */\n isInitiallyOpen?: boolean;\n /** @deprecated Use `hasCloseButton` instead. Ignored when `hasCloseButton` is set. */\n closeButton?: boolean;\n /** @deprecated Use `hasCleanChatButton` instead. Ignored when `hasCleanChatButton` is set. */\n cleanChatButton?: boolean;\n /** @deprecated Use `isInitiallyOpen` instead. Ignored when `isInitiallyOpen` is set. */\n initialOpen?: boolean;\n proactiveMessageHideDelay?: number;\n}\n\nexport interface UseChatReturn {\n isReady: boolean;\n isChatActive: boolean;\n /** Effective initial-open (boot chat_settings.initial_open ?? prop). */\n isInitiallyOpen: boolean;\n /** Effective close-button visibility (boot chat_settings.close_button ?? prop). */\n hasCloseButton: boolean;\n /** Effective clear-chat-button visibility (boot chat_settings.clean_chat_button ?? prop). */\n hasCleanChatButton: boolean;\n isMobile: boolean;\n chatInterfaceProps: Partial<ChatInterfaceProps>;\n chatOpen: boolean;\n chatOpenDebounced: boolean;\n messages: Message[];\n portalContainer: HTMLElement | null;\n onSendMessage: (message: MessageData) => Promise<void>;\n setChatOpen: (value: boolean | ((prev: boolean) => boolean)) => void;\n onCleanMessages: () => void;\n proactiveMessage?: {\n text: string;\n isVisible: boolean;\n autoHideDelay: number;\n };\n hideProactiveMessage: () => void;\n isChatClosed: boolean;\n onStartNewChat: () => void;\n onRateChat: (rating: number) => Promise<void>;\n}\n\n/**\n * The primary chat hook, responsible for managing the chat state and operations.\n * @param options The hook parameters\n * @returns The chat hook return type\n */\nexport function useChat({\n environment,\n apiUrl,\n appId,\n userId: initialUserId,\n userName,\n userData,\n chatProps,\n isMobile: propIsMobile,\n isInitiallyOpen: propIsInitiallyOpen,\n hasCloseButton: propHasCloseButton,\n hasCleanChatButton: propHasCleanChatButton,\n // Deprecated aliases, kept until hosts migrate to the is/has names above.\n initialOpen: deprecatedInitialOpen,\n closeButton: deprecatedCloseButton,\n cleanChatButton: deprecatedCleanChatButton,\n proactiveMessageHideDelay: propProactiveMessageHideDelay = 5000,\n isAlwaysOpen = false,\n hasCleanChatButtonOverride,\n}: Readonly<\n Partial<UseChatProps> & {\n environment: \"test\" | \"live\";\n apiUrl?: string;\n appId: string;\n /**\n * Internal-only kill-switch (INTERNAL_ONLY_SHOW_CLEAN_CHAT_BUTTON): when\n * set, wins over both the boot `chat_settings.clean_chat_button` and the\n * `hasCleanChatButton` prop. Leave undefined for the normal boot ?? prop\n * resolution.\n */\n hasCleanChatButtonOverride?: boolean;\n /**\n * Embedded mode (INTERNAL_ONLY_CHAT_INTERFACE_ONLY): the interface is the\n * page content and there is no launcher bubble to reopen a closed chat, so\n * open/close state does not apply — not the isInitiallyOpen prop, not the\n * boot `chat_settings.initial_open`, and not the closed-cookie. Without\n * this, a boot `initial_open: false` closes the widget from under the\n * host page a moment after it renders.\n */\n isAlwaysOpen?: boolean;\n }\n>): UseChatReturn {\n // Use UI initialization hook for mobile detection and portal container\n const { isMobile, portalContainer } = useUiInitialization(propIsMobile);\n\n // Use SDK initialization hook for API client, chat settings and conversation state\n const {\n userId,\n externalId,\n deviceId,\n apiClient,\n chatSettings,\n currentChat: initialChat,\n messages: initialMessages,\n isReady,\n isChatClosed: initialIsChatClosed,\n isChatActive,\n } = useSdkInitialization({\n environment,\n apiUrl,\n appId,\n initialUserId,\n userName,\n userData,\n });\n\n // Generate chat interface props\n const chatInterfaceProps = useInterfaceProps({ chatProps, chatSettings });\n\n // The is/has names are canonical; the deprecated aliases only apply when\n // the new name is absent.\n const propInitialOpen = propIsInitiallyOpen ?? deprecatedInitialOpen ?? false;\n const propCloseButton = propHasCloseButton ?? deprecatedCloseButton ?? true;\n const propCleanChatButton =\n propHasCleanChatButton ?? deprecatedCleanChatButton ?? true;\n\n const chatClosedCookieName = getChatClosedCookieName(appId);\n\n const [chatOpen, setChatOpenState] = useState(() => {\n if (isAlwaysOpen) return true;\n if (getCookie(chatClosedCookieName) === \"true\") return false;\n return isMobile ? false : (propInitialOpen ?? isMobile);\n });\n\n // The server can also drive the initial open (chat_settings.initial_open).\n // The boot value wins over the prop, but NOT over the user's 2-hour\n // closed-cookie: if the user explicitly closed the widget, a boot `true`\n // must not reopen it on the next page. A boot `false` still applies (the\n // server force-closing never fights the user). Boot resolves after mount,\n // so apply it once when settings arrive. The mobile guard also remains (a\n // full-screen overlay opening uninvited on mobile is too disruptive). Uses\n // the raw setter so a server-driven open/close never writes the closed\n // cookie itself.\n const [hasAppliedBootInitialOpen, setHasAppliedBootInitialOpen] =\n useState(false);\n useEffect(() => {\n if (!isReady || hasAppliedBootInitialOpen) return;\n setHasAppliedBootInitialOpen(true);\n\n if (isAlwaysOpen) return;\n const bootInitialOpen = chatSettings?.initial_open;\n if (bootInitialOpen == null) return;\n if (isMobile) return;\n if (bootInitialOpen && getCookie(chatClosedCookieName) === \"true\") return;\n setChatOpenState(bootInitialOpen);\n }, [\n isReady,\n hasAppliedBootInitialOpen,\n chatSettings?.initial_open,\n isMobile,\n chatClosedCookieName,\n isAlwaysOpen,\n ]);\n\n // Effective value (boot ?? prop) — e.g. the proactive message is\n // suppressed when the chat starts open.\n const isInitiallyOpen = chatSettings?.initial_open ?? propInitialOpen;\n\n // Same server-wins pattern for the header buttons and the proactive\n // message delay: an explicit boot value (including false) beats the prop.\n const hasCloseButton = chatSettings?.close_button ?? propCloseButton;\n // The internal-only override (when set) beats both boot and prop.\n const hasCleanChatButton =\n hasCleanChatButtonOverride ??\n chatSettings?.clean_chat_button ??\n propCleanChatButton;\n const proactiveMessageHideDelay =\n chatSettings?.proactive_message_hide_delay ?? propProactiveMessageHideDelay;\n\n // Wrap the setter so that closing the chat widget is remembered for 2\n // hours, and reopening it clears that memory. In always-open (embedded)\n // mode the widget cannot close at all, and must not write the closed-cookie\n // — it would leak into the real launcher widget for the same appId.\n const setChatOpen = useCallback<\n (value: boolean | ((prev: boolean) => boolean)) => void\n >(\n (value) => {\n if (isAlwaysOpen) return;\n setChatOpenState((prev) => {\n const next = typeof value === \"function\" ? value(prev) : value;\n if (next) {\n deleteCookie(chatClosedCookieName);\n } else {\n setCookie(chatClosedCookieName, \"true\", CHAT_CLOSED_COOKIE_TTL_HOURS);\n }\n return next;\n });\n },\n [chatClosedCookieName, isAlwaysOpen],\n );\n\n const chatOpenDebounced = useDebounce(chatOpen, 400);\n const [messages, setMessages] = useState<Message[]>(\n chatProps?.messages ?? [],\n );\n const [currentChat, setCurrentChat] = useState<{\n id: string;\n } | null>(initialChat);\n\n const [isChatClosed, setIsChatClosed] = useState(false);\n\n // Adopt values arriving asynchronously from SDK initialization (localStorage\n // restore, boot welcome message) into the locally-owned state. setState\n // during render instead of mirror effects: React restarts the render\n // immediately, so consumers never see the stale value for a frame.\n const [prevInitialMessages, setPrevInitialMessages] =\n useState(initialMessages);\n if (prevInitialMessages !== initialMessages) {\n setPrevInitialMessages(initialMessages);\n if (initialMessages.length > 0) setMessages(initialMessages);\n }\n\n const [prevInitialChat, setPrevInitialChat] = useState(initialChat);\n if (prevInitialChat !== initialChat) {\n setPrevInitialChat(initialChat);\n if (initialChat) setCurrentChat(initialChat);\n }\n\n // Restore the \"chat closed\" state saved to localStorage, so it survives a\n // page refresh.\n const [prevInitialIsChatClosed, setPrevInitialIsChatClosed] =\n useState(initialIsChatClosed);\n if (prevInitialIsChatClosed !== initialIsChatClosed) {\n setPrevInitialIsChatClosed(initialIsChatClosed);\n if (initialIsChatClosed) setIsChatClosed(true);\n }\n\n const handleChatClosed = useCallback(() => {\n setIsChatClosed(true);\n }, []);\n\n // The proactive (welcome) bubble is fully derived from boot settings; the\n // only real state is whether the user dismissed it.\n const [hasDismissedProactiveMessage, setHasDismissedProactiveMessage] =\n useState(false);\n const proactiveMessageText =\n isReady &&\n chatSettings?.auto_display_welcome_message &&\n chatSettings?.welcome_message\n ? chatSettings.welcome_message\n : \"\";\n const proactiveMessage = {\n text: proactiveMessageText,\n isVisible: proactiveMessageText !== \"\" && !hasDismissedProactiveMessage,\n autoHideDelay: proactiveMessageHideDelay,\n };\n\n // Use message events hook for sending and cleaning messages\n const { onSendMessage, onCleanMessages, onRateChat } = useMessageEvents({\n appId,\n userId,\n userName,\n userData,\n externalId,\n deviceId,\n apiClient,\n chatSettings,\n setMessages,\n messages,\n currentChat,\n setCurrentChat,\n onChatClosed: handleChatClosed,\n isChatClosed,\n });\n\n // Sync with initialMessages when they change (from SDK initialization)\n useEffect(() => {\n if (initialMessages.length > 0) {\n setMessages(initialMessages);\n }\n }, [initialMessages]);\n\n useEffect(() => {\n if (initialChat) {\n setCurrentChat(initialChat);\n }\n }, [initialChat]);\n\n // Identify the user once per distinct payload. Host apps often recreate the\n // `userData` object every render, so comparing by value (not identity)\n // prevents a duplicate network call per re-render.\n const lastIdentifyKeyRef = useRef<string | null>(null);\n useEffect(() => {\n if (!currentChat || !externalId || !apiClient) return;\n\n const identifyPayload = {\n userId,\n userName,\n userData,\n externalId,\n deviceId,\n conversationId: currentChat.id,\n };\n const identifyKey = JSON.stringify(identifyPayload);\n if (lastIdentifyKeyRef.current === identifyKey) return;\n lastIdentifyKeyRef.current = identifyKey;\n\n apiClient.identifyUser(identifyPayload);\n }, [\n externalId,\n userId,\n userName,\n userData,\n deviceId,\n currentChat,\n apiClient,\n ]);\n\n const onStartNewChat = useCallback(() => {\n onCleanMessages();\n setIsChatClosed(false);\n }, [onCleanMessages]);\n\n const hideProactiveMessage = useCallback(() => {\n setHasDismissedProactiveMessage(true);\n }, []);\n\n return {\n isReady,\n isChatActive,\n isInitiallyOpen,\n hasCloseButton,\n hasCleanChatButton,\n isMobile,\n chatInterfaceProps,\n chatOpen,\n chatOpenDebounced,\n messages,\n portalContainer,\n onSendMessage,\n setChatOpen,\n onCleanMessages,\n proactiveMessage,\n hideProactiveMessage,\n isChatClosed,\n onStartNewChat,\n onRateChat,\n };\n}\n","\"use client\";\n\nimport { useEffect, useState } from \"react\";\n\n/**\n * Tracks how much the on-screen keyboard overlaps the layout viewport, using\n * the VisualViewport API. Used to lift the chat input above the keyboard\n * without moving/resizing the rest of the chat window.\n */\nexport function useKeyboardInset(enabled: boolean): number {\n const [inset, setInset] = useState(0);\n\n useEffect(() => {\n const viewport = window.visualViewport;\n if (!enabled || !viewport) {\n setInset(0);\n return;\n }\n\n const update = () => {\n const overlap = window.innerHeight - viewport.height - viewport.offsetTop;\n setInset(Math.max(0, Math.round(overlap)));\n };\n\n update();\n viewport.addEventListener(\"resize\", update);\n viewport.addEventListener(\"scroll\", update);\n\n return () => {\n viewport.removeEventListener(\"resize\", update);\n viewport.removeEventListener(\"scroll\", update);\n setInset(0);\n };\n }, [enabled]);\n\n return inset;\n}\n","\"use client\";\n\nimport { useEffect } from \"react\";\n\n/**\n * Locks scrolling on the host page while active. Uses the fixed-body trick\n * (rather than plain `overflow: hidden`) so it also holds on iOS Safari,\n * which otherwise still allows background scroll/bounce behind the chat.\n */\nexport function useScrollLock(locked: boolean) {\n useEffect(() => {\n if (!locked) return;\n\n const { body } = document;\n const scrollY = window.scrollY;\n const previousStyle = {\n position: body.style.position,\n top: body.style.top,\n left: body.style.left,\n right: body.style.right,\n overflow: body.style.overflow,\n };\n\n body.style.position = \"fixed\";\n body.style.top = `-${scrollY}px`;\n body.style.left = \"0\";\n body.style.right = \"0\";\n body.style.overflow = \"hidden\";\n\n return () => {\n body.style.position = previousStyle.position;\n body.style.top = previousStyle.top;\n body.style.left = previousStyle.left;\n body.style.right = previousStyle.right;\n body.style.overflow = previousStyle.overflow;\n window.scrollTo(0, scrollY);\n };\n }, [locked]);\n}\n","import { useCallback, useRef, useState } from \"react\";\n\nexport interface UseAgentCognitionReturn {\n isVisible: boolean;\n content: string | null;\n showCognition: (content?: string) => void;\n hideCognition: () => void;\n}\n\nexport function useAgentCognition(): UseAgentCognitionReturn {\n const [isVisible, setIsVisible] = useState(false);\n const [content, setContent] = useState<string | null>(null);\n const timerRef = useRef<NodeJS.Timeout | null>(null);\n const pendingContentRef = useRef<string | null>(null);\n\n const showCognition = useCallback((newContent = \"...\") => {\n const updateCognition = () => {\n setContent(newContent);\n setIsVisible(true);\n pendingContentRef.current = null;\n\n // Clear existing timer\n if (timerRef.current) {\n clearTimeout(timerRef.current);\n }\n\n // Set timer to allow updates after 1 second minimum display time\n timerRef.current = setTimeout(() => {\n timerRef.current = null;\n\n // If there's pending content, show it immediately\n if (pendingContentRef.current) {\n updateCognition();\n }\n }, 1000);\n };\n\n // If no timer is active, update immediately\n if (!timerRef.current) {\n updateCognition();\n } else {\n // Timer is active, queue the new content\n pendingContentRef.current = newContent;\n }\n }, []);\n\n const hideCognition = useCallback(() => {\n // Clear timer and pending content\n if (timerRef.current) {\n clearTimeout(timerRef.current);\n timerRef.current = null;\n }\n pendingContentRef.current = null;\n\n // Hide cognition\n setIsVisible(false);\n setContent(null);\n }, []);\n\n return {\n isVisible,\n content,\n showCognition,\n hideCognition,\n };\n}\n","import { ReactNode } from \"react\";\nimport { useAgentCognition } from \"@/hooks/use-agent-cognition\";\nimport { AgentCognitionContext } from \"./agent-cognition-context-definition\";\n\ninterface AgentCognitionProviderProps {\n children: ReactNode;\n}\n\nexport function AgentCognitionProvider({\n children,\n}: AgentCognitionProviderProps) {\n const cognition = useAgentCognition();\n\n return (\n <AgentCognitionContext.Provider value={cognition}>\n {children}\n </AgentCognitionContext.Provider>\n );\n}\n","import { useState, type ReactNode } from \"react\";\nimport {\n ErrorContext,\n SdkError,\n createPublishApiError,\n} from \"./error-handling.utils\";\n\nexport const ErrorProvider = ({ children }: { children: ReactNode }) => {\n const [error, setError] = useState<SdkError | null>(null);\n const [hideSdk, setHideSdk] = useState(false);\n\n const publishApiError = createPublishApiError(setError);\n const publishError = (error: SdkError) => setError(error);\n const publishNetworkError = () => setHideSdk(true);\n const clearError = () => setError(null);\n\n const contextValue = {\n error,\n hideSdk,\n publishApiError,\n publishError,\n publishNetworkError,\n clearError,\n };\n\n return (\n <ErrorContext.Provider value={contextValue}>\n {children}\n </ErrorContext.Provider>\n );\n};\n","\"use client\";\n\nimport { type CSSProperties } from \"react\";\n\nimport mainCSS from \"@/index.css?inline\";\nimport wrapperCSS from \"@/wrapper.css?inline\";\n\nimport { Message } from \"@/type\";\n\nimport { cn } from \"@/lib/utils\";\n\nimport { ChatBubble } from \"@/components/chat-bubble\";\nimport { ChatInterface } from \"@/components/chat-interface\";\nimport { SkeletonChatInterface } from \"@/components/chat-interface/skeleton\";\nimport { Iframe } from \"@/components/iframe\";\nimport { Portal } from \"@/components/portal\";\nimport { ProactiveMessage } from \"@/components/chat/proactive-message\";\n\nimport { useChat, type UseChatProps } from \"@/components/chat/chat.hook\";\nimport { useKeyboardInset } from \"@/components/chat/keyboard-inset.hook\";\nimport { useScrollLock } from \"@/components/chat/scroll-lock.hook\";\nimport { AgentCognitionProvider } from \"@/contexts/agent-cognition.context\";\nimport { ErrorProvider } from \"@/contexts/error-handling.context\";\nimport { useErrorContext } from \"@/contexts/error-handling.utils\";\nimport { ThemeProvider } from \"@/contexts/theme.context\";\n\n/** Viewport inset (px) used to cap desktop chat height so it doesn’t overflow. */\nconst CHAT_DESKTOP_VIEWPORT_INSET_PX = 100;\n\n/** @internal */\ntype InternalChatProps = {\n INTERNAL_ONLY_CHAT_INTERFACE_ONLY?: boolean;\n INTERNAL_ONLY_BLOCK_STYLE?: boolean;\n /**\n * Force the clear-chat button on or off, winning over both the boot\n * `chat_settings.clean_chat_button` and the public `hasCleanChatButton`\n * prop. Leave unset to keep the normal boot ?? prop resolution.\n */\n INTERNAL_ONLY_SHOW_CLEAN_CHAT_BUTTON?: boolean;\n /** Show the copy-message button on assistant messages (default false). */\n INTERNAL_ONLY_SHOW_COPY_BUTTON?: boolean;\n INTERNAL_ONLY_ENVIRONMENT?: \"test\" | \"live\";\n INTERNAL_ONLY_API_URL?: string;\n INTERNAL_ONLY_FEATURE_MESSAGE_CLICK?: (message: Message) => void;\n INTERNAL_ONLY_FEATURE_CLEAR_CHAT_CLICK?: () => void;\n};\n\nexport type ChatProps = UseChatProps & InternalChatProps;\n\nfunction InternalChat({\n appId,\n userId,\n userName,\n userData,\n chatProps,\n proactiveMessageHideDelay = 5000,\n isMobile: propIsMobile,\n hasCloseButton: propHasCloseButton,\n hasCleanChatButton: propHasCleanChatButton,\n isInitiallyOpen: propIsInitiallyOpen,\n // Deprecated aliases, resolved in useChat (new name wins).\n closeButton: deprecatedCloseButton,\n cleanChatButton: deprecatedCleanChatButton,\n initialOpen: deprecatedInitialOpen,\n INTERNAL_ONLY_CHAT_INTERFACE_ONLY = false,\n INTERNAL_ONLY_SHOW_CLEAN_CHAT_BUTTON = undefined,\n INTERNAL_ONLY_BLOCK_STYLE = false,\n INTERNAL_ONLY_FEATURE_MESSAGE_CLICK = undefined,\n INTERNAL_ONLY_FEATURE_CLEAR_CHAT_CLICK = undefined,\n INTERNAL_ONLY_SHOW_COPY_BUTTON = false,\n INTERNAL_ONLY_ENVIRONMENT = \"live\",\n INTERNAL_ONLY_API_URL,\n}: Readonly<UseChatProps & InternalChatProps>) {\n const { hideSdk } = useErrorContext();\n\n const {\n isReady,\n isChatActive,\n isInitiallyOpen,\n hasCloseButton,\n hasCleanChatButton,\n isMobile,\n chatOpen,\n chatInterfaceProps,\n chatOpenDebounced,\n messages,\n portalContainer,\n onSendMessage,\n setChatOpen,\n proactiveMessage,\n hideProactiveMessage,\n isChatClosed,\n onStartNewChat,\n onRateChat,\n } = useChat({\n environment: INTERNAL_ONLY_ENVIRONMENT,\n apiUrl: INTERNAL_ONLY_API_URL,\n appId,\n userId,\n userName,\n userData,\n chatProps,\n isMobile: propIsMobile,\n isInitiallyOpen: propIsInitiallyOpen,\n hasCloseButton: propHasCloseButton,\n hasCleanChatButton: propHasCleanChatButton,\n initialOpen: deprecatedInitialOpen,\n closeButton: deprecatedCloseButton,\n cleanChatButton: deprecatedCleanChatButton,\n proactiveMessageHideDelay,\n // Embedded: the interface is the page content with no launcher to reopen\n // it, so nothing (boot initial_open, closed-cookie, props) may close it.\n isAlwaysOpen: INTERNAL_ONLY_CHAT_INTERFACE_ONLY,\n hasCleanChatButtonOverride: INTERNAL_ONLY_SHOW_CLEAN_CHAT_BUTTON,\n });\n\n const keyboardInset = useKeyboardInset(isMobile && chatOpen);\n useScrollLock(isMobile && chatOpen);\n\n const isBooting = !isReady;\n\n if (hideSdk) return null;\n // The launcher widget renders nothing until boot decides what to show. In\n // embedded mode the widget IS the page content: rendering null while a\n // remount boots (project/environment switch in the host app) collapses the\n // layout and flashes an empty hole — show the skeleton in place instead.\n if (isBooting && !INTERNAL_ONLY_CHAT_INTERFACE_ONLY) return null;\n if (!isBooting && !isChatActive) return null;\n\n const renderContent = () => {\n return (\n <div\n style={{\n WebkitTouchCallout: \"none\" /* iOS Safari */,\n WebkitUserSelect: \"none\" /* Safari */,\n KhtmlUserSelect: \"none\" /* Konqueror HTML */,\n MozUserSelect: \"none\" /* Old versions of Firefox */,\n msUserSelect: \"none\" /* Internet Explorer/Edge */,\n userSelect: \"none\" /* Chrome, Edge, Opera and Firefox */,\n position: \"fixed\",\n right: 12,\n bottom: 4,\n ...(INTERNAL_ONLY_BLOCK_STYLE\n ? { position: \"relative\", inset: 0, width: \"100%\", height: \"100%\" }\n : {}),\n }}\n >\n <style>{wrapperCSS}</style>\n <Iframe\n className=\"eloquentai-chat-messaging\"\n head={\n <>\n <link rel=\"preconnect\" href=\"https://fonts.googleapis.com\" />\n <link rel=\"preconnect\" href=\"https://fonts.gstatic.com\" />\n <link\n href=\"https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&display=swap\"\n rel=\"stylesheet\"\n />\n <style>{mainCSS}</style>\n </>\n }\n style={\n {\n display: chatOpen\n ? \"block\"\n : chatOpenDebounced\n ? \"block\"\n : \"none\",\n width: isMobile ? \"100vw\" : \"400px\",\n // 100dvh accounts for mobile browser chrome (e.g. address bar); 100vh fallback for older browsers\n \"--chat-mobile-viewport-height\": \"100dvh\",\n height: isMobile\n ? \"var(--chat-mobile-viewport-height, 100vh)\"\n : \"700px\",\n maxHeight: isMobile\n ? \"var(--chat-mobile-viewport-height, 100vh)\"\n : `calc(100% - ${CHAT_DESKTOP_VIEWPORT_INSET_PX}px)`,\n border: \"none\",\n zIndex: 2147483000,\n position: \"fixed\",\n top: isMobile ? 0 : undefined,\n left: isMobile ? 0 : undefined,\n right: isMobile ? 0 : 16,\n bottom: isMobile ? 0 : 16,\n ...(INTERNAL_ONLY_BLOCK_STYLE\n ? {\n position: \"relative\",\n top: 0,\n left: 0,\n right: 0,\n bottom: 0,\n width: \"100%\",\n height: \"100%\",\n maxHeight: \"100%\",\n zIndex: 0,\n }\n : {}),\n } as CSSProperties\n }\n >\n {isBooting ? (\n // Only reachable in embedded mode (the launcher returns null while\n // booting): hold the widget's frame with a skeleton so a remount —\n // project/environment switch in the host app — doesn't flash an\n // empty hole where the chat was.\n <SkeletonChatInterface isOpen isMobile={isMobile} skipAnimation />\n ) : (\n <ChatInterface\n {...chatInterfaceProps}\n // Embedded (interface-only) mode renders as page content: no\n // popup-style panel entrance.\n hasIntroAnimation={!INTERNAL_ONLY_CHAT_INTERFACE_ONLY}\n // Caution stripe: a session against the test agent must never be\n // mistaken for the production one.\n isTestMode={INTERNAL_ONLY_ENVIRONMENT === \"test\"}\n isOpen={chatOpen}\n keyboardInset={keyboardInset}\n messages={messages}\n onSendMessage={onSendMessage}\n onMessageClick={INTERNAL_ONLY_FEATURE_MESSAGE_CLICK}\n isMobile={isMobile}\n hasCloseButton={hasCloseButton}\n hasCleanChatButton={hasCleanChatButton}\n hasCopyButton={INTERNAL_ONLY_SHOW_COPY_BUTTON}\n isChatClosed={isChatClosed}\n onStartNewChat={onStartNewChat}\n onRateChat={onRateChat}\n onClose={() => setChatOpen(false)}\n onCleanChat={() => {\n onStartNewChat();\n INTERNAL_ONLY_FEATURE_CLEAR_CHAT_CLICK?.();\n }}\n />\n )}\n </Iframe>\n {!INTERNAL_ONLY_CHAT_INTERFACE_ONLY && (\n <Iframe\n className=\"eloquentai-chat-launcher\"\n head={<style>{mainCSS}</style>}\n style={{\n position: \"fixed\",\n bottom: 17,\n right: 17,\n display: \"block\",\n width: 48,\n height: 48,\n border: \"none\",\n zIndex: isMobile ? 2147482999 : 2147483000,\n opacity: chatOpen ? 0 : 1,\n pointerEvents: chatOpen ? \"none\" : \"auto\",\n transition: chatOpen\n ? \"opacity 100ms ease-in\"\n : \"opacity 200ms ease-out 320ms\",\n }}\n >\n <ChatBubble\n isOpen={chatOpen}\n toggleBubble={() => setChatOpen((prev) => !prev)}\n isDarkMode={chatInterfaceProps?.theme?.mode === \"dark\"}\n />\n </Iframe>\n )}\n {chatInterfaceProps?.displayWelcomeMessages ? (\n <Iframe\n className=\"eloquentai-chat-proactive-message\"\n head={<style>{mainCSS}</style>}\n style={{\n position: \"fixed\",\n // Aligns the bubble's tail with the launcher's center: the\n // launcher circle is 48px tall at bottom:17, so its center is\n // ~41px up; the tail sits ~16px above this iframe's bottom.\n bottom: 24,\n right: 17,\n }}\n >\n <ThemeProvider {...(chatInterfaceProps?.theme ?? {})}>\n {/* This iframe is outside the chat interface's dark-classed\n <main>, so dark: utilities need their own ancestor here. */}\n <div\n className={cn(\"eloq:w-full eloq:h-full\", {\n dark: chatInterfaceProps?.theme?.mode === \"dark\",\n })}\n >\n {proactiveMessage && !isInitiallyOpen && (\n <ProactiveMessage\n message={proactiveMessage.text}\n isVisible={proactiveMessage.isVisible}\n onDismiss={hideProactiveMessage}\n onMessageClick={() => {\n setChatOpen(true);\n hideProactiveMessage();\n }}\n autoHideDelay={proactiveMessage.autoHideDelay}\n />\n )}\n </div>\n </ThemeProvider>\n </Iframe>\n ) : null}\n </div>\n );\n };\n\n const renderChat = () => {\n if (INTERNAL_ONLY_BLOCK_STYLE) {\n return renderContent();\n }\n\n if (portalContainer) {\n return <Portal container={portalContainer}>{renderContent()}</Portal>;\n }\n\n return null;\n };\n\n return <>{renderChat()}</>;\n}\n\nexport function Chat(props: Readonly<ChatProps>) {\n return (\n <ErrorProvider>\n <AgentCognitionProvider>\n <InternalChat {...props} />\n </AgentCognitionProvider>\n </ErrorProvider>\n );\n}\n","import type { ComponentType } from \"react\";\nimport ReactDOMClient from \"react-dom/client\";\n\nimport { Chat, type ChatProps } from \"@/components/chat\";\n\ntype UnmountFunction = () => void;\n\nexport function renderChat(\n container: HTMLElement,\n props: ChatProps,\n): UnmountFunction {\n const render = (\n Component: ComponentType<ChatProps>,\n container: HTMLElement,\n props: ChatProps,\n ) => {\n const root = ReactDOMClient.createRoot(container);\n root.render(<Component {...props} />);\n return root.unmount;\n };\n return render(Chat, container, props);\n}\n"],"names":["environment","init","event","sensitiveHeaders","headers","key","ChatBubble","toggleBubble","isDarkMode","bubbleBackground","logoForeground","jsx","cn","Logo","Iframe","children","head","props","contentRef","setContentRef","useState","headNode","bodyNode","jsxs","createPortal","Portal","container","ProactiveMessage","message","isVisible","onDismiss","onMessageClick","autoHideDelay","shouldRender","setShouldRender","animationState","setAnimationState","theme","useTheme","useEffect","enterTimer","hideTimer","timer","getContrastingTextColor","e","X","useInterfaceProps","chatProps","chatSettings","useMemo","useLatestRef","value","reference","useRef","NetworkError","ServerError","status","response","CHAT_TOKEN_HEADER","CHAT_TOKEN_RENEWED_HEADER","HttpClient","config","region","token","url","options","regionHeader","chatTokenHeader","error","renewedToken","responseData","data","getCurrentUrlSearchParams","params","result","STORAGE_NAMESPACE","isClient","CHAT_EXPIRY_TIME","usePersistence","appId","STORAGE_KEY","defaultObject","getSavedChatData","useCallback","storedData","isChatExpired","saveChatData","conversationId","userId","messages","deviceId","chatToken","chatData","markChatClosed","clearChatData","stored","updateLastActivity","APPSYNC_EVENTS_SUBPROTOCOL","HANDSHAKE_TIMEOUT_MILLISECONDS","DEFAULT_CONNECTION_TIMEOUT_MILLISECONDS","KEEP_ALIVE_CHECK_INTERVAL_MILLISECONDS","WEB_SOCKET_OPEN_STATE","deriveRealtimeUrl","httpEndpoint","buildAuthorization","auth","host","encodeAuthProtocol","authorization","formatErrors","errors","connectAppSyncEvents","channel","onEvent","onDisconnect","createWebSocket","protocols","realtimeUrl","subscriptionId","resolve","reject","socket","phase","isClosedByClient","connectionTimeoutMilliseconds","lastLivenessTimestamp","handshakeTimer","keepAliveTimer","clearTimers","terminate","reason","wasEstablished","send","startHandshakeTimer","step","payload","_a","$constructor","name","initializer","inst","def","_","proto","keys","i","k","Parent","Definition","fn","$ZodAsyncError","globalConfig","newConfig","jsonStringifyReplacer","cached","getter","cleanRegex","source","start","end","EVALUATING","defineLazy","object","v","captureStackTrace","_args","isObject","escapeRegex","str","clone","cl","normalizeParams","_params","optionalKeys","shape","aborted","x","startIndex","explicitlyAborted","prefixIssues","path","issues","iss","unwrapMessage","finalizeIssue","ctx","_inst","_continue","_input","rest","util.jsonStringifyReplacer","$ZodError","$ZodRealError","_parse","_Err","schema","_ctx","core.$ZodAsyncError","util.finalizeIssue","core.config","util.captureStackTrace","parse","errors.$ZodRealError","_parseAsync","parseAsync","_safeParse","errors.$ZodError","safeParse","_safeParseAsync","safeParseAsync","string","regex","_null","version","$ZodType","core.$constructor","checks","ch","runChecks","isAborted","util.aborted","asyncResult","util.explicitlyAborted","currLen","handleCanaryResult","canary","checkResult","util.defineLazy","r","$ZodString","regexes.string","$ZodNull","regexes.null","input","handlePropertyResult","final","isOptionalIn","isOptionalOut","isPresent","util.prefixIssues","normalizeDef","okeys","util.optionalKeys","handleCatchall","proms","unrecognized","keySet","_catchall","t","$ZodObject","sh","newSh","_normalized","util.cached","propValues","field","util.isObject","catchall","el","handleUnionResults","results","nonaborted","$ZodUnion","o","option","patterns","p","util.cleanRegex","first","async","$ZodLiteral","values","util.escapeRegex","$ZodNullable","pattern","_string","Class","util.normalizeParams","ZodMiniType","core.$ZodType","parse.parse","parse.safeParse","parse.parseAsync","parse.safeParseAsync","_def","core.clone","reg","meta","ZodMiniString","core.$ZodString","core._string","ZodMiniNull","core.$ZodNull","core._null","ZodMiniObject","core.$ZodObject","ZodMiniUnion","core.$ZodUnion","union","ZodMiniLiteral","core.$ZodLiteral","literal","ZodMiniNullable","core.$ZodNullable","nullable","innerType","zodConfig","utteranceSchema","z.object","z.literal","z.string","agentCognitionSchema","chatClosedExpiredSchema","agentCapturedUrlSchema","agentTopicSchema","agentSummarySchema","chatRatingSchema","breadcrumbSchema","chatEscalatedSchema","z.null","errorSchema","utteranceApiResponseSchema","z.nullable","errorApiResponseSchema","agentCognitionApiResponseSchema","chatClosedExpiredApiResponseSchema","agentCapturedUrlApiResponseSchema","agentTopicApiResponseSchema","agentSummaryApiResponseSchema","chatRatingApiResponseSchema","breadcrumbApiResponseSchema","chatEscalatedApiResponseSchema","chatResponseApiSchema","z.union","INITIAL_RECONNECT_DELAY_MS","MAX_RECONNECT_DELAY_MS","DEFAULT_BACKUP_POLL_INTERVAL_MS","useRealtimeSocket","chatId","onMessage","onCognition","onCognitionComplete","onError","onChatClosed","onAgentCapturedUrl","onAgentTopic","onAgentSummary","onRatingRequest","onBreadcrumb","fetchHistory","getChatToken","backupPollingInterval","processedIdsRef","msg","eventChannelRef","activeChatIdRef","reconnectAttemptsRef","reconnectTimerRef","backupPollIntervalRef","shouldReconnectRef","isReconnectingRef","onMessageRef","onCognitionRef","onCognitionCompleteRef","onErrorRef","onChatClosedRef","onAgentCapturedUrlRef","onAgentTopicRef","onAgentSummaryRef","onRatingRequestRef","onBreadcrumbRef","fetchHistoryRef","getChatTokenRef","publishError","useErrorContext","appSyncUrl","appSyncApiKey","isSocketConfigReady","appSyncUrlRef","appSyncApiKeyRef","closeChannel","stopBackupPoll","clearReconnectTimer","scheduleReconnectRef","connectChannel","chatIdToConnect","apiKey","connection","parseResult","notification","utterance","messageId","code","getErrorMessage","cognition","capturedUrl","topic","summary","runBackupPoll","chatIdToPoll","history","err","startBackupPoll","scheduleReconnect","scheduleReconnectSelf","chatIdToReconnect","delay","connect","disconnect","clearProcessedIds","useMessageEvents","userName","userData","externalId","apiClient","setMessages","currentChat","setCurrentChat","isChatClosed","publishApiError","publishNetworkError","showCognition","hideCognition","useAgentCognitionContext","apiClientRef","onReceiveMessage","prev","updatedMessages","handleRealTimeError","handleRatingRequest","handleChatClosed","onCleanMessages","onSendMessage","userMessage","newMessages","connectError","onRateChat","rating","getEnvVariable","__vite_import_meta_env__","ENV_API_URL","ENV_REGION_API_URL","getApiUrl","getRegionApiUrl","EloquentAiApiClient","regionApiUrl","DEFAULT_OPTIONS","isRetryableError","getDelayMs","attempt","exponentialDelay","cappedDelay","withRetry","operation","opts","cache","inflight","useFetch","fetcher","dedupe","setData","setError","isLoading","setIsLoading","mountedRef","fetch","cachedData","promise","resolveUserIdentity","savedData","initialUserId","useUserIdentity","identity","setIdentity","prevInitialUserId","setPrevInitialUserId","useSdkInitialization","apiUrlOverride","isUserIdentityReady","apiUrl","setChatSettings","isReady","setIsReady","setIsChatClosed","isChatActive","setIsChatActive","sdkBootFetch","savedMessages","savedIsChatClosed","savedChatToken","hasBootedRef","orgResponse","orgError","wrapPromise","welcomeMessage","m","MOBILE_MEDIA_QUERY","getIsMobileScreen","useUiInitialization","propIsMobile","isMobileScreen","setIsMobileScreen","portalContainer","setPortalContainer","isMobile","isSSR","mediaQueryList","handleChange","CHAT_CLOSED_COOKIE_TTL_HOURS","getChatClosedCookieName","useChat","propIsInitiallyOpen","propHasCloseButton","propHasCleanChatButton","deprecatedInitialOpen","deprecatedCloseButton","deprecatedCleanChatButton","propProactiveMessageHideDelay","isAlwaysOpen","hasCleanChatButtonOverride","initialChat","initialMessages","initialIsChatClosed","chatInterfaceProps","propInitialOpen","propCloseButton","propCleanChatButton","chatClosedCookieName","chatOpen","setChatOpenState","getCookie","hasAppliedBootInitialOpen","setHasAppliedBootInitialOpen","bootInitialOpen","isInitiallyOpen","hasCloseButton","hasCleanChatButton","proactiveMessageHideDelay","setChatOpen","next","deleteCookie","setCookie","chatOpenDebounced","useDebounce","prevInitialMessages","setPrevInitialMessages","prevInitialChat","setPrevInitialChat","prevInitialIsChatClosed","setPrevInitialIsChatClosed","hasDismissedProactiveMessage","setHasDismissedProactiveMessage","proactiveMessageText","proactiveMessage","lastIdentifyKeyRef","identifyPayload","identifyKey","onStartNewChat","hideProactiveMessage","useKeyboardInset","enabled","inset","setInset","viewport","update","overlap","useScrollLock","locked","body","scrollY","previousStyle","useAgentCognition","setIsVisible","content","setContent","timerRef","pendingContentRef","newContent","updateCognition","AgentCognitionProvider","AgentCognitionContext","ErrorProvider","hideSdk","setHideSdk","createPublishApiError","contextValue","ErrorContext","CHAT_DESKTOP_VIEWPORT_INSET_PX","InternalChat","INTERNAL_ONLY_CHAT_INTERFACE_ONLY","INTERNAL_ONLY_SHOW_CLEAN_CHAT_BUTTON","INTERNAL_ONLY_BLOCK_STYLE","INTERNAL_ONLY_FEATURE_MESSAGE_CLICK","INTERNAL_ONLY_FEATURE_CLEAR_CHAT_CLICK","INTERNAL_ONLY_SHOW_COPY_BUTTON","INTERNAL_ONLY_ENVIRONMENT","INTERNAL_ONLY_API_URL","keyboardInset","isBooting","renderContent","wrapperCSS","Fragment","mainCSS","SkeletonChatInterface","ChatInterface","ThemeProvider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B,EAACqlB,GAAA,EAAW,GAAG/kB,GAAO,CAAE,GAC7BglB,EAAK;AAAA,EACd,GACcH,IAAMpkB,GAAWT,CAAK;AACtC;","x_google_ignoreList":[11,12,13,14,15,16,17,18,19]}
|
|
1
|
+
{"version":3,"file":"index.mjs","sources":["../src/instrumentation.ts","../src/components/embed/chat-bubble.tsx","../src/components/embed/iframe.tsx","../src/components/embed/portal.tsx","../src/components/embed/proactive-message.tsx","../src/lib/cookies.ts","../src/components/chat/hooks/use-interface-props.ts","../src/hooks/use-latest-ref.ts","../src/lib/http.ts","../src/lib/url-params.ts","../src/components/chat/hooks/use-persistence.ts","../src/lib/appsync-events-client.ts","../node_modules/zod/v4/core/core.js","../node_modules/zod/v4/core/util.js","../node_modules/zod/v4/core/errors.js","../node_modules/zod/v4/core/parse.js","../node_modules/zod/v4/core/regexes.js","../node_modules/zod/v4/core/versions.js","../node_modules/zod/v4/core/schemas.js","../node_modules/zod/v4/core/api.js","../node_modules/zod/v4/mini/schemas.js","../src/components/chat/validations.ts","../src/components/chat/hooks/use-realtime-socket.ts","../src/components/chat/message-mapping.ts","../src/components/chat/hooks/use-message-events.ts","../src/lib/config.ts","../src/lib/eloquent-ai-api-client.ts","../src/lib/wrap-promise.ts","../src/lib/retry.ts","../src/hooks/use-fetch.ts","../src/components/chat/hooks/use-user-identity.ts","../src/components/chat/hooks/use-sdk-initialization.ts","../src/components/chat/hooks/use-ui-initialization.ts","../src/components/chat/hooks/use-chat.ts","../src/components/chat/hooks/use-keyboard-inset.ts","../src/components/chat/hooks/use-scroll-lock.ts","../src/contexts/agent-cognition/use-agent-cognition.ts","../src/contexts/agent-cognition/agent-cognition-provider.tsx","../src/contexts/error-handling/error-provider.tsx","../src/components/chat/chat.tsx","../src/components/embed/render-chat.tsx"],"sourcesContent":["// Only initialize Sentry on the client side\nif (typeof window !== \"undefined\") {\n // Transform Vite environment values to Sentry format\n // Access import.meta.env only on the client side to avoid SSR issues\n const viteEnv = import.meta.env.VITE_ENVIRONMENT as string | undefined;\n const environment = viteEnv === \"prod\" ? \"production\" : \"development\";\n const isLocal = viteEnv === \"local\";\n\n // Dynamically import Sentry to avoid SSR issues. Destructure only `init`:\n // holding the whole namespace would keep every barrel export (replay,\n // feedback, canvas integrations — hundreds of KB) alive in the bundle.\n import(\"@sentry/react\").then(({ init }) => {\n init({\n dsn: import.meta.env.VITE_SENTRY_DSN,\n environment,\n sendDefaultPii: false,\n debug: false,\n enabled: !isLocal,\n beforeSend(event) {\n const sensitiveHeaders = new Set([\n \"authorization\",\n \"cookie\",\n \"x-api-key\",\n \"x-auth-token\",\n ]);\n const headers = event.request?.headers as\n | Record<string, string>\n | undefined;\n if (headers) {\n for (const key of Object.keys(headers)) {\n if (sensitiveHeaders.has(key.toLowerCase())) {\n headers[key] = \"[Filtered]\";\n }\n }\n }\n if (event.request) {\n event.request.data = \"[Filtered]\";\n }\n return event;\n },\n });\n });\n}\n","\"use client\";\n\nimport { cn } from \"@/lib/utils\";\n\nimport { Logo } from \"@/components/logo\";\n\nexport function ChatBubble({\n toggleBubble,\n isDarkMode = false,\n}: {\n isOpen: boolean;\n toggleBubble: () => void;\n /** Renders in its own iframe (no `.dark` ancestor), so the mode arrives as a prop. */\n isDarkMode?: boolean;\n}) {\n const bubbleBackground = isDarkMode ? \"#fff\" : \"#000\";\n const logoForeground = isDarkMode ? \"#000000\" : \"#ffffff\";\n\n return (\n <div className=\"eloq:absolute eloq:inset-0 eloq:m-auto eloq:flex eloq:items-center eloq:justify-center eloq:overflow-hidden\">\n <div\n className={cn(\n \"eloq:chat-bubble eloq:relative eloq:flex eloq:items-center eloq:justify-center eloq:w-12 eloq:h-12 eloq:rounded-full eloq:cursor-pointer\",\n // Inverted in dark mode: a black launcher disappears on dark pages.\n isDarkMode\n ? \"eloq:bg-[#fff] eloq:text-[#000]\"\n : \"eloq:bg-[#000] eloq:text-[#fff]\",\n )}\n onClick={toggleBubble}\n >\n <div className=\"eloq:absolute eloq:inset-0 eloq:flex eloq:justify-center eloq:items-center eloq:m-auto\">\n <Logo bgColor={bubbleBackground} fgColor={logoForeground} />\n </div>\n </div>\n </div>\n );\n}\n","import { HTMLAttributes, PropsWithChildren, ReactNode, useState } from \"react\";\nimport { createPortal } from \"react-dom\";\n\ntype IframeProps = PropsWithChildren<HTMLAttributes<HTMLIFrameElement>> & {\n head: ReactNode;\n};\n\nexport function Iframe({ children, head, ...props }: IframeProps) {\n const [contentRef, setContentRef] = useState<HTMLIFrameElement | null>(null);\n const headNode = contentRef?.contentWindow?.document?.head;\n const bodyNode = contentRef?.contentWindow?.document?.body;\n return (\n <iframe {...props} ref={setContentRef}>\n {headNode && createPortal(head, headNode)}\n {bodyNode && createPortal(children, bodyNode)}\n </iframe>\n );\n}\n","\"use client\";\n\nimport type { ReactNode } from \"react\";\nimport { createPortal } from \"react-dom\";\n\ninterface PortalProps {\n children: ReactNode;\n container: HTMLElement;\n}\n\nexport function Portal({ children, container }: PortalProps) {\n return createPortal(children, container);\n}\n","\"use client\";\n\nimport { useEffect, useState } from \"react\";\nimport { X } from \"lucide-react\";\n\nimport { getContrastingTextColor } from \"@/lib/color-contrast\";\nimport { cn } from \"@/lib/utils\";\nimport { useTheme } from \"@/contexts/theme.context\";\n\nexport interface ProactiveMessageProps {\n message: string;\n isVisible: boolean;\n onDismiss: () => void;\n onMessageClick?: () => void;\n autoHideDelay?: number;\n}\n\nexport function ProactiveMessage({\n message,\n isVisible,\n onDismiss,\n onMessageClick,\n autoHideDelay,\n}: ProactiveMessageProps) {\n const [shouldRender, setShouldRender] = useState(false);\n const [animationState, setAnimationState] = useState<\n \"entering\" | \"visible\" | \"exiting\"\n >(\"entering\");\n const theme = useTheme();\n\n useEffect(() => {\n if (isVisible) {\n setShouldRender(true);\n setAnimationState(\"entering\");\n\n // Start entrance animation\n const enterTimer = setTimeout(() => {\n setAnimationState(\"visible\");\n }, 50);\n\n const hideTimer = setTimeout(() => {\n setAnimationState(\"exiting\");\n // Start exit animation\n setTimeout(() => {\n onDismiss();\n }, 300);\n }, autoHideDelay);\n\n return () => {\n clearTimeout(enterTimer);\n clearTimeout(hideTimer);\n };\n } else {\n setAnimationState(\"exiting\");\n // Delay hiding to allow for exit animation\n const timer = setTimeout(() => {\n setShouldRender(false);\n setAnimationState(\"entering\"); // Reset for next time\n }, 300);\n\n return () => clearTimeout(timer);\n }\n }, [isVisible, onDismiss, autoHideDelay]);\n\n if (!shouldRender) {\n return null;\n }\n\n return (\n <div\n className={cn(\n // right-16 leaves a ~7px gap between the tail tip and the launcher\n // circle's edge — the tail points at it without sliding underneath.\n \"eloq:absolute eloq:right-16 eloq:bottom-0 eloq:max-w-xs eloq:transform eloq:transition-all eloq:duration-500 eloq:ease-out\",\n animationState === \"entering\" &&\n \"eloq:translate-x-8 eloq:opacity-0 eloq:scale-95\",\n animationState === \"visible\" &&\n \"eloq:translate-x-0 eloq:opacity-100 eloq:scale-100\",\n animationState === \"exiting\" &&\n \"eloq:translate-x-8 eloq:opacity-0 eloq:scale-95\",\n )}\n >\n {/* drop-shadow (not box-shadow) so the shadow follows the combined\n silhouette of the bubble AND its tail as one continuous shape. */}\n <div className=\"eloq:relative eloq:drop-shadow-lg eloq:hover:drop-shadow-xl eloq:transition-all eloq:duration-300\">\n {/* Message bubble */}\n <div\n className=\"eloq:relative eloq:rounded-lg eloq:border eloq:p-3 eloq:cursor-pointer\"\n style={{\n backgroundColor: theme.botBubbleColor,\n }}\n onClick={onMessageClick}\n >\n {/* Tail: the original curved wedge, stroked so it carries the same\n 1px outline as the bubble (vector-effect keeps the stroke at\n real 1px despite the viewBox scaling). The cover rect hides the\n stroke along the attachment edge inside the bubble, so tail and\n bubble outlines merge into one shape. The SVG is mirrored\n (-scale-x-100), so low viewBox x is the outward tip and high x\n the attachment side. */}\n <svg\n aria-hidden\n className=\"eloq:absolute eloq:bottom-1 eloq:-right-[9px] eloq:h-4 eloq:w-4 eloq:-scale-x-100\"\n viewBox=\"0 0 10.54 11.14\"\n >\n {/* strokeWidth 2, not 1: SVG strokes are centered on the path, so\n half sits under the fill — 2 leaves exactly 1px visible\n outside, matching the bubble's 1px CSS border. */}\n <path\n d=\"M5.75,0s0,.36,0,.51c-.09,4.52-5.74,10.64-5.74,10.64,8.19.02,10.54-2.26,10.54-2.26h0c-1.6-2.96-3.19-5.92-4.79-8.88Z\"\n fill={theme.botBubbleColor}\n strokeWidth={2}\n vectorEffect=\"non-scaling-stroke\"\n style={{ stroke: \"hsl(var(--border))\" }}\n />\n <rect\n x=\"6.2\"\n y=\"-1\"\n width=\"6\"\n height=\"14\"\n fill={theme.botBubbleColor}\n />\n </svg>\n {/* The corner-pinned X is absolutely positioned and ignores the\n text flow entirely; pr-4 (16px, on top of the bubble's own\n 12px padding) keeps the text clear of the X's glyph. */}\n <p\n className=\"eloq:text-sm eloq:leading-relaxed eloq:pr-4\"\n style={{\n color:\n theme.botBubbleTextColor ||\n getContrastingTextColor(theme.botBubbleColor),\n }}\n >\n {message}\n </p>\n <button\n aria-label=\"Dismiss message\"\n onClick={(e) => {\n e.stopPropagation();\n onDismiss();\n }}\n // Pinned to the bubble's top-right corner, outside the text\n // flow — a flex-row placement can't tuck the glyph into the\n // padding area. p-1.5 keeps a 24px hit area around the 12px\n // icon; top/right-0.5 leaves the glyph ~8px from the edges.\n className=\"eloq:absolute eloq:top-0.5 eloq:right-0.5 eloq:p-1.5 eloq:opacity-50 eloq:hover:opacity-100 eloq:hover:bg-black/5 eloq:dark:hover:bg-white/10 eloq:rounded-full eloq:transition-all eloq:duration-200\"\n style={{\n // Follows the bubble's computed text colour, so the X blends\n // with the message on any bubble background (and dark mode).\n color:\n theme.botBubbleTextColor ||\n getContrastingTextColor(theme.botBubbleColor),\n }}\n >\n <X className=\"eloq:w-2.5 eloq:h-2.5\" strokeWidth={1.75} />\n </button>\n </div>\n </div>\n </div>\n );\n}\n","/**\n * Read a cookie value by name.\n * @returns The decoded cookie value, or null if it doesn't exist or there's no document.\n */\nexport function getCookie(name: string): string | null {\n if (typeof document === \"undefined\") return null;\n const match = document.cookie.match(new RegExp(`(?:^|; )${name}=([^;]*)`));\n return match ? decodeURIComponent(match[1]) : null;\n}\n\n/**\n * Set a cookie with a given name, value, and TTL in hours.\n */\nexport function setCookie(name: string, value: string, hours: number) {\n if (typeof document === \"undefined\") return;\n const expires = new Date(Date.now() + hours * 60 * 60 * 1000).toUTCString();\n document.cookie = `${name}=${encodeURIComponent(value)}; expires=${expires}; path=/; SameSite=Lax`;\n}\n\n/**\n * Delete a cookie by name.\n */\nexport function deleteCookie(name: string) {\n if (typeof document === \"undefined\") return;\n document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`;\n}\n","\"use client\";\n\nimport { useMemo } from \"react\";\n\nimport type { BootResponse } from \"@/lib/eloquent-ai-api-client\";\n\nimport { ChatInterfaceProps } from \"@/components/chat-interface\";\n\nexport interface UseInterfacePropsParams {\n chatProps?: Partial<ChatInterfaceProps>;\n chatSettings: BootResponse[\"chat_settings\"] | null;\n}\n\n/**\n * Hook to handle chat interface properties generation\n * Combines user-provided props with server-provided settings\n */\nexport function useInterfaceProps({\n chatProps,\n chatSettings,\n}: UseInterfacePropsParams): Partial<ChatInterfaceProps> {\n const chatInterfaceProps = useMemo(() => {\n if (!chatSettings) return chatProps as Partial<ChatInterfaceProps>;\n\n return {\n assistantName: chatSettings.agent_name,\n assistantLogo: chatSettings.avatar_url || undefined,\n theme: {\n ...chatProps?.theme,\n mode: chatSettings.theme ?? \"light\",\n userBubbleColor:\n chatSettings.user_bubble_color || chatProps?.theme?.userBubbleColor,\n botBubbleColor:\n chatSettings.bot_bubble_color || chatProps?.theme?.botBubbleColor,\n suggestedMessageBubbleColor:\n chatSettings.suggested_message_bubble_color ||\n chatProps?.theme?.suggestedMessageBubbleColor,\n userBubbleTextColor:\n chatSettings.user_bubble_text_color ||\n chatProps?.theme?.userBubbleTextColor,\n botBubbleTextColor:\n chatSettings.bot_bubble_text_color ||\n chatProps?.theme?.botBubbleTextColor,\n suggestedMessageBubbleTextColor:\n chatSettings.suggested_message_bubble_text_color ||\n chatProps?.theme?.suggestedMessageBubbleTextColor,\n },\n welcomeMessage: chatSettings.welcome_message || undefined,\n legalText: chatSettings.footer_html || undefined,\n suggestedMessages: chatSettings.suggested_messages,\n suggestedMessageTexts: chatSettings.suggested_message_texts ?? undefined,\n // Boot value wins when the server sends one (?? so an explicit false\n // still wins); the host-app prop is the fallback.\n hasSuggestedMessageAura:\n chatSettings.suggested_message_aura ??\n chatProps?.hasSuggestedMessageAura,\n hasSuggestedMessageShine:\n chatSettings.suggested_message_shine ??\n chatProps?.hasSuggestedMessageShine,\n displayWelcomeMessages: chatSettings.auto_display_welcome_message,\n collectUserFeedback: chatSettings.collect_user_feedback,\n title: chatSettings.title || \"responds instantly\",\n subtitle: chatSettings.subtitle || \"Ask me anything\",\n };\n }, [chatProps, chatSettings]);\n\n return chatInterfaceProps;\n}\n","import { useEffect, useRef } from \"react\";\n\n/**\n * Returns a ref that always holds the latest `value`, updated after every\n * render. The \"latest ref\" pattern: long-lived closures (timers, socket\n * subscriptions) read `ref.current` at call time instead of capturing a\n * stale value, without needing the value in any dependency array.\n */\nexport function useLatestRef<Type>(value: Type): { readonly current: Type } {\n const reference = useRef(value);\n\n useEffect(() => {\n reference.current = value;\n });\n\n return reference;\n}\n","// Custom error class for network errors (CORS, fetch failures)\nexport class NetworkError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"NetworkError\";\n }\n}\n\n// Custom error class for server errors\nexport class ServerError extends Error {\n status: number;\n response: Record<string, Record<string, string | number>[]>;\n\n constructor(\n status: number,\n message: string,\n response: Record<string, Record<string, string | number>[]>,\n ) {\n super(message);\n this.name = \"ServerError\";\n this.status = status;\n this.response = response;\n }\n}\n\nexport interface HttpClientConfig {\n baseURL: string;\n appId: string;\n userId?: string;\n}\n\nconst CHAT_TOKEN_HEADER = \"x-elo-chat-token\";\nconst CHAT_TOKEN_RENEWED_HEADER = \"x-elo-chat-token-renewed\";\n\nexport class HttpClient {\n private baseURL: string;\n private headers: HeadersInit;\n private region: string | null = null;\n private chatToken: string | null = null;\n\n constructor(config: HttpClientConfig) {\n this.baseURL = config.baseURL;\n\n this.headers = {\n \"Content-Type\": \"application/json\",\n \"ELO-APP-ID\": config.appId,\n Origin: typeof window !== \"undefined\" ? window.location.origin : \"\",\n };\n }\n\n setRegion(region: string): void {\n this.region = region;\n }\n\n setChatToken(token: string | null): void {\n this.chatToken = token;\n }\n\n getChatToken(): string | null {\n return this.chatToken;\n }\n\n private async request<T>(url: string, options: RequestInit = {}): Promise<T> {\n const regionHeader: Record<string, string> = this.region\n ? { \"X-Region\": this.region }\n : {};\n const chatTokenHeader: Record<string, string> = this.chatToken\n ? { [CHAT_TOKEN_HEADER]: this.chatToken }\n : {};\n\n let response: Response;\n try {\n response = await fetch(`${this.baseURL}${url}`, {\n ...options,\n headers: {\n ...this.headers,\n ...regionHeader,\n ...chatTokenHeader,\n ...options.headers,\n },\n });\n } catch (error) {\n if (error instanceof TypeError) {\n throw new NetworkError(error.message);\n }\n throw error;\n }\n\n const renewedToken = response.headers.get(CHAT_TOKEN_RENEWED_HEADER);\n if (renewedToken) {\n this.chatToken = renewedToken;\n }\n\n let responseData;\n try {\n responseData = await response.json();\n } catch (e) {\n console.error(\"Error parsing JSON response:\", e);\n }\n\n if (!response.ok) {\n // Check for server errors (500 range)\n if (response.status >= 500) {\n throw new ServerError(response.status, \"API error\", responseData);\n }\n throw new ServerError(response.status, \"HTTP error\", responseData);\n }\n\n return responseData;\n }\n\n async get<T>(url: string) {\n return this.request<T>(url, { method: \"GET\" });\n }\n\n async post<T, D>(url: string, data: D): Promise<T> {\n return this.request<T>(url, {\n method: \"POST\",\n body: JSON.stringify(data),\n });\n }\n\n async put<T, D>(url: string, data: D): Promise<T> {\n return this.request<T>(url, {\n method: \"PUT\",\n body: JSON.stringify(data),\n });\n }\n\n /**\n * External GET request without default headers or credentials\n * Used for cross-origin requests that don't need authentication\n */\n async getExternal<T>(url: string): Promise<T> {\n const response = await fetch(url, {\n method: \"GET\",\n credentials: \"omit\",\n });\n\n let responseData;\n try {\n responseData = await response.json();\n } catch (e) {\n console.error(\"Error parsing JSON response:\", e);\n }\n\n if (!response.ok) {\n // Check for server errors (500 range)\n if (response.status >= 500) {\n throw new ServerError(response.status, \"API error\", responseData);\n }\n throw new ServerError(response.status, \"HTTP error\", responseData);\n }\n\n return responseData;\n }\n}\n","/**\n * Reads the current page URL search params from the host website.\n * Returns an empty object during SSR or when there are no query params.\n */\nexport function getCurrentUrlSearchParams(): Record<string, string> {\n if (typeof window === \"undefined\") {\n return {};\n }\n\n const params = new URLSearchParams(window.location.search);\n const result: Record<string, string> = {};\n\n params.forEach((value, key) => {\n result[key] = value;\n });\n\n return result;\n}\n","\"use client\";\n\nimport { useCallback, useMemo } from \"react\";\n\nimport { Message } from \"@/types/message\";\n\n// Single key for localStorage\nconst STORAGE_NAMESPACE = \"eloquent-ai::conversation-data\";\n\nconst isClient = typeof window !== \"undefined\";\n\n// 30 minutes in milliseconds\nconst CHAT_EXPIRY_TIME = 30 * 60 * 1000;\n\nexport interface ChatData {\n conversationId: string | null;\n userId: string | null;\n externalId?: string | null;\n deviceId: string | null;\n messages: Message[];\n lastActivity?: number;\n isChatClosed?: boolean;\n chatToken?: string | null;\n}\n\n/**\n * Hook to manage persistence of chat data, including conversation ID, user ID, last activity time, and messages.\n * @returns An object containing the conversation data and functions to set and clear the data.\n */\nexport function usePersistence({ appId }: { appId: string }) {\n const STORAGE_KEY = useMemo(() => `${STORAGE_NAMESPACE}-${appId}`, [appId]);\n const defaultObject = useMemo(\n () => ({\n conversationId: null,\n userId: null,\n deviceId: null,\n messages: [],\n }),\n [],\n );\n\n /**\n * Get saved conversation data from localStorage\n */\n const getSavedChatData = useCallback((): ChatData => {\n try {\n if (!isClient) return defaultObject;\n const storedData = localStorage.getItem(STORAGE_KEY);\n if (!storedData) {\n return defaultObject;\n }\n return JSON.parse(storedData) as ChatData;\n } catch (error) {\n console.error(\n \"Error retrieving conversation data from localStorage:\",\n error,\n );\n return defaultObject;\n }\n }, [STORAGE_KEY, defaultObject]);\n\n /**\n * Check if the current conversation has expired (inactive for more than 30 minutes)\n */\n const isChatExpired = useCallback((): boolean => {\n try {\n const data = getSavedChatData();\n if (!data.lastActivity) return true;\n\n const currentTime = Date.now();\n return currentTime - data.lastActivity > CHAT_EXPIRY_TIME;\n } catch (error) {\n console.error(\"Error checking conversation expiration:\", error);\n return true;\n }\n }, [getSavedChatData]);\n\n /**\n * Save conversation data to localStorage\n */\n const saveChatData = useCallback(\n (\n conversationId: string,\n userId: string,\n messages: Message[],\n deviceId: string,\n chatToken?: string | null,\n ) => {\n try {\n if (!isClient) return;\n const chatData: ChatData = {\n conversationId,\n userId,\n deviceId,\n messages,\n lastActivity: Date.now(),\n chatToken,\n };\n\n localStorage.setItem(STORAGE_KEY, JSON.stringify(chatData));\n } catch (error) {\n console.error(\"Error saving conversation data to localStorage:\", error);\n }\n },\n [STORAGE_KEY],\n );\n\n /**\n * Mark the current conversation as closed, so a page refresh still shows\n * the \"Start a new conversation\" screen instead of resetting it.\n */\n const markChatClosed = useCallback(() => {\n try {\n if (!isClient) return;\n const data = getSavedChatData();\n localStorage.setItem(\n STORAGE_KEY,\n JSON.stringify({ ...data, isChatClosed: true }),\n );\n } catch (error) {\n console.error(\n \"Error marking conversation as closed in localStorage:\",\n error,\n );\n }\n }, [STORAGE_KEY, getSavedChatData]);\n\n /**\n * Clear only conversationId, messages, and lastActivity from localStorage, preserving userId and deviceId\n */\n const clearChatData = useCallback(() => {\n try {\n if (!isClient) return;\n const stored = localStorage.getItem(STORAGE_KEY);\n if (stored) {\n const data = JSON.parse(stored);\n localStorage.setItem(\n STORAGE_KEY,\n JSON.stringify({\n ...defaultObject,\n deviceId: data.deviceId,\n userId: data.userId,\n }),\n );\n }\n } catch (error) {\n console.error(\n \"Error clearing conversation data from localStorage:\",\n error,\n );\n }\n }, [STORAGE_KEY, defaultObject]);\n\n /**\n * Update the last activity timestamp\n */\n const updateLastActivity = useCallback(() => {\n try {\n if (!isClient) return;\n const data = getSavedChatData();\n if (data.conversationId) {\n data.lastActivity = Date.now();\n localStorage.setItem(STORAGE_KEY, JSON.stringify(data));\n }\n } catch (error) {\n console.error(\"Error updating last activity timestamp:\", error);\n }\n }, [getSavedChatData, STORAGE_KEY]);\n\n return {\n isChatExpired,\n saveChatData,\n clearChatData,\n getSavedChatData,\n updateLastActivity,\n markChatClosed,\n };\n}\n","// Minimal AWS AppSync Events API real-time client — a hand-rolled\n// replacement for aws-amplify's `events.connect`, which carried ~160KB of\n// dependencies (amplify core, rxjs, graphql) for the tiny surface this SDK\n// uses: subscribe to one channel, deliver events, detect disconnects.\n//\n// Protocol reference: AWS \"Event API WebSocket protocol\" docs, cross-checked\n// against @aws-amplify/api-graphql's AWSAppSyncEventsProvider implementation\n// (subprotocol names, header encoding, keep-alive semantics, timeouts).\n//\n// Wire flow:\n// 1. Open a WebSocket to the realtime endpoint with two subprotocols:\n// \"aws-appsync-event-ws\" and \"header-<base64url(auth JSON)>\"\n// 2. Send {\"type\":\"connection_init\"}, await connection_ack (carries\n// connectionTimeoutMs — the keep-alive death window)\n// 3. Send subscribe with the SAME authorization embedded in the message\n// (per-operation auth is required by the protocol, not just per-connect)\n// 4. Receive {\"type\":\"data\", \"event\":\"<JSON string>\"} per published event\n// 5. Server sends {\"type\":\"ka\"} every ~60s; if neither ka nor data arrives\n// within connectionTimeoutMs, the connection is dead.\n\n/** Lambda-authorizer token (the chat token) or the API key fallback. */\nexport type AppSyncEventsAuth =\n | { authorizationToken: string }\n | { apiKey: string };\n\nexport type AppSyncEventsConnection = {\n /** Sends unsubscribe, closes the socket, and suppresses onDisconnect. */\n close: () => void;\n};\n\nexport type WebSocketLike = {\n readyState: number;\n send: (data: string) => void;\n close: () => void;\n addEventListener: (\n type: \"open\" | \"message\" | \"close\" | \"error\",\n listener: (event: { data?: unknown }) => void,\n ) => void;\n};\n\nexport type ConnectAppSyncEventsOptions = {\n /** The HTTP Events endpoint from boot settings (chat_settings.app_sync_url). */\n httpEndpoint: string;\n auth: AppSyncEventsAuth;\n /** Channel path, e.g. \"/default/chat/<chatId>\". */\n channel: string;\n /** Called once per published event, with the payload already JSON-parsed. */\n onEvent: (event: unknown) => void;\n /**\n * Called exactly once when an established connection dies (server close,\n * network drop, keep-alive timeout). NOT called after close(), and not\n * called for connections that never established (connect() rejects there).\n */\n onDisconnect: (reason: string) => void;\n /** Injectable for tests; defaults to the global WebSocket constructor. */\n createWebSocket?: (url: string, protocols: string[]) => WebSocketLike;\n};\n\nexport const APPSYNC_EVENTS_SUBPROTOCOL = \"aws-appsync-event-ws\";\n\n/** connection_init → connection_ack and subscribe → subscribe_success wait. */\nexport const HANDSHAKE_TIMEOUT_MILLISECONDS = 15000;\n/** Fallback keep-alive death window when the ack doesn't carry one. */\nexport const DEFAULT_CONNECTION_TIMEOUT_MILLISECONDS = 300000;\n/** How often the keep-alive clock is checked. */\nexport const KEEP_ALIVE_CHECK_INTERVAL_MILLISECONDS = 5000;\n\nconst WEB_SOCKET_OPEN_STATE = 1;\n\n/**\n * Derives the realtime WebSocket URL from the HTTP Events endpoint.\n * Standard AWS domains swap the service subdomain; custom domains keep the\n * host and only append the path.\n * https://xxx.appsync-api.us-east-1.amazonaws.com/event\n * → wss://xxx.appsync-realtime-api.us-east-1.amazonaws.com/event/realtime\n * https://events.example.com/event\n * → wss://events.example.com/event/realtime\n */\nexport function deriveRealtimeUrl(httpEndpoint: string): string {\n const url = new URL(httpEndpoint);\n const isStandardAwsDomain =\n /\\.appsync-api\\.[\\w-]+\\.amazonaws\\.com(\\.cn)?$/.test(url.hostname);\n if (isStandardAwsDomain) {\n url.hostname = url.hostname.replace(\n \".appsync-api.\",\n \".appsync-realtime-api.\",\n );\n }\n url.protocol = \"wss:\";\n url.pathname = `${url.pathname.replace(/\\/$/, \"\")}/realtime`;\n return url.toString();\n}\n\n/**\n * The authorization object embedded both in the connect subprotocol header\n * and in every subscribe message. `host` is always the HTTP endpoint's host\n * (not the realtime host), per the protocol.\n */\nexport function buildAuthorization(\n httpEndpoint: string,\n auth: AppSyncEventsAuth,\n): Record<string, string> {\n const host = new URL(httpEndpoint).host;\n if (\"authorizationToken\" in auth) {\n return { Authorization: auth.authorizationToken, host };\n }\n return { \"x-api-key\": auth.apiKey, host };\n}\n\n/**\n * Encodes the authorization object into the `header-…` subprotocol value:\n * base64url (`+`→`-`, `/`→`_`) with padding stripped — `=` is not a legal\n * character in a Sec-WebSocket-Protocol token and fails the handshake.\n */\nexport function encodeAuthProtocol(\n authorization: Record<string, string>,\n): string {\n const base64 = btoa(JSON.stringify(authorization));\n return `header-${base64.replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\")}`;\n}\n\ntype ServerMessage = {\n type?: string;\n id?: string;\n event?: unknown;\n connectionTimeoutMs?: number;\n errors?: { errorType?: string; message?: string }[];\n};\n\nfunction formatErrors(errors: ServerMessage[\"errors\"]): string {\n if (!errors || errors.length === 0) return \"unknown error\";\n return errors\n .map((error) => `${error.errorType ?? \"Error\"}: ${error.message ?? \"\"}`)\n .join(\"; \");\n}\n\n/**\n * Opens a connection and subscribes to one channel. Resolves once the\n * subscription is confirmed; rejects if any handshake step fails or times\n * out (the socket is closed in that case). After resolution, connection\n * death is reported via onDisconnect exactly once.\n */\nexport function connectAppSyncEvents(\n options: ConnectAppSyncEventsOptions,\n): Promise<AppSyncEventsConnection> {\n const {\n httpEndpoint,\n auth,\n channel,\n onEvent,\n onDisconnect,\n createWebSocket = (url, protocols) =>\n new WebSocket(url, protocols) as WebSocketLike,\n } = options;\n\n const authorization = buildAuthorization(httpEndpoint, auth);\n const realtimeUrl = deriveRealtimeUrl(httpEndpoint);\n const subscriptionId = crypto.randomUUID();\n\n return new Promise<AppSyncEventsConnection>((resolve, reject) => {\n let socket: WebSocketLike;\n try {\n socket = createWebSocket(realtimeUrl, [\n APPSYNC_EVENTS_SUBPROTOCOL,\n encodeAuthProtocol(authorization),\n ]);\n } catch (error) {\n reject(error instanceof Error ? error : new Error(String(error)));\n return;\n }\n\n let phase: \"connecting\" | \"subscribing\" | \"established\" | \"closed\" =\n \"connecting\";\n let isClosedByClient = false;\n let connectionTimeoutMilliseconds = DEFAULT_CONNECTION_TIMEOUT_MILLISECONDS;\n let lastLivenessTimestamp = Date.now();\n\n let handshakeTimer: ReturnType<typeof setTimeout> | null = null;\n let keepAliveTimer: ReturnType<typeof setInterval> | null = null;\n\n const clearTimers = () => {\n if (handshakeTimer) {\n clearTimeout(handshakeTimer);\n handshakeTimer = null;\n }\n if (keepAliveTimer) {\n clearInterval(keepAliveTimer);\n keepAliveTimer = null;\n }\n };\n\n /** Single funnel for connection death, in any phase. */\n const terminate = (reason: string) => {\n if (phase === \"closed\") return;\n const wasEstablished = phase === \"established\";\n phase = \"closed\";\n clearTimers();\n try {\n socket.close();\n } catch {\n // Already closed/closing.\n }\n if (isClosedByClient) return;\n if (wasEstablished) {\n onDisconnect(reason);\n } else {\n reject(new Error(reason));\n }\n };\n\n const send = (message: Record<string, unknown>) => {\n if (socket.readyState !== WEB_SOCKET_OPEN_STATE) return;\n socket.send(JSON.stringify(message));\n };\n\n const startHandshakeTimer = (step: string) => {\n if (handshakeTimer) clearTimeout(handshakeTimer);\n handshakeTimer = setTimeout(() => {\n terminate(`Timed out waiting for ${step}`);\n }, HANDSHAKE_TIMEOUT_MILLISECONDS);\n };\n\n socket.addEventListener(\"open\", () => {\n if (phase === \"closed\") return;\n send({ type: \"connection_init\" });\n startHandshakeTimer(\"connection_ack\");\n });\n\n socket.addEventListener(\"message\", (event) => {\n if (phase === \"closed\") return;\n\n let message: ServerMessage;\n try {\n message = JSON.parse(String(event.data)) as ServerMessage;\n } catch {\n console.warn(\"[EloquentChatSDK] Unparseable realtime frame ignored\");\n return;\n }\n\n switch (message.type) {\n case \"connection_ack\": {\n if (phase !== \"connecting\") return;\n phase = \"subscribing\";\n if (typeof message.connectionTimeoutMs === \"number\") {\n connectionTimeoutMilliseconds = message.connectionTimeoutMs;\n }\n send({\n type: \"subscribe\",\n id: subscriptionId,\n channel,\n authorization,\n });\n startHandshakeTimer(\"subscribe_success\");\n return;\n }\n case \"connection_error\": {\n terminate(`Connection error: ${formatErrors(message.errors)}`);\n return;\n }\n case \"subscribe_success\": {\n if (phase !== \"subscribing\" || message.id !== subscriptionId) return;\n phase = \"established\";\n if (handshakeTimer) {\n clearTimeout(handshakeTimer);\n handshakeTimer = null;\n }\n lastLivenessTimestamp = Date.now();\n keepAliveTimer = setInterval(() => {\n if (\n Date.now() - lastLivenessTimestamp >\n connectionTimeoutMilliseconds\n ) {\n terminate(\"Keep-alive timeout\");\n }\n }, KEEP_ALIVE_CHECK_INTERVAL_MILLISECONDS);\n resolve({\n close: () => {\n isClosedByClient = true;\n send({ type: \"unsubscribe\", id: subscriptionId });\n terminate(\"Closed by client\");\n },\n });\n return;\n }\n case \"subscribe_error\": {\n if (message.id !== subscriptionId) return;\n terminate(`Subscribe error: ${formatErrors(message.errors)}`);\n return;\n }\n case \"ka\": {\n lastLivenessTimestamp = Date.now();\n return;\n }\n case \"data\": {\n if (message.id !== subscriptionId) return;\n // A busy channel can delay ka frames; data proves liveness too\n // (mirrors the amplify client).\n lastLivenessTimestamp = Date.now();\n // The event field is a JSON *string* per the protocol.\n let payload: unknown = message.event;\n if (typeof payload === \"string\") {\n try {\n payload = JSON.parse(payload);\n } catch {\n console.warn(\n \"[EloquentChatSDK] Unparseable realtime event ignored\",\n );\n return;\n }\n }\n onEvent(payload);\n return;\n }\n case \"broadcast_error\": {\n console.warn(\n \"[EloquentChatSDK] Realtime broadcast error:\",\n formatErrors(message.errors),\n );\n return;\n }\n default:\n // unsubscribe_success and unknown/future frame types.\n return;\n }\n });\n\n socket.addEventListener(\"close\", () => {\n terminate(\"WebSocket closed\");\n });\n\n socket.addEventListener(\"error\", () => {\n // A close event follows an error; terminate here anyway so failures\n // that never fire close (some environments) still reject/notify.\n terminate(\"WebSocket error\");\n });\n });\n}\n","var _a;\n/** A special constant with type `never` */\nexport const NEVER = /*@__PURE__*/ Object.freeze({\n status: \"aborted\",\n});\nexport /*@__NO_SIDE_EFFECTS__*/ function $constructor(name, initializer, params) {\n function init(inst, def) {\n if (!inst._zod) {\n Object.defineProperty(inst, \"_zod\", {\n value: {\n def,\n constr: _,\n traits: new Set(),\n },\n enumerable: false,\n });\n }\n if (inst._zod.traits.has(name)) {\n return;\n }\n inst._zod.traits.add(name);\n initializer(inst, def);\n // support prototype modifications\n const proto = _.prototype;\n const keys = Object.keys(proto);\n for (let i = 0; i < keys.length; i++) {\n const k = keys[i];\n if (!(k in inst)) {\n inst[k] = proto[k].bind(inst);\n }\n }\n }\n // doesn't work if Parent has a constructor with arguments\n const Parent = params?.Parent ?? Object;\n class Definition extends Parent {\n }\n Object.defineProperty(Definition, \"name\", { value: name });\n function _(def) {\n var _a;\n const inst = params?.Parent ? new Definition() : this;\n init(inst, def);\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n for (const fn of inst._zod.deferred) {\n fn();\n }\n return inst;\n }\n Object.defineProperty(_, \"init\", { value: init });\n Object.defineProperty(_, Symbol.hasInstance, {\n value: (inst) => {\n if (params?.Parent && inst instanceof params.Parent)\n return true;\n return inst?._zod?.traits?.has(name);\n },\n });\n Object.defineProperty(_, \"name\", { value: name });\n return _;\n}\n////////////////////////////// UTILITIES ///////////////////////////////////////\nexport const $brand = Symbol(\"zod_brand\");\nexport class $ZodAsyncError extends Error {\n constructor() {\n super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);\n }\n}\nexport class $ZodEncodeError extends Error {\n constructor(name) {\n super(`Encountered unidirectional transform during encode: ${name}`);\n this.name = \"ZodEncodeError\";\n }\n}\n(_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {});\nexport const globalConfig = globalThis.__zod_globalConfig;\nexport function config(newConfig) {\n if (newConfig)\n Object.assign(globalConfig, newConfig);\n return globalConfig;\n}\n","import { globalConfig } from \"./core.js\";\n// functions\nexport function assertEqual(val) {\n return val;\n}\nexport function assertNotEqual(val) {\n return val;\n}\nexport function assertIs(_arg) { }\nexport function assertNever(_x) {\n throw new Error(\"Unexpected value in exhaustive check\");\n}\nexport function assert(_) { }\nexport function getEnumValues(entries) {\n const numericValues = Object.values(entries).filter((v) => typeof v === \"number\");\n const values = Object.entries(entries)\n .filter(([k, _]) => numericValues.indexOf(+k) === -1)\n .map(([_, v]) => v);\n return values;\n}\nexport function joinValues(array, separator = \"|\") {\n return array.map((val) => stringifyPrimitive(val)).join(separator);\n}\nexport function jsonStringifyReplacer(_, value) {\n if (typeof value === \"bigint\")\n return value.toString();\n return value;\n}\nexport function cached(getter) {\n const set = false;\n return {\n get value() {\n if (!set) {\n const value = getter();\n Object.defineProperty(this, \"value\", { value });\n return value;\n }\n throw new Error(\"cached value already set\");\n },\n };\n}\nexport function nullish(input) {\n return input === null || input === undefined;\n}\nexport function cleanRegex(source) {\n const start = source.startsWith(\"^\") ? 1 : 0;\n const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n return source.slice(start, end);\n}\nexport function floatSafeRemainder(val, step) {\n const ratio = val / step;\n const roundedRatio = Math.round(ratio);\n // Use a relative epsilon scaled to the magnitude of the result\n const tolerance = Number.EPSILON * Math.max(Math.abs(ratio), 1);\n if (Math.abs(ratio - roundedRatio) < tolerance)\n return 0;\n return ratio - roundedRatio;\n}\nconst EVALUATING = /* @__PURE__*/ Symbol(\"evaluating\");\nexport function defineLazy(object, key, getter) {\n let value = undefined;\n Object.defineProperty(object, key, {\n get() {\n if (value === EVALUATING) {\n // Circular reference detected, return undefined to break the cycle\n return undefined;\n }\n if (value === undefined) {\n value = EVALUATING;\n value = getter();\n }\n return value;\n },\n set(v) {\n Object.defineProperty(object, key, {\n value: v,\n // configurable: true,\n });\n // object[key] = v;\n },\n configurable: true,\n });\n}\nexport function objectClone(obj) {\n return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));\n}\nexport function assignProp(target, prop, value) {\n Object.defineProperty(target, prop, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n}\nexport function mergeDefs(...defs) {\n const mergedDescriptors = {};\n for (const def of defs) {\n const descriptors = Object.getOwnPropertyDescriptors(def);\n Object.assign(mergedDescriptors, descriptors);\n }\n return Object.defineProperties({}, mergedDescriptors);\n}\nexport function cloneDef(schema) {\n return mergeDefs(schema._zod.def);\n}\nexport function getElementAtPath(obj, path) {\n if (!path)\n return obj;\n return path.reduce((acc, key) => acc?.[key], obj);\n}\nexport function promiseAllObject(promisesObj) {\n const keys = Object.keys(promisesObj);\n const promises = keys.map((key) => promisesObj[key]);\n return Promise.all(promises).then((results) => {\n const resolvedObj = {};\n for (let i = 0; i < keys.length; i++) {\n resolvedObj[keys[i]] = results[i];\n }\n return resolvedObj;\n });\n}\nexport function randomString(length = 10) {\n const chars = \"abcdefghijklmnopqrstuvwxyz\";\n let str = \"\";\n for (let i = 0; i < length; i++) {\n str += chars[Math.floor(Math.random() * chars.length)];\n }\n return str;\n}\nexport function esc(str) {\n return JSON.stringify(str);\n}\nexport function slugify(input) {\n return input\n .toLowerCase()\n .trim()\n .replace(/[^\\w\\s-]/g, \"\")\n .replace(/[\\s_-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n}\nexport const captureStackTrace = (\"captureStackTrace\" in Error ? Error.captureStackTrace : (..._args) => { });\nexport function isObject(data) {\n return typeof data === \"object\" && data !== null && !Array.isArray(data);\n}\nexport const allowsEval = /* @__PURE__*/ cached(() => {\n // Skip the probe under `jitless`: strict CSPs report the caught `new Function`\n // as a `securitypolicyviolation` even though the throw is swallowed.\n if (globalConfig.jitless) {\n return false;\n }\n // @ts-ignore\n if (typeof navigator !== \"undefined\" && navigator?.userAgent?.includes(\"Cloudflare\")) {\n return false;\n }\n try {\n const F = Function;\n new F(\"\");\n return true;\n }\n catch (_) {\n return false;\n }\n});\nexport function isPlainObject(o) {\n if (isObject(o) === false)\n return false;\n // modified constructor\n const ctor = o.constructor;\n if (ctor === undefined)\n return true;\n if (typeof ctor !== \"function\")\n return true;\n // modified prototype\n const prot = ctor.prototype;\n if (isObject(prot) === false)\n return false;\n // ctor doesn't have static `isPrototypeOf`\n if (Object.prototype.hasOwnProperty.call(prot, \"isPrototypeOf\") === false) {\n return false;\n }\n return true;\n}\nexport function shallowClone(o) {\n if (isPlainObject(o))\n return { ...o };\n if (Array.isArray(o))\n return [...o];\n if (o instanceof Map)\n return new Map(o);\n if (o instanceof Set)\n return new Set(o);\n return o;\n}\nexport function numKeys(data) {\n let keyCount = 0;\n for (const key in data) {\n if (Object.prototype.hasOwnProperty.call(data, key)) {\n keyCount++;\n }\n }\n return keyCount;\n}\nexport const getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case \"undefined\":\n return \"undefined\";\n case \"string\":\n return \"string\";\n case \"number\":\n return Number.isNaN(data) ? \"nan\" : \"number\";\n case \"boolean\":\n return \"boolean\";\n case \"function\":\n return \"function\";\n case \"bigint\":\n return \"bigint\";\n case \"symbol\":\n return \"symbol\";\n case \"object\":\n if (Array.isArray(data)) {\n return \"array\";\n }\n if (data === null) {\n return \"null\";\n }\n if (data.then && typeof data.then === \"function\" && data.catch && typeof data.catch === \"function\") {\n return \"promise\";\n }\n if (typeof Map !== \"undefined\" && data instanceof Map) {\n return \"map\";\n }\n if (typeof Set !== \"undefined\" && data instanceof Set) {\n return \"set\";\n }\n if (typeof Date !== \"undefined\" && data instanceof Date) {\n return \"date\";\n }\n // @ts-ignore\n if (typeof File !== \"undefined\" && data instanceof File) {\n return \"file\";\n }\n return \"object\";\n default:\n throw new Error(`Unknown data type: ${t}`);\n }\n};\nexport const propertyKeyTypes = /* @__PURE__*/ new Set([\"string\", \"number\", \"symbol\"]);\nexport const primitiveTypes = /* @__PURE__*/ new Set([\n \"string\",\n \"number\",\n \"bigint\",\n \"boolean\",\n \"symbol\",\n \"undefined\",\n]);\nexport function escapeRegex(str) {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n// zod-specific utils\nexport function clone(inst, def, params) {\n const cl = new inst._zod.constr(def ?? inst._zod.def);\n if (!def || params?.parent)\n cl._zod.parent = inst;\n return cl;\n}\nexport function normalizeParams(_params) {\n const params = _params;\n if (!params)\n return {};\n if (typeof params === \"string\")\n return { error: () => params };\n if (params?.message !== undefined) {\n if (params?.error !== undefined)\n throw new Error(\"Cannot specify both `message` and `error` params\");\n params.error = params.message;\n }\n delete params.message;\n if (typeof params.error === \"string\")\n return { ...params, error: () => params.error };\n return params;\n}\nexport function createTransparentProxy(getter) {\n let target;\n return new Proxy({}, {\n get(_, prop, receiver) {\n target ?? (target = getter());\n return Reflect.get(target, prop, receiver);\n },\n set(_, prop, value, receiver) {\n target ?? (target = getter());\n return Reflect.set(target, prop, value, receiver);\n },\n has(_, prop) {\n target ?? (target = getter());\n return Reflect.has(target, prop);\n },\n deleteProperty(_, prop) {\n target ?? (target = getter());\n return Reflect.deleteProperty(target, prop);\n },\n ownKeys(_) {\n target ?? (target = getter());\n return Reflect.ownKeys(target);\n },\n getOwnPropertyDescriptor(_, prop) {\n target ?? (target = getter());\n return Reflect.getOwnPropertyDescriptor(target, prop);\n },\n defineProperty(_, prop, descriptor) {\n target ?? (target = getter());\n return Reflect.defineProperty(target, prop, descriptor);\n },\n });\n}\nexport function stringifyPrimitive(value) {\n if (typeof value === \"bigint\")\n return value.toString() + \"n\";\n if (typeof value === \"string\")\n return `\"${value}\"`;\n return `${value}`;\n}\nexport function optionalKeys(shape) {\n return Object.keys(shape).filter((k) => {\n return shape[k]._zod.optin === \"optional\" && shape[k]._zod.optout === \"optional\";\n });\n}\nexport const NUMBER_FORMAT_RANGES = {\n safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],\n int32: [-2147483648, 2147483647],\n uint32: [0, 4294967295],\n float32: [-3.4028234663852886e38, 3.4028234663852886e38],\n float64: [-Number.MAX_VALUE, Number.MAX_VALUE],\n};\nexport const BIGINT_FORMAT_RANGES = {\n int64: [/* @__PURE__*/ BigInt(\"-9223372036854775808\"), /* @__PURE__*/ BigInt(\"9223372036854775807\")],\n uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt(\"18446744073709551615\")],\n};\nexport function pick(schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".pick() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const newShape = {};\n for (const key in mask) {\n if (!(key in currDef.shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n newShape[key] = currDef.shape[key];\n }\n assignProp(this, \"shape\", newShape); // self-caching\n return newShape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function omit(schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".omit() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const newShape = { ...schema._zod.def.shape };\n for (const key in mask) {\n if (!(key in currDef.shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n delete newShape[key];\n }\n assignProp(this, \"shape\", newShape); // self-caching\n return newShape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function extend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to extend: expected a plain object\");\n }\n const checks = schema._zod.def.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n // Only throw if new shape overlaps with existing shape\n // Use getOwnPropertyDescriptor to check key existence without accessing values\n const existingShape = schema._zod.def.shape;\n for (const key in shape) {\n if (Object.getOwnPropertyDescriptor(existingShape, key) !== undefined) {\n throw new Error(\"Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.\");\n }\n }\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const _shape = { ...schema._zod.def.shape, ...shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n });\n return clone(schema, def);\n}\nexport function safeExtend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to safeExtend: expected a plain object\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const _shape = { ...schema._zod.def.shape, ...shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n });\n return clone(schema, def);\n}\nexport function merge(a, b) {\n if (a._zod.def.checks?.length) {\n throw new Error(\".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.\");\n }\n const def = mergeDefs(a._zod.def, {\n get shape() {\n const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n get catchall() {\n return b._zod.def.catchall;\n },\n checks: b._zod.def.checks ?? [],\n });\n return clone(a, def);\n}\nexport function partial(Class, schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".partial() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const oldShape = schema._zod.def.shape;\n const shape = { ...oldShape };\n if (mask) {\n for (const key in mask) {\n if (!(key in oldShape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n // if (oldShape[key]!._zod.optin === \"optional\") continue;\n shape[key] = Class\n ? new Class({\n type: \"optional\",\n innerType: oldShape[key],\n })\n : oldShape[key];\n }\n }\n else {\n for (const key in oldShape) {\n // if (oldShape[key]!._zod.optin === \"optional\") continue;\n shape[key] = Class\n ? new Class({\n type: \"optional\",\n innerType: oldShape[key],\n })\n : oldShape[key];\n }\n }\n assignProp(this, \"shape\", shape); // self-caching\n return shape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function required(Class, schema, mask) {\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const oldShape = schema._zod.def.shape;\n const shape = { ...oldShape };\n if (mask) {\n for (const key in mask) {\n if (!(key in shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n // overwrite with non-optional\n shape[key] = new Class({\n type: \"nonoptional\",\n innerType: oldShape[key],\n });\n }\n }\n else {\n for (const key in oldShape) {\n // overwrite with non-optional\n shape[key] = new Class({\n type: \"nonoptional\",\n innerType: oldShape[key],\n });\n }\n }\n assignProp(this, \"shape\", shape); // self-caching\n return shape;\n },\n });\n return clone(schema, def);\n}\n// invalid_type | too_big | too_small | invalid_format | not_multiple_of | unrecognized_keys | invalid_union | invalid_key | invalid_element | invalid_value | custom\nexport function aborted(x, startIndex = 0) {\n if (x.aborted === true)\n return true;\n for (let i = startIndex; i < x.issues.length; i++) {\n if (x.issues[i]?.continue !== true) {\n return true;\n }\n }\n return false;\n}\n// Checks for explicit abort (continue === false), as opposed to implicit abort (continue === undefined).\n// Used to respect `abort: true` in .refine() even for checks that have a `when` function.\nexport function explicitlyAborted(x, startIndex = 0) {\n if (x.aborted === true)\n return true;\n for (let i = startIndex; i < x.issues.length; i++) {\n if (x.issues[i]?.continue === false) {\n return true;\n }\n }\n return false;\n}\nexport function prefixIssues(path, issues) {\n return issues.map((iss) => {\n var _a;\n (_a = iss).path ?? (_a.path = []);\n iss.path.unshift(path);\n return iss;\n });\n}\nexport function unwrapMessage(message) {\n return typeof message === \"string\" ? message : message?.message;\n}\nexport function finalizeIssue(iss, ctx, config) {\n const message = iss.message\n ? iss.message\n : (unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ??\n unwrapMessage(ctx?.error?.(iss)) ??\n unwrapMessage(config.customError?.(iss)) ??\n unwrapMessage(config.localeError?.(iss)) ??\n \"Invalid input\");\n const { inst: _inst, continue: _continue, input: _input, ...rest } = iss;\n rest.path ?? (rest.path = []);\n rest.message = message;\n if (ctx?.reportInput) {\n rest.input = _input;\n }\n return rest;\n}\nexport function getSizableOrigin(input) {\n if (input instanceof Set)\n return \"set\";\n if (input instanceof Map)\n return \"map\";\n // @ts-ignore\n if (input instanceof File)\n return \"file\";\n return \"unknown\";\n}\nexport function getLengthableOrigin(input) {\n if (Array.isArray(input))\n return \"array\";\n if (typeof input === \"string\")\n return \"string\";\n return \"unknown\";\n}\nexport function parsedType(data) {\n const t = typeof data;\n switch (t) {\n case \"number\": {\n return Number.isNaN(data) ? \"nan\" : \"number\";\n }\n case \"object\": {\n if (data === null) {\n return \"null\";\n }\n if (Array.isArray(data)) {\n return \"array\";\n }\n const obj = data;\n if (obj && Object.getPrototypeOf(obj) !== Object.prototype && \"constructor\" in obj && obj.constructor) {\n return obj.constructor.name;\n }\n }\n }\n return t;\n}\nexport function issue(...args) {\n const [iss, input, inst] = args;\n if (typeof iss === \"string\") {\n return {\n message: iss,\n code: \"custom\",\n input,\n inst,\n };\n }\n return { ...iss };\n}\nexport function cleanEnum(obj) {\n return Object.entries(obj)\n .filter(([k, _]) => {\n // return true if NaN, meaning it's not a number, thus a string key\n return Number.isNaN(Number.parseInt(k, 10));\n })\n .map((el) => el[1]);\n}\n// Codec utility functions\nexport function base64ToUint8Array(base64) {\n const binaryString = atob(base64);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n return bytes;\n}\nexport function uint8ArrayToBase64(bytes) {\n let binaryString = \"\";\n for (let i = 0; i < bytes.length; i++) {\n binaryString += String.fromCharCode(bytes[i]);\n }\n return btoa(binaryString);\n}\nexport function base64urlToUint8Array(base64url) {\n const base64 = base64url.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padding = \"=\".repeat((4 - (base64.length % 4)) % 4);\n return base64ToUint8Array(base64 + padding);\n}\nexport function uint8ArrayToBase64url(bytes) {\n return uint8ArrayToBase64(bytes).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=/g, \"\");\n}\nexport function hexToUint8Array(hex) {\n const cleanHex = hex.replace(/^0x/, \"\");\n if (cleanHex.length % 2 !== 0) {\n throw new Error(\"Invalid hex string length\");\n }\n const bytes = new Uint8Array(cleanHex.length / 2);\n for (let i = 0; i < cleanHex.length; i += 2) {\n bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16);\n }\n return bytes;\n}\nexport function uint8ArrayToHex(bytes) {\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n// instanceof\nexport class Class {\n constructor(..._args) { }\n}\n","import { $constructor } from \"./core.js\";\nimport * as util from \"./util.js\";\nconst initializer = (inst, def) => {\n inst.name = \"$ZodError\";\n Object.defineProperty(inst, \"_zod\", {\n value: inst._zod,\n enumerable: false,\n });\n Object.defineProperty(inst, \"issues\", {\n value: def,\n enumerable: false,\n });\n inst.message = JSON.stringify(def, util.jsonStringifyReplacer, 2);\n Object.defineProperty(inst, \"toString\", {\n value: () => inst.message,\n enumerable: false,\n });\n};\nexport const $ZodError = $constructor(\"$ZodError\", initializer);\nexport const $ZodRealError = $constructor(\"$ZodError\", initializer, { Parent: Error });\nexport function flattenError(error, mapper = (issue) => issue.message) {\n const fieldErrors = {};\n const formErrors = [];\n for (const sub of error.issues) {\n if (sub.path.length > 0) {\n fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];\n fieldErrors[sub.path[0]].push(mapper(sub));\n }\n else {\n formErrors.push(mapper(sub));\n }\n }\n return { formErrors, fieldErrors };\n}\nexport function formatError(error, mapper = (issue) => issue.message) {\n const fieldErrors = { _errors: [] };\n const processError = (error, path = []) => {\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path]));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else {\n const fullpath = [...path, ...issue.path];\n if (fullpath.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n }\n else {\n let curr = fieldErrors;\n let i = 0;\n while (i < fullpath.length) {\n const el = fullpath[i];\n const terminal = i === fullpath.length - 1;\n if (!terminal) {\n curr[el] = curr[el] || { _errors: [] };\n }\n else {\n curr[el] = curr[el] || { _errors: [] };\n curr[el]._errors.push(mapper(issue));\n }\n curr = curr[el];\n i++;\n }\n }\n }\n }\n };\n processError(error);\n return fieldErrors;\n}\nexport function treeifyError(error, mapper = (issue) => issue.message) {\n const result = { errors: [] };\n const processError = (error, path = []) => {\n var _a, _b;\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n // regular union error\n issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path]));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else {\n const fullpath = [...path, ...issue.path];\n if (fullpath.length === 0) {\n result.errors.push(mapper(issue));\n continue;\n }\n let curr = result;\n let i = 0;\n while (i < fullpath.length) {\n const el = fullpath[i];\n const terminal = i === fullpath.length - 1;\n if (typeof el === \"string\") {\n curr.properties ?? (curr.properties = {});\n (_a = curr.properties)[el] ?? (_a[el] = { errors: [] });\n curr = curr.properties[el];\n }\n else {\n curr.items ?? (curr.items = []);\n (_b = curr.items)[el] ?? (_b[el] = { errors: [] });\n curr = curr.items[el];\n }\n if (terminal) {\n curr.errors.push(mapper(issue));\n }\n i++;\n }\n }\n }\n };\n processError(error);\n return result;\n}\n/** Format a ZodError as a human-readable string in the following form.\n *\n * From\n *\n * ```ts\n * ZodError {\n * issues: [\n * {\n * expected: 'string',\n * code: 'invalid_type',\n * path: [ 'username' ],\n * message: 'Invalid input: expected string'\n * },\n * {\n * expected: 'number',\n * code: 'invalid_type',\n * path: [ 'favoriteNumbers', 1 ],\n * message: 'Invalid input: expected number'\n * }\n * ];\n * }\n * ```\n *\n * to\n *\n * ```\n * username\n * ✖ Expected number, received string at \"username\n * favoriteNumbers[0]\n * ✖ Invalid input: expected number\n * ```\n */\nexport function toDotPath(_path) {\n const segs = [];\n const path = _path.map((seg) => (typeof seg === \"object\" ? seg.key : seg));\n for (const seg of path) {\n if (typeof seg === \"number\")\n segs.push(`[${seg}]`);\n else if (typeof seg === \"symbol\")\n segs.push(`[${JSON.stringify(String(seg))}]`);\n else if (/[^\\w$]/.test(seg))\n segs.push(`[${JSON.stringify(seg)}]`);\n else {\n if (segs.length)\n segs.push(\".\");\n segs.push(seg);\n }\n }\n return segs.join(\"\");\n}\nexport function prettifyError(error) {\n const lines = [];\n // sort by path length\n const issues = [...error.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length);\n // Process each issue\n for (const issue of issues) {\n lines.push(`✖ ${issue.message}`);\n if (issue.path?.length)\n lines.push(` → at ${toDotPath(issue.path)}`);\n }\n // Convert Map to formatted string\n return lines.join(\"\\n\");\n}\n","import * as core from \"./core.js\";\nimport * as errors from \"./errors.js\";\nimport * as util from \"./util.js\";\nexport const _parse = (_Err) => (schema, value, _ctx, _params) => {\n const ctx = _ctx ? { ..._ctx, async: false } : { async: false };\n const result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n if (result.issues.length) {\n const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n util.captureStackTrace(e, _params?.callee);\n throw e;\n }\n return result.value;\n};\nexport const parse = /* @__PURE__*/ _parse(errors.$ZodRealError);\nexport const _parseAsync = (_Err) => async (schema, value, _ctx, params) => {\n const ctx = _ctx ? { ..._ctx, async: true } : { async: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n if (result.issues.length) {\n const e = new (params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n util.captureStackTrace(e, params?.callee);\n throw e;\n }\n return result.value;\n};\nexport const parseAsync = /* @__PURE__*/ _parseAsync(errors.$ZodRealError);\nexport const _safeParse = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, async: false } : { async: false };\n const result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n return result.issues.length\n ? {\n success: false,\n error: new (_Err ?? errors.$ZodError)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n }\n : { success: true, data: result.value };\n};\nexport const safeParse = /* @__PURE__*/ _safeParse(errors.$ZodRealError);\nexport const _safeParseAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, async: true } : { async: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n return result.issues.length\n ? {\n success: false,\n error: new _Err(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n }\n : { success: true, data: result.value };\n};\nexport const safeParseAsync = /* @__PURE__*/ _safeParseAsync(errors.$ZodRealError);\nexport const _encode = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return _parse(_Err)(schema, value, ctx);\n};\nexport const encode = /* @__PURE__*/ _encode(errors.$ZodRealError);\nexport const _decode = (_Err) => (schema, value, _ctx) => {\n return _parse(_Err)(schema, value, _ctx);\n};\nexport const decode = /* @__PURE__*/ _decode(errors.$ZodRealError);\nexport const _encodeAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return _parseAsync(_Err)(schema, value, ctx);\n};\nexport const encodeAsync = /* @__PURE__*/ _encodeAsync(errors.$ZodRealError);\nexport const _decodeAsync = (_Err) => async (schema, value, _ctx) => {\n return _parseAsync(_Err)(schema, value, _ctx);\n};\nexport const decodeAsync = /* @__PURE__*/ _decodeAsync(errors.$ZodRealError);\nexport const _safeEncode = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return _safeParse(_Err)(schema, value, ctx);\n};\nexport const safeEncode = /* @__PURE__*/ _safeEncode(errors.$ZodRealError);\nexport const _safeDecode = (_Err) => (schema, value, _ctx) => {\n return _safeParse(_Err)(schema, value, _ctx);\n};\nexport const safeDecode = /* @__PURE__*/ _safeDecode(errors.$ZodRealError);\nexport const _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return _safeParseAsync(_Err)(schema, value, ctx);\n};\nexport const safeEncodeAsync = /* @__PURE__*/ _safeEncodeAsync(errors.$ZodRealError);\nexport const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => {\n return _safeParseAsync(_Err)(schema, value, _ctx);\n};\nexport const safeDecodeAsync = /* @__PURE__*/ _safeDecodeAsync(errors.$ZodRealError);\n","import * as util from \"./util.js\";\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link cuid2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const cuid = /^[cC][0-9a-z]{6,}$/;\nexport const cuid2 = /^[0-9a-z]+$/;\nexport const ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;\nexport const xid = /^[0-9a-vA-V]{20}$/;\nexport const ksuid = /^[A-Za-z0-9]{27}$/;\nexport const nanoid = /^[a-zA-Z0-9_-]{21}$/;\n/** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */\nexport const duration = /^P(?:(\\d+W)|(?!.*W)(?=\\d|T\\d)(\\d+Y)?(\\d+M)?(\\d+D)?(T(?=\\d)(\\d+H)?(\\d+M)?(\\d+([.,]\\d+)?S)?)?)$/;\n/** Implements ISO 8601-2 extensions like explicit +- prefixes, mixing weeks with other units, and fractional/negative components. */\nexport const extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\\d+Y)|(?:[-+]?\\d+[.,]\\d+Y$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:(?:[-+]?\\d+W)|(?:[-+]?\\d+[.,]\\d+W$))?(?:(?:[-+]?\\d+D)|(?:[-+]?\\d+[.,]\\d+D$))?(?:T(?=[\\d+-])(?:(?:[-+]?\\d+H)|(?:[-+]?\\d+[.,]\\d+H$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:[-+]?\\d+(?:[.,]\\d+)?S)?)??$/;\n/** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */\nexport const guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;\n/** Returns a regex for validating an RFC 9562/4122 UUID.\n *\n * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */\nexport const uuid = (version) => {\n if (!version)\n return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;\n return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);\n};\nexport const uuid4 = /*@__PURE__*/ uuid(4);\nexport const uuid6 = /*@__PURE__*/ uuid(6);\nexport const uuid7 = /*@__PURE__*/ uuid(7);\n/** Practical email validation */\nexport const email = /^(?!\\.)(?!.*\\.\\.)([A-Za-z0-9_'+\\-\\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$/;\n/** Equivalent to the HTML5 input[type=email] validation implemented by browsers. Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email */\nexport const html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n/** The classic emailregex.com regex for RFC 5322-compliant emails */\nexport const rfc5322Email = /^(([^<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/;\n/** A loose regex that allows Unicode characters, enforces length limits, and that's about it. */\nexport const unicodeEmail = /^[^\\s@\"]{1,64}@[^\\s@]{1,255}$/u;\nexport const idnEmail = unicodeEmail;\nexport const browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression\nconst _emoji = `^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$`;\nexport function emoji() {\n return new RegExp(_emoji, \"u\");\n}\nexport const ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;\nexport const ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;\nexport const mac = (delimiter) => {\n const escapedDelim = util.escapeRegex(delimiter ?? \":\");\n return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`);\n};\nexport const cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/([0-9]|[1-2][0-9]|3[0-2])$/;\nexport const cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;\n// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript\nexport const base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;\nexport const base64url = /^[A-Za-z0-9_-]*$/;\n// based on https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address\n// export const hostname: RegExp = /^([a-zA-Z0-9-]+\\.)*[a-zA-Z0-9-]+$/;\nexport const hostname = /^(?=.{1,253}\\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\\.?$/;\nexport const domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,}$/;\nexport const httpProtocol = /^https?$/;\n// https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces)\n// E.164: leading digit must be 1-9; total digits (excluding '+') between 7-15\nexport const e164 = /^\\+[1-9]\\d{6,14}$/;\n// const dateSource = `((\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\\\d|30)|(02)-(0[1-9]|1\\\\d|2[0-8])))`;\nconst dateSource = `(?:(?:\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\\\d|30)|(?:02)-(?:0[1-9]|1\\\\d|2[0-8])))`;\nexport const date = /*@__PURE__*/ new RegExp(`^${dateSource}$`);\nfunction timeSource(args) {\n const hhmm = `(?:[01]\\\\d|2[0-3]):[0-5]\\\\d`;\n const regex = typeof args.precision === \"number\"\n ? args.precision === -1\n ? `${hhmm}`\n : args.precision === 0\n ? `${hhmm}:[0-5]\\\\d`\n : `${hhmm}:[0-5]\\\\d\\\\.\\\\d{${args.precision}}`\n : `${hhmm}(?::[0-5]\\\\d(?:\\\\.\\\\d+)?)?`;\n return regex;\n}\nexport function time(args) {\n return new RegExp(`^${timeSource(args)}$`);\n}\n// Adapted from https://stackoverflow.com/a/3143231\nexport function datetime(args) {\n const time = timeSource({ precision: args.precision });\n const opts = [\"Z\"];\n if (args.local)\n opts.push(\"\");\n // if (args.offset) opts.push(`([+-]\\\\d{2}:\\\\d{2})`);\n if (args.offset)\n opts.push(`([+-](?:[01]\\\\d|2[0-3]):[0-5]\\\\d)`);\n const timeRegex = `${time}(?:${opts.join(\"|\")})`;\n return new RegExp(`^${dateSource}T(?:${timeRegex})$`);\n}\nexport const string = (params) => {\n const regex = params ? `[\\\\s\\\\S]{${params?.minimum ?? 0},${params?.maximum ?? \"\"}}` : `[\\\\s\\\\S]*`;\n return new RegExp(`^${regex}$`);\n};\nexport const bigint = /^-?\\d+n?$/;\nexport const integer = /^-?\\d+$/;\nexport const number = /^-?\\d+(?:\\.\\d+)?$/;\nexport const boolean = /^(?:true|false)$/i;\nconst _null = /^null$/i;\nexport { _null as null };\nconst _undefined = /^undefined$/i;\nexport { _undefined as undefined };\n// regex for string with no uppercase letters\nexport const lowercase = /^[^A-Z]*$/;\n// regex for string with no lowercase letters\nexport const uppercase = /^[^a-z]*$/;\n// regex for hexadecimal strings (any length)\nexport const hex = /^[0-9a-fA-F]*$/;\n// Hash regexes for different algorithms and encodings\n// Helper function to create base64 regex with exact length and padding\nfunction fixedBase64(bodyLength, padding) {\n return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`);\n}\n// Helper function to create base64url regex with exact length (no padding)\nfunction fixedBase64url(length) {\n return new RegExp(`^[A-Za-z0-9_-]{${length}}$`);\n}\n// MD5 (16 bytes): base64 = 24 chars total (22 + \"==\")\nexport const md5_hex = /^[0-9a-fA-F]{32}$/;\nexport const md5_base64 = /*@__PURE__*/ fixedBase64(22, \"==\");\nexport const md5_base64url = /*@__PURE__*/ fixedBase64url(22);\n// SHA1 (20 bytes): base64 = 28 chars total (27 + \"=\")\nexport const sha1_hex = /^[0-9a-fA-F]{40}$/;\nexport const sha1_base64 = /*@__PURE__*/ fixedBase64(27, \"=\");\nexport const sha1_base64url = /*@__PURE__*/ fixedBase64url(27);\n// SHA256 (32 bytes): base64 = 44 chars total (43 + \"=\")\nexport const sha256_hex = /^[0-9a-fA-F]{64}$/;\nexport const sha256_base64 = /*@__PURE__*/ fixedBase64(43, \"=\");\nexport const sha256_base64url = /*@__PURE__*/ fixedBase64url(43);\n// SHA384 (48 bytes): base64 = 64 chars total (no padding)\nexport const sha384_hex = /^[0-9a-fA-F]{96}$/;\nexport const sha384_base64 = /*@__PURE__*/ fixedBase64(64, \"\");\nexport const sha384_base64url = /*@__PURE__*/ fixedBase64url(64);\n// SHA512 (64 bytes): base64 = 88 chars total (86 + \"==\")\nexport const sha512_hex = /^[0-9a-fA-F]{128}$/;\nexport const sha512_base64 = /*@__PURE__*/ fixedBase64(86, \"==\");\nexport const sha512_base64url = /*@__PURE__*/ fixedBase64url(86);\n","export const version = {\n major: 4,\n minor: 4,\n patch: 3,\n};\n","import * as checks from \"./checks.js\";\nimport * as core from \"./core.js\";\nimport { Doc } from \"./doc.js\";\nimport { parse, parseAsync, safeParse, safeParseAsync } from \"./parse.js\";\nimport * as regexes from \"./regexes.js\";\nimport * as util from \"./util.js\";\nimport { version } from \"./versions.js\";\nexport const $ZodType = /*@__PURE__*/ core.$constructor(\"$ZodType\", (inst, def) => {\n var _a;\n inst ?? (inst = {});\n inst._zod.def = def; // set _def property\n inst._zod.bag = inst._zod.bag || {}; // initialize _bag object\n inst._zod.version = version;\n const checks = [...(inst._zod.def.checks ?? [])];\n // if inst is itself a checks.$ZodCheck, run it as a check\n if (inst._zod.traits.has(\"$ZodCheck\")) {\n checks.unshift(inst);\n }\n for (const ch of checks) {\n for (const fn of ch._zod.onattach) {\n fn(inst);\n }\n }\n if (checks.length === 0) {\n // deferred initializer\n // inst._zod.parse is not yet defined\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n inst._zod.deferred?.push(() => {\n inst._zod.run = inst._zod.parse;\n });\n }\n else {\n const runChecks = (payload, checks, ctx) => {\n let isAborted = util.aborted(payload);\n let asyncResult;\n for (const ch of checks) {\n if (ch._zod.def.when) {\n if (util.explicitlyAborted(payload))\n continue;\n const shouldRun = ch._zod.def.when(payload);\n if (!shouldRun)\n continue;\n }\n else if (isAborted) {\n continue;\n }\n const currLen = payload.issues.length;\n const _ = ch._zod.check(payload);\n if (_ instanceof Promise && ctx?.async === false) {\n throw new core.$ZodAsyncError();\n }\n if (asyncResult || _ instanceof Promise) {\n asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {\n await _;\n const nextLen = payload.issues.length;\n if (nextLen === currLen)\n return;\n if (!isAborted)\n isAborted = util.aborted(payload, currLen);\n });\n }\n else {\n const nextLen = payload.issues.length;\n if (nextLen === currLen)\n continue;\n if (!isAborted)\n isAborted = util.aborted(payload, currLen);\n }\n }\n if (asyncResult) {\n return asyncResult.then(() => {\n return payload;\n });\n }\n return payload;\n };\n const handleCanaryResult = (canary, payload, ctx) => {\n // abort if the canary is aborted\n if (util.aborted(canary)) {\n canary.aborted = true;\n return canary;\n }\n // run checks first, then\n const checkResult = runChecks(payload, checks, ctx);\n if (checkResult instanceof Promise) {\n if (ctx.async === false)\n throw new core.$ZodAsyncError();\n return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx));\n }\n return inst._zod.parse(checkResult, ctx);\n };\n inst._zod.run = (payload, ctx) => {\n if (ctx.skipChecks) {\n return inst._zod.parse(payload, ctx);\n }\n if (ctx.direction === \"backward\") {\n // run canary\n // initial pass (no checks)\n const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true });\n if (canary instanceof Promise) {\n return canary.then((canary) => {\n return handleCanaryResult(canary, payload, ctx);\n });\n }\n return handleCanaryResult(canary, payload, ctx);\n }\n // forward\n const result = inst._zod.parse(payload, ctx);\n if (result instanceof Promise) {\n if (ctx.async === false)\n throw new core.$ZodAsyncError();\n return result.then((result) => runChecks(result, checks, ctx));\n }\n return runChecks(result, checks, ctx);\n };\n }\n // Lazy initialize ~standard to avoid creating objects for every schema\n util.defineLazy(inst, \"~standard\", () => ({\n validate: (value) => {\n try {\n const r = safeParse(inst, value);\n return r.success ? { value: r.data } : { issues: r.error?.issues };\n }\n catch (_) {\n return safeParseAsync(inst, value).then((r) => (r.success ? { value: r.data } : { issues: r.error?.issues }));\n }\n },\n vendor: \"zod\",\n version: 1,\n }));\n});\nexport { clone } from \"./util.js\";\nexport const $ZodString = /*@__PURE__*/ core.$constructor(\"$ZodString\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = [...(inst?._zod.bag?.patterns ?? [])].pop() ?? regexes.string(inst._zod.bag);\n inst._zod.parse = (payload, _) => {\n if (def.coerce)\n try {\n payload.value = String(payload.value);\n }\n catch (_) { }\n if (typeof payload.value === \"string\")\n return payload;\n payload.issues.push({\n expected: \"string\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodStringFormat\", (inst, def) => {\n // check initialization must come first\n checks.$ZodCheckStringFormat.init(inst, def);\n $ZodString.init(inst, def);\n});\nexport const $ZodGUID = /*@__PURE__*/ core.$constructor(\"$ZodGUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.guid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodUUID = /*@__PURE__*/ core.$constructor(\"$ZodUUID\", (inst, def) => {\n if (def.version) {\n const versionMap = {\n v1: 1,\n v2: 2,\n v3: 3,\n v4: 4,\n v5: 5,\n v6: 6,\n v7: 7,\n v8: 8,\n };\n const v = versionMap[def.version];\n if (v === undefined)\n throw new Error(`Invalid UUID version: \"${def.version}\"`);\n def.pattern ?? (def.pattern = regexes.uuid(v));\n }\n else\n def.pattern ?? (def.pattern = regexes.uuid());\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodEmail = /*@__PURE__*/ core.$constructor(\"$ZodEmail\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.email);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodURL = /*@__PURE__*/ core.$constructor(\"$ZodURL\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n try {\n // Trim whitespace from input\n const trimmed = payload.value.trim();\n // When normalize is off, require :// for http/https URLs\n // This prevents strings like \"http:example.com\" or \"https:/path\" from being silently accepted\n if (!def.normalize && def.protocol?.source === regexes.httpProtocol.source) {\n if (!/^https?:\\/\\//i.test(trimmed)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid URL format\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n return;\n }\n }\n // @ts-ignore\n const url = new URL(trimmed);\n if (def.hostname) {\n def.hostname.lastIndex = 0;\n if (!def.hostname.test(url.hostname)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid hostname\",\n pattern: def.hostname.source,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n }\n if (def.protocol) {\n def.protocol.lastIndex = 0;\n if (!def.protocol.test(url.protocol.endsWith(\":\") ? url.protocol.slice(0, -1) : url.protocol)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid protocol\",\n pattern: def.protocol.source,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n }\n // Set the output value based on normalize flag\n if (def.normalize) {\n // Use normalized URL\n payload.value = url.href;\n }\n else {\n // Preserve the original input (trimmed)\n payload.value = trimmed;\n }\n return;\n }\n catch (_) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodEmoji = /*@__PURE__*/ core.$constructor(\"$ZodEmoji\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.emoji());\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodNanoID = /*@__PURE__*/ core.$constructor(\"$ZodNanoID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.nanoid);\n $ZodStringFormat.init(inst, def);\n});\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link $ZodCUID2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const $ZodCUID = /*@__PURE__*/ core.$constructor(\"$ZodCUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cuid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCUID2 = /*@__PURE__*/ core.$constructor(\"$ZodCUID2\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cuid2);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodULID = /*@__PURE__*/ core.$constructor(\"$ZodULID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ulid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodXID = /*@__PURE__*/ core.$constructor(\"$ZodXID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.xid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodKSUID = /*@__PURE__*/ core.$constructor(\"$ZodKSUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ksuid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODateTime = /*@__PURE__*/ core.$constructor(\"$ZodISODateTime\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.datetime(def));\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODate = /*@__PURE__*/ core.$constructor(\"$ZodISODate\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.date);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISOTime = /*@__PURE__*/ core.$constructor(\"$ZodISOTime\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.time(def));\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODuration = /*@__PURE__*/ core.$constructor(\"$ZodISODuration\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.duration);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodIPv4 = /*@__PURE__*/ core.$constructor(\"$ZodIPv4\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ipv4);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.format = `ipv4`;\n});\nexport const $ZodIPv6 = /*@__PURE__*/ core.$constructor(\"$ZodIPv6\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ipv6);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.format = `ipv6`;\n inst._zod.check = (payload) => {\n try {\n // @ts-ignore\n new URL(`http://[${payload.value}]`);\n // return;\n }\n catch {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"ipv6\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodMAC = /*@__PURE__*/ core.$constructor(\"$ZodMAC\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.mac(def.delimiter));\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.format = `mac`;\n});\nexport const $ZodCIDRv4 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv4\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cidrv4);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCIDRv6 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv6\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cidrv6); // not used for validation\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n const parts = payload.value.split(\"/\");\n try {\n if (parts.length !== 2)\n throw new Error();\n const [address, prefix] = parts;\n if (!prefix)\n throw new Error();\n const prefixNum = Number(prefix);\n if (`${prefixNum}` !== prefix)\n throw new Error();\n if (prefixNum < 0 || prefixNum > 128)\n throw new Error();\n // @ts-ignore\n new URL(`http://[${address}]`);\n }\n catch {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"cidrv6\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\n////////////////////////////// ZodBase64 //////////////////////////////\nexport function isValidBase64(data) {\n if (data === \"\")\n return true;\n // atob ignores whitespace, so reject it up front.\n if (/\\s/.test(data))\n return false;\n if (data.length % 4 !== 0)\n return false;\n try {\n // @ts-ignore\n atob(data);\n return true;\n }\n catch {\n return false;\n }\n}\nexport const $ZodBase64 = /*@__PURE__*/ core.$constructor(\"$ZodBase64\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.base64);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.contentEncoding = \"base64\";\n inst._zod.check = (payload) => {\n if (isValidBase64(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"base64\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n////////////////////////////// ZodBase64 //////////////////////////////\nexport function isValidBase64URL(data) {\n if (!regexes.base64url.test(data))\n return false;\n const base64 = data.replace(/[-_]/g, (c) => (c === \"-\" ? \"+\" : \"/\"));\n const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, \"=\");\n return isValidBase64(padded);\n}\nexport const $ZodBase64URL = /*@__PURE__*/ core.$constructor(\"$ZodBase64URL\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.base64url);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.contentEncoding = \"base64url\";\n inst._zod.check = (payload) => {\n if (isValidBase64URL(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"base64url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodE164 = /*@__PURE__*/ core.$constructor(\"$ZodE164\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.e164);\n $ZodStringFormat.init(inst, def);\n});\n////////////////////////////// ZodJWT //////////////////////////////\nexport function isValidJWT(token, algorithm = null) {\n try {\n const tokensParts = token.split(\".\");\n if (tokensParts.length !== 3)\n return false;\n const [header] = tokensParts;\n if (!header)\n return false;\n // @ts-ignore\n const parsedHeader = JSON.parse(atob(header));\n if (\"typ\" in parsedHeader && parsedHeader?.typ !== \"JWT\")\n return false;\n if (!parsedHeader.alg)\n return false;\n if (algorithm && (!(\"alg\" in parsedHeader) || parsedHeader.alg !== algorithm))\n return false;\n return true;\n }\n catch {\n return false;\n }\n}\nexport const $ZodJWT = /*@__PURE__*/ core.$constructor(\"$ZodJWT\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidJWT(payload.value, def.alg))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"jwt\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCustomStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodCustomStringFormat\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (def.fn(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: def.format,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodNumber = /*@__PURE__*/ core.$constructor(\"$ZodNumber\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = inst._zod.bag.pattern ?? regexes.number;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = Number(payload.value);\n }\n catch (_) { }\n const input = payload.value;\n if (typeof input === \"number\" && !Number.isNaN(input) && Number.isFinite(input)) {\n return payload;\n }\n const received = typeof input === \"number\"\n ? Number.isNaN(input)\n ? \"NaN\"\n : !Number.isFinite(input)\n ? \"Infinity\"\n : undefined\n : undefined;\n payload.issues.push({\n expected: \"number\",\n code: \"invalid_type\",\n input,\n inst,\n ...(received ? { received } : {}),\n });\n return payload;\n };\n});\nexport const $ZodNumberFormat = /*@__PURE__*/ core.$constructor(\"$ZodNumberFormat\", (inst, def) => {\n checks.$ZodCheckNumberFormat.init(inst, def);\n $ZodNumber.init(inst, def); // no format checks\n});\nexport const $ZodBoolean = /*@__PURE__*/ core.$constructor(\"$ZodBoolean\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.boolean;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = Boolean(payload.value);\n }\n catch (_) { }\n const input = payload.value;\n if (typeof input === \"boolean\")\n return payload;\n payload.issues.push({\n expected: \"boolean\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodBigInt = /*@__PURE__*/ core.$constructor(\"$ZodBigInt\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.bigint;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = BigInt(payload.value);\n }\n catch (_) { }\n if (typeof payload.value === \"bigint\")\n return payload;\n payload.issues.push({\n expected: \"bigint\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodBigIntFormat = /*@__PURE__*/ core.$constructor(\"$ZodBigIntFormat\", (inst, def) => {\n checks.$ZodCheckBigIntFormat.init(inst, def);\n $ZodBigInt.init(inst, def); // no format checks\n});\nexport const $ZodSymbol = /*@__PURE__*/ core.$constructor(\"$ZodSymbol\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"symbol\")\n return payload;\n payload.issues.push({\n expected: \"symbol\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodUndefined = /*@__PURE__*/ core.$constructor(\"$ZodUndefined\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.undefined;\n inst._zod.values = new Set([undefined]);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"undefined\")\n return payload;\n payload.issues.push({\n expected: \"undefined\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodNull = /*@__PURE__*/ core.$constructor(\"$ZodNull\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.null;\n inst._zod.values = new Set([null]);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (input === null)\n return payload;\n payload.issues.push({\n expected: \"null\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodAny = /*@__PURE__*/ core.$constructor(\"$ZodAny\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload) => payload;\n});\nexport const $ZodUnknown = /*@__PURE__*/ core.$constructor(\"$ZodUnknown\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload) => payload;\n});\nexport const $ZodNever = /*@__PURE__*/ core.$constructor(\"$ZodNever\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n payload.issues.push({\n expected: \"never\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodVoid = /*@__PURE__*/ core.$constructor(\"$ZodVoid\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"undefined\")\n return payload;\n payload.issues.push({\n expected: \"void\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodDate = /*@__PURE__*/ core.$constructor(\"$ZodDate\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce) {\n try {\n payload.value = new Date(payload.value);\n }\n catch (_err) { }\n }\n const input = payload.value;\n const isDate = input instanceof Date;\n const isValidDate = isDate && !Number.isNaN(input.getTime());\n if (isValidDate)\n return payload;\n payload.issues.push({\n expected: \"date\",\n code: \"invalid_type\",\n input,\n ...(isDate ? { received: \"Invalid Date\" } : {}),\n inst,\n });\n return payload;\n };\n});\nfunction handleArrayResult(result, final, index) {\n if (result.issues.length) {\n final.issues.push(...util.prefixIssues(index, result.issues));\n }\n final.value[index] = result.value;\n}\nexport const $ZodArray = /*@__PURE__*/ core.$constructor(\"$ZodArray\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!Array.isArray(input)) {\n payload.issues.push({\n expected: \"array\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n payload.value = Array(input.length);\n const proms = [];\n for (let i = 0; i < input.length; i++) {\n const item = input[i];\n const result = def.element._zod.run({\n value: item,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleArrayResult(result, payload, i)));\n }\n else {\n handleArrayResult(result, payload, i);\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => payload);\n }\n return payload; //handleArrayResultsAsync(parseResults, final);\n };\n});\nfunction handlePropertyResult(result, final, key, input, isOptionalIn, isOptionalOut) {\n const isPresent = key in input;\n if (result.issues.length) {\n // For optional-in/out schemas, ignore errors on absent keys.\n if (isOptionalIn && isOptionalOut && !isPresent) {\n return;\n }\n final.issues.push(...util.prefixIssues(key, result.issues));\n }\n if (!isPresent && !isOptionalIn) {\n if (!result.issues.length) {\n final.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: undefined,\n path: [key],\n });\n }\n return;\n }\n if (result.value === undefined) {\n if (isPresent) {\n final.value[key] = undefined;\n }\n }\n else {\n final.value[key] = result.value;\n }\n}\nfunction normalizeDef(def) {\n const keys = Object.keys(def.shape);\n for (const k of keys) {\n if (!def.shape?.[k]?._zod?.traits?.has(\"$ZodType\")) {\n throw new Error(`Invalid element at key \"${k}\": expected a Zod schema`);\n }\n }\n const okeys = util.optionalKeys(def.shape);\n return {\n ...def,\n keys,\n keySet: new Set(keys),\n numKeys: keys.length,\n optionalKeys: new Set(okeys),\n };\n}\nfunction handleCatchall(proms, input, payload, ctx, def, inst) {\n const unrecognized = [];\n const keySet = def.keySet;\n const _catchall = def.catchall._zod;\n const t = _catchall.def.type;\n const isOptionalIn = _catchall.optin === \"optional\";\n const isOptionalOut = _catchall.optout === \"optional\";\n for (const key in input) {\n // skip __proto__ so it can't replace the result prototype via the\n // assignment setter on the plain {} we build into\n if (key === \"__proto__\")\n continue;\n if (keySet.has(key))\n continue;\n if (t === \"never\") {\n unrecognized.push(key);\n continue;\n }\n const r = _catchall.run({ value: input[key], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut)));\n }\n else {\n handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut);\n }\n }\n if (unrecognized.length) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n keys: unrecognized,\n input,\n inst,\n });\n }\n if (!proms.length)\n return payload;\n return Promise.all(proms).then(() => {\n return payload;\n });\n}\nexport const $ZodObject = /*@__PURE__*/ core.$constructor(\"$ZodObject\", (inst, def) => {\n // requires cast because technically $ZodObject doesn't extend\n $ZodType.init(inst, def);\n // const sh = def.shape;\n const desc = Object.getOwnPropertyDescriptor(def, \"shape\");\n if (!desc?.get) {\n const sh = def.shape;\n Object.defineProperty(def, \"shape\", {\n get: () => {\n const newSh = { ...sh };\n Object.defineProperty(def, \"shape\", {\n value: newSh,\n });\n return newSh;\n },\n });\n }\n const _normalized = util.cached(() => normalizeDef(def));\n util.defineLazy(inst._zod, \"propValues\", () => {\n const shape = def.shape;\n const propValues = {};\n for (const key in shape) {\n const field = shape[key]._zod;\n if (field.values) {\n propValues[key] ?? (propValues[key] = new Set());\n for (const v of field.values)\n propValues[key].add(v);\n }\n }\n return propValues;\n });\n const isObject = util.isObject;\n const catchall = def.catchall;\n let value;\n inst._zod.parse = (payload, ctx) => {\n value ?? (value = _normalized.value);\n const input = payload.value;\n if (!isObject(input)) {\n payload.issues.push({\n expected: \"object\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n payload.value = {};\n const proms = [];\n const shape = value.shape;\n for (const key of value.keys) {\n const el = shape[key];\n const isOptionalIn = el._zod.optin === \"optional\";\n const isOptionalOut = el._zod.optout === \"optional\";\n const r = el._zod.run({ value: input[key], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut)));\n }\n else {\n handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut);\n }\n }\n if (!catchall) {\n return proms.length ? Promise.all(proms).then(() => payload) : payload;\n }\n return handleCatchall(proms, input, payload, ctx, _normalized.value, inst);\n };\n});\nexport const $ZodObjectJIT = /*@__PURE__*/ core.$constructor(\"$ZodObjectJIT\", (inst, def) => {\n // requires cast because technically $ZodObject doesn't extend\n $ZodObject.init(inst, def);\n const superParse = inst._zod.parse;\n const _normalized = util.cached(() => normalizeDef(def));\n const generateFastpass = (shape) => {\n const doc = new Doc([\"shape\", \"payload\", \"ctx\"]);\n const normalized = _normalized.value;\n const parseStr = (key) => {\n const k = util.esc(key);\n return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;\n };\n doc.write(`const input = payload.value;`);\n const ids = Object.create(null);\n let counter = 0;\n for (const key of normalized.keys) {\n ids[key] = `key_${counter++}`;\n }\n // A: preserve key order {\n doc.write(`const newResult = {};`);\n for (const key of normalized.keys) {\n const id = ids[key];\n const k = util.esc(key);\n const schema = shape[key];\n const isOptionalIn = schema?._zod?.optin === \"optional\";\n const isOptionalOut = schema?._zod?.optout === \"optional\";\n doc.write(`const ${id} = ${parseStr(key)};`);\n if (isOptionalIn && isOptionalOut) {\n // For optional-in/out schemas, ignore errors on absent keys\n doc.write(`\n if (${id}.issues.length) {\n if (${k} in input) {\n payload.issues = payload.issues.concat(${id}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${k}, ...iss.path] : [${k}]\n })));\n }\n }\n \n if (${id}.value === undefined) {\n if (${k} in input) {\n newResult[${k}] = undefined;\n }\n } else {\n newResult[${k}] = ${id}.value;\n }\n \n `);\n }\n else if (!isOptionalIn) {\n doc.write(`\n const ${id}_present = ${k} in input;\n if (${id}.issues.length) {\n payload.issues = payload.issues.concat(${id}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${k}, ...iss.path] : [${k}]\n })));\n }\n if (!${id}_present && !${id}.issues.length) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: undefined,\n path: [${k}]\n });\n }\n\n if (${id}_present) {\n if (${id}.value === undefined) {\n newResult[${k}] = undefined;\n } else {\n newResult[${k}] = ${id}.value;\n }\n }\n\n `);\n }\n else {\n doc.write(`\n if (${id}.issues.length) {\n payload.issues = payload.issues.concat(${id}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${k}, ...iss.path] : [${k}]\n })));\n }\n \n if (${id}.value === undefined) {\n if (${k} in input) {\n newResult[${k}] = undefined;\n }\n } else {\n newResult[${k}] = ${id}.value;\n }\n \n `);\n }\n }\n doc.write(`payload.value = newResult;`);\n doc.write(`return payload;`);\n const fn = doc.compile();\n return (payload, ctx) => fn(shape, payload, ctx);\n };\n let fastpass;\n const isObject = util.isObject;\n const jit = !core.globalConfig.jitless;\n const allowsEval = util.allowsEval;\n const fastEnabled = jit && allowsEval.value; // && !def.catchall;\n const catchall = def.catchall;\n let value;\n inst._zod.parse = (payload, ctx) => {\n value ?? (value = _normalized.value);\n const input = payload.value;\n if (!isObject(input)) {\n payload.issues.push({\n expected: \"object\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {\n // always synchronous\n if (!fastpass)\n fastpass = generateFastpass(def.shape);\n payload = fastpass(payload, ctx);\n if (!catchall)\n return payload;\n return handleCatchall([], input, payload, ctx, value, inst);\n }\n return superParse(payload, ctx);\n };\n});\nfunction handleUnionResults(results, final, inst, ctx) {\n for (const result of results) {\n if (result.issues.length === 0) {\n final.value = result.value;\n return final;\n }\n }\n const nonaborted = results.filter((r) => !util.aborted(r));\n if (nonaborted.length === 1) {\n final.value = nonaborted[0].value;\n return nonaborted[0];\n }\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n });\n return final;\n}\nexport const $ZodUnion = /*@__PURE__*/ core.$constructor(\"$ZodUnion\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"optin\", () => def.options.some((o) => o._zod.optin === \"optional\") ? \"optional\" : undefined);\n util.defineLazy(inst._zod, \"optout\", () => def.options.some((o) => o._zod.optout === \"optional\") ? \"optional\" : undefined);\n util.defineLazy(inst._zod, \"values\", () => {\n if (def.options.every((o) => o._zod.values)) {\n return new Set(def.options.flatMap((option) => Array.from(option._zod.values)));\n }\n return undefined;\n });\n util.defineLazy(inst._zod, \"pattern\", () => {\n if (def.options.every((o) => o._zod.pattern)) {\n const patterns = def.options.map((o) => o._zod.pattern);\n return new RegExp(`^(${patterns.map((p) => util.cleanRegex(p.source)).join(\"|\")})$`);\n }\n return undefined;\n });\n const first = def.options.length === 1 ? def.options[0]._zod.run : null;\n inst._zod.parse = (payload, ctx) => {\n if (first) {\n return first(payload, ctx);\n }\n let async = false;\n const results = [];\n for (const option of def.options) {\n const result = option._zod.run({\n value: payload.value,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n results.push(result);\n async = true;\n }\n else {\n if (result.issues.length === 0)\n return result;\n results.push(result);\n }\n }\n if (!async)\n return handleUnionResults(results, payload, inst, ctx);\n return Promise.all(results).then((results) => {\n return handleUnionResults(results, payload, inst, ctx);\n });\n };\n});\nfunction handleExclusiveUnionResults(results, final, inst, ctx) {\n const successes = results.filter((r) => r.issues.length === 0);\n if (successes.length === 1) {\n final.value = successes[0].value;\n return final;\n }\n if (successes.length === 0) {\n // No matches - same as regular union\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n });\n }\n else {\n // Multiple matches - exclusive union failure\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: [],\n inclusive: false,\n });\n }\n return final;\n}\nexport const $ZodXor = /*@__PURE__*/ core.$constructor(\"$ZodXor\", (inst, def) => {\n $ZodUnion.init(inst, def);\n def.inclusive = false;\n const first = def.options.length === 1 ? def.options[0]._zod.run : null;\n inst._zod.parse = (payload, ctx) => {\n if (first) {\n return first(payload, ctx);\n }\n let async = false;\n const results = [];\n for (const option of def.options) {\n const result = option._zod.run({\n value: payload.value,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n results.push(result);\n async = true;\n }\n else {\n results.push(result);\n }\n }\n if (!async)\n return handleExclusiveUnionResults(results, payload, inst, ctx);\n return Promise.all(results).then((results) => {\n return handleExclusiveUnionResults(results, payload, inst, ctx);\n });\n };\n});\nexport const $ZodDiscriminatedUnion = \n/*@__PURE__*/\ncore.$constructor(\"$ZodDiscriminatedUnion\", (inst, def) => {\n def.inclusive = false;\n $ZodUnion.init(inst, def);\n const _super = inst._zod.parse;\n util.defineLazy(inst._zod, \"propValues\", () => {\n const propValues = {};\n for (const option of def.options) {\n const pv = option._zod.propValues;\n if (!pv || Object.keys(pv).length === 0)\n throw new Error(`Invalid discriminated union option at index \"${def.options.indexOf(option)}\"`);\n for (const [k, v] of Object.entries(pv)) {\n if (!propValues[k])\n propValues[k] = new Set();\n for (const val of v) {\n propValues[k].add(val);\n }\n }\n }\n return propValues;\n });\n const disc = util.cached(() => {\n const opts = def.options;\n const map = new Map();\n for (const o of opts) {\n const values = o._zod.propValues?.[def.discriminator];\n if (!values || values.size === 0)\n throw new Error(`Invalid discriminated union option at index \"${def.options.indexOf(o)}\"`);\n for (const v of values) {\n if (map.has(v)) {\n throw new Error(`Duplicate discriminator value \"${String(v)}\"`);\n }\n map.set(v, o);\n }\n }\n return map;\n });\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!util.isObject(input)) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"object\",\n input,\n inst,\n });\n return payload;\n }\n const opt = disc.value.get(input?.[def.discriminator]);\n if (opt) {\n return opt._zod.run(payload, ctx);\n }\n // Fall back to union matching when the fast discriminator path fails:\n // - explicitly enabled via unionFallback, or\n // - during backward direction (encode), since codec-based discriminators\n // have different values in forward vs backward directions\n if (def.unionFallback || ctx.direction === \"backward\") {\n return _super(payload, ctx);\n }\n // no matching discriminator\n payload.issues.push({\n code: \"invalid_union\",\n errors: [],\n note: \"No matching discriminator\",\n discriminator: def.discriminator,\n options: Array.from(disc.value.keys()),\n input,\n path: [def.discriminator],\n inst,\n });\n return payload;\n };\n});\nexport const $ZodIntersection = /*@__PURE__*/ core.$constructor(\"$ZodIntersection\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n const left = def.left._zod.run({ value: input, issues: [] }, ctx);\n const right = def.right._zod.run({ value: input, issues: [] }, ctx);\n const async = left instanceof Promise || right instanceof Promise;\n if (async) {\n return Promise.all([left, right]).then(([left, right]) => {\n return handleIntersectionResults(payload, left, right);\n });\n }\n return handleIntersectionResults(payload, left, right);\n };\n});\nfunction mergeValues(a, b) {\n // const aType = parse.t(a);\n // const bType = parse.t(b);\n if (a === b) {\n return { valid: true, data: a };\n }\n if (a instanceof Date && b instanceof Date && +a === +b) {\n return { valid: true, data: a };\n }\n if (util.isPlainObject(a) && util.isPlainObject(b)) {\n const bKeys = Object.keys(b);\n const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);\n const newObj = { ...a, ...b };\n for (const key of sharedKeys) {\n const sharedValue = mergeValues(a[key], b[key]);\n if (!sharedValue.valid) {\n return {\n valid: false,\n mergeErrorPath: [key, ...sharedValue.mergeErrorPath],\n };\n }\n newObj[key] = sharedValue.data;\n }\n return { valid: true, data: newObj };\n }\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) {\n return { valid: false, mergeErrorPath: [] };\n }\n const newArray = [];\n for (let index = 0; index < a.length; index++) {\n const itemA = a[index];\n const itemB = b[index];\n const sharedValue = mergeValues(itemA, itemB);\n if (!sharedValue.valid) {\n return {\n valid: false,\n mergeErrorPath: [index, ...sharedValue.mergeErrorPath],\n };\n }\n newArray.push(sharedValue.data);\n }\n return { valid: true, data: newArray };\n }\n return { valid: false, mergeErrorPath: [] };\n}\nfunction handleIntersectionResults(result, left, right) {\n // Track which side(s) report each key as unrecognized\n const unrecKeys = new Map();\n let unrecIssue;\n for (const iss of left.issues) {\n if (iss.code === \"unrecognized_keys\") {\n unrecIssue ?? (unrecIssue = iss);\n for (const k of iss.keys) {\n if (!unrecKeys.has(k))\n unrecKeys.set(k, {});\n unrecKeys.get(k).l = true;\n }\n }\n else {\n result.issues.push(iss);\n }\n }\n for (const iss of right.issues) {\n if (iss.code === \"unrecognized_keys\") {\n for (const k of iss.keys) {\n if (!unrecKeys.has(k))\n unrecKeys.set(k, {});\n unrecKeys.get(k).r = true;\n }\n }\n else {\n result.issues.push(iss);\n }\n }\n // Report only keys unrecognized by BOTH sides\n const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k);\n if (bothKeys.length && unrecIssue) {\n result.issues.push({ ...unrecIssue, keys: bothKeys });\n }\n if (util.aborted(result))\n return result;\n const merged = mergeValues(left.value, right.value);\n if (!merged.valid) {\n throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`);\n }\n result.value = merged.data;\n return result;\n}\nexport const $ZodTuple = /*@__PURE__*/ core.$constructor(\"$ZodTuple\", (inst, def) => {\n $ZodType.init(inst, def);\n const items = def.items;\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!Array.isArray(input)) {\n payload.issues.push({\n input,\n inst,\n expected: \"tuple\",\n code: \"invalid_type\",\n });\n return payload;\n }\n payload.value = [];\n const proms = [];\n const optinStart = getTupleOptStart(items, \"optin\");\n const optoutStart = getTupleOptStart(items, \"optout\");\n if (!def.rest) {\n if (input.length < optinStart) {\n payload.issues.push({\n code: \"too_small\",\n minimum: optinStart,\n inclusive: true,\n input,\n inst,\n origin: \"array\",\n });\n return payload;\n }\n if (input.length > items.length) {\n payload.issues.push({\n code: \"too_big\",\n maximum: items.length,\n inclusive: true,\n input,\n inst,\n origin: \"array\",\n });\n }\n }\n // Run every item in parallel, collecting results into an indexed\n // array. The post-processing in `handleTupleResults` walks them in\n // order so it can decide whether an absent optional-output error can\n // truncate the tail or must be reported to preserve required output.\n const itemResults = new Array(items.length);\n for (let i = 0; i < items.length; i++) {\n const r = items[i]._zod.run({ value: input[i], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((rr) => {\n itemResults[i] = rr;\n }));\n }\n else {\n itemResults[i] = r;\n }\n }\n if (def.rest) {\n let i = items.length - 1;\n const rest = input.slice(items.length);\n for (const el of rest) {\n i++;\n const result = def.rest._zod.run({ value: el, issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((r) => handleTupleResult(r, payload, i)));\n }\n else {\n handleTupleResult(result, payload, i);\n }\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input, optoutStart));\n }\n return handleTupleResults(itemResults, payload, items, input, optoutStart);\n };\n});\nfunction getTupleOptStart(items, key) {\n for (let i = items.length - 1; i >= 0; i--) {\n if (items[i]._zod[key] !== \"optional\")\n return i + 1;\n }\n return 0;\n}\nfunction handleTupleResult(result, final, index) {\n if (result.issues.length) {\n final.issues.push(...util.prefixIssues(index, result.issues));\n }\n final.value[index] = result.value;\n}\nfunction handleTupleResults(itemResults, final, items, input, optoutStart) {\n // Walk results in order. Mirror $ZodObject's swallow-on-absent-optional\n // rule, but only after `optoutStart`: the first index where the output\n // tuple tail can be absent.\n for (let i = 0; i < items.length; i++) {\n const r = itemResults[i];\n const isPresent = i < input.length;\n if (r.issues.length) {\n if (!isPresent && i >= optoutStart) {\n final.value.length = i;\n break;\n }\n final.issues.push(...util.prefixIssues(i, r.issues));\n }\n final.value[i] = r.value;\n }\n // Drop trailing slots that produced `undefined` for absent input\n // (the array analog of an absent optional key on an object). The\n // `i >= input.length` floor is critical: an explicit `undefined`\n // *inside* the input must be preserved even when the schema is\n // optional-out (e.g. `z.string().or(z.undefined())` accepting an\n // explicit undefined value).\n for (let i = final.value.length - 1; i >= input.length; i--) {\n if (items[i]._zod.optout === \"optional\" && final.value[i] === undefined) {\n final.value.length = i;\n }\n else {\n break;\n }\n }\n return final;\n}\nexport const $ZodRecord = /*@__PURE__*/ core.$constructor(\"$ZodRecord\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!util.isPlainObject(input)) {\n payload.issues.push({\n expected: \"record\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n const proms = [];\n const values = def.keyType._zod.values;\n if (values) {\n payload.value = {};\n const recordKeys = new Set();\n for (const key of values) {\n if (typeof key === \"string\" || typeof key === \"number\" || typeof key === \"symbol\") {\n recordKeys.add(typeof key === \"number\" ? key.toString() : key);\n const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n if (keyResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n if (keyResult.issues.length) {\n payload.issues.push({\n code: \"invalid_key\",\n origin: \"record\",\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n input: key,\n path: [key],\n inst,\n });\n continue;\n }\n const outKey = keyResult.value;\n const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[outKey] = result.value;\n }));\n }\n else {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[outKey] = result.value;\n }\n }\n }\n let unrecognized;\n for (const key in input) {\n if (!recordKeys.has(key)) {\n unrecognized = unrecognized ?? [];\n unrecognized.push(key);\n }\n }\n if (unrecognized && unrecognized.length > 0) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n input,\n inst,\n keys: unrecognized,\n });\n }\n }\n else {\n payload.value = {};\n // Reflect.ownKeys for Symbol-key support; filter non-enumerable to match z.object()\n for (const key of Reflect.ownKeys(input)) {\n if (key === \"__proto__\")\n continue;\n if (!Object.prototype.propertyIsEnumerable.call(input, key))\n continue;\n let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n if (keyResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n // Numeric string fallback: if key is a numeric string and failed, retry with Number(key)\n // This handles z.number(), z.literal([1, 2, 3]), and unions containing numeric literals\n const checkNumericKey = typeof key === \"string\" && regexes.number.test(key) && keyResult.issues.length;\n if (checkNumericKey) {\n const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx);\n if (retryResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n if (retryResult.issues.length === 0) {\n keyResult = retryResult;\n }\n }\n if (keyResult.issues.length) {\n if (def.mode === \"loose\") {\n // Pass through unchanged\n payload.value[key] = input[key];\n }\n else {\n // Default \"strict\" behavior: error on invalid key\n payload.issues.push({\n code: \"invalid_key\",\n origin: \"record\",\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n input: key,\n path: [key],\n inst,\n });\n }\n continue;\n }\n const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[keyResult.value] = result.value;\n }));\n }\n else {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[keyResult.value] = result.value;\n }\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => payload);\n }\n return payload;\n };\n});\nexport const $ZodMap = /*@__PURE__*/ core.$constructor(\"$ZodMap\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!(input instanceof Map)) {\n payload.issues.push({\n expected: \"map\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n const proms = [];\n payload.value = new Map();\n for (const [key, value] of input) {\n const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n const valueResult = def.valueType._zod.run({ value: value, issues: [] }, ctx);\n if (keyResult instanceof Promise || valueResult instanceof Promise) {\n proms.push(Promise.all([keyResult, valueResult]).then(([keyResult, valueResult]) => {\n handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);\n }));\n }\n else {\n handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);\n }\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\n});\nfunction handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) {\n if (keyResult.issues.length) {\n if (util.propertyKeyTypes.has(typeof key)) {\n final.issues.push(...util.prefixIssues(key, keyResult.issues));\n }\n else {\n final.issues.push({\n code: \"invalid_key\",\n origin: \"map\",\n input,\n inst,\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n });\n }\n }\n if (valueResult.issues.length) {\n if (util.propertyKeyTypes.has(typeof key)) {\n final.issues.push(...util.prefixIssues(key, valueResult.issues));\n }\n else {\n final.issues.push({\n origin: \"map\",\n code: \"invalid_element\",\n input,\n inst,\n key: key,\n issues: valueResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n });\n }\n }\n final.value.set(keyResult.value, valueResult.value);\n}\nexport const $ZodSet = /*@__PURE__*/ core.$constructor(\"$ZodSet\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!(input instanceof Set)) {\n payload.issues.push({\n input,\n inst,\n expected: \"set\",\n code: \"invalid_type\",\n });\n return payload;\n }\n const proms = [];\n payload.value = new Set();\n for (const item of input) {\n const result = def.valueType._zod.run({ value: item, issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleSetResult(result, payload)));\n }\n else\n handleSetResult(result, payload);\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\n});\nfunction handleSetResult(result, final) {\n if (result.issues.length) {\n final.issues.push(...result.issues);\n }\n final.value.add(result.value);\n}\nexport const $ZodEnum = /*@__PURE__*/ core.$constructor(\"$ZodEnum\", (inst, def) => {\n $ZodType.init(inst, def);\n const values = util.getEnumValues(def.entries);\n const valuesSet = new Set(values);\n inst._zod.values = valuesSet;\n inst._zod.pattern = new RegExp(`^(${values\n .filter((k) => util.propertyKeyTypes.has(typeof k))\n .map((o) => (typeof o === \"string\" ? util.escapeRegex(o) : o.toString()))\n .join(\"|\")})$`);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (valuesSet.has(input)) {\n return payload;\n }\n payload.issues.push({\n code: \"invalid_value\",\n values,\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodLiteral = /*@__PURE__*/ core.$constructor(\"$ZodLiteral\", (inst, def) => {\n $ZodType.init(inst, def);\n if (def.values.length === 0) {\n throw new Error(\"Cannot create literal schema with no valid values\");\n }\n const values = new Set(def.values);\n inst._zod.values = values;\n inst._zod.pattern = new RegExp(`^(${def.values\n .map((o) => (typeof o === \"string\" ? util.escapeRegex(o) : o ? util.escapeRegex(o.toString()) : String(o)))\n .join(\"|\")})$`);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (values.has(input)) {\n return payload;\n }\n payload.issues.push({\n code: \"invalid_value\",\n values: def.values,\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodFile = /*@__PURE__*/ core.$constructor(\"$ZodFile\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n // @ts-ignore\n if (input instanceof File)\n return payload;\n payload.issues.push({\n expected: \"file\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodTransform = /*@__PURE__*/ core.$constructor(\"$ZodTransform\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(inst.constructor.name);\n }\n const _out = def.transform(payload.value, payload);\n if (ctx.async) {\n const output = _out instanceof Promise ? _out : Promise.resolve(_out);\n return output.then((output) => {\n payload.value = output;\n payload.fallback = true;\n return payload;\n });\n }\n if (_out instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n payload.value = _out;\n payload.fallback = true;\n return payload;\n };\n});\nfunction handleOptionalResult(result, input) {\n if (input === undefined && (result.issues.length || result.fallback)) {\n return { issues: [], value: undefined };\n }\n return result;\n}\nexport const $ZodOptional = /*@__PURE__*/ core.$constructor(\"$ZodOptional\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n inst._zod.optout = \"optional\";\n util.defineLazy(inst._zod, \"values\", () => {\n return def.innerType._zod.values ? new Set([...def.innerType._zod.values, undefined]) : undefined;\n });\n util.defineLazy(inst._zod, \"pattern\", () => {\n const pattern = def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)})?$`) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n if (def.innerType._zod.optin === \"optional\") {\n const input = payload.value;\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise)\n return result.then((r) => handleOptionalResult(r, input));\n return handleOptionalResult(result, input);\n }\n if (payload.value === undefined) {\n return payload;\n }\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodExactOptional = /*@__PURE__*/ core.$constructor(\"$ZodExactOptional\", (inst, def) => {\n // Call parent init - inherits optin/optout = \"optional\"\n $ZodOptional.init(inst, def);\n // Override values/pattern to NOT add undefined\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n util.defineLazy(inst._zod, \"pattern\", () => def.innerType._zod.pattern);\n // Override parse to just delegate (no undefined handling)\n inst._zod.parse = (payload, ctx) => {\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodNullable = /*@__PURE__*/ core.$constructor(\"$ZodNullable\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"optin\", () => def.innerType._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.innerType._zod.optout);\n util.defineLazy(inst._zod, \"pattern\", () => {\n const pattern = def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)}|null)$`) : undefined;\n });\n util.defineLazy(inst._zod, \"values\", () => {\n return def.innerType._zod.values ? new Set([...def.innerType._zod.values, null]) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n // Forward direction (decode): allow null to pass through\n if (payload.value === null)\n return payload;\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodDefault = /*@__PURE__*/ core.$constructor(\"$ZodDefault\", (inst, def) => {\n $ZodType.init(inst, def);\n // inst._zod.qin = \"true\";\n inst._zod.optin = \"optional\";\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply defaults for undefined input\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n /**\n * $ZodDefault returns the default value immediately in forward direction.\n * It doesn't pass the default value into the validator (\"prefault\"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a \"prefault\" for the pipe. */\n return payload;\n }\n // Forward direction: continue with default handling\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleDefaultResult(result, def));\n }\n return handleDefaultResult(result, def);\n };\n});\nfunction handleDefaultResult(payload, def) {\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n }\n return payload;\n}\nexport const $ZodPrefault = /*@__PURE__*/ core.$constructor(\"$ZodPrefault\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply prefault for undefined input\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n }\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodNonOptional = /*@__PURE__*/ core.$constructor(\"$ZodNonOptional\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"values\", () => {\n const v = def.innerType._zod.values;\n return v ? new Set([...v].filter((x) => x !== undefined)) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleNonOptionalResult(result, inst));\n }\n return handleNonOptionalResult(result, inst);\n };\n});\nfunction handleNonOptionalResult(payload, inst) {\n if (!payload.issues.length && payload.value === undefined) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: payload.value,\n inst,\n });\n }\n return payload;\n}\nexport const $ZodSuccess = /*@__PURE__*/ core.$constructor(\"$ZodSuccess\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(\"ZodSuccess\");\n }\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => {\n payload.value = result.issues.length === 0;\n return payload;\n });\n }\n payload.value = result.issues.length === 0;\n return payload;\n };\n});\nexport const $ZodCatch = /*@__PURE__*/ core.$constructor(\"$ZodCatch\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n util.defineLazy(inst._zod, \"optout\", () => def.innerType._zod.optout);\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply catch logic\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => {\n payload.value = result.value;\n if (result.issues.length) {\n payload.value = def.catchValue({\n ...payload,\n error: {\n issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n },\n input: payload.value,\n });\n payload.issues = [];\n payload.fallback = true;\n }\n return payload;\n });\n }\n payload.value = result.value;\n if (result.issues.length) {\n payload.value = def.catchValue({\n ...payload,\n error: {\n issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n },\n input: payload.value,\n });\n payload.issues = [];\n payload.fallback = true;\n }\n return payload;\n };\n});\nexport const $ZodNaN = /*@__PURE__*/ core.$constructor(\"$ZodNaN\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"number\" || !Number.isNaN(payload.value)) {\n payload.issues.push({\n input: payload.value,\n inst,\n expected: \"nan\",\n code: \"invalid_type\",\n });\n return payload;\n }\n return payload;\n };\n});\nexport const $ZodPipe = /*@__PURE__*/ core.$constructor(\"$ZodPipe\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"values\", () => def.in._zod.values);\n util.defineLazy(inst._zod, \"optin\", () => def.in._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.out._zod.optout);\n util.defineLazy(inst._zod, \"propValues\", () => def.in._zod.propValues);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n const right = def.out._zod.run(payload, ctx);\n if (right instanceof Promise) {\n return right.then((right) => handlePipeResult(right, def.in, ctx));\n }\n return handlePipeResult(right, def.in, ctx);\n }\n const left = def.in._zod.run(payload, ctx);\n if (left instanceof Promise) {\n return left.then((left) => handlePipeResult(left, def.out, ctx));\n }\n return handlePipeResult(left, def.out, ctx);\n };\n});\nfunction handlePipeResult(left, next, ctx) {\n if (left.issues.length) {\n // prevent further checks\n left.aborted = true;\n return left;\n }\n return next._zod.run({ value: left.value, issues: left.issues, fallback: left.fallback }, ctx);\n}\nexport const $ZodCodec = /*@__PURE__*/ core.$constructor(\"$ZodCodec\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"values\", () => def.in._zod.values);\n util.defineLazy(inst._zod, \"optin\", () => def.in._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.out._zod.optout);\n util.defineLazy(inst._zod, \"propValues\", () => def.in._zod.propValues);\n inst._zod.parse = (payload, ctx) => {\n const direction = ctx.direction || \"forward\";\n if (direction === \"forward\") {\n const left = def.in._zod.run(payload, ctx);\n if (left instanceof Promise) {\n return left.then((left) => handleCodecAResult(left, def, ctx));\n }\n return handleCodecAResult(left, def, ctx);\n }\n else {\n const right = def.out._zod.run(payload, ctx);\n if (right instanceof Promise) {\n return right.then((right) => handleCodecAResult(right, def, ctx));\n }\n return handleCodecAResult(right, def, ctx);\n }\n };\n});\nfunction handleCodecAResult(result, def, ctx) {\n if (result.issues.length) {\n // prevent further checks\n result.aborted = true;\n return result;\n }\n const direction = ctx.direction || \"forward\";\n if (direction === \"forward\") {\n const transformed = def.transform(result.value, result);\n if (transformed instanceof Promise) {\n return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx));\n }\n return handleCodecTxResult(result, transformed, def.out, ctx);\n }\n else {\n const transformed = def.reverseTransform(result.value, result);\n if (transformed instanceof Promise) {\n return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx));\n }\n return handleCodecTxResult(result, transformed, def.in, ctx);\n }\n}\nfunction handleCodecTxResult(left, value, nextSchema, ctx) {\n // Check if transform added any issues\n if (left.issues.length) {\n left.aborted = true;\n return left;\n }\n return nextSchema._zod.run({ value, issues: left.issues }, ctx);\n}\nexport const $ZodPreprocess = /*@__PURE__*/ core.$constructor(\"$ZodPreprocess\", (inst, def) => {\n $ZodPipe.init(inst, def);\n});\nexport const $ZodReadonly = /*@__PURE__*/ core.$constructor(\"$ZodReadonly\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"propValues\", () => def.innerType._zod.propValues);\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n util.defineLazy(inst._zod, \"optin\", () => def.innerType?._zod?.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.innerType?._zod?.optout);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then(handleReadonlyResult);\n }\n return handleReadonlyResult(result);\n };\n});\nfunction handleReadonlyResult(payload) {\n payload.value = Object.freeze(payload.value);\n return payload;\n}\nexport const $ZodTemplateLiteral = /*@__PURE__*/ core.$constructor(\"$ZodTemplateLiteral\", (inst, def) => {\n $ZodType.init(inst, def);\n const regexParts = [];\n for (const part of def.parts) {\n if (typeof part === \"object\" && part !== null) {\n // is Zod schema\n if (!part._zod.pattern) {\n // if (!source)\n throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`);\n }\n const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern;\n if (!source)\n throw new Error(`Invalid template literal part: ${part._zod.traits}`);\n const start = source.startsWith(\"^\") ? 1 : 0;\n const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n regexParts.push(source.slice(start, end));\n }\n else if (part === null || util.primitiveTypes.has(typeof part)) {\n regexParts.push(util.escapeRegex(`${part}`));\n }\n else {\n throw new Error(`Invalid template literal part: ${part}`);\n }\n }\n inst._zod.pattern = new RegExp(`^${regexParts.join(\"\")}$`);\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"string\") {\n payload.issues.push({\n input: payload.value,\n inst,\n expected: \"string\",\n code: \"invalid_type\",\n });\n return payload;\n }\n inst._zod.pattern.lastIndex = 0;\n if (!inst._zod.pattern.test(payload.value)) {\n payload.issues.push({\n input: payload.value,\n inst,\n code: \"invalid_format\",\n format: def.format ?? \"template_literal\",\n pattern: inst._zod.pattern.source,\n });\n return payload;\n }\n return payload;\n };\n});\nexport const $ZodFunction = /*@__PURE__*/ core.$constructor(\"$ZodFunction\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._def = def;\n inst._zod.def = def;\n inst.implement = (func) => {\n if (typeof func !== \"function\") {\n throw new Error(\"implement() must be called with a function\");\n }\n return function (...args) {\n const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args;\n const result = Reflect.apply(func, this, parsedArgs);\n if (inst._def.output) {\n return parse(inst._def.output, result);\n }\n return result;\n };\n };\n inst.implementAsync = (func) => {\n if (typeof func !== \"function\") {\n throw new Error(\"implementAsync() must be called with a function\");\n }\n return async function (...args) {\n const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args;\n const result = await Reflect.apply(func, this, parsedArgs);\n if (inst._def.output) {\n return await parseAsync(inst._def.output, result);\n }\n return result;\n };\n };\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"function\") {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"function\",\n input: payload.value,\n inst,\n });\n return payload;\n }\n // Check if output is a promise type to determine if we should use async implementation\n const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === \"promise\";\n if (hasPromiseOutput) {\n payload.value = inst.implementAsync(payload.value);\n }\n else {\n payload.value = inst.implement(payload.value);\n }\n return payload;\n };\n inst.input = (...args) => {\n const F = inst.constructor;\n if (Array.isArray(args[0])) {\n return new F({\n type: \"function\",\n input: new $ZodTuple({\n type: \"tuple\",\n items: args[0],\n rest: args[1],\n }),\n output: inst._def.output,\n });\n }\n return new F({\n type: \"function\",\n input: args[0],\n output: inst._def.output,\n });\n };\n inst.output = (output) => {\n const F = inst.constructor;\n return new F({\n type: \"function\",\n input: inst._def.input,\n output,\n });\n };\n return inst;\n});\nexport const $ZodPromise = /*@__PURE__*/ core.$constructor(\"$ZodPromise\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx));\n };\n});\nexport const $ZodLazy = /*@__PURE__*/ core.$constructor(\"$ZodLazy\", (inst, def) => {\n $ZodType.init(inst, def);\n // Cache the resolved inner type on the shared `def` so all clones of this\n // lazy (e.g. via `.describe()`/`.meta()`) share the same inner instance,\n // preserving identity for cycle detection on recursive schemas.\n util.defineLazy(inst._zod, \"innerType\", () => {\n const d = def;\n if (!d._cachedInner)\n d._cachedInner = def.getter();\n return d._cachedInner;\n });\n util.defineLazy(inst._zod, \"pattern\", () => inst._zod.innerType?._zod?.pattern);\n util.defineLazy(inst._zod, \"propValues\", () => inst._zod.innerType?._zod?.propValues);\n util.defineLazy(inst._zod, \"optin\", () => inst._zod.innerType?._zod?.optin ?? undefined);\n util.defineLazy(inst._zod, \"optout\", () => inst._zod.innerType?._zod?.optout ?? undefined);\n inst._zod.parse = (payload, ctx) => {\n const inner = inst._zod.innerType;\n return inner._zod.run(payload, ctx);\n };\n});\nexport const $ZodCustom = /*@__PURE__*/ core.$constructor(\"$ZodCustom\", (inst, def) => {\n checks.$ZodCheck.init(inst, def);\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _) => {\n return payload;\n };\n inst._zod.check = (payload) => {\n const input = payload.value;\n const r = def.fn(input);\n if (r instanceof Promise) {\n return r.then((r) => handleRefineResult(r, payload, input, inst));\n }\n handleRefineResult(r, payload, input, inst);\n return;\n };\n});\nfunction handleRefineResult(result, payload, input, inst) {\n if (!result) {\n const _iss = {\n code: \"custom\",\n input,\n inst, // incorporates params.error into issue reporting\n path: [...(inst._zod.def.path ?? [])], // incorporates params.error into issue reporting\n continue: !inst._zod.def.abort,\n // params: inst._zod.def.params,\n };\n if (inst._zod.def.params)\n _iss.params = inst._zod.def.params;\n payload.issues.push(util.issue(_iss));\n }\n}\n","import * as checks from \"./checks.js\";\nimport * as registries from \"./registries.js\";\nimport * as schemas from \"./schemas.js\";\nimport * as util from \"./util.js\";\n// @__NO_SIDE_EFFECTS__\nexport function _string(Class, params) {\n return new Class({\n type: \"string\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedString(Class, params) {\n return new Class({\n type: \"string\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _email(Class, params) {\n return new Class({\n type: \"string\",\n format: \"email\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _guid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"guid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v4\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v6\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv7(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v7\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _url(Class, params) {\n return new Class({\n type: \"string\",\n format: \"url\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _emoji(Class, params) {\n return new Class({\n type: \"string\",\n format: \"emoji\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nanoid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"nanoid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link _cuid2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\n// @__NO_SIDE_EFFECTS__\nexport function _cuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cuid2(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cuid2\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ulid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ulid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _xid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"xid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ksuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ksuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ipv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ipv4\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ipv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ipv6\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _mac(Class, params) {\n return new Class({\n type: \"string\",\n format: \"mac\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cidrv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cidrv4\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cidrv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cidrv6\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _base64(Class, params) {\n return new Class({\n type: \"string\",\n format: \"base64\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _base64url(Class, params) {\n return new Class({\n type: \"string\",\n format: \"base64url\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _e164(Class, params) {\n return new Class({\n type: \"string\",\n format: \"e164\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _jwt(Class, params) {\n return new Class({\n type: \"string\",\n format: \"jwt\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport const TimePrecision = {\n Any: null,\n Minute: -1,\n Second: 0,\n Millisecond: 3,\n Microsecond: 6,\n};\n// @__NO_SIDE_EFFECTS__\nexport function _isoDateTime(Class, params) {\n return new Class({\n type: \"string\",\n format: \"datetime\",\n check: \"string_format\",\n offset: false,\n local: false,\n precision: null,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoDate(Class, params) {\n return new Class({\n type: \"string\",\n format: \"date\",\n check: \"string_format\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoTime(Class, params) {\n return new Class({\n type: \"string\",\n format: \"time\",\n check: \"string_format\",\n precision: null,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoDuration(Class, params) {\n return new Class({\n type: \"string\",\n format: \"duration\",\n check: \"string_format\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _number(Class, params) {\n return new Class({\n type: \"number\",\n checks: [],\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedNumber(Class, params) {\n return new Class({\n type: \"number\",\n coerce: true,\n checks: [],\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"safeint\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _float32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"float32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _float64(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"float64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"int32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uint32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"uint32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _boolean(Class, params) {\n return new Class({\n type: \"boolean\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedBoolean(Class, params) {\n return new Class({\n type: \"boolean\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _bigint(Class, params) {\n return new Class({\n type: \"bigint\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedBigint(Class, params) {\n return new Class({\n type: \"bigint\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int64(Class, params) {\n return new Class({\n type: \"bigint\",\n check: \"bigint_format\",\n abort: false,\n format: \"int64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uint64(Class, params) {\n return new Class({\n type: \"bigint\",\n check: \"bigint_format\",\n abort: false,\n format: \"uint64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _symbol(Class, params) {\n return new Class({\n type: \"symbol\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _undefined(Class, params) {\n return new Class({\n type: \"undefined\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _null(Class, params) {\n return new Class({\n type: \"null\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _any(Class) {\n return new Class({\n type: \"any\",\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _unknown(Class) {\n return new Class({\n type: \"unknown\",\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _never(Class, params) {\n return new Class({\n type: \"never\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _void(Class, params) {\n return new Class({\n type: \"void\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _date(Class, params) {\n return new Class({\n type: \"date\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedDate(Class, params) {\n return new Class({\n type: \"date\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nan(Class, params) {\n return new Class({\n type: \"nan\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lt(value, params) {\n return new checks.$ZodCheckLessThan({\n check: \"less_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: false,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lte(value, params) {\n return new checks.$ZodCheckLessThan({\n check: \"less_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: true,\n });\n}\nexport { \n/** @deprecated Use `z.lte()` instead. */\n_lte as _max, };\n// @__NO_SIDE_EFFECTS__\nexport function _gt(value, params) {\n return new checks.$ZodCheckGreaterThan({\n check: \"greater_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: false,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _gte(value, params) {\n return new checks.$ZodCheckGreaterThan({\n check: \"greater_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: true,\n });\n}\nexport { \n/** @deprecated Use `z.gte()` instead. */\n_gte as _min, };\n// @__NO_SIDE_EFFECTS__\nexport function _positive(params) {\n return _gt(0, params);\n}\n// negative\n// @__NO_SIDE_EFFECTS__\nexport function _negative(params) {\n return _lt(0, params);\n}\n// nonpositive\n// @__NO_SIDE_EFFECTS__\nexport function _nonpositive(params) {\n return _lte(0, params);\n}\n// nonnegative\n// @__NO_SIDE_EFFECTS__\nexport function _nonnegative(params) {\n return _gte(0, params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function _multipleOf(value, params) {\n return new checks.$ZodCheckMultipleOf({\n check: \"multiple_of\",\n ...util.normalizeParams(params),\n value,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _maxSize(maximum, params) {\n return new checks.$ZodCheckMaxSize({\n check: \"max_size\",\n ...util.normalizeParams(params),\n maximum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _minSize(minimum, params) {\n return new checks.$ZodCheckMinSize({\n check: \"min_size\",\n ...util.normalizeParams(params),\n minimum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _size(size, params) {\n return new checks.$ZodCheckSizeEquals({\n check: \"size_equals\",\n ...util.normalizeParams(params),\n size,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _maxLength(maximum, params) {\n const ch = new checks.$ZodCheckMaxLength({\n check: \"max_length\",\n ...util.normalizeParams(params),\n maximum,\n });\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _minLength(minimum, params) {\n return new checks.$ZodCheckMinLength({\n check: \"min_length\",\n ...util.normalizeParams(params),\n minimum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _length(length, params) {\n return new checks.$ZodCheckLengthEquals({\n check: \"length_equals\",\n ...util.normalizeParams(params),\n length,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _regex(pattern, params) {\n return new checks.$ZodCheckRegex({\n check: \"string_format\",\n format: \"regex\",\n ...util.normalizeParams(params),\n pattern,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lowercase(params) {\n return new checks.$ZodCheckLowerCase({\n check: \"string_format\",\n format: \"lowercase\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uppercase(params) {\n return new checks.$ZodCheckUpperCase({\n check: \"string_format\",\n format: \"uppercase\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _includes(includes, params) {\n return new checks.$ZodCheckIncludes({\n check: \"string_format\",\n format: \"includes\",\n ...util.normalizeParams(params),\n includes,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _startsWith(prefix, params) {\n return new checks.$ZodCheckStartsWith({\n check: \"string_format\",\n format: \"starts_with\",\n ...util.normalizeParams(params),\n prefix,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _endsWith(suffix, params) {\n return new checks.$ZodCheckEndsWith({\n check: \"string_format\",\n format: \"ends_with\",\n ...util.normalizeParams(params),\n suffix,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _property(property, schema, params) {\n return new checks.$ZodCheckProperty({\n check: \"property\",\n property,\n schema,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _mime(types, params) {\n return new checks.$ZodCheckMimeType({\n check: \"mime_type\",\n mime: types,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _overwrite(tx) {\n return new checks.$ZodCheckOverwrite({\n check: \"overwrite\",\n tx,\n });\n}\n// normalize\n// @__NO_SIDE_EFFECTS__\nexport function _normalize(form) {\n return _overwrite((input) => input.normalize(form));\n}\n// trim\n// @__NO_SIDE_EFFECTS__\nexport function _trim() {\n return _overwrite((input) => input.trim());\n}\n// toLowerCase\n// @__NO_SIDE_EFFECTS__\nexport function _toLowerCase() {\n return _overwrite((input) => input.toLowerCase());\n}\n// toUpperCase\n// @__NO_SIDE_EFFECTS__\nexport function _toUpperCase() {\n return _overwrite((input) => input.toUpperCase());\n}\n// slugify\n// @__NO_SIDE_EFFECTS__\nexport function _slugify() {\n return _overwrite((input) => util.slugify(input));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _array(Class, element, params) {\n return new Class({\n type: \"array\",\n element,\n // get element() {\n // return element;\n // },\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _union(Class, options, params) {\n return new Class({\n type: \"union\",\n options,\n ...util.normalizeParams(params),\n });\n}\nexport function _xor(Class, options, params) {\n return new Class({\n type: \"union\",\n options,\n inclusive: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _discriminatedUnion(Class, discriminator, options, params) {\n return new Class({\n type: \"union\",\n options,\n discriminator,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _intersection(Class, left, right) {\n return new Class({\n type: \"intersection\",\n left,\n right,\n });\n}\n// export function _tuple(\n// Class: util.SchemaClass<schemas.$ZodTuple>,\n// items: [],\n// params?: string | $ZodTupleParams\n// ): schemas.$ZodTuple<[], null>;\n// @__NO_SIDE_EFFECTS__\nexport function _tuple(Class, items, _paramsOrRest, _params) {\n const hasRest = _paramsOrRest instanceof schemas.$ZodType;\n const params = hasRest ? _params : _paramsOrRest;\n const rest = hasRest ? _paramsOrRest : null;\n return new Class({\n type: \"tuple\",\n items,\n rest,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _record(Class, keyType, valueType, params) {\n return new Class({\n type: \"record\",\n keyType,\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _map(Class, keyType, valueType, params) {\n return new Class({\n type: \"map\",\n keyType,\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _set(Class, valueType, params) {\n return new Class({\n type: \"set\",\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _enum(Class, values, params) {\n const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;\n // if (Array.isArray(values)) {\n // for (const value of values) {\n // entries[value] = value;\n // }\n // } else {\n // Object.assign(entries, values);\n // }\n // const entries: util.EnumLike = {};\n // for (const val of values) {\n // entries[val] = val;\n // }\n return new Class({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\n/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.\n *\n * ```ts\n * enum Colors { red, green, blue }\n * z.enum(Colors);\n * ```\n */\nexport function _nativeEnum(Class, entries, params) {\n return new Class({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _literal(Class, value, params) {\n return new Class({\n type: \"literal\",\n values: Array.isArray(value) ? value : [value],\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _file(Class, params) {\n return new Class({\n type: \"file\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _transform(Class, fn) {\n return new Class({\n type: \"transform\",\n transform: fn,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _optional(Class, innerType) {\n return new Class({\n type: \"optional\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nullable(Class, innerType) {\n return new Class({\n type: \"nullable\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _default(Class, innerType, defaultValue) {\n return new Class({\n type: \"default\",\n innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nonoptional(Class, innerType, params) {\n return new Class({\n type: \"nonoptional\",\n innerType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _success(Class, innerType) {\n return new Class({\n type: \"success\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _catch(Class, innerType, catchValue) {\n return new Class({\n type: \"catch\",\n innerType,\n catchValue: (typeof catchValue === \"function\" ? catchValue : () => catchValue),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _pipe(Class, in_, out) {\n return new Class({\n type: \"pipe\",\n in: in_,\n out,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _readonly(Class, innerType) {\n return new Class({\n type: \"readonly\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _templateLiteral(Class, parts, params) {\n return new Class({\n type: \"template_literal\",\n parts,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lazy(Class, getter) {\n return new Class({\n type: \"lazy\",\n getter,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _promise(Class, innerType) {\n return new Class({\n type: \"promise\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _custom(Class, fn, _params) {\n const norm = util.normalizeParams(_params);\n norm.abort ?? (norm.abort = true); // default to abort:false\n const schema = new Class({\n type: \"custom\",\n check: \"custom\",\n fn: fn,\n ...norm,\n });\n return schema;\n}\n// same as _custom but defaults to abort:false\n// @__NO_SIDE_EFFECTS__\nexport function _refine(Class, fn, _params) {\n const schema = new Class({\n type: \"custom\",\n check: \"custom\",\n fn: fn,\n ...util.normalizeParams(_params),\n });\n return schema;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _superRefine(fn, params) {\n const ch = _check((payload) => {\n payload.addIssue = (issue) => {\n if (typeof issue === \"string\") {\n payload.issues.push(util.issue(issue, payload.value, ch._zod.def));\n }\n else {\n // for Zod 3 backwards compatibility\n const _issue = issue;\n if (_issue.fatal)\n _issue.continue = false;\n _issue.code ?? (_issue.code = \"custom\");\n _issue.input ?? (_issue.input = payload.value);\n _issue.inst ?? (_issue.inst = ch);\n _issue.continue ?? (_issue.continue = !ch._zod.def.abort); // abort is always undefined, so this is always true...\n payload.issues.push(util.issue(_issue));\n }\n };\n return fn(payload.value, payload);\n }, params);\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _check(fn, params) {\n const ch = new checks.$ZodCheck({\n check: \"custom\",\n ...util.normalizeParams(params),\n });\n ch._zod.check = fn;\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function describe(description) {\n const ch = new checks.$ZodCheck({ check: \"describe\" });\n ch._zod.onattach = [\n (inst) => {\n const existing = registries.globalRegistry.get(inst) ?? {};\n registries.globalRegistry.add(inst, { ...existing, description });\n },\n ];\n ch._zod.check = () => { }; // no-op check\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function meta(metadata) {\n const ch = new checks.$ZodCheck({ check: \"meta\" });\n ch._zod.onattach = [\n (inst) => {\n const existing = registries.globalRegistry.get(inst) ?? {};\n registries.globalRegistry.add(inst, { ...existing, ...metadata });\n },\n ];\n ch._zod.check = () => { }; // no-op check\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _stringbool(Classes, _params) {\n const params = util.normalizeParams(_params);\n let truthyArray = params.truthy ?? [\"true\", \"1\", \"yes\", \"on\", \"y\", \"enabled\"];\n let falsyArray = params.falsy ?? [\"false\", \"0\", \"no\", \"off\", \"n\", \"disabled\"];\n if (params.case !== \"sensitive\") {\n truthyArray = truthyArray.map((v) => (typeof v === \"string\" ? v.toLowerCase() : v));\n falsyArray = falsyArray.map((v) => (typeof v === \"string\" ? v.toLowerCase() : v));\n }\n const truthySet = new Set(truthyArray);\n const falsySet = new Set(falsyArray);\n const _Codec = Classes.Codec ?? schemas.$ZodCodec;\n const _Boolean = Classes.Boolean ?? schemas.$ZodBoolean;\n const _String = Classes.String ?? schemas.$ZodString;\n const stringSchema = new _String({ type: \"string\", error: params.error });\n const booleanSchema = new _Boolean({ type: \"boolean\", error: params.error });\n const codec = new _Codec({\n type: \"pipe\",\n in: stringSchema,\n out: booleanSchema,\n transform: ((input, payload) => {\n let data = input;\n if (params.case !== \"sensitive\")\n data = data.toLowerCase();\n if (truthySet.has(data)) {\n return true;\n }\n else if (falsySet.has(data)) {\n return false;\n }\n else {\n payload.issues.push({\n code: \"invalid_value\",\n expected: \"stringbool\",\n values: [...truthySet, ...falsySet],\n input: payload.value,\n inst: codec,\n continue: false,\n });\n return {};\n }\n }),\n reverseTransform: ((input, _payload) => {\n if (input === true) {\n return truthyArray[0] || \"true\";\n }\n else {\n return falsyArray[0] || \"false\";\n }\n }),\n error: params.error,\n });\n return codec;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _stringFormat(Class, format, fnOrRegex, _params = {}) {\n const params = util.normalizeParams(_params);\n const def = {\n ...util.normalizeParams(_params),\n check: \"string_format\",\n type: \"string\",\n format,\n fn: typeof fnOrRegex === \"function\" ? fnOrRegex : (val) => fnOrRegex.test(val),\n ...params,\n };\n if (fnOrRegex instanceof RegExp) {\n def.pattern = fnOrRegex;\n }\n const inst = new Class(def);\n return inst;\n}\n","import * as core from \"../core/index.js\";\nimport * as util from \"../core/util.js\";\nimport * as parse from \"./parse.js\";\nexport const ZodMiniType = /*@__PURE__*/ core.$constructor(\"ZodMiniType\", (inst, def) => {\n if (!inst._zod)\n throw new Error(\"Uninitialized schema in ZodMiniType.\");\n core.$ZodType.init(inst, def);\n inst.def = def;\n inst.type = def.type;\n inst.parse = (data, params) => parse.parse(inst, data, params, { callee: inst.parse });\n inst.safeParse = (data, params) => parse.safeParse(inst, data, params);\n inst.parseAsync = async (data, params) => parse.parseAsync(inst, data, params, { callee: inst.parseAsync });\n inst.safeParseAsync = async (data, params) => parse.safeParseAsync(inst, data, params);\n inst.check = (...checks) => {\n return inst.clone({\n ...def,\n checks: [\n ...(def.checks ?? []),\n ...checks.map((ch) => typeof ch === \"function\"\n ? {\n _zod: { check: ch, def: { check: \"custom\" }, onattach: [] },\n }\n : ch),\n ],\n }, { parent: true });\n };\n inst.with = inst.check;\n inst.clone = (_def, params) => core.clone(inst, _def, params);\n inst.brand = () => inst;\n inst.register = ((reg, meta) => {\n reg.add(inst, meta);\n return inst;\n });\n inst.apply = (fn) => fn(inst);\n});\nexport const ZodMiniString = /*@__PURE__*/ core.$constructor(\"ZodMiniString\", (inst, def) => {\n core.$ZodString.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function string(params) {\n return core._string(ZodMiniString, params);\n}\nexport const ZodMiniStringFormat = /*@__PURE__*/ core.$constructor(\"ZodMiniStringFormat\", (inst, def) => {\n core.$ZodStringFormat.init(inst, def);\n ZodMiniString.init(inst, def);\n});\nexport const ZodMiniEmail = /*@__PURE__*/ core.$constructor(\"ZodMiniEmail\", (inst, def) => {\n core.$ZodEmail.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function email(params) {\n return core._email(ZodMiniEmail, params);\n}\nexport const ZodMiniGUID = /*@__PURE__*/ core.$constructor(\"ZodMiniGUID\", (inst, def) => {\n core.$ZodGUID.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function guid(params) {\n return core._guid(ZodMiniGUID, params);\n}\nexport const ZodMiniUUID = /*@__PURE__*/ core.$constructor(\"ZodMiniUUID\", (inst, def) => {\n core.$ZodUUID.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function uuid(params) {\n return core._uuid(ZodMiniUUID, params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function uuidv4(params) {\n return core._uuidv4(ZodMiniUUID, params);\n}\n// ZodMiniUUIDv6\n// @__NO_SIDE_EFFECTS__\nexport function uuidv6(params) {\n return core._uuidv6(ZodMiniUUID, params);\n}\n// ZodMiniUUIDv7\n// @__NO_SIDE_EFFECTS__\nexport function uuidv7(params) {\n return core._uuidv7(ZodMiniUUID, params);\n}\nexport const ZodMiniURL = /*@__PURE__*/ core.$constructor(\"ZodMiniURL\", (inst, def) => {\n core.$ZodURL.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function url(params) {\n return core._url(ZodMiniURL, params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function httpUrl(params) {\n return core._url(ZodMiniURL, {\n protocol: core.regexes.httpProtocol,\n hostname: core.regexes.domain,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniEmoji = /*@__PURE__*/ core.$constructor(\"ZodMiniEmoji\", (inst, def) => {\n core.$ZodEmoji.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function emoji(params) {\n return core._emoji(ZodMiniEmoji, params);\n}\nexport const ZodMiniNanoID = /*@__PURE__*/ core.$constructor(\"ZodMiniNanoID\", (inst, def) => {\n core.$ZodNanoID.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function nanoid(params) {\n return core._nanoid(ZodMiniNanoID, params);\n}\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link ZodMiniCUID2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const ZodMiniCUID = /*@__PURE__*/ core.$constructor(\"ZodMiniCUID\", (inst, def) => {\n core.$ZodCUID.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n/**\n * Validates a CUID v1 string.\n *\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link cuid2 | `z.cuid2()`} instead.\n * See https://github.com/paralleldrive/cuid.\n */\n// @__NO_SIDE_EFFECTS__\nexport function cuid(params) {\n return core._cuid(ZodMiniCUID, params);\n}\nexport const ZodMiniCUID2 = /*@__PURE__*/ core.$constructor(\"ZodMiniCUID2\", (inst, def) => {\n core.$ZodCUID2.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function cuid2(params) {\n return core._cuid2(ZodMiniCUID2, params);\n}\nexport const ZodMiniULID = /*@__PURE__*/ core.$constructor(\"ZodMiniULID\", (inst, def) => {\n core.$ZodULID.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function ulid(params) {\n return core._ulid(ZodMiniULID, params);\n}\nexport const ZodMiniXID = /*@__PURE__*/ core.$constructor(\"ZodMiniXID\", (inst, def) => {\n core.$ZodXID.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function xid(params) {\n return core._xid(ZodMiniXID, params);\n}\nexport const ZodMiniKSUID = /*@__PURE__*/ core.$constructor(\"ZodMiniKSUID\", (inst, def) => {\n core.$ZodKSUID.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function ksuid(params) {\n return core._ksuid(ZodMiniKSUID, params);\n}\nexport const ZodMiniIPv4 = /*@__PURE__*/ core.$constructor(\"ZodMiniIPv4\", (inst, def) => {\n core.$ZodIPv4.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function ipv4(params) {\n return core._ipv4(ZodMiniIPv4, params);\n}\nexport const ZodMiniIPv6 = /*@__PURE__*/ core.$constructor(\"ZodMiniIPv6\", (inst, def) => {\n core.$ZodIPv6.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function ipv6(params) {\n return core._ipv6(ZodMiniIPv6, params);\n}\nexport const ZodMiniCIDRv4 = /*@__PURE__*/ core.$constructor(\"ZodMiniCIDRv4\", (inst, def) => {\n core.$ZodCIDRv4.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function cidrv4(params) {\n return core._cidrv4(ZodMiniCIDRv4, params);\n}\nexport const ZodMiniCIDRv6 = /*@__PURE__*/ core.$constructor(\"ZodMiniCIDRv6\", (inst, def) => {\n core.$ZodCIDRv6.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function cidrv6(params) {\n return core._cidrv6(ZodMiniCIDRv6, params);\n}\nexport const ZodMiniMAC = /*@__PURE__*/ core.$constructor(\"ZodMiniMAC\", (inst, def) => {\n core.$ZodMAC.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function mac(params) {\n return core._mac(ZodMiniMAC, params);\n}\nexport const ZodMiniBase64 = /*@__PURE__*/ core.$constructor(\"ZodMiniBase64\", (inst, def) => {\n core.$ZodBase64.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function base64(params) {\n return core._base64(ZodMiniBase64, params);\n}\nexport const ZodMiniBase64URL = /*@__PURE__*/ core.$constructor(\"ZodMiniBase64URL\", (inst, def) => {\n core.$ZodBase64URL.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function base64url(params) {\n return core._base64url(ZodMiniBase64URL, params);\n}\nexport const ZodMiniE164 = /*@__PURE__*/ core.$constructor(\"ZodMiniE164\", (inst, def) => {\n core.$ZodE164.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function e164(params) {\n return core._e164(ZodMiniE164, params);\n}\nexport const ZodMiniJWT = /*@__PURE__*/ core.$constructor(\"ZodMiniJWT\", (inst, def) => {\n core.$ZodJWT.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function jwt(params) {\n return core._jwt(ZodMiniJWT, params);\n}\nexport const ZodMiniCustomStringFormat = /*@__PURE__*/ core.$constructor(\"ZodMiniCustomStringFormat\", (inst, def) => {\n core.$ZodCustomStringFormat.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function stringFormat(format, fnOrRegex, _params = {}) {\n return core._stringFormat(ZodMiniCustomStringFormat, format, fnOrRegex, _params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function hostname(_params) {\n return core._stringFormat(ZodMiniCustomStringFormat, \"hostname\", core.regexes.hostname, _params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function hex(_params) {\n return core._stringFormat(ZodMiniCustomStringFormat, \"hex\", core.regexes.hex, _params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function hash(alg, params) {\n const enc = params?.enc ?? \"hex\";\n const format = `${alg}_${enc}`;\n const regex = core.regexes[format];\n // check for unrecognized format\n if (!regex)\n throw new Error(`Unrecognized hash format: ${format}`);\n return core._stringFormat(ZodMiniCustomStringFormat, format, regex, params);\n}\nexport const ZodMiniNumber = /*@__PURE__*/ core.$constructor(\"ZodMiniNumber\", (inst, def) => {\n core.$ZodNumber.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function number(params) {\n return core._number(ZodMiniNumber, params);\n}\nexport const ZodMiniNumberFormat = /*@__PURE__*/ core.$constructor(\"ZodMiniNumberFormat\", (inst, def) => {\n core.$ZodNumberFormat.init(inst, def);\n ZodMiniNumber.init(inst, def);\n});\n// int\n// @__NO_SIDE_EFFECTS__\nexport function int(params) {\n return core._int(ZodMiniNumberFormat, params);\n}\n// float32\n// @__NO_SIDE_EFFECTS__\nexport function float32(params) {\n return core._float32(ZodMiniNumberFormat, params);\n}\n// float64\n// @__NO_SIDE_EFFECTS__\nexport function float64(params) {\n return core._float64(ZodMiniNumberFormat, params);\n}\n// int32\n// @__NO_SIDE_EFFECTS__\nexport function int32(params) {\n return core._int32(ZodMiniNumberFormat, params);\n}\n// uint32\n// @__NO_SIDE_EFFECTS__\nexport function uint32(params) {\n return core._uint32(ZodMiniNumberFormat, params);\n}\nexport const ZodMiniBoolean = /*@__PURE__*/ core.$constructor(\"ZodMiniBoolean\", (inst, def) => {\n core.$ZodBoolean.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function boolean(params) {\n return core._boolean(ZodMiniBoolean, params);\n}\nexport const ZodMiniBigInt = /*@__PURE__*/ core.$constructor(\"ZodMiniBigInt\", (inst, def) => {\n core.$ZodBigInt.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function bigint(params) {\n return core._bigint(ZodMiniBigInt, params);\n}\nexport const ZodMiniBigIntFormat = /*@__PURE__*/ core.$constructor(\"ZodMiniBigIntFormat\", (inst, def) => {\n core.$ZodBigIntFormat.init(inst, def);\n ZodMiniBigInt.init(inst, def);\n});\n// int64\n// @__NO_SIDE_EFFECTS__\nexport function int64(params) {\n return core._int64(ZodMiniBigIntFormat, params);\n}\n// uint64\n// @__NO_SIDE_EFFECTS__\nexport function uint64(params) {\n return core._uint64(ZodMiniBigIntFormat, params);\n}\nexport const ZodMiniSymbol = /*@__PURE__*/ core.$constructor(\"ZodMiniSymbol\", (inst, def) => {\n core.$ZodSymbol.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function symbol(params) {\n return core._symbol(ZodMiniSymbol, params);\n}\nexport const ZodMiniUndefined = /*@__PURE__*/ core.$constructor(\"ZodMiniUndefined\", (inst, def) => {\n core.$ZodUndefined.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nfunction _undefined(params) {\n return core._undefined(ZodMiniUndefined, params);\n}\nexport { _undefined as undefined };\nexport const ZodMiniNull = /*@__PURE__*/ core.$constructor(\"ZodMiniNull\", (inst, def) => {\n core.$ZodNull.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nfunction _null(params) {\n return core._null(ZodMiniNull, params);\n}\nexport { _null as null };\nexport const ZodMiniAny = /*@__PURE__*/ core.$constructor(\"ZodMiniAny\", (inst, def) => {\n core.$ZodAny.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function any() {\n return core._any(ZodMiniAny);\n}\nexport const ZodMiniUnknown = /*@__PURE__*/ core.$constructor(\"ZodMiniUnknown\", (inst, def) => {\n core.$ZodUnknown.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function unknown() {\n return core._unknown(ZodMiniUnknown);\n}\nexport const ZodMiniNever = /*@__PURE__*/ core.$constructor(\"ZodMiniNever\", (inst, def) => {\n core.$ZodNever.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function never(params) {\n return core._never(ZodMiniNever, params);\n}\nexport const ZodMiniVoid = /*@__PURE__*/ core.$constructor(\"ZodMiniVoid\", (inst, def) => {\n core.$ZodVoid.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nfunction _void(params) {\n return core._void(ZodMiniVoid, params);\n}\nexport { _void as void };\nexport const ZodMiniDate = /*@__PURE__*/ core.$constructor(\"ZodMiniDate\", (inst, def) => {\n core.$ZodDate.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function date(params) {\n return core._date(ZodMiniDate, params);\n}\nexport const ZodMiniArray = /*@__PURE__*/ core.$constructor(\"ZodMiniArray\", (inst, def) => {\n core.$ZodArray.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function array(element, params) {\n return new ZodMiniArray({\n type: \"array\",\n element: element,\n ...util.normalizeParams(params),\n });\n}\n// .keyof\n// @__NO_SIDE_EFFECTS__\nexport function keyof(schema) {\n const shape = schema._zod.def.shape;\n return _enum(Object.keys(shape));\n}\nexport const ZodMiniObject = /*@__PURE__*/ core.$constructor(\"ZodMiniObject\", (inst, def) => {\n core.$ZodObject.init(inst, def);\n ZodMiniType.init(inst, def);\n util.defineLazy(inst, \"shape\", () => def.shape);\n});\n// @__NO_SIDE_EFFECTS__\nexport function object(shape, params) {\n const def = {\n type: \"object\",\n shape: shape ?? {},\n ...util.normalizeParams(params),\n };\n return new ZodMiniObject(def);\n}\n// strictObject\n// @__NO_SIDE_EFFECTS__\nexport function strictObject(shape, params) {\n return new ZodMiniObject({\n type: \"object\",\n shape,\n catchall: never(),\n ...util.normalizeParams(params),\n });\n}\n// looseObject\n// @__NO_SIDE_EFFECTS__\nexport function looseObject(shape, params) {\n return new ZodMiniObject({\n type: \"object\",\n shape,\n catchall: unknown(),\n ...util.normalizeParams(params),\n });\n}\n// object methods\n// @__NO_SIDE_EFFECTS__\nexport function extend(schema, shape) {\n return util.extend(schema, shape);\n}\n// @__NO_SIDE_EFFECTS__\nexport function safeExtend(schema, shape) {\n return util.safeExtend(schema, shape);\n}\n// @__NO_SIDE_EFFECTS__\nexport function merge(schema, shape) {\n return util.extend(schema, shape);\n}\n// @__NO_SIDE_EFFECTS__\nexport function pick(schema, mask) {\n return util.pick(schema, mask);\n}\n// .omit\n// @__NO_SIDE_EFFECTS__\nexport function omit(schema, mask) {\n return util.omit(schema, mask);\n}\n// @__NO_SIDE_EFFECTS__\nexport function partial(schema, mask) {\n return util.partial(ZodMiniOptional, schema, mask);\n}\n// @__NO_SIDE_EFFECTS__\nexport function required(schema, mask) {\n return util.required(ZodMiniNonOptional, schema, mask);\n}\n// @__NO_SIDE_EFFECTS__\nexport function catchall(inst, catchall) {\n return inst.clone({ ...inst._zod.def, catchall: catchall });\n}\nexport const ZodMiniUnion = /*@__PURE__*/ core.$constructor(\"ZodMiniUnion\", (inst, def) => {\n core.$ZodUnion.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function union(options, params) {\n return new ZodMiniUnion({\n type: \"union\",\n options: options,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniXor = /*@__PURE__*/ core.$constructor(\"ZodMiniXor\", (inst, def) => {\n ZodMiniUnion.init(inst, def);\n core.$ZodXor.init(inst, def);\n});\n/** Creates an exclusive union (XOR) where exactly one option must match.\n * Unlike regular unions that succeed when any option matches, xor fails if\n * zero or more than one option matches the input. */\nexport function xor(options, params) {\n return new ZodMiniXor({\n type: \"union\",\n options: options,\n inclusive: false,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniDiscriminatedUnion = /*@__PURE__*/ core.$constructor(\"ZodMiniDiscriminatedUnion\", (inst, def) => {\n core.$ZodDiscriminatedUnion.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function discriminatedUnion(discriminator, options, params) {\n return new ZodMiniDiscriminatedUnion({\n type: \"union\",\n options,\n discriminator,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniIntersection = /*@__PURE__*/ core.$constructor(\"ZodMiniIntersection\", (inst, def) => {\n core.$ZodIntersection.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function intersection(left, right) {\n return new ZodMiniIntersection({\n type: \"intersection\",\n left: left,\n right: right,\n });\n}\nexport const ZodMiniTuple = /*@__PURE__*/ core.$constructor(\"ZodMiniTuple\", (inst, def) => {\n core.$ZodTuple.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function tuple(items, _paramsOrRest, _params) {\n const hasRest = _paramsOrRest instanceof core.$ZodType;\n const params = hasRest ? _params : _paramsOrRest;\n const rest = hasRest ? _paramsOrRest : null;\n return new ZodMiniTuple({\n type: \"tuple\",\n items: items,\n rest,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniRecord = /*@__PURE__*/ core.$constructor(\"ZodMiniRecord\", (inst, def) => {\n core.$ZodRecord.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function record(keyType, valueType, params) {\n // v3-compat: z.record(valueType, params?) — defaults keyType to z.string()\n if (!valueType || !valueType._zod) {\n return new ZodMiniRecord({\n type: \"record\",\n keyType: string(),\n valueType: keyType,\n ...util.normalizeParams(valueType),\n });\n }\n return new ZodMiniRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function partialRecord(keyType, valueType, params) {\n const k = core.clone(keyType);\n k._zod.values = undefined;\n return new ZodMiniRecord({\n type: \"record\",\n keyType: k,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport function looseRecord(keyType, valueType, params) {\n return new ZodMiniRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n mode: \"loose\",\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniMap = /*@__PURE__*/ core.$constructor(\"ZodMiniMap\", (inst, def) => {\n core.$ZodMap.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function map(keyType, valueType, params) {\n return new ZodMiniMap({\n type: \"map\",\n keyType: keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniSet = /*@__PURE__*/ core.$constructor(\"ZodMiniSet\", (inst, def) => {\n core.$ZodSet.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function set(valueType, params) {\n return new ZodMiniSet({\n type: \"set\",\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniEnum = /*@__PURE__*/ core.$constructor(\"ZodMiniEnum\", (inst, def) => {\n core.$ZodEnum.init(inst, def);\n ZodMiniType.init(inst, def);\n inst.options = Object.values(def.entries);\n});\n// @__NO_SIDE_EFFECTS__\nfunction _enum(values, params) {\n const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;\n return new ZodMiniEnum({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\nexport { _enum as enum };\n// @__NO_SIDE_EFFECTS__\n/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.\n *\n * ```ts\n * enum Colors { red, green, blue }\n * z.enum(Colors);\n * ```\n */\nexport function nativeEnum(entries, params) {\n return new ZodMiniEnum({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniLiteral = /*@__PURE__*/ core.$constructor(\"ZodMiniLiteral\", (inst, def) => {\n core.$ZodLiteral.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function literal(value, params) {\n return new ZodMiniLiteral({\n type: \"literal\",\n values: Array.isArray(value) ? value : [value],\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniFile = /*@__PURE__*/ core.$constructor(\"ZodMiniFile\", (inst, def) => {\n core.$ZodFile.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function file(params) {\n return core._file(ZodMiniFile, params);\n}\nexport const ZodMiniTransform = /*@__PURE__*/ core.$constructor(\"ZodMiniTransform\", (inst, def) => {\n core.$ZodTransform.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function transform(fn) {\n return new ZodMiniTransform({\n type: \"transform\",\n transform: fn,\n });\n}\nexport const ZodMiniOptional = /*@__PURE__*/ core.$constructor(\"ZodMiniOptional\", (inst, def) => {\n core.$ZodOptional.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function optional(innerType) {\n return new ZodMiniOptional({\n type: \"optional\",\n innerType: innerType,\n });\n}\nexport const ZodMiniExactOptional = /*@__PURE__*/ core.$constructor(\"ZodMiniExactOptional\", (inst, def) => {\n core.$ZodExactOptional.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function exactOptional(innerType) {\n return new ZodMiniExactOptional({\n type: \"optional\",\n innerType: innerType,\n });\n}\nexport const ZodMiniNullable = /*@__PURE__*/ core.$constructor(\"ZodMiniNullable\", (inst, def) => {\n core.$ZodNullable.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function nullable(innerType) {\n return new ZodMiniNullable({\n type: \"nullable\",\n innerType: innerType,\n });\n}\n// nullish\n// @__NO_SIDE_EFFECTS__\nexport function nullish(innerType) {\n return optional(nullable(innerType));\n}\nexport const ZodMiniDefault = /*@__PURE__*/ core.$constructor(\"ZodMiniDefault\", (inst, def) => {\n core.$ZodDefault.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function _default(innerType, defaultValue) {\n return new ZodMiniDefault({\n type: \"default\",\n innerType: innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\nexport const ZodMiniPrefault = /*@__PURE__*/ core.$constructor(\"ZodMiniPrefault\", (inst, def) => {\n core.$ZodPrefault.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function prefault(innerType, defaultValue) {\n return new ZodMiniPrefault({\n type: \"prefault\",\n innerType: innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\nexport const ZodMiniNonOptional = /*@__PURE__*/ core.$constructor(\"ZodMiniNonOptional\", (inst, def) => {\n core.$ZodNonOptional.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function nonoptional(innerType, params) {\n return new ZodMiniNonOptional({\n type: \"nonoptional\",\n innerType: innerType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniSuccess = /*@__PURE__*/ core.$constructor(\"ZodMiniSuccess\", (inst, def) => {\n core.$ZodSuccess.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function success(innerType) {\n return new ZodMiniSuccess({\n type: \"success\",\n innerType: innerType,\n });\n}\nexport const ZodMiniCatch = /*@__PURE__*/ core.$constructor(\"ZodMiniCatch\", (inst, def) => {\n core.$ZodCatch.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nfunction _catch(innerType, catchValue) {\n return new ZodMiniCatch({\n type: \"catch\",\n innerType: innerType,\n catchValue: (typeof catchValue === \"function\" ? catchValue : () => catchValue),\n });\n}\nexport { _catch as catch };\nexport const ZodMiniNaN = /*@__PURE__*/ core.$constructor(\"ZodMiniNaN\", (inst, def) => {\n core.$ZodNaN.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function nan(params) {\n return core._nan(ZodMiniNaN, params);\n}\nexport const ZodMiniPipe = /*@__PURE__*/ core.$constructor(\"ZodMiniPipe\", (inst, def) => {\n core.$ZodPipe.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function pipe(in_, out) {\n return new ZodMiniPipe({\n type: \"pipe\",\n in: in_,\n out: out,\n });\n}\nexport const ZodMiniCodec = /*@__PURE__*/ core.$constructor(\"ZodMiniCodec\", (inst, def) => {\n ZodMiniPipe.init(inst, def);\n core.$ZodCodec.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function codec(in_, out, params) {\n return new ZodMiniCodec({\n type: \"pipe\",\n in: in_,\n out: out,\n transform: params.decode,\n reverseTransform: params.encode,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function invertCodec(codec) {\n const def = codec._zod.def;\n return new ZodMiniCodec({\n type: \"pipe\",\n in: def.out,\n out: def.in,\n transform: def.reverseTransform,\n reverseTransform: def.transform,\n });\n}\nexport const ZodMiniReadonly = /*@__PURE__*/ core.$constructor(\"ZodMiniReadonly\", (inst, def) => {\n core.$ZodReadonly.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function readonly(innerType) {\n return new ZodMiniReadonly({\n type: \"readonly\",\n innerType: innerType,\n });\n}\nexport const ZodMiniTemplateLiteral = /*@__PURE__*/ core.$constructor(\"ZodMiniTemplateLiteral\", (inst, def) => {\n core.$ZodTemplateLiteral.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function templateLiteral(parts, params) {\n return new ZodMiniTemplateLiteral({\n type: \"template_literal\",\n parts,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniLazy = /*@__PURE__*/ core.$constructor(\"ZodMiniLazy\", (inst, def) => {\n core.$ZodLazy.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// export function lazy<T extends object>(getter: () => T): T {\n// return util.createTransparentProxy<T>(getter);\n// }\n// @__NO_SIDE_EFFECTS__\nfunction _lazy(getter) {\n return new ZodMiniLazy({\n type: \"lazy\",\n getter: getter,\n });\n}\nexport { _lazy as lazy };\nexport const ZodMiniPromise = /*@__PURE__*/ core.$constructor(\"ZodMiniPromise\", (inst, def) => {\n core.$ZodPromise.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function promise(innerType) {\n return new ZodMiniPromise({\n type: \"promise\",\n innerType: innerType,\n });\n}\nexport const ZodMiniCustom = /*@__PURE__*/ core.$constructor(\"ZodMiniCustom\", (inst, def) => {\n core.$ZodCustom.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// custom checks\n// @__NO_SIDE_EFFECTS__\nexport function check(fn, params) {\n const ch = new core.$ZodCheck({\n check: \"custom\",\n ...util.normalizeParams(params),\n });\n ch._zod.check = fn;\n return ch;\n}\n// ZodCustom\n// custom schema\n// @__NO_SIDE_EFFECTS__\nexport function custom(fn, _params) {\n return core._custom(ZodMiniCustom, fn ?? (() => true), _params);\n}\n// refine\n// @__NO_SIDE_EFFECTS__\nexport function refine(fn, _params = {}) {\n return core._refine(ZodMiniCustom, fn, _params);\n}\n// superRefine\n// @__NO_SIDE_EFFECTS__\nexport function superRefine(fn, params) {\n return core._superRefine(fn, params);\n}\n// Re-export describe and meta from core\nexport const describe = core.describe;\nexport const meta = core.meta;\n// instanceof\nclass Class {\n constructor(..._args) { }\n}\n// @__NO_SIDE_EFFECTS__\nfunction _instanceof(cls, params = {}) {\n const inst = custom((data) => data instanceof cls, params);\n inst._zod.bag.Class = cls;\n // Override check to emit invalid_type instead of custom\n inst._zod.check = (payload) => {\n if (!(payload.value instanceof cls)) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: cls.name,\n input: payload.value,\n inst,\n path: [...(inst._zod.def.path ?? [])],\n });\n }\n };\n return inst;\n}\nexport { _instanceof as instanceof };\n// stringbool\nexport const stringbool = (...args) => core._stringbool({\n Codec: ZodMiniCodec,\n Boolean: ZodMiniBoolean,\n String: ZodMiniString,\n}, ...args);\n// @__NO_SIDE_EFFECTS__\nexport function json() {\n const jsonSchema = _lazy(() => {\n return union([string(), number(), boolean(), _null(), array(jsonSchema), record(string(), jsonSchema)]);\n });\n return jsonSchema;\n}\nexport const ZodMiniFunction = /*@__PURE__*/ core.$constructor(\"ZodMiniFunction\", (inst, def) => {\n core.$ZodFunction.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function _function(params) {\n return new ZodMiniFunction({\n type: \"function\",\n input: Array.isArray(params?.input) ? tuple(params?.input) : (params?.input ?? array(unknown())),\n output: params?.output ?? unknown(),\n });\n}\nexport { _function as function };\n","// `zod/mini` (tree-shakable functional API) instead of the full `zod` entry:\n// the widget only needs object/string/literal/union/nullable, and the mini\n// build keeps roughly 40KB of parser/refinement code out of the bundle.\nimport * as z from \"zod/mini\";\nimport { config as zodConfig } from \"zod/v4/core\";\n\n// Disable Zod's JIT-compiled fast path: it probes `Function(\"\")` at runtime,\n// which host pages with a strict Content-Security-Policy (no 'unsafe-eval')\n// block and report as a CSP violation on every widget load. Validation\n// behaves identically in jitless mode, just without eval-based codegen.\nzodConfig({ jitless: true });\n\nconst utteranceSchema = z.object({\n type: z.literal(\"utterance\"),\n content: z.string(),\n role: z.string(),\n});\n\nconst agentCognitionSchema = z.object({\n type: z.literal(\"agent_cognition\"),\n content: z.string(),\n});\n\nconst chatClosedExpiredSchema = z.object({\n type: z.literal(\"chat_closed_expired\"),\n content: z.string(),\n});\n\nconst agentCapturedUrlSchema = z.object({\n type: z.literal(\"agent_captured_url\"),\n content: z.string(),\n});\n\nconst agentTopicSchema = z.object({\n type: z.literal(\"agent_topic\"),\n content: z.string(),\n});\n\nconst agentSummarySchema = z.object({\n type: z.literal(\"agent_summary\"),\n content: z.string(),\n});\n\nconst chatRatingSchema = z.object({\n type: z.literal(\"chat_rating\"),\n content: z.string(),\n});\n\nconst breadcrumbSchema = z.object({\n type: z.literal(\"breadcrumb\"),\n content: z.string(),\n});\n\nconst chatEscalatedSchema = z.object({\n type: z.literal(\"chat_escalated\"),\n content: z.null(),\n});\n\nconst errorSchema = z.object({\n type: z.literal(\"error\"),\n code: z.string(),\n});\n\nconst utteranceApiResponseSchema = z.object({\n message_id: z.nullable(z.string()),\n created_at: z.string(),\n data: utteranceSchema,\n});\n\nconst errorApiResponseSchema = z.object({\n created_at: z.string(),\n data: errorSchema,\n});\n\nconst agentCognitionApiResponseSchema = z.object({\n created_at: z.string(),\n data: agentCognitionSchema,\n});\n\nconst chatClosedExpiredApiResponseSchema = z.object({\n message_id: z.nullable(z.string()),\n created_at: z.string(),\n data: chatClosedExpiredSchema,\n});\n\nconst agentCapturedUrlApiResponseSchema = z.object({\n created_at: z.string(),\n data: agentCapturedUrlSchema,\n});\n\nconst agentTopicApiResponseSchema = z.object({\n created_at: z.string(),\n data: agentTopicSchema,\n});\n\nconst agentSummaryApiResponseSchema = z.object({\n created_at: z.string(),\n data: agentSummarySchema,\n});\n\nconst chatRatingApiResponseSchema = z.object({\n created_at: z.string(),\n data: chatRatingSchema,\n});\n\nconst breadcrumbApiResponseSchema = z.object({\n created_at: z.string(),\n data: breadcrumbSchema,\n});\n\nconst chatEscalatedApiResponseSchema = z.object({\n message_id: z.nullable(z.string()),\n created_at: z.string(),\n data: chatEscalatedSchema,\n});\n\nexport const chatResponseApiSchema = z.union([\n utteranceApiResponseSchema,\n errorApiResponseSchema,\n agentCognitionApiResponseSchema,\n agentCapturedUrlApiResponseSchema,\n agentTopicApiResponseSchema,\n agentSummaryApiResponseSchema,\n chatClosedExpiredApiResponseSchema,\n chatRatingApiResponseSchema,\n breadcrumbApiResponseSchema,\n chatEscalatedApiResponseSchema,\n]);\n\nexport type ChatResponseApi = z.infer<typeof chatResponseApiSchema>;\n\ntype NotificationData = ChatResponseApi[\"data\"];\n\nexport type UtteranceNotification = {\n message_id: string | null;\n created_at: string;\n data: Extract<NotificationData, { type: \"utterance\" }>;\n};\n\nexport type ErrorNotification = {\n created_at: string;\n data: Extract<NotificationData, { type: \"error\" }>;\n};\n\nexport type AgentCognitionNotification = {\n created_at: string;\n data: Extract<NotificationData, { type: \"agent_cognition\" }>;\n};\n\nexport type AgentCapturedUrlNotification = {\n created_at: string;\n data: Extract<NotificationData, { type: \"agent_captured_url\" }>;\n};\n\nexport type AgentTopicNotification = {\n created_at: string;\n data: Extract<NotificationData, { type: \"agent_topic\" }>;\n};\n\nexport type AgentSummaryNotification = {\n created_at: string;\n data: Extract<NotificationData, { type: \"agent_summary\" }>;\n};\n\nexport const chatResponseSchema = z.object({\n message_id: z.string(), // message_id from api schema\n response: z.object({\n id: z.string(), // message_id from api schema\n type: z.string(),\n content: z.string(),\n }),\n});\n\nexport type ChatResponse = z.infer<typeof chatResponseSchema>;\n","import { useCallback, useEffect, useRef } from \"react\";\n\nimport { useErrorContext } from \"@/contexts/error-handling/error-context\";\nimport { getErrorMessage } from \"@/contexts/error-handling/error-messages\";\nimport { useLatestRef } from \"@/hooks/use-latest-ref\";\nimport {\n connectAppSyncEvents,\n type AppSyncEventsConnection,\n} from \"@/lib/appsync-events-client\";\nimport { BootResponse, MessageResponse } from \"@/lib/eloquent-ai-api-client\";\nimport { Message } from \"@/types/message\";\n\nimport {\n AgentCapturedUrlNotification,\n AgentCognitionNotification,\n AgentSummaryNotification,\n AgentTopicNotification,\n ChatResponse,\n chatResponseApiSchema,\n ErrorNotification,\n UtteranceNotification,\n} from \"../validations\";\n\nconst INITIAL_RECONNECT_DELAY_MS = 500;\nconst MAX_RECONNECT_DELAY_MS = 30000;\nconst DEFAULT_BACKUP_POLL_INTERVAL_MS = 60000;\n\nexport type UseRealtimeSocketOptions = {\n chatSettings: BootResponse[\"chat_settings\"] | null;\n chatId: string | null;\n messages: Message[];\n onMessage: (response: ChatResponse, chatId: string) => void;\n onCognition: (content: string) => void;\n onCognitionComplete: () => void;\n onError?: () => void;\n onChatClosed?: () => void;\n onAgentCapturedUrl?: (content: string) => void;\n onAgentTopic?: (content: string) => void;\n onAgentSummary?: (content: string) => void;\n onRatingRequest?: () => void;\n onBreadcrumb?: () => void;\n fetchHistory: (chatId: string) => Promise<MessageResponse[]>;\n getChatToken: () => string | null;\n backupPollingInterval?: number;\n};\n\nexport type UseRealtimeSocketReturn = {\n connect: (chatId: string) => Promise<void>;\n disconnect: () => void;\n clearProcessedIds: () => void;\n};\n\nexport function useRealtimeSocket({\n chatSettings,\n chatId,\n messages,\n onMessage,\n onCognition,\n onCognitionComplete,\n onError,\n onChatClosed,\n onAgentCapturedUrl,\n onAgentTopic,\n onAgentSummary,\n onRatingRequest,\n onBreadcrumb,\n fetchHistory,\n getChatToken,\n backupPollingInterval = DEFAULT_BACKUP_POLL_INTERVAL_MS,\n}: UseRealtimeSocketOptions): UseRealtimeSocketReturn {\n const processedIdsRef = useRef<Set<string>>(new Set());\n\n useEffect(() => {\n for (const msg of messages) {\n if (msg.id) processedIdsRef.current.add(msg.id);\n }\n }, [messages]);\n\n const eventChannelRef = useRef<AppSyncEventsConnection | null>(null);\n const activeChatIdRef = useRef<string | null>(null);\n const reconnectAttemptsRef = useRef(0);\n const reconnectTimerRef = useRef<NodeJS.Timeout | null>(null);\n const backupPollIntervalRef = useRef<NodeJS.Timeout | null>(null);\n const shouldReconnectRef = useRef(false);\n const isReconnectingRef = useRef(false);\n\n // Keep all mutable callbacks as latest-refs to avoid stale closures in\n // timers/intervals and the long-lived socket subscription.\n const onMessageRef = useLatestRef(onMessage);\n const onCognitionRef = useLatestRef(onCognition);\n const onCognitionCompleteRef = useLatestRef(onCognitionComplete);\n const onErrorRef = useLatestRef(onError);\n const onChatClosedRef = useLatestRef(onChatClosed);\n const onAgentCapturedUrlRef = useLatestRef(onAgentCapturedUrl);\n const onAgentTopicRef = useLatestRef(onAgentTopic);\n const onAgentSummaryRef = useLatestRef(onAgentSummary);\n const onRatingRequestRef = useLatestRef(onRatingRequest);\n const onBreadcrumbRef = useLatestRef(onBreadcrumb);\n const fetchHistoryRef = useLatestRef(fetchHistory);\n const getChatTokenRef = useLatestRef(getChatToken);\n\n const { publishError } = useErrorContext();\n\n const appSyncUrl = chatSettings?.app_sync_url;\n const appSyncApiKey = chatSettings?.app_sync_api_key;\n // The client is configuration-free (no Amplify.configure singleton) —\n // connections are ready as soon as boot settings provide the endpoint.\n const isSocketConfigReady = Boolean(appSyncUrl && appSyncApiKey);\n const appSyncUrlRef = useLatestRef(appSyncUrl);\n const appSyncApiKeyRef = useLatestRef(appSyncApiKey);\n\n const closeChannel = useCallback(() => {\n if (eventChannelRef.current) {\n eventChannelRef.current.close();\n eventChannelRef.current = null;\n }\n }, []);\n\n const stopBackupPoll = useCallback(() => {\n if (backupPollIntervalRef.current) {\n clearInterval(backupPollIntervalRef.current);\n backupPollIntervalRef.current = null;\n }\n }, []);\n\n const clearReconnectTimer = useCallback(() => {\n if (reconnectTimerRef.current) {\n clearTimeout(reconnectTimerRef.current);\n reconnectTimerRef.current = null;\n }\n }, []);\n\n // Forward-declared: connectChannel's onDisconnect needs scheduleReconnect,\n // which itself needs connectChannel — the ref breaks the cycle. Synced to\n // the latest scheduleReconnect below.\n const scheduleReconnectRef = useRef<() => void>(() => {});\n\n // Opens an AppSync Events channel and subscribes to real-time events\n const connectChannel = useCallback(\n async (chatIdToConnect: string): Promise<void> => {\n closeChannel();\n const httpEndpoint = appSyncUrlRef.current;\n const apiKey = appSyncApiKeyRef.current;\n if (!httpEndpoint || !apiKey) {\n throw new Error(\"Cannot connect: AppSync settings not available\");\n }\n const chatToken = getChatTokenRef.current();\n\n const connection = await connectAppSyncEvents({\n httpEndpoint,\n auth: chatToken ? { authorizationToken: chatToken } : { apiKey },\n channel: `/default/chat/${chatIdToConnect}`,\n onDisconnect: () => {\n eventChannelRef.current = null;\n scheduleReconnectRef.current();\n },\n onEvent: (event) => {\n const parseResult = chatResponseApiSchema.safeParse(event);\n if (!parseResult.success) {\n console.error(\"Invalid conversation response:\", parseResult.error);\n return;\n }\n\n const notification = parseResult.data;\n switch (notification.data.type) {\n case \"utterance\": {\n const utterance = notification as UtteranceNotification;\n const messageId = utterance.message_id ?? crypto.randomUUID();\n if (processedIdsRef.current.has(messageId)) {\n return;\n }\n processedIdsRef.current.add(messageId);\n onCognitionCompleteRef.current();\n onMessageRef.current(\n {\n message_id: messageId,\n response: {\n id: messageId,\n type: utterance.data.type,\n content: utterance.data.content,\n },\n },\n chatIdToConnect,\n );\n return;\n }\n case \"error\": {\n const errorNotif = notification as ErrorNotification;\n const code = parseInt(errorNotif.data.code);\n publishError({ code, message: getErrorMessage(code) });\n onErrorRef.current?.();\n return;\n }\n case \"agent_cognition\": {\n const cognition = notification as AgentCognitionNotification;\n onCognitionRef.current(cognition.data.content);\n return;\n }\n case \"agent_captured_url\": {\n const capturedUrl = notification as AgentCapturedUrlNotification;\n onAgentCapturedUrlRef.current?.(capturedUrl.data.content);\n return;\n }\n case \"agent_topic\": {\n const topic = notification as AgentTopicNotification;\n onAgentTopicRef.current?.(topic.data.content);\n return;\n }\n case \"agent_summary\": {\n const summary = notification as AgentSummaryNotification;\n onAgentSummaryRef.current?.(summary.data.content);\n return;\n }\n case \"chat_closed_expired\": {\n onChatClosedRef.current?.();\n onRatingRequestRef.current?.();\n return;\n }\n case \"chat_rating\": {\n onRatingRequestRef.current?.();\n return;\n }\n case \"breadcrumb\": {\n onBreadcrumbRef.current?.();\n return;\n }\n case \"chat_escalated\": {\n onChatClosedRef.current?.();\n onRatingRequestRef.current?.();\n return;\n }\n default:\n console.warn(\n \"Unknown notification type:\",\n (notification as { data: { type: string } }).data.type,\n );\n }\n },\n });\n\n eventChannelRef.current = connection;\n },\n // The *Ref entries are latest-refs (stable identities); listed to satisfy\n // exhaustive-deps, which can't see that useLatestRef returns a ref.\n [\n closeChannel,\n publishError,\n appSyncUrlRef,\n appSyncApiKeyRef,\n getChatTokenRef,\n onMessageRef,\n onCognitionRef,\n onCognitionCompleteRef,\n onErrorRef,\n onChatClosedRef,\n onAgentCapturedUrlRef,\n onAgentTopicRef,\n onAgentSummaryRef,\n onRatingRequestRef,\n onBreadcrumbRef,\n ],\n );\n\n // Fetches history and delivers any unseen assistant messages via onMessage\n const runBackupPoll = useCallback(\n async (chatIdToPoll: string) => {\n try {\n const history = await fetchHistoryRef.current(chatIdToPoll);\n for (const msg of history) {\n if (\n msg.role !== \"assistant\" ||\n !msg.message_id ||\n processedIdsRef.current.has(msg.message_id)\n ) {\n continue;\n }\n processedIdsRef.current.add(msg.message_id);\n onMessageRef.current(\n { message_id: msg.message_id, response: msg.response },\n chatIdToPoll,\n );\n }\n } catch (err) {\n console.warn(\"Backup poll failed:\", err);\n }\n },\n [fetchHistoryRef, onMessageRef],\n );\n\n const startBackupPoll = useCallback(\n (chatIdToPoll: string) => {\n stopBackupPoll();\n backupPollIntervalRef.current = setInterval(\n () => runBackupPoll(chatIdToPoll),\n backupPollingInterval,\n );\n },\n [stopBackupPoll, runBackupPoll, backupPollingInterval],\n );\n\n // Named function expression so the setTimeout callback can re-schedule\n // itself on failure without a circular ref dependency.\n const scheduleReconnect = useCallback(\n function scheduleReconnectSelf() {\n if (\n !shouldReconnectRef.current ||\n isReconnectingRef.current ||\n reconnectTimerRef.current\n ) {\n return;\n }\n const chatIdToReconnect = activeChatIdRef.current;\n if (!chatIdToReconnect) return;\n\n const delay = Math.min(\n INITIAL_RECONNECT_DELAY_MS * Math.pow(2, reconnectAttemptsRef.current),\n MAX_RECONNECT_DELAY_MS,\n );\n reconnectAttemptsRef.current += 1;\n\n reconnectTimerRef.current = setTimeout(async () => {\n reconnectTimerRef.current = null;\n isReconnectingRef.current = true;\n try {\n await connectChannel(chatIdToReconnect);\n reconnectAttemptsRef.current = 0;\n isReconnectingRef.current = false;\n await runBackupPoll(chatIdToReconnect);\n } catch {\n isReconnectingRef.current = false;\n scheduleReconnectSelf();\n }\n }, delay);\n },\n [connectChannel, runBackupPoll],\n );\n\n // Keep the forward-declared ref pointing at the latest scheduleReconnect\n // (same semantics as useLatestRef, but the ref had to exist earlier for\n // connectChannel's onDisconnect).\n useEffect(() => {\n scheduleReconnectRef.current = scheduleReconnect;\n });\n\n const connect = useCallback(\n async (chatIdToConnect: string): Promise<void> => {\n if (!isSocketConfigReady || !chatIdToConnect) {\n throw new Error(\n \"Cannot connect: AppSync settings not ready or missing chatId\",\n );\n }\n clearReconnectTimer();\n shouldReconnectRef.current = true;\n activeChatIdRef.current = chatIdToConnect;\n reconnectAttemptsRef.current = 0;\n // Start polling before the socket connect attempt, not after — if\n // connectChannel throws (e.g. the AppSync channel is unreachable),\n // polling must still run so messages keep arriving via history\n // instead of being lost entirely until a reconnect succeeds.\n startBackupPoll(chatIdToConnect);\n await connectChannel(chatIdToConnect);\n },\n [isSocketConfigReady, clearReconnectTimer, connectChannel, startBackupPoll],\n );\n\n const disconnect = useCallback((): void => {\n shouldReconnectRef.current = false;\n activeChatIdRef.current = null;\n reconnectAttemptsRef.current = 0;\n clearReconnectTimer();\n stopBackupPoll();\n closeChannel();\n }, [clearReconnectTimer, stopBackupPoll, closeChannel]);\n\n const clearProcessedIds = useCallback(() => {\n processedIdsRef.current.clear();\n }, []);\n\n // Eagerly connect when chatId becomes available (e.g., restored from localStorage on mount)\n useEffect(() => {\n if (!chatId || !isSocketConfigReady || activeChatIdRef.current === chatId)\n return;\n\n connect(chatId).catch((err) => {\n console.error(\"Failed to eagerly connect:\", err);\n activeChatIdRef.current = chatId;\n shouldReconnectRef.current = true;\n scheduleReconnectRef.current();\n });\n }, [chatId, isSocketConfigReady, connect]);\n\n // Disconnect detection lives inside connectAppSyncEvents (socket close and\n // keep-alive timeout both invoke connectChannel's onDisconnect), replacing\n // the amplify Hub connection-state listener.\n\n useEffect(() => {\n return () => {\n disconnect();\n };\n }, [disconnect]);\n\n return { connect, disconnect, clearProcessedIds };\n}\n","import type { ChatResponse } from \"@/components/chat/validations\";\nimport type { Message } from \"@/types/message\";\n\n/**\n * The single place where API/wire shapes become domain `Message`s.\n *\n * Everything here is a pure function: the hooks own state and timing, this\n * module owns shape. A backend field change should only ever touch this file\n * (and validations.ts), not the hooks.\n */\n\n/** A realtime/polled assistant reply, as appended to the transcript. */\nexport function messageFromChatResponse(response: ChatResponse): Message {\n return {\n id: response.message_id,\n content: response.response.content ?? \"\",\n sender: \"assistant\",\n timestamp: new Date().toISOString(),\n };\n}\n\n/** The configured welcome message, shown before any conversation exists. */\nexport function createWelcomeMessage(content: string): Message {\n return {\n id: crypto.randomUUID(),\n content,\n sender: \"assistant\",\n timestamp: new Date().toISOString(),\n isWelcomeMessage: true,\n };\n}\n\n/** The star-rating prompt appended when the server requests feedback. */\nexport function createRatingRequestMessage(): Message {\n return {\n id: crypto.randomUUID(),\n content: \"\",\n sender: \"assistant\",\n timestamp: new Date().toISOString(),\n isRatingRequest: true,\n };\n}\n\n/** The notice shown when the user writes into a closed conversation. */\nexport function createChatClosedNoticeMessage(): Message {\n return {\n id: crypto.randomUUID(),\n content: \"This conversation is closed, please start a new chat.\",\n sender: \"assistant\",\n timestamp: new Date().toISOString(),\n };\n}\n","\"use client\";\nimport {\n useCallback,\n useEffect,\n type Dispatch,\n type SetStateAction,\n} from \"react\";\n\nimport { Message, MessageData } from \"@/types/message\";\n\nimport {\n BootResponse,\n EloquentAiApiClient,\n} from \"@/lib/eloquent-ai-api-client\";\n\nimport { useErrorContext } from \"@/contexts/error-handling/error-context\";\nimport { useAgentCognitionContext } from \"@/contexts/agent-cognition/use-agent-cognition-context\";\nimport { useLatestRef } from \"@/hooks/use-latest-ref\";\nimport { NetworkError, ServerError } from \"@/lib/http\";\nimport { getCurrentUrlSearchParams } from \"@/lib/url-params\";\nimport { usePersistence } from \"./use-persistence\";\nimport { useRealtimeSocket } from \"./use-realtime-socket\";\nimport {\n createChatClosedNoticeMessage,\n createRatingRequestMessage,\n messageFromChatResponse,\n} from \"../message-mapping\";\nimport { ChatResponse } from \"../validations\";\n\nexport interface UseMessageEventsProps {\n appId: string;\n userId: string;\n userName?: string;\n userData?: Record<string, string | number | boolean>;\n externalId?: string | null;\n deviceId: string;\n apiClient: EloquentAiApiClient | null;\n chatSettings: BootResponse[\"chat_settings\"] | null;\n messages: Message[];\n setMessages: Dispatch<SetStateAction<Message[]>>;\n currentChat: { id: string } | null;\n setCurrentChat: Dispatch<SetStateAction<{ id: string } | null>>;\n onChatClosed?: () => void;\n isChatClosed?: boolean;\n}\n\nexport interface UseMessageEventsReturn {\n onCleanMessages: () => void;\n onSendMessage: (data: MessageData) => Promise<void>;\n onRateChat: (rating: number) => Promise<void>;\n}\n\n/**\n * Hook to handle message events like sending and cleaning\n */\nexport function useMessageEvents({\n appId,\n userId,\n userName,\n userData,\n externalId,\n deviceId,\n apiClient,\n chatSettings,\n messages,\n setMessages,\n currentChat,\n setCurrentChat,\n onChatClosed,\n isChatClosed,\n}: UseMessageEventsProps): UseMessageEventsReturn {\n const { saveChatData, clearChatData, updateLastActivity, markChatClosed } =\n usePersistence({\n appId,\n });\n\n const { publishApiError, publishNetworkError } = useErrorContext();\n const { showCognition, hideCognition } = useAgentCognitionContext();\n\n // Keep apiClient in a ref so stable callbacks always use the latest instance\n const apiClientRef = useLatestRef(apiClient);\n\n /**\n * Handles receiving messages from the server.\n * Called by the WebSocket and backup poll — deduplication\n * is handled inside useRealtimeSocket via processedIds.\n */\n const onReceiveMessage = useCallback(\n (response: ChatResponse, chatId: string) => {\n if (!response.response.content) return;\n\n setMessages((prev) => {\n if (prev.some((msg) => msg.isRatingRequest)) return prev;\n // Ignore the message if it matches the configured welcome message\n if (\n chatSettings?.welcome_message &&\n response.response.content === chatSettings.welcome_message\n )\n return prev;\n const filteredMessages = prev.filter((msg) => !msg.isThinking);\n const updatedMessages: Message[] = [\n ...filteredMessages,\n messageFromChatResponse(response),\n ];\n saveChatData(\n chatId,\n userId,\n updatedMessages,\n deviceId,\n apiClientRef.current?.getChatToken(),\n );\n return updatedMessages;\n });\n },\n [chatSettings, deviceId, saveChatData, setMessages, userId, apiClientRef],\n );\n\n const handleRealTimeError = useCallback(() => {\n hideCognition();\n setMessages((prev) => prev.filter((msg) => !msg.isThinking));\n }, [setMessages, hideCognition]);\n\n const handleRatingRequest = useCallback(() => {\n setMessages((prev) => {\n const filtered = prev.filter((msg) => !msg.isRatingRequest);\n return [...filtered, createRatingRequestMessage()];\n });\n }, [setMessages]);\n\n useEffect(() => {\n if (import.meta.env.DEV) {\n const w = window as unknown as Record<string, unknown>;\n w.EloquentAI_TriggerChatRating = handleRatingRequest;\n return () => {\n delete w.EloquentAI_TriggerChatRating;\n };\n }\n }, [handleRatingRequest]);\n\n const fetchHistory = useCallback(\n (chatId: string) => {\n if (!apiClientRef.current) return Promise.resolve([]);\n return apiClientRef.current.getChatHistory(chatId);\n },\n [apiClientRef],\n );\n\n const getChatToken = useCallback(() => {\n return apiClientRef.current?.getChatToken() ?? null;\n }, [apiClientRef]);\n\n const handleChatClosed = useCallback(() => {\n markChatClosed();\n onChatClosed?.();\n }, [markChatClosed, onChatClosed]);\n\n const { connect, disconnect, clearProcessedIds } = useRealtimeSocket({\n chatSettings,\n chatId: currentChat?.id ?? null,\n messages,\n onMessage: onReceiveMessage,\n onCognition: showCognition,\n onCognitionComplete: hideCognition,\n onError: handleRealTimeError,\n onChatClosed: handleChatClosed,\n onRatingRequest: handleRatingRequest,\n onBreadcrumb: handleChatClosed,\n fetchHistory,\n getChatToken,\n });\n\n const onCleanMessages = useCallback(() => {\n hideCognition();\n disconnect();\n clearProcessedIds();\n setMessages((prev) =>\n prev.filter((message) => {\n if (Array.isArray(message)) return false;\n return message.isWelcomeMessage;\n }),\n );\n clearChatData();\n setCurrentChat(null);\n }, [\n hideCognition,\n disconnect,\n clearProcessedIds,\n clearChatData,\n setMessages,\n setCurrentChat,\n ]);\n\n /**\n * Handles sending messages to the server\n */\n const onSendMessage = useCallback(\n async (message: MessageData) => {\n if (!apiClient) return;\n\n if (messages.some((msg) => msg.isRatingRequest)) return;\n\n if (isChatClosed) {\n setMessages((prev) => [...prev, createChatClosedNoticeMessage()]);\n return;\n }\n\n const userMessage = {\n ...message,\n id: crypto.randomUUID(),\n isNew: true,\n };\n\n showCognition();\n const newMessages = [...messages, userMessage];\n setMessages(newMessages);\n updateLastActivity();\n\n try {\n let chatId = currentChat?.id;\n if (!chatId) {\n const response = await apiClient.createConversation({\n userId: externalId || userId,\n deviceId,\n userName,\n userData,\n externalMetadata: {\n searchParams: getCurrentUrlSearchParams(),\n },\n });\n chatId = response.chat_id;\n setCurrentChat({ id: chatId });\n try {\n await connect(chatId);\n } catch (connectError) {\n console.warn(\n \"Failed to connect realtime channel, continuing with REST-only delivery:\",\n connectError,\n );\n }\n }\n\n const response = await apiClient.replyToConversation({\n text: message.content,\n conversationId: chatId,\n userId: externalId || userId,\n deviceId,\n userName,\n userData,\n });\n\n // Update user message with real server ID\n setMessages((prev) =>\n prev.map((msg) =>\n msg.id === userMessage.id\n ? { ...msg, id: response.message_id, isNew: false }\n : msg,\n ),\n );\n } catch (error) {\n hideCognition();\n\n setMessages((prev) => prev.filter((msg) => !msg.isThinking));\n\n if (\n error instanceof NetworkError ||\n (error instanceof ServerError && error.status === 403)\n ) {\n publishNetworkError();\n throw error;\n }\n\n publishApiError(error as ServerError);\n\n if (\n error instanceof ServerError &&\n // A 401 here means the chat's session token is invalid/expired\n // (or the chat closed) — treat it the same as a client-side\n // expired chat: drop the stale session and let the next send\n // start a fresh one, instead of surfacing an error.\n (error.status >= 500 || error.status === 401)\n ) {\n setCurrentChat(null);\n clearChatData();\n setMessages((prev) => prev.slice(0, -1));\n apiClient.reset();\n } else {\n // Mark the user message as failed\n setMessages((prev) =>\n prev.map((msg) =>\n msg.id === userMessage.id ? { ...msg, isFailed: true } : msg,\n ),\n );\n }\n\n throw error;\n }\n },\n [\n apiClient,\n isChatClosed,\n showCognition,\n messages,\n setMessages,\n updateLastActivity,\n currentChat?.id,\n externalId,\n userId,\n deviceId,\n setCurrentChat,\n connect,\n hideCognition,\n publishApiError,\n publishNetworkError,\n clearChatData,\n userName,\n userData,\n ],\n );\n\n const onRateChat = useCallback(\n async (rating: number) => {\n const chatId = currentChat?.id;\n if (!apiClientRef.current || !chatId) return;\n await apiClientRef.current.addRating(chatId, rating);\n },\n [currentChat?.id, apiClientRef],\n );\n\n return {\n onCleanMessages,\n onSendMessage,\n onRateChat,\n };\n}\n","// Helper to safely access import.meta.env in SSR environments\nfunction getEnvVariable(key: string): string {\n // Check if we're in a browser or if import.meta is available\n if (typeof window === \"undefined\" || typeof import.meta === \"undefined\") {\n return \"\";\n }\n return (import.meta.env[key] as string) || \"\";\n}\n\n// Define environment-specific constants that will be replaced during build\nconst ENV_API_URL = getEnvVariable(\"VITE_API_URL\");\nconst ENV_REGION_API_URL = getEnvVariable(\"VITE_REGION_API_URL\");\n\n/**\n * Returns the API URL based on the provided custom URL or the default API URL.\n * @returns The API URL.\n */\nexport function getApiUrl(): string {\n return ENV_API_URL || \"\";\n}\n\n/**\n * Returns the Region API URL based on the environment.\n * @returns The Region API URL.\n */\nexport function getRegionApiUrl(): string {\n return ENV_REGION_API_URL || \"\";\n}\n","import { getRegionApiUrl } from \"./config\";\nimport { HttpClient, HttpClientConfig } from \"./http\";\n\ninterface UserData {\n device_id: string;\n user_id?: string;\n user_name?: string;\n external_id?: string;\n user_data?: Record<string, string | number | boolean>;\n}\n\ninterface Message {\n text: string;\n user_data: UserData;\n}\n\nexport interface ConversationApiResponse {\n chat_id: string;\n message_id: string;\n response: {\n id: string;\n type: string;\n content: string;\n };\n}\n\nexport interface CreateConversationApiResponse {\n chat_id: string;\n chat_token: string;\n}\n\nexport interface IdentifyUserApiResponse {\n result: string;\n}\n\nexport interface MessageResponse {\n response: {\n id: string;\n type: string;\n content: string;\n };\n message_id: string;\n message_number: number;\n created_at: string;\n previousMessage?: MessageResponse;\n role: \"user\" | \"assistant\" | \"system\";\n}\n\nexport interface AddRatingApiResponse {\n result: string;\n}\n\nexport interface OrganizationResponse {\n region: string;\n}\n\nexport interface ExternalMetadata {\n [key: string]: string | ExternalMetadata;\n}\n\nexport interface BootResponse {\n chat_settings: {\n agent_name: string;\n welcome_message?: string | null;\n footer_html?: string | null;\n suggested_messages: boolean;\n suggested_message_texts?: string[] | null;\n suggested_message_aura?: boolean | null;\n suggested_message_shine?: boolean | null;\n auto_display_welcome_message: boolean;\n collect_user_feedback: boolean;\n theme: \"light\" | \"dark\";\n avatar_url?: string | null;\n user_bubble_color?: string | null;\n bot_bubble_color?: string | null;\n suggested_message_bubble_color?: string | null;\n user_bubble_text_color?: string | null;\n bot_bubble_text_color?: string | null;\n suggested_message_bubble_text_color?: string | null;\n app_sync_api_key: string;\n app_sync_url: string;\n app_sync_region: string;\n title?: string;\n subtitle?: string;\n is_active?: boolean;\n /** Open the chat window on load (desktop only). Wins over the isInitiallyOpen prop, but a `true` here never overrides the user's closed-cookie. */\n initial_open?: boolean | null;\n /** Show the close (X) button in the chat header. Always wins over the hasCloseButton prop. */\n close_button?: boolean | null;\n /** Show the clear-conversation button in the chat header. Always wins over the hasCleanChatButton prop. */\n clean_chat_button?: boolean | null;\n /** Auto-hide delay for the proactive message, in milliseconds. Always wins over the proactiveMessageHideDelay prop. */\n proactive_message_hide_delay?: number | null;\n };\n}\n\nexport class EloquentAiApiClient {\n private httpClient: HttpClient;\n private userId: string | null = null;\n private conversationId: string | null = null;\n\n constructor(config: HttpClientConfig) {\n this.userId = config.userId || null;\n this.httpClient = new HttpClient(config);\n }\n\n getUserData() {\n return {\n userId: this.userId,\n conversationId: this.conversationId,\n };\n }\n\n /**\n * Reset API client by clearing all stored state\n */\n reset() {\n this.conversationId = null;\n this.httpClient.setChatToken(null);\n }\n\n setRegion(region: string): void {\n this.httpClient.setRegion(region);\n }\n\n getChatToken(): string | null {\n return this.httpClient.getChatToken();\n }\n\n setChatToken(token: string | null): void {\n this.httpClient.setChatToken(token);\n }\n\n /**\n * Get organization data by app ID\n */\n async getOrganizationByAppId(appId: string) {\n const regionApiUrl = getRegionApiUrl();\n const response = await this.httpClient.getExternal<OrganizationResponse>(\n `${regionApiUrl}/by-app-id/${appId}`,\n );\n return response;\n }\n\n async boot() {\n const response = await this.httpClient.get<{ data: BootResponse }>(\n \"/v1/sdk/boot\",\n );\n return response.data;\n }\n\n async addRating(chatId: string, rating: number) {\n const response = await this.httpClient.put<\n { data: AddRatingApiResponse },\n { rating: number }\n >(`/v1/chat/${chatId}/rating`, { rating: rating });\n return response.data;\n }\n\n async createConversation(options: {\n userId: string;\n deviceId: string;\n userName?: string;\n externalId?: string;\n userData?: Record<string, string | number | boolean>;\n externalMetadata?: ExternalMetadata;\n }) {\n const response = await this.httpClient.post<\n { data: CreateConversationApiResponse },\n { user_data: UserData; external_metadata?: ExternalMetadata }\n >(\"/v2/chat\", {\n user_data: {\n user_id: options.userId,\n device_id: options.deviceId,\n user_name: options.userName,\n external_id: options.externalId,\n user_data: options.userData,\n },\n ...(options.externalMetadata &&\n Object.keys(options.externalMetadata).length > 0\n ? { external_metadata: options.externalMetadata }\n : {}),\n });\n\n const { data } = response;\n this.httpClient.setChatToken(data.chat_token);\n\n return data;\n }\n\n async replyToConversation(options: {\n text: string;\n conversationId: string;\n userId: string;\n deviceId: string;\n userName?: string;\n userData?: Record<string, string | number | boolean>;\n }) {\n const message: Message = {\n text: options.text,\n user_data: {\n device_id: options.deviceId,\n user_id: options.userId,\n user_name: options.userName,\n user_data: options.userData,\n },\n };\n\n const { data } = await this.httpClient.post<\n { data: ConversationApiResponse },\n Message\n >(`/v3/chat/${options.conversationId}`, message);\n\n return data;\n }\n\n async identifyUser(options: {\n conversationId: string;\n userId: string;\n deviceId: string;\n userName?: string;\n externalId?: string;\n userData?: Record<string, string | number | boolean>;\n }) {\n const message: UserData = {\n device_id: options.deviceId,\n user_id: options.userId,\n user_name: options.userName,\n external_id: options.externalId,\n user_data: options.userData,\n };\n\n const { data } = await this.httpClient.post<\n { data: IdentifyUserApiResponse },\n UserData\n >(`/v1/chat/${options.conversationId}/identify`, message);\n\n return data;\n }\n\n async getChatHistory(conversationId: string) {\n const response = await this.httpClient.get<{ data: MessageResponse[] }>(\n `/v1/chat/${conversationId}/history`,\n );\n return response.data;\n }\n}\n","import { ServerError } from \"@/lib/http\";\n\n/**\n * Wraps a Promise and returns a tuple containing the result or error\n * @param promise Promise to wrap\n * @returns [result, error] - result is null if error occurred, error is null if no error occurred\n */\nexport async function wrapPromise<T, E = ServerError>(\n promise: Promise<T>,\n): Promise<[T, null] | [null, E]> {\n try {\n return [await promise, null] as const;\n } catch (error) {\n return [null, error as E] as const;\n }\n}\n","import { NetworkError, ServerError } from \"./http\";\n\ninterface WithRetryOptions {\n retries?: number;\n minDelayMs?: number;\n maxDelayMs?: number;\n factor?: number;\n}\n\nconst DEFAULT_OPTIONS: Required<WithRetryOptions> = {\n retries: 3,\n minDelayMs: 200,\n maxDelayMs: 1_000,\n factor: 2,\n};\n\n/** Retries on network errors and 5xx/429 responses; other errors bail immediately. */\nexport function isRetryableError(error: unknown): boolean {\n if (error instanceof NetworkError) return true;\n if (error instanceof ServerError) {\n return error.status === 429 || error.status >= 500;\n }\n return false;\n}\n\n/** Exponential backoff with full jitter, mirroring the retry shape used in chat-api's http-retry.util.ts. */\nfunction getDelayMs(\n attempt: number,\n options: Required<WithRetryOptions>,\n): number {\n const exponentialDelay = options.minDelayMs * options.factor ** attempt;\n const cappedDelay = Math.min(exponentialDelay, options.maxDelayMs);\n return Math.random() * cappedDelay;\n}\n\nexport async function withRetry<T>(\n operation: () => Promise<T>,\n options: WithRetryOptions = {},\n): Promise<T> {\n const opts = { ...DEFAULT_OPTIONS, ...options };\n\n for (let attempt = 0; ; attempt++) {\n try {\n return await operation();\n } catch (error) {\n if (attempt >= opts.retries || !isRetryableError(error)) {\n throw error;\n }\n await new Promise((resolve) =>\n setTimeout(resolve, getDelayMs(attempt, opts)),\n );\n }\n }\n}\n","import { useErrorContext } from \"@/contexts/error-handling/error-context\";\nimport { NetworkError, ServerError } from \"@/lib/http\";\nimport { useCallback, useRef, useState } from \"react\";\n\n// Module-level cache and in-flight promise tracker\nconst cache = new Map<string, unknown>();\nconst inflight = new Map<string, Promise<unknown>>();\n\ninterface UseFetchOptions {\n dedupe?: boolean;\n}\n\ninterface UseFetchResult<T, E> {\n data: T | undefined;\n error: E | undefined;\n isLoading: boolean;\n fetch: () => Promise<T>;\n}\n\n/**\n * useFetch hook that deduplicates requests and prevents double-fetching.\n * Fetch is triggered by calling the returned fetch function, not automatically.\n * @param key Unique key for the resource (should uniquely identify the request)\n * @param fetcher Function that returns a promise for the data\n * @param options Options object (dedupe: boolean)\n */\nexport function useFetch<T, E = Error>(\n key: string,\n fetcher: () => Promise<T | undefined>,\n options?: UseFetchOptions,\n): UseFetchResult<T, E> {\n const dedupe = options?.dedupe !== false; // default to true\n const [data, setData] = useState<T | undefined>(\n () => cache.get(key) as T | undefined,\n );\n const { publishApiError, publishNetworkError } = useErrorContext();\n\n const [error, setError] = useState<E | undefined>(undefined);\n const [isLoading, setIsLoading] = useState<boolean>(false);\n const mountedRef = useRef(true);\n\n // Clean up on unmount\n useRef(() => {\n mountedRef.current = true;\n return () => {\n mountedRef.current = false;\n };\n });\n\n const fetch = useCallback(async (): Promise<T> => {\n if (cache.has(key)) {\n const cachedData = cache.get(key) as T;\n setData(cachedData);\n return cachedData;\n }\n\n setIsLoading(true);\n setError(undefined);\n\n try {\n // If we have an in-flight request and dedupe is enabled, use that\n if (dedupe && inflight.has(key)) {\n return (await inflight.get(key)) as Promise<T>;\n }\n\n // Otherwise, create a new request\n const promise = fetcher();\n\n // Track it if deduplication is enabled\n if (dedupe) {\n inflight.set(key, promise);\n }\n\n // Await the result directly\n const result = await promise;\n\n // Update cache and state\n cache.set(key, result);\n if (mountedRef.current) {\n setData(result);\n }\n\n return result as T;\n } catch (err) {\n if (\n err instanceof NetworkError ||\n (err instanceof ServerError && err.status === 403)\n ) {\n publishNetworkError();\n } else {\n publishApiError(err as ServerError);\n }\n if (mountedRef.current) {\n setError(err as E);\n }\n throw err;\n } finally {\n // Clean up\n if (dedupe) {\n inflight.delete(key);\n }\n if (mountedRef.current) {\n setIsLoading(false);\n }\n }\n }, [key, dedupe, fetcher, publishApiError, publishNetworkError]);\n\n return { data, error, isLoading, fetch };\n}\n","import { useState } from \"react\";\nimport { usePersistence, type ChatData } from \"./use-persistence\";\n\ntype UserIdentityOptions = { appId: string; initialUserId?: string };\n\ntype UserIdentityReturn = {\n userId: string;\n deviceId: string;\n isReady: boolean;\n externalId?: string | null;\n};\n\ntype ResolvedIdentity = {\n userId: string;\n deviceId: string;\n externalId?: string | null;\n};\n\nfunction resolveUserIdentity(\n savedData: ChatData,\n initialUserId?: string,\n): ResolvedIdentity {\n const deviceId = savedData?.deviceId || crypto.randomUUID();\n\n if (!savedData?.userId) {\n if (initialUserId) {\n // TODO should we have an internal userId and a different externalId?\n return { userId: initialUserId, externalId: initialUserId, deviceId };\n }\n return { userId: crypto.randomUUID(), externalId: null, deviceId };\n }\n if (savedData.externalId !== initialUserId) {\n // If the externalId is the same as the initialUserId, we can use the saved userId\n return { userId: savedData.userId, externalId: initialUserId, deviceId };\n }\n return {\n userId: savedData.userId,\n externalId: savedData.externalId,\n deviceId,\n };\n}\n\n/**\n * Hook that manage to generate the userId and deviceId, this should be the source of truth when dealing with user identity\n * @returns\n */\nexport function useUserIdentity(\n options: UserIdentityOptions,\n): UserIdentityReturn {\n const { appId, initialUserId } = options;\n\n const { getSavedChatData } = usePersistence({ appId });\n\n // Resolved synchronously (localStorage reads are synchronous) so dependents\n // — the SDK boot effect — can start on the first commit instead of waiting\n // an extra render for a mount effect to fill the identity in.\n const [identity, setIdentity] = useState<ResolvedIdentity>(() =>\n resolveUserIdentity(getSavedChatData(), initialUserId),\n );\n\n // Host apps may pass `userId` late (e.g. after an async login). Re-resolve\n // during render (React's alternative to a mirror effect).\n const [prevInitialUserId, setPrevInitialUserId] = useState(initialUserId);\n if (prevInitialUserId !== initialUserId) {\n setPrevInitialUserId(initialUserId);\n setIdentity(resolveUserIdentity(getSavedChatData(), initialUserId));\n }\n\n return {\n // Identity is available synchronously; kept in the contract because\n // consumers (SDK boot) still key off it.\n isReady: true,\n userId: identity.userId,\n deviceId: identity.deviceId,\n externalId: identity.externalId,\n };\n}\n","\"use client\";\n\nimport { useEffect, useRef, useState } from \"react\";\n\nimport { Message } from \"@/types/message\";\n\nimport { getApiUrl } from \"@/lib/config\";\nimport {\n BootResponse,\n EloquentAiApiClient,\n} from \"@/lib/eloquent-ai-api-client\";\nimport { wrapPromise } from \"@/lib/wrap-promise\";\nimport { withRetry } from \"@/lib/retry\";\n\nimport { useFetch } from \"@/hooks/use-fetch\";\n\nimport { createWelcomeMessage } from \"../message-mapping\";\nimport { usePersistence } from \"./use-persistence\";\nimport { useUserIdentity } from \"./use-user-identity\";\n\nexport interface UseSdkInitializationProps {\n environment: \"test\" | \"live\";\n apiUrl?: string;\n appId: string;\n initialUserId?: string;\n userName?: string;\n userData?: Record<string, string | number | boolean>;\n}\n\nexport interface UseSdkInitializationReturn {\n userId: string;\n userName?: string;\n userData?: Record<string, string | number | boolean>;\n externalId?: string | null;\n deviceId: string;\n apiClient: EloquentAiApiClient | null;\n chatSettings: BootResponse[\"chat_settings\"] | null;\n currentChat: { id: string } | null;\n messages: Message[];\n isReady: boolean;\n isChatClosed: boolean;\n isChatActive: boolean;\n}\n\n/**\n * Hook to handle SDK initialization for the EloquentAI Chat SDK\n * Handles API client initialization, saved conversation restoration, and SDK boot\n */\nexport function useSdkInitialization({\n apiUrl: apiUrlOverride,\n appId,\n initialUserId,\n userName,\n userData,\n}: UseSdkInitializationProps): UseSdkInitializationReturn {\n // Get a pair of userId and deviceId\n const {\n userId,\n externalId,\n deviceId,\n isReady: isUserIdentityReady,\n } = useUserIdentity({ appId, initialUserId });\n\n const { isChatExpired, clearChatData, getSavedChatData } = usePersistence({\n appId,\n });\n\n const { current: apiUrl } = useRef(apiUrlOverride || getApiUrl());\n const [apiClient] = useState<EloquentAiApiClient>(\n new EloquentAiApiClient({\n baseURL: apiUrl,\n appId: appId,\n }),\n );\n const [chatSettings, setChatSettings] = useState<\n BootResponse[\"chat_settings\"] | null\n >(null);\n const [currentChat, setCurrentChat] = useState<{\n id: string;\n } | null>(null);\n const [messages, setMessages] = useState<Message[]>([]);\n const [isReady, setIsReady] = useState(false);\n const [isChatClosed, setIsChatClosed] = useState(false);\n const [isChatActive, setIsChatActive] = useState(true);\n\n // Use a unique key to differentiate between Chat SDK instances with different appIds\n const sdkBoot = useFetch(`sdk-boot-${appId}`, () => apiClient.boot());\n const sdkBootFetch = sdkBoot.fetch;\n\n // Initialize API client on the client side only\n useEffect(() => {\n // Check if there's an existing conversation and if it's not expired\n if (!isChatExpired()) {\n const {\n conversationId: chatId,\n userId,\n messages: savedMessages,\n isChatClosed: savedIsChatClosed,\n chatToken: savedChatToken,\n } = getSavedChatData();\n\n if (chatId && userId) {\n setCurrentChat({\n id: chatId,\n });\n apiClient.setChatToken(savedChatToken ?? null);\n\n // If we have saved messages, use them\n if (savedMessages && savedMessages.length > 0) {\n setMessages(savedMessages);\n }\n\n if (savedIsChatClosed) {\n setIsChatClosed(true);\n }\n }\n } else {\n // Clear expired conversation data\n clearChatData();\n // The next API call will automatically generate a new device ID\n }\n }, [getSavedChatData, isChatExpired, clearChatData, apiClient]);\n\n // Boot the SDK exactly once, when the user identity becomes available. The\n // ref guard (rather than deps alone) keeps re-renders from re-firing the\n // org + boot requests: sdkBootFetch gets a new identity every render, so\n // without the guard the effect would re-run constantly.\n const hasBootedRef = useRef(false);\n useEffect(() => {\n if (!isUserIdentityReady || hasBootedRef.current) return;\n hasBootedRef.current = true;\n\n const bootSDK = async () => {\n // Step 1: Fetch organization data to get region\n const [orgResponse, orgError] = await wrapPromise(\n withRetry(() => apiClient.getOrganizationByAppId(appId)),\n );\n\n if (orgError) {\n console.error(\"Failed to fetch organization data:\", orgError);\n setIsChatActive(false);\n setIsReady(true);\n return;\n }\n\n // Step 2: Store region for subsequent API calls\n apiClient.setRegion(orgResponse.region);\n\n // Step 3: Now call boot endpoint\n const [response, error] = await wrapPromise(withRetry(sdkBootFetch));\n\n if (error) {\n setIsChatActive(false);\n setIsReady(true);\n return;\n }\n\n const welcomeMessage = response.chat_settings.welcome_message;\n\n setChatSettings(response.chat_settings);\n setIsChatActive(response.chat_settings.is_active ?? true);\n\n // Only set welcome message if we don't already have one (functional update to avoid race conditions)\n if (welcomeMessage) {\n setMessages((prev) => {\n if (prev.length > 0 || prev.some((m) => m.isWelcomeMessage))\n return prev;\n return [createWelcomeMessage(welcomeMessage)];\n });\n }\n\n setIsReady(true);\n };\n\n bootSDK();\n }, [isUserIdentityReady, apiClient, appId, sdkBootFetch]);\n\n return {\n userId,\n userName,\n userData,\n externalId,\n deviceId,\n apiClient,\n chatSettings,\n currentChat,\n messages,\n isReady,\n isChatClosed,\n isChatActive,\n };\n}\n","\"use client\";\n\nimport { useEffect, useState } from \"react\";\n\n// Matches Tailwind's `sm` breakpoint; kept in sync with the mobile-only CSS rules.\nconst MOBILE_MEDIA_QUERY = \"(max-width: 640px)\";\n\n// matchMedia (not window.innerWidth) so the check reflects the actual visual\n// viewport used for layout on mobile browsers (browser chrome, pinch-zoom,\n// display-zoom accessibility settings), and computed lazily so the very first\n// render already reflects the real device instead of defaulting to desktop.\nfunction getIsMobileScreen(): boolean {\n if (typeof window === \"undefined\") return false;\n return window.matchMedia(MOBILE_MEDIA_QUERY).matches;\n}\n\n/**\n * Hook to handle UI initialization for the chat component\n * Handles mobile detection and portal container creation\n */\nexport function useUiInitialization(propIsMobile?: boolean): {\n isMobileScreen: boolean;\n isMobile: boolean;\n portalContainer: HTMLElement | null;\n} {\n const [isMobileScreen, setIsMobileScreen] = useState(getIsMobileScreen);\n const [portalContainer, setPortalContainer] = useState<HTMLElement | null>(\n null,\n );\n\n // Determine if mobile based on prop or screen size\n const isMobile = propIsMobile ?? isMobileScreen;\n\n const isSSR = typeof window === \"undefined\";\n\n // Check if the screen is mobile, and keep it in sync as the viewport changes\n useEffect(() => {\n if (isSSR) return;\n\n const mediaQueryList = window.matchMedia(MOBILE_MEDIA_QUERY);\n const handleChange = (event: MediaQueryList | MediaQueryListEvent) => {\n setIsMobileScreen(event.matches);\n };\n\n handleChange(mediaQueryList);\n mediaQueryList.addEventListener(\"change\", handleChange);\n return () => mediaQueryList.removeEventListener(\"change\", handleChange);\n }, [isSSR]);\n\n // Create a container for the chat interface\n useEffect(() => {\n if (isSSR) return;\n\n const container = document.createElement(\"div\");\n container.className = \"eloquent-ai-chat-portal\";\n container.style.position = \"relative\";\n container.style.zIndex = \"30\";\n document.body.appendChild(container);\n setPortalContainer(container);\n\n return () => {\n if (container.parentElement) {\n container.parentElement.removeChild(container);\n }\n };\n }, [isSSR]);\n\n return {\n isMobileScreen,\n isMobile,\n portalContainer,\n };\n}\n","\"use client\";\n\nimport { useDebounce } from \"@/hooks/use-debounce\";\nimport { useCallback, useEffect, useRef, useState } from \"react\";\n\nimport { Message, MessageData } from \"@/types/message\";\n\nimport { ThemeContextType } from \"@/contexts/theme.context\";\n\nimport { ChatInterfaceProps } from \"@/components/chat-interface\";\n\nimport { deleteCookie, getCookie, setCookie } from \"@/lib/cookies\";\n\nimport { useInterfaceProps } from \"./use-interface-props\";\nimport { useMessageEvents } from \"./use-message-events\";\nimport { useSdkInitialization } from \"./use-sdk-initialization\";\nimport { useUiInitialization } from \"./use-ui-initialization\";\n\n// How long we remember that the user closed the chat widget\nconst CHAT_CLOSED_COOKIE_TTL_HOURS = 2;\nconst getChatClosedCookieName = (appId: string) =>\n `eloquent-ai:chat-widget-closed-${appId}`;\n\nexport interface UseChatProps {\n appId: string;\n userId?: string;\n userName?: string;\n userData?: Record<string, string | number | boolean>;\n theme?: Partial<ThemeContextType>;\n chatProps?: Partial<ChatInterfaceProps>;\n isMobile?: boolean;\n /** Show the close (X) button in the chat header. */\n hasCloseButton?: boolean;\n /** Show the clear-conversation button in the chat header. */\n hasCleanChatButton?: boolean;\n /** Open the chat window on load (desktop only). */\n isInitiallyOpen?: boolean;\n /** @deprecated Use `hasCloseButton` instead. Ignored when `hasCloseButton` is set. */\n closeButton?: boolean;\n /** @deprecated Use `hasCleanChatButton` instead. Ignored when `hasCleanChatButton` is set. */\n cleanChatButton?: boolean;\n /** @deprecated Use `isInitiallyOpen` instead. Ignored when `isInitiallyOpen` is set. */\n initialOpen?: boolean;\n proactiveMessageHideDelay?: number;\n}\n\nexport interface UseChatReturn {\n isReady: boolean;\n isChatActive: boolean;\n /** Effective initial-open (boot chat_settings.initial_open ?? prop). */\n isInitiallyOpen: boolean;\n /** Effective close-button visibility (boot chat_settings.close_button ?? prop). */\n hasCloseButton: boolean;\n /** Effective clear-chat-button visibility (boot chat_settings.clean_chat_button ?? prop). */\n hasCleanChatButton: boolean;\n isMobile: boolean;\n chatInterfaceProps: Partial<ChatInterfaceProps>;\n chatOpen: boolean;\n chatOpenDebounced: boolean;\n messages: Message[];\n portalContainer: HTMLElement | null;\n onSendMessage: (message: MessageData) => Promise<void>;\n setChatOpen: (value: boolean | ((prev: boolean) => boolean)) => void;\n onCleanMessages: () => void;\n proactiveMessage?: {\n text: string;\n isVisible: boolean;\n autoHideDelay: number;\n };\n hideProactiveMessage: () => void;\n isChatClosed: boolean;\n onStartNewChat: () => void;\n onRateChat: (rating: number) => Promise<void>;\n}\n\n/**\n * The primary chat hook, responsible for managing the chat state and operations.\n * @param options The hook parameters\n * @returns The chat hook return type\n */\nexport function useChat({\n environment,\n apiUrl,\n appId,\n userId: initialUserId,\n userName,\n userData,\n chatProps,\n isMobile: propIsMobile,\n isInitiallyOpen: propIsInitiallyOpen,\n hasCloseButton: propHasCloseButton,\n hasCleanChatButton: propHasCleanChatButton,\n // Deprecated aliases, kept until hosts migrate to the is/has names above.\n initialOpen: deprecatedInitialOpen,\n closeButton: deprecatedCloseButton,\n cleanChatButton: deprecatedCleanChatButton,\n proactiveMessageHideDelay: propProactiveMessageHideDelay = 5000,\n isAlwaysOpen = false,\n hasCleanChatButtonOverride,\n}: Readonly<\n Partial<UseChatProps> & {\n environment: \"test\" | \"live\";\n apiUrl?: string;\n appId: string;\n /**\n * Internal-only kill-switch (INTERNAL_ONLY_SHOW_CLEAN_CHAT_BUTTON): when\n * set, wins over both the boot `chat_settings.clean_chat_button` and the\n * `hasCleanChatButton` prop. Leave undefined for the normal boot ?? prop\n * resolution.\n */\n hasCleanChatButtonOverride?: boolean;\n /**\n * Embedded mode (INTERNAL_ONLY_CHAT_INTERFACE_ONLY): the interface is the\n * page content and there is no launcher bubble to reopen a closed chat, so\n * open/close state does not apply — not the isInitiallyOpen prop, not the\n * boot `chat_settings.initial_open`, and not the closed-cookie. Without\n * this, a boot `initial_open: false` closes the widget from under the\n * host page a moment after it renders.\n */\n isAlwaysOpen?: boolean;\n }\n>): UseChatReturn {\n // Use UI initialization hook for mobile detection and portal container\n const { isMobile, portalContainer } = useUiInitialization(propIsMobile);\n\n // Use SDK initialization hook for API client, chat settings and conversation state\n const {\n userId,\n externalId,\n deviceId,\n apiClient,\n chatSettings,\n currentChat: initialChat,\n messages: initialMessages,\n isReady,\n isChatClosed: initialIsChatClosed,\n isChatActive,\n } = useSdkInitialization({\n environment,\n apiUrl,\n appId,\n initialUserId,\n userName,\n userData,\n });\n\n // Generate chat interface props\n const chatInterfaceProps = useInterfaceProps({ chatProps, chatSettings });\n\n // The is/has names are canonical; the deprecated aliases only apply when\n // the new name is absent.\n const propInitialOpen = propIsInitiallyOpen ?? deprecatedInitialOpen ?? false;\n const propCloseButton = propHasCloseButton ?? deprecatedCloseButton ?? true;\n const propCleanChatButton =\n propHasCleanChatButton ?? deprecatedCleanChatButton ?? true;\n\n const chatClosedCookieName = getChatClosedCookieName(appId);\n\n const [chatOpen, setChatOpenState] = useState(() => {\n if (isAlwaysOpen) return true;\n if (getCookie(chatClosedCookieName) === \"true\") return false;\n return isMobile ? false : (propInitialOpen ?? isMobile);\n });\n\n // The server can also drive the initial open (chat_settings.initial_open).\n // The boot value wins over the prop, but NOT over the user's 2-hour\n // closed-cookie: if the user explicitly closed the widget, a boot `true`\n // must not reopen it on the next page. A boot `false` still applies (the\n // server force-closing never fights the user). Boot resolves after mount,\n // so apply it once when settings arrive. The mobile guard also remains (a\n // full-screen overlay opening uninvited on mobile is too disruptive). Uses\n // the raw setter so a server-driven open/close never writes the closed\n // cookie itself.\n const [hasAppliedBootInitialOpen, setHasAppliedBootInitialOpen] =\n useState(false);\n useEffect(() => {\n if (!isReady || hasAppliedBootInitialOpen) return;\n setHasAppliedBootInitialOpen(true);\n\n if (isAlwaysOpen) return;\n const bootInitialOpen = chatSettings?.initial_open;\n if (bootInitialOpen == null) return;\n if (isMobile) return;\n if (bootInitialOpen && getCookie(chatClosedCookieName) === \"true\") return;\n setChatOpenState(bootInitialOpen);\n }, [\n isReady,\n hasAppliedBootInitialOpen,\n chatSettings?.initial_open,\n isMobile,\n chatClosedCookieName,\n isAlwaysOpen,\n ]);\n\n // Effective value (boot ?? prop) — e.g. the proactive message is\n // suppressed when the chat starts open.\n const isInitiallyOpen = chatSettings?.initial_open ?? propInitialOpen;\n\n // Same server-wins pattern for the header buttons and the proactive\n // message delay: an explicit boot value (including false) beats the prop.\n const hasCloseButton = chatSettings?.close_button ?? propCloseButton;\n // The internal-only override (when set) beats both boot and prop.\n const hasCleanChatButton =\n hasCleanChatButtonOverride ??\n chatSettings?.clean_chat_button ??\n propCleanChatButton;\n const proactiveMessageHideDelay =\n chatSettings?.proactive_message_hide_delay ?? propProactiveMessageHideDelay;\n\n // Wrap the setter so that closing the chat widget is remembered for 2\n // hours, and reopening it clears that memory. In always-open (embedded)\n // mode the widget cannot close at all, and must not write the closed-cookie\n // — it would leak into the real launcher widget for the same appId.\n const setChatOpen = useCallback<\n (value: boolean | ((prev: boolean) => boolean)) => void\n >(\n (value) => {\n if (isAlwaysOpen) return;\n setChatOpenState((prev) => {\n const next = typeof value === \"function\" ? value(prev) : value;\n if (next) {\n deleteCookie(chatClosedCookieName);\n } else {\n setCookie(chatClosedCookieName, \"true\", CHAT_CLOSED_COOKIE_TTL_HOURS);\n }\n return next;\n });\n },\n [chatClosedCookieName, isAlwaysOpen],\n );\n\n const chatOpenDebounced = useDebounce(chatOpen, 400);\n const [messages, setMessages] = useState<Message[]>(\n chatProps?.messages ?? [],\n );\n const [currentChat, setCurrentChat] = useState<{\n id: string;\n } | null>(initialChat);\n\n const [isChatClosed, setIsChatClosed] = useState(false);\n\n // Adopt values arriving asynchronously from SDK initialization (localStorage\n // restore, boot welcome message) into the locally-owned state. setState\n // during render instead of mirror effects: React restarts the render\n // immediately, so consumers never see the stale value for a frame.\n const [prevInitialMessages, setPrevInitialMessages] =\n useState(initialMessages);\n if (prevInitialMessages !== initialMessages) {\n setPrevInitialMessages(initialMessages);\n if (initialMessages.length > 0) setMessages(initialMessages);\n }\n\n const [prevInitialChat, setPrevInitialChat] = useState(initialChat);\n if (prevInitialChat !== initialChat) {\n setPrevInitialChat(initialChat);\n if (initialChat) setCurrentChat(initialChat);\n }\n\n // Restore the \"chat closed\" state saved to localStorage, so it survives a\n // page refresh.\n const [prevInitialIsChatClosed, setPrevInitialIsChatClosed] =\n useState(initialIsChatClosed);\n if (prevInitialIsChatClosed !== initialIsChatClosed) {\n setPrevInitialIsChatClosed(initialIsChatClosed);\n if (initialIsChatClosed) setIsChatClosed(true);\n }\n\n const handleChatClosed = useCallback(() => {\n setIsChatClosed(true);\n }, []);\n\n // The proactive (welcome) bubble is fully derived from boot settings; the\n // only real state is whether the user dismissed it.\n const [hasDismissedProactiveMessage, setHasDismissedProactiveMessage] =\n useState(false);\n const proactiveMessageText =\n isReady &&\n chatSettings?.auto_display_welcome_message &&\n chatSettings?.welcome_message\n ? chatSettings.welcome_message\n : \"\";\n const proactiveMessage = {\n text: proactiveMessageText,\n isVisible: proactiveMessageText !== \"\" && !hasDismissedProactiveMessage,\n autoHideDelay: proactiveMessageHideDelay,\n };\n\n // Use message events hook for sending and cleaning messages\n const { onSendMessage, onCleanMessages, onRateChat } = useMessageEvents({\n appId,\n userId,\n userName,\n userData,\n externalId,\n deviceId,\n apiClient,\n chatSettings,\n setMessages,\n messages,\n currentChat,\n setCurrentChat,\n onChatClosed: handleChatClosed,\n isChatClosed,\n });\n\n // Sync with initialMessages when they change (from SDK initialization)\n useEffect(() => {\n if (initialMessages.length > 0) {\n setMessages(initialMessages);\n }\n }, [initialMessages]);\n\n useEffect(() => {\n if (initialChat) {\n setCurrentChat(initialChat);\n }\n }, [initialChat]);\n\n // Identify the user once per distinct payload. Host apps often recreate the\n // `userData` object every render, so comparing by value (not identity)\n // prevents a duplicate network call per re-render.\n const lastIdentifyKeyRef = useRef<string | null>(null);\n useEffect(() => {\n if (!currentChat || !externalId || !apiClient) return;\n\n const identifyPayload = {\n userId,\n userName,\n userData,\n externalId,\n deviceId,\n conversationId: currentChat.id,\n };\n const identifyKey = JSON.stringify(identifyPayload);\n if (lastIdentifyKeyRef.current === identifyKey) return;\n lastIdentifyKeyRef.current = identifyKey;\n\n apiClient.identifyUser(identifyPayload);\n }, [\n externalId,\n userId,\n userName,\n userData,\n deviceId,\n currentChat,\n apiClient,\n ]);\n\n const onStartNewChat = useCallback(() => {\n onCleanMessages();\n setIsChatClosed(false);\n }, [onCleanMessages]);\n\n const hideProactiveMessage = useCallback(() => {\n setHasDismissedProactiveMessage(true);\n }, []);\n\n return {\n isReady,\n isChatActive,\n isInitiallyOpen,\n hasCloseButton,\n hasCleanChatButton,\n isMobile,\n chatInterfaceProps,\n chatOpen,\n chatOpenDebounced,\n messages,\n portalContainer,\n onSendMessage,\n setChatOpen,\n onCleanMessages,\n proactiveMessage,\n hideProactiveMessage,\n isChatClosed,\n onStartNewChat,\n onRateChat,\n };\n}\n","\"use client\";\n\nimport { useEffect, useState } from \"react\";\n\n/**\n * Tracks how much the on-screen keyboard overlaps the layout viewport, using\n * the VisualViewport API. Used to lift the chat input above the keyboard\n * without moving/resizing the rest of the chat window.\n */\nexport function useKeyboardInset(enabled: boolean): number {\n const [inset, setInset] = useState(0);\n\n useEffect(() => {\n const viewport = window.visualViewport;\n if (!enabled || !viewport) {\n setInset(0);\n return;\n }\n\n const update = () => {\n const overlap = window.innerHeight - viewport.height - viewport.offsetTop;\n setInset(Math.max(0, Math.round(overlap)));\n };\n\n update();\n viewport.addEventListener(\"resize\", update);\n viewport.addEventListener(\"scroll\", update);\n\n return () => {\n viewport.removeEventListener(\"resize\", update);\n viewport.removeEventListener(\"scroll\", update);\n setInset(0);\n };\n }, [enabled]);\n\n return inset;\n}\n","\"use client\";\n\nimport { useEffect } from \"react\";\n\n/**\n * Locks scrolling on the host page while active. Uses the fixed-body trick\n * (rather than plain `overflow: hidden`) so it also holds on iOS Safari,\n * which otherwise still allows background scroll/bounce behind the chat.\n */\nexport function useScrollLock(locked: boolean) {\n useEffect(() => {\n if (!locked) return;\n\n const { body } = document;\n const scrollY = window.scrollY;\n const previousStyle = {\n position: body.style.position,\n top: body.style.top,\n left: body.style.left,\n right: body.style.right,\n overflow: body.style.overflow,\n };\n\n body.style.position = \"fixed\";\n body.style.top = `-${scrollY}px`;\n body.style.left = \"0\";\n body.style.right = \"0\";\n body.style.overflow = \"hidden\";\n\n return () => {\n body.style.position = previousStyle.position;\n body.style.top = previousStyle.top;\n body.style.left = previousStyle.left;\n body.style.right = previousStyle.right;\n body.style.overflow = previousStyle.overflow;\n window.scrollTo(0, scrollY);\n };\n }, [locked]);\n}\n","import { useCallback, useRef, useState } from \"react\";\n\nexport interface UseAgentCognitionReturn {\n isVisible: boolean;\n content: string | null;\n showCognition: (content?: string) => void;\n hideCognition: () => void;\n}\n\nexport function useAgentCognition(): UseAgentCognitionReturn {\n const [isVisible, setIsVisible] = useState(false);\n const [content, setContent] = useState<string | null>(null);\n const timerRef = useRef<NodeJS.Timeout | null>(null);\n const pendingContentRef = useRef<string | null>(null);\n\n const showCognition = useCallback((newContent = \"...\") => {\n const updateCognition = () => {\n setContent(newContent);\n setIsVisible(true);\n pendingContentRef.current = null;\n\n // Clear existing timer\n if (timerRef.current) {\n clearTimeout(timerRef.current);\n }\n\n // Set timer to allow updates after 1 second minimum display time\n timerRef.current = setTimeout(() => {\n timerRef.current = null;\n\n // If there's pending content, show it immediately\n if (pendingContentRef.current) {\n updateCognition();\n }\n }, 1000);\n };\n\n // If no timer is active, update immediately\n if (!timerRef.current) {\n updateCognition();\n } else {\n // Timer is active, queue the new content\n pendingContentRef.current = newContent;\n }\n }, []);\n\n const hideCognition = useCallback(() => {\n // Clear timer and pending content\n if (timerRef.current) {\n clearTimeout(timerRef.current);\n timerRef.current = null;\n }\n pendingContentRef.current = null;\n\n // Hide cognition\n setIsVisible(false);\n setContent(null);\n }, []);\n\n return {\n isVisible,\n content,\n showCognition,\n hideCognition,\n };\n}\n","import { ReactNode } from \"react\";\nimport { useAgentCognition } from \"@/contexts/agent-cognition/use-agent-cognition\";\nimport { AgentCognitionContext } from \"./agent-cognition-context\";\n\ninterface AgentCognitionProviderProps {\n children: ReactNode;\n}\n\nexport function AgentCognitionProvider({\n children,\n}: AgentCognitionProviderProps) {\n const cognition = useAgentCognition();\n\n return (\n <AgentCognitionContext.Provider value={cognition}>\n {children}\n </AgentCognitionContext.Provider>\n );\n}\n","import { useState, type ReactNode } from \"react\";\nimport { ErrorContext, SdkError, createPublishApiError } from \"./error-context\";\n\nexport const ErrorProvider = ({ children }: { children: ReactNode }) => {\n const [error, setError] = useState<SdkError | null>(null);\n const [hideSdk, setHideSdk] = useState(false);\n\n const publishApiError = createPublishApiError(setError);\n const publishError = (error: SdkError) => setError(error);\n const publishNetworkError = () => setHideSdk(true);\n const clearError = () => setError(null);\n\n const contextValue = {\n error,\n hideSdk,\n publishApiError,\n publishError,\n publishNetworkError,\n clearError,\n };\n\n return (\n <ErrorContext.Provider value={contextValue}>\n {children}\n </ErrorContext.Provider>\n );\n};\n","\"use client\";\n\nimport { type CSSProperties } from \"react\";\n\nimport mainCSS from \"@/index.css?inline\";\nimport wrapperCSS from \"@/wrapper.css?inline\";\n\nimport { Message } from \"@/types/message\";\n\nimport { cn } from \"@/lib/utils\";\n\nimport { ChatBubble } from \"@/components/embed/chat-bubble\";\nimport { ChatInterface } from \"@/components/chat-interface\";\nimport { SkeletonChatInterface } from \"@/components/chat-interface/skeleton\";\nimport { Iframe } from \"@/components/embed/iframe\";\nimport { Portal } from \"@/components/embed/portal\";\nimport { ProactiveMessage } from \"@/components/embed/proactive-message\";\n\nimport { useChat, type UseChatProps } from \"@/components/chat/hooks/use-chat\";\nimport { useKeyboardInset } from \"@/components/chat/hooks/use-keyboard-inset\";\nimport { useScrollLock } from \"@/components/chat/hooks/use-scroll-lock\";\nimport { AgentCognitionProvider } from \"@/contexts/agent-cognition/agent-cognition-provider\";\nimport { ErrorProvider } from \"@/contexts/error-handling/error-provider\";\nimport { useErrorContext } from \"@/contexts/error-handling/error-context\";\nimport { ThemeProvider } from \"@/contexts/theme.context\";\n\n/** Viewport inset (px) used to cap desktop chat height so it doesn’t overflow. */\nconst CHAT_DESKTOP_VIEWPORT_INSET_PX = 100;\n\n/** @internal */\ntype InternalChatProps = {\n INTERNAL_ONLY_CHAT_INTERFACE_ONLY?: boolean;\n INTERNAL_ONLY_BLOCK_STYLE?: boolean;\n /**\n * Force the clear-chat button on or off, winning over both the boot\n * `chat_settings.clean_chat_button` and the public `hasCleanChatButton`\n * prop. Leave unset to keep the normal boot ?? prop resolution.\n */\n INTERNAL_ONLY_SHOW_CLEAN_CHAT_BUTTON?: boolean;\n /** Show the copy-message button on assistant messages (default false). */\n INTERNAL_ONLY_SHOW_COPY_BUTTON?: boolean;\n INTERNAL_ONLY_ENVIRONMENT?: \"test\" | \"live\";\n INTERNAL_ONLY_API_URL?: string;\n INTERNAL_ONLY_FEATURE_MESSAGE_CLICK?: (message: Message) => void;\n INTERNAL_ONLY_FEATURE_CLEAR_CHAT_CLICK?: () => void;\n};\n\nexport type ChatProps = UseChatProps & InternalChatProps;\n\nfunction InternalChat({\n appId,\n userId,\n userName,\n userData,\n chatProps,\n proactiveMessageHideDelay = 5000,\n isMobile: propIsMobile,\n hasCloseButton: propHasCloseButton,\n hasCleanChatButton: propHasCleanChatButton,\n isInitiallyOpen: propIsInitiallyOpen,\n // Deprecated aliases, resolved in useChat (new name wins).\n closeButton: deprecatedCloseButton,\n cleanChatButton: deprecatedCleanChatButton,\n initialOpen: deprecatedInitialOpen,\n INTERNAL_ONLY_CHAT_INTERFACE_ONLY = false,\n INTERNAL_ONLY_SHOW_CLEAN_CHAT_BUTTON = undefined,\n INTERNAL_ONLY_BLOCK_STYLE = false,\n INTERNAL_ONLY_FEATURE_MESSAGE_CLICK = undefined,\n INTERNAL_ONLY_FEATURE_CLEAR_CHAT_CLICK = undefined,\n INTERNAL_ONLY_SHOW_COPY_BUTTON = false,\n INTERNAL_ONLY_ENVIRONMENT = \"live\",\n INTERNAL_ONLY_API_URL,\n}: Readonly<UseChatProps & InternalChatProps>) {\n const { hideSdk } = useErrorContext();\n\n const {\n isReady,\n isChatActive,\n isInitiallyOpen,\n hasCloseButton,\n hasCleanChatButton,\n isMobile,\n chatOpen,\n chatInterfaceProps,\n chatOpenDebounced,\n messages,\n portalContainer,\n onSendMessage,\n setChatOpen,\n proactiveMessage,\n hideProactiveMessage,\n isChatClosed,\n onStartNewChat,\n onRateChat,\n } = useChat({\n environment: INTERNAL_ONLY_ENVIRONMENT,\n apiUrl: INTERNAL_ONLY_API_URL,\n appId,\n userId,\n userName,\n userData,\n chatProps,\n isMobile: propIsMobile,\n isInitiallyOpen: propIsInitiallyOpen,\n hasCloseButton: propHasCloseButton,\n hasCleanChatButton: propHasCleanChatButton,\n initialOpen: deprecatedInitialOpen,\n closeButton: deprecatedCloseButton,\n cleanChatButton: deprecatedCleanChatButton,\n proactiveMessageHideDelay,\n // Embedded: the interface is the page content with no launcher to reopen\n // it, so nothing (boot initial_open, closed-cookie, props) may close it.\n isAlwaysOpen: INTERNAL_ONLY_CHAT_INTERFACE_ONLY,\n hasCleanChatButtonOverride: INTERNAL_ONLY_SHOW_CLEAN_CHAT_BUTTON,\n });\n\n const keyboardInset = useKeyboardInset(isMobile && chatOpen);\n useScrollLock(isMobile && chatOpen);\n\n const isBooting = !isReady;\n\n if (hideSdk) return null;\n // The launcher widget renders nothing until boot decides what to show. In\n // embedded mode the widget IS the page content: rendering null while a\n // remount boots (project/environment switch in the host app) collapses the\n // layout and flashes an empty hole — show the skeleton in place instead.\n if (isBooting && !INTERNAL_ONLY_CHAT_INTERFACE_ONLY) return null;\n if (!isBooting && !isChatActive) return null;\n\n const renderContent = () => {\n return (\n <div\n style={{\n WebkitTouchCallout: \"none\" /* iOS Safari */,\n WebkitUserSelect: \"none\" /* Safari */,\n KhtmlUserSelect: \"none\" /* Konqueror HTML */,\n MozUserSelect: \"none\" /* Old versions of Firefox */,\n msUserSelect: \"none\" /* Internet Explorer/Edge */,\n userSelect: \"none\" /* Chrome, Edge, Opera and Firefox */,\n position: \"fixed\",\n right: 12,\n bottom: 4,\n ...(INTERNAL_ONLY_BLOCK_STYLE\n ? { position: \"relative\", inset: 0, width: \"100%\", height: \"100%\" }\n : {}),\n }}\n >\n <style>{wrapperCSS}</style>\n <Iframe\n className=\"eloquentai-chat-messaging\"\n head={\n <>\n <link rel=\"preconnect\" href=\"https://fonts.googleapis.com\" />\n <link rel=\"preconnect\" href=\"https://fonts.gstatic.com\" />\n <link\n href=\"https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&display=swap\"\n rel=\"stylesheet\"\n />\n <style>{mainCSS}</style>\n </>\n }\n style={\n {\n display: chatOpen\n ? \"block\"\n : chatOpenDebounced\n ? \"block\"\n : \"none\",\n width: isMobile ? \"100vw\" : \"400px\",\n // 100dvh accounts for mobile browser chrome (e.g. address bar); 100vh fallback for older browsers\n \"--chat-mobile-viewport-height\": \"100dvh\",\n height: isMobile\n ? \"var(--chat-mobile-viewport-height, 100vh)\"\n : \"700px\",\n maxHeight: isMobile\n ? \"var(--chat-mobile-viewport-height, 100vh)\"\n : `calc(100% - ${CHAT_DESKTOP_VIEWPORT_INSET_PX}px)`,\n border: \"none\",\n zIndex: 2147483000,\n position: \"fixed\",\n top: isMobile ? 0 : undefined,\n left: isMobile ? 0 : undefined,\n right: isMobile ? 0 : 16,\n bottom: isMobile ? 0 : 16,\n ...(INTERNAL_ONLY_BLOCK_STYLE\n ? {\n position: \"relative\",\n top: 0,\n left: 0,\n right: 0,\n bottom: 0,\n width: \"100%\",\n height: \"100%\",\n maxHeight: \"100%\",\n zIndex: 0,\n }\n : {}),\n } as CSSProperties\n }\n >\n {isBooting ? (\n // Only reachable in embedded mode (the launcher returns null while\n // booting): hold the widget's frame with a skeleton so a remount —\n // project/environment switch in the host app — doesn't flash an\n // empty hole where the chat was.\n <SkeletonChatInterface isOpen isMobile={isMobile} skipAnimation />\n ) : (\n <ChatInterface\n {...chatInterfaceProps}\n // Embedded (interface-only) mode renders as page content: no\n // popup-style panel entrance.\n hasIntroAnimation={!INTERNAL_ONLY_CHAT_INTERFACE_ONLY}\n // Caution stripe: a session against the test agent must never be\n // mistaken for the production one.\n isTestMode={INTERNAL_ONLY_ENVIRONMENT === \"test\"}\n isOpen={chatOpen}\n keyboardInset={keyboardInset}\n messages={messages}\n onSendMessage={onSendMessage}\n onMessageClick={INTERNAL_ONLY_FEATURE_MESSAGE_CLICK}\n isMobile={isMobile}\n hasCloseButton={hasCloseButton}\n hasCleanChatButton={hasCleanChatButton}\n hasCopyButton={INTERNAL_ONLY_SHOW_COPY_BUTTON}\n isChatClosed={isChatClosed}\n onStartNewChat={onStartNewChat}\n onRateChat={onRateChat}\n onClose={() => setChatOpen(false)}\n onCleanChat={() => {\n onStartNewChat();\n INTERNAL_ONLY_FEATURE_CLEAR_CHAT_CLICK?.();\n }}\n />\n )}\n </Iframe>\n {!INTERNAL_ONLY_CHAT_INTERFACE_ONLY && (\n <Iframe\n className=\"eloquentai-chat-launcher\"\n head={<style>{mainCSS}</style>}\n style={{\n position: \"fixed\",\n bottom: 17,\n right: 17,\n display: \"block\",\n width: 48,\n height: 48,\n border: \"none\",\n zIndex: isMobile ? 2147482999 : 2147483000,\n opacity: chatOpen ? 0 : 1,\n pointerEvents: chatOpen ? \"none\" : \"auto\",\n transition: chatOpen\n ? \"opacity 100ms ease-in\"\n : \"opacity 200ms ease-out 320ms\",\n }}\n >\n <ChatBubble\n isOpen={chatOpen}\n toggleBubble={() => setChatOpen((prev) => !prev)}\n isDarkMode={chatInterfaceProps?.theme?.mode === \"dark\"}\n />\n </Iframe>\n )}\n {chatInterfaceProps?.displayWelcomeMessages ? (\n <Iframe\n className=\"eloquentai-chat-proactive-message\"\n head={<style>{mainCSS}</style>}\n style={{\n position: \"fixed\",\n // Aligns the bubble's tail with the launcher's center: the\n // launcher circle is 48px tall at bottom:17, so its center is\n // ~41px up; the tail sits ~16px above this iframe's bottom.\n bottom: 24,\n right: 17,\n }}\n >\n <ThemeProvider {...(chatInterfaceProps?.theme ?? {})}>\n {/* This iframe is outside the chat interface's dark-classed\n <main>, so dark: utilities need their own ancestor here. */}\n <div\n className={cn(\"eloq:w-full eloq:h-full\", {\n dark: chatInterfaceProps?.theme?.mode === \"dark\",\n })}\n >\n {proactiveMessage && !isInitiallyOpen && (\n <ProactiveMessage\n message={proactiveMessage.text}\n isVisible={proactiveMessage.isVisible}\n onDismiss={hideProactiveMessage}\n onMessageClick={() => {\n setChatOpen(true);\n hideProactiveMessage();\n }}\n autoHideDelay={proactiveMessage.autoHideDelay}\n />\n )}\n </div>\n </ThemeProvider>\n </Iframe>\n ) : null}\n </div>\n );\n };\n\n const renderChat = () => {\n if (INTERNAL_ONLY_BLOCK_STYLE) {\n return renderContent();\n }\n\n if (portalContainer) {\n return <Portal container={portalContainer}>{renderContent()}</Portal>;\n }\n\n return null;\n };\n\n return <>{renderChat()}</>;\n}\n\nexport function Chat(props: Readonly<ChatProps>) {\n return (\n <ErrorProvider>\n <AgentCognitionProvider>\n <InternalChat {...props} />\n </AgentCognitionProvider>\n </ErrorProvider>\n );\n}\n","import type { ComponentType } from \"react\";\nimport ReactDOMClient from \"react-dom/client\";\n\nimport { Chat, type ChatProps } from \"@/components/chat\";\n\ntype UnmountFunction = () => void;\n\nexport function renderChat(\n container: HTMLElement,\n props: ChatProps,\n): UnmountFunction {\n const render = (\n Component: ComponentType<ChatProps>,\n container: HTMLElement,\n props: ChatProps,\n ) => {\n const root = ReactDOMClient.createRoot(container);\n root.render(<Component {...props} />);\n return root.unmount;\n };\n return render(Chat, container, props);\n}\n"],"names":["environment","init","event","sensitiveHeaders","headers","key","ChatBubble","toggleBubble","isDarkMode","bubbleBackground","logoForeground","jsx","cn","Logo","Iframe","children","head","props","contentRef","setContentRef","useState","headNode","bodyNode","jsxs","createPortal","Portal","container","ProactiveMessage","message","isVisible","onDismiss","onMessageClick","autoHideDelay","shouldRender","setShouldRender","animationState","setAnimationState","theme","useTheme","useEffect","enterTimer","hideTimer","timer","getContrastingTextColor","e","X","getCookie","name","match","setCookie","value","hours","expires","deleteCookie","useInterfaceProps","chatProps","chatSettings","useMemo","useLatestRef","reference","useRef","NetworkError","ServerError","status","response","CHAT_TOKEN_HEADER","CHAT_TOKEN_RENEWED_HEADER","HttpClient","config","region","token","url","options","regionHeader","chatTokenHeader","error","renewedToken","responseData","data","getCurrentUrlSearchParams","params","result","STORAGE_NAMESPACE","isClient","CHAT_EXPIRY_TIME","usePersistence","appId","STORAGE_KEY","defaultObject","getSavedChatData","useCallback","storedData","isChatExpired","saveChatData","conversationId","userId","messages","deviceId","chatToken","chatData","markChatClosed","clearChatData","stored","updateLastActivity","APPSYNC_EVENTS_SUBPROTOCOL","HANDSHAKE_TIMEOUT_MILLISECONDS","DEFAULT_CONNECTION_TIMEOUT_MILLISECONDS","KEEP_ALIVE_CHECK_INTERVAL_MILLISECONDS","WEB_SOCKET_OPEN_STATE","deriveRealtimeUrl","httpEndpoint","buildAuthorization","auth","host","encodeAuthProtocol","authorization","formatErrors","errors","connectAppSyncEvents","channel","onEvent","onDisconnect","createWebSocket","protocols","realtimeUrl","subscriptionId","resolve","reject","socket","phase","isClosedByClient","connectionTimeoutMilliseconds","lastLivenessTimestamp","handshakeTimer","keepAliveTimer","clearTimers","terminate","reason","wasEstablished","send","startHandshakeTimer","step","payload","_a","$constructor","initializer","inst","def","_","proto","keys","i","k","Parent","Definition","fn","$ZodAsyncError","globalConfig","newConfig","jsonStringifyReplacer","cached","getter","cleanRegex","source","start","end","EVALUATING","defineLazy","object","v","captureStackTrace","_args","isObject","escapeRegex","str","clone","cl","normalizeParams","_params","optionalKeys","shape","aborted","x","startIndex","explicitlyAborted","prefixIssues","path","issues","iss","unwrapMessage","finalizeIssue","ctx","_inst","_continue","_input","rest","util.jsonStringifyReplacer","$ZodError","$ZodRealError","_parse","_Err","schema","_ctx","core.$ZodAsyncError","util.finalizeIssue","core.config","util.captureStackTrace","parse","errors.$ZodRealError","_parseAsync","parseAsync","_safeParse","errors.$ZodError","safeParse","_safeParseAsync","safeParseAsync","string","regex","_null","version","$ZodType","core.$constructor","checks","ch","runChecks","isAborted","util.aborted","asyncResult","util.explicitlyAborted","currLen","handleCanaryResult","canary","checkResult","util.defineLazy","r","$ZodString","regexes.string","$ZodNull","regexes.null","input","handlePropertyResult","final","isOptionalIn","isOptionalOut","isPresent","util.prefixIssues","normalizeDef","okeys","util.optionalKeys","handleCatchall","proms","unrecognized","keySet","_catchall","t","$ZodObject","sh","newSh","_normalized","util.cached","propValues","field","util.isObject","catchall","el","handleUnionResults","results","nonaborted","$ZodUnion","o","option","patterns","p","util.cleanRegex","first","async","$ZodLiteral","values","util.escapeRegex","$ZodNullable","pattern","_string","Class","util.normalizeParams","ZodMiniType","core.$ZodType","parse.parse","parse.safeParse","parse.parseAsync","parse.safeParseAsync","_def","core.clone","reg","meta","ZodMiniString","core.$ZodString","core._string","ZodMiniNull","core.$ZodNull","core._null","ZodMiniObject","core.$ZodObject","ZodMiniUnion","core.$ZodUnion","union","ZodMiniLiteral","core.$ZodLiteral","literal","ZodMiniNullable","core.$ZodNullable","nullable","innerType","zodConfig","utteranceSchema","z.object","z.literal","z.string","agentCognitionSchema","chatClosedExpiredSchema","agentCapturedUrlSchema","agentTopicSchema","agentSummarySchema","chatRatingSchema","breadcrumbSchema","chatEscalatedSchema","z.null","errorSchema","utteranceApiResponseSchema","z.nullable","errorApiResponseSchema","agentCognitionApiResponseSchema","chatClosedExpiredApiResponseSchema","agentCapturedUrlApiResponseSchema","agentTopicApiResponseSchema","agentSummaryApiResponseSchema","chatRatingApiResponseSchema","breadcrumbApiResponseSchema","chatEscalatedApiResponseSchema","chatResponseApiSchema","z.union","INITIAL_RECONNECT_DELAY_MS","MAX_RECONNECT_DELAY_MS","DEFAULT_BACKUP_POLL_INTERVAL_MS","useRealtimeSocket","chatId","onMessage","onCognition","onCognitionComplete","onError","onChatClosed","onAgentCapturedUrl","onAgentTopic","onAgentSummary","onRatingRequest","onBreadcrumb","fetchHistory","getChatToken","backupPollingInterval","processedIdsRef","msg","eventChannelRef","activeChatIdRef","reconnectAttemptsRef","reconnectTimerRef","backupPollIntervalRef","shouldReconnectRef","isReconnectingRef","onMessageRef","onCognitionRef","onCognitionCompleteRef","onErrorRef","onChatClosedRef","onAgentCapturedUrlRef","onAgentTopicRef","onAgentSummaryRef","onRatingRequestRef","onBreadcrumbRef","fetchHistoryRef","getChatTokenRef","publishError","useErrorContext","appSyncUrl","appSyncApiKey","isSocketConfigReady","appSyncUrlRef","appSyncApiKeyRef","closeChannel","stopBackupPoll","clearReconnectTimer","scheduleReconnectRef","connectChannel","chatIdToConnect","apiKey","connection","parseResult","notification","utterance","messageId","code","getErrorMessage","cognition","capturedUrl","topic","summary","runBackupPoll","chatIdToPoll","history","err","startBackupPoll","scheduleReconnect","scheduleReconnectSelf","chatIdToReconnect","delay","connect","disconnect","clearProcessedIds","messageFromChatResponse","createWelcomeMessage","content","createRatingRequestMessage","createChatClosedNoticeMessage","useMessageEvents","userName","userData","externalId","apiClient","setMessages","currentChat","setCurrentChat","isChatClosed","publishApiError","publishNetworkError","showCognition","hideCognition","useAgentCognitionContext","apiClientRef","onReceiveMessage","prev","updatedMessages","handleRealTimeError","handleRatingRequest","handleChatClosed","onCleanMessages","onSendMessage","userMessage","newMessages","connectError","onRateChat","rating","getEnvVariable","__vite_import_meta_env__","ENV_API_URL","ENV_REGION_API_URL","getApiUrl","getRegionApiUrl","EloquentAiApiClient","regionApiUrl","wrapPromise","promise","DEFAULT_OPTIONS","isRetryableError","getDelayMs","attempt","exponentialDelay","cappedDelay","withRetry","operation","opts","cache","inflight","useFetch","fetcher","dedupe","setData","setError","isLoading","setIsLoading","mountedRef","fetch","cachedData","resolveUserIdentity","savedData","initialUserId","useUserIdentity","identity","setIdentity","prevInitialUserId","setPrevInitialUserId","useSdkInitialization","apiUrlOverride","isUserIdentityReady","apiUrl","setChatSettings","isReady","setIsReady","setIsChatClosed","isChatActive","setIsChatActive","sdkBootFetch","savedMessages","savedIsChatClosed","savedChatToken","hasBootedRef","orgResponse","orgError","welcomeMessage","m","MOBILE_MEDIA_QUERY","getIsMobileScreen","useUiInitialization","propIsMobile","isMobileScreen","setIsMobileScreen","portalContainer","setPortalContainer","isMobile","isSSR","mediaQueryList","handleChange","CHAT_CLOSED_COOKIE_TTL_HOURS","getChatClosedCookieName","useChat","propIsInitiallyOpen","propHasCloseButton","propHasCleanChatButton","deprecatedInitialOpen","deprecatedCloseButton","deprecatedCleanChatButton","propProactiveMessageHideDelay","isAlwaysOpen","hasCleanChatButtonOverride","initialChat","initialMessages","initialIsChatClosed","chatInterfaceProps","propInitialOpen","propCloseButton","propCleanChatButton","chatClosedCookieName","chatOpen","setChatOpenState","hasAppliedBootInitialOpen","setHasAppliedBootInitialOpen","bootInitialOpen","isInitiallyOpen","hasCloseButton","hasCleanChatButton","proactiveMessageHideDelay","setChatOpen","next","chatOpenDebounced","useDebounce","prevInitialMessages","setPrevInitialMessages","prevInitialChat","setPrevInitialChat","prevInitialIsChatClosed","setPrevInitialIsChatClosed","hasDismissedProactiveMessage","setHasDismissedProactiveMessage","proactiveMessageText","proactiveMessage","lastIdentifyKeyRef","identifyPayload","identifyKey","onStartNewChat","hideProactiveMessage","useKeyboardInset","enabled","inset","setInset","viewport","update","overlap","useScrollLock","locked","body","scrollY","previousStyle","useAgentCognition","setIsVisible","setContent","timerRef","pendingContentRef","newContent","updateCognition","AgentCognitionProvider","AgentCognitionContext","ErrorProvider","hideSdk","setHideSdk","createPublishApiError","contextValue","ErrorContext","CHAT_DESKTOP_VIEWPORT_INSET_PX","InternalChat","INTERNAL_ONLY_CHAT_INTERFACE_ONLY","INTERNAL_ONLY_SHOW_CLEAN_CHAT_BUTTON","INTERNAL_ONLY_BLOCK_STYLE","INTERNAL_ONLY_FEATURE_MESSAGE_CLICK","INTERNAL_ONLY_FEATURE_CLEAR_CHAT_CLICK","INTERNAL_ONLY_SHOW_COPY_BUTTON","INTERNAL_ONLY_ENVIRONMENT","INTERNAL_ONLY_API_URL","keyboardInset","isBooting","renderContent","wrapperCSS","Fragment","mainCSS","SkeletonChatInterface","ChatInterface","ThemeProvider","Chat","renderChat","Component","root","ReactDOMClient"],"mappings":";;;;;;;;;;;AACA,IAAI,OAAO,SAAW,KAAa;AAIjC,QAAMA,IAAkD;AAMxD,SAAO,qBAAe,EAAE,KAAK,CAAC,EAAE,MAAAC,QAAW;AACzC,IAAAA,EAAK;AAAA,MACH,KAAK;AAAA,MACL,aAAAD;AAAA,MACA,gBAAgB;AAAA,MAChB,OAAO;AAAA,MACP,SAAS;AAAA,MACT,WAAWE,GAAO;AAChB,cAAMC,wBAAuB,IAAI;AAAA,UAC/B;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,QAAA,CACD,GACKC,IAAUF,EAAM,SAAS;AAG/B,YAAIE;AACF,qBAAWC,KAAO,OAAO,KAAKD,CAAO;AACnC,YAAID,EAAiB,IAAIE,EAAI,YAAA,CAAa,MACxCD,EAAQC,CAAG,IAAI;AAIrB,eAAIH,EAAM,YACRA,EAAM,QAAQ,OAAO,eAEhBA;AAAA,MACT;AAAA,IAAA,CACD;AAAA,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