decocms 2.285.1 → 2.286.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client/assets/{AlertCircle-Ljx3VIeb.js → AlertCircle-Bgzr6uRA.js} +1 -1
- package/dist/client/assets/{ArrowNarrowLeft-B8YVT66M.js → ArrowNarrowLeft-ByrdB8Dd.js} +1 -1
- package/dist/client/assets/{CheckCircle-BFRWTTWo.js → CheckCircle-88bls7UK.js} +1 -1
- package/dist/client/assets/{ChevronDown-BqFspEzt.js → ChevronDown-Jd-cYHC-.js} +1 -1
- package/dist/client/assets/{ChevronRight-DCsBjQ-n.js → ChevronRight-71i8ke8L.js} +1 -1
- package/dist/client/assets/{ChevronUp-D7S3j_fa.js → ChevronUp-D_szSdLd.js} +1 -1
- package/dist/client/assets/{Container-SHbLkl7K.js → Container-DWaKXfYv.js} +1 -1
- package/dist/client/assets/DotsVertical-CjXyjLNU.js +1 -0
- package/dist/client/assets/{LinkExternal01-XmkIm96u.js → LinkExternal01-DB08YntP.js} +1 -1
- package/dist/client/assets/{Lock01-CXrm99F-.js → Lock01-dBhVogWg.js} +1 -1
- package/dist/client/assets/{Palette-B46VjX8F.js → Palette-DuWQiO51.js} +1 -1
- package/dist/client/assets/{Play-9pX5w5-3.js → Play-D7pqvkYq.js} +1 -1
- package/dist/client/assets/{Plus-Bmk1thjl.js → Plus-BzxOIhxj.js} +1 -1
- package/dist/client/assets/RefreshCcw01-BxULs6ec.js +1 -0
- package/dist/client/assets/SearchMd-D6tCV38D.js +1 -0
- package/dist/client/assets/{Settings02-C88OtRRq.js → Settings02-MyfUtBA4.js} +1 -1
- package/dist/client/assets/Shield01-CMw4M4Ml.js +1 -0
- package/dist/client/assets/{Star01-fuGmPeeu.js → Star01-DZHrISf9.js} +1 -1
- package/dist/client/assets/{Sun-ndN_CHuQ.js → Sun-C8X8gjZW.js} +1 -1
- package/dist/client/assets/{Tool01-DBxgF1Y_.js → Tool01-BscqkhhO.js} +1 -1
- package/dist/client/assets/{Trash01-BHBjIGXE.js → Trash01-DZpzvWVW.js} +1 -1
- package/dist/client/assets/{User01-DCiwOMBU.js → User01-VHn0SqBP.js} +1 -1
- package/dist/client/assets/{Users03-Bgfd1KM0.js → Users03-DwNyb_q2.js} +1 -1
- package/dist/client/assets/{X-BWV-b86T.js → X-BuUY-erD.js} +1 -1
- package/dist/client/assets/XCircle-BFZeumzD.js +1 -0
- package/dist/client/assets/XClose-ANREDbeo.js +1 -0
- package/dist/client/assets/{Zap-K9sQXDlC.js → Zap-BxJkZzJb.js} +1 -1
- package/dist/client/assets/{ZapSquare-CTcr_tRy.js → ZapSquare-Bz3HDhTc.js} +1 -1
- package/dist/client/assets/{accordion-COmeMo5z.js → accordion-DK_chPAh.js} +1 -1
- package/dist/client/assets/agent-icon-DKQKq---.js +1 -0
- package/dist/client/assets/agents-list-DBdCJGrz.js +1 -0
- package/dist/client/assets/ai-providers-BhNFwI7O.js +1 -0
- package/dist/client/assets/{alert-dialog-DaP8t8su.js → alert-dialog-CtGXaT-Y.js} +2 -2
- package/dist/client/assets/{auth-catchall-CerK6T4u.js → auth-catchall-B4ADnlpm.js} +1 -1
- package/dist/client/assets/automation-list-row-B_yW9vLo.js +1 -0
- package/dist/client/assets/automations-B3iEjSty.js +1 -0
- package/dist/client/assets/{avatar-gTIcZioB.js → avatar-DcLXZkYK.js} +1 -1
- package/dist/client/assets/{badge-DsWPcX1V.js → badge-BJBM0LXp.js} +1 -1
- package/dist/client/assets/brand-context-BahSISOs.js +1 -0
- package/dist/client/assets/{card-CPVRwbgl.js → card-DqrPrhd5.js} +1 -1
- package/dist/client/assets/{chat-context-CZAEwDWp.js → chat-context-DfEaB6Uj.js} +1 -1
- package/dist/client/assets/{checkbox-CPqdqI54.js → checkbox-Dplb_VaM.js} +1 -1
- package/dist/client/assets/collection-detail-KgUZfuij.js +1 -0
- package/dist/client/assets/collection-display-button-DecHBxzk.js +1 -0
- package/dist/client/assets/{collection-search-DgokupF2.js → collection-search-B_zW9IS4.js} +1 -1
- package/dist/client/assets/{collection-search-lfil19IA.js → collection-search-DF-hPm66.js} +1 -1
- package/dist/client/assets/collection-table-wrapper-DG-B8ykv.js +1 -0
- package/dist/client/assets/{collection-tabs-BRY4wHvH.js → collection-tabs-tHg8euhu.js} +1 -1
- package/dist/client/assets/{collections-lJhN2k9k.js → collections-KKlyNHih.js} +1 -1
- package/dist/client/assets/command-Cpu7RbMv.js +1 -0
- package/dist/client/assets/{connection-card-BrctpSfE.js → connection-card-CD0fnfut.js} +1 -1
- package/dist/client/assets/connection-detail-CFY9ol5g.js +1 -0
- package/dist/client/assets/{connection-form-helpers-C1FnnBdL.js → connection-form-helpers-DVewXDLo.js} +1 -1
- package/dist/client/assets/connections-B-Liq5Ll.js +1 -0
- package/dist/client/assets/{constants-D_Nupw5-.js → constants-D7DNenhk.js} +1 -1
- package/dist/client/assets/{constants-D8VkIs2c.js → constants-aD7HJ6sY.js} +1 -1
- package/dist/client/assets/{dialog-BOagZAx2.js → dialog-nGTWjCEa.js} +1 -1
- package/dist/client/assets/{drawer-BRUzFEdi.js → drawer-DyPUsgdj.js} +1 -1
- package/dist/client/assets/dropdown-menu-Cc_jn9Z7.js +1 -0
- package/dist/client/assets/{dynamic-plugin-layout-ltkevohS.js → dynamic-plugin-layout-Bun8S8Gm.js} +1 -1
- package/dist/client/assets/{empty-state-DCK4Z2GX.js → empty-state-CqQa90x5.js} +1 -1
- package/dist/client/assets/{empty-state-BokLRSGE.js → empty-state-DgThOXBB.js} +1 -1
- package/dist/client/assets/{extract-connection-data-V-eInhlP.js → extract-connection-data-Bx0uarS8.js} +1 -1
- package/dist/client/assets/{features-DIBFVG_b.js → features-ekquKatz.js} +1 -1
- package/dist/client/assets/{form-DHQjt1Tk.js → form-DB-TdsHz.js} +1 -1
- package/dist/client/assets/general-BrK_oI6y.js +1 -0
- package/dist/client/assets/{github-repo-picker-CIYxcUMn.js → github-repo-picker-CwCtQ7G3.js} +2 -2
- package/dist/client/assets/{index-DbNFtLRR.js → index-Amg25tew.js} +3 -3
- package/dist/client/assets/index-BCwsJqWc.css +1 -0
- package/dist/client/assets/{index-DvxSs9Po.js → index-BZopUfMN.js} +1 -1
- package/dist/client/assets/{index-gfedyrlZ.js → index-BfYZ2YG_.js} +16 -16
- package/dist/client/assets/{index-uSGXbgq4.js → index-CT9V-xpg.js} +1 -1
- package/dist/client/assets/{index-sYNl3b-7.js → index-CwstDhH7.js} +1 -1
- package/dist/client/assets/{index-CNolBSVE.js → index-DhJrYN5i.js} +22 -22
- package/dist/client/assets/{index-DWOvEgKr.js → index-DtMbbDUN.js} +1 -1
- package/dist/client/assets/{index-BWvVdWtP.js → index-DtdOoKdU.js} +1 -1
- package/dist/client/assets/{index-PT6VRyBL.js → index-DvgxnJsz.js} +1 -1
- package/dist/client/assets/{index-Di0ylaLI.js → index-pD6VF9-w.js} +3 -3
- package/dist/client/assets/{infiniteQueryObserver-B8q-YDXm.js → infiniteQueryObserver-B_9sKQsI.js} +1 -1
- package/dist/client/assets/{input-B8j75XZ_.js → input-COFLoOjb.js} +1 -1
- package/dist/client/assets/{integration-icon-De50Mm7k.js → integration-icon-DKrcAAs9.js} +1 -1
- package/dist/client/assets/{label-KH35YAYU.js → label-BZVcstmy.js} +1 -1
- package/dist/client/assets/{layout-E2py7rYQ.js → layout-Dp5y9gtR.js} +1 -1
- package/dist/client/assets/{login-agOBj-o2.js → login-ComGApTe.js} +1 -1
- package/dist/client/assets/members-CHnKVrrd.js +3 -0
- package/dist/client/assets/{monaco-editor-CzAT2DWn.js → monaco-editor-EL8K9shU.js} +1 -1
- package/dist/client/assets/{monitoring-stats-row-k0blCMgl.js → monitoring-stats-row-D9crys0K.js} +1 -1
- package/dist/client/assets/{oauth-callback-ViEW-3g2.js → oauth-callback-B0mEhNIK.js} +1 -1
- package/dist/client/assets/{oauth-callback-ai-provider-cSZy9hW7.js → oauth-callback-ai-provider-Dj0EctfO.js} +1 -1
- package/dist/client/assets/{onboarding-CquRdW5q.js → onboarding-czNV0UuI.js} +1 -1
- package/dist/client/assets/{org-layout-DY9vqUg9.js → org-layout-CGtnLM_Q.js} +1 -1
- package/dist/client/assets/{org-plugin-layout-HyePbhDN.js → org-plugin-layout-Ba2ZEzcE.js} +1 -1
- package/dist/client/assets/{plugin-empty-state-tSKwN8yW.js → plugin-empty-state-fmAUJ6xt.js} +1 -1
- package/dist/client/assets/{plugin-header-CgMEgROC.js → plugin-header-3c9kItnR.js} +1 -1
- package/dist/client/assets/{plugin-layout-B0f9qTk_.js → plugin-layout-CUFHRJeM.js} +1 -1
- package/dist/client/assets/{popover-BK6PL-XB.js → popover-Bo1-wNsY.js} +1 -1
- package/dist/client/assets/{profile-C_xBhvj7.js → profile-C4ZfFzUo.js} +1 -1
- package/dist/client/assets/project-app-view-DbITEuQv.js +1 -0
- package/dist/client/assets/registry-CrUw5Sj_.js +2 -0
- package/dist/client/assets/{registry-layout-7nSgT8Ua.js → registry-layout-q6bMBk9s.js} +3 -3
- package/dist/client/assets/{required-auth-layout-D-NWWr5P.js → required-auth-layout-CP-yDaO3.js} +1 -1
- package/dist/client/assets/{reset-password-C7m0cAdE.js → reset-password-CpFcPkI4.js} +1 -1
- package/dist/client/assets/roles-CSJcHSQ8.js +1 -0
- package/dist/client/assets/{scroll-area-Da2hNrch.js → scroll-area-CXUp8wR9.js} +1 -1
- package/dist/client/assets/{search-input-BZmdDW7A.js → search-input-ClG6niuo.js} +1 -1
- package/dist/client/assets/{select-JPYD20it.js → select-Cn3ZnqjJ.js} +1 -1
- package/dist/client/assets/{select-model-DMVU-2Gx.js → select-model-BwE-9vfJ.js} +2 -2
- package/dist/client/assets/settings-layout-dHGH4vpw.js +1 -0
- package/dist/client/assets/{shell-layout-DkN8Q_tp.js → shell-layout-BsqL_vND.js} +1 -1
- package/dist/client/assets/{skeleton-DPqifXUx.js → skeleton-DOcx8lZU.js} +1 -1
- package/dist/client/assets/{sso-BdiVJFM8.js → sso-37Vu3qt9.js} +1 -1
- package/dist/client/assets/{store-D9lb1Gph.js → store-D1kidhJ8.js} +1 -1
- package/dist/client/assets/store-registry-qx_8ffch.js +2 -0
- package/dist/client/assets/{switch-CVtXvreH.js → switch-ihM2hYRH.js} +1 -1
- package/dist/client/assets/{table-C-JSrHQJ.js → table-CAUXYO7-.js} +1 -1
- package/dist/client/assets/{tabs-DtgWLQ6i.js → tabs-DcOxSeRf.js} +1 -1
- package/dist/client/assets/{task-status-DTuLfGhm.js → task-status-CHfFeACA.js} +7 -7
- package/dist/client/assets/{textarea-p_oNKH-r.js → textarea-CsnX9Ktr.js} +1 -1
- package/dist/client/assets/{toggle-group-B6-etMEh.js → toggle-group-_HWF3GFc.js} +1 -1
- package/dist/client/assets/tools-list-A0gJUqTb.js +1 -0
- package/dist/client/assets/{types-BP7V6N8z.js → types-BGXCye_w.js} +1 -1
- package/dist/client/assets/{use-ai-providers-oN1cKhaJ.js → use-ai-providers-DSLKay0D.js} +1 -1
- package/dist/client/assets/{use-collections-BTXUmiDi.js → use-collections-DvPoAlor.js} +1 -1
- package/dist/client/assets/{use-connection-DIvNoxL5.js → use-connection-MU3rXx28.js} +1 -1
- package/dist/client/assets/{use-copy-D8L6lrfC.js → use-copy-tC0v6ypy.js} +1 -1
- package/dist/client/assets/{use-create-virtual-mcp-DUKkySGS.js → use-create-virtual-mcp-C-LLRhrB.js} +1 -1
- package/dist/client/assets/{use-decopilot-events-BRc3SX00.js → use-decopilot-events-fHBaJaln.js} +1 -1
- package/dist/client/assets/{use-delete-connection-IDpzSpRp.js → use-delete-connection-CowwQ4CA.js} +1 -1
- package/dist/client/assets/{use-infinite-scroll-WKRKMI2J.js → use-infinite-scroll-BUM8dH47.js} +1 -1
- package/dist/client/assets/{use-list-state-Dyh2zhb9.js → use-list-state-Ba4O0IuX.js} +1 -1
- package/dist/client/assets/{use-mcp-tools-tZ37UBLL.js → use-mcp-tools-B5zpuics.js} +1 -1
- package/dist/client/assets/{use-members-AvAHjkiq.js → use-members-Bhu2ZnQb.js} +1 -1
- package/dist/client/assets/{use-mobile-Ctb5URy7.js → use-mobile-C4Yo3nsX.js} +1 -1
- package/dist/client/assets/{use-navigate-to-agent-CLfSU3ru.js → use-navigate-to-agent-Bx0DB5DW.js} +1 -1
- package/dist/client/assets/{use-org-sso-CmuM4ieo.js → use-org-sso-BK-ft_ER.js} +1 -1
- package/dist/client/assets/use-organization-roles-uEcrMWhG.js +1 -0
- package/dist/client/assets/{use-organization-settings-dQpmtQzl.js → use-organization-settings-CMC2yyUM.js} +1 -1
- package/dist/client/assets/{use-registry-connections-CP0QI7iA.js → use-registry-connections-Biq_9qgb.js} +1 -1
- package/dist/client/assets/{use-status-sounds-CObwI0DY.js → use-status-sounds-DfhTS64d.js} +1 -1
- package/dist/client/assets/{use-tasks-7rX1bsHL.js → use-tasks-DofxyZR4.js} +1 -1
- package/dist/client/assets/{use-view-mode-BkbloGkm.js → use-view-mode-DSeYcON6.js} +1 -1
- package/dist/client/assets/{use-virtual-mcp-CDOk_IIy.js → use-virtual-mcp-WT1ZdgMM.js} +1 -1
- package/dist/client/assets/useInfiniteQuery-Gkc0b2zi.js +1 -0
- package/dist/client/assets/useSuspenseInfiniteQuery-YePUpUV3.js +1 -0
- package/dist/client/assets/{user-lj8QRtGG.js → user-5oBDTi_W.js} +1 -1
- package/dist/client/assets/{view-mode-toggle-BiPtlB_S.js → view-mode-toggle-BvyYLass.js} +1 -1
- package/dist/client/assets/workflow-DoVF6xyx.js +1 -0
- package/dist/client/assets/workflow-detail-XUi-wHY3.js +1 -0
- package/dist/client/index.html +2 -2
- package/dist/server/cli.js +2 -2
- package/dist/server/node_modules/figures/index.d.ts +279 -0
- package/dist/server/node_modules/figures/index.js +292 -0
- package/dist/server/node_modules/{is-fullwidth-code-point → figures}/package.json +16 -20
- package/dist/server/node_modules/figures/readme.md +337 -0
- package/dist/server/node_modules/get-east-asian-width/index.d.ts +60 -0
- package/dist/server/node_modules/get-east-asian-width/index.js +30 -0
- package/dist/server/node_modules/get-east-asian-width/lookup-data.js +18 -0
- package/dist/server/node_modules/get-east-asian-width/lookup.js +135 -0
- package/dist/server/node_modules/get-east-asian-width/package.json +71 -0
- package/dist/server/node_modules/get-east-asian-width/readme.md +65 -0
- package/dist/server/node_modules/get-east-asian-width/utilities.js +24 -0
- package/dist/server/node_modules/ink/build/ansi-tokenizer.d.ts +38 -0
- package/dist/server/node_modules/ink/build/ansi-tokenizer.js +316 -0
- package/dist/server/node_modules/ink/build/ansi-tokenizer.js.map +1 -0
- package/dist/server/node_modules/ink/build/apply-styles.js +175 -0
- package/dist/server/node_modules/ink/build/build-layout.js +77 -0
- package/dist/server/node_modules/ink/build/calculate-wrapped-text.js +53 -0
- package/dist/server/node_modules/ink/build/colorize.d.ts +3 -0
- package/dist/server/node_modules/ink/build/colorize.js +48 -0
- package/dist/server/node_modules/ink/build/colorize.js.map +1 -0
- package/dist/server/node_modules/ink/build/components/AccessibilityContext.d.ts +3 -0
- package/dist/server/node_modules/ink/build/components/AccessibilityContext.js +5 -0
- package/dist/server/node_modules/ink/build/components/AccessibilityContext.js.map +1 -0
- package/dist/server/node_modules/ink/build/components/App.d.ts +18 -0
- package/dist/server/node_modules/ink/build/components/App.js +351 -0
- package/dist/server/node_modules/ink/build/components/App.js.map +1 -0
- package/dist/server/node_modules/ink/build/components/AppContext.d.ts +15 -0
- package/dist/server/node_modules/ink/build/components/AppContext.js +11 -0
- package/dist/server/node_modules/ink/build/components/AppContext.js.map +1 -0
- package/dist/server/node_modules/ink/build/components/BackgroundContext.d.ts +4 -0
- package/dist/server/node_modules/ink/build/components/BackgroundContext.js +3 -0
- package/dist/server/node_modules/ink/build/components/BackgroundContext.js.map +1 -0
- package/dist/server/node_modules/ink/build/components/Box.d.ts +117 -0
- package/dist/server/node_modules/ink/build/components/Box.js +34 -0
- package/dist/server/node_modules/ink/build/components/Box.js.map +1 -0
- package/dist/server/node_modules/ink/build/components/Color.js +62 -0
- package/dist/server/node_modules/ink/build/components/Cursor.d.ts +83 -0
- package/dist/server/node_modules/ink/build/components/Cursor.js +53 -0
- package/dist/server/node_modules/ink/build/components/Cursor.js.map +1 -0
- package/dist/server/node_modules/ink/build/components/CursorContext.d.ts +11 -0
- package/dist/server/node_modules/ink/build/components/CursorContext.js +8 -0
- package/dist/server/node_modules/ink/build/components/CursorContext.js.map +1 -0
- package/dist/server/node_modules/ink/build/components/ErrorBoundary.d.ts +18 -0
- package/dist/server/node_modules/ink/build/components/ErrorBoundary.js +23 -0
- package/dist/server/node_modules/ink/build/components/ErrorBoundary.js.map +1 -0
- package/dist/server/node_modules/ink/build/components/ErrorOverview.d.ts +6 -0
- package/dist/server/node_modules/ink/build/components/ErrorOverview.js +84 -0
- package/dist/server/node_modules/ink/build/components/ErrorOverview.js.map +1 -0
- package/dist/server/node_modules/ink/build/components/FocusContext.d.ts +16 -0
- package/dist/server/node_modules/ink/build/components/FocusContext.js +17 -0
- package/dist/server/node_modules/ink/build/components/FocusContext.js.map +1 -0
- package/dist/server/node_modules/ink/build/components/Newline.d.ts +13 -0
- package/dist/server/node_modules/ink/build/components/Newline.js +8 -0
- package/dist/server/node_modules/ink/build/components/Newline.js.map +1 -0
- package/dist/server/node_modules/ink/build/components/Spacer.d.ts +7 -0
- package/dist/server/node_modules/ink/build/components/Spacer.js +11 -0
- package/dist/server/node_modules/ink/build/components/Spacer.js.map +1 -0
- package/dist/server/node_modules/ink/build/components/Static.d.ts +24 -0
- package/dist/server/node_modules/ink/build/components/Static.js +28 -0
- package/dist/server/node_modules/ink/build/components/Static.js.map +1 -0
- package/dist/server/node_modules/ink/build/components/StderrContext.d.ts +15 -0
- package/dist/server/node_modules/ink/build/components/StderrContext.js +13 -0
- package/dist/server/node_modules/ink/build/components/StderrContext.js.map +1 -0
- package/dist/server/node_modules/ink/build/components/StdinContext.d.ts +22 -0
- package/dist/server/node_modules/ink/build/components/StdinContext.js +19 -0
- package/dist/server/node_modules/ink/build/components/StdinContext.js.map +1 -0
- package/dist/server/node_modules/ink/build/components/StdoutContext.d.ts +15 -0
- package/dist/server/node_modules/ink/build/components/StdoutContext.js +13 -0
- package/dist/server/node_modules/ink/build/components/StdoutContext.js.map +1 -0
- package/dist/server/node_modules/ink/build/components/Text.d.ts +55 -0
- package/dist/server/node_modules/ink/build/components/Text.js +50 -0
- package/dist/server/node_modules/ink/build/components/Text.js.map +1 -0
- package/dist/server/node_modules/ink/build/components/Transform.d.ts +16 -0
- package/dist/server/node_modules/ink/build/components/Transform.js +15 -0
- package/dist/server/node_modules/ink/build/components/Transform.js.map +1 -0
- package/dist/server/node_modules/ink/build/cursor-helpers.d.ts +38 -0
- package/dist/server/node_modules/ink/build/cursor-helpers.js +56 -0
- package/dist/server/node_modules/ink/build/cursor-helpers.js.map +1 -0
- package/dist/server/node_modules/ink/build/devtools-window-polyfill.d.ts +1 -0
- package/dist/server/node_modules/ink/build/devtools-window-polyfill.js +65 -0
- package/dist/server/node_modules/ink/build/devtools-window-polyfill.js.map +1 -0
- package/dist/server/node_modules/ink/build/devtools.d.ts +1 -0
- package/dist/server/node_modules/ink/build/devtools.js +11 -0
- package/dist/server/node_modules/ink/build/devtools.js.map +1 -0
- package/dist/server/node_modules/ink/build/dom.d.ts +56 -0
- package/dist/server/node_modules/ink/build/dom.js +124 -0
- package/dist/server/node_modules/ink/build/dom.js.map +1 -0
- package/dist/server/node_modules/ink/build/experimental/apply-style.js +140 -0
- package/dist/server/node_modules/ink/build/experimental/dom.js +123 -0
- package/dist/server/node_modules/ink/build/experimental/output.js +91 -0
- package/dist/server/node_modules/ink/build/experimental/reconciler.js +141 -0
- package/dist/server/node_modules/ink/build/experimental/renderer.js +81 -0
- package/dist/server/node_modules/ink/build/get-max-width.d.ts +3 -0
- package/dist/server/node_modules/ink/build/get-max-width.js +10 -0
- package/dist/server/node_modules/ink/build/get-max-width.js.map +1 -0
- package/dist/server/node_modules/ink/build/hooks/use-app.d.ts +5 -0
- package/dist/server/node_modules/ink/build/hooks/use-app.js +8 -0
- package/dist/server/node_modules/ink/build/hooks/use-app.js.map +1 -0
- package/dist/server/node_modules/ink/build/hooks/use-cursor.d.ts +12 -0
- package/dist/server/node_modules/ink/build/hooks/use-cursor.js +29 -0
- package/dist/server/node_modules/ink/build/hooks/use-cursor.js.map +1 -0
- package/dist/server/node_modules/ink/build/hooks/use-focus-manager.d.ts +28 -0
- package/dist/server/node_modules/ink/build/hooks/use-focus-manager.js +17 -0
- package/dist/server/node_modules/ink/build/hooks/use-focus-manager.js.map +1 -0
- package/dist/server/node_modules/ink/build/hooks/use-focus.d.ts +29 -0
- package/dist/server/node_modules/ink/build/hooks/use-focus.js +42 -0
- package/dist/server/node_modules/ink/build/hooks/use-focus.js.map +1 -0
- package/dist/server/node_modules/ink/build/hooks/use-input.d.ts +131 -0
- package/dist/server/node_modules/ink/build/hooks/use-input.js +124 -0
- package/dist/server/node_modules/ink/build/hooks/use-input.js.map +1 -0
- package/dist/server/node_modules/ink/build/hooks/use-is-screen-reader-enabled.d.ts +5 -0
- package/dist/server/node_modules/ink/build/hooks/use-is-screen-reader-enabled.js +11 -0
- package/dist/server/node_modules/ink/build/hooks/use-is-screen-reader-enabled.js.map +1 -0
- package/dist/server/node_modules/ink/build/hooks/use-stderr.d.ts +5 -0
- package/dist/server/node_modules/ink/build/hooks/use-stderr.js +8 -0
- package/dist/server/node_modules/ink/build/hooks/use-stderr.js.map +1 -0
- package/dist/server/node_modules/ink/build/hooks/use-stdin.d.ts +5 -0
- package/dist/server/node_modules/ink/build/hooks/use-stdin.js +8 -0
- package/dist/server/node_modules/ink/build/hooks/use-stdin.js.map +1 -0
- package/dist/server/node_modules/ink/build/hooks/use-stdout.d.ts +5 -0
- package/dist/server/node_modules/ink/build/hooks/use-stdout.js +8 -0
- package/dist/server/node_modules/ink/build/hooks/use-stdout.js.map +1 -0
- package/dist/server/node_modules/ink/build/hooks/useInput.js +38 -0
- package/dist/server/node_modules/ink/build/index.d.ts +34 -0
- package/dist/server/node_modules/ink/build/index.js +20 -0
- package/dist/server/node_modules/ink/build/index.js.map +1 -0
- package/dist/server/node_modules/ink/build/ink.d.ts +90 -0
- package/dist/server/node_modules/ink/build/ink.js +637 -0
- package/dist/server/node_modules/ink/build/ink.js.map +1 -0
- package/dist/server/node_modules/ink/build/input-parser.d.ts +7 -0
- package/dist/server/node_modules/ink/build/input-parser.js +154 -0
- package/dist/server/node_modules/ink/build/input-parser.js.map +1 -0
- package/dist/server/node_modules/ink/build/instance.js +205 -0
- package/dist/server/node_modules/ink/build/instances.d.ts +3 -0
- package/dist/server/node_modules/ink/build/instances.js +8 -0
- package/dist/server/node_modules/ink/build/instances.js.map +1 -0
- package/dist/server/node_modules/ink/build/kitty-keyboard.d.ts +23 -0
- package/dist/server/node_modules/ink/build/kitty-keyboard.js +32 -0
- package/dist/server/node_modules/ink/build/kitty-keyboard.js.map +1 -0
- package/dist/server/node_modules/ink/build/layout.d.ts +7 -0
- package/dist/server/node_modules/ink/build/layout.js +33 -0
- package/dist/server/node_modules/ink/build/layout.js.map +1 -0
- package/dist/server/node_modules/ink/build/log-update.d.ts +19 -0
- package/dist/server/node_modules/ink/build/log-update.js +242 -0
- package/dist/server/node_modules/ink/build/log-update.js.map +1 -0
- package/dist/server/node_modules/ink/build/measure-element.d.ts +16 -0
- package/dist/server/node_modules/ink/build/measure-element.js +9 -0
- package/dist/server/node_modules/ink/build/measure-element.js.map +1 -0
- package/dist/server/node_modules/ink/build/measure-text.d.ts +6 -0
- package/dist/server/node_modules/ink/build/measure-text.js +21 -0
- package/dist/server/node_modules/ink/build/measure-text.js.map +1 -0
- package/dist/server/node_modules/ink/build/options.d.ts +52 -0
- package/dist/server/node_modules/ink/build/options.js +2 -0
- package/dist/server/node_modules/ink/build/options.js.map +1 -0
- package/dist/server/node_modules/ink/build/output.d.ts +35 -0
- package/dist/server/node_modules/ink/build/output.js +183 -0
- package/dist/server/node_modules/ink/build/output.js.map +1 -0
- package/dist/server/node_modules/ink/build/parse-keypress.d.ts +22 -0
- package/dist/server/node_modules/ink/build/parse-keypress.js +493 -0
- package/dist/server/node_modules/ink/build/parse-keypress.js.map +1 -0
- package/dist/server/node_modules/ink/build/reconciler.d.ts +4 -0
- package/dist/server/node_modules/ink/build/reconciler.js +274 -0
- package/dist/server/node_modules/ink/build/reconciler.js.map +1 -0
- package/dist/server/node_modules/ink/build/render-background.d.ts +4 -0
- package/dist/server/node_modules/ink/build/render-background.js +25 -0
- package/dist/server/node_modules/ink/build/render-background.js.map +1 -0
- package/dist/server/node_modules/ink/build/render-border.d.ts +4 -0
- package/dist/server/node_modules/ink/build/render-border.js +73 -0
- package/dist/server/node_modules/ink/build/render-border.js.map +1 -0
- package/dist/server/node_modules/ink/build/render-node-to-output.d.ts +14 -0
- package/dist/server/node_modules/ink/build/render-node-to-output.js +147 -0
- package/dist/server/node_modules/ink/build/render-node-to-output.js.map +1 -0
- package/dist/server/node_modules/ink/build/render-to-string.d.ts +38 -0
- package/dist/server/node_modules/ink/build/render-to-string.js +115 -0
- package/dist/server/node_modules/ink/build/render-to-string.js.map +1 -0
- package/dist/server/node_modules/ink/build/render.d.ts +121 -0
- package/dist/server/node_modules/ink/build/render.js +55 -0
- package/dist/server/node_modules/ink/build/render.js.map +1 -0
- package/dist/server/node_modules/ink/build/renderer.d.ts +8 -0
- package/dist/server/node_modules/ink/build/renderer.js +55 -0
- package/dist/server/node_modules/ink/build/renderer.js.map +1 -0
- package/dist/server/node_modules/ink/build/sanitize-ansi.d.ts +2 -0
- package/dist/server/node_modules/ink/build/sanitize-ansi.js +27 -0
- package/dist/server/node_modules/ink/build/sanitize-ansi.js.map +1 -0
- package/dist/server/node_modules/ink/build/screen-reader-update.d.ts +13 -0
- package/dist/server/node_modules/ink/build/screen-reader-update.js +38 -0
- package/dist/server/node_modules/ink/build/screen-reader-update.js.map +1 -0
- package/dist/server/node_modules/ink/build/squash-text-nodes.d.ts +3 -0
- package/dist/server/node_modules/ink/build/squash-text-nodes.js +36 -0
- package/dist/server/node_modules/ink/build/squash-text-nodes.js.map +1 -0
- package/dist/server/node_modules/ink/build/styles.d.ts +240 -0
- package/dist/server/node_modules/ink/build/styles.js +232 -0
- package/dist/server/node_modules/ink/build/styles.js.map +1 -0
- package/dist/server/node_modules/ink/build/utils.d.ts +2 -0
- package/dist/server/node_modules/ink/build/utils.js +4 -0
- package/dist/server/node_modules/ink/build/utils.js.map +1 -0
- package/dist/server/node_modules/ink/build/wrap-text.d.ts +3 -0
- package/dist/server/node_modules/ink/build/wrap-text.js +31 -0
- package/dist/server/node_modules/ink/build/wrap-text.js.map +1 -0
- package/dist/server/node_modules/ink/build/write-synchronized.d.ts +4 -0
- package/dist/server/node_modules/ink/build/write-synchronized.js +7 -0
- package/dist/server/node_modules/ink/build/write-synchronized.js.map +1 -0
- package/dist/server/node_modules/{is-unicode-supported → ink}/license +1 -0
- package/dist/server/node_modules/ink/package.json +201 -0
- package/dist/server/node_modules/ink/readme.md +2636 -0
- package/dist/server/node_modules/slice-ansi/index.d.ts +19 -0
- package/dist/server/node_modules/slice-ansi/index.js +260 -0
- package/dist/server/node_modules/{is-fullwidth-code-point → slice-ansi}/license +1 -0
- package/dist/server/node_modules/slice-ansi/package.json +59 -0
- package/dist/server/node_modules/slice-ansi/readme.md +54 -0
- package/dist/server/node_modules/slice-ansi/tokenize-ansi.js +752 -0
- package/dist/server/server.js +1 -1
- package/package.json +1 -1
- package/dist/client/assets/SearchMd-VdXbz8fL.js +0 -1
- package/dist/client/assets/XCircle-BiHPX6_R.js +0 -1
- package/dist/client/assets/agent-icon-DCE-D-qC.js +0 -1
- package/dist/client/assets/agents-list-8_yOp3iD.js +0 -1
- package/dist/client/assets/ai-providers-DxQNSEJT.js +0 -1
- package/dist/client/assets/automation-list-row-BWjwKsQ5.js +0 -1
- package/dist/client/assets/automations-D6LOd0hH.js +0 -1
- package/dist/client/assets/brand-context-CnnwTWNT.js +0 -1
- package/dist/client/assets/collection-detail-BTibo6D3.js +0 -1
- package/dist/client/assets/collection-display-button-CfjJ9SIP.js +0 -1
- package/dist/client/assets/collection-table-wrapper-B4l_6tOy.js +0 -1
- package/dist/client/assets/command-BPSv-8-5.js +0 -1
- package/dist/client/assets/connection-detail-DgKIsKao.js +0 -1
- package/dist/client/assets/connections-rM_I7gvv.js +0 -1
- package/dist/client/assets/dropdown-menu-DO26Q0bD.js +0 -1
- package/dist/client/assets/general-VnUbEBHT.js +0 -1
- package/dist/client/assets/index-DeSgX7LP.css +0 -1
- package/dist/client/assets/members-6PieW-Nu.js +0 -3
- package/dist/client/assets/project-app-view-EMrqjiux.js +0 -1
- package/dist/client/assets/registry-CYL2cMC0.js +0 -2
- package/dist/client/assets/settings-layout-hwviWS6Q.js +0 -1
- package/dist/client/assets/store-registry-DAeO63_G.js +0 -2
- package/dist/client/assets/tools-list-C0RCBhOc.js +0 -1
- package/dist/client/assets/useInfiniteQuery-Ci00Hw-m.js +0 -1
- package/dist/client/assets/workflow-BrBlpNSn.js +0 -1
- package/dist/client/assets/workflow-detail-NqGVn5hy.js +0 -1
- package/dist/server/node_modules/ansi-regex/index.d.ts +0 -33
- package/dist/server/node_modules/ansi-regex/index.js +0 -14
- package/dist/server/node_modules/ansi-regex/package.json +0 -61
- package/dist/server/node_modules/ansi-regex/readme.md +0 -66
- package/dist/server/node_modules/emoji-regex/LICENSE-MIT.txt +0 -20
- package/dist/server/node_modules/emoji-regex/README.md +0 -107
- package/dist/server/node_modules/emoji-regex/index.d.ts +0 -3
- package/dist/server/node_modules/emoji-regex/index.js +0 -4
- package/dist/server/node_modules/emoji-regex/index.mjs +0 -4
- package/dist/server/node_modules/emoji-regex/package.json +0 -45
- package/dist/server/node_modules/environment/index.d.ts +0 -74
- package/dist/server/node_modules/environment/index.js +0 -47
- package/dist/server/node_modules/environment/package.json +0 -74
- package/dist/server/node_modules/environment/readme.md +0 -94
- package/dist/server/node_modules/escape-string-regexp/index.d.ts +0 -18
- package/dist/server/node_modules/escape-string-regexp/index.js +0 -11
- package/dist/server/node_modules/escape-string-regexp/license +0 -9
- package/dist/server/node_modules/escape-string-regexp/package.json +0 -43
- package/dist/server/node_modules/escape-string-regexp/readme.md +0 -29
- package/dist/server/node_modules/is-fullwidth-code-point/index.d.ts +0 -17
- package/dist/server/node_modules/is-fullwidth-code-point/index.js +0 -12
- package/dist/server/node_modules/is-fullwidth-code-point/readme.md +0 -31
- package/dist/server/node_modules/is-unicode-supported/index.d.ts +0 -12
- package/dist/server/node_modules/is-unicode-supported/index.js +0 -21
- package/dist/server/node_modules/is-unicode-supported/package.json +0 -47
- package/dist/server/node_modules/is-unicode-supported/readme.md +0 -35
- package/dist/server/node_modules/restore-cursor/index.d.ts +0 -11
- package/dist/server/node_modules/restore-cursor/index.js +0 -11
- package/dist/server/node_modules/restore-cursor/license +0 -9
- package/dist/server/node_modules/restore-cursor/package.json +0 -55
- package/dist/server/node_modules/restore-cursor/readme.md +0 -31
- package/dist/server/node_modules/string-width/index.d.ts +0 -39
- package/dist/server/node_modules/string-width/index.js +0 -82
- package/dist/server/node_modules/string-width/license +0 -9
- package/dist/server/node_modules/string-width/package.json +0 -64
- package/dist/server/node_modules/string-width/readme.md +0 -66
- /package/dist/server/node_modules/{ansi-regex → figures}/license +0 -0
- /package/dist/server/node_modules/{environment → get-east-asian-width}/license +0 -0
package/dist/server/cli.js
CHANGED
|
@@ -109,7 +109,7 @@ Connection: close\r
|
|
|
109
109
|
\r
|
|
110
110
|
${B}`)},K=(U)=>{W=Buffer.concat([W,U]);let N=W.indexOf(az8);if(N===-1){if(W.length>nz8)J.off("data",K),$(431,"Request Header Fields Too Large");return}J.off("data",K);let B=W.slice(0,N).toString("utf8");H(B)},H=async(U)=>{let N=rz8(U);if(!N){$(400,"Bad Request");return}let B=tz8(N.host),z=X();if(!z){$(503,"Sandbox Runner Not Initialized");return}if(!B){$(404,"Not a Sandbox Host");return}try{new URL(N.path,"http://local")}catch{$(400,"Bad Request");return}let O=await oz8(z,B);if(!O){$(404,"Sandbox Not Found");return}let w=A$1.connect(O,"127.0.0.1",()=>{w.write(W),W=Buffer.alloc(0),w.pipe(J),J.pipe(w)});w.on("error",()=>J.destroy()),J.on("error",()=>w.destroy()),J.on("close",()=>w.destroy()),w.on("close",()=>J.destroy())};J.on("data",K),J.on("error",()=>{})},Q=(J)=>{let W=A$1.createServer(G),Z=20,$=0,K=!1;W.on("listening",()=>{console.log(`[mesh-sandbox-ingress] forwarding *.localhost \u2192 ${J}:${Y}`)});let H=()=>{W.listen(Y,J)};return W.on("error",(U)=>{if(U.code==="EADDRINUSE"&&$<20){if(!K)K=!0,console.warn(`[mesh-sandbox-ingress] ${J}:${Y} in use \u2014 waiting for previous process to release (up to ${"10"}s)...`);$++,setTimeout(H,500);return}if(U.code==="EADDRINUSE"){let N=Y===7000?" (port 7000 is grabbed by macOS AirPlay Receiver \u2014 set SANDBOX_INGRESS_PORT to another port, e.g. 7070)":" \u2014 another process is holding it; find it with `lsof -iTCP:"+Y+" -sTCP:LISTEN -n -P`";console.warn(`[mesh-sandbox-ingress] ${J}:${Y} still in use after 10s; giving up${N}.`);return}console.warn(`[mesh-sandbox-ingress] ${J}:${Y} listen error: ${U.message}`)}),H(),W};return[Q("127.0.0.1"),Q("::1")]}var pz8,nz8=16384,az8;var ru0=D(()=>{pz8=/^([^.]+)\.localhost(?::\d+)?$/i,az8=Buffer.from(`\r
|
|
111
111
|
\r
|
|
112
|
-
`)});async function bn1(X={}){let Y=globalThis;if(Y[ou0])return;Y[ou0]=!0;try{let Q=await new GF(X).sweepOrphans();if(Q>0)console.log(`[sandbox] Boot sweep: stopped ${Q} stale container(s).`)}catch(G){console.warn("[sandbox] Boot sweep failed (continuing without it):",G instanceof Error?G.message:G)}}async function yn1(X){if(!X)return;console.log("[shutdown] Sweeping docker sandbox containers...");try{let Y=await X.sweepOrphans();if(Y>0)console.log(`[shutdown] Swept ${Y} sandbox container(s).`)}catch(Y){console.error("[shutdown] Sandbox sweep error:",Y)}}var ou0;var su0=D(()=>{_n1();ou0=Symbol.for("mesh.sandbox.bootSweepDone")});var Se=D(()=>{_n1();ru0();su0()});function T$1(X){if("threadId"in X){if(!X.threadId)throw Error("composeSandboxRef: threadId required");return`thread:${X.threadId}`}if(!X.orgId||!X.virtualMcpId||!X.branch)throw Error("composeSandboxRef: orgId, virtualMcpId and branch are all required for agent refs");return`agent:${X.orgId}:${X.virtualMcpId}:${X.branch}`}var ve={};R0(ve,{tryResolveRunnerKindFromEnv:()=>ke,sweepDockerOrphansOnShutdown:()=>yn1,sweepDockerOrphansOnBoot:()=>bn1,startLocalSandboxIngress:()=>fn1,sandboxIdKey:()=>Dd,resolveRunnerKindFromEnv:()=>Ed,ensureSandboxImage:()=>P$1,createDockerRunner:()=>ez8,composeSandboxRef:()=>T$1,DockerSandboxRunner:()=>GF});import{spawnSync as sz8}from"child_process";function ez8(X={}){return new GF({...X.docker,stateStore:X.stateStore})}function XO8(){if(Ce!==null)return Ce;try{Ce=sz8("docker",["--version"],{stdio:"ignore",timeout:2000}).status===0}catch{Ce=!1}return Ce}function ke(){let X=process.env.STUDIO_SANDBOX_RUNNER;if(X==="docker"||X==="freestyle"||X==="agent-sandbox")return X;if(X&&X.length>0)throw Error(`Unknown STUDIO_SANDBOX_RUNNER="${X}" \u2014 expected "docker", "freestyle", or "agent-sandbox".`);if(process.env.FREESTYLE_API_KEY)return"freestyle";return null}function Ed(){let X=ke();if(X)return X;throw Error("STUDIO_SANDBOX_RUNNER must be set explicitly in production \u2014 "+'choose "docker", "freestyle", or "agent-sandbox" (or set FREESTYLE_API_KEY).')}var Ce=null;var nT=D(()=>{Se();Se();kn1();Se();Se()});var _e={};R0(_e,{kickoffSandboxImageBuild:()=>YO8});async function YO8(X){return}var fe=D(()=>{YF()});import{homedir as GO8}from"os";function Pd(X){return X==="true"||X==="1"}function eu0(X){if(!X)return null;try{let G=new URL(X).hostname;if(G==="localhost"||G==="127.0.0.1"||G==="::1")return null;return X}catch{return null}}function I$1(X,Y){let G=X.home||Y.DATA_DIR||Y.DECOCMS_HOME||`${GO8()}/deco`,Q=X.localMode,J=X.nodeEnv||Y.NODE_ENV||"development",W=Y.NATS_URL||"nats://localhost:4222";return{settings:{nodeEnv:J,port:Number(X.port)||Number(Y.PORT)||3000,baseUrl:X.baseUrl||Y.BASE_URL,dataDir:G,databasePgSsl:Pd(Y.DATABASE_PG_SSL),databasePoolMax:Number(Y.DATABASE_POOL_MAX)||3,betterAuthSecret:Y.BETTER_AUTH_SECRET||"",encryptionKey:Y.ENCRYPTION_KEY||"",meshJwtSecret:Y.MESH_JWT_SECRET,localMode:Q,allowLocalProd:Q||Pd(Y.DECOCMS_ALLOW_LOCAL_PROD),disableRateLimit:Pd(Y.DISABLE_RATE_LIMIT),studioProvisionSecretKey:Y.STUDIO_PROVISION_SECRET_KEY,clickhouseUrl:Y.CLICKHOUSE_URL,otelServiceName:Y.OTEL_SERVICE_NAME||"mesh",configPath:Y.CONFIG_PATH||"./config.json",unsafeAllowStdioTransport:Pd(Y.UNSAFE_ALLOW_STDIO_TRANSPORT),aiGatewayEnabled:Pd(Y.DECO_AI_GATEWAY_ENABLED),aiGatewayUrl:Y.DECO_AI_GATEWAY_URL||"https://ai-site.decocache.com",enableDecoImport:Pd(Y.ENABLE_DECO_IMPORT),s3Endpoint:Y.S3_ENDPOINT,s3Bucket:Y.S3_BUCKET,s3Region:Y.S3_REGION||"auto",s3AccessKeyId:Y.S3_ACCESS_KEY_ID,s3SecretAccessKey:Y.S3_SECRET_ACCESS_KEY,s3ForcePathStyle:Y.S3_FORCE_PATH_STYLE===void 0||Y.S3_FORCE_PATH_STYLE===""||Y.S3_FORCE_PATH_STYLE==="true"||Y.S3_FORCE_PATH_STYLE==="1",isCli:!0,noTui:X.noTui===!0,podName:Y.POD_NAME??crypto.randomUUID(),decoSupabaseUrl:Y.DECO_SUPABASE_URL,decoSupabaseServiceKey:Y.DECO_SUPABASE_SERVICE_KEY,firecrawlApiKey:Y.FIRECRAWL_API_KEY},externalDatabaseUrl:eu0(Y.DATABASE_URL),externalNatsUrl:eu0(W),skipMigrations:X.skipMigrations}}var xn1=()=>{};function Xl0(X){be=Object.freeze(X)}function v6(){if(!be)QO8();return be}function QO8(){if(be)return;let X={...process.env},Y=I$1({port:X.PORT||"3000",home:X.DATA_DIR||X.DECOCMS_HOME||"",localMode:X.DECOCMS_LOCAL_MODE==="true",skipMigrations:!0,noTui:X.DECO_NO_TUI==="true",vitePort:X.VITE_PORT,baseUrl:X.BASE_URL},X);be=Object.freeze({...Y.settings,databaseUrl:X.DATABASE_URL??"postgresql://postgres:postgres@localhost:5432/postgres",natsUrls:(X.NATS_URL||"nats://localhost:4222").split(",").map((G)=>G.trim()).filter(Boolean)})}var be=null;var m9=D(()=>{xn1()});function LZ(X){return typeof X>"u"||X===void 0}function H9(X){return typeof X==="string"}function QF(X){return typeof X==="number"}function UO(X){return typeof X==="boolean"}function dL(X){return X===null}function qd(X){return X instanceof Date}function cL(X){return typeof X==="bigint"}function V$1(X){return typeof Buffer<"u"&&Buffer.isBuffer(X)}function F9(X){return typeof X==="function"}function F7(X){return typeof X==="object"&&X!==null}function j$1(X){if(!F7(X)||FO8(X)!=="[object Object]")return!1;if(Object.getPrototypeOf(X)===null)return!0;let Y=X;while(Object.getPrototypeOf(Y)!==null)Y=Object.getPrototypeOf(Y);return Object.getPrototypeOf(X)===Y}function Yl0(X){return X[X.length-1]}function n(X){return Object.freeze(X)}function ye(X){if(IG(X))return X;else return[X]}function IG(X){return Array.isArray(X)}function EZ(X){return X}function M$1(X,Y){if(IG(X)&&IG(Y))return JO8(X,Y);else if(F7(X)&&F7(Y))return ZO8(X,Y);return X===Y}function JO8(X,Y){if(X.length!==Y.length)return!1;for(let G=0;G<X.length;++G)if(!M$1(X[G],Y[G]))return!1;return!0}function ZO8(X,Y){if(V$1(X)&&V$1(Y))return WO8(X,Y);else if(qd(X)&&qd(Y))return $O8(X,Y);return KO8(X,Y)}function WO8(X,Y){return Buffer.compare(X,Y)===0}function $O8(X,Y){return X.getTime()===Y.getTime()}function KO8(X,Y){let G=Object.keys(X),Q=Object.keys(Y);if(G.length!==Q.length)return!1;for(let J of G)if(!M$1(X[J],Y[J]))return!1;return!0}function FO8(X){if(X==null)return X===void 0?"[object Undefined]":"[object Null]";return HO8.call(X)}var HO8;var W0=D(()=>{HO8=Object.prototype.toString});var _5;var aT=D(()=>{W0();_5=n({is(X){return X.kind==="AlterTableNode"},create(X){return n({kind:"AlterTableNode",table:X})},cloneWithTableProps(X,Y){return n({...X,...Y})},cloneWithColumnAlteration(X,Y){return n({...X,columnAlterations:X.columnAlterations?[...X.columnAlterations,Y]:[Y]})}})});var k4;var U7=D(()=>{W0();k4=n({is(X){return X.kind==="IdentifierNode"},create(X){return n({kind:"IdentifierNode",name:X})}})});var JF;var R$1=D(()=>{W0();U7();JF=n({is(X){return X.kind==="CreateIndexNode"},create(X){return n({kind:"CreateIndexNode",name:k4.create(X)})},cloneWith(X,Y){return n({...X,...Y})},cloneWithColumns(X,Y){return n({...X,columns:[...X.columns||[],...Y]})}})});var S$1;var C$1=D(()=>{W0();U7();S$1=n({is(X){return X.kind==="CreateSchemaNode"},create(X,Y){return n({kind:"CreateSchemaNode",schema:k4.create(X),...Y})},cloneWith(X,Y){return n({...X,...Y})}})});var Gl0,wJ;var Ad=D(()=>{W0();Gl0=["preserve rows","delete rows","drop"],wJ=n({is(X){return X.kind==="CreateTableNode"},create(X){return n({kind:"CreateTableNode",table:X,columns:n([])})},cloneWithColumn(X,Y){return n({...X,columns:n([...X.columns,Y])})},cloneWithConstraint(X,Y){return n({...X,constraints:X.constraints?n([...X.constraints,Y]):n([Y])})},cloneWithFrontModifier(X,Y){return n({...X,frontModifiers:X.frontModifiers?n([...X.frontModifiers,Y]):n([Y])})},cloneWithEndModifier(X,Y){return n({...X,endModifiers:X.endModifiers?n([...X.endModifiers,Y]):n([Y])})},cloneWith(X,Y){return n({...X,...Y})}})});var LJ;var NO=D(()=>{W0();U7();LJ=n({is(X){return X.kind==="SchemableIdentifierNode"},create(X){return n({kind:"SchemableIdentifierNode",identifier:k4.create(X)})},createWithSchema(X,Y){return n({kind:"SchemableIdentifierNode",schema:k4.create(X),identifier:k4.create(Y)})}})});var iL;var xe=D(()=>{W0();NO();iL=n({is(X){return X.kind==="DropIndexNode"},create(X,Y){return n({kind:"DropIndexNode",name:LJ.create(X),...Y})},cloneWith(X,Y){return n({...X,...Y})}})});var he;var k$1=D(()=>{W0();U7();he=n({is(X){return X.kind==="DropSchemaNode"},create(X,Y){return n({kind:"DropSchemaNode",schema:k4.create(X),...Y})},cloneWith(X,Y){return n({...X,...Y})}})});var ge;var v$1=D(()=>{W0();ge=n({is(X){return X.kind==="DropTableNode"},create(X,Y){return n({kind:"DropTableNode",table:X,...Y})},cloneWith(X,Y){return n({...X,...Y})}})});var VG;var ZF=D(()=>{W0();VG=n({is(X){return X.kind==="AliasNode"},create(X,Y){return n({kind:"AliasNode",node:X,alias:Y})}})});var _3;var Td=D(()=>{W0();NO();_3=n({is(X){return X.kind==="TableNode"},create(X){return n({kind:"TableNode",table:LJ.create(X)})},createWithSchema(X,Y){return n({kind:"TableNode",table:LJ.createWithSchema(X,Y)})}})});function R7(X){return F7(X)&&F9(X.toOperationNode)}var f3=D(()=>{W0()});function _$1(X){return F7(X)&&"expressionType"in X&&R7(X)}function Ql0(X){return F7(X)&&"expression"in X&&H9(X.alias)&&R7(X)}var f$1=D(()=>{f3();W0()});var zN;var hn1=D(()=>{W0();zN=n({is(X){return X.kind==="SelectModifierNode"},create(X,Y){return n({kind:"SelectModifierNode",modifier:X,of:Y})},createWithExpression(X){return n({kind:"SelectModifierNode",rawModifier:X})}})});var b3;var pL=D(()=>{W0();b3=n({is(X){return X.kind==="AndNode"},create(X,Y){return n({kind:"AndNode",left:X,right:Y})}})});var WF;var tT=D(()=>{W0();WF=n({is(X){return X.kind==="OrNode"},create(X,Y){return n({kind:"OrNode",left:X,right:Y})}})});var b$1;var gn1=D(()=>{W0();pL();tT();b$1=n({is(X){return X.kind==="OnNode"},create(X){return n({kind:"OnNode",on:X})},cloneWithOperation(X,Y,G){return n({...X,on:Y==="And"?b3.create(X.on,G):WF.create(X.on,G)})}})});var $F;var Id=D(()=>{W0();gn1();$F=n({is(X){return X.kind==="JoinNode"},create(X,Y){return n({kind:"JoinNode",joinType:X,table:Y,on:void 0})},createWithOn(X,Y,G){return n({kind:"JoinNode",joinType:X,table:Y,on:b$1.create(G)})},cloneWithOn(X,Y){return n({...X,on:X.on?b$1.cloneWithOperation(X.on,"And",Y):b$1.create(Y)})}})});var nL;var y$1=D(()=>{W0();nL=n({is(X){return X.kind==="BinaryOperationNode"},create(X,Y,G){return n({kind:"BinaryOperationNode",leftOperand:X,operator:Y,rightOperand:G})}})});function un1(X){return H9(X)&&Jl0.includes(X)}var UO8,NO8,Jl0,BO8,zO8,OO8,Zl0,PZ;var aL=D(()=>{W0();UO8=["=","==","!=","<>",">",">=","<","<=","in","not in","is","is not","like","not like","match","ilike","not ilike","@>","<@","^@","&&","?","?&","?|","!<","!>","<=>","!~","~","~*","!~*","@@","@@@","!!","<->","regexp","is distinct from","is not distinct from"],NO8=["+","-","*","/","%","^","&","|","#","<<",">>"],Jl0=["->","->>"],BO8=[...UO8,...NO8,"&&","||"],zO8=["exists","not exists"],OO8=["not","-",...zO8],Zl0=[...BO8,...Jl0,...OO8,"between","between symmetric"],PZ=n({is(X){return X.kind==="OperatorNode"},create(X){return n({kind:"OperatorNode",operator:X})}})});var T5;var EJ=D(()=>{W0();U7();T5=n({is(X){return X.kind==="ColumnNode"},create(X){return n({kind:"ColumnNode",column:k4.create(X)})}})});var Vd;var ue=D(()=>{W0();Vd=n({is(X){return X.kind==="SelectAllNode"},create(){return n({kind:"SelectAllNode"})}})});var jd;var x$1=D(()=>{ue();W0();jd=n({is(X){return X.kind==="ReferenceNode"},create(X,Y){return n({kind:"ReferenceNode",table:Y,column:X})},createSelectAll(X){return n({kind:"ReferenceNode",table:X,column:Vd.create()})}})});class ln1{#X;get dynamicReference(){return this.#X}get refType(){return}constructor(X){this.#X=X}toOperationNode(){return mn1(this.#X)}}function h$1(X){return F7(X)&&R7(X)&&H9(X.dynamicReference)}var le=D(()=>{f3();OQ();W0()});var KF;var g$1=D(()=>{W0();KF=n({is(X){return X.kind==="OrderByItemNode"},create(X,Y){return n({kind:"OrderByItemNode",orderBy:X,direction:Y})},cloneWith(X,Y){return n({...X,...Y})}})});var f5;var EK=D(()=>{W0();f5=n({is(X){return X.kind==="RawNode"},create(X,Y){return n({kind:"RawNode",sqlFragments:n(X),parameters:n(Y)})},createWithSql(X){return f5.create([X],[])},createWithChild(X){return f5.create(["",""],[X])},createWithChildren(X){return f5.create(Array(X.length+1).fill(""),X)}})});var Wl0;var dn1=D(()=>{W0();U7();Wl0=n({is(X){return X.kind==="CollateNode"},create(X){return n({kind:"CollateNode",collation:k4.create(X)})}})});class tL{#X;constructor(X){this.#X=n(X)}desc(){return new tL({node:KF.cloneWith(this.#X.node,{direction:f5.createWithSql("desc")})})}asc(){return new tL({node:KF.cloneWith(this.#X.node,{direction:f5.createWithSql("asc")})})}nullsLast(){return new tL({node:KF.cloneWith(this.#X.node,{nulls:"last"})})}nullsFirst(){return new tL({node:KF.cloneWith(this.#X.node,{nulls:"first"})})}collate(X){return new tL({node:KF.cloneWith(this.#X.node,{collation:Wl0.create(X)})})}toOperationNode(){return this.#X.node}}var cn1=D(()=>{dn1();g$1();EK();W0()});function ON(X){if($l0.has(X))return;$l0.add(X),console.log(X)}var $l0;var me=D(()=>{$l0=new Set});function pn1(X){return X==="asc"||X==="desc"}function tW(X){if(X.length===2)return[in1(X[0],X[1])];if(X.length===1){let[Y]=X;if(Array.isArray(Y))return ON("orderBy(array) is deprecated, use multiple orderBy calls instead."),Y.map((G)=>in1(G));return[in1(Y)]}throw Error(`Invalid number of arguments at order by! expected 1-2, received ${X.length}`)}function in1(X,Y){let G=DO8(X);if(KF.is(G)){if(Y)throw Error("Cannot specify direction twice!");return G}return Kl0(G,Y)}function DO8(X){if(BO(X))return y3(X);if(h$1(X))return X.toOperationNode();let[Y,G]=X.split(" ");if(G)return ON("`orderBy('column asc')` is deprecated. Use `orderBy('column', 'asc')` instead."),Kl0(aW(Y),G);return aW(X)}function Kl0(X,Y){if(typeof Y==="string"){if(!pn1(Y))throw Error(`Invalid order by direction: ${Y}`);return KF.create(X,f5.createWithSql(Y))}if(_$1(Y))return ON("`orderBy(..., expr)` is deprecated. Use `orderBy(..., 'asc')` or `orderBy(..., (ob) => ...)` instead."),KF.create(X,Y.toOperationNode());let G=KF.create(X);if(!Y)return G;return Y(new tL({node:G})).toOperationNode()}var rT=D(()=>{le();f$1();g$1();EK();cn1();me();HF();OQ()});var Md;var u$1=D(()=>{W0();Md=n({is(X){return X.kind==="JSONReferenceNode"},create(X,Y){return n({kind:"JSONReferenceNode",reference:X,traversal:Y})},cloneWithTraversal(X,Y){return n({...X,traversal:Y})}})});var l$1;var m$1=D(()=>{W0();l$1=n({is(X){return X.kind==="JSONOperatorChainNode"},create(X){return n({kind:"JSONOperatorChainNode",operator:X,values:n([])})},cloneWithValue(X,Y){return n({...X,values:n([...X.values,Y])})}})});var rL;var de=D(()=>{W0();rL=n({is(X){return X.kind==="JSONPathNode"},create(X){return n({kind:"JSONPathNode",inOperator:X,pathLegs:n([])})},cloneWithLeg(X,Y){return n({...X,pathLegs:n([...X.pathLegs,Y])})}})});function mn1(X){if(H9(X))return aW(X);return X.toOperationNode()}function zO(X){if(IG(X))return X.map((Y)=>DQ(Y));else return[DQ(X)]}function DQ(X){if(BO(X))return y3(X);return mn1(X)}function Hl0(X,Y){let G=aW(X);if(un1(Y))return Md.create(G,l$1.create(PZ.create(Y)));let Q=Y.slice(0,-1);if(un1(Q))return Md.create(G,rL.create(PZ.create(Q)));throw Error(`Invalid JSON operator: ${Y}`)}function aW(X){if(!X.includes("."))return jd.create(T5.create(X));let G=X.split(".").map(an1);if(G.length===3)return wO8(G);if(G.length===2)return LO8(G);throw Error(`invalid column reference ${X}`)}function Fl0(X){if(X.includes(" as ")){let[G,Q]=X.split(" as ").map(an1);return VG.create(aW(G),k4.create(Q))}else return aW(X)}function nn1(X){return T5.create(X)}function Rd(X){if(X.includes(" ")){let[G,Q]=X.split(" ").map(an1);if(!pn1(Q))throw Error(`invalid order direction "${Q}" next to "${G}"`);return tW([G,Q])[0]}else return nn1(X)}function wO8(X){let[Y,G,Q]=X;return jd.create(T5.create(Q),_3.createWithSchema(Y,G))}function LO8(X){let[Y,G]=X;return jd.create(T5.create(G),_3.create(Y))}function an1(X){return X.trim()}var OQ=D(()=>{ZF();EJ();x$1();Td();W0();HF();U7();rT();aL();u$1();m$1();de()});var Sd;var ce=D(()=>{W0();Sd=n({is(X){return X.kind==="PrimitiveValueListNode"},create(X){return n({kind:"PrimitiveValueListNode",values:n([...X])})}})});var DN;var oT=D(()=>{W0();DN=n({is(X){return X.kind==="ValueListNode"},create(X){return n({kind:"ValueListNode",values:n(X)})}})});var kY;var wN=D(()=>{W0();kY=n({is(X){return X.kind==="ValueNode"},create(X){return n({kind:"ValueNode",value:X})},createImmediate(X){return n({kind:"ValueNode",value:X,immediate:!0})}})});function Ul0(X){if(IG(X))return EO8(X);return d9(X)}function d9(X){if(BO(X))return y3(X);return kY.create(X)}function d$1(X){return QF(X)||UO(X)||dL(X)}function ie(X){if(!d$1(X))throw Error(`unsafe immediate value ${JSON.stringify(X)}`);return kY.createImmediate(X)}function EO8(X){if(X.some(BO))return DN.create(X.map((Y)=>d9(Y)));return Sd.create(X)}var LN=D(()=>{ce();oT();wN();W0();HF()});var rW;var Cd=D(()=>{W0();rW=n({is(X){return X.kind==="ParensNode"},create(X){return n({kind:"ParensNode",node:X})}})});function N7(X){if(X.length===3)return c$1(X[0],X[1],X[2]);else if(X.length===1)return d9(X[0]);throw Error(`invalid arguments: ${JSON.stringify(X)}`)}function c$1(X,Y,G){if(PO8(Y)&&Bl0(G))return nL.create(DQ(X),tn1(Y),kY.createImmediate(G));return nL.create(DQ(X),tn1(Y),Ul0(G))}function jG(X,Y,G){return nL.create(DQ(X),tn1(Y),DQ(G))}function rn1(X,Y){return kd(Object.entries(X).filter(([,G])=>!LZ(G)).map(([G,Q])=>c$1(G,Bl0(Q)?"is":"=",Q)),Y)}function kd(X,Y,G=!0){let Q=Y==="and"?b3.create:WF.create;if(X.length===0)return nL.create(kY.createImmediate(1),PZ.create("="),kY.createImmediate(Y==="and"?1:0));let J=Nl0(X[0]);for(let W=1;W<X.length;++W)J=Q(J,Nl0(X[W]));if(X.length>1&&G)return rW.create(J);return J}function PO8(X){return X==="is"||X==="is not"}function Bl0(X){return dL(X)||UO(X)}function tn1(X){if(H9(X)&&Zl0.includes(X))return PZ.create(X);if(R7(X))return X.toOperationNode();throw Error(`invalid operator ${JSON.stringify(X)}`)}function Nl0(X){return R7(X)?X.toOperationNode():X}var oW=D(()=>{y$1();W0();f3();aL();OQ();LN();wN();pL();Cd();tT()});var OO;var pe=D(()=>{W0();OO=n({is(X){return X.kind==="OrderByNode"},create(X){return n({kind:"OrderByNode",items:n([...X])})},cloneWithItems(X,Y){return n({...X,items:n([...X.items,...Y])})}})});var on1;var sn1=D(()=>{W0();on1=n({is(X){return X.kind==="PartitionByNode"},create(X){return n({kind:"PartitionByNode",items:n(X)})},cloneWithItems(X,Y){return n({...X,items:n([...X.items,...Y])})}})});var ne;var i$1=D(()=>{W0();pe();sn1();ne=n({is(X){return X.kind==="OverNode"},create(){return n({kind:"OverNode"})},cloneWithOrderByItems(X,Y){return n({...X,orderBy:X.orderBy?OO.cloneWithItems(X.orderBy,Y):OO.create(Y)})},cloneWithPartitionByItems(X,Y){return n({...X,partitionBy:X.partitionBy?on1.cloneWithItems(X.partitionBy,Y):on1.create(Y)})}})});var sT;var ae=D(()=>{W0();sT=n({is(X){return X.kind==="FromNode"},create(X){return n({kind:"FromNode",froms:n(X)})},cloneWithFroms(X,Y){return n({...X,froms:n([...X.froms,...Y])})}})});var en1;var Xa1=D(()=>{W0();en1=n({is(X){return X.kind==="GroupByNode"},create(X){return n({kind:"GroupByNode",items:n(X)})},cloneWithItems(X,Y){return n({...X,items:n([...X.items,...Y])})}})});var Ya1;var Ga1=D(()=>{W0();pL();tT();Ya1=n({is(X){return X.kind==="HavingNode"},create(X){return n({kind:"HavingNode",having:X})},cloneWithOperation(X,Y,G){return n({...X,having:Y==="And"?b3.create(X.having,G):WF.create(X.having,G)})}})});var xX;var eT=D(()=>{W0();xX=n({is(X){return X.kind==="InsertQueryNode"},create(X,Y,G){return n({kind:"InsertQueryNode",into:X,...Y&&{with:Y},replace:G})},createWithoutInto(){return n({kind:"InsertQueryNode"})},cloneWith(X,Y){return n({...X,...Y})}})});var p$1;var n$1=D(()=>{W0();p$1=n({is(X){return X.kind==="ListNode"},create(X){return n({kind:"ListNode",items:n(X)})}})});var EN;var vd=D(()=>{W0();ae();n$1();EN=n({is(X){return X.kind==="UpdateQueryNode"},create(X,Y){return n({kind:"UpdateQueryNode",table:X.length===1?X[0]:p$1.create(X),...Y&&{with:Y}})},createWithoutTable(){return n({kind:"UpdateQueryNode"})},cloneWithFromItems(X,Y){return n({...X,from:X.from?sT.cloneWithFroms(X.from,Y):sT.create(Y)})},cloneWithUpdates(X,Y){return n({...X,updates:X.updates?n([...X.updates,...Y]):Y})},cloneWithLimit(X,Y){return n({...X,limit:Y})}})});var te;var a$1=D(()=>{W0();te=n({is(X){return X.kind==="UsingNode"},create(X){return n({kind:"UsingNode",tables:n(X)})},cloneWithTables(X,Y){return n({...X,tables:n([...X.tables,...Y])})}})});var oL;var re=D(()=>{W0();ae();a$1();PK();oL=n({is(X){return X.kind==="DeleteQueryNode"},create(X,Y){return n({kind:"DeleteQueryNode",from:sT.create(X),...Y&&{with:Y}})},cloneWithOrderByItems:(X,Y)=>A6.cloneWithOrderByItems(X,Y),cloneWithoutOrderBy:(X)=>A6.cloneWithoutOrderBy(X),cloneWithLimit(X,Y){return n({...X,limit:Y})},cloneWithoutLimit(X){return n({...X,limit:void 0})},cloneWithUsing(X,Y){return n({...X,using:X.using!==void 0?te.cloneWithTables(X.using,Y):te.create(Y)})}})});var wQ;var oe=D(()=>{W0();pL();tT();wQ=n({is(X){return X.kind==="WhereNode"},create(X){return n({kind:"WhereNode",where:X})},cloneWithOperation(X,Y,G){return n({...X,where:Y==="And"?b3.create(X.where,G):WF.create(X.where,G)})}})});var Qa1;var Ja1=D(()=>{W0();Qa1=n({is(X){return X.kind==="ReturningNode"},create(X){return n({kind:"ReturningNode",selections:n(X)})},cloneWithSelections(X,Y){return n({...X,selections:X.selections?n([...X.selections,...Y]):n(Y)})}})});var zl0;var Za1=D(()=>{W0();zl0=n({is(X){return X.kind==="ExplainNode"},create(X,Y){return n({kind:"ExplainNode",format:X,options:Y})}})});var qK;var XI=D(()=>{W0();qK=n({is(X){return X.kind==="WhenNode"},create(X){return n({kind:"WhenNode",condition:X})},cloneWithResult(X,Y){return n({...X,result:Y})}})});var sW;var se=D(()=>{W0();XI();sW=n({is(X){return X.kind==="MergeQueryNode"},create(X,Y){return n({kind:"MergeQueryNode",into:X,...Y&&{with:Y}})},cloneWithUsing(X,Y){return n({...X,using:Y})},cloneWithWhen(X,Y){return n({...X,whens:X.whens?n([...X.whens,Y]):n([Y])})},cloneWithThen(X,Y){return n({...X,whens:X.whens?n([...X.whens.slice(0,-1),qK.cloneWithResult(X.whens[X.whens.length-1],Y)]):void 0})}})});var Wa1;var $a1=D(()=>{W0();Wa1=n({is(X){return X.kind==="OutputNode"},create(X){return n({kind:"OutputNode",selections:n(X)})},cloneWithSelections(X,Y){return n({...X,selections:X.selections?n([...X.selections,...Y]):n(Y)})}})});var A6;var PK=D(()=>{eT();YI();vd();re();oe();W0();Ja1();Za1();se();$a1();pe();A6=n({is(X){return U9.is(X)||xX.is(X)||EN.is(X)||oL.is(X)||sW.is(X)},cloneWithEndModifier(X,Y){return n({...X,endModifiers:X.endModifiers?n([...X.endModifiers,Y]):n([Y])})},cloneWithWhere(X,Y){return n({...X,where:X.where?wQ.cloneWithOperation(X.where,"And",Y):wQ.create(Y)})},cloneWithJoin(X,Y){return n({...X,joins:X.joins?n([...X.joins,Y]):n([Y])})},cloneWithReturning(X,Y){return n({...X,returning:X.returning?Qa1.cloneWithSelections(X.returning,Y):Qa1.create(Y)})},cloneWithoutReturning(X){return n({...X,returning:void 0})},cloneWithoutWhere(X){return n({...X,where:void 0})},cloneWithExplain(X,Y,G){return n({...X,explain:zl0.create(Y,G?.toOperationNode())})},cloneWithTop(X,Y){return n({...X,top:Y})},cloneWithOutput(X,Y){return n({...X,output:X.output?Wa1.cloneWithSelections(X.output,Y):Wa1.create(Y)})},cloneWithOrderByItems(X,Y){return n({...X,orderBy:X.orderBy?OO.cloneWithItems(X.orderBy,Y):OO.create(Y)})},cloneWithoutOrderBy(X){return n({...X,orderBy:void 0})}})});var U9;var YI=D(()=>{W0();ae();Xa1();Ga1();PK();U9=n({is(X){return X.kind==="SelectQueryNode"},create(X){return n({kind:"SelectQueryNode",...X&&{with:X}})},createFrom(X,Y){return n({kind:"SelectQueryNode",from:sT.create(X),...Y&&{with:Y}})},cloneWithSelections(X,Y){return n({...X,selections:X.selections?n([...X.selections,...Y]):n(Y)})},cloneWithDistinctOn(X,Y){return n({...X,distinctOn:X.distinctOn?n([...X.distinctOn,...Y]):n(Y)})},cloneWithFrontModifier(X,Y){return n({...X,frontModifiers:X.frontModifiers?n([...X.frontModifiers,Y]):n([Y])})},cloneWithOrderByItems:(X,Y)=>A6.cloneWithOrderByItems(X,Y),cloneWithGroupByItems(X,Y){return n({...X,groupBy:X.groupBy?en1.cloneWithItems(X.groupBy,Y):en1.create(Y)})},cloneWithLimit(X,Y){return n({...X,limit:Y})},cloneWithOffset(X,Y){return n({...X,offset:Y})},cloneWithFetch(X,Y){return n({...X,fetch:Y})},cloneWithHaving(X,Y){return n({...X,having:X.having?Ya1.cloneWithOperation(X.having,"And",Y):Ya1.create(Y)})},cloneWithSetOperations(X,Y){return n({...X,setOperations:X.setOperations?n([...X.setOperations,...Y]):n([...Y])})},cloneWithoutSelections(X){return n({...X,selections:[]})},cloneWithoutLimit(X){return n({...X,limit:void 0})},cloneWithoutOffset(X){return n({...X,offset:void 0})},cloneWithoutOrderBy:(X)=>A6.cloneWithoutOrderBy(X),cloneWithoutGroupBy(X){return n({...X,groupBy:void 0})}})});class _d{#X;constructor(X){this.#X=n(X)}on(...X){return new _d({...this.#X,joinNode:$F.cloneWithOn(this.#X.joinNode,N7(X))})}onRef(X,Y,G){return new _d({...this.#X,joinNode:$F.cloneWithOn(this.#X.joinNode,jG(X,Y,G))})}onTrue(){return new _d({...this.#X,joinNode:$F.cloneWithOn(this.#X.joinNode,f5.createWithSql("true"))})}$call(X){return X(this)}toOperationNode(){return this.#X.joinNode}}var Ka1=D(()=>{Id();EK();oW();W0()});var Ol0;var Ha1=D(()=>{W0();Ol0=n({is(X){return X.kind==="PartitionByItemNode"},create(X){return n({kind:"PartitionByItemNode",partitionBy:X})}})});function Dl0(X){return zO(X).map(Ol0.create)}var wl0=D(()=>{Ha1();OQ()});class fd{#X;constructor(X){this.#X=n(X)}orderBy(...X){return new fd({overNode:ne.cloneWithOrderByItems(this.#X.overNode,tW(X))})}clearOrderBy(){return new fd({overNode:A6.cloneWithoutOrderBy(this.#X.overNode)})}partitionBy(X){return new fd({overNode:ne.cloneWithPartitionByItems(this.#X.overNode,Dl0(X))})}$call(X){return X(this)}toOperationNode(){return this.#X.overNode}}var Ll0=D(()=>{i$1();PK();rT();wl0();W0()});var bd;var Fa1=D(()=>{W0();x$1();ue();bd=n({is(X){return X.kind==="SelectionNode"},create(X){return n({kind:"SelectionNode",selection:X})},createSelectAll(){return n({kind:"SelectionNode",selection:Vd.create()})},createSelectAllFromTable(X){return n({kind:"SelectionNode",selection:jd.createSelectAll(X)})}})});function sY(X){if(F9(X))return sY(X(FF()));else if(IG(X))return X.map((Y)=>El0(Y));else return[El0(X)]}function El0(X){if(H9(X))return bd.create(Fl0(X));else if(h$1(X))return bd.create(X.toOperationNode());else return bd.create(t$1(X))}function MG(X){if(!X)return[bd.createSelectAll()];else if(Array.isArray(X))return X.map(Pl0);else return[Pl0(X)]}function Pl0(X){if(H9(X))return bd.createSelectAllFromTable(b5(X));throw Error(`invalid value selectAll expression: ${JSON.stringify(X)}`)}var sL=D(()=>{W0();Fa1();OQ();le();HF();LQ();GI()});var ql0;var Ua1=D(()=>{W0();ql0=n({is(X){return X.kind==="ValuesNode"},create(X){return n({kind:"ValuesNode",values:n(X)})}})});var Al0;var Na1=D(()=>{W0();Al0=n({is(X){return X.kind==="DefaultInsertValueNode"},create(){return n({kind:"DefaultInsertValueNode"})}})});function r$1(X){let Y=F9(X)?X(FF()):X,G=IG(Y)?Y:n([Y]);return qO8(G)}function qO8(X){let Y=AO8(X);return[n([...Y.keys()].map(T5.create)),ql0.create(X.map((G)=>TO8(G,Y)))]}function AO8(X){let Y=new Map;for(let G of X){let Q=Object.keys(G);for(let J of Q)if(!Y.has(J)&&G[J]!==void 0)Y.set(J,Y.size)}return Y}function TO8(X,Y){let G=Object.keys(X),Q=Array.from({length:Y.size}),J=!1,W=G.length;for(let $ of G){let K=Y.get($);if(LZ(K)){W--;continue}let H=X[$];if(LZ(H)||BO(H))J=!0;Q[K]=H}if(W<Y.size||J){let $=Al0.create();return DN.create(Q.map((K)=>LZ(K)?$:d9(K)))}return Sd.create(Q)}var Ba1=D(()=>{EJ();ce();oT();W0();LN();Ua1();HF();Na1();GI()});var za1;var Oa1=D(()=>{W0();za1=n({is(X){return X.kind==="ColumnUpdateNode"},create(X,Y){return n({kind:"ColumnUpdateNode",column:X,value:Y})}})});function Tl0(...X){if(X.length===2)return[za1.create(DQ(X[0]),d9(X[1]))];return ee(X[0])}function ee(X){let Y=F9(X)?X(FF()):X;return Object.entries(Y).filter(([G,Q])=>Q!==void 0).map(([G,Q])=>{return za1.create(T5.create(G),d9(Q))})}var o$1=D(()=>{EJ();Oa1();GI();W0();LN();OQ()});var Il0;var Da1=D(()=>{W0();Il0=n({is(X){return X.kind==="OnDuplicateKeyNode"},create(X){return n({kind:"OnDuplicateKeyNode",updates:X})}})});class wa1{insertId;numInsertedOrUpdatedRows;constructor(X,Y){this.insertId=X,this.numInsertedOrUpdatedRows=Y}}function PN(X){return Object.prototype.hasOwnProperty.call(X,"prototype")}var UF;var QI=D(()=>{UF=class UF extends Error{node;constructor(X){super("no result");this.node=X}}});var qZ;var s$1=D(()=>{W0();oe();qZ=n({is(X){return X.kind==="OnConflictNode"},create(){return n({kind:"OnConflictNode"})},cloneWith(X,Y){return n({...X,...Y})},cloneWithIndexWhere(X,Y){return n({...X,indexWhere:X.indexWhere?wQ.cloneWithOperation(X.indexWhere,"And",Y):wQ.create(Y)})},cloneWithIndexOrWhere(X,Y){return n({...X,indexWhere:X.indexWhere?wQ.cloneWithOperation(X.indexWhere,"Or",Y):wQ.create(Y)})},cloneWithUpdateWhere(X,Y){return n({...X,updateWhere:X.updateWhere?wQ.cloneWithOperation(X.updateWhere,"And",Y):wQ.create(Y)})},cloneWithUpdateOrWhere(X,Y){return n({...X,updateWhere:X.updateWhere?wQ.cloneWithOperation(X.updateWhere,"Or",Y):wQ.create(Y)})},cloneWithoutIndexWhere(X){return n({...X,indexWhere:void 0})},cloneWithoutUpdateWhere(X){return n({...X,updateWhere:void 0})}})});class qN{#X;constructor(X){this.#X=n(X)}column(X){let Y=T5.create(X);return new qN({...this.#X,onConflictNode:qZ.cloneWith(this.#X.onConflictNode,{columns:this.#X.onConflictNode.columns?n([...this.#X.onConflictNode.columns,Y]):n([Y])})})}columns(X){let Y=X.map(T5.create);return new qN({...this.#X,onConflictNode:qZ.cloneWith(this.#X.onConflictNode,{columns:this.#X.onConflictNode.columns?n([...this.#X.onConflictNode.columns,...Y]):n(Y)})})}constraint(X){return new qN({...this.#X,onConflictNode:qZ.cloneWith(this.#X.onConflictNode,{constraint:k4.create(X)})})}expression(X){return new qN({...this.#X,onConflictNode:qZ.cloneWith(this.#X.onConflictNode,{indexExpression:X.toOperationNode()})})}where(...X){return new qN({...this.#X,onConflictNode:qZ.cloneWithIndexWhere(this.#X.onConflictNode,N7(X))})}whereRef(X,Y,G){return new qN({...this.#X,onConflictNode:qZ.cloneWithIndexWhere(this.#X.onConflictNode,jG(X,Y,G))})}clearWhere(){return new qN({...this.#X,onConflictNode:qZ.cloneWithoutIndexWhere(this.#X.onConflictNode)})}doNothing(){return new Vl0({...this.#X,onConflictNode:qZ.cloneWith(this.#X.onConflictNode,{doNothing:!0})})}doUpdateSet(X){return new X11({...this.#X,onConflictNode:qZ.cloneWith(this.#X.onConflictNode,{updates:ee(X)})})}$call(X){return X(this)}}class Vl0{#X;constructor(X){this.#X=n(X)}toOperationNode(){return this.#X.onConflictNode}}class X11{#X;constructor(X){this.#X=n(X)}where(...X){return new X11({...this.#X,onConflictNode:qZ.cloneWithUpdateWhere(this.#X.onConflictNode,N7(X))})}whereRef(X,Y,G){return new X11({...this.#X,onConflictNode:qZ.cloneWithUpdateWhere(this.#X.onConflictNode,jG(X,Y,G))})}clearWhere(){return new X11({...this.#X,onConflictNode:qZ.cloneWithoutUpdateWhere(this.#X.onConflictNode)})}$call(X){return X(this)}toOperationNode(){return this.#X.onConflictNode}}var La1=D(()=>{EJ();U7();s$1();oW();o$1();W0()});var jl0;var Ea1=D(()=>{W0();jl0=n({is(X){return X.kind==="TopNode"},create(X,Y){return n({kind:"TopNode",expression:X,modifiers:Y})}})});function NF(X,Y){if(!QF(X)&&!cL(X))throw Error(`Invalid top expression: ${X}`);if(!LZ(Y)&&!IO8(Y))throw Error(`Invalid top modifiers: ${Y}`);return jl0.create(X,Y)}function IO8(X){return X==="percent"||X==="with ties"||X==="percent with ties"}var yd=D(()=>{Ea1();W0()});var JI;var Pa1=D(()=>{W0();JI=n({is(X){return X.kind==="OrActionNode"},create(X){return n({kind:"OrActionNode",action:X})}})});class c9{#X;constructor(X){this.#X=n(X)}values(X){let[Y,G]=r$1(X);return new c9({...this.#X,queryNode:xX.cloneWith(this.#X.queryNode,{columns:Y,values:G})})}columns(X){return new c9({...this.#X,queryNode:xX.cloneWith(this.#X.queryNode,{columns:n(X.map(T5.create))})})}expression(X){return new c9({...this.#X,queryNode:xX.cloneWith(this.#X.queryNode,{values:y3(X)})})}defaultValues(){return new c9({...this.#X,queryNode:xX.cloneWith(this.#X.queryNode,{defaultValues:!0})})}modifyEnd(X){return new c9({...this.#X,queryNode:A6.cloneWithEndModifier(this.#X.queryNode,X.toOperationNode())})}ignore(){return new c9({...this.#X,queryNode:xX.cloneWith(this.#X.queryNode,{orAction:JI.create("ignore")})})}orIgnore(){return new c9({...this.#X,queryNode:xX.cloneWith(this.#X.queryNode,{orAction:JI.create("ignore")})})}orAbort(){return new c9({...this.#X,queryNode:xX.cloneWith(this.#X.queryNode,{orAction:JI.create("abort")})})}orFail(){return new c9({...this.#X,queryNode:xX.cloneWith(this.#X.queryNode,{orAction:JI.create("fail")})})}orReplace(){return new c9({...this.#X,queryNode:xX.cloneWith(this.#X.queryNode,{orAction:JI.create("replace")})})}orRollback(){return new c9({...this.#X,queryNode:xX.cloneWith(this.#X.queryNode,{orAction:JI.create("rollback")})})}top(X,Y){return new c9({...this.#X,queryNode:A6.cloneWithTop(this.#X.queryNode,NF(X,Y))})}onConflict(X){return new c9({...this.#X,queryNode:xX.cloneWith(this.#X.queryNode,{onConflict:X(new qN({onConflictNode:qZ.create()})).toOperationNode()})})}onDuplicateKeyUpdate(X){return new c9({...this.#X,queryNode:xX.cloneWith(this.#X.queryNode,{onDuplicateKey:Il0.create(ee(X))})})}returning(X){return new c9({...this.#X,queryNode:A6.cloneWithReturning(this.#X.queryNode,sY(X))})}returningAll(){return new c9({...this.#X,queryNode:A6.cloneWithReturning(this.#X.queryNode,MG())})}output(X){return new c9({...this.#X,queryNode:A6.cloneWithOutput(this.#X.queryNode,sY(X))})}outputAll(X){return new c9({...this.#X,queryNode:A6.cloneWithOutput(this.#X.queryNode,MG(X))})}clearReturning(){return new c9({...this.#X,queryNode:A6.cloneWithoutReturning(this.#X.queryNode)})}$call(X){return X(this)}$if(X,Y){if(X)return Y(this);return new c9({...this.#X})}$castTo(){return new c9(this.#X)}$narrowType(){return new c9(this.#X)}$assertType(){return new c9(this.#X)}withPlugin(X){return new c9({...this.#X,executor:this.#X.executor.withPlugin(X)})}toOperationNode(){return this.#X.executor.transformQuery(this.#X.queryNode,this.#X.queryId)}compile(){return this.#X.executor.compileQuery(this.toOperationNode(),this.#X.queryId)}async execute(){let X=this.compile(),Y=await this.#X.executor.executeQuery(X),{adapter:G}=this.#X.executor,Q=X.query;if(Q.returning&&G.supportsReturning||Q.output&&G.supportsOutput)return Y.rows;return[new wa1(Y.insertId,Y.numAffectedRows??BigInt(0))]}async executeTakeFirst(){let[X]=await this.execute();return X}async executeTakeFirstOrThrow(X=UF){let Y=await this.executeTakeFirst();if(Y===void 0)throw PN(X)?new X(this.toOperationNode()):X(this.toOperationNode());return Y}async*stream(X=100){let Y=this.compile(),G=this.#X.executor.stream(Y,X);for await(let Q of G)yield*Q.rows}async explain(X,Y){return await new c9({...this.#X,queryNode:A6.cloneWithExplain(this.#X.queryNode,X,Y)}).execute()}}var qa1=D(()=>{sL();Ba1();eT();PK();o$1();W0();Da1();QI();HF();EJ();La1();s$1();yd();Pa1()});class Aa1{numDeletedRows;constructor(X){this.numDeletedRows=X}}var xd;var Y11=D(()=>{W0();xd=n({is(X){return X.kind==="LimitNode"},create(X){return n({kind:"LimitNode",limit:X})}})});class e$1{#X;constructor(X){this.#X=n(X)}where(...X){return new hX({...this.#X,queryNode:A6.cloneWithWhere(this.#X.queryNode,N7(X))})}whereRef(X,Y,G){return new hX({...this.#X,queryNode:A6.cloneWithWhere(this.#X.queryNode,jG(X,Y,G))})}clearWhere(){return new hX({...this.#X,queryNode:A6.cloneWithoutWhere(this.#X.queryNode)})}top(X,Y){return new hX({...this.#X,queryNode:A6.cloneWithTop(this.#X.queryNode,NF(X,Y))})}using(X){return new hX({...this.#X,queryNode:oL.cloneWithUsing(this.#X.queryNode,BF(X))})}innerJoin(...X){return this.#Y("InnerJoin",X)}leftJoin(...X){return this.#Y("LeftJoin",X)}rightJoin(...X){return this.#Y("RightJoin",X)}fullJoin(...X){return this.#Y("FullJoin",X)}#Y(X,Y){return new hX({...this.#X,queryNode:A6.cloneWithJoin(this.#X.queryNode,eL(X,Y))})}returning(X){return new hX({...this.#X,queryNode:A6.cloneWithReturning(this.#X.queryNode,sY(X))})}returningAll(X){return new hX({...this.#X,queryNode:A6.cloneWithReturning(this.#X.queryNode,MG(X))})}output(X){return new hX({...this.#X,queryNode:A6.cloneWithOutput(this.#X.queryNode,sY(X))})}outputAll(X){return new hX({...this.#X,queryNode:A6.cloneWithOutput(this.#X.queryNode,MG(X))})}clearReturning(){return new hX({...this.#X,queryNode:A6.cloneWithoutReturning(this.#X.queryNode)})}clearLimit(){return new hX({...this.#X,queryNode:oL.cloneWithoutLimit(this.#X.queryNode)})}orderBy(...X){return new hX({...this.#X,queryNode:A6.cloneWithOrderByItems(this.#X.queryNode,tW(X))})}clearOrderBy(){return new hX({...this.#X,queryNode:A6.cloneWithoutOrderBy(this.#X.queryNode)})}limit(X){return new hX({...this.#X,queryNode:oL.cloneWithLimit(this.#X.queryNode,xd.create(d9(X)))})}modifyEnd(X){return new hX({...this.#X,queryNode:A6.cloneWithEndModifier(this.#X.queryNode,X.toOperationNode())})}$call(X){return X(this)}$if(X,Y){if(X)return Y(this);return new hX({...this.#X})}$castTo(){return new hX(this.#X)}$narrowType(){return new hX(this.#X)}$assertType(){return new hX(this.#X)}withPlugin(X){return new hX({...this.#X,executor:this.#X.executor.withPlugin(X)})}toOperationNode(){return this.#X.executor.transformQuery(this.#X.queryNode,this.#X.queryId)}compile(){return this.#X.executor.compileQuery(this.toOperationNode(),this.#X.queryId)}async execute(){let X=this.compile(),Y=await this.#X.executor.executeQuery(X),{adapter:G}=this.#X.executor,Q=X.query;if(Q.returning&&G.supportsReturning||Q.output&&G.supportsOutput)return Y.rows;return[new Aa1(Y.numAffectedRows??BigInt(0))]}async executeTakeFirst(){let[X]=await this.execute();return X}async executeTakeFirstOrThrow(X=UF){let Y=await this.executeTakeFirst();if(Y===void 0)throw PN(X)?new X(this.toOperationNode()):X(this.toOperationNode());return Y}async*stream(X=100){let Y=this.compile(),G=this.#X.executor.stream(Y,X);for await(let Q of G)yield*Q.rows}async explain(X,Y){return await new hX({...this.#X,queryNode:A6.cloneWithExplain(this.#X.queryNode,X,Y)}).execute()}}var hX;var Ta1=D(()=>{G11();LQ();sL();PK();W0();QI();re();Y11();rT();oW();LN();yd();hX=e$1});class Ia1{numUpdatedRows;numChangedRows;constructor(X,Y){this.numUpdatedRows=X,this.numChangedRows=Y}}class hd{#X;constructor(X){this.#X=n(X)}where(...X){return new gX({...this.#X,queryNode:A6.cloneWithWhere(this.#X.queryNode,N7(X))})}whereRef(X,Y,G){return new gX({...this.#X,queryNode:A6.cloneWithWhere(this.#X.queryNode,jG(X,Y,G))})}clearWhere(){return new gX({...this.#X,queryNode:A6.cloneWithoutWhere(this.#X.queryNode)})}top(X,Y){return new gX({...this.#X,queryNode:A6.cloneWithTop(this.#X.queryNode,NF(X,Y))})}from(X){return new gX({...this.#X,queryNode:EN.cloneWithFromItems(this.#X.queryNode,BF(X))})}innerJoin(...X){return this.#Y("InnerJoin",X)}leftJoin(...X){return this.#Y("LeftJoin",X)}rightJoin(...X){return this.#Y("RightJoin",X)}fullJoin(...X){return this.#Y("FullJoin",X)}#Y(X,Y){return new gX({...this.#X,queryNode:A6.cloneWithJoin(this.#X.queryNode,eL(X,Y))})}orderBy(...X){return new gX({...this.#X,queryNode:A6.cloneWithOrderByItems(this.#X.queryNode,tW(X))})}clearOrderBy(){return new gX({...this.#X,queryNode:A6.cloneWithoutOrderBy(this.#X.queryNode)})}limit(X){return new gX({...this.#X,queryNode:EN.cloneWithLimit(this.#X.queryNode,xd.create(d9(X)))})}set(...X){return new gX({...this.#X,queryNode:EN.cloneWithUpdates(this.#X.queryNode,Tl0(...X))})}returning(X){return new gX({...this.#X,queryNode:A6.cloneWithReturning(this.#X.queryNode,sY(X))})}returningAll(X){return new gX({...this.#X,queryNode:A6.cloneWithReturning(this.#X.queryNode,MG(X))})}output(X){return new gX({...this.#X,queryNode:A6.cloneWithOutput(this.#X.queryNode,sY(X))})}outputAll(X){return new gX({...this.#X,queryNode:A6.cloneWithOutput(this.#X.queryNode,MG(X))})}modifyEnd(X){return new gX({...this.#X,queryNode:A6.cloneWithEndModifier(this.#X.queryNode,X.toOperationNode())})}clearReturning(){return new gX({...this.#X,queryNode:A6.cloneWithoutReturning(this.#X.queryNode)})}$call(X){return X(this)}$if(X,Y){if(X)return Y(this);return new gX({...this.#X})}$castTo(){return new gX(this.#X)}$narrowType(){return new gX(this.#X)}$assertType(){return new gX(this.#X)}withPlugin(X){return new gX({...this.#X,executor:this.#X.executor.withPlugin(X)})}toOperationNode(){return this.#X.executor.transformQuery(this.#X.queryNode,this.#X.queryId)}compile(){return this.#X.executor.compileQuery(this.toOperationNode(),this.#X.queryId)}async execute(){let X=this.compile(),Y=await this.#X.executor.executeQuery(X),{adapter:G}=this.#X.executor,Q=X.query;if(Q.returning&&G.supportsReturning||Q.output&&G.supportsOutput)return Y.rows;return[new Ia1(Y.numAffectedRows??BigInt(0),Y.numChangedRows)]}async executeTakeFirst(){let[X]=await this.execute();return X}async executeTakeFirstOrThrow(X=UF){let Y=await this.executeTakeFirst();if(Y===void 0)throw PN(X)?new X(this.toOperationNode()):X(this.toOperationNode());return Y}async*stream(X=100){let Y=this.compile(),G=this.#X.executor.stream(Y,X);for await(let Q of G)yield*Q.rows}async explain(X,Y){return await new gX({...this.#X,queryNode:A6.cloneWithExplain(this.#X.queryNode,X,Y)}).execute()}}var gX;var XK1=D(()=>{G11();LQ();sL();PK();vd();o$1();W0();QI();oW();LN();Y11();yd();rT();gX=hd});var Va1;var ja1=D(()=>{W0();EJ();Td();Va1=n({is(X){return X.kind==="CommonTableExpressionNameNode"},create(X,Y){return n({kind:"CommonTableExpressionNameNode",table:_3.create(X),columns:Y?n(Y.map(T5.create)):void 0})}})});var gd;var YK1=D(()=>{W0();gd=n({is(X){return X.kind==="CommonTableExpressionNode"},create(X,Y){return n({kind:"CommonTableExpressionNode",name:X,expression:Y})},cloneWith(X,Y){return n({...X,...Y})}})});class Q11{#X;constructor(X){this.#X=n(X)}materialized(){return new Q11({...this.#X,node:gd.cloneWith(this.#X.node,{materialized:!0})})}notMaterialized(){return new Q11({...this.#X,node:gd.cloneWith(this.#X.node,{materialized:!1})})}toOperationNode(){return this.#X.node}}var Ml0=D(()=>{YK1();W0()});function Ma1(X,Y){let G=Y(Cl0()).toOperationNode();if(F9(X))return X(VO8(G)).toOperationNode();return gd.create(Rl0(X),G)}function VO8(X){return(Y)=>{return new Q11({node:gd.create(Rl0(Y),X)})}}function Rl0(X){if(X.includes("(")){let Y=X.split(/[\(\)]/),G=Y[0],Q=Y[1].split(",").map((J)=>J.trim());return Va1.create(G,Q)}else return Va1.create(X)}var Sl0=D(()=>{ja1();GK1();W0();Ml0();YK1()});var J11;var Ra1=D(()=>{W0();J11=n({is(X){return X.kind==="WithNode"},create(X,Y){return n({kind:"WithNode",expressions:n([X]),...Y})},cloneWithExpression(X,Y){return n({...X,expressions:n([...X.expressions,Y])})}})});function QK1(X){let Y="";for(let G=0;G<X;++G)Y+=jO8();return Y}function jO8(){return kl0[~~(Math.random()*kl0.length)]}var kl0;var Sa1=D(()=>{kl0=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9"]});function e4(){return new vl0}class vl0{#X;get queryId(){if(this.#X===void 0)this.#X=QK1(8);return this.#X}}var AN=D(()=>{Sa1()});function z6(X){return X}class zF{nodeStack=[];#X=n({AliasNode:this.transformAlias.bind(this),ColumnNode:this.transformColumn.bind(this),IdentifierNode:this.transformIdentifier.bind(this),SchemableIdentifierNode:this.transformSchemableIdentifier.bind(this),RawNode:this.transformRaw.bind(this),ReferenceNode:this.transformReference.bind(this),SelectQueryNode:this.transformSelectQuery.bind(this),SelectionNode:this.transformSelection.bind(this),TableNode:this.transformTable.bind(this),FromNode:this.transformFrom.bind(this),SelectAllNode:this.transformSelectAll.bind(this),AndNode:this.transformAnd.bind(this),OrNode:this.transformOr.bind(this),ValueNode:this.transformValue.bind(this),ValueListNode:this.transformValueList.bind(this),PrimitiveValueListNode:this.transformPrimitiveValueList.bind(this),ParensNode:this.transformParens.bind(this),JoinNode:this.transformJoin.bind(this),OperatorNode:this.transformOperator.bind(this),WhereNode:this.transformWhere.bind(this),InsertQueryNode:this.transformInsertQuery.bind(this),DeleteQueryNode:this.transformDeleteQuery.bind(this),ReturningNode:this.transformReturning.bind(this),CreateTableNode:this.transformCreateTable.bind(this),AddColumnNode:this.transformAddColumn.bind(this),ColumnDefinitionNode:this.transformColumnDefinition.bind(this),DropTableNode:this.transformDropTable.bind(this),DataTypeNode:this.transformDataType.bind(this),OrderByNode:this.transformOrderBy.bind(this),OrderByItemNode:this.transformOrderByItem.bind(this),GroupByNode:this.transformGroupBy.bind(this),GroupByItemNode:this.transformGroupByItem.bind(this),UpdateQueryNode:this.transformUpdateQuery.bind(this),ColumnUpdateNode:this.transformColumnUpdate.bind(this),LimitNode:this.transformLimit.bind(this),OffsetNode:this.transformOffset.bind(this),OnConflictNode:this.transformOnConflict.bind(this),OnDuplicateKeyNode:this.transformOnDuplicateKey.bind(this),CreateIndexNode:this.transformCreateIndex.bind(this),DropIndexNode:this.transformDropIndex.bind(this),ListNode:this.transformList.bind(this),PrimaryKeyConstraintNode:this.transformPrimaryKeyConstraint.bind(this),UniqueConstraintNode:this.transformUniqueConstraint.bind(this),ReferencesNode:this.transformReferences.bind(this),CheckConstraintNode:this.transformCheckConstraint.bind(this),WithNode:this.transformWith.bind(this),CommonTableExpressionNode:this.transformCommonTableExpression.bind(this),CommonTableExpressionNameNode:this.transformCommonTableExpressionName.bind(this),HavingNode:this.transformHaving.bind(this),CreateSchemaNode:this.transformCreateSchema.bind(this),DropSchemaNode:this.transformDropSchema.bind(this),AlterTableNode:this.transformAlterTable.bind(this),DropColumnNode:this.transformDropColumn.bind(this),RenameColumnNode:this.transformRenameColumn.bind(this),AlterColumnNode:this.transformAlterColumn.bind(this),ModifyColumnNode:this.transformModifyColumn.bind(this),AddConstraintNode:this.transformAddConstraint.bind(this),DropConstraintNode:this.transformDropConstraint.bind(this),RenameConstraintNode:this.transformRenameConstraint.bind(this),ForeignKeyConstraintNode:this.transformForeignKeyConstraint.bind(this),CreateViewNode:this.transformCreateView.bind(this),RefreshMaterializedViewNode:this.transformRefreshMaterializedView.bind(this),DropViewNode:this.transformDropView.bind(this),GeneratedNode:this.transformGenerated.bind(this),DefaultValueNode:this.transformDefaultValue.bind(this),OnNode:this.transformOn.bind(this),ValuesNode:this.transformValues.bind(this),SelectModifierNode:this.transformSelectModifier.bind(this),CreateTypeNode:this.transformCreateType.bind(this),DropTypeNode:this.transformDropType.bind(this),ExplainNode:this.transformExplain.bind(this),DefaultInsertValueNode:this.transformDefaultInsertValue.bind(this),AggregateFunctionNode:this.transformAggregateFunction.bind(this),OverNode:this.transformOver.bind(this),PartitionByNode:this.transformPartitionBy.bind(this),PartitionByItemNode:this.transformPartitionByItem.bind(this),SetOperationNode:this.transformSetOperation.bind(this),BinaryOperationNode:this.transformBinaryOperation.bind(this),UnaryOperationNode:this.transformUnaryOperation.bind(this),UsingNode:this.transformUsing.bind(this),FunctionNode:this.transformFunction.bind(this),CaseNode:this.transformCase.bind(this),WhenNode:this.transformWhen.bind(this),JSONReferenceNode:this.transformJSONReference.bind(this),JSONPathNode:this.transformJSONPath.bind(this),JSONPathLegNode:this.transformJSONPathLeg.bind(this),JSONOperatorChainNode:this.transformJSONOperatorChain.bind(this),TupleNode:this.transformTuple.bind(this),MergeQueryNode:this.transformMergeQuery.bind(this),MatchedNode:this.transformMatched.bind(this),AddIndexNode:this.transformAddIndex.bind(this),CastNode:this.transformCast.bind(this),FetchNode:this.transformFetch.bind(this),TopNode:this.transformTop.bind(this),OutputNode:this.transformOutput.bind(this),OrActionNode:this.transformOrAction.bind(this),CollateNode:this.transformCollate.bind(this)});transformNode(X,Y){if(!X)return X;this.nodeStack.push(X);let G=this.transformNodeImpl(X,Y);return this.nodeStack.pop(),n(G)}transformNodeImpl(X,Y){return this.#X[X.kind](X,Y)}transformNodeList(X,Y){if(!X)return X;return n(X.map((G)=>this.transformNode(G,Y)))}transformSelectQuery(X,Y){return z6({kind:"SelectQueryNode",from:this.transformNode(X.from,Y),selections:this.transformNodeList(X.selections,Y),distinctOn:this.transformNodeList(X.distinctOn,Y),joins:this.transformNodeList(X.joins,Y),groupBy:this.transformNode(X.groupBy,Y),orderBy:this.transformNode(X.orderBy,Y),where:this.transformNode(X.where,Y),frontModifiers:this.transformNodeList(X.frontModifiers,Y),endModifiers:this.transformNodeList(X.endModifiers,Y),limit:this.transformNode(X.limit,Y),offset:this.transformNode(X.offset,Y),with:this.transformNode(X.with,Y),having:this.transformNode(X.having,Y),explain:this.transformNode(X.explain,Y),setOperations:this.transformNodeList(X.setOperations,Y),fetch:this.transformNode(X.fetch,Y),top:this.transformNode(X.top,Y)})}transformSelection(X,Y){return z6({kind:"SelectionNode",selection:this.transformNode(X.selection,Y)})}transformColumn(X,Y){return z6({kind:"ColumnNode",column:this.transformNode(X.column,Y)})}transformAlias(X,Y){return z6({kind:"AliasNode",node:this.transformNode(X.node,Y),alias:this.transformNode(X.alias,Y)})}transformTable(X,Y){return z6({kind:"TableNode",table:this.transformNode(X.table,Y)})}transformFrom(X,Y){return z6({kind:"FromNode",froms:this.transformNodeList(X.froms,Y)})}transformReference(X,Y){return z6({kind:"ReferenceNode",column:this.transformNode(X.column,Y),table:this.transformNode(X.table,Y)})}transformAnd(X,Y){return z6({kind:"AndNode",left:this.transformNode(X.left,Y),right:this.transformNode(X.right,Y)})}transformOr(X,Y){return z6({kind:"OrNode",left:this.transformNode(X.left,Y),right:this.transformNode(X.right,Y)})}transformValueList(X,Y){return z6({kind:"ValueListNode",values:this.transformNodeList(X.values,Y)})}transformParens(X,Y){return z6({kind:"ParensNode",node:this.transformNode(X.node,Y)})}transformJoin(X,Y){return z6({kind:"JoinNode",joinType:X.joinType,table:this.transformNode(X.table,Y),on:this.transformNode(X.on,Y)})}transformRaw(X,Y){return z6({kind:"RawNode",sqlFragments:n([...X.sqlFragments]),parameters:this.transformNodeList(X.parameters,Y)})}transformWhere(X,Y){return z6({kind:"WhereNode",where:this.transformNode(X.where,Y)})}transformInsertQuery(X,Y){return z6({kind:"InsertQueryNode",into:this.transformNode(X.into,Y),columns:this.transformNodeList(X.columns,Y),values:this.transformNode(X.values,Y),returning:this.transformNode(X.returning,Y),onConflict:this.transformNode(X.onConflict,Y),onDuplicateKey:this.transformNode(X.onDuplicateKey,Y),endModifiers:this.transformNodeList(X.endModifiers,Y),with:this.transformNode(X.with,Y),ignore:X.ignore,orAction:this.transformNode(X.orAction,Y),replace:X.replace,explain:this.transformNode(X.explain,Y),defaultValues:X.defaultValues,top:this.transformNode(X.top,Y),output:this.transformNode(X.output,Y)})}transformValues(X,Y){return z6({kind:"ValuesNode",values:this.transformNodeList(X.values,Y)})}transformDeleteQuery(X,Y){return z6({kind:"DeleteQueryNode",from:this.transformNode(X.from,Y),using:this.transformNode(X.using,Y),joins:this.transformNodeList(X.joins,Y),where:this.transformNode(X.where,Y),returning:this.transformNode(X.returning,Y),endModifiers:this.transformNodeList(X.endModifiers,Y),with:this.transformNode(X.with,Y),orderBy:this.transformNode(X.orderBy,Y),limit:this.transformNode(X.limit,Y),explain:this.transformNode(X.explain,Y),top:this.transformNode(X.top,Y),output:this.transformNode(X.output,Y)})}transformReturning(X,Y){return z6({kind:"ReturningNode",selections:this.transformNodeList(X.selections,Y)})}transformCreateTable(X,Y){return z6({kind:"CreateTableNode",table:this.transformNode(X.table,Y),columns:this.transformNodeList(X.columns,Y),constraints:this.transformNodeList(X.constraints,Y),temporary:X.temporary,ifNotExists:X.ifNotExists,onCommit:X.onCommit,frontModifiers:this.transformNodeList(X.frontModifiers,Y),endModifiers:this.transformNodeList(X.endModifiers,Y),selectQuery:this.transformNode(X.selectQuery,Y)})}transformColumnDefinition(X,Y){return z6({kind:"ColumnDefinitionNode",column:this.transformNode(X.column,Y),dataType:this.transformNode(X.dataType,Y),references:this.transformNode(X.references,Y),primaryKey:X.primaryKey,autoIncrement:X.autoIncrement,unique:X.unique,notNull:X.notNull,unsigned:X.unsigned,defaultTo:this.transformNode(X.defaultTo,Y),check:this.transformNode(X.check,Y),generated:this.transformNode(X.generated,Y),frontModifiers:this.transformNodeList(X.frontModifiers,Y),endModifiers:this.transformNodeList(X.endModifiers,Y),nullsNotDistinct:X.nullsNotDistinct,identity:X.identity,ifNotExists:X.ifNotExists})}transformAddColumn(X,Y){return z6({kind:"AddColumnNode",column:this.transformNode(X.column,Y)})}transformDropTable(X,Y){return z6({kind:"DropTableNode",table:this.transformNode(X.table,Y),ifExists:X.ifExists,cascade:X.cascade})}transformOrderBy(X,Y){return z6({kind:"OrderByNode",items:this.transformNodeList(X.items,Y)})}transformOrderByItem(X,Y){return z6({kind:"OrderByItemNode",orderBy:this.transformNode(X.orderBy,Y),direction:this.transformNode(X.direction,Y),collation:this.transformNode(X.collation,Y),nulls:X.nulls})}transformGroupBy(X,Y){return z6({kind:"GroupByNode",items:this.transformNodeList(X.items,Y)})}transformGroupByItem(X,Y){return z6({kind:"GroupByItemNode",groupBy:this.transformNode(X.groupBy,Y)})}transformUpdateQuery(X,Y){return z6({kind:"UpdateQueryNode",table:this.transformNode(X.table,Y),from:this.transformNode(X.from,Y),joins:this.transformNodeList(X.joins,Y),where:this.transformNode(X.where,Y),updates:this.transformNodeList(X.updates,Y),returning:this.transformNode(X.returning,Y),endModifiers:this.transformNodeList(X.endModifiers,Y),with:this.transformNode(X.with,Y),explain:this.transformNode(X.explain,Y),limit:this.transformNode(X.limit,Y),top:this.transformNode(X.top,Y),output:this.transformNode(X.output,Y),orderBy:this.transformNode(X.orderBy,Y)})}transformColumnUpdate(X,Y){return z6({kind:"ColumnUpdateNode",column:this.transformNode(X.column,Y),value:this.transformNode(X.value,Y)})}transformLimit(X,Y){return z6({kind:"LimitNode",limit:this.transformNode(X.limit,Y)})}transformOffset(X,Y){return z6({kind:"OffsetNode",offset:this.transformNode(X.offset,Y)})}transformOnConflict(X,Y){return z6({kind:"OnConflictNode",columns:this.transformNodeList(X.columns,Y),constraint:this.transformNode(X.constraint,Y),indexExpression:this.transformNode(X.indexExpression,Y),indexWhere:this.transformNode(X.indexWhere,Y),updates:this.transformNodeList(X.updates,Y),updateWhere:this.transformNode(X.updateWhere,Y),doNothing:X.doNothing})}transformOnDuplicateKey(X,Y){return z6({kind:"OnDuplicateKeyNode",updates:this.transformNodeList(X.updates,Y)})}transformCreateIndex(X,Y){return z6({kind:"CreateIndexNode",name:this.transformNode(X.name,Y),table:this.transformNode(X.table,Y),columns:this.transformNodeList(X.columns,Y),unique:X.unique,using:this.transformNode(X.using,Y),ifNotExists:X.ifNotExists,where:this.transformNode(X.where,Y),nullsNotDistinct:X.nullsNotDistinct})}transformList(X,Y){return z6({kind:"ListNode",items:this.transformNodeList(X.items,Y)})}transformDropIndex(X,Y){return z6({kind:"DropIndexNode",name:this.transformNode(X.name,Y),table:this.transformNode(X.table,Y),ifExists:X.ifExists,cascade:X.cascade})}transformPrimaryKeyConstraint(X,Y){return z6({kind:"PrimaryKeyConstraintNode",columns:this.transformNodeList(X.columns,Y),name:this.transformNode(X.name,Y),deferrable:X.deferrable,initiallyDeferred:X.initiallyDeferred})}transformUniqueConstraint(X,Y){return z6({kind:"UniqueConstraintNode",columns:this.transformNodeList(X.columns,Y),name:this.transformNode(X.name,Y),nullsNotDistinct:X.nullsNotDistinct,deferrable:X.deferrable,initiallyDeferred:X.initiallyDeferred})}transformForeignKeyConstraint(X,Y){return z6({kind:"ForeignKeyConstraintNode",columns:this.transformNodeList(X.columns,Y),references:this.transformNode(X.references,Y),name:this.transformNode(X.name,Y),onDelete:X.onDelete,onUpdate:X.onUpdate,deferrable:X.deferrable,initiallyDeferred:X.initiallyDeferred})}transformSetOperation(X,Y){return z6({kind:"SetOperationNode",operator:X.operator,expression:this.transformNode(X.expression,Y),all:X.all})}transformReferences(X,Y){return z6({kind:"ReferencesNode",table:this.transformNode(X.table,Y),columns:this.transformNodeList(X.columns,Y),onDelete:X.onDelete,onUpdate:X.onUpdate})}transformCheckConstraint(X,Y){return z6({kind:"CheckConstraintNode",expression:this.transformNode(X.expression,Y),name:this.transformNode(X.name,Y)})}transformWith(X,Y){return z6({kind:"WithNode",expressions:this.transformNodeList(X.expressions,Y),recursive:X.recursive})}transformCommonTableExpression(X,Y){return z6({kind:"CommonTableExpressionNode",name:this.transformNode(X.name,Y),materialized:X.materialized,expression:this.transformNode(X.expression,Y)})}transformCommonTableExpressionName(X,Y){return z6({kind:"CommonTableExpressionNameNode",table:this.transformNode(X.table,Y),columns:this.transformNodeList(X.columns,Y)})}transformHaving(X,Y){return z6({kind:"HavingNode",having:this.transformNode(X.having,Y)})}transformCreateSchema(X,Y){return z6({kind:"CreateSchemaNode",schema:this.transformNode(X.schema,Y),ifNotExists:X.ifNotExists})}transformDropSchema(X,Y){return z6({kind:"DropSchemaNode",schema:this.transformNode(X.schema,Y),ifExists:X.ifExists,cascade:X.cascade})}transformAlterTable(X,Y){return z6({kind:"AlterTableNode",table:this.transformNode(X.table,Y),renameTo:this.transformNode(X.renameTo,Y),setSchema:this.transformNode(X.setSchema,Y),columnAlterations:this.transformNodeList(X.columnAlterations,Y),addConstraint:this.transformNode(X.addConstraint,Y),dropConstraint:this.transformNode(X.dropConstraint,Y),renameConstraint:this.transformNode(X.renameConstraint,Y),addIndex:this.transformNode(X.addIndex,Y),dropIndex:this.transformNode(X.dropIndex,Y)})}transformDropColumn(X,Y){return z6({kind:"DropColumnNode",column:this.transformNode(X.column,Y)})}transformRenameColumn(X,Y){return z6({kind:"RenameColumnNode",column:this.transformNode(X.column,Y),renameTo:this.transformNode(X.renameTo,Y)})}transformAlterColumn(X,Y){return z6({kind:"AlterColumnNode",column:this.transformNode(X.column,Y),dataType:this.transformNode(X.dataType,Y),dataTypeExpression:this.transformNode(X.dataTypeExpression,Y),setDefault:this.transformNode(X.setDefault,Y),dropDefault:X.dropDefault,setNotNull:X.setNotNull,dropNotNull:X.dropNotNull})}transformModifyColumn(X,Y){return z6({kind:"ModifyColumnNode",column:this.transformNode(X.column,Y)})}transformAddConstraint(X,Y){return z6({kind:"AddConstraintNode",constraint:this.transformNode(X.constraint,Y)})}transformDropConstraint(X,Y){return z6({kind:"DropConstraintNode",constraintName:this.transformNode(X.constraintName,Y),ifExists:X.ifExists,modifier:X.modifier})}transformRenameConstraint(X,Y){return z6({kind:"RenameConstraintNode",oldName:this.transformNode(X.oldName,Y),newName:this.transformNode(X.newName,Y)})}transformCreateView(X,Y){return z6({kind:"CreateViewNode",name:this.transformNode(X.name,Y),temporary:X.temporary,orReplace:X.orReplace,ifNotExists:X.ifNotExists,materialized:X.materialized,columns:this.transformNodeList(X.columns,Y),as:this.transformNode(X.as,Y)})}transformRefreshMaterializedView(X,Y){return z6({kind:"RefreshMaterializedViewNode",name:this.transformNode(X.name,Y),concurrently:X.concurrently,withNoData:X.withNoData})}transformDropView(X,Y){return z6({kind:"DropViewNode",name:this.transformNode(X.name,Y),ifExists:X.ifExists,materialized:X.materialized,cascade:X.cascade})}transformGenerated(X,Y){return z6({kind:"GeneratedNode",byDefault:X.byDefault,always:X.always,identity:X.identity,stored:X.stored,expression:this.transformNode(X.expression,Y)})}transformDefaultValue(X,Y){return z6({kind:"DefaultValueNode",defaultValue:this.transformNode(X.defaultValue,Y)})}transformOn(X,Y){return z6({kind:"OnNode",on:this.transformNode(X.on,Y)})}transformSelectModifier(X,Y){return z6({kind:"SelectModifierNode",modifier:X.modifier,rawModifier:this.transformNode(X.rawModifier,Y),of:this.transformNodeList(X.of,Y)})}transformCreateType(X,Y){return z6({kind:"CreateTypeNode",name:this.transformNode(X.name,Y),enum:this.transformNode(X.enum,Y)})}transformDropType(X,Y){return z6({kind:"DropTypeNode",name:this.transformNode(X.name,Y),ifExists:X.ifExists})}transformExplain(X,Y){return z6({kind:"ExplainNode",format:X.format,options:this.transformNode(X.options,Y)})}transformSchemableIdentifier(X,Y){return z6({kind:"SchemableIdentifierNode",schema:this.transformNode(X.schema,Y),identifier:this.transformNode(X.identifier,Y)})}transformAggregateFunction(X,Y){return z6({kind:"AggregateFunctionNode",func:X.func,aggregated:this.transformNodeList(X.aggregated,Y),distinct:X.distinct,orderBy:this.transformNode(X.orderBy,Y),withinGroup:this.transformNode(X.withinGroup,Y),filter:this.transformNode(X.filter,Y),over:this.transformNode(X.over,Y)})}transformOver(X,Y){return z6({kind:"OverNode",orderBy:this.transformNode(X.orderBy,Y),partitionBy:this.transformNode(X.partitionBy,Y)})}transformPartitionBy(X,Y){return z6({kind:"PartitionByNode",items:this.transformNodeList(X.items,Y)})}transformPartitionByItem(X,Y){return z6({kind:"PartitionByItemNode",partitionBy:this.transformNode(X.partitionBy,Y)})}transformBinaryOperation(X,Y){return z6({kind:"BinaryOperationNode",leftOperand:this.transformNode(X.leftOperand,Y),operator:this.transformNode(X.operator,Y),rightOperand:this.transformNode(X.rightOperand,Y)})}transformUnaryOperation(X,Y){return z6({kind:"UnaryOperationNode",operator:this.transformNode(X.operator,Y),operand:this.transformNode(X.operand,Y)})}transformUsing(X,Y){return z6({kind:"UsingNode",tables:this.transformNodeList(X.tables,Y)})}transformFunction(X,Y){return z6({kind:"FunctionNode",func:X.func,arguments:this.transformNodeList(X.arguments,Y)})}transformCase(X,Y){return z6({kind:"CaseNode",value:this.transformNode(X.value,Y),when:this.transformNodeList(X.when,Y),else:this.transformNode(X.else,Y),isStatement:X.isStatement})}transformWhen(X,Y){return z6({kind:"WhenNode",condition:this.transformNode(X.condition,Y),result:this.transformNode(X.result,Y)})}transformJSONReference(X,Y){return z6({kind:"JSONReferenceNode",reference:this.transformNode(X.reference,Y),traversal:this.transformNode(X.traversal,Y)})}transformJSONPath(X,Y){return z6({kind:"JSONPathNode",inOperator:this.transformNode(X.inOperator,Y),pathLegs:this.transformNodeList(X.pathLegs,Y)})}transformJSONPathLeg(X,Y){return z6({kind:"JSONPathLegNode",type:X.type,value:X.value})}transformJSONOperatorChain(X,Y){return z6({kind:"JSONOperatorChainNode",operator:this.transformNode(X.operator,Y),values:this.transformNodeList(X.values,Y)})}transformTuple(X,Y){return z6({kind:"TupleNode",values:this.transformNodeList(X.values,Y)})}transformMergeQuery(X,Y){return z6({kind:"MergeQueryNode",into:this.transformNode(X.into,Y),using:this.transformNode(X.using,Y),whens:this.transformNodeList(X.whens,Y),with:this.transformNode(X.with,Y),top:this.transformNode(X.top,Y),endModifiers:this.transformNodeList(X.endModifiers,Y),output:this.transformNode(X.output,Y),returning:this.transformNode(X.returning,Y)})}transformMatched(X,Y){return z6({kind:"MatchedNode",not:X.not,bySource:X.bySource})}transformAddIndex(X,Y){return z6({kind:"AddIndexNode",name:this.transformNode(X.name,Y),columns:this.transformNodeList(X.columns,Y),unique:X.unique,using:this.transformNode(X.using,Y),ifNotExists:X.ifNotExists})}transformCast(X,Y){return z6({kind:"CastNode",expression:this.transformNode(X.expression,Y),dataType:this.transformNode(X.dataType,Y)})}transformFetch(X,Y){return z6({kind:"FetchNode",rowCount:this.transformNode(X.rowCount,Y),modifier:X.modifier})}transformTop(X,Y){return z6({kind:"TopNode",expression:X.expression,modifiers:X.modifiers})}transformOutput(X,Y){return z6({kind:"OutputNode",selections:this.transformNodeList(X.selections,Y)})}transformDataType(X,Y){return X}transformSelectAll(X,Y){return X}transformIdentifier(X,Y){return X}transformValue(X,Y){return X}transformPrimitiveValueList(X,Y){return X}transformOperator(X,Y){return X}transformDefaultInsertValue(X,Y){return X}transformOrAction(X,Y){return X}transformCollate(X,Y){return X}}var ZI=D(()=>{W0()});var MO8,RO8,Ca1;var _l0=D(()=>{ZF();U7();Id();n$1();ZI();NO();Td();a$1();W0();MO8=n({AlterTableNode:!0,CreateIndexNode:!0,CreateSchemaNode:!0,CreateTableNode:!0,CreateTypeNode:!0,CreateViewNode:!0,RefreshMaterializedViewNode:!0,DeleteQueryNode:!0,DropIndexNode:!0,DropSchemaNode:!0,DropTableNode:!0,DropTypeNode:!0,DropViewNode:!0,InsertQueryNode:!0,RawNode:!0,SelectQueryNode:!0,UpdateQueryNode:!0,MergeQueryNode:!0}),RO8={json_agg:!0,to_json:!0};Ca1=class Ca1 extends zF{#X;#Y=new Set;#G=new Set;constructor(X){super();this.#X=X}transformNodeImpl(X,Y){if(!this.#J(X))return super.transformNodeImpl(X,Y);let G=this.#$(X);for(let W of G)this.#G.add(W);let Q=this.#Z(X);for(let W of Q)this.#Y.add(W);let J=super.transformNodeImpl(X,Y);for(let W of Q)this.#Y.delete(W);for(let W of G)this.#G.delete(W);return J}transformSchemableIdentifier(X,Y){let G=super.transformSchemableIdentifier(X,Y);if(G.schema||!this.#Y.has(X.identifier.name))return G;return{...G,schema:k4.create(this.#X)}}transformReferences(X,Y){let G=super.transformReferences(X,Y);if(G.table.table.schema)return G;return{...G,table:_3.createWithSchema(this.#X,G.table.table.identifier.name)}}transformAggregateFunction(X,Y){return{...super.transformAggregateFunction({...X,aggregated:[]},Y),aggregated:this.#Q(X,Y,"aggregated")}}transformFunction(X,Y){return{...super.transformFunction({...X,arguments:[]},Y),arguments:this.#Q(X,Y,"arguments")}}transformSelectModifier(X,Y){return{...super.transformSelectModifier({...X,of:void 0},Y),of:X.of?.map((G)=>_3.is(G)&&!G.table.schema?{...G,table:this.transformIdentifier(G.table.identifier,Y)}:this.transformNode(G,Y))}}#Q(X,Y,G){return RO8[X.func]?X[G].map((Q)=>!_3.is(Q)||Q.table.schema?this.transformNode(Q,Y):{...Q,table:this.transformIdentifier(Q.table.identifier,Y)}):this.transformNodeList(X[G],Y)}#J(X){return X.kind in MO8}#Z(X){let Y=new Set;if("name"in X&&X.name&&LJ.is(X.name))this.#K(X.name,Y);if("from"in X&&X.from)for(let G of X.from.froms)this.#W(G,Y);if("into"in X&&X.into)this.#W(X.into,Y);if("table"in X&&X.table)this.#W(X.table,Y);if("joins"in X&&X.joins)for(let G of X.joins)this.#W(G.table,Y);if("using"in X&&X.using)if($F.is(X.using))this.#W(X.using.table,Y);else this.#W(X.using,Y);return Y}#$(X){let Y=new Set;if("with"in X&&X.with)this.#H(X.with,Y);return Y}#W(X,Y){if(_3.is(X))return this.#K(X.table,Y);if(VG.is(X)&&_3.is(X.node))return this.#K(X.node.table,Y);if(p$1.is(X)){for(let G of X.items)this.#W(G,Y);return}if(te.is(X)){for(let G of X.tables)this.#W(G,Y);return}}#K(X,Y){let G=X.identifier.name;if(!this.#Y.has(G)&&!this.#G.has(G))Y.add(G)}#H(X,Y){for(let G of X.expressions){let Q=G.name.table.table.identifier.name;if(!this.#G.has(Q))Y.add(Q)}}}});class eW{#X;constructor(X){this.#X=new Ca1(X)}transformQuery(X){return this.#X.transformNode(X.node,X.queryId)}async transformResult(X){return X.result}}var WI=D(()=>{_l0()});var fl0;var ka1=D(()=>{W0();fl0=n({is(X){return X.kind==="MatchedNode"},create(X,Y=!1){return n({kind:"MatchedNode",not:X,bySource:Y})}})});function va1(X,Y,G){return qK.create(kd([fl0.create(!X.isMatched,X.bySource),...Y&&Y.length>0?[Y.length===3&&G?jG(Y[0],Y[1],Y[2]):N7(Y)]:[]],"and",!1))}function ud(X){if(H9(X))return f5.create([X],[]);if(R7(X))return X.toOperationNode();return X}var bl0=D(()=>{ka1();f3();EK();XI();W0();oW()});class XE{#X;#Y;#G;constructor(){this.#X=new Promise((X,Y)=>{this.#G=Y,this.#Y=X})}get promise(){return this.#X}resolve=(X)=>{if(this.#Y)this.#Y(X)};reject=(X)=>{if(this.#G)this.#G(X)}}async function JK1(X){let Y=new XE,G=new XE;return X.provideConnection(async(Q)=>{return Y.resolve(Q),await G.promise}).catch((Q)=>Y.reject(Q)),n({connection:await Y.promise,release:G.resolve})}var _a1=D(()=>{W0()});class Z11{#X;constructor(X=SO8){this.#X=X}get plugins(){return this.#X}transformQuery(X,Y){for(let G of this.#X){let Q=G.transformQuery({node:X,queryId:Y});if(Q.kind===X.kind)X=Q;else throw Error(["KyselyPlugin.transformQuery must return a node","of the same kind that was given to it.",`The plugin was given a ${X.kind}`,`but it returned a ${Q.kind}`].join(" "))}return X}async executeQuery(X){return await this.provideConnection(async(Y)=>{let G=await Y.executeQuery(X);if("numUpdatedOrDeletedRows"in G)ON("kysely:warning: outdated driver/plugin detected! `QueryResult.numUpdatedOrDeletedRows` has been replaced with `QueryResult.numAffectedRows`.");return await this.#Y(G,X.queryId)})}async*stream(X,Y){let{connection:G,release:Q}=await JK1(this);try{for await(let J of G.streamQuery(X,Y))yield await this.#Y(J,X.queryId)}finally{Q()}}async#Y(X,Y){for(let G of this.#X)X=await G.transformResult({result:X,queryId:Y});return X}}var SO8;var fa1=D(()=>{W0();_a1();me();SO8=n([])});var ld,YE;var md=D(()=>{fa1();ld=class ld extends Z11{get adapter(){throw Error("this query cannot be compiled to SQL")}compileQuery(){throw Error("this query cannot be compiled to SQL")}provideConnection(){throw Error("this query cannot be executed")}withConnectionProvider(){throw Error("this query cannot have a connection provider")}withPlugin(X){return new ld([...this.plugins,X])}withPlugins(X){return new ld([...this.plugins,...X])}withPluginAtFront(X){return new ld([X,...this.plugins])}withoutPlugins(){return new ld([])}};YE=new ld});class ba1{numChangedRows;constructor(X){this.numChangedRows=X}}class DO{#X;constructor(X){this.#X=n(X)}modifyEnd(X){return new DO({...this.#X,queryNode:A6.cloneWithEndModifier(this.#X.queryNode,X.toOperationNode())})}top(X,Y){return new DO({...this.#X,queryNode:A6.cloneWithTop(this.#X.queryNode,NF(X,Y))})}using(...X){return new x3({...this.#X,queryNode:sW.cloneWithUsing(this.#X.queryNode,eL("Using",X))})}returning(X){return new DO({...this.#X,queryNode:A6.cloneWithReturning(this.#X.queryNode,sY(X))})}returningAll(X){return new DO({...this.#X,queryNode:A6.cloneWithReturning(this.#X.queryNode,MG(X))})}output(X){return new DO({...this.#X,queryNode:A6.cloneWithOutput(this.#X.queryNode,sY(X))})}outputAll(X){return new DO({...this.#X,queryNode:A6.cloneWithOutput(this.#X.queryNode,MG(X))})}}class x3{#X;constructor(X){this.#X=n(X)}modifyEnd(X){return new x3({...this.#X,queryNode:A6.cloneWithEndModifier(this.#X.queryNode,X.toOperationNode())})}top(X,Y){return new x3({...this.#X,queryNode:A6.cloneWithTop(this.#X.queryNode,NF(X,Y))})}whenMatched(){return this.#Y([])}whenMatchedAnd(...X){return this.#Y(X)}whenMatchedAndRef(X,Y,G){return this.#Y([X,Y,G],!0)}#Y(X,Y){return new ya1({...this.#X,queryNode:sW.cloneWithWhen(this.#X.queryNode,va1({isMatched:!0},X,Y))})}whenNotMatched(){return this.#G([])}whenNotMatchedAnd(...X){return this.#G(X)}whenNotMatchedAndRef(X,Y,G){return this.#G([X,Y,G],!0)}whenNotMatchedBySource(){return this.#G([],!1,!0)}whenNotMatchedBySourceAnd(...X){return this.#G(X,!1,!0)}whenNotMatchedBySourceAndRef(X,Y,G){return this.#G([X,Y,G],!0,!0)}returning(X){return new x3({...this.#X,queryNode:A6.cloneWithReturning(this.#X.queryNode,sY(X))})}returningAll(X){return new x3({...this.#X,queryNode:A6.cloneWithReturning(this.#X.queryNode,MG(X))})}output(X){return new x3({...this.#X,queryNode:A6.cloneWithOutput(this.#X.queryNode,sY(X))})}outputAll(X){return new x3({...this.#X,queryNode:A6.cloneWithOutput(this.#X.queryNode,MG(X))})}#G(X,Y=!1,G=!1){let Q={...this.#X,queryNode:sW.cloneWithWhen(this.#X.queryNode,va1({isMatched:!1,bySource:G},X,Y))};return new(G?ya1:yl0)(Q)}$call(X){return X(this)}$if(X,Y){if(X)return Y(this);return new x3({...this.#X})}toOperationNode(){return this.#X.executor.transformQuery(this.#X.queryNode,this.#X.queryId)}compile(){return this.#X.executor.compileQuery(this.toOperationNode(),this.#X.queryId)}async execute(){let X=this.compile(),Y=await this.#X.executor.executeQuery(X),{adapter:G}=this.#X.executor,Q=X.query;if(Q.returning&&G.supportsReturning||Q.output&&G.supportsOutput)return Y.rows;return[new ba1(Y.numAffectedRows)]}async executeTakeFirst(){let[X]=await this.execute();return X}async executeTakeFirstOrThrow(X=UF){let Y=await this.executeTakeFirst();if(Y===void 0)throw PN(X)?new X(this.toOperationNode()):X(this.toOperationNode());return Y}}class ya1{#X;constructor(X){this.#X=n(X)}thenDelete(){return new x3({...this.#X,queryNode:sW.cloneWithThen(this.#X.queryNode,ud("delete"))})}thenDoNothing(){return new x3({...this.#X,queryNode:sW.cloneWithThen(this.#X.queryNode,ud("do nothing"))})}thenUpdate(X){return new x3({...this.#X,queryNode:sW.cloneWithThen(this.#X.queryNode,ud(X(new hd({queryId:this.#X.queryId,executor:YE,queryNode:EN.createWithoutTable()}))))})}thenUpdateSet(...X){return this.thenUpdate((Y)=>Y.set(...X))}}class yl0{#X;constructor(X){this.#X=n(X)}thenDoNothing(){return new x3({...this.#X,queryNode:sW.cloneWithThen(this.#X.queryNode,ud("do nothing"))})}thenInsertValues(X){let[Y,G]=r$1(X);return new x3({...this.#X,queryNode:sW.cloneWithThen(this.#X.queryNode,ud(xX.cloneWith(xX.createWithoutInto(),{columns:Y,values:G})))})}}var xa1=D(()=>{eT();se();PK();vd();Ba1();G11();bl0();sL();yd();md();W0();QI();XK1()});class TN{#X;constructor(X){this.#X=n(X)}selectFrom(X){return W11({queryId:e4(),executor:this.#X.executor,queryNode:U9.createFrom(BF(X),this.#X.withNode)})}selectNoFrom(X){return W11({queryId:e4(),executor:this.#X.executor,queryNode:U9.cloneWithSelections(U9.create(this.#X.withNode),sY(X))})}insertInto(X){return new c9({queryId:e4(),executor:this.#X.executor,queryNode:xX.create(b5(X),this.#X.withNode)})}replaceInto(X){return new c9({queryId:e4(),executor:this.#X.executor,queryNode:xX.create(b5(X),this.#X.withNode,!0)})}deleteFrom(X){return new e$1({queryId:e4(),executor:this.#X.executor,queryNode:oL.create(BF(X),this.#X.withNode)})}updateTable(X){return new hd({queryId:e4(),executor:this.#X.executor,queryNode:EN.create(BF(X),this.#X.withNode)})}mergeInto(X){return new DO({queryId:e4(),executor:this.#X.executor,queryNode:sW.create(ha1(X),this.#X.withNode)})}with(X,Y){let G=Ma1(X,Y);return new TN({...this.#X,withNode:this.#X.withNode?J11.cloneWithExpression(this.#X.withNode,G):J11.create(G)})}withRecursive(X,Y){let G=Ma1(X,Y);return new TN({...this.#X,withNode:this.#X.withNode?J11.cloneWithExpression(this.#X.withNode,G):J11.create(G,{recursive:!0})})}withPlugin(X){return new TN({...this.#X,executor:this.#X.executor.withPlugin(X)})}withoutPlugins(){return new TN({...this.#X,executor:this.#X.executor.withoutPlugins()})}withSchema(X){return new TN({...this.#X,executor:this.#X.executor.withPluginAtFront(new eW(X))})}}var ZK1=D(()=>{WK1();qa1();Ta1();XK1();re();eT();YI();vd();LQ();Sl0();Ra1();AN();WI();W0();sL();xa1();se()});function Cl0(){return new TN({executor:YE})}function xl0(X,Y){return new _d({joinNode:$F.create(X,$I(Y))})}function hl0(){return new fd({overNode:ne.create()})}var GK1=D(()=>{Id();i$1();Ka1();Ll0();ZK1();md();LQ()});function eL(X,Y){if(Y.length===3)return kO8(X,Y[0],Y[1],Y[2]);else if(Y.length===2)return CO8(X,Y[0],Y[1]);else if(Y.length===1)return vO8(X,Y[0]);else throw Error("not implemented")}function CO8(X,Y,G){return G(xl0(X,Y)).toOperationNode()}function kO8(X,Y,G,Q){return $F.createWithOn(X,$I(Y),jG(G,"=",Q))}function vO8(X,Y){return $F.create(X,$I(Y))}var G11=D(()=>{Id();oW();GK1();LQ()});var gl0;var ga1=D(()=>{W0();gl0=n({is(X){return X.kind==="OffsetNode"},create(X){return n({kind:"OffsetNode",offset:X})}})});var ul0;var ua1=D(()=>{W0();ul0=n({is(X){return X.kind==="GroupByItemNode"},create(X){return n({kind:"GroupByItemNode",groupBy:X})}})});function ll0(X){return X=F9(X)?X(FF()):X,zO(X).map(ul0.create)}var ml0=D(()=>{ua1();GI();W0();OQ()});var $K1;var KK1=D(()=>{W0();$K1=n({is(X){return X.kind==="SetOperationNode"},create(X,Y,G){return n({kind:"SetOperationNode",operator:X,expression:Y,all:G})}})});function KI(X,Y,G){if(F9(Y))Y=Y(HK1());if(!IG(Y))Y=[Y];return Y.map((Q)=>$K1.create(X,y3(Q),G))}var dl0=D(()=>{GI();KK1();W0();HF()});class N9{#X;constructor(X){this.#X=X}get expressionType(){return}as(X){return new NK1(this,X)}or(...X){return new FK1(WF.create(this.#X,N7(X)))}and(...X){return new UK1(b3.create(this.#X,N7(X)))}$castTo(){return new N9(this.#X)}$notNull(){return new N9(this.#X)}toOperationNode(){return this.#X}}class NK1{#X;#Y;constructor(X,Y){this.#X=X,this.#Y=Y}get expression(){return this.#X}get alias(){return this.#Y}toOperationNode(){return VG.create(this.#X.toOperationNode(),R7(this.#Y)?this.#Y.toOperationNode():k4.create(this.#Y))}}class FK1{#X;constructor(X){this.#X=X}get expressionType(){return}as(X){return new NK1(this,X)}or(...X){return new FK1(WF.create(this.#X,N7(X)))}$castTo(){return new FK1(this.#X)}toOperationNode(){return rW.create(this.#X)}}class UK1{#X;constructor(X){this.#X=X}get expressionType(){return}as(X){return new NK1(this,X)}and(...X){return new UK1(b3.create(this.#X,N7(X)))}$castTo(){return new UK1(this.#X)}toOperationNode(){return rW.create(this.#X)}}var dd=D(()=>{ZF();pL();U7();f3();tT();Cd();oW()});var cl0;var la1=D(()=>{W0();wN();cl0=n({is(X){return X.kind==="FetchNode"},create(X,Y){return{kind:"FetchNode",rowCount:kY.create(X),modifier:Y}}})});function il0(X,Y){if(!QF(X)&&!cL(X))throw Error(`Invalid fetch row count: ${X}`);if(!_O8(Y))throw Error(`Invalid fetch modifier: ${Y}`);return cl0.create(X,Y)}function _O8(X){return X==="only"||X==="with ties"}var pl0=D(()=>{la1();W0()});class ma1{#X;constructor(X){this.#X=n(X)}get expressionType(){return}get isSelectQueryBuilder(){return!0}where(...X){return new T8({...this.#X,queryNode:A6.cloneWithWhere(this.#X.queryNode,N7(X))})}whereRef(X,Y,G){return new T8({...this.#X,queryNode:A6.cloneWithWhere(this.#X.queryNode,jG(X,Y,G))})}having(...X){return new T8({...this.#X,queryNode:U9.cloneWithHaving(this.#X.queryNode,N7(X))})}havingRef(X,Y,G){return new T8({...this.#X,queryNode:U9.cloneWithHaving(this.#X.queryNode,jG(X,Y,G))})}select(X){return new T8({...this.#X,queryNode:U9.cloneWithSelections(this.#X.queryNode,sY(X))})}distinctOn(X){return new T8({...this.#X,queryNode:U9.cloneWithDistinctOn(this.#X.queryNode,zO(X))})}modifyFront(X){return new T8({...this.#X,queryNode:U9.cloneWithFrontModifier(this.#X.queryNode,zN.createWithExpression(X.toOperationNode()))})}modifyEnd(X){return new T8({...this.#X,queryNode:A6.cloneWithEndModifier(this.#X.queryNode,zN.createWithExpression(X.toOperationNode()))})}distinct(){return new T8({...this.#X,queryNode:U9.cloneWithFrontModifier(this.#X.queryNode,zN.create("Distinct"))})}forUpdate(X){return new T8({...this.#X,queryNode:A6.cloneWithEndModifier(this.#X.queryNode,zN.create("ForUpdate",X?ye(X).map(b5):void 0))})}forShare(X){return new T8({...this.#X,queryNode:A6.cloneWithEndModifier(this.#X.queryNode,zN.create("ForShare",X?ye(X).map(b5):void 0))})}forKeyShare(X){return new T8({...this.#X,queryNode:A6.cloneWithEndModifier(this.#X.queryNode,zN.create("ForKeyShare",X?ye(X).map(b5):void 0))})}forNoKeyUpdate(X){return new T8({...this.#X,queryNode:A6.cloneWithEndModifier(this.#X.queryNode,zN.create("ForNoKeyUpdate",X?ye(X).map(b5):void 0))})}skipLocked(){return new T8({...this.#X,queryNode:A6.cloneWithEndModifier(this.#X.queryNode,zN.create("SkipLocked"))})}noWait(){return new T8({...this.#X,queryNode:A6.cloneWithEndModifier(this.#X.queryNode,zN.create("NoWait"))})}selectAll(X){return new T8({...this.#X,queryNode:U9.cloneWithSelections(this.#X.queryNode,MG(X))})}innerJoin(...X){return this.#Y("InnerJoin",X)}leftJoin(...X){return this.#Y("LeftJoin",X)}rightJoin(...X){return this.#Y("RightJoin",X)}fullJoin(...X){return this.#Y("FullJoin",X)}crossJoin(...X){return this.#Y("CrossJoin",X)}innerJoinLateral(...X){return this.#Y("LateralInnerJoin",X)}leftJoinLateral(...X){return this.#Y("LateralLeftJoin",X)}crossJoinLateral(...X){return this.#Y("LateralCrossJoin",X)}crossApply(...X){return this.#Y("CrossApply",X)}outerApply(...X){return this.#Y("OuterApply",X)}#Y(X,Y){return new T8({...this.#X,queryNode:A6.cloneWithJoin(this.#X.queryNode,eL(X,Y))})}orderBy(...X){return new T8({...this.#X,queryNode:A6.cloneWithOrderByItems(this.#X.queryNode,tW(X))})}groupBy(X){return new T8({...this.#X,queryNode:U9.cloneWithGroupByItems(this.#X.queryNode,ll0(X))})}limit(X){return new T8({...this.#X,queryNode:U9.cloneWithLimit(this.#X.queryNode,xd.create(d9(X)))})}offset(X){return new T8({...this.#X,queryNode:U9.cloneWithOffset(this.#X.queryNode,gl0.create(d9(X)))})}fetch(X,Y="only"){return new T8({...this.#X,queryNode:U9.cloneWithFetch(this.#X.queryNode,il0(X,Y))})}top(X,Y){return new T8({...this.#X,queryNode:A6.cloneWithTop(this.#X.queryNode,NF(X,Y))})}union(X){return new T8({...this.#X,queryNode:U9.cloneWithSetOperations(this.#X.queryNode,KI("union",X,!1))})}unionAll(X){return new T8({...this.#X,queryNode:U9.cloneWithSetOperations(this.#X.queryNode,KI("union",X,!0))})}intersect(X){return new T8({...this.#X,queryNode:U9.cloneWithSetOperations(this.#X.queryNode,KI("intersect",X,!1))})}intersectAll(X){return new T8({...this.#X,queryNode:U9.cloneWithSetOperations(this.#X.queryNode,KI("intersect",X,!0))})}except(X){return new T8({...this.#X,queryNode:U9.cloneWithSetOperations(this.#X.queryNode,KI("except",X,!1))})}exceptAll(X){return new T8({...this.#X,queryNode:U9.cloneWithSetOperations(this.#X.queryNode,KI("except",X,!0))})}as(X){return new nl0(this,X)}clearSelect(){return new T8({...this.#X,queryNode:U9.cloneWithoutSelections(this.#X.queryNode)})}clearWhere(){return new T8({...this.#X,queryNode:A6.cloneWithoutWhere(this.#X.queryNode)})}clearLimit(){return new T8({...this.#X,queryNode:U9.cloneWithoutLimit(this.#X.queryNode)})}clearOffset(){return new T8({...this.#X,queryNode:U9.cloneWithoutOffset(this.#X.queryNode)})}clearOrderBy(){return new T8({...this.#X,queryNode:A6.cloneWithoutOrderBy(this.#X.queryNode)})}clearGroupBy(){return new T8({...this.#X,queryNode:U9.cloneWithoutGroupBy(this.#X.queryNode)})}$call(X){return X(this)}$if(X,Y){if(X)return Y(this);return new T8({...this.#X})}$castTo(){return new T8(this.#X)}$narrowType(){return new T8(this.#X)}$assertType(){return new T8(this.#X)}$asTuple(){return new N9(this.toOperationNode())}$asScalar(){return new N9(this.toOperationNode())}withPlugin(X){return new T8({...this.#X,executor:this.#X.executor.withPlugin(X)})}toOperationNode(){return this.#X.executor.transformQuery(this.#X.queryNode,this.#X.queryId)}compile(){return this.#X.executor.compileQuery(this.toOperationNode(),this.#X.queryId)}async execute(){let X=this.compile();return(await this.#X.executor.executeQuery(X)).rows}async executeTakeFirst(){let[X]=await this.execute();return X}async executeTakeFirstOrThrow(X=UF){let Y=await this.executeTakeFirst();if(Y===void 0)throw PN(X)?new X(this.toOperationNode()):X(this.toOperationNode());return Y}async*stream(X=100){let Y=this.compile(),G=this.#X.executor.stream(Y,X);for await(let Q of G)yield*Q.rows}async explain(X,Y){return await new T8({...this.#X,queryNode:A6.cloneWithExplain(this.#X.queryNode,X,Y)}).execute()}}function W11(X){return new ma1(X)}class nl0{#X;#Y;constructor(X,Y){this.#X=X,this.#Y=Y}get expression(){return this.#X}get alias(){return this.#Y}get isAliasedSelectQueryBuilder(){return!0}toOperationNode(){return VG.create(this.#X.toOperationNode(),k4.create(this.#Y))}}var T8;var WK1=D(()=>{ZF();hn1();G11();LQ();sL();OQ();YI();PK();rT();Y11();ga1();W0();ml0();QI();U7();dl0();oW();dd();LN();pl0();yd();T8=ma1});var IN;var BK1=D(()=>{W0();oe();pe();IN=n({is(X){return X.kind==="AggregateFunctionNode"},create(X,Y=[]){return n({kind:"AggregateFunctionNode",func:X,aggregated:Y})},cloneWithDistinct(X){return n({...X,distinct:!0})},cloneWithOrderBy(X,Y,G=!1){let Q=G?"withinGroup":"orderBy";return n({...X,[Q]:X[Q]?OO.cloneWithItems(X[Q],Y):OO.create(Y)})},cloneWithFilter(X,Y){return n({...X,filter:X.filter?wQ.cloneWithOperation(X.filter,"And",Y):wQ.create(Y)})},cloneWithOrFilter(X,Y){return n({...X,filter:X.filter?wQ.cloneWithOperation(X.filter,"Or",Y):wQ.create(Y)})},cloneWithOver(X,Y){return n({...X,over:Y})}})});var da1;var ca1=D(()=>{W0();da1=n({is(X){return X.kind==="FunctionNode"},create(X,Y){return n({kind:"FunctionNode",func:X,arguments:Y})}})});class h3{#X;constructor(X){this.#X=n(X)}get expressionType(){return}as(X){return new al0(this,X)}distinct(){return new h3({...this.#X,aggregateFunctionNode:IN.cloneWithDistinct(this.#X.aggregateFunctionNode)})}orderBy(...X){return new h3({...this.#X,aggregateFunctionNode:A6.cloneWithOrderByItems(this.#X.aggregateFunctionNode,tW(X))})}clearOrderBy(){return new h3({...this.#X,aggregateFunctionNode:A6.cloneWithoutOrderBy(this.#X.aggregateFunctionNode)})}withinGroupOrderBy(...X){return new h3({...this.#X,aggregateFunctionNode:IN.cloneWithOrderBy(this.#X.aggregateFunctionNode,tW(X),!0)})}filterWhere(...X){return new h3({...this.#X,aggregateFunctionNode:IN.cloneWithFilter(this.#X.aggregateFunctionNode,N7(X))})}filterWhereRef(X,Y,G){return new h3({...this.#X,aggregateFunctionNode:IN.cloneWithFilter(this.#X.aggregateFunctionNode,jG(X,Y,G))})}over(X){let Y=hl0();return new h3({...this.#X,aggregateFunctionNode:IN.cloneWithOver(this.#X.aggregateFunctionNode,(X?X(Y):Y).toOperationNode())})}$call(X){return X(this)}$castTo(){return new h3(this.#X)}$notNull(){return new h3(this.#X)}toOperationNode(){return this.#X.aggregateFunctionNode}}class al0{#X;#Y;constructor(X,Y){this.#X=X,this.#Y=Y}get expression(){return this.#X}get alias(){return this.#Y}toOperationNode(){return VG.create(this.#X.toOperationNode(),k4.create(this.#Y))}}var ia1=D(()=>{W0();BK1();ZF();U7();GK1();oW();rT();PK()});function zK1(){let X=(G,Q)=>{return new N9(da1.create(G,zO(Q??[])))},Y=(G,Q)=>{return new h3({aggregateFunctionNode:IN.create(G,Q?zO(Q):void 0)})};return Object.assign(X,{agg:Y,avg(G){return Y("avg",[G])},coalesce(...G){return X("coalesce",G)},count(G){return Y("count",[G])},countAll(G){return new h3({aggregateFunctionNode:IN.create("count",MG(G))})},max(G){return Y("max",[G])},min(G){return Y("min",[G])},sum(G){return Y("sum",[G])},any(G){return X("any",[G])},jsonAgg(G){return new h3({aggregateFunctionNode:IN.create("json_agg",[H9(G)?b5(G):G.toOperationNode()])})},toJson(G){return new N9(da1.create("to_json",[H9(G)?b5(G):G.toOperationNode()]))}})}var OK1=D(()=>{dd();BK1();ca1();OQ();sL();ia1();W0();LQ()});var tl0;var pa1=D(()=>{W0();tl0=n({is(X){return X.kind==="UnaryOperationNode"},create(X,Y){return n({kind:"UnaryOperationNode",operator:X,operand:Y})}})});function rl0(X,Y){return tl0.create(PZ.create(X),DQ(Y))}var ol0=D(()=>{aL();pa1();OQ()});var X$;var $11=D(()=>{W0();XI();X$=n({is(X){return X.kind==="CaseNode"},create(X){return n({kind:"CaseNode",value:X})},cloneWithWhen(X,Y){return n({...X,when:n(X.when?[...X.when,Y]:[Y])})},cloneWithThen(X,Y){return n({...X,when:X.when?n([...X.when.slice(0,-1),qK.cloneWithResult(X.when[X.when.length-1],Y)]):void 0})},cloneWith(X,Y){return n({...X,...Y})}})});class K11{#X;constructor(X){this.#X=n(X)}when(...X){return new na1({...this.#X,node:X$.cloneWithWhen(this.#X.node,qK.create(N7(X)))})}}class na1{#X;constructor(X){this.#X=n(X)}then(X){return new sl0({...this.#X,node:X$.cloneWithThen(this.#X.node,d$1(X)?ie(X):d9(X))})}}class sl0{#X;constructor(X){this.#X=n(X)}when(...X){return new na1({...this.#X,node:X$.cloneWithWhen(this.#X.node,qK.create(N7(X)))})}else(X){return new el0({...this.#X,node:X$.cloneWith(this.#X.node,{else:d$1(X)?ie(X):d9(X)})})}end(){return new N9(X$.cloneWith(this.#X.node,{isStatement:!1}))}endCase(){return new N9(X$.cloneWith(this.#X.node,{isStatement:!0}))}}class el0{#X;constructor(X){this.#X=n(X)}end(){return new N9(X$.cloneWith(this.#X.node,{isStatement:!1}))}endCase(){return new N9(X$.cloneWith(this.#X.node,{isStatement:!0}))}}var DK1=D(()=>{dd();W0();$11();XI();oW();LN()});var aa1;var ta1=D(()=>{W0();aa1=n({is(X){return X.kind==="JSONPathLegNode"},create(X,Y){return n({kind:"JSONPathLegNode",type:X,value:Y})}})});class F11{#X;constructor(X){this.#X=X}at(X){return this.#Y("ArrayLocation",X)}key(X){return this.#Y("Member",X)}#Y(X,Y){if(Md.is(this.#X))return new H11(Md.cloneWithTraversal(this.#X,rL.is(this.#X.traversal)?rL.cloneWithLeg(this.#X.traversal,aa1.create(X,Y)):l$1.cloneWithValue(this.#X.traversal,kY.createImmediate(Y))));return new H11(rL.cloneWithLeg(this.#X,aa1.create(X,Y)))}}class Xm0{#X;#Y;constructor(X,Y){this.#X=X,this.#Y=Y}get expression(){return this.#X}get alias(){return this.#Y}toOperationNode(){return VG.create(this.#X.toOperationNode(),R7(this.#Y)?this.#Y.toOperationNode():k4.create(this.#Y))}}var H11;var ra1=D(()=>{ZF();U7();m$1();ta1();de();u$1();f3();wN();H11=class H11 extends F11{#X;constructor(X){super(X);this.#X=X}get expressionType(){return}as(X){return new Xm0(this,X)}$castTo(){return new H11(this.#X)}$notNull(){return new H11(this.#X)}toOperationNode(){return this.#X}}});var oa1;var sa1=D(()=>{W0();oa1=n({is(X){return X.kind==="TupleNode"},create(X){return n({kind:"TupleNode",values:n(X)})}})});function Gm0(X){if(fO8.includes(X))return!0;if(bO8.some((Y)=>Y.test(X)))return!0;return!1}var fO8,bO8,Ym0;var ea1=D(()=>{W0();fO8=["varchar","char","text","integer","int2","int4","int8","smallint","bigint","boolean","real","double precision","float4","float8","decimal","numeric","binary","bytea","date","datetime","time","timetz","timestamp","timestamptz","serial","bigserial","uuid","json","jsonb","blob","varbinary","int4range","int4multirange","int8range","int8multirange","numrange","nummultirange","tsrange","tsmultirange","tstzrange","tstzmultirange","daterange","datemultirange"],bO8=[/^varchar\(\d+\)$/,/^char\(\d+\)$/,/^decimal\(\d+, \d+\)$/,/^numeric\(\d+, \d+\)$/,/^binary\(\d+\)$/,/^datetime\(\d+\)$/,/^time\(\d+\)$/,/^timetz\(\d+\)$/,/^timestamp\(\d+\)$/,/^timestamptz\(\d+\)$/,/^varbinary\(\d+\)$/],Ym0=n({is(X){return X.kind==="DataTypeNode"},create(X){return n({kind:"DataTypeNode",dataType:X})}})});function OF(X){if(R7(X))return X.toOperationNode();if(Gm0(X))return Ym0.create(X);throw Error(`invalid column data type ${JSON.stringify(X)}`)}var U11=D(()=>{ea1();f3()});var Qm0;var Xt1=D(()=>{W0();Qm0=n({is(X){return X.kind==="CastNode"},create(X,Y){return n({kind:"CastNode",expression:X,dataType:Y})}})});function HK1(X=YE){function Y(J,W,Z){return new N9(c$1(J,W,Z))}function G(J,W){return new N9(rl0(J,W))}let Q=Object.assign(Y,{fn:void 0,eb:void 0,selectFrom(J){return W11({queryId:e4(),executor:X,queryNode:U9.createFrom(BF(J))})},case(J){return new K11({node:X$.create(LZ(J)?void 0:DQ(J))})},ref(J,W){if(LZ(W))return new N9(aW(J));return new F11(Hl0(J,W))},jsonPath(){return new F11(rL.create())},table(J){return new N9(b5(J))},val(J){return new N9(d9(J))},refTuple(...J){return new N9(oa1.create(J.map(DQ)))},tuple(...J){return new N9(oa1.create(J.map(d9)))},lit(J){return new N9(ie(J))},unary:G,not(J){return G("not",J)},exists(J){return G("exists",J)},neg(J){return G("-",J)},between(J,W,Z){return new N9(nL.create(DQ(J),PZ.create("between"),b3.create(d9(W),d9(Z))))},betweenSymmetric(J,W,Z){return new N9(nL.create(DQ(J),PZ.create("between symmetric"),b3.create(d9(W),d9(Z))))},and(J){if(IG(J))return new N9(kd(J,"and"));return new N9(rn1(J,"and"))},or(J){if(IG(J))return new N9(kd(J,"or"));return new N9(rn1(J,"or"))},parens(...J){let W=N7(J);if(rW.is(W))return new N9(W);else return new N9(rW.create(W))},cast(J,W){return new N9(Qm0.create(DQ(J),OF(W)))},withSchema(J){return HK1(X.withPluginAtFront(new eW(J)))}});return Q.fn=zK1(),Q.eb=Q,Q}function FF(X){return HK1()}var GI=D(()=>{WK1();YI();LQ();WI();AN();OK1();OQ();oW();Cd();dd();aL();ol0();LN();md();DK1();$11();W0();ra1();y$1();pL();sa1();de();U11();Xt1()});function y3(X){if(R7(X))return X.toOperationNode();else if(F9(X))return X(FF()).toOperationNode();throw Error(`invalid expression: ${JSON.stringify(X)}`)}function t$1(X){if(R7(X))return X.toOperationNode();else if(F9(X))return X(FF()).toOperationNode();throw Error(`invalid aliased expression: ${JSON.stringify(X)}`)}function BO(X){return _$1(X)||Ql0(X)||F9(X)}var HF=D(()=>{f$1();f3();GI();W0()});class Yt1{#X;get table(){return this.#X}constructor(X){this.#X=X}as(X){return new Jm0(this.#X,X)}}class Jm0{#X;#Y;get table(){return this.#X}get alias(){return this.#Y}constructor(X,Y){this.#X=X,this.#Y=Y}toOperationNode(){return VG.create(b5(this.#X),k4.create(this.#Y))}}function Zm0(X){return F7(X)&&R7(X)&&H9(X.table)&&H9(X.alias)}var wK1=D(()=>{ZF();U7();f3();LQ();W0()});function BF(X){if(IG(X))return X.map((Y)=>$I(Y));else return[$I(X)]}function $I(X){if(H9(X))return ha1(X);else if(Zm0(X))return X.toOperationNode();else return t$1(X)}function ha1(X){if(X.includes(" as ")){let[G,Q]=X.split(" as ").map(Wm0);return VG.create(b5(G),k4.create(Q))}else return b5(X)}function b5(X){if(X.includes(".")){let[G,Q]=X.split(".").map(Wm0);return _3.createWithSchema(G,Q)}else return _3.create(X)}function Wm0(X){return X.trim()}var LQ=D(()=>{W0();ZF();Td();HF();U7();wK1()});var Gt1;var Qt1=D(()=>{W0();Gt1=n({is(X){return X.kind==="AddColumnNode"},create(X){return n({kind:"AddColumnNode",column:X})}})});var S7;var N11=D(()=>{W0();EJ();S7=n({is(X){return X.kind==="ColumnDefinitionNode"},create(X,Y){return n({kind:"ColumnDefinitionNode",column:T5.create(X),dataType:Y})},cloneWithFrontModifier(X,Y){return n({...X,frontModifiers:X.frontModifiers?n([...X.frontModifiers,Y]):[Y]})},cloneWithEndModifier(X,Y){return n({...X,endModifiers:X.endModifiers?n([...X.endModifiers,Y]):[Y]})},cloneWith(X,Y){return n({...X,...Y})}})});var Jt1;var Zt1=D(()=>{W0();EJ();Jt1=n({is(X){return X.kind==="DropColumnNode"},create(X){return n({kind:"DropColumnNode",column:T5.create(X)})}})});var Wt1;var $t1=D(()=>{W0();EJ();Wt1=n({is(X){return X.kind==="RenameColumnNode"},create(X,Y){return n({kind:"RenameColumnNode",column:T5.create(X),renameTo:T5.create(Y)})}})});var cd;var B11=D(()=>{W0();U7();cd=n({is(X){return X.kind==="CheckConstraintNode"},create(X,Y){return n({kind:"CheckConstraintNode",expression:X,name:Y?k4.create(Y):void 0})}})});var $m0,id;var z11=D(()=>{W0();$m0=["no action","restrict","cascade","set null","set default"],id=n({is(X){return X.kind==="ReferencesNode"},create(X,Y){return n({kind:"ReferencesNode",table:X,columns:n([...Y])})},cloneWithOnDelete(X,Y){return n({...X,onDelete:Y})},cloneWithOnUpdate(X,Y){return n({...X,onUpdate:Y})}})});function LK1(X){return R7(X)?X.toOperationNode():kY.createImmediate(X)}var Kt1=D(()=>{f3();wN()});var O11;var Ht1=D(()=>{W0();O11=n({is(X){return X.kind==="GeneratedNode"},create(X){return n({kind:"GeneratedNode",...X})},createWithExpression(X){return n({kind:"GeneratedNode",always:!0,expression:X})},cloneWith(X,Y){return n({...X,...Y})}})});var Km0;var Ft1=D(()=>{W0();Km0=n({is(X){return X.kind==="DefaultValueNode"},create(X){return n({kind:"DefaultValueNode",defaultValue:X})}})});function pd(X){if($m0.includes(X))return X;throw Error(`invalid OnModifyForeignAction ${X}`)}var Ut1=D(()=>{z11()});class C7{#X;constructor(X){this.#X=X}autoIncrement(){return new C7(S7.cloneWith(this.#X,{autoIncrement:!0}))}identity(){return new C7(S7.cloneWith(this.#X,{identity:!0}))}primaryKey(){return new C7(S7.cloneWith(this.#X,{primaryKey:!0}))}references(X){let Y=aW(X);if(!Y.table||Vd.is(Y.column))throw Error(`invalid call references('${X}'). The reference must have format table.column or schema.table.column`);return new C7(S7.cloneWith(this.#X,{references:id.create(Y.table,[Y.column])}))}onDelete(X){if(!this.#X.references)throw Error("on delete constraint can only be added for foreign keys");return new C7(S7.cloneWith(this.#X,{references:id.cloneWithOnDelete(this.#X.references,pd(X))}))}onUpdate(X){if(!this.#X.references)throw Error("on update constraint can only be added for foreign keys");return new C7(S7.cloneWith(this.#X,{references:id.cloneWithOnUpdate(this.#X.references,pd(X))}))}unique(){return new C7(S7.cloneWith(this.#X,{unique:!0}))}notNull(){return new C7(S7.cloneWith(this.#X,{notNull:!0}))}unsigned(){return new C7(S7.cloneWith(this.#X,{unsigned:!0}))}defaultTo(X){return new C7(S7.cloneWith(this.#X,{defaultTo:Km0.create(LK1(X))}))}check(X){return new C7(S7.cloneWith(this.#X,{check:cd.create(X.toOperationNode())}))}generatedAlwaysAs(X){return new C7(S7.cloneWith(this.#X,{generated:O11.createWithExpression(X.toOperationNode())}))}generatedAlwaysAsIdentity(){return new C7(S7.cloneWith(this.#X,{generated:O11.create({identity:!0,always:!0})}))}generatedByDefaultAsIdentity(){return new C7(S7.cloneWith(this.#X,{generated:O11.create({identity:!0,byDefault:!0})}))}stored(){if(!this.#X.generated)throw Error("stored() can only be called after generatedAlwaysAs");return new C7(S7.cloneWith(this.#X,{generated:O11.cloneWith(this.#X.generated,{stored:!0})}))}modifyFront(X){return new C7(S7.cloneWithFrontModifier(this.#X,X.toOperationNode()))}nullsNotDistinct(){return new C7(S7.cloneWith(this.#X,{nullsNotDistinct:!0}))}ifNotExists(){return new C7(S7.cloneWith(this.#X,{ifNotExists:!0}))}modifyEnd(X){return new C7(S7.cloneWithEndModifier(this.#X,X.toOperationNode()))}$call(X){return X(this)}toOperationNode(){return this.#X}}var EK1=D(()=>{B11();z11();ue();OQ();N11();Kt1();Ht1();Ft1();Ut1()});var Nt1;var Bt1=D(()=>{W0();Nt1=n({is(X){return X.kind==="ModifyColumnNode"},create(X){return n({kind:"ModifyColumnNode",column:X})}})});var DF;var D11=D(()=>{W0();U7();z11();DF=n({is(X){return X.kind==="ForeignKeyConstraintNode"},create(X,Y,G,Q){return n({kind:"ForeignKeyConstraintNode",columns:X,references:id.create(Y,G),name:Q?k4.create(Q):void 0})},cloneWith(X,Y){return n({...X,...Y})}})});class wF{#X;constructor(X){this.#X=X}onDelete(X){return new wF(DF.cloneWith(this.#X,{onDelete:pd(X)}))}onUpdate(X){return new wF(DF.cloneWith(this.#X,{onUpdate:pd(X)}))}deferrable(){return new wF(DF.cloneWith(this.#X,{deferrable:!0}))}notDeferrable(){return new wF(DF.cloneWith(this.#X,{deferrable:!1}))}initiallyDeferred(){return new wF(DF.cloneWith(this.#X,{initiallyDeferred:!0}))}initiallyImmediate(){return new wF(DF.cloneWith(this.#X,{initiallyDeferred:!1}))}$call(X){return X(this)}toOperationNode(){return this.#X}}var PK1=D(()=>{D11();Ut1()});var nd;var qK1=D(()=>{W0();nd=n({is(X){return X.kind==="AddConstraintNode"},create(X){return n({kind:"AddConstraintNode",constraint:X})}})});var VN;var w11=D(()=>{W0();EJ();U7();VN=n({is(X){return X.kind==="UniqueConstraintNode"},create(X,Y,G){return n({kind:"UniqueConstraintNode",columns:n(X.map(T5.create)),name:Y?k4.create(Y):void 0,nullsNotDistinct:G})},cloneWith(X,Y){return n({...X,...Y})}})});var ad;var AK1=D(()=>{W0();U7();ad=n({is(X){return X.kind==="DropConstraintNode"},create(X){return n({kind:"DropConstraintNode",constraintName:k4.create(X)})},cloneWith(X,Y){return n({...X,...Y})}})});var td;var zt1=D(()=>{W0();EJ();td=n({is(X){return X.kind==="AlterColumnNode"},create(X,Y,G){return n({kind:"AlterColumnNode",column:T5.create(X),[Y]:G})}})});class TK1{#X;constructor(X){this.#X=X}setDataType(X){return new rd(td.create(this.#X,"dataType",OF(X)))}setDefault(X){return new rd(td.create(this.#X,"setDefault",LK1(X)))}dropDefault(){return new rd(td.create(this.#X,"dropDefault",!0))}setNotNull(){return new rd(td.create(this.#X,"setNotNull",!0))}dropNotNull(){return new rd(td.create(this.#X,"dropNotNull",!0))}$call(X){return X(this)}}class rd{#X;constructor(X){this.#X=X}toOperationNode(){return this.#X}}var Ot1=D(()=>{zt1();U11();Kt1()});class GE{#X;constructor(X){this.#X=n(X)}toOperationNode(){return this.#X.executor.transformQuery(this.#X.node,this.#X.queryId)}compile(){return this.#X.executor.compileQuery(this.toOperationNode(),this.#X.queryId)}async execute(){await this.#X.executor.executeQuery(this.compile())}}var Hm0=D(()=>{W0()});class wO{#X;constructor(X){this.#X=n(X)}onDelete(X){return new wO({...this.#X,constraintBuilder:this.#X.constraintBuilder.onDelete(X)})}onUpdate(X){return new wO({...this.#X,constraintBuilder:this.#X.constraintBuilder.onUpdate(X)})}deferrable(){return new wO({...this.#X,constraintBuilder:this.#X.constraintBuilder.deferrable()})}notDeferrable(){return new wO({...this.#X,constraintBuilder:this.#X.constraintBuilder.notDeferrable()})}initiallyDeferred(){return new wO({...this.#X,constraintBuilder:this.#X.constraintBuilder.initiallyDeferred()})}initiallyImmediate(){return new wO({...this.#X,constraintBuilder:this.#X.constraintBuilder.initiallyImmediate()})}$call(X){return X(this)}toOperationNode(){return this.#X.executor.transformQuery(_5.cloneWithTableProps(this.#X.node,{addConstraint:nd.create(this.#X.constraintBuilder.toOperationNode())}),this.#X.queryId)}compile(){return this.#X.executor.compileQuery(this.toOperationNode(),this.#X.queryId)}async execute(){await this.#X.executor.executeQuery(this.compile())}}var Fm0=D(()=>{qK1();aT();W0()});class HI{#X;constructor(X){this.#X=n(X)}ifExists(){return new HI({...this.#X,node:_5.cloneWithTableProps(this.#X.node,{dropConstraint:ad.cloneWith(this.#X.node.dropConstraint,{ifExists:!0})})})}cascade(){return new HI({...this.#X,node:_5.cloneWithTableProps(this.#X.node,{dropConstraint:ad.cloneWith(this.#X.node.dropConstraint,{modifier:"cascade"})})})}restrict(){return new HI({...this.#X,node:_5.cloneWithTableProps(this.#X.node,{dropConstraint:ad.cloneWith(this.#X.node.dropConstraint,{modifier:"restrict"})})})}$call(X){return X(this)}toOperationNode(){return this.#X.executor.transformQuery(this.#X.node,this.#X.queryId)}compile(){return this.#X.executor.compileQuery(this.toOperationNode(),this.#X.queryId)}async execute(){await this.#X.executor.executeQuery(this.compile())}}var Um0=D(()=>{aT();AK1();W0()});var LO;var L11=D(()=>{W0();EJ();U7();LO=n({is(X){return X.kind==="PrimaryKeyConstraintNode"},create(X,Y){return n({kind:"PrimaryKeyConstraintNode",columns:n(X.map(T5.create)),name:Y?k4.create(Y):void 0})},cloneWith(X,Y){return n({...X,...Y})}})});var QE;var IK1=D(()=>{W0();U7();QE=n({is(X){return X.kind==="AddIndexNode"},create(X){return n({kind:"AddIndexNode",name:k4.create(X)})},cloneWith(X,Y){return n({...X,...Y})},cloneWithColumns(X,Y){return n({...X,columns:[...X.columns||[],...Y]})}})});class JE{#X;constructor(X){this.#X=n(X)}unique(){return new JE({...this.#X,node:_5.cloneWithTableProps(this.#X.node,{addIndex:QE.cloneWith(this.#X.node.addIndex,{unique:!0})})})}column(X){return new JE({...this.#X,node:_5.cloneWithTableProps(this.#X.node,{addIndex:QE.cloneWithColumns(this.#X.node.addIndex,[Rd(X)])})})}columns(X){return new JE({...this.#X,node:_5.cloneWithTableProps(this.#X.node,{addIndex:QE.cloneWithColumns(this.#X.node.addIndex,X.map(Rd))})})}expression(X){return new JE({...this.#X,node:_5.cloneWithTableProps(this.#X.node,{addIndex:QE.cloneWithColumns(this.#X.node.addIndex,[X.toOperationNode()])})})}using(X){return new JE({...this.#X,node:_5.cloneWithTableProps(this.#X.node,{addIndex:QE.cloneWith(this.#X.node.addIndex,{using:f5.createWithSql(X)})})})}$call(X){return X(this)}toOperationNode(){return this.#X.executor.transformQuery(this.#X.node,this.#X.queryId)}compile(){return this.#X.executor.compileQuery(this.toOperationNode(),this.#X.queryId)}async execute(){await this.#X.executor.executeQuery(this.compile())}}var Nm0=D(()=>{IK1();aT();EK();OQ();W0()});class jN{#X;constructor(X){this.#X=X}nullsNotDistinct(){return new jN(VN.cloneWith(this.#X,{nullsNotDistinct:!0}))}deferrable(){return new jN(VN.cloneWith(this.#X,{deferrable:!0}))}notDeferrable(){return new jN(VN.cloneWith(this.#X,{deferrable:!1}))}initiallyDeferred(){return new jN(VN.cloneWith(this.#X,{initiallyDeferred:!0}))}initiallyImmediate(){return new jN(VN.cloneWith(this.#X,{initiallyDeferred:!1}))}$call(X){return X(this)}toOperationNode(){return this.#X}}var Dt1=D(()=>{w11()});class EO{#X;constructor(X){this.#X=X}deferrable(){return new EO(LO.cloneWith(this.#X,{deferrable:!0}))}notDeferrable(){return new EO(LO.cloneWith(this.#X,{deferrable:!1}))}initiallyDeferred(){return new EO(LO.cloneWith(this.#X,{initiallyDeferred:!0}))}initiallyImmediate(){return new EO(LO.cloneWith(this.#X,{initiallyDeferred:!1}))}$call(X){return X(this)}toOperationNode(){return this.#X}}var wt1=D(()=>{L11()});class E11{#X;constructor(X){this.#X=X}$call(X){return X(this)}toOperationNode(){return this.#X}}var Bm0;var Lt1=D(()=>{W0();U7();Bm0=n({is(X){return X.kind==="RenameConstraintNode"},create(X,Y){return n({kind:"RenameConstraintNode",oldName:k4.create(X),newName:k4.create(Y)})}})});class Et1{#X;constructor(X){this.#X=n(X)}renameTo(X){return new GE({...this.#X,node:_5.cloneWithTableProps(this.#X.node,{renameTo:b5(X)})})}setSchema(X){return new GE({...this.#X,node:_5.cloneWithTableProps(this.#X.node,{setSchema:k4.create(X)})})}alterColumn(X,Y){let G=Y(new TK1(X));return new LF({...this.#X,node:_5.cloneWithColumnAlteration(this.#X.node,G.toOperationNode())})}dropColumn(X){return new LF({...this.#X,node:_5.cloneWithColumnAlteration(this.#X.node,Jt1.create(X))})}renameColumn(X,Y){return new LF({...this.#X,node:_5.cloneWithColumnAlteration(this.#X.node,Wt1.create(X,Y))})}addColumn(X,Y,G=EZ){let Q=G(new C7(S7.create(X,OF(Y))));return new LF({...this.#X,node:_5.cloneWithColumnAlteration(this.#X.node,Gt1.create(Q.toOperationNode()))})}modifyColumn(X,Y,G=EZ){let Q=G(new C7(S7.create(X,OF(Y))));return new LF({...this.#X,node:_5.cloneWithColumnAlteration(this.#X.node,Nt1.create(Q.toOperationNode()))})}addUniqueConstraint(X,Y,G=EZ){let Q=G(new jN(VN.create(Y,X)));return new GE({...this.#X,node:_5.cloneWithTableProps(this.#X.node,{addConstraint:nd.create(Q.toOperationNode())})})}addCheckConstraint(X,Y,G=EZ){let Q=G(new E11(cd.create(Y.toOperationNode(),X)));return new GE({...this.#X,node:_5.cloneWithTableProps(this.#X.node,{addConstraint:nd.create(Q.toOperationNode())})})}addForeignKeyConstraint(X,Y,G,Q,J=EZ){let W=J(new wF(DF.create(Y.map(T5.create),b5(G),Q.map(T5.create),X)));return new wO({...this.#X,constraintBuilder:W})}addPrimaryKeyConstraint(X,Y,G=EZ){let Q=G(new EO(LO.create(Y,X)));return new GE({...this.#X,node:_5.cloneWithTableProps(this.#X.node,{addConstraint:nd.create(Q.toOperationNode())})})}dropConstraint(X){return new HI({...this.#X,node:_5.cloneWithTableProps(this.#X.node,{dropConstraint:ad.create(X)})})}renameConstraint(X,Y){return new HI({...this.#X,node:_5.cloneWithTableProps(this.#X.node,{renameConstraint:Bm0.create(X,Y)})})}addIndex(X){return new JE({...this.#X,node:_5.cloneWithTableProps(this.#X.node,{addIndex:QE.create(X)})})}dropIndex(X){return new GE({...this.#X,node:_5.cloneWithTableProps(this.#X.node,{dropIndex:iL.create(X)})})}$call(X){return X(this)}}class LF{#X;constructor(X){this.#X=n(X)}alterColumn(X,Y){let G=Y(new TK1(X));return new LF({...this.#X,node:_5.cloneWithColumnAlteration(this.#X.node,G.toOperationNode())})}dropColumn(X){return new LF({...this.#X,node:_5.cloneWithColumnAlteration(this.#X.node,Jt1.create(X))})}renameColumn(X,Y){return new LF({...this.#X,node:_5.cloneWithColumnAlteration(this.#X.node,Wt1.create(X,Y))})}addColumn(X,Y,G=EZ){let Q=G(new C7(S7.create(X,OF(Y))));return new LF({...this.#X,node:_5.cloneWithColumnAlteration(this.#X.node,Gt1.create(Q.toOperationNode()))})}modifyColumn(X,Y,G=EZ){let Q=G(new C7(S7.create(X,OF(Y))));return new LF({...this.#X,node:_5.cloneWithColumnAlteration(this.#X.node,Nt1.create(Q.toOperationNode()))})}toOperationNode(){return this.#X.executor.transformQuery(this.#X.node,this.#X.queryId)}compile(){return this.#X.executor.compileQuery(this.toOperationNode(),this.#X.queryId)}async execute(){await this.#X.executor.executeQuery(this.compile())}}var Pt1=D(()=>{Qt1();aT();N11();Zt1();U7();$t1();W0();EK1();Bt1();U11();PK1();qK1();w11();B11();D11();EJ();LQ();AK1();Ot1();Hm0();Fm0();Um0();L11();xe();IK1();Nm0();Dt1();wt1();Lt1()});var P11;var qt1=D(()=>{ZI();oT();wN();P11=class P11 extends zF{transformPrimitiveValueList(X){return DN.create(X.values.map(kY.createImmediate))}transformValue(X){return kY.createImmediate(X.value)}}});class AK{#X;constructor(X){this.#X=n(X)}ifNotExists(){return new AK({...this.#X,node:JF.cloneWith(this.#X.node,{ifNotExists:!0})})}unique(){return new AK({...this.#X,node:JF.cloneWith(this.#X.node,{unique:!0})})}nullsNotDistinct(){return new AK({...this.#X,node:JF.cloneWith(this.#X.node,{nullsNotDistinct:!0})})}on(X){return new AK({...this.#X,node:JF.cloneWith(this.#X.node,{table:b5(X)})})}column(X){return new AK({...this.#X,node:JF.cloneWithColumns(this.#X.node,[Rd(X)])})}columns(X){return new AK({...this.#X,node:JF.cloneWithColumns(this.#X.node,X.map(Rd))})}expression(X){return new AK({...this.#X,node:JF.cloneWithColumns(this.#X.node,[X.toOperationNode()])})}using(X){return new AK({...this.#X,node:JF.cloneWith(this.#X.node,{using:f5.createWithSql(X)})})}where(...X){let Y=new P11;return new AK({...this.#X,node:A6.cloneWithWhere(this.#X.node,Y.transformNode(N7(X),this.#X.queryId))})}$call(X){return X(this)}toOperationNode(){return this.#X.executor.transformQuery(this.#X.node,this.#X.queryId)}compile(){return this.#X.executor.compileQuery(this.toOperationNode(),this.#X.queryId)}async execute(){await this.#X.executor.executeQuery(this.compile())}}var At1=D(()=>{R$1();EK();OQ();LQ();W0();oW();PK();qt1()});class VK1{#X;constructor(X){this.#X=n(X)}ifNotExists(){return new VK1({...this.#X,node:S$1.cloneWith(this.#X.node,{ifNotExists:!0})})}$call(X){return X(this)}toOperationNode(){return this.#X.executor.transformQuery(this.#X.node,this.#X.queryId)}compile(){return this.#X.executor.compileQuery(this.toOperationNode(),this.#X.queryId)}async execute(){await this.#X.executor.executeQuery(this.compile())}}var Tt1=D(()=>{C$1();W0()});function zm0(X){if(Gl0.includes(X))return X;throw Error(`invalid OnCommitAction ${X}`)}var Om0=D(()=>{Ad()});class g3{#X;constructor(X){this.#X=n(X)}temporary(){return new g3({...this.#X,node:wJ.cloneWith(this.#X.node,{temporary:!0})})}onCommit(X){return new g3({...this.#X,node:wJ.cloneWith(this.#X.node,{onCommit:zm0(X)})})}ifNotExists(){return new g3({...this.#X,node:wJ.cloneWith(this.#X.node,{ifNotExists:!0})})}addColumn(X,Y,G=EZ){let Q=G(new C7(S7.create(X,OF(Y))));return new g3({...this.#X,node:wJ.cloneWithColumn(this.#X.node,Q.toOperationNode())})}addPrimaryKeyConstraint(X,Y,G=EZ){let Q=G(new EO(LO.create(Y,X)));return new g3({...this.#X,node:wJ.cloneWithConstraint(this.#X.node,Q.toOperationNode())})}addUniqueConstraint(X,Y,G=EZ){let Q=G(new jN(VN.create(Y,X)));return new g3({...this.#X,node:wJ.cloneWithConstraint(this.#X.node,Q.toOperationNode())})}addCheckConstraint(X,Y,G=EZ){let Q=G(new E11(cd.create(Y.toOperationNode(),X)));return new g3({...this.#X,node:wJ.cloneWithConstraint(this.#X.node,Q.toOperationNode())})}addForeignKeyConstraint(X,Y,G,Q,J=EZ){let W=J(new wF(DF.create(Y.map(T5.create),b5(G),Q.map(T5.create),X)));return new g3({...this.#X,node:wJ.cloneWithConstraint(this.#X.node,W.toOperationNode())})}modifyFront(X){return new g3({...this.#X,node:wJ.cloneWithFrontModifier(this.#X.node,X.toOperationNode())})}modifyEnd(X){return new g3({...this.#X,node:wJ.cloneWithEndModifier(this.#X.node,X.toOperationNode())})}as(X){return new g3({...this.#X,node:wJ.cloneWith(this.#X.node,{selectQuery:y3(X)})})}$call(X){return X(this)}toOperationNode(){return this.#X.executor.transformQuery(this.#X.node,this.#X.queryId)}compile(){return this.#X.executor.compileQuery(this.toOperationNode(),this.#X.queryId)}async execute(){await this.#X.executor.executeQuery(this.compile())}}var It1=D(()=>{N11();Ad();EK1();W0();D11();EJ();PK1();U11();L11();w11();B11();LQ();Om0();Dt1();HF();wt1()});class od{#X;constructor(X){this.#X=n(X)}on(X){return new od({...this.#X,node:iL.cloneWith(this.#X.node,{table:b5(X)})})}ifExists(){return new od({...this.#X,node:iL.cloneWith(this.#X.node,{ifExists:!0})})}cascade(){return new od({...this.#X,node:iL.cloneWith(this.#X.node,{cascade:!0})})}$call(X){return X(this)}toOperationNode(){return this.#X.executor.transformQuery(this.#X.node,this.#X.queryId)}compile(){return this.#X.executor.compileQuery(this.toOperationNode(),this.#X.queryId)}async execute(){await this.#X.executor.executeQuery(this.compile())}}var Vt1=D(()=>{xe();LQ();W0()});class q11{#X;constructor(X){this.#X=n(X)}ifExists(){return new q11({...this.#X,node:he.cloneWith(this.#X.node,{ifExists:!0})})}cascade(){return new q11({...this.#X,node:he.cloneWith(this.#X.node,{cascade:!0})})}$call(X){return X(this)}toOperationNode(){return this.#X.executor.transformQuery(this.#X.node,this.#X.queryId)}compile(){return this.#X.executor.compileQuery(this.toOperationNode(),this.#X.queryId)}async execute(){await this.#X.executor.executeQuery(this.compile())}}var jt1=D(()=>{k$1();W0()});class A11{#X;constructor(X){this.#X=n(X)}ifExists(){return new A11({...this.#X,node:ge.cloneWith(this.#X.node,{ifExists:!0})})}cascade(){return new A11({...this.#X,node:ge.cloneWith(this.#X.node,{cascade:!0})})}$call(X){return X(this)}toOperationNode(){return this.#X.executor.transformQuery(this.#X.node,this.#X.queryId)}compile(){return this.#X.executor.compileQuery(this.toOperationNode(),this.#X.queryId)}async execute(){await this.#X.executor.executeQuery(this.compile())}}var Mt1=D(()=>{v$1();W0()});var EF;var T11=D(()=>{W0();NO();EF=n({is(X){return X.kind==="CreateViewNode"},create(X){return n({kind:"CreateViewNode",name:LJ.create(X)})},cloneWith(X,Y){return n({...X,...Y})}})});class Rt1{#X=new P11;transformQuery(X){return this.#X.transformNode(X.node,X.queryId)}transformResult(X){return Promise.resolve(X.result)}}var Dm0=D(()=>{qt1()});class PO{#X;constructor(X){this.#X=n(X)}temporary(){return new PO({...this.#X,node:EF.cloneWith(this.#X.node,{temporary:!0})})}materialized(){return new PO({...this.#X,node:EF.cloneWith(this.#X.node,{materialized:!0})})}ifNotExists(){return new PO({...this.#X,node:EF.cloneWith(this.#X.node,{ifNotExists:!0})})}orReplace(){return new PO({...this.#X,node:EF.cloneWith(this.#X.node,{orReplace:!0})})}columns(X){return new PO({...this.#X,node:EF.cloneWith(this.#X.node,{columns:X.map(nn1)})})}as(X){let Y=X.withPlugin(new Rt1).toOperationNode();return new PO({...this.#X,node:EF.cloneWith(this.#X.node,{as:Y})})}$call(X){return X(this)}toOperationNode(){return this.#X.executor.transformQuery(this.#X.node,this.#X.queryId)}compile(){return this.#X.executor.compileQuery(this.toOperationNode(),this.#X.queryId)}async execute(){await this.#X.executor.executeQuery(this.compile())}}var St1=D(()=>{W0();T11();OQ();Dm0()});var sd;var jK1=D(()=>{W0();NO();sd=n({is(X){return X.kind==="DropViewNode"},create(X){return n({kind:"DropViewNode",name:LJ.create(X)})},cloneWith(X,Y){return n({...X,...Y})}})});class ed{#X;constructor(X){this.#X=n(X)}materialized(){return new ed({...this.#X,node:sd.cloneWith(this.#X.node,{materialized:!0})})}ifExists(){return new ed({...this.#X,node:sd.cloneWith(this.#X.node,{ifExists:!0})})}cascade(){return new ed({...this.#X,node:sd.cloneWith(this.#X.node,{cascade:!0})})}$call(X){return X(this)}toOperationNode(){return this.#X.executor.transformQuery(this.#X.node,this.#X.queryId)}compile(){return this.#X.executor.compileQuery(this.toOperationNode(),this.#X.queryId)}async execute(){await this.#X.executor.executeQuery(this.compile())}}var Ct1=D(()=>{W0();jK1()});var MK1;var RK1=D(()=>{W0();oT();wN();MK1=n({is(X){return X.kind==="CreateTypeNode"},create(X){return n({kind:"CreateTypeNode",name:X})},cloneWithEnum(X,Y){return n({...X,enum:DN.create(Y.map(kY.createImmediate))})}})});class SK1{#X;constructor(X){this.#X=n(X)}toOperationNode(){return this.#X.executor.transformQuery(this.#X.node,this.#X.queryId)}asEnum(X){return new SK1({...this.#X,node:MK1.cloneWithEnum(this.#X.node,X)})}$call(X){return X(this)}compile(){return this.#X.executor.compileQuery(this.toOperationNode(),this.#X.queryId)}async execute(){await this.#X.executor.executeQuery(this.compile())}}var kt1=D(()=>{W0();RK1()});var CK1;var kK1=D(()=>{W0();CK1=n({is(X){return X.kind==="DropTypeNode"},create(X){return n({kind:"DropTypeNode",name:X})},cloneWith(X,Y){return n({...X,...Y})}})});class vK1{#X;constructor(X){this.#X=n(X)}ifExists(){return new vK1({...this.#X,node:CK1.cloneWith(this.#X.node,{ifExists:!0})})}$call(X){return X(this)}toOperationNode(){return this.#X.executor.transformQuery(this.#X.node,this.#X.queryId)}compile(){return this.#X.executor.compileQuery(this.toOperationNode(),this.#X.queryId)}async execute(){await this.#X.executor.executeQuery(this.compile())}}var vt1=D(()=>{kK1();W0()});function _t1(X){if(X.includes(".")){let G=X.split(".").map(yO8);if(G.length===2)return LJ.createWithSchema(G[0],G[1]);else throw Error(`invalid schemable identifier ${X}`)}else return LJ.create(X)}function yO8(X){return X.trim()}var wm0=D(()=>{NO()});var Xc;var _K1=D(()=>{W0();NO();Xc=n({is(X){return X.kind==="RefreshMaterializedViewNode"},create(X){return n({kind:"RefreshMaterializedViewNode",name:LJ.create(X)})},cloneWith(X,Y){return n({...X,...Y})}})});class Yc{#X;constructor(X){this.#X=n(X)}concurrently(){return new Yc({...this.#X,node:Xc.cloneWith(this.#X.node,{concurrently:!0,withNoData:!1})})}withData(){return new Yc({...this.#X,node:Xc.cloneWith(this.#X.node,{withNoData:!1})})}withNoData(){return new Yc({...this.#X,node:Xc.cloneWith(this.#X.node,{withNoData:!0,concurrently:!1})})}$call(X){return X(this)}toOperationNode(){return this.#X.executor.transformQuery(this.#X.node,this.#X.queryId)}compile(){return this.#X.executor.compileQuery(this.toOperationNode(),this.#X.queryId)}async execute(){await this.#X.executor.executeQuery(this.compile())}}var ft1=D(()=>{W0();_K1()});class Gc{#X;constructor(X){this.#X=X}createTable(X){return new g3({queryId:e4(),executor:this.#X,node:wJ.create(b5(X))})}dropTable(X){return new A11({queryId:e4(),executor:this.#X,node:ge.create(b5(X))})}createIndex(X){return new AK({queryId:e4(),executor:this.#X,node:JF.create(X)})}dropIndex(X){return new od({queryId:e4(),executor:this.#X,node:iL.create(X)})}createSchema(X){return new VK1({queryId:e4(),executor:this.#X,node:S$1.create(X)})}dropSchema(X){return new q11({queryId:e4(),executor:this.#X,node:he.create(X)})}alterTable(X){return new Et1({queryId:e4(),executor:this.#X,node:_5.create(b5(X))})}createView(X){return new PO({queryId:e4(),executor:this.#X,node:EF.create(X)})}refreshMaterializedView(X){return new Yc({queryId:e4(),executor:this.#X,node:Xc.create(X)})}dropView(X){return new ed({queryId:e4(),executor:this.#X,node:sd.create(X)})}createType(X){return new SK1({queryId:e4(),executor:this.#X,node:MK1.create(_t1(X))})}dropType(X){return new vK1({queryId:e4(),executor:this.#X,node:CK1.create(_t1(X))})}withPlugin(X){return new Gc(this.#X.withPlugin(X))}withoutPlugins(){return new Gc(this.#X.withoutPlugins())}withSchema(X){return new Gc(this.#X.withPluginAtFront(new eW(X)))}}var bt1=D(()=>{aT();R$1();C$1();Ad();xe();k$1();v$1();LQ();Pt1();At1();Tt1();It1();Vt1();jt1();Mt1();AN();WI();St1();T11();Ct1();jK1();kt1();vt1();RK1();kK1();wm0();ft1();_K1()});class yt1{ref(X){return new ln1(X)}table(X){return new Yt1(X)}}var xt1=D(()=>{le();wK1()});class ht1{#X;constructor(X){this.#X=X}async provideConnection(X){let Y=await this.#X.acquireConnection();try{return await X(Y)}finally{await this.#X.releaseConnection(Y)}}}var ZE;var gt1=D(()=>{fa1();ZE=class ZE extends Z11{#X;#Y;#G;constructor(X,Y,G,Q=[]){super(Q);this.#X=X,this.#Y=Y,this.#G=G}get adapter(){return this.#Y}compileQuery(X,Y){return this.#X.compileQuery(X,Y)}provideConnection(X){return this.#G.provideConnection(X)}withPlugins(X){return new ZE(this.#X,this.#Y,this.#G,[...this.plugins,...X])}withPlugin(X){return new ZE(this.#X,this.#Y,this.#G,[...this.plugins,X])}withPluginAtFront(X){return new ZE(this.#X,this.#Y,this.#G,[X,...this.plugins])}withConnectionProvider(X){return new ZE(this.#X,this.#Y,X,[...this.plugins])}withoutPlugins(){return new ZE(this.#X,this.#Y,this.#G,[])}}});function fK1(){if(typeof performance<"u"&&F9(performance.now))return performance.now();else return Date.now()}var Lm0=D(()=>{W0()});class ut1{#X;#Y;#G;#Q;#J;#Z=new WeakSet;constructor(X,Y){this.#Q=!1,this.#X=X,this.#Y=Y}async init(){if(this.#J)throw Error("driver has already been destroyed");if(!this.#G)this.#G=this.#X.init().then(()=>{this.#Q=!0}).catch((X)=>{return this.#G=void 0,Promise.reject(X)});await this.#G}async acquireConnection(){if(this.#J)throw Error("driver has already been destroyed");if(!this.#Q)await this.init();let X=await this.#X.acquireConnection();if(!this.#Z.has(X)){if(this.#$())this.#W(X);this.#Z.add(X)}return X}async releaseConnection(X){await this.#X.releaseConnection(X)}beginTransaction(X,Y){return this.#X.beginTransaction(X,Y)}commitTransaction(X){return this.#X.commitTransaction(X)}rollbackTransaction(X){return this.#X.rollbackTransaction(X)}savepoint(X,Y,G){if(this.#X.savepoint)return this.#X.savepoint(X,Y,G);throw Error("The `savepoint` method is not supported by this driver")}rollbackToSavepoint(X,Y,G){if(this.#X.rollbackToSavepoint)return this.#X.rollbackToSavepoint(X,Y,G);throw Error("The `rollbackToSavepoint` method is not supported by this driver")}releaseSavepoint(X,Y,G){if(this.#X.releaseSavepoint)return this.#X.releaseSavepoint(X,Y,G);throw Error("The `releaseSavepoint` method is not supported by this driver")}async destroy(){if(!this.#G)return;if(await this.#G,!this.#J)this.#J=this.#X.destroy().catch((X)=>{return this.#J=void 0,Promise.reject(X)});await this.#J}#$(){return this.#Y.isLevelEnabled("query")||this.#Y.isLevelEnabled("error")}#W(X){let{executeQuery:Y,streamQuery:G}=X,Q=this;X.executeQuery=async(J)=>{let W,Z=fK1();try{return await Y.call(X,J)}catch($){throw W=$,await Q.#K($,J,Z),$}finally{if(!W)await Q.#H(J,Z)}},X.streamQuery=async function*(J,W){let Z,$=fK1();try{for await(let K of G.call(X,J,W))yield K}catch(K){throw Z=K,await Q.#K(K,J,$),K}finally{if(!Z)await Q.#H(J,$,!0)}}}async#K(X,Y,G){await this.#Y.error(()=>({level:"error",error:X,query:Y,queryDurationMillis:this.#U(G)}))}async#H(X,Y,G=!1){await this.#Y.query(()=>({level:"query",isStream:G,query:X,queryDurationMillis:this.#U(Y)}))}#U(X){return fK1()-X}}var Em0=D(()=>{Lm0()});class I11{#X;#Y;constructor(X){this.#X=X}async provideConnection(X){while(this.#Y)await this.#Y.catch(xO8);return this.#Y=this.#G(X).finally(()=>{this.#Y=void 0}),this.#Y}async#G(X){return await X(this.#X)}}var xO8=()=>{};function lt1(X){if(X.accessMode&&!hO8.includes(X.accessMode))throw Error(`invalid transaction access mode ${X.accessMode}`);if(X.isolationLevel&&!gO8.includes(X.isolationLevel))throw Error(`invalid transaction isolation level ${X.isolationLevel}`)}var hO8,gO8;var mt1=D(()=>{hO8=["read only","read write"],gO8=["read uncommitted","read committed","repeatable read","serializable","snapshot"]});class dt1{#X;#Y;constructor(X){if(F9(X))this.#Y=X,this.#X=n({query:!0,error:!0});else this.#Y=lO8,this.#X=n({query:X.includes("query"),error:X.includes("error")})}isLevelEnabled(X){return this.#X[X]}async query(X){if(this.#X.query)await this.#Y(X())}async error(X){if(this.#X.error)await this.#Y(X())}}function lO8(X){if(X.level==="query"){let Y=`kysely:query:${X.isStream?"stream:":""}`;console.log(`${Y} ${X.query.sql}`),console.log(`${Y} duration: ${X.queryDurationMillis.toFixed(1)}ms`)}else if(X.level==="error")if(X.error instanceof Error)console.error(`kysely:error: ${X.error.stack??X.error.message}`);else console.error(`kysely:error: ${JSON.stringify({error:X.error,query:X.query.sql,queryDurationMillis:X.queryDurationMillis})}`)}var uO8,BT7;var ct1=D(()=>{W0();uO8=["query","error"],BT7=n(uO8)});function Pm0(X){return F7(X)&&F9(X.compile)}var it1=D(()=>{W0()});function mO8(X){return F7(X)&&F7(X.config)&&F7(X.driver)&&F7(X.executor)&&F7(X.dialect)}class qm0{#X;constructor(X){this.#X=n(X)}async execute(X){return this.#X.executor.provideConnection(async(Y)=>{let G=this.#X.executor.withConnectionProvider(new I11(Y)),Q=new AZ({...this.#X,executor:G});return await X(Q)})}}class bK1{#X;constructor(X){this.#X=n(X)}setAccessMode(X){return new bK1({...this.#X,accessMode:X})}setIsolationLevel(X){return new bK1({...this.#X,isolationLevel:X})}async execute(X){let{isolationLevel:Y,accessMode:G,...Q}=this.#X,J={isolationLevel:Y,accessMode:G};return lt1(J),this.#X.executor.provideConnection(async(W)=>{let Z={isCommitted:!1,isRolledBack:!1},$=new AO(this.#X.executor.withConnectionProvider(new I11(W)),Z),K=new UI({...Q,executor:$}),H=!1;try{await this.#X.driver.beginTransaction(W,J),H=!0;let U=await X(K);return await this.#X.driver.commitTransaction(W),Z.isCommitted=!0,U}catch(U){if(H)await this.#X.driver.rollbackTransaction(W),Z.isRolledBack=!0;throw U}})}}class yK1{#X;constructor(X){this.#X=n(X)}setAccessMode(X){return new yK1({...this.#X,accessMode:X})}setIsolationLevel(X){return new yK1({...this.#X,isolationLevel:X})}async execute(){let{isolationLevel:X,accessMode:Y,...G}=this.#X,Q={isolationLevel:X,accessMode:Y};lt1(Q);let J=await JK1(this.#X.executor);return await this.#X.driver.beginTransaction(J.connection,Q),new qO({...G,connection:J,executor:this.#X.executor.withConnectionProvider(new I11(J.connection))})}}class Qc{#X;constructor(X){this.#X=X}async execute(){return await this.#X()}}function FI(X){if(X.isCommitted)throw Error("Transaction is already committed");if(X.isRolledBack)throw Error("Transaction is already rolled back")}class AO{#X;#Y;constructor(X,Y){if(X instanceof AO)this.#X=X.#X;else this.#X=X;this.#Y=Y}get adapter(){return this.#X.adapter}get plugins(){return this.#X.plugins}transformQuery(X,Y){return this.#X.transformQuery(X,Y)}compileQuery(X,Y){return this.#X.compileQuery(X,Y)}provideConnection(X){return this.#X.provideConnection(X)}executeQuery(X){return FI(this.#Y),this.#X.executeQuery(X)}stream(X,Y){return FI(this.#Y),this.#X.stream(X,Y)}withConnectionProvider(X){return new AO(this.#X.withConnectionProvider(X),this.#Y)}withPlugin(X){return new AO(this.#X.withPlugin(X),this.#Y)}withPlugins(X){return new AO(this.#X.withPlugins(X),this.#Y)}withPluginAtFront(X){return new AO(this.#X.withPluginAtFront(X),this.#Y)}withoutPlugins(){return new AO(this.#X.withoutPlugins(),this.#Y)}}var AZ,UI,qO;var Am0=D(()=>{bt1();xt1();ZK1();gt1();W0();Em0();mt1();OK1();ct1();AN();it1();DK1();$11();HF();WI();_a1();me();Symbol.asyncDispose??=Symbol("Symbol.asyncDispose");AZ=class AZ extends TN{#X;constructor(X){let Y,G;if(mO8(X))Y={executor:X.executor},G={...X};else{let Q=X.dialect,J=Q.createDriver(),W=Q.createQueryCompiler(),Z=Q.createAdapter(),$=new dt1(X.log??[]),K=new ut1(J,$),H=new ht1(K),U=new ZE(W,Z,H,X.plugins??[]);Y={executor:U},G={config:X,executor:U,dialect:Q,driver:K}}super(Y);this.#X=n(G)}get schema(){return new Gc(this.#X.executor)}get dynamic(){return new yt1}get introspection(){return this.#X.dialect.createIntrospector(this.withoutPlugins())}case(X){return new K11({node:X$.create(LZ(X)?void 0:y3(X))})}get fn(){return zK1()}transaction(){return new bK1({...this.#X})}startTransaction(){return new yK1({...this.#X})}connection(){return new qm0({...this.#X})}withPlugin(X){return new AZ({...this.#X,executor:this.#X.executor.withPlugin(X)})}withoutPlugins(){return new AZ({...this.#X,executor:this.#X.executor.withoutPlugins()})}withSchema(X){return new AZ({...this.#X,executor:this.#X.executor.withPluginAtFront(new eW(X))})}withTables(){return new AZ({...this.#X})}async destroy(){await this.#X.driver.destroy()}get isTransaction(){return!1}getExecutor(){return this.#X.executor}executeQuery(X,Y){if(Y!==void 0)ON("Passing `queryId` in `db.executeQuery` is deprecated and will result in a compile-time error in the future.");let G=Pm0(X)?X.compile():X;return this.getExecutor().executeQuery(G)}async[Symbol.asyncDispose](){await this.destroy()}};UI=class UI extends AZ{#X;constructor(X){super(X);this.#X=X}get isTransaction(){return!0}transaction(){throw Error("calling the transaction method for a Transaction is not supported")}connection(){throw Error("calling the connection method for a Transaction is not supported")}async destroy(){throw Error("calling the destroy method for a Transaction is not supported")}withPlugin(X){return new UI({...this.#X,executor:this.#X.executor.withPlugin(X)})}withoutPlugins(){return new UI({...this.#X,executor:this.#X.executor.withoutPlugins()})}withSchema(X){return new UI({...this.#X,executor:this.#X.executor.withPluginAtFront(new eW(X))})}withTables(){return new UI({...this.#X})}};qO=class qO extends UI{#X;#Y;#G;constructor(X){let Y={isCommitted:!1,isRolledBack:!1};X={...X,executor:new AO(X.executor,Y)};let{connection:G,...Q}=X;super(Q);this.#X=n(X),this.#G=Y;let J=e4();this.#Y=(W)=>X.executor.compileQuery(W,J)}get isCommitted(){return this.#G.isCommitted}get isRolledBack(){return this.#G.isRolledBack}commit(){return FI(this.#G),new Qc(async()=>{await this.#X.driver.commitTransaction(this.#X.connection.connection),this.#G.isCommitted=!0,this.#X.connection.release()})}rollback(){return FI(this.#G),new Qc(async()=>{await this.#X.driver.rollbackTransaction(this.#X.connection.connection),this.#G.isRolledBack=!0,this.#X.connection.release()})}savepoint(X){return FI(this.#G),new Qc(async()=>{return await this.#X.driver.savepoint?.(this.#X.connection.connection,X,this.#Y),new qO({...this.#X})})}rollbackToSavepoint(X){return FI(this.#G),new Qc(async()=>{return await this.#X.driver.rollbackToSavepoint?.(this.#X.connection.connection,X,this.#Y),new qO({...this.#X})})}releaseSavepoint(X){return FI(this.#G),new Qc(async()=>{return await this.#X.driver.releaseSavepoint?.(this.#X.connection.connection,X,this.#Y),new qO({...this.#X})})}withPlugin(X){return new qO({...this.#X,executor:this.#X.executor.withPlugin(X)})}withoutPlugins(){return new qO({...this.#X,executor:this.#X.executor.withoutPlugins()})}withSchema(X){return new qO({...this.#X,executor:this.#X.executor.withPluginAtFront(new eW(X))})}withTables(){return new qO({...this.#X})}}});var Tm0=()=>{};var Im0=()=>{};var Vm0=()=>{};var jm0=()=>{};var Mm0=()=>{};class V11{#X;constructor(X){this.#X=n(X)}get expressionType(){return}get isRawBuilder(){return!0}as(X){return new Rm0(this,X)}$castTo(){return new V11({...this.#X})}$notNull(){return new V11(this.#X)}withPlugin(X){return new V11({...this.#X,plugins:this.#X.plugins!==void 0?n([...this.#X.plugins,X]):n([X])})}toOperationNode(){return this.#G(this.#Y())}compile(X){return this.#Q(this.#Y(X))}async execute(X){let Y=this.#Y(X);return Y.executeQuery(this.#Q(Y))}#Y(X){let Y=X!==void 0?X.getExecutor():YE;return this.#X.plugins!==void 0?Y.withPlugins(this.#X.plugins):Y}#G(X){return X.transformQuery(this.#X.rawNode,this.#X.queryId)}#Q(X){return X.compileQuery(this.#G(X),this.#X.queryId)}}function TO(X){return new V11(X)}class Rm0{#X;#Y;constructor(X,Y){this.#X=X,this.#Y=Y}get expression(){return this.#X}get alias(){return this.#Y}get rawBuilder(){return this.#X}toOperationNode(){return VG.create(this.#X.toOperationNode(),R7(this.#Y)?this.#Y.toOperationNode():k4.create(this.#Y))}}var pt1=D(()=>{ZF();W0();md();U7();f3()});function Sm0(X){if(R7(X))return X.toOperationNode();return d9(X)}var O1;var WE=D(()=>{U7();f3();EK();wN();OQ();LQ();LN();AN();pt1();O1=Object.assign((X,...Y)=>{return TO({queryId:e4(),rawNode:f5.create(X,Y?.map(Sm0)??[])})},{ref(X){return TO({queryId:e4(),rawNode:f5.createWithChild(aW(X))})},val(X){return TO({queryId:e4(),rawNode:f5.createWithChild(d9(X))})},value(X){return this.val(X)},table(X){return TO({queryId:e4(),rawNode:f5.createWithChild(b5(X))})},id(...X){let Y=Array(X.length+1).fill(".");return Y[0]="",Y[Y.length-1]="",TO({queryId:e4(),rawNode:f5.create(Y,X.map(k4.create))})},lit(X){return TO({queryId:e4(),rawNode:f5.createWithChild(kY.createImmediate(X))})},literal(X){return this.lit(X)},raw(X){return TO({queryId:e4(),rawNode:f5.createWithSql(X)})},join(X,Y=O1`, `){let G=Array(Math.max(2*X.length-1,0)),Q=Y.toOperationNode();for(let J=0;J<X.length;++J)if(G[2*J]=Sm0(X[J]),J!==X.length-1)G[2*J+1]=Q;return TO({queryId:e4(),rawNode:f5.createWithChildren(G)})}})});var Cm0=()=>{};var km0=()=>{};class nt1{nodeStack=[];get parentNode(){return this.nodeStack[this.nodeStack.length-2]}#X=n({AliasNode:this.visitAlias.bind(this),ColumnNode:this.visitColumn.bind(this),IdentifierNode:this.visitIdentifier.bind(this),SchemableIdentifierNode:this.visitSchemableIdentifier.bind(this),RawNode:this.visitRaw.bind(this),ReferenceNode:this.visitReference.bind(this),SelectQueryNode:this.visitSelectQuery.bind(this),SelectionNode:this.visitSelection.bind(this),TableNode:this.visitTable.bind(this),FromNode:this.visitFrom.bind(this),SelectAllNode:this.visitSelectAll.bind(this),AndNode:this.visitAnd.bind(this),OrNode:this.visitOr.bind(this),ValueNode:this.visitValue.bind(this),ValueListNode:this.visitValueList.bind(this),PrimitiveValueListNode:this.visitPrimitiveValueList.bind(this),ParensNode:this.visitParens.bind(this),JoinNode:this.visitJoin.bind(this),OperatorNode:this.visitOperator.bind(this),WhereNode:this.visitWhere.bind(this),InsertQueryNode:this.visitInsertQuery.bind(this),DeleteQueryNode:this.visitDeleteQuery.bind(this),ReturningNode:this.visitReturning.bind(this),CreateTableNode:this.visitCreateTable.bind(this),AddColumnNode:this.visitAddColumn.bind(this),ColumnDefinitionNode:this.visitColumnDefinition.bind(this),DropTableNode:this.visitDropTable.bind(this),DataTypeNode:this.visitDataType.bind(this),OrderByNode:this.visitOrderBy.bind(this),OrderByItemNode:this.visitOrderByItem.bind(this),GroupByNode:this.visitGroupBy.bind(this),GroupByItemNode:this.visitGroupByItem.bind(this),UpdateQueryNode:this.visitUpdateQuery.bind(this),ColumnUpdateNode:this.visitColumnUpdate.bind(this),LimitNode:this.visitLimit.bind(this),OffsetNode:this.visitOffset.bind(this),OnConflictNode:this.visitOnConflict.bind(this),OnDuplicateKeyNode:this.visitOnDuplicateKey.bind(this),CreateIndexNode:this.visitCreateIndex.bind(this),DropIndexNode:this.visitDropIndex.bind(this),ListNode:this.visitList.bind(this),PrimaryKeyConstraintNode:this.visitPrimaryKeyConstraint.bind(this),UniqueConstraintNode:this.visitUniqueConstraint.bind(this),ReferencesNode:this.visitReferences.bind(this),CheckConstraintNode:this.visitCheckConstraint.bind(this),WithNode:this.visitWith.bind(this),CommonTableExpressionNode:this.visitCommonTableExpression.bind(this),CommonTableExpressionNameNode:this.visitCommonTableExpressionName.bind(this),HavingNode:this.visitHaving.bind(this),CreateSchemaNode:this.visitCreateSchema.bind(this),DropSchemaNode:this.visitDropSchema.bind(this),AlterTableNode:this.visitAlterTable.bind(this),DropColumnNode:this.visitDropColumn.bind(this),RenameColumnNode:this.visitRenameColumn.bind(this),AlterColumnNode:this.visitAlterColumn.bind(this),ModifyColumnNode:this.visitModifyColumn.bind(this),AddConstraintNode:this.visitAddConstraint.bind(this),DropConstraintNode:this.visitDropConstraint.bind(this),RenameConstraintNode:this.visitRenameConstraint.bind(this),ForeignKeyConstraintNode:this.visitForeignKeyConstraint.bind(this),CreateViewNode:this.visitCreateView.bind(this),RefreshMaterializedViewNode:this.visitRefreshMaterializedView.bind(this),DropViewNode:this.visitDropView.bind(this),GeneratedNode:this.visitGenerated.bind(this),DefaultValueNode:this.visitDefaultValue.bind(this),OnNode:this.visitOn.bind(this),ValuesNode:this.visitValues.bind(this),SelectModifierNode:this.visitSelectModifier.bind(this),CreateTypeNode:this.visitCreateType.bind(this),DropTypeNode:this.visitDropType.bind(this),ExplainNode:this.visitExplain.bind(this),DefaultInsertValueNode:this.visitDefaultInsertValue.bind(this),AggregateFunctionNode:this.visitAggregateFunction.bind(this),OverNode:this.visitOver.bind(this),PartitionByNode:this.visitPartitionBy.bind(this),PartitionByItemNode:this.visitPartitionByItem.bind(this),SetOperationNode:this.visitSetOperation.bind(this),BinaryOperationNode:this.visitBinaryOperation.bind(this),UnaryOperationNode:this.visitUnaryOperation.bind(this),UsingNode:this.visitUsing.bind(this),FunctionNode:this.visitFunction.bind(this),CaseNode:this.visitCase.bind(this),WhenNode:this.visitWhen.bind(this),JSONReferenceNode:this.visitJSONReference.bind(this),JSONPathNode:this.visitJSONPath.bind(this),JSONPathLegNode:this.visitJSONPathLeg.bind(this),JSONOperatorChainNode:this.visitJSONOperatorChain.bind(this),TupleNode:this.visitTuple.bind(this),MergeQueryNode:this.visitMergeQuery.bind(this),MatchedNode:this.visitMatched.bind(this),AddIndexNode:this.visitAddIndex.bind(this),CastNode:this.visitCast.bind(this),FetchNode:this.visitFetch.bind(this),TopNode:this.visitTop.bind(this),OutputNode:this.visitOutput.bind(this),OrActionNode:this.visitOrAction.bind(this),CollateNode:this.visitCollate.bind(this)});visitNode=(X)=>{this.nodeStack.push(X),this.#X[X.kind](X),this.nodeStack.pop()}}var at1=D(()=>{W0()});var dO8,EQ,cO8,vm0,iO8;var NI=D(()=>{Ad();eT();at1();aL();Cd();EK();W0();T11();KK1();XI();me();dO8=/'/g;EQ=class EQ extends nt1{#X="";#Y=[];get numParameters(){return this.#Y.length}compileQuery(X,Y){return this.#X="",this.#Y=[],this.nodeStack.splice(0,this.nodeStack.length),this.visitNode(X),n({query:X,queryId:Y,sql:this.getSql(),parameters:[...this.#Y]})}getSql(){return this.#X}visitSelectQuery(X){let Y=this.parentNode!==void 0&&!rW.is(this.parentNode)&&!xX.is(this.parentNode)&&!wJ.is(this.parentNode)&&!EF.is(this.parentNode)&&!$K1.is(this.parentNode);if(this.parentNode===void 0&&X.explain)this.visitNode(X.explain),this.append(" ");if(Y)this.append("(");if(X.with)this.visitNode(X.with),this.append(" ");if(this.append("select"),X.distinctOn)this.append(" "),this.compileDistinctOn(X.distinctOn);if(X.frontModifiers?.length)this.append(" "),this.compileList(X.frontModifiers," ");if(X.top)this.append(" "),this.visitNode(X.top);if(X.selections)this.append(" "),this.compileList(X.selections);if(X.from)this.append(" "),this.visitNode(X.from);if(X.joins)this.append(" "),this.compileList(X.joins," ");if(X.where)this.append(" "),this.visitNode(X.where);if(X.groupBy)this.append(" "),this.visitNode(X.groupBy);if(X.having)this.append(" "),this.visitNode(X.having);if(X.setOperations)this.append(" "),this.compileList(X.setOperations," ");if(X.orderBy)this.append(" "),this.visitNode(X.orderBy);if(X.limit)this.append(" "),this.visitNode(X.limit);if(X.offset)this.append(" "),this.visitNode(X.offset);if(X.fetch)this.append(" "),this.visitNode(X.fetch);if(X.endModifiers?.length)this.append(" "),this.compileList(this.sortSelectModifiers([...X.endModifiers])," ");if(Y)this.append(")")}visitFrom(X){this.append("from "),this.compileList(X.froms)}visitSelection(X){this.visitNode(X.selection)}visitColumn(X){this.visitNode(X.column)}compileDistinctOn(X){this.append("distinct on ("),this.compileList(X),this.append(")")}compileList(X,Y=", "){let G=X.length-1;for(let Q=0;Q<=G;Q++)if(this.visitNode(X[Q]),Q<G)this.append(Y)}visitWhere(X){this.append("where "),this.visitNode(X.where)}visitHaving(X){this.append("having "),this.visitNode(X.having)}visitInsertQuery(X){let Y=this.parentNode!==void 0&&!rW.is(this.parentNode)&&!f5.is(this.parentNode)&&!qK.is(this.parentNode);if(this.parentNode===void 0&&X.explain)this.visitNode(X.explain),this.append(" ");if(Y)this.append("(");if(X.with)this.visitNode(X.with),this.append(" ");if(this.append(X.replace?"replace":"insert"),X.ignore)ON("`InsertQueryNode.ignore` is deprecated. Use `InsertQueryNode.orAction` instead."),this.append(" ignore");if(X.orAction)this.append(" "),this.visitNode(X.orAction);if(X.top)this.append(" "),this.visitNode(X.top);if(X.into)this.append(" into "),this.visitNode(X.into);if(X.columns)this.append(" ("),this.compileList(X.columns),this.append(")");if(X.output)this.append(" "),this.visitNode(X.output);if(X.values)this.append(" "),this.visitNode(X.values);if(X.defaultValues)this.append(" "),this.append("default values");if(X.onConflict)this.append(" "),this.visitNode(X.onConflict);if(X.onDuplicateKey)this.append(" "),this.visitNode(X.onDuplicateKey);if(X.returning)this.append(" "),this.visitNode(X.returning);if(Y)this.append(")");if(X.endModifiers?.length)this.append(" "),this.compileList(X.endModifiers," ")}visitValues(X){this.append("values "),this.compileList(X.values)}visitDeleteQuery(X){let Y=this.parentNode!==void 0&&!rW.is(this.parentNode)&&!f5.is(this.parentNode);if(this.parentNode===void 0&&X.explain)this.visitNode(X.explain),this.append(" ");if(Y)this.append("(");if(X.with)this.visitNode(X.with),this.append(" ");if(this.append("delete "),X.top)this.visitNode(X.top),this.append(" ");if(this.visitNode(X.from),X.output)this.append(" "),this.visitNode(X.output);if(X.using)this.append(" "),this.visitNode(X.using);if(X.joins)this.append(" "),this.compileList(X.joins," ");if(X.where)this.append(" "),this.visitNode(X.where);if(X.orderBy)this.append(" "),this.visitNode(X.orderBy);if(X.limit)this.append(" "),this.visitNode(X.limit);if(X.returning)this.append(" "),this.visitNode(X.returning);if(Y)this.append(")");if(X.endModifiers?.length)this.append(" "),this.compileList(X.endModifiers," ")}visitReturning(X){this.append("returning "),this.compileList(X.selections)}visitAlias(X){this.visitNode(X.node),this.append(" as "),this.visitNode(X.alias)}visitReference(X){if(X.table)this.visitNode(X.table),this.append(".");this.visitNode(X.column)}visitSelectAll(X){this.append("*")}visitIdentifier(X){this.append(this.getLeftIdentifierWrapper()),this.compileUnwrappedIdentifier(X),this.append(this.getRightIdentifierWrapper())}compileUnwrappedIdentifier(X){if(!H9(X.name))throw Error("a non-string identifier was passed to compileUnwrappedIdentifier.");this.append(this.sanitizeIdentifier(X.name))}visitAnd(X){this.visitNode(X.left),this.append(" and "),this.visitNode(X.right)}visitOr(X){this.visitNode(X.left),this.append(" or "),this.visitNode(X.right)}visitValue(X){if(X.immediate)this.appendImmediateValue(X.value);else this.appendValue(X.value)}visitValueList(X){this.append("("),this.compileList(X.values),this.append(")")}visitTuple(X){this.append("("),this.compileList(X.values),this.append(")")}visitPrimitiveValueList(X){this.append("(");let{values:Y}=X;for(let G=0;G<Y.length;++G)if(this.appendValue(Y[G]),G!==Y.length-1)this.append(", ");this.append(")")}visitParens(X){this.append("("),this.visitNode(X.node),this.append(")")}visitJoin(X){if(this.append(iO8[X.joinType]),this.append(" "),this.visitNode(X.table),X.on)this.append(" "),this.visitNode(X.on)}visitOn(X){this.append("on "),this.visitNode(X.on)}visitRaw(X){let{sqlFragments:Y,parameters:G}=X;for(let Q=0;Q<Y.length;++Q)if(this.append(Y[Q]),G.length>Q)this.visitNode(G[Q])}visitOperator(X){this.append(X.operator)}visitTable(X){this.visitNode(X.table)}visitSchemableIdentifier(X){if(X.schema)this.visitNode(X.schema),this.append(".");this.visitNode(X.identifier)}visitCreateTable(X){if(this.append("create "),X.frontModifiers?.length)this.compileList(X.frontModifiers," "),this.append(" ");if(X.temporary)this.append("temporary ");if(this.append("table "),X.ifNotExists)this.append("if not exists ");if(this.visitNode(X.table),!X.selectQuery)this.append(" ("),this.compileList([...X.columns,...X.constraints??[]]),this.append(")");if(X.onCommit)this.append(" on commit "),this.append(X.onCommit);if(X.endModifiers?.length)this.append(" "),this.compileList(X.endModifiers," ");if(X.selectQuery)this.append(" as "),this.visitNode(X.selectQuery)}visitColumnDefinition(X){if(X.ifNotExists)this.append("if not exists ");if(this.visitNode(X.column),this.append(" "),this.visitNode(X.dataType),X.unsigned)this.append(" unsigned");if(X.frontModifiers&&X.frontModifiers.length>0)this.append(" "),this.compileList(X.frontModifiers," ");if(X.generated)this.append(" "),this.visitNode(X.generated);if(X.identity)this.append(" identity");if(X.defaultTo)this.append(" "),this.visitNode(X.defaultTo);if(X.notNull)this.append(" not null");if(X.unique)this.append(" unique");if(X.nullsNotDistinct)this.append(" nulls not distinct");if(X.primaryKey)this.append(" primary key");if(X.autoIncrement)this.append(" "),this.append(this.getAutoIncrement());if(X.references)this.append(" "),this.visitNode(X.references);if(X.check)this.append(" "),this.visitNode(X.check);if(X.endModifiers&&X.endModifiers.length>0)this.append(" "),this.compileList(X.endModifiers," ")}getAutoIncrement(){return"auto_increment"}visitReferences(X){if(this.append("references "),this.visitNode(X.table),this.append(" ("),this.compileList(X.columns),this.append(")"),X.onDelete)this.append(" on delete "),this.append(X.onDelete);if(X.onUpdate)this.append(" on update "),this.append(X.onUpdate)}visitDropTable(X){if(this.append("drop table "),X.ifExists)this.append("if exists ");if(this.visitNode(X.table),X.cascade)this.append(" cascade")}visitDataType(X){this.append(X.dataType)}visitOrderBy(X){this.append("order by "),this.compileList(X.items)}visitOrderByItem(X){if(this.visitNode(X.orderBy),X.collation)this.append(" "),this.visitNode(X.collation);if(X.direction)this.append(" "),this.visitNode(X.direction);if(X.nulls)this.append(" nulls "),this.append(X.nulls)}visitGroupBy(X){this.append("group by "),this.compileList(X.items)}visitGroupByItem(X){this.visitNode(X.groupBy)}visitUpdateQuery(X){let Y=this.parentNode!==void 0&&!rW.is(this.parentNode)&&!f5.is(this.parentNode)&&!qK.is(this.parentNode);if(this.parentNode===void 0&&X.explain)this.visitNode(X.explain),this.append(" ");if(Y)this.append("(");if(X.with)this.visitNode(X.with),this.append(" ");if(this.append("update "),X.top)this.visitNode(X.top),this.append(" ");if(X.table)this.visitNode(X.table),this.append(" ");if(this.append("set "),X.updates)this.compileList(X.updates);if(X.output)this.append(" "),this.visitNode(X.output);if(X.from)this.append(" "),this.visitNode(X.from);if(X.joins){if(!X.from)throw Error("Joins in an update query are only supported as a part of a PostgreSQL 'update set from join' query. If you want to create a MySQL 'update join set' query, see https://kysely.dev/docs/examples/update/my-sql-joins");this.append(" "),this.compileList(X.joins," ")}if(X.where)this.append(" "),this.visitNode(X.where);if(X.returning)this.append(" "),this.visitNode(X.returning);if(X.orderBy)this.append(" "),this.visitNode(X.orderBy);if(X.limit)this.append(" "),this.visitNode(X.limit);if(Y)this.append(")");if(X.endModifiers?.length)this.append(" "),this.compileList(X.endModifiers," ")}visitColumnUpdate(X){this.visitNode(X.column),this.append(" = "),this.visitNode(X.value)}visitLimit(X){this.append("limit "),this.visitNode(X.limit)}visitOffset(X){this.append("offset "),this.visitNode(X.offset)}visitOnConflict(X){if(this.append("on conflict"),X.columns)this.append(" ("),this.compileList(X.columns),this.append(")");else if(X.constraint)this.append(" on constraint "),this.visitNode(X.constraint);else if(X.indexExpression)this.append(" ("),this.visitNode(X.indexExpression),this.append(")");if(X.indexWhere)this.append(" "),this.visitNode(X.indexWhere);if(X.doNothing===!0)this.append(" do nothing");else if(X.updates){if(this.append(" do update set "),this.compileList(X.updates),X.updateWhere)this.append(" "),this.visitNode(X.updateWhere)}}visitOnDuplicateKey(X){this.append("on duplicate key update "),this.compileList(X.updates)}visitCreateIndex(X){if(this.append("create "),X.unique)this.append("unique ");if(this.append("index "),X.ifNotExists)this.append("if not exists ");if(this.visitNode(X.name),X.table)this.append(" on "),this.visitNode(X.table);if(X.using)this.append(" using "),this.visitNode(X.using);if(X.columns)this.append(" ("),this.compileList(X.columns),this.append(")");if(X.nullsNotDistinct)this.append(" nulls not distinct");if(X.where)this.append(" "),this.visitNode(X.where)}visitDropIndex(X){if(this.append("drop index "),X.ifExists)this.append("if exists ");if(this.visitNode(X.name),X.table)this.append(" on "),this.visitNode(X.table);if(X.cascade)this.append(" cascade")}visitCreateSchema(X){if(this.append("create schema "),X.ifNotExists)this.append("if not exists ");this.visitNode(X.schema)}visitDropSchema(X){if(this.append("drop schema "),X.ifExists)this.append("if exists ");if(this.visitNode(X.schema),X.cascade)this.append(" cascade")}visitPrimaryKeyConstraint(X){if(X.name)this.append("constraint "),this.visitNode(X.name),this.append(" ");this.append("primary key ("),this.compileList(X.columns),this.append(")"),this.buildDeferrable(X)}buildDeferrable(X){if(X.deferrable!==void 0)if(X.deferrable)this.append(" deferrable");else this.append(" not deferrable");if(X.initiallyDeferred!==void 0)if(X.initiallyDeferred)this.append(" initially deferred");else this.append(" initially immediate")}visitUniqueConstraint(X){if(X.name)this.append("constraint "),this.visitNode(X.name),this.append(" ");if(this.append("unique"),X.nullsNotDistinct)this.append(" nulls not distinct");this.append(" ("),this.compileList(X.columns),this.append(")"),this.buildDeferrable(X)}visitCheckConstraint(X){if(X.name)this.append("constraint "),this.visitNode(X.name),this.append(" ");this.append("check ("),this.visitNode(X.expression),this.append(")")}visitForeignKeyConstraint(X){if(X.name)this.append("constraint "),this.visitNode(X.name),this.append(" ");if(this.append("foreign key ("),this.compileList(X.columns),this.append(") "),this.visitNode(X.references),X.onDelete)this.append(" on delete "),this.append(X.onDelete);if(X.onUpdate)this.append(" on update "),this.append(X.onUpdate);this.buildDeferrable(X)}visitList(X){this.compileList(X.items)}visitWith(X){if(this.append("with "),X.recursive)this.append("recursive ");this.compileList(X.expressions)}visitCommonTableExpression(X){if(this.visitNode(X.name),this.append(" as "),UO(X.materialized)){if(!X.materialized)this.append("not ");this.append("materialized ")}this.visitNode(X.expression)}visitCommonTableExpressionName(X){if(this.visitNode(X.table),X.columns)this.append("("),this.compileList(X.columns),this.append(")")}visitAlterTable(X){if(this.append("alter table "),this.visitNode(X.table),this.append(" "),X.renameTo)this.append("rename to "),this.visitNode(X.renameTo);if(X.setSchema)this.append("set schema "),this.visitNode(X.setSchema);if(X.addConstraint)this.visitNode(X.addConstraint);if(X.dropConstraint)this.visitNode(X.dropConstraint);if(X.renameConstraint)this.visitNode(X.renameConstraint);if(X.columnAlterations)this.compileColumnAlterations(X.columnAlterations);if(X.addIndex)this.visitNode(X.addIndex);if(X.dropIndex)this.visitNode(X.dropIndex)}visitAddColumn(X){this.append("add column "),this.visitNode(X.column)}visitRenameColumn(X){this.append("rename column "),this.visitNode(X.column),this.append(" to "),this.visitNode(X.renameTo)}visitDropColumn(X){this.append("drop column "),this.visitNode(X.column)}visitAlterColumn(X){if(this.append("alter column "),this.visitNode(X.column),this.append(" "),X.dataType){if(this.announcesNewColumnDataType())this.append("type ");if(this.visitNode(X.dataType),X.dataTypeExpression)this.append("using "),this.visitNode(X.dataTypeExpression)}if(X.setDefault)this.append("set default "),this.visitNode(X.setDefault);if(X.dropDefault)this.append("drop default");if(X.setNotNull)this.append("set not null");if(X.dropNotNull)this.append("drop not null")}visitModifyColumn(X){this.append("modify column "),this.visitNode(X.column)}visitAddConstraint(X){this.append("add "),this.visitNode(X.constraint)}visitDropConstraint(X){if(this.append("drop constraint "),X.ifExists)this.append("if exists ");if(this.visitNode(X.constraintName),X.modifier==="cascade")this.append(" cascade");else if(X.modifier==="restrict")this.append(" restrict")}visitRenameConstraint(X){this.append("rename constraint "),this.visitNode(X.oldName),this.append(" to "),this.visitNode(X.newName)}visitSetOperation(X){if(this.append(X.operator),this.append(" "),X.all)this.append("all ");this.visitNode(X.expression)}visitCreateView(X){if(this.append("create "),X.orReplace)this.append("or replace ");if(X.materialized)this.append("materialized ");if(X.temporary)this.append("temporary ");if(this.append("view "),X.ifNotExists)this.append("if not exists ");if(this.visitNode(X.name),this.append(" "),X.columns)this.append("("),this.compileList(X.columns),this.append(") ");if(X.as)this.append("as "),this.visitNode(X.as)}visitRefreshMaterializedView(X){if(this.append("refresh materialized view "),X.concurrently)this.append("concurrently ");if(this.visitNode(X.name),X.withNoData)this.append(" with no data");else this.append(" with data")}visitDropView(X){if(this.append("drop "),X.materialized)this.append("materialized ");if(this.append("view "),X.ifExists)this.append("if exists ");if(this.visitNode(X.name),X.cascade)this.append(" cascade")}visitGenerated(X){if(this.append("generated "),X.always)this.append("always ");if(X.byDefault)this.append("by default ");if(this.append("as "),X.identity)this.append("identity");if(X.expression)this.append("("),this.visitNode(X.expression),this.append(")");if(X.stored)this.append(" stored")}visitDefaultValue(X){this.append("default "),this.visitNode(X.defaultValue)}visitSelectModifier(X){if(X.rawModifier)this.visitNode(X.rawModifier);else this.append(cO8[X.modifier]);if(X.of)this.append(" of "),this.compileList(X.of,", ")}visitCreateType(X){if(this.append("create type "),this.visitNode(X.name),X.enum)this.append(" as enum "),this.visitNode(X.enum)}visitDropType(X){if(this.append("drop type "),X.ifExists)this.append("if exists ");this.visitNode(X.name)}visitExplain(X){if(this.append("explain"),X.options||X.format){if(this.append(" "),this.append(this.getLeftExplainOptionsWrapper()),X.options){if(this.visitNode(X.options),X.format)this.append(this.getExplainOptionsDelimiter())}if(X.format)this.append("format"),this.append(this.getExplainOptionAssignment()),this.append(X.format);this.append(this.getRightExplainOptionsWrapper())}}visitDefaultInsertValue(X){this.append("default")}visitAggregateFunction(X){if(this.append(X.func),this.append("("),X.distinct)this.append("distinct ");if(this.compileList(X.aggregated),X.orderBy)this.append(" "),this.visitNode(X.orderBy);if(this.append(")"),X.withinGroup)this.append(" within group ("),this.visitNode(X.withinGroup),this.append(")");if(X.filter)this.append(" filter("),this.visitNode(X.filter),this.append(")");if(X.over)this.append(" "),this.visitNode(X.over)}visitOver(X){if(this.append("over("),X.partitionBy){if(this.visitNode(X.partitionBy),X.orderBy)this.append(" ")}if(X.orderBy)this.visitNode(X.orderBy);this.append(")")}visitPartitionBy(X){this.append("partition by "),this.compileList(X.items)}visitPartitionByItem(X){this.visitNode(X.partitionBy)}visitBinaryOperation(X){this.visitNode(X.leftOperand),this.append(" "),this.visitNode(X.operator),this.append(" "),this.visitNode(X.rightOperand)}visitUnaryOperation(X){if(this.visitNode(X.operator),!this.isMinusOperator(X.operator))this.append(" ");this.visitNode(X.operand)}isMinusOperator(X){return PZ.is(X)&&X.operator==="-"}visitUsing(X){this.append("using "),this.compileList(X.tables)}visitFunction(X){this.append(X.func),this.append("("),this.compileList(X.arguments),this.append(")")}visitCase(X){if(this.append("case"),X.value)this.append(" "),this.visitNode(X.value);if(X.when)this.append(" "),this.compileList(X.when," ");if(X.else)this.append(" else "),this.visitNode(X.else);if(this.append(" end"),X.isStatement)this.append(" case")}visitWhen(X){if(this.append("when "),this.visitNode(X.condition),X.result)this.append(" then "),this.visitNode(X.result)}visitJSONReference(X){this.visitNode(X.reference),this.visitNode(X.traversal)}visitJSONPath(X){if(X.inOperator)this.visitNode(X.inOperator);this.append("'$");for(let Y of X.pathLegs)this.visitNode(Y);this.append("'")}visitJSONPathLeg(X){let Y=X.type==="ArrayLocation";if(this.append(Y?"[":"."),this.append(typeof X.value==="string"?this.sanitizeStringLiteral(X.value):String(X.value)),Y)this.append("]")}visitJSONOperatorChain(X){for(let Y=0,G=X.values.length;Y<G;Y++){if(Y===G-1)this.visitNode(X.operator);else this.append("->");this.visitNode(X.values[Y])}}visitMergeQuery(X){if(X.with)this.visitNode(X.with),this.append(" ");if(this.append("merge "),X.top)this.visitNode(X.top),this.append(" ");if(this.append("into "),this.visitNode(X.into),X.using)this.append(" "),this.visitNode(X.using);if(X.whens)this.append(" "),this.compileList(X.whens," ");if(X.returning)this.append(" "),this.visitNode(X.returning);if(X.output)this.append(" "),this.visitNode(X.output);if(X.endModifiers?.length)this.append(" "),this.compileList(X.endModifiers," ")}visitMatched(X){if(X.not)this.append("not ");if(this.append("matched"),X.bySource)this.append(" by source")}visitAddIndex(X){if(this.append("add "),X.unique)this.append("unique ");if(this.append("index "),this.visitNode(X.name),X.columns)this.append(" ("),this.compileList(X.columns),this.append(")");if(X.using)this.append(" using "),this.visitNode(X.using)}visitCast(X){this.append("cast("),this.visitNode(X.expression),this.append(" as "),this.visitNode(X.dataType),this.append(")")}visitFetch(X){this.append("fetch next "),this.visitNode(X.rowCount),this.append(` rows ${X.modifier}`)}visitOutput(X){this.append("output "),this.compileList(X.selections)}visitTop(X){if(this.append(`top(${X.expression})`),X.modifiers)this.append(` ${X.modifiers}`)}visitOrAction(X){this.append(X.action)}visitCollate(X){this.append("collate "),this.visitNode(X.collation)}append(X){this.#X+=X}appendValue(X){this.addParameter(X),this.append(this.getCurrentParameterPlaceholder())}getLeftIdentifierWrapper(){return'"'}getRightIdentifierWrapper(){return'"'}getCurrentParameterPlaceholder(){return"$"+this.numParameters}getLeftExplainOptionsWrapper(){return"("}getExplainOptionAssignment(){return" "}getExplainOptionsDelimiter(){return", "}getRightExplainOptionsWrapper(){return")"}sanitizeIdentifier(X){let Y=this.getLeftIdentifierWrapper(),G=this.getRightIdentifierWrapper(),Q="";for(let J of X)if(Q+=J,J===Y)Q+=Y;else if(J===G)Q+=G;return Q}sanitizeStringLiteral(X){return X.replace(dO8,"''")}addParameter(X){this.#Y.push(X)}appendImmediateValue(X){if(H9(X))this.appendStringLiteral(X);else if(QF(X)||UO(X)||cL(X))this.append(X.toString());else if(dL(X))this.append("null");else if(qd(X))this.appendImmediateValue(X.toISOString());else throw Error(`invalid immediate value ${X}`)}appendStringLiteral(X){this.append("'"),this.append(this.sanitizeStringLiteral(X)),this.append("'")}sortSelectModifiers(X){return X.sort((Y,G)=>Y.modifier&&G.modifier?vm0[Y.modifier]-vm0[G.modifier]:1),n(X)}compileColumnAlterations(X){this.compileList(X)}announcesNewColumnDataType(){return!0}};cO8=n({ForKeyShare:"for key share",ForNoKeyUpdate:"for no key update",ForUpdate:"for update",ForShare:"for share",NoWait:"nowait",SkipLocked:"skip locked",Distinct:"distinct"}),vm0=n({ForKeyShare:1,ForNoKeyUpdate:1,ForUpdate:1,ForShare:1,NoWait:2,SkipLocked:2,Distinct:0}),iO8=n({InnerJoin:"inner join",LeftJoin:"left join",RightJoin:"right join",FullJoin:"full join",CrossJoin:"cross join",LateralInnerJoin:"inner join lateral",LateralLeftJoin:"left join lateral",LateralCrossJoin:"cross join lateral",OuterApply:"outer apply",CrossApply:"cross apply",Using:"using"})});var B9;var Jc=D(()=>{EK();W0();AN();B9=n({raw(X,Y=[]){return n({sql:X,query:f5.createWithSql(X),parameters:n(Y),queryId:e4()})}})});var _m0=()=>{};var fm0=()=>{};var bm0=()=>{};var ym0=()=>{};class IO{get supportsCreateIfNotExists(){return!0}get supportsTransactionalDdl(){return!1}get supportsReturning(){return!1}get supportsOutput(){return!1}}var xm0=()=>{};function TK(X,Y){return f5.createWithChildren([f5.createWithSql(`${X} `),k4.create(Y)])}var xK1=D(()=>{U7();EK()});class tt1{#X;#Y=new gm0;#G;#Q;constructor(X){this.#X=n({...X})}async init(){if(this.#G=F9(this.#X.database)?await this.#X.database():this.#X.database,this.#Q=new hm0(this.#G),this.#X.onCreateConnection)await this.#X.onCreateConnection(this.#Q)}async acquireConnection(){return await this.#Y.lock(),this.#Q}async beginTransaction(X){await X.executeQuery(B9.raw("begin"))}async commitTransaction(X){await X.executeQuery(B9.raw("commit"))}async rollbackTransaction(X){await X.executeQuery(B9.raw("rollback"))}async savepoint(X,Y,G){await X.executeQuery(G(TK("savepoint",Y),e4()))}async rollbackToSavepoint(X,Y,G){await X.executeQuery(G(TK("rollback to",Y),e4()))}async releaseSavepoint(X,Y,G){await X.executeQuery(G(TK("release",Y),e4()))}async releaseConnection(){this.#Y.unlock()}async destroy(){this.#G?.close()}}class hm0{#X;constructor(X){this.#X=X}executeQuery(X){let{sql:Y,parameters:G}=X,Q=this.#X.prepare(Y);if(Q.reader)return Promise.resolve({rows:Q.all(G)});let{changes:J,lastInsertRowid:W}=Q.run(G);return Promise.resolve({numAffectedRows:J!==void 0&&J!==null?BigInt(J):void 0,insertId:W!==void 0&&W!==null?BigInt(W):void 0,rows:[]})}async*streamQuery(X,Y){let{sql:G,parameters:Q,query:J}=X,W=this.#X.prepare(G);if(U9.is(J)){let Z=W.iterate(Q);for(let $ of Z)yield{rows:[$]}}else throw Error("Sqlite driver only supports streaming of select queries")}}class gm0{#X;#Y;async lock(){while(this.#X)await this.#X;this.#X=new Promise((X)=>{this.#Y=X})}unlock(){let X=this.#Y;this.#X=void 0,this.#Y=void 0,X?.()}}var rt1=D(()=>{YI();xK1();Jc();W0();AN()});var pO8,ot1;var st1=D(()=>{NI();pO8=/"/g;ot1=class ot1 extends EQ{visitOrAction(X){this.append("or "),this.append(X.action)}getCurrentParameterPlaceholder(){return"?"}getLeftExplainOptionsWrapper(){return""}getRightExplainOptionsWrapper(){return""}getLeftIdentifierWrapper(){return'"'}getRightIdentifierWrapper(){return'"'}getAutoIncrement(){return"autoincrement"}sanitizeIdentifier(X){return X.replace(pO8,'""')}visitDefaultInsertValue(X){this.append("null")}}});class et1{transformQuery(X){return X.node}async transformResult(X){return X.result}}class gK1{#X;constructor(X){this.#X=n(X)}async getMigrations(){let Y=await this.#F(this.#Q)?await this.#X.db.withPlugin(this.#$).selectFrom(this.#Q).select(["name","timestamp"]).$narrowType().execute():[];return(await this.#O()).map(({name:Q,...J})=>{let W=Y.find((Z)=>Z.name===Q);return{name:Q,migration:J,executedAt:W?new Date(W.timestamp):void 0}})}async migrateToLatest(){return this.#Y(()=>({direction:"Up",step:1/0}))}async migrateTo(X){return this.#Y(({migrations:Y,executedMigrations:G,pendingMigrations:Q})=>{if(F7(X)&&X.__noMigrations__===!0)return{direction:"Down",step:1/0};if(!Y.find((Z)=>Z.name===X))throw Error(`migration "${X}" doesn't exist`);let J=G.indexOf(X),W=Q.findIndex((Z)=>Z.name===X);if(J!==-1)return{direction:"Down",step:G.length-J-1};else if(W!==-1)return{direction:"Up",step:W+1};else throw Error(`migration "${X}" isn't executed or pending`)})}async migrateUp(){return this.#Y(()=>({direction:"Up",step:1}))}async migrateDown(){return this.#Y(()=>({direction:"Down",step:1}))}async#Y(X){try{return await this.#W(),await this.#K(),await this.#H(),await this.#U(),await this.#D(X)}catch(Y){if(Y instanceof hK1)return Y.resultSet;return{error:Y}}}get#G(){return this.#X.migrationTableSchema}get#Q(){return this.#X.migrationTableName??eY}get#J(){return this.#X.migrationLockTableName??RG}get#Z(){return this.#X.allowUnorderedMigrations??nO8}get#$(){if(this.#G)return new eW(this.#G);return new et1}async#W(){if(!this.#G)return;if(await this.#N())return;try{await this.#B(this.#X.db.schema.createSchema(this.#G))}catch(Y){if(!await this.#N())throw Y}}async#K(){if(await this.#F(this.#Q))return;try{await this.#B(this.#X.db.schema.withPlugin(this.#$).createTable(this.#Q).addColumn("name","varchar(255)",(Y)=>Y.notNull().primaryKey()).addColumn("timestamp","varchar(255)",(Y)=>Y.notNull()))}catch(Y){if(!await this.#F(this.#Q))throw Y}}async#H(){if(await this.#F(this.#J))return;try{await this.#B(this.#X.db.schema.withPlugin(this.#$).createTable(this.#J).addColumn("id","varchar(255)",(Y)=>Y.notNull().primaryKey()).addColumn("is_locked","integer",(Y)=>Y.notNull().defaultTo(0)))}catch(Y){if(!await this.#F(this.#J))throw Y}}async#U(){if(await this.#z())return;try{await this.#X.db.withPlugin(this.#$).insertInto(this.#J).values({id:Xr1,is_locked:0}).execute()}catch(Y){if(!await this.#z())throw Y}}async#N(){return(await this.#X.db.introspection.getSchemas()).some((Y)=>Y.name===this.#G)}async#F(X){let Y=this.#G;return(await this.#X.db.introspection.getTables({withInternalKyselyTables:!0})).some((Q)=>Q.name===X&&(!Y||Q.schema===Y))}async#z(){return!!await this.#X.db.withPlugin(this.#$).selectFrom(this.#J).where("id","=",Xr1).select("id").executeTakeFirst()}async#D(X){let Y=this.#X.db.getExecutor().adapter,G=n({lockTable:this.#X.migrationLockTableName??RG,lockRowId:Xr1,lockTableSchema:this.#X.migrationTableSchema}),Q=async(J)=>{try{await Y.acquireMigrationLock(J,G);let W=await this.#w(J);if(W.migrations.length===0)return{results:[]};let{direction:Z,step:$}=X(W);if($<=0)return{results:[]};if(Z==="Down")return await this.#A(J,W,$);else if(Z==="Up")return await this.#T(J,W,$);return{results:[]}}finally{await Y.releaseMigrationLock(J,G)}};if(Y.supportsTransactionalDdl&&!this.#X.disableTransactions)return this.#X.db.transaction().execute(Q);else return this.#X.db.connection().execute(Q)}async#w(X){let Y=await this.#O(),G=await this.#E(X);if(this.#P(Y,G),!this.#Z)this.#q(Y,G);let Q=this.#L(Y,G);return n({migrations:Y,executedMigrations:G,lastMigration:Yl0(G),pendingMigrations:Q})}#L(X,Y){return X.filter((G)=>{return!Y.includes(G.name)})}async#O(){let X=await this.#X.provider.getMigrations();return Object.keys(X).sort().map((Y)=>({...X[Y],name:Y}))}async#E(X){let Y=await X.withPlugin(this.#$).selectFrom(this.#Q).select(["name","timestamp"]).$narrowType().execute(),G=this.#X.nameComparator||((Q,J)=>Q.localeCompare(J));return Y.sort((Q,J)=>{if(Q.timestamp===J.timestamp)return G(Q.name,J.name);return new Date(Q.timestamp).getTime()-new Date(J.timestamp).getTime()}).map((Q)=>Q.name)}#P(X,Y){for(let G of Y)if(!X.some((Q)=>Q.name===G))throw Error(`corrupted migrations: previously executed migration ${G} is missing`)}#q(X,Y){for(let G=0;G<Y.length;++G)if(X[G].name!==Y[G])throw Error(`corrupted migrations: expected previously executed migration ${Y[G]} to be at index ${G} but ${X[G].name} was found in its place. New migrations must always have a name that comes alphabetically after the last executed migration.`)}async#A(X,Y,G){let Q=Y.executedMigrations.slice().reverse().slice(0,G).map((W)=>{return Y.migrations.find((Z)=>Z.name===W)}),J=Q.map((W)=>{return{migrationName:W.name,direction:"Down",status:"NotExecuted"}});for(let W=0;W<J.length;++W){let Z=Q[W];try{if(Z.down)await Z.down(X),await X.withPlugin(this.#$).deleteFrom(this.#Q).where("name","=",Z.name).execute(),J[W]={migrationName:Z.name,direction:"Down",status:"Success"}}catch($){throw J[W]={migrationName:Z.name,direction:"Down",status:"Error"},new hK1({error:$,results:J})}}return{results:J}}async#T(X,Y,G){let J=Y.pendingMigrations.slice(0,G).map((W)=>{return{migrationName:W.name,direction:"Up",status:"NotExecuted"}});for(let W=0;W<J.length;W++){let Z=Y.pendingMigrations[W];try{await Z.up(X),await X.withPlugin(this.#$).insertInto(this.#Q).values({name:Z.name,timestamp:new Date().toISOString()}).execute(),J[W]={migrationName:Z.name,direction:"Up",status:"Success"}}catch($){throw J[W]={migrationName:Z.name,direction:"Up",status:"Error"},new hK1({error:$,results:J})}}return{results:J}}async#B(X){if(this.#X.db.getExecutor().adapter.supportsCreateIfNotExists)X=X.ifNotExists();await X.execute()}}var eY="kysely_migration",RG="kysely_migration_lock",nO8=!1,Xr1="migration_lock",_I7,hK1;var BI=D(()=>{WI();W0();_I7=n({__noMigrations__:!0});hK1=class hK1 extends Error{#X;constructor(X){super();this.#X=X}get resultSet(){return this.#X}}});class Yr1{#X;constructor(X){this.#X=X}async getSchemas(){return[]}async getTables(X={withInternalKyselyTables:!1}){return await this.#G(X)}async getMetadata(X){return{tables:await this.getTables(X)}}#Y(X,Y){let G=X.selectFrom("sqlite_master").where("type","in",["table","view"]).where("name","not like","sqlite_%").select(["name","sql","type"]).orderBy("name");if(!Y.withInternalKyselyTables)G=G.where("name","!=",eY).where("name","!=",RG);return G}async#G(X){let Y=await this.#Y(this.#X,X).execute(),G=await this.#X.with("table_list",(J)=>this.#Y(J,X)).selectFrom(["table_list as tl",O1`pragma_table_info(tl.name)`.as("p")]).select(["tl.name as table","p.cid","p.name","p.type","p.notnull","p.dflt_value","p.pk"]).orderBy("tl.name").orderBy("p.cid").execute(),Q={};for(let J of G)Q[J.table]??=[],Q[J.table].push(J);return Y.map(({name:J,sql:W,type:Z})=>{let $=W?.split(/[\(\),]/)?.find((H)=>H.toLowerCase().includes("autoincrement"))?.trimStart()?.split(/\s+/)?.[0]?.replace(/["`]/g,""),K=Q[J]??[];if(!$){let H=K.filter((U)=>U.pk>0);if(H.length===1&&H[0].type.toLowerCase()==="integer")$=H[0].name}return{name:J,isView:Z==="view",columns:K.map((H)=>({name:H.name,dataType:H.type,isNullable:!H.notnull,isAutoIncrementing:H.name===$,hasDefaultValue:H.dflt_value!=null,comment:void 0}))}})}}var Gr1=D(()=>{BI();WE()});var Qr1;var Jr1=D(()=>{Qr1=class Qr1 extends IO{get supportsTransactionalDdl(){return!1}get supportsReturning(){return!0}async acquireMigrationLock(X,Y){}async releaseMigrationLock(X,Y){}}});class zI{#X;constructor(X){this.#X=n({...X})}createDriver(){return new tt1(this.#X)}createQueryCompiler(){return new ot1}createAdapter(){return new Qr1}createIntrospector(X){return new Yr1(X)}}var um0=D(()=>{rt1();st1();Gr1();Jr1();W0()});var lm0=()=>{};var aO8,Zr1;var Wr1=D(()=>{NI();aO8=/"/g;Zr1=class Zr1 extends EQ{sanitizeIdentifier(X){return X.replace(aO8,'""')}}});class $r1{#X;constructor(X){this.#X=X}async getSchemas(){return(await this.#X.selectFrom("pg_catalog.pg_namespace").select("nspname").$castTo().execute()).map((Y)=>({name:Y.nspname}))}async getTables(X={withInternalKyselyTables:!1}){let Y=this.#X.selectFrom("pg_catalog.pg_attribute as a").innerJoin("pg_catalog.pg_class as c","a.attrelid","c.oid").innerJoin("pg_catalog.pg_namespace as ns","c.relnamespace","ns.oid").innerJoin("pg_catalog.pg_type as typ","a.atttypid","typ.oid").innerJoin("pg_catalog.pg_namespace as dtns","typ.typnamespace","dtns.oid").select(["a.attname as column","a.attnotnull as not_null","a.atthasdef as has_default","c.relname as table","c.relkind as table_type","ns.nspname as schema","typ.typname as type","dtns.nspname as type_schema",O1`col_description(a.attrelid, a.attnum)`.as("column_description"),O1`pg_get_serial_sequence(quote_ident(ns.nspname) || '.' || quote_ident(c.relname), a.attname)`.as("auto_incrementing")]).where("c.relkind","in",["r","v","p"]).where("ns.nspname","!~","^pg_").where("ns.nspname","!=","information_schema").where("ns.nspname","!=","crdb_internal").where(O1`has_schema_privilege(ns.nspname, 'USAGE')`).where("a.attnum",">=",0).where("a.attisdropped","!=",!0).orderBy("ns.nspname").orderBy("c.relname").orderBy("a.attnum").$castTo();if(!X.withInternalKyselyTables)Y=Y.where("c.relname","!=",eY).where("c.relname","!=",RG);let G=await Y.execute();return this.#Y(G)}async getMetadata(X){return{tables:await this.getTables(X)}}#Y(X){let Y=new Map;for(let G=0,Q=X.length;G<Q;G++){let J=X[G],{schema:W,table:Z}=J,$=`schema:${W};table:${Z}`;if(!Y.has($))Y.set($,n({columns:[],isView:J.table_type==="v",name:Z,schema:W}));Y.get($).columns.push(n({comment:J.column_description??void 0,dataType:J.type,dataTypeSchema:J.type_schema,hasDefaultValue:J.has_default,isAutoIncrementing:J.auto_incrementing!==null,isNullable:!J.not_null,name:J.column}))}return Array.from(Y.values())}}var Kr1=D(()=>{BI();W0();WE()});var tO8,Hr1;var Fr1=D(()=>{WE();tO8=BigInt("3853314791062309107");Hr1=class Hr1 extends IO{get supportsTransactionalDdl(){return!0}get supportsReturning(){return!0}async acquireMigrationLock(X,Y){await O1`select pg_advisory_xact_lock(${O1.lit(tO8)})`.execute(X)}async releaseMigrationLock(X,Y){}}});function Zc(X,Y){if(rO8(X)&&Y.stack){let G=Y.stack.split(`
|
|
112
|
+
`)});async function bn1(X={}){let Y=globalThis;if(Y[ou0])return;Y[ou0]=!0;try{let Q=await new GF(X).sweepOrphans();if(Q>0)console.log(`[sandbox] Boot sweep: stopped ${Q} stale container(s).`)}catch(G){console.warn("[sandbox] Boot sweep failed (continuing without it):",G instanceof Error?G.message:G)}}async function yn1(X){if(!X)return;console.log("[shutdown] Sweeping docker sandbox containers...");try{let Y=await X.sweepOrphans();if(Y>0)console.log(`[shutdown] Swept ${Y} sandbox container(s).`)}catch(Y){console.error("[shutdown] Sandbox sweep error:",Y)}}var ou0;var su0=D(()=>{_n1();ou0=Symbol.for("mesh.sandbox.bootSweepDone")});var Se=D(()=>{_n1();ru0();su0()});function T$1(X){if("threadId"in X){if(!X.threadId)throw Error("composeSandboxRef: threadId required");return`thread:${X.threadId}`}if(!X.orgId||!X.virtualMcpId||!X.branch)throw Error("composeSandboxRef: orgId, virtualMcpId and branch are all required for agent refs");return`agent:${X.orgId}:${X.virtualMcpId}:${X.branch}`}var ve={};R0(ve,{tryResolveRunnerKindFromEnv:()=>ke,sweepDockerOrphansOnShutdown:()=>yn1,sweepDockerOrphansOnBoot:()=>bn1,startLocalSandboxIngress:()=>fn1,sandboxIdKey:()=>Dd,resolveRunnerKindFromEnv:()=>Ed,ensureSandboxImage:()=>P$1,createDockerRunner:()=>ez8,composeSandboxRef:()=>T$1,DockerSandboxRunner:()=>GF});import{spawnSync as sz8}from"child_process";function ez8(X={}){return new GF({...X.docker,stateStore:X.stateStore})}function XO8(){if(Ce!==null)return Ce;try{Ce=sz8("docker",["--version"],{stdio:"ignore",timeout:2000}).status===0}catch{Ce=!1}return Ce}function ke(){let X=process.env.STUDIO_SANDBOX_RUNNER;if(X==="docker"||X==="freestyle"||X==="agent-sandbox")return X;if(X&&X.length>0)throw Error(`Unknown STUDIO_SANDBOX_RUNNER="${X}" \u2014 expected "docker", "freestyle", or "agent-sandbox".`);if(process.env.FREESTYLE_API_KEY)return"freestyle";return XO8()?"docker":null}function Ed(){let X=ke();if(X)return X;throw Error("No sandbox runner available: Docker CLI not found on PATH. Install Docker, set FREESTYLE_API_KEY, or set STUDIO_SANDBOX_RUNNER explicitly.")}var Ce=null;var nT=D(()=>{Se();Se();kn1();Se();Se()});var _e={};R0(_e,{kickoffSandboxImageBuild:()=>YO8});async function YO8(X){return}var fe=D(()=>{YF()});import{homedir as GO8}from"os";function Pd(X){return X==="true"||X==="1"}function eu0(X){if(!X)return null;try{let G=new URL(X).hostname;if(G==="localhost"||G==="127.0.0.1"||G==="::1")return null;return X}catch{return null}}function I$1(X,Y){let G=X.home||Y.DATA_DIR||Y.DECOCMS_HOME||`${GO8()}/deco`,Q=X.localMode,J=X.nodeEnv||Y.NODE_ENV||"development",W=Y.NATS_URL||"nats://localhost:4222";return{settings:{nodeEnv:J,port:Number(X.port)||Number(Y.PORT)||3000,baseUrl:X.baseUrl||Y.BASE_URL,dataDir:G,databasePgSsl:Pd(Y.DATABASE_PG_SSL),databasePoolMax:Number(Y.DATABASE_POOL_MAX)||3,betterAuthSecret:Y.BETTER_AUTH_SECRET||"",encryptionKey:Y.ENCRYPTION_KEY||"",meshJwtSecret:Y.MESH_JWT_SECRET,localMode:Q,allowLocalProd:Q||Pd(Y.DECOCMS_ALLOW_LOCAL_PROD),disableRateLimit:Pd(Y.DISABLE_RATE_LIMIT),studioProvisionSecretKey:Y.STUDIO_PROVISION_SECRET_KEY,clickhouseUrl:Y.CLICKHOUSE_URL,otelServiceName:Y.OTEL_SERVICE_NAME||"mesh",configPath:Y.CONFIG_PATH||"./config.json",unsafeAllowStdioTransport:Pd(Y.UNSAFE_ALLOW_STDIO_TRANSPORT),aiGatewayEnabled:Pd(Y.DECO_AI_GATEWAY_ENABLED),aiGatewayUrl:Y.DECO_AI_GATEWAY_URL||"https://ai-site.decocache.com",enableDecoImport:Pd(Y.ENABLE_DECO_IMPORT),s3Endpoint:Y.S3_ENDPOINT,s3Bucket:Y.S3_BUCKET,s3Region:Y.S3_REGION||"auto",s3AccessKeyId:Y.S3_ACCESS_KEY_ID,s3SecretAccessKey:Y.S3_SECRET_ACCESS_KEY,s3ForcePathStyle:Y.S3_FORCE_PATH_STYLE===void 0||Y.S3_FORCE_PATH_STYLE===""||Y.S3_FORCE_PATH_STYLE==="true"||Y.S3_FORCE_PATH_STYLE==="1",isCli:!0,noTui:X.noTui===!0,podName:Y.POD_NAME??crypto.randomUUID(),decoSupabaseUrl:Y.DECO_SUPABASE_URL,decoSupabaseServiceKey:Y.DECO_SUPABASE_SERVICE_KEY,firecrawlApiKey:Y.FIRECRAWL_API_KEY},externalDatabaseUrl:eu0(Y.DATABASE_URL),externalNatsUrl:eu0(W),skipMigrations:X.skipMigrations}}var xn1=()=>{};function Xl0(X){be=Object.freeze(X)}function v6(){if(!be)QO8();return be}function QO8(){if(be)return;let X={...process.env},Y=I$1({port:X.PORT||"3000",home:X.DATA_DIR||X.DECOCMS_HOME||"",localMode:X.DECOCMS_LOCAL_MODE==="true",skipMigrations:!0,noTui:X.DECO_NO_TUI==="true",vitePort:X.VITE_PORT,baseUrl:X.BASE_URL},X);be=Object.freeze({...Y.settings,databaseUrl:X.DATABASE_URL??"postgresql://postgres:postgres@localhost:5432/postgres",natsUrls:(X.NATS_URL||"nats://localhost:4222").split(",").map((G)=>G.trim()).filter(Boolean)})}var be=null;var m9=D(()=>{xn1()});function LZ(X){return typeof X>"u"||X===void 0}function H9(X){return typeof X==="string"}function QF(X){return typeof X==="number"}function UO(X){return typeof X==="boolean"}function dL(X){return X===null}function qd(X){return X instanceof Date}function cL(X){return typeof X==="bigint"}function V$1(X){return typeof Buffer<"u"&&Buffer.isBuffer(X)}function F9(X){return typeof X==="function"}function F7(X){return typeof X==="object"&&X!==null}function j$1(X){if(!F7(X)||FO8(X)!=="[object Object]")return!1;if(Object.getPrototypeOf(X)===null)return!0;let Y=X;while(Object.getPrototypeOf(Y)!==null)Y=Object.getPrototypeOf(Y);return Object.getPrototypeOf(X)===Y}function Yl0(X){return X[X.length-1]}function n(X){return Object.freeze(X)}function ye(X){if(IG(X))return X;else return[X]}function IG(X){return Array.isArray(X)}function EZ(X){return X}function M$1(X,Y){if(IG(X)&&IG(Y))return JO8(X,Y);else if(F7(X)&&F7(Y))return ZO8(X,Y);return X===Y}function JO8(X,Y){if(X.length!==Y.length)return!1;for(let G=0;G<X.length;++G)if(!M$1(X[G],Y[G]))return!1;return!0}function ZO8(X,Y){if(V$1(X)&&V$1(Y))return WO8(X,Y);else if(qd(X)&&qd(Y))return $O8(X,Y);return KO8(X,Y)}function WO8(X,Y){return Buffer.compare(X,Y)===0}function $O8(X,Y){return X.getTime()===Y.getTime()}function KO8(X,Y){let G=Object.keys(X),Q=Object.keys(Y);if(G.length!==Q.length)return!1;for(let J of G)if(!M$1(X[J],Y[J]))return!1;return!0}function FO8(X){if(X==null)return X===void 0?"[object Undefined]":"[object Null]";return HO8.call(X)}var HO8;var W0=D(()=>{HO8=Object.prototype.toString});var _5;var aT=D(()=>{W0();_5=n({is(X){return X.kind==="AlterTableNode"},create(X){return n({kind:"AlterTableNode",table:X})},cloneWithTableProps(X,Y){return n({...X,...Y})},cloneWithColumnAlteration(X,Y){return n({...X,columnAlterations:X.columnAlterations?[...X.columnAlterations,Y]:[Y]})}})});var k4;var U7=D(()=>{W0();k4=n({is(X){return X.kind==="IdentifierNode"},create(X){return n({kind:"IdentifierNode",name:X})}})});var JF;var R$1=D(()=>{W0();U7();JF=n({is(X){return X.kind==="CreateIndexNode"},create(X){return n({kind:"CreateIndexNode",name:k4.create(X)})},cloneWith(X,Y){return n({...X,...Y})},cloneWithColumns(X,Y){return n({...X,columns:[...X.columns||[],...Y]})}})});var S$1;var C$1=D(()=>{W0();U7();S$1=n({is(X){return X.kind==="CreateSchemaNode"},create(X,Y){return n({kind:"CreateSchemaNode",schema:k4.create(X),...Y})},cloneWith(X,Y){return n({...X,...Y})}})});var Gl0,wJ;var Ad=D(()=>{W0();Gl0=["preserve rows","delete rows","drop"],wJ=n({is(X){return X.kind==="CreateTableNode"},create(X){return n({kind:"CreateTableNode",table:X,columns:n([])})},cloneWithColumn(X,Y){return n({...X,columns:n([...X.columns,Y])})},cloneWithConstraint(X,Y){return n({...X,constraints:X.constraints?n([...X.constraints,Y]):n([Y])})},cloneWithFrontModifier(X,Y){return n({...X,frontModifiers:X.frontModifiers?n([...X.frontModifiers,Y]):n([Y])})},cloneWithEndModifier(X,Y){return n({...X,endModifiers:X.endModifiers?n([...X.endModifiers,Y]):n([Y])})},cloneWith(X,Y){return n({...X,...Y})}})});var LJ;var NO=D(()=>{W0();U7();LJ=n({is(X){return X.kind==="SchemableIdentifierNode"},create(X){return n({kind:"SchemableIdentifierNode",identifier:k4.create(X)})},createWithSchema(X,Y){return n({kind:"SchemableIdentifierNode",schema:k4.create(X),identifier:k4.create(Y)})}})});var iL;var xe=D(()=>{W0();NO();iL=n({is(X){return X.kind==="DropIndexNode"},create(X,Y){return n({kind:"DropIndexNode",name:LJ.create(X),...Y})},cloneWith(X,Y){return n({...X,...Y})}})});var he;var k$1=D(()=>{W0();U7();he=n({is(X){return X.kind==="DropSchemaNode"},create(X,Y){return n({kind:"DropSchemaNode",schema:k4.create(X),...Y})},cloneWith(X,Y){return n({...X,...Y})}})});var ge;var v$1=D(()=>{W0();ge=n({is(X){return X.kind==="DropTableNode"},create(X,Y){return n({kind:"DropTableNode",table:X,...Y})},cloneWith(X,Y){return n({...X,...Y})}})});var VG;var ZF=D(()=>{W0();VG=n({is(X){return X.kind==="AliasNode"},create(X,Y){return n({kind:"AliasNode",node:X,alias:Y})}})});var _3;var Td=D(()=>{W0();NO();_3=n({is(X){return X.kind==="TableNode"},create(X){return n({kind:"TableNode",table:LJ.create(X)})},createWithSchema(X,Y){return n({kind:"TableNode",table:LJ.createWithSchema(X,Y)})}})});function R7(X){return F7(X)&&F9(X.toOperationNode)}var f3=D(()=>{W0()});function _$1(X){return F7(X)&&"expressionType"in X&&R7(X)}function Ql0(X){return F7(X)&&"expression"in X&&H9(X.alias)&&R7(X)}var f$1=D(()=>{f3();W0()});var zN;var hn1=D(()=>{W0();zN=n({is(X){return X.kind==="SelectModifierNode"},create(X,Y){return n({kind:"SelectModifierNode",modifier:X,of:Y})},createWithExpression(X){return n({kind:"SelectModifierNode",rawModifier:X})}})});var b3;var pL=D(()=>{W0();b3=n({is(X){return X.kind==="AndNode"},create(X,Y){return n({kind:"AndNode",left:X,right:Y})}})});var WF;var tT=D(()=>{W0();WF=n({is(X){return X.kind==="OrNode"},create(X,Y){return n({kind:"OrNode",left:X,right:Y})}})});var b$1;var gn1=D(()=>{W0();pL();tT();b$1=n({is(X){return X.kind==="OnNode"},create(X){return n({kind:"OnNode",on:X})},cloneWithOperation(X,Y,G){return n({...X,on:Y==="And"?b3.create(X.on,G):WF.create(X.on,G)})}})});var $F;var Id=D(()=>{W0();gn1();$F=n({is(X){return X.kind==="JoinNode"},create(X,Y){return n({kind:"JoinNode",joinType:X,table:Y,on:void 0})},createWithOn(X,Y,G){return n({kind:"JoinNode",joinType:X,table:Y,on:b$1.create(G)})},cloneWithOn(X,Y){return n({...X,on:X.on?b$1.cloneWithOperation(X.on,"And",Y):b$1.create(Y)})}})});var nL;var y$1=D(()=>{W0();nL=n({is(X){return X.kind==="BinaryOperationNode"},create(X,Y,G){return n({kind:"BinaryOperationNode",leftOperand:X,operator:Y,rightOperand:G})}})});function un1(X){return H9(X)&&Jl0.includes(X)}var UO8,NO8,Jl0,BO8,zO8,OO8,Zl0,PZ;var aL=D(()=>{W0();UO8=["=","==","!=","<>",">",">=","<","<=","in","not in","is","is not","like","not like","match","ilike","not ilike","@>","<@","^@","&&","?","?&","?|","!<","!>","<=>","!~","~","~*","!~*","@@","@@@","!!","<->","regexp","is distinct from","is not distinct from"],NO8=["+","-","*","/","%","^","&","|","#","<<",">>"],Jl0=["->","->>"],BO8=[...UO8,...NO8,"&&","||"],zO8=["exists","not exists"],OO8=["not","-",...zO8],Zl0=[...BO8,...Jl0,...OO8,"between","between symmetric"],PZ=n({is(X){return X.kind==="OperatorNode"},create(X){return n({kind:"OperatorNode",operator:X})}})});var T5;var EJ=D(()=>{W0();U7();T5=n({is(X){return X.kind==="ColumnNode"},create(X){return n({kind:"ColumnNode",column:k4.create(X)})}})});var Vd;var ue=D(()=>{W0();Vd=n({is(X){return X.kind==="SelectAllNode"},create(){return n({kind:"SelectAllNode"})}})});var jd;var x$1=D(()=>{ue();W0();jd=n({is(X){return X.kind==="ReferenceNode"},create(X,Y){return n({kind:"ReferenceNode",table:Y,column:X})},createSelectAll(X){return n({kind:"ReferenceNode",table:X,column:Vd.create()})}})});class ln1{#X;get dynamicReference(){return this.#X}get refType(){return}constructor(X){this.#X=X}toOperationNode(){return mn1(this.#X)}}function h$1(X){return F7(X)&&R7(X)&&H9(X.dynamicReference)}var le=D(()=>{f3();OQ();W0()});var KF;var g$1=D(()=>{W0();KF=n({is(X){return X.kind==="OrderByItemNode"},create(X,Y){return n({kind:"OrderByItemNode",orderBy:X,direction:Y})},cloneWith(X,Y){return n({...X,...Y})}})});var f5;var EK=D(()=>{W0();f5=n({is(X){return X.kind==="RawNode"},create(X,Y){return n({kind:"RawNode",sqlFragments:n(X),parameters:n(Y)})},createWithSql(X){return f5.create([X],[])},createWithChild(X){return f5.create(["",""],[X])},createWithChildren(X){return f5.create(Array(X.length+1).fill(""),X)}})});var Wl0;var dn1=D(()=>{W0();U7();Wl0=n({is(X){return X.kind==="CollateNode"},create(X){return n({kind:"CollateNode",collation:k4.create(X)})}})});class tL{#X;constructor(X){this.#X=n(X)}desc(){return new tL({node:KF.cloneWith(this.#X.node,{direction:f5.createWithSql("desc")})})}asc(){return new tL({node:KF.cloneWith(this.#X.node,{direction:f5.createWithSql("asc")})})}nullsLast(){return new tL({node:KF.cloneWith(this.#X.node,{nulls:"last"})})}nullsFirst(){return new tL({node:KF.cloneWith(this.#X.node,{nulls:"first"})})}collate(X){return new tL({node:KF.cloneWith(this.#X.node,{collation:Wl0.create(X)})})}toOperationNode(){return this.#X.node}}var cn1=D(()=>{dn1();g$1();EK();W0()});function ON(X){if($l0.has(X))return;$l0.add(X),console.log(X)}var $l0;var me=D(()=>{$l0=new Set});function pn1(X){return X==="asc"||X==="desc"}function tW(X){if(X.length===2)return[in1(X[0],X[1])];if(X.length===1){let[Y]=X;if(Array.isArray(Y))return ON("orderBy(array) is deprecated, use multiple orderBy calls instead."),Y.map((G)=>in1(G));return[in1(Y)]}throw Error(`Invalid number of arguments at order by! expected 1-2, received ${X.length}`)}function in1(X,Y){let G=DO8(X);if(KF.is(G)){if(Y)throw Error("Cannot specify direction twice!");return G}return Kl0(G,Y)}function DO8(X){if(BO(X))return y3(X);if(h$1(X))return X.toOperationNode();let[Y,G]=X.split(" ");if(G)return ON("`orderBy('column asc')` is deprecated. Use `orderBy('column', 'asc')` instead."),Kl0(aW(Y),G);return aW(X)}function Kl0(X,Y){if(typeof Y==="string"){if(!pn1(Y))throw Error(`Invalid order by direction: ${Y}`);return KF.create(X,f5.createWithSql(Y))}if(_$1(Y))return ON("`orderBy(..., expr)` is deprecated. Use `orderBy(..., 'asc')` or `orderBy(..., (ob) => ...)` instead."),KF.create(X,Y.toOperationNode());let G=KF.create(X);if(!Y)return G;return Y(new tL({node:G})).toOperationNode()}var rT=D(()=>{le();f$1();g$1();EK();cn1();me();HF();OQ()});var Md;var u$1=D(()=>{W0();Md=n({is(X){return X.kind==="JSONReferenceNode"},create(X,Y){return n({kind:"JSONReferenceNode",reference:X,traversal:Y})},cloneWithTraversal(X,Y){return n({...X,traversal:Y})}})});var l$1;var m$1=D(()=>{W0();l$1=n({is(X){return X.kind==="JSONOperatorChainNode"},create(X){return n({kind:"JSONOperatorChainNode",operator:X,values:n([])})},cloneWithValue(X,Y){return n({...X,values:n([...X.values,Y])})}})});var rL;var de=D(()=>{W0();rL=n({is(X){return X.kind==="JSONPathNode"},create(X){return n({kind:"JSONPathNode",inOperator:X,pathLegs:n([])})},cloneWithLeg(X,Y){return n({...X,pathLegs:n([...X.pathLegs,Y])})}})});function mn1(X){if(H9(X))return aW(X);return X.toOperationNode()}function zO(X){if(IG(X))return X.map((Y)=>DQ(Y));else return[DQ(X)]}function DQ(X){if(BO(X))return y3(X);return mn1(X)}function Hl0(X,Y){let G=aW(X);if(un1(Y))return Md.create(G,l$1.create(PZ.create(Y)));let Q=Y.slice(0,-1);if(un1(Q))return Md.create(G,rL.create(PZ.create(Q)));throw Error(`Invalid JSON operator: ${Y}`)}function aW(X){if(!X.includes("."))return jd.create(T5.create(X));let G=X.split(".").map(an1);if(G.length===3)return wO8(G);if(G.length===2)return LO8(G);throw Error(`invalid column reference ${X}`)}function Fl0(X){if(X.includes(" as ")){let[G,Q]=X.split(" as ").map(an1);return VG.create(aW(G),k4.create(Q))}else return aW(X)}function nn1(X){return T5.create(X)}function Rd(X){if(X.includes(" ")){let[G,Q]=X.split(" ").map(an1);if(!pn1(Q))throw Error(`invalid order direction "${Q}" next to "${G}"`);return tW([G,Q])[0]}else return nn1(X)}function wO8(X){let[Y,G,Q]=X;return jd.create(T5.create(Q),_3.createWithSchema(Y,G))}function LO8(X){let[Y,G]=X;return jd.create(T5.create(G),_3.create(Y))}function an1(X){return X.trim()}var OQ=D(()=>{ZF();EJ();x$1();Td();W0();HF();U7();rT();aL();u$1();m$1();de()});var Sd;var ce=D(()=>{W0();Sd=n({is(X){return X.kind==="PrimitiveValueListNode"},create(X){return n({kind:"PrimitiveValueListNode",values:n([...X])})}})});var DN;var oT=D(()=>{W0();DN=n({is(X){return X.kind==="ValueListNode"},create(X){return n({kind:"ValueListNode",values:n(X)})}})});var kY;var wN=D(()=>{W0();kY=n({is(X){return X.kind==="ValueNode"},create(X){return n({kind:"ValueNode",value:X})},createImmediate(X){return n({kind:"ValueNode",value:X,immediate:!0})}})});function Ul0(X){if(IG(X))return EO8(X);return d9(X)}function d9(X){if(BO(X))return y3(X);return kY.create(X)}function d$1(X){return QF(X)||UO(X)||dL(X)}function ie(X){if(!d$1(X))throw Error(`unsafe immediate value ${JSON.stringify(X)}`);return kY.createImmediate(X)}function EO8(X){if(X.some(BO))return DN.create(X.map((Y)=>d9(Y)));return Sd.create(X)}var LN=D(()=>{ce();oT();wN();W0();HF()});var rW;var Cd=D(()=>{W0();rW=n({is(X){return X.kind==="ParensNode"},create(X){return n({kind:"ParensNode",node:X})}})});function N7(X){if(X.length===3)return c$1(X[0],X[1],X[2]);else if(X.length===1)return d9(X[0]);throw Error(`invalid arguments: ${JSON.stringify(X)}`)}function c$1(X,Y,G){if(PO8(Y)&&Bl0(G))return nL.create(DQ(X),tn1(Y),kY.createImmediate(G));return nL.create(DQ(X),tn1(Y),Ul0(G))}function jG(X,Y,G){return nL.create(DQ(X),tn1(Y),DQ(G))}function rn1(X,Y){return kd(Object.entries(X).filter(([,G])=>!LZ(G)).map(([G,Q])=>c$1(G,Bl0(Q)?"is":"=",Q)),Y)}function kd(X,Y,G=!0){let Q=Y==="and"?b3.create:WF.create;if(X.length===0)return nL.create(kY.createImmediate(1),PZ.create("="),kY.createImmediate(Y==="and"?1:0));let J=Nl0(X[0]);for(let W=1;W<X.length;++W)J=Q(J,Nl0(X[W]));if(X.length>1&&G)return rW.create(J);return J}function PO8(X){return X==="is"||X==="is not"}function Bl0(X){return dL(X)||UO(X)}function tn1(X){if(H9(X)&&Zl0.includes(X))return PZ.create(X);if(R7(X))return X.toOperationNode();throw Error(`invalid operator ${JSON.stringify(X)}`)}function Nl0(X){return R7(X)?X.toOperationNode():X}var oW=D(()=>{y$1();W0();f3();aL();OQ();LN();wN();pL();Cd();tT()});var OO;var pe=D(()=>{W0();OO=n({is(X){return X.kind==="OrderByNode"},create(X){return n({kind:"OrderByNode",items:n([...X])})},cloneWithItems(X,Y){return n({...X,items:n([...X.items,...Y])})}})});var on1;var sn1=D(()=>{W0();on1=n({is(X){return X.kind==="PartitionByNode"},create(X){return n({kind:"PartitionByNode",items:n(X)})},cloneWithItems(X,Y){return n({...X,items:n([...X.items,...Y])})}})});var ne;var i$1=D(()=>{W0();pe();sn1();ne=n({is(X){return X.kind==="OverNode"},create(){return n({kind:"OverNode"})},cloneWithOrderByItems(X,Y){return n({...X,orderBy:X.orderBy?OO.cloneWithItems(X.orderBy,Y):OO.create(Y)})},cloneWithPartitionByItems(X,Y){return n({...X,partitionBy:X.partitionBy?on1.cloneWithItems(X.partitionBy,Y):on1.create(Y)})}})});var sT;var ae=D(()=>{W0();sT=n({is(X){return X.kind==="FromNode"},create(X){return n({kind:"FromNode",froms:n(X)})},cloneWithFroms(X,Y){return n({...X,froms:n([...X.froms,...Y])})}})});var en1;var Xa1=D(()=>{W0();en1=n({is(X){return X.kind==="GroupByNode"},create(X){return n({kind:"GroupByNode",items:n(X)})},cloneWithItems(X,Y){return n({...X,items:n([...X.items,...Y])})}})});var Ya1;var Ga1=D(()=>{W0();pL();tT();Ya1=n({is(X){return X.kind==="HavingNode"},create(X){return n({kind:"HavingNode",having:X})},cloneWithOperation(X,Y,G){return n({...X,having:Y==="And"?b3.create(X.having,G):WF.create(X.having,G)})}})});var xX;var eT=D(()=>{W0();xX=n({is(X){return X.kind==="InsertQueryNode"},create(X,Y,G){return n({kind:"InsertQueryNode",into:X,...Y&&{with:Y},replace:G})},createWithoutInto(){return n({kind:"InsertQueryNode"})},cloneWith(X,Y){return n({...X,...Y})}})});var p$1;var n$1=D(()=>{W0();p$1=n({is(X){return X.kind==="ListNode"},create(X){return n({kind:"ListNode",items:n(X)})}})});var EN;var vd=D(()=>{W0();ae();n$1();EN=n({is(X){return X.kind==="UpdateQueryNode"},create(X,Y){return n({kind:"UpdateQueryNode",table:X.length===1?X[0]:p$1.create(X),...Y&&{with:Y}})},createWithoutTable(){return n({kind:"UpdateQueryNode"})},cloneWithFromItems(X,Y){return n({...X,from:X.from?sT.cloneWithFroms(X.from,Y):sT.create(Y)})},cloneWithUpdates(X,Y){return n({...X,updates:X.updates?n([...X.updates,...Y]):Y})},cloneWithLimit(X,Y){return n({...X,limit:Y})}})});var te;var a$1=D(()=>{W0();te=n({is(X){return X.kind==="UsingNode"},create(X){return n({kind:"UsingNode",tables:n(X)})},cloneWithTables(X,Y){return n({...X,tables:n([...X.tables,...Y])})}})});var oL;var re=D(()=>{W0();ae();a$1();PK();oL=n({is(X){return X.kind==="DeleteQueryNode"},create(X,Y){return n({kind:"DeleteQueryNode",from:sT.create(X),...Y&&{with:Y}})},cloneWithOrderByItems:(X,Y)=>A6.cloneWithOrderByItems(X,Y),cloneWithoutOrderBy:(X)=>A6.cloneWithoutOrderBy(X),cloneWithLimit(X,Y){return n({...X,limit:Y})},cloneWithoutLimit(X){return n({...X,limit:void 0})},cloneWithUsing(X,Y){return n({...X,using:X.using!==void 0?te.cloneWithTables(X.using,Y):te.create(Y)})}})});var wQ;var oe=D(()=>{W0();pL();tT();wQ=n({is(X){return X.kind==="WhereNode"},create(X){return n({kind:"WhereNode",where:X})},cloneWithOperation(X,Y,G){return n({...X,where:Y==="And"?b3.create(X.where,G):WF.create(X.where,G)})}})});var Qa1;var Ja1=D(()=>{W0();Qa1=n({is(X){return X.kind==="ReturningNode"},create(X){return n({kind:"ReturningNode",selections:n(X)})},cloneWithSelections(X,Y){return n({...X,selections:X.selections?n([...X.selections,...Y]):n(Y)})}})});var zl0;var Za1=D(()=>{W0();zl0=n({is(X){return X.kind==="ExplainNode"},create(X,Y){return n({kind:"ExplainNode",format:X,options:Y})}})});var qK;var XI=D(()=>{W0();qK=n({is(X){return X.kind==="WhenNode"},create(X){return n({kind:"WhenNode",condition:X})},cloneWithResult(X,Y){return n({...X,result:Y})}})});var sW;var se=D(()=>{W0();XI();sW=n({is(X){return X.kind==="MergeQueryNode"},create(X,Y){return n({kind:"MergeQueryNode",into:X,...Y&&{with:Y}})},cloneWithUsing(X,Y){return n({...X,using:Y})},cloneWithWhen(X,Y){return n({...X,whens:X.whens?n([...X.whens,Y]):n([Y])})},cloneWithThen(X,Y){return n({...X,whens:X.whens?n([...X.whens.slice(0,-1),qK.cloneWithResult(X.whens[X.whens.length-1],Y)]):void 0})}})});var Wa1;var $a1=D(()=>{W0();Wa1=n({is(X){return X.kind==="OutputNode"},create(X){return n({kind:"OutputNode",selections:n(X)})},cloneWithSelections(X,Y){return n({...X,selections:X.selections?n([...X.selections,...Y]):n(Y)})}})});var A6;var PK=D(()=>{eT();YI();vd();re();oe();W0();Ja1();Za1();se();$a1();pe();A6=n({is(X){return U9.is(X)||xX.is(X)||EN.is(X)||oL.is(X)||sW.is(X)},cloneWithEndModifier(X,Y){return n({...X,endModifiers:X.endModifiers?n([...X.endModifiers,Y]):n([Y])})},cloneWithWhere(X,Y){return n({...X,where:X.where?wQ.cloneWithOperation(X.where,"And",Y):wQ.create(Y)})},cloneWithJoin(X,Y){return n({...X,joins:X.joins?n([...X.joins,Y]):n([Y])})},cloneWithReturning(X,Y){return n({...X,returning:X.returning?Qa1.cloneWithSelections(X.returning,Y):Qa1.create(Y)})},cloneWithoutReturning(X){return n({...X,returning:void 0})},cloneWithoutWhere(X){return n({...X,where:void 0})},cloneWithExplain(X,Y,G){return n({...X,explain:zl0.create(Y,G?.toOperationNode())})},cloneWithTop(X,Y){return n({...X,top:Y})},cloneWithOutput(X,Y){return n({...X,output:X.output?Wa1.cloneWithSelections(X.output,Y):Wa1.create(Y)})},cloneWithOrderByItems(X,Y){return n({...X,orderBy:X.orderBy?OO.cloneWithItems(X.orderBy,Y):OO.create(Y)})},cloneWithoutOrderBy(X){return n({...X,orderBy:void 0})}})});var U9;var YI=D(()=>{W0();ae();Xa1();Ga1();PK();U9=n({is(X){return X.kind==="SelectQueryNode"},create(X){return n({kind:"SelectQueryNode",...X&&{with:X}})},createFrom(X,Y){return n({kind:"SelectQueryNode",from:sT.create(X),...Y&&{with:Y}})},cloneWithSelections(X,Y){return n({...X,selections:X.selections?n([...X.selections,...Y]):n(Y)})},cloneWithDistinctOn(X,Y){return n({...X,distinctOn:X.distinctOn?n([...X.distinctOn,...Y]):n(Y)})},cloneWithFrontModifier(X,Y){return n({...X,frontModifiers:X.frontModifiers?n([...X.frontModifiers,Y]):n([Y])})},cloneWithOrderByItems:(X,Y)=>A6.cloneWithOrderByItems(X,Y),cloneWithGroupByItems(X,Y){return n({...X,groupBy:X.groupBy?en1.cloneWithItems(X.groupBy,Y):en1.create(Y)})},cloneWithLimit(X,Y){return n({...X,limit:Y})},cloneWithOffset(X,Y){return n({...X,offset:Y})},cloneWithFetch(X,Y){return n({...X,fetch:Y})},cloneWithHaving(X,Y){return n({...X,having:X.having?Ya1.cloneWithOperation(X.having,"And",Y):Ya1.create(Y)})},cloneWithSetOperations(X,Y){return n({...X,setOperations:X.setOperations?n([...X.setOperations,...Y]):n([...Y])})},cloneWithoutSelections(X){return n({...X,selections:[]})},cloneWithoutLimit(X){return n({...X,limit:void 0})},cloneWithoutOffset(X){return n({...X,offset:void 0})},cloneWithoutOrderBy:(X)=>A6.cloneWithoutOrderBy(X),cloneWithoutGroupBy(X){return n({...X,groupBy:void 0})}})});class _d{#X;constructor(X){this.#X=n(X)}on(...X){return new _d({...this.#X,joinNode:$F.cloneWithOn(this.#X.joinNode,N7(X))})}onRef(X,Y,G){return new _d({...this.#X,joinNode:$F.cloneWithOn(this.#X.joinNode,jG(X,Y,G))})}onTrue(){return new _d({...this.#X,joinNode:$F.cloneWithOn(this.#X.joinNode,f5.createWithSql("true"))})}$call(X){return X(this)}toOperationNode(){return this.#X.joinNode}}var Ka1=D(()=>{Id();EK();oW();W0()});var Ol0;var Ha1=D(()=>{W0();Ol0=n({is(X){return X.kind==="PartitionByItemNode"},create(X){return n({kind:"PartitionByItemNode",partitionBy:X})}})});function Dl0(X){return zO(X).map(Ol0.create)}var wl0=D(()=>{Ha1();OQ()});class fd{#X;constructor(X){this.#X=n(X)}orderBy(...X){return new fd({overNode:ne.cloneWithOrderByItems(this.#X.overNode,tW(X))})}clearOrderBy(){return new fd({overNode:A6.cloneWithoutOrderBy(this.#X.overNode)})}partitionBy(X){return new fd({overNode:ne.cloneWithPartitionByItems(this.#X.overNode,Dl0(X))})}$call(X){return X(this)}toOperationNode(){return this.#X.overNode}}var Ll0=D(()=>{i$1();PK();rT();wl0();W0()});var bd;var Fa1=D(()=>{W0();x$1();ue();bd=n({is(X){return X.kind==="SelectionNode"},create(X){return n({kind:"SelectionNode",selection:X})},createSelectAll(){return n({kind:"SelectionNode",selection:Vd.create()})},createSelectAllFromTable(X){return n({kind:"SelectionNode",selection:jd.createSelectAll(X)})}})});function sY(X){if(F9(X))return sY(X(FF()));else if(IG(X))return X.map((Y)=>El0(Y));else return[El0(X)]}function El0(X){if(H9(X))return bd.create(Fl0(X));else if(h$1(X))return bd.create(X.toOperationNode());else return bd.create(t$1(X))}function MG(X){if(!X)return[bd.createSelectAll()];else if(Array.isArray(X))return X.map(Pl0);else return[Pl0(X)]}function Pl0(X){if(H9(X))return bd.createSelectAllFromTable(b5(X));throw Error(`invalid value selectAll expression: ${JSON.stringify(X)}`)}var sL=D(()=>{W0();Fa1();OQ();le();HF();LQ();GI()});var ql0;var Ua1=D(()=>{W0();ql0=n({is(X){return X.kind==="ValuesNode"},create(X){return n({kind:"ValuesNode",values:n(X)})}})});var Al0;var Na1=D(()=>{W0();Al0=n({is(X){return X.kind==="DefaultInsertValueNode"},create(){return n({kind:"DefaultInsertValueNode"})}})});function r$1(X){let Y=F9(X)?X(FF()):X,G=IG(Y)?Y:n([Y]);return qO8(G)}function qO8(X){let Y=AO8(X);return[n([...Y.keys()].map(T5.create)),ql0.create(X.map((G)=>TO8(G,Y)))]}function AO8(X){let Y=new Map;for(let G of X){let Q=Object.keys(G);for(let J of Q)if(!Y.has(J)&&G[J]!==void 0)Y.set(J,Y.size)}return Y}function TO8(X,Y){let G=Object.keys(X),Q=Array.from({length:Y.size}),J=!1,W=G.length;for(let $ of G){let K=Y.get($);if(LZ(K)){W--;continue}let H=X[$];if(LZ(H)||BO(H))J=!0;Q[K]=H}if(W<Y.size||J){let $=Al0.create();return DN.create(Q.map((K)=>LZ(K)?$:d9(K)))}return Sd.create(Q)}var Ba1=D(()=>{EJ();ce();oT();W0();LN();Ua1();HF();Na1();GI()});var za1;var Oa1=D(()=>{W0();za1=n({is(X){return X.kind==="ColumnUpdateNode"},create(X,Y){return n({kind:"ColumnUpdateNode",column:X,value:Y})}})});function Tl0(...X){if(X.length===2)return[za1.create(DQ(X[0]),d9(X[1]))];return ee(X[0])}function ee(X){let Y=F9(X)?X(FF()):X;return Object.entries(Y).filter(([G,Q])=>Q!==void 0).map(([G,Q])=>{return za1.create(T5.create(G),d9(Q))})}var o$1=D(()=>{EJ();Oa1();GI();W0();LN();OQ()});var Il0;var Da1=D(()=>{W0();Il0=n({is(X){return X.kind==="OnDuplicateKeyNode"},create(X){return n({kind:"OnDuplicateKeyNode",updates:X})}})});class wa1{insertId;numInsertedOrUpdatedRows;constructor(X,Y){this.insertId=X,this.numInsertedOrUpdatedRows=Y}}function PN(X){return Object.prototype.hasOwnProperty.call(X,"prototype")}var UF;var QI=D(()=>{UF=class UF extends Error{node;constructor(X){super("no result");this.node=X}}});var qZ;var s$1=D(()=>{W0();oe();qZ=n({is(X){return X.kind==="OnConflictNode"},create(){return n({kind:"OnConflictNode"})},cloneWith(X,Y){return n({...X,...Y})},cloneWithIndexWhere(X,Y){return n({...X,indexWhere:X.indexWhere?wQ.cloneWithOperation(X.indexWhere,"And",Y):wQ.create(Y)})},cloneWithIndexOrWhere(X,Y){return n({...X,indexWhere:X.indexWhere?wQ.cloneWithOperation(X.indexWhere,"Or",Y):wQ.create(Y)})},cloneWithUpdateWhere(X,Y){return n({...X,updateWhere:X.updateWhere?wQ.cloneWithOperation(X.updateWhere,"And",Y):wQ.create(Y)})},cloneWithUpdateOrWhere(X,Y){return n({...X,updateWhere:X.updateWhere?wQ.cloneWithOperation(X.updateWhere,"Or",Y):wQ.create(Y)})},cloneWithoutIndexWhere(X){return n({...X,indexWhere:void 0})},cloneWithoutUpdateWhere(X){return n({...X,updateWhere:void 0})}})});class qN{#X;constructor(X){this.#X=n(X)}column(X){let Y=T5.create(X);return new qN({...this.#X,onConflictNode:qZ.cloneWith(this.#X.onConflictNode,{columns:this.#X.onConflictNode.columns?n([...this.#X.onConflictNode.columns,Y]):n([Y])})})}columns(X){let Y=X.map(T5.create);return new qN({...this.#X,onConflictNode:qZ.cloneWith(this.#X.onConflictNode,{columns:this.#X.onConflictNode.columns?n([...this.#X.onConflictNode.columns,...Y]):n(Y)})})}constraint(X){return new qN({...this.#X,onConflictNode:qZ.cloneWith(this.#X.onConflictNode,{constraint:k4.create(X)})})}expression(X){return new qN({...this.#X,onConflictNode:qZ.cloneWith(this.#X.onConflictNode,{indexExpression:X.toOperationNode()})})}where(...X){return new qN({...this.#X,onConflictNode:qZ.cloneWithIndexWhere(this.#X.onConflictNode,N7(X))})}whereRef(X,Y,G){return new qN({...this.#X,onConflictNode:qZ.cloneWithIndexWhere(this.#X.onConflictNode,jG(X,Y,G))})}clearWhere(){return new qN({...this.#X,onConflictNode:qZ.cloneWithoutIndexWhere(this.#X.onConflictNode)})}doNothing(){return new Vl0({...this.#X,onConflictNode:qZ.cloneWith(this.#X.onConflictNode,{doNothing:!0})})}doUpdateSet(X){return new X11({...this.#X,onConflictNode:qZ.cloneWith(this.#X.onConflictNode,{updates:ee(X)})})}$call(X){return X(this)}}class Vl0{#X;constructor(X){this.#X=n(X)}toOperationNode(){return this.#X.onConflictNode}}class X11{#X;constructor(X){this.#X=n(X)}where(...X){return new X11({...this.#X,onConflictNode:qZ.cloneWithUpdateWhere(this.#X.onConflictNode,N7(X))})}whereRef(X,Y,G){return new X11({...this.#X,onConflictNode:qZ.cloneWithUpdateWhere(this.#X.onConflictNode,jG(X,Y,G))})}clearWhere(){return new X11({...this.#X,onConflictNode:qZ.cloneWithoutUpdateWhere(this.#X.onConflictNode)})}$call(X){return X(this)}toOperationNode(){return this.#X.onConflictNode}}var La1=D(()=>{EJ();U7();s$1();oW();o$1();W0()});var jl0;var Ea1=D(()=>{W0();jl0=n({is(X){return X.kind==="TopNode"},create(X,Y){return n({kind:"TopNode",expression:X,modifiers:Y})}})});function NF(X,Y){if(!QF(X)&&!cL(X))throw Error(`Invalid top expression: ${X}`);if(!LZ(Y)&&!IO8(Y))throw Error(`Invalid top modifiers: ${Y}`);return jl0.create(X,Y)}function IO8(X){return X==="percent"||X==="with ties"||X==="percent with ties"}var yd=D(()=>{Ea1();W0()});var JI;var Pa1=D(()=>{W0();JI=n({is(X){return X.kind==="OrActionNode"},create(X){return n({kind:"OrActionNode",action:X})}})});class c9{#X;constructor(X){this.#X=n(X)}values(X){let[Y,G]=r$1(X);return new c9({...this.#X,queryNode:xX.cloneWith(this.#X.queryNode,{columns:Y,values:G})})}columns(X){return new c9({...this.#X,queryNode:xX.cloneWith(this.#X.queryNode,{columns:n(X.map(T5.create))})})}expression(X){return new c9({...this.#X,queryNode:xX.cloneWith(this.#X.queryNode,{values:y3(X)})})}defaultValues(){return new c9({...this.#X,queryNode:xX.cloneWith(this.#X.queryNode,{defaultValues:!0})})}modifyEnd(X){return new c9({...this.#X,queryNode:A6.cloneWithEndModifier(this.#X.queryNode,X.toOperationNode())})}ignore(){return new c9({...this.#X,queryNode:xX.cloneWith(this.#X.queryNode,{orAction:JI.create("ignore")})})}orIgnore(){return new c9({...this.#X,queryNode:xX.cloneWith(this.#X.queryNode,{orAction:JI.create("ignore")})})}orAbort(){return new c9({...this.#X,queryNode:xX.cloneWith(this.#X.queryNode,{orAction:JI.create("abort")})})}orFail(){return new c9({...this.#X,queryNode:xX.cloneWith(this.#X.queryNode,{orAction:JI.create("fail")})})}orReplace(){return new c9({...this.#X,queryNode:xX.cloneWith(this.#X.queryNode,{orAction:JI.create("replace")})})}orRollback(){return new c9({...this.#X,queryNode:xX.cloneWith(this.#X.queryNode,{orAction:JI.create("rollback")})})}top(X,Y){return new c9({...this.#X,queryNode:A6.cloneWithTop(this.#X.queryNode,NF(X,Y))})}onConflict(X){return new c9({...this.#X,queryNode:xX.cloneWith(this.#X.queryNode,{onConflict:X(new qN({onConflictNode:qZ.create()})).toOperationNode()})})}onDuplicateKeyUpdate(X){return new c9({...this.#X,queryNode:xX.cloneWith(this.#X.queryNode,{onDuplicateKey:Il0.create(ee(X))})})}returning(X){return new c9({...this.#X,queryNode:A6.cloneWithReturning(this.#X.queryNode,sY(X))})}returningAll(){return new c9({...this.#X,queryNode:A6.cloneWithReturning(this.#X.queryNode,MG())})}output(X){return new c9({...this.#X,queryNode:A6.cloneWithOutput(this.#X.queryNode,sY(X))})}outputAll(X){return new c9({...this.#X,queryNode:A6.cloneWithOutput(this.#X.queryNode,MG(X))})}clearReturning(){return new c9({...this.#X,queryNode:A6.cloneWithoutReturning(this.#X.queryNode)})}$call(X){return X(this)}$if(X,Y){if(X)return Y(this);return new c9({...this.#X})}$castTo(){return new c9(this.#X)}$narrowType(){return new c9(this.#X)}$assertType(){return new c9(this.#X)}withPlugin(X){return new c9({...this.#X,executor:this.#X.executor.withPlugin(X)})}toOperationNode(){return this.#X.executor.transformQuery(this.#X.queryNode,this.#X.queryId)}compile(){return this.#X.executor.compileQuery(this.toOperationNode(),this.#X.queryId)}async execute(){let X=this.compile(),Y=await this.#X.executor.executeQuery(X),{adapter:G}=this.#X.executor,Q=X.query;if(Q.returning&&G.supportsReturning||Q.output&&G.supportsOutput)return Y.rows;return[new wa1(Y.insertId,Y.numAffectedRows??BigInt(0))]}async executeTakeFirst(){let[X]=await this.execute();return X}async executeTakeFirstOrThrow(X=UF){let Y=await this.executeTakeFirst();if(Y===void 0)throw PN(X)?new X(this.toOperationNode()):X(this.toOperationNode());return Y}async*stream(X=100){let Y=this.compile(),G=this.#X.executor.stream(Y,X);for await(let Q of G)yield*Q.rows}async explain(X,Y){return await new c9({...this.#X,queryNode:A6.cloneWithExplain(this.#X.queryNode,X,Y)}).execute()}}var qa1=D(()=>{sL();Ba1();eT();PK();o$1();W0();Da1();QI();HF();EJ();La1();s$1();yd();Pa1()});class Aa1{numDeletedRows;constructor(X){this.numDeletedRows=X}}var xd;var Y11=D(()=>{W0();xd=n({is(X){return X.kind==="LimitNode"},create(X){return n({kind:"LimitNode",limit:X})}})});class e$1{#X;constructor(X){this.#X=n(X)}where(...X){return new hX({...this.#X,queryNode:A6.cloneWithWhere(this.#X.queryNode,N7(X))})}whereRef(X,Y,G){return new hX({...this.#X,queryNode:A6.cloneWithWhere(this.#X.queryNode,jG(X,Y,G))})}clearWhere(){return new hX({...this.#X,queryNode:A6.cloneWithoutWhere(this.#X.queryNode)})}top(X,Y){return new hX({...this.#X,queryNode:A6.cloneWithTop(this.#X.queryNode,NF(X,Y))})}using(X){return new hX({...this.#X,queryNode:oL.cloneWithUsing(this.#X.queryNode,BF(X))})}innerJoin(...X){return this.#Y("InnerJoin",X)}leftJoin(...X){return this.#Y("LeftJoin",X)}rightJoin(...X){return this.#Y("RightJoin",X)}fullJoin(...X){return this.#Y("FullJoin",X)}#Y(X,Y){return new hX({...this.#X,queryNode:A6.cloneWithJoin(this.#X.queryNode,eL(X,Y))})}returning(X){return new hX({...this.#X,queryNode:A6.cloneWithReturning(this.#X.queryNode,sY(X))})}returningAll(X){return new hX({...this.#X,queryNode:A6.cloneWithReturning(this.#X.queryNode,MG(X))})}output(X){return new hX({...this.#X,queryNode:A6.cloneWithOutput(this.#X.queryNode,sY(X))})}outputAll(X){return new hX({...this.#X,queryNode:A6.cloneWithOutput(this.#X.queryNode,MG(X))})}clearReturning(){return new hX({...this.#X,queryNode:A6.cloneWithoutReturning(this.#X.queryNode)})}clearLimit(){return new hX({...this.#X,queryNode:oL.cloneWithoutLimit(this.#X.queryNode)})}orderBy(...X){return new hX({...this.#X,queryNode:A6.cloneWithOrderByItems(this.#X.queryNode,tW(X))})}clearOrderBy(){return new hX({...this.#X,queryNode:A6.cloneWithoutOrderBy(this.#X.queryNode)})}limit(X){return new hX({...this.#X,queryNode:oL.cloneWithLimit(this.#X.queryNode,xd.create(d9(X)))})}modifyEnd(X){return new hX({...this.#X,queryNode:A6.cloneWithEndModifier(this.#X.queryNode,X.toOperationNode())})}$call(X){return X(this)}$if(X,Y){if(X)return Y(this);return new hX({...this.#X})}$castTo(){return new hX(this.#X)}$narrowType(){return new hX(this.#X)}$assertType(){return new hX(this.#X)}withPlugin(X){return new hX({...this.#X,executor:this.#X.executor.withPlugin(X)})}toOperationNode(){return this.#X.executor.transformQuery(this.#X.queryNode,this.#X.queryId)}compile(){return this.#X.executor.compileQuery(this.toOperationNode(),this.#X.queryId)}async execute(){let X=this.compile(),Y=await this.#X.executor.executeQuery(X),{adapter:G}=this.#X.executor,Q=X.query;if(Q.returning&&G.supportsReturning||Q.output&&G.supportsOutput)return Y.rows;return[new Aa1(Y.numAffectedRows??BigInt(0))]}async executeTakeFirst(){let[X]=await this.execute();return X}async executeTakeFirstOrThrow(X=UF){let Y=await this.executeTakeFirst();if(Y===void 0)throw PN(X)?new X(this.toOperationNode()):X(this.toOperationNode());return Y}async*stream(X=100){let Y=this.compile(),G=this.#X.executor.stream(Y,X);for await(let Q of G)yield*Q.rows}async explain(X,Y){return await new hX({...this.#X,queryNode:A6.cloneWithExplain(this.#X.queryNode,X,Y)}).execute()}}var hX;var Ta1=D(()=>{G11();LQ();sL();PK();W0();QI();re();Y11();rT();oW();LN();yd();hX=e$1});class Ia1{numUpdatedRows;numChangedRows;constructor(X,Y){this.numUpdatedRows=X,this.numChangedRows=Y}}class hd{#X;constructor(X){this.#X=n(X)}where(...X){return new gX({...this.#X,queryNode:A6.cloneWithWhere(this.#X.queryNode,N7(X))})}whereRef(X,Y,G){return new gX({...this.#X,queryNode:A6.cloneWithWhere(this.#X.queryNode,jG(X,Y,G))})}clearWhere(){return new gX({...this.#X,queryNode:A6.cloneWithoutWhere(this.#X.queryNode)})}top(X,Y){return new gX({...this.#X,queryNode:A6.cloneWithTop(this.#X.queryNode,NF(X,Y))})}from(X){return new gX({...this.#X,queryNode:EN.cloneWithFromItems(this.#X.queryNode,BF(X))})}innerJoin(...X){return this.#Y("InnerJoin",X)}leftJoin(...X){return this.#Y("LeftJoin",X)}rightJoin(...X){return this.#Y("RightJoin",X)}fullJoin(...X){return this.#Y("FullJoin",X)}#Y(X,Y){return new gX({...this.#X,queryNode:A6.cloneWithJoin(this.#X.queryNode,eL(X,Y))})}orderBy(...X){return new gX({...this.#X,queryNode:A6.cloneWithOrderByItems(this.#X.queryNode,tW(X))})}clearOrderBy(){return new gX({...this.#X,queryNode:A6.cloneWithoutOrderBy(this.#X.queryNode)})}limit(X){return new gX({...this.#X,queryNode:EN.cloneWithLimit(this.#X.queryNode,xd.create(d9(X)))})}set(...X){return new gX({...this.#X,queryNode:EN.cloneWithUpdates(this.#X.queryNode,Tl0(...X))})}returning(X){return new gX({...this.#X,queryNode:A6.cloneWithReturning(this.#X.queryNode,sY(X))})}returningAll(X){return new gX({...this.#X,queryNode:A6.cloneWithReturning(this.#X.queryNode,MG(X))})}output(X){return new gX({...this.#X,queryNode:A6.cloneWithOutput(this.#X.queryNode,sY(X))})}outputAll(X){return new gX({...this.#X,queryNode:A6.cloneWithOutput(this.#X.queryNode,MG(X))})}modifyEnd(X){return new gX({...this.#X,queryNode:A6.cloneWithEndModifier(this.#X.queryNode,X.toOperationNode())})}clearReturning(){return new gX({...this.#X,queryNode:A6.cloneWithoutReturning(this.#X.queryNode)})}$call(X){return X(this)}$if(X,Y){if(X)return Y(this);return new gX({...this.#X})}$castTo(){return new gX(this.#X)}$narrowType(){return new gX(this.#X)}$assertType(){return new gX(this.#X)}withPlugin(X){return new gX({...this.#X,executor:this.#X.executor.withPlugin(X)})}toOperationNode(){return this.#X.executor.transformQuery(this.#X.queryNode,this.#X.queryId)}compile(){return this.#X.executor.compileQuery(this.toOperationNode(),this.#X.queryId)}async execute(){let X=this.compile(),Y=await this.#X.executor.executeQuery(X),{adapter:G}=this.#X.executor,Q=X.query;if(Q.returning&&G.supportsReturning||Q.output&&G.supportsOutput)return Y.rows;return[new Ia1(Y.numAffectedRows??BigInt(0),Y.numChangedRows)]}async executeTakeFirst(){let[X]=await this.execute();return X}async executeTakeFirstOrThrow(X=UF){let Y=await this.executeTakeFirst();if(Y===void 0)throw PN(X)?new X(this.toOperationNode()):X(this.toOperationNode());return Y}async*stream(X=100){let Y=this.compile(),G=this.#X.executor.stream(Y,X);for await(let Q of G)yield*Q.rows}async explain(X,Y){return await new gX({...this.#X,queryNode:A6.cloneWithExplain(this.#X.queryNode,X,Y)}).execute()}}var gX;var XK1=D(()=>{G11();LQ();sL();PK();vd();o$1();W0();QI();oW();LN();Y11();yd();rT();gX=hd});var Va1;var ja1=D(()=>{W0();EJ();Td();Va1=n({is(X){return X.kind==="CommonTableExpressionNameNode"},create(X,Y){return n({kind:"CommonTableExpressionNameNode",table:_3.create(X),columns:Y?n(Y.map(T5.create)):void 0})}})});var gd;var YK1=D(()=>{W0();gd=n({is(X){return X.kind==="CommonTableExpressionNode"},create(X,Y){return n({kind:"CommonTableExpressionNode",name:X,expression:Y})},cloneWith(X,Y){return n({...X,...Y})}})});class Q11{#X;constructor(X){this.#X=n(X)}materialized(){return new Q11({...this.#X,node:gd.cloneWith(this.#X.node,{materialized:!0})})}notMaterialized(){return new Q11({...this.#X,node:gd.cloneWith(this.#X.node,{materialized:!1})})}toOperationNode(){return this.#X.node}}var Ml0=D(()=>{YK1();W0()});function Ma1(X,Y){let G=Y(Cl0()).toOperationNode();if(F9(X))return X(VO8(G)).toOperationNode();return gd.create(Rl0(X),G)}function VO8(X){return(Y)=>{return new Q11({node:gd.create(Rl0(Y),X)})}}function Rl0(X){if(X.includes("(")){let Y=X.split(/[\(\)]/),G=Y[0],Q=Y[1].split(",").map((J)=>J.trim());return Va1.create(G,Q)}else return Va1.create(X)}var Sl0=D(()=>{ja1();GK1();W0();Ml0();YK1()});var J11;var Ra1=D(()=>{W0();J11=n({is(X){return X.kind==="WithNode"},create(X,Y){return n({kind:"WithNode",expressions:n([X]),...Y})},cloneWithExpression(X,Y){return n({...X,expressions:n([...X.expressions,Y])})}})});function QK1(X){let Y="";for(let G=0;G<X;++G)Y+=jO8();return Y}function jO8(){return kl0[~~(Math.random()*kl0.length)]}var kl0;var Sa1=D(()=>{kl0=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9"]});function e4(){return new vl0}class vl0{#X;get queryId(){if(this.#X===void 0)this.#X=QK1(8);return this.#X}}var AN=D(()=>{Sa1()});function z6(X){return X}class zF{nodeStack=[];#X=n({AliasNode:this.transformAlias.bind(this),ColumnNode:this.transformColumn.bind(this),IdentifierNode:this.transformIdentifier.bind(this),SchemableIdentifierNode:this.transformSchemableIdentifier.bind(this),RawNode:this.transformRaw.bind(this),ReferenceNode:this.transformReference.bind(this),SelectQueryNode:this.transformSelectQuery.bind(this),SelectionNode:this.transformSelection.bind(this),TableNode:this.transformTable.bind(this),FromNode:this.transformFrom.bind(this),SelectAllNode:this.transformSelectAll.bind(this),AndNode:this.transformAnd.bind(this),OrNode:this.transformOr.bind(this),ValueNode:this.transformValue.bind(this),ValueListNode:this.transformValueList.bind(this),PrimitiveValueListNode:this.transformPrimitiveValueList.bind(this),ParensNode:this.transformParens.bind(this),JoinNode:this.transformJoin.bind(this),OperatorNode:this.transformOperator.bind(this),WhereNode:this.transformWhere.bind(this),InsertQueryNode:this.transformInsertQuery.bind(this),DeleteQueryNode:this.transformDeleteQuery.bind(this),ReturningNode:this.transformReturning.bind(this),CreateTableNode:this.transformCreateTable.bind(this),AddColumnNode:this.transformAddColumn.bind(this),ColumnDefinitionNode:this.transformColumnDefinition.bind(this),DropTableNode:this.transformDropTable.bind(this),DataTypeNode:this.transformDataType.bind(this),OrderByNode:this.transformOrderBy.bind(this),OrderByItemNode:this.transformOrderByItem.bind(this),GroupByNode:this.transformGroupBy.bind(this),GroupByItemNode:this.transformGroupByItem.bind(this),UpdateQueryNode:this.transformUpdateQuery.bind(this),ColumnUpdateNode:this.transformColumnUpdate.bind(this),LimitNode:this.transformLimit.bind(this),OffsetNode:this.transformOffset.bind(this),OnConflictNode:this.transformOnConflict.bind(this),OnDuplicateKeyNode:this.transformOnDuplicateKey.bind(this),CreateIndexNode:this.transformCreateIndex.bind(this),DropIndexNode:this.transformDropIndex.bind(this),ListNode:this.transformList.bind(this),PrimaryKeyConstraintNode:this.transformPrimaryKeyConstraint.bind(this),UniqueConstraintNode:this.transformUniqueConstraint.bind(this),ReferencesNode:this.transformReferences.bind(this),CheckConstraintNode:this.transformCheckConstraint.bind(this),WithNode:this.transformWith.bind(this),CommonTableExpressionNode:this.transformCommonTableExpression.bind(this),CommonTableExpressionNameNode:this.transformCommonTableExpressionName.bind(this),HavingNode:this.transformHaving.bind(this),CreateSchemaNode:this.transformCreateSchema.bind(this),DropSchemaNode:this.transformDropSchema.bind(this),AlterTableNode:this.transformAlterTable.bind(this),DropColumnNode:this.transformDropColumn.bind(this),RenameColumnNode:this.transformRenameColumn.bind(this),AlterColumnNode:this.transformAlterColumn.bind(this),ModifyColumnNode:this.transformModifyColumn.bind(this),AddConstraintNode:this.transformAddConstraint.bind(this),DropConstraintNode:this.transformDropConstraint.bind(this),RenameConstraintNode:this.transformRenameConstraint.bind(this),ForeignKeyConstraintNode:this.transformForeignKeyConstraint.bind(this),CreateViewNode:this.transformCreateView.bind(this),RefreshMaterializedViewNode:this.transformRefreshMaterializedView.bind(this),DropViewNode:this.transformDropView.bind(this),GeneratedNode:this.transformGenerated.bind(this),DefaultValueNode:this.transformDefaultValue.bind(this),OnNode:this.transformOn.bind(this),ValuesNode:this.transformValues.bind(this),SelectModifierNode:this.transformSelectModifier.bind(this),CreateTypeNode:this.transformCreateType.bind(this),DropTypeNode:this.transformDropType.bind(this),ExplainNode:this.transformExplain.bind(this),DefaultInsertValueNode:this.transformDefaultInsertValue.bind(this),AggregateFunctionNode:this.transformAggregateFunction.bind(this),OverNode:this.transformOver.bind(this),PartitionByNode:this.transformPartitionBy.bind(this),PartitionByItemNode:this.transformPartitionByItem.bind(this),SetOperationNode:this.transformSetOperation.bind(this),BinaryOperationNode:this.transformBinaryOperation.bind(this),UnaryOperationNode:this.transformUnaryOperation.bind(this),UsingNode:this.transformUsing.bind(this),FunctionNode:this.transformFunction.bind(this),CaseNode:this.transformCase.bind(this),WhenNode:this.transformWhen.bind(this),JSONReferenceNode:this.transformJSONReference.bind(this),JSONPathNode:this.transformJSONPath.bind(this),JSONPathLegNode:this.transformJSONPathLeg.bind(this),JSONOperatorChainNode:this.transformJSONOperatorChain.bind(this),TupleNode:this.transformTuple.bind(this),MergeQueryNode:this.transformMergeQuery.bind(this),MatchedNode:this.transformMatched.bind(this),AddIndexNode:this.transformAddIndex.bind(this),CastNode:this.transformCast.bind(this),FetchNode:this.transformFetch.bind(this),TopNode:this.transformTop.bind(this),OutputNode:this.transformOutput.bind(this),OrActionNode:this.transformOrAction.bind(this),CollateNode:this.transformCollate.bind(this)});transformNode(X,Y){if(!X)return X;this.nodeStack.push(X);let G=this.transformNodeImpl(X,Y);return this.nodeStack.pop(),n(G)}transformNodeImpl(X,Y){return this.#X[X.kind](X,Y)}transformNodeList(X,Y){if(!X)return X;return n(X.map((G)=>this.transformNode(G,Y)))}transformSelectQuery(X,Y){return z6({kind:"SelectQueryNode",from:this.transformNode(X.from,Y),selections:this.transformNodeList(X.selections,Y),distinctOn:this.transformNodeList(X.distinctOn,Y),joins:this.transformNodeList(X.joins,Y),groupBy:this.transformNode(X.groupBy,Y),orderBy:this.transformNode(X.orderBy,Y),where:this.transformNode(X.where,Y),frontModifiers:this.transformNodeList(X.frontModifiers,Y),endModifiers:this.transformNodeList(X.endModifiers,Y),limit:this.transformNode(X.limit,Y),offset:this.transformNode(X.offset,Y),with:this.transformNode(X.with,Y),having:this.transformNode(X.having,Y),explain:this.transformNode(X.explain,Y),setOperations:this.transformNodeList(X.setOperations,Y),fetch:this.transformNode(X.fetch,Y),top:this.transformNode(X.top,Y)})}transformSelection(X,Y){return z6({kind:"SelectionNode",selection:this.transformNode(X.selection,Y)})}transformColumn(X,Y){return z6({kind:"ColumnNode",column:this.transformNode(X.column,Y)})}transformAlias(X,Y){return z6({kind:"AliasNode",node:this.transformNode(X.node,Y),alias:this.transformNode(X.alias,Y)})}transformTable(X,Y){return z6({kind:"TableNode",table:this.transformNode(X.table,Y)})}transformFrom(X,Y){return z6({kind:"FromNode",froms:this.transformNodeList(X.froms,Y)})}transformReference(X,Y){return z6({kind:"ReferenceNode",column:this.transformNode(X.column,Y),table:this.transformNode(X.table,Y)})}transformAnd(X,Y){return z6({kind:"AndNode",left:this.transformNode(X.left,Y),right:this.transformNode(X.right,Y)})}transformOr(X,Y){return z6({kind:"OrNode",left:this.transformNode(X.left,Y),right:this.transformNode(X.right,Y)})}transformValueList(X,Y){return z6({kind:"ValueListNode",values:this.transformNodeList(X.values,Y)})}transformParens(X,Y){return z6({kind:"ParensNode",node:this.transformNode(X.node,Y)})}transformJoin(X,Y){return z6({kind:"JoinNode",joinType:X.joinType,table:this.transformNode(X.table,Y),on:this.transformNode(X.on,Y)})}transformRaw(X,Y){return z6({kind:"RawNode",sqlFragments:n([...X.sqlFragments]),parameters:this.transformNodeList(X.parameters,Y)})}transformWhere(X,Y){return z6({kind:"WhereNode",where:this.transformNode(X.where,Y)})}transformInsertQuery(X,Y){return z6({kind:"InsertQueryNode",into:this.transformNode(X.into,Y),columns:this.transformNodeList(X.columns,Y),values:this.transformNode(X.values,Y),returning:this.transformNode(X.returning,Y),onConflict:this.transformNode(X.onConflict,Y),onDuplicateKey:this.transformNode(X.onDuplicateKey,Y),endModifiers:this.transformNodeList(X.endModifiers,Y),with:this.transformNode(X.with,Y),ignore:X.ignore,orAction:this.transformNode(X.orAction,Y),replace:X.replace,explain:this.transformNode(X.explain,Y),defaultValues:X.defaultValues,top:this.transformNode(X.top,Y),output:this.transformNode(X.output,Y)})}transformValues(X,Y){return z6({kind:"ValuesNode",values:this.transformNodeList(X.values,Y)})}transformDeleteQuery(X,Y){return z6({kind:"DeleteQueryNode",from:this.transformNode(X.from,Y),using:this.transformNode(X.using,Y),joins:this.transformNodeList(X.joins,Y),where:this.transformNode(X.where,Y),returning:this.transformNode(X.returning,Y),endModifiers:this.transformNodeList(X.endModifiers,Y),with:this.transformNode(X.with,Y),orderBy:this.transformNode(X.orderBy,Y),limit:this.transformNode(X.limit,Y),explain:this.transformNode(X.explain,Y),top:this.transformNode(X.top,Y),output:this.transformNode(X.output,Y)})}transformReturning(X,Y){return z6({kind:"ReturningNode",selections:this.transformNodeList(X.selections,Y)})}transformCreateTable(X,Y){return z6({kind:"CreateTableNode",table:this.transformNode(X.table,Y),columns:this.transformNodeList(X.columns,Y),constraints:this.transformNodeList(X.constraints,Y),temporary:X.temporary,ifNotExists:X.ifNotExists,onCommit:X.onCommit,frontModifiers:this.transformNodeList(X.frontModifiers,Y),endModifiers:this.transformNodeList(X.endModifiers,Y),selectQuery:this.transformNode(X.selectQuery,Y)})}transformColumnDefinition(X,Y){return z6({kind:"ColumnDefinitionNode",column:this.transformNode(X.column,Y),dataType:this.transformNode(X.dataType,Y),references:this.transformNode(X.references,Y),primaryKey:X.primaryKey,autoIncrement:X.autoIncrement,unique:X.unique,notNull:X.notNull,unsigned:X.unsigned,defaultTo:this.transformNode(X.defaultTo,Y),check:this.transformNode(X.check,Y),generated:this.transformNode(X.generated,Y),frontModifiers:this.transformNodeList(X.frontModifiers,Y),endModifiers:this.transformNodeList(X.endModifiers,Y),nullsNotDistinct:X.nullsNotDistinct,identity:X.identity,ifNotExists:X.ifNotExists})}transformAddColumn(X,Y){return z6({kind:"AddColumnNode",column:this.transformNode(X.column,Y)})}transformDropTable(X,Y){return z6({kind:"DropTableNode",table:this.transformNode(X.table,Y),ifExists:X.ifExists,cascade:X.cascade})}transformOrderBy(X,Y){return z6({kind:"OrderByNode",items:this.transformNodeList(X.items,Y)})}transformOrderByItem(X,Y){return z6({kind:"OrderByItemNode",orderBy:this.transformNode(X.orderBy,Y),direction:this.transformNode(X.direction,Y),collation:this.transformNode(X.collation,Y),nulls:X.nulls})}transformGroupBy(X,Y){return z6({kind:"GroupByNode",items:this.transformNodeList(X.items,Y)})}transformGroupByItem(X,Y){return z6({kind:"GroupByItemNode",groupBy:this.transformNode(X.groupBy,Y)})}transformUpdateQuery(X,Y){return z6({kind:"UpdateQueryNode",table:this.transformNode(X.table,Y),from:this.transformNode(X.from,Y),joins:this.transformNodeList(X.joins,Y),where:this.transformNode(X.where,Y),updates:this.transformNodeList(X.updates,Y),returning:this.transformNode(X.returning,Y),endModifiers:this.transformNodeList(X.endModifiers,Y),with:this.transformNode(X.with,Y),explain:this.transformNode(X.explain,Y),limit:this.transformNode(X.limit,Y),top:this.transformNode(X.top,Y),output:this.transformNode(X.output,Y),orderBy:this.transformNode(X.orderBy,Y)})}transformColumnUpdate(X,Y){return z6({kind:"ColumnUpdateNode",column:this.transformNode(X.column,Y),value:this.transformNode(X.value,Y)})}transformLimit(X,Y){return z6({kind:"LimitNode",limit:this.transformNode(X.limit,Y)})}transformOffset(X,Y){return z6({kind:"OffsetNode",offset:this.transformNode(X.offset,Y)})}transformOnConflict(X,Y){return z6({kind:"OnConflictNode",columns:this.transformNodeList(X.columns,Y),constraint:this.transformNode(X.constraint,Y),indexExpression:this.transformNode(X.indexExpression,Y),indexWhere:this.transformNode(X.indexWhere,Y),updates:this.transformNodeList(X.updates,Y),updateWhere:this.transformNode(X.updateWhere,Y),doNothing:X.doNothing})}transformOnDuplicateKey(X,Y){return z6({kind:"OnDuplicateKeyNode",updates:this.transformNodeList(X.updates,Y)})}transformCreateIndex(X,Y){return z6({kind:"CreateIndexNode",name:this.transformNode(X.name,Y),table:this.transformNode(X.table,Y),columns:this.transformNodeList(X.columns,Y),unique:X.unique,using:this.transformNode(X.using,Y),ifNotExists:X.ifNotExists,where:this.transformNode(X.where,Y),nullsNotDistinct:X.nullsNotDistinct})}transformList(X,Y){return z6({kind:"ListNode",items:this.transformNodeList(X.items,Y)})}transformDropIndex(X,Y){return z6({kind:"DropIndexNode",name:this.transformNode(X.name,Y),table:this.transformNode(X.table,Y),ifExists:X.ifExists,cascade:X.cascade})}transformPrimaryKeyConstraint(X,Y){return z6({kind:"PrimaryKeyConstraintNode",columns:this.transformNodeList(X.columns,Y),name:this.transformNode(X.name,Y),deferrable:X.deferrable,initiallyDeferred:X.initiallyDeferred})}transformUniqueConstraint(X,Y){return z6({kind:"UniqueConstraintNode",columns:this.transformNodeList(X.columns,Y),name:this.transformNode(X.name,Y),nullsNotDistinct:X.nullsNotDistinct,deferrable:X.deferrable,initiallyDeferred:X.initiallyDeferred})}transformForeignKeyConstraint(X,Y){return z6({kind:"ForeignKeyConstraintNode",columns:this.transformNodeList(X.columns,Y),references:this.transformNode(X.references,Y),name:this.transformNode(X.name,Y),onDelete:X.onDelete,onUpdate:X.onUpdate,deferrable:X.deferrable,initiallyDeferred:X.initiallyDeferred})}transformSetOperation(X,Y){return z6({kind:"SetOperationNode",operator:X.operator,expression:this.transformNode(X.expression,Y),all:X.all})}transformReferences(X,Y){return z6({kind:"ReferencesNode",table:this.transformNode(X.table,Y),columns:this.transformNodeList(X.columns,Y),onDelete:X.onDelete,onUpdate:X.onUpdate})}transformCheckConstraint(X,Y){return z6({kind:"CheckConstraintNode",expression:this.transformNode(X.expression,Y),name:this.transformNode(X.name,Y)})}transformWith(X,Y){return z6({kind:"WithNode",expressions:this.transformNodeList(X.expressions,Y),recursive:X.recursive})}transformCommonTableExpression(X,Y){return z6({kind:"CommonTableExpressionNode",name:this.transformNode(X.name,Y),materialized:X.materialized,expression:this.transformNode(X.expression,Y)})}transformCommonTableExpressionName(X,Y){return z6({kind:"CommonTableExpressionNameNode",table:this.transformNode(X.table,Y),columns:this.transformNodeList(X.columns,Y)})}transformHaving(X,Y){return z6({kind:"HavingNode",having:this.transformNode(X.having,Y)})}transformCreateSchema(X,Y){return z6({kind:"CreateSchemaNode",schema:this.transformNode(X.schema,Y),ifNotExists:X.ifNotExists})}transformDropSchema(X,Y){return z6({kind:"DropSchemaNode",schema:this.transformNode(X.schema,Y),ifExists:X.ifExists,cascade:X.cascade})}transformAlterTable(X,Y){return z6({kind:"AlterTableNode",table:this.transformNode(X.table,Y),renameTo:this.transformNode(X.renameTo,Y),setSchema:this.transformNode(X.setSchema,Y),columnAlterations:this.transformNodeList(X.columnAlterations,Y),addConstraint:this.transformNode(X.addConstraint,Y),dropConstraint:this.transformNode(X.dropConstraint,Y),renameConstraint:this.transformNode(X.renameConstraint,Y),addIndex:this.transformNode(X.addIndex,Y),dropIndex:this.transformNode(X.dropIndex,Y)})}transformDropColumn(X,Y){return z6({kind:"DropColumnNode",column:this.transformNode(X.column,Y)})}transformRenameColumn(X,Y){return z6({kind:"RenameColumnNode",column:this.transformNode(X.column,Y),renameTo:this.transformNode(X.renameTo,Y)})}transformAlterColumn(X,Y){return z6({kind:"AlterColumnNode",column:this.transformNode(X.column,Y),dataType:this.transformNode(X.dataType,Y),dataTypeExpression:this.transformNode(X.dataTypeExpression,Y),setDefault:this.transformNode(X.setDefault,Y),dropDefault:X.dropDefault,setNotNull:X.setNotNull,dropNotNull:X.dropNotNull})}transformModifyColumn(X,Y){return z6({kind:"ModifyColumnNode",column:this.transformNode(X.column,Y)})}transformAddConstraint(X,Y){return z6({kind:"AddConstraintNode",constraint:this.transformNode(X.constraint,Y)})}transformDropConstraint(X,Y){return z6({kind:"DropConstraintNode",constraintName:this.transformNode(X.constraintName,Y),ifExists:X.ifExists,modifier:X.modifier})}transformRenameConstraint(X,Y){return z6({kind:"RenameConstraintNode",oldName:this.transformNode(X.oldName,Y),newName:this.transformNode(X.newName,Y)})}transformCreateView(X,Y){return z6({kind:"CreateViewNode",name:this.transformNode(X.name,Y),temporary:X.temporary,orReplace:X.orReplace,ifNotExists:X.ifNotExists,materialized:X.materialized,columns:this.transformNodeList(X.columns,Y),as:this.transformNode(X.as,Y)})}transformRefreshMaterializedView(X,Y){return z6({kind:"RefreshMaterializedViewNode",name:this.transformNode(X.name,Y),concurrently:X.concurrently,withNoData:X.withNoData})}transformDropView(X,Y){return z6({kind:"DropViewNode",name:this.transformNode(X.name,Y),ifExists:X.ifExists,materialized:X.materialized,cascade:X.cascade})}transformGenerated(X,Y){return z6({kind:"GeneratedNode",byDefault:X.byDefault,always:X.always,identity:X.identity,stored:X.stored,expression:this.transformNode(X.expression,Y)})}transformDefaultValue(X,Y){return z6({kind:"DefaultValueNode",defaultValue:this.transformNode(X.defaultValue,Y)})}transformOn(X,Y){return z6({kind:"OnNode",on:this.transformNode(X.on,Y)})}transformSelectModifier(X,Y){return z6({kind:"SelectModifierNode",modifier:X.modifier,rawModifier:this.transformNode(X.rawModifier,Y),of:this.transformNodeList(X.of,Y)})}transformCreateType(X,Y){return z6({kind:"CreateTypeNode",name:this.transformNode(X.name,Y),enum:this.transformNode(X.enum,Y)})}transformDropType(X,Y){return z6({kind:"DropTypeNode",name:this.transformNode(X.name,Y),ifExists:X.ifExists})}transformExplain(X,Y){return z6({kind:"ExplainNode",format:X.format,options:this.transformNode(X.options,Y)})}transformSchemableIdentifier(X,Y){return z6({kind:"SchemableIdentifierNode",schema:this.transformNode(X.schema,Y),identifier:this.transformNode(X.identifier,Y)})}transformAggregateFunction(X,Y){return z6({kind:"AggregateFunctionNode",func:X.func,aggregated:this.transformNodeList(X.aggregated,Y),distinct:X.distinct,orderBy:this.transformNode(X.orderBy,Y),withinGroup:this.transformNode(X.withinGroup,Y),filter:this.transformNode(X.filter,Y),over:this.transformNode(X.over,Y)})}transformOver(X,Y){return z6({kind:"OverNode",orderBy:this.transformNode(X.orderBy,Y),partitionBy:this.transformNode(X.partitionBy,Y)})}transformPartitionBy(X,Y){return z6({kind:"PartitionByNode",items:this.transformNodeList(X.items,Y)})}transformPartitionByItem(X,Y){return z6({kind:"PartitionByItemNode",partitionBy:this.transformNode(X.partitionBy,Y)})}transformBinaryOperation(X,Y){return z6({kind:"BinaryOperationNode",leftOperand:this.transformNode(X.leftOperand,Y),operator:this.transformNode(X.operator,Y),rightOperand:this.transformNode(X.rightOperand,Y)})}transformUnaryOperation(X,Y){return z6({kind:"UnaryOperationNode",operator:this.transformNode(X.operator,Y),operand:this.transformNode(X.operand,Y)})}transformUsing(X,Y){return z6({kind:"UsingNode",tables:this.transformNodeList(X.tables,Y)})}transformFunction(X,Y){return z6({kind:"FunctionNode",func:X.func,arguments:this.transformNodeList(X.arguments,Y)})}transformCase(X,Y){return z6({kind:"CaseNode",value:this.transformNode(X.value,Y),when:this.transformNodeList(X.when,Y),else:this.transformNode(X.else,Y),isStatement:X.isStatement})}transformWhen(X,Y){return z6({kind:"WhenNode",condition:this.transformNode(X.condition,Y),result:this.transformNode(X.result,Y)})}transformJSONReference(X,Y){return z6({kind:"JSONReferenceNode",reference:this.transformNode(X.reference,Y),traversal:this.transformNode(X.traversal,Y)})}transformJSONPath(X,Y){return z6({kind:"JSONPathNode",inOperator:this.transformNode(X.inOperator,Y),pathLegs:this.transformNodeList(X.pathLegs,Y)})}transformJSONPathLeg(X,Y){return z6({kind:"JSONPathLegNode",type:X.type,value:X.value})}transformJSONOperatorChain(X,Y){return z6({kind:"JSONOperatorChainNode",operator:this.transformNode(X.operator,Y),values:this.transformNodeList(X.values,Y)})}transformTuple(X,Y){return z6({kind:"TupleNode",values:this.transformNodeList(X.values,Y)})}transformMergeQuery(X,Y){return z6({kind:"MergeQueryNode",into:this.transformNode(X.into,Y),using:this.transformNode(X.using,Y),whens:this.transformNodeList(X.whens,Y),with:this.transformNode(X.with,Y),top:this.transformNode(X.top,Y),endModifiers:this.transformNodeList(X.endModifiers,Y),output:this.transformNode(X.output,Y),returning:this.transformNode(X.returning,Y)})}transformMatched(X,Y){return z6({kind:"MatchedNode",not:X.not,bySource:X.bySource})}transformAddIndex(X,Y){return z6({kind:"AddIndexNode",name:this.transformNode(X.name,Y),columns:this.transformNodeList(X.columns,Y),unique:X.unique,using:this.transformNode(X.using,Y),ifNotExists:X.ifNotExists})}transformCast(X,Y){return z6({kind:"CastNode",expression:this.transformNode(X.expression,Y),dataType:this.transformNode(X.dataType,Y)})}transformFetch(X,Y){return z6({kind:"FetchNode",rowCount:this.transformNode(X.rowCount,Y),modifier:X.modifier})}transformTop(X,Y){return z6({kind:"TopNode",expression:X.expression,modifiers:X.modifiers})}transformOutput(X,Y){return z6({kind:"OutputNode",selections:this.transformNodeList(X.selections,Y)})}transformDataType(X,Y){return X}transformSelectAll(X,Y){return X}transformIdentifier(X,Y){return X}transformValue(X,Y){return X}transformPrimitiveValueList(X,Y){return X}transformOperator(X,Y){return X}transformDefaultInsertValue(X,Y){return X}transformOrAction(X,Y){return X}transformCollate(X,Y){return X}}var ZI=D(()=>{W0()});var MO8,RO8,Ca1;var _l0=D(()=>{ZF();U7();Id();n$1();ZI();NO();Td();a$1();W0();MO8=n({AlterTableNode:!0,CreateIndexNode:!0,CreateSchemaNode:!0,CreateTableNode:!0,CreateTypeNode:!0,CreateViewNode:!0,RefreshMaterializedViewNode:!0,DeleteQueryNode:!0,DropIndexNode:!0,DropSchemaNode:!0,DropTableNode:!0,DropTypeNode:!0,DropViewNode:!0,InsertQueryNode:!0,RawNode:!0,SelectQueryNode:!0,UpdateQueryNode:!0,MergeQueryNode:!0}),RO8={json_agg:!0,to_json:!0};Ca1=class Ca1 extends zF{#X;#Y=new Set;#G=new Set;constructor(X){super();this.#X=X}transformNodeImpl(X,Y){if(!this.#J(X))return super.transformNodeImpl(X,Y);let G=this.#$(X);for(let W of G)this.#G.add(W);let Q=this.#Z(X);for(let W of Q)this.#Y.add(W);let J=super.transformNodeImpl(X,Y);for(let W of Q)this.#Y.delete(W);for(let W of G)this.#G.delete(W);return J}transformSchemableIdentifier(X,Y){let G=super.transformSchemableIdentifier(X,Y);if(G.schema||!this.#Y.has(X.identifier.name))return G;return{...G,schema:k4.create(this.#X)}}transformReferences(X,Y){let G=super.transformReferences(X,Y);if(G.table.table.schema)return G;return{...G,table:_3.createWithSchema(this.#X,G.table.table.identifier.name)}}transformAggregateFunction(X,Y){return{...super.transformAggregateFunction({...X,aggregated:[]},Y),aggregated:this.#Q(X,Y,"aggregated")}}transformFunction(X,Y){return{...super.transformFunction({...X,arguments:[]},Y),arguments:this.#Q(X,Y,"arguments")}}transformSelectModifier(X,Y){return{...super.transformSelectModifier({...X,of:void 0},Y),of:X.of?.map((G)=>_3.is(G)&&!G.table.schema?{...G,table:this.transformIdentifier(G.table.identifier,Y)}:this.transformNode(G,Y))}}#Q(X,Y,G){return RO8[X.func]?X[G].map((Q)=>!_3.is(Q)||Q.table.schema?this.transformNode(Q,Y):{...Q,table:this.transformIdentifier(Q.table.identifier,Y)}):this.transformNodeList(X[G],Y)}#J(X){return X.kind in MO8}#Z(X){let Y=new Set;if("name"in X&&X.name&&LJ.is(X.name))this.#K(X.name,Y);if("from"in X&&X.from)for(let G of X.from.froms)this.#W(G,Y);if("into"in X&&X.into)this.#W(X.into,Y);if("table"in X&&X.table)this.#W(X.table,Y);if("joins"in X&&X.joins)for(let G of X.joins)this.#W(G.table,Y);if("using"in X&&X.using)if($F.is(X.using))this.#W(X.using.table,Y);else this.#W(X.using,Y);return Y}#$(X){let Y=new Set;if("with"in X&&X.with)this.#H(X.with,Y);return Y}#W(X,Y){if(_3.is(X))return this.#K(X.table,Y);if(VG.is(X)&&_3.is(X.node))return this.#K(X.node.table,Y);if(p$1.is(X)){for(let G of X.items)this.#W(G,Y);return}if(te.is(X)){for(let G of X.tables)this.#W(G,Y);return}}#K(X,Y){let G=X.identifier.name;if(!this.#Y.has(G)&&!this.#G.has(G))Y.add(G)}#H(X,Y){for(let G of X.expressions){let Q=G.name.table.table.identifier.name;if(!this.#G.has(Q))Y.add(Q)}}}});class eW{#X;constructor(X){this.#X=new Ca1(X)}transformQuery(X){return this.#X.transformNode(X.node,X.queryId)}async transformResult(X){return X.result}}var WI=D(()=>{_l0()});var fl0;var ka1=D(()=>{W0();fl0=n({is(X){return X.kind==="MatchedNode"},create(X,Y=!1){return n({kind:"MatchedNode",not:X,bySource:Y})}})});function va1(X,Y,G){return qK.create(kd([fl0.create(!X.isMatched,X.bySource),...Y&&Y.length>0?[Y.length===3&&G?jG(Y[0],Y[1],Y[2]):N7(Y)]:[]],"and",!1))}function ud(X){if(H9(X))return f5.create([X],[]);if(R7(X))return X.toOperationNode();return X}var bl0=D(()=>{ka1();f3();EK();XI();W0();oW()});class XE{#X;#Y;#G;constructor(){this.#X=new Promise((X,Y)=>{this.#G=Y,this.#Y=X})}get promise(){return this.#X}resolve=(X)=>{if(this.#Y)this.#Y(X)};reject=(X)=>{if(this.#G)this.#G(X)}}async function JK1(X){let Y=new XE,G=new XE;return X.provideConnection(async(Q)=>{return Y.resolve(Q),await G.promise}).catch((Q)=>Y.reject(Q)),n({connection:await Y.promise,release:G.resolve})}var _a1=D(()=>{W0()});class Z11{#X;constructor(X=SO8){this.#X=X}get plugins(){return this.#X}transformQuery(X,Y){for(let G of this.#X){let Q=G.transformQuery({node:X,queryId:Y});if(Q.kind===X.kind)X=Q;else throw Error(["KyselyPlugin.transformQuery must return a node","of the same kind that was given to it.",`The plugin was given a ${X.kind}`,`but it returned a ${Q.kind}`].join(" "))}return X}async executeQuery(X){return await this.provideConnection(async(Y)=>{let G=await Y.executeQuery(X);if("numUpdatedOrDeletedRows"in G)ON("kysely:warning: outdated driver/plugin detected! `QueryResult.numUpdatedOrDeletedRows` has been replaced with `QueryResult.numAffectedRows`.");return await this.#Y(G,X.queryId)})}async*stream(X,Y){let{connection:G,release:Q}=await JK1(this);try{for await(let J of G.streamQuery(X,Y))yield await this.#Y(J,X.queryId)}finally{Q()}}async#Y(X,Y){for(let G of this.#X)X=await G.transformResult({result:X,queryId:Y});return X}}var SO8;var fa1=D(()=>{W0();_a1();me();SO8=n([])});var ld,YE;var md=D(()=>{fa1();ld=class ld extends Z11{get adapter(){throw Error("this query cannot be compiled to SQL")}compileQuery(){throw Error("this query cannot be compiled to SQL")}provideConnection(){throw Error("this query cannot be executed")}withConnectionProvider(){throw Error("this query cannot have a connection provider")}withPlugin(X){return new ld([...this.plugins,X])}withPlugins(X){return new ld([...this.plugins,...X])}withPluginAtFront(X){return new ld([X,...this.plugins])}withoutPlugins(){return new ld([])}};YE=new ld});class ba1{numChangedRows;constructor(X){this.numChangedRows=X}}class DO{#X;constructor(X){this.#X=n(X)}modifyEnd(X){return new DO({...this.#X,queryNode:A6.cloneWithEndModifier(this.#X.queryNode,X.toOperationNode())})}top(X,Y){return new DO({...this.#X,queryNode:A6.cloneWithTop(this.#X.queryNode,NF(X,Y))})}using(...X){return new x3({...this.#X,queryNode:sW.cloneWithUsing(this.#X.queryNode,eL("Using",X))})}returning(X){return new DO({...this.#X,queryNode:A6.cloneWithReturning(this.#X.queryNode,sY(X))})}returningAll(X){return new DO({...this.#X,queryNode:A6.cloneWithReturning(this.#X.queryNode,MG(X))})}output(X){return new DO({...this.#X,queryNode:A6.cloneWithOutput(this.#X.queryNode,sY(X))})}outputAll(X){return new DO({...this.#X,queryNode:A6.cloneWithOutput(this.#X.queryNode,MG(X))})}}class x3{#X;constructor(X){this.#X=n(X)}modifyEnd(X){return new x3({...this.#X,queryNode:A6.cloneWithEndModifier(this.#X.queryNode,X.toOperationNode())})}top(X,Y){return new x3({...this.#X,queryNode:A6.cloneWithTop(this.#X.queryNode,NF(X,Y))})}whenMatched(){return this.#Y([])}whenMatchedAnd(...X){return this.#Y(X)}whenMatchedAndRef(X,Y,G){return this.#Y([X,Y,G],!0)}#Y(X,Y){return new ya1({...this.#X,queryNode:sW.cloneWithWhen(this.#X.queryNode,va1({isMatched:!0},X,Y))})}whenNotMatched(){return this.#G([])}whenNotMatchedAnd(...X){return this.#G(X)}whenNotMatchedAndRef(X,Y,G){return this.#G([X,Y,G],!0)}whenNotMatchedBySource(){return this.#G([],!1,!0)}whenNotMatchedBySourceAnd(...X){return this.#G(X,!1,!0)}whenNotMatchedBySourceAndRef(X,Y,G){return this.#G([X,Y,G],!0,!0)}returning(X){return new x3({...this.#X,queryNode:A6.cloneWithReturning(this.#X.queryNode,sY(X))})}returningAll(X){return new x3({...this.#X,queryNode:A6.cloneWithReturning(this.#X.queryNode,MG(X))})}output(X){return new x3({...this.#X,queryNode:A6.cloneWithOutput(this.#X.queryNode,sY(X))})}outputAll(X){return new x3({...this.#X,queryNode:A6.cloneWithOutput(this.#X.queryNode,MG(X))})}#G(X,Y=!1,G=!1){let Q={...this.#X,queryNode:sW.cloneWithWhen(this.#X.queryNode,va1({isMatched:!1,bySource:G},X,Y))};return new(G?ya1:yl0)(Q)}$call(X){return X(this)}$if(X,Y){if(X)return Y(this);return new x3({...this.#X})}toOperationNode(){return this.#X.executor.transformQuery(this.#X.queryNode,this.#X.queryId)}compile(){return this.#X.executor.compileQuery(this.toOperationNode(),this.#X.queryId)}async execute(){let X=this.compile(),Y=await this.#X.executor.executeQuery(X),{adapter:G}=this.#X.executor,Q=X.query;if(Q.returning&&G.supportsReturning||Q.output&&G.supportsOutput)return Y.rows;return[new ba1(Y.numAffectedRows)]}async executeTakeFirst(){let[X]=await this.execute();return X}async executeTakeFirstOrThrow(X=UF){let Y=await this.executeTakeFirst();if(Y===void 0)throw PN(X)?new X(this.toOperationNode()):X(this.toOperationNode());return Y}}class ya1{#X;constructor(X){this.#X=n(X)}thenDelete(){return new x3({...this.#X,queryNode:sW.cloneWithThen(this.#X.queryNode,ud("delete"))})}thenDoNothing(){return new x3({...this.#X,queryNode:sW.cloneWithThen(this.#X.queryNode,ud("do nothing"))})}thenUpdate(X){return new x3({...this.#X,queryNode:sW.cloneWithThen(this.#X.queryNode,ud(X(new hd({queryId:this.#X.queryId,executor:YE,queryNode:EN.createWithoutTable()}))))})}thenUpdateSet(...X){return this.thenUpdate((Y)=>Y.set(...X))}}class yl0{#X;constructor(X){this.#X=n(X)}thenDoNothing(){return new x3({...this.#X,queryNode:sW.cloneWithThen(this.#X.queryNode,ud("do nothing"))})}thenInsertValues(X){let[Y,G]=r$1(X);return new x3({...this.#X,queryNode:sW.cloneWithThen(this.#X.queryNode,ud(xX.cloneWith(xX.createWithoutInto(),{columns:Y,values:G})))})}}var xa1=D(()=>{eT();se();PK();vd();Ba1();G11();bl0();sL();yd();md();W0();QI();XK1()});class TN{#X;constructor(X){this.#X=n(X)}selectFrom(X){return W11({queryId:e4(),executor:this.#X.executor,queryNode:U9.createFrom(BF(X),this.#X.withNode)})}selectNoFrom(X){return W11({queryId:e4(),executor:this.#X.executor,queryNode:U9.cloneWithSelections(U9.create(this.#X.withNode),sY(X))})}insertInto(X){return new c9({queryId:e4(),executor:this.#X.executor,queryNode:xX.create(b5(X),this.#X.withNode)})}replaceInto(X){return new c9({queryId:e4(),executor:this.#X.executor,queryNode:xX.create(b5(X),this.#X.withNode,!0)})}deleteFrom(X){return new e$1({queryId:e4(),executor:this.#X.executor,queryNode:oL.create(BF(X),this.#X.withNode)})}updateTable(X){return new hd({queryId:e4(),executor:this.#X.executor,queryNode:EN.create(BF(X),this.#X.withNode)})}mergeInto(X){return new DO({queryId:e4(),executor:this.#X.executor,queryNode:sW.create(ha1(X),this.#X.withNode)})}with(X,Y){let G=Ma1(X,Y);return new TN({...this.#X,withNode:this.#X.withNode?J11.cloneWithExpression(this.#X.withNode,G):J11.create(G)})}withRecursive(X,Y){let G=Ma1(X,Y);return new TN({...this.#X,withNode:this.#X.withNode?J11.cloneWithExpression(this.#X.withNode,G):J11.create(G,{recursive:!0})})}withPlugin(X){return new TN({...this.#X,executor:this.#X.executor.withPlugin(X)})}withoutPlugins(){return new TN({...this.#X,executor:this.#X.executor.withoutPlugins()})}withSchema(X){return new TN({...this.#X,executor:this.#X.executor.withPluginAtFront(new eW(X))})}}var ZK1=D(()=>{WK1();qa1();Ta1();XK1();re();eT();YI();vd();LQ();Sl0();Ra1();AN();WI();W0();sL();xa1();se()});function Cl0(){return new TN({executor:YE})}function xl0(X,Y){return new _d({joinNode:$F.create(X,$I(Y))})}function hl0(){return new fd({overNode:ne.create()})}var GK1=D(()=>{Id();i$1();Ka1();Ll0();ZK1();md();LQ()});function eL(X,Y){if(Y.length===3)return kO8(X,Y[0],Y[1],Y[2]);else if(Y.length===2)return CO8(X,Y[0],Y[1]);else if(Y.length===1)return vO8(X,Y[0]);else throw Error("not implemented")}function CO8(X,Y,G){return G(xl0(X,Y)).toOperationNode()}function kO8(X,Y,G,Q){return $F.createWithOn(X,$I(Y),jG(G,"=",Q))}function vO8(X,Y){return $F.create(X,$I(Y))}var G11=D(()=>{Id();oW();GK1();LQ()});var gl0;var ga1=D(()=>{W0();gl0=n({is(X){return X.kind==="OffsetNode"},create(X){return n({kind:"OffsetNode",offset:X})}})});var ul0;var ua1=D(()=>{W0();ul0=n({is(X){return X.kind==="GroupByItemNode"},create(X){return n({kind:"GroupByItemNode",groupBy:X})}})});function ll0(X){return X=F9(X)?X(FF()):X,zO(X).map(ul0.create)}var ml0=D(()=>{ua1();GI();W0();OQ()});var $K1;var KK1=D(()=>{W0();$K1=n({is(X){return X.kind==="SetOperationNode"},create(X,Y,G){return n({kind:"SetOperationNode",operator:X,expression:Y,all:G})}})});function KI(X,Y,G){if(F9(Y))Y=Y(HK1());if(!IG(Y))Y=[Y];return Y.map((Q)=>$K1.create(X,y3(Q),G))}var dl0=D(()=>{GI();KK1();W0();HF()});class N9{#X;constructor(X){this.#X=X}get expressionType(){return}as(X){return new NK1(this,X)}or(...X){return new FK1(WF.create(this.#X,N7(X)))}and(...X){return new UK1(b3.create(this.#X,N7(X)))}$castTo(){return new N9(this.#X)}$notNull(){return new N9(this.#X)}toOperationNode(){return this.#X}}class NK1{#X;#Y;constructor(X,Y){this.#X=X,this.#Y=Y}get expression(){return this.#X}get alias(){return this.#Y}toOperationNode(){return VG.create(this.#X.toOperationNode(),R7(this.#Y)?this.#Y.toOperationNode():k4.create(this.#Y))}}class FK1{#X;constructor(X){this.#X=X}get expressionType(){return}as(X){return new NK1(this,X)}or(...X){return new FK1(WF.create(this.#X,N7(X)))}$castTo(){return new FK1(this.#X)}toOperationNode(){return rW.create(this.#X)}}class UK1{#X;constructor(X){this.#X=X}get expressionType(){return}as(X){return new NK1(this,X)}and(...X){return new UK1(b3.create(this.#X,N7(X)))}$castTo(){return new UK1(this.#X)}toOperationNode(){return rW.create(this.#X)}}var dd=D(()=>{ZF();pL();U7();f3();tT();Cd();oW()});var cl0;var la1=D(()=>{W0();wN();cl0=n({is(X){return X.kind==="FetchNode"},create(X,Y){return{kind:"FetchNode",rowCount:kY.create(X),modifier:Y}}})});function il0(X,Y){if(!QF(X)&&!cL(X))throw Error(`Invalid fetch row count: ${X}`);if(!_O8(Y))throw Error(`Invalid fetch modifier: ${Y}`);return cl0.create(X,Y)}function _O8(X){return X==="only"||X==="with ties"}var pl0=D(()=>{la1();W0()});class ma1{#X;constructor(X){this.#X=n(X)}get expressionType(){return}get isSelectQueryBuilder(){return!0}where(...X){return new T8({...this.#X,queryNode:A6.cloneWithWhere(this.#X.queryNode,N7(X))})}whereRef(X,Y,G){return new T8({...this.#X,queryNode:A6.cloneWithWhere(this.#X.queryNode,jG(X,Y,G))})}having(...X){return new T8({...this.#X,queryNode:U9.cloneWithHaving(this.#X.queryNode,N7(X))})}havingRef(X,Y,G){return new T8({...this.#X,queryNode:U9.cloneWithHaving(this.#X.queryNode,jG(X,Y,G))})}select(X){return new T8({...this.#X,queryNode:U9.cloneWithSelections(this.#X.queryNode,sY(X))})}distinctOn(X){return new T8({...this.#X,queryNode:U9.cloneWithDistinctOn(this.#X.queryNode,zO(X))})}modifyFront(X){return new T8({...this.#X,queryNode:U9.cloneWithFrontModifier(this.#X.queryNode,zN.createWithExpression(X.toOperationNode()))})}modifyEnd(X){return new T8({...this.#X,queryNode:A6.cloneWithEndModifier(this.#X.queryNode,zN.createWithExpression(X.toOperationNode()))})}distinct(){return new T8({...this.#X,queryNode:U9.cloneWithFrontModifier(this.#X.queryNode,zN.create("Distinct"))})}forUpdate(X){return new T8({...this.#X,queryNode:A6.cloneWithEndModifier(this.#X.queryNode,zN.create("ForUpdate",X?ye(X).map(b5):void 0))})}forShare(X){return new T8({...this.#X,queryNode:A6.cloneWithEndModifier(this.#X.queryNode,zN.create("ForShare",X?ye(X).map(b5):void 0))})}forKeyShare(X){return new T8({...this.#X,queryNode:A6.cloneWithEndModifier(this.#X.queryNode,zN.create("ForKeyShare",X?ye(X).map(b5):void 0))})}forNoKeyUpdate(X){return new T8({...this.#X,queryNode:A6.cloneWithEndModifier(this.#X.queryNode,zN.create("ForNoKeyUpdate",X?ye(X).map(b5):void 0))})}skipLocked(){return new T8({...this.#X,queryNode:A6.cloneWithEndModifier(this.#X.queryNode,zN.create("SkipLocked"))})}noWait(){return new T8({...this.#X,queryNode:A6.cloneWithEndModifier(this.#X.queryNode,zN.create("NoWait"))})}selectAll(X){return new T8({...this.#X,queryNode:U9.cloneWithSelections(this.#X.queryNode,MG(X))})}innerJoin(...X){return this.#Y("InnerJoin",X)}leftJoin(...X){return this.#Y("LeftJoin",X)}rightJoin(...X){return this.#Y("RightJoin",X)}fullJoin(...X){return this.#Y("FullJoin",X)}crossJoin(...X){return this.#Y("CrossJoin",X)}innerJoinLateral(...X){return this.#Y("LateralInnerJoin",X)}leftJoinLateral(...X){return this.#Y("LateralLeftJoin",X)}crossJoinLateral(...X){return this.#Y("LateralCrossJoin",X)}crossApply(...X){return this.#Y("CrossApply",X)}outerApply(...X){return this.#Y("OuterApply",X)}#Y(X,Y){return new T8({...this.#X,queryNode:A6.cloneWithJoin(this.#X.queryNode,eL(X,Y))})}orderBy(...X){return new T8({...this.#X,queryNode:A6.cloneWithOrderByItems(this.#X.queryNode,tW(X))})}groupBy(X){return new T8({...this.#X,queryNode:U9.cloneWithGroupByItems(this.#X.queryNode,ll0(X))})}limit(X){return new T8({...this.#X,queryNode:U9.cloneWithLimit(this.#X.queryNode,xd.create(d9(X)))})}offset(X){return new T8({...this.#X,queryNode:U9.cloneWithOffset(this.#X.queryNode,gl0.create(d9(X)))})}fetch(X,Y="only"){return new T8({...this.#X,queryNode:U9.cloneWithFetch(this.#X.queryNode,il0(X,Y))})}top(X,Y){return new T8({...this.#X,queryNode:A6.cloneWithTop(this.#X.queryNode,NF(X,Y))})}union(X){return new T8({...this.#X,queryNode:U9.cloneWithSetOperations(this.#X.queryNode,KI("union",X,!1))})}unionAll(X){return new T8({...this.#X,queryNode:U9.cloneWithSetOperations(this.#X.queryNode,KI("union",X,!0))})}intersect(X){return new T8({...this.#X,queryNode:U9.cloneWithSetOperations(this.#X.queryNode,KI("intersect",X,!1))})}intersectAll(X){return new T8({...this.#X,queryNode:U9.cloneWithSetOperations(this.#X.queryNode,KI("intersect",X,!0))})}except(X){return new T8({...this.#X,queryNode:U9.cloneWithSetOperations(this.#X.queryNode,KI("except",X,!1))})}exceptAll(X){return new T8({...this.#X,queryNode:U9.cloneWithSetOperations(this.#X.queryNode,KI("except",X,!0))})}as(X){return new nl0(this,X)}clearSelect(){return new T8({...this.#X,queryNode:U9.cloneWithoutSelections(this.#X.queryNode)})}clearWhere(){return new T8({...this.#X,queryNode:A6.cloneWithoutWhere(this.#X.queryNode)})}clearLimit(){return new T8({...this.#X,queryNode:U9.cloneWithoutLimit(this.#X.queryNode)})}clearOffset(){return new T8({...this.#X,queryNode:U9.cloneWithoutOffset(this.#X.queryNode)})}clearOrderBy(){return new T8({...this.#X,queryNode:A6.cloneWithoutOrderBy(this.#X.queryNode)})}clearGroupBy(){return new T8({...this.#X,queryNode:U9.cloneWithoutGroupBy(this.#X.queryNode)})}$call(X){return X(this)}$if(X,Y){if(X)return Y(this);return new T8({...this.#X})}$castTo(){return new T8(this.#X)}$narrowType(){return new T8(this.#X)}$assertType(){return new T8(this.#X)}$asTuple(){return new N9(this.toOperationNode())}$asScalar(){return new N9(this.toOperationNode())}withPlugin(X){return new T8({...this.#X,executor:this.#X.executor.withPlugin(X)})}toOperationNode(){return this.#X.executor.transformQuery(this.#X.queryNode,this.#X.queryId)}compile(){return this.#X.executor.compileQuery(this.toOperationNode(),this.#X.queryId)}async execute(){let X=this.compile();return(await this.#X.executor.executeQuery(X)).rows}async executeTakeFirst(){let[X]=await this.execute();return X}async executeTakeFirstOrThrow(X=UF){let Y=await this.executeTakeFirst();if(Y===void 0)throw PN(X)?new X(this.toOperationNode()):X(this.toOperationNode());return Y}async*stream(X=100){let Y=this.compile(),G=this.#X.executor.stream(Y,X);for await(let Q of G)yield*Q.rows}async explain(X,Y){return await new T8({...this.#X,queryNode:A6.cloneWithExplain(this.#X.queryNode,X,Y)}).execute()}}function W11(X){return new ma1(X)}class nl0{#X;#Y;constructor(X,Y){this.#X=X,this.#Y=Y}get expression(){return this.#X}get alias(){return this.#Y}get isAliasedSelectQueryBuilder(){return!0}toOperationNode(){return VG.create(this.#X.toOperationNode(),k4.create(this.#Y))}}var T8;var WK1=D(()=>{ZF();hn1();G11();LQ();sL();OQ();YI();PK();rT();Y11();ga1();W0();ml0();QI();U7();dl0();oW();dd();LN();pl0();yd();T8=ma1});var IN;var BK1=D(()=>{W0();oe();pe();IN=n({is(X){return X.kind==="AggregateFunctionNode"},create(X,Y=[]){return n({kind:"AggregateFunctionNode",func:X,aggregated:Y})},cloneWithDistinct(X){return n({...X,distinct:!0})},cloneWithOrderBy(X,Y,G=!1){let Q=G?"withinGroup":"orderBy";return n({...X,[Q]:X[Q]?OO.cloneWithItems(X[Q],Y):OO.create(Y)})},cloneWithFilter(X,Y){return n({...X,filter:X.filter?wQ.cloneWithOperation(X.filter,"And",Y):wQ.create(Y)})},cloneWithOrFilter(X,Y){return n({...X,filter:X.filter?wQ.cloneWithOperation(X.filter,"Or",Y):wQ.create(Y)})},cloneWithOver(X,Y){return n({...X,over:Y})}})});var da1;var ca1=D(()=>{W0();da1=n({is(X){return X.kind==="FunctionNode"},create(X,Y){return n({kind:"FunctionNode",func:X,arguments:Y})}})});class h3{#X;constructor(X){this.#X=n(X)}get expressionType(){return}as(X){return new al0(this,X)}distinct(){return new h3({...this.#X,aggregateFunctionNode:IN.cloneWithDistinct(this.#X.aggregateFunctionNode)})}orderBy(...X){return new h3({...this.#X,aggregateFunctionNode:A6.cloneWithOrderByItems(this.#X.aggregateFunctionNode,tW(X))})}clearOrderBy(){return new h3({...this.#X,aggregateFunctionNode:A6.cloneWithoutOrderBy(this.#X.aggregateFunctionNode)})}withinGroupOrderBy(...X){return new h3({...this.#X,aggregateFunctionNode:IN.cloneWithOrderBy(this.#X.aggregateFunctionNode,tW(X),!0)})}filterWhere(...X){return new h3({...this.#X,aggregateFunctionNode:IN.cloneWithFilter(this.#X.aggregateFunctionNode,N7(X))})}filterWhereRef(X,Y,G){return new h3({...this.#X,aggregateFunctionNode:IN.cloneWithFilter(this.#X.aggregateFunctionNode,jG(X,Y,G))})}over(X){let Y=hl0();return new h3({...this.#X,aggregateFunctionNode:IN.cloneWithOver(this.#X.aggregateFunctionNode,(X?X(Y):Y).toOperationNode())})}$call(X){return X(this)}$castTo(){return new h3(this.#X)}$notNull(){return new h3(this.#X)}toOperationNode(){return this.#X.aggregateFunctionNode}}class al0{#X;#Y;constructor(X,Y){this.#X=X,this.#Y=Y}get expression(){return this.#X}get alias(){return this.#Y}toOperationNode(){return VG.create(this.#X.toOperationNode(),k4.create(this.#Y))}}var ia1=D(()=>{W0();BK1();ZF();U7();GK1();oW();rT();PK()});function zK1(){let X=(G,Q)=>{return new N9(da1.create(G,zO(Q??[])))},Y=(G,Q)=>{return new h3({aggregateFunctionNode:IN.create(G,Q?zO(Q):void 0)})};return Object.assign(X,{agg:Y,avg(G){return Y("avg",[G])},coalesce(...G){return X("coalesce",G)},count(G){return Y("count",[G])},countAll(G){return new h3({aggregateFunctionNode:IN.create("count",MG(G))})},max(G){return Y("max",[G])},min(G){return Y("min",[G])},sum(G){return Y("sum",[G])},any(G){return X("any",[G])},jsonAgg(G){return new h3({aggregateFunctionNode:IN.create("json_agg",[H9(G)?b5(G):G.toOperationNode()])})},toJson(G){return new N9(da1.create("to_json",[H9(G)?b5(G):G.toOperationNode()]))}})}var OK1=D(()=>{dd();BK1();ca1();OQ();sL();ia1();W0();LQ()});var tl0;var pa1=D(()=>{W0();tl0=n({is(X){return X.kind==="UnaryOperationNode"},create(X,Y){return n({kind:"UnaryOperationNode",operator:X,operand:Y})}})});function rl0(X,Y){return tl0.create(PZ.create(X),DQ(Y))}var ol0=D(()=>{aL();pa1();OQ()});var X$;var $11=D(()=>{W0();XI();X$=n({is(X){return X.kind==="CaseNode"},create(X){return n({kind:"CaseNode",value:X})},cloneWithWhen(X,Y){return n({...X,when:n(X.when?[...X.when,Y]:[Y])})},cloneWithThen(X,Y){return n({...X,when:X.when?n([...X.when.slice(0,-1),qK.cloneWithResult(X.when[X.when.length-1],Y)]):void 0})},cloneWith(X,Y){return n({...X,...Y})}})});class K11{#X;constructor(X){this.#X=n(X)}when(...X){return new na1({...this.#X,node:X$.cloneWithWhen(this.#X.node,qK.create(N7(X)))})}}class na1{#X;constructor(X){this.#X=n(X)}then(X){return new sl0({...this.#X,node:X$.cloneWithThen(this.#X.node,d$1(X)?ie(X):d9(X))})}}class sl0{#X;constructor(X){this.#X=n(X)}when(...X){return new na1({...this.#X,node:X$.cloneWithWhen(this.#X.node,qK.create(N7(X)))})}else(X){return new el0({...this.#X,node:X$.cloneWith(this.#X.node,{else:d$1(X)?ie(X):d9(X)})})}end(){return new N9(X$.cloneWith(this.#X.node,{isStatement:!1}))}endCase(){return new N9(X$.cloneWith(this.#X.node,{isStatement:!0}))}}class el0{#X;constructor(X){this.#X=n(X)}end(){return new N9(X$.cloneWith(this.#X.node,{isStatement:!1}))}endCase(){return new N9(X$.cloneWith(this.#X.node,{isStatement:!0}))}}var DK1=D(()=>{dd();W0();$11();XI();oW();LN()});var aa1;var ta1=D(()=>{W0();aa1=n({is(X){return X.kind==="JSONPathLegNode"},create(X,Y){return n({kind:"JSONPathLegNode",type:X,value:Y})}})});class F11{#X;constructor(X){this.#X=X}at(X){return this.#Y("ArrayLocation",X)}key(X){return this.#Y("Member",X)}#Y(X,Y){if(Md.is(this.#X))return new H11(Md.cloneWithTraversal(this.#X,rL.is(this.#X.traversal)?rL.cloneWithLeg(this.#X.traversal,aa1.create(X,Y)):l$1.cloneWithValue(this.#X.traversal,kY.createImmediate(Y))));return new H11(rL.cloneWithLeg(this.#X,aa1.create(X,Y)))}}class Xm0{#X;#Y;constructor(X,Y){this.#X=X,this.#Y=Y}get expression(){return this.#X}get alias(){return this.#Y}toOperationNode(){return VG.create(this.#X.toOperationNode(),R7(this.#Y)?this.#Y.toOperationNode():k4.create(this.#Y))}}var H11;var ra1=D(()=>{ZF();U7();m$1();ta1();de();u$1();f3();wN();H11=class H11 extends F11{#X;constructor(X){super(X);this.#X=X}get expressionType(){return}as(X){return new Xm0(this,X)}$castTo(){return new H11(this.#X)}$notNull(){return new H11(this.#X)}toOperationNode(){return this.#X}}});var oa1;var sa1=D(()=>{W0();oa1=n({is(X){return X.kind==="TupleNode"},create(X){return n({kind:"TupleNode",values:n(X)})}})});function Gm0(X){if(fO8.includes(X))return!0;if(bO8.some((Y)=>Y.test(X)))return!0;return!1}var fO8,bO8,Ym0;var ea1=D(()=>{W0();fO8=["varchar","char","text","integer","int2","int4","int8","smallint","bigint","boolean","real","double precision","float4","float8","decimal","numeric","binary","bytea","date","datetime","time","timetz","timestamp","timestamptz","serial","bigserial","uuid","json","jsonb","blob","varbinary","int4range","int4multirange","int8range","int8multirange","numrange","nummultirange","tsrange","tsmultirange","tstzrange","tstzmultirange","daterange","datemultirange"],bO8=[/^varchar\(\d+\)$/,/^char\(\d+\)$/,/^decimal\(\d+, \d+\)$/,/^numeric\(\d+, \d+\)$/,/^binary\(\d+\)$/,/^datetime\(\d+\)$/,/^time\(\d+\)$/,/^timetz\(\d+\)$/,/^timestamp\(\d+\)$/,/^timestamptz\(\d+\)$/,/^varbinary\(\d+\)$/],Ym0=n({is(X){return X.kind==="DataTypeNode"},create(X){return n({kind:"DataTypeNode",dataType:X})}})});function OF(X){if(R7(X))return X.toOperationNode();if(Gm0(X))return Ym0.create(X);throw Error(`invalid column data type ${JSON.stringify(X)}`)}var U11=D(()=>{ea1();f3()});var Qm0;var Xt1=D(()=>{W0();Qm0=n({is(X){return X.kind==="CastNode"},create(X,Y){return n({kind:"CastNode",expression:X,dataType:Y})}})});function HK1(X=YE){function Y(J,W,Z){return new N9(c$1(J,W,Z))}function G(J,W){return new N9(rl0(J,W))}let Q=Object.assign(Y,{fn:void 0,eb:void 0,selectFrom(J){return W11({queryId:e4(),executor:X,queryNode:U9.createFrom(BF(J))})},case(J){return new K11({node:X$.create(LZ(J)?void 0:DQ(J))})},ref(J,W){if(LZ(W))return new N9(aW(J));return new F11(Hl0(J,W))},jsonPath(){return new F11(rL.create())},table(J){return new N9(b5(J))},val(J){return new N9(d9(J))},refTuple(...J){return new N9(oa1.create(J.map(DQ)))},tuple(...J){return new N9(oa1.create(J.map(d9)))},lit(J){return new N9(ie(J))},unary:G,not(J){return G("not",J)},exists(J){return G("exists",J)},neg(J){return G("-",J)},between(J,W,Z){return new N9(nL.create(DQ(J),PZ.create("between"),b3.create(d9(W),d9(Z))))},betweenSymmetric(J,W,Z){return new N9(nL.create(DQ(J),PZ.create("between symmetric"),b3.create(d9(W),d9(Z))))},and(J){if(IG(J))return new N9(kd(J,"and"));return new N9(rn1(J,"and"))},or(J){if(IG(J))return new N9(kd(J,"or"));return new N9(rn1(J,"or"))},parens(...J){let W=N7(J);if(rW.is(W))return new N9(W);else return new N9(rW.create(W))},cast(J,W){return new N9(Qm0.create(DQ(J),OF(W)))},withSchema(J){return HK1(X.withPluginAtFront(new eW(J)))}});return Q.fn=zK1(),Q.eb=Q,Q}function FF(X){return HK1()}var GI=D(()=>{WK1();YI();LQ();WI();AN();OK1();OQ();oW();Cd();dd();aL();ol0();LN();md();DK1();$11();W0();ra1();y$1();pL();sa1();de();U11();Xt1()});function y3(X){if(R7(X))return X.toOperationNode();else if(F9(X))return X(FF()).toOperationNode();throw Error(`invalid expression: ${JSON.stringify(X)}`)}function t$1(X){if(R7(X))return X.toOperationNode();else if(F9(X))return X(FF()).toOperationNode();throw Error(`invalid aliased expression: ${JSON.stringify(X)}`)}function BO(X){return _$1(X)||Ql0(X)||F9(X)}var HF=D(()=>{f$1();f3();GI();W0()});class Yt1{#X;get table(){return this.#X}constructor(X){this.#X=X}as(X){return new Jm0(this.#X,X)}}class Jm0{#X;#Y;get table(){return this.#X}get alias(){return this.#Y}constructor(X,Y){this.#X=X,this.#Y=Y}toOperationNode(){return VG.create(b5(this.#X),k4.create(this.#Y))}}function Zm0(X){return F7(X)&&R7(X)&&H9(X.table)&&H9(X.alias)}var wK1=D(()=>{ZF();U7();f3();LQ();W0()});function BF(X){if(IG(X))return X.map((Y)=>$I(Y));else return[$I(X)]}function $I(X){if(H9(X))return ha1(X);else if(Zm0(X))return X.toOperationNode();else return t$1(X)}function ha1(X){if(X.includes(" as ")){let[G,Q]=X.split(" as ").map(Wm0);return VG.create(b5(G),k4.create(Q))}else return b5(X)}function b5(X){if(X.includes(".")){let[G,Q]=X.split(".").map(Wm0);return _3.createWithSchema(G,Q)}else return _3.create(X)}function Wm0(X){return X.trim()}var LQ=D(()=>{W0();ZF();Td();HF();U7();wK1()});var Gt1;var Qt1=D(()=>{W0();Gt1=n({is(X){return X.kind==="AddColumnNode"},create(X){return n({kind:"AddColumnNode",column:X})}})});var S7;var N11=D(()=>{W0();EJ();S7=n({is(X){return X.kind==="ColumnDefinitionNode"},create(X,Y){return n({kind:"ColumnDefinitionNode",column:T5.create(X),dataType:Y})},cloneWithFrontModifier(X,Y){return n({...X,frontModifiers:X.frontModifiers?n([...X.frontModifiers,Y]):[Y]})},cloneWithEndModifier(X,Y){return n({...X,endModifiers:X.endModifiers?n([...X.endModifiers,Y]):[Y]})},cloneWith(X,Y){return n({...X,...Y})}})});var Jt1;var Zt1=D(()=>{W0();EJ();Jt1=n({is(X){return X.kind==="DropColumnNode"},create(X){return n({kind:"DropColumnNode",column:T5.create(X)})}})});var Wt1;var $t1=D(()=>{W0();EJ();Wt1=n({is(X){return X.kind==="RenameColumnNode"},create(X,Y){return n({kind:"RenameColumnNode",column:T5.create(X),renameTo:T5.create(Y)})}})});var cd;var B11=D(()=>{W0();U7();cd=n({is(X){return X.kind==="CheckConstraintNode"},create(X,Y){return n({kind:"CheckConstraintNode",expression:X,name:Y?k4.create(Y):void 0})}})});var $m0,id;var z11=D(()=>{W0();$m0=["no action","restrict","cascade","set null","set default"],id=n({is(X){return X.kind==="ReferencesNode"},create(X,Y){return n({kind:"ReferencesNode",table:X,columns:n([...Y])})},cloneWithOnDelete(X,Y){return n({...X,onDelete:Y})},cloneWithOnUpdate(X,Y){return n({...X,onUpdate:Y})}})});function LK1(X){return R7(X)?X.toOperationNode():kY.createImmediate(X)}var Kt1=D(()=>{f3();wN()});var O11;var Ht1=D(()=>{W0();O11=n({is(X){return X.kind==="GeneratedNode"},create(X){return n({kind:"GeneratedNode",...X})},createWithExpression(X){return n({kind:"GeneratedNode",always:!0,expression:X})},cloneWith(X,Y){return n({...X,...Y})}})});var Km0;var Ft1=D(()=>{W0();Km0=n({is(X){return X.kind==="DefaultValueNode"},create(X){return n({kind:"DefaultValueNode",defaultValue:X})}})});function pd(X){if($m0.includes(X))return X;throw Error(`invalid OnModifyForeignAction ${X}`)}var Ut1=D(()=>{z11()});class C7{#X;constructor(X){this.#X=X}autoIncrement(){return new C7(S7.cloneWith(this.#X,{autoIncrement:!0}))}identity(){return new C7(S7.cloneWith(this.#X,{identity:!0}))}primaryKey(){return new C7(S7.cloneWith(this.#X,{primaryKey:!0}))}references(X){let Y=aW(X);if(!Y.table||Vd.is(Y.column))throw Error(`invalid call references('${X}'). The reference must have format table.column or schema.table.column`);return new C7(S7.cloneWith(this.#X,{references:id.create(Y.table,[Y.column])}))}onDelete(X){if(!this.#X.references)throw Error("on delete constraint can only be added for foreign keys");return new C7(S7.cloneWith(this.#X,{references:id.cloneWithOnDelete(this.#X.references,pd(X))}))}onUpdate(X){if(!this.#X.references)throw Error("on update constraint can only be added for foreign keys");return new C7(S7.cloneWith(this.#X,{references:id.cloneWithOnUpdate(this.#X.references,pd(X))}))}unique(){return new C7(S7.cloneWith(this.#X,{unique:!0}))}notNull(){return new C7(S7.cloneWith(this.#X,{notNull:!0}))}unsigned(){return new C7(S7.cloneWith(this.#X,{unsigned:!0}))}defaultTo(X){return new C7(S7.cloneWith(this.#X,{defaultTo:Km0.create(LK1(X))}))}check(X){return new C7(S7.cloneWith(this.#X,{check:cd.create(X.toOperationNode())}))}generatedAlwaysAs(X){return new C7(S7.cloneWith(this.#X,{generated:O11.createWithExpression(X.toOperationNode())}))}generatedAlwaysAsIdentity(){return new C7(S7.cloneWith(this.#X,{generated:O11.create({identity:!0,always:!0})}))}generatedByDefaultAsIdentity(){return new C7(S7.cloneWith(this.#X,{generated:O11.create({identity:!0,byDefault:!0})}))}stored(){if(!this.#X.generated)throw Error("stored() can only be called after generatedAlwaysAs");return new C7(S7.cloneWith(this.#X,{generated:O11.cloneWith(this.#X.generated,{stored:!0})}))}modifyFront(X){return new C7(S7.cloneWithFrontModifier(this.#X,X.toOperationNode()))}nullsNotDistinct(){return new C7(S7.cloneWith(this.#X,{nullsNotDistinct:!0}))}ifNotExists(){return new C7(S7.cloneWith(this.#X,{ifNotExists:!0}))}modifyEnd(X){return new C7(S7.cloneWithEndModifier(this.#X,X.toOperationNode()))}$call(X){return X(this)}toOperationNode(){return this.#X}}var EK1=D(()=>{B11();z11();ue();OQ();N11();Kt1();Ht1();Ft1();Ut1()});var Nt1;var Bt1=D(()=>{W0();Nt1=n({is(X){return X.kind==="ModifyColumnNode"},create(X){return n({kind:"ModifyColumnNode",column:X})}})});var DF;var D11=D(()=>{W0();U7();z11();DF=n({is(X){return X.kind==="ForeignKeyConstraintNode"},create(X,Y,G,Q){return n({kind:"ForeignKeyConstraintNode",columns:X,references:id.create(Y,G),name:Q?k4.create(Q):void 0})},cloneWith(X,Y){return n({...X,...Y})}})});class wF{#X;constructor(X){this.#X=X}onDelete(X){return new wF(DF.cloneWith(this.#X,{onDelete:pd(X)}))}onUpdate(X){return new wF(DF.cloneWith(this.#X,{onUpdate:pd(X)}))}deferrable(){return new wF(DF.cloneWith(this.#X,{deferrable:!0}))}notDeferrable(){return new wF(DF.cloneWith(this.#X,{deferrable:!1}))}initiallyDeferred(){return new wF(DF.cloneWith(this.#X,{initiallyDeferred:!0}))}initiallyImmediate(){return new wF(DF.cloneWith(this.#X,{initiallyDeferred:!1}))}$call(X){return X(this)}toOperationNode(){return this.#X}}var PK1=D(()=>{D11();Ut1()});var nd;var qK1=D(()=>{W0();nd=n({is(X){return X.kind==="AddConstraintNode"},create(X){return n({kind:"AddConstraintNode",constraint:X})}})});var VN;var w11=D(()=>{W0();EJ();U7();VN=n({is(X){return X.kind==="UniqueConstraintNode"},create(X,Y,G){return n({kind:"UniqueConstraintNode",columns:n(X.map(T5.create)),name:Y?k4.create(Y):void 0,nullsNotDistinct:G})},cloneWith(X,Y){return n({...X,...Y})}})});var ad;var AK1=D(()=>{W0();U7();ad=n({is(X){return X.kind==="DropConstraintNode"},create(X){return n({kind:"DropConstraintNode",constraintName:k4.create(X)})},cloneWith(X,Y){return n({...X,...Y})}})});var td;var zt1=D(()=>{W0();EJ();td=n({is(X){return X.kind==="AlterColumnNode"},create(X,Y,G){return n({kind:"AlterColumnNode",column:T5.create(X),[Y]:G})}})});class TK1{#X;constructor(X){this.#X=X}setDataType(X){return new rd(td.create(this.#X,"dataType",OF(X)))}setDefault(X){return new rd(td.create(this.#X,"setDefault",LK1(X)))}dropDefault(){return new rd(td.create(this.#X,"dropDefault",!0))}setNotNull(){return new rd(td.create(this.#X,"setNotNull",!0))}dropNotNull(){return new rd(td.create(this.#X,"dropNotNull",!0))}$call(X){return X(this)}}class rd{#X;constructor(X){this.#X=X}toOperationNode(){return this.#X}}var Ot1=D(()=>{zt1();U11();Kt1()});class GE{#X;constructor(X){this.#X=n(X)}toOperationNode(){return this.#X.executor.transformQuery(this.#X.node,this.#X.queryId)}compile(){return this.#X.executor.compileQuery(this.toOperationNode(),this.#X.queryId)}async execute(){await this.#X.executor.executeQuery(this.compile())}}var Hm0=D(()=>{W0()});class wO{#X;constructor(X){this.#X=n(X)}onDelete(X){return new wO({...this.#X,constraintBuilder:this.#X.constraintBuilder.onDelete(X)})}onUpdate(X){return new wO({...this.#X,constraintBuilder:this.#X.constraintBuilder.onUpdate(X)})}deferrable(){return new wO({...this.#X,constraintBuilder:this.#X.constraintBuilder.deferrable()})}notDeferrable(){return new wO({...this.#X,constraintBuilder:this.#X.constraintBuilder.notDeferrable()})}initiallyDeferred(){return new wO({...this.#X,constraintBuilder:this.#X.constraintBuilder.initiallyDeferred()})}initiallyImmediate(){return new wO({...this.#X,constraintBuilder:this.#X.constraintBuilder.initiallyImmediate()})}$call(X){return X(this)}toOperationNode(){return this.#X.executor.transformQuery(_5.cloneWithTableProps(this.#X.node,{addConstraint:nd.create(this.#X.constraintBuilder.toOperationNode())}),this.#X.queryId)}compile(){return this.#X.executor.compileQuery(this.toOperationNode(),this.#X.queryId)}async execute(){await this.#X.executor.executeQuery(this.compile())}}var Fm0=D(()=>{qK1();aT();W0()});class HI{#X;constructor(X){this.#X=n(X)}ifExists(){return new HI({...this.#X,node:_5.cloneWithTableProps(this.#X.node,{dropConstraint:ad.cloneWith(this.#X.node.dropConstraint,{ifExists:!0})})})}cascade(){return new HI({...this.#X,node:_5.cloneWithTableProps(this.#X.node,{dropConstraint:ad.cloneWith(this.#X.node.dropConstraint,{modifier:"cascade"})})})}restrict(){return new HI({...this.#X,node:_5.cloneWithTableProps(this.#X.node,{dropConstraint:ad.cloneWith(this.#X.node.dropConstraint,{modifier:"restrict"})})})}$call(X){return X(this)}toOperationNode(){return this.#X.executor.transformQuery(this.#X.node,this.#X.queryId)}compile(){return this.#X.executor.compileQuery(this.toOperationNode(),this.#X.queryId)}async execute(){await this.#X.executor.executeQuery(this.compile())}}var Um0=D(()=>{aT();AK1();W0()});var LO;var L11=D(()=>{W0();EJ();U7();LO=n({is(X){return X.kind==="PrimaryKeyConstraintNode"},create(X,Y){return n({kind:"PrimaryKeyConstraintNode",columns:n(X.map(T5.create)),name:Y?k4.create(Y):void 0})},cloneWith(X,Y){return n({...X,...Y})}})});var QE;var IK1=D(()=>{W0();U7();QE=n({is(X){return X.kind==="AddIndexNode"},create(X){return n({kind:"AddIndexNode",name:k4.create(X)})},cloneWith(X,Y){return n({...X,...Y})},cloneWithColumns(X,Y){return n({...X,columns:[...X.columns||[],...Y]})}})});class JE{#X;constructor(X){this.#X=n(X)}unique(){return new JE({...this.#X,node:_5.cloneWithTableProps(this.#X.node,{addIndex:QE.cloneWith(this.#X.node.addIndex,{unique:!0})})})}column(X){return new JE({...this.#X,node:_5.cloneWithTableProps(this.#X.node,{addIndex:QE.cloneWithColumns(this.#X.node.addIndex,[Rd(X)])})})}columns(X){return new JE({...this.#X,node:_5.cloneWithTableProps(this.#X.node,{addIndex:QE.cloneWithColumns(this.#X.node.addIndex,X.map(Rd))})})}expression(X){return new JE({...this.#X,node:_5.cloneWithTableProps(this.#X.node,{addIndex:QE.cloneWithColumns(this.#X.node.addIndex,[X.toOperationNode()])})})}using(X){return new JE({...this.#X,node:_5.cloneWithTableProps(this.#X.node,{addIndex:QE.cloneWith(this.#X.node.addIndex,{using:f5.createWithSql(X)})})})}$call(X){return X(this)}toOperationNode(){return this.#X.executor.transformQuery(this.#X.node,this.#X.queryId)}compile(){return this.#X.executor.compileQuery(this.toOperationNode(),this.#X.queryId)}async execute(){await this.#X.executor.executeQuery(this.compile())}}var Nm0=D(()=>{IK1();aT();EK();OQ();W0()});class jN{#X;constructor(X){this.#X=X}nullsNotDistinct(){return new jN(VN.cloneWith(this.#X,{nullsNotDistinct:!0}))}deferrable(){return new jN(VN.cloneWith(this.#X,{deferrable:!0}))}notDeferrable(){return new jN(VN.cloneWith(this.#X,{deferrable:!1}))}initiallyDeferred(){return new jN(VN.cloneWith(this.#X,{initiallyDeferred:!0}))}initiallyImmediate(){return new jN(VN.cloneWith(this.#X,{initiallyDeferred:!1}))}$call(X){return X(this)}toOperationNode(){return this.#X}}var Dt1=D(()=>{w11()});class EO{#X;constructor(X){this.#X=X}deferrable(){return new EO(LO.cloneWith(this.#X,{deferrable:!0}))}notDeferrable(){return new EO(LO.cloneWith(this.#X,{deferrable:!1}))}initiallyDeferred(){return new EO(LO.cloneWith(this.#X,{initiallyDeferred:!0}))}initiallyImmediate(){return new EO(LO.cloneWith(this.#X,{initiallyDeferred:!1}))}$call(X){return X(this)}toOperationNode(){return this.#X}}var wt1=D(()=>{L11()});class E11{#X;constructor(X){this.#X=X}$call(X){return X(this)}toOperationNode(){return this.#X}}var Bm0;var Lt1=D(()=>{W0();U7();Bm0=n({is(X){return X.kind==="RenameConstraintNode"},create(X,Y){return n({kind:"RenameConstraintNode",oldName:k4.create(X),newName:k4.create(Y)})}})});class Et1{#X;constructor(X){this.#X=n(X)}renameTo(X){return new GE({...this.#X,node:_5.cloneWithTableProps(this.#X.node,{renameTo:b5(X)})})}setSchema(X){return new GE({...this.#X,node:_5.cloneWithTableProps(this.#X.node,{setSchema:k4.create(X)})})}alterColumn(X,Y){let G=Y(new TK1(X));return new LF({...this.#X,node:_5.cloneWithColumnAlteration(this.#X.node,G.toOperationNode())})}dropColumn(X){return new LF({...this.#X,node:_5.cloneWithColumnAlteration(this.#X.node,Jt1.create(X))})}renameColumn(X,Y){return new LF({...this.#X,node:_5.cloneWithColumnAlteration(this.#X.node,Wt1.create(X,Y))})}addColumn(X,Y,G=EZ){let Q=G(new C7(S7.create(X,OF(Y))));return new LF({...this.#X,node:_5.cloneWithColumnAlteration(this.#X.node,Gt1.create(Q.toOperationNode()))})}modifyColumn(X,Y,G=EZ){let Q=G(new C7(S7.create(X,OF(Y))));return new LF({...this.#X,node:_5.cloneWithColumnAlteration(this.#X.node,Nt1.create(Q.toOperationNode()))})}addUniqueConstraint(X,Y,G=EZ){let Q=G(new jN(VN.create(Y,X)));return new GE({...this.#X,node:_5.cloneWithTableProps(this.#X.node,{addConstraint:nd.create(Q.toOperationNode())})})}addCheckConstraint(X,Y,G=EZ){let Q=G(new E11(cd.create(Y.toOperationNode(),X)));return new GE({...this.#X,node:_5.cloneWithTableProps(this.#X.node,{addConstraint:nd.create(Q.toOperationNode())})})}addForeignKeyConstraint(X,Y,G,Q,J=EZ){let W=J(new wF(DF.create(Y.map(T5.create),b5(G),Q.map(T5.create),X)));return new wO({...this.#X,constraintBuilder:W})}addPrimaryKeyConstraint(X,Y,G=EZ){let Q=G(new EO(LO.create(Y,X)));return new GE({...this.#X,node:_5.cloneWithTableProps(this.#X.node,{addConstraint:nd.create(Q.toOperationNode())})})}dropConstraint(X){return new HI({...this.#X,node:_5.cloneWithTableProps(this.#X.node,{dropConstraint:ad.create(X)})})}renameConstraint(X,Y){return new HI({...this.#X,node:_5.cloneWithTableProps(this.#X.node,{renameConstraint:Bm0.create(X,Y)})})}addIndex(X){return new JE({...this.#X,node:_5.cloneWithTableProps(this.#X.node,{addIndex:QE.create(X)})})}dropIndex(X){return new GE({...this.#X,node:_5.cloneWithTableProps(this.#X.node,{dropIndex:iL.create(X)})})}$call(X){return X(this)}}class LF{#X;constructor(X){this.#X=n(X)}alterColumn(X,Y){let G=Y(new TK1(X));return new LF({...this.#X,node:_5.cloneWithColumnAlteration(this.#X.node,G.toOperationNode())})}dropColumn(X){return new LF({...this.#X,node:_5.cloneWithColumnAlteration(this.#X.node,Jt1.create(X))})}renameColumn(X,Y){return new LF({...this.#X,node:_5.cloneWithColumnAlteration(this.#X.node,Wt1.create(X,Y))})}addColumn(X,Y,G=EZ){let Q=G(new C7(S7.create(X,OF(Y))));return new LF({...this.#X,node:_5.cloneWithColumnAlteration(this.#X.node,Gt1.create(Q.toOperationNode()))})}modifyColumn(X,Y,G=EZ){let Q=G(new C7(S7.create(X,OF(Y))));return new LF({...this.#X,node:_5.cloneWithColumnAlteration(this.#X.node,Nt1.create(Q.toOperationNode()))})}toOperationNode(){return this.#X.executor.transformQuery(this.#X.node,this.#X.queryId)}compile(){return this.#X.executor.compileQuery(this.toOperationNode(),this.#X.queryId)}async execute(){await this.#X.executor.executeQuery(this.compile())}}var Pt1=D(()=>{Qt1();aT();N11();Zt1();U7();$t1();W0();EK1();Bt1();U11();PK1();qK1();w11();B11();D11();EJ();LQ();AK1();Ot1();Hm0();Fm0();Um0();L11();xe();IK1();Nm0();Dt1();wt1();Lt1()});var P11;var qt1=D(()=>{ZI();oT();wN();P11=class P11 extends zF{transformPrimitiveValueList(X){return DN.create(X.values.map(kY.createImmediate))}transformValue(X){return kY.createImmediate(X.value)}}});class AK{#X;constructor(X){this.#X=n(X)}ifNotExists(){return new AK({...this.#X,node:JF.cloneWith(this.#X.node,{ifNotExists:!0})})}unique(){return new AK({...this.#X,node:JF.cloneWith(this.#X.node,{unique:!0})})}nullsNotDistinct(){return new AK({...this.#X,node:JF.cloneWith(this.#X.node,{nullsNotDistinct:!0})})}on(X){return new AK({...this.#X,node:JF.cloneWith(this.#X.node,{table:b5(X)})})}column(X){return new AK({...this.#X,node:JF.cloneWithColumns(this.#X.node,[Rd(X)])})}columns(X){return new AK({...this.#X,node:JF.cloneWithColumns(this.#X.node,X.map(Rd))})}expression(X){return new AK({...this.#X,node:JF.cloneWithColumns(this.#X.node,[X.toOperationNode()])})}using(X){return new AK({...this.#X,node:JF.cloneWith(this.#X.node,{using:f5.createWithSql(X)})})}where(...X){let Y=new P11;return new AK({...this.#X,node:A6.cloneWithWhere(this.#X.node,Y.transformNode(N7(X),this.#X.queryId))})}$call(X){return X(this)}toOperationNode(){return this.#X.executor.transformQuery(this.#X.node,this.#X.queryId)}compile(){return this.#X.executor.compileQuery(this.toOperationNode(),this.#X.queryId)}async execute(){await this.#X.executor.executeQuery(this.compile())}}var At1=D(()=>{R$1();EK();OQ();LQ();W0();oW();PK();qt1()});class VK1{#X;constructor(X){this.#X=n(X)}ifNotExists(){return new VK1({...this.#X,node:S$1.cloneWith(this.#X.node,{ifNotExists:!0})})}$call(X){return X(this)}toOperationNode(){return this.#X.executor.transformQuery(this.#X.node,this.#X.queryId)}compile(){return this.#X.executor.compileQuery(this.toOperationNode(),this.#X.queryId)}async execute(){await this.#X.executor.executeQuery(this.compile())}}var Tt1=D(()=>{C$1();W0()});function zm0(X){if(Gl0.includes(X))return X;throw Error(`invalid OnCommitAction ${X}`)}var Om0=D(()=>{Ad()});class g3{#X;constructor(X){this.#X=n(X)}temporary(){return new g3({...this.#X,node:wJ.cloneWith(this.#X.node,{temporary:!0})})}onCommit(X){return new g3({...this.#X,node:wJ.cloneWith(this.#X.node,{onCommit:zm0(X)})})}ifNotExists(){return new g3({...this.#X,node:wJ.cloneWith(this.#X.node,{ifNotExists:!0})})}addColumn(X,Y,G=EZ){let Q=G(new C7(S7.create(X,OF(Y))));return new g3({...this.#X,node:wJ.cloneWithColumn(this.#X.node,Q.toOperationNode())})}addPrimaryKeyConstraint(X,Y,G=EZ){let Q=G(new EO(LO.create(Y,X)));return new g3({...this.#X,node:wJ.cloneWithConstraint(this.#X.node,Q.toOperationNode())})}addUniqueConstraint(X,Y,G=EZ){let Q=G(new jN(VN.create(Y,X)));return new g3({...this.#X,node:wJ.cloneWithConstraint(this.#X.node,Q.toOperationNode())})}addCheckConstraint(X,Y,G=EZ){let Q=G(new E11(cd.create(Y.toOperationNode(),X)));return new g3({...this.#X,node:wJ.cloneWithConstraint(this.#X.node,Q.toOperationNode())})}addForeignKeyConstraint(X,Y,G,Q,J=EZ){let W=J(new wF(DF.create(Y.map(T5.create),b5(G),Q.map(T5.create),X)));return new g3({...this.#X,node:wJ.cloneWithConstraint(this.#X.node,W.toOperationNode())})}modifyFront(X){return new g3({...this.#X,node:wJ.cloneWithFrontModifier(this.#X.node,X.toOperationNode())})}modifyEnd(X){return new g3({...this.#X,node:wJ.cloneWithEndModifier(this.#X.node,X.toOperationNode())})}as(X){return new g3({...this.#X,node:wJ.cloneWith(this.#X.node,{selectQuery:y3(X)})})}$call(X){return X(this)}toOperationNode(){return this.#X.executor.transformQuery(this.#X.node,this.#X.queryId)}compile(){return this.#X.executor.compileQuery(this.toOperationNode(),this.#X.queryId)}async execute(){await this.#X.executor.executeQuery(this.compile())}}var It1=D(()=>{N11();Ad();EK1();W0();D11();EJ();PK1();U11();L11();w11();B11();LQ();Om0();Dt1();HF();wt1()});class od{#X;constructor(X){this.#X=n(X)}on(X){return new od({...this.#X,node:iL.cloneWith(this.#X.node,{table:b5(X)})})}ifExists(){return new od({...this.#X,node:iL.cloneWith(this.#X.node,{ifExists:!0})})}cascade(){return new od({...this.#X,node:iL.cloneWith(this.#X.node,{cascade:!0})})}$call(X){return X(this)}toOperationNode(){return this.#X.executor.transformQuery(this.#X.node,this.#X.queryId)}compile(){return this.#X.executor.compileQuery(this.toOperationNode(),this.#X.queryId)}async execute(){await this.#X.executor.executeQuery(this.compile())}}var Vt1=D(()=>{xe();LQ();W0()});class q11{#X;constructor(X){this.#X=n(X)}ifExists(){return new q11({...this.#X,node:he.cloneWith(this.#X.node,{ifExists:!0})})}cascade(){return new q11({...this.#X,node:he.cloneWith(this.#X.node,{cascade:!0})})}$call(X){return X(this)}toOperationNode(){return this.#X.executor.transformQuery(this.#X.node,this.#X.queryId)}compile(){return this.#X.executor.compileQuery(this.toOperationNode(),this.#X.queryId)}async execute(){await this.#X.executor.executeQuery(this.compile())}}var jt1=D(()=>{k$1();W0()});class A11{#X;constructor(X){this.#X=n(X)}ifExists(){return new A11({...this.#X,node:ge.cloneWith(this.#X.node,{ifExists:!0})})}cascade(){return new A11({...this.#X,node:ge.cloneWith(this.#X.node,{cascade:!0})})}$call(X){return X(this)}toOperationNode(){return this.#X.executor.transformQuery(this.#X.node,this.#X.queryId)}compile(){return this.#X.executor.compileQuery(this.toOperationNode(),this.#X.queryId)}async execute(){await this.#X.executor.executeQuery(this.compile())}}var Mt1=D(()=>{v$1();W0()});var EF;var T11=D(()=>{W0();NO();EF=n({is(X){return X.kind==="CreateViewNode"},create(X){return n({kind:"CreateViewNode",name:LJ.create(X)})},cloneWith(X,Y){return n({...X,...Y})}})});class Rt1{#X=new P11;transformQuery(X){return this.#X.transformNode(X.node,X.queryId)}transformResult(X){return Promise.resolve(X.result)}}var Dm0=D(()=>{qt1()});class PO{#X;constructor(X){this.#X=n(X)}temporary(){return new PO({...this.#X,node:EF.cloneWith(this.#X.node,{temporary:!0})})}materialized(){return new PO({...this.#X,node:EF.cloneWith(this.#X.node,{materialized:!0})})}ifNotExists(){return new PO({...this.#X,node:EF.cloneWith(this.#X.node,{ifNotExists:!0})})}orReplace(){return new PO({...this.#X,node:EF.cloneWith(this.#X.node,{orReplace:!0})})}columns(X){return new PO({...this.#X,node:EF.cloneWith(this.#X.node,{columns:X.map(nn1)})})}as(X){let Y=X.withPlugin(new Rt1).toOperationNode();return new PO({...this.#X,node:EF.cloneWith(this.#X.node,{as:Y})})}$call(X){return X(this)}toOperationNode(){return this.#X.executor.transformQuery(this.#X.node,this.#X.queryId)}compile(){return this.#X.executor.compileQuery(this.toOperationNode(),this.#X.queryId)}async execute(){await this.#X.executor.executeQuery(this.compile())}}var St1=D(()=>{W0();T11();OQ();Dm0()});var sd;var jK1=D(()=>{W0();NO();sd=n({is(X){return X.kind==="DropViewNode"},create(X){return n({kind:"DropViewNode",name:LJ.create(X)})},cloneWith(X,Y){return n({...X,...Y})}})});class ed{#X;constructor(X){this.#X=n(X)}materialized(){return new ed({...this.#X,node:sd.cloneWith(this.#X.node,{materialized:!0})})}ifExists(){return new ed({...this.#X,node:sd.cloneWith(this.#X.node,{ifExists:!0})})}cascade(){return new ed({...this.#X,node:sd.cloneWith(this.#X.node,{cascade:!0})})}$call(X){return X(this)}toOperationNode(){return this.#X.executor.transformQuery(this.#X.node,this.#X.queryId)}compile(){return this.#X.executor.compileQuery(this.toOperationNode(),this.#X.queryId)}async execute(){await this.#X.executor.executeQuery(this.compile())}}var Ct1=D(()=>{W0();jK1()});var MK1;var RK1=D(()=>{W0();oT();wN();MK1=n({is(X){return X.kind==="CreateTypeNode"},create(X){return n({kind:"CreateTypeNode",name:X})},cloneWithEnum(X,Y){return n({...X,enum:DN.create(Y.map(kY.createImmediate))})}})});class SK1{#X;constructor(X){this.#X=n(X)}toOperationNode(){return this.#X.executor.transformQuery(this.#X.node,this.#X.queryId)}asEnum(X){return new SK1({...this.#X,node:MK1.cloneWithEnum(this.#X.node,X)})}$call(X){return X(this)}compile(){return this.#X.executor.compileQuery(this.toOperationNode(),this.#X.queryId)}async execute(){await this.#X.executor.executeQuery(this.compile())}}var kt1=D(()=>{W0();RK1()});var CK1;var kK1=D(()=>{W0();CK1=n({is(X){return X.kind==="DropTypeNode"},create(X){return n({kind:"DropTypeNode",name:X})},cloneWith(X,Y){return n({...X,...Y})}})});class vK1{#X;constructor(X){this.#X=n(X)}ifExists(){return new vK1({...this.#X,node:CK1.cloneWith(this.#X.node,{ifExists:!0})})}$call(X){return X(this)}toOperationNode(){return this.#X.executor.transformQuery(this.#X.node,this.#X.queryId)}compile(){return this.#X.executor.compileQuery(this.toOperationNode(),this.#X.queryId)}async execute(){await this.#X.executor.executeQuery(this.compile())}}var vt1=D(()=>{kK1();W0()});function _t1(X){if(X.includes(".")){let G=X.split(".").map(yO8);if(G.length===2)return LJ.createWithSchema(G[0],G[1]);else throw Error(`invalid schemable identifier ${X}`)}else return LJ.create(X)}function yO8(X){return X.trim()}var wm0=D(()=>{NO()});var Xc;var _K1=D(()=>{W0();NO();Xc=n({is(X){return X.kind==="RefreshMaterializedViewNode"},create(X){return n({kind:"RefreshMaterializedViewNode",name:LJ.create(X)})},cloneWith(X,Y){return n({...X,...Y})}})});class Yc{#X;constructor(X){this.#X=n(X)}concurrently(){return new Yc({...this.#X,node:Xc.cloneWith(this.#X.node,{concurrently:!0,withNoData:!1})})}withData(){return new Yc({...this.#X,node:Xc.cloneWith(this.#X.node,{withNoData:!1})})}withNoData(){return new Yc({...this.#X,node:Xc.cloneWith(this.#X.node,{withNoData:!0,concurrently:!1})})}$call(X){return X(this)}toOperationNode(){return this.#X.executor.transformQuery(this.#X.node,this.#X.queryId)}compile(){return this.#X.executor.compileQuery(this.toOperationNode(),this.#X.queryId)}async execute(){await this.#X.executor.executeQuery(this.compile())}}var ft1=D(()=>{W0();_K1()});class Gc{#X;constructor(X){this.#X=X}createTable(X){return new g3({queryId:e4(),executor:this.#X,node:wJ.create(b5(X))})}dropTable(X){return new A11({queryId:e4(),executor:this.#X,node:ge.create(b5(X))})}createIndex(X){return new AK({queryId:e4(),executor:this.#X,node:JF.create(X)})}dropIndex(X){return new od({queryId:e4(),executor:this.#X,node:iL.create(X)})}createSchema(X){return new VK1({queryId:e4(),executor:this.#X,node:S$1.create(X)})}dropSchema(X){return new q11({queryId:e4(),executor:this.#X,node:he.create(X)})}alterTable(X){return new Et1({queryId:e4(),executor:this.#X,node:_5.create(b5(X))})}createView(X){return new PO({queryId:e4(),executor:this.#X,node:EF.create(X)})}refreshMaterializedView(X){return new Yc({queryId:e4(),executor:this.#X,node:Xc.create(X)})}dropView(X){return new ed({queryId:e4(),executor:this.#X,node:sd.create(X)})}createType(X){return new SK1({queryId:e4(),executor:this.#X,node:MK1.create(_t1(X))})}dropType(X){return new vK1({queryId:e4(),executor:this.#X,node:CK1.create(_t1(X))})}withPlugin(X){return new Gc(this.#X.withPlugin(X))}withoutPlugins(){return new Gc(this.#X.withoutPlugins())}withSchema(X){return new Gc(this.#X.withPluginAtFront(new eW(X)))}}var bt1=D(()=>{aT();R$1();C$1();Ad();xe();k$1();v$1();LQ();Pt1();At1();Tt1();It1();Vt1();jt1();Mt1();AN();WI();St1();T11();Ct1();jK1();kt1();vt1();RK1();kK1();wm0();ft1();_K1()});class yt1{ref(X){return new ln1(X)}table(X){return new Yt1(X)}}var xt1=D(()=>{le();wK1()});class ht1{#X;constructor(X){this.#X=X}async provideConnection(X){let Y=await this.#X.acquireConnection();try{return await X(Y)}finally{await this.#X.releaseConnection(Y)}}}var ZE;var gt1=D(()=>{fa1();ZE=class ZE extends Z11{#X;#Y;#G;constructor(X,Y,G,Q=[]){super(Q);this.#X=X,this.#Y=Y,this.#G=G}get adapter(){return this.#Y}compileQuery(X,Y){return this.#X.compileQuery(X,Y)}provideConnection(X){return this.#G.provideConnection(X)}withPlugins(X){return new ZE(this.#X,this.#Y,this.#G,[...this.plugins,...X])}withPlugin(X){return new ZE(this.#X,this.#Y,this.#G,[...this.plugins,X])}withPluginAtFront(X){return new ZE(this.#X,this.#Y,this.#G,[X,...this.plugins])}withConnectionProvider(X){return new ZE(this.#X,this.#Y,X,[...this.plugins])}withoutPlugins(){return new ZE(this.#X,this.#Y,this.#G,[])}}});function fK1(){if(typeof performance<"u"&&F9(performance.now))return performance.now();else return Date.now()}var Lm0=D(()=>{W0()});class ut1{#X;#Y;#G;#Q;#J;#Z=new WeakSet;constructor(X,Y){this.#Q=!1,this.#X=X,this.#Y=Y}async init(){if(this.#J)throw Error("driver has already been destroyed");if(!this.#G)this.#G=this.#X.init().then(()=>{this.#Q=!0}).catch((X)=>{return this.#G=void 0,Promise.reject(X)});await this.#G}async acquireConnection(){if(this.#J)throw Error("driver has already been destroyed");if(!this.#Q)await this.init();let X=await this.#X.acquireConnection();if(!this.#Z.has(X)){if(this.#$())this.#W(X);this.#Z.add(X)}return X}async releaseConnection(X){await this.#X.releaseConnection(X)}beginTransaction(X,Y){return this.#X.beginTransaction(X,Y)}commitTransaction(X){return this.#X.commitTransaction(X)}rollbackTransaction(X){return this.#X.rollbackTransaction(X)}savepoint(X,Y,G){if(this.#X.savepoint)return this.#X.savepoint(X,Y,G);throw Error("The `savepoint` method is not supported by this driver")}rollbackToSavepoint(X,Y,G){if(this.#X.rollbackToSavepoint)return this.#X.rollbackToSavepoint(X,Y,G);throw Error("The `rollbackToSavepoint` method is not supported by this driver")}releaseSavepoint(X,Y,G){if(this.#X.releaseSavepoint)return this.#X.releaseSavepoint(X,Y,G);throw Error("The `releaseSavepoint` method is not supported by this driver")}async destroy(){if(!this.#G)return;if(await this.#G,!this.#J)this.#J=this.#X.destroy().catch((X)=>{return this.#J=void 0,Promise.reject(X)});await this.#J}#$(){return this.#Y.isLevelEnabled("query")||this.#Y.isLevelEnabled("error")}#W(X){let{executeQuery:Y,streamQuery:G}=X,Q=this;X.executeQuery=async(J)=>{let W,Z=fK1();try{return await Y.call(X,J)}catch($){throw W=$,await Q.#K($,J,Z),$}finally{if(!W)await Q.#H(J,Z)}},X.streamQuery=async function*(J,W){let Z,$=fK1();try{for await(let K of G.call(X,J,W))yield K}catch(K){throw Z=K,await Q.#K(K,J,$),K}finally{if(!Z)await Q.#H(J,$,!0)}}}async#K(X,Y,G){await this.#Y.error(()=>({level:"error",error:X,query:Y,queryDurationMillis:this.#U(G)}))}async#H(X,Y,G=!1){await this.#Y.query(()=>({level:"query",isStream:G,query:X,queryDurationMillis:this.#U(Y)}))}#U(X){return fK1()-X}}var Em0=D(()=>{Lm0()});class I11{#X;#Y;constructor(X){this.#X=X}async provideConnection(X){while(this.#Y)await this.#Y.catch(xO8);return this.#Y=this.#G(X).finally(()=>{this.#Y=void 0}),this.#Y}async#G(X){return await X(this.#X)}}var xO8=()=>{};function lt1(X){if(X.accessMode&&!hO8.includes(X.accessMode))throw Error(`invalid transaction access mode ${X.accessMode}`);if(X.isolationLevel&&!gO8.includes(X.isolationLevel))throw Error(`invalid transaction isolation level ${X.isolationLevel}`)}var hO8,gO8;var mt1=D(()=>{hO8=["read only","read write"],gO8=["read uncommitted","read committed","repeatable read","serializable","snapshot"]});class dt1{#X;#Y;constructor(X){if(F9(X))this.#Y=X,this.#X=n({query:!0,error:!0});else this.#Y=lO8,this.#X=n({query:X.includes("query"),error:X.includes("error")})}isLevelEnabled(X){return this.#X[X]}async query(X){if(this.#X.query)await this.#Y(X())}async error(X){if(this.#X.error)await this.#Y(X())}}function lO8(X){if(X.level==="query"){let Y=`kysely:query:${X.isStream?"stream:":""}`;console.log(`${Y} ${X.query.sql}`),console.log(`${Y} duration: ${X.queryDurationMillis.toFixed(1)}ms`)}else if(X.level==="error")if(X.error instanceof Error)console.error(`kysely:error: ${X.error.stack??X.error.message}`);else console.error(`kysely:error: ${JSON.stringify({error:X.error,query:X.query.sql,queryDurationMillis:X.queryDurationMillis})}`)}var uO8,BT7;var ct1=D(()=>{W0();uO8=["query","error"],BT7=n(uO8)});function Pm0(X){return F7(X)&&F9(X.compile)}var it1=D(()=>{W0()});function mO8(X){return F7(X)&&F7(X.config)&&F7(X.driver)&&F7(X.executor)&&F7(X.dialect)}class qm0{#X;constructor(X){this.#X=n(X)}async execute(X){return this.#X.executor.provideConnection(async(Y)=>{let G=this.#X.executor.withConnectionProvider(new I11(Y)),Q=new AZ({...this.#X,executor:G});return await X(Q)})}}class bK1{#X;constructor(X){this.#X=n(X)}setAccessMode(X){return new bK1({...this.#X,accessMode:X})}setIsolationLevel(X){return new bK1({...this.#X,isolationLevel:X})}async execute(X){let{isolationLevel:Y,accessMode:G,...Q}=this.#X,J={isolationLevel:Y,accessMode:G};return lt1(J),this.#X.executor.provideConnection(async(W)=>{let Z={isCommitted:!1,isRolledBack:!1},$=new AO(this.#X.executor.withConnectionProvider(new I11(W)),Z),K=new UI({...Q,executor:$}),H=!1;try{await this.#X.driver.beginTransaction(W,J),H=!0;let U=await X(K);return await this.#X.driver.commitTransaction(W),Z.isCommitted=!0,U}catch(U){if(H)await this.#X.driver.rollbackTransaction(W),Z.isRolledBack=!0;throw U}})}}class yK1{#X;constructor(X){this.#X=n(X)}setAccessMode(X){return new yK1({...this.#X,accessMode:X})}setIsolationLevel(X){return new yK1({...this.#X,isolationLevel:X})}async execute(){let{isolationLevel:X,accessMode:Y,...G}=this.#X,Q={isolationLevel:X,accessMode:Y};lt1(Q);let J=await JK1(this.#X.executor);return await this.#X.driver.beginTransaction(J.connection,Q),new qO({...G,connection:J,executor:this.#X.executor.withConnectionProvider(new I11(J.connection))})}}class Qc{#X;constructor(X){this.#X=X}async execute(){return await this.#X()}}function FI(X){if(X.isCommitted)throw Error("Transaction is already committed");if(X.isRolledBack)throw Error("Transaction is already rolled back")}class AO{#X;#Y;constructor(X,Y){if(X instanceof AO)this.#X=X.#X;else this.#X=X;this.#Y=Y}get adapter(){return this.#X.adapter}get plugins(){return this.#X.plugins}transformQuery(X,Y){return this.#X.transformQuery(X,Y)}compileQuery(X,Y){return this.#X.compileQuery(X,Y)}provideConnection(X){return this.#X.provideConnection(X)}executeQuery(X){return FI(this.#Y),this.#X.executeQuery(X)}stream(X,Y){return FI(this.#Y),this.#X.stream(X,Y)}withConnectionProvider(X){return new AO(this.#X.withConnectionProvider(X),this.#Y)}withPlugin(X){return new AO(this.#X.withPlugin(X),this.#Y)}withPlugins(X){return new AO(this.#X.withPlugins(X),this.#Y)}withPluginAtFront(X){return new AO(this.#X.withPluginAtFront(X),this.#Y)}withoutPlugins(){return new AO(this.#X.withoutPlugins(),this.#Y)}}var AZ,UI,qO;var Am0=D(()=>{bt1();xt1();ZK1();gt1();W0();Em0();mt1();OK1();ct1();AN();it1();DK1();$11();HF();WI();_a1();me();Symbol.asyncDispose??=Symbol("Symbol.asyncDispose");AZ=class AZ extends TN{#X;constructor(X){let Y,G;if(mO8(X))Y={executor:X.executor},G={...X};else{let Q=X.dialect,J=Q.createDriver(),W=Q.createQueryCompiler(),Z=Q.createAdapter(),$=new dt1(X.log??[]),K=new ut1(J,$),H=new ht1(K),U=new ZE(W,Z,H,X.plugins??[]);Y={executor:U},G={config:X,executor:U,dialect:Q,driver:K}}super(Y);this.#X=n(G)}get schema(){return new Gc(this.#X.executor)}get dynamic(){return new yt1}get introspection(){return this.#X.dialect.createIntrospector(this.withoutPlugins())}case(X){return new K11({node:X$.create(LZ(X)?void 0:y3(X))})}get fn(){return zK1()}transaction(){return new bK1({...this.#X})}startTransaction(){return new yK1({...this.#X})}connection(){return new qm0({...this.#X})}withPlugin(X){return new AZ({...this.#X,executor:this.#X.executor.withPlugin(X)})}withoutPlugins(){return new AZ({...this.#X,executor:this.#X.executor.withoutPlugins()})}withSchema(X){return new AZ({...this.#X,executor:this.#X.executor.withPluginAtFront(new eW(X))})}withTables(){return new AZ({...this.#X})}async destroy(){await this.#X.driver.destroy()}get isTransaction(){return!1}getExecutor(){return this.#X.executor}executeQuery(X,Y){if(Y!==void 0)ON("Passing `queryId` in `db.executeQuery` is deprecated and will result in a compile-time error in the future.");let G=Pm0(X)?X.compile():X;return this.getExecutor().executeQuery(G)}async[Symbol.asyncDispose](){await this.destroy()}};UI=class UI extends AZ{#X;constructor(X){super(X);this.#X=X}get isTransaction(){return!0}transaction(){throw Error("calling the transaction method for a Transaction is not supported")}connection(){throw Error("calling the connection method for a Transaction is not supported")}async destroy(){throw Error("calling the destroy method for a Transaction is not supported")}withPlugin(X){return new UI({...this.#X,executor:this.#X.executor.withPlugin(X)})}withoutPlugins(){return new UI({...this.#X,executor:this.#X.executor.withoutPlugins()})}withSchema(X){return new UI({...this.#X,executor:this.#X.executor.withPluginAtFront(new eW(X))})}withTables(){return new UI({...this.#X})}};qO=class qO extends UI{#X;#Y;#G;constructor(X){let Y={isCommitted:!1,isRolledBack:!1};X={...X,executor:new AO(X.executor,Y)};let{connection:G,...Q}=X;super(Q);this.#X=n(X),this.#G=Y;let J=e4();this.#Y=(W)=>X.executor.compileQuery(W,J)}get isCommitted(){return this.#G.isCommitted}get isRolledBack(){return this.#G.isRolledBack}commit(){return FI(this.#G),new Qc(async()=>{await this.#X.driver.commitTransaction(this.#X.connection.connection),this.#G.isCommitted=!0,this.#X.connection.release()})}rollback(){return FI(this.#G),new Qc(async()=>{await this.#X.driver.rollbackTransaction(this.#X.connection.connection),this.#G.isRolledBack=!0,this.#X.connection.release()})}savepoint(X){return FI(this.#G),new Qc(async()=>{return await this.#X.driver.savepoint?.(this.#X.connection.connection,X,this.#Y),new qO({...this.#X})})}rollbackToSavepoint(X){return FI(this.#G),new Qc(async()=>{return await this.#X.driver.rollbackToSavepoint?.(this.#X.connection.connection,X,this.#Y),new qO({...this.#X})})}releaseSavepoint(X){return FI(this.#G),new Qc(async()=>{return await this.#X.driver.releaseSavepoint?.(this.#X.connection.connection,X,this.#Y),new qO({...this.#X})})}withPlugin(X){return new qO({...this.#X,executor:this.#X.executor.withPlugin(X)})}withoutPlugins(){return new qO({...this.#X,executor:this.#X.executor.withoutPlugins()})}withSchema(X){return new qO({...this.#X,executor:this.#X.executor.withPluginAtFront(new eW(X))})}withTables(){return new qO({...this.#X})}}});var Tm0=()=>{};var Im0=()=>{};var Vm0=()=>{};var jm0=()=>{};var Mm0=()=>{};class V11{#X;constructor(X){this.#X=n(X)}get expressionType(){return}get isRawBuilder(){return!0}as(X){return new Rm0(this,X)}$castTo(){return new V11({...this.#X})}$notNull(){return new V11(this.#X)}withPlugin(X){return new V11({...this.#X,plugins:this.#X.plugins!==void 0?n([...this.#X.plugins,X]):n([X])})}toOperationNode(){return this.#G(this.#Y())}compile(X){return this.#Q(this.#Y(X))}async execute(X){let Y=this.#Y(X);return Y.executeQuery(this.#Q(Y))}#Y(X){let Y=X!==void 0?X.getExecutor():YE;return this.#X.plugins!==void 0?Y.withPlugins(this.#X.plugins):Y}#G(X){return X.transformQuery(this.#X.rawNode,this.#X.queryId)}#Q(X){return X.compileQuery(this.#G(X),this.#X.queryId)}}function TO(X){return new V11(X)}class Rm0{#X;#Y;constructor(X,Y){this.#X=X,this.#Y=Y}get expression(){return this.#X}get alias(){return this.#Y}get rawBuilder(){return this.#X}toOperationNode(){return VG.create(this.#X.toOperationNode(),R7(this.#Y)?this.#Y.toOperationNode():k4.create(this.#Y))}}var pt1=D(()=>{ZF();W0();md();U7();f3()});function Sm0(X){if(R7(X))return X.toOperationNode();return d9(X)}var O1;var WE=D(()=>{U7();f3();EK();wN();OQ();LQ();LN();AN();pt1();O1=Object.assign((X,...Y)=>{return TO({queryId:e4(),rawNode:f5.create(X,Y?.map(Sm0)??[])})},{ref(X){return TO({queryId:e4(),rawNode:f5.createWithChild(aW(X))})},val(X){return TO({queryId:e4(),rawNode:f5.createWithChild(d9(X))})},value(X){return this.val(X)},table(X){return TO({queryId:e4(),rawNode:f5.createWithChild(b5(X))})},id(...X){let Y=Array(X.length+1).fill(".");return Y[0]="",Y[Y.length-1]="",TO({queryId:e4(),rawNode:f5.create(Y,X.map(k4.create))})},lit(X){return TO({queryId:e4(),rawNode:f5.createWithChild(kY.createImmediate(X))})},literal(X){return this.lit(X)},raw(X){return TO({queryId:e4(),rawNode:f5.createWithSql(X)})},join(X,Y=O1`, `){let G=Array(Math.max(2*X.length-1,0)),Q=Y.toOperationNode();for(let J=0;J<X.length;++J)if(G[2*J]=Sm0(X[J]),J!==X.length-1)G[2*J+1]=Q;return TO({queryId:e4(),rawNode:f5.createWithChildren(G)})}})});var Cm0=()=>{};var km0=()=>{};class nt1{nodeStack=[];get parentNode(){return this.nodeStack[this.nodeStack.length-2]}#X=n({AliasNode:this.visitAlias.bind(this),ColumnNode:this.visitColumn.bind(this),IdentifierNode:this.visitIdentifier.bind(this),SchemableIdentifierNode:this.visitSchemableIdentifier.bind(this),RawNode:this.visitRaw.bind(this),ReferenceNode:this.visitReference.bind(this),SelectQueryNode:this.visitSelectQuery.bind(this),SelectionNode:this.visitSelection.bind(this),TableNode:this.visitTable.bind(this),FromNode:this.visitFrom.bind(this),SelectAllNode:this.visitSelectAll.bind(this),AndNode:this.visitAnd.bind(this),OrNode:this.visitOr.bind(this),ValueNode:this.visitValue.bind(this),ValueListNode:this.visitValueList.bind(this),PrimitiveValueListNode:this.visitPrimitiveValueList.bind(this),ParensNode:this.visitParens.bind(this),JoinNode:this.visitJoin.bind(this),OperatorNode:this.visitOperator.bind(this),WhereNode:this.visitWhere.bind(this),InsertQueryNode:this.visitInsertQuery.bind(this),DeleteQueryNode:this.visitDeleteQuery.bind(this),ReturningNode:this.visitReturning.bind(this),CreateTableNode:this.visitCreateTable.bind(this),AddColumnNode:this.visitAddColumn.bind(this),ColumnDefinitionNode:this.visitColumnDefinition.bind(this),DropTableNode:this.visitDropTable.bind(this),DataTypeNode:this.visitDataType.bind(this),OrderByNode:this.visitOrderBy.bind(this),OrderByItemNode:this.visitOrderByItem.bind(this),GroupByNode:this.visitGroupBy.bind(this),GroupByItemNode:this.visitGroupByItem.bind(this),UpdateQueryNode:this.visitUpdateQuery.bind(this),ColumnUpdateNode:this.visitColumnUpdate.bind(this),LimitNode:this.visitLimit.bind(this),OffsetNode:this.visitOffset.bind(this),OnConflictNode:this.visitOnConflict.bind(this),OnDuplicateKeyNode:this.visitOnDuplicateKey.bind(this),CreateIndexNode:this.visitCreateIndex.bind(this),DropIndexNode:this.visitDropIndex.bind(this),ListNode:this.visitList.bind(this),PrimaryKeyConstraintNode:this.visitPrimaryKeyConstraint.bind(this),UniqueConstraintNode:this.visitUniqueConstraint.bind(this),ReferencesNode:this.visitReferences.bind(this),CheckConstraintNode:this.visitCheckConstraint.bind(this),WithNode:this.visitWith.bind(this),CommonTableExpressionNode:this.visitCommonTableExpression.bind(this),CommonTableExpressionNameNode:this.visitCommonTableExpressionName.bind(this),HavingNode:this.visitHaving.bind(this),CreateSchemaNode:this.visitCreateSchema.bind(this),DropSchemaNode:this.visitDropSchema.bind(this),AlterTableNode:this.visitAlterTable.bind(this),DropColumnNode:this.visitDropColumn.bind(this),RenameColumnNode:this.visitRenameColumn.bind(this),AlterColumnNode:this.visitAlterColumn.bind(this),ModifyColumnNode:this.visitModifyColumn.bind(this),AddConstraintNode:this.visitAddConstraint.bind(this),DropConstraintNode:this.visitDropConstraint.bind(this),RenameConstraintNode:this.visitRenameConstraint.bind(this),ForeignKeyConstraintNode:this.visitForeignKeyConstraint.bind(this),CreateViewNode:this.visitCreateView.bind(this),RefreshMaterializedViewNode:this.visitRefreshMaterializedView.bind(this),DropViewNode:this.visitDropView.bind(this),GeneratedNode:this.visitGenerated.bind(this),DefaultValueNode:this.visitDefaultValue.bind(this),OnNode:this.visitOn.bind(this),ValuesNode:this.visitValues.bind(this),SelectModifierNode:this.visitSelectModifier.bind(this),CreateTypeNode:this.visitCreateType.bind(this),DropTypeNode:this.visitDropType.bind(this),ExplainNode:this.visitExplain.bind(this),DefaultInsertValueNode:this.visitDefaultInsertValue.bind(this),AggregateFunctionNode:this.visitAggregateFunction.bind(this),OverNode:this.visitOver.bind(this),PartitionByNode:this.visitPartitionBy.bind(this),PartitionByItemNode:this.visitPartitionByItem.bind(this),SetOperationNode:this.visitSetOperation.bind(this),BinaryOperationNode:this.visitBinaryOperation.bind(this),UnaryOperationNode:this.visitUnaryOperation.bind(this),UsingNode:this.visitUsing.bind(this),FunctionNode:this.visitFunction.bind(this),CaseNode:this.visitCase.bind(this),WhenNode:this.visitWhen.bind(this),JSONReferenceNode:this.visitJSONReference.bind(this),JSONPathNode:this.visitJSONPath.bind(this),JSONPathLegNode:this.visitJSONPathLeg.bind(this),JSONOperatorChainNode:this.visitJSONOperatorChain.bind(this),TupleNode:this.visitTuple.bind(this),MergeQueryNode:this.visitMergeQuery.bind(this),MatchedNode:this.visitMatched.bind(this),AddIndexNode:this.visitAddIndex.bind(this),CastNode:this.visitCast.bind(this),FetchNode:this.visitFetch.bind(this),TopNode:this.visitTop.bind(this),OutputNode:this.visitOutput.bind(this),OrActionNode:this.visitOrAction.bind(this),CollateNode:this.visitCollate.bind(this)});visitNode=(X)=>{this.nodeStack.push(X),this.#X[X.kind](X),this.nodeStack.pop()}}var at1=D(()=>{W0()});var dO8,EQ,cO8,vm0,iO8;var NI=D(()=>{Ad();eT();at1();aL();Cd();EK();W0();T11();KK1();XI();me();dO8=/'/g;EQ=class EQ extends nt1{#X="";#Y=[];get numParameters(){return this.#Y.length}compileQuery(X,Y){return this.#X="",this.#Y=[],this.nodeStack.splice(0,this.nodeStack.length),this.visitNode(X),n({query:X,queryId:Y,sql:this.getSql(),parameters:[...this.#Y]})}getSql(){return this.#X}visitSelectQuery(X){let Y=this.parentNode!==void 0&&!rW.is(this.parentNode)&&!xX.is(this.parentNode)&&!wJ.is(this.parentNode)&&!EF.is(this.parentNode)&&!$K1.is(this.parentNode);if(this.parentNode===void 0&&X.explain)this.visitNode(X.explain),this.append(" ");if(Y)this.append("(");if(X.with)this.visitNode(X.with),this.append(" ");if(this.append("select"),X.distinctOn)this.append(" "),this.compileDistinctOn(X.distinctOn);if(X.frontModifiers?.length)this.append(" "),this.compileList(X.frontModifiers," ");if(X.top)this.append(" "),this.visitNode(X.top);if(X.selections)this.append(" "),this.compileList(X.selections);if(X.from)this.append(" "),this.visitNode(X.from);if(X.joins)this.append(" "),this.compileList(X.joins," ");if(X.where)this.append(" "),this.visitNode(X.where);if(X.groupBy)this.append(" "),this.visitNode(X.groupBy);if(X.having)this.append(" "),this.visitNode(X.having);if(X.setOperations)this.append(" "),this.compileList(X.setOperations," ");if(X.orderBy)this.append(" "),this.visitNode(X.orderBy);if(X.limit)this.append(" "),this.visitNode(X.limit);if(X.offset)this.append(" "),this.visitNode(X.offset);if(X.fetch)this.append(" "),this.visitNode(X.fetch);if(X.endModifiers?.length)this.append(" "),this.compileList(this.sortSelectModifiers([...X.endModifiers])," ");if(Y)this.append(")")}visitFrom(X){this.append("from "),this.compileList(X.froms)}visitSelection(X){this.visitNode(X.selection)}visitColumn(X){this.visitNode(X.column)}compileDistinctOn(X){this.append("distinct on ("),this.compileList(X),this.append(")")}compileList(X,Y=", "){let G=X.length-1;for(let Q=0;Q<=G;Q++)if(this.visitNode(X[Q]),Q<G)this.append(Y)}visitWhere(X){this.append("where "),this.visitNode(X.where)}visitHaving(X){this.append("having "),this.visitNode(X.having)}visitInsertQuery(X){let Y=this.parentNode!==void 0&&!rW.is(this.parentNode)&&!f5.is(this.parentNode)&&!qK.is(this.parentNode);if(this.parentNode===void 0&&X.explain)this.visitNode(X.explain),this.append(" ");if(Y)this.append("(");if(X.with)this.visitNode(X.with),this.append(" ");if(this.append(X.replace?"replace":"insert"),X.ignore)ON("`InsertQueryNode.ignore` is deprecated. Use `InsertQueryNode.orAction` instead."),this.append(" ignore");if(X.orAction)this.append(" "),this.visitNode(X.orAction);if(X.top)this.append(" "),this.visitNode(X.top);if(X.into)this.append(" into "),this.visitNode(X.into);if(X.columns)this.append(" ("),this.compileList(X.columns),this.append(")");if(X.output)this.append(" "),this.visitNode(X.output);if(X.values)this.append(" "),this.visitNode(X.values);if(X.defaultValues)this.append(" "),this.append("default values");if(X.onConflict)this.append(" "),this.visitNode(X.onConflict);if(X.onDuplicateKey)this.append(" "),this.visitNode(X.onDuplicateKey);if(X.returning)this.append(" "),this.visitNode(X.returning);if(Y)this.append(")");if(X.endModifiers?.length)this.append(" "),this.compileList(X.endModifiers," ")}visitValues(X){this.append("values "),this.compileList(X.values)}visitDeleteQuery(X){let Y=this.parentNode!==void 0&&!rW.is(this.parentNode)&&!f5.is(this.parentNode);if(this.parentNode===void 0&&X.explain)this.visitNode(X.explain),this.append(" ");if(Y)this.append("(");if(X.with)this.visitNode(X.with),this.append(" ");if(this.append("delete "),X.top)this.visitNode(X.top),this.append(" ");if(this.visitNode(X.from),X.output)this.append(" "),this.visitNode(X.output);if(X.using)this.append(" "),this.visitNode(X.using);if(X.joins)this.append(" "),this.compileList(X.joins," ");if(X.where)this.append(" "),this.visitNode(X.where);if(X.orderBy)this.append(" "),this.visitNode(X.orderBy);if(X.limit)this.append(" "),this.visitNode(X.limit);if(X.returning)this.append(" "),this.visitNode(X.returning);if(Y)this.append(")");if(X.endModifiers?.length)this.append(" "),this.compileList(X.endModifiers," ")}visitReturning(X){this.append("returning "),this.compileList(X.selections)}visitAlias(X){this.visitNode(X.node),this.append(" as "),this.visitNode(X.alias)}visitReference(X){if(X.table)this.visitNode(X.table),this.append(".");this.visitNode(X.column)}visitSelectAll(X){this.append("*")}visitIdentifier(X){this.append(this.getLeftIdentifierWrapper()),this.compileUnwrappedIdentifier(X),this.append(this.getRightIdentifierWrapper())}compileUnwrappedIdentifier(X){if(!H9(X.name))throw Error("a non-string identifier was passed to compileUnwrappedIdentifier.");this.append(this.sanitizeIdentifier(X.name))}visitAnd(X){this.visitNode(X.left),this.append(" and "),this.visitNode(X.right)}visitOr(X){this.visitNode(X.left),this.append(" or "),this.visitNode(X.right)}visitValue(X){if(X.immediate)this.appendImmediateValue(X.value);else this.appendValue(X.value)}visitValueList(X){this.append("("),this.compileList(X.values),this.append(")")}visitTuple(X){this.append("("),this.compileList(X.values),this.append(")")}visitPrimitiveValueList(X){this.append("(");let{values:Y}=X;for(let G=0;G<Y.length;++G)if(this.appendValue(Y[G]),G!==Y.length-1)this.append(", ");this.append(")")}visitParens(X){this.append("("),this.visitNode(X.node),this.append(")")}visitJoin(X){if(this.append(iO8[X.joinType]),this.append(" "),this.visitNode(X.table),X.on)this.append(" "),this.visitNode(X.on)}visitOn(X){this.append("on "),this.visitNode(X.on)}visitRaw(X){let{sqlFragments:Y,parameters:G}=X;for(let Q=0;Q<Y.length;++Q)if(this.append(Y[Q]),G.length>Q)this.visitNode(G[Q])}visitOperator(X){this.append(X.operator)}visitTable(X){this.visitNode(X.table)}visitSchemableIdentifier(X){if(X.schema)this.visitNode(X.schema),this.append(".");this.visitNode(X.identifier)}visitCreateTable(X){if(this.append("create "),X.frontModifiers?.length)this.compileList(X.frontModifiers," "),this.append(" ");if(X.temporary)this.append("temporary ");if(this.append("table "),X.ifNotExists)this.append("if not exists ");if(this.visitNode(X.table),!X.selectQuery)this.append(" ("),this.compileList([...X.columns,...X.constraints??[]]),this.append(")");if(X.onCommit)this.append(" on commit "),this.append(X.onCommit);if(X.endModifiers?.length)this.append(" "),this.compileList(X.endModifiers," ");if(X.selectQuery)this.append(" as "),this.visitNode(X.selectQuery)}visitColumnDefinition(X){if(X.ifNotExists)this.append("if not exists ");if(this.visitNode(X.column),this.append(" "),this.visitNode(X.dataType),X.unsigned)this.append(" unsigned");if(X.frontModifiers&&X.frontModifiers.length>0)this.append(" "),this.compileList(X.frontModifiers," ");if(X.generated)this.append(" "),this.visitNode(X.generated);if(X.identity)this.append(" identity");if(X.defaultTo)this.append(" "),this.visitNode(X.defaultTo);if(X.notNull)this.append(" not null");if(X.unique)this.append(" unique");if(X.nullsNotDistinct)this.append(" nulls not distinct");if(X.primaryKey)this.append(" primary key");if(X.autoIncrement)this.append(" "),this.append(this.getAutoIncrement());if(X.references)this.append(" "),this.visitNode(X.references);if(X.check)this.append(" "),this.visitNode(X.check);if(X.endModifiers&&X.endModifiers.length>0)this.append(" "),this.compileList(X.endModifiers," ")}getAutoIncrement(){return"auto_increment"}visitReferences(X){if(this.append("references "),this.visitNode(X.table),this.append(" ("),this.compileList(X.columns),this.append(")"),X.onDelete)this.append(" on delete "),this.append(X.onDelete);if(X.onUpdate)this.append(" on update "),this.append(X.onUpdate)}visitDropTable(X){if(this.append("drop table "),X.ifExists)this.append("if exists ");if(this.visitNode(X.table),X.cascade)this.append(" cascade")}visitDataType(X){this.append(X.dataType)}visitOrderBy(X){this.append("order by "),this.compileList(X.items)}visitOrderByItem(X){if(this.visitNode(X.orderBy),X.collation)this.append(" "),this.visitNode(X.collation);if(X.direction)this.append(" "),this.visitNode(X.direction);if(X.nulls)this.append(" nulls "),this.append(X.nulls)}visitGroupBy(X){this.append("group by "),this.compileList(X.items)}visitGroupByItem(X){this.visitNode(X.groupBy)}visitUpdateQuery(X){let Y=this.parentNode!==void 0&&!rW.is(this.parentNode)&&!f5.is(this.parentNode)&&!qK.is(this.parentNode);if(this.parentNode===void 0&&X.explain)this.visitNode(X.explain),this.append(" ");if(Y)this.append("(");if(X.with)this.visitNode(X.with),this.append(" ");if(this.append("update "),X.top)this.visitNode(X.top),this.append(" ");if(X.table)this.visitNode(X.table),this.append(" ");if(this.append("set "),X.updates)this.compileList(X.updates);if(X.output)this.append(" "),this.visitNode(X.output);if(X.from)this.append(" "),this.visitNode(X.from);if(X.joins){if(!X.from)throw Error("Joins in an update query are only supported as a part of a PostgreSQL 'update set from join' query. If you want to create a MySQL 'update join set' query, see https://kysely.dev/docs/examples/update/my-sql-joins");this.append(" "),this.compileList(X.joins," ")}if(X.where)this.append(" "),this.visitNode(X.where);if(X.returning)this.append(" "),this.visitNode(X.returning);if(X.orderBy)this.append(" "),this.visitNode(X.orderBy);if(X.limit)this.append(" "),this.visitNode(X.limit);if(Y)this.append(")");if(X.endModifiers?.length)this.append(" "),this.compileList(X.endModifiers," ")}visitColumnUpdate(X){this.visitNode(X.column),this.append(" = "),this.visitNode(X.value)}visitLimit(X){this.append("limit "),this.visitNode(X.limit)}visitOffset(X){this.append("offset "),this.visitNode(X.offset)}visitOnConflict(X){if(this.append("on conflict"),X.columns)this.append(" ("),this.compileList(X.columns),this.append(")");else if(X.constraint)this.append(" on constraint "),this.visitNode(X.constraint);else if(X.indexExpression)this.append(" ("),this.visitNode(X.indexExpression),this.append(")");if(X.indexWhere)this.append(" "),this.visitNode(X.indexWhere);if(X.doNothing===!0)this.append(" do nothing");else if(X.updates){if(this.append(" do update set "),this.compileList(X.updates),X.updateWhere)this.append(" "),this.visitNode(X.updateWhere)}}visitOnDuplicateKey(X){this.append("on duplicate key update "),this.compileList(X.updates)}visitCreateIndex(X){if(this.append("create "),X.unique)this.append("unique ");if(this.append("index "),X.ifNotExists)this.append("if not exists ");if(this.visitNode(X.name),X.table)this.append(" on "),this.visitNode(X.table);if(X.using)this.append(" using "),this.visitNode(X.using);if(X.columns)this.append(" ("),this.compileList(X.columns),this.append(")");if(X.nullsNotDistinct)this.append(" nulls not distinct");if(X.where)this.append(" "),this.visitNode(X.where)}visitDropIndex(X){if(this.append("drop index "),X.ifExists)this.append("if exists ");if(this.visitNode(X.name),X.table)this.append(" on "),this.visitNode(X.table);if(X.cascade)this.append(" cascade")}visitCreateSchema(X){if(this.append("create schema "),X.ifNotExists)this.append("if not exists ");this.visitNode(X.schema)}visitDropSchema(X){if(this.append("drop schema "),X.ifExists)this.append("if exists ");if(this.visitNode(X.schema),X.cascade)this.append(" cascade")}visitPrimaryKeyConstraint(X){if(X.name)this.append("constraint "),this.visitNode(X.name),this.append(" ");this.append("primary key ("),this.compileList(X.columns),this.append(")"),this.buildDeferrable(X)}buildDeferrable(X){if(X.deferrable!==void 0)if(X.deferrable)this.append(" deferrable");else this.append(" not deferrable");if(X.initiallyDeferred!==void 0)if(X.initiallyDeferred)this.append(" initially deferred");else this.append(" initially immediate")}visitUniqueConstraint(X){if(X.name)this.append("constraint "),this.visitNode(X.name),this.append(" ");if(this.append("unique"),X.nullsNotDistinct)this.append(" nulls not distinct");this.append(" ("),this.compileList(X.columns),this.append(")"),this.buildDeferrable(X)}visitCheckConstraint(X){if(X.name)this.append("constraint "),this.visitNode(X.name),this.append(" ");this.append("check ("),this.visitNode(X.expression),this.append(")")}visitForeignKeyConstraint(X){if(X.name)this.append("constraint "),this.visitNode(X.name),this.append(" ");if(this.append("foreign key ("),this.compileList(X.columns),this.append(") "),this.visitNode(X.references),X.onDelete)this.append(" on delete "),this.append(X.onDelete);if(X.onUpdate)this.append(" on update "),this.append(X.onUpdate);this.buildDeferrable(X)}visitList(X){this.compileList(X.items)}visitWith(X){if(this.append("with "),X.recursive)this.append("recursive ");this.compileList(X.expressions)}visitCommonTableExpression(X){if(this.visitNode(X.name),this.append(" as "),UO(X.materialized)){if(!X.materialized)this.append("not ");this.append("materialized ")}this.visitNode(X.expression)}visitCommonTableExpressionName(X){if(this.visitNode(X.table),X.columns)this.append("("),this.compileList(X.columns),this.append(")")}visitAlterTable(X){if(this.append("alter table "),this.visitNode(X.table),this.append(" "),X.renameTo)this.append("rename to "),this.visitNode(X.renameTo);if(X.setSchema)this.append("set schema "),this.visitNode(X.setSchema);if(X.addConstraint)this.visitNode(X.addConstraint);if(X.dropConstraint)this.visitNode(X.dropConstraint);if(X.renameConstraint)this.visitNode(X.renameConstraint);if(X.columnAlterations)this.compileColumnAlterations(X.columnAlterations);if(X.addIndex)this.visitNode(X.addIndex);if(X.dropIndex)this.visitNode(X.dropIndex)}visitAddColumn(X){this.append("add column "),this.visitNode(X.column)}visitRenameColumn(X){this.append("rename column "),this.visitNode(X.column),this.append(" to "),this.visitNode(X.renameTo)}visitDropColumn(X){this.append("drop column "),this.visitNode(X.column)}visitAlterColumn(X){if(this.append("alter column "),this.visitNode(X.column),this.append(" "),X.dataType){if(this.announcesNewColumnDataType())this.append("type ");if(this.visitNode(X.dataType),X.dataTypeExpression)this.append("using "),this.visitNode(X.dataTypeExpression)}if(X.setDefault)this.append("set default "),this.visitNode(X.setDefault);if(X.dropDefault)this.append("drop default");if(X.setNotNull)this.append("set not null");if(X.dropNotNull)this.append("drop not null")}visitModifyColumn(X){this.append("modify column "),this.visitNode(X.column)}visitAddConstraint(X){this.append("add "),this.visitNode(X.constraint)}visitDropConstraint(X){if(this.append("drop constraint "),X.ifExists)this.append("if exists ");if(this.visitNode(X.constraintName),X.modifier==="cascade")this.append(" cascade");else if(X.modifier==="restrict")this.append(" restrict")}visitRenameConstraint(X){this.append("rename constraint "),this.visitNode(X.oldName),this.append(" to "),this.visitNode(X.newName)}visitSetOperation(X){if(this.append(X.operator),this.append(" "),X.all)this.append("all ");this.visitNode(X.expression)}visitCreateView(X){if(this.append("create "),X.orReplace)this.append("or replace ");if(X.materialized)this.append("materialized ");if(X.temporary)this.append("temporary ");if(this.append("view "),X.ifNotExists)this.append("if not exists ");if(this.visitNode(X.name),this.append(" "),X.columns)this.append("("),this.compileList(X.columns),this.append(") ");if(X.as)this.append("as "),this.visitNode(X.as)}visitRefreshMaterializedView(X){if(this.append("refresh materialized view "),X.concurrently)this.append("concurrently ");if(this.visitNode(X.name),X.withNoData)this.append(" with no data");else this.append(" with data")}visitDropView(X){if(this.append("drop "),X.materialized)this.append("materialized ");if(this.append("view "),X.ifExists)this.append("if exists ");if(this.visitNode(X.name),X.cascade)this.append(" cascade")}visitGenerated(X){if(this.append("generated "),X.always)this.append("always ");if(X.byDefault)this.append("by default ");if(this.append("as "),X.identity)this.append("identity");if(X.expression)this.append("("),this.visitNode(X.expression),this.append(")");if(X.stored)this.append(" stored")}visitDefaultValue(X){this.append("default "),this.visitNode(X.defaultValue)}visitSelectModifier(X){if(X.rawModifier)this.visitNode(X.rawModifier);else this.append(cO8[X.modifier]);if(X.of)this.append(" of "),this.compileList(X.of,", ")}visitCreateType(X){if(this.append("create type "),this.visitNode(X.name),X.enum)this.append(" as enum "),this.visitNode(X.enum)}visitDropType(X){if(this.append("drop type "),X.ifExists)this.append("if exists ");this.visitNode(X.name)}visitExplain(X){if(this.append("explain"),X.options||X.format){if(this.append(" "),this.append(this.getLeftExplainOptionsWrapper()),X.options){if(this.visitNode(X.options),X.format)this.append(this.getExplainOptionsDelimiter())}if(X.format)this.append("format"),this.append(this.getExplainOptionAssignment()),this.append(X.format);this.append(this.getRightExplainOptionsWrapper())}}visitDefaultInsertValue(X){this.append("default")}visitAggregateFunction(X){if(this.append(X.func),this.append("("),X.distinct)this.append("distinct ");if(this.compileList(X.aggregated),X.orderBy)this.append(" "),this.visitNode(X.orderBy);if(this.append(")"),X.withinGroup)this.append(" within group ("),this.visitNode(X.withinGroup),this.append(")");if(X.filter)this.append(" filter("),this.visitNode(X.filter),this.append(")");if(X.over)this.append(" "),this.visitNode(X.over)}visitOver(X){if(this.append("over("),X.partitionBy){if(this.visitNode(X.partitionBy),X.orderBy)this.append(" ")}if(X.orderBy)this.visitNode(X.orderBy);this.append(")")}visitPartitionBy(X){this.append("partition by "),this.compileList(X.items)}visitPartitionByItem(X){this.visitNode(X.partitionBy)}visitBinaryOperation(X){this.visitNode(X.leftOperand),this.append(" "),this.visitNode(X.operator),this.append(" "),this.visitNode(X.rightOperand)}visitUnaryOperation(X){if(this.visitNode(X.operator),!this.isMinusOperator(X.operator))this.append(" ");this.visitNode(X.operand)}isMinusOperator(X){return PZ.is(X)&&X.operator==="-"}visitUsing(X){this.append("using "),this.compileList(X.tables)}visitFunction(X){this.append(X.func),this.append("("),this.compileList(X.arguments),this.append(")")}visitCase(X){if(this.append("case"),X.value)this.append(" "),this.visitNode(X.value);if(X.when)this.append(" "),this.compileList(X.when," ");if(X.else)this.append(" else "),this.visitNode(X.else);if(this.append(" end"),X.isStatement)this.append(" case")}visitWhen(X){if(this.append("when "),this.visitNode(X.condition),X.result)this.append(" then "),this.visitNode(X.result)}visitJSONReference(X){this.visitNode(X.reference),this.visitNode(X.traversal)}visitJSONPath(X){if(X.inOperator)this.visitNode(X.inOperator);this.append("'$");for(let Y of X.pathLegs)this.visitNode(Y);this.append("'")}visitJSONPathLeg(X){let Y=X.type==="ArrayLocation";if(this.append(Y?"[":"."),this.append(typeof X.value==="string"?this.sanitizeStringLiteral(X.value):String(X.value)),Y)this.append("]")}visitJSONOperatorChain(X){for(let Y=0,G=X.values.length;Y<G;Y++){if(Y===G-1)this.visitNode(X.operator);else this.append("->");this.visitNode(X.values[Y])}}visitMergeQuery(X){if(X.with)this.visitNode(X.with),this.append(" ");if(this.append("merge "),X.top)this.visitNode(X.top),this.append(" ");if(this.append("into "),this.visitNode(X.into),X.using)this.append(" "),this.visitNode(X.using);if(X.whens)this.append(" "),this.compileList(X.whens," ");if(X.returning)this.append(" "),this.visitNode(X.returning);if(X.output)this.append(" "),this.visitNode(X.output);if(X.endModifiers?.length)this.append(" "),this.compileList(X.endModifiers," ")}visitMatched(X){if(X.not)this.append("not ");if(this.append("matched"),X.bySource)this.append(" by source")}visitAddIndex(X){if(this.append("add "),X.unique)this.append("unique ");if(this.append("index "),this.visitNode(X.name),X.columns)this.append(" ("),this.compileList(X.columns),this.append(")");if(X.using)this.append(" using "),this.visitNode(X.using)}visitCast(X){this.append("cast("),this.visitNode(X.expression),this.append(" as "),this.visitNode(X.dataType),this.append(")")}visitFetch(X){this.append("fetch next "),this.visitNode(X.rowCount),this.append(` rows ${X.modifier}`)}visitOutput(X){this.append("output "),this.compileList(X.selections)}visitTop(X){if(this.append(`top(${X.expression})`),X.modifiers)this.append(` ${X.modifiers}`)}visitOrAction(X){this.append(X.action)}visitCollate(X){this.append("collate "),this.visitNode(X.collation)}append(X){this.#X+=X}appendValue(X){this.addParameter(X),this.append(this.getCurrentParameterPlaceholder())}getLeftIdentifierWrapper(){return'"'}getRightIdentifierWrapper(){return'"'}getCurrentParameterPlaceholder(){return"$"+this.numParameters}getLeftExplainOptionsWrapper(){return"("}getExplainOptionAssignment(){return" "}getExplainOptionsDelimiter(){return", "}getRightExplainOptionsWrapper(){return")"}sanitizeIdentifier(X){let Y=this.getLeftIdentifierWrapper(),G=this.getRightIdentifierWrapper(),Q="";for(let J of X)if(Q+=J,J===Y)Q+=Y;else if(J===G)Q+=G;return Q}sanitizeStringLiteral(X){return X.replace(dO8,"''")}addParameter(X){this.#Y.push(X)}appendImmediateValue(X){if(H9(X))this.appendStringLiteral(X);else if(QF(X)||UO(X)||cL(X))this.append(X.toString());else if(dL(X))this.append("null");else if(qd(X))this.appendImmediateValue(X.toISOString());else throw Error(`invalid immediate value ${X}`)}appendStringLiteral(X){this.append("'"),this.append(this.sanitizeStringLiteral(X)),this.append("'")}sortSelectModifiers(X){return X.sort((Y,G)=>Y.modifier&&G.modifier?vm0[Y.modifier]-vm0[G.modifier]:1),n(X)}compileColumnAlterations(X){this.compileList(X)}announcesNewColumnDataType(){return!0}};cO8=n({ForKeyShare:"for key share",ForNoKeyUpdate:"for no key update",ForUpdate:"for update",ForShare:"for share",NoWait:"nowait",SkipLocked:"skip locked",Distinct:"distinct"}),vm0=n({ForKeyShare:1,ForNoKeyUpdate:1,ForUpdate:1,ForShare:1,NoWait:2,SkipLocked:2,Distinct:0}),iO8=n({InnerJoin:"inner join",LeftJoin:"left join",RightJoin:"right join",FullJoin:"full join",CrossJoin:"cross join",LateralInnerJoin:"inner join lateral",LateralLeftJoin:"left join lateral",LateralCrossJoin:"cross join lateral",OuterApply:"outer apply",CrossApply:"cross apply",Using:"using"})});var B9;var Jc=D(()=>{EK();W0();AN();B9=n({raw(X,Y=[]){return n({sql:X,query:f5.createWithSql(X),parameters:n(Y),queryId:e4()})}})});var _m0=()=>{};var fm0=()=>{};var bm0=()=>{};var ym0=()=>{};class IO{get supportsCreateIfNotExists(){return!0}get supportsTransactionalDdl(){return!1}get supportsReturning(){return!1}get supportsOutput(){return!1}}var xm0=()=>{};function TK(X,Y){return f5.createWithChildren([f5.createWithSql(`${X} `),k4.create(Y)])}var xK1=D(()=>{U7();EK()});class tt1{#X;#Y=new gm0;#G;#Q;constructor(X){this.#X=n({...X})}async init(){if(this.#G=F9(this.#X.database)?await this.#X.database():this.#X.database,this.#Q=new hm0(this.#G),this.#X.onCreateConnection)await this.#X.onCreateConnection(this.#Q)}async acquireConnection(){return await this.#Y.lock(),this.#Q}async beginTransaction(X){await X.executeQuery(B9.raw("begin"))}async commitTransaction(X){await X.executeQuery(B9.raw("commit"))}async rollbackTransaction(X){await X.executeQuery(B9.raw("rollback"))}async savepoint(X,Y,G){await X.executeQuery(G(TK("savepoint",Y),e4()))}async rollbackToSavepoint(X,Y,G){await X.executeQuery(G(TK("rollback to",Y),e4()))}async releaseSavepoint(X,Y,G){await X.executeQuery(G(TK("release",Y),e4()))}async releaseConnection(){this.#Y.unlock()}async destroy(){this.#G?.close()}}class hm0{#X;constructor(X){this.#X=X}executeQuery(X){let{sql:Y,parameters:G}=X,Q=this.#X.prepare(Y);if(Q.reader)return Promise.resolve({rows:Q.all(G)});let{changes:J,lastInsertRowid:W}=Q.run(G);return Promise.resolve({numAffectedRows:J!==void 0&&J!==null?BigInt(J):void 0,insertId:W!==void 0&&W!==null?BigInt(W):void 0,rows:[]})}async*streamQuery(X,Y){let{sql:G,parameters:Q,query:J}=X,W=this.#X.prepare(G);if(U9.is(J)){let Z=W.iterate(Q);for(let $ of Z)yield{rows:[$]}}else throw Error("Sqlite driver only supports streaming of select queries")}}class gm0{#X;#Y;async lock(){while(this.#X)await this.#X;this.#X=new Promise((X)=>{this.#Y=X})}unlock(){let X=this.#Y;this.#X=void 0,this.#Y=void 0,X?.()}}var rt1=D(()=>{YI();xK1();Jc();W0();AN()});var pO8,ot1;var st1=D(()=>{NI();pO8=/"/g;ot1=class ot1 extends EQ{visitOrAction(X){this.append("or "),this.append(X.action)}getCurrentParameterPlaceholder(){return"?"}getLeftExplainOptionsWrapper(){return""}getRightExplainOptionsWrapper(){return""}getLeftIdentifierWrapper(){return'"'}getRightIdentifierWrapper(){return'"'}getAutoIncrement(){return"autoincrement"}sanitizeIdentifier(X){return X.replace(pO8,'""')}visitDefaultInsertValue(X){this.append("null")}}});class et1{transformQuery(X){return X.node}async transformResult(X){return X.result}}class gK1{#X;constructor(X){this.#X=n(X)}async getMigrations(){let Y=await this.#F(this.#Q)?await this.#X.db.withPlugin(this.#$).selectFrom(this.#Q).select(["name","timestamp"]).$narrowType().execute():[];return(await this.#O()).map(({name:Q,...J})=>{let W=Y.find((Z)=>Z.name===Q);return{name:Q,migration:J,executedAt:W?new Date(W.timestamp):void 0}})}async migrateToLatest(){return this.#Y(()=>({direction:"Up",step:1/0}))}async migrateTo(X){return this.#Y(({migrations:Y,executedMigrations:G,pendingMigrations:Q})=>{if(F7(X)&&X.__noMigrations__===!0)return{direction:"Down",step:1/0};if(!Y.find((Z)=>Z.name===X))throw Error(`migration "${X}" doesn't exist`);let J=G.indexOf(X),W=Q.findIndex((Z)=>Z.name===X);if(J!==-1)return{direction:"Down",step:G.length-J-1};else if(W!==-1)return{direction:"Up",step:W+1};else throw Error(`migration "${X}" isn't executed or pending`)})}async migrateUp(){return this.#Y(()=>({direction:"Up",step:1}))}async migrateDown(){return this.#Y(()=>({direction:"Down",step:1}))}async#Y(X){try{return await this.#W(),await this.#K(),await this.#H(),await this.#U(),await this.#D(X)}catch(Y){if(Y instanceof hK1)return Y.resultSet;return{error:Y}}}get#G(){return this.#X.migrationTableSchema}get#Q(){return this.#X.migrationTableName??eY}get#J(){return this.#X.migrationLockTableName??RG}get#Z(){return this.#X.allowUnorderedMigrations??nO8}get#$(){if(this.#G)return new eW(this.#G);return new et1}async#W(){if(!this.#G)return;if(await this.#N())return;try{await this.#B(this.#X.db.schema.createSchema(this.#G))}catch(Y){if(!await this.#N())throw Y}}async#K(){if(await this.#F(this.#Q))return;try{await this.#B(this.#X.db.schema.withPlugin(this.#$).createTable(this.#Q).addColumn("name","varchar(255)",(Y)=>Y.notNull().primaryKey()).addColumn("timestamp","varchar(255)",(Y)=>Y.notNull()))}catch(Y){if(!await this.#F(this.#Q))throw Y}}async#H(){if(await this.#F(this.#J))return;try{await this.#B(this.#X.db.schema.withPlugin(this.#$).createTable(this.#J).addColumn("id","varchar(255)",(Y)=>Y.notNull().primaryKey()).addColumn("is_locked","integer",(Y)=>Y.notNull().defaultTo(0)))}catch(Y){if(!await this.#F(this.#J))throw Y}}async#U(){if(await this.#z())return;try{await this.#X.db.withPlugin(this.#$).insertInto(this.#J).values({id:Xr1,is_locked:0}).execute()}catch(Y){if(!await this.#z())throw Y}}async#N(){return(await this.#X.db.introspection.getSchemas()).some((Y)=>Y.name===this.#G)}async#F(X){let Y=this.#G;return(await this.#X.db.introspection.getTables({withInternalKyselyTables:!0})).some((Q)=>Q.name===X&&(!Y||Q.schema===Y))}async#z(){return!!await this.#X.db.withPlugin(this.#$).selectFrom(this.#J).where("id","=",Xr1).select("id").executeTakeFirst()}async#D(X){let Y=this.#X.db.getExecutor().adapter,G=n({lockTable:this.#X.migrationLockTableName??RG,lockRowId:Xr1,lockTableSchema:this.#X.migrationTableSchema}),Q=async(J)=>{try{await Y.acquireMigrationLock(J,G);let W=await this.#w(J);if(W.migrations.length===0)return{results:[]};let{direction:Z,step:$}=X(W);if($<=0)return{results:[]};if(Z==="Down")return await this.#A(J,W,$);else if(Z==="Up")return await this.#T(J,W,$);return{results:[]}}finally{await Y.releaseMigrationLock(J,G)}};if(Y.supportsTransactionalDdl&&!this.#X.disableTransactions)return this.#X.db.transaction().execute(Q);else return this.#X.db.connection().execute(Q)}async#w(X){let Y=await this.#O(),G=await this.#E(X);if(this.#P(Y,G),!this.#Z)this.#q(Y,G);let Q=this.#L(Y,G);return n({migrations:Y,executedMigrations:G,lastMigration:Yl0(G),pendingMigrations:Q})}#L(X,Y){return X.filter((G)=>{return!Y.includes(G.name)})}async#O(){let X=await this.#X.provider.getMigrations();return Object.keys(X).sort().map((Y)=>({...X[Y],name:Y}))}async#E(X){let Y=await X.withPlugin(this.#$).selectFrom(this.#Q).select(["name","timestamp"]).$narrowType().execute(),G=this.#X.nameComparator||((Q,J)=>Q.localeCompare(J));return Y.sort((Q,J)=>{if(Q.timestamp===J.timestamp)return G(Q.name,J.name);return new Date(Q.timestamp).getTime()-new Date(J.timestamp).getTime()}).map((Q)=>Q.name)}#P(X,Y){for(let G of Y)if(!X.some((Q)=>Q.name===G))throw Error(`corrupted migrations: previously executed migration ${G} is missing`)}#q(X,Y){for(let G=0;G<Y.length;++G)if(X[G].name!==Y[G])throw Error(`corrupted migrations: expected previously executed migration ${Y[G]} to be at index ${G} but ${X[G].name} was found in its place. New migrations must always have a name that comes alphabetically after the last executed migration.`)}async#A(X,Y,G){let Q=Y.executedMigrations.slice().reverse().slice(0,G).map((W)=>{return Y.migrations.find((Z)=>Z.name===W)}),J=Q.map((W)=>{return{migrationName:W.name,direction:"Down",status:"NotExecuted"}});for(let W=0;W<J.length;++W){let Z=Q[W];try{if(Z.down)await Z.down(X),await X.withPlugin(this.#$).deleteFrom(this.#Q).where("name","=",Z.name).execute(),J[W]={migrationName:Z.name,direction:"Down",status:"Success"}}catch($){throw J[W]={migrationName:Z.name,direction:"Down",status:"Error"},new hK1({error:$,results:J})}}return{results:J}}async#T(X,Y,G){let J=Y.pendingMigrations.slice(0,G).map((W)=>{return{migrationName:W.name,direction:"Up",status:"NotExecuted"}});for(let W=0;W<J.length;W++){let Z=Y.pendingMigrations[W];try{await Z.up(X),await X.withPlugin(this.#$).insertInto(this.#Q).values({name:Z.name,timestamp:new Date().toISOString()}).execute(),J[W]={migrationName:Z.name,direction:"Up",status:"Success"}}catch($){throw J[W]={migrationName:Z.name,direction:"Up",status:"Error"},new hK1({error:$,results:J})}}return{results:J}}async#B(X){if(this.#X.db.getExecutor().adapter.supportsCreateIfNotExists)X=X.ifNotExists();await X.execute()}}var eY="kysely_migration",RG="kysely_migration_lock",nO8=!1,Xr1="migration_lock",_I7,hK1;var BI=D(()=>{WI();W0();_I7=n({__noMigrations__:!0});hK1=class hK1 extends Error{#X;constructor(X){super();this.#X=X}get resultSet(){return this.#X}}});class Yr1{#X;constructor(X){this.#X=X}async getSchemas(){return[]}async getTables(X={withInternalKyselyTables:!1}){return await this.#G(X)}async getMetadata(X){return{tables:await this.getTables(X)}}#Y(X,Y){let G=X.selectFrom("sqlite_master").where("type","in",["table","view"]).where("name","not like","sqlite_%").select(["name","sql","type"]).orderBy("name");if(!Y.withInternalKyselyTables)G=G.where("name","!=",eY).where("name","!=",RG);return G}async#G(X){let Y=await this.#Y(this.#X,X).execute(),G=await this.#X.with("table_list",(J)=>this.#Y(J,X)).selectFrom(["table_list as tl",O1`pragma_table_info(tl.name)`.as("p")]).select(["tl.name as table","p.cid","p.name","p.type","p.notnull","p.dflt_value","p.pk"]).orderBy("tl.name").orderBy("p.cid").execute(),Q={};for(let J of G)Q[J.table]??=[],Q[J.table].push(J);return Y.map(({name:J,sql:W,type:Z})=>{let $=W?.split(/[\(\),]/)?.find((H)=>H.toLowerCase().includes("autoincrement"))?.trimStart()?.split(/\s+/)?.[0]?.replace(/["`]/g,""),K=Q[J]??[];if(!$){let H=K.filter((U)=>U.pk>0);if(H.length===1&&H[0].type.toLowerCase()==="integer")$=H[0].name}return{name:J,isView:Z==="view",columns:K.map((H)=>({name:H.name,dataType:H.type,isNullable:!H.notnull,isAutoIncrementing:H.name===$,hasDefaultValue:H.dflt_value!=null,comment:void 0}))}})}}var Gr1=D(()=>{BI();WE()});var Qr1;var Jr1=D(()=>{Qr1=class Qr1 extends IO{get supportsTransactionalDdl(){return!1}get supportsReturning(){return!0}async acquireMigrationLock(X,Y){}async releaseMigrationLock(X,Y){}}});class zI{#X;constructor(X){this.#X=n({...X})}createDriver(){return new tt1(this.#X)}createQueryCompiler(){return new ot1}createAdapter(){return new Qr1}createIntrospector(X){return new Yr1(X)}}var um0=D(()=>{rt1();st1();Gr1();Jr1();W0()});var lm0=()=>{};var aO8,Zr1;var Wr1=D(()=>{NI();aO8=/"/g;Zr1=class Zr1 extends EQ{sanitizeIdentifier(X){return X.replace(aO8,'""')}}});class $r1{#X;constructor(X){this.#X=X}async getSchemas(){return(await this.#X.selectFrom("pg_catalog.pg_namespace").select("nspname").$castTo().execute()).map((Y)=>({name:Y.nspname}))}async getTables(X={withInternalKyselyTables:!1}){let Y=this.#X.selectFrom("pg_catalog.pg_attribute as a").innerJoin("pg_catalog.pg_class as c","a.attrelid","c.oid").innerJoin("pg_catalog.pg_namespace as ns","c.relnamespace","ns.oid").innerJoin("pg_catalog.pg_type as typ","a.atttypid","typ.oid").innerJoin("pg_catalog.pg_namespace as dtns","typ.typnamespace","dtns.oid").select(["a.attname as column","a.attnotnull as not_null","a.atthasdef as has_default","c.relname as table","c.relkind as table_type","ns.nspname as schema","typ.typname as type","dtns.nspname as type_schema",O1`col_description(a.attrelid, a.attnum)`.as("column_description"),O1`pg_get_serial_sequence(quote_ident(ns.nspname) || '.' || quote_ident(c.relname), a.attname)`.as("auto_incrementing")]).where("c.relkind","in",["r","v","p"]).where("ns.nspname","!~","^pg_").where("ns.nspname","!=","information_schema").where("ns.nspname","!=","crdb_internal").where(O1`has_schema_privilege(ns.nspname, 'USAGE')`).where("a.attnum",">=",0).where("a.attisdropped","!=",!0).orderBy("ns.nspname").orderBy("c.relname").orderBy("a.attnum").$castTo();if(!X.withInternalKyselyTables)Y=Y.where("c.relname","!=",eY).where("c.relname","!=",RG);let G=await Y.execute();return this.#Y(G)}async getMetadata(X){return{tables:await this.getTables(X)}}#Y(X){let Y=new Map;for(let G=0,Q=X.length;G<Q;G++){let J=X[G],{schema:W,table:Z}=J,$=`schema:${W};table:${Z}`;if(!Y.has($))Y.set($,n({columns:[],isView:J.table_type==="v",name:Z,schema:W}));Y.get($).columns.push(n({comment:J.column_description??void 0,dataType:J.type,dataTypeSchema:J.type_schema,hasDefaultValue:J.has_default,isAutoIncrementing:J.auto_incrementing!==null,isNullable:!J.not_null,name:J.column}))}return Array.from(Y.values())}}var Kr1=D(()=>{BI();W0();WE()});var tO8,Hr1;var Fr1=D(()=>{WE();tO8=BigInt("3853314791062309107");Hr1=class Hr1 extends IO{get supportsTransactionalDdl(){return!0}get supportsReturning(){return!0}async acquireMigrationLock(X,Y){await O1`select pg_advisory_xact_lock(${O1.lit(tO8)})`.execute(X)}async releaseMigrationLock(X,Y){}}});function Zc(X,Y){if(rO8(X)&&Y.stack){let G=Y.stack.split(`
|
|
113
113
|
`).slice(1).join(`
|
|
114
114
|
`);return X.stack+=`
|
|
115
115
|
${G}`,X}return X}function rO8(X){return F7(X)&&H9(X.stack)}var uK1=D(()=>{W0()});class Ur1{#X;#Y=new WeakMap;#G;constructor(X){this.#X=n({...X})}async init(){this.#G=F9(this.#X.pool)?await this.#X.pool():this.#X.pool}async acquireConnection(){let X=await this.#Q(),Y=this.#Y.get(X);if(!Y){if(Y=new dm0(X),this.#Y.set(X,Y),this.#X?.onCreateConnection)await this.#X.onCreateConnection(Y)}if(this.#X?.onReserveConnection)await this.#X.onReserveConnection(Y);return Y}async#Q(){return new Promise((X,Y)=>{this.#G.getConnection(async(G,Q)=>{if(G)Y(G);else X(Q)})})}async beginTransaction(X,Y){if(Y.isolationLevel||Y.accessMode){let G=[];if(Y.isolationLevel)G.push(`isolation level ${Y.isolationLevel}`);if(Y.accessMode)G.push(Y.accessMode);let Q=`set transaction ${G.join(", ")}`;await X.executeQuery(B9.raw(Q))}await X.executeQuery(B9.raw("begin"))}async commitTransaction(X){await X.executeQuery(B9.raw("commit"))}async rollbackTransaction(X){await X.executeQuery(B9.raw("rollback"))}async savepoint(X,Y,G){await X.executeQuery(G(TK("savepoint",Y),e4()))}async rollbackToSavepoint(X,Y,G){await X.executeQuery(G(TK("rollback to",Y),e4()))}async releaseSavepoint(X,Y,G){await X.executeQuery(G(TK("release savepoint",Y),e4()))}async releaseConnection(X){X[mm0]()}async destroy(){return new Promise((X,Y)=>{this.#G.end((G)=>{if(G)Y(G);else X()})})}}function oO8(X){return F7(X)&&"insertId"in X&&"affectedRows"in X}var mm0,dm0;var Nr1=D(()=>{xK1();Jc();W0();AN();uK1();mm0=Symbol();dm0=class dm0{#X;constructor(X){this.#X=X}async executeQuery(X){try{let Y=await this.#Y(X);if(oO8(Y)){let{insertId:G,affectedRows:Q,changedRows:J}=Y;return{insertId:G!==void 0&&G!==null&&G.toString()!=="0"?BigInt(G):void 0,numAffectedRows:Q!==void 0&&Q!==null?BigInt(Q):void 0,numChangedRows:J!==void 0&&J!==null?BigInt(J):void 0,rows:[]}}else if(Array.isArray(Y))return{rows:Y};return{rows:[]}}catch(Y){throw Zc(Y,Error())}}#Y(X){return new Promise((Y,G)=>{this.#X.query(X.sql,X.parameters,(Q,J)=>{if(Q)G(Q);else Y(J)})})}async*streamQuery(X,Y){let G=this.#X.query(X.sql,X.parameters).stream({objectMode:!0});try{for await(let Q of G)yield{rows:[Q]}}catch(Q){if(Q&&typeof Q==="object"&&"code"in Q&&Q.code==="ERR_STREAM_PREMATURE_CLOSE")return;throw Q}}[mm0](){this.#X.release()}}});var sO8,Br1,zr1;var Or1=D(()=>{NI();sO8=/\\|'/g,Br1=/`/g;zr1=class zr1 extends EQ{getCurrentParameterPlaceholder(){return"?"}getLeftExplainOptionsWrapper(){return""}getExplainOptionAssignment(){return"="}getExplainOptionsDelimiter(){return" "}getRightExplainOptionsWrapper(){return""}getLeftIdentifierWrapper(){return Br1.source}getRightIdentifierWrapper(){return Br1.source}sanitizeIdentifier(X){return X.replace(Br1,"``")}sanitizeStringLiteral(X){return X.replace(sO8,(Y)=>Y==="\\"?"\\\\":"''")}visitCreateIndex(X){if(this.append("create "),X.unique)this.append("unique ");if(this.append("index "),X.ifNotExists)this.append("if not exists ");if(this.visitNode(X.name),X.using)this.append(" using "),this.visitNode(X.using);if(X.table)this.append(" on "),this.visitNode(X.table);if(X.columns)this.append(" ("),this.compileList(X.columns),this.append(")");if(X.where)this.append(" "),this.visitNode(X.where)}}});class Dr1{#X;constructor(X){this.#X=X}async getSchemas(){return(await this.#X.selectFrom("information_schema.schemata").select("schema_name").$castTo().execute()).map((Y)=>({name:Y.SCHEMA_NAME}))}async getTables(X={withInternalKyselyTables:!1}){let Y=this.#X.selectFrom("information_schema.columns as columns").innerJoin("information_schema.tables as tables",(Q)=>Q.onRef("columns.TABLE_CATALOG","=","tables.TABLE_CATALOG").onRef("columns.TABLE_SCHEMA","=","tables.TABLE_SCHEMA").onRef("columns.TABLE_NAME","=","tables.TABLE_NAME")).select(["columns.COLUMN_NAME","columns.COLUMN_DEFAULT","columns.TABLE_NAME","columns.TABLE_SCHEMA","tables.TABLE_TYPE","columns.IS_NULLABLE","columns.DATA_TYPE","columns.EXTRA","columns.COLUMN_COMMENT"]).where("columns.TABLE_SCHEMA","=",O1`database()`).orderBy("columns.TABLE_NAME").orderBy("columns.ORDINAL_POSITION").$castTo();if(!X.withInternalKyselyTables)Y=Y.where("columns.TABLE_NAME","!=",eY).where("columns.TABLE_NAME","!=",RG);let G=await Y.execute();return this.#Y(G)}async getMetadata(X){return{tables:await this.getTables(X)}}#Y(X){return X.reduce((Y,G)=>{let Q=Y.find((J)=>J.name===G.TABLE_NAME);if(!Q)Q=n({name:G.TABLE_NAME,isView:G.TABLE_TYPE==="VIEW",schema:G.TABLE_SCHEMA,columns:[]}),Y.push(Q);return Q.columns.push(n({name:G.COLUMN_NAME,dataType:G.DATA_TYPE,isNullable:G.IS_NULLABLE==="YES",isAutoIncrementing:G.EXTRA.toLowerCase().includes("auto_increment"),hasDefaultValue:G.COLUMN_DEFAULT!==null,comment:G.COLUMN_COMMENT===""?void 0:G.COLUMN_COMMENT})),Y},[])}}var wr1=D(()=>{BI();W0();WE()});var cm0="ea586330-2c93-47c8-908d-981d9d270f9d",eO8=3600,Lr1;var Er1=D(()=>{WE();Lr1=class Lr1 extends IO{get supportsTransactionalDdl(){return!1}get supportsReturning(){return!1}async acquireMigrationLock(X,Y){await O1`select get_lock(${O1.lit(cm0)}, ${O1.lit(eO8)})`.execute(X)}async releaseMigrationLock(X,Y){await O1`select release_lock(${O1.lit(cm0)})`.execute(X)}}});class OI{#X;constructor(X){this.#X=X}createDriver(){return new Ur1(this.#X)}createQueryCompiler(){return new zr1}createAdapter(){return new Lr1}createIntrospector(X){return new Dr1(X)}}var im0=D(()=>{Nr1();Or1();wr1();Er1()});var pm0=()=>{};class Pr1{#X;#Y=new WeakMap;#G;constructor(X){this.#X=n({...X})}async init(){this.#G=F9(this.#X.pool)?await this.#X.pool():this.#X.pool}async acquireConnection(){let X=await this.#G.connect(),Y=this.#Y.get(X);if(!Y){if(Y=new am0(X,{cursor:this.#X.cursor??null}),this.#Y.set(X,Y),this.#X.onCreateConnection)await this.#X.onCreateConnection(Y)}if(this.#X.onReserveConnection)await this.#X.onReserveConnection(Y);return Y}async beginTransaction(X,Y){if(Y.isolationLevel||Y.accessMode){let G="start transaction";if(Y.isolationLevel)G+=` isolation level ${Y.isolationLevel}`;if(Y.accessMode)G+=` ${Y.accessMode}`;await X.executeQuery(B9.raw(G))}else await X.executeQuery(B9.raw("begin"))}async commitTransaction(X){await X.executeQuery(B9.raw("commit"))}async rollbackTransaction(X){await X.executeQuery(B9.raw("rollback"))}async savepoint(X,Y,G){await X.executeQuery(G(TK("savepoint",Y),e4()))}async rollbackToSavepoint(X,Y,G){await X.executeQuery(G(TK("rollback to",Y),e4()))}async releaseSavepoint(X,Y,G){await X.executeQuery(G(TK("release",Y),e4()))}async releaseConnection(X){X[nm0]()}async destroy(){if(this.#G){let X=this.#G;this.#G=void 0,await X.end()}}}var nm0,am0;var qr1=D(()=>{xK1();Jc();W0();AN();uK1();nm0=Symbol();am0=class am0{#X;#Y;constructor(X,Y){this.#X=X,this.#Y=Y}async executeQuery(X){try{let{command:Y,rowCount:G,rows:Q}=await this.#X.query(X.sql,[...X.parameters]);return{numAffectedRows:Y==="INSERT"||Y==="UPDATE"||Y==="DELETE"||Y==="MERGE"?BigInt(G):void 0,rows:Q??[]}}catch(Y){throw Zc(Y,Error())}}async*streamQuery(X,Y){if(!this.#Y.cursor)throw Error("'cursor' is not present in your postgres dialect config. It's required to make streaming work in postgres.");if(!Number.isInteger(Y)||Y<=0)throw Error("chunkSize must be a positive integer");let G=this.#X.query(new this.#Y.cursor(X.sql,X.parameters.slice()));try{while(!0){let Q=await G.read(Y);if(Q.length===0)break;yield{rows:Q}}}finally{await G.close()}}[nm0](){this.#X.release()}}});var tm0=()=>{};class MN{#X;constructor(X){this.#X=X}createDriver(){return new Pr1(this.#X)}createQueryCompiler(){return new Zr1}createAdapter(){return new Hr1}createIntrospector(X){return new $r1(X)}}var rm0=D(()=>{qr1();Kr1();Wr1();Fr1()});var Ar1;var Tr1=D(()=>{BI();WE();Ar1=class Ar1 extends IO{get supportsCreateIfNotExists(){return!1}get supportsTransactionalDdl(){return!0}get supportsOutput(){return!0}async acquireMigrationLock(X){await O1`exec sp_getapplock @DbPrincipal = ${O1.lit("dbo")}, @Resource = ${O1.lit(eY)}, @LockMode = ${O1.lit("Exclusive")}`.execute(X)}async releaseMigrationLock(){}}});var om0=()=>{};class Ir1{#X;#Y;constructor(X){this.#X=n({...X});let{tarn:Y,tedious:G,validateConnections:Q}=this.#X,{validateConnections:J,...W}=Y.options;this.#Y=new Y.Pool({...W,create:async()=>{let Z=await G.connectionFactory();return await new Yd0(Z,G).connect()},destroy:async(Z)=>{await Z[em0]()},validate:Q===!1||J===!1?void 0:(Z)=>Z[Xd0]()})}async init(){}async acquireConnection(){return await this.#Y.acquire().promise}async beginTransaction(X,Y){await X.beginTransaction(Y)}async commitTransaction(X){await X.commitTransaction()}async rollbackTransaction(X){await X.rollbackTransaction()}async savepoint(X,Y){await X.savepoint(Y)}async rollbackToSavepoint(X,Y){await X.rollbackTransaction(Y)}async releaseConnection(X){if(this.#X.resetConnectionsOnRelease||this.#X.tedious.resetConnectionOnRelease)await X[sm0]();this.#Y.release(X)}async destroy(){await this.#Y.destroy()}}class lK1{#X;#Y;#G;#Q;#J;#Z;constructor(X){let{compiledQuery:Y,onDone:G,streamChunkSize:Q,tedious:J}=X;if(this.#Y=[],this.#G=Q,this.#Q={},this.#J=J,G)this.#Q.onDone=(Z,$)=>{if(Z==="chunkReady")return;if(delete this.#Q.onDone,Z==="error")return G.reject($);G.resolve({rowCount:this.#Z,rows:this.#Y})};this.#X=new this.#J.Request(Y.sql,(W,Z)=>{if(W)return Object.values(this.#Q).forEach(($)=>$("error",W instanceof AggregateError?W.errors:W));this.#Z=Z}),this.#$(Y.parameters),this.#W()}get request(){return this.#X}readChunk(){let X=this.readChunk.name;return new Promise((Y,G)=>{this.#Q[X]=(Q,J)=>{if(delete this.#Q[X],Q==="error")return G(J);Y(this.#Y.splice(0,this.#G))},this.#X.resume()})}#$(X){for(let Y=0;Y<X.length;Y++){let G=X[Y];this.#X.addParameter(String(Y+1),this.#K(G),G)}}#W(){let X=this.#G?()=>{if(this.#G<=this.#Y.length)this.#X.pause(),Object.values(this.#Q).forEach((G)=>G("chunkReady"))}:()=>{},Y=(G)=>{let Q={};for(let J of G)Q[J.metadata.colName]=J.value;this.#Y.push(Q),X()};this.#X.on("row",Y),this.#X.once("requestCompleted",()=>{Object.values(this.#Q).forEach((G)=>G("completed")),this.#X.off("row",Y)})}#K(X){if(dL(X)||LZ(X)||H9(X))return this.#J.TYPES.NVarChar;if(cL(X)||QF(X)&&X%1===0)if(X<-2147483648||X>2147483647)return this.#J.TYPES.BigInt;else return this.#J.TYPES.Int;if(QF(X))return this.#J.TYPES.Float;if(UO(X))return this.#J.TYPES.Bit;if(qd(X))return this.#J.TYPES.DateTime;if(V$1(X))return this.#J.TYPES.VarBinary;return this.#J.TYPES.NVarChar}}var sm0,em0,Xd0,Yd0;var Vr1=D(()=>{W0();Jc();uK1();Sa1();sm0=Symbol(),em0=Symbol(),Xd0=Symbol();Yd0=class Yd0{#X;#Y;#G;constructor(X,Y){this.#X=X,this.#Y=!1,this.#G=Y}async beginTransaction(X){let{isolationLevel:Y}=X;await new Promise((G,Q)=>this.#X.beginTransaction((J)=>{if(J)Q(J);else G(void 0)},Y?QK1(8):void 0,Y?this.#Q(Y):void 0))}async commitTransaction(){await new Promise((X,Y)=>this.#X.commitTransaction((G)=>{if(G)Y(G);else X(void 0)}))}async connect(){let{promise:X,reject:Y,resolve:G}=new XE;this.#X.connect((J)=>{if(J)return Y(J);G()}),this.#X.on("error",(J)=>{if(J instanceof Error&&"code"in J&&J.code==="ESOCKET")this.#Y=!0;console.error(J),Y(J)});function Q(){Y(Error("The connection ended without ever completing the connection"))}return this.#X.once("end",Q),await X,this.#X.off("end",Q),this}async executeQuery(X){try{let Y=new XE,G=new lK1({compiledQuery:X,tedious:this.#G,onDone:Y});this.#X.execSql(G.request);let{rowCount:Q,rows:J}=await Y.promise;return{numAffectedRows:Q!==void 0?BigInt(Q):void 0,rows:J}}catch(Y){throw Zc(Y,Error())}}async rollbackTransaction(X){await new Promise((Y,G)=>this.#X.rollbackTransaction((Q)=>{if(Q)G(Q);else Y(void 0)},X))}async savepoint(X){await new Promise((Y,G)=>this.#X.saveTransaction((Q)=>{if(Q)G(Q);else Y(void 0)},X))}async*streamQuery(X,Y){if(!Number.isInteger(Y)||Y<=0)throw Error("chunkSize must be a positive integer");let G=new lK1({compiledQuery:X,streamChunkSize:Y,tedious:this.#G});this.#X.execSql(G.request);try{while(!0){let Q=await G.readChunk();if(Q.length===0)break;if(yield{rows:Q},Q.length<Y)break}}finally{await this.#J(G)}}#Q(X){let{ISOLATION_LEVEL:Y}=this.#G,Q={"read committed":Y.READ_COMMITTED,"read uncommitted":Y.READ_UNCOMMITTED,"repeatable read":Y.REPEATABLE_READ,serializable:Y.SERIALIZABLE,snapshot:Y.SNAPSHOT}[X];if(Q===void 0)throw Error(`Unknown isolation level: ${X}`);return Q}#J(X){return new Promise((Y)=>{if(X.request.once("requestCompleted",Y),!this.#X.cancel())X.request.off("requestCompleted",Y),Y()})}[em0](){if("closed"in this.#X&&this.#X.closed)return Promise.resolve();return new Promise((X)=>{this.#X.once("end",X),this.#X.close()})}async[sm0](){await new Promise((X,Y)=>{this.#X.reset((G)=>{if(G)return Y(G);X()})})}async[Xd0](){if(this.#Y||this.#Z())return!1;try{let X=new XE,Y=new lK1({compiledQuery:B9.raw("select 1"),onDone:X,tedious:this.#G});return this.#X.execSql(Y.request),await X.promise,!0}catch{return!1}}#Z(){return"closed"in this.#X&&Boolean(this.#X.closed)}}});class jr1{#X;constructor(X){this.#X=X}async getSchemas(){return await this.#X.selectFrom("sys.schemas").select("name").execute()}async getTables(X={withInternalKyselyTables:!1}){let Y=await this.#X.selectFrom("sys.tables as tables").leftJoin("sys.schemas as table_schemas","table_schemas.schema_id","tables.schema_id").innerJoin("sys.columns as columns","columns.object_id","tables.object_id").innerJoin("sys.types as types","types.user_type_id","columns.user_type_id").leftJoin("sys.schemas as type_schemas","type_schemas.schema_id","types.schema_id").leftJoin("sys.extended_properties as comments",(Q)=>Q.onRef("comments.major_id","=","tables.object_id").onRef("comments.minor_id","=","columns.column_id").on("comments.name","=","MS_Description")).$if(!X.withInternalKyselyTables,(Q)=>Q.where("tables.name","!=",eY).where("tables.name","!=",RG)).select(["tables.name as table_name",(Q)=>Q.ref("tables.type").$castTo().as("table_type"),"table_schemas.name as table_schema_name","columns.default_object_id as column_default_object_id","columns.generated_always_type_desc as column_generated_always_type","columns.is_computed as column_is_computed","columns.is_identity as column_is_identity","columns.is_nullable as column_is_nullable","columns.is_rowguidcol as column_is_rowguidcol","columns.name as column_name","types.is_nullable as type_is_nullable","types.name as type_name","type_schemas.name as type_schema_name","comments.value as column_comment"]).unionAll(this.#X.selectFrom("sys.views as views").leftJoin("sys.schemas as view_schemas","view_schemas.schema_id","views.schema_id").innerJoin("sys.columns as columns","columns.object_id","views.object_id").innerJoin("sys.types as types","types.user_type_id","columns.user_type_id").leftJoin("sys.schemas as type_schemas","type_schemas.schema_id","types.schema_id").leftJoin("sys.extended_properties as comments",(Q)=>Q.onRef("comments.major_id","=","views.object_id").onRef("comments.minor_id","=","columns.column_id").on("comments.name","=","MS_Description")).select(["views.name as table_name","views.type as table_type","view_schemas.name as table_schema_name","columns.default_object_id as column_default_object_id","columns.generated_always_type_desc as column_generated_always_type","columns.is_computed as column_is_computed","columns.is_identity as column_is_identity","columns.is_nullable as column_is_nullable","columns.is_rowguidcol as column_is_rowguidcol","columns.name as column_name","types.is_nullable as type_is_nullable","types.name as type_name","type_schemas.name as type_schema_name","comments.value as column_comment"])).orderBy("table_schema_name").orderBy("table_name").orderBy("column_name").execute(),G={};for(let Q of Y){let J=`${Q.table_schema_name}.${Q.table_name}`;(G[J]=G[J]||n({columns:[],isView:Q.table_type==="V ",name:Q.table_name,schema:Q.table_schema_name??void 0})).columns.push(n({dataType:Q.type_name,dataTypeSchema:Q.type_schema_name??void 0,hasDefaultValue:Q.column_default_object_id>0||Q.column_generated_always_type!=="NOT_APPLICABLE"||Q.column_is_identity||Q.column_is_computed||Q.column_is_rowguidcol,isAutoIncrementing:Q.column_is_identity,isNullable:Q.column_is_nullable&&Q.type_is_nullable,name:Q.column_name,comment:Q.column_comment??void 0}))}return Object.values(G)}async getMetadata(X){return{tables:await this.getTables(X)}}}var Mr1=D(()=>{BI();W0()});var XD8,Rr1;var Sr1=D(()=>{NI();XD8=/^[a-z0-9_]$/i;Rr1=class Rr1 extends EQ{getCurrentParameterPlaceholder(){return`@${this.numParameters}`}visitOffset(X){super.visitOffset(X),this.append(" rows")}compileColumnAlterations(X){let Y={};for(let Q of X){if(!Y[Q.kind])Y[Q.kind]=[];Y[Q.kind].push(Q)}let G=!0;if(Y.AddColumnNode)this.append("add "),this.compileList(Y.AddColumnNode),G=!1;if(Y.AlterColumnNode){if(!G)this.append(", ");this.compileList(Y.AlterColumnNode)}if(Y.DropColumnNode){if(!G)this.append(", ");this.append("drop column "),this.compileList(Y.DropColumnNode)}if(Y.ModifyColumnNode){if(!G)this.append(", ");this.compileList(Y.ModifyColumnNode)}if(Y.RenameColumnNode){if(!G)this.append(", ");this.compileList(Y.RenameColumnNode)}}visitAddColumn(X){this.visitNode(X.column)}visitDropColumn(X){this.visitNode(X.column)}visitMergeQuery(X){super.visitMergeQuery(X),this.append(";")}visitCollate(X){this.append("collate ");let{name:Y}=X.collation;for(let G of Y)if(!XD8.test(G))throw Error(`Invalid collation: ${Y}`);this.append(Y)}announcesNewColumnDataType(){return!1}}});class j11{#X;constructor(X){this.#X=X}createDriver(){return new Ir1(this.#X)}createQueryCompiler(){return new Rr1}createAdapter(){return new Ar1}createIntrospector(X){return new jr1(X)}}var Gd0=D(()=>{Tr1();Vr1();Mr1();Sr1()});var Qd0=()=>{};class YD8{#X;constructor(X){this.#X=X}async getMigrations(){let X={},Y=await this.#X.fs.readdir(this.#X.migrationFolder);for(let G of Y)if(G.endsWith(".js")||G.endsWith(".ts")&&!G.endsWith(".d.ts")||G.endsWith(".mjs")||G.endsWith(".mts")&&!G.endsWith(".d.mts")){let Q=await import(this.#X.path.join(this.#X.migrationFolder,G)),J=G.substring(0,G.lastIndexOf("."));if(Jd0(Q?.default))X[J]=Q.default;else if(Jd0(Q))X[J]=Q}return X}}function Jd0(X){return F7(X)&&F9(X.up)}var Zd0=D(()=>{W0()});var Wd0=()=>{};var Cr1;var $d0=D(()=>{ZI();Cr1=class Cr1 extends zF{#X;constructor(X){super();this.#X=X}transformIdentifier(X,Y){return X=super.transformIdentifier(X,Y),{...X,name:this.#X(X.name)}}}});function Hd0({upperCase:X=!1,underscoreBeforeDigits:Y=!1,underscoreBetweenUppercaseLetters:G=!1}={}){return Ud0((Q)=>{if(Q.length===0)return Q;let J=Q.toUpperCase(),W=Q.toLowerCase(),Z=W[0];for(let $=1,K=Q.length;$<K;++$){let H=Q[$],U=Q[$-1],N=J[$],B=J[$-1],z=W[$],O=W[$-1];if(Y&&Kd0(H)&&!Kd0(U)&&!Z.endsWith("_")){Z+="_"+H;continue}if(H===N&&N!==z)if(G||!(U===B&&B!==O))Z+="_"+z;else Z+=z;else Z+=H}if(X)return Z.toUpperCase();else return Z})}function Fd0({upperCase:X=!1}={}){return Ud0((Y)=>{if(Y.length===0)return Y;if(X&&GD8(Y))Y=Y.toLowerCase();let G=Y[0];for(let Q=1,J=Y.length;Q<J;++Q){let W=Y[Q],Z=Y[Q-1];if(W!=="_")if(Z==="_")G+=W.toUpperCase();else G+=W}return G})}function GD8(X){for(let Y=1,G=X.length;Y<G;++Y){let Q=X[Y];if(Q!=="_"&&Q!==Q.toUpperCase())return!1}return!0}function Kd0(X){return X>="0"&&X<="9"}function Ud0(X){let Y=new Map;return(G)=>{let Q=Y.get(G);if(!Q)Q=X(G),Y.set(G,Q);return Q}}class QD8{opt;#X;#Y;#G;constructor(X={}){this.opt=X,this.#X=Fd0(X),this.#Y=Hd0(X),this.#G=new Cr1(this.snakeCase.bind(this))}transformQuery(X){return this.#G.transformNode(X.node,X.queryId)}async transformResult(X){if(X.result.rows&&Array.isArray(X.result.rows))return{...X.result,rows:X.result.rows.map((Y)=>this.mapRow(Y))};return X.result}mapRow(X){return Object.keys(X).reduce((Y,G)=>{let Q=X[G];if(Array.isArray(Q))Q=Q.map((J)=>Nd0(J,this.opt)?this.mapRow(J):J);else if(Nd0(Q,this.opt))Q=this.mapRow(Q);return Y[this.camelCase(G)]=Q,Y},{})}snakeCase(X){return this.#Y(X)}camelCase(X){return this.#X(X)}}function Nd0(X,Y){return j$1(X)&&!Y?.maintainNestedObjectKeys}var Bd0=D(()=>{W0();$d0()});var kr1;var zd0=D(()=>{ZI();W0();kr1=class kr1 extends zF{transformSelectQuery(X,Y){return this.#X(super.transformSelectQuery(X,Y))}transformUpdateQuery(X,Y){return this.#X(super.transformUpdateQuery(X,Y))}transformDeleteQuery(X,Y){return this.#X(super.transformDeleteQuery(X,Y))}#X(X){if(!X.joins||X.joins.length===0)return X;return n({...X,joins:this.#Y(X.joins)})}#Y(X){let Y=[];for(let G=0;G<X.length;++G){let Q=!1;for(let J=0;J<Y.length;++J)if(M$1(X[G],Y[J])){Q=!0;break}if(!Q)Y.push(X[G])}return n(Y)}}});class JD8{#X=new kr1;transformQuery(X){return this.#X.transformNode(X.node,X.queryId)}transformResult(X){return Promise.resolve(X.result)}}var Od0=D(()=>{zd0()});class ZD8{opt;#X;constructor(X={}){this.opt=X,this.#X=X.objectStrategy||"in-place"}transformQuery(X){return X.node}async transformResult(X){return{...X.result,rows:Dd0(X.result.rows,this.#X)}}}function Dd0(X,Y){let G=Y==="create"?Array(X.length):X;for(let Q=0;Q<X.length;++Q)G[Q]=vr1(X[Q],Y);return G}function vr1(X,Y){if(H9(X))return WD8(X);if(Array.isArray(X))return Dd0(X,Y);if(j$1(X))return KD8(X,Y);return X}function WD8(X){if($D8(X))try{return vr1(JSON.parse(X),"in-place")}catch(Y){}return X}function $D8(X){return X.match(/^[\[\{]/)!=null}function KD8(X,Y){let G=Y==="create"?{}:X;for(let Q in X)G[Q]=vr1(X[Q],Y);return G}var wd0=D(()=>{W0()});var _r1;var Ld0=D(()=>{ZI();ce();aL();oT();_r1=class _r1 extends zF{#X;constructor(X){super();this.#X=X}transformBinaryOperation(X){if(this.#Y(X))return this.#X(X);return X}#Y(X){let{operator:Y,rightOperand:G}=X;return(Sd.is(G)||DN.is(G))&&G.values.length===0&&PZ.is(Y)&&(Y.operator==="in"||Y.operator==="not in")}}});class HD8{opt;#X;constructor(X){this.opt=X,this.#X=new _r1(X.strategy)}transformQuery(X){return this.#X.transformNode(X.node,X.queryId)}async transformResult(X){return X.result}}var Ed0=D(()=>{Ld0()});var Pd0=()=>{};var qd0=()=>{};var Ad0=()=>{};var Td0=()=>{};var Id0=()=>{};var Vd0=()=>{};var jd0=()=>{};var Md0=()=>{};var q4=D(()=>{Am0();ZK1();f$1();dd();Tm0();Im0();Vm0();jm0();Mm0();WK1();qa1();XK1();Ta1();QI();Ka1();OK1();La1();ia1();DK1();ra1();xa1();cn1();pt1();WE();Cm0();gt1();md();km0();NI();Jc();bt1();It1();kt1();Mt1();vt1();At1();Vt1();Tt1();jt1();EK1();PK1();Pt1();St1();ft1();Ct1();Ot1();xt1();le();wK1();mt1();_m0();fm0();bm0();ym0();xm0();um0();lm0();rt1();Wr1();Kr1();Fr1();im0();pm0();Nr1();Or1();wr1();Er1();qr1();tm0();rm0();st1();Gr1();Jr1();Tr1();om0();Gd0();Vr1();Mr1();Sr1();NI();Qd0();BI();Zd0();Wd0();Bd0();Od0();WI();wd0();Ed0();Pd0();Qt1();qK1();IK1();BK1();ZF();zt1();aT();pL();y$1();$11();Xt1();B11();dn1();N11();EJ();Oa1();ja1();YK1();qd0();R$1();C$1();Ad();RK1();T11();_K1();ea1();Na1();Ft1();re();Zt1();AK1();xe();k$1();v$1();kK1();jK1();Za1();la1();D11();ae();ca1();Ht1();ua1();Xa1();Ga1();U7();eT();Id();m$1();ta1();de();u$1();Y11();n$1();ka1();se();Bt1();ga1();s$1();Da1();gn1();f3();ZI();at1();Ad0();aL();Pa1();tT();g$1();pe();$a1();i$1();Cd();Ha1();sn1();L11();ce();PK();EK();x$1();z11();$t1();Lt1();Ja1();NO();ue();hn1();YI();Fa1();KK1();Td0();Td();Ea1();sa1();pa1();w11();vd();a$1();oT();wN();Ua1();XI();oe();Ra1();Id0();it1();Vd0();jd0();ct1();Md0()});var Rd0={};R0(Rd0,{BunSqliteDialect:()=>DD8});var FD8=class{get supportsCreateIfNotExists(){return!0}get supportsTransactionalDdl(){return!1}get supportsReturning(){return!0}async acquireMigrationLock(){}async releaseMigrationLock(){}get supportsOutput(){return!0}},UD8=class{#X;#Y=new BD8;#G;#Q;constructor(X){this.#X={...X}}async init(){if(this.#G=this.#X.database,this.#Q=new ND8(this.#G),this.#X.onCreateConnection)await this.#X.onCreateConnection(this.#Q)}async acquireConnection(){return await this.#Y.lock(),this.#Q}async beginTransaction(X){await X.executeQuery(B9.raw("begin"))}async commitTransaction(X){await X.executeQuery(B9.raw("commit"))}async rollbackTransaction(X){await X.executeQuery(B9.raw("rollback"))}async releaseConnection(){this.#Y.unlock()}async destroy(){this.#G?.close()}},ND8=class{#X;constructor(X){this.#X=X}executeQuery(X){let{sql:Y,parameters:G}=X,Q=this.#X.prepare(Y);return Promise.resolve({rows:Q.all(G)})}async*streamQuery(){throw Error("Streaming query is not supported by SQLite driver.")}},BD8=class{#X;#Y;async lock(){while(this.#X)await this.#X;this.#X=new Promise((X)=>{this.#Y=X})}unlock(){let X=this.#Y;this.#X=void 0,this.#Y=void 0,X?.()}},zD8=class{#X;constructor(X){this.#X=X}async getSchemas(){return[]}async getTables(X={withInternalKyselyTables:!1}){let Y=this.#X.selectFrom("sqlite_schema").where("type","=","table").where("name","not like","sqlite_%").select("name").$castTo();if(!X.withInternalKyselyTables)Y=Y.where("name","!=",eY).where("name","!=",RG);let G=await Y.execute();return Promise.all(G.map(({name:Q})=>this.#Y(Q)))}async getMetadata(X){return{tables:await this.getTables(X)}}async#Y(X){let Y=this.#X,G=(await Y.selectFrom("sqlite_master").where("name","=",X).select("sql").$castTo().execute())[0]?.sql?.split(/[\(\),]/)?.find((Q)=>Q.toLowerCase().includes("autoincrement"))?.split(/\s+/)?.[0]?.replace(/["`]/g,"");return{name:X,columns:(await Y.selectFrom(O1`pragma_table_info(${X})`.as("table_info")).select(["name","type","notnull","dflt_value"]).execute()).map((Q)=>({name:Q.name,dataType:Q.type,isNullable:!Q.notnull,isAutoIncrementing:Q.name===G,hasDefaultValue:Q.dflt_value!=null})),isView:!0}}},OD8,DD8=class{#X;constructor(X){this.#X={...X}}createDriver(){return new UD8(this.#X)}createQueryCompiler(){return new OD8}createAdapter(){return new FD8}createIntrospector(X){return new zD8(X)}};var Sd0=D(()=>{q4();OD8=class extends EQ{getCurrentParameterPlaceholder(){return"?"}getLeftIdentifierWrapper(){return'"'}getRightIdentifierWrapper(){return'"'}getAutoIncrement(){return"autoincrement"}}});var Cd0={};R0(Cd0,{NodeSqliteDialect:()=>TD8});var wD8=class{get supportsCreateIfNotExists(){return!0}get supportsTransactionalDdl(){return!1}get supportsReturning(){return!0}async acquireMigrationLock(){}async releaseMigrationLock(){}get supportsOutput(){return!0}},LD8=class{#X;#Y=new PD8;#G;#Q;constructor(X){this.#X={...X}}async init(){if(this.#G=this.#X.database,this.#Q=new ED8(this.#G),this.#X.onCreateConnection)await this.#X.onCreateConnection(this.#Q)}async acquireConnection(){return await this.#Y.lock(),this.#Q}async beginTransaction(X){await X.executeQuery(B9.raw("begin"))}async commitTransaction(X){await X.executeQuery(B9.raw("commit"))}async rollbackTransaction(X){await X.executeQuery(B9.raw("rollback"))}async releaseConnection(){this.#Y.unlock()}async destroy(){this.#G?.close()}},ED8=class{#X;constructor(X){this.#X=X}executeQuery(X){let{sql:Y,parameters:G}=X,Q=this.#X.prepare(Y).all(...G);return Promise.resolve({rows:Q})}async*streamQuery(){throw Error("Streaming query is not supported by SQLite driver.")}},PD8=class{#X;#Y;async lock(){while(this.#X)await this.#X;this.#X=new Promise((X)=>{this.#Y=X})}unlock(){let X=this.#Y;this.#X=void 0,this.#Y=void 0,X?.()}},qD8=class{#X;constructor(X){this.#X=X}async getSchemas(){return[]}async getTables(X={withInternalKyselyTables:!1}){let Y=this.#X.selectFrom("sqlite_schema").where("type","=","table").where("name","not like","sqlite_%").select("name").$castTo();if(!X.withInternalKyselyTables)Y=Y.where("name","!=",eY).where("name","!=",RG);let G=await Y.execute();return Promise.all(G.map(({name:Q})=>this.#Y(Q)))}async getMetadata(X){return{tables:await this.getTables(X)}}async#Y(X){let Y=this.#X,G=(await Y.selectFrom("sqlite_master").where("name","=",X).select("sql").$castTo().execute())[0]?.sql?.split(/[\(\),]/)?.find((Q)=>Q.toLowerCase().includes("autoincrement"))?.split(/\s+/)?.[0]?.replace(/["`]/g,"");return{name:X,columns:(await Y.selectFrom(O1`pragma_table_info(${X})`.as("table_info")).select(["name","type","notnull","dflt_value"]).execute()).map((Q)=>({name:Q.name,dataType:Q.type,isNullable:!Q.notnull,isAutoIncrementing:Q.name===G,hasDefaultValue:Q.dflt_value!=null})),isView:!0}}},AD8,TD8=class{#X;constructor(X){this.#X={...X}}createDriver(){return new LD8(this.#X)}createQueryCompiler(){return new AD8}createAdapter(){return new wD8}createIntrospector(X){return new qD8(X)}};var kd0=D(()=>{q4();AD8=class extends EQ{getCurrentParameterPlaceholder(){return"?"}getLeftIdentifierWrapper(){return'"'}getRightIdentifierWrapper(){return'"'}getAutoIncrement(){return"autoincrement"}}});function Wc(X){if(!X)return null;if("dialect"in X)return Wc(X.dialect);if("createDriver"in X){if(X instanceof zI)return"sqlite";if(X instanceof OI)return"mysql";if(X instanceof MN)return"postgres";if(X instanceof j11)return"mssql"}if("aggregate"in X)return"sqlite";if("getConnection"in X)return"mysql";if("connect"in X)return"postgres";if("fileControl"in X)return"sqlite";if("open"in X&&"close"in X&&"prepare"in X)return"sqlite";return null}var mK1=async(X)=>{let Y=X.database;if(!Y)return{kysely:null,databaseType:null,transaction:void 0};if("db"in Y)return{kysely:Y.db,databaseType:Y.type,transaction:Y.transaction};if("dialect"in Y)return{kysely:new AZ({dialect:Y.dialect}),databaseType:Y.type,transaction:Y.transaction};let G=void 0,Q=Wc(Y);if("createDriver"in Y)G=Y;if("aggregate"in Y&&!("createSession"in Y))G=new zI({database:Y});if("getConnection"in Y)G=new OI(Y);if("connect"in Y)G=new MN({pool:Y});if("fileControl"in Y){let{BunSqliteDialect:J}=await Promise.resolve().then(() => (Sd0(),Rd0));G=new J({database:Y})}if("createSession"in Y&&typeof window>"u"){let J=void 0;try{({DatabaseSync:J}=await import("node:sqlite"))}catch(W){if(W!==null&&typeof W==="object"&&"code"in W&&W.code!=="ERR_UNKNOWN_BUILTIN_MODULE")throw W}if(J&&Y instanceof J){let{NodeSqliteDialect:W}=await Promise.resolve().then(() => (kd0(),Cd0));G=new W({database:Y})}}return{kysely:G?new AZ({dialect:G}):null,databaseType:Q,transaction:void 0}};var RN=D(()=>{q4()});function k9(X){return X}var M11=()=>{};var x6,U4;var fr1=D(()=>{M11();x6=k9({USER_NOT_FOUND:"User not found",FAILED_TO_CREATE_USER:"Failed to create user",FAILED_TO_CREATE_SESSION:"Failed to create session",FAILED_TO_UPDATE_USER:"Failed to update user",FAILED_TO_GET_SESSION:"Failed to get session",INVALID_PASSWORD:"Invalid password",INVALID_EMAIL:"Invalid email",INVALID_EMAIL_OR_PASSWORD:"Invalid email or password",SOCIAL_ACCOUNT_ALREADY_LINKED:"Social account already linked",PROVIDER_NOT_FOUND:"Provider not found",INVALID_TOKEN:"Invalid token",ID_TOKEN_NOT_SUPPORTED:"id_token not supported",FAILED_TO_GET_USER_INFO:"Failed to get user info",USER_EMAIL_NOT_FOUND:"User email not found",EMAIL_NOT_VERIFIED:"Email not verified",PASSWORD_TOO_SHORT:"Password too short",PASSWORD_TOO_LONG:"Password too long",USER_ALREADY_EXISTS:"User already exists.",USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL:"User already exists. Use another email.",EMAIL_CAN_NOT_BE_UPDATED:"Email can not be updated",CREDENTIAL_ACCOUNT_NOT_FOUND:"Credential account not found",SESSION_EXPIRED:"Session expired. Re-authenticate to perform this action.",FAILED_TO_UNLINK_LAST_ACCOUNT:"You can't unlink your last account",ACCOUNT_NOT_FOUND:"Account not found",USER_ALREADY_HAS_PASSWORD:"User already has a password. Provide that to delete the account."}),U4=class extends Error{constructor(X,Y){super(X);this.name="BetterAuthError",this.message=X,this.cause=Y,this.stack=""}}});var WY=D(()=>{M11();fr1()});var Y$=(X)=>{let Y=(X.plugins??[]).reduce((H,U)=>{let N=U.schema;if(!N)return H;for(let[B,z]of Object.entries(N))H[B]={fields:{...H[B]?.fields,...z.fields},modelName:z.modelName||B};return H},{}),G=X.rateLimit?.storage==="database",Q={rateLimit:{modelName:X.rateLimit?.modelName||"rateLimit",fields:{key:{type:"string",fieldName:X.rateLimit?.fields?.key||"key"},count:{type:"number",fieldName:X.rateLimit?.fields?.count||"count"},lastRequest:{type:"number",bigint:!0,fieldName:X.rateLimit?.fields?.lastRequest||"lastRequest"}}}},{user:J,session:W,account:Z,...$}=Y,K={session:{modelName:X.session?.modelName||"session",fields:{expiresAt:{type:"date",required:!0,fieldName:X.session?.fields?.expiresAt||"expiresAt"},token:{type:"string",required:!0,fieldName:X.session?.fields?.token||"token",unique:!0},createdAt:{type:"date",required:!0,fieldName:X.session?.fields?.createdAt||"createdAt",defaultValue:()=>new Date},updatedAt:{type:"date",required:!0,fieldName:X.session?.fields?.updatedAt||"updatedAt",onUpdate:()=>new Date},ipAddress:{type:"string",required:!1,fieldName:X.session?.fields?.ipAddress||"ipAddress"},userAgent:{type:"string",required:!1,fieldName:X.session?.fields?.userAgent||"userAgent"},userId:{type:"string",fieldName:X.session?.fields?.userId||"userId",references:{model:X.user?.modelName||"user",field:"id",onDelete:"cascade"},required:!0,index:!0},...W?.fields,...X.session?.additionalFields},order:2}};return{user:{modelName:X.user?.modelName||"user",fields:{name:{type:"string",required:!0,fieldName:X.user?.fields?.name||"name",sortable:!0},email:{type:"string",unique:!0,required:!0,fieldName:X.user?.fields?.email||"email",sortable:!0},emailVerified:{type:"boolean",defaultValue:!1,required:!0,fieldName:X.user?.fields?.emailVerified||"emailVerified",input:!1},image:{type:"string",required:!1,fieldName:X.user?.fields?.image||"image"},createdAt:{type:"date",defaultValue:()=>new Date,required:!0,fieldName:X.user?.fields?.createdAt||"createdAt"},updatedAt:{type:"date",defaultValue:()=>new Date,onUpdate:()=>new Date,required:!0,fieldName:X.user?.fields?.updatedAt||"updatedAt"},...J?.fields,...X.user?.additionalFields},order:1},...!X.secondaryStorage||X.session?.storeSessionInDatabase?K:{},account:{modelName:X.account?.modelName||"account",fields:{accountId:{type:"string",required:!0,fieldName:X.account?.fields?.accountId||"accountId"},providerId:{type:"string",required:!0,fieldName:X.account?.fields?.providerId||"providerId"},userId:{type:"string",references:{model:X.user?.modelName||"user",field:"id",onDelete:"cascade"},required:!0,fieldName:X.account?.fields?.userId||"userId",index:!0},accessToken:{type:"string",required:!1,fieldName:X.account?.fields?.accessToken||"accessToken"},refreshToken:{type:"string",required:!1,fieldName:X.account?.fields?.refreshToken||"refreshToken"},idToken:{type:"string",required:!1,fieldName:X.account?.fields?.idToken||"idToken"},accessTokenExpiresAt:{type:"date",required:!1,fieldName:X.account?.fields?.accessTokenExpiresAt||"accessTokenExpiresAt"},refreshTokenExpiresAt:{type:"date",required:!1,fieldName:X.account?.fields?.refreshTokenExpiresAt||"refreshTokenExpiresAt"},scope:{type:"string",required:!1,fieldName:X.account?.fields?.scope||"scope"},password:{type:"string",required:!1,fieldName:X.account?.fields?.password||"password"},createdAt:{type:"date",required:!0,fieldName:X.account?.fields?.createdAt||"createdAt",defaultValue:()=>new Date},updatedAt:{type:"date",required:!0,fieldName:X.account?.fields?.updatedAt||"updatedAt",onUpdate:()=>new Date},...Z?.fields,...X.account?.additionalFields},order:3},verification:{modelName:X.verification?.modelName||"verification",fields:{identifier:{type:"string",required:!0,fieldName:X.verification?.fields?.identifier||"identifier",index:!0},value:{type:"string",required:!0,fieldName:X.verification?.fields?.value||"value"},expiresAt:{type:"date",required:!0,fieldName:X.verification?.fields?.expiresAt||"expiresAt"},createdAt:{type:"date",required:!0,defaultValue:()=>new Date,fieldName:X.verification?.fields?.createdAt||"createdAt"},updatedAt:{type:"date",required:!0,defaultValue:()=>new Date,onUpdate:()=>new Date,fieldName:X.verification?.fields?.updatedAt||"updatedAt"}},order:4},...$,...G?Q:{}}},DI=({usePlural:X,schema:Y})=>{return(Q)=>{if(X&&Q.charAt(Q.length-1)==="s"){let W=Q.slice(0,-1),Z=Y[W]?W:void 0;if(!Z)Z=Object.entries(Y).find(([$,K])=>K.modelName===W)?.[0];if(Z)return Z}let J=Y[Q]?Q:void 0;if(!J)J=Object.entries(Y).find(([W,Z])=>Z.modelName===Q)?.[0];if(!J)throw new U4(`Model "${Q}" not found in schema`);return J}},dK1=({schema:X,usePlural:Y})=>{let G=DI({schema:X,usePlural:Y});return({field:J,model:W})=>{if(J==="id"||J==="_id")return"id";let Z=G(W),$=X[Z]?.fields[J];if(!$){let K=Object.entries(X[Z].fields).find(([H,U])=>U.fieldName===J);if(K)$=K[1],J=K[0]}if(!$)throw new U4(`Field ${J} not found in model ${Z}`);return J}},cK1=({schema:X,usePlural:Y})=>{let G=DI({schema:X,usePlural:Y}),Q=dK1({schema:X,usePlural:Y});function J({model:W,field:Z}){let $=G(W),K=Q({model:$,field:Z});return X[$]?.fields[K]?.fieldName||K}return J},iK1=({usePlural:X,schema:Y})=>{let G=DI({schema:Y,usePlural:X});return(J)=>{let W=G(J);if(Y&&Y[W]&&Y[W].modelName!==J)return X?`${Y[W].modelName}s`:Y[W].modelName;return X?`${J}s`:J}};var G$=D(()=>{WY()});function pK1(X){return X?"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_":"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"}function vd0(X,Y,G){let Q="",J=0,W=0;for(let Z of X){J=J<<8|Z,W+=8;while(W>=6)W-=6,Q+=Y[J>>W&63]}if(W>0)Q+=Y[J<<6-W&63];if(G){let Z=(4-Q.length%4)%4;Q+="=".repeat(Z)}return Q}function _d0(X,Y){let G=new Map;for(let Z=0;Z<Y.length;Z++)G.set(Y[Z],Z);let Q=[],J=0,W=0;for(let Z of X){if(Z==="=")break;let $=G.get(Z);if($===void 0)throw Error(`Invalid Base64 character: ${Z}`);if(J=J<<6|$,W+=6,W>=8)W-=8,Q.push(J>>W&255)}return Uint8Array.from(Q)}var t5,z9;var k7=D(()=>{t5={encode(X,Y={}){let G=pK1(!1),Q=typeof X==="string"?new TextEncoder().encode(X):new Uint8Array(X);return vd0(Q,G,Y.padding??!0)},decode(X){if(typeof X!=="string")X=new TextDecoder().decode(X);let Y=X.includes("-")||X.includes("_"),G=pK1(Y);return _d0(X,G)}},z9={encode(X,Y={}){let G=pK1(!0),Q=typeof X==="string"?new TextEncoder().encode(X):new Uint8Array(X);return vd0(Q,G,Y.padding??!0)},decode(X){let Y=X.includes("-")||X.includes("_"),G=pK1(Y);return _d0(X,G)}}});function XG(){let X=typeof globalThis<"u"&&globalThis.crypto;if(X&&typeof X.subtle==="object"&&X.subtle!=null)return X.subtle;throw Error("crypto.subtle must be defined")}var SN=()=>{};function B7(X,Y){return{digest:async(G)=>{let J=typeof G==="string"?new TextEncoder().encode(G):G,W=await XG().digest(X,J);if(Y==="hex")return Array.from(new Uint8Array(W)).map((K)=>K.toString(16).padStart(2,"0")).join("");if(Y==="base64"||Y==="base64url"||Y==="base64urlnopad"){if(Y.includes("url"))return z9.encode(W,{padding:Y!=="base64urlnopad"});return t5.encode(W)}return W}}}var SG=D(()=>{k7();SN()});function ID8(X){return X instanceof Uint8Array||ArrayBuffer.isView(X)&&X.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in X&&X.BYTES_PER_ELEMENT===1}function nK1(X){if(typeof X!=="boolean")throw TypeError(`boolean expected, not ${X}`)}function $E(X){if(typeof X!=="number")throw TypeError("number expected, got "+typeof X);if(!Number.isSafeInteger(X)||X<0)throw RangeError("positive integer expected, got "+X)}function uX(X,Y,G=""){let Q=ID8(X),J=X?.length,W=Y!==void 0;if(!Q||W&&J!==Y){let Z=G&&`"${G}" `,$=W?` of length ${Y}`:"",K=Q?`length=${J}`:`type=${typeof X}`,H=Z+"expected Uint8Array"+$+", got "+K;if(!Q)throw TypeError(H);throw RangeError(H)}return X}function br1(X,Y=!0){if(X.destroyed)throw Error("Hash instance has been destroyed");if(Y&&X.finished)throw Error("Hash#digest() has already been called")}function bd0(X,Y,G=!1){uX(X,void 0,"output");let Q=Y.outputLen;if(X.length<Q)throw RangeError("digestInto() expects output buffer of length at least "+Q);if(G&&!$c(X))throw Error("invalid output, must be aligned")}function CN(X){return new Uint32Array(X.buffer,X.byteOffset,Math.floor(X.byteLength/4))}function PF(...X){for(let Y=0;Y<X.length;Y++)X[Y].fill(0)}function VD8(X){return new DataView(X.buffer,X.byteOffset,X.byteLength)}function R11(X){if(uX(X),xd0)return X.toHex();let Y="";for(let G=0;G<X.length;G++)Y+=MD8[X[G]];return Y}function fd0(X){if(X>=VO._0&&X<=VO._9)return X-VO._0;if(X>=VO.A&&X<=VO.F)return X-(VO.A-10);if(X>=VO.a&&X<=VO.f)return X-(VO.a-10);return}function aK1(X){if(typeof X!=="string")throw TypeError("hex string expected, got "+typeof X);if(xd0)try{return Uint8Array.fromHex(X)}catch(J){if(J instanceof SyntaxError)throw RangeError(J.message);throw J}let Y=X.length,G=Y/2;if(Y%2)throw RangeError("hex string expected, got unpadded hex of length "+Y);let Q=new Uint8Array(G);for(let J=0,W=0;J<G;J++,W+=2){let Z=fd0(X.charCodeAt(W)),$=fd0(X.charCodeAt(W+1));if(Z===void 0||$===void 0){let K=X[W]+X[W+1];throw RangeError('hex string expected, got non-hex character "'+K+'" at index '+W)}Q[J]=Z*16+$}return Q}function tK1(X){if(typeof X!=="string")throw TypeError("string expected");return new Uint8Array(new TextEncoder().encode(X))}function RD8(X,Y){if(!X.byteLength||!Y.byteLength)return!1;return X.buffer===Y.buffer&&X.byteOffset<Y.byteOffset+Y.byteLength&&Y.byteOffset<X.byteOffset+X.byteLength}function hd0(...X){let Y=0;for(let Q=0;Q<X.length;Q++){let J=X[Q];uX(J),Y+=J.length}let G=new Uint8Array(Y);for(let Q=0,J=0;Q<X.length;Q++){let W=X[Q];G.set(W,J),J+=W.length}return G}function gd0(X,Y){if(Y==null||typeof Y!=="object")throw Error("options must be defined");return Object.assign(X,Y)}function ud0(X,Y){if(X.length!==Y.length)return!1;let G=0;for(let Q=0;Q<X.length;Q++)G|=X[Q]^Y[Q];return G===0}function ld0(X,Y,G){let Q=Y,J=G||(()=>[]),W=($,K)=>Q(K,...J($)).update($).digest(),Z=Q(new Uint8Array(X),...J(new Uint8Array(0)));return W.outputLen=Z.outputLen,W.blockLen=Z.blockLen,W.create=($,...K)=>Q($,...K),W}function S11(X,Y,G=!0){if(Y===void 0)return new Uint8Array(X);if(uX(Y,void 0,"output"),Y.length!==X)throw Error('"output" expected Uint8Array of length '+X+", got: "+Y.length);if(G&&!$c(Y))throw Error("invalid output, must be aligned");return Y}function dd0(X,Y,G){$E(X),$E(Y),nK1(G);let Q=new Uint8Array(16),J=VD8(Q);return J.setBigUint64(0,BigInt(Y),G),J.setBigUint64(8,BigInt(X),G),Q}function $c(X){return X.byteOffset%4===0}function Kc(X){return Uint8Array.from(uX(X))}function cd0(X=32){$E(X);let Y=typeof globalThis==="object"?globalThis.crypto:null;if(typeof Y?.getRandomValues!=="function")throw Error("crypto.getRandomValues must be defined");return Y.getRandomValues(new Uint8Array(X))}function Hc(X,Y=cd0){let{nonceLength:G}=X;$E(G);let Q=(W,Z,$)=>{let K=hd0(W,Z);if(!RD8($,Z))Z.fill(0);return K},J=(W,...Z)=>({encrypt($){uX($);let K=Y(G),H=X(W,K,...Z).encrypt($);if(H instanceof Promise)return H.then((U)=>Q(K,U,$));return Q(K,H,$)},decrypt($){uX($);let K=$.subarray(0,G),H=$.subarray(G);return X(W,K,...Z).decrypt(H)}});if("blockSize"in X)J.blockSize=X.blockSize;if("tagLength"in X)J.tagLength=X.tagLength;return J}var KE,yd0=(X)=>X<<24&4278190080|X<<8&16711680|X>>>8&65280|X>>>24&255,PQ,jD8=(X)=>{for(let Y=0;Y<X.length;Y++)X[Y]=yd0(X[Y]);return X},kN,xd0,MD8,VO,md0=(X,Y)=>{function G(Q,...J){if(uX(Q,void 0,"key"),X.nonceLength!==void 0){let U=J[0];uX(U,X.varSizeNonce?void 0:X.nonceLength,"nonce")}let W=X.tagLength;if(W&&J[1]!==void 0)uX(J[1],void 0,"AAD");let Z=Y(Q,...J),$=(U,N)=>{if(N!==void 0){if(U!==2)throw Error("cipher output not supported");uX(N,void 0,"output")}},K=!1;return{encrypt(U,N){if(K)throw Error("cannot encrypt() twice with same key + nonce");return K=!0,uX(U),$(Z.encrypt.length,N),Z.encrypt(U,N)},decrypt(U,N){if(uX(U),W&&U.length<W)throw Error('"ciphertext" expected length bigger than tagLength='+W);return $(Z.decrypt.length,N),Z.decrypt(U,N)}}}return Object.assign(G,X),G};var Fc=D(()=>{/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */KE=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)(),PQ=KE?(X)=>X:(X)=>yd0(X)>>>0,kN=KE?(X)=>X:jD8,xd0=(()=>typeof Uint8Array.from([]).toHex==="function"&&typeof Uint8Array.fromHex==="function")(),MD8=Array.from({length:256},(X,Y)=>Y.toString(16).padStart(2,"0"));VO={_0:48,_9:57,A:65,F:70,a:97,f:102}});function X4(X,Y){return X<<Y|X>>>32-Y}function vD8(X,Y,G,Q,J,W,Z,$){let K=J.length,H=new Uint8Array(C11),U=CN(H),N=KE&&$c(J)&&$c(W),B=N?CN(J):id0,z=N?CN(W):id0;if(!KE){for(let O=0;O<K;Z++){if(X(Y,G,Q,U,Z,$),kN(U),Z>=yr1)throw Error("arx: counter overflow");let w=Math.min(C11,K-O);for(let E=0,P;E<w;E++)P=O+E,W[P]=J[P]^H[E];O+=w}return}for(let O=0;O<K;Z++){if(X(Y,G,Q,U,Z,$),Z>=yr1)throw Error("arx: counter overflow");let w=Math.min(C11,K-O);if(N&&w===C11){let E=O/4;if(O%4!==0)throw Error("arx: invalid block position");for(let P=0,q;P<kD8;P++)q=E+P,z[q]=B[q]^U[P];O+=C11;continue}for(let E=0,P;E<w;E++)P=O+E,W[P]=J[P]^H[E];O+=w}}function nd0(X,Y){let{allowShortKeys:G,extendNonceFn:Q,counterLength:J,counterRight:W,rounds:Z}=gd0({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},Y);if(typeof X!=="function")throw Error("core must be a function");return $E(J),$E(Z),nK1(W),nK1(G),($,K,H,U,N=0)=>{uX($,void 0,"key"),uX(K,void 0,"nonce"),uX(H,void 0,"data");let B=H.length;if(U=S11(B,U,!1),$E(N),N<0||N>=yr1)throw Error("arx: counter overflow");let z=[],O=$.length,w,E;if(O===32)z.push(w=Kc($)),E=CD8;else if(O===16&&G)w=new Uint8Array(32),w.set($),w.set($,16),E=SD8,z.push(w);else throw uX($,32,"arx key"),Error("invalid key size");if(!KE||!$c(K))z.push(K=Kc(K));let P=CN(w);if(Q){if(K.length!==24)throw Error("arx: extended nonce must be 24 bytes");let M=K.subarray(0,16);if(KE)Q(E,P,CN(M),P);else{let V=kN(Uint32Array.from(E));Q(V,P,CN(M),P),PF(V),kN(P)}K=K.subarray(16)}else if(!KE)kN(P);let q=16-J;if(q!==K.length)throw Error(`arx: nonce must be ${q} or 16 bytes`);if(q!==12){let M=new Uint8Array(12);M.set(K,W?0:12-K.length),K=M,z.push(K)}let j=kN(CN(K));try{return vD8(X,E,P,j,H,U,N,Z),U}finally{PF(...z)}}}var pd0=(X)=>Uint8Array.from(X.split(""),(Y)=>Y.charCodeAt(0)),SD8,CD8,C11=64,kD8=16,yr1,id0;var ad0=D(()=>{Fc();SD8=(()=>kN(CN(pd0("expand 16-byte k"))))(),CD8=(()=>kN(CN(pd0("expand 32-byte k"))))();yr1=(()=>4294967295)(),id0=Uint32Array.of()});function qQ(X,Y){return X[Y++]&255|(X[Y++]&255)<<8}class td0{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;destroyed=!1;constructor(X){X=Kc(uX(X,32,"key"));let Y=qQ(X,0),G=qQ(X,2),Q=qQ(X,4),J=qQ(X,6),W=qQ(X,8),Z=qQ(X,10),$=qQ(X,12),K=qQ(X,14);this.r[0]=Y&8191,this.r[1]=(Y>>>13|G<<3)&8191,this.r[2]=(G>>>10|Q<<6)&7939,this.r[3]=(Q>>>7|J<<9)&8191,this.r[4]=(J>>>4|W<<12)&255,this.r[5]=W>>>1&8190,this.r[6]=(W>>>14|Z<<2)&8191,this.r[7]=(Z>>>11|$<<5)&8065,this.r[8]=($>>>8|K<<8)&8191,this.r[9]=K>>>5&127;for(let H=0;H<8;H++)this.pad[H]=qQ(X,16+2*H)}process(X,Y,G=!1){let Q=G?0:2048,{h:J,r:W}=this,Z=W[0],$=W[1],K=W[2],H=W[3],U=W[4],N=W[5],B=W[6],z=W[7],O=W[8],w=W[9],E=qQ(X,Y+0),P=qQ(X,Y+2),q=qQ(X,Y+4),j=qQ(X,Y+6),M=qQ(X,Y+8),V=qQ(X,Y+10),R=qQ(X,Y+12),k=qQ(X,Y+14),_=J[0]+(E&8191),v=J[1]+((E>>>13|P<<3)&8191),y=J[2]+((P>>>10|q<<6)&8191),h=J[3]+((q>>>7|j<<9)&8191),i=J[4]+((j>>>4|M<<12)&8191),p=J[5]+(M>>>1&8191),f=J[6]+((M>>>14|V<<2)&8191),u=J[7]+((V>>>11|R<<5)&8191),r=J[8]+((R>>>8|k<<8)&8191),o=J[9]+(k>>>5|Q),N1=0,L1=N1+_*Z+v*(5*w)+y*(5*O)+h*(5*z)+i*(5*B);N1=L1>>>13,L1&=8191,L1+=p*(5*N)+f*(5*U)+u*(5*H)+r*(5*K)+o*(5*$),N1+=L1>>>13,L1&=8191;let U1=N1+_*$+v*Z+y*(5*w)+h*(5*O)+i*(5*z);N1=U1>>>13,U1&=8191,U1+=p*(5*B)+f*(5*N)+u*(5*U)+r*(5*H)+o*(5*K),N1+=U1>>>13,U1&=8191;let D1=N1+_*K+v*$+y*Z+h*(5*w)+i*(5*O);N1=D1>>>13,D1&=8191,D1+=p*(5*z)+f*(5*B)+u*(5*N)+r*(5*U)+o*(5*H),N1+=D1>>>13,D1&=8191;let G1=N1+_*H+v*K+y*$+h*Z+i*(5*w);N1=G1>>>13,G1&=8191,G1+=p*(5*O)+f*(5*z)+u*(5*B)+r*(5*N)+o*(5*U),N1+=G1>>>13,G1&=8191;let h1=N1+_*U+v*H+y*K+h*$+i*Z;N1=h1>>>13,h1&=8191,h1+=p*(5*w)+f*(5*O)+u*(5*z)+r*(5*B)+o*(5*N),N1+=h1>>>13,h1&=8191;let y1=N1+_*N+v*U+y*H+h*K+i*$;N1=y1>>>13,y1&=8191,y1+=p*Z+f*(5*w)+u*(5*O)+r*(5*z)+o*(5*B),N1+=y1>>>13,y1&=8191;let v1=N1+_*B+v*N+y*U+h*H+i*K;N1=v1>>>13,v1&=8191,v1+=p*$+f*Z+u*(5*w)+r*(5*O)+o*(5*z),N1+=v1>>>13,v1&=8191;let X1=N1+_*z+v*B+y*N+h*U+i*H;N1=X1>>>13,X1&=8191,X1+=p*K+f*$+u*Z+r*(5*w)+o*(5*O),N1+=X1>>>13,X1&=8191;let x1=N1+_*O+v*z+y*B+h*N+i*U;N1=x1>>>13,x1&=8191,x1+=p*H+f*K+u*$+r*Z+o*(5*w),N1+=x1>>>13,x1&=8191;let G0=N1+_*w+v*O+y*z+h*B+i*N;N1=G0>>>13,G0&=8191,G0+=p*U+f*H+u*K+r*$+o*Z,N1+=G0>>>13,G0&=8191,N1=(N1<<2)+N1|0,N1=N1+L1|0,L1=N1&8191,N1=N1>>>13,U1+=N1,J[0]=L1,J[1]=U1,J[2]=D1,J[3]=G1,J[4]=h1,J[5]=y1,J[6]=v1,J[7]=X1,J[8]=x1,J[9]=G0}finalize(){let{h:X,pad:Y}=this,G=new Uint16Array(10),Q=X[1]>>>13;X[1]&=8191;for(let Z=2;Z<10;Z++)X[Z]+=Q,Q=X[Z]>>>13,X[Z]&=8191;X[0]+=Q*5,Q=X[0]>>>13,X[0]&=8191,X[1]+=Q,Q=X[1]>>>13,X[1]&=8191,X[2]+=Q,G[0]=X[0]+5,Q=G[0]>>>13,G[0]&=8191;for(let Z=1;Z<10;Z++)G[Z]=X[Z]+Q,Q=G[Z]>>>13,G[Z]&=8191;G[9]-=8192;let J=(Q^1)-1;for(let Z=0;Z<10;Z++)G[Z]&=J;J=~J;for(let Z=0;Z<10;Z++)X[Z]=X[Z]&J|G[Z];X[0]=(X[0]|X[1]<<13)&65535,X[1]=(X[1]>>>3|X[2]<<10)&65535,X[2]=(X[2]>>>6|X[3]<<7)&65535,X[3]=(X[3]>>>9|X[4]<<4)&65535,X[4]=(X[4]>>>12|X[5]<<1|X[6]<<14)&65535,X[5]=(X[6]>>>2|X[7]<<11)&65535,X[6]=(X[7]>>>5|X[8]<<8)&65535,X[7]=(X[8]>>>8|X[9]<<5)&65535;let W=X[0]+Y[0];X[0]=W&65535;for(let Z=1;Z<8;Z++)W=(X[Z]+Y[Z]|0)+(W>>>16)|0,X[Z]=W&65535;PF(G)}update(X){br1(this),uX(X),X=Kc(X);let{buffer:Y,blockLen:G}=this,Q=X.length;for(let J=0;J<Q;){let W=Math.min(G-this.pos,Q-J);if(W===G){for(;G<=Q-J;J+=G)this.process(X,J);continue}if(Y.set(X.subarray(J,J+W),this.pos),this.pos+=W,J+=W,this.pos===G)this.process(Y,0,!1),this.pos=0}return this}destroy(){this.destroyed=!0,PF(this.h,this.r,this.buffer,this.pad)}digestInto(X){br1(this),bd0(X,this),this.finished=!0;let{buffer:Y,h:G}=this,{pos:Q}=this;if(Q){Y[Q++]=1;for(;Q<16;Q++)Y[Q]=0;this.process(Y,0,!0)}this.finalize();let J=0;for(let W=0;W<8;W++)X[J++]=G[W]>>>0,X[J++]=G[W]>>>8}digest(){let{buffer:X,outputLen:Y}=this;this.digestInto(X);let G=X.slice(0,Y);return this.destroy(),G}}var rd0;var od0=D(()=>{Fc();rd0=ld0(32,(X)=>new td0(X))});function _D8(X,Y,G,Q,J,W=20){let Z=X[0],$=X[1],K=X[2],H=X[3],U=Y[0],N=Y[1],B=Y[2],z=Y[3],O=Y[4],w=Y[5],E=Y[6],P=Y[7],q=J,j=G[0],M=G[1],V=G[2],R=Z,k=$,_=K,v=H,y=U,h=N,i=B,p=z,f=O,u=w,r=E,o=P,N1=q,L1=j,U1=M,D1=V;for(let h1=0;h1<W;h1+=2)R=R+y|0,N1=X4(N1^R,16),f=f+N1|0,y=X4(y^f,12),R=R+y|0,N1=X4(N1^R,8),f=f+N1|0,y=X4(y^f,7),k=k+h|0,L1=X4(L1^k,16),u=u+L1|0,h=X4(h^u,12),k=k+h|0,L1=X4(L1^k,8),u=u+L1|0,h=X4(h^u,7),_=_+i|0,U1=X4(U1^_,16),r=r+U1|0,i=X4(i^r,12),_=_+i|0,U1=X4(U1^_,8),r=r+U1|0,i=X4(i^r,7),v=v+p|0,D1=X4(D1^v,16),o=o+D1|0,p=X4(p^o,12),v=v+p|0,D1=X4(D1^v,8),o=o+D1|0,p=X4(p^o,7),R=R+h|0,D1=X4(D1^R,16),r=r+D1|0,h=X4(h^r,12),R=R+h|0,D1=X4(D1^R,8),r=r+D1|0,h=X4(h^r,7),k=k+i|0,N1=X4(N1^k,16),o=o+N1|0,i=X4(i^o,12),k=k+i|0,N1=X4(N1^k,8),o=o+N1|0,i=X4(i^o,7),_=_+p|0,L1=X4(L1^_,16),f=f+L1|0,p=X4(p^f,12),_=_+p|0,L1=X4(L1^_,8),f=f+L1|0,p=X4(p^f,7),v=v+y|0,U1=X4(U1^v,16),u=u+U1|0,y=X4(y^u,12),v=v+y|0,U1=X4(U1^v,8),u=u+U1|0,y=X4(y^u,7);let G1=0;Q[G1++]=Z+R|0,Q[G1++]=$+k|0,Q[G1++]=K+_|0,Q[G1++]=H+v|0,Q[G1++]=U+y|0,Q[G1++]=N+h|0,Q[G1++]=B+i|0,Q[G1++]=z+p|0,Q[G1++]=O+f|0,Q[G1++]=w+u|0,Q[G1++]=E+r|0,Q[G1++]=P+o|0,Q[G1++]=q+N1|0,Q[G1++]=j+L1|0,Q[G1++]=M+U1|0,Q[G1++]=V+D1|0}function fD8(X,Y,G,Q){let J=PQ(X[0]),W=PQ(X[1]),Z=PQ(X[2]),$=PQ(X[3]),K=PQ(Y[0]),H=PQ(Y[1]),U=PQ(Y[2]),N=PQ(Y[3]),B=PQ(Y[4]),z=PQ(Y[5]),O=PQ(Y[6]),w=PQ(Y[7]),E=PQ(G[0]),P=PQ(G[1]),q=PQ(G[2]),j=PQ(G[3]);for(let V=0;V<20;V+=2)J=J+K|0,E=X4(E^J,16),B=B+E|0,K=X4(K^B,12),J=J+K|0,E=X4(E^J,8),B=B+E|0,K=X4(K^B,7),W=W+H|0,P=X4(P^W,16),z=z+P|0,H=X4(H^z,12),W=W+H|0,P=X4(P^W,8),z=z+P|0,H=X4(H^z,7),Z=Z+U|0,q=X4(q^Z,16),O=O+q|0,U=X4(U^O,12),Z=Z+U|0,q=X4(q^Z,8),O=O+q|0,U=X4(U^O,7),$=$+N|0,j=X4(j^$,16),w=w+j|0,N=X4(N^w,12),$=$+N|0,j=X4(j^$,8),w=w+j|0,N=X4(N^w,7),J=J+H|0,j=X4(j^J,16),O=O+j|0,H=X4(H^O,12),J=J+H|0,j=X4(j^J,8),O=O+j|0,H=X4(H^O,7),W=W+U|0,E=X4(E^W,16),w=w+E|0,U=X4(U^w,12),W=W+U|0,E=X4(E^W,8),w=w+E|0,U=X4(U^w,7),Z=Z+N|0,P=X4(P^Z,16),B=B+P|0,N=X4(N^B,12),Z=Z+N|0,P=X4(P^Z,8),B=B+P|0,N=X4(N^B,7),$=$+K|0,q=X4(q^$,16),z=z+q|0,K=X4(K^z,12),$=$+K|0,q=X4(q^$,8),z=z+q|0,K=X4(K^z,7);let M=0;Q[M++]=J,Q[M++]=W,Q[M++]=Z,Q[M++]=$,Q[M++]=E,Q[M++]=P,Q[M++]=q,Q[M++]=j,kN(Q)}function ed0(X,Y,G,Q,J){if(J!==void 0)uX(J,void 0,"AAD");let W=X(Y,G,xD8),Z=dd0(Q.length,J?J.length:0,!0),$=rd0.create(W);if(J)sd0($,J);sd0($,Q),$.update(Z);let K=$.digest();return PF(W,Z),K}var bD8,yD8,sd0=(X,Y)=>{X.update(Y);let G=Y.length%16;if(G)X.update(yD8.subarray(G))},xD8,hD8=(X)=>(Y,G,Q)=>{return{encrypt(W,Z){let $=W.length;Z=S11($+16,Z,!1),Z.set(W);let K=Z.subarray(0,-16);X(Y,G,K,K,1);let H=ed0(X,Y,G,K,Q);return Z.set(H,$),PF(H),Z},decrypt(W,Z){Z=S11(W.length-16,Z,!1);let $=W.subarray(0,-16),K=W.subarray(-16),H=ed0(X,Y,G,$,Q);if(!ud0(K,H))throw PF(H),Error("invalid tag");return Z.set(W.subarray(0,-16)),X(Y,G,Z,Z,1),PF(H),Z}}},Uc;var xr1=D(()=>{ad0();od0();Fc();bD8=nd0(_D8,{counterRight:!1,counterLength:8,extendNonceFn:fD8,allowShortKeys:!1}),yD8=new Uint8Array(16),xD8=new Uint8Array(32);Uc=md0({blockSize:64,nonceLength:24,tagLength:16},hD8(bD8))});function gD8(X){return X instanceof Uint8Array||ArrayBuffer.isView(X)&&X.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in X&&X.BYTES_PER_ELEMENT===1}function TZ(X,Y=""){if(typeof X!=="number"){let G=Y&&`"${Y}" `;throw TypeError(`${G}expected number, got ${typeof X}`)}if(!Number.isSafeInteger(X)||X<0){let G=Y&&`"${Y}" `;throw RangeError(`${G}expected integer >= 0, got ${X}`)}}function MO(X,Y,G=""){let Q=gD8(X),J=X?.length,W=Y!==void 0;if(!Q||W&&J!==Y){let Z=G&&`"${G}" `,$=W?` of length ${Y}`:"",K=Q?`length=${J}`:`type=${typeof X}`,H=Z+"expected Uint8Array"+$+", got "+K;if(!Q)throw TypeError(H);throw RangeError(H)}return X}function wI(X){if(typeof X!=="function"||typeof X.create!=="function")throw TypeError("Hash must wrapped by utils.createHasher");if(TZ(X.outputLen),TZ(X.blockLen),X.outputLen<1)throw Error('"outputLen" must be >= 1');if(X.blockLen<1)throw Error('"blockLen" must be >= 1')}function Nc(X,Y=!0){if(X.destroyed)throw Error("Hash instance has been destroyed");if(Y&&X.finished)throw Error("Hash#digest() has already been called")}function rK1(X,Y){MO(X,void 0,"digestInto() output");let G=Y.outputLen;if(X.length<G)throw RangeError('"digestInto() output" expected to be of length >='+G)}function oK1(X){return new Uint32Array(X.buffer,X.byteOffset,Math.floor(X.byteLength/4))}function IZ(...X){for(let Y=0;Y<X.length;Y++)X[Y].fill(0)}function Bc(X){return new DataView(X.buffer,X.byteOffset,X.byteLength)}function qF(X,Y){return X<<32-Y|X>>>Y}function r5(X,Y){return X<<Y|X>>>32-Y>>>0}function lD8(X){return X<<24&4278190080|X<<8&16711680|X>>>8&65280|X>>>24&255}function mD8(X){for(let Y=0;Y<X.length;Y++)X[Y]=lD8(X[Y]);return X}function Xc0(X){if(X>=jO._0&&X<=jO._9)return X-jO._0;if(X>=jO.A&&X<=jO.F)return X-(jO.A-10);if(X>=jO.a&&X<=jO.f)return X-(jO.a-10);return}function Yc0(X){if(typeof X!=="string")throw TypeError("hex string expected, got "+typeof X);if(dD8)try{return Uint8Array.fromHex(X)}catch(J){if(J instanceof SyntaxError)throw RangeError(J.message);throw J}let Y=X.length,G=Y/2;if(Y%2)throw RangeError("hex string expected, got unpadded hex of length "+Y);let Q=new Uint8Array(G);for(let J=0,W=0;J<G;J++,W+=2){let Z=Xc0(X.charCodeAt(W)),$=Xc0(X.charCodeAt(W+1));if(Z===void 0||$===void 0){let K=X[W]+X[W+1];throw RangeError('hex string expected, got non-hex character "'+K+'" at index '+W)}Q[J]=Z*16+$}return Q}async function sK1(X,Y,G){let Q=Date.now();for(let J=0;J<X;J++){G(J);let W=Date.now()-Q;if(W>=0&&W<Y)continue;await cD8(),Q+=W}}function iD8(X){if(typeof X!=="string")throw TypeError("string expected");return new Uint8Array(new TextEncoder().encode(X))}function gr1(X,Y=""){if(typeof X==="string")return iD8(X);return MO(X,void 0,Y)}function eK1(X,Y){if(Y!==void 0&&{}.toString.call(Y)!=="[object Object]")throw TypeError("options must be object or undefined");return Object.assign(X,Y)}function Gc0(X,Y={}){let G=(J,W)=>X(W).update(J).digest(),Q=X(void 0);return G.outputLen=Q.outputLen,G.blockLen=Q.blockLen,G.canXOF=Q.canXOF,G.create=(J)=>X(J),Object.assign(G,Y),Object.freeze(G)}var uD8,hr1,dD8,jO,cD8=async()=>{},Qc0=(X)=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,X])});var HE=D(()=>{uD8=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();hr1=uD8?(X)=>X:mD8,dD8=(()=>typeof Uint8Array.from([]).toHex==="function"&&typeof Uint8Array.fromHex==="function")(),jO={_0:48,_9:57,A:65,F:70,a:97,f:102}});class ur1{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(X,Y){if(wI(X),MO(Y,void 0,"key"),this.iHash=X.create(),typeof this.iHash.update!=="function")throw Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let G=this.blockLen,Q=new Uint8Array(G);Q.set(Y.length>G?X.create().update(Y).digest():Y);for(let J=0;J<Q.length;J++)Q[J]^=54;this.iHash.update(Q),this.oHash=X.create();for(let J=0;J<Q.length;J++)Q[J]^=106;this.oHash.update(Q),IZ(Q)}update(X){return Nc(this),this.iHash.update(X),this}digestInto(X){Nc(this),rK1(X,this),this.finished=!0;let Y=X.subarray(0,this.outputLen);this.iHash.digestInto(Y),this.oHash.update(Y),this.oHash.digestInto(Y),this.destroy()}digest(){let X=new Uint8Array(this.oHash.outputLen);return this.digestInto(X),X}_cloneInto(X){X||=Object.create(Object.getPrototypeOf(this),{});let{oHash:Y,iHash:G,finished:Q,destroyed:J,blockLen:W,outputLen:Z}=this;return X=X,X.finished=Q,X.destroyed=J,X.blockLen=W,X.outputLen=Z,X.oHash=Y._cloneInto(X.oHash),X.iHash=G._cloneInto(X.iHash),X}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}var k11;var lr1=D(()=>{HE();k11=(()=>{let X=(Y,G,Q)=>new ur1(Y,G).update(Q).digest();return X.create=(Y,G)=>new ur1(Y,G),X})()});function pD8(X,Y,G){if(wI(X),G===void 0)G=new Uint8Array(X.outputLen);return k11(X,G,Y)}function nD8(X,Y,G,Q=32){wI(X),TZ(Q,"length"),MO(Y,void 0,"prk");let J=X.outputLen;if(Y.length<J)throw Error('"prk" must be at least HashLen octets');if(Q>255*J)throw Error("Length must be <= 255*HashLen");let W=Math.ceil(Q/J);if(G===void 0)G=Jc0;else MO(G,void 0,"info");let Z=new Uint8Array(W*J),$=k11.create(X,Y),K=$._cloneInto(),H=new Uint8Array($.outputLen);for(let U=0;U<W;U++)mr1[0]=U+1,K.update(U===0?Jc0:H).update(G).update(mr1).digestInto(H),Z.set(H,J*U),$._cloneInto(K);return $.destroy(),K.destroy(),IZ(H,mr1),Z.slice(0,Q)}var mr1,Jc0,zc=(X,Y,G,Q,J)=>nD8(X,pD8(X,Y,G),Q,J);var dr1=D(()=>{lr1();HE();mr1=Uint8Array.of(0),Jc0=Uint8Array.of()});function Zc0(X,Y,G){return X&Y^~X&G}function Wc0(X,Y,G){return X&Y^X&G^Y&G}class XH1{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(X,Y,G,Q){this.blockLen=X,this.outputLen=Y,this.padOffset=G,this.isLE=Q,this.buffer=new Uint8Array(X),this.view=Bc(this.buffer)}update(X){Nc(this),MO(X);let{view:Y,buffer:G,blockLen:Q}=this,J=X.length;for(let W=0;W<J;){let Z=Math.min(Q-this.pos,J-W);if(Z===Q){let $=Bc(X);for(;Q<=J-W;W+=Q)this.process($,W);continue}if(G.set(X.subarray(W,W+Z),this.pos),this.pos+=Z,W+=Z,this.pos===Q)this.process(Y,0),this.pos=0}return this.length+=X.length,this.roundClean(),this}digestInto(X){Nc(this),rK1(X,this),this.finished=!0;let{buffer:Y,view:G,blockLen:Q,isLE:J}=this,{pos:W}=this;if(Y[W++]=128,IZ(this.buffer.subarray(W)),this.padOffset>Q-W)this.process(G,0),W=0;for(let U=W;U<Q;U++)Y[U]=0;G.setBigUint64(Q-8,BigInt(this.length*8),J),this.process(G,0);let Z=Bc(X),$=this.outputLen;if($%4)throw Error("_sha2: outputLen must be aligned to 32bit");let K=$/4,H=this.get();if(K>H.length)throw Error("_sha2: outputLen bigger than state");for(let U=0;U<K;U++)Z.setUint32(4*U,H[U],J)}digest(){let{buffer:X,outputLen:Y}=this;this.digestInto(X);let G=X.slice(0,Y);return this.destroy(),G}_cloneInto(X){X||=new this.constructor,X.set(...this.get());let{blockLen:Y,buffer:G,length:Q,finished:J,destroyed:W,pos:Z}=this;if(X.destroyed=W,X.finished=J,X.length=Q,X.pos=Z,Q%Y)X.buffer.set(G);return X}clone(){return this._cloneInto()}}var RO,SO,AQ,TQ;var $c0=D(()=>{HE();RO=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),SO=Uint32Array.from([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]),AQ=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),TQ=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209])});function aD8(X,Y=!1){if(Y)return{h:Number(X&YH1),l:Number(X>>Kc0&YH1)};return{h:Number(X>>Kc0&YH1)|0,l:Number(X&YH1)|0}}function Hc0(X,Y=!1){let G=X.length,Q=new Uint32Array(G),J=new Uint32Array(G);for(let W=0;W<G;W++){let{h:Z,l:$}=aD8(X[W],Y);[Q[W],J[W]]=[Z,$]}return[Q,J]}function vN(X,Y,G,Q){let J=(Y>>>0)+(Q>>>0);return{h:X+G+(J/4294967296|0)|0,l:J|0}}var YH1,Kc0,cr1=(X,Y,G)=>X>>>G,ir1=(X,Y,G)=>X<<32-G|Y>>>G,LI=(X,Y,G)=>X>>>G|Y<<32-G,EI=(X,Y,G)=>X<<32-G|Y>>>G,v11=(X,Y,G)=>X<<64-G|Y>>>G-32,_11=(X,Y,G)=>X>>>G-32|Y<<64-G,Fc0=(X,Y,G)=>(X>>>0)+(Y>>>0)+(G>>>0),Uc0=(X,Y,G,Q)=>Y+G+Q+(X/4294967296|0)|0,Nc0=(X,Y,G,Q)=>(X>>>0)+(Y>>>0)+(G>>>0)+(Q>>>0),Bc0=(X,Y,G,Q,J)=>Y+G+Q+J+(X/4294967296|0)|0,zc0=(X,Y,G,Q,J)=>(X>>>0)+(Y>>>0)+(G>>>0)+(Q>>>0)+(J>>>0),Oc0=(X,Y,G,Q,J,W)=>Y+G+Q+J+W+(X/4294967296|0)|0;var Dc0=D(()=>{YH1=BigInt(4294967295),Kc0=BigInt(32)});var rD8,FE,pr1,wc0,oD8,Lc0,sD8,eD8,UE,NE,f11,Xw8,Yw8,PJ,qJ,Gw8,Qw8,CO;var GH1=D(()=>{$c0();Dc0();HE();rD8=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),FE=new Uint32Array(64);pr1=class pr1 extends XH1{constructor(X){super(64,X,8,!1)}get(){let{A:X,B:Y,C:G,D:Q,E:J,F:W,G:Z,H:$}=this;return[X,Y,G,Q,J,W,Z,$]}set(X,Y,G,Q,J,W,Z,$){this.A=X|0,this.B=Y|0,this.C=G|0,this.D=Q|0,this.E=J|0,this.F=W|0,this.G=Z|0,this.H=$|0}process(X,Y){for(let U=0;U<16;U++,Y+=4)FE[U]=X.getUint32(Y,!1);for(let U=16;U<64;U++){let N=FE[U-15],B=FE[U-2],z=qF(N,7)^qF(N,18)^N>>>3,O=qF(B,17)^qF(B,19)^B>>>10;FE[U]=O+FE[U-7]+z+FE[U-16]|0}let{A:G,B:Q,C:J,D:W,E:Z,F:$,G:K,H}=this;for(let U=0;U<64;U++){let N=qF(Z,6)^qF(Z,11)^qF(Z,25),B=H+N+Zc0(Z,$,K)+rD8[U]+FE[U]|0,O=(qF(G,2)^qF(G,13)^qF(G,22))+Wc0(G,Q,J)|0;H=K,K=$,$=Z,Z=W+B|0,W=J,J=Q,Q=G,G=B+O|0}G=G+this.A|0,Q=Q+this.B|0,J=J+this.C|0,W=W+this.D|0,Z=Z+this.E|0,$=$+this.F|0,K=K+this.G|0,H=H+this.H|0,this.set(G,Q,J,W,Z,$,K,H)}roundClean(){IZ(FE)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),IZ(this.buffer)}};wc0=class wc0 extends pr1{A=RO[0]|0;B=RO[1]|0;C=RO[2]|0;D=RO[3]|0;E=RO[4]|0;F=RO[5]|0;G=RO[6]|0;H=RO[7]|0;constructor(){super(32)}};oD8=class oD8 extends pr1{A=SO[0]|0;B=SO[1]|0;C=SO[2]|0;D=SO[3]|0;E=SO[4]|0;F=SO[5]|0;G=SO[6]|0;H=SO[7]|0;constructor(){super(28)}};Lc0=(()=>Hc0(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map((X)=>BigInt(X))))(),sD8=(()=>Lc0[0])(),eD8=(()=>Lc0[1])(),UE=new Uint32Array(80),NE=new Uint32Array(80);f11=class f11 extends XH1{constructor(X){super(128,X,16,!1)}get(){let{Ah:X,Al:Y,Bh:G,Bl:Q,Ch:J,Cl:W,Dh:Z,Dl:$,Eh:K,El:H,Fh:U,Fl:N,Gh:B,Gl:z,Hh:O,Hl:w}=this;return[X,Y,G,Q,J,W,Z,$,K,H,U,N,B,z,O,w]}set(X,Y,G,Q,J,W,Z,$,K,H,U,N,B,z,O,w){this.Ah=X|0,this.Al=Y|0,this.Bh=G|0,this.Bl=Q|0,this.Ch=J|0,this.Cl=W|0,this.Dh=Z|0,this.Dl=$|0,this.Eh=K|0,this.El=H|0,this.Fh=U|0,this.Fl=N|0,this.Gh=B|0,this.Gl=z|0,this.Hh=O|0,this.Hl=w|0}process(X,Y){for(let q=0;q<16;q++,Y+=4)UE[q]=X.getUint32(Y),NE[q]=X.getUint32(Y+=4);for(let q=16;q<80;q++){let j=UE[q-15]|0,M=NE[q-15]|0,V=LI(j,M,1)^LI(j,M,8)^cr1(j,M,7),R=EI(j,M,1)^EI(j,M,8)^ir1(j,M,7),k=UE[q-2]|0,_=NE[q-2]|0,v=LI(k,_,19)^v11(k,_,61)^cr1(k,_,6),y=EI(k,_,19)^_11(k,_,61)^ir1(k,_,6),h=Nc0(R,y,NE[q-7],NE[q-16]),i=Bc0(h,V,v,UE[q-7],UE[q-16]);UE[q]=i|0,NE[q]=h|0}let{Ah:G,Al:Q,Bh:J,Bl:W,Ch:Z,Cl:$,Dh:K,Dl:H,Eh:U,El:N,Fh:B,Fl:z,Gh:O,Gl:w,Hh:E,Hl:P}=this;for(let q=0;q<80;q++){let j=LI(U,N,14)^LI(U,N,18)^v11(U,N,41),M=EI(U,N,14)^EI(U,N,18)^_11(U,N,41),V=U&B^~U&O,R=N&z^~N&w,k=zc0(P,M,R,eD8[q],NE[q]),_=Oc0(k,E,j,V,sD8[q],UE[q]),v=k|0,y=LI(G,Q,28)^v11(G,Q,34)^v11(G,Q,39),h=EI(G,Q,28)^_11(G,Q,34)^_11(G,Q,39),i=G&J^G&Z^J&Z,p=Q&W^Q&$^W&$;E=O|0,P=w|0,O=B|0,w=z|0,B=U|0,z=N|0,{h:U,l:N}=vN(K|0,H|0,_|0,v|0),K=Z|0,H=$|0,Z=J|0,$=W|0,J=G|0,W=Q|0;let f=Fc0(v,h,p);G=Uc0(f,_,y,i),Q=f|0}({h:G,l:Q}=vN(this.Ah|0,this.Al|0,G|0,Q|0)),{h:J,l:W}=vN(this.Bh|0,this.Bl|0,J|0,W|0),{h:Z,l:$}=vN(this.Ch|0,this.Cl|0,Z|0,$|0),{h:K,l:H}=vN(this.Dh|0,this.Dl|0,K|0,H|0),{h:U,l:N}=vN(this.Eh|0,this.El|0,U|0,N|0),{h:B,l:z}=vN(this.Fh|0,this.Fl|0,B|0,z|0),{h:O,l:w}=vN(this.Gh|0,this.Gl|0,O|0,w|0),{h:E,l:P}=vN(this.Hh|0,this.Hl|0,E|0,P|0),this.set(G,Q,J,W,Z,$,K,H,U,N,B,z,O,w,E,P)}roundClean(){IZ(UE,NE)}destroy(){this.destroyed=!0,IZ(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};Xw8=class Xw8 extends f11{Ah=TQ[0]|0;Al=TQ[1]|0;Bh=TQ[2]|0;Bl=TQ[3]|0;Ch=TQ[4]|0;Cl=TQ[5]|0;Dh=TQ[6]|0;Dl=TQ[7]|0;Eh=TQ[8]|0;El=TQ[9]|0;Fh=TQ[10]|0;Fl=TQ[11]|0;Gh=TQ[12]|0;Gl=TQ[13]|0;Hh=TQ[14]|0;Hl=TQ[15]|0;constructor(){super(64)}};Yw8=class Yw8 extends f11{Ah=AQ[0]|0;Al=AQ[1]|0;Bh=AQ[2]|0;Bl=AQ[3]|0;Ch=AQ[4]|0;Cl=AQ[5]|0;Dh=AQ[6]|0;Dl=AQ[7]|0;Eh=AQ[8]|0;El=AQ[9]|0;Fh=AQ[10]|0;Fl=AQ[11]|0;Gh=AQ[12]|0;Gl=AQ[13]|0;Hh=AQ[14]|0;Hl=AQ[15]|0;constructor(){super(48)}};PJ=Uint32Array.from([2352822216,424955298,1944164710,2312950998,502970286,855612546,1738396948,1479516111,258812777,2077511080,2011393907,79989058,1067287976,1780299464,286451373,2446758561]),qJ=Uint32Array.from([573645204,4230739756,2673172387,3360449730,596883563,1867755857,2520282905,1497426621,2519219938,2827943907,3193839141,1401305490,721525244,746961066,246885852,2177182882]);Gw8=class Gw8 extends f11{Ah=PJ[0]|0;Al=PJ[1]|0;Bh=PJ[2]|0;Bl=PJ[3]|0;Ch=PJ[4]|0;Cl=PJ[5]|0;Dh=PJ[6]|0;Dl=PJ[7]|0;Eh=PJ[8]|0;El=PJ[9]|0;Fh=PJ[10]|0;Fl=PJ[11]|0;Gh=PJ[12]|0;Gl=PJ[13]|0;Hh=PJ[14]|0;Hl=PJ[15]|0;constructor(){super(28)}};Qw8=class Qw8 extends f11{Ah=qJ[0]|0;Al=qJ[1]|0;Bh=qJ[2]|0;Bl=qJ[3]|0;Ch=qJ[4]|0;Cl=qJ[5]|0;Dh=qJ[6]|0;Dl=qJ[7]|0;Eh=qJ[8]|0;El=qJ[9]|0;Fh=qJ[10]|0;Fl=qJ[11]|0;Gh=qJ[12]|0;Gl=qJ[13]|0;Hh=qJ[14]|0;Hl=qJ[15]|0;constructor(){super(32)}};CO=Gc0(()=>new wc0,Qc0(1))});function vY(...X){let Y=X.reduce((J,{length:W})=>J+W,0),G=new Uint8Array(Y),Q=0;for(let J of X)G.set(J,Q),Q+=J.length;return G}function nr1(X,Y,G){if(Y<0||Y>=4294967296)throw RangeError(`value must be >= 0 and <= 4294967295. Received ${Y}`);X.set([Y>>>24,Y>>>16,Y>>>8,Y&255],G)}function ar1(X){let Y=Math.floor(X/4294967296),G=X%4294967296,Q=new Uint8Array(8);return nr1(Q,Y,0),nr1(Q,G,4),Q}function QH1(X){let Y=new Uint8Array(4);return nr1(Y,X),Y}function nX(X){let Y=new Uint8Array(X.length);for(let G=0;G<X.length;G++){let Q=X.charCodeAt(G);if(Q>127)throw TypeError("non-ASCII string encountered in encode()");Y[G]=Q}return Y}var PI,IQ;var AJ=D(()=>{PI=new TextEncoder,IQ=new TextDecoder});function Ec0(X){if(Uint8Array.prototype.toBase64)return X.toBase64();let Y=32768,G=[];for(let Q=0;Q<X.length;Q+=Y)G.push(String.fromCharCode.apply(null,X.subarray(Q,Q+Y)));return btoa(G.join(""))}function Pc0(X){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(X);let Y=atob(X),G=new Uint8Array(Y.length);for(let Q=0;Q<Y.length;Q++)G[Q]=Y.charCodeAt(Q);return G}var BE={};R0(BE,{encode:()=>NX,decode:()=>VZ});function VZ(X){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof X==="string"?X:IQ.decode(X),{alphabet:"base64url"});let Y=X;if(Y instanceof Uint8Array)Y=IQ.decode(Y);Y=Y.replace(/-/g,"+").replace(/_/g,"/");try{return Pc0(Y)}catch{throw TypeError("The input to be decoded is not correctly encoded.")}}function NX(X){let Y=X;if(typeof Y==="string")Y=PI.encode(Y);if(Uint8Array.prototype.toBase64)return Y.toBase64({alphabet:"base64url",omitPadding:!0});return Ec0(Y).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}var TJ=D(()=>{AJ()});function Jw8(X){return parseInt(X.name.slice(4),10)}function JH1(X,Y){if(Jw8(X.hash)!==Y)throw jZ(`SHA-${Y}`,"algorithm.hash")}function Zw8(X){switch(X){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw Error("unreachable")}}function qc0(X,Y){if(Y&&!X.usages.includes(Y))throw TypeError(`CryptoKey does not support this operation, its usages must include ${Y}.`)}function Ac0(X,Y,G){switch(Y){case"HS256":case"HS384":case"HS512":{if(!_N(X.algorithm,"HMAC"))throw jZ("HMAC");JH1(X.algorithm,parseInt(Y.slice(2),10));break}case"RS256":case"RS384":case"RS512":{if(!_N(X.algorithm,"RSASSA-PKCS1-v1_5"))throw jZ("RSASSA-PKCS1-v1_5");JH1(X.algorithm,parseInt(Y.slice(2),10));break}case"PS256":case"PS384":case"PS512":{if(!_N(X.algorithm,"RSA-PSS"))throw jZ("RSA-PSS");JH1(X.algorithm,parseInt(Y.slice(2),10));break}case"Ed25519":case"EdDSA":{if(!_N(X.algorithm,"Ed25519"))throw jZ("Ed25519");break}case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":{if(!_N(X.algorithm,Y))throw jZ(Y);break}case"ES256":case"ES384":case"ES512":{if(!_N(X.algorithm,"ECDSA"))throw jZ("ECDSA");let Q=Zw8(Y);if(X.algorithm.namedCurve!==Q)throw jZ(Q,"algorithm.namedCurve");break}default:throw TypeError("CryptoKey does not support this operation")}qc0(X,G)}function Q$(X,Y,G){switch(Y){case"A128GCM":case"A192GCM":case"A256GCM":{if(!_N(X.algorithm,"AES-GCM"))throw jZ("AES-GCM");let Q=parseInt(Y.slice(1,4),10);if(X.algorithm.length!==Q)throw jZ(Q,"algorithm.length");break}case"A128KW":case"A192KW":case"A256KW":{if(!_N(X.algorithm,"AES-KW"))throw jZ("AES-KW");let Q=parseInt(Y.slice(1,4),10);if(X.algorithm.length!==Q)throw jZ(Q,"algorithm.length");break}case"ECDH":{switch(X.algorithm.name){case"ECDH":case"X25519":break;default:throw jZ("ECDH or X25519")}break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":if(!_N(X.algorithm,"PBKDF2"))throw jZ("PBKDF2");break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{if(!_N(X.algorithm,"RSA-OAEP"))throw jZ("RSA-OAEP");JH1(X.algorithm,parseInt(Y.slice(9),10)||1);break}default:throw TypeError("CryptoKey does not support this operation")}qc0(X,G)}var jZ=(X,Y="algorithm.name")=>TypeError(`CryptoKey does not support this operation, its ${Y} must be ${X}`),_N=(X,Y)=>X.name===Y;function Tc0(X,Y,...G){if(G=G.filter(Boolean),G.length>2){let Q=G.pop();X+=`one of type ${G.join(", ")}, or ${Q}.`}else if(G.length===2)X+=`one of type ${G[0]} or ${G[1]}.`;else X+=`of type ${G[0]}.`;if(Y==null)X+=` Received ${Y}`;else if(typeof Y==="function"&&Y.name)X+=` Received function ${Y.name}`;else if(typeof Y==="object"&&Y!=null){if(Y.constructor?.name)X+=` Received an instance of ${Y.constructor.name}`}return X}var fN=(X,...Y)=>Tc0("Key must be ",X,...Y),tr1=(X,Y,...G)=>Tc0(`Key for the ${X} algorithm must be `,Y,...G);var CG,IJ,zE,Oc,I8,b11,Y4,v7,MZ,rr1,ZH1,y11,or1,sr1,er1;var _7=D(()=>{CG=class CG extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(X,Y){super(X,Y);this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}};IJ=class IJ extends CG{static code="ERR_JWT_CLAIM_VALIDATION_FAILED";code="ERR_JWT_CLAIM_VALIDATION_FAILED";claim;reason;payload;constructor(X,Y,G="unspecified",Q="unspecified"){super(X,{cause:{claim:G,reason:Q,payload:Y}});this.claim=G,this.reason=Q,this.payload=Y}};zE=class zE extends CG{static code="ERR_JWT_EXPIRED";code="ERR_JWT_EXPIRED";claim;reason;payload;constructor(X,Y,G="unspecified",Q="unspecified"){super(X,{cause:{claim:G,reason:Q,payload:Y}});this.claim=G,this.reason=Q,this.payload=Y}};Oc=class Oc extends CG{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"};I8=class I8 extends CG{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"};b11=class b11 extends CG{static code="ERR_JWE_DECRYPTION_FAILED";code="ERR_JWE_DECRYPTION_FAILED";constructor(X="decryption operation failed",Y){super(X,Y)}};Y4=class Y4 extends CG{static code="ERR_JWE_INVALID";code="ERR_JWE_INVALID"};v7=class v7 extends CG{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"};MZ=class MZ extends CG{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"};rr1=class rr1 extends CG{static code="ERR_JWK_INVALID";code="ERR_JWK_INVALID"};ZH1=class ZH1 extends CG{static code="ERR_JWKS_INVALID";code="ERR_JWKS_INVALID"};y11=class y11 extends CG{static code="ERR_JWKS_NO_MATCHING_KEY";code="ERR_JWKS_NO_MATCHING_KEY";constructor(X="no applicable key found in the JSON Web Key Set",Y){super(X,Y)}};or1=class or1 extends CG{[Symbol.asyncIterator];static code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";constructor(X="multiple matching keys found in the JSON Web Key Set",Y){super(X,Y)}};sr1=class sr1 extends CG{static code="ERR_JWKS_TIMEOUT";code="ERR_JWKS_TIMEOUT";constructor(X="request timed out",Y){super(X,Y)}};er1=class er1 extends CG{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(X="signature verification failed",Y){super(X,Y)}}});function Dc(X){if(!kO(X))throw Error("CryptoKey instance expected")}var kO=(X)=>{if(X?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return X instanceof CryptoKey}catch{return!1}},x11=(X)=>X?.[Symbol.toStringTag]==="KeyObject",h11=(X)=>kO(X)||x11(X);function $H1(X){switch(X){case"A128GCM":return 128;case"A192GCM":return 192;case"A256GCM":case"A128CBC-HS256":return 256;case"A192CBC-HS384":return 384;case"A256CBC-HS512":return 512;default:throw new I8(`Unsupported JWE Algorithm: ${X}`)}}function WH1(X,Y){let G=X.byteLength<<3;if(G!==Y)throw new Y4(`Invalid Content Encryption Key length. Expected ${Y} bits, got ${G} bits`)}function Ic0(X){switch(X){case"A128GCM":case"A128GCMKW":case"A192GCM":case"A192GCMKW":case"A256GCM":case"A256GCMKW":return 96;case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return 128;default:throw new I8(`Unsupported JWE Algorithm: ${X}`)}}function Vc0(X,Y){if(Y.length<<3!==Ic0(X))throw new Y4("Invalid Initialization Vector length")}async function jc0(X,Y,G){if(!(Y instanceof Uint8Array))throw TypeError(fN(Y,"Uint8Array"));let Q=parseInt(X.slice(1,4),10),J=await crypto.subtle.importKey("raw",Y.subarray(Q>>3),"AES-CBC",!1,[G]),W=await crypto.subtle.importKey("raw",Y.subarray(0,Q>>3),{hash:`SHA-${Q<<1}`,name:"HMAC"},!1,["sign"]);return{encKey:J,macKey:W,keySize:Q}}async function Mc0(X,Y,G){return new Uint8Array((await crypto.subtle.sign("HMAC",X,Y)).slice(0,G>>3))}async function $w8(X,Y,G,Q,J){let{encKey:W,macKey:Z,keySize:$}=await jc0(X,G,"encrypt"),K=new Uint8Array(await crypto.subtle.encrypt({iv:Q,name:"AES-CBC"},W,Y)),H=vY(J,Q,K,ar1(J.length<<3)),U=await Mc0(Z,H,$);return{ciphertext:K,tag:U,iv:Q}}async function Kw8(X,Y){if(!(X instanceof Uint8Array))throw TypeError("First argument must be a buffer");if(!(Y instanceof Uint8Array))throw TypeError("Second argument must be a buffer");let G={name:"HMAC",hash:"SHA-256"},Q=await crypto.subtle.generateKey(G,!1,["sign"]),J=new Uint8Array(await crypto.subtle.sign(G,Q,X)),W=new Uint8Array(await crypto.subtle.sign(G,Q,Y)),Z=0,$=-1;while(++$<32)Z|=J[$]^W[$];return Z===0}async function Hw8(X,Y,G,Q,J,W){let{encKey:Z,macKey:$,keySize:K}=await jc0(X,Y,"decrypt"),H=vY(W,Q,G,ar1(W.length<<3)),U=await Mc0($,H,K),N;try{N=await Kw8(J,U)}catch{}if(!N)throw new b11;let B;try{B=new Uint8Array(await crypto.subtle.decrypt({iv:Q,name:"AES-CBC"},Z,G))}catch{}if(!B)throw new b11;return B}async function Fw8(X,Y,G,Q,J){let W;if(G instanceof Uint8Array)W=await crypto.subtle.importKey("raw",G,"AES-GCM",!1,["encrypt"]);else Q$(G,X,"encrypt"),W=G;let Z=new Uint8Array(await crypto.subtle.encrypt({additionalData:J,iv:Q,name:"AES-GCM",tagLength:128},W,Y)),$=Z.slice(-16);return{ciphertext:Z.slice(0,-16),tag:$,iv:Q}}async function Uw8(X,Y,G,Q,J,W){let Z;if(Y instanceof Uint8Array)Z=await crypto.subtle.importKey("raw",Y,"AES-GCM",!1,["decrypt"]);else Q$(Y,X,"decrypt"),Z=Y;try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:W,iv:Q,name:"AES-GCM",tagLength:128},Z,vY(G,J)))}catch{throw new b11}}async function KH1(X,Y,G,Q,J){if(!kO(G)&&!(G instanceof Uint8Array))throw TypeError(fN(G,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(Q)Vc0(X,Q);else Q=Ww8(X);switch(X){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":if(G instanceof Uint8Array)WH1(G,parseInt(X.slice(-3),10));return $w8(X,Y,G,Q,J);case"A128GCM":case"A192GCM":case"A256GCM":if(G instanceof Uint8Array)WH1(G,parseInt(X.slice(1,4),10));return Fw8(X,Y,G,Q,J);default:throw new I8(Rc0)}}async function HH1(X,Y,G,Q,J,W){if(!kO(Y)&&!(Y instanceof Uint8Array))throw TypeError(fN(Y,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(!Q)throw new Y4("JWE Initialization Vector missing");if(!J)throw new Y4("JWE Authentication Tag missing");switch(Vc0(X,Q),X){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":if(Y instanceof Uint8Array)WH1(Y,parseInt(X.slice(-3),10));return Hw8(X,Y,G,Q,J,W);case"A128GCM":case"A192GCM":case"A256GCM":if(Y instanceof Uint8Array)WH1(Y,parseInt(X.slice(1,4),10));return Uw8(X,Y,G,Q,J,W);default:throw new I8(Rc0)}}var OE=(X)=>crypto.getRandomValues(new Uint8Array($H1(X)>>3)),Ww8=(X)=>crypto.getRandomValues(new Uint8Array(Ic0(X)>>3)),Rc0="Unsupported JWE Content Encryption Algorithm";var wc=D(()=>{AJ();_7()});function RZ(X,Y){if(X)throw TypeError(`${Y} can only be called once`)}function SZ(X,Y,G){try{return VZ(X)}catch{throw new G(`Failed to base64url decode the ${Y}`)}}async function FH1(X,Y){let G=`SHA-${X.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(G,Y))}var Sc0;var vO=D(()=>{TJ();Sc0=Symbol()});function BX(X){if(!Nw8(X)||Object.prototype.toString.call(X)!=="[object Object]")return!1;if(Object.getPrototypeOf(X)===null)return!0;let Y=X;while(Object.getPrototypeOf(Y)!==null)Y=Object.getPrototypeOf(Y);return Object.getPrototypeOf(X)===Y}function DE(...X){let Y=X.filter(Boolean);if(Y.length===0||Y.length===1)return!0;let G;for(let Q of Y){let J=Object.keys(Q);if(!G||G.size===0){G=new Set(J);continue}for(let W of J){if(G.has(W))return!1;G.add(W)}}return!0}var Nw8=(X)=>typeof X==="object"&&X!==null,qI=(X)=>BX(X)&&typeof X.kty==="string",Cc0=(X)=>X.kty!=="oct"&&(X.kty==="AKP"&&typeof X.priv==="string"||typeof X.d==="string"),kc0=(X)=>X.kty!=="oct"&&X.d===void 0&&X.priv===void 0,vc0=(X)=>X.kty==="oct"&&typeof X.k==="string";function _c0(X,Y){if(X.algorithm.length!==parseInt(Y.slice(1,4),10))throw TypeError(`Invalid key size for alg: ${Y}`)}function fc0(X,Y,G){if(X instanceof Uint8Array)return crypto.subtle.importKey("raw",X,"AES-KW",!0,[G]);return Q$(X,Y,G),X}async function g11(X,Y,G){let Q=await fc0(Y,X,"wrapKey");_c0(Q,X);let J=await crypto.subtle.importKey("raw",G,{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.wrapKey("raw",J,Q,"AES-KW"))}async function u11(X,Y,G){let Q=await fc0(Y,X,"unwrapKey");_c0(Q,X);let J=await crypto.subtle.unwrapKey("raw",G,Q,"AES-KW",{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.exportKey("raw",J))}var Xo1=()=>{};function Yo1(X){return vY(QH1(X.length),X)}async function zw8(X,Y,G){let Q=Y>>3,J=32,W=Math.ceil(Q/32),Z=new Uint8Array(W*32);for(let $=1;$<=W;$++){let K=new Uint8Array(4+X.length+G.length);K.set(QH1($),0),K.set(X,4),K.set(G,4+X.length);let H=await FH1("sha256",K);Z.set(H,($-1)*32)}return Z.slice(0,Q)}async function Go1(X,Y,G,Q,J=new Uint8Array,W=new Uint8Array){Q$(X,"ECDH"),Q$(Y,"ECDH","deriveBits");let Z=Yo1(nX(G)),$=Yo1(J),K=Yo1(W),H=QH1(Q),U=new Uint8Array,N=vY(Z,$,K,H,U),B=new Uint8Array(await crypto.subtle.deriveBits({name:X.algorithm.name,public:X},Y,Ow8(X)));return zw8(B,Q,N)}function Ow8(X){if(X.algorithm.name==="X25519")return 256;return Math.ceil(parseInt(X.algorithm.namedCurve.slice(-3),10)/8)<<3}function Qo1(X){switch(X.algorithm.namedCurve){case"P-256":case"P-384":case"P-521":return!0;default:return X.algorithm.name==="X25519"}}var yc0=D(()=>{AJ();vO()});function ww8(X,Y){if(X instanceof Uint8Array)return crypto.subtle.importKey("raw",X,"PBKDF2",!1,["deriveBits"]);return Q$(X,Y,"deriveBits"),X}async function xc0(X,Y,G,Q){if(!(X instanceof Uint8Array)||X.length<8)throw new Y4("PBES2 Salt Input must be 8 or more octets");if(!Number.isSafeInteger(G)||Math.sign(G)!==1)throw new Y4("PBES2 Count Input must be a positive integer");let J=Lw8(Y,X),W=parseInt(Y.slice(13,16),10),Z={hash:`SHA-${Y.slice(8,11)}`,iterations:G,name:"PBKDF2",salt:J},$=await ww8(Q,Y);return new Uint8Array(await crypto.subtle.deriveBits(Z,$,W))}async function hc0(X,Y,G,Q=2048,J=crypto.getRandomValues(new Uint8Array(16))){let W=await xc0(J,X,Q,Y);return{encryptedKey:await g11(X.slice(-6),W,G),p2c:Q,p2s:NX(J)}}async function gc0(X,Y,G,Q,J){let W=await xc0(J,X,Q,Y);return u11(X.slice(-6),W,G)}var Lw8=(X,Y)=>vY(nX(X),Uint8Array.of(0),Y);var uc0=D(()=>{TJ();Xo1();AJ();_7()});function l11(X,Y){if(X.startsWith("RS")||X.startsWith("PS")){let{modulusLength:G}=Y.algorithm;if(typeof G!=="number"||G<2048)throw TypeError(`${X} requires key modulusLength to be 2048 bits or larger`)}}function lc0(X,Y){let G=`SHA-${X.slice(-3)}`;switch(X){case"HS256":case"HS384":case"HS512":return{hash:G,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:G,name:"RSA-PSS",saltLength:parseInt(X.slice(-3),10)>>3};case"RS256":case"RS384":case"RS512":return{hash:G,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:G,name:"ECDSA",namedCurve:Y.namedCurve};case"Ed25519":case"EdDSA":return{name:"Ed25519"};case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":return{name:X};default:throw new I8(`alg ${X} is not supported either by JOSE or your javascript runtime`)}}async function mc0(X,Y,G){if(Y instanceof Uint8Array){if(!X.startsWith("HS"))throw TypeError(fN(Y,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",Y,{hash:`SHA-${X.slice(-3)}`,name:"HMAC"},!1,[G])}return Ac0(Y,X,G),Y}async function dc0(X,Y,G){let Q=await mc0(X,Y,"sign");l11(X,Q);let J=await crypto.subtle.sign(lc0(X,Q.algorithm),Q,G);return new Uint8Array(J)}async function cc0(X,Y,G,Q){let J=await mc0(X,Y,"verify");l11(X,J);let W=lc0(X,J.algorithm);try{return await crypto.subtle.verify(W,J,G,Q)}catch{return!1}}var UH1=D(()=>{_7()});async function pc0(X,Y,G){return Q$(Y,X,"encrypt"),l11(X,Y),new Uint8Array(await crypto.subtle.encrypt(ic0(X),Y,G))}async function nc0(X,Y,G){return Q$(Y,X,"decrypt"),l11(X,Y),new Uint8Array(await crypto.subtle.decrypt(ic0(X),Y,G))}var ic0=(X)=>{switch(X){case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":return"RSA-OAEP";default:throw new I8(`alg ${X} is not supported either by JOSE or your javascript runtime`)}};var ac0=D(()=>{UH1();_7()});function qw8(X){let Y,G;switch(X.kty){case"AKP":{switch(X.alg){case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":Y={name:X.alg},G=X.priv?["sign"]:["verify"];break;default:throw new I8(NH1)}break}case"RSA":{switch(X.alg){case"PS256":case"PS384":case"PS512":Y={name:"RSA-PSS",hash:`SHA-${X.alg.slice(-3)}`},G=X.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":Y={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${X.alg.slice(-3)}`},G=X.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":Y={name:"RSA-OAEP",hash:`SHA-${parseInt(X.alg.slice(-3),10)||1}`},G=X.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new I8(NH1)}break}case"EC":{switch(X.alg){case"ES256":case"ES384":case"ES512":Y={name:"ECDSA",namedCurve:{ES256:"P-256",ES384:"P-384",ES512:"P-521"}[X.alg]},G=X.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":Y={name:"ECDH",namedCurve:X.crv},G=X.d?["deriveBits"]:[];break;default:throw new I8(NH1)}break}case"OKP":{switch(X.alg){case"Ed25519":case"EdDSA":Y={name:"Ed25519"},G=X.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":Y={name:X.crv},G=X.d?["deriveBits"]:[];break;default:throw new I8(NH1)}break}default:throw new I8('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:Y,keyUsages:G}}async function Lc(X){if(!X.alg)throw TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:Y,keyUsages:G}=qw8(X),Q={...X};if(Q.kty!=="AKP")delete Q.alg;return delete Q.use,crypto.subtle.importKey("jwk",Q,Y,X.ext??(X.d||X.priv?!1:!0),X.key_ops??G)}var NH1='Invalid or unsupported JWK "alg" (Algorithm) Parameter value';var Jo1=D(()=>{_7()});async function bN(X,Y){if(X instanceof Uint8Array)return X;if(kO(X))return X;if(x11(X)){if(X.type==="secret")return X.export();if("toCryptoKey"in X&&typeof X.toCryptoKey==="function")try{return Aw8(X,Y)}catch(Q){if(Q instanceof TypeError)throw Q}let G=X.export({format:"jwk"});return tc0(X,G,Y)}if(qI(X)){if(X.k)return VZ(X.k);return tc0(X,X,Y,!0)}throw Error("unreachable")}var Ec="given KeyObject instance cannot be used for this algorithm",Pc,tc0=async(X,Y,G,Q=!1)=>{Pc||=new WeakMap;let J=Pc.get(X);if(J?.[G])return J[G];let W=await Lc({...Y,alg:G});if(Q)Object.freeze(X);if(!J)Pc.set(X,{[G]:W});else J[G]=W;return W},Aw8=(X,Y)=>{Pc||=new WeakMap;let G=Pc.get(X);if(G?.[Y])return G[Y];let Q=X.type==="public",J=Q?!0:!1,W;if(X.asymmetricKeyType==="x25519"){switch(Y){case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":break;default:throw TypeError(Ec)}W=X.toCryptoKey(X.asymmetricKeyType,J,Q?[]:["deriveBits"])}if(X.asymmetricKeyType==="ed25519"){if(Y!=="EdDSA"&&Y!=="Ed25519")throw TypeError(Ec);W=X.toCryptoKey(X.asymmetricKeyType,J,[Q?"verify":"sign"])}switch(X.asymmetricKeyType){case"ml-dsa-44":case"ml-dsa-65":case"ml-dsa-87":{if(Y!==X.asymmetricKeyType.toUpperCase())throw TypeError(Ec);W=X.toCryptoKey(X.asymmetricKeyType,J,[Q?"verify":"sign"])}}if(X.asymmetricKeyType==="rsa"){let Z;switch(Y){case"RSA-OAEP":Z="SHA-1";break;case"RS256":case"PS256":case"RSA-OAEP-256":Z="SHA-256";break;case"RS384":case"PS384":case"RSA-OAEP-384":Z="SHA-384";break;case"RS512":case"PS512":case"RSA-OAEP-512":Z="SHA-512";break;default:throw TypeError(Ec)}if(Y.startsWith("RSA-OAEP"))return X.toCryptoKey({name:"RSA-OAEP",hash:Z},J,Q?["encrypt"]:["decrypt"]);W=X.toCryptoKey({name:Y.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:Z},J,[Q?"verify":"sign"])}if(X.asymmetricKeyType==="ec"){let $=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(X.asymmetricKeyDetails?.namedCurve);if(!$)throw TypeError(Ec);let K={ES256:"P-256",ES384:"P-384",ES512:"P-521"};if(K[Y]&&$===K[Y])W=X.toCryptoKey({name:"ECDSA",namedCurve:$},J,[Q?"verify":"sign"]);if(Y.startsWith("ECDH-ES"))W=X.toCryptoKey({name:"ECDH",namedCurve:$},J,Q?[]:["deriveBits"])}if(!W)throw TypeError(Ec);if(!G)Pc.set(X,{[Y]:W});else G[Y]=W;return W};var qc=D(()=>{TJ();Jo1()});async function u3(X,Y,G){if(!BX(X))throw TypeError("JWK must be an object");let Q;switch(Y??=X.alg,Q??=G?.extractable??X.ext,X.kty){case"oct":if(typeof X.k!=="string"||!X.k)throw TypeError('missing "k" (Key Value) Parameter value');return VZ(X.k);case"RSA":if("oth"in X&&X.oth!==void 0)throw new I8('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');return Lc({...X,alg:Y,ext:Q});case"AKP":{if(typeof X.alg!=="string"||!X.alg)throw TypeError('missing "alg" (Algorithm) Parameter value');if(Y!==void 0&&Y!==X.alg)throw TypeError("JWK alg and alg option value mismatch");return Lc({...X,ext:Q})}case"EC":case"OKP":return Lc({...X,alg:Y,ext:Q});default:throw new I8('Unsupported "kty" (Key Type) Parameter value')}}var BH1=D(()=>{TJ();Jo1();_7()});async function rc0(X){if(x11(X))if(X.type==="secret")X=X.export();else return X.export({format:"jwk"});if(X instanceof Uint8Array)return{kty:"oct",k:NX(X)};if(!kO(X))throw TypeError(fN(X,"CryptoKey","KeyObject","Uint8Array"));if(!X.extractable)throw TypeError("non-extractable CryptoKey cannot be exported as a JWK");let{ext:Y,key_ops:G,alg:Q,use:J,...W}=await crypto.subtle.exportKey("jwk",X);if(W.kty==="AKP")W.alg=Q;return W}var oc0=D(()=>{TJ()});async function wE(X){return rc0(X)}var zH1=D(()=>{oc0()});async function sc0(X,Y,G,Q){let J=X.slice(0,7),W=await KH1(J,G,Y,Q,new Uint8Array);return{encryptedKey:W.ciphertext,iv:NX(W.iv),tag:NX(W.tag)}}async function ec0(X,Y,G,Q,J){let W=X.slice(0,7);return HH1(W,Y,G,Q,J,new Uint8Array)}var Xi0=D(()=>{wc();TJ()});function m11(X){if(X===void 0)throw new Y4("JWE Encrypted Key missing")}async function Gi0(X,Y,G,Q,J){switch(X){case"dir":{if(G!==void 0)throw new Y4("Encountered unexpected JWE Encrypted Key");return Y}case"ECDH-ES":if(G!==void 0)throw new Y4("Encountered unexpected JWE Encrypted Key");case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!BX(Q.epk))throw new Y4('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');if(Dc(Y),!Qo1(Y))throw new I8("ECDH with the provided key is not allowed or not supported by your javascript runtime");let W=await u3(Q.epk,X);Dc(W);let Z,$;if(Q.apu!==void 0){if(typeof Q.apu!=="string")throw new Y4('JOSE Header "apu" (Agreement PartyUInfo) invalid');Z=SZ(Q.apu,"apu",Y4)}if(Q.apv!==void 0){if(typeof Q.apv!=="string")throw new Y4('JOSE Header "apv" (Agreement PartyVInfo) invalid');$=SZ(Q.apv,"apv",Y4)}let K=await Go1(W,Y,X==="ECDH-ES"?Q.enc:X,X==="ECDH-ES"?$H1(Q.enc):parseInt(X.slice(-5,-2),10),Z,$);if(X==="ECDH-ES")return K;return m11(G),u11(X.slice(-6),K,G)}case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":return m11(G),Dc(Y),nc0(X,Y,G);case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{if(m11(G),typeof Q.p2c!=="number")throw new Y4('JOSE Header "p2c" (PBES2 Count) missing or invalid');let W=J?.maxPBES2Count||1e4;if(Q.p2c>W)throw new Y4('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if(typeof Q.p2s!=="string")throw new Y4('JOSE Header "p2s" (PBES2 Salt) missing or invalid');let Z;return Z=SZ(Q.p2s,"p2s",Y4),gc0(X,Y,G,Q.p2c,Z)}case"A128KW":case"A192KW":case"A256KW":return m11(G),u11(X,Y,G);case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{if(m11(G),typeof Q.iv!=="string")throw new Y4('JOSE Header "iv" (Initialization Vector) missing or invalid');if(typeof Q.tag!=="string")throw new Y4('JOSE Header "tag" (Authentication Tag) missing or invalid');let W;W=SZ(Q.iv,"iv",Y4);let Z;return Z=SZ(Q.tag,"tag",Y4),ec0(X,Y,G,W,Z)}default:throw new I8(Yi0)}}async function Qi0(X,Y,G,Q,J={}){let W,Z,$;switch(X){case"dir":{$=G;break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(Dc(G),!Qo1(G))throw new I8("ECDH with the provided key is not allowed or not supported by your javascript runtime");let{apu:K,apv:H}=J,U;if(J.epk)U=await bN(J.epk,X);else U=(await crypto.subtle.generateKey(G.algorithm,!0,["deriveBits"])).privateKey;let{x:N,y:B,crv:z,kty:O}=await wE(U),w=await Go1(G,U,X==="ECDH-ES"?Y:X,X==="ECDH-ES"?$H1(Y):parseInt(X.slice(-5,-2),10),K,H);if(Z={epk:{x:N,crv:z,kty:O}},O==="EC")Z.epk.y=B;if(K)Z.apu=NX(K);if(H)Z.apv=NX(H);if(X==="ECDH-ES"){$=w;break}$=Q||OE(Y);let E=X.slice(-6);W=await g11(E,w,$);break}case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{$=Q||OE(Y),Dc(G),W=await pc0(X,G,$);break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{$=Q||OE(Y);let{p2c:K,p2s:H}=J;({encryptedKey:W,...Z}=await hc0(X,G,$,K,H));break}case"A128KW":case"A192KW":case"A256KW":{$=Q||OE(Y),W=await g11(X,G,$);break}case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{$=Q||OE(Y);let{iv:K}=J;({encryptedKey:W,...Z}=await sc0(X,G,$,K));break}default:throw new I8(Yi0)}return{cek:$,encryptedKey:W,parameters:Z}}var Yi0='Invalid or unsupported "alg" (JWE Algorithm) header value';var Zo1=D(()=>{Xo1();yc0();uc0();ac0();TJ();qc();_7();vO();wc();BH1();zH1();Xi0()});function LE(X,Y,G,Q,J){if(J.crit!==void 0&&Q?.crit===void 0)throw new X('"crit" (Critical) Header Parameter MUST be integrity protected');if(!Q||Q.crit===void 0)return new Set;if(!Array.isArray(Q.crit)||Q.crit.length===0||Q.crit.some((Z)=>typeof Z!=="string"||Z.length===0))throw new X('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let W;if(G!==void 0)W=new Map([...Object.entries(G),...Y.entries()]);else W=Y;for(let Z of Q.crit){if(!W.has(Z))throw new I8(`Extension Header Parameter "${Z}" is not recognized`);if(J[Z]===void 0)throw new X(`Extension Header Parameter "${Z}" is missing`);if(W.get(Z)&&Q[Z]===void 0)throw new X(`Extension Header Parameter "${Z}" MUST be integrity protected`)}return new Set(Q.crit)}var d11=D(()=>{_7()});function c11(X,Y){if(Y!==void 0&&(!Array.isArray(Y)||Y.some((G)=>typeof G!=="string")))throw TypeError(`"${X}" option must be an array of strings`);if(!Y)return;return new Set(Y)}function EE(X,Y,G){switch(X.substring(0,2)){case"A1":case"A2":case"di":case"HS":case"PB":Tw8(X,Y,G);break;default:Iw8(X,Y,G)}}var Ac=(X)=>X?.[Symbol.toStringTag],Wo1=(X,Y,G)=>{if(Y.use!==void 0){let Q;switch(G){case"sign":case"verify":Q="sig";break;case"encrypt":case"decrypt":Q="enc";break}if(Y.use!==Q)throw TypeError(`Invalid key for this operation, its "use" must be "${Q}" when present`)}if(Y.alg!==void 0&&Y.alg!==X)throw TypeError(`Invalid key for this operation, its "alg" must be "${X}" when present`);if(Array.isArray(Y.key_ops)){let Q;switch(!0){case(G==="sign"||G==="verify"):case X==="dir":case X.includes("CBC-HS"):Q=G;break;case X.startsWith("PBES2"):Q="deriveBits";break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(X):if(!X.includes("GCM")&&X.endsWith("KW"))Q=G==="encrypt"?"wrapKey":"unwrapKey";else Q=G;break;case(G==="encrypt"&&X.startsWith("RSA")):Q="wrapKey";break;case G==="decrypt":Q=X.startsWith("RSA")?"unwrapKey":"deriveBits";break}if(Q&&Y.key_ops?.includes?.(Q)===!1)throw TypeError(`Invalid key for this operation, its "key_ops" must include "${Q}" when present`)}return!0},Tw8=(X,Y,G)=>{if(Y instanceof Uint8Array)return;if(qI(Y)){if(vc0(Y)&&Wo1(X,Y,G))return;throw TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!h11(Y))throw TypeError(tr1(X,Y,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if(Y.type!=="secret")throw TypeError(`${Ac(Y)} instances for symmetric algorithms must be of type "secret"`)},Iw8=(X,Y,G)=>{if(qI(Y))switch(G){case"decrypt":case"sign":if(Cc0(Y)&&Wo1(X,Y,G))return;throw TypeError("JSON Web Key for this operation must be a private JWK");case"encrypt":case"verify":if(kc0(Y)&&Wo1(X,Y,G))return;throw TypeError("JSON Web Key for this operation must be a public JWK")}if(!h11(Y))throw TypeError(tr1(X,Y,"CryptoKey","KeyObject","JSON Web Key"));if(Y.type==="secret")throw TypeError(`${Ac(Y)} instances for asymmetric algorithms must not be of type "secret"`);if(Y.type==="public")switch(G){case"sign":throw TypeError(`${Ac(Y)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw TypeError(`${Ac(Y)} instances for asymmetric algorithm decryption must be of type "private"`)}if(Y.type==="private")switch(G){case"verify":throw TypeError(`${Ac(Y)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw TypeError(`${Ac(Y)} instances for asymmetric algorithm encryption must be of type "public"`)}};var i11=()=>{};function Ji0(X){if(typeof globalThis[X]>"u")throw new I8(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${X} API.`)}async function Zi0(X){Ji0("CompressionStream");let Y=new CompressionStream("deflate-raw"),G=Y.writable.getWriter();G.write(X).catch(()=>{}),G.close().catch(()=>{});let Q=[],J=Y.readable.getReader();for(;;){let{value:W,done:Z}=await J.read();if(Z)break;Q.push(W)}return vY(...Q)}async function Wi0(X,Y){Ji0("DecompressionStream");let G=new DecompressionStream("deflate-raw"),Q=G.writable.getWriter();Q.write(X).catch(()=>{}),Q.close().catch(()=>{});let J=[],W=0,Z=G.readable.getReader();for(;;){let{value:$,done:K}=await Z.read();if(K)break;if(J.push($),W+=$.byteLength,Y!==1/0&&W>Y)throw new Y4("Decompressed plaintext exceeded the configured limit")}return vY(...J)}var $o1=D(()=>{_7();AJ()});async function $i0(X,Y,G){if(!BX(X))throw new Y4("Flattened JWE must be an object");if(X.protected===void 0&&X.header===void 0&&X.unprotected===void 0)throw new Y4("JOSE Header missing");if(X.iv!==void 0&&typeof X.iv!=="string")throw new Y4("JWE Initialization Vector incorrect type");if(typeof X.ciphertext!=="string")throw new Y4("JWE Ciphertext missing or incorrect type");if(X.tag!==void 0&&typeof X.tag!=="string")throw new Y4("JWE Authentication Tag incorrect type");if(X.protected!==void 0&&typeof X.protected!=="string")throw new Y4("JWE Protected Header incorrect type");if(X.encrypted_key!==void 0&&typeof X.encrypted_key!=="string")throw new Y4("JWE Encrypted Key incorrect type");if(X.aad!==void 0&&typeof X.aad!=="string")throw new Y4("JWE AAD incorrect type");if(X.header!==void 0&&!BX(X.header))throw new Y4("JWE Shared Unprotected Header incorrect type");if(X.unprotected!==void 0&&!BX(X.unprotected))throw new Y4("JWE Per-Recipient Unprotected Header incorrect type");let Q;if(X.protected)try{let M=VZ(X.protected);Q=JSON.parse(IQ.decode(M))}catch{throw new Y4("JWE Protected Header is invalid")}if(!DE(Q,X.header,X.unprotected))throw new Y4("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");let J={...Q,...X.header,...X.unprotected};if(LE(Y4,new Map,G?.crit,Q,J),J.zip!==void 0&&J.zip!=="DEF")throw new I8('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');if(J.zip!==void 0&&!Q?.zip)throw new Y4('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.');let{alg:W,enc:Z}=J;if(typeof W!=="string"||!W)throw new Y4("missing JWE Algorithm (alg) in JWE Header");if(typeof Z!=="string"||!Z)throw new Y4("missing JWE Encryption Algorithm (enc) in JWE Header");let $=G&&c11("keyManagementAlgorithms",G.keyManagementAlgorithms),K=G&&c11("contentEncryptionAlgorithms",G.contentEncryptionAlgorithms);if($&&!$.has(W)||!$&&W.startsWith("PBES2"))throw new Oc('"alg" (Algorithm) Header Parameter value not allowed');if(K&&!K.has(Z))throw new Oc('"enc" (Encryption Algorithm) Header Parameter value not allowed');let H;if(X.encrypted_key!==void 0)H=SZ(X.encrypted_key,"encrypted_key",Y4);let U=!1;if(typeof Y==="function")Y=await Y(Q,X),U=!0;EE(W==="dir"?Z:W,Y,"decrypt");let N=await bN(Y,W),B;try{B=await Gi0(W,N,H,J,G)}catch(M){if(M instanceof TypeError||M instanceof Y4||M instanceof I8)throw M;B=OE(Z)}let z,O;if(X.iv!==void 0)z=SZ(X.iv,"iv",Y4);if(X.tag!==void 0)O=SZ(X.tag,"tag",Y4);let w=X.protected!==void 0?nX(X.protected):new Uint8Array,E;if(X.aad!==void 0)E=vY(w,nX("."),nX(X.aad));else E=w;let P=SZ(X.ciphertext,"ciphertext",Y4),q=await HH1(Z,B,P,z,O,E),j={plaintext:q};if(J.zip==="DEF"){let M=G?.maxDecompressedLength??250000;if(M===0)throw new I8('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');if(M!==1/0&&(!Number.isSafeInteger(M)||M<1))throw TypeError("maxDecompressedLength must be 0, a positive safe integer, or Infinity");j.plaintext=await Wi0(q,M).catch((V)=>{if(V instanceof Y4)throw V;throw new Y4("Failed to decompress plaintext",{cause:V})})}if(X.protected!==void 0)j.protectedHeader=Q;if(X.aad!==void 0)j.additionalAuthenticatedData=SZ(X.aad,"aad",Y4);if(X.unprotected!==void 0)j.sharedUnprotectedHeader=X.unprotected;if(X.header!==void 0)j.unprotectedHeader=X.header;if(U)return{...j,key:N};return j}var Ki0=D(()=>{TJ();wc();vO();_7();Zo1();AJ();wc();d11();qc();i11();$o1()});async function Hi0(X,Y,G){if(X instanceof Uint8Array)X=IQ.decode(X);if(typeof X!=="string")throw new Y4("Compact JWE must be a string or Uint8Array");let{0:Q,1:J,2:W,3:Z,4:$,length:K}=X.split(".");if(K!==5)throw new Y4("Invalid Compact JWE");let H=await $i0({ciphertext:Z,iv:W||void 0,protected:Q,tag:$||void 0,encrypted_key:J||void 0},Y,G),U={plaintext:H.plaintext,protectedHeader:H.protectedHeader};if(typeof Y==="function")return{...U,key:H.key};return U}var Fi0=D(()=>{Ki0();_7();AJ()});class Ko1{#X;#Y;#G;#Q;#J;#Z;#$;#W;constructor(X){if(!(X instanceof Uint8Array))throw TypeError("plaintext must be an instance of Uint8Array");this.#X=X}setKeyManagementParameters(X){return RZ(this.#W,"setKeyManagementParameters"),this.#W=X,this}setProtectedHeader(X){return RZ(this.#Y,"setProtectedHeader"),this.#Y=X,this}setSharedUnprotectedHeader(X){return RZ(this.#G,"setSharedUnprotectedHeader"),this.#G=X,this}setUnprotectedHeader(X){return RZ(this.#Q,"setUnprotectedHeader"),this.#Q=X,this}setAdditionalAuthenticatedData(X){return this.#J=X,this}setContentEncryptionKey(X){return RZ(this.#Z,"setContentEncryptionKey"),this.#Z=X,this}setInitializationVector(X){return RZ(this.#$,"setInitializationVector"),this.#$=X,this}async encrypt(X,Y){if(!this.#Y&&!this.#Q&&!this.#G)throw new Y4("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");if(!DE(this.#Y,this.#Q,this.#G))throw new Y4("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");let G={...this.#Y,...this.#Q,...this.#G};if(LE(Y4,new Map,Y?.crit,this.#Y,G),G.zip!==void 0&&G.zip!=="DEF")throw new I8('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');if(G.zip!==void 0&&!this.#Y?.zip)throw new Y4('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.');let{alg:Q,enc:J}=G;if(typeof Q!=="string"||!Q)throw new Y4('JWE "alg" (Algorithm) Header Parameter missing or invalid');if(typeof J!=="string"||!J)throw new Y4('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');let W;if(this.#Z&&(Q==="dir"||Q==="ECDH-ES"))throw TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${Q}`);EE(Q==="dir"?J:Q,X,"encrypt");let Z;{let E,P=await bN(X,Q);if({cek:Z,encryptedKey:W,parameters:E}=await Qi0(Q,J,P,this.#Z,this.#W),E)if(Y&&Sc0 in Y)if(!this.#Q)this.setUnprotectedHeader(E);else this.#Q={...this.#Q,...E};else if(!this.#Y)this.setProtectedHeader(E);else this.#Y={...this.#Y,...E}}let $,K,H,U;if(this.#Y)K=NX(JSON.stringify(this.#Y)),H=nX(K);else K="",H=new Uint8Array;if(this.#J){U=NX(this.#J);let E=nX(U);$=vY(H,nX("."),E)}else $=H;let N=this.#X;if(G.zip==="DEF")N=await Zi0(N).catch((E)=>{throw new Y4("Failed to compress plaintext",{cause:E})});let{ciphertext:B,tag:z,iv:O}=await KH1(J,N,Z,this.#$,$),w={ciphertext:NX(B)};if(O)w.iv=NX(O);if(z)w.tag=NX(z);if(W)w.encrypted_key=NX(W);if(U)w.aad=U;if(this.#Y)w.protected=K;if(this.#G)w.unprotected=this.#G;if(this.#Q)w.header=this.#Q;return w}}var Ui0=D(()=>{TJ();vO();wc();Zo1();_7();AJ();d11();qc();i11();$o1()});async function Ni0(X,Y,G){if(!BX(X))throw new v7("Flattened JWS must be an object");if(X.protected===void 0&&X.header===void 0)throw new v7('Flattened JWS must have either of the "protected" or "header" members');if(X.protected!==void 0&&typeof X.protected!=="string")throw new v7("JWS Protected Header incorrect type");if(X.payload===void 0)throw new v7("JWS Payload missing");if(typeof X.signature!=="string")throw new v7("JWS Signature missing or incorrect type");if(X.header!==void 0&&!BX(X.header))throw new v7("JWS Unprotected Header incorrect type");let Q={};if(X.protected)try{let E=VZ(X.protected);Q=JSON.parse(IQ.decode(E))}catch{throw new v7("JWS Protected Header is invalid")}if(!DE(Q,X.header))throw new v7("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let J={...Q,...X.header},W=LE(v7,new Map([["b64",!0]]),G?.crit,Q,J),Z=!0;if(W.has("b64")){if(Z=Q.b64,typeof Z!=="boolean")throw new v7('The "b64" (base64url-encode payload) Header Parameter must be a boolean')}let{alg:$}=J;if(typeof $!=="string"||!$)throw new v7('JWS "alg" (Algorithm) Header Parameter missing or invalid');let K=G&&c11("algorithms",G.algorithms);if(K&&!K.has($))throw new Oc('"alg" (Algorithm) Header Parameter value not allowed');if(Z){if(typeof X.payload!=="string")throw new v7("JWS Payload must be a string")}else if(typeof X.payload!=="string"&&!(X.payload instanceof Uint8Array))throw new v7("JWS Payload must be a string or an Uint8Array instance");let H=!1;if(typeof Y==="function")Y=await Y(Q,X),H=!0;EE($,Y,"verify");let U=vY(X.protected!==void 0?nX(X.protected):new Uint8Array,nX("."),typeof X.payload==="string"?Z?nX(X.payload):PI.encode(X.payload):X.payload),N=SZ(X.signature,"signature",v7),B=await bN(Y,$);if(!await cc0($,B,N,U))throw new er1;let O;if(Z)O=SZ(X.payload,"payload",v7);else if(typeof X.payload==="string")O=PI.encode(X.payload);else O=X.payload;let w={payload:O};if(X.protected!==void 0)w.protectedHeader=Q;if(X.header!==void 0)w.unprotectedHeader=X.header;if(H)return{...w,key:B};return w}var Bi0=D(()=>{TJ();UH1();_7();AJ();vO();i11();d11();qc()});async function zi0(X,Y,G){if(X instanceof Uint8Array)X=IQ.decode(X);if(typeof X!=="string")throw new v7("Compact JWS must be a string or Uint8Array");let{0:Q,1:J,2:W,length:Z}=X.split(".");if(Z!==3)throw new v7("Invalid Compact JWS");let $=await Ni0({payload:J,protected:Q,signature:W},Y,G),K={payload:$.payload,protectedHeader:$.protectedHeader};if(typeof Y==="function")return{...K,key:$.key};return K}var Oi0=D(()=>{Bi0();_7();AJ()});function p11(X){let Y=Mw8.exec(X);if(!Y||Y[4]&&Y[1])throw TypeError("Invalid time period format");let G=parseFloat(Y[2]),Q=Y[3].toLowerCase(),J;switch(Q){case"sec":case"secs":case"second":case"seconds":case"s":J=Math.round(G);break;case"minute":case"minutes":case"min":case"mins":case"m":J=Math.round(G*wi0);break;case"hour":case"hours":case"hr":case"hrs":case"h":J=Math.round(G*Li0);break;case"day":case"days":case"d":J=Math.round(G*Ho1);break;case"week":case"weeks":case"w":J=Math.round(G*Vw8);break;default:J=Math.round(G*jw8);break}if(Y[1]==="-"||Y[4]==="ago")return-J;return J}function AI(X,Y){if(!Number.isFinite(Y))throw TypeError(`Invalid ${X} input`);return Y}function OH1(X,Y,G={}){let Q;try{Q=JSON.parse(IQ.decode(Y))}catch{}if(!BX(Q))throw new MZ("JWT Claims Set must be a top-level JSON object");let{typ:J}=G;if(J&&(typeof X.typ!=="string"||Di0(X.typ)!==Di0(J)))throw new IJ('unexpected "typ" JWT header value',Q,"typ","check_failed");let{requiredClaims:W=[],issuer:Z,subject:$,audience:K,maxTokenAge:H}=G,U=[...W];if(H!==void 0)U.push("iat");if(K!==void 0)U.push("aud");if($!==void 0)U.push("sub");if(Z!==void 0)U.push("iss");for(let O of new Set(U.reverse()))if(!(O in Q))throw new IJ(`missing required "${O}" claim`,Q,O,"missing");if(Z&&!(Array.isArray(Z)?Z:[Z]).includes(Q.iss))throw new IJ('unexpected "iss" claim value',Q,"iss","check_failed");if($&&Q.sub!==$)throw new IJ('unexpected "sub" claim value',Q,"sub","check_failed");if(K&&!Rw8(Q.aud,typeof K==="string"?[K]:K))throw new IJ('unexpected "aud" claim value',Q,"aud","check_failed");let N;switch(typeof G.clockTolerance){case"string":N=p11(G.clockTolerance);break;case"number":N=G.clockTolerance;break;case"undefined":N=0;break;default:throw TypeError("Invalid clockTolerance option type")}let{currentDate:B}=G,z=PE(B||new Date);if((Q.iat!==void 0||H)&&typeof Q.iat!=="number")throw new IJ('"iat" claim must be a number',Q,"iat","invalid");if(Q.nbf!==void 0){if(typeof Q.nbf!=="number")throw new IJ('"nbf" claim must be a number',Q,"nbf","invalid");if(Q.nbf>z+N)throw new IJ('"nbf" claim timestamp check failed',Q,"nbf","check_failed")}if(Q.exp!==void 0){if(typeof Q.exp!=="number")throw new IJ('"exp" claim must be a number',Q,"exp","invalid");if(Q.exp<=z-N)throw new zE('"exp" claim timestamp check failed',Q,"exp","check_failed")}if(H){let O=z-Q.iat,w=typeof H==="number"?H:p11(H);if(O-N>w)throw new zE('"iat" claim timestamp check failed (too far in the past)',Q,"iat","check_failed");if(O<0-N)throw new IJ('"iat" claim timestamp check failed (it should be in the past)',Q,"iat","check_failed")}return Q}class n11{#X;constructor(X){if(!BX(X))throw TypeError("JWT Claims Set MUST be an object");this.#X=structuredClone(X)}data(){return PI.encode(JSON.stringify(this.#X))}get iss(){return this.#X.iss}set iss(X){this.#X.iss=X}get sub(){return this.#X.sub}set sub(X){this.#X.sub=X}get aud(){return this.#X.aud}set aud(X){this.#X.aud=X}set jti(X){this.#X.jti=X}set nbf(X){if(typeof X==="number")this.#X.nbf=AI("setNotBefore",X);else if(X instanceof Date)this.#X.nbf=AI("setNotBefore",PE(X));else this.#X.nbf=PE(new Date)+p11(X)}set exp(X){if(typeof X==="number")this.#X.exp=AI("setExpirationTime",X);else if(X instanceof Date)this.#X.exp=AI("setExpirationTime",PE(X));else this.#X.exp=PE(new Date)+p11(X)}set iat(X){if(X===void 0)this.#X.iat=PE(new Date);else if(X instanceof Date)this.#X.iat=AI("setIssuedAt",PE(X));else if(typeof X==="string")this.#X.iat=AI("setIssuedAt",PE(new Date)+p11(X));else this.#X.iat=AI("setIssuedAt",X)}}var PE=(X)=>Math.floor(X.getTime()/1000),wi0=60,Li0,Ho1,Vw8,jw8,Mw8,Di0=(X)=>{if(X.includes("/"))return X.toLowerCase();return`application/${X.toLowerCase()}`},Rw8=(X,Y)=>{if(typeof X==="string")return Y.includes(X);if(Array.isArray(X))return Y.some(Set.prototype.has.bind(new Set(X)));return!1};var a11=D(()=>{_7();AJ();Li0=wi0*60,Ho1=Li0*24,Vw8=Ho1*7,jw8=Ho1*365.25,Mw8=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i});async function f7(X,Y,G){let Q=await zi0(X,Y,G);if(Q.protectedHeader.crit?.includes("b64")&&Q.protectedHeader.b64===!1)throw new MZ("JWTs MUST NOT use unencoded payload");let W={payload:OH1(Q.protectedHeader,Q.payload,G),protectedHeader:Q.protectedHeader};if(typeof Y==="function")return{...W,key:Q.key};return W}var Ei0=D(()=>{Oi0();a11();_7()});async function t11(X,Y,G){let Q=await Hi0(X,Y,G),J=OH1(Q.protectedHeader,Q.plaintext,G),{protectedHeader:W}=Q;if(W.iss!==void 0&&W.iss!==J.iss)throw new IJ('replicated "iss" claim header parameter mismatch',J,"iss","mismatch");if(W.sub!==void 0&&W.sub!==J.sub)throw new IJ('replicated "sub" claim header parameter mismatch',J,"sub","mismatch");if(W.aud!==void 0&&JSON.stringify(W.aud)!==JSON.stringify(J.aud))throw new IJ('replicated "aud" claim header parameter mismatch',J,"aud","mismatch");let Z={payload:J,protectedHeader:W};if(typeof Y==="function")return{...Z,key:Q.key};return Z}var Pi0=D(()=>{Fi0();a11();_7()});class Fo1{#X;constructor(X){this.#X=new Ko1(X)}setContentEncryptionKey(X){return this.#X.setContentEncryptionKey(X),this}setInitializationVector(X){return this.#X.setInitializationVector(X),this}setProtectedHeader(X){return this.#X.setProtectedHeader(X),this}setKeyManagementParameters(X){return this.#X.setKeyManagementParameters(X),this}async encrypt(X,Y){let G=await this.#X.encrypt(X,Y);return[G.protected,G.encrypted_key,G.iv,G.ciphertext,G.tag].join(".")}}var qi0=D(()=>{Ui0()});class Uo1{#X;#Y;#G;constructor(X){if(!(X instanceof Uint8Array))throw TypeError("payload must be an instance of Uint8Array");this.#X=X}setProtectedHeader(X){return RZ(this.#Y,"setProtectedHeader"),this.#Y=X,this}setUnprotectedHeader(X){return RZ(this.#G,"setUnprotectedHeader"),this.#G=X,this}async sign(X,Y){if(!this.#Y&&!this.#G)throw new v7("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!DE(this.#Y,this.#G))throw new v7("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let G={...this.#Y,...this.#G},Q=LE(v7,new Map([["b64",!0]]),Y?.crit,this.#Y,G),J=!0;if(Q.has("b64")){if(J=this.#Y.b64,typeof J!=="boolean")throw new v7('The "b64" (base64url-encode payload) Header Parameter must be a boolean')}let{alg:W}=G;if(typeof W!=="string"||!W)throw new v7('JWS "alg" (Algorithm) Header Parameter missing or invalid');EE(W,X,"sign");let Z,$;if(J)Z=NX(this.#X),$=nX(Z);else $=this.#X,Z="";let K,H;if(this.#Y)K=NX(JSON.stringify(this.#Y)),H=nX(K);else K="",H=new Uint8Array;let U=vY(H,nX("."),$),N=await bN(X,W),B=await dc0(W,N,U),z={signature:NX(B),payload:Z};if(this.#G)z.header=this.#G;if(this.#Y)z.protected=K;return z}}var Ai0=D(()=>{TJ();UH1();_7();AJ();i11();d11();qc();vO()});class No1{#X;constructor(X){this.#X=new Uo1(X)}setProtectedHeader(X){return this.#X.setProtectedHeader(X),this}async sign(X,Y){let G=await this.#X.sign(X,Y);if(G.payload===void 0)throw TypeError("use the flattened module for creating JWS with b64: false");return`${G.protected}.${G.payload}.${G.signature}`}}var Ti0=D(()=>{Ai0()});class CZ{#X;#Y;constructor(X={}){this.#Y=new n11(X)}setIssuer(X){return this.#Y.iss=X,this}setSubject(X){return this.#Y.sub=X,this}setAudience(X){return this.#Y.aud=X,this}setJti(X){return this.#Y.jti=X,this}setNotBefore(X){return this.#Y.nbf=X,this}setExpirationTime(X){return this.#Y.exp=X,this}setIssuedAt(X){return this.#Y.iat=X,this}setProtectedHeader(X){return this.#X=X,this}async sign(X,Y){let G=new No1(this.#Y.data());if(G.setProtectedHeader(this.#X),Array.isArray(this.#X?.crit)&&this.#X.crit.includes("b64")&&this.#X.b64===!1)throw new MZ("JWTs MUST NOT use unencoded payload");return G.sign(X,Y)}}var Ii0=D(()=>{Ti0();_7();a11()});class Tc{#X;#Y;#G;#Q;#J;#Z;#$;#W;constructor(X={}){this.#W=new n11(X)}setIssuer(X){return this.#W.iss=X,this}setSubject(X){return this.#W.sub=X,this}setAudience(X){return this.#W.aud=X,this}setJti(X){return this.#W.jti=X,this}setNotBefore(X){return this.#W.nbf=X,this}setExpirationTime(X){return this.#W.exp=X,this}setIssuedAt(X){return this.#W.iat=X,this}setProtectedHeader(X){return RZ(this.#Q,"setProtectedHeader"),this.#Q=X,this}setKeyManagementParameters(X){return RZ(this.#G,"setKeyManagementParameters"),this.#G=X,this}setContentEncryptionKey(X){return RZ(this.#X,"setContentEncryptionKey"),this.#X=X,this}setInitializationVector(X){return RZ(this.#Y,"setInitializationVector"),this.#Y=X,this}replicateIssuerAsHeader(){return this.#J=!0,this}replicateSubjectAsHeader(){return this.#Z=!0,this}replicateAudienceAsHeader(){return this.#$=!0,this}async encrypt(X,Y){let G=new Fo1(this.#W.data());if(this.#Q&&(this.#J||this.#Z||this.#$))this.#Q={...this.#Q,iss:this.#J?this.#W.iss:void 0,sub:this.#Z?this.#W.sub:void 0,aud:this.#$?this.#W.aud:void 0};if(G.setProtectedHeader(this.#Q),this.#Y)G.setInitializationVector(this.#Y);if(this.#X)G.setContentEncryptionKey(this.#X);if(this.#G)G.setKeyManagementParameters(this.#G);return G.encrypt(X,Y)}}var Vi0=D(()=>{qi0();a11();vO()});async function TI(X,Y){let G;if(qI(X))G=X;else if(h11(X))G=await wE(X);else throw TypeError(fN(X,"CryptoKey","KeyObject","JSON Web Key"));if(Y??="sha256",Y!=="sha256"&&Y!=="sha384"&&Y!=="sha512")throw TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');let Q;switch(G.kty){case"AKP":yN(G.alg,'"alg" (Algorithm) Parameter'),yN(G.pub,'"pub" (Public key) Parameter'),Q={alg:G.alg,kty:G.kty,pub:G.pub};break;case"EC":yN(G.crv,'"crv" (Curve) Parameter'),yN(G.x,'"x" (X Coordinate) Parameter'),yN(G.y,'"y" (Y Coordinate) Parameter'),Q={crv:G.crv,kty:G.kty,x:G.x,y:G.y};break;case"OKP":yN(G.crv,'"crv" (Subtype of Key Pair) Parameter'),yN(G.x,'"x" (Public Key) Parameter'),Q={crv:G.crv,kty:G.kty,x:G.x};break;case"RSA":yN(G.e,'"e" (Exponent) Parameter'),yN(G.n,'"n" (Modulus) Parameter'),Q={e:G.e,kty:G.kty,n:G.n};break;case"oct":yN(G.k,'"k" (Key Value) Parameter'),Q={k:G.k,kty:G.kty};break;default:throw new I8('"kty" (Key Type) Parameter missing or unsupported')}let J=nX(JSON.stringify(Q));return NX(await FH1(Y,J))}var yN=(X,Y)=>{if(typeof X!=="string"||!X)throw new rr1(`${Y} missing or invalid`)};var ji0=D(()=>{vO();TJ();_7();AJ();zH1()});function Sw8(X){switch(typeof X==="string"&&X.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";case"ML":return"AKP";default:throw new I8('Unsupported "alg" value for a JSON Web Key Set')}}function Cw8(X){return X&&typeof X==="object"&&Array.isArray(X.keys)&&X.keys.every(kw8)}function kw8(X){return BX(X)}class Ri0{#X;#Y=new WeakMap;constructor(X){if(!Cw8(X))throw new ZH1("JSON Web Key Set malformed");this.#X=structuredClone(X)}jwks(){return this.#X}async getKey(X,Y){let{alg:G,kid:Q}={...X,...Y?.header},J=Sw8(G),W=this.#X.keys.filter((K)=>{let H=J===K.kty;if(H&&typeof Q==="string")H=Q===K.kid;if(H&&(typeof K.alg==="string"||J==="AKP"))H=G===K.alg;if(H&&typeof K.use==="string")H=K.use==="sig";if(H&&Array.isArray(K.key_ops))H=K.key_ops.includes("verify");if(H)switch(G){case"ES256":H=K.crv==="P-256";break;case"ES384":H=K.crv==="P-384";break;case"ES512":H=K.crv==="P-521";break;case"Ed25519":case"EdDSA":H=K.crv==="Ed25519";break}return H}),{0:Z,length:$}=W;if($===0)throw new y11;if($!==1){let K=new or1,H=this.#Y;throw K[Symbol.asyncIterator]=async function*(){for(let U of W)try{yield await Mi0(H,U,G)}catch{}},K}return Mi0(this.#Y,Z,G)}}async function Mi0(X,Y,G){let Q=X.get(Y)||X.set(Y,{}).get(Y);if(Q[G]===void 0){let J=await u3({...Y,ext:!0},G);if(J instanceof Uint8Array||J.type!=="public")throw new ZH1("JSON Web Key Set members must be public keys");Q[G]=J}return Q[G]}function Bo1(X){let Y=new Ri0(X),G=async(Q,J)=>Y.getKey(Q,J);return Object.defineProperties(G,{jwks:{value:()=>structuredClone(Y.jwks()),enumerable:!1,configurable:!1,writable:!1}}),G}var Si0=D(()=>{BH1();_7()});function vw8(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}async function _w8(X,Y,G,Q=fetch){let J=await Q(X,{method:"GET",signal:G,redirect:"manual",headers:Y}).catch((W)=>{if(W.name==="TimeoutError")throw new sr1;throw W});if(J.status!==200)throw new CG("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await J.json()}catch{throw new CG("Failed to parse the JSON Web Key Set HTTP response as JSON")}}function fw8(X,Y){if(typeof X!=="object"||X===null)return!1;if(!("uat"in X)||typeof X.uat!=="number"||Date.now()-X.uat>=Y)return!1;if(!("jwks"in X)||!BX(X.jwks)||!Array.isArray(X.jwks.keys)||!Array.prototype.every.call(X.jwks.keys,BX))return!1;return!0}class ki0{#X;#Y;#G;#Q;#J;#Z;#$;#W;#K;#H;constructor(X,Y){if(!(X instanceof URL))throw TypeError("url must be an instance of URL");if(this.#X=new URL(X.href),this.#Y=typeof Y?.timeoutDuration==="number"?Y?.timeoutDuration:5000,this.#G=typeof Y?.cooldownDuration==="number"?Y?.cooldownDuration:30000,this.#Q=typeof Y?.cacheMaxAge==="number"?Y?.cacheMaxAge:600000,this.#$=new Headers(Y?.headers),zo1&&!this.#$.has("User-Agent"))this.#$.set("User-Agent",zo1);if(!this.#$.has("accept"))this.#$.set("accept","application/json"),this.#$.append("accept","application/jwk-set+json");if(this.#W=Y?.[Ci0],Y?.[DH1]!==void 0){if(this.#H=Y?.[DH1],fw8(Y?.[DH1],this.#Q))this.#J=this.#H.uat,this.#K=Bo1(this.#H.jwks)}}pendingFetch(){return!!this.#Z}coolingDown(){return typeof this.#J==="number"?Date.now()<this.#J+this.#G:!1}fresh(){return typeof this.#J==="number"?Date.now()<this.#J+this.#Q:!1}jwks(){return this.#K?.jwks()}async getKey(X,Y){if(!this.#K||!this.fresh())await this.reload();try{return await this.#K(X,Y)}catch(G){if(G instanceof y11){if(this.coolingDown()===!1)return await this.reload(),this.#K(X,Y)}throw G}}async reload(){if(this.#Z&&vw8())this.#Z=void 0;this.#Z||=_w8(this.#X.href,this.#$,AbortSignal.timeout(this.#Y),this.#W).then((X)=>{if(this.#K=Bo1(X),this.#H)this.#H.uat=Date.now(),this.#H.jwks=X;this.#J=Date.now(),this.#Z=void 0}).catch((X)=>{throw this.#Z=void 0,X}),await this.#Z}}function II(X,Y){let G=new ki0(X,Y),Q=async(J,W)=>G.getKey(J,W);return Object.defineProperties(Q,{coolingDown:{get:()=>G.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>G.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>G.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>G.pendingFetch(),enumerable:!0,configurable:!1},jwks:{value:()=>G.jwks(),enumerable:!0,configurable:!1,writable:!1}}),Q}var zo1,Ci0,DH1;var vi0=D(()=>{_7();Si0();if(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))zo1="jose/v6.2.3";Ci0=Symbol();DH1=Symbol()});function VI(X){let Y;if(typeof X==="string"){let G=X.split(".");if(G.length===3||G.length===5)[Y]=G}else if(typeof X==="object"&&X)if("protected"in X)Y=X.protected;else throw TypeError("Token does not contain a Protected Header");try{if(typeof Y!=="string"||!Y)throw Error();let G=JSON.parse(IQ.decode(VZ(Y)));if(!BX(G))throw Error();return G}catch{throw TypeError("Invalid Token or Protected Header formatting")}}var _i0=D(()=>{TJ();AJ()});function i9(X){if(typeof X!=="string")throw new MZ("JWTs must use Compact JWS serialization, JWT must be a string");let{1:Y,length:G}=X.split(".");if(G===5)throw new MZ("Only JWTs using Compact JWS serialization can be decoded");if(G!==3)throw new MZ("Invalid JWT");if(!Y)throw new MZ("JWTs must contain a payload");let Q;try{Q=VZ(Y)}catch{throw new MZ("Failed to base64url decode the payload")}let J;try{J=JSON.parse(IQ.decode(Q))}catch{throw new MZ("Failed to parse the decoded payload as JSON")}if(!BX(J))throw new MZ("Invalid JWT Claims Set");return J}var fi0=D(()=>{TJ();AJ();_7()});function Oo1(X){let Y=X?.modulusLength??2048;if(typeof Y!=="number"||Y<2048)throw new I8("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return Y}async function Do1(X,Y){let G,Q;switch(X){case"PS256":case"PS384":case"PS512":G={name:"RSA-PSS",hash:`SHA-${X.slice(-3)}`,publicExponent:Uint8Array.of(1,0,1),modulusLength:Oo1(Y)},Q=["sign","verify"];break;case"RS256":case"RS384":case"RS512":G={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${X.slice(-3)}`,publicExponent:Uint8Array.of(1,0,1),modulusLength:Oo1(Y)},Q=["sign","verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":G={name:"RSA-OAEP",hash:`SHA-${parseInt(X.slice(-3),10)||1}`,publicExponent:Uint8Array.of(1,0,1),modulusLength:Oo1(Y)},Q=["decrypt","unwrapKey","encrypt","wrapKey"];break;case"ES256":G={name:"ECDSA",namedCurve:"P-256"},Q=["sign","verify"];break;case"ES384":G={name:"ECDSA",namedCurve:"P-384"},Q=["sign","verify"];break;case"ES512":G={name:"ECDSA",namedCurve:"P-521"},Q=["sign","verify"];break;case"Ed25519":case"EdDSA":{Q=["sign","verify"],G={name:"Ed25519"};break}case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":{Q=["sign","verify"],G={name:X};break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{Q=["deriveBits"];let J=Y?.crv??"P-256";switch(J){case"P-256":case"P-384":case"P-521":{G={name:"ECDH",namedCurve:J};break}case"X25519":G={name:"X25519"};break;default:throw new I8("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, and X25519")}break}default:throw new I8('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return crypto.subtle.generateKey(G,Y?.extractable??!1,Q)}var bi0=D(()=>{_7()});var VJ=D(()=>{Ei0();Pi0();Ii0();Vi0();ji0();vi0();zH1();BH1();_i0();fi0();bi0();TJ()});var jI;var r11=D(()=>{jI={encode:(X)=>{if(typeof X==="string")X=new TextEncoder().encode(X);if(X.byteLength===0)return"";let Y=new Uint8Array(X),G="";for(let Q of Y)G+=Q.toString(16).padStart(2,"0");return G},decode:(X)=>{if(!X)return"";if(typeof X==="string"){if(X.length%2!==0)throw Error("Invalid hexadecimal string");if(!new RegExp("^[0123456789abcdef]+$").test(X))throw Error("Invalid hexadecimal string");let Y=new Uint8Array(X.length/2);for(let G=0;G<X.length;G+=2)Y[G/2]=parseInt(X.slice(G,G+2),16);return new TextDecoder().decode(Y)}return new TextDecoder().decode(X)}}});function yw8(X,Y,G,Q){wI(X);let J=eK1({dkLen:32,asyncTick:10},Q),{c:W,dkLen:Z,asyncTick:$}=J;if(TZ(W,"c"),TZ(Z,"dkLen"),TZ($,"asyncTick"),W<1)throw Error("iterations (c) must be >= 1");if(Z<1)throw Error('"dkLen" must be >= 1');if(Z>4294967295*X.outputLen)throw Error("derived key too long");let K=gr1(Y,"password"),H=gr1(G,"salt"),U=new Uint8Array(Z),N=k11.create(X,K),B=N._cloneInto().update(H);return{c:W,dkLen:Z,asyncTick:$,DK:U,PRF:N,PRFSalt:B}}function xw8(X,Y,G,Q,J){if(X.destroy(),Y.destroy(),Q)Q.destroy();return IZ(J),G}function wo1(X,Y,G,Q){let{c:J,dkLen:W,DK:Z,PRF:$,PRFSalt:K}=yw8(X,Y,G,Q),H,U=new Uint8Array(4),N=Bc(U),B=new Uint8Array($.outputLen);for(let z=1,O=0;O<W;z++,O+=$.outputLen){let w=Z.subarray(O,O+$.outputLen);N.setInt32(0,z,!1),(H=K._cloneInto(H)).update(U).digestInto(B),w.set(B.subarray(0,w.length));for(let E=1;E<J;E++){$._cloneInto(H).update(B).digestInto(B);for(let P=0;P<w.length;P++)w[P]^=B[P]}}return xw8($,K,Z,H,B)}var yi0=D(()=>{lr1();HE()});function xi0(X,Y,G,Q,J,W){let Z=X[Y++]^G[Q++],$=X[Y++]^G[Q++],K=X[Y++]^G[Q++],H=X[Y++]^G[Q++],U=X[Y++]^G[Q++],N=X[Y++]^G[Q++],B=X[Y++]^G[Q++],z=X[Y++]^G[Q++],O=X[Y++]^G[Q++],w=X[Y++]^G[Q++],E=X[Y++]^G[Q++],P=X[Y++]^G[Q++],q=X[Y++]^G[Q++],j=X[Y++]^G[Q++],M=X[Y++]^G[Q++],V=X[Y++]^G[Q++],R=Z,k=$,_=K,v=H,y=U,h=N,i=B,p=z,f=O,u=w,r=E,o=P,N1=q,L1=j,U1=M,D1=V;for(let G1=0;G1<8;G1+=2)y^=r5(R+N1|0,7),f^=r5(y+R|0,9),N1^=r5(f+y|0,13),R^=r5(N1+f|0,18),u^=r5(h+k|0,7),L1^=r5(u+h|0,9),k^=r5(L1+u|0,13),h^=r5(k+L1|0,18),U1^=r5(r+i|0,7),_^=r5(U1+r|0,9),i^=r5(_+U1|0,13),r^=r5(i+_|0,18),v^=r5(D1+o|0,7),p^=r5(v+D1|0,9),o^=r5(p+v|0,13),D1^=r5(o+p|0,18),k^=r5(R+v|0,7),_^=r5(k+R|0,9),v^=r5(_+k|0,13),R^=r5(v+_|0,18),i^=r5(h+y|0,7),p^=r5(i+h|0,9),y^=r5(p+i|0,13),h^=r5(y+p|0,18),o^=r5(r+u|0,7),f^=r5(o+r|0,9),u^=r5(f+o|0,13),r^=r5(u+f|0,18),N1^=r5(D1+U1|0,7),L1^=r5(N1+D1|0,9),U1^=r5(L1+N1|0,13),D1^=r5(U1+L1|0,18);J[W++]=Z+R|0,J[W++]=$+k|0,J[W++]=K+_|0,J[W++]=H+v|0,J[W++]=U+y|0,J[W++]=N+h|0,J[W++]=B+i|0,J[W++]=z+p|0,J[W++]=O+f|0,J[W++]=w+u|0,J[W++]=E+r|0,J[W++]=P+o|0,J[W++]=q+N1|0,J[W++]=j+L1|0,J[W++]=M+U1|0,J[W++]=V+D1|0}function Lo1(X,Y,G,Q,J){let W=Q+0,Z=Q+16*J;for(let $=0;$<16;$++)G[Z+$]=X[Y+(2*J-1)*16+$];for(let $=0;$<J;$++,W+=16,Y+=16){if(xi0(G,Z,X,Y,G,W),$>0)Z+=16;xi0(G,W,X,Y+=16,G,Z)}}function hw8(X,Y,G){let Q=eK1({dkLen:32,asyncTick:10,maxmem:1073742848},G),{N:J,r:W,p:Z,dkLen:$,asyncTick:K,maxmem:H,onProgress:U}=Q;if(TZ(J,"N"),TZ(W,"r"),TZ(Z,"p"),TZ($,"dkLen"),TZ(K,"asyncTick"),TZ(H,"maxmem"),U!==void 0&&typeof U!=="function")throw Error("progressCb must be a function");let N=128*W,B=N/4,z=Math.pow(2,32);if(J<=1||(J&J-1)!==0||J>z)throw Error('"N" expected a power of 2, and 2^1 <= N <= 2^32');if(Z<1||Z>(z-1)*32/N)throw Error('"p" expected integer 1..((2^32 - 1) * 32) / (128 * r)');if($<1||$>(z-1)*32)throw Error('"dkLen" expected integer 1..(2^32 - 1) * 32');let O=N*(J+Z+1);if(O>H)throw Error('"maxmem" limit was hit: memUsed(128*r*(N+p+1))='+O+", maxmem="+H);let w=wo1(CO,X,Y,{c:1,dkLen:N*Z}),E=oK1(w),P=oK1(new Uint8Array(N*J)),q=oK1(new Uint8Array(N)),j=()=>{};if(U){let M=2*J*Z,V=Math.max(Math.floor(M/1e4),1),R=0;j=()=>{if(R++,U&&(!(R%V)||R===M))U(R/M)}}return{N:J,r:W,p:Z,dkLen:$,blockSize32:B,V:P,B32:E,B:w,tmp:q,blockMixCb:j,asyncTick:K}}function gw8(X,Y,G,Q,J){let W=wo1(CO,X,G,{c:1,dkLen:Y});return IZ(G,Q,J),W}async function hi0(X,Y,G){let{N:Q,r:J,p:W,dkLen:Z,blockSize32:$,V:K,B32:H,B:U,tmp:N,blockMixCb:B,asyncTick:z}=hw8(X,Y,G);hr1(H);for(let O=0;O<W;O++){let w=$*O;for(let P=0;P<$;P++)K[P]=H[w+P];let E=0;await sK1(Q-1,z,()=>{Lo1(K,E,K,E+=$,J),B()}),Lo1(K,(Q-1)*$,H,w,J),B(),await sK1(Q,z,()=>{let P=(H[w+$-16]&Q-1)>>>0;for(let q=0;q<$;q++)N[q]=H[w+q]^K[P*$+q];Lo1(N,0,H,w,J),B()})}return hr1(H),gw8(X,Z,U,K,N)}var gi0=D(()=>{yi0();GH1();HE()});function ui0(X){switch(X){case"a-z":return"abcdefghijklmnopqrstuvwxyz";case"A-Z":return"ABCDEFGHIJKLMNOPQRSTUVWXYZ";case"0-9":return"0123456789";case"-_":return"-_";default:throw Error(`Unsupported alphabet: ${X}`)}}function xN(...X){let Y=X.map(ui0).join("");if(Y.length===0)throw Error("No valid characters provided for random string generation.");let G=Y.length;return(Q,...J)=>{if(Q<=0)throw Error("Length must be a positive integer.");let W=Y,Z=G;if(J.length>0)W=J.map(ui0).join(""),Z=W.length;let $=Math.floor(256/Z)*Z,K=new Uint8Array(Q*2),H=K.length,U="",N=H,B;while(U.length<Q){if(N>=H)crypto.getRandomValues(K),N=0;if(B=K[N++],B<$)U+=W[B%Z]}return U}}var Ic=()=>{};function _O(X,Y){if(typeof X==="string")X=new TextEncoder().encode(X);if(typeof Y==="string")Y=new TextEncoder().encode(Y);let G=new Uint8Array(X),Q=new Uint8Array(Y),J=G.length^Q.length,W=Math.max(G.length,Q.length);for(let Z=0;Z<W;Z++)J|=(Z<G.length?G[Z]:0)^(Z<Q.length?Q[Z]:0);return J===0}async function o11(X,Y,G=3600){return await new CZ(X).setProtectedHeader({alg:"HS256"}).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1000)+G).sign(new TextEncoder().encode(Y))}async function wH1(X,Y){try{return(await f7(X,new TextEncoder().encode(Y))).payload}catch(G){return null}}async function LH1(X,Y,G,Q=3600){let J=zc(CO,new TextEncoder().encode(Y),new TextEncoder().encode(G),li0,64),W=await TI({kty:"oct",k:BE.encode(J)},"sha256");return await new Tc(X).setProtectedHeader({alg:mi0,enc:di0,kid:W}).setIssuedAt().setExpirationTime(uw8()+Q).setJti(crypto.randomUUID()).encrypt(J)}async function s11(X,Y,G){if(!X)return null;try{let{payload:Q}=await t11(X,async({kid:J})=>{let W=zc(CO,new TextEncoder().encode(Y),new TextEncoder().encode(G),li0,64);if(J===void 0)return W;if(J===await TI({kty:"oct",k:BE.encode(W)},"sha256"))return W;throw Error("no matching decryption secret")},{clockTolerance:15,keyManagementAlgorithms:[mi0],contentEncryptionAlgorithms:[di0,"A256GCM"]});return Q}catch(Q){return null}}async function ci0(X,Y){return await hi0(X.normalize("NFKC"),Y,{N:Vc.N,p:Vc.p,r:Vc.r,dkLen:Vc.dkLen,maxmem:128*Vc.N*Vc.r*2})}var li0,uw8=()=>Date.now()/1000|0,mi0="dir",di0="A256CBC-HS512",Vc,Eo1=async(X)=>{let Y=jI.encode(crypto.getRandomValues(new Uint8Array(16))),G=await ci0(X,Y);return`${Y}:${jI.encode(G)}`},Po1=async({hash:X,password:Y})=>{let[G,Q]=X.split(":");if(!G||!Q)throw new U4("Invalid password hash");return _O(await ci0(Y,G),Yc0(Q))},z5,J$=async({key:X,data:Y})=>{let G=await B7("SHA-256").digest(X),Q=tK1(Y);return R11(Hc(Uc)(new Uint8Array(G)).encrypt(Q))},l3=async({key:X,data:Y})=>{let G=await B7("SHA-256").digest(X),Q=aK1(Y),J=Hc(Uc)(new Uint8Array(G));return new TextDecoder().decode(J.decrypt(Q))};var i7=D(()=>{WY();SG();xr1();Fc();dr1();GH1();VJ();r11();gi0();HE();Ic();li0=new Uint8Array([66,101,116,116,101,114,65,117,116,104,46,106,115,32,71,101,110,101,114,97,116,101,100,32,69,110,99,114,121,112,116,105,111,110,32,75,101,121]);Vc={N:16384,r:16,p:1,dkLen:64};z5=xN("a-z","0-9","A-Z","-_")});async function EH1(){return lw8}var lw8;var PH1=D(()=>{lw8=import("async_hooks").then((X)=>X.AsyncLocalStorage).catch((X)=>{if("AsyncLocalStorage"in globalThis)return globalThis.AsyncLocalStorage;throw console.warn("[better-auth] Warning: AsyncLocalStorage is not available in this environment. Some features may not work as expected."),console.warn("[better-auth] Please read more about this warning at https://better-auth.com/docs/installation#mount-handler"),console.warn("[better-auth] If you are using Cloudflare Workers, please see: https://developers.cloudflare.com/workers/configuration/compatibility-flags/#nodejs-compatibility-flag"),X})});async function Z$(){let X=(await ii0()).getStore();if(!X)throw Error("No auth context found. Please make sure you are calling this function within a `runWithEndpointContext` callback.");return X}async function jc(X,Y){return(await ii0()).run(X,Y)}async function jo1(){return(await Vo1()).getStore()!==void 0}async function Io1(){let X=(await Vo1()).getStore();if(!X)throw Error("No request state found. Please make sure you are calling this function within a `runWithRequestState` callback.");return X}async function Mo1(X,Y){return(await Vo1()).run(X,Y)}function Ro1(X){let Y=Object.freeze({});return{get ref(){return Y},async get(){let G=await Io1();if(!G.has(Y)){let Q=await X();return G.set(Y,Q),Q}return G.get(Y)},async set(G){(await Io1()).set(Y,G)}}}var qo1=null,ii0=async()=>{if(!qo1)qo1=new(await EH1());return qo1},Ao1=null,Vo1=async()=>{if(!Ao1)Ao1=new(await EH1());return Ao1},To1=null,So1=async()=>{if(!To1)To1=new(await EH1());return To1},q9=async(X)=>{return So1().then((Y)=>{return Y.getStore()||X}).catch(()=>{return X})},Co1=async(X,Y)=>{let G=!0;return So1().then((Q)=>{return G=!0,Q.run(X,Y)}).catch((Q)=>{if(!G)return Y();throw Q})},e11=async(X,Y)=>{let G=!0;return So1().then((Q)=>{return G=!0,X.transaction(async(J)=>{return Q.run(J,Y)})}).catch((Q)=>{if(!G)return Y();throw Q})};var ko1=D(()=>{PH1()});var hN=D(()=>{PH1();ko1()});function fo1(){return{root:{key:""},static:new qH1}}function bo1(X){let[Y,...G]=X.split("/");return G[G.length-1]===""?G.slice(0,-1):G}function pi0(X,Y){let G=new qH1;for(let[Q,J]of Y){let W=Q<0?X.slice(-(Q+1)).join("/"):X[Q];if(typeof J==="string")G[J]=W;else{let Z=W.match(J);if(Z)for(let $ in Z.groups)G[$]=Z.groups[$]}}return G}function yo1(X,Y="",G,Q){if(Y=Y.toUpperCase(),G.charCodeAt(0)!==47)G=`/${G}`;G=G.replace(/\\:/g,"%3A");let J=bo1(G),W=X.root,Z=0,$=[],K=[];for(let U=0;U<J.length;U++){let N=J[U];if(N.startsWith("**")){if(!W.wildcard)W.wildcard={key:"**"};W=W.wildcard,$.push([-(U+1),N.split(":")[1]||"_",N.length===2]);break}if(N==="*"||N.includes(":")){if(!W.param)W.param={key:"*"};if(W=W.param,N==="*")$.push([U,`_${Z++}`,!0]);else if(N.includes(":",1)){let z=mw8(N);K[U]=z,W.hasRegexParam=!0,$.push([U,z,!1])}else $.push([U,N.slice(1),!1]);continue}if(N==="\\*")N=J[U]="*";else if(N==="\\*\\*")N=J[U]="**";let B=W.static?.[N];if(B)W=B;else{let z={key:N};if(!W.static)W.static=new qH1;W.static[N]=z,W=z}}let H=$.length>0;if(!W.methods)W.methods=new qH1;if(W.methods[Y]??=[],W.methods[Y].push({data:Q||null,paramsRegexp:K,paramsMap:H?$:void 0}),!H)X.static["/"+J.join("/")]=W}function mw8(X){let Y=X.replace(/:(\w+)/g,(G,Q)=>`(?<${Q}>[^/]+)`).replace(/\./g,"\\.");return new RegExp(`^${Y}$`)}function ni0(X,Y="",G,Q){if(G.charCodeAt(G.length-1)===47)G=G.slice(0,-1);let J=X.static[G];if(J&&J.methods){let $=J.methods[Y]||J.methods[""];if($!==void 0)return $[0]}let W=bo1(G),Z=vo1(X,X.root,Y,W,0)?.[0];if(Z===void 0)return;if(Q?.params===!1)return Z;return{data:Z.data,params:Z.paramsMap?pi0(W,Z.paramsMap):void 0}}function vo1(X,Y,G,Q,J){if(J===Q.length){if(Y.methods){let Z=Y.methods[G]||Y.methods[""];if(Z)return Z}if(Y.param&&Y.param.methods){let Z=Y.param.methods[G]||Y.param.methods[""];if(Z){let $=Z[0].paramsMap;if($?.[$?.length-1]?.[2])return Z}}if(Y.wildcard&&Y.wildcard.methods){let Z=Y.wildcard.methods[G]||Y.wildcard.methods[""];if(Z){let $=Z[0].paramsMap;if($?.[$?.length-1]?.[2])return Z}}return}let W=Q[J];if(Y.static){let Z=Y.static[W];if(Z){let $=vo1(X,Z,G,Q,J+1);if($)return $}}if(Y.param){let Z=vo1(X,Y.param,G,Q,J+1);if(Z){if(Y.param.hasRegexParam){let $=Z.find((K)=>K.paramsRegexp[J]?.test(W))||Z.find((K)=>!K.paramsRegexp[J]);return $?[$]:void 0}return Z}}if(Y.wildcard&&Y.wildcard.methods)return Y.wildcard.methods[G]||Y.wildcard.methods[""]}function ai0(X,Y="",G,Q){if(G.charCodeAt(G.length-1)===47)G=G.slice(0,-1);let J=bo1(G),W=_o1(X,X.root,Y,J,0);if(Q?.params===!1)return W;return W.map((Z)=>{return{data:Z.data,params:Z.paramsMap?pi0(J,Z.paramsMap):void 0}})}function _o1(X,Y,G,Q,J,W=[]){let Z=Q[J];if(Y.wildcard&&Y.wildcard.methods){let K=Y.wildcard.methods[G]||Y.wildcard.methods[""];if(K)W.push(...K)}if(Y.param){if(_o1(X,Y.param,G,Q,J+1,W),J===Q.length&&Y.param.methods){let K=Y.param.methods[G]||Y.param.methods[""];if(K){let H=K[0].paramsMap;if(H?.[H?.length-1]?.[2])W.push(...K)}}}let $=Y.static?.[Z];if($)_o1(X,$,G,Q,J+1,W);if(J===Q.length&&Y.methods){let K=Y.methods[G]||Y.methods[""];if(K)W.push(...K)}return W}var qH1;var ti0=D(()=>{qH1=(()=>{let X=function(){};return X.prototype=Object.create(null),Object.freeze(X.prototype),X})()});function X0(X,Y,G){function Q($,K){if(!$._zod)Object.defineProperty($,"_zod",{value:{def:K,constr:Z,traits:new Set},enumerable:!1});if($._zod.traits.has(X))return;$._zod.traits.add(X),Y($,K);let H=Z.prototype,U=Object.keys(H);for(let N=0;N<U.length;N++){let B=U[N];if(!(B in $))$[B]=H[B].bind($)}}let J=G?.Parent??Object;class W extends J{}Object.defineProperty(W,"name",{value:X});function Z($){var K;let H=G?.Parent?new W:this;Q(H,$),(K=H._zod).deferred??(K.deferred=[]);for(let U of H._zod.deferred)U();return H}return Object.defineProperty(Z,"init",{value:Q}),Object.defineProperty(Z,Symbol.hasInstance,{value:($)=>{if(G?.Parent&&$ instanceof G.Parent)return!0;return $?._zod?.traits?.has(X)}}),Object.defineProperty(Z,"name",{value:X}),Z}function aX(X){if(X)Object.assign(X01,X);return X01}var Mc,AH1,gN,MI,X01;var Rc=D(()=>{Mc=Object.freeze({status:"aborted"});AH1=Symbol("zod_brand");gN=class gN extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};MI=class MI extends Error{constructor(X){super(`Encountered unidirectional transform during encode: ${X}`);this.name="ZodEncodeError"}};X01={}});var J6={};R0(J6,{unwrapMessage:()=>Y01,uint8ArrayToHex:()=>$L8,uint8ArrayToBase64url:()=>ZL8,uint8ArrayToBase64:()=>Jp0,stringifyPrimitive:()=>G6,slugify:()=>go1,shallowClone:()=>VH1,safeExtend:()=>Xp0,required:()=>Gp0,randomString:()=>sw8,propertyKeyTypes:()=>J01,promiseAllObject:()=>ow8,primitiveTypes:()=>lo1,prefixIssues:()=>W$,pick:()=>oi0,partial:()=>Yp0,parsedType:()=>$6,optionalKeys:()=>mo1,omit:()=>si0,objectClone:()=>aw8,numKeys:()=>ew8,nullish:()=>qE,normalizeParams:()=>F6,mergeDefs:()=>fO,merge:()=>GL8,jsonStringifyReplacer:()=>Sc,joinValues:()=>V0,issue:()=>kc,isPlainObject:()=>TE,isObject:()=>RI,hexToUint8Array:()=>WL8,getSizableOrigin:()=>Z01,getParsedType:()=>XL8,getLengthableOrigin:()=>W01,getEnumValues:()=>G01,getElementAtPath:()=>rw8,floatSafeRemainder:()=>ho1,finalizeIssue:()=>m3,extend:()=>ei0,escapeRegex:()=>IK,esc:()=>TH1,defineLazy:()=>V8,createTransparentProxy:()=>YL8,cloneDef:()=>tw8,clone:()=>kG,cleanRegex:()=>Q01,cleanEnum:()=>QL8,captureStackTrace:()=>IH1,cached:()=>Cc,base64urlToUint8Array:()=>JL8,base64ToUint8Array:()=>Qp0,assignProp:()=>AE,assertNotEqual:()=>cw8,assertNever:()=>pw8,assertIs:()=>iw8,assertEqual:()=>dw8,assert:()=>nw8,allowsEval:()=>uo1,aborted:()=>IE,NUMBER_FORMAT_RANGES:()=>do1,Class:()=>Zp0,BIGINT_FORMAT_RANGES:()=>co1});function dw8(X){return X}function cw8(X){return X}function iw8(X){}function pw8(X){throw Error("Unexpected value in exhaustive check")}function nw8(X){}function G01(X){let Y=Object.values(X).filter((Q)=>typeof Q==="number");return Object.entries(X).filter(([Q,J])=>Y.indexOf(+Q)===-1).map(([Q,J])=>J)}function V0(X,Y="|"){return X.map((G)=>G6(G)).join(Y)}function Sc(X,Y){if(typeof Y==="bigint")return Y.toString();return Y}function Cc(X){return{get value(){{let G=X();return Object.defineProperty(this,"value",{value:G}),G}throw Error("cached value already set")}}}function qE(X){return X===null||X===void 0}function Q01(X){let Y=X.startsWith("^")?1:0,G=X.endsWith("$")?X.length-1:X.length;return X.slice(Y,G)}function ho1(X,Y){let G=(X.toString().split(".")[1]||"").length,Q=Y.toString(),J=(Q.split(".")[1]||"").length;if(J===0&&/\d?e-\d?/.test(Q)){let K=Q.match(/\d?e-(\d?)/);if(K?.[1])J=Number.parseInt(K[1])}let W=G>J?G:J,Z=Number.parseInt(X.toFixed(W).replace(".","")),$=Number.parseInt(Y.toFixed(W).replace(".",""));return Z%$/10**W}function V8(X,Y,G){let Q=void 0;Object.defineProperty(X,Y,{get(){if(Q===ri0)return;if(Q===void 0)Q=ri0,Q=G();return Q},set(J){Object.defineProperty(X,Y,{value:J})},configurable:!0})}function aw8(X){return Object.create(Object.getPrototypeOf(X),Object.getOwnPropertyDescriptors(X))}function AE(X,Y,G){Object.defineProperty(X,Y,{value:G,writable:!0,enumerable:!0,configurable:!0})}function fO(...X){let Y={};for(let G of X){let Q=Object.getOwnPropertyDescriptors(G);Object.assign(Y,Q)}return Object.defineProperties({},Y)}function tw8(X){return fO(X._zod.def)}function rw8(X,Y){if(!Y)return X;return Y.reduce((G,Q)=>G?.[Q],X)}function ow8(X){let Y=Object.keys(X),G=Y.map((Q)=>X[Q]);return Promise.all(G).then((Q)=>{let J={};for(let W=0;W<Y.length;W++)J[Y[W]]=Q[W];return J})}function sw8(X=10){let G="";for(let Q=0;Q<X;Q++)G+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return G}function TH1(X){return JSON.stringify(X)}function go1(X){return X.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function RI(X){return typeof X==="object"&&X!==null&&!Array.isArray(X)}function TE(X){if(RI(X)===!1)return!1;let Y=X.constructor;if(Y===void 0)return!0;if(typeof Y!=="function")return!0;let G=Y.prototype;if(RI(G)===!1)return!1;if(Object.prototype.hasOwnProperty.call(G,"isPrototypeOf")===!1)return!1;return!0}function VH1(X){if(TE(X))return{...X};if(Array.isArray(X))return[...X];return X}function ew8(X){let Y=0;for(let G in X)if(Object.prototype.hasOwnProperty.call(X,G))Y++;return Y}function IK(X){return X.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function kG(X,Y,G){let Q=new X._zod.constr(Y??X._zod.def);if(!Y||G?.parent)Q._zod.parent=X;return Q}function F6(X){let Y=X;if(!Y)return{};if(typeof Y==="string")return{error:()=>Y};if(Y?.message!==void 0){if(Y?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");Y.error=Y.message}if(delete Y.message,typeof Y.error==="string")return{...Y,error:()=>Y.error};return Y}function YL8(X){let Y;return new Proxy({},{get(G,Q,J){return Y??(Y=X()),Reflect.get(Y,Q,J)},set(G,Q,J,W){return Y??(Y=X()),Reflect.set(Y,Q,J,W)},has(G,Q){return Y??(Y=X()),Reflect.has(Y,Q)},deleteProperty(G,Q){return Y??(Y=X()),Reflect.deleteProperty(Y,Q)},ownKeys(G){return Y??(Y=X()),Reflect.ownKeys(Y)},getOwnPropertyDescriptor(G,Q){return Y??(Y=X()),Reflect.getOwnPropertyDescriptor(Y,Q)},defineProperty(G,Q,J){return Y??(Y=X()),Reflect.defineProperty(Y,Q,J)}})}function G6(X){if(typeof X==="bigint")return X.toString()+"n";if(typeof X==="string")return`"${X}"`;return`${X}`}function mo1(X){return Object.keys(X).filter((Y)=>{return X[Y]._zod.optin==="optional"&&X[Y]._zod.optout==="optional"})}function oi0(X,Y){let G=X._zod.def,Q=G.checks;if(Q&&Q.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let W=fO(X._zod.def,{get shape(){let Z={};for(let $ in Y){if(!($ in G.shape))throw Error(`Unrecognized key: "${$}"`);if(!Y[$])continue;Z[$]=G.shape[$]}return AE(this,"shape",Z),Z},checks:[]});return kG(X,W)}function si0(X,Y){let G=X._zod.def,Q=G.checks;if(Q&&Q.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let W=fO(X._zod.def,{get shape(){let Z={...X._zod.def.shape};for(let $ in Y){if(!($ in G.shape))throw Error(`Unrecognized key: "${$}"`);if(!Y[$])continue;delete Z[$]}return AE(this,"shape",Z),Z},checks:[]});return kG(X,W)}function ei0(X,Y){if(!TE(Y))throw Error("Invalid input to extend: expected a plain object");let G=X._zod.def.checks;if(G&&G.length>0){let W=X._zod.def.shape;for(let Z in Y)if(Object.getOwnPropertyDescriptor(W,Z)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let J=fO(X._zod.def,{get shape(){let W={...X._zod.def.shape,...Y};return AE(this,"shape",W),W}});return kG(X,J)}function Xp0(X,Y){if(!TE(Y))throw Error("Invalid input to safeExtend: expected a plain object");let G=fO(X._zod.def,{get shape(){let Q={...X._zod.def.shape,...Y};return AE(this,"shape",Q),Q}});return kG(X,G)}function GL8(X,Y){let G=fO(X._zod.def,{get shape(){let Q={...X._zod.def.shape,...Y._zod.def.shape};return AE(this,"shape",Q),Q},get catchall(){return Y._zod.def.catchall},checks:[]});return kG(X,G)}function Yp0(X,Y,G){let J=Y._zod.def.checks;if(J&&J.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let Z=fO(Y._zod.def,{get shape(){let $=Y._zod.def.shape,K={...$};if(G)for(let H in G){if(!(H in $))throw Error(`Unrecognized key: "${H}"`);if(!G[H])continue;K[H]=X?new X({type:"optional",innerType:$[H]}):$[H]}else for(let H in $)K[H]=X?new X({type:"optional",innerType:$[H]}):$[H];return AE(this,"shape",K),K},checks:[]});return kG(Y,Z)}function Gp0(X,Y,G){let Q=fO(Y._zod.def,{get shape(){let J=Y._zod.def.shape,W={...J};if(G)for(let Z in G){if(!(Z in W))throw Error(`Unrecognized key: "${Z}"`);if(!G[Z])continue;W[Z]=new X({type:"nonoptional",innerType:J[Z]})}else for(let Z in J)W[Z]=new X({type:"nonoptional",innerType:J[Z]});return AE(this,"shape",W),W}});return kG(Y,Q)}function IE(X,Y=0){if(X.aborted===!0)return!0;for(let G=Y;G<X.issues.length;G++)if(X.issues[G]?.continue!==!0)return!0;return!1}function W$(X,Y){return Y.map((G)=>{var Q;return(Q=G).path??(Q.path=[]),G.path.unshift(X),G})}function Y01(X){return typeof X==="string"?X:X?.message}function m3(X,Y,G){let Q={...X,path:X.path??[]};if(!X.message){let J=Y01(X.inst?._zod.def?.error?.(X))??Y01(Y?.error?.(X))??Y01(G.customError?.(X))??Y01(G.localeError?.(X))??"Invalid input";Q.message=J}if(delete Q.inst,delete Q.continue,!Y?.reportInput)delete Q.input;return Q}function Z01(X){if(X instanceof Set)return"set";if(X instanceof Map)return"map";if(X instanceof File)return"file";return"unknown"}function W01(X){if(Array.isArray(X))return"array";if(typeof X==="string")return"string";return"unknown"}function $6(X){let Y=typeof X;switch(Y){case"number":return Number.isNaN(X)?"nan":"number";case"object":{if(X===null)return"null";if(Array.isArray(X))return"array";let G=X;if(G&&Object.getPrototypeOf(G)!==Object.prototype&&"constructor"in G&&G.constructor)return G.constructor.name}}return Y}function kc(...X){let[Y,G,Q]=X;if(typeof Y==="string")return{message:Y,code:"custom",input:G,inst:Q};return{...Y}}function QL8(X){return Object.entries(X).filter(([Y,G])=>{return Number.isNaN(Number.parseInt(Y,10))}).map((Y)=>Y[1])}function Qp0(X){let Y=atob(X),G=new Uint8Array(Y.length);for(let Q=0;Q<Y.length;Q++)G[Q]=Y.charCodeAt(Q);return G}function Jp0(X){let Y="";for(let G=0;G<X.length;G++)Y+=String.fromCharCode(X[G]);return btoa(Y)}function JL8(X){let Y=X.replace(/-/g,"+").replace(/_/g,"/"),G="=".repeat((4-Y.length%4)%4);return Qp0(Y+G)}function ZL8(X){return Jp0(X).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function WL8(X){let Y=X.replace(/^0x/,"");if(Y.length%2!==0)throw Error("Invalid hex string length");let G=new Uint8Array(Y.length/2);for(let Q=0;Q<Y.length;Q+=2)G[Q/2]=Number.parseInt(Y.slice(Q,Q+2),16);return G}function $L8(X){return Array.from(X).map((Y)=>Y.toString(16).padStart(2,"0")).join("")}class Zp0{constructor(...X){}}var ri0,IH1,uo1,XL8=(X)=>{let Y=typeof X;switch(Y){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(X)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(X))return"array";if(X===null)return"null";if(X.then&&typeof X.then==="function"&&X.catch&&typeof X.catch==="function")return"promise";if(typeof Map<"u"&&X instanceof Map)return"map";if(typeof Set<"u"&&X instanceof Set)return"set";if(typeof Date<"u"&&X instanceof Date)return"date";if(typeof File<"u"&&X instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${Y}`)}},J01,lo1,do1,co1;var E4=D(()=>{ri0=Symbol("evaluating");IH1="captureStackTrace"in Error?Error.captureStackTrace:(...X)=>{};uo1=Cc(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(X){return!1}});J01=new Set(["string","number","symbol"]),lo1=new Set(["string","number","bigint","boolean","symbol","undefined"]);do1={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},co1={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]}});function vc(X,Y=(G)=>G.message){let G={},Q=[];for(let J of X.issues)if(J.path.length>0)G[J.path[0]]=G[J.path[0]]||[],G[J.path[0]].push(Y(J));else Q.push(Y(J));return{formErrors:Q,fieldErrors:G}}function _c(X,Y=(G)=>G.message){let G={_errors:[]},Q=(J)=>{for(let W of J.issues)if(W.code==="invalid_union"&&W.errors.length)W.errors.map((Z)=>Q({issues:Z}));else if(W.code==="invalid_key")Q({issues:W.issues});else if(W.code==="invalid_element")Q({issues:W.issues});else if(W.path.length===0)G._errors.push(Y(W));else{let Z=G,$=0;while($<W.path.length){let K=W.path[$];if($!==W.path.length-1)Z[K]=Z[K]||{_errors:[]};else Z[K]=Z[K]||{_errors:[]},Z[K]._errors.push(Y(W));Z=Z[K],$++}}};return Q(X),G}function jH1(X,Y=(G)=>G.message){let G={errors:[]},Q=(J,W=[])=>{var Z,$;for(let K of J.issues)if(K.code==="invalid_union"&&K.errors.length)K.errors.map((H)=>Q({issues:H},K.path));else if(K.code==="invalid_key")Q({issues:K.issues},K.path);else if(K.code==="invalid_element")Q({issues:K.issues},K.path);else{let H=[...W,...K.path];if(H.length===0){G.errors.push(Y(K));continue}let U=G,N=0;while(N<H.length){let B=H[N],z=N===H.length-1;if(typeof B==="string")U.properties??(U.properties={}),(Z=U.properties)[B]??(Z[B]={errors:[]}),U=U.properties[B];else U.items??(U.items=[]),($=U.items)[B]??($[B]={errors:[]}),U=U.items[B];if(z)U.errors.push(Y(K));N++}}};return Q(X),G}function $p0(X){let Y=[],G=X.map((Q)=>typeof Q==="object"?Q.key:Q);for(let Q of G)if(typeof Q==="number")Y.push(`[${Q}]`);else if(typeof Q==="symbol")Y.push(`[${JSON.stringify(String(Q))}]`);else if(/[^\w$]/.test(Q))Y.push(`[${JSON.stringify(Q)}]`);else{if(Y.length)Y.push(".");Y.push(Q)}return Y.join("")}function MH1(X){let Y=[],G=[...X.issues].sort((Q,J)=>(Q.path??[]).length-(J.path??[]).length);for(let Q of G)if(Y.push(`\u2716 ${Q.message}`),Q.path?.length)Y.push(` \u2192 at ${$p0(Q.path)}`);return Y.join(`
|
|
@@ -1636,7 +1636,7 @@ AS SELECT
|
|
|
1636
1636
|
FROM monitoring_metrics
|
|
1637
1637
|
GROUP BY organization_id, name, bucket, connection_id, tool_name, status
|
|
1638
1638
|
`}),console.log("[clickhouse-schema] monitoring_metrics_rollup_1m_mv view ready")}finally{await G.close()}}catch(Y){console.error("[clickhouse-schema] Failed to create rollup DDL (queries will fall back to raw table):",Y)}}async function DA1(X){let Y={...process.env},G=I$1(X,Y),Q=G.settings.encryptionKey;console.log(`[settings] ENCRYPTION_KEY = ${JSON.stringify(Q)} (${Q.length} chars)`);let{ensureServices:J}=await Promise.resolve().then(() => (H$1(),K$1)),{outputs:W,services:Z}=await J({home:G.settings.dataDir,externalDatabaseUrl:G.externalDatabaseUrl,externalNatsUrl:G.externalNatsUrl});if(!G.skipMigrations){let{migrateBetterAuth:K}=await Promise.resolve().then(() => (X30(),Xx6));await K(W.databaseUrl);let{createDatabase:H}=await Promise.resolve().then(() => (QU(),ey6)),{migrateToLatest:U}=await Promise.resolve().then(() => (Zr6(),Jr6)),N=H(W.databaseUrl);await U({keepOpen:!0,database:N,skipBetterAuth:!0})}if(G.settings.clickhouseUrl){let{ensureClickHouseRollup:K}=await Promise.resolve().then(() => Ws6);await K(G.settings.clickhouseUrl)}let $={...G.settings,databaseUrl:W.databaseUrl,natsUrls:W.natsUrls};return Xl0($),{settings:$,services:Z.map((K)=>({name:K.name==="PostgreSQL"?"Postgres":K.name,port:K.port})),managedServiceNames:Z.filter((K)=>K.owner==="managed").map((K)=>K.name)}}var IN0=D(()=>{xn1();m9()});import{createServer as $s6}from"net";function Di5(X){return new Promise((Y)=>{let G=$s6();G.once("error",()=>Y(!1)),G.listen(X,"0.0.0.0",()=>{G.close(()=>Y(!0))})})}async function wA1(X){if(await Di5(X))return X;let Y=await new Promise((G,Q)=>{let J=$s6();J.once("error",Q),J.listen(0,"0.0.0.0",()=>{let W=J.address(),Z=typeof W==="object"&&W?W.port:0;J.close(()=>G(Z))})});return console.warn(`Port ${X} is in use, using port ${Y} instead.`),Y}var VN0=()=>{};var jN0={};R0(jN0,{startDevServer:()=>Li5});import{join as wi5}from"path";function Ks6(X){return X.replace(/\x1b\[[0-9;]*m/g,"")}function Hs6(X){let Y=X.getReader(),G=new TextDecoder,Q="";function J(){let W=Q.split(`
|
|
1639
|
-
`);Q=W.pop()??"";for(let Z of W){let $=Ks6(Z).replace(/^\[\d+\]\s*/,"").trim();if(!$)continue;LK({method:"",path:"",status:0,duration:0,timestamp:new Date,rawLine:$})}}(async()=>{for(;;){let{done:W,value:Z}=await Y.read();if(W)break;Q+=G.decode(Z,{stream:!0}),J()}if(Q.trim()){let W=Ks6(Q).replace(/^\[\d+\]\s*/,"").trim();if(W)LK({method:"",path:"",status:0,duration:0,timestamp:new Date,rawLine:W})}})()}async function Li5(X){let{vitePort:Y,baseUrl:G,noTui:Q}=X,J=await wA1(Number(X.port)),{settings:W,services:Z,managedServiceNames:$}=await DA1({port:String(J),home:X.home,baseUrl:X.baseUrl,localMode:X.localMode,skipMigrations:X.skipMigrations,noTui:X.noTui,vitePort:X.vitePort});for(let z of Z)Nd({name:z.name,status:"ready",port:z.port});Te(W),qe();let K=wi5(import.meta.dir,"..","..","..","..",".."),H=Q===!0,U=Bun.spawn(["bun","run","--cwd=apps/mesh","dev:servers"],{cwd:K,env:{...process.env,PORT:String(W.port),VITE_PORT:String(Y),DATABASE_URL:W.databaseUrl,NATS_URL:W.natsUrls.join(","),NODE_ENV:W.nodeEnv,DECOCMS_LOCAL_MODE:String(W.localMode),DECOCMS_HOME:W.dataDir,DATA_DIR:W.dataDir,DECO_CLI:"1",...W.baseUrl?{BASE_URL:W.baseUrl}:{}},stdio:["inherit",H?"inherit":"pipe",H?"inherit":"pipe"]});if(!H)Hs6(U.stdout),Hs6(U.stderr);let N=G||`http://localhost:${W.port}`;Ae(N),Nd({name:"Vite",status:"ready",port:Number(Y)});let B=async(z)=>{if(U.kill(z),$.length>0){let{stopServices:O}=await Promise.resolve().then(() => (H$1(),K$1));await O(W.dataDir)}};return process.on("SIGINT",()=>B("SIGINT")),process.on("SIGTERM",()=>B("SIGTERM")),{port:Number(W.port),process:U}}var MN0=D(()=>{IN0();YF();VN0()});import{Box as RN0,Text as SN0}from"ink";import{jsx as Us6,jsxs as LA1}from"react/jsx-runtime";function Fs6(X){if(!X)return"not set";try{let Y=new URL(X);if(Y.password)Y.password="***";if(Y.username&&Y.username.length>3)Y.username=Y.username.slice(0,3)+"***";return Y.pathname="/",Y.search="",Y.hash="",Y.toString()}catch{if(X.length<=10)return X;return X.slice(0,6)+"***"+X.slice(-4)}}function qi5(X,Y){if(Ei5.has(X))return Y?{text:"\u25CF\u25CF\u25CF\u25CF\u25CF\u25CF",dimColor:!0}:{text:"not set",dimColor:!0};if(Pi5.has(X)){if(Array.isArray(Y)){if(Y.length===0)return{text:"not set",dimColor:!0};return{text:Y.map((W)=>Fs6(W)).join(", "),color:"cyan"}}let Q=Fs6(Y);return Q==="not set"?{text:Q,dimColor:!0}:{text:Q,color:"cyan"}}if(Y===void 0||Y===null||Y==="")return{text:"not set",dimColor:!0};let G=String(Y);if(G==="true")return{text:G,color:"green"};if(G==="false")return{text:G,color:"yellow"};try{return new URL(G),{text:G,color:"cyan"}}catch{return{text:G}}}function Ai5(X){return[{title:"Core",entries:[{key:"NODE_ENV",value:X.nodeEnv},{key:"PORT",value:X.port},{key:"BASE_URL",value:X.baseUrl??`http://localhost:${X.port}`},{key:"DATA_DIR",value:X.dataDir}]},{title:"Database",entries:[{key:"DATABASE_URL",value:X.databaseUrl},{key:"DATABASE_PG_SSL",value:X.databasePgSsl}]},{title:"Auth & Secrets",entries:[{key:"BETTER_AUTH_SECRET",value:X.betterAuthSecret},{key:"ENCRYPTION_KEY",value:X.encryptionKey},{key:"MESH_JWT_SECRET",value:X.meshJwtSecret},{key:"STUDIO_PROVISION_SECRET_KEY",value:X.studioProvisionSecretKey},{key:"DISABLE_RATE_LIMIT",value:X.disableRateLimit}]},{title:"Auth Providers",entries:[{key:"AUTH_EMAIL_PASSWORD_ENABLED",value:process.env.AUTH_EMAIL_PASSWORD_ENABLED??"true"},{key:"AUTH_GOOGLE_CLIENT_ID",value:!!process.env.AUTH_GOOGLE_CLIENT_ID},{key:"AUTH_GITHUB_CLIENT_ID",value:!!process.env.AUTH_GITHUB_CLIENT_ID},{key:"AUTH_RESEND_API_KEY",value:!!process.env.AUTH_RESEND_API_KEY},{key:"AUTH_SENDGRID_API_KEY",value:!!process.env.AUTH_SENDGRID_API_KEY},{key:"AUTH_SSO_MS_CLIENT_ID",value:!!process.env.AUTH_SSO_MS_CLIENT_ID},{key:"AUTH_MAGIC_LINK_ENABLED",value:process.env.AUTH_MAGIC_LINK_ENABLED==="true"},{key:"AUTH_EMAIL_OTP_ENABLED",value:process.env.AUTH_EMAIL_OTP_ENABLED==="true"}]},{title:"Observability",entries:[{key:"CLICKHOUSE_URL",value:X.clickhouseUrl},{key:"OTEL_SERVICE_NAME",value:X.otelServiceName}]},{title:"Event Bus & Networking",entries:[{key:"NATS_URL",value:X.natsUrls}]},{title:"Config Files",entries:[{key:"CONFIG_PATH",value:X.configPath}]},{title:"Transport",entries:[{key:"UNSAFE_ALLOW_STDIO_TRANSPORT",value:X.unsafeAllowStdioTransport}]},{title:"AI Gateway",entries:[{key:"DECO_AI_GATEWAY_ENABLED",value:X.aiGatewayEnabled},{key:"DECO_AI_GATEWAY_URL",value:X.aiGatewayUrl}]}]}function Ns6({env:X}){let Y=Ai5(X);return Us6(RN0,{flexDirection:"column",children:Y.map((G)=>LA1(RN0,{flexDirection:"column",marginTop:1,children:[LA1(SN0,{dimColor:!0,children:[" ","\u2500\u2500 ",G.title," ","\u2500".repeat(Math.max(0,38-G.title.length))]}),G.entries.map(({key:Q,value:J})=>{let W=qi5(Q,J);return LA1(RN0,{children:[LA1(SN0,{dimColor:!0,children:[" ",Q.padEnd(36)]}),Us6(SN0,{color:W.color,dimColor:W.dimColor,children:W.text})]},Q)})]},G.title))})}var Ei5,Pi5;var Bs6=D(()=>{Ei5=new Set(["BETTER_AUTH_SECRET","ENCRYPTION_KEY","MESH_JWT_SECRET","STUDIO_PROVISION_SECRET_KEY"]),Pi5=new Set(["DATABASE_URL","CLICKHOUSE_URL","NATS_URL"])});var CN0;var zs6=D(()=>{CN0={name:"decocms",version:"2.285.1",description:"Deco CMS \u2014 Self-hostable MCP Gateway for managing AI connections and tools",author:"Deco team",repository:{type:"git",url:"git+https://github.com/decocms/studio.git",directory:"apps/mesh"},bugs:{url:"https://github.com/decocms/studio/issues"},type:"module",bin:{deco:"./dist/server/cli.js"},files:["dist/**/*"],scripts:{dev:'bun run migrate && concurrently "bun run dev:client" "bun run dev:server"',"dev:servers":'concurrently "bun run dev:client" "bun run dev:server"',"dev:client":"bun --bun vite dev","dev:server":"bun run --cwd=../../packages/sandbox build && NODE_ENV=development bun --env-file=.env --hot run src/index.ts","build:client":"bun --bun vite build","build:server":"bun run scripts/bundle-server-script.ts --dist ./dist/server","db:migrate":"bun run ./dist/server/migrate.js",check:"tsc --noEmit",start:"bun run ./dist/server/server.js",migrate:"bun run src/database/migrate.ts",test:"bun test","test:e2e":"playwright test","test:e2e:ui":"playwright test --ui","better-auth:migrate":"bunx --bun @better-auth/cli migrate -y --config src/auth/index.ts",prepublishOnly:"bun run build:client && bun run build:server"},optionalDependencies:{"@duckdb/node-api":"^1.5.0-r.1","@freestyle-sh/with-bun":"^0.2.12","@freestyle-sh/with-deno":"^0.0.4","@freestyle-sh/with-nodejs":"^0.2.9","freestyle-sandboxes":"^0.1.46"},dependencies:{"@ai-sdk/anthropic":"^3.0.58","@ai-sdk/google":"^3.0.60","@ai-sdk/openai":"^3.0.50","@anthropic-ai/sdk":"^0.79.0","@aws-sdk/client-s3":"^3.1013.0","@aws-sdk/s3-request-presigner":"^3.1013.0","@clickhouse/client":"^1.8.1","@dnd-kit/core":"^6.3.1","@dnd-kit/sortable":"^10.0.0","@dnd-kit/utilities":"^3.2.2","@inkjs/ui":"^2.0.0","@modelcontextprotocol/ext-apps":"^1.2.2","@openrouter/ai-sdk-provider":"^2.2.5","@opentelemetry/core":"^2.6.0","@tanstack/react-virtual":"^3.13.21","@xterm/addon-fit":"^0.11.0","@xterm/xterm":"^6.0.0","ai-sdk-provider-claude-code":"^3.4.4","ai-sdk-provider-codex-cli":"^1.1.0","embedded-postgres":"^18.3.0-beta.16",ink:"^6.8.0",kysely:"^0.28.12",nats:"^2.29.3","posthog-js":"^1.371.1","posthog-node":"^5.0.0",react:"^19.2.0","react-dom":"^19.2.0"},devDependencies:{"@ai-sdk/provider":"^3.0.8","@ai-sdk/react":"^3.0.118","@anthropic-ai/claude-agent-sdk":"^0.2.80","@better-auth/sso":"1.4.1","@daveyplate/better-auth-ui":"^3.2.7","@deco/ui":"workspace:*","@decocms/better-auth":"1.5.17","@decocms/bindings":"workspace:*","@decocms/mcp-utils":"workspace:*","@decocms/mesh-sdk":"workspace:*","@decocms/runtime":"workspace:*","@decocms/vite-plugin":"workspace:*","@electric-sql/pglite":"^0.3.15","@floating-ui/react":"^0.27.16","@hookform/resolvers":"^5.2.2","@jitl/quickjs-wasmfile-release-sync":"0.31.0","@modelcontextprotocol/sdk":"1.27.1","@monaco-editor/react":"^4.7.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.211.0","@opentelemetry/exporter-logs-otlp-proto":"^0.211.0","@opentelemetry/exporter-prometheus":"^0.208.0","@opentelemetry/exporter-trace-otlp-proto":"^0.207.0","@opentelemetry/instrumentation-runtime-node":"^0.24.0","@opentelemetry/sdk-logs":"^0.211.0","@opentelemetry/sdk-metrics":"^2.2.0","@opentelemetry/sdk-node":"^0.207.0","@opentelemetry/sdk-trace-base":"^2.5.0","@playwright/test":"^1.58.2","@radix-ui/react-avatar":"^1.1.10","@radix-ui/react-checkbox":"^1.3.3","@radix-ui/react-dialog":"^1.1.15","@radix-ui/react-dropdown-menu":"^2.1.16","@radix-ui/react-label":"^2.1.7","@radix-ui/react-select":"^2.2.6","@radix-ui/react-separator":"^1.1.7","@radix-ui/react-slot":"^1.2.3","@radix-ui/react-tabs":"^1.1.13","@rjsf/core":"^6.1.2","@rjsf/shadcn":"^6.1.2","@rjsf/utils":"^6.1.2","@rjsf/validator-ajv8":"^6.1.2","@tailwindcss/vite":"^4.1.17","@tanstack/react-query":"5.90.11","@tanstack/react-router":"^1.139.7","@tiptap/core":"3.20.2","@tiptap/extension-mention":"3.20.2","@tiptap/extension-placeholder":"3.20.2","@tiptap/pm":"3.20.2","@tiptap/react":"3.20.2","@tiptap/starter-kit":"3.20.2","@tiptap/suggestion":"3.20.2","@types/bun":"^1.3.1","@types/pg":"^8.15.6","@types/react-syntax-highlighter":"^15.5.13","@untitledui/icons":"^0.0.19","@vercel/nft":"^1.1.1","@vitejs/plugin-react":"^5.1.0",ai:"^6.0.116","babel-plugin-react-compiler":"^1.0.0","better-auth":"1.4.5","class-variance-authority":"^0.7.1",clsx:"^2.1.1",concurrently:"^9.2.1",croner:"^9.1.0","date-fns":"^4.1.0",degit:"^2.8.4",hono:"^4.10.7","input-otp":"^1.4.2",jose:"^6.0.11","kysely-pglite":"^0.6.1","lucide-react":"^0.468.0",marked:"^15.0.6","@decocms/sandbox":"workspace:*","mesh-plugin-workflows":"workspace:*",nanoid:"^5.1.6",pg:"^8.16.3",prettier:"^3.4.2","react-hook-form":"^7.66.0","react-markdown":"^10.1.0","react-resizable-panels":"^2.1.7","react-syntax-highlighter":"^15.6.1",recharts:"^3.6.0","rehype-raw":"^7.0.0","remark-gfm":"^4.0.0","sass-embedded":"^1.97.2",sonner:"^2.0.7","tailwind-merge":"^3.3.1",tailwindcss:"^4.1.17",typescript:"^5.9.3",vite:"^7.2.1","vite-tsconfig-paths":"^5.1.4",zod:"^4.0.0",zustand:"^5.0.9"},homepage:"https://github.com/decocms/studio",keywords:["mcp","model-context-protocol","ai","gateway","self-hosted","mesh","tools"],license:"MIT",publishConfig:{access:"public"}}});import{Box as qU,Text as MX}from"ink";import{Spinner as Ii5}from"@inkjs/ui";import{useSyncExternalStore as Os6}from"react";import{jsx as qY,jsxs as tQ}from"react/jsx-runtime";function Si5(X,Y){if(!X||!Ri5.has(X))return X;let G=kN0[Y]??kN0[kN0.length-1];return X==="#875f00"?G[0]:G[1]}function Ds6({status:X}){if(X==="pending")return qY(Ii5,{label:""});return qY(MX,{color:"green",children:"\u2713"})}function ws6({services:X,migrationsStatus:Y,home:G,serverUrl:Q,vibe:J}){let W=Os6(Tu0,Au0),Z=Os6(Su0,Ru0);return tQ(qU,{flexDirection:"column",paddingBottom:1,children:[J?tQ(qU,{flexDirection:"column",children:[W.map(($,K)=>{let H=Z[K],U=$.reduce((B,z)=>B+z.text.length,0),N=Math.max(0,Mi5-U);return tQ(qU,{flexDirection:"row",children:[$.map((B,z)=>{let O=Si5(B.color,K);return O?qY(MX,{color:O,children:B.text},z):qY(MX,{children:B.text},z)}),qY(MX,{children:" ".repeat(N+2)}),H?.map((B,z)=>B.color?qY(MX,{color:B.color,children:B.char},z):qY(MX,{children:B.char},z))]},K)}),tQ(MX,{dimColor:!0,children:[" v",CN0.version]})]}):tQ(qU,{flexDirection:"column",marginTop:1,children:[Vi5.map(($,K)=>qY(MX,{color:ji5[K],children:$},K)),tQ(MX,{dimColor:!0,children:[" v",CN0.version]})]}),qY(qU,{marginBottom:1,children:qY(MX,{dimColor:!0,children:"\u2500".repeat(80)})}),qY(qU,{children:tQ(MX,{dimColor:!0,children:["Home: ",G]})}),tQ(qU,{gap:2,children:[X.map(($)=>tQ(qU,{gap:1,children:[tQ(MX,{children:[$.name," :",$.port||"...."]}),qY(Ds6,{status:$.status})]},$.name)),tQ(qU,{gap:1,children:[qY(MX,{children:"Migrations"}),qY(Ds6,{status:Y})]})]}),qY(qU,{children:Q?tQ(MX,{children:["Open in browser: ",qY(MX,{color:"cyan",children:Q})]}):qY(MX,{dimColor:!0,children:"Starting..."})}),tQ(qU,{gap:2,children:[tQ(MX,{dimColor:!0,children:[qY(MX,{bold:!0,dimColor:!0,children:"K"})," ","toggle config"]}),tQ(MX,{dimColor:!0,children:[qY(MX,{bold:!0,dimColor:!0,children:"L"})," ","toggle log flow"]}),tQ(MX,{dimColor:!0,children:[qY(MX,{bold:!0,dimColor:!0,children:"V"})," ","toggle vibe ",J?"\u266A Nihilore \xB7 CC BY 4.0":""]}),J&&tQ(MX,{dimColor:!0,children:[qY(MX,{bold:!0,dimColor:!0,children:"N"})," ","skip song"]})]})]})}var Vi5,ji5,kN0,Mi5=30,Ri5;var Ls6=D(()=>{zs6();Bn1();En1();Vi5=[" \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588 ","\u2591\u2591\u2588\u2588\u2588\u2591\u2591\u2591\u2591\u2588\u2588\u2588 \u2591\u2591\u2588\u2588\u2588\u2591\u2591\u2591\u2591\u2591\u2588 \u2588\u2588\u2588\u2591\u2591\u2591\u2591\u2591\u2588\u2588\u2588 \u2588\u2588\u2588\u2591\u2591\u2591\u2591\u2591\u2588\u2588\u2588 "," \u2591\u2588\u2588\u2588 \u2591\u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2588 \u2591 \u2588\u2588\u2588 \u2591\u2591\u2591 \u2588\u2588\u2588 \u2591\u2591\u2588\u2588\u2588"," \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588"," \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588\u2591\u2591\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588"," \u2591\u2588\u2588\u2588 \u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591 \u2588\u2591\u2591\u2588\u2588\u2588 \u2588\u2588\u2588\u2591\u2591\u2588\u2588\u2588 \u2588\u2588\u2588 "," \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2591\u2591\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2591\u2591\u2591\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2591 ","\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591 \u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591 \u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591 \u2591\u2591\u2591\u2591\u2591\u2591\u2591 "],ji5=["#00ff64","#00ee5e","#00dc56","#00c84e","#00b444","#00a03c","#008832","#006e28"],kN0=[["#00ff64","#00cc50"],["#00f060","#00c04c"],["#00e05c","#00b448"],["#00d058","#00a844"],["#00c054","#009c40"],["#00b050","#00903c"],["#00a04c","#008438"],["#009048","#007834"],["#008044","#006c30"],["#007040","#00602c"],["#00603c","#005428"]],Ri5=new Set(["#875f00","#5f3800"])});import{useSyncExternalStore as Ci5}from"react";function ki5(){let X=process.stdout.rows||24,Y=process.stdout.columns||80;if(X!==EA1.rows||Y!==EA1.columns)EA1={rows:X,columns:Y};return EA1}function vi5(X){return process.stdout.on("resize",X),()=>{process.stdout.off("resize",X)}}function Es6(){return Ci5(vi5,ki5)}var EA1;var Ps6=D(()=>{EA1={rows:process.stdout.rows||24,columns:process.stdout.columns||80}});import{Box as _i5,Text as qX1}from"ink";import{useSyncExternalStore as fi5}from"react";import{jsx as vN0,jsxs as _N0}from"react/jsx-runtime";function bi5(X){if(X>=500)return"red";if(X>=400)return"yellow";if(X>=300)return"cyan";return"green"}function qs6({logs:X,headerHeight:Y}){let{rows:G}=Es6(),{logFlow:Q}=fi5(Pe,Ee),J=Math.max(1,G-Y-1),W=Q?X:X.slice(-J);return vN0(_i5,{flexDirection:"column",children:W.map((Z,$)=>{if(Z.rawLine)return vN0(qX1,{dimColor:!0,children:Z.rawLine},$);let K=Z.duration<1000?`${Z.duration}ms`:`${(Z.duration/1000).toFixed(1)}s`;return _N0(qX1,{children:[_N0(qX1,{dimColor:!0,children:[Z.method.padEnd(6)," ",Z.path.padEnd(30)," "]}),vN0(qX1,{color:bi5(Z.status),children:Z.status}),_N0(qX1,{dimColor:!0,children:[" ",K.padStart(8)]})]},$)})})}var As6=D(()=>{YF();Ps6()});var fN0={};R0(fN0,{App:()=>mi5});import{Box as yi5,Text as xi5,useInput as hi5}from"ink";import{useSyncExternalStore as gi5}from"react";import{jsx as PA1,jsxs as di5}from"react/jsx-runtime";function mi5({home:X}){let Y=gi5(Pe,Ee);return hi5((G)=>{if(G==="k"||G==="K")Vn1();if(G==="l"||G==="L")jn1();if((G==="v"||G==="V")&&Y.dataDir)Tn1(Y.dataDir),Mn1();if((G==="n"||G==="N")&&Y.vibe)An1()}),di5(yi5,{flexDirection:"column",children:[PA1(ws6,{services:Y.services,migrationsStatus:Y.migrationsStatus,home:X,serverUrl:Y.serverUrl,vibe:Y.vibe}),Y.viewMode==="config"?Y.env?PA1(Ns6,{env:Y.env}):PA1(xi5,{dimColor:!0,children:"Loading configuration..."}):PA1(qs6,{logs:Y.logs,headerHeight:Y.vibe?li5:ui5})]})}var ui5=15,li5=19;var bN0=D(()=>{Bs6();Ls6();As6();YF();Ud()});function Ts6(X,Y={}){return{PORT:String(X.port),NODE_ENV:X.nodeEnv,BASE_URL:X.baseUrl,DATA_DIR:X.dataDir,DECOCMS_HOME:X.dataDir,DATABASE_URL:X.databaseUrl,DATABASE_PG_SSL:String(X.databasePgSsl),DATABASE_POOL_MAX:String(X.databasePoolMax),NATS_URL:X.natsUrls.join(","),BETTER_AUTH_SECRET:X.betterAuthSecret,ENCRYPTION_KEY:X.encryptionKey,MESH_JWT_SECRET:X.meshJwtSecret,DECOCMS_LOCAL_MODE:String(X.localMode),DECOCMS_ALLOW_LOCAL_PROD:String(X.allowLocalProd),DISABLE_RATE_LIMIT:String(X.disableRateLimit),STUDIO_PROVISION_SECRET_KEY:X.studioProvisionSecretKey,CONFIG_PATH:X.configPath,...Object.fromEntries(Object.entries(process.env).filter(([G])=>G.startsWith("AUTH_"))),UNSAFE_ALLOW_STDIO_TRANSPORT:String(X.unsafeAllowStdioTransport),DECO_AI_GATEWAY_ENABLED:String(X.aiGatewayEnabled),DECO_AI_GATEWAY_URL:X.aiGatewayUrl,ENABLE_DECO_IMPORT:String(X.enableDecoImport),S3_ENDPOINT:X.s3Endpoint,S3_BUCKET:X.s3Bucket,S3_REGION:X.s3Region,S3_ACCESS_KEY_ID:X.s3AccessKeyId,S3_SECRET_ACCESS_KEY:X.s3SecretAccessKey,S3_FORCE_PATH_STYLE:String(X.s3ForcePathStyle),OTEL_SERVICE_NAME:X.otelServiceName,CLICKHOUSE_URL:X.clickhouseUrl,DECO_SUPABASE_URL:X.decoSupabaseUrl,DECO_SUPABASE_SERVICE_KEY:X.decoSupabaseServiceKey,FIRECRAWL_API_KEY:X.firecrawlApiKey,STUDIO_SANDBOX_RUNNER:process.env.STUDIO_SANDBOX_RUNNER,FREESTYLE_API_KEY:process.env.FREESTYLE_API_KEY,BROWSERLESS_TOKEN:process.env.BROWSERLESS_TOKEN,NODE_EXTRA_CA_CERTS:process.env.NODE_EXTRA_CA_CERTS,DECO_CLI:"1",DECO_NO_TUI:"true",...Y}}function Vs6(X){if(!X)return!1;try{return new URL(X).host==="api.decocms.com"&&X!=="https://studio.decocms.com/org/deco/registry/mcp"}catch{return!1}}var Is6="https://studio.decocms.com/org/deco/registry/mcp";var yN0=(X,Y,G)=>{return(Q,J)=>{let W=-1;return Z(0);async function Z($){if($<=W)throw Error("next() called multiple times");W=$;let K,H=!1,U;if(X[$])U=X[$][0][0],Q.req.routeIndex=$;else U=$===X.length&&J||void 0;if(U)try{K=await U(Q,()=>Z($+1))}catch(N){if(N instanceof Error&&Y)Q.error=N,K=await Y(N,Q),H=!0;else throw N}else if(Q.finalized===!1&&G)K=await G(Q);if(K&&(Q.finalized===!1||H))Q.res=K;return Q}}};var js6=()=>{};var M9;var Lq=D(()=>{M9=class extends Error{res;status;constructor(X=500,Y){super(Y?.message,{cause:Y?.cause});this.res=Y?.res,this.status=X}getResponse(){if(this.res)return new Response(this.res.body,{status:this.status,headers:this.res.headers});return new Response(this.message,{status:this.status})}}});var Ms6;var Rs6=D(()=>{Ms6=Symbol()});async function ci5(X,Y){let G=await X.formData();if(G)return ii5(G,Y);return{}}function ii5(X,Y){let G=Object.create(null);if(X.forEach((Q,J)=>{if(!(Y.all||J.endsWith("[]")))G[J]=Q;else pi5(G,J,Q)}),Y.dot)Object.entries(G).forEach(([Q,J])=>{if(Q.includes("."))ni5(G,Q,J),delete G[Q]});return G}var Ss6=async(X,Y=Object.create(null))=>{let{all:G=!1,dot:Q=!1}=Y,W=(X instanceof qA1?X.raw.headers:X.headers).get("Content-Type");if(W?.startsWith("multipart/form-data")||W?.startsWith("application/x-www-form-urlencoded"))return ci5(X,{all:G,dot:Q});return{}},pi5=(X,Y,G)=>{if(X[Y]!==void 0)if(Array.isArray(X[Y]))X[Y].push(G);else X[Y]=[X[Y],G];else if(!Y.endsWith("[]"))X[Y]=G;else X[Y]=[G]},ni5=(X,Y,G)=>{if(/(?:^|\.)__proto__\./.test(Y))return;let Q=X,J=Y.split(".");J.forEach((W,Z)=>{if(Z===J.length-1)Q[W]=G;else{if(!Q[W]||typeof Q[W]!=="object"||Array.isArray(Q[W])||Q[W]instanceof File)Q[W]=Object.create(null);Q=Q[W]}})};var Cs6=D(()=>{xN0()});var gN0=(X)=>{let Y=X.split("/");if(Y[0]==="")Y.shift();return Y},ks6=(X)=>{let{groups:Y,path:G}=ai5(X),Q=gN0(G);return ti5(Q,Y)},ai5=(X)=>{let Y=[];return X=X.replace(/\{[^}]+\}/g,(G,Q)=>{let J=`@${Q}`;return Y.push([J,G]),J}),{groups:Y,path:X}},ti5=(X,Y)=>{for(let G=Y.length-1;G>=0;G--){let[Q]=Y[G];for(let J=X.length-1;J>=0;J--)if(X[J].includes(Q)){X[J]=X[J].replace(Q,Y[G][1]);break}}return X},AA1,vs6=(X,Y)=>{if(X==="*")return"*";let G=X.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(G){let Q=`${X}#${Y}`;if(!AA1[Q])if(G[2])AA1[Q]=Y&&Y[0]!==":"&&Y[0]!=="*"?[Q,G[1],new RegExp(`^${G[2]}(?=/${Y})`)]:[X,G[1],new RegExp(`^${G[2]}$`)];else AA1[Q]=[X,G[1],!0];return AA1[Q]}return null},la=(X,Y)=>{try{return Y(X)}catch{return X.replace(/(?:%[0-9A-Fa-f]{2})+/g,(G)=>{try{return Y(G)}catch{return G}})}},_s6=(X)=>la(X,decodeURI),uN0=(X)=>{let Y=X.url,G=Y.indexOf("/",Y.indexOf(":")+4),Q=G;for(;Q<Y.length;Q++){let J=Y.charCodeAt(Q);if(J===37){let W=Y.indexOf("?",Q),Z=Y.indexOf("#",Q),$=W===-1?Z===-1?void 0:Z:Z===-1?W:Math.min(W,Z),K=Y.slice(G,$);return _s6(K.includes("%25")?K.replace(/%25/g,"%2525"):K)}else if(J===63||J===35)break}return Y.slice(G,Q)},fs6=(X)=>{let Y=uN0(X);return Y.length>1&&Y.at(-1)==="/"?Y.slice(0,-1):Y},Pj=(X,Y,...G)=>{if(G.length)Y=Pj(Y,...G);return`${X?.[0]==="/"?"":"/"}${X}${Y==="/"?"":`${X?.at(-1)==="/"?"":"/"}${Y?.[0]==="/"?Y.slice(1):Y}`}`},TA1=(X)=>{if(X.charCodeAt(X.length-1)!==63||!X.includes(":"))return null;let Y=X.split("/"),G=[],Q="";return Y.forEach((J)=>{if(J!==""&&!/\:/.test(J))Q+="/"+J;else if(/\:/.test(J))if(/\?/.test(J)){if(G.length===0&&Q==="")G.push("/");else G.push(Q);let W=J.replace("?","");Q+="/"+W,G.push(Q)}else Q+="/"+J}),G.filter((J,W,Z)=>Z.indexOf(J)===W)},hN0=(X)=>{if(!/[%+]/.test(X))return X;if(X.indexOf("+")!==-1)X=X.replace(/\+/g," ");return X.indexOf("%")!==-1?la(X,AX1):X},bs6=(X,Y,G)=>{let Q;if(!G&&Y&&!/[%+]/.test(Y)){let Z=X.indexOf("?",8);if(Z===-1)return;if(!X.startsWith(Y,Z+1))Z=X.indexOf(`&${Y}`,Z+1);while(Z!==-1){let $=X.charCodeAt(Z+Y.length+1);if($===61){let K=Z+Y.length+2,H=X.indexOf("&",K);return hN0(X.slice(K,H===-1?void 0:H))}else if($==38||isNaN($))return"";Z=X.indexOf(`&${Y}`,Z+1)}if(Q=/[%+]/.test(X),!Q)return}let J={};Q??=/[%+]/.test(X);let W=X.indexOf("?",8);while(W!==-1){let Z=X.indexOf("&",W+1),$=X.indexOf("=",W);if($>Z&&Z!==-1)$=-1;let K=X.slice(W+1,$===-1?Z===-1?void 0:Z:$);if(Q)K=hN0(K);if(W=Z,K==="")continue;let H;if($===-1)H="";else if(H=X.slice($+1,Z===-1?void 0:Z),Q)H=hN0(H);if(G){if(!(J[K]&&Array.isArray(J[K])))J[K]=[];J[K].push(H)}else J[K]??=H}return Y?J[Y]:J},ys6,xs6=(X,Y)=>{return bs6(X,Y,!0)},AX1;var Eq=D(()=>{AA1={},ys6=bs6,AX1=decodeURIComponent});var hs6=(X)=>la(X,AX1),qA1;var xN0=D(()=>{Lq();Rs6();Cs6();Eq();qA1=class{raw;#X;#Y;routeIndex=0;path;bodyCache={};constructor(X,Y="/",G=[[]]){this.raw=X,this.path=Y,this.#Y=G,this.#X={}}param(X){return X?this.#G(X):this.#Q()}#G(X){let Y=this.#Y[0][this.routeIndex][1][X],G=this.#J(Y);return G&&/\%/.test(G)?hs6(G):G}#Q(){let X={},Y=Object.keys(this.#Y[0][this.routeIndex][1]);for(let G of Y){let Q=this.#J(this.#Y[0][this.routeIndex][1][G]);if(Q!==void 0)X[G]=/\%/.test(Q)?hs6(Q):Q}return X}#J(X){return this.#Y[1]?this.#Y[1][X]:X}query(X){return ys6(this.url,X)}queries(X){return xs6(this.url,X)}header(X){if(X)return this.raw.headers.get(X)??void 0;let Y={};return this.raw.headers.forEach((G,Q)=>{Y[Q]=G}),Y}async parseBody(X){return Ss6(this,X)}#Z=(X)=>{let{bodyCache:Y,raw:G}=this,Q=Y[X];if(Q)return Q;let J=Object.keys(Y)[0];if(J)return Y[J].then((W)=>{if(J==="json")W=JSON.stringify(W);return new Response(W)[X]()});return Y[X]=G[X]()};json(){return this.#Z("text").then((X)=>JSON.parse(X))}text(){return this.#Z("text")}arrayBuffer(){return this.#Z("arrayBuffer")}blob(){return this.#Z("blob")}formData(){return this.#Z("formData")}addValidatedData(X,Y){this.#X[X]=Y}valid(X){return this.#X[X]}get url(){return this.raw.url}get method(){return this.raw.method}get[Ms6](){return this.#Y}get matchedRoutes(){return this.#Y[0].map(([[,X]])=>X)}get routePath(){return this.#Y[0].map(([[,X]])=>X)[this.routeIndex].path}}});var IA1,gs6=(X,Y)=>{let G=new String(X);return G.isEscaped=!0,G.callbacks=Y,G},TX1=async(X,Y,G,Q,J)=>{if(typeof X==="object"&&!(X instanceof String)){if(!(X instanceof Promise))X=X.toString();if(X instanceof Promise)X=await X}let W=X.callbacks;if(!W?.length)return Promise.resolve(X);if(J)J[0]+=X;else J=[X];let Z=Promise.all(W.map(($)=>$({phase:Y,buffer:J,context:Q}))).then(($)=>Promise.all($.filter(Boolean).map((K)=>TX1(K,Y,!1,Q,J))).then(()=>J[0]));if(G)return gs6(await Z,W);else return Z};var VA1=D(()=>{IA1={Stringify:1,BeforeStream:2,Stream:3}});var us6="text/plain; charset=UTF-8",lN0=(X,Y)=>{return{"Content-Type":X,...Y}},IX1=(X,Y)=>new Response(X,Y),ls6=class{#X;#Y;env={};#G;finalized=!1;error;#Q;#J;#Z;#$;#W;#K;#H;#U;#N;constructor(X,Y){if(this.#X=X,Y)this.#J=Y.executionCtx,this.env=Y.env,this.#K=Y.notFoundHandler,this.#N=Y.path,this.#U=Y.matchResult}get req(){return this.#Y??=new qA1(this.#X,this.#N,this.#U),this.#Y}get event(){if(this.#J&&"respondWith"in this.#J)return this.#J;else throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#J)return this.#J;else throw Error("This context has no ExecutionContext")}get res(){return this.#Z||=IX1(null,{headers:this.#H??=new Headers})}set res(X){if(this.#Z&&X){X=IX1(X.body,X);for(let[Y,G]of this.#Z.headers.entries()){if(Y==="content-type")continue;if(Y==="set-cookie"){let Q=this.#Z.headers.getSetCookie();X.headers.delete("set-cookie");for(let J of Q)X.headers.append("set-cookie",J)}else X.headers.set(Y,G)}}this.#Z=X,this.finalized=!0}render=(...X)=>{return this.#W??=(Y)=>this.html(Y),this.#W(...X)};setLayout=(X)=>this.#$=X;getLayout=()=>this.#$;setRenderer=(X)=>{this.#W=X};header=(X,Y,G)=>{if(this.finalized)this.#Z=IX1(this.#Z.body,this.#Z);let Q=this.#Z?this.#Z.headers:this.#H??=new Headers;if(Y===void 0)Q.delete(X);else if(G?.append)Q.append(X,Y);else Q.set(X,Y)};status=(X)=>{this.#Q=X};set=(X,Y)=>{this.#G??=new Map,this.#G.set(X,Y)};get=(X)=>{return this.#G?this.#G.get(X):void 0};get var(){if(!this.#G)return{};return Object.fromEntries(this.#G)}#F(X,Y,G){let Q=this.#Z?new Headers(this.#Z.headers):this.#H??new Headers;if(typeof Y==="object"&&"headers"in Y){let W=Y.headers instanceof Headers?Y.headers:new Headers(Y.headers);for(let[Z,$]of W)if(Z.toLowerCase()==="set-cookie")Q.append(Z,$);else Q.set(Z,$)}if(G)for(let[W,Z]of Object.entries(G))if(typeof Z==="string")Q.set(W,Z);else{Q.delete(W);for(let $ of Z)Q.append(W,$)}let J=typeof Y==="number"?Y:Y?.status??this.#Q;return IX1(X,{status:J,headers:Q})}newResponse=(...X)=>this.#F(...X);body=(X,Y,G)=>this.#F(X,Y,G);text=(X,Y,G)=>{return!this.#H&&!this.#Q&&!Y&&!G&&!this.finalized?new Response(X):this.#F(X,Y,lN0(us6,G))};json=(X,Y,G)=>{return this.#F(JSON.stringify(X),Y,lN0("application/json",G))};html=(X,Y,G)=>{let Q=(J)=>this.#F(J,Y,lN0("text/html; charset=UTF-8",G));return typeof X==="object"?TX1(X,IA1.Stringify,!1,{}).then(Q):Q(X)};redirect=(X,Y)=>{let G=String(X);return this.header("Location",!/[^\x00-\xFF]/.test(G)?G:encodeURI(G)),this.newResponse(null,Y??302)};notFound=()=>{return this.#K??=()=>IX1(),this.#K(this)}};var jA1=D(()=>{xN0();VA1()});var T7="ALL",ms6="all",ds6,MA1="Can not add a route since the matcher is already built.",RA1;var Pq=D(()=>{ds6=["get","post","put","delete","options","patch"],RA1=class extends Error{}});var mN0="__COMPOSED_HANDLER";var dN0=()=>{};var ri5=(X)=>{return X.text("404 Not Found",404)},cs6=(X,Y)=>{if("getResponse"in X){let G=X.getResponse();return Y.newResponse(G.body,G)}return console.error(X),Y.text("Internal Server Error",500)},is6=class X{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#X="/";routes=[];constructor(Y={}){[...ds6,ms6].forEach((W)=>{this[W]=(Z,...$)=>{if(typeof Z==="string")this.#X=Z;else this.#Q(W,this.#X,Z);return $.forEach((K)=>{this.#Q(W,this.#X,K)}),this}}),this.on=(W,Z,...$)=>{for(let K of[Z].flat()){this.#X=K;for(let H of[W].flat())$.map((U)=>{this.#Q(H.toUpperCase(),this.#X,U)})}return this},this.use=(W,...Z)=>{if(typeof W==="string")this.#X=W;else this.#X="*",Z.unshift(W);return Z.forEach(($)=>{this.#Q(T7,this.#X,$)}),this};let{strict:Q,...J}=Y;Object.assign(this,J),this.getPath=Q??!0?Y.getPath??uN0:fs6}#Y(){let Y=new X({router:this.router,getPath:this.getPath});return Y.errorHandler=this.errorHandler,Y.#G=this.#G,Y.routes=this.routes,Y}#G=ri5;errorHandler=cs6;route(Y,G){let Q=this.basePath(Y);return G.routes.map((J)=>{let W;if(G.errorHandler===cs6)W=J.handler;else W=async(Z,$)=>(await yN0([],G.errorHandler)(Z,()=>J.handler(Z,$))).res,W[mN0]=J.handler;Q.#Q(J.method,J.path,W)}),this}basePath(Y){let G=this.#Y();return G._basePath=Pj(this._basePath,Y),G}onError=(Y)=>{return this.errorHandler=Y,this};notFound=(Y)=>{return this.#G=Y,this};mount(Y,G,Q){let J,W;if(Q)if(typeof Q==="function")W=Q;else if(W=Q.optionHandler,Q.replaceRequest===!1)J=(K)=>K;else J=Q.replaceRequest;let Z=W?(K)=>{let H=W(K);return Array.isArray(H)?H:[H]}:(K)=>{let H=void 0;try{H=K.executionCtx}catch{}return[K.env,H]};J||=(()=>{let K=Pj(this._basePath,Y),H=K==="/"?0:K.length;return(U)=>{let N=new URL(U.url);return N.pathname=N.pathname.slice(H)||"/",new Request(N,U)}})();let $=async(K,H)=>{let U=await G(J(K.req.raw),...Z(K));if(U)return U;await H()};return this.#Q(T7,Pj(Y,"*"),$),this}#Q(Y,G,Q){Y=Y.toUpperCase(),G=Pj(this._basePath,G);let J={basePath:this._basePath,path:G,method:Y,handler:Q};this.router.add(Y,G,[Q,J]),this.routes.push(J)}#J(Y,G){if(Y instanceof Error)return this.errorHandler(Y,G);throw Y}#Z(Y,G,Q,J){if(J==="HEAD")return(async()=>new Response(null,await this.#Z(Y,G,Q,"GET")))();let W=this.getPath(Y,{env:Q}),Z=this.router.match(J,W),$=new ls6(Y,{path:W,matchResult:Z,env:Q,executionCtx:G,notFoundHandler:this.#G});if(Z[0].length===1){let H;try{H=Z[0][0][0][0]($,async()=>{$.res=await this.#G($)})}catch(U){return this.#J(U,$)}return H instanceof Promise?H.then((U)=>U||($.finalized?$.res:this.#G($))).catch((U)=>this.#J(U,$)):H??this.#G($)}let K=yN0(Z[0],this.errorHandler,this.#G);return(async()=>{try{let H=await K($);if(!H.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return H.res}catch(H){return this.#J(H,$)}})()}fetch=(Y,...G)=>{return this.#Z(Y,G[1],G[0],Y.method)};request=(Y,G,Q,J)=>{if(Y instanceof Request)return this.fetch(G?new Request(Y,G):Y,Q,J);return Y=Y.toString(),this.fetch(new Request(/^https?:\/\//.test(Y)?Y:`http://localhost${Pj("/",Y)}`,G),Q,J)};fire=()=>{addEventListener("fetch",(Y)=>{Y.respondWith(this.#Z(Y.request,Y,void 0,Y.request.method))})}};var ps6=D(()=>{js6();jA1();Pq();dN0();Eq()});function SA1(X,Y){let G=this.buildAllMatchers(),Q=(J,W)=>{let Z=G[J]||G[T7],$=Z[2][W];if($)return $;let K=W.match(Z[0]);if(!K)return[[],VX1];let H=K.indexOf("",1);return[Z[1][H],K]};return this.match=Q,Q(X,Y)}var VX1;var cN0=D(()=>{Pq();VX1=[]});function si5(X,Y){if(X.length===1)return Y.length===1?X<Y?-1:1:-1;if(Y.length===1)return 1;if(X===jX1||X===MX1)return 1;else if(Y===jX1||Y===MX1)return-1;if(X===CA1)return 1;else if(Y===CA1)return-1;return X.length===Y.length?X<Y?-1:1:Y.length-X.length}var CA1="[^/]+",jX1=".*",MX1="(?:|/.*)",qj,oi5,ns6=class X{#X;#Y;#G=Object.create(null);insert(Y,G,Q,J,W){if(Y.length===0){if(this.#X!==void 0)throw qj;if(W)return;this.#X=G;return}let[Z,...$]=Y,K=Z==="*"?$.length===0?["","",jX1]:["","",CA1]:Z==="/*"?["","",MX1]:Z.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),H;if(K){let U=K[1],N=K[2]||CA1;if(U&&K[2]){if(N===".*")throw qj;if(N=N.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(N))throw qj}if(H=this.#G[N],!H){if(Object.keys(this.#G).some((B)=>B!==jX1&&B!==MX1))throw qj;if(W)return;if(H=this.#G[N]=new X,U!=="")H.#Y=J.varIndex++}if(!W&&U!=="")Q.push([U,H.#Y])}else if(H=this.#G[Z],!H){if(Object.keys(this.#G).some((U)=>U.length>1&&U!==jX1&&U!==MX1))throw qj;if(W)return;H=this.#G[Z]=new X}H.insert($,G,Q,J,W)}buildRegExpStr(){let G=Object.keys(this.#G).sort(si5).map((Q)=>{let J=this.#G[Q];return(typeof J.#Y==="number"?`(${Q})@${J.#Y}`:oi5.has(Q)?`\\${Q}`:Q)+J.buildRegExpStr()});if(typeof this.#X==="number")G.unshift(`#${this.#X}`);if(G.length===0)return"";if(G.length===1)return G[0];return"(?:"+G.join("|")+")"}};var iN0=D(()=>{qj=Symbol(),oi5=new Set(".\\+*[^]$()")});var as6=class{#X={varIndex:0};#Y=new ns6;insert(X,Y,G){let Q=[],J=[];for(let Z=0;;){let $=!1;if(X=X.replace(/\{[^}]+\}/g,(K)=>{let H=`@\\${Z}`;return J[Z]=[H,K],Z++,$=!0,H}),!$)break}let W=X.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let Z=J.length-1;Z>=0;Z--){let[$]=J[Z];for(let K=W.length-1;K>=0;K--)if(W[K].indexOf($)!==-1){W[K]=W[K].replace($,J[Z][1]);break}}return this.#Y.insert(W,Y,Q,this.#X,G),Q}buildRegExp(){let X=this.#Y.buildRegExpStr();if(X==="")return[/^$/,[],[]];let Y=0,G=[],Q=[];return X=X.replace(/#(\d+)|@(\d+)|\.\*\$/g,(J,W,Z)=>{if(W!==void 0)return G[++Y]=Number(W),"$()";if(Z!==void 0)return Q[Number(Z)]=++Y,"";return""}),[new RegExp(`^${X}`),G,Q]}};var ts6=D(()=>{iN0()});function os6(X){return rs6[X]??=new RegExp(X==="*"?"":`^${X.replace(/\/\*$|([.\\+*[^\]$()])/g,(Y,G)=>G?`\\${G}`:"(?:|/.*)")}$`)}function Xp5(){rs6=Object.create(null)}function Yp5(X){let Y=new as6,G=[];if(X.length===0)return ei5;let Q=X.map((H)=>[!/\*|\/:/.test(H[0]),...H]).sort(([H,U],[N,B])=>H?1:N?-1:U.length-B.length),J=Object.create(null);for(let H=0,U=-1,N=Q.length;H<N;H++){let[B,z,O]=Q[H];if(B)J[z]=[O.map(([E])=>[E,Object.create(null)]),VX1];else U++;let w;try{w=Y.insert(z,U,B)}catch(E){throw E===qj?new RA1(z):E}if(B)continue;G[U]=O.map(([E,P])=>{let q=Object.create(null);P-=1;for(;P>=0;P--){let[j,M]=w[P];q[j]=M}return[E,q]})}let[W,Z,$]=Y.buildRegExp();for(let H=0,U=G.length;H<U;H++)for(let N=0,B=G[H].length;N<B;N++){let z=G[H][N]?.[1];if(!z)continue;let O=Object.keys(z);for(let w=0,E=O.length;w<E;w++)z[O[w]]=$[z[O[w]]]}let K=[];for(let H in Z)K[H]=G[Z[H]];return[W,K,J]}function ma(X,Y){if(!X)return;for(let G of Object.keys(X).sort((Q,J)=>J.length-Q.length))if(os6(G).test(Y))return[...X[G]];return}var ei5,rs6,kA1=class{name="RegExpRouter";#X;#Y;constructor(){this.#X={[T7]:Object.create(null)},this.#Y={[T7]:Object.create(null)}}add(X,Y,G){let Q=this.#X,J=this.#Y;if(!Q||!J)throw Error(MA1);if(!Q[X])[Q,J].forEach(($)=>{$[X]=Object.create(null),Object.keys($[T7]).forEach((K)=>{$[X][K]=[...$[T7][K]]})});if(Y==="/*")Y="*";let W=(Y.match(/\/:/g)||[]).length;if(/\*$/.test(Y)){let $=os6(Y);if(X===T7)Object.keys(Q).forEach((K)=>{Q[K][Y]||=ma(Q[K],Y)||ma(Q[T7],Y)||[]});else Q[X][Y]||=ma(Q[X],Y)||ma(Q[T7],Y)||[];Object.keys(Q).forEach((K)=>{if(X===T7||X===K)Object.keys(Q[K]).forEach((H)=>{$.test(H)&&Q[K][H].push([G,W])})}),Object.keys(J).forEach((K)=>{if(X===T7||X===K)Object.keys(J[K]).forEach((H)=>$.test(H)&&J[K][H].push([G,W]))});return}let Z=TA1(Y)||[Y];for(let $=0,K=Z.length;$<K;$++){let H=Z[$];Object.keys(J).forEach((U)=>{if(X===T7||X===U)J[U][H]||=[...ma(Q[U],H)||ma(Q[T7],H)||[]],J[U][H].push([G,W-K+$+1])})}}match=SA1;buildAllMatchers(){let X=Object.create(null);return Object.keys(this.#Y).concat(Object.keys(this.#X)).forEach((Y)=>{X[Y]||=this.#G(Y)}),this.#X=this.#Y=void 0,Xp5(),X}#G(X){let Y=[],G=X===T7;if([this.#X,this.#Y].forEach((Q)=>{let J=Q[X]?Object.keys(Q[X]).map((W)=>[W,Q[X][W]]):[];if(J.length!==0)G||=!0,Y.push(...J);else if(X!==T7)Y.push(...Object.keys(Q[T7]).map((W)=>[W,Q[T7][W]]))}),!G)return null;else return Yp5(Y)}};var pN0=D(()=>{Pq();Eq();cN0();iN0();ts6();ei5=[/^$/,[],Object.create(null)],rs6=Object.create(null)});var Gp5=class{name="PreparedRegExpRouter";#X;#Y;constructor(X,Y){this.#X=X,this.#Y=Y}#G(X,Y){let G=this.#X[X];G[1].forEach((Q)=>Q&&Q.push(Y)),Object.values(G[2]).forEach((Q)=>Q[0].push(Y))}#Q(X,Y,G,Q,J){let W=this.#X[X];if(!J)W[2][Y][0].push([G,{}]);else Q.forEach((Z)=>{if(typeof Z==="number")W[1][Z].push([G,J]);else W[2][Z||Y][0].push([G,J])})}add(X,Y,G){if(!this.#X[X]){let J=this.#X[T7],W={};for(let Z in J[2])W[Z]=[J[2][Z][0].slice(),VX1];this.#X[X]=[J[0],J[1].map((Z)=>Array.isArray(Z)?Z.slice():0),W]}if(Y==="/*"||Y==="*"){let J=[G,{}];if(X===T7)for(let W in this.#X)this.#G(W,J);else this.#G(X,J);return}let Q=this.#Y[Y];if(!Q)throw Error(`Path ${Y} is not registered`);for(let[J,W]of Q)if(X===T7)for(let Z in this.#X)this.#Q(Z,Y,G,J,W);else this.#Q(X,Y,G,J,W)}buildAllMatchers(){return this.#X}match=SA1};var ss6=D(()=>{Pq();cN0();pN0()});var es6=D(()=>{pN0();ss6()});var nN0=class{name="SmartRouter";#X=[];#Y=[];constructor(X){this.#X=X.routers}add(X,Y,G){if(!this.#Y)throw Error(MA1);this.#Y.push([X,Y,G])}match(X,Y){if(!this.#Y)throw Error("Fatal error");let G=this.#X,Q=this.#Y,J=G.length,W=0,Z;for(;W<J;W++){let $=G[W];try{for(let K=0,H=Q.length;K<H;K++)$.add(...Q[K]);Z=$.match(X,Y)}catch(K){if(K instanceof RA1)continue;throw K}this.match=$.match.bind($),this.#X=[$],this.#Y=void 0;break}if(W===J)throw Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,Z}get activeRouter(){if(this.#Y||this.#X.length!==1)throw Error("No active router has been determined yet.");return this.#X[0]}};var Xe6=D(()=>{Pq()});var Ye6=D(()=>{Xe6()});var RX1,Qp5=(X)=>{for(let Y in X)return!0;return!1},Ge6=class X{#X;#Y;#G;#Q=0;#J=RX1;constructor(Y,G,Q){if(this.#Y=Q||Object.create(null),this.#X=[],Y&&G){let J=Object.create(null);J[Y]={handler:G,possibleKeys:[],score:0},this.#X=[J]}this.#G=[]}insert(Y,G,Q){this.#Q=++this.#Q;let J=this,W=ks6(G),Z=[];for(let $=0,K=W.length;$<K;$++){let H=W[$],U=W[$+1],N=vs6(H,U),B=Array.isArray(N)?N[0]:H;if(B in J.#Y){if(J=J.#Y[B],N)Z.push(N[1]);continue}if(J.#Y[B]=new X,N)J.#G.push(N),Z.push(N[1]);J=J.#Y[B]}return J.#X.push({[Y]:{handler:Q,possibleKeys:Z.filter(($,K,H)=>H.indexOf($)===K),score:this.#Q}}),J}#Z(Y,G,Q,J,W){for(let Z=0,$=G.#X.length;Z<$;Z++){let K=G.#X[Z],H=K[Q]||K[T7],U={};if(H!==void 0){if(H.params=Object.create(null),Y.push(H),J!==RX1||W&&W!==RX1)for(let N=0,B=H.possibleKeys.length;N<B;N++){let z=H.possibleKeys[N],O=U[H.score];H.params[z]=W?.[z]&&!O?W[z]:J[z]??W?.[z],U[H.score]=!0}}}}search(Y,G){let Q=[];this.#J=RX1;let W=[this],Z=gN0(G),$=[],K=Z.length,H=null;for(let U=0;U<K;U++){let N=Z[U],B=U===K-1,z=[];for(let w=0,E=W.length;w<E;w++){let P=W[w],q=P.#Y[N];if(q)if(q.#J=P.#J,B){if(q.#Y["*"])this.#Z(Q,q.#Y["*"],Y,P.#J);this.#Z(Q,q,Y,P.#J)}else z.push(q);for(let j=0,M=P.#G.length;j<M;j++){let V=P.#G[j],R=P.#J===RX1?{}:{...P.#J};if(V==="*"){let h=P.#Y["*"];if(h)this.#Z(Q,h,Y,P.#J),h.#J=R,z.push(h);continue}let[k,_,v]=V;if(!N&&!(v instanceof RegExp))continue;let y=P.#Y[k];if(v instanceof RegExp){if(H===null){H=Array(K);let p=G[0]==="/"?1:0;for(let f=0;f<K;f++)H[f]=p,p+=Z[f].length+1}let h=G.substring(H[U]),i=v.exec(h);if(i){if(R[_]=i[0],this.#Z(Q,y,Y,P.#J,R),Qp5(y.#Y)){y.#J=R;let p=i[0].match(/\//)?.length??0;($[p]||=[]).push(y)}continue}}if(v===!0||v.test(N))if(R[_]=N,B){if(this.#Z(Q,y,Y,R,P.#J),y.#Y["*"])this.#Z(Q,y.#Y["*"],Y,R,P.#J)}else y.#J=R,z.push(y)}}let O=$.shift();W=O?z.concat(O):z}if(Q.length>1)Q.sort((U,N)=>{return U.score-N.score});return[Q.map(({handler:U,params:N})=>[U,N])]}};var Qe6=D(()=>{Pq();Eq();RX1=Object.create(null)});var aN0=class{name="TrieRouter";#X;constructor(){this.#X=new Ge6}add(X,Y,G){let Q=TA1(Y);if(Q){for(let J=0,W=Q.length;J<W;J++)this.#X.insert(X,Q[J],G);return}this.#X.insert(X,Y,G)}match(X,Y){return this.#X.search(X,Y)}};var Je6=D(()=>{Eq();Qe6()});var Ze6=D(()=>{Je6()});var R5;var We6=D(()=>{ps6();es6();Ye6();Ze6();R5=class extends is6{constructor(X={}){super(X);this.router=X.router??new nN0({routers:[new kA1,new aN0]})}}});var JQ=D(()=>{We6()});var Ke6,Jp5,$e6=(X)=>{let Y=0,G=X.length;while(Y<G){let Q=X.charCodeAt(Y);if(Q!==32&&Q!==9)break;Y++}while(G>Y){let Q=X.charCodeAt(G-1);if(Q!==32&&Q!==9)break;G--}return Y===0&&G===X.length?X:X.slice(Y,G)},tN0=(X,Y)=>{if(Y&&X.indexOf(Y)===-1)return{};let G=X.split(";"),Q={};for(let J of G){let W=J.indexOf("=");if(W===-1)continue;let Z=$e6(J.substring(0,W));if(Y&&Y!==Z||!Ke6.test(Z))continue;let $=$e6(J.substring(W+1));if($.startsWith('"')&&$.endsWith('"'))$=$.slice(1,-1);if(Jp5.test($)){if(Q[Z]=$.indexOf("%")!==-1?la($,AX1):$,Y)break}}return Q},Zp5=(X,Y,G={})=>{if(!Ke6.test(X))throw Error("Invalid cookie name");let Q=`${X}=${Y}`;if(X.startsWith("__Secure-")&&!G.secure)throw Error("__Secure- Cookie must have Secure attributes");if(X.startsWith("__Host-")){if(!G.secure)throw Error("__Host- Cookie must have Secure attributes");if(G.path!=="/")throw Error('__Host- Cookie must have Path attributes with "/"');if(G.domain)throw Error("__Host- Cookie must not have Domain attributes")}for(let J of["domain","path"])if(G[J]&&/[;\r\n]/.test(G[J]))throw Error(`${J} must not contain ";", "\\r", or "\\n"`);if(G&&typeof G.maxAge==="number"&&G.maxAge>=0){if(G.maxAge>34560000)throw Error("Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.");Q+=`; Max-Age=${G.maxAge|0}`}if(G.domain&&G.prefix!=="host")Q+=`; Domain=${G.domain}`;if(G.path)Q+=`; Path=${G.path}`;if(G.expires){if(G.expires.getTime()-Date.now()>34560000000)throw Error("Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.");Q+=`; Expires=${G.expires.toUTCString()}`}if(G.httpOnly)Q+="; HttpOnly";if(G.secure)Q+="; Secure";if(G.sameSite)Q+=`; SameSite=${G.sameSite.charAt(0).toUpperCase()+G.sameSite.slice(1)}`;if(G.priority)Q+=`; Priority=${G.priority.charAt(0).toUpperCase()+G.priority.slice(1)}`;if(G.partitioned){if(!G.secure)throw Error("Partitioned Cookie must have Secure attributes");Q+="; Partitioned"}return Q},vA1=(X,Y,G)=>{return Y=encodeURIComponent(Y),Zp5(X,Y,G)};var He6=D(()=>{Eq();Ke6=/^[\w!#$%&'*.^`|~+-]+$/,Jp5=/^[ !#-:<-[\]-~]*$/});var _A1=(X,Y,G)=>{let Q=X.req.raw.headers.get("Cookie");if(typeof Y==="string"){if(!Q)return;let W=Y;if(G==="secure")W="__Secure-"+Y;else if(G==="host")W="__Host-"+Y;return tN0(Q,W)[W]}if(!Q)return{};return tN0(Q)},Wp5=(X,Y,G)=>{let Q;if(G?.prefix==="secure")Q=vA1("__Secure-"+X,Y,{path:"/",...G,secure:!0});else if(G?.prefix==="host")Q=vA1("__Host-"+X,Y,{...G,path:"/",secure:!0,domain:void 0});else Q=vA1(X,Y,{path:"/",...G});return Q},rN0=(X,Y,G,Q)=>{let J=Wp5(Y,G,Q);X.header("Set-Cookie",J,{append:!0})};var oN0=D(()=>{He6()});var Fe6=(X)=>{let G={...{origin:"*",allowMethods:["GET","HEAD","PUT","POST","DELETE","PATCH"],allowHeaders:[],exposeHeaders:[]},...X},Q=((W)=>{if(typeof W==="string")if(W==="*"){if(G.credentials)return(Z)=>Z||null;return()=>W}else return(Z)=>W===Z?Z:null;else if(typeof W==="function")return W;else return(Z)=>W.includes(Z)?Z:null})(G.origin),J=((W)=>{if(typeof W==="function")return W;else if(Array.isArray(W))return()=>W;else return()=>[]})(G.allowMethods);return async function(Z,$){function K(U,N){Z.res.headers.set(U,N)}let H=await Q(Z.req.header("origin")||"",Z);if(H)K("Access-Control-Allow-Origin",H);if(G.credentials)K("Access-Control-Allow-Credentials","true");if(G.exposeHeaders?.length)K("Access-Control-Expose-Headers",G.exposeHeaders.join(","));if(Z.req.method==="OPTIONS"){if(G.origin!=="*"||G.credentials)K("Vary","Origin");if(G.maxAge!=null)K("Access-Control-Max-Age",G.maxAge.toString());let U=await J(Z.req.header("origin")||"",Z);if(U.length)K("Access-Control-Allow-Methods",U.join(","));let N=G.allowHeaders;if(!N?.length){let B=Z.req.header("Access-Control-Request-Headers");if(B)N=B.split(/\s*,\s*/)}if(N?.length)K("Access-Control-Allow-Headers",N.join(",")),Z.res.headers.append("Vary","Access-Control-Request-Headers");return Z.res.headers.delete("Content-Length"),Z.res.headers.delete("Content-Type"),new Response(null,{headers:Z.res.headers,status:204,statusText:"No Content"})}if(await $(),G.origin!=="*"||G.credentials)Z.header("Vary","Origin",{append:!0})}};var Ue6=()=>{};var Ne6=()=>{try{return performance.now()}catch{}return Date.now()},sN0=(X)=>{let Y={total:!0,enabled:!0,totalDescription:"Total Response Time",autoEnd:!0,crossOrigin:!1,...X};return async function(Q,J){let W=[],Z=new Map;if(Q.get("metric"))return await J();if(Q.set("metric",{headers:W,timers:Z}),Y.total)zH(Q,"total",Y.totalDescription);if(await J(),Y.total)h$(Q,"total");if(Y.autoEnd)Z.forEach((K,H)=>h$(Q,H));if(typeof Y.enabled==="function"?Y.enabled(Q):Y.enabled){Q.res.headers.append("Server-Timing",W.join(","));let K=typeof Y.crossOrigin==="function"?Y.crossOrigin(Q):Y.crossOrigin;if(K)Q.res.headers.append("Timing-Allow-Origin",typeof K==="string"?K:"*")}}},Be6=(X,Y,G,Q,J)=>{let W=X.get("metric");if(!W){console.warn("Metrics not initialized! Please add the `timing()` middleware to this route!");return}if(typeof G==="number"){let Z=G.toFixed(J||1),$=Q?`${Y};dur=${Z};desc="${Q}"`:`${Y};dur=${Z}`;W.headers.push($)}else{let Z=G?`${Y};desc="${G}"`:`${Y}`;W.headers.push(Z)}},zH=(X,Y,G)=>{let Q=X.get("metric");if(!Q){console.warn("Metrics not initialized! Please add the `timing()` middleware to this route!");return}Q.timers.set(Y,{description:G,start:Ne6()})},h$=(X,Y,G)=>{let Q=X.get("metric");if(!Q){console.warn("Metrics not initialized! Please add the `timing()` middleware to this route!");return}let J=Q.timers.get(Y);if(!J){console.warn(`Timer "${Y}" does not exist!`);return}let{description:W,start:Z}=J,$=Ne6()-Z;Be6(X,Y,$,W,G),Q.timers.delete(Y)};var ze6=D(()=>{jA1()});var eN0=D(()=>{ze6()});function SX1(){let X={Organizations:[],Connections:[],"Virtual MCPs":[],Threads:[],Monitoring:[],Users:[],"API Keys":[],"Event Bus":[],Tags:[],"AI Providers":[],Automations:[],"Object Storage":[],Registry:[],GitHub:[],VM:[]};for(let Y of XB0)X[Y.category]?.push(Y);return X}var XB0;var YB0=D(()=>{XB0=[{name:"ORGANIZATION_CREATE",description:"Create a new organization",category:"Organizations"},{name:"ORGANIZATION_LIST",description:"List organizations",category:"Organizations"},{name:"ORGANIZATION_GET",description:"View organization details",category:"Organizations"},{name:"ORGANIZATION_UPDATE",description:"Update organization",category:"Organizations"},{name:"ORGANIZATION_DELETE",description:"Delete organization",category:"Organizations",dangerous:!0},{name:"ORGANIZATION_SETTINGS_GET",description:"View organization settings",category:"Organizations"},{name:"ORGANIZATION_SETTINGS_UPDATE",description:"Update organization settings",category:"Organizations"},{name:"BRAND_CONTEXT_LIST",description:"List brand contexts",category:"Organizations"},{name:"BRAND_CONTEXT_GET",description:"View brand context",category:"Organizations"},{name:"BRAND_CONTEXT_CREATE",description:"Create brand context",category:"Organizations"},{name:"BRAND_CONTEXT_UPDATE",description:"Update brand context",category:"Organizations"},{name:"BRAND_CONTEXT_DELETE",description:"Delete brand context",category:"Organizations",dangerous:!0},{name:"BRAND_CONTEXT_EXTRACT",description:"Extract brand context from website",category:"Organizations"},{name:"BRAND_GET",description:"Get brand (binding)",category:"Organizations"},{name:"BRAND_LIST",description:"List brands (binding)",category:"Organizations"},{name:"ORGANIZATION_DOMAIN_GET",description:"Get organization domain claim",category:"Organizations"},{name:"ORGANIZATION_DOMAIN_SET",description:"Set organization domain claim",category:"Organizations"},{name:"ORGANIZATION_DOMAIN_UPDATE",description:"Update organization domain settings",category:"Organizations"},{name:"ORGANIZATION_DOMAIN_CLEAR",description:"Clear organization domain claim",category:"Organizations"},{name:"ORGANIZATION_MEMBER_ADD",description:"Add members",category:"Organizations"},{name:"ORGANIZATION_MEMBER_REMOVE",description:"Remove members",category:"Organizations",dangerous:!0},{name:"ORGANIZATION_MEMBER_LIST",description:"List members",category:"Organizations"},{name:"ORGANIZATION_MEMBER_UPDATE_ROLE",description:"Update member roles",category:"Organizations"},{name:"COLLECTION_CONNECTIONS_CREATE",description:"Create connections",category:"Connections"},{name:"COLLECTION_CONNECTIONS_LIST",description:"List connections",category:"Connections"},{name:"COLLECTION_CONNECTIONS_GET",description:"View connection details",category:"Connections"},{name:"COLLECTION_CONNECTIONS_UPDATE",description:"Update connections",category:"Connections"},{name:"COLLECTION_CONNECTIONS_DELETE",description:"Delete connections",category:"Connections",dangerous:!0},{name:"CONNECTION_TEST",description:"Test connections",category:"Connections"},{name:"DATABASES_RUN_SQL",description:"Run SQL queries",category:"Connections",dangerous:!0},{name:"COLLECTION_VIRTUAL_MCP_CREATE",description:"Create virtual MCPs",category:"Virtual MCPs"},{name:"COLLECTION_VIRTUAL_MCP_LIST",description:"List virtual MCPs",category:"Virtual MCPs"},{name:"COLLECTION_VIRTUAL_MCP_GET",description:"View virtual MCP details",category:"Virtual MCPs"},{name:"COLLECTION_VIRTUAL_MCP_UPDATE",description:"Update virtual MCPs",category:"Virtual MCPs"},{name:"COLLECTION_VIRTUAL_MCP_DELETE",description:"Delete virtual MCPs",category:"Virtual MCPs",dangerous:!0},{name:"MONITORING_LOG_GET",description:"View monitoring log details",category:"Monitoring"},{name:"MONITORING_LOGS_LIST",description:"List monitoring logs",category:"Monitoring"},{name:"MONITORING_STATS",description:"View monitoring statistics",category:"Monitoring"},{name:"API_KEY_CREATE",description:"Create API key",category:"API Keys"},{name:"API_KEY_LIST",description:"List API keys",category:"API Keys"},{name:"API_KEY_UPDATE",description:"Update API key",category:"API Keys"},{name:"API_KEY_DELETE",description:"Delete API key",category:"API Keys",dangerous:!0},{name:"EVENT_PUBLISH",description:"Publish events",category:"Event Bus"},{name:"EVENT_SUBSCRIBE",description:"Subscribe to events",category:"Event Bus"},{name:"EVENT_UNSUBSCRIBE",description:"Unsubscribe from events",category:"Event Bus"},{name:"EVENT_CANCEL",description:"Cancel recurring events",category:"Event Bus"},{name:"EVENT_ACK",description:"Acknowledge event delivery",category:"Event Bus"},{name:"EVENT_SUBSCRIPTION_LIST",description:"List event subscriptions",category:"Event Bus"},{name:"EVENT_SYNC_SUBSCRIPTIONS",description:"Sync subscriptions to desired state",category:"Event Bus"},{name:"USER_GET",description:"Get a user by id",category:"Users"},{name:"COLLECTION_THREADS_CREATE",description:"Create threads",category:"Threads"},{name:"COLLECTION_THREADS_LIST",description:"List threads",category:"Threads"},{name:"COLLECTION_THREADS_GET",description:"View thread details",category:"Threads"},{name:"COLLECTION_THREADS_UPDATE",description:"Update threads",category:"Threads"},{name:"COLLECTION_THREADS_DELETE",description:"Delete threads",category:"Threads",dangerous:!0},{name:"COLLECTION_THREAD_MESSAGES_LIST",description:"List thread messages",category:"Threads"},{name:"TAGS_LIST",description:"List organization tags",category:"Tags"},{name:"TAGS_CREATE",description:"Create organization tag",category:"Tags"},{name:"TAGS_DELETE",description:"Delete organization tag",category:"Tags",dangerous:!0},{name:"MEMBER_TAGS_GET",description:"Get member tags",category:"Tags"},{name:"MEMBER_TAGS_SET",description:"Set member tags",category:"Tags"},{name:"AUTOMATION_CREATE",description:"Create automation",category:"Automations"},{name:"AUTOMATION_GET",description:"View automation details",category:"Automations"},{name:"AUTOMATION_LIST",description:"List automations",category:"Automations"},{name:"AUTOMATION_UPDATE",description:"Update automation",category:"Automations"},{name:"AUTOMATION_DELETE",description:"Delete automation",category:"Automations",dangerous:!0},{name:"AUTOMATION_TRIGGER_ADD",description:"Add trigger to automation",category:"Automations"},{name:"AUTOMATION_TRIGGER_REMOVE",description:"Remove trigger from automation",category:"Automations"},{name:"AUTOMATION_RUN",description:"Manually trigger an automation run",category:"Automations"},{name:"VIRTUAL_MCP_PLUGIN_CONFIG_GET",description:"View virtual MCP plugin configuration",category:"Virtual MCPs"},{name:"VIRTUAL_MCP_PLUGIN_CONFIG_UPDATE",description:"Update virtual MCP plugin configuration",category:"Virtual MCPs"},{name:"VIRTUAL_MCP_PINNED_VIEWS_UPDATE",description:"Update virtual MCP pinned sidebar views",category:"Virtual MCPs"},{name:"AI_PROVIDERS_LIST",description:"List available AI providers",category:"AI Providers"},{name:"AI_PROVIDERS_LIST_MODELS",description:"List AI provider models",category:"AI Providers"},{name:"AI_PROVIDERS_ACTIVE",description:"List active AI providers",category:"AI Providers"},{name:"AI_PROVIDER_KEY_CREATE",description:"Store AI provider API key",category:"AI Providers"},{name:"AI_PROVIDER_KEY_LIST",description:"List AI provider API keys",category:"AI Providers"},{name:"AI_PROVIDER_KEY_DELETE",description:"Delete AI provider API key",category:"AI Providers",dangerous:!0},{name:"AI_PROVIDER_OAUTH_URL",description:"Get OAuth URL for provider",category:"AI Providers"},{name:"AI_PROVIDER_OAUTH_EXCHANGE",description:"Exchange OAuth code for API key",category:"AI Providers"},{name:"AI_PROVIDER_PROVISION_KEY",description:"Auto-provision API key for a provider",category:"AI Providers"},{name:"AI_PROVIDER_TOPUP_URL",description:"Get checkout URL to top up provider credits",category:"AI Providers"},{name:"AI_PROVIDER_CREDITS",description:"Get current credit balance for a provider",category:"AI Providers"},{name:"AI_PROVIDER_CLI_ACTIVATE",description:"Activate Claude Code via local CLI",category:"AI Providers"},{name:"LIST_OBJECTS",description:"List objects in storage",category:"Object Storage"},{name:"GET_OBJECT_METADATA",description:"Get object metadata",category:"Object Storage"},{name:"GET_PRESIGNED_URL",description:"Generate download URL",category:"Object Storage"},{name:"PUT_PRESIGNED_URL",description:"Generate upload URL",category:"Object Storage"},{name:"DELETE_OBJECT",description:"Delete object",category:"Object Storage",dangerous:!0},{name:"DELETE_OBJECTS",description:"Delete multiple objects",category:"Object Storage",dangerous:!0},{name:"COLLECTION_REGISTRY_APP_LIST",description:"List registry apps",category:"Registry"},{name:"COLLECTION_REGISTRY_APP_GET",description:"Get registry app details",category:"Registry"},{name:"COLLECTION_REGISTRY_APP_VERSIONS",description:"List registry app versions",category:"Registry"},{name:"COLLECTION_REGISTRY_APP_FILTERS",description:"Get registry app filters",category:"Registry"},{name:"REGISTRY_ITEM_LIST",description:"List private registry items",category:"Registry"},{name:"REGISTRY_ITEM_SEARCH",description:"Search registry items",category:"Registry"},{name:"REGISTRY_ITEM_GET",description:"Get registry item details",category:"Registry"},{name:"REGISTRY_ITEM_VERSIONS",description:"List registry item versions",category:"Registry"},{name:"REGISTRY_ITEM_CREATE",description:"Create registry item",category:"Registry"},{name:"REGISTRY_ITEM_BULK_CREATE",description:"Bulk create registry items",category:"Registry"},{name:"REGISTRY_ITEM_UPDATE",description:"Update registry item",category:"Registry"},{name:"REGISTRY_ITEM_DELETE",description:"Delete registry item",category:"Registry",dangerous:!0},{name:"REGISTRY_ITEM_FILTERS",description:"Get registry item filters",category:"Registry"},{name:"REGISTRY_DISCOVER_TOOLS",description:"Discover tools from MCP server",category:"Registry"},{name:"REGISTRY_AI_GENERATE",description:"AI-generate registry content",category:"Registry"},{name:"REGISTRY_PUBLISH_REQUEST_LIST",description:"List publish requests",category:"Registry"},{name:"REGISTRY_PUBLISH_REQUEST_REVIEW",description:"Review publish request",category:"Registry"},{name:"REGISTRY_PUBLISH_REQUEST_COUNT",description:"Count pending publish requests",category:"Registry"},{name:"REGISTRY_PUBLISH_REQUEST_DELETE",description:"Delete publish request",category:"Registry",dangerous:!0},{name:"REGISTRY_PUBLISH_API_KEY_GENERATE",description:"Generate publish API key",category:"Registry"},{name:"REGISTRY_PUBLISH_API_KEY_LIST",description:"List publish API keys",category:"Registry"},{name:"REGISTRY_PUBLISH_API_KEY_REVOKE",description:"Revoke publish API key",category:"Registry",dangerous:!0},{name:"REGISTRY_MONITOR_RUN_START",description:"Start monitor run",category:"Registry"},{name:"REGISTRY_MONITOR_RUN_LIST",description:"List monitor runs",category:"Registry"},{name:"REGISTRY_MONITOR_RUN_GET",description:"Get monitor run details",category:"Registry"},{name:"REGISTRY_MONITOR_RUN_CANCEL",description:"Cancel monitor run",category:"Registry"},{name:"REGISTRY_MONITOR_RESULT_LIST",description:"List monitor results",category:"Registry"},{name:"REGISTRY_MONITOR_CONNECTION_LIST",description:"List monitor connections",category:"Registry"},{name:"REGISTRY_MONITOR_CONNECTION_SYNC",description:"Sync monitor connections",category:"Registry"},{name:"REGISTRY_MONITOR_CONNECTION_UPDATE_AUTH",description:"Update monitor connection auth",category:"Registry"},{name:"REGISTRY_MONITOR_SCHEDULE_SET",description:"Set monitor schedule",category:"Registry"},{name:"REGISTRY_MONITOR_SCHEDULE_CANCEL",description:"Cancel monitor schedule",category:"Registry"},{name:"VM_START",description:"Start a Freestyle VM with dev server preview",category:"VM"},{name:"VM_DELETE",description:"Stop and delete a Freestyle VM",category:"VM"},{name:"GITHUB_LIST_USER_ORGS",description:"List GitHub user's personal account and organizations",category:"GitHub"}]});var Oe6=D(()=>{ni();dz1()});function De6(){return Kp5.parse(process.env)}var GB0=(X)=>F.enum(["true","false","1","0"]).optional().transform((Y)=>Y===void 0?X:Y==="true"||Y==="1"),$p5=(X)=>F.string().optional().transform((Y)=>Y?Y.split(",").map((G)=>G.trim()):X),Kp5;var we6=D(()=>{H0();Kp5=F.object({AUTH_EMAIL_PASSWORD_ENABLED:GB0(!0),AUTH_GOOGLE_CLIENT_ID:F.string().optional(),AUTH_GOOGLE_CLIENT_SECRET:F.string().optional(),AUTH_GITHUB_CLIENT_ID:F.string().optional(),AUTH_GITHUB_CLIENT_SECRET:F.string().optional(),AUTH_RESEND_API_KEY:F.string().optional(),AUTH_RESEND_FROM_EMAIL:F.string().optional(),AUTH_SENDGRID_API_KEY:F.string().optional(),AUTH_SENDGRID_FROM_EMAIL:F.string().optional(),AUTH_INVITE_EMAIL_PROVIDER:F.enum(["resend","sendgrid"]).optional(),AUTH_RESET_PASSWORD_EMAIL_PROVIDER:F.enum(["resend","sendgrid"]).optional(),AUTH_MAGIC_LINK_ENABLED:GB0(!1),AUTH_MAGIC_LINK_EMAIL_PROVIDER:F.enum(["resend","sendgrid"]).optional(),AUTH_EMAIL_OTP_ENABLED:GB0(!1),AUTH_EMAIL_OTP_EMAIL_PROVIDER:F.enum(["resend","sendgrid"]).optional(),AUTH_EMAIL_OTP_LENGTH:F.coerce.number().optional(),AUTH_EMAIL_OTP_EXPIRES_IN:F.coerce.number().optional(),AUTH_SSO_DOMAIN:F.string().optional(),AUTH_SSO_MS_TENANT_ID:F.string().optional(),AUTH_SSO_MS_CLIENT_ID:F.string().optional(),AUTH_SSO_MS_CLIENT_SECRET:F.string().optional(),AUTH_SSO_SCOPES:$p5(["openid","email","profile"])}).transform((X)=>{let Y={};if(X.AUTH_GOOGLE_CLIENT_ID)Y.google={clientId:X.AUTH_GOOGLE_CLIENT_ID,clientSecret:X.AUTH_GOOGLE_CLIENT_SECRET??""};if(X.AUTH_GITHUB_CLIENT_ID)Y.github={clientId:X.AUTH_GITHUB_CLIENT_ID,clientSecret:X.AUTH_GITHUB_CLIENT_SECRET??""};let G=[];if(X.AUTH_RESEND_API_KEY)G.push({id:"resend",provider:"resend",config:{apiKey:X.AUTH_RESEND_API_KEY,fromEmail:X.AUTH_RESEND_FROM_EMAIL??"noreply@example.com"}});if(X.AUTH_SENDGRID_API_KEY)G.push({id:"sendgrid",provider:"sendgrid",config:{apiKey:X.AUTH_SENDGRID_API_KEY,fromEmail:X.AUTH_SENDGRID_FROM_EMAIL??"noreply@example.com"}});let Q=G[0]?.id,J;if(X.AUTH_SSO_MS_CLIENT_ID&&X.AUTH_SSO_DOMAIN)J={providerId:"microsoft",domain:X.AUTH_SSO_DOMAIN,MS_TENANT_ID:X.AUTH_SSO_MS_TENANT_ID??"",MS_CLIENT_ID:X.AUTH_SSO_MS_CLIENT_ID,MS_CLIENT_SECRET:X.AUTH_SSO_MS_CLIENT_SECRET??"",scopes:X.AUTH_SSO_SCOPES};let W;if(X.AUTH_MAGIC_LINK_ENABLED)W={enabled:!0,emailProviderId:X.AUTH_MAGIC_LINK_EMAIL_PROVIDER??Q??""};let Z;if(X.AUTH_EMAIL_OTP_ENABLED)Z={enabled:!0,emailProviderId:X.AUTH_EMAIL_OTP_EMAIL_PROVIDER??Q??"",...X.AUTH_EMAIL_OTP_LENGTH!==void 0&&{otpLength:X.AUTH_EMAIL_OTP_LENGTH},...X.AUTH_EMAIL_OTP_EXPIRES_IN!==void 0&&{expiresIn:X.AUTH_EMAIL_OTP_EXPIRES_IN}};return{emailAndPassword:{enabled:X.AUTH_EMAIL_PASSWORD_ENABLED},socialProviders:Object.keys(Y).length>0?Y:void 0,emailProviders:G.length>0?G:void 0,inviteEmailProviderId:X.AUTH_INVITE_EMAIL_PROVIDER,resetPasswordEmailProviderId:X.AUTH_RESET_PASSWORD_EMAIL_PROVIDER,ssoConfig:J,magicLinkConfig:W,emailOtpConfig:Z}})});var fA1;var Le6=D(()=>{fA1={enabled:!0,batchSize:250,flushIntervalMs:300,maxQueueSize:1e4,redactor:"regex"}});import{existsSync as Hp5,readFileSync as Fp5}from"fs";function Up5(){let X=De6(),Y=v6().configPath;if(!Hp5(Y))return{auth:X,monitoring:fA1};try{let G=JSON.parse(Fp5(Y,"utf-8"));if(G.auth)console.warn("[config] DEPRECATION: 'auth' key found in config.json. Auth is now configured via AUTH_* environment variables. The 'auth' key will be ignored.");return{auth:X,monitoring:G.monitoring??fA1,theme:G.theme,logo:G.logo,autoCreateOrganizationOnSignup:G.autoCreateOrganizationOnSignup}}catch{return{auth:X,monitoring:fA1}}}function Aj(){if(!QB0)QB0=Up5();return QB0}function Ee6(){return Aj().theme}var QB0=null;var JB0=D(()=>{we6();Le6();m9()});import{dirname as Np5,posix as Bp5,sep as zp5}from"path";function qe6(){let X=Op5();return async(Y)=>{for(let G of Y)G.module=X(G.filename);return Y}}function Op5(X=process.argv[1]?Np5(process.argv[1]):process.cwd(),Y=zp5==="\\"){let G=Y?Pe6(X):X;return(Q)=>{if(!Q)return;let J=Y?Pe6(Q):Q,{dir:W,base:Z,ext:$}=Bp5.parse(J);if($===".js"||$===".mjs"||$===".cjs")Z=Z.slice(0,-1*$.length);let K=decodeURIComponent(Z);if(!W)W=".";let H=W.lastIndexOf("/node_modules");if(H>-1)return`${W.slice(H+14).replace(/\//g,".")}:${K}`;if(W.startsWith(G)){let U=W.slice(G.length+1).replace(/\//g,".");return U?`${U}:${K}`:K}return K}}function Pe6(X){return X.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var Ae6=()=>{};function Dp5(X,Y,G){return{key:X,enabled:typeof Y=="string"?!0:Y,variant:typeof Y=="string"?Y:void 0,reason:void 0,metadata:{id:void 0,version:void 0,payload:G?JSON.stringify(G):void 0,description:void 0}}}var ZB0=(X)=>{if("flags"in X){let Y=Te6(X.flags),G=Ie6(X.flags);return{...X,featureFlags:Y,featureFlagPayloads:G}}{let Y=X.featureFlags??{},G=Object.fromEntries(Object.entries(X.featureFlagPayloads||{}).map(([J,W])=>[J,WB0(W)])),Q=Object.fromEntries(Object.entries(Y).map(([J,W])=>[J,Dp5(J,W,G[J])]));return{...X,featureFlags:Y,featureFlagPayloads:G,flags:Q}}},Te6=(X)=>Object.fromEntries(Object.entries(X??{}).map(([Y,G])=>[Y,CX1(G)]).filter(([,Y])=>Y!==void 0)),Ie6=(X)=>{let Y=X??{};return Object.fromEntries(Object.keys(Y).filter((G)=>{let Q=Y[G];return Q.enabled&&Q.metadata&&Q.metadata.payload!==void 0}).map((G)=>{let Q=Y[G].metadata?.payload;return[G,Q?WB0(Q):void 0]}))},CX1=(X)=>X===void 0?void 0:X.variant??X.enabled,WB0=(X)=>{if(typeof X!="string")return X;try{return JSON.parse(X)}catch{return X}};var bA1=()=>{};function Ve6(){return"CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&typeof Response.prototype.blob=="function"}async function yA1(X,Y=!0,G){try{let Q=new CompressionStream("gzip"),J=Q.writable.getWriter(),W=J.write(new TextEncoder().encode(X)).then(()=>J.close()).catch(async(K)=>{try{await J.abort(K)}catch{}throw K}),Z=new Response(Q.readable).blob(),[$]=await Promise.all([Z,W]);return $}catch(Q){if(G?.rethrow)throw Q;if(Y)console.error("Failed to gzip compress data",Q);return null}}var $B0=()=>{};var wp5,je6=function(X,Y=[]){if(!X)return!1;let G=X.toLowerCase();return wp5.concat(Y).some((Q)=>{let J=Q.toLowerCase();return G.indexOf(J)!==-1})};var Me6=D(()=>{wp5=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterest","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"]});var pJ;var Tj=D(()=>{pJ=function(X){return X.AnonymousId="anonymous_id",X.DistinctId="distinct_id",X.Props="props",X.EnablePersonProcessing="enable_person_processing",X.PersonMode="person_mode",X.FeatureFlagDetails="feature_flag_details",X.FeatureFlags="feature_flags",X.FeatureFlagPayloads="feature_flag_payloads",X.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",X.BootstrapFeatureFlags="bootstrap_feature_flags",X.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",X.OverrideFeatureFlags="override_feature_flags",X.Queue="queue",X.LogsQueue="logs_queue",X.OptedOut="opted_out",X.SessionId="session_id",X.SessionStartTimestamp="session_start_timestamp",X.SessionLastTimestamp="session_timestamp",X.PersonProperties="person_properties",X.GroupProperties="group_properties",X.InstalledAppBuild="installed_app_build",X.InstalledAppVersion="installed_app_version",X.SessionReplay="session_replay",X.SurveyLastSeenDate="survey_last_seen_date",X.SurveysSeen="surveys_seen",X.Surveys="surveys",X.RemoteConfig="remote_config",X.FlagsEndpointWasHit="flags_endpoint_was_hit",X.DeviceId="device_id",X}({})});var xA1=()=>{};function gA1(X){return X===null||typeof X!="object"}function Ij(X,Y){return Object.prototype.toString.call(X)===`[object ${Y}]`}function Ce6(X){return Ij(X,"ErrorEvent")}function ca(X){return typeof Event<"u"&&Pp5(X,Event)}function ke6(X){return Ij(X,"Object")}function Pp5(X,Y){try{return X instanceof Y}catch{return!1}}var Ep5,Re6,qlX,KB0,hA1,kX1=(X)=>X===Object(X)&&!hA1(X),da=(X)=>X===void 0,qq=(X)=>KB0.call(X)=="[object String]",Se6=(X)=>qq(X)&&X.trim().length===0,vX1=(X)=>KB0.call(X)=="[object Number]"&&X===X,HB0=(X)=>X instanceof Error;var _X1=D(()=>{Tj();xA1();Ep5=Array.isArray,Re6=Object.prototype,qlX=Re6.hasOwnProperty,KB0=Re6.toString,hA1=Ep5||function(X){return KB0.call(X)==="[object Array]"}});function fX1(X,Y,G,Q,J){if(Y>G)Q.warn("min cannot be greater than max."),Y=G;if(vX1(X))if(X>G)return Q.warn(" cannot be greater than max: "+G+". Using max value instead."),G;else{if(!(X<Y))return X;return Q.warn(" cannot be less than min: "+Y+". Using min value instead."),Y}return Q.warn(" must be a number. using max or fallback. max: "+G+", fallback: "+J),fX1(J||G,Y,G,Q)}var FB0=D(()=>{_X1()});class UB0{constructor(X){this._buckets={},this._onBucketRateLimited=X._onBucketRateLimited,this._bucketSize=fX1(X.bucketSize,0,100,X._logger),this._refillRate=fX1(X.refillRate,0,this._bucketSize,X._logger),this._refillInterval=fX1(X.refillInterval,0,qp5,X._logger)}_applyRefill(X,Y){let G=Y-X.lastAccess,Q=Math.floor(G/this._refillInterval);if(Q>0){let J=Q*this._refillRate;X.tokens=Math.min(X.tokens+J,this._bucketSize),X.lastAccess=X.lastAccess+Q*this._refillInterval}}consumeRateLimit(X){let Y=Date.now(),G=String(X),Q=this._buckets[G];if(Q)this._applyRefill(Q,Y);else Q={tokens:this._bucketSize,lastAccess:Y},this._buckets[G]=Q;if(Q.tokens===0)return!0;if(Q.tokens--,Q.tokens===0)this._onBucketRateLimited?.(X);return Q.tokens===0}stop(){this._buckets={}}}var qp5=86400000;var ve6=D(()=>{FB0()});class Vj{constructor(X){this.bytes=X}static ofInner(X){if(X.length===16)return new Vj(X);throw TypeError("not 128-bit length")}static fromFieldsV7(X,Y,G,Q){if(!Number.isInteger(X)||!Number.isInteger(Y)||!Number.isInteger(G)||!Number.isInteger(Q)||X<0||Y<0||G<0||Q<0||X>281474976710655||Y>4095||G>1073741823||Q>4294967295)throw RangeError("invalid field value");let J=new Uint8Array(16);return J[0]=X/1099511627776,J[1]=X/4294967296,J[2]=X/16777216,J[3]=X/65536,J[4]=X/256,J[5]=X,J[6]=112|Y>>>8,J[7]=Y,J[8]=128|G>>>24,J[9]=G>>>16,J[10]=G>>>8,J[11]=G,J[12]=Q>>>24,J[13]=Q>>>16,J[14]=Q>>>8,J[15]=Q,new Vj(J)}static parse(X){let Y;switch(X.length){case 32:Y=/^[0-9a-f]{32}$/i.exec(X)?.[0];break;case 36:Y=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(X)?.slice(1,6).join("");break;case 38:Y=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(X)?.slice(1,6).join("");break;case 45:Y=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(X)?.slice(1,6).join("");break;default:break}if(Y){let G=new Uint8Array(16);for(let Q=0;Q<16;Q+=4){let J=parseInt(Y.substring(2*Q,2*Q+8),16);G[Q+0]=J>>>24,G[Q+1]=J>>>16,G[Q+2]=J>>>8,G[Q+3]=J}return new Vj(G)}throw SyntaxError("could not parse UUID string")}toString(){let X="";for(let Y=0;Y<this.bytes.length;Y++)if(X+="0123456789abcdef".charAt(this.bytes[Y]>>>4),X+="0123456789abcdef".charAt(15&this.bytes[Y]),Y===3||Y===5||Y===7||Y===9)X+="-";return X}toHex(){let X="";for(let Y=0;Y<this.bytes.length;Y++)X+="0123456789abcdef".charAt(this.bytes[Y]>>>4),X+="0123456789abcdef".charAt(15&this.bytes[Y]);return X}toJSON(){return this.toString()}getVariant(){let X=this.bytes[8]>>>4;if(X<0)throw Error("unreachable");if(X<=7)return this.bytes.every((Y)=>Y===0)?"NIL":"VAR_0";if(X<=11)return"VAR_10";if(X<=13)return"VAR_110";if(X<=15)return this.bytes.every((Y)=>Y===255)?"MAX":"VAR_RESERVED";else throw Error("unreachable")}getVersion(){return this.getVariant()==="VAR_10"?this.bytes[6]>>>4:void 0}clone(){return new Vj(this.bytes.slice(0))}equals(X){return this.compareTo(X)===0}compareTo(X){for(let Y=0;Y<16;Y++){let G=this.bytes[Y]-X.bytes[Y];if(G!==0)return Math.sign(G)}return 0}}class fe6{constructor(X){this.timestamp=0,this.counter=0,this.random=X??Ap5()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(X,Y){let G=this.generateOrAbortCore(X,Y);if(G===void 0)this.timestamp=0,G=this.generateOrAbortCore(X,Y);return G}generateOrAbortCore(X,Y){if(!Number.isInteger(X)||X<1||X>281474976710655)throw RangeError("`unixTsMs` must be a 48-bit positive integer");if(Y<0||Y>281474976710655)throw RangeError("`rollbackAllowance` out of reasonable range");if(X>this.timestamp)this.timestamp=X,this.resetCounter();else{if(!(X+Y>=this.timestamp))return;if(this.counter++,this.counter>4398046511103)this.timestamp++,this.resetCounter()}return Vj.fromFieldsV7(this.timestamp,Math.trunc(this.counter/1073741824),this.counter&1073741823,this.random.nextUint32())}resetCounter(){this.counter=1024*this.random.nextUint32()+(1023&this.random.nextUint32())}generateV4(){let X=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return X[6]=64|X[6]>>>4,X[8]=128|X[8]>>>2,Vj.ofInner(X)}}var Ap5=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())}),_e6,Aq=()=>Tp5().toString(),Tp5=()=>(_e6||(_e6=new fe6)).generate();var bX1=D(()=>{/*! For license information please see uuidv7.mjs.LICENSE.txt */});class NB0{add(X){let Y=Aq();return this.promiseByIds[Y]=X,X.catch(()=>{}).finally(()=>{delete this.promiseByIds[Y]}),X}async join(){let X=Object.values(this.promiseByIds),Y=X.length;while(Y>0)await Promise.all(X),X=Object.values(this.promiseByIds),Y=X.length}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={}}}var be6=D(()=>{bX1()});function Ip5(X=console){return{log:X.log.bind(X),warn:X.warn.bind(X),error:X.error.bind(X),debug:X.debug.bind(X)}}function xe6(X,Y=Vp5){return ye6(X,Y,Ip5())}var ye6=(X,Y,G)=>{function Q(W,...Z){Y(()=>{let $=G[W];$(X,...Z)})}return{info:(...W)=>{Q("log",...W)},warn:(...W)=>{Q("warn",...W)},error:(...W)=>{Q("error",...W)},critical:(...W)=>{G.error(X,...W)},createLogger:(W)=>ye6(`${X} ${W}`,Y,G)}},Vp5=(X)=>X();var he6=()=>{};var pa="Mobile",lA1="iOS",ia="Android",ge6="Tablet",_lX,Mp5="Apple",flX,ue6="Safari",mA1="BlackBerry",le6="Samsung",Rp5,Sp5,dA1="Chrome",Cp5,kp5,me6="Internet Explorer",vp5,zB0="Opera",blX,de6="Edge",_p5,OB0="Firefox",fp5,DB0="Nintendo",wB0="PlayStation",uA1="Xbox",bp5,yp5,yX1="Windows",xp5,ce6="Generic",ylX,xlX,hp5="Konqueror",K3="(\\d+(\\.\\d+)?)",BB0,hlX,glX,ulX,gp5,up5,llX,mlX;var ie6=D(()=>{xA1();_X1();_lX=ia+" "+ge6,flX=Mp5+" Watch",Rp5=le6+"Browser",Sp5=le6+" Internet",Cp5=dA1+" OS",kp5=dA1+" "+lA1,vp5=me6+" "+pa,blX=zB0+" Mini",_p5="Microsoft "+de6,fp5=OB0+" "+lA1,bp5=ia+" "+pa,yp5=pa+" "+ue6,xp5=yX1+" Phone",ylX=ce6+" "+pa.toLowerCase(),xlX=ce6+" "+ge6.toLowerCase(),BB0=new RegExp("Version/"+K3),hlX=new RegExp(uA1,"i"),glX=new RegExp(wB0+" \\w+","i"),ulX=new RegExp(DB0+" \\w+","i"),gp5=new RegExp(mA1+"|PlayBook|BB10","i"),up5={"NT3.51":"NT 3.11","NT4.0":"NT 4.0","5.0":"2000","5.1":"XP","5.2":"XP","6.0":"Vista","6.1":"7","6.2":"8","6.3":"8.1","6.4":"10","10.0":"10"},llX={[vp5]:[new RegExp("rv:"+K3)],[_p5]:[new RegExp(de6+"?\\/"+K3)],[dA1]:[new RegExp("("+dA1+"|CrMo)\\/"+K3)],[kp5]:[new RegExp("CriOS\\/"+K3)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+K3)],[ue6]:[BB0],[yp5]:[BB0],[zB0]:[new RegExp("("+zB0+"|OPR)\\/"+K3)],[OB0]:[new RegExp(OB0+"\\/"+K3)],[fp5]:[new RegExp("FxiOS\\/"+K3)],[hp5]:[new RegExp("Konqueror[:/]?"+K3,"i")],[mA1]:[new RegExp(mA1+" "+K3),BB0],[bp5]:[new RegExp("android\\s"+K3,"i")],[Sp5]:[new RegExp(Rp5+"\\/"+K3)],[me6]:[new RegExp("(rv:|MSIE )"+K3)],Mozilla:[new RegExp("rv:"+K3)]},mlX=[[new RegExp(uA1+"; "+uA1+" (.*?)[);]","i"),(X)=>[uA1,X&&X[1]||""]],[new RegExp(DB0,"i"),[DB0,""]],[new RegExp(wB0,"i"),[wB0,""]],[gp5,[mA1,""]],[new RegExp(yX1,"i"),(X,Y)=>{if(/Phone/.test(Y)||/WPDesktop/.test(Y))return[xp5,""];if(new RegExp(pa).test(Y)&&!/IEMobile\b/.test(Y))return[yX1+" "+pa,""];let G=/Windows NT ([0-9.]+)/i.exec(Y);if(G&&G[1]){let Q=G[1],J=up5[Q]||"";if(/arm/i.test(Y))J="RT";return[yX1,J]}return[yX1,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,(X)=>{if(X&&X[3]){let Y=[X[3],X[4],X[5]||"0"];return[lA1,Y.join(".")]}return[lA1,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,(X)=>{let Y="";if(X&&X.length>=3)Y=da(X[2])?X[3]:X[2];return["watchOS",Y]}],[new RegExp("("+ia+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+ia+")","i"),(X)=>{if(X&&X[2]){let Y=[X[2],X[3],X[4]||"0"];return[ia,Y.join(".")]}return[ia,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,(X)=>{let Y=["Mac OS X",""];if(X&&X[1]){let G=[X[1],X[2],X[3]||"0"];Y[1]=G.join(".")}return Y}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[Cp5,""]],[/Linux|debian/i,["Linux",""]]]});function ne6(X){return X?.replace(/\/+$/,"")}async function ae6(X,Y){let G=null;for(let Q=0;Q<Y.retryCount+1;Q++){if(Q>0)await new Promise((J)=>setTimeout(J,Y.retryDelay));try{return await X()}catch(J){if(G=J,!Y.retryCheck(J))throw J}}throw G}function cA1(){return new Date().toISOString()}function Kw(X,Y){let G=setTimeout(X,Y);return G?.unref&&G?.unref(),G}function LB0(X){return Promise.all(X.map((Y)=>(Y??Promise.resolve()).then((G)=>({status:"fulfilled",value:G}),(G)=>({status:"rejected",reason:G}))))}var pe6="utf8",te6=(X)=>X instanceof Error;var H3=D(()=>{Me6();ve6();FB0();xA1();_X1();be6();he6();ie6()});var lp5,GmX;var EB0=D(()=>{H3();lp5={trace:{text:"TRACE",number:1},debug:{text:"DEBUG",number:5},info:{text:"INFO",number:9},warn:{text:"WARN",number:13},error:{text:"ERROR",number:17},fatal:{text:"FATAL",number:21}},GmX=lp5.info});var re6=D(()=>{EB0();Tj()});var oe6=D(()=>{Tj()});class PB0{constructor(){this.events={},this.events={}}on(X,Y){if(!this.events[X])this.events[X]=[];return this.events[X].push(Y),()=>{this.events[X]=this.events[X].filter((G)=>G!==Y)}}emit(X,Y){for(let G of this.events[X]||[])G(Y);for(let G of this.events["*"]||[])G(X,Y)}}var se6=()=>{};async function ee6(X){if(X instanceof na){let Y="";try{Y=await X.text}catch{}console.error(`Error while flushing PostHog: message=${X.message}, response body=${Y}`,X)}else console.error("Error while flushing PostHog",X);return Promise.resolve()}function qB0(X){return typeof X=="object"&&(X instanceof na||X instanceof xX1)}function X14(X){return typeof X=="object"&&X instanceof na&&X.status===413}class iA1{constructor(X,Y={}){this.flushPromise=null,this.shutdownPromise=null,this.promiseQueue=new NB0,this._events=new PB0,this._isInitialized=!1;let G=typeof X=="string"?X.trim():"",Q=typeof Y.host=="string"?Y.host.trim():"",J=!G;if(this._logger=xe6("[PostHog]",this.logMsgIfDebug.bind(this)),J)this._logger.error("You must pass your PostHog project's api key. The client will be disabled.");if(this.apiKey=G,this.host=ne6(Q||"https://us.i.posthog.com"),this.flushAt=Y.flushAt?Math.max(Y.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,Y.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,Y.maxQueueSize??1000),this.flushInterval=Y.flushInterval??1e4,this.preloadFeatureFlags=Y.preloadFeatureFlags??!0,this.defaultOptIn=Y.defaultOptIn??!0,this.disableSurveys=Y.disableSurveys??!1,this._retryOptions={retryCount:Y.fetchRetryCount??3,retryDelay:Y.fetchRetryDelay??3000,retryCheck:qB0},this.requestTimeout=Y.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=Y.featureFlagsRequestTimeoutMs??3000,this.remoteConfigRequestTimeoutMs=Y.remoteConfigRequestTimeoutMs??3000,this.disableGeoip=Y.disableGeoip??!0,this.disabled=(Y.disabled??!1)||J,this.historicalMigration=Y?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,this.evaluationContexts=Y?.evaluationContexts??Y?.evaluationEnvironments,Y?.evaluationEnvironments&&!Y?.evaluationContexts)this._logger.warn("evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version.");this.disableCompression=!Ve6()||(Y?.disableCompression??!1)}logMsgIfDebug(X){if(this.isDebug)X()}wrap(X){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized)return X();this._initPromise.then(()=>X())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(pJ.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(pJ.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(pJ.OptedOut,!0)})}on(X,Y){return this._events.on(X,Y)}debug(X=!0){if(this.removeDebugCallback?.(),X){let Y=this.on("*",(G,Q)=>this._logger.info(G,Q));this.removeDebugCallback=()=>{Y(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(X){return{distinct_id:X.distinct_id,event:X.event,properties:{...X.properties||{},...this.getCommonEventProperties()}}}addPendingPromise(X){return this.promiseQueue.add(X)}identifyStateless(X,Y,G){this.wrap(()=>{let Q={...this.buildPayload({distinct_id:X,event:"$identify",properties:Y})};this.enqueue("identify",Q,G)})}async identifyStatelessImmediate(X,Y,G){let Q={...this.buildPayload({distinct_id:X,event:"$identify",properties:Y})};await this.sendImmediate("identify",Q,G)}captureStateless(X,Y,G,Q){this.wrap(()=>{let J=this.buildPayload({distinct_id:X,event:Y,properties:G});this.enqueue("capture",J,Q)})}async captureStatelessImmediate(X,Y,G,Q){let J=this.buildPayload({distinct_id:X,event:Y,properties:G});await this.sendImmediate("capture",J,Q)}aliasStateless(X,Y,G,Q){this.wrap(()=>{let J=this.buildPayload({event:"$create_alias",distinct_id:Y,properties:{...G||{},distinct_id:Y,alias:X}});this.enqueue("alias",J,Q)})}async aliasStatelessImmediate(X,Y,G,Q){let J=this.buildPayload({event:"$create_alias",distinct_id:Y,properties:{...G||{},distinct_id:Y,alias:X}});await this.sendImmediate("alias",J,Q)}groupIdentifyStateless(X,Y,G,Q,J,W){this.wrap(()=>{let Z=this.buildPayload({distinct_id:J||`$${X}_${Y}`,event:"$groupidentify",properties:{$group_type:X,$group_key:Y,$group_set:G||{},...W||{}}});this.enqueue("capture",Z,Q)})}async getRemoteConfig(){await this._initPromise;let X=this.host;if(X==="https://us.i.posthog.com")X="https://us-assets.i.posthog.com";else if(X==="https://eu.i.posthog.com")X="https://eu-assets.i.posthog.com";let Y=`${X}/array/${this.apiKey}/config`,G={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(Y,G,{retryCount:0},this.remoteConfigRequestTimeoutMs).then((Q)=>Q.json()).catch((Q)=>{this._logger.error("Remote config could not be loaded",Q),this._events.emit("error",Q)})}async getFlags(X,Y={},G={},Q={},J={},W=!1){await this._initPromise;let Z=W?"&config=true":"",$=`${this.host}/flags/?v=2${Z}`,K={token:this.apiKey,distinct_id:X,groups:Y,person_properties:G,group_properties:Q,...J};if(G.$device_id)K.$device_id=G.$device_id;if(this.evaluationContexts&&this.evaluationContexts.length>0)K.evaluation_contexts=this.evaluationContexts;let H={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(K)};return this._logger.info("Flags URL",$),this.fetchWithRetry($,H,{retryCount:0},this.featureFlagsRequestTimeoutMs).then((U)=>U.json()).then((U)=>({success:!0,response:ZB0(U)})).catch((U)=>{return this._events.emit("error",U),{success:!1,error:this.categorizeRequestError(U)}})}categorizeRequestError(X){if(X instanceof na)return{type:"api_error",statusCode:X.status};if(X instanceof xX1){let Y=X.error;if(Y instanceof Error&&(Y.name==="AbortError"||Y.name==="TimeoutError"))return{type:"timeout"};return{type:"connection_error"}}return{type:"unknown_error"}}async getFeatureFlagStateless(X,Y,G={},Q={},J={},W){await this._initPromise;let Z=await this.getFeatureFlagDetailStateless(X,Y,G,Q,J,W);if(Z===void 0)return{response:void 0,requestId:void 0};let $=CX1(Z.response);if($===void 0)$=!1;return{response:$,requestId:Z.requestId}}async getFeatureFlagDetailStateless(X,Y,G={},Q={},J={},W){await this._initPromise;let Z=await this.getFeatureFlagDetailsStateless(Y,G,Q,J,W,[X]);if(Z===void 0)return;return{response:Z.flags[X],requestId:Z.requestId,evaluatedAt:Z.evaluatedAt}}async getFeatureFlagPayloadStateless(X,Y,G={},Q={},J={},W){await this._initPromise;let Z=await this.getFeatureFlagPayloadsStateless(Y,G,Q,J,W,[X]);if(!Z)return;let $=Z[X];if($===void 0)return null;return $}async getFeatureFlagPayloadsStateless(X,Y={},G={},Q={},J,W){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(X,Y,G,Q,J,W)).payloads}async getFeatureFlagsStateless(X,Y={},G={},Q={},J,W){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(X,Y,G,Q,J,W)}async getFeatureFlagsAndPayloadsStateless(X,Y={},G={},Q={},J,W){await this._initPromise;let Z=await this.getFeatureFlagDetailsStateless(X,Y,G,Q,J,W);if(!Z)return{flags:void 0,payloads:void 0,requestId:void 0};return{flags:Z.featureFlags,payloads:Z.featureFlagPayloads,requestId:Z.requestId}}async getFeatureFlagDetailsStateless(X,Y={},G={},Q={},J,W){await this._initPromise;let Z={};if(J??this.disableGeoip)Z.geoip_disable=!0;if(W)Z.flag_keys_to_evaluate=W;let $=await this.getFlags(X,Y,G,Q,Z);if(!$.success)return;let K=$.response;if(K.errorsWhileComputingFlags)console.error("[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices");if(K.quotaLimited?.includes("feature_flags"))return console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),{flags:{},featureFlags:{},featureFlagPayloads:{},requestId:K?.requestId,quotaLimited:K.quotaLimited};return K}async getSurveysStateless(){if(await this._initPromise,this.disableSurveys===!0)return this._logger.info("Loading surveys is disabled."),[];let X=`${this.host}/api/surveys/?token=${this.apiKey}`,Y={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},Q=(await this.fetchWithRetry(X,Y).then((J)=>{if(J.status!==200||!J.json){let W=`Surveys API could not be loaded: ${J.status}`,Z=Error(W);this._logger.error(Z),this._events.emit("error",Error(W));return}return J.json()}).catch((J)=>{this._logger.error("Surveys API could not be loaded",J),this._events.emit("error",J)}))?.surveys;if(Q)this._logger.info("Surveys fetched from API: ",JSON.stringify(Q));return Q??[]}get props(){if(!this._props)this._props=this.getPersistedProperty(pJ.Props);return this._props||{}}set props(X){this._props=X}async register(X){this.wrap(()=>{this.props={...this.props,...X},this.setPersistedProperty(pJ.Props,this.props)})}async unregister(X){this.wrap(()=>{delete this.props[X],this.setPersistedProperty(pJ.Props,this.props)})}processBeforeEnqueue(X){return X}async flushStorage(){}enqueue(X,Y,G){this.wrap(()=>{if(this.optedOut)return void this._events.emit(X,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let Q=this.prepareMessage(X,Y,G);if(Q=this.processBeforeEnqueue(Q),Q===null)return;let J=this.getPersistedProperty(pJ.Queue)||[];if(J.length>=this.maxQueueSize)J.shift(),this._logger.info("Queue is full, the oldest event is dropped.");if(J.push({message:Q}),this.setPersistedProperty(pJ.Queue,J),this._events.emit(X,Q),J.length>=this.flushAt)this.flushBackground();if(this.flushInterval&&!this._flushTimer)this._flushTimer=Kw(()=>this.flushBackground(),this.flushInterval)})}async sendImmediate(X,Y,G){if(this.disabled)return void this._logger.warn("The client is disabled");if(!this._isInitialized)await this._initPromise;if(this.optedOut)return void this._events.emit(X,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let Q=this.prepareMessage(X,Y,G);if(Q=this.processBeforeEnqueue(Q),Q===null)return;let J={api_key:this.apiKey,batch:[Q],sent_at:cA1()};if(this.historicalMigration)J.historical_migration=!0;let W=JSON.stringify(J),Z=`${this.host}/batch/`,$=this.disableCompression?null:await yA1(W,this.isDebug),K={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...$!==null&&{"Content-Encoding":"gzip"}},body:$||W};try{await this.fetchWithRetry(Z,K)}catch(H){this._events.emit("error",H)}}prepareMessage(X,Y,G){let Q={...Y,type:X,library:this.getLibraryId(),library_version:this.getLibraryVersion(),timestamp:G?.timestamp?G?.timestamp:cA1(),uuid:G?.uuid?G.uuid:Aq()};if(G?.disableGeoip??this.disableGeoip){if(!Q.properties)Q.properties={};Q.properties.$geoip_disable=!0}if(Q.distinctId)Q.distinct_id=Q.distinctId,delete Q.distinctId;return Q}clearFlushTimer(){if(this._flushTimer)clearTimeout(this._flushTimer),this._flushTimer=void 0}flushBackground(){this.flush().catch(async(X)=>{await ee6(X)})}async flush(){let X=LB0([this.flushPromise]).then(()=>this._flush());return this.flushPromise=X,this.addPendingPromise(X),LB0([X]).then(()=>{if(this.flushPromise===X)this.flushPromise=null}),X}getCustomHeaders(){let X=this.getCustomUserAgent(),Y={};if(X&&X!=="")Y["User-Agent"]=X;return Y}async _flush(){this.clearFlushTimer(),await this._initPromise;let X=this.getPersistedProperty(pJ.Queue)||[];if(!X.length)return;let Y=[],G=X.length;while(X.length>0&&Y.length<G){let Q=X.slice(0,this.maxBatchSize),J=Q.map((B)=>B.message),W=async()=>{let z=(this.getPersistedProperty(pJ.Queue)||[]).slice(Q.length);this.setPersistedProperty(pJ.Queue,z),X=z,await this.flushStorage()},Z={api_key:this.apiKey,batch:J,sent_at:cA1()};if(this.historicalMigration)Z.historical_migration=!0;let $=JSON.stringify(Z),K=`${this.host}/batch/`,H=this.disableCompression?null:await yA1($,this.isDebug),U={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...H!==null&&{"Content-Encoding":"gzip"}},body:H||$},N={retryCheck:(B)=>{if(X14(B))return!1;return qB0(B)}};try{await this.fetchWithRetry(K,U,N)}catch(B){if(X14(B)&&J.length>1){this.maxBatchSize=Math.max(1,Math.floor(J.length/2)),this._logger.warn(`Received 413 when sending batch of size ${J.length}, reducing batch size to ${this.maxBatchSize}`);continue}if(!(B instanceof xX1))await W();throw this._events.emit("error",B),B}await W(),Y.push(...J)}this._events.emit("flush",Y)}async fetchWithRetry(X,Y,G,Q){let J=Y.body?Y.body:"",W=-1;try{W=J instanceof Blob?J.size:Buffer.byteLength(J,pe6)}catch{if(J instanceof Blob)W=J.size;else W=new TextEncoder().encode(J).length}return await ae6(async()=>{let Z=new AbortController,$=Q??this.requestTimeout,K=Kw(()=>Z.abort(),$),H=null;try{H=await this.fetch(X,{signal:Z.signal,...Y})}catch(N){throw new xX1(N)}finally{clearTimeout(K)}if(Y.mode!=="no-cors"&&(H.status<200||H.status>=400))throw new na(H,W);return H},{...this._retryOptions,...G})}async _shutdown(X=30000){await this._initPromise;let Y=!1;this.clearFlushTimer();let G=async()=>{try{await this.promiseQueue.join();while(!0){if((this.getPersistedProperty(pJ.Queue)||[]).length===0)break;if(await this.flush(),Y)break}}catch(J){if(!qB0(J))throw J;await ee6(J)}},Q;try{return await Promise.race([new Promise((J,W)=>{Q=Kw(()=>{this._logger.error("Timed out while shutting down PostHog"),Y=!0,W("Timeout while shutting down PostHog. Some events may not have been sent.")},X)}),G()])}finally{clearTimeout(Q)}}async shutdown(X=30000){if(this.shutdownPromise)this._logger.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup");else this.shutdownPromise=this._shutdown(X).finally(()=>{this.shutdownPromise=null});return this.shutdownPromise}}var na,xX1;var AB0=D(()=>{se6();bA1();$B0();Tj();H3();bX1();na=class na extends Error{constructor(X,Y){super("HTTP error while fetching PostHog: status="+X.status+", reqByteLength="+Y),this.response=X,this.reqByteLength=Y,this.name="PostHogFetchHttpError"}get status(){return this.response.status}get text(){return this.response.text()}get json(){return this.response.json()}};xX1=class xX1 extends Error{constructor(X){super("Network error while fetching PostHog",X instanceof Error?{cause:X}:{}),this.error=X,this.name="PostHogFetchNetworkError"}}});var Y14=D(()=>{bA1();Tj();AB0();bX1();H3()});var G14=D(()=>{_X1()});function J14(X){let Y=globalThis._posthogChunkIds;if(!Y)return;let G=Object.keys(Y);if(nA1&&G.length===Q14)return nA1;return Q14=G.length,nA1=G.reduce((Q,J)=>{if(!pA1)pA1={};let W=pA1[J];if(W)Q[W[0]]=W[1];else{let Z=X(J);for(let $=Z.length-1;$>=0;$--){let H=Z[$]?.filename,U=Y[J];if(H&&U){Q[H]=U,pA1[J]=[H,U];break}}}return Q},{}),nA1}var pA1,Q14,nA1;var Z14=()=>{};class W14{constructor(X,Y,G=[]){this.coercers=X,this.stackParser=Y,this.modifiers=G}buildFromUnknown(X,Y={}){let Q=Y&&Y.mechanism||{handled:!0,type:"generic"},W=this.buildCoercingContext(Q,Y,0).apply(X),Z=this.buildParsingContext(Y),$=this.parseStacktrace(W,Z);return{$exception_list:this.convertToExceptionList($,Q),$exception_level:"error"}}async modifyFrames(X){for(let Y of X)if(Y.stacktrace&&Y.stacktrace.frames&&hA1(Y.stacktrace.frames))Y.stacktrace.frames=await this.applyModifiers(Y.stacktrace.frames);return X}coerceFallback(X){return{type:"Error",value:"Unknown error",stack:X.syntheticException?.stack,synthetic:!0}}parseStacktrace(X,Y){let G;if(X.cause!=null)G=this.parseStacktrace(X.cause,Y);let Q;if(X.stack!=""&&X.stack!=null)Q=this.applyChunkIds(this.stackParser(X.stack,X.synthetic?Y.skipFirstLines:0),Y.chunkIdMap);return{...X,cause:G,stack:Q}}applyChunkIds(X,Y){return X.map((G)=>{if(G.filename&&Y)G.chunk_id=Y[G.filename];return G})}applyCoercers(X,Y){for(let G of this.coercers)if(G.match(X))return G.coerce(X,Y);return this.coerceFallback(Y)}async applyModifiers(X){let Y=X;for(let G of this.modifiers)Y=await G(Y);return Y}convertToExceptionList(X,Y){let G={type:X.type,value:X.value,mechanism:{type:Y.type??"generic",handled:Y.handled??!0,synthetic:X.synthetic??!1}};if(X.stack)G.stacktrace={type:"raw",frames:X.stack};let Q=[G];if(X.cause!=null)Q.push(...this.convertToExceptionList(X.cause,{...Y,handled:!0}));return Q}buildParsingContext(X){return{chunkIdMap:J14(this.stackParser),skipFirstLines:X.skipFirstLines??1}}buildCoercingContext(X,Y,G=0){let Q=(W,Z)=>{if(!(Z<=cp5))return;{let $=this.buildCoercingContext(X,Y,Z);return this.applyCoercers(W,$)}};return{...Y,syntheticException:G==0?Y.syntheticException:void 0,mechanism:X,apply:(W)=>Q(W,G),next:(W)=>Q(W,G+1)}}}var cp5=4;var $14=D(()=>{H3();Z14()});function Yz(X,Y,G,Q,J){let W={platform:X,filename:Y,function:G==="<anonymous>"?rQ:G,in_app:!0};if(!da(Q))W.lineno=Q;if(!da(J))W.colno=J;return W}var rQ="?";var Tq=D(()=>{H3()});var aA1=(X,Y)=>{let G=X.indexOf("safari-extension")!==-1,Q=X.indexOf("safari-web-extension")!==-1;return G||Q?[X.indexOf("@")!==-1?X.split("@")[0]:rQ,G?`safari-extension:${Y}`:`safari-web-extension:${Y}`]:[X,Y]};var TB0=D(()=>{Tq()});var ip5,pp5,np5,IB0=(X,Y)=>{let G=ip5.exec(X);if(G){let[,J,W,Z]=G;return Yz(Y,J,rQ,+W,+Z)}let Q=pp5.exec(X);if(Q){if(Q[2]&&Q[2].indexOf("eval")===0){let $=np5.exec(Q[2]);if($)Q[2]=$[1],Q[3]=$[2],Q[4]=$[3]}let[W,Z]=aA1(Q[1]||rQ,Q[2]);return Yz(Y,Z,W,Q[3]?+Q[3]:void 0,Q[4]?+Q[4]:void 0)}};var K14=D(()=>{Tq();TB0();ip5=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,pp5=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,np5=/\((\S*)(?::(\d+))(?::(\d+))\)/});var ap5,tp5,VB0=(X,Y)=>{let G=ap5.exec(X);if(G){if(G[3]&&G[3].indexOf(" > eval")>-1){let Z=tp5.exec(G[3]);if(Z)G[1]=G[1]||"eval",G[3]=Z[1],G[4]=Z[2],G[5]=""}let J=G[3],W=G[1]||rQ;return[W,J]=aA1(W,J),Yz(Y,J,W,G[4]?+G[4]:void 0,G[5]?+G[5]:void 0)}};var H14=D(()=>{Tq();TB0();ap5=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,tp5=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i});var rp5,F14=(X,Y)=>{let G=rp5.exec(X);return G?Yz(Y,G[2],G[1]||rQ,+G[3],G[4]?+G[4]:void 0):void 0};var U14=D(()=>{Tq();rp5=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i});var op5,N14=(X,Y)=>{let G=op5.exec(X);return G?Yz(Y,G[2],G[3]||rQ,+G[1]):void 0},sp5,B14=(X,Y)=>{let G=sp5.exec(X);return G?Yz(Y,G[5],G[3]||G[4]||rQ,+G[1],+G[2]):void 0};var z14=D(()=>{Tq();op5=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,sp5=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i});function Yn5(X,Y=!1){return!(Y||X&&!X.startsWith("/")&&!X.match(/^[A-Z]:/)&&!X.startsWith(".")&&!X.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&X!==void 0&&!X.includes("node_modules/")}function O14(X){return parseInt(X||"",10)||void 0}var ep5,Xn5,D14=(X,Y)=>{let G=X.match(Xn5);if(G){let Q,J,W,Z,$;if(G[1]){W=G[1];let U=W.lastIndexOf(".");if(W[U-1]===".")U--;if(U>0){Q=W.slice(0,U),J=W.slice(U+1);let N=Q.indexOf(".Module");if(N>0)W=W.slice(N+1),Q=Q.slice(0,N)}Z=void 0}if(J)Z=Q,$=J;if(J==="<anonymous>")$=void 0,W=void 0;if(W===void 0)$=$||rQ,W=Z?`${Z}.${$}`:$;let K=G[2]?.startsWith("file://")?G[2].slice(7):G[2],H=G[5]==="native";if(K?.match(/\/[A-Z]:/))K=K.slice(1);if(!K&&G[5]&&!H)K=G[5];return{filename:K?decodeURI(K):void 0,module:void 0,function:W,lineno:O14(G[3]),colno:O14(G[4]),in_app:Yn5(K||"",H),platform:Y}}if(X.match(ep5))return{filename:X,platform:Y}};var w14=D(()=>{Tq();ep5=/^\s*[-]{4,}$/,Xn5=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/});function P14(X){if(!X.length)return[];let Y=Array.from(X);return Y.reverse(),Y.slice(0,E14).map((G)=>({...G,filename:G.filename||Gn5(Y).filename,function:G.function||rQ}))}function Gn5(X){return X[X.length-1]||{}}function Qn5(){return q14("web:javascript",IB0,VB0)}function q14(X,...Y){return(G,Q=0)=>{let J=[],W=G.split(`
|
|
1639
|
+
`);Q=W.pop()??"";for(let Z of W){let $=Ks6(Z).replace(/^\[\d+\]\s*/,"").trim();if(!$)continue;LK({method:"",path:"",status:0,duration:0,timestamp:new Date,rawLine:$})}}(async()=>{for(;;){let{done:W,value:Z}=await Y.read();if(W)break;Q+=G.decode(Z,{stream:!0}),J()}if(Q.trim()){let W=Ks6(Q).replace(/^\[\d+\]\s*/,"").trim();if(W)LK({method:"",path:"",status:0,duration:0,timestamp:new Date,rawLine:W})}})()}async function Li5(X){let{vitePort:Y,baseUrl:G,noTui:Q}=X,J=await wA1(Number(X.port)),{settings:W,services:Z,managedServiceNames:$}=await DA1({port:String(J),home:X.home,baseUrl:X.baseUrl,localMode:X.localMode,skipMigrations:X.skipMigrations,noTui:X.noTui,vitePort:X.vitePort});for(let z of Z)Nd({name:z.name,status:"ready",port:z.port});Te(W),qe();let K=wi5(import.meta.dir,"..","..","..","..",".."),H=Q===!0,U=Bun.spawn(["bun","run","--cwd=apps/mesh","dev:servers"],{cwd:K,env:{...process.env,PORT:String(W.port),VITE_PORT:String(Y),DATABASE_URL:W.databaseUrl,NATS_URL:W.natsUrls.join(","),NODE_ENV:W.nodeEnv,DECOCMS_LOCAL_MODE:String(W.localMode),DECOCMS_HOME:W.dataDir,DATA_DIR:W.dataDir,DECO_CLI:"1",...W.baseUrl?{BASE_URL:W.baseUrl}:{}},stdio:["inherit",H?"inherit":"pipe",H?"inherit":"pipe"]});if(!H)Hs6(U.stdout),Hs6(U.stderr);let N=G||`http://localhost:${W.port}`;Ae(N),Nd({name:"Vite",status:"ready",port:Number(Y)});let B=async(z)=>{if(U.kill(z),$.length>0){let{stopServices:O}=await Promise.resolve().then(() => (H$1(),K$1));await O(W.dataDir)}};return process.on("SIGINT",()=>B("SIGINT")),process.on("SIGTERM",()=>B("SIGTERM")),{port:Number(W.port),process:U}}var MN0=D(()=>{IN0();YF();VN0()});import{Box as RN0,Text as SN0}from"ink";import{jsx as Us6,jsxs as LA1}from"react/jsx-runtime";function Fs6(X){if(!X)return"not set";try{let Y=new URL(X);if(Y.password)Y.password="***";if(Y.username&&Y.username.length>3)Y.username=Y.username.slice(0,3)+"***";return Y.pathname="/",Y.search="",Y.hash="",Y.toString()}catch{if(X.length<=10)return X;return X.slice(0,6)+"***"+X.slice(-4)}}function qi5(X,Y){if(Ei5.has(X))return Y?{text:"\u25CF\u25CF\u25CF\u25CF\u25CF\u25CF",dimColor:!0}:{text:"not set",dimColor:!0};if(Pi5.has(X)){if(Array.isArray(Y)){if(Y.length===0)return{text:"not set",dimColor:!0};return{text:Y.map((W)=>Fs6(W)).join(", "),color:"cyan"}}let Q=Fs6(Y);return Q==="not set"?{text:Q,dimColor:!0}:{text:Q,color:"cyan"}}if(Y===void 0||Y===null||Y==="")return{text:"not set",dimColor:!0};let G=String(Y);if(G==="true")return{text:G,color:"green"};if(G==="false")return{text:G,color:"yellow"};try{return new URL(G),{text:G,color:"cyan"}}catch{return{text:G}}}function Ai5(X){return[{title:"Core",entries:[{key:"NODE_ENV",value:X.nodeEnv},{key:"PORT",value:X.port},{key:"BASE_URL",value:X.baseUrl??`http://localhost:${X.port}`},{key:"DATA_DIR",value:X.dataDir}]},{title:"Database",entries:[{key:"DATABASE_URL",value:X.databaseUrl},{key:"DATABASE_PG_SSL",value:X.databasePgSsl}]},{title:"Auth & Secrets",entries:[{key:"BETTER_AUTH_SECRET",value:X.betterAuthSecret},{key:"ENCRYPTION_KEY",value:X.encryptionKey},{key:"MESH_JWT_SECRET",value:X.meshJwtSecret},{key:"STUDIO_PROVISION_SECRET_KEY",value:X.studioProvisionSecretKey},{key:"DISABLE_RATE_LIMIT",value:X.disableRateLimit}]},{title:"Auth Providers",entries:[{key:"AUTH_EMAIL_PASSWORD_ENABLED",value:process.env.AUTH_EMAIL_PASSWORD_ENABLED??"true"},{key:"AUTH_GOOGLE_CLIENT_ID",value:!!process.env.AUTH_GOOGLE_CLIENT_ID},{key:"AUTH_GITHUB_CLIENT_ID",value:!!process.env.AUTH_GITHUB_CLIENT_ID},{key:"AUTH_RESEND_API_KEY",value:!!process.env.AUTH_RESEND_API_KEY},{key:"AUTH_SENDGRID_API_KEY",value:!!process.env.AUTH_SENDGRID_API_KEY},{key:"AUTH_SSO_MS_CLIENT_ID",value:!!process.env.AUTH_SSO_MS_CLIENT_ID},{key:"AUTH_MAGIC_LINK_ENABLED",value:process.env.AUTH_MAGIC_LINK_ENABLED==="true"},{key:"AUTH_EMAIL_OTP_ENABLED",value:process.env.AUTH_EMAIL_OTP_ENABLED==="true"}]},{title:"Observability",entries:[{key:"CLICKHOUSE_URL",value:X.clickhouseUrl},{key:"OTEL_SERVICE_NAME",value:X.otelServiceName}]},{title:"Event Bus & Networking",entries:[{key:"NATS_URL",value:X.natsUrls}]},{title:"Config Files",entries:[{key:"CONFIG_PATH",value:X.configPath}]},{title:"Transport",entries:[{key:"UNSAFE_ALLOW_STDIO_TRANSPORT",value:X.unsafeAllowStdioTransport}]},{title:"AI Gateway",entries:[{key:"DECO_AI_GATEWAY_ENABLED",value:X.aiGatewayEnabled},{key:"DECO_AI_GATEWAY_URL",value:X.aiGatewayUrl}]}]}function Ns6({env:X}){let Y=Ai5(X);return Us6(RN0,{flexDirection:"column",children:Y.map((G)=>LA1(RN0,{flexDirection:"column",marginTop:1,children:[LA1(SN0,{dimColor:!0,children:[" ","\u2500\u2500 ",G.title," ","\u2500".repeat(Math.max(0,38-G.title.length))]}),G.entries.map(({key:Q,value:J})=>{let W=qi5(Q,J);return LA1(RN0,{children:[LA1(SN0,{dimColor:!0,children:[" ",Q.padEnd(36)]}),Us6(SN0,{color:W.color,dimColor:W.dimColor,children:W.text})]},Q)})]},G.title))})}var Ei5,Pi5;var Bs6=D(()=>{Ei5=new Set(["BETTER_AUTH_SECRET","ENCRYPTION_KEY","MESH_JWT_SECRET","STUDIO_PROVISION_SECRET_KEY"]),Pi5=new Set(["DATABASE_URL","CLICKHOUSE_URL","NATS_URL"])});var CN0;var zs6=D(()=>{CN0={name:"decocms",version:"2.286.1",description:"Deco CMS \u2014 Self-hostable MCP Gateway for managing AI connections and tools",author:"Deco team",repository:{type:"git",url:"git+https://github.com/decocms/studio.git",directory:"apps/mesh"},bugs:{url:"https://github.com/decocms/studio/issues"},type:"module",bin:{deco:"./dist/server/cli.js"},files:["dist/**/*"],scripts:{dev:'bun run migrate && concurrently "bun run dev:client" "bun run dev:server"',"dev:servers":'concurrently "bun run dev:client" "bun run dev:server"',"dev:client":"bun --bun vite dev","dev:server":"bun run --cwd=../../packages/sandbox build && NODE_ENV=development bun --env-file=.env --hot run src/index.ts","build:client":"bun --bun vite build","build:server":"bun run scripts/bundle-server-script.ts --dist ./dist/server","db:migrate":"bun run ./dist/server/migrate.js",check:"tsc --noEmit",start:"bun run ./dist/server/server.js",migrate:"bun run src/database/migrate.ts",test:"bun test","test:e2e":"playwright test","test:e2e:ui":"playwright test --ui","better-auth:migrate":"bunx --bun @better-auth/cli migrate -y --config src/auth/index.ts",prepublishOnly:"bun run build:client && bun run build:server"},optionalDependencies:{"@duckdb/node-api":"^1.5.0-r.1","@freestyle-sh/with-bun":"^0.2.12","@freestyle-sh/with-deno":"^0.0.4","@freestyle-sh/with-nodejs":"^0.2.9","freestyle-sandboxes":"^0.1.46"},dependencies:{"@ai-sdk/anthropic":"^3.0.58","@ai-sdk/google":"^3.0.60","@ai-sdk/openai":"^3.0.50","@anthropic-ai/sdk":"^0.79.0","@aws-sdk/client-s3":"^3.1013.0","@aws-sdk/s3-request-presigner":"^3.1013.0","@clickhouse/client":"^1.8.1","@dnd-kit/core":"^6.3.1","@dnd-kit/sortable":"^10.0.0","@dnd-kit/utilities":"^3.2.2","@inkjs/ui":"^2.0.0","@modelcontextprotocol/ext-apps":"^1.2.2","@openrouter/ai-sdk-provider":"^2.2.5","@opentelemetry/core":"^2.6.0","@tanstack/react-virtual":"^3.13.21","@xterm/addon-fit":"^0.11.0","@xterm/xterm":"^6.0.0","ai-sdk-provider-claude-code":"^3.4.4","ai-sdk-provider-codex-cli":"^1.1.0","embedded-postgres":"^18.3.0-beta.16",ink:"^6.8.0",kysely:"^0.28.12",nats:"^2.29.3","posthog-js":"^1.371.1","posthog-node":"^5.0.0",react:"^19.2.0","react-dom":"^19.2.0"},devDependencies:{"@ai-sdk/provider":"^3.0.8","@ai-sdk/react":"^3.0.118","@anthropic-ai/claude-agent-sdk":"^0.2.80","@better-auth/sso":"1.4.1","@daveyplate/better-auth-ui":"^3.2.7","@deco/ui":"workspace:*","@decocms/better-auth":"1.5.17","@decocms/bindings":"workspace:*","@decocms/mcp-utils":"workspace:*","@decocms/mesh-sdk":"workspace:*","@decocms/runtime":"workspace:*","@decocms/vite-plugin":"workspace:*","@electric-sql/pglite":"^0.3.15","@floating-ui/react":"^0.27.16","@hookform/resolvers":"^5.2.2","@jitl/quickjs-wasmfile-release-sync":"0.31.0","@modelcontextprotocol/sdk":"1.27.1","@monaco-editor/react":"^4.7.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.211.0","@opentelemetry/exporter-logs-otlp-proto":"^0.211.0","@opentelemetry/exporter-prometheus":"^0.208.0","@opentelemetry/exporter-trace-otlp-proto":"^0.207.0","@opentelemetry/instrumentation-runtime-node":"^0.24.0","@opentelemetry/sdk-logs":"^0.211.0","@opentelemetry/sdk-metrics":"^2.2.0","@opentelemetry/sdk-node":"^0.207.0","@opentelemetry/sdk-trace-base":"^2.5.0","@playwright/test":"^1.58.2","@radix-ui/react-avatar":"^1.1.10","@radix-ui/react-checkbox":"^1.3.3","@radix-ui/react-dialog":"^1.1.15","@radix-ui/react-dropdown-menu":"^2.1.16","@radix-ui/react-label":"^2.1.7","@radix-ui/react-select":"^2.2.6","@radix-ui/react-separator":"^1.1.7","@radix-ui/react-slot":"^1.2.3","@radix-ui/react-tabs":"^1.1.13","@rjsf/core":"^6.1.2","@rjsf/shadcn":"^6.1.2","@rjsf/utils":"^6.1.2","@rjsf/validator-ajv8":"^6.1.2","@tailwindcss/vite":"^4.1.17","@tanstack/react-query":"5.90.11","@tanstack/react-router":"^1.139.7","@tiptap/core":"3.20.2","@tiptap/extension-mention":"3.20.2","@tiptap/extension-placeholder":"3.20.2","@tiptap/pm":"3.20.2","@tiptap/react":"3.20.2","@tiptap/starter-kit":"3.20.2","@tiptap/suggestion":"3.20.2","@types/bun":"^1.3.1","@types/pg":"^8.15.6","@types/react-syntax-highlighter":"^15.5.13","@untitledui/icons":"^0.0.19","@vercel/nft":"^1.1.1","@vitejs/plugin-react":"^5.1.0",ai:"^6.0.116","babel-plugin-react-compiler":"^1.0.0","better-auth":"1.4.5","class-variance-authority":"^0.7.1",clsx:"^2.1.1",concurrently:"^9.2.1",croner:"^9.1.0","date-fns":"^4.1.0",degit:"^2.8.4",hono:"^4.10.7","input-otp":"^1.4.2",jose:"^6.0.11","kysely-pglite":"^0.6.1","lucide-react":"^0.468.0",marked:"^15.0.6","@decocms/sandbox":"workspace:*","mesh-plugin-workflows":"workspace:*",nanoid:"^5.1.6",pg:"^8.16.3",prettier:"^3.4.2","react-hook-form":"^7.66.0","react-markdown":"^10.1.0","react-resizable-panels":"^2.1.7","react-syntax-highlighter":"^15.6.1",recharts:"^3.6.0","rehype-raw":"^7.0.0","remark-gfm":"^4.0.0","sass-embedded":"^1.97.2",sonner:"^2.0.7","tailwind-merge":"^3.3.1",tailwindcss:"^4.1.17",typescript:"^5.9.3",vite:"^7.2.1","vite-tsconfig-paths":"^5.1.4",zod:"^4.0.0",zustand:"^5.0.9"},homepage:"https://github.com/decocms/studio",keywords:["mcp","model-context-protocol","ai","gateway","self-hosted","mesh","tools"],license:"MIT",publishConfig:{access:"public"}}});import{Box as qU,Text as MX}from"ink";import{Spinner as Ii5}from"@inkjs/ui";import{useSyncExternalStore as Os6}from"react";import{jsx as qY,jsxs as tQ}from"react/jsx-runtime";function Si5(X,Y){if(!X||!Ri5.has(X))return X;let G=kN0[Y]??kN0[kN0.length-1];return X==="#875f00"?G[0]:G[1]}function Ds6({status:X}){if(X==="pending")return qY(Ii5,{label:""});return qY(MX,{color:"green",children:"\u2713"})}function ws6({services:X,migrationsStatus:Y,home:G,serverUrl:Q,vibe:J}){let W=Os6(Tu0,Au0),Z=Os6(Su0,Ru0);return tQ(qU,{flexDirection:"column",paddingBottom:1,children:[J?tQ(qU,{flexDirection:"column",children:[W.map(($,K)=>{let H=Z[K],U=$.reduce((B,z)=>B+z.text.length,0),N=Math.max(0,Mi5-U);return tQ(qU,{flexDirection:"row",children:[$.map((B,z)=>{let O=Si5(B.color,K);return O?qY(MX,{color:O,children:B.text},z):qY(MX,{children:B.text},z)}),qY(MX,{children:" ".repeat(N+2)}),H?.map((B,z)=>B.color?qY(MX,{color:B.color,children:B.char},z):qY(MX,{children:B.char},z))]},K)}),tQ(MX,{dimColor:!0,children:[" v",CN0.version]})]}):tQ(qU,{flexDirection:"column",marginTop:1,children:[Vi5.map(($,K)=>qY(MX,{color:ji5[K],children:$},K)),tQ(MX,{dimColor:!0,children:[" v",CN0.version]})]}),qY(qU,{marginBottom:1,children:qY(MX,{dimColor:!0,children:"\u2500".repeat(80)})}),qY(qU,{children:tQ(MX,{dimColor:!0,children:["Home: ",G]})}),tQ(qU,{gap:2,children:[X.map(($)=>tQ(qU,{gap:1,children:[tQ(MX,{children:[$.name," :",$.port||"...."]}),qY(Ds6,{status:$.status})]},$.name)),tQ(qU,{gap:1,children:[qY(MX,{children:"Migrations"}),qY(Ds6,{status:Y})]})]}),qY(qU,{children:Q?tQ(MX,{children:["Open in browser: ",qY(MX,{color:"cyan",children:Q})]}):qY(MX,{dimColor:!0,children:"Starting..."})}),tQ(qU,{gap:2,children:[tQ(MX,{dimColor:!0,children:[qY(MX,{bold:!0,dimColor:!0,children:"K"})," ","toggle config"]}),tQ(MX,{dimColor:!0,children:[qY(MX,{bold:!0,dimColor:!0,children:"L"})," ","toggle log flow"]}),tQ(MX,{dimColor:!0,children:[qY(MX,{bold:!0,dimColor:!0,children:"V"})," ","toggle vibe ",J?"\u266A Nihilore \xB7 CC BY 4.0":""]}),J&&tQ(MX,{dimColor:!0,children:[qY(MX,{bold:!0,dimColor:!0,children:"N"})," ","skip song"]})]})]})}var Vi5,ji5,kN0,Mi5=30,Ri5;var Ls6=D(()=>{zs6();Bn1();En1();Vi5=[" \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588 ","\u2591\u2591\u2588\u2588\u2588\u2591\u2591\u2591\u2591\u2588\u2588\u2588 \u2591\u2591\u2588\u2588\u2588\u2591\u2591\u2591\u2591\u2591\u2588 \u2588\u2588\u2588\u2591\u2591\u2591\u2591\u2591\u2588\u2588\u2588 \u2588\u2588\u2588\u2591\u2591\u2591\u2591\u2591\u2588\u2588\u2588 "," \u2591\u2588\u2588\u2588 \u2591\u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2588 \u2591 \u2588\u2588\u2588 \u2591\u2591\u2591 \u2588\u2588\u2588 \u2591\u2591\u2588\u2588\u2588"," \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588"," \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588\u2591\u2591\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588"," \u2591\u2588\u2588\u2588 \u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591 \u2588\u2591\u2591\u2588\u2588\u2588 \u2588\u2588\u2588\u2591\u2591\u2588\u2588\u2588 \u2588\u2588\u2588 "," \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2591\u2591\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2591\u2591\u2591\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2591 ","\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591 \u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591 \u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591 \u2591\u2591\u2591\u2591\u2591\u2591\u2591 "],ji5=["#00ff64","#00ee5e","#00dc56","#00c84e","#00b444","#00a03c","#008832","#006e28"],kN0=[["#00ff64","#00cc50"],["#00f060","#00c04c"],["#00e05c","#00b448"],["#00d058","#00a844"],["#00c054","#009c40"],["#00b050","#00903c"],["#00a04c","#008438"],["#009048","#007834"],["#008044","#006c30"],["#007040","#00602c"],["#00603c","#005428"]],Ri5=new Set(["#875f00","#5f3800"])});import{useSyncExternalStore as Ci5}from"react";function ki5(){let X=process.stdout.rows||24,Y=process.stdout.columns||80;if(X!==EA1.rows||Y!==EA1.columns)EA1={rows:X,columns:Y};return EA1}function vi5(X){return process.stdout.on("resize",X),()=>{process.stdout.off("resize",X)}}function Es6(){return Ci5(vi5,ki5)}var EA1;var Ps6=D(()=>{EA1={rows:process.stdout.rows||24,columns:process.stdout.columns||80}});import{Box as _i5,Text as qX1}from"ink";import{useSyncExternalStore as fi5}from"react";import{jsx as vN0,jsxs as _N0}from"react/jsx-runtime";function bi5(X){if(X>=500)return"red";if(X>=400)return"yellow";if(X>=300)return"cyan";return"green"}function qs6({logs:X,headerHeight:Y}){let{rows:G}=Es6(),{logFlow:Q}=fi5(Pe,Ee),J=Math.max(1,G-Y-1),W=Q?X:X.slice(-J);return vN0(_i5,{flexDirection:"column",children:W.map((Z,$)=>{if(Z.rawLine)return vN0(qX1,{dimColor:!0,children:Z.rawLine},$);let K=Z.duration<1000?`${Z.duration}ms`:`${(Z.duration/1000).toFixed(1)}s`;return _N0(qX1,{children:[_N0(qX1,{dimColor:!0,children:[Z.method.padEnd(6)," ",Z.path.padEnd(30)," "]}),vN0(qX1,{color:bi5(Z.status),children:Z.status}),_N0(qX1,{dimColor:!0,children:[" ",K.padStart(8)]})]},$)})})}var As6=D(()=>{YF();Ps6()});var fN0={};R0(fN0,{App:()=>mi5});import{Box as yi5,Text as xi5,useInput as hi5}from"ink";import{useSyncExternalStore as gi5}from"react";import{jsx as PA1,jsxs as di5}from"react/jsx-runtime";function mi5({home:X}){let Y=gi5(Pe,Ee);return hi5((G)=>{if(G==="k"||G==="K")Vn1();if(G==="l"||G==="L")jn1();if((G==="v"||G==="V")&&Y.dataDir)Tn1(Y.dataDir),Mn1();if((G==="n"||G==="N")&&Y.vibe)An1()}),di5(yi5,{flexDirection:"column",children:[PA1(ws6,{services:Y.services,migrationsStatus:Y.migrationsStatus,home:X,serverUrl:Y.serverUrl,vibe:Y.vibe}),Y.viewMode==="config"?Y.env?PA1(Ns6,{env:Y.env}):PA1(xi5,{dimColor:!0,children:"Loading configuration..."}):PA1(qs6,{logs:Y.logs,headerHeight:Y.vibe?li5:ui5})]})}var ui5=15,li5=19;var bN0=D(()=>{Bs6();Ls6();As6();YF();Ud()});function Ts6(X,Y={}){return{PORT:String(X.port),NODE_ENV:X.nodeEnv,BASE_URL:X.baseUrl,DATA_DIR:X.dataDir,DECOCMS_HOME:X.dataDir,DATABASE_URL:X.databaseUrl,DATABASE_PG_SSL:String(X.databasePgSsl),DATABASE_POOL_MAX:String(X.databasePoolMax),NATS_URL:X.natsUrls.join(","),BETTER_AUTH_SECRET:X.betterAuthSecret,ENCRYPTION_KEY:X.encryptionKey,MESH_JWT_SECRET:X.meshJwtSecret,DECOCMS_LOCAL_MODE:String(X.localMode),DECOCMS_ALLOW_LOCAL_PROD:String(X.allowLocalProd),DISABLE_RATE_LIMIT:String(X.disableRateLimit),STUDIO_PROVISION_SECRET_KEY:X.studioProvisionSecretKey,CONFIG_PATH:X.configPath,...Object.fromEntries(Object.entries(process.env).filter(([G])=>G.startsWith("AUTH_"))),UNSAFE_ALLOW_STDIO_TRANSPORT:String(X.unsafeAllowStdioTransport),DECO_AI_GATEWAY_ENABLED:String(X.aiGatewayEnabled),DECO_AI_GATEWAY_URL:X.aiGatewayUrl,ENABLE_DECO_IMPORT:String(X.enableDecoImport),S3_ENDPOINT:X.s3Endpoint,S3_BUCKET:X.s3Bucket,S3_REGION:X.s3Region,S3_ACCESS_KEY_ID:X.s3AccessKeyId,S3_SECRET_ACCESS_KEY:X.s3SecretAccessKey,S3_FORCE_PATH_STYLE:String(X.s3ForcePathStyle),OTEL_SERVICE_NAME:X.otelServiceName,CLICKHOUSE_URL:X.clickhouseUrl,DECO_SUPABASE_URL:X.decoSupabaseUrl,DECO_SUPABASE_SERVICE_KEY:X.decoSupabaseServiceKey,FIRECRAWL_API_KEY:X.firecrawlApiKey,STUDIO_SANDBOX_RUNNER:process.env.STUDIO_SANDBOX_RUNNER,FREESTYLE_API_KEY:process.env.FREESTYLE_API_KEY,BROWSERLESS_TOKEN:process.env.BROWSERLESS_TOKEN,NODE_EXTRA_CA_CERTS:process.env.NODE_EXTRA_CA_CERTS,DECO_CLI:"1",DECO_NO_TUI:"true",...Y}}function Vs6(X){if(!X)return!1;try{return new URL(X).host==="api.decocms.com"&&X!=="https://studio.decocms.com/org/deco/registry/mcp"}catch{return!1}}var Is6="https://studio.decocms.com/org/deco/registry/mcp";var yN0=(X,Y,G)=>{return(Q,J)=>{let W=-1;return Z(0);async function Z($){if($<=W)throw Error("next() called multiple times");W=$;let K,H=!1,U;if(X[$])U=X[$][0][0],Q.req.routeIndex=$;else U=$===X.length&&J||void 0;if(U)try{K=await U(Q,()=>Z($+1))}catch(N){if(N instanceof Error&&Y)Q.error=N,K=await Y(N,Q),H=!0;else throw N}else if(Q.finalized===!1&&G)K=await G(Q);if(K&&(Q.finalized===!1||H))Q.res=K;return Q}}};var js6=()=>{};var M9;var Lq=D(()=>{M9=class extends Error{res;status;constructor(X=500,Y){super(Y?.message,{cause:Y?.cause});this.res=Y?.res,this.status=X}getResponse(){if(this.res)return new Response(this.res.body,{status:this.status,headers:this.res.headers});return new Response(this.message,{status:this.status})}}});var Ms6;var Rs6=D(()=>{Ms6=Symbol()});async function ci5(X,Y){let G=await X.formData();if(G)return ii5(G,Y);return{}}function ii5(X,Y){let G=Object.create(null);if(X.forEach((Q,J)=>{if(!(Y.all||J.endsWith("[]")))G[J]=Q;else pi5(G,J,Q)}),Y.dot)Object.entries(G).forEach(([Q,J])=>{if(Q.includes("."))ni5(G,Q,J),delete G[Q]});return G}var Ss6=async(X,Y=Object.create(null))=>{let{all:G=!1,dot:Q=!1}=Y,W=(X instanceof qA1?X.raw.headers:X.headers).get("Content-Type");if(W?.startsWith("multipart/form-data")||W?.startsWith("application/x-www-form-urlencoded"))return ci5(X,{all:G,dot:Q});return{}},pi5=(X,Y,G)=>{if(X[Y]!==void 0)if(Array.isArray(X[Y]))X[Y].push(G);else X[Y]=[X[Y],G];else if(!Y.endsWith("[]"))X[Y]=G;else X[Y]=[G]},ni5=(X,Y,G)=>{if(/(?:^|\.)__proto__\./.test(Y))return;let Q=X,J=Y.split(".");J.forEach((W,Z)=>{if(Z===J.length-1)Q[W]=G;else{if(!Q[W]||typeof Q[W]!=="object"||Array.isArray(Q[W])||Q[W]instanceof File)Q[W]=Object.create(null);Q=Q[W]}})};var Cs6=D(()=>{xN0()});var gN0=(X)=>{let Y=X.split("/");if(Y[0]==="")Y.shift();return Y},ks6=(X)=>{let{groups:Y,path:G}=ai5(X),Q=gN0(G);return ti5(Q,Y)},ai5=(X)=>{let Y=[];return X=X.replace(/\{[^}]+\}/g,(G,Q)=>{let J=`@${Q}`;return Y.push([J,G]),J}),{groups:Y,path:X}},ti5=(X,Y)=>{for(let G=Y.length-1;G>=0;G--){let[Q]=Y[G];for(let J=X.length-1;J>=0;J--)if(X[J].includes(Q)){X[J]=X[J].replace(Q,Y[G][1]);break}}return X},AA1,vs6=(X,Y)=>{if(X==="*")return"*";let G=X.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(G){let Q=`${X}#${Y}`;if(!AA1[Q])if(G[2])AA1[Q]=Y&&Y[0]!==":"&&Y[0]!=="*"?[Q,G[1],new RegExp(`^${G[2]}(?=/${Y})`)]:[X,G[1],new RegExp(`^${G[2]}$`)];else AA1[Q]=[X,G[1],!0];return AA1[Q]}return null},la=(X,Y)=>{try{return Y(X)}catch{return X.replace(/(?:%[0-9A-Fa-f]{2})+/g,(G)=>{try{return Y(G)}catch{return G}})}},_s6=(X)=>la(X,decodeURI),uN0=(X)=>{let Y=X.url,G=Y.indexOf("/",Y.indexOf(":")+4),Q=G;for(;Q<Y.length;Q++){let J=Y.charCodeAt(Q);if(J===37){let W=Y.indexOf("?",Q),Z=Y.indexOf("#",Q),$=W===-1?Z===-1?void 0:Z:Z===-1?W:Math.min(W,Z),K=Y.slice(G,$);return _s6(K.includes("%25")?K.replace(/%25/g,"%2525"):K)}else if(J===63||J===35)break}return Y.slice(G,Q)},fs6=(X)=>{let Y=uN0(X);return Y.length>1&&Y.at(-1)==="/"?Y.slice(0,-1):Y},Pj=(X,Y,...G)=>{if(G.length)Y=Pj(Y,...G);return`${X?.[0]==="/"?"":"/"}${X}${Y==="/"?"":`${X?.at(-1)==="/"?"":"/"}${Y?.[0]==="/"?Y.slice(1):Y}`}`},TA1=(X)=>{if(X.charCodeAt(X.length-1)!==63||!X.includes(":"))return null;let Y=X.split("/"),G=[],Q="";return Y.forEach((J)=>{if(J!==""&&!/\:/.test(J))Q+="/"+J;else if(/\:/.test(J))if(/\?/.test(J)){if(G.length===0&&Q==="")G.push("/");else G.push(Q);let W=J.replace("?","");Q+="/"+W,G.push(Q)}else Q+="/"+J}),G.filter((J,W,Z)=>Z.indexOf(J)===W)},hN0=(X)=>{if(!/[%+]/.test(X))return X;if(X.indexOf("+")!==-1)X=X.replace(/\+/g," ");return X.indexOf("%")!==-1?la(X,AX1):X},bs6=(X,Y,G)=>{let Q;if(!G&&Y&&!/[%+]/.test(Y)){let Z=X.indexOf("?",8);if(Z===-1)return;if(!X.startsWith(Y,Z+1))Z=X.indexOf(`&${Y}`,Z+1);while(Z!==-1){let $=X.charCodeAt(Z+Y.length+1);if($===61){let K=Z+Y.length+2,H=X.indexOf("&",K);return hN0(X.slice(K,H===-1?void 0:H))}else if($==38||isNaN($))return"";Z=X.indexOf(`&${Y}`,Z+1)}if(Q=/[%+]/.test(X),!Q)return}let J={};Q??=/[%+]/.test(X);let W=X.indexOf("?",8);while(W!==-1){let Z=X.indexOf("&",W+1),$=X.indexOf("=",W);if($>Z&&Z!==-1)$=-1;let K=X.slice(W+1,$===-1?Z===-1?void 0:Z:$);if(Q)K=hN0(K);if(W=Z,K==="")continue;let H;if($===-1)H="";else if(H=X.slice($+1,Z===-1?void 0:Z),Q)H=hN0(H);if(G){if(!(J[K]&&Array.isArray(J[K])))J[K]=[];J[K].push(H)}else J[K]??=H}return Y?J[Y]:J},ys6,xs6=(X,Y)=>{return bs6(X,Y,!0)},AX1;var Eq=D(()=>{AA1={},ys6=bs6,AX1=decodeURIComponent});var hs6=(X)=>la(X,AX1),qA1;var xN0=D(()=>{Lq();Rs6();Cs6();Eq();qA1=class{raw;#X;#Y;routeIndex=0;path;bodyCache={};constructor(X,Y="/",G=[[]]){this.raw=X,this.path=Y,this.#Y=G,this.#X={}}param(X){return X?this.#G(X):this.#Q()}#G(X){let Y=this.#Y[0][this.routeIndex][1][X],G=this.#J(Y);return G&&/\%/.test(G)?hs6(G):G}#Q(){let X={},Y=Object.keys(this.#Y[0][this.routeIndex][1]);for(let G of Y){let Q=this.#J(this.#Y[0][this.routeIndex][1][G]);if(Q!==void 0)X[G]=/\%/.test(Q)?hs6(Q):Q}return X}#J(X){return this.#Y[1]?this.#Y[1][X]:X}query(X){return ys6(this.url,X)}queries(X){return xs6(this.url,X)}header(X){if(X)return this.raw.headers.get(X)??void 0;let Y={};return this.raw.headers.forEach((G,Q)=>{Y[Q]=G}),Y}async parseBody(X){return Ss6(this,X)}#Z=(X)=>{let{bodyCache:Y,raw:G}=this,Q=Y[X];if(Q)return Q;let J=Object.keys(Y)[0];if(J)return Y[J].then((W)=>{if(J==="json")W=JSON.stringify(W);return new Response(W)[X]()});return Y[X]=G[X]()};json(){return this.#Z("text").then((X)=>JSON.parse(X))}text(){return this.#Z("text")}arrayBuffer(){return this.#Z("arrayBuffer")}blob(){return this.#Z("blob")}formData(){return this.#Z("formData")}addValidatedData(X,Y){this.#X[X]=Y}valid(X){return this.#X[X]}get url(){return this.raw.url}get method(){return this.raw.method}get[Ms6](){return this.#Y}get matchedRoutes(){return this.#Y[0].map(([[,X]])=>X)}get routePath(){return this.#Y[0].map(([[,X]])=>X)[this.routeIndex].path}}});var IA1,gs6=(X,Y)=>{let G=new String(X);return G.isEscaped=!0,G.callbacks=Y,G},TX1=async(X,Y,G,Q,J)=>{if(typeof X==="object"&&!(X instanceof String)){if(!(X instanceof Promise))X=X.toString();if(X instanceof Promise)X=await X}let W=X.callbacks;if(!W?.length)return Promise.resolve(X);if(J)J[0]+=X;else J=[X];let Z=Promise.all(W.map(($)=>$({phase:Y,buffer:J,context:Q}))).then(($)=>Promise.all($.filter(Boolean).map((K)=>TX1(K,Y,!1,Q,J))).then(()=>J[0]));if(G)return gs6(await Z,W);else return Z};var VA1=D(()=>{IA1={Stringify:1,BeforeStream:2,Stream:3}});var us6="text/plain; charset=UTF-8",lN0=(X,Y)=>{return{"Content-Type":X,...Y}},IX1=(X,Y)=>new Response(X,Y),ls6=class{#X;#Y;env={};#G;finalized=!1;error;#Q;#J;#Z;#$;#W;#K;#H;#U;#N;constructor(X,Y){if(this.#X=X,Y)this.#J=Y.executionCtx,this.env=Y.env,this.#K=Y.notFoundHandler,this.#N=Y.path,this.#U=Y.matchResult}get req(){return this.#Y??=new qA1(this.#X,this.#N,this.#U),this.#Y}get event(){if(this.#J&&"respondWith"in this.#J)return this.#J;else throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#J)return this.#J;else throw Error("This context has no ExecutionContext")}get res(){return this.#Z||=IX1(null,{headers:this.#H??=new Headers})}set res(X){if(this.#Z&&X){X=IX1(X.body,X);for(let[Y,G]of this.#Z.headers.entries()){if(Y==="content-type")continue;if(Y==="set-cookie"){let Q=this.#Z.headers.getSetCookie();X.headers.delete("set-cookie");for(let J of Q)X.headers.append("set-cookie",J)}else X.headers.set(Y,G)}}this.#Z=X,this.finalized=!0}render=(...X)=>{return this.#W??=(Y)=>this.html(Y),this.#W(...X)};setLayout=(X)=>this.#$=X;getLayout=()=>this.#$;setRenderer=(X)=>{this.#W=X};header=(X,Y,G)=>{if(this.finalized)this.#Z=IX1(this.#Z.body,this.#Z);let Q=this.#Z?this.#Z.headers:this.#H??=new Headers;if(Y===void 0)Q.delete(X);else if(G?.append)Q.append(X,Y);else Q.set(X,Y)};status=(X)=>{this.#Q=X};set=(X,Y)=>{this.#G??=new Map,this.#G.set(X,Y)};get=(X)=>{return this.#G?this.#G.get(X):void 0};get var(){if(!this.#G)return{};return Object.fromEntries(this.#G)}#F(X,Y,G){let Q=this.#Z?new Headers(this.#Z.headers):this.#H??new Headers;if(typeof Y==="object"&&"headers"in Y){let W=Y.headers instanceof Headers?Y.headers:new Headers(Y.headers);for(let[Z,$]of W)if(Z.toLowerCase()==="set-cookie")Q.append(Z,$);else Q.set(Z,$)}if(G)for(let[W,Z]of Object.entries(G))if(typeof Z==="string")Q.set(W,Z);else{Q.delete(W);for(let $ of Z)Q.append(W,$)}let J=typeof Y==="number"?Y:Y?.status??this.#Q;return IX1(X,{status:J,headers:Q})}newResponse=(...X)=>this.#F(...X);body=(X,Y,G)=>this.#F(X,Y,G);text=(X,Y,G)=>{return!this.#H&&!this.#Q&&!Y&&!G&&!this.finalized?new Response(X):this.#F(X,Y,lN0(us6,G))};json=(X,Y,G)=>{return this.#F(JSON.stringify(X),Y,lN0("application/json",G))};html=(X,Y,G)=>{let Q=(J)=>this.#F(J,Y,lN0("text/html; charset=UTF-8",G));return typeof X==="object"?TX1(X,IA1.Stringify,!1,{}).then(Q):Q(X)};redirect=(X,Y)=>{let G=String(X);return this.header("Location",!/[^\x00-\xFF]/.test(G)?G:encodeURI(G)),this.newResponse(null,Y??302)};notFound=()=>{return this.#K??=()=>IX1(),this.#K(this)}};var jA1=D(()=>{xN0();VA1()});var T7="ALL",ms6="all",ds6,MA1="Can not add a route since the matcher is already built.",RA1;var Pq=D(()=>{ds6=["get","post","put","delete","options","patch"],RA1=class extends Error{}});var mN0="__COMPOSED_HANDLER";var dN0=()=>{};var ri5=(X)=>{return X.text("404 Not Found",404)},cs6=(X,Y)=>{if("getResponse"in X){let G=X.getResponse();return Y.newResponse(G.body,G)}return console.error(X),Y.text("Internal Server Error",500)},is6=class X{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#X="/";routes=[];constructor(Y={}){[...ds6,ms6].forEach((W)=>{this[W]=(Z,...$)=>{if(typeof Z==="string")this.#X=Z;else this.#Q(W,this.#X,Z);return $.forEach((K)=>{this.#Q(W,this.#X,K)}),this}}),this.on=(W,Z,...$)=>{for(let K of[Z].flat()){this.#X=K;for(let H of[W].flat())$.map((U)=>{this.#Q(H.toUpperCase(),this.#X,U)})}return this},this.use=(W,...Z)=>{if(typeof W==="string")this.#X=W;else this.#X="*",Z.unshift(W);return Z.forEach(($)=>{this.#Q(T7,this.#X,$)}),this};let{strict:Q,...J}=Y;Object.assign(this,J),this.getPath=Q??!0?Y.getPath??uN0:fs6}#Y(){let Y=new X({router:this.router,getPath:this.getPath});return Y.errorHandler=this.errorHandler,Y.#G=this.#G,Y.routes=this.routes,Y}#G=ri5;errorHandler=cs6;route(Y,G){let Q=this.basePath(Y);return G.routes.map((J)=>{let W;if(G.errorHandler===cs6)W=J.handler;else W=async(Z,$)=>(await yN0([],G.errorHandler)(Z,()=>J.handler(Z,$))).res,W[mN0]=J.handler;Q.#Q(J.method,J.path,W)}),this}basePath(Y){let G=this.#Y();return G._basePath=Pj(this._basePath,Y),G}onError=(Y)=>{return this.errorHandler=Y,this};notFound=(Y)=>{return this.#G=Y,this};mount(Y,G,Q){let J,W;if(Q)if(typeof Q==="function")W=Q;else if(W=Q.optionHandler,Q.replaceRequest===!1)J=(K)=>K;else J=Q.replaceRequest;let Z=W?(K)=>{let H=W(K);return Array.isArray(H)?H:[H]}:(K)=>{let H=void 0;try{H=K.executionCtx}catch{}return[K.env,H]};J||=(()=>{let K=Pj(this._basePath,Y),H=K==="/"?0:K.length;return(U)=>{let N=new URL(U.url);return N.pathname=N.pathname.slice(H)||"/",new Request(N,U)}})();let $=async(K,H)=>{let U=await G(J(K.req.raw),...Z(K));if(U)return U;await H()};return this.#Q(T7,Pj(Y,"*"),$),this}#Q(Y,G,Q){Y=Y.toUpperCase(),G=Pj(this._basePath,G);let J={basePath:this._basePath,path:G,method:Y,handler:Q};this.router.add(Y,G,[Q,J]),this.routes.push(J)}#J(Y,G){if(Y instanceof Error)return this.errorHandler(Y,G);throw Y}#Z(Y,G,Q,J){if(J==="HEAD")return(async()=>new Response(null,await this.#Z(Y,G,Q,"GET")))();let W=this.getPath(Y,{env:Q}),Z=this.router.match(J,W),$=new ls6(Y,{path:W,matchResult:Z,env:Q,executionCtx:G,notFoundHandler:this.#G});if(Z[0].length===1){let H;try{H=Z[0][0][0][0]($,async()=>{$.res=await this.#G($)})}catch(U){return this.#J(U,$)}return H instanceof Promise?H.then((U)=>U||($.finalized?$.res:this.#G($))).catch((U)=>this.#J(U,$)):H??this.#G($)}let K=yN0(Z[0],this.errorHandler,this.#G);return(async()=>{try{let H=await K($);if(!H.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return H.res}catch(H){return this.#J(H,$)}})()}fetch=(Y,...G)=>{return this.#Z(Y,G[1],G[0],Y.method)};request=(Y,G,Q,J)=>{if(Y instanceof Request)return this.fetch(G?new Request(Y,G):Y,Q,J);return Y=Y.toString(),this.fetch(new Request(/^https?:\/\//.test(Y)?Y:`http://localhost${Pj("/",Y)}`,G),Q,J)};fire=()=>{addEventListener("fetch",(Y)=>{Y.respondWith(this.#Z(Y.request,Y,void 0,Y.request.method))})}};var ps6=D(()=>{js6();jA1();Pq();dN0();Eq()});function SA1(X,Y){let G=this.buildAllMatchers(),Q=(J,W)=>{let Z=G[J]||G[T7],$=Z[2][W];if($)return $;let K=W.match(Z[0]);if(!K)return[[],VX1];let H=K.indexOf("",1);return[Z[1][H],K]};return this.match=Q,Q(X,Y)}var VX1;var cN0=D(()=>{Pq();VX1=[]});function si5(X,Y){if(X.length===1)return Y.length===1?X<Y?-1:1:-1;if(Y.length===1)return 1;if(X===jX1||X===MX1)return 1;else if(Y===jX1||Y===MX1)return-1;if(X===CA1)return 1;else if(Y===CA1)return-1;return X.length===Y.length?X<Y?-1:1:Y.length-X.length}var CA1="[^/]+",jX1=".*",MX1="(?:|/.*)",qj,oi5,ns6=class X{#X;#Y;#G=Object.create(null);insert(Y,G,Q,J,W){if(Y.length===0){if(this.#X!==void 0)throw qj;if(W)return;this.#X=G;return}let[Z,...$]=Y,K=Z==="*"?$.length===0?["","",jX1]:["","",CA1]:Z==="/*"?["","",MX1]:Z.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),H;if(K){let U=K[1],N=K[2]||CA1;if(U&&K[2]){if(N===".*")throw qj;if(N=N.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(N))throw qj}if(H=this.#G[N],!H){if(Object.keys(this.#G).some((B)=>B!==jX1&&B!==MX1))throw qj;if(W)return;if(H=this.#G[N]=new X,U!=="")H.#Y=J.varIndex++}if(!W&&U!=="")Q.push([U,H.#Y])}else if(H=this.#G[Z],!H){if(Object.keys(this.#G).some((U)=>U.length>1&&U!==jX1&&U!==MX1))throw qj;if(W)return;H=this.#G[Z]=new X}H.insert($,G,Q,J,W)}buildRegExpStr(){let G=Object.keys(this.#G).sort(si5).map((Q)=>{let J=this.#G[Q];return(typeof J.#Y==="number"?`(${Q})@${J.#Y}`:oi5.has(Q)?`\\${Q}`:Q)+J.buildRegExpStr()});if(typeof this.#X==="number")G.unshift(`#${this.#X}`);if(G.length===0)return"";if(G.length===1)return G[0];return"(?:"+G.join("|")+")"}};var iN0=D(()=>{qj=Symbol(),oi5=new Set(".\\+*[^]$()")});var as6=class{#X={varIndex:0};#Y=new ns6;insert(X,Y,G){let Q=[],J=[];for(let Z=0;;){let $=!1;if(X=X.replace(/\{[^}]+\}/g,(K)=>{let H=`@\\${Z}`;return J[Z]=[H,K],Z++,$=!0,H}),!$)break}let W=X.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let Z=J.length-1;Z>=0;Z--){let[$]=J[Z];for(let K=W.length-1;K>=0;K--)if(W[K].indexOf($)!==-1){W[K]=W[K].replace($,J[Z][1]);break}}return this.#Y.insert(W,Y,Q,this.#X,G),Q}buildRegExp(){let X=this.#Y.buildRegExpStr();if(X==="")return[/^$/,[],[]];let Y=0,G=[],Q=[];return X=X.replace(/#(\d+)|@(\d+)|\.\*\$/g,(J,W,Z)=>{if(W!==void 0)return G[++Y]=Number(W),"$()";if(Z!==void 0)return Q[Number(Z)]=++Y,"";return""}),[new RegExp(`^${X}`),G,Q]}};var ts6=D(()=>{iN0()});function os6(X){return rs6[X]??=new RegExp(X==="*"?"":`^${X.replace(/\/\*$|([.\\+*[^\]$()])/g,(Y,G)=>G?`\\${G}`:"(?:|/.*)")}$`)}function Xp5(){rs6=Object.create(null)}function Yp5(X){let Y=new as6,G=[];if(X.length===0)return ei5;let Q=X.map((H)=>[!/\*|\/:/.test(H[0]),...H]).sort(([H,U],[N,B])=>H?1:N?-1:U.length-B.length),J=Object.create(null);for(let H=0,U=-1,N=Q.length;H<N;H++){let[B,z,O]=Q[H];if(B)J[z]=[O.map(([E])=>[E,Object.create(null)]),VX1];else U++;let w;try{w=Y.insert(z,U,B)}catch(E){throw E===qj?new RA1(z):E}if(B)continue;G[U]=O.map(([E,P])=>{let q=Object.create(null);P-=1;for(;P>=0;P--){let[j,M]=w[P];q[j]=M}return[E,q]})}let[W,Z,$]=Y.buildRegExp();for(let H=0,U=G.length;H<U;H++)for(let N=0,B=G[H].length;N<B;N++){let z=G[H][N]?.[1];if(!z)continue;let O=Object.keys(z);for(let w=0,E=O.length;w<E;w++)z[O[w]]=$[z[O[w]]]}let K=[];for(let H in Z)K[H]=G[Z[H]];return[W,K,J]}function ma(X,Y){if(!X)return;for(let G of Object.keys(X).sort((Q,J)=>J.length-Q.length))if(os6(G).test(Y))return[...X[G]];return}var ei5,rs6,kA1=class{name="RegExpRouter";#X;#Y;constructor(){this.#X={[T7]:Object.create(null)},this.#Y={[T7]:Object.create(null)}}add(X,Y,G){let Q=this.#X,J=this.#Y;if(!Q||!J)throw Error(MA1);if(!Q[X])[Q,J].forEach(($)=>{$[X]=Object.create(null),Object.keys($[T7]).forEach((K)=>{$[X][K]=[...$[T7][K]]})});if(Y==="/*")Y="*";let W=(Y.match(/\/:/g)||[]).length;if(/\*$/.test(Y)){let $=os6(Y);if(X===T7)Object.keys(Q).forEach((K)=>{Q[K][Y]||=ma(Q[K],Y)||ma(Q[T7],Y)||[]});else Q[X][Y]||=ma(Q[X],Y)||ma(Q[T7],Y)||[];Object.keys(Q).forEach((K)=>{if(X===T7||X===K)Object.keys(Q[K]).forEach((H)=>{$.test(H)&&Q[K][H].push([G,W])})}),Object.keys(J).forEach((K)=>{if(X===T7||X===K)Object.keys(J[K]).forEach((H)=>$.test(H)&&J[K][H].push([G,W]))});return}let Z=TA1(Y)||[Y];for(let $=0,K=Z.length;$<K;$++){let H=Z[$];Object.keys(J).forEach((U)=>{if(X===T7||X===U)J[U][H]||=[...ma(Q[U],H)||ma(Q[T7],H)||[]],J[U][H].push([G,W-K+$+1])})}}match=SA1;buildAllMatchers(){let X=Object.create(null);return Object.keys(this.#Y).concat(Object.keys(this.#X)).forEach((Y)=>{X[Y]||=this.#G(Y)}),this.#X=this.#Y=void 0,Xp5(),X}#G(X){let Y=[],G=X===T7;if([this.#X,this.#Y].forEach((Q)=>{let J=Q[X]?Object.keys(Q[X]).map((W)=>[W,Q[X][W]]):[];if(J.length!==0)G||=!0,Y.push(...J);else if(X!==T7)Y.push(...Object.keys(Q[T7]).map((W)=>[W,Q[T7][W]]))}),!G)return null;else return Yp5(Y)}};var pN0=D(()=>{Pq();Eq();cN0();iN0();ts6();ei5=[/^$/,[],Object.create(null)],rs6=Object.create(null)});var Gp5=class{name="PreparedRegExpRouter";#X;#Y;constructor(X,Y){this.#X=X,this.#Y=Y}#G(X,Y){let G=this.#X[X];G[1].forEach((Q)=>Q&&Q.push(Y)),Object.values(G[2]).forEach((Q)=>Q[0].push(Y))}#Q(X,Y,G,Q,J){let W=this.#X[X];if(!J)W[2][Y][0].push([G,{}]);else Q.forEach((Z)=>{if(typeof Z==="number")W[1][Z].push([G,J]);else W[2][Z||Y][0].push([G,J])})}add(X,Y,G){if(!this.#X[X]){let J=this.#X[T7],W={};for(let Z in J[2])W[Z]=[J[2][Z][0].slice(),VX1];this.#X[X]=[J[0],J[1].map((Z)=>Array.isArray(Z)?Z.slice():0),W]}if(Y==="/*"||Y==="*"){let J=[G,{}];if(X===T7)for(let W in this.#X)this.#G(W,J);else this.#G(X,J);return}let Q=this.#Y[Y];if(!Q)throw Error(`Path ${Y} is not registered`);for(let[J,W]of Q)if(X===T7)for(let Z in this.#X)this.#Q(Z,Y,G,J,W);else this.#Q(X,Y,G,J,W)}buildAllMatchers(){return this.#X}match=SA1};var ss6=D(()=>{Pq();cN0();pN0()});var es6=D(()=>{pN0();ss6()});var nN0=class{name="SmartRouter";#X=[];#Y=[];constructor(X){this.#X=X.routers}add(X,Y,G){if(!this.#Y)throw Error(MA1);this.#Y.push([X,Y,G])}match(X,Y){if(!this.#Y)throw Error("Fatal error");let G=this.#X,Q=this.#Y,J=G.length,W=0,Z;for(;W<J;W++){let $=G[W];try{for(let K=0,H=Q.length;K<H;K++)$.add(...Q[K]);Z=$.match(X,Y)}catch(K){if(K instanceof RA1)continue;throw K}this.match=$.match.bind($),this.#X=[$],this.#Y=void 0;break}if(W===J)throw Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,Z}get activeRouter(){if(this.#Y||this.#X.length!==1)throw Error("No active router has been determined yet.");return this.#X[0]}};var Xe6=D(()=>{Pq()});var Ye6=D(()=>{Xe6()});var RX1,Qp5=(X)=>{for(let Y in X)return!0;return!1},Ge6=class X{#X;#Y;#G;#Q=0;#J=RX1;constructor(Y,G,Q){if(this.#Y=Q||Object.create(null),this.#X=[],Y&&G){let J=Object.create(null);J[Y]={handler:G,possibleKeys:[],score:0},this.#X=[J]}this.#G=[]}insert(Y,G,Q){this.#Q=++this.#Q;let J=this,W=ks6(G),Z=[];for(let $=0,K=W.length;$<K;$++){let H=W[$],U=W[$+1],N=vs6(H,U),B=Array.isArray(N)?N[0]:H;if(B in J.#Y){if(J=J.#Y[B],N)Z.push(N[1]);continue}if(J.#Y[B]=new X,N)J.#G.push(N),Z.push(N[1]);J=J.#Y[B]}return J.#X.push({[Y]:{handler:Q,possibleKeys:Z.filter(($,K,H)=>H.indexOf($)===K),score:this.#Q}}),J}#Z(Y,G,Q,J,W){for(let Z=0,$=G.#X.length;Z<$;Z++){let K=G.#X[Z],H=K[Q]||K[T7],U={};if(H!==void 0){if(H.params=Object.create(null),Y.push(H),J!==RX1||W&&W!==RX1)for(let N=0,B=H.possibleKeys.length;N<B;N++){let z=H.possibleKeys[N],O=U[H.score];H.params[z]=W?.[z]&&!O?W[z]:J[z]??W?.[z],U[H.score]=!0}}}}search(Y,G){let Q=[];this.#J=RX1;let W=[this],Z=gN0(G),$=[],K=Z.length,H=null;for(let U=0;U<K;U++){let N=Z[U],B=U===K-1,z=[];for(let w=0,E=W.length;w<E;w++){let P=W[w],q=P.#Y[N];if(q)if(q.#J=P.#J,B){if(q.#Y["*"])this.#Z(Q,q.#Y["*"],Y,P.#J);this.#Z(Q,q,Y,P.#J)}else z.push(q);for(let j=0,M=P.#G.length;j<M;j++){let V=P.#G[j],R=P.#J===RX1?{}:{...P.#J};if(V==="*"){let h=P.#Y["*"];if(h)this.#Z(Q,h,Y,P.#J),h.#J=R,z.push(h);continue}let[k,_,v]=V;if(!N&&!(v instanceof RegExp))continue;let y=P.#Y[k];if(v instanceof RegExp){if(H===null){H=Array(K);let p=G[0]==="/"?1:0;for(let f=0;f<K;f++)H[f]=p,p+=Z[f].length+1}let h=G.substring(H[U]),i=v.exec(h);if(i){if(R[_]=i[0],this.#Z(Q,y,Y,P.#J,R),Qp5(y.#Y)){y.#J=R;let p=i[0].match(/\//)?.length??0;($[p]||=[]).push(y)}continue}}if(v===!0||v.test(N))if(R[_]=N,B){if(this.#Z(Q,y,Y,R,P.#J),y.#Y["*"])this.#Z(Q,y.#Y["*"],Y,R,P.#J)}else y.#J=R,z.push(y)}}let O=$.shift();W=O?z.concat(O):z}if(Q.length>1)Q.sort((U,N)=>{return U.score-N.score});return[Q.map(({handler:U,params:N})=>[U,N])]}};var Qe6=D(()=>{Pq();Eq();RX1=Object.create(null)});var aN0=class{name="TrieRouter";#X;constructor(){this.#X=new Ge6}add(X,Y,G){let Q=TA1(Y);if(Q){for(let J=0,W=Q.length;J<W;J++)this.#X.insert(X,Q[J],G);return}this.#X.insert(X,Y,G)}match(X,Y){return this.#X.search(X,Y)}};var Je6=D(()=>{Eq();Qe6()});var Ze6=D(()=>{Je6()});var R5;var We6=D(()=>{ps6();es6();Ye6();Ze6();R5=class extends is6{constructor(X={}){super(X);this.router=X.router??new nN0({routers:[new kA1,new aN0]})}}});var JQ=D(()=>{We6()});var Ke6,Jp5,$e6=(X)=>{let Y=0,G=X.length;while(Y<G){let Q=X.charCodeAt(Y);if(Q!==32&&Q!==9)break;Y++}while(G>Y){let Q=X.charCodeAt(G-1);if(Q!==32&&Q!==9)break;G--}return Y===0&&G===X.length?X:X.slice(Y,G)},tN0=(X,Y)=>{if(Y&&X.indexOf(Y)===-1)return{};let G=X.split(";"),Q={};for(let J of G){let W=J.indexOf("=");if(W===-1)continue;let Z=$e6(J.substring(0,W));if(Y&&Y!==Z||!Ke6.test(Z))continue;let $=$e6(J.substring(W+1));if($.startsWith('"')&&$.endsWith('"'))$=$.slice(1,-1);if(Jp5.test($)){if(Q[Z]=$.indexOf("%")!==-1?la($,AX1):$,Y)break}}return Q},Zp5=(X,Y,G={})=>{if(!Ke6.test(X))throw Error("Invalid cookie name");let Q=`${X}=${Y}`;if(X.startsWith("__Secure-")&&!G.secure)throw Error("__Secure- Cookie must have Secure attributes");if(X.startsWith("__Host-")){if(!G.secure)throw Error("__Host- Cookie must have Secure attributes");if(G.path!=="/")throw Error('__Host- Cookie must have Path attributes with "/"');if(G.domain)throw Error("__Host- Cookie must not have Domain attributes")}for(let J of["domain","path"])if(G[J]&&/[;\r\n]/.test(G[J]))throw Error(`${J} must not contain ";", "\\r", or "\\n"`);if(G&&typeof G.maxAge==="number"&&G.maxAge>=0){if(G.maxAge>34560000)throw Error("Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.");Q+=`; Max-Age=${G.maxAge|0}`}if(G.domain&&G.prefix!=="host")Q+=`; Domain=${G.domain}`;if(G.path)Q+=`; Path=${G.path}`;if(G.expires){if(G.expires.getTime()-Date.now()>34560000000)throw Error("Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.");Q+=`; Expires=${G.expires.toUTCString()}`}if(G.httpOnly)Q+="; HttpOnly";if(G.secure)Q+="; Secure";if(G.sameSite)Q+=`; SameSite=${G.sameSite.charAt(0).toUpperCase()+G.sameSite.slice(1)}`;if(G.priority)Q+=`; Priority=${G.priority.charAt(0).toUpperCase()+G.priority.slice(1)}`;if(G.partitioned){if(!G.secure)throw Error("Partitioned Cookie must have Secure attributes");Q+="; Partitioned"}return Q},vA1=(X,Y,G)=>{return Y=encodeURIComponent(Y),Zp5(X,Y,G)};var He6=D(()=>{Eq();Ke6=/^[\w!#$%&'*.^`|~+-]+$/,Jp5=/^[ !#-:<-[\]-~]*$/});var _A1=(X,Y,G)=>{let Q=X.req.raw.headers.get("Cookie");if(typeof Y==="string"){if(!Q)return;let W=Y;if(G==="secure")W="__Secure-"+Y;else if(G==="host")W="__Host-"+Y;return tN0(Q,W)[W]}if(!Q)return{};return tN0(Q)},Wp5=(X,Y,G)=>{let Q;if(G?.prefix==="secure")Q=vA1("__Secure-"+X,Y,{path:"/",...G,secure:!0});else if(G?.prefix==="host")Q=vA1("__Host-"+X,Y,{...G,path:"/",secure:!0,domain:void 0});else Q=vA1(X,Y,{path:"/",...G});return Q},rN0=(X,Y,G,Q)=>{let J=Wp5(Y,G,Q);X.header("Set-Cookie",J,{append:!0})};var oN0=D(()=>{He6()});var Fe6=(X)=>{let G={...{origin:"*",allowMethods:["GET","HEAD","PUT","POST","DELETE","PATCH"],allowHeaders:[],exposeHeaders:[]},...X},Q=((W)=>{if(typeof W==="string")if(W==="*"){if(G.credentials)return(Z)=>Z||null;return()=>W}else return(Z)=>W===Z?Z:null;else if(typeof W==="function")return W;else return(Z)=>W.includes(Z)?Z:null})(G.origin),J=((W)=>{if(typeof W==="function")return W;else if(Array.isArray(W))return()=>W;else return()=>[]})(G.allowMethods);return async function(Z,$){function K(U,N){Z.res.headers.set(U,N)}let H=await Q(Z.req.header("origin")||"",Z);if(H)K("Access-Control-Allow-Origin",H);if(G.credentials)K("Access-Control-Allow-Credentials","true");if(G.exposeHeaders?.length)K("Access-Control-Expose-Headers",G.exposeHeaders.join(","));if(Z.req.method==="OPTIONS"){if(G.origin!=="*"||G.credentials)K("Vary","Origin");if(G.maxAge!=null)K("Access-Control-Max-Age",G.maxAge.toString());let U=await J(Z.req.header("origin")||"",Z);if(U.length)K("Access-Control-Allow-Methods",U.join(","));let N=G.allowHeaders;if(!N?.length){let B=Z.req.header("Access-Control-Request-Headers");if(B)N=B.split(/\s*,\s*/)}if(N?.length)K("Access-Control-Allow-Headers",N.join(",")),Z.res.headers.append("Vary","Access-Control-Request-Headers");return Z.res.headers.delete("Content-Length"),Z.res.headers.delete("Content-Type"),new Response(null,{headers:Z.res.headers,status:204,statusText:"No Content"})}if(await $(),G.origin!=="*"||G.credentials)Z.header("Vary","Origin",{append:!0})}};var Ue6=()=>{};var Ne6=()=>{try{return performance.now()}catch{}return Date.now()},sN0=(X)=>{let Y={total:!0,enabled:!0,totalDescription:"Total Response Time",autoEnd:!0,crossOrigin:!1,...X};return async function(Q,J){let W=[],Z=new Map;if(Q.get("metric"))return await J();if(Q.set("metric",{headers:W,timers:Z}),Y.total)zH(Q,"total",Y.totalDescription);if(await J(),Y.total)h$(Q,"total");if(Y.autoEnd)Z.forEach((K,H)=>h$(Q,H));if(typeof Y.enabled==="function"?Y.enabled(Q):Y.enabled){Q.res.headers.append("Server-Timing",W.join(","));let K=typeof Y.crossOrigin==="function"?Y.crossOrigin(Q):Y.crossOrigin;if(K)Q.res.headers.append("Timing-Allow-Origin",typeof K==="string"?K:"*")}}},Be6=(X,Y,G,Q,J)=>{let W=X.get("metric");if(!W){console.warn("Metrics not initialized! Please add the `timing()` middleware to this route!");return}if(typeof G==="number"){let Z=G.toFixed(J||1),$=Q?`${Y};dur=${Z};desc="${Q}"`:`${Y};dur=${Z}`;W.headers.push($)}else{let Z=G?`${Y};desc="${G}"`:`${Y}`;W.headers.push(Z)}},zH=(X,Y,G)=>{let Q=X.get("metric");if(!Q){console.warn("Metrics not initialized! Please add the `timing()` middleware to this route!");return}Q.timers.set(Y,{description:G,start:Ne6()})},h$=(X,Y,G)=>{let Q=X.get("metric");if(!Q){console.warn("Metrics not initialized! Please add the `timing()` middleware to this route!");return}let J=Q.timers.get(Y);if(!J){console.warn(`Timer "${Y}" does not exist!`);return}let{description:W,start:Z}=J,$=Ne6()-Z;Be6(X,Y,$,W,G),Q.timers.delete(Y)};var ze6=D(()=>{jA1()});var eN0=D(()=>{ze6()});function SX1(){let X={Organizations:[],Connections:[],"Virtual MCPs":[],Threads:[],Monitoring:[],Users:[],"API Keys":[],"Event Bus":[],Tags:[],"AI Providers":[],Automations:[],"Object Storage":[],Registry:[],GitHub:[],VM:[]};for(let Y of XB0)X[Y.category]?.push(Y);return X}var XB0;var YB0=D(()=>{XB0=[{name:"ORGANIZATION_CREATE",description:"Create a new organization",category:"Organizations"},{name:"ORGANIZATION_LIST",description:"List organizations",category:"Organizations"},{name:"ORGANIZATION_GET",description:"View organization details",category:"Organizations"},{name:"ORGANIZATION_UPDATE",description:"Update organization",category:"Organizations"},{name:"ORGANIZATION_DELETE",description:"Delete organization",category:"Organizations",dangerous:!0},{name:"ORGANIZATION_SETTINGS_GET",description:"View organization settings",category:"Organizations"},{name:"ORGANIZATION_SETTINGS_UPDATE",description:"Update organization settings",category:"Organizations"},{name:"BRAND_CONTEXT_LIST",description:"List brand contexts",category:"Organizations"},{name:"BRAND_CONTEXT_GET",description:"View brand context",category:"Organizations"},{name:"BRAND_CONTEXT_CREATE",description:"Create brand context",category:"Organizations"},{name:"BRAND_CONTEXT_UPDATE",description:"Update brand context",category:"Organizations"},{name:"BRAND_CONTEXT_DELETE",description:"Delete brand context",category:"Organizations",dangerous:!0},{name:"BRAND_CONTEXT_EXTRACT",description:"Extract brand context from website",category:"Organizations"},{name:"BRAND_GET",description:"Get brand (binding)",category:"Organizations"},{name:"BRAND_LIST",description:"List brands (binding)",category:"Organizations"},{name:"ORGANIZATION_DOMAIN_GET",description:"Get organization domain claim",category:"Organizations"},{name:"ORGANIZATION_DOMAIN_SET",description:"Set organization domain claim",category:"Organizations"},{name:"ORGANIZATION_DOMAIN_UPDATE",description:"Update organization domain settings",category:"Organizations"},{name:"ORGANIZATION_DOMAIN_CLEAR",description:"Clear organization domain claim",category:"Organizations"},{name:"ORGANIZATION_MEMBER_ADD",description:"Add members",category:"Organizations"},{name:"ORGANIZATION_MEMBER_REMOVE",description:"Remove members",category:"Organizations",dangerous:!0},{name:"ORGANIZATION_MEMBER_LIST",description:"List members",category:"Organizations"},{name:"ORGANIZATION_MEMBER_UPDATE_ROLE",description:"Update member roles",category:"Organizations"},{name:"COLLECTION_CONNECTIONS_CREATE",description:"Create connections",category:"Connections"},{name:"COLLECTION_CONNECTIONS_LIST",description:"List connections",category:"Connections"},{name:"COLLECTION_CONNECTIONS_GET",description:"View connection details",category:"Connections"},{name:"COLLECTION_CONNECTIONS_UPDATE",description:"Update connections",category:"Connections"},{name:"COLLECTION_CONNECTIONS_DELETE",description:"Delete connections",category:"Connections",dangerous:!0},{name:"CONNECTION_TEST",description:"Test connections",category:"Connections"},{name:"DATABASES_RUN_SQL",description:"Run SQL queries",category:"Connections",dangerous:!0},{name:"COLLECTION_VIRTUAL_MCP_CREATE",description:"Create virtual MCPs",category:"Virtual MCPs"},{name:"COLLECTION_VIRTUAL_MCP_LIST",description:"List virtual MCPs",category:"Virtual MCPs"},{name:"COLLECTION_VIRTUAL_MCP_GET",description:"View virtual MCP details",category:"Virtual MCPs"},{name:"COLLECTION_VIRTUAL_MCP_UPDATE",description:"Update virtual MCPs",category:"Virtual MCPs"},{name:"COLLECTION_VIRTUAL_MCP_DELETE",description:"Delete virtual MCPs",category:"Virtual MCPs",dangerous:!0},{name:"MONITORING_LOG_GET",description:"View monitoring log details",category:"Monitoring"},{name:"MONITORING_LOGS_LIST",description:"List monitoring logs",category:"Monitoring"},{name:"MONITORING_STATS",description:"View monitoring statistics",category:"Monitoring"},{name:"API_KEY_CREATE",description:"Create API key",category:"API Keys"},{name:"API_KEY_LIST",description:"List API keys",category:"API Keys"},{name:"API_KEY_UPDATE",description:"Update API key",category:"API Keys"},{name:"API_KEY_DELETE",description:"Delete API key",category:"API Keys",dangerous:!0},{name:"EVENT_PUBLISH",description:"Publish events",category:"Event Bus"},{name:"EVENT_SUBSCRIBE",description:"Subscribe to events",category:"Event Bus"},{name:"EVENT_UNSUBSCRIBE",description:"Unsubscribe from events",category:"Event Bus"},{name:"EVENT_CANCEL",description:"Cancel recurring events",category:"Event Bus"},{name:"EVENT_ACK",description:"Acknowledge event delivery",category:"Event Bus"},{name:"EVENT_SUBSCRIPTION_LIST",description:"List event subscriptions",category:"Event Bus"},{name:"EVENT_SYNC_SUBSCRIPTIONS",description:"Sync subscriptions to desired state",category:"Event Bus"},{name:"USER_GET",description:"Get a user by id",category:"Users"},{name:"COLLECTION_THREADS_CREATE",description:"Create threads",category:"Threads"},{name:"COLLECTION_THREADS_LIST",description:"List threads",category:"Threads"},{name:"COLLECTION_THREADS_GET",description:"View thread details",category:"Threads"},{name:"COLLECTION_THREADS_UPDATE",description:"Update threads",category:"Threads"},{name:"COLLECTION_THREADS_DELETE",description:"Delete threads",category:"Threads",dangerous:!0},{name:"COLLECTION_THREAD_MESSAGES_LIST",description:"List thread messages",category:"Threads"},{name:"TAGS_LIST",description:"List organization tags",category:"Tags"},{name:"TAGS_CREATE",description:"Create organization tag",category:"Tags"},{name:"TAGS_DELETE",description:"Delete organization tag",category:"Tags",dangerous:!0},{name:"MEMBER_TAGS_GET",description:"Get member tags",category:"Tags"},{name:"MEMBER_TAGS_SET",description:"Set member tags",category:"Tags"},{name:"AUTOMATION_CREATE",description:"Create automation",category:"Automations"},{name:"AUTOMATION_GET",description:"View automation details",category:"Automations"},{name:"AUTOMATION_LIST",description:"List automations",category:"Automations"},{name:"AUTOMATION_UPDATE",description:"Update automation",category:"Automations"},{name:"AUTOMATION_DELETE",description:"Delete automation",category:"Automations",dangerous:!0},{name:"AUTOMATION_TRIGGER_ADD",description:"Add trigger to automation",category:"Automations"},{name:"AUTOMATION_TRIGGER_REMOVE",description:"Remove trigger from automation",category:"Automations"},{name:"AUTOMATION_RUN",description:"Manually trigger an automation run",category:"Automations"},{name:"VIRTUAL_MCP_PLUGIN_CONFIG_GET",description:"View virtual MCP plugin configuration",category:"Virtual MCPs"},{name:"VIRTUAL_MCP_PLUGIN_CONFIG_UPDATE",description:"Update virtual MCP plugin configuration",category:"Virtual MCPs"},{name:"VIRTUAL_MCP_PINNED_VIEWS_UPDATE",description:"Update virtual MCP pinned sidebar views",category:"Virtual MCPs"},{name:"AI_PROVIDERS_LIST",description:"List available AI providers",category:"AI Providers"},{name:"AI_PROVIDERS_LIST_MODELS",description:"List AI provider models",category:"AI Providers"},{name:"AI_PROVIDERS_ACTIVE",description:"List active AI providers",category:"AI Providers"},{name:"AI_PROVIDER_KEY_CREATE",description:"Store AI provider API key",category:"AI Providers"},{name:"AI_PROVIDER_KEY_LIST",description:"List AI provider API keys",category:"AI Providers"},{name:"AI_PROVIDER_KEY_DELETE",description:"Delete AI provider API key",category:"AI Providers",dangerous:!0},{name:"AI_PROVIDER_OAUTH_URL",description:"Get OAuth URL for provider",category:"AI Providers"},{name:"AI_PROVIDER_OAUTH_EXCHANGE",description:"Exchange OAuth code for API key",category:"AI Providers"},{name:"AI_PROVIDER_PROVISION_KEY",description:"Auto-provision API key for a provider",category:"AI Providers"},{name:"AI_PROVIDER_TOPUP_URL",description:"Get checkout URL to top up provider credits",category:"AI Providers"},{name:"AI_PROVIDER_CREDITS",description:"Get current credit balance for a provider",category:"AI Providers"},{name:"AI_PROVIDER_CLI_ACTIVATE",description:"Activate Claude Code via local CLI",category:"AI Providers"},{name:"LIST_OBJECTS",description:"List objects in storage",category:"Object Storage"},{name:"GET_OBJECT_METADATA",description:"Get object metadata",category:"Object Storage"},{name:"GET_PRESIGNED_URL",description:"Generate download URL",category:"Object Storage"},{name:"PUT_PRESIGNED_URL",description:"Generate upload URL",category:"Object Storage"},{name:"DELETE_OBJECT",description:"Delete object",category:"Object Storage",dangerous:!0},{name:"DELETE_OBJECTS",description:"Delete multiple objects",category:"Object Storage",dangerous:!0},{name:"COLLECTION_REGISTRY_APP_LIST",description:"List registry apps",category:"Registry"},{name:"COLLECTION_REGISTRY_APP_GET",description:"Get registry app details",category:"Registry"},{name:"COLLECTION_REGISTRY_APP_VERSIONS",description:"List registry app versions",category:"Registry"},{name:"COLLECTION_REGISTRY_APP_FILTERS",description:"Get registry app filters",category:"Registry"},{name:"REGISTRY_ITEM_LIST",description:"List private registry items",category:"Registry"},{name:"REGISTRY_ITEM_SEARCH",description:"Search registry items",category:"Registry"},{name:"REGISTRY_ITEM_GET",description:"Get registry item details",category:"Registry"},{name:"REGISTRY_ITEM_VERSIONS",description:"List registry item versions",category:"Registry"},{name:"REGISTRY_ITEM_CREATE",description:"Create registry item",category:"Registry"},{name:"REGISTRY_ITEM_BULK_CREATE",description:"Bulk create registry items",category:"Registry"},{name:"REGISTRY_ITEM_UPDATE",description:"Update registry item",category:"Registry"},{name:"REGISTRY_ITEM_DELETE",description:"Delete registry item",category:"Registry",dangerous:!0},{name:"REGISTRY_ITEM_FILTERS",description:"Get registry item filters",category:"Registry"},{name:"REGISTRY_DISCOVER_TOOLS",description:"Discover tools from MCP server",category:"Registry"},{name:"REGISTRY_AI_GENERATE",description:"AI-generate registry content",category:"Registry"},{name:"REGISTRY_PUBLISH_REQUEST_LIST",description:"List publish requests",category:"Registry"},{name:"REGISTRY_PUBLISH_REQUEST_REVIEW",description:"Review publish request",category:"Registry"},{name:"REGISTRY_PUBLISH_REQUEST_COUNT",description:"Count pending publish requests",category:"Registry"},{name:"REGISTRY_PUBLISH_REQUEST_DELETE",description:"Delete publish request",category:"Registry",dangerous:!0},{name:"REGISTRY_PUBLISH_API_KEY_GENERATE",description:"Generate publish API key",category:"Registry"},{name:"REGISTRY_PUBLISH_API_KEY_LIST",description:"List publish API keys",category:"Registry"},{name:"REGISTRY_PUBLISH_API_KEY_REVOKE",description:"Revoke publish API key",category:"Registry",dangerous:!0},{name:"REGISTRY_MONITOR_RUN_START",description:"Start monitor run",category:"Registry"},{name:"REGISTRY_MONITOR_RUN_LIST",description:"List monitor runs",category:"Registry"},{name:"REGISTRY_MONITOR_RUN_GET",description:"Get monitor run details",category:"Registry"},{name:"REGISTRY_MONITOR_RUN_CANCEL",description:"Cancel monitor run",category:"Registry"},{name:"REGISTRY_MONITOR_RESULT_LIST",description:"List monitor results",category:"Registry"},{name:"REGISTRY_MONITOR_CONNECTION_LIST",description:"List monitor connections",category:"Registry"},{name:"REGISTRY_MONITOR_CONNECTION_SYNC",description:"Sync monitor connections",category:"Registry"},{name:"REGISTRY_MONITOR_CONNECTION_UPDATE_AUTH",description:"Update monitor connection auth",category:"Registry"},{name:"REGISTRY_MONITOR_SCHEDULE_SET",description:"Set monitor schedule",category:"Registry"},{name:"REGISTRY_MONITOR_SCHEDULE_CANCEL",description:"Cancel monitor schedule",category:"Registry"},{name:"VM_START",description:"Start a Freestyle VM with dev server preview",category:"VM"},{name:"VM_DELETE",description:"Stop and delete a Freestyle VM",category:"VM"},{name:"GITHUB_LIST_USER_ORGS",description:"List GitHub user's personal account and organizations",category:"GitHub"}]});var Oe6=D(()=>{ni();dz1()});function De6(){return Kp5.parse(process.env)}var GB0=(X)=>F.enum(["true","false","1","0"]).optional().transform((Y)=>Y===void 0?X:Y==="true"||Y==="1"),$p5=(X)=>F.string().optional().transform((Y)=>Y?Y.split(",").map((G)=>G.trim()):X),Kp5;var we6=D(()=>{H0();Kp5=F.object({AUTH_EMAIL_PASSWORD_ENABLED:GB0(!0),AUTH_GOOGLE_CLIENT_ID:F.string().optional(),AUTH_GOOGLE_CLIENT_SECRET:F.string().optional(),AUTH_GITHUB_CLIENT_ID:F.string().optional(),AUTH_GITHUB_CLIENT_SECRET:F.string().optional(),AUTH_RESEND_API_KEY:F.string().optional(),AUTH_RESEND_FROM_EMAIL:F.string().optional(),AUTH_SENDGRID_API_KEY:F.string().optional(),AUTH_SENDGRID_FROM_EMAIL:F.string().optional(),AUTH_INVITE_EMAIL_PROVIDER:F.enum(["resend","sendgrid"]).optional(),AUTH_RESET_PASSWORD_EMAIL_PROVIDER:F.enum(["resend","sendgrid"]).optional(),AUTH_MAGIC_LINK_ENABLED:GB0(!1),AUTH_MAGIC_LINK_EMAIL_PROVIDER:F.enum(["resend","sendgrid"]).optional(),AUTH_EMAIL_OTP_ENABLED:GB0(!1),AUTH_EMAIL_OTP_EMAIL_PROVIDER:F.enum(["resend","sendgrid"]).optional(),AUTH_EMAIL_OTP_LENGTH:F.coerce.number().optional(),AUTH_EMAIL_OTP_EXPIRES_IN:F.coerce.number().optional(),AUTH_SSO_DOMAIN:F.string().optional(),AUTH_SSO_MS_TENANT_ID:F.string().optional(),AUTH_SSO_MS_CLIENT_ID:F.string().optional(),AUTH_SSO_MS_CLIENT_SECRET:F.string().optional(),AUTH_SSO_SCOPES:$p5(["openid","email","profile"])}).transform((X)=>{let Y={};if(X.AUTH_GOOGLE_CLIENT_ID)Y.google={clientId:X.AUTH_GOOGLE_CLIENT_ID,clientSecret:X.AUTH_GOOGLE_CLIENT_SECRET??""};if(X.AUTH_GITHUB_CLIENT_ID)Y.github={clientId:X.AUTH_GITHUB_CLIENT_ID,clientSecret:X.AUTH_GITHUB_CLIENT_SECRET??""};let G=[];if(X.AUTH_RESEND_API_KEY)G.push({id:"resend",provider:"resend",config:{apiKey:X.AUTH_RESEND_API_KEY,fromEmail:X.AUTH_RESEND_FROM_EMAIL??"noreply@example.com"}});if(X.AUTH_SENDGRID_API_KEY)G.push({id:"sendgrid",provider:"sendgrid",config:{apiKey:X.AUTH_SENDGRID_API_KEY,fromEmail:X.AUTH_SENDGRID_FROM_EMAIL??"noreply@example.com"}});let Q=G[0]?.id,J;if(X.AUTH_SSO_MS_CLIENT_ID&&X.AUTH_SSO_DOMAIN)J={providerId:"microsoft",domain:X.AUTH_SSO_DOMAIN,MS_TENANT_ID:X.AUTH_SSO_MS_TENANT_ID??"",MS_CLIENT_ID:X.AUTH_SSO_MS_CLIENT_ID,MS_CLIENT_SECRET:X.AUTH_SSO_MS_CLIENT_SECRET??"",scopes:X.AUTH_SSO_SCOPES};let W;if(X.AUTH_MAGIC_LINK_ENABLED)W={enabled:!0,emailProviderId:X.AUTH_MAGIC_LINK_EMAIL_PROVIDER??Q??""};let Z;if(X.AUTH_EMAIL_OTP_ENABLED)Z={enabled:!0,emailProviderId:X.AUTH_EMAIL_OTP_EMAIL_PROVIDER??Q??"",...X.AUTH_EMAIL_OTP_LENGTH!==void 0&&{otpLength:X.AUTH_EMAIL_OTP_LENGTH},...X.AUTH_EMAIL_OTP_EXPIRES_IN!==void 0&&{expiresIn:X.AUTH_EMAIL_OTP_EXPIRES_IN}};return{emailAndPassword:{enabled:X.AUTH_EMAIL_PASSWORD_ENABLED},socialProviders:Object.keys(Y).length>0?Y:void 0,emailProviders:G.length>0?G:void 0,inviteEmailProviderId:X.AUTH_INVITE_EMAIL_PROVIDER,resetPasswordEmailProviderId:X.AUTH_RESET_PASSWORD_EMAIL_PROVIDER,ssoConfig:J,magicLinkConfig:W,emailOtpConfig:Z}})});var fA1;var Le6=D(()=>{fA1={enabled:!0,batchSize:250,flushIntervalMs:300,maxQueueSize:1e4,redactor:"regex"}});import{existsSync as Hp5,readFileSync as Fp5}from"fs";function Up5(){let X=De6(),Y=v6().configPath;if(!Hp5(Y))return{auth:X,monitoring:fA1};try{let G=JSON.parse(Fp5(Y,"utf-8"));if(G.auth)console.warn("[config] DEPRECATION: 'auth' key found in config.json. Auth is now configured via AUTH_* environment variables. The 'auth' key will be ignored.");return{auth:X,monitoring:G.monitoring??fA1,theme:G.theme,logo:G.logo,autoCreateOrganizationOnSignup:G.autoCreateOrganizationOnSignup}}catch{return{auth:X,monitoring:fA1}}}function Aj(){if(!QB0)QB0=Up5();return QB0}function Ee6(){return Aj().theme}var QB0=null;var JB0=D(()=>{we6();Le6();m9()});import{dirname as Np5,posix as Bp5,sep as zp5}from"path";function qe6(){let X=Op5();return async(Y)=>{for(let G of Y)G.module=X(G.filename);return Y}}function Op5(X=process.argv[1]?Np5(process.argv[1]):process.cwd(),Y=zp5==="\\"){let G=Y?Pe6(X):X;return(Q)=>{if(!Q)return;let J=Y?Pe6(Q):Q,{dir:W,base:Z,ext:$}=Bp5.parse(J);if($===".js"||$===".mjs"||$===".cjs")Z=Z.slice(0,-1*$.length);let K=decodeURIComponent(Z);if(!W)W=".";let H=W.lastIndexOf("/node_modules");if(H>-1)return`${W.slice(H+14).replace(/\//g,".")}:${K}`;if(W.startsWith(G)){let U=W.slice(G.length+1).replace(/\//g,".");return U?`${U}:${K}`:K}return K}}function Pe6(X){return X.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var Ae6=()=>{};function Dp5(X,Y,G){return{key:X,enabled:typeof Y=="string"?!0:Y,variant:typeof Y=="string"?Y:void 0,reason:void 0,metadata:{id:void 0,version:void 0,payload:G?JSON.stringify(G):void 0,description:void 0}}}var ZB0=(X)=>{if("flags"in X){let Y=Te6(X.flags),G=Ie6(X.flags);return{...X,featureFlags:Y,featureFlagPayloads:G}}{let Y=X.featureFlags??{},G=Object.fromEntries(Object.entries(X.featureFlagPayloads||{}).map(([J,W])=>[J,WB0(W)])),Q=Object.fromEntries(Object.entries(Y).map(([J,W])=>[J,Dp5(J,W,G[J])]));return{...X,featureFlags:Y,featureFlagPayloads:G,flags:Q}}},Te6=(X)=>Object.fromEntries(Object.entries(X??{}).map(([Y,G])=>[Y,CX1(G)]).filter(([,Y])=>Y!==void 0)),Ie6=(X)=>{let Y=X??{};return Object.fromEntries(Object.keys(Y).filter((G)=>{let Q=Y[G];return Q.enabled&&Q.metadata&&Q.metadata.payload!==void 0}).map((G)=>{let Q=Y[G].metadata?.payload;return[G,Q?WB0(Q):void 0]}))},CX1=(X)=>X===void 0?void 0:X.variant??X.enabled,WB0=(X)=>{if(typeof X!="string")return X;try{return JSON.parse(X)}catch{return X}};var bA1=()=>{};function Ve6(){return"CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&typeof Response.prototype.blob=="function"}async function yA1(X,Y=!0,G){try{let Q=new CompressionStream("gzip"),J=Q.writable.getWriter(),W=J.write(new TextEncoder().encode(X)).then(()=>J.close()).catch(async(K)=>{try{await J.abort(K)}catch{}throw K}),Z=new Response(Q.readable).blob(),[$]=await Promise.all([Z,W]);return $}catch(Q){if(G?.rethrow)throw Q;if(Y)console.error("Failed to gzip compress data",Q);return null}}var $B0=()=>{};var wp5,je6=function(X,Y=[]){if(!X)return!1;let G=X.toLowerCase();return wp5.concat(Y).some((Q)=>{let J=Q.toLowerCase();return G.indexOf(J)!==-1})};var Me6=D(()=>{wp5=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterest","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"]});var pJ;var Tj=D(()=>{pJ=function(X){return X.AnonymousId="anonymous_id",X.DistinctId="distinct_id",X.Props="props",X.EnablePersonProcessing="enable_person_processing",X.PersonMode="person_mode",X.FeatureFlagDetails="feature_flag_details",X.FeatureFlags="feature_flags",X.FeatureFlagPayloads="feature_flag_payloads",X.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",X.BootstrapFeatureFlags="bootstrap_feature_flags",X.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",X.OverrideFeatureFlags="override_feature_flags",X.Queue="queue",X.LogsQueue="logs_queue",X.OptedOut="opted_out",X.SessionId="session_id",X.SessionStartTimestamp="session_start_timestamp",X.SessionLastTimestamp="session_timestamp",X.PersonProperties="person_properties",X.GroupProperties="group_properties",X.InstalledAppBuild="installed_app_build",X.InstalledAppVersion="installed_app_version",X.SessionReplay="session_replay",X.SurveyLastSeenDate="survey_last_seen_date",X.SurveysSeen="surveys_seen",X.Surveys="surveys",X.RemoteConfig="remote_config",X.FlagsEndpointWasHit="flags_endpoint_was_hit",X.DeviceId="device_id",X}({})});var xA1=()=>{};function gA1(X){return X===null||typeof X!="object"}function Ij(X,Y){return Object.prototype.toString.call(X)===`[object ${Y}]`}function Ce6(X){return Ij(X,"ErrorEvent")}function ca(X){return typeof Event<"u"&&Pp5(X,Event)}function ke6(X){return Ij(X,"Object")}function Pp5(X,Y){try{return X instanceof Y}catch{return!1}}var Ep5,Re6,qlX,KB0,hA1,kX1=(X)=>X===Object(X)&&!hA1(X),da=(X)=>X===void 0,qq=(X)=>KB0.call(X)=="[object String]",Se6=(X)=>qq(X)&&X.trim().length===0,vX1=(X)=>KB0.call(X)=="[object Number]"&&X===X,HB0=(X)=>X instanceof Error;var _X1=D(()=>{Tj();xA1();Ep5=Array.isArray,Re6=Object.prototype,qlX=Re6.hasOwnProperty,KB0=Re6.toString,hA1=Ep5||function(X){return KB0.call(X)==="[object Array]"}});function fX1(X,Y,G,Q,J){if(Y>G)Q.warn("min cannot be greater than max."),Y=G;if(vX1(X))if(X>G)return Q.warn(" cannot be greater than max: "+G+". Using max value instead."),G;else{if(!(X<Y))return X;return Q.warn(" cannot be less than min: "+Y+". Using min value instead."),Y}return Q.warn(" must be a number. using max or fallback. max: "+G+", fallback: "+J),fX1(J||G,Y,G,Q)}var FB0=D(()=>{_X1()});class UB0{constructor(X){this._buckets={},this._onBucketRateLimited=X._onBucketRateLimited,this._bucketSize=fX1(X.bucketSize,0,100,X._logger),this._refillRate=fX1(X.refillRate,0,this._bucketSize,X._logger),this._refillInterval=fX1(X.refillInterval,0,qp5,X._logger)}_applyRefill(X,Y){let G=Y-X.lastAccess,Q=Math.floor(G/this._refillInterval);if(Q>0){let J=Q*this._refillRate;X.tokens=Math.min(X.tokens+J,this._bucketSize),X.lastAccess=X.lastAccess+Q*this._refillInterval}}consumeRateLimit(X){let Y=Date.now(),G=String(X),Q=this._buckets[G];if(Q)this._applyRefill(Q,Y);else Q={tokens:this._bucketSize,lastAccess:Y},this._buckets[G]=Q;if(Q.tokens===0)return!0;if(Q.tokens--,Q.tokens===0)this._onBucketRateLimited?.(X);return Q.tokens===0}stop(){this._buckets={}}}var qp5=86400000;var ve6=D(()=>{FB0()});class Vj{constructor(X){this.bytes=X}static ofInner(X){if(X.length===16)return new Vj(X);throw TypeError("not 128-bit length")}static fromFieldsV7(X,Y,G,Q){if(!Number.isInteger(X)||!Number.isInteger(Y)||!Number.isInteger(G)||!Number.isInteger(Q)||X<0||Y<0||G<0||Q<0||X>281474976710655||Y>4095||G>1073741823||Q>4294967295)throw RangeError("invalid field value");let J=new Uint8Array(16);return J[0]=X/1099511627776,J[1]=X/4294967296,J[2]=X/16777216,J[3]=X/65536,J[4]=X/256,J[5]=X,J[6]=112|Y>>>8,J[7]=Y,J[8]=128|G>>>24,J[9]=G>>>16,J[10]=G>>>8,J[11]=G,J[12]=Q>>>24,J[13]=Q>>>16,J[14]=Q>>>8,J[15]=Q,new Vj(J)}static parse(X){let Y;switch(X.length){case 32:Y=/^[0-9a-f]{32}$/i.exec(X)?.[0];break;case 36:Y=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(X)?.slice(1,6).join("");break;case 38:Y=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(X)?.slice(1,6).join("");break;case 45:Y=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(X)?.slice(1,6).join("");break;default:break}if(Y){let G=new Uint8Array(16);for(let Q=0;Q<16;Q+=4){let J=parseInt(Y.substring(2*Q,2*Q+8),16);G[Q+0]=J>>>24,G[Q+1]=J>>>16,G[Q+2]=J>>>8,G[Q+3]=J}return new Vj(G)}throw SyntaxError("could not parse UUID string")}toString(){let X="";for(let Y=0;Y<this.bytes.length;Y++)if(X+="0123456789abcdef".charAt(this.bytes[Y]>>>4),X+="0123456789abcdef".charAt(15&this.bytes[Y]),Y===3||Y===5||Y===7||Y===9)X+="-";return X}toHex(){let X="";for(let Y=0;Y<this.bytes.length;Y++)X+="0123456789abcdef".charAt(this.bytes[Y]>>>4),X+="0123456789abcdef".charAt(15&this.bytes[Y]);return X}toJSON(){return this.toString()}getVariant(){let X=this.bytes[8]>>>4;if(X<0)throw Error("unreachable");if(X<=7)return this.bytes.every((Y)=>Y===0)?"NIL":"VAR_0";if(X<=11)return"VAR_10";if(X<=13)return"VAR_110";if(X<=15)return this.bytes.every((Y)=>Y===255)?"MAX":"VAR_RESERVED";else throw Error("unreachable")}getVersion(){return this.getVariant()==="VAR_10"?this.bytes[6]>>>4:void 0}clone(){return new Vj(this.bytes.slice(0))}equals(X){return this.compareTo(X)===0}compareTo(X){for(let Y=0;Y<16;Y++){let G=this.bytes[Y]-X.bytes[Y];if(G!==0)return Math.sign(G)}return 0}}class fe6{constructor(X){this.timestamp=0,this.counter=0,this.random=X??Ap5()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(X,Y){let G=this.generateOrAbortCore(X,Y);if(G===void 0)this.timestamp=0,G=this.generateOrAbortCore(X,Y);return G}generateOrAbortCore(X,Y){if(!Number.isInteger(X)||X<1||X>281474976710655)throw RangeError("`unixTsMs` must be a 48-bit positive integer");if(Y<0||Y>281474976710655)throw RangeError("`rollbackAllowance` out of reasonable range");if(X>this.timestamp)this.timestamp=X,this.resetCounter();else{if(!(X+Y>=this.timestamp))return;if(this.counter++,this.counter>4398046511103)this.timestamp++,this.resetCounter()}return Vj.fromFieldsV7(this.timestamp,Math.trunc(this.counter/1073741824),this.counter&1073741823,this.random.nextUint32())}resetCounter(){this.counter=1024*this.random.nextUint32()+(1023&this.random.nextUint32())}generateV4(){let X=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return X[6]=64|X[6]>>>4,X[8]=128|X[8]>>>2,Vj.ofInner(X)}}var Ap5=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())}),_e6,Aq=()=>Tp5().toString(),Tp5=()=>(_e6||(_e6=new fe6)).generate();var bX1=D(()=>{/*! For license information please see uuidv7.mjs.LICENSE.txt */});class NB0{add(X){let Y=Aq();return this.promiseByIds[Y]=X,X.catch(()=>{}).finally(()=>{delete this.promiseByIds[Y]}),X}async join(){let X=Object.values(this.promiseByIds),Y=X.length;while(Y>0)await Promise.all(X),X=Object.values(this.promiseByIds),Y=X.length}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={}}}var be6=D(()=>{bX1()});function Ip5(X=console){return{log:X.log.bind(X),warn:X.warn.bind(X),error:X.error.bind(X),debug:X.debug.bind(X)}}function xe6(X,Y=Vp5){return ye6(X,Y,Ip5())}var ye6=(X,Y,G)=>{function Q(W,...Z){Y(()=>{let $=G[W];$(X,...Z)})}return{info:(...W)=>{Q("log",...W)},warn:(...W)=>{Q("warn",...W)},error:(...W)=>{Q("error",...W)},critical:(...W)=>{G.error(X,...W)},createLogger:(W)=>ye6(`${X} ${W}`,Y,G)}},Vp5=(X)=>X();var he6=()=>{};var pa="Mobile",lA1="iOS",ia="Android",ge6="Tablet",_lX,Mp5="Apple",flX,ue6="Safari",mA1="BlackBerry",le6="Samsung",Rp5,Sp5,dA1="Chrome",Cp5,kp5,me6="Internet Explorer",vp5,zB0="Opera",blX,de6="Edge",_p5,OB0="Firefox",fp5,DB0="Nintendo",wB0="PlayStation",uA1="Xbox",bp5,yp5,yX1="Windows",xp5,ce6="Generic",ylX,xlX,hp5="Konqueror",K3="(\\d+(\\.\\d+)?)",BB0,hlX,glX,ulX,gp5,up5,llX,mlX;var ie6=D(()=>{xA1();_X1();_lX=ia+" "+ge6,flX=Mp5+" Watch",Rp5=le6+"Browser",Sp5=le6+" Internet",Cp5=dA1+" OS",kp5=dA1+" "+lA1,vp5=me6+" "+pa,blX=zB0+" Mini",_p5="Microsoft "+de6,fp5=OB0+" "+lA1,bp5=ia+" "+pa,yp5=pa+" "+ue6,xp5=yX1+" Phone",ylX=ce6+" "+pa.toLowerCase(),xlX=ce6+" "+ge6.toLowerCase(),BB0=new RegExp("Version/"+K3),hlX=new RegExp(uA1,"i"),glX=new RegExp(wB0+" \\w+","i"),ulX=new RegExp(DB0+" \\w+","i"),gp5=new RegExp(mA1+"|PlayBook|BB10","i"),up5={"NT3.51":"NT 3.11","NT4.0":"NT 4.0","5.0":"2000","5.1":"XP","5.2":"XP","6.0":"Vista","6.1":"7","6.2":"8","6.3":"8.1","6.4":"10","10.0":"10"},llX={[vp5]:[new RegExp("rv:"+K3)],[_p5]:[new RegExp(de6+"?\\/"+K3)],[dA1]:[new RegExp("("+dA1+"|CrMo)\\/"+K3)],[kp5]:[new RegExp("CriOS\\/"+K3)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+K3)],[ue6]:[BB0],[yp5]:[BB0],[zB0]:[new RegExp("("+zB0+"|OPR)\\/"+K3)],[OB0]:[new RegExp(OB0+"\\/"+K3)],[fp5]:[new RegExp("FxiOS\\/"+K3)],[hp5]:[new RegExp("Konqueror[:/]?"+K3,"i")],[mA1]:[new RegExp(mA1+" "+K3),BB0],[bp5]:[new RegExp("android\\s"+K3,"i")],[Sp5]:[new RegExp(Rp5+"\\/"+K3)],[me6]:[new RegExp("(rv:|MSIE )"+K3)],Mozilla:[new RegExp("rv:"+K3)]},mlX=[[new RegExp(uA1+"; "+uA1+" (.*?)[);]","i"),(X)=>[uA1,X&&X[1]||""]],[new RegExp(DB0,"i"),[DB0,""]],[new RegExp(wB0,"i"),[wB0,""]],[gp5,[mA1,""]],[new RegExp(yX1,"i"),(X,Y)=>{if(/Phone/.test(Y)||/WPDesktop/.test(Y))return[xp5,""];if(new RegExp(pa).test(Y)&&!/IEMobile\b/.test(Y))return[yX1+" "+pa,""];let G=/Windows NT ([0-9.]+)/i.exec(Y);if(G&&G[1]){let Q=G[1],J=up5[Q]||"";if(/arm/i.test(Y))J="RT";return[yX1,J]}return[yX1,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,(X)=>{if(X&&X[3]){let Y=[X[3],X[4],X[5]||"0"];return[lA1,Y.join(".")]}return[lA1,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,(X)=>{let Y="";if(X&&X.length>=3)Y=da(X[2])?X[3]:X[2];return["watchOS",Y]}],[new RegExp("("+ia+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+ia+")","i"),(X)=>{if(X&&X[2]){let Y=[X[2],X[3],X[4]||"0"];return[ia,Y.join(".")]}return[ia,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,(X)=>{let Y=["Mac OS X",""];if(X&&X[1]){let G=[X[1],X[2],X[3]||"0"];Y[1]=G.join(".")}return Y}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[Cp5,""]],[/Linux|debian/i,["Linux",""]]]});function ne6(X){return X?.replace(/\/+$/,"")}async function ae6(X,Y){let G=null;for(let Q=0;Q<Y.retryCount+1;Q++){if(Q>0)await new Promise((J)=>setTimeout(J,Y.retryDelay));try{return await X()}catch(J){if(G=J,!Y.retryCheck(J))throw J}}throw G}function cA1(){return new Date().toISOString()}function Kw(X,Y){let G=setTimeout(X,Y);return G?.unref&&G?.unref(),G}function LB0(X){return Promise.all(X.map((Y)=>(Y??Promise.resolve()).then((G)=>({status:"fulfilled",value:G}),(G)=>({status:"rejected",reason:G}))))}var pe6="utf8",te6=(X)=>X instanceof Error;var H3=D(()=>{Me6();ve6();FB0();xA1();_X1();be6();he6();ie6()});var lp5,GmX;var EB0=D(()=>{H3();lp5={trace:{text:"TRACE",number:1},debug:{text:"DEBUG",number:5},info:{text:"INFO",number:9},warn:{text:"WARN",number:13},error:{text:"ERROR",number:17},fatal:{text:"FATAL",number:21}},GmX=lp5.info});var re6=D(()=>{EB0();Tj()});var oe6=D(()=>{Tj()});class PB0{constructor(){this.events={},this.events={}}on(X,Y){if(!this.events[X])this.events[X]=[];return this.events[X].push(Y),()=>{this.events[X]=this.events[X].filter((G)=>G!==Y)}}emit(X,Y){for(let G of this.events[X]||[])G(Y);for(let G of this.events["*"]||[])G(X,Y)}}var se6=()=>{};async function ee6(X){if(X instanceof na){let Y="";try{Y=await X.text}catch{}console.error(`Error while flushing PostHog: message=${X.message}, response body=${Y}`,X)}else console.error("Error while flushing PostHog",X);return Promise.resolve()}function qB0(X){return typeof X=="object"&&(X instanceof na||X instanceof xX1)}function X14(X){return typeof X=="object"&&X instanceof na&&X.status===413}class iA1{constructor(X,Y={}){this.flushPromise=null,this.shutdownPromise=null,this.promiseQueue=new NB0,this._events=new PB0,this._isInitialized=!1;let G=typeof X=="string"?X.trim():"",Q=typeof Y.host=="string"?Y.host.trim():"",J=!G;if(this._logger=xe6("[PostHog]",this.logMsgIfDebug.bind(this)),J)this._logger.error("You must pass your PostHog project's api key. The client will be disabled.");if(this.apiKey=G,this.host=ne6(Q||"https://us.i.posthog.com"),this.flushAt=Y.flushAt?Math.max(Y.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,Y.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,Y.maxQueueSize??1000),this.flushInterval=Y.flushInterval??1e4,this.preloadFeatureFlags=Y.preloadFeatureFlags??!0,this.defaultOptIn=Y.defaultOptIn??!0,this.disableSurveys=Y.disableSurveys??!1,this._retryOptions={retryCount:Y.fetchRetryCount??3,retryDelay:Y.fetchRetryDelay??3000,retryCheck:qB0},this.requestTimeout=Y.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=Y.featureFlagsRequestTimeoutMs??3000,this.remoteConfigRequestTimeoutMs=Y.remoteConfigRequestTimeoutMs??3000,this.disableGeoip=Y.disableGeoip??!0,this.disabled=(Y.disabled??!1)||J,this.historicalMigration=Y?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,this.evaluationContexts=Y?.evaluationContexts??Y?.evaluationEnvironments,Y?.evaluationEnvironments&&!Y?.evaluationContexts)this._logger.warn("evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version.");this.disableCompression=!Ve6()||(Y?.disableCompression??!1)}logMsgIfDebug(X){if(this.isDebug)X()}wrap(X){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized)return X();this._initPromise.then(()=>X())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(pJ.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(pJ.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(pJ.OptedOut,!0)})}on(X,Y){return this._events.on(X,Y)}debug(X=!0){if(this.removeDebugCallback?.(),X){let Y=this.on("*",(G,Q)=>this._logger.info(G,Q));this.removeDebugCallback=()=>{Y(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(X){return{distinct_id:X.distinct_id,event:X.event,properties:{...X.properties||{},...this.getCommonEventProperties()}}}addPendingPromise(X){return this.promiseQueue.add(X)}identifyStateless(X,Y,G){this.wrap(()=>{let Q={...this.buildPayload({distinct_id:X,event:"$identify",properties:Y})};this.enqueue("identify",Q,G)})}async identifyStatelessImmediate(X,Y,G){let Q={...this.buildPayload({distinct_id:X,event:"$identify",properties:Y})};await this.sendImmediate("identify",Q,G)}captureStateless(X,Y,G,Q){this.wrap(()=>{let J=this.buildPayload({distinct_id:X,event:Y,properties:G});this.enqueue("capture",J,Q)})}async captureStatelessImmediate(X,Y,G,Q){let J=this.buildPayload({distinct_id:X,event:Y,properties:G});await this.sendImmediate("capture",J,Q)}aliasStateless(X,Y,G,Q){this.wrap(()=>{let J=this.buildPayload({event:"$create_alias",distinct_id:Y,properties:{...G||{},distinct_id:Y,alias:X}});this.enqueue("alias",J,Q)})}async aliasStatelessImmediate(X,Y,G,Q){let J=this.buildPayload({event:"$create_alias",distinct_id:Y,properties:{...G||{},distinct_id:Y,alias:X}});await this.sendImmediate("alias",J,Q)}groupIdentifyStateless(X,Y,G,Q,J,W){this.wrap(()=>{let Z=this.buildPayload({distinct_id:J||`$${X}_${Y}`,event:"$groupidentify",properties:{$group_type:X,$group_key:Y,$group_set:G||{},...W||{}}});this.enqueue("capture",Z,Q)})}async getRemoteConfig(){await this._initPromise;let X=this.host;if(X==="https://us.i.posthog.com")X="https://us-assets.i.posthog.com";else if(X==="https://eu.i.posthog.com")X="https://eu-assets.i.posthog.com";let Y=`${X}/array/${this.apiKey}/config`,G={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(Y,G,{retryCount:0},this.remoteConfigRequestTimeoutMs).then((Q)=>Q.json()).catch((Q)=>{this._logger.error("Remote config could not be loaded",Q),this._events.emit("error",Q)})}async getFlags(X,Y={},G={},Q={},J={},W=!1){await this._initPromise;let Z=W?"&config=true":"",$=`${this.host}/flags/?v=2${Z}`,K={token:this.apiKey,distinct_id:X,groups:Y,person_properties:G,group_properties:Q,...J};if(G.$device_id)K.$device_id=G.$device_id;if(this.evaluationContexts&&this.evaluationContexts.length>0)K.evaluation_contexts=this.evaluationContexts;let H={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(K)};return this._logger.info("Flags URL",$),this.fetchWithRetry($,H,{retryCount:0},this.featureFlagsRequestTimeoutMs).then((U)=>U.json()).then((U)=>({success:!0,response:ZB0(U)})).catch((U)=>{return this._events.emit("error",U),{success:!1,error:this.categorizeRequestError(U)}})}categorizeRequestError(X){if(X instanceof na)return{type:"api_error",statusCode:X.status};if(X instanceof xX1){let Y=X.error;if(Y instanceof Error&&(Y.name==="AbortError"||Y.name==="TimeoutError"))return{type:"timeout"};return{type:"connection_error"}}return{type:"unknown_error"}}async getFeatureFlagStateless(X,Y,G={},Q={},J={},W){await this._initPromise;let Z=await this.getFeatureFlagDetailStateless(X,Y,G,Q,J,W);if(Z===void 0)return{response:void 0,requestId:void 0};let $=CX1(Z.response);if($===void 0)$=!1;return{response:$,requestId:Z.requestId}}async getFeatureFlagDetailStateless(X,Y,G={},Q={},J={},W){await this._initPromise;let Z=await this.getFeatureFlagDetailsStateless(Y,G,Q,J,W,[X]);if(Z===void 0)return;return{response:Z.flags[X],requestId:Z.requestId,evaluatedAt:Z.evaluatedAt}}async getFeatureFlagPayloadStateless(X,Y,G={},Q={},J={},W){await this._initPromise;let Z=await this.getFeatureFlagPayloadsStateless(Y,G,Q,J,W,[X]);if(!Z)return;let $=Z[X];if($===void 0)return null;return $}async getFeatureFlagPayloadsStateless(X,Y={},G={},Q={},J,W){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(X,Y,G,Q,J,W)).payloads}async getFeatureFlagsStateless(X,Y={},G={},Q={},J,W){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(X,Y,G,Q,J,W)}async getFeatureFlagsAndPayloadsStateless(X,Y={},G={},Q={},J,W){await this._initPromise;let Z=await this.getFeatureFlagDetailsStateless(X,Y,G,Q,J,W);if(!Z)return{flags:void 0,payloads:void 0,requestId:void 0};return{flags:Z.featureFlags,payloads:Z.featureFlagPayloads,requestId:Z.requestId}}async getFeatureFlagDetailsStateless(X,Y={},G={},Q={},J,W){await this._initPromise;let Z={};if(J??this.disableGeoip)Z.geoip_disable=!0;if(W)Z.flag_keys_to_evaluate=W;let $=await this.getFlags(X,Y,G,Q,Z);if(!$.success)return;let K=$.response;if(K.errorsWhileComputingFlags)console.error("[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices");if(K.quotaLimited?.includes("feature_flags"))return console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),{flags:{},featureFlags:{},featureFlagPayloads:{},requestId:K?.requestId,quotaLimited:K.quotaLimited};return K}async getSurveysStateless(){if(await this._initPromise,this.disableSurveys===!0)return this._logger.info("Loading surveys is disabled."),[];let X=`${this.host}/api/surveys/?token=${this.apiKey}`,Y={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},Q=(await this.fetchWithRetry(X,Y).then((J)=>{if(J.status!==200||!J.json){let W=`Surveys API could not be loaded: ${J.status}`,Z=Error(W);this._logger.error(Z),this._events.emit("error",Error(W));return}return J.json()}).catch((J)=>{this._logger.error("Surveys API could not be loaded",J),this._events.emit("error",J)}))?.surveys;if(Q)this._logger.info("Surveys fetched from API: ",JSON.stringify(Q));return Q??[]}get props(){if(!this._props)this._props=this.getPersistedProperty(pJ.Props);return this._props||{}}set props(X){this._props=X}async register(X){this.wrap(()=>{this.props={...this.props,...X},this.setPersistedProperty(pJ.Props,this.props)})}async unregister(X){this.wrap(()=>{delete this.props[X],this.setPersistedProperty(pJ.Props,this.props)})}processBeforeEnqueue(X){return X}async flushStorage(){}enqueue(X,Y,G){this.wrap(()=>{if(this.optedOut)return void this._events.emit(X,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let Q=this.prepareMessage(X,Y,G);if(Q=this.processBeforeEnqueue(Q),Q===null)return;let J=this.getPersistedProperty(pJ.Queue)||[];if(J.length>=this.maxQueueSize)J.shift(),this._logger.info("Queue is full, the oldest event is dropped.");if(J.push({message:Q}),this.setPersistedProperty(pJ.Queue,J),this._events.emit(X,Q),J.length>=this.flushAt)this.flushBackground();if(this.flushInterval&&!this._flushTimer)this._flushTimer=Kw(()=>this.flushBackground(),this.flushInterval)})}async sendImmediate(X,Y,G){if(this.disabled)return void this._logger.warn("The client is disabled");if(!this._isInitialized)await this._initPromise;if(this.optedOut)return void this._events.emit(X,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let Q=this.prepareMessage(X,Y,G);if(Q=this.processBeforeEnqueue(Q),Q===null)return;let J={api_key:this.apiKey,batch:[Q],sent_at:cA1()};if(this.historicalMigration)J.historical_migration=!0;let W=JSON.stringify(J),Z=`${this.host}/batch/`,$=this.disableCompression?null:await yA1(W,this.isDebug),K={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...$!==null&&{"Content-Encoding":"gzip"}},body:$||W};try{await this.fetchWithRetry(Z,K)}catch(H){this._events.emit("error",H)}}prepareMessage(X,Y,G){let Q={...Y,type:X,library:this.getLibraryId(),library_version:this.getLibraryVersion(),timestamp:G?.timestamp?G?.timestamp:cA1(),uuid:G?.uuid?G.uuid:Aq()};if(G?.disableGeoip??this.disableGeoip){if(!Q.properties)Q.properties={};Q.properties.$geoip_disable=!0}if(Q.distinctId)Q.distinct_id=Q.distinctId,delete Q.distinctId;return Q}clearFlushTimer(){if(this._flushTimer)clearTimeout(this._flushTimer),this._flushTimer=void 0}flushBackground(){this.flush().catch(async(X)=>{await ee6(X)})}async flush(){let X=LB0([this.flushPromise]).then(()=>this._flush());return this.flushPromise=X,this.addPendingPromise(X),LB0([X]).then(()=>{if(this.flushPromise===X)this.flushPromise=null}),X}getCustomHeaders(){let X=this.getCustomUserAgent(),Y={};if(X&&X!=="")Y["User-Agent"]=X;return Y}async _flush(){this.clearFlushTimer(),await this._initPromise;let X=this.getPersistedProperty(pJ.Queue)||[];if(!X.length)return;let Y=[],G=X.length;while(X.length>0&&Y.length<G){let Q=X.slice(0,this.maxBatchSize),J=Q.map((B)=>B.message),W=async()=>{let z=(this.getPersistedProperty(pJ.Queue)||[]).slice(Q.length);this.setPersistedProperty(pJ.Queue,z),X=z,await this.flushStorage()},Z={api_key:this.apiKey,batch:J,sent_at:cA1()};if(this.historicalMigration)Z.historical_migration=!0;let $=JSON.stringify(Z),K=`${this.host}/batch/`,H=this.disableCompression?null:await yA1($,this.isDebug),U={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...H!==null&&{"Content-Encoding":"gzip"}},body:H||$},N={retryCheck:(B)=>{if(X14(B))return!1;return qB0(B)}};try{await this.fetchWithRetry(K,U,N)}catch(B){if(X14(B)&&J.length>1){this.maxBatchSize=Math.max(1,Math.floor(J.length/2)),this._logger.warn(`Received 413 when sending batch of size ${J.length}, reducing batch size to ${this.maxBatchSize}`);continue}if(!(B instanceof xX1))await W();throw this._events.emit("error",B),B}await W(),Y.push(...J)}this._events.emit("flush",Y)}async fetchWithRetry(X,Y,G,Q){let J=Y.body?Y.body:"",W=-1;try{W=J instanceof Blob?J.size:Buffer.byteLength(J,pe6)}catch{if(J instanceof Blob)W=J.size;else W=new TextEncoder().encode(J).length}return await ae6(async()=>{let Z=new AbortController,$=Q??this.requestTimeout,K=Kw(()=>Z.abort(),$),H=null;try{H=await this.fetch(X,{signal:Z.signal,...Y})}catch(N){throw new xX1(N)}finally{clearTimeout(K)}if(Y.mode!=="no-cors"&&(H.status<200||H.status>=400))throw new na(H,W);return H},{...this._retryOptions,...G})}async _shutdown(X=30000){await this._initPromise;let Y=!1;this.clearFlushTimer();let G=async()=>{try{await this.promiseQueue.join();while(!0){if((this.getPersistedProperty(pJ.Queue)||[]).length===0)break;if(await this.flush(),Y)break}}catch(J){if(!qB0(J))throw J;await ee6(J)}},Q;try{return await Promise.race([new Promise((J,W)=>{Q=Kw(()=>{this._logger.error("Timed out while shutting down PostHog"),Y=!0,W("Timeout while shutting down PostHog. Some events may not have been sent.")},X)}),G()])}finally{clearTimeout(Q)}}async shutdown(X=30000){if(this.shutdownPromise)this._logger.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup");else this.shutdownPromise=this._shutdown(X).finally(()=>{this.shutdownPromise=null});return this.shutdownPromise}}var na,xX1;var AB0=D(()=>{se6();bA1();$B0();Tj();H3();bX1();na=class na extends Error{constructor(X,Y){super("HTTP error while fetching PostHog: status="+X.status+", reqByteLength="+Y),this.response=X,this.reqByteLength=Y,this.name="PostHogFetchHttpError"}get status(){return this.response.status}get text(){return this.response.text()}get json(){return this.response.json()}};xX1=class xX1 extends Error{constructor(X){super("Network error while fetching PostHog",X instanceof Error?{cause:X}:{}),this.error=X,this.name="PostHogFetchNetworkError"}}});var Y14=D(()=>{bA1();Tj();AB0();bX1();H3()});var G14=D(()=>{_X1()});function J14(X){let Y=globalThis._posthogChunkIds;if(!Y)return;let G=Object.keys(Y);if(nA1&&G.length===Q14)return nA1;return Q14=G.length,nA1=G.reduce((Q,J)=>{if(!pA1)pA1={};let W=pA1[J];if(W)Q[W[0]]=W[1];else{let Z=X(J);for(let $=Z.length-1;$>=0;$--){let H=Z[$]?.filename,U=Y[J];if(H&&U){Q[H]=U,pA1[J]=[H,U];break}}}return Q},{}),nA1}var pA1,Q14,nA1;var Z14=()=>{};class W14{constructor(X,Y,G=[]){this.coercers=X,this.stackParser=Y,this.modifiers=G}buildFromUnknown(X,Y={}){let Q=Y&&Y.mechanism||{handled:!0,type:"generic"},W=this.buildCoercingContext(Q,Y,0).apply(X),Z=this.buildParsingContext(Y),$=this.parseStacktrace(W,Z);return{$exception_list:this.convertToExceptionList($,Q),$exception_level:"error"}}async modifyFrames(X){for(let Y of X)if(Y.stacktrace&&Y.stacktrace.frames&&hA1(Y.stacktrace.frames))Y.stacktrace.frames=await this.applyModifiers(Y.stacktrace.frames);return X}coerceFallback(X){return{type:"Error",value:"Unknown error",stack:X.syntheticException?.stack,synthetic:!0}}parseStacktrace(X,Y){let G;if(X.cause!=null)G=this.parseStacktrace(X.cause,Y);let Q;if(X.stack!=""&&X.stack!=null)Q=this.applyChunkIds(this.stackParser(X.stack,X.synthetic?Y.skipFirstLines:0),Y.chunkIdMap);return{...X,cause:G,stack:Q}}applyChunkIds(X,Y){return X.map((G)=>{if(G.filename&&Y)G.chunk_id=Y[G.filename];return G})}applyCoercers(X,Y){for(let G of this.coercers)if(G.match(X))return G.coerce(X,Y);return this.coerceFallback(Y)}async applyModifiers(X){let Y=X;for(let G of this.modifiers)Y=await G(Y);return Y}convertToExceptionList(X,Y){let G={type:X.type,value:X.value,mechanism:{type:Y.type??"generic",handled:Y.handled??!0,synthetic:X.synthetic??!1}};if(X.stack)G.stacktrace={type:"raw",frames:X.stack};let Q=[G];if(X.cause!=null)Q.push(...this.convertToExceptionList(X.cause,{...Y,handled:!0}));return Q}buildParsingContext(X){return{chunkIdMap:J14(this.stackParser),skipFirstLines:X.skipFirstLines??1}}buildCoercingContext(X,Y,G=0){let Q=(W,Z)=>{if(!(Z<=cp5))return;{let $=this.buildCoercingContext(X,Y,Z);return this.applyCoercers(W,$)}};return{...Y,syntheticException:G==0?Y.syntheticException:void 0,mechanism:X,apply:(W)=>Q(W,G),next:(W)=>Q(W,G+1)}}}var cp5=4;var $14=D(()=>{H3();Z14()});function Yz(X,Y,G,Q,J){let W={platform:X,filename:Y,function:G==="<anonymous>"?rQ:G,in_app:!0};if(!da(Q))W.lineno=Q;if(!da(J))W.colno=J;return W}var rQ="?";var Tq=D(()=>{H3()});var aA1=(X,Y)=>{let G=X.indexOf("safari-extension")!==-1,Q=X.indexOf("safari-web-extension")!==-1;return G||Q?[X.indexOf("@")!==-1?X.split("@")[0]:rQ,G?`safari-extension:${Y}`:`safari-web-extension:${Y}`]:[X,Y]};var TB0=D(()=>{Tq()});var ip5,pp5,np5,IB0=(X,Y)=>{let G=ip5.exec(X);if(G){let[,J,W,Z]=G;return Yz(Y,J,rQ,+W,+Z)}let Q=pp5.exec(X);if(Q){if(Q[2]&&Q[2].indexOf("eval")===0){let $=np5.exec(Q[2]);if($)Q[2]=$[1],Q[3]=$[2],Q[4]=$[3]}let[W,Z]=aA1(Q[1]||rQ,Q[2]);return Yz(Y,Z,W,Q[3]?+Q[3]:void 0,Q[4]?+Q[4]:void 0)}};var K14=D(()=>{Tq();TB0();ip5=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,pp5=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,np5=/\((\S*)(?::(\d+))(?::(\d+))\)/});var ap5,tp5,VB0=(X,Y)=>{let G=ap5.exec(X);if(G){if(G[3]&&G[3].indexOf(" > eval")>-1){let Z=tp5.exec(G[3]);if(Z)G[1]=G[1]||"eval",G[3]=Z[1],G[4]=Z[2],G[5]=""}let J=G[3],W=G[1]||rQ;return[W,J]=aA1(W,J),Yz(Y,J,W,G[4]?+G[4]:void 0,G[5]?+G[5]:void 0)}};var H14=D(()=>{Tq();TB0();ap5=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,tp5=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i});var rp5,F14=(X,Y)=>{let G=rp5.exec(X);return G?Yz(Y,G[2],G[1]||rQ,+G[3],G[4]?+G[4]:void 0):void 0};var U14=D(()=>{Tq();rp5=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i});var op5,N14=(X,Y)=>{let G=op5.exec(X);return G?Yz(Y,G[2],G[3]||rQ,+G[1]):void 0},sp5,B14=(X,Y)=>{let G=sp5.exec(X);return G?Yz(Y,G[5],G[3]||G[4]||rQ,+G[1],+G[2]):void 0};var z14=D(()=>{Tq();op5=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,sp5=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i});function Yn5(X,Y=!1){return!(Y||X&&!X.startsWith("/")&&!X.match(/^[A-Z]:/)&&!X.startsWith(".")&&!X.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&X!==void 0&&!X.includes("node_modules/")}function O14(X){return parseInt(X||"",10)||void 0}var ep5,Xn5,D14=(X,Y)=>{let G=X.match(Xn5);if(G){let Q,J,W,Z,$;if(G[1]){W=G[1];let U=W.lastIndexOf(".");if(W[U-1]===".")U--;if(U>0){Q=W.slice(0,U),J=W.slice(U+1);let N=Q.indexOf(".Module");if(N>0)W=W.slice(N+1),Q=Q.slice(0,N)}Z=void 0}if(J)Z=Q,$=J;if(J==="<anonymous>")$=void 0,W=void 0;if(W===void 0)$=$||rQ,W=Z?`${Z}.${$}`:$;let K=G[2]?.startsWith("file://")?G[2].slice(7):G[2],H=G[5]==="native";if(K?.match(/\/[A-Z]:/))K=K.slice(1);if(!K&&G[5]&&!H)K=G[5];return{filename:K?decodeURI(K):void 0,module:void 0,function:W,lineno:O14(G[3]),colno:O14(G[4]),in_app:Yn5(K||"",H),platform:Y}}if(X.match(ep5))return{filename:X,platform:Y}};var w14=D(()=>{Tq();ep5=/^\s*[-]{4,}$/,Xn5=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/});function P14(X){if(!X.length)return[];let Y=Array.from(X);return Y.reverse(),Y.slice(0,E14).map((G)=>({...G,filename:G.filename||Gn5(Y).filename,function:G.function||rQ}))}function Gn5(X){return X[X.length-1]||{}}function Qn5(){return q14("web:javascript",IB0,VB0)}function q14(X,...Y){return(G,Q=0)=>{let J=[],W=G.split(`
|
|
1640
1640
|
`);for(let Z=Q;Z<W.length;Z++){let $=W[Z];if($.length>1024)continue;let K=L14.test($)?$.replace(L14,"$1"):$;if(!K.match(/\S*Error: /)){for(let H of Y){let U=H(K,X);if(U){J.push(U);break}}if(J.length>=E14)break}}return P14(J)}}var L14,E14=50;var A14=D(()=>{Tq();K14();H14();U14();z14();w14();L14=/\(error: (.*)\)/});class T14{match(X){return this.isDOMException(X)||this.isDOMError(X)}coerce(X,Y){let G=qq(X.stack);return{type:this.getType(X),value:this.getValue(X),stack:G?X.stack:void 0,cause:X.cause?Y.next(X.cause):void 0,synthetic:!1}}getType(X){return this.isDOMError(X)?"DOMError":"DOMException"}getValue(X){let Y=X.name||(this.isDOMError(X)?"DOMError":"DOMException");return X.message?`${Y}: ${X.message}`:Y}isDOMException(X){return Ij(X,"DOMException")}isDOMError(X){return Ij(X,"DOMError")}}var I14=D(()=>{H3()});class V14{match(X){return HB0(X)}coerce(X,Y){return{type:this.getType(X),value:this.getMessage(X,Y),stack:this.getStack(X),cause:X.cause?Y.next(X.cause):void 0,synthetic:!1}}getType(X){return X.name||X.constructor.name}getMessage(X,Y){let G=X.message;if(G.error&&typeof G.error.message=="string")return String(G.error.message);return String(G)}getStack(X){return X.stacktrace||X.stack||void 0}}var j14=D(()=>{H3()});class M14{constructor(){}match(X){return Ce6(X)&&X.error!=null}coerce(X,Y){let G=Y.apply(X.error);if(!G)return{type:"ErrorEvent",value:X.message,stack:Y.syntheticException?.stack,synthetic:!0};return G}}var R14=D(()=>{H3()});class S14{match(X){return typeof X=="string"}coerce(X,Y){let[G,Q]=this.getInfos(X);return{type:G??"Error",value:Q??X,stack:Y.syntheticException?.stack,synthetic:!0}}getInfos(X){let Y="Error",G=X,Q=X.match(Jn5);if(Q)Y=Q[1],G=Q[2];return[Y,G]}}var Jn5;var C14=D(()=>{Jn5=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i});var k14;var v14=D(()=>{k14=["fatal","error","warning","log","info","debug"]});function tA1(X,Y=40){let G=Object.keys(X);if(G.sort(),!G.length)return"[object has no keys]";for(let Q=G.length;Q>0;Q--){let J=G.slice(0,Q).join(", ");if(!(J.length>Y)){if(Q===G.length)return J;return J.length<=Y?J:`${J.slice(0,Y)}...`}}return""}var jB0=()=>{};class _14{match(X){return typeof X=="object"&&X!==null}coerce(X,Y){let G=this.getErrorPropertyFromObject(X);if(G)return Y.apply(G);return{type:this.getType(X),value:this.getValue(X),stack:Y.syntheticException?.stack,level:this.isSeverityLevel(X.level)?X.level:"error",synthetic:!0}}getType(X){return ca(X)?X.constructor.name:"Error"}getValue(X){if("name"in X&&typeof X.name=="string"){let Q=`'${X.name}' captured as exception`;if("message"in X&&typeof X.message=="string")Q+=` with message: '${X.message}'`;return Q}if("message"in X&&typeof X.message=="string")return X.message;let Y=this.getObjectClassName(X),G=tA1(X);return`${Y&&Y!=="Object"?`'${Y}'`:"Object"} captured as exception with keys: ${G}`}isSeverityLevel(X){return qq(X)&&!Se6(X)&&k14.indexOf(X)>=0}getErrorPropertyFromObject(X){for(let Y in X)if(Object.prototype.hasOwnProperty.call(X,Y)){let G=X[Y];if(te6(G))return G}}getObjectClassName(X){try{let Y=Object.getPrototypeOf(X);return Y?Y.constructor.name:void 0}catch(Y){return}}}var f14=D(()=>{H3();v14();jB0()});class b14{match(X){return ca(X)}coerce(X,Y){let G=X.constructor.name;return{type:G,value:`${G} captured as exception with keys: ${tA1(X)}`,stack:Y.syntheticException?.stack,synthetic:!0}}}var y14=D(()=>{H3();jB0()});class x14{match(X){return gA1(X)}coerce(X,Y){return{type:"Error",value:`Primitive value captured as exception: ${String(X)}`,stack:Y.syntheticException?.stack,synthetic:!0}}}var h14=D(()=>{H3()});class g14{match(X){return Ij(X,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(X)}isCustomEventWrappingRejection(X){if(!ca(X))return!1;try{let Y=X.detail;return Y!=null&&typeof Y=="object"&&"reason"in Y}catch{return!1}}coerce(X,Y){let G=this.getUnhandledRejectionReason(X);if(gA1(G))return{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(G)}`,stack:Y.syntheticException?.stack,synthetic:!0};return Y.apply(G)}getUnhandledRejectionReason(X){try{if("reason"in X)return X.reason;if("detail"in X&&X.detail!=null&&typeof X.detail=="object"&&"reason"in X.detail)return X.detail.reason}catch{}return X}}var u14=D(()=>{H3()});var l14=D(()=>{I14();j14();R14();C14();f14();y14();h14();u14()});class m14{constructor(X){this._maxSize=X,this._cache=new Map}get(X){let Y=this._cache.get(X);if(Y===void 0)return;return this._cache.delete(X),this._cache.set(X,Y),Y}set(X,Y){this._cache.set(X,Y)}reduce(){while(this._cache.size>=this._maxSize){let X=this._cache.keys().next().value;if(X)this._cache.delete(X)}}}var d14=()=>{};function MB0(X){if(!X)return{...rA1};return{enabled:X.enabled??rA1.enabled,max_bytes:$n5(X.max_bytes,rA1.max_bytes)}}function Wn5(X){if(!X)return{sanitizedProperties:{},droppedKeys:[]};let Y=[];return{sanitizedProperties:Object.keys(X).reduce((Q,J)=>{if(Zn5.has(J))return Y.push(J),Q;return Q[J]=X[J],Q},{}),droppedKeys:Y}}class c14{constructor(X){this._entries=[],this._totalBytes=0,this._config=MB0(X)}setConfig(X){this._config=MB0(X),this._trimToMaxBytes()}add(X){let Y=Kn5(X);if(!Y)return;let G=i14(Y.json);if(G>this._config.max_bytes)return;this._entries.push({step:Y.step,bytes:G}),this._totalBytes+=G,this._trimToMaxBytes()}getAttachable(){return this._entries.map((X)=>X.step)}clear(){this._entries=[],this._totalBytes=0}size(){return this._entries.length}_trimToMaxBytes(){while(this._totalBytes>this._config.max_bytes&&this._entries.length>0){let X=this._entries.shift();if(X)this._totalBytes-=X.bytes}}}function $n5(X,Y){if(!vX1(X)||X===1/0||X===-1/0)return Y;let G=Math.floor(X);if(G<0)return Y;return G}function Kn5(X){let Y=Hn5(X);if(!Y)return;try{let G=JSON.parse(Y);if(!kX1(G))return;let Q=G,J=Q[hX1.MESSAGE],W=Q[hX1.TIMESTAMP];if(!qq(J)||J.trim().length===0)return;if(!qq(W)&&!vX1(W))return;return{step:Q,json:Y}}catch{return}}function Hn5(X){let Y=new WeakSet;try{return JSON.stringify(X,(G,Q)=>{if(typeof Q=="bigint")return Q.toString();if(typeof Q=="function"||typeof Q=="symbol")return;if(Q instanceof Date)return Q.toISOString();if(Q instanceof Error)return{name:Q.name,message:Q.message,stack:Q.stack};if(Q&&typeof Q=="object"){if(Y.has(Q))return"[Circular]";Y.add(Q)}return Q})}catch{return}}function i14(X){if(typeof TextEncoder<"u")return new TextEncoder().encode(X).length;let Y=encodeURIComponent(X),G=0;for(let Q=0;Q<Y.length;Q++)if(Y[Q]==="%")G+=1,Q+=2;else G+=1;return G}var hX1,Zn5,rA1;var p14=D(()=>{H3();hX1={MESSAGE:"$message",TIMESTAMP:"$timestamp"},Zn5=new Set([hX1.MESSAGE,hX1.TIMESTAMP]),rA1={enabled:!0,max_bytes:32768}});var PW={};R0(PW,{winjsStackLineParser:()=>F14,stripReservedExceptionStepFields:()=>Wn5,reverseAndStripFrames:()=>P14,resolveExceptionStepsConfig:()=>MB0,opera11StackLineParser:()=>B14,opera10StackLineParser:()=>N14,nodeStackLineParser:()=>D14,getUtf8ByteLength:()=>i14,geckoStackLineParser:()=>VB0,createStackParser:()=>q14,createDefaultStackParser:()=>Qn5,chromeStackLineParser:()=>IB0,StringCoercer:()=>S14,ReduceableCache:()=>m14,PromiseRejectionEventCoercer:()=>g14,PrimitiveCoercer:()=>x14,ObjectCoercer:()=>_14,ExceptionStepsBuffer:()=>c14,EventCoercer:()=>b14,ErrorPropertiesBuilder:()=>W14,ErrorEventCoercer:()=>M14,ErrorCoercer:()=>V14,EXCEPTION_STEP_INTERNAL_FIELDS:()=>hX1,DOMExceptionCoercer:()=>T14,DEFAULT_EXCEPTION_STEPS_CONFIG:()=>rA1});var n14=D(()=>{$14();A14();l14();d14();p14()});var jj=D(()=>{bA1();$B0();EB0();re6();bX1();oe6();n14();H3();Y14();AB0();G14();Tj()});import{createReadStream as Fn5}from"fs";import{createInterface as Un5}from"readline";async function o14(X){let Y={};for(let J=X.length-1;J>=0;J--){let W=X[J],Z=W?.filename;if(!W||typeof Z!="string"||typeof W.lineno!="number"||wn5(Z)||Ln5(W))continue;if(!Y[Z])Y[Z]=[];Y[Z].push(W.lineno)}let G=Object.keys(Y);if(G.length==0)return X;let Q=[];for(let J of G){if(r14.get(J))continue;let W=Y[J];if(!W)continue;W.sort((K,H)=>K-H);let Z=Pn5(W);if(Z.every((K)=>En5(J,K)))continue;let $=qn5(oA1,J,{});Q.push(zn5(J,Z,$))}if(await Promise.all(Q).catch(()=>{}),X&&X.length>0)On5(X,oA1);return oA1.reduce(),X}function zn5(X,Y,G){return new Promise((Q)=>{let J=Fn5(X),W=Un5({input:J});function Z(){J.destroy(),Q()}let $=0,K=0,H=Y[K];if(H===void 0)return void Z();let U=H[0],N=H[1];function B(){r14.set(X,1),W.close(),W.removeAllListeners(),Z()}J.on("error",B),W.on("error",B),W.on("close",Z),W.on("line",(z)=>{if($++,$<U)return;if(G[$]=An5(z,0),$>=N){if(K===Y.length-1){W.close(),W.removeAllListeners();return}K++;let O=Y[K];if(O===void 0){W.close(),W.removeAllListeners();return}U=O[0],N=O[1]}})})}function On5(X,Y){for(let G of X)if(G.filename&&G.context_line===void 0&&typeof G.lineno=="number"){let Q=Y.get(G.filename);if(Q===void 0)continue;Dn5(G.lineno,G,Q)}}function Dn5(X,Y,G){if(Y.lineno===void 0||G===void 0)return;Y.pre_context=[];for(let J=s14(X);J<X;J++){let W=G[J];if(W===void 0)return void a14(Y);Y.pre_context.push(W)}if(G[X]===void 0)return void a14(Y);Y.context_line=G[X];let Q=e14(X);Y.post_context=[];for(let J=X+1;J<=Q;J++){let W=G[J];if(W===void 0)break;Y.post_context.push(W)}}function a14(X){delete X.pre_context,delete X.context_line,delete X.post_context}function wn5(X){return X.startsWith("node:")||X.endsWith(".min.js")||X.endsWith(".min.cjs")||X.endsWith(".min.mjs")||X.startsWith("data:")}function Ln5(X){if(X.lineno!==void 0&&X.lineno>Bn5)return!0;if(X.colno!==void 0&&X.colno>Nn5)return!0;return!1}function En5(X,Y){let G=oA1.get(X);if(G===void 0)return!1;for(let Q=Y[0];Q<=Y[1];Q++)if(G[Q]===void 0)return!1;return!0}function Pn5(X){if(!X.length)return[];let Y=0,G=X[0];if(typeof G!="number")return[];let Q=t14(G),J=[];while(!0){if(Y===X.length-1){J.push(Q);break}let W=X[Y+1];if(typeof W!="number")break;if(W<=Q[1])Q[1]=W+RB0;else J.push(Q),Q=t14(W);Y++}return J}function t14(X){return[s14(X),e14(X)]}function s14(X){return Math.max(1,X-RB0)}function e14(X){return X+RB0}function qn5(X,Y,G){let Q=X.get(Y);if(Q===void 0)return X.set(Y,G),G;return Q}function An5(X,Y){let G=X,Q=G.length;if(Q<=150)return G;if(Y>Q)Y=Q;let J=Math.max(Y-60,0);if(J<5)J=0;let W=Math.min(J+140,Q);if(W>Q-5)W=Q;if(W===Q)J=Math.max(W-140,0);if(G=G.slice(J,W),J>0)G=`...${G}`;if(W<Q)G+="...";return G}var oA1,r14,RB0=7,Nn5=1000,Bn5=1e4;var X04=D(()=>{jj();oA1=new PW.ReduceableCache(25),r14=new PW.ReduceableCache(20)});import{isAbsolute as Tn5,relative as In5,sep as Vn5}from"path";function Y04(X=process.cwd()){let Y=Vn5==="\\",G=(J)=>Y?J.replace(/\\/g,"/"):J,Q=G(X);return async(J)=>{for(let W of J)if(!(!W.filename||W.filename.startsWith("node:")||W.filename.startsWith("data:"))){if(Tn5(W.filename))W.filename=G(In5(Q,G(W.filename)))}return J}}var G04=()=>{};function jn5(X,Y){let G=!1;return Object.assign((Q)=>{let W=global.process.listeners("uncaughtException").filter((Z)=>Z.name!=="domainUncaughtExceptionClear"&&Z._posthogErrorHandler!==!0).length===0;if(X(Q,{mechanism:{type:"onuncaughtexception",handled:!1}}),!G&&W)G=!0,Y(Q)},{_posthogErrorHandler:!0})}function Q04(X,Y){globalThis.process?.on("uncaughtException",jn5(X,Y))}function J04(X){globalThis.process?.on("unhandledRejection",(Y)=>X(Y,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var Z04=()=>{};class OH{constructor(X,Y,G){this.client=X,this._exceptionAutocaptureEnabled=Y.enableExceptionAutocapture||!1,this._logger=G,this._rateLimiter=new UB0({refillRate:1,bucketSize:10,refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(X){return kX1(X)&&"__posthog_previously_captured_error"in X&&X.__posthog_previously_captured_error===!0}static async buildEventMessage(X,Y,G,Q){let J={...Q},W=this.errorPropertiesBuilder.buildFromUnknown(X,Y);return W.$exception_list=await this.errorPropertiesBuilder.modifyFrames(W.$exception_list),{event:"$exception",distinctId:G,properties:{...W,...J},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){if(this.isEnabled())Q04(this.onException.bind(this),this.onFatalError.bind(this)),J04(this.onException.bind(this))}onException(X,Y){this.client.addPendingPromise((async()=>{if(!OH.isPreviouslyCapturedError(X)){let G=await OH.buildEventMessage(X,Y),J=G.properties?.$exception_list[0]?.type??"Exception";if(this._rateLimiter.consumeRateLimit(J))return void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:J});return this.client.capture(G)}})())}async onFatalError(X){console.error(X),await this.client.shutdown(Mn5),process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}}var Mn5=2000;var sA1=D(()=>{Z04();jj()});var W04="5.30.6";var $04=()=>{};var gX1;var SB0=D(()=>{gX1={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"}});async function K04(X){let Y=globalThis.crypto?.subtle;if(!Y)throw Error("SubtleCrypto API not available");let G=await Y.digest("SHA-1",new TextEncoder().encode(X));return Array.from(new Uint8Array(G)).map((J)=>J.toString(16).padStart(2,"0")).join("")}var H04=()=>{};class CB0{constructor({pollingInterval:X,personalApiKey:Y,projectApiKey:G,timeout:Q,host:J,customHeaders:W,...Z}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollingInterval=X,this.personalApiKey=Y,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=Q,this.projectApiKey=G,this.host=J,this.poller=void 0,this.fetch=Z.fetch||fetch,this.onError=Z.onError,this.customHeaders=W,this.onLoad=Z.onLoad,this.cacheProvider=Z.cacheProvider,this.strictLocalEvaluation=Z.strictLocalEvaluation??!1,this.loadFeatureFlags()}debug(X=!0){this.debugMode=X}logMsgIfDebug(X){if(this.debugMode)X()}createEvaluationContext(X,Y={},G={},Q={},J={}){return{distinctId:X,groups:Y,personProperties:G,groupProperties:Q,evaluationCache:J}}async getFeatureFlag(X,Y,G={},Q={},J={}){await this.loadFeatureFlags();let W,Z;if(!this.loadedSuccessfullyOnce)return W;if(Z=this.featureFlagsByKey[X],Z!==void 0){let $=this.createEvaluationContext(Y,G,Q,J);try{W=(await this.computeFlagAndPayloadLocally(Z,$)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${X} -> ${W}`))}catch(K){if(K instanceof Gz||K instanceof d5)this.logMsgIfDebug(()=>console.debug(`${K.name} when computing flag locally: ${X}: ${K.message}`));else if(K instanceof Error)this.onError?.(Error(`Error computing flag locally: ${X}: ${K}`))}}return W}async getAllFlagsAndPayloads(X,Y){await this.loadFeatureFlags();let G={},Q={},J=this.featureFlags.length==0,W=Y?Y.map(($)=>this.featureFlagsByKey[$]).filter(Boolean):this.featureFlags,Z={...X,evaluationCache:X.evaluationCache??{}};return await Promise.all(W.map(async($)=>{try{let{value:K,payload:H}=await this.computeFlagAndPayloadLocally($,Z);if(G[$.key]=K,H)Q[$.key]=H}catch(K){if(K instanceof Gz||K instanceof d5)this.logMsgIfDebug(()=>console.debug(`${K.name} when computing flag locally: ${$.key}: ${K.message}`));else if(K instanceof Error)this.onError?.(Error(`Error computing flag locally: ${$.key}: ${K}`));J=!0}})),{response:G,payloads:Q,fallbackToFlags:J}}async computeFlagAndPayloadLocally(X,Y,G={}){let{matchValue:Q,skipLoadCheck:J=!1}=G;if(!J)await this.loadFeatureFlags();if(!this.loadedSuccessfullyOnce)return{value:!1,payload:null};let W;W=Q!==void 0?Q:await this.computeFlagValueLocally(X,Y);let Z=this.getFeatureFlagPayload(X.key,W);return{value:W,payload:Z}}async computeFlagValueLocally(X,Y){let{distinctId:G,groups:Q,personProperties:J,groupProperties:W}=Y;if(X.ensure_experience_continuity)throw new d5("Flag has experience continuity enabled");if(!X.active)return!1;let $=(X.filters||{}).aggregation_group_type_index;if($!=null){let K=this.groupTypeMapping[String($)];if(!K)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${$} for feature flag ${X.key}`)),new d5("Flag has unknown group type index");if(!(K in Q))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${X.key} without group names passed in`)),!1;if(X.bucketing_identifier==="device_id"&&(J?.$device_id===void 0||J?.$device_id===null||J?.$device_id===""))this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${X.key}`));let H=W[K];return await this.matchFeatureFlagProperties(X,Q[K],H,Y)}{let K=this.getBucketingValueForFlag(X,G,J);if(K===void 0)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${X.key} without $device_id, falling back to server evaluation`)),new d5(`Can't compute feature flag: ${X.key} without $device_id`);return await this.matchFeatureFlagProperties(X,K,J,Y)}}getBucketingValueForFlag(X,Y,G){if(X.filters?.aggregation_group_type_index!=null)return Y;if(X.bucketing_identifier==="device_id"){let Q=G?.$device_id;if(Q==null||Q==="")return;return Q}return Y}getFeatureFlagPayload(X,Y){let G=null;if(Y!==!1&&Y!=null){if(typeof Y=="boolean")G=this.featureFlagsByKey?.[X]?.filters?.payloads?.[Y.toString()]||null;else if(typeof Y=="string")G=this.featureFlagsByKey?.[X]?.filters?.payloads?.[Y]||null;if(G!=null){if(typeof G=="object")return G;if(typeof G=="string")try{return JSON.parse(G)}catch{}return G}}return null}async evaluateFlagDependency(X,Y,G){let{evaluationCache:Q}=G,J=X.key;if(!this.featureFlagsByKey)throw new d5("Feature flags not available for dependency evaluation");if(!("dependency_chain"in X))throw new d5(`Flag dependency property for '${J}' is missing required 'dependency_chain' field`);let W=X.dependency_chain;if(!Array.isArray(W))throw new d5(`Flag dependency property for '${J}' has an invalid 'dependency_chain' (expected array, got ${typeof W})`);if(W.length===0)throw new d5(`Circular dependency detected for flag '${J}' (empty dependency chain)`);for(let $ of W){if(!($ in Q)){let H=this.featureFlagsByKey[$];if(H)if(H.active)try{let U=await this.computeFlagValueLocally(H,G);Q[$]=U}catch(U){throw new d5(`Error evaluating flag dependency '${$}' for flag '${J}': ${U}`)}else Q[$]=!1;else throw new d5(`Missing flag dependency '${$}' for flag '${J}'`)}if(Q[$]==null)throw new d5(`Dependency '${$}' could not be evaluated`)}let Z=Q[J];return this.flagEvaluatesToExpectedValue(X.value,Z)}flagEvaluatesToExpectedValue(X,Y){if(typeof X=="boolean")return X===Y||typeof Y=="string"&&Y!==""&&X===!0;if(typeof X=="string")return Y===X;return!1}async matchFeatureFlagProperties(X,Y,G,Q){let J=X.filters||{},W=J.groups||[],Z=!1,$;for(let K of W)try{if(await this.isConditionMatch(X,Y,K,G,Q)){let H=K.variant,U=J.multivariate?.variants||[];$=H&&U.some((N)=>N.key===H)?H:await this.getMatchingVariant(X,Y)||!0;break}}catch(H){if(H instanceof Gz)throw H;if(H instanceof d5)Z=!0;else throw H}if($!==void 0)return $;if(Z)throw new d5("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(X,Y,G,Q,J){let W=G.rollout_percentage,Z=($)=>{this.logMsgIfDebug(()=>console.warn($))};if((G.properties||[]).length>0){for(let $ of G.properties){let K=$.type,H=!1;if(H=K==="cohort"?z04($,Q,this.cohorts,this.debugMode):K==="flag"?await this.evaluateFlagDependency($,Q,J):B04($,Q,Z),!H)return!1}if(W==null)return!0}if(W!=null&&await F04(X.key,Y)>W/100)return!1;return!0}async getMatchingVariant(X,Y){let G=await F04(X.key,Y,"variant"),Q=this.variantLookupTable(X).find((J)=>G>=J.valueMin&&G<J.valueMax);if(Q)return Q.key}variantLookupTable(X){let Y=[],G=0,Q=0;return((X.filters||{}).multivariate?.variants||[]).forEach((Z)=>{Q=G+Z.rollout_percentage/100,Y.push({valueMin:G,valueMax:Q,key:Z.key}),G=Q}),Y}updateFlagState(X){this.featureFlags=X.flags,this.featureFlagsByKey=X.flags.reduce((Y,G)=>(Y[G.key]=G,Y),{}),this.groupTypeMapping=X.groupTypeMapping,this.cohorts=X.cohorts,this.loadedSuccessfullyOnce=!0}warnAboutExperienceContinuityFlags(X){if(this.strictLocalEvaluation)return;let Y=X.filter((G)=>G.ensure_experience_continuity);if(Y.length>0)console.warn(`[PostHog] You are using local evaluation but ${Y.length} flag(s) have experience continuity enabled: ${Y.map((G)=>G.key).join(", ")}. Experience continuity is incompatible with local evaluation and will cause a server request on every flag evaluation, negating local evaluation cost savings. To avoid server requests and unexpected costs, either disable experience continuity on these flags in PostHog, use strictLocalEvaluation: true in client init, or pass onlyEvaluateLocally: true per flag call (flags that cannot be evaluated locally will return undefined).`)}async loadFromCache(X){if(!this.cacheProvider)return!1;try{let Y=await this.cacheProvider.getFlagDefinitions();if(Y)return this.updateFlagState(Y),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${X} (${Y.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(Y.flags),!0;return!1}catch(Y){return this.onError?.(Error(`Failed to load from cache: ${Y}`)),!1}}async loadFeatureFlags(X=!1){if(this.loadedSuccessfullyOnce&&!X)return;if(!X&&this.nextFetchAllowedAt&&Date.now()<this.nextFetchAllowedAt)return void this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Skipping fetch, in backoff period"));if(!this.loadingPromise)this.loadingPromise=this._loadFeatureFlags().catch((Y)=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${Y}`))).finally(()=>{this.loadingPromise=void 0});return this.loadingPromise}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getFlagDefinitionsLoadedAt(){return this.flagDefinitionsLoadedAt}getPollingInterval(){if(!this.shouldBeginExponentialBackoff)return this.pollingInterval;return Math.min(Rn5,this.pollingInterval*2**this.backOffCount)}beginBackoff(){this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,this.nextFetchAllowedAt=Date.now()+this.getPollingInterval()}clearBackoff(){this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.nextFetchAllowedAt=void 0}async _loadFeatureFlags(){if(this.poller)clearTimeout(this.poller),this.poller=void 0;this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval());try{let X=!0;if(this.cacheProvider)try{X=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(G){this.onError?.(Error(`Error in shouldFetchFlagDefinitions: ${G}`))}if(!X){if(await this.loadFromCache("Loaded flags from cache (skipped fetch)"))return;if(this.loadedSuccessfullyOnce)return}let Y=await this._requestFeatureFlagDefinitions();if(!Y)return;switch(Y.status){case 304:this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Flags not modified (304), using cached data")),this.flagsEtag=Y.headers?.get("ETag")??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.clearBackoff();return;case 401:throw this.beginBackoff(),new aa(`Your project key or personal API key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 402:console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={};return;case 403:throw this.beginBackoff(),new aa(`Your personal API key does not have permission to fetch feature flag definitions for local evaluation. Setting next polling interval to ${this.getPollingInterval()}ms. Are you sure you're using the correct personal and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.beginBackoff(),new aa(`You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 200:{let G=await Y.json()??{};if(!("flags"in G))return void this.onError?.(Error(`Invalid response when getting feature flags: ${JSON.stringify(G)}`));this.flagsEtag=Y.headers?.get("ETag")??void 0;let Q={flags:G.flags??[],groupTypeMapping:G.group_type_mapping||{},cohorts:G.cohorts||{}};if(this.updateFlagState(Q),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&X)try{await this.cacheProvider.onFlagDefinitionsReceived(Q)}catch(J){this.onError?.(Error(`Failed to store in cache: ${J}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(Q.flags);break}default:return}}catch(X){if(X instanceof aa)this.onError?.(X)}}getPersonalApiKeyRequestOptions(X="GET",Y){let G={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};if(Y)G["If-None-Match"]=Y;return{method:X,headers:G}}_requestFeatureFlagDefinitions(){let X=`${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`,Y=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),G=null;if(this.timeout&&typeof this.timeout=="number"){let Q=new AbortController;G=Kw(()=>{Q.abort()},this.timeout),Y.signal=Q.signal}try{let Q=this.fetch;return Q(X,Y)}finally{clearTimeout(G)}}async stopPoller(X=30000){if(clearTimeout(this.poller),this.cacheProvider)try{let Y=this.cacheProvider.shutdown();if(Y instanceof Promise)await Promise.race([Y,new Promise((G,Q)=>setTimeout(()=>Q(Error(`Cache shutdown timeout after ${X}ms`)),X))])}catch(Y){this.onError?.(Error(`Error during cache shutdown: ${Y}`))}}}async function F04(X,Y,G=""){let Q=await K04(`${X}.${Y}${G}`);return parseInt(Q.slice(0,15),16)/Sn5}function B04(X,Y,G){let{key:Q,value:J}=X,W=X.operator||"exact";if(Q in Y){if(W==="is_not_set")throw new d5("Operator is_not_set is not supported")}else throw new d5(`Property ${Q} not found in propertyValues`);let Z=Y[Q];if(Z==null&&!Cn5.includes(W)){if(G)G(`Property ${Q} cannot have a value of null/undefined with the ${W} operator`);return!1}function $(H,U){if(Array.isArray(H))return H.map((N)=>String(N).toLowerCase()).includes(String(U).toLowerCase());return String(H).toLowerCase()===String(U).toLowerCase()}function K(H,U,N){if(N==="gt")return H>U;if(N==="gte")return H>=U;if(N==="lt")return H<U;if(N==="lte")return H<=U;throw Error(`Invalid operator: ${N}`)}switch(W){case"exact":return $(J,Z);case"is_not":return!$(J,Z);case"is_set":return Q in Y;case"icontains":return String(Z).toLowerCase().includes(String(J).toLowerCase());case"not_icontains":return!String(Z).toLowerCase().includes(String(J).toLowerCase());case"regex":return U04(String(J))&&String(Z).match(String(J))!==null;case"not_regex":return U04(String(J))&&String(Z).match(String(J))===null;case"gt":case"gte":case"lt":case"lte":{let H=typeof J=="number"?J:null;if(typeof J=="string")try{H=parseFloat(J)}catch(U){}if(H==null||Z==null)return K(String(Z),String(J),W);if(typeof Z=="string")return K(Z,String(J),W);return K(Z,H,W)}case"is_date_after":case"is_date_before":{if(typeof J=="boolean")throw new d5("Date operations cannot be performed on boolean values");let H=bn5(String(J));if(H==null)H=N04(J);if(H==null)throw new d5(`Invalid date: ${J}`);let U=N04(Z);if(["is_date_before"].includes(W))return U<H;return U>H}case"semver_eq":return DH(oQ(String(Z)),oQ(String(J)))===0;case"semver_neq":return DH(oQ(String(Z)),oQ(String(J)))!==0;case"semver_gt":return DH(oQ(String(Z)),oQ(String(J)))>0;case"semver_gte":return DH(oQ(String(Z)),oQ(String(J)))>=0;case"semver_lt":return DH(oQ(String(Z)),oQ(String(J)))<0;case"semver_lte":return DH(oQ(String(Z)),oQ(String(J)))<=0;case"semver_tilde":{let H=oQ(String(Z)),{lower:U,upper:N}=vn5(String(J));return DH(H,U)>=0&&DH(H,N)<0}case"semver_caret":{let H=oQ(String(Z)),{lower:U,upper:N}=_n5(String(J));return DH(H,U)>=0&&DH(H,N)<0}case"semver_wildcard":{let H=oQ(String(Z)),{lower:U,upper:N}=fn5(String(J));return DH(H,U)>=0&&DH(H,N)<0}default:throw new d5(`Unknown operator: ${W}`)}}function kn5(X,Y){if(!(X in Y))throw new Gz(`cohort ${X} not found in local cohorts - likely a static cohort that requires server evaluation`)}function z04(X,Y,G,Q=!1){let J=String(X.value);kn5(J,G);let W=G[J];return O04(W,Y,G,Q)}function O04(X,Y,G,Q=!1){if(!X)return!0;let{type:J,values:W}=X;if(!W||W.length===0)return!0;let Z=!1;if("values"in W[0]){for(let $ of W)try{let K=O04($,Y,G,Q);if(J==="AND"){if(!K)return!1}else if(K)return!0}catch(K){if(K instanceof Gz)throw K;if(K instanceof d5){if(Q)console.debug(`Failed to compute property ${$} locally: ${K}`);Z=!0}else throw K}if(Z)throw new d5("Can't match cohort without a given cohort property value");return J==="AND"}for(let $ of W)try{let K;if($.type==="cohort")K=z04($,Y,G,Q);else if($.type==="flag"){if(Q)console.warn(`[FEATURE FLAGS] Flag dependency filters are not supported in local evaluation. Skipping condition with dependency on flag '${$.key||"unknown"}'`);continue}else K=B04($,Y);let H=$.negation||!1;if(J==="AND"){if(!K&&!H)return!1;if(K&&H)return!1}else{if(K&&!H)return!0;if(!K&&H)return!0}}catch(K){if(K instanceof Gz)throw K;if(K instanceof d5){if(Q)console.debug(`Failed to compute property ${$} locally: ${K}`);Z=!0}else throw K}if(Z)throw new d5("can't match cohort without a given cohort property value");return J==="AND"}function U04(X){try{return new RegExp(X),!0}catch(Y){return!1}}function oQ(X){let G=String(X).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!G||G.startsWith("."))throw new d5(`Invalid semver: ${X}`);let Q=G.split("."),J=(K)=>{if(K===void 0||K==="")return 0;if(!/^\d+$/.test(K))throw new d5(`Invalid semver: ${X}`);return parseInt(K,10)},W=J(Q[0]),Z=J(Q[1]),$=J(Q[2]);return[W,Z,$]}function DH(X,Y){for(let G=0;G<3;G++){if(X[G]<Y[G])return-1;if(X[G]>Y[G])return 1}return 0}function vn5(X){let Y=oQ(X),G=[Y[0],Y[1],Y[2]],Q=[Y[0],Y[1]+1,0];return{lower:G,upper:Q}}function _n5(X){let Y=oQ(X),[G,Q,J]=Y,W=[G,Q,J],Z;return Z=G>0?[G+1,0,0]:Q>0?[0,Q+1,0]:[0,0,J+1],{lower:W,upper:Z}}function fn5(X){let G=String(X).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!G)throw new d5(`Invalid wildcard semver: ${X}`);let Q=G.split("."),J=parseInt(Q[0],10);if(isNaN(J))throw new d5(`Invalid wildcard semver: ${X}`);let W,Z;if(Q.length===1)W=[J,0,0],Z=[J+1,0,0];else{let $=parseInt(Q[1],10);if(isNaN($))throw new d5(`Invalid wildcard semver: ${X}`);W=[J,$,0],Z=[J,$+1,0]}return{lower:W,upper:Z}}function N04(X){if(X instanceof Date)return X;if(typeof X=="string"||typeof X=="number"){let Y=new Date(X);if(!isNaN(Y.valueOf()))return Y;throw new d5(`${X} is in an invalid date format`)}throw new d5(`The date provided ${X} must be a string, number, or date object`)}function bn5(X){let Y=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,G=X.match(Y),Q=new Date(new Date().toISOString());if(!G)return null;{if(!G.groups)return null;let J=parseInt(G.groups.number);if(J>=1e4)return null;let W=G.groups.interval;if(W=="h")Q.setUTCHours(Q.getUTCHours()-J);else if(W=="d")Q.setUTCDate(Q.getUTCDate()-J);else if(W=="w")Q.setUTCDate(Q.getUTCDate()-7*J);else if(W=="m")Q.setUTCMonth(Q.getUTCMonth()-J);else{if(W!="y")return null;Q.setUTCFullYear(Q.getUTCFullYear()-J)}return Q}}var Rn5=60000,Sn5=1152921504606847000,Cn5,aa,d5,Gz;var D04=D(()=>{jj();H04();Cn5=["is_not"];aa=class aa extends Error{constructor(X){super();Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=X,Object.setPrototypeOf(this,aa.prototype)}};d5=class d5 extends Error{constructor(X){super(X);this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,d5.prototype)}};Gz=class Gz extends Error{constructor(X){super(X);this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,Gz.prototype)}}});class kB0{getProperty(X){return this._memoryStorage[X]}setProperty(X,Y){this._memoryStorage[X]=Y!==null?Y:void 0}constructor(){this._memoryStorage={}}}var w04=()=>{};function ln5(X){return typeof X=="string"?X.trim():""}function mn5(X){return(typeof X=="string"?X.trim():"")||void 0}function dn5(X){return(typeof X=="string"?X.trim():"")||un5}var yn5=100,L04=30000,xn5=50000,hn5=50,gn5=500,un5="https://us.i.posthog.com",vB0;var E04=D(()=>{$04();jj();SB0();D04();sA1();w04();vB0=class vB0 extends iA1{constructor(X,Y={}){let G=ln5(X),Q={...Y,host:dn5(Y.host),personalApiKey:mn5(Y.personalApiKey)};if(super(G,Q),this._memoryStorage=new kB0,this.options=Q,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof Q.featureFlagsPollingInterval=="number"?Math.max(Q.featureFlagsPollingInterval,yn5):L04,typeof Q.waitUntilDebounceMs=="number")this.options.waitUntilDebounceMs=Math.max(Q.waitUntilDebounceMs,0);if(typeof Q.waitUntilMaxWaitMs=="number")this.options.waitUntilMaxWaitMs=Math.max(Q.waitUntilMaxWaitMs,0);if(Q.personalApiKey){if(Q.personalApiKey.includes("phc_"))throw Error('Your Personal API key is invalid. These keys are prefixed with "phx_" and can be created in PostHog project settings.');if(Q.enableLocalEvaluation!==!1)this.featureFlagsPoller=new CB0({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:Q.personalApiKey,projectApiKey:G,timeout:Q.requestTimeout??1e4,host:this.host,fetch:Q.fetch,onError:(W)=>{this._events.emit("error",W)},onLoad:(W)=>{this._events.emit("localEvaluationFlagsLoaded",W)},customHeaders:this.getCustomHeaders(),cacheProvider:Q.flagDefinitionCacheProvider,strictLocalEvaluation:Q.strictLocalEvaluation})}this.errorTracking=new OH(this,Q,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=Q.maxCacheSize||xn5}enqueue(X,Y,G){super.enqueue(X,Y,G),this.scheduleDebouncedFlush()}async flush(){let X=super.flush(),Y=this.options.waitUntil;if(Y&&!this._waitUntilCycle)try{Y(X.catch(()=>{}))}catch{}return X}scheduleDebouncedFlush(){let X=this.options.waitUntil;if(!X)return;if(this.disabled||this.optedOut)return;if(!this._waitUntilCycle){let W,Z=new Promise(($)=>{W=$});try{X(Z)}catch{return}this._waitUntilCycle={resolve:W,startedAt:Date.now(),timer:void 0}}let Y=Date.now()-this._waitUntilCycle.startedAt,G=this.options.waitUntilMaxWaitMs??gn5,Q=Y>=G;if(this._waitUntilCycle.timer!==void 0)clearTimeout(this._waitUntilCycle.timer);if(Q)return void this.resolveWaitUntilFlush();let J=this.options.waitUntilDebounceMs??hn5;this._waitUntilCycle.timer=Kw(()=>{this.resolveWaitUntilFlush()},J)}_consumeWaitUntilCycle(){let X=this._waitUntilCycle;if(X)clearTimeout(X.timer),this._waitUntilCycle=void 0;return X?.resolve}async resolveWaitUntilFlush(){let X=this._consumeWaitUntilCycle();try{await super.flush()}catch{}finally{X?.()}}getPersistedProperty(X){return this._memoryStorage.getProperty(X)}setPersistedProperty(X,Y){return this._memoryStorage.setProperty(X,Y)}fetch(X,Y){return this.options.fetch?this.options.fetch(X,Y):fetch(X,Y)}getLibraryVersion(){return W04}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}enable(){return super.optIn()}disable(){return super.optOut()}debug(X=!0){super.debug(X),this.featureFlagsPoller?.debug(X)}capture(X){if(typeof X=="string")this._logger.warn("Called capture() with a string as the first argument when an object was expected.");if(X.event==="$exception"&&!X._originatedFromCaptureException)this._logger.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically.");this.addPendingPromise(this.prepareEventMessage(X).then(({distinctId:Y,event:G,properties:Q,options:J})=>super.captureStateless(Y,G,Q,{timestamp:J.timestamp,disableGeoip:J.disableGeoip,uuid:J.uuid})).catch((Y)=>{if(Y)console.error(Y)}))}async captureImmediate(X){if(typeof X=="string")this._logger.warn("Called captureImmediate() with a string as the first argument when an object was expected.");if(X.event==="$exception"&&!X._originatedFromCaptureException)this._logger.warn("Capturing a `$exception` event via `posthog.captureImmediate('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureExceptionImmediate(error)` instead, which attaches this metadata by default.");return this.addPendingPromise(this.prepareEventMessage(X).then(({distinctId:Y,event:G,properties:Q,options:J})=>super.captureStatelessImmediate(Y,G,Q,{timestamp:J.timestamp,disableGeoip:J.disableGeoip,uuid:J.uuid})).catch((Y)=>{if(Y)console.error(Y)}))}identify({distinctId:X,properties:Y={},disableGeoip:G}){let{$set:Q,$set_once:J,$anon_distinct_id:W,...Z}=Y,H={$set:Q||Z,$set_once:J||{},$anon_distinct_id:W??void 0};super.identifyStateless(X,H,{disableGeoip:G})}async identifyImmediate({distinctId:X,properties:Y={},disableGeoip:G}){let{$set:Q,$set_once:J,$anon_distinct_id:W,...Z}=Y,H={$set:Q||Z,$set_once:J||{},$anon_distinct_id:W??void 0};super.identifyStatelessImmediate(X,H,{disableGeoip:G})}alias(X){super.aliasStateless(X.alias,X.distinctId,void 0,{disableGeoip:X.disableGeoip})}async aliasImmediate(X){await super.aliasStatelessImmediate(X.alias,X.distinctId,void 0,{disableGeoip:X.disableGeoip})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}async waitForLocalEvaluationReady(X=L04){if(this.isLocalEvaluationReady())return!0;if(this.featureFlagsPoller===void 0)return!1;return new Promise((Y)=>{let G=setTimeout(()=>{Q(),Y(!1)},X),Q=this._events.on("localEvaluationFlagsLoaded",(J)=>{clearTimeout(G),Q(),Y(J>0)})})}_resolveDistinctId(X,Y){if(typeof X=="string")return{distinctId:X,options:Y};return{distinctId:this.context?.get()?.distinctId,options:X}}async _getFeatureFlagResult(X,Y,G={},Q){let J=G.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&X in this._flagOverrides){let V=this._flagOverrides[X];if(V===void 0)return;let R=this._payloadOverrides?.[X];return{key:X,enabled:V!==!1,variant:typeof V=="string"?V:void 0,payload:R}}let{groups:W,disableGeoip:Z}=G,{onlyEvaluateLocally:$,personProperties:K,groupProperties:H}=G,U=this.addLocalPersonAndGroupProperties(Y,W,K,H);K=U.allPersonProperties,H=U.allGroupProperties;let N=this.createFeatureFlagEvaluationContext(Y,W,K,H);if($==null)$=this.options.strictLocalEvaluation??!1;let B,z=!1,O,w,E,P,q,j;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let V=this.featureFlagsPoller?.featureFlagsByKey[X];if(V)try{let R=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(V,N,{matchValue:Q});if(R){z=!0;let k=R.value;P=V.id,j="Evaluated locally",B={key:X,enabled:k!==!1,variant:typeof k=="string"?k:void 0,payload:R.payload??void 0}}}catch(R){if(R instanceof Gz||R instanceof d5)this._logger?.info(`${R.name} when computing flag locally: ${X}: ${R.message}`);else throw R}}if(!z&&!$){let V=await super.getFeatureFlagDetailsStateless(N.distinctId,N.groups,N.personProperties,N.groupProperties,Z,[X]);if(V===void 0)E=gX1.UNKNOWN_ERROR;else{O=V.requestId,w=V.evaluatedAt;let R=[];if(V.errorsWhileComputingFlags)R.push(gX1.ERRORS_WHILE_COMPUTING);if(V.quotaLimited?.includes("feature_flags"))R.push(gX1.QUOTA_LIMITED);let k=V.flags[X];if(k===void 0)R.push(gX1.FLAG_MISSING);else{P=k.metadata?.id,q=k.metadata?.version,j=k.reason?.description??k.reason?.code;let _;if(k.metadata?.payload!==void 0)try{_=JSON.parse(k.metadata.payload)}catch{_=k.metadata.payload}B={key:X,enabled:k.enabled,variant:k.variant,payload:_}}if(R.length>0)E=R.join(",")}}if(J){let V=B===void 0?void 0:B.enabled===!1?!1:B.variant??!0,R=`${X}_${V}`;if(!(Y in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[Y].includes(R)){if(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize)this.distinctIdHasSentFlagCalls={};if(Array.isArray(this.distinctIdHasSentFlagCalls[Y]))this.distinctIdHasSentFlagCalls[Y].push(R);else this.distinctIdHasSentFlagCalls[Y]=[R];let k={$feature_flag:X,$feature_flag_response:V,$feature_flag_id:P,$feature_flag_version:q,$feature_flag_reason:j,locally_evaluated:z,[`$feature/${X}`]:V,$feature_flag_request_id:O,$feature_flag_evaluated_at:z?Date.now():w};if(z&&this.featureFlagsPoller){let _=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();if(_!==void 0)k.$feature_flag_definitions_loaded_at=_}if(E)k.$feature_flag_error=E;this.capture({distinctId:Y,event:"$feature_flag_called",properties:k,groups:W,disableGeoip:Z})}}if(B!==void 0&&this._payloadOverrides!==void 0&&X in this._payloadOverrides)B={...B,payload:this._payloadOverrides[X]};return B}async getFeatureFlag(X,Y,G){let Q=await this._getFeatureFlagResult(X,Y,{...G,sendFeatureFlagEvents:G?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(Q===void 0)return;if(Q.enabled===!1)return!1;return Q.variant??!0}async getFeatureFlagPayload(X,Y,G,Q){if(this._payloadOverrides!==void 0&&X in this._payloadOverrides)return this._payloadOverrides[X];let J=await this._getFeatureFlagResult(X,Y,{...Q,sendFeatureFlagEvents:!1},G);if(J===void 0)return;return J.payload??null}async getFeatureFlagResult(X,Y,G){let{distinctId:Q,options:J}=this._resolveDistinctId(Y,G);if(!Q)return void this._logger.warn("[PostHog] distinctId is required \u2014 pass it explicitly or use withContext()");return this._getFeatureFlagResult(X,Q,{...J,sendFeatureFlagEvents:J?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0})}async getRemoteConfigPayload(X){if(!this.options.personalApiKey)throw Error("Personal API key is required for remote config payload decryption");let Y=await this._requestRemoteConfigPayload(X);if(!Y)return;let G=await Y.json();if(typeof G=="string")try{return JSON.parse(G)}catch(Q){}return G}async isFeatureEnabled(X,Y,G){let Q=await this.getFeatureFlag(X,Y,G);if(Q===void 0)return;return!!Q||!1}async getAllFlags(X,Y){let{distinctId:G,options:Q}=this._resolveDistinctId(X,Y);if(!G)return this._logger.warn("[PostHog] distinctId is required to get feature flags \u2014 pass it explicitly or use withContext()"),{};return(await this.getAllFlagsAndPayloads(G,Q)).featureFlags||{}}async getAllFlagsAndPayloads(X,Y){let{distinctId:G,options:Q}=this._resolveDistinctId(X,Y);if(!G)return this._logger.warn("[PostHog] distinctId is required to get feature flags and payloads \u2014 pass it explicitly or use withContext()"),{featureFlags:{},featureFlagPayloads:{}};let{groups:J,disableGeoip:W,flagKeys:Z}=Q||{},{onlyEvaluateLocally:$,personProperties:K,groupProperties:H}=Q||{},U=this.addLocalPersonAndGroupProperties(G,J,K,H);K=U.allPersonProperties,H=U.allGroupProperties;let N=this.createFeatureFlagEvaluationContext(G,J,K,H);if($==null)$=this.options.strictLocalEvaluation??!1;let B=await this.featureFlagsPoller?.getAllFlagsAndPayloads(N,Z),z={},O={},w=!0;if(B)z=B.response,O=B.payloads,w=B.fallbackToFlags;if(w&&!$){let E=await super.getFeatureFlagsAndPayloadsStateless(N.distinctId,N.groups,N.personProperties,N.groupProperties,W,Z);z={...z,...E.flags||{}},O={...O,...E.payloads||{}}}if(this._flagOverrides!==void 0)z={...z,...this._flagOverrides};if(this._payloadOverrides!==void 0)O={...O,...this._payloadOverrides};return{featureFlags:z,featureFlagPayloads:O}}groupIdentify({groupType:X,groupKey:Y,properties:G,distinctId:Q,disableGeoip:J}){super.groupIdentifyStateless(X,Y,G,{disableGeoip:J},Q)}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(X){let Y=(G)=>Object.fromEntries(G.map((Q)=>[Q,!0]));if(X===!1){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(X)){this._flagOverrides=Y(X);return}if(this._isFeatureFlagOverrideOptions(X)){if("flags"in X){if(X.flags===!1)this._flagOverrides=void 0;else if(Array.isArray(X.flags))this._flagOverrides=Y(X.flags);else if(X.flags!==void 0)this._flagOverrides={...X.flags}}if("payloads"in X){if(X.payloads===!1)this._payloadOverrides=void 0;else if(X.payloads!==void 0)this._payloadOverrides={...X.payloads}}return}this._flagOverrides={...X}}_isFeatureFlagOverrideOptions(X){if(typeof X!="object"||X===null||Array.isArray(X))return!1;let Y=X;if("flags"in Y){let G=Y.flags;if(G===!1||Array.isArray(G)||typeof G=="object"&&G!==null)return!0}if("payloads"in Y){let G=Y.payloads;if(G===!1||typeof G=="object"&&G!==null)return!0}return!1}withContext(X,Y,G){if(!this.context)return Y();return this.context.run(X,Y,G)}getContext(){return this.context?.get()}enterContext(X,Y){this.context?.enter(X,Y)}async _shutdown(X){let Y=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller(X),this.errorTracking.shutdown();try{return await super._shutdown(X)}finally{Y?.()}}async _requestRemoteConfigPayload(X){if(!this.options.personalApiKey)return;let Y=`${this.host}/api/projects/@current/feature_flags/${X}/remote_config?token=${encodeURIComponent(this.apiKey)}`,G={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},Q=null;if(this.options.requestTimeout&&typeof this.options.requestTimeout=="number"){let J=new AbortController;Q=Kw(()=>{J.abort()},this.options.requestTimeout),G.signal=J.signal}try{return await this.fetch(Y,G)}catch(J){this._events.emit("error",J);return}finally{if(Q)clearTimeout(Q)}}extractPropertiesFromEvent(X,Y){if(!X)return{personProperties:{},groupProperties:{}};let G={},Q={};for(let[J,W]of Object.entries(X))if(ke6(W)&&Y&&J in Y){let Z={};for(let[$,K]of Object.entries(W))Z[String($)]=String(K);Q[String(J)]=Z}else G[String(J)]=String(W);return{personProperties:G,groupProperties:Q}}async getFeatureFlagsForEvent(X,Y,G,Q){let J=Q?.personProperties||{},W=Q?.groupProperties||{},Z=Q?.flagKeys;if(Q?.onlyEvaluateLocally??this.options.strictLocalEvaluation??!1)if(!((this.featureFlagsPoller?.featureFlags?.length||0)>0))return{};else{let K={};for(let[H,U]of Object.entries(Y||{}))K[H]=String(U);return await this.getAllFlags(X,{groups:K,personProperties:J,groupProperties:W,disableGeoip:G,onlyEvaluateLocally:!0,flagKeys:Z})}if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let K={};for(let[H,U]of Object.entries(Y||{}))K[H]=String(U);return await this.getAllFlags(X,{groups:K,personProperties:J,groupProperties:W,disableGeoip:G,onlyEvaluateLocally:!0,flagKeys:Z})}return(await super.getFeatureFlagsStateless(X,Y,J,W,G)).flags}addLocalPersonAndGroupProperties(X,Y,G,Q){let J={distinct_id:X,...G||{}},W={};if(Y)for(let Z of Object.keys(Y))W[Z]={$group_key:Y[Z],...Q?.[Z]||{}};return{allPersonProperties:J,allGroupProperties:W}}createFeatureFlagEvaluationContext(X,Y,G,Q){return{distinctId:X,groups:Y||{},personProperties:G||{},groupProperties:Q||{},evaluationCache:{}}}captureException(X,Y,G,Q){if(!OH.isPreviouslyCapturedError(X)){let J=Error("PostHog syntheticException");this.addPendingPromise(OH.buildEventMessage(X,{syntheticException:J},Y,G).then((W)=>this.capture({...W,uuid:Q})))}}async captureExceptionImmediate(X,Y,G){if(!OH.isPreviouslyCapturedError(X)){let Q=Error("PostHog syntheticException");return this.addPendingPromise(OH.buildEventMessage(X,{syntheticException:Q},Y,G).then((J)=>this.captureImmediate(J)))}}async prepareEventMessage(X){let{distinctId:Y,event:G,properties:Q,groups:J,sendFeatureFlags:W,timestamp:Z,disableGeoip:$,uuid:K}=X,H=this.context?.get(),U=Y||H?.distinctId,N={...this.props,...H?.properties||{},...Q||{}};if(!U)U=Aq(),N.$process_person_profile=!1;if(H?.sessionId&&!N.$session_id)N.$session_id=H.sessionId;let B=this._runBeforeSend({distinctId:U,event:G,properties:N,groups:J,sendFeatureFlags:W,timestamp:Z,disableGeoip:$,uuid:K});if(!B)return Promise.reject(null);let z=await Promise.resolve().then(async()=>{if(W){let O=typeof W=="object"?W:void 0;return await this.getFeatureFlagsForEvent(B.distinctId,J,$,O)}return B.event,{}}).then((O)=>{let w={};if(O)for(let[P,q]of Object.entries(O))w[`$feature/${P}`]=q;let E=Object.keys(O||{}).filter((P)=>O?.[P]!==!1).sort();if(E.length>0)w.$active_feature_flags=E;return w}).catch(()=>({})).then((O)=>{return{...O,...B.properties||{},$groups:B.groups||J}});if(B.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof z.$raw_user_agent=="string"){if(je6(z.$raw_user_agent,this.options.custom_blocked_useragents||[]))B.event="$bot_pageview",z.$browser_type="bot"}return{distinctId:B.distinctId,event:B.event,properties:z,options:{timestamp:B.timestamp,disableGeoip:B.disableGeoip,uuid:B.uuid}}}_runBeforeSend(X){let Y=this.options.before_send;if(!Y)return X;let G=Array.isArray(Y)?Y:[Y],Q=X;for(let J of G){if(Q=J(Q),!Q)return this._logger.info(`Event '${X.event}' was rejected in beforeSend function`),null;if(!Q.properties||Object.keys(Q.properties).length===0){let W=`Event '${Q.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(W)}}return Q}}});import{AsyncLocalStorage as cn5}from"async_hooks";class _B0{constructor(){this.storage=new cn5}get(){return this.storage.getStore()}run(X,Y,G){return this.storage.run(this.resolve(X,G),Y)}enter(X,Y){this.storage.enterWith(this.resolve(X,Y))}resolve(X,Y){if(Y?.fresh===!0)return X;let G=this.get()||{};return{distinctId:X.distinctId??G.distinctId,sessionId:X.sessionId??G.sessionId,properties:{...G.properties||{},...X.properties||{}}}}}var P04=()=>{};function in5(X,{organization:Y,projectId:G,prefix:Q,severityAllowList:J=["error"],sendExceptionsToPostHog:W=!0}={}){return(Z)=>{if(!(J==="*"||J.includes(Z.level)))return Z;if(!Z.tags)Z.tags={};let K=Z.tags[q04.POSTHOG_ID_TAG];if(K===void 0)return Z;let H=X.options.host??"https://us.i.posthog.com",U=new URL(`/project/${X.apiKey}/person/${K}`,H).toString();Z.tags["PostHog Person URL"]=U;let N=Z.exception?.values||[],B=N.map((O)=>({...O,stacktrace:O.stacktrace?{...O.stacktrace,type:"raw",frames:(O.stacktrace.frames||[]).map((w)=>({...w,platform:"node:javascript"}))}:void 0})),z={$exception_message:N[0]?.value||Z.message,$exception_type:N[0]?.type,$exception_level:Z.level,$exception_list:B,$sentry_event_id:Z.event_id,$sentry_exception:Z.exception,$sentry_exception_message:N[0]?.value||Z.message,$sentry_exception_type:N[0]?.type,$sentry_tags:Z.tags};if(Y&&G)z.$sentry_url=(Q||"https://sentry.io/organizations/")+Y+"/issues/?project="+G+"&query="+Z.event_id;if(W)X.capture({event:"$exception",distinctId:K,properties:z});return Z}}var q04;var A04=D(()=>{q04=class q04{static#X=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(X,Y,G,Q,J){this.name="posthog-node",this.name="posthog-node",this.setupOnce=function(W,Z){let $=Z()?.getClient()?.getDsn()?.projectId;W(in5(X,{organization:Y,projectId:$,prefix:G,severityAllowList:Q,sendExceptionsToPostHog:J??!0}))}}}});var T04=D(()=>{sA1()});var I04=D(()=>{jj();A04();T04();SB0()});var fB0;var V04=D(()=>{Ae6();X04();G04();sA1();E04();jj();P04();I04();OH.errorPropertiesBuilder=new PW.ErrorPropertiesBuilder([new PW.EventCoercer,new PW.ErrorCoercer,new PW.ObjectCoercer,new PW.StringCoercer,new PW.PrimitiveCoercer],PW.createStackParser("node:javascript",PW.nodeStackLineParser),[qe6(),o14,Y04()]);fB0=class fB0 extends vB0{getLibraryId(){return"posthog-node"}initializeContext(){return new _B0}}});function pn5(){return{capture:()=>{},identify:()=>{},captureException:()=>{},groupIdentify:()=>{},shutdown:async()=>{}}}var bB0,j04,j4;var RX=D(()=>{V04();bB0=process.env.POSTHOG_KEY,j04=process.env.POSTHOG_HOST;j4=bB0?new fB0(bB0,{...j04?{host:j04}:{},enableExceptionAutocapture:!0,flushAt:1,flushInterval:0}):pn5();if(bB0){let X=()=>{j4.shutdown().catch(()=>{})};process.on("SIGTERM",X),process.on("SIGINT",X)}});function g$(){let X=v6();if(X.baseUrl)return X.baseUrl;return`http://localhost:${X.port??3000}`}function uX1(){return`http://localhost:${v6().port??3000}`}var Hw=D(()=>{m9()});var M04=D(()=>{RV()});function R04(X){return{organizationId:X.organization_id,domain:X.domain,autoJoinEnabled:X.auto_join_enabled,createdAt:X.created_at,updatedAt:X.updated_at}}class Fw{db;constructor(X){this.db=X}async getByDomain(X){let Y=await this.db.selectFrom("organization_domains").selectAll().where("domain","=",X.toLowerCase()).executeTakeFirst();return Y?R04(Y):null}async getByOrganizationId(X){let Y=await this.db.selectFrom("organization_domains").selectAll().where("organization_id","=",X).executeTakeFirst();return Y?R04(Y):null}async setDomain(X,Y,G=!1){let Q=new Date().toISOString(),J=Y.toLowerCase();try{await this.db.insertInto("organization_domains").values({organization_id:X,domain:J,auto_join_enabled:G,created_at:Q,updated_at:Q}).onConflict((Z)=>Z.column("organization_id").doUpdateSet({domain:J,auto_join_enabled:G,updated_at:Q})).execute()}catch(Z){if(Z.code==="23505")throw Error(`Domain "${J}" is already claimed by another organization.`);throw Z}let W=await this.getByOrganizationId(X);if(!W)throw Error("Failed to set domain");return W}async updateAutoJoin(X,Y){let G=new Date().toISOString();await this.db.updateTable("organization_domains").set({auto_join_enabled:Y,updated_at:G}).where("organization_id","=",X).execute();let Q=await this.getByOrganizationId(X);if(!Q)throw Error("No domain found for organization");return Q}async clearDomain(X){await this.db.deleteFrom("organization_domains").where("organization_id","=",X).execute()}}class yB0{apiKey;constructor(X){this.apiKey=X}async sendEmail({to:X,from:Y,subject:G,html:Q}){let J=await fetch("https://api.resend.com/emails",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({to:X,from:Y,subject:G,html:Q})});if(!J.ok)throw Error(`Failed to send email: ${J.statusText}`)}}class xB0{apiKey;constructor(X){this.apiKey=X}async sendEmail({to:X,from:Y,subject:G,html:Q}){let J=await fetch("https://api.sendgrid.com/v3/mail/send",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({personalizations:[{to:[{email:X}]}],from:{email:Y},subject:G,content:[{type:"text/html",value:Q}]})});if(!J.ok){let W=await J.text();throw Error(`Failed to send email via SendGrid: ${J.statusText} - ${W}`)}}}function Mj(X){let Y=tn5[X.provider];if(!Y)throw Error(`Unknown email provider: ${X.provider}`);return Y(X)}function Rj(X,Y){return X.find((G)=>G.id===Y)}var nn5=(X)=>{let Y=new yB0(X.config.apiKey);return async({to:G,subject:Q,html:J})=>{await Y.sendEmail({to:G,from:X.config.fromEmail,subject:Q,html:J})}},an5=(X)=>{let Y=new xB0(X.config.apiKey);return async({to:G,subject:Q,html:J})=>{await Y.sendEmail({to:G,from:X.config.fromEmail,subject:Q,html:J})}},tn5;var eA1=D(()=>{tn5={resend:nn5,sendgrid:an5}});function Sj({preheader:X="",heading:Y,subheading:G,body:Q,footnote:J}){return`<!DOCTYPE html>
|
|
1641
1641
|
<html lang="en">
|
|
1642
1642
|
<head>
|