@gengage/assistant-fe 0.1.0

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.
Files changed (200) hide show
  1. package/LICENSE +61 -0
  2. package/README.md +232 -0
  3. package/dist/assistant-fe.css +1 -0
  4. package/dist/chat/api.d.ts +87 -0
  5. package/dist/chat/api.d.ts.map +1 -0
  6. package/dist/chat/attachment-utils.d.ts +10 -0
  7. package/dist/chat/attachment-utils.d.ts.map +1 -0
  8. package/dist/chat/catalog.d.ts +1114 -0
  9. package/dist/chat/catalog.d.ts.map +1 -0
  10. package/dist/chat/components/AIGroupingCards.d.ts +4 -0
  11. package/dist/chat/components/AIGroupingCards.d.ts.map +1 -0
  12. package/dist/chat/components/AISuggestedSearchCards.d.ts +4 -0
  13. package/dist/chat/components/AISuggestedSearchCards.d.ts.map +1 -0
  14. package/dist/chat/components/AITopPicks.d.ts +4 -0
  15. package/dist/chat/components/AITopPicks.d.ts.map +1 -0
  16. package/dist/chat/components/CategoriesContainer.d.ts +4 -0
  17. package/dist/chat/components/CategoriesContainer.d.ts.map +1 -0
  18. package/dist/chat/components/ChatDrawer.d.ts +140 -0
  19. package/dist/chat/components/ChatDrawer.d.ts.map +1 -0
  20. package/dist/chat/components/ChoicePrompter.d.ts +16 -0
  21. package/dist/chat/components/ChoicePrompter.d.ts.map +1 -0
  22. package/dist/chat/components/ComparisonTable.d.ts +47 -0
  23. package/dist/chat/components/ComparisonTable.d.ts.map +1 -0
  24. package/dist/chat/components/FloatingComparisonButton.d.ts +11 -0
  25. package/dist/chat/components/FloatingComparisonButton.d.ts.map +1 -0
  26. package/dist/chat/components/GroundingReviewCard.d.ts +4 -0
  27. package/dist/chat/components/GroundingReviewCard.d.ts.map +1 -0
  28. package/dist/chat/components/KvkkBanner.d.ts +6 -0
  29. package/dist/chat/components/KvkkBanner.d.ts.map +1 -0
  30. package/dist/chat/components/Launcher.d.ts +25 -0
  31. package/dist/chat/components/Launcher.d.ts.map +1 -0
  32. package/dist/chat/components/PanelTopBar.d.ts +20 -0
  33. package/dist/chat/components/PanelTopBar.d.ts.map +1 -0
  34. package/dist/chat/components/ProactivePopup.d.ts +11 -0
  35. package/dist/chat/components/ProactivePopup.d.ts.map +1 -0
  36. package/dist/chat/components/ProsAndCons.d.ts +9 -0
  37. package/dist/chat/components/ProsAndCons.d.ts.map +1 -0
  38. package/dist/chat/components/ReviewHighlights.d.ts +3 -0
  39. package/dist/chat/components/ReviewHighlights.d.ts.map +1 -0
  40. package/dist/chat/components/ThumbnailsColumn.d.ts +23 -0
  41. package/dist/chat/components/ThumbnailsColumn.d.ts.map +1 -0
  42. package/dist/chat/components/actionClassifier.d.ts +13 -0
  43. package/dist/chat/components/actionClassifier.d.ts.map +1 -0
  44. package/dist/chat/components/productMentionLinker.d.ts +26 -0
  45. package/dist/chat/components/productMentionLinker.d.ts.map +1 -0
  46. package/dist/chat/components/renderUISpec.d.ts +15 -0
  47. package/dist/chat/components/renderUISpec.d.ts.map +1 -0
  48. package/dist/chat/components/typewriter.d.ts +25 -0
  49. package/dist/chat/components/typewriter.d.ts.map +1 -0
  50. package/dist/chat/extendedModeManager.d.ts +33 -0
  51. package/dist/chat/extendedModeManager.d.ts.map +1 -0
  52. package/dist/chat/index.d.ts +192 -0
  53. package/dist/chat/index.d.ts.map +1 -0
  54. package/dist/chat/locales/en.d.ts +3 -0
  55. package/dist/chat/locales/en.d.ts.map +1 -0
  56. package/dist/chat/locales/index.d.ts +6 -0
  57. package/dist/chat/locales/index.d.ts.map +1 -0
  58. package/dist/chat/locales/tr.d.ts +3 -0
  59. package/dist/chat/locales/tr.d.ts.map +1 -0
  60. package/dist/chat/types.d.ts +212 -0
  61. package/dist/chat/types.d.ts.map +1 -0
  62. package/dist/chat.cjs +2 -0
  63. package/dist/chat.cjs.map +1 -0
  64. package/dist/chat.iife.js +59 -0
  65. package/dist/chat.iife.js.map +1 -0
  66. package/dist/chat.js +11 -0
  67. package/dist/chat.js.map +1 -0
  68. package/dist/common/action-router.d.ts +30 -0
  69. package/dist/common/action-router.d.ts.map +1 -0
  70. package/dist/common/activity-tracker.d.ts +38 -0
  71. package/dist/common/activity-tracker.d.ts.map +1 -0
  72. package/dist/common/analytics-events.d.ts +90 -0
  73. package/dist/common/analytics-events.d.ts.map +1 -0
  74. package/dist/common/analytics.d.ts +58 -0
  75. package/dist/common/analytics.d.ts.map +1 -0
  76. package/dist/common/api-paths.d.ts +14 -0
  77. package/dist/common/api-paths.d.ts.map +1 -0
  78. package/dist/common/client.d.ts +20 -0
  79. package/dist/common/client.d.ts.map +1 -0
  80. package/dist/common/communication-bridge.d.ts +51 -0
  81. package/dist/common/communication-bridge.d.ts.map +1 -0
  82. package/dist/common/config-schema.d.ts +241 -0
  83. package/dist/common/config-schema.d.ts.map +1 -0
  84. package/dist/common/context.d.ts +28 -0
  85. package/dist/common/context.d.ts.map +1 -0
  86. package/dist/common/customization-factories.d.ts +63 -0
  87. package/dist/common/customization-factories.d.ts.map +1 -0
  88. package/dist/common/events.d.ts +47 -0
  89. package/dist/common/events.d.ts.map +1 -0
  90. package/dist/common/global-error-toast.d.ts +6 -0
  91. package/dist/common/global-error-toast.d.ts.map +1 -0
  92. package/dist/common/index.d.ts +36 -0
  93. package/dist/common/index.d.ts.map +1 -0
  94. package/dist/common/indexed-db.d.ts +74 -0
  95. package/dist/common/indexed-db.d.ts.map +1 -0
  96. package/dist/common/overlay.d.ts +64 -0
  97. package/dist/common/overlay.d.ts.map +1 -0
  98. package/dist/common/preflight.d.ts +12 -0
  99. package/dist/common/preflight.d.ts.map +1 -0
  100. package/dist/common/renderer/dom.d.ts +4 -0
  101. package/dist/common/renderer/dom.d.ts.map +1 -0
  102. package/dist/common/renderer/index.d.ts +5 -0
  103. package/dist/common/renderer/index.d.ts.map +1 -0
  104. package/dist/common/renderer/overrides.d.ts +24 -0
  105. package/dist/common/renderer/overrides.d.ts.map +1 -0
  106. package/dist/common/renderer/registry.d.ts +3 -0
  107. package/dist/common/renderer/registry.d.ts.map +1 -0
  108. package/dist/common/renderer/types.d.ts +20 -0
  109. package/dist/common/renderer/types.d.ts.map +1 -0
  110. package/dist/common/safe-html.d.ts +19 -0
  111. package/dist/common/safe-html.d.ts.map +1 -0
  112. package/dist/common/streaming.d.ts +32 -0
  113. package/dist/common/streaming.d.ts.map +1 -0
  114. package/dist/common/theme-utils.d.ts +16 -0
  115. package/dist/common/theme-utils.d.ts.map +1 -0
  116. package/dist/common/types.d.ts +298 -0
  117. package/dist/common/types.d.ts.map +1 -0
  118. package/dist/common/ui-theme.d.ts +10 -0
  119. package/dist/common/ui-theme.d.ts.map +1 -0
  120. package/dist/common/uuidv7.d.ts +8 -0
  121. package/dist/common/uuidv7.d.ts.map +1 -0
  122. package/dist/common/v1-protocol-adapter.d.ts +66 -0
  123. package/dist/common/v1-protocol-adapter.d.ts.map +1 -0
  124. package/dist/common/widget-base.d.ts +75 -0
  125. package/dist/common/widget-base.d.ts.map +1 -0
  126. package/dist/common.cjs +2 -0
  127. package/dist/common.cjs.map +1 -0
  128. package/dist/common.js +584 -0
  129. package/dist/common.js.map +1 -0
  130. package/dist/index-CFA70IGF.js +3626 -0
  131. package/dist/index-CFA70IGF.js.map +1 -0
  132. package/dist/index-Dfl89zpe.cjs +13 -0
  133. package/dist/index-Dfl89zpe.cjs.map +1 -0
  134. package/dist/index.cjs +2 -0
  135. package/dist/index.cjs.map +1 -0
  136. package/dist/index.d.ts +24 -0
  137. package/dist/index.d.ts.map +1 -0
  138. package/dist/index.js +59 -0
  139. package/dist/index.js.map +1 -0
  140. package/dist/qna/api.d.ts +22 -0
  141. package/dist/qna/api.d.ts.map +1 -0
  142. package/dist/qna/catalog.d.ts +140 -0
  143. package/dist/qna/catalog.d.ts.map +1 -0
  144. package/dist/qna/components/ButtonRow.d.ts +16 -0
  145. package/dist/qna/components/ButtonRow.d.ts.map +1 -0
  146. package/dist/qna/components/TextInput.d.ts +12 -0
  147. package/dist/qna/components/TextInput.d.ts.map +1 -0
  148. package/dist/qna/components/renderUISpec.d.ts +8 -0
  149. package/dist/qna/components/renderUISpec.d.ts.map +1 -0
  150. package/dist/qna/index.d.ts +34 -0
  151. package/dist/qna/index.d.ts.map +1 -0
  152. package/dist/qna/locales/en.d.ts +3 -0
  153. package/dist/qna/locales/en.d.ts.map +1 -0
  154. package/dist/qna/locales/index.d.ts +6 -0
  155. package/dist/qna/locales/index.d.ts.map +1 -0
  156. package/dist/qna/locales/tr.d.ts +3 -0
  157. package/dist/qna/locales/tr.d.ts.map +1 -0
  158. package/dist/qna/types.d.ts +62 -0
  159. package/dist/qna/types.d.ts.map +1 -0
  160. package/dist/qna.cjs +2 -0
  161. package/dist/qna.cjs.map +1 -0
  162. package/dist/qna.css +1 -0
  163. package/dist/qna.iife.js +48 -0
  164. package/dist/qna.iife.js.map +1 -0
  165. package/dist/qna.js +435 -0
  166. package/dist/qna.js.map +1 -0
  167. package/dist/simrel/api.d.ts +26 -0
  168. package/dist/simrel/api.d.ts.map +1 -0
  169. package/dist/simrel/catalog.d.ts +319 -0
  170. package/dist/simrel/catalog.d.ts.map +1 -0
  171. package/dist/simrel/components/GroupTabs.d.ts +17 -0
  172. package/dist/simrel/components/GroupTabs.d.ts.map +1 -0
  173. package/dist/simrel/components/ProductCard.d.ts +17 -0
  174. package/dist/simrel/components/ProductCard.d.ts.map +1 -0
  175. package/dist/simrel/components/ProductGrid.d.ts +17 -0
  176. package/dist/simrel/components/ProductGrid.d.ts.map +1 -0
  177. package/dist/simrel/components/renderUISpec.d.ts +8 -0
  178. package/dist/simrel/components/renderUISpec.d.ts.map +1 -0
  179. package/dist/simrel/index.d.ts +36 -0
  180. package/dist/simrel/index.d.ts.map +1 -0
  181. package/dist/simrel/locales/en.d.ts +3 -0
  182. package/dist/simrel/locales/en.d.ts.map +1 -0
  183. package/dist/simrel/locales/index.d.ts +6 -0
  184. package/dist/simrel/locales/index.d.ts.map +1 -0
  185. package/dist/simrel/locales/tr.d.ts +3 -0
  186. package/dist/simrel/locales/tr.d.ts.map +1 -0
  187. package/dist/simrel/types.d.ts +111 -0
  188. package/dist/simrel/types.d.ts.map +1 -0
  189. package/dist/simrel.cjs +2 -0
  190. package/dist/simrel.cjs.map +1 -0
  191. package/dist/simrel.css +1 -0
  192. package/dist/simrel.iife.js +48 -0
  193. package/dist/simrel.iife.js.map +1 -0
  194. package/dist/simrel.js +620 -0
  195. package/dist/simrel.js.map +1 -0
  196. package/dist/types-CeON7iBO.cjs +48 -0
  197. package/dist/types-CeON7iBO.cjs.map +1 -0
  198. package/dist/types-yxW8WA7u.js +4132 -0
  199. package/dist/types-yxW8WA7u.js.map +1 -0
  200. package/package.json +100 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"simrel.js","sources":["../src/simrel/api.ts","../src/simrel/components/ProductCard.ts","../src/simrel/components/ProductGrid.ts","../src/simrel/components/GroupTabs.ts","../src/simrel/components/renderUISpec.ts","../src/simrel/locales/tr.ts","../src/simrel/locales/en.ts","../src/simrel/locales/index.ts","../src/simrel/catalog.ts","../src/simrel/index.ts"],"sourcesContent":["import { buildChatEndpointUrl } from '../common/api-paths.js';\nimport { consumeStream } from '../common/streaming.js';\nimport {\n adaptV1Event,\n normalizeSimilarProductsResponse,\n normalizeProductGroupingsResponse,\n} from '../common/v1-protocol-adapter.js';\nimport type { NormalizedProduct } from '../common/v1-protocol-adapter.js';\nimport type { StreamEvent } from '../common/types.js';\nimport type { ChatTransportConfig } from '../common/api-paths.js';\n\nexport interface SimilarProductsRequest {\n account_id: string;\n session_id: string;\n correlation_id: string;\n sku: string;\n domain?: string;\n limit?: number;\n output_language?: string;\n}\n\nexport interface ProductGroupingsRequest {\n account_id: string;\n session_id: string;\n correlation_id: string;\n skus: string[];\n output_language?: string;\n}\n\nexport interface ProductGroup {\n name: string;\n highlight?: string;\n products: NormalizedProduct[];\n}\n\nfunction isNDJSONResponse(response: Response): boolean {\n const ct = response.headers.get('Content-Type') ?? '';\n return ct.includes('application/x-ndjson') || ct.includes('text/event-stream');\n}\n\nasync function collectProductsFromStream(response: Response, signal?: AbortSignal): Promise<NormalizedProduct[]> {\n const products: NormalizedProduct[] = [];\n const opts: import('../common/streaming.js').StreamOptions = {\n onEvent: (event: StreamEvent) => {\n const normalized = adaptV1Event(event as unknown as Record<string, unknown>);\n if (!normalized || normalized.type !== 'ui_spec') return;\n\n for (const el of Object.values(normalized.spec.elements)) {\n if (el.type === 'ProductCard' && el.props) {\n const product = (el.props['product'] ?? el.props) as Record<string, unknown>;\n if (typeof product['sku'] === 'string' && typeof product['name'] === 'string') {\n products.push(product as unknown as NormalizedProduct);\n }\n }\n }\n },\n };\n if (signal !== undefined) opts.signal = signal;\n await consumeStream(response, opts);\n return products;\n}\n\nexport async function fetchSimilarProducts(\n request: SimilarProductsRequest,\n transport: ChatTransportConfig,\n signal?: AbortSignal,\n): Promise<NormalizedProduct[]> {\n const url = buildChatEndpointUrl('similar_products', transport);\n\n const fetchInit: RequestInit = {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(request),\n };\n if (signal !== undefined) fetchInit.signal = signal;\n const response = await fetch(url, fetchInit);\n\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}: ${response.statusText}`);\n }\n\n if (isNDJSONResponse(response)) {\n return collectProductsFromStream(response, signal);\n }\n\n const text = await response.text();\n if (!text) return [];\n return normalizeSimilarProductsResponse(JSON.parse(text));\n}\n\nasync function collectGroupingsFromStream(response: Response, signal?: AbortSignal): Promise<ProductGroup[]> {\n const groups: ProductGroup[] = [];\n let currentGroup: ProductGroup | null = null;\n\n const opts: import('../common/streaming.js').StreamOptions = {\n onEvent: (event: StreamEvent) => {\n const normalized = adaptV1Event(event as unknown as Record<string, unknown>);\n if (!normalized) return;\n\n if (normalized.type === 'metadata' && normalized.meta) {\n const name = normalized.meta['group_name'];\n if (typeof name === 'string') {\n currentGroup = { name, products: [] };\n const highlight = normalized.meta['highlight'];\n if (typeof highlight === 'string') currentGroup.highlight = highlight;\n groups.push(currentGroup);\n }\n }\n\n if (normalized.type === 'ui_spec' && currentGroup) {\n for (const el of Object.values(normalized.spec.elements)) {\n if (el.type === 'ProductCard' && el.props) {\n const product = (el.props['product'] ?? el.props) as Record<string, unknown>;\n if (typeof product['sku'] === 'string' && typeof product['name'] === 'string') {\n currentGroup.products.push(product as unknown as NormalizedProduct);\n }\n }\n }\n }\n },\n };\n if (signal !== undefined) opts.signal = signal;\n await consumeStream(response, opts);\n\n return groups;\n}\n\nexport async function fetchProductGroupings(\n request: ProductGroupingsRequest,\n transport: ChatTransportConfig,\n signal?: AbortSignal,\n): Promise<ProductGroup[]> {\n const url = buildChatEndpointUrl('product_groupings', transport);\n\n const fetchInit: RequestInit = {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(request),\n };\n if (signal !== undefined) fetchInit.signal = signal;\n const response = await fetch(url, fetchInit);\n\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}: ${response.statusText}`);\n }\n\n if (isNDJSONResponse(response)) {\n return collectGroupingsFromStream(response, signal);\n }\n\n const text = await response.text();\n if (!text) return [];\n return normalizeProductGroupingsResponse(JSON.parse(text));\n}\n","import type { NormalizedProduct } from '../../common/v1-protocol-adapter.js';\nimport type { SimRelI18n } from '../types.js';\n\nexport interface ProductCardOptions {\n product: NormalizedProduct;\n index: number;\n discountType?: 'strike-through' | 'badge';\n onClick: (product: NormalizedProduct) => void;\n onAddToCart: (params: { sku: string; quantity: number; cartCode: string }) => void;\n renderCard?: (product: NormalizedProduct, index: number) => string;\n i18n?: SimRelI18n;\n}\n\nexport function renderProductCard(options: ProductCardOptions): HTMLElement {\n const { product, index, discountType, onClick, onAddToCart, renderCard } = options;\n const i18n = options.i18n;\n const priceSuffix = i18n?.priceSuffix ?? ' TL';\n\n // Custom card renderer (XSS warning: raw HTML injection)\n if (renderCard) {\n const wrapper = document.createElement('div');\n wrapper.className = 'gengage-simrel-card gengage-simrel-card--custom';\n // ⚠️ XSS: renderCard returns raw HTML. Caller must sanitize.\n wrapper.innerHTML = renderCard(product, index);\n wrapper.addEventListener('click', (e) => {\n if ((e.target as HTMLElement).closest('.gengage-simrel-atc')) return;\n onClick(product);\n });\n return wrapper;\n }\n\n const card = document.createElement('article');\n card.className = 'gengage-simrel-card';\n card.setAttribute('role', 'listitem');\n card.dataset['sku'] = product.sku;\n\n // Image\n const imgWrapper = document.createElement('div');\n imgWrapper.className = 'gengage-simrel-card-image';\n if (product.imageUrl) {\n const img = document.createElement('img');\n img.src = product.imageUrl;\n img.alt = product.name;\n img.loading = 'lazy';\n imgWrapper.appendChild(img);\n }\n\n // Discount badge\n if (discountType === 'badge' && product.discountPercent && product.discountPercent > 0) {\n const badge = document.createElement('span');\n badge.className = 'gengage-simrel-badge';\n badge.textContent = `%${product.discountPercent}`;\n imgWrapper.appendChild(badge);\n }\n\n card.appendChild(imgWrapper);\n\n // Info section\n const info = document.createElement('div');\n info.className = 'gengage-simrel-card-info';\n\n // Brand\n if (product.brand) {\n const brandEl = document.createElement('div');\n brandEl.className = 'gengage-simrel-card-brand';\n brandEl.textContent = product.brand;\n info.appendChild(brandEl);\n }\n\n // Name\n const nameEl = document.createElement('div');\n nameEl.className = 'gengage-simrel-card-name';\n nameEl.textContent = product.name;\n info.appendChild(nameEl);\n\n // Rating\n if (product.rating != null && product.rating > 0) {\n const ratingEl = document.createElement('div');\n ratingEl.className = 'gengage-simrel-card-rating';\n const stars = '\\u2605'.repeat(Math.round(product.rating)) + '\\u2606'.repeat(5 - Math.round(product.rating));\n ratingEl.textContent = stars;\n if (product.reviewCount != null) {\n const count = document.createElement('span');\n count.className = 'gengage-simrel-card-review-count';\n count.textContent = ` (${product.reviewCount})`;\n ratingEl.appendChild(count);\n }\n info.appendChild(ratingEl);\n }\n\n // Price\n const priceContainer = document.createElement('div');\n priceContainer.className = 'gengage-simrel-card-price';\n\n if (product.originalPrice && product.originalPrice !== product.price) {\n if (discountType === 'strike-through' || !discountType) {\n const original = document.createElement('span');\n original.className = 'gengage-simrel-card-price-original';\n original.textContent = product.originalPrice + priceSuffix;\n priceContainer.appendChild(original);\n }\n }\n\n if (product.price) {\n const current = document.createElement('span');\n current.className = 'gengage-simrel-card-price-current';\n current.textContent = product.price + priceSuffix;\n priceContainer.appendChild(current);\n }\n\n info.appendChild(priceContainer);\n card.appendChild(info);\n\n // Add to cart button\n if (product.cartCode) {\n const atcBtn = document.createElement('button');\n atcBtn.className = 'gengage-simrel-atc';\n atcBtn.type = 'button';\n atcBtn.textContent = i18n?.addToCartButton ?? 'Sepete Ekle';\n atcBtn.addEventListener('click', (e) => {\n e.stopPropagation();\n onAddToCart({ sku: product.sku, quantity: 1, cartCode: product.cartCode! });\n });\n card.appendChild(atcBtn);\n }\n\n // Card click → navigate\n card.addEventListener('click', (e) => {\n if ((e.target as HTMLElement).closest('.gengage-simrel-atc')) return;\n onClick(product);\n });\n\n return card;\n}\n","import type { NormalizedProduct } from '../../common/v1-protocol-adapter.js';\nimport type { SimRelI18n } from '../types.js';\nimport { renderProductCard } from './ProductCard.js';\nimport type { ProductCardOptions } from './ProductCard.js';\n\nexport interface ProductGridOptions {\n products: NormalizedProduct[];\n columns?: number;\n discountType?: 'strike-through' | 'badge';\n onClick: (product: NormalizedProduct) => void;\n onAddToCart: (params: { sku: string; quantity: number; cartCode: string }) => void;\n renderCard?: (product: NormalizedProduct, index: number) => string;\n i18n?: SimRelI18n;\n}\n\nexport function renderProductGrid(options: ProductGridOptions): HTMLElement {\n const grid = document.createElement('div');\n grid.className = 'gengage-simrel-grid';\n grid.setAttribute('role', 'list');\n grid.setAttribute('aria-label', options.i18n?.similarProductsAriaLabel ?? 'Similar products');\n\n if (options.columns) {\n grid.style.setProperty('--gengage-simrel-columns', String(options.columns));\n }\n\n for (let i = 0; i < options.products.length; i++) {\n const product = options.products[i]!;\n const cardOpts: ProductCardOptions = {\n product,\n index: i,\n onClick: options.onClick,\n onAddToCart: options.onAddToCart,\n };\n if (options.i18n !== undefined) cardOpts.i18n = options.i18n;\n if (options.discountType !== undefined) cardOpts.discountType = options.discountType;\n if (options.renderCard !== undefined) cardOpts.renderCard = options.renderCard;\n const card = renderProductCard(cardOpts);\n grid.appendChild(card);\n }\n\n if (options.products.length === 0) {\n const empty = document.createElement('div');\n empty.className = 'gengage-simrel-empty';\n empty.textContent = options.i18n?.emptyStateMessage ?? 'Benzer ürün bulunamadı.';\n grid.appendChild(empty);\n }\n\n return grid;\n}\n","import type { NormalizedProduct } from '../../common/v1-protocol-adapter.js';\nimport type { ProductGroup } from '../api.js';\nimport type { SimRelI18n } from '../types.js';\nimport { renderProductGrid } from './ProductGrid.js';\n\nexport interface GroupTabsOptions {\n groups: ProductGroup[];\n discountType?: 'strike-through' | 'badge';\n onClick: (product: NormalizedProduct) => void;\n onAddToCart: (params: { sku: string; quantity: number; cartCode: string }) => void;\n renderCard?: (product: NormalizedProduct, index: number) => string;\n i18n?: SimRelI18n;\n}\n\nexport function renderGroupTabs(options: GroupTabsOptions): HTMLElement {\n const container = document.createElement('div');\n container.className = 'gengage-simrel-groups';\n\n if (options.groups.length === 0) {\n const empty = document.createElement('div');\n empty.className = 'gengage-simrel-empty';\n empty.textContent = options.i18n?.emptyStateMessage ?? 'Benzer ürün bulunamadı.';\n container.appendChild(empty);\n return container;\n }\n\n // Tab bar\n const tabBar = document.createElement('div');\n tabBar.className = 'gengage-simrel-tabs';\n tabBar.setAttribute('role', 'tablist');\n\n // Content area\n const contentArea = document.createElement('div');\n contentArea.className = 'gengage-simrel-tab-content';\n\n for (let i = 0; i < options.groups.length; i++) {\n const group = options.groups[i]!;\n const tab = document.createElement('button');\n tab.className = 'gengage-simrel-tab';\n tab.type = 'button';\n tab.textContent = group.name;\n tab.setAttribute('role', 'tab');\n tab.setAttribute('aria-selected', i === 0 ? 'true' : 'false');\n if (i === 0) tab.classList.add('gengage-simrel-tab--active');\n\n tab.addEventListener('click', () => {\n // Deactivate previous\n const prevTab = tabBar.querySelector('.gengage-simrel-tab--active');\n prevTab?.classList.remove('gengage-simrel-tab--active');\n prevTab?.setAttribute('aria-selected', 'false');\n\n // Activate current\n tab.classList.add('gengage-simrel-tab--active');\n tab.setAttribute('aria-selected', 'true');\n\n // Render grid for this group\n contentArea.innerHTML = '';\n const gridOpts: import('./ProductGrid.js').ProductGridOptions = {\n products: group.products,\n onClick: options.onClick,\n onAddToCart: options.onAddToCart,\n };\n if (options.i18n !== undefined) gridOpts.i18n = options.i18n;\n if (options.discountType !== undefined) gridOpts.discountType = options.discountType;\n if (options.renderCard !== undefined) gridOpts.renderCard = options.renderCard;\n const grid = renderProductGrid(gridOpts);\n contentArea.appendChild(grid);\n });\n\n tabBar.appendChild(tab);\n }\n\n container.appendChild(tabBar);\n\n // Render initial tab content\n const firstGroup = options.groups[0]!;\n const initialGridOpts: import('./ProductGrid.js').ProductGridOptions = {\n products: firstGroup.products,\n onClick: options.onClick,\n onAddToCart: options.onAddToCart,\n };\n if (options.i18n !== undefined) initialGridOpts.i18n = options.i18n;\n if (options.discountType !== undefined) initialGridOpts.discountType = options.discountType;\n if (options.renderCard !== undefined) initialGridOpts.renderCard = options.renderCard;\n const initialGrid = renderProductGrid(initialGridOpts);\n contentArea.appendChild(initialGrid);\n\n container.appendChild(contentArea);\n return container;\n}\n","import { renderUISpecWithRegistry } from '../../common/renderer/index.js';\nimport type { UISpecDomRegistry, UISpecDomUnknownRenderer } from '../../common/renderer/index.js';\nimport type { UISpec, ActionPayload } from '../../common/types.js';\nimport type { SimRelUISpecRenderContext, SimilarProduct } from '../types.js';\nimport type { ProductGroup } from '../api.js';\nimport { renderProductCard } from './ProductCard.js';\nimport { renderGroupTabs } from './GroupTabs.js';\n\nexport type SimRelUISpecRegistry = UISpecDomRegistry<SimRelUISpecRenderContext>;\n\nfunction toSimRelProduct(raw: unknown): SimilarProduct | null {\n if (!raw || typeof raw !== 'object') return null;\n const obj = raw as Record<string, unknown>;\n if (typeof obj['sku'] !== 'string' || typeof obj['name'] !== 'string' || typeof obj['url'] !== 'string') {\n return null;\n }\n\n const result: SimilarProduct = {\n sku: obj['sku'],\n name: obj['name'],\n url: obj['url'],\n };\n\n const imageUrl = obj['imageUrl'];\n if (typeof imageUrl === 'string') result.imageUrl = imageUrl;\n const price = obj['price'];\n if (typeof price === 'string') result.price = price;\n const originalPrice = obj['originalPrice'];\n if (typeof originalPrice === 'string') result.originalPrice = originalPrice;\n const discountPercent = obj['discountPercent'];\n if (typeof discountPercent === 'number') result.discountPercent = discountPercent;\n const brand = obj['brand'];\n if (typeof brand === 'string') result.brand = brand;\n const rating = obj['rating'];\n if (typeof rating === 'number') result.rating = rating;\n const reviewCount = obj['reviewCount'];\n if (typeof reviewCount === 'number') result.reviewCount = reviewCount;\n const cartCode = obj['cartCode'];\n if (typeof cartCode === 'string') result.cartCode = cartCode;\n const inStock = obj['inStock'];\n if (typeof inStock === 'boolean') result.inStock = inStock;\n\n return result;\n}\n\nfunction toActionPayload(raw: unknown): ActionPayload | null {\n if (!raw || typeof raw !== 'object') return null;\n const obj = raw as Record<string, unknown>;\n const title = obj['title'];\n const type = obj['type'];\n if (typeof title !== 'string' || typeof type !== 'string') return null;\n const action: ActionPayload = { title, type };\n if (obj['payload'] !== undefined) action.payload = obj['payload'];\n return action;\n}\n\nconst DEFAULT_SIMREL_UI_SPEC_REGISTRY: SimRelUISpecRegistry = {\n ProductGrid: ({ element, renderElement }) => {\n const grid = document.createElement('div');\n grid.className = 'gengage-simrel-grid';\n grid.setAttribute('role', 'list');\n\n const columns = element.props?.['columns'];\n if (typeof columns === 'number' && Number.isFinite(columns) && columns > 0) {\n grid.style.setProperty('--gengage-simrel-columns', String(columns));\n }\n\n for (const childId of element.children ?? []) {\n const rendered = renderElement(childId);\n if (rendered) grid.appendChild(rendered);\n }\n\n if (grid.children.length === 0) {\n const empty = document.createElement('div');\n empty.className = 'gengage-simrel-empty';\n empty.textContent = 'Benzer ürün bulunamadı.';\n grid.appendChild(empty);\n }\n\n return grid;\n },\n\n ProductCard: ({ element, context }) => {\n const productRaw = (element.props?.['product'] ?? element.props) as unknown;\n const product = toSimRelProduct(productRaw);\n if (!product) return null;\n\n const indexRaw = element.props?.['index'];\n const index = typeof indexRaw === 'number' && Number.isFinite(indexRaw) ? indexRaw : 0;\n const discountTypeRaw = element.props?.['discountType'];\n const discountType =\n discountTypeRaw === 'strike-through' || discountTypeRaw === 'badge' ? discountTypeRaw : context.discountType;\n\n const options: import('./ProductCard.js').ProductCardOptions = {\n product,\n index,\n onClick: context.onClick,\n onAddToCart: context.onAddToCart,\n i18n: context.i18n,\n };\n if (discountType !== undefined) options.discountType = discountType;\n if (context.renderCard !== undefined) options.renderCard = context.renderCard;\n return renderProductCard(options);\n },\n\n GroupTabs: ({ element, context }) => {\n const groupsRaw = element.props?.['groups'];\n if (!Array.isArray(groupsRaw)) return null;\n const groups: ProductGroup[] = [];\n\n for (const entry of groupsRaw) {\n if (!entry || typeof entry !== 'object') continue;\n const obj = entry as Record<string, unknown>;\n if (typeof obj['name'] !== 'string') continue;\n\n const products: SimilarProduct[] = [];\n if (Array.isArray(obj['products'])) {\n for (const rawProduct of obj['products']) {\n const normalized = toSimRelProduct(rawProduct);\n if (normalized) products.push(normalized);\n }\n }\n\n const group: ProductGroup = {\n name: obj['name'],\n products,\n };\n if (typeof obj['highlight'] === 'string') group.highlight = obj['highlight'];\n groups.push(group);\n }\n\n const options: import('./GroupTabs.js').GroupTabsOptions = {\n groups,\n onClick: context.onClick,\n onAddToCart: context.onAddToCart,\n i18n: context.i18n,\n };\n if (context.discountType !== undefined) options.discountType = context.discountType;\n if (context.renderCard !== undefined) options.renderCard = context.renderCard;\n return renderGroupTabs(options);\n },\n\n EmptyState: ({ element, context }) => {\n const empty = document.createElement('div');\n empty.className = 'gengage-simrel-empty';\n const message = element.props?.['message'];\n empty.textContent = typeof message === 'string' ? message : context.i18n.emptyStateMessage;\n return empty;\n },\n\n AddToCartButton: ({ element, context }) => {\n const sku = element.props?.['sku'];\n const cartCode = element.props?.['cartCode'];\n if (typeof sku !== 'string' || typeof cartCode !== 'string') return null;\n\n const button = document.createElement('button');\n button.className = 'gengage-simrel-atc';\n button.type = 'button';\n const label = element.props?.['label'];\n button.textContent = typeof label === 'string' ? label : context.i18n.addToCartButton;\n button.addEventListener('click', (e) => {\n e.preventDefault();\n e.stopPropagation();\n context.onAddToCart({ sku, quantity: 1, cartCode });\n });\n return button;\n },\n\n QuickActions: ({ element, context }) => {\n const wrapper = document.createElement('div');\n wrapper.className = 'gengage-simrel-quick-actions';\n const actions = element.props?.['actions'];\n if (!Array.isArray(actions) || !context.onAction) return wrapper;\n\n for (const raw of actions) {\n if (!raw || typeof raw !== 'object') continue;\n const actionObj = raw as Record<string, unknown>;\n const label = actionObj['label'];\n const action = toActionPayload(actionObj['action']);\n if (typeof label !== 'string' || !action) continue;\n\n const button = document.createElement('button');\n button.className = 'gengage-simrel-quick-action';\n button.type = 'button';\n button.textContent = label;\n button.addEventListener('click', (e) => {\n e.preventDefault();\n e.stopPropagation();\n context.onAction?.(action);\n });\n wrapper.appendChild(button);\n }\n return wrapper;\n },\n};\n\nexport const defaultSimRelUnknownUISpecRenderer: UISpecDomUnknownRenderer<SimRelUISpecRenderContext> = ({\n element,\n renderElement,\n}) => {\n if (import.meta.env?.DEV) {\n console.warn(`[gengage:simrel] Unknown ui_spec component type: ${element.type}`);\n }\n if (!element.children || element.children.length === 0) {\n return null;\n }\n const wrapper = document.createElement('div');\n for (const childId of element.children) {\n const rendered = renderElement(childId);\n if (rendered) wrapper.appendChild(rendered);\n }\n return wrapper;\n};\n\nexport function createDefaultSimRelUISpecRegistry(): SimRelUISpecRegistry {\n return { ...DEFAULT_SIMREL_UI_SPEC_REGISTRY };\n}\n\nexport function renderSimRelUISpec(\n spec: UISpec,\n context: SimRelUISpecRenderContext,\n registry = DEFAULT_SIMREL_UI_SPEC_REGISTRY,\n unknownRenderer: UISpecDomUnknownRenderer<SimRelUISpecRenderContext> = defaultSimRelUnknownUISpecRenderer,\n): HTMLElement {\n return renderUISpecWithRegistry({\n spec,\n context,\n registry,\n containerClassName: 'gengage-simrel-uispec',\n unknownRenderer,\n });\n}\n","import type { SimRelI18n } from '../types.js';\n\nexport const SIMREL_I18N_TR: SimRelI18n = {\n similarProductsAriaLabel: 'Benzer ürünler',\n emptyStateMessage: 'Benzer ürün bulunamadı.',\n addToCartButton: 'Sepete Ekle',\n priceSuffix: ' TL',\n};\n","import type { SimRelI18n } from '../types.js';\n\nexport const SIMREL_I18N_EN: SimRelI18n = {\n similarProductsAriaLabel: 'Similar products',\n emptyStateMessage: 'No similar products found.',\n addToCartButton: 'Add to cart',\n priceSuffix: '',\n};\n","import type { SimRelI18n } from '../types.js';\nimport { SIMREL_I18N_TR } from './tr.js';\nimport { SIMREL_I18N_EN } from './en.js';\n\nfunction normalizeLocale(locale?: string): string {\n if (!locale) return 'tr';\n return locale.toLowerCase().split('-')[0] ?? 'tr';\n}\n\nexport function resolveSimRelLocale(locale?: string): SimRelI18n {\n switch (normalizeLocale(locale)) {\n case 'en':\n return SIMREL_I18N_EN;\n default:\n return SIMREL_I18N_TR;\n }\n}\n\nexport { SIMREL_I18N_TR, SIMREL_I18N_EN };\n","/**\n * Similar Products (SimRel) widget — json-render catalog definition.\n *\n * Backend endpoints:\n * POST /chat/similar_products — primary product list\n * POST /chat/product_groupings — grouped/tabbed view\n *\n * The backend streams NDJSON events. `ui_spec` events reference\n * component names defined below. Implementations live in ./registry.\n */\n\nimport { z } from 'zod';\n\nconst SimilarProductSchema = z.object({\n sku: z.string(),\n name: z.string(),\n imageUrl: z.string().url().optional(),\n price: z.string().optional(),\n originalPrice: z.string().optional(),\n discountPercent: z.number().optional(),\n url: z.string().url(),\n brand: z.string().optional(),\n rating: z.number().min(0).max(5).optional(),\n reviewCount: z.number().int().nonnegative().optional(),\n});\n\nexport const ProductGridSchema = z.object({\n layout: z.enum(['grid', 'carousel']).optional(),\n columns: z.number().int().positive().optional(),\n});\n\nexport const ProductCardSchema = z.object({\n product: SimilarProductSchema,\n index: z.number().int().nonnegative(),\n discountType: z.enum(['strike-through', 'badge']).optional(),\n});\n\nexport const AddToCartButtonSchema = z.object({\n sku: z.string(),\n label: z.string().optional(),\n cartCode: z.string(),\n});\n\nexport const QuickActionsSchema = z.object({\n actions: z.array(\n z.object({\n label: z.string(),\n action: z.object({\n title: z.string(),\n type: z.string(),\n payload: z.unknown().optional(),\n }),\n }),\n ),\n});\n\nexport const EmptyStateSchema = z.object({\n message: z.string().optional(),\n});\n\nexport const simRelCatalog = {\n components: {\n ProductGrid: {\n schema: ProductGridSchema,\n description: 'Outer grid or carousel container for similar products.',\n },\n ProductCard: {\n schema: ProductCardSchema,\n description: 'A single product card with image, title, price, and actions.',\n },\n AddToCartButton: {\n schema: AddToCartButtonSchema,\n description: 'Add-to-cart CTA rendered inside or below a product card.',\n },\n QuickActions: {\n schema: QuickActionsSchema,\n description: 'A row of quick-action buttons below product info.',\n },\n EmptyState: {\n schema: EmptyStateSchema,\n description: 'Empty state shown when no similar products are available.',\n },\n },\n} as const;\n\nexport type SimRelCatalog = typeof simRelCatalog;\nexport type SimRelComponentName = keyof SimRelCatalog['components'];\n","/**\n * Similar Products (SimRel) widget — public entry point.\n *\n * Fetches and renders similar / related products for the current SKU.\n * Backend: POST /chat/similar_products + /chat/product_groupings\n */\n\nimport type { PageContext, UISpec, UIElement } from '../common/types.js';\nimport type { NormalizedProduct } from '../common/v1-protocol-adapter.js';\nimport type { ChatTransportConfig } from '../common/api-paths.js';\nimport type { UISpecRenderHelpers } from '../common/renderer/index.js';\nimport { mergeUISpecRegistry } from '../common/renderer/index.js';\nimport { BaseWidget } from '../common/widget-base.js';\nimport { dispatch } from '../common/events.js';\nimport { getGlobalErrorMessage } from '../common/global-error-toast.js';\nimport {\n streamStartEvent,\n streamDoneEvent,\n streamErrorEvent,\n basketAddEvent,\n widgetHistorySnapshotEvent,\n} from '../common/analytics-events.js';\nimport { fetchSimilarProducts, fetchProductGroupings } from './api.js';\nimport {\n createDefaultSimRelUISpecRegistry,\n defaultSimRelUnknownUISpecRenderer,\n renderSimRelUISpec,\n} from './components/renderUISpec.js';\nimport type { SimRelWidgetConfig, SimilarProduct, SimRelI18n, SimRelUISpecRenderContext } from './types.js';\nimport { SIMREL_I18N_TR, resolveSimRelLocale } from './locales/index.js';\n\nimport './components/simrel.css';\n\nexport class GengageSimRel extends BaseWidget<SimRelWidgetConfig> {\n private _abortController: AbortController | null = null;\n private _contentEl: HTMLElement | null = null;\n private _lastSku: string | undefined;\n private _i18n: SimRelI18n = SIMREL_I18N_TR;\n\n protected async onInit(config: SimRelWidgetConfig): Promise<void> {\n this._i18n = this._resolveI18n(config);\n\n this._contentEl = document.createElement('div');\n this._contentEl.className = 'gengage-simrel-container';\n this.root.appendChild(this._contentEl);\n\n this._lastSku = config.sku;\n await this._fetchAndRender(config.sku);\n this.isVisible = true;\n }\n\n protected onUpdate(context: Partial<PageContext>): void {\n const newSku = context.sku;\n if (!newSku || newSku === this._lastSku) return;\n this._lastSku = newSku;\n void this._fetchAndRender(newSku);\n }\n\n protected onShow(): void {\n if (this._contentEl) {\n this._contentEl.style.opacity = '0';\n this._contentEl.style.transition = 'opacity 0.3s ease-in';\n requestAnimationFrame(() => {\n if (this._contentEl) this._contentEl.style.opacity = '1';\n });\n }\n }\n\n protected onHide(): void {\n // Preserve fetched products for re-show\n }\n\n protected onDestroy(): void {\n this._abort();\n if (this._contentEl) {\n this._contentEl.remove();\n this._contentEl = null;\n }\n }\n\n // ---------------------------------------------------------------------------\n // Internal event dispatchers\n // ---------------------------------------------------------------------------\n\n _handleProductClick(product: NormalizedProduct): void {\n const simRelProduct: SimilarProduct = {\n sku: product.sku,\n name: product.name,\n url: product.url,\n };\n if (product.imageUrl !== undefined) simRelProduct.imageUrl = product.imageUrl;\n if (product.price !== undefined) simRelProduct.price = product.price;\n if (product.originalPrice !== undefined) simRelProduct.originalPrice = product.originalPrice;\n if (product.discountPercent !== undefined) simRelProduct.discountPercent = product.discountPercent;\n if (product.brand !== undefined) simRelProduct.brand = product.brand;\n if (product.rating !== undefined) simRelProduct.rating = product.rating;\n if (product.reviewCount !== undefined) simRelProduct.reviewCount = product.reviewCount;\n if (product.cartCode !== undefined) simRelProduct.cartCode = product.cartCode;\n if (product.inStock !== undefined) simRelProduct.inStock = product.inStock;\n\n if (this.config.onProductClick?.(simRelProduct) === false) return;\n\n const sessionId = this.config.session?.sessionId ?? null;\n dispatch('gengage:similar:product-click', {\n sku: product.sku,\n url: product.url,\n sessionId,\n });\n\n this.config.onProductNavigate?.(product.url, product.sku, sessionId);\n }\n\n _handleAddToCart(params: { sku: string; quantity: number; cartCode: string }): void {\n this.config.onAddToCart?.(params);\n dispatch('gengage:similar:add-to-cart', params);\n\n this.track(\n basketAddEvent(this.analyticsContext(), {\n attribution_source: 'simrel',\n attribution_action_id: crypto.randomUUID(),\n cart_value: 0, // Host page should enrich via event listener\n currency: 'TRY',\n line_items: params.quantity,\n sku: params.sku,\n }),\n );\n }\n\n // ---------------------------------------------------------------------------\n // Private\n // ---------------------------------------------------------------------------\n\n private _abort(): void {\n this._abortController?.abort();\n this._abortController = null;\n }\n\n private async _fetchAndRender(sku: string): Promise<void> {\n this._abort();\n this._abortController = new AbortController();\n\n if (!this._contentEl) return;\n this._contentEl.innerHTML = '';\n\n // Show loading spinner\n const loading = document.createElement('div');\n loading.className = 'gengage-simrel-loading';\n const spinner = document.createElement('div');\n spinner.className = 'gengage-simrel-spinner';\n loading.appendChild(spinner);\n this._contentEl.appendChild(loading);\n\n const transport: ChatTransportConfig = {\n middlewareUrl: this.config.middlewareUrl,\n };\n\n const requestId = crypto.randomUUID();\n const fetchStart = Date.now();\n\n this.track(\n streamStartEvent(this.analyticsContext(), {\n endpoint: 'similar_products',\n request_id: requestId,\n widget: 'simrel',\n }),\n );\n\n try {\n // Fetch similar products\n const simReq: import('./api.js').SimilarProductsRequest = {\n account_id: this.config.accountId,\n session_id: this.config.session?.sessionId ?? '',\n correlation_id: this.config.session?.sessionId ?? '',\n sku,\n };\n if (this.config.domain !== undefined) simReq.domain = this.config.domain;\n const products = await fetchSimilarProducts(simReq, transport, this._abortController.signal);\n\n if (!this._contentEl) return;\n this._contentEl.innerHTML = '';\n\n // Try to fetch product groupings for tabbed view\n if (products.length > 0) {\n try {\n const skus = products.map((p) => p.sku);\n const groups = await fetchProductGroupings(\n {\n account_id: this.config.accountId,\n session_id: this.config.session?.sessionId ?? '',\n correlation_id: this.config.session?.sessionId ?? '',\n skus,\n },\n transport,\n this._abortController.signal,\n );\n\n if (groups.length > 0 && this._contentEl) {\n const groupsSpec = this._buildGroupsSpec(groups);\n const renderedGroups = this._renderUISpec(groupsSpec);\n this._contentEl.appendChild(renderedGroups);\n return;\n }\n } catch {\n // Product groupings is optional; fall through to flat grid\n }\n }\n\n // Flat grid (no groupings or groupings failed)\n if (this._contentEl) {\n const gridSpec = this._buildProductsSpec(products);\n const renderedGrid = this._renderUISpec(gridSpec);\n this._contentEl.appendChild(renderedGrid);\n }\n\n this.track(\n streamDoneEvent(this.analyticsContext(), {\n request_id: requestId,\n latency_ms: Date.now() - fetchStart,\n chunk_count: products.length,\n widget: 'simrel',\n }),\n );\n\n this.track(\n widgetHistorySnapshotEvent(this.analyticsContext(), {\n message_count: products.length,\n history_ref: requestId,\n redaction_level: 'none',\n widget: 'simrel',\n }),\n );\n } catch (err) {\n if (err instanceof DOMException && err.name === 'AbortError') return;\n\n dispatch('gengage:global:error', {\n source: 'simrel',\n code: 'FETCH_ERROR',\n message: getGlobalErrorMessage(this.config.locale),\n });\n\n this.track(\n streamErrorEvent(this.analyticsContext(), {\n request_id: requestId,\n error_code: 'FETCH_ERROR',\n error_message: err instanceof Error ? err.message : String(err),\n widget: 'simrel',\n }),\n );\n\n if (import.meta.env?.DEV) {\n console.error('[gengage:simrel] Failed to fetch similar products:', err);\n }\n // Hide the widget gracefully — no user-facing error for backend unavailability\n if (this._contentEl) {\n this._contentEl.innerHTML = '';\n this._contentEl.style.display = 'none';\n }\n }\n }\n\n private _resolveI18n(config: SimRelWidgetConfig): SimRelI18n {\n const base = resolveSimRelLocale(config.locale);\n return { ...base, ...config.i18n };\n }\n\n private _resolveUISpecRegistry() {\n const baseRegistry = createDefaultSimRelUISpecRegistry();\n return mergeUISpecRegistry(baseRegistry, this.config.renderer?.registry);\n }\n\n private _buildRenderContext(): SimRelUISpecRenderContext {\n const renderCard = this.config.renderCard as ((product: SimilarProduct, index: number) => string) | undefined;\n const context: SimRelUISpecRenderContext = {\n onClick: (product) => this._handleProductClick(product as unknown as NormalizedProduct),\n onAddToCart: (params) => this._handleAddToCart(params),\n i18n: this._i18n,\n };\n if (this.config.discountType !== undefined) context.discountType = this.config.discountType;\n if (renderCard !== undefined) context.renderCard = renderCard;\n return context;\n }\n\n private _renderUISpec(spec: UISpec): HTMLElement {\n const registry = this._resolveUISpecRegistry();\n const context = this._buildRenderContext();\n const unknownRenderer = this.config.renderer?.unknownRenderer ?? defaultSimRelUnknownUISpecRenderer;\n const defaultRender = (inputSpec: UISpec, inputContext: SimRelUISpecRenderContext) =>\n renderSimRelUISpec(inputSpec, inputContext, registry, unknownRenderer);\n\n const override = this.config.renderer?.renderUISpec;\n if (!override) return defaultRender(spec, context);\n\n const helpers: UISpecRenderHelpers<SimRelUISpecRenderContext> = {\n registry,\n unknownRenderer,\n defaultRender,\n };\n return override(spec, context, helpers);\n }\n\n private _buildProductsSpec(products: NormalizedProduct[]): UISpec {\n const elements: Record<string, UIElement> = {};\n const children: string[] = [];\n for (let i = 0; i < products.length; i++) {\n const product = products[i]!;\n const id = `product-${i}`;\n children.push(id);\n elements[id] = {\n type: 'ProductCard',\n props: {\n product,\n index: i,\n discountType: this.config.discountType,\n },\n };\n }\n elements['root'] = {\n type: 'ProductGrid',\n props: {\n layout: 'grid',\n },\n children,\n };\n return {\n root: 'root',\n elements,\n };\n }\n\n private _buildGroupsSpec(\n groups: Array<{\n name: string;\n highlight?: string;\n products: NormalizedProduct[];\n }>,\n ): UISpec {\n return {\n root: 'root',\n elements: {\n root: {\n type: 'GroupTabs',\n props: { groups },\n },\n },\n };\n }\n}\n\nexport function createSimRelWidget(): GengageSimRel {\n return new GengageSimRel();\n}\n\nexport type {\n SimRelWidgetConfig,\n SimilarProduct,\n SimRelUIComponents,\n SimRelI18n,\n SimRelUISpecRenderContext,\n SimRelRendererConfig,\n} from './types.js';\nexport {\n renderSimRelUISpec,\n createDefaultSimRelUISpecRegistry,\n defaultSimRelUnknownUISpecRenderer,\n} from './components/renderUISpec.js';\nexport type { SimRelUISpecRegistry } from './components/renderUISpec.js';\nexport { simRelCatalog } from './catalog.js';\nexport type { SimRelCatalog, SimRelComponentName } from './catalog.js';\n"],"names":["isNDJSONResponse","response","ct","collectProductsFromStream","signal","products","opts","event","normalized","adaptV1Event","el","product","consumeStream","fetchSimilarProducts","request","transport","url","buildChatEndpointUrl","fetchInit","text","normalizeSimilarProductsResponse","collectGroupingsFromStream","groups","currentGroup","name","highlight","fetchProductGroupings","normalizeProductGroupingsResponse","renderProductCard","options","index","discountType","onClick","onAddToCart","renderCard","i18n","priceSuffix","wrapper","e","card","imgWrapper","img","badge","info","brandEl","nameEl","ratingEl","stars","count","priceContainer","original","current","atcBtn","renderProductGrid","grid","i","cardOpts","empty","renderGroupTabs","container","tabBar","contentArea","group","tab","prevTab","gridOpts","initialGridOpts","initialGrid","toSimRelProduct","raw","obj","result","imageUrl","price","originalPrice","discountPercent","brand","rating","reviewCount","cartCode","inStock","toActionPayload","title","type","action","DEFAULT_SIMREL_UI_SPEC_REGISTRY","element","renderElement","columns","childId","rendered","context","productRaw","indexRaw","discountTypeRaw","groupsRaw","entry","rawProduct","message","sku","button","label","actions","actionObj","defaultSimRelUnknownUISpecRenderer","createDefaultSimRelUISpecRegistry","renderSimRelUISpec","spec","registry","unknownRenderer","renderUISpecWithRegistry","SIMREL_I18N_TR","SIMREL_I18N_EN","normalizeLocale","locale","resolveSimRelLocale","SimilarProductSchema","z.object","z.string","z.number","ProductGridSchema","z.enum","ProductCardSchema","AddToCartButtonSchema","QuickActionsSchema","z.array","z.unknown","EmptyStateSchema","simRelCatalog","GengageSimRel","BaseWidget","config","newSku","simRelProduct","sessionId","dispatch","params","basketAddEvent","loading","spinner","requestId","fetchStart","streamStartEvent","simReq","skus","groupsSpec","renderedGroups","gridSpec","renderedGrid","streamDoneEvent","widgetHistorySnapshotEvent","err","getGlobalErrorMessage","streamErrorEvent","baseRegistry","mergeUISpecRegistry","defaultRender","inputSpec","inputContext","override","elements","children","id","createSimRelWidget"],"mappings":";AAmCA,SAASA,EAAiBC,GAA6B;AACrD,QAAMC,IAAKD,EAAS,QAAQ,IAAI,cAAc,KAAK;AACnD,SAAOC,EAAG,SAAS,sBAAsB,KAAKA,EAAG,SAAS,mBAAmB;AAC/E;AAEA,eAAeC,EAA0BF,GAAoBG,GAAoD;AAC/G,QAAMC,IAAgC,CAAA,GAChCC,IAAuD;AAAA,IAC3D,SAAS,CAACC,MAAuB;AAC/B,YAAMC,IAAaC,EAAaF,CAA2C;AAC3E,UAAI,GAACC,KAAcA,EAAW,SAAS;AAEvC,mBAAWE,KAAM,OAAO,OAAOF,EAAW,KAAK,QAAQ;AACrD,cAAIE,EAAG,SAAS,iBAAiBA,EAAG,OAAO;AACzC,kBAAMC,IAAWD,EAAG,MAAM,WAAcA,EAAG;AAC3C,YAAI,OAAOC,EAAQ,OAAW,YAAY,OAAOA,EAAQ,QAAY,YACnEN,EAAS,KAAKM,CAAuC;AAAA,UAEzD;AAAA;AAAA,IAEJ;AAAA,EAAA;AAEF,SAAIP,MAAW,WAAWE,EAAK,SAASF,IACxC,MAAMQ,EAAcX,GAAUK,CAAI,GAC3BD;AACT;AAEA,eAAsBQ,EACpBC,GACAC,GACAX,GAC8B;AAC9B,QAAMY,IAAMC,EAAqB,oBAAoBF,CAAS,GAExDG,IAAyB;AAAA,IAC7B,QAAQ;AAAA,IACR,SAAS,EAAE,gBAAgB,mBAAA;AAAA,IAC3B,MAAM,KAAK,UAAUJ,CAAO;AAAA,EAAA;AAE9B,EAAIV,MAAW,WAAWc,EAAU,SAASd;AAC7C,QAA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tF,GAAuC;AAChE,UAAM2J,IAAsC,CAAA,GACtCC,IAAqB,CAAA;AAC3B,aAAS,IAAI,GAAG,IAAI5J,EAAS,QAAQ,KAAK;AACxC,YAAMM,IAAUN,EAAS,CAAC,GACpB6J,IAAK,WAAW,CAAC;AACvB,MAAAD,EAAS,KAAKC,CAAE,GAChBF,EAASE,CAAE,IAAI;AAAA,QACb,MAAM;AAAA,QACN,OAAO;AAAA,UACL,SAAAvJ;AAAA,UACA,OAAO;AAAA,UACP,cAAc,KAAK,OAAO;AAAA,QAAA;AAAA,MAC5B;AAAA,IAEJ;AACA,WAAAqJ,EAAS,OAAU;AAAA,MACjB,MAAM;AAAA,MACN,OAAO;AAAA,QACL,QAAQ;AAAA,MAAA;AAAA,MAEV,UAAAC;AAAA,IAAA,GAEK;AAAA,MACL,MAAM;AAAA,MACN,UAAAD;AAAA,IAAA;AAAA,EAEJ;AAAA,EAEQ,iBACN1I,GAKQ;AACR,WAAO;AAAA,MACL,MAAM;AAAA,MACN,UAAU;AAAA,QACR,MAAM;AAAA,UACJ,MAAM;AAAA,UACN,OAAO,EAAE,QAAAA,EAAA;AAAA,QAAO;AAAA,MAClB;AAAA,IACF;AAAA,EAEJ;AACF;AAEO,SAAS6I,KAAoC;AAClD,SAAO,IAAIlC,GAAA;AACb;"}
