@hexclave/cli 1.0.20 → 1.0.21
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/dashboard/apps/dashboard/.next/BUILD_ID +1 -1
- package/dist/dashboard/apps/dashboard/.next/build-manifest.json +5 -5
- package/dist/dashboard/apps/dashboard/.next/prerender-manifest.json +3 -3
- package/dist/dashboard/apps/dashboard/.next/required-server-files.json +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/(outside-dashboard)/new-project/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/(outside-dashboard)/new-project/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/(outside-dashboard)/playground/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/(outside-dashboard)/playground/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/(outside-dashboard)/projects/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/(outside-dashboard)/projects/page/server-reference-manifest.json +3 -3
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/(outside-dashboard)/projects/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/-selector-/[...path]/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/-selector-/[...path]/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/(overview)/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/(overview)/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/@modal/(.)apps/[appId]/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/@modal/(.)apps/[appId]/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/analytics/clickmaps/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/analytics/clickmaps/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/analytics/overview/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/analytics/overview/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/analytics/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/analytics/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/analytics/queries/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/analytics/queries/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/analytics/tables/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/analytics/tables/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/api-keys/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/api-keys/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/api-keys-app/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/api-keys-app/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/apps/[appId]/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/apps/[appId]/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/apps/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/apps/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/auth-methods/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/auth-methods/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/conversations/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/conversations/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/convex/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/convex/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/dashboards/[dashboardId]/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/dashboards/[dashboardId]/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/dashboards/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/dashboards/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/data-vault/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/data-vault/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/data-vault/stores/[storeId]/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/data-vault/stores/[storeId]/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/data-vault/stores/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/data-vault/stores/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/design-language/chart-demo/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/design-language/chart-demo/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/design-language/datagrid-demo/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/design-language/datagrid-demo/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/design-language/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/design-language/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/design-language/realistic-demo/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/design-language/realistic-demo/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/domains/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/domains/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/email-drafts/[draftId]/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/email-drafts/[draftId]/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/email-drafts/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/email-drafts/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/email-outbox/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/email-outbox/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/email-sent/no-source/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/email-sent/no-source/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/email-sent/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/email-sent/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/email-settings/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/email-settings/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/email-templates/[templateId]/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/email-templates/[templateId]/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/email-templates/[templateId]/sent/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/email-templates/[templateId]/sent/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/email-templates/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/email-templates/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/email-themes/[themeId]/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/email-themes/[themeId]/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/email-themes/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/email-themes/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/email-viewer/[emailId]/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/email-viewer/[emailId]/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/emails/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/emails/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/expert-mode/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/expert-mode/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/external-db-sync/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/external-db-sync/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/launch-checklist/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/launch-checklist/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/onboarding/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/onboarding/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/payments/customers/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/payments/customers/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/payments/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/payments/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/payments/payouts/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/payments/payouts/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/payments/product-lines/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/payments/product-lines/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/payments/products/[productId]/edit/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/payments/products/[productId]/edit/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/payments/products/[productId]/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/payments/products/[productId]/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/payments/products/new/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/payments/products/new/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/payments/products/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/payments/products/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/payments/settings/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/payments/settings/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/payments/transactions/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/payments/transactions/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/project-keys/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/project-keys/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/project-permissions/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/project-permissions/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/project-settings/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/project-settings/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/query-analytics/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/query-analytics/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/session-replays/[replayId]/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/session-replays/[replayId]/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/session-replays/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/session-replays/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/sign-up-rules/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/sign-up-rules/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/support/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/support/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/team-permissions/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/team-permissions/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/team-settings/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/team-settings/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/teams/[teamId]/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/teams/[teamId]/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/teams/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/teams/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/users/[userId]/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/users/[userId]/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/users/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/users/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/vercel/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/vercel/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/webhooks/[endpointId]/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/webhooks/[endpointId]/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/webhooks/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/webhooks/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/widget-playground/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/(protected)/projects/[projectId]/widget-playground/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/handler/[...hexclave]/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/handler/[...hexclave]/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/integrations/custom/confirm/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/integrations/custom/confirm/page/server-reference-manifest.json +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/integrations/custom/confirm/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/integrations/custom/projects/transfer/confirm/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/integrations/custom/projects/transfer/confirm/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/integrations/featurebase/sso/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/integrations/featurebase/sso/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/integrations/neon/confirm/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/integrations/neon/confirm/page/server-reference-manifest.json +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/integrations/neon/confirm/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/integrations/neon/projects/transfer/confirm/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/integrations/neon/projects/transfer/confirm/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/purchase/[code]/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/purchase/[code]/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/purchase/return/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/purchase/return/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/wizard-congrats/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/(main)/wizard-congrats/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/_global-error/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/_global-error.html +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/_global-error.rsc +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/_not-found/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/_not-found.html +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/_not-found.rsc +16 -16
- package/dist/dashboard/apps/dashboard/.next/server/app/_not-found.segments/_full.segment.rsc +16 -16
- package/dist/dashboard/apps/dashboard/.next/server/app/_not-found.segments/_head.segment.rsc +4 -4
- package/dist/dashboard/apps/dashboard/.next/server/app/_not-found.segments/_index.segment.rsc +10 -10
- package/dist/dashboard/apps/dashboard/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +4 -4
- package/dist/dashboard/apps/dashboard/.next/server/app/_not-found.segments/_not-found.segment.rsc +3 -3
- package/dist/dashboard/apps/dashboard/.next/server/app/_not-found.segments/_tree.segment.rsc +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/development-environment/browser-secret/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/development-environment/browser-secret/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/development-environment/browser-secret.html +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/development-environment/browser-secret.rsc +16 -16
- package/dist/dashboard/apps/dashboard/.next/server/app/development-environment/browser-secret.segments/_full.segment.rsc +16 -16
- package/dist/dashboard/apps/dashboard/.next/server/app/development-environment/browser-secret.segments/_head.segment.rsc +4 -4
- package/dist/dashboard/apps/dashboard/.next/server/app/development-environment/browser-secret.segments/_index.segment.rsc +10 -10
- package/dist/dashboard/apps/dashboard/.next/server/app/development-environment/browser-secret.segments/_tree.segment.rsc +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/development-environment/browser-secret.segments/development-environment/browser-secret/__PAGE__.segment.rsc +3 -3
- package/dist/dashboard/apps/dashboard/.next/server/app/development-environment/browser-secret.segments/development-environment/browser-secret.segment.rsc +3 -3
- package/dist/dashboard/apps/dashboard/.next/server/app/development-environment/browser-secret.segments/development-environment.segment.rsc +3 -3
- package/dist/dashboard/apps/dashboard/.next/server/app/health/error-handler-debug/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/health/error-handler-debug/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/health/error-handler-debug.html +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/health/error-handler-debug.rsc +17 -17
- package/dist/dashboard/apps/dashboard/.next/server/app/health/error-handler-debug.segments/_full.segment.rsc +17 -17
- package/dist/dashboard/apps/dashboard/.next/server/app/health/error-handler-debug.segments/_head.segment.rsc +4 -4
- package/dist/dashboard/apps/dashboard/.next/server/app/health/error-handler-debug.segments/_index.segment.rsc +10 -10
- package/dist/dashboard/apps/dashboard/.next/server/app/health/error-handler-debug.segments/_tree.segment.rsc +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/health/error-handler-debug.segments/health/error-handler-debug/__PAGE__.segment.rsc +4 -4
- package/dist/dashboard/apps/dashboard/.next/server/app/health/error-handler-debug.segments/health/error-handler-debug.segment.rsc +3 -3
- package/dist/dashboard/apps/dashboard/.next/server/app/health/error-handler-debug.segments/health.segment.rsc +3 -3
- package/dist/dashboard/apps/dashboard/.next/server/app/index.html +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/index.rsc +15 -15
- package/dist/dashboard/apps/dashboard/.next/server/app/index.segments/!KG1haW4p/__PAGE__.segment.rsc +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/index.segments/!KG1haW4p.segment.rsc +4 -4
- package/dist/dashboard/apps/dashboard/.next/server/app/index.segments/_full.segment.rsc +15 -15
- package/dist/dashboard/apps/dashboard/.next/server/app/index.segments/_head.segment.rsc +4 -4
- package/dist/dashboard/apps/dashboard/.next/server/app/index.segments/_index.segment.rsc +10 -10
- package/dist/dashboard/apps/dashboard/.next/server/app/index.segments/_tree.segment.rsc +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/new-project.html +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/new-project.rsc +19 -19
- package/dist/dashboard/apps/dashboard/.next/server/app/new-project.segments/!KG1haW4p/!KHByb3RlY3RlZCk/!KG91dHNpZGUtZGFzaGJvYXJkKQ/new-project/__PAGE__.segment.rsc +3 -3
- package/dist/dashboard/apps/dashboard/.next/server/app/new-project.segments/!KG1haW4p/!KHByb3RlY3RlZCk/!KG91dHNpZGUtZGFzaGJvYXJkKQ/new-project.segment.rsc +3 -3
- package/dist/dashboard/apps/dashboard/.next/server/app/new-project.segments/!KG1haW4p/!KHByb3RlY3RlZCk/!KG91dHNpZGUtZGFzaGJvYXJkKQ.segment.rsc +5 -5
- package/dist/dashboard/apps/dashboard/.next/server/app/new-project.segments/!KG1haW4p/!KHByb3RlY3RlZCk.segment.rsc +4 -4
- package/dist/dashboard/apps/dashboard/.next/server/app/new-project.segments/!KG1haW4p.segment.rsc +4 -4
- package/dist/dashboard/apps/dashboard/.next/server/app/new-project.segments/_full.segment.rsc +19 -19
- package/dist/dashboard/apps/dashboard/.next/server/app/new-project.segments/_head.segment.rsc +4 -4
- package/dist/dashboard/apps/dashboard/.next/server/app/new-project.segments/_index.segment.rsc +10 -10
- package/dist/dashboard/apps/dashboard/.next/server/app/new-project.segments/_tree.segment.rsc +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/playground.html +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/playground.rsc +19 -19
- package/dist/dashboard/apps/dashboard/.next/server/app/playground.segments/!KG1haW4p/!KHByb3RlY3RlZCk/!KG91dHNpZGUtZGFzaGJvYXJkKQ/playground/__PAGE__.segment.rsc +3 -3
- package/dist/dashboard/apps/dashboard/.next/server/app/playground.segments/!KG1haW4p/!KHByb3RlY3RlZCk/!KG91dHNpZGUtZGFzaGJvYXJkKQ/playground.segment.rsc +3 -3
- package/dist/dashboard/apps/dashboard/.next/server/app/playground.segments/!KG1haW4p/!KHByb3RlY3RlZCk/!KG91dHNpZGUtZGFzaGJvYXJkKQ.segment.rsc +5 -5
- package/dist/dashboard/apps/dashboard/.next/server/app/playground.segments/!KG1haW4p/!KHByb3RlY3RlZCk.segment.rsc +4 -4
- package/dist/dashboard/apps/dashboard/.next/server/app/playground.segments/!KG1haW4p.segment.rsc +4 -4
- package/dist/dashboard/apps/dashboard/.next/server/app/playground.segments/_full.segment.rsc +19 -19
- package/dist/dashboard/apps/dashboard/.next/server/app/playground.segments/_head.segment.rsc +4 -4
- package/dist/dashboard/apps/dashboard/.next/server/app/playground.segments/_index.segment.rsc +10 -10
- package/dist/dashboard/apps/dashboard/.next/server/app/playground.segments/_tree.segment.rsc +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/projects.html +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/projects.rsc +19 -19
- package/dist/dashboard/apps/dashboard/.next/server/app/projects.segments/!KG1haW4p/!KHByb3RlY3RlZCk/!KG91dHNpZGUtZGFzaGJvYXJkKQ/projects/__PAGE__.segment.rsc +3 -3
- package/dist/dashboard/apps/dashboard/.next/server/app/projects.segments/!KG1haW4p/!KHByb3RlY3RlZCk/!KG91dHNpZGUtZGFzaGJvYXJkKQ/projects.segment.rsc +3 -3
- package/dist/dashboard/apps/dashboard/.next/server/app/projects.segments/!KG1haW4p/!KHByb3RlY3RlZCk/!KG91dHNpZGUtZGFzaGJvYXJkKQ.segment.rsc +5 -5
- package/dist/dashboard/apps/dashboard/.next/server/app/projects.segments/!KG1haW4p/!KHByb3RlY3RlZCk.segment.rsc +4 -4
- package/dist/dashboard/apps/dashboard/.next/server/app/projects.segments/!KG1haW4p.segment.rsc +4 -4
- package/dist/dashboard/apps/dashboard/.next/server/app/projects.segments/_full.segment.rsc +19 -19
- package/dist/dashboard/apps/dashboard/.next/server/app/projects.segments/_head.segment.rsc +4 -4
- package/dist/dashboard/apps/dashboard/.next/server/app/projects.segments/_index.segment.rsc +10 -10
- package/dist/dashboard/apps/dashboard/.next/server/app/projects.segments/_tree.segment.rsc +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/rde-debug/page/build-manifest.json +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/rde-debug/page_client-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/app/wizard-congrats.html +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/app/wizard-congrats.rsc +20 -20
- package/dist/dashboard/apps/dashboard/.next/server/app/wizard-congrats.segments/!KG1haW4p/wizard-congrats/__PAGE__.segment.rsc +6 -6
- package/dist/dashboard/apps/dashboard/.next/server/app/wizard-congrats.segments/!KG1haW4p/wizard-congrats.segment.rsc +3 -3
- package/dist/dashboard/apps/dashboard/.next/server/app/wizard-congrats.segments/!KG1haW4p.segment.rsc +4 -4
- package/dist/dashboard/apps/dashboard/.next/server/app/wizard-congrats.segments/_full.segment.rsc +20 -20
- package/dist/dashboard/apps/dashboard/.next/server/app/wizard-congrats.segments/_head.segment.rsc +4 -4
- package/dist/dashboard/apps/dashboard/.next/server/app/wizard-congrats.segments/_index.segment.rsc +10 -10
- package/dist/dashboard/apps/dashboard/.next/server/app/wizard-congrats.segments/_tree.segment.rsc +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/chunks/[root-of-the-server]__1m-q0b3._.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/chunks/_04as7p-._.js +22 -22
- package/dist/dashboard/apps/dashboard/.next/server/chunks/_0tnctfw._.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/chunks/node_modules__pnpm_1_a837b._.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/chunks/packages_0rk1u8f._.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/chunks/packages_1eprmn6._.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/chunks/ssr/044u_dashboard_src_app_(main)_(protected)_projects_[projectId]_email-sent_06e1zir._.js +9 -0
- package/dist/dashboard/apps/dashboard/.next/server/chunks/ssr/044u_dashboard_src_app_(main)_(protected)_projects_[projectId]_email-sent_18ofnte._.js +9 -0
- package/dist/dashboard/apps/dashboard/.next/server/chunks/ssr/15dq_(main)_(protected)_projects_[projectId]_users_[userId]_page-client_tsx_0ptfo2h._.js +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/chunks/ssr/[root-of-the-server]__0fiuqqk._.js +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/chunks/ssr/_05oib0d._.js +3 -0
- package/dist/dashboard/apps/dashboard/.next/server/chunks/ssr/_0s_ag9o._.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/chunks/ssr/_0xl4mrg._.js +3 -3
- package/dist/dashboard/apps/dashboard/.next/server/chunks/ssr/_1-axnoc._.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/chunks/ssr/_132pp19._.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/chunks/ssr/_1gqr2d9._.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/chunks/ssr/_1jp05wg._.js +3 -0
- package/dist/dashboard/apps/dashboard/.next/server/chunks/ssr/_1q7j2d7._.js +5 -5
- package/dist/dashboard/apps/dashboard/.next/server/chunks/ssr/_1wwwu_3._.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/chunks/ssr/_1z655xf._.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/chunks/ssr/apps_dashboard_src_components_dashboard-user-button_tsx_1m9znfy._.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/chunks/ssr/node_modules__pnpm_0cfdzin._.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/chunks/ssr/packages_0kveln1._.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/chunks/ssr/packages_1r7flhi._.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/middleware-build-manifest.js +5 -5
- package/dist/dashboard/apps/dashboard/.next/server/pages/404.html +2 -2
- package/dist/dashboard/apps/dashboard/.next/server/pages/500.html +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/server-reference-manifest.js +1 -1
- package/dist/dashboard/apps/dashboard/.next/server/server-reference-manifest.json +5 -5
- package/dist/dashboard/apps/dashboard/.next/static/chunks/{2djrn7poti_fw.js → 0-cvg3igufvd6.js} +2 -2
- package/dist/dashboard/apps/dashboard/.next/static/chunks/{4079rt6gkozmp.js → 0n_amwdwnr5qv.js} +1 -1
- package/dist/dashboard/apps/dashboard/.next/static/chunks/{1c9um9pw7riw0.js → 0n_xejiuv6hi3.js} +2 -2
- package/dist/dashboard/apps/dashboard/.next/static/chunks/0nwiy21paqdxk.js +9 -0
- package/dist/dashboard/apps/dashboard/.next/static/chunks/{41e2zx2dgkq1w.js → 0x24ip8d8uywa.js} +2 -2
- package/dist/dashboard/apps/dashboard/.next/static/chunks/{2zkv3tg8lrss9.js → 1_3_bf5h-idt6.js} +1 -1
- package/dist/dashboard/apps/dashboard/.next/static/chunks/1fvvqk0r2b0xi.css +1 -0
- package/dist/dashboard/apps/dashboard/.next/static/chunks/{1g7ocjd1h6op9.js → 1iz1z3p9tjgbd.js} +2 -2
- package/dist/dashboard/apps/dashboard/.next/static/chunks/{1yis25nn36osv.js → 1l5uzgfyrdupp.js} +5 -5
- package/dist/dashboard/apps/dashboard/.next/static/chunks/{2qgng6gut-lpo.js → 2-bdllt91-l80.js} +1 -1
- package/dist/dashboard/apps/dashboard/.next/static/chunks/{3bo2ua_y4q43v.js → 2envmrg1f61w5.js} +3 -3
- package/dist/dashboard/apps/dashboard/.next/static/chunks/{0_k8aohi1d6c5.js → 2rtuock2-guiu.js} +1 -1
- package/dist/dashboard/apps/dashboard/.next/static/chunks/{3d-5wrlqx-xi5.js → 2vif9i05n-kbh.js} +2 -2
- package/dist/dashboard/apps/dashboard/.next/static/chunks/{0al4rf0wulms6.js → 2xzp981upsrrz.js} +4 -4
- package/dist/dashboard/apps/dashboard/.next/static/chunks/{3yr78v6baa_dn.js → 3kqlh2r279xvm.js} +1 -1
- package/dist/dashboard/apps/dashboard/.next/static/chunks/{0nd-d9_e0czkl.js → 3x2nrm-cfkt_s.js} +1 -1
- package/dist/dashboard/apps/dashboard/.next/static/chunks/{2u4zmrk36sq5y.js → 3xy61pxy24_4d.js} +1 -1
- package/dist/dashboard/apps/dashboard/.next/static/chunks/{turbopack-425k_ofsbf1gw.js → turbopack-2t16bx-7bi0_i.js} +1 -1
- package/dist/dashboard/apps/dashboard/package.json +1 -1
- package/dist/dashboard/apps/dashboard/server.js +1 -1
- package/dist/index.js +39 -15
- package/dist/index.js.map +1 -1
- package/package.json +4 -4
- package/src/commands/dev.ts +49 -10
- package/dist/dashboard/apps/dashboard/.next/server/chunks/ssr/044u_dashboard_src_app_(main)_(protected)_projects_[projectId]_email-sent_07k2db_._.js +0 -9
- package/dist/dashboard/apps/dashboard/.next/server/chunks/ssr/_0lvurax._.js +0 -9
- package/dist/dashboard/apps/dashboard/.next/server/chunks/ssr/_1_40imk._.js +0 -3
- package/dist/dashboard/apps/dashboard/.next/static/chunks/0z4wcrkw_j19e.js +0 -9
- package/dist/dashboard/apps/dashboard/.next/static/chunks/3kqudwiyy5y1a.css +0 -1
- /package/dist/dashboard/apps/dashboard/.next/static/{B9KRozRzmPbGbXUg8svB2 → dLM871duwxsKII1or2IEw}/_buildManifest.js +0 -0
- /package/dist/dashboard/apps/dashboard/.next/static/{B9KRozRzmPbGbXUg8svB2 → dLM871duwxsKII1or2IEw}/_clientMiddlewareManifest.js +0 -0
- /package/dist/dashboard/apps/dashboard/.next/static/{B9KRozRzmPbGbXUg8svB2 → dLM871duwxsKII1or2IEw}/_ssgManifest.js +0 -0
|
@@ -345,29 +345,29 @@ ${o}`)};let i=new Set},"./node_modules/.pnpm/@babel+types@7.28.4/node_modules/@b
|
|
|
345
345
|
`},wrapReference(t,r){if("lazy/function"===r)return n.types.callExpression(t,[])}}))},visitor:{["CallExpression"+(t.types.importExpression?"|ImportExpression":"")](t){var r;if(t.isCallExpression()&&!n.types.isImport(t.node.callee))return;let{scope:i}=t;do i.rename("require");while(i=i.parent)r=this.file,t.replaceWith((0,tR.buildDynamicImport)(t.node,!0,!1,t=>{let i;return i=n.template.expression.ast`jitiImport(${t})`,p?i:n.types.callExpression(n.types.memberExpression(i,n.types.identifier("then")),[n.types.arrowFunctionExpression([n.types.identifier("m")],n.types.callExpression(r.addHelper("interopRequireWildcard"),[n.types.identifier("m")]))])}))},Program:{exit(t,h){let g;if(!(0,tL.isModule)(t))return;t.scope.rename("exports"),t.scope.rename("module"),t.scope.rename("require"),t.scope.rename("__filename"),t.scope.rename("__dirname"),d||(process.env.BABEL_8_BREAKING?(0,tM.default)(t,new Set(["module","exports"])):(0,tM.default)(t,new Set(["module","exports"]),!1),t.traverse(v,{scope:t.scope}));let x=(0,tR.getModuleName)(this.file.opts,r);x&&(x=n.types.stringLiteral(x));let T=(g=this.file.get(tF),{getWrapperPayload:(...t)=>tB(g,r=>r.getWrapperPayload?.(...t)),wrapReference:(...t)=>tB(g,r=>r.wrapReference?.(...t)),buildRequireWrapper:(...t)=>tB(g,r=>r.buildRequireWrapper?.(...t))}),{meta:E,headers:S}=(0,tR.rewriteModuleStatementsAndPrepareHeader)(t,{exportName:"exports",constantReexports:m,enumerableModuleMeta:y,strict:o,strictMode:l,allowTopLevelThis:a,noInterop:p,importInterop:u,wrapReference:T.wrapReference,getWrapperPayload:T.getWrapperPayload,esNamespaceOnly:"string"==typeof h.filename&&/\.mjs$/.test(h.filename)?s:i,noIncompleteNsImportDetection:b,filename:this.file.opts.filename});for(let[r,i]of E.source){let s,a=f?n.types.awaitExpression(n.types.callExpression(n.types.identifier("jitiImport"),[n.types.stringLiteral(r)])):n.types.callExpression(n.types.identifier("require"),[n.types.stringLiteral(r)]);if((0,tR.isSideEffectImport)(i)){if(c&&"function"===i.wrap)throw Error("Assertion failure");s=n.types.expressionStatement(a)}else{let r=(0,tR.wrapInterop)(t,a,i.interop)||a;if(i.wrap){let t=T.buildRequireWrapper(i.name,r,i.wrap,i.referenced);if(!1===t)continue;s=t}s??=n.template.statement.ast`
|
|
346
346
|
var ${i.name} = ${r};
|
|
347
347
|
`}s.loc=i.loc,S.push(s,...(0,tR.buildNamespaceInitStatements)(E,i,m,T.wrapReference))}(0,tR.ensureStatementsHoisted)(S),t.unshiftContainer("body",S),t.get("body").forEach(t=>{S.includes(t.node)&&t.isVariableDeclaration()&&t.scope.registerDeclaration(t)})}}}}});function t$(t){let r={babelrc:!1,configFile:!1,compact:!1,retainLines:"boolean"!=typeof t.retainLines||t.retainLines,filename:"",cwd:"/",...t.babel,plugins:[[tU,{allowTopLevelThis:!0,noInterop:!t.interopDefault,async:t.async}],[tj,{filename:t.filename}],[P],[A],[p.default],[d.default]]};t.jsx&&r.plugins.push([c.default],[h.default,Object.assign({},t.jsx)]),t.ts&&(r.plugins.push([f.default,{allowDeclareFields:!0,isTSX:t.jsx&&/\.[cm]?tsx$/.test(t.filename||"")}]),r.plugins.unshift([_],[l.default,{legacy:!0}]),r.plugins.push(y(),u.default)),t.babel&&Array.isArray(t.babel.plugins)&&r.plugins?.push(...t.babel.plugins);try{return{code:(0,n.transformSync)(t.source,r)?.code||""}}catch(r){return{error:r,code:"exports.__JITI_ERROR__ = "+JSON.stringify({filename:t.filename,line:r.loc?.line||0,column:r.loc?.column||0,code:r.code?.replace("BABEL_","").replace("PARSE_ERROR","ParseError"),message:r.message?.replace("/: ","").replace(/\(.+\)\s*$/,"")})}}}})(),r.exports=o.default},656340,653002,t=>{"use strict";let r,i,s,n,a,o,l,p;var u,c,d,h,f,m,y,b,g,v=t.i(165935),x=t.i(517930);let T=Symbol.for("StackAuth--DO-NOT-USE-OR-YOU-WILL-BE-FIRED--StackAppInternals");var E=t.i(357063),S=t.i(649434);t.i(654909);var _=t.i(501049),P=t.i(517252),A=t.i(402713),w=t.i(830561),C=t.i(181199),I=t.i(703163);function k(t){let r=new Uint8Array(t),i="";for(let t of r)i+=String.fromCharCode(t);return btoa(i).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function N(t){let r=t.replace(/-/g,"+").replace(/_/g,"/"),i=(4-r.length%4)%4,s=atob(r.padEnd(r.length+i,"=")),n=new ArrayBuffer(s.length),a=new Uint8Array(n);for(let t=0;t<s.length;t++)a[t]=s.charCodeAt(t);return n}function O(){return D.stubThis(globalThis?.PublicKeyCredential!==void 0&&"function"==typeof globalThis.PublicKeyCredential)}let D={stubThis:t=>t};function j(t){let{id:r}=t;return{...t,id:N(r),transports:t.transports}}function L(t){return"localhost"===t||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}class R extends Error{constructor({message:t,code:r,cause:i,name:s}){super(t,{cause:i}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=s??i.name,this.code=r}}let M=new class{constructor(){Object.defineProperty(this,"controller",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}createNewAbortSignal(){if(this.controller){let t=Error("Cancelling existing WebAuthn API call for new one");t.name="AbortError",this.controller.abort(t)}let t=new AbortController;return this.controller=t,t.signal}cancelCeremony(){if(this.controller){let t=Error("Manually cancelling existing WebAuthn API call");t.name="AbortError",this.controller.abort(t),this.controller=void 0}}},F=["cross-platform","platform"];function B(t){if(t&&!(0>F.indexOf(t)))return t}async function U(t){let r,i,s,n,a;!t.optionsJSON&&t.challenge&&(console.warn("startRegistration() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information."),t={optionsJSON:t});let{optionsJSON:o,useAutoRegister:l=!1}=t;if(!O())throw Error("WebAuthn is not supported in this browser");let p={...o,challenge:N(o.challenge),user:{...o.user,id:N(o.user.id)},excludeCredentials:o.excludeCredentials?.map(j)},u={};l&&(u.mediation="conditional"),u.publicKey=p,u.signal=M.createNewAbortSignal();try{r=await navigator.credentials.create(u)}catch(t){throw function({error:t,options:r}){let{publicKey:i}=r;if(!i)throw Error("options was missing required publicKey property");if("AbortError"===t.name){if(r.signal instanceof AbortSignal)return new R({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else if("ConstraintError"===t.name){if(i.authenticatorSelection?.requireResidentKey===!0)return new R({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:t});else if("conditional"===r.mediation&&i.authenticatorSelection?.userVerification==="required")return new R({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:t});else if(i.authenticatorSelection?.userVerification==="required")return new R({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:t})}else if("InvalidStateError"===t.name)return new R({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:t});else if("NotAllowedError"===t.name)return new R({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});else if("NotSupportedError"===t.name)return new R(0===i.pubKeyCredParams.filter(t=>"public-key"===t.type).length?{message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:t}:{message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:t});else if("SecurityError"===t.name){let r=globalThis.location.hostname;if(!L(r))return new R({message:`${globalThis.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t});if(i.rp.id!==r)return new R({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else if("TypeError"===t.name){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new R({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:t})}else if("UnknownError"===t.name)return new R({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t});return t}({error:t,options:u})}if(!r)throw Error("Registration was not completed");let{id:c,rawId:d,response:h,type:f}=r;if("function"==typeof h.getTransports&&(s=h.getTransports()),"function"==typeof h.getPublicKeyAlgorithm)try{n=h.getPublicKeyAlgorithm()}catch(t){$("getPublicKeyAlgorithm()",t)}if("function"==typeof h.getPublicKey)try{let t=h.getPublicKey();null!==t&&(a=k(t))}catch(t){$("getPublicKey()",t)}if("function"==typeof h.getAuthenticatorData)try{i=k(h.getAuthenticatorData())}catch(t){$("getAuthenticatorData()",t)}return{id:c,rawId:k(d),response:{attestationObject:k(h.attestationObject),clientDataJSON:k(h.clientDataJSON),transports:s,publicKeyAlgorithm:n,publicKey:a,authenticatorData:i},type:f,clientExtensionResults:r.getClientExtensionResults(),authenticatorAttachment:B(r.authenticatorAttachment)}}function $(t,r){console.warn(`The browser extension that intercepted this WebAuthn API call incorrectly implemented ${t}. You should report this error to them.
|
|
348
|
-
`,r)}let V=t=>t;async function K(t){let r,i,s;!t.optionsJSON&&t.challenge&&(console.warn("startAuthentication() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information."),t={optionsJSON:t});let{optionsJSON:n,useBrowserAutofill:a=!1,verifyBrowserAutofillInput:o=!0}=t;if(!O())throw Error("WebAuthn is not supported in this browser");n.allowCredentials?.length!==0&&(r=n.allowCredentials?.map(j));let l={...n,challenge:N(n.challenge),allowCredentials:r},p={};if(a){if(!await function(){if(!O())return V(new Promise(t=>t(!1)));let t=globalThis.PublicKeyCredential;return t?.isConditionalMediationAvailable===void 0?V(new Promise(t=>t(!1))):V(t.isConditionalMediationAvailable())}())throw Error("Browser does not support WebAuthn autofill");if(document.querySelectorAll("input[autocomplete$='webauthn']").length<1&&o)throw Error('No <input> with "webauthn" as the only or last value in its `autocomplete` attribute was detected');p.mediation="conditional",l.allowCredentials=[]}p.publicKey=l,p.signal=M.createNewAbortSignal();try{i=await navigator.credentials.get(p)}catch(t){throw function({error:t,options:r}){let{publicKey:i}=r;if(!i)throw Error("options was missing required publicKey property");if("AbortError"===t.name){if(r.signal instanceof AbortSignal)return new R({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else if("NotAllowedError"===t.name)return new R({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});else if("SecurityError"===t.name){let r=globalThis.location.hostname;if(!L(r))return new R({message:`${globalThis.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t});if(i.rpId!==r)return new R({message:`The RP ID "${i.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else if("UnknownError"===t.name)return new R({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t});return t}({error:t,options:p})}if(!i)throw Error("Authentication was not completed");let{id:u,rawId:c,response:d,type:h}=i;return d.userHandle&&(s=k(d.userHandle)),{id:u,rawId:k(c),response:{authenticatorData:k(d.authenticatorData),clientDataJSON:k(d.clientDataJSON),signature:k(d.signature),userHandle:s},type:h,clientExtensionResults:i.getClientExtensionResults(),authenticatorAttachment:B(i.authenticatorAttachment)}}function q(t,r){throw new x.HexclaveAssertionError(`${r} option is required in a non-browser environment.`,{redirectUrl:t})}var z=t.i(538022);async function W(t,r,i){return{description:i.description,expires_at_millis:null==i.expiresAt?i.expiresAt:i.expiresAt.getTime(),is_public:i.isPublic,..."user"===t?{user_id:r}:{team_id:r}}}async function H(t,r){return(0,z.filterUndefined)({description:r.description,expires_at_millis:null==r.expiresAt?r.expiresAt:r.expiresAt.getTime(),revoked:r.revoked})}function J(t){return{display_name:t.displayName,profile_image_url:t.profileImageUrl,creator_user_id:t.creatorUserId}}var Y=t.i(782366);function X(t){return Object.freeze(t),new Proxy(t,{get:(t,r,i)=>"user"===r?function(){throw Error("Hexclave: useUser() already returns the user object. Use `const user = useUser()` (or `const user = await app.getUser()`) instead of destructuring it like `const { user } = ...`.")}():t[r]})}var G=t.i(478129),Z=t.i(121288),Q=t.i(498898),ee=t.i(872128);t.s([],839325),t.i(839325),t.s([],873299),t.j(ee,873299);var et=t.i(873299),er=t.i(238717),ei=t.i(578472),es=t.i(525694);function en(t){return{display_name:t.displayName,description:t.description,is_production_mode:t.isProductionMode,onboarding_status:t.onboardingStatus,logo_url:t.logoUrl,logo_full_url:t.logoFullUrl,logo_dark_mode_url:t.logoDarkModeUrl,logo_full_dark_mode_url:t.logoFullDarkModeUrl,config:{domains:t.config?.domains?.map(t=>({domain:t.domain,handler_path:t.handlerPath})),oauth_providers:t.config?.oauthProviders?.filter(t=>"custom_oidc"!==t.type).map(t=>({id:t.id,type:t.type,..."standard"===t.type&&{client_id:t.clientId,client_secret:t.clientSecret,facebook_config_id:t.facebookConfigId,microsoft_tenant_id:t.microsoftTenantId,apple_bundle_ids:t.appleBundleIds}})),email_config:t.config?.emailConfig&&("shared"===t.config.emailConfig.type?{type:"shared"}:{type:"standard",host:t.config.emailConfig.host,port:t.config.emailConfig.port,username:t.config.emailConfig.username,password:t.config.emailConfig.password,sender_name:t.config.emailConfig.senderName,sender_email:t.config.emailConfig.senderEmail}),email_theme:t.config?.emailTheme,sign_up_enabled:t.config?.signUpEnabled,credential_enabled:t.config?.credentialEnabled,magic_link_enabled:t.config?.magicLinkEnabled,passkey_enabled:t.config?.passkeyEnabled,allow_localhost:t.config?.allowLocalhost,create_team_on_sign_up:t.config?.createTeamOnSignUp,client_team_creation_enabled:t.config?.clientTeamCreationEnabled,client_user_deletion_enabled:t.config?.clientUserDeletionEnabled,team_creator_default_permissions:t.config?.teamCreatorDefaultPermissions,team_member_default_permissions:t.config?.teamMemberDefaultPermissions,user_default_permissions:t.config?.userDefaultPermissions,oauth_account_merge_strategy:t.config?.oauthAccountMergeStrategy,allow_user_api_keys:t.config?.allowUserApiKeys,allow_team_api_keys:t.config?.allowTeamApiKeys}}}var ea=t.i(519327);function eo(t){return 1e-5>Math.random()&&Math.random()>.99999&&1e-5>Math.random()&&Math.random()>.99999?"this will never happen":t}function el(t){return w.Result.fromThrowing(()=>JSON.parse(t))}var ep=t.i(347306),eu=class extends Error{constructor(){super("User cancelled the bot challenge"),this.name="BotChallengeUserCancelledError"}},ec=class extends Error{constructor(t="Bot challenge could not be completed",r){super(t,r),this.name="BotChallengeExecutionFailedError"}};async function ed(t){return await t.execute({})}var eh=t.i(477821),ef=t.i(724168),em=t.i(819794);let ey=em.cookies,eb=em.headers;function eg(t){for(var r=1;r<arguments.length;r++){var i=arguments[r];for(var s in i)t[s]=i[s]}return t}var ev=function t(r,i){function s(t,s,n){if("u">typeof document){"number"==typeof(n=eg({},i,n)).expires&&(n.expires=new Date(Date.now()+864e5*n.expires)),n.expires&&(n.expires=n.expires.toUTCString()),t=encodeURIComponent(t).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var a="";for(var o in n)n[o]&&(a+="; "+o,!0!==n[o]&&(a+="="+n[o].split(";")[0]));return document.cookie=t+"="+r.write(s,t)+a}}return Object.create({set:s,get:function(t){if("u">typeof document&&(!arguments.length||t)){for(var i=document.cookie?document.cookie.split("; "):[],s={},n=0;n<i.length;n++){var a=i[n].split("="),o=a.slice(1).join("=");try{var l=decodeURIComponent(a[0]);if(s[l]=r.read(o,l),t===l)break}catch(t){}}return t?s[t]:s}},remove:function(t,r){s(t,"",eg({},r,{expires:-1}))},withAttributes:function(r){return t(this.converter,eg({},this.attributes,r))},withConverter:function(r){return t(eg({},this.converter,r),this.attributes)}},{attributes:{value:Object.freeze(i)},converter:{value:Object.freeze(r)}})}({read:function(t){return'"'===t[0]&&(t=t.slice(1,-1)),t.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(t){return encodeURIComponent(t).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}},{path:"/"});"u"<typeof navigator||navigator.userAgent?.startsWith?.("Mozilla/5.0 ");let ex="ERR_INVALID_ARG_VALUE";function eT(t,r,i){let s=TypeError(t,{cause:i});return Object.assign(s,{code:r}),s}let eE=new TextEncoder,eS=new TextDecoder;function e_(t){return"string"==typeof t?i(t):r(t)}r=Uint8Array.prototype.toBase64?t=>(t instanceof ArrayBuffer&&(t=new Uint8Array(t)),t.toBase64({alphabet:"base64url",omitPadding:!0})):t=>{t instanceof ArrayBuffer&&(t=new Uint8Array(t));let r=[];for(let i=0;i<t.byteLength;i+=32768)r.push(String.fromCharCode.apply(null,t.subarray(i,i+32768)));return btoa(r.join("")).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")},i=Uint8Array.fromBase64?t=>{try{return Uint8Array.fromBase64(t,{alphabet:"base64url"})}catch(t){throw eT("The input to be decoded is not correctly encoded.",ex,t)}}:t=>{try{let r=atob(t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"")),i=new Uint8Array(r.length);for(let t=0;t<r.length;t++)i[t]=r.charCodeAt(t);return i}catch(t){throw eT("The input to be decoded is not correctly encoded.",ex,t)}};function eP(){return e_(crypto.getRandomValues(new Uint8Array(32)))}async function eA(t){var r="codeVerifier";try{if("string"!=typeof t)throw eT(`${r} must be a string`,"ERR_INVALID_ARG_TYPE",void 0);if(0===t.length)throw eT(`${r} must not be empty`,ex,void 0)}catch(t){throw t}return e_(await crypto.subtle.digest("SHA-256","string"==typeof t?eE.encode(t):eS.decode(t)))}URL.parse;let ew="[a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+";function eC(){if(!(0,er.isBrowserLike)())throw Error("cookieClient functions can only be called in a browser environment, yet window is undefined")}async function eI(){function t(){throw new x.HexclaveAssertionError("Throwing cookie helper is just a placeholder. This should never be called")}return{get:t,getAll:t,set:t,setOrDelete:t,delete:t}}function ek(t){return t.startsWith("__Host-")}function eN(t,r){if(ek(t)&&void 0!==r.domain)throw new x.HexclaveAssertionError("__Host- cookies must not specify a Domain attribute")}async function eO(){var t,r;let i;return(0,er.isBrowserLike)()?eD():(t=await ey(),r=await eb(),i={get:t=>i.getAll()[t]??null,getAll:()=>{try{t.set("hexclave-is-https","true",{secure:!0,expires:new Date(Date.now()+31536e6)}),t.set("stack-is-https","true",{secure:!0,expires:new Date(Date.now()+31536e6)})}catch(t){if("object"==typeof t&&null!==t&&"message"in t&&"string"==typeof t.message&&t.message.includes("Cookies can only be modified in a Server Action or Route Handler"));else throw t}return t.getAll().reduce((t,r)=>(t[r.name]=r.value,t),{})},set:(i,s,n)=>{eN(i,n);let a=eF(t,r);try{t.set(i,s,{secure:ek(i)||a,maxAge:"session"===n.maxAge?void 0:n.maxAge,domain:n.domain,sameSite:"lax",path:"/"})}catch(t){ej(t,n)}},setOrDelete(t,r,i){null===r?this.delete(t,i):this.set(t,r,i)},delete(r,i){try{eN(r,i),void 0!==i.domain?t.delete({name:r,domain:i.domain,path:"/"}):t.delete({name:r,path:"/"})}catch(t){ej(t,i)}}})}function eD(){return{get:eL,getAll:eR,set:ez,setOrDelete:e$,delete:eK}}function ej(t,r){if(t instanceof Error&&t.message.includes("Cookies can only be modified in"))if(r.noOpIfServerComponent);else throw new x.HexclaveAssertionError("Attempted to set cookie in server component. Pass { noOpIfServerComponent: true } in the options of Stack's cookie functions if this is intentional and you want to ignore this error. Read more: https://nextjs.org/docs/app/api-reference/functions/cookies#options");else throw t}function eL(t){return eR()[t]??null}function eR(){return eC(),ev.set("hexclave-is-https","true",{secure:!0,expires:new Date(Date.now()+31536e6)}),ev.set("stack-is-https","true",{secure:!0,expires:new Date(Date.now()+31536e6)}),ev.get()}async function eM(){return!(0,er.isBrowserLike)()&&eF(await ey(),await eb())}RegExp("^[,\\s]*("+ew+")"),RegExp("^[,\\s]*("+ew+')\\s*=\\s*"((?:[^"\\\\]|\\\\[\\s\\S])*)"[,\\s]*(.*)'),RegExp("^[,\\s]*("+ew+")\\s*=\\s*([a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+)[,\\s]*(.*)"),RegExp("^([a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2})(?:$|[,\\s])(.*)");function eF(t,r){return t.has("hexclave-is-https")||t.has("stack-is-https")||"https"===r.get("x-forwarded-proto")}function eB(t,r,i){eN(t,i);let s=ek(t)||(i.secure??!1),a=n??=(eC(),!1);ev.set(t,r,{expires:"session"===i.maxAge?void 0:new Date(Date.now()+1e3*i.maxAge),domain:i.domain,secure:s,path:"/",sameSite:"Lax",...a?{partitioned:a,sameSite:"None"}:{}})}function eU(t,r){for(let i of(eN(t,r),[!0,!1]))void 0!==r.domain&&ev.remove(t,{domain:r.domain,secure:!1,partitioned:i,path:"/"}),ev.remove(t,{secure:ek(t)||!1,partitioned:i,path:"/"})}function e$(t,r,i){eC(),null===r?eU(t,i):eB(t,r,i)}async function eV(t,r,i){(await eO()).setOrDelete(t,r,i)}function eK(t,r){eC(),eU(t,r)}async function eq(t,r){(await eO()).delete(t,r)}function ez(t,r,i){eC(),eB(t,r,i)}async function eW(t,r,i){(await eO()).set(t,r,i)}async function eH(){let t=eP(),r=await eA(t),i=eP();return await eW("hexclave-oauth-outer-"+i,t,{maxAge:3600}),await eW("stack-oauth-outer-"+i,t,{maxAge:3600}),{codeChallenge:r,state:i}}async function eJ(t,r,i){let{codeChallenge:s,state:n}=await eH();return await t.getOAuthUrl({provider:r.provider,redirectUrl:q(r.redirectUrl,"redirectUrl"),errorRedirectUrl:q(r.errorRedirectUrl,"errorRedirectUrl"),afterCallbackRedirectUrl:q(window.location.href,"afterCallbackRedirectUrl"),codeChallenge:s,state:n,type:"link",session:i,providerScope:r.providerScope})}var eY=t.i(866137),eX=t.i(352901),eG=t.i(951865),eZ=t.i(423656),eQ=t.i(494950);function e0(t){if(!t)return null;try{let r=JSON.parse(t);if("object"!=typeof r||null===r||"string"!=typeof r.session_id||"number"!=typeof r.created_at_ms||"number"!=typeof r.last_activity_ms)return null;return r}catch{return null}}function e1(){return crypto.randomUUID()}function e2(t){let r=e0(localStorage.getItem(t.key))??(t.legacyKey?e0(localStorage.getItem(t.legacyKey)):null);if(r&&t.nowMs-r.last_activity_ms<=18e4)return r;let i={session_id:e1(),created_at_ms:t.nowMs,last_activity_ms:t.nowMs};return localStorage.setItem(t.key,JSON.stringify(i)),i}var e4=class{constructor(t,r){this._started=!1,this._cancelled=!1,this._disabled=!1,this._stopRecording=null,this._detachListeners=null,this._flushTimer=null,this._events=[],this._approxBytes=0,this._lastPersistActivity=0,this._recording=!1,this._rrwebModule=null,this._lastBrowserSessionId=null,this._takingSnapshot=!1,this._flushInProgress=!1,this._deps=t,this._replayOptions=r,this._sessionReplaySegmentId=e1(),this._storageKey=function(t){return`hexclave:session-replay:v1:${t}`}(t.projectId),this._legacyStorageKey=function(t){return`stack:session-replay:v1:${t}`}(t.projectId)}start(){this._started||(0,er.isBrowserLike)()&&(this._started=!0,(0,E.runAsynchronously)(()=>this._startRecording(),{noErrorLogging:!0}),this._flushTimer=setInterval(()=>this._tick(),5e3))}stop(){this._cancelled=!0,null!==this._flushTimer&&(clearInterval(this._flushTimer),this._flushTimer=null),(0,E.runAsynchronously)(()=>this._flush({keepalive:!0})),this._stopCurrentRecording()}clearBuffer(){this._events=[],this._approxBytes=0}_persistActivity(t){let r=e2({key:this._storageKey,legacyKey:this._legacyStorageKey,nowMs:t});if(t-this._lastPersistActivity<5e3)return r;this._lastPersistActivity=t;let i={...r,last_activity_ms:t};return localStorage.setItem(this._storageKey,JSON.stringify(i)),r}async _flush(t){if(this._disabled||0===this._events.length||this._flushInProgress)return;let r=Date.now(),i=e2({key:this._storageKey,legacyKey:this._legacyStorageKey,nowMs:r}),s=e1(),n={browser_session_id:i.session_id,session_replay_segment_id:this._sessionReplaySegmentId,batch_id:s,started_at_ms:i.created_at_ms,sent_at_ms:r,events:this._events};this._events=[],this._approxBytes=0,this._flushInProgress=!0;try{let r=await this._deps.sendBatch(JSON.stringify(n),{keepalive:t.keepalive});if("error"===r.status)return void(0,x.captureWarning)("SessionRecorder.flush",r.error);if(!r.data.ok){if((r.data.headers.get("x-hexclave-known-error")??r.data.headers.get("x-stack-known-error"))==="ANALYTICS_NOT_ENABLED"){this._disabled=!0,null!==this._flushTimer&&(clearInterval(this._flushTimer),this._flushTimer=null),this._stopCurrentRecording();return}(0,x.captureWarning)("SessionRecorder.flush",Error(`SessionRecorder flush failed: ${r.data.status} ${await r.data.text()}`))}}finally{this._flushInProgress=!1}}async _startRecording(){if(this._recording||this._cancelled)return;if(!this._rrwebModule){let r=await w.Result.fromPromise(t.A(488354));if("error"===r.status)return void console.warn("SessionRecorder: rrweb import failed. Is rrweb installed?",r.error);this._rrwebModule=r.data}if(this._cancelled)return;this._stopRecording=this._rrwebModule.record({emit:t=>{let r=Date.now(),i=this._persistActivity(r);if(null===this._lastBrowserSessionId)this._lastBrowserSessionId=i.session_id;else if(i.session_id!==this._lastBrowserSessionId&&!this._takingSnapshot){this._lastBrowserSessionId=i.session_id,this._takingSnapshot=!0;try{this._rrwebModule.record.takeFullSnapshot()}finally{this._takingSnapshot=!1}}this._events.push(t),this._approxBytes+=JSON.stringify(t).length,(this._events.length>=200||this._approxBytes>=512e3)&&(0,E.runAsynchronously)(()=>this._flush({keepalive:!1}))},maskAllInputs:this._replayOptions.maskAllInputs??!0,...void 0!==this._replayOptions.blockClass?{blockClass:this._replayOptions.blockClass}:{},...void 0!==this._replayOptions.blockSelector?{blockSelector:this._replayOptions.blockSelector}:{}})??null,this._recording=!0;let r=()=>{(0,E.runAsynchronously)(()=>this._flush({keepalive:!0}))};window.addEventListener("pagehide",r),document.addEventListener("visibilitychange",r),this._detachListeners=()=>{window.removeEventListener("pagehide",r),document.removeEventListener("visibilitychange",r)}}_stopCurrentRecording(){this._detachListeners&&(this._detachListeners(),this._detachListeners=null),this._stopRecording&&(this._stopRecording(),this._stopRecording=null),this._events=[],this._approxBytes=0,this._recording=!1}_tick(){!this._cancelled&&this._events.length>0&&(0,E.runAsynchronously)(()=>this._flush({keepalive:!1}))}};function e3(t){return null!=t&&"object"==typeof t&&"width"in t&&"height"in t&&"number"==typeof t.width&&"number"==typeof t.height}function e8(t){return null!=t&&"object"==typeof t&&"pushState"in t&&"replaceState"in t&&"function"==typeof t.pushState&&"function"==typeof t.replaceState}function e7(t){return null!=t.closest(`#${(0,eZ.cssEscapeIdent)(eG.DEV_TOOL_ROOT_ID)}, #${(0,eZ.cssEscapeIdent)(eG.CLICKMAP_ROOT_ID)}`)}var e9=class{constructor(t){this._started=!1,this._cancelled=!1,this._disabled=!1,this._detachListeners=null,this._flushTimer=null,this._events=[],this._approxBytes=0,this._lastUrl=null,this._originalPushState=null,this._originalReplaceState=null,this._deadClickTimer=null,this._deadClickMutationObserver=null,this._unclassifiedClicks=new Set,this._lastMutationAtMs=null,this._lastScrollAtMs=null,this._lastSelectionChangedAtMs=null,this._lastVisibilityChangeAtMs=null,this._onPopState=()=>{this._capturePageView("pop")},this._onClickCapture=t=>{let r=t.target;if(!(r instanceof Element)||e7(r))return;let i=window.innerWidth,s=window.innerHeight,n=function(t){let r=t,i=0;for(;null!=r&&i<2*eQ.ELEMENTS_CHAIN_MAX_DEPTH;){let t=window.getComputedStyle(r);if("fixed"===t.position||"sticky"===t.position)return!0;r=r.parentElement,i+=1}return!1}(r),a=Math.round(t.pageX/16),o=Math.round(t.pageY/16),l=Math.round(t.clientY/16),p=i>0?t.clientX/i:0,u={event_type:"$click",event_at_ms:Date.now(),data:{tag_name:r.tagName.toLowerCase(),text:r.textContent.trim().substring(0,200),href:this._findNearestAnchorHref(r),selector:this._buildSelector(r),elements_chain:(0,eQ.buildElementsChain)(r),pointer_target_fixed:+!!n,url:window.location.href,path:window.location.pathname,title:document.title,x:t.clientX,y:t.clientY,page_x:t.pageX,page_y:t.pageY,x_scaled:a,y_scaled:o,client_y_scaled:l,pointer_relative_x:p,viewport_width:i,viewport_height:s,scale_factor:16}};null!==this._deadClickTimer&&this._unclassifiedClicks.size<50&&this._unclassifiedClicks.add(u),this._pushEvent(u)},this._onDeadClickScroll=()=>{this._lastScrollAtMs=Date.now()},this._onDeadClickSelectionChange=()=>{this._lastSelectionChangedAtMs=Date.now()},this._onDeadClickVisibilityChange=()=>{this._lastVisibilityChangeAtMs=Date.now()},this._onPageHide=()=>{(0,E.runAsynchronously)(()=>this._flush({keepalive:!0}))},this._deps=t,this._sessionReplaySegmentId=e1()}start(){this._started||!(0,er.isBrowserLike)()||"function"==typeof window.addEventListener&&"function"==typeof window.removeEventListener&&"function"==typeof document.addEventListener&&"function"==typeof document.removeEventListener&&e3(window.screen)&&(this._started=!0,this._setupPageViewCapture(),this._setupClickCapture(),this._setupDeadClickDetection(),this._setupPageHideListeners(),this._flushTimer=setInterval(()=>this._tick(),1e4))}stop(){this._cancelled=!0,null!==this._flushTimer&&(clearInterval(this._flushTimer),this._flushTimer=null),(0,E.runAsynchronously)(()=>this._flush({keepalive:!0})),this._teardown()}clearBuffer(){this._events=[],this._approxBytes=0,this._unclassifiedClicks.clear()}_pushEvent(t){!this._disabled&&(this._events.push(t),this._approxBytes+=JSON.stringify(t).length,(this._events.length>=50||this._approxBytes>=64e3)&&(0,E.runAsynchronously)(()=>this._flush({keepalive:!1})))}_capturePageView(t){let r=window.screen;if(!e3(r))return;let i=window.location.href;(i!==this._lastUrl||"initial"===t)&&(this._lastUrl=i,this._pushEvent({event_type:"$page-view",event_at_ms:Date.now(),data:{url:i,path:window.location.pathname,referrer:document.referrer,title:document.title,entry_type:t,viewport_width:window.innerWidth,viewport_height:window.innerHeight,screen_width:r.width,screen_height:r.height,user_agent:"u">typeof navigator?navigator.userAgent:null}}))}_setupPageViewCapture(){this._capturePageView("initial");let t=window.history;if(!e8(t))return;let r=t.pushState,i=t.replaceState;this._originalPushState=(...i)=>r.apply(t,i),t.pushState=(...t)=>{this._originalPushState(...t),this._capturePageView("push")},this._originalReplaceState=(...r)=>i.apply(t,r),t.replaceState=(...t)=>{this._originalReplaceState(...t),this._capturePageView("replace")},window.addEventListener("popstate",this._onPopState)}_buildSelector(t){let r=[],i=t,s=0;for(;i&&s<8&&i!==document.documentElement;){let t=i.tagName.toLowerCase(),n="data-testid",a=i.getAttribute("data-testid");if(null==a&&(n="data-test-id",a=i.getAttribute("data-test-id")),null!=a&&""!==a.trim()){t+=`[${n}="${a.replace(/"/g,'\\"')}"]`,r.unshift(t);break}if(""!==i.id){t+=`#${(0,eZ.cssEscapeIdent)(i.id)}`,r.unshift(t);break}if(i.className&&"string"==typeof i.className){let r=i.className.trim().split(/\s+/).filter(Boolean).slice(0,4);r.length>0&&(t+=`.${r.map(eZ.cssEscapeIdent).join(".")}`)}let o=i.parentElement;if(null!=o){let r=i.tagName,s=Array.from(o.children).filter(t=>t.tagName===r);s.length>1&&(t+=`:nth-of-type(${s.indexOf(i)+1})`)}r.unshift(t),i=o,s++}return r.join(" > ")}_findNearestAnchorHref(t){let r=t;for(;r;){if("A"===r.tagName&&r.hasAttribute("href"))return r.getAttribute("href");r=r.parentElement}return null}_setupClickCapture(){document.addEventListener("click",this._onClickCapture,{capture:!0})}_setupDeadClickDetection(){"function"==typeof MutationObserver&&(this._deadClickMutationObserver=new MutationObserver(t=>{t.every(t=>{var r;let i;return null!=(i=(r=t.target)instanceof Element?r:r?.parentElement??null)&&e7(i)})||(this._lastMutationAtMs=Date.now())}),this._deadClickMutationObserver.observe(document.documentElement,{childList:!0,attributes:!0,characterData:!0,subtree:!0}),document.addEventListener("scroll",this._onDeadClickScroll,{capture:!0,passive:!0}),document.addEventListener("selectionchange",this._onDeadClickSelectionChange),document.addEventListener("visibilitychange",this._onDeadClickVisibilityChange),this._deadClickTimer=setInterval(()=>this._checkDeadClicks(),1e3))}_checkDeadClicks(){let t=Date.now();for(let r of this._unclassifiedClicks){let i=(t,i)=>null!=t&&t>=r.event_at_ms&&t-r.event_at_ms<i;i(this._lastScrollAtMs,100)||i(this._lastSelectionChangedAtMs,100)||i(this._lastVisibilityChangeAtMs,100)||i(this._lastMutationAtMs,2500)?this._unclassifiedClicks.delete(r):t-r.event_at_ms>=2750&&(r.data.dead=1,this._unclassifiedClicks.delete(r))}}_teardownDeadClickDetection(){null!==this._deadClickTimer&&(clearInterval(this._deadClickTimer),this._deadClickTimer=null),null!==this._deadClickMutationObserver&&(this._deadClickMutationObserver.disconnect(),this._deadClickMutationObserver=null),document.removeEventListener("scroll",this._onDeadClickScroll,{capture:!0}),document.removeEventListener("selectionchange",this._onDeadClickSelectionChange),document.removeEventListener("visibilitychange",this._onDeadClickVisibilityChange),this._unclassifiedClicks.clear()}_setupPageHideListeners(){window.addEventListener("pagehide",this._onPageHide),document.addEventListener("visibilitychange",this._onPageHide),this._detachListeners=()=>{window.removeEventListener("pagehide",this._onPageHide),document.removeEventListener("visibilitychange",this._onPageHide)}}_teardown(){this._detachListeners&&(this._detachListeners(),this._detachListeners=null);let t=window.history;e8(t)&&(this._originalPushState&&(t.pushState=this._originalPushState),this._originalReplaceState&&(t.replaceState=this._originalReplaceState)),this._originalPushState=null,this._originalReplaceState=null,window.removeEventListener("popstate",this._onPopState),document.removeEventListener("click",this._onClickCapture,{capture:!0}),this._teardownDeadClickDetection(),this._events=[],this._approxBytes=0}async _flush(t){if(this._disabled)return;t.keepalive&&this._unclassifiedClicks.clear();let r=this._events.filter(t=>!this._unclassifiedClicks.has(t));if(0===r.length)return;this._events=this._events.filter(t=>this._unclassifiedClicks.has(t)),this._approxBytes=this._events.reduce((t,r)=>t+JSON.stringify(r).length,0);let i=Date.now(),s=e1(),n={session_replay_segment_id:this._sessionReplaySegmentId,batch_id:s,sent_at_ms:i,events:r},a=await this._deps.sendBatch(JSON.stringify(n),{keepalive:t.keepalive});if("error"===a.status)return void console.warn("EventTracker flush failed:",a.error);if(!a.data.ok){if((a.data.headers.get("x-hexclave-known-error")??a.data.headers.get("x-stack-known-error"))==="ANALYTICS_NOT_ENABLED"){this._disabled=!0,null!==this._flushTimer&&(clearInterval(this._flushTimer),this._flushTimer=null),this._teardown();return}console.warn("EventTracker flush failed:",a.data.status,await a.data.text())}}_tick(){!this._cancelled&&this._events.length>0&&(0,E.runAsynchronously)(()=>this._flush({keepalive:!1}))}};let e5={marker:"hexclave_cross_domain_auth",state:"hexclave_cross_domain_state",codeChallenge:"hexclave_cross_domain_code_challenge",afterCallbackRedirectUrl:"hexclave_cross_domain_after_callback_redirect_url"};function e6(t,r){return t.get(e5[r])}function te(t,r){return t.has(e5[r])}function tt(t,r,i){t.set(e5[r],i)}function tr(t){let r=e6(t.searchParams,"state"),i=e6(t.searchParams,"codeChallenge");return null==r||null==i?null:{state:r,codeChallenge:i}}function ti(t){return te(t.searchParams,"state")&&te(t.searchParams,"codeChallenge")&&te(t.searchParams,"afterCallbackRedirectUrl")}function ts(t){let r=new URL(t.rawHandlerUrl,t.currentUrl),i=t.currentUrl.searchParams.get("after_auth_return_to");for(let s of(null==i||r.searchParams.has("after_auth_return_to")||r.searchParams.set("after_auth_return_to",i),["state","codeChallenge","afterCallbackRedirectUrl"])){let i=e6(t.currentUrl.searchParams,s);null==i||te(r.searchParams,s)||tt(r.searchParams,s,i)}if("signOut"===t.handlerName)return r.searchParams.has("after_auth_return_to")||(t.currentUrl.protocol===r.protocol&&t.currentUrl.host===r.host?r.searchParams.set("after_auth_return_to",(0,Q.getRelativePart)(t.currentUrl)):r.searchParams.set("after_auth_return_to",t.currentUrl.toString())),r.origin===t.currentUrl.origin?(0,Q.getRelativePart)(r):r.toString();if(t.currentUrl.origin!==r.origin){if(!ti(r)){let i=t.currentUrl.searchParams.get("after_auth_return_to"),s=i?new URL(i,t.currentUrl).toString():t.currentUrl.toString(),n=function(t){let r=new URL(t.localOAuthCallbackUrl,t.currentUrl);if(r.origin!==t.currentUrl.origin)throw new x.HexclaveAssertionError("Cross-domain auth callback URL must stay on the current origin",{localOAuthCallbackUrl:r.toString(),currentUrl:t.currentUrl.toString()});return tt(r.searchParams,"marker","1"),null!=t.state&&tt(r.searchParams,"state",t.state),null!=t.codeChallenge&&tt(r.searchParams,"codeChallenge",t.codeChallenge),null!=t.afterCallbackRedirectUrl&&tt(r.searchParams,"afterCallbackRedirectUrl",t.afterCallbackRedirectUrl),r}({currentUrl:t.currentUrl,localOAuthCallbackUrl:t.localOAuthCallbackUrl,state:t.crossDomainHandoffParams?.state,codeChallenge:t.crossDomainHandoffParams?.codeChallenge,afterCallbackRedirectUrl:s});r.searchParams.set("after_auth_return_to",n.toString()),tt(r.searchParams,"afterCallbackRedirectUrl",s),null!=t.crossDomainHandoffParams&&(tt(r.searchParams,"state",t.crossDomainHandoffParams.state),tt(r.searchParams,"codeChallenge",t.crossDomainHandoffParams.codeChallenge))}}else t.currentUrl.protocol!==r.protocol||t.currentUrl.host!==r.host||r.searchParams.has("after_auth_return_to")||r.searchParams.set("after_auth_return_to",(0,Q.getRelativePart)(t.currentUrl));return r.origin===t.currentUrl.origin?(0,Q.getRelativePart)(r):r.toString()}async function tn(t){let r=ts({handlerName:t.handlerName,rawHandlerUrl:t.rawHandlerUrl,currentUrl:t.currentUrl,crossDomainHandoffParams:null,localOAuthCallbackUrl:t.localOAuthCallbackUrl});if("signOut"===t.handlerName)return r;let i=new URL(r,t.currentUrl);if(t.currentUrl.origin===i.origin||ti(i))return r;let s=await t.getCrossDomainHandoffParams(t.currentUrl);return ts({handlerName:t.handlerName,rawHandlerUrl:t.rawHandlerUrl,currentUrl:t.currentUrl,crossDomainHandoffParams:s,localOAuthCallbackUrl:t.localOAuthCallbackUrl})}async function ta(t){if(t.noRedirectBack||null==t.currentUrl)return{type:"redirect",url:t.rawHandlerUrl};let r=function(t){return"afterSignIn"===t||"afterSignUp"===t?"after-auth-return":"signIn"===t||"signUp"===t||"onboarding"===t||"signOut"===t?"redirect-back-aware":"none"}(t.handlerName);if("none"===r)return{type:"redirect",url:t.rawHandlerUrl};if("after-auth-return"===r){var i,s,n;let r,a,o=t.currentUrl.searchParams.get("after_auth_return_to");if(null==o)return{type:"redirect",url:t.rawHandlerUrl};let l=new URL(o,t.currentUrl),p=(r=(s=(i={currentUrl:t.currentUrl,redirectBackTarget:l}).currentUrl,n=i.redirectBackTarget,{state:e6(s.searchParams,"state")??e6(n.searchParams,"state"),codeChallenge:e6(s.searchParams,"codeChallenge")??e6(n.searchParams,"codeChallenge"),afterCallbackRedirectUrl:e6(s.searchParams,"afterCallbackRedirectUrl")??e6(n.searchParams,"afterCallbackRedirectUrl")}),null==(a=function(t){if(t.redirectBackTarget.origin!==t.currentUrl.origin)return t.redirectBackTarget;if(null==t.handoffParams.state||null==t.handoffParams.codeChallenge||null==t.handoffParams.afterCallbackRedirectUrl)return null;let r=new URL(t.handoffParams.afterCallbackRedirectUrl,t.currentUrl);return r.origin===t.currentUrl.origin?null:new URL(`${t.redirectBackTarget.pathname}${t.redirectBackTarget.search}${t.redirectBackTarget.hash}`,r.origin)}({currentUrl:i.currentUrl,redirectBackTarget:i.redirectBackTarget,handoffParams:r}))?null:{redirectBackTarget:a,handoffParams:r});if(null==p)return{type:"redirect",url:o};let u=p.handoffParams.state,c=p.handoffParams.codeChallenge,d=p.handoffParams.afterCallbackRedirectUrl;if(null==u||null==c){let r=await t.getCrossDomainHandoffParams(t.currentUrl);u??=r.state,c??=r.codeChallenge}return d??=t.currentUrl.toString(),{type:"cross-domain-authorize",redirectUri:p.redirectBackTarget.toString(),state:u,codeChallenge:c,afterCallbackRedirectUrl:d}}if("signIn"!==t.handlerName&&"signUp"!==t.handlerName&&"onboarding"!==t.handlerName&&"signOut"!==t.handlerName)throw new x.HexclaveAssertionError("Unexpected redirect-back-aware handler policy mismatch",{handlerName:t.handlerName,policy:r});return{type:"redirect",url:await tn({handlerName:t.handlerName,rawHandlerUrl:t.rawHandlerUrl,currentUrl:t.currentUrl,localOAuthCallbackUrl:t.localOAuthCallbackUrl,getCrossDomainHandoffParams:t.getCrossDomainHandoffParams})}}var to=t.i(895842),tl=t.i(902528);let tp=null,tu=null,tc=0,td=null;function th(){let t=function(){try{let t=localStorage.getItem("__hexclave-dev-tool-override");if("true"===t)return!0;if("false"===t)return!1}catch{}return null}();return null!==t?t:!!(0,tl.canMountIntoDom)()&&(0,Q.isLocalhost)(window.location.href)}let tf=null,tm=null,ty=0,tb=null,tg=!1;tg=!0;let tv=eo(et),tx=new Map,tT="stackauth_",tE="hexclave_";function tS(t){return null==t.accessToken&&null==t.refreshToken?null:`Bearer ${tT}${(0,Y.encodeBase64)(new TextEncoder().encode(JSON.stringify(t)))}`}function t_(t,r){if("get"in t&&"function"==typeof t.get)return t.get(r);let i=r.toLowerCase();for(let[r,s]of Object.entries(t))if(r.toLowerCase()===i)return s;return null}async function tP(){return(await eb?.())?.get("host")??null}var tA=class r{static{this.LazyStackAdminAppImpl={value:void 0}}async _createCookieHelper(t){let r=void 0===t?this._tokenStoreInit:t;return"nextjs-cookie"===r||"cookie"===r?await eO():await eI()}async _getUserOAuthConnectionCacheFn(t){let r=await t.getUser(),i=!0;if(r&&r.oauth_providers.find(r=>r.id===t.providerId)||(i=!1),await t.getOrWaitOAuthToken()||(i=!1),!i&&t.redirect){if(!t.session)throw Error(G.deindent`
|
|
348
|
+
`,r)}let V=t=>t;async function K(t){let r,i,s;!t.optionsJSON&&t.challenge&&(console.warn("startAuthentication() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information."),t={optionsJSON:t});let{optionsJSON:n,useBrowserAutofill:a=!1,verifyBrowserAutofillInput:o=!0}=t;if(!O())throw Error("WebAuthn is not supported in this browser");n.allowCredentials?.length!==0&&(r=n.allowCredentials?.map(j));let l={...n,challenge:N(n.challenge),allowCredentials:r},p={};if(a){if(!await function(){if(!O())return V(new Promise(t=>t(!1)));let t=globalThis.PublicKeyCredential;return t?.isConditionalMediationAvailable===void 0?V(new Promise(t=>t(!1))):V(t.isConditionalMediationAvailable())}())throw Error("Browser does not support WebAuthn autofill");if(document.querySelectorAll("input[autocomplete$='webauthn']").length<1&&o)throw Error('No <input> with "webauthn" as the only or last value in its `autocomplete` attribute was detected');p.mediation="conditional",l.allowCredentials=[]}p.publicKey=l,p.signal=M.createNewAbortSignal();try{i=await navigator.credentials.get(p)}catch(t){throw function({error:t,options:r}){let{publicKey:i}=r;if(!i)throw Error("options was missing required publicKey property");if("AbortError"===t.name){if(r.signal instanceof AbortSignal)return new R({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else if("NotAllowedError"===t.name)return new R({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});else if("SecurityError"===t.name){let r=globalThis.location.hostname;if(!L(r))return new R({message:`${globalThis.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t});if(i.rpId!==r)return new R({message:`The RP ID "${i.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else if("UnknownError"===t.name)return new R({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t});return t}({error:t,options:p})}if(!i)throw Error("Authentication was not completed");let{id:u,rawId:c,response:d,type:h}=i;return d.userHandle&&(s=k(d.userHandle)),{id:u,rawId:k(c),response:{authenticatorData:k(d.authenticatorData),clientDataJSON:k(d.clientDataJSON),signature:k(d.signature),userHandle:s},type:h,clientExtensionResults:i.getClientExtensionResults(),authenticatorAttachment:B(i.authenticatorAttachment)}}function q(t,r){throw new x.HexclaveAssertionError(`${r} option is required in a non-browser environment.`,{redirectUrl:t})}var z=t.i(538022);async function W(t,r,i){return{description:i.description,expires_at_millis:null==i.expiresAt?i.expiresAt:i.expiresAt.getTime(),is_public:i.isPublic,..."user"===t?{user_id:r}:{team_id:r}}}async function H(t,r){return(0,z.filterUndefined)({description:r.description,expires_at_millis:null==r.expiresAt?r.expiresAt:r.expiresAt.getTime(),revoked:r.revoked})}function J(t){return{display_name:t.displayName,profile_image_url:t.profileImageUrl,creator_user_id:t.creatorUserId}}var Y=t.i(782366);function X(t){return Object.freeze(t),new Proxy(t,{get:(t,r,i)=>"user"===r?function(){throw Error("Hexclave: useUser() already returns the user object. Use `const user = useUser()` (or `const user = await app.getUser()`) instead of destructuring it like `const { user } = ...`.")}():t[r]})}var G=t.i(478129),Z=t.i(121288),Q=t.i(498898),ee=t.i(872128);t.s([],839325),t.i(839325),t.s([],873299),t.j(ee,873299);var et=t.i(873299),er=t.i(238717),ei=t.i(578472),es=t.i(525694);function en(t){return{display_name:t.displayName,description:t.description,is_production_mode:t.isProductionMode,onboarding_status:t.onboardingStatus,logo_url:t.logoUrl,logo_full_url:t.logoFullUrl,logo_dark_mode_url:t.logoDarkModeUrl,logo_full_dark_mode_url:t.logoFullDarkModeUrl,config:{domains:t.config?.domains?.map(t=>({domain:t.domain,handler_path:t.handlerPath})),oauth_providers:t.config?.oauthProviders?.filter(t=>"custom_oidc"!==t.type).map(t=>({id:t.id,type:t.type,..."standard"===t.type&&{client_id:t.clientId,client_secret:t.clientSecret,facebook_config_id:t.facebookConfigId,microsoft_tenant_id:t.microsoftTenantId,apple_bundle_ids:t.appleBundleIds}})),email_config:t.config?.emailConfig&&("shared"===t.config.emailConfig.type?{type:"shared"}:{type:"standard",host:t.config.emailConfig.host,port:t.config.emailConfig.port,username:t.config.emailConfig.username,password:t.config.emailConfig.password,sender_name:t.config.emailConfig.senderName,sender_email:t.config.emailConfig.senderEmail}),email_theme:t.config?.emailTheme,sign_up_enabled:t.config?.signUpEnabled,credential_enabled:t.config?.credentialEnabled,magic_link_enabled:t.config?.magicLinkEnabled,passkey_enabled:t.config?.passkeyEnabled,allow_localhost:t.config?.allowLocalhost,create_team_on_sign_up:t.config?.createTeamOnSignUp,client_team_creation_enabled:t.config?.clientTeamCreationEnabled,client_user_deletion_enabled:t.config?.clientUserDeletionEnabled,team_creator_default_permissions:t.config?.teamCreatorDefaultPermissions,team_member_default_permissions:t.config?.teamMemberDefaultPermissions,user_default_permissions:t.config?.userDefaultPermissions,oauth_account_merge_strategy:t.config?.oauthAccountMergeStrategy,allow_user_api_keys:t.config?.allowUserApiKeys,allow_team_api_keys:t.config?.allowTeamApiKeys}}}var ea=t.i(519327);function eo(t){return 1e-5>Math.random()&&Math.random()>.99999&&1e-5>Math.random()&&Math.random()>.99999?"this will never happen":t}function el(t){return w.Result.fromThrowing(()=>JSON.parse(t))}var ep=t.i(347306),eu=class extends Error{constructor(){super("User cancelled the bot challenge"),this.name="BotChallengeUserCancelledError"}},ec=class extends Error{constructor(t="Bot challenge could not be completed",r){super(t,r),this.name="BotChallengeExecutionFailedError"}};async function ed(t){return await t.execute({})}var eh=t.i(477821),ef=t.i(724168),em=t.i(819794);let ey=em.cookies,eb=em.headers;function eg(t){for(var r=1;r<arguments.length;r++){var i=arguments[r];for(var s in i)t[s]=i[s]}return t}var ev=function t(r,i){function s(t,s,n){if("u">typeof document){"number"==typeof(n=eg({},i,n)).expires&&(n.expires=new Date(Date.now()+864e5*n.expires)),n.expires&&(n.expires=n.expires.toUTCString()),t=encodeURIComponent(t).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var a="";for(var o in n)n[o]&&(a+="; "+o,!0!==n[o]&&(a+="="+n[o].split(";")[0]));return document.cookie=t+"="+r.write(s,t)+a}}return Object.create({set:s,get:function(t){if("u">typeof document&&(!arguments.length||t)){for(var i=document.cookie?document.cookie.split("; "):[],s={},n=0;n<i.length;n++){var a=i[n].split("="),o=a.slice(1).join("=");try{var l=decodeURIComponent(a[0]);if(s[l]=r.read(o,l),t===l)break}catch(t){}}return t?s[t]:s}},remove:function(t,r){s(t,"",eg({},r,{expires:-1}))},withAttributes:function(r){return t(this.converter,eg({},this.attributes,r))},withConverter:function(r){return t(eg({},this.converter,r),this.attributes)}},{attributes:{value:Object.freeze(i)},converter:{value:Object.freeze(r)}})}({read:function(t){return'"'===t[0]&&(t=t.slice(1,-1)),t.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(t){return encodeURIComponent(t).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}},{path:"/"});"u"<typeof navigator||navigator.userAgent?.startsWith?.("Mozilla/5.0 ");let ex="ERR_INVALID_ARG_VALUE";function eT(t,r,i){let s=TypeError(t,{cause:i});return Object.assign(s,{code:r}),s}let eE=new TextEncoder,eS=new TextDecoder;function e_(t){return"string"==typeof t?i(t):r(t)}r=Uint8Array.prototype.toBase64?t=>(t instanceof ArrayBuffer&&(t=new Uint8Array(t)),t.toBase64({alphabet:"base64url",omitPadding:!0})):t=>{t instanceof ArrayBuffer&&(t=new Uint8Array(t));let r=[];for(let i=0;i<t.byteLength;i+=32768)r.push(String.fromCharCode.apply(null,t.subarray(i,i+32768)));return btoa(r.join("")).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")},i=Uint8Array.fromBase64?t=>{try{return Uint8Array.fromBase64(t,{alphabet:"base64url"})}catch(t){throw eT("The input to be decoded is not correctly encoded.",ex,t)}}:t=>{try{let r=atob(t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"")),i=new Uint8Array(r.length);for(let t=0;t<r.length;t++)i[t]=r.charCodeAt(t);return i}catch(t){throw eT("The input to be decoded is not correctly encoded.",ex,t)}};function eP(){return e_(crypto.getRandomValues(new Uint8Array(32)))}async function eA(t){var r="codeVerifier";try{if("string"!=typeof t)throw eT(`${r} must be a string`,"ERR_INVALID_ARG_TYPE",void 0);if(0===t.length)throw eT(`${r} must not be empty`,ex,void 0)}catch(t){throw t}return e_(await crypto.subtle.digest("SHA-256","string"==typeof t?eE.encode(t):eS.decode(t)))}URL.parse;let ew="[a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+";function eC(){if(!(0,er.isBrowserLike)())throw Error("cookieClient functions can only be called in a browser environment, yet window is undefined")}async function eI(){function t(){throw new x.HexclaveAssertionError("Throwing cookie helper is just a placeholder. This should never be called")}return{get:t,getAll:t,set:t,setOrDelete:t,delete:t}}function ek(t){return t.startsWith("__Host-")}function eN(t,r){if(ek(t)&&void 0!==r.domain)throw new x.HexclaveAssertionError("__Host- cookies must not specify a Domain attribute")}async function eO(){var t,r;let i;return(0,er.isBrowserLike)()?eD():(t=await ey(),r=await eb(),i={get:t=>i.getAll()[t]??null,getAll:()=>{try{t.set("hexclave-is-https","true",{secure:!0,expires:new Date(Date.now()+31536e6)}),t.set("stack-is-https","true",{secure:!0,expires:new Date(Date.now()+31536e6)})}catch(t){if("object"==typeof t&&null!==t&&"message"in t&&"string"==typeof t.message&&t.message.includes("Cookies can only be modified in a Server Action or Route Handler"));else throw t}return t.getAll().reduce((t,r)=>(t[r.name]=r.value,t),{})},set:(i,s,n)=>{eN(i,n);let a=eF(t,r);try{t.set(i,s,{secure:ek(i)||a,maxAge:"session"===n.maxAge?void 0:n.maxAge,domain:n.domain,sameSite:"lax",path:"/"})}catch(t){ej(t,n)}},setOrDelete(t,r,i){null===r?this.delete(t,i):this.set(t,r,i)},delete(r,i){try{eN(r,i),void 0!==i.domain?t.delete({name:r,domain:i.domain,path:"/"}):t.delete({name:r,path:"/"})}catch(t){ej(t,i)}}})}function eD(){return{get:eL,getAll:eR,set:ez,setOrDelete:e$,delete:eK}}function ej(t,r){if(t instanceof Error&&t.message.includes("Cookies can only be modified in"))if(r.noOpIfServerComponent);else throw new x.HexclaveAssertionError("Attempted to set cookie in server component. Pass { noOpIfServerComponent: true } in the options of Stack's cookie functions if this is intentional and you want to ignore this error. Read more: https://nextjs.org/docs/app/api-reference/functions/cookies#options");else throw t}function eL(t){return eR()[t]??null}function eR(){return eC(),ev.set("hexclave-is-https","true",{secure:!0,expires:new Date(Date.now()+31536e6)}),ev.set("stack-is-https","true",{secure:!0,expires:new Date(Date.now()+31536e6)}),ev.get()}async function eM(){return!(0,er.isBrowserLike)()&&eF(await ey(),await eb())}RegExp("^[,\\s]*("+ew+")"),RegExp("^[,\\s]*("+ew+')\\s*=\\s*"((?:[^"\\\\]|\\\\[\\s\\S])*)"[,\\s]*(.*)'),RegExp("^[,\\s]*("+ew+")\\s*=\\s*([a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+)[,\\s]*(.*)"),RegExp("^([a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2})(?:$|[,\\s])(.*)");function eF(t,r){return t.has("hexclave-is-https")||t.has("stack-is-https")||"https"===r.get("x-forwarded-proto")}function eB(t,r,i){eN(t,i);let s=ek(t)||(i.secure??!1),a=n??=(eC(),!1);ev.set(t,r,{expires:"session"===i.maxAge?void 0:new Date(Date.now()+1e3*i.maxAge),domain:i.domain,secure:s,path:"/",sameSite:"Lax",...a?{partitioned:a,sameSite:"None"}:{}})}function eU(t,r){for(let i of(eN(t,r),[!0,!1]))void 0!==r.domain&&ev.remove(t,{domain:r.domain,secure:!1,partitioned:i,path:"/"}),ev.remove(t,{secure:ek(t)||!1,partitioned:i,path:"/"})}function e$(t,r,i){eC(),null===r?eU(t,i):eB(t,r,i)}async function eV(t,r,i){(await eO()).setOrDelete(t,r,i)}function eK(t,r){eC(),eU(t,r)}async function eq(t,r){(await eO()).delete(t,r)}function ez(t,r,i){eC(),eB(t,r,i)}async function eW(t,r,i){(await eO()).set(t,r,i)}async function eH(){let t=eP(),r=await eA(t),i=eP();return await eW("hexclave-oauth-outer-"+i,t,{maxAge:3600}),await eW("stack-oauth-outer-"+i,t,{maxAge:3600}),{codeChallenge:r,state:i}}async function eJ(t,r,i){let{codeChallenge:s,state:n}=await eH();return await t.getOAuthUrl({provider:r.provider,redirectUrl:q(r.redirectUrl,"redirectUrl"),errorRedirectUrl:q(r.errorRedirectUrl,"errorRedirectUrl"),afterCallbackRedirectUrl:q(window.location.href,"afterCallbackRedirectUrl"),codeChallenge:s,state:n,type:"link",session:i,providerScope:r.providerScope})}var eY=t.i(866137),eX=t.i(352901),eG=t.i(951865),eZ=t.i(423656),eQ=t.i(494950);function e0(t){if(!t)return null;try{let r=JSON.parse(t);if("object"!=typeof r||null===r||"string"!=typeof r.session_id||"number"!=typeof r.created_at_ms||"number"!=typeof r.last_activity_ms)return null;return r}catch{return null}}function e1(){return crypto.randomUUID()}function e2(t){let r=e0(localStorage.getItem(t.key))??(t.legacyKey?e0(localStorage.getItem(t.legacyKey)):null);if(r&&t.nowMs-r.last_activity_ms<=18e4)return r;let i={session_id:e1(),created_at_ms:t.nowMs,last_activity_ms:t.nowMs};return localStorage.setItem(t.key,JSON.stringify(i)),i}function e4(t){return P.KnownErrors.AnalyticsNotEnabled.isInstance(t)}var e3=class{constructor(t,r){this._started=!1,this._cancelled=!1,this._disabled=!1,this._stopRecording=null,this._detachListeners=null,this._flushTimer=null,this._events=[],this._approxBytes=0,this._lastPersistActivity=0,this._recording=!1,this._rrwebModule=null,this._lastBrowserSessionId=null,this._takingSnapshot=!1,this._flushInProgress=!1,this._deps=t,this._replayOptions=r,this._sessionReplaySegmentId=e1(),this._storageKey=function(t){return`hexclave:session-replay:v1:${t}`}(t.projectId),this._legacyStorageKey=function(t){return`stack:session-replay:v1:${t}`}(t.projectId)}start(){this._started||(0,er.isBrowserLike)()&&(this._started=!0,(0,E.runAsynchronously)(()=>this._startRecording(),{noErrorLogging:!0}),this._flushTimer=setInterval(()=>this._tick(),5e3))}stop(){this._cancelled=!0,null!==this._flushTimer&&(clearInterval(this._flushTimer),this._flushTimer=null),(0,E.runAsynchronously)(()=>this._flush({keepalive:!0})),this._stopCurrentRecording()}clearBuffer(){this._events=[],this._approxBytes=0}_persistActivity(t){let r=e2({key:this._storageKey,legacyKey:this._legacyStorageKey,nowMs:t});if(t-this._lastPersistActivity<5e3)return r;this._lastPersistActivity=t;let i={...r,last_activity_ms:t};return localStorage.setItem(this._storageKey,JSON.stringify(i)),r}async _flush(t){if(this._disabled||0===this._events.length||this._flushInProgress)return;let r=Date.now(),i=e2({key:this._storageKey,legacyKey:this._legacyStorageKey,nowMs:r}),s=e1(),n={browser_session_id:i.session_id,session_replay_segment_id:this._sessionReplaySegmentId,batch_id:s,started_at_ms:i.created_at_ms,sent_at_ms:r,events:this._events};this._events=[],this._approxBytes=0,this._flushInProgress=!0;try{let r=await this._deps.sendBatch(JSON.stringify(n),{keepalive:t.keepalive});if("error"===r.status){if(e4(r.error))return void this._disable();(0,x.captureWarning)("SessionRecorder.flush",r.error);return}r.data.ok||(0,x.captureWarning)("SessionRecorder.flush",Error(`SessionRecorder flush failed: ${r.data.status} ${await r.data.text()}`))}finally{this._flushInProgress=!1}}_disable(){this._disabled=!0,this.clearBuffer(),null!==this._flushTimer&&(clearInterval(this._flushTimer),this._flushTimer=null),this._stopCurrentRecording()}async _startRecording(){if(this._recording||this._cancelled)return;if(!this._rrwebModule){let r=await w.Result.fromPromise(t.A(488354));if("error"===r.status)return void console.warn("SessionRecorder: rrweb import failed. Is rrweb installed?",r.error);this._rrwebModule=r.data}if(this._cancelled)return;this._stopRecording=this._rrwebModule.record({emit:t=>{let r=Date.now(),i=this._persistActivity(r);if(null===this._lastBrowserSessionId)this._lastBrowserSessionId=i.session_id;else if(i.session_id!==this._lastBrowserSessionId&&!this._takingSnapshot){this._lastBrowserSessionId=i.session_id,this._takingSnapshot=!0;try{this._rrwebModule.record.takeFullSnapshot()}finally{this._takingSnapshot=!1}}this._events.push(t),this._approxBytes+=JSON.stringify(t).length,(this._events.length>=200||this._approxBytes>=512e3)&&(0,E.runAsynchronously)(()=>this._flush({keepalive:!1}))},maskAllInputs:this._replayOptions.maskAllInputs??!0,...void 0!==this._replayOptions.blockClass?{blockClass:this._replayOptions.blockClass}:{},...void 0!==this._replayOptions.blockSelector?{blockSelector:this._replayOptions.blockSelector}:{}})??null,this._recording=!0;let r=()=>{(0,E.runAsynchronously)(()=>this._flush({keepalive:!0}))};window.addEventListener("pagehide",r),document.addEventListener("visibilitychange",r),this._detachListeners=()=>{window.removeEventListener("pagehide",r),document.removeEventListener("visibilitychange",r)}}_stopCurrentRecording(){this._detachListeners&&(this._detachListeners(),this._detachListeners=null),this._stopRecording&&(this._stopRecording(),this._stopRecording=null),this._events=[],this._approxBytes=0,this._recording=!1}_tick(){!this._cancelled&&this._events.length>0&&(0,E.runAsynchronously)(()=>this._flush({keepalive:!1}))}};function e8(t){return null!=t&&"object"==typeof t&&"width"in t&&"height"in t&&"number"==typeof t.width&&"number"==typeof t.height}function e7(t){return null!=t&&"object"==typeof t&&"pushState"in t&&"replaceState"in t&&"function"==typeof t.pushState&&"function"==typeof t.replaceState}function e9(t){return null!=t.closest(`#${(0,eZ.cssEscapeIdent)(eG.DEV_TOOL_ROOT_ID)}, #${(0,eZ.cssEscapeIdent)(eG.CLICKMAP_ROOT_ID)}`)}var e5=class{constructor(t){this._started=!1,this._cancelled=!1,this._disabled=!1,this._detachListeners=null,this._flushTimer=null,this._events=[],this._approxBytes=0,this._lastUrl=null,this._originalPushState=null,this._originalReplaceState=null,this._deadClickTimer=null,this._deadClickMutationObserver=null,this._unclassifiedClicks=new Set,this._lastMutationAtMs=null,this._lastScrollAtMs=null,this._lastSelectionChangedAtMs=null,this._lastVisibilityChangeAtMs=null,this._onPopState=()=>{this._capturePageView("pop")},this._onClickCapture=t=>{var r;let i=t.target;if(!(i instanceof Element)||e9(i))return;let s=window.innerWidth,n=window.innerHeight,a=function(t){let r=t,i=0;for(;null!=r&&i<2*eQ.ELEMENTS_CHAIN_MAX_DEPTH;){let t=window.getComputedStyle(r);if("fixed"===t.position||"sticky"===t.position)return!0;r=r.parentElement,i+=1}return!1}(i),o=Math.round(t.pageX/16),l=Math.round(t.pageY/16),p=Math.round(t.clientY/16),u=s>0?t.clientX/s:0,c={event_type:"$click",event_at_ms:Date.now(),data:{tag_name:i.tagName.toLowerCase(),text:null==(r=i.textContent)?"":r.trim().substring(0,200),href:this._findNearestAnchorHref(i),selector:this._buildSelector(i),elements_chain:(0,eQ.buildElementsChain)(i),pointer_target_fixed:+!!a,url:window.location.href,path:window.location.pathname,title:document.title,x:t.clientX,y:t.clientY,page_x:t.pageX,page_y:t.pageY,x_scaled:o,y_scaled:l,client_y_scaled:p,pointer_relative_x:u,viewport_width:s,viewport_height:n,scale_factor:16}};null!==this._deadClickTimer&&this._unclassifiedClicks.size<50&&this._unclassifiedClicks.add(c),this._pushEvent(c)},this._onDeadClickScroll=()=>{this._lastScrollAtMs=Date.now()},this._onDeadClickSelectionChange=()=>{this._lastSelectionChangedAtMs=Date.now()},this._onDeadClickVisibilityChange=()=>{this._lastVisibilityChangeAtMs=Date.now()},this._onPageHide=()=>{(0,E.runAsynchronously)(()=>this._flush({keepalive:!0}))},this._deps=t,this._sessionReplaySegmentId=e1()}start(){this._started||!(0,er.isBrowserLike)()||"function"==typeof window.addEventListener&&"function"==typeof window.removeEventListener&&"function"==typeof document.addEventListener&&"function"==typeof document.removeEventListener&&e8(window.screen)&&(this._started=!0,this._setupPageViewCapture(),this._setupClickCapture(),this._setupDeadClickDetection(),this._setupPageHideListeners(),this._flushTimer=setInterval(()=>this._tick(),1e4))}stop(){this._cancelled=!0,null!==this._flushTimer&&(clearInterval(this._flushTimer),this._flushTimer=null),(0,E.runAsynchronously)(()=>this._flush({keepalive:!0})),this._teardown()}clearBuffer(){this._events=[],this._approxBytes=0,this._unclassifiedClicks.clear()}_pushEvent(t){!this._disabled&&(this._events.push(t),this._approxBytes+=JSON.stringify(t).length,(this._events.length>=50||this._approxBytes>=64e3)&&(0,E.runAsynchronously)(()=>this._flush({keepalive:!1})))}_capturePageView(t){let r=window.screen;if(!e8(r))return;let i=window.location.href;(i!==this._lastUrl||"initial"===t)&&(this._lastUrl=i,this._pushEvent({event_type:"$page-view",event_at_ms:Date.now(),data:{url:i,path:window.location.pathname,referrer:document.referrer,title:document.title,entry_type:t,viewport_width:window.innerWidth,viewport_height:window.innerHeight,screen_width:r.width,screen_height:r.height,user_agent:"u">typeof navigator?navigator.userAgent:null}}))}_setupPageViewCapture(){this._capturePageView("initial");let t=window.history;if(!e7(t))return;let r=t.pushState,i=t.replaceState;this._originalPushState=(...i)=>r.apply(t,i),t.pushState=(...t)=>{this._originalPushState(...t),this._capturePageView("push")},this._originalReplaceState=(...r)=>i.apply(t,r),t.replaceState=(...t)=>{this._originalReplaceState(...t),this._capturePageView("replace")},window.addEventListener("popstate",this._onPopState)}_buildSelector(t){let r=[],i=t,s=0;for(;i&&s<8&&i!==document.documentElement;){let t=i.tagName.toLowerCase(),n="data-testid",a=i.getAttribute("data-testid");if(null==a&&(n="data-test-id",a=i.getAttribute("data-test-id")),null!=a&&""!==a.trim()){t+=`[${n}="${a.replace(/"/g,'\\"')}"]`,r.unshift(t);break}if(""!==i.id){t+=`#${(0,eZ.cssEscapeIdent)(i.id)}`,r.unshift(t);break}if(i.className&&"string"==typeof i.className){let r=i.className.trim().split(/\s+/).filter(Boolean).slice(0,4);r.length>0&&(t+=`.${r.map(eZ.cssEscapeIdent).join(".")}`)}let o=i.parentElement;if(null!=o){let r=i.tagName,s=Array.from(o.children).filter(t=>t.tagName===r);s.length>1&&(t+=`:nth-of-type(${s.indexOf(i)+1})`)}r.unshift(t),i=o,s++}return r.join(" > ")}_findNearestAnchorHref(t){let r=t;for(;r;){if("A"===r.tagName&&r.hasAttribute("href"))return r.getAttribute("href");r=r.parentElement}return null}_setupClickCapture(){document.addEventListener("click",this._onClickCapture,{capture:!0})}_setupDeadClickDetection(){"function"==typeof MutationObserver&&(this._deadClickMutationObserver=new MutationObserver(t=>{t.every(t=>{var r;let i;return null!=(i=(r=t.target)instanceof Element?r:r?.parentElement??null)&&e9(i)})||(this._lastMutationAtMs=Date.now())}),this._deadClickMutationObserver.observe(document.documentElement,{childList:!0,attributes:!0,characterData:!0,subtree:!0}),document.addEventListener("scroll",this._onDeadClickScroll,{capture:!0,passive:!0}),document.addEventListener("selectionchange",this._onDeadClickSelectionChange),document.addEventListener("visibilitychange",this._onDeadClickVisibilityChange),this._deadClickTimer=setInterval(()=>this._checkDeadClicks(),1e3))}_checkDeadClicks(){let t=Date.now();for(let r of this._unclassifiedClicks){let i=(t,i)=>null!=t&&t>=r.event_at_ms&&t-r.event_at_ms<i;i(this._lastScrollAtMs,100)||i(this._lastSelectionChangedAtMs,100)||i(this._lastVisibilityChangeAtMs,100)||i(this._lastMutationAtMs,2500)?this._unclassifiedClicks.delete(r):t-r.event_at_ms>=2750&&(r.data.dead=1,this._unclassifiedClicks.delete(r))}}_teardownDeadClickDetection(){null!==this._deadClickTimer&&(clearInterval(this._deadClickTimer),this._deadClickTimer=null),null!==this._deadClickMutationObserver&&(this._deadClickMutationObserver.disconnect(),this._deadClickMutationObserver=null),document.removeEventListener("scroll",this._onDeadClickScroll,{capture:!0}),document.removeEventListener("selectionchange",this._onDeadClickSelectionChange),document.removeEventListener("visibilitychange",this._onDeadClickVisibilityChange),this._unclassifiedClicks.clear()}_setupPageHideListeners(){window.addEventListener("pagehide",this._onPageHide),document.addEventListener("visibilitychange",this._onPageHide),this._detachListeners=()=>{window.removeEventListener("pagehide",this._onPageHide),document.removeEventListener("visibilitychange",this._onPageHide)}}_teardown(){this._detachListeners&&(this._detachListeners(),this._detachListeners=null);let t=window.history;e7(t)&&(this._originalPushState&&(t.pushState=this._originalPushState),this._originalReplaceState&&(t.replaceState=this._originalReplaceState)),this._originalPushState=null,this._originalReplaceState=null,window.removeEventListener("popstate",this._onPopState),document.removeEventListener("click",this._onClickCapture,{capture:!0}),this._teardownDeadClickDetection(),this._events=[],this._approxBytes=0}async _flush(t){if(this._disabled)return;t.keepalive&&this._unclassifiedClicks.clear();let r=this._events.filter(t=>!this._unclassifiedClicks.has(t));if(0===r.length)return;this._events=this._events.filter(t=>this._unclassifiedClicks.has(t)),this._approxBytes=this._events.reduce((t,r)=>t+JSON.stringify(r).length,0);let i=Date.now(),s=e1(),n={session_replay_segment_id:this._sessionReplaySegmentId,batch_id:s,sent_at_ms:i,events:r},a=await this._deps.sendBatch(JSON.stringify(n),{keepalive:t.keepalive});"error"===a.status?e4(a.error)?this._disable():console.warn("EventTracker flush failed:",a.error):a.data.ok||console.warn("EventTracker flush failed:",a.data.status,await a.data.text())}_disable(){this._disabled=!0,null!==this._flushTimer&&(clearInterval(this._flushTimer),this._flushTimer=null),this._teardown()}_tick(){!this._cancelled&&this._events.length>0&&(0,E.runAsynchronously)(()=>this._flush({keepalive:!1}))}};let e6={marker:"hexclave_cross_domain_auth",state:"hexclave_cross_domain_state",codeChallenge:"hexclave_cross_domain_code_challenge",afterCallbackRedirectUrl:"hexclave_cross_domain_after_callback_redirect_url"};function te(t,r){return t.get(e6[r])}function tt(t,r){return t.has(e6[r])}function tr(t,r,i){t.set(e6[r],i)}function ti(t){let r=te(t.searchParams,"state"),i=te(t.searchParams,"codeChallenge");return null==r||null==i?null:{state:r,codeChallenge:i}}function ts(t){return tt(t.searchParams,"state")&&tt(t.searchParams,"codeChallenge")&&tt(t.searchParams,"afterCallbackRedirectUrl")}function tn(t){let r=new URL(t.rawHandlerUrl,t.currentUrl),i=t.currentUrl.searchParams.get("after_auth_return_to");for(let s of(null==i||r.searchParams.has("after_auth_return_to")||r.searchParams.set("after_auth_return_to",i),["state","codeChallenge","afterCallbackRedirectUrl"])){let i=te(t.currentUrl.searchParams,s);null==i||tt(r.searchParams,s)||tr(r.searchParams,s,i)}if("signOut"===t.handlerName)return r.searchParams.has("after_auth_return_to")||(t.currentUrl.protocol===r.protocol&&t.currentUrl.host===r.host?r.searchParams.set("after_auth_return_to",(0,Q.getRelativePart)(t.currentUrl)):r.searchParams.set("after_auth_return_to",t.currentUrl.toString())),r.origin===t.currentUrl.origin?(0,Q.getRelativePart)(r):r.toString();if(t.currentUrl.origin!==r.origin){if(!ts(r)){let i=t.currentUrl.searchParams.get("after_auth_return_to"),s=i?new URL(i,t.currentUrl).toString():t.currentUrl.toString(),n=function(t){let r=new URL(t.localOAuthCallbackUrl,t.currentUrl);if(r.origin!==t.currentUrl.origin)throw new x.HexclaveAssertionError("Cross-domain auth callback URL must stay on the current origin",{localOAuthCallbackUrl:r.toString(),currentUrl:t.currentUrl.toString()});return tr(r.searchParams,"marker","1"),null!=t.state&&tr(r.searchParams,"state",t.state),null!=t.codeChallenge&&tr(r.searchParams,"codeChallenge",t.codeChallenge),null!=t.afterCallbackRedirectUrl&&tr(r.searchParams,"afterCallbackRedirectUrl",t.afterCallbackRedirectUrl),r}({currentUrl:t.currentUrl,localOAuthCallbackUrl:t.localOAuthCallbackUrl,state:t.crossDomainHandoffParams?.state,codeChallenge:t.crossDomainHandoffParams?.codeChallenge,afterCallbackRedirectUrl:s});r.searchParams.set("after_auth_return_to",n.toString()),tr(r.searchParams,"afterCallbackRedirectUrl",s),null!=t.crossDomainHandoffParams&&(tr(r.searchParams,"state",t.crossDomainHandoffParams.state),tr(r.searchParams,"codeChallenge",t.crossDomainHandoffParams.codeChallenge))}}else t.currentUrl.protocol!==r.protocol||t.currentUrl.host!==r.host||r.searchParams.has("after_auth_return_to")||r.searchParams.set("after_auth_return_to",(0,Q.getRelativePart)(t.currentUrl));return r.origin===t.currentUrl.origin?(0,Q.getRelativePart)(r):r.toString()}async function ta(t){let r=tn({handlerName:t.handlerName,rawHandlerUrl:t.rawHandlerUrl,currentUrl:t.currentUrl,crossDomainHandoffParams:null,localOAuthCallbackUrl:t.localOAuthCallbackUrl});if("signOut"===t.handlerName)return r;let i=new URL(r,t.currentUrl);if(t.currentUrl.origin===i.origin||ts(i))return r;let s=await t.getCrossDomainHandoffParams(t.currentUrl);return tn({handlerName:t.handlerName,rawHandlerUrl:t.rawHandlerUrl,currentUrl:t.currentUrl,crossDomainHandoffParams:s,localOAuthCallbackUrl:t.localOAuthCallbackUrl})}async function to(t){if(t.noRedirectBack||null==t.currentUrl)return{type:"redirect",url:t.rawHandlerUrl};let r=function(t){return"afterSignIn"===t||"afterSignUp"===t?"after-auth-return":"signIn"===t||"signUp"===t||"onboarding"===t||"signOut"===t?"redirect-back-aware":"none"}(t.handlerName);if("none"===r)return{type:"redirect",url:t.rawHandlerUrl};if("after-auth-return"===r){var i,s,n;let r,a,o=t.currentUrl.searchParams.get("after_auth_return_to");if(null==o)return{type:"redirect",url:t.rawHandlerUrl};let l=new URL(o,t.currentUrl),p=(r=(s=(i={currentUrl:t.currentUrl,redirectBackTarget:l}).currentUrl,n=i.redirectBackTarget,{state:te(s.searchParams,"state")??te(n.searchParams,"state"),codeChallenge:te(s.searchParams,"codeChallenge")??te(n.searchParams,"codeChallenge"),afterCallbackRedirectUrl:te(s.searchParams,"afterCallbackRedirectUrl")??te(n.searchParams,"afterCallbackRedirectUrl")}),null==(a=function(t){if(t.redirectBackTarget.origin!==t.currentUrl.origin)return t.redirectBackTarget;if(null==t.handoffParams.state||null==t.handoffParams.codeChallenge||null==t.handoffParams.afterCallbackRedirectUrl)return null;let r=new URL(t.handoffParams.afterCallbackRedirectUrl,t.currentUrl);return r.origin===t.currentUrl.origin?null:new URL(`${t.redirectBackTarget.pathname}${t.redirectBackTarget.search}${t.redirectBackTarget.hash}`,r.origin)}({currentUrl:i.currentUrl,redirectBackTarget:i.redirectBackTarget,handoffParams:r}))?null:{redirectBackTarget:a,handoffParams:r});if(null==p)return{type:"redirect",url:o};let u=p.handoffParams.state,c=p.handoffParams.codeChallenge,d=p.handoffParams.afterCallbackRedirectUrl;if(null==u||null==c){let r=await t.getCrossDomainHandoffParams(t.currentUrl);u??=r.state,c??=r.codeChallenge}return d??=t.currentUrl.toString(),{type:"cross-domain-authorize",redirectUri:p.redirectBackTarget.toString(),state:u,codeChallenge:c,afterCallbackRedirectUrl:d}}if("signIn"!==t.handlerName&&"signUp"!==t.handlerName&&"onboarding"!==t.handlerName&&"signOut"!==t.handlerName)throw new x.HexclaveAssertionError("Unexpected redirect-back-aware handler policy mismatch",{handlerName:t.handlerName,policy:r});return{type:"redirect",url:await ta({handlerName:t.handlerName,rawHandlerUrl:t.rawHandlerUrl,currentUrl:t.currentUrl,localOAuthCallbackUrl:t.localOAuthCallbackUrl,getCrossDomainHandoffParams:t.getCrossDomainHandoffParams})}}var tl=t.i(895842),tp=t.i(902528);let tu=null,tc=null,td=0,th=null;function tf(){let t=function(){try{let t=localStorage.getItem("__hexclave-dev-tool-override");if("true"===t)return!0;if("false"===t)return!1}catch{}return null}();return null!==t?t:!!(0,tp.canMountIntoDom)()&&(0,Q.isLocalhost)(window.location.href)}let tm=null,ty=null,tb=0,tg=null,tv=!1;tv=!0;let tx=eo(et),tT=new Map,tE="stackauth_",tS="hexclave_";function t_(t){return null==t.accessToken&&null==t.refreshToken?null:`Bearer ${tE}${(0,Y.encodeBase64)(new TextEncoder().encode(JSON.stringify(t)))}`}function tP(t,r){if("get"in t&&"function"==typeof t.get)return t.get(r);let i=r.toLowerCase();for(let[r,s]of Object.entries(t))if(r.toLowerCase()===i)return s;return null}async function tA(){return(await eb?.())?.get("host")??null}var tw=class r{static{this.LazyStackAdminAppImpl={value:void 0}}async _createCookieHelper(t){let r=void 0===t?this._tokenStoreInit:t;return"nextjs-cookie"===r||"cookie"===r?await eO():await eI()}async _getUserOAuthConnectionCacheFn(t){let r=await t.getUser(),i=!0;if(r&&r.oauth_providers.find(r=>r.id===t.providerId)||(i=!1),await t.getOrWaitOAuthToken()||(i=!1),!i&&t.redirect){if(!t.session)throw Error(G.deindent`
|
|
349
349
|
Cannot add new scopes to a user that is not a CurrentUser. Please ensure that you are calling this function on a CurrentUser object, or remove the 'or: redirect' option.
|
|
350
350
|
|
|
351
351
|
Often, you can solve this by calling this function in the browser instead, or by removing the 'or: redirect' option and dealing with the case where the user doesn't have enough permissions.
|
|
352
|
-
`);let r=await eJ(this._interface,{provider:t.providerId,redirectUrl:this._getOAuthCallbackRedirectUri(),errorRedirectUrl:this.urls.error,providerScope:(0,G.mergeScopeStrings)(t.scope||"",(this._oauthScopesOnSignIn[t.providerId]??[]).join(" "))},t.session);return await this._redirectTo({url:r}),await (0,E.neverResolve)()}if(!i)return null;let s=r.oauth_providers.find(r=>r.id===t.providerId)?.account_id??"";return{id:t.providerId,provider:t.providerId,providerAccountId:s,async getAccessToken(){let r=await t.getOrWaitOAuthToken();if(!r)throw new x.HexclaveAssertionError(`Failed to retrieve an access token for this connected account (provider: ${t.providerId}). This usually means the OAuth refresh token has been revoked or expired. The user needs to re-authorize by calling \`linkConnectedAccount\` or using \`getOrLinkConnectedAccount\`.`);return r},useAccessToken(){let r=t.useOAuthToken();if(!r)throw new x.HexclaveAssertionError(`Failed to retrieve an access token for this connected account (provider: ${t.providerId}). This usually means the OAuth refresh token has been revoked or expired. The user needs to re-authorize by calling \`linkConnectedAccount\` or using \`getOrLinkConnectedAccount\`.`);return r}}}_createOAuthConnectionFromCrudItem(t,r){let i=this,s=t.provider,n=t.provider_account_id;return{id:s,provider:s,providerAccountId:n,async getAccessToken(t){let a=t?.scopes?.join(" ")??"",o=w.Result.orThrow(await i._currentUserOAuthConnectionAccessTokensByAccountCache.getOrWait([r,s,n,a],"write-only"));if(!o){let t=a?`The requested scopes [${a}] are not available on the existing token.`:"The OAuth refresh token has likely been revoked or expired.";return w.Result.error(new P.KnownErrors.OAuthAccessTokenNotAvailable(s,`${t} The user needs to re-authorize by calling \`linkConnectedAccount\` or using \`getOrLinkConnectedAccount\`.`))}return w.Result.ok(o)},useAccessToken(t){let a=t?.scopes?.join(" ")??"",o=(0,C.useAsyncCache)(i._currentUserOAuthConnectionAccessTokensByAccountCache,[r,s,n,a],"connection.useAccessToken()");if(!o){let t=a?`The requested scopes [${a}] are not available on the existing token.`:"The OAuth refresh token has likely been revoked or expired.";return w.Result.error(new P.KnownErrors.OAuthAccessTokenNotAvailable(s,`${t} The user needs to re-authorize by calling \`linkConnectedAccount\` or using \`getOrLinkConnectedAccount\`.`))}return w.Result.ok(o)}}}constructor(i,s){this._uniqueIdentifier=void 0,this._sessionRecorder=null,this._eventTracker=null,this.__DEMO_ENABLE_SLIGHT_FETCH_DELAY=!1,this._ownedAdminApps=new ep.DependenciesMap,this._currentUserCache=(0,C.createCacheBySession)(async t=>(this.__DEMO_ENABLE_SLIGHT_FETCH_DELAY&&await (0,E.wait)(2e3),t.isKnownToBeInvalid())?null:await this._interface.getClientUserByToken(t)),this._currentProjectCache=(0,C.createCache)(async()=>w.Result.orThrow(await this._interface.getClientProject())),this._ownedProjectsCache=(0,C.createCacheBySession)(async t=>await this._interface.listProjects(t)),this._currentUserPermissionsCache=(0,C.createCacheBySession)(async(t,[r,i])=>await this._interface.listCurrentUserTeamPermissions({teamId:r,recursive:i},t)),this._currentUserProjectPermissionsCache=(0,C.createCacheBySession)(async(t,[r])=>await this._interface.listCurrentUserProjectPermissions({recursive:r},t)),this._currentUserTeamsCache=(0,C.createCacheBySession)(async t=>await this._interface.listCurrentUserTeams(t)),this._currentUserOAuthConnectionAccessTokensCache=(0,C.createCacheBySession)(async(t,[r,i])=>{try{return{accessToken:(await this._interface.createProviderAccessToken(r,i||"",t)).access_token}}catch(t){if(!(P.KnownErrors.OAuthAccessTokenNotAvailable.isInstance(t)||P.KnownErrors.OAuthConnectionDoesNotHaveRequiredScope.isInstance(t)||P.KnownErrors.OAuthConnectionNotConnectedToUser.isInstance(t)))throw t}return null}),this._currentUserOAuthConnectionCache=(0,C.createCacheBySession)(async(t,[r,i,s])=>await this._getUserOAuthConnectionCacheFn({getUser:async()=>w.Result.orThrow(await this._currentUserCache.getOrWait([t],"write-only")),getOrWaitOAuthToken:async()=>w.Result.orThrow(await this._currentUserOAuthConnectionAccessTokensCache.getOrWait([t,r,i||""],"write-only")),useOAuthToken:()=>(0,C.useAsyncCache)(this._currentUserOAuthConnectionAccessTokensCache,[t,r,i||""],"connection.useAccessToken()"),providerId:r,scope:i,redirect:s,session:t})),this._currentUserConnectedAccountsCache=(0,C.createCacheBySession)(async t=>(await this._interface.listConnectedAccounts(t)).items.map(r=>this._createOAuthConnectionFromCrudItem(r,t))),this._currentUserOAuthConnectionAccessTokensByAccountCache=(0,C.createCacheBySession)(async(t,[r,i,s])=>{try{return{accessToken:(await this._interface.createProviderAccessTokenByAccount(r,i,s,t)).access_token}}catch(t){if(P.KnownErrors.OAuthAccessTokenNotAvailable.isInstance(t)||P.KnownErrors.OAuthConnectionDoesNotHaveRequiredScope.isInstance(t)||P.KnownErrors.OAuthConnectionNotConnectedToUser.isInstance(t))return null;throw t}}),this._currentUserValidConnectedAccountForProviderCache=(0,C.createCacheBySession)(async(t,[r,i])=>{let s=w.Result.orThrow(await this._currentUserConnectedAccountsCache.getOrWait([t],"write-only")).filter(t=>t.provider===r),n=i?i.split(" "):void 0;for(let t of s)if("ok"===(await t.getAccessToken({scopes:n})).status)return t;let a=await eJ(this._interface,{provider:r,redirectUrl:this._getOAuthCallbackRedirectUri(),errorRedirectUrl:this.urls.error,providerScope:(0,G.mergeScopeStrings)(i,(this._oauthScopesOnSignIn[r]??[]).join(" "))},t);return await this._redirectTo({url:a}),await (0,E.neverResolve)()}),this._teamMemberProfilesCache=(0,C.createCacheBySession)(async(t,[r])=>await this._interface.listTeamMemberProfiles({teamId:r},t)),this._teamInvitationsCache=(0,C.createCacheBySession)(async(t,[r])=>await this._interface.listTeamInvitations({teamId:r},t)),this._currentUserTeamProfileCache=(0,C.createCacheBySession)(async(t,[r])=>await this._interface.getTeamMemberProfile({teamId:r,userId:"me"},t)),this._currentUserTeamInvitationsCache=(0,C.createCacheBySession)(async t=>await this._interface.listCurrentUserTeamInvitations(t)),this._clientContactChannelsCache=(0,C.createCacheBySession)(async t=>await this._interface.listClientContactChannels(t)),this._userApiKeysCache=(0,C.createCacheBySession)(async t=>await this._interface.listProjectApiKeys({user_id:"me"},t,"client")),this._teamApiKeysCache=(0,C.createCacheBySession)(async(t,[r])=>await this._interface.listProjectApiKeys({team_id:r},t,"client")),this._notificationCategoriesCache=(0,C.createCacheBySession)(async t=>await this._interface.listNotificationCategories(t)),this._currentUserOAuthProvidersCache=(0,C.createCacheBySession)(async t=>await this._interface.listOAuthProviders({user_id:"me"},t)),this._userItemCache=(0,C.createCacheBySession)(async(t,[r,i])=>await this._interface.getItem({userId:r,itemId:i},t)),this._teamItemCache=(0,C.createCacheBySession)(async(t,[r,i])=>await this._interface.getItem({teamId:r,itemId:i},t)),this._customItemCache=(0,C.createCacheBySession)(async(t,[r,i])=>await this._interface.getItem({customCustomerId:r,itemId:i},t)),this._userProductsCache=(0,C.createCacheBySession)(async(t,[r,i,s])=>await this._interface.listProducts({customer_type:"user",customer_id:r,cursor:i??void 0,limit:s??void 0},t)),this._teamProductsCache=(0,C.createCacheBySession)(async(t,[r,i,s])=>await this._interface.listProducts({customer_type:"team",customer_id:r,cursor:i??void 0,limit:s??void 0},t)),this._customProductsCache=(0,C.createCacheBySession)(async(t,[r,i,s])=>await this._interface.listProducts({customer_type:"custom",customer_id:r,cursor:i??void 0,limit:s??void 0},t)),this._userInvoicesCache=(0,C.createCacheBySession)(async(t,[r,i,s])=>await this._interface.listInvoices({customer_type:"user",customer_id:r,cursor:i??void 0,limit:s??void 0},t)),this._teamInvoicesCache=(0,C.createCacheBySession)(async(t,[r,i,s])=>await this._interface.listInvoices({customer_type:"team",customer_id:r,cursor:i??void 0,limit:s??void 0},t)),this._customerBillingCache=(0,C.createCacheBySession)(async(t,[r,i])=>await this._interface.getCustomerBilling(r,i,t)),this._convexPartialUserCache=(0,C.createCache)(async([t])=>await this._getPartialUserFromConvex(t)),this._trustedParentDomainCache=(0,C.createCache)(async([t])=>await this._getTrustedParentDomain(t)),this._anonymousSignUpInProgress=null,this._prefetchedCrossDomainHandoffParams=null,this._prefetchedCrossDomainHandoffParamsFetchedAt=0,this._isPrefetchingCrossDomainHandoffParams=!1,this._pendingAuthResolutionPromises=[],this._memoryTokenStore=(0,C.createEmptyTokenStore)(),this._nextServerCookiesTokenStores=new WeakMap,this._requestTokenStores=new WeakMap,this._storedBrowserCookieTokenStore=null,this._mostRecentQueuedCookieRefreshIndex=0,this._sessionsByTokenStoreAndSessionKey=new WeakMap,this._botChallengeSiteKeysWarned=!1;const n=(0,C.resolveConstructorOptions)(i);if(!r.LazyStackAdminAppImpl.value)throw new x.HexclaveAssertionError("Admin app implementation not initialized. Did you import the _HexclaveClientApp from hexclave-app/apps/implementations/index.ts? You can't import it directly from ./apps/implementations/client-app-impl.ts as that causes a circular dependency (see the comment at _LazyHexclaveAdminAppImpl for more details).");this._options=n,this._extraOptions=s;const a=n.projectId??(0,C.getDefaultProjectId)();if("internal"!==a&&!a.match(/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}$/i))throw Error(`Invalid project ID: ${a}. Project IDs must be UUIDs. Please check your environment variables and/or your StackApp.`);const o=n.publishableClientKey??(0,C.getDefaultPublishableClientKey)();if(s&&s.interface)this._interface=s.interface;else{const t=(0,C.resolveApiUrls)(n.baseUrl);this._interface=new Z.HexclaveClientInterface({getBaseUrl:()=>t()[0],getAnalyticsBaseUrl:()=>(0,C.getAnalyticsBaseUrl)(t()[0]),getApiUrls:t,extraRequestHeaders:n.extraRequestHeaders??(0,C.getDefaultExtraRequestHeaders)(),projectId:a,clientVersion:C.clientVersion,...null!=o?{publishableClientKey:o}:{},prepareRequest:async()=>{await ey?.()}})}this._tokenStoreInit=n.tokenStore,this._redirectMethod=n.redirectMethod||((0,er.isBrowserLike)()?"window":"none"),this._redirectMethod=n.redirectMethod||"nextjs",this._urlOptions=n.urls??{},this._oauthScopesOnSignIn=n.oauthScopesOnSignIn??{},(0,er.isBrowserLike)()&&("cookie"===n.tokenStore||"nextjs-cookie"===n.tokenStore)&&((0,E.runAsynchronously)(this._trustedParentDomainCache.getOrWait([window.location.hostname],"write-only")),this._ensureCrossSubdomainCookieExists()),s&&s.uniqueIdentifier&&(this._uniqueIdentifier=s.uniqueIdentifier,this._initUniqueIdentifier()),this._analyticsOptions=n.analytics;const l=async()=>(this._ensurePersistentTokenStore(),await this.getPartialUser({from:"token",or:"anonymous-if-exists"}))?await this._getSession():(await this.getUser({or:"anonymous"}))._internalSession,p=this._analyticsOptions?.enabled!==!1,u=function(t){return{...t?.replays,enabled:t?.replays?.enabled??!0}}(this._analyticsOptions);if(p&&(0,er.isBrowserLike)()&&this._hasPersistentTokenStore()&&u.enabled&&(this._sessionRecorder=new e4({projectId:this.projectId,sendBatch:async(t,r)=>await this._interface.sendSessionReplayBatch(t,await l(),r)},u),this._sessionRecorder.start()),p&&(0,er.isBrowserLike)()&&this._hasPersistentTokenStore()&&(this._eventTracker=new e9({projectId:this.projectId,sendBatch:async(t,r)=>await this._interface.sendAnalyticsEventBatch(t,await l(),r)}),this._eventTracker.start()),(0,er.isBrowserLike)()&&(this._isOAuthCallbackUrlHosted()||this._currentUrlLooksLikeNestedCrossDomainOAuthCallback())&&this._currentUrlLooksLikeHexclaveOAuthCallback()&&this._trackPendingAuthResolution(async()=>{(0,er.isBrowserLike)()&&await this.callOAuthCallback({dontWarnAboutMissingQueryParams:!0})}),(0,er.isBrowserLike)()){const t=new URL(window.location.href);this._trackPendingAuthResolution(async()=>{await this._maybeHandleNestedCrossDomainAuth(t)})}(0,er.isBrowserLike)()&&!1!==n.devTool&&function(r){tm=r,function(){if(tf&&(tf(),tf=null),!th()||!tm||!(0,tl.canMountIntoDom)())return;let r=++ty,i=tm;(0,E.runAsynchronously)(async()=>{let s=await (!tb&&(tb=t.A(295567).then(t=>t.createDevTool).catch(t=>{throw tb=null,t})),tb);r!==ty||th()&&tm===i&&(0,tl.canMountIntoDom)()&&(tf=s(i))},{noErrorLogging:!0,onError:t=>{(0,x.captureError)("dev-tool-mount",t)}})}()}(this),(0,er.isBrowserLike)()&&function(r){tp=r,(0,tl.canMountIntoDom)()&&function(){try{if("1"!==sessionStorage.getItem(to.CLICKMAP_OVERLAY_RESUME_STORAGE_KEY))return!1;return sessionStorage.removeItem(to.CLICKMAP_OVERLAY_RESUME_STORAGE_KEY),!0}catch{return!1}}()&&function(){if(tu||!tp||!(0,tl.canMountIntoDom)())return;let r=++tc,i=tp;(0,E.runAsynchronously)(async()=>{let s=await (!td&&(td=t.A(273427).then(t=>t.openClickmapOverlay).catch(t=>{throw td=null,t})),td);r!==tc||!tu&&tp===i&&(0,tl.canMountIntoDom)()&&(tu=s(i,()=>{tu=null}))},{noErrorLogging:!0,onError:t=>{(0,x.captureError)("clickmap-mount",t)}})}()}(this)}_initUniqueIdentifier(){if(!this._uniqueIdentifier)throw new x.HexclaveAssertionError("Unique identifier not initialized");if(tx.has(this._uniqueIdentifier))throw new x.HexclaveAssertionError("A Stack client app with the same unique identifier already exists");tx.set(this._uniqueIdentifier,[this._extraOptions?.checkString??void 0,this])}_trackPendingAuthResolution(t){let r=(async()=>{await Promise.resolve();try{await t()}catch(t){(0,x.captureError)("pending-auth-resolution-failed",t)}})();this._pendingAuthResolutionPromises.push(r),(0,E.runAsynchronously)(async()=>{try{await r}finally{this._pendingAuthResolutionPromises=this._pendingAuthResolutionPromises.filter(t=>t!==r)}})}async _awaitPendingAuthResolutions(t,r){r?.awaitPendingAuthResolutions!==!1&&void 0===t&&this._hasPersistentTokenStore()&&0!==this._pendingAuthResolutionPromises.length&&await Promise.all(this._pendingAuthResolutionPromises)}_usePendingAuthResolutions(t){void 0===t&&this._hasPersistentTokenStore()&&0!==this._pendingAuthResolutionPromises.length&&(0,A.use)(Promise.all(this._pendingAuthResolutionPromises))}_isOAuthCallbackUrlHosted(){let t=this._urlOptions.oauthCallback??this._urlOptions.default;return"string"!=typeof t&&t?.type==="hosted"}_currentUrlLooksLikeOAuthCallback(){return!1}_currentUrlLooksLikeHexclaveOAuthCallback(){return!1}_currentUrlLooksLikeNestedCrossDomainOAuthCallback(){return!1}_getOAuthCallbackRedirectUri(){if(!this._isOAuthCallbackUrlHosted())return this.urls.oauthCallback;throw new x.HexclaveAssertionError("Hosted OAuth callback URLs require a browser environment to use the current URL as the redirect URI")}async _fetchCurrentRefreshTokenIdIfSignedIn(t){let r=await (await this._getSession(t?.overrideTokenStoreInit,t)).fetchNewTokens();return r?.refreshToken==null?null:r.accessToken.payload.refresh_token_id}async _addNestedCrossDomainAuthParamsToRedirectUrl(t){let r=new URL(t.url,t.currentUrl);if(r.origin===t.currentUrl.origin)return t.url;let i=await this._fetchCurrentRefreshTokenIdIfSignedIn({awaitPendingAuthResolutions:t.awaitPendingAuthResolutions,overrideTokenStoreInit:t.overrideTokenStoreInit});return null==i?t.url:(r.searchParams.set("stack_nested_cross_domain_auth_refresh_token_id",i),r.searchParams.set("stack_nested_cross_domain_auth_callback_url",new URL(this._getOAuthCallbackRedirectUri(),t.currentUrl).toString()),r.toString())}async _maybeHandleNestedCrossDomainAuth(t){return!1}_getUniqueIdentifier(){return this._uniqueIdentifier||(this._uniqueIdentifier=(0,eh.generateUuid)(),this._initUniqueIdentifier()),this._uniqueIdentifier}async _checkFeatureSupport(t,r){return await this._interface.checkFeatureSupport({...r,name:t})}_useCheckFeatureSupport(t,r){throw(0,E.runAsynchronously)(this._checkFeatureSupport(t,r)),new x.HexclaveAssertionError(`${t} is not currently supported. Please reach out to Stack support for more information.`)}get _legacyRefreshTokenCookieName(){return`stack-refresh-${this.projectId}`}get _refreshTokenCookieName(){return`hexclave-refresh-${this.projectId}`}_getRefreshTokenDefaultCookieNameForSecure(t){return`${t?"__Host-":""}${this._refreshTokenCookieName}--default`}_getCustomRefreshCookieName(t){let r=(0,Y.encodeBase32)(new TextEncoder().encode(t.toLowerCase()));return`${this._refreshTokenCookieName}--custom-${r}`}_getDomainFromCustomRefreshCookieName(t){for(let r of[this._refreshTokenCookieName,this._legacyRefreshTokenCookieName]){let i=`${r}--custom-`;if(t.startsWith(i))try{return new TextDecoder().decode((0,Y.decodeBase32)(t.slice(i.length)))}catch{break}}return null}_formatRefreshCookieValue(t,r){return JSON.stringify({refresh_token:t,updated_at_millis:r})}_formatAccessCookieValue(t,r){return t&&r?JSON.stringify([t,r]):null}_parseStructuredRefreshCookie(t){if(!t)return null;let r=el(t);if("ok"!==r.status||"object"!=typeof r.data||null===r.data)return console.warn("Failed to parse structured refresh cookie"),null;let i=r.data,s="refresh_token"in i&&"string"==typeof i.refresh_token?i.refresh_token:null,n="updated_at_millis"in i&&"number"==typeof i.updated_at_millis?i.updated_at_millis:null;return s?{refreshToken:s,updatedAt:n}:(console.warn("Refresh token not found in structured refresh cookie"),null)}_extractRefreshTokenFromCookieMap(t){let{legacyNames:r,structuredPrefixes:i}=this._getRefreshTokenCookieNamePatterns(),s=[`${this._refreshTokenCookieName}--`,`__Host-${this._refreshTokenCookieName}--`],n=r=>{let i=null;for(let[s,n]of Object.entries(t)){if(!r.some(t=>s.startsWith(t)))continue;let t=this._parseStructuredRefreshCookie(n);if(!t)continue;let a=t.updatedAt??-1/0,o=i?.updatedAt??-1/0;(!i||a>o)&&(i=t)}return i},a=n(s);if(a)return{refreshToken:a.refreshToken,updatedAt:a.updatedAt??null};for(let i of r){let r=t[i];if(r)return{refreshToken:r,updatedAt:null}}let o=n(i);return o?{refreshToken:o.refreshToken,updatedAt:o.updatedAt??null}:{refreshToken:null,updatedAt:null}}_getTokensFromCookies(t){let{refreshToken:r}=this._extractRefreshTokenFromCookieMap(t),i=t[this._accessTokenCookieName]??t[this._legacyAccessTokenCookieName]??null,s=null;if(i&&i.startsWith('["')){let t=el(i);"ok"===t.status&&"object"==typeof t.data&&null!==t.data&&Array.isArray(t.data)&&2===t.data.length&&"string"==typeof t.data[0]&&"string"==typeof t.data[1]?t.data[0]===r&&(s=t.data[1]):console.warn("Access token cookie has invalid format")}return{refreshToken:r,accessToken:s}}_getCurrentBrowserCookieTokenStoreValue(t){let r=this._getTokensFromCookies(this._getAllBrowserCookies());return{refreshToken:r.refreshToken,accessToken:r.accessToken??(t?.refreshToken===r.refreshToken?t.accessToken:null)}}get _accessTokenCookieName(){return"hexclave-access"}get _legacyAccessTokenCookieName(){return"stack-access"}_getAllBrowserCookies(){if(!(0,er.isBrowserLike)())throw new x.HexclaveAssertionError("Cannot get browser cookies on the server!");return ef.parseCookie(document.cookie||"")}_getRefreshTokenCookieNamePatterns(){return{legacyNames:[this._legacyRefreshTokenCookieName,"stack-refresh"],structuredPrefixes:[`${this._refreshTokenCookieName}--`,`__Host-${this._refreshTokenCookieName}--`,`${this._legacyRefreshTokenCookieName}--`,`__Host-${this._legacyRefreshTokenCookieName}--`]}}_collectRefreshTokenCookieNames(t){let{legacyNames:r,structuredPrefixes:i}=this._getRefreshTokenCookieNamePatterns(),s=new Set;for(let i of r)t[i]&&s.add(i);for(let r of Object.keys(t))i.some(t=>r.startsWith(t))&&s.add(r);return s}_prepareRefreshCookieUpdate(t,r,i,s){let n=this._collectRefreshTokenCookieNames(t);n.delete(s);let a=r?Date.now():null;return{updatedAt:a,refreshCookieValue:r&&null!==a?this._formatRefreshCookieValue(r,a):null,accessTokenPayload:this._formatAccessCookieValue(r,i),cookieNamesToDelete:[...n]}}_ensureCrossSubdomainCookieExists(){(0,E.runAsynchronously)(async()=>{let t=window.location.hostname,r=await this._trustedParentDomainCache.getOrWait([t],"read-write");if("error"===r.status||!r.data)return;let i=this._getAllBrowserCookies(),s=this._getCustomRefreshCookieName(r.data);if(i[s])return;let{refreshToken:n,updatedAt:a}=this._extractRefreshTokenFromCookieMap(i);n&&a&&e$(s,this._formatRefreshCookieValue(n,a),{maxAge:31536e3,domain:r.data})})}_queueCustomRefreshCookieUpdate(t,r,i){(0,E.runAsynchronously)(async()=>{let s;this._mostRecentQueuedCookieRefreshIndex++;let n=this._mostRecentQueuedCookieRefreshIndex;if(!(s=(0,er.isBrowserLike)()?window.location.hostname:await tP()))return void console.warn("No hostname found when queueing custom refresh cookie update");let a=await this._trustedParentDomainCache.getOrWait([s],"read-write"),o={maxAge:31536e3,noOpIfServerComponent:!0},l=async(t,r)=>{let s=this._getCustomRefreshCookieName(t),n={...o,domain:t};"browser"===i?e$(s,r,n):await eV(s,r,n)};if("error"===a.status||!a.data||n!==this._mostRecentQueuedCookieRefreshIndex)return;let p=t&&r?this._formatRefreshCookieValue(t,r):null;await l(a.data,p);let u=await eM(),c=this._getRefreshTokenDefaultCookieNameForSecure(u);"browser"===i?e$(c,null,o):await eV(c,null,o)})}async _getTrustedRedirectConfig(){let t=w.Result.orThrow(await this._currentProjectCache.getOrWait([],"write-only"));return{allowLocalhost:t.config.allow_localhost,trustedDomains:[...t.config.domains.map(t=>t.domain),new URL((0,eX.getHostedHandlerUrl)({projectId:this.projectId,pagePath:""})).origin]}}async _getTrustedParentDomain(t){return(0,ei.getTrustedParentDomain)(t,(await this._getTrustedRedirectConfig()).trustedDomains)}_getBrowserCookieTokenStore(){if(!(0,er.isBrowserLike)())throw Error("Cannot use cookie token store on the server!");if(null===this._storedBrowserCookieTokenStore){this._storedBrowserCookieTokenStore=new ea.Store(this._getCurrentBrowserCookieTokenStoreValue(null));let t=!0;setInterval(()=>{if(t){let t=this._storedBrowserCookieTokenStore.get(),r=this._getCurrentBrowserCookieTokenStoreValue(t);(0,z.deepPlainEquals)(r,t)||this._storedBrowserCookieTokenStore.set(r)}},100),this._storedBrowserCookieTokenStore.onChange(r=>{try{let i=r.refreshToken,s="https:"===window.location.protocol,n=this._getRefreshTokenDefaultCookieNameForSecure(s),{updatedAt:a,refreshCookieValue:o,accessTokenPayload:l,cookieNamesToDelete:p}=this._prepareRefreshCookieUpdate(this._getAllBrowserCookies(),i,r.accessToken??null,n);e$(n,o,{maxAge:31536e3,secure:s}),e$(this._accessTokenCookieName,l,{maxAge:86400}),p.forEach(t=>{let r=this._getDomainFromCustomRefreshCookieName(t);eK(t,r?{domain:r}:{})}),this._queueCustomRefreshCookieUpdate(i,a,"browser"),t=!0}catch(r){if((0,er.isBrowserLike)())throw r;t=!1}})}else{let t=this._storedBrowserCookieTokenStore.get(),r=this._getCurrentBrowserCookieTokenStoreValue(t);(0,z.deepPlainEquals)(r,t)||this._storedBrowserCookieTokenStore.set(r)}return this._storedBrowserCookieTokenStore}_getOrCreateTokenStore(t,r){let i=void 0===r?this._tokenStoreInit:r;switch(i){case"cookie":return this._getBrowserCookieTokenStore();case"nextjs-cookie":if((0,er.isBrowserLike)())return this._getBrowserCookieTokenStore();{let r=new ea.Store(this._getTokensFromCookies(t.getAll()));return r.onChange(r=>{(0,E.runAsynchronously)(async()=>{let i=r.refreshToken,s=await eM(),n=this._getRefreshTokenDefaultCookieNameForSecure(s),{updatedAt:a,refreshCookieValue:o,accessTokenPayload:l,cookieNamesToDelete:p}=this._prepareRefreshCookieUpdate(t.getAll(),i,r.accessToken??null,n);await Promise.all([eV(n,o,{maxAge:31536e3,noOpIfServerComponent:!0}),eV(this._accessTokenCookieName,l,{maxAge:86400,noOpIfServerComponent:!0})]),p.length>0&&await Promise.all(p.map(t=>{let r=this._getDomainFromCustomRefreshCookieName(t);return eq(t,{noOpIfServerComponent:!0,...r?{domain:r}:{}})})),this._queueCustomRefreshCookieUpdate(i,a,"server")})}),r}case"memory":return this._memoryTokenStore;default:if(null===i)return(0,C.createEmptyTokenStore)();if("object"==typeof i&&"headers"in i){if(this._requestTokenStores.has(i))return this._requestTokenStores.get(i);let r=t_(i.headers,"authorization");if(r){let t=function(t){let r,i=t.match(/^Bearer\s+(.+)$/i);if(null==i)return null;let s=i[1].trim(),n=s.startsWith(tE)?tE:s.startsWith(tT)?tT:null;if(null==n)return null;let a=s.slice(n.length);if(0===a.length)throw Error("Invalid Authorization header format. Expected `Bearer stackauth_<base64(getAuthJson())>`.");try{let t=new TextDecoder().decode((0,Y.decodeBase64)(a));r=JSON.parse(t)}catch(t){throw Error("Invalid stackauth authorization header.",{cause:t})}if(null==r||"object"!=typeof r||Array.isArray(r))throw Error("Invalid stackauth authorization payload. Expected an object.");let o=Reflect.get(r,"accessToken"),l=Reflect.get(r,"refreshToken");if(null!=o&&"string"!=typeof o)throw Error("Invalid stackauth authorization payload. `accessToken` must be a string or null.");if(null!=l&&"string"!=typeof l)throw Error("Invalid stackauth authorization payload. `refreshToken` must be a string or null.");return{accessToken:o??null,refreshToken:l??null}}(r);if(null!=t){let r=new ea.Store({accessToken:t.accessToken,refreshToken:t.refreshToken});return this._requestTokenStores.set(i,r),r}}let s=t_(i.headers,"x-stack-auth");if(s){let r;try{if(r=JSON.parse(s),"object"!=typeof r)throw Error("x-stack-auth header must be a JSON object");if(null===r)throw Error("x-stack-auth header must not be null")}catch(t){throw Error("Invalid x-stack-auth header.",{cause:t})}return this._getOrCreateTokenStore(t,{accessToken:r.accessToken??null,refreshToken:r.refreshToken??null})}let n=t_(i.headers,"cookie"),a=ef.parseCookie(n||""),o=new ea.Store(this._getTokensFromCookies(a));return this._requestTokenStores.set(i,o),o}if("accessToken"in i||"refreshToken"in i)return new ea.Store({refreshToken:i.refreshToken,accessToken:i.accessToken});throw Error(`Invalid token store ${i}`)}}_useTokenStore(t){(0,A.suspendIfSsr)();let r=eD();return this._getOrCreateTokenStore(r,t)}_getSessionFromTokenStore(t){let r=t.get(),i=I.InternalSession.calculateSessionKey(r),s=i?this._sessionsByTokenStoreAndSessionKey.get(t)?.get(i):null;if(s)return s;let n=this._interface.createSession({refreshToken:r.refreshToken,accessToken:r.accessToken});n.onAccessTokenChange(r=>{t.update(t=>I.InternalSession.calculateSessionKey(t)===i?{...t,accessToken:r?.token??null}:t)}),n.onInvalidate(()=>{t.update(t=>I.InternalSession.calculateSessionKey(t)===i?{...t,accessToken:null,refreshToken:null}:t)});let a=this._sessionsByTokenStoreAndSessionKey.get(t)??new Map;return this._sessionsByTokenStoreAndSessionKey.set(t,a),a.set(i,n),n}async _getSession(t,r){await this._awaitPendingAuthResolutions(t,r);let i=this._getOrCreateTokenStore(await this._createCookieHelper(t),t);return this._getSessionFromTokenStore(i)}_useSession(t){this._usePendingAuthResolutions(t);let r=this._useTokenStore(t),i=(0,S.useCallback)(t=>{var i;let s,n,a,o,l;return s=(i={tokenStore:r,getSession:()=>this._getSessionFromTokenStore(r),onTokenStoreChange:t}).minMillisUntilExpiration??3e4,n=i.maxMillisSinceIssued??6e4,o=(a=i.getSession()).startRefreshingAccessToken(s,n),l=i.tokenStore.onChange(()=>{let t=i.getSession();t.sessionKey!==a.sessionKey&&(o.unsubscribe(),o=(a=t).startRefreshingAccessToken(s,n)),i.onTokenStoreChange()}),()=>{l.unsubscribe(),o.unsubscribe()}},[r]),s=(0,S.useCallback)(()=>this._getSessionFromTokenStore(r),[r]);return S.default.useSyncExternalStore(i,s,s)}async _signInToAccountWithTokens(t){if(!("accessToken"in t)||!("refreshToken"in t))throw new x.HexclaveAssertionError("Invalid tokens object; can't sign in with this",{tokens:t});let r=this._getOrCreateTokenStore(await this._createCookieHelper());r.set(t);let i=this._getSessionFromTokenStore(r);i.updateAccessToken(t),(0,E.runAsynchronously)(this._currentUserCache.getOrWait([i],"write-only"))}_getTokenStoreInitForFreshTokens(t){if(null!=t.accessToken)return{accessToken:t.accessToken,refreshToken:t.refreshToken}}_hasPersistentTokenStore(t){return(void 0!==t?t:this._tokenStoreInit)!==null}_ensurePersistentTokenStore(t){if(!this._hasPersistentTokenStore(t))throw Error("Cannot call this function on a Stack app without a persistent token store. Make sure the tokenStore option on the constructor is set to a non-null value when initializing Stack.\n\nStack uses token stores to access access tokens of the current user. For example, on web frontends it is commonly the string value 'cookies' for cookie storage.")}_isInternalProject(){return"internal"===this.projectId}_ensureInternalProject(){if(!this._isInternalProject())throw Error("Cannot call this function on a Stack app with a project ID other than 'internal'.")}_clientProjectFromCrud(t){return{id:t.id,displayName:t.display_name,config:{signUpEnabled:t.config.sign_up_enabled,credentialEnabled:t.config.credential_enabled,magicLinkEnabled:t.config.magic_link_enabled,passkeyEnabled:t.config.passkey_enabled,clientTeamCreationEnabled:t.config.client_team_creation_enabled,clientUserDeletionEnabled:t.config.client_user_deletion_enabled,allowTeamApiKeys:t.config.allow_team_api_keys,allowUserApiKeys:t.config.allow_user_api_keys,oauthProviders:t.config.enabled_oauth_providers.map(t=>({id:t.id}))}}}_clientPermissionFromCrud(t){return{id:t.id}}_clientTeamUserFromCrud(t){return{id:t.user_id,teamProfile:{displayName:t.display_name,profileImageUrl:t.profile_image_url}}}_clientSentTeamInvitationFromCrud(t,r){return{id:r.id,recipientEmail:r.recipient_email,expiresAt:new Date(r.expires_at_millis),revoke:async()=>{await this._interface.revokeTeamInvitation(r.id,r.team_id,t),await this._teamInvitationsCache.refresh([t,r.team_id])}}}_clientReceivedTeamInvitationFromCrud(t,r){let i=this;return{id:r.id,teamId:r.team_id,teamDisplayName:r.team_display_name,recipientEmail:r.recipient_email,expiresAt:new Date(r.expires_at_millis),accept:async()=>{await i._interface.acceptTeamInvitationById(r.id,t),await Promise.all([i._currentUserTeamInvitationsCache.refresh([t]),i._currentUserTeamsCache.refresh([t]),i._teamInvitationsCache.refresh([t,r.team_id])])}}}_baseApiKeyFromCrud(t){return{id:t.id,description:t.description,expiresAt:t.expires_at_millis?new Date(t.expires_at_millis):void 0,manuallyRevokedAt:t.manually_revoked_at_millis?new Date(t.manually_revoked_at_millis):null,createdAt:new Date(t.created_at_millis),..."team"===t.type?{type:"team",teamId:t.team_id}:{type:"user",userId:t.user_id},value:"string"==typeof t.value?t.value:{lastFour:t.value.last_four},isValid:function(){return null===this.whyInvalid()},whyInvalid:function(){return this.manuallyRevokedAt?"manually-revoked":this.expiresAt&&this.expiresAt<new Date?"expired":null}}}_clientApiKeyFromCrud(t,r){return{...this._baseApiKeyFromCrud(r),async revoke(){await this.update({revoked:!0})},update:async i=>{await this._interface.updateProjectApiKey("team"===r.type?{team_id:r.team_id}:{user_id:r.user_id},r.id,i,t,"client"),"team"===r.type?await this._teamApiKeysCache.refresh([t,r.team_id]):await this._userApiKeysCache.refresh([t])}}}_clientTeamFromCrud(t,r){let i=this;return{id:t.id,displayName:t.display_name,profileImageUrl:t.profile_image_url,clientMetadata:t.client_metadata,clientReadOnlyMetadata:t.client_read_only_metadata,...this._createCustomer(t.id,"team",r),async inviteUser(s){await i._interface.sendTeamInvitation({teamId:t.id,email:s.email,session:r,callbackUrl:s.callbackUrl??q(i._getUrls().teamInvitation,"callbackUrl")}),await i._teamInvitationsCache.refresh([r,t.id])},listUsers:async()=>w.Result.orThrow(await i._teamMemberProfilesCache.getOrWait([r,t.id],"write-only")).map(t=>i._clientTeamUserFromCrud(t)),useUsers:()=>(0,C.useAsyncCache)(i._teamMemberProfilesCache,[r,t.id],"team.useUsers()").map(t=>i._clientTeamUserFromCrud(t)),listInvitations:async()=>w.Result.orThrow(await i._teamInvitationsCache.getOrWait([r,t.id],"write-only")).map(t=>i._clientSentTeamInvitationFromCrud(r,t)),useInvitations:()=>(0,C.useAsyncCache)(i._teamInvitationsCache,[r,t.id],"team.useInvitations()").map(t=>i._clientSentTeamInvitationFromCrud(r,t)),async update(s){await i._interface.updateTeam({data:{display_name:s.displayName,profile_image_url:s.profileImageUrl,client_metadata:s.clientMetadata},teamId:t.id},r),await i._currentUserTeamsCache.refresh([r])},async delete(){await i._interface.deleteTeam(t.id,r),await i._currentUserTeamsCache.refresh([r])},useApiKeys:()=>(0,C.useAsyncCache)(i._teamApiKeysCache,[r,t.id],"team.useApiKeys()").map(t=>i._clientApiKeyFromCrud(r,t)),listApiKeys:async()=>w.Result.orThrow(await i._teamApiKeysCache.getOrWait([r,t.id],"write-only")).map(t=>i._clientApiKeyFromCrud(r,t)),async createApiKey(s){let n=await i._interface.createProjectApiKey(await W("team",t.id,s),r,"client");return await i._teamApiKeysCache.refresh([r,t.id]),i._clientApiKeyFromCrud(r,n)}}}_clientContactChannelFromCrud(t,r){let i=this;return{id:t.id,value:t.value,type:t.type,isVerified:t.is_verified,isPrimary:t.is_primary,usedForAuth:t.used_for_auth,async sendVerificationEmail(s){await i._interface.sendCurrentUserContactChannelVerificationEmail(t.id,s?.callbackUrl||q(i._getUrls().emailVerification,"callbackUrl"),r)},async update(s){await i._interface.updateClientContactChannel(t.id,{value:s.value,used_for_auth:s.usedForAuth,is_primary:s.isPrimary},r),await i._clientContactChannelsCache.refresh([r])},async delete(){await i._interface.deleteClientContactChannel(t.id,r),await i._clientContactChannelsCache.refresh([r])}}}_clientNotificationCategoryFromCrud(t,r){let i=this;return{id:t.notification_category_id,name:t.notification_category_name,enabled:t.enabled,canDisable:t.can_disable,async setEnabled(s){await i._interface.setNotificationsEnabled(t.notification_category_id,s,r),await i._notificationCategoriesCache.refresh([r])}}}_clientOAuthProviderFromCrud(t,r){let i=this;return{id:t.id,type:t.type,userId:t.user_id,email:t.email,allowSignIn:t.allow_sign_in,allowConnectedAccounts:t.allow_connected_accounts,async update(s){try{return await i._interface.updateOAuthProvider(t.user_id,t.id,{allow_sign_in:s.allowSignIn,allow_connected_accounts:s.allowConnectedAccounts},r),await Promise.all([i._currentUserOAuthProvidersCache.refresh([r]),i._currentUserConnectedAccountsCache.refresh([r])]),w.Result.ok(void 0)}catch(t){if(P.KnownErrors.OAuthProviderAccountIdAlreadyUsedForSignIn.isInstance(t))return w.Result.error(t);throw t}},async delete(){await i._interface.deleteOAuthProvider(t.user_id,t.id,r),await Promise.all([i._currentUserOAuthProvidersCache.refresh([r]),i._currentUserConnectedAccountsCache.refresh([r])])}}}_clientItemFromCrud(t){return{displayName:t.display_name,quantity:t.quantity,nonNegativeQuantity:Math.max(0,t.quantity)}}_customerProductsFromResponse(t){return Object.assign(t.items.map(t=>({id:t.id,quantity:t.quantity,displayName:t.product.display_name,customerType:t.product.customer_type,isServerOnly:t.product.server_only,stackable:t.product.stackable,type:t.type,subscription:t.subscription?{subscriptionId:t.subscription.subscription_id,currentPeriodEnd:t.subscription.current_period_end?new Date(t.subscription.current_period_end):null,cancelAtPeriodEnd:t.subscription.cancel_at_period_end,isCancelable:t.subscription.is_cancelable}:null,switchOptions:t.switch_options?.map(t=>({productId:t.product_id,displayName:t.product.display_name,prices:t.product.prices}))})),{nextCursor:t.pagination.next_cursor??null})}_customerInvoicesFromResponse(t){return Object.assign(t.items.map(t=>({status:t.status,amountTotal:t.amount_total,hostedInvoiceUrl:t.hosted_invoice_url,createdAt:new Date(t.created_at_millis)})),{nextCursor:t.pagination.next_cursor??null})}_customerBillingFromResponse(t){return{hasCustomer:t.has_customer,defaultPaymentMethod:t.default_payment_method}}_createAuth(t){let r=this;return{_internalSession:t,currentSession:{async getTokens(){let r=await t.getOrFetchLikelyValidTokens(2e4,75e3);return{accessToken:r?.accessToken.token??null,refreshToken:r?.refreshToken?.token??null}},useTokens(){let r=(0,S.useCallback)(r=>{let{unsubscribe:i}=t.onInvalidate(r),{unsubscribe:s}=t.onAccessTokenChange(r);return()=>{i(),s()}},[t]),i=(0,S.useCallback)(()=>t.isKnownToBeInvalid()?null:t.getAccessTokenIfNotExpiredYet(2e4,75e3)?.token??null,[t]),s=S.default.useSyncExternalStore(r,i,i);return null!==s||t.isKnownToBeInvalid()||(s=(0,A.use)(t.getOrFetchLikelyValidTokens(2e4,75e3))?.accessToken.token??null),{accessToken:s,refreshToken:t.getRefreshToken()?.token??null}}},async getAccessToken(){return(await this.currentSession.getTokens()).accessToken},useAccessToken(){return this.currentSession.useTokens().accessToken},async getRefreshToken(){return(await this.currentSession.getTokens()).refreshToken},useRefreshToken(){return this.currentSession.useTokens().refreshToken},async getAuthorizationHeader(){return tS(await this.getAuthJson())},useAuthorizationHeader(){return tS(this.useAuthJson())},async getAuthHeaders(){return{"x-stack-auth":JSON.stringify(await this.getAuthJson())}},useAuthHeaders(){return{"x-stack-auth":JSON.stringify(this.useAuthJson())}},async getAuthJson(){return await this.currentSession.getTokens()},useAuthJson(){return this.currentSession.useTokens()},signOut:i=>r._signOut(t,i)}}_editableTeamProfileFromCrud(t,r){let i=this;return{displayName:t.display_name,profileImageUrl:t.profile_image_url,async update(s){await i._interface.updateTeamMemberProfile({teamId:t.team_id,userId:t.user_id,profile:{display_name:s.displayName,profile_image_url:s.profileImageUrl}},r),await i._currentUserTeamProfileCache.refresh([r,t.team_id])}}}_createBaseUser(t){return{id:t.id,displayName:t.display_name,primaryEmail:t.primary_email,primaryEmailVerified:t.primary_email_verified,profileImageUrl:t.profile_image_url,signedUpAt:new Date(t.signed_up_at_millis),clientMetadata:t.client_metadata,clientReadOnlyMetadata:t.client_read_only_metadata,hasPassword:t.has_password,emailAuthEnabled:t.auth_with_email,otpAuthEnabled:t.otp_auth_enabled,oauthProviders:t.oauth_providers,passkeyAuthEnabled:t.passkey_auth_enabled,isMultiFactorRequired:t.requires_totp_mfa,isAnonymous:t.is_anonymous,isRestricted:t.is_restricted,restrictedReason:t.restricted_reason,toClientJson:()=>t}}_createUserExtraFromCurrent(t,r){let i=this;return{getActiveSessions:async()=>(await i._interface.listSessions(r)).items.map(t=>i._clientSessionFromCrud(t)),async revokeSession(t){await i._interface.deleteSession(t,r)},setDisplayName(t){return this.update({displayName:t})},setClientMetadata(t){return this.update({clientMetadata:t})},async setSelectedTeam(t){await this.update({selectedTeamId:"string"==typeof t?t:t?.id??null})},getConnectedAccount:async function t(t,s){let n=s?.scopes?.join(" ")??"";if("object"==typeof t&&"provider"in t&&"providerAccountId"in t){let{provider:s,providerAccountId:n}=t,a=w.Result.orThrow(await i._currentUserConnectedAccountsCache.getOrWait([r],"write-only")).find(t=>t.provider===s&&t.providerAccountId===n);return a||null}return w.Result.orThrow(await i._currentUserOAuthConnectionCache.getOrWait([r,t,n,s?.or==="redirect"],"write-only"))},useConnectedAccount:function(t,s){let n=s?.scopes?.join(" ")??"";if("object"==typeof t&&"provider"in t&&"providerAccountId"in t){let{provider:s,providerAccountId:n}=t;return(0,C.useAsyncCache)(i._currentUserConnectedAccountsCache,[r],"user.useConnectedAccount()").find(t=>t.provider===s&&t.providerAccountId===n)??null}return(0,C.useAsyncCache)(i._currentUserOAuthConnectionCache,[r,t,n,s?.or==="redirect"],"user.useConnectedAccount()")},listConnectedAccounts:async()=>w.Result.orThrow(await i._currentUserConnectedAccountsCache.getOrWait([r],"write-only")),useConnectedAccounts:()=>(0,C.useAsyncCache)(i._currentUserConnectedAccountsCache,[r],"user.useConnectedAccounts()"),async linkConnectedAccount(t,s){let n=s?.scopes?.join(" ")??"",a=await eJ(i._interface,{provider:t,redirectUrl:i._getOAuthCallbackRedirectUri(),errorRedirectUrl:i._getUrls().error,providerScope:(0,G.mergeScopeStrings)(n,(i._oauthScopesOnSignIn[t]??[]).join(" "))},r);return await i._redirectTo({url:a}),await (0,E.neverResolve)()},async getOrLinkConnectedAccount(t,s){for(let n of w.Result.orThrow(await i._currentUserConnectedAccountsCache.getOrWait([r],"write-only")).filter(r=>r.provider===t))if("ok"===(await n.getAccessToken({scopes:s?.scopes})).status)return n;return await this.linkConnectedAccount(t,s),await (0,E.neverResolve)()},useOrLinkConnectedAccount(t,s){let n=s?.scopes?.join(" ")??"";return(0,C.useAsyncCache)(i._currentUserValidConnectedAccountForProviderCache,[r,t,n],"user.useOrLinkConnectedAccount()")},async getTeam(t){return(await this.listTeams()).find(r=>r.id===t)??null},useTeam(t){let r=this.useTeams();return(0,S.useMemo)(()=>r.find(r=>r.id===t)??null,[r,t])},listTeams:async()=>w.Result.orThrow(await i._currentUserTeamsCache.getOrWait([r],"write-only")).map(t=>i._clientTeamFromCrud(t,r)),useTeams(){let t=(0,C.useAsyncCache)(i._currentUserTeamsCache,[r],"user.useTeams()");return(0,S.useMemo)(()=>t.map(t=>i._clientTeamFromCrud(t,r)),[t])},async createTeam(t){let s=await i._interface.createClientTeam({display_name:t.displayName,profile_image_url:t.profileImageUrl,creator_user_id:"me"},r);return await i._currentUserTeamsCache.refresh([r]),await this.update({selectedTeamId:s.id}),i._clientTeamFromCrud(s,r)},async leaveTeam(t){await i._interface.leaveTeam(t.id,r)},listTeamInvitations:async()=>w.Result.orThrow(await i._currentUserTeamInvitationsCache.getOrWait([r],"write-only")).map(t=>i._clientReceivedTeamInvitationFromCrud(r,t)),useTeamInvitations(){let t=(0,C.useAsyncCache)(i._currentUserTeamInvitationsCache,[r],"user.useTeamInvitations()");return(0,S.useMemo)(()=>t.map(t=>i._clientReceivedTeamInvitationFromCrud(r,t)),[t])},async listPermissions(t,s){if(t&&"id"in t){let n=s?.recursive??!0;return w.Result.orThrow(await i._currentUserPermissionsCache.getOrWait([r,t.id,n],"write-only")).map(t=>i._clientPermissionFromCrud(t))}{let s=t?.recursive??!0;return w.Result.orThrow(await i._currentUserProjectPermissionsCache.getOrWait([r,s],"write-only")).map(t=>i._clientPermissionFromCrud(t))}},usePermissions(t,s){if(t&&"id"in t){let n=s?.recursive??!0,a=(0,C.useAsyncCache)(i._currentUserPermissionsCache,[r,t.id,n],"user.usePermissions()");return(0,S.useMemo)(()=>a.map(t=>i._clientPermissionFromCrud(t)),[a])}{let s=t?.recursive??!0,n=(0,C.useAsyncCache)(i._currentUserProjectPermissionsCache,[r,s],"user.usePermissions()");return(0,S.useMemo)(()=>n.map(t=>i._clientPermissionFromCrud(t)),[n])}},usePermission(t,r){if(t&&"string"!=typeof t){let i=this.usePermissions(t);return(0,S.useMemo)(()=>i.find(t=>t.id===r)??null,[i,r])}{let r=this.usePermissions();return(0,S.useMemo)(()=>r.find(r=>r.id===t)??null,[r,t])}},async getPermission(t,r){return t&&"string"!=typeof t?(await this.listPermissions(t)).find(t=>t.id===r)??null:(await this.listPermissions()).find(r=>r.id===t)??null},async hasPermission(t,r){return t&&"string"!=typeof t?await this.getPermission(t,r)!==null:await this.getPermission(t)!==null},update:async t=>await i._updateClientUser(t,r),async sendVerificationEmail(s){if(!t.primary_email)throw new x.HexclaveAssertionError("User does not have a primary email");return await i._interface.sendVerificationEmail(t.primary_email,s?.callbackUrl??q(i._getUrls().emailVerification,"callbackUrl"),r)},async updatePassword(t){let s=await i._interface.updatePassword(t,r);return await i._currentUserCache.refresh([r]),s},async setPassword(t){let s=await i._interface.setPassword(t,r);return await i._currentUserCache.refresh([r]),s},selectedTeam:t.selected_team&&this._clientTeamFromCrud(t.selected_team,r),async getTeamProfile(t){let s=w.Result.orThrow(await i._currentUserTeamProfileCache.getOrWait([r,t.id],"write-only"));return i._editableTeamProfileFromCrud(s,r)},useTeamProfile(t){let s=(0,C.useAsyncCache)(i._currentUserTeamProfileCache,[r,t.id],"user.useTeamProfile()");return i._editableTeamProfileFromCrud(s,r)},async delete(){await i._interface.deleteCurrentUser(r),r.markInvalid()},listContactChannels:async()=>w.Result.orThrow(await i._clientContactChannelsCache.getOrWait([r],"write-only")).map(t=>i._clientContactChannelFromCrud(t,r)),useContactChannels:()=>(0,C.useAsyncCache)(i._clientContactChannelsCache,[r],"user.useContactChannels()").map(t=>i._clientContactChannelFromCrud(t,r)),async createContactChannel(t){let s=await i._interface.createClientContactChannel({value:t.value,type:t.type,used_for_auth:t.usedForAuth,is_primary:t.isPrimary,user_id:"me"},r);return await i._clientContactChannelsCache.refresh([r]),i._clientContactChannelFromCrud(s,r)},useNotificationCategories:()=>(0,C.useAsyncCache)(i._notificationCategoriesCache,[r],"user.useNotificationCategories()").map(t=>i._clientNotificationCategoryFromCrud(t,r)),listNotificationCategories:async()=>w.Result.orThrow(await i._notificationCategoriesCache.getOrWait([r],"write-only")).map(t=>i._clientNotificationCategoryFromCrud(t,r)),useApiKeys:()=>(0,C.useAsyncCache)(i._userApiKeysCache,[r],"user.useApiKeys()").map(t=>i._clientApiKeyFromCrud(r,t)),listApiKeys:async()=>(await i._interface.listProjectApiKeys({user_id:"me"},r,"client")).map(t=>i._clientApiKeyFromCrud(r,t)),async createApiKey(t){let s=await i._interface.createProjectApiKey(await W("user","me",t),r,"client");return await i._userApiKeysCache.refresh([r]),i._clientApiKeyFromCrud(r,s)},useOAuthProviders:()=>(0,C.useAsyncCache)(i._currentUserOAuthProvidersCache,[r],"user.useOAuthProviders()").map(t=>i._clientOAuthProviderFromCrud(t,r)),listOAuthProviders:async()=>w.Result.orThrow(await i._currentUserOAuthProvidersCache.getOrWait([r],"write-only")).map(t=>i._clientOAuthProviderFromCrud(t,r)),useOAuthProvider(t){let r=this.useOAuthProviders();return(0,S.useMemo)(()=>r.find(r=>r.id===t)??null,[r,t])},async getOAuthProvider(t){return(await this.listOAuthProviders()).find(r=>r.id===t)??null},async registerPasskey(t){let s,n=(await i._getCurrentUrl())?.hostname;if(!n)throw new x.HexclaveAssertionError("hostname must be provided if the Stack App does not have a redirect method");let a=await i._interface.initiatePasskeyRegistration({},r);if("ok"!==a.status)return w.Result.error(new P.KnownErrors.PasskeyRegistrationFailed("Failed to get initiation options for passkey registration"));let{options_json:o,code:l}=a.data;if("THIS_VALUE_WILL_BE_REPLACED.example.com"!==o.rp.id)throw new x.HexclaveAssertionError(`Expected returned RP ID from server to equal sentinel, but found ${o.rp.id}`);o.rp.id=n;try{s=await U({optionsJSON:o})}catch(t){if(t instanceof R)return w.Result.error(new P.KnownErrors.PasskeyWebAuthnError(t.message,t.name));return(0,x.captureError)("passkey-registration-failed",t),w.Result.error(new P.KnownErrors.PasskeyRegistrationFailed("Failed to start passkey registration due to unknown error"))}let p=await i._interface.registerPasskey({credential:s,code:l},r);return await i._refreshUser(r),p}}}_createInternalUserExtra(t){let r=this;return this._ensureInternalProject(),{createProject:i=>r._createProject(t,i),async transferProject(i,s){await r._interface.transferProject(t,i,s),await r._refreshProject()},listOwnedProjects:()=>r._listOwnedProjects(t),useOwnedProjects:()=>r._useOwnedProjects(t)}}_createCustomer(t,r,i){let s=this,n=i??s._interface.createSession({refreshToken:null}),a="user"===r?{userId:t}:{teamId:t};return{async getBilling(){let i=w.Result.orThrow(await s._customerBillingCache.getOrWait([n,r,t],"write-only"));return s._customerBillingFromResponse(i)},useBilling(){let i=(0,C.useAsyncCache)(s._customerBillingCache,[n,r,t],"customer.useBilling()");return s._customerBillingFromResponse(i)},async createPaymentMethodSetupIntent(){let i=await s._interface.createCustomerPaymentMethodSetupIntent(r,t,n);return{clientSecret:i.client_secret,stripeAccountId:i.stripe_account_id}},async setDefaultPaymentMethodFromSetupIntent(i){let a=await s._interface.setDefaultCustomerPaymentMethodFromSetupIntent(r,t,i,n);return await s._customerBillingCache.refresh([n,r,t]),a.default_payment_method},getItem:async t=>await s.getItem({itemId:t,...a}),useItem:t=>s.useItem({itemId:t,...a}),listProducts:async t=>await s.listProducts({...t,...a}),useProducts:t=>s.useProducts({...t,...a}),listInvoices:async t=>await s.listInvoices({...t,...a}),useInvoices:t=>s.useInvoices({...t,...a}),createCheckoutUrl:async i=>await s._interface.createCheckoutUrl(r,t,i.productId,n,i.returnUrl,"client"),async switchSubscription(i){await s._interface.switchSubscription({customer_type:r,customer_id:t,from_product_id:i.fromProductId,to_product_id:i.toProductId,price_id:i.priceId,quantity:i.quantity},n),await s._customerBillingCache.refresh([n,r,t]),"user"===r?await s._userProductsCache.invalidateWhere(([r,i])=>r===n&&i===t):await s._teamProductsCache.invalidateWhere(([r,i])=>r===n&&i===t)}}}async getItem(t){let r,i=await this._getSession();return r="userId"in t?w.Result.orThrow(await this._userItemCache.getOrWait([i,t.userId,t.itemId],"write-only")):"teamId"in t?w.Result.orThrow(await this._teamItemCache.getOrWait([i,t.teamId,t.itemId],"write-only")):w.Result.orThrow(await this._customItemCache.getOrWait([i,t.customCustomerId,t.itemId],"write-only")),this._clientItemFromCrud(r)}useItem(t){let r=this._useSession(),[i,s]="userId"in t?[this._userItemCache,t.userId]:"teamId"in t?[this._teamItemCache,t.teamId]:[this._customItemCache,t.customCustomerId],n=(0,C.useAsyncCache)(i,[r,s,t.itemId],"app.useItem()");return this._clientItemFromCrud(n)}async listProducts(t){let r=(await this.getUser())?._internalSession??await this._getSession();if("userId"in t){let i=w.Result.orThrow(await this._userProductsCache.getOrWait([r,t.userId,t.cursor??null,t.limit??null],"write-only"));return this._customerProductsFromResponse(i)}if("teamId"in t){let i=w.Result.orThrow(await this._teamProductsCache.getOrWait([r,t.teamId,t.cursor??null,t.limit??null],"write-only"));return this._customerProductsFromResponse(i)}let i=w.Result.orThrow(await this._customProductsCache.getOrWait([r,t.customCustomerId,t.cursor??null,t.limit??null],"write-only"));return this._customerProductsFromResponse(i)}async listInvoices(t){let r=await this._getSession();if("userId"in t){let i=w.Result.orThrow(await this._userInvoicesCache.getOrWait([r,t.userId,t.cursor??null,t.limit??null],"write-only"));return this._customerInvoicesFromResponse(i)}let i=w.Result.orThrow(await this._teamInvoicesCache.getOrWait([r,t.teamId,t.cursor??null,t.limit??null],"write-only"));return this._customerInvoicesFromResponse(i)}async cancelSubscription(t){let r=await this._getSession(),i=await this.getUser();if(!i)throw new P.KnownErrors.UserAuthenticationRequired;let s="teamId"in t?"team":"user",n="teamId"in t?t.teamId:i.id;await this._interface.cancelSubscription({customer_type:s,customer_id:n,product_id:t.productId,subscription_id:t.subscriptionId},r),"user"===s?await this._userProductsCache.invalidateWhere(([t,i])=>t===r&&i===n):await this._teamProductsCache.invalidateWhere(([t,i])=>t===r&&i===n)}useProducts(t){let r=this._useSession(),i=(0,C.useAsyncCache)("userId"in t?this._userProductsCache:"teamId"in t?this._teamProductsCache:this._customProductsCache,[r,"userId"in t?t.userId:"teamId"in t?t.teamId:t.customCustomerId,t.cursor??null,t.limit??null],"clientApp.useProducts()");return this._customerProductsFromResponse(i)}useInvoices(t){let r=this._useSession(),i=(0,C.useAsyncCache)("userId"in t?this._userInvoicesCache:this._teamInvoicesCache,[r,"userId"in t?t.userId:t.teamId,t.cursor??null,t.limit??null],"clientApp.useInvoices()");return this._customerInvoicesFromResponse(i)}_currentUserFromCrud(t,r){return X({...this._createBaseUser(t),...this._createAuth(r),...this._createUserExtraFromCurrent(t,r),...this._isInternalProject()?this._createInternalUserExtra(r):{},...this._createCustomer(t.id,"user",r)})}_clientSessionFromCrud(t){return{id:t.id,userId:t.user_id,createdAt:new Date(t.created_at),isImpersonation:t.is_impersonation,lastUsedAt:t.last_used_at?new Date(t.last_used_at):void 0,isCurrentSession:t.is_current_session??!1,geoInfo:t.last_used_at_end_user_ip_info}}_getOwnedAdminApp(t,i){return this._ownedAdminApps.has([i,t])||this._ownedAdminApps.set([i,t],new r.LazyStackAdminAppImpl.value({baseUrl:this._interface.options.getBaseUrl(),projectId:t,tokenStore:null,projectOwnerSession:i,noAutomaticPrefetch:!0})),this._ownedAdminApps.get([i,t])}get projectId(){return this._interface.projectId}get version(){return C.clientVersion}_getBotChallengeSiteKeys(){if(!(0,er.isBrowserLike)())return null;let t=eY.envVars.HEXCLAVE_BOT_CHALLENGE_SITE_KEY;return t?{visibleSiteKey:t,invisibleSiteKey:eY.envVars.HEXCLAVE_BOT_CHALLENGE_INVISIBLE_SITE_KEY??t}:(this._botChallengeSiteKeysWarned||(this._botChallengeSiteKeysWarned=!0,console.warn("[stack-auth] HEXCLAVE_BOT_CHALLENGE_SITE_KEY is not set — bot challenge fraud protection is disabled. Set the env variable to enable it.")),null)}_getBotChallengeFlowFailure(t){return t instanceof eu?{type:"cancelled",knownError:new P.KnownErrors.BotChallengeFailed("Bot challenge cancelled by user")}:t instanceof ec?{type:"failed",knownError:new P.KnownErrors.BotChallengeFailed(t.message)}:null}_normalizeBotChallengeResult(t){return"ok"===t.status?t:P.KnownErrors.BotChallengeRequired.isInstance(t.error)?((0,x.captureError)("bot-challenge-unexpected-after-flow",t.error),w.Result.error(new P.KnownErrors.BotChallengeFailed("Unexpected bot challenge after flow completion"))):w.Result.error(t.error)}_toInterfaceBotChallengeInput(t){return t.unavailable?{phase:"visible"}:{token:t.token,phase:t.phase}}async _executeResultWithBotChallengeFlow(t){let r,i=this._getBotChallengeSiteKeys();try{r=i?await ed({...i,action:t.action,execute:t.execute,isChallengeRequired:t=>"error"===t.status&&P.KnownErrors.BotChallengeRequired.isInstance(t.error)}):await t.execute({})}catch(r){let t=this._getBotChallengeFlowFailure(r);if(t)return w.Result.error(t.knownError);throw r}return this._normalizeBotChallengeResult(r)}async _isTrusted(t){if((0,Q.isRelative)(t))return!0;let r=(0,Q.createUrlIfValid)(t);if(null==r)return!1;if((0,eX.isHostedHandlerUrlForProject)({url:t,projectId:this.projectId}))return!0;let i=await this._getTrustedRedirectConfig();return(0,ei.validateRedirectUrl)(r,{allowLocalhost:i.allowLocalhost,trustedDomains:i.trustedDomains})}get urls(){var t;let r;return r=new Set(Object.entries((t={urls:this._getUrls(),projectId:this.projectId}).urls).filter(([,r])=>(0,eX.isHostedHandlerUrlForProject)({url:r,projectId:t.projectId})).map(([t])=>t)),new Proxy(t.urls,{get(t,i,s){if("string"==typeof i&&r.has(i))throw Error(`app.urls.${i} cannot be used when this app is configured to use hosted components. \`app.urls\` is static and does not include the runtime redirect-back, cross-domain auth, or sign-out state required by hosted components. `+("handler"===i?"Use a page-specific redirect helper such as app.redirectToSignIn() instead.":`Use app.redirectTo${i.slice(0,1).toUpperCase()}${i.slice(1)}() instead.`));return Reflect.get(t,i,s)}})}_getUrls(){return(0,C.getUrls)(this._urlOptions,{projectId:this.projectId})}_prefetchCrossDomainHandoffParamsIfNeeded(){let t="cookie"===this._tokenStoreInit||"nextjs-cookie"===this._tokenStoreInit;(0,er.isBrowserLike)()&&t&&!this._isPrefetchingCrossDomainHandoffParams&&null==this._getFreshPrefetchedCrossDomainHandoffParams()&&(this._isPrefetchingCrossDomainHandoffParams=!0,(0,E.runAsynchronously)(async()=>{try{if(!(0,er.isBrowserLike)())return;let{state:t,codeChallenge:r}=await eH();this._prefetchedCrossDomainHandoffParams={state:t,codeChallenge:r},this._prefetchedCrossDomainHandoffParamsFetchedAt=performance.now()}finally{this._isPrefetchingCrossDomainHandoffParams=!1}}))}_getCrossDomainHandoffParamsForUrlsGetter(t){let r=tr(t);if(null!=r)return r;let i=this._getFreshPrefetchedCrossDomainHandoffParams();return null!=i?i:(this._prefetchCrossDomainHandoffParamsIfNeeded(),null)}async _getCrossDomainHandoffParamsForRedirect(t){let r=tr(t);if(null!=r)return r;let i=this._getFreshPrefetchedCrossDomainHandoffParams();if(null!=i)return i;let{state:s,codeChallenge:n}=await eH();return this._prefetchedCrossDomainHandoffParams={state:s,codeChallenge:n},this._prefetchedCrossDomainHandoffParamsFetchedAt=performance.now(),{state:s,codeChallenge:n}}_getLocalOAuthCallbackHandlerUrl(){return this._isOAuthCallbackUrlHosted()?this._getOAuthCallbackRedirectUri():(0,eX.resolveHandlerUrls)({urls:{...this._urlOptions,default:{type:"handler-component"},oauthCallback:{type:"handler-component"}},projectId:this.projectId}).oauthCallback}async _createCrossDomainAuthRedirectUrl(t){let r=await this._getSession(t.overrideTokenStoreInit,{awaitPendingAuthResolutions:t.awaitPendingAuthResolutions});await r.fetchNewTokens();let i=await this._interface.sendClientRequest("/auth/oauth/cross-domain/authorize",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({redirect_uri:t.redirectUri,state:t.state,code_challenge:t.codeChallenge,code_challenge_method:"S256",after_callback_redirect_url:t.afterCallbackRedirectUrl})},r);if(!i.ok){let t=await i.text();throw new x.HexclaveAssertionError(`Cross-domain authorization endpoint failed: ${i.status} ${t}`)}let s=await i.json();if(!("redirect_url"in s)||"string"!=typeof s.redirect_url)throw new x.HexclaveAssertionError("Cross-domain authorization endpoint returned an invalid payload",{result:s});return s.redirect_url}_getFreshPrefetchedCrossDomainHandoffParams(){return null==this._prefetchedCrossDomainHandoffParams?null:performance.now()-this._prefetchedCrossDomainHandoffParamsFetchedAt>33e5?(this._prefetchedCrossDomainHandoffParams=null,this._prefetchedCrossDomainHandoffParamsFetchedAt=0,null):this._prefetchedCrossDomainHandoffParams}async _getCurrentUrl(){return"none"===this._redirectMethod?null:new URL(window.location.href)}async _redirectTo(t){"none"!==this._redirectMethod&&(tg&&"nextjs"===this._redirectMethod?tv.redirect(t.url.toString(),t.replace?tv.RedirectType.replace:tv.RedirectType.push):"object"==typeof this._redirectMethod&&this._redirectMethod.navigate?this._redirectMethod.navigate(t.url.toString()):t.replace?window.location.replace(t.url):window.location.assign(t.url),await (0,E.wait)(2e3))}useNavigate(){if("object"==typeof this._redirectMethod)return this._redirectMethod.useNavigate();if("window"===this._redirectMethod)return t=>window.location.assign(t);if("nextjs"!==this._redirectMethod)return t=>{};{let t=tv.useRouter();return r=>t.push(r)}}async _redirectIfTrusted(t,r){if(!await this._isTrusted(t))throw Error(`Redirect URL ${t} is not trusted; should be relative.`);return await this._redirectTo({url:t,...r})}async _redirectToHandler(t,r,i){let s=(0,C.getUrls)(this._urlOptions,{projectId:this.projectId})[t];if(!s)throw Error(`No URL for handler name ${t}`);let n=await ta({handlerName:t,rawHandlerUrl:s,noRedirectBack:r?.noRedirectBack===!0,currentUrl:null,localOAuthCallbackUrl:this._getLocalOAuthCallbackHandlerUrl(),getCrossDomainHandoffParams:async t=>await this._getCrossDomainHandoffParamsForRedirect(t)});if("cross-domain-authorize"===n.type){let t=await this._createCrossDomainAuthRedirectUrl({redirectUri:n.redirectUri,state:n.state,codeChallenge:n.codeChallenge,afterCallbackRedirectUrl:n.afterCallbackRedirectUrl,awaitPendingAuthResolutions:i?.awaitPendingAuthResolutions,overrideTokenStoreInit:i?.overrideTokenStoreInit});await this._redirectTo({url:t,...r});return}let a=n.url;await this._redirectIfTrusted(a,r)}_redirectToHandlerDuringRender(t,r){return!1}async redirectToSignIn(t){return await this._redirectToHandler("signIn",t)}async redirectToSignUp(t){return await this._redirectToHandler("signUp",t)}async redirectToSignOut(t){let r=this._urlOptions.signOut??this._urlOptions.default;return"string"!=typeof r&&r?.type==="hosted"?await this.signOut():await this._redirectToHandler("signOut",t)}async redirectToEmailVerification(t){return await this._redirectToHandler("emailVerification",t)}async redirectToPasswordReset(t){return await this._redirectToHandler("passwordReset",t)}async redirectToForgotPassword(t){return await this._redirectToHandler("forgotPassword",t)}async redirectToHome(t){return await this._redirectToHandler("home",t)}async redirectToOAuthCallback(t){return await this._redirectToHandler("oauthCallback",t)}async redirectToMagicLinkCallback(t){return await this._redirectToHandler("magicLinkCallback",t)}async redirectToAfterSignIn(t){return await this._redirectToHandler("afterSignIn",t)}async redirectToAfterSignUp(t){return await this._redirectToHandler("afterSignUp",t)}async redirectToOnboarding(t){return await this._redirectToHandler("onboarding",t)}async redirectToAfterSignOut(t){return await this._redirectToHandler("afterSignOut",t)}async redirectToAccountSettings(t){return await this._redirectToHandler("accountSettings",t)}async redirectToError(t){return await this._redirectToHandler("error",t)}async redirectToTeamInvitation(t){return await this._redirectToHandler("teamInvitation",t)}async redirectToCliAuthConfirm(t){return await this._redirectToHandler("cliAuthConfirm",t)}async redirectToMfa(t){return await this._redirectToHandler("mfa",t)}async sendForgotPasswordEmail(t,r){return await this._interface.sendForgotPasswordEmail(t,r?.callbackUrl??q(this.urls.passwordReset,"callbackUrl"))}async sendMagicLinkEmail(t,r){let i=r?.callbackUrl??q(this.urls.magicLinkCallback,"callbackUrl");return await this._executeResultWithBotChallengeFlow({action:"send_magic_link_email",execute:async r=>await this._interface.sendMagicLinkEmail(t,i,this._toInterfaceBotChallengeInput(r))})}async resetPassword(t){return await this._interface.resetPassword(t)}async verifyPasswordResetCode(t){return await this._interface.verifyPasswordResetCode(t)}async verifyTeamInvitationCode(t){return await this._interface.acceptTeamInvitation({type:"check",code:t,session:await this._getSession()})}async acceptTeamInvitation(t){let r=await this._interface.acceptTeamInvitation({type:"use",code:t,session:await this._getSession()});return"ok"===r.status?w.Result.ok(void 0):w.Result.error(r.error)}async getTeamInvitationDetails(t){let r=await this._interface.acceptTeamInvitation({type:"details",code:t,session:await this._getSession()});return"ok"===r.status?w.Result.ok({teamDisplayName:r.data.team_display_name}):w.Result.error(r.error)}async verifyEmail(t){let r=await this._interface.verifyEmail(t);return await this._currentUserCache.refresh([await this._getSession()]),await this._clientContactChannelsCache.refresh([await this._getSession()]),r}async getUser(t){if(t?.or==="anonymous"&&!1===t.includeRestricted)throw Error("Cannot use { or: 'anonymous' } with { includeRestricted: false }. Anonymous users implicitly include restricted users.");this._ensurePersistentTokenStore(t?.tokenStore);let r=await this._getSession(t?.tokenStore),i=w.Result.orThrow(await this._currentUserCache.getOrWait([r],"write-only")),s=t?.or==="anonymous"||t?.or==="anonymous-if-exists[deprecated]",n=t?.includeRestricted===!0||s;if(null===i||i.is_anonymous&&!s||i.is_restricted&&!n)switch(t?.or){case"redirect":!i?.is_anonymous&&i?.is_restricted?await this.redirectToOnboarding({replace:!0}):await this.redirectToSignIn({replace:!0});break;case"throw":throw Error("User is not signed in but getUser was called with { or: 'throw' }");case"anonymous":{let t=await this._signUpAnonymously();return await this.getUser({tokenStore:t,or:"anonymous-if-exists[deprecated]",includeRestricted:!0})??(0,x.throwErr)("Something went wrong while signing up anonymously")}case void 0:case"anonymous-if-exists[deprecated]":case"return-null":return null}return i&&this._currentUserFromCrud(i,r)}useUser(t){if(t?.or==="anonymous"&&!1===t.includeRestricted)throw Error("Cannot use { or: 'anonymous' } with { includeRestricted: false }. Anonymous users implicitly include restricted users.");this._ensurePersistentTokenStore(t?.tokenStore);let r=this._useSession(t?.tokenStore),i=(0,C.useAsyncCache)(this._currentUserCache,[r],"clientApp.useUser()"),s=t?.or==="anonymous"||t?.or==="anonymous-if-exists[deprecated]",n=t?.includeRestricted===!0||s;if(null===i||i.is_anonymous&&!s||i.is_restricted&&!n)switch(t?.or){case"redirect":throw!i?.is_anonymous&&i?.is_restricted?this._redirectToHandlerDuringRender("onboarding",{replace:!0})||(0,E.runAsynchronously)(this.redirectToOnboarding({replace:!0})):this._redirectToHandlerDuringRender("signIn",{replace:!0})||(0,E.runAsynchronously)(this.redirectToSignIn({replace:!0})),(0,A.suspend)(),new x.HexclaveAssertionError("suspend should never return");case"throw":throw Error("User is not signed in but useUser was called with { or: 'throw' }");case"anonymous":throw(0,E.runAsynchronously)(async()=>{await this._signUpAnonymously()}),(0,A.suspend)(),new x.HexclaveAssertionError("suspend should never return");case void 0:case"anonymous-if-exists[deprecated]":case"return-null":i=null}return(0,S.useMemo)(()=>i&&this._currentUserFromCrud(i,r),[i,r,t?.or])}_getTokenPartialUserFromSession(t,r){let i=t.getAccessTokenIfNotExpiredYet(0,null);if(!i)return null;let s=i.payload.is_anonymous;return s&&"anonymous-if-exists"!==r.or?null:{id:i.payload.sub,primaryEmail:i.payload.email,displayName:i.payload.name,primaryEmailVerified:i.payload.email_verified,isAnonymous:s,isMultiFactorRequired:i.payload.requires_totp_mfa,isRestricted:i.payload.is_restricted,restrictedReason:i.payload.restricted_reason}}async _getPartialUserFromConvex(t){let r=await t.auth.getUserIdentity();return r?{id:r.subject,displayName:r.name??null,primaryEmail:r.email??null,primaryEmailVerified:r.email_verified,isAnonymous:r.is_anonymous,isMultiFactorRequired:r.requires_totp_mfa,isRestricted:r.is_restricted,restrictedReason:r.restricted_reason??null}:null}async getPartialUser(t){switch(t.from){case"token":{this._ensurePersistentTokenStore(t.tokenStore??this._tokenStoreInit);let r=await this._getSession(t.tokenStore);return this._getTokenPartialUserFromSession(r,t)}case"convex":return await this._getPartialUserFromConvex(t.ctx);default:throw Error(`Invalid 'from' option: ${t.from}`)}}usePartialUser(t){switch(t.from){case"token":{this._ensurePersistentTokenStore(t.tokenStore??this._tokenStoreInit);let r=this._useSession(t.tokenStore);return this._getTokenPartialUserFromSession(r,t)}case"convex":return(0,C.useAsyncCache)(this._convexPartialUserCache,[t.ctx],"clientApp.usePartialUser()");default:throw Error(`Invalid 'from' option: ${t.from}`)}}getConvexClientAuth(t){return async r=>{let i=await this._getSession(t.tokenStore??this._tokenStoreInit);return r.forceRefreshToken?(await i.fetchNewTokens())?.accessToken.token??null:(await i.getOrFetchLikelyValidTokens(2e4,75e3))?.accessToken.token??null}}async getConvexHttpClientAuth(t){return(await (await this._getSession(t.tokenStore)).getOrFetchLikelyValidTokens(2e4,75e3))?.accessToken.token??""}async _updateClientUser(t,r){let i=await this._interface.updateClientUser({display_name:t.displayName,client_metadata:t.clientMetadata,selected_team_id:t.selectedTeamId,totp_secret_base64:null!=t.totpMultiFactorSecret?(0,Y.encodeBase64)(t.totpMultiFactorSecret):t.totpMultiFactorSecret,profile_image_url:t.profileImageUrl,otp_auth_enabled:t.otpAuthEnabled,passkey_auth_enabled:t.passkeyAuthEnabled,primary_email:t.primaryEmail},r);return await this._refreshUser(r),i}async signInWithOAuth(t,r){throw Error("signInWithOAuth can currently only be called in a browser environment")}async _experimentalMfa(t,r){throw await this.redirectToMfa(),new x.HexclaveAssertionError("we should have redirected in redirectToMfa()")}async _catchMfaRequiredError(t){try{return await t()}catch(t){if(P.KnownErrors.MultiFactorAuthenticationRequired.isInstance(t))return w.Result.ok(await this._experimentalMfa(t,await this._getSession(void 0,{awaitPendingAuthResolutions:!1})));throw t}}async signInWithCredential(t){let r;this._ensurePersistentTokenStore();let i=await this._getSession();try{r=await this._catchMfaRequiredError(async()=>await this._interface.signInWithCredential(t.email,t.password,i))}catch(t){if(P.KnownErrors.InvalidTotpCode.isInstance(t))return w.Result.error(t);throw t}return"ok"===r.status?(await this._signInToAccountWithTokens(r.data),t.noRedirect||await this._redirectToHandler("afterSignIn",{replace:!0},{overrideTokenStoreInit:this._getTokenStoreInitForFreshTokens(r.data)}),w.Result.ok(void 0)):w.Result.error(r.error)}async signUpWithCredential(t){let r;if(t.noVerificationCallback&&t.verificationCallbackUrl)throw new x.HexclaveAssertionError("verificationCallbackUrl is not allowed when noVerificationCallback is true");this._ensurePersistentTokenStore();let i=await this._getSession(),s=t.noVerificationCallback?void 0:t.verificationCallbackUrl??q(this.urls.emailVerification,"verificationCallbackUrl"),n=async r=>{let n=await this._interface.signUpWithCredential(t.email,t.password,s,i,this._toInterfaceBotChallengeInput(r));return"error"===n.status&&n.error instanceof P.KnownErrors.RedirectUrlNotWhitelisted&&void 0!==s&&!t.verificationCallbackUrl&&((0,x.captureError)("signup-verification-url-not-whitelisted",new x.HexclaveAssertionError("The auto-constructed verification callback URL is not whitelisted; proceeding without email verification",{emailVerificationRedirectUrl:s})),n=await this._interface.signUpWithCredential(t.email,t.password,void 0,i,this._toInterfaceBotChallengeInput(r))),n};return"ok"===(r=await this._executeResultWithBotChallengeFlow({action:"sign_up_with_credential",execute:n})).status?(await this._signInToAccountWithTokens(r.data),t.noRedirect||await this._redirectToHandler("afterSignUp",{replace:!0},{overrideTokenStoreInit:this._getTokenStoreInitForFreshTokens(r.data)}),w.Result.ok(void 0)):w.Result.error(r.error)}async _signUpAnonymously(){return this._ensurePersistentTokenStore(),this._anonymousSignUpInProgress||(this._anonymousSignUpInProgress=(async()=>{this._ensurePersistentTokenStore();let t=await this._getSession(),r=await this._interface.signUpAnonymously(t);if("ok"===r.status)await this._signInToAccountWithTokens(r.data);else throw new x.HexclaveAssertionError("signUpAnonymously() should never return an error");return this._anonymousSignUpInProgress=null,r.data})()),await this._anonymousSignUpInProgress}async signInWithMagicLink(t,r){let i;this._ensurePersistentTokenStore();let s=await this._getSession();try{i=await this._catchMfaRequiredError(async()=>await this._interface.signInWithMagicLink(t,s))}catch(t){if(P.KnownErrors.InvalidTotpCode.isInstance(t))return w.Result.error(t);throw t}return"ok"===i.status?(await this._signInToAccountWithTokens(i.data),r?.noRedirect||(i.data.newUser?await this._redirectToHandler("afterSignUp",{replace:!0},{awaitPendingAuthResolutions:!1,overrideTokenStoreInit:this._getTokenStoreInitForFreshTokens(i.data)}):await this._redirectToHandler("afterSignIn",{replace:!0},{awaitPendingAuthResolutions:!1,overrideTokenStoreInit:this._getTokenStoreInitForFreshTokens(i.data)})),w.Result.ok(void 0)):w.Result.error(i.error)}async promptCliLogin(t){let r=await this._interface.sendClientRequest("/auth/cli",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({expires_in_millis:t.expiresInMillis,...null!=t.anonRefreshToken?{anon_refresh_token:t.anonRefreshToken}:{}})},null);if(!r.ok)return w.Result.error(new P.KnownErrors.CliAuthError(`Failed to initiate CLI auth: ${r.status} ${await r.text()}`));let i=await r.json(),s=i.polling_code,n=i.login_code,a=(0,eX.buildCliAuthConfirmUrl)({cliAuthConfirmUrl:this.urls.cliAuthConfirm,appUrl:t.appUrl,loginCode:n});t.promptLink?t.promptLink(a,n):(console.log(`Your verification code: ${n}`),console.log(`Please visit the following URL to authenticate:
|
|
353
|
-
${a}`));let o=0;for(;o<(t.maxAttempts??1/0);){o++;let r=await this._interface.sendClientRequest("/auth/cli/poll",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({polling_code:s})},null);if(!r.ok)return w.Result.error(new P.KnownErrors.CliAuthError(`Failed to initiate CLI auth: ${r.status} ${await r.text()}`));let i=await r.json();if(201===r.status&&"success"===i.status)return w.Result.ok(i.refresh_token);if("waiting"===i.status){await (0,E.wait)(t.waitTimeMillis??2e3);continue}if("expired"===i.status)return w.Result.error(new P.KnownErrors.CliAuthExpiredError("CLI authentication request expired. Please try again."));if("used"===i.status)return w.Result.error(new P.KnownErrors.CliAuthUsedError("This authentication token has already been used."));return w.Result.error(new P.KnownErrors.CliAuthError(`Unexpected status from CLI auth polling: ${i.status}`))}return w.Result.error(new P.KnownErrors.CliAuthError("Timed out waiting for CLI authentication."))}async signInWithMfa(t,r,i){let s;this._ensurePersistentTokenStore();let n=await this._getSession();try{s=await this._catchMfaRequiredError(async()=>await this._interface.signInWithMfa(t,r,n))}catch(t){if(t instanceof P.KnownErrors.InvalidTotpCode)return w.Result.error(t);throw t}return"ok"===s.status?(await this._signInToAccountWithTokens(s.data),i?.noRedirect||(s.data.newUser?await this._redirectToHandler("afterSignUp",{replace:!0},{overrideTokenStoreInit:this._getTokenStoreInitForFreshTokens(s.data)}):await this._redirectToHandler("afterSignIn",{replace:!0},{overrideTokenStoreInit:this._getTokenStoreInitForFreshTokens(s.data)})),w.Result.ok(void 0)):w.Result.error(s.error)}async signInWithPasskey(){let t;this._ensurePersistentTokenStore();let r=await this._getSession();try{t=await this._catchMfaRequiredError(async()=>{let t=await this._interface.initiatePasskeyAuthentication({},r);if("ok"!==t.status)return w.Result.error(new P.KnownErrors.PasskeyAuthenticationFailed("Failed to get initiation options for passkey authentication"));let{options_json:i,code:s}=t.data;if("THIS_VALUE_WILL_BE_REPLACED.example.com"!==i.rpId)throw new x.HexclaveAssertionError(`Expected returned RP ID from server to equal sentinel, but found ${i.rpId}`);i.rpId=window.location.hostname;let n=await K({optionsJSON:i});return await this._interface.signInWithPasskey({authentication_response:n,code:s},r)})}catch(t){if(t instanceof R)return w.Result.error(new P.KnownErrors.PasskeyWebAuthnError(t.message,t.name));return w.Result.error(new P.KnownErrors.PasskeyAuthenticationFailed("Failed to sign in with passkey"))}return"ok"===t.status?(await this._signInToAccountWithTokens(t.data),await this._redirectToHandler("afterSignIn",{replace:!0},{overrideTokenStoreInit:this._getTokenStoreInitForFreshTokens(t.data)}),w.Result.ok(void 0)):w.Result.error(t.error)}async callOAuthCallback(t){throw Error("callOAuthCallback can currently only be called in a browser environment")}async _signOut(t,r){this._eventTracker?.clearBuffer(),this._sessionRecorder?.clearBuffer(),await ea.storeLock.withWriteLock(async()=>{await this._interface.signOut(t),r?.redirectUrl?await this._redirectTo({url:r.redirectUrl,replace:!0}):await this._redirectToDefaultAfterSignOut()})}async _redirectToDefaultAfterSignOut(){null!=this._urlOptions.afterSignOut?await this.redirectToAfterSignOut({replace:!0}):null!=this._urlOptions.home?await this.redirectToHome({replace:!0}):(this._urlOptions.default?.type,await this.redirectToAfterSignOut({replace:!0}))}async signOut(t){let r=await this.getUser({tokenStore:t?.tokenStore??void 0});r&&await r.signOut({redirectUrl:t?.redirectUrl})}async getAccessToken(t){let r=await this.getUser({tokenStore:t?.tokenStore??void 0});return r?await r.getAccessToken():null}useAccessToken(t){let r=this.useUser({tokenStore:t?.tokenStore??void 0});return r?r.useAccessToken():null}async getRefreshToken(t){let r=await this.getUser({tokenStore:t?.tokenStore??void 0});return r?await r.getRefreshToken():null}useRefreshToken(t){let r=this.useUser({tokenStore:t?.tokenStore??void 0});return r?r.useRefreshToken():null}async getAuthorizationHeader(t){return tS(await this.getAuthJson(t))}useAuthorizationHeader(t){return tS(this.useAuthJson(t))}async getAuthHeaders(t){return{"x-stack-auth":JSON.stringify(await this.getAuthJson(t))}}useAuthHeaders(t){return{"x-stack-auth":JSON.stringify(this.useAuthJson(t))}}async getAuthJson(t){let r=await this.getUser({tokenStore:t?.tokenStore??void 0});return r?await r.getAuthJson():{accessToken:null,refreshToken:null}}useAuthJson(t){let r=this.useUser({tokenStore:t?.tokenStore??void 0});return r?r.useAuthJson():{accessToken:null,refreshToken:null}}async getProject(){let t=w.Result.orThrow(await this._currentProjectCache.getOrWait([],"write-only"));return this._clientProjectFromCrud(t)}useProject(){let t=(0,C.useAsyncCache)(this._currentProjectCache,[],"clientApp.useProject()");return(0,S.useMemo)(()=>this._clientProjectFromCrud(t),[t])}async _listOwnedProjects(t){return this._ensureInternalProject(),w.Result.orThrow(await this._ownedProjectsCache.getOrWait([t],"write-only")).map(r=>this._getOwnedAdminApp(r.id,t)._adminOwnedProjectFromCrud(r,()=>this._refreshOwnedProjects(t)))}_useOwnedProjects(t){this._ensureInternalProject();let r=(0,C.useAsyncCache)(this._ownedProjectsCache,[t],"clientApp.useOwnedProjects()");return(0,S.useMemo)(()=>r.map(r=>this._getOwnedAdminApp(r.id,t)._adminOwnedProjectFromCrud(r,()=>this._refreshOwnedProjects(t))),[r])}async _createProject(t,r){this._ensureInternalProject();let i=await this._interface.createProject({...en(r),display_name:r.displayName,is_development_environment:r.isDevelopmentEnvironment,owner_team_id:r.teamId},t),s=this._getOwnedAdminApp(i.id,t)._adminOwnedProjectFromCrud(i,()=>this._refreshOwnedProjects(t));return await this._refreshOwnedProjects(t),s}async _refreshUser(t){await this._refreshSession(t)}async _refreshSession(t){await Promise.all([this._currentUserCache.refresh([t]),this._currentUserConnectedAccountsCache.refresh([t])]),t.suggestAccessTokenExpired()}async _refreshUsers(){}async _refreshProject(){await this._currentProjectCache.refresh([])}async _refreshOwnedProjects(t){await this._ownedProjectsCache.refresh([t])}static get[es.hexclaveAppInternalsSymbol](){return{fromClientJson:t=>{let i=JSON.stringify((0,z.omit)(t,[])),s=tx.get(t.uniqueIdentifier);if(s){let[r,n]=s;if(void 0!==r&&r!==i)throw new x.HexclaveAssertionError("The provided app JSON does not match the configuration of the existing client app with the same unique identifier",{providedObj:t,existingString:r});return n}let{analytics:n,...a}=(0,z.omit)(t,["uniqueIdentifier"]);return new r({...a,analytics:function(t){if(!t?.replays?.blockClass)return t;let{blockClass:r,...i}=t.replays;return"object"==typeof r&&"__regexp"in r?{...t,replays:{...i,blockClass:new RegExp(r.__regexp,r.__flags)}}:t}(n)},{uniqueIdentifier:t.uniqueIdentifier,checkString:i})}}}get[es.hexclaveAppInternalsSymbol](){return{toClientJson:()=>{if("string"!=typeof this._redirectMethod)throw new x.HexclaveAssertionError("Cannot serialize to JSON from an application with a non-string redirect method");let t="publishableClientKey"in this._interface.options?this._interface.options.publishableClientKey:void 0;return{baseUrl:this._options.baseUrl,projectId:this.projectId,...null!=t?{publishableClientKey:t}:{},tokenStore:this._tokenStoreInit,urls:this._urlOptions,oauthScopesOnSignIn:this._oauthScopesOnSignIn,uniqueIdentifier:this._getUniqueIdentifier(),redirectMethod:this._redirectMethod,extraRequestHeaders:this._options.extraRequestHeaders,devTool:this._options.devTool,analytics:function(t){if(!t?.replays?.blockClass)return t;let{blockClass:r,...i}=t.replays;return r instanceof RegExp?{...t,replays:{...i,blockClass:{__regexp:r.source,__flags:r.flags}}}:t}(this._analyticsOptions)}},setCurrentUser:t=>{(0,E.runAsynchronously)(async()=>{await this._currentUserCache.forceSetCachedValueAsync([await this._getSession()],w.Result.fromPromise(t))})},getConstructorOptions:()=>this._options,sendSessionReplayBatch:async(t,r)=>await this._interface.sendSessionReplayBatch(t,await this._getSession(),r),sendAnalyticsEventBatch:async(t,r)=>await this._interface.sendAnalyticsEventBatch(t,await this._getSession(),r),addRequestListener:t=>this._interface.addRequestListener(t),sendRequest:async(t,r,i="client")=>await this._interface.sendClientRequest(t,r,await this._getSession(),i),getRedirectMethod:()=>this._redirectMethod??(0,x.throwErr)("Redirect method should have been initialized in the Stack client app constructor"),redirectToUrl:async(t,r)=>{await this._redirectTo({url:t,...r})},redirectToHandler:async(t,r)=>{await this._redirectToHandler(t,r)},refreshOwnedProjects:async()=>{await this._refreshOwnedProjects(await this._getSession())},signInWithTokens:async t=>{await this._signInToAccountWithTokens(t)}}}},tw=class extends tA{async _refreshTeamMembership(t,r){await Promise.all([this._serverTeamMemberProfilesCache.refresh([t]),this._serverTeamsCache.refreshWhere(([t])=>t===r||void 0===t),this._serverUsersCache.refreshWhere(r=>r[8]===t)])}_createServerCustomer(t,r){let i=this,s="user"===r?i._serverUserProductsCache:i._serverTeamProductsCache,n="user"===r?{userId:t}:{teamId:t};return{...this._createCustomer(t,r,null),getItem:async t=>await i.getItem({itemId:t,...n}),useItem:t=>i.useItem({itemId:t,...n}),async grantProduct(n){"user"===r?"productId"in n?await i.grantProduct({userId:t,productId:n.productId,quantity:n.quantity}):await i.grantProduct({userId:t,product:n.product,quantity:n.quantity}):"productId"in n?await i.grantProduct({teamId:t,productId:n.productId,quantity:n.quantity}):await i.grantProduct({teamId:t,product:n.product,quantity:n.quantity}),await s.refresh([t,null,null])},async createCheckoutUrl(s){let n="productId"in s?s.productId:s.product;return await i._interface.createCheckoutUrl(r,t,n,null,s.returnUrl,"server")}}}async _updateServerUser(t,r){let i=await this._interface.updateServerUser(t,{display_name:r.displayName,primary_email:r.primaryEmail,client_metadata:r.clientMetadata,client_read_only_metadata:r.clientReadOnlyMetadata,server_metadata:r.serverMetadata,selected_team_id:r.selectedTeamId,primary_email_auth_enabled:r.primaryEmailAuthEnabled,primary_email_verified:r.primaryEmailVerified,password:r.password,profile_image_url:r.profileImageUrl,totp_secret_base64:null!=r.totpMultiFactorSecret?(0,Y.encodeBase64)(r.totpMultiFactorSecret):r.totpMultiFactorSecret,restricted_by_admin:r.restrictedByAdmin,restricted_by_admin_reason:r.restrictedByAdminReason,restricted_by_admin_private_details:r.restrictedByAdminPrivateDetails,country_code:r.countryCode,risk_scores:r.riskScores?{sign_up:{bot:r.riskScores.signUp.bot,free_trial_abuse:r.riskScores.signUp.freeTrialAbuse}}:void 0});return await this._refreshUsers(),i}_serverEditableTeamProfileFromCrud(t){let r=this;return{displayName:t.display_name,profileImageUrl:t.profile_image_url,async update(i){await r._interface.updateServerTeamMemberProfile({teamId:t.team_id,userId:t.user_id,profile:{display_name:i.displayName,profile_image_url:i.profileImageUrl}}),await r._serverUserTeamProfileCache.refresh([t.team_id,t.user_id])}}}_serverContactChannelFromCrud(t,r){let i=this;return{id:r.id,value:r.value,type:r.type,isVerified:r.is_verified,isPrimary:r.is_primary,usedForAuth:r.used_for_auth,async sendVerificationEmail(s){await i._interface.sendServerContactChannelVerificationEmail(t,r.id,s?.callbackUrl??q(i._getUrls().emailVerification,"callbackUrl"))},async update(s){await i._interface.updateServerContactChannel(t,r.id,{value:s.value,is_verified:s.isVerified,used_for_auth:s.usedForAuth,is_primary:s.isPrimary}),await Promise.all([i._serverContactChannelsCache.refresh([t]),i._serverUserCache.refresh([t])])},async delete(){await i._interface.deleteServerContactChannel(t,r.id),await Promise.all([i._serverContactChannelsCache.refresh([t]),i._serverUserCache.refresh([t])])}}}_serverNotificationCategoryFromCrud(t,r){let i=this;return{id:r.notification_category_id,name:r.notification_category_name,enabled:r.enabled,canDisable:r.can_disable,async setEnabled(s){await i._interface.setServerNotificationsEnabled(t,r.notification_category_id,s),await i._serverNotificationCategoriesCache.refresh([t])}}}_serverOAuthProviderFromCrud(t){let r=this;return{id:t.id,type:t.type,userId:t.user_id,accountId:t.account_id,email:t.email,allowSignIn:t.allow_sign_in,allowConnectedAccounts:t.allow_connected_accounts,async update(i){try{return await r._interface.updateServerOAuthProvider(t.user_id,t.id,{account_id:i.accountId,email:i.email,allow_sign_in:i.allowSignIn,allow_connected_accounts:i.allowConnectedAccounts}),await Promise.all([r._serverOAuthProvidersCache.refresh([t.user_id]),r._serverUserConnectedAccountsCache.refresh([t.user_id])]),w.Result.ok(void 0)}catch(t){if(P.KnownErrors.OAuthProviderAccountIdAlreadyUsedForSignIn.isInstance(t))return w.Result.error(t);throw t}},async delete(){await r._interface.deleteServerOAuthProvider(t.user_id,t.id),await Promise.all([r._serverOAuthProvidersCache.refresh([t.user_id]),r._serverUserConnectedAccountsCache.refresh([t.user_id])])}}}constructor(t,r){const i=(0,C.resolveConstructorOptions)(t),s=i.publishableClientKey??(0,C.getDefaultPublishableClientKey)();super(i,{...r,interface:r?.interface??(()=>{let t=(0,C.resolveApiUrls)(i.baseUrl);return new _.HexclaveServerInterface({getBaseUrl:()=>t()[0],getApiUrls:t,projectId:i.projectId??(0,C.getDefaultProjectId)(),extraRequestHeaders:i.extraRequestHeaders??(0,C.getDefaultExtraRequestHeaders)(),clientVersion:C.clientVersion,...null!=s?{publishableClientKey:s}:{},secretServerKey:i.secretServerKey??(0,C.getDefaultSecretServerKey)()})})()}),this._currentServerUserCache=(0,C.createCacheBySession)(async t=>t.isKnownToBeInvalid()?null:await this._interface.getServerUserByToken(t)),this._serverUsersCache=(0,C.createCache)(async([t,r,i,s,n,a,o,l,p])=>{if(l&&!o)throw new x.HexclaveAssertionError("onlyAnonymous=true requires includeAnonymous=true");return l?await this._interface.listServerUsers({cursor:t,limit:r,orderBy:i,desc:s,query:n,includeRestricted:a,includeAnonymous:!0,onlyAnonymous:!0,teamId:p}):await this._interface.listServerUsers({cursor:t,limit:r,orderBy:i,desc:s,query:n,includeRestricted:a,includeAnonymous:o,teamId:p})}),this._serverUserCache=(0,C.createCache)(async([t])=>{let r=await this._interface.getServerUserById(t);return w.Result.or(r,null)}),this._serverTeamsCache=(0,C.createCache)(async([t,r,i,s,n,a])=>await this._interface.listServerTeamsPaginated({userId:t,orderBy:r,desc:i,cursor:s,limit:n,query:a})),this._serverUserTeamInvitationsCache=(0,C.createCache)(async([t])=>await this._interface.listServerUserTeamInvitations(t)),this._serverTeamUserPermissionsCache=(0,C.createCache)(async([t,r,i])=>await this._interface.listServerTeamPermissions({teamId:t,userId:r,recursive:i},null)),this._serverAllTeamMemberPermissionsCache=(0,C.createCache)(async([t,r])=>await this._interface.listServerTeamPermissions({teamId:t,recursive:r},null)),this._serverUserProjectPermissionsCache=(0,C.createCache)(async([t,r])=>await this._interface.listServerProjectPermissions({userId:t,recursive:r},null)),this._serverUserOAuthConnectionAccessTokensCache=(0,C.createCache)(async([t,r,i])=>{try{return{accessToken:(await this._interface.createServerProviderAccessToken(t,r,i||"")).access_token}}catch(t){if(!(P.KnownErrors.OAuthAccessTokenNotAvailable.isInstance(t)||P.KnownErrors.OAuthConnectionDoesNotHaveRequiredScope.isInstance(t)||P.KnownErrors.OAuthConnectionNotConnectedToUser.isInstance(t)))throw t}return null}),this._serverUserOAuthConnectionCache=(0,C.createCache)(async([t,r,i,s])=>await this._getUserOAuthConnectionCacheFn({getUser:async()=>w.Result.orThrow(await this._serverUserCache.getOrWait([t],"write-only")),getOrWaitOAuthToken:async()=>w.Result.orThrow(await this._serverUserOAuthConnectionAccessTokensCache.getOrWait([t,r,i||""],"write-only")),useOAuthToken:()=>(0,C.useAsyncCache)(this._serverUserOAuthConnectionAccessTokensCache,[t,r,i||""],"user.useConnectedAccount()"),providerId:r,scope:i,redirect:s,session:null})),this._serverUserConnectedAccountsCache=(0,C.createCache)(async([t])=>(await this._interface.listServerConnectedAccounts(t)).items.map(r=>this._createServerOAuthConnectionFromCrudItem(t,r))),this._serverUserOAuthConnectionAccessTokensByAccountCache=(0,C.createCache)(async([t,r,i,s])=>{try{return{accessToken:(await this._interface.createServerProviderAccessTokenByAccount(t,r,i,s||"")).access_token}}catch(t){if(!(P.KnownErrors.OAuthAccessTokenNotAvailable.isInstance(t)||P.KnownErrors.OAuthConnectionDoesNotHaveRequiredScope.isInstance(t)||P.KnownErrors.OAuthConnectionNotConnectedToUser.isInstance(t)))throw t}return null}),this._serverTeamMemberProfilesCache=(0,C.createCache)(async([t])=>await this._interface.listServerTeamMemberProfiles({teamId:t})),this._serverTeamInvitationsCache=(0,C.createCache)(async([t])=>await this._interface.listServerTeamInvitations({teamId:t})),this._serverUserTeamProfileCache=(0,C.createCache)(async([t,r])=>await this._interface.getServerTeamMemberProfile({teamId:t,userId:r})),this._serverContactChannelsCache=(0,C.createCache)(async([t])=>await this._interface.listServerContactChannels(t)),this._serverNotificationCategoriesCache=(0,C.createCache)(async([t])=>await this._interface.listServerNotificationCategories(t)),this._serverDataVaultStoreValueCache=(0,C.createCache)(async([t,r,i])=>await this._interface.getDataVaultStoreValue(i,t,r)),this._emailDeliveryInfoCache=(0,C.createCache)(async()=>await this._interface.getEmailDeliveryInfo()),this._serverUserApiKeysCache=(0,C.createCache)(async([t])=>await this._interface.listProjectApiKeys({user_id:t},null,"server")),this._serverTeamApiKeysCache=(0,C.createCache)(async([t])=>await this._interface.listProjectApiKeys({team_id:t},null,"server")),this._convexIdentitySubjectCache=(0,C.createCache)(async([t])=>{let r=await t.auth.getUserIdentity();return r?r.subject:null}),this._serverCheckApiKeyCache=(0,C.createCache)(async([t,r])=>await this._interface.checkProjectApiKey(t,r,null,"server")),this._serverOAuthProvidersCache=(0,C.createCache)(async([t])=>await this._interface.listServerOAuthProviders({user_id:t})),this._serverTeamItemsCache=(0,C.createCache)(async([t,r])=>await this._interface.getItem({teamId:t,itemId:r},null,"server")),this._serverUserItemsCache=(0,C.createCache)(async([t,r])=>await this._interface.getItem({userId:t,itemId:r},null,"server")),this._serverCustomItemsCache=(0,C.createCache)(async([t,r])=>await this._interface.getItem({customCustomerId:t,itemId:r},null,"server")),this._serverUserProductsCache=(0,C.createCache)(async([t,r,i])=>await this._interface.listProducts({customer_type:"user",customer_id:t,cursor:r??void 0,limit:i??void 0},null,"server")),this._serverTeamProductsCache=(0,C.createCache)(async([t,r,i])=>await this._interface.listProducts({customer_type:"team",customer_id:t,cursor:r??void 0,limit:i??void 0},null,"server")),this._serverCustomProductsCache=(0,C.createCache)(async([t,r,i])=>await this._interface.listProducts({customer_type:"custom",customer_id:t,cursor:r??void 0,limit:i??void 0},null,"server"))}_serverApiKeyFromCrud(t){return{...this._baseApiKeyFromCrud(t),async revoke(){await this.update({revoked:!0})},update:async r=>{await this._interface.updateProjectApiKey("team"===t.type?{team_id:t.team_id}:{user_id:t.user_id},t.id,await H(t.type,r),null,"server"),"team"===t.type?await this._serverTeamApiKeysCache.refresh([t.team_id]):await this._serverUserApiKeysCache.refresh([t.user_id])}}}_createServerOAuthConnectionFromCrudItem(t,r){let i=this,s=r.provider,n=r.provider_account_id;return{id:s,provider:s,providerAccountId:n,async getAccessToken(r){let a=r?.scopes?.join(" ")??"",o=w.Result.orThrow(await i._serverUserOAuthConnectionAccessTokensByAccountCache.getOrWait([t,s,n,a],"write-only"));if(!o){let t=a?`The requested scopes [${a}] are not available on the existing token.`:"The OAuth refresh token has likely been revoked or expired.";return w.Result.error(new P.KnownErrors.OAuthAccessTokenNotAvailable(s,`${t} The user needs to re-authorize by calling \`linkConnectedAccount\` or using \`getOrLinkConnectedAccount\`.`))}return w.Result.ok(o)},useAccessToken(r){let a=r?.scopes?.join(" ")??"",o=(0,C.useAsyncCache)(i._serverUserOAuthConnectionAccessTokensByAccountCache,[t,s,n,a],"connection.useAccessToken()");if(!o){let t=a?`The requested scopes [${a}] are not available on the existing token.`:"The OAuth refresh token has likely been revoked or expired.";return w.Result.error(new P.KnownErrors.OAuthAccessTokenNotAvailable(s,`${t} The user needs to re-authorize by calling \`linkConnectedAccount\` or using \`getOrLinkConnectedAccount\`.`))}return w.Result.ok(o)}}}_serverUserFromCrud(t){let r=this;async function i(i,s){let n=s?.scopes?.join(" ")??"";if("object"==typeof i&&"provider"in i&&"providerAccountId"in i){let{provider:s,providerAccountId:n}=i,a=w.Result.orThrow(await r._serverUserConnectedAccountsCache.getOrWait([t.id],"write-only")).find(t=>t.provider===s&&t.providerAccountId===n);return a||null}return w.Result.orThrow(await r._serverUserOAuthConnectionCache.getOrWait([t.id,i,n,s?.or==="redirect"],"write-only"))}return X({...super._createBaseUser(t),lastActiveAt:new Date(t.last_active_at_millis),serverMetadata:t.server_metadata,restrictedByAdmin:t.restricted_by_admin,restrictedByAdminReason:t.restricted_by_admin_reason,restrictedByAdminPrivateDetails:t.restricted_by_admin_private_details,countryCode:t.country_code,riskScores:{signUp:{bot:t.risk_scores.sign_up.bot,freeTrialAbuse:t.risk_scores.sign_up.free_trial_abuse}},async setPrimaryEmail(i,s){await r._updateServerUser(t.id,{primaryEmail:i,primaryEmailVerified:s?.verified})},async grantPermission(i,s){if(i&&"string"!=typeof i&&s)for(let n of(await r._interface.grantServerTeamUserPermission(i.id,t.id,s),[!0,!1]))await r._serverTeamUserPermissionsCache.refresh([i.id,t.id,n]),await r._serverAllTeamMemberPermissionsCache.refresh([i.id,n]);else for(let s of(await r._interface.grantServerProjectPermission(t.id,i),[!0,!1]))await r._serverUserProjectPermissionsCache.refresh([t.id,s])},async revokePermission(i,s){if(i&&"string"!=typeof i&&s)for(let n of(await r._interface.revokeServerTeamUserPermission(i.id,t.id,s),[!0,!1]))await r._serverTeamUserPermissionsCache.refresh([i.id,t.id,n]),await r._serverAllTeamMemberPermissionsCache.refresh([i.id,n]);else for(let s of(await r._interface.revokeServerProjectPermission(t.id,i),[!0,!1]))await r._serverUserProjectPermissionsCache.refresh([t.id,s])},async delete(){let i=await r._interface.deleteServerUser(t.id);return await r._refreshUsers(),i},async createSession(i){let s=await r._interface.createServerUserSession(t.id,i.expiresInMillis??31536e6,i.isImpersonation??!1);return{getTokens:async()=>s}},getActiveSessions:async()=>(await r._interface.listServerSessions(t.id)).items.map(t=>r._clientSessionFromCrud(t)),async revokeSession(t){await r._interface.deleteServerSession(t)},async setDisplayName(t){return await this.update({displayName:t})},async setClientMetadata(t){return await this.update({clientMetadata:t})},async setClientReadOnlyMetadata(t){return await this.update({clientReadOnlyMetadata:t})},async setServerMetadata(t){return await this.update({serverMetadata:t})},async setSelectedTeam(t){return await this.update({selectedTeamId:"string"==typeof t?t:t?.id??null})},getConnectedAccount:i,useConnectedAccount:function(i,s){let n=s?.scopes?.join(" ")??"";if("object"==typeof i&&"provider"in i&&"providerAccountId"in i){let{provider:s,providerAccountId:n}=i;return(0,C.useAsyncCache)(r._serverUserConnectedAccountsCache,[t.id],"user.useConnectedAccount()").find(t=>t.provider===s&&t.providerAccountId===n)??null}return(0,C.useAsyncCache)(r._serverUserOAuthConnectionCache,[t.id,i,n,s?.or==="redirect"],"user.useConnectedAccount()")},listConnectedAccounts:async()=>w.Result.orThrow(await r._serverUserConnectedAccountsCache.getOrWait([t.id],"write-only")),useConnectedAccounts:()=>(0,C.useAsyncCache)(r._serverUserConnectedAccountsCache,[t.id],"user.useConnectedAccounts()"),async linkConnectedAccount(){throw new x.HexclaveAssertionError("linkConnectedAccount is not available for server users. OAuth flows must be initiated on the client side.")},async getOrLinkConnectedAccount(){throw new x.HexclaveAssertionError("getOrLinkConnectedAccount is not available for server users. OAuth flows must be initiated on the client side.")},useOrLinkConnectedAccount(){throw new x.HexclaveAssertionError("useOrLinkConnectedAccount is not available for server users. OAuth flows must be initiated on the client side.")},selectedTeam:t.selected_team?r._serverTeamFromCrud(t.selected_team):null,async getTeam(t){return(await this.listTeams()).find(r=>r.id===t)??null},useTeam(t){let r=this.useTeams();return(0,S.useMemo)(()=>r.find(r=>r.id===t)??null,[r,t])},async listTeams(i){let s=w.Result.orThrow(await r._serverTeamsCache.getOrWait([t.id,i?.orderBy,i?.desc,i?.cursor,i?.limit,i?.query],"write-only")),n=s.items.map(t=>r._serverTeamFromCrud(t));return n.nextCursor=s.pagination?.next_cursor??null,n},useTeams(i){let s=(0,C.useAsyncCache)(r._serverTeamsCache,[t.id,i?.orderBy,i?.desc,i?.cursor,i?.limit,i?.query],"user.useTeams()");return(0,S.useMemo)(()=>{let t=s.items.map(t=>r._serverTeamFromCrud(t));return t.nextCursor=s.pagination?.next_cursor??null,t},[s])},createTeam:async i=>{let s=await r._interface.createServerTeam(J({creatorUserId:t.id,...i}));return await r._serverTeamsCache.refreshWhere(()=>!0),await r._updateServerUser(t.id,{selectedTeamId:s.id}),r._serverTeamFromCrud(s)},leaveTeam:async i=>{await r._interface.leaveServerTeam({teamId:i.id,userId:t.id}),await r._refreshTeamMembership(i.id,t.id)},listTeamInvitations:async()=>w.Result.orThrow(await r._serverUserTeamInvitationsCache.getOrWait([t.id],"write-only")).map(i=>r._serverReceivedTeamInvitationFromCrud(t.id,i)),useTeamInvitations(){let i=(0,C.useAsyncCache)(r._serverUserTeamInvitationsCache,[t.id],"user.useTeamInvitations()");return(0,S.useMemo)(()=>i.map(i=>r._serverReceivedTeamInvitationFromCrud(t.id,i)),[i])},async listPermissions(i,s){if(i&&"id"in i){let n=s?.recursive??!0;return w.Result.orThrow(await r._serverTeamUserPermissionsCache.getOrWait([i.id,t.id,n],"write-only")).map(t=>r._serverPermissionFromCrud(t))}{let s=i?.recursive??!0;return w.Result.orThrow(await r._serverUserProjectPermissionsCache.getOrWait([t.id,s],"write-only")).map(t=>r._serverPermissionFromCrud(t))}},usePermissions(i,s){if(i&&"id"in i){let n=s?.recursive??!0,a=(0,C.useAsyncCache)(r._serverTeamUserPermissionsCache,[i.id,t.id,n],"user.usePermissions()");return(0,S.useMemo)(()=>a.map(t=>r._serverPermissionFromCrud(t)),[a])}{let s=i?.recursive??!0,n=(0,C.useAsyncCache)(r._serverUserProjectPermissionsCache,[t.id,s],"user.usePermissions()");return(0,S.useMemo)(()=>n.map(t=>r._serverPermissionFromCrud(t)),[n])}},async getPermission(t,r){return t&&"string"!=typeof t?(await this.listPermissions(t)).find(t=>t.id===r)??null:(await this.listPermissions()).find(r=>r.id===t)??null},usePermission(t,r){if(t&&"string"!=typeof t){let i=this.usePermissions(t);return(0,S.useMemo)(()=>i.find(t=>t.id===r)??null,[i,r])}{let r=this.usePermissions();return(0,S.useMemo)(()=>r.find(r=>r.id===t)??null,[r,t])}},async hasPermission(t,r){return t&&"string"!=typeof t?await this.getPermission(t,r)!==null:await this.getPermission(t)!==null},async update(i){await r._updateServerUser(t.id,i)},sendVerificationEmail:async()=>await r._checkFeatureSupport("sendVerificationEmail() on ServerUser",{}),async updatePassword(i){let s=await r._interface.updatePassword(i);return await r._serverUserCache.refresh([t.id]),s},async setPassword(i){let s=await this.update(i);return await r._serverUserCache.refresh([t.id]),s},async getTeamProfile(i){let s=w.Result.orThrow(await r._serverUserTeamProfileCache.getOrWait([i.id,t.id],"write-only"));return r._serverEditableTeamProfileFromCrud(s)},useTeamProfile(i){let s=(0,C.useAsyncCache)(r._serverUserTeamProfileCache,[i.id,t.id],"user.useTeamProfile()");return(0,S.useMemo)(()=>r._serverEditableTeamProfileFromCrud(s),[s])},listContactChannels:async()=>w.Result.orThrow(await r._serverContactChannelsCache.getOrWait([t.id],"write-only")).map(i=>r._serverContactChannelFromCrud(t.id,i)),useContactChannels(){let i=(0,C.useAsyncCache)(r._serverContactChannelsCache,[t.id],"user.useContactChannels()");return(0,S.useMemo)(()=>i.map(i=>r._serverContactChannelFromCrud(t.id,i)),[i])},createContactChannel:async i=>{var s;let n=await r._interface.createServerContactChannel((s=t.id,{type:i.type,value:i.value,is_verified:i.isVerified,user_id:s,used_for_auth:i.usedForAuth,is_primary:i.isPrimary}));return await Promise.all([r._serverContactChannelsCache.refresh([t.id]),r._serverUserCache.refresh([t.id])]),r._serverContactChannelFromCrud(t.id,n)},useNotificationCategories:()=>(0,C.useAsyncCache)(r._serverNotificationCategoriesCache,[t.id],"user.useNotificationCategories()").map(i=>r._serverNotificationCategoryFromCrud(t.id,i)),listNotificationCategories:async()=>w.Result.orThrow(await r._serverNotificationCategoriesCache.getOrWait([t.id],"write-only")).map(i=>r._serverNotificationCategoryFromCrud(t.id,i)),useApiKeys:()=>(0,C.useAsyncCache)(r._serverUserApiKeysCache,[t.id],"user.useApiKeys()").map(t=>r._serverApiKeyFromCrud(t)),listApiKeys:async()=>w.Result.orThrow(await r._serverUserApiKeysCache.getOrWait([t.id],"write-only")).map(t=>r._serverApiKeyFromCrud(t)),async createApiKey(i){let s=await r._interface.createProjectApiKey(await W("user",t.id,i),null,"server");return await r._serverUserApiKeysCache.refresh([t.id]),r._serverApiKeyFromCrud(s)},useOAuthProviders(){let i=(0,C.useAsyncCache)(r._serverOAuthProvidersCache,[t.id],"user.useOAuthProviders()");return(0,S.useMemo)(()=>i.map(t=>r._serverOAuthProviderFromCrud(t)),[i])},listOAuthProviders:async()=>w.Result.orThrow(await r._serverOAuthProvidersCache.getOrWait([t.id],"write-only")).map(t=>r._serverOAuthProviderFromCrud(t)),useOAuthProvider(t){let r=this.useOAuthProviders();return(0,S.useMemo)(()=>r.find(r=>r.id===t)??null,[r,t])},async getOAuthProvider(t){return(await this.listOAuthProviders()).find(r=>r.id===t)??null},async registerPasskey(i){let s,n=i?.hostname||(await r._getCurrentUrl())?.hostname;if(!n)throw new x.HexclaveAssertionError("hostname must be provided if the Stack App does not have a redirect method");let a=await r._interface.initiateServerPasskeyRegistration(t.id);if("ok"!==a.status)return w.Result.error(new P.KnownErrors.PasskeyRegistrationFailed("Failed to get initiation options for passkey registration"));let{options_json:o,code:l}=a.data;if("THIS_VALUE_WILL_BE_REPLACED.example.com"!==o.rp.id)throw new x.HexclaveAssertionError(`Expected returned RP ID from server to equal sentinel, but found ${o.rp.id}`);o.rp.id=n;try{s=await U({optionsJSON:o})}catch(t){if(t instanceof R)return w.Result.error(new P.KnownErrors.PasskeyWebAuthnError(t.message,t.name));return(0,x.captureError)("passkey-registration-failed",t),w.Result.error(new P.KnownErrors.PasskeyRegistrationFailed("Failed to start passkey registration due to unknown error"))}let{accessToken:p,refreshToken:u}=await r._interface.createServerUserSession(t.id,6e4*2,!1),c=new I.InternalSession({accessToken:p,refreshToken:u,refreshAccessTokenCallback:async()=>null}),d=await r._interface.registerPasskey({credential:s,code:l},c);return await r._serverUserCache.refresh([t.id]),d},...r._createServerCustomer(t.id,"user")})}_serverTeamUserFromCrud(t){return X({...this._serverUserFromCrud(t.user),teamProfile:{displayName:t.display_name,profileImageUrl:t.profile_image_url}})}_serverSentTeamInvitationFromCrud(t){return{id:t.id,recipientEmail:t.recipient_email,expiresAt:new Date(t.expires_at_millis),revoke:async()=>{await this._interface.revokeServerTeamInvitation(t.id,t.team_id),await this._serverTeamInvitationsCache.refresh([t.team_id])}}}_serverReceivedTeamInvitationFromCrud(t,r){let i=this;return{id:r.id,teamId:r.team_id,teamDisplayName:r.team_display_name,recipientEmail:r.recipient_email,expiresAt:new Date(r.expires_at_millis),accept:async()=>{await i._interface.acceptServerTeamInvitationById(r.id,t),await Promise.all([i._serverUserTeamInvitationsCache.refresh([t]),i._serverTeamInvitationsCache.refresh([r.team_id]),i._refreshTeamMembership(r.team_id,t)])}}}_currentUserFromCrud(t,r){return X({...this._serverUserFromCrud(t),...this._createAuth(r),...this._isInternalProject()?this._createInternalUserExtra(r):{}})}_serverTeamFromCrud(t){let r=this;return{id:t.id,displayName:t.display_name,profileImageUrl:t.profile_image_url,createdAt:new Date(t.created_at_millis),clientMetadata:t.client_metadata,clientReadOnlyMetadata:t.client_read_only_metadata,serverMetadata:t.server_metadata,async update(i){await r._interface.updateServerTeam(t.id,{display_name:i.displayName,profile_image_url:i.profileImageUrl,client_metadata:i.clientMetadata,client_read_only_metadata:i.clientReadOnlyMetadata,server_metadata:i.serverMetadata}),await Promise.all([r._serverTeamsCache.refreshWhere(()=>!0),r._serverUsersCache.refreshWhere(()=>!0)])},async delete(){await r._interface.deleteServerTeam(t.id),await Promise.all([r._serverTeamsCache.refreshWhere(()=>!0),r._serverUsersCache.refreshWhere(()=>!0)])},listUsers:async()=>w.Result.orThrow(await r._serverTeamMemberProfilesCache.getOrWait([t.id],"write-only")).map(t=>r._serverTeamUserFromCrud(t)),useUsers(){let i=(0,C.useAsyncCache)(r._serverTeamMemberProfilesCache,[t.id],"team.useUsers()");return(0,S.useMemo)(()=>i.map(t=>r._serverTeamUserFromCrud(t)),[i])},async addUser(i){await r._interface.addServerUserToTeam({teamId:t.id,userId:i}),await r._refreshTeamMembership(t.id,i)},async removeUser(i){await r._interface.removeServerUserFromTeam({teamId:t.id,userId:i}),await r._refreshTeamMembership(t.id,i)},async inviteUser(i){await r._interface.sendServerTeamInvitation({teamId:t.id,email:i.email,callbackUrl:i.callbackUrl??q(r._getUrls().teamInvitation,"callbackUrl")}),await r._serverTeamInvitationsCache.refresh([t.id])},listInvitations:async()=>w.Result.orThrow(await r._serverTeamInvitationsCache.getOrWait([t.id],"write-only")).map(t=>r._serverSentTeamInvitationFromCrud(t)),useInvitations(){let i=(0,C.useAsyncCache)(r._serverTeamInvitationsCache,[t.id],"team.useInvitations()");return(0,S.useMemo)(()=>i.map(t=>r._serverSentTeamInvitationFromCrud(t)),[i])},useApiKeys:()=>(0,C.useAsyncCache)(r._serverTeamApiKeysCache,[t.id],"team.useApiKeys()").map(t=>r._serverApiKeyFromCrud(t)),listApiKeys:async()=>w.Result.orThrow(await r._serverTeamApiKeysCache.getOrWait([t.id],"write-only")).map(t=>r._serverApiKeyFromCrud(t)),async createApiKey(i){let s=await r._interface.createProjectApiKey(await W("team",t.id,i),null,"server");return await r._serverTeamApiKeysCache.refresh([t.id]),r._serverApiKeyFromCrud(s)},...r._createServerCustomer(t.id,"team")}}_serverItemFromCrud(t,r){let i=this;return{displayName:r.display_name,quantity:r.quantity,nonNegativeQuantity:Math.max(0,r.quantity),increaseQuantity:async s=>{let n="user"===t.type?{itemId:r.id,userId:t.id}:"team"===t.type?{itemId:r.id,teamId:t.id}:{itemId:r.id,customCustomerId:t.id};await i._interface.updateItemQuantity(n,{delta:s}),"user"===t.type?await i._serverUserItemsCache.refresh([t.id,r.id]):"team"===t.type?await i._serverTeamItemsCache.refresh([t.id,r.id]):await i._serverCustomItemsCache.refresh([t.id,r.id])},decreaseQuantity:async s=>{let n="user"===t.type?{itemId:r.id,userId:t.id}:"team"===t.type?{itemId:r.id,teamId:t.id}:{itemId:r.id,customCustomerId:t.id};await i._interface.updateItemQuantity(n,{delta:-s,allow_negative:!0}),"user"===t.type?await i._serverUserItemsCache.refresh([t.id,r.id]):"team"===t.type?await i._serverTeamItemsCache.refresh([t.id,r.id]):await i._serverCustomItemsCache.refresh([t.id,r.id])},tryDecreaseQuantity:async s=>{try{let n="user"===t.type?{itemId:r.id,userId:t.id}:"team"===t.type?{itemId:r.id,teamId:t.id}:{itemId:r.id,customCustomerId:t.id};return await i._interface.updateItemQuantity(n,{delta:-s}),"user"===t.type?await i._serverUserItemsCache.refresh([t.id,r.id]):"team"===t.type?await i._serverTeamItemsCache.refresh([t.id,r.id]):await i._serverCustomItemsCache.refresh([t.id,r.id]),!0}catch(t){if(t instanceof P.KnownErrors.ItemQuantityInsufficientAmount)return!1;throw t}}}}async _getUserApiKey(t){let r=w.Result.orThrow(await this._serverCheckApiKeyCache.getOrWait(["user",t.apiKey],"write-only"));return r?this._serverApiKeyFromCrud(r):null}async _getTeamApiKey(t){let r=w.Result.orThrow(await this._serverCheckApiKeyCache.getOrWait(["team",t.apiKey],"write-only"));return r?this._serverApiKeyFromCrud(r):null}_useUserApiKey(t){let r=(0,C.useAsyncCache)(this._serverCheckApiKeyCache,["user",t.apiKey],"serverApp.useUserApiKey()");return(0,S.useMemo)(()=>r?this._serverApiKeyFromCrud(r):null,[r])}_useTeamApiKey(t){let r=(0,C.useAsyncCache)(this._serverCheckApiKeyCache,["team",t.apiKey],"serverApp.useTeamApiKey()");return(0,S.useMemo)(()=>r?this._serverApiKeyFromCrud(r):null,[r])}async _getUserByApiKey(t){let r=await this._getUserApiKey({apiKey:t});return null===r?null:await this.getServerUserById(r.userId)}async _getUserByConvex(t,r){let i=await t.auth.getUserIdentity();if(null===i)return null;let s=await this.getServerUserById(i.subject);return s?.isAnonymous&&!r?null:s}_useUserByConvex(t,r){let i=(0,C.useAsyncCache)(this._convexIdentitySubjectCache,[t],"serverApp.useUserByConvex()");if(null===i)return null;let s=this.useUserById(i);return s?.isAnonymous&&!r?null:s}_useUserByApiKey(t){let r=this._useUserApiKey({apiKey:t});return null===r?null:this.useUserById(r.userId)}async _getTeamByApiKey(t){let r=await this._getTeamApiKey({apiKey:t});return null===r?null:await this.getTeam(r.teamId)}_useTeamByApiKey(t){let r=this._useTeamApiKey({apiKey:t});return null===r?null:this.useTeam(r.teamId)}async createUser(t){let r=await this._interface.createServerUser({primary_email:t.primaryEmail,password:t.password,otp_auth_enabled:t.otpAuthEnabled,primary_email_auth_enabled:t.primaryEmailAuthEnabled,display_name:t.displayName,primary_email_verified:t.primaryEmailVerified,client_metadata:t.clientMetadata,client_read_only_metadata:t.clientReadOnlyMetadata,server_metadata:t.serverMetadata,country_code:t.countryCode,risk_scores:t.riskScores?{sign_up:{bot:t.riskScores.signUp.bot,free_trial_abuse:t.riskScores.signUp.freeTrialAbuse}}:void 0});return await this._refreshUsers(),this._serverUserFromCrud(r)}async getUser(t){if("string"==typeof t)return await this.getServerUserById(t);{if("object"==typeof t&&"apiKey"in t)return await this._getUserByApiKey(t.apiKey);if("object"==typeof t&&"from"in t&&"convex"===t.from)return await this._getUserByConvex(t.ctx,"or"in t&&"anonymous"===t.or);if(t?.or==="anonymous"&&!1===t.includeRestricted)throw Error("Cannot use { or: 'anonymous' } with { includeRestricted: false }. Anonymous users implicitly include restricted users.");this._ensurePersistentTokenStore(t?.tokenStore);let r=await this._getSession(t?.tokenStore),i=w.Result.orThrow(await this._currentServerUserCache.getOrWait([r],"write-only")),s=t?.or==="anonymous"||t?.or==="anonymous-if-exists[deprecated]",n=t?.includeRestricted===!0||s;if(null===i||i.is_anonymous&&!s||i.is_restricted&&!n)switch(t?.or){case"redirect":!i?.is_anonymous&&i?.is_restricted?await this.redirectToOnboarding({replace:!0}):await this.redirectToSignIn({replace:!0});break;case"throw":throw Error("User is not signed in but getUser was called with { or: 'throw' }");case"anonymous":{let t=await this._signUpAnonymously();return await this.getUser({tokenStore:t,or:"anonymous-if-exists[deprecated]",includeRestricted:!0})??(0,x.throwErr)("Something went wrong while signing up anonymously")}case void 0:case"anonymous-if-exists[deprecated]":case"return-null":return null}return i&&this._currentUserFromCrud(i,r)}}async getServerUser(){return console.warn("hexclaveServerApp.getServerUser is deprecated; use hexclaveServerApp.getUser instead"),await this.getUser()}async getServerUserById(t){let r=w.Result.orThrow(await this._serverUserCache.getOrWait([t],"write-only"));return r&&this._serverUserFromCrud(r)}useUser(t){if("string"==typeof t)return this.useUserById(t);{if("object"==typeof t&&"apiKey"in t)return this._useUserByApiKey(t.apiKey);if("object"==typeof t&&"from"in t&&"convex"===t.from)return this._useUserByConvex(t.ctx,"or"in t&&"anonymous"===t.or);if(t?.or==="anonymous"&&!1===t.includeRestricted)throw Error("Cannot use { or: 'anonymous' } with { includeRestricted: false }. Anonymous users implicitly include restricted users.");this._ensurePersistentTokenStore(t?.tokenStore);let r=this._useSession(t?.tokenStore),i=(0,C.useAsyncCache)(this._currentServerUserCache,[r],"serverApp.useUser()");if(t?.or==="anonymous"||t?.or,t?.includeRestricted,null===i)switch(t?.or){case"redirect":throw(0,E.runAsynchronously)(this.redirectToSignIn({replace:!0})),(0,A.suspend)(),new x.HexclaveAssertionError("suspend should never return");case"throw":throw Error("User is not signed in but useUser was called with { or: 'throw' }");case"anonymous":throw(0,E.runAsynchronously)(async()=>{await this._signUpAnonymously()}),(0,A.suspend)(),new x.HexclaveAssertionError("suspend should never return")}return(0,S.useMemo)(()=>i&&this._currentUserFromCrud(i,r),[i,r,t?.or])}}useUserById(t){let r=(0,C.useAsyncCache)(this._serverUserCache,[t],"serverApp.useUserById()");return(0,S.useMemo)(()=>r&&this._serverUserFromCrud(r),[r])}async listUsers(t){let r=w.Result.orThrow(await this._serverUsersCache.getOrWait([t?.cursor,t?.limit,t?.orderBy,t?.desc,t?.query,t?.includeRestricted,t?.includeAnonymous,t?.onlyAnonymous,t?.teamId],"write-only")),i=r.items.map(t=>this._serverUserFromCrud(t));return i.nextCursor=r.pagination?.next_cursor??null,i}useUsers(t){let r=(0,C.useAsyncCache)(this._serverUsersCache,[t?.cursor,t?.limit,t?.orderBy,t?.desc,t?.query,t?.includeRestricted,t?.includeAnonymous,t?.onlyAnonymous,t?.teamId],"serverApp.useUsers()"),i=r.items.map(t=>this._serverUserFromCrud(t));return i.nextCursor=r.pagination?.next_cursor??null,i}_serverPermissionFromCrud(t){return{id:t.id}}_serverTeamPermissionDefinitionFromCrud(t){return{id:t.id,description:t.description,containedPermissionIds:t.contained_permission_ids}}_serverProjectPermissionDefinitionFromCrud(t){return{id:t.id,description:t.description,containedPermissionIds:t.contained_permission_ids}}async getItem(t){if("userId"in t){let r=w.Result.orThrow(await this._serverUserItemsCache.getOrWait([t.userId,t.itemId],"write-only"));return this._serverItemFromCrud({type:"user",id:t.userId},r)}if("teamId"in t){let r=w.Result.orThrow(await this._serverTeamItemsCache.getOrWait([t.teamId,t.itemId],"write-only"));return this._serverItemFromCrud({type:"team",id:t.teamId},r)}{let r=w.Result.orThrow(await this._serverCustomItemsCache.getOrWait([t.customCustomerId,t.itemId],"write-only"));return this._serverItemFromCrud({type:"custom",id:t.customCustomerId},r)}}async listProducts(t){if("userId"in t){let r=w.Result.orThrow(await this._serverUserProductsCache.getOrWait([t.userId,t.cursor??null,t.limit??null],"write-only"));return this._customerProductsFromResponse(r)}if("teamId"in t){let r=w.Result.orThrow(await this._serverTeamProductsCache.getOrWait([t.teamId,t.cursor??null,t.limit??null],"write-only"));return this._customerProductsFromResponse(r)}let r=w.Result.orThrow(await this._serverCustomProductsCache.getOrWait([t.customCustomerId,t.cursor??null,t.limit??null],"write-only"));return this._customerProductsFromResponse(r)}useItem(t){let r,i,s;"userId"in t?(r="user",i=t.userId,s=this._serverUserItemsCache):"teamId"in t?(r="team",i=t.teamId,s=this._serverTeamItemsCache):(r="custom",i=t.customCustomerId,s=this._serverCustomItemsCache);let n=[i,t.itemId],a=(0,C.useAsyncCache)(s,n,"serverApp.useItem()");return(0,S.useMemo)(()=>this._serverItemFromCrud({type:r,id:i},a),[a])}async grantProduct(t){let r,i;"userId"in t?(r="user",i=t.userId):"teamId"in t?(r="team",i=t.teamId):(r="custom",i=t.customCustomerId),await this._interface.grantProduct({customerType:r,customerId:i,productId:"productId"in t?t.productId:void 0,product:"product"in t?t.product:void 0,quantity:t.quantity}),await ("user"===r?this._serverUserProductsCache:"team"===r?this._serverTeamProductsCache:this._serverCustomProductsCache).refresh([i,null,null])}async createTeam(t){let r=await this._interface.createServerTeam(J(t));return await this._serverTeamsCache.refreshWhere(()=>!0),this._serverTeamFromCrud(r)}async listTeams(t){let r=w.Result.orThrow(await this._serverTeamsCache.getOrWait([void 0,t?.orderBy,t?.desc,t?.cursor,t?.limit,t?.query],"write-only")),i=r.items.map(t=>this._serverTeamFromCrud(t));return i.nextCursor=r.pagination?.next_cursor??null,i}useTeams(t){let r=(0,C.useAsyncCache)(this._serverTeamsCache,[void 0,t?.orderBy,t?.desc,t?.cursor,t?.limit,t?.query],"serverApp.useTeams()");return(0,S.useMemo)(()=>{let t=r.items.map(t=>this._serverTeamFromCrud(t));return t.nextCursor=r.pagination?.next_cursor??null,t},[r])}async listTeamMemberPermissions(t,r){let i=r?.recursive??!1;return w.Result.orThrow(await this._serverAllTeamMemberPermissionsCache.getOrWait([t,i],"write-only")).map(t=>({userId:t.user_id,permissionId:t.id}))}useTeamMemberPermissions(t,r){let i=r?.recursive??!1,s=(0,C.useAsyncCache)(this._serverAllTeamMemberPermissionsCache,[t,i],"serverApp.useTeamMemberPermissions()");return(0,S.useMemo)(()=>s.map(t=>({userId:t.user_id,permissionId:t.id})),[s])}async getTeam(t){return"object"==typeof t&&"apiKey"in t?await this._getTeamByApiKey(t.apiKey):(await this.listTeams()).find(r=>r.id===t)??null}useTeam(t){if("object"==typeof t&&"apiKey"in t)return this._useTeamByApiKey(t.apiKey);{let r=this.useTeams();return(0,S.useMemo)(()=>r.find(r=>r.id===t)??null,[r,t])}}_createServerDataVaultStore(t){let r=t=>{if("string"!=typeof t.secret)throw Error("secret must be a string, got "+typeof t.secret)};return{id:t,setValue:async(i,s,n)=>{r(n),await this._interface.setDataVaultStoreValue(n.secret,t,i,s)},getValue:async(i,s)=>(r(s),w.Result.orThrow(await this._serverDataVaultStoreValueCache.getOrWait([t,i,s.secret],"write-only"))),useValue:(i,s)=>(r(s),(0,C.useAsyncCache)(this._serverDataVaultStoreValueCache,[t,i,s.secret],"store.useValue()"))}}async getDataVaultStore(t){return this._createServerDataVaultStore(t)}useDataVaultStore(t){return(0,S.useMemo)(()=>this._createServerDataVaultStore(t),[t])}async sendEmail(t){await this._interface.sendEmail(t),await this._emailDeliveryInfoCache.refresh([])}async getEmailDeliveryStats(){return w.Result.orThrow(await this._emailDeliveryInfoCache.getOrWait([],"write-only"))}useEmailDeliveryStats(){return(0,C.useAsyncCache)(this._emailDeliveryInfoCache,[],"hexclaveServerApp.useEmailDeliveryStats()")}async activateEmailCapacityBoost(){await this._interface.activateEmailCapacityBoost(),await this._emailDeliveryInfoCache.refresh([])}async _refreshSession(t){await Promise.all([super._refreshUser(t),this._currentServerUserCache.refresh([t])])}async _refreshUsers(){await Promise.all([super._refreshUsers(),this._serverUserCache.refreshWhere(()=>!0),this._serverUsersCache.refreshWhere(()=>!0),this._serverContactChannelsCache.refreshWhere(()=>!0),this._serverOAuthProvidersCache.refreshWhere(()=>!0),this._serverUserConnectedAccountsCache.refreshWhere(()=>!0)])}async createOAuthProvider(t){try{let r=await this._interface.createServerOAuthProvider({user_id:t.userId,provider_config_id:t.providerConfigId,account_id:t.accountId,email:t.email,allow_sign_in:t.allowSignIn,allow_connected_accounts:t.allowConnectedAccounts});return await Promise.all([this._serverOAuthProvidersCache.refresh([t.userId]),this._serverUserConnectedAccountsCache.refresh([t.userId])]),w.Result.ok(this._serverOAuthProviderFromCrud(r))}catch(t){if(P.KnownErrors.OAuthProviderAccountIdAlreadyUsedForSignIn.isInstance(t))return w.Result.error(t);throw t}}},tC=t.i(403600);function tI(t){let r=[],i=`/projects/${t.id}/domains`;for(let{domain:s}of(t.config.allow_localhost&&r.push({message:"Localhost is not allowed in production mode, turn off 'Allow localhost' in project settings",relativeFixUrl:i}),t.config.domains)){let n;try{let t=s.replace(/\*+/g,"wildcard-placeholder");n=new URL(t)}catch(n){(0,x.captureError)("production-mode-domain-not-valid",new x.HexclaveAssertionError("Domain was somehow not a valid URL; we should've caught this when setting the domain in the first place",{domain:s,projectId:t})),r.push({message:"Trusted domain is not a valid URL: "+s,relativeFixUrl:i});continue}(0,Q.isLocalhost)(n)?r.push({message:"Localhost domains are not allowed to be trusted in production mode: "+s,relativeFixUrl:i}):n.hostname.match(/^\d+(\.\d+)*$/)?r.push({message:"Direct IPs are not valid for trusted domains in production mode: "+s,relativeFixUrl:i}):"https:"!==n.protocol&&r.push({message:"Trusted domains should be HTTPS: "+s,relativeFixUrl:i})}return r}var tk=class extends tw{constructor(t,r){const i=(0,C.resolveConstructorOptions)(t),s=i.publishableClientKey??(0,C.getDefaultPublishableClientKey)();super(i,{...r,interface:r?.interface??(()=>{let t=(0,C.resolveApiUrls)(i.baseUrl);return new tC.HexclaveAdminInterface({getBaseUrl:()=>t()[0],getApiUrls:t,projectId:i.projectId??(0,C.getDefaultProjectId)(),extraRequestHeaders:i.extraRequestHeaders??(0,C.getDefaultExtraRequestHeaders)(),clientVersion:C.clientVersion,...i.projectOwnerSession?{projectOwnerSession:i.projectOwnerSession}:{...s?{publishableClientKey:s}:{},secretServerKey:i.secretServerKey??(0,C.getDefaultSecretServerKey)(),superSecretAdminKey:i.superSecretAdminKey??(0,C.getDefaultSuperSecretAdminKey)()}})})()}),this._adminProjectCache=(0,C.createCache)(async()=>await this._interface.getProject()),this._internalApiKeysCache=(0,C.createCache)(async()=>await this._interface.listInternalApiKeys()),this._adminEmailThemeCache=(0,C.createCache)(async([t])=>await this._interface.getEmailTheme(t)),this._adminEmailThemesCache=(0,C.createCache)(async()=>await this._interface.listEmailThemes()),this._adminEmailTemplatesCache=(0,C.createCache)(async()=>await this._interface.listInternalEmailTemplates()),this._adminEmailDraftsCache=(0,C.createCache)(async()=>await this._interface.listInternalEmailDrafts()),this._adminTeamPermissionDefinitionsCache=(0,C.createCache)(async()=>await this._interface.listTeamPermissionDefinitions()),this._adminProjectPermissionDefinitionsCache=(0,C.createCache)(async()=>await this._interface.listProjectPermissionDefinitions()),this._svixTokenCache=(0,C.createCache)(async()=>await this._interface.getSvixToken()),this._metricsCache=(0,C.createCache)(async([t,r])=>{let i=r?Object.fromEntries(new URLSearchParams(r)):void 0;return await this._interface.getMetrics(t,i)}),this._userActivityCache=(0,C.createCache)(async([t])=>await this._interface.getUserActivity(t)),this._metricsUserCountsCache=(0,C.createCache)(async()=>await this._interface.getMetricsUserCounts()),this._emailPreviewCache=(0,C.createCache)(async([t,r,i,s])=>await this._interface.renderEmailPreview({themeId:t,themeTsxSource:r,templateId:i,templateTsxSource:s})),this._emailPreviewWithEditableMarkersCache=(0,C.createCache)(async([t,r,i,s,n])=>await this._interface.renderEmailPreview({themeId:t,themeTsxSource:r,templateId:i,templateTsxSource:s,editableMarkers:!0,editableSource:n})),this._configOverridesCache=(0,C.createCache)(async()=>await this._interface.getConfig()),this._stripeAccountInfoCache=(0,C.createCache)(async()=>{try{return await this._interface.getStripeAccountInfo()}catch(t){if(t?.status===404)return null;throw t}}),this._transactionsCache=(0,C.createCache)(async([t,r,i,s,n])=>await this._interface.listTransactions({cursor:t,limit:r,type:i,customerType:s,customerId:n}))}_adminConfigFromCrud(t){return JSON.parse(t.config_string)}_adminOwnedProjectFromCrud(t,r){if(null!==this._tokenStoreInit)throw new x.HexclaveAssertionError("Owned apps must always have tokenStore === null — did you not create this project with app._createOwnedApp()?");return{...this._adminProjectFromCrud(t,r),app:this}}_adminProjectFromCrud(t,r){if(t.id!==this.projectId)throw new x.HexclaveAssertionError(`The project ID of the provided project JSON (${t.id}) does not match the project ID of the app (${this.projectId})!`);let i=this;return{id:t.id,displayName:t.display_name,description:t.description,createdAt:new Date(t.created_at_millis),isProductionMode:t.is_production_mode,isDevelopmentEnvironment:t.is_development_environment,ownerTeamId:t.owner_team_id,onboardingStatus:t.onboarding_status,logoUrl:t.logo_url,logoFullUrl:t.logo_full_url,logoDarkModeUrl:t.logo_dark_mode_url,logoFullDarkModeUrl:t.logo_full_dark_mode_url,config:{signUpEnabled:t.config.sign_up_enabled,credentialEnabled:t.config.credential_enabled,magicLinkEnabled:t.config.magic_link_enabled,passkeyEnabled:t.config.passkey_enabled,clientTeamCreationEnabled:t.config.client_team_creation_enabled,clientUserDeletionEnabled:t.config.client_user_deletion_enabled,allowLocalhost:t.config.allow_localhost,oauthAccountMergeStrategy:t.config.oauth_account_merge_strategy,allowUserApiKeys:t.config.allow_user_api_keys,allowTeamApiKeys:t.config.allow_team_api_keys,oauthProviders:t.config.oauth_providers.map(t=>"shared"===t.type?{id:t.id,type:"shared"}:{id:t.id,type:"standard",clientId:t.client_id??(0,x.throwErr)("Client ID is missing"),clientSecret:t.client_secret??(0,x.throwErr)("Client secret is missing"),facebookConfigId:t.facebook_config_id,microsoftTenantId:t.microsoft_tenant_id,appleBundleIds:t.apple_bundle_ids}),emailConfig:"shared"===t.config.email_config.type?{type:"shared"}:{type:"standard",host:t.config.email_config.host??(0,x.throwErr)("Email host is missing"),port:t.config.email_config.port??(0,x.throwErr)("Email port is missing"),username:t.config.email_config.username??(0,x.throwErr)("Email username is missing"),password:t.config.email_config.password??(0,x.throwErr)("Email password is missing"),senderName:t.config.email_config.sender_name??(0,x.throwErr)("Email sender name is missing"),senderEmail:t.config.email_config.sender_email??(0,x.throwErr)("Email sender email is missing")},emailTheme:t.config.email_theme,domains:t.config.domains.map(t=>({domain:t.domain,handlerPath:t.handler_path})),createTeamOnSignUp:t.config.create_team_on_sign_up,teamCreatorDefaultPermissions:t.config.team_creator_default_permissions,teamMemberDefaultPermissions:t.config.team_member_default_permissions,userDefaultPermissions:t.config.user_default_permissions},getConfig:async()=>i._adminConfigFromCrud(await i._interface.getConfig()),useConfig(){let t=(0,C.useAsyncCache)(i._configOverridesCache,[],"project.useConfig()");return(0,S.useMemo)(()=>i._adminConfigFromCrud(t),[t])},async updateConfig(t){await i._interface.updateConfigOverride("environment",t),await i._refreshProjectConfig()},async pushConfig(t,r){var s;await i._interface.setConfigOverride("branch",t,"pushed-from-github"===(s=r.source).type?{type:"pushed-from-github",owner:s.owner,repo:s.repo,branch:s.branch,commit_hash:s.commitHash,config_file_path:s.configFilePath,workflow_path:s.workflowPath}:s),await i._refreshProjectConfig()},async updatePushedConfig(t){await i._interface.updateConfigOverride("branch",t),await i._refreshProjectConfig()},getPushedConfigSource:async()=>{var t;return"pushed-from-github"===(t=await i._interface.getPushedConfigSource()).type?{type:"pushed-from-github",owner:t.owner,repo:t.repo,branch:t.branch,commitHash:t.commit_hash,configFilePath:t.config_file_path,workflowPath:t.workflow_path}:t},async unlinkPushedConfigSource(){await i._interface.unlinkPushedConfigSource(),await i._refreshProjectConfig()},async resetConfigOverrideKeys(t,r){await i._interface.resetConfigOverrideKeys(t,r),await i._refreshProjectConfig()},getConfigOverride:async t=>JSON.parse((await i._interface.getConfigOverride(t)).config_string),async replaceConfigOverride(t,r){if("branch"===t){let s=await i._interface.getPushedConfigSource();await i._interface.setConfigOverride(t,r,s)}else await i._interface.setConfigOverride(t,r);await i._refreshProjectConfig()},async update(t){let{requirePublishableClientKey:s,...n}=t,a=en(n),o=!!a.config&&(0,z.typedValues)(a.config).some(t=>void 0!==t);(0,z.typedEntries)(a).some(([t,r])=>"config"===t?o:void 0!==r)&&(await i._interface.updateProject(a),await r()),void 0!==s&&(await i._interface.updateConfigOverride("project",{"project.requirePublishableClientKey":s}),await i._refreshProjectConfig())},async delete(){await i._interface.deleteProject()},getProductionModeErrors:async()=>tI(t),useProductionModeErrors:()=>tI(t)}}_adminEmailTemplateFromCrud(t){return{type:t.type,subject:t.subject,content:t.content,isDefault:t.is_default}}async getProject(){return this._adminProjectFromCrud(w.Result.orThrow(await this._adminProjectCache.getOrWait([],"write-only")),()=>this._refreshProject())}useProject(){let t=(0,C.useAsyncCache)(this._adminProjectCache,[],"adminApp.useProject()");return(0,S.useMemo)(()=>this._adminProjectFromCrud(t,()=>this._refreshProject()),[t])}_createInternalApiKeyBaseFromCrud(t){let r=this;return{id:t.id,description:t.description,expiresAt:new Date(t.expires_at_millis),manuallyRevokedAt:t.manually_revoked_at_millis?new Date(t.manually_revoked_at_millis):null,createdAt:new Date(t.created_at_millis),isValid(){return null===this.whyInvalid()},whyInvalid(){return this.expiresAt.getTime()<Date.now()?"expired":this.manuallyRevokedAt?"manually-revoked":null},async revoke(){let i=await r._interface.revokeInternalApiKeyById(t.id);return await r._refreshInternalApiKeys(),i}}}_createInternalApiKeyFromCrud(t){return{...this._createInternalApiKeyBaseFromCrud(t),publishableClientKey:t.publishable_client_key?{lastFour:t.publishable_client_key.last_four}:null,secretServerKey:t.secret_server_key?{lastFour:t.secret_server_key.last_four}:null,superSecretAdminKey:t.super_secret_admin_key?{lastFour:t.super_secret_admin_key.last_four}:null}}_createInternalApiKeyFirstViewFromCrud(t){return{...this._createInternalApiKeyBaseFromCrud(t),publishableClientKey:t.publishable_client_key,secretServerKey:t.secret_server_key,superSecretAdminKey:t.super_secret_admin_key}}async listInternalApiKeys(){return w.Result.orThrow(await this._internalApiKeysCache.getOrWait([],"write-only")).map(t=>this._createInternalApiKeyFromCrud(t))}useInternalApiKeys(){let t=(0,C.useAsyncCache)(this._internalApiKeysCache,[],"adminApp.useInternalApiKeys()");return(0,S.useMemo)(()=>t.map(t=>this._createInternalApiKeyFromCrud(t)),[t])}async createInternalApiKey(t){let r=await this._interface.createInternalApiKey({description:t.description,expires_at_millis:t.expiresAt.getTime(),has_publishable_client_key:t.hasPublishableClientKey,has_secret_server_key:t.hasSecretServerKey,has_super_secret_admin_key:t.hasSuperSecretAdminKey});return await this._refreshInternalApiKeys(),this._createInternalApiKeyFirstViewFromCrud(r)}useEmailThemes(){let t=(0,C.useAsyncCache)(this._adminEmailThemesCache,[],"adminApp.useEmailThemes()");return(0,S.useMemo)(()=>t.map(t=>({id:t.id,displayName:t.display_name})),[t])}useEmailTemplates(){let t=(0,C.useAsyncCache)(this._adminEmailTemplatesCache,[],"adminApp.useEmailTemplates()");return(0,S.useMemo)(()=>t.map(t=>({id:t.id,displayName:t.display_name,themeId:t.theme_id,tsxSource:t.tsx_source})),[t])}useEmailDrafts(){let t=(0,C.useAsyncCache)(this._adminEmailDraftsCache,[],"adminApp.useEmailDrafts()");return(0,S.useMemo)(()=>t.map(t=>({id:t.id,displayName:t.display_name,themeId:t.theme_id,tsxSource:t.tsx_source,sentAt:t.sent_at_millis?new Date(t.sent_at_millis):null})),[t])}async listEmailThemes(){return w.Result.orThrow(await this._adminEmailThemesCache.getOrWait([],"write-only")).map(t=>({id:t.id,displayName:t.display_name}))}async listEmailTemplates(){return w.Result.orThrow(await this._adminEmailTemplatesCache.getOrWait([],"write-only")).map(t=>({id:t.id,displayName:t.display_name,themeId:t.theme_id,tsxSource:t.tsx_source}))}async listEmailDrafts(){return w.Result.orThrow(await this._adminEmailDraftsCache.getOrWait([],"write-only")).map(t=>({id:t.id,displayName:t.display_name,themeId:t.theme_id,tsxSource:t.tsx_source,sentAt:t.sent_at_millis?new Date(t.sent_at_millis):null}))}async createTeamPermissionDefinition(t){let r=await this._interface.createTeamPermissionDefinition({id:t.id,description:t.description,contained_permission_ids:t.containedPermissionIds});return await this._adminTeamPermissionDefinitionsCache.refresh([]),this._serverTeamPermissionDefinitionFromCrud(r)}async updateTeamPermissionDefinition(t,r){await this._interface.updateTeamPermissionDefinition(t,{description:r.description,contained_permission_ids:r.containedPermissionIds}),await this._adminTeamPermissionDefinitionsCache.refresh([])}async deleteTeamPermissionDefinition(t){await this._interface.deleteTeamPermissionDefinition(t),await this._adminTeamPermissionDefinitionsCache.refresh([])}async listTeamPermissionDefinitions(){return w.Result.orThrow(await this._adminTeamPermissionDefinitionsCache.getOrWait([],"write-only")).map(t=>this._serverTeamPermissionDefinitionFromCrud(t))}async listTeamPermissionDefinitionsPaginated(t){let r=await this._interface.listTeamPermissionDefinitionsPaginated(t);return{items:r.items.map(t=>this._serverTeamPermissionDefinitionFromCrud(t)),nextCursor:r.nextCursor}}useTeamPermissionDefinitions(){let t=(0,C.useAsyncCache)(this._adminTeamPermissionDefinitionsCache,[],"adminApp.useTeamPermissionDefinitions()");return(0,S.useMemo)(()=>t.map(t=>this._serverTeamPermissionDefinitionFromCrud(t)),[t])}async createProjectPermissionDefinition(t){let r=await this._interface.createProjectPermissionDefinition({id:t.id,description:t.description,contained_permission_ids:t.containedPermissionIds});return await this._adminProjectPermissionDefinitionsCache.refresh([]),this._serverProjectPermissionDefinitionFromCrud(r)}async updateProjectPermissionDefinition(t,r){await this._interface.updateProjectPermissionDefinition(t,{description:r.description,contained_permission_ids:r.containedPermissionIds}),await this._adminProjectPermissionDefinitionsCache.refresh([])}async deleteProjectPermissionDefinition(t){await this._interface.deleteProjectPermissionDefinition(t),await this._adminProjectPermissionDefinitionsCache.refresh([])}async listProjectPermissionDefinitions(){return w.Result.orThrow(await this._adminProjectPermissionDefinitionsCache.getOrWait([],"write-only")).map(t=>this._serverProjectPermissionDefinitionFromCrud(t))}useProjectPermissionDefinitions(){let t=(0,C.useAsyncCache)(this._adminProjectPermissionDefinitionsCache,[],"adminApp.useProjectPermissionDefinitions()");return(0,S.useMemo)(()=>t.map(t=>this._serverProjectPermissionDefinitionFromCrud(t)),[t])}useSvixToken(){let t=(0,C.useAsyncCache)(this._svixTokenCache,[],"adminApp.useSvixToken()");return{token:t.token,url:t.url}}async _refreshProject(){await Promise.all([super._refreshProject(),this._adminProjectCache.refresh([])])}async _refreshProjectConfig(){await Promise.all([this._configOverridesCache.refresh([]),this._adminProjectCache.refresh([])])}async _refreshInternalApiKeys(){await this._internalApiKeysCache.refresh([])}async _refreshUsers(){await Promise.all([super._refreshUsers(),this._metricsCache.refreshWhere(()=>!0),this._metricsUserCountsCache.refresh([])])}get[es.hexclaveAppInternalsSymbol](){return{...super[es.hexclaveAppInternalsSymbol],useMetrics:(t=!1,r)=>{let i=(()=>{if(null==r)return"";let t=new URLSearchParams;for(let i of["browser","country_code","device","os","referrer","since","until"]){let s=r[i];null!=s&&t.set(i,s)}return t.toString()})();return(0,C.useAsyncCache)(this._metricsCache,[t,i],"adminApp.useMetrics()")},useUserActivity:t=>(0,C.useAsyncCache)(this._userActivityCache,[t],"adminApp.useUserActivity()"),useMetricsUserCounts:()=>(0,C.useAsyncCache)(this._metricsUserCountsCache,[],"adminApp.useMetricsUserCounts()")}}async sendTestEmail(t){let r;try{r=await this._interface.sendTestEmail({recipient_email:t.recipientEmail,email_config:{...(0,z.pick)(t.emailConfig,["host","port","username","password"]),sender_email:t.emailConfig.senderEmail,sender_name:t.emailConfig.senderName}})}catch(t){if(t instanceof P.KnownErrors.ItemQuantityInsufficientAmount)return w.Result.error({errorMessage:"Monthly email sending limit exceeded for your plan. Please upgrade your plan or wait until next month before sending more test emails."});throw t}return r.success?w.Result.ok(void 0):w.Result.error({errorMessage:r.error_message??(0,x.throwErr)("Email test error not specified")})}async sendTestWebhook(t){let r=await this._interface.sendTestWebhook({endpoint_id:t.endpointId});return r.success?w.Result.ok(void 0):w.Result.error({errorMessage:r.error_message??(0,x.throwErr)("Webhook test error not specified")})}async listSentEmails(){return(await this._interface.listSentEmails()).items.map(t=>({id:t.id,to:t.to??[],subject:t.subject,recipient:t.to?.[0]??"",sentAt:new Date(t.sent_at_millis),error:t.error}))}async setupManagedEmailProvider(t){let r=await this._interface.setupManagedEmailProvider({subdomain:t.subdomain,sender_local_part:t.senderLocalPart});return{domainId:r.domain_id,subdomain:r.subdomain,senderLocalPart:r.sender_local_part,nameServerRecords:r.name_server_records,status:r.status}}async checkManagedEmailStatus(t){return{status:(await this._interface.checkManagedEmailStatus({domain_id:t.domainId,subdomain:t.subdomain,sender_local_part:t.senderLocalPart})).status}}async listManagedEmailDomains(){return(await this._interface.listManagedEmailDomains()).items.map(t=>({domainId:t.domain_id,subdomain:t.subdomain,senderLocalPart:t.sender_local_part,status:t.status,nameServerRecords:t.name_server_records}))}async applyManagedEmailProvider(t){let r=await this._interface.applyManagedEmailProvider({domain_id:t.domainId});return await this._refreshProjectConfig(),r}async deleteManagedEmailDomain(t){return await this._interface.deleteManagedEmailDomain({resend_domain_id:t.resendDomainId})}async sendSignInInvitationEmail(t,r){await this._interface.sendSignInInvitationEmail(t,r)}async createEmailTemplate(t){let r=await this._interface.createEmailTemplate(t);return await this._adminEmailTemplatesCache.refresh([]),r}async deleteEmailTemplate(t){await this._interface.deleteEmailTemplate(t),await this._adminEmailTemplatesCache.refresh([])}async createEmailDraft(t){let r=await this._interface.createEmailDraft({display_name:t.displayName,theme_id:t.themeId,tsx_source:t.tsxSource});return await this._adminEmailDraftsCache.refresh([]),r}async updateEmailDraft(t,r){await this._interface.updateEmailDraft(t,{display_name:r.displayName,theme_id:r.themeId,tsx_source:r.tsxSource}),await this._adminEmailDraftsCache.refresh([])}async deleteEmailDraft(t){await this._interface.deleteEmailDraft(t);let r=this._adminEmailDraftsCache.getIfCached([]);"ok"===r.status&&"ok"===r.data.status&&this._adminEmailDraftsCache.forceSetCachedValue([],w.Result.ok(r.data.data.filter(r=>r.id!==t))),await this._adminEmailDraftsCache.refresh([])}async refreshEmailDrafts(){await this._adminEmailDraftsCache.refresh([])}async saveChatMessage(t,r){await this._interface.saveChatMessage(t,r)}async listChatMessages(t){return await this._interface.listChatMessages(t)}async rewriteTemplateSourceWithAI(t){return{tsxSource:(await this._interface.rewriteTemplateSourceWithAI(t)).tsx_source}}async createEmailTheme(t){let r=await this._interface.createEmailTheme(t);return await this._adminEmailThemesCache.refresh([]),r}async getEmailPreview(t){return(await this._interface.renderEmailPreview(t)).html}useEmailPreview(t){return(0,C.useAsyncCache)(this._emailPreviewCache,[t.themeId,t.themeTsxSource,t.templateId,t.templateTsxSource],"adminApp.useEmailPreview()").html}async getEmailPreviewWithEditableMarkers(t){let r=await this._interface.renderEmailPreview({...t,editableMarkers:!0,editableSource:t.editableSource});return{html:r.html,editableRegions:r.editable_regions}}useEmailPreviewWithEditableMarkers(t){let r=(0,C.useAsyncCache)(this._emailPreviewWithEditableMarkersCache,[t.themeId,t.themeTsxSource,t.templateId,t.templateTsxSource,t.editableSource],"adminApp.useEmailPreviewWithEditableMarkers()");return{html:r.html,editableRegions:r.editable_regions}}useEmailTheme(t){let r=(0,C.useAsyncCache)(this._adminEmailThemeCache,[t],"adminApp.useEmailTheme()");return{displayName:r.display_name,tsxSource:r.tsx_source}}async updateEmailTheme(t,r){await this._interface.updateEmailTheme(t,r),await this._adminEmailThemesCache.refresh([]),await this._adminEmailThemeCache.invalidate([t])}async deleteEmailTheme(t){await this._interface.deleteEmailTheme(t),await this._adminEmailThemesCache.refresh([]),await this._adminEmailThemeCache.invalidate([t])}async updateEmailTemplate(t,r,i){let s=await this._interface.updateEmailTemplate(t,r,i);return await this._adminEmailTemplatesCache.refresh([]),{renderedHtml:s.rendered_html}}async setupPayments(){let t=await this._interface.setupPayments();return await this._stripeAccountInfoCache.refresh([]),t}async createStripeWidgetAccountSession(){return await this._interface.createStripeWidgetAccountSession()}async getPaymentMethodConfigs(){return await this._interface.getPaymentMethodConfigs()}async updatePaymentMethodConfigs(t,r){await this._interface.updatePaymentMethodConfigs(t,r)}async createItemQuantityChange(t){await this._interface.updateItemQuantity({itemId:t.itemId,..."userId"in t?{userId:t.userId}:"teamId"in t?{teamId:t.teamId}:{customCustomerId:t.customCustomerId}},{delta:t.quantity,expires_at:t.expiresAt,description:t.description,allow_negative:!0})}async refundTransaction(t){let r=await this._interface.refundTransaction({type:t.type,id:t.id,invoiceId:t.invoiceId,amountUsd:t.amountUsd,endAction:t.endAction});return await this._transactionsCache.invalidateWhere(()=>!0),{refundTransactionId:r.refundTransactionId}}async listTransactions(t){return w.Result.orThrow(await this._transactionsCache.getOrWait([t.cursor,t.limit,t.type,t.customerType,t.customerId],"write-only"))}_emailOutboxCrudToAdmin(t){let r,i=t.to;r="user-primary-email"===i.type?{type:"user-primary-email",userId:i.user_id}:"user-custom-emails"===i.type?{type:"user-custom-emails",userId:i.user_id,emails:i.emails}:{type:"custom-emails",emails:i.emails};let s={id:t.id,createdAt:new Date(t.created_at_millis),updatedAt:new Date(t.updated_at_millis),tsxSource:t.tsx_source,themeId:t.theme_id??null,to:r,scheduledAt:new Date(t.scheduled_at_millis),createdWith:t.created_with,emailDraftId:t.email_draft_id,emailProgrammaticCallTemplateId:t.email_programmatic_call_template_id,variables:t.variables??{},isPaused:!1,hasRendered:!1,hasDelivered:!1,sendRetries:t.send_retries,nextSendRetryAt:t.next_send_retry_at_millis?new Date(t.next_send_retry_at_millis):null,sendAttemptErrors:t.send_attempt_errors?t.send_attempt_errors.map(t=>({attemptNumber:t.attempt_number,timestamp:t.timestamp,externalMessage:t.external_message,externalDetails:t.external_details,internalMessage:t.internal_message,internalDetails:t.internal_details})):null},n=t.has_rendered?{...s,startedRenderingAt:new Date(t.started_rendering_at_millis),renderedAt:new Date(t.rendered_at_millis),subject:t.subject,html:t.html,text:t.text,isTransactional:t.is_transactional,isHighPriority:t.is_high_priority,notificationCategoryId:t.notification_category_id,hasRendered:!0}:null,a=n&&t.started_sending_at_millis?{...n,startedSendingAt:new Date(t.started_sending_at_millis)}:null,o=a&&t.has_delivered?{...a,deliveredAt:new Date(t.delivered_at_millis),hasDelivered:!0}:null;switch(t.status){case"paused":return{...s,status:"paused",simpleStatus:"in-progress",isPaused:!0};case"preparing":return{...s,status:"preparing",simpleStatus:"in-progress"};case"rendering":return{...s,status:"rendering",simpleStatus:"in-progress",startedRenderingAt:new Date(t.started_rendering_at_millis)};case"render-error":return{...s,status:"render-error",simpleStatus:"error",startedRenderingAt:new Date(t.started_rendering_at_millis),renderedAt:new Date(t.rendered_at_millis),renderError:t.render_error};case"scheduled":return{...n,status:"scheduled",simpleStatus:"in-progress"};case"queued":return{...n,status:"queued",simpleStatus:"in-progress"};case"sending":return{...a,status:"sending",simpleStatus:"in-progress"};case"server-error":return{...a,status:"server-error",simpleStatus:"error",errorAt:new Date(t.error_at_millis),serverError:t.server_error};case"skipped":return{...s,status:"skipped",simpleStatus:"ok",skippedAt:new Date(t.skipped_at_millis),skippedReason:t.skipped_reason,skippedDetails:t.skipped_details??{},hasRendered:t.has_rendered,startedRenderingAt:t.started_rendering_at_millis?new Date(t.started_rendering_at_millis):void 0,renderedAt:t.rendered_at_millis?new Date(t.rendered_at_millis):void 0,subject:t.subject,html:t.html,text:t.text,isTransactional:t.is_transactional,isHighPriority:t.is_high_priority,notificationCategoryId:t.notification_category_id,startedSendingAt:t.started_sending_at_millis?new Date(t.started_sending_at_millis):void 0};case"bounced":return{...a,status:"bounced",simpleStatus:"error",bouncedAt:new Date(t.bounced_at_millis)};case"delivery-delayed":return{...a,status:"delivery-delayed",simpleStatus:"ok",deliveryDelayedAt:new Date(t.delivery_delayed_at_millis)};case"sent":return{...o,status:"sent",simpleStatus:"ok",canHaveDeliveryInfo:t.can_have_delivery_info};case"opened":return{...o,status:"opened",simpleStatus:"ok",openedAt:new Date(t.opened_at_millis),canHaveDeliveryInfo:!0};case"clicked":return{...o,status:"clicked",simpleStatus:"ok",clickedAt:new Date(t.clicked_at_millis),canHaveDeliveryInfo:!0};case"marked-as-spam":return{...o,status:"marked-as-spam",simpleStatus:"ok",markedAsSpamAt:new Date(t.marked_as_spam_at_millis),canHaveDeliveryInfo:!0};default:throw new x.HexclaveAssertionError(`Unknown email outbox status: ${t.status}`,{status:t.status})}}async listOutboxEmails(t){let r=await this._interface.listOutboxEmails({status:t?.status,simple_status:t?.simpleStatus,limit:t?.limit,cursor:t?.cursor});return{items:r.items.map(t=>this._emailOutboxCrudToAdmin(t)),nextCursor:r.pagination?.next_cursor??null}}async getOutboxEmail(t){let r=await this._interface.getOutboxEmail(t);return this._emailOutboxCrudToAdmin(r)}async updateOutboxEmail(t,r){let i=await this._interface.updateOutboxEmail(t,{is_paused:r.isPaused,scheduled_at_millis:r.scheduledAtMillis,cancel:r.cancel,tsx_source:r.tsxSource,theme_id:r.themeId});return this._emailOutboxCrudToAdmin(i)}async pauseOutboxEmail(t){return await this.updateOutboxEmail(t,{isPaused:!0})}async unpauseOutboxEmail(t){return await this.updateOutboxEmail(t,{isPaused:!1})}async cancelOutboxEmail(t){return await this.updateOutboxEmail(t,{cancel:!0})}useTransactions(t){return(0,C.useAsyncCache)(this._transactionsCache,[t.cursor,t.limit,t.type,t.customerType,t.customerId],"adminApp.useTransactions()")}async getStripeAccountInfo(){return await this._interface.getStripeAccountInfo()}useStripeAccountInfo(){return(0,C.useAsyncCache)(this._stripeAccountInfoCache,[],"adminApp.useStripeAccountInfo()")}async queryAnalytics(t){return await this._interface.queryAnalytics(t)}async getAnalyticsClickmap(t){return await this._interface.getAnalyticsClickmap({kind:t.kind,member_user_ids:t.memberUserIds,route_path:t.routePath,route_regex:t.routeRegex,url_pattern:t.urlPattern,user_id:t.userId,replay_id:t.replayId,device:t.device,viewport_width_min:t.viewportWidthMin,viewport_width_max:t.viewportWidthMax,sampling:t.sampling,since:t.since,until:t.until})}async createAnalyticsClickmapToken(t){return await this._interface.createAnalyticsClickmapToken(t)}async listSessionReplays(t){let r=await this._interface.listSessionReplays({cursor:t?.cursor,limit:t?.limit,user_ids:t?.userIds,team_ids:t?.teamIds,duration_ms_min:t?.durationMsMin,duration_ms_max:t?.durationMsMax,last_event_at_from_millis:t?.lastEventAtFromMillis,last_event_at_to_millis:t?.lastEventAtToMillis,click_count_min:t?.clickCountMin});return{items:r.items.map(t=>({id:t.id,projectUser:{id:t.project_user.id,displayName:t.project_user.display_name,primaryEmail:t.project_user.primary_email},startedAt:new Date(t.started_at_millis),lastEventAt:new Date(t.last_event_at_millis),chunkCount:t.chunk_count,eventCount:t.event_count})),nextCursor:r.pagination.next_cursor}}async getSessionReplay(t){let r=await this._interface.getSessionReplay(t);return{id:r.id,projectUser:{id:r.project_user.id,displayName:r.project_user.display_name,primaryEmail:r.project_user.primary_email},startedAt:new Date(r.started_at_millis),lastEventAt:new Date(r.last_event_at_millis),chunkCount:r.chunk_count,eventCount:r.event_count}}async listSessionReplayChunks(t,r){let i=await this._interface.listSessionReplayChunks(t,{cursor:r?.cursor,limit:r?.limit});return{items:i.items.map(t=>({id:t.id,batchId:t.batch_id,sessionReplaySegmentId:t.session_replay_segment_id,browserSessionId:t.browser_session_id,eventCount:t.event_count,byteLength:t.byte_length,firstEventAt:new Date(t.first_event_at_millis),lastEventAt:new Date(t.last_event_at_millis),createdAt:new Date(t.created_at_millis)})),nextCursor:i.pagination.next_cursor}}async getSessionReplayChunkEvents(t,r){return await this._interface.getSessionReplayChunkEvents(t,r)}async getSessionReplayEvents(t,r){let i=await this._interface.getSessionReplayEvents(t,r);return{chunks:i.chunks.map(t=>({id:t.id,batchId:t.batch_id,sessionReplaySegmentId:t.session_replay_segment_id,eventCount:t.event_count,byteLength:t.byte_length,firstEventAt:new Date(t.first_event_at_millis),lastEventAt:new Date(t.last_event_at_millis),createdAt:new Date(t.created_at_millis)})),chunkEvents:i.chunk_events.map(t=>({chunkId:t.chunk_id,events:t.events}))}}async previewAffectedUsersByOnboardingChange(t,r){let i=await this._interface.previewAffectedUsersByOnboardingChange({require_email_verification:t.requireEmailVerification},r);return{affectedUsers:i.affected_users.map(t=>({id:t.id,displayName:t.display_name,primaryEmail:t.primary_email,restrictedReason:t.restricted_reason})),totalAffectedCount:i.total_affected_count}}};let{_HexclaveAdminAppImpl:tN,_HexclaveClientAppImpl:tO,_HexclaveServerAppImpl:tD}=(tA.LazyStackAdminAppImpl.value=tk,{_HexclaveAdminAppImpl:eo(tk),_HexclaveClientAppImpl:eo(tA),_HexclaveServerAppImpl:eo(tw)});function tj(t){return void 0===tL(t)}function tL(t,r={}){let i=r.configName??"config";if(null===t||"object"!=typeof t)return`${i} must be a non-null object`;for(let[r,s]of Object.entries(t)){if(void 0===s)continue;if("string"!=typeof r)return`${i} must have only string keys (found: ${typeof r})`;if(!r.match(/^[a-zA-Z0-9_:$][a-zA-Z_:$0-9\-]*(?:\.[a-zA-Z0-9_:$][a-zA-Z_:$0-9\-]*)*$/))return`All keys of ${i} must consist of only alphanumeric characters, dots, underscores, colons, dollar signs, or hyphens and start with a character other than a hyphen (found: ${r})`;let t=function t(r,i={}){let s=i.valueName??"value";switch(typeof r){case"string":case"number":case"boolean":break;case"object":if(null===r);else if(Array.isArray(r))for(let[i,n]of r.entries()){let r=`${s}[${i}]`;if(null===n)return`${r} is null; tuple elements cannot be null`;let a=t(n,{valueName:r});if(a)return a}else{let t=tL(r,{configName:s});if(t)return t}break;default:return`${s} has an invalid value type ${typeof r} (value: ${r})`}}(s,{valueName:`${i}.${r}`});if(t)return t}}function tR(t){let r=tL(t);if(r)throw new x.HexclaveAssertionError(`Invalid config: ${r}`,{c:t})}function tM(t,...r){if(0===r.length)return t;if(r.length>1)return tM(tM(t,r[0]),...r.slice(1));let i=r[0];tR(t),tR(i);let s=t;for(let t of Object.keys((0,z.filterUndefined)(i)))s=Object.fromEntries(Object.entries(s).filter(([r])=>r!==t&&!r.startsWith(t+".")));return{...s,...(0,z.filterUndefined)(i)}}var tF=class extends Error{constructor(...t){super(...t)}};function tB(t,r={}){tR(t);let i=r.onDotIntoNonObject??"throw",s=r.onDotIntoNull??"like-non-object",n=t=>t.match(/\./g)?.length??0,a={},o=Object.keys(t).sort((t,r)=>n(t)-n(r));i:for(let n of o){var l,p,u,c;let o=n.split("."),d=o.pop()??(0,x.throwErr)("split returns empty array?"),h=(0,z.get)(t,n);if(void 0===h)continue;let f=a;for(let t of o){if(!(0,z.hasAndNotUndefined)(f,t))switch("like-non-object"===s?i:s){case"throw":throw new tF(`Tried to use dot notation to access ${JSON.stringify(n)}, but ${JSON.stringify(t)} doesn't exist on the object (or is null).`);case"ignore":r.droppedKeys?.push(n);continue i;case"empty-object":(0,z.set)(f,t,{})}let a=(0,z.get)(f,t);if("object"!=typeof a)switch(i){case"throw":throw new tF(`Tried to use dot notation to access ${JSON.stringify(n)}, but ${JSON.stringify(t)} is not an object.`);case"ignore":r.droppedKeys?.push(n);continue i}f=a}l=f,p=d,u=h,c=r,null===u?(0,z.hasAndNotUndefined)(l,p)&&(0,z.deleteKey)(l,p):(0,z.set)(l,p,function t(r,i){if(null===r)throw new tF("Tried to normalize a null value");return Array.isArray(r)?r.map(r=>t(r,i)):"object"==typeof r?tB(r,i):r}(u,c))}return a}tF.prototype.name="NormalizationError",t.s(["isValidConfig",0,tj,"normalize",0,tB,"override",0,tM],653002);var tU=t.i(254799),t$=t.i(522734),tV=t.i(814747),tK=t.i(258062),tq=t.i(103749),tz=t.i(640923);function tW(t,r){if(""===t.trim())return{};for(let i of tq.parse(t,{sourceType:"module",plugins:["typescript","importAttributes"]}).program.body)if(tz.isExportNamedDeclaration(i)&&tz.isVariableDeclaration(i.declaration)){for(let t of i.declaration.declarations)if(tz.isIdentifier(t.id)&&"config"===t.id.name){if(null==t.init||!tz.isExpression(t.init))throw Error(`Config export in ${r} must have an initializer.`);return function t(r){let i=function t(r){return tz.isTSAsExpression(r)||tz.isTSSatisfiesExpression(r)||tz.isTSTypeAssertion(r)||tz.isTSNonNullExpression(r)?t(r.expression):r}(r);if(tz.isStringLiteral(i)||tz.isBooleanLiteral(i)||tz.isNumericLiteral(i))return i.value;if(tz.isNullLiteral(i))return null;if(!tz.isIdentifier(i)||"undefined"!==i.name){if(tz.isUnaryExpression(i)&&"-"===i.operator&&tz.isNumericLiteral(i.argument))return-i.argument.value;if(tz.isArrayExpression(i))return i.elements.map(r=>{if(null==r||tz.isSpreadElement(r))throw Error("Config arrays cannot contain holes or spreads.");return t(r)});if(tz.isObjectExpression(i)){let r={};for(let s of i.properties){if(tz.isSpreadElement(s))throw Error("Config objects cannot contain spreads.");if(s.computed)throw Error("Config object keys cannot be computed.");let i=tz.isIdentifier(s.key)?s.key.name:tz.isStringLiteral(s.key)||tz.isNumericLiteral(s.key)?String(s.key.value):null;if(null==i)throw Error("Unsupported config object key.");if(tz.isObjectMethod(s))throw Error("Config objects cannot contain methods.");if(!tz.isExpression(s.value))throw Error("Unsupported config object value.");r[i]=t(s.value)}return r}throw Error(`Unsupported config expression: ${i.type}`)}}(t.init)}}throw Error(`Invalid config in ${r}. The file must export a plain \`config\` object or "show-onboarding".`)}let tH=["@hexclave/next","@hexclave/react","@hexclave/tanstack-start","@hexclave/js","@hexclave/template","@stackframe/stack","@stackframe/react","@stackframe/js","@stackframe/template"];var tJ=t.i(844376),tY=t.i(513927);function tX(t){throw t}let tG=t=>Promise.resolve().then(()=>{let t=Error("Cannot find module as expression is too dynamic");throw t.code="MODULE_NOT_FOUND",t});function tZ(...r){return s||(s=t.r(648621)),s(...r)}var tQ=t.i(792509),t0=t.i(427699),t1=t.i(233405),t2=t.i(319668),t4=t.i(924868),t3=t.i(446786),t8=t.i(605365),t7=t.i(224361);let t9={get url(){return`file://${t.P("node_modules/.pnpm/@anthropic-ai+claude-agent-sdk@0.2.73_zod@4.3.6/node_modules/@anthropic-ai/claude-agent-sdk/sdk.mjs")}`}};var t5=Object.create,{getPrototypeOf:t6,defineProperty:re,getOwnPropertyNames:rt}=Object,rr=Object.prototype.hasOwnProperty;function ri(t){return this[t]}var rs,rn,ra=(t,r,i)=>{var s=null!=t&&"object"==typeof t;if(s){var n=r?rs??=new WeakMap:rn??=new WeakMap,a=n.get(t);if(a)return a}i=null!=t?t5(t6(t)):{};let o=!r&&t&&t.__esModule?i:re(i,"default",{value:t,enumerable:!0});for(let r of rt(t))rr.call(o,r)||re(o,r,{get:ri.bind(t,r),enumerable:!0});return s&&n.set(t,o),o},ro=(t,r)=>()=>(r||t((r={exports:{}}).exports,r),r.exports),rl=t=>t;function rp(t,r){this[t]=rl.bind(null,r)}var ru=(t,r)=>{for(var i in r)re(t,i,{get:r[i],enumerable:!0,configurable:!0,set:rp.bind(r,i)})},rc=Symbol.dispose||Symbol.for("Symbol.dispose"),rd=Symbol.asyncDispose||Symbol.for("Symbol.asyncDispose"),rh=(t,r,i)=>{if(null!=r){var s;if("object"!=typeof r&&"function"!=typeof r)throw TypeError('Object expected to be assigned to "using" declaration');if(i&&(s=r[rd]),void 0===s&&(s=r[rc]),"function"!=typeof s)throw TypeError("Object not disposable");t.push([i,s,r])}else i&&t.push([i]);return r},rf=(t,r,i)=>{var s="function"==typeof SuppressedError?SuppressedError:function(t,r,i,s){return(s=Error(i)).name="SuppressedError",s.error=t,s.suppressed=r,s},n=t=>r=i?new s(t,r,"An error was suppressed during disposal"):(i=!0,t),a=s=>{for(;s=t.pop();)try{var o=s[1]&&s[1].call(s[2]);if(s[0])return Promise.resolve(o).then(a,t=>(n(t),a()))}catch(t){n(t)}if(i)throw r};return a()},rm=ro(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.regexpCode=t.getEsmExportName=t.getProperty=t.safeStringify=t.stringify=t.strConcat=t.addCodeArg=t.str=t._=t.nil=t._Code=t.Name=t.IDENTIFIER=t._CodeOrName=void 0;class r{}t._CodeOrName=r,t.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class i extends r{constructor(r){if(super(),!t.IDENTIFIER.test(r))throw Error("CodeGen: name must be a valid identifier");this.str=r}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}t.Name=i;class s extends r{constructor(t){super(),this._items="string"==typeof t?[t]:t}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let t=this._items[0];return""===t||'""'===t}get str(){var t;return null!=(t=this._str)?t:this._str=this._items.reduce((t,r)=>`${t}${r}`,"")}get names(){var t;return null!=(t=this._names)?t:this._names=this._items.reduce((t,r)=>(r instanceof i&&(t[r.str]=(t[r.str]||0)+1),t),{})}}function n(t,...r){let i=[t[0]],a=0;for(;a<r.length;)l(i,r[a]),i.push(t[++a]);return new s(i)}t._Code=s,t.nil=new s(""),t._=n;var a=new s("+");function o(t,...r){let n=[p(t[0])],u=0;for(;u<r.length;)n.push(a),l(n,r[u]),n.push(a,p(t[++u]));return function(t){let r=1;for(;r<t.length-1;){if(t[r]===a){var s,n;let a=(s=t[r-1],'""'===(n=t[r+1])?s:'""'===s?n:"string"==typeof s?n instanceof i||'"'!==s[s.length-1]?void 0:"string"!=typeof n?`${s.slice(0,-1)}${n}"`:'"'===n[0]?s.slice(0,-1)+n.slice(1):void 0:"string"!=typeof n||'"'!==n[0]||s instanceof i?void 0:`"${s}${n.slice(1)}`);if(void 0!==a){t.splice(r-1,3,a);continue}t[r++]="+"}r++}}(n),new s(n)}function l(t,r){var n;r instanceof s?t.push(...r._items):r instanceof i?t.push(r):t.push("number"==typeof(n=r)||"boolean"==typeof n||null===n?n:p(Array.isArray(n)?n.join(","):n))}function p(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}t.str=o,t.addCodeArg=l,t.strConcat=function(t,r){return r.emptyStr()?t:t.emptyStr()?r:o`${t}${r}`},t.stringify=function(t){return new s(p(t))},t.safeStringify=p,t.getProperty=function(r){return"string"==typeof r&&t.IDENTIFIER.test(r)?new s(`.${r}`):n`[${r}]`},t.getEsmExportName=function(r){if("string"==typeof r&&t.IDENTIFIER.test(r))return new s(`${r}`);throw Error(`CodeGen: invalid export name: ${r}, use explicit $id name mapping`)},t.regexpCode=function(t){return new s(t.toString())}}),ry=ro(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ValueScope=t.ValueScopeName=t.Scope=t.varKinds=t.UsedValueState=void 0;var r,i,s=rm();class n extends Error{constructor(t){super(`CodeGen: "code" for ${t} not defined`),this.value=t.value}}(r=i||(t.UsedValueState=i={}))[r.Started=0]="Started",r[r.Completed=1]="Completed",t.varKinds={const:new s.Name("const"),let:new s.Name("let"),var:new s.Name("var")};class a{constructor({prefixes:t,parent:r}={}){this._names={},this._prefixes=t,this._parent=r}toName(t){return t instanceof s.Name?t:this.name(t)}name(t){return new s.Name(this._newName(t))}_newName(t){let r=this._names[t]||this._nameGroup(t);return`${t}${r.index++}`}_nameGroup(t){var r,i;if((null==(i=null==(r=this._parent)?void 0:r._prefixes)?void 0:i.has(t))||this._prefixes&&!this._prefixes.has(t))throw Error(`CodeGen: prefix "${t}" is not allowed in this scope`);return this._names[t]={prefix:t,index:0}}}t.Scope=a;class o extends s.Name{constructor(t,r){super(r),this.prefix=t}setValue(t,{property:r,itemIndex:i}){this.value=t,this.scopePath=s._`.${new s.Name(r)}[${i}]`}}t.ValueScopeName=o;var l=s._`\n`;t.ValueScope=class extends a{constructor(t){super(t),this._values={},this._scope=t.scope,this.opts={...t,_n:t.lines?l:s.nil}}get(){return this._scope}name(t){return new o(t,this._newName(t))}value(t,r){var i;if(void 0===r.ref)throw Error("CodeGen: ref must be passed in value");let s=this.toName(t),{prefix:n}=s,a=null!=(i=r.key)?i:r.ref,o=this._values[n];if(o){let t=o.get(a);if(t)return t}else o=this._values[n]=new Map;o.set(a,s);let l=this._scope[n]||(this._scope[n]=[]),p=l.length;return l[p]=r.ref,s.setValue(r,{property:n,itemIndex:p}),s}getValue(t,r){let i=this._values[t];if(i)return i.get(r)}scopeRefs(t,r=this._values){return this._reduceValues(r,r=>{if(void 0===r.scopePath)throw Error(`CodeGen: name "${r}" has no value`);return s._`${t}${r.scopePath}`})}scopeCode(t=this._values,r,i){return this._reduceValues(t,t=>{if(void 0===t.value)throw Error(`CodeGen: name "${t}" has no value`);return t.value.code},r,i)}_reduceValues(r,a,o={},l){let p=s.nil;for(let u in r){let c=r[u];if(!c)continue;let d=o[u]=o[u]||new Map;c.forEach(r=>{if(d.has(r))return;d.set(r,i.Started);let o=a(r);if(o){let i=this.opts.es5?t.varKinds.var:t.varKinds.const;p=s._`${p}${i} ${r} = ${o};${this.opts._n}`}else if(o=null==l?void 0:l(r))p=s._`${p}${o}${this.opts._n}`;else throw new n(r);d.set(r,i.Completed)})}return p}}}),rb=ro(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.or=t.and=t.not=t.CodeGen=t.operators=t.varKinds=t.ValueScopeName=t.ValueScope=t.Scope=t.Name=t.regexpCode=t.stringify=t.getProperty=t.nil=t.strConcat=t.str=t._=void 0;var r=rm(),i=ry(),s=rm();Object.defineProperty(t,"_",{enumerable:!0,get:function(){return s._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return s.str}}),Object.defineProperty(t,"strConcat",{enumerable:!0,get:function(){return s.strConcat}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return s.nil}}),Object.defineProperty(t,"getProperty",{enumerable:!0,get:function(){return s.getProperty}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return s.stringify}}),Object.defineProperty(t,"regexpCode",{enumerable:!0,get:function(){return s.regexpCode}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return s.Name}});var n=ry();Object.defineProperty(t,"Scope",{enumerable:!0,get:function(){return n.Scope}}),Object.defineProperty(t,"ValueScope",{enumerable:!0,get:function(){return n.ValueScope}}),Object.defineProperty(t,"ValueScopeName",{enumerable:!0,get:function(){return n.ValueScopeName}}),Object.defineProperty(t,"varKinds",{enumerable:!0,get:function(){return n.varKinds}}),t.operators={GT:new r._Code(">"),GTE:new r._Code(">="),LT:new r._Code("<"),LTE:new r._Code("<="),EQ:new r._Code("==="),NEQ:new r._Code("!=="),NOT:new r._Code("!"),OR:new r._Code("||"),AND:new r._Code("&&"),ADD:new r._Code("+")};class a{optimizeNodes(){return this}optimizeNames(t,r){return this}}class o extends a{constructor(t,r,i){super(),this.varKind=t,this.name=r,this.rhs=i}render({es5:t,_n:r}){let s=t?i.varKinds.var:this.varKind,n=void 0===this.rhs?"":` = ${this.rhs}`;return`${s} ${this.name}${n};`+r}optimizeNames(t,r){if(t[this.name.str])return this.rhs&&(this.rhs=k(this.rhs,t,r)),this}get names(){return this.rhs instanceof r._CodeOrName?this.rhs.names:{}}}class l extends a{constructor(t,r,i){super(),this.lhs=t,this.rhs=r,this.sideEffects=i}render({_n:t}){return`${this.lhs} = ${this.rhs};`+t}optimizeNames(t,i){if(!(this.lhs instanceof r.Name)||t[this.lhs.str]||this.sideEffects)return this.rhs=k(this.rhs,t,i),this}get names(){return I(this.lhs instanceof r.Name?{}:{...this.lhs.names},this.rhs)}}class p extends l{constructor(t,r,i,s){super(t,i,s),this.op=r}render({_n:t}){return`${this.lhs} ${this.op}= ${this.rhs};`+t}}class u extends a{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`${this.label}:`+t}}class c extends a{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`break${this.label?` ${this.label}`:""};`+t}}class d extends a{constructor(t){super(),this.error=t}render({_n:t}){return`throw ${this.error};`+t}get names(){return this.error.names}}class h extends a{constructor(t){super(),this.code=t}render({_n:t}){return`${this.code};`+t}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(t,r){return this.code=k(this.code,t,r),this}get names(){return this.code instanceof r._CodeOrName?this.code.names:{}}}class f extends a{constructor(t=[]){super(),this.nodes=t}render(t){return this.nodes.reduce((r,i)=>r+i.render(t),"")}optimizeNodes(){let{nodes:t}=this,r=t.length;for(;r--;){let i=t[r].optimizeNodes();Array.isArray(i)?t.splice(r,1,...i):i?t[r]=i:t.splice(r,1)}return t.length>0?this:void 0}optimizeNames(t,r){let{nodes:i}=this,s=i.length;for(;s--;){let n=i[s];n.optimizeNames(t,r)||(function(t,r){for(let i in r)t[i]=(t[i]||0)-(r[i]||0)}(t,n.names),i.splice(s,1))}return i.length>0?this:void 0}get names(){return this.nodes.reduce((t,r)=>C(t,r.names),{})}}class m extends f{render(t){return"{"+t._n+super.render(t)+"}"+t._n}}class y extends f{}class b extends m{}b.kind="else";class g extends m{constructor(t,r){super(r),this.condition=t}render(t){let r=`if(${this.condition})`+super.render(t);return this.else&&(r+="else "+this.else.render(t)),r}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(!0===t)return this.nodes;let r=this.else;if(r){let t=r.optimizeNodes();r=this.else=Array.isArray(t)?new b(t):t}return r?!1===t?r instanceof g?r:r.nodes:this.nodes.length?this:new g(N(t),r instanceof g?[r]:r.nodes):!1!==t&&this.nodes.length?this:void 0}optimizeNames(t,r){var i;if(this.else=null==(i=this.else)?void 0:i.optimizeNames(t,r),super.optimizeNames(t,r)||this.else)return this.condition=k(this.condition,t,r),this}get names(){let t=super.names;return I(t,this.condition),this.else&&C(t,this.else.names),t}}g.kind="if";class v extends m{}v.kind="for";class x extends v{constructor(t){super(),this.iteration=t}render(t){return`for(${this.iteration})`+super.render(t)}optimizeNames(t,r){if(super.optimizeNames(t,r))return this.iteration=k(this.iteration,t,r),this}get names(){return C(super.names,this.iteration.names)}}class T extends v{constructor(t,r,i,s){super(),this.varKind=t,this.name=r,this.from=i,this.to=s}render(t){let r=t.es5?i.varKinds.var:this.varKind,{name:s,from:n,to:a}=this;return`for(${r} ${s}=${n}; ${s}<${a}; ${s}++)`+super.render(t)}get names(){let t=I(super.names,this.from);return I(t,this.to)}}class E extends v{constructor(t,r,i,s){super(),this.loop=t,this.varKind=r,this.name=i,this.iterable=s}render(t){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(t)}optimizeNames(t,r){if(super.optimizeNames(t,r))return this.iterable=k(this.iterable,t,r),this}get names(){return C(super.names,this.iterable.names)}}class S extends m{constructor(t,r,i){super(),this.name=t,this.args=r,this.async=i}render(t){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(t)}}S.kind="func";class _ extends f{render(t){return"return "+super.render(t)}}_.kind="return";class P extends m{render(t){let r="try"+super.render(t);return this.catch&&(r+=this.catch.render(t)),this.finally&&(r+=this.finally.render(t)),r}optimizeNodes(){var t,r;return super.optimizeNodes(),null==(t=this.catch)||t.optimizeNodes(),null==(r=this.finally)||r.optimizeNodes(),this}optimizeNames(t,r){var i,s;return super.optimizeNames(t,r),null==(i=this.catch)||i.optimizeNames(t,r),null==(s=this.finally)||s.optimizeNames(t,r),this}get names(){let t=super.names;return this.catch&&C(t,this.catch.names),this.finally&&C(t,this.finally.names),t}}class A extends m{constructor(t){super(),this.error=t}render(t){return`catch(${this.error})`+super.render(t)}}A.kind="catch";class w extends m{render(t){return"finally"+super.render(t)}}function C(t,r){for(let i in r)t[i]=(t[i]||0)+(r[i]||0);return t}function I(t,i){return i instanceof r._CodeOrName?C(t,i.names):t}function k(t,i,s){var n;if(t instanceof r.Name)return a(t);if(!((n=t)instanceof r._Code&&n._items.some(t=>t instanceof r.Name&&1===i[t.str]&&void 0!==s[t.str])))return t;return new r._Code(t._items.reduce((t,i)=>(i instanceof r.Name&&(i=a(i)),i instanceof r._Code?t.push(...i._items):t.push(i),t),[]));function a(t){let r=s[t.str];return void 0===r||1!==i[t.str]?t:(delete i[t.str],r)}}function N(t){return"boolean"==typeof t||"number"==typeof t||null===t?!t:r._`!${L(t)}`}w.kind="finally",t.CodeGen=class{constructor(t,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
354
|
-
`:""},this._extScope=t,this._scope=new i.Scope({parent:t}),this._nodes=[new y]}toString(){return this._root.render(this.opts)}name(t){return this._scope.name(t)}scopeName(t){return this._extScope.name(t)}scopeValue(t,r){let i=this._extScope.value(t,r);return(this._values[i.prefix]||(this._values[i.prefix]=new Set)).add(i),i}getScopeValue(t,r){return this._extScope.getValue(t,r)}scopeRefs(t){return this._extScope.scopeRefs(t,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(t,r,i,s){let n=this._scope.toName(r);return void 0!==i&&s&&(this._constants[n.str]=i),this._leafNode(new o(t,n,i)),n}const(t,r,s){return this._def(i.varKinds.const,t,r,s)}let(t,r,s){return this._def(i.varKinds.let,t,r,s)}var(t,r,s){return this._def(i.varKinds.var,t,r,s)}assign(t,r,i){return this._leafNode(new l(t,r,i))}add(r,i){return this._leafNode(new p(r,t.operators.ADD,i))}code(t){return"function"==typeof t?t():t!==r.nil&&this._leafNode(new h(t)),this}object(...t){let i=["{"];for(let[s,n]of t)i.length>1&&i.push(","),i.push(s),(s!==n||this.opts.es5)&&(i.push(":"),(0,r.addCodeArg)(i,n));return i.push("}"),new r._Code(i)}if(t,r,i){if(this._blockNode(new g(t)),r&&i)this.code(r).else().code(i).endIf();else if(r)this.code(r).endIf();else if(i)throw Error('CodeGen: "else" body without "then" body');return this}elseIf(t){return this._elseNode(new g(t))}else(){return this._elseNode(new b)}endIf(){return this._endBlockNode(g,b)}_for(t,r){return this._blockNode(t),r&&this.code(r).endFor(),this}for(t,r){return this._for(new x(t),r)}forRange(t,r,s,n,a=this.opts.es5?i.varKinds.var:i.varKinds.let){let o=this._scope.toName(t);return this._for(new T(a,o,r,s),()=>n(o))}forOf(t,s,n,a=i.varKinds.const){let o=this._scope.toName(t);if(this.opts.es5){let t=s instanceof r.Name?s:this.var("_arr",s);return this.forRange("_i",0,r._`${t}.length`,i=>{this.var(o,r._`${t}[${i}]`),n(o)})}return this._for(new E("of",a,o,s),()=>n(o))}forIn(t,s,n,a=this.opts.es5?i.varKinds.var:i.varKinds.const){if(this.opts.ownProperties)return this.forOf(t,r._`Object.keys(${s})`,n);let o=this._scope.toName(t);return this._for(new E("in",a,o,s),()=>n(o))}endFor(){return this._endBlockNode(v)}label(t){return this._leafNode(new u(t))}break(t){return this._leafNode(new c(t))}return(t){let r=new _;if(this._blockNode(r),this.code(t),1!==r.nodes.length)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(_)}try(t,r,i){if(!r&&!i)throw Error('CodeGen: "try" without "catch" and "finally"');let s=new P;if(this._blockNode(s),this.code(t),r){let t=this.name("e");this._currNode=s.catch=new A(t),r(t)}return i&&(this._currNode=s.finally=new w,this.code(i)),this._endBlockNode(A,w)}throw(t){return this._leafNode(new d(t))}block(t,r){return this._blockStarts.push(this._nodes.length),t&&this.code(t).endBlock(r),this}endBlock(t){let r=this._blockStarts.pop();if(void 0===r)throw Error("CodeGen: not in self-balancing block");let i=this._nodes.length-r;if(i<0||void 0!==t&&i!==t)throw Error(`CodeGen: wrong number of nodes: ${i} vs ${t} expected`);return this._nodes.length=r,this}func(t,i=r.nil,s,n){return this._blockNode(new S(t,i,s)),n&&this.code(n).endFunc(),this}endFunc(){return this._endBlockNode(S)}optimize(t=1){for(;t-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(t){return this._currNode.nodes.push(t),this}_blockNode(t){this._currNode.nodes.push(t),this._nodes.push(t)}_endBlockNode(t,r){let i=this._currNode;if(i instanceof t||r&&i instanceof r)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${r?`${t.kind}/${r.kind}`:t.kind}"`)}_elseNode(t){let r=this._currNode;if(!(r instanceof g))throw Error('CodeGen: "else" without "if"');return this._currNode=r.else=t,this}get _root(){return this._nodes[0]}get _currNode(){let t=this._nodes;return t[t.length-1]}set _currNode(t){let r=this._nodes;r[r.length-1]=t}},t.not=N;var O=j(t.operators.AND);t.and=function(...t){return t.reduce(O)};var D=j(t.operators.OR);function j(t){return(i,s)=>i===r.nil?s:s===r.nil?i:r._`${L(i)} ${t} ${L(s)}`}function L(t){return t instanceof r.Name?t:r._`(${t})`}t.or=function(...t){return t.reduce(D)}}),rg=ro(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.checkStrictMode=t.getErrorPath=t.Type=t.useFunc=t.setEvaluated=t.evaluatedPropsToName=t.mergeEvaluated=t.eachItem=t.unescapeJsonPointer=t.escapeJsonPointer=t.escapeFragment=t.unescapeFragment=t.schemaRefOrVal=t.schemaHasRulesButRef=t.schemaHasRules=t.checkUnknownRules=t.alwaysValidSchema=t.toHash=void 0;var r,i,s=rb(),n=rm();function a(t,r=t.schema){let{opts:i,self:s}=t;if(!i.strictSchema||"boolean"==typeof r)return;let n=s.RULES.keywords;for(let i in r)n[i]||f(t,`unknown keyword: "${i}"`)}function o(t,r){if("boolean"==typeof t)return!t;for(let i in t)if(r[i])return!0;return!1}function l(t){return"number"==typeof t?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}function p(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function u({mergeNames:t,mergeToName:r,mergeValues:i,resultToName:n}){return(a,o,l,p)=>{let u=void 0===l?o:l instanceof s.Name?(o instanceof s.Name?t(a,o,l):r(a,o,l),l):o instanceof s.Name?(r(a,l,o),o):i(o,l);return p!==s.Name||u instanceof s.Name?u:n(a,u)}}function c(t,r){if(!0===r)return t.var("props",!0);let i=t.var("props",s._`{}`);return void 0!==r&&d(t,i,r),i}function d(t,r,i){Object.keys(i).forEach(i=>t.assign(s._`${r}${(0,s.getProperty)(i)}`,!0))}t.toHash=function(t){let r={};for(let i of t)r[i]=!0;return r},t.alwaysValidSchema=function(t,r){return"boolean"==typeof r?r:0===Object.keys(r).length||(a(t,r),!o(r,t.self.RULES.all))},t.checkUnknownRules=a,t.schemaHasRules=o,t.schemaHasRulesButRef=function(t,r){if("boolean"==typeof t)return!t;for(let i in t)if("$ref"!==i&&r.all[i])return!0;return!1},t.schemaRefOrVal=function({topSchemaRef:t,schemaPath:r},i,n,a){if(!a){if("number"==typeof i||"boolean"==typeof i)return i;if("string"==typeof i)return s._`${i}`}return s._`${t}${r}${(0,s.getProperty)(n)}`},t.unescapeFragment=function(t){return p(decodeURIComponent(t))},t.escapeFragment=function(t){return encodeURIComponent(l(t))},t.escapeJsonPointer=l,t.unescapeJsonPointer=p,t.eachItem=function(t,r){if(Array.isArray(t))for(let i of t)r(i);else r(t)},t.mergeEvaluated={props:u({mergeNames:(t,r,i)=>t.if(s._`${i} !== true && ${r} !== undefined`,()=>{t.if(s._`${r} === true`,()=>t.assign(i,!0),()=>t.assign(i,s._`${i} || {}`).code(s._`Object.assign(${i}, ${r})`))}),mergeToName:(t,r,i)=>t.if(s._`${i} !== true`,()=>{!0===r?t.assign(i,!0):(t.assign(i,s._`${i} || {}`),d(t,i,r))}),mergeValues:(t,r)=>!0===t||{...t,...r},resultToName:c}),items:u({mergeNames:(t,r,i)=>t.if(s._`${i} !== true && ${r} !== undefined`,()=>t.assign(i,s._`${r} === true ? true : ${i} > ${r} ? ${i} : ${r}`)),mergeToName:(t,r,i)=>t.if(s._`${i} !== true`,()=>t.assign(i,!0===r||s._`${i} > ${r} ? ${i} : ${r}`)),mergeValues:(t,r)=>!0===t||Math.max(t,r),resultToName:(t,r)=>t.var("items",r)})},t.evaluatedPropsToName=c,t.setEvaluated=d;var h={};function f(t,r,i=t.opts.strictSchema){if(i){if(r=`strict mode: ${r}`,!0===i)throw Error(r);t.self.logger.warn(r)}}t.useFunc=function(t,r){return t.scopeValue("func",{ref:r,code:h[r.code]||(h[r.code]=new n._Code(r.code))})},(r=i||(t.Type=i={}))[r.Num=0]="Num",r[r.Str=1]="Str",t.getErrorPath=function(t,r,n){if(t instanceof s.Name){let a=r===i.Num;return n?a?s._`"[" + ${t} + "]"`:s._`"['" + ${t} + "']"`:a?s._`"/" + ${t}`:s._`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return n?(0,s.getProperty)(t).toString():"/"+l(t)},t.checkStrictMode=f}),rv=ro(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=rb();t.default={data:new r.Name("data"),valCxt:new r.Name("valCxt"),instancePath:new r.Name("instancePath"),parentData:new r.Name("parentData"),parentDataProperty:new r.Name("parentDataProperty"),rootData:new r.Name("rootData"),dynamicAnchors:new r.Name("dynamicAnchors"),vErrors:new r.Name("vErrors"),errors:new r.Name("errors"),this:new r.Name("this"),self:new r.Name("self"),scope:new r.Name("scope"),json:new r.Name("json"),jsonPos:new r.Name("jsonPos"),jsonLen:new r.Name("jsonLen"),jsonPart:new r.Name("jsonPart")}}),rx=ro(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extendErrors=t.resetErrorsCount=t.reportExtraError=t.reportError=t.keyword$DataError=t.keywordError=void 0;var r=rb(),i=rg(),s=rv();function n(t,i){let n=t.const("err",i);t.if(r._`${s.default.vErrors} === null`,()=>t.assign(s.default.vErrors,r._`[${n}]`),r._`${s.default.vErrors}.push(${n})`),t.code(r._`${s.default.errors}++`)}function a(t,i){let{gen:s,validateName:n,schemaEnv:a}=t;a.$async?s.throw(r._`new ${t.ValidationError}(${i})`):(s.assign(r._`${n}.errors`,i),s.return(!1))}t.keywordError={message:({keyword:t})=>r.str`must pass "${t}" keyword validation`},t.keyword$DataError={message:({keyword:t,schemaType:i})=>i?r.str`"${t}" keyword must be ${i} ($data)`:r.str`"${t}" keyword is invalid ($data)`},t.reportError=function(i,s=t.keywordError,o,p){let{it:u}=i,{gen:c,compositeRule:d,allErrors:h}=u,f=l(i,s,o);(null!=p?p:d||h)?n(c,f):a(u,r._`[${f}]`)},t.reportExtraError=function(r,i=t.keywordError,o){let{it:p}=r,{gen:u,compositeRule:c,allErrors:d}=p;n(u,l(r,i,o)),c||d||a(p,s.default.vErrors)},t.resetErrorsCount=function(t,i){t.assign(s.default.errors,i),t.if(r._`${s.default.vErrors} !== null`,()=>t.if(i,()=>t.assign(r._`${s.default.vErrors}.length`,i),()=>t.assign(s.default.vErrors,null)))},t.extendErrors=function({gen:t,keyword:i,schemaValue:n,data:a,errsCount:o,it:l}){if(void 0===o)throw Error("ajv implementation error");let p=t.name("err");t.forRange("i",o,s.default.errors,o=>{t.const(p,r._`${s.default.vErrors}[${o}]`),t.if(r._`${p}.instancePath === undefined`,()=>t.assign(r._`${p}.instancePath`,(0,r.strConcat)(s.default.instancePath,l.errorPath))),t.assign(r._`${p}.schemaPath`,r.str`${l.errSchemaPath}/${i}`),l.opts.verbose&&(t.assign(r._`${p}.schema`,n),t.assign(r._`${p}.data`,a))})};var o={keyword:new r.Name("keyword"),schemaPath:new r.Name("schemaPath"),params:new r.Name("params"),propertyName:new r.Name("propertyName"),message:new r.Name("message"),schema:new r.Name("schema"),parentSchema:new r.Name("parentSchema")};function l(t,n,a){let{createErrors:l}=t.it;return!1===l?r._`{}`:function(t,n,a={}){let{gen:l,it:p}=t,u=[function({errorPath:t},{instancePath:n}){let a=n?r.str`${t}${(0,i.getErrorPath)(n,i.Type.Str)}`:t;return[s.default.instancePath,(0,r.strConcat)(s.default.instancePath,a)]}(p,a),function({keyword:t,it:{errSchemaPath:s}},{schemaPath:n,parentSchema:a}){let l=a?s:r.str`${s}/${t}`;return n&&(l=r.str`${l}${(0,i.getErrorPath)(n,i.Type.Str)}`),[o.schemaPath,l]}(t,a)];return function(t,{params:i,message:n},a){let{keyword:l,data:p,schemaValue:u,it:c}=t,{opts:d,propertyName:h,topSchemaRef:f,schemaPath:m}=c;a.push([o.keyword,l],[o.params,"function"==typeof i?i(t):i||r._`{}`]),d.messages&&a.push([o.message,"function"==typeof n?n(t):n]),d.verbose&&a.push([o.schema,u],[o.parentSchema,r._`${f}${m}`],[s.default.data,p]),h&&a.push([o.propertyName,h])}(t,n,u),l.object(...u)}(t,n,a)}}),rT=ro(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.boolOrEmptySchema=t.topBoolOrEmptySchema=void 0;var r=rx(),i=rb(),s=rv(),n={message:"boolean schema is false"};function a(t,i){let{gen:s,data:a}=t;(0,r.reportError)({gen:s,keyword:"false schema",data:a,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t},n,void 0,i)}t.topBoolOrEmptySchema=function(t){let{gen:r,schema:n,validateName:o}=t;!1===n?a(t,!1):"object"==typeof n&&!0===n.$async?r.return(s.default.data):(r.assign(i._`${o}.errors`,null),r.return(!0))},t.boolOrEmptySchema=function(t,r){let{gen:i,schema:s}=t;!1===s?(i.var(r,!1),a(t)):i.var(r,!0)}}),rE=ro(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getRules=t.isJSONType=void 0;var r=new Set(["string","number","integer","boolean","null","object","array"]);t.isJSONType=function(t){return"string"==typeof t&&r.has(t)},t.getRules=function(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}}),rS=ro(t=>{function r(t,r){return r.rules.some(r=>i(t,r))}function i(t,r){var i;return void 0!==t[r.keyword]||(null==(i=r.definition.implements)?void 0:i.some(r=>void 0!==t[r]))}Object.defineProperty(t,"__esModule",{value:!0}),t.shouldUseRule=t.shouldUseGroup=t.schemaHasRulesForType=void 0,t.schemaHasRulesForType=function({schema:t,self:i},s){let n=i.RULES.types[s];return n&&!0!==n&&r(t,n)},t.shouldUseGroup=r,t.shouldUseRule=i}),r_=ro(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.reportTypeError=t.checkDataTypes=t.checkDataType=t.coerceAndCheckDataType=t.getJSONTypes=t.getSchemaTypes=t.DataType=void 0;var r,i,s=rE(),n=rS(),a=rx(),o=rb(),l=rg();function p(t){let r=Array.isArray(t)?t:t?[t]:[];if(r.every(s.isJSONType))return r;throw Error("type must be JSONType or JSONType[]: "+r.join(","))}(r=i||(t.DataType=i={}))[r.Correct=0]="Correct",r[r.Wrong=1]="Wrong",t.getSchemaTypes=function(t){let r=p(t.type);if(r.includes("null")){if(!1===t.nullable)throw Error("type: null contradicts nullable: false")}else{if(!r.length&&void 0!==t.nullable)throw Error('"nullable" cannot be used without "type"');!0===t.nullable&&r.push("null")}return r},t.getJSONTypes=p,t.coerceAndCheckDataType=function(t,r){var s,a;let{gen:l,data:p,opts:c}=t,h=(s=r,(a=c.coerceTypes)?s.filter(t=>u.has(t)||"array"===a&&"array"===t):[]),m=r.length>0&&!(0===h.length&&1===r.length&&(0,n.schemaHasRulesForType)(t,r[0]));if(m){let s=d(r,p,c.strictNumbers,i.Wrong);l.if(s,()=>{h.length?function(t,r,i){let{gen:s,data:n,opts:a}=t,l=s.let("dataType",o._`typeof ${n}`),p=s.let("coerced",o._`undefined`);for(let t of("array"===a.coerceTypes&&s.if(o._`${l} == 'object' && Array.isArray(${n}) && ${n}.length == 1`,()=>s.assign(n,o._`${n}[0]`).assign(l,o._`typeof ${n}`).if(d(r,n,a.strictNumbers),()=>s.assign(p,n))),s.if(o._`${p} !== undefined`),i))(u.has(t)||"array"===t&&"array"===a.coerceTypes)&&function(t){switch(t){case"string":s.elseIf(o._`${l} == "number" || ${l} == "boolean"`).assign(p,o._`"" + ${n}`).elseIf(o._`${n} === null`).assign(p,o._`""`);return;case"number":s.elseIf(o._`${l} == "boolean" || ${n} === null
|
|
352
|
+
`);let r=await eJ(this._interface,{provider:t.providerId,redirectUrl:this._getOAuthCallbackRedirectUri(),errorRedirectUrl:this.urls.error,providerScope:(0,G.mergeScopeStrings)(t.scope||"",(this._oauthScopesOnSignIn[t.providerId]??[]).join(" "))},t.session);return await this._redirectTo({url:r}),await (0,E.neverResolve)()}if(!i)return null;let s=r.oauth_providers.find(r=>r.id===t.providerId)?.account_id??"";return{id:t.providerId,provider:t.providerId,providerAccountId:s,async getAccessToken(){let r=await t.getOrWaitOAuthToken();if(!r)throw new x.HexclaveAssertionError(`Failed to retrieve an access token for this connected account (provider: ${t.providerId}). This usually means the OAuth refresh token has been revoked or expired. The user needs to re-authorize by calling \`linkConnectedAccount\` or using \`getOrLinkConnectedAccount\`.`);return r},useAccessToken(){let r=t.useOAuthToken();if(!r)throw new x.HexclaveAssertionError(`Failed to retrieve an access token for this connected account (provider: ${t.providerId}). This usually means the OAuth refresh token has been revoked or expired. The user needs to re-authorize by calling \`linkConnectedAccount\` or using \`getOrLinkConnectedAccount\`.`);return r}}}_createOAuthConnectionFromCrudItem(t,r){let i=this,s=t.provider,n=t.provider_account_id;return{id:s,provider:s,providerAccountId:n,async getAccessToken(t){let a=t?.scopes?.join(" ")??"",o=w.Result.orThrow(await i._currentUserOAuthConnectionAccessTokensByAccountCache.getOrWait([r,s,n,a],"write-only"));if(!o){let t=a?`The requested scopes [${a}] are not available on the existing token.`:"The OAuth refresh token has likely been revoked or expired.";return w.Result.error(new P.KnownErrors.OAuthAccessTokenNotAvailable(s,`${t} The user needs to re-authorize by calling \`linkConnectedAccount\` or using \`getOrLinkConnectedAccount\`.`))}return w.Result.ok(o)},useAccessToken(t){let a=t?.scopes?.join(" ")??"",o=(0,C.useAsyncCache)(i._currentUserOAuthConnectionAccessTokensByAccountCache,[r,s,n,a],"connection.useAccessToken()");if(!o){let t=a?`The requested scopes [${a}] are not available on the existing token.`:"The OAuth refresh token has likely been revoked or expired.";return w.Result.error(new P.KnownErrors.OAuthAccessTokenNotAvailable(s,`${t} The user needs to re-authorize by calling \`linkConnectedAccount\` or using \`getOrLinkConnectedAccount\`.`))}return w.Result.ok(o)}}}constructor(i,s){this._uniqueIdentifier=void 0,this._sessionRecorder=null,this._eventTracker=null,this.__DEMO_ENABLE_SLIGHT_FETCH_DELAY=!1,this._ownedAdminApps=new ep.DependenciesMap,this._currentUserCache=(0,C.createCacheBySession)(async t=>(this.__DEMO_ENABLE_SLIGHT_FETCH_DELAY&&await (0,E.wait)(2e3),t.isKnownToBeInvalid())?null:await this._interface.getClientUserByToken(t)),this._currentProjectCache=(0,C.createCache)(async()=>w.Result.orThrow(await this._interface.getClientProject())),this._ownedProjectsCache=(0,C.createCacheBySession)(async t=>await this._interface.listProjects(t)),this._currentUserPermissionsCache=(0,C.createCacheBySession)(async(t,[r,i])=>await this._interface.listCurrentUserTeamPermissions({teamId:r,recursive:i},t)),this._currentUserProjectPermissionsCache=(0,C.createCacheBySession)(async(t,[r])=>await this._interface.listCurrentUserProjectPermissions({recursive:r},t)),this._currentUserTeamsCache=(0,C.createCacheBySession)(async t=>await this._interface.listCurrentUserTeams(t)),this._currentUserOAuthConnectionAccessTokensCache=(0,C.createCacheBySession)(async(t,[r,i])=>{try{return{accessToken:(await this._interface.createProviderAccessToken(r,i||"",t)).access_token}}catch(t){if(!(P.KnownErrors.OAuthAccessTokenNotAvailable.isInstance(t)||P.KnownErrors.OAuthConnectionDoesNotHaveRequiredScope.isInstance(t)||P.KnownErrors.OAuthConnectionNotConnectedToUser.isInstance(t)))throw t}return null}),this._currentUserOAuthConnectionCache=(0,C.createCacheBySession)(async(t,[r,i,s])=>await this._getUserOAuthConnectionCacheFn({getUser:async()=>w.Result.orThrow(await this._currentUserCache.getOrWait([t],"write-only")),getOrWaitOAuthToken:async()=>w.Result.orThrow(await this._currentUserOAuthConnectionAccessTokensCache.getOrWait([t,r,i||""],"write-only")),useOAuthToken:()=>(0,C.useAsyncCache)(this._currentUserOAuthConnectionAccessTokensCache,[t,r,i||""],"connection.useAccessToken()"),providerId:r,scope:i,redirect:s,session:t})),this._currentUserConnectedAccountsCache=(0,C.createCacheBySession)(async t=>(await this._interface.listConnectedAccounts(t)).items.map(r=>this._createOAuthConnectionFromCrudItem(r,t))),this._currentUserOAuthConnectionAccessTokensByAccountCache=(0,C.createCacheBySession)(async(t,[r,i,s])=>{try{return{accessToken:(await this._interface.createProviderAccessTokenByAccount(r,i,s,t)).access_token}}catch(t){if(P.KnownErrors.OAuthAccessTokenNotAvailable.isInstance(t)||P.KnownErrors.OAuthConnectionDoesNotHaveRequiredScope.isInstance(t)||P.KnownErrors.OAuthConnectionNotConnectedToUser.isInstance(t))return null;throw t}}),this._currentUserValidConnectedAccountForProviderCache=(0,C.createCacheBySession)(async(t,[r,i])=>{let s=w.Result.orThrow(await this._currentUserConnectedAccountsCache.getOrWait([t],"write-only")).filter(t=>t.provider===r),n=i?i.split(" "):void 0;for(let t of s)if("ok"===(await t.getAccessToken({scopes:n})).status)return t;let a=await eJ(this._interface,{provider:r,redirectUrl:this._getOAuthCallbackRedirectUri(),errorRedirectUrl:this.urls.error,providerScope:(0,G.mergeScopeStrings)(i,(this._oauthScopesOnSignIn[r]??[]).join(" "))},t);return await this._redirectTo({url:a}),await (0,E.neverResolve)()}),this._teamMemberProfilesCache=(0,C.createCacheBySession)(async(t,[r])=>await this._interface.listTeamMemberProfiles({teamId:r},t)),this._teamInvitationsCache=(0,C.createCacheBySession)(async(t,[r])=>await this._interface.listTeamInvitations({teamId:r},t)),this._currentUserTeamProfileCache=(0,C.createCacheBySession)(async(t,[r])=>await this._interface.getTeamMemberProfile({teamId:r,userId:"me"},t)),this._currentUserTeamInvitationsCache=(0,C.createCacheBySession)(async t=>await this._interface.listCurrentUserTeamInvitations(t)),this._clientContactChannelsCache=(0,C.createCacheBySession)(async t=>await this._interface.listClientContactChannels(t)),this._userApiKeysCache=(0,C.createCacheBySession)(async t=>await this._interface.listProjectApiKeys({user_id:"me"},t,"client")),this._teamApiKeysCache=(0,C.createCacheBySession)(async(t,[r])=>await this._interface.listProjectApiKeys({team_id:r},t,"client")),this._notificationCategoriesCache=(0,C.createCacheBySession)(async t=>await this._interface.listNotificationCategories(t)),this._currentUserOAuthProvidersCache=(0,C.createCacheBySession)(async t=>await this._interface.listOAuthProviders({user_id:"me"},t)),this._userItemCache=(0,C.createCacheBySession)(async(t,[r,i])=>await this._interface.getItem({userId:r,itemId:i},t)),this._teamItemCache=(0,C.createCacheBySession)(async(t,[r,i])=>await this._interface.getItem({teamId:r,itemId:i},t)),this._customItemCache=(0,C.createCacheBySession)(async(t,[r,i])=>await this._interface.getItem({customCustomerId:r,itemId:i},t)),this._userProductsCache=(0,C.createCacheBySession)(async(t,[r,i,s])=>await this._interface.listProducts({customer_type:"user",customer_id:r,cursor:i??void 0,limit:s??void 0},t)),this._teamProductsCache=(0,C.createCacheBySession)(async(t,[r,i,s])=>await this._interface.listProducts({customer_type:"team",customer_id:r,cursor:i??void 0,limit:s??void 0},t)),this._customProductsCache=(0,C.createCacheBySession)(async(t,[r,i,s])=>await this._interface.listProducts({customer_type:"custom",customer_id:r,cursor:i??void 0,limit:s??void 0},t)),this._userInvoicesCache=(0,C.createCacheBySession)(async(t,[r,i,s])=>await this._interface.listInvoices({customer_type:"user",customer_id:r,cursor:i??void 0,limit:s??void 0},t)),this._teamInvoicesCache=(0,C.createCacheBySession)(async(t,[r,i,s])=>await this._interface.listInvoices({customer_type:"team",customer_id:r,cursor:i??void 0,limit:s??void 0},t)),this._customerBillingCache=(0,C.createCacheBySession)(async(t,[r,i])=>await this._interface.getCustomerBilling(r,i,t)),this._convexPartialUserCache=(0,C.createCache)(async([t])=>await this._getPartialUserFromConvex(t)),this._trustedParentDomainCache=(0,C.createCache)(async([t])=>await this._getTrustedParentDomain(t)),this._anonymousSignUpInProgress=null,this._prefetchedCrossDomainHandoffParams=null,this._prefetchedCrossDomainHandoffParamsFetchedAt=0,this._isPrefetchingCrossDomainHandoffParams=!1,this._pendingAuthResolutionPromises=[],this._memoryTokenStore=(0,C.createEmptyTokenStore)(),this._nextServerCookiesTokenStores=new WeakMap,this._requestTokenStores=new WeakMap,this._storedBrowserCookieTokenStore=null,this._mostRecentQueuedCookieRefreshIndex=0,this._sessionsByTokenStoreAndSessionKey=new WeakMap,this._botChallengeSiteKeysWarned=!1;const n=(0,C.resolveConstructorOptions)(i);if(!r.LazyStackAdminAppImpl.value)throw new x.HexclaveAssertionError("Admin app implementation not initialized. Did you import the _HexclaveClientApp from hexclave-app/apps/implementations/index.ts? You can't import it directly from ./apps/implementations/client-app-impl.ts as that causes a circular dependency (see the comment at _LazyHexclaveAdminAppImpl for more details).");this._options=n,this._extraOptions=s;const a=n.projectId??(0,C.getDefaultProjectId)();if("internal"!==a&&!a.match(/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}$/i))throw Error(`Invalid project ID: ${a}. Project IDs must be UUIDs. Please check your environment variables and/or your StackApp.`);const o=n.publishableClientKey??(0,C.getDefaultPublishableClientKey)();if(s&&s.interface)this._interface=s.interface;else{const t=(0,C.resolveApiUrls)(n.baseUrl);this._interface=new Z.HexclaveClientInterface({getBaseUrl:()=>t()[0],getAnalyticsBaseUrl:()=>(0,C.getAnalyticsBaseUrl)(t()[0]),getApiUrls:t,extraRequestHeaders:n.extraRequestHeaders??(0,C.getDefaultExtraRequestHeaders)(),projectId:a,clientVersion:C.clientVersion,...null!=o?{publishableClientKey:o}:{},prepareRequest:async()=>{await ey?.()}})}this._tokenStoreInit=n.tokenStore,this._redirectMethod=n.redirectMethod||((0,er.isBrowserLike)()?"window":"none"),this._redirectMethod=n.redirectMethod||"nextjs",this._urlOptions=n.urls??{},this._oauthScopesOnSignIn=n.oauthScopesOnSignIn??{},(0,er.isBrowserLike)()&&("cookie"===n.tokenStore||"nextjs-cookie"===n.tokenStore)&&((0,E.runAsynchronously)(this._trustedParentDomainCache.getOrWait([window.location.hostname],"write-only")),this._ensureCrossSubdomainCookieExists()),s&&s.uniqueIdentifier&&(this._uniqueIdentifier=s.uniqueIdentifier,this._initUniqueIdentifier()),this._analyticsOptions=n.analytics;const l=async()=>(this._ensurePersistentTokenStore(),await this.getPartialUser({from:"token",or:"anonymous-if-exists"}))?await this._getSession():(await this.getUser({or:"anonymous"}))._internalSession,p=this._analyticsOptions?.enabled!==!1,u=function(t){return{...t?.replays,enabled:t?.replays?.enabled??!0}}(this._analyticsOptions);if(p&&(0,er.isBrowserLike)()&&this._hasPersistentTokenStore()&&u.enabled&&(this._sessionRecorder=new e3({projectId:this.projectId,sendBatch:async(t,r)=>await this._interface.sendSessionReplayBatch(t,await l(),r)},u),this._sessionRecorder.start()),p&&(0,er.isBrowserLike)()&&this._hasPersistentTokenStore()&&(this._eventTracker=new e5({projectId:this.projectId,sendBatch:async(t,r)=>await this._interface.sendAnalyticsEventBatch(t,await l(),r)}),this._eventTracker.start()),(0,er.isBrowserLike)()&&(this._isOAuthCallbackUrlHosted()||this._currentUrlLooksLikeNestedCrossDomainOAuthCallback())&&this._currentUrlLooksLikeHexclaveOAuthCallback()&&this._trackPendingAuthResolution(async()=>{(0,er.isBrowserLike)()&&await this.callOAuthCallback({dontWarnAboutMissingQueryParams:!0})}),(0,er.isBrowserLike)()){const t=new URL(window.location.href);this._trackPendingAuthResolution(async()=>{await this._maybeHandleNestedCrossDomainAuth(t)})}(0,er.isBrowserLike)()&&!1!==n.devTool&&function(r){ty=r,function(){if(tm&&(tm(),tm=null),!tf()||!ty||!(0,tp.canMountIntoDom)())return;let r=++tb,i=ty;(0,E.runAsynchronously)(async()=>{let s=await (!tg&&(tg=t.A(295567).then(t=>t.createDevTool).catch(t=>{throw tg=null,t})),tg);r!==tb||tf()&&ty===i&&(0,tp.canMountIntoDom)()&&(tm=s(i))},{noErrorLogging:!0,onError:t=>{(0,x.captureError)("dev-tool-mount",t)}})}()}(this),(0,er.isBrowserLike)()&&function(r){tu=r,(0,tp.canMountIntoDom)()&&function(){try{if("1"!==sessionStorage.getItem(tl.CLICKMAP_OVERLAY_RESUME_STORAGE_KEY))return!1;return sessionStorage.removeItem(tl.CLICKMAP_OVERLAY_RESUME_STORAGE_KEY),!0}catch{return!1}}()&&function(){if(tc||!tu||!(0,tp.canMountIntoDom)())return;let r=++td,i=tu;(0,E.runAsynchronously)(async()=>{let s=await (!th&&(th=t.A(273427).then(t=>t.openClickmapOverlay).catch(t=>{throw th=null,t})),th);r!==td||!tc&&tu===i&&(0,tp.canMountIntoDom)()&&(tc=s(i,()=>{tc=null}))},{noErrorLogging:!0,onError:t=>{(0,x.captureError)("clickmap-mount",t)}})}()}(this)}_initUniqueIdentifier(){if(!this._uniqueIdentifier)throw new x.HexclaveAssertionError("Unique identifier not initialized");if(tT.has(this._uniqueIdentifier))throw new x.HexclaveAssertionError("A Stack client app with the same unique identifier already exists");tT.set(this._uniqueIdentifier,[this._extraOptions?.checkString??void 0,this])}_trackPendingAuthResolution(t){let r=(async()=>{await Promise.resolve();try{await t()}catch(t){(0,x.captureError)("pending-auth-resolution-failed",t)}})();this._pendingAuthResolutionPromises.push(r),(0,E.runAsynchronously)(async()=>{try{await r}finally{this._pendingAuthResolutionPromises=this._pendingAuthResolutionPromises.filter(t=>t!==r)}})}async _awaitPendingAuthResolutions(t,r){r?.awaitPendingAuthResolutions!==!1&&void 0===t&&this._hasPersistentTokenStore()&&0!==this._pendingAuthResolutionPromises.length&&await Promise.all(this._pendingAuthResolutionPromises)}_usePendingAuthResolutions(t){void 0===t&&this._hasPersistentTokenStore()&&0!==this._pendingAuthResolutionPromises.length&&(0,A.use)(Promise.all(this._pendingAuthResolutionPromises))}_isOAuthCallbackUrlHosted(){let t=this._urlOptions.oauthCallback??this._urlOptions.default;return"string"!=typeof t&&t?.type==="hosted"}_currentUrlLooksLikeOAuthCallback(){return!1}_currentUrlLooksLikeHexclaveOAuthCallback(){return!1}_currentUrlLooksLikeNestedCrossDomainOAuthCallback(){return!1}_getOAuthCallbackRedirectUri(){if(!this._isOAuthCallbackUrlHosted())return this.urls.oauthCallback;throw new x.HexclaveAssertionError("Hosted OAuth callback URLs require a browser environment to use the current URL as the redirect URI")}async _fetchCurrentRefreshTokenIdIfSignedIn(t){let r=await (await this._getSession(t?.overrideTokenStoreInit,t)).fetchNewTokens();return r?.refreshToken==null?null:r.accessToken.payload.refresh_token_id}async _addNestedCrossDomainAuthParamsToRedirectUrl(t){let r=new URL(t.url,t.currentUrl);if(r.origin===t.currentUrl.origin)return t.url;let i=await this._fetchCurrentRefreshTokenIdIfSignedIn({awaitPendingAuthResolutions:t.awaitPendingAuthResolutions,overrideTokenStoreInit:t.overrideTokenStoreInit});return null==i?t.url:(r.searchParams.set("stack_nested_cross_domain_auth_refresh_token_id",i),r.searchParams.set("stack_nested_cross_domain_auth_callback_url",new URL(this._getOAuthCallbackRedirectUri(),t.currentUrl).toString()),r.toString())}async _maybeHandleNestedCrossDomainAuth(t){return!1}_getUniqueIdentifier(){return this._uniqueIdentifier||(this._uniqueIdentifier=(0,eh.generateUuid)(),this._initUniqueIdentifier()),this._uniqueIdentifier}async _checkFeatureSupport(t,r){return await this._interface.checkFeatureSupport({...r,name:t})}_useCheckFeatureSupport(t,r){throw(0,E.runAsynchronously)(this._checkFeatureSupport(t,r)),new x.HexclaveAssertionError(`${t} is not currently supported. Please reach out to Stack support for more information.`)}get _legacyRefreshTokenCookieName(){return`stack-refresh-${this.projectId}`}get _refreshTokenCookieName(){return`hexclave-refresh-${this.projectId}`}_getRefreshTokenDefaultCookieNameForSecure(t){return`${t?"__Host-":""}${this._refreshTokenCookieName}--default`}_getCustomRefreshCookieName(t){let r=(0,Y.encodeBase32)(new TextEncoder().encode(t.toLowerCase()));return`${this._refreshTokenCookieName}--custom-${r}`}_getDomainFromCustomRefreshCookieName(t){for(let r of[this._refreshTokenCookieName,this._legacyRefreshTokenCookieName]){let i=`${r}--custom-`;if(t.startsWith(i))try{return new TextDecoder().decode((0,Y.decodeBase32)(t.slice(i.length)))}catch{break}}return null}_formatRefreshCookieValue(t,r){return JSON.stringify({refresh_token:t,updated_at_millis:r})}_formatAccessCookieValue(t,r){return t&&r?JSON.stringify([t,r]):null}_parseStructuredRefreshCookie(t){if(!t)return null;let r=el(t);if("ok"!==r.status||"object"!=typeof r.data||null===r.data)return console.warn("Failed to parse structured refresh cookie"),null;let i=r.data,s="refresh_token"in i&&"string"==typeof i.refresh_token?i.refresh_token:null,n="updated_at_millis"in i&&"number"==typeof i.updated_at_millis?i.updated_at_millis:null;return s?{refreshToken:s,updatedAt:n}:(console.warn("Refresh token not found in structured refresh cookie"),null)}_extractRefreshTokenFromCookieMap(t){let{legacyNames:r,structuredPrefixes:i}=this._getRefreshTokenCookieNamePatterns(),s=[`${this._refreshTokenCookieName}--`,`__Host-${this._refreshTokenCookieName}--`],n=r=>{let i=null;for(let[s,n]of Object.entries(t)){if(!r.some(t=>s.startsWith(t)))continue;let t=this._parseStructuredRefreshCookie(n);if(!t)continue;let a=t.updatedAt??-1/0,o=i?.updatedAt??-1/0;(!i||a>o)&&(i=t)}return i},a=n(s);if(a)return{refreshToken:a.refreshToken,updatedAt:a.updatedAt??null};for(let i of r){let r=t[i];if(r)return{refreshToken:r,updatedAt:null}}let o=n(i);return o?{refreshToken:o.refreshToken,updatedAt:o.updatedAt??null}:{refreshToken:null,updatedAt:null}}_getTokensFromCookies(t){let{refreshToken:r}=this._extractRefreshTokenFromCookieMap(t),i=t[this._accessTokenCookieName]??t[this._legacyAccessTokenCookieName]??null,s=null;if(i&&i.startsWith('["')){let t=el(i);"ok"===t.status&&"object"==typeof t.data&&null!==t.data&&Array.isArray(t.data)&&2===t.data.length&&"string"==typeof t.data[0]&&"string"==typeof t.data[1]?t.data[0]===r&&(s=t.data[1]):console.warn("Access token cookie has invalid format")}return{refreshToken:r,accessToken:s}}_getCurrentBrowserCookieTokenStoreValue(t){let r=this._getTokensFromCookies(this._getAllBrowserCookies());return{refreshToken:r.refreshToken,accessToken:r.accessToken??(t?.refreshToken===r.refreshToken?t.accessToken:null)}}get _accessTokenCookieName(){return"hexclave-access"}get _legacyAccessTokenCookieName(){return"stack-access"}_getAllBrowserCookies(){if(!(0,er.isBrowserLike)())throw new x.HexclaveAssertionError("Cannot get browser cookies on the server!");return ef.parseCookie(document.cookie||"")}_getRefreshTokenCookieNamePatterns(){return{legacyNames:[this._legacyRefreshTokenCookieName,"stack-refresh"],structuredPrefixes:[`${this._refreshTokenCookieName}--`,`__Host-${this._refreshTokenCookieName}--`,`${this._legacyRefreshTokenCookieName}--`,`__Host-${this._legacyRefreshTokenCookieName}--`]}}_collectRefreshTokenCookieNames(t){let{legacyNames:r,structuredPrefixes:i}=this._getRefreshTokenCookieNamePatterns(),s=new Set;for(let i of r)t[i]&&s.add(i);for(let r of Object.keys(t))i.some(t=>r.startsWith(t))&&s.add(r);return s}_prepareRefreshCookieUpdate(t,r,i,s){let n=this._collectRefreshTokenCookieNames(t);n.delete(s);let a=r?Date.now():null;return{updatedAt:a,refreshCookieValue:r&&null!==a?this._formatRefreshCookieValue(r,a):null,accessTokenPayload:this._formatAccessCookieValue(r,i),cookieNamesToDelete:[...n]}}_ensureCrossSubdomainCookieExists(){(0,E.runAsynchronously)(async()=>{let t=window.location.hostname,r=await this._trustedParentDomainCache.getOrWait([t],"read-write");if("error"===r.status||!r.data)return;let i=this._getAllBrowserCookies(),s=this._getCustomRefreshCookieName(r.data);if(i[s])return;let{refreshToken:n,updatedAt:a}=this._extractRefreshTokenFromCookieMap(i);n&&a&&e$(s,this._formatRefreshCookieValue(n,a),{maxAge:31536e3,domain:r.data})})}_queueCustomRefreshCookieUpdate(t,r,i){(0,E.runAsynchronously)(async()=>{let s;this._mostRecentQueuedCookieRefreshIndex++;let n=this._mostRecentQueuedCookieRefreshIndex;if(!(s=(0,er.isBrowserLike)()?window.location.hostname:await tA()))return void console.warn("No hostname found when queueing custom refresh cookie update");let a=await this._trustedParentDomainCache.getOrWait([s],"read-write"),o={maxAge:31536e3,noOpIfServerComponent:!0},l=async(t,r)=>{let s=this._getCustomRefreshCookieName(t),n={...o,domain:t};"browser"===i?e$(s,r,n):await eV(s,r,n)};if("error"===a.status||!a.data||n!==this._mostRecentQueuedCookieRefreshIndex)return;let p=t&&r?this._formatRefreshCookieValue(t,r):null;await l(a.data,p);let u=await eM(),c=this._getRefreshTokenDefaultCookieNameForSecure(u);"browser"===i?e$(c,null,o):await eV(c,null,o)})}async _getTrustedRedirectConfig(){let t=w.Result.orThrow(await this._currentProjectCache.getOrWait([],"write-only"));return{allowLocalhost:t.config.allow_localhost,trustedDomains:[...t.config.domains.map(t=>t.domain),new URL((0,eX.getHostedHandlerUrl)({projectId:this.projectId,pagePath:""})).origin]}}async _getTrustedParentDomain(t){return(0,ei.getTrustedParentDomain)(t,(await this._getTrustedRedirectConfig()).trustedDomains)}_getBrowserCookieTokenStore(){if(!(0,er.isBrowserLike)())throw Error("Cannot use cookie token store on the server!");if(null===this._storedBrowserCookieTokenStore){this._storedBrowserCookieTokenStore=new ea.Store(this._getCurrentBrowserCookieTokenStoreValue(null));let t=!0;setInterval(()=>{if(t){let t=this._storedBrowserCookieTokenStore.get(),r=this._getCurrentBrowserCookieTokenStoreValue(t);(0,z.deepPlainEquals)(r,t)||this._storedBrowserCookieTokenStore.set(r)}},100),this._storedBrowserCookieTokenStore.onChange(r=>{try{let i=r.refreshToken,s="https:"===window.location.protocol,n=this._getRefreshTokenDefaultCookieNameForSecure(s),{updatedAt:a,refreshCookieValue:o,accessTokenPayload:l,cookieNamesToDelete:p}=this._prepareRefreshCookieUpdate(this._getAllBrowserCookies(),i,r.accessToken??null,n);e$(n,o,{maxAge:31536e3,secure:s}),e$(this._accessTokenCookieName,l,{maxAge:86400}),p.forEach(t=>{let r=this._getDomainFromCustomRefreshCookieName(t);eK(t,r?{domain:r}:{})}),this._queueCustomRefreshCookieUpdate(i,a,"browser"),t=!0}catch(r){if((0,er.isBrowserLike)())throw r;t=!1}})}else{let t=this._storedBrowserCookieTokenStore.get(),r=this._getCurrentBrowserCookieTokenStoreValue(t);(0,z.deepPlainEquals)(r,t)||this._storedBrowserCookieTokenStore.set(r)}return this._storedBrowserCookieTokenStore}_getOrCreateTokenStore(t,r){let i=void 0===r?this._tokenStoreInit:r;switch(i){case"cookie":return this._getBrowserCookieTokenStore();case"nextjs-cookie":if((0,er.isBrowserLike)())return this._getBrowserCookieTokenStore();{let r=new ea.Store(this._getTokensFromCookies(t.getAll()));return r.onChange(r=>{(0,E.runAsynchronously)(async()=>{let i=r.refreshToken,s=await eM(),n=this._getRefreshTokenDefaultCookieNameForSecure(s),{updatedAt:a,refreshCookieValue:o,accessTokenPayload:l,cookieNamesToDelete:p}=this._prepareRefreshCookieUpdate(t.getAll(),i,r.accessToken??null,n);await Promise.all([eV(n,o,{maxAge:31536e3,noOpIfServerComponent:!0}),eV(this._accessTokenCookieName,l,{maxAge:86400,noOpIfServerComponent:!0})]),p.length>0&&await Promise.all(p.map(t=>{let r=this._getDomainFromCustomRefreshCookieName(t);return eq(t,{noOpIfServerComponent:!0,...r?{domain:r}:{}})})),this._queueCustomRefreshCookieUpdate(i,a,"server")})}),r}case"memory":return this._memoryTokenStore;default:if(null===i)return(0,C.createEmptyTokenStore)();if("object"==typeof i&&"headers"in i){if(this._requestTokenStores.has(i))return this._requestTokenStores.get(i);let r=tP(i.headers,"authorization");if(r){let t=function(t){let r,i=t.match(/^Bearer\s+(.+)$/i);if(null==i)return null;let s=i[1].trim(),n=s.startsWith(tS)?tS:s.startsWith(tE)?tE:null;if(null==n)return null;let a=s.slice(n.length);if(0===a.length)throw Error("Invalid Authorization header format. Expected `Bearer stackauth_<base64(getAuthJson())>`.");try{let t=new TextDecoder().decode((0,Y.decodeBase64)(a));r=JSON.parse(t)}catch(t){throw Error("Invalid stackauth authorization header.",{cause:t})}if(null==r||"object"!=typeof r||Array.isArray(r))throw Error("Invalid stackauth authorization payload. Expected an object.");let o=Reflect.get(r,"accessToken"),l=Reflect.get(r,"refreshToken");if(null!=o&&"string"!=typeof o)throw Error("Invalid stackauth authorization payload. `accessToken` must be a string or null.");if(null!=l&&"string"!=typeof l)throw Error("Invalid stackauth authorization payload. `refreshToken` must be a string or null.");return{accessToken:o??null,refreshToken:l??null}}(r);if(null!=t){let r=new ea.Store({accessToken:t.accessToken,refreshToken:t.refreshToken});return this._requestTokenStores.set(i,r),r}}let s=tP(i.headers,"x-stack-auth");if(s){let r;try{if(r=JSON.parse(s),"object"!=typeof r)throw Error("x-stack-auth header must be a JSON object");if(null===r)throw Error("x-stack-auth header must not be null")}catch(t){throw Error("Invalid x-stack-auth header.",{cause:t})}return this._getOrCreateTokenStore(t,{accessToken:r.accessToken??null,refreshToken:r.refreshToken??null})}let n=tP(i.headers,"cookie"),a=ef.parseCookie(n||""),o=new ea.Store(this._getTokensFromCookies(a));return this._requestTokenStores.set(i,o),o}if("accessToken"in i||"refreshToken"in i)return new ea.Store({refreshToken:i.refreshToken,accessToken:i.accessToken});throw Error(`Invalid token store ${i}`)}}_useTokenStore(t){(0,A.suspendIfSsr)();let r=eD();return this._getOrCreateTokenStore(r,t)}_getSessionFromTokenStore(t){let r=t.get(),i=I.InternalSession.calculateSessionKey(r),s=i?this._sessionsByTokenStoreAndSessionKey.get(t)?.get(i):null;if(s)return s;let n=this._interface.createSession({refreshToken:r.refreshToken,accessToken:r.accessToken});n.onAccessTokenChange(r=>{t.update(t=>I.InternalSession.calculateSessionKey(t)===i?{...t,accessToken:r?.token??null}:t)}),n.onInvalidate(()=>{t.update(t=>I.InternalSession.calculateSessionKey(t)===i?{...t,accessToken:null,refreshToken:null}:t)});let a=this._sessionsByTokenStoreAndSessionKey.get(t)??new Map;return this._sessionsByTokenStoreAndSessionKey.set(t,a),a.set(i,n),n}async _getSession(t,r){await this._awaitPendingAuthResolutions(t,r);let i=this._getOrCreateTokenStore(await this._createCookieHelper(t),t);return this._getSessionFromTokenStore(i)}_useSession(t){this._usePendingAuthResolutions(t);let r=this._useTokenStore(t),i=(0,S.useCallback)(t=>{var i;let s,n,a,o,l;return s=(i={tokenStore:r,getSession:()=>this._getSessionFromTokenStore(r),onTokenStoreChange:t}).minMillisUntilExpiration??3e4,n=i.maxMillisSinceIssued??6e4,o=(a=i.getSession()).startRefreshingAccessToken(s,n),l=i.tokenStore.onChange(()=>{let t=i.getSession();t.sessionKey!==a.sessionKey&&(o.unsubscribe(),o=(a=t).startRefreshingAccessToken(s,n)),i.onTokenStoreChange()}),()=>{l.unsubscribe(),o.unsubscribe()}},[r]),s=(0,S.useCallback)(()=>this._getSessionFromTokenStore(r),[r]);return S.default.useSyncExternalStore(i,s,s)}async _signInToAccountWithTokens(t){if(!("accessToken"in t)||!("refreshToken"in t))throw new x.HexclaveAssertionError("Invalid tokens object; can't sign in with this",{tokens:t});let r=this._getOrCreateTokenStore(await this._createCookieHelper());r.set(t);let i=this._getSessionFromTokenStore(r);i.updateAccessToken(t),(0,E.runAsynchronously)(this._currentUserCache.getOrWait([i],"write-only"))}_getTokenStoreInitForFreshTokens(t){if(null!=t.accessToken)return{accessToken:t.accessToken,refreshToken:t.refreshToken}}_hasPersistentTokenStore(t){return(void 0!==t?t:this._tokenStoreInit)!==null}_ensurePersistentTokenStore(t){if(!this._hasPersistentTokenStore(t))throw Error("Cannot call this function on a Stack app without a persistent token store. Make sure the tokenStore option on the constructor is set to a non-null value when initializing Stack.\n\nStack uses token stores to access access tokens of the current user. For example, on web frontends it is commonly the string value 'cookies' for cookie storage.")}_isInternalProject(){return"internal"===this.projectId}_ensureInternalProject(){if(!this._isInternalProject())throw Error("Cannot call this function on a Stack app with a project ID other than 'internal'.")}_clientProjectFromCrud(t){return{id:t.id,displayName:t.display_name,config:{signUpEnabled:t.config.sign_up_enabled,credentialEnabled:t.config.credential_enabled,magicLinkEnabled:t.config.magic_link_enabled,passkeyEnabled:t.config.passkey_enabled,clientTeamCreationEnabled:t.config.client_team_creation_enabled,clientUserDeletionEnabled:t.config.client_user_deletion_enabled,allowTeamApiKeys:t.config.allow_team_api_keys,allowUserApiKeys:t.config.allow_user_api_keys,oauthProviders:t.config.enabled_oauth_providers.map(t=>({id:t.id}))}}}_clientPermissionFromCrud(t){return{id:t.id}}_clientTeamUserFromCrud(t){return{id:t.user_id,teamProfile:{displayName:t.display_name,profileImageUrl:t.profile_image_url}}}_clientSentTeamInvitationFromCrud(t,r){return{id:r.id,recipientEmail:r.recipient_email,expiresAt:new Date(r.expires_at_millis),revoke:async()=>{await this._interface.revokeTeamInvitation(r.id,r.team_id,t),await this._teamInvitationsCache.refresh([t,r.team_id])}}}_clientReceivedTeamInvitationFromCrud(t,r){let i=this;return{id:r.id,teamId:r.team_id,teamDisplayName:r.team_display_name,recipientEmail:r.recipient_email,expiresAt:new Date(r.expires_at_millis),accept:async()=>{await i._interface.acceptTeamInvitationById(r.id,t),await Promise.all([i._currentUserTeamInvitationsCache.refresh([t]),i._currentUserTeamsCache.refresh([t]),i._teamInvitationsCache.refresh([t,r.team_id])])}}}_baseApiKeyFromCrud(t){return{id:t.id,description:t.description,expiresAt:t.expires_at_millis?new Date(t.expires_at_millis):void 0,manuallyRevokedAt:t.manually_revoked_at_millis?new Date(t.manually_revoked_at_millis):null,createdAt:new Date(t.created_at_millis),..."team"===t.type?{type:"team",teamId:t.team_id}:{type:"user",userId:t.user_id},value:"string"==typeof t.value?t.value:{lastFour:t.value.last_four},isValid:function(){return null===this.whyInvalid()},whyInvalid:function(){return this.manuallyRevokedAt?"manually-revoked":this.expiresAt&&this.expiresAt<new Date?"expired":null}}}_clientApiKeyFromCrud(t,r){return{...this._baseApiKeyFromCrud(r),async revoke(){await this.update({revoked:!0})},update:async i=>{await this._interface.updateProjectApiKey("team"===r.type?{team_id:r.team_id}:{user_id:r.user_id},r.id,i,t,"client"),"team"===r.type?await this._teamApiKeysCache.refresh([t,r.team_id]):await this._userApiKeysCache.refresh([t])}}}_clientTeamFromCrud(t,r){let i=this;return{id:t.id,displayName:t.display_name,profileImageUrl:t.profile_image_url,clientMetadata:t.client_metadata,clientReadOnlyMetadata:t.client_read_only_metadata,...this._createCustomer(t.id,"team",r),async inviteUser(s){await i._interface.sendTeamInvitation({teamId:t.id,email:s.email,session:r,callbackUrl:s.callbackUrl??q(i._getUrls().teamInvitation,"callbackUrl")}),await i._teamInvitationsCache.refresh([r,t.id])},listUsers:async()=>w.Result.orThrow(await i._teamMemberProfilesCache.getOrWait([r,t.id],"write-only")).map(t=>i._clientTeamUserFromCrud(t)),useUsers:()=>(0,C.useAsyncCache)(i._teamMemberProfilesCache,[r,t.id],"team.useUsers()").map(t=>i._clientTeamUserFromCrud(t)),listInvitations:async()=>w.Result.orThrow(await i._teamInvitationsCache.getOrWait([r,t.id],"write-only")).map(t=>i._clientSentTeamInvitationFromCrud(r,t)),useInvitations:()=>(0,C.useAsyncCache)(i._teamInvitationsCache,[r,t.id],"team.useInvitations()").map(t=>i._clientSentTeamInvitationFromCrud(r,t)),async update(s){await i._interface.updateTeam({data:{display_name:s.displayName,profile_image_url:s.profileImageUrl,client_metadata:s.clientMetadata},teamId:t.id},r),await i._currentUserTeamsCache.refresh([r])},async delete(){await i._interface.deleteTeam(t.id,r),await i._currentUserTeamsCache.refresh([r])},useApiKeys:()=>(0,C.useAsyncCache)(i._teamApiKeysCache,[r,t.id],"team.useApiKeys()").map(t=>i._clientApiKeyFromCrud(r,t)),listApiKeys:async()=>w.Result.orThrow(await i._teamApiKeysCache.getOrWait([r,t.id],"write-only")).map(t=>i._clientApiKeyFromCrud(r,t)),async createApiKey(s){let n=await i._interface.createProjectApiKey(await W("team",t.id,s),r,"client");return await i._teamApiKeysCache.refresh([r,t.id]),i._clientApiKeyFromCrud(r,n)}}}_clientContactChannelFromCrud(t,r){let i=this;return{id:t.id,value:t.value,type:t.type,isVerified:t.is_verified,isPrimary:t.is_primary,usedForAuth:t.used_for_auth,async sendVerificationEmail(s){await i._interface.sendCurrentUserContactChannelVerificationEmail(t.id,s?.callbackUrl||q(i._getUrls().emailVerification,"callbackUrl"),r)},async update(s){await i._interface.updateClientContactChannel(t.id,{value:s.value,used_for_auth:s.usedForAuth,is_primary:s.isPrimary},r),await i._clientContactChannelsCache.refresh([r])},async delete(){await i._interface.deleteClientContactChannel(t.id,r),await i._clientContactChannelsCache.refresh([r])}}}_clientNotificationCategoryFromCrud(t,r){let i=this;return{id:t.notification_category_id,name:t.notification_category_name,enabled:t.enabled,canDisable:t.can_disable,async setEnabled(s){await i._interface.setNotificationsEnabled(t.notification_category_id,s,r),await i._notificationCategoriesCache.refresh([r])}}}_clientOAuthProviderFromCrud(t,r){let i=this;return{id:t.id,type:t.type,userId:t.user_id,email:t.email,allowSignIn:t.allow_sign_in,allowConnectedAccounts:t.allow_connected_accounts,async update(s){try{return await i._interface.updateOAuthProvider(t.user_id,t.id,{allow_sign_in:s.allowSignIn,allow_connected_accounts:s.allowConnectedAccounts},r),await Promise.all([i._currentUserOAuthProvidersCache.refresh([r]),i._currentUserConnectedAccountsCache.refresh([r])]),w.Result.ok(void 0)}catch(t){if(P.KnownErrors.OAuthProviderAccountIdAlreadyUsedForSignIn.isInstance(t))return w.Result.error(t);throw t}},async delete(){await i._interface.deleteOAuthProvider(t.user_id,t.id,r),await Promise.all([i._currentUserOAuthProvidersCache.refresh([r]),i._currentUserConnectedAccountsCache.refresh([r])])}}}_clientItemFromCrud(t){return{displayName:t.display_name,quantity:t.quantity,nonNegativeQuantity:Math.max(0,t.quantity)}}_customerProductsFromResponse(t){return Object.assign(t.items.map(t=>({id:t.id,quantity:t.quantity,displayName:t.product.display_name,customerType:t.product.customer_type,isServerOnly:t.product.server_only,stackable:t.product.stackable,type:t.type,subscription:t.subscription?{subscriptionId:t.subscription.subscription_id,currentPeriodEnd:t.subscription.current_period_end?new Date(t.subscription.current_period_end):null,cancelAtPeriodEnd:t.subscription.cancel_at_period_end,isCancelable:t.subscription.is_cancelable}:null,switchOptions:t.switch_options?.map(t=>({productId:t.product_id,displayName:t.product.display_name,prices:t.product.prices}))})),{nextCursor:t.pagination.next_cursor??null})}_customerInvoicesFromResponse(t){return Object.assign(t.items.map(t=>({status:t.status,amountTotal:t.amount_total,hostedInvoiceUrl:t.hosted_invoice_url,createdAt:new Date(t.created_at_millis)})),{nextCursor:t.pagination.next_cursor??null})}_customerBillingFromResponse(t){return{hasCustomer:t.has_customer,defaultPaymentMethod:t.default_payment_method}}_createAuth(t){let r=this;return{_internalSession:t,currentSession:{async getTokens(){let r=await t.getOrFetchLikelyValidTokens(2e4,75e3);return{accessToken:r?.accessToken.token??null,refreshToken:r?.refreshToken?.token??null}},useTokens(){let r=(0,S.useCallback)(r=>{let{unsubscribe:i}=t.onInvalidate(r),{unsubscribe:s}=t.onAccessTokenChange(r);return()=>{i(),s()}},[t]),i=(0,S.useCallback)(()=>t.isKnownToBeInvalid()?null:t.getAccessTokenIfNotExpiredYet(2e4,75e3)?.token??null,[t]),s=S.default.useSyncExternalStore(r,i,i);return null!==s||t.isKnownToBeInvalid()||(s=(0,A.use)(t.getOrFetchLikelyValidTokens(2e4,75e3))?.accessToken.token??null),{accessToken:s,refreshToken:t.getRefreshToken()?.token??null}}},async getAccessToken(){return(await this.currentSession.getTokens()).accessToken},useAccessToken(){return this.currentSession.useTokens().accessToken},async getRefreshToken(){return(await this.currentSession.getTokens()).refreshToken},useRefreshToken(){return this.currentSession.useTokens().refreshToken},async getAuthorizationHeader(){return t_(await this.getAuthJson())},useAuthorizationHeader(){return t_(this.useAuthJson())},async getAuthHeaders(){return{"x-stack-auth":JSON.stringify(await this.getAuthJson())}},useAuthHeaders(){return{"x-stack-auth":JSON.stringify(this.useAuthJson())}},async getAuthJson(){return await this.currentSession.getTokens()},useAuthJson(){return this.currentSession.useTokens()},signOut:i=>r._signOut(t,i)}}_editableTeamProfileFromCrud(t,r){let i=this;return{displayName:t.display_name,profileImageUrl:t.profile_image_url,async update(s){await i._interface.updateTeamMemberProfile({teamId:t.team_id,userId:t.user_id,profile:{display_name:s.displayName,profile_image_url:s.profileImageUrl}},r),await i._currentUserTeamProfileCache.refresh([r,t.team_id])}}}_createBaseUser(t){return{id:t.id,displayName:t.display_name,primaryEmail:t.primary_email,primaryEmailVerified:t.primary_email_verified,profileImageUrl:t.profile_image_url,signedUpAt:new Date(t.signed_up_at_millis),clientMetadata:t.client_metadata,clientReadOnlyMetadata:t.client_read_only_metadata,hasPassword:t.has_password,emailAuthEnabled:t.auth_with_email,otpAuthEnabled:t.otp_auth_enabled,oauthProviders:t.oauth_providers,passkeyAuthEnabled:t.passkey_auth_enabled,isMultiFactorRequired:t.requires_totp_mfa,isAnonymous:t.is_anonymous,isRestricted:t.is_restricted,restrictedReason:t.restricted_reason,toClientJson:()=>t}}_createUserExtraFromCurrent(t,r){let i=this;return{getActiveSessions:async()=>(await i._interface.listSessions(r)).items.map(t=>i._clientSessionFromCrud(t)),async revokeSession(t){await i._interface.deleteSession(t,r)},setDisplayName(t){return this.update({displayName:t})},setClientMetadata(t){return this.update({clientMetadata:t})},async setSelectedTeam(t){await this.update({selectedTeamId:"string"==typeof t?t:t?.id??null})},getConnectedAccount:async function t(t,s){let n=s?.scopes?.join(" ")??"";if("object"==typeof t&&"provider"in t&&"providerAccountId"in t){let{provider:s,providerAccountId:n}=t,a=w.Result.orThrow(await i._currentUserConnectedAccountsCache.getOrWait([r],"write-only")).find(t=>t.provider===s&&t.providerAccountId===n);return a||null}return w.Result.orThrow(await i._currentUserOAuthConnectionCache.getOrWait([r,t,n,s?.or==="redirect"],"write-only"))},useConnectedAccount:function(t,s){let n=s?.scopes?.join(" ")??"";if("object"==typeof t&&"provider"in t&&"providerAccountId"in t){let{provider:s,providerAccountId:n}=t;return(0,C.useAsyncCache)(i._currentUserConnectedAccountsCache,[r],"user.useConnectedAccount()").find(t=>t.provider===s&&t.providerAccountId===n)??null}return(0,C.useAsyncCache)(i._currentUserOAuthConnectionCache,[r,t,n,s?.or==="redirect"],"user.useConnectedAccount()")},listConnectedAccounts:async()=>w.Result.orThrow(await i._currentUserConnectedAccountsCache.getOrWait([r],"write-only")),useConnectedAccounts:()=>(0,C.useAsyncCache)(i._currentUserConnectedAccountsCache,[r],"user.useConnectedAccounts()"),async linkConnectedAccount(t,s){let n=s?.scopes?.join(" ")??"",a=await eJ(i._interface,{provider:t,redirectUrl:i._getOAuthCallbackRedirectUri(),errorRedirectUrl:i._getUrls().error,providerScope:(0,G.mergeScopeStrings)(n,(i._oauthScopesOnSignIn[t]??[]).join(" "))},r);return await i._redirectTo({url:a}),await (0,E.neverResolve)()},async getOrLinkConnectedAccount(t,s){for(let n of w.Result.orThrow(await i._currentUserConnectedAccountsCache.getOrWait([r],"write-only")).filter(r=>r.provider===t))if("ok"===(await n.getAccessToken({scopes:s?.scopes})).status)return n;return await this.linkConnectedAccount(t,s),await (0,E.neverResolve)()},useOrLinkConnectedAccount(t,s){let n=s?.scopes?.join(" ")??"";return(0,C.useAsyncCache)(i._currentUserValidConnectedAccountForProviderCache,[r,t,n],"user.useOrLinkConnectedAccount()")},async getTeam(t){return(await this.listTeams()).find(r=>r.id===t)??null},useTeam(t){let r=this.useTeams();return(0,S.useMemo)(()=>r.find(r=>r.id===t)??null,[r,t])},listTeams:async()=>w.Result.orThrow(await i._currentUserTeamsCache.getOrWait([r],"write-only")).map(t=>i._clientTeamFromCrud(t,r)),useTeams(){let t=(0,C.useAsyncCache)(i._currentUserTeamsCache,[r],"user.useTeams()");return(0,S.useMemo)(()=>t.map(t=>i._clientTeamFromCrud(t,r)),[t])},async createTeam(t){let s=await i._interface.createClientTeam({display_name:t.displayName,profile_image_url:t.profileImageUrl,creator_user_id:"me"},r);return await i._currentUserTeamsCache.refresh([r]),await this.update({selectedTeamId:s.id}),i._clientTeamFromCrud(s,r)},async leaveTeam(t){await i._interface.leaveTeam(t.id,r)},listTeamInvitations:async()=>w.Result.orThrow(await i._currentUserTeamInvitationsCache.getOrWait([r],"write-only")).map(t=>i._clientReceivedTeamInvitationFromCrud(r,t)),useTeamInvitations(){let t=(0,C.useAsyncCache)(i._currentUserTeamInvitationsCache,[r],"user.useTeamInvitations()");return(0,S.useMemo)(()=>t.map(t=>i._clientReceivedTeamInvitationFromCrud(r,t)),[t])},async listPermissions(t,s){if(t&&"id"in t){let n=s?.recursive??!0;return w.Result.orThrow(await i._currentUserPermissionsCache.getOrWait([r,t.id,n],"write-only")).map(t=>i._clientPermissionFromCrud(t))}{let s=t?.recursive??!0;return w.Result.orThrow(await i._currentUserProjectPermissionsCache.getOrWait([r,s],"write-only")).map(t=>i._clientPermissionFromCrud(t))}},usePermissions(t,s){if(t&&"id"in t){let n=s?.recursive??!0,a=(0,C.useAsyncCache)(i._currentUserPermissionsCache,[r,t.id,n],"user.usePermissions()");return(0,S.useMemo)(()=>a.map(t=>i._clientPermissionFromCrud(t)),[a])}{let s=t?.recursive??!0,n=(0,C.useAsyncCache)(i._currentUserProjectPermissionsCache,[r,s],"user.usePermissions()");return(0,S.useMemo)(()=>n.map(t=>i._clientPermissionFromCrud(t)),[n])}},usePermission(t,r){if(t&&"string"!=typeof t){let i=this.usePermissions(t);return(0,S.useMemo)(()=>i.find(t=>t.id===r)??null,[i,r])}{let r=this.usePermissions();return(0,S.useMemo)(()=>r.find(r=>r.id===t)??null,[r,t])}},async getPermission(t,r){return t&&"string"!=typeof t?(await this.listPermissions(t)).find(t=>t.id===r)??null:(await this.listPermissions()).find(r=>r.id===t)??null},async hasPermission(t,r){return t&&"string"!=typeof t?await this.getPermission(t,r)!==null:await this.getPermission(t)!==null},update:async t=>await i._updateClientUser(t,r),async sendVerificationEmail(s){if(!t.primary_email)throw new x.HexclaveAssertionError("User does not have a primary email");return await i._interface.sendVerificationEmail(t.primary_email,s?.callbackUrl??q(i._getUrls().emailVerification,"callbackUrl"),r)},async updatePassword(t){let s=await i._interface.updatePassword(t,r);return await i._currentUserCache.refresh([r]),s},async setPassword(t){let s=await i._interface.setPassword(t,r);return await i._currentUserCache.refresh([r]),s},selectedTeam:t.selected_team&&this._clientTeamFromCrud(t.selected_team,r),async getTeamProfile(t){let s=w.Result.orThrow(await i._currentUserTeamProfileCache.getOrWait([r,t.id],"write-only"));return i._editableTeamProfileFromCrud(s,r)},useTeamProfile(t){let s=(0,C.useAsyncCache)(i._currentUserTeamProfileCache,[r,t.id],"user.useTeamProfile()");return i._editableTeamProfileFromCrud(s,r)},async delete(){await i._interface.deleteCurrentUser(r),r.markInvalid()},listContactChannels:async()=>w.Result.orThrow(await i._clientContactChannelsCache.getOrWait([r],"write-only")).map(t=>i._clientContactChannelFromCrud(t,r)),useContactChannels:()=>(0,C.useAsyncCache)(i._clientContactChannelsCache,[r],"user.useContactChannels()").map(t=>i._clientContactChannelFromCrud(t,r)),async createContactChannel(t){let s=await i._interface.createClientContactChannel({value:t.value,type:t.type,used_for_auth:t.usedForAuth,is_primary:t.isPrimary,user_id:"me"},r);return await i._clientContactChannelsCache.refresh([r]),i._clientContactChannelFromCrud(s,r)},useNotificationCategories:()=>(0,C.useAsyncCache)(i._notificationCategoriesCache,[r],"user.useNotificationCategories()").map(t=>i._clientNotificationCategoryFromCrud(t,r)),listNotificationCategories:async()=>w.Result.orThrow(await i._notificationCategoriesCache.getOrWait([r],"write-only")).map(t=>i._clientNotificationCategoryFromCrud(t,r)),useApiKeys:()=>(0,C.useAsyncCache)(i._userApiKeysCache,[r],"user.useApiKeys()").map(t=>i._clientApiKeyFromCrud(r,t)),listApiKeys:async()=>(await i._interface.listProjectApiKeys({user_id:"me"},r,"client")).map(t=>i._clientApiKeyFromCrud(r,t)),async createApiKey(t){let s=await i._interface.createProjectApiKey(await W("user","me",t),r,"client");return await i._userApiKeysCache.refresh([r]),i._clientApiKeyFromCrud(r,s)},useOAuthProviders:()=>(0,C.useAsyncCache)(i._currentUserOAuthProvidersCache,[r],"user.useOAuthProviders()").map(t=>i._clientOAuthProviderFromCrud(t,r)),listOAuthProviders:async()=>w.Result.orThrow(await i._currentUserOAuthProvidersCache.getOrWait([r],"write-only")).map(t=>i._clientOAuthProviderFromCrud(t,r)),useOAuthProvider(t){let r=this.useOAuthProviders();return(0,S.useMemo)(()=>r.find(r=>r.id===t)??null,[r,t])},async getOAuthProvider(t){return(await this.listOAuthProviders()).find(r=>r.id===t)??null},async registerPasskey(t){let s,n=(await i._getCurrentUrl())?.hostname;if(!n)throw new x.HexclaveAssertionError("hostname must be provided if the Stack App does not have a redirect method");let a=await i._interface.initiatePasskeyRegistration({},r);if("ok"!==a.status)return w.Result.error(new P.KnownErrors.PasskeyRegistrationFailed("Failed to get initiation options for passkey registration"));let{options_json:o,code:l}=a.data;if("THIS_VALUE_WILL_BE_REPLACED.example.com"!==o.rp.id)throw new x.HexclaveAssertionError(`Expected returned RP ID from server to equal sentinel, but found ${o.rp.id}`);o.rp.id=n;try{s=await U({optionsJSON:o})}catch(t){if(t instanceof R)return w.Result.error(new P.KnownErrors.PasskeyWebAuthnError(t.message,t.name));return(0,x.captureError)("passkey-registration-failed",t),w.Result.error(new P.KnownErrors.PasskeyRegistrationFailed("Failed to start passkey registration due to unknown error"))}let p=await i._interface.registerPasskey({credential:s,code:l},r);return await i._refreshUser(r),p}}}_createInternalUserExtra(t){let r=this;return this._ensureInternalProject(),{createProject:i=>r._createProject(t,i),async transferProject(i,s){await r._interface.transferProject(t,i,s),await r._refreshProject()},listOwnedProjects:()=>r._listOwnedProjects(t),useOwnedProjects:()=>r._useOwnedProjects(t)}}_createCustomer(t,r,i){let s=this,n=i??s._interface.createSession({refreshToken:null}),a="user"===r?{userId:t}:{teamId:t};return{async getBilling(){let i=w.Result.orThrow(await s._customerBillingCache.getOrWait([n,r,t],"write-only"));return s._customerBillingFromResponse(i)},useBilling(){let i=(0,C.useAsyncCache)(s._customerBillingCache,[n,r,t],"customer.useBilling()");return s._customerBillingFromResponse(i)},async createPaymentMethodSetupIntent(){let i=await s._interface.createCustomerPaymentMethodSetupIntent(r,t,n);return{clientSecret:i.client_secret,stripeAccountId:i.stripe_account_id}},async setDefaultPaymentMethodFromSetupIntent(i){let a=await s._interface.setDefaultCustomerPaymentMethodFromSetupIntent(r,t,i,n);return await s._customerBillingCache.refresh([n,r,t]),a.default_payment_method},getItem:async t=>await s.getItem({itemId:t,...a}),useItem:t=>s.useItem({itemId:t,...a}),listProducts:async t=>await s.listProducts({...t,...a}),useProducts:t=>s.useProducts({...t,...a}),listInvoices:async t=>await s.listInvoices({...t,...a}),useInvoices:t=>s.useInvoices({...t,...a}),createCheckoutUrl:async i=>await s._interface.createCheckoutUrl(r,t,i.productId,n,i.returnUrl,"client"),async switchSubscription(i){await s._interface.switchSubscription({customer_type:r,customer_id:t,from_product_id:i.fromProductId,to_product_id:i.toProductId,price_id:i.priceId,quantity:i.quantity},n),await s._customerBillingCache.refresh([n,r,t]),"user"===r?await s._userProductsCache.invalidateWhere(([r,i])=>r===n&&i===t):await s._teamProductsCache.invalidateWhere(([r,i])=>r===n&&i===t)}}}async getItem(t){let r,i=await this._getSession();return r="userId"in t?w.Result.orThrow(await this._userItemCache.getOrWait([i,t.userId,t.itemId],"write-only")):"teamId"in t?w.Result.orThrow(await this._teamItemCache.getOrWait([i,t.teamId,t.itemId],"write-only")):w.Result.orThrow(await this._customItemCache.getOrWait([i,t.customCustomerId,t.itemId],"write-only")),this._clientItemFromCrud(r)}useItem(t){let r=this._useSession(),[i,s]="userId"in t?[this._userItemCache,t.userId]:"teamId"in t?[this._teamItemCache,t.teamId]:[this._customItemCache,t.customCustomerId],n=(0,C.useAsyncCache)(i,[r,s,t.itemId],"app.useItem()");return this._clientItemFromCrud(n)}async listProducts(t){let r=(await this.getUser())?._internalSession??await this._getSession();if("userId"in t){let i=w.Result.orThrow(await this._userProductsCache.getOrWait([r,t.userId,t.cursor??null,t.limit??null],"write-only"));return this._customerProductsFromResponse(i)}if("teamId"in t){let i=w.Result.orThrow(await this._teamProductsCache.getOrWait([r,t.teamId,t.cursor??null,t.limit??null],"write-only"));return this._customerProductsFromResponse(i)}let i=w.Result.orThrow(await this._customProductsCache.getOrWait([r,t.customCustomerId,t.cursor??null,t.limit??null],"write-only"));return this._customerProductsFromResponse(i)}async listInvoices(t){let r=await this._getSession();if("userId"in t){let i=w.Result.orThrow(await this._userInvoicesCache.getOrWait([r,t.userId,t.cursor??null,t.limit??null],"write-only"));return this._customerInvoicesFromResponse(i)}let i=w.Result.orThrow(await this._teamInvoicesCache.getOrWait([r,t.teamId,t.cursor??null,t.limit??null],"write-only"));return this._customerInvoicesFromResponse(i)}async cancelSubscription(t){let r=await this._getSession(),i=await this.getUser();if(!i)throw new P.KnownErrors.UserAuthenticationRequired;let s="teamId"in t?"team":"user",n="teamId"in t?t.teamId:i.id;await this._interface.cancelSubscription({customer_type:s,customer_id:n,product_id:t.productId,subscription_id:t.subscriptionId},r),"user"===s?await this._userProductsCache.invalidateWhere(([t,i])=>t===r&&i===n):await this._teamProductsCache.invalidateWhere(([t,i])=>t===r&&i===n)}useProducts(t){let r=this._useSession(),i=(0,C.useAsyncCache)("userId"in t?this._userProductsCache:"teamId"in t?this._teamProductsCache:this._customProductsCache,[r,"userId"in t?t.userId:"teamId"in t?t.teamId:t.customCustomerId,t.cursor??null,t.limit??null],"clientApp.useProducts()");return this._customerProductsFromResponse(i)}useInvoices(t){let r=this._useSession(),i=(0,C.useAsyncCache)("userId"in t?this._userInvoicesCache:this._teamInvoicesCache,[r,"userId"in t?t.userId:t.teamId,t.cursor??null,t.limit??null],"clientApp.useInvoices()");return this._customerInvoicesFromResponse(i)}_currentUserFromCrud(t,r){return X({...this._createBaseUser(t),...this._createAuth(r),...this._createUserExtraFromCurrent(t,r),...this._isInternalProject()?this._createInternalUserExtra(r):{},...this._createCustomer(t.id,"user",r)})}_clientSessionFromCrud(t){return{id:t.id,userId:t.user_id,createdAt:new Date(t.created_at),isImpersonation:t.is_impersonation,lastUsedAt:t.last_used_at?new Date(t.last_used_at):void 0,isCurrentSession:t.is_current_session??!1,geoInfo:t.last_used_at_end_user_ip_info}}_getOwnedAdminApp(t,i){return this._ownedAdminApps.has([i,t])||this._ownedAdminApps.set([i,t],new r.LazyStackAdminAppImpl.value({baseUrl:this._interface.options.getBaseUrl(),projectId:t,tokenStore:null,projectOwnerSession:i,noAutomaticPrefetch:!0})),this._ownedAdminApps.get([i,t])}get projectId(){return this._interface.projectId}get version(){return C.clientVersion}_getBotChallengeSiteKeys(){if(!(0,er.isBrowserLike)())return null;let t=eY.envVars.HEXCLAVE_BOT_CHALLENGE_SITE_KEY;return t?{visibleSiteKey:t,invisibleSiteKey:eY.envVars.HEXCLAVE_BOT_CHALLENGE_INVISIBLE_SITE_KEY??t}:(this._botChallengeSiteKeysWarned||(this._botChallengeSiteKeysWarned=!0,console.warn("[stack-auth] HEXCLAVE_BOT_CHALLENGE_SITE_KEY is not set — bot challenge fraud protection is disabled. Set the env variable to enable it.")),null)}_getBotChallengeFlowFailure(t){return t instanceof eu?{type:"cancelled",knownError:new P.KnownErrors.BotChallengeFailed("Bot challenge cancelled by user")}:t instanceof ec?{type:"failed",knownError:new P.KnownErrors.BotChallengeFailed(t.message)}:null}_normalizeBotChallengeResult(t){return"ok"===t.status?t:P.KnownErrors.BotChallengeRequired.isInstance(t.error)?((0,x.captureError)("bot-challenge-unexpected-after-flow",t.error),w.Result.error(new P.KnownErrors.BotChallengeFailed("Unexpected bot challenge after flow completion"))):w.Result.error(t.error)}_toInterfaceBotChallengeInput(t){return t.unavailable?{phase:"visible"}:{token:t.token,phase:t.phase}}async _executeResultWithBotChallengeFlow(t){let r,i=this._getBotChallengeSiteKeys();try{r=i?await ed({...i,action:t.action,execute:t.execute,isChallengeRequired:t=>"error"===t.status&&P.KnownErrors.BotChallengeRequired.isInstance(t.error)}):await t.execute({})}catch(r){let t=this._getBotChallengeFlowFailure(r);if(t)return w.Result.error(t.knownError);throw r}return this._normalizeBotChallengeResult(r)}async _isTrusted(t){if((0,Q.isRelative)(t))return!0;let r=(0,Q.createUrlIfValid)(t);if(null==r)return!1;if((0,eX.isHostedHandlerUrlForProject)({url:t,projectId:this.projectId}))return!0;let i=await this._getTrustedRedirectConfig();return(0,ei.validateRedirectUrl)(r,{allowLocalhost:i.allowLocalhost,trustedDomains:i.trustedDomains})}get urls(){var t;let r;return r=new Set(Object.entries((t={urls:this._getUrls(),projectId:this.projectId}).urls).filter(([,r])=>(0,eX.isHostedHandlerUrlForProject)({url:r,projectId:t.projectId})).map(([t])=>t)),new Proxy(t.urls,{get(t,i,s){if("string"==typeof i&&r.has(i))throw Error(`app.urls.${i} cannot be used when this app is configured to use hosted components. \`app.urls\` is static and does not include the runtime redirect-back, cross-domain auth, or sign-out state required by hosted components. `+("handler"===i?"Use a page-specific redirect helper such as app.redirectToSignIn() instead.":`Use app.redirectTo${i.slice(0,1).toUpperCase()}${i.slice(1)}() instead.`));return Reflect.get(t,i,s)}})}_getUrls(){return(0,C.getUrls)(this._urlOptions,{projectId:this.projectId})}_prefetchCrossDomainHandoffParamsIfNeeded(){let t="cookie"===this._tokenStoreInit||"nextjs-cookie"===this._tokenStoreInit;(0,er.isBrowserLike)()&&t&&!this._isPrefetchingCrossDomainHandoffParams&&null==this._getFreshPrefetchedCrossDomainHandoffParams()&&(this._isPrefetchingCrossDomainHandoffParams=!0,(0,E.runAsynchronously)(async()=>{try{if(!(0,er.isBrowserLike)())return;let{state:t,codeChallenge:r}=await eH();this._prefetchedCrossDomainHandoffParams={state:t,codeChallenge:r},this._prefetchedCrossDomainHandoffParamsFetchedAt=performance.now()}finally{this._isPrefetchingCrossDomainHandoffParams=!1}}))}_getCrossDomainHandoffParamsForUrlsGetter(t){let r=ti(t);if(null!=r)return r;let i=this._getFreshPrefetchedCrossDomainHandoffParams();return null!=i?i:(this._prefetchCrossDomainHandoffParamsIfNeeded(),null)}async _getCrossDomainHandoffParamsForRedirect(t){let r=ti(t);if(null!=r)return r;let i=this._getFreshPrefetchedCrossDomainHandoffParams();if(null!=i)return i;let{state:s,codeChallenge:n}=await eH();return this._prefetchedCrossDomainHandoffParams={state:s,codeChallenge:n},this._prefetchedCrossDomainHandoffParamsFetchedAt=performance.now(),{state:s,codeChallenge:n}}_getLocalOAuthCallbackHandlerUrl(){return this._isOAuthCallbackUrlHosted()?this._getOAuthCallbackRedirectUri():(0,eX.resolveHandlerUrls)({urls:{...this._urlOptions,default:{type:"handler-component"},oauthCallback:{type:"handler-component"}},projectId:this.projectId}).oauthCallback}async _createCrossDomainAuthRedirectUrl(t){let r=await this._getSession(t.overrideTokenStoreInit,{awaitPendingAuthResolutions:t.awaitPendingAuthResolutions});await r.fetchNewTokens();let i=await this._interface.sendClientRequest("/auth/oauth/cross-domain/authorize",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({redirect_uri:t.redirectUri,state:t.state,code_challenge:t.codeChallenge,code_challenge_method:"S256",after_callback_redirect_url:t.afterCallbackRedirectUrl})},r);if(!i.ok){let t=await i.text();throw new x.HexclaveAssertionError(`Cross-domain authorization endpoint failed: ${i.status} ${t}`)}let s=await i.json();if(!("redirect_url"in s)||"string"!=typeof s.redirect_url)throw new x.HexclaveAssertionError("Cross-domain authorization endpoint returned an invalid payload",{result:s});return s.redirect_url}_getFreshPrefetchedCrossDomainHandoffParams(){return null==this._prefetchedCrossDomainHandoffParams?null:performance.now()-this._prefetchedCrossDomainHandoffParamsFetchedAt>33e5?(this._prefetchedCrossDomainHandoffParams=null,this._prefetchedCrossDomainHandoffParamsFetchedAt=0,null):this._prefetchedCrossDomainHandoffParams}async _getCurrentUrl(){return"none"===this._redirectMethod?null:new URL(window.location.href)}async _redirectTo(t){"none"!==this._redirectMethod&&(tv&&"nextjs"===this._redirectMethod?tx.redirect(t.url.toString(),t.replace?tx.RedirectType.replace:tx.RedirectType.push):"object"==typeof this._redirectMethod&&this._redirectMethod.navigate?this._redirectMethod.navigate(t.url.toString()):t.replace?window.location.replace(t.url):window.location.assign(t.url),await (0,E.wait)(2e3))}useNavigate(){if("object"==typeof this._redirectMethod)return this._redirectMethod.useNavigate();if("window"===this._redirectMethod)return t=>window.location.assign(t);if("nextjs"!==this._redirectMethod)return t=>{};{let t=tx.useRouter();return r=>t.push(r)}}async _redirectIfTrusted(t,r){if(!await this._isTrusted(t))throw Error(`Redirect URL ${t} is not trusted; should be relative.`);return await this._redirectTo({url:t,...r})}async _redirectToHandler(t,r,i){let s=(0,C.getUrls)(this._urlOptions,{projectId:this.projectId})[t];if(!s)throw Error(`No URL for handler name ${t}`);let n=await to({handlerName:t,rawHandlerUrl:s,noRedirectBack:r?.noRedirectBack===!0,currentUrl:null,localOAuthCallbackUrl:this._getLocalOAuthCallbackHandlerUrl(),getCrossDomainHandoffParams:async t=>await this._getCrossDomainHandoffParamsForRedirect(t)});if("cross-domain-authorize"===n.type){let t=await this._createCrossDomainAuthRedirectUrl({redirectUri:n.redirectUri,state:n.state,codeChallenge:n.codeChallenge,afterCallbackRedirectUrl:n.afterCallbackRedirectUrl,awaitPendingAuthResolutions:i?.awaitPendingAuthResolutions,overrideTokenStoreInit:i?.overrideTokenStoreInit});await this._redirectTo({url:t,...r});return}let a=n.url;await this._redirectIfTrusted(a,r)}_redirectToHandlerDuringRender(t,r){return!1}async redirectToSignIn(t){return await this._redirectToHandler("signIn",t)}async redirectToSignUp(t){return await this._redirectToHandler("signUp",t)}async redirectToSignOut(t){let r=this._urlOptions.signOut??this._urlOptions.default;return"string"!=typeof r&&r?.type==="hosted"?await this.signOut():await this._redirectToHandler("signOut",t)}async redirectToEmailVerification(t){return await this._redirectToHandler("emailVerification",t)}async redirectToPasswordReset(t){return await this._redirectToHandler("passwordReset",t)}async redirectToForgotPassword(t){return await this._redirectToHandler("forgotPassword",t)}async redirectToHome(t){return await this._redirectToHandler("home",t)}async redirectToOAuthCallback(t){return await this._redirectToHandler("oauthCallback",t)}async redirectToMagicLinkCallback(t){return await this._redirectToHandler("magicLinkCallback",t)}async redirectToAfterSignIn(t){return await this._redirectToHandler("afterSignIn",t)}async redirectToAfterSignUp(t){return await this._redirectToHandler("afterSignUp",t)}async redirectToOnboarding(t){return await this._redirectToHandler("onboarding",t)}async redirectToAfterSignOut(t){return await this._redirectToHandler("afterSignOut",t)}async redirectToAccountSettings(t){return await this._redirectToHandler("accountSettings",t)}async redirectToError(t){return await this._redirectToHandler("error",t)}async redirectToTeamInvitation(t){return await this._redirectToHandler("teamInvitation",t)}async redirectToCliAuthConfirm(t){return await this._redirectToHandler("cliAuthConfirm",t)}async redirectToMfa(t){return await this._redirectToHandler("mfa",t)}async sendForgotPasswordEmail(t,r){return await this._interface.sendForgotPasswordEmail(t,r?.callbackUrl??q(this.urls.passwordReset,"callbackUrl"))}async sendMagicLinkEmail(t,r){let i=r?.callbackUrl??q(this.urls.magicLinkCallback,"callbackUrl");return await this._executeResultWithBotChallengeFlow({action:"send_magic_link_email",execute:async r=>await this._interface.sendMagicLinkEmail(t,i,this._toInterfaceBotChallengeInput(r))})}async resetPassword(t){return await this._interface.resetPassword(t)}async verifyPasswordResetCode(t){return await this._interface.verifyPasswordResetCode(t)}async verifyTeamInvitationCode(t){return await this._interface.acceptTeamInvitation({type:"check",code:t,session:await this._getSession()})}async acceptTeamInvitation(t){let r=await this._interface.acceptTeamInvitation({type:"use",code:t,session:await this._getSession()});return"ok"===r.status?w.Result.ok(void 0):w.Result.error(r.error)}async getTeamInvitationDetails(t){let r=await this._interface.acceptTeamInvitation({type:"details",code:t,session:await this._getSession()});return"ok"===r.status?w.Result.ok({teamDisplayName:r.data.team_display_name}):w.Result.error(r.error)}async verifyEmail(t){let r=await this._interface.verifyEmail(t);return await this._currentUserCache.refresh([await this._getSession()]),await this._clientContactChannelsCache.refresh([await this._getSession()]),r}async getUser(t){if(t?.or==="anonymous"&&!1===t.includeRestricted)throw Error("Cannot use { or: 'anonymous' } with { includeRestricted: false }. Anonymous users implicitly include restricted users.");this._ensurePersistentTokenStore(t?.tokenStore);let r=await this._getSession(t?.tokenStore),i=w.Result.orThrow(await this._currentUserCache.getOrWait([r],"write-only")),s=t?.or==="anonymous"||t?.or==="anonymous-if-exists[deprecated]",n=t?.includeRestricted===!0||s;if(null===i||i.is_anonymous&&!s||i.is_restricted&&!n)switch(t?.or){case"redirect":!i?.is_anonymous&&i?.is_restricted?await this.redirectToOnboarding({replace:!0}):await this.redirectToSignIn({replace:!0});break;case"throw":throw Error("User is not signed in but getUser was called with { or: 'throw' }");case"anonymous":{let t=await this._signUpAnonymously();return await this.getUser({tokenStore:t,or:"anonymous-if-exists[deprecated]",includeRestricted:!0})??(0,x.throwErr)("Something went wrong while signing up anonymously")}case void 0:case"anonymous-if-exists[deprecated]":case"return-null":return null}return i&&this._currentUserFromCrud(i,r)}useUser(t){if(t?.or==="anonymous"&&!1===t.includeRestricted)throw Error("Cannot use { or: 'anonymous' } with { includeRestricted: false }. Anonymous users implicitly include restricted users.");this._ensurePersistentTokenStore(t?.tokenStore);let r=this._useSession(t?.tokenStore),i=(0,C.useAsyncCache)(this._currentUserCache,[r],"clientApp.useUser()"),s=t?.or==="anonymous"||t?.or==="anonymous-if-exists[deprecated]",n=t?.includeRestricted===!0||s;if(null===i||i.is_anonymous&&!s||i.is_restricted&&!n)switch(t?.or){case"redirect":throw!i?.is_anonymous&&i?.is_restricted?this._redirectToHandlerDuringRender("onboarding",{replace:!0})||(0,E.runAsynchronously)(this.redirectToOnboarding({replace:!0})):this._redirectToHandlerDuringRender("signIn",{replace:!0})||(0,E.runAsynchronously)(this.redirectToSignIn({replace:!0})),(0,A.suspend)(),new x.HexclaveAssertionError("suspend should never return");case"throw":throw Error("User is not signed in but useUser was called with { or: 'throw' }");case"anonymous":throw(0,E.runAsynchronously)(async()=>{await this._signUpAnonymously()}),(0,A.suspend)(),new x.HexclaveAssertionError("suspend should never return");case void 0:case"anonymous-if-exists[deprecated]":case"return-null":i=null}return(0,S.useMemo)(()=>i&&this._currentUserFromCrud(i,r),[i,r,t?.or])}_getTokenPartialUserFromSession(t,r){let i=t.getAccessTokenIfNotExpiredYet(0,null);if(!i)return null;let s=i.payload.is_anonymous;return s&&"anonymous-if-exists"!==r.or?null:{id:i.payload.sub,primaryEmail:i.payload.email,displayName:i.payload.name,primaryEmailVerified:i.payload.email_verified,isAnonymous:s,isMultiFactorRequired:i.payload.requires_totp_mfa,isRestricted:i.payload.is_restricted,restrictedReason:i.payload.restricted_reason}}async _getPartialUserFromConvex(t){let r=await t.auth.getUserIdentity();return r?{id:r.subject,displayName:r.name??null,primaryEmail:r.email??null,primaryEmailVerified:r.email_verified,isAnonymous:r.is_anonymous,isMultiFactorRequired:r.requires_totp_mfa,isRestricted:r.is_restricted,restrictedReason:r.restricted_reason??null}:null}async getPartialUser(t){switch(t.from){case"token":{this._ensurePersistentTokenStore(t.tokenStore??this._tokenStoreInit);let r=await this._getSession(t.tokenStore);return this._getTokenPartialUserFromSession(r,t)}case"convex":return await this._getPartialUserFromConvex(t.ctx);default:throw Error(`Invalid 'from' option: ${t.from}`)}}usePartialUser(t){switch(t.from){case"token":{this._ensurePersistentTokenStore(t.tokenStore??this._tokenStoreInit);let r=this._useSession(t.tokenStore);return this._getTokenPartialUserFromSession(r,t)}case"convex":return(0,C.useAsyncCache)(this._convexPartialUserCache,[t.ctx],"clientApp.usePartialUser()");default:throw Error(`Invalid 'from' option: ${t.from}`)}}getConvexClientAuth(t){return async r=>{let i=await this._getSession(t.tokenStore??this._tokenStoreInit);return r.forceRefreshToken?(await i.fetchNewTokens())?.accessToken.token??null:(await i.getOrFetchLikelyValidTokens(2e4,75e3))?.accessToken.token??null}}async getConvexHttpClientAuth(t){return(await (await this._getSession(t.tokenStore)).getOrFetchLikelyValidTokens(2e4,75e3))?.accessToken.token??""}async _updateClientUser(t,r){let i=await this._interface.updateClientUser({display_name:t.displayName,client_metadata:t.clientMetadata,selected_team_id:t.selectedTeamId,totp_secret_base64:null!=t.totpMultiFactorSecret?(0,Y.encodeBase64)(t.totpMultiFactorSecret):t.totpMultiFactorSecret,profile_image_url:t.profileImageUrl,otp_auth_enabled:t.otpAuthEnabled,passkey_auth_enabled:t.passkeyAuthEnabled,primary_email:t.primaryEmail},r);return await this._refreshUser(r),i}async signInWithOAuth(t,r){throw Error("signInWithOAuth can currently only be called in a browser environment")}async _experimentalMfa(t,r){throw await this.redirectToMfa(),new x.HexclaveAssertionError("we should have redirected in redirectToMfa()")}async _catchMfaRequiredError(t){try{return await t()}catch(t){if(P.KnownErrors.MultiFactorAuthenticationRequired.isInstance(t))return w.Result.ok(await this._experimentalMfa(t,await this._getSession(void 0,{awaitPendingAuthResolutions:!1})));throw t}}async signInWithCredential(t){let r;this._ensurePersistentTokenStore();let i=await this._getSession();try{r=await this._catchMfaRequiredError(async()=>await this._interface.signInWithCredential(t.email,t.password,i))}catch(t){if(P.KnownErrors.InvalidTotpCode.isInstance(t))return w.Result.error(t);throw t}return"ok"===r.status?(await this._signInToAccountWithTokens(r.data),t.noRedirect||await this._redirectToHandler("afterSignIn",{replace:!0},{overrideTokenStoreInit:this._getTokenStoreInitForFreshTokens(r.data)}),w.Result.ok(void 0)):w.Result.error(r.error)}async signUpWithCredential(t){let r;if(t.noVerificationCallback&&t.verificationCallbackUrl)throw new x.HexclaveAssertionError("verificationCallbackUrl is not allowed when noVerificationCallback is true");this._ensurePersistentTokenStore();let i=await this._getSession(),s=t.noVerificationCallback?void 0:t.verificationCallbackUrl??q(this.urls.emailVerification,"verificationCallbackUrl"),n=async r=>{let n=await this._interface.signUpWithCredential(t.email,t.password,s,i,this._toInterfaceBotChallengeInput(r));return"error"===n.status&&n.error instanceof P.KnownErrors.RedirectUrlNotWhitelisted&&void 0!==s&&!t.verificationCallbackUrl&&((0,x.captureError)("signup-verification-url-not-whitelisted",new x.HexclaveAssertionError("The auto-constructed verification callback URL is not whitelisted; proceeding without email verification",{emailVerificationRedirectUrl:s})),n=await this._interface.signUpWithCredential(t.email,t.password,void 0,i,this._toInterfaceBotChallengeInput(r))),n};return"ok"===(r=await this._executeResultWithBotChallengeFlow({action:"sign_up_with_credential",execute:n})).status?(await this._signInToAccountWithTokens(r.data),t.noRedirect||await this._redirectToHandler("afterSignUp",{replace:!0},{overrideTokenStoreInit:this._getTokenStoreInitForFreshTokens(r.data)}),w.Result.ok(void 0)):w.Result.error(r.error)}async _signUpAnonymously(){return this._ensurePersistentTokenStore(),this._anonymousSignUpInProgress||(this._anonymousSignUpInProgress=(async()=>{this._ensurePersistentTokenStore();let t=await this._getSession(),r=await this._interface.signUpAnonymously(t);if("ok"===r.status)await this._signInToAccountWithTokens(r.data);else throw new x.HexclaveAssertionError("signUpAnonymously() should never return an error");return this._anonymousSignUpInProgress=null,r.data})()),await this._anonymousSignUpInProgress}async signInWithMagicLink(t,r){let i;this._ensurePersistentTokenStore();let s=await this._getSession();try{i=await this._catchMfaRequiredError(async()=>await this._interface.signInWithMagicLink(t,s))}catch(t){if(P.KnownErrors.InvalidTotpCode.isInstance(t))return w.Result.error(t);throw t}return"ok"===i.status?(await this._signInToAccountWithTokens(i.data),r?.noRedirect||(i.data.newUser?await this._redirectToHandler("afterSignUp",{replace:!0},{awaitPendingAuthResolutions:!1,overrideTokenStoreInit:this._getTokenStoreInitForFreshTokens(i.data)}):await this._redirectToHandler("afterSignIn",{replace:!0},{awaitPendingAuthResolutions:!1,overrideTokenStoreInit:this._getTokenStoreInitForFreshTokens(i.data)})),w.Result.ok(void 0)):w.Result.error(i.error)}async promptCliLogin(t){let r=await this._interface.sendClientRequest("/auth/cli",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({expires_in_millis:t.expiresInMillis,...null!=t.anonRefreshToken?{anon_refresh_token:t.anonRefreshToken}:{}})},null);if(!r.ok)return w.Result.error(new P.KnownErrors.CliAuthError(`Failed to initiate CLI auth: ${r.status} ${await r.text()}`));let i=await r.json(),s=i.polling_code,n=i.login_code,a=(0,eX.buildCliAuthConfirmUrl)({cliAuthConfirmUrl:this.urls.cliAuthConfirm,appUrl:t.appUrl,loginCode:n});t.promptLink?t.promptLink(a,n):(console.log(`Your verification code: ${n}`),console.log(`Please visit the following URL to authenticate:
|
|
353
|
+
${a}`));let o=0;for(;o<(t.maxAttempts??1/0);){o++;let r=await this._interface.sendClientRequest("/auth/cli/poll",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({polling_code:s})},null);if(!r.ok)return w.Result.error(new P.KnownErrors.CliAuthError(`Failed to initiate CLI auth: ${r.status} ${await r.text()}`));let i=await r.json();if(201===r.status&&"success"===i.status)return w.Result.ok(i.refresh_token);if("waiting"===i.status){await (0,E.wait)(t.waitTimeMillis??2e3);continue}if("expired"===i.status)return w.Result.error(new P.KnownErrors.CliAuthExpiredError("CLI authentication request expired. Please try again."));if("used"===i.status)return w.Result.error(new P.KnownErrors.CliAuthUsedError("This authentication token has already been used."));return w.Result.error(new P.KnownErrors.CliAuthError(`Unexpected status from CLI auth polling: ${i.status}`))}return w.Result.error(new P.KnownErrors.CliAuthError("Timed out waiting for CLI authentication."))}async signInWithMfa(t,r,i){let s;this._ensurePersistentTokenStore();let n=await this._getSession();try{s=await this._catchMfaRequiredError(async()=>await this._interface.signInWithMfa(t,r,n))}catch(t){if(t instanceof P.KnownErrors.InvalidTotpCode)return w.Result.error(t);throw t}return"ok"===s.status?(await this._signInToAccountWithTokens(s.data),i?.noRedirect||(s.data.newUser?await this._redirectToHandler("afterSignUp",{replace:!0},{overrideTokenStoreInit:this._getTokenStoreInitForFreshTokens(s.data)}):await this._redirectToHandler("afterSignIn",{replace:!0},{overrideTokenStoreInit:this._getTokenStoreInitForFreshTokens(s.data)})),w.Result.ok(void 0)):w.Result.error(s.error)}async signInWithPasskey(){let t;this._ensurePersistentTokenStore();let r=await this._getSession();try{t=await this._catchMfaRequiredError(async()=>{let t=await this._interface.initiatePasskeyAuthentication({},r);if("ok"!==t.status)return w.Result.error(new P.KnownErrors.PasskeyAuthenticationFailed("Failed to get initiation options for passkey authentication"));let{options_json:i,code:s}=t.data;if("THIS_VALUE_WILL_BE_REPLACED.example.com"!==i.rpId)throw new x.HexclaveAssertionError(`Expected returned RP ID from server to equal sentinel, but found ${i.rpId}`);i.rpId=window.location.hostname;let n=await K({optionsJSON:i});return await this._interface.signInWithPasskey({authentication_response:n,code:s},r)})}catch(t){if(t instanceof R)return w.Result.error(new P.KnownErrors.PasskeyWebAuthnError(t.message,t.name));return w.Result.error(new P.KnownErrors.PasskeyAuthenticationFailed("Failed to sign in with passkey"))}return"ok"===t.status?(await this._signInToAccountWithTokens(t.data),await this._redirectToHandler("afterSignIn",{replace:!0},{overrideTokenStoreInit:this._getTokenStoreInitForFreshTokens(t.data)}),w.Result.ok(void 0)):w.Result.error(t.error)}async callOAuthCallback(t){throw Error("callOAuthCallback can currently only be called in a browser environment")}async _signOut(t,r){this._eventTracker?.clearBuffer(),this._sessionRecorder?.clearBuffer(),await ea.storeLock.withWriteLock(async()=>{await this._interface.signOut(t),r?.redirectUrl?await this._redirectTo({url:r.redirectUrl,replace:!0}):await this._redirectToDefaultAfterSignOut()})}async _redirectToDefaultAfterSignOut(){null!=this._urlOptions.afterSignOut?await this.redirectToAfterSignOut({replace:!0}):null!=this._urlOptions.home?await this.redirectToHome({replace:!0}):(this._urlOptions.default?.type,await this.redirectToAfterSignOut({replace:!0}))}async signOut(t){let r=await this.getUser({tokenStore:t?.tokenStore??void 0});r&&await r.signOut({redirectUrl:t?.redirectUrl})}async getAccessToken(t){let r=await this.getUser({tokenStore:t?.tokenStore??void 0});return r?await r.getAccessToken():null}useAccessToken(t){let r=this.useUser({tokenStore:t?.tokenStore??void 0});return r?r.useAccessToken():null}async getRefreshToken(t){let r=await this.getUser({tokenStore:t?.tokenStore??void 0});return r?await r.getRefreshToken():null}useRefreshToken(t){let r=this.useUser({tokenStore:t?.tokenStore??void 0});return r?r.useRefreshToken():null}async getAuthorizationHeader(t){return t_(await this.getAuthJson(t))}useAuthorizationHeader(t){return t_(this.useAuthJson(t))}async getAuthHeaders(t){return{"x-stack-auth":JSON.stringify(await this.getAuthJson(t))}}useAuthHeaders(t){return{"x-stack-auth":JSON.stringify(this.useAuthJson(t))}}async getAuthJson(t){let r=await this.getUser({tokenStore:t?.tokenStore??void 0});return r?await r.getAuthJson():{accessToken:null,refreshToken:null}}useAuthJson(t){let r=this.useUser({tokenStore:t?.tokenStore??void 0});return r?r.useAuthJson():{accessToken:null,refreshToken:null}}async getProject(){let t=w.Result.orThrow(await this._currentProjectCache.getOrWait([],"write-only"));return this._clientProjectFromCrud(t)}useProject(){let t=(0,C.useAsyncCache)(this._currentProjectCache,[],"clientApp.useProject()");return(0,S.useMemo)(()=>this._clientProjectFromCrud(t),[t])}async _listOwnedProjects(t){return this._ensureInternalProject(),w.Result.orThrow(await this._ownedProjectsCache.getOrWait([t],"write-only")).map(r=>this._getOwnedAdminApp(r.id,t)._adminOwnedProjectFromCrud(r,()=>this._refreshOwnedProjects(t)))}_useOwnedProjects(t){this._ensureInternalProject();let r=(0,C.useAsyncCache)(this._ownedProjectsCache,[t],"clientApp.useOwnedProjects()");return(0,S.useMemo)(()=>r.map(r=>this._getOwnedAdminApp(r.id,t)._adminOwnedProjectFromCrud(r,()=>this._refreshOwnedProjects(t))),[r])}async _createProject(t,r){this._ensureInternalProject();let i=await this._interface.createProject({...en(r),display_name:r.displayName,is_development_environment:r.isDevelopmentEnvironment,owner_team_id:r.teamId},t),s=this._getOwnedAdminApp(i.id,t)._adminOwnedProjectFromCrud(i,()=>this._refreshOwnedProjects(t));return await this._refreshOwnedProjects(t),s}async _refreshUser(t){await this._refreshSession(t)}async _refreshSession(t){await Promise.all([this._currentUserCache.refresh([t]),this._currentUserConnectedAccountsCache.refresh([t])]),t.suggestAccessTokenExpired()}async _refreshUsers(){}async _refreshProject(){await this._currentProjectCache.refresh([])}async _refreshOwnedProjects(t){await this._ownedProjectsCache.refresh([t])}static get[es.hexclaveAppInternalsSymbol](){return{fromClientJson:t=>{let i=JSON.stringify((0,z.omit)(t,[])),s=tT.get(t.uniqueIdentifier);if(s){let[r,n]=s;if(void 0!==r&&r!==i)throw new x.HexclaveAssertionError("The provided app JSON does not match the configuration of the existing client app with the same unique identifier",{providedObj:t,existingString:r});return n}let{analytics:n,...a}=(0,z.omit)(t,["uniqueIdentifier"]);return new r({...a,analytics:function(t){if(!t?.replays?.blockClass)return t;let{blockClass:r,...i}=t.replays;return"object"==typeof r&&"__regexp"in r?{...t,replays:{...i,blockClass:new RegExp(r.__regexp,r.__flags)}}:t}(n)},{uniqueIdentifier:t.uniqueIdentifier,checkString:i})}}}get[es.hexclaveAppInternalsSymbol](){return{toClientJson:()=>{if("string"!=typeof this._redirectMethod)throw new x.HexclaveAssertionError("Cannot serialize to JSON from an application with a non-string redirect method");let t="publishableClientKey"in this._interface.options?this._interface.options.publishableClientKey:void 0;return{baseUrl:this._options.baseUrl,projectId:this.projectId,...null!=t?{publishableClientKey:t}:{},tokenStore:this._tokenStoreInit,urls:this._urlOptions,oauthScopesOnSignIn:this._oauthScopesOnSignIn,uniqueIdentifier:this._getUniqueIdentifier(),redirectMethod:this._redirectMethod,extraRequestHeaders:this._options.extraRequestHeaders,devTool:this._options.devTool,analytics:function(t){if(!t?.replays?.blockClass)return t;let{blockClass:r,...i}=t.replays;return r instanceof RegExp?{...t,replays:{...i,blockClass:{__regexp:r.source,__flags:r.flags}}}:t}(this._analyticsOptions)}},setCurrentUser:t=>{(0,E.runAsynchronously)(async()=>{await this._currentUserCache.forceSetCachedValueAsync([await this._getSession()],w.Result.fromPromise(t))})},getConstructorOptions:()=>this._options,sendSessionReplayBatch:async(t,r)=>await this._interface.sendSessionReplayBatch(t,await this._getSession(),r),sendAnalyticsEventBatch:async(t,r)=>await this._interface.sendAnalyticsEventBatch(t,await this._getSession(),r),addRequestListener:t=>this._interface.addRequestListener(t),sendRequest:async(t,r,i="client")=>await this._interface.sendClientRequest(t,r,await this._getSession(),i),getRedirectMethod:()=>this._redirectMethod??(0,x.throwErr)("Redirect method should have been initialized in the Stack client app constructor"),redirectToUrl:async(t,r)=>{await this._redirectTo({url:t,...r})},redirectToHandler:async(t,r)=>{await this._redirectToHandler(t,r)},refreshOwnedProjects:async()=>{await this._refreshOwnedProjects(await this._getSession())},signInWithTokens:async t=>{await this._signInToAccountWithTokens(t)}}}},tC=class extends tw{async _refreshTeamMembership(t,r){await Promise.all([this._serverTeamMemberProfilesCache.refresh([t]),this._serverTeamsCache.refreshWhere(([t])=>t===r||void 0===t),this._serverUsersCache.refreshWhere(r=>r[8]===t)])}_createServerCustomer(t,r){let i=this,s="user"===r?i._serverUserProductsCache:i._serverTeamProductsCache,n="user"===r?{userId:t}:{teamId:t};return{...this._createCustomer(t,r,null),getItem:async t=>await i.getItem({itemId:t,...n}),useItem:t=>i.useItem({itemId:t,...n}),async grantProduct(n){"user"===r?"productId"in n?await i.grantProduct({userId:t,productId:n.productId,quantity:n.quantity}):await i.grantProduct({userId:t,product:n.product,quantity:n.quantity}):"productId"in n?await i.grantProduct({teamId:t,productId:n.productId,quantity:n.quantity}):await i.grantProduct({teamId:t,product:n.product,quantity:n.quantity}),await s.refresh([t,null,null])},async createCheckoutUrl(s){let n="productId"in s?s.productId:s.product;return await i._interface.createCheckoutUrl(r,t,n,null,s.returnUrl,"server")}}}async _updateServerUser(t,r){let i=await this._interface.updateServerUser(t,{display_name:r.displayName,primary_email:r.primaryEmail,client_metadata:r.clientMetadata,client_read_only_metadata:r.clientReadOnlyMetadata,server_metadata:r.serverMetadata,selected_team_id:r.selectedTeamId,primary_email_auth_enabled:r.primaryEmailAuthEnabled,primary_email_verified:r.primaryEmailVerified,password:r.password,profile_image_url:r.profileImageUrl,totp_secret_base64:null!=r.totpMultiFactorSecret?(0,Y.encodeBase64)(r.totpMultiFactorSecret):r.totpMultiFactorSecret,restricted_by_admin:r.restrictedByAdmin,restricted_by_admin_reason:r.restrictedByAdminReason,restricted_by_admin_private_details:r.restrictedByAdminPrivateDetails,country_code:r.countryCode,risk_scores:r.riskScores?{sign_up:{bot:r.riskScores.signUp.bot,free_trial_abuse:r.riskScores.signUp.freeTrialAbuse}}:void 0});return await this._refreshUsers(),i}_serverEditableTeamProfileFromCrud(t){let r=this;return{displayName:t.display_name,profileImageUrl:t.profile_image_url,async update(i){await r._interface.updateServerTeamMemberProfile({teamId:t.team_id,userId:t.user_id,profile:{display_name:i.displayName,profile_image_url:i.profileImageUrl}}),await r._serverUserTeamProfileCache.refresh([t.team_id,t.user_id])}}}_serverContactChannelFromCrud(t,r){let i=this;return{id:r.id,value:r.value,type:r.type,isVerified:r.is_verified,isPrimary:r.is_primary,usedForAuth:r.used_for_auth,async sendVerificationEmail(s){await i._interface.sendServerContactChannelVerificationEmail(t,r.id,s?.callbackUrl??q(i._getUrls().emailVerification,"callbackUrl"))},async update(s){await i._interface.updateServerContactChannel(t,r.id,{value:s.value,is_verified:s.isVerified,used_for_auth:s.usedForAuth,is_primary:s.isPrimary}),await Promise.all([i._serverContactChannelsCache.refresh([t]),i._serverUserCache.refresh([t])])},async delete(){await i._interface.deleteServerContactChannel(t,r.id),await Promise.all([i._serverContactChannelsCache.refresh([t]),i._serverUserCache.refresh([t])])}}}_serverNotificationCategoryFromCrud(t,r){let i=this;return{id:r.notification_category_id,name:r.notification_category_name,enabled:r.enabled,canDisable:r.can_disable,async setEnabled(s){await i._interface.setServerNotificationsEnabled(t,r.notification_category_id,s),await i._serverNotificationCategoriesCache.refresh([t])}}}_serverOAuthProviderFromCrud(t){let r=this;return{id:t.id,type:t.type,userId:t.user_id,accountId:t.account_id,email:t.email,allowSignIn:t.allow_sign_in,allowConnectedAccounts:t.allow_connected_accounts,async update(i){try{return await r._interface.updateServerOAuthProvider(t.user_id,t.id,{account_id:i.accountId,email:i.email,allow_sign_in:i.allowSignIn,allow_connected_accounts:i.allowConnectedAccounts}),await Promise.all([r._serverOAuthProvidersCache.refresh([t.user_id]),r._serverUserConnectedAccountsCache.refresh([t.user_id])]),w.Result.ok(void 0)}catch(t){if(P.KnownErrors.OAuthProviderAccountIdAlreadyUsedForSignIn.isInstance(t))return w.Result.error(t);throw t}},async delete(){await r._interface.deleteServerOAuthProvider(t.user_id,t.id),await Promise.all([r._serverOAuthProvidersCache.refresh([t.user_id]),r._serverUserConnectedAccountsCache.refresh([t.user_id])])}}}constructor(t,r){const i=(0,C.resolveConstructorOptions)(t),s=i.publishableClientKey??(0,C.getDefaultPublishableClientKey)();super(i,{...r,interface:r?.interface??(()=>{let t=(0,C.resolveApiUrls)(i.baseUrl);return new _.HexclaveServerInterface({getBaseUrl:()=>t()[0],getApiUrls:t,projectId:i.projectId??(0,C.getDefaultProjectId)(),extraRequestHeaders:i.extraRequestHeaders??(0,C.getDefaultExtraRequestHeaders)(),clientVersion:C.clientVersion,...null!=s?{publishableClientKey:s}:{},secretServerKey:i.secretServerKey??(0,C.getDefaultSecretServerKey)()})})()}),this._currentServerUserCache=(0,C.createCacheBySession)(async t=>t.isKnownToBeInvalid()?null:await this._interface.getServerUserByToken(t)),this._serverUsersCache=(0,C.createCache)(async([t,r,i,s,n,a,o,l,p])=>{if(l&&!o)throw new x.HexclaveAssertionError("onlyAnonymous=true requires includeAnonymous=true");return l?await this._interface.listServerUsers({cursor:t,limit:r,orderBy:i,desc:s,query:n,includeRestricted:a,includeAnonymous:!0,onlyAnonymous:!0,teamId:p}):await this._interface.listServerUsers({cursor:t,limit:r,orderBy:i,desc:s,query:n,includeRestricted:a,includeAnonymous:o,teamId:p})}),this._serverUserCache=(0,C.createCache)(async([t])=>{let r=await this._interface.getServerUserById(t);return w.Result.or(r,null)}),this._serverTeamsCache=(0,C.createCache)(async([t,r,i,s,n,a])=>await this._interface.listServerTeamsPaginated({userId:t,orderBy:r,desc:i,cursor:s,limit:n,query:a})),this._serverUserTeamInvitationsCache=(0,C.createCache)(async([t])=>await this._interface.listServerUserTeamInvitations(t)),this._serverTeamUserPermissionsCache=(0,C.createCache)(async([t,r,i])=>await this._interface.listServerTeamPermissions({teamId:t,userId:r,recursive:i},null)),this._serverAllTeamMemberPermissionsCache=(0,C.createCache)(async([t,r])=>await this._interface.listServerTeamPermissions({teamId:t,recursive:r},null)),this._serverUserProjectPermissionsCache=(0,C.createCache)(async([t,r])=>await this._interface.listServerProjectPermissions({userId:t,recursive:r},null)),this._serverUserOAuthConnectionAccessTokensCache=(0,C.createCache)(async([t,r,i])=>{try{return{accessToken:(await this._interface.createServerProviderAccessToken(t,r,i||"")).access_token}}catch(t){if(!(P.KnownErrors.OAuthAccessTokenNotAvailable.isInstance(t)||P.KnownErrors.OAuthConnectionDoesNotHaveRequiredScope.isInstance(t)||P.KnownErrors.OAuthConnectionNotConnectedToUser.isInstance(t)))throw t}return null}),this._serverUserOAuthConnectionCache=(0,C.createCache)(async([t,r,i,s])=>await this._getUserOAuthConnectionCacheFn({getUser:async()=>w.Result.orThrow(await this._serverUserCache.getOrWait([t],"write-only")),getOrWaitOAuthToken:async()=>w.Result.orThrow(await this._serverUserOAuthConnectionAccessTokensCache.getOrWait([t,r,i||""],"write-only")),useOAuthToken:()=>(0,C.useAsyncCache)(this._serverUserOAuthConnectionAccessTokensCache,[t,r,i||""],"user.useConnectedAccount()"),providerId:r,scope:i,redirect:s,session:null})),this._serverUserConnectedAccountsCache=(0,C.createCache)(async([t])=>(await this._interface.listServerConnectedAccounts(t)).items.map(r=>this._createServerOAuthConnectionFromCrudItem(t,r))),this._serverUserOAuthConnectionAccessTokensByAccountCache=(0,C.createCache)(async([t,r,i,s])=>{try{return{accessToken:(await this._interface.createServerProviderAccessTokenByAccount(t,r,i,s||"")).access_token}}catch(t){if(!(P.KnownErrors.OAuthAccessTokenNotAvailable.isInstance(t)||P.KnownErrors.OAuthConnectionDoesNotHaveRequiredScope.isInstance(t)||P.KnownErrors.OAuthConnectionNotConnectedToUser.isInstance(t)))throw t}return null}),this._serverTeamMemberProfilesCache=(0,C.createCache)(async([t])=>await this._interface.listServerTeamMemberProfiles({teamId:t})),this._serverTeamInvitationsCache=(0,C.createCache)(async([t])=>await this._interface.listServerTeamInvitations({teamId:t})),this._serverUserTeamProfileCache=(0,C.createCache)(async([t,r])=>await this._interface.getServerTeamMemberProfile({teamId:t,userId:r})),this._serverContactChannelsCache=(0,C.createCache)(async([t])=>await this._interface.listServerContactChannels(t)),this._serverNotificationCategoriesCache=(0,C.createCache)(async([t])=>await this._interface.listServerNotificationCategories(t)),this._serverDataVaultStoreValueCache=(0,C.createCache)(async([t,r,i])=>await this._interface.getDataVaultStoreValue(i,t,r)),this._emailDeliveryInfoCache=(0,C.createCache)(async()=>await this._interface.getEmailDeliveryInfo()),this._serverUserApiKeysCache=(0,C.createCache)(async([t])=>await this._interface.listProjectApiKeys({user_id:t},null,"server")),this._serverTeamApiKeysCache=(0,C.createCache)(async([t])=>await this._interface.listProjectApiKeys({team_id:t},null,"server")),this._convexIdentitySubjectCache=(0,C.createCache)(async([t])=>{let r=await t.auth.getUserIdentity();return r?r.subject:null}),this._serverCheckApiKeyCache=(0,C.createCache)(async([t,r])=>await this._interface.checkProjectApiKey(t,r,null,"server")),this._serverOAuthProvidersCache=(0,C.createCache)(async([t])=>await this._interface.listServerOAuthProviders({user_id:t})),this._serverTeamItemsCache=(0,C.createCache)(async([t,r])=>await this._interface.getItem({teamId:t,itemId:r},null,"server")),this._serverUserItemsCache=(0,C.createCache)(async([t,r])=>await this._interface.getItem({userId:t,itemId:r},null,"server")),this._serverCustomItemsCache=(0,C.createCache)(async([t,r])=>await this._interface.getItem({customCustomerId:t,itemId:r},null,"server")),this._serverUserProductsCache=(0,C.createCache)(async([t,r,i])=>await this._interface.listProducts({customer_type:"user",customer_id:t,cursor:r??void 0,limit:i??void 0},null,"server")),this._serverTeamProductsCache=(0,C.createCache)(async([t,r,i])=>await this._interface.listProducts({customer_type:"team",customer_id:t,cursor:r??void 0,limit:i??void 0},null,"server")),this._serverCustomProductsCache=(0,C.createCache)(async([t,r,i])=>await this._interface.listProducts({customer_type:"custom",customer_id:t,cursor:r??void 0,limit:i??void 0},null,"server"))}_serverApiKeyFromCrud(t){return{...this._baseApiKeyFromCrud(t),async revoke(){await this.update({revoked:!0})},update:async r=>{await this._interface.updateProjectApiKey("team"===t.type?{team_id:t.team_id}:{user_id:t.user_id},t.id,await H(t.type,r),null,"server"),"team"===t.type?await this._serverTeamApiKeysCache.refresh([t.team_id]):await this._serverUserApiKeysCache.refresh([t.user_id])}}}_createServerOAuthConnectionFromCrudItem(t,r){let i=this,s=r.provider,n=r.provider_account_id;return{id:s,provider:s,providerAccountId:n,async getAccessToken(r){let a=r?.scopes?.join(" ")??"",o=w.Result.orThrow(await i._serverUserOAuthConnectionAccessTokensByAccountCache.getOrWait([t,s,n,a],"write-only"));if(!o){let t=a?`The requested scopes [${a}] are not available on the existing token.`:"The OAuth refresh token has likely been revoked or expired.";return w.Result.error(new P.KnownErrors.OAuthAccessTokenNotAvailable(s,`${t} The user needs to re-authorize by calling \`linkConnectedAccount\` or using \`getOrLinkConnectedAccount\`.`))}return w.Result.ok(o)},useAccessToken(r){let a=r?.scopes?.join(" ")??"",o=(0,C.useAsyncCache)(i._serverUserOAuthConnectionAccessTokensByAccountCache,[t,s,n,a],"connection.useAccessToken()");if(!o){let t=a?`The requested scopes [${a}] are not available on the existing token.`:"The OAuth refresh token has likely been revoked or expired.";return w.Result.error(new P.KnownErrors.OAuthAccessTokenNotAvailable(s,`${t} The user needs to re-authorize by calling \`linkConnectedAccount\` or using \`getOrLinkConnectedAccount\`.`))}return w.Result.ok(o)}}}_serverUserFromCrud(t){let r=this;async function i(i,s){let n=s?.scopes?.join(" ")??"";if("object"==typeof i&&"provider"in i&&"providerAccountId"in i){let{provider:s,providerAccountId:n}=i,a=w.Result.orThrow(await r._serverUserConnectedAccountsCache.getOrWait([t.id],"write-only")).find(t=>t.provider===s&&t.providerAccountId===n);return a||null}return w.Result.orThrow(await r._serverUserOAuthConnectionCache.getOrWait([t.id,i,n,s?.or==="redirect"],"write-only"))}return X({...super._createBaseUser(t),lastActiveAt:new Date(t.last_active_at_millis),serverMetadata:t.server_metadata,restrictedByAdmin:t.restricted_by_admin,restrictedByAdminReason:t.restricted_by_admin_reason,restrictedByAdminPrivateDetails:t.restricted_by_admin_private_details,countryCode:t.country_code,riskScores:{signUp:{bot:t.risk_scores.sign_up.bot,freeTrialAbuse:t.risk_scores.sign_up.free_trial_abuse}},async setPrimaryEmail(i,s){await r._updateServerUser(t.id,{primaryEmail:i,primaryEmailVerified:s?.verified})},async grantPermission(i,s){if(i&&"string"!=typeof i&&s)for(let n of(await r._interface.grantServerTeamUserPermission(i.id,t.id,s),[!0,!1]))await r._serverTeamUserPermissionsCache.refresh([i.id,t.id,n]),await r._serverAllTeamMemberPermissionsCache.refresh([i.id,n]);else for(let s of(await r._interface.grantServerProjectPermission(t.id,i),[!0,!1]))await r._serverUserProjectPermissionsCache.refresh([t.id,s])},async revokePermission(i,s){if(i&&"string"!=typeof i&&s)for(let n of(await r._interface.revokeServerTeamUserPermission(i.id,t.id,s),[!0,!1]))await r._serverTeamUserPermissionsCache.refresh([i.id,t.id,n]),await r._serverAllTeamMemberPermissionsCache.refresh([i.id,n]);else for(let s of(await r._interface.revokeServerProjectPermission(t.id,i),[!0,!1]))await r._serverUserProjectPermissionsCache.refresh([t.id,s])},async delete(){let i=await r._interface.deleteServerUser(t.id);return await r._refreshUsers(),i},async createSession(i){let s=await r._interface.createServerUserSession(t.id,i.expiresInMillis??31536e6,i.isImpersonation??!1);return{getTokens:async()=>s}},getActiveSessions:async()=>(await r._interface.listServerSessions(t.id)).items.map(t=>r._clientSessionFromCrud(t)),async revokeSession(t){await r._interface.deleteServerSession(t)},async setDisplayName(t){return await this.update({displayName:t})},async setClientMetadata(t){return await this.update({clientMetadata:t})},async setClientReadOnlyMetadata(t){return await this.update({clientReadOnlyMetadata:t})},async setServerMetadata(t){return await this.update({serverMetadata:t})},async setSelectedTeam(t){return await this.update({selectedTeamId:"string"==typeof t?t:t?.id??null})},getConnectedAccount:i,useConnectedAccount:function(i,s){let n=s?.scopes?.join(" ")??"";if("object"==typeof i&&"provider"in i&&"providerAccountId"in i){let{provider:s,providerAccountId:n}=i;return(0,C.useAsyncCache)(r._serverUserConnectedAccountsCache,[t.id],"user.useConnectedAccount()").find(t=>t.provider===s&&t.providerAccountId===n)??null}return(0,C.useAsyncCache)(r._serverUserOAuthConnectionCache,[t.id,i,n,s?.or==="redirect"],"user.useConnectedAccount()")},listConnectedAccounts:async()=>w.Result.orThrow(await r._serverUserConnectedAccountsCache.getOrWait([t.id],"write-only")),useConnectedAccounts:()=>(0,C.useAsyncCache)(r._serverUserConnectedAccountsCache,[t.id],"user.useConnectedAccounts()"),async linkConnectedAccount(){throw new x.HexclaveAssertionError("linkConnectedAccount is not available for server users. OAuth flows must be initiated on the client side.")},async getOrLinkConnectedAccount(){throw new x.HexclaveAssertionError("getOrLinkConnectedAccount is not available for server users. OAuth flows must be initiated on the client side.")},useOrLinkConnectedAccount(){throw new x.HexclaveAssertionError("useOrLinkConnectedAccount is not available for server users. OAuth flows must be initiated on the client side.")},selectedTeam:t.selected_team?r._serverTeamFromCrud(t.selected_team):null,async getTeam(t){return(await this.listTeams()).find(r=>r.id===t)??null},useTeam(t){let r=this.useTeams();return(0,S.useMemo)(()=>r.find(r=>r.id===t)??null,[r,t])},async listTeams(i){let s=w.Result.orThrow(await r._serverTeamsCache.getOrWait([t.id,i?.orderBy,i?.desc,i?.cursor,i?.limit,i?.query],"write-only")),n=s.items.map(t=>r._serverTeamFromCrud(t));return n.nextCursor=s.pagination?.next_cursor??null,n},useTeams(i){let s=(0,C.useAsyncCache)(r._serverTeamsCache,[t.id,i?.orderBy,i?.desc,i?.cursor,i?.limit,i?.query],"user.useTeams()");return(0,S.useMemo)(()=>{let t=s.items.map(t=>r._serverTeamFromCrud(t));return t.nextCursor=s.pagination?.next_cursor??null,t},[s])},createTeam:async i=>{let s=await r._interface.createServerTeam(J({creatorUserId:t.id,...i}));return await r._serverTeamsCache.refreshWhere(()=>!0),await r._updateServerUser(t.id,{selectedTeamId:s.id}),r._serverTeamFromCrud(s)},leaveTeam:async i=>{await r._interface.leaveServerTeam({teamId:i.id,userId:t.id}),await r._refreshTeamMembership(i.id,t.id)},listTeamInvitations:async()=>w.Result.orThrow(await r._serverUserTeamInvitationsCache.getOrWait([t.id],"write-only")).map(i=>r._serverReceivedTeamInvitationFromCrud(t.id,i)),useTeamInvitations(){let i=(0,C.useAsyncCache)(r._serverUserTeamInvitationsCache,[t.id],"user.useTeamInvitations()");return(0,S.useMemo)(()=>i.map(i=>r._serverReceivedTeamInvitationFromCrud(t.id,i)),[i])},async listPermissions(i,s){if(i&&"id"in i){let n=s?.recursive??!0;return w.Result.orThrow(await r._serverTeamUserPermissionsCache.getOrWait([i.id,t.id,n],"write-only")).map(t=>r._serverPermissionFromCrud(t))}{let s=i?.recursive??!0;return w.Result.orThrow(await r._serverUserProjectPermissionsCache.getOrWait([t.id,s],"write-only")).map(t=>r._serverPermissionFromCrud(t))}},usePermissions(i,s){if(i&&"id"in i){let n=s?.recursive??!0,a=(0,C.useAsyncCache)(r._serverTeamUserPermissionsCache,[i.id,t.id,n],"user.usePermissions()");return(0,S.useMemo)(()=>a.map(t=>r._serverPermissionFromCrud(t)),[a])}{let s=i?.recursive??!0,n=(0,C.useAsyncCache)(r._serverUserProjectPermissionsCache,[t.id,s],"user.usePermissions()");return(0,S.useMemo)(()=>n.map(t=>r._serverPermissionFromCrud(t)),[n])}},async getPermission(t,r){return t&&"string"!=typeof t?(await this.listPermissions(t)).find(t=>t.id===r)??null:(await this.listPermissions()).find(r=>r.id===t)??null},usePermission(t,r){if(t&&"string"!=typeof t){let i=this.usePermissions(t);return(0,S.useMemo)(()=>i.find(t=>t.id===r)??null,[i,r])}{let r=this.usePermissions();return(0,S.useMemo)(()=>r.find(r=>r.id===t)??null,[r,t])}},async hasPermission(t,r){return t&&"string"!=typeof t?await this.getPermission(t,r)!==null:await this.getPermission(t)!==null},async update(i){await r._updateServerUser(t.id,i)},sendVerificationEmail:async()=>await r._checkFeatureSupport("sendVerificationEmail() on ServerUser",{}),async updatePassword(i){let s=await r._interface.updatePassword(i);return await r._serverUserCache.refresh([t.id]),s},async setPassword(i){let s=await this.update(i);return await r._serverUserCache.refresh([t.id]),s},async getTeamProfile(i){let s=w.Result.orThrow(await r._serverUserTeamProfileCache.getOrWait([i.id,t.id],"write-only"));return r._serverEditableTeamProfileFromCrud(s)},useTeamProfile(i){let s=(0,C.useAsyncCache)(r._serverUserTeamProfileCache,[i.id,t.id],"user.useTeamProfile()");return(0,S.useMemo)(()=>r._serverEditableTeamProfileFromCrud(s),[s])},listContactChannels:async()=>w.Result.orThrow(await r._serverContactChannelsCache.getOrWait([t.id],"write-only")).map(i=>r._serverContactChannelFromCrud(t.id,i)),useContactChannels(){let i=(0,C.useAsyncCache)(r._serverContactChannelsCache,[t.id],"user.useContactChannels()");return(0,S.useMemo)(()=>i.map(i=>r._serverContactChannelFromCrud(t.id,i)),[i])},createContactChannel:async i=>{var s;let n=await r._interface.createServerContactChannel((s=t.id,{type:i.type,value:i.value,is_verified:i.isVerified,user_id:s,used_for_auth:i.usedForAuth,is_primary:i.isPrimary}));return await Promise.all([r._serverContactChannelsCache.refresh([t.id]),r._serverUserCache.refresh([t.id])]),r._serverContactChannelFromCrud(t.id,n)},useNotificationCategories:()=>(0,C.useAsyncCache)(r._serverNotificationCategoriesCache,[t.id],"user.useNotificationCategories()").map(i=>r._serverNotificationCategoryFromCrud(t.id,i)),listNotificationCategories:async()=>w.Result.orThrow(await r._serverNotificationCategoriesCache.getOrWait([t.id],"write-only")).map(i=>r._serverNotificationCategoryFromCrud(t.id,i)),useApiKeys:()=>(0,C.useAsyncCache)(r._serverUserApiKeysCache,[t.id],"user.useApiKeys()").map(t=>r._serverApiKeyFromCrud(t)),listApiKeys:async()=>w.Result.orThrow(await r._serverUserApiKeysCache.getOrWait([t.id],"write-only")).map(t=>r._serverApiKeyFromCrud(t)),async createApiKey(i){let s=await r._interface.createProjectApiKey(await W("user",t.id,i),null,"server");return await r._serverUserApiKeysCache.refresh([t.id]),r._serverApiKeyFromCrud(s)},useOAuthProviders(){let i=(0,C.useAsyncCache)(r._serverOAuthProvidersCache,[t.id],"user.useOAuthProviders()");return(0,S.useMemo)(()=>i.map(t=>r._serverOAuthProviderFromCrud(t)),[i])},listOAuthProviders:async()=>w.Result.orThrow(await r._serverOAuthProvidersCache.getOrWait([t.id],"write-only")).map(t=>r._serverOAuthProviderFromCrud(t)),useOAuthProvider(t){let r=this.useOAuthProviders();return(0,S.useMemo)(()=>r.find(r=>r.id===t)??null,[r,t])},async getOAuthProvider(t){return(await this.listOAuthProviders()).find(r=>r.id===t)??null},async registerPasskey(i){let s,n=i?.hostname||(await r._getCurrentUrl())?.hostname;if(!n)throw new x.HexclaveAssertionError("hostname must be provided if the Stack App does not have a redirect method");let a=await r._interface.initiateServerPasskeyRegistration(t.id);if("ok"!==a.status)return w.Result.error(new P.KnownErrors.PasskeyRegistrationFailed("Failed to get initiation options for passkey registration"));let{options_json:o,code:l}=a.data;if("THIS_VALUE_WILL_BE_REPLACED.example.com"!==o.rp.id)throw new x.HexclaveAssertionError(`Expected returned RP ID from server to equal sentinel, but found ${o.rp.id}`);o.rp.id=n;try{s=await U({optionsJSON:o})}catch(t){if(t instanceof R)return w.Result.error(new P.KnownErrors.PasskeyWebAuthnError(t.message,t.name));return(0,x.captureError)("passkey-registration-failed",t),w.Result.error(new P.KnownErrors.PasskeyRegistrationFailed("Failed to start passkey registration due to unknown error"))}let{accessToken:p,refreshToken:u}=await r._interface.createServerUserSession(t.id,6e4*2,!1),c=new I.InternalSession({accessToken:p,refreshToken:u,refreshAccessTokenCallback:async()=>null}),d=await r._interface.registerPasskey({credential:s,code:l},c);return await r._serverUserCache.refresh([t.id]),d},...r._createServerCustomer(t.id,"user")})}_serverTeamUserFromCrud(t){return X({...this._serverUserFromCrud(t.user),teamProfile:{displayName:t.display_name,profileImageUrl:t.profile_image_url}})}_serverSentTeamInvitationFromCrud(t){return{id:t.id,recipientEmail:t.recipient_email,expiresAt:new Date(t.expires_at_millis),revoke:async()=>{await this._interface.revokeServerTeamInvitation(t.id,t.team_id),await this._serverTeamInvitationsCache.refresh([t.team_id])}}}_serverReceivedTeamInvitationFromCrud(t,r){let i=this;return{id:r.id,teamId:r.team_id,teamDisplayName:r.team_display_name,recipientEmail:r.recipient_email,expiresAt:new Date(r.expires_at_millis),accept:async()=>{await i._interface.acceptServerTeamInvitationById(r.id,t),await Promise.all([i._serverUserTeamInvitationsCache.refresh([t]),i._serverTeamInvitationsCache.refresh([r.team_id]),i._refreshTeamMembership(r.team_id,t)])}}}_currentUserFromCrud(t,r){return X({...this._serverUserFromCrud(t),...this._createAuth(r),...this._isInternalProject()?this._createInternalUserExtra(r):{}})}_serverTeamFromCrud(t){let r=this;return{id:t.id,displayName:t.display_name,profileImageUrl:t.profile_image_url,createdAt:new Date(t.created_at_millis),clientMetadata:t.client_metadata,clientReadOnlyMetadata:t.client_read_only_metadata,serverMetadata:t.server_metadata,async update(i){await r._interface.updateServerTeam(t.id,{display_name:i.displayName,profile_image_url:i.profileImageUrl,client_metadata:i.clientMetadata,client_read_only_metadata:i.clientReadOnlyMetadata,server_metadata:i.serverMetadata}),await Promise.all([r._serverTeamsCache.refreshWhere(()=>!0),r._serverUsersCache.refreshWhere(()=>!0)])},async delete(){await r._interface.deleteServerTeam(t.id),await Promise.all([r._serverTeamsCache.refreshWhere(()=>!0),r._serverUsersCache.refreshWhere(()=>!0)])},listUsers:async()=>w.Result.orThrow(await r._serverTeamMemberProfilesCache.getOrWait([t.id],"write-only")).map(t=>r._serverTeamUserFromCrud(t)),useUsers(){let i=(0,C.useAsyncCache)(r._serverTeamMemberProfilesCache,[t.id],"team.useUsers()");return(0,S.useMemo)(()=>i.map(t=>r._serverTeamUserFromCrud(t)),[i])},async addUser(i){await r._interface.addServerUserToTeam({teamId:t.id,userId:i}),await r._refreshTeamMembership(t.id,i)},async removeUser(i){await r._interface.removeServerUserFromTeam({teamId:t.id,userId:i}),await r._refreshTeamMembership(t.id,i)},async inviteUser(i){await r._interface.sendServerTeamInvitation({teamId:t.id,email:i.email,callbackUrl:i.callbackUrl??q(r._getUrls().teamInvitation,"callbackUrl")}),await r._serverTeamInvitationsCache.refresh([t.id])},listInvitations:async()=>w.Result.orThrow(await r._serverTeamInvitationsCache.getOrWait([t.id],"write-only")).map(t=>r._serverSentTeamInvitationFromCrud(t)),useInvitations(){let i=(0,C.useAsyncCache)(r._serverTeamInvitationsCache,[t.id],"team.useInvitations()");return(0,S.useMemo)(()=>i.map(t=>r._serverSentTeamInvitationFromCrud(t)),[i])},useApiKeys:()=>(0,C.useAsyncCache)(r._serverTeamApiKeysCache,[t.id],"team.useApiKeys()").map(t=>r._serverApiKeyFromCrud(t)),listApiKeys:async()=>w.Result.orThrow(await r._serverTeamApiKeysCache.getOrWait([t.id],"write-only")).map(t=>r._serverApiKeyFromCrud(t)),async createApiKey(i){let s=await r._interface.createProjectApiKey(await W("team",t.id,i),null,"server");return await r._serverTeamApiKeysCache.refresh([t.id]),r._serverApiKeyFromCrud(s)},...r._createServerCustomer(t.id,"team")}}_serverItemFromCrud(t,r){let i=this;return{displayName:r.display_name,quantity:r.quantity,nonNegativeQuantity:Math.max(0,r.quantity),increaseQuantity:async s=>{let n="user"===t.type?{itemId:r.id,userId:t.id}:"team"===t.type?{itemId:r.id,teamId:t.id}:{itemId:r.id,customCustomerId:t.id};await i._interface.updateItemQuantity(n,{delta:s}),"user"===t.type?await i._serverUserItemsCache.refresh([t.id,r.id]):"team"===t.type?await i._serverTeamItemsCache.refresh([t.id,r.id]):await i._serverCustomItemsCache.refresh([t.id,r.id])},decreaseQuantity:async s=>{let n="user"===t.type?{itemId:r.id,userId:t.id}:"team"===t.type?{itemId:r.id,teamId:t.id}:{itemId:r.id,customCustomerId:t.id};await i._interface.updateItemQuantity(n,{delta:-s,allow_negative:!0}),"user"===t.type?await i._serverUserItemsCache.refresh([t.id,r.id]):"team"===t.type?await i._serverTeamItemsCache.refresh([t.id,r.id]):await i._serverCustomItemsCache.refresh([t.id,r.id])},tryDecreaseQuantity:async s=>{try{let n="user"===t.type?{itemId:r.id,userId:t.id}:"team"===t.type?{itemId:r.id,teamId:t.id}:{itemId:r.id,customCustomerId:t.id};return await i._interface.updateItemQuantity(n,{delta:-s}),"user"===t.type?await i._serverUserItemsCache.refresh([t.id,r.id]):"team"===t.type?await i._serverTeamItemsCache.refresh([t.id,r.id]):await i._serverCustomItemsCache.refresh([t.id,r.id]),!0}catch(t){if(t instanceof P.KnownErrors.ItemQuantityInsufficientAmount)return!1;throw t}}}}async _getUserApiKey(t){let r=w.Result.orThrow(await this._serverCheckApiKeyCache.getOrWait(["user",t.apiKey],"write-only"));return r?this._serverApiKeyFromCrud(r):null}async _getTeamApiKey(t){let r=w.Result.orThrow(await this._serverCheckApiKeyCache.getOrWait(["team",t.apiKey],"write-only"));return r?this._serverApiKeyFromCrud(r):null}_useUserApiKey(t){let r=(0,C.useAsyncCache)(this._serverCheckApiKeyCache,["user",t.apiKey],"serverApp.useUserApiKey()");return(0,S.useMemo)(()=>r?this._serverApiKeyFromCrud(r):null,[r])}_useTeamApiKey(t){let r=(0,C.useAsyncCache)(this._serverCheckApiKeyCache,["team",t.apiKey],"serverApp.useTeamApiKey()");return(0,S.useMemo)(()=>r?this._serverApiKeyFromCrud(r):null,[r])}async _getUserByApiKey(t){let r=await this._getUserApiKey({apiKey:t});return null===r?null:await this.getServerUserById(r.userId)}async _getUserByConvex(t,r){let i=await t.auth.getUserIdentity();if(null===i)return null;let s=await this.getServerUserById(i.subject);return s?.isAnonymous&&!r?null:s}_useUserByConvex(t,r){let i=(0,C.useAsyncCache)(this._convexIdentitySubjectCache,[t],"serverApp.useUserByConvex()");if(null===i)return null;let s=this.useUserById(i);return s?.isAnonymous&&!r?null:s}_useUserByApiKey(t){let r=this._useUserApiKey({apiKey:t});return null===r?null:this.useUserById(r.userId)}async _getTeamByApiKey(t){let r=await this._getTeamApiKey({apiKey:t});return null===r?null:await this.getTeam(r.teamId)}_useTeamByApiKey(t){let r=this._useTeamApiKey({apiKey:t});return null===r?null:this.useTeam(r.teamId)}async createUser(t){let r=await this._interface.createServerUser({primary_email:t.primaryEmail,password:t.password,otp_auth_enabled:t.otpAuthEnabled,primary_email_auth_enabled:t.primaryEmailAuthEnabled,display_name:t.displayName,primary_email_verified:t.primaryEmailVerified,client_metadata:t.clientMetadata,client_read_only_metadata:t.clientReadOnlyMetadata,server_metadata:t.serverMetadata,country_code:t.countryCode,risk_scores:t.riskScores?{sign_up:{bot:t.riskScores.signUp.bot,free_trial_abuse:t.riskScores.signUp.freeTrialAbuse}}:void 0});return await this._refreshUsers(),this._serverUserFromCrud(r)}async getUser(t){if("string"==typeof t)return await this.getServerUserById(t);{if("object"==typeof t&&"apiKey"in t)return await this._getUserByApiKey(t.apiKey);if("object"==typeof t&&"from"in t&&"convex"===t.from)return await this._getUserByConvex(t.ctx,"or"in t&&"anonymous"===t.or);if(t?.or==="anonymous"&&!1===t.includeRestricted)throw Error("Cannot use { or: 'anonymous' } with { includeRestricted: false }. Anonymous users implicitly include restricted users.");this._ensurePersistentTokenStore(t?.tokenStore);let r=await this._getSession(t?.tokenStore),i=w.Result.orThrow(await this._currentServerUserCache.getOrWait([r],"write-only")),s=t?.or==="anonymous"||t?.or==="anonymous-if-exists[deprecated]",n=t?.includeRestricted===!0||s;if(null===i||i.is_anonymous&&!s||i.is_restricted&&!n)switch(t?.or){case"redirect":!i?.is_anonymous&&i?.is_restricted?await this.redirectToOnboarding({replace:!0}):await this.redirectToSignIn({replace:!0});break;case"throw":throw Error("User is not signed in but getUser was called with { or: 'throw' }");case"anonymous":{let t=await this._signUpAnonymously();return await this.getUser({tokenStore:t,or:"anonymous-if-exists[deprecated]",includeRestricted:!0})??(0,x.throwErr)("Something went wrong while signing up anonymously")}case void 0:case"anonymous-if-exists[deprecated]":case"return-null":return null}return i&&this._currentUserFromCrud(i,r)}}async getServerUser(){return console.warn("hexclaveServerApp.getServerUser is deprecated; use hexclaveServerApp.getUser instead"),await this.getUser()}async getServerUserById(t){let r=w.Result.orThrow(await this._serverUserCache.getOrWait([t],"write-only"));return r&&this._serverUserFromCrud(r)}useUser(t){if("string"==typeof t)return this.useUserById(t);{if("object"==typeof t&&"apiKey"in t)return this._useUserByApiKey(t.apiKey);if("object"==typeof t&&"from"in t&&"convex"===t.from)return this._useUserByConvex(t.ctx,"or"in t&&"anonymous"===t.or);if(t?.or==="anonymous"&&!1===t.includeRestricted)throw Error("Cannot use { or: 'anonymous' } with { includeRestricted: false }. Anonymous users implicitly include restricted users.");this._ensurePersistentTokenStore(t?.tokenStore);let r=this._useSession(t?.tokenStore),i=(0,C.useAsyncCache)(this._currentServerUserCache,[r],"serverApp.useUser()");if(t?.or==="anonymous"||t?.or,t?.includeRestricted,null===i)switch(t?.or){case"redirect":throw(0,E.runAsynchronously)(this.redirectToSignIn({replace:!0})),(0,A.suspend)(),new x.HexclaveAssertionError("suspend should never return");case"throw":throw Error("User is not signed in but useUser was called with { or: 'throw' }");case"anonymous":throw(0,E.runAsynchronously)(async()=>{await this._signUpAnonymously()}),(0,A.suspend)(),new x.HexclaveAssertionError("suspend should never return")}return(0,S.useMemo)(()=>i&&this._currentUserFromCrud(i,r),[i,r,t?.or])}}useUserById(t){let r=(0,C.useAsyncCache)(this._serverUserCache,[t],"serverApp.useUserById()");return(0,S.useMemo)(()=>r&&this._serverUserFromCrud(r),[r])}async listUsers(t){let r=w.Result.orThrow(await this._serverUsersCache.getOrWait([t?.cursor,t?.limit,t?.orderBy,t?.desc,t?.query,t?.includeRestricted,t?.includeAnonymous,t?.onlyAnonymous,t?.teamId],"write-only")),i=r.items.map(t=>this._serverUserFromCrud(t));return i.nextCursor=r.pagination?.next_cursor??null,i}useUsers(t){let r=(0,C.useAsyncCache)(this._serverUsersCache,[t?.cursor,t?.limit,t?.orderBy,t?.desc,t?.query,t?.includeRestricted,t?.includeAnonymous,t?.onlyAnonymous,t?.teamId],"serverApp.useUsers()"),i=r.items.map(t=>this._serverUserFromCrud(t));return i.nextCursor=r.pagination?.next_cursor??null,i}_serverPermissionFromCrud(t){return{id:t.id}}_serverTeamPermissionDefinitionFromCrud(t){return{id:t.id,description:t.description,containedPermissionIds:t.contained_permission_ids}}_serverProjectPermissionDefinitionFromCrud(t){return{id:t.id,description:t.description,containedPermissionIds:t.contained_permission_ids}}async getItem(t){if("userId"in t){let r=w.Result.orThrow(await this._serverUserItemsCache.getOrWait([t.userId,t.itemId],"write-only"));return this._serverItemFromCrud({type:"user",id:t.userId},r)}if("teamId"in t){let r=w.Result.orThrow(await this._serverTeamItemsCache.getOrWait([t.teamId,t.itemId],"write-only"));return this._serverItemFromCrud({type:"team",id:t.teamId},r)}{let r=w.Result.orThrow(await this._serverCustomItemsCache.getOrWait([t.customCustomerId,t.itemId],"write-only"));return this._serverItemFromCrud({type:"custom",id:t.customCustomerId},r)}}async listProducts(t){if("userId"in t){let r=w.Result.orThrow(await this._serverUserProductsCache.getOrWait([t.userId,t.cursor??null,t.limit??null],"write-only"));return this._customerProductsFromResponse(r)}if("teamId"in t){let r=w.Result.orThrow(await this._serverTeamProductsCache.getOrWait([t.teamId,t.cursor??null,t.limit??null],"write-only"));return this._customerProductsFromResponse(r)}let r=w.Result.orThrow(await this._serverCustomProductsCache.getOrWait([t.customCustomerId,t.cursor??null,t.limit??null],"write-only"));return this._customerProductsFromResponse(r)}useItem(t){let r,i,s;"userId"in t?(r="user",i=t.userId,s=this._serverUserItemsCache):"teamId"in t?(r="team",i=t.teamId,s=this._serverTeamItemsCache):(r="custom",i=t.customCustomerId,s=this._serverCustomItemsCache);let n=[i,t.itemId],a=(0,C.useAsyncCache)(s,n,"serverApp.useItem()");return(0,S.useMemo)(()=>this._serverItemFromCrud({type:r,id:i},a),[a])}async grantProduct(t){let r,i;"userId"in t?(r="user",i=t.userId):"teamId"in t?(r="team",i=t.teamId):(r="custom",i=t.customCustomerId),await this._interface.grantProduct({customerType:r,customerId:i,productId:"productId"in t?t.productId:void 0,product:"product"in t?t.product:void 0,quantity:t.quantity}),await ("user"===r?this._serverUserProductsCache:"team"===r?this._serverTeamProductsCache:this._serverCustomProductsCache).refresh([i,null,null])}async createTeam(t){let r=await this._interface.createServerTeam(J(t));return await this._serverTeamsCache.refreshWhere(()=>!0),this._serverTeamFromCrud(r)}async listTeams(t){let r=w.Result.orThrow(await this._serverTeamsCache.getOrWait([void 0,t?.orderBy,t?.desc,t?.cursor,t?.limit,t?.query],"write-only")),i=r.items.map(t=>this._serverTeamFromCrud(t));return i.nextCursor=r.pagination?.next_cursor??null,i}useTeams(t){let r=(0,C.useAsyncCache)(this._serverTeamsCache,[void 0,t?.orderBy,t?.desc,t?.cursor,t?.limit,t?.query],"serverApp.useTeams()");return(0,S.useMemo)(()=>{let t=r.items.map(t=>this._serverTeamFromCrud(t));return t.nextCursor=r.pagination?.next_cursor??null,t},[r])}async listTeamMemberPermissions(t,r){let i=r?.recursive??!1;return w.Result.orThrow(await this._serverAllTeamMemberPermissionsCache.getOrWait([t,i],"write-only")).map(t=>({userId:t.user_id,permissionId:t.id}))}useTeamMemberPermissions(t,r){let i=r?.recursive??!1,s=(0,C.useAsyncCache)(this._serverAllTeamMemberPermissionsCache,[t,i],"serverApp.useTeamMemberPermissions()");return(0,S.useMemo)(()=>s.map(t=>({userId:t.user_id,permissionId:t.id})),[s])}async getTeam(t){return"object"==typeof t&&"apiKey"in t?await this._getTeamByApiKey(t.apiKey):(await this.listTeams()).find(r=>r.id===t)??null}useTeam(t){if("object"==typeof t&&"apiKey"in t)return this._useTeamByApiKey(t.apiKey);{let r=this.useTeams();return(0,S.useMemo)(()=>r.find(r=>r.id===t)??null,[r,t])}}_createServerDataVaultStore(t){let r=t=>{if("string"!=typeof t.secret)throw Error("secret must be a string, got "+typeof t.secret)};return{id:t,setValue:async(i,s,n)=>{r(n),await this._interface.setDataVaultStoreValue(n.secret,t,i,s)},getValue:async(i,s)=>(r(s),w.Result.orThrow(await this._serverDataVaultStoreValueCache.getOrWait([t,i,s.secret],"write-only"))),useValue:(i,s)=>(r(s),(0,C.useAsyncCache)(this._serverDataVaultStoreValueCache,[t,i,s.secret],"store.useValue()"))}}async getDataVaultStore(t){return this._createServerDataVaultStore(t)}useDataVaultStore(t){return(0,S.useMemo)(()=>this._createServerDataVaultStore(t),[t])}async sendEmail(t){await this._interface.sendEmail(t),await this._emailDeliveryInfoCache.refresh([])}async getEmailDeliveryStats(){return w.Result.orThrow(await this._emailDeliveryInfoCache.getOrWait([],"write-only"))}useEmailDeliveryStats(){return(0,C.useAsyncCache)(this._emailDeliveryInfoCache,[],"hexclaveServerApp.useEmailDeliveryStats()")}async activateEmailCapacityBoost(){await this._interface.activateEmailCapacityBoost(),await this._emailDeliveryInfoCache.refresh([])}async _refreshSession(t){await Promise.all([super._refreshUser(t),this._currentServerUserCache.refresh([t])])}async _refreshUsers(){await Promise.all([super._refreshUsers(),this._serverUserCache.refreshWhere(()=>!0),this._serverUsersCache.refreshWhere(()=>!0),this._serverContactChannelsCache.refreshWhere(()=>!0),this._serverOAuthProvidersCache.refreshWhere(()=>!0),this._serverUserConnectedAccountsCache.refreshWhere(()=>!0)])}async createOAuthProvider(t){try{let r=await this._interface.createServerOAuthProvider({user_id:t.userId,provider_config_id:t.providerConfigId,account_id:t.accountId,email:t.email,allow_sign_in:t.allowSignIn,allow_connected_accounts:t.allowConnectedAccounts});return await Promise.all([this._serverOAuthProvidersCache.refresh([t.userId]),this._serverUserConnectedAccountsCache.refresh([t.userId])]),w.Result.ok(this._serverOAuthProviderFromCrud(r))}catch(t){if(P.KnownErrors.OAuthProviderAccountIdAlreadyUsedForSignIn.isInstance(t))return w.Result.error(t);throw t}}},tI=t.i(403600);function tk(t){let r=[],i=`/projects/${t.id}/domains`;for(let{domain:s}of(t.config.allow_localhost&&r.push({message:"Localhost is not allowed in production mode, turn off 'Allow localhost' in project settings",relativeFixUrl:i}),t.config.domains)){let n;try{let t=s.replace(/\*+/g,"wildcard-placeholder");n=new URL(t)}catch(n){(0,x.captureError)("production-mode-domain-not-valid",new x.HexclaveAssertionError("Domain was somehow not a valid URL; we should've caught this when setting the domain in the first place",{domain:s,projectId:t})),r.push({message:"Trusted domain is not a valid URL: "+s,relativeFixUrl:i});continue}(0,Q.isLocalhost)(n)?r.push({message:"Localhost domains are not allowed to be trusted in production mode: "+s,relativeFixUrl:i}):n.hostname.match(/^\d+(\.\d+)*$/)?r.push({message:"Direct IPs are not valid for trusted domains in production mode: "+s,relativeFixUrl:i}):"https:"!==n.protocol&&r.push({message:"Trusted domains should be HTTPS: "+s,relativeFixUrl:i})}return r}var tN=class extends tC{constructor(t,r){const i=(0,C.resolveConstructorOptions)(t),s=i.publishableClientKey??(0,C.getDefaultPublishableClientKey)();super(i,{...r,interface:r?.interface??(()=>{let t=(0,C.resolveApiUrls)(i.baseUrl);return new tI.HexclaveAdminInterface({getBaseUrl:()=>t()[0],getApiUrls:t,projectId:i.projectId??(0,C.getDefaultProjectId)(),extraRequestHeaders:i.extraRequestHeaders??(0,C.getDefaultExtraRequestHeaders)(),clientVersion:C.clientVersion,...i.projectOwnerSession?{projectOwnerSession:i.projectOwnerSession}:{...s?{publishableClientKey:s}:{},secretServerKey:i.secretServerKey??(0,C.getDefaultSecretServerKey)(),superSecretAdminKey:i.superSecretAdminKey??(0,C.getDefaultSuperSecretAdminKey)()}})})()}),this._adminProjectCache=(0,C.createCache)(async()=>await this._interface.getProject()),this._internalApiKeysCache=(0,C.createCache)(async()=>await this._interface.listInternalApiKeys()),this._adminEmailThemeCache=(0,C.createCache)(async([t])=>await this._interface.getEmailTheme(t)),this._adminEmailThemesCache=(0,C.createCache)(async()=>await this._interface.listEmailThemes()),this._adminEmailTemplatesCache=(0,C.createCache)(async()=>await this._interface.listInternalEmailTemplates()),this._adminEmailDraftsCache=(0,C.createCache)(async()=>await this._interface.listInternalEmailDrafts()),this._adminTeamPermissionDefinitionsCache=(0,C.createCache)(async()=>await this._interface.listTeamPermissionDefinitions()),this._adminProjectPermissionDefinitionsCache=(0,C.createCache)(async()=>await this._interface.listProjectPermissionDefinitions()),this._svixTokenCache=(0,C.createCache)(async()=>await this._interface.getSvixToken()),this._metricsCache=(0,C.createCache)(async([t,r])=>{let i=r?Object.fromEntries(new URLSearchParams(r)):void 0;return await this._interface.getMetrics(t,i)}),this._userActivityCache=(0,C.createCache)(async([t])=>await this._interface.getUserActivity(t)),this._metricsUserCountsCache=(0,C.createCache)(async()=>await this._interface.getMetricsUserCounts()),this._emailPreviewCache=(0,C.createCache)(async([t,r,i,s])=>await this._interface.renderEmailPreview({themeId:t,themeTsxSource:r,templateId:i,templateTsxSource:s})),this._emailPreviewWithEditableMarkersCache=(0,C.createCache)(async([t,r,i,s,n])=>await this._interface.renderEmailPreview({themeId:t,themeTsxSource:r,templateId:i,templateTsxSource:s,editableMarkers:!0,editableSource:n})),this._configOverridesCache=(0,C.createCache)(async()=>await this._interface.getConfig()),this._stripeAccountInfoCache=(0,C.createCache)(async()=>{try{return await this._interface.getStripeAccountInfo()}catch(t){if(t?.status===404)return null;throw t}}),this._transactionsCache=(0,C.createCache)(async([t,r,i,s,n])=>await this._interface.listTransactions({cursor:t,limit:r,type:i,customerType:s,customerId:n}))}_adminConfigFromCrud(t){return JSON.parse(t.config_string)}_adminOwnedProjectFromCrud(t,r){if(null!==this._tokenStoreInit)throw new x.HexclaveAssertionError("Owned apps must always have tokenStore === null — did you not create this project with app._createOwnedApp()?");return{...this._adminProjectFromCrud(t,r),app:this}}_adminProjectFromCrud(t,r){if(t.id!==this.projectId)throw new x.HexclaveAssertionError(`The project ID of the provided project JSON (${t.id}) does not match the project ID of the app (${this.projectId})!`);let i=this;return{id:t.id,displayName:t.display_name,description:t.description,createdAt:new Date(t.created_at_millis),isProductionMode:t.is_production_mode,isDevelopmentEnvironment:t.is_development_environment,ownerTeamId:t.owner_team_id,onboardingStatus:t.onboarding_status,logoUrl:t.logo_url,logoFullUrl:t.logo_full_url,logoDarkModeUrl:t.logo_dark_mode_url,logoFullDarkModeUrl:t.logo_full_dark_mode_url,config:{signUpEnabled:t.config.sign_up_enabled,credentialEnabled:t.config.credential_enabled,magicLinkEnabled:t.config.magic_link_enabled,passkeyEnabled:t.config.passkey_enabled,clientTeamCreationEnabled:t.config.client_team_creation_enabled,clientUserDeletionEnabled:t.config.client_user_deletion_enabled,allowLocalhost:t.config.allow_localhost,oauthAccountMergeStrategy:t.config.oauth_account_merge_strategy,allowUserApiKeys:t.config.allow_user_api_keys,allowTeamApiKeys:t.config.allow_team_api_keys,oauthProviders:t.config.oauth_providers.map(t=>"shared"===t.type?{id:t.id,type:"shared"}:{id:t.id,type:"standard",clientId:t.client_id??(0,x.throwErr)("Client ID is missing"),clientSecret:t.client_secret??(0,x.throwErr)("Client secret is missing"),facebookConfigId:t.facebook_config_id,microsoftTenantId:t.microsoft_tenant_id,appleBundleIds:t.apple_bundle_ids}),emailConfig:"shared"===t.config.email_config.type?{type:"shared"}:{type:"standard",host:t.config.email_config.host??(0,x.throwErr)("Email host is missing"),port:t.config.email_config.port??(0,x.throwErr)("Email port is missing"),username:t.config.email_config.username??(0,x.throwErr)("Email username is missing"),password:t.config.email_config.password??(0,x.throwErr)("Email password is missing"),senderName:t.config.email_config.sender_name??(0,x.throwErr)("Email sender name is missing"),senderEmail:t.config.email_config.sender_email??(0,x.throwErr)("Email sender email is missing")},emailTheme:t.config.email_theme,domains:t.config.domains.map(t=>({domain:t.domain,handlerPath:t.handler_path})),createTeamOnSignUp:t.config.create_team_on_sign_up,teamCreatorDefaultPermissions:t.config.team_creator_default_permissions,teamMemberDefaultPermissions:t.config.team_member_default_permissions,userDefaultPermissions:t.config.user_default_permissions},getConfig:async()=>i._adminConfigFromCrud(await i._interface.getConfig()),useConfig(){let t=(0,C.useAsyncCache)(i._configOverridesCache,[],"project.useConfig()");return(0,S.useMemo)(()=>i._adminConfigFromCrud(t),[t])},async updateConfig(t){await i._interface.updateConfigOverride("environment",t),await i._refreshProjectConfig()},async pushConfig(t,r){var s;await i._interface.setConfigOverride("branch",t,"pushed-from-github"===(s=r.source).type?{type:"pushed-from-github",owner:s.owner,repo:s.repo,branch:s.branch,commit_hash:s.commitHash,config_file_path:s.configFilePath,workflow_path:s.workflowPath}:s),await i._refreshProjectConfig()},async updatePushedConfig(t){await i._interface.updateConfigOverride("branch",t),await i._refreshProjectConfig()},getPushedConfigSource:async()=>{var t;return"pushed-from-github"===(t=await i._interface.getPushedConfigSource()).type?{type:"pushed-from-github",owner:t.owner,repo:t.repo,branch:t.branch,commitHash:t.commit_hash,configFilePath:t.config_file_path,workflowPath:t.workflow_path}:t},async unlinkPushedConfigSource(){await i._interface.unlinkPushedConfigSource(),await i._refreshProjectConfig()},async resetConfigOverrideKeys(t,r){await i._interface.resetConfigOverrideKeys(t,r),await i._refreshProjectConfig()},getConfigOverride:async t=>JSON.parse((await i._interface.getConfigOverride(t)).config_string),async replaceConfigOverride(t,r){if("branch"===t){let s=await i._interface.getPushedConfigSource();await i._interface.setConfigOverride(t,r,s)}else await i._interface.setConfigOverride(t,r);await i._refreshProjectConfig()},async update(t){let{requirePublishableClientKey:s,...n}=t,a=en(n),o=!!a.config&&(0,z.typedValues)(a.config).some(t=>void 0!==t);(0,z.typedEntries)(a).some(([t,r])=>"config"===t?o:void 0!==r)&&(await i._interface.updateProject(a),await r()),void 0!==s&&(await i._interface.updateConfigOverride("project",{"project.requirePublishableClientKey":s}),await i._refreshProjectConfig())},async delete(){await i._interface.deleteProject()},getProductionModeErrors:async()=>tk(t),useProductionModeErrors:()=>tk(t)}}_adminEmailTemplateFromCrud(t){return{type:t.type,subject:t.subject,content:t.content,isDefault:t.is_default}}async getProject(){return this._adminProjectFromCrud(w.Result.orThrow(await this._adminProjectCache.getOrWait([],"write-only")),()=>this._refreshProject())}useProject(){let t=(0,C.useAsyncCache)(this._adminProjectCache,[],"adminApp.useProject()");return(0,S.useMemo)(()=>this._adminProjectFromCrud(t,()=>this._refreshProject()),[t])}_createInternalApiKeyBaseFromCrud(t){let r=this;return{id:t.id,description:t.description,expiresAt:new Date(t.expires_at_millis),manuallyRevokedAt:t.manually_revoked_at_millis?new Date(t.manually_revoked_at_millis):null,createdAt:new Date(t.created_at_millis),isValid(){return null===this.whyInvalid()},whyInvalid(){return this.expiresAt.getTime()<Date.now()?"expired":this.manuallyRevokedAt?"manually-revoked":null},async revoke(){let i=await r._interface.revokeInternalApiKeyById(t.id);return await r._refreshInternalApiKeys(),i}}}_createInternalApiKeyFromCrud(t){return{...this._createInternalApiKeyBaseFromCrud(t),publishableClientKey:t.publishable_client_key?{lastFour:t.publishable_client_key.last_four}:null,secretServerKey:t.secret_server_key?{lastFour:t.secret_server_key.last_four}:null,superSecretAdminKey:t.super_secret_admin_key?{lastFour:t.super_secret_admin_key.last_four}:null}}_createInternalApiKeyFirstViewFromCrud(t){return{...this._createInternalApiKeyBaseFromCrud(t),publishableClientKey:t.publishable_client_key,secretServerKey:t.secret_server_key,superSecretAdminKey:t.super_secret_admin_key}}async listInternalApiKeys(){return w.Result.orThrow(await this._internalApiKeysCache.getOrWait([],"write-only")).map(t=>this._createInternalApiKeyFromCrud(t))}useInternalApiKeys(){let t=(0,C.useAsyncCache)(this._internalApiKeysCache,[],"adminApp.useInternalApiKeys()");return(0,S.useMemo)(()=>t.map(t=>this._createInternalApiKeyFromCrud(t)),[t])}async createInternalApiKey(t){let r=await this._interface.createInternalApiKey({description:t.description,expires_at_millis:t.expiresAt.getTime(),has_publishable_client_key:t.hasPublishableClientKey,has_secret_server_key:t.hasSecretServerKey,has_super_secret_admin_key:t.hasSuperSecretAdminKey});return await this._refreshInternalApiKeys(),this._createInternalApiKeyFirstViewFromCrud(r)}useEmailThemes(){let t=(0,C.useAsyncCache)(this._adminEmailThemesCache,[],"adminApp.useEmailThemes()");return(0,S.useMemo)(()=>t.map(t=>({id:t.id,displayName:t.display_name})),[t])}useEmailTemplates(){let t=(0,C.useAsyncCache)(this._adminEmailTemplatesCache,[],"adminApp.useEmailTemplates()");return(0,S.useMemo)(()=>t.map(t=>({id:t.id,displayName:t.display_name,themeId:t.theme_id,tsxSource:t.tsx_source})),[t])}useEmailDrafts(){let t=(0,C.useAsyncCache)(this._adminEmailDraftsCache,[],"adminApp.useEmailDrafts()");return(0,S.useMemo)(()=>t.map(t=>({id:t.id,displayName:t.display_name,themeId:t.theme_id,tsxSource:t.tsx_source,sentAt:t.sent_at_millis?new Date(t.sent_at_millis):null})),[t])}async listEmailThemes(){return w.Result.orThrow(await this._adminEmailThemesCache.getOrWait([],"write-only")).map(t=>({id:t.id,displayName:t.display_name}))}async listEmailTemplates(){return w.Result.orThrow(await this._adminEmailTemplatesCache.getOrWait([],"write-only")).map(t=>({id:t.id,displayName:t.display_name,themeId:t.theme_id,tsxSource:t.tsx_source}))}async listEmailDrafts(){return w.Result.orThrow(await this._adminEmailDraftsCache.getOrWait([],"write-only")).map(t=>({id:t.id,displayName:t.display_name,themeId:t.theme_id,tsxSource:t.tsx_source,sentAt:t.sent_at_millis?new Date(t.sent_at_millis):null}))}async createTeamPermissionDefinition(t){let r=await this._interface.createTeamPermissionDefinition({id:t.id,description:t.description,contained_permission_ids:t.containedPermissionIds});return await this._adminTeamPermissionDefinitionsCache.refresh([]),this._serverTeamPermissionDefinitionFromCrud(r)}async updateTeamPermissionDefinition(t,r){await this._interface.updateTeamPermissionDefinition(t,{description:r.description,contained_permission_ids:r.containedPermissionIds}),await this._adminTeamPermissionDefinitionsCache.refresh([])}async deleteTeamPermissionDefinition(t){await this._interface.deleteTeamPermissionDefinition(t),await this._adminTeamPermissionDefinitionsCache.refresh([])}async listTeamPermissionDefinitions(){return w.Result.orThrow(await this._adminTeamPermissionDefinitionsCache.getOrWait([],"write-only")).map(t=>this._serverTeamPermissionDefinitionFromCrud(t))}async listTeamPermissionDefinitionsPaginated(t){let r=await this._interface.listTeamPermissionDefinitionsPaginated(t);return{items:r.items.map(t=>this._serverTeamPermissionDefinitionFromCrud(t)),nextCursor:r.nextCursor}}useTeamPermissionDefinitions(){let t=(0,C.useAsyncCache)(this._adminTeamPermissionDefinitionsCache,[],"adminApp.useTeamPermissionDefinitions()");return(0,S.useMemo)(()=>t.map(t=>this._serverTeamPermissionDefinitionFromCrud(t)),[t])}async createProjectPermissionDefinition(t){let r=await this._interface.createProjectPermissionDefinition({id:t.id,description:t.description,contained_permission_ids:t.containedPermissionIds});return await this._adminProjectPermissionDefinitionsCache.refresh([]),this._serverProjectPermissionDefinitionFromCrud(r)}async updateProjectPermissionDefinition(t,r){await this._interface.updateProjectPermissionDefinition(t,{description:r.description,contained_permission_ids:r.containedPermissionIds}),await this._adminProjectPermissionDefinitionsCache.refresh([])}async deleteProjectPermissionDefinition(t){await this._interface.deleteProjectPermissionDefinition(t),await this._adminProjectPermissionDefinitionsCache.refresh([])}async listProjectPermissionDefinitions(){return w.Result.orThrow(await this._adminProjectPermissionDefinitionsCache.getOrWait([],"write-only")).map(t=>this._serverProjectPermissionDefinitionFromCrud(t))}useProjectPermissionDefinitions(){let t=(0,C.useAsyncCache)(this._adminProjectPermissionDefinitionsCache,[],"adminApp.useProjectPermissionDefinitions()");return(0,S.useMemo)(()=>t.map(t=>this._serverProjectPermissionDefinitionFromCrud(t)),[t])}useSvixToken(){let t=(0,C.useAsyncCache)(this._svixTokenCache,[],"adminApp.useSvixToken()");return{token:t.token,url:t.url}}async _refreshProject(){await Promise.all([super._refreshProject(),this._adminProjectCache.refresh([])])}async _refreshProjectConfig(){await Promise.all([this._configOverridesCache.refresh([]),this._adminProjectCache.refresh([])])}async _refreshInternalApiKeys(){await this._internalApiKeysCache.refresh([])}async _refreshUsers(){await Promise.all([super._refreshUsers(),this._metricsCache.refreshWhere(()=>!0),this._metricsUserCountsCache.refresh([])])}get[es.hexclaveAppInternalsSymbol](){return{...super[es.hexclaveAppInternalsSymbol],useMetrics:(t=!1,r)=>{let i=(()=>{if(null==r)return"";let t=new URLSearchParams;for(let i of["browser","country_code","device","os","referrer","since","until"]){let s=r[i];null!=s&&t.set(i,s)}return t.toString()})();return(0,C.useAsyncCache)(this._metricsCache,[t,i],"adminApp.useMetrics()")},useUserActivity:t=>(0,C.useAsyncCache)(this._userActivityCache,[t],"adminApp.useUserActivity()"),useMetricsUserCounts:()=>(0,C.useAsyncCache)(this._metricsUserCountsCache,[],"adminApp.useMetricsUserCounts()")}}async sendTestEmail(t){let r;try{r=await this._interface.sendTestEmail({recipient_email:t.recipientEmail,email_config:{...(0,z.pick)(t.emailConfig,["host","port","username","password"]),sender_email:t.emailConfig.senderEmail,sender_name:t.emailConfig.senderName}})}catch(t){if(t instanceof P.KnownErrors.ItemQuantityInsufficientAmount)return w.Result.error({errorMessage:"Monthly email sending limit exceeded for your plan. Please upgrade your plan or wait until next month before sending more test emails."});throw t}return r.success?w.Result.ok(void 0):w.Result.error({errorMessage:r.error_message??(0,x.throwErr)("Email test error not specified")})}async sendTestWebhook(t){let r=await this._interface.sendTestWebhook({endpoint_id:t.endpointId});return r.success?w.Result.ok(void 0):w.Result.error({errorMessage:r.error_message??(0,x.throwErr)("Webhook test error not specified")})}async listSentEmails(){return(await this._interface.listSentEmails()).items.map(t=>({id:t.id,to:t.to??[],subject:t.subject,recipient:t.to?.[0]??"",sentAt:new Date(t.sent_at_millis),error:t.error}))}async setupManagedEmailProvider(t){let r=await this._interface.setupManagedEmailProvider({subdomain:t.subdomain,sender_local_part:t.senderLocalPart});return{domainId:r.domain_id,subdomain:r.subdomain,senderLocalPart:r.sender_local_part,nameServerRecords:r.name_server_records,status:r.status}}async checkManagedEmailStatus(t){return{status:(await this._interface.checkManagedEmailStatus({domain_id:t.domainId,subdomain:t.subdomain,sender_local_part:t.senderLocalPart})).status}}async listManagedEmailDomains(){return(await this._interface.listManagedEmailDomains()).items.map(t=>({domainId:t.domain_id,subdomain:t.subdomain,senderLocalPart:t.sender_local_part,status:t.status,nameServerRecords:t.name_server_records}))}async applyManagedEmailProvider(t){let r=await this._interface.applyManagedEmailProvider({domain_id:t.domainId});return await this._refreshProjectConfig(),r}async deleteManagedEmailDomain(t){return await this._interface.deleteManagedEmailDomain({resend_domain_id:t.resendDomainId})}async sendSignInInvitationEmail(t,r){await this._interface.sendSignInInvitationEmail(t,r)}async createEmailTemplate(t){let r=await this._interface.createEmailTemplate(t);return await this._adminEmailTemplatesCache.refresh([]),r}async deleteEmailTemplate(t){await this._interface.deleteEmailTemplate(t),await this._adminEmailTemplatesCache.refresh([])}async createEmailDraft(t){let r=await this._interface.createEmailDraft({display_name:t.displayName,theme_id:t.themeId,tsx_source:t.tsxSource});return await this._adminEmailDraftsCache.refresh([]),r}async updateEmailDraft(t,r){await this._interface.updateEmailDraft(t,{display_name:r.displayName,theme_id:r.themeId,tsx_source:r.tsxSource}),await this._adminEmailDraftsCache.refresh([])}async deleteEmailDraft(t){await this._interface.deleteEmailDraft(t);let r=this._adminEmailDraftsCache.getIfCached([]);"ok"===r.status&&"ok"===r.data.status&&this._adminEmailDraftsCache.forceSetCachedValue([],w.Result.ok(r.data.data.filter(r=>r.id!==t))),await this._adminEmailDraftsCache.refresh([])}async refreshEmailDrafts(){await this._adminEmailDraftsCache.refresh([])}async saveChatMessage(t,r){await this._interface.saveChatMessage(t,r)}async listChatMessages(t){return await this._interface.listChatMessages(t)}async rewriteTemplateSourceWithAI(t){return{tsxSource:(await this._interface.rewriteTemplateSourceWithAI(t)).tsx_source}}async createEmailTheme(t){let r=await this._interface.createEmailTheme(t);return await this._adminEmailThemesCache.refresh([]),r}async getEmailPreview(t){return(await this._interface.renderEmailPreview(t)).html}useEmailPreview(t){return(0,C.useAsyncCache)(this._emailPreviewCache,[t.themeId,t.themeTsxSource,t.templateId,t.templateTsxSource],"adminApp.useEmailPreview()").html}async getEmailPreviewWithEditableMarkers(t){let r=await this._interface.renderEmailPreview({...t,editableMarkers:!0,editableSource:t.editableSource});return{html:r.html,editableRegions:r.editable_regions}}useEmailPreviewWithEditableMarkers(t){let r=(0,C.useAsyncCache)(this._emailPreviewWithEditableMarkersCache,[t.themeId,t.themeTsxSource,t.templateId,t.templateTsxSource,t.editableSource],"adminApp.useEmailPreviewWithEditableMarkers()");return{html:r.html,editableRegions:r.editable_regions}}useEmailTheme(t){let r=(0,C.useAsyncCache)(this._adminEmailThemeCache,[t],"adminApp.useEmailTheme()");return{displayName:r.display_name,tsxSource:r.tsx_source}}async updateEmailTheme(t,r){await this._interface.updateEmailTheme(t,r),await this._adminEmailThemesCache.refresh([]),await this._adminEmailThemeCache.invalidate([t])}async deleteEmailTheme(t){await this._interface.deleteEmailTheme(t),await this._adminEmailThemesCache.refresh([]),await this._adminEmailThemeCache.invalidate([t])}async updateEmailTemplate(t,r,i){let s=await this._interface.updateEmailTemplate(t,r,i);return await this._adminEmailTemplatesCache.refresh([]),{renderedHtml:s.rendered_html}}async setupPayments(){let t=await this._interface.setupPayments();return await this._stripeAccountInfoCache.refresh([]),t}async createStripeWidgetAccountSession(){return await this._interface.createStripeWidgetAccountSession()}async getPaymentMethodConfigs(){return await this._interface.getPaymentMethodConfigs()}async updatePaymentMethodConfigs(t,r){await this._interface.updatePaymentMethodConfigs(t,r)}async createItemQuantityChange(t){await this._interface.updateItemQuantity({itemId:t.itemId,..."userId"in t?{userId:t.userId}:"teamId"in t?{teamId:t.teamId}:{customCustomerId:t.customCustomerId}},{delta:t.quantity,expires_at:t.expiresAt,description:t.description,allow_negative:!0})}async refundTransaction(t){let r=await this._interface.refundTransaction({type:t.type,id:t.id,invoiceId:t.invoiceId,amountUsd:t.amountUsd,endAction:t.endAction});return await this._transactionsCache.invalidateWhere(()=>!0),{refundTransactionId:r.refundTransactionId}}async listTransactions(t){return w.Result.orThrow(await this._transactionsCache.getOrWait([t.cursor,t.limit,t.type,t.customerType,t.customerId],"write-only"))}_emailOutboxCrudToAdmin(t){let r,i=t.to;r="user-primary-email"===i.type?{type:"user-primary-email",userId:i.user_id}:"user-custom-emails"===i.type?{type:"user-custom-emails",userId:i.user_id,emails:i.emails}:{type:"custom-emails",emails:i.emails};let s={id:t.id,createdAt:new Date(t.created_at_millis),updatedAt:new Date(t.updated_at_millis),tsxSource:t.tsx_source,themeId:t.theme_id??null,to:r,scheduledAt:new Date(t.scheduled_at_millis),createdWith:t.created_with,emailDraftId:t.email_draft_id,emailProgrammaticCallTemplateId:t.email_programmatic_call_template_id,variables:t.variables??{},isPaused:!1,hasRendered:!1,hasDelivered:!1,sendRetries:t.send_retries,nextSendRetryAt:t.next_send_retry_at_millis?new Date(t.next_send_retry_at_millis):null,sendAttemptErrors:t.send_attempt_errors?t.send_attempt_errors.map(t=>({attemptNumber:t.attempt_number,timestamp:t.timestamp,externalMessage:t.external_message,externalDetails:t.external_details,internalMessage:t.internal_message,internalDetails:t.internal_details})):null},n=t.has_rendered?{...s,startedRenderingAt:new Date(t.started_rendering_at_millis),renderedAt:new Date(t.rendered_at_millis),subject:t.subject,html:t.html,text:t.text,isTransactional:t.is_transactional,isHighPriority:t.is_high_priority,notificationCategoryId:t.notification_category_id,hasRendered:!0}:null,a=n&&t.started_sending_at_millis?{...n,startedSendingAt:new Date(t.started_sending_at_millis)}:null,o=a&&t.has_delivered?{...a,deliveredAt:new Date(t.delivered_at_millis),hasDelivered:!0}:null;switch(t.status){case"paused":return{...s,status:"paused",simpleStatus:"in-progress",isPaused:!0};case"preparing":return{...s,status:"preparing",simpleStatus:"in-progress"};case"rendering":return{...s,status:"rendering",simpleStatus:"in-progress",startedRenderingAt:new Date(t.started_rendering_at_millis)};case"render-error":return{...s,status:"render-error",simpleStatus:"error",startedRenderingAt:new Date(t.started_rendering_at_millis),renderedAt:new Date(t.rendered_at_millis),renderError:t.render_error};case"scheduled":return{...n,status:"scheduled",simpleStatus:"in-progress"};case"queued":return{...n,status:"queued",simpleStatus:"in-progress"};case"sending":return{...a,status:"sending",simpleStatus:"in-progress"};case"server-error":return{...a,status:"server-error",simpleStatus:"error",errorAt:new Date(t.error_at_millis),serverError:t.server_error};case"skipped":return{...s,status:"skipped",simpleStatus:"ok",skippedAt:new Date(t.skipped_at_millis),skippedReason:t.skipped_reason,skippedDetails:t.skipped_details??{},hasRendered:t.has_rendered,startedRenderingAt:t.started_rendering_at_millis?new Date(t.started_rendering_at_millis):void 0,renderedAt:t.rendered_at_millis?new Date(t.rendered_at_millis):void 0,subject:t.subject,html:t.html,text:t.text,isTransactional:t.is_transactional,isHighPriority:t.is_high_priority,notificationCategoryId:t.notification_category_id,startedSendingAt:t.started_sending_at_millis?new Date(t.started_sending_at_millis):void 0};case"bounced":return{...a,status:"bounced",simpleStatus:"error",bouncedAt:new Date(t.bounced_at_millis)};case"delivery-delayed":return{...a,status:"delivery-delayed",simpleStatus:"ok",deliveryDelayedAt:new Date(t.delivery_delayed_at_millis)};case"sent":return{...o,status:"sent",simpleStatus:"ok",canHaveDeliveryInfo:t.can_have_delivery_info};case"opened":return{...o,status:"opened",simpleStatus:"ok",openedAt:new Date(t.opened_at_millis),canHaveDeliveryInfo:!0};case"clicked":return{...o,status:"clicked",simpleStatus:"ok",clickedAt:new Date(t.clicked_at_millis),canHaveDeliveryInfo:!0};case"marked-as-spam":return{...o,status:"marked-as-spam",simpleStatus:"ok",markedAsSpamAt:new Date(t.marked_as_spam_at_millis),canHaveDeliveryInfo:!0};default:throw new x.HexclaveAssertionError(`Unknown email outbox status: ${t.status}`,{status:t.status})}}async listOutboxEmails(t){let r=await this._interface.listOutboxEmails({status:t?.status,simple_status:t?.simpleStatus,limit:t?.limit,cursor:t?.cursor});return{items:r.items.map(t=>this._emailOutboxCrudToAdmin(t)),nextCursor:r.pagination?.next_cursor??null}}async getOutboxEmail(t){let r=await this._interface.getOutboxEmail(t);return this._emailOutboxCrudToAdmin(r)}async updateOutboxEmail(t,r){let i=await this._interface.updateOutboxEmail(t,{is_paused:r.isPaused,scheduled_at_millis:r.scheduledAtMillis,cancel:r.cancel,tsx_source:r.tsxSource,theme_id:r.themeId});return this._emailOutboxCrudToAdmin(i)}async pauseOutboxEmail(t){return await this.updateOutboxEmail(t,{isPaused:!0})}async unpauseOutboxEmail(t){return await this.updateOutboxEmail(t,{isPaused:!1})}async cancelOutboxEmail(t){return await this.updateOutboxEmail(t,{cancel:!0})}useTransactions(t){return(0,C.useAsyncCache)(this._transactionsCache,[t.cursor,t.limit,t.type,t.customerType,t.customerId],"adminApp.useTransactions()")}async getStripeAccountInfo(){return await this._interface.getStripeAccountInfo()}useStripeAccountInfo(){return(0,C.useAsyncCache)(this._stripeAccountInfoCache,[],"adminApp.useStripeAccountInfo()")}async queryAnalytics(t){return await this._interface.queryAnalytics(t)}async getAnalyticsClickmap(t){return await this._interface.getAnalyticsClickmap({kind:t.kind,member_user_ids:t.memberUserIds,route_path:t.routePath,route_regex:t.routeRegex,url_pattern:t.urlPattern,user_id:t.userId,replay_id:t.replayId,device:t.device,viewport_width_min:t.viewportWidthMin,viewport_width_max:t.viewportWidthMax,sampling:t.sampling,since:t.since,until:t.until})}async createAnalyticsClickmapToken(t){return await this._interface.createAnalyticsClickmapToken(t)}async listSessionReplays(t){let r=await this._interface.listSessionReplays({cursor:t?.cursor,limit:t?.limit,user_ids:t?.userIds,team_ids:t?.teamIds,duration_ms_min:t?.durationMsMin,duration_ms_max:t?.durationMsMax,last_event_at_from_millis:t?.lastEventAtFromMillis,last_event_at_to_millis:t?.lastEventAtToMillis,click_count_min:t?.clickCountMin});return{items:r.items.map(t=>({id:t.id,projectUser:{id:t.project_user.id,displayName:t.project_user.display_name,primaryEmail:t.project_user.primary_email},startedAt:new Date(t.started_at_millis),lastEventAt:new Date(t.last_event_at_millis),chunkCount:t.chunk_count,eventCount:t.event_count})),nextCursor:r.pagination.next_cursor}}async getSessionReplay(t){let r=await this._interface.getSessionReplay(t);return{id:r.id,projectUser:{id:r.project_user.id,displayName:r.project_user.display_name,primaryEmail:r.project_user.primary_email},startedAt:new Date(r.started_at_millis),lastEventAt:new Date(r.last_event_at_millis),chunkCount:r.chunk_count,eventCount:r.event_count}}async listSessionReplayChunks(t,r){let i=await this._interface.listSessionReplayChunks(t,{cursor:r?.cursor,limit:r?.limit});return{items:i.items.map(t=>({id:t.id,batchId:t.batch_id,sessionReplaySegmentId:t.session_replay_segment_id,browserSessionId:t.browser_session_id,eventCount:t.event_count,byteLength:t.byte_length,firstEventAt:new Date(t.first_event_at_millis),lastEventAt:new Date(t.last_event_at_millis),createdAt:new Date(t.created_at_millis)})),nextCursor:i.pagination.next_cursor}}async getSessionReplayChunkEvents(t,r){return await this._interface.getSessionReplayChunkEvents(t,r)}async getSessionReplayEvents(t,r){let i=await this._interface.getSessionReplayEvents(t,r);return{chunks:i.chunks.map(t=>({id:t.id,batchId:t.batch_id,sessionReplaySegmentId:t.session_replay_segment_id,eventCount:t.event_count,byteLength:t.byte_length,firstEventAt:new Date(t.first_event_at_millis),lastEventAt:new Date(t.last_event_at_millis),createdAt:new Date(t.created_at_millis)})),chunkEvents:i.chunk_events.map(t=>({chunkId:t.chunk_id,events:t.events}))}}async previewAffectedUsersByOnboardingChange(t,r){let i=await this._interface.previewAffectedUsersByOnboardingChange({require_email_verification:t.requireEmailVerification},r);return{affectedUsers:i.affected_users.map(t=>({id:t.id,displayName:t.display_name,primaryEmail:t.primary_email,restrictedReason:t.restricted_reason})),totalAffectedCount:i.total_affected_count}}};let{_HexclaveAdminAppImpl:tO,_HexclaveClientAppImpl:tD,_HexclaveServerAppImpl:tj}=(tw.LazyStackAdminAppImpl.value=tN,{_HexclaveAdminAppImpl:eo(tN),_HexclaveClientAppImpl:eo(tw),_HexclaveServerAppImpl:eo(tC)});function tL(t){return void 0===tR(t)}function tR(t,r={}){let i=r.configName??"config";if(null===t||"object"!=typeof t)return`${i} must be a non-null object`;for(let[r,s]of Object.entries(t)){if(void 0===s)continue;if("string"!=typeof r)return`${i} must have only string keys (found: ${typeof r})`;if(!r.match(/^[a-zA-Z0-9_:$][a-zA-Z_:$0-9\-]*(?:\.[a-zA-Z0-9_:$][a-zA-Z_:$0-9\-]*)*$/))return`All keys of ${i} must consist of only alphanumeric characters, dots, underscores, colons, dollar signs, or hyphens and start with a character other than a hyphen (found: ${r})`;let t=function t(r,i={}){let s=i.valueName??"value";switch(typeof r){case"string":case"number":case"boolean":break;case"object":if(null===r);else if(Array.isArray(r))for(let[i,n]of r.entries()){let r=`${s}[${i}]`;if(null===n)return`${r} is null; tuple elements cannot be null`;let a=t(n,{valueName:r});if(a)return a}else{let t=tR(r,{configName:s});if(t)return t}break;default:return`${s} has an invalid value type ${typeof r} (value: ${r})`}}(s,{valueName:`${i}.${r}`});if(t)return t}}function tM(t){let r=tR(t);if(r)throw new x.HexclaveAssertionError(`Invalid config: ${r}`,{c:t})}function tF(t,...r){if(0===r.length)return t;if(r.length>1)return tF(tF(t,r[0]),...r.slice(1));let i=r[0];tM(t),tM(i);let s=t;for(let t of Object.keys((0,z.filterUndefined)(i)))s=Object.fromEntries(Object.entries(s).filter(([r])=>r!==t&&!r.startsWith(t+".")));return{...s,...(0,z.filterUndefined)(i)}}var tB=class extends Error{constructor(...t){super(...t)}};function tU(t,r={}){tM(t);let i=r.onDotIntoNonObject??"throw",s=r.onDotIntoNull??"like-non-object",n=t=>t.match(/\./g)?.length??0,a={},o=Object.keys(t).sort((t,r)=>n(t)-n(r));i:for(let n of o){var l,p,u,c;let o=n.split("."),d=o.pop()??(0,x.throwErr)("split returns empty array?"),h=(0,z.get)(t,n);if(void 0===h)continue;let f=a;for(let t of o){if(!(0,z.hasAndNotUndefined)(f,t))switch("like-non-object"===s?i:s){case"throw":throw new tB(`Tried to use dot notation to access ${JSON.stringify(n)}, but ${JSON.stringify(t)} doesn't exist on the object (or is null).`);case"ignore":r.droppedKeys?.push(n);continue i;case"empty-object":(0,z.set)(f,t,{})}let a=(0,z.get)(f,t);if("object"!=typeof a)switch(i){case"throw":throw new tB(`Tried to use dot notation to access ${JSON.stringify(n)}, but ${JSON.stringify(t)} is not an object.`);case"ignore":r.droppedKeys?.push(n);continue i}f=a}l=f,p=d,u=h,c=r,null===u?(0,z.hasAndNotUndefined)(l,p)&&(0,z.deleteKey)(l,p):(0,z.set)(l,p,function t(r,i){if(null===r)throw new tB("Tried to normalize a null value");return Array.isArray(r)?r.map(r=>t(r,i)):"object"==typeof r?tU(r,i):r}(u,c))}return a}tB.prototype.name="NormalizationError",t.s(["isValidConfig",0,tL,"normalize",0,tU,"override",0,tF],653002);var t$=t.i(254799),tV=t.i(522734),tK=t.i(814747),tq=t.i(258062),tz=t.i(103749),tW=t.i(640923);function tH(t,r){if(""===t.trim())return{};for(let i of tz.parse(t,{sourceType:"module",plugins:["typescript","importAttributes"]}).program.body)if(tW.isExportNamedDeclaration(i)&&tW.isVariableDeclaration(i.declaration)){for(let t of i.declaration.declarations)if(tW.isIdentifier(t.id)&&"config"===t.id.name){if(null==t.init||!tW.isExpression(t.init))throw Error(`Config export in ${r} must have an initializer.`);return function t(r){let i=function t(r){return tW.isTSAsExpression(r)||tW.isTSSatisfiesExpression(r)||tW.isTSTypeAssertion(r)||tW.isTSNonNullExpression(r)?t(r.expression):r}(r);if(tW.isStringLiteral(i)||tW.isBooleanLiteral(i)||tW.isNumericLiteral(i))return i.value;if(tW.isNullLiteral(i))return null;if(!tW.isIdentifier(i)||"undefined"!==i.name){if(tW.isUnaryExpression(i)&&"-"===i.operator&&tW.isNumericLiteral(i.argument))return-i.argument.value;if(tW.isArrayExpression(i))return i.elements.map(r=>{if(null==r||tW.isSpreadElement(r))throw Error("Config arrays cannot contain holes or spreads.");return t(r)});if(tW.isObjectExpression(i)){let r={};for(let s of i.properties){if(tW.isSpreadElement(s))throw Error("Config objects cannot contain spreads.");if(s.computed)throw Error("Config object keys cannot be computed.");let i=tW.isIdentifier(s.key)?s.key.name:tW.isStringLiteral(s.key)||tW.isNumericLiteral(s.key)?String(s.key.value):null;if(null==i)throw Error("Unsupported config object key.");if(tW.isObjectMethod(s))throw Error("Config objects cannot contain methods.");if(!tW.isExpression(s.value))throw Error("Unsupported config object value.");r[i]=t(s.value)}return r}throw Error(`Unsupported config expression: ${i.type}`)}}(t.init)}}throw Error(`Invalid config in ${r}. The file must export a plain \`config\` object or "show-onboarding".`)}let tJ=["@hexclave/next","@hexclave/react","@hexclave/tanstack-start","@hexclave/js","@hexclave/template","@stackframe/stack","@stackframe/react","@stackframe/js","@stackframe/template"];var tY=t.i(844376),tX=t.i(513927);function tG(t){throw t}let tZ=t=>Promise.resolve().then(()=>{let t=Error("Cannot find module as expression is too dynamic");throw t.code="MODULE_NOT_FOUND",t});function tQ(...r){return s||(s=t.r(648621)),s(...r)}var t0=t.i(792509),t1=t.i(427699),t2=t.i(233405),t4=t.i(319668),t3=t.i(924868),t8=t.i(446786),t7=t.i(605365),t9=t.i(224361);let t5={get url(){return`file://${t.P("node_modules/.pnpm/@anthropic-ai+claude-agent-sdk@0.2.73_zod@4.3.6/node_modules/@anthropic-ai/claude-agent-sdk/sdk.mjs")}`}};var t6=Object.create,{getPrototypeOf:re,defineProperty:rt,getOwnPropertyNames:rr}=Object,ri=Object.prototype.hasOwnProperty;function rs(t){return this[t]}var rn,ra,ro=(t,r,i)=>{var s=null!=t&&"object"==typeof t;if(s){var n=r?rn??=new WeakMap:ra??=new WeakMap,a=n.get(t);if(a)return a}i=null!=t?t6(re(t)):{};let o=!r&&t&&t.__esModule?i:rt(i,"default",{value:t,enumerable:!0});for(let r of rr(t))ri.call(o,r)||rt(o,r,{get:rs.bind(t,r),enumerable:!0});return s&&n.set(t,o),o},rl=(t,r)=>()=>(r||t((r={exports:{}}).exports,r),r.exports),rp=t=>t;function ru(t,r){this[t]=rp.bind(null,r)}var rc=(t,r)=>{for(var i in r)rt(t,i,{get:r[i],enumerable:!0,configurable:!0,set:ru.bind(r,i)})},rd=Symbol.dispose||Symbol.for("Symbol.dispose"),rh=Symbol.asyncDispose||Symbol.for("Symbol.asyncDispose"),rf=(t,r,i)=>{if(null!=r){var s;if("object"!=typeof r&&"function"!=typeof r)throw TypeError('Object expected to be assigned to "using" declaration');if(i&&(s=r[rh]),void 0===s&&(s=r[rd]),"function"!=typeof s)throw TypeError("Object not disposable");t.push([i,s,r])}else i&&t.push([i]);return r},rm=(t,r,i)=>{var s="function"==typeof SuppressedError?SuppressedError:function(t,r,i,s){return(s=Error(i)).name="SuppressedError",s.error=t,s.suppressed=r,s},n=t=>r=i?new s(t,r,"An error was suppressed during disposal"):(i=!0,t),a=s=>{for(;s=t.pop();)try{var o=s[1]&&s[1].call(s[2]);if(s[0])return Promise.resolve(o).then(a,t=>(n(t),a()))}catch(t){n(t)}if(i)throw r};return a()},ry=rl(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.regexpCode=t.getEsmExportName=t.getProperty=t.safeStringify=t.stringify=t.strConcat=t.addCodeArg=t.str=t._=t.nil=t._Code=t.Name=t.IDENTIFIER=t._CodeOrName=void 0;class r{}t._CodeOrName=r,t.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class i extends r{constructor(r){if(super(),!t.IDENTIFIER.test(r))throw Error("CodeGen: name must be a valid identifier");this.str=r}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}t.Name=i;class s extends r{constructor(t){super(),this._items="string"==typeof t?[t]:t}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let t=this._items[0];return""===t||'""'===t}get str(){var t;return null!=(t=this._str)?t:this._str=this._items.reduce((t,r)=>`${t}${r}`,"")}get names(){var t;return null!=(t=this._names)?t:this._names=this._items.reduce((t,r)=>(r instanceof i&&(t[r.str]=(t[r.str]||0)+1),t),{})}}function n(t,...r){let i=[t[0]],a=0;for(;a<r.length;)l(i,r[a]),i.push(t[++a]);return new s(i)}t._Code=s,t.nil=new s(""),t._=n;var a=new s("+");function o(t,...r){let n=[p(t[0])],u=0;for(;u<r.length;)n.push(a),l(n,r[u]),n.push(a,p(t[++u]));return function(t){let r=1;for(;r<t.length-1;){if(t[r]===a){var s,n;let a=(s=t[r-1],'""'===(n=t[r+1])?s:'""'===s?n:"string"==typeof s?n instanceof i||'"'!==s[s.length-1]?void 0:"string"!=typeof n?`${s.slice(0,-1)}${n}"`:'"'===n[0]?s.slice(0,-1)+n.slice(1):void 0:"string"!=typeof n||'"'!==n[0]||s instanceof i?void 0:`"${s}${n.slice(1)}`);if(void 0!==a){t.splice(r-1,3,a);continue}t[r++]="+"}r++}}(n),new s(n)}function l(t,r){var n;r instanceof s?t.push(...r._items):r instanceof i?t.push(r):t.push("number"==typeof(n=r)||"boolean"==typeof n||null===n?n:p(Array.isArray(n)?n.join(","):n))}function p(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}t.str=o,t.addCodeArg=l,t.strConcat=function(t,r){return r.emptyStr()?t:t.emptyStr()?r:o`${t}${r}`},t.stringify=function(t){return new s(p(t))},t.safeStringify=p,t.getProperty=function(r){return"string"==typeof r&&t.IDENTIFIER.test(r)?new s(`.${r}`):n`[${r}]`},t.getEsmExportName=function(r){if("string"==typeof r&&t.IDENTIFIER.test(r))return new s(`${r}`);throw Error(`CodeGen: invalid export name: ${r}, use explicit $id name mapping`)},t.regexpCode=function(t){return new s(t.toString())}}),rb=rl(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ValueScope=t.ValueScopeName=t.Scope=t.varKinds=t.UsedValueState=void 0;var r,i,s=ry();class n extends Error{constructor(t){super(`CodeGen: "code" for ${t} not defined`),this.value=t.value}}(r=i||(t.UsedValueState=i={}))[r.Started=0]="Started",r[r.Completed=1]="Completed",t.varKinds={const:new s.Name("const"),let:new s.Name("let"),var:new s.Name("var")};class a{constructor({prefixes:t,parent:r}={}){this._names={},this._prefixes=t,this._parent=r}toName(t){return t instanceof s.Name?t:this.name(t)}name(t){return new s.Name(this._newName(t))}_newName(t){let r=this._names[t]||this._nameGroup(t);return`${t}${r.index++}`}_nameGroup(t){var r,i;if((null==(i=null==(r=this._parent)?void 0:r._prefixes)?void 0:i.has(t))||this._prefixes&&!this._prefixes.has(t))throw Error(`CodeGen: prefix "${t}" is not allowed in this scope`);return this._names[t]={prefix:t,index:0}}}t.Scope=a;class o extends s.Name{constructor(t,r){super(r),this.prefix=t}setValue(t,{property:r,itemIndex:i}){this.value=t,this.scopePath=s._`.${new s.Name(r)}[${i}]`}}t.ValueScopeName=o;var l=s._`\n`;t.ValueScope=class extends a{constructor(t){super(t),this._values={},this._scope=t.scope,this.opts={...t,_n:t.lines?l:s.nil}}get(){return this._scope}name(t){return new o(t,this._newName(t))}value(t,r){var i;if(void 0===r.ref)throw Error("CodeGen: ref must be passed in value");let s=this.toName(t),{prefix:n}=s,a=null!=(i=r.key)?i:r.ref,o=this._values[n];if(o){let t=o.get(a);if(t)return t}else o=this._values[n]=new Map;o.set(a,s);let l=this._scope[n]||(this._scope[n]=[]),p=l.length;return l[p]=r.ref,s.setValue(r,{property:n,itemIndex:p}),s}getValue(t,r){let i=this._values[t];if(i)return i.get(r)}scopeRefs(t,r=this._values){return this._reduceValues(r,r=>{if(void 0===r.scopePath)throw Error(`CodeGen: name "${r}" has no value`);return s._`${t}${r.scopePath}`})}scopeCode(t=this._values,r,i){return this._reduceValues(t,t=>{if(void 0===t.value)throw Error(`CodeGen: name "${t}" has no value`);return t.value.code},r,i)}_reduceValues(r,a,o={},l){let p=s.nil;for(let u in r){let c=r[u];if(!c)continue;let d=o[u]=o[u]||new Map;c.forEach(r=>{if(d.has(r))return;d.set(r,i.Started);let o=a(r);if(o){let i=this.opts.es5?t.varKinds.var:t.varKinds.const;p=s._`${p}${i} ${r} = ${o};${this.opts._n}`}else if(o=null==l?void 0:l(r))p=s._`${p}${o}${this.opts._n}`;else throw new n(r);d.set(r,i.Completed)})}return p}}}),rg=rl(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.or=t.and=t.not=t.CodeGen=t.operators=t.varKinds=t.ValueScopeName=t.ValueScope=t.Scope=t.Name=t.regexpCode=t.stringify=t.getProperty=t.nil=t.strConcat=t.str=t._=void 0;var r=ry(),i=rb(),s=ry();Object.defineProperty(t,"_",{enumerable:!0,get:function(){return s._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return s.str}}),Object.defineProperty(t,"strConcat",{enumerable:!0,get:function(){return s.strConcat}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return s.nil}}),Object.defineProperty(t,"getProperty",{enumerable:!0,get:function(){return s.getProperty}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return s.stringify}}),Object.defineProperty(t,"regexpCode",{enumerable:!0,get:function(){return s.regexpCode}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return s.Name}});var n=rb();Object.defineProperty(t,"Scope",{enumerable:!0,get:function(){return n.Scope}}),Object.defineProperty(t,"ValueScope",{enumerable:!0,get:function(){return n.ValueScope}}),Object.defineProperty(t,"ValueScopeName",{enumerable:!0,get:function(){return n.ValueScopeName}}),Object.defineProperty(t,"varKinds",{enumerable:!0,get:function(){return n.varKinds}}),t.operators={GT:new r._Code(">"),GTE:new r._Code(">="),LT:new r._Code("<"),LTE:new r._Code("<="),EQ:new r._Code("==="),NEQ:new r._Code("!=="),NOT:new r._Code("!"),OR:new r._Code("||"),AND:new r._Code("&&"),ADD:new r._Code("+")};class a{optimizeNodes(){return this}optimizeNames(t,r){return this}}class o extends a{constructor(t,r,i){super(),this.varKind=t,this.name=r,this.rhs=i}render({es5:t,_n:r}){let s=t?i.varKinds.var:this.varKind,n=void 0===this.rhs?"":` = ${this.rhs}`;return`${s} ${this.name}${n};`+r}optimizeNames(t,r){if(t[this.name.str])return this.rhs&&(this.rhs=k(this.rhs,t,r)),this}get names(){return this.rhs instanceof r._CodeOrName?this.rhs.names:{}}}class l extends a{constructor(t,r,i){super(),this.lhs=t,this.rhs=r,this.sideEffects=i}render({_n:t}){return`${this.lhs} = ${this.rhs};`+t}optimizeNames(t,i){if(!(this.lhs instanceof r.Name)||t[this.lhs.str]||this.sideEffects)return this.rhs=k(this.rhs,t,i),this}get names(){return I(this.lhs instanceof r.Name?{}:{...this.lhs.names},this.rhs)}}class p extends l{constructor(t,r,i,s){super(t,i,s),this.op=r}render({_n:t}){return`${this.lhs} ${this.op}= ${this.rhs};`+t}}class u extends a{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`${this.label}:`+t}}class c extends a{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`break${this.label?` ${this.label}`:""};`+t}}class d extends a{constructor(t){super(),this.error=t}render({_n:t}){return`throw ${this.error};`+t}get names(){return this.error.names}}class h extends a{constructor(t){super(),this.code=t}render({_n:t}){return`${this.code};`+t}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(t,r){return this.code=k(this.code,t,r),this}get names(){return this.code instanceof r._CodeOrName?this.code.names:{}}}class f extends a{constructor(t=[]){super(),this.nodes=t}render(t){return this.nodes.reduce((r,i)=>r+i.render(t),"")}optimizeNodes(){let{nodes:t}=this,r=t.length;for(;r--;){let i=t[r].optimizeNodes();Array.isArray(i)?t.splice(r,1,...i):i?t[r]=i:t.splice(r,1)}return t.length>0?this:void 0}optimizeNames(t,r){let{nodes:i}=this,s=i.length;for(;s--;){let n=i[s];n.optimizeNames(t,r)||(function(t,r){for(let i in r)t[i]=(t[i]||0)-(r[i]||0)}(t,n.names),i.splice(s,1))}return i.length>0?this:void 0}get names(){return this.nodes.reduce((t,r)=>C(t,r.names),{})}}class m extends f{render(t){return"{"+t._n+super.render(t)+"}"+t._n}}class y extends f{}class b extends m{}b.kind="else";class g extends m{constructor(t,r){super(r),this.condition=t}render(t){let r=`if(${this.condition})`+super.render(t);return this.else&&(r+="else "+this.else.render(t)),r}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(!0===t)return this.nodes;let r=this.else;if(r){let t=r.optimizeNodes();r=this.else=Array.isArray(t)?new b(t):t}return r?!1===t?r instanceof g?r:r.nodes:this.nodes.length?this:new g(N(t),r instanceof g?[r]:r.nodes):!1!==t&&this.nodes.length?this:void 0}optimizeNames(t,r){var i;if(this.else=null==(i=this.else)?void 0:i.optimizeNames(t,r),super.optimizeNames(t,r)||this.else)return this.condition=k(this.condition,t,r),this}get names(){let t=super.names;return I(t,this.condition),this.else&&C(t,this.else.names),t}}g.kind="if";class v extends m{}v.kind="for";class x extends v{constructor(t){super(),this.iteration=t}render(t){return`for(${this.iteration})`+super.render(t)}optimizeNames(t,r){if(super.optimizeNames(t,r))return this.iteration=k(this.iteration,t,r),this}get names(){return C(super.names,this.iteration.names)}}class T extends v{constructor(t,r,i,s){super(),this.varKind=t,this.name=r,this.from=i,this.to=s}render(t){let r=t.es5?i.varKinds.var:this.varKind,{name:s,from:n,to:a}=this;return`for(${r} ${s}=${n}; ${s}<${a}; ${s}++)`+super.render(t)}get names(){let t=I(super.names,this.from);return I(t,this.to)}}class E extends v{constructor(t,r,i,s){super(),this.loop=t,this.varKind=r,this.name=i,this.iterable=s}render(t){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(t)}optimizeNames(t,r){if(super.optimizeNames(t,r))return this.iterable=k(this.iterable,t,r),this}get names(){return C(super.names,this.iterable.names)}}class S extends m{constructor(t,r,i){super(),this.name=t,this.args=r,this.async=i}render(t){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(t)}}S.kind="func";class _ extends f{render(t){return"return "+super.render(t)}}_.kind="return";class P extends m{render(t){let r="try"+super.render(t);return this.catch&&(r+=this.catch.render(t)),this.finally&&(r+=this.finally.render(t)),r}optimizeNodes(){var t,r;return super.optimizeNodes(),null==(t=this.catch)||t.optimizeNodes(),null==(r=this.finally)||r.optimizeNodes(),this}optimizeNames(t,r){var i,s;return super.optimizeNames(t,r),null==(i=this.catch)||i.optimizeNames(t,r),null==(s=this.finally)||s.optimizeNames(t,r),this}get names(){let t=super.names;return this.catch&&C(t,this.catch.names),this.finally&&C(t,this.finally.names),t}}class A extends m{constructor(t){super(),this.error=t}render(t){return`catch(${this.error})`+super.render(t)}}A.kind="catch";class w extends m{render(t){return"finally"+super.render(t)}}function C(t,r){for(let i in r)t[i]=(t[i]||0)+(r[i]||0);return t}function I(t,i){return i instanceof r._CodeOrName?C(t,i.names):t}function k(t,i,s){var n;if(t instanceof r.Name)return a(t);if(!((n=t)instanceof r._Code&&n._items.some(t=>t instanceof r.Name&&1===i[t.str]&&void 0!==s[t.str])))return t;return new r._Code(t._items.reduce((t,i)=>(i instanceof r.Name&&(i=a(i)),i instanceof r._Code?t.push(...i._items):t.push(i),t),[]));function a(t){let r=s[t.str];return void 0===r||1!==i[t.str]?t:(delete i[t.str],r)}}function N(t){return"boolean"==typeof t||"number"==typeof t||null===t?!t:r._`!${L(t)}`}w.kind="finally",t.CodeGen=class{constructor(t,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
354
|
+
`:""},this._extScope=t,this._scope=new i.Scope({parent:t}),this._nodes=[new y]}toString(){return this._root.render(this.opts)}name(t){return this._scope.name(t)}scopeName(t){return this._extScope.name(t)}scopeValue(t,r){let i=this._extScope.value(t,r);return(this._values[i.prefix]||(this._values[i.prefix]=new Set)).add(i),i}getScopeValue(t,r){return this._extScope.getValue(t,r)}scopeRefs(t){return this._extScope.scopeRefs(t,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(t,r,i,s){let n=this._scope.toName(r);return void 0!==i&&s&&(this._constants[n.str]=i),this._leafNode(new o(t,n,i)),n}const(t,r,s){return this._def(i.varKinds.const,t,r,s)}let(t,r,s){return this._def(i.varKinds.let,t,r,s)}var(t,r,s){return this._def(i.varKinds.var,t,r,s)}assign(t,r,i){return this._leafNode(new l(t,r,i))}add(r,i){return this._leafNode(new p(r,t.operators.ADD,i))}code(t){return"function"==typeof t?t():t!==r.nil&&this._leafNode(new h(t)),this}object(...t){let i=["{"];for(let[s,n]of t)i.length>1&&i.push(","),i.push(s),(s!==n||this.opts.es5)&&(i.push(":"),(0,r.addCodeArg)(i,n));return i.push("}"),new r._Code(i)}if(t,r,i){if(this._blockNode(new g(t)),r&&i)this.code(r).else().code(i).endIf();else if(r)this.code(r).endIf();else if(i)throw Error('CodeGen: "else" body without "then" body');return this}elseIf(t){return this._elseNode(new g(t))}else(){return this._elseNode(new b)}endIf(){return this._endBlockNode(g,b)}_for(t,r){return this._blockNode(t),r&&this.code(r).endFor(),this}for(t,r){return this._for(new x(t),r)}forRange(t,r,s,n,a=this.opts.es5?i.varKinds.var:i.varKinds.let){let o=this._scope.toName(t);return this._for(new T(a,o,r,s),()=>n(o))}forOf(t,s,n,a=i.varKinds.const){let o=this._scope.toName(t);if(this.opts.es5){let t=s instanceof r.Name?s:this.var("_arr",s);return this.forRange("_i",0,r._`${t}.length`,i=>{this.var(o,r._`${t}[${i}]`),n(o)})}return this._for(new E("of",a,o,s),()=>n(o))}forIn(t,s,n,a=this.opts.es5?i.varKinds.var:i.varKinds.const){if(this.opts.ownProperties)return this.forOf(t,r._`Object.keys(${s})`,n);let o=this._scope.toName(t);return this._for(new E("in",a,o,s),()=>n(o))}endFor(){return this._endBlockNode(v)}label(t){return this._leafNode(new u(t))}break(t){return this._leafNode(new c(t))}return(t){let r=new _;if(this._blockNode(r),this.code(t),1!==r.nodes.length)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(_)}try(t,r,i){if(!r&&!i)throw Error('CodeGen: "try" without "catch" and "finally"');let s=new P;if(this._blockNode(s),this.code(t),r){let t=this.name("e");this._currNode=s.catch=new A(t),r(t)}return i&&(this._currNode=s.finally=new w,this.code(i)),this._endBlockNode(A,w)}throw(t){return this._leafNode(new d(t))}block(t,r){return this._blockStarts.push(this._nodes.length),t&&this.code(t).endBlock(r),this}endBlock(t){let r=this._blockStarts.pop();if(void 0===r)throw Error("CodeGen: not in self-balancing block");let i=this._nodes.length-r;if(i<0||void 0!==t&&i!==t)throw Error(`CodeGen: wrong number of nodes: ${i} vs ${t} expected`);return this._nodes.length=r,this}func(t,i=r.nil,s,n){return this._blockNode(new S(t,i,s)),n&&this.code(n).endFunc(),this}endFunc(){return this._endBlockNode(S)}optimize(t=1){for(;t-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(t){return this._currNode.nodes.push(t),this}_blockNode(t){this._currNode.nodes.push(t),this._nodes.push(t)}_endBlockNode(t,r){let i=this._currNode;if(i instanceof t||r&&i instanceof r)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${r?`${t.kind}/${r.kind}`:t.kind}"`)}_elseNode(t){let r=this._currNode;if(!(r instanceof g))throw Error('CodeGen: "else" without "if"');return this._currNode=r.else=t,this}get _root(){return this._nodes[0]}get _currNode(){let t=this._nodes;return t[t.length-1]}set _currNode(t){let r=this._nodes;r[r.length-1]=t}},t.not=N;var O=j(t.operators.AND);t.and=function(...t){return t.reduce(O)};var D=j(t.operators.OR);function j(t){return(i,s)=>i===r.nil?s:s===r.nil?i:r._`${L(i)} ${t} ${L(s)}`}function L(t){return t instanceof r.Name?t:r._`(${t})`}t.or=function(...t){return t.reduce(D)}}),rv=rl(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.checkStrictMode=t.getErrorPath=t.Type=t.useFunc=t.setEvaluated=t.evaluatedPropsToName=t.mergeEvaluated=t.eachItem=t.unescapeJsonPointer=t.escapeJsonPointer=t.escapeFragment=t.unescapeFragment=t.schemaRefOrVal=t.schemaHasRulesButRef=t.schemaHasRules=t.checkUnknownRules=t.alwaysValidSchema=t.toHash=void 0;var r,i,s=rg(),n=ry();function a(t,r=t.schema){let{opts:i,self:s}=t;if(!i.strictSchema||"boolean"==typeof r)return;let n=s.RULES.keywords;for(let i in r)n[i]||f(t,`unknown keyword: "${i}"`)}function o(t,r){if("boolean"==typeof t)return!t;for(let i in t)if(r[i])return!0;return!1}function l(t){return"number"==typeof t?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}function p(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function u({mergeNames:t,mergeToName:r,mergeValues:i,resultToName:n}){return(a,o,l,p)=>{let u=void 0===l?o:l instanceof s.Name?(o instanceof s.Name?t(a,o,l):r(a,o,l),l):o instanceof s.Name?(r(a,l,o),o):i(o,l);return p!==s.Name||u instanceof s.Name?u:n(a,u)}}function c(t,r){if(!0===r)return t.var("props",!0);let i=t.var("props",s._`{}`);return void 0!==r&&d(t,i,r),i}function d(t,r,i){Object.keys(i).forEach(i=>t.assign(s._`${r}${(0,s.getProperty)(i)}`,!0))}t.toHash=function(t){let r={};for(let i of t)r[i]=!0;return r},t.alwaysValidSchema=function(t,r){return"boolean"==typeof r?r:0===Object.keys(r).length||(a(t,r),!o(r,t.self.RULES.all))},t.checkUnknownRules=a,t.schemaHasRules=o,t.schemaHasRulesButRef=function(t,r){if("boolean"==typeof t)return!t;for(let i in t)if("$ref"!==i&&r.all[i])return!0;return!1},t.schemaRefOrVal=function({topSchemaRef:t,schemaPath:r},i,n,a){if(!a){if("number"==typeof i||"boolean"==typeof i)return i;if("string"==typeof i)return s._`${i}`}return s._`${t}${r}${(0,s.getProperty)(n)}`},t.unescapeFragment=function(t){return p(decodeURIComponent(t))},t.escapeFragment=function(t){return encodeURIComponent(l(t))},t.escapeJsonPointer=l,t.unescapeJsonPointer=p,t.eachItem=function(t,r){if(Array.isArray(t))for(let i of t)r(i);else r(t)},t.mergeEvaluated={props:u({mergeNames:(t,r,i)=>t.if(s._`${i} !== true && ${r} !== undefined`,()=>{t.if(s._`${r} === true`,()=>t.assign(i,!0),()=>t.assign(i,s._`${i} || {}`).code(s._`Object.assign(${i}, ${r})`))}),mergeToName:(t,r,i)=>t.if(s._`${i} !== true`,()=>{!0===r?t.assign(i,!0):(t.assign(i,s._`${i} || {}`),d(t,i,r))}),mergeValues:(t,r)=>!0===t||{...t,...r},resultToName:c}),items:u({mergeNames:(t,r,i)=>t.if(s._`${i} !== true && ${r} !== undefined`,()=>t.assign(i,s._`${r} === true ? true : ${i} > ${r} ? ${i} : ${r}`)),mergeToName:(t,r,i)=>t.if(s._`${i} !== true`,()=>t.assign(i,!0===r||s._`${i} > ${r} ? ${i} : ${r}`)),mergeValues:(t,r)=>!0===t||Math.max(t,r),resultToName:(t,r)=>t.var("items",r)})},t.evaluatedPropsToName=c,t.setEvaluated=d;var h={};function f(t,r,i=t.opts.strictSchema){if(i){if(r=`strict mode: ${r}`,!0===i)throw Error(r);t.self.logger.warn(r)}}t.useFunc=function(t,r){return t.scopeValue("func",{ref:r,code:h[r.code]||(h[r.code]=new n._Code(r.code))})},(r=i||(t.Type=i={}))[r.Num=0]="Num",r[r.Str=1]="Str",t.getErrorPath=function(t,r,n){if(t instanceof s.Name){let a=r===i.Num;return n?a?s._`"[" + ${t} + "]"`:s._`"['" + ${t} + "']"`:a?s._`"/" + ${t}`:s._`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return n?(0,s.getProperty)(t).toString():"/"+l(t)},t.checkStrictMode=f}),rx=rl(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=rg();t.default={data:new r.Name("data"),valCxt:new r.Name("valCxt"),instancePath:new r.Name("instancePath"),parentData:new r.Name("parentData"),parentDataProperty:new r.Name("parentDataProperty"),rootData:new r.Name("rootData"),dynamicAnchors:new r.Name("dynamicAnchors"),vErrors:new r.Name("vErrors"),errors:new r.Name("errors"),this:new r.Name("this"),self:new r.Name("self"),scope:new r.Name("scope"),json:new r.Name("json"),jsonPos:new r.Name("jsonPos"),jsonLen:new r.Name("jsonLen"),jsonPart:new r.Name("jsonPart")}}),rT=rl(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extendErrors=t.resetErrorsCount=t.reportExtraError=t.reportError=t.keyword$DataError=t.keywordError=void 0;var r=rg(),i=rv(),s=rx();function n(t,i){let n=t.const("err",i);t.if(r._`${s.default.vErrors} === null`,()=>t.assign(s.default.vErrors,r._`[${n}]`),r._`${s.default.vErrors}.push(${n})`),t.code(r._`${s.default.errors}++`)}function a(t,i){let{gen:s,validateName:n,schemaEnv:a}=t;a.$async?s.throw(r._`new ${t.ValidationError}(${i})`):(s.assign(r._`${n}.errors`,i),s.return(!1))}t.keywordError={message:({keyword:t})=>r.str`must pass "${t}" keyword validation`},t.keyword$DataError={message:({keyword:t,schemaType:i})=>i?r.str`"${t}" keyword must be ${i} ($data)`:r.str`"${t}" keyword is invalid ($data)`},t.reportError=function(i,s=t.keywordError,o,p){let{it:u}=i,{gen:c,compositeRule:d,allErrors:h}=u,f=l(i,s,o);(null!=p?p:d||h)?n(c,f):a(u,r._`[${f}]`)},t.reportExtraError=function(r,i=t.keywordError,o){let{it:p}=r,{gen:u,compositeRule:c,allErrors:d}=p;n(u,l(r,i,o)),c||d||a(p,s.default.vErrors)},t.resetErrorsCount=function(t,i){t.assign(s.default.errors,i),t.if(r._`${s.default.vErrors} !== null`,()=>t.if(i,()=>t.assign(r._`${s.default.vErrors}.length`,i),()=>t.assign(s.default.vErrors,null)))},t.extendErrors=function({gen:t,keyword:i,schemaValue:n,data:a,errsCount:o,it:l}){if(void 0===o)throw Error("ajv implementation error");let p=t.name("err");t.forRange("i",o,s.default.errors,o=>{t.const(p,r._`${s.default.vErrors}[${o}]`),t.if(r._`${p}.instancePath === undefined`,()=>t.assign(r._`${p}.instancePath`,(0,r.strConcat)(s.default.instancePath,l.errorPath))),t.assign(r._`${p}.schemaPath`,r.str`${l.errSchemaPath}/${i}`),l.opts.verbose&&(t.assign(r._`${p}.schema`,n),t.assign(r._`${p}.data`,a))})};var o={keyword:new r.Name("keyword"),schemaPath:new r.Name("schemaPath"),params:new r.Name("params"),propertyName:new r.Name("propertyName"),message:new r.Name("message"),schema:new r.Name("schema"),parentSchema:new r.Name("parentSchema")};function l(t,n,a){let{createErrors:l}=t.it;return!1===l?r._`{}`:function(t,n,a={}){let{gen:l,it:p}=t,u=[function({errorPath:t},{instancePath:n}){let a=n?r.str`${t}${(0,i.getErrorPath)(n,i.Type.Str)}`:t;return[s.default.instancePath,(0,r.strConcat)(s.default.instancePath,a)]}(p,a),function({keyword:t,it:{errSchemaPath:s}},{schemaPath:n,parentSchema:a}){let l=a?s:r.str`${s}/${t}`;return n&&(l=r.str`${l}${(0,i.getErrorPath)(n,i.Type.Str)}`),[o.schemaPath,l]}(t,a)];return function(t,{params:i,message:n},a){let{keyword:l,data:p,schemaValue:u,it:c}=t,{opts:d,propertyName:h,topSchemaRef:f,schemaPath:m}=c;a.push([o.keyword,l],[o.params,"function"==typeof i?i(t):i||r._`{}`]),d.messages&&a.push([o.message,"function"==typeof n?n(t):n]),d.verbose&&a.push([o.schema,u],[o.parentSchema,r._`${f}${m}`],[s.default.data,p]),h&&a.push([o.propertyName,h])}(t,n,u),l.object(...u)}(t,n,a)}}),rE=rl(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.boolOrEmptySchema=t.topBoolOrEmptySchema=void 0;var r=rT(),i=rg(),s=rx(),n={message:"boolean schema is false"};function a(t,i){let{gen:s,data:a}=t;(0,r.reportError)({gen:s,keyword:"false schema",data:a,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t},n,void 0,i)}t.topBoolOrEmptySchema=function(t){let{gen:r,schema:n,validateName:o}=t;!1===n?a(t,!1):"object"==typeof n&&!0===n.$async?r.return(s.default.data):(r.assign(i._`${o}.errors`,null),r.return(!0))},t.boolOrEmptySchema=function(t,r){let{gen:i,schema:s}=t;!1===s?(i.var(r,!1),a(t)):i.var(r,!0)}}),rS=rl(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getRules=t.isJSONType=void 0;var r=new Set(["string","number","integer","boolean","null","object","array"]);t.isJSONType=function(t){return"string"==typeof t&&r.has(t)},t.getRules=function(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}}),r_=rl(t=>{function r(t,r){return r.rules.some(r=>i(t,r))}function i(t,r){var i;return void 0!==t[r.keyword]||(null==(i=r.definition.implements)?void 0:i.some(r=>void 0!==t[r]))}Object.defineProperty(t,"__esModule",{value:!0}),t.shouldUseRule=t.shouldUseGroup=t.schemaHasRulesForType=void 0,t.schemaHasRulesForType=function({schema:t,self:i},s){let n=i.RULES.types[s];return n&&!0!==n&&r(t,n)},t.shouldUseGroup=r,t.shouldUseRule=i}),rP=rl(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.reportTypeError=t.checkDataTypes=t.checkDataType=t.coerceAndCheckDataType=t.getJSONTypes=t.getSchemaTypes=t.DataType=void 0;var r,i,s=rS(),n=r_(),a=rT(),o=rg(),l=rv();function p(t){let r=Array.isArray(t)?t:t?[t]:[];if(r.every(s.isJSONType))return r;throw Error("type must be JSONType or JSONType[]: "+r.join(","))}(r=i||(t.DataType=i={}))[r.Correct=0]="Correct",r[r.Wrong=1]="Wrong",t.getSchemaTypes=function(t){let r=p(t.type);if(r.includes("null")){if(!1===t.nullable)throw Error("type: null contradicts nullable: false")}else{if(!r.length&&void 0!==t.nullable)throw Error('"nullable" cannot be used without "type"');!0===t.nullable&&r.push("null")}return r},t.getJSONTypes=p,t.coerceAndCheckDataType=function(t,r){var s,a;let{gen:l,data:p,opts:c}=t,h=(s=r,(a=c.coerceTypes)?s.filter(t=>u.has(t)||"array"===a&&"array"===t):[]),m=r.length>0&&!(0===h.length&&1===r.length&&(0,n.schemaHasRulesForType)(t,r[0]));if(m){let s=d(r,p,c.strictNumbers,i.Wrong);l.if(s,()=>{h.length?function(t,r,i){let{gen:s,data:n,opts:a}=t,l=s.let("dataType",o._`typeof ${n}`),p=s.let("coerced",o._`undefined`);for(let t of("array"===a.coerceTypes&&s.if(o._`${l} == 'object' && Array.isArray(${n}) && ${n}.length == 1`,()=>s.assign(n,o._`${n}[0]`).assign(l,o._`typeof ${n}`).if(d(r,n,a.strictNumbers),()=>s.assign(p,n))),s.if(o._`${p} !== undefined`),i))(u.has(t)||"array"===t&&"array"===a.coerceTypes)&&function(t){switch(t){case"string":s.elseIf(o._`${l} == "number" || ${l} == "boolean"`).assign(p,o._`"" + ${n}`).elseIf(o._`${n} === null`).assign(p,o._`""`);return;case"number":s.elseIf(o._`${l} == "boolean" || ${n} === null
|
|
355
355
|
|| (${l} == "string" && ${n} && ${n} == +${n})`).assign(p,o._`+${n}`);return;case"integer":s.elseIf(o._`${l} === "boolean" || ${n} === null
|
|
356
356
|
|| (${l} === "string" && ${n} && ${n} == +${n} && !(${n} % 1))`).assign(p,o._`+${n}`);return;case"boolean":s.elseIf(o._`${n} === "false" || ${n} === 0 || ${n} === null`).assign(p,!1).elseIf(o._`${n} === "true" || ${n} === 1`).assign(p,!0);return;case"null":s.elseIf(o._`${n} === "" || ${n} === 0 || ${n} === false`),s.assign(p,null);return;case"array":s.elseIf(o._`${l} === "string" || ${l} === "number"
|
|
357
|
-
|| ${l} === "boolean" || ${n} === null`).assign(p,o._`[${n}]`)}}(t);s.else(),f(t),s.endIf(),s.if(o._`${p} !== undefined`,()=>{s.assign(n,p),function({gen:t,parentData:r,parentDataProperty:i},s){t.if(o._`${r} !== undefined`,()=>t.assign(o._`${r}[${i}]`,s))}(t,p)})}(t,r,h):f(t)})}return m};var u=new Set(["string","number","integer","boolean","null"]);function c(t,r,s,n=i.Correct){let a=n===i.Correct?o.operators.EQ:o.operators.NEQ,l;switch(t){case"null":return o._`${r} ${a} null`;case"array":l=o._`Array.isArray(${r})`;break;case"object":l=o._`${r} && typeof ${r} == "object" && !Array.isArray(${r})`;break;case"integer":l=p(o._`!(${r} % 1) && !isNaN(${r})`);break;case"number":l=p();break;default:return o._`typeof ${r} ${a} ${t}`}return n===i.Correct?l:(0,o.not)(l);function p(t=o.nil){return(0,o.and)(o._`typeof ${r} == "number"`,t,s?o._`isFinite(${r})`:o.nil)}}function d(t,r,i,s){if(1===t.length)return c(t[0],r,i,s);let n,a=(0,l.toHash)(t);if(a.array&&a.object){let t=o._`typeof ${r} != "object"`;n=a.null?t:o._`!${r} || ${t}`,delete a.null,delete a.array,delete a.object}else n=o.nil;for(let t in a.number&&delete a.integer,a)n=(0,o.and)(n,c(t,r,i,s));return n}t.checkDataType=c,t.checkDataTypes=d;var h={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:r})=>"string"==typeof t?o._`{type: ${t}}`:o._`{type: ${r}}`};function f(t){let r=function(t){let{gen:r,data:i,schema:s}=t,n=(0,l.schemaRefOrVal)(t,s,"type");return{gen:r,keyword:"type",data:i,schema:s.type,schemaCode:n,schemaValue:n,parentSchema:s,params:{},it:t}}(t);(0,a.reportError)(r,h)}t.reportTypeError=f}),rP=ro(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.assignDefaults=void 0;var r=rb(),i=rg();function s(t,s,n){let{gen:a,compositeRule:o,data:l,opts:p}=t;if(void 0===n)return;let u=r._`${l}${(0,r.getProperty)(s)}`;if(o)return void(0,i.checkStrictMode)(t,`default is ignored for: ${u}`);let c=r._`${u} === undefined`;"empty"===p.useDefaults&&(c=r._`${c} || ${u} === null || ${u} === ""`),a.if(c,r._`${u} = ${(0,r.stringify)(n)}`)}t.assignDefaults=function(t,r){let{properties:i,items:n}=t.schema;if("object"===r&&i)for(let r in i)s(t,r,i[r].default);else"array"===r&&Array.isArray(n)&&n.forEach((r,i)=>s(t,i,r.default))}}),rA=ro(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validateUnion=t.validateArray=t.usePattern=t.callValidateCode=t.schemaProperties=t.allSchemaProperties=t.noPropertyInData=t.propertyInData=t.isOwnProperty=t.hasPropFunc=t.reportMissingProp=t.checkMissingProp=t.checkReportMissingProp=void 0;var r=rb(),i=rg(),s=rv(),n=rg();function a(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:r._`Object.prototype.hasOwnProperty`})}function o(t,i,s){return r._`${a(t)}.call(${i}, ${s})`}function l(t,i,s,n){let a=r._`${i}${(0,r.getProperty)(s)} === undefined`;return n?(0,r.or)(a,(0,r.not)(o(t,i,s))):a}function p(t){return t?Object.keys(t).filter(t=>"__proto__"!==t):[]}t.checkReportMissingProp=function(t,i){let{gen:s,data:n,it:a}=t;s.if(l(s,n,i,a.opts.ownProperties),()=>{t.setParams({missingProperty:r._`${i}`},!0),t.error()})},t.checkMissingProp=function({gen:t,data:i,it:{opts:s}},n,a){return(0,r.or)(...n.map(n=>(0,r.and)(l(t,i,n,s.ownProperties),r._`${a} = ${n}`)))},t.reportMissingProp=function(t,r){t.setParams({missingProperty:r},!0),t.error()},t.hasPropFunc=a,t.isOwnProperty=o,t.propertyInData=function(t,i,s,n){let a=r._`${i}${(0,r.getProperty)(s)} !== undefined`;return n?r._`${a} && ${o(t,i,s)}`:a},t.noPropertyInData=l,t.allSchemaProperties=p,t.schemaProperties=function(t,r){return p(r).filter(s=>!(0,i.alwaysValidSchema)(t,r[s]))},t.callValidateCode=function({schemaCode:t,data:i,it:{gen:n,topSchemaRef:a,schemaPath:o,errorPath:l},it:p},u,c,d){let h=d?r._`${t}, ${i}, ${a}${o}`:i,f=[[s.default.instancePath,(0,r.strConcat)(s.default.instancePath,l)],[s.default.parentData,p.parentData],[s.default.parentDataProperty,p.parentDataProperty],[s.default.rootData,s.default.rootData]];p.opts.dynamicRef&&f.push([s.default.dynamicAnchors,s.default.dynamicAnchors]);let m=r._`${h}, ${n.object(...f)}`;return c!==r.nil?r._`${u}.call(${c}, ${m})`:r._`${u}(${m})`};var u=r._`new RegExp`;t.usePattern=function({gen:t,it:{opts:i}},s){let a=i.unicodeRegExp?"u":"",{regExp:o}=i.code,l=o(s,a);return t.scopeValue("pattern",{key:l.toString(),ref:l,code:r._`${"new RegExp"===o.code?u:(0,n.useFunc)(t,o)}(${s}, ${a})`})},t.validateArray=function(t){let{gen:s,data:n,keyword:a,it:o}=t,l=s.name("valid");if(o.allErrors){let t=s.let("valid",!0);return p(()=>s.assign(t,!1)),t}return s.var(l,!0),p(()=>s.break()),l;function p(o){let p=s.const("len",r._`${n}.length`);s.forRange("i",0,p,n=>{t.subschema({keyword:a,dataProp:n,dataPropType:i.Type.Num},l),s.if((0,r.not)(l),o)})}},t.validateUnion=function(t){let{gen:s,schema:n,keyword:a,it:o}=t;if(!Array.isArray(n))throw Error("ajv implementation error");if(n.some(t=>(0,i.alwaysValidSchema)(o,t))&&!o.opts.unevaluated)return;let l=s.let("valid",!1),p=s.name("_valid");s.block(()=>n.forEach((i,n)=>{let o=t.subschema({keyword:a,schemaProp:n,compositeRule:!0},p);s.assign(l,r._`${l} || ${p}`),t.mergeValidEvaluated(o,p)||s.if((0,r.not)(l))})),t.result(l,()=>t.reset(),()=>t.error(!0))}}),rw=ro(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validateKeywordUsage=t.validSchemaType=t.funcKeywordCode=t.macroKeywordCode=void 0;var r=rb(),i=rv(),s=rA(),n=rx();function a(t){let{gen:i,data:s,it:n}=t;i.if(n.parentData,()=>i.assign(s,r._`${n.parentData}[${n.parentDataProperty}]`))}function o(t,i,s){if(void 0===s)throw Error(`keyword "${i}" failed to compile`);return t.scopeValue("keyword","function"==typeof s?{ref:s}:{ref:s,code:(0,r.stringify)(s)})}t.macroKeywordCode=function(t,i){let{gen:s,keyword:n,schema:a,parentSchema:l,it:p}=t,u=i.macro.call(p.self,a,l,p),c=o(s,n,u);!1!==p.opts.validateSchema&&p.self.validateSchema(u,!0);let d=s.name("valid");t.subschema({schema:u,schemaPath:r.nil,errSchemaPath:`${p.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},d),t.pass(d,()=>t.error(!0))},t.funcKeywordCode=function(t,l){var p;let{gen:u,keyword:c,schema:d,parentSchema:h,$data:f,it:m}=t;!function({schemaEnv:t},r){if(r.async&&!t.$async)throw Error("async keyword in sync schema")}(m,l);let y=o(u,c,!f&&l.compile?l.compile.call(m.self,d,h,m):l.validate),b=u.let("valid");function g(n=l.async?r._`await `:r.nil){let a=m.opts.passContext?i.default.this:i.default.self,o=!("compile"in l&&!f||!1===l.schema);u.assign(b,r._`${n}${(0,s.callValidateCode)(t,y,a,o)}`,l.modifying)}function v(t){var i;u.if((0,r.not)(null!=(i=l.valid)?i:b),t)}t.block$data(b,function(){if(!1===l.errors)g(),l.modifying&&a(t),v(()=>t.error());else{let s,o,p=l.async?(s=u.let("ruleErrs",null),u.try(()=>g(r._`await `),t=>u.assign(b,!1).if(r._`${t} instanceof ${m.ValidationError}`,()=>u.assign(s,r._`${t}.errors`),()=>u.throw(t))),s):(o=r._`${y}.errors`,u.assign(o,null),g(r.nil),o);l.modifying&&a(t),v(()=>(function(t,s){let{gen:a}=t;a.if(r._`Array.isArray(${s})`,()=>{a.assign(i.default.vErrors,r._`${i.default.vErrors} === null ? ${s} : ${i.default.vErrors}.concat(${s})`).assign(i.default.errors,r._`${i.default.vErrors}.length`),(0,n.extendErrors)(t)},()=>t.error())})(t,p))}}),t.ok(null!=(p=l.valid)?p:b)},t.validSchemaType=function(t,r,i=!1){return!r.length||r.some(r=>"array"===r?Array.isArray(t):"object"===r?t&&"object"==typeof t&&!Array.isArray(t):typeof t==r||i&&typeof t>"u")},t.validateKeywordUsage=function({schema:t,opts:r,self:i,errSchemaPath:s},n,a){if(Array.isArray(n.keyword)?!n.keyword.includes(a):n.keyword!==a)throw Error("ajv implementation error");let o=n.dependencies;if(null==o?void 0:o.some(r=>!Object.prototype.hasOwnProperty.call(t,r)))throw Error(`parent schema must have dependencies of ${a}: ${o.join(",")}`);if(n.validateSchema&&!n.validateSchema(t[a])){let t=`keyword "${a}" value is invalid at path "${s}": `+i.errorsText(n.validateSchema.errors);if("log"===r.validateSchema)i.logger.error(t);else throw Error(t)}}}),rC=ro(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extendSubschemaMode=t.extendSubschemaData=t.getSubschema=void 0;var r=rb(),i=rg();t.getSubschema=function(t,{keyword:s,schemaProp:n,schema:a,schemaPath:o,errSchemaPath:l,topSchemaRef:p}){if(void 0!==s&&void 0!==a)throw Error('both "keyword" and "schema" passed, only one allowed');if(void 0!==s){let a=t.schema[s];return void 0===n?{schema:a,schemaPath:r._`${t.schemaPath}${(0,r.getProperty)(s)}`,errSchemaPath:`${t.errSchemaPath}/${s}`}:{schema:a[n],schemaPath:r._`${t.schemaPath}${(0,r.getProperty)(s)}${(0,r.getProperty)(n)}`,errSchemaPath:`${t.errSchemaPath}/${s}/${(0,i.escapeFragment)(n)}`}}if(void 0!==a){if(void 0===o||void 0===l||void 0===p)throw Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:a,schemaPath:o,topSchemaRef:p,errSchemaPath:l}}throw Error('either "keyword" or "schema" must be passed')},t.extendSubschemaData=function(t,s,{dataProp:n,dataPropType:a,data:o,dataTypes:l,propertyName:p}){if(void 0!==o&&void 0!==n)throw Error('both "data" and "dataProp" passed, only one allowed');let{gen:u}=s;if(void 0!==n){let{errorPath:o,dataPathArr:l,opts:p}=s;c(u.let("data",r._`${s.data}${(0,r.getProperty)(n)}`,!0)),t.errorPath=r.str`${o}${(0,i.getErrorPath)(n,a,p.jsPropertySyntax)}`,t.parentDataProperty=r._`${n}`,t.dataPathArr=[...l,t.parentDataProperty]}function c(r){t.data=r,t.dataLevel=s.dataLevel+1,t.dataTypes=[],s.definedProperties=new Set,t.parentData=s.data,t.dataNames=[...s.dataNames,r]}void 0!==o&&(c(o instanceof r.Name?o:u.let("data",o,!0)),void 0!==p&&(t.propertyName=p)),l&&(t.dataTypes=l)},t.extendSubschemaMode=function(t,{jtdDiscriminator:r,jtdMetadata:i,compositeRule:s,createErrors:n,allErrors:a}){void 0!==s&&(t.compositeRule=s),void 0!==n&&(t.createErrors=n),void 0!==a&&(t.allErrors=a),t.jtdDiscriminator=r,t.jtdMetadata=i}}),rI=ro((t,r)=>{r.exports=function t(r,i){if(r===i)return!0;if(r&&i&&"object"==typeof r&&"object"==typeof i){if(r.constructor!==i.constructor)return!1;if(Array.isArray(r)){if((s=r.length)!=i.length)return!1;for(n=s;0!=n--;)if(!t(r[n],i[n]))return!1;return!0}if(r.constructor===RegExp)return r.source===i.source&&r.flags===i.flags;if(r.valueOf!==Object.prototype.valueOf)return r.valueOf()===i.valueOf();if(r.toString!==Object.prototype.toString)return r.toString()===i.toString();if((s=(a=Object.keys(r)).length)!==Object.keys(i).length)return!1;for(n=s;0!=n--;)if(!Object.prototype.hasOwnProperty.call(i,a[n]))return!1;for(n=s;0!=n--;){var s,n,a,o=a[n];if(!t(r[o],i[o]))return!1}return!0}return r!=r&&i!=i}}),rk=ro((t,r)=>{var i=r.exports=function(t,r,s){"function"==typeof r&&(s=r,r={});var n="function"==typeof(s=r.cb||s)?s:s.pre||function(){};!function t(r,s,n,a,o,l,p,u,c,d){if(a&&"object"==typeof a&&!Array.isArray(a)){for(var h in s(a,o,l,p,u,c,d),a){var f=a[h];if(Array.isArray(f)){if(h in i.arrayKeywords)for(var m=0;m<f.length;m++)t(r,s,n,f[m],o+"/"+h+"/"+m,l,o,h,a,m)}else if(h in i.propsKeywords){if(f&&"object"==typeof f)for(var y in f)t(r,s,n,f[y],o+"/"+h+"/"+y.replace(/~/g,"~0").replace(/\//g,"~1"),l,o,h,a,y)}else(h in i.keywords||r.allKeys&&!(h in i.skipKeywords))&&t(r,s,n,f,o+"/"+h,l,o,h,a)}n(a,o,l,p,u,c,d)}}(r,n,s.post||function(){},t,"",t)};i.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},i.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},i.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},i.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0}}),rN=ro(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getSchemaRefs=t.resolveUrl=t.normalizeId=t._getFullPath=t.getFullPath=t.inlineRef=void 0;var r=rg(),i=rI(),s=rk(),n=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);t.inlineRef=function(t,i=!0){return"boolean"==typeof t||(!0===i?!function t(r){for(let i in r){if(a.has(i))return!0;let s=r[i];if(Array.isArray(s)&&s.some(t)||"object"==typeof s&&t(s))return!0}return!1}(t):!!i&&function t(i){let s=0;for(let a in i)if("$ref"===a||(s++,!n.has(a)&&("object"==typeof i[a]&&(0,r.eachItem)(i[a],r=>s+=t(r)),s===1/0)))return 1/0;return s}(t)<=i)};var a=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function o(t,r="",i){!1!==i&&(r=u(r));let s=t.parse(r);return l(t,s)}function l(t,r){return t.serialize(r).split("#")[0]+"#"}t.getFullPath=o,t._getFullPath=l;var p=/#\/?$/;function u(t){return t?t.replace(p,""):""}t.normalizeId=u,t.resolveUrl=function(t,r,i){return i=u(i),t.resolve(r,i)};var c=/^[a-z_][-a-z0-9._]*$/i;t.getSchemaRefs=function(t,r){if("boolean"==typeof t)return{};let{schemaId:n,uriResolver:a}=this.opts,l=u(t[n]||r),p={"":l},d=o(a,l,!1),h={},f=new Set;return s(t,{allKeys:!0},(t,r,i,s)=>{if(void 0===s)return;let a=d+r,o=p[s];function l(r){let i=this.opts.uriResolver.resolve;if(r=u(o?i(o,r):r),f.has(r))throw y(r);f.add(r);let s=this.refs[r];return"string"==typeof s&&(s=this.refs[s]),"object"==typeof s?m(t,s.schema,r):r!==u(a)&&("#"===r[0]?(m(t,h[r],r),h[r]=t):this.refs[r]=a),r}function b(t){if("string"==typeof t){if(!c.test(t))throw Error(`invalid anchor "${t}"`);l.call(this,`#${t}`)}}"string"==typeof t[n]&&(o=l.call(this,t[n])),b.call(this,t.$anchor),b.call(this,t.$dynamicAnchor),p[r]=o}),h;function m(t,r,s){if(void 0!==r&&!i(t,r))throw y(s)}function y(t){return Error(`reference "${t}" resolves to more than one schema`)}}}),rO=ro(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getData=t.KeywordCxt=t.validateFunctionCode=void 0;var r=rT(),i=r_(),s=rS(),n=r_(),a=rP(),o=rw(),l=rC(),p=rb(),u=rv(),c=rN(),d=rg(),h=rx();function f({gen:t,validateName:r,schema:i,schemaEnv:s,opts:n},a){var o;n.code.es5?t.func(r,p._`${u.default.data}, ${u.default.valCxt}`,s.$async,()=>{var r,s;t.code(p._`"use strict"; ${m(i,n)}`),r=t,s=n,r.if(u.default.valCxt,()=>{r.var(u.default.instancePath,p._`${u.default.valCxt}.${u.default.instancePath}`),r.var(u.default.parentData,p._`${u.default.valCxt}.${u.default.parentData}`),r.var(u.default.parentDataProperty,p._`${u.default.valCxt}.${u.default.parentDataProperty}`),r.var(u.default.rootData,p._`${u.default.valCxt}.${u.default.rootData}`),s.dynamicRef&&r.var(u.default.dynamicAnchors,p._`${u.default.valCxt}.${u.default.dynamicAnchors}`)},()=>{r.var(u.default.instancePath,p._`""`),r.var(u.default.parentData,p._`undefined`),r.var(u.default.parentDataProperty,p._`undefined`),r.var(u.default.rootData,u.default.data),s.dynamicRef&&r.var(u.default.dynamicAnchors,p._`{}`)}),t.code(a)}):t.func(r,p._`${u.default.data}, ${(o=n,p._`{${u.default.instancePath}="", ${u.default.parentData}, ${u.default.parentDataProperty}, ${u.default.rootData}=${u.default.data}${o.dynamicRef?p._`, ${u.default.dynamicAnchors}={}`:p.nil}}={}`)}`,s.$async,()=>t.code(m(i,n)).code(a))}function m(t,r){let i="object"==typeof t&&t[r.schemaId];return i&&(r.code.source||r.code.process)?p._`/*# sourceURL=${i} */`:p.nil}function y({schema:t,self:r}){if("boolean"==typeof t)return!t;for(let i in t)if(r.RULES.all[i])return!0;return!1}function b(t){return"boolean"!=typeof t.schema}function g(t){(0,d.checkUnknownRules)(t),function(t){let{schema:r,errSchemaPath:i,opts:s,self:n}=t;r.$ref&&s.ignoreKeywordsWithRef&&(0,d.schemaHasRulesButRef)(r,n.RULES)&&n.logger.warn(`$ref: keywords ignored in schema at path "${i}"`)}(t)}function v(t,r){if(t.opts.jtd)return T(t,[],!1,r);let s=(0,i.getSchemaTypes)(t.schema),n=(0,i.coerceAndCheckDataType)(t,s);T(t,s,!n,r)}function x({gen:t,schemaEnv:r,schema:i,errSchemaPath:s,opts:n}){let a=i.$comment;if(!0===n.$comment)t.code(p._`${u.default.self}.logger.log(${a})`);else if("function"==typeof n.$comment){let i=p.str`${s}/$comment`,n=t.scopeValue("root",{ref:r.root});t.code(p._`${u.default.self}.opts.$comment(${a}, ${i}, ${n}.schema)`)}}function T(t,r,i,a){var o,l,c,h;let{gen:f,schema:m,data:y,allErrors:b,opts:g,self:v}=t,{RULES:x}=v;if(m.$ref&&(g.ignoreKeywordsWithRef||!(0,d.schemaHasRulesButRef)(m,x)))return void f.block(()=>A(t,"$ref",x.all.$ref.definition));function T(o){(0,s.shouldUseGroup)(m,o)&&(o.type?(f.if((0,n.checkDataType)(o.type,y,g.strictNumbers)),E(t,o),1===r.length&&r[0]===o.type&&i&&(f.else(),(0,n.reportTypeError)(t)),f.endIf()):E(t,o),b||f.if(p._`${u.default.errors} === ${a||0}`))}g.jtd||(o=t,l=r,!o.schemaEnv.meta&&o.opts.strictTypes&&(function(t,r){if(r.length){if(!t.dataTypes.length){t.dataTypes=r;return}r.forEach(r=>{S(t.dataTypes,r)||_(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),function(t,r){let i=[];for(let s of t.dataTypes)S(r,s)?i.push(s):r.includes("integer")&&"number"===s&&i.push("integer");t.dataTypes=i}(t,r)}}(o,l),o.opts.allowUnionTypes||(c=o,(h=l).length>1&&!(2===h.length&&h.includes("null"))&&_(c,"use allowUnionTypes to allow union type keyword")),function(t,r){let i=t.self.RULES.all;for(let n in i){let a=i[n];if("object"==typeof a&&(0,s.shouldUseRule)(t.schema,a)){let{type:i}=a.definition;i.length&&!i.some(t=>{var i,s;return i=r,s=t,i.includes(s)||"number"===s&&i.includes("integer")})&&_(t,`missing type "${i.join(",")}" for keyword "${n}"`)}}}(o,o.dataTypes))),f.block(()=>{for(let t of x.rules)T(t);T(x.post)})}function E(t,r){let{gen:i,schema:n,opts:{useDefaults:o}}=t;o&&(0,a.assignDefaults)(t,r.type),i.block(()=>{for(let i of r.rules)(0,s.shouldUseRule)(n,i)&&A(t,i.keyword,i.definition,r.type)})}function S(t,r){return t.includes(r)||"integer"===r&&t.includes("number")}function _(t,r){let i=t.schemaEnv.baseId+t.errSchemaPath;r+=` at "${i}" (strictTypes)`,(0,d.checkStrictMode)(t,r,t.opts.strictTypes)}t.validateFunctionCode=function(t){b(t)&&(g(t),y(t))?function(t){let{schema:r,opts:i,gen:s}=t;f(t,()=>{i.$comment&&r.$comment&&x(t),function(t){let{schema:r,opts:i}=t;void 0!==r.default&&i.useDefaults&&i.strictSchema&&(0,d.checkStrictMode)(t,"default is ignored in the schema root")}(t),s.let(u.default.vErrors,null),s.let(u.default.errors,0),i.unevaluated&&function(t){let{gen:r,validateName:i}=t;t.evaluated=r.const("evaluated",p._`${i}.evaluated`),r.if(p._`${t.evaluated}.dynamicProps`,()=>r.assign(p._`${t.evaluated}.props`,p._`undefined`)),r.if(p._`${t.evaluated}.dynamicItems`,()=>r.assign(p._`${t.evaluated}.items`,p._`undefined`))}(t),v(t),function(t){let{gen:r,schemaEnv:i,validateName:s,ValidationError:n,opts:a}=t;i.$async?r.if(p._`${u.default.errors} === 0`,()=>r.return(u.default.data),()=>r.throw(p._`new ${n}(${u.default.vErrors})`)):(r.assign(p._`${s}.errors`,u.default.vErrors),a.unevaluated&&function({gen:t,evaluated:r,props:i,items:s}){i instanceof p.Name&&t.assign(p._`${r}.props`,i),s instanceof p.Name&&t.assign(p._`${r}.items`,s)}(t),r.return(p._`${u.default.errors} === 0`))}(t)})}(t):f(t,()=>(0,r.topBoolOrEmptySchema)(t))};class P{constructor(t,r,i){if((0,o.validateKeywordUsage)(t,r,i),this.gen=t.gen,this.allErrors=t.allErrors,this.keyword=i,this.data=t.data,this.schema=t.schema[i],this.$data=r.$data&&t.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,d.schemaRefOrVal)(t,this.schema,i,this.$data),this.schemaType=r.schemaType,this.parentSchema=t.schema,this.params={},this.it=t,this.def=r,this.$data)this.schemaCode=t.gen.const("vSchema",I(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0,o.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw Error(`${i} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:!1!==r.errors)&&(this.errsCount=t.gen.const("_errs",u.default.errors))}result(t,r,i){this.failResult((0,p.not)(t),r,i)}failResult(t,r,i){(this.gen.if(t),i)?i():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(t,r){this.failResult((0,p.not)(t),void 0,r)}fail(t){if(void 0===t){this.error(),this.allErrors||this.gen.if(!1);return}(this.gen.if(t),this.error(),this.allErrors)?this.gen.endIf():this.gen.else()}fail$data(t){if(!this.$data)return this.fail(t);let{schemaCode:r}=this;this.fail(p._`${r} !== undefined && (${(0,p.or)(this.invalid$data(),t)})`)}error(t,r,i){if(r){this.setParams(r),this._error(t,i),this.setParams({});return}this._error(t,i)}_error(t,r){(t?h.reportExtraError:h.reportError)(this,this.def.error,r)}$dataError(){(0,h.reportError)(this,this.def.$dataError||h.keyword$DataError)}reset(){if(void 0===this.errsCount)throw Error('add "trackErrors" to keyword definition');(0,h.resetErrorsCount)(this.gen,this.errsCount)}ok(t){this.allErrors||this.gen.if(t)}setParams(t,r){r?Object.assign(this.params,t):this.params=t}block$data(t,r,i=p.nil){this.gen.block(()=>{this.check$data(t,i),r()})}check$data(t=p.nil,r=p.nil){if(!this.$data)return;let{gen:i,schemaCode:s,schemaType:n,def:a}=this;i.if((0,p.or)(p._`${s} === undefined`,r)),t!==p.nil&&i.assign(t,!0),(n.length||a.validateSchema)&&(i.elseIf(this.invalid$data()),this.$dataError(),t!==p.nil)&&i.assign(t,!1),i.else()}invalid$data(){let{gen:t,schemaCode:r,schemaType:i,def:s,it:a}=this;return(0,p.or)(function(){if(i.length){if(!(r instanceof p.Name))throw Error("ajv implementation error");let t=Array.isArray(i)?i:[i];return p._`${(0,n.checkDataTypes)(t,r,a.opts.strictNumbers,n.DataType.Wrong)}`}return p.nil}(),function(){if(s.validateSchema){let i=t.scopeValue("validate$data",{ref:s.validateSchema});return p._`!${i}(${r})`}return p.nil}())}subschema(t,i){let s=(0,l.getSubschema)(this.it,t);(0,l.extendSubschemaData)(s,this.it,t),(0,l.extendSubschemaMode)(s,t);let n={...this.it,...s,items:void 0,props:void 0};return b(n)&&(g(n),y(n))?function(t,r){var i;let s,{schema:n,gen:a,opts:o}=t;o.$comment&&n.$comment&&x(t),(s=(i=t).schema[i.opts.schemaId])&&(i.baseId=(0,c.resolveUrl)(i.opts.uriResolver,i.baseId,s)),function(t){if(t.schema.$async&&!t.schemaEnv.$async)throw Error("async schema in sync schema")}(t);let l=a.const("_errs",u.default.errors);v(t,l),a.var(r,p._`${l} === ${u.default.errors}`)}(n,i):(0,r.boolOrEmptySchema)(n,i),n}mergeEvaluated(t,r){let{it:i,gen:s}=this;i.opts.unevaluated&&(!0!==i.props&&void 0!==t.props&&(i.props=d.mergeEvaluated.props(s,t.props,i.props,r)),!0!==i.items&&void 0!==t.items&&(i.items=d.mergeEvaluated.items(s,t.items,i.items,r)))}mergeValidEvaluated(t,r){let{it:i,gen:s}=this;if(i.opts.unevaluated&&(!0!==i.props||!0!==i.items))return s.if(r,()=>this.mergeEvaluated(t,p.Name)),!0}}function A(t,r,i,s){let n=new P(t,i,r);"code"in i?i.code(n,s):n.$data&&i.validate?(0,o.funcKeywordCode)(n,i):"macro"in i?(0,o.macroKeywordCode)(n,i):(i.compile||i.validate)&&(0,o.funcKeywordCode)(n,i)}t.KeywordCxt=P;var w=/^\/(?:[^~]|~0|~1)*$/,C=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function I(t,{dataLevel:r,dataNames:i,dataPathArr:s}){let n,a;if(""===t)return u.default.rootData;if("/"===t[0]){if(!w.test(t))throw Error(`Invalid JSON-pointer: ${t}`);n=t,a=u.default.rootData}else{let o=C.exec(t);if(!o)throw Error(`Invalid JSON-pointer: ${t}`);let p=+o[1];if("#"===(n=o[2])){if(p>=r)throw Error(l("property/index",p));return s[r-p]}if(p>r)throw Error(l("data",p));if(a=i[r-p],!n)return a}let o=a;for(let t of n.split("/"))t&&(a=p._`${a}${(0,p.getProperty)((0,d.unescapeJsonPointer)(t))}`,o=p._`${o} && ${a}`);return o;function l(t,i){return`Cannot access ${t} ${i} levels up, current level is ${r}`}}t.getData=I}),rD=ro(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=class extends Error{constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}}}),rj=ro(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=rN();t.default=class extends Error{constructor(t,i,s,n){super(n||`can't resolve reference ${s} from id ${i}`),this.missingRef=(0,r.resolveUrl)(t,i,s),this.missingSchema=(0,r.normalizeId)((0,r.getFullPath)(t,this.missingRef))}}}),rL=ro(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.resolveSchema=t.getCompilingSchema=t.resolveRef=t.compileSchema=t.SchemaEnv=void 0;var r=rb(),i=rD(),s=rv(),n=rN(),a=rg(),o=rO();class l{constructor(t){var r;let i;this.refs={},this.dynamicAnchors={},"object"==typeof t.schema&&(i=t.schema),this.schema=t.schema,this.schemaId=t.schemaId,this.root=t.root||this,this.baseId=null!=(r=t.baseId)?r:(0,n.normalizeId)(null==i?void 0:i[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=null==i?void 0:i.$async,this.refs={}}}function p(t){let a=c.call(this,t);if(a)return a;let l=(0,n.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:p,lines:u}=this.opts.code,{ownProperties:d}=this.opts,h=new r.CodeGen(this.scope,{es5:p,lines:u,ownProperties:d}),f;t.$async&&(f=h.scopeValue("Error",{ref:i.default,code:r._`require("ajv/dist/runtime/validation_error").default`}));let m=h.scopeName("validate");t.validateName=m;let y={gen:h,allErrors:this.opts.allErrors,data:s.default.data,parentData:s.default.parentData,parentDataProperty:s.default.parentDataProperty,dataNames:[s.default.data],dataPathArr:[r.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:h.scopeValue("schema",!0===this.opts.code.source?{ref:t.schema,code:(0,r.stringify)(t.schema)}:{ref:t.schema}),validateName:m,ValidationError:f,schema:t.schema,schemaEnv:t,rootId:l,baseId:t.baseId||l,schemaPath:r.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:r._`""`,opts:this.opts,self:this},b;try{this._compilations.add(t),(0,o.validateFunctionCode)(y),h.optimize(this.opts.code.optimize);let i=h.toString();b=`${h.scopeRefs(s.default.scope)}return ${i}`,this.opts.code.process&&(b=this.opts.code.process(b,t));let n=Function(`${s.default.self}`,`${s.default.scope}`,b)(this,this.scope.get());if(this.scope.value(m,{ref:n}),n.errors=null,n.schema=t.schema,n.schemaEnv=t,t.$async&&(n.$async=!0),!0===this.opts.code.source&&(n.source={validateName:m,validateCode:i,scopeValues:h._values}),this.opts.unevaluated){let{props:t,items:i}=y;n.evaluated={props:t instanceof r.Name?void 0:t,items:i instanceof r.Name?void 0:i,dynamicProps:t instanceof r.Name,dynamicItems:i instanceof r.Name},n.source&&(n.source.evaluated=(0,r.stringify)(n.evaluated))}return t.validate=n,t}catch(r){throw delete t.validate,delete t.validateName,b&&this.logger.error("Error compiling schema, function code:",b),r}finally{this._compilations.delete(t)}}function u(t){return(0,n.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:p.call(this,t)}function c(t){for(let s of this._compilations){var r,i;if(r=s,i=t,r.schema===i.schema&&r.root===i.root&&r.baseId===i.baseId)return s}}function d(t,r){let i;for(;"string"==typeof(i=this.refs[r]);)r=i;return i||this.schemas[r]||h.call(this,t,r)}function h(t,r){let i=this.opts.uriResolver.parse(r),s=(0,n._getFullPath)(this.opts.uriResolver,i),a=(0,n.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&s===a)return m.call(this,i,t);let o=(0,n.normalizeId)(s),u=this.refs[o]||this.schemas[o];if("string"==typeof u){let r=h.call(this,t,u);if("object"!=typeof(null==r?void 0:r.schema))return;return m.call(this,i,r)}if("object"==typeof(null==u?void 0:u.schema)){if(u.validate||p.call(this,u),o===(0,n.normalizeId)(r)){let{schema:r}=u,{schemaId:i}=this.opts,s=r[i];return s&&(a=(0,n.resolveUrl)(this.opts.uriResolver,a,s)),new l({schema:r,schemaId:i,root:t,baseId:a})}return m.call(this,i,u)}}t.SchemaEnv=l,t.compileSchema=p,t.resolveRef=function(t,r,i){var s;i=(0,n.resolveUrl)(this.opts.uriResolver,r,i);let a=t.refs[i];if(a)return a;let o=d.call(this,t,i);if(void 0===o){let n=null==(s=t.localRefs)?void 0:s[i],{schemaId:a}=this.opts;n&&(o=new l({schema:n,schemaId:a,root:t,baseId:r}))}if(void 0!==o)return t.refs[i]=u.call(this,o)},t.getCompilingSchema=c,t.resolveSchema=h;var f=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function m(t,{baseId:r,schema:i,root:s}){var o;let p;if((null==(o=t.fragment)?void 0:o[0])!=="/")return;for(let s of t.fragment.slice(1).split("/")){if("boolean"==typeof i)return;let t=i[(0,a.unescapeFragment)(s)];if(void 0===t)return;let o="object"==typeof(i=t)&&i[this.opts.schemaId];!f.has(s)&&o&&(r=(0,n.resolveUrl)(this.opts.uriResolver,r,o))}if("boolean"!=typeof i&&i.$ref&&!(0,a.schemaHasRulesButRef)(i,this.RULES)){let t=(0,n.resolveUrl)(this.opts.uriResolver,r,i.$ref);p=h.call(this,s,t)}let{schemaId:u}=this.opts;if((p=p||new l({schema:i,schemaId:u,root:s,baseId:r})).schema!==p.root.schema)return p}}),rR=ro((t,r)=>{r.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}}),rM=ro((t,r)=>{r.exports={HEX:{0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,a:10,A:10,b:11,B:11,c:12,C:12,d:13,D:13,e:14,E:14,f:15,F:15}}}),rF=ro((t,r)=>{var{HEX:i}=rM(),s=/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u;function n(t){if(3>l(t,"."))return{host:t,isIPV4:!1};let[r]=t.match(s)||[];return r?{host:function(t){let r="",i=!0,s=t.length;for(let n=0;n<s;n++){let a=t[n];"0"===a&&i?(n+1<=s&&"."===t[n+1]||n+1===s)&&(r+=a,i=!1):(i="."===a,r+=a)}return r}(r),isIPV4:!0}:{host:t,isIPV4:!1}}function a(t,r=!1){let s="",n=!0;for(let r of t){if(void 0===i[r])return;"0"!==r&&!0===n&&(n=!1),n||(s+=r)}return r&&0===s.length&&(s="0"),s}function o(t){if(2>l(t,":"))return{host:t,isIPV6:!1};let r=function(t){let r=0,i={error:!1,address:"",zone:""},s=[],n=[],o=!1,l=!1,p=!1;function u(){if(n.length){if(!1===o){let t=a(n);if(void 0===t)return i.error=!0,!1;s.push(t)}n.length=0}return!0}for(let a=0;a<t.length;a++){let c=t[a];if("["!==c&&"]"!==c)if(":"===c){if(!0===l&&(p=!0),!u())break;if(r++,s.push(":"),r>7){i.error=!0;break}a-1>=0&&":"===t[a-1]&&(l=!0);continue}else if("%"===c){if(!u())break;o=!0}else{n.push(c);continue}}return n.length&&(o?i.zone=n.join(""):p?s.push(n.join("")):s.push(a(n))),i.address=s.join(""),i}(t);if(r.error)return{host:t,isIPV6:!1};{let{address:t,address:i}=r;return r.zone&&(t+="%"+r.zone,i+="%25"+r.zone),{host:t,escapedHost:i,isIPV6:!0}}}function l(t,r){let i=0;for(let s=0;s<t.length;s++)t[s]===r&&i++;return i}var p=/^\.\.?\//u,u=/^\/\.(?:\/|$)/u,c=/^\/\.\.(?:\/|$)/u,d=/^\/?(?:.|\n)*?(?=\/|$)/u;r.exports={recomposeAuthority:function(t){let r=[];if(void 0!==t.userinfo&&(r.push(t.userinfo),r.push("@")),void 0!==t.host){let i=unescape(t.host),s=n(i);if(s.isIPV4)i=s.host;else{let r=o(s.host);i=!0===r.isIPV6?`[${r.escapedHost}]`:t.host}r.push(i)}return("number"==typeof t.port||"string"==typeof t.port)&&(r.push(":"),r.push(String(t.port))),r.length?r.join(""):void 0},normalizeComponentEncoding:function(t,r){let i=!0!==r?escape:unescape;return void 0!==t.scheme&&(t.scheme=i(t.scheme)),void 0!==t.userinfo&&(t.userinfo=i(t.userinfo)),void 0!==t.host&&(t.host=i(t.host)),void 0!==t.path&&(t.path=i(t.path)),void 0!==t.query&&(t.query=i(t.query)),void 0!==t.fragment&&(t.fragment=i(t.fragment)),t},removeDotSegments:function(t){let r=[];for(;t.length;)if(t.match(p))t=t.replace(p,"");else if(t.match(u))t=t.replace(u,"/");else if(t.match(c))t=t.replace(c,"/"),r.pop();else if("."===t||".."===t)t="";else{let i=t.match(d);if(i){let s=i[0];t=t.slice(s.length),r.push(s)}else throw Error("Unexpected dot segment condition")}return r.join("")},normalizeIPv4:n,normalizeIPv6:o,stringArrayToHexStripped:a}}),rB=ro((t,r)=>{var i=/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu,s=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu;function n(t){return"boolean"==typeof t.secure?t.secure:"wss"===String(t.scheme).toLowerCase()}function a(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function o(t){let r="https"===String(t.scheme).toLowerCase();return(t.port===(r?443:80)||""===t.port)&&(t.port=void 0),t.path||(t.path="/"),t}var l={scheme:"http",domainHost:!0,parse:a,serialize:o},p={scheme:"https",domainHost:l.domainHost,parse:a,serialize:o},u={scheme:"ws",domainHost:!0,parse:function(t){return t.secure=n(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t},serialize:function(t){if((t.port===(n(t)?443:80)||""===t.port)&&(t.port=void 0),"boolean"==typeof t.secure&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[r,i]=t.resourceName.split("?");t.path=r&&"/"!==r?r:void 0,t.query=i,t.resourceName=void 0}return t.fragment=void 0,t}},c={scheme:"wss",domainHost:u.domainHost,parse:u.parse,serialize:u.serialize},d={http:l,https:p,ws:u,wss:c,urn:{scheme:"urn",parse:function(t,r){if(!t.path)return t.error="URN can not be parsed",t;let i=t.path.match(s);if(i){let s=r.scheme||t.scheme||"urn";t.nid=i[1].toLowerCase(),t.nss=i[2];let n=d[`${s}:${r.nid||t.nid}`];t.path=void 0,n&&(t=n.parse(t,r))}else t.error=t.error||"URN can not be parsed.";return t},serialize:function(t,r){let i=r.scheme||t.scheme||"urn",s=t.nid.toLowerCase(),n=d[`${i}:${r.nid||s}`];n&&(t=n.serialize(t,r));let a=t,o=t.nss;return a.path=`${s||r.nid}:${o}`,r.skipEscape=!0,a},skipNormalize:!0},"urn:uuid":{scheme:"urn:uuid",parse:function(t,r){return t.uuid=t.nss,t.nss=void 0,r.tolerant||t.uuid&&i.test(t.uuid)||(t.error=t.error||"UUID is not valid."),t},serialize:function(t){return t.nss=(t.uuid||"").toLowerCase(),t},skipNormalize:!0}};r.exports=d}),rU=ro((t,r)=>{var{normalizeIPv6:i,normalizeIPv4:s,removeDotSegments:n,recomposeAuthority:a,normalizeComponentEncoding:o}=rF(),l=rB();function p(t,r,i,s){let a={};return s||(t=h(u(t,i),i),r=h(u(r,i),i)),!(i=i||{}).tolerant&&r.scheme?(a.scheme=r.scheme,a.userinfo=r.userinfo,a.host=r.host,a.port=r.port,a.path=n(r.path||""),a.query=r.query):(void 0!==r.userinfo||void 0!==r.host||void 0!==r.port?(a.userinfo=r.userinfo,a.host=r.host,a.port=r.port,a.path=n(r.path||""),a.query=r.query):(r.path?("/"===r.path.charAt(0)?a.path=n(r.path):(void 0===t.userinfo&&void 0===t.host&&void 0===t.port||t.path?t.path?a.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+r.path:a.path=r.path:a.path="/"+r.path,a.path=n(a.path)),a.query=r.query):(a.path=t.path,void 0!==r.query)?a.query=r.query:a.query=t.query,a.userinfo=t.userinfo,a.host=t.host,a.port=t.port),a.scheme=t.scheme),a.fragment=r.fragment,a}function u(t,r){let i={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},s=Object.assign({},r),o=[],p=l[(s.scheme||i.scheme||"").toLowerCase()];p&&p.serialize&&p.serialize(i,s),void 0!==i.path&&(s.skipEscape?i.path=unescape(i.path):(i.path=escape(i.path),void 0!==i.scheme&&(i.path=i.path.split("%3A").join(":")))),"suffix"!==s.reference&&i.scheme&&o.push(i.scheme,":");let u=a(i);if(void 0!==u&&("suffix"!==s.reference&&o.push("//"),o.push(u),i.path&&"/"!==i.path.charAt(0)&&o.push("/")),void 0!==i.path){let t=i.path;s.absolutePath||p&&p.absolutePath||(t=n(t)),void 0===u&&(t=t.replace(/^\/\//u,"/%2F")),o.push(t)}return void 0!==i.query&&o.push("?",i.query),void 0!==i.fragment&&o.push("#",i.fragment),o.join("")}var c=Array.from({length:127},(t,r)=>/[^!"$&'()*+,\-.;=_`a-z{}~]/u.test(String.fromCharCode(r))),d=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function h(t,r){let n=Object.assign({},r),a={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=-1!==t.indexOf("%"),p=!1;"suffix"===n.reference&&(t=(n.scheme?n.scheme+":":"")+"//"+t);let u=t.match(d);if(u){if(a.scheme=u[1],a.userinfo=u[3],a.host=u[4],a.port=parseInt(u[5],10),a.path=u[6]||"",a.query=u[7],a.fragment=u[8],isNaN(a.port)&&(a.port=u[5]),a.host){let t=s(a.host);if(!1===t.isIPV4){let r=i(t.host);a.host=r.host.toLowerCase(),p=r.isIPV6}else a.host=t.host,p=!0}void 0!==a.scheme||void 0!==a.userinfo||void 0!==a.host||void 0!==a.port||void 0!==a.query||a.path?void 0===a.scheme?a.reference="relative":void 0===a.fragment?a.reference="absolute":a.reference="uri":a.reference="same-document",n.reference&&"suffix"!==n.reference&&n.reference!==a.reference&&(a.error=a.error||"URI is not a "+n.reference+" reference.");let t=l[(n.scheme||a.scheme||"").toLowerCase()];if(!n.unicodeSupport&&(!t||!t.unicodeSupport)&&a.host&&(n.domainHost||t&&t.domainHost)&&!1===p&&function(t){let r=0;for(let i=0,s=t.length;i<s;++i)if((r=t.charCodeAt(i))>126||c[r])return!0;return!1}(a.host))try{a.host=URL.domainToASCII(a.host.toLowerCase())}catch(t){a.error=a.error||"Host's domain name can not be converted to ASCII: "+t}(!t||t&&!t.skipNormalize)&&(o&&void 0!==a.scheme&&(a.scheme=unescape(a.scheme)),o&&void 0!==a.host&&(a.host=unescape(a.host)),a.path&&(a.path=escape(unescape(a.path))),a.fragment&&(a.fragment=encodeURI(decodeURIComponent(a.fragment)))),t&&t.parse&&t.parse(a,n)}else a.error=a.error||"URI can not be parsed.";return a}var f={SCHEMES:l,normalize:function(t,r){return"string"==typeof t?t=u(h(t,r),r):"object"==typeof t&&(t=h(u(t,r),r)),t},resolve:function(t,r,i){let s=Object.assign({scheme:"null"},i);return u(p(h(t,s),h(r,s),s,!0),{...s,skipEscape:!0})},resolveComponents:p,equal:function(t,r,i){return"string"==typeof t?t=u(o(h(t=unescape(t),i),!0),{...i,skipEscape:!0}):"object"==typeof t&&(t=u(o(t,!0),{...i,skipEscape:!0})),"string"==typeof r?r=u(o(h(r=unescape(r),i),!0),{...i,skipEscape:!0}):"object"==typeof r&&(r=u(o(r,!0),{...i,skipEscape:!0})),t.toLowerCase()===r.toLowerCase()},serialize:u,parse:h};r.exports=f,r.exports.default=f,r.exports.fastUri=f}),r$=ro(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=rU();r.code='require("ajv/dist/runtime/uri").default',t.default=r}),rV=ro(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=void 0;var r=rO();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return r.KeywordCxt}});var i=rb();Object.defineProperty(t,"_",{enumerable:!0,get:function(){return i._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return i.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return i.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return i.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return i.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return i.CodeGen}});var s=rD(),n=rj(),a=rE(),o=rL(),l=rb(),p=rN(),u=r_(),c=rg(),d=rR(),h=r$(),f=(t,r)=>new RegExp(t,r);f.code="new RegExp";var m=["removeAdditional","useDefaults","coerceTypes"],y=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),b={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},g={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'};class v{constructor(t={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,t=this.opts={...t,...function(t){var r,i,s,n,a,o,l,p,u,c,d,m,y,b,g,v,x,T,E,S,_,P,A,w,C;let I=t.strict,k=null==(r=t.code)?void 0:r.optimize,N=!0===k||void 0===k?1:k||0,O=null!=(s=null==(i=t.code)?void 0:i.regExp)?s:f,D=null!=(n=t.uriResolver)?n:h.default;return{strictSchema:null==(o=null!=(a=t.strictSchema)?a:I)||o,strictNumbers:null==(p=null!=(l=t.strictNumbers)?l:I)||p,strictTypes:null!=(c=null!=(u=t.strictTypes)?u:I)?c:"log",strictTuples:null!=(m=null!=(d=t.strictTuples)?d:I)?m:"log",strictRequired:null!=(b=null!=(y=t.strictRequired)?y:I)&&b,code:t.code?{...t.code,optimize:N,regExp:O}:{optimize:N,regExp:O},loopRequired:null!=(g=t.loopRequired)?g:200,loopEnum:null!=(v=t.loopEnum)?v:200,meta:null==(x=t.meta)||x,messages:null==(T=t.messages)||T,inlineRefs:null==(E=t.inlineRefs)||E,schemaId:null!=(S=t.schemaId)?S:"$id",addUsedSchema:null==(_=t.addUsedSchema)||_,validateSchema:null==(P=t.validateSchema)||P,validateFormats:null==(A=t.validateFormats)||A,unicodeRegExp:null==(w=t.unicodeRegExp)||w,int32range:null==(C=t.int32range)||C,uriResolver:D}}(t)};let{es5:r,lines:i}=this.opts.code;this.scope=new l.ValueScope({scope:{},prefixes:y,es5:r,lines:i}),this.logger=function(t){if(!1===t)return A;if(void 0===t)return console;if(t.log&&t.warn&&t.error)return t;throw Error("logger must implement log, warn and error methods")}(t.logger);let s=t.validateFormats;t.validateFormats=!1,this.RULES=(0,a.getRules)(),x.call(this,b,t,"NOT SUPPORTED"),x.call(this,g,t,"DEPRECATED","warn"),this._metaOpts=P.call(this),t.formats&&S.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),t.keywords&&_.call(this,t.keywords),"object"==typeof t.meta&&this.addMetaSchema(t.meta),E.call(this),t.validateFormats=s}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:t,meta:r,schemaId:i}=this.opts,s=d;"id"===i&&((s={...d}).id=s.$id,delete s.$id),r&&t&&this.addMetaSchema(s,s[i],!1)}defaultMeta(){let{meta:t,schemaId:r}=this.opts;return this.opts.defaultMeta="object"==typeof t?t[r]||t:void 0}validate(t,r){let i;if("string"==typeof t){if(!(i=this.getSchema(t)))throw Error(`no schema with key or ref "${t}"`)}else i=this.compile(t);let s=i(r);return"$async"in i||(this.errors=i.errors),s}compile(t,r){let i=this._addSchema(t,r);return i.validate||this._compileSchemaEnv(i)}compileAsync(t,r){if("function"!=typeof this.opts.loadSchema)throw Error("options.loadSchema should be a function");let{loadSchema:i}=this.opts;return s.call(this,t,r);async function s(t,r){await a.call(this,t.$schema);let i=this._addSchema(t,r);return i.validate||o.call(this,i)}async function a(t){t&&!this.getSchema(t)&&await s.call(this,{$ref:t},!0)}async function o(t){try{return this._compileSchemaEnv(t)}catch(r){if(!(r instanceof n.default))throw r;return l.call(this,r),await p.call(this,r.missingSchema),o.call(this,t)}}function l({missingSchema:t,missingRef:r}){if(this.refs[t])throw Error(`AnySchema ${t} is loaded but ${r} cannot be resolved`)}async function p(t){let i=await u.call(this,t);this.refs[t]||await a.call(this,i.$schema),this.refs[t]||this.addSchema(i,t,r)}async function u(t){let r=this._loading[t];if(r)return r;try{return await (this._loading[t]=i(t))}finally{delete this._loading[t]}}}addSchema(t,r,i,s=this.opts.validateSchema){let n;if(Array.isArray(t)){for(let r of t)this.addSchema(r,void 0,i,s);return this}if("object"==typeof t){let{schemaId:r}=this.opts;if(void 0!==(n=t[r])&&"string"!=typeof n)throw Error(`schema ${r} must be string`)}return r=(0,p.normalizeId)(r||n),this._checkUnique(r),this.schemas[r]=this._addSchema(t,i,r,s,!0),this}addMetaSchema(t,r,i=this.opts.validateSchema){return this.addSchema(t,r,!0,i),this}validateSchema(t,r){let i;if("boolean"==typeof t)return!0;if(void 0!==(i=t.$schema)&&"string"!=typeof i)throw Error("$schema must be a string");if(!(i=i||this.opts.defaultMeta||this.defaultMeta()))return this.logger.warn("meta-schema not available"),this.errors=null,!0;let s=this.validate(i,t);if(!s&&r){let t="schema is invalid: "+this.errorsText();if("log"===this.opts.validateSchema)this.logger.error(t);else throw Error(t)}return s}getSchema(t){let r;for(;"string"==typeof(r=T.call(this,t));)t=r;if(void 0===r){let{schemaId:i}=this.opts,s=new o.SchemaEnv({schema:{},schemaId:i});if(!(r=o.resolveSchema.call(this,s,t)))return;this.refs[t]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(t){if(t instanceof RegExp)return this._removeAllSchemas(this.schemas,t),this._removeAllSchemas(this.refs,t),this;switch(typeof t){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=T.call(this,t);return"object"==typeof r&&this._cache.delete(r.schema),delete this.schemas[t],delete this.refs[t],this}case"object":{this._cache.delete(t);let r=t[this.opts.schemaId];return r&&(r=(0,p.normalizeId)(r),delete this.schemas[r],delete this.refs[r]),this}default:throw Error("ajv.removeSchema: invalid parameter")}}addVocabulary(t){for(let r of t)this.addKeyword(r);return this}addKeyword(t,r){let i;if("string"==typeof t)i=t,"object"==typeof r&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=i);else if("object"==typeof t&&void 0===r){if(Array.isArray(i=(r=t).keyword)&&!i.length)throw Error("addKeywords: keyword must be string or non-empty array")}else throw Error("invalid addKeywords parameters");if(C.call(this,i,r),!r)return(0,c.eachItem)(i,t=>I.call(this,t)),this;N.call(this,r);let s={...r,type:(0,u.getJSONTypes)(r.type),schemaType:(0,u.getJSONTypes)(r.schemaType)};return(0,c.eachItem)(i,0===s.type.length?t=>I.call(this,t,s):t=>s.type.forEach(r=>I.call(this,t,s,r))),this}getKeyword(t){let r=this.RULES.all[t];return"object"==typeof r?r.definition:!!r}removeKeyword(t){let{RULES:r}=this;for(let i of(delete r.keywords[t],delete r.all[t],r.rules)){let r=i.rules.findIndex(r=>r.keyword===t);r>=0&&i.rules.splice(r,1)}return this}addFormat(t,r){return"string"==typeof r&&(r=new RegExp(r)),this.formats[t]=r,this}errorsText(t=this.errors,{separator:r=", ",dataVar:i="data"}={}){return t&&0!==t.length?t.map(t=>`${i}${t.instancePath} ${t.message}`).reduce((t,i)=>t+r+i):"No errors"}$dataMetaSchema(t,r){let i=this.RULES.all;for(let s of(t=JSON.parse(JSON.stringify(t)),r)){let r=s.split("/").slice(1),n=t;for(let t of r)n=n[t];for(let t in i){let r=i[t];if("object"!=typeof r)continue;let{$data:s}=r.definition,a=n[t];s&&a&&(n[t]=D(a))}}return t}_removeAllSchemas(t,r){for(let i in t){let s=t[i];(!r||r.test(i))&&("string"==typeof s?delete t[i]:s&&!s.meta&&(this._cache.delete(s.schema),delete t[i]))}}_addSchema(t,r,i,s=this.opts.validateSchema,n=this.opts.addUsedSchema){let a,{schemaId:l}=this.opts;if("object"==typeof t)a=t[l];else if(this.opts.jtd)throw Error("schema must be object");else if("boolean"!=typeof t)throw Error("schema must be object or boolean");let u=this._cache.get(t);if(void 0!==u)return u;i=(0,p.normalizeId)(a||i);let c=p.getSchemaRefs.call(this,t,i);return u=new o.SchemaEnv({schema:t,schemaId:l,meta:r,baseId:i,localRefs:c}),this._cache.set(u.schema,u),n&&!i.startsWith("#")&&(i&&this._checkUnique(i),this.refs[i]=u),s&&this.validateSchema(t,!0),u}_checkUnique(t){if(this.schemas[t]||this.refs[t])throw Error(`schema with key or id "${t}" already exists`)}_compileSchemaEnv(t){if(t.meta?this._compileMetaSchema(t):o.compileSchema.call(this,t),!t.validate)throw Error("ajv implementation error");return t.validate}_compileMetaSchema(t){let r=this.opts;this.opts=this._metaOpts;try{o.compileSchema.call(this,t)}finally{this.opts=r}}}function x(t,r,i,s="error"){for(let n in t)n in r&&this.logger[s](`${i}: option ${n}. ${t[n]}`)}function T(t){return t=(0,p.normalizeId)(t),this.schemas[t]||this.refs[t]}function E(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let r in t)this.addSchema(t[r],r)}function S(){for(let t in this.opts.formats){let r=this.opts.formats[t];r&&this.addFormat(t,r)}}function _(t){if(Array.isArray(t))return void this.addVocabulary(t);for(let r in this.logger.warn("keywords option as map is deprecated, pass array"),t){let i=t[r];i.keyword||(i.keyword=r),this.addKeyword(i)}}function P(){let t={...this.opts};for(let r of m)delete t[r];return t}v.ValidationError=s.default,v.MissingRefError=n.default,t.default=v;var A={log(){},warn(){},error(){}},w=/^[a-z_$][a-z0-9_$:-]*$/i;function C(t,r){let{RULES:i}=this;if((0,c.eachItem)(t,t=>{if(i.keywords[t])throw Error(`Keyword ${t} is already defined`);if(!w.test(t))throw Error(`Keyword ${t} has invalid name`)}),r&&r.$data&&!("code"in r||"validate"in r))throw Error('$data keyword must have "code" or "validate" function')}function I(t,r,i){var s;let n=null==r?void 0:r.post;if(i&&n)throw Error('keyword with "post" flag cannot have "type"');let{RULES:a}=this,o=n?a.post:a.rules.find(({type:t})=>t===i);if(o||(o={type:i,rules:[]},a.rules.push(o)),a.keywords[t]=!0,!r)return;let l={keyword:t,definition:{...r,type:(0,u.getJSONTypes)(r.type),schemaType:(0,u.getJSONTypes)(r.schemaType)}};r.before?k.call(this,o,l,r.before):o.rules.push(l),a.all[t]=l,null==(s=r.implements)||s.forEach(t=>this.addKeyword(t))}function k(t,r,i){let s=t.rules.findIndex(t=>t.keyword===i);s>=0?t.rules.splice(s,0,r):(t.rules.push(r),this.logger.warn(`rule ${i} is not defined`))}function N(t){let{metaSchema:r}=t;void 0!==r&&(t.$data&&this.opts.$data&&(r=D(r)),t.validateSchema=this.compile(r,!0))}var O={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function D(t){return{anyOf:[t,O]}}}),rK=ro(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default={keyword:"id",code(){throw Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}}}),rq=ro(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.callRef=t.getValidate=void 0;var r=rj(),i=rA(),s=rb(),n=rv(),a=rL(),o=rg();function l(t,r){let{gen:i}=t;return r.validate?i.scopeValue("validate",{ref:r.validate}):s._`${i.scopeValue("wrapper",{ref:r})}.validate`}function p(t,r,a,l){let{gen:p,it:u}=t,{allErrors:c,schemaEnv:d,opts:h}=u,f=h.passContext?n.default.this:s.nil;function m(t){let r=s._`${t}.errors`;p.assign(n.default.vErrors,s._`${n.default.vErrors} === null ? ${r} : ${n.default.vErrors}.concat(${r})`),p.assign(n.default.errors,s._`${n.default.vErrors}.length`)}function y(t){var r;if(!u.opts.unevaluated)return;let i=null==(r=null==a?void 0:a.validate)?void 0:r.evaluated;if(!0!==u.props)if(i&&!i.dynamicProps)void 0!==i.props&&(u.props=o.mergeEvaluated.props(p,i.props,u.props));else{let r=p.var("props",s._`${t}.evaluated.props`);u.props=o.mergeEvaluated.props(p,r,u.props,s.Name)}if(!0!==u.items)if(i&&!i.dynamicItems)void 0!==i.items&&(u.items=o.mergeEvaluated.items(p,i.items,u.items));else{let r=p.var("items",s._`${t}.evaluated.items`);u.items=o.mergeEvaluated.items(p,r,u.items,s.Name)}}l?function(){if(!d.$async)throw Error("async schema referenced by sync schema");let n=p.let("valid");p.try(()=>{p.code(s._`await ${(0,i.callValidateCode)(t,r,f)}`),y(r),c||p.assign(n,!0)},t=>{p.if(s._`!(${t} instanceof ${u.ValidationError})`,()=>p.throw(t)),m(t),c||p.assign(n,!1)}),t.ok(n)}():t.result((0,i.callValidateCode)(t,r,f),()=>y(r),()=>m(r))}t.getValidate=l,t.callRef=p,t.default={keyword:"$ref",schemaType:"string",code(t){var i,n;let o,u,c,d,{gen:h,schema:f,it:m}=t,{baseId:y,schemaEnv:b,validateName:g,opts:v,self:x}=m,{root:T}=b;if(("#"===f||"#/"===f)&&y===T.baseId){if(b===T)return p(t,g,b,b.$async);let r=h.scopeValue("root",{ref:T});return p(t,s._`${r}.validate`,T,T.$async)}let E=a.resolveRef.call(x,T,y,f);if(void 0===E)throw new r.default(m.opts.uriResolver,y,f);return E instanceof a.SchemaEnv?(o=l(t,i=E),void p(t,o,i,i.$async)):(n=E,u=h.scopeValue("schema",!0===v.code.source?{ref:n,code:(0,s.stringify)(n)}:{ref:n}),c=h.name("valid"),d=t.subschema({schema:n,dataTypes:[],schemaPath:s.nil,topSchemaRef:u,errSchemaPath:f},c),void(t.mergeEvaluated(d),t.ok(c)))}}}),rz=ro(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=rK(),i=rq();t.default=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",r.default,i.default]}),rW=ro(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=rb(),i=r.operators,s={maximum:{okStr:"<=",ok:i.LTE,fail:i.GT},minimum:{okStr:">=",ok:i.GTE,fail:i.LT},exclusiveMaximum:{okStr:"<",ok:i.LT,fail:i.GTE},exclusiveMinimum:{okStr:">",ok:i.GT,fail:i.LTE}};t.default={keyword:Object.keys(s),type:"number",schemaType:"number",$data:!0,error:{message:({keyword:t,schemaCode:i})=>r.str`must be ${s[t].okStr} ${i}`,params:({keyword:t,schemaCode:i})=>r._`{comparison: ${s[t].okStr}, limit: ${i}}`},code(t){let{keyword:i,data:n,schemaCode:a}=t;t.fail$data(r._`${n} ${s[i].fail} ${a} || isNaN(${n})`)}}}),rH=ro(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=rb();t.default={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:{message:({schemaCode:t})=>r.str`must be multiple of ${t}`,params:({schemaCode:t})=>r._`{multipleOf: ${t}}`},code(t){let{gen:i,data:s,schemaCode:n,it:a}=t,o=a.opts.multipleOfPrecision,l=i.let("res"),p=o?r._`Math.abs(Math.round(${l}) - ${l}) > 1e-${o}`:r._`${l} !== parseInt(${l})`;t.fail$data(r._`(${n} === 0 || (${l} = ${s}/${n}, ${p}))`)}}}),rJ=ro(t=>{function r(t){let r=t.length,i=0,s=0,n;for(;s<r;)i++,(n=t.charCodeAt(s++))>=55296&&n<=56319&&s<r&&(64512&(n=t.charCodeAt(s)))==56320&&s++;return i}Object.defineProperty(t,"__esModule",{value:!0}),t.default=r,r.code='require("ajv/dist/runtime/ucs2length").default'}),rY=ro(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=rb(),i=rg(),s=rJ();t.default={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:{message:({keyword:t,schemaCode:i})=>r.str`must NOT have ${"maxLength"===t?"more":"fewer"} than ${i} characters`,params:({schemaCode:t})=>r._`{limit: ${t}}`},code(t){let{keyword:n,data:a,schemaCode:o,it:l}=t,p="maxLength"===n?r.operators.GT:r.operators.LT,u=!1===l.opts.unicode?r._`${a}.length`:r._`${(0,i.useFunc)(t.gen,s.default)}(${a})`;t.fail$data(r._`${u} ${p} ${o}`)}}}),rX=ro(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=rA(),i=rb();t.default={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:{message:({schemaCode:t})=>i.str`must match pattern "${t}"`,params:({schemaCode:t})=>i._`{pattern: ${t}}`},code(t){let{data:s,$data:n,schema:a,schemaCode:o,it:l}=t,p=l.opts.unicodeRegExp?"u":"",u=n?i._`(new RegExp(${o}, ${p}))`:(0,r.usePattern)(t,a);t.fail$data(i._`!${u}.test(${s})`)}}}),rG=ro(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=rb();t.default={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:{message:({keyword:t,schemaCode:i})=>r.str`must NOT have ${"maxProperties"===t?"more":"fewer"} than ${i} properties`,params:({schemaCode:t})=>r._`{limit: ${t}}`},code(t){let{keyword:i,data:s,schemaCode:n}=t,a="maxProperties"===i?r.operators.GT:r.operators.LT;t.fail$data(r._`Object.keys(${s}).length ${a} ${n}`)}}}),rZ=ro(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=rA(),i=rb(),s=rg();t.default={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:({params:{missingProperty:t}})=>i.str`must have required property '${t}'`,params:({params:{missingProperty:t}})=>i._`{missingProperty: ${t}}`},code(t){let{gen:n,schema:a,schemaCode:o,data:l,$data:p,it:u}=t,{opts:c}=u;if(!p&&0===a.length)return;let d=a.length>=c.loopRequired;if(u.allErrors?function(){if(d||p)t.block$data(i.nil,h);else for(let i of a)(0,r.checkReportMissingProp)(t,i)}():function(){let s=n.let("missing");if(d||p){let a=n.let("valid",!0);t.block$data(a,()=>{var p,u;return p=s,u=a,void(t.setParams({missingProperty:p}),n.forOf(p,o,()=>{n.assign(u,(0,r.propertyInData)(n,l,p,c.ownProperties)),n.if((0,i.not)(u),()=>{t.error(),n.break()})},i.nil))}),t.ok(a)}else n.if((0,r.checkMissingProp)(t,a,s)),(0,r.reportMissingProp)(t,s),n.else()}(),c.strictRequired){let r=t.parentSchema.properties,{definedProperties:i}=t.it;for(let t of a)if((null==r?void 0:r[t])===void 0&&!i.has(t)){let r=u.schemaEnv.baseId+u.errSchemaPath,i=`required property "${t}" is not defined at "${r}" (strictRequired)`;(0,s.checkStrictMode)(u,i,u.opts.strictRequired)}}function h(){n.forOf("prop",o,i=>{t.setParams({missingProperty:i}),n.if((0,r.noPropertyInData)(n,l,i,c.ownProperties),()=>t.error())})}}}}),rQ=ro(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=rb();t.default={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:{message:({keyword:t,schemaCode:i})=>r.str`must NOT have ${"maxItems"===t?"more":"fewer"} than ${i} items`,params:({schemaCode:t})=>r._`{limit: ${t}}`},code(t){let{keyword:i,data:s,schemaCode:n}=t,a="maxItems"===i?r.operators.GT:r.operators.LT;t.fail$data(r._`${s}.length ${a} ${n}`)}}}),r0=ro(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=rI();r.code='require("ajv/dist/runtime/equal").default',t.default=r}),r1=ro(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=r_(),i=rb(),s=rg(),n=r0();t.default={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:{message:({params:{i:t,j:r}})=>i.str`must NOT have duplicate items (items ## ${r} and ${t} are identical)`,params:({params:{i:t,j:r}})=>i._`{i: ${t}, j: ${r}}`},code(t){let{gen:a,data:o,$data:l,schema:p,parentSchema:u,schemaCode:c,it:d}=t;if(!l&&!p)return;let h=a.let("valid"),f=u.items?(0,r.getSchemaTypes)(u.items):[];t.block$data(h,function(){let l=a.let("i",i._`${o}.length`),p=a.let("j");t.setParams({i:l,j:p}),a.assign(h,!0),a.if(i._`${l} > 1`,()=>(f.length>0&&!f.some(t=>"object"===t||"array"===t)?function(s,n){let l=a.name("item"),p=(0,r.checkDataTypes)(f,l,d.opts.strictNumbers,r.DataType.Wrong),u=a.const("indices",i._`{}`);a.for(i._`;${s}--;`,()=>{a.let(l,i._`${o}[${s}]`),a.if(p,i._`continue`),f.length>1&&a.if(i._`typeof ${l} == "string"`,i._`${l} += "_"`),a.if(i._`typeof ${u}[${l}] == "number"`,()=>{a.assign(n,i._`${u}[${l}]`),t.error(),a.assign(h,!1).break()}).code(i._`${u}[${l}] = ${s}`)})}:function(r,l){let p=(0,s.useFunc)(a,n.default),u=a.name("outer");a.label(u).for(i._`;${r}--;`,()=>a.for(i._`${l} = ${r}; ${l}--;`,()=>a.if(i._`${p}(${o}[${r}], ${o}[${l}])`,()=>{t.error(),a.assign(h,!1).break(u)})))})(l,p))},i._`${c} === false`),t.ok(h)}}}),r2=ro(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=rb(),i=rg(),s=r0();t.default={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:({schemaCode:t})=>r._`{allowedValue: ${t}}`},code(t){let{gen:n,data:a,$data:o,schemaCode:l,schema:p}=t;o||p&&"object"==typeof p?t.fail$data(r._`!${(0,i.useFunc)(n,s.default)}(${a}, ${l})`):t.fail(r._`${p} !== ${a}`)}}}),r4=ro(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=rb(),i=rg(),s=r0();t.default={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode:t})=>r._`{allowedValues: ${t}}`},code(t){let{gen:n,data:a,$data:o,schema:l,schemaCode:p,it:u}=t;if(!o&&0===l.length)throw Error("enum must have non-empty array");let c=l.length>=u.opts.loopEnum,d,h=()=>null!=d?d:d=(0,i.useFunc)(n,s.default),f;if(c||o)f=n.let("valid"),t.block$data(f,function(){n.assign(f,!1),n.forOf("v",p,t=>n.if(r._`${h()}(${a}, ${t})`,()=>n.assign(f,!0).break()))});else{if(!Array.isArray(l))throw Error("ajv implementation error");let t=n.const("vSchema",p);f=(0,r.or)(...l.map((i,s)=>{var n,o;let p;return n=t,"object"==typeof(p=l[o=s])&&null!==p?r._`${h()}(${a}, ${n}[${o}])`:r._`${a} === ${p}`}))}t.pass(f)}}}),r3=ro(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=rW(),i=rH(),s=rY(),n=rX(),a=rG(),o=rZ(),l=rQ(),p=r1(),u=r2(),c=r4();t.default=[r.default,i.default,s.default,n.default,a.default,o.default,l.default,p.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},u.default,c.default]}),r8=ro(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validateAdditionalItems=void 0;var r=rb(),i=rg();function s(t,s){let{gen:n,schema:a,data:o,keyword:l,it:p}=t;p.items=!0;let u=n.const("len",r._`${o}.length`);if(!1===a)t.setParams({len:s.length}),t.pass(r._`${u} <= ${s.length}`);else if("object"==typeof a&&!(0,i.alwaysValidSchema)(p,a)){let a=n.var("valid",r._`${u} <= ${s.length}`);n.if((0,r.not)(a),()=>{var o;return o=a,void n.forRange("i",s.length,u,s=>{t.subschema({keyword:l,dataProp:s,dataPropType:i.Type.Num},o),p.allErrors||n.if((0,r.not)(o),()=>n.break())})}),t.ok(a)}}t.validateAdditionalItems=s,t.default={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:{message:({params:{len:t}})=>r.str`must NOT have more than ${t} items`,params:({params:{len:t}})=>r._`{limit: ${t}}`},code(t){let{parentSchema:r,it:n}=t,{items:a}=r;Array.isArray(a)?s(t,a):(0,i.checkStrictMode)(n,'"additionalItems" is ignored when "items" is not an array of schemas')}}}),r7=ro(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validateTuple=void 0;var r=rb(),i=rg(),s=rA();function n(t,s,a=t.schema){let{gen:o,parentSchema:l,data:p,keyword:u,it:c}=t;(function(t){let{opts:r,errSchemaPath:n}=c,o=a.length,l=o===t.minItems&&(o===t.maxItems||!1===t[s]);if(r.strictTuples&&!l){let t=`"${u}" is ${o}-tuple, but minItems or maxItems/${s} are not specified or different at path "${n}"`;(0,i.checkStrictMode)(c,t,r.strictTuples)}})(l),c.opts.unevaluated&&a.length&&!0!==c.items&&(c.items=i.mergeEvaluated.items(o,a.length,c.items));let d=o.name("valid"),h=o.const("len",r._`${p}.length`);a.forEach((s,n)=>{(0,i.alwaysValidSchema)(c,s)||(o.if(r._`${h} > ${n}`,()=>t.subschema({keyword:u,schemaProp:n,dataProp:n},d)),t.ok(d))})}t.validateTuple=n,t.default={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:r,it:a}=t;if(Array.isArray(r))return n(t,"additionalItems",r);a.items=!0,(0,i.alwaysValidSchema)(a,r)||t.ok((0,s.validateArray)(t))}}}),r9=ro(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=r7();t.default={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,r.validateTuple)(t,"items")}}),r5=ro(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=rb(),i=rg(),s=rA(),n=r8();t.default={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:({params:{len:t}})=>r.str`must NOT have more than ${t} items`,params:({params:{len:t}})=>r._`{limit: ${t}}`},code(t){let{schema:r,parentSchema:a,it:o}=t,{prefixItems:l}=a;o.items=!0,(0,i.alwaysValidSchema)(o,r)||(l?(0,n.validateAdditionalItems)(t,l):t.ok((0,s.validateArray)(t)))}}}),r6=ro(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=rb(),i=rg();t.default={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:{message:({params:{min:t,max:i}})=>void 0===i?r.str`must contain at least ${t} valid item(s)`:r.str`must contain at least ${t} and no more than ${i} valid item(s)`,params:({params:{min:t,max:i}})=>void 0===i?r._`{minContains: ${t}}`:r._`{minContains: ${t}, maxContains: ${i}}`},code(t){let{gen:s,schema:n,parentSchema:a,data:o,it:l}=t,p,u,{minContains:c,maxContains:d}=a;l.opts.next?(p=void 0===c?1:c,u=d):p=1;let h=s.const("len",r._`${o}.length`);if(t.setParams({min:p,max:u}),void 0===u&&0===p)return void(0,i.checkStrictMode)(l,'"minContains" == 0 without "maxContains": "contains" keyword ignored');if(void 0!==u&&p>u){(0,i.checkStrictMode)(l,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,i.alwaysValidSchema)(l,n)){let i=r._`${h} >= ${p}`;void 0!==u&&(i=r._`${i} && ${h} <= ${u}`),t.pass(i);return}l.items=!0;let f=s.name("valid");function m(){let t=s.name("_valid"),i=s.let("count",0);y(t,()=>s.if(t,()=>{var t;return t=i,void((s.code(r._`${t}++`),void 0===u)?s.if(r._`${t} >= ${p}`,()=>s.assign(f,!0).break()):(s.if(r._`${t} > ${u}`,()=>s.assign(f,!1).break()),1===p)?s.assign(f,!0):s.if(r._`${t} >= ${p}`,()=>s.assign(f,!0)))}))}function y(r,n){s.forRange("i",0,h,s=>{t.subschema({keyword:"contains",dataProp:s,dataPropType:i.Type.Num,compositeRule:!0},r),n()})}void 0===u&&1===p?y(f,()=>s.if(f,()=>s.break())):0===p?(s.let(f,!0),void 0!==u&&s.if(r._`${o}.length > 0`,m)):(s.let(f,!1),m()),t.result(f,()=>t.reset())}}}),ie=ro(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validateSchemaDeps=t.validatePropertyDeps=t.error=void 0;var r=rb(),i=rg(),s=rA();t.error={message:({params:{property:t,depsCount:i,deps:s}})=>r.str`must have ${1===i?"property":"properties"} ${s} when property ${t} is present`,params:({params:{property:t,depsCount:i,deps:s,missingProperty:n}})=>r._`{property: ${t},
|
|
357
|
+
|| ${l} === "boolean" || ${n} === null`).assign(p,o._`[${n}]`)}}(t);s.else(),f(t),s.endIf(),s.if(o._`${p} !== undefined`,()=>{s.assign(n,p),function({gen:t,parentData:r,parentDataProperty:i},s){t.if(o._`${r} !== undefined`,()=>t.assign(o._`${r}[${i}]`,s))}(t,p)})}(t,r,h):f(t)})}return m};var u=new Set(["string","number","integer","boolean","null"]);function c(t,r,s,n=i.Correct){let a=n===i.Correct?o.operators.EQ:o.operators.NEQ,l;switch(t){case"null":return o._`${r} ${a} null`;case"array":l=o._`Array.isArray(${r})`;break;case"object":l=o._`${r} && typeof ${r} == "object" && !Array.isArray(${r})`;break;case"integer":l=p(o._`!(${r} % 1) && !isNaN(${r})`);break;case"number":l=p();break;default:return o._`typeof ${r} ${a} ${t}`}return n===i.Correct?l:(0,o.not)(l);function p(t=o.nil){return(0,o.and)(o._`typeof ${r} == "number"`,t,s?o._`isFinite(${r})`:o.nil)}}function d(t,r,i,s){if(1===t.length)return c(t[0],r,i,s);let n,a=(0,l.toHash)(t);if(a.array&&a.object){let t=o._`typeof ${r} != "object"`;n=a.null?t:o._`!${r} || ${t}`,delete a.null,delete a.array,delete a.object}else n=o.nil;for(let t in a.number&&delete a.integer,a)n=(0,o.and)(n,c(t,r,i,s));return n}t.checkDataType=c,t.checkDataTypes=d;var h={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:r})=>"string"==typeof t?o._`{type: ${t}}`:o._`{type: ${r}}`};function f(t){let r=function(t){let{gen:r,data:i,schema:s}=t,n=(0,l.schemaRefOrVal)(t,s,"type");return{gen:r,keyword:"type",data:i,schema:s.type,schemaCode:n,schemaValue:n,parentSchema:s,params:{},it:t}}(t);(0,a.reportError)(r,h)}t.reportTypeError=f}),rA=rl(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.assignDefaults=void 0;var r=rg(),i=rv();function s(t,s,n){let{gen:a,compositeRule:o,data:l,opts:p}=t;if(void 0===n)return;let u=r._`${l}${(0,r.getProperty)(s)}`;if(o)return void(0,i.checkStrictMode)(t,`default is ignored for: ${u}`);let c=r._`${u} === undefined`;"empty"===p.useDefaults&&(c=r._`${c} || ${u} === null || ${u} === ""`),a.if(c,r._`${u} = ${(0,r.stringify)(n)}`)}t.assignDefaults=function(t,r){let{properties:i,items:n}=t.schema;if("object"===r&&i)for(let r in i)s(t,r,i[r].default);else"array"===r&&Array.isArray(n)&&n.forEach((r,i)=>s(t,i,r.default))}}),rw=rl(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validateUnion=t.validateArray=t.usePattern=t.callValidateCode=t.schemaProperties=t.allSchemaProperties=t.noPropertyInData=t.propertyInData=t.isOwnProperty=t.hasPropFunc=t.reportMissingProp=t.checkMissingProp=t.checkReportMissingProp=void 0;var r=rg(),i=rv(),s=rx(),n=rv();function a(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:r._`Object.prototype.hasOwnProperty`})}function o(t,i,s){return r._`${a(t)}.call(${i}, ${s})`}function l(t,i,s,n){let a=r._`${i}${(0,r.getProperty)(s)} === undefined`;return n?(0,r.or)(a,(0,r.not)(o(t,i,s))):a}function p(t){return t?Object.keys(t).filter(t=>"__proto__"!==t):[]}t.checkReportMissingProp=function(t,i){let{gen:s,data:n,it:a}=t;s.if(l(s,n,i,a.opts.ownProperties),()=>{t.setParams({missingProperty:r._`${i}`},!0),t.error()})},t.checkMissingProp=function({gen:t,data:i,it:{opts:s}},n,a){return(0,r.or)(...n.map(n=>(0,r.and)(l(t,i,n,s.ownProperties),r._`${a} = ${n}`)))},t.reportMissingProp=function(t,r){t.setParams({missingProperty:r},!0),t.error()},t.hasPropFunc=a,t.isOwnProperty=o,t.propertyInData=function(t,i,s,n){let a=r._`${i}${(0,r.getProperty)(s)} !== undefined`;return n?r._`${a} && ${o(t,i,s)}`:a},t.noPropertyInData=l,t.allSchemaProperties=p,t.schemaProperties=function(t,r){return p(r).filter(s=>!(0,i.alwaysValidSchema)(t,r[s]))},t.callValidateCode=function({schemaCode:t,data:i,it:{gen:n,topSchemaRef:a,schemaPath:o,errorPath:l},it:p},u,c,d){let h=d?r._`${t}, ${i}, ${a}${o}`:i,f=[[s.default.instancePath,(0,r.strConcat)(s.default.instancePath,l)],[s.default.parentData,p.parentData],[s.default.parentDataProperty,p.parentDataProperty],[s.default.rootData,s.default.rootData]];p.opts.dynamicRef&&f.push([s.default.dynamicAnchors,s.default.dynamicAnchors]);let m=r._`${h}, ${n.object(...f)}`;return c!==r.nil?r._`${u}.call(${c}, ${m})`:r._`${u}(${m})`};var u=r._`new RegExp`;t.usePattern=function({gen:t,it:{opts:i}},s){let a=i.unicodeRegExp?"u":"",{regExp:o}=i.code,l=o(s,a);return t.scopeValue("pattern",{key:l.toString(),ref:l,code:r._`${"new RegExp"===o.code?u:(0,n.useFunc)(t,o)}(${s}, ${a})`})},t.validateArray=function(t){let{gen:s,data:n,keyword:a,it:o}=t,l=s.name("valid");if(o.allErrors){let t=s.let("valid",!0);return p(()=>s.assign(t,!1)),t}return s.var(l,!0),p(()=>s.break()),l;function p(o){let p=s.const("len",r._`${n}.length`);s.forRange("i",0,p,n=>{t.subschema({keyword:a,dataProp:n,dataPropType:i.Type.Num},l),s.if((0,r.not)(l),o)})}},t.validateUnion=function(t){let{gen:s,schema:n,keyword:a,it:o}=t;if(!Array.isArray(n))throw Error("ajv implementation error");if(n.some(t=>(0,i.alwaysValidSchema)(o,t))&&!o.opts.unevaluated)return;let l=s.let("valid",!1),p=s.name("_valid");s.block(()=>n.forEach((i,n)=>{let o=t.subschema({keyword:a,schemaProp:n,compositeRule:!0},p);s.assign(l,r._`${l} || ${p}`),t.mergeValidEvaluated(o,p)||s.if((0,r.not)(l))})),t.result(l,()=>t.reset(),()=>t.error(!0))}}),rC=rl(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validateKeywordUsage=t.validSchemaType=t.funcKeywordCode=t.macroKeywordCode=void 0;var r=rg(),i=rx(),s=rw(),n=rT();function a(t){let{gen:i,data:s,it:n}=t;i.if(n.parentData,()=>i.assign(s,r._`${n.parentData}[${n.parentDataProperty}]`))}function o(t,i,s){if(void 0===s)throw Error(`keyword "${i}" failed to compile`);return t.scopeValue("keyword","function"==typeof s?{ref:s}:{ref:s,code:(0,r.stringify)(s)})}t.macroKeywordCode=function(t,i){let{gen:s,keyword:n,schema:a,parentSchema:l,it:p}=t,u=i.macro.call(p.self,a,l,p),c=o(s,n,u);!1!==p.opts.validateSchema&&p.self.validateSchema(u,!0);let d=s.name("valid");t.subschema({schema:u,schemaPath:r.nil,errSchemaPath:`${p.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},d),t.pass(d,()=>t.error(!0))},t.funcKeywordCode=function(t,l){var p;let{gen:u,keyword:c,schema:d,parentSchema:h,$data:f,it:m}=t;!function({schemaEnv:t},r){if(r.async&&!t.$async)throw Error("async keyword in sync schema")}(m,l);let y=o(u,c,!f&&l.compile?l.compile.call(m.self,d,h,m):l.validate),b=u.let("valid");function g(n=l.async?r._`await `:r.nil){let a=m.opts.passContext?i.default.this:i.default.self,o=!("compile"in l&&!f||!1===l.schema);u.assign(b,r._`${n}${(0,s.callValidateCode)(t,y,a,o)}`,l.modifying)}function v(t){var i;u.if((0,r.not)(null!=(i=l.valid)?i:b),t)}t.block$data(b,function(){if(!1===l.errors)g(),l.modifying&&a(t),v(()=>t.error());else{let s,o,p=l.async?(s=u.let("ruleErrs",null),u.try(()=>g(r._`await `),t=>u.assign(b,!1).if(r._`${t} instanceof ${m.ValidationError}`,()=>u.assign(s,r._`${t}.errors`),()=>u.throw(t))),s):(o=r._`${y}.errors`,u.assign(o,null),g(r.nil),o);l.modifying&&a(t),v(()=>(function(t,s){let{gen:a}=t;a.if(r._`Array.isArray(${s})`,()=>{a.assign(i.default.vErrors,r._`${i.default.vErrors} === null ? ${s} : ${i.default.vErrors}.concat(${s})`).assign(i.default.errors,r._`${i.default.vErrors}.length`),(0,n.extendErrors)(t)},()=>t.error())})(t,p))}}),t.ok(null!=(p=l.valid)?p:b)},t.validSchemaType=function(t,r,i=!1){return!r.length||r.some(r=>"array"===r?Array.isArray(t):"object"===r?t&&"object"==typeof t&&!Array.isArray(t):typeof t==r||i&&typeof t>"u")},t.validateKeywordUsage=function({schema:t,opts:r,self:i,errSchemaPath:s},n,a){if(Array.isArray(n.keyword)?!n.keyword.includes(a):n.keyword!==a)throw Error("ajv implementation error");let o=n.dependencies;if(null==o?void 0:o.some(r=>!Object.prototype.hasOwnProperty.call(t,r)))throw Error(`parent schema must have dependencies of ${a}: ${o.join(",")}`);if(n.validateSchema&&!n.validateSchema(t[a])){let t=`keyword "${a}" value is invalid at path "${s}": `+i.errorsText(n.validateSchema.errors);if("log"===r.validateSchema)i.logger.error(t);else throw Error(t)}}}),rI=rl(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extendSubschemaMode=t.extendSubschemaData=t.getSubschema=void 0;var r=rg(),i=rv();t.getSubschema=function(t,{keyword:s,schemaProp:n,schema:a,schemaPath:o,errSchemaPath:l,topSchemaRef:p}){if(void 0!==s&&void 0!==a)throw Error('both "keyword" and "schema" passed, only one allowed');if(void 0!==s){let a=t.schema[s];return void 0===n?{schema:a,schemaPath:r._`${t.schemaPath}${(0,r.getProperty)(s)}`,errSchemaPath:`${t.errSchemaPath}/${s}`}:{schema:a[n],schemaPath:r._`${t.schemaPath}${(0,r.getProperty)(s)}${(0,r.getProperty)(n)}`,errSchemaPath:`${t.errSchemaPath}/${s}/${(0,i.escapeFragment)(n)}`}}if(void 0!==a){if(void 0===o||void 0===l||void 0===p)throw Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:a,schemaPath:o,topSchemaRef:p,errSchemaPath:l}}throw Error('either "keyword" or "schema" must be passed')},t.extendSubschemaData=function(t,s,{dataProp:n,dataPropType:a,data:o,dataTypes:l,propertyName:p}){if(void 0!==o&&void 0!==n)throw Error('both "data" and "dataProp" passed, only one allowed');let{gen:u}=s;if(void 0!==n){let{errorPath:o,dataPathArr:l,opts:p}=s;c(u.let("data",r._`${s.data}${(0,r.getProperty)(n)}`,!0)),t.errorPath=r.str`${o}${(0,i.getErrorPath)(n,a,p.jsPropertySyntax)}`,t.parentDataProperty=r._`${n}`,t.dataPathArr=[...l,t.parentDataProperty]}function c(r){t.data=r,t.dataLevel=s.dataLevel+1,t.dataTypes=[],s.definedProperties=new Set,t.parentData=s.data,t.dataNames=[...s.dataNames,r]}void 0!==o&&(c(o instanceof r.Name?o:u.let("data",o,!0)),void 0!==p&&(t.propertyName=p)),l&&(t.dataTypes=l)},t.extendSubschemaMode=function(t,{jtdDiscriminator:r,jtdMetadata:i,compositeRule:s,createErrors:n,allErrors:a}){void 0!==s&&(t.compositeRule=s),void 0!==n&&(t.createErrors=n),void 0!==a&&(t.allErrors=a),t.jtdDiscriminator=r,t.jtdMetadata=i}}),rk=rl((t,r)=>{r.exports=function t(r,i){if(r===i)return!0;if(r&&i&&"object"==typeof r&&"object"==typeof i){if(r.constructor!==i.constructor)return!1;if(Array.isArray(r)){if((s=r.length)!=i.length)return!1;for(n=s;0!=n--;)if(!t(r[n],i[n]))return!1;return!0}if(r.constructor===RegExp)return r.source===i.source&&r.flags===i.flags;if(r.valueOf!==Object.prototype.valueOf)return r.valueOf()===i.valueOf();if(r.toString!==Object.prototype.toString)return r.toString()===i.toString();if((s=(a=Object.keys(r)).length)!==Object.keys(i).length)return!1;for(n=s;0!=n--;)if(!Object.prototype.hasOwnProperty.call(i,a[n]))return!1;for(n=s;0!=n--;){var s,n,a,o=a[n];if(!t(r[o],i[o]))return!1}return!0}return r!=r&&i!=i}}),rN=rl((t,r)=>{var i=r.exports=function(t,r,s){"function"==typeof r&&(s=r,r={});var n="function"==typeof(s=r.cb||s)?s:s.pre||function(){};!function t(r,s,n,a,o,l,p,u,c,d){if(a&&"object"==typeof a&&!Array.isArray(a)){for(var h in s(a,o,l,p,u,c,d),a){var f=a[h];if(Array.isArray(f)){if(h in i.arrayKeywords)for(var m=0;m<f.length;m++)t(r,s,n,f[m],o+"/"+h+"/"+m,l,o,h,a,m)}else if(h in i.propsKeywords){if(f&&"object"==typeof f)for(var y in f)t(r,s,n,f[y],o+"/"+h+"/"+y.replace(/~/g,"~0").replace(/\//g,"~1"),l,o,h,a,y)}else(h in i.keywords||r.allKeys&&!(h in i.skipKeywords))&&t(r,s,n,f,o+"/"+h,l,o,h,a)}n(a,o,l,p,u,c,d)}}(r,n,s.post||function(){},t,"",t)};i.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},i.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},i.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},i.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0}}),rO=rl(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getSchemaRefs=t.resolveUrl=t.normalizeId=t._getFullPath=t.getFullPath=t.inlineRef=void 0;var r=rv(),i=rk(),s=rN(),n=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);t.inlineRef=function(t,i=!0){return"boolean"==typeof t||(!0===i?!function t(r){for(let i in r){if(a.has(i))return!0;let s=r[i];if(Array.isArray(s)&&s.some(t)||"object"==typeof s&&t(s))return!0}return!1}(t):!!i&&function t(i){let s=0;for(let a in i)if("$ref"===a||(s++,!n.has(a)&&("object"==typeof i[a]&&(0,r.eachItem)(i[a],r=>s+=t(r)),s===1/0)))return 1/0;return s}(t)<=i)};var a=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function o(t,r="",i){!1!==i&&(r=u(r));let s=t.parse(r);return l(t,s)}function l(t,r){return t.serialize(r).split("#")[0]+"#"}t.getFullPath=o,t._getFullPath=l;var p=/#\/?$/;function u(t){return t?t.replace(p,""):""}t.normalizeId=u,t.resolveUrl=function(t,r,i){return i=u(i),t.resolve(r,i)};var c=/^[a-z_][-a-z0-9._]*$/i;t.getSchemaRefs=function(t,r){if("boolean"==typeof t)return{};let{schemaId:n,uriResolver:a}=this.opts,l=u(t[n]||r),p={"":l},d=o(a,l,!1),h={},f=new Set;return s(t,{allKeys:!0},(t,r,i,s)=>{if(void 0===s)return;let a=d+r,o=p[s];function l(r){let i=this.opts.uriResolver.resolve;if(r=u(o?i(o,r):r),f.has(r))throw y(r);f.add(r);let s=this.refs[r];return"string"==typeof s&&(s=this.refs[s]),"object"==typeof s?m(t,s.schema,r):r!==u(a)&&("#"===r[0]?(m(t,h[r],r),h[r]=t):this.refs[r]=a),r}function b(t){if("string"==typeof t){if(!c.test(t))throw Error(`invalid anchor "${t}"`);l.call(this,`#${t}`)}}"string"==typeof t[n]&&(o=l.call(this,t[n])),b.call(this,t.$anchor),b.call(this,t.$dynamicAnchor),p[r]=o}),h;function m(t,r,s){if(void 0!==r&&!i(t,r))throw y(s)}function y(t){return Error(`reference "${t}" resolves to more than one schema`)}}}),rD=rl(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getData=t.KeywordCxt=t.validateFunctionCode=void 0;var r=rE(),i=rP(),s=r_(),n=rP(),a=rA(),o=rC(),l=rI(),p=rg(),u=rx(),c=rO(),d=rv(),h=rT();function f({gen:t,validateName:r,schema:i,schemaEnv:s,opts:n},a){var o;n.code.es5?t.func(r,p._`${u.default.data}, ${u.default.valCxt}`,s.$async,()=>{var r,s;t.code(p._`"use strict"; ${m(i,n)}`),r=t,s=n,r.if(u.default.valCxt,()=>{r.var(u.default.instancePath,p._`${u.default.valCxt}.${u.default.instancePath}`),r.var(u.default.parentData,p._`${u.default.valCxt}.${u.default.parentData}`),r.var(u.default.parentDataProperty,p._`${u.default.valCxt}.${u.default.parentDataProperty}`),r.var(u.default.rootData,p._`${u.default.valCxt}.${u.default.rootData}`),s.dynamicRef&&r.var(u.default.dynamicAnchors,p._`${u.default.valCxt}.${u.default.dynamicAnchors}`)},()=>{r.var(u.default.instancePath,p._`""`),r.var(u.default.parentData,p._`undefined`),r.var(u.default.parentDataProperty,p._`undefined`),r.var(u.default.rootData,u.default.data),s.dynamicRef&&r.var(u.default.dynamicAnchors,p._`{}`)}),t.code(a)}):t.func(r,p._`${u.default.data}, ${(o=n,p._`{${u.default.instancePath}="", ${u.default.parentData}, ${u.default.parentDataProperty}, ${u.default.rootData}=${u.default.data}${o.dynamicRef?p._`, ${u.default.dynamicAnchors}={}`:p.nil}}={}`)}`,s.$async,()=>t.code(m(i,n)).code(a))}function m(t,r){let i="object"==typeof t&&t[r.schemaId];return i&&(r.code.source||r.code.process)?p._`/*# sourceURL=${i} */`:p.nil}function y({schema:t,self:r}){if("boolean"==typeof t)return!t;for(let i in t)if(r.RULES.all[i])return!0;return!1}function b(t){return"boolean"!=typeof t.schema}function g(t){(0,d.checkUnknownRules)(t),function(t){let{schema:r,errSchemaPath:i,opts:s,self:n}=t;r.$ref&&s.ignoreKeywordsWithRef&&(0,d.schemaHasRulesButRef)(r,n.RULES)&&n.logger.warn(`$ref: keywords ignored in schema at path "${i}"`)}(t)}function v(t,r){if(t.opts.jtd)return T(t,[],!1,r);let s=(0,i.getSchemaTypes)(t.schema),n=(0,i.coerceAndCheckDataType)(t,s);T(t,s,!n,r)}function x({gen:t,schemaEnv:r,schema:i,errSchemaPath:s,opts:n}){let a=i.$comment;if(!0===n.$comment)t.code(p._`${u.default.self}.logger.log(${a})`);else if("function"==typeof n.$comment){let i=p.str`${s}/$comment`,n=t.scopeValue("root",{ref:r.root});t.code(p._`${u.default.self}.opts.$comment(${a}, ${i}, ${n}.schema)`)}}function T(t,r,i,a){var o,l,c,h;let{gen:f,schema:m,data:y,allErrors:b,opts:g,self:v}=t,{RULES:x}=v;if(m.$ref&&(g.ignoreKeywordsWithRef||!(0,d.schemaHasRulesButRef)(m,x)))return void f.block(()=>A(t,"$ref",x.all.$ref.definition));function T(o){(0,s.shouldUseGroup)(m,o)&&(o.type?(f.if((0,n.checkDataType)(o.type,y,g.strictNumbers)),E(t,o),1===r.length&&r[0]===o.type&&i&&(f.else(),(0,n.reportTypeError)(t)),f.endIf()):E(t,o),b||f.if(p._`${u.default.errors} === ${a||0}`))}g.jtd||(o=t,l=r,!o.schemaEnv.meta&&o.opts.strictTypes&&(function(t,r){if(r.length){if(!t.dataTypes.length){t.dataTypes=r;return}r.forEach(r=>{S(t.dataTypes,r)||_(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),function(t,r){let i=[];for(let s of t.dataTypes)S(r,s)?i.push(s):r.includes("integer")&&"number"===s&&i.push("integer");t.dataTypes=i}(t,r)}}(o,l),o.opts.allowUnionTypes||(c=o,(h=l).length>1&&!(2===h.length&&h.includes("null"))&&_(c,"use allowUnionTypes to allow union type keyword")),function(t,r){let i=t.self.RULES.all;for(let n in i){let a=i[n];if("object"==typeof a&&(0,s.shouldUseRule)(t.schema,a)){let{type:i}=a.definition;i.length&&!i.some(t=>{var i,s;return i=r,s=t,i.includes(s)||"number"===s&&i.includes("integer")})&&_(t,`missing type "${i.join(",")}" for keyword "${n}"`)}}}(o,o.dataTypes))),f.block(()=>{for(let t of x.rules)T(t);T(x.post)})}function E(t,r){let{gen:i,schema:n,opts:{useDefaults:o}}=t;o&&(0,a.assignDefaults)(t,r.type),i.block(()=>{for(let i of r.rules)(0,s.shouldUseRule)(n,i)&&A(t,i.keyword,i.definition,r.type)})}function S(t,r){return t.includes(r)||"integer"===r&&t.includes("number")}function _(t,r){let i=t.schemaEnv.baseId+t.errSchemaPath;r+=` at "${i}" (strictTypes)`,(0,d.checkStrictMode)(t,r,t.opts.strictTypes)}t.validateFunctionCode=function(t){b(t)&&(g(t),y(t))?function(t){let{schema:r,opts:i,gen:s}=t;f(t,()=>{i.$comment&&r.$comment&&x(t),function(t){let{schema:r,opts:i}=t;void 0!==r.default&&i.useDefaults&&i.strictSchema&&(0,d.checkStrictMode)(t,"default is ignored in the schema root")}(t),s.let(u.default.vErrors,null),s.let(u.default.errors,0),i.unevaluated&&function(t){let{gen:r,validateName:i}=t;t.evaluated=r.const("evaluated",p._`${i}.evaluated`),r.if(p._`${t.evaluated}.dynamicProps`,()=>r.assign(p._`${t.evaluated}.props`,p._`undefined`)),r.if(p._`${t.evaluated}.dynamicItems`,()=>r.assign(p._`${t.evaluated}.items`,p._`undefined`))}(t),v(t),function(t){let{gen:r,schemaEnv:i,validateName:s,ValidationError:n,opts:a}=t;i.$async?r.if(p._`${u.default.errors} === 0`,()=>r.return(u.default.data),()=>r.throw(p._`new ${n}(${u.default.vErrors})`)):(r.assign(p._`${s}.errors`,u.default.vErrors),a.unevaluated&&function({gen:t,evaluated:r,props:i,items:s}){i instanceof p.Name&&t.assign(p._`${r}.props`,i),s instanceof p.Name&&t.assign(p._`${r}.items`,s)}(t),r.return(p._`${u.default.errors} === 0`))}(t)})}(t):f(t,()=>(0,r.topBoolOrEmptySchema)(t))};class P{constructor(t,r,i){if((0,o.validateKeywordUsage)(t,r,i),this.gen=t.gen,this.allErrors=t.allErrors,this.keyword=i,this.data=t.data,this.schema=t.schema[i],this.$data=r.$data&&t.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,d.schemaRefOrVal)(t,this.schema,i,this.$data),this.schemaType=r.schemaType,this.parentSchema=t.schema,this.params={},this.it=t,this.def=r,this.$data)this.schemaCode=t.gen.const("vSchema",I(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0,o.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw Error(`${i} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:!1!==r.errors)&&(this.errsCount=t.gen.const("_errs",u.default.errors))}result(t,r,i){this.failResult((0,p.not)(t),r,i)}failResult(t,r,i){(this.gen.if(t),i)?i():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(t,r){this.failResult((0,p.not)(t),void 0,r)}fail(t){if(void 0===t){this.error(),this.allErrors||this.gen.if(!1);return}(this.gen.if(t),this.error(),this.allErrors)?this.gen.endIf():this.gen.else()}fail$data(t){if(!this.$data)return this.fail(t);let{schemaCode:r}=this;this.fail(p._`${r} !== undefined && (${(0,p.or)(this.invalid$data(),t)})`)}error(t,r,i){if(r){this.setParams(r),this._error(t,i),this.setParams({});return}this._error(t,i)}_error(t,r){(t?h.reportExtraError:h.reportError)(this,this.def.error,r)}$dataError(){(0,h.reportError)(this,this.def.$dataError||h.keyword$DataError)}reset(){if(void 0===this.errsCount)throw Error('add "trackErrors" to keyword definition');(0,h.resetErrorsCount)(this.gen,this.errsCount)}ok(t){this.allErrors||this.gen.if(t)}setParams(t,r){r?Object.assign(this.params,t):this.params=t}block$data(t,r,i=p.nil){this.gen.block(()=>{this.check$data(t,i),r()})}check$data(t=p.nil,r=p.nil){if(!this.$data)return;let{gen:i,schemaCode:s,schemaType:n,def:a}=this;i.if((0,p.or)(p._`${s} === undefined`,r)),t!==p.nil&&i.assign(t,!0),(n.length||a.validateSchema)&&(i.elseIf(this.invalid$data()),this.$dataError(),t!==p.nil)&&i.assign(t,!1),i.else()}invalid$data(){let{gen:t,schemaCode:r,schemaType:i,def:s,it:a}=this;return(0,p.or)(function(){if(i.length){if(!(r instanceof p.Name))throw Error("ajv implementation error");let t=Array.isArray(i)?i:[i];return p._`${(0,n.checkDataTypes)(t,r,a.opts.strictNumbers,n.DataType.Wrong)}`}return p.nil}(),function(){if(s.validateSchema){let i=t.scopeValue("validate$data",{ref:s.validateSchema});return p._`!${i}(${r})`}return p.nil}())}subschema(t,i){let s=(0,l.getSubschema)(this.it,t);(0,l.extendSubschemaData)(s,this.it,t),(0,l.extendSubschemaMode)(s,t);let n={...this.it,...s,items:void 0,props:void 0};return b(n)&&(g(n),y(n))?function(t,r){var i;let s,{schema:n,gen:a,opts:o}=t;o.$comment&&n.$comment&&x(t),(s=(i=t).schema[i.opts.schemaId])&&(i.baseId=(0,c.resolveUrl)(i.opts.uriResolver,i.baseId,s)),function(t){if(t.schema.$async&&!t.schemaEnv.$async)throw Error("async schema in sync schema")}(t);let l=a.const("_errs",u.default.errors);v(t,l),a.var(r,p._`${l} === ${u.default.errors}`)}(n,i):(0,r.boolOrEmptySchema)(n,i),n}mergeEvaluated(t,r){let{it:i,gen:s}=this;i.opts.unevaluated&&(!0!==i.props&&void 0!==t.props&&(i.props=d.mergeEvaluated.props(s,t.props,i.props,r)),!0!==i.items&&void 0!==t.items&&(i.items=d.mergeEvaluated.items(s,t.items,i.items,r)))}mergeValidEvaluated(t,r){let{it:i,gen:s}=this;if(i.opts.unevaluated&&(!0!==i.props||!0!==i.items))return s.if(r,()=>this.mergeEvaluated(t,p.Name)),!0}}function A(t,r,i,s){let n=new P(t,i,r);"code"in i?i.code(n,s):n.$data&&i.validate?(0,o.funcKeywordCode)(n,i):"macro"in i?(0,o.macroKeywordCode)(n,i):(i.compile||i.validate)&&(0,o.funcKeywordCode)(n,i)}t.KeywordCxt=P;var w=/^\/(?:[^~]|~0|~1)*$/,C=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function I(t,{dataLevel:r,dataNames:i,dataPathArr:s}){let n,a;if(""===t)return u.default.rootData;if("/"===t[0]){if(!w.test(t))throw Error(`Invalid JSON-pointer: ${t}`);n=t,a=u.default.rootData}else{let o=C.exec(t);if(!o)throw Error(`Invalid JSON-pointer: ${t}`);let p=+o[1];if("#"===(n=o[2])){if(p>=r)throw Error(l("property/index",p));return s[r-p]}if(p>r)throw Error(l("data",p));if(a=i[r-p],!n)return a}let o=a;for(let t of n.split("/"))t&&(a=p._`${a}${(0,p.getProperty)((0,d.unescapeJsonPointer)(t))}`,o=p._`${o} && ${a}`);return o;function l(t,i){return`Cannot access ${t} ${i} levels up, current level is ${r}`}}t.getData=I}),rj=rl(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=class extends Error{constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}}}),rL=rl(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=rO();t.default=class extends Error{constructor(t,i,s,n){super(n||`can't resolve reference ${s} from id ${i}`),this.missingRef=(0,r.resolveUrl)(t,i,s),this.missingSchema=(0,r.normalizeId)((0,r.getFullPath)(t,this.missingRef))}}}),rR=rl(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.resolveSchema=t.getCompilingSchema=t.resolveRef=t.compileSchema=t.SchemaEnv=void 0;var r=rg(),i=rj(),s=rx(),n=rO(),a=rv(),o=rD();class l{constructor(t){var r;let i;this.refs={},this.dynamicAnchors={},"object"==typeof t.schema&&(i=t.schema),this.schema=t.schema,this.schemaId=t.schemaId,this.root=t.root||this,this.baseId=null!=(r=t.baseId)?r:(0,n.normalizeId)(null==i?void 0:i[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=null==i?void 0:i.$async,this.refs={}}}function p(t){let a=c.call(this,t);if(a)return a;let l=(0,n.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:p,lines:u}=this.opts.code,{ownProperties:d}=this.opts,h=new r.CodeGen(this.scope,{es5:p,lines:u,ownProperties:d}),f;t.$async&&(f=h.scopeValue("Error",{ref:i.default,code:r._`require("ajv/dist/runtime/validation_error").default`}));let m=h.scopeName("validate");t.validateName=m;let y={gen:h,allErrors:this.opts.allErrors,data:s.default.data,parentData:s.default.parentData,parentDataProperty:s.default.parentDataProperty,dataNames:[s.default.data],dataPathArr:[r.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:h.scopeValue("schema",!0===this.opts.code.source?{ref:t.schema,code:(0,r.stringify)(t.schema)}:{ref:t.schema}),validateName:m,ValidationError:f,schema:t.schema,schemaEnv:t,rootId:l,baseId:t.baseId||l,schemaPath:r.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:r._`""`,opts:this.opts,self:this},b;try{this._compilations.add(t),(0,o.validateFunctionCode)(y),h.optimize(this.opts.code.optimize);let i=h.toString();b=`${h.scopeRefs(s.default.scope)}return ${i}`,this.opts.code.process&&(b=this.opts.code.process(b,t));let n=Function(`${s.default.self}`,`${s.default.scope}`,b)(this,this.scope.get());if(this.scope.value(m,{ref:n}),n.errors=null,n.schema=t.schema,n.schemaEnv=t,t.$async&&(n.$async=!0),!0===this.opts.code.source&&(n.source={validateName:m,validateCode:i,scopeValues:h._values}),this.opts.unevaluated){let{props:t,items:i}=y;n.evaluated={props:t instanceof r.Name?void 0:t,items:i instanceof r.Name?void 0:i,dynamicProps:t instanceof r.Name,dynamicItems:i instanceof r.Name},n.source&&(n.source.evaluated=(0,r.stringify)(n.evaluated))}return t.validate=n,t}catch(r){throw delete t.validate,delete t.validateName,b&&this.logger.error("Error compiling schema, function code:",b),r}finally{this._compilations.delete(t)}}function u(t){return(0,n.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:p.call(this,t)}function c(t){for(let s of this._compilations){var r,i;if(r=s,i=t,r.schema===i.schema&&r.root===i.root&&r.baseId===i.baseId)return s}}function d(t,r){let i;for(;"string"==typeof(i=this.refs[r]);)r=i;return i||this.schemas[r]||h.call(this,t,r)}function h(t,r){let i=this.opts.uriResolver.parse(r),s=(0,n._getFullPath)(this.opts.uriResolver,i),a=(0,n.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&s===a)return m.call(this,i,t);let o=(0,n.normalizeId)(s),u=this.refs[o]||this.schemas[o];if("string"==typeof u){let r=h.call(this,t,u);if("object"!=typeof(null==r?void 0:r.schema))return;return m.call(this,i,r)}if("object"==typeof(null==u?void 0:u.schema)){if(u.validate||p.call(this,u),o===(0,n.normalizeId)(r)){let{schema:r}=u,{schemaId:i}=this.opts,s=r[i];return s&&(a=(0,n.resolveUrl)(this.opts.uriResolver,a,s)),new l({schema:r,schemaId:i,root:t,baseId:a})}return m.call(this,i,u)}}t.SchemaEnv=l,t.compileSchema=p,t.resolveRef=function(t,r,i){var s;i=(0,n.resolveUrl)(this.opts.uriResolver,r,i);let a=t.refs[i];if(a)return a;let o=d.call(this,t,i);if(void 0===o){let n=null==(s=t.localRefs)?void 0:s[i],{schemaId:a}=this.opts;n&&(o=new l({schema:n,schemaId:a,root:t,baseId:r}))}if(void 0!==o)return t.refs[i]=u.call(this,o)},t.getCompilingSchema=c,t.resolveSchema=h;var f=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function m(t,{baseId:r,schema:i,root:s}){var o;let p;if((null==(o=t.fragment)?void 0:o[0])!=="/")return;for(let s of t.fragment.slice(1).split("/")){if("boolean"==typeof i)return;let t=i[(0,a.unescapeFragment)(s)];if(void 0===t)return;let o="object"==typeof(i=t)&&i[this.opts.schemaId];!f.has(s)&&o&&(r=(0,n.resolveUrl)(this.opts.uriResolver,r,o))}if("boolean"!=typeof i&&i.$ref&&!(0,a.schemaHasRulesButRef)(i,this.RULES)){let t=(0,n.resolveUrl)(this.opts.uriResolver,r,i.$ref);p=h.call(this,s,t)}let{schemaId:u}=this.opts;if((p=p||new l({schema:i,schemaId:u,root:s,baseId:r})).schema!==p.root.schema)return p}}),rM=rl((t,r)=>{r.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}}),rF=rl((t,r)=>{r.exports={HEX:{0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,a:10,A:10,b:11,B:11,c:12,C:12,d:13,D:13,e:14,E:14,f:15,F:15}}}),rB=rl((t,r)=>{var{HEX:i}=rF(),s=/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u;function n(t){if(3>l(t,"."))return{host:t,isIPV4:!1};let[r]=t.match(s)||[];return r?{host:function(t){let r="",i=!0,s=t.length;for(let n=0;n<s;n++){let a=t[n];"0"===a&&i?(n+1<=s&&"."===t[n+1]||n+1===s)&&(r+=a,i=!1):(i="."===a,r+=a)}return r}(r),isIPV4:!0}:{host:t,isIPV4:!1}}function a(t,r=!1){let s="",n=!0;for(let r of t){if(void 0===i[r])return;"0"!==r&&!0===n&&(n=!1),n||(s+=r)}return r&&0===s.length&&(s="0"),s}function o(t){if(2>l(t,":"))return{host:t,isIPV6:!1};let r=function(t){let r=0,i={error:!1,address:"",zone:""},s=[],n=[],o=!1,l=!1,p=!1;function u(){if(n.length){if(!1===o){let t=a(n);if(void 0===t)return i.error=!0,!1;s.push(t)}n.length=0}return!0}for(let a=0;a<t.length;a++){let c=t[a];if("["!==c&&"]"!==c)if(":"===c){if(!0===l&&(p=!0),!u())break;if(r++,s.push(":"),r>7){i.error=!0;break}a-1>=0&&":"===t[a-1]&&(l=!0);continue}else if("%"===c){if(!u())break;o=!0}else{n.push(c);continue}}return n.length&&(o?i.zone=n.join(""):p?s.push(n.join("")):s.push(a(n))),i.address=s.join(""),i}(t);if(r.error)return{host:t,isIPV6:!1};{let{address:t,address:i}=r;return r.zone&&(t+="%"+r.zone,i+="%25"+r.zone),{host:t,escapedHost:i,isIPV6:!0}}}function l(t,r){let i=0;for(let s=0;s<t.length;s++)t[s]===r&&i++;return i}var p=/^\.\.?\//u,u=/^\/\.(?:\/|$)/u,c=/^\/\.\.(?:\/|$)/u,d=/^\/?(?:.|\n)*?(?=\/|$)/u;r.exports={recomposeAuthority:function(t){let r=[];if(void 0!==t.userinfo&&(r.push(t.userinfo),r.push("@")),void 0!==t.host){let i=unescape(t.host),s=n(i);if(s.isIPV4)i=s.host;else{let r=o(s.host);i=!0===r.isIPV6?`[${r.escapedHost}]`:t.host}r.push(i)}return("number"==typeof t.port||"string"==typeof t.port)&&(r.push(":"),r.push(String(t.port))),r.length?r.join(""):void 0},normalizeComponentEncoding:function(t,r){let i=!0!==r?escape:unescape;return void 0!==t.scheme&&(t.scheme=i(t.scheme)),void 0!==t.userinfo&&(t.userinfo=i(t.userinfo)),void 0!==t.host&&(t.host=i(t.host)),void 0!==t.path&&(t.path=i(t.path)),void 0!==t.query&&(t.query=i(t.query)),void 0!==t.fragment&&(t.fragment=i(t.fragment)),t},removeDotSegments:function(t){let r=[];for(;t.length;)if(t.match(p))t=t.replace(p,"");else if(t.match(u))t=t.replace(u,"/");else if(t.match(c))t=t.replace(c,"/"),r.pop();else if("."===t||".."===t)t="";else{let i=t.match(d);if(i){let s=i[0];t=t.slice(s.length),r.push(s)}else throw Error("Unexpected dot segment condition")}return r.join("")},normalizeIPv4:n,normalizeIPv6:o,stringArrayToHexStripped:a}}),rU=rl((t,r)=>{var i=/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu,s=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu;function n(t){return"boolean"==typeof t.secure?t.secure:"wss"===String(t.scheme).toLowerCase()}function a(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function o(t){let r="https"===String(t.scheme).toLowerCase();return(t.port===(r?443:80)||""===t.port)&&(t.port=void 0),t.path||(t.path="/"),t}var l={scheme:"http",domainHost:!0,parse:a,serialize:o},p={scheme:"https",domainHost:l.domainHost,parse:a,serialize:o},u={scheme:"ws",domainHost:!0,parse:function(t){return t.secure=n(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t},serialize:function(t){if((t.port===(n(t)?443:80)||""===t.port)&&(t.port=void 0),"boolean"==typeof t.secure&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[r,i]=t.resourceName.split("?");t.path=r&&"/"!==r?r:void 0,t.query=i,t.resourceName=void 0}return t.fragment=void 0,t}},c={scheme:"wss",domainHost:u.domainHost,parse:u.parse,serialize:u.serialize},d={http:l,https:p,ws:u,wss:c,urn:{scheme:"urn",parse:function(t,r){if(!t.path)return t.error="URN can not be parsed",t;let i=t.path.match(s);if(i){let s=r.scheme||t.scheme||"urn";t.nid=i[1].toLowerCase(),t.nss=i[2];let n=d[`${s}:${r.nid||t.nid}`];t.path=void 0,n&&(t=n.parse(t,r))}else t.error=t.error||"URN can not be parsed.";return t},serialize:function(t,r){let i=r.scheme||t.scheme||"urn",s=t.nid.toLowerCase(),n=d[`${i}:${r.nid||s}`];n&&(t=n.serialize(t,r));let a=t,o=t.nss;return a.path=`${s||r.nid}:${o}`,r.skipEscape=!0,a},skipNormalize:!0},"urn:uuid":{scheme:"urn:uuid",parse:function(t,r){return t.uuid=t.nss,t.nss=void 0,r.tolerant||t.uuid&&i.test(t.uuid)||(t.error=t.error||"UUID is not valid."),t},serialize:function(t){return t.nss=(t.uuid||"").toLowerCase(),t},skipNormalize:!0}};r.exports=d}),r$=rl((t,r)=>{var{normalizeIPv6:i,normalizeIPv4:s,removeDotSegments:n,recomposeAuthority:a,normalizeComponentEncoding:o}=rB(),l=rU();function p(t,r,i,s){let a={};return s||(t=h(u(t,i),i),r=h(u(r,i),i)),!(i=i||{}).tolerant&&r.scheme?(a.scheme=r.scheme,a.userinfo=r.userinfo,a.host=r.host,a.port=r.port,a.path=n(r.path||""),a.query=r.query):(void 0!==r.userinfo||void 0!==r.host||void 0!==r.port?(a.userinfo=r.userinfo,a.host=r.host,a.port=r.port,a.path=n(r.path||""),a.query=r.query):(r.path?("/"===r.path.charAt(0)?a.path=n(r.path):(void 0===t.userinfo&&void 0===t.host&&void 0===t.port||t.path?t.path?a.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+r.path:a.path=r.path:a.path="/"+r.path,a.path=n(a.path)),a.query=r.query):(a.path=t.path,void 0!==r.query)?a.query=r.query:a.query=t.query,a.userinfo=t.userinfo,a.host=t.host,a.port=t.port),a.scheme=t.scheme),a.fragment=r.fragment,a}function u(t,r){let i={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},s=Object.assign({},r),o=[],p=l[(s.scheme||i.scheme||"").toLowerCase()];p&&p.serialize&&p.serialize(i,s),void 0!==i.path&&(s.skipEscape?i.path=unescape(i.path):(i.path=escape(i.path),void 0!==i.scheme&&(i.path=i.path.split("%3A").join(":")))),"suffix"!==s.reference&&i.scheme&&o.push(i.scheme,":");let u=a(i);if(void 0!==u&&("suffix"!==s.reference&&o.push("//"),o.push(u),i.path&&"/"!==i.path.charAt(0)&&o.push("/")),void 0!==i.path){let t=i.path;s.absolutePath||p&&p.absolutePath||(t=n(t)),void 0===u&&(t=t.replace(/^\/\//u,"/%2F")),o.push(t)}return void 0!==i.query&&o.push("?",i.query),void 0!==i.fragment&&o.push("#",i.fragment),o.join("")}var c=Array.from({length:127},(t,r)=>/[^!"$&'()*+,\-.;=_`a-z{}~]/u.test(String.fromCharCode(r))),d=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function h(t,r){let n=Object.assign({},r),a={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=-1!==t.indexOf("%"),p=!1;"suffix"===n.reference&&(t=(n.scheme?n.scheme+":":"")+"//"+t);let u=t.match(d);if(u){if(a.scheme=u[1],a.userinfo=u[3],a.host=u[4],a.port=parseInt(u[5],10),a.path=u[6]||"",a.query=u[7],a.fragment=u[8],isNaN(a.port)&&(a.port=u[5]),a.host){let t=s(a.host);if(!1===t.isIPV4){let r=i(t.host);a.host=r.host.toLowerCase(),p=r.isIPV6}else a.host=t.host,p=!0}void 0!==a.scheme||void 0!==a.userinfo||void 0!==a.host||void 0!==a.port||void 0!==a.query||a.path?void 0===a.scheme?a.reference="relative":void 0===a.fragment?a.reference="absolute":a.reference="uri":a.reference="same-document",n.reference&&"suffix"!==n.reference&&n.reference!==a.reference&&(a.error=a.error||"URI is not a "+n.reference+" reference.");let t=l[(n.scheme||a.scheme||"").toLowerCase()];if(!n.unicodeSupport&&(!t||!t.unicodeSupport)&&a.host&&(n.domainHost||t&&t.domainHost)&&!1===p&&function(t){let r=0;for(let i=0,s=t.length;i<s;++i)if((r=t.charCodeAt(i))>126||c[r])return!0;return!1}(a.host))try{a.host=URL.domainToASCII(a.host.toLowerCase())}catch(t){a.error=a.error||"Host's domain name can not be converted to ASCII: "+t}(!t||t&&!t.skipNormalize)&&(o&&void 0!==a.scheme&&(a.scheme=unescape(a.scheme)),o&&void 0!==a.host&&(a.host=unescape(a.host)),a.path&&(a.path=escape(unescape(a.path))),a.fragment&&(a.fragment=encodeURI(decodeURIComponent(a.fragment)))),t&&t.parse&&t.parse(a,n)}else a.error=a.error||"URI can not be parsed.";return a}var f={SCHEMES:l,normalize:function(t,r){return"string"==typeof t?t=u(h(t,r),r):"object"==typeof t&&(t=h(u(t,r),r)),t},resolve:function(t,r,i){let s=Object.assign({scheme:"null"},i);return u(p(h(t,s),h(r,s),s,!0),{...s,skipEscape:!0})},resolveComponents:p,equal:function(t,r,i){return"string"==typeof t?t=u(o(h(t=unescape(t),i),!0),{...i,skipEscape:!0}):"object"==typeof t&&(t=u(o(t,!0),{...i,skipEscape:!0})),"string"==typeof r?r=u(o(h(r=unescape(r),i),!0),{...i,skipEscape:!0}):"object"==typeof r&&(r=u(o(r,!0),{...i,skipEscape:!0})),t.toLowerCase()===r.toLowerCase()},serialize:u,parse:h};r.exports=f,r.exports.default=f,r.exports.fastUri=f}),rV=rl(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=r$();r.code='require("ajv/dist/runtime/uri").default',t.default=r}),rK=rl(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=void 0;var r=rD();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return r.KeywordCxt}});var i=rg();Object.defineProperty(t,"_",{enumerable:!0,get:function(){return i._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return i.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return i.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return i.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return i.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return i.CodeGen}});var s=rj(),n=rL(),a=rS(),o=rR(),l=rg(),p=rO(),u=rP(),c=rv(),d=rM(),h=rV(),f=(t,r)=>new RegExp(t,r);f.code="new RegExp";var m=["removeAdditional","useDefaults","coerceTypes"],y=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),b={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},g={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'};class v{constructor(t={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,t=this.opts={...t,...function(t){var r,i,s,n,a,o,l,p,u,c,d,m,y,b,g,v,x,T,E,S,_,P,A,w,C;let I=t.strict,k=null==(r=t.code)?void 0:r.optimize,N=!0===k||void 0===k?1:k||0,O=null!=(s=null==(i=t.code)?void 0:i.regExp)?s:f,D=null!=(n=t.uriResolver)?n:h.default;return{strictSchema:null==(o=null!=(a=t.strictSchema)?a:I)||o,strictNumbers:null==(p=null!=(l=t.strictNumbers)?l:I)||p,strictTypes:null!=(c=null!=(u=t.strictTypes)?u:I)?c:"log",strictTuples:null!=(m=null!=(d=t.strictTuples)?d:I)?m:"log",strictRequired:null!=(b=null!=(y=t.strictRequired)?y:I)&&b,code:t.code?{...t.code,optimize:N,regExp:O}:{optimize:N,regExp:O},loopRequired:null!=(g=t.loopRequired)?g:200,loopEnum:null!=(v=t.loopEnum)?v:200,meta:null==(x=t.meta)||x,messages:null==(T=t.messages)||T,inlineRefs:null==(E=t.inlineRefs)||E,schemaId:null!=(S=t.schemaId)?S:"$id",addUsedSchema:null==(_=t.addUsedSchema)||_,validateSchema:null==(P=t.validateSchema)||P,validateFormats:null==(A=t.validateFormats)||A,unicodeRegExp:null==(w=t.unicodeRegExp)||w,int32range:null==(C=t.int32range)||C,uriResolver:D}}(t)};let{es5:r,lines:i}=this.opts.code;this.scope=new l.ValueScope({scope:{},prefixes:y,es5:r,lines:i}),this.logger=function(t){if(!1===t)return A;if(void 0===t)return console;if(t.log&&t.warn&&t.error)return t;throw Error("logger must implement log, warn and error methods")}(t.logger);let s=t.validateFormats;t.validateFormats=!1,this.RULES=(0,a.getRules)(),x.call(this,b,t,"NOT SUPPORTED"),x.call(this,g,t,"DEPRECATED","warn"),this._metaOpts=P.call(this),t.formats&&S.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),t.keywords&&_.call(this,t.keywords),"object"==typeof t.meta&&this.addMetaSchema(t.meta),E.call(this),t.validateFormats=s}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:t,meta:r,schemaId:i}=this.opts,s=d;"id"===i&&((s={...d}).id=s.$id,delete s.$id),r&&t&&this.addMetaSchema(s,s[i],!1)}defaultMeta(){let{meta:t,schemaId:r}=this.opts;return this.opts.defaultMeta="object"==typeof t?t[r]||t:void 0}validate(t,r){let i;if("string"==typeof t){if(!(i=this.getSchema(t)))throw Error(`no schema with key or ref "${t}"`)}else i=this.compile(t);let s=i(r);return"$async"in i||(this.errors=i.errors),s}compile(t,r){let i=this._addSchema(t,r);return i.validate||this._compileSchemaEnv(i)}compileAsync(t,r){if("function"!=typeof this.opts.loadSchema)throw Error("options.loadSchema should be a function");let{loadSchema:i}=this.opts;return s.call(this,t,r);async function s(t,r){await a.call(this,t.$schema);let i=this._addSchema(t,r);return i.validate||o.call(this,i)}async function a(t){t&&!this.getSchema(t)&&await s.call(this,{$ref:t},!0)}async function o(t){try{return this._compileSchemaEnv(t)}catch(r){if(!(r instanceof n.default))throw r;return l.call(this,r),await p.call(this,r.missingSchema),o.call(this,t)}}function l({missingSchema:t,missingRef:r}){if(this.refs[t])throw Error(`AnySchema ${t} is loaded but ${r} cannot be resolved`)}async function p(t){let i=await u.call(this,t);this.refs[t]||await a.call(this,i.$schema),this.refs[t]||this.addSchema(i,t,r)}async function u(t){let r=this._loading[t];if(r)return r;try{return await (this._loading[t]=i(t))}finally{delete this._loading[t]}}}addSchema(t,r,i,s=this.opts.validateSchema){let n;if(Array.isArray(t)){for(let r of t)this.addSchema(r,void 0,i,s);return this}if("object"==typeof t){let{schemaId:r}=this.opts;if(void 0!==(n=t[r])&&"string"!=typeof n)throw Error(`schema ${r} must be string`)}return r=(0,p.normalizeId)(r||n),this._checkUnique(r),this.schemas[r]=this._addSchema(t,i,r,s,!0),this}addMetaSchema(t,r,i=this.opts.validateSchema){return this.addSchema(t,r,!0,i),this}validateSchema(t,r){let i;if("boolean"==typeof t)return!0;if(void 0!==(i=t.$schema)&&"string"!=typeof i)throw Error("$schema must be a string");if(!(i=i||this.opts.defaultMeta||this.defaultMeta()))return this.logger.warn("meta-schema not available"),this.errors=null,!0;let s=this.validate(i,t);if(!s&&r){let t="schema is invalid: "+this.errorsText();if("log"===this.opts.validateSchema)this.logger.error(t);else throw Error(t)}return s}getSchema(t){let r;for(;"string"==typeof(r=T.call(this,t));)t=r;if(void 0===r){let{schemaId:i}=this.opts,s=new o.SchemaEnv({schema:{},schemaId:i});if(!(r=o.resolveSchema.call(this,s,t)))return;this.refs[t]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(t){if(t instanceof RegExp)return this._removeAllSchemas(this.schemas,t),this._removeAllSchemas(this.refs,t),this;switch(typeof t){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=T.call(this,t);return"object"==typeof r&&this._cache.delete(r.schema),delete this.schemas[t],delete this.refs[t],this}case"object":{this._cache.delete(t);let r=t[this.opts.schemaId];return r&&(r=(0,p.normalizeId)(r),delete this.schemas[r],delete this.refs[r]),this}default:throw Error("ajv.removeSchema: invalid parameter")}}addVocabulary(t){for(let r of t)this.addKeyword(r);return this}addKeyword(t,r){let i;if("string"==typeof t)i=t,"object"==typeof r&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=i);else if("object"==typeof t&&void 0===r){if(Array.isArray(i=(r=t).keyword)&&!i.length)throw Error("addKeywords: keyword must be string or non-empty array")}else throw Error("invalid addKeywords parameters");if(C.call(this,i,r),!r)return(0,c.eachItem)(i,t=>I.call(this,t)),this;N.call(this,r);let s={...r,type:(0,u.getJSONTypes)(r.type),schemaType:(0,u.getJSONTypes)(r.schemaType)};return(0,c.eachItem)(i,0===s.type.length?t=>I.call(this,t,s):t=>s.type.forEach(r=>I.call(this,t,s,r))),this}getKeyword(t){let r=this.RULES.all[t];return"object"==typeof r?r.definition:!!r}removeKeyword(t){let{RULES:r}=this;for(let i of(delete r.keywords[t],delete r.all[t],r.rules)){let r=i.rules.findIndex(r=>r.keyword===t);r>=0&&i.rules.splice(r,1)}return this}addFormat(t,r){return"string"==typeof r&&(r=new RegExp(r)),this.formats[t]=r,this}errorsText(t=this.errors,{separator:r=", ",dataVar:i="data"}={}){return t&&0!==t.length?t.map(t=>`${i}${t.instancePath} ${t.message}`).reduce((t,i)=>t+r+i):"No errors"}$dataMetaSchema(t,r){let i=this.RULES.all;for(let s of(t=JSON.parse(JSON.stringify(t)),r)){let r=s.split("/").slice(1),n=t;for(let t of r)n=n[t];for(let t in i){let r=i[t];if("object"!=typeof r)continue;let{$data:s}=r.definition,a=n[t];s&&a&&(n[t]=D(a))}}return t}_removeAllSchemas(t,r){for(let i in t){let s=t[i];(!r||r.test(i))&&("string"==typeof s?delete t[i]:s&&!s.meta&&(this._cache.delete(s.schema),delete t[i]))}}_addSchema(t,r,i,s=this.opts.validateSchema,n=this.opts.addUsedSchema){let a,{schemaId:l}=this.opts;if("object"==typeof t)a=t[l];else if(this.opts.jtd)throw Error("schema must be object");else if("boolean"!=typeof t)throw Error("schema must be object or boolean");let u=this._cache.get(t);if(void 0!==u)return u;i=(0,p.normalizeId)(a||i);let c=p.getSchemaRefs.call(this,t,i);return u=new o.SchemaEnv({schema:t,schemaId:l,meta:r,baseId:i,localRefs:c}),this._cache.set(u.schema,u),n&&!i.startsWith("#")&&(i&&this._checkUnique(i),this.refs[i]=u),s&&this.validateSchema(t,!0),u}_checkUnique(t){if(this.schemas[t]||this.refs[t])throw Error(`schema with key or id "${t}" already exists`)}_compileSchemaEnv(t){if(t.meta?this._compileMetaSchema(t):o.compileSchema.call(this,t),!t.validate)throw Error("ajv implementation error");return t.validate}_compileMetaSchema(t){let r=this.opts;this.opts=this._metaOpts;try{o.compileSchema.call(this,t)}finally{this.opts=r}}}function x(t,r,i,s="error"){for(let n in t)n in r&&this.logger[s](`${i}: option ${n}. ${t[n]}`)}function T(t){return t=(0,p.normalizeId)(t),this.schemas[t]||this.refs[t]}function E(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let r in t)this.addSchema(t[r],r)}function S(){for(let t in this.opts.formats){let r=this.opts.formats[t];r&&this.addFormat(t,r)}}function _(t){if(Array.isArray(t))return void this.addVocabulary(t);for(let r in this.logger.warn("keywords option as map is deprecated, pass array"),t){let i=t[r];i.keyword||(i.keyword=r),this.addKeyword(i)}}function P(){let t={...this.opts};for(let r of m)delete t[r];return t}v.ValidationError=s.default,v.MissingRefError=n.default,t.default=v;var A={log(){},warn(){},error(){}},w=/^[a-z_$][a-z0-9_$:-]*$/i;function C(t,r){let{RULES:i}=this;if((0,c.eachItem)(t,t=>{if(i.keywords[t])throw Error(`Keyword ${t} is already defined`);if(!w.test(t))throw Error(`Keyword ${t} has invalid name`)}),r&&r.$data&&!("code"in r||"validate"in r))throw Error('$data keyword must have "code" or "validate" function')}function I(t,r,i){var s;let n=null==r?void 0:r.post;if(i&&n)throw Error('keyword with "post" flag cannot have "type"');let{RULES:a}=this,o=n?a.post:a.rules.find(({type:t})=>t===i);if(o||(o={type:i,rules:[]},a.rules.push(o)),a.keywords[t]=!0,!r)return;let l={keyword:t,definition:{...r,type:(0,u.getJSONTypes)(r.type),schemaType:(0,u.getJSONTypes)(r.schemaType)}};r.before?k.call(this,o,l,r.before):o.rules.push(l),a.all[t]=l,null==(s=r.implements)||s.forEach(t=>this.addKeyword(t))}function k(t,r,i){let s=t.rules.findIndex(t=>t.keyword===i);s>=0?t.rules.splice(s,0,r):(t.rules.push(r),this.logger.warn(`rule ${i} is not defined`))}function N(t){let{metaSchema:r}=t;void 0!==r&&(t.$data&&this.opts.$data&&(r=D(r)),t.validateSchema=this.compile(r,!0))}var O={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function D(t){return{anyOf:[t,O]}}}),rq=rl(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default={keyword:"id",code(){throw Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}}}),rz=rl(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.callRef=t.getValidate=void 0;var r=rL(),i=rw(),s=rg(),n=rx(),a=rR(),o=rv();function l(t,r){let{gen:i}=t;return r.validate?i.scopeValue("validate",{ref:r.validate}):s._`${i.scopeValue("wrapper",{ref:r})}.validate`}function p(t,r,a,l){let{gen:p,it:u}=t,{allErrors:c,schemaEnv:d,opts:h}=u,f=h.passContext?n.default.this:s.nil;function m(t){let r=s._`${t}.errors`;p.assign(n.default.vErrors,s._`${n.default.vErrors} === null ? ${r} : ${n.default.vErrors}.concat(${r})`),p.assign(n.default.errors,s._`${n.default.vErrors}.length`)}function y(t){var r;if(!u.opts.unevaluated)return;let i=null==(r=null==a?void 0:a.validate)?void 0:r.evaluated;if(!0!==u.props)if(i&&!i.dynamicProps)void 0!==i.props&&(u.props=o.mergeEvaluated.props(p,i.props,u.props));else{let r=p.var("props",s._`${t}.evaluated.props`);u.props=o.mergeEvaluated.props(p,r,u.props,s.Name)}if(!0!==u.items)if(i&&!i.dynamicItems)void 0!==i.items&&(u.items=o.mergeEvaluated.items(p,i.items,u.items));else{let r=p.var("items",s._`${t}.evaluated.items`);u.items=o.mergeEvaluated.items(p,r,u.items,s.Name)}}l?function(){if(!d.$async)throw Error("async schema referenced by sync schema");let n=p.let("valid");p.try(()=>{p.code(s._`await ${(0,i.callValidateCode)(t,r,f)}`),y(r),c||p.assign(n,!0)},t=>{p.if(s._`!(${t} instanceof ${u.ValidationError})`,()=>p.throw(t)),m(t),c||p.assign(n,!1)}),t.ok(n)}():t.result((0,i.callValidateCode)(t,r,f),()=>y(r),()=>m(r))}t.getValidate=l,t.callRef=p,t.default={keyword:"$ref",schemaType:"string",code(t){var i,n;let o,u,c,d,{gen:h,schema:f,it:m}=t,{baseId:y,schemaEnv:b,validateName:g,opts:v,self:x}=m,{root:T}=b;if(("#"===f||"#/"===f)&&y===T.baseId){if(b===T)return p(t,g,b,b.$async);let r=h.scopeValue("root",{ref:T});return p(t,s._`${r}.validate`,T,T.$async)}let E=a.resolveRef.call(x,T,y,f);if(void 0===E)throw new r.default(m.opts.uriResolver,y,f);return E instanceof a.SchemaEnv?(o=l(t,i=E),void p(t,o,i,i.$async)):(n=E,u=h.scopeValue("schema",!0===v.code.source?{ref:n,code:(0,s.stringify)(n)}:{ref:n}),c=h.name("valid"),d=t.subschema({schema:n,dataTypes:[],schemaPath:s.nil,topSchemaRef:u,errSchemaPath:f},c),void(t.mergeEvaluated(d),t.ok(c)))}}}),rW=rl(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=rq(),i=rz();t.default=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",r.default,i.default]}),rH=rl(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=rg(),i=r.operators,s={maximum:{okStr:"<=",ok:i.LTE,fail:i.GT},minimum:{okStr:">=",ok:i.GTE,fail:i.LT},exclusiveMaximum:{okStr:"<",ok:i.LT,fail:i.GTE},exclusiveMinimum:{okStr:">",ok:i.GT,fail:i.LTE}};t.default={keyword:Object.keys(s),type:"number",schemaType:"number",$data:!0,error:{message:({keyword:t,schemaCode:i})=>r.str`must be ${s[t].okStr} ${i}`,params:({keyword:t,schemaCode:i})=>r._`{comparison: ${s[t].okStr}, limit: ${i}}`},code(t){let{keyword:i,data:n,schemaCode:a}=t;t.fail$data(r._`${n} ${s[i].fail} ${a} || isNaN(${n})`)}}}),rJ=rl(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=rg();t.default={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:{message:({schemaCode:t})=>r.str`must be multiple of ${t}`,params:({schemaCode:t})=>r._`{multipleOf: ${t}}`},code(t){let{gen:i,data:s,schemaCode:n,it:a}=t,o=a.opts.multipleOfPrecision,l=i.let("res"),p=o?r._`Math.abs(Math.round(${l}) - ${l}) > 1e-${o}`:r._`${l} !== parseInt(${l})`;t.fail$data(r._`(${n} === 0 || (${l} = ${s}/${n}, ${p}))`)}}}),rY=rl(t=>{function r(t){let r=t.length,i=0,s=0,n;for(;s<r;)i++,(n=t.charCodeAt(s++))>=55296&&n<=56319&&s<r&&(64512&(n=t.charCodeAt(s)))==56320&&s++;return i}Object.defineProperty(t,"__esModule",{value:!0}),t.default=r,r.code='require("ajv/dist/runtime/ucs2length").default'}),rX=rl(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=rg(),i=rv(),s=rY();t.default={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:{message:({keyword:t,schemaCode:i})=>r.str`must NOT have ${"maxLength"===t?"more":"fewer"} than ${i} characters`,params:({schemaCode:t})=>r._`{limit: ${t}}`},code(t){let{keyword:n,data:a,schemaCode:o,it:l}=t,p="maxLength"===n?r.operators.GT:r.operators.LT,u=!1===l.opts.unicode?r._`${a}.length`:r._`${(0,i.useFunc)(t.gen,s.default)}(${a})`;t.fail$data(r._`${u} ${p} ${o}`)}}}),rG=rl(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=rw(),i=rg();t.default={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:{message:({schemaCode:t})=>i.str`must match pattern "${t}"`,params:({schemaCode:t})=>i._`{pattern: ${t}}`},code(t){let{data:s,$data:n,schema:a,schemaCode:o,it:l}=t,p=l.opts.unicodeRegExp?"u":"",u=n?i._`(new RegExp(${o}, ${p}))`:(0,r.usePattern)(t,a);t.fail$data(i._`!${u}.test(${s})`)}}}),rZ=rl(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=rg();t.default={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:{message:({keyword:t,schemaCode:i})=>r.str`must NOT have ${"maxProperties"===t?"more":"fewer"} than ${i} properties`,params:({schemaCode:t})=>r._`{limit: ${t}}`},code(t){let{keyword:i,data:s,schemaCode:n}=t,a="maxProperties"===i?r.operators.GT:r.operators.LT;t.fail$data(r._`Object.keys(${s}).length ${a} ${n}`)}}}),rQ=rl(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=rw(),i=rg(),s=rv();t.default={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:({params:{missingProperty:t}})=>i.str`must have required property '${t}'`,params:({params:{missingProperty:t}})=>i._`{missingProperty: ${t}}`},code(t){let{gen:n,schema:a,schemaCode:o,data:l,$data:p,it:u}=t,{opts:c}=u;if(!p&&0===a.length)return;let d=a.length>=c.loopRequired;if(u.allErrors?function(){if(d||p)t.block$data(i.nil,h);else for(let i of a)(0,r.checkReportMissingProp)(t,i)}():function(){let s=n.let("missing");if(d||p){let a=n.let("valid",!0);t.block$data(a,()=>{var p,u;return p=s,u=a,void(t.setParams({missingProperty:p}),n.forOf(p,o,()=>{n.assign(u,(0,r.propertyInData)(n,l,p,c.ownProperties)),n.if((0,i.not)(u),()=>{t.error(),n.break()})},i.nil))}),t.ok(a)}else n.if((0,r.checkMissingProp)(t,a,s)),(0,r.reportMissingProp)(t,s),n.else()}(),c.strictRequired){let r=t.parentSchema.properties,{definedProperties:i}=t.it;for(let t of a)if((null==r?void 0:r[t])===void 0&&!i.has(t)){let r=u.schemaEnv.baseId+u.errSchemaPath,i=`required property "${t}" is not defined at "${r}" (strictRequired)`;(0,s.checkStrictMode)(u,i,u.opts.strictRequired)}}function h(){n.forOf("prop",o,i=>{t.setParams({missingProperty:i}),n.if((0,r.noPropertyInData)(n,l,i,c.ownProperties),()=>t.error())})}}}}),r0=rl(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=rg();t.default={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:{message:({keyword:t,schemaCode:i})=>r.str`must NOT have ${"maxItems"===t?"more":"fewer"} than ${i} items`,params:({schemaCode:t})=>r._`{limit: ${t}}`},code(t){let{keyword:i,data:s,schemaCode:n}=t,a="maxItems"===i?r.operators.GT:r.operators.LT;t.fail$data(r._`${s}.length ${a} ${n}`)}}}),r1=rl(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=rk();r.code='require("ajv/dist/runtime/equal").default',t.default=r}),r2=rl(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=rP(),i=rg(),s=rv(),n=r1();t.default={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:{message:({params:{i:t,j:r}})=>i.str`must NOT have duplicate items (items ## ${r} and ${t} are identical)`,params:({params:{i:t,j:r}})=>i._`{i: ${t}, j: ${r}}`},code(t){let{gen:a,data:o,$data:l,schema:p,parentSchema:u,schemaCode:c,it:d}=t;if(!l&&!p)return;let h=a.let("valid"),f=u.items?(0,r.getSchemaTypes)(u.items):[];t.block$data(h,function(){let l=a.let("i",i._`${o}.length`),p=a.let("j");t.setParams({i:l,j:p}),a.assign(h,!0),a.if(i._`${l} > 1`,()=>(f.length>0&&!f.some(t=>"object"===t||"array"===t)?function(s,n){let l=a.name("item"),p=(0,r.checkDataTypes)(f,l,d.opts.strictNumbers,r.DataType.Wrong),u=a.const("indices",i._`{}`);a.for(i._`;${s}--;`,()=>{a.let(l,i._`${o}[${s}]`),a.if(p,i._`continue`),f.length>1&&a.if(i._`typeof ${l} == "string"`,i._`${l} += "_"`),a.if(i._`typeof ${u}[${l}] == "number"`,()=>{a.assign(n,i._`${u}[${l}]`),t.error(),a.assign(h,!1).break()}).code(i._`${u}[${l}] = ${s}`)})}:function(r,l){let p=(0,s.useFunc)(a,n.default),u=a.name("outer");a.label(u).for(i._`;${r}--;`,()=>a.for(i._`${l} = ${r}; ${l}--;`,()=>a.if(i._`${p}(${o}[${r}], ${o}[${l}])`,()=>{t.error(),a.assign(h,!1).break(u)})))})(l,p))},i._`${c} === false`),t.ok(h)}}}),r4=rl(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=rg(),i=rv(),s=r1();t.default={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:({schemaCode:t})=>r._`{allowedValue: ${t}}`},code(t){let{gen:n,data:a,$data:o,schemaCode:l,schema:p}=t;o||p&&"object"==typeof p?t.fail$data(r._`!${(0,i.useFunc)(n,s.default)}(${a}, ${l})`):t.fail(r._`${p} !== ${a}`)}}}),r3=rl(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=rg(),i=rv(),s=r1();t.default={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode:t})=>r._`{allowedValues: ${t}}`},code(t){let{gen:n,data:a,$data:o,schema:l,schemaCode:p,it:u}=t;if(!o&&0===l.length)throw Error("enum must have non-empty array");let c=l.length>=u.opts.loopEnum,d,h=()=>null!=d?d:d=(0,i.useFunc)(n,s.default),f;if(c||o)f=n.let("valid"),t.block$data(f,function(){n.assign(f,!1),n.forOf("v",p,t=>n.if(r._`${h()}(${a}, ${t})`,()=>n.assign(f,!0).break()))});else{if(!Array.isArray(l))throw Error("ajv implementation error");let t=n.const("vSchema",p);f=(0,r.or)(...l.map((i,s)=>{var n,o;let p;return n=t,"object"==typeof(p=l[o=s])&&null!==p?r._`${h()}(${a}, ${n}[${o}])`:r._`${a} === ${p}`}))}t.pass(f)}}}),r8=rl(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=rH(),i=rJ(),s=rX(),n=rG(),a=rZ(),o=rQ(),l=r0(),p=r2(),u=r4(),c=r3();t.default=[r.default,i.default,s.default,n.default,a.default,o.default,l.default,p.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},u.default,c.default]}),r7=rl(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validateAdditionalItems=void 0;var r=rg(),i=rv();function s(t,s){let{gen:n,schema:a,data:o,keyword:l,it:p}=t;p.items=!0;let u=n.const("len",r._`${o}.length`);if(!1===a)t.setParams({len:s.length}),t.pass(r._`${u} <= ${s.length}`);else if("object"==typeof a&&!(0,i.alwaysValidSchema)(p,a)){let a=n.var("valid",r._`${u} <= ${s.length}`);n.if((0,r.not)(a),()=>{var o;return o=a,void n.forRange("i",s.length,u,s=>{t.subschema({keyword:l,dataProp:s,dataPropType:i.Type.Num},o),p.allErrors||n.if((0,r.not)(o),()=>n.break())})}),t.ok(a)}}t.validateAdditionalItems=s,t.default={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:{message:({params:{len:t}})=>r.str`must NOT have more than ${t} items`,params:({params:{len:t}})=>r._`{limit: ${t}}`},code(t){let{parentSchema:r,it:n}=t,{items:a}=r;Array.isArray(a)?s(t,a):(0,i.checkStrictMode)(n,'"additionalItems" is ignored when "items" is not an array of schemas')}}}),r9=rl(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validateTuple=void 0;var r=rg(),i=rv(),s=rw();function n(t,s,a=t.schema){let{gen:o,parentSchema:l,data:p,keyword:u,it:c}=t;(function(t){let{opts:r,errSchemaPath:n}=c,o=a.length,l=o===t.minItems&&(o===t.maxItems||!1===t[s]);if(r.strictTuples&&!l){let t=`"${u}" is ${o}-tuple, but minItems or maxItems/${s} are not specified or different at path "${n}"`;(0,i.checkStrictMode)(c,t,r.strictTuples)}})(l),c.opts.unevaluated&&a.length&&!0!==c.items&&(c.items=i.mergeEvaluated.items(o,a.length,c.items));let d=o.name("valid"),h=o.const("len",r._`${p}.length`);a.forEach((s,n)=>{(0,i.alwaysValidSchema)(c,s)||(o.if(r._`${h} > ${n}`,()=>t.subschema({keyword:u,schemaProp:n,dataProp:n},d)),t.ok(d))})}t.validateTuple=n,t.default={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:r,it:a}=t;if(Array.isArray(r))return n(t,"additionalItems",r);a.items=!0,(0,i.alwaysValidSchema)(a,r)||t.ok((0,s.validateArray)(t))}}}),r5=rl(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=r9();t.default={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,r.validateTuple)(t,"items")}}),r6=rl(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=rg(),i=rv(),s=rw(),n=r7();t.default={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:({params:{len:t}})=>r.str`must NOT have more than ${t} items`,params:({params:{len:t}})=>r._`{limit: ${t}}`},code(t){let{schema:r,parentSchema:a,it:o}=t,{prefixItems:l}=a;o.items=!0,(0,i.alwaysValidSchema)(o,r)||(l?(0,n.validateAdditionalItems)(t,l):t.ok((0,s.validateArray)(t)))}}}),ie=rl(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=rg(),i=rv();t.default={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:{message:({params:{min:t,max:i}})=>void 0===i?r.str`must contain at least ${t} valid item(s)`:r.str`must contain at least ${t} and no more than ${i} valid item(s)`,params:({params:{min:t,max:i}})=>void 0===i?r._`{minContains: ${t}}`:r._`{minContains: ${t}, maxContains: ${i}}`},code(t){let{gen:s,schema:n,parentSchema:a,data:o,it:l}=t,p,u,{minContains:c,maxContains:d}=a;l.opts.next?(p=void 0===c?1:c,u=d):p=1;let h=s.const("len",r._`${o}.length`);if(t.setParams({min:p,max:u}),void 0===u&&0===p)return void(0,i.checkStrictMode)(l,'"minContains" == 0 without "maxContains": "contains" keyword ignored');if(void 0!==u&&p>u){(0,i.checkStrictMode)(l,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,i.alwaysValidSchema)(l,n)){let i=r._`${h} >= ${p}`;void 0!==u&&(i=r._`${i} && ${h} <= ${u}`),t.pass(i);return}l.items=!0;let f=s.name("valid");function m(){let t=s.name("_valid"),i=s.let("count",0);y(t,()=>s.if(t,()=>{var t;return t=i,void((s.code(r._`${t}++`),void 0===u)?s.if(r._`${t} >= ${p}`,()=>s.assign(f,!0).break()):(s.if(r._`${t} > ${u}`,()=>s.assign(f,!1).break()),1===p)?s.assign(f,!0):s.if(r._`${t} >= ${p}`,()=>s.assign(f,!0)))}))}function y(r,n){s.forRange("i",0,h,s=>{t.subschema({keyword:"contains",dataProp:s,dataPropType:i.Type.Num,compositeRule:!0},r),n()})}void 0===u&&1===p?y(f,()=>s.if(f,()=>s.break())):0===p?(s.let(f,!0),void 0!==u&&s.if(r._`${o}.length > 0`,m)):(s.let(f,!1),m()),t.result(f,()=>t.reset())}}}),it=rl(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validateSchemaDeps=t.validatePropertyDeps=t.error=void 0;var r=rg(),i=rv(),s=rw();t.error={message:({params:{property:t,depsCount:i,deps:s}})=>r.str`must have ${1===i?"property":"properties"} ${s} when property ${t} is present`,params:({params:{property:t,depsCount:i,deps:s,missingProperty:n}})=>r._`{property: ${t},
|
|
358
358
|
missingProperty: ${n},
|
|
359
359
|
depsCount: ${i},
|
|
360
|
-
deps: ${s}}`};var n={keyword:"dependencies",type:"object",schemaType:"object",error:t.error,code(t){let[r,i]=function({schema:t}){let r={},i={};for(let s in t)"__proto__"!==s&&((Array.isArray(t[s])?r:i)[s]=t[s]);return[r,i]}(t);a(t,r),o(t,i)}};function a(t,i=t.schema){let{gen:n,data:o,it:l}=t;if(0===Object.keys(i).length)return;let p=n.let("missing");for(let a in i){let u=i[a];if(0===u.length)continue;let c=(0,s.propertyInData)(n,o,a,l.opts.ownProperties);(t.setParams({property:a,depsCount:u.length,deps:u.join(", ")}),l.allErrors)?n.if(c,()=>{for(let r of u)(0,s.checkReportMissingProp)(t,r)}):(n.if(r._`${c} && (${(0,s.checkMissingProp)(t,u,p)})`),(0,s.reportMissingProp)(t,p),n.else())}}function o(t,r=t.schema){let{gen:n,data:a,keyword:l,it:p}=t,u=n.name("valid");for(let o in r)(0,i.alwaysValidSchema)(p,r[o])||(n.if((0,s.propertyInData)(n,a,o,p.opts.ownProperties),()=>{let r=t.subschema({keyword:l,schemaProp:o},u);t.mergeValidEvaluated(r,u)},()=>n.var(u,!0)),t.ok(u))}t.validatePropertyDeps=a,t.validateSchemaDeps=o,t.default=n}),it=ro(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=rb(),i=rg();t.default={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:{message:"property name must be valid",params:({params:t})=>r._`{propertyName: ${t.propertyName}}`},code(t){let{gen:s,schema:n,data:a,it:o}=t;if((0,i.alwaysValidSchema)(o,n))return;let l=s.name("valid");s.forIn("key",a,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},l),s.if((0,r.not)(l),()=>{t.error(!0),o.allErrors||s.break()})}),t.ok(l)}}}),ir=ro(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=rA(),i=rb(),s=rv(),n=rg();t.default={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:({params:t})=>i._`{additionalProperty: ${t.additionalProperty}}`},code(t){let{gen:a,schema:o,parentSchema:l,data:p,errsCount:u,it:c}=t;if(!u)throw Error("ajv implementation error");let{allErrors:d,opts:h}=c;if(c.props=!0,"all"!==h.removeAdditional&&(0,n.alwaysValidSchema)(c,o))return;let f=(0,r.allSchemaProperties)(l.properties),m=(0,r.allSchemaProperties)(l.patternProperties);function y(t){a.code(i._`delete ${p}[${t}]`)}function b(r){if("all"===h.removeAdditional||h.removeAdditional&&!1===o)return void y(r);if(!1===o){t.setParams({additionalProperty:r}),t.error(),d||a.break();return}if("object"==typeof o&&!(0,n.alwaysValidSchema)(c,o)){let s=a.name("valid");"failing"===h.removeAdditional?(g(r,s,!1),a.if((0,i.not)(s),()=>{t.reset(),y(r)})):(g(r,s),d||a.if((0,i.not)(s),()=>a.break()))}}function g(r,i,s){let a={keyword:"additionalProperties",dataProp:r,dataPropType:n.Type.Str};!1===s&&Object.assign(a,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(a,i)}a.forIn("key",p,s=>{f.length||m.length?a.if(function(s){let o;if(f.length>8){let t=(0,n.schemaRefOrVal)(c,l.properties,"properties");o=(0,r.isOwnProperty)(a,t,s)}else o=f.length?(0,i.or)(...f.map(t=>i._`${s} === ${t}`)):i.nil;return m.length&&(o=(0,i.or)(o,...m.map(n=>i._`${(0,r.usePattern)(t,n)}.test(${s})`))),(0,i.not)(o)}(s),()=>b(s)):b(s)}),t.ok(i._`${u} === ${s.default.errors}`)}}}),ii=ro(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=rO(),i=rA(),s=rg(),n=ir();t.default={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:a,schema:o,parentSchema:l,data:p,it:u}=t;"all"===u.opts.removeAdditional&&void 0===l.additionalProperties&&n.default.code(new r.KeywordCxt(u,n.default,"additionalProperties"));let c=(0,i.allSchemaProperties)(o);for(let t of c)u.definedProperties.add(t);u.opts.unevaluated&&c.length&&!0!==u.props&&(u.props=s.mergeEvaluated.props(a,(0,s.toHash)(c),u.props));let d=c.filter(t=>!(0,s.alwaysValidSchema)(u,o[t]));if(0===d.length)return;let h=a.name("valid");for(let r of d){var f;(f=r,u.opts.useDefaults&&!u.compositeRule&&void 0!==o[f].default)?m(r):(a.if((0,i.propertyInData)(a,p,r,u.opts.ownProperties)),m(r),u.allErrors||a.else().var(h,!0),a.endIf()),t.it.definedProperties.add(r),t.ok(h)}function m(r){t.subschema({keyword:"properties",schemaProp:r,dataProp:r},h)}}}}),is=ro(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=rA(),i=rb(),s=rg(),n=rg();t.default={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:a,schema:o,data:l,parentSchema:p,it:u}=t,{opts:c}=u,d=(0,r.allSchemaProperties)(o),h=d.filter(t=>(0,s.alwaysValidSchema)(u,o[t]));if(0===d.length||h.length===d.length&&(!u.opts.unevaluated||!0===u.props))return;let f=c.strictSchema&&!c.allowMatchingProperties&&p.properties,m=a.name("valid");!0===u.props||u.props instanceof i.Name||(u.props=(0,n.evaluatedPropsToName)(a,u.props));let{props:y}=u;for(let t of d)f&&function(t){for(let r in f)new RegExp(t).test(r)&&(0,s.checkStrictMode)(u,`property ${r} matches pattern ${t} (use allowMatchingProperties)`)}(t),u.allErrors?b(t):(a.var(m,!0),b(t),a.if(m));function b(s){a.forIn("key",l,o=>{a.if(i._`${(0,r.usePattern)(t,s)}.test(${o})`,()=>{let r=h.includes(s);r||t.subschema({keyword:"patternProperties",schemaProp:s,dataProp:o,dataPropType:n.Type.Str},m),u.opts.unevaluated&&!0!==y?a.assign(i._`${y}[${o}]`,!0):r||u.allErrors||a.if((0,i.not)(m),()=>a.break())})})}}}}),ia=ro(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=rg();t.default={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:i,schema:s,it:n}=t;if((0,r.alwaysValidSchema)(n,s))return void t.fail();let a=i.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},a),t.failResult(a,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}}}),io=ro(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:rA().validateUnion,error:{message:"must match a schema in anyOf"}}}),il=ro(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=rb(),i=rg();t.default={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:{message:"must match exactly one schema in oneOf",params:({params:t})=>r._`{passingSchemas: ${t.passing}}`},code(t){let{gen:s,schema:n,parentSchema:a,it:o}=t;if(!Array.isArray(n))throw Error("ajv implementation error");if(o.opts.discriminator&&a.discriminator)return;let l=s.let("valid",!1),p=s.let("passing",null),u=s.name("_valid");t.setParams({passing:p}),s.block(function(){n.forEach((n,a)=>{let c;(0,i.alwaysValidSchema)(o,n)?s.var(u,!0):c=t.subschema({keyword:"oneOf",schemaProp:a,compositeRule:!0},u),a>0&&s.if(r._`${u} && ${l}`).assign(l,!1).assign(p,r._`[${p}, ${a}]`).else(),s.if(u,()=>{s.assign(l,!0),s.assign(p,a),c&&t.mergeEvaluated(c,r.Name)})})}),t.result(l,()=>t.reset(),()=>t.error(!0))}}}),ip=ro(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=rg();t.default={keyword:"allOf",schemaType:"array",code(t){let{gen:i,schema:s,it:n}=t;if(!Array.isArray(s))throw Error("ajv implementation error");let a=i.name("valid");s.forEach((i,s)=>{if((0,r.alwaysValidSchema)(n,i))return;let o=t.subschema({keyword:"allOf",schemaProp:s},a);t.ok(a),t.mergeEvaluated(o)})}}}),iu=ro(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=rb(),i=rg();function s(t,r){let s=t.schema[r];return void 0!==s&&!(0,i.alwaysValidSchema)(t,s)}t.default={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:{message:({params:t})=>r.str`must match "${t.ifClause}" schema`,params:({params:t})=>r._`{failingKeyword: ${t.ifClause}}`},code(t){let n,{gen:a,parentSchema:o,it:l}=t;void 0===o.then&&void 0===o.else&&(0,i.checkStrictMode)(l,'"if" without "then" and "else" is ignored');let p=s(l,"then"),u=s(l,"else");if(!p&&!u)return;let c=a.let("valid",!0),d=a.name("_valid");if(n=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},d),t.mergeEvaluated(n),t.reset(),p&&u){let r=a.let("ifClause");t.setParams({ifClause:r}),a.if(d,h("then",r),h("else",r))}else p?a.if(d,h("then")):a.if((0,r.not)(d),h("else"));function h(i,s){return()=>{let n=t.subschema({keyword:i},d);(a.assign(c,d),t.mergeValidEvaluated(n,c),s)?a.assign(s,r._`${i}`):t.setParams({ifClause:i})}}t.pass(c,()=>t.error(!0))}}}),ic=ro(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=rg();t.default={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:i,it:s}){void 0===i.if&&(0,r.checkStrictMode)(s,`"${t}" without "if" is ignored`)}}}),id=ro(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=r8(),i=r9(),s=r7(),n=r5(),a=r6(),o=ie(),l=it(),p=ir(),u=ii(),c=is(),d=ia(),h=io(),f=il(),m=ip(),y=iu(),b=ic();t.default=function(t=!1){let g=[d.default,h.default,f.default,m.default,y.default,b.default,l.default,p.default,o.default,u.default,c.default];return t?g.push(i.default,n.default):g.push(r.default,s.default),g.push(a.default),g}}),ih=ro(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=rb();t.default={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode:t})=>r.str`must match format "${t}"`,params:({schemaCode:t})=>r._`{format: ${t}}`},code(t,i){let s,n,a,o,l,p,{gen:u,data:c,$data:d,schema:h,schemaCode:f,it:m}=t,{opts:y,errSchemaPath:b,schemaEnv:g,self:v}=m;y.validateFormats&&(d?(s=u.scopeValue("formats",{ref:v.formats,code:y.code.formats}),n=u.const("fDef",r._`${s}[${f}]`),a=u.let("fType"),o=u.let("format"),u.if(r._`typeof ${n} == "object" && !(${n} instanceof RegExp)`,()=>u.assign(a,r._`${n}.type || "string"`).assign(o,r._`${n}.validate`),()=>u.assign(a,r._`"string"`).assign(o,n)),t.fail$data((0,r.or)(!1===y.strictSchema?r.nil:r._`${f} && !${o}`,(l=g.$async?r._`(${n}.async ? await ${o}(${c}) : ${o}(${c}))`:r._`${o}(${c})`,p=r._`(typeof ${o} == "function" ? ${l} : ${o}.test(${c}))`,r._`${o} && ${o} !== true && ${a} === ${i} && !${p}`)))):function(){var s;let n,a,o=v.formats[h];if(!o){if(!1===y.strictSchema)return v.logger.warn(l());throw Error(l());function l(){return`unknown format "${h}" ignored in schema at path "${b}"`}}if(!0===o)return;let[p,d,f]=(n=(s=o)instanceof RegExp?(0,r.regexpCode)(s):y.code.formats?r._`${y.code.formats}${(0,r.getProperty)(h)}`:void 0,a=u.scopeValue("formats",{key:h,ref:s,code:n}),"object"!=typeof s||s instanceof RegExp?["string",s,a]:[s.type||"string",s.validate,r._`${a}.validate`]);p===i&&t.pass(function(){if("object"==typeof o&&!(o instanceof RegExp)&&o.async){if(!g.$async)throw Error("async format in sync schema");return r._`await ${f}(${c})`}return"function"==typeof d?r._`${f}(${c})`:r._`${f}.test(${c})`}())}())}}}),im=ro(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=[ih().default]}),iy=ro(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.contentVocabulary=t.metadataVocabulary=void 0,t.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],t.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]}),ib=ro(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=rz(),i=r3(),s=id(),n=im(),a=iy();t.default=[r.default,i.default,(0,s.default)(),n.default,a.metadataVocabulary,a.contentVocabulary]}),ig=ro(t=>{var r,i;Object.defineProperty(t,"__esModule",{value:!0}),t.DiscrError=void 0,(i=r||(t.DiscrError=r={})).Tag="tag",i.Mapping="mapping"}),iv=ro(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=rb(),i=ig(),s=rL(),n=rj(),a=rg();t.default={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError:t,tagName:r}})=>t===i.DiscrError.Tag?`tag "${r}" must be string`:`value of tag "${r}" must be in oneOf`,params:({params:{discrError:t,tag:i,tagName:s}})=>r._`{error: ${t}, tag: ${s}, tagValue: ${i}}`},code(t){let{gen:o,data:l,schema:p,parentSchema:u,it:c}=t,{oneOf:d}=u;if(!c.opts.discriminator)throw Error("discriminator: requires discriminator option");let h=p.propertyName;if("string"!=typeof h)throw Error("discriminator: requires propertyName");if(p.mapping)throw Error("discriminator: mapping is not supported");if(!d)throw Error("discriminator: requires oneOf keyword");let f=o.let("valid",!1),m=o.const("tag",r._`${l}${(0,r.getProperty)(h)}`);o.if(r._`typeof ${m} == "string"`,()=>(function(){let l=function(){var t;let r={},i=l(u),o=!0;for(let r=0;r<d.length;r++){let u=d[r];if((null==u?void 0:u.$ref)&&!(0,a.schemaHasRulesButRef)(u,c.self.RULES)){let t=u.$ref;if((u=s.resolveRef.call(c.self,c.schemaEnv.root,c.baseId,t))instanceof s.SchemaEnv&&(u=u.schema),void 0===u)throw new n.default(c.opts.uriResolver,c.baseId,t)}let f=null==(t=null==u?void 0:u.properties)?void 0:t[h];if("object"!=typeof f)throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${h}"`);o=o&&(i||l(u)),function(t,r){if(t.const)p(t.const,r);else if(t.enum)for(let i of t.enum)p(i,r);else throw Error(`discriminator: "properties/${h}" must have "const" or "enum"`)}(f,r)}if(!o)throw Error(`discriminator: "${h}" must be required`);return r;function l({required:t}){return Array.isArray(t)&&t.includes(h)}function p(t,i){if("string"!=typeof t||t in r)throw Error(`discriminator: "${h}" values must be unique strings`);r[t]=i}}();for(let i in o.if(!1),l)o.elseIf(r._`${m} === ${i}`),o.assign(f,function(i){let s=o.name("valid"),n=t.subschema({keyword:"oneOf",schemaProp:i},s);return t.mergeEvaluated(n,r.Name),s}(l[i]));o.else(),t.error(!1,{discrError:i.DiscrError.Mapping,tag:m,tagName:h}),o.endIf()})(),()=>t.error(!1,{discrError:i.DiscrError.Tag,tag:m,tagName:h})),t.ok(f)}}}),ix=ro((t,r)=>{r.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}}),iT=ro((t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MissingRefError=t.ValidationError=t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=t.Ajv=void 0;var i=rV(),s=ib(),n=iv(),a=ix(),o=["/properties"],l="http://json-schema.org/draft-07/schema";class p extends i.default{_addVocabularies(){super._addVocabularies(),s.default.forEach(t=>this.addVocabulary(t)),this.opts.discriminator&&this.addKeyword(n.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let t=this.opts.$data?this.$dataMetaSchema(a,o):a;this.addMetaSchema(t,l,!1),this.refs["http://json-schema.org/schema"]=l}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(l)?l:void 0)}}t.Ajv=p,r.exports=t=p,r.exports.Ajv=p,Object.defineProperty(t,"__esModule",{value:!0}),t.default=p;var u=rO();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return u.KeywordCxt}});var c=rb();Object.defineProperty(t,"_",{enumerable:!0,get:function(){return c._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return c.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return c.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return c.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return c.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return c.CodeGen}});var d=rD();Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return d.default}});var h=rj();Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return h.default}})}),iE=ro(t=>{function r(t,r){return{validate:t,compare:r}}Object.defineProperty(t,"__esModule",{value:!0}),t.formatNames=t.fastFormats=t.fullFormats=void 0,t.fullFormats={date:r(n,a),time:r(l(!0),p),"date-time":r(d(!0),h),"iso-time":r(l(),u),"iso-date-time":r(d(),f),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:function(t){return m.test(t)&&y.test(t)},"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:function(t){if(v.test(t))return!1;try{return new RegExp(t),!0}catch(t){return!1}},uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:function(t){return b.lastIndex=0,b.test(t)},int32:{type:"number",validate:function(t){return Number.isInteger(t)&&t<=0x7fffffff&&t>=-0x80000000}},int64:{type:"number",validate:function(t){return Number.isInteger(t)}},float:{type:"number",validate:g},double:{type:"number",validate:g},password:!0,binary:!0},t.fastFormats={...t.fullFormats,date:r(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,a),time:r(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,p),"date-time":r(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,h),"iso-time":r(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,u),"iso-date-time":r(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,f),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},t.formatNames=Object.keys(t.fullFormats);var i=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,s=[0,31,28,31,30,31,30,31,31,30,31,30,31];function n(t){var r;let n=i.exec(t);if(!n)return!1;let a=+n[1],o=+n[2],l=+n[3];return o>=1&&o<=12&&l>=1&&l<=(2===o&&(r=a)%4==0&&(r%100!=0||r%400==0)?29:s[o])}function a(t,r){if(t&&r)return t>r?1:t<r?-1:0}var o=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function l(t){return function(r){let i=o.exec(r);if(!i)return!1;let s=+i[1],n=+i[2],a=+i[3],l=i[4],p="-"===i[5]?-1:1,u=+(i[6]||0),c=+(i[7]||0);if(u>23||c>59||t&&!l)return!1;if(s<=23&&n<=59&&a<60)return!0;let d=n-c*p,h=s-u*p-(d<0);return(23===h||-1===h)&&(59===d||-1===d)&&a<61}}function p(t,r){if(!(t&&r))return;let i=new Date("2020-01-01T"+t).valueOf(),s=new Date("2020-01-01T"+r).valueOf();if(i&&s)return i-s}function u(t,r){if(!(t&&r))return;let i=o.exec(t),s=o.exec(r);if(i&&s)return(t=i[1]+i[2]+i[3])>(r=s[1]+s[2]+s[3])?1:t<r?-1:0}var c=/t|\s/i;function d(t){let r=l(t);return function(t){let i=t.split(c);return 2===i.length&&n(i[0])&&r(i[1])}}function h(t,r){if(!(t&&r))return;let i=new Date(t).valueOf(),s=new Date(r).valueOf();if(i&&s)return i-s}function f(t,r){if(!(t&&r))return;let[i,s]=t.split(c),[n,o]=r.split(c),l=a(i,n);if(void 0!==l)return l||p(s,o)}var m=/\/|:/,y=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,b=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function g(){return!0}var v=/[^\\]\\Z/}),iS=ro(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.formatLimitDefinition=void 0;var r=iT(),i=rb(),s=i.operators,n={formatMaximum:{okStr:"<=",ok:s.LTE,fail:s.GT},formatMinimum:{okStr:">=",ok:s.GTE,fail:s.LT},formatExclusiveMaximum:{okStr:"<",ok:s.LT,fail:s.GTE},formatExclusiveMinimum:{okStr:">",ok:s.GT,fail:s.LTE}};t.formatLimitDefinition={keyword:Object.keys(n),type:"string",schemaType:"string",$data:!0,error:{message:({keyword:t,schemaCode:r})=>i.str`should be ${n[t].okStr} ${r}`,params:({keyword:t,schemaCode:r})=>i._`{comparison: ${n[t].okStr}, limit: ${r}}`},code(t){let s,a,{gen:o,data:l,schemaCode:p,keyword:u,it:c}=t,{opts:d,self:h}=c;if(!d.validateFormats)return;let f=new r.KeywordCxt(c,h.RULES.all.format.definition,"format");function m(t){return i._`${t}.compare(${l}, ${p}) ${n[u].fail} 0`}f.$data?(s=o.scopeValue("formats",{ref:h.formats,code:d.code.formats}),a=o.const("fmt",i._`${s}[${f.schemaCode}]`),t.fail$data((0,i.or)(i._`typeof ${a} != "object"`,i._`${a} instanceof RegExp`,i._`typeof ${a}.compare != "function"`,m(a)))):function(){let r=f.schema,s=h.formats[r];if(!s||!0===s)return;if("object"!=typeof s||s instanceof RegExp||"function"!=typeof s.compare)throw Error(`"${u}": format "${r}" does not define "compare" function`);let n=o.scopeValue("formats",{key:r,ref:s,code:d.code.formats?i._`${d.code.formats}${(0,i.getProperty)(r)}`:void 0});t.fail$data(m(n))}()},dependencies:["format"]},t.default=r=>(r.addKeyword(t.formatLimitDefinition),r)}),i_=ro((t,r)=>{Object.defineProperty(t,"__esModule",{value:!0});var i=iE(),s=iS(),n=rb(),a=new n.Name("fullFormats"),o=new n.Name("fastFormats"),l=(t,r={keywords:!0})=>{if(Array.isArray(r))return p(t,r,i.fullFormats,a),t;let[n,l]="fast"===r.mode?[i.fastFormats,o]:[i.fullFormats,a];return p(t,r.formats||i.formatNames,n,l),r.keywords&&(0,s.default)(t),t};function p(t,r,i,s){var a;for(let o of(null!=(a=t.opts.code).formats||(a.formats=n._`require("ajv-formats/dist/formats").${s}`),r))t.addFormat(o,i[o])}l.get=(t,r="full")=>{let s=("fast"===r?i.fastFormats:i.fullFormats)[t];if(!s)throw Error(`Unknown format "${t}"`);return s},r.exports=t=l,Object.defineProperty(t,"__esModule",{value:!0}),t.default=l});function iP(t=50){let r=new AbortController;return(0,t0.setMaxListeners)(t,r.signal),r}class iA extends Error{}function iw(){return void 0!==process.versions.bun}var iC=t.g&&t.g.Object===Object&&t.g,iI="object"==typeof self&&self&&self.Object===Object&&self,ik=iC||iI||Function("return this")(),iN=ik.Symbol,iO=Object.prototype,iD=iO.hasOwnProperty,ij=iO.toString,iL=iN?iN.toStringTag:void 0,iR=function(t){var r=iD.call(t,iL),i=t[iL];try{t[iL]=void 0;var s=!0}catch(t){}var n=ij.call(t);return s&&(r?t[iL]=i:delete t[iL]),n},iM=Object.prototype.toString,iF=iN?iN.toStringTag:void 0,iB=function(t){return null==t?void 0===t?"[object Undefined]":"[object Null]":iF&&iF in Object(t)?iR(t):iM.call(t)},iU=function(t){var r=typeof t;return null!=t&&("object"==r||"function"==r)},i$=function(t){if(!iU(t))return!1;var r=iB(t);return"[object Function]"==r||"[object GeneratorFunction]"==r||"[object AsyncFunction]"==r||"[object Proxy]"==r},iV=ik["__core-js_shared__"],iK=(si=/[^.]+$/.exec(iV&&iV.keys&&iV.keys.IE_PROTO||""))?"Symbol(src)_1."+si:"",iq=Function.prototype.toString,iz=function(t){if(null!=t){try{return iq.call(t)}catch(t){}try{return t+""}catch(t){}}return""},iW=/^\[object .+?Constructor\]$/,iH=Object.prototype,iJ=Function.prototype.toString,iY=iH.hasOwnProperty,iX=RegExp("^"+iJ.call(iY).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),iG=function(t){return!!iU(t)&&(!iK||!(iK in t))&&(i$(t)?iX:iW).test(iz(t))},iZ=function(t,r){var i=null==t?void 0:t[r];return iG(i)?i:void 0},iQ=iZ(Object,"create"),i0=Object.prototype.hasOwnProperty,i1=Object.prototype.hasOwnProperty;function i2(t){var r=-1,i=null==t?0:t.length;for(this.clear();++r<i;){var s=t[r];this.set(s[0],s[1])}}i2.prototype.clear=function(){this.__data__=iQ?iQ(null):{},this.size=0},i2.prototype.delete=function(t){var r=this.has(t)&&delete this.__data__[t];return this.size-=!!r,r},i2.prototype.get=function(t){var r=this.__data__;if(iQ){var i=r[t];return"__lodash_hash_undefined__"===i?void 0:i}return i0.call(r,t)?r[t]:void 0},i2.prototype.has=function(t){var r=this.__data__;return iQ?void 0!==r[t]:i1.call(r,t)},i2.prototype.set=function(t,r){var i=this.__data__;return this.size+=+!this.has(t),i[t]=iQ&&void 0===r?"__lodash_hash_undefined__":r,this};var i4=function(t,r){for(var i,s=t.length;s--;)if((i=t[s][0])===r||i!=i&&r!=r)return s;return -1},i3=Array.prototype.splice;function i8(t){var r=-1,i=null==t?0:t.length;for(this.clear();++r<i;){var s=t[r];this.set(s[0],s[1])}}i8.prototype.clear=function(){this.__data__=[],this.size=0},i8.prototype.delete=function(t){var r=this.__data__,i=i4(r,t);return!(i<0)&&(i==r.length-1?r.pop():i3.call(r,i,1),--this.size,!0)},i8.prototype.get=function(t){var r=this.__data__,i=i4(r,t);return i<0?void 0:r[i][1]},i8.prototype.has=function(t){return i4(this.__data__,t)>-1},i8.prototype.set=function(t,r){var i=this.__data__,s=i4(i,t);return s<0?(++this.size,i.push([t,r])):i[s][1]=r,this};var i7=iZ(ik,"Map"),i9=function(t){var r=typeof t;return"string"==r||"number"==r||"symbol"==r||"boolean"==r?"__proto__"!==t:null===t},i5=function(t,r){var i=t.__data__;return i9(r)?i["string"==typeof r?"string":"hash"]:i.map};function i6(t){var r=-1,i=null==t?0:t.length;for(this.clear();++r<i;){var s=t[r];this.set(s[0],s[1])}}function se(t,r){if("function"!=typeof t||null!=r&&"function"!=typeof r)throw TypeError("Expected a function");var i=function(){var s=arguments,n=r?r.apply(this,s):s[0],a=i.cache;if(a.has(n))return a.get(n);var o=t.apply(this,s);return i.cache=a.set(n,o)||a,o};return i.cache=new(se.Cache||i6),i}i6.prototype.clear=function(){this.size=0,this.__data__={hash:new i2,map:new(i7||i8),string:new i2}},i6.prototype.delete=function(t){var r=i5(this,t).delete(t);return this.size-=!!r,r},i6.prototype.get=function(t){return i5(this,t).get(t)},i6.prototype.has=function(t){return i5(this,t).has(t)},i6.prototype.set=function(t,r){var i=i5(this,t),s=i.size;return i.set(t,r),this.size+=+(i.size!=s),this},se.Cache=i6;var st=se(()=>(process.env.CLAUDE_CONFIG_DIR??(0,tV.join)((0,t3.homedir)(),".claude")).normalize("NFC"),()=>process.env.CLAUDE_CONFIG_DIR);function sr(t){return!!t&&("boolean"==typeof t?t:["1","true","yes","on"].includes(t.toLowerCase().trim()))}var si,ss,sn=null;function sa(t){if(null===ss)return;let r=`${new Date().toISOString()} ${t}
|
|
361
|
-
`;(function(){if(
|
|
362
|
-
`),
|
|
363
|
-
`;if(sm()){var s;return void(s=process.stderr,!s.destroyed&&s.write(i))}(function(){if(!sb){var t;let r=null;sb=function({writeFn:t,flushIntervalMs:r=1e3,maxBufferSize:i=100,maxBufferBytes:s=1/0,immediateMode:n=!1}){let a=[],o=0,l=null,p=null;function u(){l&&(clearTimeout(l),l=null)}function c(){p&&(t(p.join("")),p=null),0!==a.length&&(t(a.join("")),a=[],o=0,u())}return{write(d){n?t(d):(a.push(d),o+=d.length,l||(l=setTimeout(c,r)),(a.length>=i||o>=s)&&function(){if(p){p.push(...a),a=[],o=0,u();return}let r=a;a=[],o=0,u(),p=r,setImmediate(()=>{let r=p;p=null,r&&t(r.join(""))})}())},flush:c,dispose(){c()}}}({writeFn:t=>{let i=sv(),s=(0,tV.dirname)(i);if(r!==s){try{sl.mkdirSync(s)}catch{}r=s}sl.appendFileSync(i,t),sx()},flushIntervalMs:1e3,maxBufferSize:100,immediateMode:sh()}),t=async()=>sb?.dispose(),su.add(t)}return sb})().write(i)}function sv(){return sy()??process.env.CLAUDE_CODE_DEBUG_LOGS_DIR??(0,tV.join)(st(),"debug",`${sp.sessionId}.txt`)}var sx=se(()=>{try{let t=sv(),r=(0,tV.dirname)(t),i=(0,tV.join)(r,"latest");try{sl.mkdirSync(r)}catch{}try{sl.unlinkSync(i)}catch{}sl.symlinkSync(t,i)}catch{}});let sT=process.env.CLAUDE_CODE_SLOW_OPERATION_THRESHOLD_MS;if(void 0!==sT){let t=Number(sT);!Number.isNaN(t)}var sE={[Symbol.dispose](){}},sS=function(){return sE};function s_(t,r,i){let s=[];try{return rh(s,sS`JSON.stringify(${t})`,0),JSON.stringify(t,r,i)}catch(t){var n=t,a=1}finally{rf(s,n,a)}}var sP=(t,r)=>{let i=[];try{return rh(i,sS`JSON.parse(${t})`,0),typeof r>"u"?JSON.parse(t):JSON.parse(t,r)}catch(t){var s=t,n=1}finally{rf(i,s,n)}};class sA{options;process;processStdin;processStdout;ready=!1;abortController;exitError;exitListeners=[];processExitHandler;abortHandler;constructor(t){this.options=t,this.abortController=t.abortController||iP(),this.initialize()}getDefaultExecutable(){return iw()?"bun":"node"}spawnLocalProcess(t){let{command:r,args:i,cwd:s,env:n,signal:a}=t,o=n.DEBUG_CLAUDE_AGENT_SDK||this.options.stderr?"pipe":"ignore",l=(0,t1.spawn)(r,i,{cwd:s,stdio:["pipe","pipe",o],signal:a,env:n,windowsHide:!0});return(n.DEBUG_CLAUDE_AGENT_SDK||this.options.stderr)&&l.stderr.on("data",t=>{let r=t.toString();sa(r),this.options.stderr&&this.options.stderr(r)}),{stdin:l.stdin,stdout:l.stdout,get killed(){return l.killed},get exitCode(){return l.exitCode},kill:l.kill.bind(l),on:l.on.bind(l),once:l.once.bind(l),off:l.off.bind(l)}}initialize(){try{var t;let{additionalDirectories:r=[],agent:i,betas:s,cwd:n,executable:a=this.getDefaultExecutable(),executableArgs:o=[],extraArgs:l={},pathToClaudeCodeExecutable:p,env:u={...process.env},thinkingConfig:c,maxTurns:d,maxBudgetUsd:h,model:f,fallbackModel:m,jsonSchema:y,permissionMode:b,allowDangerouslySkipPermissions:g,permissionPromptToolName:v,continueConversation:x,resume:T,settingSources:E,allowedTools:S=[],disallowedTools:_=[],tools:P,mcpServers:A,strictMcpConfig:w,canUseTool:C,includePartialMessages:I,plugins:k,sandbox:N}=this.options,O=["--output-format","stream-json","--verbose","--input-format","stream-json"];if(c)switch(c.type){case"enabled":void 0===c.budgetTokens?O.push("--thinking","adaptive"):O.push("--max-thinking-tokens",c.budgetTokens.toString());break;case"disabled":O.push("--thinking","disabled");break;case"adaptive":O.push("--thinking","adaptive")}if(this.options.effort&&O.push("--effort",this.options.effort),d&&O.push("--max-turns",d.toString()),void 0!==h&&O.push("--max-budget-usd",h.toString()),f&&O.push("--model",f),i&&O.push("--agent",i),s&&s.length>0&&O.push("--betas",s.join(",")),y&&O.push("--json-schema",s_(y)),this.options.debugFile?O.push("--debug-file",this.options.debugFile):this.options.debug&&O.push("--debug"),u.DEBUG_CLAUDE_AGENT_SDK&&O.push("--debug-to-stderr"),C){if(v)throw Error("canUseTool callback cannot be used with permissionPromptToolName. Please use one or the other.");O.push("--permission-prompt-tool","stdio")}else v&&O.push("--permission-prompt-tool",v);if(x&&O.push("--continue"),T&&O.push("--resume",T),this.options.proactive&&O.push("--proactive"),this.options.assistant&&O.push("--assistant"),S.length>0&&O.push("--allowedTools",S.join(",")),_.length>0&&O.push("--disallowedTools",_.join(",")),void 0!==P&&(Array.isArray(P)?0===P.length?O.push("--tools",""):O.push("--tools",P.join(",")):O.push("--tools","default")),A&&Object.keys(A).length>0&&O.push("--mcp-config",s_({mcpServers:A})),E&&O.push("--setting-sources",E.join(",")),w&&O.push("--strict-mcp-config"),b&&O.push("--permission-mode",b),g&&O.push("--allow-dangerously-skip-permissions"),m){if(f&&m===f)throw Error("Fallback model cannot be the same as the main model. Please specify a different model for fallbackModel option.");O.push("--fallback-model",m)}for(let t of(I&&O.push("--include-partial-messages"),r))O.push("--add-dir",t);if(k&&k.length>0)for(let t of k)if("local"===t.type)O.push("--plugin-dir",t.path);else throw Error(`Unsupported plugin type: ${t.type}`);this.options.forkSession&&O.push("--fork-session"),this.options.resumeSessionAt&&O.push("--resume-session-at",this.options.resumeSessionAt),this.options.sessionId&&O.push("--session-id",this.options.sessionId),!1===this.options.persistSession&&O.push("--no-session-persistence");let D={...l??{}};this.options.settings&&(D.settings=this.options.settings);let j=function(t,r){let i={...t};if(r){let t,s=i.settings;if(s&&!((t=s.trim()).startsWith("{")&&t.endsWith("}")))throw Error("Cannot use both a settings file path and the sandbox option. Include the sandbox configuration in your settings file instead.");let n={sandbox:r};if(s)try{n={...sP(s),sandbox:r}}catch{}i.settings=s_(n)}return i}(D,N);for(let[t,r]of Object.entries(j))null===r?O.push(`--${t}`):O.push(`--${t}`,r);u.CLAUDE_CODE_ENTRYPOINT||(u.CLAUDE_CODE_ENTRYPOINT="sdk-ts"),(delete u.NODE_OPTIONS,u.DEBUG_CLAUDE_AGENT_SDK)?u.DEBUG="1":delete u.DEBUG;let L=(t=p,![".js",".mjs",".tsx",".ts",".jsx"].some(r=>t.endsWith(r))),R=L?p:a,M=L?[...o,...O]:[...o,p,...O],F={command:R,args:M,cwd:n,env:u,signal:this.abortController.signal};this.options.spawnClaudeCodeProcess?(sa(`Spawning Claude Code (custom): ${R} ${M.join(" ")}`),this.process=this.options.spawnClaudeCodeProcess(F)):(sa(`Spawning Claude Code: ${R} ${M.join(" ")}`),this.process=this.spawnLocalProcess(F)),this.processStdin=this.process.stdin,this.processStdout=this.process.stdout;let B=()=>{this.process&&!this.process.killed&&this.process.kill("SIGTERM")};this.processExitHandler=B,this.abortHandler=B,process.on("exit",this.processExitHandler),this.abortController.signal.addEventListener("abort",this.abortHandler),this.process.on("error",t=>{if(this.ready=!1,this.abortController.signal.aborted)this.exitError=new iA("Claude Code process aborted by user");else if("ENOENT"===t.code){let t=L?`Claude Code native binary not found at ${p}. Please ensure Claude Code is installed via native installer or specify a valid path with options.pathToClaudeCodeExecutable.`:`Claude Code executable not found at ${p}. Is options.pathToClaudeCodeExecutable set?`;this.exitError=ReferenceError(t),sa(this.exitError.message)}else this.exitError=Error(`Failed to spawn Claude Code process: ${t.message}`),sa(this.exitError.message)}),this.process.on("exit",(t,r)=>{if(this.ready=!1,this.abortController.signal.aborted)this.exitError=new iA("Claude Code process aborted by user");else{let i=this.getProcessExitError(t,r);i&&(this.exitError=i,sa(i.message))}}),this.ready=!0}catch(t){throw this.ready=!1,t}}getProcessExitError(t,r){return 0!==t&&null!==t?Error(`Claude Code process exited with code ${t}`):r?Error(`Claude Code process terminated by signal ${r}`):void 0}write(t){if(this.abortController.signal.aborted)throw new iA("Operation aborted");if(!this.ready||!this.processStdin)throw Error("ProcessTransport is not ready for writing");if(this.process?.killed||this.process?.exitCode!==null)throw Error("Cannot write to terminated process");if(this.exitError)throw Error(`Cannot write to process that exited with error: ${this.exitError.message}`);sa(`[ProcessTransport] Writing to stdin: ${t.substring(0,100)}`);try{this.processStdin.write(t)||sa("[ProcessTransport] Write buffer full, data queued")}catch(t){throw this.ready=!1,Error(`Failed to write to process stdin: ${t.message}`)}}close(){for(let{handler:t}of(this.processStdin&&(this.processStdin.end(),this.processStdin=void 0),this.abortHandler&&(this.abortController.signal.removeEventListener("abort",this.abortHandler),this.abortHandler=void 0),this.exitListeners))this.process?.off("exit",t);this.exitListeners=[],this.process&&!this.process.killed&&null===this.process.exitCode&&(this.process.kill("SIGTERM"),setTimeout(()=>{this.process&&!this.process.killed&&this.process.kill("SIGKILL")},5e3).unref()),this.ready=!1,this.processExitHandler&&(process.off("exit",this.processExitHandler),this.processExitHandler=void 0)}isReady(){return this.ready}async *readMessages(){if(!this.processStdout)throw Error("ProcessTransport output stream not available");let t=(0,t2.createInterface)({input:this.processStdout});try{for await(let r of t)if(r.trim())try{yield sP(r)}catch(t){throw sa(`Non-JSON stdout: ${r}`),Error(`CLI output was not valid JSON. This may indicate an error during startup. Output: ${r.slice(0,200)}${r.length>200?"...":""}`)}await this.waitForExit()}catch(t){throw t}finally{t.close()}}endInput(){this.processStdin&&this.processStdin.end()}getInputStream(){return this.processStdin}onExit(t){if(!this.process)return()=>{};let r=(r,i)=>{t(this.getProcessExitError(r,i))};return this.process.on("exit",r),this.exitListeners.push({callback:t,handler:r}),()=>{this.process&&this.process.off("exit",r);let t=this.exitListeners.findIndex(t=>t.handler===r);-1!==t&&this.exitListeners.splice(t,1)}}async waitForExit(){if(!this.process||null!==this.process.exitCode||this.process.killed){if(this.exitError)throw this.exitError;return}return new Promise((t,r)=>{let i=(i,s)=>{if(this.abortController.signal.aborted)return void r(new iA("Operation aborted"));let n=this.getProcessExitError(i,s);n?r(n):t()};this.process.once("exit",i);let s=t=>{this.process.off("exit",i),r(t)};this.process.once("error",s),this.process.once("exit",()=>{this.process.off("error",s)})})}}class sw{returned;queue=[];readResolve;readReject;isDone=!1;hasError;started=!1;constructor(t){this.returned=t}[Symbol.asyncIterator](){if(this.started)throw Error("Stream can only be iterated once");return this.started=!0,this}next(){return this.queue.length>0?Promise.resolve({done:!1,value:this.queue.shift()}):this.isDone?Promise.resolve({done:!0,value:void 0}):this.hasError?Promise.reject(this.hasError):new Promise((t,r)=>{this.readResolve=t,this.readReject=r})}enqueue(t){if(this.readResolve){let r=this.readResolve;this.readResolve=void 0,this.readReject=void 0,r({done:!1,value:t})}else this.queue.push(t)}done(){if(this.isDone=!0,this.readResolve){let t=this.readResolve;this.readResolve=void 0,this.readReject=void 0,t({done:!0,value:void 0})}}error(t){if(this.hasError=t,this.readReject){let r=this.readReject;this.readResolve=void 0,this.readReject=void 0,r(t)}}return(){return this.isDone=!0,this.returned&&this.returned(),Promise.resolve({done:!0,value:void 0})}}class sC{sendMcpMessage;isClosed=!1;constructor(t){this.sendMcpMessage=t}onclose;onerror;onmessage;async start(){}async send(t){if(this.isClosed)throw Error("Transport is closed");this.sendMcpMessage(t)}async close(){this.isClosed||(this.isClosed=!0,this.onclose?.())}}class sI{transport;isSingleUserTurn;canUseTool;hooks;abortController;jsonSchema;initConfig;onElicitation;pendingControlResponses=new Map;cleanupPerformed=!1;sdkMessages;inputStream=new sw;initialization;cancelControllers=new Map;hookCallbacks=new Map;nextCallbackId=0;sdkMcpTransports=new Map;sdkMcpServerInstances=new Map;pendingMcpResponses=new Map;firstResultReceivedResolve;firstResultReceived=!1;hasBidirectionalNeeds(){return this.sdkMcpTransports.size>0||void 0!==this.hooks&&Object.keys(this.hooks).length>0||void 0!==this.canUseTool||void 0!==this.onElicitation}constructor(t,r,i,s,n,a=new Map,o,l,p){for(let[u,c]of(this.transport=t,this.isSingleUserTurn=r,this.canUseTool=i,this.hooks=s,this.abortController=n,this.jsonSchema=o,this.initConfig=l,this.onElicitation=p,a))this.connectSdkMcpServer(u,c);this.sdkMessages=this.readSdkMessages(),this.readMessages(),this.initialization=this.initialize(),this.initialization.catch(()=>{})}setError(t){this.inputStream.error(t)}async stopTask(t){await this.request({subtype:"stop_task",task_id:t})}close(){this.cleanup()}cleanup(t){if(!this.cleanupPerformed){this.cleanupPerformed=!0;try{this.transport.close();let r=Error("Query closed before response received");for(let{reject:t}of this.pendingControlResponses.values())t(r);for(let{reject:t}of(this.pendingControlResponses.clear(),this.pendingMcpResponses.values()))t(r);for(let t of(this.pendingMcpResponses.clear(),this.cancelControllers.clear(),this.hookCallbacks.clear(),this.sdkMcpTransports.values()))try{t.close()}catch{}(this.sdkMcpTransports.clear(),t)?this.inputStream.error(t):this.inputStream.done()}catch(t){}}}next(...[t]){return this.sdkMessages.next(t)}return(t){return this.sdkMessages.return(t)}throw(t){return this.sdkMessages.throw(t)}[Symbol.asyncIterator](){return this.sdkMessages}[Symbol.asyncDispose](){return this.sdkMessages[Symbol.asyncDispose]()}async readMessages(){try{for await(let t of this.transport.readMessages()){if("control_response"===t.type){let r=this.pendingControlResponses.get(t.response.request_id);r&&r.handler(t.response);continue}if("control_request"===t.type){this.handleControlRequest(t);continue}if("control_cancel_request"===t.type){this.handleControlCancelRequest(t);continue}else if("keep_alive"===t.type)continue;"streamlined_text"!==t.type&&"streamlined_tool_use_summary"!==t.type&&("result"===t.type&&(this.firstResultReceived=!0,this.firstResultReceivedResolve&&this.firstResultReceivedResolve(),this.isSingleUserTurn&&(sg("[Query.readMessages] First result received for single-turn query, closing stdin"),this.transport.endInput())),this.inputStream.enqueue(t))}this.firstResultReceivedResolve&&this.firstResultReceivedResolve(),this.inputStream.done(),this.cleanup()}catch(t){this.firstResultReceivedResolve&&this.firstResultReceivedResolve(),this.inputStream.error(t),this.cleanup(t)}}async handleControlRequest(t){let r=new AbortController;this.cancelControllers.set(t.request_id,r);try{let i=await this.processControlRequest(t,r.signal),s={type:"control_response",response:{subtype:"success",request_id:t.request_id,response:i}};await Promise.resolve(this.transport.write(s_(s)+`
|
|
364
|
-
`))}catch(i){let r={type:"control_response",response:{subtype:"error",request_id:t.request_id,error:i.message||String(i)}};await Promise.resolve(this.transport.write(
|
|
365
|
-
`))}finally{this.cancelControllers.delete(t.request_id)}}handleControlCancelRequest(t){let r=this.cancelControllers.get(t.request_id);r&&(r.abort(),this.cancelControllers.delete(t.request_id))}async processControlRequest(t,r){if("can_use_tool"===t.request.subtype){if(!this.canUseTool)throw Error("canUseTool callback is not provided.");return{...await this.canUseTool(t.request.tool_name,t.request.input,{signal:r,suggestions:t.request.permission_suggestions,blockedPath:t.request.blocked_path,decisionReason:t.request.decision_reason,toolUseID:t.request.tool_use_id,agentID:t.request.agent_id}),toolUseID:t.request.tool_use_id}}if("hook_callback"===t.request.subtype)return await this.handleHookCallbacks(t.request.callback_id,t.request.input,t.request.tool_use_id,r);if("mcp_message"===t.request.subtype){let r=t.request,i=this.sdkMcpTransports.get(r.server_name);if(!i)throw Error(`SDK MCP server not found: ${r.server_name}`);return"method"in r.message&&"id"in r.message&&null!==r.message.id?{mcp_response:await this.handleMcpControlRequest(r.server_name,r,i)}:(i.onmessage&&i.onmessage(r.message),{mcp_response:{jsonrpc:"2.0",result:{},id:0}})}if("elicitation"===t.request.subtype){let i=t.request;return this.onElicitation?await this.onElicitation({serverName:i.mcp_server_name,message:i.message,mode:i.mode,url:i.url,elicitationId:i.elicitation_id,requestedSchema:i.requested_schema},{signal:r}):{action:"decline"}}throw Error("Unsupported control request subtype: "+t.request.subtype)}async *readSdkMessages(){for await(let t of this.inputStream)yield t}async initialize(){let t;if(this.hooks)for(let[r,i]of(t={},Object.entries(this.hooks)))i.length>0&&(t[r]=i.map(t=>{let r=[];for(let i of t.hooks){let t=`hook_${this.nextCallbackId++}`;this.hookCallbacks.set(t,i),r.push(t)}return{matcher:t.matcher,hookCallbackIds:r,timeout:t.timeout}}));let r={subtype:"initialize",hooks:t,sdkMcpServers:this.sdkMcpTransports.size>0?Array.from(this.sdkMcpTransports.keys()):void 0,jsonSchema:this.jsonSchema,systemPrompt:this.initConfig?.systemPrompt,appendSystemPrompt:this.initConfig?.appendSystemPrompt,agents:this.initConfig?.agents,promptSuggestions:this.initConfig?.promptSuggestions,agentProgressSummaries:this.initConfig?.agentProgressSummaries};return(await this.request(r)).response}async interrupt(){await this.request({subtype:"interrupt"})}async setPermissionMode(t){await this.request({subtype:"set_permission_mode",mode:t})}async setModel(t){await this.request({subtype:"set_model",model:t})}async setMaxThinkingTokens(t){await this.request({subtype:"set_max_thinking_tokens",max_thinking_tokens:t})}async applyFlagSettings(t){await this.request({subtype:"apply_flag_settings",settings:t})}async getSettings(){return(await this.request({subtype:"get_settings"})).response}async rewindFiles(t,r){return(await this.request({subtype:"rewind_files",user_message_id:t,dry_run:r?.dryRun})).response}async enableRemoteControl(t){return(await this.request({subtype:"remote_control",enabled:t})).response}async setProactive(t){await this.request({subtype:"set_proactive",enabled:t})}async processPendingPermissionRequests(t){for(let r of t)"can_use_tool"===r.request.subtype&&this.handleControlRequest(r).catch(()=>{})}request(t){let r=Math.random().toString(36).substring(2,15),i={request_id:r,type:"control_request",request:t};return new Promise((t,s)=>{this.pendingControlResponses.set(r,{handler:i=>{(this.pendingControlResponses.delete(r),"success"===i.subtype)?t(i):(s(Error(i.error)),i.pending_permission_requests&&this.processPendingPermissionRequests(i.pending_permission_requests))},reject:s}),Promise.resolve(this.transport.write(
|
|
366
|
-
`))})}async initializationResult(){return this.initialization}async supportedCommands(){return(await this.initialization).commands}async supportedModels(){return(await this.initialization).models}async supportedAgents(){return(await this.initialization).agents}async reconnectMcpServer(t){await this.request({subtype:"mcp_reconnect",serverName:t})}async toggleMcpServer(t,r){await this.request({subtype:"mcp_toggle",serverName:t,enabled:r})}async mcpAuthenticate(t){return(await this.request({subtype:"mcp_authenticate",serverName:t})).response}async mcpClearAuth(t){return(await this.request({subtype:"mcp_clear_auth",serverName:t})).response}async mcpSubmitOAuthCallbackUrl(t,r){return(await this.request({subtype:"mcp_oauth_callback_url",serverName:t,callbackUrl:r})).response}async mcpServerStatus(){return(await this.request({subtype:"mcp_status"})).response.mcpServers}async setMcpServers(t){let r={},i={};for(let[s,n]of Object.entries(t))"sdk"===n.type&&"instance"in n?r[s]=n.instance:i[s]=n;let s=new Set(this.sdkMcpServerInstances.keys()),n=new Set(Object.keys(r));for(let t of s)n.has(t)||await this.disconnectSdkMcpServer(t);for(let[t,i]of Object.entries(r))s.has(t)||this.connectSdkMcpServer(t,i);let a={};for(let t of Object.keys(r))a[t]={type:"sdk",name:t};return(await this.request({subtype:"mcp_set_servers",servers:{...i,...a}})).response}async accountInfo(){return(await this.initialization).account}async streamInput(t){
|
|
367
|
-
`))}
|
|
368
|
-
`)}handleMcpControlRequest(t,r,i){let s="id"in r.message?r.message.id:null,n=`${t}:${s}`;return new Promise((t,s)=>{let a=()=>{this.pendingMcpResponses.delete(n)};if(this.pendingMcpResponses.set(n,{resolve:r=>{a(),t(r)},reject:t=>{a(),s(t)}}),i.onmessage)i.onmessage(r.message);else{a(),s(Error("No message handler registered"));return}})}}(0,t7.promisify)(t1.execFile);var sk={};ru(sk,{void:()=>ao,util:()=>s4,unknown:()=>an,union:()=>ac,undefined:()=>ar,tuple:()=>af,transformer:()=>a_,symbol:()=>at,string:()=>n8,strictObject:()=>au,setErrorMap:()=>sF,set:()=>ab,record:()=>am,quotelessJson:()=>sj,promise:()=>aS,preprocess:()=>aw,pipeline:()=>aC,ostring:()=>aI,optional:()=>aP,onumber:()=>ak,oboolean:()=>aN,objectUtil:()=>s3,object:()=>ap,number:()=>n7,nullable:()=>aA,null:()=>ai,never:()=>aa,nativeEnum:()=>aE,nan:()=>n9,map:()=>ay,makeIssue:()=>sU,literal:()=>ax,lazy:()=>av,late:()=>n4,isValid:()=>sY,isDirty:()=>sJ,isAsync:()=>sX,isAborted:()=>sH,intersection:()=>ah,instanceof:()=>n3,getParsedType:()=>sO,getErrorMap:()=>sB,function:()=>ag,enum:()=>aT,effect:()=>a_,discriminatedUnion:()=>ad,defaultErrorMap:()=>sR,datetimeRegex:()=>nf,date:()=>ae,custom:()=>n1,coerce:()=>aO,boolean:()=>n6,bigint:()=>n5,array:()=>al,any:()=>as,addIssueToContext:()=>sV,ZodVoid:()=>nA,ZodUnknown:()=>n_,ZodUnion:()=>nI,ZodUndefined:()=>nT,ZodType:()=>s0,ZodTuple:()=>nD,ZodTransformer:()=>nq,ZodSymbol:()=>nx,ZodString:()=>nm,ZodSet:()=>nR,ZodSchema:()=>s0,ZodRecord:()=>nj,ZodReadonly:()=>nQ,ZodPromise:()=>nK,ZodPipeline:()=>nZ,ZodParsedType:()=>sN,ZodOptional:()=>nz,ZodObject:()=>nC,ZodNumber:()=>ny,ZodNullable:()=>nW,ZodNull:()=>nE,ZodNever:()=>nP,ZodNativeEnum:()=>nV,ZodNaN:()=>nY,ZodMap:()=>nL,ZodLiteral:()=>nB,ZodLazy:()=>nF,ZodIssueCode:()=>sD,ZodIntersection:()=>nO,ZodFunction:()=>nM,ZodFirstPartyTypeKind:()=>n2,ZodError:()=>sL,ZodEnum:()=>n$,ZodEffects:()=>nq,ZodDiscriminatedUnion:()=>nN,ZodDefault:()=>nH,ZodDate:()=>nv,ZodCatch:()=>nJ,ZodBranded:()=>nG,ZodBoolean:()=>ng,ZodBigInt:()=>nb,ZodArray:()=>nw,ZodAny:()=>nS,Schema:()=>s0,ParseStatus:()=>sK,OK:()=>sW,NEVER:()=>aD,INVALID:()=>sq,EMPTY_PATH:()=>s$,DIRTY:()=>sz,BRAND:()=>nX}),(s1=s4||(s4={})).assertEqual=t=>{},s1.assertIs=function(t){},s1.assertNever=function(t){throw Error()},s1.arrayToEnum=t=>{let r={};for(let i of t)r[i]=i;return r},s1.getValidEnumValues=t=>{let r=s1.objectKeys(t).filter(r=>"number"!=typeof t[t[r]]),i={};for(let s of r)i[s]=t[s];return s1.objectValues(i)},s1.objectValues=t=>s1.objectKeys(t).map(function(r){return t[r]}),s1.objectKeys="function"==typeof Object.keys?t=>Object.keys(t):t=>{let r=[];for(let i in t)Object.prototype.hasOwnProperty.call(t,i)&&r.push(i);return r},s1.find=(t,r)=>{for(let i of t)if(r(i))return i},s1.isInteger="function"==typeof Number.isInteger?t=>Number.isInteger(t):t=>"number"==typeof t&&Number.isFinite(t)&&Math.floor(t)===t,s1.joinValues=function(t,r=" | "){return t.map(t=>"string"==typeof t?`'${t}'`:t).join(r)},s1.jsonStringifyReplacer=(t,r)=>"bigint"==typeof r?r.toString():r,(s3||(s3={})).mergeShapes=(t,r)=>({...t,...r});var sN=s4.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),sO=t=>{switch(typeof t){case"undefined":return sN.undefined;case"string":return sN.string;case"number":return Number.isNaN(t)?sN.nan:sN.number;case"boolean":return sN.boolean;case"function":return sN.function;case"bigint":return sN.bigint;case"symbol":return sN.symbol;case"object":if(Array.isArray(t))return sN.array;if(null===t)return sN.null;if(t.then&&"function"==typeof t.then&&t.catch&&"function"==typeof t.catch)return sN.promise;if("u">typeof Map&&t instanceof Map)return sN.map;if("u">typeof Set&&t instanceof Set)return sN.set;if("u">typeof Date&&t instanceof Date)return sN.date;return sN.object;default:return sN.unknown}},sD=s4.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),sj=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:");class sL extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=t=>{this.issues=[...this.issues,t]},this.addIssues=(t=[])=>{this.issues=[...this.issues,...t]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=t}format(t){let r=t||function(t){return t.message},i={_errors:[]},s=t=>{for(let n of t.issues)if("invalid_union"===n.code)n.unionErrors.map(s);else if("invalid_return_type"===n.code)s(n.returnTypeError);else if("invalid_arguments"===n.code)s(n.argumentsError);else if(0===n.path.length)i._errors.push(r(n));else{let t=i,s=0;for(;s<n.path.length;){let i=n.path[s];s!==n.path.length-1?t[i]=t[i]||{_errors:[]}:(t[i]=t[i]||{_errors:[]},t[i]._errors.push(r(n))),t=t[i],s++}}};return s(this),i}static assert(t){if(!(t instanceof sL))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,s4.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(t=t=>t.message){let r={},i=[];for(let s of this.issues)if(s.path.length>0){let i=s.path[0];r[i]=r[i]||[],r[i].push(t(s))}else i.push(t(s));return{formErrors:i,fieldErrors:r}}get formErrors(){return this.flatten()}}sL.create=t=>new sL(t);var sR=(t,r)=>{let i;switch(t.code){case sD.invalid_type:i=t.received===sN.undefined?"Required":`Expected ${t.expected}, received ${t.received}`;break;case sD.invalid_literal:i=`Invalid literal value, expected ${JSON.stringify(t.expected,s4.jsonStringifyReplacer)}`;break;case sD.unrecognized_keys:i=`Unrecognized key(s) in object: ${s4.joinValues(t.keys,", ")}`;break;case sD.invalid_union:i="Invalid input";break;case sD.invalid_union_discriminator:i=`Invalid discriminator value. Expected ${s4.joinValues(t.options)}`;break;case sD.invalid_enum_value:i=`Invalid enum value. Expected ${s4.joinValues(t.options)}, received '${t.received}'`;break;case sD.invalid_arguments:i="Invalid function arguments";break;case sD.invalid_return_type:i="Invalid function return type";break;case sD.invalid_date:i="Invalid date";break;case sD.invalid_string:"object"==typeof t.validation?"includes"in t.validation?(i=`Invalid input: must include "${t.validation.includes}"`,"number"==typeof t.validation.position&&(i=`${i} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?i=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?i=`Invalid input: must end with "${t.validation.endsWith}"`:s4.assertNever(t.validation):i="regex"!==t.validation?`Invalid ${t.validation}`:"Invalid";break;case sD.too_small:i="array"===t.type?`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:"string"===t.type?`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:"number"===t.type||"bigint"===t.type?`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:"date"===t.type?`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:"Invalid input";break;case sD.too_big:i="array"===t.type?`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:"string"===t.type?`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:"number"===t.type?`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:"bigint"===t.type?`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:"date"===t.type?`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:"Invalid input";break;case sD.custom:i="Invalid input";break;case sD.invalid_intersection_types:i="Intersection results could not be merged";break;case sD.not_multiple_of:i=`Number must be a multiple of ${t.multipleOf}`;break;case sD.not_finite:i="Number must be finite";break;default:i=r.defaultError,s4.assertNever(t)}return{message:i}},sM=sR;function sF(t){sM=t}function sB(){return sM}var sU=t=>{let{data:r,path:i,errorMaps:s,issueData:n}=t,a=[...i,...n.path||[]],o={...n,path:a};if(void 0!==n.message)return{...n,path:a,message:n.message};let l="";for(let t of s.filter(t=>!!t).slice().reverse())l=t(o,{data:r,defaultError:l}).message;return{...n,path:a,message:l}},s$=[];function sV(t,r){let i=sM,s=sU({issueData:r,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,i,i===sR?void 0:sR].filter(t=>!!t)});t.common.issues.push(s)}class sK{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(t,r){let i=[];for(let s of r){if("aborted"===s.status)return sq;"dirty"===s.status&&t.dirty(),i.push(s.value)}return{status:t.value,value:i}}static async mergeObjectAsync(t,r){let i=[];for(let t of r){let r=await t.key,s=await t.value;i.push({key:r,value:s})}return sK.mergeObjectSync(t,i)}static mergeObjectSync(t,r){let i={};for(let s of r){let{key:r,value:n}=s;if("aborted"===r.status||"aborted"===n.status)return sq;"dirty"===r.status&&t.dirty(),"dirty"===n.status&&t.dirty(),"__proto__"!==r.value&&("u">typeof n.value||s.alwaysSet)&&(i[r.value]=n.value)}return{status:t.value,value:i}}}var sq=Object.freeze({status:"aborted"}),sz=t=>({status:"dirty",value:t}),sW=t=>({status:"valid",value:t}),sH=t=>"aborted"===t.status,sJ=t=>"dirty"===t.status,sY=t=>"valid"===t.status,sX=t=>"u">typeof Promise&&t instanceof Promise;(s2=s8||(s8={})).errToObj=t=>"string"==typeof t?{message:t}:t||{},s2.toString=t=>"string"==typeof t?t:t?.message;class sG{constructor(t,r,i,s){this._cachedPath=[],this.parent=t,this.data=r,this._path=i,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}var sZ=(t,r)=>{if(sY(r))return{success:!0,data:r.value};if(!t.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new sL(t.common.issues);return this._error=r,this._error}}};function sQ(t){if(!t)return{};let{errorMap:r,invalid_type_error:i,required_error:s,description:n}=t;if(r&&(i||s))throw Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');return r?{errorMap:r,description:n}:{errorMap:(r,n)=>{let{message:a}=t;return"invalid_enum_value"===r.code?{message:a??n.defaultError}:typeof n.data>"u"?{message:a??s??n.defaultError}:"invalid_type"!==r.code?{message:n.defaultError}:{message:a??i??n.defaultError}},description:n}}class s0{get description(){return this._def.description}_getType(t){return sO(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:sO(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new sK,ctx:{common:t.parent.common,data:t.data,parsedType:sO(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let r=this._parse(t);if(sX(r))throw Error("Synchronous parse encountered promise.");return r}_parseAsync(t){return Promise.resolve(this._parse(t))}parse(t,r){let i=this.safeParse(t,r);if(i.success)return i.data;throw i.error}safeParse(t,r){let i={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:sO(t)},s=this._parseSync({data:t,path:i.path,parent:i});return sZ(i,s)}"~validate"(t){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:sO(t)};if(!this["~standard"].async)try{let i=this._parseSync({data:t,path:[],parent:r});return sY(i)?{value:i.value}:{issues:r.common.issues}}catch(t){t?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:r}).then(t=>sY(t)?{value:t.value}:{issues:r.common.issues})}async parseAsync(t,r){let i=await this.safeParseAsync(t,r);if(i.success)return i.data;throw i.error}async safeParseAsync(t,r){let i={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:sO(t)},s=this._parse({data:t,path:i.path,parent:i});return sZ(i,await (sX(s)?s:Promise.resolve(s)))}refine(t,r){return this._refinement((i,s)=>{let n=t(i),a=()=>s.addIssue({code:sD.custom,..."string"==typeof r||typeof r>"u"?{message:r}:"function"==typeof r?r(i):r});return"u">typeof Promise&&n instanceof Promise?n.then(t=>!!t||(a(),!1)):!!n||(a(),!1)})}refinement(t,r){return this._refinement((i,s)=>!!t(i)||(s.addIssue("function"==typeof r?r(i,s):r),!1))}_refinement(t){return new nq({schema:this,typeName:n2.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return nz.create(this,this._def)}nullable(){return nW.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return nw.create(this)}promise(){return nK.create(this,this._def)}or(t){return nI.create([this,t],this._def)}and(t){return nO.create(this,t,this._def)}transform(t){return new nq({...sQ(this._def),schema:this,typeName:n2.ZodEffects,effect:{type:"transform",transform:t}})}default(t){return new nH({...sQ(this._def),innerType:this,defaultValue:"function"==typeof t?t:()=>t,typeName:n2.ZodDefault})}brand(){return new nG({typeName:n2.ZodBranded,type:this,...sQ(this._def)})}catch(t){return new nJ({...sQ(this._def),innerType:this,catchValue:"function"==typeof t?t:()=>t,typeName:n2.ZodCatch})}describe(t){return new this.constructor({...this._def,description:t})}pipe(t){return nZ.create(this,t)}readonly(){return nQ.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var s1,s2,s4,s3,s8,s7,s9=/^c[^\s-]{8,}$/i,s5=/^[0-9a-z]+$/,s6=/^[0-9A-HJKMNP-TV-Z]{26}$/i,ne=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,nt=/^[a-z0-9_-]{21}$/i,nr=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,ni=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,ns=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,nn=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,na=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,no=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,nl=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,np=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,nu=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nc="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",nd=RegExp(`^${nc}$`);function nh(t){let r="[0-5]\\d";t.precision?r=`${r}\\.\\d{${t.precision}}`:null==t.precision&&(r=`${r}(\\.\\d+)?`);let i=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${r})${i}`}function nf(t){let r=`${nc}T${nh(t)}`,i=[];return i.push(t.local?"Z?":"Z"),t.offset&&i.push("([+-]\\d{2}:?\\d{2})"),r=`${r}(${i.join("|")})`,RegExp(`^${r}$`)}class nm extends s0{_parse(t){var r,i,s,n;if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==sN.string){let r=this._getOrReturnCtx(t);return sV(r,{code:sD.invalid_type,expected:sN.string,received:r.parsedType}),sq}let a=new sK,o;for(let l of this._def.checks)if("min"===l.kind)t.data.length<l.value&&(sV(o=this._getOrReturnCtx(t,o),{code:sD.too_small,minimum:l.value,type:"string",inclusive:!0,exact:!1,message:l.message}),a.dirty());else if("max"===l.kind)t.data.length>l.value&&(sV(o=this._getOrReturnCtx(t,o),{code:sD.too_big,maximum:l.value,type:"string",inclusive:!0,exact:!1,message:l.message}),a.dirty());else if("length"===l.kind){let r=t.data.length>l.value,i=t.data.length<l.value;(r||i)&&((o=this._getOrReturnCtx(t,o),r)?sV(o,{code:sD.too_big,maximum:l.value,type:"string",inclusive:!0,exact:!0,message:l.message}):i&&sV(o,{code:sD.too_small,minimum:l.value,type:"string",inclusive:!0,exact:!0,message:l.message}),a.dirty())}else if("email"===l.kind)ns.test(t.data)||(sV(o=this._getOrReturnCtx(t,o),{validation:"email",code:sD.invalid_string,message:l.message}),a.dirty());else if("emoji"===l.kind)s7||(s7=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),s7.test(t.data)||(sV(o=this._getOrReturnCtx(t,o),{validation:"emoji",code:sD.invalid_string,message:l.message}),a.dirty());else if("uuid"===l.kind)ne.test(t.data)||(sV(o=this._getOrReturnCtx(t,o),{validation:"uuid",code:sD.invalid_string,message:l.message}),a.dirty());else if("nanoid"===l.kind)nt.test(t.data)||(sV(o=this._getOrReturnCtx(t,o),{validation:"nanoid",code:sD.invalid_string,message:l.message}),a.dirty());else if("cuid"===l.kind)s9.test(t.data)||(sV(o=this._getOrReturnCtx(t,o),{validation:"cuid",code:sD.invalid_string,message:l.message}),a.dirty());else if("cuid2"===l.kind)s5.test(t.data)||(sV(o=this._getOrReturnCtx(t,o),{validation:"cuid2",code:sD.invalid_string,message:l.message}),a.dirty());else if("ulid"===l.kind)s6.test(t.data)||(sV(o=this._getOrReturnCtx(t,o),{validation:"ulid",code:sD.invalid_string,message:l.message}),a.dirty());else if("url"===l.kind)try{new URL(t.data)}catch{sV(o=this._getOrReturnCtx(t,o),{validation:"url",code:sD.invalid_string,message:l.message}),a.dirty()}else"regex"===l.kind?(l.regex.lastIndex=0,l.regex.test(t.data)||(sV(o=this._getOrReturnCtx(t,o),{validation:"regex",code:sD.invalid_string,message:l.message}),a.dirty())):"trim"===l.kind?t.data=t.data.trim():"includes"===l.kind?t.data.includes(l.value,l.position)||(sV(o=this._getOrReturnCtx(t,o),{code:sD.invalid_string,validation:{includes:l.value,position:l.position},message:l.message}),a.dirty()):"toLowerCase"===l.kind?t.data=t.data.toLowerCase():"toUpperCase"===l.kind?t.data=t.data.toUpperCase():"startsWith"===l.kind?t.data.startsWith(l.value)||(sV(o=this._getOrReturnCtx(t,o),{code:sD.invalid_string,validation:{startsWith:l.value},message:l.message}),a.dirty()):"endsWith"===l.kind?t.data.endsWith(l.value)||(sV(o=this._getOrReturnCtx(t,o),{code:sD.invalid_string,validation:{endsWith:l.value},message:l.message}),a.dirty()):"datetime"===l.kind?nf(l).test(t.data)||(sV(o=this._getOrReturnCtx(t,o),{code:sD.invalid_string,validation:"datetime",message:l.message}),a.dirty()):"date"===l.kind?nd.test(t.data)||(sV(o=this._getOrReturnCtx(t,o),{code:sD.invalid_string,validation:"date",message:l.message}),a.dirty()):"time"===l.kind?RegExp(`^${nh(l)}$`).test(t.data)||(sV(o=this._getOrReturnCtx(t,o),{code:sD.invalid_string,validation:"time",message:l.message}),a.dirty()):"duration"===l.kind?ni.test(t.data)||(sV(o=this._getOrReturnCtx(t,o),{validation:"duration",code:sD.invalid_string,message:l.message}),a.dirty()):"ip"===l.kind?(r=t.data,("v4"===(i=l.version)||!i)&&nn.test(r)||("v6"===i||!i)&&no.test(r)||(sV(o=this._getOrReturnCtx(t,o),{validation:"ip",code:sD.invalid_string,message:l.message}),a.dirty())):"jwt"===l.kind?!function(t,r){if(!nr.test(t))return!1;try{let[i]=t.split(".");if(!i)return!1;let s=i.replace(/-/g,"+").replace(/_/g,"/").padEnd(i.length+(4-i.length%4)%4,"="),n=JSON.parse(atob(s));if("object"!=typeof n||null===n||"typ"in n&&n?.typ!=="JWT"||!n.alg||r&&n.alg!==r)return!1;return!0}catch{return!1}}(t.data,l.alg)&&(sV(o=this._getOrReturnCtx(t,o),{validation:"jwt",code:sD.invalid_string,message:l.message}),a.dirty()):"cidr"===l.kind?(s=t.data,("v4"===(n=l.version)||!n)&&na.test(s)||("v6"===n||!n)&&nl.test(s)||(sV(o=this._getOrReturnCtx(t,o),{validation:"cidr",code:sD.invalid_string,message:l.message}),a.dirty())):"base64"===l.kind?np.test(t.data)||(sV(o=this._getOrReturnCtx(t,o),{validation:"base64",code:sD.invalid_string,message:l.message}),a.dirty()):"base64url"===l.kind?nu.test(t.data)||(sV(o=this._getOrReturnCtx(t,o),{validation:"base64url",code:sD.invalid_string,message:l.message}),a.dirty()):s4.assertNever(l);return{status:a.value,value:t.data}}_regex(t,r,i){return this.refinement(r=>t.test(r),{validation:r,code:sD.invalid_string,...s8.errToObj(i)})}_addCheck(t){return new nm({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...s8.errToObj(t)})}url(t){return this._addCheck({kind:"url",...s8.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...s8.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...s8.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...s8.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...s8.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...s8.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...s8.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...s8.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...s8.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...s8.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...s8.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...s8.errToObj(t)})}datetime(t){return"string"==typeof t?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...s8.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return"string"==typeof t?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...s8.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...s8.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...s8.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...s8.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...s8.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...s8.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...s8.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...s8.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...s8.errToObj(r)})}nonempty(t){return this.min(1,s8.errToObj(t))}trim(){return new nm({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new nm({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new nm({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>"datetime"===t.kind)}get isDate(){return!!this._def.checks.find(t=>"date"===t.kind)}get isTime(){return!!this._def.checks.find(t=>"time"===t.kind)}get isDuration(){return!!this._def.checks.find(t=>"duration"===t.kind)}get isEmail(){return!!this._def.checks.find(t=>"email"===t.kind)}get isURL(){return!!this._def.checks.find(t=>"url"===t.kind)}get isEmoji(){return!!this._def.checks.find(t=>"emoji"===t.kind)}get isUUID(){return!!this._def.checks.find(t=>"uuid"===t.kind)}get isNANOID(){return!!this._def.checks.find(t=>"nanoid"===t.kind)}get isCUID(){return!!this._def.checks.find(t=>"cuid"===t.kind)}get isCUID2(){return!!this._def.checks.find(t=>"cuid2"===t.kind)}get isULID(){return!!this._def.checks.find(t=>"ulid"===t.kind)}get isIP(){return!!this._def.checks.find(t=>"ip"===t.kind)}get isCIDR(){return!!this._def.checks.find(t=>"cidr"===t.kind)}get isBase64(){return!!this._def.checks.find(t=>"base64"===t.kind)}get isBase64url(){return!!this._def.checks.find(t=>"base64url"===t.kind)}get minLength(){let t=null;for(let r of this._def.checks)"min"===r.kind&&(null===t||r.value>t)&&(t=r.value);return t}get maxLength(){let t=null;for(let r of this._def.checks)"max"===r.kind&&(null===t||r.value<t)&&(t=r.value);return t}}nm.create=t=>new nm({checks:[],typeName:n2.ZodString,coerce:t?.coerce??!1,...sQ(t)});class ny extends s0{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==sN.number){let r=this._getOrReturnCtx(t);return sV(r,{code:sD.invalid_type,expected:sN.number,received:r.parsedType}),sq}let r,i=new sK;for(let s of this._def.checks)"int"===s.kind?s4.isInteger(t.data)||(sV(r=this._getOrReturnCtx(t,r),{code:sD.invalid_type,expected:"integer",received:"float",message:s.message}),i.dirty()):"min"===s.kind?(s.inclusive?t.data<s.value:t.data<=s.value)&&(sV(r=this._getOrReturnCtx(t,r),{code:sD.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):"max"===s.kind?(s.inclusive?t.data>s.value:t.data>=s.value)&&(sV(r=this._getOrReturnCtx(t,r),{code:sD.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):"multipleOf"===s.kind?0!==function(t,r){let i=(t.toString().split(".")[1]||"").length,s=(r.toString().split(".")[1]||"").length,n=i>s?i:s;return Number.parseInt(t.toFixed(n).replace(".",""))%Number.parseInt(r.toFixed(n).replace(".",""))/10**n}(t.data,s.value)&&(sV(r=this._getOrReturnCtx(t,r),{code:sD.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):"finite"===s.kind?Number.isFinite(t.data)||(sV(r=this._getOrReturnCtx(t,r),{code:sD.not_finite,message:s.message}),i.dirty()):s4.assertNever(s);return{status:i.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,s8.toString(r))}gt(t,r){return this.setLimit("min",t,!1,s8.toString(r))}lte(t,r){return this.setLimit("max",t,!0,s8.toString(r))}lt(t,r){return this.setLimit("max",t,!1,s8.toString(r))}setLimit(t,r,i,s){return new ny({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:i,message:s8.toString(s)}]})}_addCheck(t){return new ny({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:s8.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:s8.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:s8.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:s8.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:s8.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:s8.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:s8.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:s8.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:s8.toString(t)})}get minValue(){let t=null;for(let r of this._def.checks)"min"===r.kind&&(null===t||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)"max"===r.kind&&(null===t||r.value<t)&&(t=r.value);return t}get isInt(){return!!this._def.checks.find(t=>"int"===t.kind||"multipleOf"===t.kind&&s4.isInteger(t.value))}get isFinite(){let t=null,r=null;for(let i of this._def.checks)if("finite"===i.kind||"int"===i.kind||"multipleOf"===i.kind)return!0;else"min"===i.kind?(null===r||i.value>r)&&(r=i.value):"max"===i.kind&&(null===t||i.value<t)&&(t=i.value);return Number.isFinite(r)&&Number.isFinite(t)}}ny.create=t=>new ny({checks:[],typeName:n2.ZodNumber,coerce:t?.coerce||!1,...sQ(t)});class nb extends s0{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==sN.bigint)return this._getInvalidInput(t);let r,i=new sK;for(let s of this._def.checks)"min"===s.kind?(s.inclusive?t.data<s.value:t.data<=s.value)&&(sV(r=this._getOrReturnCtx(t,r),{code:sD.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):"max"===s.kind?(s.inclusive?t.data>s.value:t.data>=s.value)&&(sV(r=this._getOrReturnCtx(t,r),{code:sD.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):"multipleOf"===s.kind?t.data%s.value!==BigInt(0)&&(sV(r=this._getOrReturnCtx(t,r),{code:sD.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):s4.assertNever(s);return{status:i.value,value:t.data}}_getInvalidInput(t){let r=this._getOrReturnCtx(t);return sV(r,{code:sD.invalid_type,expected:sN.bigint,received:r.parsedType}),sq}gte(t,r){return this.setLimit("min",t,!0,s8.toString(r))}gt(t,r){return this.setLimit("min",t,!1,s8.toString(r))}lte(t,r){return this.setLimit("max",t,!0,s8.toString(r))}lt(t,r){return this.setLimit("max",t,!1,s8.toString(r))}setLimit(t,r,i,s){return new nb({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:i,message:s8.toString(s)}]})}_addCheck(t){return new nb({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:s8.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:s8.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:s8.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:s8.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:s8.toString(r)})}get minValue(){let t=null;for(let r of this._def.checks)"min"===r.kind&&(null===t||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)"max"===r.kind&&(null===t||r.value<t)&&(t=r.value);return t}}nb.create=t=>new nb({checks:[],typeName:n2.ZodBigInt,coerce:t?.coerce??!1,...sQ(t)});class ng extends s0{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==sN.boolean){let r=this._getOrReturnCtx(t);return sV(r,{code:sD.invalid_type,expected:sN.boolean,received:r.parsedType}),sq}return sW(t.data)}}ng.create=t=>new ng({typeName:n2.ZodBoolean,coerce:t?.coerce||!1,...sQ(t)});class nv extends s0{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==sN.date){let r=this._getOrReturnCtx(t);return sV(r,{code:sD.invalid_type,expected:sN.date,received:r.parsedType}),sq}if(Number.isNaN(t.data.getTime()))return sV(this._getOrReturnCtx(t),{code:sD.invalid_date}),sq;let r=new sK,i;for(let s of this._def.checks)"min"===s.kind?t.data.getTime()<s.value&&(sV(i=this._getOrReturnCtx(t,i),{code:sD.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),r.dirty()):"max"===s.kind?t.data.getTime()>s.value&&(sV(i=this._getOrReturnCtx(t,i),{code:sD.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):s4.assertNever(s);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new nv({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:s8.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:s8.toString(r)})}get minDate(){let t=null;for(let r of this._def.checks)"min"===r.kind&&(null===t||r.value>t)&&(t=r.value);return null!=t?new Date(t):null}get maxDate(){let t=null;for(let r of this._def.checks)"max"===r.kind&&(null===t||r.value<t)&&(t=r.value);return null!=t?new Date(t):null}}nv.create=t=>new nv({checks:[],coerce:t?.coerce||!1,typeName:n2.ZodDate,...sQ(t)});class nx extends s0{_parse(t){if(this._getType(t)!==sN.symbol){let r=this._getOrReturnCtx(t);return sV(r,{code:sD.invalid_type,expected:sN.symbol,received:r.parsedType}),sq}return sW(t.data)}}nx.create=t=>new nx({typeName:n2.ZodSymbol,...sQ(t)});class nT extends s0{_parse(t){if(this._getType(t)!==sN.undefined){let r=this._getOrReturnCtx(t);return sV(r,{code:sD.invalid_type,expected:sN.undefined,received:r.parsedType}),sq}return sW(t.data)}}nT.create=t=>new nT({typeName:n2.ZodUndefined,...sQ(t)});class nE extends s0{_parse(t){if(this._getType(t)!==sN.null){let r=this._getOrReturnCtx(t);return sV(r,{code:sD.invalid_type,expected:sN.null,received:r.parsedType}),sq}return sW(t.data)}}nE.create=t=>new nE({typeName:n2.ZodNull,...sQ(t)});class nS extends s0{constructor(){super(...arguments),this._any=!0}_parse(t){return sW(t.data)}}nS.create=t=>new nS({typeName:n2.ZodAny,...sQ(t)});class n_ extends s0{constructor(){super(...arguments),this._unknown=!0}_parse(t){return sW(t.data)}}n_.create=t=>new n_({typeName:n2.ZodUnknown,...sQ(t)});class nP extends s0{_parse(t){let r=this._getOrReturnCtx(t);return sV(r,{code:sD.invalid_type,expected:sN.never,received:r.parsedType}),sq}}nP.create=t=>new nP({typeName:n2.ZodNever,...sQ(t)});class nA extends s0{_parse(t){if(this._getType(t)!==sN.undefined){let r=this._getOrReturnCtx(t);return sV(r,{code:sD.invalid_type,expected:sN.void,received:r.parsedType}),sq}return sW(t.data)}}nA.create=t=>new nA({typeName:n2.ZodVoid,...sQ(t)});class nw extends s0{_parse(t){let{ctx:r,status:i}=this._processInputParams(t),s=this._def;if(r.parsedType!==sN.array)return sV(r,{code:sD.invalid_type,expected:sN.array,received:r.parsedType}),sq;if(null!==s.exactLength){let t=r.data.length>s.exactLength.value,n=r.data.length<s.exactLength.value;(t||n)&&(sV(r,{code:t?sD.too_big:sD.too_small,minimum:n?s.exactLength.value:void 0,maximum:t?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),i.dirty())}if(null!==s.minLength&&r.data.length<s.minLength.value&&(sV(r,{code:sD.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),i.dirty()),null!==s.maxLength&&r.data.length>s.maxLength.value&&(sV(r,{code:sD.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),i.dirty()),r.common.async)return Promise.all([...r.data].map((t,i)=>s.type._parseAsync(new sG(r,t,r.path,i)))).then(t=>sK.mergeArray(i,t));let n=[...r.data].map((t,i)=>s.type._parseSync(new sG(r,t,r.path,i)));return sK.mergeArray(i,n)}get element(){return this._def.type}min(t,r){return new nw({...this._def,minLength:{value:t,message:s8.toString(r)}})}max(t,r){return new nw({...this._def,maxLength:{value:t,message:s8.toString(r)}})}length(t,r){return new nw({...this._def,exactLength:{value:t,message:s8.toString(r)}})}nonempty(t){return this.min(1,t)}}nw.create=(t,r)=>new nw({type:t,minLength:null,maxLength:null,exactLength:null,typeName:n2.ZodArray,...sQ(r)});class nC extends s0{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;let t=this._def.shape(),r=s4.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==sN.object){let r=this._getOrReturnCtx(t);return sV(r,{code:sD.invalid_type,expected:sN.object,received:r.parsedType}),sq}let{status:r,ctx:i}=this._processInputParams(t),{shape:s,keys:n}=this._getCached(),a=[];if(!(this._def.catchall instanceof nP&&"strip"===this._def.unknownKeys))for(let t in i.data)n.includes(t)||a.push(t);let o=[];for(let t of n){let r=s[t],n=i.data[t];o.push({key:{status:"valid",value:t},value:r._parse(new sG(i,n,i.path,t)),alwaysSet:t in i.data})}if(this._def.catchall instanceof nP){let t=this._def.unknownKeys;if("passthrough"===t)for(let t of a)o.push({key:{status:"valid",value:t},value:{status:"valid",value:i.data[t]}});else if("strict"===t)a.length>0&&(sV(i,{code:sD.unrecognized_keys,keys:a}),r.dirty());else if("strip"===t);else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let t=this._def.catchall;for(let r of a){let s=i.data[r];o.push({key:{status:"valid",value:r},value:t._parse(new sG(i,s,i.path,r)),alwaysSet:r in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let t=[];for(let r of o){let i=await r.key,s=await r.value;t.push({key:i,value:s,alwaysSet:r.alwaysSet})}return t}).then(t=>sK.mergeObjectSync(r,t)):sK.mergeObjectSync(r,o)}get shape(){return this._def.shape()}strict(t){return s8.errToObj,new nC({...this._def,unknownKeys:"strict",...void 0!==t?{errorMap:(r,i)=>{let s=this._def.errorMap?.(r,i).message??i.defaultError;return"unrecognized_keys"===r.code?{message:s8.errToObj(t).message??s}:{message:s}}}:{}})}strip(){return new nC({...this._def,unknownKeys:"strip"})}passthrough(){return new nC({...this._def,unknownKeys:"passthrough"})}extend(t){return new nC({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new nC({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:n2.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new nC({...this._def,catchall:t})}pick(t){let r={};for(let i of s4.objectKeys(t))t[i]&&this.shape[i]&&(r[i]=this.shape[i]);return new nC({...this._def,shape:()=>r})}omit(t){let r={};for(let i of s4.objectKeys(this.shape))t[i]||(r[i]=this.shape[i]);return new nC({...this._def,shape:()=>r})}deepPartial(){return function t(r){if(r instanceof nC){let i={};for(let s in r.shape){let n=r.shape[s];i[s]=nz.create(t(n))}return new nC({...r._def,shape:()=>i})}if(r instanceof nw)return new nw({...r._def,type:t(r.element)});if(r instanceof nz)return nz.create(t(r.unwrap()));if(r instanceof nW)return nW.create(t(r.unwrap()));if(r instanceof nD)return nD.create(r.items.map(r=>t(r)));else return r}(this)}partial(t){let r={};for(let i of s4.objectKeys(this.shape)){let s=this.shape[i];t&&!t[i]?r[i]=s:r[i]=s.optional()}return new nC({...this._def,shape:()=>r})}required(t){let r={};for(let i of s4.objectKeys(this.shape))if(t&&!t[i])r[i]=this.shape[i];else{let t=this.shape[i];for(;t instanceof nz;)t=t._def.innerType;r[i]=t}return new nC({...this._def,shape:()=>r})}keyof(){return nU(s4.objectKeys(this.shape))}}nC.create=(t,r)=>new nC({shape:()=>t,unknownKeys:"strip",catchall:nP.create(),typeName:n2.ZodObject,...sQ(r)}),nC.strictCreate=(t,r)=>new nC({shape:()=>t,unknownKeys:"strict",catchall:nP.create(),typeName:n2.ZodObject,...sQ(r)}),nC.lazycreate=(t,r)=>new nC({shape:t,unknownKeys:"strip",catchall:nP.create(),typeName:n2.ZodObject,...sQ(r)});class nI extends s0{_parse(t){let{ctx:r}=this._processInputParams(t),i=this._def.options;if(r.common.async)return Promise.all(i.map(async t=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await t._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(function(t){for(let r of t)if("valid"===r.result.status)return r.result;for(let i of t)if("dirty"===i.result.status)return r.common.issues.push(...i.ctx.common.issues),i.result;let i=t.map(t=>new sL(t.ctx.common.issues));return sV(r,{code:sD.invalid_union,unionErrors:i}),sq});{let t,s=[];for(let n of i){let i={...r,common:{...r.common,issues:[]},parent:null},a=n._parseSync({data:r.data,path:r.path,parent:i});if("valid"===a.status)return a;"dirty"!==a.status||t||(t={result:a,ctx:i}),i.common.issues.length&&s.push(i.common.issues)}if(t)return r.common.issues.push(...t.ctx.common.issues),t.result;let n=s.map(t=>new sL(t));return sV(r,{code:sD.invalid_union,unionErrors:n}),sq}}get options(){return this._def.options}}nI.create=(t,r)=>new nI({options:t,typeName:n2.ZodUnion,...sQ(r)});var nk=t=>{if(t instanceof nF)return nk(t.schema);if(t instanceof nq)return nk(t.innerType());if(t instanceof nB)return[t.value];if(t instanceof n$)return t.options;if(t instanceof nV)return s4.objectValues(t.enum);else if(t instanceof nH)return nk(t._def.innerType);else if(t instanceof nT)return[void 0];else if(t instanceof nE)return[null];else if(t instanceof nz)return[void 0,...nk(t.unwrap())];else if(t instanceof nW)return[null,...nk(t.unwrap())];else if(t instanceof nG)return nk(t.unwrap());else if(t instanceof nQ)return nk(t.unwrap());else if(t instanceof nJ)return nk(t._def.innerType);else return[]};class nN extends s0{_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==sN.object)return sV(r,{code:sD.invalid_type,expected:sN.object,received:r.parsedType}),sq;let i=this.discriminator,s=r.data[i],n=this.optionsMap.get(s);return n?r.common.async?n._parseAsync({data:r.data,path:r.path,parent:r}):n._parseSync({data:r.data,path:r.path,parent:r}):(sV(r,{code:sD.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[i]}),sq)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,r,i){let s=new Map;for(let i of r){let r=nk(i.shape[t]);if(!r.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let n of r){if(s.has(n))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(n)}`);s.set(n,i)}}return new nN({typeName:n2.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:s,...sQ(i)})}}class nO extends s0{_parse(t){let{status:r,ctx:i}=this._processInputParams(t),s=(t,s)=>{if(sH(t)||sH(s))return sq;let n=function t(r,i){let s=sO(r),n=sO(i);if(r===i)return{valid:!0,data:r};if(s===sN.object&&n===sN.object){let s=s4.objectKeys(i),n=s4.objectKeys(r).filter(t=>-1!==s.indexOf(t)),a={...r,...i};for(let s of n){let n=t(r[s],i[s]);if(!n.valid)return{valid:!1};a[s]=n.data}return{valid:!0,data:a}}if(s===sN.array&&n===sN.array){if(r.length!==i.length)return{valid:!1};let s=[];for(let n=0;n<r.length;n++){let a=t(r[n],i[n]);if(!a.valid)return{valid:!1};s.push(a.data)}return{valid:!0,data:s}}if(s===sN.date&&n===sN.date&&+r==+i)return{valid:!0,data:r};return{valid:!1}}(t.value,s.value);return n.valid?((sJ(t)||sJ(s))&&r.dirty(),{status:r.value,value:n.data}):(sV(i,{code:sD.invalid_intersection_types}),sq)};return i.common.async?Promise.all([this._def.left._parseAsync({data:i.data,path:i.path,parent:i}),this._def.right._parseAsync({data:i.data,path:i.path,parent:i})]).then(([t,r])=>s(t,r)):s(this._def.left._parseSync({data:i.data,path:i.path,parent:i}),this._def.right._parseSync({data:i.data,path:i.path,parent:i}))}}nO.create=(t,r,i)=>new nO({left:t,right:r,typeName:n2.ZodIntersection,...sQ(i)});class nD extends s0{_parse(t){let{status:r,ctx:i}=this._processInputParams(t);if(i.parsedType!==sN.array)return sV(i,{code:sD.invalid_type,expected:sN.array,received:i.parsedType}),sq;if(i.data.length<this._def.items.length)return sV(i,{code:sD.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),sq;!this._def.rest&&i.data.length>this._def.items.length&&(sV(i,{code:sD.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...i.data].map((t,r)=>{let s=this._def.items[r]||this._def.rest;return s?s._parse(new sG(i,t,i.path,r)):null}).filter(t=>!!t);return i.common.async?Promise.all(s).then(t=>sK.mergeArray(r,t)):sK.mergeArray(r,s)}get items(){return this._def.items}rest(t){return new nD({...this._def,rest:t})}}nD.create=(t,r)=>{if(!Array.isArray(t))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new nD({items:t,typeName:n2.ZodTuple,rest:null,...sQ(r)})};class nj extends s0{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:i}=this._processInputParams(t);if(i.parsedType!==sN.object)return sV(i,{code:sD.invalid_type,expected:sN.object,received:i.parsedType}),sq;let s=[],n=this._def.keyType,a=this._def.valueType;for(let t in i.data)s.push({key:n._parse(new sG(i,t,i.path,t)),value:a._parse(new sG(i,i.data[t],i.path,t)),alwaysSet:t in i.data});return i.common.async?sK.mergeObjectAsync(r,s):sK.mergeObjectSync(r,s)}get element(){return this._def.valueType}static create(t,r,i){return new nj(r instanceof s0?{keyType:t,valueType:r,typeName:n2.ZodRecord,...sQ(i)}:{keyType:nm.create(),valueType:t,typeName:n2.ZodRecord,...sQ(r)})}}class nL extends s0{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:i}=this._processInputParams(t);if(i.parsedType!==sN.map)return sV(i,{code:sD.invalid_type,expected:sN.map,received:i.parsedType}),sq;let s=this._def.keyType,n=this._def.valueType,a=[...i.data.entries()].map(([t,r],a)=>({key:s._parse(new sG(i,t,i.path,[a,"key"])),value:n._parse(new sG(i,r,i.path,[a,"value"]))}));if(i.common.async){let t=new Map;return Promise.resolve().then(async()=>{for(let i of a){let s=await i.key,n=await i.value;if("aborted"===s.status||"aborted"===n.status)return sq;("dirty"===s.status||"dirty"===n.status)&&r.dirty(),t.set(s.value,n.value)}return{status:r.value,value:t}})}{let t=new Map;for(let i of a){let{key:s,value:n}=i;if("aborted"===s.status||"aborted"===n.status)return sq;("dirty"===s.status||"dirty"===n.status)&&r.dirty(),t.set(s.value,n.value)}return{status:r.value,value:t}}}}nL.create=(t,r,i)=>new nL({valueType:r,keyType:t,typeName:n2.ZodMap,...sQ(i)});class nR extends s0{_parse(t){let{status:r,ctx:i}=this._processInputParams(t);if(i.parsedType!==sN.set)return sV(i,{code:sD.invalid_type,expected:sN.set,received:i.parsedType}),sq;let s=this._def;null!==s.minSize&&i.data.size<s.minSize.value&&(sV(i,{code:sD.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),r.dirty()),null!==s.maxSize&&i.data.size>s.maxSize.value&&(sV(i,{code:sD.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),r.dirty());let n=this._def.valueType;function a(t){let i=new Set;for(let s of t){if("aborted"===s.status)return sq;"dirty"===s.status&&r.dirty(),i.add(s.value)}return{status:r.value,value:i}}let o=[...i.data.values()].map((t,r)=>n._parse(new sG(i,t,i.path,r)));return i.common.async?Promise.all(o).then(t=>a(t)):a(o)}min(t,r){return new nR({...this._def,minSize:{value:t,message:s8.toString(r)}})}max(t,r){return new nR({...this._def,maxSize:{value:t,message:s8.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}}nR.create=(t,r)=>new nR({valueType:t,minSize:null,maxSize:null,typeName:n2.ZodSet,...sQ(r)});class nM extends s0{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==sN.function)return sV(r,{code:sD.invalid_type,expected:sN.function,received:r.parsedType}),sq;function i(t,i){return sU({data:t,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,sM,sR].filter(t=>!!t),issueData:{code:sD.invalid_arguments,argumentsError:i}})}function s(t,i){return sU({data:t,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,sM,sR].filter(t=>!!t),issueData:{code:sD.invalid_return_type,returnTypeError:i}})}let n={errorMap:r.common.contextualErrorMap},a=r.data;if(this._def.returns instanceof nK){let t=this;return sW(async function(...r){let o=new sL([]),l=await t._def.args.parseAsync(r,n).catch(t=>{throw o.addIssue(i(r,t)),o}),p=await Reflect.apply(a,this,l);return await t._def.returns._def.type.parseAsync(p,n).catch(t=>{throw o.addIssue(s(p,t)),o})})}{let t=this;return sW(function(...r){let o=t._def.args.safeParse(r,n);if(!o.success)throw new sL([i(r,o.error)]);let l=Reflect.apply(a,this,o.data),p=t._def.returns.safeParse(l,n);if(!p.success)throw new sL([s(l,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new nM({...this._def,args:nD.create(t).rest(n_.create())})}returns(t){return new nM({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,r,i){return new nM({args:t||nD.create([]).rest(n_.create()),returns:r||n_.create(),typeName:n2.ZodFunction,...sQ(i)})}}class nF extends s0{get schema(){return this._def.getter()}_parse(t){let{ctx:r}=this._processInputParams(t);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}}nF.create=(t,r)=>new nF({getter:t,typeName:n2.ZodLazy,...sQ(r)});class nB extends s0{_parse(t){if(t.data!==this._def.value){let r=this._getOrReturnCtx(t);return sV(r,{received:r.data,code:sD.invalid_literal,expected:this._def.value}),sq}return{status:"valid",value:t.data}}get value(){return this._def.value}}function nU(t,r){return new n$({values:t,typeName:n2.ZodEnum,...sQ(r)})}nB.create=(t,r)=>new nB({value:t,typeName:n2.ZodLiteral,...sQ(r)});class n$ extends s0{_parse(t){if("string"!=typeof t.data){let r=this._getOrReturnCtx(t),i=this._def.values;return sV(r,{expected:s4.joinValues(i),received:r.parsedType,code:sD.invalid_type}),sq}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let r=this._getOrReturnCtx(t),i=this._def.values;return sV(r,{received:r.data,code:sD.invalid_enum_value,options:i}),sq}return sW(t.data)}get options(){return this._def.values}get enum(){let t={};for(let r of this._def.values)t[r]=r;return t}get Values(){let t={};for(let r of this._def.values)t[r]=r;return t}get Enum(){let t={};for(let r of this._def.values)t[r]=r;return t}extract(t,r=this._def){return n$.create(t,{...this._def,...r})}exclude(t,r=this._def){return n$.create(this.options.filter(r=>!t.includes(r)),{...this._def,...r})}}n$.create=nU;class nV extends s0{_parse(t){let r=s4.getValidEnumValues(this._def.values),i=this._getOrReturnCtx(t);if(i.parsedType!==sN.string&&i.parsedType!==sN.number){let t=s4.objectValues(r);return sV(i,{expected:s4.joinValues(t),received:i.parsedType,code:sD.invalid_type}),sq}if(this._cache||(this._cache=new Set(s4.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let t=s4.objectValues(r);return sV(i,{received:i.data,code:sD.invalid_enum_value,options:t}),sq}return sW(t.data)}get enum(){return this._def.values}}nV.create=(t,r)=>new nV({values:t,typeName:n2.ZodNativeEnum,...sQ(r)});class nK extends s0{unwrap(){return this._def.type}_parse(t){let{ctx:r}=this._processInputParams(t);return r.parsedType!==sN.promise&&!1===r.common.async?(sV(r,{code:sD.invalid_type,expected:sN.promise,received:r.parsedType}),sq):sW((r.parsedType===sN.promise?r.data:Promise.resolve(r.data)).then(t=>this._def.type.parseAsync(t,{path:r.path,errorMap:r.common.contextualErrorMap})))}}nK.create=(t,r)=>new nK({type:t,typeName:n2.ZodPromise,...sQ(r)});class nq extends s0{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===n2.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:r,ctx:i}=this._processInputParams(t),s=this._def.effect||null,n={addIssue:t=>{(sV(i,t),t.fatal)?r.abort():r.dirty()},get path(){return i.path}};if(n.addIssue=n.addIssue.bind(n),"preprocess"===s.type){let t=s.transform(i.data,n);if(i.common.async)return Promise.resolve(t).then(async t=>{if("aborted"===r.value)return sq;let s=await this._def.schema._parseAsync({data:t,path:i.path,parent:i});return"aborted"===s.status?sq:"dirty"===s.status||"dirty"===r.value?sz(s.value):s});{if("aborted"===r.value)return sq;let s=this._def.schema._parseSync({data:t,path:i.path,parent:i});return"aborted"===s.status?sq:"dirty"===s.status||"dirty"===r.value?sz(s.value):s}}if("refinement"===s.type){let t=t=>{let r=s.refinement(t,n);if(i.common.async)return Promise.resolve(r);if(r instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return t};if(!1!==i.common.async)return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(i=>"aborted"===i.status?sq:("dirty"===i.status&&r.dirty(),t(i.value).then(()=>({status:r.value,value:i.value}))));{let s=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});return"aborted"===s.status?sq:("dirty"===s.status&&r.dirty(),t(s.value),{status:r.value,value:s.value})}}if("transform"===s.type)if(!1!==i.common.async)return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(t=>sY(t)?Promise.resolve(s.transform(t.value,n)).then(t=>({status:r.value,value:t})):sq);else{let t=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});if(!sY(t))return sq;let a=s.transform(t.value,n);if(a instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}s4.assertNever(s)}}nq.create=(t,r,i)=>new nq({schema:t,typeName:n2.ZodEffects,effect:r,...sQ(i)}),nq.createWithPreprocess=(t,r,i)=>new nq({schema:r,effect:{type:"preprocess",transform:t},typeName:n2.ZodEffects,...sQ(i)});class nz extends s0{_parse(t){return this._getType(t)===sN.undefined?sW(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}nz.create=(t,r)=>new nz({innerType:t,typeName:n2.ZodOptional,...sQ(r)});class nW extends s0{_parse(t){return this._getType(t)===sN.null?sW(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}nW.create=(t,r)=>new nW({innerType:t,typeName:n2.ZodNullable,...sQ(r)});class nH extends s0{_parse(t){let{ctx:r}=this._processInputParams(t),i=r.data;return r.parsedType===sN.undefined&&(i=this._def.defaultValue()),this._def.innerType._parse({data:i,path:r.path,parent:r})}removeDefault(){return this._def.innerType}}nH.create=(t,r)=>new nH({innerType:t,typeName:n2.ZodDefault,defaultValue:"function"==typeof r.default?r.default:()=>r.default,...sQ(r)});class nJ extends s0{_parse(t){let{ctx:r}=this._processInputParams(t),i={...r,common:{...r.common,issues:[]}},s=this._def.innerType._parse({data:i.data,path:i.path,parent:{...i}});return sX(s)?s.then(t=>({status:"valid",value:"valid"===t.status?t.value:this._def.catchValue({get error(){return new sL(i.common.issues)},input:i.data})})):{status:"valid",value:"valid"===s.status?s.value:this._def.catchValue({get error(){return new sL(i.common.issues)},input:i.data})}}removeCatch(){return this._def.innerType}}nJ.create=(t,r)=>new nJ({innerType:t,typeName:n2.ZodCatch,catchValue:"function"==typeof r.catch?r.catch:()=>r.catch,...sQ(r)});class nY extends s0{_parse(t){if(this._getType(t)!==sN.nan){let r=this._getOrReturnCtx(t);return sV(r,{code:sD.invalid_type,expected:sN.nan,received:r.parsedType}),sq}return{status:"valid",value:t.data}}}nY.create=t=>new nY({typeName:n2.ZodNaN,...sQ(t)});var nX=Symbol("zod_brand");class nG extends s0{_parse(t){let{ctx:r}=this._processInputParams(t),i=r.data;return this._def.type._parse({data:i,path:r.path,parent:r})}unwrap(){return this._def.type}}class nZ extends s0{_parse(t){let{status:r,ctx:i}=this._processInputParams(t);if(i.common.async)return(async()=>{let t=await this._def.in._parseAsync({data:i.data,path:i.path,parent:i});return"aborted"===t.status?sq:"dirty"===t.status?(r.dirty(),sz(t.value)):this._def.out._parseAsync({data:t.value,path:i.path,parent:i})})();{let t=this._def.in._parseSync({data:i.data,path:i.path,parent:i});return"aborted"===t.status?sq:"dirty"===t.status?(r.dirty(),{status:"dirty",value:t.value}):this._def.out._parseSync({data:t.value,path:i.path,parent:i})}}static create(t,r){return new nZ({in:t,out:r,typeName:n2.ZodPipeline})}}class nQ extends s0{_parse(t){let r=this._def.innerType._parse(t),i=t=>(sY(t)&&(t.value=Object.freeze(t.value)),t);return sX(r)?r.then(t=>i(t)):i(r)}unwrap(){return this._def.innerType}}function n0(t,r){let i="function"==typeof t?t(r):"string"==typeof t?{message:t}:t;return"string"==typeof i?{message:i}:i}function n1(t,r={},i){return t?nS.create().superRefine((s,n)=>{let a=t(s);if(a instanceof Promise)return a.then(t=>{if(!t){let t=n0(r,s),a=t.fatal??i??!0;n.addIssue({code:"custom",...t,fatal:a})}});if(!a){let t=n0(r,s),a=t.fatal??i??!0;n.addIssue({code:"custom",...t,fatal:a})}}):nS.create()}nQ.create=(t,r)=>new nQ({innerType:t,typeName:n2.ZodReadonly,...sQ(r)});var n2,n4={object:nC.lazycreate};(u=n2||(n2={})).ZodString="ZodString",u.ZodNumber="ZodNumber",u.ZodNaN="ZodNaN",u.ZodBigInt="ZodBigInt",u.ZodBoolean="ZodBoolean",u.ZodDate="ZodDate",u.ZodSymbol="ZodSymbol",u.ZodUndefined="ZodUndefined",u.ZodNull="ZodNull",u.ZodAny="ZodAny",u.ZodUnknown="ZodUnknown",u.ZodNever="ZodNever",u.ZodVoid="ZodVoid",u.ZodArray="ZodArray",u.ZodObject="ZodObject",u.ZodUnion="ZodUnion",u.ZodDiscriminatedUnion="ZodDiscriminatedUnion",u.ZodIntersection="ZodIntersection",u.ZodTuple="ZodTuple",u.ZodRecord="ZodRecord",u.ZodMap="ZodMap",u.ZodSet="ZodSet",u.ZodFunction="ZodFunction",u.ZodLazy="ZodLazy",u.ZodLiteral="ZodLiteral",u.ZodEnum="ZodEnum",u.ZodEffects="ZodEffects",u.ZodNativeEnum="ZodNativeEnum",u.ZodOptional="ZodOptional",u.ZodNullable="ZodNullable",u.ZodDefault="ZodDefault",u.ZodCatch="ZodCatch",u.ZodPromise="ZodPromise",u.ZodBranded="ZodBranded",u.ZodPipeline="ZodPipeline",u.ZodReadonly="ZodReadonly";var n3=(t,r={message:`Input not instance of ${t.name}`})=>n1(r=>r instanceof t,r),n8=nm.create,n7=ny.create,n9=nY.create,n5=nb.create,n6=ng.create,ae=nv.create,at=nx.create,ar=nT.create,ai=nE.create,as=nS.create,an=n_.create,aa=nP.create,ao=nA.create,al=nw.create,ap=nC.create,au=nC.strictCreate,ac=nI.create,ad=nN.create,ah=nO.create,af=nD.create,am=nj.create,ay=nL.create,ab=nR.create,ag=nM.create,av=nF.create,ax=nB.create,aT=n$.create,aE=nV.create,aS=nK.create,a_=nq.create,aP=nz.create,aA=nW.create,aw=nq.createWithPreprocess,aC=nZ.create,aI=()=>n8().optional(),ak=()=>n7().optional(),aN=()=>n6().optional(),aO={string:t=>nm.create({...t,coerce:!0}),number:t=>ny.create({...t,coerce:!0}),boolean:t=>ng.create({...t,coerce:!0}),bigint:t=>nb.create({...t,coerce:!0}),date:t=>nv.create({...t,coerce:!0})},aD=sq;function aj(t,r,i){function s(i,s){var n;for(let a in Object.defineProperty(i,"_zod",{value:i._zod??{},enumerable:!1}),(n=i._zod).traits??(n.traits=new Set),i._zod.traits.add(t),r(i,s),o.prototype)a in i||Object.defineProperty(i,a,{value:o.prototype[a].bind(i)});i._zod.constr=o,i._zod.def=s}let n=i?.Parent??Object;class a extends n{}function o(t){var r;let n=i?.Parent?new a:this;for(let i of(s(n,t),(r=n._zod).deferred??(r.deferred=[]),n._zod.deferred))i();return n}return Object.defineProperty(a,"name",{value:t}),Object.defineProperty(o,"init",{value:s}),Object.defineProperty(o,Symbol.hasInstance,{value:r=>!!i?.Parent&&r instanceof i.Parent||r?._zod?.traits?.has(t)}),Object.defineProperty(o,"name",{value:t}),o}Object.freeze({status:"aborted"}),Symbol("zod_brand");class aL extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}var aR={};function aM(t){return t&&Object.assign(aR,t),aR}var aF={};function aB(t){return t}function aU(t){return t}function a$(t){}function aV(t){throw Error()}function aK(t){}function aq(t){let r=Object.values(t).filter(t=>"number"==typeof t);return Object.entries(t).filter(([t,i])=>-1===r.indexOf(+t)).map(([t,r])=>r)}function az(t,r="|"){return t.map(t=>on(t)).join(r)}function aW(t,r){return"bigint"==typeof r?r.toString():r}function aH(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}}}}function aJ(t){return null==t}function aY(t){let r=+!!t.startsWith("^"),i=t.endsWith("$")?t.length-1:t.length;return t.slice(r,i)}function aX(t,r){let i=(t.toString().split(".")[1]||"").length,s=(r.toString().split(".")[1]||"").length,n=i>s?i:s;return Number.parseInt(t.toFixed(n).replace(".",""))%Number.parseInt(r.toFixed(n).replace(".",""))/10**n}function aG(t,r,i){Object.defineProperty(t,r,{get(){{let s=i();return t[r]=s,s}},set(i){Object.defineProperty(t,r,{value:i})},configurable:!0})}function aZ(t,r,i){Object.defineProperty(t,r,{value:i,writable:!0,enumerable:!0,configurable:!0})}function aQ(t,r){return r?r.reduce((t,r)=>t?.[r],t):t}function a0(t){let r=Object.keys(t);return Promise.all(r.map(r=>t[r])).then(t=>{let i={};for(let s=0;s<r.length;s++)i[r[s]]=t[s];return i})}function a1(t=10){let r="";for(let i=0;i<t;i++)r+="abcdefghijklmnopqrstuvwxyz"[Math.floor(26*Math.random())];return r}function a2(t){return JSON.stringify(t)}ru(aF,{unwrapMessage:()=>ob,stringifyPrimitive:()=>on,required:()=>of,randomString:()=>a1,propertyKeyTypes:()=>a6,promiseAllObject:()=>a0,primitiveTypes:()=>oe,prefixIssues:()=>oy,pick:()=>op,partial:()=>oh,optionalKeys:()=>oa,omit:()=>ou,numKeys:()=>a9,nullish:()=>aJ,normalizeParams:()=>oi,merge:()=>od,jsonStringifyReplacer:()=>aW,joinValues:()=>az,issue:()=>oT,isPlainObject:()=>a7,isObject:()=>a3,getSizableOrigin:()=>ov,getParsedType:()=>a5,getLengthableOrigin:()=>ox,getEnumValues:()=>aq,getElementAtPath:()=>aQ,floatSafeRemainder:()=>aX,finalizeIssue:()=>og,extend:()=>oc,escapeRegex:()=>ot,esc:()=>a2,defineLazy:()=>aG,createTransparentProxy:()=>os,clone:()=>or,cleanRegex:()=>aY,cleanEnum:()=>oE,captureStackTrace:()=>a4,cached:()=>aH,assignProp:()=>aZ,assertNotEqual:()=>aU,assertNever:()=>aV,assertIs:()=>a$,assertEqual:()=>aB,assert:()=>aK,allowsEval:()=>a8,aborted:()=>om,NUMBER_FORMAT_RANGES:()=>oo,Class:()=>oS,BIGINT_FORMAT_RANGES:()=>ol});var a4=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function a3(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}var a8=aH(()=>{if("u">typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return Function(""),!0}catch(t){return!1}});function a7(t){if(!1===a3(t))return!1;let r=t.constructor;if(void 0===r)return!0;let i=r.prototype;return!1!==a3(i)&&!1!==Object.prototype.hasOwnProperty.call(i,"isPrototypeOf")}function a9(t){let r=0;for(let i in t)Object.prototype.hasOwnProperty.call(t,i)&&r++;return r}var a5=t=>{let r=typeof t;switch(r){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(t))return"array";if(null===t)return"null";if(t.then&&"function"==typeof t.then&&t.catch&&"function"==typeof t.catch)return"promise";if("u">typeof Map&&t instanceof Map)return"map";if("u">typeof Set&&t instanceof Set)return"set";if("u">typeof Date&&t instanceof Date)return"date";if("u">typeof File&&t instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${r}`)}},a6=new Set(["string","number","symbol"]),oe=new Set(["string","number","bigint","boolean","symbol","undefined"]);function ot(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function or(t,r,i){let s=new t._zod.constr(r??t._zod.def);return(!r||i?.parent)&&(s._zod.parent=t),s}function oi(t){if(!t)return{};if("string"==typeof t)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return(delete t.message,"string"==typeof t.error)?{...t,error:()=>t.error}:t}function os(t){let r;return new Proxy({},{get:(i,s,n)=>(r??(r=t()),Reflect.get(r,s,n)),set:(i,s,n,a)=>(r??(r=t()),Reflect.set(r,s,n,a)),has:(i,s)=>(r??(r=t()),Reflect.has(r,s)),deleteProperty:(i,s)=>(r??(r=t()),Reflect.deleteProperty(r,s)),ownKeys:i=>(r??(r=t()),Reflect.ownKeys(r)),getOwnPropertyDescriptor:(i,s)=>(r??(r=t()),Reflect.getOwnPropertyDescriptor(r,s)),defineProperty:(i,s,n)=>(r??(r=t()),Reflect.defineProperty(r,s,n))})}function on(t){return"bigint"==typeof t?t.toString()+"n":"string"==typeof t?`"${t}"`:`${t}`}function oa(t){return Object.keys(t).filter(r=>"optional"===t[r]._zod.optin&&"optional"===t[r]._zod.optout)}var oo={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-0x80000000,0x7fffffff],uint32:[0,0xffffffff],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},ol={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function op(t,r){let i={},s=t._zod.def;for(let t in r){if(!(t in s.shape))throw Error(`Unrecognized key: "${t}"`);r[t]&&(i[t]=s.shape[t])}return or(t,{...t._zod.def,shape:i,checks:[]})}function ou(t,r){let i={...t._zod.def.shape},s=t._zod.def;for(let t in r){if(!(t in s.shape))throw Error(`Unrecognized key: "${t}"`);r[t]&&delete i[t]}return or(t,{...t._zod.def,shape:i,checks:[]})}function oc(t,r){if(!a7(r))throw Error("Invalid input to extend: expected a plain object");let i={...t._zod.def,get shape(){let i={...t._zod.def.shape,...r};return aZ(this,"shape",i),i},checks:[]};return or(t,i)}function od(t,r){return or(t,{...t._zod.def,get shape(){let i={...t._zod.def.shape,...r._zod.def.shape};return aZ(this,"shape",i),i},catchall:r._zod.def.catchall,checks:[]})}function oh(t,r,i){let s=r._zod.def.shape,n={...s};if(i)for(let r in i){if(!(r in s))throw Error(`Unrecognized key: "${r}"`);i[r]&&(n[r]=t?new t({type:"optional",innerType:s[r]}):s[r])}else for(let r in s)n[r]=t?new t({type:"optional",innerType:s[r]}):s[r];return or(r,{...r._zod.def,shape:n,checks:[]})}function of(t,r,i){let s=r._zod.def.shape,n={...s};if(i)for(let r in i){if(!(r in n))throw Error(`Unrecognized key: "${r}"`);i[r]&&(n[r]=new t({type:"nonoptional",innerType:s[r]}))}else for(let r in s)n[r]=new t({type:"nonoptional",innerType:s[r]});return or(r,{...r._zod.def,shape:n,checks:[]})}function om(t,r=0){for(let i=r;i<t.issues.length;i++)if(t.issues[i]?.continue!==!0)return!0;return!1}function oy(t,r){return r.map(r=>(r.path??(r.path=[]),r.path.unshift(t),r))}function ob(t){return"string"==typeof t?t:t?.message}function og(t,r,i){let s={...t,path:t.path??[]};return t.message||(s.message=ob(t.inst?._zod.def?.error?.(t))??ob(r?.error?.(t))??ob(i.customError?.(t))??ob(i.localeError?.(t))??"Invalid input"),delete s.inst,delete s.continue,r?.reportInput||delete s.input,s}function ov(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function ox(t){return Array.isArray(t)?"array":"string"==typeof t?"string":"unknown"}function oT(...t){let[r,i,s]=t;return"string"==typeof r?{message:r,code:"custom",input:i,inst:s}:{...r}}function oE(t){return Object.entries(t).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}class oS{constructor(...t){}}var o_=(t,r)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:r,enumerable:!1}),Object.defineProperty(t,"message",{get:()=>JSON.stringify(r,aW,2),enumerable:!0})},oP=aj("$ZodError",o_),oA=aj("$ZodError",o_,{Parent:Error}),ow=t=>(r,i,s,n)=>{let a=s?Object.assign(s,{async:!1}):{async:!1},o=r._zod.run({value:i,issues:[]},a);if(o instanceof Promise)throw new aL;if(o.issues.length){let r=new(n?.Err??t)(o.issues.map(t=>og(t,a,aM())));throw a4(r,n?.callee),r}return o.value},oC=ow(oA),oI=t=>async(r,i,s,n)=>{let a=s?Object.assign(s,{async:!0}):{async:!0},o=r._zod.run({value:i,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){let r=new(n?.Err??t)(o.issues.map(t=>og(t,a,aM())));throw a4(r,n?.callee),r}return o.value},ok=oI(oA),oN=t=>(r,i,s)=>{let n=s?{...s,async:!1}:{async:!1},a=r._zod.run({value:i,issues:[]},n);if(a instanceof Promise)throw new aL;return a.issues.length?{success:!1,error:new(t??oP)(a.issues.map(t=>og(t,n,aM())))}:{success:!0,data:a.value}},oO=oN(oA),oD=t=>async(r,i,s)=>{let n=s?Object.assign(s,{async:!0}):{async:!0},a=r._zod.run({value:i,issues:[]},n);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new t(a.issues.map(t=>og(t,n,aM())))}:{success:!0,data:a.value}},oj=oD(oA),oL=/^[cC][^\s-]{8,}$/,oR=/^[0-9a-z]+$/,oM=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,oF=/^[0-9a-vA-V]{20}$/,oB=/^[A-Za-z0-9]{27}$/,oU=/^[a-zA-Z0-9_-]{21}$/,o$=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,oV=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,oK=t=>t?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,oq=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,oz=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,oW=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,oH=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,oJ=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,oY=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,oX=/^[A-Za-z0-9_-]*$/,oG=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,oZ=/^\+(?:[0-9]){6,14}[0-9]$/,oQ="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",o0=RegExp(`^${oQ}$`);function o1(t){return"number"==typeof t.precision?-1===t.precision?"(?:[01]\\d|2[0-3]):[0-5]\\d":0===t.precision?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${t.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}var o2=/^\d+$/,o4=/^-?\d+(?:\.\d+)?/i,o3=/true|false/i,o8=/null/i,o7=/^[^A-Z]*$/,o9=/^[^a-z]*$/,o5=aj("$ZodCheck",(t,r)=>{var i;t._zod??(t._zod={}),t._zod.def=r,(i=t._zod).onattach??(i.onattach=[])}),o6={number:"number",bigint:"bigint",object:"date"},le=aj("$ZodCheckLessThan",(t,r)=>{o5.init(t,r);let i=o6[typeof r.value];t._zod.onattach.push(t=>{let i=t._zod.bag,s=(r.inclusive?i.maximum:i.exclusiveMaximum)??1/0;r.value<s&&(r.inclusive?i.maximum=r.value:i.exclusiveMaximum=r.value)}),t._zod.check=s=>{(r.inclusive?s.value<=r.value:s.value<r.value)||s.issues.push({origin:i,code:"too_big",maximum:r.value,input:s.value,inclusive:r.inclusive,inst:t,continue:!r.abort})}}),lt=aj("$ZodCheckGreaterThan",(t,r)=>{o5.init(t,r);let i=o6[typeof r.value];t._zod.onattach.push(t=>{let i=t._zod.bag,s=(r.inclusive?i.minimum:i.exclusiveMinimum)??-1/0;r.value>s&&(r.inclusive?i.minimum=r.value:i.exclusiveMinimum=r.value)}),t._zod.check=s=>{(r.inclusive?s.value>=r.value:s.value>r.value)||s.issues.push({origin:i,code:"too_small",minimum:r.value,input:s.value,inclusive:r.inclusive,inst:t,continue:!r.abort})}}),lr=aj("$ZodCheckMultipleOf",(t,r)=>{o5.init(t,r),t._zod.onattach.push(t=>{var i;(i=t._zod.bag).multipleOf??(i.multipleOf=r.value)}),t._zod.check=i=>{if(typeof i.value!=typeof r.value)throw Error("Cannot mix number and bigint in multiple_of check.");("bigint"==typeof i.value?i.value%r.value!==BigInt(0):0!==aX(i.value,r.value))&&i.issues.push({origin:typeof i.value,code:"not_multiple_of",divisor:r.value,input:i.value,inst:t,continue:!r.abort})}}),li=aj("$ZodCheckNumberFormat",(t,r)=>{o5.init(t,r),r.format=r.format||"float64";let i=r.format?.includes("int"),s=i?"int":"number",[n,a]=oo[r.format];t._zod.onattach.push(t=>{let s=t._zod.bag;s.format=r.format,s.minimum=n,s.maximum=a,i&&(s.pattern=o2)}),t._zod.check=o=>{let l=o.value;if(i){if(!Number.isInteger(l))return void o.issues.push({expected:s,format:r.format,code:"invalid_type",input:l,inst:t});if(!Number.isSafeInteger(l))return void(l>0?o.issues.push({input:l,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:s,continue:!r.abort}):o.issues.push({input:l,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:s,continue:!r.abort}))}l<n&&o.issues.push({origin:"number",input:l,code:"too_small",minimum:n,inclusive:!0,inst:t,continue:!r.abort}),l>a&&o.issues.push({origin:"number",input:l,code:"too_big",maximum:a,inst:t})}}),ls=aj("$ZodCheckMaxLength",(t,r)=>{o5.init(t,r),t._zod.when=t=>{let r=t.value;return!aJ(r)&&void 0!==r.length},t._zod.onattach.push(t=>{let i=t._zod.bag.maximum??1/0;r.maximum<i&&(t._zod.bag.maximum=r.maximum)}),t._zod.check=i=>{let s=i.value;if(s.length<=r.maximum)return;let n=ox(s);i.issues.push({origin:n,code:"too_big",maximum:r.maximum,inclusive:!0,input:s,inst:t,continue:!r.abort})}}),ln=aj("$ZodCheckMinLength",(t,r)=>{o5.init(t,r),t._zod.when=t=>{let r=t.value;return!aJ(r)&&void 0!==r.length},t._zod.onattach.push(t=>{let i=t._zod.bag.minimum??-1/0;r.minimum>i&&(t._zod.bag.minimum=r.minimum)}),t._zod.check=i=>{let s=i.value;if(s.length>=r.minimum)return;let n=ox(s);i.issues.push({origin:n,code:"too_small",minimum:r.minimum,inclusive:!0,input:s,inst:t,continue:!r.abort})}}),la=aj("$ZodCheckLengthEquals",(t,r)=>{o5.init(t,r),t._zod.when=t=>{let r=t.value;return!aJ(r)&&void 0!==r.length},t._zod.onattach.push(t=>{let i=t._zod.bag;i.minimum=r.length,i.maximum=r.length,i.length=r.length}),t._zod.check=i=>{let s=i.value,n=s.length;if(n===r.length)return;let a=ox(s),o=n>r.length;i.issues.push({origin:a,...o?{code:"too_big",maximum:r.length}:{code:"too_small",minimum:r.length},inclusive:!0,exact:!0,input:i.value,inst:t,continue:!r.abort})}}),lo=aj("$ZodCheckStringFormat",(t,r)=>{var i,s;(o5.init(t,r),t._zod.onattach.push(t=>{let i=t._zod.bag;i.format=r.format,r.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(r.pattern))}),r.pattern)?(i=t._zod).check??(i.check=i=>{r.pattern.lastIndex=0,r.pattern.test(i.value)||i.issues.push({origin:"string",code:"invalid_format",format:r.format,input:i.value,...r.pattern?{pattern:r.pattern.toString()}:{},inst:t,continue:!r.abort})}):(s=t._zod).check??(s.check=()=>{})}),ll=aj("$ZodCheckRegex",(t,r)=>{lo.init(t,r),t._zod.check=i=>{r.pattern.lastIndex=0,r.pattern.test(i.value)||i.issues.push({origin:"string",code:"invalid_format",format:"regex",input:i.value,pattern:r.pattern.toString(),inst:t,continue:!r.abort})}}),lp=aj("$ZodCheckLowerCase",(t,r)=>{r.pattern??(r.pattern=o7),lo.init(t,r)}),lu=aj("$ZodCheckUpperCase",(t,r)=>{r.pattern??(r.pattern=o9),lo.init(t,r)}),lc=aj("$ZodCheckIncludes",(t,r)=>{o5.init(t,r);let i=ot(r.includes),s=new RegExp("number"==typeof r.position?`^.{${r.position}}${i}`:i);r.pattern=s,t._zod.onattach.push(t=>{let r=t._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(s)}),t._zod.check=i=>{i.value.includes(r.includes,r.position)||i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:r.includes,input:i.value,inst:t,continue:!r.abort})}}),ld=aj("$ZodCheckStartsWith",(t,r)=>{o5.init(t,r);let i=RegExp(`^${ot(r.prefix)}.*`);r.pattern??(r.pattern=i),t._zod.onattach.push(t=>{let r=t._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(i)}),t._zod.check=i=>{i.value.startsWith(r.prefix)||i.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:r.prefix,input:i.value,inst:t,continue:!r.abort})}}),lh=aj("$ZodCheckEndsWith",(t,r)=>{o5.init(t,r);let i=RegExp(`.*${ot(r.suffix)}$`);r.pattern??(r.pattern=i),t._zod.onattach.push(t=>{let r=t._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(i)}),t._zod.check=i=>{i.value.endsWith(r.suffix)||i.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:r.suffix,input:i.value,inst:t,continue:!r.abort})}}),lf=aj("$ZodCheckOverwrite",(t,r)=>{o5.init(t,r),t._zod.check=t=>{t.value=r.tx(t.value)}});class lm{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if("function"==typeof t){t(this,{execution:"sync"}),t(this,{execution:"async"});return}let r=t.split(`
|
|
360
|
+
deps: ${s}}`};var n={keyword:"dependencies",type:"object",schemaType:"object",error:t.error,code(t){let[r,i]=function({schema:t}){let r={},i={};for(let s in t)"__proto__"!==s&&((Array.isArray(t[s])?r:i)[s]=t[s]);return[r,i]}(t);a(t,r),o(t,i)}};function a(t,i=t.schema){let{gen:n,data:o,it:l}=t;if(0===Object.keys(i).length)return;let p=n.let("missing");for(let a in i){let u=i[a];if(0===u.length)continue;let c=(0,s.propertyInData)(n,o,a,l.opts.ownProperties);(t.setParams({property:a,depsCount:u.length,deps:u.join(", ")}),l.allErrors)?n.if(c,()=>{for(let r of u)(0,s.checkReportMissingProp)(t,r)}):(n.if(r._`${c} && (${(0,s.checkMissingProp)(t,u,p)})`),(0,s.reportMissingProp)(t,p),n.else())}}function o(t,r=t.schema){let{gen:n,data:a,keyword:l,it:p}=t,u=n.name("valid");for(let o in r)(0,i.alwaysValidSchema)(p,r[o])||(n.if((0,s.propertyInData)(n,a,o,p.opts.ownProperties),()=>{let r=t.subschema({keyword:l,schemaProp:o},u);t.mergeValidEvaluated(r,u)},()=>n.var(u,!0)),t.ok(u))}t.validatePropertyDeps=a,t.validateSchemaDeps=o,t.default=n}),ir=rl(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=rg(),i=rv();t.default={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:{message:"property name must be valid",params:({params:t})=>r._`{propertyName: ${t.propertyName}}`},code(t){let{gen:s,schema:n,data:a,it:o}=t;if((0,i.alwaysValidSchema)(o,n))return;let l=s.name("valid");s.forIn("key",a,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},l),s.if((0,r.not)(l),()=>{t.error(!0),o.allErrors||s.break()})}),t.ok(l)}}}),ii=rl(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=rw(),i=rg(),s=rx(),n=rv();t.default={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:({params:t})=>i._`{additionalProperty: ${t.additionalProperty}}`},code(t){let{gen:a,schema:o,parentSchema:l,data:p,errsCount:u,it:c}=t;if(!u)throw Error("ajv implementation error");let{allErrors:d,opts:h}=c;if(c.props=!0,"all"!==h.removeAdditional&&(0,n.alwaysValidSchema)(c,o))return;let f=(0,r.allSchemaProperties)(l.properties),m=(0,r.allSchemaProperties)(l.patternProperties);function y(t){a.code(i._`delete ${p}[${t}]`)}function b(r){if("all"===h.removeAdditional||h.removeAdditional&&!1===o)return void y(r);if(!1===o){t.setParams({additionalProperty:r}),t.error(),d||a.break();return}if("object"==typeof o&&!(0,n.alwaysValidSchema)(c,o)){let s=a.name("valid");"failing"===h.removeAdditional?(g(r,s,!1),a.if((0,i.not)(s),()=>{t.reset(),y(r)})):(g(r,s),d||a.if((0,i.not)(s),()=>a.break()))}}function g(r,i,s){let a={keyword:"additionalProperties",dataProp:r,dataPropType:n.Type.Str};!1===s&&Object.assign(a,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(a,i)}a.forIn("key",p,s=>{f.length||m.length?a.if(function(s){let o;if(f.length>8){let t=(0,n.schemaRefOrVal)(c,l.properties,"properties");o=(0,r.isOwnProperty)(a,t,s)}else o=f.length?(0,i.or)(...f.map(t=>i._`${s} === ${t}`)):i.nil;return m.length&&(o=(0,i.or)(o,...m.map(n=>i._`${(0,r.usePattern)(t,n)}.test(${s})`))),(0,i.not)(o)}(s),()=>b(s)):b(s)}),t.ok(i._`${u} === ${s.default.errors}`)}}}),is=rl(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=rD(),i=rw(),s=rv(),n=ii();t.default={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:a,schema:o,parentSchema:l,data:p,it:u}=t;"all"===u.opts.removeAdditional&&void 0===l.additionalProperties&&n.default.code(new r.KeywordCxt(u,n.default,"additionalProperties"));let c=(0,i.allSchemaProperties)(o);for(let t of c)u.definedProperties.add(t);u.opts.unevaluated&&c.length&&!0!==u.props&&(u.props=s.mergeEvaluated.props(a,(0,s.toHash)(c),u.props));let d=c.filter(t=>!(0,s.alwaysValidSchema)(u,o[t]));if(0===d.length)return;let h=a.name("valid");for(let r of d){var f;(f=r,u.opts.useDefaults&&!u.compositeRule&&void 0!==o[f].default)?m(r):(a.if((0,i.propertyInData)(a,p,r,u.opts.ownProperties)),m(r),u.allErrors||a.else().var(h,!0),a.endIf()),t.it.definedProperties.add(r),t.ok(h)}function m(r){t.subschema({keyword:"properties",schemaProp:r,dataProp:r},h)}}}}),ia=rl(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=rw(),i=rg(),s=rv(),n=rv();t.default={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:a,schema:o,data:l,parentSchema:p,it:u}=t,{opts:c}=u,d=(0,r.allSchemaProperties)(o),h=d.filter(t=>(0,s.alwaysValidSchema)(u,o[t]));if(0===d.length||h.length===d.length&&(!u.opts.unevaluated||!0===u.props))return;let f=c.strictSchema&&!c.allowMatchingProperties&&p.properties,m=a.name("valid");!0===u.props||u.props instanceof i.Name||(u.props=(0,n.evaluatedPropsToName)(a,u.props));let{props:y}=u;for(let t of d)f&&function(t){for(let r in f)new RegExp(t).test(r)&&(0,s.checkStrictMode)(u,`property ${r} matches pattern ${t} (use allowMatchingProperties)`)}(t),u.allErrors?b(t):(a.var(m,!0),b(t),a.if(m));function b(s){a.forIn("key",l,o=>{a.if(i._`${(0,r.usePattern)(t,s)}.test(${o})`,()=>{let r=h.includes(s);r||t.subschema({keyword:"patternProperties",schemaProp:s,dataProp:o,dataPropType:n.Type.Str},m),u.opts.unevaluated&&!0!==y?a.assign(i._`${y}[${o}]`,!0):r||u.allErrors||a.if((0,i.not)(m),()=>a.break())})})}}}}),io=rl(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=rv();t.default={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:i,schema:s,it:n}=t;if((0,r.alwaysValidSchema)(n,s))return void t.fail();let a=i.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},a),t.failResult(a,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}}}),il=rl(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:rw().validateUnion,error:{message:"must match a schema in anyOf"}}}),ip=rl(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=rg(),i=rv();t.default={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:{message:"must match exactly one schema in oneOf",params:({params:t})=>r._`{passingSchemas: ${t.passing}}`},code(t){let{gen:s,schema:n,parentSchema:a,it:o}=t;if(!Array.isArray(n))throw Error("ajv implementation error");if(o.opts.discriminator&&a.discriminator)return;let l=s.let("valid",!1),p=s.let("passing",null),u=s.name("_valid");t.setParams({passing:p}),s.block(function(){n.forEach((n,a)=>{let c;(0,i.alwaysValidSchema)(o,n)?s.var(u,!0):c=t.subschema({keyword:"oneOf",schemaProp:a,compositeRule:!0},u),a>0&&s.if(r._`${u} && ${l}`).assign(l,!1).assign(p,r._`[${p}, ${a}]`).else(),s.if(u,()=>{s.assign(l,!0),s.assign(p,a),c&&t.mergeEvaluated(c,r.Name)})})}),t.result(l,()=>t.reset(),()=>t.error(!0))}}}),iu=rl(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=rv();t.default={keyword:"allOf",schemaType:"array",code(t){let{gen:i,schema:s,it:n}=t;if(!Array.isArray(s))throw Error("ajv implementation error");let a=i.name("valid");s.forEach((i,s)=>{if((0,r.alwaysValidSchema)(n,i))return;let o=t.subschema({keyword:"allOf",schemaProp:s},a);t.ok(a),t.mergeEvaluated(o)})}}}),ic=rl(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=rg(),i=rv();function s(t,r){let s=t.schema[r];return void 0!==s&&!(0,i.alwaysValidSchema)(t,s)}t.default={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:{message:({params:t})=>r.str`must match "${t.ifClause}" schema`,params:({params:t})=>r._`{failingKeyword: ${t.ifClause}}`},code(t){let n,{gen:a,parentSchema:o,it:l}=t;void 0===o.then&&void 0===o.else&&(0,i.checkStrictMode)(l,'"if" without "then" and "else" is ignored');let p=s(l,"then"),u=s(l,"else");if(!p&&!u)return;let c=a.let("valid",!0),d=a.name("_valid");if(n=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},d),t.mergeEvaluated(n),t.reset(),p&&u){let r=a.let("ifClause");t.setParams({ifClause:r}),a.if(d,h("then",r),h("else",r))}else p?a.if(d,h("then")):a.if((0,r.not)(d),h("else"));function h(i,s){return()=>{let n=t.subschema({keyword:i},d);(a.assign(c,d),t.mergeValidEvaluated(n,c),s)?a.assign(s,r._`${i}`):t.setParams({ifClause:i})}}t.pass(c,()=>t.error(!0))}}}),id=rl(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=rv();t.default={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:i,it:s}){void 0===i.if&&(0,r.checkStrictMode)(s,`"${t}" without "if" is ignored`)}}}),ih=rl(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=r7(),i=r5(),s=r9(),n=r6(),a=ie(),o=it(),l=ir(),p=ii(),u=is(),c=ia(),d=io(),h=il(),f=ip(),m=iu(),y=ic(),b=id();t.default=function(t=!1){let g=[d.default,h.default,f.default,m.default,y.default,b.default,l.default,p.default,o.default,u.default,c.default];return t?g.push(i.default,n.default):g.push(r.default,s.default),g.push(a.default),g}}),im=rl(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=rg();t.default={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode:t})=>r.str`must match format "${t}"`,params:({schemaCode:t})=>r._`{format: ${t}}`},code(t,i){let s,n,a,o,l,p,{gen:u,data:c,$data:d,schema:h,schemaCode:f,it:m}=t,{opts:y,errSchemaPath:b,schemaEnv:g,self:v}=m;y.validateFormats&&(d?(s=u.scopeValue("formats",{ref:v.formats,code:y.code.formats}),n=u.const("fDef",r._`${s}[${f}]`),a=u.let("fType"),o=u.let("format"),u.if(r._`typeof ${n} == "object" && !(${n} instanceof RegExp)`,()=>u.assign(a,r._`${n}.type || "string"`).assign(o,r._`${n}.validate`),()=>u.assign(a,r._`"string"`).assign(o,n)),t.fail$data((0,r.or)(!1===y.strictSchema?r.nil:r._`${f} && !${o}`,(l=g.$async?r._`(${n}.async ? await ${o}(${c}) : ${o}(${c}))`:r._`${o}(${c})`,p=r._`(typeof ${o} == "function" ? ${l} : ${o}.test(${c}))`,r._`${o} && ${o} !== true && ${a} === ${i} && !${p}`)))):function(){var s;let n,a,o=v.formats[h];if(!o){if(!1===y.strictSchema)return v.logger.warn(l());throw Error(l());function l(){return`unknown format "${h}" ignored in schema at path "${b}"`}}if(!0===o)return;let[p,d,f]=(n=(s=o)instanceof RegExp?(0,r.regexpCode)(s):y.code.formats?r._`${y.code.formats}${(0,r.getProperty)(h)}`:void 0,a=u.scopeValue("formats",{key:h,ref:s,code:n}),"object"!=typeof s||s instanceof RegExp?["string",s,a]:[s.type||"string",s.validate,r._`${a}.validate`]);p===i&&t.pass(function(){if("object"==typeof o&&!(o instanceof RegExp)&&o.async){if(!g.$async)throw Error("async format in sync schema");return r._`await ${f}(${c})`}return"function"==typeof d?r._`${f}(${c})`:r._`${f}.test(${c})`}())}())}}}),iy=rl(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=[im().default]}),ib=rl(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.contentVocabulary=t.metadataVocabulary=void 0,t.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],t.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]}),ig=rl(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=rW(),i=r8(),s=ih(),n=iy(),a=ib();t.default=[r.default,i.default,(0,s.default)(),n.default,a.metadataVocabulary,a.contentVocabulary]}),iv=rl(t=>{var r,i;Object.defineProperty(t,"__esModule",{value:!0}),t.DiscrError=void 0,(i=r||(t.DiscrError=r={})).Tag="tag",i.Mapping="mapping"}),ix=rl(t=>{Object.defineProperty(t,"__esModule",{value:!0});var r=rg(),i=iv(),s=rR(),n=rL(),a=rv();t.default={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError:t,tagName:r}})=>t===i.DiscrError.Tag?`tag "${r}" must be string`:`value of tag "${r}" must be in oneOf`,params:({params:{discrError:t,tag:i,tagName:s}})=>r._`{error: ${t}, tag: ${s}, tagValue: ${i}}`},code(t){let{gen:o,data:l,schema:p,parentSchema:u,it:c}=t,{oneOf:d}=u;if(!c.opts.discriminator)throw Error("discriminator: requires discriminator option");let h=p.propertyName;if("string"!=typeof h)throw Error("discriminator: requires propertyName");if(p.mapping)throw Error("discriminator: mapping is not supported");if(!d)throw Error("discriminator: requires oneOf keyword");let f=o.let("valid",!1),m=o.const("tag",r._`${l}${(0,r.getProperty)(h)}`);o.if(r._`typeof ${m} == "string"`,()=>(function(){let l=function(){var t;let r={},i=l(u),o=!0;for(let r=0;r<d.length;r++){let u=d[r];if((null==u?void 0:u.$ref)&&!(0,a.schemaHasRulesButRef)(u,c.self.RULES)){let t=u.$ref;if((u=s.resolveRef.call(c.self,c.schemaEnv.root,c.baseId,t))instanceof s.SchemaEnv&&(u=u.schema),void 0===u)throw new n.default(c.opts.uriResolver,c.baseId,t)}let f=null==(t=null==u?void 0:u.properties)?void 0:t[h];if("object"!=typeof f)throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${h}"`);o=o&&(i||l(u)),function(t,r){if(t.const)p(t.const,r);else if(t.enum)for(let i of t.enum)p(i,r);else throw Error(`discriminator: "properties/${h}" must have "const" or "enum"`)}(f,r)}if(!o)throw Error(`discriminator: "${h}" must be required`);return r;function l({required:t}){return Array.isArray(t)&&t.includes(h)}function p(t,i){if("string"!=typeof t||t in r)throw Error(`discriminator: "${h}" values must be unique strings`);r[t]=i}}();for(let i in o.if(!1),l)o.elseIf(r._`${m} === ${i}`),o.assign(f,function(i){let s=o.name("valid"),n=t.subschema({keyword:"oneOf",schemaProp:i},s);return t.mergeEvaluated(n,r.Name),s}(l[i]));o.else(),t.error(!1,{discrError:i.DiscrError.Mapping,tag:m,tagName:h}),o.endIf()})(),()=>t.error(!1,{discrError:i.DiscrError.Tag,tag:m,tagName:h})),t.ok(f)}}}),iT=rl((t,r)=>{r.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}}),iE=rl((t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MissingRefError=t.ValidationError=t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=t.Ajv=void 0;var i=rK(),s=ig(),n=ix(),a=iT(),o=["/properties"],l="http://json-schema.org/draft-07/schema";class p extends i.default{_addVocabularies(){super._addVocabularies(),s.default.forEach(t=>this.addVocabulary(t)),this.opts.discriminator&&this.addKeyword(n.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let t=this.opts.$data?this.$dataMetaSchema(a,o):a;this.addMetaSchema(t,l,!1),this.refs["http://json-schema.org/schema"]=l}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(l)?l:void 0)}}t.Ajv=p,r.exports=t=p,r.exports.Ajv=p,Object.defineProperty(t,"__esModule",{value:!0}),t.default=p;var u=rD();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return u.KeywordCxt}});var c=rg();Object.defineProperty(t,"_",{enumerable:!0,get:function(){return c._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return c.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return c.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return c.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return c.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return c.CodeGen}});var d=rj();Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return d.default}});var h=rL();Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return h.default}})}),iS=rl(t=>{function r(t,r){return{validate:t,compare:r}}Object.defineProperty(t,"__esModule",{value:!0}),t.formatNames=t.fastFormats=t.fullFormats=void 0,t.fullFormats={date:r(n,a),time:r(l(!0),p),"date-time":r(d(!0),h),"iso-time":r(l(),u),"iso-date-time":r(d(),f),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:function(t){return m.test(t)&&y.test(t)},"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:function(t){if(v.test(t))return!1;try{return new RegExp(t),!0}catch(t){return!1}},uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:function(t){return b.lastIndex=0,b.test(t)},int32:{type:"number",validate:function(t){return Number.isInteger(t)&&t<=0x7fffffff&&t>=-0x80000000}},int64:{type:"number",validate:function(t){return Number.isInteger(t)}},float:{type:"number",validate:g},double:{type:"number",validate:g},password:!0,binary:!0},t.fastFormats={...t.fullFormats,date:r(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,a),time:r(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,p),"date-time":r(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,h),"iso-time":r(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,u),"iso-date-time":r(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,f),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},t.formatNames=Object.keys(t.fullFormats);var i=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,s=[0,31,28,31,30,31,30,31,31,30,31,30,31];function n(t){var r;let n=i.exec(t);if(!n)return!1;let a=+n[1],o=+n[2],l=+n[3];return o>=1&&o<=12&&l>=1&&l<=(2===o&&(r=a)%4==0&&(r%100!=0||r%400==0)?29:s[o])}function a(t,r){if(t&&r)return t>r?1:t<r?-1:0}var o=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function l(t){return function(r){let i=o.exec(r);if(!i)return!1;let s=+i[1],n=+i[2],a=+i[3],l=i[4],p="-"===i[5]?-1:1,u=+(i[6]||0),c=+(i[7]||0);if(u>23||c>59||t&&!l)return!1;if(s<=23&&n<=59&&a<60)return!0;let d=n-c*p,h=s-u*p-(d<0);return(23===h||-1===h)&&(59===d||-1===d)&&a<61}}function p(t,r){if(!(t&&r))return;let i=new Date("2020-01-01T"+t).valueOf(),s=new Date("2020-01-01T"+r).valueOf();if(i&&s)return i-s}function u(t,r){if(!(t&&r))return;let i=o.exec(t),s=o.exec(r);if(i&&s)return(t=i[1]+i[2]+i[3])>(r=s[1]+s[2]+s[3])?1:t<r?-1:0}var c=/t|\s/i;function d(t){let r=l(t);return function(t){let i=t.split(c);return 2===i.length&&n(i[0])&&r(i[1])}}function h(t,r){if(!(t&&r))return;let i=new Date(t).valueOf(),s=new Date(r).valueOf();if(i&&s)return i-s}function f(t,r){if(!(t&&r))return;let[i,s]=t.split(c),[n,o]=r.split(c),l=a(i,n);if(void 0!==l)return l||p(s,o)}var m=/\/|:/,y=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,b=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function g(){return!0}var v=/[^\\]\\Z/}),i_=rl(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.formatLimitDefinition=void 0;var r=iE(),i=rg(),s=i.operators,n={formatMaximum:{okStr:"<=",ok:s.LTE,fail:s.GT},formatMinimum:{okStr:">=",ok:s.GTE,fail:s.LT},formatExclusiveMaximum:{okStr:"<",ok:s.LT,fail:s.GTE},formatExclusiveMinimum:{okStr:">",ok:s.GT,fail:s.LTE}};t.formatLimitDefinition={keyword:Object.keys(n),type:"string",schemaType:"string",$data:!0,error:{message:({keyword:t,schemaCode:r})=>i.str`should be ${n[t].okStr} ${r}`,params:({keyword:t,schemaCode:r})=>i._`{comparison: ${n[t].okStr}, limit: ${r}}`},code(t){let s,a,{gen:o,data:l,schemaCode:p,keyword:u,it:c}=t,{opts:d,self:h}=c;if(!d.validateFormats)return;let f=new r.KeywordCxt(c,h.RULES.all.format.definition,"format");function m(t){return i._`${t}.compare(${l}, ${p}) ${n[u].fail} 0`}f.$data?(s=o.scopeValue("formats",{ref:h.formats,code:d.code.formats}),a=o.const("fmt",i._`${s}[${f.schemaCode}]`),t.fail$data((0,i.or)(i._`typeof ${a} != "object"`,i._`${a} instanceof RegExp`,i._`typeof ${a}.compare != "function"`,m(a)))):function(){let r=f.schema,s=h.formats[r];if(!s||!0===s)return;if("object"!=typeof s||s instanceof RegExp||"function"!=typeof s.compare)throw Error(`"${u}": format "${r}" does not define "compare" function`);let n=o.scopeValue("formats",{key:r,ref:s,code:d.code.formats?i._`${d.code.formats}${(0,i.getProperty)(r)}`:void 0});t.fail$data(m(n))}()},dependencies:["format"]},t.default=r=>(r.addKeyword(t.formatLimitDefinition),r)}),iP=rl((t,r)=>{Object.defineProperty(t,"__esModule",{value:!0});var i=iS(),s=i_(),n=rg(),a=new n.Name("fullFormats"),o=new n.Name("fastFormats"),l=(t,r={keywords:!0})=>{if(Array.isArray(r))return p(t,r,i.fullFormats,a),t;let[n,l]="fast"===r.mode?[i.fastFormats,o]:[i.fullFormats,a];return p(t,r.formats||i.formatNames,n,l),r.keywords&&(0,s.default)(t),t};function p(t,r,i,s){var a;for(let o of(null!=(a=t.opts.code).formats||(a.formats=n._`require("ajv-formats/dist/formats").${s}`),r))t.addFormat(o,i[o])}l.get=(t,r="full")=>{let s=("fast"===r?i.fastFormats:i.fullFormats)[t];if(!s)throw Error(`Unknown format "${t}"`);return s},r.exports=t=l,Object.defineProperty(t,"__esModule",{value:!0}),t.default=l});function iA(t=50){let r=new AbortController;return(0,t1.setMaxListeners)(t,r.signal),r}class iw extends Error{}function iC(){return void 0!==process.versions.bun}var iI=t.g&&t.g.Object===Object&&t.g,ik="object"==typeof self&&self&&self.Object===Object&&self,iN=iI||ik||Function("return this")(),iO=iN.Symbol,iD=Object.prototype,ij=iD.hasOwnProperty,iL=iD.toString,iR=iO?iO.toStringTag:void 0,iM=function(t){var r=ij.call(t,iR),i=t[iR];try{t[iR]=void 0;var s=!0}catch(t){}var n=iL.call(t);return s&&(r?t[iR]=i:delete t[iR]),n},iF=Object.prototype.toString,iB=iO?iO.toStringTag:void 0,iU=function(t){return null==t?void 0===t?"[object Undefined]":"[object Null]":iB&&iB in Object(t)?iM(t):iF.call(t)},i$=function(t){var r=typeof t;return null!=t&&("object"==r||"function"==r)},iV=function(t){if(!i$(t))return!1;var r=iU(t);return"[object Function]"==r||"[object GeneratorFunction]"==r||"[object AsyncFunction]"==r||"[object Proxy]"==r},iK=iN["__core-js_shared__"],iq=(ss=/[^.]+$/.exec(iK&&iK.keys&&iK.keys.IE_PROTO||""))?"Symbol(src)_1."+ss:"",iz=Function.prototype.toString,iW=function(t){if(null!=t){try{return iz.call(t)}catch(t){}try{return t+""}catch(t){}}return""},iH=/^\[object .+?Constructor\]$/,iJ=Object.prototype,iY=Function.prototype.toString,iX=iJ.hasOwnProperty,iG=RegExp("^"+iY.call(iX).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),iZ=function(t){return!!i$(t)&&(!iq||!(iq in t))&&(iV(t)?iG:iH).test(iW(t))},iQ=function(t,r){var i=null==t?void 0:t[r];return iZ(i)?i:void 0},i0=iQ(Object,"create"),i1=Object.prototype.hasOwnProperty,i2=Object.prototype.hasOwnProperty;function i4(t){var r=-1,i=null==t?0:t.length;for(this.clear();++r<i;){var s=t[r];this.set(s[0],s[1])}}i4.prototype.clear=function(){this.__data__=i0?i0(null):{},this.size=0},i4.prototype.delete=function(t){var r=this.has(t)&&delete this.__data__[t];return this.size-=!!r,r},i4.prototype.get=function(t){var r=this.__data__;if(i0){var i=r[t];return"__lodash_hash_undefined__"===i?void 0:i}return i1.call(r,t)?r[t]:void 0},i4.prototype.has=function(t){var r=this.__data__;return i0?void 0!==r[t]:i2.call(r,t)},i4.prototype.set=function(t,r){var i=this.__data__;return this.size+=+!this.has(t),i[t]=i0&&void 0===r?"__lodash_hash_undefined__":r,this};var i3=function(t,r){for(var i,s=t.length;s--;)if((i=t[s][0])===r||i!=i&&r!=r)return s;return -1},i8=Array.prototype.splice;function i7(t){var r=-1,i=null==t?0:t.length;for(this.clear();++r<i;){var s=t[r];this.set(s[0],s[1])}}i7.prototype.clear=function(){this.__data__=[],this.size=0},i7.prototype.delete=function(t){var r=this.__data__,i=i3(r,t);return!(i<0)&&(i==r.length-1?r.pop():i8.call(r,i,1),--this.size,!0)},i7.prototype.get=function(t){var r=this.__data__,i=i3(r,t);return i<0?void 0:r[i][1]},i7.prototype.has=function(t){return i3(this.__data__,t)>-1},i7.prototype.set=function(t,r){var i=this.__data__,s=i3(i,t);return s<0?(++this.size,i.push([t,r])):i[s][1]=r,this};var i9=iQ(iN,"Map"),i5=function(t){var r=typeof t;return"string"==r||"number"==r||"symbol"==r||"boolean"==r?"__proto__"!==t:null===t},i6=function(t,r){var i=t.__data__;return i5(r)?i["string"==typeof r?"string":"hash"]:i.map};function se(t){var r=-1,i=null==t?0:t.length;for(this.clear();++r<i;){var s=t[r];this.set(s[0],s[1])}}function st(t,r){if("function"!=typeof t||null!=r&&"function"!=typeof r)throw TypeError("Expected a function");var i=function(){var s=arguments,n=r?r.apply(this,s):s[0],a=i.cache;if(a.has(n))return a.get(n);var o=t.apply(this,s);return i.cache=a.set(n,o)||a,o};return i.cache=new(st.Cache||se),i}se.prototype.clear=function(){this.size=0,this.__data__={hash:new i4,map:new(i9||i7),string:new i4}},se.prototype.delete=function(t){var r=i6(this,t).delete(t);return this.size-=!!r,r},se.prototype.get=function(t){return i6(this,t).get(t)},se.prototype.has=function(t){return i6(this,t).has(t)},se.prototype.set=function(t,r){var i=i6(this,t),s=i.size;return i.set(t,r),this.size+=+(i.size!=s),this},st.Cache=se;var sr=st(()=>(process.env.CLAUDE_CONFIG_DIR??(0,tK.join)((0,t8.homedir)(),".claude")).normalize("NFC"),()=>process.env.CLAUDE_CONFIG_DIR);function si(t){return!!t&&("boolean"==typeof t?t:["1","true","yes","on"].includes(t.toLowerCase().trim()))}var ss,sn,sa=null;function so(t){if(null===sn)return;let r=`${new Date().toISOString()} ${t}
|
|
361
|
+
`;(function(){if(sa)return sa;if(!process.env.DEBUG_CLAUDE_AGENT_SDK)return sn=null,sa=Promise.resolve();let t=(0,tK.join)(sr(),"debug");return sn=(0,tK.join)(t,`sdk-${(0,t$.randomUUID)()}.txt`),process.stderr.write(`SDK debug logs: ${sn}
|
|
362
|
+
`),sa=(0,t3.mkdir)(t,{recursive:!0}).then(()=>{}).catch(()=>{})})().then(()=>{sn&&(0,t3.appendFile)(sn,r).catch(()=>{})})}var sl=st(t=>{if(!t||""===t.trim())return null;let r=t.split(",").map(t=>t.trim()).filter(Boolean);if(0===r.length)return null;let i=r.some(t=>t.startsWith("!")),s=r.some(t=>!t.startsWith("!"));if(i&&s)return null;let n=r.map(t=>t.replace(/^!/,"").toLowerCase());return{include:i?[]:n,exclude:i?n:[],isExclusive:i}}),sp={cwd:()=>process.cwd(),existsSync(t){let r=[];try{return rf(r,s_`fs.existsSync(${t})`,0),tV.existsSync(t)}catch(t){var i=t,s=1}finally{rm(r,i,s)}},stat:async t=>(0,t3.stat)(t),readdir:async t=>(0,t3.readdir)(t,{withFileTypes:!0}),unlink:async t=>(0,t3.unlink)(t),rmdir:async t=>(0,t3.rmdir)(t),rm:async(t,r)=>(0,t3.rm)(t,r),async mkdir(t,r){try{await (0,t3.mkdir)(t,{recursive:!0,...r})}catch(t){if("EEXIST"!==t.code)throw t}},readFile:async(t,r)=>(0,t3.readFile)(t,{encoding:r.encoding}),rename:async(t,r)=>(0,t3.rename)(t,r),statSync(t){let r=[];try{return rf(r,s_`fs.statSync(${t})`,0),tV.statSync(t)}catch(t){var i=t,s=1}finally{rm(r,i,s)}},lstatSync(t){let r=[];try{return rf(r,s_`fs.lstatSync(${t})`,0),tV.lstatSync(t)}catch(t){var i=t,s=1}finally{rm(r,i,s)}},readFileSync(t,r){let i=[];try{return rf(i,s_`fs.readFileSync(${t})`,0),tV.readFileSync(t,{encoding:r.encoding})}catch(t){var s=t,n=1}finally{rm(i,s,n)}},readFileBytesSync(t){let r=[];try{return rf(r,s_`fs.readFileBytesSync(${t})`,0),tV.readFileSync(t)}catch(t){var i=t,s=1}finally{rm(r,i,s)}},readSync(t,r){let i=[];try{let s;rf(i,s_`fs.readSync(${t}, ${r.length} bytes)`,0);try{s=tV.openSync(t,"r");let i=Buffer.alloc(r.length),n=tV.readSync(s,i,0,r.length,0);return{buffer:i,bytesRead:n}}finally{s&&tV.closeSync(s)}}catch(t){var s=t,n=1}finally{rm(i,s,n)}},appendFileSync(t,r,i){let s=[];try{if(rf(s,s_`fs.appendFileSync(${t}, ${r.length} chars)`,0),i?.mode!==void 0)try{let s=tV.openSync(t,"ax",i.mode);try{tV.appendFileSync(s,r)}finally{tV.closeSync(s)}return}catch(t){if("EEXIST"!==t.code)throw t}tV.appendFileSync(t,r)}catch(t){var n=t,a=1}finally{rm(s,n,a)}},copyFileSync(t,r){let i=[];try{rf(i,s_`fs.copyFileSync(${t} → ${r})`,0),tV.copyFileSync(t,r)}catch(t){var s=t,n=1}finally{rm(i,s,n)}},unlinkSync(t){let r=[];try{rf(r,s_`fs.unlinkSync(${t})`,0),tV.unlinkSync(t)}catch(t){var i=t,s=1}finally{rm(r,i,s)}},renameSync(t,r){let i=[];try{rf(i,s_`fs.renameSync(${t} → ${r})`,0),tV.renameSync(t,r)}catch(t){var s=t,n=1}finally{rm(i,s,n)}},linkSync(t,r){let i=[];try{rf(i,s_`fs.linkSync(${t} → ${r})`,0),tV.linkSync(t,r)}catch(t){var s=t,n=1}finally{rm(i,s,n)}},symlinkSync(t,r,i){let s=[];try{rf(s,s_`fs.symlinkSync(${t} → ${r})`,0),tV.symlinkSync(t,r,i)}catch(t){var n=t,a=1}finally{rm(s,n,a)}},readlinkSync(t){let r=[];try{return rf(r,s_`fs.readlinkSync(${t})`,0),tV.readlinkSync(t)}catch(t){var i=t,s=1}finally{rm(r,i,s)}},realpathSync(t){let r=[];try{return rf(r,s_`fs.realpathSync(${t})`,0),tV.realpathSync(t).normalize("NFC")}catch(t){var i=t,s=1}finally{rm(r,i,s)}},mkdirSync(t,r){let i=[];try{rf(i,s_`fs.mkdirSync(${t})`,0);let s={recursive:!0};r?.mode!==void 0&&(s.mode=r.mode);try{tV.mkdirSync(t,s)}catch(t){if("EEXIST"!==t.code)throw t}}catch(t){var s=t,n=1}finally{rm(i,s,n)}},readdirSync(t){let r=[];try{return rf(r,s_`fs.readdirSync(${t})`,0),tV.readdirSync(t,{withFileTypes:!0})}catch(t){var i=t,s=1}finally{rm(r,i,s)}},readdirStringSync(t){let r=[];try{return rf(r,s_`fs.readdirStringSync(${t})`,0),tV.readdirSync(t)}catch(t){var i=t,s=1}finally{rm(r,i,s)}},isDirEmptySync(t){let r=[];try{rf(r,s_`fs.isDirEmptySync(${t})`,0);let i=this.readdirSync(t);return 0===i.length}catch(t){var i=t,s=1}finally{rm(r,i,s)}},rmdirSync(t){let r=[];try{rf(r,s_`fs.rmdirSync(${t})`,0),tV.rmdirSync(t)}catch(t){var i=t,s=1}finally{rm(r,i,s)}},rmSync(t,r){let i=[];try{rf(i,s_`fs.rmSync(${t})`,0),tV.rmSync(t,r)}catch(t){var s=t,n=1}finally{rm(i,s,n)}},createWriteStream:t=>tV.createWriteStream(t),async readFileBytes(t,r){if(void 0===r)return(0,t3.readFile)(t);let i=await (0,t3.open)(t,"r");try{let{size:t}=await i.stat(),s=Math.min(t,r),n=Buffer.allocUnsafe(s),a=0;for(;a<s;){let{bytesRead:t}=await i.read(n,a,s-a,a);if(0===t)break;a+=t}return a<s?n.subarray(0,a):n}finally{await i.close()}}},su=(a="","u">typeof process&&"function"==typeof process.cwd&&"function"==typeof tV.realpathSync&&(a=(0,tV.realpathSync)((0,t7.cwd)()).normalize("NFC")),{originalCwd:a,projectRoot:a,totalCostUSD:0,totalAPIDuration:0,totalAPIDurationWithoutRetries:0,totalToolDuration:0,tokenSaverBytesSaved:0,tokenSaverHits:0,turnHookDurationMs:0,turnToolDurationMs:0,turnClassifierDurationMs:0,turnToolCount:0,turnHookCount:0,turnClassifierCount:0,startTime:Date.now(),lastInteractionTime:Date.now(),totalLinesAdded:0,totalLinesRemoved:0,hasUnknownModelCost:!1,cwd:a,modelUsage:{},mainLoopModelOverride:void 0,initialMainLoopModel:null,modelStrings:null,isInteractive:!1,kairosActive:!1,sdkAgentProgressSummariesEnabled:!1,userMsgOptIn:!1,clientType:"cli",sessionSource:void 0,questionPreviewFormat:void 0,sessionIngressToken:void 0,oauthTokenFromFd:void 0,apiKeyFromFd:void 0,flagSettingsPath:void 0,flagSettingsInline:null,allowedSettingSources:["userSettings","projectSettings","localSettings","flagSettings","policySettings"],meter:null,sessionCounter:null,locCounter:null,prCounter:null,commitCounter:null,costCounter:null,tokenCounter:null,codeEditToolDecisionCounter:null,activeTimeCounter:null,statsStore:null,sessionId:(0,t$.randomUUID)(),parentSessionId:void 0,loggerProvider:null,eventLogger:null,meterProvider:null,tracerProvider:null,agentColorMap:new Map,agentColorIndex:0,lastAPIRequest:null,lastClassifierRequests:null,inMemoryErrorLog:[],inlinePlugins:[],chromeFlagOverride:void 0,useCoworkPlugins:!1,sessionBypassPermissionsMode:!1,scheduledTasksEnabled:!1,sessionCronTasks:[],sessionTrustAccepted:!1,sessionPersistenceDisabled:!1,hasExitedPlanMode:!1,needsPlanModeExitAttachment:!1,needsAutoModeExitAttachment:!1,lspRecommendationShownThisSession:!1,initJsonSchema:null,registeredHooks:null,planSlugCache:new Map,teleportedSessionInfo:null,invokedSkills:new Map,slowOperations:[],sdkBetas:void 0,mainThreadAgentType:void 0,isRemoteMode:!1,isInWorktree:!1,...{},directConnectServerUrl:void 0,systemPromptSectionCache:new Map,lastEmittedDate:null,additionalDirectoriesForClaudeMd:[],sessionProjectDir:null,promptCache1hAllowlist:null,promptId:null}),sc=new Set,sd={verbose:0,debug:1,info:2,warn:3,error:4},sh=st(()=>{let t=process.env.CLAUDE_CODE_DEBUG_LOG_LEVEL?.toLowerCase().trim();return t&&Object.hasOwn(sd,t)?t:"debug"}),sf=st(()=>si(process.env.DEBUG)||si(process.env.DEBUG_SDK)||process.argv.includes("--debug")||process.argv.includes("-d")||sy()||process.argv.some(t=>t.startsWith("--debug="))||null!==sb()),sm=st(()=>{let t=process.argv.find(t=>t.startsWith("--debug="));return t?sl(t.substring(8)):null}),sy=st(()=>process.argv.includes("--debug-to-stderr")||process.argv.includes("-d2e")),sb=st(()=>{for(let t=0;t<process.argv.length;t++){let r=process.argv[t];if(r.startsWith("--debug-file="))return r.substring(13);if("--debug-file"===r&&t+1<process.argv.length)return process.argv[t+1]}return null}),sg=null;function sv(t,{level:r}={level:"debug"}){if(sd[r]<sd[sh()]||!function(t){var r;if(!sf()||typeof process>"u"||typeof process.versions>"u"||typeof process.versions.node>"u")return!1;let i=sm();return!i||(r=function(t){let r=[],i=t.match(/^MCP server ["']([^"']+)["']/);if(i&&i[1])r.push("mcp"),r.push(i[1].toLowerCase());else{let i=t.match(/^([^:[]+):/);i&&i[1]&&r.push(i[1].trim().toLowerCase())}let s=t.match(/^\[([^\]]+)]/);s&&s[1]&&r.push(s[1].trim().toLowerCase()),t.toLowerCase().includes("1p event:")&&r.push("1p");let n=t.match(/:\s*([^:]+?)(?:\s+(?:type|mode|status|event))?:/);if(n&&n[1]){let t=n[1].trim().toLowerCase();t.length<30&&!t.includes(" ")&&r.push(t)}return Array.from(new Set(r))}(t),!i||0!==r.length&&(i.isExclusive?!r.some(t=>i.exclude.includes(t)):r.some(t=>i.include.includes(t))))}(t))return;let i=`${new Date().toISOString()} [${r.toUpperCase()}] ${t.trim()}
|
|
363
|
+
`;if(sy()){var s;return void(s=process.stderr,!s.destroyed&&s.write(i))}(function(){if(!sg){var t;let r=null;sg=function({writeFn:t,flushIntervalMs:r=1e3,maxBufferSize:i=100,maxBufferBytes:s=1/0,immediateMode:n=!1}){let a=[],o=0,l=null,p=null;function u(){l&&(clearTimeout(l),l=null)}function c(){p&&(t(p.join("")),p=null),0!==a.length&&(t(a.join("")),a=[],o=0,u())}return{write(d){n?t(d):(a.push(d),o+=d.length,l||(l=setTimeout(c,r)),(a.length>=i||o>=s)&&function(){if(p){p.push(...a),a=[],o=0,u();return}let r=a;a=[],o=0,u(),p=r,setImmediate(()=>{let r=p;p=null,r&&t(r.join(""))})}())},flush:c,dispose(){c()}}}({writeFn:t=>{let i=sx(),s=(0,tK.dirname)(i);if(r!==s){try{sp.mkdirSync(s)}catch{}r=s}sp.appendFileSync(i,t),sT()},flushIntervalMs:1e3,maxBufferSize:100,immediateMode:sf()}),t=async()=>sg?.dispose(),sc.add(t)}return sg})().write(i)}function sx(){return sb()??process.env.CLAUDE_CODE_DEBUG_LOGS_DIR??(0,tK.join)(sr(),"debug",`${su.sessionId}.txt`)}var sT=st(()=>{try{let t=sx(),r=(0,tK.dirname)(t),i=(0,tK.join)(r,"latest");try{sp.mkdirSync(r)}catch{}try{sp.unlinkSync(i)}catch{}sp.symlinkSync(t,i)}catch{}});let sE=process.env.CLAUDE_CODE_SLOW_OPERATION_THRESHOLD_MS;if(void 0!==sE){let t=Number(sE);!Number.isNaN(t)}var sS={[Symbol.dispose](){}},s_=function(){return sS};function sP(t,r,i){let s=[];try{return rf(s,s_`JSON.stringify(${t})`,0),JSON.stringify(t,r,i)}catch(t){var n=t,a=1}finally{rm(s,n,a)}}var sA=(t,r)=>{let i=[];try{return rf(i,s_`JSON.parse(${t})`,0),typeof r>"u"?JSON.parse(t):JSON.parse(t,r)}catch(t){var s=t,n=1}finally{rm(i,s,n)}};class sw{options;process;processStdin;processStdout;ready=!1;abortController;exitError;exitListeners=[];processExitHandler;abortHandler;constructor(t){this.options=t,this.abortController=t.abortController||iA(),this.initialize()}getDefaultExecutable(){return iC()?"bun":"node"}spawnLocalProcess(t){let{command:r,args:i,cwd:s,env:n,signal:a}=t,o=n.DEBUG_CLAUDE_AGENT_SDK||this.options.stderr?"pipe":"ignore",l=(0,t2.spawn)(r,i,{cwd:s,stdio:["pipe","pipe",o],signal:a,env:n,windowsHide:!0});return(n.DEBUG_CLAUDE_AGENT_SDK||this.options.stderr)&&l.stderr.on("data",t=>{let r=t.toString();so(r),this.options.stderr&&this.options.stderr(r)}),{stdin:l.stdin,stdout:l.stdout,get killed(){return l.killed},get exitCode(){return l.exitCode},kill:l.kill.bind(l),on:l.on.bind(l),once:l.once.bind(l),off:l.off.bind(l)}}initialize(){try{var t;let{additionalDirectories:r=[],agent:i,betas:s,cwd:n,executable:a=this.getDefaultExecutable(),executableArgs:o=[],extraArgs:l={},pathToClaudeCodeExecutable:p,env:u={...process.env},thinkingConfig:c,maxTurns:d,maxBudgetUsd:h,model:f,fallbackModel:m,jsonSchema:y,permissionMode:b,allowDangerouslySkipPermissions:g,permissionPromptToolName:v,continueConversation:x,resume:T,settingSources:E,allowedTools:S=[],disallowedTools:_=[],tools:P,mcpServers:A,strictMcpConfig:w,canUseTool:C,includePartialMessages:I,plugins:k,sandbox:N}=this.options,O=["--output-format","stream-json","--verbose","--input-format","stream-json"];if(c)switch(c.type){case"enabled":void 0===c.budgetTokens?O.push("--thinking","adaptive"):O.push("--max-thinking-tokens",c.budgetTokens.toString());break;case"disabled":O.push("--thinking","disabled");break;case"adaptive":O.push("--thinking","adaptive")}if(this.options.effort&&O.push("--effort",this.options.effort),d&&O.push("--max-turns",d.toString()),void 0!==h&&O.push("--max-budget-usd",h.toString()),f&&O.push("--model",f),i&&O.push("--agent",i),s&&s.length>0&&O.push("--betas",s.join(",")),y&&O.push("--json-schema",sP(y)),this.options.debugFile?O.push("--debug-file",this.options.debugFile):this.options.debug&&O.push("--debug"),u.DEBUG_CLAUDE_AGENT_SDK&&O.push("--debug-to-stderr"),C){if(v)throw Error("canUseTool callback cannot be used with permissionPromptToolName. Please use one or the other.");O.push("--permission-prompt-tool","stdio")}else v&&O.push("--permission-prompt-tool",v);if(x&&O.push("--continue"),T&&O.push("--resume",T),this.options.proactive&&O.push("--proactive"),this.options.assistant&&O.push("--assistant"),S.length>0&&O.push("--allowedTools",S.join(",")),_.length>0&&O.push("--disallowedTools",_.join(",")),void 0!==P&&(Array.isArray(P)?0===P.length?O.push("--tools",""):O.push("--tools",P.join(",")):O.push("--tools","default")),A&&Object.keys(A).length>0&&O.push("--mcp-config",sP({mcpServers:A})),E&&O.push("--setting-sources",E.join(",")),w&&O.push("--strict-mcp-config"),b&&O.push("--permission-mode",b),g&&O.push("--allow-dangerously-skip-permissions"),m){if(f&&m===f)throw Error("Fallback model cannot be the same as the main model. Please specify a different model for fallbackModel option.");O.push("--fallback-model",m)}for(let t of(I&&O.push("--include-partial-messages"),r))O.push("--add-dir",t);if(k&&k.length>0)for(let t of k)if("local"===t.type)O.push("--plugin-dir",t.path);else throw Error(`Unsupported plugin type: ${t.type}`);this.options.forkSession&&O.push("--fork-session"),this.options.resumeSessionAt&&O.push("--resume-session-at",this.options.resumeSessionAt),this.options.sessionId&&O.push("--session-id",this.options.sessionId),!1===this.options.persistSession&&O.push("--no-session-persistence");let D={...l??{}};this.options.settings&&(D.settings=this.options.settings);let j=function(t,r){let i={...t};if(r){let t,s=i.settings;if(s&&!((t=s.trim()).startsWith("{")&&t.endsWith("}")))throw Error("Cannot use both a settings file path and the sandbox option. Include the sandbox configuration in your settings file instead.");let n={sandbox:r};if(s)try{n={...sA(s),sandbox:r}}catch{}i.settings=sP(n)}return i}(D,N);for(let[t,r]of Object.entries(j))null===r?O.push(`--${t}`):O.push(`--${t}`,r);u.CLAUDE_CODE_ENTRYPOINT||(u.CLAUDE_CODE_ENTRYPOINT="sdk-ts"),(delete u.NODE_OPTIONS,u.DEBUG_CLAUDE_AGENT_SDK)?u.DEBUG="1":delete u.DEBUG;let L=(t=p,![".js",".mjs",".tsx",".ts",".jsx"].some(r=>t.endsWith(r))),R=L?p:a,M=L?[...o,...O]:[...o,p,...O],F={command:R,args:M,cwd:n,env:u,signal:this.abortController.signal};this.options.spawnClaudeCodeProcess?(so(`Spawning Claude Code (custom): ${R} ${M.join(" ")}`),this.process=this.options.spawnClaudeCodeProcess(F)):(so(`Spawning Claude Code: ${R} ${M.join(" ")}`),this.process=this.spawnLocalProcess(F)),this.processStdin=this.process.stdin,this.processStdout=this.process.stdout;let B=()=>{this.process&&!this.process.killed&&this.process.kill("SIGTERM")};this.processExitHandler=B,this.abortHandler=B,process.on("exit",this.processExitHandler),this.abortController.signal.addEventListener("abort",this.abortHandler),this.process.on("error",t=>{if(this.ready=!1,this.abortController.signal.aborted)this.exitError=new iw("Claude Code process aborted by user");else if("ENOENT"===t.code){let t=L?`Claude Code native binary not found at ${p}. Please ensure Claude Code is installed via native installer or specify a valid path with options.pathToClaudeCodeExecutable.`:`Claude Code executable not found at ${p}. Is options.pathToClaudeCodeExecutable set?`;this.exitError=ReferenceError(t),so(this.exitError.message)}else this.exitError=Error(`Failed to spawn Claude Code process: ${t.message}`),so(this.exitError.message)}),this.process.on("exit",(t,r)=>{if(this.ready=!1,this.abortController.signal.aborted)this.exitError=new iw("Claude Code process aborted by user");else{let i=this.getProcessExitError(t,r);i&&(this.exitError=i,so(i.message))}}),this.ready=!0}catch(t){throw this.ready=!1,t}}getProcessExitError(t,r){return 0!==t&&null!==t?Error(`Claude Code process exited with code ${t}`):r?Error(`Claude Code process terminated by signal ${r}`):void 0}write(t){if(this.abortController.signal.aborted)throw new iw("Operation aborted");if(!this.ready||!this.processStdin)throw Error("ProcessTransport is not ready for writing");if(this.process?.killed||this.process?.exitCode!==null)throw Error("Cannot write to terminated process");if(this.exitError)throw Error(`Cannot write to process that exited with error: ${this.exitError.message}`);so(`[ProcessTransport] Writing to stdin: ${t.substring(0,100)}`);try{this.processStdin.write(t)||so("[ProcessTransport] Write buffer full, data queued")}catch(t){throw this.ready=!1,Error(`Failed to write to process stdin: ${t.message}`)}}close(){for(let{handler:t}of(this.processStdin&&(this.processStdin.end(),this.processStdin=void 0),this.abortHandler&&(this.abortController.signal.removeEventListener("abort",this.abortHandler),this.abortHandler=void 0),this.exitListeners))this.process?.off("exit",t);this.exitListeners=[],this.process&&!this.process.killed&&null===this.process.exitCode&&(this.process.kill("SIGTERM"),setTimeout(()=>{this.process&&!this.process.killed&&this.process.kill("SIGKILL")},5e3).unref()),this.ready=!1,this.processExitHandler&&(process.off("exit",this.processExitHandler),this.processExitHandler=void 0)}isReady(){return this.ready}async *readMessages(){if(!this.processStdout)throw Error("ProcessTransport output stream not available");let t=(0,t4.createInterface)({input:this.processStdout});try{for await(let r of t)if(r.trim())try{yield sA(r)}catch(t){throw so(`Non-JSON stdout: ${r}`),Error(`CLI output was not valid JSON. This may indicate an error during startup. Output: ${r.slice(0,200)}${r.length>200?"...":""}`)}await this.waitForExit()}catch(t){throw t}finally{t.close()}}endInput(){this.processStdin&&this.processStdin.end()}getInputStream(){return this.processStdin}onExit(t){if(!this.process)return()=>{};let r=(r,i)=>{t(this.getProcessExitError(r,i))};return this.process.on("exit",r),this.exitListeners.push({callback:t,handler:r}),()=>{this.process&&this.process.off("exit",r);let t=this.exitListeners.findIndex(t=>t.handler===r);-1!==t&&this.exitListeners.splice(t,1)}}async waitForExit(){if(!this.process||null!==this.process.exitCode||this.process.killed){if(this.exitError)throw this.exitError;return}return new Promise((t,r)=>{let i=(i,s)=>{if(this.abortController.signal.aborted)return void r(new iw("Operation aborted"));let n=this.getProcessExitError(i,s);n?r(n):t()};this.process.once("exit",i);let s=t=>{this.process.off("exit",i),r(t)};this.process.once("error",s),this.process.once("exit",()=>{this.process.off("error",s)})})}}class sC{returned;queue=[];readResolve;readReject;isDone=!1;hasError;started=!1;constructor(t){this.returned=t}[Symbol.asyncIterator](){if(this.started)throw Error("Stream can only be iterated once");return this.started=!0,this}next(){return this.queue.length>0?Promise.resolve({done:!1,value:this.queue.shift()}):this.isDone?Promise.resolve({done:!0,value:void 0}):this.hasError?Promise.reject(this.hasError):new Promise((t,r)=>{this.readResolve=t,this.readReject=r})}enqueue(t){if(this.readResolve){let r=this.readResolve;this.readResolve=void 0,this.readReject=void 0,r({done:!1,value:t})}else this.queue.push(t)}done(){if(this.isDone=!0,this.readResolve){let t=this.readResolve;this.readResolve=void 0,this.readReject=void 0,t({done:!0,value:void 0})}}error(t){if(this.hasError=t,this.readReject){let r=this.readReject;this.readResolve=void 0,this.readReject=void 0,r(t)}}return(){return this.isDone=!0,this.returned&&this.returned(),Promise.resolve({done:!0,value:void 0})}}class sI{sendMcpMessage;isClosed=!1;constructor(t){this.sendMcpMessage=t}onclose;onerror;onmessage;async start(){}async send(t){if(this.isClosed)throw Error("Transport is closed");this.sendMcpMessage(t)}async close(){this.isClosed||(this.isClosed=!0,this.onclose?.())}}class sk{transport;isSingleUserTurn;canUseTool;hooks;abortController;jsonSchema;initConfig;onElicitation;pendingControlResponses=new Map;cleanupPerformed=!1;sdkMessages;inputStream=new sC;initialization;cancelControllers=new Map;hookCallbacks=new Map;nextCallbackId=0;sdkMcpTransports=new Map;sdkMcpServerInstances=new Map;pendingMcpResponses=new Map;firstResultReceivedResolve;firstResultReceived=!1;hasBidirectionalNeeds(){return this.sdkMcpTransports.size>0||void 0!==this.hooks&&Object.keys(this.hooks).length>0||void 0!==this.canUseTool||void 0!==this.onElicitation}constructor(t,r,i,s,n,a=new Map,o,l,p){for(let[u,c]of(this.transport=t,this.isSingleUserTurn=r,this.canUseTool=i,this.hooks=s,this.abortController=n,this.jsonSchema=o,this.initConfig=l,this.onElicitation=p,a))this.connectSdkMcpServer(u,c);this.sdkMessages=this.readSdkMessages(),this.readMessages(),this.initialization=this.initialize(),this.initialization.catch(()=>{})}setError(t){this.inputStream.error(t)}async stopTask(t){await this.request({subtype:"stop_task",task_id:t})}close(){this.cleanup()}cleanup(t){if(!this.cleanupPerformed){this.cleanupPerformed=!0;try{this.transport.close();let r=Error("Query closed before response received");for(let{reject:t}of this.pendingControlResponses.values())t(r);for(let{reject:t}of(this.pendingControlResponses.clear(),this.pendingMcpResponses.values()))t(r);for(let t of(this.pendingMcpResponses.clear(),this.cancelControllers.clear(),this.hookCallbacks.clear(),this.sdkMcpTransports.values()))try{t.close()}catch{}(this.sdkMcpTransports.clear(),t)?this.inputStream.error(t):this.inputStream.done()}catch(t){}}}next(...[t]){return this.sdkMessages.next(t)}return(t){return this.sdkMessages.return(t)}throw(t){return this.sdkMessages.throw(t)}[Symbol.asyncIterator](){return this.sdkMessages}[Symbol.asyncDispose](){return this.sdkMessages[Symbol.asyncDispose]()}async readMessages(){try{for await(let t of this.transport.readMessages()){if("control_response"===t.type){let r=this.pendingControlResponses.get(t.response.request_id);r&&r.handler(t.response);continue}if("control_request"===t.type){this.handleControlRequest(t);continue}if("control_cancel_request"===t.type){this.handleControlCancelRequest(t);continue}else if("keep_alive"===t.type)continue;"streamlined_text"!==t.type&&"streamlined_tool_use_summary"!==t.type&&("result"===t.type&&(this.firstResultReceived=!0,this.firstResultReceivedResolve&&this.firstResultReceivedResolve(),this.isSingleUserTurn&&(sv("[Query.readMessages] First result received for single-turn query, closing stdin"),this.transport.endInput())),this.inputStream.enqueue(t))}this.firstResultReceivedResolve&&this.firstResultReceivedResolve(),this.inputStream.done(),this.cleanup()}catch(t){this.firstResultReceivedResolve&&this.firstResultReceivedResolve(),this.inputStream.error(t),this.cleanup(t)}}async handleControlRequest(t){let r=new AbortController;this.cancelControllers.set(t.request_id,r);try{let i=await this.processControlRequest(t,r.signal),s={type:"control_response",response:{subtype:"success",request_id:t.request_id,response:i}};await Promise.resolve(this.transport.write(sP(s)+`
|
|
364
|
+
`))}catch(i){let r={type:"control_response",response:{subtype:"error",request_id:t.request_id,error:i.message||String(i)}};await Promise.resolve(this.transport.write(sP(r)+`
|
|
365
|
+
`))}finally{this.cancelControllers.delete(t.request_id)}}handleControlCancelRequest(t){let r=this.cancelControllers.get(t.request_id);r&&(r.abort(),this.cancelControllers.delete(t.request_id))}async processControlRequest(t,r){if("can_use_tool"===t.request.subtype){if(!this.canUseTool)throw Error("canUseTool callback is not provided.");return{...await this.canUseTool(t.request.tool_name,t.request.input,{signal:r,suggestions:t.request.permission_suggestions,blockedPath:t.request.blocked_path,decisionReason:t.request.decision_reason,toolUseID:t.request.tool_use_id,agentID:t.request.agent_id}),toolUseID:t.request.tool_use_id}}if("hook_callback"===t.request.subtype)return await this.handleHookCallbacks(t.request.callback_id,t.request.input,t.request.tool_use_id,r);if("mcp_message"===t.request.subtype){let r=t.request,i=this.sdkMcpTransports.get(r.server_name);if(!i)throw Error(`SDK MCP server not found: ${r.server_name}`);return"method"in r.message&&"id"in r.message&&null!==r.message.id?{mcp_response:await this.handleMcpControlRequest(r.server_name,r,i)}:(i.onmessage&&i.onmessage(r.message),{mcp_response:{jsonrpc:"2.0",result:{},id:0}})}if("elicitation"===t.request.subtype){let i=t.request;return this.onElicitation?await this.onElicitation({serverName:i.mcp_server_name,message:i.message,mode:i.mode,url:i.url,elicitationId:i.elicitation_id,requestedSchema:i.requested_schema},{signal:r}):{action:"decline"}}throw Error("Unsupported control request subtype: "+t.request.subtype)}async *readSdkMessages(){for await(let t of this.inputStream)yield t}async initialize(){let t;if(this.hooks)for(let[r,i]of(t={},Object.entries(this.hooks)))i.length>0&&(t[r]=i.map(t=>{let r=[];for(let i of t.hooks){let t=`hook_${this.nextCallbackId++}`;this.hookCallbacks.set(t,i),r.push(t)}return{matcher:t.matcher,hookCallbackIds:r,timeout:t.timeout}}));let r={subtype:"initialize",hooks:t,sdkMcpServers:this.sdkMcpTransports.size>0?Array.from(this.sdkMcpTransports.keys()):void 0,jsonSchema:this.jsonSchema,systemPrompt:this.initConfig?.systemPrompt,appendSystemPrompt:this.initConfig?.appendSystemPrompt,agents:this.initConfig?.agents,promptSuggestions:this.initConfig?.promptSuggestions,agentProgressSummaries:this.initConfig?.agentProgressSummaries};return(await this.request(r)).response}async interrupt(){await this.request({subtype:"interrupt"})}async setPermissionMode(t){await this.request({subtype:"set_permission_mode",mode:t})}async setModel(t){await this.request({subtype:"set_model",model:t})}async setMaxThinkingTokens(t){await this.request({subtype:"set_max_thinking_tokens",max_thinking_tokens:t})}async applyFlagSettings(t){await this.request({subtype:"apply_flag_settings",settings:t})}async getSettings(){return(await this.request({subtype:"get_settings"})).response}async rewindFiles(t,r){return(await this.request({subtype:"rewind_files",user_message_id:t,dry_run:r?.dryRun})).response}async enableRemoteControl(t){return(await this.request({subtype:"remote_control",enabled:t})).response}async setProactive(t){await this.request({subtype:"set_proactive",enabled:t})}async processPendingPermissionRequests(t){for(let r of t)"can_use_tool"===r.request.subtype&&this.handleControlRequest(r).catch(()=>{})}request(t){let r=Math.random().toString(36).substring(2,15),i={request_id:r,type:"control_request",request:t};return new Promise((t,s)=>{this.pendingControlResponses.set(r,{handler:i=>{(this.pendingControlResponses.delete(r),"success"===i.subtype)?t(i):(s(Error(i.error)),i.pending_permission_requests&&this.processPendingPermissionRequests(i.pending_permission_requests))},reject:s}),Promise.resolve(this.transport.write(sP(i)+`
|
|
366
|
+
`))})}async initializationResult(){return this.initialization}async supportedCommands(){return(await this.initialization).commands}async supportedModels(){return(await this.initialization).models}async supportedAgents(){return(await this.initialization).agents}async reconnectMcpServer(t){await this.request({subtype:"mcp_reconnect",serverName:t})}async toggleMcpServer(t,r){await this.request({subtype:"mcp_toggle",serverName:t,enabled:r})}async mcpAuthenticate(t){return(await this.request({subtype:"mcp_authenticate",serverName:t})).response}async mcpClearAuth(t){return(await this.request({subtype:"mcp_clear_auth",serverName:t})).response}async mcpSubmitOAuthCallbackUrl(t,r){return(await this.request({subtype:"mcp_oauth_callback_url",serverName:t,callbackUrl:r})).response}async mcpServerStatus(){return(await this.request({subtype:"mcp_status"})).response.mcpServers}async setMcpServers(t){let r={},i={};for(let[s,n]of Object.entries(t))"sdk"===n.type&&"instance"in n?r[s]=n.instance:i[s]=n;let s=new Set(this.sdkMcpServerInstances.keys()),n=new Set(Object.keys(r));for(let t of s)n.has(t)||await this.disconnectSdkMcpServer(t);for(let[t,i]of Object.entries(r))s.has(t)||this.connectSdkMcpServer(t,i);let a={};for(let t of Object.keys(r))a[t]={type:"sdk",name:t};return(await this.request({subtype:"mcp_set_servers",servers:{...i,...a}})).response}async accountInfo(){return(await this.initialization).account}async streamInput(t){sv("[Query.streamInput] Starting to process input stream");try{let r=0;for await(let i of t){if(r++,sv(`[Query.streamInput] Processing message ${r}: ${i.type}`),this.abortController?.signal.aborted)break;await Promise.resolve(this.transport.write(sP(i)+`
|
|
367
|
+
`))}sv(`[Query.streamInput] Finished processing ${r} messages from input stream`),r>0&&this.hasBidirectionalNeeds()&&(sv("[Query.streamInput] Has bidirectional needs, waiting for first result"),await this.waitForFirstResult()),sv("[Query] Calling transport.endInput() to close stdin to CLI process"),this.transport.endInput()}catch(t){if(!(t instanceof iw))throw t}}waitForFirstResult(){return this.firstResultReceived?(sv("[Query.waitForFirstResult] Result already received, returning immediately"),Promise.resolve()):new Promise(t=>{this.abortController?.signal.aborted?t():(this.abortController?.signal.addEventListener("abort",()=>t(),{once:!0}),this.firstResultReceivedResolve=t)})}handleHookCallbacks(t,r,i,s){let n=this.hookCallbacks.get(t);if(!n)throw Error(`No hook callback found for ID: ${t}`);return n(r,i,{signal:s})}connectSdkMcpServer(t,r){let i=new sI(r=>this.sendMcpServerMessageToCli(t,r));this.sdkMcpTransports.set(t,i),this.sdkMcpServerInstances.set(t,r),r.connect(i)}async disconnectSdkMcpServer(t){let r=this.sdkMcpTransports.get(t);r&&(await r.close(),this.sdkMcpTransports.delete(t)),this.sdkMcpServerInstances.delete(t)}sendMcpServerMessageToCli(t,r){if("id"in r&&null!==r.id&&void 0!==r.id){let i=`${t}:${r.id}`,s=this.pendingMcpResponses.get(i);if(s){s.resolve(r),this.pendingMcpResponses.delete(i);return}}let i={type:"control_request",request_id:(0,t$.randomUUID)(),request:{subtype:"mcp_message",server_name:t,message:r}};this.transport.write(sP(i)+`
|
|
368
|
+
`)}handleMcpControlRequest(t,r,i){let s="id"in r.message?r.message.id:null,n=`${t}:${s}`;return new Promise((t,s)=>{let a=()=>{this.pendingMcpResponses.delete(n)};if(this.pendingMcpResponses.set(n,{resolve:r=>{a(),t(r)},reject:t=>{a(),s(t)}}),i.onmessage)i.onmessage(r.message);else{a(),s(Error("No message handler registered"));return}})}}(0,t9.promisify)(t2.execFile);var sN={};rc(sN,{void:()=>al,util:()=>s3,unknown:()=>aa,union:()=>ad,undefined:()=>ai,tuple:()=>am,transformer:()=>aP,symbol:()=>ar,string:()=>n7,strictObject:()=>ac,setErrorMap:()=>sB,set:()=>ag,record:()=>ay,quotelessJson:()=>sL,promise:()=>a_,preprocess:()=>aC,pipeline:()=>aI,ostring:()=>ak,optional:()=>aA,onumber:()=>aN,oboolean:()=>aO,objectUtil:()=>s8,object:()=>au,number:()=>n9,nullable:()=>aw,null:()=>as,never:()=>ao,nativeEnum:()=>aS,nan:()=>n5,map:()=>ab,makeIssue:()=>s$,literal:()=>aT,lazy:()=>ax,late:()=>n3,isValid:()=>sX,isDirty:()=>sY,isAsync:()=>sG,isAborted:()=>sJ,intersection:()=>af,instanceof:()=>n8,getParsedType:()=>sD,getErrorMap:()=>sU,function:()=>av,enum:()=>aE,effect:()=>aP,discriminatedUnion:()=>ah,defaultErrorMap:()=>sM,datetimeRegex:()=>nm,date:()=>at,custom:()=>n2,coerce:()=>aD,boolean:()=>ae,bigint:()=>n6,array:()=>ap,any:()=>an,addIssueToContext:()=>sK,ZodVoid:()=>nw,ZodUnknown:()=>nP,ZodUnion:()=>nk,ZodUndefined:()=>nE,ZodType:()=>s1,ZodTuple:()=>nj,ZodTransformer:()=>nz,ZodSymbol:()=>nT,ZodString:()=>ny,ZodSet:()=>nM,ZodSchema:()=>s1,ZodRecord:()=>nL,ZodReadonly:()=>n0,ZodPromise:()=>nq,ZodPipeline:()=>nQ,ZodParsedType:()=>sO,ZodOptional:()=>nW,ZodObject:()=>nI,ZodNumber:()=>nb,ZodNullable:()=>nH,ZodNull:()=>nS,ZodNever:()=>nA,ZodNativeEnum:()=>nK,ZodNaN:()=>nX,ZodMap:()=>nR,ZodLiteral:()=>nU,ZodLazy:()=>nB,ZodIssueCode:()=>sj,ZodIntersection:()=>nD,ZodFunction:()=>nF,ZodFirstPartyTypeKind:()=>n4,ZodError:()=>sR,ZodEnum:()=>nV,ZodEffects:()=>nz,ZodDiscriminatedUnion:()=>nO,ZodDefault:()=>nJ,ZodDate:()=>nx,ZodCatch:()=>nY,ZodBranded:()=>nZ,ZodBoolean:()=>nv,ZodBigInt:()=>ng,ZodArray:()=>nC,ZodAny:()=>n_,Schema:()=>s1,ParseStatus:()=>sq,OK:()=>sH,NEVER:()=>aj,INVALID:()=>sz,EMPTY_PATH:()=>sV,DIRTY:()=>sW,BRAND:()=>nG}),(s2=s3||(s3={})).assertEqual=t=>{},s2.assertIs=function(t){},s2.assertNever=function(t){throw Error()},s2.arrayToEnum=t=>{let r={};for(let i of t)r[i]=i;return r},s2.getValidEnumValues=t=>{let r=s2.objectKeys(t).filter(r=>"number"!=typeof t[t[r]]),i={};for(let s of r)i[s]=t[s];return s2.objectValues(i)},s2.objectValues=t=>s2.objectKeys(t).map(function(r){return t[r]}),s2.objectKeys="function"==typeof Object.keys?t=>Object.keys(t):t=>{let r=[];for(let i in t)Object.prototype.hasOwnProperty.call(t,i)&&r.push(i);return r},s2.find=(t,r)=>{for(let i of t)if(r(i))return i},s2.isInteger="function"==typeof Number.isInteger?t=>Number.isInteger(t):t=>"number"==typeof t&&Number.isFinite(t)&&Math.floor(t)===t,s2.joinValues=function(t,r=" | "){return t.map(t=>"string"==typeof t?`'${t}'`:t).join(r)},s2.jsonStringifyReplacer=(t,r)=>"bigint"==typeof r?r.toString():r,(s8||(s8={})).mergeShapes=(t,r)=>({...t,...r});var sO=s3.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),sD=t=>{switch(typeof t){case"undefined":return sO.undefined;case"string":return sO.string;case"number":return Number.isNaN(t)?sO.nan:sO.number;case"boolean":return sO.boolean;case"function":return sO.function;case"bigint":return sO.bigint;case"symbol":return sO.symbol;case"object":if(Array.isArray(t))return sO.array;if(null===t)return sO.null;if(t.then&&"function"==typeof t.then&&t.catch&&"function"==typeof t.catch)return sO.promise;if("u">typeof Map&&t instanceof Map)return sO.map;if("u">typeof Set&&t instanceof Set)return sO.set;if("u">typeof Date&&t instanceof Date)return sO.date;return sO.object;default:return sO.unknown}},sj=s3.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),sL=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:");class sR extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=t=>{this.issues=[...this.issues,t]},this.addIssues=(t=[])=>{this.issues=[...this.issues,...t]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=t}format(t){let r=t||function(t){return t.message},i={_errors:[]},s=t=>{for(let n of t.issues)if("invalid_union"===n.code)n.unionErrors.map(s);else if("invalid_return_type"===n.code)s(n.returnTypeError);else if("invalid_arguments"===n.code)s(n.argumentsError);else if(0===n.path.length)i._errors.push(r(n));else{let t=i,s=0;for(;s<n.path.length;){let i=n.path[s];s!==n.path.length-1?t[i]=t[i]||{_errors:[]}:(t[i]=t[i]||{_errors:[]},t[i]._errors.push(r(n))),t=t[i],s++}}};return s(this),i}static assert(t){if(!(t instanceof sR))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,s3.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(t=t=>t.message){let r={},i=[];for(let s of this.issues)if(s.path.length>0){let i=s.path[0];r[i]=r[i]||[],r[i].push(t(s))}else i.push(t(s));return{formErrors:i,fieldErrors:r}}get formErrors(){return this.flatten()}}sR.create=t=>new sR(t);var sM=(t,r)=>{let i;switch(t.code){case sj.invalid_type:i=t.received===sO.undefined?"Required":`Expected ${t.expected}, received ${t.received}`;break;case sj.invalid_literal:i=`Invalid literal value, expected ${JSON.stringify(t.expected,s3.jsonStringifyReplacer)}`;break;case sj.unrecognized_keys:i=`Unrecognized key(s) in object: ${s3.joinValues(t.keys,", ")}`;break;case sj.invalid_union:i="Invalid input";break;case sj.invalid_union_discriminator:i=`Invalid discriminator value. Expected ${s3.joinValues(t.options)}`;break;case sj.invalid_enum_value:i=`Invalid enum value. Expected ${s3.joinValues(t.options)}, received '${t.received}'`;break;case sj.invalid_arguments:i="Invalid function arguments";break;case sj.invalid_return_type:i="Invalid function return type";break;case sj.invalid_date:i="Invalid date";break;case sj.invalid_string:"object"==typeof t.validation?"includes"in t.validation?(i=`Invalid input: must include "${t.validation.includes}"`,"number"==typeof t.validation.position&&(i=`${i} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?i=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?i=`Invalid input: must end with "${t.validation.endsWith}"`:s3.assertNever(t.validation):i="regex"!==t.validation?`Invalid ${t.validation}`:"Invalid";break;case sj.too_small:i="array"===t.type?`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:"string"===t.type?`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:"number"===t.type||"bigint"===t.type?`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:"date"===t.type?`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:"Invalid input";break;case sj.too_big:i="array"===t.type?`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:"string"===t.type?`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:"number"===t.type?`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:"bigint"===t.type?`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:"date"===t.type?`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:"Invalid input";break;case sj.custom:i="Invalid input";break;case sj.invalid_intersection_types:i="Intersection results could not be merged";break;case sj.not_multiple_of:i=`Number must be a multiple of ${t.multipleOf}`;break;case sj.not_finite:i="Number must be finite";break;default:i=r.defaultError,s3.assertNever(t)}return{message:i}},sF=sM;function sB(t){sF=t}function sU(){return sF}var s$=t=>{let{data:r,path:i,errorMaps:s,issueData:n}=t,a=[...i,...n.path||[]],o={...n,path:a};if(void 0!==n.message)return{...n,path:a,message:n.message};let l="";for(let t of s.filter(t=>!!t).slice().reverse())l=t(o,{data:r,defaultError:l}).message;return{...n,path:a,message:l}},sV=[];function sK(t,r){let i=sF,s=s$({issueData:r,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,i,i===sM?void 0:sM].filter(t=>!!t)});t.common.issues.push(s)}class sq{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(t,r){let i=[];for(let s of r){if("aborted"===s.status)return sz;"dirty"===s.status&&t.dirty(),i.push(s.value)}return{status:t.value,value:i}}static async mergeObjectAsync(t,r){let i=[];for(let t of r){let r=await t.key,s=await t.value;i.push({key:r,value:s})}return sq.mergeObjectSync(t,i)}static mergeObjectSync(t,r){let i={};for(let s of r){let{key:r,value:n}=s;if("aborted"===r.status||"aborted"===n.status)return sz;"dirty"===r.status&&t.dirty(),"dirty"===n.status&&t.dirty(),"__proto__"!==r.value&&("u">typeof n.value||s.alwaysSet)&&(i[r.value]=n.value)}return{status:t.value,value:i}}}var sz=Object.freeze({status:"aborted"}),sW=t=>({status:"dirty",value:t}),sH=t=>({status:"valid",value:t}),sJ=t=>"aborted"===t.status,sY=t=>"dirty"===t.status,sX=t=>"valid"===t.status,sG=t=>"u">typeof Promise&&t instanceof Promise;(s4=s7||(s7={})).errToObj=t=>"string"==typeof t?{message:t}:t||{},s4.toString=t=>"string"==typeof t?t:t?.message;class sZ{constructor(t,r,i,s){this._cachedPath=[],this.parent=t,this.data=r,this._path=i,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}var sQ=(t,r)=>{if(sX(r))return{success:!0,data:r.value};if(!t.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new sR(t.common.issues);return this._error=r,this._error}}};function s0(t){if(!t)return{};let{errorMap:r,invalid_type_error:i,required_error:s,description:n}=t;if(r&&(i||s))throw Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');return r?{errorMap:r,description:n}:{errorMap:(r,n)=>{let{message:a}=t;return"invalid_enum_value"===r.code?{message:a??n.defaultError}:typeof n.data>"u"?{message:a??s??n.defaultError}:"invalid_type"!==r.code?{message:n.defaultError}:{message:a??i??n.defaultError}},description:n}}class s1{get description(){return this._def.description}_getType(t){return sD(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:sD(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new sq,ctx:{common:t.parent.common,data:t.data,parsedType:sD(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let r=this._parse(t);if(sG(r))throw Error("Synchronous parse encountered promise.");return r}_parseAsync(t){return Promise.resolve(this._parse(t))}parse(t,r){let i=this.safeParse(t,r);if(i.success)return i.data;throw i.error}safeParse(t,r){let i={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:sD(t)},s=this._parseSync({data:t,path:i.path,parent:i});return sQ(i,s)}"~validate"(t){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:sD(t)};if(!this["~standard"].async)try{let i=this._parseSync({data:t,path:[],parent:r});return sX(i)?{value:i.value}:{issues:r.common.issues}}catch(t){t?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:r}).then(t=>sX(t)?{value:t.value}:{issues:r.common.issues})}async parseAsync(t,r){let i=await this.safeParseAsync(t,r);if(i.success)return i.data;throw i.error}async safeParseAsync(t,r){let i={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:sD(t)},s=this._parse({data:t,path:i.path,parent:i});return sQ(i,await (sG(s)?s:Promise.resolve(s)))}refine(t,r){return this._refinement((i,s)=>{let n=t(i),a=()=>s.addIssue({code:sj.custom,..."string"==typeof r||typeof r>"u"?{message:r}:"function"==typeof r?r(i):r});return"u">typeof Promise&&n instanceof Promise?n.then(t=>!!t||(a(),!1)):!!n||(a(),!1)})}refinement(t,r){return this._refinement((i,s)=>!!t(i)||(s.addIssue("function"==typeof r?r(i,s):r),!1))}_refinement(t){return new nz({schema:this,typeName:n4.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return nW.create(this,this._def)}nullable(){return nH.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return nC.create(this)}promise(){return nq.create(this,this._def)}or(t){return nk.create([this,t],this._def)}and(t){return nD.create(this,t,this._def)}transform(t){return new nz({...s0(this._def),schema:this,typeName:n4.ZodEffects,effect:{type:"transform",transform:t}})}default(t){return new nJ({...s0(this._def),innerType:this,defaultValue:"function"==typeof t?t:()=>t,typeName:n4.ZodDefault})}brand(){return new nZ({typeName:n4.ZodBranded,type:this,...s0(this._def)})}catch(t){return new nY({...s0(this._def),innerType:this,catchValue:"function"==typeof t?t:()=>t,typeName:n4.ZodCatch})}describe(t){return new this.constructor({...this._def,description:t})}pipe(t){return nQ.create(this,t)}readonly(){return n0.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var s2,s4,s3,s8,s7,s9,s5=/^c[^\s-]{8,}$/i,s6=/^[0-9a-z]+$/,ne=/^[0-9A-HJKMNP-TV-Z]{26}$/i,nt=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,nr=/^[a-z0-9_-]{21}$/i,ni=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,ns=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,nn=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,na=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,no=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,nl=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,np=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,nu=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,nc=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nd="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",nh=RegExp(`^${nd}$`);function nf(t){let r="[0-5]\\d";t.precision?r=`${r}\\.\\d{${t.precision}}`:null==t.precision&&(r=`${r}(\\.\\d+)?`);let i=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${r})${i}`}function nm(t){let r=`${nd}T${nf(t)}`,i=[];return i.push(t.local?"Z?":"Z"),t.offset&&i.push("([+-]\\d{2}:?\\d{2})"),r=`${r}(${i.join("|")})`,RegExp(`^${r}$`)}class ny extends s1{_parse(t){var r,i,s,n;if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==sO.string){let r=this._getOrReturnCtx(t);return sK(r,{code:sj.invalid_type,expected:sO.string,received:r.parsedType}),sz}let a=new sq,o;for(let l of this._def.checks)if("min"===l.kind)t.data.length<l.value&&(sK(o=this._getOrReturnCtx(t,o),{code:sj.too_small,minimum:l.value,type:"string",inclusive:!0,exact:!1,message:l.message}),a.dirty());else if("max"===l.kind)t.data.length>l.value&&(sK(o=this._getOrReturnCtx(t,o),{code:sj.too_big,maximum:l.value,type:"string",inclusive:!0,exact:!1,message:l.message}),a.dirty());else if("length"===l.kind){let r=t.data.length>l.value,i=t.data.length<l.value;(r||i)&&((o=this._getOrReturnCtx(t,o),r)?sK(o,{code:sj.too_big,maximum:l.value,type:"string",inclusive:!0,exact:!0,message:l.message}):i&&sK(o,{code:sj.too_small,minimum:l.value,type:"string",inclusive:!0,exact:!0,message:l.message}),a.dirty())}else if("email"===l.kind)nn.test(t.data)||(sK(o=this._getOrReturnCtx(t,o),{validation:"email",code:sj.invalid_string,message:l.message}),a.dirty());else if("emoji"===l.kind)s9||(s9=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),s9.test(t.data)||(sK(o=this._getOrReturnCtx(t,o),{validation:"emoji",code:sj.invalid_string,message:l.message}),a.dirty());else if("uuid"===l.kind)nt.test(t.data)||(sK(o=this._getOrReturnCtx(t,o),{validation:"uuid",code:sj.invalid_string,message:l.message}),a.dirty());else if("nanoid"===l.kind)nr.test(t.data)||(sK(o=this._getOrReturnCtx(t,o),{validation:"nanoid",code:sj.invalid_string,message:l.message}),a.dirty());else if("cuid"===l.kind)s5.test(t.data)||(sK(o=this._getOrReturnCtx(t,o),{validation:"cuid",code:sj.invalid_string,message:l.message}),a.dirty());else if("cuid2"===l.kind)s6.test(t.data)||(sK(o=this._getOrReturnCtx(t,o),{validation:"cuid2",code:sj.invalid_string,message:l.message}),a.dirty());else if("ulid"===l.kind)ne.test(t.data)||(sK(o=this._getOrReturnCtx(t,o),{validation:"ulid",code:sj.invalid_string,message:l.message}),a.dirty());else if("url"===l.kind)try{new URL(t.data)}catch{sK(o=this._getOrReturnCtx(t,o),{validation:"url",code:sj.invalid_string,message:l.message}),a.dirty()}else"regex"===l.kind?(l.regex.lastIndex=0,l.regex.test(t.data)||(sK(o=this._getOrReturnCtx(t,o),{validation:"regex",code:sj.invalid_string,message:l.message}),a.dirty())):"trim"===l.kind?t.data=t.data.trim():"includes"===l.kind?t.data.includes(l.value,l.position)||(sK(o=this._getOrReturnCtx(t,o),{code:sj.invalid_string,validation:{includes:l.value,position:l.position},message:l.message}),a.dirty()):"toLowerCase"===l.kind?t.data=t.data.toLowerCase():"toUpperCase"===l.kind?t.data=t.data.toUpperCase():"startsWith"===l.kind?t.data.startsWith(l.value)||(sK(o=this._getOrReturnCtx(t,o),{code:sj.invalid_string,validation:{startsWith:l.value},message:l.message}),a.dirty()):"endsWith"===l.kind?t.data.endsWith(l.value)||(sK(o=this._getOrReturnCtx(t,o),{code:sj.invalid_string,validation:{endsWith:l.value},message:l.message}),a.dirty()):"datetime"===l.kind?nm(l).test(t.data)||(sK(o=this._getOrReturnCtx(t,o),{code:sj.invalid_string,validation:"datetime",message:l.message}),a.dirty()):"date"===l.kind?nh.test(t.data)||(sK(o=this._getOrReturnCtx(t,o),{code:sj.invalid_string,validation:"date",message:l.message}),a.dirty()):"time"===l.kind?RegExp(`^${nf(l)}$`).test(t.data)||(sK(o=this._getOrReturnCtx(t,o),{code:sj.invalid_string,validation:"time",message:l.message}),a.dirty()):"duration"===l.kind?ns.test(t.data)||(sK(o=this._getOrReturnCtx(t,o),{validation:"duration",code:sj.invalid_string,message:l.message}),a.dirty()):"ip"===l.kind?(r=t.data,("v4"===(i=l.version)||!i)&&na.test(r)||("v6"===i||!i)&&nl.test(r)||(sK(o=this._getOrReturnCtx(t,o),{validation:"ip",code:sj.invalid_string,message:l.message}),a.dirty())):"jwt"===l.kind?!function(t,r){if(!ni.test(t))return!1;try{let[i]=t.split(".");if(!i)return!1;let s=i.replace(/-/g,"+").replace(/_/g,"/").padEnd(i.length+(4-i.length%4)%4,"="),n=JSON.parse(atob(s));if("object"!=typeof n||null===n||"typ"in n&&n?.typ!=="JWT"||!n.alg||r&&n.alg!==r)return!1;return!0}catch{return!1}}(t.data,l.alg)&&(sK(o=this._getOrReturnCtx(t,o),{validation:"jwt",code:sj.invalid_string,message:l.message}),a.dirty()):"cidr"===l.kind?(s=t.data,("v4"===(n=l.version)||!n)&&no.test(s)||("v6"===n||!n)&&np.test(s)||(sK(o=this._getOrReturnCtx(t,o),{validation:"cidr",code:sj.invalid_string,message:l.message}),a.dirty())):"base64"===l.kind?nu.test(t.data)||(sK(o=this._getOrReturnCtx(t,o),{validation:"base64",code:sj.invalid_string,message:l.message}),a.dirty()):"base64url"===l.kind?nc.test(t.data)||(sK(o=this._getOrReturnCtx(t,o),{validation:"base64url",code:sj.invalid_string,message:l.message}),a.dirty()):s3.assertNever(l);return{status:a.value,value:t.data}}_regex(t,r,i){return this.refinement(r=>t.test(r),{validation:r,code:sj.invalid_string,...s7.errToObj(i)})}_addCheck(t){return new ny({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...s7.errToObj(t)})}url(t){return this._addCheck({kind:"url",...s7.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...s7.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...s7.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...s7.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...s7.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...s7.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...s7.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...s7.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...s7.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...s7.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...s7.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...s7.errToObj(t)})}datetime(t){return"string"==typeof t?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...s7.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return"string"==typeof t?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...s7.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...s7.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...s7.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...s7.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...s7.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...s7.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...s7.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...s7.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...s7.errToObj(r)})}nonempty(t){return this.min(1,s7.errToObj(t))}trim(){return new ny({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ny({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ny({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>"datetime"===t.kind)}get isDate(){return!!this._def.checks.find(t=>"date"===t.kind)}get isTime(){return!!this._def.checks.find(t=>"time"===t.kind)}get isDuration(){return!!this._def.checks.find(t=>"duration"===t.kind)}get isEmail(){return!!this._def.checks.find(t=>"email"===t.kind)}get isURL(){return!!this._def.checks.find(t=>"url"===t.kind)}get isEmoji(){return!!this._def.checks.find(t=>"emoji"===t.kind)}get isUUID(){return!!this._def.checks.find(t=>"uuid"===t.kind)}get isNANOID(){return!!this._def.checks.find(t=>"nanoid"===t.kind)}get isCUID(){return!!this._def.checks.find(t=>"cuid"===t.kind)}get isCUID2(){return!!this._def.checks.find(t=>"cuid2"===t.kind)}get isULID(){return!!this._def.checks.find(t=>"ulid"===t.kind)}get isIP(){return!!this._def.checks.find(t=>"ip"===t.kind)}get isCIDR(){return!!this._def.checks.find(t=>"cidr"===t.kind)}get isBase64(){return!!this._def.checks.find(t=>"base64"===t.kind)}get isBase64url(){return!!this._def.checks.find(t=>"base64url"===t.kind)}get minLength(){let t=null;for(let r of this._def.checks)"min"===r.kind&&(null===t||r.value>t)&&(t=r.value);return t}get maxLength(){let t=null;for(let r of this._def.checks)"max"===r.kind&&(null===t||r.value<t)&&(t=r.value);return t}}ny.create=t=>new ny({checks:[],typeName:n4.ZodString,coerce:t?.coerce??!1,...s0(t)});class nb extends s1{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==sO.number){let r=this._getOrReturnCtx(t);return sK(r,{code:sj.invalid_type,expected:sO.number,received:r.parsedType}),sz}let r,i=new sq;for(let s of this._def.checks)"int"===s.kind?s3.isInteger(t.data)||(sK(r=this._getOrReturnCtx(t,r),{code:sj.invalid_type,expected:"integer",received:"float",message:s.message}),i.dirty()):"min"===s.kind?(s.inclusive?t.data<s.value:t.data<=s.value)&&(sK(r=this._getOrReturnCtx(t,r),{code:sj.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):"max"===s.kind?(s.inclusive?t.data>s.value:t.data>=s.value)&&(sK(r=this._getOrReturnCtx(t,r),{code:sj.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):"multipleOf"===s.kind?0!==function(t,r){let i=(t.toString().split(".")[1]||"").length,s=(r.toString().split(".")[1]||"").length,n=i>s?i:s;return Number.parseInt(t.toFixed(n).replace(".",""))%Number.parseInt(r.toFixed(n).replace(".",""))/10**n}(t.data,s.value)&&(sK(r=this._getOrReturnCtx(t,r),{code:sj.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):"finite"===s.kind?Number.isFinite(t.data)||(sK(r=this._getOrReturnCtx(t,r),{code:sj.not_finite,message:s.message}),i.dirty()):s3.assertNever(s);return{status:i.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,s7.toString(r))}gt(t,r){return this.setLimit("min",t,!1,s7.toString(r))}lte(t,r){return this.setLimit("max",t,!0,s7.toString(r))}lt(t,r){return this.setLimit("max",t,!1,s7.toString(r))}setLimit(t,r,i,s){return new nb({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:i,message:s7.toString(s)}]})}_addCheck(t){return new nb({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:s7.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:s7.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:s7.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:s7.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:s7.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:s7.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:s7.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:s7.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:s7.toString(t)})}get minValue(){let t=null;for(let r of this._def.checks)"min"===r.kind&&(null===t||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)"max"===r.kind&&(null===t||r.value<t)&&(t=r.value);return t}get isInt(){return!!this._def.checks.find(t=>"int"===t.kind||"multipleOf"===t.kind&&s3.isInteger(t.value))}get isFinite(){let t=null,r=null;for(let i of this._def.checks)if("finite"===i.kind||"int"===i.kind||"multipleOf"===i.kind)return!0;else"min"===i.kind?(null===r||i.value>r)&&(r=i.value):"max"===i.kind&&(null===t||i.value<t)&&(t=i.value);return Number.isFinite(r)&&Number.isFinite(t)}}nb.create=t=>new nb({checks:[],typeName:n4.ZodNumber,coerce:t?.coerce||!1,...s0(t)});class ng extends s1{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==sO.bigint)return this._getInvalidInput(t);let r,i=new sq;for(let s of this._def.checks)"min"===s.kind?(s.inclusive?t.data<s.value:t.data<=s.value)&&(sK(r=this._getOrReturnCtx(t,r),{code:sj.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):"max"===s.kind?(s.inclusive?t.data>s.value:t.data>=s.value)&&(sK(r=this._getOrReturnCtx(t,r),{code:sj.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):"multipleOf"===s.kind?t.data%s.value!==BigInt(0)&&(sK(r=this._getOrReturnCtx(t,r),{code:sj.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):s3.assertNever(s);return{status:i.value,value:t.data}}_getInvalidInput(t){let r=this._getOrReturnCtx(t);return sK(r,{code:sj.invalid_type,expected:sO.bigint,received:r.parsedType}),sz}gte(t,r){return this.setLimit("min",t,!0,s7.toString(r))}gt(t,r){return this.setLimit("min",t,!1,s7.toString(r))}lte(t,r){return this.setLimit("max",t,!0,s7.toString(r))}lt(t,r){return this.setLimit("max",t,!1,s7.toString(r))}setLimit(t,r,i,s){return new ng({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:i,message:s7.toString(s)}]})}_addCheck(t){return new ng({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:s7.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:s7.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:s7.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:s7.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:s7.toString(r)})}get minValue(){let t=null;for(let r of this._def.checks)"min"===r.kind&&(null===t||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)"max"===r.kind&&(null===t||r.value<t)&&(t=r.value);return t}}ng.create=t=>new ng({checks:[],typeName:n4.ZodBigInt,coerce:t?.coerce??!1,...s0(t)});class nv extends s1{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==sO.boolean){let r=this._getOrReturnCtx(t);return sK(r,{code:sj.invalid_type,expected:sO.boolean,received:r.parsedType}),sz}return sH(t.data)}}nv.create=t=>new nv({typeName:n4.ZodBoolean,coerce:t?.coerce||!1,...s0(t)});class nx extends s1{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==sO.date){let r=this._getOrReturnCtx(t);return sK(r,{code:sj.invalid_type,expected:sO.date,received:r.parsedType}),sz}if(Number.isNaN(t.data.getTime()))return sK(this._getOrReturnCtx(t),{code:sj.invalid_date}),sz;let r=new sq,i;for(let s of this._def.checks)"min"===s.kind?t.data.getTime()<s.value&&(sK(i=this._getOrReturnCtx(t,i),{code:sj.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),r.dirty()):"max"===s.kind?t.data.getTime()>s.value&&(sK(i=this._getOrReturnCtx(t,i),{code:sj.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):s3.assertNever(s);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new nx({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:s7.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:s7.toString(r)})}get minDate(){let t=null;for(let r of this._def.checks)"min"===r.kind&&(null===t||r.value>t)&&(t=r.value);return null!=t?new Date(t):null}get maxDate(){let t=null;for(let r of this._def.checks)"max"===r.kind&&(null===t||r.value<t)&&(t=r.value);return null!=t?new Date(t):null}}nx.create=t=>new nx({checks:[],coerce:t?.coerce||!1,typeName:n4.ZodDate,...s0(t)});class nT extends s1{_parse(t){if(this._getType(t)!==sO.symbol){let r=this._getOrReturnCtx(t);return sK(r,{code:sj.invalid_type,expected:sO.symbol,received:r.parsedType}),sz}return sH(t.data)}}nT.create=t=>new nT({typeName:n4.ZodSymbol,...s0(t)});class nE extends s1{_parse(t){if(this._getType(t)!==sO.undefined){let r=this._getOrReturnCtx(t);return sK(r,{code:sj.invalid_type,expected:sO.undefined,received:r.parsedType}),sz}return sH(t.data)}}nE.create=t=>new nE({typeName:n4.ZodUndefined,...s0(t)});class nS extends s1{_parse(t){if(this._getType(t)!==sO.null){let r=this._getOrReturnCtx(t);return sK(r,{code:sj.invalid_type,expected:sO.null,received:r.parsedType}),sz}return sH(t.data)}}nS.create=t=>new nS({typeName:n4.ZodNull,...s0(t)});class n_ extends s1{constructor(){super(...arguments),this._any=!0}_parse(t){return sH(t.data)}}n_.create=t=>new n_({typeName:n4.ZodAny,...s0(t)});class nP extends s1{constructor(){super(...arguments),this._unknown=!0}_parse(t){return sH(t.data)}}nP.create=t=>new nP({typeName:n4.ZodUnknown,...s0(t)});class nA extends s1{_parse(t){let r=this._getOrReturnCtx(t);return sK(r,{code:sj.invalid_type,expected:sO.never,received:r.parsedType}),sz}}nA.create=t=>new nA({typeName:n4.ZodNever,...s0(t)});class nw extends s1{_parse(t){if(this._getType(t)!==sO.undefined){let r=this._getOrReturnCtx(t);return sK(r,{code:sj.invalid_type,expected:sO.void,received:r.parsedType}),sz}return sH(t.data)}}nw.create=t=>new nw({typeName:n4.ZodVoid,...s0(t)});class nC extends s1{_parse(t){let{ctx:r,status:i}=this._processInputParams(t),s=this._def;if(r.parsedType!==sO.array)return sK(r,{code:sj.invalid_type,expected:sO.array,received:r.parsedType}),sz;if(null!==s.exactLength){let t=r.data.length>s.exactLength.value,n=r.data.length<s.exactLength.value;(t||n)&&(sK(r,{code:t?sj.too_big:sj.too_small,minimum:n?s.exactLength.value:void 0,maximum:t?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),i.dirty())}if(null!==s.minLength&&r.data.length<s.minLength.value&&(sK(r,{code:sj.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),i.dirty()),null!==s.maxLength&&r.data.length>s.maxLength.value&&(sK(r,{code:sj.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),i.dirty()),r.common.async)return Promise.all([...r.data].map((t,i)=>s.type._parseAsync(new sZ(r,t,r.path,i)))).then(t=>sq.mergeArray(i,t));let n=[...r.data].map((t,i)=>s.type._parseSync(new sZ(r,t,r.path,i)));return sq.mergeArray(i,n)}get element(){return this._def.type}min(t,r){return new nC({...this._def,minLength:{value:t,message:s7.toString(r)}})}max(t,r){return new nC({...this._def,maxLength:{value:t,message:s7.toString(r)}})}length(t,r){return new nC({...this._def,exactLength:{value:t,message:s7.toString(r)}})}nonempty(t){return this.min(1,t)}}nC.create=(t,r)=>new nC({type:t,minLength:null,maxLength:null,exactLength:null,typeName:n4.ZodArray,...s0(r)});class nI extends s1{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;let t=this._def.shape(),r=s3.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==sO.object){let r=this._getOrReturnCtx(t);return sK(r,{code:sj.invalid_type,expected:sO.object,received:r.parsedType}),sz}let{status:r,ctx:i}=this._processInputParams(t),{shape:s,keys:n}=this._getCached(),a=[];if(!(this._def.catchall instanceof nA&&"strip"===this._def.unknownKeys))for(let t in i.data)n.includes(t)||a.push(t);let o=[];for(let t of n){let r=s[t],n=i.data[t];o.push({key:{status:"valid",value:t},value:r._parse(new sZ(i,n,i.path,t)),alwaysSet:t in i.data})}if(this._def.catchall instanceof nA){let t=this._def.unknownKeys;if("passthrough"===t)for(let t of a)o.push({key:{status:"valid",value:t},value:{status:"valid",value:i.data[t]}});else if("strict"===t)a.length>0&&(sK(i,{code:sj.unrecognized_keys,keys:a}),r.dirty());else if("strip"===t);else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let t=this._def.catchall;for(let r of a){let s=i.data[r];o.push({key:{status:"valid",value:r},value:t._parse(new sZ(i,s,i.path,r)),alwaysSet:r in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let t=[];for(let r of o){let i=await r.key,s=await r.value;t.push({key:i,value:s,alwaysSet:r.alwaysSet})}return t}).then(t=>sq.mergeObjectSync(r,t)):sq.mergeObjectSync(r,o)}get shape(){return this._def.shape()}strict(t){return s7.errToObj,new nI({...this._def,unknownKeys:"strict",...void 0!==t?{errorMap:(r,i)=>{let s=this._def.errorMap?.(r,i).message??i.defaultError;return"unrecognized_keys"===r.code?{message:s7.errToObj(t).message??s}:{message:s}}}:{}})}strip(){return new nI({...this._def,unknownKeys:"strip"})}passthrough(){return new nI({...this._def,unknownKeys:"passthrough"})}extend(t){return new nI({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new nI({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:n4.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new nI({...this._def,catchall:t})}pick(t){let r={};for(let i of s3.objectKeys(t))t[i]&&this.shape[i]&&(r[i]=this.shape[i]);return new nI({...this._def,shape:()=>r})}omit(t){let r={};for(let i of s3.objectKeys(this.shape))t[i]||(r[i]=this.shape[i]);return new nI({...this._def,shape:()=>r})}deepPartial(){return function t(r){if(r instanceof nI){let i={};for(let s in r.shape){let n=r.shape[s];i[s]=nW.create(t(n))}return new nI({...r._def,shape:()=>i})}if(r instanceof nC)return new nC({...r._def,type:t(r.element)});if(r instanceof nW)return nW.create(t(r.unwrap()));if(r instanceof nH)return nH.create(t(r.unwrap()));if(r instanceof nj)return nj.create(r.items.map(r=>t(r)));else return r}(this)}partial(t){let r={};for(let i of s3.objectKeys(this.shape)){let s=this.shape[i];t&&!t[i]?r[i]=s:r[i]=s.optional()}return new nI({...this._def,shape:()=>r})}required(t){let r={};for(let i of s3.objectKeys(this.shape))if(t&&!t[i])r[i]=this.shape[i];else{let t=this.shape[i];for(;t instanceof nW;)t=t._def.innerType;r[i]=t}return new nI({...this._def,shape:()=>r})}keyof(){return n$(s3.objectKeys(this.shape))}}nI.create=(t,r)=>new nI({shape:()=>t,unknownKeys:"strip",catchall:nA.create(),typeName:n4.ZodObject,...s0(r)}),nI.strictCreate=(t,r)=>new nI({shape:()=>t,unknownKeys:"strict",catchall:nA.create(),typeName:n4.ZodObject,...s0(r)}),nI.lazycreate=(t,r)=>new nI({shape:t,unknownKeys:"strip",catchall:nA.create(),typeName:n4.ZodObject,...s0(r)});class nk extends s1{_parse(t){let{ctx:r}=this._processInputParams(t),i=this._def.options;if(r.common.async)return Promise.all(i.map(async t=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await t._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(function(t){for(let r of t)if("valid"===r.result.status)return r.result;for(let i of t)if("dirty"===i.result.status)return r.common.issues.push(...i.ctx.common.issues),i.result;let i=t.map(t=>new sR(t.ctx.common.issues));return sK(r,{code:sj.invalid_union,unionErrors:i}),sz});{let t,s=[];for(let n of i){let i={...r,common:{...r.common,issues:[]},parent:null},a=n._parseSync({data:r.data,path:r.path,parent:i});if("valid"===a.status)return a;"dirty"!==a.status||t||(t={result:a,ctx:i}),i.common.issues.length&&s.push(i.common.issues)}if(t)return r.common.issues.push(...t.ctx.common.issues),t.result;let n=s.map(t=>new sR(t));return sK(r,{code:sj.invalid_union,unionErrors:n}),sz}}get options(){return this._def.options}}nk.create=(t,r)=>new nk({options:t,typeName:n4.ZodUnion,...s0(r)});var nN=t=>{if(t instanceof nB)return nN(t.schema);if(t instanceof nz)return nN(t.innerType());if(t instanceof nU)return[t.value];if(t instanceof nV)return t.options;if(t instanceof nK)return s3.objectValues(t.enum);else if(t instanceof nJ)return nN(t._def.innerType);else if(t instanceof nE)return[void 0];else if(t instanceof nS)return[null];else if(t instanceof nW)return[void 0,...nN(t.unwrap())];else if(t instanceof nH)return[null,...nN(t.unwrap())];else if(t instanceof nZ)return nN(t.unwrap());else if(t instanceof n0)return nN(t.unwrap());else if(t instanceof nY)return nN(t._def.innerType);else return[]};class nO extends s1{_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==sO.object)return sK(r,{code:sj.invalid_type,expected:sO.object,received:r.parsedType}),sz;let i=this.discriminator,s=r.data[i],n=this.optionsMap.get(s);return n?r.common.async?n._parseAsync({data:r.data,path:r.path,parent:r}):n._parseSync({data:r.data,path:r.path,parent:r}):(sK(r,{code:sj.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[i]}),sz)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,r,i){let s=new Map;for(let i of r){let r=nN(i.shape[t]);if(!r.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let n of r){if(s.has(n))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(n)}`);s.set(n,i)}}return new nO({typeName:n4.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:s,...s0(i)})}}class nD extends s1{_parse(t){let{status:r,ctx:i}=this._processInputParams(t),s=(t,s)=>{if(sJ(t)||sJ(s))return sz;let n=function t(r,i){let s=sD(r),n=sD(i);if(r===i)return{valid:!0,data:r};if(s===sO.object&&n===sO.object){let s=s3.objectKeys(i),n=s3.objectKeys(r).filter(t=>-1!==s.indexOf(t)),a={...r,...i};for(let s of n){let n=t(r[s],i[s]);if(!n.valid)return{valid:!1};a[s]=n.data}return{valid:!0,data:a}}if(s===sO.array&&n===sO.array){if(r.length!==i.length)return{valid:!1};let s=[];for(let n=0;n<r.length;n++){let a=t(r[n],i[n]);if(!a.valid)return{valid:!1};s.push(a.data)}return{valid:!0,data:s}}if(s===sO.date&&n===sO.date&&+r==+i)return{valid:!0,data:r};return{valid:!1}}(t.value,s.value);return n.valid?((sY(t)||sY(s))&&r.dirty(),{status:r.value,value:n.data}):(sK(i,{code:sj.invalid_intersection_types}),sz)};return i.common.async?Promise.all([this._def.left._parseAsync({data:i.data,path:i.path,parent:i}),this._def.right._parseAsync({data:i.data,path:i.path,parent:i})]).then(([t,r])=>s(t,r)):s(this._def.left._parseSync({data:i.data,path:i.path,parent:i}),this._def.right._parseSync({data:i.data,path:i.path,parent:i}))}}nD.create=(t,r,i)=>new nD({left:t,right:r,typeName:n4.ZodIntersection,...s0(i)});class nj extends s1{_parse(t){let{status:r,ctx:i}=this._processInputParams(t);if(i.parsedType!==sO.array)return sK(i,{code:sj.invalid_type,expected:sO.array,received:i.parsedType}),sz;if(i.data.length<this._def.items.length)return sK(i,{code:sj.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),sz;!this._def.rest&&i.data.length>this._def.items.length&&(sK(i,{code:sj.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...i.data].map((t,r)=>{let s=this._def.items[r]||this._def.rest;return s?s._parse(new sZ(i,t,i.path,r)):null}).filter(t=>!!t);return i.common.async?Promise.all(s).then(t=>sq.mergeArray(r,t)):sq.mergeArray(r,s)}get items(){return this._def.items}rest(t){return new nj({...this._def,rest:t})}}nj.create=(t,r)=>{if(!Array.isArray(t))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new nj({items:t,typeName:n4.ZodTuple,rest:null,...s0(r)})};class nL extends s1{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:i}=this._processInputParams(t);if(i.parsedType!==sO.object)return sK(i,{code:sj.invalid_type,expected:sO.object,received:i.parsedType}),sz;let s=[],n=this._def.keyType,a=this._def.valueType;for(let t in i.data)s.push({key:n._parse(new sZ(i,t,i.path,t)),value:a._parse(new sZ(i,i.data[t],i.path,t)),alwaysSet:t in i.data});return i.common.async?sq.mergeObjectAsync(r,s):sq.mergeObjectSync(r,s)}get element(){return this._def.valueType}static create(t,r,i){return new nL(r instanceof s1?{keyType:t,valueType:r,typeName:n4.ZodRecord,...s0(i)}:{keyType:ny.create(),valueType:t,typeName:n4.ZodRecord,...s0(r)})}}class nR extends s1{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:i}=this._processInputParams(t);if(i.parsedType!==sO.map)return sK(i,{code:sj.invalid_type,expected:sO.map,received:i.parsedType}),sz;let s=this._def.keyType,n=this._def.valueType,a=[...i.data.entries()].map(([t,r],a)=>({key:s._parse(new sZ(i,t,i.path,[a,"key"])),value:n._parse(new sZ(i,r,i.path,[a,"value"]))}));if(i.common.async){let t=new Map;return Promise.resolve().then(async()=>{for(let i of a){let s=await i.key,n=await i.value;if("aborted"===s.status||"aborted"===n.status)return sz;("dirty"===s.status||"dirty"===n.status)&&r.dirty(),t.set(s.value,n.value)}return{status:r.value,value:t}})}{let t=new Map;for(let i of a){let{key:s,value:n}=i;if("aborted"===s.status||"aborted"===n.status)return sz;("dirty"===s.status||"dirty"===n.status)&&r.dirty(),t.set(s.value,n.value)}return{status:r.value,value:t}}}}nR.create=(t,r,i)=>new nR({valueType:r,keyType:t,typeName:n4.ZodMap,...s0(i)});class nM extends s1{_parse(t){let{status:r,ctx:i}=this._processInputParams(t);if(i.parsedType!==sO.set)return sK(i,{code:sj.invalid_type,expected:sO.set,received:i.parsedType}),sz;let s=this._def;null!==s.minSize&&i.data.size<s.minSize.value&&(sK(i,{code:sj.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),r.dirty()),null!==s.maxSize&&i.data.size>s.maxSize.value&&(sK(i,{code:sj.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),r.dirty());let n=this._def.valueType;function a(t){let i=new Set;for(let s of t){if("aborted"===s.status)return sz;"dirty"===s.status&&r.dirty(),i.add(s.value)}return{status:r.value,value:i}}let o=[...i.data.values()].map((t,r)=>n._parse(new sZ(i,t,i.path,r)));return i.common.async?Promise.all(o).then(t=>a(t)):a(o)}min(t,r){return new nM({...this._def,minSize:{value:t,message:s7.toString(r)}})}max(t,r){return new nM({...this._def,maxSize:{value:t,message:s7.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}}nM.create=(t,r)=>new nM({valueType:t,minSize:null,maxSize:null,typeName:n4.ZodSet,...s0(r)});class nF extends s1{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==sO.function)return sK(r,{code:sj.invalid_type,expected:sO.function,received:r.parsedType}),sz;function i(t,i){return s$({data:t,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,sF,sM].filter(t=>!!t),issueData:{code:sj.invalid_arguments,argumentsError:i}})}function s(t,i){return s$({data:t,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,sF,sM].filter(t=>!!t),issueData:{code:sj.invalid_return_type,returnTypeError:i}})}let n={errorMap:r.common.contextualErrorMap},a=r.data;if(this._def.returns instanceof nq){let t=this;return sH(async function(...r){let o=new sR([]),l=await t._def.args.parseAsync(r,n).catch(t=>{throw o.addIssue(i(r,t)),o}),p=await Reflect.apply(a,this,l);return await t._def.returns._def.type.parseAsync(p,n).catch(t=>{throw o.addIssue(s(p,t)),o})})}{let t=this;return sH(function(...r){let o=t._def.args.safeParse(r,n);if(!o.success)throw new sR([i(r,o.error)]);let l=Reflect.apply(a,this,o.data),p=t._def.returns.safeParse(l,n);if(!p.success)throw new sR([s(l,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new nF({...this._def,args:nj.create(t).rest(nP.create())})}returns(t){return new nF({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,r,i){return new nF({args:t||nj.create([]).rest(nP.create()),returns:r||nP.create(),typeName:n4.ZodFunction,...s0(i)})}}class nB extends s1{get schema(){return this._def.getter()}_parse(t){let{ctx:r}=this._processInputParams(t);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}}nB.create=(t,r)=>new nB({getter:t,typeName:n4.ZodLazy,...s0(r)});class nU extends s1{_parse(t){if(t.data!==this._def.value){let r=this._getOrReturnCtx(t);return sK(r,{received:r.data,code:sj.invalid_literal,expected:this._def.value}),sz}return{status:"valid",value:t.data}}get value(){return this._def.value}}function n$(t,r){return new nV({values:t,typeName:n4.ZodEnum,...s0(r)})}nU.create=(t,r)=>new nU({value:t,typeName:n4.ZodLiteral,...s0(r)});class nV extends s1{_parse(t){if("string"!=typeof t.data){let r=this._getOrReturnCtx(t),i=this._def.values;return sK(r,{expected:s3.joinValues(i),received:r.parsedType,code:sj.invalid_type}),sz}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let r=this._getOrReturnCtx(t),i=this._def.values;return sK(r,{received:r.data,code:sj.invalid_enum_value,options:i}),sz}return sH(t.data)}get options(){return this._def.values}get enum(){let t={};for(let r of this._def.values)t[r]=r;return t}get Values(){let t={};for(let r of this._def.values)t[r]=r;return t}get Enum(){let t={};for(let r of this._def.values)t[r]=r;return t}extract(t,r=this._def){return nV.create(t,{...this._def,...r})}exclude(t,r=this._def){return nV.create(this.options.filter(r=>!t.includes(r)),{...this._def,...r})}}nV.create=n$;class nK extends s1{_parse(t){let r=s3.getValidEnumValues(this._def.values),i=this._getOrReturnCtx(t);if(i.parsedType!==sO.string&&i.parsedType!==sO.number){let t=s3.objectValues(r);return sK(i,{expected:s3.joinValues(t),received:i.parsedType,code:sj.invalid_type}),sz}if(this._cache||(this._cache=new Set(s3.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let t=s3.objectValues(r);return sK(i,{received:i.data,code:sj.invalid_enum_value,options:t}),sz}return sH(t.data)}get enum(){return this._def.values}}nK.create=(t,r)=>new nK({values:t,typeName:n4.ZodNativeEnum,...s0(r)});class nq extends s1{unwrap(){return this._def.type}_parse(t){let{ctx:r}=this._processInputParams(t);return r.parsedType!==sO.promise&&!1===r.common.async?(sK(r,{code:sj.invalid_type,expected:sO.promise,received:r.parsedType}),sz):sH((r.parsedType===sO.promise?r.data:Promise.resolve(r.data)).then(t=>this._def.type.parseAsync(t,{path:r.path,errorMap:r.common.contextualErrorMap})))}}nq.create=(t,r)=>new nq({type:t,typeName:n4.ZodPromise,...s0(r)});class nz extends s1{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===n4.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:r,ctx:i}=this._processInputParams(t),s=this._def.effect||null,n={addIssue:t=>{(sK(i,t),t.fatal)?r.abort():r.dirty()},get path(){return i.path}};if(n.addIssue=n.addIssue.bind(n),"preprocess"===s.type){let t=s.transform(i.data,n);if(i.common.async)return Promise.resolve(t).then(async t=>{if("aborted"===r.value)return sz;let s=await this._def.schema._parseAsync({data:t,path:i.path,parent:i});return"aborted"===s.status?sz:"dirty"===s.status||"dirty"===r.value?sW(s.value):s});{if("aborted"===r.value)return sz;let s=this._def.schema._parseSync({data:t,path:i.path,parent:i});return"aborted"===s.status?sz:"dirty"===s.status||"dirty"===r.value?sW(s.value):s}}if("refinement"===s.type){let t=t=>{let r=s.refinement(t,n);if(i.common.async)return Promise.resolve(r);if(r instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return t};if(!1!==i.common.async)return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(i=>"aborted"===i.status?sz:("dirty"===i.status&&r.dirty(),t(i.value).then(()=>({status:r.value,value:i.value}))));{let s=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});return"aborted"===s.status?sz:("dirty"===s.status&&r.dirty(),t(s.value),{status:r.value,value:s.value})}}if("transform"===s.type)if(!1!==i.common.async)return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(t=>sX(t)?Promise.resolve(s.transform(t.value,n)).then(t=>({status:r.value,value:t})):sz);else{let t=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});if(!sX(t))return sz;let a=s.transform(t.value,n);if(a instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}s3.assertNever(s)}}nz.create=(t,r,i)=>new nz({schema:t,typeName:n4.ZodEffects,effect:r,...s0(i)}),nz.createWithPreprocess=(t,r,i)=>new nz({schema:r,effect:{type:"preprocess",transform:t},typeName:n4.ZodEffects,...s0(i)});class nW extends s1{_parse(t){return this._getType(t)===sO.undefined?sH(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}nW.create=(t,r)=>new nW({innerType:t,typeName:n4.ZodOptional,...s0(r)});class nH extends s1{_parse(t){return this._getType(t)===sO.null?sH(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}nH.create=(t,r)=>new nH({innerType:t,typeName:n4.ZodNullable,...s0(r)});class nJ extends s1{_parse(t){let{ctx:r}=this._processInputParams(t),i=r.data;return r.parsedType===sO.undefined&&(i=this._def.defaultValue()),this._def.innerType._parse({data:i,path:r.path,parent:r})}removeDefault(){return this._def.innerType}}nJ.create=(t,r)=>new nJ({innerType:t,typeName:n4.ZodDefault,defaultValue:"function"==typeof r.default?r.default:()=>r.default,...s0(r)});class nY extends s1{_parse(t){let{ctx:r}=this._processInputParams(t),i={...r,common:{...r.common,issues:[]}},s=this._def.innerType._parse({data:i.data,path:i.path,parent:{...i}});return sG(s)?s.then(t=>({status:"valid",value:"valid"===t.status?t.value:this._def.catchValue({get error(){return new sR(i.common.issues)},input:i.data})})):{status:"valid",value:"valid"===s.status?s.value:this._def.catchValue({get error(){return new sR(i.common.issues)},input:i.data})}}removeCatch(){return this._def.innerType}}nY.create=(t,r)=>new nY({innerType:t,typeName:n4.ZodCatch,catchValue:"function"==typeof r.catch?r.catch:()=>r.catch,...s0(r)});class nX extends s1{_parse(t){if(this._getType(t)!==sO.nan){let r=this._getOrReturnCtx(t);return sK(r,{code:sj.invalid_type,expected:sO.nan,received:r.parsedType}),sz}return{status:"valid",value:t.data}}}nX.create=t=>new nX({typeName:n4.ZodNaN,...s0(t)});var nG=Symbol("zod_brand");class nZ extends s1{_parse(t){let{ctx:r}=this._processInputParams(t),i=r.data;return this._def.type._parse({data:i,path:r.path,parent:r})}unwrap(){return this._def.type}}class nQ extends s1{_parse(t){let{status:r,ctx:i}=this._processInputParams(t);if(i.common.async)return(async()=>{let t=await this._def.in._parseAsync({data:i.data,path:i.path,parent:i});return"aborted"===t.status?sz:"dirty"===t.status?(r.dirty(),sW(t.value)):this._def.out._parseAsync({data:t.value,path:i.path,parent:i})})();{let t=this._def.in._parseSync({data:i.data,path:i.path,parent:i});return"aborted"===t.status?sz:"dirty"===t.status?(r.dirty(),{status:"dirty",value:t.value}):this._def.out._parseSync({data:t.value,path:i.path,parent:i})}}static create(t,r){return new nQ({in:t,out:r,typeName:n4.ZodPipeline})}}class n0 extends s1{_parse(t){let r=this._def.innerType._parse(t),i=t=>(sX(t)&&(t.value=Object.freeze(t.value)),t);return sG(r)?r.then(t=>i(t)):i(r)}unwrap(){return this._def.innerType}}function n1(t,r){let i="function"==typeof t?t(r):"string"==typeof t?{message:t}:t;return"string"==typeof i?{message:i}:i}function n2(t,r={},i){return t?n_.create().superRefine((s,n)=>{let a=t(s);if(a instanceof Promise)return a.then(t=>{if(!t){let t=n1(r,s),a=t.fatal??i??!0;n.addIssue({code:"custom",...t,fatal:a})}});if(!a){let t=n1(r,s),a=t.fatal??i??!0;n.addIssue({code:"custom",...t,fatal:a})}}):n_.create()}n0.create=(t,r)=>new n0({innerType:t,typeName:n4.ZodReadonly,...s0(r)});var n4,n3={object:nI.lazycreate};(u=n4||(n4={})).ZodString="ZodString",u.ZodNumber="ZodNumber",u.ZodNaN="ZodNaN",u.ZodBigInt="ZodBigInt",u.ZodBoolean="ZodBoolean",u.ZodDate="ZodDate",u.ZodSymbol="ZodSymbol",u.ZodUndefined="ZodUndefined",u.ZodNull="ZodNull",u.ZodAny="ZodAny",u.ZodUnknown="ZodUnknown",u.ZodNever="ZodNever",u.ZodVoid="ZodVoid",u.ZodArray="ZodArray",u.ZodObject="ZodObject",u.ZodUnion="ZodUnion",u.ZodDiscriminatedUnion="ZodDiscriminatedUnion",u.ZodIntersection="ZodIntersection",u.ZodTuple="ZodTuple",u.ZodRecord="ZodRecord",u.ZodMap="ZodMap",u.ZodSet="ZodSet",u.ZodFunction="ZodFunction",u.ZodLazy="ZodLazy",u.ZodLiteral="ZodLiteral",u.ZodEnum="ZodEnum",u.ZodEffects="ZodEffects",u.ZodNativeEnum="ZodNativeEnum",u.ZodOptional="ZodOptional",u.ZodNullable="ZodNullable",u.ZodDefault="ZodDefault",u.ZodCatch="ZodCatch",u.ZodPromise="ZodPromise",u.ZodBranded="ZodBranded",u.ZodPipeline="ZodPipeline",u.ZodReadonly="ZodReadonly";var n8=(t,r={message:`Input not instance of ${t.name}`})=>n2(r=>r instanceof t,r),n7=ny.create,n9=nb.create,n5=nX.create,n6=ng.create,ae=nv.create,at=nx.create,ar=nT.create,ai=nE.create,as=nS.create,an=n_.create,aa=nP.create,ao=nA.create,al=nw.create,ap=nC.create,au=nI.create,ac=nI.strictCreate,ad=nk.create,ah=nO.create,af=nD.create,am=nj.create,ay=nL.create,ab=nR.create,ag=nM.create,av=nF.create,ax=nB.create,aT=nU.create,aE=nV.create,aS=nK.create,a_=nq.create,aP=nz.create,aA=nW.create,aw=nH.create,aC=nz.createWithPreprocess,aI=nQ.create,ak=()=>n7().optional(),aN=()=>n9().optional(),aO=()=>ae().optional(),aD={string:t=>ny.create({...t,coerce:!0}),number:t=>nb.create({...t,coerce:!0}),boolean:t=>nv.create({...t,coerce:!0}),bigint:t=>ng.create({...t,coerce:!0}),date:t=>nx.create({...t,coerce:!0})},aj=sz;function aL(t,r,i){function s(i,s){var n;for(let a in Object.defineProperty(i,"_zod",{value:i._zod??{},enumerable:!1}),(n=i._zod).traits??(n.traits=new Set),i._zod.traits.add(t),r(i,s),o.prototype)a in i||Object.defineProperty(i,a,{value:o.prototype[a].bind(i)});i._zod.constr=o,i._zod.def=s}let n=i?.Parent??Object;class a extends n{}function o(t){var r;let n=i?.Parent?new a:this;for(let i of(s(n,t),(r=n._zod).deferred??(r.deferred=[]),n._zod.deferred))i();return n}return Object.defineProperty(a,"name",{value:t}),Object.defineProperty(o,"init",{value:s}),Object.defineProperty(o,Symbol.hasInstance,{value:r=>!!i?.Parent&&r instanceof i.Parent||r?._zod?.traits?.has(t)}),Object.defineProperty(o,"name",{value:t}),o}Object.freeze({status:"aborted"}),Symbol("zod_brand");class aR extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}var aM={};function aF(t){return t&&Object.assign(aM,t),aM}var aB={};function aU(t){return t}function a$(t){return t}function aV(t){}function aK(t){throw Error()}function aq(t){}function az(t){let r=Object.values(t).filter(t=>"number"==typeof t);return Object.entries(t).filter(([t,i])=>-1===r.indexOf(+t)).map(([t,r])=>r)}function aW(t,r="|"){return t.map(t=>oa(t)).join(r)}function aH(t,r){return"bigint"==typeof r?r.toString():r}function aJ(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}}}}function aY(t){return null==t}function aX(t){let r=+!!t.startsWith("^"),i=t.endsWith("$")?t.length-1:t.length;return t.slice(r,i)}function aG(t,r){let i=(t.toString().split(".")[1]||"").length,s=(r.toString().split(".")[1]||"").length,n=i>s?i:s;return Number.parseInt(t.toFixed(n).replace(".",""))%Number.parseInt(r.toFixed(n).replace(".",""))/10**n}function aZ(t,r,i){Object.defineProperty(t,r,{get(){{let s=i();return t[r]=s,s}},set(i){Object.defineProperty(t,r,{value:i})},configurable:!0})}function aQ(t,r,i){Object.defineProperty(t,r,{value:i,writable:!0,enumerable:!0,configurable:!0})}function a0(t,r){return r?r.reduce((t,r)=>t?.[r],t):t}function a1(t){let r=Object.keys(t);return Promise.all(r.map(r=>t[r])).then(t=>{let i={};for(let s=0;s<r.length;s++)i[r[s]]=t[s];return i})}function a2(t=10){let r="";for(let i=0;i<t;i++)r+="abcdefghijklmnopqrstuvwxyz"[Math.floor(26*Math.random())];return r}function a4(t){return JSON.stringify(t)}rc(aB,{unwrapMessage:()=>og,stringifyPrimitive:()=>oa,required:()=>om,randomString:()=>a2,propertyKeyTypes:()=>oe,promiseAllObject:()=>a1,primitiveTypes:()=>ot,prefixIssues:()=>ob,pick:()=>ou,partial:()=>of,optionalKeys:()=>oo,omit:()=>oc,numKeys:()=>a5,nullish:()=>aY,normalizeParams:()=>os,merge:()=>oh,jsonStringifyReplacer:()=>aH,joinValues:()=>aW,issue:()=>oE,isPlainObject:()=>a9,isObject:()=>a8,getSizableOrigin:()=>ox,getParsedType:()=>a6,getLengthableOrigin:()=>oT,getEnumValues:()=>az,getElementAtPath:()=>a0,floatSafeRemainder:()=>aG,finalizeIssue:()=>ov,extend:()=>od,escapeRegex:()=>or,esc:()=>a4,defineLazy:()=>aZ,createTransparentProxy:()=>on,clone:()=>oi,cleanRegex:()=>aX,cleanEnum:()=>oS,captureStackTrace:()=>a3,cached:()=>aJ,assignProp:()=>aQ,assertNotEqual:()=>a$,assertNever:()=>aK,assertIs:()=>aV,assertEqual:()=>aU,assert:()=>aq,allowsEval:()=>a7,aborted:()=>oy,NUMBER_FORMAT_RANGES:()=>ol,Class:()=>o_,BIGINT_FORMAT_RANGES:()=>op});var a3=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function a8(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}var a7=aJ(()=>{if("u">typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return Function(""),!0}catch(t){return!1}});function a9(t){if(!1===a8(t))return!1;let r=t.constructor;if(void 0===r)return!0;let i=r.prototype;return!1!==a8(i)&&!1!==Object.prototype.hasOwnProperty.call(i,"isPrototypeOf")}function a5(t){let r=0;for(let i in t)Object.prototype.hasOwnProperty.call(t,i)&&r++;return r}var a6=t=>{let r=typeof t;switch(r){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(t))return"array";if(null===t)return"null";if(t.then&&"function"==typeof t.then&&t.catch&&"function"==typeof t.catch)return"promise";if("u">typeof Map&&t instanceof Map)return"map";if("u">typeof Set&&t instanceof Set)return"set";if("u">typeof Date&&t instanceof Date)return"date";if("u">typeof File&&t instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${r}`)}},oe=new Set(["string","number","symbol"]),ot=new Set(["string","number","bigint","boolean","symbol","undefined"]);function or(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function oi(t,r,i){let s=new t._zod.constr(r??t._zod.def);return(!r||i?.parent)&&(s._zod.parent=t),s}function os(t){if(!t)return{};if("string"==typeof t)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return(delete t.message,"string"==typeof t.error)?{...t,error:()=>t.error}:t}function on(t){let r;return new Proxy({},{get:(i,s,n)=>(r??(r=t()),Reflect.get(r,s,n)),set:(i,s,n,a)=>(r??(r=t()),Reflect.set(r,s,n,a)),has:(i,s)=>(r??(r=t()),Reflect.has(r,s)),deleteProperty:(i,s)=>(r??(r=t()),Reflect.deleteProperty(r,s)),ownKeys:i=>(r??(r=t()),Reflect.ownKeys(r)),getOwnPropertyDescriptor:(i,s)=>(r??(r=t()),Reflect.getOwnPropertyDescriptor(r,s)),defineProperty:(i,s,n)=>(r??(r=t()),Reflect.defineProperty(r,s,n))})}function oa(t){return"bigint"==typeof t?t.toString()+"n":"string"==typeof t?`"${t}"`:`${t}`}function oo(t){return Object.keys(t).filter(r=>"optional"===t[r]._zod.optin&&"optional"===t[r]._zod.optout)}var ol={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-0x80000000,0x7fffffff],uint32:[0,0xffffffff],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},op={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function ou(t,r){let i={},s=t._zod.def;for(let t in r){if(!(t in s.shape))throw Error(`Unrecognized key: "${t}"`);r[t]&&(i[t]=s.shape[t])}return oi(t,{...t._zod.def,shape:i,checks:[]})}function oc(t,r){let i={...t._zod.def.shape},s=t._zod.def;for(let t in r){if(!(t in s.shape))throw Error(`Unrecognized key: "${t}"`);r[t]&&delete i[t]}return oi(t,{...t._zod.def,shape:i,checks:[]})}function od(t,r){if(!a9(r))throw Error("Invalid input to extend: expected a plain object");let i={...t._zod.def,get shape(){let i={...t._zod.def.shape,...r};return aQ(this,"shape",i),i},checks:[]};return oi(t,i)}function oh(t,r){return oi(t,{...t._zod.def,get shape(){let i={...t._zod.def.shape,...r._zod.def.shape};return aQ(this,"shape",i),i},catchall:r._zod.def.catchall,checks:[]})}function of(t,r,i){let s=r._zod.def.shape,n={...s};if(i)for(let r in i){if(!(r in s))throw Error(`Unrecognized key: "${r}"`);i[r]&&(n[r]=t?new t({type:"optional",innerType:s[r]}):s[r])}else for(let r in s)n[r]=t?new t({type:"optional",innerType:s[r]}):s[r];return oi(r,{...r._zod.def,shape:n,checks:[]})}function om(t,r,i){let s=r._zod.def.shape,n={...s};if(i)for(let r in i){if(!(r in n))throw Error(`Unrecognized key: "${r}"`);i[r]&&(n[r]=new t({type:"nonoptional",innerType:s[r]}))}else for(let r in s)n[r]=new t({type:"nonoptional",innerType:s[r]});return oi(r,{...r._zod.def,shape:n,checks:[]})}function oy(t,r=0){for(let i=r;i<t.issues.length;i++)if(t.issues[i]?.continue!==!0)return!0;return!1}function ob(t,r){return r.map(r=>(r.path??(r.path=[]),r.path.unshift(t),r))}function og(t){return"string"==typeof t?t:t?.message}function ov(t,r,i){let s={...t,path:t.path??[]};return t.message||(s.message=og(t.inst?._zod.def?.error?.(t))??og(r?.error?.(t))??og(i.customError?.(t))??og(i.localeError?.(t))??"Invalid input"),delete s.inst,delete s.continue,r?.reportInput||delete s.input,s}function ox(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function oT(t){return Array.isArray(t)?"array":"string"==typeof t?"string":"unknown"}function oE(...t){let[r,i,s]=t;return"string"==typeof r?{message:r,code:"custom",input:i,inst:s}:{...r}}function oS(t){return Object.entries(t).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}class o_{constructor(...t){}}var oP=(t,r)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:r,enumerable:!1}),Object.defineProperty(t,"message",{get:()=>JSON.stringify(r,aH,2),enumerable:!0})},oA=aL("$ZodError",oP),ow=aL("$ZodError",oP,{Parent:Error}),oC=t=>(r,i,s,n)=>{let a=s?Object.assign(s,{async:!1}):{async:!1},o=r._zod.run({value:i,issues:[]},a);if(o instanceof Promise)throw new aR;if(o.issues.length){let r=new(n?.Err??t)(o.issues.map(t=>ov(t,a,aF())));throw a3(r,n?.callee),r}return o.value},oI=oC(ow),ok=t=>async(r,i,s,n)=>{let a=s?Object.assign(s,{async:!0}):{async:!0},o=r._zod.run({value:i,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){let r=new(n?.Err??t)(o.issues.map(t=>ov(t,a,aF())));throw a3(r,n?.callee),r}return o.value},oN=ok(ow),oO=t=>(r,i,s)=>{let n=s?{...s,async:!1}:{async:!1},a=r._zod.run({value:i,issues:[]},n);if(a instanceof Promise)throw new aR;return a.issues.length?{success:!1,error:new(t??oA)(a.issues.map(t=>ov(t,n,aF())))}:{success:!0,data:a.value}},oD=oO(ow),oj=t=>async(r,i,s)=>{let n=s?Object.assign(s,{async:!0}):{async:!0},a=r._zod.run({value:i,issues:[]},n);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new t(a.issues.map(t=>ov(t,n,aF())))}:{success:!0,data:a.value}},oL=oj(ow),oR=/^[cC][^\s-]{8,}$/,oM=/^[0-9a-z]+$/,oF=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,oB=/^[0-9a-vA-V]{20}$/,oU=/^[A-Za-z0-9]{27}$/,o$=/^[a-zA-Z0-9_-]{21}$/,oV=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,oK=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,oq=t=>t?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,oz=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,oW=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,oH=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,oJ=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,oY=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,oX=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,oG=/^[A-Za-z0-9_-]*$/,oZ=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,oQ=/^\+(?:[0-9]){6,14}[0-9]$/,o0="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",o1=RegExp(`^${o0}$`);function o2(t){return"number"==typeof t.precision?-1===t.precision?"(?:[01]\\d|2[0-3]):[0-5]\\d":0===t.precision?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${t.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}var o4=/^\d+$/,o3=/^-?\d+(?:\.\d+)?/i,o8=/true|false/i,o7=/null/i,o9=/^[^A-Z]*$/,o5=/^[^a-z]*$/,o6=aL("$ZodCheck",(t,r)=>{var i;t._zod??(t._zod={}),t._zod.def=r,(i=t._zod).onattach??(i.onattach=[])}),le={number:"number",bigint:"bigint",object:"date"},lt=aL("$ZodCheckLessThan",(t,r)=>{o6.init(t,r);let i=le[typeof r.value];t._zod.onattach.push(t=>{let i=t._zod.bag,s=(r.inclusive?i.maximum:i.exclusiveMaximum)??1/0;r.value<s&&(r.inclusive?i.maximum=r.value:i.exclusiveMaximum=r.value)}),t._zod.check=s=>{(r.inclusive?s.value<=r.value:s.value<r.value)||s.issues.push({origin:i,code:"too_big",maximum:r.value,input:s.value,inclusive:r.inclusive,inst:t,continue:!r.abort})}}),lr=aL("$ZodCheckGreaterThan",(t,r)=>{o6.init(t,r);let i=le[typeof r.value];t._zod.onattach.push(t=>{let i=t._zod.bag,s=(r.inclusive?i.minimum:i.exclusiveMinimum)??-1/0;r.value>s&&(r.inclusive?i.minimum=r.value:i.exclusiveMinimum=r.value)}),t._zod.check=s=>{(r.inclusive?s.value>=r.value:s.value>r.value)||s.issues.push({origin:i,code:"too_small",minimum:r.value,input:s.value,inclusive:r.inclusive,inst:t,continue:!r.abort})}}),li=aL("$ZodCheckMultipleOf",(t,r)=>{o6.init(t,r),t._zod.onattach.push(t=>{var i;(i=t._zod.bag).multipleOf??(i.multipleOf=r.value)}),t._zod.check=i=>{if(typeof i.value!=typeof r.value)throw Error("Cannot mix number and bigint in multiple_of check.");("bigint"==typeof i.value?i.value%r.value!==BigInt(0):0!==aG(i.value,r.value))&&i.issues.push({origin:typeof i.value,code:"not_multiple_of",divisor:r.value,input:i.value,inst:t,continue:!r.abort})}}),ls=aL("$ZodCheckNumberFormat",(t,r)=>{o6.init(t,r),r.format=r.format||"float64";let i=r.format?.includes("int"),s=i?"int":"number",[n,a]=ol[r.format];t._zod.onattach.push(t=>{let s=t._zod.bag;s.format=r.format,s.minimum=n,s.maximum=a,i&&(s.pattern=o4)}),t._zod.check=o=>{let l=o.value;if(i){if(!Number.isInteger(l))return void o.issues.push({expected:s,format:r.format,code:"invalid_type",input:l,inst:t});if(!Number.isSafeInteger(l))return void(l>0?o.issues.push({input:l,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:s,continue:!r.abort}):o.issues.push({input:l,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:s,continue:!r.abort}))}l<n&&o.issues.push({origin:"number",input:l,code:"too_small",minimum:n,inclusive:!0,inst:t,continue:!r.abort}),l>a&&o.issues.push({origin:"number",input:l,code:"too_big",maximum:a,inst:t})}}),ln=aL("$ZodCheckMaxLength",(t,r)=>{o6.init(t,r),t._zod.when=t=>{let r=t.value;return!aY(r)&&void 0!==r.length},t._zod.onattach.push(t=>{let i=t._zod.bag.maximum??1/0;r.maximum<i&&(t._zod.bag.maximum=r.maximum)}),t._zod.check=i=>{let s=i.value;if(s.length<=r.maximum)return;let n=oT(s);i.issues.push({origin:n,code:"too_big",maximum:r.maximum,inclusive:!0,input:s,inst:t,continue:!r.abort})}}),la=aL("$ZodCheckMinLength",(t,r)=>{o6.init(t,r),t._zod.when=t=>{let r=t.value;return!aY(r)&&void 0!==r.length},t._zod.onattach.push(t=>{let i=t._zod.bag.minimum??-1/0;r.minimum>i&&(t._zod.bag.minimum=r.minimum)}),t._zod.check=i=>{let s=i.value;if(s.length>=r.minimum)return;let n=oT(s);i.issues.push({origin:n,code:"too_small",minimum:r.minimum,inclusive:!0,input:s,inst:t,continue:!r.abort})}}),lo=aL("$ZodCheckLengthEquals",(t,r)=>{o6.init(t,r),t._zod.when=t=>{let r=t.value;return!aY(r)&&void 0!==r.length},t._zod.onattach.push(t=>{let i=t._zod.bag;i.minimum=r.length,i.maximum=r.length,i.length=r.length}),t._zod.check=i=>{let s=i.value,n=s.length;if(n===r.length)return;let a=oT(s),o=n>r.length;i.issues.push({origin:a,...o?{code:"too_big",maximum:r.length}:{code:"too_small",minimum:r.length},inclusive:!0,exact:!0,input:i.value,inst:t,continue:!r.abort})}}),ll=aL("$ZodCheckStringFormat",(t,r)=>{var i,s;(o6.init(t,r),t._zod.onattach.push(t=>{let i=t._zod.bag;i.format=r.format,r.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(r.pattern))}),r.pattern)?(i=t._zod).check??(i.check=i=>{r.pattern.lastIndex=0,r.pattern.test(i.value)||i.issues.push({origin:"string",code:"invalid_format",format:r.format,input:i.value,...r.pattern?{pattern:r.pattern.toString()}:{},inst:t,continue:!r.abort})}):(s=t._zod).check??(s.check=()=>{})}),lp=aL("$ZodCheckRegex",(t,r)=>{ll.init(t,r),t._zod.check=i=>{r.pattern.lastIndex=0,r.pattern.test(i.value)||i.issues.push({origin:"string",code:"invalid_format",format:"regex",input:i.value,pattern:r.pattern.toString(),inst:t,continue:!r.abort})}}),lu=aL("$ZodCheckLowerCase",(t,r)=>{r.pattern??(r.pattern=o9),ll.init(t,r)}),lc=aL("$ZodCheckUpperCase",(t,r)=>{r.pattern??(r.pattern=o5),ll.init(t,r)}),ld=aL("$ZodCheckIncludes",(t,r)=>{o6.init(t,r);let i=or(r.includes),s=new RegExp("number"==typeof r.position?`^.{${r.position}}${i}`:i);r.pattern=s,t._zod.onattach.push(t=>{let r=t._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(s)}),t._zod.check=i=>{i.value.includes(r.includes,r.position)||i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:r.includes,input:i.value,inst:t,continue:!r.abort})}}),lh=aL("$ZodCheckStartsWith",(t,r)=>{o6.init(t,r);let i=RegExp(`^${or(r.prefix)}.*`);r.pattern??(r.pattern=i),t._zod.onattach.push(t=>{let r=t._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(i)}),t._zod.check=i=>{i.value.startsWith(r.prefix)||i.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:r.prefix,input:i.value,inst:t,continue:!r.abort})}}),lf=aL("$ZodCheckEndsWith",(t,r)=>{o6.init(t,r);let i=RegExp(`.*${or(r.suffix)}$`);r.pattern??(r.pattern=i),t._zod.onattach.push(t=>{let r=t._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(i)}),t._zod.check=i=>{i.value.endsWith(r.suffix)||i.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:r.suffix,input:i.value,inst:t,continue:!r.abort})}}),lm=aL("$ZodCheckOverwrite",(t,r)=>{o6.init(t,r),t._zod.check=t=>{t.value=r.tx(t.value)}});class ly{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if("function"==typeof t){t(this,{execution:"sync"}),t(this,{execution:"async"});return}let r=t.split(`
|
|
369
369
|
`).filter(t=>t),i=Math.min(...r.map(t=>t.length-t.trimStart().length));for(let t of r.map(t=>t.slice(i)).map(t=>" ".repeat(2*this.indent)+t))this.content.push(t)}compile(){return Function(...this?.args,[...(this?.content??[""]).map(t=>` ${t}`)].join(`
|
|
370
|
-
`))}}var
|
|
370
|
+
`))}}var lb={major:4,minor:0,patch:0},lg=aL("$ZodType",(t,r)=>{var i;t??(t={}),t._zod.def=r,t._zod.bag=t._zod.bag||{},t._zod.version=lb;let s=[...t._zod.def.checks??[]];for(let r of(t._zod.traits.has("$ZodCheck")&&s.unshift(t),s))for(let i of r._zod.onattach)i(t);if(0===s.length)(i=t._zod).deferred??(i.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let r=(t,r,i)=>{let s=oy(t),n;for(let a of r){if(a._zod.when){if(!a._zod.when(t))continue}else if(s)continue;let r=t.issues.length,o=a._zod.check(t);if(o instanceof Promise&&i?.async===!1)throw new aR;if(n||o instanceof Promise)n=(n??Promise.resolve()).then(async()=>{await o,t.issues.length!==r&&(s||(s=oy(t,r)))});else{if(t.issues.length===r)continue;s||(s=oy(t,r))}}return n?n.then(()=>t):t};t._zod.run=(i,n)=>{let a=t._zod.parse(i,n);if(a instanceof Promise){if(!1===n.async)throw new aR;return a.then(t=>r(t,s,n))}return r(a,s,n)}}t["~standard"]={validate:r=>{try{let i=oD(t,r);return i.success?{value:i.data}:{issues:i.error?.issues}}catch(i){return oL(t,r).then(t=>t.success?{value:t.data}:{issues:t.error?.issues})}},vendor:"zod",version:1}}),lv=aL("$ZodString",(t,r)=>{var i;let s;lg.init(t,r),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??(s=(i=t._zod.bag)?`[\\s\\S]{${i?.minimum??0},${i?.maximum??""}}`:"[\\s\\S]*",RegExp(`^${s}$`)),t._zod.parse=(i,s)=>{if(r.coerce)try{i.value=String(i.value)}catch(t){}return"string"==typeof i.value||i.issues.push({expected:"string",code:"invalid_type",input:i.value,inst:t}),i}}),lx=aL("$ZodStringFormat",(t,r)=>{ll.init(t,r),lv.init(t,r)}),lT=aL("$ZodGUID",(t,r)=>{r.pattern??(r.pattern=oK),lx.init(t,r)}),lE=aL("$ZodUUID",(t,r)=>{if(r.version){let t={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[r.version];if(void 0===t)throw Error(`Invalid UUID version: "${r.version}"`);r.pattern??(r.pattern=oq(t))}else r.pattern??(r.pattern=oq());lx.init(t,r)}),lS=aL("$ZodEmail",(t,r)=>{r.pattern??(r.pattern=oz),lx.init(t,r)}),l_=aL("$ZodURL",(t,r)=>{lx.init(t,r),t._zod.check=i=>{try{let s=i.value,n=new URL(s),a=n.href;r.hostname&&(r.hostname.lastIndex=0,!r.hostname.test(n.hostname))&&i.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:oZ.source,input:i.value,inst:t,continue:!r.abort}),r.protocol&&(r.protocol.lastIndex=0,!r.protocol.test(n.protocol.endsWith(":")?n.protocol.slice(0,-1):n.protocol))&&i.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:r.protocol.source,input:i.value,inst:t,continue:!r.abort}),!s.endsWith("/")&&a.endsWith("/")?i.value=a.slice(0,-1):i.value=a;return}catch(s){i.issues.push({code:"invalid_format",format:"url",input:i.value,inst:t,continue:!r.abort})}}}),lP=aL("$ZodEmoji",(t,r)=>{r.pattern??(r.pattern=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),lx.init(t,r)}),lA=aL("$ZodNanoID",(t,r)=>{r.pattern??(r.pattern=o$),lx.init(t,r)}),lw=aL("$ZodCUID",(t,r)=>{r.pattern??(r.pattern=oR),lx.init(t,r)}),lC=aL("$ZodCUID2",(t,r)=>{r.pattern??(r.pattern=oM),lx.init(t,r)}),lI=aL("$ZodULID",(t,r)=>{r.pattern??(r.pattern=oF),lx.init(t,r)}),lk=aL("$ZodXID",(t,r)=>{r.pattern??(r.pattern=oB),lx.init(t,r)}),lN=aL("$ZodKSUID",(t,r)=>{r.pattern??(r.pattern=oU),lx.init(t,r)}),lO=aL("$ZodISODateTime",(t,r)=>{let i,s,n;r.pattern??(i=o2({precision:r.precision}),s=["Z"],r.local&&s.push(""),r.offset&&s.push("([+-]\\d{2}:\\d{2})"),n=`${i}(?:${s.join("|")})`,r.pattern=RegExp(`^${o0}T(?:${n})$`)),lx.init(t,r)}),lD=aL("$ZodISODate",(t,r)=>{r.pattern??(r.pattern=o1),lx.init(t,r)}),lj=aL("$ZodISOTime",(t,r)=>{r.pattern??(r.pattern=RegExp(`^${o2(r)}$`)),lx.init(t,r)}),lL=aL("$ZodISODuration",(t,r)=>{r.pattern??(r.pattern=oV),lx.init(t,r)}),lR=aL("$ZodIPv4",(t,r)=>{r.pattern??(r.pattern=oW),lx.init(t,r),t._zod.onattach.push(t=>{t._zod.bag.format="ipv4"})}),lM=aL("$ZodIPv6",(t,r)=>{r.pattern??(r.pattern=oH),lx.init(t,r),t._zod.onattach.push(t=>{t._zod.bag.format="ipv6"}),t._zod.check=i=>{try{new URL(`http://[${i.value}]`)}catch{i.issues.push({code:"invalid_format",format:"ipv6",input:i.value,inst:t,continue:!r.abort})}}}),lF=aL("$ZodCIDRv4",(t,r)=>{r.pattern??(r.pattern=oJ),lx.init(t,r)}),lB=aL("$ZodCIDRv6",(t,r)=>{r.pattern??(r.pattern=oY),lx.init(t,r),t._zod.check=i=>{let[s,n]=i.value.split("/");try{if(!n)throw Error();let t=Number(n);if(`${t}`!==n||t<0||t>128)throw Error();new URL(`http://[${s}]`)}catch{i.issues.push({code:"invalid_format",format:"cidrv6",input:i.value,inst:t,continue:!r.abort})}}});function lU(t){if(""===t)return!0;if(t.length%4!=0)return!1;try{return atob(t),!0}catch{return!1}}var l$=aL("$ZodBase64",(t,r)=>{r.pattern??(r.pattern=oX),lx.init(t,r),t._zod.onattach.push(t=>{t._zod.bag.contentEncoding="base64"}),t._zod.check=i=>{lU(i.value)||i.issues.push({code:"invalid_format",format:"base64",input:i.value,inst:t,continue:!r.abort})}}),lV=aL("$ZodBase64URL",(t,r)=>{r.pattern??(r.pattern=oG),lx.init(t,r),t._zod.onattach.push(t=>{t._zod.bag.contentEncoding="base64url"}),t._zod.check=i=>{!function(t){if(!oG.test(t))return!1;let r=t.replace(/[-_]/g,t=>"-"===t?"+":"/");return lU(r.padEnd(4*Math.ceil(r.length/4),"="))}(i.value)&&i.issues.push({code:"invalid_format",format:"base64url",input:i.value,inst:t,continue:!r.abort})}}),lK=aL("$ZodE164",(t,r)=>{r.pattern??(r.pattern=oQ),lx.init(t,r)}),lq=aL("$ZodJWT",(t,r)=>{lx.init(t,r),t._zod.check=i=>{!function(t,r=null){try{let i=t.split(".");if(3!==i.length)return!1;let[s]=i;if(!s)return!1;let n=JSON.parse(atob(s));if("typ"in n&&n?.typ!=="JWT"||!n.alg||r&&(!("alg"in n)||n.alg!==r))return!1;return!0}catch{return!1}}(i.value,r.alg)&&i.issues.push({code:"invalid_format",format:"jwt",input:i.value,inst:t,continue:!r.abort})}}),lz=aL("$ZodNumber",(t,r)=>{lg.init(t,r),t._zod.pattern=t._zod.bag.pattern??o3,t._zod.parse=(i,s)=>{if(r.coerce)try{i.value=Number(i.value)}catch(t){}let n=i.value;if("number"==typeof n&&!Number.isNaN(n)&&Number.isFinite(n))return i;let a="number"==typeof n?Number.isNaN(n)?"NaN":Number.isFinite(n)?void 0:"Infinity":void 0;return i.issues.push({expected:"number",code:"invalid_type",input:n,inst:t,...a?{received:a}:{}}),i}}),lW=aL("$ZodNumber",(t,r)=>{ls.init(t,r),lz.init(t,r)}),lH=aL("$ZodBoolean",(t,r)=>{lg.init(t,r),t._zod.pattern=o8,t._zod.parse=(i,s)=>{if(r.coerce)try{i.value=!!i.value}catch(t){}let n=i.value;return"boolean"==typeof n||i.issues.push({expected:"boolean",code:"invalid_type",input:n,inst:t}),i}}),lJ=aL("$ZodNull",(t,r)=>{lg.init(t,r),t._zod.pattern=o7,t._zod.values=new Set([null]),t._zod.parse=(r,i)=>{let s=r.value;return null===s||r.issues.push({expected:"null",code:"invalid_type",input:s,inst:t}),r}}),lY=aL("$ZodUnknown",(t,r)=>{lg.init(t,r),t._zod.parse=t=>t}),lX=aL("$ZodNever",(t,r)=>{lg.init(t,r),t._zod.parse=(r,i)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});function lG(t,r,i){t.issues.length&&r.issues.push(...ob(i,t.issues)),r.value[i]=t.value}var lZ=aL("$ZodArray",(t,r)=>{lg.init(t,r),t._zod.parse=(i,s)=>{let n=i.value;if(!Array.isArray(n))return i.issues.push({expected:"array",code:"invalid_type",input:n,inst:t}),i;i.value=Array(n.length);let a=[];for(let t=0;t<n.length;t++){let o=n[t],l=r.element._zod.run({value:o,issues:[]},s);l instanceof Promise?a.push(l.then(r=>lG(r,i,t))):lG(l,i,t)}return a.length?Promise.all(a).then(()=>i):i}});function lQ(t,r,i){t.issues.length&&r.issues.push(...ob(i,t.issues)),r.value[i]=t.value}function l0(t,r,i,s){t.issues.length?void 0===s[i]?i in s?r.value[i]=void 0:r.value[i]=t.value:r.issues.push(...ob(i,t.issues)):void 0===t.value?i in s&&(r.value[i]=void 0):r.value[i]=t.value}var l1=aL("$ZodObject",(t,r)=>{lg.init(t,r);let i=aJ(()=>{let t=Object.keys(r.shape);for(let i of t)if(!(r.shape[i]instanceof lg))throw Error(`Invalid element at key "${i}": expected a Zod schema`);let i=oo(r.shape);return{shape:r.shape,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(i)}});aZ(t._zod,"propValues",()=>{let t=r.shape,i={};for(let r in t){let s=t[r]._zod;if(s.values)for(let t of(i[r]??(i[r]=new Set),s.values))i[r].add(t)}return i});let s,n=!aM.jitless,a=n&&a7.value,o=r.catchall,l;t._zod.parse=(p,u)=>{l??(l=i.value);let c=p.value;if(!a8(c))return p.issues.push({expected:"object",code:"invalid_type",input:c,inst:t}),p;let d=[];if(n&&a&&u?.async===!1&&!0!==u.jitless)s||(s=(t=>{let r=new ly(["shape","payload","ctx"]),s=i.value,n=t=>{let r=a4(t);return`shape[${r}]._zod.run({ value: input[${r}], issues: [] }, ctx)`};r.write("const input = payload.value;");let a=Object.create(null),o=0;for(let t of s.keys)a[t]=`key_${o++}`;for(let t of(r.write("const newResult = {}"),s.keys))if(s.optionalKeys.has(t)){let i=a[t];r.write(`const ${i} = ${n(t)};`);let s=a4(t);r.write(`
|
|
371
371
|
if (${i}.issues.length) {
|
|
372
372
|
if (input[${s}] === undefined) {
|
|
373
373
|
if (${s} in input) {
|
|
@@ -389,19 +389,19 @@ ${a}`));let o=0;for(;o<(t.maxAttempts??1/0);){o++;let r=await this._interface.se
|
|
|
389
389
|
`)}else{let i=a[t];r.write(`const ${i} = ${n(t)};`),r.write(`
|
|
390
390
|
if (${i}.issues.length) payload.issues = payload.issues.concat(${i}.issues.map(iss => ({
|
|
391
391
|
...iss,
|
|
392
|
-
path: iss.path ? [${
|
|
393
|
-
})));`),r.write(`newResult[${a2(t)}] = ${i}.value`)}r.write("payload.value = newResult;"),r.write("return payload;");let l=r.compile();return(r,i)=>l(t,r,i)})(r.shape)),p=s(p,u);else{p.value={};let t=l.shape;for(let r of l.keys){let i=t[r],s=i._zod.run({value:c[r],issues:[]},u),n="optional"===i._zod.optin&&"optional"===i._zod.optout;s instanceof Promise?d.push(s.then(t=>n?lQ(t,p,r,c):lZ(t,p,r))):n?lQ(s,p,r,c):lZ(s,p,r)}}if(!o)return d.length?Promise.all(d).then(()=>p):p;let h=[],f=l.keySet,m=o._zod,y=m.def.type;for(let t of Object.keys(c)){if(f.has(t))continue;if("never"===y){h.push(t);continue}let r=m.run({value:c[t],issues:[]},u);r instanceof Promise?d.push(r.then(r=>lZ(r,p,t))):lZ(r,p,t)}return(h.length&&p.issues.push({code:"unrecognized_keys",keys:h,input:c,inst:t}),d.length)?Promise.all(d).then(()=>p):p}});function l1(t,r,i,s){for(let i of t)if(0===i.issues.length)return r.value=i.value,r;return r.issues.push({code:"invalid_union",input:r.value,inst:i,errors:t.map(t=>t.issues.map(t=>og(t,s,aM())))}),r}var l2=aj("$ZodUnion",(t,r)=>{lb.init(t,r),aG(t._zod,"optin",()=>r.options.some(t=>"optional"===t._zod.optin)?"optional":void 0),aG(t._zod,"optout",()=>r.options.some(t=>"optional"===t._zod.optout)?"optional":void 0),aG(t._zod,"values",()=>{if(r.options.every(t=>t._zod.values))return new Set(r.options.flatMap(t=>Array.from(t._zod.values)))}),aG(t._zod,"pattern",()=>{if(r.options.every(t=>t._zod.pattern)){let t=r.options.map(t=>t._zod.pattern);return RegExp(`^(${t.map(t=>aY(t.source)).join("|")})$`)}}),t._zod.parse=(i,s)=>{let n=!1,a=[];for(let t of r.options){let r=t._zod.run({value:i.value,issues:[]},s);if(r instanceof Promise)a.push(r),n=!0;else{if(0===r.issues.length)return r;a.push(r)}}return n?Promise.all(a).then(r=>l1(r,i,t,s)):l1(a,i,t,s)}}),l4=aj("$ZodDiscriminatedUnion",(t,r)=>{l2.init(t,r);let i=t._zod.parse;aG(t._zod,"propValues",()=>{let t={};for(let i of r.options){let s=i._zod.propValues;if(!s||0===Object.keys(s).length)throw Error(`Invalid discriminated union option at index "${r.options.indexOf(i)}"`);for(let[r,i]of Object.entries(s))for(let s of(t[r]||(t[r]=new Set),i))t[r].add(s)}return t});let s=aH(()=>{let t=r.options,i=new Map;for(let s of t){let t=s._zod.propValues[r.discriminator];if(!t||0===t.size)throw Error(`Invalid discriminated union option at index "${r.options.indexOf(s)}"`);for(let r of t){if(i.has(r))throw Error(`Duplicate discriminator value "${String(r)}"`);i.set(r,s)}}return i});t._zod.parse=(n,a)=>{let o=n.value;if(!a3(o))return n.issues.push({code:"invalid_type",expected:"object",input:o,inst:t}),n;let l=s.value.get(o?.[r.discriminator]);return l?l._zod.run(n,a):r.unionFallback?i(n,a):(n.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:o,path:[r.discriminator],inst:t}),n)}}),l3=aj("$ZodIntersection",(t,r)=>{lb.init(t,r),t._zod.parse=(t,i)=>{let s=t.value,n=r.left._zod.run({value:s,issues:[]},i),a=r.right._zod.run({value:s,issues:[]},i);return n instanceof Promise||a instanceof Promise?Promise.all([n,a]).then(([r,i])=>l8(t,r,i)):l8(t,n,a)}});function l8(t,r,i){if(r.issues.length&&t.issues.push(...r.issues),i.issues.length&&t.issues.push(...i.issues),om(t))return t;let s=function t(r,i){if(r===i||r instanceof Date&&i instanceof Date&&+r==+i)return{valid:!0,data:r};if(a7(r)&&a7(i)){let s=Object.keys(i),n=Object.keys(r).filter(t=>-1!==s.indexOf(t)),a={...r,...i};for(let s of n){let n=t(r[s],i[s]);if(!n.valid)return{valid:!1,mergeErrorPath:[s,...n.mergeErrorPath]};a[s]=n.data}return{valid:!0,data:a}}if(Array.isArray(r)&&Array.isArray(i)){if(r.length!==i.length)return{valid:!1,mergeErrorPath:[]};let s=[];for(let n=0;n<r.length;n++){let a=t(r[n],i[n]);if(!a.valid)return{valid:!1,mergeErrorPath:[n,...a.mergeErrorPath]};s.push(a.data)}return{valid:!0,data:s}}return{valid:!1,mergeErrorPath:[]}}(r.value,i.value);if(!s.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(s.mergeErrorPath)}`);return t.value=s.data,t}var l7=aj("$ZodRecord",(t,r)=>{lb.init(t,r),t._zod.parse=(i,s)=>{let n=i.value;if(!a7(n))return i.issues.push({expected:"record",code:"invalid_type",input:n,inst:t}),i;let a=[];if(r.keyType._zod.values){let o,l=r.keyType._zod.values;for(let t of(i.value={},l))if("string"==typeof t||"number"==typeof t||"symbol"==typeof t){let o=r.valueType._zod.run({value:n[t],issues:[]},s);o instanceof Promise?a.push(o.then(r=>{r.issues.length&&i.issues.push(...oy(t,r.issues)),i.value[t]=r.value})):(o.issues.length&&i.issues.push(...oy(t,o.issues)),i.value[t]=o.value)}for(let t in n)l.has(t)||(o=o??[]).push(t);o&&o.length>0&&i.issues.push({code:"unrecognized_keys",input:n,inst:t,keys:o})}else for(let o of(i.value={},Reflect.ownKeys(n))){if("__proto__"===o)continue;let l=r.keyType._zod.run({value:o,issues:[]},s);if(l instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(l.issues.length){i.issues.push({origin:"record",code:"invalid_key",issues:l.issues.map(t=>og(t,s,aM())),input:o,path:[o],inst:t}),i.value[l.value]=l.value;continue}let p=r.valueType._zod.run({value:n[o],issues:[]},s);p instanceof Promise?a.push(p.then(t=>{t.issues.length&&i.issues.push(...oy(o,t.issues)),i.value[l.value]=t.value})):(p.issues.length&&i.issues.push(...oy(o,p.issues)),i.value[l.value]=p.value)}return a.length?Promise.all(a).then(()=>i):i}}),l9=aj("$ZodEnum",(t,r)=>{lb.init(t,r);let i=aq(r.entries);t._zod.values=new Set(i),t._zod.pattern=RegExp(`^(${i.filter(t=>a6.has(typeof t)).map(t=>"string"==typeof t?ot(t):t.toString()).join("|")})$`),t._zod.parse=(r,s)=>{let n=r.value;return t._zod.values.has(n)||r.issues.push({code:"invalid_value",values:i,input:n,inst:t}),r}}),l5=aj("$ZodLiteral",(t,r)=>{lb.init(t,r),t._zod.values=new Set(r.values),t._zod.pattern=RegExp(`^(${r.values.map(t=>"string"==typeof t?ot(t):t?t.toString():String(t)).join("|")})$`),t._zod.parse=(i,s)=>{let n=i.value;return t._zod.values.has(n)||i.issues.push({code:"invalid_value",values:r.values,input:n,inst:t}),i}}),l6=aj("$ZodTransform",(t,r)=>{lb.init(t,r),t._zod.parse=(t,i)=>{let s=r.transform(t.value,t);if(i.async)return(s instanceof Promise?s:Promise.resolve(s)).then(r=>(t.value=r,t));if(s instanceof Promise)throw new aL;return t.value=s,t}}),pe=aj("$ZodOptional",(t,r)=>{lb.init(t,r),t._zod.optin="optional",t._zod.optout="optional",aG(t._zod,"values",()=>r.innerType._zod.values?new Set([...r.innerType._zod.values,void 0]):void 0),aG(t._zod,"pattern",()=>{let t=r.innerType._zod.pattern;return t?RegExp(`^(${aY(t.source)})?$`):void 0}),t._zod.parse=(t,i)=>"optional"===r.innerType._zod.optin?r.innerType._zod.run(t,i):void 0===t.value?t:r.innerType._zod.run(t,i)}),pt=aj("$ZodNullable",(t,r)=>{lb.init(t,r),aG(t._zod,"optin",()=>r.innerType._zod.optin),aG(t._zod,"optout",()=>r.innerType._zod.optout),aG(t._zod,"pattern",()=>{let t=r.innerType._zod.pattern;return t?RegExp(`^(${aY(t.source)}|null)$`):void 0}),aG(t._zod,"values",()=>r.innerType._zod.values?new Set([...r.innerType._zod.values,null]):void 0),t._zod.parse=(t,i)=>null===t.value?t:r.innerType._zod.run(t,i)}),pr=aj("$ZodDefault",(t,r)=>{lb.init(t,r),t._zod.optin="optional",aG(t._zod,"values",()=>r.innerType._zod.values),t._zod.parse=(t,i)=>{if(void 0===t.value)return t.value=r.defaultValue,t;let s=r.innerType._zod.run(t,i);return s instanceof Promise?s.then(t=>pi(t,r)):pi(s,r)}});function pi(t,r){return void 0===t.value&&(t.value=r.defaultValue),t}var ps=aj("$ZodPrefault",(t,r)=>{lb.init(t,r),t._zod.optin="optional",aG(t._zod,"values",()=>r.innerType._zod.values),t._zod.parse=(t,i)=>(void 0===t.value&&(t.value=r.defaultValue),r.innerType._zod.run(t,i))}),pn=aj("$ZodNonOptional",(t,r)=>{lb.init(t,r),aG(t._zod,"values",()=>{let t=r.innerType._zod.values;return t?new Set([...t].filter(t=>void 0!==t)):void 0}),t._zod.parse=(i,s)=>{let n=r.innerType._zod.run(i,s);return n instanceof Promise?n.then(r=>pa(r,t)):pa(n,t)}});function pa(t,r){return t.issues.length||void 0!==t.value||t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:r}),t}var po=aj("$ZodCatch",(t,r)=>{lb.init(t,r),t._zod.optin="optional",aG(t._zod,"optout",()=>r.innerType._zod.optout),aG(t._zod,"values",()=>r.innerType._zod.values),t._zod.parse=(t,i)=>{let s=r.innerType._zod.run(t,i);return s instanceof Promise?s.then(s=>(t.value=s.value,s.issues.length&&(t.value=r.catchValue({...t,error:{issues:s.issues.map(t=>og(t,i,aM()))},input:t.value}),t.issues=[]),t)):(t.value=s.value,s.issues.length&&(t.value=r.catchValue({...t,error:{issues:s.issues.map(t=>og(t,i,aM()))},input:t.value}),t.issues=[]),t)}}),pl=aj("$ZodPipe",(t,r)=>{lb.init(t,r),aG(t._zod,"values",()=>r.in._zod.values),aG(t._zod,"optin",()=>r.in._zod.optin),aG(t._zod,"optout",()=>r.out._zod.optout),t._zod.parse=(t,i)=>{let s=r.in._zod.run(t,i);return s instanceof Promise?s.then(t=>pp(t,r,i)):pp(s,r,i)}});function pp(t,r,i){return om(t)?t:r.out._zod.run({value:t.value,issues:t.issues},i)}var pu=aj("$ZodReadonly",(t,r)=>{lb.init(t,r),aG(t._zod,"propValues",()=>r.innerType._zod.propValues),aG(t._zod,"values",()=>r.innerType._zod.values),aG(t._zod,"optin",()=>r.innerType._zod.optin),aG(t._zod,"optout",()=>r.innerType._zod.optout),t._zod.parse=(t,i)=>{let s=r.innerType._zod.run(t,i);return s instanceof Promise?s.then(pc):pc(s)}});function pc(t){return t.value=Object.freeze(t.value),t}var pd=aj("$ZodCustom",(t,r)=>{o5.init(t,r),lb.init(t,r),t._zod.parse=(t,r)=>t,t._zod.check=i=>{let s=i.value,n=r.fn(s);if(n instanceof Promise)return n.then(r=>ph(r,i,s,t));ph(n,i,s,t)}});function ph(t,r,i,s){if(!t){let t={code:"custom",input:i,inst:s,path:[...s._zod.def.path??[]],continue:!s._zod.def.abort};s._zod.def.params&&(t.params=s._zod.def.params),r.issues.push(oT(t))}}Symbol("ZodOutput"),Symbol("ZodInput");var pf=new class t{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...r){let i=r[0];if(this._map.set(t,i),i&&"object"==typeof i&&"id"in i){if(this._idmap.has(i.id))throw Error(`ID ${i.id} already exists in the registry`);this._idmap.set(i.id,t)}return this}remove(t){return this._map.delete(t),this}get(t){let r=t._zod.parent;if(r){let i={...this.get(r)??{}};return delete i.id,{...i,...this._map.get(t)}}return this._map.get(t)}has(t){return this._map.has(t)}};function pm(t,r){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...oi(r)})}function py(t,r){return new le({check:"less_than",...oi(r),value:t,inclusive:!1})}function pb(t,r){return new le({check:"less_than",...oi(r),value:t,inclusive:!0})}function pg(t,r){return new lt({check:"greater_than",...oi(r),value:t,inclusive:!1})}function pv(t,r){return new lt({check:"greater_than",...oi(r),value:t,inclusive:!0})}function px(t,r){return new lr({check:"multiple_of",...oi(r),value:t})}function pT(t,r){return new ls({check:"max_length",...oi(r),maximum:t})}function pE(t,r){return new ln({check:"min_length",...oi(r),minimum:t})}function pS(t,r){return new la({check:"length_equals",...oi(r),length:t})}function p_(t){return new lf({check:"overwrite",tx:t})}var pP=aj("ZodMiniType",(t,r)=>{if(!t._zod)throw Error("Uninitialized schema in ZodMiniType.");lb.init(t,r),t.def=r,t.parse=(r,i)=>oC(t,r,i,{callee:t.parse}),t.safeParse=(r,i)=>oO(t,r,i),t.parseAsync=async(r,i)=>ok(t,r,i,{callee:t.parseAsync}),t.safeParseAsync=async(r,i)=>oj(t,r,i),t.check=(...i)=>t.clone({...r,checks:[...r.checks??[],...i.map(t=>"function"==typeof t?{_zod:{check:t,def:{check:"custom"},onattach:[]}}:t)]}),t.clone=(r,i)=>or(t,r,i),t.brand=()=>t,t.register=(r,i)=>(r.add(t,i),t)});aj("ZodMiniObject",(t,r)=>{l0.init(t,r),pP.init(t,r),aF.defineLazy(t,"shape",()=>r.shape)});var pA={};ru(pA,{time:()=>pO,duration:()=>pj,datetime:()=>pC,date:()=>pk,ZodISOTime:()=>pN,ZodISODuration:()=>pD,ZodISODateTime:()=>pw,ZodISODate:()=>pI});var pw=aj("ZodISODateTime",(t,r)=>{lN.init(t,r),pz.init(t,r)});function pC(t){return new pw({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...oi(t)})}var pI=aj("ZodISODate",(t,r)=>{lO.init(t,r),pz.init(t,r)});function pk(t){return new pI({type:"string",format:"date",check:"string_format",...oi(t)})}var pN=aj("ZodISOTime",(t,r)=>{lD.init(t,r),pz.init(t,r)});function pO(t){return new pN({type:"string",format:"time",check:"string_format",precision:null,...oi(t)})}var pD=aj("ZodISODuration",(t,r)=>{lj.init(t,r),pz.init(t,r)});function pj(t){return new pD({type:"string",format:"duration",check:"string_format",...oi(t)})}var pL=(t,r)=>{oP.init(t,r),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>{let i,s,n;return i=r||function(t){return t.message},s={_errors:[]},(n=t=>{for(let r of t.issues)if("invalid_union"===r.code&&r.errors.length)r.errors.map(t=>n({issues:t}));else if("invalid_key"===r.code)n({issues:r.issues});else if("invalid_element"===r.code)n({issues:r.issues});else if(0===r.path.length)s._errors.push(i(r));else{let t=s,n=0;for(;n<r.path.length;){let s=r.path[n];n!==r.path.length-1?t[s]=t[s]||{_errors:[]}:(t[s]=t[s]||{_errors:[]},t[s]._errors.push(i(r))),t=t[s],n++}}})(t),s}},flatten:{value:r=>(function(t,r=t=>t.message){let i={},s=[];for(let n of t.issues)n.path.length>0?(i[n.path[0]]=i[n.path[0]]||[],i[n.path[0]].push(r(n))):s.push(r(n));return{formErrors:s,fieldErrors:i}})(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get:()=>0===t.issues.length}})},pR=(aj("ZodError",pL),aj("ZodError",pL,{Parent:Error})),pM=ow(pR),pF=oI(pR),pB=oN(pR),pU=oD(pR),p$=aj("ZodType",(t,r)=>(lb.init(t,r),t.def=r,Object.defineProperty(t,"_def",{value:r}),t.check=(...i)=>t.clone({...r,checks:[...r.checks??[],...i.map(t=>"function"==typeof t?{_zod:{check:t,def:{check:"custom"},onattach:[]}}:t)]}),t.clone=(r,i)=>or(t,r,i),t.brand=()=>t,t.register=(r,i)=>(r.add(t,i),t),t.parse=(r,i)=>pM(t,r,i,{callee:t.parse}),t.safeParse=(r,i)=>pB(t,r,i),t.parseAsync=async(r,i)=>pF(t,r,i,{callee:t.parseAsync}),t.safeParseAsync=async(r,i)=>pU(t,r,i),t.spa=t.safeParseAsync,t.refine=(r,i)=>t.check(function(t,r={}){return new uV({type:"custom",check:"custom",fn:t,...oi(r)})}(r,i)),t.superRefine=r=>t.check(function(t){var r;let i,s=(r=r=>(r.addIssue=t=>{"string"==typeof t?r.issues.push(aF.issue(t,r.value,s._zod.def)):(t.fatal&&(t.continue=!1),t.code??(t.code="custom"),t.input??(t.input=r.value),t.inst??(t.inst=s),t.continue??(t.continue=!s._zod.def.abort),r.issues.push(aF.issue(t)))},t(r.value,r)),(i=new o5({check:"custom",...aF.normalizeParams(void 0)}))._zod.check=r,i);return s}(r)),t.overwrite=r=>t.check(p_(r)),t.optional=()=>uO(t),t.nullable=()=>uj(t),t.nullish=()=>uO(uj(t)),t.nonoptional=r=>{var i,s;return i=t,s=r,new uM({type:"nonoptional",innerType:i,...aF.normalizeParams(s)})},t.array=()=>uh(t),t.or=r=>ug([t,r]),t.and=r=>uE(t,r),t.transform=r=>uU(t,uk(r)),t.default=r=>{var i,s;return i=t,s=r,new uL({type:"default",innerType:i,get defaultValue(){return"function"==typeof s?s():s}})},t.prefault=r=>{var i,s;return i=t,s=r,new uR({type:"prefault",innerType:i,get defaultValue(){return"function"==typeof s?s():s}})},t.catch=r=>{var i;return new uF({type:"catch",innerType:t,catchValue:"function"==typeof(i=r)?i:()=>i})},t.pipe=r=>uU(t,r),t.readonly=()=>new u$({type:"readonly",innerType:t}),t.describe=r=>{let i=t.clone();return pf.add(i,{description:r}),i},Object.defineProperty(t,"description",{get:()=>pf.get(t)?.description,configurable:!0}),t.meta=(...r)=>{if(0===r.length)return pf.get(t);let i=t.clone();return pf.add(i,r[0]),i},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),pV=aj("_ZodString",(t,r)=>{lg.init(t,r),p$.init(t,r);let i=t._zod.bag;t.format=i.format??null,t.minLength=i.minimum??null,t.maxLength=i.maximum??null,t.regex=(...r)=>t.check(function(t,r){return new ll({check:"string_format",format:"regex",...oi(r),pattern:t})}(...r)),t.includes=(...r)=>t.check(function(t,r){return new lc({check:"string_format",format:"includes",...oi(r),includes:t})}(...r)),t.startsWith=(...r)=>t.check(function(t,r){return new ld({check:"string_format",format:"starts_with",...oi(r),prefix:t})}(...r)),t.endsWith=(...r)=>t.check(function(t,r){return new lh({check:"string_format",format:"ends_with",...oi(r),suffix:t})}(...r)),t.min=(...r)=>t.check(pE(...r)),t.max=(...r)=>t.check(pT(...r)),t.length=(...r)=>t.check(pS(...r)),t.nonempty=(...r)=>t.check(pE(1,...r)),t.lowercase=r=>t.check(new lp({check:"string_format",format:"lowercase",...oi(r)})),t.uppercase=r=>t.check(new lu({check:"string_format",format:"uppercase",...oi(r)})),t.trim=()=>t.check(p_(t=>t.trim())),t.normalize=(...r)=>t.check(function(t){return p_(r=>r.normalize(t))}(...r)),t.toLowerCase=()=>t.check(p_(t=>t.toLowerCase())),t.toUpperCase=()=>t.check(p_(t=>t.toUpperCase()))}),pK=aj("ZodString",(t,r)=>{lg.init(t,r),pV.init(t,r),t.email=r=>t.check(new pW({type:"string",format:"email",check:"string_format",abort:!1,...oi(r)})),t.url=r=>t.check(new pY({type:"string",format:"url",check:"string_format",abort:!1,...oi(r)})),t.jwt=r=>t.check(new ue({type:"string",format:"jwt",check:"string_format",abort:!1,...oi(r)})),t.emoji=r=>t.check(new pX({type:"string",format:"emoji",check:"string_format",abort:!1,...oi(r)})),t.guid=r=>t.check(pm(pH,r)),t.uuid=r=>t.check(new pJ({type:"string",format:"uuid",check:"string_format",abort:!1,...oi(r)})),t.uuidv4=r=>t.check(new pJ({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...oi(r)})),t.uuidv6=r=>t.check(new pJ({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...oi(r)})),t.uuidv7=r=>t.check(new pJ({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...oi(r)})),t.nanoid=r=>t.check(new pG({type:"string",format:"nanoid",check:"string_format",abort:!1,...oi(r)})),t.guid=r=>t.check(pm(pH,r)),t.cuid=r=>t.check(new pZ({type:"string",format:"cuid",check:"string_format",abort:!1,...oi(r)})),t.cuid2=r=>t.check(new pQ({type:"string",format:"cuid2",check:"string_format",abort:!1,...oi(r)})),t.ulid=r=>t.check(new p0({type:"string",format:"ulid",check:"string_format",abort:!1,...oi(r)})),t.base64=r=>t.check(new p9({type:"string",format:"base64",check:"string_format",abort:!1,...oi(r)})),t.base64url=r=>t.check(new p5({type:"string",format:"base64url",check:"string_format",abort:!1,...oi(r)})),t.xid=r=>t.check(new p1({type:"string",format:"xid",check:"string_format",abort:!1,...oi(r)})),t.ksuid=r=>t.check(new p2({type:"string",format:"ksuid",check:"string_format",abort:!1,...oi(r)})),t.ipv4=r=>t.check(new p4({type:"string",format:"ipv4",check:"string_format",abort:!1,...oi(r)})),t.ipv6=r=>t.check(new p3({type:"string",format:"ipv6",check:"string_format",abort:!1,...oi(r)})),t.cidrv4=r=>t.check(new p8({type:"string",format:"cidrv4",check:"string_format",abort:!1,...oi(r)})),t.cidrv6=r=>t.check(new p7({type:"string",format:"cidrv6",check:"string_format",abort:!1,...oi(r)})),t.e164=r=>t.check(new p6({type:"string",format:"e164",check:"string_format",abort:!1,...oi(r)})),t.datetime=r=>t.check(pC(r)),t.date=r=>t.check(pk(r)),t.time=r=>t.check(pO(r)),t.duration=r=>t.check(pj(r))});function pq(t){return new pK({type:"string",...oi(t)})}var pz=aj("ZodStringFormat",(t,r)=>{lv.init(t,r),pV.init(t,r)}),pW=aj("ZodEmail",(t,r)=>{lE.init(t,r),pz.init(t,r)}),pH=aj("ZodGUID",(t,r)=>{lx.init(t,r),pz.init(t,r)}),pJ=aj("ZodUUID",(t,r)=>{lT.init(t,r),pz.init(t,r)}),pY=aj("ZodURL",(t,r)=>{lS.init(t,r),pz.init(t,r)}),pX=aj("ZodEmoji",(t,r)=>{l_.init(t,r),pz.init(t,r)}),pG=aj("ZodNanoID",(t,r)=>{lP.init(t,r),pz.init(t,r)}),pZ=aj("ZodCUID",(t,r)=>{lA.init(t,r),pz.init(t,r)}),pQ=aj("ZodCUID2",(t,r)=>{lw.init(t,r),pz.init(t,r)}),p0=aj("ZodULID",(t,r)=>{lC.init(t,r),pz.init(t,r)}),p1=aj("ZodXID",(t,r)=>{lI.init(t,r),pz.init(t,r)}),p2=aj("ZodKSUID",(t,r)=>{lk.init(t,r),pz.init(t,r)}),p4=aj("ZodIPv4",(t,r)=>{lL.init(t,r),pz.init(t,r)}),p3=aj("ZodIPv6",(t,r)=>{lR.init(t,r),pz.init(t,r)}),p8=aj("ZodCIDRv4",(t,r)=>{lM.init(t,r),pz.init(t,r)}),p7=aj("ZodCIDRv6",(t,r)=>{lF.init(t,r),pz.init(t,r)}),p9=aj("ZodBase64",(t,r)=>{lU.init(t,r),pz.init(t,r)}),p5=aj("ZodBase64URL",(t,r)=>{l$.init(t,r),pz.init(t,r)}),p6=aj("ZodE164",(t,r)=>{lV.init(t,r),pz.init(t,r)}),ue=aj("ZodJWT",(t,r)=>{lK.init(t,r),pz.init(t,r)}),ut=aj("ZodNumber",(t,r)=>{lq.init(t,r),p$.init(t,r),t.gt=(r,i)=>t.check(pg(r,i)),t.gte=(r,i)=>t.check(pv(r,i)),t.min=(r,i)=>t.check(pv(r,i)),t.lt=(r,i)=>t.check(py(r,i)),t.lte=(r,i)=>t.check(pb(r,i)),t.max=(r,i)=>t.check(pb(r,i)),t.int=r=>t.check(us(r)),t.safe=r=>t.check(us(r)),t.positive=r=>t.check(pg(0,r)),t.nonnegative=r=>t.check(pv(0,r)),t.negative=r=>t.check(py(0,r)),t.nonpositive=r=>t.check(pb(0,r)),t.multipleOf=(r,i)=>t.check(px(r,i)),t.step=(r,i)=>t.check(px(r,i)),t.finite=()=>t;let i=t._zod.bag;t.minValue=Math.max(i.minimum??-1/0,i.exclusiveMinimum??-1/0)??null,t.maxValue=Math.min(i.maximum??1/0,i.exclusiveMaximum??1/0)??null,t.isInt=(i.format??"").includes("int")||Number.isSafeInteger(i.multipleOf??.5),t.isFinite=!0,t.format=i.format??null});function ur(t){return new ut({type:"number",checks:[],...oi(t)})}var ui=aj("ZodNumberFormat",(t,r)=>{lz.init(t,r),ut.init(t,r)});function us(t){return new ui({type:"number",check:"number_format",abort:!1,format:"safeint",...oi(t)})}var un=aj("ZodBoolean",(t,r)=>{lW.init(t,r),p$.init(t,r)});function ua(t){return new un({type:"boolean",...oi(t)})}var uo=aj("ZodNull",(t,r)=>{lH.init(t,r),p$.init(t,r)});function ul(t){return new uo({type:"null",...oi(t)})}var up=aj("ZodUnknown",(t,r)=>{lJ.init(t,r),p$.init(t,r)});function uu(){return new up({type:"unknown"})}var uc=aj("ZodNever",(t,r)=>{lY.init(t,r),p$.init(t,r)}),ud=aj("ZodArray",(t,r)=>{lG.init(t,r),p$.init(t,r),t.element=r.element,t.min=(r,i)=>t.check(pE(r,i)),t.nonempty=r=>t.check(pE(1,r)),t.max=(r,i)=>t.check(pT(r,i)),t.length=(r,i)=>t.check(pS(r,i)),t.unwrap=()=>t.element});function uh(t,r){return new ud({type:"array",element:t,...oi(r)})}var uf=aj("ZodObject",(t,r)=>{l0.init(t,r),p$.init(t,r),aF.defineLazy(t,"shape",()=>r.shape),t.keyof=()=>uA(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:uu()}),t.loose=()=>t.clone({...t._zod.def,catchall:uu()}),t.strict=()=>t.clone({...t._zod.def,catchall:new uc({type:"never",...oi(void 0)})}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>aF.extend(t,r),t.merge=r=>aF.merge(t,r),t.pick=r=>aF.pick(t,r),t.omit=r=>aF.omit(t,r),t.partial=(...r)=>aF.partial(uN,t,r[0]),t.required=(...r)=>aF.required(uM,t,r[0])});function um(t,r){return new uf({type:"object",get shape(){return aF.assignProp(this,"shape",{...t}),this.shape},...aF.normalizeParams(r)})}function uy(t,r){return new uf({type:"object",get shape(){return aF.assignProp(this,"shape",{...t}),this.shape},catchall:uu(),...aF.normalizeParams(r)})}var ub=aj("ZodUnion",(t,r)=>{l2.init(t,r),p$.init(t,r),t.options=r.options});function ug(t,r){return new ub({type:"union",options:t,...aF.normalizeParams(r)})}var uv=aj("ZodDiscriminatedUnion",(t,r)=>{ub.init(t,r),l4.init(t,r)});function ux(t,r,i){return new uv({type:"union",options:r,discriminator:t,...aF.normalizeParams(i)})}var uT=aj("ZodIntersection",(t,r)=>{l3.init(t,r),p$.init(t,r)});function uE(t,r){return new uT({type:"intersection",left:t,right:r})}var uS=aj("ZodRecord",(t,r)=>{l7.init(t,r),p$.init(t,r),t.keyType=r.keyType,t.valueType=r.valueType});function u_(t,r,i){return new uS({type:"record",keyType:t,valueType:r,...aF.normalizeParams(i)})}var uP=aj("ZodEnum",(t,r)=>{l9.init(t,r),p$.init(t,r),t.enum=r.entries,t.options=Object.values(r.entries);let i=new Set(Object.keys(r.entries));t.extract=(t,s)=>{let n={};for(let s of t)if(i.has(s))n[s]=r.entries[s];else throw Error(`Key ${s} not found in enum`);return new uP({...r,checks:[],...aF.normalizeParams(s),entries:n})},t.exclude=(t,s)=>{let n={...r.entries};for(let r of t)if(i.has(r))delete n[r];else throw Error(`Key ${r} not found in enum`);return new uP({...r,checks:[],...aF.normalizeParams(s),entries:n})}});function uA(t,r){return new uP({type:"enum",entries:Array.isArray(t)?Object.fromEntries(t.map(t=>[t,t])):t,...aF.normalizeParams(r)})}var uw=aj("ZodLiteral",(t,r)=>{l5.init(t,r),p$.init(t,r),t.values=new Set(r.values),Object.defineProperty(t,"value",{get(){if(r.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return r.values[0]}})});function uC(t,r){return new uw({type:"literal",values:Array.isArray(t)?t:[t],...aF.normalizeParams(r)})}var uI=aj("ZodTransform",(t,r)=>{l6.init(t,r),p$.init(t,r),t._zod.parse=(i,s)=>{i.addIssue=s=>{"string"==typeof s?i.issues.push(aF.issue(s,i.value,r)):(s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=i.value),s.inst??(s.inst=t),s.continue??(s.continue=!0),i.issues.push(aF.issue(s)))};let n=r.transform(i.value,i);return n instanceof Promise?n.then(t=>(i.value=t,i)):(i.value=n,i)}});function uk(t){return new uI({type:"transform",transform:t})}var uN=aj("ZodOptional",(t,r)=>{pe.init(t,r),p$.init(t,r),t.unwrap=()=>t._zod.def.innerType});function uO(t){return new uN({type:"optional",innerType:t})}var uD=aj("ZodNullable",(t,r)=>{pt.init(t,r),p$.init(t,r),t.unwrap=()=>t._zod.def.innerType});function uj(t){return new uD({type:"nullable",innerType:t})}var uL=aj("ZodDefault",(t,r)=>{pr.init(t,r),p$.init(t,r),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap}),uR=aj("ZodPrefault",(t,r)=>{ps.init(t,r),p$.init(t,r),t.unwrap=()=>t._zod.def.innerType}),uM=aj("ZodNonOptional",(t,r)=>{pn.init(t,r),p$.init(t,r),t.unwrap=()=>t._zod.def.innerType}),uF=aj("ZodCatch",(t,r)=>{po.init(t,r),p$.init(t,r),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap}),uB=aj("ZodPipe",(t,r)=>{pl.init(t,r),p$.init(t,r),t.in=r.in,t.out=r.out});function uU(t,r){return new uB({type:"pipe",in:t,out:r})}var u$=aj("ZodReadonly",(t,r)=>{pu.init(t,r),p$.init(t,r)}),uV=aj("ZodCustom",(t,r)=>{pd.init(t,r),p$.init(t,r)});aM({localeError:(l={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}},p={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},t=>{switch(t.code){case"invalid_type":return`Invalid input: expected ${t.expected}, received ${(t=>{let r=typeof t;switch(r){case"number":return Number.isNaN(t)?"NaN":"number";case"object":if(Array.isArray(t))return"array";if(null===t)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}return r})(t.input)}`;case"invalid_value":if(1===t.values.length)return`Invalid input: expected ${on(t.values[0])}`;return`Invalid option: expected one of ${az(t.values,"|")}`;case"too_big":{let r=t.inclusive?"<=":"<",i=l[t.origin]??null;if(i)return`Too big: expected ${t.origin??"value"} to have ${r}${t.maximum.toString()} ${i.unit??"elements"}`;return`Too big: expected ${t.origin??"value"} to be ${r}${t.maximum.toString()}`}case"too_small":{let r=t.inclusive?">=":">",i=l[t.origin]??null;if(i)return`Too small: expected ${t.origin} to have ${r}${t.minimum.toString()} ${i.unit}`;return`Too small: expected ${t.origin} to be ${r}${t.minimum.toString()}`}case"invalid_format":if("starts_with"===t.format)return`Invalid string: must start with "${t.prefix}"`;if("ends_with"===t.format)return`Invalid string: must end with "${t.suffix}"`;if("includes"===t.format)return`Invalid string: must include "${t.includes}"`;if("regex"===t.format)return`Invalid string: must match pattern ${t.pattern}`;return`Invalid ${p[t.format]??t.format}`;case"not_multiple_of":return`Invalid number: must be a multiple of ${t.divisor}`;case"unrecognized_keys":return`Unrecognized key${t.keys.length>1?"s":""}: ${az(t.keys,", ")}`;case"invalid_key":return`Invalid key in ${t.origin}`;case"invalid_union":default:return"Invalid input";case"invalid_element":return`Invalid value in ${t.origin}`}})});var uK=(c=(t=>null!==t&&("object"==typeof t||"function"==typeof t))??(()=>!0),(o=oi(void 0)).abort??(o.abort=!0),new uV({type:"custom",check:"custom",fn:c,...o})),uq=ug([pq(),ur().int()]),uz=pq(),uW=(uy({ttl:ug([ur(),ul()]).optional(),pollInterval:ur().optional()}),um({ttl:ur().optional()})),uH=um({taskId:pq()}),uJ=uy({progressToken:uq.optional(),"io.modelcontextprotocol/related-task":uH.optional()}),uY=um({_meta:uJ.optional()}),uX=uY.extend({task:uW.optional()}),uG=um({method:pq(),params:uY.loose().optional()}),uZ=um({_meta:uJ.optional()}),uQ=um({method:pq(),params:uZ.loose().optional()}),u0=uy({_meta:uJ.optional()}),u1=ug([pq(),ur().int()]),u2=um({jsonrpc:uC("2.0"),id:u1,...uG.shape}).strict(),u4=um({jsonrpc:uC("2.0"),...uQ.shape}).strict(),u3=um({jsonrpc:uC("2.0"),id:u1,result:u0}).strict();(d=b||(b={}))[d.ConnectionClosed=-32e3]="ConnectionClosed",d[d.RequestTimeout=-32001]="RequestTimeout",d[d.ParseError=-32700]="ParseError",d[d.InvalidRequest=-32600]="InvalidRequest",d[d.MethodNotFound=-32601]="MethodNotFound",d[d.InvalidParams=-32602]="InvalidParams",d[d.InternalError=-32603]="InternalError",d[d.UrlElicitationRequired=-32042]="UrlElicitationRequired";var u8=um({jsonrpc:uC("2.0"),id:u1.optional(),error:um({code:ur().int(),message:pq(),data:uu().optional()})}).strict();ug([u2,u4,u3,u8]),ug([u3,u8]);var u7=u0.strict(),u9=uZ.extend({requestId:u1.optional(),reason:pq().optional()}),u5=uQ.extend({method:uC("notifications/cancelled"),params:u9}),u6=um({src:pq(),mimeType:pq().optional(),sizes:uh(pq()).optional(),theme:uA(["light","dark"]).optional()}),ce=um({icons:uh(u6).optional()}),ct=um({name:pq(),title:pq().optional()}),cr=ct.extend({...ct.shape,...ce.shape,version:pq(),websiteUrl:pq().optional(),description:pq().optional()}),ci=uE(um({applyDefaults:ua().optional()}),u_(pq(),uu())),cs=(h=t=>t&&"object"==typeof t&&!Array.isArray(t)&&0===Object.keys(t).length?{form:{}}:t,f=uE(um({form:ci.optional(),url:uK.optional()}),u_(pq(),uu()).optional()),uU(uk(h),f)),cn=uy({list:uK.optional(),cancel:uK.optional(),requests:uy({sampling:uy({createMessage:uK.optional()}).optional(),elicitation:uy({create:uK.optional()}).optional()}).optional()}),ca=uy({list:uK.optional(),cancel:uK.optional(),requests:uy({tools:uy({call:uK.optional()}).optional()}).optional()}),co=um({experimental:u_(pq(),uK).optional(),sampling:um({context:uK.optional(),tools:uK.optional()}).optional(),elicitation:cs.optional(),roots:um({listChanged:ua().optional()}).optional(),tasks:cn.optional()}),cl=uY.extend({protocolVersion:pq(),capabilities:co,clientInfo:cr}),cp=uG.extend({method:uC("initialize"),params:cl}),cu=um({experimental:u_(pq(),uK).optional(),logging:uK.optional(),completions:uK.optional(),prompts:um({listChanged:ua().optional()}).optional(),resources:um({subscribe:ua().optional(),listChanged:ua().optional()}).optional(),tools:um({listChanged:ua().optional()}).optional(),tasks:ca.optional()}),cc=u0.extend({protocolVersion:pq(),capabilities:cu,serverInfo:cr,instructions:pq().optional()}),cd=uQ.extend({method:uC("notifications/initialized"),params:uZ.optional()}),ch=uG.extend({method:uC("ping"),params:uY.optional()}),cf=um({progress:ur(),total:uO(ur()),message:uO(pq())}),cm=um({...uZ.shape,...cf.shape,progressToken:uq}),cy=uQ.extend({method:uC("notifications/progress"),params:cm}),cb=uY.extend({cursor:uz.optional()}),cg=uG.extend({params:cb.optional()}),cv=u0.extend({nextCursor:uz.optional()}),cx=uA(["working","input_required","completed","failed","cancelled"]),cT=um({taskId:pq(),status:cx,ttl:ug([ur(),ul()]),createdAt:pq(),lastUpdatedAt:pq(),pollInterval:uO(ur()),statusMessage:uO(pq())}),cE=u0.extend({task:cT}),cS=uZ.merge(cT),c_=uQ.extend({method:uC("notifications/tasks/status"),params:cS}),cP=uG.extend({method:uC("tasks/get"),params:uY.extend({taskId:pq()})}),cA=u0.merge(cT),cw=uG.extend({method:uC("tasks/result"),params:uY.extend({taskId:pq()})}),cC=(u0.loose(),cg.extend({method:uC("tasks/list")})),cI=cv.extend({tasks:uh(cT)}),ck=uG.extend({method:uC("tasks/cancel"),params:uY.extend({taskId:pq()})}),cN=(u0.merge(cT),um({uri:pq(),mimeType:uO(pq()),_meta:u_(pq(),uu()).optional()})),cO=cN.extend({text:pq()}),cD=pq().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),cj=cN.extend({blob:cD}),cL=uA(["user","assistant"]),cR=um({audience:uh(cL).optional(),priority:ur().min(0).max(1).optional(),lastModified:pA.datetime({offset:!0}).optional()}),cM=um({...ct.shape,...ce.shape,uri:pq(),description:uO(pq()),mimeType:uO(pq()),annotations:cR.optional(),_meta:uO(uy({}))}),cF=um({...ct.shape,...ce.shape,uriTemplate:pq(),description:uO(pq()),mimeType:uO(pq()),annotations:cR.optional(),_meta:uO(uy({}))}),cB=cg.extend({method:uC("resources/list")}),cU=cv.extend({resources:uh(cM)}),c$=cg.extend({method:uC("resources/templates/list")}),cV=cv.extend({resourceTemplates:uh(cF)}),cK=uY.extend({uri:pq()}),cq=uG.extend({method:uC("resources/read"),params:cK}),cz=u0.extend({contents:uh(ug([cO,cj]))}),cW=uQ.extend({method:uC("notifications/resources/list_changed"),params:uZ.optional()}),cH=uG.extend({method:uC("resources/subscribe"),params:cK}),cJ=uG.extend({method:uC("resources/unsubscribe"),params:cK}),cY=uZ.extend({uri:pq()}),cX=uQ.extend({method:uC("notifications/resources/updated"),params:cY}),cG=um({name:pq(),description:uO(pq()),required:uO(ua())}),cZ=um({...ct.shape,...ce.shape,description:uO(pq()),arguments:uO(uh(cG)),_meta:uO(uy({}))}),cQ=cg.extend({method:uC("prompts/list")}),c0=cv.extend({prompts:uh(cZ)}),c1=uY.extend({name:pq(),arguments:u_(pq(),pq()).optional()}),c2=uG.extend({method:uC("prompts/get"),params:c1}),c4=um({type:uC("text"),text:pq(),annotations:cR.optional(),_meta:u_(pq(),uu()).optional()}),c3=um({type:uC("image"),data:cD,mimeType:pq(),annotations:cR.optional(),_meta:u_(pq(),uu()).optional()}),c8=um({type:uC("audio"),data:cD,mimeType:pq(),annotations:cR.optional(),_meta:u_(pq(),uu()).optional()}),c7=um({type:uC("tool_use"),name:pq(),id:pq(),input:u_(pq(),uu()),_meta:u_(pq(),uu()).optional()}),c9=um({type:uC("resource"),resource:ug([cO,cj]),annotations:cR.optional(),_meta:u_(pq(),uu()).optional()}),c5=ug([c4,c3,c8,cM.extend({type:uC("resource_link")}),c9]),c6=um({role:cL,content:c5}),de=u0.extend({description:pq().optional(),messages:uh(c6)}),dt=uQ.extend({method:uC("notifications/prompts/list_changed"),params:uZ.optional()}),dr=um({title:pq().optional(),readOnlyHint:ua().optional(),destructiveHint:ua().optional(),idempotentHint:ua().optional(),openWorldHint:ua().optional()}),di=um({taskSupport:uA(["required","optional","forbidden"]).optional()}),ds=um({...ct.shape,...ce.shape,description:pq().optional(),inputSchema:um({type:uC("object"),properties:u_(pq(),uK).optional(),required:uh(pq()).optional()}).catchall(uu()),outputSchema:um({type:uC("object"),properties:u_(pq(),uK).optional(),required:uh(pq()).optional()}).catchall(uu()).optional(),annotations:dr.optional(),execution:di.optional(),_meta:u_(pq(),uu()).optional()}),dn=cg.extend({method:uC("tools/list")}),da=cv.extend({tools:uh(ds)}),dl=u0.extend({content:uh(c5).default([]),structuredContent:u_(pq(),uu()).optional(),isError:ua().optional()}),dp=(dl.or(u0.extend({toolResult:uu()})),uX.extend({name:pq(),arguments:u_(pq(),uu()).optional()})),du=uG.extend({method:uC("tools/call"),params:dp}),dc=uQ.extend({method:uC("notifications/tools/list_changed"),params:uZ.optional()}),dd=(um({autoRefresh:ua().default(!0),debounceMs:ur().int().nonnegative().default(300)}),uA(["debug","info","notice","warning","error","critical","alert","emergency"])),dh=uY.extend({level:dd}),df=uG.extend({method:uC("logging/setLevel"),params:dh}),dm=uZ.extend({level:dd,logger:pq().optional(),data:uu()}),dy=uQ.extend({method:uC("notifications/message"),params:dm}),db=um({name:pq().optional()}),dg=um({hints:uh(db).optional(),costPriority:ur().min(0).max(1).optional(),speedPriority:ur().min(0).max(1).optional(),intelligencePriority:ur().min(0).max(1).optional()}),dv=um({mode:uA(["auto","required","none"]).optional()}),dx=um({type:uC("tool_result"),toolUseId:pq().describe("The unique identifier for the corresponding tool call."),content:uh(c5).default([]),structuredContent:um({}).loose().optional(),isError:ua().optional(),_meta:u_(pq(),uu()).optional()}),dT=ux("type",[c4,c3,c8]),dE=ux("type",[c4,c3,c8,c7,dx]),dS=um({role:cL,content:ug([dE,uh(dE)]),_meta:u_(pq(),uu()).optional()}),d_=uX.extend({messages:uh(dS),modelPreferences:dg.optional(),systemPrompt:pq().optional(),includeContext:uA(["none","thisServer","allServers"]).optional(),temperature:ur().optional(),maxTokens:ur().int(),stopSequences:uh(pq()).optional(),metadata:uK.optional(),tools:uh(ds).optional(),toolChoice:dv.optional()}),dP=uG.extend({method:uC("sampling/createMessage"),params:d_}),dA=u0.extend({model:pq(),stopReason:uO(uA(["endTurn","stopSequence","maxTokens"]).or(pq())),role:cL,content:dT}),dw=u0.extend({model:pq(),stopReason:uO(uA(["endTurn","stopSequence","maxTokens","toolUse"]).or(pq())),role:cL,content:ug([dE,uh(dE)])}),dC=um({type:uC("boolean"),title:pq().optional(),description:pq().optional(),default:ua().optional()}),dI=um({type:uC("string"),title:pq().optional(),description:pq().optional(),minLength:ur().optional(),maxLength:ur().optional(),format:uA(["email","uri","date","date-time"]).optional(),default:pq().optional()}),dk=um({type:uA(["number","integer"]),title:pq().optional(),description:pq().optional(),minimum:ur().optional(),maximum:ur().optional(),default:ur().optional()}),dN=um({type:uC("string"),title:pq().optional(),description:pq().optional(),enum:uh(pq()),default:pq().optional()}),dO=um({type:uC("string"),title:pq().optional(),description:pq().optional(),oneOf:uh(um({const:pq(),title:pq()})),default:pq().optional()}),dD=um({type:uC("string"),title:pq().optional(),description:pq().optional(),enum:uh(pq()),enumNames:uh(pq()).optional(),default:pq().optional()}),dj=ug([dN,dO]),dL=ug([um({type:uC("array"),title:pq().optional(),description:pq().optional(),minItems:ur().optional(),maxItems:ur().optional(),items:um({type:uC("string"),enum:uh(pq())}),default:uh(pq()).optional()}),um({type:uC("array"),title:pq().optional(),description:pq().optional(),minItems:ur().optional(),maxItems:ur().optional(),items:um({anyOf:uh(um({const:pq(),title:pq()}))}),default:uh(pq()).optional()})]),dR=ug([dD,dj,dL]),dM=ug([dR,dC,dI,dk]),dF=ug([uX.extend({mode:uC("form").optional(),message:pq(),requestedSchema:um({type:uC("object"),properties:u_(pq(),dM),required:uh(pq()).optional()})}),uX.extend({mode:uC("url"),message:pq(),elicitationId:pq(),url:pq().url()})]),dB=uG.extend({method:uC("elicitation/create"),params:dF}),dU=uZ.extend({elicitationId:pq()}),d$=uQ.extend({method:uC("notifications/elicitation/complete"),params:dU}),dV=u0.extend({action:uA(["accept","decline","cancel"]),content:(m=t=>null===t?void 0:t,y=u_(pq(),ug([pq(),ur(),ua(),uh(pq())])).optional(),uU(uk(m),y))}),dK=um({type:uC("ref/resource"),uri:pq()}),dq=um({type:uC("ref/prompt"),name:pq()}),dz=uY.extend({ref:ug([dq,dK]),argument:um({name:pq(),value:pq()}),context:um({arguments:u_(pq(),pq()).optional()}).optional()}),dW=uG.extend({method:uC("completion/complete"),params:dz}),dH=u0.extend({completion:uy({values:uh(pq()).max(100),total:uO(ur().int()),hasMore:uO(ua())})}),dJ=um({uri:pq().startsWith("file://"),name:pq().optional(),_meta:u_(pq(),uu()).optional()}),dY=uG.extend({method:uC("roots/list"),params:uY.optional()}),dX=u0.extend({roots:uh(dJ)}),dG=uQ.extend({method:uC("notifications/roots/list_changed"),params:uZ.optional()});ug([ch,cp,dW,df,c2,cQ,cB,c$,cq,cH,cJ,du,dn,cP,cw,cC,ck]),ug([u5,cy,cd,dG,c_]),ug([u7,dA,dw,dV,dX,cA,cI,cE]),ug([ch,dP,dB,dY,cP,cw,cC,ck]),ug([u5,cy,dy,cX,cW,dc,dt,c_,d$]),ug([u7,cc,dH,de,c0,cU,cV,cz,dl,da,cA,cI,cE]);class dZ extends Error{constructor(t,r,i){super(`MCP error ${t}: ${r}`),this.code=t,this.data=i,this.name="McpError"}static fromError(t,r,i){return t===b.UrlElicitationRequired&&i&&i.elicitations?new dQ(i.elicitations,r):new dZ(t,r,i)}}class dQ extends dZ{constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(b.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}}var d0=Symbol("Let zodToJsonSchema decide on which parser to use");function d1(t,r,i,s){s?.errorMessages&&i&&(t.errorMessage={...t.errorMessage,[r]:i})}function d2(t,r,i,s,n){t[r]=i,d1(t,r,s,n)}var d4=(t,r)=>{let i=0;for(;i<t.length&&i<r.length&&t[i]===r[i];i++);return[(t.length-i).toString(),...r.slice(i)].join("/")};function d3(t){if("openAi"!==t.target)return{};let r=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:"relative"===t.$refStrategy?d4(r,t.currentPath):r.join("/")}}function d8(t,r){return hb(t.type._def,r)}var d7=void 0,d9=/^[cC][^\s-]{8,}$/,d5=/^[0-9a-z]+$/,d6=/^[0-9A-HJKMNP-TV-Z]{26}$/,he=/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,ht=()=>(void 0===d7&&(d7=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),d7),hr=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,hi=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,hs=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,hn=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ha=/^[a-zA-Z0-9_-]{21}$/,ho=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;function hl(t,r){let i={type:"string"};if(t.checks)for(let s of t.checks)switch(s.kind){case"min":d2(i,"minLength","number"==typeof i.minLength?Math.max(i.minLength,s.value):s.value,s.message,r);break;case"max":d2(i,"maxLength","number"==typeof i.maxLength?Math.min(i.maxLength,s.value):s.value,s.message,r);break;case"email":switch(r.emailStrategy){case"format:email":hc(i,"email",s.message,r);break;case"format:idn-email":hc(i,"idn-email",s.message,r);break;case"pattern:zod":hd(i,he,s.message,r)}break;case"url":hc(i,"uri",s.message,r);break;case"uuid":hc(i,"uuid",s.message,r);break;case"regex":hd(i,s.regex,s.message,r);break;case"cuid":hd(i,d9,s.message,r);break;case"cuid2":hd(i,d5,s.message,r);break;case"startsWith":hd(i,RegExp(`^${hp(s.value,r)}`),s.message,r);break;case"endsWith":hd(i,RegExp(`${hp(s.value,r)}$`),s.message,r);break;case"datetime":hc(i,"date-time",s.message,r);break;case"date":hc(i,"date",s.message,r);break;case"time":hc(i,"time",s.message,r);break;case"duration":hc(i,"duration",s.message,r);break;case"length":d2(i,"minLength","number"==typeof i.minLength?Math.max(i.minLength,s.value):s.value,s.message,r),d2(i,"maxLength","number"==typeof i.maxLength?Math.min(i.maxLength,s.value):s.value,s.message,r);break;case"includes":hd(i,RegExp(hp(s.value,r)),s.message,r);break;case"ip":"v6"!==s.version&&hc(i,"ipv4",s.message,r),"v4"!==s.version&&hc(i,"ipv6",s.message,r);break;case"base64url":hd(i,hn,s.message,r);break;case"jwt":hd(i,ho,s.message,r);break;case"cidr":"v6"!==s.version&&hd(i,hr,s.message,r),"v4"!==s.version&&hd(i,hi,s.message,r);break;case"emoji":hd(i,ht(),s.message,r);break;case"ulid":hd(i,d6,s.message,r);break;case"base64":switch(r.base64Strategy){case"format:binary":hc(i,"binary",s.message,r);break;case"contentEncoding:base64":d2(i,"contentEncoding","base64",s.message,r);break;case"pattern:zod":hd(i,hs,s.message,r)}break;case"nanoid":hd(i,ha,s.message,r)}return i}function hp(t,r){return"escape"===r.patternStrategy?function(t){let r="";for(let i=0;i<t.length;i++)hu.has(t[i])||(r+="\\"),r+=t[i];return r}(t):t}var hu=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function hc(t,r,i,s){t.format||t.anyOf?.some(t=>t.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&s.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,0===Object.keys(t.errorMessage).length))&&delete t.errorMessage,t.anyOf.push({format:r,...i&&s.errorMessages&&{errorMessage:{format:i}}})):d2(t,"format",r,i,s)}function hd(t,r,i,s){t.pattern||t.allOf?.some(t=>t.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&s.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,0===Object.keys(t.errorMessage).length))&&delete t.errorMessage,t.allOf.push({pattern:hh(r,s),...i&&s.errorMessages&&{errorMessage:{pattern:i}}})):d2(t,"pattern",hh(r,s),i,s)}function hh(t,r){if(!r.applyRegexFlags||!t.flags)return t.source;let i={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},s=i.i?t.source.toLowerCase():t.source,n="",a=!1,o=!1,l=!1;for(let t=0;t<s.length;t++){if(a){n+=s[t],a=!1;continue}if(i.i){if(o){if(s[t].match(/[a-z]/)){l?(n+=s[t],n+=`${s[t-2]}-${s[t]}`.toUpperCase(),l=!1):"-"===s[t+1]&&s[t+2]?.match(/[a-z]/)?(n+=s[t],l=!0):n+=`${s[t]}${s[t].toUpperCase()}`;continue}}else if(s[t].match(/[a-z]/)){n+=`[${s[t]}${s[t].toUpperCase()}]`;continue}}if(i.m){if("^"===s[t]){n+=`(^|(?<=[\r
|
|
392
|
+
path: iss.path ? [${a4(t)}, ...iss.path] : [${a4(t)}]
|
|
393
|
+
})));`),r.write(`newResult[${a4(t)}] = ${i}.value`)}r.write("payload.value = newResult;"),r.write("return payload;");let l=r.compile();return(r,i)=>l(t,r,i)})(r.shape)),p=s(p,u);else{p.value={};let t=l.shape;for(let r of l.keys){let i=t[r],s=i._zod.run({value:c[r],issues:[]},u),n="optional"===i._zod.optin&&"optional"===i._zod.optout;s instanceof Promise?d.push(s.then(t=>n?l0(t,p,r,c):lQ(t,p,r))):n?l0(s,p,r,c):lQ(s,p,r)}}if(!o)return d.length?Promise.all(d).then(()=>p):p;let h=[],f=l.keySet,m=o._zod,y=m.def.type;for(let t of Object.keys(c)){if(f.has(t))continue;if("never"===y){h.push(t);continue}let r=m.run({value:c[t],issues:[]},u);r instanceof Promise?d.push(r.then(r=>lQ(r,p,t))):lQ(r,p,t)}return(h.length&&p.issues.push({code:"unrecognized_keys",keys:h,input:c,inst:t}),d.length)?Promise.all(d).then(()=>p):p}});function l2(t,r,i,s){for(let i of t)if(0===i.issues.length)return r.value=i.value,r;return r.issues.push({code:"invalid_union",input:r.value,inst:i,errors:t.map(t=>t.issues.map(t=>ov(t,s,aF())))}),r}var l4=aL("$ZodUnion",(t,r)=>{lg.init(t,r),aZ(t._zod,"optin",()=>r.options.some(t=>"optional"===t._zod.optin)?"optional":void 0),aZ(t._zod,"optout",()=>r.options.some(t=>"optional"===t._zod.optout)?"optional":void 0),aZ(t._zod,"values",()=>{if(r.options.every(t=>t._zod.values))return new Set(r.options.flatMap(t=>Array.from(t._zod.values)))}),aZ(t._zod,"pattern",()=>{if(r.options.every(t=>t._zod.pattern)){let t=r.options.map(t=>t._zod.pattern);return RegExp(`^(${t.map(t=>aX(t.source)).join("|")})$`)}}),t._zod.parse=(i,s)=>{let n=!1,a=[];for(let t of r.options){let r=t._zod.run({value:i.value,issues:[]},s);if(r instanceof Promise)a.push(r),n=!0;else{if(0===r.issues.length)return r;a.push(r)}}return n?Promise.all(a).then(r=>l2(r,i,t,s)):l2(a,i,t,s)}}),l3=aL("$ZodDiscriminatedUnion",(t,r)=>{l4.init(t,r);let i=t._zod.parse;aZ(t._zod,"propValues",()=>{let t={};for(let i of r.options){let s=i._zod.propValues;if(!s||0===Object.keys(s).length)throw Error(`Invalid discriminated union option at index "${r.options.indexOf(i)}"`);for(let[r,i]of Object.entries(s))for(let s of(t[r]||(t[r]=new Set),i))t[r].add(s)}return t});let s=aJ(()=>{let t=r.options,i=new Map;for(let s of t){let t=s._zod.propValues[r.discriminator];if(!t||0===t.size)throw Error(`Invalid discriminated union option at index "${r.options.indexOf(s)}"`);for(let r of t){if(i.has(r))throw Error(`Duplicate discriminator value "${String(r)}"`);i.set(r,s)}}return i});t._zod.parse=(n,a)=>{let o=n.value;if(!a8(o))return n.issues.push({code:"invalid_type",expected:"object",input:o,inst:t}),n;let l=s.value.get(o?.[r.discriminator]);return l?l._zod.run(n,a):r.unionFallback?i(n,a):(n.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:o,path:[r.discriminator],inst:t}),n)}}),l8=aL("$ZodIntersection",(t,r)=>{lg.init(t,r),t._zod.parse=(t,i)=>{let s=t.value,n=r.left._zod.run({value:s,issues:[]},i),a=r.right._zod.run({value:s,issues:[]},i);return n instanceof Promise||a instanceof Promise?Promise.all([n,a]).then(([r,i])=>l7(t,r,i)):l7(t,n,a)}});function l7(t,r,i){if(r.issues.length&&t.issues.push(...r.issues),i.issues.length&&t.issues.push(...i.issues),oy(t))return t;let s=function t(r,i){if(r===i||r instanceof Date&&i instanceof Date&&+r==+i)return{valid:!0,data:r};if(a9(r)&&a9(i)){let s=Object.keys(i),n=Object.keys(r).filter(t=>-1!==s.indexOf(t)),a={...r,...i};for(let s of n){let n=t(r[s],i[s]);if(!n.valid)return{valid:!1,mergeErrorPath:[s,...n.mergeErrorPath]};a[s]=n.data}return{valid:!0,data:a}}if(Array.isArray(r)&&Array.isArray(i)){if(r.length!==i.length)return{valid:!1,mergeErrorPath:[]};let s=[];for(let n=0;n<r.length;n++){let a=t(r[n],i[n]);if(!a.valid)return{valid:!1,mergeErrorPath:[n,...a.mergeErrorPath]};s.push(a.data)}return{valid:!0,data:s}}return{valid:!1,mergeErrorPath:[]}}(r.value,i.value);if(!s.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(s.mergeErrorPath)}`);return t.value=s.data,t}var l9=aL("$ZodRecord",(t,r)=>{lg.init(t,r),t._zod.parse=(i,s)=>{let n=i.value;if(!a9(n))return i.issues.push({expected:"record",code:"invalid_type",input:n,inst:t}),i;let a=[];if(r.keyType._zod.values){let o,l=r.keyType._zod.values;for(let t of(i.value={},l))if("string"==typeof t||"number"==typeof t||"symbol"==typeof t){let o=r.valueType._zod.run({value:n[t],issues:[]},s);o instanceof Promise?a.push(o.then(r=>{r.issues.length&&i.issues.push(...ob(t,r.issues)),i.value[t]=r.value})):(o.issues.length&&i.issues.push(...ob(t,o.issues)),i.value[t]=o.value)}for(let t in n)l.has(t)||(o=o??[]).push(t);o&&o.length>0&&i.issues.push({code:"unrecognized_keys",input:n,inst:t,keys:o})}else for(let o of(i.value={},Reflect.ownKeys(n))){if("__proto__"===o)continue;let l=r.keyType._zod.run({value:o,issues:[]},s);if(l instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(l.issues.length){i.issues.push({origin:"record",code:"invalid_key",issues:l.issues.map(t=>ov(t,s,aF())),input:o,path:[o],inst:t}),i.value[l.value]=l.value;continue}let p=r.valueType._zod.run({value:n[o],issues:[]},s);p instanceof Promise?a.push(p.then(t=>{t.issues.length&&i.issues.push(...ob(o,t.issues)),i.value[l.value]=t.value})):(p.issues.length&&i.issues.push(...ob(o,p.issues)),i.value[l.value]=p.value)}return a.length?Promise.all(a).then(()=>i):i}}),l5=aL("$ZodEnum",(t,r)=>{lg.init(t,r);let i=az(r.entries);t._zod.values=new Set(i),t._zod.pattern=RegExp(`^(${i.filter(t=>oe.has(typeof t)).map(t=>"string"==typeof t?or(t):t.toString()).join("|")})$`),t._zod.parse=(r,s)=>{let n=r.value;return t._zod.values.has(n)||r.issues.push({code:"invalid_value",values:i,input:n,inst:t}),r}}),l6=aL("$ZodLiteral",(t,r)=>{lg.init(t,r),t._zod.values=new Set(r.values),t._zod.pattern=RegExp(`^(${r.values.map(t=>"string"==typeof t?or(t):t?t.toString():String(t)).join("|")})$`),t._zod.parse=(i,s)=>{let n=i.value;return t._zod.values.has(n)||i.issues.push({code:"invalid_value",values:r.values,input:n,inst:t}),i}}),pe=aL("$ZodTransform",(t,r)=>{lg.init(t,r),t._zod.parse=(t,i)=>{let s=r.transform(t.value,t);if(i.async)return(s instanceof Promise?s:Promise.resolve(s)).then(r=>(t.value=r,t));if(s instanceof Promise)throw new aR;return t.value=s,t}}),pt=aL("$ZodOptional",(t,r)=>{lg.init(t,r),t._zod.optin="optional",t._zod.optout="optional",aZ(t._zod,"values",()=>r.innerType._zod.values?new Set([...r.innerType._zod.values,void 0]):void 0),aZ(t._zod,"pattern",()=>{let t=r.innerType._zod.pattern;return t?RegExp(`^(${aX(t.source)})?$`):void 0}),t._zod.parse=(t,i)=>"optional"===r.innerType._zod.optin?r.innerType._zod.run(t,i):void 0===t.value?t:r.innerType._zod.run(t,i)}),pr=aL("$ZodNullable",(t,r)=>{lg.init(t,r),aZ(t._zod,"optin",()=>r.innerType._zod.optin),aZ(t._zod,"optout",()=>r.innerType._zod.optout),aZ(t._zod,"pattern",()=>{let t=r.innerType._zod.pattern;return t?RegExp(`^(${aX(t.source)}|null)$`):void 0}),aZ(t._zod,"values",()=>r.innerType._zod.values?new Set([...r.innerType._zod.values,null]):void 0),t._zod.parse=(t,i)=>null===t.value?t:r.innerType._zod.run(t,i)}),pi=aL("$ZodDefault",(t,r)=>{lg.init(t,r),t._zod.optin="optional",aZ(t._zod,"values",()=>r.innerType._zod.values),t._zod.parse=(t,i)=>{if(void 0===t.value)return t.value=r.defaultValue,t;let s=r.innerType._zod.run(t,i);return s instanceof Promise?s.then(t=>ps(t,r)):ps(s,r)}});function ps(t,r){return void 0===t.value&&(t.value=r.defaultValue),t}var pn=aL("$ZodPrefault",(t,r)=>{lg.init(t,r),t._zod.optin="optional",aZ(t._zod,"values",()=>r.innerType._zod.values),t._zod.parse=(t,i)=>(void 0===t.value&&(t.value=r.defaultValue),r.innerType._zod.run(t,i))}),pa=aL("$ZodNonOptional",(t,r)=>{lg.init(t,r),aZ(t._zod,"values",()=>{let t=r.innerType._zod.values;return t?new Set([...t].filter(t=>void 0!==t)):void 0}),t._zod.parse=(i,s)=>{let n=r.innerType._zod.run(i,s);return n instanceof Promise?n.then(r=>po(r,t)):po(n,t)}});function po(t,r){return t.issues.length||void 0!==t.value||t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:r}),t}var pl=aL("$ZodCatch",(t,r)=>{lg.init(t,r),t._zod.optin="optional",aZ(t._zod,"optout",()=>r.innerType._zod.optout),aZ(t._zod,"values",()=>r.innerType._zod.values),t._zod.parse=(t,i)=>{let s=r.innerType._zod.run(t,i);return s instanceof Promise?s.then(s=>(t.value=s.value,s.issues.length&&(t.value=r.catchValue({...t,error:{issues:s.issues.map(t=>ov(t,i,aF()))},input:t.value}),t.issues=[]),t)):(t.value=s.value,s.issues.length&&(t.value=r.catchValue({...t,error:{issues:s.issues.map(t=>ov(t,i,aF()))},input:t.value}),t.issues=[]),t)}}),pp=aL("$ZodPipe",(t,r)=>{lg.init(t,r),aZ(t._zod,"values",()=>r.in._zod.values),aZ(t._zod,"optin",()=>r.in._zod.optin),aZ(t._zod,"optout",()=>r.out._zod.optout),t._zod.parse=(t,i)=>{let s=r.in._zod.run(t,i);return s instanceof Promise?s.then(t=>pu(t,r,i)):pu(s,r,i)}});function pu(t,r,i){return oy(t)?t:r.out._zod.run({value:t.value,issues:t.issues},i)}var pc=aL("$ZodReadonly",(t,r)=>{lg.init(t,r),aZ(t._zod,"propValues",()=>r.innerType._zod.propValues),aZ(t._zod,"values",()=>r.innerType._zod.values),aZ(t._zod,"optin",()=>r.innerType._zod.optin),aZ(t._zod,"optout",()=>r.innerType._zod.optout),t._zod.parse=(t,i)=>{let s=r.innerType._zod.run(t,i);return s instanceof Promise?s.then(pd):pd(s)}});function pd(t){return t.value=Object.freeze(t.value),t}var ph=aL("$ZodCustom",(t,r)=>{o6.init(t,r),lg.init(t,r),t._zod.parse=(t,r)=>t,t._zod.check=i=>{let s=i.value,n=r.fn(s);if(n instanceof Promise)return n.then(r=>pf(r,i,s,t));pf(n,i,s,t)}});function pf(t,r,i,s){if(!t){let t={code:"custom",input:i,inst:s,path:[...s._zod.def.path??[]],continue:!s._zod.def.abort};s._zod.def.params&&(t.params=s._zod.def.params),r.issues.push(oE(t))}}Symbol("ZodOutput"),Symbol("ZodInput");var pm=new class t{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...r){let i=r[0];if(this._map.set(t,i),i&&"object"==typeof i&&"id"in i){if(this._idmap.has(i.id))throw Error(`ID ${i.id} already exists in the registry`);this._idmap.set(i.id,t)}return this}remove(t){return this._map.delete(t),this}get(t){let r=t._zod.parent;if(r){let i={...this.get(r)??{}};return delete i.id,{...i,...this._map.get(t)}}return this._map.get(t)}has(t){return this._map.has(t)}};function py(t,r){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...os(r)})}function pb(t,r){return new lt({check:"less_than",...os(r),value:t,inclusive:!1})}function pg(t,r){return new lt({check:"less_than",...os(r),value:t,inclusive:!0})}function pv(t,r){return new lr({check:"greater_than",...os(r),value:t,inclusive:!1})}function px(t,r){return new lr({check:"greater_than",...os(r),value:t,inclusive:!0})}function pT(t,r){return new li({check:"multiple_of",...os(r),value:t})}function pE(t,r){return new ln({check:"max_length",...os(r),maximum:t})}function pS(t,r){return new la({check:"min_length",...os(r),minimum:t})}function p_(t,r){return new lo({check:"length_equals",...os(r),length:t})}function pP(t){return new lm({check:"overwrite",tx:t})}var pA=aL("ZodMiniType",(t,r)=>{if(!t._zod)throw Error("Uninitialized schema in ZodMiniType.");lg.init(t,r),t.def=r,t.parse=(r,i)=>oI(t,r,i,{callee:t.parse}),t.safeParse=(r,i)=>oD(t,r,i),t.parseAsync=async(r,i)=>oN(t,r,i,{callee:t.parseAsync}),t.safeParseAsync=async(r,i)=>oL(t,r,i),t.check=(...i)=>t.clone({...r,checks:[...r.checks??[],...i.map(t=>"function"==typeof t?{_zod:{check:t,def:{check:"custom"},onattach:[]}}:t)]}),t.clone=(r,i)=>oi(t,r,i),t.brand=()=>t,t.register=(r,i)=>(r.add(t,i),t)});aL("ZodMiniObject",(t,r)=>{l1.init(t,r),pA.init(t,r),aB.defineLazy(t,"shape",()=>r.shape)});var pw={};rc(pw,{time:()=>pD,duration:()=>pL,datetime:()=>pI,date:()=>pN,ZodISOTime:()=>pO,ZodISODuration:()=>pj,ZodISODateTime:()=>pC,ZodISODate:()=>pk});var pC=aL("ZodISODateTime",(t,r)=>{lO.init(t,r),pW.init(t,r)});function pI(t){return new pC({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...os(t)})}var pk=aL("ZodISODate",(t,r)=>{lD.init(t,r),pW.init(t,r)});function pN(t){return new pk({type:"string",format:"date",check:"string_format",...os(t)})}var pO=aL("ZodISOTime",(t,r)=>{lj.init(t,r),pW.init(t,r)});function pD(t){return new pO({type:"string",format:"time",check:"string_format",precision:null,...os(t)})}var pj=aL("ZodISODuration",(t,r)=>{lL.init(t,r),pW.init(t,r)});function pL(t){return new pj({type:"string",format:"duration",check:"string_format",...os(t)})}var pR=(t,r)=>{oA.init(t,r),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>{let i,s,n;return i=r||function(t){return t.message},s={_errors:[]},(n=t=>{for(let r of t.issues)if("invalid_union"===r.code&&r.errors.length)r.errors.map(t=>n({issues:t}));else if("invalid_key"===r.code)n({issues:r.issues});else if("invalid_element"===r.code)n({issues:r.issues});else if(0===r.path.length)s._errors.push(i(r));else{let t=s,n=0;for(;n<r.path.length;){let s=r.path[n];n!==r.path.length-1?t[s]=t[s]||{_errors:[]}:(t[s]=t[s]||{_errors:[]},t[s]._errors.push(i(r))),t=t[s],n++}}})(t),s}},flatten:{value:r=>(function(t,r=t=>t.message){let i={},s=[];for(let n of t.issues)n.path.length>0?(i[n.path[0]]=i[n.path[0]]||[],i[n.path[0]].push(r(n))):s.push(r(n));return{formErrors:s,fieldErrors:i}})(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get:()=>0===t.issues.length}})},pM=(aL("ZodError",pR),aL("ZodError",pR,{Parent:Error})),pF=oC(pM),pB=ok(pM),pU=oO(pM),p$=oj(pM),pV=aL("ZodType",(t,r)=>(lg.init(t,r),t.def=r,Object.defineProperty(t,"_def",{value:r}),t.check=(...i)=>t.clone({...r,checks:[...r.checks??[],...i.map(t=>"function"==typeof t?{_zod:{check:t,def:{check:"custom"},onattach:[]}}:t)]}),t.clone=(r,i)=>oi(t,r,i),t.brand=()=>t,t.register=(r,i)=>(r.add(t,i),t),t.parse=(r,i)=>pF(t,r,i,{callee:t.parse}),t.safeParse=(r,i)=>pU(t,r,i),t.parseAsync=async(r,i)=>pB(t,r,i,{callee:t.parseAsync}),t.safeParseAsync=async(r,i)=>p$(t,r,i),t.spa=t.safeParseAsync,t.refine=(r,i)=>t.check(function(t,r={}){return new uK({type:"custom",check:"custom",fn:t,...os(r)})}(r,i)),t.superRefine=r=>t.check(function(t){var r;let i,s=(r=r=>(r.addIssue=t=>{"string"==typeof t?r.issues.push(aB.issue(t,r.value,s._zod.def)):(t.fatal&&(t.continue=!1),t.code??(t.code="custom"),t.input??(t.input=r.value),t.inst??(t.inst=s),t.continue??(t.continue=!s._zod.def.abort),r.issues.push(aB.issue(t)))},t(r.value,r)),(i=new o6({check:"custom",...aB.normalizeParams(void 0)}))._zod.check=r,i);return s}(r)),t.overwrite=r=>t.check(pP(r)),t.optional=()=>uD(t),t.nullable=()=>uL(t),t.nullish=()=>uD(uL(t)),t.nonoptional=r=>{var i,s;return i=t,s=r,new uF({type:"nonoptional",innerType:i,...aB.normalizeParams(s)})},t.array=()=>uf(t),t.or=r=>uv([t,r]),t.and=r=>uS(t,r),t.transform=r=>u$(t,uN(r)),t.default=r=>{var i,s;return i=t,s=r,new uR({type:"default",innerType:i,get defaultValue(){return"function"==typeof s?s():s}})},t.prefault=r=>{var i,s;return i=t,s=r,new uM({type:"prefault",innerType:i,get defaultValue(){return"function"==typeof s?s():s}})},t.catch=r=>{var i;return new uB({type:"catch",innerType:t,catchValue:"function"==typeof(i=r)?i:()=>i})},t.pipe=r=>u$(t,r),t.readonly=()=>new uV({type:"readonly",innerType:t}),t.describe=r=>{let i=t.clone();return pm.add(i,{description:r}),i},Object.defineProperty(t,"description",{get:()=>pm.get(t)?.description,configurable:!0}),t.meta=(...r)=>{if(0===r.length)return pm.get(t);let i=t.clone();return pm.add(i,r[0]),i},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),pK=aL("_ZodString",(t,r)=>{lv.init(t,r),pV.init(t,r);let i=t._zod.bag;t.format=i.format??null,t.minLength=i.minimum??null,t.maxLength=i.maximum??null,t.regex=(...r)=>t.check(function(t,r){return new lp({check:"string_format",format:"regex",...os(r),pattern:t})}(...r)),t.includes=(...r)=>t.check(function(t,r){return new ld({check:"string_format",format:"includes",...os(r),includes:t})}(...r)),t.startsWith=(...r)=>t.check(function(t,r){return new lh({check:"string_format",format:"starts_with",...os(r),prefix:t})}(...r)),t.endsWith=(...r)=>t.check(function(t,r){return new lf({check:"string_format",format:"ends_with",...os(r),suffix:t})}(...r)),t.min=(...r)=>t.check(pS(...r)),t.max=(...r)=>t.check(pE(...r)),t.length=(...r)=>t.check(p_(...r)),t.nonempty=(...r)=>t.check(pS(1,...r)),t.lowercase=r=>t.check(new lu({check:"string_format",format:"lowercase",...os(r)})),t.uppercase=r=>t.check(new lc({check:"string_format",format:"uppercase",...os(r)})),t.trim=()=>t.check(pP(t=>t.trim())),t.normalize=(...r)=>t.check(function(t){return pP(r=>r.normalize(t))}(...r)),t.toLowerCase=()=>t.check(pP(t=>t.toLowerCase())),t.toUpperCase=()=>t.check(pP(t=>t.toUpperCase()))}),pq=aL("ZodString",(t,r)=>{lv.init(t,r),pK.init(t,r),t.email=r=>t.check(new pH({type:"string",format:"email",check:"string_format",abort:!1,...os(r)})),t.url=r=>t.check(new pX({type:"string",format:"url",check:"string_format",abort:!1,...os(r)})),t.jwt=r=>t.check(new ut({type:"string",format:"jwt",check:"string_format",abort:!1,...os(r)})),t.emoji=r=>t.check(new pG({type:"string",format:"emoji",check:"string_format",abort:!1,...os(r)})),t.guid=r=>t.check(py(pJ,r)),t.uuid=r=>t.check(new pY({type:"string",format:"uuid",check:"string_format",abort:!1,...os(r)})),t.uuidv4=r=>t.check(new pY({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...os(r)})),t.uuidv6=r=>t.check(new pY({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...os(r)})),t.uuidv7=r=>t.check(new pY({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...os(r)})),t.nanoid=r=>t.check(new pZ({type:"string",format:"nanoid",check:"string_format",abort:!1,...os(r)})),t.guid=r=>t.check(py(pJ,r)),t.cuid=r=>t.check(new pQ({type:"string",format:"cuid",check:"string_format",abort:!1,...os(r)})),t.cuid2=r=>t.check(new p0({type:"string",format:"cuid2",check:"string_format",abort:!1,...os(r)})),t.ulid=r=>t.check(new p1({type:"string",format:"ulid",check:"string_format",abort:!1,...os(r)})),t.base64=r=>t.check(new p5({type:"string",format:"base64",check:"string_format",abort:!1,...os(r)})),t.base64url=r=>t.check(new p6({type:"string",format:"base64url",check:"string_format",abort:!1,...os(r)})),t.xid=r=>t.check(new p2({type:"string",format:"xid",check:"string_format",abort:!1,...os(r)})),t.ksuid=r=>t.check(new p4({type:"string",format:"ksuid",check:"string_format",abort:!1,...os(r)})),t.ipv4=r=>t.check(new p3({type:"string",format:"ipv4",check:"string_format",abort:!1,...os(r)})),t.ipv6=r=>t.check(new p8({type:"string",format:"ipv6",check:"string_format",abort:!1,...os(r)})),t.cidrv4=r=>t.check(new p7({type:"string",format:"cidrv4",check:"string_format",abort:!1,...os(r)})),t.cidrv6=r=>t.check(new p9({type:"string",format:"cidrv6",check:"string_format",abort:!1,...os(r)})),t.e164=r=>t.check(new ue({type:"string",format:"e164",check:"string_format",abort:!1,...os(r)})),t.datetime=r=>t.check(pI(r)),t.date=r=>t.check(pN(r)),t.time=r=>t.check(pD(r)),t.duration=r=>t.check(pL(r))});function pz(t){return new pq({type:"string",...os(t)})}var pW=aL("ZodStringFormat",(t,r)=>{lx.init(t,r),pK.init(t,r)}),pH=aL("ZodEmail",(t,r)=>{lS.init(t,r),pW.init(t,r)}),pJ=aL("ZodGUID",(t,r)=>{lT.init(t,r),pW.init(t,r)}),pY=aL("ZodUUID",(t,r)=>{lE.init(t,r),pW.init(t,r)}),pX=aL("ZodURL",(t,r)=>{l_.init(t,r),pW.init(t,r)}),pG=aL("ZodEmoji",(t,r)=>{lP.init(t,r),pW.init(t,r)}),pZ=aL("ZodNanoID",(t,r)=>{lA.init(t,r),pW.init(t,r)}),pQ=aL("ZodCUID",(t,r)=>{lw.init(t,r),pW.init(t,r)}),p0=aL("ZodCUID2",(t,r)=>{lC.init(t,r),pW.init(t,r)}),p1=aL("ZodULID",(t,r)=>{lI.init(t,r),pW.init(t,r)}),p2=aL("ZodXID",(t,r)=>{lk.init(t,r),pW.init(t,r)}),p4=aL("ZodKSUID",(t,r)=>{lN.init(t,r),pW.init(t,r)}),p3=aL("ZodIPv4",(t,r)=>{lR.init(t,r),pW.init(t,r)}),p8=aL("ZodIPv6",(t,r)=>{lM.init(t,r),pW.init(t,r)}),p7=aL("ZodCIDRv4",(t,r)=>{lF.init(t,r),pW.init(t,r)}),p9=aL("ZodCIDRv6",(t,r)=>{lB.init(t,r),pW.init(t,r)}),p5=aL("ZodBase64",(t,r)=>{l$.init(t,r),pW.init(t,r)}),p6=aL("ZodBase64URL",(t,r)=>{lV.init(t,r),pW.init(t,r)}),ue=aL("ZodE164",(t,r)=>{lK.init(t,r),pW.init(t,r)}),ut=aL("ZodJWT",(t,r)=>{lq.init(t,r),pW.init(t,r)}),ur=aL("ZodNumber",(t,r)=>{lz.init(t,r),pV.init(t,r),t.gt=(r,i)=>t.check(pv(r,i)),t.gte=(r,i)=>t.check(px(r,i)),t.min=(r,i)=>t.check(px(r,i)),t.lt=(r,i)=>t.check(pb(r,i)),t.lte=(r,i)=>t.check(pg(r,i)),t.max=(r,i)=>t.check(pg(r,i)),t.int=r=>t.check(un(r)),t.safe=r=>t.check(un(r)),t.positive=r=>t.check(pv(0,r)),t.nonnegative=r=>t.check(px(0,r)),t.negative=r=>t.check(pb(0,r)),t.nonpositive=r=>t.check(pg(0,r)),t.multipleOf=(r,i)=>t.check(pT(r,i)),t.step=(r,i)=>t.check(pT(r,i)),t.finite=()=>t;let i=t._zod.bag;t.minValue=Math.max(i.minimum??-1/0,i.exclusiveMinimum??-1/0)??null,t.maxValue=Math.min(i.maximum??1/0,i.exclusiveMaximum??1/0)??null,t.isInt=(i.format??"").includes("int")||Number.isSafeInteger(i.multipleOf??.5),t.isFinite=!0,t.format=i.format??null});function ui(t){return new ur({type:"number",checks:[],...os(t)})}var us=aL("ZodNumberFormat",(t,r)=>{lW.init(t,r),ur.init(t,r)});function un(t){return new us({type:"number",check:"number_format",abort:!1,format:"safeint",...os(t)})}var ua=aL("ZodBoolean",(t,r)=>{lH.init(t,r),pV.init(t,r)});function uo(t){return new ua({type:"boolean",...os(t)})}var ul=aL("ZodNull",(t,r)=>{lJ.init(t,r),pV.init(t,r)});function up(t){return new ul({type:"null",...os(t)})}var uu=aL("ZodUnknown",(t,r)=>{lY.init(t,r),pV.init(t,r)});function uc(){return new uu({type:"unknown"})}var ud=aL("ZodNever",(t,r)=>{lX.init(t,r),pV.init(t,r)}),uh=aL("ZodArray",(t,r)=>{lZ.init(t,r),pV.init(t,r),t.element=r.element,t.min=(r,i)=>t.check(pS(r,i)),t.nonempty=r=>t.check(pS(1,r)),t.max=(r,i)=>t.check(pE(r,i)),t.length=(r,i)=>t.check(p_(r,i)),t.unwrap=()=>t.element});function uf(t,r){return new uh({type:"array",element:t,...os(r)})}var um=aL("ZodObject",(t,r)=>{l1.init(t,r),pV.init(t,r),aB.defineLazy(t,"shape",()=>r.shape),t.keyof=()=>uw(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:uc()}),t.loose=()=>t.clone({...t._zod.def,catchall:uc()}),t.strict=()=>t.clone({...t._zod.def,catchall:new ud({type:"never",...os(void 0)})}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>aB.extend(t,r),t.merge=r=>aB.merge(t,r),t.pick=r=>aB.pick(t,r),t.omit=r=>aB.omit(t,r),t.partial=(...r)=>aB.partial(uO,t,r[0]),t.required=(...r)=>aB.required(uF,t,r[0])});function uy(t,r){return new um({type:"object",get shape(){return aB.assignProp(this,"shape",{...t}),this.shape},...aB.normalizeParams(r)})}function ub(t,r){return new um({type:"object",get shape(){return aB.assignProp(this,"shape",{...t}),this.shape},catchall:uc(),...aB.normalizeParams(r)})}var ug=aL("ZodUnion",(t,r)=>{l4.init(t,r),pV.init(t,r),t.options=r.options});function uv(t,r){return new ug({type:"union",options:t,...aB.normalizeParams(r)})}var ux=aL("ZodDiscriminatedUnion",(t,r)=>{ug.init(t,r),l3.init(t,r)});function uT(t,r,i){return new ux({type:"union",options:r,discriminator:t,...aB.normalizeParams(i)})}var uE=aL("ZodIntersection",(t,r)=>{l8.init(t,r),pV.init(t,r)});function uS(t,r){return new uE({type:"intersection",left:t,right:r})}var u_=aL("ZodRecord",(t,r)=>{l9.init(t,r),pV.init(t,r),t.keyType=r.keyType,t.valueType=r.valueType});function uP(t,r,i){return new u_({type:"record",keyType:t,valueType:r,...aB.normalizeParams(i)})}var uA=aL("ZodEnum",(t,r)=>{l5.init(t,r),pV.init(t,r),t.enum=r.entries,t.options=Object.values(r.entries);let i=new Set(Object.keys(r.entries));t.extract=(t,s)=>{let n={};for(let s of t)if(i.has(s))n[s]=r.entries[s];else throw Error(`Key ${s} not found in enum`);return new uA({...r,checks:[],...aB.normalizeParams(s),entries:n})},t.exclude=(t,s)=>{let n={...r.entries};for(let r of t)if(i.has(r))delete n[r];else throw Error(`Key ${r} not found in enum`);return new uA({...r,checks:[],...aB.normalizeParams(s),entries:n})}});function uw(t,r){return new uA({type:"enum",entries:Array.isArray(t)?Object.fromEntries(t.map(t=>[t,t])):t,...aB.normalizeParams(r)})}var uC=aL("ZodLiteral",(t,r)=>{l6.init(t,r),pV.init(t,r),t.values=new Set(r.values),Object.defineProperty(t,"value",{get(){if(r.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return r.values[0]}})});function uI(t,r){return new uC({type:"literal",values:Array.isArray(t)?t:[t],...aB.normalizeParams(r)})}var uk=aL("ZodTransform",(t,r)=>{pe.init(t,r),pV.init(t,r),t._zod.parse=(i,s)=>{i.addIssue=s=>{"string"==typeof s?i.issues.push(aB.issue(s,i.value,r)):(s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=i.value),s.inst??(s.inst=t),s.continue??(s.continue=!0),i.issues.push(aB.issue(s)))};let n=r.transform(i.value,i);return n instanceof Promise?n.then(t=>(i.value=t,i)):(i.value=n,i)}});function uN(t){return new uk({type:"transform",transform:t})}var uO=aL("ZodOptional",(t,r)=>{pt.init(t,r),pV.init(t,r),t.unwrap=()=>t._zod.def.innerType});function uD(t){return new uO({type:"optional",innerType:t})}var uj=aL("ZodNullable",(t,r)=>{pr.init(t,r),pV.init(t,r),t.unwrap=()=>t._zod.def.innerType});function uL(t){return new uj({type:"nullable",innerType:t})}var uR=aL("ZodDefault",(t,r)=>{pi.init(t,r),pV.init(t,r),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap}),uM=aL("ZodPrefault",(t,r)=>{pn.init(t,r),pV.init(t,r),t.unwrap=()=>t._zod.def.innerType}),uF=aL("ZodNonOptional",(t,r)=>{pa.init(t,r),pV.init(t,r),t.unwrap=()=>t._zod.def.innerType}),uB=aL("ZodCatch",(t,r)=>{pl.init(t,r),pV.init(t,r),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap}),uU=aL("ZodPipe",(t,r)=>{pp.init(t,r),pV.init(t,r),t.in=r.in,t.out=r.out});function u$(t,r){return new uU({type:"pipe",in:t,out:r})}var uV=aL("ZodReadonly",(t,r)=>{pc.init(t,r),pV.init(t,r)}),uK=aL("ZodCustom",(t,r)=>{ph.init(t,r),pV.init(t,r)});aF({localeError:(l={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}},p={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},t=>{switch(t.code){case"invalid_type":return`Invalid input: expected ${t.expected}, received ${(t=>{let r=typeof t;switch(r){case"number":return Number.isNaN(t)?"NaN":"number";case"object":if(Array.isArray(t))return"array";if(null===t)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}return r})(t.input)}`;case"invalid_value":if(1===t.values.length)return`Invalid input: expected ${oa(t.values[0])}`;return`Invalid option: expected one of ${aW(t.values,"|")}`;case"too_big":{let r=t.inclusive?"<=":"<",i=l[t.origin]??null;if(i)return`Too big: expected ${t.origin??"value"} to have ${r}${t.maximum.toString()} ${i.unit??"elements"}`;return`Too big: expected ${t.origin??"value"} to be ${r}${t.maximum.toString()}`}case"too_small":{let r=t.inclusive?">=":">",i=l[t.origin]??null;if(i)return`Too small: expected ${t.origin} to have ${r}${t.minimum.toString()} ${i.unit}`;return`Too small: expected ${t.origin} to be ${r}${t.minimum.toString()}`}case"invalid_format":if("starts_with"===t.format)return`Invalid string: must start with "${t.prefix}"`;if("ends_with"===t.format)return`Invalid string: must end with "${t.suffix}"`;if("includes"===t.format)return`Invalid string: must include "${t.includes}"`;if("regex"===t.format)return`Invalid string: must match pattern ${t.pattern}`;return`Invalid ${p[t.format]??t.format}`;case"not_multiple_of":return`Invalid number: must be a multiple of ${t.divisor}`;case"unrecognized_keys":return`Unrecognized key${t.keys.length>1?"s":""}: ${aW(t.keys,", ")}`;case"invalid_key":return`Invalid key in ${t.origin}`;case"invalid_union":default:return"Invalid input";case"invalid_element":return`Invalid value in ${t.origin}`}})});var uq=(c=(t=>null!==t&&("object"==typeof t||"function"==typeof t))??(()=>!0),(o=os(void 0)).abort??(o.abort=!0),new uK({type:"custom",check:"custom",fn:c,...o})),uz=uv([pz(),ui().int()]),uW=pz(),uH=(ub({ttl:uv([ui(),up()]).optional(),pollInterval:ui().optional()}),uy({ttl:ui().optional()})),uJ=uy({taskId:pz()}),uY=ub({progressToken:uz.optional(),"io.modelcontextprotocol/related-task":uJ.optional()}),uX=uy({_meta:uY.optional()}),uG=uX.extend({task:uH.optional()}),uZ=uy({method:pz(),params:uX.loose().optional()}),uQ=uy({_meta:uY.optional()}),u0=uy({method:pz(),params:uQ.loose().optional()}),u1=ub({_meta:uY.optional()}),u2=uv([pz(),ui().int()]),u4=uy({jsonrpc:uI("2.0"),id:u2,...uZ.shape}).strict(),u3=uy({jsonrpc:uI("2.0"),...u0.shape}).strict(),u8=uy({jsonrpc:uI("2.0"),id:u2,result:u1}).strict();(d=b||(b={}))[d.ConnectionClosed=-32e3]="ConnectionClosed",d[d.RequestTimeout=-32001]="RequestTimeout",d[d.ParseError=-32700]="ParseError",d[d.InvalidRequest=-32600]="InvalidRequest",d[d.MethodNotFound=-32601]="MethodNotFound",d[d.InvalidParams=-32602]="InvalidParams",d[d.InternalError=-32603]="InternalError",d[d.UrlElicitationRequired=-32042]="UrlElicitationRequired";var u7=uy({jsonrpc:uI("2.0"),id:u2.optional(),error:uy({code:ui().int(),message:pz(),data:uc().optional()})}).strict();uv([u4,u3,u8,u7]),uv([u8,u7]);var u9=u1.strict(),u5=uQ.extend({requestId:u2.optional(),reason:pz().optional()}),u6=u0.extend({method:uI("notifications/cancelled"),params:u5}),ce=uy({src:pz(),mimeType:pz().optional(),sizes:uf(pz()).optional(),theme:uw(["light","dark"]).optional()}),ct=uy({icons:uf(ce).optional()}),cr=uy({name:pz(),title:pz().optional()}),ci=cr.extend({...cr.shape,...ct.shape,version:pz(),websiteUrl:pz().optional(),description:pz().optional()}),cs=uS(uy({applyDefaults:uo().optional()}),uP(pz(),uc())),cn=(h=t=>t&&"object"==typeof t&&!Array.isArray(t)&&0===Object.keys(t).length?{form:{}}:t,f=uS(uy({form:cs.optional(),url:uq.optional()}),uP(pz(),uc()).optional()),u$(uN(h),f)),ca=ub({list:uq.optional(),cancel:uq.optional(),requests:ub({sampling:ub({createMessage:uq.optional()}).optional(),elicitation:ub({create:uq.optional()}).optional()}).optional()}),co=ub({list:uq.optional(),cancel:uq.optional(),requests:ub({tools:ub({call:uq.optional()}).optional()}).optional()}),cl=uy({experimental:uP(pz(),uq).optional(),sampling:uy({context:uq.optional(),tools:uq.optional()}).optional(),elicitation:cn.optional(),roots:uy({listChanged:uo().optional()}).optional(),tasks:ca.optional()}),cp=uX.extend({protocolVersion:pz(),capabilities:cl,clientInfo:ci}),cu=uZ.extend({method:uI("initialize"),params:cp}),cc=uy({experimental:uP(pz(),uq).optional(),logging:uq.optional(),completions:uq.optional(),prompts:uy({listChanged:uo().optional()}).optional(),resources:uy({subscribe:uo().optional(),listChanged:uo().optional()}).optional(),tools:uy({listChanged:uo().optional()}).optional(),tasks:co.optional()}),cd=u1.extend({protocolVersion:pz(),capabilities:cc,serverInfo:ci,instructions:pz().optional()}),ch=u0.extend({method:uI("notifications/initialized"),params:uQ.optional()}),cf=uZ.extend({method:uI("ping"),params:uX.optional()}),cm=uy({progress:ui(),total:uD(ui()),message:uD(pz())}),cy=uy({...uQ.shape,...cm.shape,progressToken:uz}),cb=u0.extend({method:uI("notifications/progress"),params:cy}),cg=uX.extend({cursor:uW.optional()}),cv=uZ.extend({params:cg.optional()}),cx=u1.extend({nextCursor:uW.optional()}),cT=uw(["working","input_required","completed","failed","cancelled"]),cE=uy({taskId:pz(),status:cT,ttl:uv([ui(),up()]),createdAt:pz(),lastUpdatedAt:pz(),pollInterval:uD(ui()),statusMessage:uD(pz())}),cS=u1.extend({task:cE}),c_=uQ.merge(cE),cP=u0.extend({method:uI("notifications/tasks/status"),params:c_}),cA=uZ.extend({method:uI("tasks/get"),params:uX.extend({taskId:pz()})}),cw=u1.merge(cE),cC=uZ.extend({method:uI("tasks/result"),params:uX.extend({taskId:pz()})}),cI=(u1.loose(),cv.extend({method:uI("tasks/list")})),ck=cx.extend({tasks:uf(cE)}),cN=uZ.extend({method:uI("tasks/cancel"),params:uX.extend({taskId:pz()})}),cO=(u1.merge(cE),uy({uri:pz(),mimeType:uD(pz()),_meta:uP(pz(),uc()).optional()})),cD=cO.extend({text:pz()}),cj=pz().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),cL=cO.extend({blob:cj}),cR=uw(["user","assistant"]),cM=uy({audience:uf(cR).optional(),priority:ui().min(0).max(1).optional(),lastModified:pw.datetime({offset:!0}).optional()}),cF=uy({...cr.shape,...ct.shape,uri:pz(),description:uD(pz()),mimeType:uD(pz()),annotations:cM.optional(),_meta:uD(ub({}))}),cB=uy({...cr.shape,...ct.shape,uriTemplate:pz(),description:uD(pz()),mimeType:uD(pz()),annotations:cM.optional(),_meta:uD(ub({}))}),cU=cv.extend({method:uI("resources/list")}),c$=cx.extend({resources:uf(cF)}),cV=cv.extend({method:uI("resources/templates/list")}),cK=cx.extend({resourceTemplates:uf(cB)}),cq=uX.extend({uri:pz()}),cz=uZ.extend({method:uI("resources/read"),params:cq}),cW=u1.extend({contents:uf(uv([cD,cL]))}),cH=u0.extend({method:uI("notifications/resources/list_changed"),params:uQ.optional()}),cJ=uZ.extend({method:uI("resources/subscribe"),params:cq}),cY=uZ.extend({method:uI("resources/unsubscribe"),params:cq}),cX=uQ.extend({uri:pz()}),cG=u0.extend({method:uI("notifications/resources/updated"),params:cX}),cZ=uy({name:pz(),description:uD(pz()),required:uD(uo())}),cQ=uy({...cr.shape,...ct.shape,description:uD(pz()),arguments:uD(uf(cZ)),_meta:uD(ub({}))}),c0=cv.extend({method:uI("prompts/list")}),c1=cx.extend({prompts:uf(cQ)}),c2=uX.extend({name:pz(),arguments:uP(pz(),pz()).optional()}),c4=uZ.extend({method:uI("prompts/get"),params:c2}),c3=uy({type:uI("text"),text:pz(),annotations:cM.optional(),_meta:uP(pz(),uc()).optional()}),c8=uy({type:uI("image"),data:cj,mimeType:pz(),annotations:cM.optional(),_meta:uP(pz(),uc()).optional()}),c7=uy({type:uI("audio"),data:cj,mimeType:pz(),annotations:cM.optional(),_meta:uP(pz(),uc()).optional()}),c9=uy({type:uI("tool_use"),name:pz(),id:pz(),input:uP(pz(),uc()),_meta:uP(pz(),uc()).optional()}),c5=uy({type:uI("resource"),resource:uv([cD,cL]),annotations:cM.optional(),_meta:uP(pz(),uc()).optional()}),c6=uv([c3,c8,c7,cF.extend({type:uI("resource_link")}),c5]),de=uy({role:cR,content:c6}),dt=u1.extend({description:pz().optional(),messages:uf(de)}),dr=u0.extend({method:uI("notifications/prompts/list_changed"),params:uQ.optional()}),di=uy({title:pz().optional(),readOnlyHint:uo().optional(),destructiveHint:uo().optional(),idempotentHint:uo().optional(),openWorldHint:uo().optional()}),ds=uy({taskSupport:uw(["required","optional","forbidden"]).optional()}),dn=uy({...cr.shape,...ct.shape,description:pz().optional(),inputSchema:uy({type:uI("object"),properties:uP(pz(),uq).optional(),required:uf(pz()).optional()}).catchall(uc()),outputSchema:uy({type:uI("object"),properties:uP(pz(),uq).optional(),required:uf(pz()).optional()}).catchall(uc()).optional(),annotations:di.optional(),execution:ds.optional(),_meta:uP(pz(),uc()).optional()}),da=cv.extend({method:uI("tools/list")}),dl=cx.extend({tools:uf(dn)}),dp=u1.extend({content:uf(c6).default([]),structuredContent:uP(pz(),uc()).optional(),isError:uo().optional()}),du=(dp.or(u1.extend({toolResult:uc()})),uG.extend({name:pz(),arguments:uP(pz(),uc()).optional()})),dc=uZ.extend({method:uI("tools/call"),params:du}),dd=u0.extend({method:uI("notifications/tools/list_changed"),params:uQ.optional()}),dh=(uy({autoRefresh:uo().default(!0),debounceMs:ui().int().nonnegative().default(300)}),uw(["debug","info","notice","warning","error","critical","alert","emergency"])),df=uX.extend({level:dh}),dm=uZ.extend({method:uI("logging/setLevel"),params:df}),dy=uQ.extend({level:dh,logger:pz().optional(),data:uc()}),db=u0.extend({method:uI("notifications/message"),params:dy}),dg=uy({name:pz().optional()}),dv=uy({hints:uf(dg).optional(),costPriority:ui().min(0).max(1).optional(),speedPriority:ui().min(0).max(1).optional(),intelligencePriority:ui().min(0).max(1).optional()}),dx=uy({mode:uw(["auto","required","none"]).optional()}),dT=uy({type:uI("tool_result"),toolUseId:pz().describe("The unique identifier for the corresponding tool call."),content:uf(c6).default([]),structuredContent:uy({}).loose().optional(),isError:uo().optional(),_meta:uP(pz(),uc()).optional()}),dE=uT("type",[c3,c8,c7]),dS=uT("type",[c3,c8,c7,c9,dT]),d_=uy({role:cR,content:uv([dS,uf(dS)]),_meta:uP(pz(),uc()).optional()}),dP=uG.extend({messages:uf(d_),modelPreferences:dv.optional(),systemPrompt:pz().optional(),includeContext:uw(["none","thisServer","allServers"]).optional(),temperature:ui().optional(),maxTokens:ui().int(),stopSequences:uf(pz()).optional(),metadata:uq.optional(),tools:uf(dn).optional(),toolChoice:dx.optional()}),dA=uZ.extend({method:uI("sampling/createMessage"),params:dP}),dw=u1.extend({model:pz(),stopReason:uD(uw(["endTurn","stopSequence","maxTokens"]).or(pz())),role:cR,content:dE}),dC=u1.extend({model:pz(),stopReason:uD(uw(["endTurn","stopSequence","maxTokens","toolUse"]).or(pz())),role:cR,content:uv([dS,uf(dS)])}),dI=uy({type:uI("boolean"),title:pz().optional(),description:pz().optional(),default:uo().optional()}),dk=uy({type:uI("string"),title:pz().optional(),description:pz().optional(),minLength:ui().optional(),maxLength:ui().optional(),format:uw(["email","uri","date","date-time"]).optional(),default:pz().optional()}),dN=uy({type:uw(["number","integer"]),title:pz().optional(),description:pz().optional(),minimum:ui().optional(),maximum:ui().optional(),default:ui().optional()}),dO=uy({type:uI("string"),title:pz().optional(),description:pz().optional(),enum:uf(pz()),default:pz().optional()}),dD=uy({type:uI("string"),title:pz().optional(),description:pz().optional(),oneOf:uf(uy({const:pz(),title:pz()})),default:pz().optional()}),dj=uy({type:uI("string"),title:pz().optional(),description:pz().optional(),enum:uf(pz()),enumNames:uf(pz()).optional(),default:pz().optional()}),dL=uv([dO,dD]),dR=uv([uy({type:uI("array"),title:pz().optional(),description:pz().optional(),minItems:ui().optional(),maxItems:ui().optional(),items:uy({type:uI("string"),enum:uf(pz())}),default:uf(pz()).optional()}),uy({type:uI("array"),title:pz().optional(),description:pz().optional(),minItems:ui().optional(),maxItems:ui().optional(),items:uy({anyOf:uf(uy({const:pz(),title:pz()}))}),default:uf(pz()).optional()})]),dM=uv([dj,dL,dR]),dF=uv([dM,dI,dk,dN]),dB=uv([uG.extend({mode:uI("form").optional(),message:pz(),requestedSchema:uy({type:uI("object"),properties:uP(pz(),dF),required:uf(pz()).optional()})}),uG.extend({mode:uI("url"),message:pz(),elicitationId:pz(),url:pz().url()})]),dU=uZ.extend({method:uI("elicitation/create"),params:dB}),d$=uQ.extend({elicitationId:pz()}),dV=u0.extend({method:uI("notifications/elicitation/complete"),params:d$}),dK=u1.extend({action:uw(["accept","decline","cancel"]),content:(m=t=>null===t?void 0:t,y=uP(pz(),uv([pz(),ui(),uo(),uf(pz())])).optional(),u$(uN(m),y))}),dq=uy({type:uI("ref/resource"),uri:pz()}),dz=uy({type:uI("ref/prompt"),name:pz()}),dW=uX.extend({ref:uv([dz,dq]),argument:uy({name:pz(),value:pz()}),context:uy({arguments:uP(pz(),pz()).optional()}).optional()}),dH=uZ.extend({method:uI("completion/complete"),params:dW}),dJ=u1.extend({completion:ub({values:uf(pz()).max(100),total:uD(ui().int()),hasMore:uD(uo())})}),dY=uy({uri:pz().startsWith("file://"),name:pz().optional(),_meta:uP(pz(),uc()).optional()}),dX=uZ.extend({method:uI("roots/list"),params:uX.optional()}),dG=u1.extend({roots:uf(dY)}),dZ=u0.extend({method:uI("notifications/roots/list_changed"),params:uQ.optional()});uv([cf,cu,dH,dm,c4,c0,cU,cV,cz,cJ,cY,dc,da,cA,cC,cI,cN]),uv([u6,cb,ch,dZ,cP]),uv([u9,dw,dC,dK,dG,cw,ck,cS]),uv([cf,dA,dU,dX,cA,cC,cI,cN]),uv([u6,cb,db,cG,cH,dd,dr,cP,dV]),uv([u9,cd,dJ,dt,c1,c$,cK,cW,dp,dl,cw,ck,cS]);class dQ extends Error{constructor(t,r,i){super(`MCP error ${t}: ${r}`),this.code=t,this.data=i,this.name="McpError"}static fromError(t,r,i){return t===b.UrlElicitationRequired&&i&&i.elicitations?new d0(i.elicitations,r):new dQ(t,r,i)}}class d0 extends dQ{constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(b.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}}var d1=Symbol("Let zodToJsonSchema decide on which parser to use");function d2(t,r,i,s){s?.errorMessages&&i&&(t.errorMessage={...t.errorMessage,[r]:i})}function d4(t,r,i,s,n){t[r]=i,d2(t,r,s,n)}var d3=(t,r)=>{let i=0;for(;i<t.length&&i<r.length&&t[i]===r[i];i++);return[(t.length-i).toString(),...r.slice(i)].join("/")};function d8(t){if("openAi"!==t.target)return{};let r=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:"relative"===t.$refStrategy?d3(r,t.currentPath):r.join("/")}}function d7(t,r){return hg(t.type._def,r)}var d9=void 0,d5=/^[cC][^\s-]{8,}$/,d6=/^[0-9a-z]+$/,he=/^[0-9A-HJKMNP-TV-Z]{26}$/,ht=/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,hr=()=>(void 0===d9&&(d9=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),d9),hi=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,hs=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,hn=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ha=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ho=/^[a-zA-Z0-9_-]{21}$/,hl=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;function hp(t,r){let i={type:"string"};if(t.checks)for(let s of t.checks)switch(s.kind){case"min":d4(i,"minLength","number"==typeof i.minLength?Math.max(i.minLength,s.value):s.value,s.message,r);break;case"max":d4(i,"maxLength","number"==typeof i.maxLength?Math.min(i.maxLength,s.value):s.value,s.message,r);break;case"email":switch(r.emailStrategy){case"format:email":hd(i,"email",s.message,r);break;case"format:idn-email":hd(i,"idn-email",s.message,r);break;case"pattern:zod":hh(i,ht,s.message,r)}break;case"url":hd(i,"uri",s.message,r);break;case"uuid":hd(i,"uuid",s.message,r);break;case"regex":hh(i,s.regex,s.message,r);break;case"cuid":hh(i,d5,s.message,r);break;case"cuid2":hh(i,d6,s.message,r);break;case"startsWith":hh(i,RegExp(`^${hu(s.value,r)}`),s.message,r);break;case"endsWith":hh(i,RegExp(`${hu(s.value,r)}$`),s.message,r);break;case"datetime":hd(i,"date-time",s.message,r);break;case"date":hd(i,"date",s.message,r);break;case"time":hd(i,"time",s.message,r);break;case"duration":hd(i,"duration",s.message,r);break;case"length":d4(i,"minLength","number"==typeof i.minLength?Math.max(i.minLength,s.value):s.value,s.message,r),d4(i,"maxLength","number"==typeof i.maxLength?Math.min(i.maxLength,s.value):s.value,s.message,r);break;case"includes":hh(i,RegExp(hu(s.value,r)),s.message,r);break;case"ip":"v6"!==s.version&&hd(i,"ipv4",s.message,r),"v4"!==s.version&&hd(i,"ipv6",s.message,r);break;case"base64url":hh(i,ha,s.message,r);break;case"jwt":hh(i,hl,s.message,r);break;case"cidr":"v6"!==s.version&&hh(i,hi,s.message,r),"v4"!==s.version&&hh(i,hs,s.message,r);break;case"emoji":hh(i,hr(),s.message,r);break;case"ulid":hh(i,he,s.message,r);break;case"base64":switch(r.base64Strategy){case"format:binary":hd(i,"binary",s.message,r);break;case"contentEncoding:base64":d4(i,"contentEncoding","base64",s.message,r);break;case"pattern:zod":hh(i,hn,s.message,r)}break;case"nanoid":hh(i,ho,s.message,r)}return i}function hu(t,r){return"escape"===r.patternStrategy?function(t){let r="";for(let i=0;i<t.length;i++)hc.has(t[i])||(r+="\\"),r+=t[i];return r}(t):t}var hc=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function hd(t,r,i,s){t.format||t.anyOf?.some(t=>t.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&s.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,0===Object.keys(t.errorMessage).length))&&delete t.errorMessage,t.anyOf.push({format:r,...i&&s.errorMessages&&{errorMessage:{format:i}}})):d4(t,"format",r,i,s)}function hh(t,r,i,s){t.pattern||t.allOf?.some(t=>t.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&s.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,0===Object.keys(t.errorMessage).length))&&delete t.errorMessage,t.allOf.push({pattern:hf(r,s),...i&&s.errorMessages&&{errorMessage:{pattern:i}}})):d4(t,"pattern",hf(r,s),i,s)}function hf(t,r){if(!r.applyRegexFlags||!t.flags)return t.source;let i={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},s=i.i?t.source.toLowerCase():t.source,n="",a=!1,o=!1,l=!1;for(let t=0;t<s.length;t++){if(a){n+=s[t],a=!1;continue}if(i.i){if(o){if(s[t].match(/[a-z]/)){l?(n+=s[t],n+=`${s[t-2]}-${s[t]}`.toUpperCase(),l=!1):"-"===s[t+1]&&s[t+2]?.match(/[a-z]/)?(n+=s[t],l=!0):n+=`${s[t]}${s[t].toUpperCase()}`;continue}}else if(s[t].match(/[a-z]/)){n+=`[${s[t]}${s[t].toUpperCase()}]`;continue}}if(i.m){if("^"===s[t]){n+=`(^|(?<=[\r
|
|
394
394
|
]))`;continue}else if("$"===s[t]){n+=`($|(?=[\r
|
|
395
395
|
]))`;continue}}if(i.s&&"."===s[t]){n+=o?`${s[t]}\r
|
|
396
396
|
`:`[${s[t]}\r
|
|
397
|
-
]`;continue}(n+=s[t],"\\"===s[t])?a=!0:o&&"]"===s[t]?o=!1:o||"["!==s[t]||(o=!0)}try{new RegExp(n)}catch{return console.warn(`Could not convert regex pattern at ${r.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return n}function hf(t,r){if("openAi"===r.target&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),"openApi3"===r.target&&t.keyType?._def.typeName===n2.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((i,s)=>({...i,[s]:hb(t.valueType._def,{...r,currentPath:[...r.currentPath,"properties",s]})??d3(r)}),{}),additionalProperties:r.rejectedAdditionalProperties};let i={type:"object",additionalProperties:hb(t.valueType._def,{...r,currentPath:[...r.currentPath,"additionalProperties"]})??r.allowedAdditionalProperties};if("openApi3"===r.target)return i;if(t.keyType?._def.typeName===n2.ZodString&&t.keyType._def.checks?.length){let{type:s,...n}=hl(t.keyType._def,r);return{...i,propertyNames:n}}if(t.keyType?._def.typeName===n2.ZodEnum)return{...i,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===n2.ZodBranded&&t.keyType._def.type._def.typeName===n2.ZodString&&t.keyType._def.type._def.checks?.length){let{type:s,...n}=d8(t.keyType._def,r);return{...i,propertyNames:n}}return i}var hm={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"},hy=(t,r)=>{let i=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((t,i)=>hb(t._def,{...r,currentPath:[...r.currentPath,"anyOf",`${i}`]})).filter(t=>!!t&&(!r.strictUnions||"object"==typeof t&&Object.keys(t).length>0));return i.length?{anyOf:i}:void 0};function hb(t,r,i=!1){let s=r.seen.get(t);if(r.override){let n=r.override?.(t,r,s,i);if(n!==d0)return n}if(s&&!i){let t=hg(s,r);if(void 0!==t)return t}let n={def:t,path:r.currentPath,jsonSchema:void 0};r.seen.set(t,n);let a=((t,r,i)=>{switch(r){case n2.ZodString:return hl(t,i);case n2.ZodNumber:let s={type:"number"};if(!t.checks)return s;for(let r of t.checks)switch(r.kind){case"int":s.type="integer",d1(s,"type",r.message,i);break;case"min":"jsonSchema7"===i.target?r.inclusive?d2(s,"minimum",r.value,r.message,i):d2(s,"exclusiveMinimum",r.value,r.message,i):(r.inclusive||(s.exclusiveMinimum=!0),d2(s,"minimum",r.value,r.message,i));break;case"max":"jsonSchema7"===i.target?r.inclusive?d2(s,"maximum",r.value,r.message,i):d2(s,"exclusiveMaximum",r.value,r.message,i):(r.inclusive||(s.exclusiveMaximum=!0),d2(s,"maximum",r.value,r.message,i));break;case"multipleOf":d2(s,"multipleOf",r.value,r.message,i)}return s;case n2.ZodObject:return function(t,r){let i="openAi"===r.target,s={type:"object",properties:{}},n=[],a=t.shape();for(let t in a){let o=a[t];if(void 0===o||void 0===o._def)continue;let l=function(t){try{return t.isOptional()}catch{return!0}}(o);l&&i&&("ZodOptional"===o._def.typeName&&(o=o._def.innerType),o.isNullable()||(o=o.nullable()),l=!1);let p=hb(o._def,{...r,currentPath:[...r.currentPath,"properties",t],propertyPath:[...r.currentPath,"properties",t]});void 0!==p&&(s.properties[t]=p,l||n.push(t))}n.length&&(s.required=n);let o=function(t,r){if("ZodNever"!==t.catchall._def.typeName)return hb(t.catchall._def,{...r,currentPath:[...r.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return r.allowedAdditionalProperties;case"strict":return r.rejectedAdditionalProperties;case"strip":return"strict"===r.removeAdditionalStrategy?r.allowedAdditionalProperties:r.rejectedAdditionalProperties}}(t,r);return void 0!==o&&(s.additionalProperties=o),s}(t,i);case n2.ZodBigInt:let n={type:"integer",format:"int64"};if(!t.checks)return n;for(let r of t.checks)switch(r.kind){case"min":"jsonSchema7"===i.target?r.inclusive?d2(n,"minimum",r.value,r.message,i):d2(n,"exclusiveMinimum",r.value,r.message,i):(r.inclusive||(n.exclusiveMinimum=!0),d2(n,"minimum",r.value,r.message,i));break;case"max":"jsonSchema7"===i.target?r.inclusive?d2(n,"maximum",r.value,r.message,i):d2(n,"exclusiveMaximum",r.value,r.message,i):(r.inclusive||(n.exclusiveMaximum=!0),d2(n,"maximum",r.value,r.message,i));break;case"multipleOf":d2(n,"multipleOf",r.value,r.message,i)}return n;case n2.ZodBoolean:return{type:"boolean"};case n2.ZodDate:return function t(r,i,s){let n=s??i.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((s,n)=>t(r,i,s))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":var a=r,o=i;let l={type:"integer",format:"unix-time"};if("openApi3"===o.target)return l;for(let t of a.checks)switch(t.kind){case"min":d2(l,"minimum",t.value,t.message,o);break;case"max":d2(l,"maximum",t.value,t.message,o)}return l}}(t,i);case n2.ZodUndefined:return{not:d3(i)};case n2.ZodNull:return"openApi3"===i.target?{enum:["null"],nullable:!0}:{type:"null"};case n2.ZodArray:let a;return a={type:"array"},t.type?._def&&t.type?._def?.typeName!==n2.ZodAny&&(a.items=hb(t.type._def,{...i,currentPath:[...i.currentPath,"items"]})),t.minLength&&d2(a,"minItems",t.minLength.value,t.minLength.message,i),t.maxLength&&d2(a,"maxItems",t.maxLength.value,t.maxLength.message,i),t.exactLength&&(d2(a,"minItems",t.exactLength.value,t.exactLength.message,i),d2(a,"maxItems",t.exactLength.value,t.exactLength.message,i)),a;case n2.ZodUnion:case n2.ZodDiscriminatedUnion:if("openApi3"===i.target)return hy(t,i);let o=t.options instanceof Map?Array.from(t.options.values()):t.options;if(o.every(t=>t._def.typeName in hm&&(!t._def.checks||!t._def.checks.length))){let t=o.reduce((t,r)=>{let i=hm[r._def.typeName];return i&&!t.includes(i)?[...t,i]:t},[]);return{type:t.length>1?t:t[0]}}if(o.every(t=>"ZodLiteral"===t._def.typeName&&!t.description)){let t=o.reduce((t,r)=>{let i=typeof r._def.value;switch(i){case"string":case"number":case"boolean":return[...t,i];case"bigint":return[...t,"integer"];case"object":if(null===r._def.value)return[...t,"null"];default:return t}},[]);if(t.length===o.length){let r=t.filter((t,r,i)=>i.indexOf(t)===r);return{type:r.length>1?r:r[0],enum:o.reduce((t,r)=>t.includes(r._def.value)?t:[...t,r._def.value],[])}}}else if(o.every(t=>"ZodEnum"===t._def.typeName))return{type:"string",enum:o.reduce((t,r)=>[...t,...r._def.values.filter(r=>!t.includes(r))],[])};return hy(t,i);case n2.ZodIntersection:let l,p,u;return l=[hb(t.left._def,{...i,currentPath:[...i.currentPath,"allOf","0"]}),hb(t.right._def,{...i,currentPath:[...i.currentPath,"allOf","1"]})].filter(t=>!!t),p="jsonSchema2019-09"===i.target?{unevaluatedProperties:!1}:void 0,u=[],l.forEach(t=>{if((!("type"in t)||"string"!==t.type)&&"allOf"in t)u.push(...t.allOf),void 0===t.unevaluatedProperties&&(p=void 0);else{let r=t;if("additionalProperties"in t&&!1===t.additionalProperties){let{additionalProperties:i,...s}=t;r=s}else p=void 0;u.push(r)}}),u.length?{allOf:u,...p}:void 0;case n2.ZodTuple:return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((t,r)=>hb(t._def,{...i,currentPath:[...i.currentPath,"items",`${r}`]})).reduce((t,r)=>void 0===r?t:[...t,r],[]),additionalItems:hb(t.rest._def,{...i,currentPath:[...i.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((t,r)=>hb(t._def,{...i,currentPath:[...i.currentPath,"items",`${r}`]})).reduce((t,r)=>void 0===r?t:[...t,r],[])};case n2.ZodRecord:return hf(t,i);case n2.ZodLiteral:let c;return"bigint"!=(c=typeof t.value)&&"number"!==c&&"boolean"!==c&&"string"!==c?{type:Array.isArray(t.value)?"array":"object"}:"openApi3"===i.target?{type:"bigint"===c?"integer":c,enum:[t.value]}:{type:"bigint"===c?"integer":c,const:t.value};case n2.ZodEnum:return{type:"string",enum:Array.from(t.values)};case n2.ZodNativeEnum:let d,h,f;return d=t.values,{type:1===(f=Array.from(new Set((h=Object.keys(t.values).filter(t=>"number"!=typeof d[d[t]]).map(t=>d[t])).map(t=>typeof t)))).length?"string"===f[0]?"string":"number":["string","number"],enum:h};case n2.ZodNullable:if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return"openApi3"===i.target?{type:hm[t.innerType._def.typeName],nullable:!0}:{type:[hm[t.innerType._def.typeName],"null"]};if("openApi3"===i.target){let r=hb(t.innerType._def,{...i,currentPath:[...i.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}let m=hb(t.innerType._def,{...i,currentPath:[...i.currentPath,"anyOf","0"]});return m&&{anyOf:[m,{type:"null"}]};case n2.ZodOptional:if(i.currentPath.toString()===i.propertyPath?.toString())return hb(t.innerType._def,i);let y=hb(t.innerType._def,{...i,currentPath:[...i.currentPath,"anyOf","1"]});return y?{anyOf:[{not:d3(i)},y]}:d3(i);case n2.ZodMap:return"record"===i.mapStrategy?hf(t,i):{type:"array",maxItems:125,items:{type:"array",items:[hb(t.keyType._def,{...i,currentPath:[...i.currentPath,"items","items","0"]})||d3(i),hb(t.valueType._def,{...i,currentPath:[...i.currentPath,"items","items","1"]})||d3(i)],minItems:2,maxItems:2}};case n2.ZodSet:let b;return b={type:"array",uniqueItems:!0,items:hb(t.valueType._def,{...i,currentPath:[...i.currentPath,"items"]})},t.minSize&&d2(b,"minItems",t.minSize.value,t.minSize.message,i),t.maxSize&&d2(b,"maxItems",t.maxSize.value,t.maxSize.message,i),b;case n2.ZodLazy:return()=>t.getter()._def;case n2.ZodPromise:return hb(t.type._def,i);case n2.ZodNaN:case n2.ZodNever:return"openAi"===i.target?void 0:{not:d3({...i,currentPath:[...i.currentPath,"not"]})};case n2.ZodEffects:return"input"===i.effectStrategy?hb(t.schema._def,i):d3(i);case n2.ZodAny:case n2.ZodUnknown:return d3(i);case n2.ZodDefault:return{...hb(t.innerType._def,i),default:t.defaultValue()};case n2.ZodBranded:return d8(t,i);case n2.ZodReadonly:case n2.ZodCatch:return hb(t.innerType._def,i);case n2.ZodPipeline:if("input"===i.pipeStrategy)return hb(t.in._def,i);if("output"===i.pipeStrategy)return hb(t.out._def,i);let g=hb(t.in._def,{...i,currentPath:[...i.currentPath,"allOf","0"]}),v=hb(t.out._def,{...i,currentPath:[...i.currentPath,"allOf",g?"1":"0"]});return{allOf:[g,v].filter(t=>void 0!==t)};case n2.ZodFunction:case n2.ZodVoid:case n2.ZodSymbol:default:return}})(t,t.typeName,r),o="function"==typeof a?hb(a(),r):a;if(o&&hv(t,r,o),r.postProcess){let i=r.postProcess(o,t,r);return n.jsonSchema=o,i}return n.jsonSchema=o,o}var hg=(t,r)=>{switch(r.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:d4(r.currentPath,t.path)};case"none":case"seen":if(t.path.length<r.currentPath.length&&t.path.every((t,i)=>r.currentPath[i]===t))return console.warn(`Recursive reference detected at ${r.currentPath.join("/")}! Defaulting to any`),d3(r);return"seen"===r.$refStrategy?d3(r):void 0}},hv=(t,r,i)=>(t.description&&(i.description=t.description,r.markdownDescription)&&(i.markdownDescription=t.description),i);ra(iT(),1),ra(i_(),1),Symbol.for("mcp.completable"),(g||(g={})).Completable="McpCompletable";let hx=process.env.STACK_CLAUDE_PROXY_URL??"https://api.hexclave.com/api/v1/integrations/ai-proxy";var hT=class extends Error{constructor(t){super(`Claude agent timed out${null==t?"":` after ${t}ms`}.`),this.name="ClaudeAgentTimeoutError"}},hE=class extends Error{constructor(t){super(`Claude agent failed (${t}).`),this.name="ClaudeAgentFailureError"}};async function hS(t){let r=new AbortController,i=null==t.timeoutMs?null:setTimeout(()=>r.abort(),t.timeoutMs),s=!1,n="",a=t.onPreToolUse;try{let i;for await(let o of function({prompt:t,options:r}){let{systemPrompt:i,settings:s,settingSources:n,sandbox:a,...o}=r??{},l,p;void 0===i?l="":"string"==typeof i?l=i:"preset"===i.type&&(p=i.append);let u=o.pathToClaudeCodeExecutable;if(!u){let t=(0,tQ.fileURLToPath)(t9.url),r=(0,tV.join)(t,"..");u=(0,tV.join)(r,"cli.js")}process.env.CLAUDE_AGENT_SDK_VERSION="0.2.73";let{abortController:c=iP(),additionalDirectories:d=[],agent:h,agents:f,allowedTools:m=[],betas:y,canUseTool:b,continue:g,cwd:v,debug:x,debugFile:T,disallowedTools:E=[],tools:S,env:_,executable:P=iw()?"bun":"node",executableArgs:A=[],extraArgs:w={},fallbackModel:C,enableFileCheckpointing:I,toolConfig:k,forkSession:N,hooks:O,includePartialMessages:D,onElicitation:j,persistSession:L,thinking:R,effort:M,maxThinkingTokens:F,maxTurns:B,maxBudgetUsd:U,mcpServers:$,model:V,outputFormat:K,permissionMode:q="default",allowDangerouslySkipPermissions:z=!1,permissionPromptToolName:W,plugins:H,workload:J,resume:Y,resumeSessionAt:X,sessionId:G,stderr:Z,strictMcpConfig:Q}=o,ee=K?.type==="json_schema"?K.schema:void 0,et=_;if(et||(et={...process.env}),et.CLAUDE_CODE_ENTRYPOINT||(et.CLAUDE_CODE_ENTRYPOINT="sdk-ts"),I&&(et.CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING="true"),k?.askUserQuestion?.previewFormat&&(et.CLAUDE_CODE_QUESTION_PREVIEW_FORMAT=k.askUserQuestion.previewFormat),!u)throw Error("pathToClaudeCodeExecutable is required");let er={},ei=new Map;if($)for(let[t,r]of Object.entries($))"sdk"===r.type&&"instance"in r?(ei.set(t,r.instance),er[t]={type:"sdk",name:t}):er[t]=r;let es="string"==typeof t,en;if(R)switch(R.type){case"adaptive":en={type:"adaptive"};break;case"enabled":en={type:"enabled",budgetTokens:R.budgetTokens};break;case"disabled":en={type:"disabled"}}else void 0!==F&&(en=0===F?{type:"disabled"}:{type:"enabled",budgetTokens:F});let ea=new sA({abortController:c,additionalDirectories:d,agent:h,betas:y,cwd:v,debug:x,debugFile:T,executable:P,executableArgs:A,extraArgs:J?{...w,workload:J}:w,pathToClaudeCodeExecutable:u,env:et,forkSession:N,stderr:Z,thinkingConfig:en,effort:M,maxTurns:B,maxBudgetUsd:U,model:V,fallbackModel:C,jsonSchema:ee,permissionMode:q,allowDangerouslySkipPermissions:z,permissionPromptToolName:W,continueConversation:g,resume:Y,resumeSessionAt:X,sessionId:G,settings:"object"==typeof s?s_(s):s,settingSources:n??[],allowedTools:m,disallowedTools:E,tools:S,mcpServers:er,strictMcpConfig:Q,canUseTool:!!b,hooks:!!O,includePartialMessages:D,persistSession:L,plugins:H,sandbox:a,spawnClaudeCodeProcess:o.spawnClaudeCodeProcess}),eo=new sI(ea,es,b,O,c,ei,ee,{systemPrompt:l,appendSystemPrompt:p,agents:f,promptSuggestions:o.promptSuggestions,agentProgressSummaries:o.agentProgressSummaries},j);return"string"==typeof t?ea.write(s_({type:"user",session_id:"",message:{role:"user",content:[{type:"text",text:t}]},parent_tool_use_id:null})+`
|
|
398
|
-
`):eo.streamInput(t),eo}({prompt:t.prompt,options:{model:"nvidia/nemotron-3-super-120b-a12b:nitro",...!0===t.strictIsolation?{settingSources:[],strictMcpConfig:!0}:{},...null==a?{}:{hooks:{PreToolUse:[{hooks:[async t=>"PreToolUse"!==t.hook_event_name?{continue:!0}:await a(t)]}]}},allowedTools:t.allowedTools,permissionMode:"dontAsk",cwd:t.cwd,abortController:r,env:{...(i={...process.env},delete i.CLAUDECODE,i),...!0===t.strictIsolation?{CLAUDE_CODE_DISABLE_AUTO_MEMORY:"1"}:{},ANTHROPIC_BASE_URL:
|
|
397
|
+
]`;continue}(n+=s[t],"\\"===s[t])?a=!0:o&&"]"===s[t]?o=!1:o||"["!==s[t]||(o=!0)}try{new RegExp(n)}catch{return console.warn(`Could not convert regex pattern at ${r.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return n}function hm(t,r){if("openAi"===r.target&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),"openApi3"===r.target&&t.keyType?._def.typeName===n4.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((i,s)=>({...i,[s]:hg(t.valueType._def,{...r,currentPath:[...r.currentPath,"properties",s]})??d8(r)}),{}),additionalProperties:r.rejectedAdditionalProperties};let i={type:"object",additionalProperties:hg(t.valueType._def,{...r,currentPath:[...r.currentPath,"additionalProperties"]})??r.allowedAdditionalProperties};if("openApi3"===r.target)return i;if(t.keyType?._def.typeName===n4.ZodString&&t.keyType._def.checks?.length){let{type:s,...n}=hp(t.keyType._def,r);return{...i,propertyNames:n}}if(t.keyType?._def.typeName===n4.ZodEnum)return{...i,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===n4.ZodBranded&&t.keyType._def.type._def.typeName===n4.ZodString&&t.keyType._def.type._def.checks?.length){let{type:s,...n}=d7(t.keyType._def,r);return{...i,propertyNames:n}}return i}var hy={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"},hb=(t,r)=>{let i=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((t,i)=>hg(t._def,{...r,currentPath:[...r.currentPath,"anyOf",`${i}`]})).filter(t=>!!t&&(!r.strictUnions||"object"==typeof t&&Object.keys(t).length>0));return i.length?{anyOf:i}:void 0};function hg(t,r,i=!1){let s=r.seen.get(t);if(r.override){let n=r.override?.(t,r,s,i);if(n!==d1)return n}if(s&&!i){let t=hv(s,r);if(void 0!==t)return t}let n={def:t,path:r.currentPath,jsonSchema:void 0};r.seen.set(t,n);let a=((t,r,i)=>{switch(r){case n4.ZodString:return hp(t,i);case n4.ZodNumber:let s={type:"number"};if(!t.checks)return s;for(let r of t.checks)switch(r.kind){case"int":s.type="integer",d2(s,"type",r.message,i);break;case"min":"jsonSchema7"===i.target?r.inclusive?d4(s,"minimum",r.value,r.message,i):d4(s,"exclusiveMinimum",r.value,r.message,i):(r.inclusive||(s.exclusiveMinimum=!0),d4(s,"minimum",r.value,r.message,i));break;case"max":"jsonSchema7"===i.target?r.inclusive?d4(s,"maximum",r.value,r.message,i):d4(s,"exclusiveMaximum",r.value,r.message,i):(r.inclusive||(s.exclusiveMaximum=!0),d4(s,"maximum",r.value,r.message,i));break;case"multipleOf":d4(s,"multipleOf",r.value,r.message,i)}return s;case n4.ZodObject:return function(t,r){let i="openAi"===r.target,s={type:"object",properties:{}},n=[],a=t.shape();for(let t in a){let o=a[t];if(void 0===o||void 0===o._def)continue;let l=function(t){try{return t.isOptional()}catch{return!0}}(o);l&&i&&("ZodOptional"===o._def.typeName&&(o=o._def.innerType),o.isNullable()||(o=o.nullable()),l=!1);let p=hg(o._def,{...r,currentPath:[...r.currentPath,"properties",t],propertyPath:[...r.currentPath,"properties",t]});void 0!==p&&(s.properties[t]=p,l||n.push(t))}n.length&&(s.required=n);let o=function(t,r){if("ZodNever"!==t.catchall._def.typeName)return hg(t.catchall._def,{...r,currentPath:[...r.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return r.allowedAdditionalProperties;case"strict":return r.rejectedAdditionalProperties;case"strip":return"strict"===r.removeAdditionalStrategy?r.allowedAdditionalProperties:r.rejectedAdditionalProperties}}(t,r);return void 0!==o&&(s.additionalProperties=o),s}(t,i);case n4.ZodBigInt:let n={type:"integer",format:"int64"};if(!t.checks)return n;for(let r of t.checks)switch(r.kind){case"min":"jsonSchema7"===i.target?r.inclusive?d4(n,"minimum",r.value,r.message,i):d4(n,"exclusiveMinimum",r.value,r.message,i):(r.inclusive||(n.exclusiveMinimum=!0),d4(n,"minimum",r.value,r.message,i));break;case"max":"jsonSchema7"===i.target?r.inclusive?d4(n,"maximum",r.value,r.message,i):d4(n,"exclusiveMaximum",r.value,r.message,i):(r.inclusive||(n.exclusiveMaximum=!0),d4(n,"maximum",r.value,r.message,i));break;case"multipleOf":d4(n,"multipleOf",r.value,r.message,i)}return n;case n4.ZodBoolean:return{type:"boolean"};case n4.ZodDate:return function t(r,i,s){let n=s??i.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((s,n)=>t(r,i,s))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":var a=r,o=i;let l={type:"integer",format:"unix-time"};if("openApi3"===o.target)return l;for(let t of a.checks)switch(t.kind){case"min":d4(l,"minimum",t.value,t.message,o);break;case"max":d4(l,"maximum",t.value,t.message,o)}return l}}(t,i);case n4.ZodUndefined:return{not:d8(i)};case n4.ZodNull:return"openApi3"===i.target?{enum:["null"],nullable:!0}:{type:"null"};case n4.ZodArray:let a;return a={type:"array"},t.type?._def&&t.type?._def?.typeName!==n4.ZodAny&&(a.items=hg(t.type._def,{...i,currentPath:[...i.currentPath,"items"]})),t.minLength&&d4(a,"minItems",t.minLength.value,t.minLength.message,i),t.maxLength&&d4(a,"maxItems",t.maxLength.value,t.maxLength.message,i),t.exactLength&&(d4(a,"minItems",t.exactLength.value,t.exactLength.message,i),d4(a,"maxItems",t.exactLength.value,t.exactLength.message,i)),a;case n4.ZodUnion:case n4.ZodDiscriminatedUnion:if("openApi3"===i.target)return hb(t,i);let o=t.options instanceof Map?Array.from(t.options.values()):t.options;if(o.every(t=>t._def.typeName in hy&&(!t._def.checks||!t._def.checks.length))){let t=o.reduce((t,r)=>{let i=hy[r._def.typeName];return i&&!t.includes(i)?[...t,i]:t},[]);return{type:t.length>1?t:t[0]}}if(o.every(t=>"ZodLiteral"===t._def.typeName&&!t.description)){let t=o.reduce((t,r)=>{let i=typeof r._def.value;switch(i){case"string":case"number":case"boolean":return[...t,i];case"bigint":return[...t,"integer"];case"object":if(null===r._def.value)return[...t,"null"];default:return t}},[]);if(t.length===o.length){let r=t.filter((t,r,i)=>i.indexOf(t)===r);return{type:r.length>1?r:r[0],enum:o.reduce((t,r)=>t.includes(r._def.value)?t:[...t,r._def.value],[])}}}else if(o.every(t=>"ZodEnum"===t._def.typeName))return{type:"string",enum:o.reduce((t,r)=>[...t,...r._def.values.filter(r=>!t.includes(r))],[])};return hb(t,i);case n4.ZodIntersection:let l,p,u;return l=[hg(t.left._def,{...i,currentPath:[...i.currentPath,"allOf","0"]}),hg(t.right._def,{...i,currentPath:[...i.currentPath,"allOf","1"]})].filter(t=>!!t),p="jsonSchema2019-09"===i.target?{unevaluatedProperties:!1}:void 0,u=[],l.forEach(t=>{if((!("type"in t)||"string"!==t.type)&&"allOf"in t)u.push(...t.allOf),void 0===t.unevaluatedProperties&&(p=void 0);else{let r=t;if("additionalProperties"in t&&!1===t.additionalProperties){let{additionalProperties:i,...s}=t;r=s}else p=void 0;u.push(r)}}),u.length?{allOf:u,...p}:void 0;case n4.ZodTuple:return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((t,r)=>hg(t._def,{...i,currentPath:[...i.currentPath,"items",`${r}`]})).reduce((t,r)=>void 0===r?t:[...t,r],[]),additionalItems:hg(t.rest._def,{...i,currentPath:[...i.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((t,r)=>hg(t._def,{...i,currentPath:[...i.currentPath,"items",`${r}`]})).reduce((t,r)=>void 0===r?t:[...t,r],[])};case n4.ZodRecord:return hm(t,i);case n4.ZodLiteral:let c;return"bigint"!=(c=typeof t.value)&&"number"!==c&&"boolean"!==c&&"string"!==c?{type:Array.isArray(t.value)?"array":"object"}:"openApi3"===i.target?{type:"bigint"===c?"integer":c,enum:[t.value]}:{type:"bigint"===c?"integer":c,const:t.value};case n4.ZodEnum:return{type:"string",enum:Array.from(t.values)};case n4.ZodNativeEnum:let d,h,f;return d=t.values,{type:1===(f=Array.from(new Set((h=Object.keys(t.values).filter(t=>"number"!=typeof d[d[t]]).map(t=>d[t])).map(t=>typeof t)))).length?"string"===f[0]?"string":"number":["string","number"],enum:h};case n4.ZodNullable:if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return"openApi3"===i.target?{type:hy[t.innerType._def.typeName],nullable:!0}:{type:[hy[t.innerType._def.typeName],"null"]};if("openApi3"===i.target){let r=hg(t.innerType._def,{...i,currentPath:[...i.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}let m=hg(t.innerType._def,{...i,currentPath:[...i.currentPath,"anyOf","0"]});return m&&{anyOf:[m,{type:"null"}]};case n4.ZodOptional:if(i.currentPath.toString()===i.propertyPath?.toString())return hg(t.innerType._def,i);let y=hg(t.innerType._def,{...i,currentPath:[...i.currentPath,"anyOf","1"]});return y?{anyOf:[{not:d8(i)},y]}:d8(i);case n4.ZodMap:return"record"===i.mapStrategy?hm(t,i):{type:"array",maxItems:125,items:{type:"array",items:[hg(t.keyType._def,{...i,currentPath:[...i.currentPath,"items","items","0"]})||d8(i),hg(t.valueType._def,{...i,currentPath:[...i.currentPath,"items","items","1"]})||d8(i)],minItems:2,maxItems:2}};case n4.ZodSet:let b;return b={type:"array",uniqueItems:!0,items:hg(t.valueType._def,{...i,currentPath:[...i.currentPath,"items"]})},t.minSize&&d4(b,"minItems",t.minSize.value,t.minSize.message,i),t.maxSize&&d4(b,"maxItems",t.maxSize.value,t.maxSize.message,i),b;case n4.ZodLazy:return()=>t.getter()._def;case n4.ZodPromise:return hg(t.type._def,i);case n4.ZodNaN:case n4.ZodNever:return"openAi"===i.target?void 0:{not:d8({...i,currentPath:[...i.currentPath,"not"]})};case n4.ZodEffects:return"input"===i.effectStrategy?hg(t.schema._def,i):d8(i);case n4.ZodAny:case n4.ZodUnknown:return d8(i);case n4.ZodDefault:return{...hg(t.innerType._def,i),default:t.defaultValue()};case n4.ZodBranded:return d7(t,i);case n4.ZodReadonly:case n4.ZodCatch:return hg(t.innerType._def,i);case n4.ZodPipeline:if("input"===i.pipeStrategy)return hg(t.in._def,i);if("output"===i.pipeStrategy)return hg(t.out._def,i);let g=hg(t.in._def,{...i,currentPath:[...i.currentPath,"allOf","0"]}),v=hg(t.out._def,{...i,currentPath:[...i.currentPath,"allOf",g?"1":"0"]});return{allOf:[g,v].filter(t=>void 0!==t)};case n4.ZodFunction:case n4.ZodVoid:case n4.ZodSymbol:default:return}})(t,t.typeName,r),o="function"==typeof a?hg(a(),r):a;if(o&&hx(t,r,o),r.postProcess){let i=r.postProcess(o,t,r);return n.jsonSchema=o,i}return n.jsonSchema=o,o}var hv=(t,r)=>{switch(r.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:d3(r.currentPath,t.path)};case"none":case"seen":if(t.path.length<r.currentPath.length&&t.path.every((t,i)=>r.currentPath[i]===t))return console.warn(`Recursive reference detected at ${r.currentPath.join("/")}! Defaulting to any`),d8(r);return"seen"===r.$refStrategy?d8(r):void 0}},hx=(t,r,i)=>(t.description&&(i.description=t.description,r.markdownDescription)&&(i.markdownDescription=t.description),i);ro(iE(),1),ro(iP(),1),Symbol.for("mcp.completable"),(g||(g={})).Completable="McpCompletable";let hT=process.env.STACK_CLAUDE_PROXY_URL??"https://api.hexclave.com/api/v1/integrations/ai-proxy";var hE=class extends Error{constructor(t){super(`Claude agent timed out${null==t?"":` after ${t}ms`}.`),this.name="ClaudeAgentTimeoutError"}},hS=class extends Error{constructor(t){super(`Claude agent failed (${t}).`),this.name="ClaudeAgentFailureError"}};async function h_(t){let r=new AbortController,i=null==t.timeoutMs?null:setTimeout(()=>r.abort(),t.timeoutMs),s=!1,n="",a=t.onPreToolUse;try{let i;for await(let o of function({prompt:t,options:r}){let{systemPrompt:i,settings:s,settingSources:n,sandbox:a,...o}=r??{},l,p;void 0===i?l="":"string"==typeof i?l=i:"preset"===i.type&&(p=i.append);let u=o.pathToClaudeCodeExecutable;if(!u){let t=(0,t0.fileURLToPath)(t5.url),r=(0,tK.join)(t,"..");u=(0,tK.join)(r,"cli.js")}process.env.CLAUDE_AGENT_SDK_VERSION="0.2.73";let{abortController:c=iA(),additionalDirectories:d=[],agent:h,agents:f,allowedTools:m=[],betas:y,canUseTool:b,continue:g,cwd:v,debug:x,debugFile:T,disallowedTools:E=[],tools:S,env:_,executable:P=iC()?"bun":"node",executableArgs:A=[],extraArgs:w={},fallbackModel:C,enableFileCheckpointing:I,toolConfig:k,forkSession:N,hooks:O,includePartialMessages:D,onElicitation:j,persistSession:L,thinking:R,effort:M,maxThinkingTokens:F,maxTurns:B,maxBudgetUsd:U,mcpServers:$,model:V,outputFormat:K,permissionMode:q="default",allowDangerouslySkipPermissions:z=!1,permissionPromptToolName:W,plugins:H,workload:J,resume:Y,resumeSessionAt:X,sessionId:G,stderr:Z,strictMcpConfig:Q}=o,ee=K?.type==="json_schema"?K.schema:void 0,et=_;if(et||(et={...process.env}),et.CLAUDE_CODE_ENTRYPOINT||(et.CLAUDE_CODE_ENTRYPOINT="sdk-ts"),I&&(et.CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING="true"),k?.askUserQuestion?.previewFormat&&(et.CLAUDE_CODE_QUESTION_PREVIEW_FORMAT=k.askUserQuestion.previewFormat),!u)throw Error("pathToClaudeCodeExecutable is required");let er={},ei=new Map;if($)for(let[t,r]of Object.entries($))"sdk"===r.type&&"instance"in r?(ei.set(t,r.instance),er[t]={type:"sdk",name:t}):er[t]=r;let es="string"==typeof t,en;if(R)switch(R.type){case"adaptive":en={type:"adaptive"};break;case"enabled":en={type:"enabled",budgetTokens:R.budgetTokens};break;case"disabled":en={type:"disabled"}}else void 0!==F&&(en=0===F?{type:"disabled"}:{type:"enabled",budgetTokens:F});let ea=new sw({abortController:c,additionalDirectories:d,agent:h,betas:y,cwd:v,debug:x,debugFile:T,executable:P,executableArgs:A,extraArgs:J?{...w,workload:J}:w,pathToClaudeCodeExecutable:u,env:et,forkSession:N,stderr:Z,thinkingConfig:en,effort:M,maxTurns:B,maxBudgetUsd:U,model:V,fallbackModel:C,jsonSchema:ee,permissionMode:q,allowDangerouslySkipPermissions:z,permissionPromptToolName:W,continueConversation:g,resume:Y,resumeSessionAt:X,sessionId:G,settings:"object"==typeof s?sP(s):s,settingSources:n??[],allowedTools:m,disallowedTools:E,tools:S,mcpServers:er,strictMcpConfig:Q,canUseTool:!!b,hooks:!!O,includePartialMessages:D,persistSession:L,plugins:H,sandbox:a,spawnClaudeCodeProcess:o.spawnClaudeCodeProcess}),eo=new sk(ea,es,b,O,c,ei,ee,{systemPrompt:l,appendSystemPrompt:p,agents:f,promptSuggestions:o.promptSuggestions,agentProgressSummaries:o.agentProgressSummaries},j);return"string"==typeof t?ea.write(sP({type:"user",session_id:"",message:{role:"user",content:[{type:"text",text:t}]},parent_tool_use_id:null})+`
|
|
398
|
+
`):eo.streamInput(t),eo}({prompt:t.prompt,options:{model:"nvidia/nemotron-3-super-120b-a12b:nitro",...!0===t.strictIsolation?{settingSources:[],strictMcpConfig:!0}:{},...null==a?{}:{hooks:{PreToolUse:[{hooks:[async t=>"PreToolUse"!==t.hook_event_name?{continue:!0}:await a(t)]}]}},allowedTools:t.allowedTools,permissionMode:"dontAsk",cwd:t.cwd,abortController:r,env:{...(i={...process.env},delete i.CLAUDECODE,i),...!0===t.strictIsolation?{CLAUDE_CODE_DISABLE_AUTO_MEMORY:"1"}:{},ANTHROPIC_BASE_URL:hT,ANTHROPIC_API_KEY:"stack-auth-proxy"},stderr:t.stderr}}))if(t.onMessage?.(o),"result"===o.type)if("result"in o)s=!0,n=o.result;else throw new hS(o.subtype)}catch(i){var o;if(r.signal.aborted&&(o=i)instanceof Error&&"AbortError"===o.name)throw new hE(t.timeoutMs??void 0);throw i}finally{null!=i&&clearTimeout(i)}if(!s)throw Error("Claude agent ended without reporting a result.");return{resultText:n}}let hP=new Set(["Write","Edit"]);function hA(t,r){let i=tK.default.relative(tK.default.resolve(t),tK.default.resolve(r));return""===i||!i.startsWith("..")&&!tK.default.isAbsolute(i)}let hw=function(t,r={}){return r.transform||(r={...r,transform:tQ}),(0,tX.default)(t,r,{onError:tG,nativeImport:tZ,createRequire:tY.createRequire})}({get url(){return`file://${t.P("packages/shared-backend/dist/esm/index.js")}`}}.url,{moduleCache:!1}),hC="[Stack config updater]";function hI(t){(0,tV.existsSync)(t)||((0,tV.mkdirSync)(tK.default.dirname(t),{recursive:!0}),hN(t,{}))}async function hk(t){var r;let i;if(hI(t),""===(0,tV.readFileSync)(t,"utf-8").trim())return{config:{},showOnboarding:!1};try{i=await hw.import(t)}catch(r){throw(0,x.captureError)("shared-backend/readConfigFile",r),Error(`Failed to load config file ${t}. If your config imports a value (e.g. defineHexclaveConfig) from a framework package such as "@hexclave/next", import it from that package's lightweight "/config" entrypoint instead, which doesn't load the framework runtime:
|
|
399
399
|
|
|
400
400
|
import { defineHexclaveConfig } from "@hexclave/next/config";
|
|
401
|
-
`)}if(null===(r=i)||"object"!=typeof r)throw Error(`Invalid config in ${t}. The file must export a plain \`config\` object or "show-onboarding".`);let s=i.config;if("show-onboarding"===s)return{config:{},showOnboarding:!0};if(!
|
|
401
|
+
`)}if(null===(r=i)||"object"!=typeof r)throw Error(`Invalid config in ${t}. The file must export a plain \`config\` object or "show-onboarding".`);let s=i.config;if("show-onboarding"===s)return{config:{},showOnboarding:!0};if(!tL(s))throw Error(`Invalid config in ${t}.`);return{config:s,showOnboarding:!1}}function hN(t,r){var i=function(t,r){if(!tL(t))throw Error("Invalid config: expected a plain object.");let i=[],s=tU(t,{onDotIntoNonObject:"ignore",onDotIntoNull:"empty-object",droppedKeys:i});if(i.length>0)throw Error(`Config has conflicting keys that would be dropped during normalization: ${i.map(t=>JSON.stringify(t)).join(", ")}`);let n=r??"@hexclave/js";return`import type { HexclaveConfig } from "${n.startsWith("@hexclave/")?`${n}/config`:n}";
|
|
402
402
|
|
|
403
403
|
export const config: HexclaveConfig = ${JSON.stringify(s,null,2)};
|
|
404
|
-
`}(r,function(t){let r=t;for(;;){let t=
|
|
404
|
+
`}(r,function(t){let r=t;for(;;){let t=tK.default.join(r,"package.json");if((0,tV.existsSync)(t))try{let r=JSON.parse((0,tV.readFileSync)(t,"utf-8"));var i=[...Object.keys(r.dependencies??{}),...Object.keys(r.devDependencies??{})];for(let t of tJ)if(i.includes(t))return t;return}catch{return}let s=tK.default.dirname(r);if(s===r)break;r=s}}(tK.default.dirname(t)));let s=tK.default.dirname(t);(0,tV.mkdirSync)(s,{recursive:!0});let n=tK.default.join(s,`.stack.config.${Math.random().toString(36).slice(2)}.tmp`);(0,tV.writeFileSync)(n,i,"utf-8");try{(0,tV.renameSync)(n,t)}catch(t){try{(0,tV.rmSync)(n)}catch{}throw t}}async function hO(t,r){if(hI(t),0===hF(r).length)return;let i=(0,tV.readFileSync)(t,"utf-8"),s=function(t,r){try{let i=tH(t,r);return tL(i)?i:null}catch{return null}}(i,t);if(null!=s&&tL(s)){let i=tF(s,r);if(!tL(i))throw Error(`${hC} Merged config is invalid after applying update to ${t}`);hN(t,i);return}let n=await hR(t),{snapshots:a,seen:o}=function(t,r){let i=tK.default.dirname(t),s=tK.default.resolve(t),n=[{path:s,content:r}],a=new Set([s]);for(let t of function(t){let r,i=[],s=/\bimport\b(?:[^'"]*?\bfrom\s*)?["'](\.{1,2}\/[^"']+)["']/g;for(;null!==(r=s.exec(t));)i.push(r[1]);return i}(r)){let r=tK.default.resolve(i,t);hA(i,r)&&hL(n,r,a)}return{snapshots:n,seen:a}}(t,i);try{var l,p,u;let i,s,c;await hj({prompt:(l=tK.default.basename(t),p=r,u=n,i=hF(p).map(({path:t,value:r})=>`- ${JSON.stringify(t)}: set to ${JSON.stringify(r)}`).join("\n"),s=null==u?null:hB(tF(u,p)),c=null==s?"":`
|
|
405
405
|
After the edit, evaluating the exported \`config\` must produce this exact JSON value:
|
|
406
406
|
|
|
407
407
|
${JSON.stringify(s,null,2)}
|
|
@@ -424,6 +424,6 @@ Rules:
|
|
|
424
424
|
- If a listed path's value is currently provided by an imported external file (like the \`import ... with { type: "text" }\` example above), DO NOT inline the new value into the config file. Instead, overwrite that external file with the new value and keep the import statement intact.
|
|
425
425
|
- If a listed path's value is a plain inline literal, edit it inline.
|
|
426
426
|
- Keep the file valid: it must still export a \`config\` that, once evaluated, reflects the new values exactly.
|
|
427
|
-
- Do not run any shell commands and do not create files other than what is required to apply these changes.`),cwd:tV.default.dirname(t),onFileWillChange:t=>hj(a,t,o)}),await hR(t,n,r,a)}catch(r){try{var c=a;let t=[];for(let{path:r,content:i}of c)try{null===i?(0,t$.existsSync)(r)&&(0,t$.rmSync)(r):(0,t$.writeFileSync)(r,i,"utf-8")}catch(i){t.push(`${r}: ${i instanceof Error?i.message:String(i)}`)}if(t.length>0)throw Error(`Failed to restore ${t.length} file(s) during rollback: ${t.join("; ")}`)}catch(r){console.error(`${hw} Failed to fully roll back config files after a failed update of ${t}; some files may be left in a partially-restored state`,{configFilePath:t,restoreError:r instanceof Error?r.message:String(r)})}throw r}}async function hO(t,r){hk(t,r)}async function hD(t){let r=function(){let t=process.env.STACK_CONFIG_UPDATE_AGENT_TIMEOUT_MS;if(null==t||""===t.trim())return 12e4;let r=Number(t);if(!Number.isFinite(r)||r<=0)throw Error(`Invalid STACK_CONFIG_UPDATE_AGENT_TIMEOUT_MS: ${JSON.stringify(t)}. Expected a positive number of milliseconds.`);return r}(),i=new Set;try{await hS({prompt:t.prompt,cwd:t.cwd,allowedTools:["Read","Write","Edit","Glob","Grep"],strictIsolation:!0,timeoutMs:r,stderr:t=>{console.warn(`${hw} [agent] ${t}`)},onPreToolUse:r=>{var s,n,a;let o=(s=r.tool_name,n=r.tool_input,a=t.cwd,h_.has(s)&&"object"==typeof n&&null!==n&&"file_path"in n&&"string"==typeof n.file_path?tV.default.isAbsolute(n.file_path)?n.file_path:tV.default.resolve(a,n.file_path):null);return null==o?{continue:!0}:hP(t.cwd,o)?(t.onFileWillChange?.(o),{continue:!0}):(i.add(o),{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`Refusing to modify ${o}: config updates may only change files inside the config directory.`}})}})}catch(t){if(t instanceof hT)throw Error(`Config update agent timed out after ${r}ms. It was unable to apply the config changes to the file.`);if(t instanceof hE)throw Error(`${t.message} It was unable to apply the config changes to the file.`);throw t}if(i.size>0)throw Error(`Config update agent tried to modify ${i.size} file(s) outside the config directory, which is not allowed: ${[...i].join(", ")}. The config was not updated.`)}function hj(t,r,i){let s=tV.default.resolve(r);i.has(s)||(i.add(s),t.push({path:s,content:(0,t$.existsSync)(s)?(0,t$.readFileSync)(s,"utf-8"):null}))}async function hL(t){try{return(await hI(t)).config}catch(r){return console.warn(`${hw} Could not evaluate config for validation baseline; will fall back to a structural check`,{configFilePath:t,error:r instanceof Error?r.message:String(r)}),null}}async function hR(t,r,i,s){if(null!=r){let s=hF(tM(r,i));if(!function t(r,i){if(r===i)return!0;if(null===r||null===i)return r===i;if(Array.isArray(r)||Array.isArray(i))return!!Array.isArray(r)&&!!Array.isArray(i)&&r.length===i.length&&r.every((r,s)=>t(r,i[s]));if("object"==typeof r&&"object"==typeof i){let s=Object.entries(r),n=new Map(Object.entries(i));return s.length===n.size&&s.every(([r,i])=>n.has(r)&&t(i,n.get(r)))}return!1}(hF((await hI(t)).config),s))throw Error(`Config update validation failed for ${t}: the updated file does not evaluate to the expected configuration.`);return}if(hM(i).length>0&&!s.some(({path:t,content:r})=>((0,t$.existsSync)(t)?(0,t$.readFileSync)(t,"utf-8"):null)!==r)&&console.warn(`${hw} Agent did not modify any file for ${t}; assuming values are already up to date.`),!function(t,r){try{return tW(t,r),!0}catch{return/\bexport\s+const\s+config\b/.test(t)}}((0,t$.readFileSync)(t,"utf-8"),t))throw Error(`Config update validation failed for ${t}: the updated file no longer exports a valid \`config\`.`)}function hM(t){let r=[],i=(t,s)=>{for(let[n,a]of Object.entries(s)){let s=""===t?n:`${t}.${n}`;void 0!==a&&(null!==a&&"object"==typeof a&&!Array.isArray(a)&&Object.keys(a).length>0?i(s,a):r.push({path:s,value:a}))}};return i("",t),r}function hF(t){let r=[],i=tB(t,{onDotIntoNonObject:"ignore",onDotIntoNull:"empty-object",droppedKeys:r});if(r.length>0)throw Error(`Config update has conflicting keys that would be dropped during normalization: ${r.map(t=>JSON.stringify(t)).join(", ")}`);return i}var hB=t.i(716571),hU=t.i(572004);let h$="[Stack RDE]";class hV extends Error{constructor(t,r){super(`Could not connect to the Hexclave API at ${t}. Make sure the backend for this development environment is running and reachable.`,{cause:r}),this.name="RemoteDevelopmentEnvironmentApiUnavailableError"}}let hK=globalThis;function hq(){return(0,hB.assertRemoteDevelopmentEnvironmentEnabled)(),hK.__stackRemoteDevelopmentEnvironment??={sessions:new Map,watchers:new Map,syncTimers:new Map,syncErrors:new Map,synchronouslyUpdatingConfigFiles:new Set,shutdownTimerStarted:!1,startedAtMs:performance.now(),activeOperations:0,hasClosedSession:!1},hK.__stackRemoteDevelopmentEnvironment}function hz(t,r){null==r?console.log(`${h$} ${t}`):console.log(`${h$} ${t}`,r)}function hW(t,r){null==r?console.warn(`${h$} ${t}`):console.warn(`${h$} ${t}`,r)}function hH(t,r){let i;if((i=(0,x.errorToNiceString)(r)).includes("ECONNREFUSED")||i.includes("ECONNRESET")||i.includes("ETIMEDOUT")||i.includes("ENOTFOUND")||i.includes("fetch failed"))throw new hV(t,r);throw r}function hJ(t,r){let i=hq();i.activeOperations+=1,hz(`Started ${t}`,{...r,activeOperations:i.activeOperations});let s=!1;return()=>{s||(s=!0,i.activeOperations-=1,hz(`Finished ${t}`,{...r,activeOperations:i.activeOperations}))}}function hY(t,r){return new tO({projectId:"internal",publishableClientKey:function(){let t=process.env.STACK_CLI_PUBLISHABLE_CLIENT_KEY??(0,v.getPublicEnvVar)("NEXT_PUBLIC_STACK_PUBLISHABLE_CLIENT_KEY");if(null==t||0===t.length)throw Error("Missing internal publishable client key for remote development environment dashboard.");return t}(),baseUrl:t,tokenStore:null==r?"memory":{refreshToken:r,accessToken:""},noAutomaticPrefetch:!0})}async function hX(t){hz("Ensuring development-environment project exists",{apiBaseUrl:t.apiBaseUrl,configFilePath:t.configFilePath,hasExistingAnonymousSession:null!=t.anonymousRefreshToken});let r=hY(t.apiBaseUrl,t.anonymousRefreshToken),i=await r.getUser({or:"anonymous"}),s=(await i.getAuthJson()).refreshToken??(()=>{throw Error("Anonymous session did not return a refresh token.")})(),n=(0,hU.readRemoteDevelopmentEnvironmentState)().projectsByConfigPath[t.configFilePath],a=await i.listOwnedProjects(),o=null==n?void 0:a.find(t=>t.id===n.projectId);if(null!=n&&null!=o){let r={...n,apiBaseUrl:t.apiBaseUrl,updatedAtMillis:Date.now()};return(0,hU.updateRemoteDevelopmentEnvironmentState)(i=>({...i,anonymousRefreshToken:s,anonymousApiBaseUrl:t.apiBaseUrl,projectsByConfigPath:{...i.projectsByConfigPath,[t.configFilePath]:r}})),hz("Reusing stored development-environment project",{projectId:r.projectId,teamId:r.teamId,configFilePath:t.configFilePath}),{anonymousRefreshToken:s,project:r}}let l=(0,tV.basename)((0,tV.dirname)(t.configFilePath))||"Project";hz("Creating new development-environment team and project",{label:l,configFilePath:t.configFilePath});let p=await i.createTeam({displayName:`Development Environment: ${l}`}),u=await i.createProject({displayName:"Development Environment Project",description:`Development environment for ${l}`,teamId:p.id,isProductionMode:!1,isDevelopmentEnvironment:!0}),c=await u.app.createInternalApiKey({description:`Development environment key for ${l}`,expiresAt:new Date("2099-12-31T23:59:59Z"),hasPublishableClientKey:!0,hasSecretServerKey:!0,hasSuperSecretAdminKey:!1});if(null==c.publishableClientKey||null==c.secretServerKey)throw Error("Development environment API key response did not include the expected keys.");let d={projectId:u.id,teamId:p.id,publishableClientKey:c.publishableClientKey,secretServerKey:c.secretServerKey,apiBaseUrl:t.apiBaseUrl,updatedAtMillis:Date.now()};return hz("Created development-environment project",{projectId:d.projectId,teamId:d.teamId,configFilePath:t.configFilePath}),(0,hU.updateRemoteDevelopmentEnvironmentState)(r=>({...r,anonymousRefreshToken:s,anonymousApiBaseUrl:t.apiBaseUrl,projectsByConfigPath:{...r.projectsByConfigPath,[t.configFilePath]:d}})),{anonymousRefreshToken:s,project:d}}async function hG(){let t=(0,hU.readRemoteDevelopmentEnvironmentState)();if(null==t.anonymousRefreshToken)throw Error("Remote development environment has no anonymous session yet.");let r=t.anonymousApiBaseUrl??Object.values(t.projectsByConfigPath)[0]?.apiBaseUrl;if(null==r)throw Error("Remote development environment has no API base URL yet.");let i=hY(r,t.anonymousRefreshToken),s=await i.getUser({or:"anonymous"}),n=(await s.getAuthJson()).accessToken??(()=>{throw Error("Remote development environment anonymous session did not return an access token.")})(),a=I.AccessToken.createIfValid(n)??(()=>{throw Error("Remote development environment anonymous session returned an invalid access token.")})();return{accessToken:n,expiresAtMillis:a.expiresAt.getTime(),issuedAtMillis:a.issuedAt.getTime(),userId:s.id}}async function hZ(t,r){let i=r&&"completed"===t.onboardingStatus?"config_choice":r?t.onboardingStatus:"completed",s=await (function(t){if(null==t||"object"!=typeof t)throw Error("The Stack app instance is unavailable.");let r=Reflect.get(t,T);if(!(null!=r&&"object"==typeof r&&"sendRequest"in r&&"function"==typeof r.sendRequest))throw Error("The Stack app cannot send remote development environment onboarding updates.");return r})(t.app).sendRequest("/internal/projects/current",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(r?{onboarding_status:i}:{onboarding_status:i,onboarding_state:null})},"admin");if(!s.ok)throw Error(`Failed to sync development-environment project onboarding status (${s.status}): ${await s.text()}`);return i}async function hQ(t){var r;let i=(0,hU.readRemoteDevelopmentEnvironmentState)(),s=i.projectsByConfigPath[t];if(null==s||null==i.anonymousRefreshToken)return void hW("Skipping config sync because local state is incomplete",{configFilePath:t,hasProject:null!=s,hasAnonymousRefreshToken:null!=i.anonymousRefreshToken});let{config:n,showOnboarding:a}=await hI(t),o=(r=JSON.stringify({config:n,showOnboarding:a,syncFormatVersion:2}),(0,tU.createHash)("sha256").update(r).digest("hex")),l=hY(s.apiBaseUrl,i.anonymousRefreshToken),p=await l.getUser({or:"anonymous"}),u=(await p.listOwnedProjects()).find(t=>t.id===s.projectId);if(null==u)return void hW("Skipping config sync because the project is not owned by the anonymous user",{projectId:s.projectId,configFilePath:t});let c=await hZ(u,a);return s.lastSyncedConfigHash===o||(hz("Syncing config to development-environment project",{projectId:s.projectId,configFilePath:t,showOnboarding:a}),await u.replaceConfigOverride("branch",n),(0,hU.updateRemoteDevelopmentEnvironmentState)(r=>({...r,projectsByConfigPath:{...r.projectsByConfigPath,[t]:{...s,lastSyncedConfigHash:o,updatedAtMillis:Date.now()}}})),hz("Synced config to development-environment project",{projectId:s.projectId,configFilePath:t,showOnboarding:a,onboardingStatus:c})),c}function h0(t){let r=hq();if(r.synchronouslyUpdatingConfigFiles.has(t))return void hz("Skipping async config sync during synchronous dashboard update",{configFilePath:t});let i=r.syncTimers.get(t);null!=i&&clearTimeout(i),hz("Scheduling config sync after local file change",{configFilePath:t,debounceMs:500});let s=setTimeout(()=>{r.syncTimers.delete(t),(0,E.runAsynchronously)(async()=>{await hQ(t),r.syncErrors.delete(t)},{onError:i=>{hW("Config sync failed",{configFilePath:t,error:(0,x.errorToNiceString)(i)}),r.syncErrors.set(t,i)}})},500);s.unref(),r.syncTimers.set(t,s)}async function h1(t){let r=hq(),i=r.syncTimers.get(t);null!=i&&(clearTimeout(i),r.syncTimers.delete(t));let s=await hQ(t);return r.syncErrors.delete(t),s}async function h2(t){if((0,hB.assertRemoteDevelopmentEnvironmentEnabled)(),(0,hB.assertRemoteDevelopmentEnvironmentEnabled)(),!hq().shutdownTimerStarted){let t;hz("Starting local dashboard lifecycle"),(t=hq()).shutdownTimerStarted||(t.shutdownTimerStarted=!0,hz("Started shutdown timer",{sessionTtlMs:25e3,startupEmptySessionGraceMs:2e4}),setInterval(()=>{let r=performance.now();for(let[i,s]of t.sessions.entries()){let n=s.receivedFirstHeartbeat?25e3:3e5;r-s.lastHeartbeatMs>n&&(hW("Expiring stale session",{sessionId:i,ageMs:Math.round(r-s.lastHeartbeatMs),activeSessionsBeforeExpire:t.sessions.size,receivedFirstHeartbeat:s.receivedFirstHeartbeat}),t.sessions.delete(i))}if(0===t.sessions.size&&0===t.activeOperations&&(t.hasClosedSession||r-t.startedAtMs>2e4)){for(let i of(hz("No active sessions remain; shutting down local dashboard",{uptimeMs:Math.round(r-t.startedAtMs),watchedConfigFiles:t.watchers.size,pendingSyncs:t.syncTimers.size,syncErrors:t.syncErrors.size,activeOperations:t.activeOperations,hasClosedSession:t.hasClosedSession}),t.watchers.values()))i.close();process.exit(0)}},5e3).unref())}let r=function(t){let r=tV.default.resolve(t);if(/\.(ts|js|mjs|cjs)$/i.test(r))return r;let i=tV.default.join(r,"hexclave.config.ts"),s=tV.default.join(r,"stack.config.ts");return(0,t$.existsSync)(i)?i:(0,t$.existsSync)(s)?s:i}(t.configPath),i=hJ("session registration",{apiBaseUrl:t.apiBaseUrl,configFilePath:r});try{hz("Registering CLI session",{apiBaseUrl:t.apiBaseUrl,configFilePath:r}),hC(r);let i=(0,hU.readRemoteDevelopmentEnvironmentState)(),{project:s}=await hX({apiBaseUrl:t.apiBaseUrl,configFilePath:r,anonymousRefreshToken:i.anonymousRefreshToken}).catch(r=>hH(t.apiBaseUrl,r));!function(t){let r=hq();if(r.watchers.has(t))return;let i=(0,t$.watch)(t,{persistent:!1},()=>{h0(t)});r.watchers.set(t,i),hz("Started watching config file",{configFilePath:t,watchedConfigFiles:r.watchers.size})}(r);let n=await h1(r).catch(r=>hH(t.apiBaseUrl,r)),a=(0,tU.randomUUID)();return hq().sessions.set(a,{configFilePath:r,lastHeartbeatMs:performance.now(),receivedFirstHeartbeat:!1}),hz("Registered CLI session",{sessionId:a,projectId:s.projectId,activeSessions:hq().sessions.size,configFilePath:r}),{sessionId:a,env:{STACK_PROJECT_ID:s.projectId,NEXT_PUBLIC_STACK_PROJECT_ID:s.projectId,VITE_STACK_PROJECT_ID:s.projectId,EXPO_PUBLIC_STACK_PROJECT_ID:s.projectId,STACK_PUBLISHABLE_CLIENT_KEY:s.publishableClientKey,NEXT_PUBLIC_STACK_PUBLISHABLE_CLIENT_KEY:s.publishableClientKey,VITE_STACK_PUBLISHABLE_CLIENT_KEY:s.publishableClientKey,EXPO_PUBLIC_STACK_PUBLISHABLE_CLIENT_KEY:s.publishableClientKey,STACK_SECRET_SERVER_KEY:s.secretServerKey,STACK_API_URL:s.apiBaseUrl,NEXT_PUBLIC_STACK_API_URL:s.apiBaseUrl,VITE_STACK_API_URL:s.apiBaseUrl,EXPO_PUBLIC_STACK_API_URL:s.apiBaseUrl},projectId:s.projectId,onboardingOutstanding:null!=n&&"completed"!==n}}finally{i()}}async function h4(t){(0,hB.assertRemoteDevelopmentEnvironmentEnabled)();let r=hJ("config update",{sessionId:t.sessionId,projectId:t.projectId});try{let r=hq(),i=(()=>{if(null!=t.sessionId)return r.sessions.get(t.sessionId);if(null==t.projectId)throw Error("Remote development environment config update requires a session ID or project ID.");for(let i of r.sessions.values()){let r=(0,hU.readRemoteDevelopmentEnvironmentState)().projectsByConfigPath[i.configFilePath];if(r?.projectId===t.projectId)return i}})();if(null==i)throw Error("Remote development environment session is not active.");let s=i.configFilePath;if(hz("Applying config update from local dashboard",{sessionId:t.sessionId,projectId:t.projectId,configFilePath:s}),!1===t.waitForSync){let r=(await hI(s)).config;await hO(s,tM(r,t.configUpdate)),h0(s)}else{r.synchronouslyUpdatingConfigFiles.add(s);try{await hN(s,t.configUpdate)}finally{setTimeout(()=>{r.synchronouslyUpdatingConfigFiles.delete(s)},500).unref()}await h1(s)}hz("Applied config update from local dashboard",{sessionId:t.sessionId,projectId:t.projectId,configFilePath:s,waitForSync:t.waitForSync??!0})}finally{r()}}t.s(["RemoteDevelopmentEnvironmentApiUnavailableError",0,hV,"applyRemoteDevelopmentEnvironmentConfigUpdate",0,h4,"closeRemoteDevelopmentEnvironmentSession",0,function(t){(0,hB.assertRemoteDevelopmentEnvironmentEnabled)();let r=hq(),i=r.sessions.delete(t);i&&(r.hasClosedSession=!0),hz("Closed CLI session",{sessionId:t,existed:i,activeSessions:r.sessions.size})},"getPendingRemoteDevelopmentEnvironmentBrowserSecretConfirmationCode",0,function(){return(0,hB.assertRemoteDevelopmentEnvironmentEnabled)(),(0,tK.peekRemoteDevelopmentEnvironmentBrowserSecretConfirmationCodeForCli)()},"getRemoteDevelopmentEnvironmentAccessToken",0,hG,"getRemoteDevelopmentEnvironmentHealth",0,function(){let t;(0,hB.assertRemoteDevelopmentEnvironmentEnabled)();let r=hq().sessions.values().next().value;if(null!=r)return{healthy:!0,configFilePath:r.configFilePath};let i=(0,hU.readRemoteDevelopmentEnvironmentState)(),s=-1/0;for(let[r,n]of Object.entries(i.projectsByConfigPath))null==n||n.updatedAtMillis<=s||(t=r,s=n.updatedAtMillis);return{healthy:!1,configFilePath:t}},"heartbeatRemoteDevelopmentEnvironmentSession",0,function(t){(0,hB.assertRemoteDevelopmentEnvironmentEnabled)();let r=hq().sessions.get(t);return null==r?(hW("Received heartbeat for unknown session",{sessionId:t}),!1):(r.lastHeartbeatMs=performance.now(),r.receivedFirstHeartbeat=!0,!0)},"registerRemoteDevelopmentEnvironmentSession",0,h2],656340)}];
|
|
427
|
+
- Do not run any shell commands and do not create files other than what is required to apply these changes.`),cwd:tK.default.dirname(t),onFileWillChange:t=>hL(a,t,o)}),await hM(t,n,r,a)}catch(r){try{var c=a;let t=[];for(let{path:r,content:i}of c)try{null===i?(0,tV.existsSync)(r)&&(0,tV.rmSync)(r):(0,tV.writeFileSync)(r,i,"utf-8")}catch(i){t.push(`${r}: ${i instanceof Error?i.message:String(i)}`)}if(t.length>0)throw Error(`Failed to restore ${t.length} file(s) during rollback: ${t.join("; ")}`)}catch(r){console.error(`${hC} Failed to fully roll back config files after a failed update of ${t}; some files may be left in a partially-restored state`,{configFilePath:t,restoreError:r instanceof Error?r.message:String(r)})}throw r}}async function hD(t,r){hN(t,r)}async function hj(t){let r=function(){let t=process.env.STACK_CONFIG_UPDATE_AGENT_TIMEOUT_MS;if(null==t||""===t.trim())return 12e4;let r=Number(t);if(!Number.isFinite(r)||r<=0)throw Error(`Invalid STACK_CONFIG_UPDATE_AGENT_TIMEOUT_MS: ${JSON.stringify(t)}. Expected a positive number of milliseconds.`);return r}(),i=new Set;try{await h_({prompt:t.prompt,cwd:t.cwd,allowedTools:["Read","Write","Edit","Glob","Grep"],strictIsolation:!0,timeoutMs:r,stderr:t=>{console.warn(`${hC} [agent] ${t}`)},onPreToolUse:r=>{var s,n,a;let o=(s=r.tool_name,n=r.tool_input,a=t.cwd,hP.has(s)&&"object"==typeof n&&null!==n&&"file_path"in n&&"string"==typeof n.file_path?tK.default.isAbsolute(n.file_path)?n.file_path:tK.default.resolve(a,n.file_path):null);return null==o?{continue:!0}:hA(t.cwd,o)?(t.onFileWillChange?.(o),{continue:!0}):(i.add(o),{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`Refusing to modify ${o}: config updates may only change files inside the config directory.`}})}})}catch(t){if(t instanceof hE)throw Error(`Config update agent timed out after ${r}ms. It was unable to apply the config changes to the file.`);if(t instanceof hS)throw Error(`${t.message} It was unable to apply the config changes to the file.`);throw t}if(i.size>0)throw Error(`Config update agent tried to modify ${i.size} file(s) outside the config directory, which is not allowed: ${[...i].join(", ")}. The config was not updated.`)}function hL(t,r,i){let s=tK.default.resolve(r);i.has(s)||(i.add(s),t.push({path:s,content:(0,tV.existsSync)(s)?(0,tV.readFileSync)(s,"utf-8"):null}))}async function hR(t){try{return(await hk(t)).config}catch(r){return console.warn(`${hC} Could not evaluate config for validation baseline; will fall back to a structural check`,{configFilePath:t,error:r instanceof Error?r.message:String(r)}),null}}async function hM(t,r,i,s){if(null!=r){let s=hB(tF(r,i));if(!function t(r,i){if(r===i)return!0;if(null===r||null===i)return r===i;if(Array.isArray(r)||Array.isArray(i))return!!Array.isArray(r)&&!!Array.isArray(i)&&r.length===i.length&&r.every((r,s)=>t(r,i[s]));if("object"==typeof r&&"object"==typeof i){let s=Object.entries(r),n=new Map(Object.entries(i));return s.length===n.size&&s.every(([r,i])=>n.has(r)&&t(i,n.get(r)))}return!1}(hB((await hk(t)).config),s))throw Error(`Config update validation failed for ${t}: the updated file does not evaluate to the expected configuration.`);return}if(hF(i).length>0&&!s.some(({path:t,content:r})=>((0,tV.existsSync)(t)?(0,tV.readFileSync)(t,"utf-8"):null)!==r)&&console.warn(`${hC} Agent did not modify any file for ${t}; assuming values are already up to date.`),!function(t,r){try{return tH(t,r),!0}catch{return/\bexport\s+const\s+config\b/.test(t)}}((0,tV.readFileSync)(t,"utf-8"),t))throw Error(`Config update validation failed for ${t}: the updated file no longer exports a valid \`config\`.`)}function hF(t){let r=[],i=(t,s)=>{for(let[n,a]of Object.entries(s)){let s=""===t?n:`${t}.${n}`;void 0!==a&&(null!==a&&"object"==typeof a&&!Array.isArray(a)&&Object.keys(a).length>0?i(s,a):r.push({path:s,value:a}))}};return i("",t),r}function hB(t){let r=[],i=tU(t,{onDotIntoNonObject:"ignore",onDotIntoNull:"empty-object",droppedKeys:r});if(r.length>0)throw Error(`Config update has conflicting keys that would be dropped during normalization: ${r.map(t=>JSON.stringify(t)).join(", ")}`);return i}var hU=t.i(716571),h$=t.i(572004);let hV="[Stack RDE]";class hK extends Error{constructor(t,r){super(`Could not connect to the Hexclave API at ${t}. Make sure the backend for this development environment is running and reachable.`,{cause:r}),this.name="RemoteDevelopmentEnvironmentApiUnavailableError"}}let hq=globalThis;function hz(){return(0,hU.assertRemoteDevelopmentEnvironmentEnabled)(),hq.__stackRemoteDevelopmentEnvironment??={sessions:new Map,watchers:new Map,syncTimers:new Map,syncErrors:new Map,synchronouslyUpdatingConfigFiles:new Set,shutdownTimerStarted:!1,startedAtMs:performance.now(),activeOperations:0,hasClosedSession:!1},hq.__stackRemoteDevelopmentEnvironment}function hW(t,r){null==r?console.log(`${hV} ${t}`):console.log(`${hV} ${t}`,r)}function hH(t,r){null==r?console.warn(`${hV} ${t}`):console.warn(`${hV} ${t}`,r)}function hJ(t,r){let i;if((i=(0,x.errorToNiceString)(r)).includes("ECONNREFUSED")||i.includes("ECONNRESET")||i.includes("ETIMEDOUT")||i.includes("ENOTFOUND")||i.includes("fetch failed"))throw new hK(t,r);throw r}function hY(t,r){let i=hz();i.activeOperations+=1,hW(`Started ${t}`,{...r,activeOperations:i.activeOperations});let s=!1;return()=>{s||(s=!0,i.activeOperations-=1,hW(`Finished ${t}`,{...r,activeOperations:i.activeOperations}))}}function hX(t,r){return new tD({projectId:"internal",publishableClientKey:function(){let t=process.env.STACK_CLI_PUBLISHABLE_CLIENT_KEY??(0,v.getPublicEnvVar)("NEXT_PUBLIC_STACK_PUBLISHABLE_CLIENT_KEY");if(null==t||0===t.length)throw Error("Missing internal publishable client key for remote development environment dashboard.");return t}(),baseUrl:t,tokenStore:null==r?"memory":{refreshToken:r,accessToken:""},noAutomaticPrefetch:!0})}async function hG(t){hW("Ensuring development-environment project exists",{apiBaseUrl:t.apiBaseUrl,configFilePath:t.configFilePath,hasExistingAnonymousSession:null!=t.anonymousRefreshToken});let r=hX(t.apiBaseUrl,t.anonymousRefreshToken),i=await r.getUser({or:"anonymous"}),s=(await i.getAuthJson()).refreshToken??(()=>{throw Error("Anonymous session did not return a refresh token.")})(),n=(0,h$.readRemoteDevelopmentEnvironmentState)().projectsByConfigPath[t.configFilePath],a=await i.listOwnedProjects(),o=null==n?void 0:a.find(t=>t.id===n.projectId);if(null!=n&&null!=o){let r={...n,apiBaseUrl:t.apiBaseUrl,updatedAtMillis:Date.now()};return(0,h$.updateRemoteDevelopmentEnvironmentState)(i=>({...i,anonymousRefreshToken:s,anonymousApiBaseUrl:t.apiBaseUrl,projectsByConfigPath:{...i.projectsByConfigPath,[t.configFilePath]:r}})),hW("Reusing stored development-environment project",{projectId:r.projectId,teamId:r.teamId,configFilePath:t.configFilePath}),{anonymousRefreshToken:s,project:r}}let l=(0,tK.basename)((0,tK.dirname)(t.configFilePath))||"Project";hW("Creating new development-environment team and project",{label:l,configFilePath:t.configFilePath});let p=await i.createTeam({displayName:`Development Environment: ${l}`}),u=await i.createProject({displayName:"Development Environment Project",description:`Development environment for ${l}`,teamId:p.id,isProductionMode:!1,isDevelopmentEnvironment:!0}),c=await u.app.createInternalApiKey({description:`Development environment key for ${l}`,expiresAt:new Date("2099-12-31T23:59:59Z"),hasPublishableClientKey:!0,hasSecretServerKey:!0,hasSuperSecretAdminKey:!1});if(null==c.publishableClientKey||null==c.secretServerKey)throw Error("Development environment API key response did not include the expected keys.");let d={projectId:u.id,teamId:p.id,publishableClientKey:c.publishableClientKey,secretServerKey:c.secretServerKey,apiBaseUrl:t.apiBaseUrl,updatedAtMillis:Date.now()};return hW("Created development-environment project",{projectId:d.projectId,teamId:d.teamId,configFilePath:t.configFilePath}),(0,h$.updateRemoteDevelopmentEnvironmentState)(r=>({...r,anonymousRefreshToken:s,anonymousApiBaseUrl:t.apiBaseUrl,projectsByConfigPath:{...r.projectsByConfigPath,[t.configFilePath]:d}})),{anonymousRefreshToken:s,project:d}}async function hZ(){let t=(0,h$.readRemoteDevelopmentEnvironmentState)();if(null==t.anonymousRefreshToken)throw Error("Remote development environment has no anonymous session yet.");let r=t.anonymousApiBaseUrl??Object.values(t.projectsByConfigPath)[0]?.apiBaseUrl;if(null==r)throw Error("Remote development environment has no API base URL yet.");let i=hX(r,t.anonymousRefreshToken),s=await i.getUser({or:"anonymous"}),n=(await s.getAuthJson()).accessToken??(()=>{throw Error("Remote development environment anonymous session did not return an access token.")})(),a=I.AccessToken.createIfValid(n)??(()=>{throw Error("Remote development environment anonymous session returned an invalid access token.")})();return{accessToken:n,expiresAtMillis:a.expiresAt.getTime(),issuedAtMillis:a.issuedAt.getTime(),userId:s.id}}async function hQ(t,r){let i=r&&"completed"===t.onboardingStatus?"config_choice":r?t.onboardingStatus:"completed",s=await (function(t){if(null==t||"object"!=typeof t)throw Error("The Stack app instance is unavailable.");let r=Reflect.get(t,T);if(!(null!=r&&"object"==typeof r&&"sendRequest"in r&&"function"==typeof r.sendRequest))throw Error("The Stack app cannot send remote development environment onboarding updates.");return r})(t.app).sendRequest("/internal/projects/current",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(r?{onboarding_status:i}:{onboarding_status:i,onboarding_state:null})},"admin");if(!s.ok)throw Error(`Failed to sync development-environment project onboarding status (${s.status}): ${await s.text()}`);return i}async function h0(t){var r;let i=(0,h$.readRemoteDevelopmentEnvironmentState)(),s=i.projectsByConfigPath[t];if(null==s||null==i.anonymousRefreshToken)return void hH("Skipping config sync because local state is incomplete",{configFilePath:t,hasProject:null!=s,hasAnonymousRefreshToken:null!=i.anonymousRefreshToken});let{config:n,showOnboarding:a}=await hk(t),o=(r=JSON.stringify({config:n,showOnboarding:a,syncFormatVersion:2}),(0,t$.createHash)("sha256").update(r).digest("hex")),l=hX(s.apiBaseUrl,i.anonymousRefreshToken),p=await l.getUser({or:"anonymous"}),u=(await p.listOwnedProjects()).find(t=>t.id===s.projectId);if(null==u)return void hH("Skipping config sync because the project is not owned by the anonymous user",{projectId:s.projectId,configFilePath:t});let c=await hQ(u,a);return s.lastSyncedConfigHash===o||(hW("Syncing config to development-environment project",{projectId:s.projectId,configFilePath:t,showOnboarding:a}),await u.replaceConfigOverride("branch",n),(0,h$.updateRemoteDevelopmentEnvironmentState)(r=>({...r,projectsByConfigPath:{...r.projectsByConfigPath,[t]:{...s,lastSyncedConfigHash:o,updatedAtMillis:Date.now()}}})),hW("Synced config to development-environment project",{projectId:s.projectId,configFilePath:t,showOnboarding:a,onboardingStatus:c})),c}function h1(t){let r=hz();if(r.synchronouslyUpdatingConfigFiles.has(t))return void hW("Skipping async config sync during synchronous dashboard update",{configFilePath:t});let i=r.syncTimers.get(t);null!=i&&clearTimeout(i),hW("Scheduling config sync after local file change",{configFilePath:t,debounceMs:500});let s=setTimeout(()=>{r.syncTimers.delete(t),(0,E.runAsynchronously)(async()=>{await h0(t),r.syncErrors.delete(t)},{onError:i=>{hH("Config sync failed",{configFilePath:t,error:(0,x.errorToNiceString)(i)}),r.syncErrors.set(t,i)}})},500);s.unref(),r.syncTimers.set(t,s)}async function h2(t){let r=hz(),i=r.syncTimers.get(t);null!=i&&(clearTimeout(i),r.syncTimers.delete(t));let s=await h0(t);return r.syncErrors.delete(t),s}async function h4(t){if((0,hU.assertRemoteDevelopmentEnvironmentEnabled)(),(0,hU.assertRemoteDevelopmentEnvironmentEnabled)(),!hz().shutdownTimerStarted){let t;hW("Starting local dashboard lifecycle"),(t=hz()).shutdownTimerStarted||(t.shutdownTimerStarted=!0,hW("Started shutdown timer",{sessionTtlMs:25e3,startupEmptySessionGraceMs:2e4}),setInterval(()=>{let r=performance.now();for(let[i,s]of t.sessions.entries()){let n=s.receivedFirstHeartbeat?25e3:3e5;r-s.lastHeartbeatMs>n&&(hH("Expiring stale session",{sessionId:i,ageMs:Math.round(r-s.lastHeartbeatMs),activeSessionsBeforeExpire:t.sessions.size,receivedFirstHeartbeat:s.receivedFirstHeartbeat}),t.sessions.delete(i))}if(0===t.sessions.size&&0===t.activeOperations&&(t.hasClosedSession||r-t.startedAtMs>2e4)){for(let i of(hW("No active sessions remain; shutting down local dashboard",{uptimeMs:Math.round(r-t.startedAtMs),watchedConfigFiles:t.watchers.size,pendingSyncs:t.syncTimers.size,syncErrors:t.syncErrors.size,activeOperations:t.activeOperations,hasClosedSession:t.hasClosedSession}),t.watchers.values()))i.close();process.exit(0)}},5e3).unref())}let r=function(t){let r=tK.default.resolve(t);if(/\.(ts|js|mjs|cjs)$/i.test(r))return r;let i=tK.default.join(r,"hexclave.config.ts"),s=tK.default.join(r,"stack.config.ts");return(0,tV.existsSync)(i)?i:(0,tV.existsSync)(s)?s:i}(t.configPath),i=hY("session registration",{apiBaseUrl:t.apiBaseUrl,configFilePath:r});try{hW("Registering CLI session",{apiBaseUrl:t.apiBaseUrl,configFilePath:r}),hI(r);let i=(0,h$.readRemoteDevelopmentEnvironmentState)(),{project:s}=await hG({apiBaseUrl:t.apiBaseUrl,configFilePath:r,anonymousRefreshToken:i.anonymousRefreshToken}).catch(r=>hJ(t.apiBaseUrl,r));!function(t){let r=hz();if(r.watchers.has(t))return;let i=(0,tV.watch)(t,{persistent:!1},()=>{h1(t)});r.watchers.set(t,i),hW("Started watching config file",{configFilePath:t,watchedConfigFiles:r.watchers.size})}(r);let n=await h2(r).catch(r=>hJ(t.apiBaseUrl,r)),a=(0,t$.randomUUID)();return hz().sessions.set(a,{configFilePath:r,lastHeartbeatMs:performance.now(),receivedFirstHeartbeat:!1}),hW("Registered CLI session",{sessionId:a,projectId:s.projectId,activeSessions:hz().sessions.size,configFilePath:r}),{sessionId:a,env:{STACK_PROJECT_ID:s.projectId,NEXT_PUBLIC_STACK_PROJECT_ID:s.projectId,VITE_STACK_PROJECT_ID:s.projectId,EXPO_PUBLIC_STACK_PROJECT_ID:s.projectId,STACK_PUBLISHABLE_CLIENT_KEY:s.publishableClientKey,NEXT_PUBLIC_STACK_PUBLISHABLE_CLIENT_KEY:s.publishableClientKey,VITE_STACK_PUBLISHABLE_CLIENT_KEY:s.publishableClientKey,EXPO_PUBLIC_STACK_PUBLISHABLE_CLIENT_KEY:s.publishableClientKey,STACK_SECRET_SERVER_KEY:s.secretServerKey,STACK_API_URL:s.apiBaseUrl,NEXT_PUBLIC_STACK_API_URL:s.apiBaseUrl,VITE_STACK_API_URL:s.apiBaseUrl,EXPO_PUBLIC_STACK_API_URL:s.apiBaseUrl},projectId:s.projectId,onboardingOutstanding:null!=n&&"completed"!==n}}finally{i()}}async function h3(t){(0,hU.assertRemoteDevelopmentEnvironmentEnabled)();let r=hY("config update",{sessionId:t.sessionId,projectId:t.projectId});try{let r=hz(),i=(()=>{if(null!=t.sessionId)return r.sessions.get(t.sessionId);if(null==t.projectId)throw Error("Remote development environment config update requires a session ID or project ID.");for(let i of r.sessions.values()){let r=(0,h$.readRemoteDevelopmentEnvironmentState)().projectsByConfigPath[i.configFilePath];if(r?.projectId===t.projectId)return i}})();if(null==i)throw Error("Remote development environment session is not active.");let s=i.configFilePath;if(hW("Applying config update from local dashboard",{sessionId:t.sessionId,projectId:t.projectId,configFilePath:s}),!1===t.waitForSync){let r=(await hk(s)).config;await hD(s,tF(r,t.configUpdate)),h1(s)}else{r.synchronouslyUpdatingConfigFiles.add(s);try{await hO(s,t.configUpdate)}finally{setTimeout(()=>{r.synchronouslyUpdatingConfigFiles.delete(s)},500).unref()}await h2(s)}hW("Applied config update from local dashboard",{sessionId:t.sessionId,projectId:t.projectId,configFilePath:s,waitForSync:t.waitForSync??!0})}finally{r()}}t.s(["RemoteDevelopmentEnvironmentApiUnavailableError",0,hK,"applyRemoteDevelopmentEnvironmentConfigUpdate",0,h3,"closeRemoteDevelopmentEnvironmentSession",0,function(t){(0,hU.assertRemoteDevelopmentEnvironmentEnabled)();let r=hz(),i=r.sessions.delete(t);i&&(r.hasClosedSession=!0),hW("Closed CLI session",{sessionId:t,existed:i,activeSessions:r.sessions.size})},"getPendingRemoteDevelopmentEnvironmentBrowserSecretConfirmationCode",0,function(){return(0,hU.assertRemoteDevelopmentEnvironmentEnabled)(),(0,tq.peekRemoteDevelopmentEnvironmentBrowserSecretConfirmationCodeForCli)()},"getRemoteDevelopmentEnvironmentAccessToken",0,hZ,"getRemoteDevelopmentEnvironmentHealth",0,function(){let t;(0,hU.assertRemoteDevelopmentEnvironmentEnabled)();let r=hz().sessions.values().next().value;if(null!=r)return{healthy:!0,configFilePath:r.configFilePath};let i=(0,h$.readRemoteDevelopmentEnvironmentState)(),s=-1/0;for(let[r,n]of Object.entries(i.projectsByConfigPath))null==n||n.updatedAtMillis<=s||(t=r,s=n.updatedAtMillis);return{healthy:!1,configFilePath:t}},"heartbeatRemoteDevelopmentEnvironmentSession",0,function(t){(0,hU.assertRemoteDevelopmentEnvironmentEnabled)();let r=hz().sessions.get(t);return null==r?(hH("Received heartbeat for unknown session",{sessionId:t}),!1):(r.lastHeartbeatMs=performance.now(),r.receivedFirstHeartbeat=!0,!0)},"registerRemoteDevelopmentEnvironmentSession",0,h4],656340)}];
|
|
428
428
|
|
|
429
429
|
//# sourceMappingURL=_04as7p-._.js.map
|