@@ -0,0 +1,48 @@
1
+ "use strict";const $e=({element:t,renderElement:e})=>{if(!t.children||t.children.length===0)return null;const n=document.createElement("div");for(const s of t.children){const r=e(s);r&&n.appendChild(r)}return n};function rt(t){const e=document.createElement("div");if(e.className=t.containerClassName,!t.spec.elements[t.spec.root])return e;const s=t.unknownRenderer??$e,r=a=>{const o=t.spec.elements[a];if(!o)return null;const c=t.registry[o.type];return c?c({elementId:a,element:o,spec:t.spec,context:t.context,renderElement:r}):s({elementId:a,element:o,spec:t.spec,context:t.context,renderElement:r})},i=r(t.spec.root);return i&&e.appendChild(i),e}function it(t,e){if(!e)return t;const n={...t};for(const[s,r]of Object.entries(e))r&&(n[s]=r);return n}function at(t,e){const n={event_name:"stream.start",account_id:t.account_id,session_id:t.session_id,correlation_id:t.correlation_id,payload:{endpoint:e.endpoint,request_id:e.request_id}};return t.view_id!==void 0&&(n.view_id=t.view_id),t.user_id!==void 0&&(n.user_id=t.user_id),e.widget!==void 0&&(n.widget=e.widget),t.page_type!==void 0&&(n.page_type=t.page_type),t.sku!==void 0&&(n.sku=t.sku),n}function ot(t,e){const n={request_id:e.request_id,chunk_index:e.chunk_index};e.latency_ms!==void 0&&(n.latency_ms=e.latency_ms);const s={event_name:"stream.chunk",account_id:t.account_id,session_id:t.session_id,correlation_id:t.correlation_id,payload:n};return t.view_id!==void 0&&(s.view_id=t.view_id),t.user_id!==void 0&&(s.user_id=t.user_id),e.widget!==void 0&&(s.widget=e.widget),t.page_type!==void 0&&(s.page_type=t.page_type),t.sku!==void 0&&(s.sku=t.sku),s}function dt(t,e){const n={event_name:"stream.ui_spec",account_id:t.account_id,session_id:t.session_id,correlation_id:t.correlation_id,payload:{request_id:e.request_id,chunk_index:e.chunk_index,component_type:e.component_type}};return t.view_id!==void 0&&(n.view_id=t.view_id),t.user_id!==void 0&&(n.user_id=t.user_id),e.widget!==void 0&&(n.widget=e.widget),t.page_type!==void 0&&(n.page_type=t.page_type),t.sku!==void 0&&(n.sku=t.sku),n}function ct(t,e){const n={event_name:"stream.done",account_id:t.account_id,session_id:t.session_id,correlation_id:t.correlation_id,payload:{request_id:e.request_id,latency_ms:e.latency_ms,chunk_count:e.chunk_count}};return t.view_id!==void 0&&(n.view_id=t.view_id),t.user_id!==void 0&&(n.user_id=t.user_id),e.widget!==void 0&&(n.widget=e.widget),t.page_type!==void 0&&(n.page_type=t.page_type),t.sku!==void 0&&(n.sku=t.sku),n}function ut(t,e){const n={event_name:"stream.error",account_id:t.account_id,session_id:t.session_id,correlation_id:t.correlation_id,payload:{request_id:e.request_id,error_code:e.error_code,error_message:e.error_message}};return t.view_id!==void 0&&(n.view_id=t.view_id),t.user_id!==void 0&&(n.user_id=t.user_id),e.widget!==void 0&&(n.widget=e.widget),t.page_type!==void 0&&(n.page_type=t.page_type),t.sku!==void 0&&(n.sku=t.sku),n}function lt(t,e){const n={model:e.model,prompt_tokens:e.prompt_tokens,completion_tokens:e.completion_tokens,total_tokens:e.total_tokens};e.provider!==void 0&&(n.provider=e.provider);const s={event_name:"llm.usage",account_id:t.account_id,session_id:t.session_id,correlation_id:t.correlation_id,payload:n};return t.view_id!==void 0&&(s.view_id=t.view_id),t.user_id!==void 0&&(s.user_id=t.user_id),t.page_type!==void 0&&(s.page_type=t.page_type),t.sku!==void 0&&(s.sku=t.sku),s}function ft(t,e){const n={event_name:"metering.increment",account_id:t.account_id,session_id:t.session_id,correlation_id:t.correlation_id,payload:{meter_key:e.meter_key,quantity:e.quantity,unit:e.unit}};return t.view_id!==void 0&&(n.view_id=t.view_id),t.user_id!==void 0&&(n.user_id=t.user_id),t.page_type!==void 0&&(n.page_type=t.page_type),t.sku!==void 0&&(n.sku=t.sku),n}function De(t,e){const n={event_name:"metering.summary",account_id:t.account_id,session_id:t.session_id,correlation_id:t.correlation_id,payload:{meter_key:e.meter_key,quantity:e.quantity,unit:e.unit}};return t.view_id!==void 0&&(n.view_id=t.view_id),t.user_id!==void 0&&(n.user_id=t.user_id),t.page_type!==void 0&&(n.page_type=t.page_type),t.sku!==void 0&&(n.sku=t.sku),n}function pt(t,e){const n={event_name:"chat.history.snapshot",account_id:t.account_id,session_id:t.session_id,correlation_id:t.correlation_id,payload:{message_count:e.message_count,history_ref:e.history_ref,redaction_level:e.redaction_level}};return t.view_id!==void 0&&(n.view_id=t.view_id),t.user_id!==void 0&&(n.user_id=t.user_id),t.page_type!==void 0&&(n.page_type=t.page_type),t.sku!==void 0&&(n.sku=t.sku),n}function ht(t,e){const n={event_name:"widget.history.snapshot",account_id:t.account_id,session_id:t.session_id,correlation_id:t.correlation_id,widget:e.widget,payload:{message_count:e.message_count,history_ref:e.history_ref,redaction_level:e.redaction_level}};return t.view_id!==void 0&&(n.view_id=t.view_id),t.user_id!==void 0&&(n.user_id=t.user_id),t.page_type!==void 0&&(n.page_type=t.page_type),t.sku!==void 0&&(n.sku=t.sku),n}function mt(t,e){const n={event_name:"basket.add",account_id:t.account_id,session_id:t.session_id,correlation_id:t.correlation_id,widget:e.attribution_source,payload:{attribution_source:e.attribution_source,attribution_action_id:e.attribution_action_id,cart_value:e.cart_value,currency:e.currency,line_items:e.line_items,sku:e.sku}};return t.view_id!==void 0&&(n.view_id=t.view_id),t.user_id!==void 0&&(n.user_id=t.user_id),t.page_type!==void 0&&(n.page_type=t.page_type),t.sku!==void 0&&(n.sku=t.sku),n}function Me(t,e){const n={event_name:"checkout.start",account_id:t.account_id,session_id:t.session_id,correlation_id:t.correlation_id,widget:e.attribution_source,payload:{attribution_source:e.attribution_source,attribution_action_id:e.attribution_action_id,cart_value:e.cart_value,currency:e.currency,line_items:e.line_items}};return t.view_id!==void 0&&(n.view_id=t.view_id),t.user_id!==void 0&&(n.user_id=t.user_id),t.page_type!==void 0&&(n.page_type=t.page_type),t.sku!==void 0&&(n.sku=t.sku),n}function Ue(t,e){const n={event_name:"checkout.complete",account_id:t.account_id,session_id:t.session_id,correlation_id:t.correlation_id,widget:e.attribution_source,payload:{attribution_source:e.attribution_source,attribution_action_id:e.attribution_action_id,cart_value:e.cart_value,currency:e.currency,line_items:e.line_items}};return t.view_id!==void 0&&(n.view_id=t.view_id),t.user_id!==void 0&&(n.user_id=t.user_id),t.page_type!==void 0&&(n.page_type=t.page_type),t.sku!==void 0&&(n.sku=t.sku),n}function gt(t,e){window.dispatchEvent(new CustomEvent(t,{detail:e,bubbles:!1}))}function q(t,e){const n=s=>{e(s.detail)};return window.addEventListener(t,n),()=>window.removeEventListener(t,n)}function _t(t){let e=!1;function n(){return window.gengage?.chat!==void 0?!0:(e||(console.warn("[gengage] QNA tried to open chat, but chat widget is not initialized. Ensure GengageChat is initialized before calling wireQNAToChat()."),e=!0),t?.onChatUnavailable?.(),!1)}const s=q("gengage:qna:action",i=>{n()&&window.gengage?.chat?.openWithAction(i)}),r=q("gengage:qna:open-chat",()=>{n()&&window.gengage?.chat?.open()});return()=>{s(),r()}}function yt(){return q("gengage:similar:product-click",({sku:t,url:e,sessionId:n})=>{n&&window.gengage?.chat?.saveSession(n,t),window.location.href=e})}function ze(){const e=window.__gengageSessionId??sessionStorage.getItem("gengage_session_id")??null??crypto.randomUUID();return window.__gengageSessionId=e,sessionStorage.setItem("gengage_session_id",e),window.gengage||(window.gengage={}),window.gengage.sessionId=e,e}function vt(){return window.gengage?.pageContext??null}function kt(t){window.gengage||(window.gengage={}),window.gengage.pageContext={pageType:"other",...window.gengage.pageContext,...t},window.dispatchEvent(new CustomEvent("gengage:context:update",{detail:t}))}function Ve(t){return{sessionId:t?.sessionId??ze(),...t}}const ce={"--gengage-chat-offset":"20px","--gengage-chat-launcher-size":"56px","--gengage-chat-width":"400px","--gengage-chat-shell-radius":"12px","--gengage-chat-header-height":"60px","--gengage-chat-conversation-width":"396px","--gengage-chat-panel-min-width":"320px","--gengage-chat-panel-max-width":"860px","--gengage-chat-input-height":"48px","--gengage-qna-pill-radius":"999px","--gengage-qna-input-radius":"14px","--gengage-simrel-card-radius":"14px"};function qe(t){return t?{...ce,...t}:{...ce}}const j="gengage-global-toast-root",we="gengage-global-toast-style",ye="gengage-global-toast-root--visible",wt=4200,bt=1500,xt=15e3;let be=!1,M=null;function Tt(t){return typeof t=="string"&&t.toLowerCase().startsWith("tr")?"Baglanti sorunu olustu. Lutfen tekrar deneyin.":"Connection issue. Please try again."}function Be(){be||typeof window>"u"||typeof document>"u"||(be=!0,q("gengage:global:error",t=>{We(t)}))}function We(t){if(typeof document>"u")return;const e=t.message.trim();if(!e)return;At();const n=St();n.innerHTML="";const s=document.createElement("section");s.className="gengage-global-toast gengage-global-toast--error",s.setAttribute("role","status"),s.setAttribute("aria-live","polite");const r=document.createElement("div");r.className="gengage-global-toast-title",r.textContent=Ct(t.source);const i=document.createElement("div");i.className="gengage-global-toast-message",i.textContent=e,s.appendChild(r),s.appendChild(i),n.appendChild(s),n.classList.add(ye),M&&(clearTimeout(M),M=null),M=setTimeout(()=>{He()},Et(t.durationMs))}function He(){if(typeof document>"u")return;const t=document.getElementById(j);t&&(t.classList.remove(ye),t.innerHTML="",M&&(clearTimeout(M),M=null))}function Ct(t){switch(t){case"chat":return"Chat warning";case"qna":return"QnA warning";case"simrel":return"Widget warning";default:return"Connection warning"}}function St(){const t=document.getElementById(j);if(t instanceof HTMLElement)return t;const e=document.createElement("div");return e.id=j,e.className="gengage-global-toast-root",document.body.appendChild(e),e}function Et(t){return typeof t!="number"||!Number.isFinite(t)?wt:Math.min(xt,Math.max(bt,Math.round(t)))}function At(){if(document.getElementById(we))return;const t=document.createElement("style");t.id=we,t.textContent=`
2
+ #${j} {
3
+ position: fixed;
4
+ top: 16px;
5
+ right: 16px;
6
+ z-index: 2147483646;
7
+ pointer-events: none;
8
+ }
9
+ #${j}.${ye} {
10
+ pointer-events: auto;
11
+ }
12
+ #${j} .gengage-global-toast {
13
+ min-width: 260px;
14
+ max-width: min(92vw, 420px);
15
+ border-radius: 12px;
16
+ border: 1px solid #f5c2c7;
17
+ border-left: 4px solid #d93025;
18
+ background: #fff9f9;
19
+ color: #4a1f21;
20
+ box-shadow: 0 10px 30px rgba(38, 18, 18, 0.18);
21
+ padding: 10px 12px;
22
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
23
+ font-size: 13px;
24
+ line-height: 1.4;
25
+ animation: gengage-global-toast-in 180ms ease-out forwards;
26
+ }
27
+ #${j} .gengage-global-toast-title {
28
+ margin: 0 0 4px;
29
+ font-size: 12px;
30
+ font-weight: 700;
31
+ }
32
+ #${j} .gengage-global-toast-message {
33
+ margin: 0;
34
+ font-weight: 500;
35
+ }
36
+ @keyframes gengage-global-toast-in {
37
+ from {
38
+ opacity: 0;
39
+ transform: translateY(-8px);
40
+ }
41
+ to {
42
+ opacity: 1;
43
+ transform: translateY(0);
44
+ }
45
+ }
46
+ `,document.head.appendChild(t)}class It{constructor(){this.isVisible=!1,this.isInitialised=!1,this._handlers=new Map,this._cleanups=[],this._ownsRoot=!1}async init(e){if(this.isInitialised){console.warn("[gengage] Widget already initialised. Call update() instead.");return}const n=qe(e.theme);this.config={...e,theme:n,session:Ve(e.session)},this.root=this._resolveMount(e.mountTarget),this._applyTheme(n),Be();const s=q("gengage:context:update",r=>this.update(r));this._cleanups.push(s),await this.onInit(this.config),this.isInitialised=!0,this.emit("ready")}update(e){this.isInitialised&&(this.config.pageContext?this.config={...this.config,pageContext:{...this.config.pageContext,...e}}:this.config={...this.config,pageContext:e},this.onUpdate(e))}show(){this.isVisible||(this.isVisible=!0,this.root.style.display="",this.onShow(),this.emit("show"))}hide(){this.isVisible&&(this.isVisible=!1,this.root.style.display="none",this.onHide(),this.emit("hide"))}destroy(){this._cleanups.forEach(e=>e()),this._cleanups.length=0,this._handlers.clear(),this.onDestroy(),this._ownsRoot?this.root.remove():this.root.innerHTML="",this.isInitialised=!1}on(e,n){return this._handlers.has(e)||this._handlers.set(e,new Set),this._handlers.get(e).add(n),()=>this._handlers.get(e)?.delete(n)}trackCheckout(e,n){const s=e==="start"?Me:Ue;this.track(s(this.analyticsContext(),n))}flushMeteringSummary(e){this.track(De(this.analyticsContext(),e))}emit(e,...n){this._handlers.get(e)?.forEach(s=>s(...n))}addCleanup(e){this._cleanups.push(e)}track(e){this.config.analyticsClient?.track(e)}analyticsContext(){const e={account_id:this.config.accountId,session_id:this.config.session?.sessionId??"",correlation_id:this.config.session?.sessionId??""};return this.config.session?.viewId!==void 0&&(e.view_id=this.config.session.viewId),this.config.session?.userId!==void 0&&(e.user_id=this.config.session.userId),this.config.pageContext?.pageType!==void 0&&(e.page_type=this.config.pageContext.pageType),this.config.pageContext?.sku!==void 0&&(e.sku=this.config.pageContext.sku),e}_resolveMount(e){if(e instanceof HTMLElement)return e;if(typeof e=="string"){const s=document.querySelector(e);if(!s)throw new Error(`[gengage] Mount target not found: "${e}"`);return s}const n=document.createElement("div");return n.dataset.gengageWidget=this.constructor.name.toLowerCase(),document.body.appendChild(n),this._ownsRoot=!0,n}_applyTheme(e){if(e){for(const[n,s]of Object.entries(e))if(s!==void 0){const r=n.startsWith("--")?n:`--gengage-${Nt(n)}`;this.root.style.setProperty(r,s)}}}}function Nt(t){return t.replace(/([A-Z])/g,"-$1").toLowerCase()}function Rt(t){const e=[];let n=0,s=!1,r=!1,i=0;for(let a=0;a<t.length;a++){const o=t[a];if(r){r=!1;continue}if(o==="\\"&&s){r=!0;continue}if(o==='"'){s=!s;continue}s||(o==="{"&&n++,o==="}"&&(n--,n===0&&(e.push(t.slice(i,a+1)),i=a+1)))}return e.length>0?e:[t]}function xe(t,e){const n=t.trim();if(!n||n.startsWith(":"))return!1;const s=n.startsWith("data: ")?n.slice(6):n;if(s==="[DONE]")return!0;try{const r=JSON.parse(s);return e.onEvent(r),r.type==="done"?(e.onDone?.(),!0):!1}catch{const r=Rt(s);if(r.length>1){for(const i of r)try{const a=JSON.parse(i);if(e.onEvent(a),a.type==="done")return e.onDone?.(),!0}catch{}return!1}return!1}}async function Fe(t,e){if(!t.ok){e.onError?.(new Error(`HTTP ${t.status}: ${t.statusText}`));return}if(!t.body){e.onError?.(new Error("Response body is null — streaming not supported"));return}const n=t.body.getReader(),s=new TextDecoder("utf-8");let r="";try{for(;;){const{done:i,value:a}=await n.read();if(i)break;r+=s.decode(a,{stream:!0});const o=r.split(`
47
+ `);r=o.pop()??"";for(const c of o)if(xe(c,e))return}r.trim()&&xe(r,e)}catch(i){if(i instanceof DOMException&&i.name==="AbortError")return;e.onError?.(i instanceof Error?i:new Error(String(i)))}finally{n.releaseLock()}e.onDone?.()}function Ot(t,e,n){const s=new AbortController,r=n.signal?Zt([n.signal,s.signal]):s.signal;return fetch(t,{method:"POST",headers:{"Content-Type":"application/json",...n.headers},body:JSON.stringify(e),signal:r}).then(i=>Fe(i,{...n,signal:r})).catch(i=>{i instanceof DOMException&&i.name==="AbortError"||n.onError?.(i instanceof Error?i:new Error(String(i)))}),s}function Zt(t){const e=new AbortController;for(const n of t){if(n.aborted)return e.abort(n.reason),e.signal;n.addEventListener("abort",()=>e.abort(n.reason),{once:!0})}return e.signal}function Pt(t){if(typeof t.type!="string")return null;if(jt(t))return t;const n=t;switch(n.type){case"outputText":return Lt(n);case"suggestedActions":return $t(n);case"productList":return Dt(n);case"productDetails":return Mt(n);case"productDetailsSimilars":return Ut(n);case"comparisonTable":return zt(n);case"context":return Vt(n);case"chatStreamEnd":return qt();case"loading":return Bt(n);case"panelLoading":return Wt(n);case"similarLoading":return Ht(n);case"redirect":return Ft(n);case"error":return Gt(n);case"dummy":return Qt();case"launcherAction":return Jt(n);case"text":return ve(n);case"productItem":return Yt(n);case"text_image":return Ge(n);case"quick_qna":return Qe(n);case"reviewHighlights":return Kt(n);case"aiProductSuggestions":return tn(n);case"aiProductGroupings":return nn(n);case"aiSuggestedSearches":return sn(n);case"prosAndCons":return Xt(n);case"getGroundingReview":return rn(n);case"voice":return on(n);case"visitorDataResponse":return en(n);case"productListPreview":return an();case"groupList":return dn(n);case"formGetInfo":case"formTestDrive":case"formServiceRequest":case"launchFormPage":return cn(n);case"launcherContent":return un(n);default:return null}}function jt(t){const e=t.type;if(typeof e!="string")return!1;switch(e){case"metadata":return typeof t.sessionId=="string"&&typeof t.model=="string";case"text_chunk":return typeof t.content=="string";case"ui_spec":{const n=t.widget;if(n!=="chat"&&n!=="qna"&&n!=="simrel")return!1;const s=U(t.spec);return s?typeof s.root=="string"&&U(s.elements)!==null:!1}case"action":{const n=U(t.action);return n!==null&&typeof n.kind=="string"}case"error":return typeof t.code=="string"&&typeof t.message=="string";case"done":return!0;default:return!1}}function Lt(t){const e=k(t.payload.text,t.payload.plain_text)??"",n=k(t.payload.plain_text,t.payload.text)??e;if(t.payload.is_error)return{type:"error",code:"BACKEND_ERROR",message:n||"Backend returned an error"};const s={type:"text_chunk",content:e,final:!0},r=t.payload.product_mentions;Array.isArray(r)&&r.length>0&&(s.productMentions=r.filter(o=>typeof o=="object"&&o!==null&&typeof o.sku=="string"&&typeof o.short_name=="string"));const i=t.payload.sku_to_product_item;i&&typeof i=="object"&&!Array.isArray(i)&&(s.skuToProductItem=i);const a=t.payload.conversation_mode;return typeof a=="string"&&a&&(s.conversationMode=a),s}function $t(t){const e=(t.payload.actions??[]).map(n=>{const s=k(n.title)??"",r=D(n.requestDetails,s),i=r?{label:s,action:r}:null;return i?(typeof n.icon=="string"&&(i.icon=n.icon),typeof n.image=="string"&&(i.image=n.image),i):null});return Je(e.filter(Ke),"chat")}function Dt(t){const e=Ye(t.payload.product_list??[],"chat");e.panelHint="panel";const n=e.spec.elements[e.spec.root];return n&&(typeof t.payload.offset=="number"&&(n.props={...n.props,offset:t.payload.offset}),typeof t.payload.end_of_list=="boolean"&&(n.props={...n.props,endOfList:t.payload.end_of_list})),e}function Mt(t){const e=t.payload.productDetails;return e?{type:"ui_spec",widget:"chat",spec:{root:"root",elements:{root:{type:"ProductDetailsPanel",props:{product:O(e)}}}},panelHint:"panel"}:fn("chat")}function Ut(t){const e=Ye(t.payload.similarProducts??[],"chat"),n=e.spec.elements[e.spec.root];return n&&(n.props={...n.props,similarsAppend:!0}),{...e,panelHint:"panel"}}function zt(t){const e=t.payload.multiple_product_details??[],n=t.payload.product_comparison_framework,s=t.payload.table,r=[];for(const b of e){const Z=O(b);r.push(Z)}const i=[];if(s){const b=n?.criteria_view??n?.criteria_view_short??{},Z=n?.compared_field_names??Object.keys(s);for(const ie of Z){const ae=s[ie];if(!ae||!Array.isArray(ae))continue;const st=b[ie]??ie;i.push({label:st,values:ae.map(oe=>typeof oe=="string"?oe:String(oe??""))})}}let a;n?.recommended_choice_sku?a=n.recommended_choice_sku:n?.winner_product&&n.winner_product.length>0&&(a=n.winner_product[0]?.sku);const o=a?r.find(b=>b.sku===a)??r[0]:r[0],c=[];if(n?.key_differences)for(const b of n.key_differences)typeof b=="string"&&c.push(b);const l=[];if(n?.special_considerations)for(const b of n.special_considerations)typeof b=="string"&&l.push(b);const g=n?.recommended_choice,x=n?.winner_hits,E={};for(const b of r){const Z=b.sku;Z&&(E[Z]={title:b.name??Z,type:"launchSingleProduct",payload:{sku:Z}})}const C={products:r,attributes:i,highlights:c,productActions:E};return o&&(C.recommended=o),l.length>0&&(C.specialCases=l),g&&(C.recommendedText=g),x&&(C.winnerHits=x),typeof n?.key_differences=="string"&&(C.keyDifferencesHtml=n.key_differences),n?.special_considerations&&(C.specialConsiderations=n.special_considerations),{type:"ui_spec",widget:"chat",spec:{root:"root",elements:{root:{type:"ComparisonTable",props:C}}},panelHint:"panel"}}function Vt(t){return{type:"metadata",sessionId:"",model:"",meta:{panel:t.payload.panel,messages:t.payload.messages,message_id:t.payload.message_id}}}function qt(){return{type:"done"}}function Bt(t){return{type:"metadata",sessionId:"",model:"",meta:{loading:!0,loadingText:t.payload.text,thinkingMessages:t.payload.thinking_messages,dynamicLoading:t.payload.is_dynamic===!0}}}function Wt(t){return{type:"metadata",sessionId:"",model:"",meta:{loading:!0,panelLoading:!0,panelPendingType:t.payload?.pending_type,loadingText:t.payload?.text}}}function Ht(t){return{type:"metadata",sessionId:"",model:"",meta:{loading:!0,similarPanelLoading:!0,panelPendingType:t.payload?.pending_type,loadingText:t.payload?.text}}}function Ft(t){const e=k(t.payload.url);return e?{type:"action",action:{kind:"navigate",url:e,newTab:t.payload.new_tab===!0}}:{type:"metadata",sessionId:"",model:"",meta:{redirect:t.payload,redirectTarget:k(t.payload.to)}}}function Gt(t){return{type:"error",code:"BACKEND_ERROR",message:k(t.payload?.text,t.payload?.message,t.payload?.error)??"Backend returned an error"}}function Qt(t){return{type:"metadata",sessionId:"",model:"",meta:{noop:!0}}}function Jt(t){const e=t.payload??{};if(Array.isArray(e.action_list)){const i={action_list:e.action_list},a=typeof e.type=="string"?e.type:void 0,o=typeof e.theme=="string"?e.theme:void 0;return a!==void 0&&(i.type=a),o!==void 0&&(i.theme=o),Qe({payload:i})}const s=U(e.action);if(s){const i={action:s},a=typeof e.text=="string"?e.text:void 0,o=typeof e.image_url=="string"?e.image_url:void 0,c=typeof e.theme=="string"?e.theme:void 0;return a!==void 0&&(i.text=a),o!==void 0&&(i.image_url=o),c!==void 0&&(i.theme=c),Ge({payload:i})}const r=typeof e.text=="string"?e.text:"";if(r){const i={text:r},a=typeof e.type=="string"?e.type:void 0,o=typeof e.theme=="string"?e.theme:void 0,c=U(e.payload)??void 0;return a!==void 0&&(i.type=a),c!==void 0&&(i.payload=c),o!==void 0&&(i.theme=o),ve({payload:i})}return{type:"metadata",sessionId:"",model:"",meta:{launcherAction:e}}}function ve(t){const e={text:k(t.payload.text)??""};return typeof t.payload.theme=="string"&&(e.theme=t.payload.theme),t.payload.payload!==void 0&&(e.payload=t.payload.payload),{type:"ui_spec",widget:"qna",spec:{root:"root",elements:{root:{type:"QuestionHeading",props:e}}}}}function Yt(t){return ln(t.payload,"qna")}function Ge(t){const e=k(t.payload.text)??"",n=D(t.payload.action,e);if(n){const r={label:e||n.title,action:n};return typeof t.payload.image_url=="string"&&(r.image=t.payload.image_url),typeof t.payload.theme=="string"&&(r.theme=t.payload.theme),{type:"ui_spec",widget:"qna",spec:{root:"root",elements:{root:{type:"ActionButton",props:r}}}}}const s={text:e};return typeof t.payload.theme=="string"&&(s.theme=t.payload.theme),ve({payload:s})}function Qe(t){const e=(t.payload.action_list??[]).map(n=>{const s=k(n.title)??"",r=D(n.requestDetails,s),i=r?{label:s,action:r}:null;return i?(typeof n.icon=="string"&&(i.icon=n.icon),typeof n.image=="string"&&(i.image=n.image),i):null});return Je(e.filter(Ke),"qna")}function Kt(t){const n={reviews:(t.payload.reviews??[]).map(s=>{const r={};return typeof s.review_class=="string"&&(r.review_class=s.review_class),typeof s.review_text=="string"&&(r.review_text=s.review_text),(typeof s.review_rating=="string"||typeof s.review_rating=="number")&&(r.review_rating=s.review_rating),typeof s.review_tag=="string"&&(r.review_tag=s.review_tag),r})};return typeof t.payload.sku=="string"&&(n.sku=t.payload.sku),{type:"ui_spec",widget:"chat",spec:{root:"root",elements:{root:{type:"ReviewHighlights",props:n}}}}}function Xt(t){const e={};return Array.isArray(t.payload.pros)&&(e.pros=t.payload.pros),Array.isArray(t.payload.cons)&&(e.cons=t.payload.cons),typeof t.payload.product_name=="string"&&(e.productName=t.payload.product_name),{type:"ui_spec",widget:"chat",spec:{root:"root",elements:{root:{type:"ProsAndCons",props:e}}}}}function en(t){return{type:"metadata",sessionId:"",model:"",meta:{visitorDataResponse:t.payload}}}function tn(t){const e=t.payload.product_suggestions??[],n=[];for(let s=0;s<e.length;s++){const r=e[s];if(!r)continue;const i=pn(r);if(!i)continue;const a={product:i},o=D(r.requestDetails,i.name);o&&(a.action=o),typeof r.role=="string"&&(a.role=r.role),typeof r.reason=="string"&&(a.reason=r.reason),typeof r.review_highlight=="string"&&(a.reviewHighlight=r.review_highlight),Array.isArray(r.labels)&&(a.labels=r.labels),typeof r.expert_quality_score=="number"&&(a.expertQualityScore=r.expert_quality_score),n.push(a)}return n.length===0?{type:"metadata",sessionId:"",model:"",meta:{aiProductSuggestions:t.payload.product_suggestions??[]}}:{type:"ui_spec",widget:"chat",spec:{root:"root",elements:{root:{type:"AITopPicks",props:{suggestions:n}}}}}}function nn(t){const e=t.payload.product_groupings??[],n=[];for(let s=0;s<e.length;s++){const r=e[s];if(!r)continue;const i=k(r.name)??"",a=r.sku&&r.sku.length>0?{type:"findSimilar",payload:{sku:r.sku}}:void 0,o=D(r.requestDetails??a,i);if(!o)continue;const c={name:i,action:o};if(Array.isArray(r.labels)){const l=r.labels.filter(g=>typeof g=="string");l.length>0&&(c.labels=l)}typeof r.image=="string"&&(c.image=r.image),n.push(c)}return n.length===0?{type:"metadata",sessionId:"",model:"",meta:{aiProductGroupings:t.payload.product_groupings??[]}}:{type:"ui_spec",widget:"chat",spec:{root:"root",elements:{root:{type:"AIGroupingCards",props:{entries:n}}}}}}function sn(t){const e=t.payload.suggested_searches??[],n=[];for(let s=0;s<e.length;s++){const r=e[s];if(!r)continue;const i=k(r.short_name,r.chosen_attribute,r.detailed_user_message)??`Arama ${s+1}`,a={},o=k(r.detailed_user_message);o&&(a.text=o),r.group_skus&&Array.isArray(r.group_skus)&&(a.group_skus=r.group_skus);const c=k(r.sku,r.representative_product_sku);c&&(a.sku=c),a.is_suggested_text=1;const l={type:"inputText",payload:a},g=D(r.requestDetails??l,i);if(!g)continue;const x={shortName:i,action:g},E=k(r.detailed_user_message);E&&E!==i&&(x.detailedMessage=E);const C=k(r.why_different);C&&(x.whyDifferent=C),typeof r.image=="string"&&(x.image=r.image),n.push(x)}return n.length===0?{type:"metadata",sessionId:"",model:"",meta:{aiSuggestedSearches:t.payload.suggested_searches??[]}}:{type:"ui_spec",widget:"chat",spec:{root:"root",elements:{root:{type:"AISuggestedSearchCards",props:{entries:n}}}}}}function rn(t){const e=D(t.payload.requestDetails,k(t.payload.review_count,t.payload.text,t.payload.title)??"Urun yorumlarini goster");if(!e)return{type:"metadata",sessionId:"",model:"",meta:{groundingReview:t.payload}};const n={action:e};return t.payload.title&&(n.title=t.payload.title),t.payload.text&&(n.text=t.payload.text),t.payload.review_count&&(n.reviewCount=t.payload.review_count),{type:"ui_spec",widget:"chat",spec:{root:"root",elements:{root:{type:"GroundingReviewCard",props:n}}}}}function an(){return{type:"metadata",sessionId:"",model:"",meta:{analyzeAnimation:!0}}}function on(t){return{type:"metadata",sessionId:"",model:"",meta:{voice:t.payload}}}function dn(t){const e=t.payload.group_list??[],n=[];for(const r of e){const i=r.group_name??"",a=(r.product_list??[]).map(O);n.push({groupName:i,products:a})}const s=[];for(const r of t.payload.filter_tags??[]){const i=r.title??"";if(!i)continue;const a=D(r.requestDetails,i),o={title:i};a&&(o.action=a),s.push(o)}return{type:"ui_spec",widget:"chat",spec:{root:"root",elements:{root:{type:"CategoriesContainer",props:{groups:n,filterTags:s}}}},panelHint:"panel"}}function cn(t){return{type:"metadata",sessionId:"",model:"",meta:{formType:t.type,formPayload:t.payload??{}}}}function un(t){return{type:"metadata",sessionId:"",model:"",meta:{launcherContent:t.payload??{}}}}function Je(t,e){const n={},s=[];for(let r=0;r<t.length;r++){const i=t[r];if(!i)continue;const a=`action-${r}`;s.push(a);const o={label:i.label,action:i.action};i.icon!==void 0&&(o.icon=i.icon),i.image!==void 0&&(o.image=i.image),i.description!==void 0&&(o.description=i.description),n[a]={type:"ActionButton",props:o}}return n.root={type:"ActionButtons",props:{buttons:t.map(r=>{const i={label:r.label,action:r.action};return r.image!==void 0&&(i.image=r.image),r.description!==void 0&&(i.description=r.description),r.icon!==void 0&&(i.icon=r.icon),i})},children:s},{type:"ui_spec",widget:e,spec:{root:"root",elements:n}}}function Ye(t,e){const n={},s=[];for(let r=0;r<t.length;r++){const i=t[r];if(!i)continue;const a=`product-${r}`;s.push(a),n[a]={type:"ProductCard",props:{product:O(i),index:r}}}return n.root={type:"ProductGrid",props:{layout:"grid"},children:s},{type:"ui_spec",widget:e,spec:{root:"root",elements:n}}}function ln(t,e){return{type:"ui_spec",widget:e,spec:{root:"root",elements:{root:{type:"ProductCard",props:{product:O(t),index:0}}}}}}function fn(t){return{type:"ui_spec",widget:t,spec:{root:"root",elements:{root:{type:"ActionButtons",props:{buttons:[]},children:[]}}}}}function pn(t){const e=k(t.sku),n=k(t.short_name),s=U(t.product_item)??t;return hn(s,e,n)}function hn(t,e,n){const s=k(t.sku,e),r=k(t.name,n);if(!s||!r)return null;const i={sku:s,name:r},a=k(t.brand);a&&(i.brand=a);const o=k(t.url);o&&(i.url=o);const c=mn(t.images);if(c.length>0)i.images=c;else{const b=k(t.image,t.image_url,t.imageUrl);b&&(i.images=[b])}const l=Q(t.price_discounted);l!==void 0&&(i.price_discounted=l);const g=Q(t.price);g!==void 0&&(i.price=g);const x=Q(t.rating);x!==void 0&&(i.rating=x);const E=Q(t.review_count)??Q(t.reviewCount);E!==void 0&&(i.review_count=E);const C=k(t.cart_code,t.cartCode);return C&&(i.cart_code=C),typeof t.in_stock=="boolean"&&(i.in_stock=t.in_stock),typeof t.inStock=="boolean"&&(i.in_stock=t.inStock),O(i)}function D(t,e){const n=U(t);if(!n)return null;const s=n.type;if(typeof s!="string"||s.length===0)return null;const r={title:e||s,type:s};return n.payload!==void 0&&(r.payload=n.payload),r}function U(t){return!t||typeof t!="object"||Array.isArray(t)?null:t}function k(...t){for(const e of t)if(typeof e=="string"){const n=e.trim();if(n.length>0)return n}}function mn(t){return Array.isArray(t)?t.filter(e=>typeof e=="string"&&e.length>0):[]}function Q(t){if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"){const e=t.replace(",","."),n=Number(e);if(Number.isFinite(n))return n}}function Ke(t){return t!=null}function O(t){const e=t.price_discounted!=null&&t.price_discounted>0?t.price_discounted:t.price,n=t.price_discounted!=null&&t.price_discounted>0&&t.price!=null?t.price:void 0;let s;n!=null&&e!=null&&n>0&&(s=Math.round((n-e)/n*100));const r=k(t.brand),i=k(t.name)??t.sku,a=r&&!i.startsWith(r)?`${r} ${i}`:i,o={sku:t.sku,name:a,url:k(t.url)??""},c=t.images?.[0];return c&&(o.imageUrl=c),t.images&&t.images.length>1&&(o.images=t.images),e!=null&&(o.price=String(e)),n!=null&&(o.originalPrice=String(n)),s!==void 0&&(o.discountPercent=s),r!==void 0&&(o.brand=r),t.rating!==void 0&&(o.rating=t.rating),t.review_count!==void 0&&(o.reviewCount=t.review_count),t.cart_code!==void 0&&(o.cartCode=t.cart_code),t.in_stock!==void 0&&(o.inStock=t.in_stock),t.variants&&t.variants.length>0&&(o.variants=t.variants),t.discount_reason!==void 0&&(o.discountReason=t.discount_reason),t.promotions&&t.promotions.length>0&&(o.promotions=t.promotions),o}function gn(t){return t.results.map(O)}function _n(t){return t.product_groupings.map(e=>{const n={name:e.name,products:(e.group_products??[]).map(O)};return e.highlight!==void 0&&(n.highlight=e.highlight),n})}const yn={process_action:"/process_action",launcher_action:"/launcher_action",similar_products:"/similar_products",product_groupings:"/product_groupings",proactive_action:"/proactive_action"};function Xe(t){if(t===void 0)throw new Error("[gengage] middlewareUrl is required. Pass your Gengage backend URL in widget config.");const e=t.trim();return e===""?"":e.replace(/\/+$/,"")}function vn(t,e){return`${Xe(e?.middlewareUrl)}/chat${yn[t]}`}var v;(function(t){t.assertEqual=r=>{};function e(r){}t.assertIs=e;function n(r){throw new Error}t.assertNever=n,t.arrayToEnum=r=>{const i={};for(const a of r)i[a]=a;return i},t.getValidEnumValues=r=>{const i=t.objectKeys(r).filter(o=>typeof r[r[o]]!="number"),a={};for(const o of i)a[o]=r[o];return t.objectValues(a)},t.objectValues=r=>t.objectKeys(r).map(function(i){return r[i]}),t.objectKeys=typeof Object.keys=="function"?r=>Object.keys(r):r=>{const i=[];for(const a in r)Object.prototype.hasOwnProperty.call(r,a)&&i.push(a);return i},t.find=(r,i)=>{for(const a of r)if(i(a))return a},t.isInteger=typeof Number.isInteger=="function"?r=>Number.isInteger(r):r=>typeof r=="number"&&Number.isFinite(r)&&Math.floor(r)===r;function s(r,i=" | "){return r.map(a=>typeof a=="string"?`'${a}'`:a).join(i)}t.joinValues=s,t.jsonStringifyReplacer=(r,i)=>typeof i=="bigint"?i.toString():i})(v||(v={}));var Te;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(Te||(Te={}));const f=v.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),P=t=>{switch(typeof t){case"undefined":return f.undefined;case"string":return f.string;case"number":return Number.isNaN(t)?f.nan:f.number;case"boolean":return f.boolean;case"function":return f.function;case"bigint":return f.bigint;case"symbol":return f.symbol;case"object":return Array.isArray(t)?f.array:t===null?f.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?f.promise:typeof Map<"u"&&t instanceof Map?f.map:typeof Set<"u"&&t instanceof Set?f.set:typeof Date<"u"&&t instanceof Date?f.date:f.object;default:return f.unknown}},d=v.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class R extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=s=>{this.issues=[...this.issues,s]},this.addIssues=(s=[])=>{this.issues=[...this.issues,...s]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){const n=e||function(i){return i.message},s={_errors:[]},r=i=>{for(const a of i.issues)if(a.code==="invalid_union")a.unionErrors.map(r);else if(a.code==="invalid_return_type")r(a.returnTypeError);else if(a.code==="invalid_arguments")r(a.argumentsError);else if(a.path.length===0)s._errors.push(n(a));else{let o=s,c=0;for(;c<a.path.length;){const l=a.path[c];c===a.path.length-1?(o[l]=o[l]||{_errors:[]},o[l]._errors.push(n(a))):o[l]=o[l]||{_errors:[]},o=o[l],c++}}};return r(this),s}static assert(e){if(!(e instanceof R))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,v.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){const n={},s=[];for(const r of this.issues)if(r.path.length>0){const i=r.path[0];n[i]=n[i]||[],n[i].push(e(r))}else s.push(e(r));return{formErrors:s,fieldErrors:n}}get formErrors(){return this.flatten()}}R.create=t=>new R(t);const ue=(t,e)=>{let n;switch(t.code){case d.invalid_type:t.received===f.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case d.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,v.jsonStringifyReplacer)}`;break;case d.unrecognized_keys:n=`Unrecognized key(s) in object: ${v.joinValues(t.keys,", ")}`;break;case d.invalid_union:n="Invalid input";break;case d.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${v.joinValues(t.options)}`;break;case d.invalid_enum_value:n=`Invalid enum value. Expected ${v.joinValues(t.options)}, received '${t.received}'`;break;case d.invalid_arguments:n="Invalid function arguments";break;case d.invalid_return_type:n="Invalid function return type";break;case d.invalid_date:n="Invalid date";break;case d.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:v.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case d.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case d.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case d.custom:n="Invalid input";break;case d.invalid_intersection_types:n="Intersection results could not be merged";break;case d.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case d.not_finite:n="Number must be finite";break;default:n=e.defaultError,v.assertNever(t)}return{message:n}};let kn=ue;function wn(){return kn}const bn=t=>{const{data:e,path:n,errorMaps:s,issueData:r}=t,i=[...n,...r.path||[]],a={...r,path:i};if(r.message!==void 0)return{...r,path:i,message:r.message};let o="";const c=s.filter(l=>!!l).slice().reverse();for(const l of c)o=l(a,{data:e,defaultError:o}).message;return{...r,path:i,message:o}};function u(t,e){const n=wn(),s=bn({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===ue?void 0:ue].filter(r=>!!r)});t.common.issues.push(s)}class T{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){const s=[];for(const r of n){if(r.status==="aborted")return m;r.status==="dirty"&&e.dirty(),s.push(r.value)}return{status:e.value,value:s}}static async mergeObjectAsync(e,n){const s=[];for(const r of n){const i=await r.key,a=await r.value;s.push({key:i,value:a})}return T.mergeObjectSync(e,s)}static mergeObjectSync(e,n){const s={};for(const r of n){const{key:i,value:a}=r;if(i.status==="aborted"||a.status==="aborted")return m;i.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof a.value<"u"||r.alwaysSet)&&(s[i.value]=a.value)}return{status:e.value,value:s}}}const m=Object.freeze({status:"aborted"}),J=t=>({status:"dirty",value:t}),S=t=>({status:"valid",value:t}),Ce=t=>t.status==="aborted",Se=t=>t.status==="dirty",B=t=>t.status==="valid",X=t=>typeof Promise<"u"&&t instanceof Promise;var p;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(p||(p={}));class I{constructor(e,n,s,r){this._cachedPath=[],this.parent=e,this.data=n,this._path=s,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const Ee=(t,e)=>{if(B(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new R(t.common.issues);return this._error=n,this._error}}};function _(t){if(!t)return{};const{errorMap:e,invalid_type_error:n,required_error:s,description:r}=t;if(e&&(n||s))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:r}:{errorMap:(a,o)=>{const{message:c}=t;return a.code==="invalid_enum_value"?{message:c??o.defaultError}:typeof o.data>"u"?{message:c??s??o.defaultError}:a.code!=="invalid_type"?{message:o.defaultError}:{message:c??n??o.defaultError}},description:r}}class y{get description(){return this._def.description}_getType(e){return P(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:P(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new T,ctx:{common:e.parent.common,data:e.data,parsedType:P(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const n=this._parse(e);if(X(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){const n=this._parse(e);return Promise.resolve(n)}parse(e,n){const s=this.safeParse(e,n);if(s.success)return s.data;throw s.error}safeParse(e,n){const s={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:P(e)},r=this._parseSync({data:e,path:s.path,parent:s});return Ee(s,r)}"~validate"(e){const n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:P(e)};if(!this["~standard"].async)try{const s=this._parseSync({data:e,path:[],parent:n});return B(s)?{value:s.value}:{issues:n.common.issues}}catch(s){s?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(s=>B(s)?{value:s.value}:{issues:n.common.issues})}async parseAsync(e,n){const s=await this.safeParseAsync(e,n);if(s.success)return s.data;throw s.error}async safeParseAsync(e,n){const s={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:P(e)},r=this._parse({data:e,path:s.path,parent:s}),i=await(X(r)?r:Promise.resolve(r));return Ee(s,i)}refine(e,n){const s=r=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(r):n;return this._refinement((r,i)=>{const a=e(r),o=()=>i.addIssue({code:d.custom,...s(r)});return typeof Promise<"u"&&a instanceof Promise?a.then(c=>c?!0:(o(),!1)):a?!0:(o(),!1)})}refinement(e,n){return this._refinement((s,r)=>e(s)?!0:(r.addIssue(typeof n=="function"?n(s,r):n),!1))}_refinement(e){return new F({schema:this,typeName:h.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return L.create(this,this._def)}nullable(){return G.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return A.create(this)}promise(){return re.create(this,this._def)}or(e){return te.create([this,e],this._def)}and(e){return ne.create(this,e,this._def)}transform(e){return new F({..._(this._def),schema:this,typeName:h.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const n=typeof e=="function"?e:()=>e;return new me({..._(this._def),innerType:this,defaultValue:n,typeName:h.ZodDefault})}brand(){return new Wn({typeName:h.ZodBranded,type:this,..._(this._def)})}catch(e){const n=typeof e=="function"?e:()=>e;return new ge({..._(this._def),innerType:this,catchValue:n,typeName:h.ZodCatch})}describe(e){const n=this.constructor;return new n({...this._def,description:e})}pipe(e){return ke.create(this,e)}readonly(){return _e.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const xn=/^c[^\s-]{8,}$/i,Tn=/^[0-9a-z]+$/,Cn=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Sn=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,En=/^[a-z0-9_-]{21}$/i,An=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,In=/^[-+]?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)?)??$/,Nn=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Rn="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let de;const On=/^(?:(?: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]|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,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Ln=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,$n=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,et="((\\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])))",Dn=new RegExp(`^${et}$`);function tt(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);const n=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function Mn(t){return new RegExp(`^${tt(t)}$`)}function Un(t){let e=`${et}T${tt(t)}`;const n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function zn(t,e){return!!((e==="v4"||!e)&&On.test(t)||(e==="v6"||!e)&&Pn.test(t))}function Vn(t,e){if(!An.test(t))return!1;try{const[n]=t.split(".");if(!n)return!1;const s=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),r=JSON.parse(atob(s));return!(typeof r!="object"||r===null||"typ"in r&&r?.typ!=="JWT"||!r.alg||e&&r.alg!==e)}catch{return!1}}function qn(t,e){return!!((e==="v4"||!e)&&Zn.test(t)||(e==="v6"||!e)&&jn.test(t))}class N extends y{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==f.string){const i=this._getOrReturnCtx(e);return u(i,{code:d.invalid_type,expected:f.string,received:i.parsedType}),m}const s=new T;let r;for(const i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(r=this._getOrReturnCtx(e,r),u(r,{code:d.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),s.dirty());else if(i.kind==="max")e.data.length>i.value&&(r=this._getOrReturnCtx(e,r),u(r,{code:d.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),s.dirty());else if(i.kind==="length"){const a=e.data.length>i.value,o=e.data.length<i.value;(a||o)&&(r=this._getOrReturnCtx(e,r),a?u(r,{code:d.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):o&&u(r,{code:d.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),s.dirty())}else if(i.kind==="email")Nn.test(e.data)||(r=this._getOrReturnCtx(e,r),u(r,{validation:"email",code:d.invalid_string,message:i.message}),s.dirty());else if(i.kind==="emoji")de||(de=new RegExp(Rn,"u")),de.test(e.data)||(r=this._getOrReturnCtx(e,r),u(r,{validation:"emoji",code:d.invalid_string,message:i.message}),s.dirty());else if(i.kind==="uuid")Sn.test(e.data)||(r=this._getOrReturnCtx(e,r),u(r,{validation:"uuid",code:d.invalid_string,message:i.message}),s.dirty());else if(i.kind==="nanoid")En.test(e.data)||(r=this._getOrReturnCtx(e,r),u(r,{validation:"nanoid",code:d.invalid_string,message:i.message}),s.dirty());else if(i.kind==="cuid")xn.test(e.data)||(r=this._getOrReturnCtx(e,r),u(r,{validation:"cuid",code:d.invalid_string,message:i.message}),s.dirty());else if(i.kind==="cuid2")Tn.test(e.data)||(r=this._getOrReturnCtx(e,r),u(r,{validation:"cuid2",code:d.invalid_string,message:i.message}),s.dirty());else if(i.kind==="ulid")Cn.test(e.data)||(r=this._getOrReturnCtx(e,r),u(r,{validation:"ulid",code:d.invalid_string,message:i.message}),s.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{r=this._getOrReturnCtx(e,r),u(r,{validation:"url",code:d.invalid_string,message:i.message}),s.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(r=this._getOrReturnCtx(e,r),u(r,{validation:"regex",code:d.invalid_string,message:i.message}),s.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(r=this._getOrReturnCtx(e,r),u(r,{code:d.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),s.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(r=this._getOrReturnCtx(e,r),u(r,{code:d.invalid_string,validation:{startsWith:i.value},message:i.message}),s.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(r=this._getOrReturnCtx(e,r),u(r,{code:d.invalid_string,validation:{endsWith:i.value},message:i.message}),s.dirty()):i.kind==="datetime"?Un(i).test(e.data)||(r=this._getOrReturnCtx(e,r),u(r,{code:d.invalid_string,validation:"datetime",message:i.message}),s.dirty()):i.kind==="date"?Dn.test(e.data)||(r=this._getOrReturnCtx(e,r),u(r,{code:d.invalid_string,validation:"date",message:i.message}),s.dirty()):i.kind==="time"?Mn(i).test(e.data)||(r=this._getOrReturnCtx(e,r),u(r,{code:d.invalid_string,validation:"time",message:i.message}),s.dirty()):i.kind==="duration"?In.test(e.data)||(r=this._getOrReturnCtx(e,r),u(r,{validation:"duration",code:d.invalid_string,message:i.message}),s.dirty()):i.kind==="ip"?zn(e.data,i.version)||(r=this._getOrReturnCtx(e,r),u(r,{validation:"ip",code:d.invalid_string,message:i.message}),s.dirty()):i.kind==="jwt"?Vn(e.data,i.alg)||(r=this._getOrReturnCtx(e,r),u(r,{validation:"jwt",code:d.invalid_string,message:i.message}),s.dirty()):i.kind==="cidr"?qn(e.data,i.version)||(r=this._getOrReturnCtx(e,r),u(r,{validation:"cidr",code:d.invalid_string,message:i.message}),s.dirty()):i.kind==="base64"?Ln.test(e.data)||(r=this._getOrReturnCtx(e,r),u(r,{validation:"base64",code:d.invalid_string,message:i.message}),s.dirty()):i.kind==="base64url"?$n.test(e.data)||(r=this._getOrReturnCtx(e,r),u(r,{validation:"base64url",code:d.invalid_string,message:i.message}),s.dirty()):v.assertNever(i);return{status:s.value,value:e.data}}_regex(e,n,s){return this.refinement(r=>e.test(r),{validation:n,code:d.invalid_string,...p.errToObj(s)})}_addCheck(e){return new N({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...p.errToObj(e)})}url(e){return this._addCheck({kind:"url",...p.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...p.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...p.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...p.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...p.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...p.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...p.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...p.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...p.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...p.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...p.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...p.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...p.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...p.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...p.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...p.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...p.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...p.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...p.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...p.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...p.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...p.errToObj(n)})}nonempty(e){return this.min(1,p.errToObj(e))}trim(){return new N({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new N({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new N({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}}N.create=t=>new N({checks:[],typeName:h.ZodString,coerce:t?.coerce??!1,..._(t)});function Bn(t,e){const n=(t.toString().split(".")[1]||"").length,s=(e.toString().split(".")[1]||"").length,r=n>s?n:s,i=Number.parseInt(t.toFixed(r).replace(".","")),a=Number.parseInt(e.toFixed(r).replace(".",""));return i%a/10**r}class W extends y{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==f.number){const i=this._getOrReturnCtx(e);return u(i,{code:d.invalid_type,expected:f.number,received:i.parsedType}),m}let s;const r=new T;for(const i of this._def.checks)i.kind==="int"?v.isInteger(e.data)||(s=this._getOrReturnCtx(e,s),u(s,{code:d.invalid_type,expected:"integer",received:"float",message:i.message}),r.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(s=this._getOrReturnCtx(e,s),u(s,{code:d.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),r.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(s=this._getOrReturnCtx(e,s),u(s,{code:d.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),r.dirty()):i.kind==="multipleOf"?Bn(e.data,i.value)!==0&&(s=this._getOrReturnCtx(e,s),u(s,{code:d.not_multiple_of,multipleOf:i.value,message:i.message}),r.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(s=this._getOrReturnCtx(e,s),u(s,{code:d.not_finite,message:i.message}),r.dirty()):v.assertNever(i);return{status:r.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,p.toString(n))}gt(e,n){return this.setLimit("min",e,!1,p.toString(n))}lte(e,n){return this.setLimit("max",e,!0,p.toString(n))}lt(e,n){return this.setLimit("max",e,!1,p.toString(n))}setLimit(e,n,s,r){return new W({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:s,message:p.toString(r)}]})}_addCheck(e){return new W({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:p.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:p.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:p.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:p.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:p.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:p.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:p.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:p.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:p.toString(e)})}get minValue(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&v.isInteger(e.value))}get isFinite(){let e=null,n=null;for(const s of this._def.checks){if(s.kind==="finite"||s.kind==="int"||s.kind==="multipleOf")return!0;s.kind==="min"?(n===null||s.value>n)&&(n=s.value):s.kind==="max"&&(e===null||s.value<e)&&(e=s.value)}return Number.isFinite(n)&&Number.isFinite(e)}}W.create=t=>new W({checks:[],typeName:h.ZodNumber,coerce:t?.coerce||!1,..._(t)});class Y extends y{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==f.bigint)return this._getInvalidInput(e);let s;const r=new T;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(s=this._getOrReturnCtx(e,s),u(s,{code:d.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),r.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(s=this._getOrReturnCtx(e,s),u(s,{code:d.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),r.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(s=this._getOrReturnCtx(e,s),u(s,{code:d.not_multiple_of,multipleOf:i.value,message:i.message}),r.dirty()):v.assertNever(i);return{status:r.value,value:e.data}}_getInvalidInput(e){const n=this._getOrReturnCtx(e);return u(n,{code:d.invalid_type,expected:f.bigint,received:n.parsedType}),m}gte(e,n){return this.setLimit("min",e,!0,p.toString(n))}gt(e,n){return this.setLimit("min",e,!1,p.toString(n))}lte(e,n){return this.setLimit("max",e,!0,p.toString(n))}lt(e,n){return this.setLimit("max",e,!1,p.toString(n))}setLimit(e,n,s,r){return new Y({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:s,message:p.toString(r)}]})}_addCheck(e){return new Y({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:p.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:p.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:p.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:p.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:p.toString(n)})}get minValue(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}}Y.create=t=>new Y({checks:[],typeName:h.ZodBigInt,coerce:t?.coerce??!1,..._(t)});class le extends y{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==f.boolean){const s=this._getOrReturnCtx(e);return u(s,{code:d.invalid_type,expected:f.boolean,received:s.parsedType}),m}return S(e.data)}}le.create=t=>new le({typeName:h.ZodBoolean,coerce:t?.coerce||!1,..._(t)});class ee extends y{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==f.date){const i=this._getOrReturnCtx(e);return u(i,{code:d.invalid_type,expected:f.date,received:i.parsedType}),m}if(Number.isNaN(e.data.getTime())){const i=this._getOrReturnCtx(e);return u(i,{code:d.invalid_date}),m}const s=new T;let r;for(const i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(r=this._getOrReturnCtx(e,r),u(r,{code:d.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),s.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(r=this._getOrReturnCtx(e,r),u(r,{code:d.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),s.dirty()):v.assertNever(i);return{status:s.value,value:new Date(e.data.getTime())}}_addCheck(e){return new ee({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:p.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:p.toString(n)})}get minDate(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}}ee.create=t=>new ee({checks:[],coerce:t?.coerce||!1,typeName:h.ZodDate,..._(t)});class Ae extends y{_parse(e){if(this._getType(e)!==f.symbol){const s=this._getOrReturnCtx(e);return u(s,{code:d.invalid_type,expected:f.symbol,received:s.parsedType}),m}return S(e.data)}}Ae.create=t=>new Ae({typeName:h.ZodSymbol,..._(t)});class Ie extends y{_parse(e){if(this._getType(e)!==f.undefined){const s=this._getOrReturnCtx(e);return u(s,{code:d.invalid_type,expected:f.undefined,received:s.parsedType}),m}return S(e.data)}}Ie.create=t=>new Ie({typeName:h.ZodUndefined,..._(t)});class Ne extends y{_parse(e){if(this._getType(e)!==f.null){const s=this._getOrReturnCtx(e);return u(s,{code:d.invalid_type,expected:f.null,received:s.parsedType}),m}return S(e.data)}}Ne.create=t=>new Ne({typeName:h.ZodNull,..._(t)});class Re extends y{constructor(){super(...arguments),this._any=!0}_parse(e){return S(e.data)}}Re.create=t=>new Re({typeName:h.ZodAny,..._(t)});class fe extends y{constructor(){super(...arguments),this._unknown=!0}_parse(e){return S(e.data)}}fe.create=t=>new fe({typeName:h.ZodUnknown,..._(t)});class $ extends y{_parse(e){const n=this._getOrReturnCtx(e);return u(n,{code:d.invalid_type,expected:f.never,received:n.parsedType}),m}}$.create=t=>new $({typeName:h.ZodNever,..._(t)});class Oe extends y{_parse(e){if(this._getType(e)!==f.undefined){const s=this._getOrReturnCtx(e);return u(s,{code:d.invalid_type,expected:f.void,received:s.parsedType}),m}return S(e.data)}}Oe.create=t=>new Oe({typeName:h.ZodVoid,..._(t)});class A extends y{_parse(e){const{ctx:n,status:s}=this._processInputParams(e),r=this._def;if(n.parsedType!==f.array)return u(n,{code:d.invalid_type,expected:f.array,received:n.parsedType}),m;if(r.exactLength!==null){const a=n.data.length>r.exactLength.value,o=n.data.length<r.exactLength.value;(a||o)&&(u(n,{code:a?d.too_big:d.too_small,minimum:o?r.exactLength.value:void 0,maximum:a?r.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:r.exactLength.message}),s.dirty())}if(r.minLength!==null&&n.data.length<r.minLength.value&&(u(n,{code:d.too_small,minimum:r.minLength.value,type:"array",inclusive:!0,exact:!1,message:r.minLength.message}),s.dirty()),r.maxLength!==null&&n.data.length>r.maxLength.value&&(u(n,{code:d.too_big,maximum:r.maxLength.value,type:"array",inclusive:!0,exact:!1,message:r.maxLength.message}),s.dirty()),n.common.async)return Promise.all([...n.data].map((a,o)=>r.type._parseAsync(new I(n,a,n.path,o)))).then(a=>T.mergeArray(s,a));const i=[...n.data].map((a,o)=>r.type._parseSync(new I(n,a,n.path,o)));return T.mergeArray(s,i)}get element(){return this._def.type}min(e,n){return new A({...this._def,minLength:{value:e,message:p.toString(n)}})}max(e,n){return new A({...this._def,maxLength:{value:e,message:p.toString(n)}})}length(e,n){return new A({...this._def,exactLength:{value:e,message:p.toString(n)}})}nonempty(e){return this.min(1,e)}}A.create=(t,e)=>new A({type:t,minLength:null,maxLength:null,exactLength:null,typeName:h.ZodArray,..._(e)});function V(t){if(t instanceof w){const e={};for(const n in t.shape){const s=t.shape[n];e[n]=L.create(V(s))}return new w({...t._def,shape:()=>e})}else return t instanceof A?new A({...t._def,type:V(t.element)}):t instanceof L?L.create(V(t.unwrap())):t instanceof G?G.create(V(t.unwrap())):t instanceof z?z.create(t.items.map(e=>V(e))):t}class w extends y{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),n=v.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==f.object){const l=this._getOrReturnCtx(e);return u(l,{code:d.invalid_type,expected:f.object,received:l.parsedType}),m}const{status:s,ctx:r}=this._processInputParams(e),{shape:i,keys:a}=this._getCached(),o=[];if(!(this._def.catchall instanceof $&&this._def.unknownKeys==="strip"))for(const l in r.data)a.includes(l)||o.push(l);const c=[];for(const l of a){const g=i[l],x=r.data[l];c.push({key:{status:"valid",value:l},value:g._parse(new I(r,x,r.path,l)),alwaysSet:l in r.data})}if(this._def.catchall instanceof $){const l=this._def.unknownKeys;if(l==="passthrough")for(const g of o)c.push({key:{status:"valid",value:g},value:{status:"valid",value:r.data[g]}});else if(l==="strict")o.length>0&&(u(r,{code:d.unrecognized_keys,keys:o}),s.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const l=this._def.catchall;for(const g of o){const x=r.data[g];c.push({key:{status:"valid",value:g},value:l._parse(new I(r,x,r.path,g)),alwaysSet:g in r.data})}}return r.common.async?Promise.resolve().then(async()=>{const l=[];for(const g of c){const x=await g.key,E=await g.value;l.push({key:x,value:E,alwaysSet:g.alwaysSet})}return l}).then(l=>T.mergeObjectSync(s,l)):T.mergeObjectSync(s,c)}get shape(){return this._def.shape()}strict(e){return p.errToObj,new w({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,s)=>{const r=this._def.errorMap?.(n,s).message??s.defaultError;return n.code==="unrecognized_keys"?{message:p.errToObj(e).message??r}:{message:r}}}:{}})}strip(){return new w({...this._def,unknownKeys:"strip"})}passthrough(){return new w({...this._def,unknownKeys:"passthrough"})}extend(e){return new w({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new w({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:h.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new w({...this._def,catchall:e})}pick(e){const n={};for(const s of v.objectKeys(e))e[s]&&this.shape[s]&&(n[s]=this.shape[s]);return new w({...this._def,shape:()=>n})}omit(e){const n={};for(const s of v.objectKeys(this.shape))e[s]||(n[s]=this.shape[s]);return new w({...this._def,shape:()=>n})}deepPartial(){return V(this)}partial(e){const n={};for(const s of v.objectKeys(this.shape)){const r=this.shape[s];e&&!e[s]?n[s]=r:n[s]=r.optional()}return new w({...this._def,shape:()=>n})}required(e){const n={};for(const s of v.objectKeys(this.shape))if(e&&!e[s])n[s]=this.shape[s];else{let i=this.shape[s];for(;i instanceof L;)i=i._def.innerType;n[s]=i}return new w({...this._def,shape:()=>n})}keyof(){return nt(v.objectKeys(this.shape))}}w.create=(t,e)=>new w({shape:()=>t,unknownKeys:"strip",catchall:$.create(),typeName:h.ZodObject,..._(e)});w.strictCreate=(t,e)=>new w({shape:()=>t,unknownKeys:"strict",catchall:$.create(),typeName:h.ZodObject,..._(e)});w.lazycreate=(t,e)=>new w({shape:t,unknownKeys:"strip",catchall:$.create(),typeName:h.ZodObject,..._(e)});class te extends y{_parse(e){const{ctx:n}=this._processInputParams(e),s=this._def.options;function r(i){for(const o of i)if(o.result.status==="valid")return o.result;for(const o of i)if(o.result.status==="dirty")return n.common.issues.push(...o.ctx.common.issues),o.result;const a=i.map(o=>new R(o.ctx.common.issues));return u(n,{code:d.invalid_union,unionErrors:a}),m}if(n.common.async)return Promise.all(s.map(async i=>{const a={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:a}),ctx:a}})).then(r);{let i;const a=[];for(const c of s){const l={...n,common:{...n.common,issues:[]},parent:null},g=c._parseSync({data:n.data,path:n.path,parent:l});if(g.status==="valid")return g;g.status==="dirty"&&!i&&(i={result:g,ctx:l}),l.common.issues.length&&a.push(l.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;const o=a.map(c=>new R(c));return u(n,{code:d.invalid_union,unionErrors:o}),m}}get options(){return this._def.options}}te.create=(t,e)=>new te({options:t,typeName:h.ZodUnion,..._(e)});function pe(t,e){const n=P(t),s=P(e);if(t===e)return{valid:!0,data:t};if(n===f.object&&s===f.object){const r=v.objectKeys(e),i=v.objectKeys(t).filter(o=>r.indexOf(o)!==-1),a={...t,...e};for(const o of i){const c=pe(t[o],e[o]);if(!c.valid)return{valid:!1};a[o]=c.data}return{valid:!0,data:a}}else if(n===f.array&&s===f.array){if(t.length!==e.length)return{valid:!1};const r=[];for(let i=0;i<t.length;i++){const a=t[i],o=e[i],c=pe(a,o);if(!c.valid)return{valid:!1};r.push(c.data)}return{valid:!0,data:r}}else return n===f.date&&s===f.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}class ne extends y{_parse(e){const{status:n,ctx:s}=this._processInputParams(e),r=(i,a)=>{if(Ce(i)||Ce(a))return m;const o=pe(i.value,a.value);return o.valid?((Se(i)||Se(a))&&n.dirty(),{status:n.value,value:o.data}):(u(s,{code:d.invalid_intersection_types}),m)};return s.common.async?Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then(([i,a])=>r(i,a)):r(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}}ne.create=(t,e,n)=>new ne({left:t,right:e,typeName:h.ZodIntersection,..._(n)});class z extends y{_parse(e){const{status:n,ctx:s}=this._processInputParams(e);if(s.parsedType!==f.array)return u(s,{code:d.invalid_type,expected:f.array,received:s.parsedType}),m;if(s.data.length<this._def.items.length)return u(s,{code:d.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),m;!this._def.rest&&s.data.length>this._def.items.length&&(u(s,{code:d.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const i=[...s.data].map((a,o)=>{const c=this._def.items[o]||this._def.rest;return c?c._parse(new I(s,a,s.path,o)):null}).filter(a=>!!a);return s.common.async?Promise.all(i).then(a=>T.mergeArray(n,a)):T.mergeArray(n,i)}get items(){return this._def.items}rest(e){return new z({...this._def,rest:e})}}z.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new z({items:t,typeName:h.ZodTuple,rest:null,..._(e)})};class se extends y{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:n,ctx:s}=this._processInputParams(e);if(s.parsedType!==f.object)return u(s,{code:d.invalid_type,expected:f.object,received:s.parsedType}),m;const r=[],i=this._def.keyType,a=this._def.valueType;for(const o in s.data)r.push({key:i._parse(new I(s,o,s.path,o)),value:a._parse(new I(s,s.data[o],s.path,o)),alwaysSet:o in s.data});return s.common.async?T.mergeObjectAsync(n,r):T.mergeObjectSync(n,r)}get element(){return this._def.valueType}static create(e,n,s){return n instanceof y?new se({keyType:e,valueType:n,typeName:h.ZodRecord,..._(s)}):new se({keyType:N.create(),valueType:e,typeName:h.ZodRecord,..._(n)})}}class Ze extends y{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:n,ctx:s}=this._processInputParams(e);if(s.parsedType!==f.map)return u(s,{code:d.invalid_type,expected:f.map,received:s.parsedType}),m;const r=this._def.keyType,i=this._def.valueType,a=[...s.data.entries()].map(([o,c],l)=>({key:r._parse(new I(s,o,s.path,[l,"key"])),value:i._parse(new I(s,c,s.path,[l,"value"]))}));if(s.common.async){const o=new Map;return Promise.resolve().then(async()=>{for(const c of a){const l=await c.key,g=await c.value;if(l.status==="aborted"||g.status==="aborted")return m;(l.status==="dirty"||g.status==="dirty")&&n.dirty(),o.set(l.value,g.value)}return{status:n.value,value:o}})}else{const o=new Map;for(const c of a){const l=c.key,g=c.value;if(l.status==="aborted"||g.status==="aborted")return m;(l.status==="dirty"||g.status==="dirty")&&n.dirty(),o.set(l.value,g.value)}return{status:n.value,value:o}}}}Ze.create=(t,e,n)=>new Ze({valueType:e,keyType:t,typeName:h.ZodMap,..._(n)});class K extends y{_parse(e){const{status:n,ctx:s}=this._processInputParams(e);if(s.parsedType!==f.set)return u(s,{code:d.invalid_type,expected:f.set,received:s.parsedType}),m;const r=this._def;r.minSize!==null&&s.data.size<r.minSize.value&&(u(s,{code:d.too_small,minimum:r.minSize.value,type:"set",inclusive:!0,exact:!1,message:r.minSize.message}),n.dirty()),r.maxSize!==null&&s.data.size>r.maxSize.value&&(u(s,{code:d.too_big,maximum:r.maxSize.value,type:"set",inclusive:!0,exact:!1,message:r.maxSize.message}),n.dirty());const i=this._def.valueType;function a(c){const l=new Set;for(const g of c){if(g.status==="aborted")return m;g.status==="dirty"&&n.dirty(),l.add(g.value)}return{status:n.value,value:l}}const o=[...s.data.values()].map((c,l)=>i._parse(new I(s,c,s.path,l)));return s.common.async?Promise.all(o).then(c=>a(c)):a(o)}min(e,n){return new K({...this._def,minSize:{value:e,message:p.toString(n)}})}max(e,n){return new K({...this._def,maxSize:{value:e,message:p.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}}K.create=(t,e)=>new K({valueType:t,minSize:null,maxSize:null,typeName:h.ZodSet,..._(e)});class Pe extends y{get schema(){return this._def.getter()}_parse(e){const{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}Pe.create=(t,e)=>new Pe({getter:t,typeName:h.ZodLazy,..._(e)});class he extends y{_parse(e){if(e.data!==this._def.value){const n=this._getOrReturnCtx(e);return u(n,{received:n.data,code:d.invalid_literal,expected:this._def.value}),m}return{status:"valid",value:e.data}}get value(){return this._def.value}}he.create=(t,e)=>new he({value:t,typeName:h.ZodLiteral,..._(e)});function nt(t,e){return new H({values:t,typeName:h.ZodEnum,..._(e)})}class H extends y{_parse(e){if(typeof e.data!="string"){const n=this._getOrReturnCtx(e),s=this._def.values;return u(n,{expected:v.joinValues(s),received:n.parsedType,code:d.invalid_type}),m}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const n=this._getOrReturnCtx(e),s=this._def.values;return u(n,{received:n.data,code:d.invalid_enum_value,options:s}),m}return S(e.data)}get options(){return this._def.values}get enum(){const e={};for(const n of this._def.values)e[n]=n;return e}get Values(){const e={};for(const n of this._def.values)e[n]=n;return e}get Enum(){const e={};for(const n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return H.create(e,{...this._def,...n})}exclude(e,n=this._def){return H.create(this.options.filter(s=>!e.includes(s)),{...this._def,...n})}}H.create=nt;class je extends y{_parse(e){const n=v.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==f.string&&s.parsedType!==f.number){const r=v.objectValues(n);return u(s,{expected:v.joinValues(r),received:s.parsedType,code:d.invalid_type}),m}if(this._cache||(this._cache=new Set(v.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const r=v.objectValues(n);return u(s,{received:s.data,code:d.invalid_enum_value,options:r}),m}return S(e.data)}get enum(){return this._def.values}}je.create=(t,e)=>new je({values:t,typeName:h.ZodNativeEnum,..._(e)});class re extends y{unwrap(){return this._def.type}_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==f.promise&&n.common.async===!1)return u(n,{code:d.invalid_type,expected:f.promise,received:n.parsedType}),m;const s=n.parsedType===f.promise?n.data:Promise.resolve(n.data);return S(s.then(r=>this._def.type.parseAsync(r,{path:n.path,errorMap:n.common.contextualErrorMap})))}}re.create=(t,e)=>new re({type:t,typeName:h.ZodPromise,..._(e)});class F extends y{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===h.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:n,ctx:s}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:a=>{u(s,a),a.fatal?n.abort():n.dirty()},get path(){return s.path}};if(i.addIssue=i.addIssue.bind(i),r.type==="preprocess"){const a=r.transform(s.data,i);if(s.common.async)return Promise.resolve(a).then(async o=>{if(n.value==="aborted")return m;const c=await this._def.schema._parseAsync({data:o,path:s.path,parent:s});return c.status==="aborted"?m:c.status==="dirty"||n.value==="dirty"?J(c.value):c});{if(n.value==="aborted")return m;const o=this._def.schema._parseSync({data:a,path:s.path,parent:s});return o.status==="aborted"?m:o.status==="dirty"||n.value==="dirty"?J(o.value):o}}if(r.type==="refinement"){const a=o=>{const c=r.refinement(o,i);if(s.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(s.common.async===!1){const o=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return o.status==="aborted"?m:(o.status==="dirty"&&n.dirty(),a(o.value),{status:n.value,value:o.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(o=>o.status==="aborted"?m:(o.status==="dirty"&&n.dirty(),a(o.value).then(()=>({status:n.value,value:o.value}))))}if(r.type==="transform")if(s.common.async===!1){const a=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!B(a))return m;const o=r.transform(a.value,i);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:o}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(a=>B(a)?Promise.resolve(r.transform(a.value,i)).then(o=>({status:n.value,value:o})):m);v.assertNever(r)}}F.create=(t,e,n)=>new F({schema:t,typeName:h.ZodEffects,effect:e,..._(n)});F.createWithPreprocess=(t,e,n)=>new F({schema:e,effect:{type:"preprocess",transform:t},typeName:h.ZodEffects,..._(n)});class L extends y{_parse(e){return this._getType(e)===f.undefined?S(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}L.create=(t,e)=>new L({innerType:t,typeName:h.ZodOptional,..._(e)});class G extends y{_parse(e){return this._getType(e)===f.null?S(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}G.create=(t,e)=>new G({innerType:t,typeName:h.ZodNullable,..._(e)});class me extends y{_parse(e){const{ctx:n}=this._processInputParams(e);let s=n.data;return n.parsedType===f.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}me.create=(t,e)=>new me({innerType:t,typeName:h.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,..._(e)});class ge extends y{_parse(e){const{ctx:n}=this._processInputParams(e),s={...n,common:{...n.common,issues:[]}},r=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return X(r)?r.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new R(s.common.issues)},input:s.data})})):{status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new R(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}}ge.create=(t,e)=>new ge({innerType:t,typeName:h.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,..._(e)});class Le extends y{_parse(e){if(this._getType(e)!==f.nan){const s=this._getOrReturnCtx(e);return u(s,{code:d.invalid_type,expected:f.nan,received:s.parsedType}),m}return{status:"valid",value:e.data}}}Le.create=t=>new Le({typeName:h.ZodNaN,..._(t)});class Wn extends y{_parse(e){const{ctx:n}=this._processInputParams(e),s=n.data;return this._def.type._parse({data:s,path:n.path,parent:n})}unwrap(){return this._def.type}}class ke extends y{_parse(e){const{status:n,ctx:s}=this._processInputParams(e);if(s.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return i.status==="aborted"?m:i.status==="dirty"?(n.dirty(),J(i.value)):this._def.out._parseAsync({data:i.value,path:s.path,parent:s})})();{const r=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return r.status==="aborted"?m:r.status==="dirty"?(n.dirty(),{status:"dirty",value:r.value}):this._def.out._parseSync({data:r.value,path:s.path,parent:s})}}static create(e,n){return new ke({in:e,out:n,typeName:h.ZodPipeline})}}class _e extends y{_parse(e){const n=this._def.innerType._parse(e),s=r=>(B(r)&&(r.value=Object.freeze(r.value)),r);return X(n)?n.then(r=>s(r)):s(n)}unwrap(){return this._def.innerType}}_e.create=(t,e)=>new _e({innerType:t,typeName:h.ZodReadonly,..._(e)});var h;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(h||(h={}));const Hn=N.create,Fn=W.create,Gn=le.create,Qn=fe.create;$.create;const Jn=A.create,Yn=w.create,Kn=te.create;ne.create;z.create;const Xn=se.create,es=he.create,ts=H.create;re.create;L.create;G.create;exports.BaseWidget=It;exports.DEFAULT_WIDGET_THEME_TOKENS=ce;exports.adaptV1Event=Pt;exports.arrayType=Jn;exports.basketAddEvent=mt;exports.booleanType=Gn;exports.bootstrapSession=ze;exports.buildChatEndpointUrl=vn;exports.chatHistorySnapshotEvent=pt;exports.checkoutCompleteEvent=Ue;exports.checkoutStartEvent=Me;exports.consumeStream=Fe;exports.defaultUnknownUISpecRenderer=$e;exports.dismissGlobalErrorToast=He;exports.dispatch=gt;exports.enumType=ts;exports.getGlobalErrorMessage=Tt;exports.getWindowPageContext=vt;exports.listen=q;exports.literalType=es;exports.llmUsageEvent=lt;exports.mergeUISpecRegistry=it;exports.meteringIncrementEvent=ft;exports.meteringSummaryEvent=De;exports.normalizeMiddlewareUrl=Xe;exports.normalizeProductGroupingsResponse=_n;exports.normalizeSimilarProductsResponse=gn;exports.numberType=Fn;exports.objectType=Yn;exports.productToNormalized=O;exports.recordType=Xn;exports.registerGlobalErrorToastListener=Be;exports.renderUISpecWithRegistry=rt;exports.resolveSession=Ve;exports.showGlobalErrorToast=We;exports.streamChunkEvent=ot;exports.streamDoneEvent=ct;exports.streamErrorEvent=ut;exports.streamPost=Ot;exports.streamStartEvent=at;exports.streamUiSpecEvent=dt;exports.stringType=Hn;exports.unionType=Kn;exports.unknownType=Qn;exports.updatePageContext=kt;exports.widgetHistorySnapshotEvent=ht;exports.wireQNAToChat=_t;exports.wireSimilarToChat=yt;exports.withDefaultWidgetTheme=qe;
48
+ //# sourceMappingURL=types-CeON7iBO.cjs.map