fnloom 0.3.0 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +27 -20
- package/package.json +14 -11
- package/packages/build/package.json +2 -2
- package/packages/build/src/tests.ts +2 -2
- package/packages/cli/package.json +1 -1
- package/packages/cli/src/cli.ts +2 -2
- package/packages/cli/src/command.ts +2 -2
- package/packages/cli/src/commands/install.ts +1 -1
- package/packages/cli/src/commands/mcp.ts +6 -6
- package/packages/cli/src/commands/store.ts +3 -3
- package/packages/cli/src/hub.ts +25 -25
- package/packages/cli/src/index.ts +1 -1
- package/packages/cli/src/io.ts +2 -2
- package/packages/cli/src/local.ts +7 -7
- package/packages/cli/src/premade.ts +1 -1
- package/packages/core/package.json +4 -4
- package/packages/core/src/auto-pair.ts +1 -1
- package/packages/core/src/connections.ts +1 -14
- package/packages/core/src/context-graph.ts +1 -1
- package/packages/core/src/data.ts +1 -1
- package/packages/core/src/gin-a.ts +13 -2
- package/packages/core/src/https.ts +2 -2
- package/packages/core/src/identity.ts +1 -1
- package/packages/core/src/image-embeddings.ts +1 -1
- package/packages/core/src/index.ts +5 -7
- package/packages/core/src/link.ts +1 -1
- package/packages/core/src/manifest.ts +2 -2
- package/packages/core/src/mention-search.ts +1 -1
- package/packages/core/src/model-calls.ts +1 -1
- package/packages/core/src/package.ts +1 -1
- package/packages/core/src/ports.ts +2 -2
- package/packages/core/src/query.ts +1 -1
- package/packages/core/src/records/chat.ts +1 -1
- package/packages/core/src/records/runs.ts +1 -1
- package/packages/core/src/records/spend.ts +4 -0
- package/packages/core/src/registries.ts +9 -3
- package/packages/core/src/sso.ts +2 -2
- package/packages/core/src/stores.ts +1 -1
- package/packages/core/src/suggestions.ts +2 -2
- package/packages/core/src/system-pages.ts +32 -6
- package/packages/core/src/tables.ts +233 -0
- package/packages/core/src/visuals.ts +47 -139
- package/packages/core/src/web.ts +2 -2
- package/packages/core/src/widgets-v1.ts +78 -1
- package/packages/hub/package.json +13 -11
- package/packages/hub/src/api/admin-ops.ts +5 -5
- package/packages/hub/src/api/auth.ts +2 -2
- package/packages/hub/src/api/https.ts +6 -6
- package/packages/hub/src/api/identities.ts +1 -1
- package/packages/hub/src/api/reads.ts +1 -1
- package/packages/hub/src/api/secrets.ts +1 -1
- package/packages/hub/src/api/serve.ts +2 -2
- package/packages/hub/src/api/sso-route.ts +2 -2
- package/packages/hub/src/api/sso.ts +6 -6
- package/packages/hub/src/api/store-ops.ts +9 -2
- package/packages/hub/src/api/testing/rig.ts +1 -1
- package/packages/hub/src/api/tls.ts +2 -2
- package/packages/hub/src/api/web/auth.ts +1 -1
- package/packages/hub/src/api/web/find.ts +1 -1
- package/packages/hub/src/api/web/pages.ts +4 -3
- package/packages/hub/src/api/web/pickers.ts +4 -4
- package/packages/hub/src/boot/env.ts +82 -78
- package/packages/hub/src/boot/hub-fns.ts +1 -1
- package/packages/hub/src/boot/identity.ts +2 -2
- package/packages/hub/src/boot/index.ts +1 -1
- package/packages/hub/src/boot/info.ts +1 -1
- package/packages/hub/src/boot/keys.ts +6 -6
- package/packages/hub/src/boot/log.ts +4 -4
- package/packages/hub/src/boot/modules.ts +4 -4
- package/packages/hub/src/boot/services.ts +9 -9
- package/packages/hub/src/boot/start.ts +23 -23
- package/packages/hub/src/catalog/catalog.ts +3 -2
- package/packages/hub/src/chat/cache.ts +1 -1
- package/packages/hub/src/chat/chat.ts +1 -1
- package/packages/hub/src/chat/compare.ts +2 -2
- package/packages/hub/src/chat/deliveries.ts +1 -1
- package/packages/hub/src/chat/deps.ts +3 -3
- package/packages/hub/src/chat/enrich.ts +7 -7
- package/packages/hub/src/chat/env.ts +20 -20
- package/packages/hub/src/chat/mention-requests.ts +1 -1
- package/packages/hub/src/chat/mention-search.ts +1 -1
- package/packages/hub/src/chat/mentions.ts +3 -3
- package/packages/hub/src/chat/notifications.ts +2 -2
- package/packages/hub/src/chat/presence.ts +2 -2
- package/packages/hub/src/chat/sessions.ts +2 -2
- package/packages/hub/src/chat/suggestions.ts +8 -8
- package/packages/hub/src/chat/testing.ts +1 -1
- package/packages/hub/src/chat/turns.ts +6 -6
- package/packages/hub/src/chat/undo.ts +1 -1
- package/packages/hub/src/connections/create.ts +1 -1
- package/packages/hub/src/connections/env.ts +2 -2
- package/packages/hub/src/connections/service.ts +5 -9
- package/packages/hub/src/contextor/contextors.ts +9 -9
- package/packages/hub/src/contextor/crawl.ts +1 -1
- package/packages/hub/src/contextor/create.ts +5 -5
- package/packages/hub/src/contextor/dynamic.ts +5 -5
- package/packages/hub/src/contextor/env.ts +46 -46
- package/packages/hub/src/contextor/injected.ts +1 -1
- package/packages/hub/src/contextor/limits.ts +9 -9
- package/packages/hub/src/contextor/planner.ts +11 -11
- package/packages/hub/src/contextor/testing.ts +1 -1
- package/packages/hub/src/data/env.ts +3 -3
- package/packages/hub/src/data/service.ts +5 -5
- package/packages/hub/src/execution/agent.ts +8 -8
- package/packages/hub/src/execution/ai.ts +7 -7
- package/packages/hub/src/execution/create.ts +11 -6
- package/packages/hub/src/execution/env.ts +16 -16
- package/packages/hub/src/execution/executors.ts +2 -2
- package/packages/hub/src/execution/gateway.ts +1 -1
- package/packages/hub/src/execution/index.ts +1 -1
- package/packages/hub/src/execution/ledger.ts +2 -2
- package/packages/hub/src/execution/limits.ts +2 -2
- package/packages/hub/src/execution/models.ts +2 -2
- package/packages/hub/src/execution/ports.ts +1 -1
- package/packages/hub/src/execution/providers.ts +55 -11
- package/packages/hub/src/execution/queues.ts +6 -6
- package/packages/hub/src/execution/runs.ts +10 -10
- package/packages/hub/src/execution/stream-guard.ts +2 -2
- package/packages/hub/src/execution/testing.ts +5 -5
- package/packages/hub/src/execution/wire.ts +3 -3
- package/packages/hub/src/fns/auto.ts +2 -2
- package/packages/hub/src/fns/client-logs.ts +2 -2
- package/packages/hub/src/fns/create.ts +2 -2
- package/packages/hub/src/fns/decided.ts +2 -2
- package/packages/hub/src/fns/env.ts +14 -14
- package/packages/hub/src/fns/examples.ts +3 -3
- package/packages/hub/src/fns/facts.ts +5 -5
- package/packages/hub/src/fns/search.ts +5 -5
- package/packages/hub/src/graph/graph.ts +1 -1
- package/packages/hub/src/index/context-sections.ts +1 -1
- package/packages/hub/src/index/embedders.ts +3 -3
- package/packages/hub/src/index/env.ts +12 -12
- package/packages/hub/src/index/index.ts +1 -1
- package/packages/hub/src/index/indexer.ts +4 -4
- package/packages/hub/src/index/search.ts +1 -1
- package/packages/hub/src/index/testing.ts +2 -2
- package/packages/hub/src/link/build.ts +32 -32
- package/packages/hub/src/link/env.ts +14 -14
- package/packages/hub/src/link/grants.ts +10 -10
- package/packages/hub/src/link/lifecycle.ts +4 -4
- package/packages/hub/src/link/migrate-api.ts +55 -15
- package/packages/hub/src/link/pairing.ts +1 -1
- package/packages/hub/src/link/process.ts +1 -1
- package/packages/hub/src/link/rig.ts +12 -12
- package/packages/hub/src/link/supervisor.ts +1 -1
- package/packages/hub/src/mcp/calls.ts +6 -6
- package/packages/hub/src/mcp/create.ts +5 -5
- package/packages/hub/src/mcp/env.ts +6 -6
- package/packages/hub/src/mcp/fns.ts +2 -2
- package/packages/hub/src/mcp/index.ts +2 -2
- package/packages/hub/src/mcp/sources.ts +3 -3
- package/packages/hub/src/mcp/tokens.ts +1 -1
- package/packages/hub/src/models/create.ts +1 -1
- package/packages/hub/src/models/decide.ts +2 -2
- package/packages/hub/src/models/index.ts +1 -1
- package/packages/hub/src/models/roles.ts +12 -12
- package/packages/hub/src/query/env.ts +5 -5
- package/packages/hub/src/query/sources.ts +3 -3
- package/packages/hub/src/questions/plans.ts +1 -1
- package/packages/hub/src/questions/worker.ts +2 -2
- package/packages/hub/src/resources/context.ts +3 -3
- package/packages/hub/src/resources/converters.ts +2 -2
- package/packages/hub/src/resources/create.ts +6 -6
- package/packages/hub/src/resources/env.ts +15 -15
- package/packages/hub/src/resources/fetch.ts +5 -5
- package/packages/hub/src/resources/forms.ts +5 -5
- package/packages/hub/src/resources/index.ts +1 -1
- package/packages/hub/src/resources/library.ts +2 -2
- package/packages/hub/src/resources/raw.ts +1 -1
- package/packages/hub/src/resources/reader.ts +2 -2
- package/packages/hub/src/resources/sqlite-files.ts +1 -1
- package/packages/hub/src/resources/storage.ts +5 -5
- package/packages/hub/src/resources/testing.ts +6 -6
- package/packages/hub/src/store/env.ts +4 -4
- package/packages/hub/src/store/hybrid.ts +4 -4
- package/packages/hub/src/store/sqlite.ts +3 -3
- package/packages/hub/src/stores/drivers.ts +2 -2
- package/packages/hub/src/stores/host.ts +3 -3
- package/packages/hub/src/stores/moves.ts +2 -2
- package/packages/hub/src/stores/service.ts +2 -2
- package/packages/hub/src/tables/env.ts +3 -3
- package/packages/hub/src/tables/index.ts +5 -5
- package/packages/hub/src/tables/service.ts +7 -7
- package/packages/sdk/AUTHORING.md +1206 -881
- package/packages/sdk/package.json +11 -8
- package/packages/sdk/src/agent.ts +1 -1
- package/packages/sdk/src/app-parts.ts +95 -0
- package/packages/sdk/src/authored.ts +26 -0
- package/packages/sdk/src/authoring.ts +13 -30
- package/packages/sdk/src/client-runtime.ts +24 -1
- package/packages/sdk/src/client-ui/AddServiceDialog.vue +43 -0
- package/packages/sdk/src/client-ui/InstanceNameField.vue +29 -0
- package/packages/sdk/src/client-ui/PairRowsEditor.vue +74 -0
- package/packages/sdk/src/client-ui/RemoteAuthFields.vue +95 -0
- package/packages/sdk/src/client-ui/ServiceRows.vue +57 -0
- package/packages/sdk/src/client-ui/draft.ts +10 -0
- package/packages/sdk/src/client-ui/host.ts +37 -0
- package/packages/sdk/src/client-ui/index.ts +19 -0
- package/packages/sdk/src/client-ui/loaded.ts +69 -0
- package/packages/sdk/src/client-ui/problems.ts +98 -0
- package/packages/sdk/src/client-ui/remote-config.ts +199 -0
- package/packages/sdk/src/client-ui/service-rows.ts +25 -0
- package/packages/sdk/src/client-ui/state.ts +14 -0
- package/packages/sdk/src/client-ui/testing.ts +147 -0
- package/packages/sdk/src/client-ui/vue-shim.d.ts +13 -0
- package/packages/sdk/src/client.ts +82 -11
- package/packages/sdk/src/hub.ts +4 -4
- package/packages/sdk/src/index.ts +13 -9
- package/packages/sdk/src/page-parts.ts +4 -0
- package/packages/sdk/src/program/env.ts +7 -7
- package/packages/sdk/src/program/runtime.ts +5 -5
- package/packages/sdk/src/program/tools.ts +3 -3
- package/packages/sdk/src/remote-auth.ts +128 -7
- package/packages/sdk/src/server/context-files.ts +1 -1
- package/packages/sdk/src/server/env.ts +36 -36
- package/packages/sdk/src/server/fake-hub-widgets.ts +7 -6
- package/packages/sdk/src/server/host.ts +28 -28
- package/packages/sdk/src/server/index.ts +2 -2
- package/packages/sdk/src/server/live.ts +4 -4
- package/packages/sdk/src/server/llm-wire.ts +54 -5
- package/packages/sdk/src/server/pairing.ts +1 -1
- package/packages/sdk/src/server/results.ts +4 -4
- package/packages/sdk/src/server/socket-guard.ts +1 -1
- package/packages/sdk/src/server/start-gate.ts +2 -2
- package/packages/sdk/src/server/store/engines.ts +2 -2
- package/packages/sdk/src/server/store/keeper.ts +2 -2
- package/packages/sdk/src/server/supervise.ts +4 -4
- package/packages/sdk/src/testing/env.ts +6 -6
- package/packages/sdk/src/testing/hub.ts +3 -1
- package/packages/sdk/src/testing/models.ts +3 -3
- package/packages/sdk/src/testing/openrouter.ts +3 -2
- package/packages/sdk/src/testing/preview.ts +7 -7
- package/packages/sdk/src/widgets.ts +21 -136
- package/packages/sdk/tsconfig.json +2 -2
- package/packages/web/dist/assets/{ActorSettingsView-v2k7v454.js → ActorSettingsView-CiWhrnP4.js} +2 -2
- package/packages/web/dist/assets/AdminLayout-CjVNzmYD.js +2 -0
- package/packages/web/dist/assets/{AdminLayout-1hbRPV3d.css → AdminLayout-ggcdQGlQ.css} +1 -1
- package/packages/web/dist/assets/{AppPage-CFmKZS8G.js → AppPage-D_kkUatv.js} +2 -2
- package/packages/web/dist/assets/{AutoPairPicker-C61gihmh.js → AutoPairPicker-BdCHi7dL.js} +2 -2
- package/packages/web/dist/assets/{BrowserFrame-Sq9EmQRT.js → BrowserFrame-CVQvfCB8.js} +2 -2
- package/packages/web/dist/assets/ChatPage-CPZJ8ya6.js +4 -0
- package/packages/web/dist/assets/{ChatPage-CbsRmktV.css → ChatPage-DjPv238m.css} +1 -1
- package/packages/web/dist/assets/{CodeViewer-tUNXZB77.js → CodeViewer-DzWZyAp4.js} +2 -2
- package/packages/web/dist/assets/ConfigWithCustom-C49loznj.js +3 -0
- package/packages/web/dist/assets/{ConfirmDialog-Dd3E4sJt.js → ConfirmDialog-BtugUGEY.js} +2 -2
- package/packages/web/dist/assets/{ConnectPage-CX9acyQH.js → ConnectPage-D8k2nSdX.js} +2 -2
- package/packages/web/dist/assets/ContextItemPage-DC4FGi8V.js +2 -0
- package/packages/web/dist/assets/ContextPage-MlEkKMq0.js +3 -0
- package/packages/web/dist/assets/{ContextRow-DrtPumZ5.js → ContextRow-BN26Di1B.js} +2 -2
- package/packages/web/dist/assets/{DataPage-DDSsxHro.js → DataPage-CvOYkEkS.js} +2 -2
- package/packages/web/dist/assets/DataTypePage-CDEL6BHp.js +2 -0
- package/packages/web/dist/assets/{DataTypePage-Cr238Hx_.css → DataTypePage-CWrWvUPs.css} +1 -1
- package/packages/web/dist/assets/{DesignPage-6e0XbOFC.js → DesignPage-D-MsKLuP.js} +3 -3
- package/packages/web/dist/assets/{ExplorePage-B7ND0W0l.js → ExplorePage-CNQpEe_8.js} +2 -2
- package/packages/web/dist/assets/{FnPill-Cp3KuLmP.js → FnPill-Dm5mmffj.js} +2 -2
- package/packages/web/dist/assets/{FnView-C0XZdnsS.js → FnView-oiIU5vka.js} +2 -2
- package/packages/web/dist/assets/{FnsView-GTH3p7a0.js → FnsView-DgIfza4W.js} +2 -2
- package/packages/web/dist/assets/{GinExprView-DGxns6lH.js → GinExprView-C19g0UgI.js} +2 -2
- package/packages/web/dist/assets/{GinForm-BDBUzuDP.js → GinForm-p7UsKQ3s.js} +2 -2
- package/packages/web/dist/assets/{GinTypeView-CUsymbVf.js → GinTypeView-DvdHc0V4.js} +2 -2
- package/packages/web/dist/assets/{GinValueView-jsKIfiEA.js → GinValueView-D6c7E4C_.js} +2 -2
- package/packages/web/dist/assets/{GraphPage-BCcPPsHu.js → GraphPage-BTamx4d-.js} +2 -2
- package/packages/web/dist/assets/GraphPanel-DKpbijQD.js +2 -0
- package/packages/web/dist/assets/{HubPicker-EoOErgmk.js → HubPicker-DfXIcUz1.js} +2 -2
- package/packages/web/dist/assets/{InboxApprovals-Dkq7DFp_.js → InboxApprovals-B9qwPCHR.js} +2 -2
- package/packages/web/dist/assets/{InboxPage-CHhslePq.js → InboxPage-j2lF00uW.js} +2 -2
- package/packages/web/dist/assets/InjectedList-BTGvy8GB.js +2 -0
- package/packages/web/dist/assets/{InstallDialog-D-VwfZYF.js → InstallDialog-BRJXLSMJ.js} +2 -2
- package/packages/web/dist/assets/InstanceTypes-DYdolFFW.js +2 -0
- package/packages/web/dist/assets/InstanceView-C5dJLBPe.js +2 -0
- package/packages/web/dist/assets/{ItemHistory-NQAP69ma.js → ItemHistory-vsyIMjIX.js} +2 -2
- package/packages/web/dist/assets/LimitsView-BtbQzkX1.js +2 -0
- package/packages/web/dist/assets/{ListSearch-BunVrDO0.js → ListSearch-BdVW9FHD.js} +2 -2
- package/packages/web/dist/assets/{LlmCallDetails-BoVNDTVs.js → LlmCallDetails-Cd7qtybU.js} +2 -2
- package/packages/web/dist/assets/{LlmCallsView-BGpV92RC.js → LlmCallsView-CrZB_I1H.js} +2 -2
- package/packages/web/dist/assets/{LoadState-h-K9bTYc.js → LoadState-8UknKQ6e.js} +2 -2
- package/packages/web/dist/assets/McpDialog-r-qJDHOO.js +2 -0
- package/packages/web/dist/assets/{McpView-GPXdCMne.js → McpView-FeDQWGxu.js} +2 -2
- package/packages/web/dist/assets/{McpsView-DJIR2JX5.js → McpsView-Czd2yUdE.js} +2 -2
- package/packages/web/dist/assets/{MemoryDialog-BTeIHQyA.js → MemoryDialog-DDiT6wO1.js} +2 -2
- package/packages/web/dist/assets/{ModelCallsView-DMcnwF2S.js → ModelCallsView-DsdztwCR.js} +2 -2
- package/packages/web/dist/assets/{ModelPicker-CgkMFxSO.js → ModelPicker-Df_3l8nS.js} +2 -2
- package/packages/web/dist/assets/ModelsView-YXwRDgWv.js +2 -0
- package/packages/web/dist/assets/{NotFoundPage-Tk92K7HN.js → NotFoundPage-DDEOlB6B.js} +2 -2
- package/packages/web/dist/assets/{PairPage-D0BK8CCw.js → PairPage-D3uHAkh1.js} +2 -2
- package/packages/web/dist/assets/{PanelHost-C-gKrxAk.js → PanelHost-BzWYqH39.js} +2 -2
- package/packages/web/dist/assets/PeopleView-Cg9RO5SF.js +2 -0
- package/packages/web/dist/assets/{PeopleView-CJ8yArTh.css → PeopleView-DBxdbT1C.css} +1 -1
- package/packages/web/dist/assets/{PoliciesView-BRi-QAuo.js → PoliciesView-BoshL7RQ.js} +2 -2
- package/packages/web/dist/assets/{RefusalList-DVO0bmeB.js → RefusalList-DnLIfmi-.js} +2 -2
- package/packages/web/dist/assets/RendererHost-CmkaVEX0.js +2 -0
- package/packages/web/dist/assets/RendererHost-Ym_SMkhp.css +1 -0
- package/packages/web/dist/assets/{ResourceViewer-Do0chYxU.js → ResourceViewer-CSAY6xIs.js} +2 -2
- package/packages/web/dist/assets/ResourcesPage-DAoa9mDs.js +2 -0
- package/packages/web/dist/assets/ResultGrid-CL2WSYQH.css +1 -0
- package/packages/web/dist/assets/ResultGrid-DSyc0btv.js +2 -0
- package/packages/web/dist/assets/{ReviewSummaryStrip-DO3p64Qj.js → ReviewSummaryStrip-Bzy-KGz_.js} +2 -2
- package/packages/web/dist/assets/ReviewView-Cwq8Az_B.js +3 -0
- package/packages/web/dist/assets/{RuleRow-DX9v4iGP.js → RuleRow-DAvl2m9p.js} +2 -2
- package/packages/web/dist/assets/RunCard-BMyRkKxJ.js +2 -0
- package/packages/web/dist/assets/RunCard-CSDiz-Nt.css +1 -0
- package/packages/web/dist/assets/{RunDetails-DjR206q6.js → RunDetails-Bvyr1HYK.js} +2 -2
- package/packages/web/dist/assets/{RunDot-lHRICdM5.js → RunDot-Lfrt5XR3.js} +2 -2
- package/packages/web/dist/assets/{RunPage-CbAQ_WPR.js → RunPage-C0-wY6Uz.js} +2 -2
- package/packages/web/dist/assets/{RunProgress-C3-B4tQf.js → RunProgress-BbzwzrTK.js} +2 -2
- package/packages/web/dist/assets/{RunsView-DMkPmkqX.js → RunsView-so-UV2Cq.js} +2 -2
- package/packages/web/dist/assets/SettingsPage-B4SQLk09.js +3 -0
- package/packages/web/dist/assets/{SettingsPage-t03BqXw8.css → SettingsPage-BTl3Ie4F.css} +1 -1
- package/packages/web/dist/assets/SignInPage-CXxLf7Rp.css +1 -0
- package/packages/web/dist/assets/{SignInPage-ByqGEZfj.js → SignInPage-Ck-v3eH0.js} +2 -2
- package/packages/web/dist/assets/{StatusBadge-CXne0sRZ.js → StatusBadge-C4NawPsO.js} +2 -2
- package/packages/web/dist/assets/{StorePlacementStep-B6SwTmdM.js → StorePlacementStep-DjLWeQF9.js} +2 -2
- package/packages/web/dist/assets/{SystemConfig-vQDL_eUl.js → SystemConfig-B5C5B3b0.js} +2 -2
- package/packages/web/dist/assets/SystemPageHost-DX7LrFoN.css +1 -0
- package/packages/web/dist/assets/SystemPageHost-DoyQlhKM.js +2 -0
- package/packages/web/dist/assets/SystemView-CTdpay8I.js +2 -0
- package/packages/web/dist/assets/SystemsView-Cnv2moRw.js +2 -0
- package/packages/web/dist/assets/TableView-BK_95qHT.js +3 -0
- package/packages/web/dist/assets/TableView-B_4MViVb.css +1 -0
- package/packages/web/dist/assets/{TableViewer-Boxx86f5.js → TableViewer-CRsIxdku.js} +3 -3
- package/packages/web/dist/assets/{ThemePicker-CIg_oRQX.js → ThemePicker-BlW7qvUd.js} +2 -2
- package/packages/web/dist/assets/{TurnTree-Ecm0yA5g.js → TurnTree-D6OYRutQ.js} +2 -2
- package/packages/web/dist/assets/{UserMessage-BtECa8ka.css → UserMessage-B63G9sxC.css} +1 -1
- package/packages/web/dist/assets/{UserMessage-BlnqZDVU.js → UserMessage-DJH2bXqv.js} +6 -6
- package/packages/web/dist/assets/{ValueVisual-C-MWpp7c.js → ValueVisual-BJUrdkHO.js} +2 -2
- package/packages/web/dist/assets/{fn-modal-B98MR7JN.js → fn-modal-DFtN7Kn-.js} +2 -2
- package/packages/web/dist/assets/{fn-notices-CfTa1E8y.js → fn-notices-C8HXeo7m.js} +2 -2
- package/packages/web/dist/assets/{formats-JwoKfXIq.js → formats-CHSYhY4X.js} +2 -2
- package/packages/web/dist/assets/index-BY7M8QUk.css +1 -0
- package/packages/web/dist/assets/index-Uz-h2M5K.js +4 -0
- package/packages/web/dist/assets/{labels-BFbk11BE.js → labels-DkV96Md_.js} +2 -2
- package/packages/web/dist/assets/{layout-D1gf481r.js → layout-CTAHAwIH.js} +2 -2
- package/packages/web/dist/assets/loaded-BrwmsuZY.js +2 -0
- package/packages/web/dist/assets/{metrics-CBPX3W5Y.js → metrics-BBvD6KSk.js} +2 -2
- package/packages/web/dist/assets/problems-CI9huk1n.js +2 -0
- package/packages/web/dist/assets/{push-payload-BeU1ADYt.js → push-payload-C1ppI5V2.js} +64 -64
- package/packages/web/dist/assets/record-edits-DFJBcNnL.js +2 -0
- package/packages/web/dist/assets/{review-fP-l9D6H.js → review-DlP8FQiO.js} +3 -3
- package/packages/web/dist/assets/routes-oIISbS5Z.js +4 -0
- package/packages/web/dist/assets/{runs-CveC2kKo.js → runs-BWVBevgu.js} +2 -2
- package/packages/web/dist/assets/{shared-LbaIHjbV.js → shared-Bc4GJbiE.js} +2 -2
- package/packages/web/dist/assets/{sources-VPrtgLIi.js → sources-gONU9kk2.js} +2 -2
- package/packages/web/dist/assets/src-ClMFVauH.js +43 -0
- package/packages/web/dist/assets/state-BQlvjJzT.js +2 -0
- package/packages/web/dist/assets/{systems-BqE3WTSF.js → systems-Dt01wDhP.js} +2 -2
- package/packages/web/dist/assets/table-host-BvEY0Zxn.js +2 -0
- package/packages/web/dist/assets/tables-CkqGZ0Yq.js +2 -0
- package/packages/web/dist/assets/{ui-BzgWquIU.js → ui-CjoSgSyZ.js} +5 -5
- package/packages/web/dist/assets/{url-DKGcECT1.js → url-Deh5u3O5.js} +2 -2
- package/packages/web/dist/index.html +49 -47
- package/packages/web/dist/sw.js +1 -1
- package/packages/web/package.json +2 -4
- package/premade/claude.zip +0 -0
- package/premade/database.zip +0 -0
- package/premade/web.zip +0 -0
- package/scripts/dev-env.ts +9 -9
- package/scripts/run-stack.ts +15 -15
- package/scripts/stack.ts +3 -3
- package/scripts/start.ts +18 -18
- package/systems/api/client/ApiServiceForm.vue +55 -0
- package/systems/api/client/ServiceList.vue +90 -0
- package/systems/api/client/ServicePage.vue +142 -0
- package/systems/api/client/ServicesPage.vue +32 -0
- package/systems/api/client/index.ts +15 -0
- package/systems/api/client/logic.ts +140 -0
- package/systems/api/client/state.ts +92 -0
- package/systems/api/package.json +9 -6
- package/systems/api/server/authoring.ts +2 -1
- package/systems/api/server/env.ts +1 -1
- package/systems/api/server/guard.ts +1 -1
- package/systems/api/server/http.ts +3 -2
- package/systems/api/server/impl.ts +3 -2
- package/systems/api/server/main.ts +11 -7
- package/systems/api/server/openapi.ts +1 -1
- package/systems/api/server/program.ts +2 -1
- package/systems/api/server/services.ts +2 -1
- package/systems/api/shared/http.ts +2 -1
- package/systems/api/shared/index.ts +15 -5
- package/{packages/core/src/programs.ts → systems/api/shared/services.ts} +7 -51
- package/systems/api/system.json +2 -1
- package/systems/api/tsconfig.json +2 -2
- package/systems/code/package.json +4 -3
- package/systems/code/server/authoring.ts +2 -1
- package/systems/code/server/impl.ts +2 -1
- package/systems/code/server/main.ts +5 -5
- package/systems/code/shared/index.ts +2 -3
- package/systems/code/shared/program.ts +23 -0
- package/systems/embedder/package.json +1 -1
- package/systems/embedder/server/env.ts +1 -1
- package/systems/embedder/server/main.ts +5 -5
- package/systems/embedder/shared/index.ts +1 -1
- package/systems/fs/client/machines/fakes.ts +1 -1
- package/systems/fs/client/machines/files/CommentComposer.vue +6 -3
- package/systems/fs/client/machines/files/FilePane.vue +2 -2
- package/systems/fs/client/machines/files/fakes.ts +1 -1
- package/systems/fs/client/machines/palette.ts +3 -2
- package/systems/fs/context/authoring/parts/client.md +23 -5
- package/systems/fs/context/authoring/parts/client.reference/client.md +7 -16
- package/systems/fs/context/authoring/parts/client.reference/pageinbox.md +524 -0
- package/systems/fs/context/authoring/parts/client.reference/{resultview.md → visuals.md} +85 -116
- package/systems/fs/context/authoring/parts/client.reference.md +8 -8
- package/systems/fs/context/authoring/parts/context.md +1 -1
- package/systems/fs/context/authoring/parts/contract.md +1 -1
- package/systems/fs/context/authoring/parts/core-types/admin-ts.md +2 -2
- package/systems/fs/context/authoring/parts/core-types/connections-ts.md +12 -1
- package/systems/fs/context/authoring/parts/core-types/context-files-ts.md +2 -2
- package/systems/fs/context/authoring/parts/core-types/context-graph-ts.md +2 -2
- package/systems/fs/context/authoring/parts/core-types/contextdecl.md +2 -2
- package/systems/fs/context/authoring/parts/core-types/lifecycle-ts.md +27 -2
- package/systems/fs/context/authoring/parts/core-types/manifest.md +27 -2
- package/systems/fs/context/authoring/parts/core-types/manifestpatch.md +26 -2
- package/systems/fs/context/authoring/parts/core-types/modes-ts.md +3 -3
- package/systems/fs/context/authoring/parts/core-types/records-systems-ts.md +145 -1
- package/systems/fs/context/authoring/parts/core-types/registries-ts.md +98 -2
- package/systems/fs/context/authoring/parts/core-types/run-ts.md +2 -2
- package/systems/fs/context/authoring/parts/core-types/system-pages-ts.md +4 -2
- package/systems/fs/context/authoring/parts/core-types/system-providers-ts.md +2 -2
- package/systems/fs/context/authoring/parts/core-types/tables-ts.md +91 -0
- package/systems/fs/context/authoring/parts/core-types/web-ts.md +1 -2
- package/systems/fs/context/authoring/parts/core-types.md +5 -8
- package/systems/fs/context/authoring/parts/examples/server-main-ts.md +4 -4
- package/systems/fs/context/authoring/parts/examples/systems-fs-shared-index-ts-lines-568-660.md +1 -1
- package/systems/fs/context/authoring/parts/fns.md +1 -1
- package/systems/fs/context/authoring/parts/folder.md +6 -6
- package/systems/fs/context/authoring/parts/hub/hub-ctx-from-resource.md +2 -2
- package/systems/fs/context/authoring/parts/hub/hub-install-package.md +2 -2
- package/systems/fs/context/authoring/parts/hub.reference.md +3 -3
- package/systems/fs/context/authoring/parts/internals/manifestof.md +2 -2
- package/systems/fs/context/authoring/parts/internals/permissionargs.md +4 -4
- package/systems/fs/context/authoring/parts/kinds-agents.md +1 -1
- package/systems/fs/context/authoring/parts/kinds-agents.reference/authoringsession.md +7 -5
- package/systems/fs/context/authoring/parts/kinds-agents.reference/kind.md +4 -4
- package/systems/fs/context/authoring/parts/outcomes.md +2 -2
- package/systems/fs/context/authoring/parts/outcomes.reference.md +2 -2
- package/systems/fs/context/authoring/parts/packaging.md +4 -4
- package/systems/fs/context/authoring/parts/remote.md +5 -5
- package/systems/fs/context/authoring/parts/remote.reference.md +201 -17
- package/systems/fs/context/authoring/parts/server.md +7 -7
- package/systems/fs/context/authoring/parts/server.reference.md +15 -15
- package/systems/fs/context/authoring/parts/testing.reference/equal.md +3 -3
- package/systems/fs/context/authoring/parts/testing.reference/fakehub.md +1 -1
- package/systems/fs/context/authoring/parts/testing.reference/kindprops.md +22 -10
- package/systems/fs/context/authoring/parts/testing.reference/{openmemorystore.md → storeconnection.md} +7 -19
- package/systems/fs/context/authoring/parts/testing.reference.md +5 -5
- package/systems/fs/context/authoring/parts/widgets.md +32 -22
- package/systems/fs/context/authoring/parts/widgets.reference.md +503 -9
- package/systems/fs/package.json +3 -3
- package/systems/fs/server/hosting.ts +10 -10
- package/systems/fs/server/main.ts +8 -8
- package/systems/fs/server/metrics/os.ts +50 -29
- package/systems/fs/server/shell.ts +1 -1
- package/systems/fs/shared/index.ts +1 -1
- package/systems/google-calendar/package.json +1 -1
- package/systems/google-calendar/server/main.ts +4 -4
- package/systems/input/package.json +3 -3
- package/systems/input/server/main.ts +6 -6
- package/systems/mcp/client/McpServerForm.vue +99 -0
- package/systems/mcp/client/ServerList.vue +78 -0
- package/systems/mcp/client/ServerPage.vue +194 -0
- package/systems/mcp/client/ServersPage.vue +32 -0
- package/systems/mcp/client/index.ts +15 -0
- package/systems/mcp/client/logic.ts +224 -0
- package/systems/mcp/client/state.ts +128 -0
- package/systems/mcp/package.json +9 -6
- package/systems/mcp/server/dial.ts +1 -1
- package/systems/mcp/server/impl.ts +2 -1
- package/systems/mcp/server/instance.ts +3 -5
- package/systems/mcp/server/main.ts +10 -6
- package/systems/mcp/server/mirror.ts +2 -3
- package/systems/mcp/server/oauth.ts +2 -1
- package/systems/mcp/server/server-link.ts +2 -1
- package/systems/mcp/shared/index.ts +15 -2
- package/{packages/core/src/mcp-servers.ts → systems/mcp/shared/servers.ts} +6 -5
- package/systems/mcp/system.json +2 -1
- package/systems/mcp/tsconfig.json +2 -2
- package/systems/ollama/package.json +3 -3
- package/systems/ollama/server/main.ts +5 -5
- package/systems/schedule/package.json +3 -3
- package/systems/schedule/server/main.ts +6 -6
- package/systems/template/README.md +2 -2
- package/systems/template/package.json +1 -1
- package/systems/template/server/main.ts +4 -4
- package/systems/widgets/client/ChipRow.vue +22 -0
- package/systems/widgets/client/ProposalCard.vue +6 -5
- package/systems/widgets/client/SavedWidget.vue +11 -8
- package/systems/widgets/client/WidgetChips.vue +137 -0
- package/systems/widgets/client/WidgetView.vue +32 -0
- package/systems/widgets/client/charts/ChartVisual.vue +157 -0
- package/systems/widgets/client/charts/chart-data.ts +230 -0
- package/systems/widgets/client/charts/echarts-setup.ts +69 -0
- package/systems/widgets/client/charts/export.ts +36 -0
- package/systems/widgets/client/charts/families/calendar.ts +105 -0
- package/systems/widgets/client/charts/families/category.ts +186 -0
- package/systems/widgets/client/charts/families/crosstab.ts +113 -0
- package/systems/widgets/client/charts/families/distribution.ts +160 -0
- package/systems/widgets/client/charts/families/finance.ts +96 -0
- package/systems/widgets/client/charts/families/gauge.ts +75 -0
- package/systems/widgets/client/charts/families/hierarchy.ts +166 -0
- package/systems/widgets/client/charts/families/index.ts +21 -0
- package/systems/widgets/client/charts/families/network.ts +140 -0
- package/systems/widgets/client/charts/families/part.ts +61 -0
- package/systems/widgets/client/charts/families/profile.ts +30 -0
- package/systems/widgets/client/charts/families/progress.ts +76 -0
- package/systems/widgets/client/charts/families/range.ts +107 -0
- package/systems/widgets/client/charts/families/time.ts +177 -0
- package/systems/widgets/client/charts/families/timeline.ts +114 -0
- package/systems/widgets/client/charts/families/wide.ts +41 -0
- package/systems/widgets/client/charts/index.ts +37 -0
- package/systems/widgets/client/charts/maths.ts +139 -0
- package/systems/widgets/client/charts/size.ts +39 -0
- package/systems/widgets/client/chips.ts +150 -0
- package/systems/widgets/client/index.ts +18 -5
- package/systems/widgets/client/proposal.ts +2 -1
- package/systems/widgets/package.json +7 -4
- package/systems/widgets/server/authoring.ts +13 -7
- package/systems/widgets/server/env.ts +1 -1
- package/systems/widgets/server/impl.ts +10 -6
- package/systems/widgets/server/main.ts +6 -6
- package/systems/widgets/server/run.ts +16 -9
- package/systems/widgets/server/upgrade.ts +34 -0
- package/systems/widgets/shared/args.ts +137 -0
- package/systems/widgets/shared/charts.ts +243 -0
- package/systems/widgets/shared/index.ts +12 -3
- package/{packages/sdk/src → systems/widgets/shared}/relative-dates.ts +2 -1
- package/systems/widgets/shared/spec.ts +208 -0
- package/{packages/sdk/src → systems/widgets/shared}/widget-check.ts +7 -9
- package/{packages/sdk/src → systems/widgets/shared}/widget-schema.ts +4 -4
- package/packages/core/src/remote-auth.ts +0 -111
- package/packages/core/src/widgets.ts +0 -427
- package/packages/web/dist/assets/AdminLayout-B6Jrc_4W.js +0 -2
- package/packages/web/dist/assets/ApiServiceForm-BxprSaAq.css +0 -1
- package/packages/web/dist/assets/ApiServiceForm-CuuQgOJc.js +0 -2
- package/packages/web/dist/assets/ApiServiceView-7bTHSO_Z.js +0 -2
- package/packages/web/dist/assets/ApiServiceView-BVmdRCjR.css +0 -1
- package/packages/web/dist/assets/ApiServicesView-BTLV6c8n.css +0 -1
- package/packages/web/dist/assets/ApiServicesView-BXi24n49.js +0 -2
- package/packages/web/dist/assets/ChartVisual-BnFG9aFi.css +0 -1
- package/packages/web/dist/assets/ChartVisual-C4mgw4wh.js +0 -11
- package/packages/web/dist/assets/ChatPage-CAhHE03Z.js +0 -4
- package/packages/web/dist/assets/ConfigWithCustom-D_-rY66L.js +0 -3
- package/packages/web/dist/assets/ContextItemPage-rUI3-T_L.js +0 -2
- package/packages/web/dist/assets/ContextPage-CtefzyKg.js +0 -3
- package/packages/web/dist/assets/DataTypePage-BW9fWaz8.js +0 -2
- package/packages/web/dist/assets/FnList-BCnb4kOB.css +0 -1
- package/packages/web/dist/assets/FnList-Bx6H-kux.js +0 -2
- package/packages/web/dist/assets/GraphPanel-9tztGHmu.js +0 -2
- package/packages/web/dist/assets/InjectedList-CSWqRiON.js +0 -2
- package/packages/web/dist/assets/InstanceTypes-D3rAEiE7.js +0 -2
- package/packages/web/dist/assets/InstanceView-DoH8C-1j.js +0 -2
- package/packages/web/dist/assets/LimitsView-DY2C9nYS.js +0 -2
- package/packages/web/dist/assets/McpDialog-DhOCk6_E.js +0 -2
- package/packages/web/dist/assets/McpServerForm-Cor3fI7s.js +0 -2
- package/packages/web/dist/assets/McpServerForm-DsHaf5Um.css +0 -1
- package/packages/web/dist/assets/McpServerView-7I76EznB.css +0 -1
- package/packages/web/dist/assets/McpServerView-ewXRPEmZ.js +0 -2
- package/packages/web/dist/assets/McpServersView-Dd0xmfws.js +0 -2
- package/packages/web/dist/assets/ModelsView-cMHygeiK.js +0 -2
- package/packages/web/dist/assets/PeopleView-DRfeNWK5.js +0 -2
- package/packages/web/dist/assets/RemoteAuthFields-CgiufuqQ.js +0 -2
- package/packages/web/dist/assets/RemoteAuthFields-Dm44vz2t.css +0 -1
- package/packages/web/dist/assets/ResourcesPage-BBx2u2mw.js +0 -2
- package/packages/web/dist/assets/ResultGrid-Bj-0I5HY.js +0 -2
- package/packages/web/dist/assets/ResultGrid-CuUQyTjW.css +0 -1
- package/packages/web/dist/assets/ReviewView-DZF9E1hb.js +0 -3
- package/packages/web/dist/assets/RunCard-BnrtK2Yp.js +0 -2
- package/packages/web/dist/assets/RunCard-CfyRaDLS.css +0 -1
- package/packages/web/dist/assets/ServiceRows-4WythFpF.js +0 -2
- package/packages/web/dist/assets/ServiceRows-HPQ0pN6b.css +0 -1
- package/packages/web/dist/assets/SettingsPage-BN4oSzoL.js +0 -3
- package/packages/web/dist/assets/SignInPage-Djx-M-0U.css +0 -1
- package/packages/web/dist/assets/SystemPageHost-BeZ-6N0-.css +0 -1
- package/packages/web/dist/assets/SystemPageHost-DrMrEPyh.js +0 -2
- package/packages/web/dist/assets/SystemView-Be6TBM4j.js +0 -2
- package/packages/web/dist/assets/SystemsView-DZtT3laz.js +0 -2
- package/packages/web/dist/assets/WidgetView-DQUDeFkB.css +0 -1
- package/packages/web/dist/assets/WidgetView-DX4ejNb6.js +0 -3
- package/packages/web/dist/assets/export-BwFkEtcm.js +0 -15
- package/packages/web/dist/assets/index-6ScWTFy2.js +0 -4
- package/packages/web/dist/assets/index-CEslGcrX.css +0 -1
- package/packages/web/dist/assets/problems-t1E_ovSz.js +0 -2
- package/packages/web/dist/assets/record-edits-Bfsi4lU3.js +0 -2
- package/packages/web/dist/assets/remote-config-BNQhSDzB.js +0 -2
- package/packages/web/dist/assets/routes-DV4IJpwe.js +0 -4
- package/packages/web/dist/assets/size-Bh__w5aI.js +0 -2
- package/packages/web/dist/assets/src-CT3TeFaM.js +0 -43
- package/packages/web/dist/assets/state-xfQqaQPX.js +0 -2
- package/packages/web/dist/assets/widget-host-B87MTaTn.js +0 -2
- package/packages/web/dist/assets/widgets-BBCuSS6E.js +0 -2
- package/systems/fs/context/authoring/parts/client.reference/textareaprops.md +0 -195
- package/systems/fs/context/authoring/parts/core-types/remote-auth-ts.md +0 -64
- package/systems/fs/context/authoring/parts/core-types/widgets-ts.md +0 -303
- package/systems/fs/context/authoring/parts/widgets.reference/hub-visuals.md +0 -627
- package/systems/fs/context/authoring/parts/widgets.reference/sourcecompatible.md +0 -154
|
@@ -52,72 +52,72 @@ function e(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object
|
|
|
52
52
|
|
|
53
53
|
`)}return o.write(`payload.value = newResult;`),o.write(`return payload;`),o.compile()},s,c=ae,l=!rt.jitless,u=l&&oe.value,d=t.catchall,f;e._zod.parse=(i,a)=>{f??=r.value;let p=i.value;return c(p)?l&&u&&a?.async===!1&&a.jitless!==!0?(s||=o(t.shape),i=s(i,a),d?zr([],p,i,a,f,e,a?.abortEarly===!0):i):n(i,a):(i.issues.push({expected:`object`,code:`invalid_type`,input:p,inst:e}),i)}});function Hr(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;let i=e.filter(e=>!Ee(e));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>Me(e,r,it())))}),t)}var Ur=_(`$ZodUnion`,(e,t)=>{Fn.init(e,t),qe(e,`optin`,e=>e.def.options.some(e=>e._zod.optin===`defaulted`)?`defaulted`:e.def.options.some(e=>e._zod.optin!==void 0)?`optional`:void 0),qe(e,`optout`,e=>e.def.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),qe(e,`values`,e=>{if(e.def.options.every(e=>e._zod.values))return new Set(e.def.options.flatMap(e=>Array.from(e._zod.values)))}),qe(e,`pattern`,e=>{if(e.def.options.every(e=>e._zod.pattern)){let t=e.def.options.map(e=>e._zod.pattern);return RegExp(`^(${t.map(e=>o(e.source)).join(`|`)})$`)}});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let a=!1,o=[];for(let e of t.options){let t=e._zod.run({value:r.value,issues:[]},i);if(t instanceof Promise)o.push(t),a=!0;else{if(t.issues.length===0)return t;o.push(t)}}return a?Promise.all(o).then(t=>Hr(t,r,e,i)):Hr(o,r,e,i)}});function Wr(e){let t=new Map;for(let n of e.options){let r=n._zod.propValues?.[e.discriminator];if(!r||r.size===0)throw Error(`Invalid discriminated union option at index "${e.options.indexOf(n)}"`);for(let e of r)if(t.has(e)){if(e!==void 0)throw Error(`Duplicate discriminator value "${String(e)}"`);t.set(e,null)}else t.set(e,n)}return t}var Gr=_(`$ZodDiscriminatedUnion`,(e,t)=>{t.inclusive=!1,Ur.init(e,t);let n=e._zod.parse;qe(e,`propValues`,e=>{let t={},n=0;for(let r of e.def.options){let i=r._zod.propValues;if(!i||Object.keys(i).length===0)throw Error(`Invalid discriminated union option at index "${e.def.options.indexOf(r)}"`);i[e.def.discriminator]?.has(void 0)&&n++;for(let[e,n]of Object.entries(i)){Object.prototype.hasOwnProperty.call(t,e)||u(t,e,new Set);for(let r of n)t[e].add(r)}}return!e.def.unionFallback&&n>1&&t[e.def.discriminator]?.delete(void 0),t}),t.options.forEach((e,n)=>{let r=d(e._zod.def);if(r&&!Object.prototype.hasOwnProperty.call(r,t.discriminator))throw Error(`Invalid discriminated union option at index "${n}"`)});let r=i(()=>Wr(t));e._zod.parse=(i,a)=>{let o=i.value;if(!ae(o))return i.issues.push({code:`invalid_type`,expected:`object`,input:o,inst:e}),i;let s=o?.[t.discriminator],c=r.value.get(s);return c&&(s!==void 0||a.direction!==`backward`)?c._zod.run(i,a):t.unionFallback||a.direction===`backward`?n(i,a):(i.issues.push({code:`invalid_union`,errors:[],note:`No matching discriminator`,discriminator:t.discriminator,options:Array.from(r.value.keys()).filter(e=>r.value.get(e)!==null),input:o,path:[t.discriminator],inst:e}),i)}}),Kr=_(`$ZodIntersection`,(e,t)=>{Fn.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>Jr(e,t,n)):Jr(e,i,a)}});function qr(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(se(e)&&se(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};Object.prototype.hasOwnProperty.call(i,`__proto__`)&&delete i.__proto__;for(let n of r){if(n===`__proto__`)continue;let r=qr(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=qr(i,a);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Jr(e,t,n){let r=new Map,i,a=new Map,o=(e,t)=>{let n;if(e.code===`unrecognized_keys`&&!e.path?.length)i??=e,n=e.keys;else if(e.code===`invalid_key`&&e.origin===`record`&&e.path?.length===1){let t=String(e.path[0]);a.has(t)||a.set(t,e),n=[t]}else return!1;for(let e of n)r.has(e)||r.set(e,{}),r.get(e)[t]=!0;return!0};for(let n of t.issues)o(n,`l`)||e.issues.push(n);for(let t of n.issues)o(t,`r`)||e.issues.push(t);let s=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(s.length){let t=i?s.filter(e=>i.keys.includes(e)):[];t.length&&e.issues.push({...i,keys:t});for(let n of s)!t.includes(n)&&a.has(n)&&e.issues.push(a.get(n))}let c=qr(t.value,n.value);if(!c.valid){if(Ee(e))return e;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(c.mergeErrorPath)}`)}return e.value=c.data,e}var Yr=_(`$ZodTuple`,(e,t)=>{Fn.init(e,t);let n=t.items,r=rt.memoizer;r?.attach(e),e._zod.parse=(i,a)=>{let o=i.value;if(!Array.isArray(o))return i.issues.push({input:o,inst:e,expected:`tuple`,code:`invalid_type`}),i;i.value=r?r.alloc(e,i,[],a):[];let s=[],c=Xr(n,`optin`),l=Xr(n,`optout`);if(!t.rest){if(o.length<c)return i.issues.push({code:`too_small`,minimum:c,inclusive:!0,input:o,inst:e,origin:`array`}),i;o.length>n.length&&i.issues.push({code:`too_big`,maximum:n.length,inclusive:!0,input:o,inst:e,origin:`array`})}let u=Array(n.length),d=t.rest?a?.abortEarly:void 0,f=!1;for(let e=0;e<n.length;e++){let t=n[e]._zod.run({value:o[e],issues:[]},a);t instanceof Promise?s.push(t.then(t=>{u[e]=t})):(u[e]=t,d&&!f&&t.issues.length&&(f=Ee(t)))}if(t.rest&&!f){let e=n.length-1,r=o.slice(n.length),c=i.issues.length;for(let n of r){if(d&&i.issues.length!==c){if(Ee(i,c))break;c=i.issues.length}e++;let r=t.rest._zod.run({value:n,issues:[]},a);r instanceof Promise?s.push(r.then(t=>Zr(t,i,e))):Zr(r,i,e)}}return s.length?Promise.all(s).then(()=>Qr(u,i,n,o,l)):Qr(u,i,n,o,l)}});function Xr(e,t){for(let n=e.length-1;n>=0;n--)if(!(t===`optin`?e[n]._zod.optin!==void 0:e[n]._zod.optout===`optional`))return n+1;return 0}function Zr(e,t,n){e.issues.length&&t.issues.push(...Oe(n,e.issues)),t.value[n]=e.value}function Qr(e,t,n,r,i){for(let a=0;a<n.length;a++){let o=e[a],s=a<r.length;if(!s&&a>=i&&n[a]._zod.optin===`optional`){t.value.length=a;break}if(o.issues.length){if(!s&&a>=i){t.value.length=a;break}t.issues.push(...Oe(a,o.issues))}t.value[a]=o.value}for(let e=t.value.length-1;e>=r.length&&n[e]._zod.optout===`optional`&&t.value[e]===void 0;e--)t.value.length=e;return t}var $r=_(`$ZodRecord`,(e,t)=>{Fn.init(e,t);let n=rt.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let a=r.value;if(!se(a))return r.issues.push({expected:`record`,code:`invalid_type`,input:a,inst:e}),r;let o=[],s=t.keyType._zod.values;if(s&&!t.partial){r.value=n?n.alloc(e,r,{},i):{};let c=new Set;for(let n of s)if(typeof n==`string`||typeof n==`number`||typeof n==`symbol`){if(c.add(typeof n==`number`?n.toString():n),n===`__proto__`)continue;let s=t.keyType._zod.run({value:n,issues:[]},i);if(s instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(s.issues.length){r.issues.push({code:`invalid_key`,origin:`record`,issues:s.issues.map(e=>Me(e,i,it())),input:n,path:[n],inst:e});continue}let l=s.value;if(l===`__proto__`)continue;let u=t.valueType._zod.run({value:a[n],issues:[]},i);u instanceof Promise?o.push(u.then(e=>{e.issues.length&&r.issues.push(...Oe(n,e.issues)),r.value[l]=e.value})):(u.issues.length&&r.issues.push(...Oe(n,u.issues)),r.value[l]=u.value)}let l;for(let e in a)if(!c.has(e)){if(t.mode===`loose`){if(e===`__proto__`)continue;r.value[e]=a[e]}else l??=[],l.push(e)}l&&l.length>0&&r.issues.push({code:`unrecognized_keys`,input:a,inst:e,keys:l,continue:!0})}else{r.value=n?n.alloc(e,r,{},i):{};let c;for(let n of Reflect.ownKeys(a)){if(n===`__proto__`||!Object.prototype.propertyIsEnumerable.call(a,n))continue;let l=t.keyType._zod.run({value:n,issues:[]},i);if(l instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(typeof n==`string`&&un.test(n)&&l.issues.length){let e=t.keyType._zod.run({value:Number(n),issues:[]},i);if(e instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);e.issues.length===0&&(l=e)}if(l.issues.length){t.mode===`loose`?r.value[n]=a[n]:s?(c??=[],c.push(n)):r.issues.push({code:`invalid_key`,origin:`record`,issues:l.issues.map(e=>Me(e,i,it())),input:n,path:[n],inst:e});continue}let u=l.value;if(u===`__proto__`)continue;let d=t.valueType._zod.run({value:a[n],issues:[]},i);d instanceof Promise?o.push(d.then(e=>{e.issues.length&&r.issues.push(...Oe(n,e.issues)),r.value[u]=e.value})):(d.issues.length&&r.issues.push(...Oe(n,d.issues)),r.value[u]=d.value)}c&&c.length>0&&r.issues.push({code:`unrecognized_keys`,input:a,inst:e,keys:c,continue:!0})}return o.length?Promise.all(o).then(()=>r):r}}),ei=_(`$ZodEnum`,(t,n)=>{Fn.init(t,n);let r=e(n.entries),i=new Set(r);t._zod.values=i,qe(t,`pattern`,t=>{let n=e(t.def.entries).filter(e=>le.has(typeof e));return RegExp(n.length?`^(${n.map(e=>de(e.toString())).join(`|`)})$`:`^[^\\s\\S]$`)}),t._zod.parse=(e,n)=>{let a=e.value;return i.has(a)||e.issues.push({code:`invalid_value`,values:r,input:a,inst:t}),e}}),ti=_(`$ZodLiteral`,(e,t)=>{Fn.init(e,t);let n=new Set(t.values);e._zod.values=n,qe(e,`pattern`,e=>{let t=e.def.values;return RegExp(t.length?`^(${t.map(e=>typeof e==`string`?de(e):e?de(e.toString()):String(e)).join(`|`)})$`:`^[^\\s\\S]$`)}),e._zod.parse=(r,i)=>{let a=r.value;return n.has(a)||r.issues.push({code:`invalid_value`,values:t.values,input:a,inst:e}),r}}),ni=_(`$ZodTransform`,(e,t)=>{Fn.init(e,t),e._zod.optin=`optional`,rt.memoizer?.guard(e),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new nt(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(n.value=e,n));if(i instanceof Promise)throw new tt;return n.value=i,n}});function ri(e,t){return e.value=t.issues.length?void 0:t.value,e}var ii=_(`$ZodOptional`,(e,t)=>{Fn.init(e,t),qe(e,`optin`,e=>e.def.innerType._zod.optin===`defaulted`?`defaulted`:`optional`),e._zod.optout=`optional`,qe(e,`values`,e=>{let t=e.def.innerType._zod.values;return t?new Set([...t,void 0]):void 0}),qe(e,`pattern`,e=>{let t=e.def.innerType._zod.pattern;return t?RegExp(`^(${o(t.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(e.value===void 0){if(t.innerType._zod.optin!==`defaulted`)return e;let r=t.innerType._zod.run({value:e.value,issues:[]},n);return r instanceof Promise?r.then(t=>ri(e,t)):ri(e,r)}return t.innerType._zod.run(e,n)}}),ai=_(`$ZodExactOptional`,(e,t)=>{ii.init(e,t),qe(e,`values`,e=>e.def.innerType._zod.values),qe(e,`pattern`,e=>e.def.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),oi=_(`$ZodNullable`,(e,t)=>{Fn.init(e,t),qe(e,`optin`,e=>e.def.innerType._zod.optin),qe(e,`optout`,e=>e.def.innerType._zod.optout),qe(e,`pattern`,e=>{let t=e.def.innerType._zod.pattern;return t?RegExp(`^(${o(t.source)}|null)$`):void 0}),qe(e,`values`,e=>e.def.innerType._zod.values?new Set([...e.def.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),si=_(`$ZodDefault`,(e,t)=>{Fn.init(e,t),e._zod.optin=`defaulted`,qe(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>ci(e,t)):ci(r,t)}});function ci(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var li=_(`$ZodPrefault`,(e,t)=>{Fn.init(e,t),e._zod.optin=`defaulted`,qe(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>(n.direction===`backward`||e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),ui=_(`$ZodNonOptional`,(e,t)=>{Fn.init(e,t),qe(e,`values`,e=>{let t=e.def.innerType._zod.values;return t?new Set([...t].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>di(t,e)):di(i,e)}});function di(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}function fi(e,t,n,r){return t.issues.length?(e.value=n.catchValue({...t,value:e.value,error:{issues:t.issues.map(e=>Me(e,r,it()))},input:e.value}),e):(e.value=t.value,t.memo&&(e.memo=!0),e)}var pi=_(`$ZodCatch`,(e,t)=>{Fn.init(e,t),qe(e,`optin`,e=>e.def.innerType._zod.optin===`defaulted`?`defaulted`:`optional`),qe(e,`optout`,e=>e.def.innerType._zod.optout),qe(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run({value:e.value,issues:[]},n);return r instanceof Promise?r.then(r=>fi(e,r,t,n)):fi(e,r,t,n)}}),mi=_(`$ZodPipe`,(e,t)=>{Fn.init(e,t),qe(e,`values`,e=>e.def.in._zod.values),qe(e,`optin`,e=>e.def.in._zod.optin),qe(e,`optout`,e=>e.def.out._zod.optout),qe(e,`propValues`,e=>e.def.in._zod.propValues),e._zod.parse=(e,n)=>{if(n.direction===`backward`){let r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>hi(e,t.in,n)):hi(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>hi(e,t.out,n)):hi(r,t.out,n)}});function hi(e,t,n){return e.issues.some(e=>e.code!==`unrecognized_keys`)?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}var gi=_(`$ZodReadonly`,(e,t)=>{Fn.init(e,t),qe(e,`propValues`,e=>e.def.innerType._zod.propValues),qe(e,`values`,e=>e.def.innerType._zod.values),qe(e,`optin`,e=>e.def.innerType?._zod?.optin),qe(e,`optout`,e=>e.def.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(_i):_i(r)}});function _i(e){return e.memo||(e.value=Object.freeze(e.value)),e}function vi(e){let t=e._zod.def,n=t.pattern,r=!!t.format?.includes(`int`),i,a;for(let e of t.checks??[]){let t=e._zod.def;t.pattern&&(n=t.pattern),r||=!!t.format?.includes(`int`);let o=t.minimum??t.length,s=t.maximum??t.length;o!==void 0&&(i===void 0||o>i)&&(i=o),s!==void 0&&(a===void 0||s<a)&&(a=s)}if(n)return n.source;if(i!==void 0&&a!==void 0&&i>a)return`(?!)`;if(i!==void 0||a!==void 0)return cn({minimum:i,maximum:a}).source;let o=e._zod.pattern;return(r&&o===un?ln:o)?.source}function yi(e){let t=e._zod.def,n=e._zod.pattern?.source,r=t.innerType??e._zod.innerType;if(r){let e=r._zod.pattern?.source,t=yi(r);return n&&e&&t&&t!==e?n.replace(o(e),()=>o(t)):n}if(t.options){let e=t.options.map(yi);if(e.every(Boolean))return`^(${e.map(e=>o(e)).join(`|`)})$`}return vi(e)}var bi=_(`$ZodTemplateLiteral`,(e,t)=>{Fn.init(e,t);let n=[];for(let e of t.parts)if(typeof e==`object`&&e){let t=yi(e);if(!t)throw Error(`Invalid template literal part, no pattern found: ${[...e._zod.traits].shift()}`);n.push(o(t))}else if(e===null||ue.has(typeof e))n.push(de(`${e}`));else throw Error(`Invalid template literal part: ${e}`);e._zod.pattern=RegExp(`^${n.join(``)}$`),e._zod.parse=(n,r)=>typeof n.value==`string`?(e._zod.pattern.lastIndex=0,e._zod.pattern.test(n.value)||n.issues.push({input:n.value,inst:e,code:`invalid_format`,format:t.format??`template_literal`,pattern:e._zod.pattern.source}),n):(n.issues.push({input:n.value,inst:e,expected:`string`,code:`invalid_type`}),n)}),xi=_(`$ZodLazy`,(e,t)=>{Fn.init(e,t),l(e._zod,`innerType`,()=>{let e=t;return e._cachedInner||=t.getter(),e._cachedInner}),qe(e,`pattern`,e=>e.innerType?._zod?.pattern),qe(e,`propValues`,e=>e.innerType?._zod?.propValues),qe(e,`optin`,e=>e.innerType?._zod?.optin??void 0),qe(e,`optout`,e=>e.innerType?._zod?.optout??void 0),e._zod.parse=(t,n)=>e._zod.innerType._zod.run(t,n)}),Si=_(`$ZodCustom`,(e,t)=>{hn.init(e,t),Fn.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>Ci(t,n,r,e));Ci(i,n,r,e)}});function Ci(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(Le(e))}}var wi=class extends Error{constructor(){super(`Cannot parse a reference cycle that closes through a transform`),this.name=`ZodCyclicError`}},Ti=`~memo`,Ei=[];function Di(e){return typeof e==`object`&&!!e}function Oi(e){return e.map(e=>e.path?{...e,path:e.path.slice()}:{...e})}var ki=new WeakMap,Ai=0,ji=1,Mi=2;function Ni(e,t,n){let r=ki.get(e);if(r!==void 0)return r?Mi:Ai;if(t.has(e))return Mi;t.add(e);let i=Ai,a=e=>{if(i!==Mi&&e?._zod){let r=Ni(e,t,n);r>i&&(i=r)}},o=(e,r)=>{let i=Ai;for(let a of Reflect.ownKeys(e)){let o=Object.getOwnPropertyDescriptor(e,a);if(r&&!o.enumerable)continue;let s=o.get?ji:o.value?._zod?Ni(o.value,t,n):Ai;s>i&&(i=s)}return i},s=e=>{e>i&&(i=e)},c=e._zod.def;switch(c.type){case`object`:{let e=d(c);s(e?o(e,!0):ji),a(c.catchall);break}case`array`:a(c.element);break;case`tuple`:for(let e of c.items)a(e);a(c.rest);break;case`record`:case`map`:a(c.keyType),a(c.valueType);break;case`set`:a(c.valueType);break;case`union`:for(let e of c.options)a(e);break;case`intersection`:a(c.left),a(c.right);break;case`optional`:case`nullable`:case`default`:case`prefault`:case`catch`:case`readonly`:case`nonoptional`:case`promise`:case`success`:a(c.innerType);break;case`pipe`:a(c.in),a(c.out);break;case`function`:a(c.input),a(c.output);break;case`lazy`:{let r=c._cachedInner??(n?e._zod.innerType:void 0);s(r?Ni(r,t,!1):ji);break}case`template_literal`:case`string`:case`number`:case`int`:case`boolean`:case`bigint`:case`symbol`:case`undefined`:case`null`:case`void`:case`never`:case`any`:case`unknown`:case`date`:case`nan`:case`enum`:case`literal`:case`file`:case`transform`:case`custom`:break;default:for(let e in c){let t=Object.getOwnPropertyDescriptor(c,e);if(!t||t.get)continue;let n=t.value;if(n&&typeof n==`object`){if(n._zod)a(n);else if(Array.isArray(n))for(let e of n)a(e)}}}return t.delete(e),Pi(e,i)}function Pi(e,t){return t!==ji&&ki.set(e,t===Mi),t}function Fi(e,t){let n=e.buckets.get(t);return n||(n=new WeakMap,e.buckets.set(t,n)),n}var Ii,Li=[],Ri={alloc(e,t,n){let r=Ii;if(!r)return n;Ii=void 0;let i={value:n,issues:null};return r.set(t.value,i),Li.push(i),n},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let t=e._zod.parse,n=(e,n)=>{if(n.direction!==`backward`&&Bi(n,e.value))throw new wi;return t(e,n)};e._zod.parse=n,e._zod.run===t&&(e._zod.run=n)})},attach(e){var t;let n,r=!1,i,a;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let t=e._zod.parse,o=(s,c)=>{if(n===void 0){let i=Ni(e,new Set,!1);if(i===Ai)return e._zod.parse=t,e._zod.run===o&&(e._zod.run=t),t(s,c);i===Mi||r?n=!0:r=!0}let l=s.value;if(!Di(l))return t(s,c);let u=c[Ti];u||(u={buckets:new WeakMap,backEdges:void 0},c[Ti]=u);let d;i===c?d=a:(d=Fi(u,e),i=c,a=d);let f=d.get(l);if(f)return s.value=f.value,f.issues?f.issues.length&&s.issues.push(...Oi(f.issues)):(s.memo=!0,u.backEdges??(u.backEdges=new WeakSet),u.backEdges.add(f.value)),s;Ii=d;let p=Li.length,m=t(s,c);Ii=void 0;let h=Li.length>p?Li.pop():void 0;return m instanceof Promise?m.then(e=>(h&&(h.issues=e.issues.length?Oi(e.issues):Ei),e)):(h&&(h.issues=m.issues.length?Oi(m.issues):Ei),m)};e._zod.parse=o,e._zod.run===t&&(e._zod.run=o)})}};function zi(){return Ri}function Bi(e,t){let n=e[Ti]?.backEdges;return n!==void 0&&Di(t)&&n.has(t)}var Vi=()=>{let e={string:{unit:`characters`,verb:`to have`},file:{unit:`bytes`,verb:`to have`},array:{unit:`items`,verb:`to have`},set:{unit:`items`,verb:`to have`},map:{unit:`entries`,verb:`to have`}};function n(t){return e[t]??null}let r={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`,mac:`MAC address`,cidrv4:`IPv4 range`,cidrv6:`IPv6 range`,base64:`base64-encoded string`,base64url:`base64url-encoded string`,json_string:`JSON string`,e164:`E.164 number`,currency_code:`currency code`,credit_card:`credit card number`,iban:`IBAN`,jwt:`JWT`,template_literal:`input`},i={nan:`NaN`};function a(e,t){return e===`number`&&typeof t==`number`&&!Number.isFinite(t)?String(t):i[e]??e}return e=>{switch(e.code){case`invalid_type`:return`Invalid input: expected ${a(e.expected)}, received ${a(Ie(e.input),e.input)}`;case`invalid_value`:return e.values.length===1?`Invalid input: expected ${pe(e.values[0])}`:`Invalid option: expected one of ${t(e.values,`|`)}`;case`too_big`:{let t=e.exact?`exactly `:e.inclusive?`<=`:`<`,r=n(e.origin);return r?`Too big: expected ${e.origin??`value`} to have ${t}${e.maximum.toString()} ${r.unit??`elements`}`:`Too big: expected ${e.origin??`value`} to be ${t}${e.maximum.toString()}`}case`too_small`:{let t=e.exact?`exactly `:e.inclusive?`>=`:`>`,r=n(e.origin);return r?`Too small: expected ${e.origin} to have ${t}${e.minimum.toString()} ${r.unit}`:`Too small: expected ${e.origin} to be ${t}${e.minimum.toString()}`}case`invalid_format`:{let t=e;return t.format===`starts_with`?`Invalid string: must start with "${t.prefix}"`:t.format===`ends_with`?`Invalid string: must end with "${t.suffix}"`:t.format===`includes`?`Invalid string: must include "${t.includes}"`:t.format===`regex`?`Invalid string: must match pattern ${t.pattern}`:`Invalid ${r[t.format]??e.format}`}case`not_multiple_of`:return`Invalid number: must be a multiple of ${e.divisor}`;case`unrecognized_keys`:return`Unrecognized key${e.keys.length>1?`s`:``}: ${t(e.keys,`, `)}`;case`invalid_key`:return`Invalid key in ${e.origin}`;case`invalid_union`:return e.options&&Array.isArray(e.options)&&e.options.length>0?`Invalid discriminator value. Expected ${e.options.map(e=>`'${e}'`).join(` | `)}`:e.inclusive===!1?`Invalid input: more than one option matched`:`Invalid input`;case`invalid_element`:return`Invalid value in ${e.origin}`;default:return`Invalid input`}}};function Hi(){return{localeError:Vi()}}var Ui,Wi=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];return this._map.set(e,n),n&&typeof n==`object`&&`id`in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function Gi(){return new Wi}(Ui=globalThis).__zod_globalRegistry??(Ui.__zod_globalRegistry=Gi());var Ki=globalThis.__zod_globalRegistry;function qi(e){return e.checks&&=[...e.checks],e}function Ji(e,t){return new e(qi({type:`string`,...g(t)}))}function Yi(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...g(t)})}function Xi(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...g(t)})}function Zi(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...g(t)})}function Qi(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...g(t)})}function $i(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...g(t)})}function ea(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...g(t)})}function ta(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...g(t)})}function na(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...g(t)})}function ra(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...g(t)})}function ia(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...g(t)})}function aa(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...g(t)})}function oa(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...g(t)})}function sa(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...g(t)})}function ca(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...g(t)})}function la(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...g(t)})}function ua(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...g(t)})}function da(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...g(t)})}function fa(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...g(t)})}function pa(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...g(t)})}function ma(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...g(t)})}function ha(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...g(t)})}function ga(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...g(t)})}function _a(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...g(t)})}function va(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...g(t)})}function ya(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...g(t)})}function ba(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...g(t)})}function xa(e,t){return new e(qi({type:`number`,checks:[],...g(t)}))}function Sa(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...g(t)})}function Ca(e,t){return new e({type:`boolean`,...g(t)})}function wa(e,t){return new e({type:`null`,...g(t)})}function Ta(e){return new e({type:`unknown`})}function Ea(e,t){return new e({type:`never`,...g(t)})}function Da(e,t){return new vn({check:`less_than`,...g(t),value:e,inclusive:!1})}function Oa(e,t){return new vn({check:`less_than`,...g(t),value:e,inclusive:!0})}function ka(e,t){return new yn({check:`greater_than`,...g(t),value:e,inclusive:!1})}function Aa(e,t){return new yn({check:`greater_than`,...g(t),value:e,inclusive:!0})}function ja(e,t){return new bn({check:`multiple_of`,...g(t),value:e})}function Ma(e,t){return new Sn({check:`max_length`,...g(t),maximum:e})}function Na(e,t){return new Cn({check:`min_length`,...g(t),minimum:e})}function Pa(e,t){return new wn({check:`length_equals`,...g(t),length:e})}function Fa(e,t){return new En({check:`string_format`,format:`regex`,...g(t),pattern:e})}function Ia(e){return new Dn({check:`string_format`,format:`lowercase`,...g(e)})}function La(e){return new On({check:`string_format`,format:`uppercase`,...g(e)})}function Ra(e,t){return new kn({check:`string_format`,format:`includes`,...g(t),includes:e})}function za(e,t){return new An({check:`string_format`,format:`starts_with`,...g(t),prefix:e})}function Ba(e,t){return new jn({check:`string_format`,format:`ends_with`,...g(t),suffix:e})}function Va(e){return new Mn({check:`overwrite`,tx:e})}function Ha(e){return Va(t=>t.normalize(e))}function Ua(){return Va(e=>e.trim())}function Wa(){return Va(e=>e.toLowerCase())}function Ga(){return Va(e=>e.toUpperCase())}function Ka(){return Va(e=>re(e))}function qa(e,t,n){return new e({type:`array`,element:t,...g(n)})}function Ja(e,t,n){let r=g(n);return r.abort??=!0,new e({type:`custom`,check:`custom`,fn:t,...r})}function Ya(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...g(n)})}function Xa(e,t){let n=Za(t=>(t.addIssue=e=>{if(typeof e==`string`)t.issues.push(Le(e,t.value,n._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,`input`in r||(r.input=t.value),r.inst??=n,r.continue??=!n._zod.def.abort,t.issues.push(Le(r))}},e(t.value,t)),t);return n}function Za(e,t){let n=new hn({check:`custom`,...g(t)});return n._zod.check=e,n}function Qa(e,...t){for(let n of t)for(let t of Reflect.ownKeys(n))Object.prototype.propertyIsEnumerable.call(n,t)&&u(e,t,n[t]);return e}function $a(e){let t=e?.target??`draft-2020-12`;return t===`draft-4`&&(t=`draft-04`),t===`draft-7`&&(t=`draft-07`),{processors:e.processors??{},metadataRegistry:e?.metadata??Ki,target:t,unrepresentable:e?.unrepresentable??`throw`,override:e?.override??(()=>{}),io:e?.io??`output`,counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??`ref`,reused:e?.reused??`inline`,intersections:[],deferred:[],external:e?.external??void 0}}function eo(e,t,n,r,i){let a=typeof t.unrepresentable==`function`?t.unrepresentable({zodSchema:e,path:r.path,message:i}):t.unrepresentable;if(a===`any`)return!1;if(a===void 0||a===`throw`)throw Error(i);return Object.assign(n,a),!0}function to(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,a=t.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;let s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{let r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,r);else{let n=o.schema,a=t.processors[i.type];if(!a)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);a(e,t,n,r)}let a=e._zod.parent;a&&(o.ref||=a,to(a,t,r),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&Qa(o.schema,c),t.io===`input`&&fo(e)&&(delete o.schema.examples,delete o.schema.default),t.io===`input`&&`_prefault`in o.schema&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function no(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function ro(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);if(e.external&&e.sharedDefsExtractedFor===e.external)return;let r=new Map;for(let t of e.seen.entries()){let n=e.metadataRegistry.get(t[0])?.id;if(n){let e=r.get(n);if(e&&e!==t[0])throw Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}let i=t=>{let r=e.target===`draft-2020-12`?`$defs`:`definitions`;if(e.external){let n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};let a=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=a,{defId:a,ref:`${i(`__shared`)}#/${r}/${no(a)}`}}let i=`#/${r}/`;if(t[1]===n&&!t[1].schema.id)return{ref:`#`};let a=t[1].schema.id??`__schema${e.counter++}`;return{defId:a,ref:i+no(a)}},a=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:n,defId:r}=i(e);t.def={...t.schema},r&&(t.defId=r);let a=t.schema;for(let e in a)delete a[e];a.$ref=n};if(e.cycles===`throw`)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join(`/`)}/<root>
|
|
54
54
|
|
|
55
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0])a(n);else{if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}(e.metadataRegistry.get(n[0])?.id||r.cycle||r.count>1&&e.reused===`ref`)&&a(n)}}e.external&&(e.sharedDefsExtractedFor=e.external)}function io(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let n=[];for(let e of t){if(!e||typeof e!=`object`)return;io(e);let t=Object.keys(e);if(t.length!==1||t[0]!==`type`)return;let r=e.type;for(let e of Array.isArray(r)?r:[r]){if(typeof e!=`string`)return;n.includes(e)||n.push(e)}}delete e.anyOf,e.type=n.length===1?n[0]:n}var ao=new Set([`type`,`properties`,`required`,`additionalProperties`]),oo=[`oneOf`,`anyOf`];function so(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!=`object`||!t?null:Object.keys(t).length?t:null}function co(e){let t=[];for(let n of e){if(typeof n!=`object`||n.type!==`object`)return null;for(let e in n)if(!ao.has(e))return null;t.push(n)}let n={},r=new Set;for(let e of t){for(let r in e.properties){if(Object.prototype.hasOwnProperty.call(n,r))continue;let e=[];for(let n of t){let t=n.properties?.[r]??so(n);t!=null&&(e.some(e=>JSON.stringify(e)===JSON.stringify(t))||e.push(t))}u(n,r,e.length===1?e[0]:co(e)??{allOf:e})}for(let t of e.required??[])r.add(t)}let i={type:`object`,properties:n};if(r.size&&(i.required=[...r]),t.every(e=>e.additionalProperties===!1))i.additionalProperties=!1;else{let e=[];for(let n of t){let t=so(n);t&&!e.some(e=>JSON.stringify(e)===JSON.stringify(t))&&e.push(t)}e.length===1?i.additionalProperties=e[0]:e.length>1&&(i.additionalProperties={allOf:e})}return i}function lo(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let t of ao)if(t in e)return;let n=t.filter(e=>oo.some(t=>Array.isArray(e[t]))),r=null;if(!n.length)r=co(t);else{let e=n[0],i=oo.find(t=>Array.isArray(e[t]));if(Object.keys(e).length!==1)return;let a=t.filter(t=>t!==e),o=e[i].map(e=>co([...a,e]));if(o.some(e=>!e))return;r={[i]:o}}r&&(delete e.allOf,Qa(e,r))}function uo(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):Qa(i,s),Qa(i,a),t._zod.parent===o)for(let e in i)e!==`$ref`&&e!==`allOf`&&(e in a||delete i[e]);if(s.$ref&&n.def)for(let e in i)e!==`$ref`&&e!==`allOf`&&e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e!==`$ref`&&e!==`allOf`&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let t of[...e.seen.entries()].reverse())r(t[0]);if(e.target!==`openapi-3.0`)for(let t of e.seen.entries())io(t[1].def??t[1].schema);for(let t of e.deferred)t();if(e.intersections.length){let t=new Map;for(let n of e.seen.values())for(let e of[n.schema,n.def]){let n=e?.allOf;if(!Array.isArray(n))continue;let r=t.get(n);r?r.push(e):t.set(n,[e])}for(let n of e.intersections)for(let e of t.get(n)??[])lo(e)}}let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}Qa(i,n.defId?n.schema:n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,u(o,e.defId,e.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t[`~standard`],jsonSchema:{input:mo(t,`input`,e.processors),output:mo(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function fo(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return fo(r.element,n);if(r.type===`set`)return fo(r.valueType,n);if(r.type===`lazy`)return fo(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`||r.type===`catch`)return fo(r.innerType,n);if(r.type===`intersection`)return fo(r.left,n)||fo(r.right,n);if(r.type===`record`||r.type===`map`)return fo(r.keyType,n)||fo(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:fo(r.in,n)||fo(r.out,n);if(r.type===`object`){for(let e in r.shape)if(fo(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(fo(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(fo(e,n))return!0;return!!(r.rest&&fo(r.rest,n))}return!1}var po=(e,t={})=>n=>{let r=$a({...n,processors:t});return to(e,r),ro(r,e),uo(r,e)},mo=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=$a({...i??{},target:a,io:t,processors:n});return to(e,o),ro(o,e),uo(o,e)},ho=(e,t,n)=>{(e[t]===void 0||n>e[t])&&(e[t]=n)},go=(e,t,n)=>{(e[t]===void 0||n<e[t])&&(e[t]=n)},_o=(e,t)=>{ho(e,`minimum`,t),go(e,`maximum`,t)},vo=(e,t)=>{e.multipleOf??=[],e.multipleOf.includes(t)||e.multipleOf.push(t)},yo=(e,t)=>{e.patterns??=new Set,e.patterns.add(t)},bo=(e,t)=>{e.mime=e.mime?e.mime.filter(e=>t.includes(e)):[...t]},xo=(e,t)=>{e.format=t,t.includes(`int`)&&(e.isInt=!0)},So=(e,t)=>ho(e,`minimum`,t.minimum),Co=(e,t)=>go(e,`maximum`,t.maximum),wo=e=>(t,n)=>{xo(t,n.format);let[r,i]=e[n.format];ho(t,`minimum`,r),go(t,`maximum`,i)},To={greater_than:(e,t)=>ho(e,t.inclusive?`minimum`:`exclusiveMinimum`,t.value),less_than:(e,t)=>go(e,t.inclusive?`maximum`:`exclusiveMaximum`,t.value),multiple_of:(e,t)=>vo(e,t.value),number_format:wo(he),bigint_format:wo(ge),min_length:So,max_length:Co,length_equals:(e,t)=>_o(e,t.length),min_size:So,max_size:Co,size_equals:(e,t)=>_o(e,t.size),string_format:(e,t)=>{xo(e,t.format),t.pattern&&yo(e,t.pattern),(t.format===`base64`||t.format===`base64url`)&&(e.contentEncoding=t.format),(t.local||t.precision===-1)&&(e.laxFormat=!0)},mime_type:(e,t)=>bo(e,t.mime)};function Eo(e){let t={},n=e._zod.def,r=e._zod.traits.has(`$ZodCheck`)?[e,...n.checks??[]]:n.checks??[];for(let e of r)To[e._zod.def.check]?.(t,e._zod.def);let i=e._zod.bag;i.minimum!==void 0&&ho(t,`minimum`,i.minimum),i.exclusiveMinimum!==void 0&&ho(t,`exclusiveMinimum`,i.exclusiveMinimum),i.maximum!==void 0&&go(t,`maximum`,i.maximum),i.exclusiveMaximum!==void 0&&go(t,`exclusiveMaximum`,i.exclusiveMaximum),i.multipleOf!==void 0&&vo(t,i.multipleOf),i.format!==void 0&&(t.format??=i.format,i.format.includes(`int`)&&(t.isInt=!0)),i.mime&&bo(t,i.mime);for(let e of i.patterns??[])yo(t,e);return t}var Do={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},Oo=new Map([[_r,Xt],[yr,Zt]]),ko=e=>Oo.get(e)??e,Ao=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l,laxFormat:u}=Eo(e);if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=Do[s]??s,i.format===``&&delete i.format,(s===`time`||u)&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c].map(ko);e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},jo=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,multipleOf:s,exclusiveMaximum:c,exclusiveMinimum:l,isInt:u}=Eo(e);i.type=u?`integer`:`number`;let d=typeof l==`number`&&l>=(a??-1/0),f=typeof c==`number`&&c<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;if(d?p?(i.minimum=l,i.exclusiveMinimum=!0):i.exclusiveMinimum=l:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=c,i.exclusiveMaximum=!0):i.exclusiveMaximum=c:typeof o==`number`&&(i.maximum=o),s){let n=new Set;for(let a of s)Number.isFinite(a)&&a!==0?n.add(Math.abs(a)):eo(e,t,i,r,`A multipleOf divisor of ${a} cannot be represented in JSON Schema`);let[a,...o]=n;a!==void 0&&(i.multipleOf=a),o.length&&(i.allOf=[...i.allOf??[],...o.map(e=>({multipleOf:e}))])}},Mo=(e,t,n,r)=>{n.type=`boolean`},No=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},Po=(e,t,n,r)=>{n.not={}},Fo=(t,n,r,i)=>{let a=t._zod.def,o=e(a.entries);o.length===0?r.not={}:(o.every(e=>typeof e==`number`)&&(r.type=`number`),o.every(e=>typeof e==`string`)&&(r.type=`string`),r.enum=o)},Io=(e,t,n,r)=>{let i=e._zod.def;if(i.values.length===0){n.not={};return}let a=[];for(let o of i.values)if(o===void 0){if(eo(e,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof o==`bigint`){if(eo(e,t,n,r,`BigInt literals cannot be represented in JSON Schema`))return;a.push(Number(o))}else a.push(o);if(a.length!==0){if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a}},Lo=(e,t,n,r)=>{let i=n,a=e._zod.pattern;if(!a)throw Error(`Pattern not found in template literal`);i.type=`string`,i.pattern=a.source},Ro=(e,t,n,r)=>{eo(e,t,n,r,`Custom types cannot be represented in JSON Schema`)},zo=(e,t,n,r)=>{eo(e,t,n,r,`Transforms cannot be represented in JSON Schema`)},Bo=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=Eo(e);typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=to(a.element,t,{...r,path:[...r.path,`items`]})};function Vo(e){let t=e._zod.def;return t.type===`pipe`&&t.in._zod.traits.has(`$ZodTransform`)?Vo(t.out):t.type===`catch`?Vo(t.innerType):e._zod.optin}var Ho=(e,t,n,r)=>{let i=n,a=e._zod.def,o=a.shape;if(Object.getOwnPropertySymbols(o).length&&eo(e,t,i,r,`Symbol keys cannot be represented in JSON Schema`))return;i.type=`object`,i.properties={};for(let e in o)u(i.properties,e,to(o[e],t,{...r,path:[...r.path,`properties`,e]}));let s=[];for(let e of Object.keys(o)){let n=a.shape[e];(t.io===`input`?Vo(n)===void 0:n._zod.optout===void 0)&&s.push(e)}s.length>0&&(i.required=s),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=to(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},Uo=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>to(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},Wo=(e,t,n,r)=>{let i=e._zod.def,a=to(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=to(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1,c=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]];n.allOf=c,t.intersections.push(c)},Go=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`array`;let o=t.target===`draft-2020-12`?`prefixItems`:`items`,s=t.target===`draft-2020-12`||t.target===`openapi-3.0`?`items`:`additionalItems`,c=a.items.map((e,n)=>to(e,t,{...r,path:[...r.path,o,n]})),l=a.rest?to(a.rest,t,{...r,path:[...r.path,s,...t.target===`openapi-3.0`?[a.items.length]:[]]}):null,u=a.items.length;for(;u>0;){let e=a.items[u-1];if(!(t.io===`input`?Vo(e)!==void 0:e._zod.optout===`optional`))break;u--}let d=a.items.length,f=!a.rest;t.target===`draft-2020-12`?(i.prefixItems=c,f?i.items=!1:l&&(i.items=l),u>0&&(i.minItems=u),f&&(i.maxItems=d)):t.target===`openapi-3.0`?(i.items={anyOf:c},l&&i.items.anyOf.push(l),u>0&&(i.minItems=u),f&&(i.maxItems=d)):(i.items=c,f?i.additionalItems=!1:l&&(i.additionalItems=l),u>0&&(i.minItems=u),f&&(i.maxItems=d));let{minimum:p,maximum:m}=Eo(e);typeof p==`number`&&(i.minItems=p),typeof m==`number`&&(i.maxItems=m)};function Ko(e,t,n){if(t.$ref){if(n.has(t))return t;n.add(t);let r=e.get(t)?.def;if(!r)return t;let i=Ko(e,r,n);return i===r?t:i}for(let r of[`anyOf`,`oneOf`]){let i=t[r];if(!Array.isArray(i))continue;let a=i.map(t=>Ko(e,t,n));a.some((e,t)=>e!==i[t])&&(t={...t,[r]:a})}let r=Array.isArray(t.type)?t.type:[t.type],i=!r.includes(`string`)&&r.some(e=>e===`number`||e===`integer`),a=t.enum??(t.const===void 0?void 0:[t.const]);if(!i&&!a?.some(e=>typeof e==`number`))return t;let{minimum:o,maximum:s,exclusiveMinimum:c,exclusiveMaximum:l,multipleOf:u,format:d,id:f,...p}=t;return p.enum?p.enum=p.enum.map(e=>typeof e==`number`?String(e):e):typeof p.const==`number`&&(p.const=String(p.const)),i&&(p.type=`string`,a||(p.pattern=(r.includes(`number`)?un:ln).source)),p}var qo=new WeakMap;function Jo(e){let t=new Map;for(let n of e.seen.values())n.def&&!t.has(n.schema)&&t.set(n.schema,n);let n=new Map;for(let r of qo.get(e)??[]){let i=e.seen.get(r),a=(i?.def??i?.schema)?.propertyNames;if(!a||a===!0||n.has(a))continue;let o=Ko(t,a,new Set);o!==a&&n.set(a,o)}if(n.size)for(let t of e.seen.values())for(let e of[t.schema,t.def]){let t=e&&n.get(e.propertyNames);t&&(e.propertyNames=t)}}var Yo=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=Eo(o).patterns;if(a.mode===`loose`&&s&&s.size>0){let e=to(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)u(i.patternProperties,ko(t).source,e)}else{if(t.target===`draft-07`||t.target===`draft-2020-12`){i.propertyNames=to(a.keyType,t,{...r,path:[...r.path,`propertyNames`]});let n=qo.get(t);n||(n=[],qo.set(t,n),t.deferred.push(()=>Jo(t))),n.push(e)}i.additionalProperties=to(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]})}let c=o._zod.values,l=t.io===`input`&&Vo(a.valueType)!==void 0;if(c&&!a.partial&&!l){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e.map(String))}},Xo=(e,t,n,r)=>{let i=e._zod.def,a=to(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},Zo=(e,t,n,r)=>{let i=e._zod.def;to(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Qo=Symbol();function $o(e,t,n,r,i){let a=!1,o=JSON.stringify(e,(e,t)=>typeof t==`bigint`?(a=!0,null):t);return a?(eo(t,n,r,i,`BigInt defaults cannot be represented in JSON Schema`),Qo):JSON.parse(o)}var es=(e,t,n,r)=>{let i=e._zod.def;to(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o=$o(i.defaultValue,e,t,n,r);o!==Qo&&(n.default=o)},ts=(e,t,n,r)=>{let i=e._zod.def;to(i.innerType,t,r);let a=t.seen.get(e);if(a.ref=i.innerType,t.io!==`input`)return;let o=$o(i.defaultValue,e,t,n,r);o!==Qo&&(n._prefault=o)},ns=(e,t,n,r)=>{let i=e._zod.def;to(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{eo(e,t,n,r,`Dynamic catch values are not supported in JSON Schema`);return}n.default=o},rs=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;to(o,t,r);let s=t.seen.get(e);s.ref=o},is=(e,t,n,r)=>{let i=e._zod.def;to(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},as=(e,t,n,r)=>{let i=e._zod.def;to(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},os=(e,t,n,r)=>{let i=e._zod.innerType;to(i,t,r);let a=t.seen.get(e);a.ref=i},ss=new WeakSet([Object.prototype,Error.prototype]);function cs(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let e=n(this);return Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0})}})}var ls=_(`ZodError`,(e,t)=>{ut.init(e,t),e.name=`ZodError`;let r=Object.getPrototypeOf(e);ss.has(r)||(ss.add(r),cs(r,`format`,e=>t=>pt(e,t)),cs(r,`flatten`,e=>t=>ft(e,t)),cs(r,`addIssue`,e=>t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,n,2)}),cs(r,`addIssues`,e=>t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,n,2)}),Object.defineProperty(r,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},void 0,{Parent:Error}),us=ht(ls),ds=gt(ls),fs=_t(ls),ps=yt(ls),ms=Tt(ls),hs=Et(ls),gs=Dt(ls),_s=Ot(ls),vs=kt(ls),ys=At(ls),bs=jt(ls),xs=Mt(ls);function Ss(){rt.localeError||it(Hi())}function Cs(){rt.memoizer||it({memoizer:zi()})}var ws=_(`ZodType`,(e,t)=>(Ss(),Fn.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(te(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return fe(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(Yc(e,t))},superRefine(e,t){return this.check(Xc(e,t))},overwrite(e){return this.check(Va(e))},optional(){return Ec(this)},exactOptional(){return Oc(this)},nullable(){return Ac(this)},nullish(){return Ec(Ac(this))},nonoptional(e){return Ic(this,e)},array(){return x(this)},or(e){return C([this,e])},and(e){return gc(this,e)},transform(e){return Bc(this,wc(e))},default(e){return Mc(this,e)},prefault(e){return Pc(this,e)},catch(e){return Rc(this,e)},pipe(e){return Bc(this,e)},readonly(){return Hc(this)},describe(e){let t=this.clone();return Ki.add(t,{description:e}),t},meta(...e){if(e.length===0)return Ki.get(this);let t=this.clone();return Ki.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get"~standard"(){return Be(this,`~standard`,{...Rn(this),jsonSchema:{input:mo(this,`input`),output:mo(this,`output`)}})},set"~standard"(e){ze(this,`~standard`,e)},parse:function e(t,n){return us(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await ds(this,t,n,{callee:e})},safeParse(e,t){return fs(this,e,t)},async safeParseAsync(e,t){return ps(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){ze(this,`spa`,e)},validate(e,t){return St(this,e,t)},validateAsync(e,t){return wt(this,e,t)},encode:function e(t,n){return ms(this,t,n,{callee:e})},decode:function e(t,n){return hs(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await gs(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await _s(this,t,n,{callee:e})},safeEncode(e,t){return vs(this,e,t)},safeDecode(e,t){return ys(this,e,t)},async safeEncodeAsync(e,t){return bs(this,e,t)},async safeDecodeAsync(e,t){return xs(this,e,t)},toJSONSchema(e){return po(this,{})(e)},get description(){return Ki.get(this)?.description},get _def(){return this._zod.def}}),Ts=_(`_ZodString`,(e,t)=>{zn.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ao(e,t,n,r)},Ve({format:e=>Eo(e).format??null,minLength:e=>Eo(e).minimum??null,maxLength:e=>Eo(e).maximum??null},{regex(...e){return this.check(Fa(...e))},includes(...e){return this.check(Ra(...e))},startsWith(...e){return this.check(za(...e))},endsWith(...e){return this.check(Ba(...e))},min(...e){return this.check(Na(...e))},max(...e){return this.check(Ma(...e))},length(...e){return this.check(Pa(...e))},nonempty(...e){return this.check(Na(1,...e))},lowercase(e){return this.check(Ia(e))},uppercase(e){return this.check(La(e))},trim(){return this.check(Ua())},normalize(...e){return this.check(Ha(...e))},toLowerCase(){return this.check(Wa())},toUpperCase(){return this.check(Ga())},slugify(){return this.check(Ka())}})),Es=_(`ZodString`,(e,t)=>{zn.init(e,t),Ts.init(e,t)},{email(e){return this.check(Yi(Ms,e))},url(e){return this.check(ta(Is,e))},jwt(e){return this.check(ga(Qs,e))},emoji(e){return this.check(na(Rs,e))},guid(e){return this.check(Xi(Ps,e))},uuid(e){return this.check(Zi(Fs,e))},uuidv4(e){return this.check(Qi(Fs,e))},uuidv6(e){return this.check($i(Fs,e))},uuidv7(e){return this.check(ea(Fs,e))},nanoid(e){return this.check(ra(zs,e))},cuid(e){return this.check(ia(Bs,e))},cuid2(e){return this.check(aa(Vs,e))},ulid(e){return this.check(oa(Hs,e))},base64(e){return this.check(pa(Ys,e))},base64url(e){return this.check(ma(Xs,e))},xid(e){return this.check(sa(Us,e))},ksuid(e){return this.check(ca(Ws,e))},ipv4(e){return this.check(la(Gs,e))},ipv6(e){return this.check(ua(Ks,e))},cidrv4(e){return this.check(da(qs,e))},cidrv6(e){return this.check(fa(Js,e))},e164(e){return this.check(ha(Zs,e))},datetime(e){return this.check(_a(Os,e))},date(e){return this.check(va(ks,e))},time(e){return this.check(ya(As,e))},duration(e){return this.check(ba(js,e))}});function v(e){return Ji(Es,e)}var Ds=_(`ZodStringFormat`,(e,t)=>{Bn.init(e,t),Ts.init(e,t)}),Os=_(`ZodISODateTime`,(e,t)=>{ar.init(e,t),Ds.init(e,t)}),ks=_(`ZodISODate`,(e,t)=>{or.init(e,t),Ds.init(e,t)}),As=_(`ZodISOTime`,(e,t)=>{sr.init(e,t),Ds.init(e,t)}),js=_(`ZodISODuration`,(e,t)=>{cr.init(e,t),Ds.init(e,t)}),Ms=_(`ZodEmail`,(e,t)=>{Un.init(e,t),Ds.init(e,t)});function Ns(e){return Yi(Ms,e)}var Ps=_(`ZodGUID`,(e,t)=>{Vn.init(e,t),Ds.init(e,t)}),Fs=_(`ZodUUID`,(e,t)=>{Hn.init(e,t),Ds.init(e,t)}),Is=_(`ZodURL`,(e,t)=>{Zn.init(e,t),Ds.init(e,t)});function Ls(e){return ta(Is,e)}var Rs=_(`ZodEmoji`,(e,t)=>{Qn.init(e,t),Ds.init(e,t)}),zs=_(`ZodNanoID`,(e,t)=>{$n.init(e,t),Ds.init(e,t)}),Bs=_(`ZodCUID`,(e,t)=>{er.init(e,t),Ds.init(e,t)}),Vs=_(`ZodCUID2`,(e,t)=>{tr.init(e,t),Ds.init(e,t)}),Hs=_(`ZodULID`,(e,t)=>{nr.init(e,t),Ds.init(e,t)}),Us=_(`ZodXID`,(e,t)=>{rr.init(e,t),Ds.init(e,t)}),Ws=_(`ZodKSUID`,(e,t)=>{ir.init(e,t),Ds.init(e,t)}),Gs=_(`ZodIPv4`,(e,t)=>{lr.init(e,t),Ds.init(e,t)}),Ks=_(`ZodIPv6`,(e,t)=>{fr.init(e,t),Ds.init(e,t)}),qs=_(`ZodCIDRv4`,(e,t)=>{pr.init(e,t),Ds.init(e,t)}),Js=_(`ZodCIDRv6`,(e,t)=>{hr.init(e,t),Ds.init(e,t)}),Ys=_(`ZodBase64`,(e,t)=>{vr.init(e,t),Ds.init(e,t)}),Xs=_(`ZodBase64URL`,(e,t)=>{xr.init(e,t),Ds.init(e,t)}),Zs=_(`ZodE164`,(e,t)=>{Sr.init(e,t),Ds.init(e,t)}),Qs=_(`ZodJWT`,(e,t)=>{wr.init(e,t),Ds.init(e,t)}),$s=_(`ZodNumber`,(e,t)=>{Tr.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>jo(e,t,n,r),e.isFinite=!0},Ve({minValue:e=>{let{minimum:t,exclusiveMinimum:n}=Eo(e);return Math.max(t??-1/0,n??-1/0)},maxValue:e=>{let{maximum:t,exclusiveMaximum:n}=Eo(e);return Math.min(t??1/0,n??1/0)},isInt:e=>{let{isInt:t,multipleOf:n}=Eo(e);return!!t||!!n?.some(Number.isSafeInteger)},format:e=>Eo(e).format??null},{gt(e,t){return this.check(ka(e,t))},gte(e,t){return this.check(Aa(e,t))},min(e,t){return this.check(Aa(e,t))},lt(e,t){return this.check(Da(e,t))},lte(e,t){return this.check(Oa(e,t))},max(e,t){return this.check(Oa(e,t))},int(e){return this.check(tc(e))},safe(e){return this.check(tc(e))},positive(e){return this.check(ka(0,e))},nonnegative(e){return this.check(Aa(0,e))},negative(e){return this.check(Da(0,e))},nonpositive(e){return this.check(Oa(0,e))},multipleOf(e,t){return this.check(ja(e,t))},step(e,t){return this.check(ja(e,t))},finite(){return this}}));function y(e){return xa($s,e)}var ec=_(`ZodNumberFormat`,(e,t)=>{Er.init(e,t),$s.init(e,t)});function tc(e){return Sa(ec,e)}var nc=_(`ZodBoolean`,(e,t)=>{Dr.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Mo(e,t,n,r)});function b(e){return Ca(nc,e)}var rc=_(`ZodNull`,(e,t)=>{Or.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>No(e,t,n,r)});function ic(e){return wa(rc,e)}var ac=_(`ZodAny`,(e,t)=>{kr.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0}),oc=_(`ZodUnknown`,(e,t)=>{Ar.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function sc(){return Ta(oc)}var cc=_(`ZodNever`,(e,t)=>{jr.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Po(e,t,n,r)});function lc(e){return Ea(cc,e)}var uc=_(`ZodArray`,(e,t)=>{Cs(),Fr.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Bo(e,t,n,r),e.element=t.element},{min(e,t){return this.check(Na(e,t))},nonempty(e){return this.check(Na(1,e))},max(e,t){return this.check(Ma(e,t))},length(e,t){return this.check(Pa(e,t))},unwrap(){return this.element}});function x(e,t){return qa(uc,e,t)}var dc=_(`ZodObject`,(e,t)=>{Cs(),Vr.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ho(e,t,n,r),Je(e,`shape`,e=>e._zod.def.shape,!1)},{keyof(){return E(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(te(this._zod.def,{catchall:e}))},passthrough(){return this.clone(te(this._zod.def,{catchall:sc()}))},loose(){return this.clone(te(this._zod.def,{catchall:sc()}))},strict(){return this.clone(te(this._zod.def,{catchall:lc()}))},strip(){return this.clone(te(this._zod.def,{catchall:void 0}))},extend(e){return be(this,e)},safeExtend(e){return Se(this,e)},merge(e){return Ce(this,e)},pick(e){return _e(this,e)},omit(e){return ye(this,e)},partial(...e){return we(Tc,this,e[0])},exactPartial(...e){return we(Dc,this,e[0],`exactPartial`)},required(...e){return Te(Fc,this,e[0])}});function S(e,t){return new dc({type:`object`,shape:e??{},...g(t)})}function fc(e,t){return new dc({type:`object`,shape:e,catchall:sc(),...g(t)})}var pc=_(`ZodUnion`,(e,t)=>{Ur.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Uo(e,t,n,r),e.options=t.options});function C(e,t){return new pc({type:`union`,options:e,...g(t)})}var mc=_(`ZodDiscriminatedUnion`,(e,t)=>{pc.init(e,t),Gr.init(e,t)});function w(e,t,n){return new mc({type:`union`,options:t,discriminator:e,...g(n)})}var hc=_(`ZodIntersection`,(e,t)=>{Kr.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Wo(e,t,n,r)});function gc(e,t){return new hc({type:`intersection`,left:e,right:t})}var _c=_(`ZodTuple`,(e,t)=>{Cs(),Yr.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Go(e,t,n,r)},{rest(e){return this.clone({...this._zod.def,rest:e})},partial(){let e=this._zod.def;if(e.checks?.length)throw Error(`.partial() cannot be used on tuple schemas containing refinements`);return this.clone({...e,items:e.items.map(e=>new Tc({type:`optional`,innerType:e}))})}});function vc(e,t,n){let r=t instanceof Fn;return new _c({type:`tuple`,items:e,rest:r?t:null,...g(r?n:t)})}var yc=_(`ZodRecord`,(e,t)=>{Cs(),$r.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Yo(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function T(e,t,n){return!t||!t._zod?new yc({type:`record`,keyType:v(),valueType:e,...g(t)}):new yc({type:`record`,keyType:e,valueType:t,...g(n)})}function bc(e,t,n){return new yc({type:`record`,keyType:e,valueType:t,...g(n),partial:!0})}var xc=_(`ZodEnum`,(e,t)=>{ei.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Fo(e,t,n,r),e.enum=t.entries,e.options=[...e._zod.values];let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new xc({...t,checks:[],...g(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new xc({...t,checks:[],...g(r),entries:i})}});function E(e,t){return new xc({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...g(t)})}var Sc=_(`ZodLiteral`,(e,t)=>{ti.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Io(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function D(e,t){return new Sc({type:`literal`,values:Array.isArray(e)?e:[e],...g(t)})}var Cc=_(`ZodTransform`,(e,t)=>{Cs(),ni.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>zo(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new nt(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(Le(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,`input`in t||(t.input=n.value),t.inst??=e,n.issues.push(Le(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function wc(e){return new Cc({type:`transform`,transform:e})}var Tc=_(`ZodOptional`,(e,t)=>{ii.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>as(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ec(e){return new Tc({type:`optional`,innerType:e})}var Dc=_(`ZodExactOptional`,(e,t)=>{ai.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>as(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Oc(e){return new Dc({type:`optional`,innerType:e})}var kc=_(`ZodNullable`,(e,t)=>{oi.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Xo(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ac(e){return new kc({type:`nullable`,innerType:e})}var jc=_(`ZodDefault`,(e,t)=>{si.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>es(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Mc(e,t){return new jc({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():ce(t)}})}var Nc=_(`ZodPrefault`,(e,t)=>{li.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ts(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Pc(e,t){return new Nc({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():ce(t)}})}var Fc=_(`ZodNonOptional`,(e,t)=>{ui.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Zo(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ic(e,t){return new Fc({type:`nonoptional`,innerType:e,...g(t)})}var Lc=_(`ZodCatch`,(e,t)=>{pi.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ns(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Rc(e,t){return new Lc({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:Xe(t)})}var zc=_(`ZodPipe`,(e,t)=>{mi.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>rs(e,t,n,r),e.in=t.in,e.out=t.out});function Bc(e,t){return new zc({type:`pipe`,in:e,out:t})}var Vc=_(`ZodReadonly`,(e,t)=>{gi.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>is(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Hc(e){return new Vc({type:`readonly`,innerType:e})}var Uc=_(`ZodTemplateLiteral`,(e,t)=>{bi.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Lo(e,t,n,r)});function Wc(e,t){return new Uc({type:`template_literal`,parts:e,...g(t)})}var Gc=_(`ZodLazy`,(e,t)=>{xi.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>os(e,t,n,r),e.unwrap=()=>e._zod.def.getter()});function Kc(e){return new Gc({type:`lazy`,getter:e})}var qc=_(`ZodCustom`,(e,t)=>{Si.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ro(e,t,n,r)});function Jc(e,t){return Ja(qc,e??(()=>!0),t)}function Yc(e,t={}){return Ya(qc,e,t)}function Xc(e,t){return Xa(e,t)}function Zc(e){let t=Kc(()=>C([v(e),y(),b(),ic(),x(t),T(v(),t)]));return t}function Qc(e){return _a(Os,e)}function $c(e){return va(ks,e)}var O=Zc(),el=T(v(),O);function tl(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var nl={run:`run`,turn:`trn`,session:`ses`,actor:`act`,message:`msg`,delivery:`dlv`,handlerCall:`hcl`,llmInteraction:`llm`,pairing:`par`,pairingToken:`ptk`,policy:`pol`,approval:`apr`,budget:`bgt`,priorityRule:`pri`,reservation:`rsv`,ledger:`led`,notification:`ntf`,push:`psh`,secret:`sec`,modelCategory:`mct`,provider:`prv`,sectionRule:`srl`,authSession:`aus`,modelCall:`mdl`,mcp:`mcp`,autoPair:`apk`,connection:`cnx`,fnExample:`fex`,refusal:`rfs`,record:`rec`,mentionRequest:`mrq`},rl=e=>v().regex(RegExp(`^${nl[e]}_.+$`),`expected a ${e} id starting with "${nl[e]}_"`).brand().describe(`${e} id`),il=e=>Object.hasOwn(nl,e);function al(){return Object.fromEntries(Object.keys(nl).filter(il).map(e=>[e,rl(e)]))}var k=v().regex(/^[A-Za-z_][A-Za-z0-9_.-]*$/),ol=al(),A=ol.run,sl=ol.turn,j=ol.session,M=ol.actor,cl=ol.message,ll=ol.delivery,ul=ol.handlerCall,dl=ol.llmInteraction,fl=ol.pairing,pl=ol.pairingToken,ml=ol.policy,hl=ol.approval,gl=ol.budget,_l=ol.priorityRule,vl=ol.reservation,yl=ol.ledger,bl=ol.notification,xl=ol.push,Sl=ol.secret,Cl=ol.modelCategory,wl=ol.provider,Tl=ol.sectionRule,El=ol.authSession,Dl=ol.modelCall,Ol=ol.mcp,kl=ol.autoPair,Al=ol.connection,jl=y().int().min(0),N=y().int(),P=y(),Ml=/^[a-z][a-z0-9-]*$/,F=v().regex(Ml).brand(),I=Wc([v().regex(Ml),`/`,v().min(1)]),Nl=C([D(`native`),I]);function Pl(e,t){return`${e}/${t}`}function Fl(e){let t=e.indexOf(`/`);return{system:e.slice(0,t),local:e.slice(t+1)}}var Il=[`urgent`,`interactive`,`normal`,`background`],Ll=E(Il),Rl=E([`user`,`llm`,`both`,`none`]),zl=E([`user`,`group`,`agent`,`system`,`mcp`]),Bl=e=>S({items:x(e),cursor:v().optional()}),Vl=S({cursor:v().optional(),limit:y().int().min(1).max(200).optional()});function Hl(e){return e instanceof Error?e.message:String(e)}var Ul=`read`,Wl=`admin`,L=v().regex(Ml).brand(),Gl=L.parse(`main`),Kl=S({system:F,instance:L}),ql=v().regex(/^[a-z*][a-z0-9*-]*\/[A-Za-z0-9_.*-]+$/).brand(),Jl=Object.defineProperty,Yl=(e,t)=>{for(var n in t)Jl(e,n,{get:t[n],enumerable:!0})},R={};Yl(R,{array:()=>pp,boolean:()=>ap,codec:()=>Dp,conditional:()=>bp,declare:()=>Ap,default:()=>Cp,define:()=>kp,dependent:()=>xp,discriminatedUnion:()=>_p,dispatch:()=>Op,enum:()=>cp,fromJSONSchema:()=>ep,int:()=>ip,intersection:()=>vp,json:()=>dp,literal:()=>sp,module:()=>jp,never:()=>lp,not:()=>yp,null:()=>op,nullable:()=>wp,number:()=>rp,object:()=>fp,optional:()=>Sp,record:()=>hp,ref:()=>Tp,refOf:()=>Ep,string:()=>np,tuple:()=>mp,union:()=>gp,unknown:()=>up});var Xl=Object.freeze({length:!0,range:!0,items:`all`,pattern:`full`}),Zl=Object.freeze({length:!1,range:!1,items:`none`,pattern:`none`}),Ql=Object.freeze({id:`lenient`,family:`lenient`,strict:!1,optional:`omit`,closedObjects:!1,records:`open`,tuples:`prefixItems`,unions:`anyOf`,nulls:`type-array`,allOf:!0,conditionals:!0,patternProperties:!0,defs:!0,recursion:!0,any:`empty`,constraints:Xl,formats:`all`,examples:`keyword`,propertyOrdering:!1,rootObject:!1}),$l=Object.freeze({...Ql,id:`people`,family:`people`,audience:`people`}),eu=Object.freeze({...Ql,id:`openai`,family:`openai`,rootObject:!0,request:Object.freeze({maxTools:128})}),tu=new Set([`date-time`,`time`,`date`,`duration`,`email`,`hostname`,`ipv4`,`ipv6`,`uuid`]),nu=Object.freeze({id:`openai-strict`,family:`openai`,strict:!0,optional:`null`,closedObjects:!0,records:`pairs`,tuples:`object`,unions:`anyOf`,nulls:`anyOf`,allOf:!1,conditionals:!1,patternProperties:!1,defs:!0,refSiblings:!1,recursion:!0,any:`json-text`,constraints:Object.freeze({length:!0,range:!0,items:`all`,pattern:`basic`}),formats:tu,examples:`description`,propertyOrdering:!1,maxDepth:10,rootObject:!0,limits:Object.freeze({maxProperties:5e3,maxDepth:10,maxStringChars:12e4,maxEnumValues:1e3,largeEnumValues:250,maxLargeEnumChars:15e3}),request:Object.freeze({maxTools:128}),loose:eu}),ru=Object.freeze({...nu,id:`openai-finetuned-strict`,constraints:Zl,formats:new Set}),iu=Object.freeze({...Ql,id:`anthropic`,family:`anthropic`,rootObject:!0}),au=Object.freeze({id:`anthropic-strict`,family:`anthropic`,strict:!0,optional:`omit`,closedObjects:!0,records:`pairs`,tuples:`array`,unions:`anyOf`,nulls:`type-array`,allOf:!1,conditionals:!1,patternProperties:!1,defs:!0,recursion:!1,any:`json-text`,constraints:Object.freeze({length:!1,range:!1,items:`min-0-1`,pattern:`basic`}),formats:new Set([`date-time`,`time`,`date`,`duration`,`email`,`hostname`,`uri`,`ipv4`,`ipv6`,`uuid`]),examples:`description`,propertyOrdering:!1,rootObject:!0,request:Object.freeze({maxStrictTools:20,totals:Object.freeze({maxOptional:24,maxUnions:16})}),loose:iu,alwaysStrictOutput:!0}),ou=`Return ONLY a single raw JSON object that conforms to the schema above. Do NOT wrap it in markdown code fences, do NOT add any prose before or after it, and do NOT echo the schema itself: emit only the JSON instance.`,su=Object.freeze({...Ql,id:`google`,family:`google`,recursion:`guarded`,maxEnumValues:40,rootObject:!0,jsonInstruction:ou}),cu=Object.freeze({id:`google-strict`,family:`google`,strict:!0,optional:`omit`,closedObjects:!1,records:`open`,tuples:`prefixItems`,unions:`anyOf`,nulls:`type-array`,allOf:!1,conditionals:!1,patternProperties:!1,defs:!0,recursion:`guarded`,any:`empty`,constraints:Object.freeze({length:!1,range:!0,items:`all`,pattern:`none`}),formats:new Set([`date-time`,`date`,`time`]),examples:`description`,propertyOrdering:!1,maxEnumValues:40,rootObject:!0,loose:su,jsonInstruction:ou}),lu=Object.freeze({id:`google-openapi`,family:`google`,strict:!0,optional:`omit`,closedObjects:!1,records:`pairs`,tuples:`array`,unions:`anyOf`,nulls:`nullable`,allOf:!1,conditionals:!1,patternProperties:!1,defs:!1,recursion:!1,any:`json-text`,constraints:Object.freeze({length:!0,range:!0,items:`all`,pattern:`basic`}),formats:new Set([`date-time`,`date`,`time`,`duration`]),examples:`description`,propertyOrdering:!0,maxEnumValues:40,maxDepth:10,rootObject:!0,loose:su,jsonInstruction:ou}),uu=new Set([`date`,`time`,`date-time`,`email`,`uuid`,`ipv4`,`ipv6`,`uri`]),du=Object.freeze({id:`xai-strict`,family:`xai`,strict:!0,optional:`omit`,closedObjects:!0,records:`open`,tuples:`prefixItems`,unions:`anyOf`,nulls:`type-array`,allOf:!1,conditionals:!1,patternProperties:!1,defs:!0,recursion:!1,any:`flat`,constraints:Object.freeze({length:!0,range:!0,items:`all`,pattern:`basic`}),formats:uu,examples:`description`,propertyOrdering:!1,rootObject:!0}),fu=Object.freeze({...du,id:`xai`,strict:!1}),pu=Object.freeze({...Ql,id:`ollama`,family:`ollama`,rootObject:!0}),mu=Object.freeze({id:`minimal`,family:`minimal`,strict:!0,optional:`null`,closedObjects:!0,records:`pairs`,tuples:`object`,unions:`tagged`,nulls:`type-array`,allOf:!1,conditionals:!1,patternProperties:!1,defs:!1,recursion:!1,any:`json-text`,constraints:Zl,formats:new Set,examples:`description`,propertyOrdering:!1,maxDepth:6,maxEnumValues:8,rootObject:!0}),hu=new Map,gu=new Map;function _u(e){hu.set(e.id,e);let t=gu.get(e.family)??{};e.strict?t.strict??=e:t.loose??=e,gu.set(e.family,t)}for(let e of[Ql,$l,eu,nu,ru,iu,au,su,cu,lu,du,fu,pu,mu])_u(e);var vu=new WeakMap;function yu(e){let t=vu.get(e);return t||(t=Object.freeze({profile:e,records:e.records,optional:e.optional,recordWord:e.records===`pairs`?`a list of {key, value} entries`:`an object`}),vu.set(e,t)),t}Object.freeze({properties:0,depth:0,stringChars:0,enumValues:0,enums:Object.freeze([]),optional:0,unions:0});function bu(e){let t=0,n=0,r=0,i=0,a=0,o=[],s=e.$defs??{};for(let e of Object.keys(s))n+=e.length;let c=e=>{if(!e||typeof e!=`object`)return;if(Array.isArray(e)){for(let t of e)c(t);return}let s=e;if(s.properties&&typeof s.properties==`object`){let e=s.properties,r=new Set(Array.isArray(s.required)?s.required:[]);for(let[a,o]of Object.entries(e))t++,n+=a.length,r.has(a)||i++,c(o)}if(Array.isArray(s.enum)){let e=0;for(let t of s.enum)typeof t==`string`&&(e+=t.length);r+=s.enum.length,n+=e,o.push({values:s.enum.length,chars:e})}typeof s.const==`string`&&(n+=s.const.length);let l=s.anyOf??s.oneOf;(Array.isArray(l)&&l.length>1||Array.isArray(s.type)&&s.type.length>1)&&a++;for(let e of[`items`,`prefixItems`,`anyOf`,`oneOf`,`allOf`,`additionalProperties`,`not`,`if`,`then`,`else`])e in s&&c(s[e]);if(s.patternProperties&&typeof s.patternProperties==`object`)for(let e of Object.values(s.patternProperties))c(e)},{$defs:l,...u}=e;c(u);for(let e of Object.values(s))c(e);let d=e=>{if(typeof e.$ref==`string`)return/^#\/\$defs\/(.+)$/.exec(e.$ref)?.[1]?.replace(/~1/g,`/`).replace(/~0/g,`~`)},f=xu(s,d),p=new Set,m=new Map,h=e=>{if(!e||typeof e!=`object`||Array.isArray(e))return 0;let t=e;if(typeof t.$ref==`string`){let e=d(t);if(!e||p.has(e)||!s[e])return 0;let n=f.get(e),r=e;if(n){r+=`|`;for(let e of n)r+=p.has(e)?`1`:`0`}let i=m.get(r);if(i!==void 0)return i;p.add(e);let a=h(s[e]);return p.delete(e),m.set(r,a),a}let n=t.type===`object`||t.type===`array`||Array.isArray(t.type)&&(t.type.includes(`object`)||t.type.includes(`array`)),r=0,i=e=>{let t=h(e);t>r&&(r=t)};if(t.properties&&typeof t.properties==`object`)for(let e of Object.values(t.properties))i(e);for(let e of[`items`,`additionalProperties`,`not`])e in t&&i(t[e]);for(let e of[`prefixItems`,`anyOf`,`oneOf`,`allOf`])if(Array.isArray(t[e]))for(let n of t[e])i(n);return+!!n+r},ee=h(u);return{properties:t,depth:ee,stringChars:n,enumValues:r,enums:o,optional:i,unions:a}}function xu(e,t){let n=new Map,r=(n,i)=>{if(!n||typeof n!=`object`)return;if(Array.isArray(n)){for(let e of n)r(e,i);return}let a=t(n);a!==void 0&&e[a]&&i.add(a);for(let e of Object.values(n))r(e,i)};for(let t of Object.keys(e)){let i=new Set;r(e[t],i),n.set(t,[...i])}let i=new Map,a=new Map,o=new Set,s=[],c=new Map,l=0;for(let e of n.keys()){if(i.has(e))continue;let t=[[e,0]];for(;t.length;){let e=t[t.length-1],[r,u]=e;u===0&&(i.set(r,l),a.set(r,l),l++,s.push(r),o.add(r));let d=n.get(r);if(u<d.length){e[1]++;let n=d[u];i.has(n)?o.has(n)&&a.set(r,Math.min(a.get(r),i.get(n))):t.push([n,0]);continue}t.pop();let f=t[t.length-1];if(f&&a.set(f[0],Math.min(a.get(f[0]),a.get(r))),a.get(r)===i.get(r)){let e=[],t;do t=s.pop(),o.delete(t),e.push(t);while(t!==r);if(e.length>1||d.includes(r))for(let t of e)c.set(t,e)}}}return c}var Su=class extends Error{constructor(e){super(`@aeye/schema: ${e}`),this.name=`SchemaDefinitionError`}},Cu=class extends Error{constructor(e,t=Ud(e)){super(t),this.issues=e,this.name=`SchemaParseError`}issues};function wu(e,t){let n=[];for(let e=0;e<=t.length;e++)n[e]=e;for(let r=1;r<=e.length;r++){let i=n[0];n[0]=r;for(let a=1;a<=t.length;a++){let o=n[a],s=e[r-1]===t[a-1]?0:1;n[a]=Math.min(n[a]+1,n[a-1]+1,i+s),i=o}}return n[t.length]}function Tu(e){return Math.min(3,Math.max(1,Math.floor(e/3)))}function Eu(e,t,n=Tu(e.length)){let r=e.toLowerCase(),i=[];for(let a=0;a<t.length;a++){let o=t[a];if(Math.abs(o.length-e.length)>n)continue;let s=wu(r,o.toLowerCase());s<=n&&i.push({candidate:o,index:a,ci:s,exact:wu(e,o)})}return i.sort((e,t)=>e.ci-t.ci||e.exact-t.exact||e.index-t.index),i.map(e=>e.candidate)}function Du(e,t,n){return Eu(e,t,n)[0]}var Ou=Object.freeze({detail:`full`,maxErrors:5,maxChars:2e3,suggestions:!0,context:3,depth:6,header:!0});function ku(...e){let t;for(let n of e)n!==void 0&&(t={...t,...ju(typeof n==`string`?{detail:n}:n)});return t}function Au(...e){let t=ku(...e)??{},n=t.detail??Ou.detail;return{...Ou,...t,detail:n,expected:t.expected??n===`full`}}function ju(e){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}function Mu(e){let t=typeof e==`string`?e:e?.detail??Ou.detail;return t===`markers`||t===`full`}var Nu=new WeakMap;function Pu(e,t){Nu.set(e,t)}function Fu(e,t,n){for(let r=t;r<e.length;r++){let t=Nu.get(e[r]);t&&!t.node&&(t.node=n)}}var Iu=/^[A-Za-z_$][\w$]*$/;function Lu(e){let t=``,n=``;for(let r of e)r===`(json)`?(t+=`${n||`(root)`} \u2192 JSON text \u2192 `,n=``):n+=typeof r==`number`?`[${r}]`:Iu.test(r)?n?`.${r}`:r:`[${JSON.stringify(r)}]`;return t&&!n?t.slice(0,-3):t+(n||(t?``:`(root)`))}var Ru=Symbol(`absent`);function zu(e,t){let n=e;for(let e of t)if(e===`(json)`){if(typeof n!=`string`)continue;if(n=Vu(n),n===Ru)return Ru}else{if(typeof n==`string`&&(n=Vu(n)),typeof n!=`object`||!n||!Object.prototype.hasOwnProperty.call(n,e))return Ru;n=n[e]}return n}var Bu;function Vu(e){let t=Bu?.get(e);if(t!==void 0)return t;let n;try{n=JSON.parse(e)}catch{n=Ru}return Bu?.set(e,n),n}function Hu(e,t=160){for(let n of[2,1,0]){let r=Wu(e,n,6);if(r.length<=t)return r}let n=Wu(e,0,3);return n.length<=t?n:`${n.slice(0,t-1)}\u2026`}function Uu(e){return e.replace(/^#\/\$defs\//,``).replace(/~1/g,`/`).replace(/~0/g,`~`)}function Wu(e,t,n){if(typeof e.$ref==`string`)return Uu(e.$ref);if(`const`in e)return JSON.stringify(e.const);if(Array.isArray(e.enum))return Ku(e.enum.map(e=>JSON.stringify(e)),n,` | `);let r=e.anyOf??e.oneOf;if(Array.isArray(r))return Ku([...new Set(r.map(e=>Wu(e,t,n)))],n,` | `,`options`);if(Array.isArray(e.allOf))return e.allOf.map(e=>Gu(Wu(e,t,n))).join(` & `);if(Array.isArray(e.type))return e.type.map(r=>Wu({...e,type:r},t,n)).join(` | `);if(e.nullable===!0)return`${Gu(Wu({...e,nullable:!1},t,n))} | null`;switch(e.type){case`string`:if(typeof e.description==`string`&&/JSON text/.test(e.description)){let t=/TypeScript type: ([^\n(]+?)(?: \(its named types|\.\s*$)/.exec(e.description);return t?`string (JSON text of ${t[1].trim()})`:`string (JSON text)`}return typeof e.format==`string`?`string (${e.format})`:`string`;case`integer`:return`integer`;case`number`:return`number`;case`boolean`:return`boolean`;case`null`:return`null`;case`array`:return Array.isArray(e.prefixItems)?`[${e.prefixItems.map(e=>Wu(e,t-1,n)).join(`, `)}]`:`${Gu(e.items&&typeof e.items==`object`?Wu(e.items,t-1,n):`any`)}[]`;case`object`:{let r=e.properties??{},i=Object.keys(r),a=e.additionalProperties&&typeof e.additionalProperties==`object`?e.additionalProperties:void 0;if(!i.length&&!a)return e.additionalProperties===!1?`{}`:`object`;if(t<=0)return`{…}`;let o=new Set(e.required??[]),s=i.slice(0,n).map(e=>`${Iu.test(e)?e:JSON.stringify(e)}${o.has(e)?``:`?`}: ${Wu(r[e],t-1,n)}`);return i.length>n&&s.push(`\u2026 ${i.length-n} more`),a&&s.push(`[key: string]: ${Wu(a,t-1,n)}`),`{ ${s.join(`; `)} }`}default:return`any JSON value`}}function Gu(e){return/ \| | & /.test(e)&&!/^[{[(]/.test(e)?`(${e})`:e}function Ku(e,t,n,r=`more`){return e.length<=t?e.join(n):`${e.slice(0,t).join(n)}${n}\u2026 (${e.length} ${r===`more`?`values`:r})`}function qu(e,t){let n=t?.node;if(n&&t&&t.kind!==`enum`&&t.kind!==`literal`&&t.kind!==`tag`&&t.kind!==`tool`&&t.kind!==`rule`&&t.kind!==`unknown-key`&&t.kind!==`not-allowed`)try{if(n.jsonText&&n.schema){let e=n.typeText();return`string (JSON text of ${e.length>120?`${e.slice(0,119)}\u2026`:e})`}let e=Hu(n.json());return t.kind===`type`&&/^(string|number|integer|boolean|null)$/.test(e)?void 0:e}catch{return}}function Ju(e){let t=e.message;for(let n of e.path)t+=`\0${typeof n==`number`?`#`:n}`;return t}function Yu(e){let t=[],n=new Map;for(let r of e){let e=Ju(r),i=n.get(e);if(i){i.paths.push(r.path);continue}let a={issue:r,info:Nu.get(r),paths:[r.path]};n.set(e,a),t.push(a)}return t}function Xu(e,t){let n=e.issue.message,r=e.info?.kind;if(t.terse&&e.info?.candidates&&(r===`enum`||r===`tag`||r===`tool`)){let t=e.info.candidates().length;n=n.replace(/ one of: .*$/s,` one of ${t} value${t===1?``:`s`}.`)}if(t.suggestions&&e.info?.candidates){let t=Zu(e.issue,e.info);t&&(n=n.replace(/\.$/,``)+t)}if(e.paths.length>1){if(t.terse)n+=` (the same at ${e.paths.length-1} more place${e.paths.length===2?``:`s`})`;else{let t=e.paths.slice(1,3).map(Lu),r=e.paths.length-1-t.length;n+=` (the same at ${t.join(`, `)}${r>0?` and ${r} more place${r===1?``:`s`}`:``})`}}return n.length>400?`${n.slice(0,399)}\u2026`:n}function Zu(e,t){let n=t.candidates();if(!n.length)return``;if(t.kind===`required`){let t=e.path[e.path.length-1];if(typeof t!=`string`)return``;let r=Du(t,n);return r?` \u2014 you wrote \`${r}\`; did you mean \`${t}\`?`:``}let r=t.kind===`unknown-key`?e.path[e.path.length-1]:t.received;if(typeof r!=`string`)return``;let i=Eu(r,n)[0];return i!==void 0&&i!==r?` \u2014 did you mean \`${i}\`?`:``}function Qu(e,t,n,r=`your answer`){if(!e.length)return``;let i=ed(n)?n:Au(n),a=Yu(i.suggestions?$u(e):e),o=Bu;Bu=new Map;try{for(let e of td(i)){let n=rd(a,t,e,r);if(n.length<=i.maxChars)return n}let e=rd(a,t,{...i,detail:`summary`,maxErrors:1,terse:!0},r);return e.length<=i.maxChars?e:`${e.slice(0,Math.max(0,i.maxChars-1))}\u2026`}finally{Bu=o}}function $u(e){let t,n=0;for(let r of e){let e=Nu.get(r);if(e?.kind!==`required`||!e.candidates||++n>50)continue;let i=r.path[r.path.length-1],a=typeof i==`string`?Du(i,e.candidates()):void 0;a!==void 0&&(t??=new Set).add(id([...r.path.slice(0,-1),a]))}return t?e.filter(e=>!(Nu.get(e)?.kind===`unknown-key`&&t.has(id(e.path)))):e}function ed(e){return typeof e==`object`&&!!e&&`detail`in e&&`maxChars`in e&&`expected`in e&&`context`in e&&`depth`in e&&`header`in e&&`suggestions`in e&&`maxErrors`in e}function*td(e){for(let t of nd(e))yield t,yield{...t,terse:!0}}function*nd(e){let t=e;if(yield t,t.detail===`markers`||t.detail===`full`){for(t.expected&&(yield t={...t,expected:!1}),t.context>0&&(yield t={...t,context:0}),t.depth>2&&(yield t={...t,depth:2});t.maxErrors>1;)yield t={...t,maxErrors:Math.max(1,Math.floor(t.maxErrors/2))};yield t={...t,detail:`list`,maxErrors:e.maxErrors}}for(;t.maxErrors>1;)yield t={...t,maxErrors:Math.max(1,Math.floor(t.maxErrors/2))};t.detail!==`summary`&&(yield{...t,detail:`summary`})}function rd(e,t,n,r){let i=e.slice(0,Math.max(1,n.maxErrors)),a=e.reduce((e,t)=>e+t.paths.length,0),o=e.length-i.length,s=e.slice(i.length).reduce((e,t)=>e+t.paths.length,0),c=`${a} problem${a===1?``:`s`}`;if(n.detail===`summary`){let e=i[0],t=a-e.paths.length;return`${n.header?`${a===1?`A problem`:c} in ${r}: `:``}at ${Lu(e.issue.path)}: ${Xu(e,n)}${t>0?` (and ${t} more problem${t===1?``:`s`})`:``}`}let l=[];if(n.header&&l.push(`${c} in ${r}:`),n.detail===`list`)for(let e of i){let t=n.expected?qu(e.issue,e.info):void 0;l.push(`- at ${Lu(e.issue.path)}: ${Xu(e,n)}${t?` (expected: ${t})`:``}`)}else n.header&&l.push(``),l.push(...cd(i,t,n));return s>0&&l.push(`\u2026 and ${s} more problem${s===1?``:`s`}${o>1?` (${o} kinds)`:``} not shown.`),l.join(`
|
|
56
|
-
`)}var
|
|
55
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0])a(n);else{if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}(e.metadataRegistry.get(n[0])?.id||r.cycle||r.count>1&&e.reused===`ref`)&&a(n)}}e.external&&(e.sharedDefsExtractedFor=e.external)}function io(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let n=[];for(let e of t){if(!e||typeof e!=`object`)return;io(e);let t=Object.keys(e);if(t.length!==1||t[0]!==`type`)return;let r=e.type;for(let e of Array.isArray(r)?r:[r]){if(typeof e!=`string`)return;n.includes(e)||n.push(e)}}delete e.anyOf,e.type=n.length===1?n[0]:n}var ao=new Set([`type`,`properties`,`required`,`additionalProperties`]),oo=[`oneOf`,`anyOf`];function so(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!=`object`||!t?null:Object.keys(t).length?t:null}function co(e){let t=[];for(let n of e){if(typeof n!=`object`||n.type!==`object`)return null;for(let e in n)if(!ao.has(e))return null;t.push(n)}let n={},r=new Set;for(let e of t){for(let r in e.properties){if(Object.prototype.hasOwnProperty.call(n,r))continue;let e=[];for(let n of t){let t=n.properties?.[r]??so(n);t!=null&&(e.some(e=>JSON.stringify(e)===JSON.stringify(t))||e.push(t))}u(n,r,e.length===1?e[0]:co(e)??{allOf:e})}for(let t of e.required??[])r.add(t)}let i={type:`object`,properties:n};if(r.size&&(i.required=[...r]),t.every(e=>e.additionalProperties===!1))i.additionalProperties=!1;else{let e=[];for(let n of t){let t=so(n);t&&!e.some(e=>JSON.stringify(e)===JSON.stringify(t))&&e.push(t)}e.length===1?i.additionalProperties=e[0]:e.length>1&&(i.additionalProperties={allOf:e})}return i}function lo(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let t of ao)if(t in e)return;let n=t.filter(e=>oo.some(t=>Array.isArray(e[t]))),r=null;if(!n.length)r=co(t);else{let e=n[0],i=oo.find(t=>Array.isArray(e[t]));if(Object.keys(e).length!==1)return;let a=t.filter(t=>t!==e),o=e[i].map(e=>co([...a,e]));if(o.some(e=>!e))return;r={[i]:o}}r&&(delete e.allOf,Qa(e,r))}function uo(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):Qa(i,s),Qa(i,a),t._zod.parent===o)for(let e in i)e!==`$ref`&&e!==`allOf`&&(e in a||delete i[e]);if(s.$ref&&n.def)for(let e in i)e!==`$ref`&&e!==`allOf`&&e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e!==`$ref`&&e!==`allOf`&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let t of[...e.seen.entries()].reverse())r(t[0]);if(e.target!==`openapi-3.0`)for(let t of e.seen.entries())io(t[1].def??t[1].schema);for(let t of e.deferred)t();if(e.intersections.length){let t=new Map;for(let n of e.seen.values())for(let e of[n.schema,n.def]){let n=e?.allOf;if(!Array.isArray(n))continue;let r=t.get(n);r?r.push(e):t.set(n,[e])}for(let n of e.intersections)for(let e of t.get(n)??[])lo(e)}}let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}Qa(i,n.defId?n.schema:n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,u(o,e.defId,e.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t[`~standard`],jsonSchema:{input:mo(t,`input`,e.processors),output:mo(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function fo(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return fo(r.element,n);if(r.type===`set`)return fo(r.valueType,n);if(r.type===`lazy`)return fo(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`||r.type===`catch`)return fo(r.innerType,n);if(r.type===`intersection`)return fo(r.left,n)||fo(r.right,n);if(r.type===`record`||r.type===`map`)return fo(r.keyType,n)||fo(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:fo(r.in,n)||fo(r.out,n);if(r.type===`object`){for(let e in r.shape)if(fo(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(fo(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(fo(e,n))return!0;return!!(r.rest&&fo(r.rest,n))}return!1}var po=(e,t={})=>n=>{let r=$a({...n,processors:t});return to(e,r),ro(r,e),uo(r,e)},mo=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=$a({...i??{},target:a,io:t,processors:n});return to(e,o),ro(o,e),uo(o,e)},ho=(e,t,n)=>{(e[t]===void 0||n>e[t])&&(e[t]=n)},go=(e,t,n)=>{(e[t]===void 0||n<e[t])&&(e[t]=n)},_o=(e,t)=>{ho(e,`minimum`,t),go(e,`maximum`,t)},vo=(e,t)=>{e.multipleOf??=[],e.multipleOf.includes(t)||e.multipleOf.push(t)},yo=(e,t)=>{e.patterns??=new Set,e.patterns.add(t)},bo=(e,t)=>{e.mime=e.mime?e.mime.filter(e=>t.includes(e)):[...t]},xo=(e,t)=>{e.format=t,t.includes(`int`)&&(e.isInt=!0)},So=(e,t)=>ho(e,`minimum`,t.minimum),Co=(e,t)=>go(e,`maximum`,t.maximum),wo=e=>(t,n)=>{xo(t,n.format);let[r,i]=e[n.format];ho(t,`minimum`,r),go(t,`maximum`,i)},To={greater_than:(e,t)=>ho(e,t.inclusive?`minimum`:`exclusiveMinimum`,t.value),less_than:(e,t)=>go(e,t.inclusive?`maximum`:`exclusiveMaximum`,t.value),multiple_of:(e,t)=>vo(e,t.value),number_format:wo(he),bigint_format:wo(ge),min_length:So,max_length:Co,length_equals:(e,t)=>_o(e,t.length),min_size:So,max_size:Co,size_equals:(e,t)=>_o(e,t.size),string_format:(e,t)=>{xo(e,t.format),t.pattern&&yo(e,t.pattern),(t.format===`base64`||t.format===`base64url`)&&(e.contentEncoding=t.format),(t.local||t.precision===-1)&&(e.laxFormat=!0)},mime_type:(e,t)=>bo(e,t.mime)};function Eo(e){let t={},n=e._zod.def,r=e._zod.traits.has(`$ZodCheck`)?[e,...n.checks??[]]:n.checks??[];for(let e of r)To[e._zod.def.check]?.(t,e._zod.def);let i=e._zod.bag;i.minimum!==void 0&&ho(t,`minimum`,i.minimum),i.exclusiveMinimum!==void 0&&ho(t,`exclusiveMinimum`,i.exclusiveMinimum),i.maximum!==void 0&&go(t,`maximum`,i.maximum),i.exclusiveMaximum!==void 0&&go(t,`exclusiveMaximum`,i.exclusiveMaximum),i.multipleOf!==void 0&&vo(t,i.multipleOf),i.format!==void 0&&(t.format??=i.format,i.format.includes(`int`)&&(t.isInt=!0)),i.mime&&bo(t,i.mime);for(let e of i.patterns??[])yo(t,e);return t}var Do={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},Oo=new Map([[_r,Xt],[yr,Zt]]),ko=e=>Oo.get(e)??e,Ao=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l,laxFormat:u}=Eo(e);if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=Do[s]??s,i.format===``&&delete i.format,(s===`time`||u)&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c].map(ko);e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},jo=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,multipleOf:s,exclusiveMaximum:c,exclusiveMinimum:l,isInt:u}=Eo(e);i.type=u?`integer`:`number`;let d=typeof l==`number`&&l>=(a??-1/0),f=typeof c==`number`&&c<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;if(d?p?(i.minimum=l,i.exclusiveMinimum=!0):i.exclusiveMinimum=l:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=c,i.exclusiveMaximum=!0):i.exclusiveMaximum=c:typeof o==`number`&&(i.maximum=o),s){let n=new Set;for(let a of s)Number.isFinite(a)&&a!==0?n.add(Math.abs(a)):eo(e,t,i,r,`A multipleOf divisor of ${a} cannot be represented in JSON Schema`);let[a,...o]=n;a!==void 0&&(i.multipleOf=a),o.length&&(i.allOf=[...i.allOf??[],...o.map(e=>({multipleOf:e}))])}},Mo=(e,t,n,r)=>{n.type=`boolean`},No=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},Po=(e,t,n,r)=>{n.not={}},Fo=(t,n,r,i)=>{let a=t._zod.def,o=e(a.entries);o.length===0?r.not={}:(o.every(e=>typeof e==`number`)&&(r.type=`number`),o.every(e=>typeof e==`string`)&&(r.type=`string`),r.enum=o)},Io=(e,t,n,r)=>{let i=e._zod.def;if(i.values.length===0){n.not={};return}let a=[];for(let o of i.values)if(o===void 0){if(eo(e,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof o==`bigint`){if(eo(e,t,n,r,`BigInt literals cannot be represented in JSON Schema`))return;a.push(Number(o))}else a.push(o);if(a.length!==0){if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a}},Lo=(e,t,n,r)=>{let i=n,a=e._zod.pattern;if(!a)throw Error(`Pattern not found in template literal`);i.type=`string`,i.pattern=a.source},Ro=(e,t,n,r)=>{eo(e,t,n,r,`Custom types cannot be represented in JSON Schema`)},zo=(e,t,n,r)=>{eo(e,t,n,r,`Transforms cannot be represented in JSON Schema`)},Bo=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=Eo(e);typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=to(a.element,t,{...r,path:[...r.path,`items`]})};function Vo(e){let t=e._zod.def;return t.type===`pipe`&&t.in._zod.traits.has(`$ZodTransform`)?Vo(t.out):t.type===`catch`?Vo(t.innerType):e._zod.optin}var Ho=(e,t,n,r)=>{let i=n,a=e._zod.def,o=a.shape;if(Object.getOwnPropertySymbols(o).length&&eo(e,t,i,r,`Symbol keys cannot be represented in JSON Schema`))return;i.type=`object`,i.properties={};for(let e in o)u(i.properties,e,to(o[e],t,{...r,path:[...r.path,`properties`,e]}));let s=[];for(let e of Object.keys(o)){let n=a.shape[e];(t.io===`input`?Vo(n)===void 0:n._zod.optout===void 0)&&s.push(e)}s.length>0&&(i.required=s),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=to(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},Uo=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>to(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},Wo=(e,t,n,r)=>{let i=e._zod.def,a=to(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=to(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1,c=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]];n.allOf=c,t.intersections.push(c)},Go=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`array`;let o=t.target===`draft-2020-12`?`prefixItems`:`items`,s=t.target===`draft-2020-12`||t.target===`openapi-3.0`?`items`:`additionalItems`,c=a.items.map((e,n)=>to(e,t,{...r,path:[...r.path,o,n]})),l=a.rest?to(a.rest,t,{...r,path:[...r.path,s,...t.target===`openapi-3.0`?[a.items.length]:[]]}):null,u=a.items.length;for(;u>0;){let e=a.items[u-1];if(!(t.io===`input`?Vo(e)!==void 0:e._zod.optout===`optional`))break;u--}let d=a.items.length,f=!a.rest;t.target===`draft-2020-12`?(i.prefixItems=c,f?i.items=!1:l&&(i.items=l),u>0&&(i.minItems=u),f&&(i.maxItems=d)):t.target===`openapi-3.0`?(i.items={anyOf:c},l&&i.items.anyOf.push(l),u>0&&(i.minItems=u),f&&(i.maxItems=d)):(i.items=c,f?i.additionalItems=!1:l&&(i.additionalItems=l),u>0&&(i.minItems=u),f&&(i.maxItems=d));let{minimum:p,maximum:m}=Eo(e);typeof p==`number`&&(i.minItems=p),typeof m==`number`&&(i.maxItems=m)};function Ko(e,t,n){if(t.$ref){if(n.has(t))return t;n.add(t);let r=e.get(t)?.def;if(!r)return t;let i=Ko(e,r,n);return i===r?t:i}for(let r of[`anyOf`,`oneOf`]){let i=t[r];if(!Array.isArray(i))continue;let a=i.map(t=>Ko(e,t,n));a.some((e,t)=>e!==i[t])&&(t={...t,[r]:a})}let r=Array.isArray(t.type)?t.type:[t.type],i=!r.includes(`string`)&&r.some(e=>e===`number`||e===`integer`),a=t.enum??(t.const===void 0?void 0:[t.const]);if(!i&&!a?.some(e=>typeof e==`number`))return t;let{minimum:o,maximum:s,exclusiveMinimum:c,exclusiveMaximum:l,multipleOf:u,format:d,id:f,...p}=t;return p.enum?p.enum=p.enum.map(e=>typeof e==`number`?String(e):e):typeof p.const==`number`&&(p.const=String(p.const)),i&&(p.type=`string`,a||(p.pattern=(r.includes(`number`)?un:ln).source)),p}var qo=new WeakMap;function Jo(e){let t=new Map;for(let n of e.seen.values())n.def&&!t.has(n.schema)&&t.set(n.schema,n);let n=new Map;for(let r of qo.get(e)??[]){let i=e.seen.get(r),a=(i?.def??i?.schema)?.propertyNames;if(!a||a===!0||n.has(a))continue;let o=Ko(t,a,new Set);o!==a&&n.set(a,o)}if(n.size)for(let t of e.seen.values())for(let e of[t.schema,t.def]){let t=e&&n.get(e.propertyNames);t&&(e.propertyNames=t)}}var Yo=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=Eo(o).patterns;if(a.mode===`loose`&&s&&s.size>0){let e=to(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)u(i.patternProperties,ko(t).source,e)}else{if(t.target===`draft-07`||t.target===`draft-2020-12`){i.propertyNames=to(a.keyType,t,{...r,path:[...r.path,`propertyNames`]});let n=qo.get(t);n||(n=[],qo.set(t,n),t.deferred.push(()=>Jo(t))),n.push(e)}i.additionalProperties=to(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]})}let c=o._zod.values,l=t.io===`input`&&Vo(a.valueType)!==void 0;if(c&&!a.partial&&!l){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e.map(String))}},Xo=(e,t,n,r)=>{let i=e._zod.def,a=to(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},Zo=(e,t,n,r)=>{let i=e._zod.def;to(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Qo=Symbol();function $o(e,t,n,r,i){let a=!1,o=JSON.stringify(e,(e,t)=>typeof t==`bigint`?(a=!0,null):t);return a?(eo(t,n,r,i,`BigInt defaults cannot be represented in JSON Schema`),Qo):JSON.parse(o)}var es=(e,t,n,r)=>{let i=e._zod.def;to(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o=$o(i.defaultValue,e,t,n,r);o!==Qo&&(n.default=o)},ts=(e,t,n,r)=>{let i=e._zod.def;to(i.innerType,t,r);let a=t.seen.get(e);if(a.ref=i.innerType,t.io!==`input`)return;let o=$o(i.defaultValue,e,t,n,r);o!==Qo&&(n._prefault=o)},ns=(e,t,n,r)=>{let i=e._zod.def;to(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{eo(e,t,n,r,`Dynamic catch values are not supported in JSON Schema`);return}n.default=o},rs=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;to(o,t,r);let s=t.seen.get(e);s.ref=o},is=(e,t,n,r)=>{let i=e._zod.def;to(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},as=(e,t,n,r)=>{let i=e._zod.def;to(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},os=(e,t,n,r)=>{let i=e._zod.innerType;to(i,t,r);let a=t.seen.get(e);a.ref=i},ss=new WeakSet([Object.prototype,Error.prototype]);function cs(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let e=n(this);return Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0})}})}var ls=_(`ZodError`,(e,t)=>{ut.init(e,t),e.name=`ZodError`;let r=Object.getPrototypeOf(e);ss.has(r)||(ss.add(r),cs(r,`format`,e=>t=>pt(e,t)),cs(r,`flatten`,e=>t=>ft(e,t)),cs(r,`addIssue`,e=>t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,n,2)}),cs(r,`addIssues`,e=>t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,n,2)}),Object.defineProperty(r,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},void 0,{Parent:Error}),us=ht(ls),ds=gt(ls),fs=_t(ls),ps=yt(ls),ms=Tt(ls),hs=Et(ls),gs=Dt(ls),_s=Ot(ls),vs=kt(ls),ys=At(ls),bs=jt(ls),xs=Mt(ls);function Ss(){rt.localeError||it(Hi())}function Cs(){rt.memoizer||it({memoizer:zi()})}var ws=_(`ZodType`,(e,t)=>(Ss(),Fn.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(te(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return fe(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(Yc(e,t))},superRefine(e,t){return this.check(Xc(e,t))},overwrite(e){return this.check(Va(e))},optional(){return Ec(this)},exactOptional(){return Oc(this)},nullable(){return Ac(this)},nullish(){return Ec(Ac(this))},nonoptional(e){return Ic(this,e)},array(){return x(this)},or(e){return C([this,e])},and(e){return gc(this,e)},transform(e){return Bc(this,wc(e))},default(e){return Mc(this,e)},prefault(e){return Pc(this,e)},catch(e){return Rc(this,e)},pipe(e){return Bc(this,e)},readonly(){return Hc(this)},describe(e){let t=this.clone();return Ki.add(t,{description:e}),t},meta(...e){if(e.length===0)return Ki.get(this);let t=this.clone();return Ki.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get"~standard"(){return Be(this,`~standard`,{...Rn(this),jsonSchema:{input:mo(this,`input`),output:mo(this,`output`)}})},set"~standard"(e){ze(this,`~standard`,e)},parse:function e(t,n){return us(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await ds(this,t,n,{callee:e})},safeParse(e,t){return fs(this,e,t)},async safeParseAsync(e,t){return ps(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){ze(this,`spa`,e)},validate(e,t){return St(this,e,t)},validateAsync(e,t){return wt(this,e,t)},encode:function e(t,n){return ms(this,t,n,{callee:e})},decode:function e(t,n){return hs(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await gs(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await _s(this,t,n,{callee:e})},safeEncode(e,t){return vs(this,e,t)},safeDecode(e,t){return ys(this,e,t)},async safeEncodeAsync(e,t){return bs(this,e,t)},async safeDecodeAsync(e,t){return xs(this,e,t)},toJSONSchema(e){return po(this,{})(e)},get description(){return Ki.get(this)?.description},get _def(){return this._zod.def}}),Ts=_(`_ZodString`,(e,t)=>{zn.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ao(e,t,n,r)},Ve({format:e=>Eo(e).format??null,minLength:e=>Eo(e).minimum??null,maxLength:e=>Eo(e).maximum??null},{regex(...e){return this.check(Fa(...e))},includes(...e){return this.check(Ra(...e))},startsWith(...e){return this.check(za(...e))},endsWith(...e){return this.check(Ba(...e))},min(...e){return this.check(Na(...e))},max(...e){return this.check(Ma(...e))},length(...e){return this.check(Pa(...e))},nonempty(...e){return this.check(Na(1,...e))},lowercase(e){return this.check(Ia(e))},uppercase(e){return this.check(La(e))},trim(){return this.check(Ua())},normalize(...e){return this.check(Ha(...e))},toLowerCase(){return this.check(Wa())},toUpperCase(){return this.check(Ga())},slugify(){return this.check(Ka())}})),Es=_(`ZodString`,(e,t)=>{zn.init(e,t),Ts.init(e,t)},{email(e){return this.check(Yi(Ms,e))},url(e){return this.check(ta(Is,e))},jwt(e){return this.check(ga(Qs,e))},emoji(e){return this.check(na(Rs,e))},guid(e){return this.check(Xi(Ps,e))},uuid(e){return this.check(Zi(Fs,e))},uuidv4(e){return this.check(Qi(Fs,e))},uuidv6(e){return this.check($i(Fs,e))},uuidv7(e){return this.check(ea(Fs,e))},nanoid(e){return this.check(ra(zs,e))},cuid(e){return this.check(ia(Bs,e))},cuid2(e){return this.check(aa(Vs,e))},ulid(e){return this.check(oa(Hs,e))},base64(e){return this.check(pa(Ys,e))},base64url(e){return this.check(ma(Xs,e))},xid(e){return this.check(sa(Us,e))},ksuid(e){return this.check(ca(Ws,e))},ipv4(e){return this.check(la(Gs,e))},ipv6(e){return this.check(ua(Ks,e))},cidrv4(e){return this.check(da(qs,e))},cidrv6(e){return this.check(fa(Js,e))},e164(e){return this.check(ha(Zs,e))},datetime(e){return this.check(_a(Os,e))},date(e){return this.check(va(ks,e))},time(e){return this.check(ya(As,e))},duration(e){return this.check(ba(js,e))}});function v(e){return Ji(Es,e)}var Ds=_(`ZodStringFormat`,(e,t)=>{Bn.init(e,t),Ts.init(e,t)}),Os=_(`ZodISODateTime`,(e,t)=>{ar.init(e,t),Ds.init(e,t)}),ks=_(`ZodISODate`,(e,t)=>{or.init(e,t),Ds.init(e,t)}),As=_(`ZodISOTime`,(e,t)=>{sr.init(e,t),Ds.init(e,t)}),js=_(`ZodISODuration`,(e,t)=>{cr.init(e,t),Ds.init(e,t)}),Ms=_(`ZodEmail`,(e,t)=>{Un.init(e,t),Ds.init(e,t)});function Ns(e){return Yi(Ms,e)}var Ps=_(`ZodGUID`,(e,t)=>{Vn.init(e,t),Ds.init(e,t)}),Fs=_(`ZodUUID`,(e,t)=>{Hn.init(e,t),Ds.init(e,t)}),Is=_(`ZodURL`,(e,t)=>{Zn.init(e,t),Ds.init(e,t)});function Ls(e){return ta(Is,e)}var Rs=_(`ZodEmoji`,(e,t)=>{Qn.init(e,t),Ds.init(e,t)}),zs=_(`ZodNanoID`,(e,t)=>{$n.init(e,t),Ds.init(e,t)}),Bs=_(`ZodCUID`,(e,t)=>{er.init(e,t),Ds.init(e,t)}),Vs=_(`ZodCUID2`,(e,t)=>{tr.init(e,t),Ds.init(e,t)}),Hs=_(`ZodULID`,(e,t)=>{nr.init(e,t),Ds.init(e,t)}),Us=_(`ZodXID`,(e,t)=>{rr.init(e,t),Ds.init(e,t)}),Ws=_(`ZodKSUID`,(e,t)=>{ir.init(e,t),Ds.init(e,t)}),Gs=_(`ZodIPv4`,(e,t)=>{lr.init(e,t),Ds.init(e,t)}),Ks=_(`ZodIPv6`,(e,t)=>{fr.init(e,t),Ds.init(e,t)}),qs=_(`ZodCIDRv4`,(e,t)=>{pr.init(e,t),Ds.init(e,t)}),Js=_(`ZodCIDRv6`,(e,t)=>{hr.init(e,t),Ds.init(e,t)}),Ys=_(`ZodBase64`,(e,t)=>{vr.init(e,t),Ds.init(e,t)}),Xs=_(`ZodBase64URL`,(e,t)=>{xr.init(e,t),Ds.init(e,t)}),Zs=_(`ZodE164`,(e,t)=>{Sr.init(e,t),Ds.init(e,t)}),Qs=_(`ZodJWT`,(e,t)=>{wr.init(e,t),Ds.init(e,t)}),$s=_(`ZodNumber`,(e,t)=>{Tr.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>jo(e,t,n,r),e.isFinite=!0},Ve({minValue:e=>{let{minimum:t,exclusiveMinimum:n}=Eo(e);return Math.max(t??-1/0,n??-1/0)},maxValue:e=>{let{maximum:t,exclusiveMaximum:n}=Eo(e);return Math.min(t??1/0,n??1/0)},isInt:e=>{let{isInt:t,multipleOf:n}=Eo(e);return!!t||!!n?.some(Number.isSafeInteger)},format:e=>Eo(e).format??null},{gt(e,t){return this.check(ka(e,t))},gte(e,t){return this.check(Aa(e,t))},min(e,t){return this.check(Aa(e,t))},lt(e,t){return this.check(Da(e,t))},lte(e,t){return this.check(Oa(e,t))},max(e,t){return this.check(Oa(e,t))},int(e){return this.check(tc(e))},safe(e){return this.check(tc(e))},positive(e){return this.check(ka(0,e))},nonnegative(e){return this.check(Aa(0,e))},negative(e){return this.check(Da(0,e))},nonpositive(e){return this.check(Oa(0,e))},multipleOf(e,t){return this.check(ja(e,t))},step(e,t){return this.check(ja(e,t))},finite(){return this}}));function y(e){return xa($s,e)}var ec=_(`ZodNumberFormat`,(e,t)=>{Er.init(e,t),$s.init(e,t)});function tc(e){return Sa(ec,e)}var nc=_(`ZodBoolean`,(e,t)=>{Dr.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Mo(e,t,n,r)});function b(e){return Ca(nc,e)}var rc=_(`ZodNull`,(e,t)=>{Or.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>No(e,t,n,r)});function ic(e){return wa(rc,e)}var ac=_(`ZodAny`,(e,t)=>{kr.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0}),oc=_(`ZodUnknown`,(e,t)=>{Ar.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function sc(){return Ta(oc)}var cc=_(`ZodNever`,(e,t)=>{jr.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Po(e,t,n,r)});function lc(e){return Ea(cc,e)}var uc=_(`ZodArray`,(e,t)=>{Cs(),Fr.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Bo(e,t,n,r),e.element=t.element},{min(e,t){return this.check(Na(e,t))},nonempty(e){return this.check(Na(1,e))},max(e,t){return this.check(Ma(e,t))},length(e,t){return this.check(Pa(e,t))},unwrap(){return this.element}});function x(e,t){return qa(uc,e,t)}var dc=_(`ZodObject`,(e,t)=>{Cs(),Vr.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ho(e,t,n,r),Je(e,`shape`,e=>e._zod.def.shape,!1)},{keyof(){return E(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(te(this._zod.def,{catchall:e}))},passthrough(){return this.clone(te(this._zod.def,{catchall:sc()}))},loose(){return this.clone(te(this._zod.def,{catchall:sc()}))},strict(){return this.clone(te(this._zod.def,{catchall:lc()}))},strip(){return this.clone(te(this._zod.def,{catchall:void 0}))},extend(e){return be(this,e)},safeExtend(e){return Se(this,e)},merge(e){return Ce(this,e)},pick(e){return _e(this,e)},omit(e){return ye(this,e)},partial(...e){return we(Tc,this,e[0])},exactPartial(...e){return we(Dc,this,e[0],`exactPartial`)},required(...e){return Te(Fc,this,e[0])}});function S(e,t){return new dc({type:`object`,shape:e??{},...g(t)})}function fc(e,t){return new dc({type:`object`,shape:e,catchall:sc(),...g(t)})}var pc=_(`ZodUnion`,(e,t)=>{Ur.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Uo(e,t,n,r),e.options=t.options});function C(e,t){return new pc({type:`union`,options:e,...g(t)})}var mc=_(`ZodDiscriminatedUnion`,(e,t)=>{pc.init(e,t),Gr.init(e,t)});function w(e,t,n){return new mc({type:`union`,options:t,discriminator:e,...g(n)})}var hc=_(`ZodIntersection`,(e,t)=>{Kr.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Wo(e,t,n,r)});function gc(e,t){return new hc({type:`intersection`,left:e,right:t})}var _c=_(`ZodTuple`,(e,t)=>{Cs(),Yr.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Go(e,t,n,r)},{rest(e){return this.clone({...this._zod.def,rest:e})},partial(){let e=this._zod.def;if(e.checks?.length)throw Error(`.partial() cannot be used on tuple schemas containing refinements`);return this.clone({...e,items:e.items.map(e=>new Tc({type:`optional`,innerType:e}))})}});function vc(e,t,n){let r=t instanceof Fn;return new _c({type:`tuple`,items:e,rest:r?t:null,...g(r?n:t)})}var yc=_(`ZodRecord`,(e,t)=>{Cs(),$r.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Yo(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function T(e,t,n){return!t||!t._zod?new yc({type:`record`,keyType:v(),valueType:e,...g(t)}):new yc({type:`record`,keyType:e,valueType:t,...g(n)})}function bc(e,t,n){return new yc({type:`record`,keyType:e,valueType:t,...g(n),partial:!0})}var xc=_(`ZodEnum`,(e,t)=>{ei.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Fo(e,t,n,r),e.enum=t.entries,e.options=[...e._zod.values];let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new xc({...t,checks:[],...g(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new xc({...t,checks:[],...g(r),entries:i})}});function E(e,t){return new xc({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...g(t)})}var Sc=_(`ZodLiteral`,(e,t)=>{ti.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Io(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function D(e,t){return new Sc({type:`literal`,values:Array.isArray(e)?e:[e],...g(t)})}var Cc=_(`ZodTransform`,(e,t)=>{Cs(),ni.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>zo(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new nt(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(Le(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,`input`in t||(t.input=n.value),t.inst??=e,n.issues.push(Le(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function wc(e){return new Cc({type:`transform`,transform:e})}var Tc=_(`ZodOptional`,(e,t)=>{ii.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>as(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ec(e){return new Tc({type:`optional`,innerType:e})}var Dc=_(`ZodExactOptional`,(e,t)=>{ai.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>as(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Oc(e){return new Dc({type:`optional`,innerType:e})}var kc=_(`ZodNullable`,(e,t)=>{oi.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Xo(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ac(e){return new kc({type:`nullable`,innerType:e})}var jc=_(`ZodDefault`,(e,t)=>{si.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>es(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Mc(e,t){return new jc({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():ce(t)}})}var Nc=_(`ZodPrefault`,(e,t)=>{li.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ts(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Pc(e,t){return new Nc({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():ce(t)}})}var Fc=_(`ZodNonOptional`,(e,t)=>{ui.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Zo(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ic(e,t){return new Fc({type:`nonoptional`,innerType:e,...g(t)})}var Lc=_(`ZodCatch`,(e,t)=>{pi.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ns(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Rc(e,t){return new Lc({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:Xe(t)})}var zc=_(`ZodPipe`,(e,t)=>{mi.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>rs(e,t,n,r),e.in=t.in,e.out=t.out});function Bc(e,t){return new zc({type:`pipe`,in:e,out:t})}var Vc=_(`ZodReadonly`,(e,t)=>{gi.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>is(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Hc(e){return new Vc({type:`readonly`,innerType:e})}var Uc=_(`ZodTemplateLiteral`,(e,t)=>{bi.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Lo(e,t,n,r)});function Wc(e,t){return new Uc({type:`template_literal`,parts:e,...g(t)})}var Gc=_(`ZodLazy`,(e,t)=>{xi.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>os(e,t,n,r),e.unwrap=()=>e._zod.def.getter()});function Kc(e){return new Gc({type:`lazy`,getter:e})}var qc=_(`ZodCustom`,(e,t)=>{Si.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ro(e,t,n,r)});function Jc(e,t){return Ja(qc,e??(()=>!0),t)}function Yc(e,t={}){return Ya(qc,e,t)}function Xc(e,t){return Xa(e,t)}function Zc(e){let t=Kc(()=>C([v(e),y(),b(),ic(),x(t),T(v(),t)]));return t}function Qc(e){return _a(Os,e)}function $c(e){return va(ks,e)}var O=Zc(),el=T(v(),O);function tl(e){return e===void 0?null:O.parse(JSON.parse(JSON.stringify(e)))}function nl(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var rl={run:`run`,turn:`trn`,session:`ses`,actor:`act`,message:`msg`,delivery:`dlv`,handlerCall:`hcl`,llmInteraction:`llm`,pairing:`par`,pairingToken:`ptk`,policy:`pol`,approval:`apr`,budget:`bgt`,priorityRule:`pri`,reservation:`rsv`,ledger:`led`,notification:`ntf`,push:`psh`,secret:`sec`,modelCategory:`mct`,provider:`prv`,sectionRule:`srl`,authSession:`aus`,modelCall:`mdl`,mcp:`mcp`,autoPair:`apk`,connection:`cnx`,fnExample:`fex`,refusal:`rfs`,record:`rec`,mentionRequest:`mrq`},il=e=>v().regex(RegExp(`^${rl[e]}_.+$`),`expected a ${e} id starting with "${rl[e]}_"`).brand().describe(`${e} id`),al=e=>Object.hasOwn(rl,e);function ol(){return Object.fromEntries(Object.keys(rl).filter(al).map(e=>[e,il(e)]))}var k=v().regex(/^[A-Za-z_][A-Za-z0-9_.-]*$/),sl=ol(),A=sl.run,cl=sl.turn,j=sl.session,M=sl.actor,ll=sl.message,ul=sl.delivery,dl=sl.handlerCall,fl=sl.llmInteraction,pl=sl.pairing,ml=sl.pairingToken,hl=sl.policy,gl=sl.approval,_l=sl.budget,vl=sl.priorityRule,yl=sl.reservation,bl=sl.ledger,xl=sl.notification,Sl=sl.push,Cl=sl.secret,wl=sl.modelCategory,Tl=sl.provider,El=sl.sectionRule,Dl=sl.authSession,Ol=sl.modelCall,kl=sl.mcp,Al=sl.autoPair,jl=sl.connection,Ml=y().int().min(0),N=y().int(),P=y(),Nl=/^[a-z][a-z0-9-]*$/,F=v().regex(Nl).brand(),I=Wc([v().regex(Nl),`/`,v().min(1)]),Pl=C([D(`native`),I]);function Fl(e,t){return`${e}/${t}`}function Il(e){let t=e.indexOf(`/`);return{system:e.slice(0,t),local:e.slice(t+1)}}var Ll=[`urgent`,`interactive`,`normal`,`background`],Rl=E(Ll),zl=E([`user`,`llm`,`both`,`none`]),Bl=E([`user`,`group`,`agent`,`system`,`mcp`]),Vl=e=>S({items:x(e),cursor:v().optional()}),Hl=S({cursor:v().optional(),limit:y().int().min(1).max(200).optional()});function Ul(e){return e instanceof Error?e.message:String(e)}var Wl=`read`,Gl=`admin`,L=v().regex(Nl).brand(),Kl=L.parse(`main`),ql=S({system:F,instance:L}),Jl=v().regex(/^[a-z*][a-z0-9*-]*\/[A-Za-z0-9_.*-]+$/).brand(),Yl=Object.defineProperty,Xl=(e,t)=>{for(var n in t)Yl(e,n,{get:t[n],enumerable:!0})},R={};Xl(R,{array:()=>yp,boolean:()=>dp,codec:()=>Np,conditional:()=>Ep,declare:()=>Ip,default:()=>kp,define:()=>Fp,dependent:()=>Dp,discriminatedUnion:()=>Cp,dispatch:()=>Pp,enum:()=>mp,fromJSONSchema:()=>op,int:()=>up,intersection:()=>wp,json:()=>_p,literal:()=>pp,module:()=>Lp,never:()=>hp,not:()=>Tp,null:()=>fp,nullable:()=>Ap,number:()=>lp,object:()=>vp,optional:()=>Op,record:()=>xp,ref:()=>jp,refOf:()=>Mp,string:()=>cp,tuple:()=>bp,union:()=>Sp,unknown:()=>gp});var Zl=Object.freeze({length:!0,range:!0,items:`all`,pattern:`full`}),Ql=Object.freeze({length:!1,range:!1,items:`none`,pattern:`none`}),$l=Object.freeze({id:`lenient`,family:`lenient`,strict:!1,optional:`omit`,closedObjects:!1,records:`open`,tuples:`prefixItems`,unions:`anyOf`,nulls:`type-array`,allOf:!0,conditionals:!0,patternProperties:!0,defs:!0,recursion:!0,any:`empty`,constraints:Zl,formats:`all`,examples:`keyword`,propertyOrdering:!1,rootObject:!1}),eu=Object.freeze({...$l,id:`people`,family:`people`,audience:`people`}),tu=Object.freeze({...$l,id:`openai`,family:`openai`,rootObject:!0,request:Object.freeze({maxTools:128})}),nu=new Set([`date-time`,`time`,`date`,`duration`,`email`,`hostname`,`ipv4`,`ipv6`,`uuid`]),ru=Object.freeze({id:`openai-strict`,family:`openai`,strict:!0,optional:`null`,closedObjects:!0,records:`pairs`,tuples:`object`,unions:`anyOf`,nulls:`anyOf`,allOf:!1,conditionals:!1,patternProperties:!1,defs:!0,refSiblings:!1,recursion:!0,any:`json-text`,constraints:Object.freeze({length:!0,range:!0,items:`all`,pattern:`basic`}),formats:nu,examples:`description`,propertyOrdering:!1,maxDepth:10,rootObject:!0,limits:Object.freeze({maxProperties:5e3,maxDepth:10,maxStringChars:12e4,maxEnumValues:1e3,largeEnumValues:250,maxLargeEnumChars:15e3}),request:Object.freeze({maxTools:128}),loose:tu}),iu=Object.freeze({...ru,id:`openai-finetuned-strict`,constraints:Ql,formats:new Set}),au=Object.freeze({...$l,id:`anthropic`,family:`anthropic`,rootObject:!0}),ou={id:`anthropic-strict`,family:`anthropic`,strict:!0,optional:`omit`,closedObjects:!0,records:`pairs`,tuples:`array`,unions:`anyOf`,nulls:`type-array`,allOf:!1,conditionals:!1,patternProperties:!1,defs:!0,recursion:!1,any:`json-text`,constraints:Object.freeze({length:!1,range:!1,items:`min-0-1`,pattern:`basic`}),formats:new Set([`date-time`,`time`,`date`,`duration`,`email`,`hostname`,`uri`,`ipv4`,`ipv6`,`uuid`]),examples:`description`,propertyOrdering:!1,rootObject:!0,limits:Object.freeze({maxObjectProperties:34}),request:Object.freeze({maxStrictTools:20,totals:Object.freeze({maxOptional:24,maxUnions:16,maxProperties:54})}),loose:au,alwaysStrictOutput:!0},su=Object.freeze({...ou,id:`anthropic-strict-output`,limits:Object.freeze({maxObjectOptional:12})}),cu=Object.freeze({...ou,output:su}),lu=`Return ONLY a single raw JSON object that conforms to the schema above. Do NOT wrap it in markdown code fences, do NOT add any prose before or after it, and do NOT echo the schema itself: emit only the JSON instance.`,uu=Object.freeze({...$l,id:`google`,family:`google`,recursion:`guarded`,maxEnumValues:40,rootObject:!0,jsonInstruction:lu}),du=Object.freeze({id:`google-strict`,family:`google`,strict:!0,optional:`omit`,closedObjects:!1,records:`open`,tuples:`prefixItems`,unions:`anyOf`,nulls:`type-array`,allOf:!1,conditionals:!1,patternProperties:!1,defs:!0,recursion:`guarded`,any:`empty`,constraints:Object.freeze({length:!1,range:!0,items:`all`,pattern:`none`}),formats:new Set([`date-time`,`date`,`time`]),examples:`description`,propertyOrdering:!1,maxEnumValues:40,rootObject:!0,loose:uu,jsonInstruction:lu}),fu=Object.freeze({id:`google-openapi`,family:`google`,strict:!0,optional:`omit`,closedObjects:!1,records:`pairs`,tuples:`array`,unions:`anyOf`,nulls:`nullable`,allOf:!1,conditionals:!1,patternProperties:!1,defs:!1,recursion:!1,any:`json-text`,constraints:Object.freeze({length:!0,range:!0,items:`all`,pattern:`basic`}),formats:new Set([`date-time`,`date`,`time`,`duration`]),examples:`description`,propertyOrdering:!0,maxEnumValues:40,maxDepth:10,rootObject:!0,loose:uu,jsonInstruction:lu}),pu=new Set([`date`,`time`,`date-time`,`email`,`uuid`,`ipv4`,`ipv6`,`uri`]),mu=Object.freeze({id:`xai-strict`,family:`xai`,strict:!0,optional:`omit`,closedObjects:!0,records:`open`,tuples:`prefixItems`,unions:`anyOf`,nulls:`type-array`,allOf:!1,conditionals:!1,patternProperties:!1,defs:!0,recursion:!1,any:`flat`,constraints:Object.freeze({length:!0,range:!0,items:`all`,pattern:`basic`}),formats:pu,examples:`description`,propertyOrdering:!1,rootObject:!0}),hu=Object.freeze({...mu,id:`xai`,strict:!1}),gu=Object.freeze({...$l,id:`ollama`,family:`ollama`,rootObject:!0}),_u=Object.freeze({id:`minimal`,family:`minimal`,strict:!0,optional:`null`,closedObjects:!0,records:`pairs`,tuples:`object`,unions:`tagged`,nulls:`type-array`,allOf:!1,conditionals:!1,patternProperties:!1,defs:!1,recursion:!1,any:`json-text`,constraints:Ql,formats:new Set,examples:`description`,propertyOrdering:!1,maxDepth:6,maxEnumValues:8,rootObject:!0}),vu=new Map,yu=new Map;function bu(e){vu.set(e.id,e);let t=yu.get(e.family)??{};e.strict?t.strict??=e:t.loose??=e,yu.set(e.family,t)}for(let e of[$l,eu,tu,ru,iu,au,cu,su,uu,du,fu,mu,hu,gu,_u])bu(e);var xu=new WeakMap;function Su(e){let t=xu.get(e);return t||(t=Object.freeze({profile:e,records:e.records,optional:e.optional,recordWord:e.records===`pairs`?`a list of {key, value} entries`:`an object`}),xu.set(e,t)),t}Object.freeze({properties:0,depth:0,stringChars:0,enumValues:0,enums:Object.freeze([]),optional:0,unions:0,objectProperties:0,objectOptional:0});function Cu(e){let t=0,n=0,r=0,i=0,a=0,o=0,s=0,c=[],l=e.$defs??{};for(let e of Object.keys(l))n+=e.length;let u=e=>{if(!e||typeof e!=`object`)return;if(Array.isArray(e)){for(let t of e)u(t);return}let l=e;if(l.properties&&typeof l.properties==`object`){let e=l.properties,r=new Set(Array.isArray(l.required)?l.required:[]),a=Object.keys(e);o=Math.max(o,a.length),s=Math.max(s,a.filter(e=>!r.has(e)).length);for(let[a,o]of Object.entries(e))t++,n+=a.length,r.has(a)||i++,u(o)}if(Array.isArray(l.enum)){let e=0;for(let t of l.enum)typeof t==`string`&&(e+=t.length);r+=l.enum.length,n+=e,c.push({values:l.enum.length,chars:e})}typeof l.const==`string`&&(n+=l.const.length);let d=l.anyOf??l.oneOf;(Array.isArray(d)&&d.length>1||Array.isArray(l.type)&&l.type.length>1)&&a++;for(let e of[`items`,`prefixItems`,`anyOf`,`oneOf`,`allOf`,`additionalProperties`,`not`,`if`,`then`,`else`])e in l&&u(l[e]);if(l.patternProperties&&typeof l.patternProperties==`object`)for(let e of Object.values(l.patternProperties))u(e)},{$defs:d,...f}=e;u(f);for(let e of Object.values(l))u(e);let p=e=>{if(typeof e.$ref==`string`)return/^#\/\$defs\/(.+)$/.exec(e.$ref)?.[1]?.replace(/~1/g,`/`).replace(/~0/g,`~`)},m=wu(l,p),h=new Set,ee=new Map,te=e=>{if(!e||typeof e!=`object`||Array.isArray(e))return 0;let t=e;if(typeof t.$ref==`string`){let e=p(t);if(!e||h.has(e)||!l[e])return 0;let n=m.get(e),r=e;if(n){r+=`|`;for(let e of n)r+=h.has(e)?`1`:`0`}let i=ee.get(r);if(i!==void 0)return i;h.add(e);let a=te(l[e]);return h.delete(e),ee.set(r,a),a}let n=t.type===`object`||t.type===`array`||Array.isArray(t.type)&&(t.type.includes(`object`)||t.type.includes(`array`)),r=0,i=e=>{let t=te(e);t>r&&(r=t)};if(t.properties&&typeof t.properties==`object`)for(let e of Object.values(t.properties))i(e);for(let e of[`items`,`additionalProperties`,`not`])e in t&&i(t[e]);for(let e of[`prefixItems`,`anyOf`,`oneOf`,`allOf`])if(Array.isArray(t[e]))for(let n of t[e])i(n);return+!!n+r},ne=te(f);return{properties:t,depth:ne,stringChars:n,enumValues:r,enums:c,optional:i,unions:a,objectProperties:o,objectOptional:s}}function wu(e,t){let n=new Map,r=(n,i)=>{if(!n||typeof n!=`object`)return;if(Array.isArray(n)){for(let e of n)r(e,i);return}let a=t(n);a!==void 0&&e[a]&&i.add(a);for(let e of Object.values(n))r(e,i)};for(let t of Object.keys(e)){let i=new Set;r(e[t],i),n.set(t,[...i])}let i=new Map,a=new Map,o=new Set,s=[],c=new Map,l=0;for(let e of n.keys()){if(i.has(e))continue;let t=[[e,0]];for(;t.length;){let e=t[t.length-1],[r,u]=e;u===0&&(i.set(r,l),a.set(r,l),l++,s.push(r),o.add(r));let d=n.get(r);if(u<d.length){e[1]++;let n=d[u];i.has(n)?o.has(n)&&a.set(r,Math.min(a.get(r),i.get(n))):t.push([n,0]);continue}t.pop();let f=t[t.length-1];if(f&&a.set(f[0],Math.min(a.get(f[0]),a.get(r))),a.get(r)===i.get(r)){let e=[],t;do t=s.pop(),o.delete(t),e.push(t);while(t!==r);if(e.length>1||d.includes(r))for(let t of e)c.set(t,e)}}}return c}var Tu=class extends Error{constructor(e){super(`@aeye/schema: ${e}`),this.name=`SchemaDefinitionError`}},Eu=class extends Error{constructor(e,t=Yd(e)){super(t),this.issues=e,this.name=`SchemaParseError`}issues};function Du(e,t){let n=[];for(let e=0;e<=t.length;e++)n[e]=e;for(let r=1;r<=e.length;r++){let i=n[0];n[0]=r;for(let a=1;a<=t.length;a++){let o=n[a],s=e[r-1]===t[a-1]?0:1;n[a]=Math.min(n[a]+1,n[a-1]+1,i+s),i=o}}return n[t.length]}function Ou(e){return Math.min(3,Math.max(1,Math.floor(e/3)))}function ku(e,t,n=Ou(e.length)){let r=e.toLowerCase(),i=[];for(let a=0;a<t.length;a++){let o=t[a];if(Math.abs(o.length-e.length)>n)continue;let s=Du(r,o.toLowerCase());s<=n&&i.push({candidate:o,index:a,ci:s,exact:Du(e,o)})}return i.sort((e,t)=>e.ci-t.ci||e.exact-t.exact||e.index-t.index),i.map(e=>e.candidate)}function Au(e,t,n){return ku(e,t,n)[0]}var ju=Object.freeze({detail:`full`,maxErrors:5,maxChars:2e3,suggestions:!0,context:3,depth:6,header:!0});function Mu(...e){let t;for(let n of e)n!==void 0&&(t={...t,...Pu(typeof n==`string`?{detail:n}:n)});return t}function Nu(...e){let t=Mu(...e)??{},n=t.detail??ju.detail;return{...ju,...t,detail:n,expected:t.expected??n===`full`}}function Pu(e){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}function Fu(e){let t=typeof e==`string`?e:e?.detail??ju.detail;return t===`markers`||t===`full`}var Iu=new WeakMap;function Lu(e,t){Iu.set(e,t)}function Ru(e,t,n){for(let r=t;r<e.length;r++){let t=Iu.get(e[r]);t&&!t.node&&(t.node=n)}}var zu=/^[A-Za-z_$][\w$]*$/;function Bu(e){let t=``,n=``;for(let r of e)r===`(json)`?(t+=`${n||`(root)`} \u2192 JSON text \u2192 `,n=``):n+=typeof r==`number`?`[${r}]`:zu.test(r)?n?`.${r}`:r:`[${JSON.stringify(r)}]`;return t&&!n?t.slice(0,-3):t+(n||(t?``:`(root)`))}var Vu=Symbol(`absent`);function Hu(e,t){let n=e;for(let e of t)if(e===`(json)`){if(typeof n!=`string`)continue;if(n=Wu(n),n===Vu)return Vu}else{if(typeof n==`string`&&(n=Wu(n)),typeof n!=`object`||!n||!Object.prototype.hasOwnProperty.call(n,e))return Vu;n=n[e]}return n}var Uu;function Wu(e){let t=Uu?.get(e);if(t!==void 0)return t;let n;try{n=JSON.parse(e)}catch{n=Vu}return Uu?.set(e,n),n}function Gu(e,t=160){for(let n of[2,1,0]){let r=qu(e,n,6);if(r.length<=t)return r}let n=qu(e,0,3);return n.length<=t?n:`${n.slice(0,t-1)}\u2026`}function Ku(e){return e.replace(/^#\/\$defs\//,``).replace(/~1/g,`/`).replace(/~0/g,`~`)}function qu(e,t,n){if(typeof e.$ref==`string`)return Ku(e.$ref);if(`const`in e)return JSON.stringify(e.const);if(Array.isArray(e.enum))return Yu(e.enum.map(e=>JSON.stringify(e)),n,` | `);let r=e.anyOf??e.oneOf;if(Array.isArray(r))return Yu([...new Set(r.map(e=>qu(e,t,n)))],n,` | `,`options`);if(Array.isArray(e.allOf))return e.allOf.map(e=>Ju(qu(e,t,n))).join(` & `);if(Array.isArray(e.type))return e.type.map(r=>qu({...e,type:r},t,n)).join(` | `);if(e.nullable===!0)return`${Ju(qu({...e,nullable:!1},t,n))} | null`;switch(e.type){case`string`:if(typeof e.description==`string`&&/JSON text/.test(e.description)){let t=/TypeScript type: ([^\n(]+?)(?: \(its named types|\.\s*$)/.exec(e.description);return t?`string (JSON text of ${t[1].trim()})`:`string (JSON text)`}return typeof e.format==`string`?`string (${e.format})`:`string`;case`integer`:return`integer`;case`number`:return`number`;case`boolean`:return`boolean`;case`null`:return`null`;case`array`:return Array.isArray(e.prefixItems)?`[${e.prefixItems.map(e=>qu(e,t-1,n)).join(`, `)}]`:`${Ju(e.items&&typeof e.items==`object`?qu(e.items,t-1,n):`any`)}[]`;case`object`:{let r=e.properties??{},i=Object.keys(r),a=e.additionalProperties&&typeof e.additionalProperties==`object`?e.additionalProperties:void 0;if(!i.length&&!a)return e.additionalProperties===!1?`{}`:`object`;if(t<=0)return`{…}`;let o=new Set(e.required??[]),s=i.slice(0,n).map(e=>`${zu.test(e)?e:JSON.stringify(e)}${o.has(e)?``:`?`}: ${qu(r[e],t-1,n)}`);return i.length>n&&s.push(`\u2026 ${i.length-n} more`),a&&s.push(`[key: string]: ${qu(a,t-1,n)}`),`{ ${s.join(`; `)} }`}default:return`any JSON value`}}function Ju(e){return/ \| | & /.test(e)&&!/^[{[(]/.test(e)?`(${e})`:e}function Yu(e,t,n,r=`more`){return e.length<=t?e.join(n):`${e.slice(0,t).join(n)}${n}\u2026 (${e.length} ${r===`more`?`values`:r})`}function Xu(e,t){let n=t?.node;if(n&&t&&t.kind!==`enum`&&t.kind!==`literal`&&t.kind!==`tag`&&t.kind!==`tool`&&t.kind!==`rule`&&t.kind!==`unknown-key`&&t.kind!==`not-allowed`)try{if(n.jsonText&&n.schema){let e=n.typeText();return`string (JSON text of ${e.length>120?`${e.slice(0,119)}\u2026`:e})`}let e=Gu(n.json());return t.kind===`type`&&/^(string|number|integer|boolean|null)$/.test(e)?void 0:e}catch{return}}function Zu(e){let t=e.message;for(let n of e.path)t+=`\0${typeof n==`number`?`#`:n}`;return t}function Qu(e){let t=[],n=new Map;for(let r of e){let e=Zu(r),i=n.get(e);if(i){i.paths.push(r.path);continue}let a={issue:r,info:Iu.get(r),paths:[r.path]};n.set(e,a),t.push(a)}return t}function $u(e,t){let n=e.issue.message,r=e.info?.kind;if(t.terse&&e.info?.candidates&&(r===`enum`||r===`tag`||r===`tool`)){let t=e.info.candidates().length;n=n.replace(/ one of: .*$/s,` one of ${t} value${t===1?``:`s`}.`)}if(t.suggestions&&e.info?.candidates){let t=ed(e.issue,e.info);t&&(n=n.replace(/\.$/,``)+t)}if(e.paths.length>1){if(t.terse)n+=` (the same at ${e.paths.length-1} more place${e.paths.length===2?``:`s`})`;else{let t=e.paths.slice(1,3).map(Bu),r=e.paths.length-1-t.length;n+=` (the same at ${t.join(`, `)}${r>0?` and ${r} more place${r===1?``:`s`}`:``})`}}return n.length>400?`${n.slice(0,399)}\u2026`:n}function ed(e,t){let n=t.candidates();if(!n.length)return``;if(t.kind===`required`){let t=e.path[e.path.length-1];if(typeof t!=`string`)return``;let r=Au(t,n);return r?` \u2014 you wrote \`${r}\`; did you mean \`${t}\`?`:``}let r=t.kind===`unknown-key`?e.path[e.path.length-1]:t.received;if(typeof r!=`string`)return``;let i=ku(r,n)[0];return i!==void 0&&i!==r?` \u2014 did you mean \`${i}\`?`:``}function td(e,t,n,r=`your answer`){if(!e.length)return``;let i=rd(n)?n:Nu(n),a=Qu(i.suggestions?nd(e):e),o=Uu;Uu=new Map;try{for(let e of id(i)){let n=od(a,t,e,r);if(n.length<=i.maxChars)return n}let e=od(a,t,{...i,detail:`summary`,maxErrors:1,terse:!0},r);return e.length<=i.maxChars?e:`${e.slice(0,Math.max(0,i.maxChars-1))}\u2026`}finally{Uu=o}}function nd(e){let t,n=0;for(let r of e){let e=Iu.get(r);if(e?.kind!==`required`||!e.candidates||++n>50)continue;let i=r.path[r.path.length-1],a=typeof i==`string`?Au(i,e.candidates()):void 0;a!==void 0&&(t??=new Set).add(sd([...r.path.slice(0,-1),a]))}return t?e.filter(e=>!(Iu.get(e)?.kind===`unknown-key`&&t.has(sd(e.path)))):e}function rd(e){return typeof e==`object`&&!!e&&`detail`in e&&`maxChars`in e&&`expected`in e&&`context`in e&&`depth`in e&&`header`in e&&`suggestions`in e&&`maxErrors`in e}function*id(e){for(let t of ad(e))yield t,yield{...t,terse:!0}}function*ad(e){let t=e;if(yield t,t.detail===`markers`||t.detail===`full`){for(t.expected&&(yield t={...t,expected:!1}),t.context>0&&(yield t={...t,context:0}),t.depth>2&&(yield t={...t,depth:2});t.maxErrors>1;)yield t={...t,maxErrors:Math.max(1,Math.floor(t.maxErrors/2))};yield t={...t,detail:`list`,maxErrors:e.maxErrors}}for(;t.maxErrors>1;)yield t={...t,maxErrors:Math.max(1,Math.floor(t.maxErrors/2))};t.detail!==`summary`&&(yield{...t,detail:`summary`})}function od(e,t,n,r){let i=e.slice(0,Math.max(1,n.maxErrors)),a=e.reduce((e,t)=>e+t.paths.length,0),o=e.length-i.length,s=e.slice(i.length).reduce((e,t)=>e+t.paths.length,0),c=`${a} problem${a===1?``:`s`}`;if(n.detail===`summary`){let e=i[0],t=a-e.paths.length;return`${n.header?`${a===1?`A problem`:c} in ${r}: `:``}at ${Bu(e.issue.path)}: ${$u(e,n)}${t>0?` (and ${t} more problem${t===1?``:`s`})`:``}`}let l=[];if(n.header&&l.push(`${c} in ${r}:`),n.detail===`list`)for(let e of i){let t=n.expected?Xu(e.issue,e.info):void 0;l.push(`- at ${Bu(e.issue.path)}: ${$u(e,n)}${t?` (expected: ${t})`:``}`)}else n.header&&l.push(``),l.push(...dd(i,t,n));return s>0&&l.push(`\u2026 and ${s} more problem${s===1?``:`s`}${o>1?` (${o} kinds)`:``} not shown.`),l.join(`
|
|
56
|
+
`)}var sd=e=>{let t=``;for(let n of e)t+=`${typeof n==`number`?`#`:`$`}${n}\0`;return t};function cd(e,t){for(let n=0;n<Math.min(e.length,t.length);n++){let r=e[n],i=t[n];if(r!==i)return typeof r==`number`&&typeof i==`number`?r-i:String(r)<String(i)?-1:1}return e.length-t.length}function ld(e,t){let n=[];for(let r=0;r<Math.min(e.length,t.length)&&e[r]===t[r];r++)n.push(e[r]);return n}var ud=e=>e.filter(e=>e!==`(json)`).length;function dd(e,t,n){let r=[],i=[];for(let n of e){let e=n.issue.path,a=n.info?.kind;t===void 0?i.push(n):Hu(t,e)===Vu?e.length&&fd(Hu(t,e.slice(0,-1)))?r.push({p:n,at:e.slice(0,-1),where:`missing`}):i.push(n):r.push({p:n,at:e,where:a===`unknown-key`||a===`not-allowed`?`key`:`value`})}r.sort((e,t)=>cd(e.p.issue.path,t.p.issue.path));let a=[],o=e=>{let t=[];for(let r of e){if(ud(e)-ud(t)<=n.depth)break;t.push(r)}return t};for(let e of r){let t=a[a.length-1];if(t){let r=ld(t.anchor,e.at);if([...t.members,e].every(e=>ud(e.at)-ud(r)<=n.depth+1)){t.anchor=r,t.members.push(e);continue}}a.push({anchor:o(e.at),members:[e]})}let s=[];for(let e of a){let r=e.anchor;for(;r.length&&Hu(t,r)===Vu;)r=r.slice(0,-1);let i=new Map,a=new Map;for(let t of e.members){let e=sd(t.at),n=i.get(e);n?n.push({p:t.p,where:t.where}):i.set(e,[{p:t.p,where:t.where}]);for(let e=r.length;e<t.at.length;e++){let n=sd(t.at.slice(0,e)),r=a.get(n);r?r.add(t.at[e]):a.set(n,new Set([t.at[e]]))}}s.length&&s.push(``),r.length&&s.push(`at ${Bu(r)}:`),new md(i,a,n,s,r.length).node(Hu(t,r),r,``,``,``)}for(let e of i)s.push(`- at ${Bu(e.issue.path)}: ${$u(e,n)}`);return s}var fd=e=>typeof e==`object`&&!!e;function pd(e){if(!e.length)return`…`;let t=e[0],n=Bu(e);return t===`(json)`?`\u2026 \u2192 ${n.replace(/^\(root\) → /,``)}`:typeof t==`number`||!zu.test(t)?`\u2026${n}`:`\u2026.${n}`}var md=class{constructor(e,t,n,r,i=0){this.marks=e,this.below=t,this.f=n,this.out=r,this.from=i}marks;below;f;out;from;node(e,t,n,r,i){let a=sd(t),o=this.below.has(a);if(typeof e==`string`&&o){let a=Wu(e);if(a!==Vu){let e=[...t,`(json)`],o=sd(e);return this.marks.has(o)||this.below.has(o)?this.node(a,e,n,`${r}/* JSON text */ `,i):this.node(a,t,n,r,i)}}let s=this.marks.get(a)??[];if(!(fd(e)&&(o||s.some(e=>e.where===`missing`)))){let t=hd(e,60);this.out.push(n+r+t+i);for(let e of s)e.where===`key`?this.mark(e.p,n.length,r.length+t.length):this.mark(e.p,n.length+r.length,t.length);return}let c=Array.isArray(e);this.out.push(`${n}${r}${c?`[`:`{`}`);for(let e of s)this.mark(e.p,n.length+r.length,1);let l=`${n} `;c?this.items(e,t,l):this.keys(e,t,l),this.out.push(`${n}${c?`]`:`}`}${i}`)}keys(e,t,n){let r=Object.keys(e),i=this.below.get(sd(t)),a=r.filter(e=>i?.has(e)),o=r.filter(e=>!a.includes(e)),s=new Set(o.filter(t=>hd(e[t],40).length<=40&&!fd(e[t])).slice(0,this.f.context));for(let e of o)s.size<this.f.context&&!s.has(e)&&s.add(e);let c=r.filter(e=>a.includes(e)||s.has(e)),l=r.length-c.length;c.forEach((r,i)=>{let a=i===c.length-1&&!l;this.node(e[r],[...t,r],n,`${JSON.stringify(r)}: `,a?``:`,`)}),l&&this.out.push(`${n}\u2026 ${l} more key${l===1?``:`s`}`)}items(e,t,n){let r=new Set;for(let n of this.below.get(sd(t))??[])typeof n==`number`&&n<e.length&&r.add(n);let i=e.length-r.size<=this.f.context&&e.every((e,t)=>r.has(t)||hd(e,40).length<=40),a=0,o=!1,s=()=>{a&&(this.out.push(`${n}\u2026 ${a} item${a===1?``:`s`}`),a=0,o=!0)};for(let c=0;c<e.length;c++){if(!i&&!r.has(c)){a++;continue}s();let l=c===e.length-1,u=o||!i&&c>0?`/* ${c} */ `:``;this.node(e[c],[...t,c],n,u,l?``:`,`)}s()}mark(e,t,n){let r=Math.max(1,Math.min(n,40)),i=`${this.from?pd(e.issue.path.slice(this.from)):Bu(e.issue.path)}: ${$u(e,this.f)}`;this.out.push(`${` `.repeat(t)}${`^`.repeat(r)} ${i}`);let a=this.f.expected?Xu(e.issue,e.info):void 0;a&&this.out.push(`${` `.repeat(t+r+1)}expected: ${a}`)}};function hd(e,t){if(typeof e==`string`){let n=JSON.stringify(e);return n.length<=t?n:`${n.slice(0,t-2)}\u2026"`}if(!fd(e))return e===void 0?`undefined`:JSON.stringify(e);let n=gd(e,t);if(n!==void 0)return n;if(Array.isArray(e))return`[\u2026 ${e.length} item${e.length===1?``:`s`}]`;let r=Object.keys(e).length;return`{\u2026 ${r} key${r===1?``:`s`}}`}function gd(e,t){let n=``,r=e=>{if(n.length>t)return!1;if(Array.isArray(e)){n+=`[`;for(let t=0;t<e.length;t++)if(t&&(n+=`,`),!r(e[t]))return!1;return n+=`]`,n.length<=t}if(fd(e)){n+=`{`;let i=!0;for(let t of Object.keys(e)){let a=e[t];if(a!==void 0&&(i||(n+=`,`),i=!1,n+=`${JSON.stringify(t)}:`,!r(a)))return!1}return n+=`}`,n.length<=t}return n+=e===void 0?`null`:JSON.stringify(e),n.length<=t};return r(e)?n:void 0}var _d=class{constructor(e){this.issues=e}issues};function vd(){return{objects:0,arrays:0,edits:0,parsed:0,repaired:0}}function yd(e){let t=``;for(let n of e)t+=typeof n==`number`?`[${n}]`:/^[A-Za-z_$][\w$]*$/.test(n)?t?`.${n}`:n:`[${JSON.stringify(n)}]`;return t||`(root)`}var bd=Object.freeze({path:[],codePath:[],message:``}),xd=vd(),Sd=Symbol(`absent`),Cd=Symbol(`order`),wd,Td=class e{constructor(e,t,n,r=!0,i=!1){this.inPlace=e,this.dry=t,this.stats=n,this.repair=r,this.countOnly=i}inPlace;dry;stats;repair;countOnly;errors=[];undo;undoN=0;wire=[];code=[];wd=0;cd=0;fail(e,t=`other`,n,r,i){if(this.countOnly){this.errors.push(bd);return}let a={path:this.wire.slice(0,this.wd),codePath:this.code.slice(0,this.cd),message:e};this.errors.push(a),Lu(a,{kind:t,node:i,received:n,candidates:r})}failAt(e,t,n=`rule`){if(!e.length)return this.fail(t,n);if(this.countOnly){this.errors.push(bd);return}let r={path:[...this.wire.slice(0,this.wd),...e],codePath:[...this.code.slice(0,this.cd),...e],message:t};this.errors.push(r),Lu(r,{kind:n})}enter(e,t=e){this.wire[this.wd++]=e,t!==null&&(this.code[this.cd++]=t)}leave(e=!0){this.wd--,e&&this.cd--}dryRun(t=!1){if(!t)return new e(!1,!0,xd,this.repair,!0);let n=new e(!1,!0,xd,this.repair);for(let e=0;e<this.wd;e++)n.wire[n.wd++]=this.wire[e];for(let e=0;e<this.cd;e++)n.code[n.cd++]=this.code[e];return n}saving(e,t,n=!1){let r=this.undo;if(!r)return;n&&this.ordered!==e&&(this.ordered=e,r[this.undoN++]=e,r[this.undoN++]=Cd,r[this.undoN++]=Object.keys(e));let i=Object.prototype.hasOwnProperty.call(e,t);r[this.undoN++]=e,r[this.undoN++]=t,r[this.undoN++]=i?e[t]:Sd}ordered;restore(){let e=this.undo;if(e)for(let t=this.undoN-3;t>=0;t-=3){let n=e[t],r=e[t+1],i=e[t+2];if(r===Cd)for(let e of i){let t=n[e];delete n[e],n[e]=t}else i===Sd?delete n[r]:n[r]=i}}keepUndo(){this.undo=wd??[],wd=void 0,this.undoN=0}releaseUndo(){let e=this.undo;if(e){for(let t=0;t<this.undoN;t++)e[t]=void 0;this.undo=void 0,this.undoN=0,e.length<=65536&&(wd=e)}}},Ed=class{constructor(e,t){this.impl=e,this.compiler=t}impl;compiler;needs=!1;schema;outer;jsonText=!1;_json;get own(){return!!this.impl?.own}get deps(){return this.impl?.deps??[]}json(){return this._json||=this.compiler.decorate(this,this.impl.emit()),this._json}run(e,t){let n=t.errors,r=n.length,i=this.impl.run(e,t);return n.length===r&&(this.schema?.checks.length&&this.check(i,t,this.schema),this.outer?.checks.length&&n.length===r&&this.check(i,t,this.outer),n.length===r)||t.countOnly||Ru(n,r,this),i}check(e,t,n){if(n)for(let r of n.checks){let n=r.fn(e);if(n!==!0){if(Array.isArray(n))for(let e of n)typeof e==`string`?t.fail(e,`rule`):t.failAt(e.path,e.message,`rule`);else t.fail(typeof n==`string`?n:r.message??`Failed a check.`,`rule`)}}}typeText(){return this.schema?this.schema.print(new Dd(this.compiler.env)):`any JSON value`}encode(e,t=vd()){return this.needs?this.impl.encode(e,t):e}child(e){return this.impl?.child?.(e)}},Dd=class{constructor(e){this.env=e}env;names=new Set;print(e){return e.print(this)}ref(e){return this.names.add(e),e}used(){return[...this.names]}definitions(e){for(let t of e)this.names.add(t);let t=[],n=new Set;for(let e=!0;e;){e=!1;for(let r of[...this.names]){if(n.has(r))continue;n.add(r),e=!0;let i=this.env.get(r);i&&t.push(`type ${r} = ${i.print(this)}`)}}return t.join(`
|
|
57
57
|
`)}full(e){let t=this.print(e),n=[],r=new Set;for(let e=!0;e;){e=!1;for(let t of[...this.names]){if(r.has(t))continue;r.add(t),e=!0;let i=this.env.get(t);i&&n.push(`type ${t} = ${i.print(this)}`)}}return n.length?`${t}
|
|
58
58
|
where
|
|
59
59
|
${n.join(`
|
|
60
|
-
`)}`:t}},
|
|
61
|
-
`)),this.profile.refSiblings===!1&&typeof c.$ref==`string`&&(c.description!==void 0||c.title!==void 0||c.examples!==void 0)){let{$ref:e,...t}=c;return{anyOf:[{$ref:e}],...t}}return c}checkExample(e,t){let n=e.schema;if(!n)return;let r=new
|
|
62
|
-
${
|
|
63
|
-
${new
|
|
64
|
-
${t}`:t}}let t={};for(let[e,n]of this.compiler.defs)t[e]=n.json();return this._json=this.compiler.defs.size?{...e,$defs:t}:e,this._json}get measure(){return this._measure??=
|
|
65
|
-
`)}var Wd=class e{constructor(e={}){this.defs=e}defs;define(t){for(let e of Object.keys(t))if(e in this.defs)throw new Su(`"${e}" is already defined.`);return new e({...this.defs,...t})}declare(){return this}dynamic(e,t={}){return new Gd(this.defs,e,t)}result(e){return new qd(this.defs,Kd(e))}},Gd=class{constructor(e,t,n){this.defs=e,this.fn=t,this.opts=n}defs;fn;opts;result(e){return new qd(this.defs,Kd(e),{fn:this.fn,opts:this.opts})}};function Kd(e){return typeof e==`string`?new Af(e):e}var qd=class e{constructor(e,t,n){this.defs=e,this.root=t,this.dyn=n}defs;root;dyn;cache=new Map;staticBound;bind=(...e)=>{let t=this.dyn;if(!t)return this.staticBound??=new Jd(new Map(Object.entries(this.defs)),this.root);let n=t.opts.key?.(...e);if(n!==void 0){let e=this.cache.get(n);if(e)return this.cache.delete(n),this.cache.set(n,e),e}let r=t.fn(...e),i=new Map(Object.entries(this.defs));for(let[e,t]of Object.entries(r)){if(i.has(e))throw new Su(`the dynamic step redefined "${e}".`);i.set(e,t)}let a=new Jd(i,this.root);if(n!==void 0){this.cache.set(n,a);let e=t.opts.cacheSize??4;for(;this.cache.size>e;)this.cache.delete(this.cache.keys().next().value)}return a};adapt(t){let n=this.dyn;if(!n)return this;let r=n.opts.key;return new e(this.defs,this.root,{fn:(...e)=>n.fn(...t(...e)),opts:{...n.opts,...r?{key:(...e)=>r(...t(...e))}:{}}})}render(e,...t){return this.bind(...t).render(e)}},Jd=class{constructor(e,t){this.env=e,this.root=t;let n=[],r=t=>{for(let r of t.refNames())!e.has(r)&&!n.includes(r)&&n.push(r)};r(t);for(let t of e.values())r(t);if(n.length)throw new Su(`unresolved ref(s) ${n.join(`, `)}.`)}env;root;rendered=new Map;render(e){let t=this.rendered.get(e.id);if(!t){let n=()=>this.render(Ql),r=new Ld(e,this.env,n),i;try{i=r.compile(this.root)}catch(t){if(!(t instanceof Id))throw t;r=new Ld(e,this.env,n,!0),i=r.compile(this.root)}r.finish(),t=new Vd(r,i),this.rendered.set(e.id,t)}return t}},Yd=new WeakMap;function Xd(e){let t=Yd.get(e);return t||Yd.set(e,t=new qd({},e)),t}var Zd=Object.freeze({}),Qd=Object.freeze([]),$d=class{meta=Zd;checks=Qd;_refNames;refNames(){if(!this._refNames){let e=new Set;this instanceof Af&&e.add(this.name);for(let t of this.children())for(let n of t.refNames())e.add(n);if(this.meta.forModels)for(let t of this.meta.forModels.refNames())e.add(t);this._refNames=e}return this._refNames}with(e){let t=Object.create(Object.getPrototypeOf(this));return Object.assign(t,this,e,{_refNames:void 0}),t}describe(e){return this.with({meta:{...this.meta,description:e}})}title(e){return this.with({meta:{...this.meta,title:e}})}example(...e){return this.with({meta:{...this.meta,examples:[...this.meta.examples??[],...e]}})}refine(e,t,n){let r={fn:e,...t===void 0?{}:{message:t},visible:n?.visible??t!==void 0};return this.with({checks:[...this.checks,r]})}brand(){return this}forPeople(){return this.with({meta:{...this.meta,audience:`people`}})}forModels(e){return this.with({meta:{...this.meta,forModels:e}})}optional(){return new Of(this)}nullable(){return new kf(this)}default(e){return new Df(this,e)}bind(){return Xd(this).bind()}render(e){return Xd(this).bind().render(e)}ruleHint(){let e=this.checks.filter(e=>e.visible&&e.message).map(e=>e.message);return e.length?`Rules: ${e.join(` `)}`:void 0}hintOf(e){let t=[...e],n=this.ruleHint();return n&&t.push(n),t.length?t.join(` `):void 0}},ef={"date-time":/^\d{4}-\d{2}-\d{2}[Tt ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?([Zz]|[+-]\d{2}:?\d{2})?$/,date:/^\d{4}-\d{2}-\d{2}$/,time:/^\d{2}:\d{2}(:\d{2}(\.\d+)?)?([Zz]|[+-]\d{2}:?\d{2})?$/,duration:/^-?P(?=\d|T\d)(\d+(\.\d+)?Y)?(\d+(\.\d+)?M)?(\d+(\.\d+)?W)?(\d+(\.\d+)?D)?(T(?=\d)(\d+(\.\d+)?H)?(\d+(\.\d+)?M)?(\d+(\.\d+)?S)?)?$/,email:/^[^\s@]+@[^\s@]+\.[^\s@]+$/,uuid:/^[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}$/,uri:/^[a-zA-Z][a-zA-Z\d+.-]*:\S*$/,hostname:/^(?=.{1,253}$)[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,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:{test:e=>e.includes(`:`)&&/^[0-9a-fA-F:.]+$/.test(e)&&tf(`[${e}]`)}};function tf(e){try{return new URL(`http://${e}/`),!0}catch{return!1}}function nf(e){if(/\(\?<?[=!]|\\[bB]|\\[pP]\{|\\[1-9]|\\k</.test(e))return!1;for(let t of e.matchAll(/\{(\d+)(?:,(\d*))?\}/g))if(Number(t[1])>100||Number(t[2]||0)>100)return!1;return!0}var rf=class extends $d{constructor(e={}){super(),this.options=e}options;kind=`string`;children(){return[]}min(e){return this.opts({minLength:e})}max(e){return this.opts({maxLength:e})}pattern(e,t){let n=typeof e==`string`?t:t??(e.flags||void 0);return this.opts({pattern:typeof e==`string`?e:e.source,...n?{flags:n}:{}})}format(e){return this.opts({format:e})}opts(e){return this.with({options:{...this.options,...e}})}print(){return`string`}compile(e){let t=this.options,n=e.profile,r=t.pattern===void 0?void 0:new RegExp(t.pattern,t.flags?.replace(/[gy]/g,``)),i=`/${t.pattern}/${t.flags??``}`,a=t.format===void 0?void 0:ef[t.format],o=[];return e.node({hint:()=>this.hintOf(o),emit:()=>{let e={type:`string`};Jf(e,o,`minLength`,t.minLength,n.constraints.length,`At least ${t.minLength} characters.`),Jf(e,o,`maxLength`,t.maxLength,n.constraints.length,`At most ${t.maxLength} characters.`);let r=!t.flags&&(n.constraints.pattern===`full`||n.constraints.pattern===`basic`&&t.pattern!==void 0&&nf(t.pattern));return Jf(e,o,`pattern`,t.pattern,r,`Must match ${i}.`),Jf(e,o,`format`,t.format,n.formats===`all`||t.format!==void 0&&n.formats.has(t.format),`Format: ${t.format}.`),e},run:(e,n)=>typeof e==`string`?(t.minLength!==void 0&&e.length<t.minLength&&n.fail(`Must be at least ${t.minLength} characters.`,`rule`),t.maxLength!==void 0&&e.length>t.maxLength&&n.fail(`Must be at most ${t.maxLength} characters.`,`rule`),r&&!r.test(e)&&n.fail(`Must match ${i}.`,`rule`),a&&!a.test(e)&&n.fail(`Must be a valid ${t.format}.`,`rule`),e):If(n,e,`Expected a string, got ${Nf(e)}.`),encode:e=>e})}},af=class extends $d{constructor(e={}){super(),this.options=e}options;kind=`number`;children(){return[]}min(e){return this.opts({minimum:e})}max(e){return this.opts({maximum:e})}gt(e){return this.opts({exclusiveMinimum:e})}lt(e){return this.opts({exclusiveMaximum:e})}positive(){return this.gt(0)}negative(){return this.lt(0)}nonnegative(){return this.min(0)}int(){return this.opts({int:!0})}opts(e){return this.with({options:{...this.options,...e}})}print(){return`number`}compile(e){let t=this.options,n=e.profile.constraints.range,r=[];return e.node({hint:()=>this.hintOf(r),emit:()=>{let e={type:t.int?`integer`:`number`};return Jf(e,r,`minimum`,t.minimum,n,`At least ${t.minimum}.`),Jf(e,r,`maximum`,t.maximum,n,`At most ${t.maximum}.`),Jf(e,r,`exclusiveMinimum`,t.exclusiveMinimum,n,`Greater than ${t.exclusiveMinimum}.`),Jf(e,r,`exclusiveMaximum`,t.exclusiveMaximum,n,`Less than ${t.exclusiveMaximum}.`),e},run:(e,n)=>typeof e!=`number`||!Number.isFinite(e)?If(n,e,`Expected a number, got ${Nf(e)}.`):(t.int&&!Number.isInteger(e)&&n.fail(`Expected a whole number.`,`type`),t.minimum!==void 0&&e<t.minimum&&n.fail(`Must be at least ${t.minimum}.`,`rule`),t.exclusiveMinimum!==void 0&&e<=t.exclusiveMinimum&&n.fail(`Must be greater than ${t.exclusiveMinimum}.`,`rule`),t.exclusiveMaximum!==void 0&&e>=t.exclusiveMaximum&&n.fail(`Must be less than ${t.exclusiveMaximum}.`,`rule`),t.maximum!==void 0&&e>t.maximum&&n.fail(`Must be at most ${t.maximum}.`,`rule`),e),encode:e=>e})}},of=class extends $d{kind=`boolean`;children(){return[]}print(){return`boolean`}compile(e){return e.node({hint:()=>this.ruleHint(),emit:()=>({type:`boolean`}),run:(e,t)=>typeof e==`boolean`?e:If(t,e,`Expected true or false, got ${Nf(e)}.`),encode:e=>e})}},sf=class extends $d{kind=`null`;children(){return[]}print(){return`null`}compile(e){return e.node({emit:()=>({type:`null`}),run:(e,t)=>e===null?e:If(t,e,`Expected null, got ${Nf(e)}.`),encode:e=>e})}},cf=class extends $d{constructor(e){super(),this.value=e}value;kind=`literal`;children(){return[]}print(){return JSON.stringify(this.value)}compile(e){let t=this.value;return e.node({hint:()=>this.ruleHint(),emit:()=>t===null?{type:`null`}:{type:Ff(t),enum:[t]},run:(e,n)=>e===t?e:If(n,e,`Expected ${JSON.stringify(t)}.`,`literal`,typeof t==`string`?()=>[t]:void 0),encode:e=>e})}},lf=class extends $d{constructor(e){super(),this.values=e}values;kind=`enum`;children(){return[]}print(){return this.values.length?this.values.map(e=>JSON.stringify(e)).join(` | `):`never`}compile(e){let t=this.values;if(!t.length)return Ef(e,()=>this.ruleHint());let n=new Set(t),r=e.profile.maxEnumValues,i=r!==void 0&&t.length>r;return e.node({hint:()=>this.hintOf(i?[`One of: ${t.join(`, `)}.`]:[]),emit:()=>i?{type:`string`}:{type:`string`,enum:[...t]},run:(e,r)=>typeof e!=`string`||!n.has(e)?If(r,e,`Expected one of: ${Lf(t)}.`,`enum`,()=>t):e,encode:e=>e})}},uf=class extends $d{kind=`any`;children(){return[]}print(){return`any JSON value`}compile(e){let t=e.profile.any;return t===`empty`||t===`flat`?e.node({hint:()=>this.ruleHint(),emit:()=>t===`empty`?{}:{anyOf:ff.map(e=>({...e}))},run:(e,t)=>e===void 0?If(t,e,`Required.`,`required`):e,encode:e=>e}):df(e.node({own:!0,hint:()=>this.hintOf([`Write the value as JSON text.`]),emit:()=>({type:`string`}),run:(e,t)=>{let n=Bd(e,t);return n===zd?e:n},encode:e=>JSON.stringify(e)}))}};function df(e){return e.jsonText=!0,e}var ff=Object.freeze([{type:`string`},{type:`number`},{type:`boolean`},{type:`null`},{type:`array`},{type:`object`,additionalProperties:!0}]),pf=class extends $d{constructor(e,t={}){super(),this.element=e,this.options=t}element;options;kind=`array`;children(){return[this.element]}min(e){return this.with({options:{...this.options,minItems:e}})}max(e){return this.with({options:{...this.options,maxItems:e}})}print(e){let t=e.print(this.element);return/[|&]/.test(t)?`(${t})[]`:`${t}[]`}compile(e){let t=Tf(this.element,e.env)?{...this.options,maxItems:0}:this.options,n=(t.minItems??0)>0?e.compile(this.element):e.guarded(this.element),r=e.profile.constraints.items,i=[];return e.node({deps:[n],hint:()=>this.hintOf(i),emit:()=>{let e={type:`array`,items:n.json()};return Jf(e,i,`minItems`,t.minItems,r===`all`||r===`min-0-1`&&(t.minItems??0)<=1,`At least ${t.minItems} items.`),Jf(e,i,`maxItems`,t.maxItems,r===`all`,`At most ${t.maxItems} items.`),e},run:(e,r)=>{let i=Yf(e,r,`array`);if(!Array.isArray(i))return If(r,i,`Expected a list, got ${Nf(i)}.`);t.minItems!==void 0&&i.length<t.minItems&&r.fail(`Must have at least ${t.minItems} items.`,`rule`),t.maxItems!==void 0&&i.length>t.maxItems&&r.fail(`Must have at most ${t.maxItems} items.`,`rule`);let a=i;for(let e=0;e<i.length;e++){r.enter(e);let t=n.run(i[e],r);r.leave(),t!==i[e]&&!r.dry&&(a=$f(a,i,e,t,r))}return a},encode:(e,t)=>Xf(e,e=>n.encode(e,t),t),child:()=>n})}},mf=class extends $d{constructor(e){super(),this.items=e}items;kind=`tuple`;children(){return this.items}print(e){return`[${this.items.map(t=>e.print(t)).join(`, `)}]`}compile(e){let t=this.items.map(t=>e.compile(t)),n=e.profile.tuples,r=t.length,i=(e,n,i)=>{let a=e;for(let o=0;o<r;o++){n.enter(i(o),o);let r=t[o].run(e[o],n);n.leave(),r!==e[o]&&!n.dry&&(a=$f(a,e,o,r,n))}return a};return e.node({own:n===`object`,deps:t,hint:()=>this.hintOf(n===`object`?[`Positions are written as keys "0".."${r-1}".`]:n===`array`?[`Exactly ${r} items, in order: ${this.items.map(t=>t.print(new wd(e.env))).join(`, `)}.`]:[]),emit:()=>{if(n===`object`){let n={};return t.forEach((e,t)=>n[String(t)]=e.json()),e.object(n,Object.keys(n))}return n===`prefixItems`?{type:`array`,prefixItems:t.map(e=>e.json()),minItems:r,maxItems:r}:{type:`array`,items:{anyOf:t.map(e=>e.json())}}},run:(e,t)=>{if(n===`object`){let n=Yf(e,t,`object`);if(!Mf(n))return If(t,n,`Expected an object with keys "0".."`+(r-1)+`".`);let a=Array(r);for(let e=0;e<r;e++)a[e]=n[String(e)];t.dry||t.stats.arrays++;let o=i(a,t,e=>String(e));return t.dry?n:o}let a=Yf(e,t,`array`);return Array.isArray(a)?(a.length!==r&&t.fail(`Expected exactly ${r} items.`,`rule`),i(a,t,e=>e)):If(t,a,`Expected a list of ${r} items.`)},encode:(e,r)=>{let i=e;if(n!==`object`)return Xf(i,(e,n)=>t[n].encode(e,r),r);let a={};return r.objects++,i.forEach((e,n)=>a[String(n)]=t[n].encode(e,r)),a},child:e=>t[Number(e)]})}},hf=class e extends $d{constructor(e,t=!1,n={}){super(),this.shape=e,this.closed=t,this.extras=n}shape;closed;extras;kind=`object`;children(){let e=Object.values(this.shape);this.extras.rest&&e.push(this.extras.rest);for(let t of this.extras.patterns??[])e.push(t.schema);return e}strict(){return this.with({closed:!0})}extend(t){return new e({...this.shape,...t},this.closed,this.extras)}rest(t){return new e(this.shape,this.closed,{...this.extras,rest:t})}patterns(t){let n=Object.entries(t).map(([e,t])=>({pattern:e,schema:t}));return new e(this.shape,this.closed,{...this.extras,patterns:[...this.extras.patterns??[],...n]})}dependent(t,n,r,i){let a=new Sf(n,r,i??new uf);return new e({...this.shape,[t]:a},this.closed,this.extras)}print(e){let t=Object.entries(this.shape).map(([t,n])=>{let r=n instanceof Of||n instanceof Df;return`${/^[A-Za-z_$][\w$]*$/.test(t)?t:JSON.stringify(t)}${r?`?`:``}: ${e.print(r?n.inner:n)}`}),n=this.extraValue();return n&&t.push(`[key: string]: ${e.print(n)}`),`{ ${t.join(`; `)} }`}_extraValue;extraValue(){if(this._extraValue===void 0){let e=[...(this.extras.patterns??[]).map(e=>e.schema),...this.extras.rest?[this.extras.rest]:[]];this._extraValue=e.length===0?null:e.length===1?e[0]:new vf(e)}return this._extraValue??void 0}compile(e){let t=e.profile,n=t.optional===`null`,r=t.audience!==`people`,i=[],a=new Set;for(let[t,n]of Object.entries(this.shape)){let o=r?n.meta.forModels:void 0,s=o?o.meta.description===void 0&&n.meta.description!==void 0?o.describe(n.meta.description):o:n;if(r&&n.meta.audience===`people`){a.add(t);continue}let c=s instanceof Df?s:void 0,l=s instanceof Of||!!c,u=s instanceof Of?s.inner:c?c.inner:s;if(l&&Tf(u,e.env)){a.add(t);continue}let d=l?e.guarded(u,s):e.compile(u);i.push({key:t,optional:l,node:d,nullable:u instanceof kf,...u instanceof Sf?{dep:u}:{},...c?{dflt:c}:{}})}let o=i.filter(e=>!e.dep),s=i.filter(e=>e.dep),c=new Set(Object.keys(this.shape)),l=this.extraValue(),u=(this.extras.patterns??[]).map(t=>({re:new RegExp(t.pattern),pattern:t.pattern,node:e.guarded(t.schema)})),d=this.extras.rest?e.guarded(this.extras.rest):void 0,f=l?t.records===`pairs`?`pairs`:t.patternProperties?`keywords`:`open`:`none`,p=f===`pairs`?c.has(`extra`)?`_extra`:`extra`:``,m=l&&f!==`keywords`?e.guarded(l):void 0,h=e=>u.find(t=>t.re.test(e))?.node??d;return e.node({own:n&&i.some(e=>e.optional&&!e.nullable)||a.size>0||f===`pairs`||i.some(e=>e.dflt),deps:[...i.map(e=>e.node),...u.map(e=>e.node),...d?[d]:[],...m?[m]:[]],hint:()=>this.hintOf(f===`pairs`?[`Other keys go in "${p}" as a list of {key, value} entries.`]:f===`open`&&u.length?[`Other keys: ${u.map(t=>`keys matching /${t.pattern}/ hold ${t.node.schema?.print(new wd(e.env))??`a value`}`).join(`; `)}${d?`; any other key holds the rest`:``}.`]:[]),emit:()=>{let r={},a=[];for(let t of i){let i=t.node.json();t.dep&&(i={...i,description:[i.description,`Its type is given by "${t.dep.on}".`].filter(Boolean).join(`
|
|
60
|
+
`)}`:t}},Od=new Set([`object`,`array`,`record`,`tuple`]),kd=new WeakMap;function Ad(e){let t=kd.get(e);return t===void 0&&(t=e.kind===`dependent`||e.children().some(Ad),kd.set(e,t)),t}var jd=new WeakMap;function Md(e){let t=jd.get(e);return t===void 0&&(t=+!!Od.has(e.kind)+Math.max(0,...e.children().map(Md)),jd.set(e,t)),t}var Nd=new WeakMap,Pd=new WeakMap;function Fd(e){let t=Pd.get(e);return t||Pd.set(e,t=new Ud(e,Id,Rd,!1,!0)),t}var Id=new Map,Ld;function Rd(){if(!Ld){let e=Fd($l);Ld=new qd(e,e.node({emit:()=>({}),run:e=>e,encode:e=>e}))}return Ld}var zd=/^[A-Za-z0-9_.-]+$/,Bd=new WeakMap;function Vd(e){let t=Bd.get(e);if(t)return t;let n=new Map,r=new Set;for(let t of e.keys())zd.test(t)&&(n.set(t,t),r.add(t));for(let t of[...e.keys()].filter(e=>!zd.test(e)).sort()){let e=t.replace(/[^A-Za-z0-9_.-]/g,`_`)||`_`,i=e;for(let t=2;r.has(i);t++)i=`${e}_${t}`;r.add(i),n.set(t,i)}return Bd.set(e,n),n}var Hd=class extends Error{},Ud=class{constructor(e,t,n,r=!1,i=!1){this.profile=e,this.env=t,this.lenient=n,this.inlineOnce=r,this.shared=i,this.view=Su(e)}profile;env;lenient;inlineOnce;shared;nodes=[];defs=new Map;_defKeys;glossary=new Set;inlined=new Set;recursive=new Map;view;stack=[];depth=0;guard=0;isRecursive(e){let t=this.recursive.get(e);if(t===void 0){let n=new Set,r=[...this.env.get(e)?.refNames()??[]];for(t=!1;r.length;){let i=r.pop();if(i===e){t=!0;break}n.has(i)||(n.add(i),r.push(...this.env.get(i)?.refNames()??[]))}this.recursive.set(e,t)}return t}node(e){return new Ed(e,this)}compile(e,t){if(this.profile.audience!==`people`&&e.meta.forModels){let{forModels:t,...n}=e.meta,r=t;e=r.meta.description===void 0&&n.description!==void 0?r.describe(n.description):r}let n=Od.has(e.kind);if(n&&this.profile.maxDepth!==void 0&&this.depth>=this.profile.maxDepth)return this.escape(e,`Nested too deep for this model to describe directly.`);let r=!t&&e.refNames().size===0&&!Ad(e)&&(this.profile.maxDepth===void 0||this.depth+Md(e)<this.profile.maxDepth);if(r){let t=Nd.get(e)?.get(this.profile.id);if(t)return t;if(!this.shared){let t=Fd(this.profile),n=t.compile(e);return t.finish(),n}}n&&this.depth++;let i=e.compile(this);if(n&&this.depth--,i.schema=e,i.outer=t,this.nodes.push(i),r){let t=Nd.get(e);t||Nd.set(e,t=new Map),t.set(this.profile.id,i)}return i}guarded(e,t){this.guard++;try{return this.compile(e,t)}finally{this.guard--}}ref(e){let t=this.env.get(e);if(!t)throw new Tu(`ref "${e}" is not defined (the chain's types should have prevented this).`);let n=this.profile,r=this.stack.find(t=>t.name===e);if(r)return n.defs&&(n.recursion===!0||n.recursion===`guarded`&&this.guard>r.guard)?this.defRef(e,this.defs.get(e)):this.escape(t,`"${e}" contains itself, which this model cannot describe directly.`,e);if(n.defs){let n=this.defs.get(e);if(n)return this.defRef(e,n);let r=new Wd(this);return this.defs.set(e,r),this.stack.push({name:e,guard:this.guard}),r.target=this.compile(t),this.stack.pop(),this.nodes.push(r),this.defRef(e,r)}if(this.inlineOnce&&this.isRecursive(e)){if(this.inlined.has(e))return this.escape(t,`"${e}" is written out once elsewhere in this schema.`,e);this.inlined.add(e)}else if(!this.inlineOnce&&this.nodes.length>4e3)throw new Hd;this.stack.push({name:e,guard:this.guard});let i=this.compile(t);return this.stack.pop(),i}defKey(e){return(this._defKeys??=Vd(this.env)).get(e)??e.replace(/[^A-Za-z0-9_.-]/g,`_`)}defRef(e,t){let n=this.node({deps:[t],emit:()=>({$ref:`#/$defs/${this.defKey(e)}`}),run:(e,n)=>t.run(e,n),encode:(e,n)=>t.encode(e,n),child:e=>t.child(e)});return this.nodes.push(n),n.refName=e,n}escape(e,t,n){let r=new Dd(this.env),i=n??r.print(e);for(let e of n?[n]:r.used())this.glossary.add(e);let a=n||r.used().length?` (its named types are defined in the description of the whole schema)`:``,o,s=()=>o??=this.lenient().nodeFor(e),c=this.node({own:!0,emit:()=>({type:`string`,description:`${t} Write it as JSON text of this TypeScript type: ${i}${a}.`}),run:(e,t)=>{let n=Kd(e,t);if(n===Gd)return e;t.enter(`(json)`,null);let r=s().run(n,t);return t.leave(!1),r},encode:e=>JSON.stringify(e)});return c.jsonText=!0,this.nodes.push(c),c}late(e){let t=this.compile(e);return this.finish(),t}finish(){for(let e=!0;e;){e=!1;for(let t of this.nodes)t.needs||(t.own||t.deps.some(e=>e.needs))&&(t.needs=!0,e=!0)}this.shared&&(this.nodes.length=0)}text(e){return e===void 0?void 0:typeof e==`function`?e(this.view):e}nullable(e){let t=this.profile.nulls;if(e.nullable===!0||Array.isArray(e.type)&&e.type.includes(`null`)||e.type===`null`)return e;if(t===`nullable`)return{...e,nullable:!0};if(t===`type-array`&&typeof e.type==`string`&&!(`$ref`in e)&&!(`anyOf`in e)){let t={...e,type:[e.type,`null`]};return Array.isArray(e.enum)&&(t.enum=[...e.enum,null]),t}if(Array.isArray(e.anyOf)&&!(`$ref`in e))return e.anyOf.some(e=>e.type===`null`)?e:{...e,anyOf:[...e.anyOf,{type:`null`}]};let{description:n,...r}=e;return n===void 0?{anyOf:[r,{type:`null`}]}:{anyOf:[r,{type:`null`}],description:n}}object(e,t,n=this.profile.closedObjects){let r={type:`object`,properties:e,required:[...t]};return n&&(r.additionalProperties=!1),this.profile.propertyOrdering&&(r.propertyOrdering=Object.keys(e)),r}decorate(e,t){let n=[],r=[e.schema?.meta,e.outer?.meta],i,a=[];for(let t of r){if(!t)continue;let r=this.text(t.description);if(r&&n.push(r),t.title&&(i=t.title),t.examples)for(let n of t.examples)this.checkExample(e,n),a.push(e.encode(n))}let o=e.impl?.hint?.(this.view);o&&n.push(o);let s=typeof t.description==`string`?t.description:void 0;s&&n.push(s);let c={...t};if(i&&(c.title=i),a.length&&(this.profile.examples===`keyword`?c.examples=a:this.profile.examples===`description`&&n.push(`Example${a.length>1?`s`:``}: ${a.map(e=>JSON.stringify(e)).join(` ; `)}`)),n.length&&(c.description=n.join(`
|
|
61
|
+
`)),this.profile.refSiblings===!1&&typeof c.$ref==`string`&&(c.description!==void 0||c.title!==void 0||c.examples!==void 0)){let{$ref:e,...t}=c;return{anyOf:[{$ref:e}],...t}}return c}checkExample(e,t){let n=e.schema;if(!n)return;let r=new Td(!1,!0,vd(),!1);if(this.lenient().nodeFor(n).run(t,r),r.errors.length)throw new Tu(`example ${JSON.stringify(t)} does not fit its schema:
|
|
62
|
+
${Yd(r.errors)}`)}},Wd=class extends Ed{target;constructor(e){super(void 0,e)}get own(){return!1}get deps(){return this.target?[this.target]:[]}json(){return this.target.json()}run(e,t){return this.target.run(e,t)}encode(e,t=vd()){return this.target.encode(e,t)}child(e){return this.target.child(e)}},Gd=Symbol(`failed`);function Kd(e,t){if(typeof e!=`string`)return t.repair&&e!==void 0?(t.dry||t.stats.repaired++,e):(t.fail(`Expected a string of JSON text.`,`type`),Gd);try{let n=JSON.parse(e);return t.dry||t.stats.parsed++,n}catch(e){return t.fail(`Not valid JSON text: ${e.message}`,`json`),Gd}}var qd=class{constructor(e,t){this.compiler=e,this.root=t}compiler;root;_json;_body;_wrapped;_measure;_encoder;get profile(){return this.compiler.profile}body(){if(!this._body){let e=this.root.refName;this._body=e?this.compiler.defs.get(e).json():this.root.json()}return this._body}get wrapped(){if(this._wrapped===void 0){let e=this.body();this._wrapped=this.profile.rootObject&&!(e.type===`object`&&!(`anyOf`in e))}return this._wrapped}get jsonSchema(){if(this._json)return this._json;let e=this.body();if(this.wrapped&&(e=this.compiler.object({input:e},[`input`],this.profile.closedObjects||this.profile.strict)),this.compiler.glossary.size){let t=`Named types used by the fields written as JSON text:
|
|
63
|
+
${new Dd(this.compiler.env).definitions(this.compiler.glossary)}`;e={...e,description:typeof e.description==`string`?`${e.description}
|
|
64
|
+
${t}`:t}}let t={};for(let[e,n]of this.compiler.defs)t[this.compiler.defKey(e)]=n.json();return this._json=this.compiler.defs.size?{...e,$defs:t}:e,this._json}get measure(){return this._measure??=Cu(this.jsonSchema)}parse(e,t){return this.decode(e,t,void 0)}decode(e,t,n){let r=vd(),i=t?.inPlace??!0,a=new Td(i,!1,r,t?.repair??!0),o=i&&!n&&Fu(t?.errorFormat);o&&a.keepUndo();let s;if(this.wrapped?typeof e!=`object`||!e||Array.isArray(e)||!(`input`in e)?a.fail(`Expected an object with an "input" field.`,`type`):(a.enter(`input`,null),s=this.root.run(e.input,a),a.leave(!1)):s=this.root.run(e,a),a.errors.length){a.restore(),a.releaseUndo();let i=n?n():e;return{ok:!1,issues:a.errors,message:td(a.errors,i,Nu(t?.errorFormat),t?.label),stats:r}}return o&&a.releaseUndo(),{ok:!0,value:s,stats:r}}parseText(e,t){let n;try{n=JSON.parse(e)}catch(e){let n=[{path:[],codePath:[],message:`Not valid JSON: ${e.message}`}];return Lu(n[0],{kind:`json`}),{ok:!1,issues:n,message:td(n,void 0,Nu(t?.errorFormat),t?.label),stats:vd()}}return this.decode(n,t,()=>JSON.parse(e))}parseOrThrow(e,t){let n=this.parse(e,t);if(!n.ok)throw new Eu(n.issues,n.message);return n.value}encode(e,t=vd()){let n=this.root.encode(e,t);return this.wrapped?(t.objects++,{input:n}):n}encodeAt(e,t,n=vd()){let r=Jd(t);if(!r.length)return this.encode(e,n);let i=this.root;for(let e of r)if(i=i?.child(e),!i)throw new Tu(`no schema at path ${yd(r)}.`);return i.encode(e,n)}encodeText(e,t={}){let n=t.path===void 0?this.encode(e):this.encodeAt(e,t.path),r=t.pretty===!0?2:typeof t.pretty==`number`?t.pretty:void 0;return JSON.stringify(n,null,r)}get encoder(){if(!this._encoder){let e=((e,t)=>this.encodeText(e,t));e.wire=(e,t)=>t===void 0?this.encode(e):this.encodeAt(e,t),this._encoder=Object.freeze(e)}return this._encoder}nodeFor(e){let t=this.lateNodes.get(e);return t||this.lateNodes.set(e,t=this.compiler.late(e)),t}lateNodes=new WeakMap;typescript(){let e=this.root.schema;return new Dd(this.compiler.env).full(e)}};function Jd(e){return e===void 0||e===``?[]:typeof e==`string`?e.split(`.`).map(e=>/^\d+$/.test(e)?Number(e):e):[...e]}function Yd(e){return e.map(e=>`- at ${yd(e.path)}: ${e.message}`).join(`
|
|
65
|
+
`)}var Xd=class e{constructor(e={}){this.defs=e}defs;define(t){for(let e of Object.keys(t))if(e in this.defs)throw new Tu(`"${e}" is already defined.`);return new e({...this.defs,...t})}declare(){return this}dynamic(e,t={}){return new Zd(this.defs,e,t)}result(e){return new $d(this.defs,Qd(e))}},Zd=class{constructor(e,t,n){this.defs=e,this.fn=t,this.opts=n}defs;fn;opts;result(e){return new $d(this.defs,Qd(e),{fn:this.fn,opts:this.opts})}};function Qd(e){return typeof e==`string`?new If(e):e}var $d=class e{constructor(e,t,n){this.defs=e,this.root=t,this.dyn=n}defs;root;dyn;cache=new Map;staticBound;bind=(...e)=>{let t=this.dyn;if(!t)return this.staticBound??=new ef(new Map(Object.entries(this.defs)),this.root);let n=t.opts.key?.(...e);if(n!==void 0){let e=this.cache.get(n);if(e)return this.cache.delete(n),this.cache.set(n,e),e}let r=t.fn(...e),i=new Map(Object.entries(this.defs));for(let[e,t]of Object.entries(r)){if(i.has(e))throw new Tu(`the dynamic step redefined "${e}".`);i.set(e,t)}let a=new ef(i,this.root);if(n!==void 0){this.cache.set(n,a);let e=t.opts.cacheSize??4;for(;this.cache.size>e;)this.cache.delete(this.cache.keys().next().value)}return a};adapt(t){let n=this.dyn;if(!n)return this;let r=n.opts.key;return new e(this.defs,this.root,{fn:(...e)=>n.fn(...t(...e)),opts:{...n.opts,...r?{key:(...e)=>r(...t(...e))}:{}}})}render(e,...t){return this.bind(...t).render(e)}},ef=class{constructor(e,t){this.env=e,this.root=t;let n=[],r=t=>{for(let r of t.refNames())!e.has(r)&&!n.includes(r)&&n.push(r)};r(t);for(let t of e.values())r(t);if(n.length)throw new Tu(`unresolved ref(s) ${n.join(`, `)}.`)}env;root;rendered=new Map;render(e){let t=this.rendered.get(e.id);if(!t){let n=()=>this.render($l),r=new Ud(e,this.env,n),i;try{i=r.compile(this.root)}catch(t){if(!(t instanceof Hd))throw t;r=new Ud(e,this.env,n,!0),i=r.compile(this.root)}r.finish(),t=new qd(r,i),this.rendered.set(e.id,t)}return t}},tf=new WeakMap;function nf(e){let t=tf.get(e);return t||tf.set(e,t=new $d({},e)),t}var rf=Object.freeze({}),af=Object.freeze([]),of=class{meta=rf;checks=af;_refNames;refNames(){if(!this._refNames){let e=new Set;this instanceof If&&e.add(this.name);for(let t of this.children())for(let n of t.refNames())e.add(n);if(this.meta.forModels)for(let t of this.meta.forModels.refNames())e.add(t);this._refNames=e}return this._refNames}with(e){let t=Object.create(Object.getPrototypeOf(this));return Object.assign(t,this,e,{_refNames:void 0}),t}describe(e){return this.with({meta:{...this.meta,description:e}})}title(e){return this.with({meta:{...this.meta,title:e}})}example(...e){return this.with({meta:{...this.meta,examples:[...this.meta.examples??[],...e]}})}refine(e,t,n){let r={fn:e,...t===void 0?{}:{message:t},visible:n?.visible??t!==void 0};return this.with({checks:[...this.checks,r]})}brand(){return this}forPeople(){return this.with({meta:{...this.meta,audience:`people`}})}forModels(e){return this.with({meta:{...this.meta,forModels:e}})}optional(){return new Pf(this)}nullable(){return new Ff(this)}default(e){return new Nf(this,e)}bind(){return nf(this).bind()}render(e){return nf(this).bind().render(e)}ruleHint(){let e=this.checks.filter(e=>e.visible&&e.message).map(e=>e.message);return e.length?`Rules: ${e.join(` `)}`:void 0}hintOf(e){let t=[...e],n=this.ruleHint();return n&&t.push(n),t.length?t.join(` `):void 0}},sf={"date-time":/^\d{4}-\d{2}-\d{2}[Tt ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?([Zz]|[+-]\d{2}:?\d{2})?$/,date:/^\d{4}-\d{2}-\d{2}$/,time:/^\d{2}:\d{2}(:\d{2}(\.\d+)?)?([Zz]|[+-]\d{2}:?\d{2})?$/,duration:/^-?P(?=\d|T\d)(\d+(\.\d+)?Y)?(\d+(\.\d+)?M)?(\d+(\.\d+)?W)?(\d+(\.\d+)?D)?(T(?=\d)(\d+(\.\d+)?H)?(\d+(\.\d+)?M)?(\d+(\.\d+)?S)?)?$/,email:/^[^\s@]+@[^\s@]+\.[^\s@]+$/,uuid:/^[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}$/,uri:/^[a-zA-Z][a-zA-Z\d+.-]*:\S*$/,hostname:/^(?=.{1,253}$)[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,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:{test:e=>e.includes(`:`)&&/^[0-9a-fA-F:.]+$/.test(e)&&cf(`[${e}]`)}};function cf(e){try{return new URL(`http://${e}/`),!0}catch{return!1}}function lf(e){if(/\(\?<?[=!]|\\[bB]|\\[pP]\{|\\[1-9]|\\k</.test(e))return!1;for(let t of e.matchAll(/\{(\d+)(?:,(\d*))?\}/g))if(Number(t[1])>100||Number(t[2]||0)>100)return!1;return!0}var uf=class extends of{constructor(e={}){super(),this.options=e}options;kind=`string`;children(){return[]}min(e){return this.opts({minLength:e})}max(e){return this.opts({maxLength:e})}pattern(e,t){let n=typeof e==`string`?t:t??(e.flags||void 0);return this.opts({pattern:typeof e==`string`?e:e.source,...n?{flags:n}:{}})}format(e){return this.opts({format:e})}opts(e){return this.with({options:{...this.options,...e}})}print(){return`string`}compile(e){let t=this.options,n=e.profile,r=t.pattern===void 0?void 0:new RegExp(t.pattern,t.flags?.replace(/[gy]/g,``)),i=`/${t.pattern}/${t.flags??``}`,a=t.format===void 0?void 0:sf[t.format],o=[];return e.node({hint:()=>this.hintOf(o),emit:()=>{let e={type:`string`};ep(e,o,`minLength`,t.minLength,n.constraints.length,`At least ${t.minLength} characters.`),ep(e,o,`maxLength`,t.maxLength,n.constraints.length,`At most ${t.maxLength} characters.`);let r=!t.flags&&(n.constraints.pattern===`full`||n.constraints.pattern===`basic`&&t.pattern!==void 0&&lf(t.pattern));return ep(e,o,`pattern`,t.pattern,r,`Must match ${i}.`),ep(e,o,`format`,t.format,n.formats===`all`||t.format!==void 0&&n.formats.has(t.format),`Format: ${t.format}.`),e},run:(e,n)=>typeof e==`string`?(t.minLength!==void 0&&e.length<t.minLength&&n.fail(`Must be at least ${t.minLength} characters.`,`rule`),t.maxLength!==void 0&&e.length>t.maxLength&&n.fail(`Must be at most ${t.maxLength} characters.`,`rule`),r&&!r.test(e)&&n.fail(`Must match ${i}.`,`rule`),a&&!a.test(e)&&n.fail(`Must be a valid ${t.format}.`,`rule`),e):Hf(n,e,`Expected a string, got ${zf(e)}.`),encode:e=>e})}},df=class extends of{constructor(e={}){super(),this.options=e}options;kind=`number`;children(){return[]}min(e){return this.opts({minimum:e})}max(e){return this.opts({maximum:e})}gt(e){return this.opts({exclusiveMinimum:e})}lt(e){return this.opts({exclusiveMaximum:e})}positive(){return this.gt(0)}negative(){return this.lt(0)}nonnegative(){return this.min(0)}int(){return this.opts({int:!0})}opts(e){return this.with({options:{...this.options,...e}})}print(){return`number`}compile(e){let t=this.options,n=e.profile.constraints.range,r=[];return e.node({hint:()=>this.hintOf(r),emit:()=>{let e={type:t.int?`integer`:`number`};return ep(e,r,`minimum`,t.minimum,n,`At least ${t.minimum}.`),ep(e,r,`maximum`,t.maximum,n,`At most ${t.maximum}.`),ep(e,r,`exclusiveMinimum`,t.exclusiveMinimum,n,`Greater than ${t.exclusiveMinimum}.`),ep(e,r,`exclusiveMaximum`,t.exclusiveMaximum,n,`Less than ${t.exclusiveMaximum}.`),e},run:(e,n)=>typeof e!=`number`||!Number.isFinite(e)?Hf(n,e,`Expected a number, got ${zf(e)}.`):(t.int&&!Number.isInteger(e)&&n.fail(`Expected a whole number.`,`type`),t.minimum!==void 0&&e<t.minimum&&n.fail(`Must be at least ${t.minimum}.`,`rule`),t.exclusiveMinimum!==void 0&&e<=t.exclusiveMinimum&&n.fail(`Must be greater than ${t.exclusiveMinimum}.`,`rule`),t.exclusiveMaximum!==void 0&&e>=t.exclusiveMaximum&&n.fail(`Must be less than ${t.exclusiveMaximum}.`,`rule`),t.maximum!==void 0&&e>t.maximum&&n.fail(`Must be at most ${t.maximum}.`,`rule`),e),encode:e=>e})}},ff=class extends of{kind=`boolean`;children(){return[]}print(){return`boolean`}compile(e){return e.node({hint:()=>this.ruleHint(),emit:()=>({type:`boolean`}),run:(e,t)=>typeof e==`boolean`?e:Hf(t,e,`Expected true or false, got ${zf(e)}.`),encode:e=>e})}},pf=class extends of{kind=`null`;children(){return[]}print(){return`null`}compile(e){return e.node({emit:()=>({type:`null`}),run:(e,t)=>e===null?e:Hf(t,e,`Expected null, got ${zf(e)}.`),encode:e=>e})}},mf=class extends of{constructor(e){super(),this.value=e}value;kind=`literal`;children(){return[]}print(){return JSON.stringify(this.value)}compile(e){let t=this.value;return e.node({hint:()=>this.ruleHint(),emit:()=>t===null?{type:`null`}:{type:Vf(t),enum:[t]},run:(e,n)=>e===t?e:Hf(n,e,`Expected ${JSON.stringify(t)}.`,`literal`,typeof t==`string`?()=>[t]:void 0),encode:e=>e})}},hf=class extends of{constructor(e){super(),this.values=e}values;kind=`enum`;children(){return[]}print(){return this.values.length?this.values.map(e=>JSON.stringify(e)).join(` | `):`never`}compile(e){let t=this.values;if(!t.length)return Mf(e,()=>this.ruleHint());let n=new Set(t),r=e.profile.maxEnumValues,i=r!==void 0&&t.length>r;return e.node({hint:()=>this.hintOf(i?[`One of: ${t.join(`, `)}.`]:[]),emit:()=>i?{type:`string`}:{type:`string`,enum:[...t]},run:(e,r)=>typeof e!=`string`||!n.has(e)?Hf(r,e,`Expected one of: ${Uf(t)}.`,`enum`,()=>t):e,encode:e=>e})}},gf=class extends of{kind=`any`;children(){return[]}print(){return`any JSON value`}compile(e){let t=e.profile.any;return t===`empty`||t===`flat`?e.node({hint:()=>this.ruleHint(),emit:()=>t===`empty`?{}:{anyOf:vf.map(e=>({...e}))},run:(e,t)=>e===void 0?Hf(t,e,`Required.`,`required`):e,encode:e=>e}):_f(e.node({own:!0,hint:()=>this.hintOf([`Write the value as JSON text.`]),emit:()=>({type:`string`}),run:(e,t)=>{let n=Kd(e,t);return n===Gd?e:n},encode:e=>JSON.stringify(e)}))}};function _f(e){return e.jsonText=!0,e}var vf=Object.freeze([{type:`string`},{type:`number`},{type:`boolean`},{type:`null`},{type:`array`},{type:`object`,additionalProperties:!0}]),yf=class extends of{constructor(e,t={}){super(),this.element=e,this.options=t}element;options;kind=`array`;children(){return[this.element]}min(e){return this.with({options:{...this.options,minItems:e}})}max(e){return this.with({options:{...this.options,maxItems:e}})}print(e){let t=e.print(this.element);return/[|&]/.test(t)?`(${t})[]`:`${t}[]`}compile(e){let t=jf(this.element,e.env)?{...this.options,maxItems:0}:this.options,n=(t.minItems??0)>0?e.compile(this.element):e.guarded(this.element),r=e.profile.constraints.items,i=[];return e.node({deps:[n],hint:()=>this.hintOf(i),emit:()=>{let e={type:`array`,items:n.json()};return ep(e,i,`minItems`,t.minItems,r===`all`||r===`min-0-1`&&(t.minItems??0)<=1,`At least ${t.minItems} items.`),ep(e,i,`maxItems`,t.maxItems,r===`all`,`At most ${t.maxItems} items.`),e},run:(e,r)=>{let i=tp(e,r,`array`);if(!Array.isArray(i))return Hf(r,i,`Expected a list, got ${zf(i)}.`);t.minItems!==void 0&&i.length<t.minItems&&r.fail(`Must have at least ${t.minItems} items.`,`rule`),t.maxItems!==void 0&&i.length>t.maxItems&&r.fail(`Must have at most ${t.maxItems} items.`,`rule`);let a=i;for(let e=0;e<i.length;e++){r.enter(e);let t=n.run(i[e],r);r.leave(),t!==i[e]&&!r.dry&&(a=ap(a,i,e,t,r))}return a},encode:(e,t)=>np(e,e=>n.encode(e,t),t),child:()=>n})}},bf=class extends of{constructor(e){super(),this.items=e}items;kind=`tuple`;children(){return this.items}print(e){return`[${this.items.map(t=>e.print(t)).join(`, `)}]`}compile(e){let t=this.items.map(t=>e.compile(t)),n=e.profile.tuples,r=t.length,i=(e,n,i)=>{let a=e;for(let o=0;o<r;o++){n.enter(i(o),o);let r=t[o].run(e[o],n);n.leave(),r!==e[o]&&!n.dry&&(a=ap(a,e,o,r,n))}return a};return e.node({own:n===`object`,deps:t,hint:()=>this.hintOf(n===`object`?[`Positions are written as keys "0".."${r-1}".`]:n===`array`?[`Exactly ${r} items, in order: ${this.items.map(t=>t.print(new Dd(e.env))).join(`, `)}.`]:[]),emit:()=>{if(n===`object`){let n={};return t.forEach((e,t)=>n[String(t)]=e.json()),e.object(n,Object.keys(n))}return n===`prefixItems`?{type:`array`,prefixItems:t.map(e=>e.json()),minItems:r,maxItems:r}:{type:`array`,items:{anyOf:t.map(e=>e.json())}}},run:(e,t)=>{if(n===`object`){let n=tp(e,t,`object`);if(!Rf(n))return Hf(t,n,`Expected an object with keys "0".."`+(r-1)+`".`);let a=Array(r);for(let e=0;e<r;e++)a[e]=n[String(e)];t.dry||t.stats.arrays++;let o=i(a,t,e=>String(e));return t.dry?n:o}let a=tp(e,t,`array`);return Array.isArray(a)?(a.length!==r&&t.fail(`Expected exactly ${r} items.`,`rule`),i(a,t,e=>e)):Hf(t,a,`Expected a list of ${r} items.`)},encode:(e,r)=>{let i=e;if(n!==`object`)return np(i,(e,n)=>t[n].encode(e,r),r);let a={};return r.objects++,i.forEach((e,n)=>a[String(n)]=t[n].encode(e,r)),a},child:e=>t[Number(e)]})}},xf=class e extends of{constructor(e,t=!1,n={}){super(),this.shape=e,this.closed=t,this.extras=n}shape;closed;extras;kind=`object`;children(){let e=Object.values(this.shape);this.extras.rest&&e.push(this.extras.rest);for(let t of this.extras.patterns??[])e.push(t.schema);return e}strict(){return this.with({closed:!0})}extend(t){return new e({...this.shape,...t},this.closed,this.extras)}rest(t){return new e(this.shape,this.closed,{...this.extras,rest:t})}patterns(t){let n=Object.entries(t).map(([e,t])=>({pattern:e,schema:t}));return new e(this.shape,this.closed,{...this.extras,patterns:[...this.extras.patterns??[],...n]})}dependent(t,n,r,i){let a=new Of(n,r,i??new gf);return new e({...this.shape,[t]:a},this.closed,this.extras)}print(e){let t=Object.entries(this.shape).map(([t,n])=>{let r=n instanceof Pf||n instanceof Nf;return`${/^[A-Za-z_$][\w$]*$/.test(t)?t:JSON.stringify(t)}${r?`?`:``}: ${e.print(r?n.inner:n)}`}),n=this.extraValue();return n&&t.push(`[key: string]: ${e.print(n)}`),`{ ${t.join(`; `)} }`}_extraValue;extraValue(){if(this._extraValue===void 0){let e=[...(this.extras.patterns??[]).map(e=>e.schema),...this.extras.rest?[this.extras.rest]:[]];this._extraValue=e.length===0?null:e.length===1?e[0]:new wf(e)}return this._extraValue??void 0}compile(e){let t=e.profile,n=t.optional===`null`,r=t.audience!==`people`,i=[],a=new Set;for(let[t,n]of Object.entries(this.shape)){let o=r?n.meta.forModels:void 0,s=o?o.meta.description===void 0&&n.meta.description!==void 0?o.describe(n.meta.description):o:n;if(r&&n.meta.audience===`people`){a.add(t);continue}let c=s instanceof Nf?s:void 0,l=s instanceof Pf||!!c,u=s instanceof Pf?s.inner:c?c.inner:s;if(l&&jf(u,e.env)){a.add(t);continue}let d=l?e.guarded(u,s):e.compile(u);i.push({key:t,optional:l,node:d,nullable:u instanceof Ff,...u instanceof Of?{dep:u}:{},...c?{dflt:c}:{}})}let o=i.filter(e=>!e.dep),s=i.filter(e=>e.dep),c=new Set(Object.keys(this.shape)),l=this.extraValue(),u=(this.extras.patterns??[]).map(t=>({re:new RegExp(t.pattern),pattern:t.pattern,node:e.guarded(t.schema)})),d=this.extras.rest?e.guarded(this.extras.rest):void 0,f=l?t.records===`pairs`?`pairs`:t.patternProperties?`keywords`:`open`:`none`,p=f===`pairs`?c.has(`extra`)?`_extra`:`extra`:``,m=l&&f!==`keywords`?e.guarded(l):void 0,h=e=>u.find(t=>t.re.test(e))?.node??d;return e.node({own:n&&i.some(e=>e.optional&&!e.nullable)||a.size>0||f===`pairs`||i.some(e=>e.dflt),deps:[...i.map(e=>e.node),...u.map(e=>e.node),...d?[d]:[],...m?[m]:[]],hint:()=>this.hintOf(f===`pairs`?[`Other keys go in "${p}" as a list of {key, value} entries.`]:f===`open`&&u.length?[`Other keys: ${u.map(t=>`keys matching /${t.pattern}/ hold ${t.node.schema?.print(new Dd(e.env))??`a value`}`).join(`; `)}${d?`; any other key holds the rest`:``}.`]:[]),emit:()=>{let r={},a=[];for(let t of i){let i=t.node.json();t.dep&&(i={...i,description:[i.description,`Its type is given by "${t.dep.on}".`].filter(Boolean).join(`
|
|
66
66
|
`)}),t.dflt&&(i={...i,description:[i.description,`Default when left out: ${JSON.stringify(t.node.encode(t.dflt.value))}.`].filter(Boolean).join(`
|
|
67
67
|
`)}),t.optional&&n&&(i=e.nullable(i),i.description=[i.description,`Write null to leave it out.`].filter(Boolean).join(`
|
|
68
|
-
`)),r[t.key]=i,(!t.optional||n)&&a.push(t.key)}f===`pairs`&&(r[p]={type:`array`,items:e.object({key:{type:`string`},value:m.json()},[`key`,`value`],!0)},n&&a.push(p));let o=e.object(r,a,this.closed||t.closedObjects);return f===`keywords`?(u.length&&(o.patternProperties=Object.fromEntries(u.map(e=>[e.pattern,e.node.json()]))),d&&(o.additionalProperties=d.json())):f===`open`&&(o.additionalProperties=m.json()),o},run:(t,r)=>{let i=Yf(t,r,`object`);if(!Mf(i))return If(r,i,`Expected an object, got ${Nf(i)}.`);let u=i,d=u;for(let e=0;e<o.length;e++){let t=o[e],i=Object.prototype.hasOwnProperty.call(u,t.key)?u[t.key]:void 0;if(i===void 0){t.dflt?r.dry||(d=Zf(d,u,t.key,t.dflt.fresh(r.stats),r)):t.optional||(r.enter(t.key),r.fail(`Required.`,`required`,void 0,()=>Object.keys(u).filter(e=>!c.has(e)),t.node),r.leave());continue}if(i===null&&t.optional&&n&&!t.nullable){r.dry||(d=t.dflt?Zf(d,u,t.key,t.dflt.fresh(r.stats),r):Qf(d,u,t.key,r));continue}r.enter(t.key);let a=t.node.run(i,r);r.leave(),a!==i&&!r.dry&&(d=Zf(d,u,t.key,a,r))}for(let t=0;t<s.length;t++){let i=s[t],a=u[i.key];if(a===void 0||a===null&&i.optional&&n){a===null&&!r.dry?d=Qf(d,u,i.key,r):i.optional||(r.enter(i.key),r.fail(`Required.`,`required`,void 0,()=>Object.keys(u).filter(e=>!c.has(e)),i.node),r.leave());continue}r.enter(i.key);let o=r.errors.length,l=i.node.run(a,r);if(r.errors.length===o){let t=i.dep.schemaFor(d[i.dep.on]);t&&(l=e.lenient().nodeFor(t).run(l,r))}r.leave(),l!==a&&!r.dry&&(d=Zf(d,u,i.key,l,r))}if(a.size)for(let e of a)Object.prototype.hasOwnProperty.call(u,e)&&(r.enter(e),r.fail(`Not allowed.`,`not-allowed`),r.leave());if(f===`pairs`){let e=u[p];if(e!=null){r.enter(p,null);let t=Yf(e,r,`array`);if(!Array.isArray(t))If(r,t,`Expected a list of {key, value} entries.`);else{r.dry||(d=Qf(d,u,p,r));for(let e=0;e<t.length;e++){let n=t[e];if(r.enter(e,null),!Mf(n)||typeof n.key!=`string`){r.fail(`Expected a {key, value} entry with a string key.`,`type`),r.leave(!1);continue}let i=n.key;if(c.has(i)||Object.prototype.hasOwnProperty.call(d,i)){r.enter(`key`,null),r.fail(`Duplicate key "${i}".`,`rule`),r.leave(!1),r.leave(!1);continue}let a=h(i);r.enter(`value`,i);let o=a?a.run(n.value,r):this.closed?If(r,n.value,`Key "${i}" is not allowed.`,`not-allowed`):n.value;r.leave(),r.dry||(d=Zf(d,u,i,o,r)),r.leave(!1)}}r.leave(!1)}else p&&e===null&&!r.dry&&(d=Qf(d,u,p,r))}else if(l||this.closed){let e=Object.keys(u);for(let t=0;t<e.length;t++){let n=e[t];if(c.has(n))continue;let i=l?h(n):void 0;if(i){r.enter(n);let e=i.run(u[n],r);r.leave(),e!==u[n]&&!r.dry&&(d=Zf(d,u,n,e,r))}else this.closed&&(r.enter(n),r.fail(`Unknown field "${n}".`,`unknown-key`,n,()=>[...c].filter(e=>!Object.prototype.hasOwnProperty.call(u,e))),r.leave())}}return d},encode:(e,t)=>{let r=e,o={};t.objects++;let s=[];for(let e of Object.keys(r)){if(a.has(e)||c.has(e))continue;let n=h(e),i=n?n.encode(r[e],t):r[e];f===`pairs`?s.push({key:e,value:i}):o[e]=i}for(let e of i){let i=r[e.key];i===void 0?e.optional&&n&&(o[e.key]=null):o[e.key]=e.node.encode(i,t)}return f===`pairs`&&(s.length||n)&&(t.arrays++,t.objects+=s.length,o[p]=s),o},child:e=>i.find(t=>t.key===e)?.node??(typeof e==`string`?h(e):void 0)})}},gf=class extends $d{constructor(e,t){super(),this.value=e,this.key=t}value;key;kind=`record`;children(){return this.key?[this.key,this.value]:[this.value]}print(e){return`{ [key: ${this.key?e.print(this.key):`string`}]: ${e.print(this.value)} }`}compile(e){let t=e.guarded(this.value),n=e.compile(this.key??_f),r=e.profile.records===`pairs`;return e.node({own:r,deps:[t,n],hint:e=>this.hintOf(r?[`A map written as ${e.recordWord}; each key at most once.`]:[]),emit:()=>{if(r)return{type:`array`,items:e.object({key:n.json(),value:t.json()},[`key`,`value`],!0)};let i={type:`object`,additionalProperties:t.json()};return this.key&&!e.profile.closedObjects&&!(this.key instanceof rf&&!Object.keys(this.key.options).length)&&(i.propertyNames=n.json()),i},run:(i,a)=>{if(r){let r=Yf(i,a,`array`);if(!Array.isArray(r)){let t=a.repair?Yf(i,a,`object`):i;if(a.repair&&!a.dry&&Mf(t)){t===i&&a.stats.repaired++;let r=t,o=e.lenient().nodeFor(this.value),s=r;for(let e of Object.keys(r)){a.enter(e),n.run(e,a);let t=o.run(r[e],a);a.leave(),t!==r[e]&&!a.dry&&(s=Zf(s,r,e,t,a))}return s}return If(a,r,`Expected a list of {key, value} entries, got ${Nf(r)}.`)}let o={};a.dry||a.stats.objects++;for(let e=0;e<r.length;e++){let i=r[e];if(a.enter(e,null),!Mf(i)){If(a,i,`Expected a {key, value} entry.`),a.leave(!1);continue}let s=i.key;a.enter(`key`,null),s===void 0?a.fail(`Required.`,`required`,void 0,()=>Object.keys(i).filter(e=>e!==`key`&&e!==`value`),n):n.run(s,a),a.leave(!1),typeof s==`string`&&(Object.prototype.hasOwnProperty.call(o,s)&&(a.enter(`key`,null),a.fail(`Duplicate key "${s}".`,`rule`),a.leave(!1)),a.enter(`value`,s),o[s]=t.run(i.value,a),a.leave()),a.leave(!1)}return a.dry?r:o}let o=Yf(i,a,`object`);if(!Mf(o))return If(a,o,`Expected an object, got ${Nf(o)}.`);let s=o,c=s;for(let e of Object.keys(s)){this.key&&(a.enter(e),n.run(e,a),a.leave()),a.enter(e);let r=t.run(s[e],a);a.leave(),r!==s[e]&&!a.dry&&(c=Zf(c,s,e,r,a))}return c},encode:(e,n)=>{let i=e;if(r){let e=Object.keys(i);return n.arrays++,n.objects+=e.length,e.map(e=>({key:e,value:t.encode(i[e],n)}))}let a=i;for(let e of Object.keys(i)){let r=t.encode(i[e],n);r!==i[e]&&(a===i&&(a={...i},n.objects++),a[e]=r)}return a},child:()=>t})}},_f=new rf,vf=class extends $d{constructor(e,t){super(),this.options=e,this.tag=t}options;tag;kind=`union`;children(){return this.options}print(e){return this.options.map(t=>e.print(t)).join(` | `)}tagIndex(e,t){let n=this.tag??Uf(this.options,e);if(!n)return;let r=new Map,i=[];return this.options.forEach((a,o)=>{let s=t.has(o)?void 0:zf(a,n,e);if(s)for(let e of s)r.has(e)||r.set(e,o);else i.push(o)}),{tag:n,byTag:r,fallback:i}}label(e,t){let n=this.tag?Kf(this.options[e],t).shape?.[this.tag]:void 0;return n instanceof cf&&typeof n.value==`string`?n.value:`option${e+1}`}compile(e){if(this.options.some(t=>Tf(t,e.env))){let t=this.options.filter(t=>!Tf(t,e.env));return t.length?this.with({options:t}).compile(e):Ef(e,()=>this.ruleHint())}let t=e.profile.unions===`tagged`,n=new Set,r=this.options.map(t=>e.compile(t));if(r.length>1&&r.every(e=>e.jsonText))return e.escape(this,`Nested too deep for this model to describe directly.`);let i=t=>Kf(t,e.env)?.kind,a=this.options.some(t=>i(t)===`array`||i(t)===`tuple`&&e.profile.tuples!==`object`),o=r.map((r,o,s)=>t||s.length<2?r:r.jsonText?(n.add(o),Gf(e,r)):a&&e.profile.records===`pairs`&&i(this.options[o])===`record`?(n.add(o),Gf(e,r,`entries`)):r),s=this.tagIndex(e.env,n),c=s?.byTag,l=s?.tag,u=this.options.map((t,n)=>this.label(n,e.env)),d=t=>Kf(this.options[t],e.env)instanceof sf,f=(t,n)=>{if(c&&Mf(t)){let r=c.get(t[l]);if(r!==void 0){let i=new Set(Vf(this.options[r],e.env));if(e.profile.closedObjects&&i.size&&s.fallback.length&&Object.keys(t).some(e=>!i.has(e)))for(let e of s.fallback){let r=n.dryRun();if(o[e].run(t,r),!r.errors.length)return e}return r}}let r=!Mf(t)||t[l]===void 0;for(let e of s&&!r?s.fallback:o.keys()){let r=n.dryRun();if(o[e].run(t,r),!r.errors.length)return e}return-1},p=()=>new wd(e.env);return e.node({own:t,deps:o,hint:()=>this.hintOf(t?[`Fill exactly one of these fields and set the others to null.`]:[]),emit:()=>{if(t){let t={};return o.forEach((n,r)=>t[u[r]]=e.nullable(d(r)?{type:`boolean`,enum:[!0],description:`true for null`}:n.json())),e.object(t,u)}return{anyOf:o.map(e=>e.json())}},run:(n,r)=>{if(t){if(!Mf(n))return If(r,n,`Expected an object with one of: ${u.join(`, `)}.`);let e=u.filter(e=>n[e]!=null);if(e.length!==1)return If(r,n,`Fill exactly one of: ${u.join(`, `)} (got ${e.length}).`,`union`);let t=u.indexOf(e[0]);if(d(t))return n[e[0]]===!0?null:If(r,n,`Set ${e[0]} to true for null.`,`literal`);r.enter(e[0],null);let i=o[t].run(n[e[0]],r);return r.leave(!1),i}let i=f(n,r);if(i<0){if(c&&!s.fallback.length&&Mf(n)&&n[l]!==void 0){r.enter(l);let e=n[l];return r.fail(`Expected ${l} to be one of: ${Lf([...c.keys()].map(e=>JSON.stringify(e)))}.`,`tag`,e,()=>[...c.keys()].filter(e=>typeof e==`string`)),r.leave(),n}let t=Wf(this.options,n,e.env);return t>=0?o[t].run(n,r):If(r,n,`Did not match any of: ${Rf(this.options.map(e=>e.print(p())).join(` | `),300)}.`,`union`,typeof n==`string`?()=>Bf(this.options,e.env):void 0)}return o[i].run(n,r)},encode:(n,r)=>{let i=this.optionOf(n,e,c,l);if(i<0)return n;let a=d(i)&&t?!0:o[i].encode(n,r);return t?(r.objects++,Object.fromEntries(u.map((e,t)=>[e,t===i?a:null]))):a},child:t=>{let n=o.map(e=>e.child(t)).filter(e=>!!e);if(n.length<=1)return n[0];let r=t=>n.find(n=>!n.schema||qf(e,n.schema,t))??n[0],i=e.node({deps:n,emit:()=>({anyOf:n.map(e=>e.json())}),run:(e,t)=>r(e).run(e,t),encode:(e,t)=>r(e).encode(e,t),child:e=>n[0].child(e)});return i.needs=n.some(e=>e.needs),i}})}optionOf(e,t,n,r){if(n&&Mf(e)){let t=n.get(e[r]);if(t!==void 0)return t}let i=t.lenient();return this.options.findIndex(t=>{let n=new Sd(!1,!0,hd(),!1,!0);return i.nodeFor(t).run(e,n),n.errors.length===0})}},yf=class extends $d{constructor(e){super(),this.members=e}members;kind=`intersection`;children(){return this.members}print(e){return this.members.map(t=>e.print(t)).join(` & `)}mergedByEnv=new WeakMap;merged(e){let t=this.mergedByEnv.get(e);if(t===void 0){let n=this.members.map(t=>Kf(t,e));if(n.every(e=>e instanceof hf)){let e=n,r={};for(let t of e)Object.assign(r,t.shape);let i=e.map(e=>e.extras.rest).filter(Boolean).at(-1),a=e.flatMap(e=>e.extras.patterns??[]);t=new hf(r,e.some(e=>e.closed),{...i?{rest:i}:{},...a.length?{patterns:a}:{}}).with({checks:[...e.flatMap(e=>e.checks),...this.checks],meta:this.meta})}else t=null;this.mergedByEnv.set(e,t)}return t??void 0}compile(e){let t=this.merged(e.env);if(t){let n=e.compile(t);return e.node({deps:[n],emit:()=>n.json(),run:(e,t)=>n.run(e,t),encode:(e,t)=>n.encode(e,t),child:e=>n.child(e)})}let n=this.members.map(t=>e.compile(t)),r=this.members.slice(1),i=()=>e.profile.allOf&&n.every(e=>!e.needs);return e.node({deps:n,hint:()=>this.hintOf(i()?[]:[`Must also be: ${r.map(t=>t.print(new wd(e.env))).join(` & `)}.`]),emit:()=>i()?{allOf:n.map(e=>e.json())}:n[0].json(),run:(t,i)=>{let a=i.errors.length,o=n[0].run(t,i);if(i.errors.length!==a)return o;let s=e.lenient();for(let e of r){let t=i.dryRun(!0);s.nodeFor(e).run(o,t);for(let e of t.errors)i.errors.push(e)}return o},encode:(e,t)=>n[0].encode(e,t),child:e=>n[0].child(e)})}},bf=class extends $d{constructor(e,t){super(),this.excluded=e,this.base=t}excluded;base;kind=`not`;children(){return[this.base,this.excluded]}print(e){return e.print(this.base)}compile(e){let t=e.compile(this.base),n=()=>e.profile.conditionals?[]:[`Must not be: ${this.excluded.print(new wd(e.env))}.`];return e.node({deps:[t],hint:()=>this.hintOf(n()),emit:()=>e.profile.conditionals?{...t.json(),not:e.lenient().nodeFor(this.excluded).json()}:t.json(),run:(n,r)=>{let i=r.errors.length,a=t.run(n,r);return r.errors.length===i&&qf(e,this.excluded,a)&&r.fail(`Must not be: ${this.excluded.print(new wd(e.env))}.`,`rule`),a},encode:(e,n)=>t.encode(e,n),child:e=>t.child(e)})}},xf=class extends $d{constructor(e,t,n,r){super(),this.base=e,this.when=t,this.then=n,this.otherwise=r}base;when;then;otherwise;kind=`conditional`;children(){return[this.base,this.when,...this.then?[this.then]:[],...this.otherwise?[this.otherwise]:[]]}print(e){return e.print(this.base)}compile(e){let t=e.compile(this.base),n=t=>t.print(new wd(e.env)),r=[this.then?`If it is ${n(this.when)}, it must also be ${n(this.then)}.`:``,this.otherwise?`${this.then?`Otherwise`:`If it is not ${n(this.when)}`}, it must be ${n(this.otherwise)}.`:``].filter(Boolean).join(` `);return e.node({deps:[t],hint:()=>this.hintOf(e.profile.conditionals?[]:[r]),emit:()=>{if(!e.profile.conditionals)return t.json();let n=e.lenient();return{...t.json(),if:n.nodeFor(this.when).json(),...this.then?{then:n.nodeFor(this.then).json()}:{},...this.otherwise?{else:n.nodeFor(this.otherwise).json()}:{}}},run:(n,i)=>{let a=i.errors.length,o=t.run(n,i);if(i.errors.length!==a)return o;let s=qf(e,this.when,o)?this.then:this.otherwise;return s&&!qf(e,s,o)&&i.fail(r,`rule`),o},encode:(e,n)=>t.encode(e,n),child:e=>t.child(e)})}},Sf=class extends $d{constructor(e,t,n=new uf){super(),this.on=e,this.schemaFor=t,this.base=n}on;schemaFor;base;kind=`dependent`;children(){return[this.base]}print(e){return e.print(this.base)}compile(e){let t=e.compile(this.base);return e.node({deps:[t],hint:()=>this.ruleHint(),emit:()=>t.json(),run:(e,n)=>t.run(e,n),encode:(e,n)=>t.encode(e,n)})}},Cf=class extends $d{constructor(e,t=`tool`,n=`args`){super(),this.cases=e,this.tagKey=t,this.argsKey=n}cases;tagKey;argsKey;kind=`dispatch`;children(){return this.cases.map(e=>e.schema)}print(e){return this.cases.map(t=>`{ ${this.tagKey}: ${JSON.stringify(t.name)}; ${this.argsKey}: ${e.print(t.schema)} }`).join(` | `)}compile(e){let t=this.cases.map(e=>e.name),n=new Map(t.map((e,t)=>[e,t])),r=this.cases.map(t=>e.compile(t.schema)),i=e.compile(new lf(t)),a=e.profile.unions===`tagged`,{tagKey:o,argsKey:s}=this,c=this.cases.map(e=>`- ${e.name}${e.description?`: ${e.description}`:``}`).join(`
|
|
68
|
+
`)),r[t.key]=i,(!t.optional||n)&&a.push(t.key)}f===`pairs`&&(r[p]={type:`array`,items:e.object({key:{type:`string`},value:m.json()},[`key`,`value`],!0)},n&&a.push(p));let o=e.object(r,a,this.closed||t.closedObjects);return f===`keywords`?(u.length&&(o.patternProperties=Object.fromEntries(u.map(e=>[e.pattern,e.node.json()]))),d&&(o.additionalProperties=d.json())):f===`open`&&(o.additionalProperties=m.json()),o},run:(t,r)=>{let i=tp(t,r,`object`);if(!Rf(i))return Hf(r,i,`Expected an object, got ${zf(i)}.`);let u=i,d=u;for(let e=0;e<o.length;e++){let t=o[e],i=Object.prototype.hasOwnProperty.call(u,t.key)?u[t.key]:void 0;if(i===void 0){t.dflt?r.dry||(d=rp(d,u,t.key,t.dflt.fresh(r.stats),r)):t.optional||(r.enter(t.key),r.fail(`Required.`,`required`,void 0,()=>Object.keys(u).filter(e=>!c.has(e)),t.node),r.leave());continue}if(i===null&&t.optional&&n&&!t.nullable){r.dry||(d=t.dflt?rp(d,u,t.key,t.dflt.fresh(r.stats),r):ip(d,u,t.key,r));continue}r.enter(t.key);let a=t.node.run(i,r);r.leave(),a!==i&&!r.dry&&(d=rp(d,u,t.key,a,r))}for(let t=0;t<s.length;t++){let i=s[t],a=u[i.key];if(a===void 0||a===null&&i.optional&&n){a===null&&!r.dry?d=ip(d,u,i.key,r):i.optional||(r.enter(i.key),r.fail(`Required.`,`required`,void 0,()=>Object.keys(u).filter(e=>!c.has(e)),i.node),r.leave());continue}r.enter(i.key);let o=r.errors.length,l=i.node.run(a,r);if(r.errors.length===o){let t=i.dep.schemaFor(d[i.dep.on]);t&&(l=e.lenient().nodeFor(t).run(l,r))}r.leave(),l!==a&&!r.dry&&(d=rp(d,u,i.key,l,r))}if(a.size)for(let e of a)Object.prototype.hasOwnProperty.call(u,e)&&(r.enter(e),r.fail(`Not allowed.`,`not-allowed`),r.leave());if(f===`pairs`){let e=u[p];if(e!=null){r.enter(p,null);let t=tp(e,r,`array`);if(!Array.isArray(t))Hf(r,t,`Expected a list of {key, value} entries.`);else{r.dry||(d=ip(d,u,p,r));for(let e=0;e<t.length;e++){let n=t[e];if(r.enter(e,null),!Rf(n)||typeof n.key!=`string`){r.fail(`Expected a {key, value} entry with a string key.`,`type`),r.leave(!1);continue}let i=n.key;if(c.has(i)||Object.prototype.hasOwnProperty.call(d,i)){r.enter(`key`,null),r.fail(`Duplicate key "${i}".`,`rule`),r.leave(!1),r.leave(!1);continue}let a=h(i);r.enter(`value`,i);let o=a?a.run(n.value,r):this.closed?Hf(r,n.value,`Key "${i}" is not allowed.`,`not-allowed`):n.value;r.leave(),r.dry||(d=rp(d,u,i,o,r)),r.leave(!1)}}r.leave(!1)}else p&&e===null&&!r.dry&&(d=ip(d,u,p,r))}else if(l||this.closed){let e=Object.keys(u);for(let t=0;t<e.length;t++){let n=e[t];if(c.has(n))continue;let i=l?h(n):void 0;if(i){r.enter(n);let e=i.run(u[n],r);r.leave(),e!==u[n]&&!r.dry&&(d=rp(d,u,n,e,r))}else this.closed&&(r.enter(n),r.fail(`Unknown field "${n}".`,`unknown-key`,n,()=>[...c].filter(e=>!Object.prototype.hasOwnProperty.call(u,e))),r.leave())}}return d},encode:(e,t)=>{let r=e,o={};t.objects++;let s=[];for(let e of Object.keys(r)){if(a.has(e)||c.has(e))continue;let n=h(e),i=n?n.encode(r[e],t):r[e];f===`pairs`?s.push({key:e,value:i}):o[e]=i}for(let e of i){let i=r[e.key];i===void 0?e.optional&&n&&(o[e.key]=null):o[e.key]=e.node.encode(i,t)}return f===`pairs`&&(s.length||n)&&(t.arrays++,t.objects+=s.length,o[p]=s),o},child:e=>i.find(t=>t.key===e)?.node??(typeof e==`string`?h(e):void 0)})}},Sf=class extends of{constructor(e,t){super(),this.value=e,this.key=t}value;key;kind=`record`;children(){return this.key?[this.key,this.value]:[this.value]}print(e){return`{ [key: ${this.key?e.print(this.key):`string`}]: ${e.print(this.value)} }`}compile(e){let t=e.guarded(this.value),n=e.compile(this.key??Cf),r=e.profile.records===`pairs`;return e.node({own:r,deps:[t,n],hint:e=>this.hintOf(r?[`A map written as ${e.recordWord}; each key at most once.`]:[]),emit:()=>{if(r)return{type:`array`,items:e.object({key:n.json(),value:t.json()},[`key`,`value`],e.profile.closedObjects)};let i={type:`object`,additionalProperties:t.json()};return this.key&&!e.profile.closedObjects&&!(this.key instanceof uf&&!Object.keys(this.key.options).length)&&(i.propertyNames=n.json()),i},run:(i,a)=>{if(r){let r=tp(i,a,`array`);if(!Array.isArray(r)){let t=a.repair?tp(i,a,`object`):i;if(a.repair&&!a.dry&&Rf(t)){t===i&&a.stats.repaired++;let r=t,o=e.lenient().nodeFor(this.value),s=r;for(let e of Object.keys(r)){a.enter(e),n.run(e,a);let t=o.run(r[e],a);a.leave(),t!==r[e]&&!a.dry&&(s=rp(s,r,e,t,a))}return s}return Hf(a,r,`Expected a list of {key, value} entries, got ${zf(r)}.`)}let o={};a.dry||a.stats.objects++;for(let e=0;e<r.length;e++){let i=r[e];if(a.enter(e,null),!Rf(i)){Hf(a,i,`Expected a {key, value} entry.`),a.leave(!1);continue}let s=i.key;a.enter(`key`,null),s===void 0?a.fail(`Required.`,`required`,void 0,()=>Object.keys(i).filter(e=>e!==`key`&&e!==`value`),n):n.run(s,a),a.leave(!1),typeof s==`string`&&(Object.prototype.hasOwnProperty.call(o,s)&&(a.enter(`key`,null),a.fail(`Duplicate key "${s}".`,`rule`),a.leave(!1)),a.enter(`value`,s),o[s]=t.run(i.value,a),a.leave()),a.leave(!1)}return a.dry?r:o}let o=tp(i,a,`object`);if(!Rf(o))return Hf(a,o,`Expected an object, got ${zf(o)}.`);let s=o,c=s;for(let e of Object.keys(s)){this.key&&(a.enter(e),n.run(e,a),a.leave()),a.enter(e);let r=t.run(s[e],a);a.leave(),r!==s[e]&&!a.dry&&(c=rp(c,s,e,r,a))}return c},encode:(e,n)=>{let i=e;if(r){let e=Object.keys(i);return n.arrays++,n.objects+=e.length,e.map(e=>({key:e,value:t.encode(i[e],n)}))}let a=i;for(let e of Object.keys(i)){let r=t.encode(i[e],n);r!==i[e]&&(a===i&&(a={...i},n.objects++),a[e]=r)}return a},child:()=>t})}},Cf=new uf,wf=class extends of{constructor(e,t){super(),this.options=e,this.tag=t}options;tag;kind=`union`;children(){return this.options}print(e){return this.options.map(t=>e.print(t)).join(` | `)}tagIndex(e,t){let n=this.tag??Yf(this.options,e);if(!n)return;let r=new Map,i=[];return this.options.forEach((a,o)=>{let s=t.has(o)?void 0:Gf(a,n,e);if(s)for(let e of s)r.has(e)||r.set(e,o);else i.push(o)}),{tag:n,byTag:r,fallback:i}}label(e,t){let n=this.tag?Qf(this.options[e],t).shape?.[this.tag]:void 0;return n instanceof mf&&typeof n.value==`string`?n.value:`option${e+1}`}compile(e){if(this.options.some(t=>jf(t,e.env))){let t=this.options.filter(t=>!jf(t,e.env));return t.length?this.with({options:t}).compile(e):Mf(e,()=>this.ruleHint())}let t=e.profile.unions===`tagged`,n=new Set,r=this.options.map(t=>e.compile(t));if(r.length>1&&r.every(e=>e.jsonText))return e.escape(this,`Nested too deep for this model to describe directly.`);let i=t=>Qf(t,e.env)?.kind,a=this.options.some(t=>i(t)===`array`||i(t)===`tuple`&&e.profile.tuples!==`object`),o=r.map((r,o,s)=>t||s.length<2?r:r.jsonText?(n.add(o),Zf(e,r)):a&&e.profile.records===`pairs`&&i(this.options[o])===`record`?(n.add(o),Zf(e,r,`entries`)):r),s=this.tagIndex(e.env,n),c=s?.byTag,l=s?.tag,u=this.options.map((t,n)=>this.label(n,e.env)),d=t=>Qf(this.options[t],e.env)instanceof pf,f=(t,n)=>{if(c&&Rf(t)){let r=c.get(t[l]);if(r!==void 0){let i=new Set(qf(this.options[r],e.env));if(e.profile.closedObjects&&i.size&&s.fallback.length&&Object.keys(t).some(e=>!i.has(e)))for(let e of s.fallback){let r=n.dryRun();if(o[e].run(t,r),!r.errors.length)return e}return r}}let r=!Rf(t)||t[l]===void 0;for(let e of s&&!r?s.fallback:o.keys()){let r=n.dryRun();if(o[e].run(t,r),!r.errors.length)return e}return-1},p=()=>new Dd(e.env);return e.node({own:t,deps:o,hint:()=>this.hintOf(t?[`Fill exactly one of these fields and set the others to null.`]:[]),emit:()=>{if(t){let t={};return o.forEach((n,r)=>t[u[r]]=e.nullable(d(r)?{type:`boolean`,enum:[!0],description:`true for null`}:n.json())),e.object(t,u)}return{anyOf:o.map(e=>e.json())}},run:(n,r)=>{if(t){if(!Rf(n))return Hf(r,n,`Expected an object with one of: ${u.join(`, `)}.`);let e=u.filter(e=>n[e]!=null);if(e.length!==1)return Hf(r,n,`Fill exactly one of: ${u.join(`, `)} (got ${e.length}).`,`union`);let t=u.indexOf(e[0]);if(d(t))return n[e[0]]===!0?null:Hf(r,n,`Set ${e[0]} to true for null.`,`literal`);r.enter(e[0],null);let i=o[t].run(n[e[0]],r);return r.leave(!1),i}let i=f(n,r);if(i<0){if(c&&!s.fallback.length&&Rf(n)&&n[l]!==void 0){r.enter(l);let e=n[l];return r.fail(`Expected ${l} to be one of: ${Uf([...c.keys()].map(e=>JSON.stringify(e)))}.`,`tag`,e,()=>[...c.keys()].filter(e=>typeof e==`string`)),r.leave(),n}let t=Xf(this.options,n,e.env);return t>=0?o[t].run(n,r):Hf(r,n,`Did not match any of: ${Wf(this.options.map(e=>e.print(p())).join(` | `),300)}.`,`union`,typeof n==`string`?()=>Kf(this.options,e.env):void 0)}return o[i].run(n,r)},encode:(n,r)=>{let i=this.optionOf(n,e,c,l);if(i<0)return n;let a=d(i)&&t?!0:o[i].encode(n,r);return t?(r.objects++,Object.fromEntries(u.map((e,t)=>[e,t===i?a:null]))):a},child:t=>{let n=o.map(e=>e.child(t)).filter(e=>!!e);if(n.length<=1)return n[0];let r=t=>n.find(n=>!n.schema||$f(e,n.schema,t))??n[0],i=e.node({deps:n,emit:()=>({anyOf:n.map(e=>e.json())}),run:(e,t)=>r(e).run(e,t),encode:(e,t)=>r(e).encode(e,t),child:e=>n[0].child(e)});return i.needs=n.some(e=>e.needs),i}})}optionOf(e,t,n,r){if(n&&Rf(e)){let t=n.get(e[r]);if(t!==void 0)return t}let i=t.lenient();return this.options.findIndex(t=>{let n=new Td(!1,!0,vd(),!1,!0);return i.nodeFor(t).run(e,n),n.errors.length===0})}},Tf=class extends of{constructor(e){super(),this.members=e}members;kind=`intersection`;children(){return this.members}print(e){return this.members.map(t=>e.print(t)).join(` & `)}mergedByEnv=new WeakMap;merged(e){let t=this.mergedByEnv.get(e);if(t===void 0){let n=this.members.map(t=>Qf(t,e));if(n.every(e=>e instanceof xf)){let e=n,r={};for(let t of e)Object.assign(r,t.shape);let i=e.map(e=>e.extras.rest).filter(Boolean).at(-1),a=e.flatMap(e=>e.extras.patterns??[]);t=new xf(r,e.some(e=>e.closed),{...i?{rest:i}:{},...a.length?{patterns:a}:{}}).with({checks:[...e.flatMap(e=>e.checks),...this.checks],meta:this.meta})}else t=null;this.mergedByEnv.set(e,t)}return t??void 0}compile(e){let t=this.merged(e.env);if(t){let n=e.compile(t);return e.node({deps:[n],emit:()=>n.json(),run:(e,t)=>n.run(e,t),encode:(e,t)=>n.encode(e,t),child:e=>n.child(e)})}let n=this.members.map(t=>e.compile(t)),r=this.members.slice(1),i=()=>e.profile.allOf&&n.every(e=>!e.needs);return e.node({deps:n,hint:()=>this.hintOf(i()?[]:[`Must also be: ${r.map(t=>t.print(new Dd(e.env))).join(` & `)}.`]),emit:()=>i()?{allOf:n.map(e=>e.json())}:n[0].json(),run:(t,i)=>{let a=i.errors.length,o=n[0].run(t,i);if(i.errors.length!==a)return o;let s=e.lenient();for(let e of r){let t=i.dryRun(!0);s.nodeFor(e).run(o,t);for(let e of t.errors)i.errors.push(e)}return o},encode:(e,t)=>n[0].encode(e,t),child:e=>n[0].child(e)})}},Ef=class extends of{constructor(e,t){super(),this.excluded=e,this.base=t}excluded;base;kind=`not`;children(){return[this.base,this.excluded]}print(e){return e.print(this.base)}compile(e){let t=e.compile(this.base),n=()=>e.profile.conditionals?[]:[`Must not be: ${this.excluded.print(new Dd(e.env))}.`];return e.node({deps:[t],hint:()=>this.hintOf(n()),emit:()=>e.profile.conditionals?{...t.json(),not:e.lenient().nodeFor(this.excluded).json()}:t.json(),run:(n,r)=>{let i=r.errors.length,a=t.run(n,r);return r.errors.length===i&&$f(e,this.excluded,a)&&r.fail(`Must not be: ${this.excluded.print(new Dd(e.env))}.`,`rule`),a},encode:(e,n)=>t.encode(e,n),child:e=>t.child(e)})}},Df=class extends of{constructor(e,t,n,r){super(),this.base=e,this.when=t,this.then=n,this.otherwise=r}base;when;then;otherwise;kind=`conditional`;children(){return[this.base,this.when,...this.then?[this.then]:[],...this.otherwise?[this.otherwise]:[]]}print(e){return e.print(this.base)}compile(e){let t=e.compile(this.base),n=t=>t.print(new Dd(e.env)),r=[this.then?`If it is ${n(this.when)}, it must also be ${n(this.then)}.`:``,this.otherwise?`${this.then?`Otherwise`:`If it is not ${n(this.when)}`}, it must be ${n(this.otherwise)}.`:``].filter(Boolean).join(` `);return e.node({deps:[t],hint:()=>this.hintOf(e.profile.conditionals?[]:[r]),emit:()=>{if(!e.profile.conditionals)return t.json();let n=e.lenient();return{...t.json(),if:n.nodeFor(this.when).json(),...this.then?{then:n.nodeFor(this.then).json()}:{},...this.otherwise?{else:n.nodeFor(this.otherwise).json()}:{}}},run:(n,i)=>{let a=i.errors.length,o=t.run(n,i);if(i.errors.length!==a)return o;let s=$f(e,this.when,o)?this.then:this.otherwise;return s&&!$f(e,s,o)&&i.fail(r,`rule`),o},encode:(e,n)=>t.encode(e,n),child:e=>t.child(e)})}},Of=class extends of{constructor(e,t,n=new gf){super(),this.on=e,this.schemaFor=t,this.base=n}on;schemaFor;base;kind=`dependent`;children(){return[this.base]}print(e){return e.print(this.base)}compile(e){let t=e.compile(this.base);return e.node({deps:[t],hint:()=>this.ruleHint(),emit:()=>t.json(),run:(e,n)=>t.run(e,n),encode:(e,n)=>t.encode(e,n)})}},kf=class extends of{constructor(e,t=`tool`,n=`args`){super(),this.cases=e,this.tagKey=t,this.argsKey=n}cases;tagKey;argsKey;kind=`dispatch`;children(){return this.cases.map(e=>e.schema)}print(e){return this.cases.map(t=>`{ ${this.tagKey}: ${JSON.stringify(t.name)}; ${this.argsKey}: ${e.print(t.schema)} }`).join(` | `)}compile(e){let t=this.cases.map(e=>e.name),n=new Map(t.map((e,t)=>[e,t])),r=this.cases.map(t=>e.compile(t.schema)),i=e.compile(new hf(t)),a=e.profile.unions===`tagged`,{tagKey:o,argsKey:s}=this,c=this.cases.map(e=>`- ${e.name}${e.description?`: ${e.description}`:``}`).join(`
|
|
69
69
|
`);return e.node({own:!0,deps:[i,...r],hint:()=>this.hintOf([`Set "${o}" to the tool to run and "${s}" to its arguments.`]),emit:()=>{let n={...i.json(),description:[i.json().description,`The tool to run:
|
|
70
70
|
${c}`].filter(Boolean).join(`
|
|
71
|
-
`)},l;if(a){let n={};t.forEach((t,i)=>n[t]=e.nullable(r[i].json())),l={...e.object(n,t),description:`Fill only the field named by "${o}"; set the others to null.`}}else l=r.length===1?r[0].json():{anyOf:r.map(e=>e.json())};return e.object({[o]:n,[s]:l},[o,s])},run:(e,i)=>{let c=Yf(e,i,`object`);if(!Mf(c))return If(i,c,`Expected an object with "${o}" and "${s}".`);let l=c,u=l[o],d=typeof u==`string`?n.get(u):void 0;if(d===void 0)return i.enter(o),i.fail(`Expected one of: ${Lf(t)}.`,`tool`,u,()=>t),i.leave(),c;let f=l[s];if(a){let e=Yf(f,i,`object`);f=Mf(e)?e[u]:void 0,i.enter(s),i.enter(u,null)}else i.enter(s);let p=f===void 0?If(i,f,`Required.`,`required`,r[d]):r[d].run(f,i);return a&&i.leave(!1),i.leave(),p!==l[s]&&!i.dry?Zf(l,l,s,p,i):l},encode:(e,i)=>{let c=e,l=c[o],u=n.get(l);if(u===void 0)return e;let d=r[u].encode(c[s],i);return i.objects++,a?(i.objects++,{[o]:l,[s]:Object.fromEntries(t.map(e=>[e,e===l?d:null]))}):{[o]:l,[s]:d}}})}},wf=class extends $d{kind=`never`;children(){return[]}print(){return`never`}compile(e){return Ef(e,()=>this.ruleHint())}};function Tf(e,t){let n=Kf(e,t);return n?n.kind===`never`?!0:n instanceof lf?n.values.length===0:n instanceof vf&&n.options.every(e=>Tf(e,t)):!1}function Ef(e,t){return e.node({hint:()=>[`No value is allowed here.`,t()].filter(Boolean).join(` `),emit:()=>e.profile.conditionals?{not:{}}:{type:`null`},run:(e,t)=>If(t,e,`No value is allowed here.`,`not-allowed`),encode:e=>e})}var Df=class extends $d{constructor(e,t){super(),this.inner=e,this.value=t}inner;value;kind=`default`;children(){return[this.inner]}print(e){return e.print(this.inner)}fresh(e){let t=this.value;return typeof t!=`object`||!t?t:(e&&(Array.isArray(t)?e.arrays++:e.objects++),structuredClone(t))}compile(e){let t=e.guarded(this.inner,this),n=e.profile.optional===`null`,r=this.inner instanceof kf;return e.node({own:!0,deps:[t],hint:()=>this.hintOf([`Default when left out: ${JSON.stringify(t.encode(this.value))}.`]),emit:()=>n&&!r?e.nullable(t.json()):t.json(),run:(e,i)=>e===void 0||e===null&&n&&!r?this.fresh(i.dry?void 0:i.stats):t.run(e,i),encode:(e,n)=>t.encode(e,n),child:e=>t.child(e)})}},Of=class extends $d{constructor(e){super(),this.inner=e}inner;kind=`optional`;children(){return[this.inner]}print(e){return`${e.print(this.inner)} | undefined`}compile(e){let t=e.guarded(this.inner,this),n=e.profile.optional===`null`;return e.node({own:n,deps:[t],emit:()=>n?e.nullable(t.json()):t.json(),run:(e,r)=>e===void 0?e:e===null&&n&&!(this.inner instanceof kf)?void 0:t.run(e,r),encode:(e,r)=>e===void 0?n?null:void 0:t.encode(e,r),child:e=>t.child(e)})}},kf=class extends $d{constructor(e){super(),this.inner=e}inner;kind=`nullable`;children(){return[this.inner]}print(e){return`${e.print(this.inner)} | null`}compile(e){let t=e.guarded(this.inner);return e.node({deps:[t],hint:()=>this.ruleHint(),emit:()=>e.nullable(t.json()),run:(e,n)=>e===null?e:t.run(e,n),encode:(e,n)=>e===null?null:t.encode(e,n),child:e=>t.child(e)})}},Af=class extends $d{constructor(e){super(),this.name=e}name;kind=`ref`;children(){return[]}print(e){return e.ref(this.name)}compile(e){return e.ref(this.name)}},jf=class extends $d{constructor(e,t){super(),this.wire=e,this.codec=t}wire;codec;kind=`codec`;children(){return[this.wire]}print(e){return e.print(this.wire)}compile(e){let t=e.compile(this.wire);return e.node({own:!0,deps:[t],hint:()=>this.ruleHint(),emit:()=>t.json(),run:(e,n)=>{let r=n.errors.length,i=t.run(e,n);if(n.errors.length!==r)return e;let a=this.codec.decode(i);if(a instanceof Error)return If(n,e,a.message,`other`);if(a instanceof md){if(!a.issues.length)return If(n,e,`Rejected.`,`rule`);for(let e of a.issues)n.failAt(e.path,e.message,`rule`);return e}return a},encode:(e,n)=>t.encode(this.codec.encode(e),n)})}};function Mf(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Nf(e){return typeof e==`string`?Pf(e)??`string`:e===null?`null`:Array.isArray(e)?`a list`:typeof e==`object`?`an object`:typeof e}function Pf(e){let t=e.trimStart()[0];if(t===`{`||t===`[`)try{JSON.parse(e);return}catch(e){return`a string of JSON text that doesn't parse (${e.message}); send the value itself, not as a string`}}function Ff(e){return typeof e==`string`?`string`:typeof e==`number`?`number`:typeof e==`boolean`?`boolean`:`null`}function If(e,t,n,r=`type`,i){return typeof i==`function`?e.fail(n,r,t,i):e.fail(n,r,t,void 0,i),t}function Lf(e,t=30){return e.length<=t?e.join(`, `):`${e.slice(0,t).join(`, `)}, \u2026 (${e.length-t} more)`}function Rf(e,t){return e.length<=t?e:`${e.slice(0,t-1)}\u2026`}function zf(e,t,n,r=0){let i=Kf(e,n);if(i instanceof hf){let e=Kf(i.shape[t],n);return e instanceof cf?[e.value]:e instanceof lf?[...e.values]:void 0}if(i instanceof vf&&r<8){let e=[];for(let a of i.options){let i=zf(a,t,n,r+1);if(!i)return;e.push(...i)}return e}}function Bf(e,t,n=0){let r=[];for(let i of e){let e=Kf(i,t);e instanceof lf?r.push(...e.values):e instanceof cf&&typeof e.value==`string`?r.push(e.value):e instanceof vf&&n<8&&r.push(...Bf(e.options,t,n+1))}return r}function Vf(e,t,n=0){let r=Kf(e,t);return r instanceof hf?Object.keys(r.shape):r instanceof vf&&n<8?Vf(r.options[0],t,n+1):[]}var Hf=new WeakMap;function Uf(e,t){let n=Hf.get(e);n||Hf.set(e,n=new WeakMap);let r=n.get(t);if(r===void 0){if(r=null,e.length>1)for(let n of Vf(e[0],t)){let i=new Set,a=!0;for(let r of e){let e=zf(r,n,t);if(!e||e.some(e=>i.has(e))){a=!1;break}for(let t of e)i.add(t)}if(a){r=n;break}}n.set(t,r)}return r??void 0}function Wf(e,t,n){if(!Mf(t))return-1;let r=t,i=-1,a=0,o=!1;if(e.forEach((e,t)=>{let s=0;for(let t of Vf(e,n)){let i=zf(e,t,n);i&&t in r&&(s+=i.includes(r[t])?1:-1)}s>a?(i=t,a=s,o=!1):s===a&&s>0&&(o=!0)}),!o&&i>=0)return i;let s=Object.keys(r);return s.length?(i=-1,a=0,o=!1,e.forEach((e,t)=>{let r=new Set(Vf(e,n));if(!r.size||s.some(e=>!r.has(e)))return;let c=s.length;c>a?(i=t,a=c,o=!1):c===a&&(o=!0)}),o?-1:i):-1}function Gf(e,t,n=`json`){let r=e.node({own:!0,deps:[t],emit:()=>e.object({[n]:t.json()},[n]),run:(e,r)=>{if(!Mf(e)||!(n in e))return If(r,e,n===`json`?`Expected {"json": "<JSON text>"}.`:`Expected {"${n}": [...]}.`);r.enter(n,null);let i=t.run(e[n],r);return r.leave(!1),i},encode:(e,r)=>(r.objects++,{[n]:t.encode(e,r)})});return e.nodes.push(r),r}function Kf(e,t){for(let n=0;e instanceof Af&&n<16;n++)e=t.get(e.name);return e}function qf(e,t,n){let r=new Sd(!1,!0,hd(),!1,!0);return e.lenient().nodeFor(t).run(n,r),r.errors.length===0}function Jf(e,t,n,r,i,a){r!==void 0&&(i?e[n]=r:t.includes(a)||t.push(a))}function Yf(e,t,n){if(!t.repair||typeof e!=`string`)return e;let r=e;for(let t=0;t<2&&typeof r==`string`;t++){let t=r.trim();if(!/^[[{"]/.test(t))return e;try{r=JSON.parse(t)}catch{return e}}return(n===`array`?Array.isArray(r):Mf(r))?(t.dry||t.stats.repaired++,r):e}function Xf(e,t,n){let r=e;for(let i=0;i<e.length;i++){let a=t(e[i],i);a!==e[i]&&(r===e&&(r=e.slice(),n.arrays++),r[i]=a)}return r}function Zf(e,t,n,r,i){return i.inPlace?(i.saving(t,n),t[n]=r,i.stats.edits++,t):(e===t&&(e={...t},i.stats.objects++),e[n]=r,e)}function Qf(e,t,n,r){return r.inPlace?(r.saving(t,n,!0),delete t[n],r.stats.edits++,t):(e===t&&(e={...t},r.stats.objects++),delete e[n],e)}function $f(e,t,n,r,i){return i.inPlace?(i.saving(t,n),t[n]=r,i.stats.edits++,t):(e===t&&(e=t.slice(),i.stats.arrays++),e[n]=r,e)}function ep(e,t={unsupported:[]}){let n=typeof e==`object`?e:{},r={...n.definitions??{},...n.$defs??{}},i={},a=!1,o=e=>{if(e===`#`)return a=!0,`__root`;let n=/^#\/(?:\$defs|definitions)\/(.+)$/.exec(e);return n?n[1].replace(/~1/g,`/`).replace(/~0/g,`~`):(t.unsupported.push(`$ref ${e}`),`__any`)},s=e=>{if(e===!0||e===void 0)return new uf;if(e===!1)return new vf([new sf]).refine(()=>!1,`No value is allowed here.`);let{allOf:n,not:r,if:i,then:a,else:o,...l}=e,u=Object.keys(l).every(e=>[`description`,`title`,`examples`,`$comment`,`default`].includes(e)),d=c(l);if(Array.isArray(n)&&n.length){let e=n.map(s),t=u?e:[d,...e];d=t.length===1?t[0]:new yf(t)}r!==void 0&&(d=new bf(s(r),d)),i!==void 0&&(d=new xf(d,s(i),a===void 0?void 0:s(a),o===void 0?void 0:s(o)));for(let n of[`dependentSchemas`,`dependentRequired`])n in e&&t.unsupported.push(n);return typeof e.description==`string`&&(d=d.describe(e.description)),typeof e.title==`string`&&(d=d.title(e.title)),Array.isArray(e.examples)&&(d=d.example(...e.examples)),d},c=e=>{if(typeof e.$ref==`string`)return new Af(o(e.$ref));if(`const`in e)return new cf(e.const);if(Array.isArray(e.enum)){let t=e.enum,n=t.filter(e=>typeof e==`string`),r=t.includes(null),i=n.length===t.length-+!!r&&n.length?new lf(n):new vf(t.filter(e=>e!==null).map(e=>new cf(e)));return r?new kf(i):i}let t=e.anyOf??e.oneOf;if(Array.isArray(t)){let e=t.map(s),n=e.filter(e=>!(e instanceof sf)),r=n.length===1?n[0]:new vf(n);return n.length<e.length?new kf(r):r}if(Array.isArray(e.type)){let t=e.type,n=t.filter(e=>e!==`null`).map(t=>c({...e,type:t})),r=n.length===1?n[0]:n.length?new vf(n):new sf;return t.includes(`null`)&&n.length?new kf(r):r}let n=e.type??tp(e);switch(n){case`string`:{let t=new rf;return typeof e.minLength==`number`&&(t=t.min(e.minLength)),typeof e.maxLength==`number`&&(t=t.max(e.maxLength)),typeof e.pattern==`string`&&(t=t.pattern(e.pattern)),typeof e.format==`string`&&(t=t.format(e.format)),t}case`number`:case`integer`:{let t=new af({int:e.type===`integer`});return typeof e.minimum==`number`&&(t=t.min(e.minimum)),typeof e.maximum==`number`&&(t=t.max(e.maximum)),t}case`boolean`:return new of;case`null`:return new sf;case`array`:{if(Array.isArray(e.prefixItems)&&e.prefixItems.length)return new mf(e.prefixItems.map(s));let t=new pf(s(e.items??!0));return typeof e.minItems==`number`&&(t=t.min(e.minItems)),typeof e.maxItems==`number`&&(t=t.max(e.maxItems)),t}default:{if(n===void 0&&!e.properties&&!e.patternProperties&&e.additionalProperties===void 0&&!e.required)return new uf;if(!e.properties&&!e.patternProperties&&e.additionalProperties===void 0&&!e.required)return new gf(new uf);let t=e.properties??{},r=new Set(e.required??[]),i=e.additionalProperties,a=e.patternProperties;if(!Object.keys(t).length&&!a&&i!==void 0&&i!==!1)return new gf(i===!0?new uf:s(i));let o={};for(let[e,n]of Object.entries(t))o[e]=r.has(e)?s(n):new Of(s(n));for(let e of r)e in o||(o[e]=new uf);let c=new hf(o);return a&&(c=c.patterns(Object.fromEntries(Object.entries(a).map(([e,t])=>[e,s(t)])))),i===!0?c=c.rest(new uf):i!==void 0&&typeof i==`object`&&(c=c.rest(s(i))),i===!1?c.strict():c}}};for(let[e,t]of Object.entries(r))i[e]=s(t);let{$defs:l,definitions:u,...d}=n,f=s(d);a&&(i.__root=f),(t.unsupported.includes(`$ref`)||Object.values(i).some(()=>!1))&&(i.__any=new uf);for(let e of[f,...Object.values(i)].flatMap(e=>[...e.refNames()]))e in i||(e.startsWith(`__`)||t.unsupported.push(`$ref to a missing definition "${e}" (any JSON instead)`),i[e]=new uf().describe(`Unknown reference ${e}.`));return new qd(i,a?new Af(`__root`):f)}function tp(e){if([`minLength`,`maxLength`,`pattern`,`format`].some(t=>t in e))return`string`;if([`minimum`,`maximum`,`exclusiveMinimum`,`exclusiveMaximum`,`multipleOf`].some(t=>t in e))return`number`;if([`items`,`prefixItems`,`minItems`,`maxItems`].some(t=>t in e))return`array`;if([`properties`,`required`,`patternProperties`,`additionalProperties`].some(t=>t in e))return`object`}var np=()=>new rf,rp=()=>new af,ip=()=>new af({int:!0}),ap=()=>new of,op=()=>new sf,sp=e=>new cf(e);function cp(e){return new lf([...e])}var lp=()=>new wf,up=()=>new uf,dp=()=>new uf,fp=e=>new hf(e),pp=e=>new pf(e),mp=e=>new mf(e);function hp(e,t){return t?new gf(t,e):new gf(e)}function gp(e){return new vf([...e])}function _p(e,t){return new vf([...t],e)}var vp=e=>new yf(e);function yp(e,t){return new bf(e,t??new uf)}function bp(e,t){return new xf(e,t.if,t.then,t.else)}function xp(e,t,n){return new Sf(e,t,n)}var Sp=e=>new Of(e),Cp=(e,t)=>new Df(e,t),wp=e=>new kf(e),Tp=e=>new Af(e),Ep=e=>new Af(e),Dp=(e,t)=>new jf(e,t),Op=(e,t={})=>new Cf(e,t.tag??`tool`,t.args??`args`),kp=e=>new Wd(e),Ap=()=>new Wd,jp=()=>new Wd;function Mp(e,t){let n=[];for(let e=0;e<=t.length;e++)n[e]=e;for(let r=1;r<=e.length;r++){let i=n[0];n[0]=r;for(let a=1;a<=t.length;a++){let o=n[a],s=e[r-1]===t[a-1]?0:1;n[a]=Math.min(n[a]+1,n[a-1]+1,i+s),i=o}}return n[t.length]}function Np(e){return Math.min(3,Math.max(1,Math.floor(e/3)))}function Pp(e,t,n){let r=e.toLowerCase(),i=t.map((t,n)=>({candidate:t,index:n,ci:Mp(r,t.toLowerCase()),exact:Mp(e,t)})).filter(e=>e.ci<=n);return i.sort((e,t)=>e.ci-t.ci||e.exact-t.exact||e.index-t.index),i.map(e=>e.candidate)}function Fp(e,t,n=Np(e.length)){return Pp(e,t,n)[0]}function Ip(e,t,n={}){let r=Math.max(1,n.max??1),i=Pp(e,t,Np(e.length)).slice(0,r);return i.length===0?``:` \u2014 did you mean ${Lp(i.map(e=>`\`${e}\``))}?`}function Lp(e){return e.length===2?`${e[0]} or ${e[1]}`:e.length>2?`${e.slice(0,-1).join(`, `)}, or ${e[e.length-1]}`:e.join(`, `)}function Rp(e,t,n=2){let r=e.length,i=t.length,a=[];for(let e=0;e<=i;e++)a[e]=e*n;for(let o=1;o<=r;o++){let r=a[0];a[0]=o*n;let s=e[o-1].toLowerCase();for(let e=1;e<=i;e++){let i=a[e],o=r+Mp(s,t[e-1].toLowerCase());a[e]=Math.min(a[e]+n,a[e-1]+n,o),r=i}}return a[i]}function zp(e,t,n,r,i={}){if(r.length===0)return;let a=i.maxDepth??Math.min(6,r.length+1),o=r[r.length-1].toLowerCase(),s=Np(o.length),c=r.reduce((e,t)=>e+Np(t.length),0)+2,l=i.nodeBudget??2e3,u,d=new Set,f=(e,i)=>{if(!(l<=0)){for(let n of t(e)){if(l<=0)return;if(l--,Mp(n.toLowerCase(),o)>s)continue;let e=[...i,n],t=Rp(e,r);t>c||(!u||t<u.score||t===u.score&&e.length<u.path.length)&&(u={score:t,path:e})}if(!(i.length>=a||d.has(e))){d.add(e);for(let[t,r]of n(e)){if(l<=0)break;f(r,[...i,t])}d.delete(e)}}};return f(e,[]),u?.path}var Bp=[`name`,`docs`,`extends`,`satisfies`,`generic`,`options`,`init`,`props`,`get`,`call`,`constraint`],Vp=[`docs`,`type`,`get`,`default`,`set`],Hp=[`docs`,`key`,`value`,`get`,`set`,`loop`,`loopDynamic`],Up=[`docs`,`types`,`args`,`returns`,`throws`,`get`,`set`],Wp=[`docs`,`args`,`run`];function Gp(e,t,n,r){let i=e;for(let n of Xp(i))if(!Bp.includes(n))throw Error(`registry.parse: type '${e.name}' has unknown key '${n}'`+em(n,i[n],Bp,t,`top`,r));let a=Zp(e.options)?e.options:void 0;if(t?.optionKeys&&a){for(let n of Xp(a))if(!t.optionKeys.includes(n))throw Error(`registry.parse: type '${e.name}' has unknown options key '${n}'`+em(n,a[n],t.optionKeys,t,`options`,r))}let o=Zp(e.generic)?e.generic:void 0;if(n&&t?.genericKeys&&o){for(let n of Xp(o))if(!t.genericKeys.includes(n))throw Error(`registry.parse: type '${e.name}' has unknown generic parameter '${n}'`+em(n,o[n],t.genericKeys,t,`generic`,r))}}function Kp(e,t,n,r,i){if(Zp(t))for(let a of Xp(t)){if(n.includes(a))continue;let o=r?.[a],s=typeof o==`function`?o(t[a],i):o,c=Fp(a,n);throw Error(`gin.parse: ${e} has unknown key '${a}'`+(s?` \u2014 ${s}`:c?` \u2014 did you mean \`${c}\`?`:` \u2014 valid keys: ${n.join(`, `)}`))}}var qp={generic:`a fn declares its type parameters on the TYPE, not the call: {"name":"fn","generic":{"T":{"name":"any"}},"call":{"args":…,"returns":…}}`},Jp=[{by:`prop`,keys:[`prop`],example:`{"prop":"name"}`},{by:`args`,keys:[`args`,`generic`,`catch`],example:`{"args":{…}}`},{by:`key`,keys:[`key`],example:`{"key":<expr>}`}];function Yp(e){if(!Zp(e))return;let t=Jp.filter(t=>e[t.by]!==void 0);if(t.length===0){let t=Xp(e),n=Jp.map(e=>e.by),r=t.map(e=>Fp(e,n)).find(e=>e!==void 0);throw Error(`gin.parse: path step selects no form (keys: ${t.join(`, `)||`none`})`+(r?` \u2014 did you mean \`${r}\`?`:``)+` \u2014 a step is one of ${Jp.map(e=>e.example).join(`, `)}`)}if(t.length>1){let n=t.map(e=>`'${e.by}'`).join(` and `),r=t.map(t=>t.by===`prop`?JSON.stringify({prop:e.prop}):t.example).join(`, `);throw Error(`gin.parse: path step names ${t.length} forms (${n}) \u2014 each is its own step: [${r}]`)}Kp(`path step`,e,t[0].keys)}function Xp(e){return Object.keys(e).filter(t=>e[t]!==void 0)}function Zp(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Qp(e){return Array.isArray(e)?e.length>0&&Qp(e[0]):Zp(e)&&typeof e.name==`string`}function $p(e){return Zp(e)&&`type`in e}function em(e,t,n,r,i,a){let o=[],s=Fp(e,n);if(s)return` \u2014 did you mean \`${s}\`?`;let c=r?.genericKeys??[],l=i===`options`?nm(t,r,a):void 0;return l?o.push(l):r&&i!==`generic`&&c.length>0&&Qp(t)?o.push(`that value is a TypeDef, and '${r.NAME}' takes its type argument${c.length>1?`s`:``} in \`generic\` (${c.join(`, `)})`):i===`top`&&$p(t)&&(r?.consumes??[]).includes(`props`)&&o.push("that value is a PropDef — declare it under `props`"),o.push(am(n,r,i)),` \u2014 ${o.join(`; `)}`}var tm=12;function nm(e,t,n){if(!(!t||t.NAME===`enum`||(t.genericKeys?.length??0)>0))return im(e,n,"an `enum` in gin, not an option")}var rm={values:(e,t)=>t?im(e,t,`the prop's TYPE in gin, not a key beside it`,e=>`{"type":${e}}`):"a closed set of constants is the prop's TYPE in gin, not a key beside it: declare `type` as an `enum`"};function im(e,t,n,r=e=>e){let i=!Array.isArray(e)&&Zp(e),a=Array.isArray(e)?e:i?Object.values(e):void 0;if(!a||a.length===0)return;let o=typeof a[0];if(!a.every(e=>typeof e===o)||o!==`number`&&o!==`boolean`&&o!==`string`)return;let s=`a closed set of constants is ${n}`;if(a.length>tm)return s;let c=i?e:Object.fromEntries(a.map(e=>[String(e),e])),l=o===`number`?t.enum(c,t.num()):o===`boolean`?t.enum(c,t.bool()):o===`string`?t.enum(c,t.text()):void 0;if(l)return`${s}: ${r(JSON.stringify(l.toJSON()))}`}function am(e,t,n){let r=t?`'${t.NAME}'`:`this type`;return n===`top`?`valid keys: ${e.join(`, `)}`:n===`options`?e.length===0?`${r} takes no options`:`valid options for ${r}: ${e.join(`, `)}`:e.length===0?`${r} is not generic`:`valid generic parameters for ${r}: ${e.join(`, `)}`}var om=/^(?:\w[\w-]*\/)*\w+$/;function sm(e){return typeof e==`string`&&om.test(e)}var cm={any:`Type_any`,void:`Type_void`,null:`Type_null`,bool:`Type_bool`,num:`Type_num`,text:`Type_text`,list:`Type_list`,map:`Type_map`,tuple:`Type_tuple`,obj:`Type_object`,optional:`Type_optional`,nullable:`Type_nullable`,not:`Type_not`,or:`Type_or`,and:`Type_and`,enum:`Type_enum`,literal:`Type_literal`,fn:`Type_function`,interface:`Type_interface`,typ:`Type_typ`,date:`Type_date`,timestamp:`Type_timestamp`,duration:`Type_duration`,color:`Type_color`},lm=()=>R.string().pattern(om.source).describe(`A type name: an identifier, optionally namespaced as ns/Name.`);function um(e,t){let n=cm[t],r=e.typeClass(t);return r!==void 0&&n!==void 0&&e.namedTypeList().every(e=>e.name!==t)?R.ref(n):r===void 0?R.object({name:R.literal(t)}):r.toA?.()??R.object({name:R.literal(t)})}function dm(){return R.object({name:lm()}).strict().describe(`A named type, by its name.`)}function fm(e){return R.object({name:lm(),extends:e.length>0?R.enum([...new Set(e)]):R.never(),docs:R.string().optional(),satisfies:R.array(lm()).optional(),generic:R.ref(`Generic`).optional(),options:R.record(R.unknown()).optional(),props:R.record(R.ref(`PropDef`)).optional(),get:R.ref(`GetSetDef`).optional(),call:R.ref(`CallDef`).optional(),init:R.ref(`InitDef`).optional(),constraint:R.ref(`Expr`).optional()}).describe(`A NEW named type declared inline: a name, the type it extends, and what it adds.`)}var pm=R.ref(`TypeDef`),z=R.ref(`Expr`),mm=R.string().optional().describe("Optional one-line note explaining why this expression exists. Travels with the node, surfaces in `toCode` as a `/* … */` annotation, and shows up in error paths. Use for non-obvious steps; skip for trivial reads."),hm={Generic:R.record(pm).describe(`Generic-parameter bindings: parameter name → TypeDef.`),PathStep:R.union([R.object({prop:R.string().describe("Named-property access. First step looks up a scope variable by name; subsequent steps read the previous value's prop / method. Reject if the name isn't on the type's `props()`.")}).describe("PROP step — `.<name>` access (scope var on first step, prop/method on later steps)."),R.object({args:R.record(z).describe("Map of arg-name → ExprDef. Calls the previous step (a method or any callable). Each arg expression is evaluated in the caller scope before the call; the result obj is bound as `args` inside the call body."),generic:R.ref(`Generic`).optional().describe("Optional generic-parameter map for parameterized callables (e.g. `list.map<R>` binds `R` to the element type of the result list). Usually unnecessary — most callables infer generics."),catch:z.optional().describe("Optional handler expression evaluated if this call throws. The thrown value is bound under `error` in the handler scope.")}).describe("CALL step — invoke the previous step, as its OWN step. Comes after a method (e.g. `list.push`) or any callable value; never fused into the prop step as `{prop, args}`."),R.object({key:z.describe("Indexed-access key expression. Evaluated at run time and passed to the previous value's `[key]` get/set surface.")}).describe("INDEX step — `[<key>]` access for types with index signatures (lists by `num`, maps by their key type).")]),PropDef:R.object({docs:R.string().optional(),type:pm,get:z.optional(),default:z.optional(),set:z.optional()}),GetSetDef:R.object({docs:R.string().optional(),key:pm,value:pm,get:z.optional(),set:z.optional(),loop:z.optional(),loopDynamic:R.boolean().optional().describe("When true, `loop over: <this-typed value>` re-evaluates the expression each iteration and exits when the result's raw is falsy. Bool uses this for while-loop semantics. The type may have either `loop` (for static iterables) OR `loopDynamic` set; with loopDynamic, no `loop` ExprDef is required.")}),CallDef:R.object({docs:R.string().optional(),types:R.record(pm).optional().describe('Call-local type aliases. Declare reusable named types here ONCE and reference them inside `args` / `returns` / `throws` / `get` / `set` as a bare `{name: "<alias>"}`. Aliases process AFTER any enclosing generics (so they may reference generic placeholders) and BEFORE the call slots — the call slots resolve them at parse time. Sequential: later aliases may reference earlier ones. Use this whenever the same composite type appears more than once in a signature — instead of writing `num{whole:true, min:1}` four times, declare `{ counter: { name:"num", options:{whole:true,min:1} } }` once and reference `{name:"counter"}`.'),args:pm,returns:pm.optional(),throws:pm.optional(),get:z.optional(),set:z.optional()}),InitDef:R.object({docs:R.string().optional(),args:pm,run:z})},gm=[`any`,`void`,`null`,`bool`,`num`,`text`,`list`,`map`,`tuple`,`obj`,`optional`,`nullable`,`not`,`or`,`and`,`enum`,`literal`,`fn`,`interface`,`typ`,`date`,`timestamp`,`duration`,`color`],_m={Type_any:R.object({name:R.literal(`any`)}),Type_void:R.object({name:R.literal(`void`)}),Type_null:R.object({name:R.literal(`null`)}),Type_bool:R.object({name:R.literal(`bool`),options:R.object({trueText:R.string().optional(),falseText:R.string().optional()}).optional()}),Type_num:R.object({name:R.literal(`num`),options:R.object({min:R.number().optional().describe('Only set when a real lower bound is part of the spec — e.g. "positive count" → min: 1, "age" → min: 0. Do NOT add `min: 0` to every num just because most numbers happen to be non-negative.'),max:R.number().optional().describe(`Only set when there is an actual upper bound — a percentage capped at 100, a year capped at 9999. Do NOT pick a generic ceiling like 1000/9999 to fill the field.`),whole:R.boolean().optional().describe(`Only set to true when the value is genuinely integral (counts, indices, ids). Leave unset (allow fractions) for measurements, ratios, etc.`),minPrecision:R.number().optional().describe(`Decimal-place floor. Almost never needed; omit unless the spec explicitly requires N decimal places.`),maxPrecision:R.number().optional().describe(`Decimal-place ceiling. Same rule as minPrecision — omit unless explicitly required.`),prefix:R.string().optional().describe(`Display-only prefix (e.g. "$"). Has no effect on validation. Omit unless rendering needs it.`),suffix:R.string().optional().describe(`Display-only suffix (e.g. "%"). Same as prefix — omit unless rendering needs it.`)}).optional().describe(`Omit entirely for ordinary numbers. Only include when the value has a real, named constraint worth enforcing on every parse.`)}),Type_text:R.object({name:R.literal(`text`),options:R.object({minLength:R.number().optional().describe(`Only set when a real lower bound is part of the spec — e.g. "non-empty input" → minLength: 1. Do NOT default to 0.`),maxLength:R.number().optional().describe(`Only set when there is an actual upper bound — a database column width, an API limit, an explicit "no longer than X chars" rule. Do NOT pick a generic ceiling like 100/200/1000 just to fill the field.`),pattern:R.string().optional().describe(`Only set for actual format constraints (UUID, ISO date, slug, etc.). Do NOT use ".*" or other accept-anything patterns — they add zero validation and clutter the schema.`),flags:R.string().optional().describe('Regex flags (e.g. "i"). Omit unless `pattern` is set AND requires flags.')}).optional().describe(`Omit entirely for ordinary strings. Only include when the value has a real, named constraint worth enforcing on every parse.`)}),Type_list:R.object({name:R.literal(`list`),generic:R.object({V:pm}).optional(),options:R.object({minLength:R.number().optional(),maxLength:R.number().optional()}).optional()}),Type_map:R.object({name:R.literal(`map`),generic:R.object({K:pm,V:pm}).optional()}),Type_tuple:R.object({name:R.literal(`tuple`),options:R.object({elements:R.array(pm)})}),Type_object:R.object({name:R.literal(`obj`),props:R.record(R.ref(`PropDef`)).optional()}),Type_optional:R.object({name:R.literal(`optional`),generic:R.object({T:pm}).optional()}),Type_nullable:R.object({name:R.literal(`nullable`),generic:R.object({T:pm}).optional()}),Type_not:R.object({name:R.literal(`not`),options:R.object({excluded:pm})}),Type_or:R.object({name:R.literal(`or`),options:R.object({types:R.array(pm)})}),Type_and:R.object({name:R.literal(`and`),options:R.object({types:R.array(pm)})}),Type_enum:R.object({name:R.literal(`enum`),generic:R.object({V:pm}).optional(),options:R.object({values:R.record(R.unknown())})}),Type_literal:R.object({name:R.literal(`literal`),generic:R.object({T:pm}).optional(),options:R.object({value:R.unknown()})}),Type_function:R.object({name:R.literal(`fn`),call:R.ref(`CallDef`).optional()}),Type_interface:R.object({name:R.literal(`interface`),props:R.record(R.ref(`PropDef`)).optional(),get:R.ref(`GetSetDef`).optional(),call:R.ref(`CallDef`).optional()}),Type_typ:R.object({name:R.literal(`typ`),generic:R.object({T:pm}).optional()}),Type_date:R.object({name:R.literal(`date`),options:R.object({min:R.string().optional(),max:R.string().optional(),utc:R.boolean().optional()}).optional()}),Type_timestamp:R.object({name:R.literal(`timestamp`),options:R.object({min:R.string().optional(),max:R.string().optional(),utc:R.boolean().optional(),precision:R.enum([`ms`,`s`,`us`]).optional()}).optional()}),Type_duration:R.object({name:R.literal(`duration`)}),Type_color:R.object({name:R.literal(`color`),options:R.object({hasAlpha:R.boolean().optional()}).optional()})},vm={Expr_block:R.object({kind:R.literal(`block`),comment:mm,lines:R.array(z).describe(`Sequence of expressions evaluated in order. The block's value is the LAST line's value (an empty block returns void). Earlier lines run for their side effects (set, fns.fetch, etc.).`)}),Expr_define:R.object({kind:R.literal(`define`),comment:mm,vars:R.array(R.object({name:R.string().describe(`Variable name. Must NOT be a reserved name (args, recurse, this, super, key, value, yield, error) and must NOT shadow anything already in scope.`),type:pm.optional().describe("Optional declared type. OMIT this field when the value already determines the type — every value Expr (`new`, `get`, `if`, ...) is typed, and the var inherits that type. Set this only when you need to widen / narrow / annotate beyond what the value alone produces; a mismatch with the value's inferred type is reported as `define.var.type-mismatch`."),value:z.describe("The expression whose result is bound under `name`. May reference any earlier var in this define — each var is added to scope before the next var's value is evaluated.")})).describe("Bindings introduced before `body`. Evaluated sequentially, so `vars[i].value` may reference any of `vars[0..i-1]`."),body:z}),Expr_flow:R.object({kind:R.literal(`flow`),action:R.enum([`break`,`continue`,`return`,`exit`,`throw`]).describe("Which control-flow signal to raise. `break`/`continue` only valid inside a loop. `return` only valid inside a fn body / lambda; unwinds to the enclosing call with `value`. `exit` unwinds all the way to `engine.run`, returning `value` as the program result. `throw` raises `error` (caught by a path step's `catch:` handler)."),value:z.optional().describe("Required for `return` and `exit` (the value being returned). Ignored by `break` / `continue` / `throw`."),error:z.optional().describe("Required for `throw` — the value to raise. Ignored otherwise.")}),Expr_get:R.object({kind:R.literal(`get`),path:R.array(R.ref(`PathStep`)).describe('Steps walked left-to-right starting from a scope variable. Step shapes: `{prop:"name"}` for prop/method access, `{args:{…}}` to call the previous step, `{key:Expr}` for index access. The first step MUST be a prop step (the scope-var name). A step names exactly ONE shape — a call is its own step, so a method with arguments is `[{"prop":"m"},{"args":{…}}]` and never `{"prop":"m","args":{…}}`. Result is the final step\'s value.')}),Expr_if:R.object({kind:R.literal(`if`),comment:mm,ifs:R.array(R.object({condition:z.describe("Bool-typed expression. First branch whose condition is `true` wins; the rest are skipped."),body:z.describe(`Evaluated when this branch's condition is true. The if-expression's value is this body's value.`)})).describe("Ordered list of `{condition, body}` branches — first true condition wins. Each `condition` must be bool-typed (warned otherwise). With multiple branches this is the gin equivalent of `if / else if / else if`."),else:z.optional().describe("Optional fallback evaluated when every `ifs[i].condition` is false. Without an else, a no-match if-expression evaluates to void.")}),Expr_lambda:R.object({kind:R.literal(`lambda`),comment:mm,type:pm.describe('The lambda\'s function type — `{ name: "fn", call: { args, returns } }` (or a registered named fn type). The `args` obj defines what the body sees under the `args` scope variable; `returns` is what the body must produce.'),body:z.describe('The lambda body. At runtime, scope contains the lexical scope at definition site PLUS `args` (the call arguments) and `recurse` (this same lambda, for self-calls). Read params via `[{prop:"args"},{prop:"<name>"}]`.'),constraint:z.optional().describe("Optional bool-typed precondition evaluated before the body on every call (with `args` in scope). If it returns false, the call throws. Use for input invariants you want enforced regardless of caller.")}),Expr_loop:R.object({kind:R.literal(`loop`),comment:mm,over:z.describe("The iterable expression. Two evaluation modes: (1) iterable types (list, map, etc. — anything whose `get().loop` is defined) iterate once; the expression is evaluated ONCE at the start. (2) bool — while-loop semantics: the expression is RE-EVALUATED each iteration; the loop continues while the value is `true` and exits the moment it becomes `false`. Use `flow:break` / `flow:continue` inside the body to control iteration regardless of mode."),body:z.describe("Evaluated once per iteration with the current `key` and `value` bound in scope. Use `{kind:'flow', action:'break'}` or `'continue'` for early-exit. The loop expression itself returns void."),key:R.string().optional().describe("Override the scope-variable name the iteration index/key is bound under (default: `key`). Must NOT be reserved or shadow an outer scope var. Use to disambiguate when looping inside another loop."),value:R.string().optional().describe("Override the scope-variable name the iteration value is bound under (default: `value`). Same rules as `key`."),parallel:R.object({concurrent:z.optional().describe(`Max in-flight iterations as a num (omit / 1 → strictly sequential). Use when iterations are independent I/O — e.g. fetching N URLs concurrently.`),rate:z.optional().describe(`Minimum interval between iteration starts. Accepts a num (milliseconds) or a duration. Use to rate-limit fan-out (e.g. avoid hammering an API).`)}).optional().describe("Opt-in parallelism. Both fields are optional and independent: `concurrent` caps fan-out width, `rate` paces start times. Iterations may finish out of order; the body should not assume sequential ordering. Composes with dynamic (bool while-loop) iteration: the body fans out up to `concurrent`, and `over` is re-evaluated against the outer scope each time a task completes — so accumulating side effects of earlier tasks decide whether more tasks spawn.")}),Expr_native:R.object({kind:R.literal(`native`),comment:mm,id:R.string().describe("Identifier of a native impl registered via `registry.setNative(id, fn)` (e.g. `list.push`, `num.add`). The model should NOT generate `native` expressions directly — methods on built-in types are reached via `get` paths, which gin resolves to natives internally."),type:pm.optional().describe("Optional type to wrap the native's raw return value with when the impl returns a non-Value. Defaults to `any` if omitted.")}),Expr_set:R.object({kind:R.literal(`set`),comment:mm,path:R.array(R.ref(`PathStep`)).describe('Steps walked left-to-right to a writable target. Single-step `[{prop:"x"}]` re-assigns scope variable `x`. Multi-step targets need the type to support set on the final step (a prop with a `set` ExprDef, an indexed slot, or a method whose call has `set:`).'),value:z.describe("The expression evaluated and assigned to the path target. Its type must be compatible with the target's declared type — checked statically as `set.type-mismatch`.")}),Expr_switch:R.object({kind:R.literal(`switch`),comment:mm,value:z.describe("Expression whose result is compared against each case's `equals` candidates. Evaluated once."),cases:R.array(R.object({equals:R.array(z).describe("Candidate values for this case. The case wins if `value` equals ANY one of them (logical OR). Each candidate's type must be compatible with `value`'s type — checked as `switch.case.type`."),body:z.describe(`Evaluated when this case wins. The switch expression's value is this body's value.`)})).describe(`Ordered list of cases — first match wins. Cases are NOT fall-through; only the matching case's body runs.`),else:z.optional().describe(`Optional fallback evaluated when no case matches. Without an else, a no-match switch evaluates to void.`)}),Expr_template:R.object({kind:R.literal(`template`),template:R.union([z,R.string()]).describe("The template string — either a literal string (auto-wrapped as `new text`) or an Expr that evaluates to text. Placeholders use `{name}` syntax; each `name` is looked up first in `params` (when supplied) and then in the surrounding scope."),params:z.optional().describe("Optional obj-typed expression supplying placeholder values. When omitted or when a key is missing, `{name}` falls back to a scope lookup of the same name — so a `${baseUrl}` placeholder resolves to a surrounding `define baseUrl = ...`. Provide `params` only when placeholders need values not already in scope (or to override scope values).")})},ym=[`new`,`get`,`set`,`define`,`block`,`if`,`switch`,`loop`,`lambda`,`template`,`flow`,`native`],bm={any:R.unknown(),void:R.null(),null:R.null(),bool:R.boolean(),num:R.number(),text:R.string(),list:R.array(z),map:R.array(R.object({key:z,value:z})),tuple:R.array(z),obj:R.record(z),optional:z,nullable:R.nullable(z),not:R.unknown(),or:z,and:z,enum:R.union([R.string(),R.number()]),literal:R.unknown(),fn:R.union([R.string(),R.object({kind:R.string()})]),interface:R.record(z),typ:pm,date:R.string().pattern(`^\\d{4}-\\d{2}-\\d{2}`),timestamp:R.string().pattern(`^\\d{4}-\\d{2}-\\d{2}[T ]\\d{2}:\\d{2}(:\\d{2}(\\.\\d+)?)?(Z|[+-]\\d{2}:?\\d{2})?$`),duration:R.object({days:R.number().optional(),hours:R.number().optional(),minutes:R.number().optional(),seconds:R.number().optional(),ms:R.number().optional()}),color:R.object({r:R.int().min(0).max(255),g:R.int().min(0).max(255),b:R.int().min(0).max(255),a:R.number().min(0).max(1).optional()})},xm=(e,t,n)=>R.object({kind:R.literal(`new`),type:t.describe(`Full TypeDef for a \`${e}\` instance (name + options + per-class fields).`),value:R.optional(n).describe(`Initial value matching this \`${e}\` instance. Composites accept Expr slots; primitives accept their raw form.`)}),Sm=Object.fromEntries(gm.map(e=>[`New_${e}`,xm(e,R.ref(cm[e]),bm[e])])),Cm=R.object({kind:R.literal(`new`),type:pm.describe("TypeDef of the value being constructed. The `value` field is interpreted relative to this type — primitives take their raw form (`new num` → number), composites take Expr slots (`new list` → Expr[])."),value:R.unknown().optional().describe("Initial value matching `type`. Optional when the type has a defined `init` constructor or a sensible default (empty list, zero num with no constraints, etc.).")}),wm=new Set([...Object.keys(hm),...Object.keys(_m),...Object.keys(vm),...Object.keys(Sm),`TypeDef`,`Type_Extension`,`Expr_new`,`Expr`]),Tm=(e,t)=>t.length===0?R.never():t.length===1?t[0]:R.discriminatedUnion(e,t);function Em(e,t){let n=new Map;for(let e of t?.types??[])n.set(e.name,e);for(let t of e.namedTypeList())n.has(t.name)||n.set(t.name,t);return n}function Dm(e,t){let n=Em(e,t),r=[...n.keys()],i=e.typeClasses(),a=[...r.map(e=>R.object({name:R.literal(e)}).describe(`The registered named type \`${e}\`, by name.`)),...i.map(t=>um(e,t.NAME)),R.ref(`Type_Extension`)];t?.namedRefs&&a.push(dm());let o=fm([...i.map(e=>e.NAME),...r]),s=e.exprClassList().map(e=>ym.includes(e.KIND)&&e.KIND!==`new`?R.ref(`Expr_${e.KIND}`):e.KIND===`new`?R.ref(`Expr_new`):e.toA?.()??R.object({kind:R.literal(e.KIND)}).describe(`A \`${e.KIND}\` expression.`)),c=Cm,l={};if(t?.newStrict){let t=[...n].map(([e,t])=>{let r=R.object({kind:R.literal(`new`),type:R.object({name:R.literal(e)}).describe(`Reference to the registered named type \`${e}\` \u2014 name-only, the registry resolves it to its full definition.`),value:R.optional(t.toNewA()).describe(`Initial value for the new \`${e}\` instance. Each composite slot accepts an Expr (Get, NewExpr, etc.); per-slot type correctness is enforced at runtime.`)});return wm.has(`New_${e}`)||n.has(`New_${e}`)?r:(l[`New_${e}`]=r,R.ref(`New_${e}`))}),r=i.map(t=>cm[t.NAME]!==void 0&&gm.includes(t.NAME)?R.ref(`New_${t.NAME}`):xm(t.NAME,um(e,t.NAME),t.toNewA?.()??R.unknown()));c=R.union([...t,...r])}let u={};for(let[e,t]of n)wm.has(e)||(u[e]=t.defineA({includeDocs:`all`}));return{...u,...l,TypeDef:Tm(`name`,a),Type_Extension:o,Expr_new:c,Expr:Tm(`kind`,s)}}var Om=new WeakMap,km=0,Am=e=>{let t=Om.get(e);return t===void 0&&Om.set(e,t=++km),t},jm=(e,t)=>`${Am(e)}:${e.version}|${t?.newStrict?`s`:``}${t?.namedRefs?`r`:``}|${(t?.types??[]).map(e=>e.name).join(`,`)}`,Mm=R.define(hm).define(_m).define(vm).define(Sm).declare(),Nm=Mm.dynamic((e,t)=>Dm(e,t),{key:jm,cacheSize:8});Nm.result(`TypeDef`),Nm.result(`Expr`);var Pm=class{list=[];stack=[];enter(e){return Array.isArray(e)?this.stack.push(...e):this.stack.push(e),this}leave(e=1){return this.stack.length=Math.max(0,this.stack.length-e),this}at(e,t){let n=Array.isArray(e)?e.length:1;this.enter(e);try{return t()}finally{this.leave(n)}}push(e,t,n=`error`,r){this.list.push({path:this.stack.slice(),code:e,message:t,severity:n,source:r})}error(e,t,n){this.push(e,t,`error`,n)}warn(e,t,n){this.push(e,t,`warning`,n)}info(e,t,n){this.push(e,t,`info`,n)}get hasErrors(){return this.list.some(e=>e.severity===`error`)}},Fm=class extends Error{constructor(e){super(`${e.code}: ${e.message} at ${e.path.join(`.`)}`),this.problem=e,this.name=`TypeError`}problem},B={NONE:0,STATE:1,SYSTEM:2,EXTERNAL:4};function Im(...e){let t=B.NONE;for(let n of e)t|=n;return t}var V=class e{constructor(e,t=[]){this.text=e,this.spans=t}text;spans;toString(){return this.text}concat(t){if(typeof t==`string`)return new e(this.text+t,this.spans);let n=this.text.length,r=t.spans.map(e=>({...e,start:e.start+n,end:e.end+n}));return new e(this.text+t.text,[...this.spans,...r])}indent(t){if(!t||!this.text.includes(`
|
|
71
|
+
`)},l;if(a){let n={};t.forEach((t,i)=>n[t]=e.nullable(r[i].json())),l={...e.object(n,t),description:`Fill only the field named by "${o}"; set the others to null.`}}else l=r.length===1?r[0].json():{anyOf:r.map(e=>e.json())};return e.object({[o]:n,[s]:l},[o,s])},run:(e,i)=>{let c=tp(e,i,`object`);if(!Rf(c))return Hf(i,c,`Expected an object with "${o}" and "${s}".`);let l=c,u=l[o],d=typeof u==`string`?n.get(u):void 0;if(d===void 0)return i.enter(o),i.fail(`Expected one of: ${Uf(t)}.`,`tool`,u,()=>t),i.leave(),c;let f=l[s];if(a){let e=tp(f,i,`object`);f=Rf(e)?e[u]:void 0,i.enter(s),i.enter(u,null)}else i.enter(s);let p=f===void 0?Hf(i,f,`Required.`,`required`,r[d]):r[d].run(f,i);return a&&i.leave(!1),i.leave(),p!==l[s]&&!i.dry?rp(l,l,s,p,i):l},encode:(e,i)=>{let c=e,l=c[o],u=n.get(l);if(u===void 0)return e;let d=r[u].encode(c[s],i);return i.objects++,a?(i.objects++,{[o]:l,[s]:Object.fromEntries(t.map(e=>[e,e===l?d:null]))}):{[o]:l,[s]:d}}})}},Af=class extends of{kind=`never`;children(){return[]}print(){return`never`}compile(e){return Mf(e,()=>this.ruleHint())}};function jf(e,t){let n=Qf(e,t);return n?n.kind===`never`?!0:n instanceof hf?n.values.length===0:n instanceof wf&&n.options.every(e=>jf(e,t)):!1}function Mf(e,t){return e.node({hint:()=>[`No value is allowed here.`,t()].filter(Boolean).join(` `),emit:()=>e.profile.conditionals?{not:{}}:{type:`null`},run:(e,t)=>Hf(t,e,`No value is allowed here.`,`not-allowed`),encode:e=>e})}var Nf=class extends of{constructor(e,t){super(),this.inner=e,this.value=t}inner;value;kind=`default`;children(){return[this.inner]}print(e){return e.print(this.inner)}fresh(e){let t=this.value;return typeof t!=`object`||!t?t:(e&&(Array.isArray(t)?e.arrays++:e.objects++),structuredClone(t))}compile(e){let t=e.guarded(this.inner,this),n=e.profile.optional===`null`,r=this.inner instanceof Ff;return e.node({own:!0,deps:[t],hint:()=>this.hintOf([`Default when left out: ${JSON.stringify(t.encode(this.value))}.`]),emit:()=>n&&!r?e.nullable(t.json()):t.json(),run:(e,i)=>e===void 0||e===null&&n&&!r?this.fresh(i.dry?void 0:i.stats):t.run(e,i),encode:(e,n)=>t.encode(e,n),child:e=>t.child(e)})}},Pf=class extends of{constructor(e){super(),this.inner=e}inner;kind=`optional`;children(){return[this.inner]}print(e){return`${e.print(this.inner)} | undefined`}compile(e){let t=e.guarded(this.inner,this),n=e.profile.optional===`null`;return e.node({own:n,deps:[t],emit:()=>n?e.nullable(t.json()):t.json(),run:(e,r)=>e===void 0?e:e===null&&n&&!(this.inner instanceof Ff)?void 0:t.run(e,r),encode:(e,r)=>e===void 0?n?null:void 0:t.encode(e,r),child:e=>t.child(e)})}},Ff=class extends of{constructor(e){super(),this.inner=e}inner;kind=`nullable`;children(){return[this.inner]}print(e){return`${e.print(this.inner)} | null`}compile(e){let t=e.guarded(this.inner);return e.node({deps:[t],hint:()=>this.ruleHint(),emit:()=>e.nullable(t.json()),run:(e,n)=>e===null?e:t.run(e,n),encode:(e,n)=>e===null?null:t.encode(e,n),child:e=>t.child(e)})}},If=class extends of{constructor(e){super(),this.name=e}name;kind=`ref`;children(){return[]}print(e){return e.ref(this.name)}compile(e){return e.ref(this.name)}},Lf=class extends of{constructor(e,t){super(),this.wire=e,this.codec=t}wire;codec;kind=`codec`;children(){return[this.wire]}print(e){return e.print(this.wire)}compile(e){let t=e.compile(this.wire);return e.node({own:!0,deps:[t],hint:()=>this.ruleHint(),emit:()=>t.json(),run:(e,n)=>{let r=n.errors.length,i=t.run(e,n);if(n.errors.length!==r)return e;let a=this.codec.decode(i);if(a instanceof Error)return Hf(n,e,a.message,`other`);if(a instanceof _d){if(!a.issues.length)return Hf(n,e,`Rejected.`,`rule`);for(let e of a.issues)n.failAt(e.path,e.message,`rule`);return e}return a},encode:(e,n)=>t.encode(this.codec.encode(e),n)})}};function Rf(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function zf(e){return typeof e==`string`?Bf(e)??`string`:e===null?`null`:Array.isArray(e)?`a list`:typeof e==`object`?`an object`:typeof e}function Bf(e){let t=e.trimStart()[0];if(t===`{`||t===`[`)try{JSON.parse(e);return}catch(e){return`a string of JSON text that doesn't parse (${e.message}); send the value itself, not as a string`}}function Vf(e){return typeof e==`string`?`string`:typeof e==`number`?`number`:typeof e==`boolean`?`boolean`:`null`}function Hf(e,t,n,r=`type`,i){return typeof i==`function`?e.fail(n,r,t,i):e.fail(n,r,t,void 0,i),t}function Uf(e,t=30){return e.length<=t?e.join(`, `):`${e.slice(0,t).join(`, `)}, \u2026 (${e.length-t} more)`}function Wf(e,t){return e.length<=t?e:`${e.slice(0,t-1)}\u2026`}function Gf(e,t,n,r=0){let i=Qf(e,n);if(i instanceof xf){let e=Qf(i.shape[t],n);return e instanceof mf?[e.value]:e instanceof hf?[...e.values]:void 0}if(i instanceof wf&&r<8){let e=[];for(let a of i.options){let i=Gf(a,t,n,r+1);if(!i)return;e.push(...i)}return e}}function Kf(e,t,n=0){let r=[];for(let i of e){let e=Qf(i,t);e instanceof hf?r.push(...e.values):e instanceof mf&&typeof e.value==`string`?r.push(e.value):e instanceof wf&&n<8&&r.push(...Kf(e.options,t,n+1))}return r}function qf(e,t,n=0){let r=Qf(e,t);return r instanceof xf?Object.keys(r.shape):r instanceof wf&&n<8?qf(r.options[0],t,n+1):[]}var Jf=new WeakMap;function Yf(e,t){let n=Jf.get(e);n||Jf.set(e,n=new WeakMap);let r=n.get(t);if(r===void 0){if(r=null,e.length>1)for(let n of qf(e[0],t)){let i=new Set,a=!0;for(let r of e){let e=Gf(r,n,t);if(!e||e.some(e=>i.has(e))){a=!1;break}for(let t of e)i.add(t)}if(a){r=n;break}}n.set(t,r)}return r??void 0}function Xf(e,t,n){if(!Rf(t))return-1;let r=t,i=-1,a=0,o=!1;if(e.forEach((e,t)=>{let s=0;for(let t of qf(e,n)){let i=Gf(e,t,n);i&&t in r&&(s+=i.includes(r[t])?1:-1)}s>a?(i=t,a=s,o=!1):s===a&&s>0&&(o=!0)}),!o&&i>=0)return i;let s=Object.keys(r);return s.length?(i=-1,a=0,o=!1,e.forEach((e,t)=>{let r=new Set(qf(e,n));if(!r.size||s.some(e=>!r.has(e)))return;let c=s.length;c>a?(i=t,a=c,o=!1):c===a&&(o=!0)}),o?-1:i):-1}function Zf(e,t,n=`json`){let r=e.node({own:!0,deps:[t],emit:()=>e.object({[n]:t.json()},[n]),run:(e,r)=>{if(!Rf(e)||!(n in e))return Hf(r,e,n===`json`?`Expected {"json": "<JSON text>"}.`:`Expected {"${n}": [...]}.`);r.enter(n,null);let i=t.run(e[n],r);return r.leave(!1),i},encode:(e,r)=>(r.objects++,{[n]:t.encode(e,r)})});return e.nodes.push(r),r}function Qf(e,t){for(let n=0;e instanceof If&&n<16;n++)e=t.get(e.name);return e}function $f(e,t,n){let r=new Td(!1,!0,vd(),!1,!0);return e.lenient().nodeFor(t).run(n,r),r.errors.length===0}function ep(e,t,n,r,i,a){r!==void 0&&(i?e[n]=r:t.includes(a)||t.push(a))}function tp(e,t,n){if(!t.repair||typeof e!=`string`)return e;let r=e;for(let t=0;t<2&&typeof r==`string`;t++){let t=r.trim();if(!/^[[{"]/.test(t))return e;try{r=JSON.parse(t)}catch{return e}}return(n===`array`?Array.isArray(r):Rf(r))?(t.dry||t.stats.repaired++,r):e}function np(e,t,n){let r=e;for(let i=0;i<e.length;i++){let a=t(e[i],i);a!==e[i]&&(r===e&&(r=e.slice(),n.arrays++),r[i]=a)}return r}function rp(e,t,n,r,i){return i.inPlace?(i.saving(t,n),t[n]=r,i.stats.edits++,t):(e===t&&(e={...t},i.stats.objects++),e[n]=r,e)}function ip(e,t,n,r){return r.inPlace?(r.saving(t,n,!0),delete t[n],r.stats.edits++,t):(e===t&&(e={...t},r.stats.objects++),delete e[n],e)}function ap(e,t,n,r,i){return i.inPlace?(i.saving(t,n),t[n]=r,i.stats.edits++,t):(e===t&&(e=t.slice(),i.stats.arrays++),e[n]=r,e)}function op(e,t={unsupported:[]}){let n=typeof e==`object`?e:{},r={...n.definitions??{},...n.$defs??{}},i={},a=!1,o=e=>{if(e===`#`)return a=!0,`__root`;let n=/^#\/(?:\$defs|definitions)\/(.+)$/.exec(e);return n?n[1].replace(/~1/g,`/`).replace(/~0/g,`~`):(t.unsupported.push(`$ref ${e}`),`__any`)},s=e=>{if(e===!0||e===void 0)return new gf;if(e===!1)return new wf([new pf]).refine(()=>!1,`No value is allowed here.`);let{allOf:n,not:r,if:i,then:a,else:o,...l}=e,u=Object.keys(l).every(e=>[`description`,`title`,`examples`,`$comment`,`default`].includes(e)),d=c(l);if(Array.isArray(n)&&n.length){let e=n.map(s),t=u?e:[d,...e];d=t.length===1?t[0]:new Tf(t)}r!==void 0&&(d=new Ef(s(r),d)),i!==void 0&&(d=new Df(d,s(i),a===void 0?void 0:s(a),o===void 0?void 0:s(o)));for(let n of[`dependentSchemas`,`dependentRequired`])n in e&&t.unsupported.push(n);return typeof e.description==`string`&&(d=d.describe(e.description)),typeof e.title==`string`&&(d=d.title(e.title)),Array.isArray(e.examples)&&(d=d.example(...e.examples)),d},c=e=>{if(typeof e.$ref==`string`)return new If(o(e.$ref));if(`const`in e)return new mf(e.const);if(Array.isArray(e.enum)){let t=e.enum,n=t.filter(e=>typeof e==`string`),r=t.includes(null),i=n.length===t.length-+!!r&&n.length?new hf(n):new wf(t.filter(e=>e!==null).map(e=>new mf(e)));return r?new Ff(i):i}let t=e.anyOf??e.oneOf;if(Array.isArray(t)){let e=t.map(s),n=e.filter(e=>!(e instanceof pf)),r=n.length===1?n[0]:new wf(n);return n.length<e.length?new Ff(r):r}if(Array.isArray(e.type)){let t=e.type,n=t.filter(e=>e!==`null`).map(t=>c({...e,type:t})),r=n.length===1?n[0]:n.length?new wf(n):new pf;return t.includes(`null`)&&n.length?new Ff(r):r}let n=e.type??sp(e);switch(n){case`string`:{let t=new uf;return typeof e.minLength==`number`&&(t=t.min(e.minLength)),typeof e.maxLength==`number`&&(t=t.max(e.maxLength)),typeof e.pattern==`string`&&(t=t.pattern(e.pattern)),typeof e.format==`string`&&(t=t.format(e.format)),t}case`number`:case`integer`:{let t=new df({int:e.type===`integer`});return typeof e.minimum==`number`&&(t=t.min(e.minimum)),typeof e.maximum==`number`&&(t=t.max(e.maximum)),t}case`boolean`:return new ff;case`null`:return new pf;case`array`:{if(Array.isArray(e.prefixItems)&&e.prefixItems.length)return new bf(e.prefixItems.map(s));let t=new yf(s(e.items??!0));return typeof e.minItems==`number`&&(t=t.min(e.minItems)),typeof e.maxItems==`number`&&(t=t.max(e.maxItems)),t}default:{if(n===void 0&&!e.properties&&!e.patternProperties&&e.additionalProperties===void 0&&!e.required)return new gf;if(!e.properties&&!e.patternProperties&&e.additionalProperties===void 0&&!e.required)return new Sf(new gf);let t=e.properties??{},r=new Set(e.required??[]),i=e.additionalProperties,a=e.patternProperties;if(!Object.keys(t).length&&!a&&i!==void 0&&i!==!1)return new Sf(i===!0?new gf:s(i));let o={};for(let[e,n]of Object.entries(t))o[e]=r.has(e)?s(n):new Pf(s(n));for(let e of r)e in o||(o[e]=new gf);let c=new xf(o);return a&&(c=c.patterns(Object.fromEntries(Object.entries(a).map(([e,t])=>[e,s(t)])))),i===!0?c=c.rest(new gf):i!==void 0&&typeof i==`object`&&(c=c.rest(s(i))),i===!1?c.strict():c}}};for(let[e,t]of Object.entries(r))i[e]=s(t);let{$defs:l,definitions:u,...d}=n,f=s(d);a&&(i.__root=f),(t.unsupported.includes(`$ref`)||Object.values(i).some(()=>!1))&&(i.__any=new gf);for(let e of[f,...Object.values(i)].flatMap(e=>[...e.refNames()]))e in i||(e.startsWith(`__`)||t.unsupported.push(`$ref to a missing definition "${e}" (any JSON instead)`),i[e]=new gf().describe(`Unknown reference ${e}.`));return new $d(i,a?new If(`__root`):f)}function sp(e){if([`minLength`,`maxLength`,`pattern`,`format`].some(t=>t in e))return`string`;if([`minimum`,`maximum`,`exclusiveMinimum`,`exclusiveMaximum`,`multipleOf`].some(t=>t in e))return`number`;if([`items`,`prefixItems`,`minItems`,`maxItems`].some(t=>t in e))return`array`;if([`properties`,`required`,`patternProperties`,`additionalProperties`].some(t=>t in e))return`object`}var cp=()=>new uf,lp=()=>new df,up=()=>new df({int:!0}),dp=()=>new ff,fp=()=>new pf,pp=e=>new mf(e);function mp(e){return new hf([...e])}var hp=()=>new Af,gp=()=>new gf,_p=()=>new gf,vp=e=>new xf(e),yp=e=>new yf(e),bp=e=>new bf(e);function xp(e,t){return t?new Sf(t,e):new Sf(e)}function Sp(e){return new wf([...e])}function Cp(e,t){return new wf([...t],e)}var wp=e=>new Tf(e);function Tp(e,t){return new Ef(e,t??new gf)}function Ep(e,t){return new Df(e,t.if,t.then,t.else)}function Dp(e,t,n){return new Of(e,t,n)}var Op=e=>new Pf(e),kp=(e,t)=>new Nf(e,t),Ap=e=>new Ff(e),jp=e=>new If(e),Mp=e=>new If(e),Np=(e,t)=>new Lf(e,t),Pp=(e,t={})=>new kf(e,t.tag??`tool`,t.args??`args`),Fp=e=>new Xd(e),Ip=()=>new Xd,Lp=()=>new Xd,Rp={optional:[`omit`,`null`],closedObjects:`boolean`,records:[`open`,`pairs`],tuples:[`prefixItems`,`object`,`array`],unions:[`anyOf`,`tagged`],nulls:[`type-array`,`anyOf`,`nullable`],allOf:`boolean`,conditionals:`boolean`,patternProperties:`boolean`,defs:`boolean`,refSiblings:`boolean`,recursion:[!0,!1,`guarded`],any:[`empty`,`flat`,`json-text`],examples:[`keyword`,`description`,`none`],propertyOrdering:`boolean`,rootObject:`boolean`,alwaysStrictOutput:`boolean`,jsonInstruction:`string`,audience:[`model`,`people`]},zp={properties:`maxProperties`,objectProperties:`maxObjectProperties`,objectOptionals:`maxObjectOptional`,optionals:`maxOptional`,unions:`maxUnions`,depth:`maxDepth`,enumSize:null,enumValues:`maxEnumValues`,stringChars:`maxStringChars`,largeEnumValues:`largeEnumValues`,largeEnumChars:`maxLargeEnumChars`},Bp={tools:[`request`,`maxTools`],strictTools:[`request`,`maxStrictTools`],requestProperties:[`totals`,`maxProperties`],requestOptionals:[`totals`,`maxOptional`],requestUnions:[`totals`,`maxUnions`],requestDepth:[`totals`,`maxDepth`],requestStringChars:[`totals`,`maxStringChars`],requestEnumValues:[`totals`,`maxEnumValues`],requestLargeEnumValues:[`totals`,`largeEnumValues`],requestLargeEnumChars:[`totals`,`maxLargeEnumChars`],requestObjectProperties:[`totals`,`maxObjectProperties`],requestObjectOptionals:[`totals`,`maxObjectOptional`]},Vp={length:`boolean`,range:`boolean`,items:[`all`,`min-0-1`,`none`],pattern:[`full`,`basic`,`none`]},Hp=e=>Object.fromEntries(Object.keys(e).map(e=>[e,`number`])),Up={rules:Rp,limits:Hp(zp),constraints:Vp,formats:`formats`},Wp={strict:`boolean`,dialect:`string`,loose:`string`,...Up,looseRules:Up},Gp={base:`string`,tools:Wp,output:Wp,delivery:[`structured`,`prompt`],limits:Hp(Bp)},Kp=e=>typeof e==`object`&&!!e&&!Array.isArray(e),qp=e=>JSON.stringify(e)??String(e);function Jp(e,t,n,r){let i=t=>{throw Error(`Schema rules${r}: ${n} is ${qp(e)}, expected ${t}`)};Array.isArray(t)?t.includes(e)||i(t.map(qp).join(` | `)):t===`boolean`||t===`string`?typeof e!==t&&i(`a ${t}`):t===`number`?typeof e==`number`&&e>=0||i(`a number of 0 or more`):t===`formats`?e!==`all`&&!(Array.isArray(e)&&e.every(e=>typeof e==`string`))&&i(`"all" or a list of format names`):Yp(e,t,n,r)}function Yp(e,t,n,r){if(!Kp(e))throw Error(`Schema rules${r}: ${n||`the rules`} is ${qp(e)}, expected an object`);for(let[i,a]of Object.entries(e)){let e=n?`${n}.${i}`:i,o=t[i];if(!o)throw Error(`Schema rules${r}: unknown key "${e}" (known: ${Object.keys(t).join(`, `)})`);a!==void 0&&Jp(a,o,e,r)}}var Xp=new WeakSet;function Zp(e,t){Kp(e)&&Xp.has(e)||(Yp(e,Gp,``,t?` of ${t}`:``),Xp.add(e))}var Qp=new Map;function $p(e,t){Zp(t,`base "${e}"`);let n=Object.freeze({...t});Xp.add(n),Qp.set(e,n)}var em=(e,t)=>({tools:{dialect:e,loose:t},output:{dialect:e,loose:t}});$p(`lenient`,em(`lenient`,`lenient`)),$p(`openai`,em(`openai-strict`,`openai`)),$p(`openai-finetuned`,{base:`openai`,...em(`openai-finetuned-strict`,`openai`)}),$p(`anthropic`,{tools:{dialect:`anthropic-strict`,loose:`anthropic`},output:{dialect:`anthropic-strict-output`,loose:`anthropic`}}),$p(`google`,em(`google-strict`,`google`)),$p(`google-openapi`,em(`google-openapi`,`google`)),$p(`xai`,{tools:{strict:!0,dialect:`xai-strict`,loose:`xai`},output:{dialect:`xai-strict`,loose:`xai`}}),$p(`ollama`,em(`ollama`,`ollama`));function tm(e,t){let n=[];for(let e=0;e<=t.length;e++)n[e]=e;for(let r=1;r<=e.length;r++){let i=n[0];n[0]=r;for(let a=1;a<=t.length;a++){let o=n[a],s=e[r-1]===t[a-1]?0:1;n[a]=Math.min(n[a]+1,n[a-1]+1,i+s),i=o}}return n[t.length]}function nm(e){return Math.min(3,Math.max(1,Math.floor(e/3)))}function rm(e,t,n){let r=e.toLowerCase(),i=t.map((t,n)=>({candidate:t,index:n,ci:tm(r,t.toLowerCase()),exact:tm(e,t)})).filter(e=>e.ci<=n);return i.sort((e,t)=>e.ci-t.ci||e.exact-t.exact||e.index-t.index),i.map(e=>e.candidate)}function im(e,t,n=nm(e.length)){return rm(e,t,n)[0]}function am(e,t,n={}){let r=Math.max(1,n.max??1),i=rm(e,t,nm(e.length)).slice(0,r);return i.length===0?``:` \u2014 did you mean ${om(i.map(e=>`\`${e}\``))}?`}function om(e){return e.length===2?`${e[0]} or ${e[1]}`:e.length>2?`${e.slice(0,-1).join(`, `)}, or ${e[e.length-1]}`:e.join(`, `)}function sm(e,t,n=2){let r=e.length,i=t.length,a=[];for(let e=0;e<=i;e++)a[e]=e*n;for(let o=1;o<=r;o++){let r=a[0];a[0]=o*n;let s=e[o-1].toLowerCase();for(let e=1;e<=i;e++){let i=a[e],o=r+tm(s,t[e-1].toLowerCase());a[e]=Math.min(a[e]+n,a[e-1]+n,o),r=i}}return a[i]}function cm(e,t,n,r,i={}){if(r.length===0)return;let a=i.maxDepth??Math.min(6,r.length+1),o=r[r.length-1].toLowerCase(),s=nm(o.length),c=r.reduce((e,t)=>e+nm(t.length),0)+2,l=i.nodeBudget??2e3,u,d=new Set,f=(e,i)=>{if(!(l<=0)){for(let n of t(e)){if(l<=0)return;if(l--,tm(n.toLowerCase(),o)>s)continue;let e=[...i,n],t=sm(e,r);t>c||(!u||t<u.score||t===u.score&&e.length<u.path.length)&&(u={score:t,path:e})}if(!(i.length>=a||d.has(e))){d.add(e);for(let[t,r]of n(e)){if(l<=0)break;f(r,[...i,t])}d.delete(e)}}};return f(e,[]),u?.path}var lm=[`name`,`docs`,`extends`,`satisfies`,`generic`,`options`,`init`,`props`,`get`,`call`,`constraint`],um=[`docs`,`type`,`get`,`default`,`set`],dm=[`docs`,`key`,`value`,`get`,`set`,`loop`,`loopDynamic`],fm=[`docs`,`types`,`args`,`returns`,`throws`,`get`,`set`],pm=[`docs`,`args`,`run`];function mm(e,t,n,r){let i=e;for(let n of ym(i))if(!lm.includes(n))throw Error(`registry.parse: type '${e.name}' has unknown key '${n}'`+Cm(n,i[n],lm,t,`top`,r));let a=bm(e.options)?e.options:void 0;if(t?.optionKeys&&a){for(let n of ym(a))if(!t.optionKeys.includes(n))throw Error(`registry.parse: type '${e.name}' has unknown options key '${n}'`+Cm(n,a[n],t.optionKeys,t,`options`,r))}let o=bm(e.generic)?e.generic:void 0;if(n&&t?.genericKeys&&o){for(let n of ym(o))if(!t.genericKeys.includes(n))throw Error(`registry.parse: type '${e.name}' has unknown generic parameter '${n}'`+Cm(n,o[n],t.genericKeys,t,`generic`,r))}}function hm(e,t,n,r,i){if(bm(t))for(let a of ym(t)){if(n.includes(a))continue;let o=r?.[a],s=typeof o==`function`?o(t[a],i):o,c=im(a,n);throw Error(`gin.parse: ${e} has unknown key '${a}'`+(s?` \u2014 ${s}`:c?` \u2014 did you mean \`${c}\`?`:` \u2014 valid keys: ${n.join(`, `)}`))}}var gm={generic:`a fn declares its type parameters on the TYPE, not the call: {"name":"fn","generic":{"T":{"name":"any"}},"call":{"args":…,"returns":…}}`},_m=[{by:`prop`,keys:[`prop`],example:`{"prop":"name"}`},{by:`args`,keys:[`args`,`generic`,`catch`],example:`{"args":{…}}`},{by:`key`,keys:[`key`],example:`{"key":<expr>}`}];function vm(e){if(!bm(e))return;let t=_m.filter(t=>e[t.by]!==void 0);if(t.length===0){let t=ym(e),n=_m.map(e=>e.by),r=t.map(e=>im(e,n)).find(e=>e!==void 0);throw Error(`gin.parse: path step selects no form (keys: ${t.join(`, `)||`none`})`+(r?` \u2014 did you mean \`${r}\`?`:``)+` \u2014 a step is one of ${_m.map(e=>e.example).join(`, `)}`)}if(t.length>1){let n=t.map(e=>`'${e.by}'`).join(` and `),r=t.map(t=>t.by===`prop`?JSON.stringify({prop:e.prop}):t.example).join(`, `);throw Error(`gin.parse: path step names ${t.length} forms (${n}) \u2014 each is its own step: [${r}]`)}hm(`path step`,e,t[0].keys)}function ym(e){return Object.keys(e).filter(t=>e[t]!==void 0)}function bm(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function xm(e){return Array.isArray(e)?e.length>0&&xm(e[0]):bm(e)&&typeof e.name==`string`}function Sm(e){return bm(e)&&`type`in e}function Cm(e,t,n,r,i,a){let o=[],s=im(e,n);if(s)return` \u2014 did you mean \`${s}\`?`;let c=r?.genericKeys??[],l=i===`options`?Tm(t,r,a):void 0;return l?o.push(l):r&&i!==`generic`&&c.length>0&&xm(t)?o.push(`that value is a TypeDef, and '${r.NAME}' takes its type argument${c.length>1?`s`:``} in \`generic\` (${c.join(`, `)})`):i===`top`&&Sm(t)&&(r?.consumes??[]).includes(`props`)&&o.push("that value is a PropDef — declare it under `props`"),o.push(Om(n,r,i)),` \u2014 ${o.join(`; `)}`}var wm=12;function Tm(e,t,n){if(!(!t||t.NAME===`enum`||(t.genericKeys?.length??0)>0))return Dm(e,n,"an `enum` in gin, not an option")}var Em={values:(e,t)=>t?Dm(e,t,`the prop's TYPE in gin, not a key beside it`,e=>`{"type":${e}}`):"a closed set of constants is the prop's TYPE in gin, not a key beside it: declare `type` as an `enum`"};function Dm(e,t,n,r=e=>e){let i=!Array.isArray(e)&&bm(e),a=Array.isArray(e)?e:i?Object.values(e):void 0;if(!a||a.length===0)return;let o=typeof a[0];if(!a.every(e=>typeof e===o)||o!==`number`&&o!==`boolean`&&o!==`string`)return;let s=`a closed set of constants is ${n}`;if(a.length>wm)return s;let c=i?e:Object.fromEntries(a.map(e=>[String(e),e])),l=o===`number`?t.enum(c,t.num()):o===`boolean`?t.enum(c,t.bool()):o===`string`?t.enum(c,t.text()):void 0;if(l)return`${s}: ${r(JSON.stringify(l.toJSON()))}`}function Om(e,t,n){let r=t?`'${t.NAME}'`:`this type`;return n===`top`?`valid keys: ${e.join(`, `)}`:n===`options`?e.length===0?`${r} takes no options`:`valid options for ${r}: ${e.join(`, `)}`:e.length===0?`${r} is not generic`:`valid generic parameters for ${r}: ${e.join(`, `)}`}var km=/^(?:\w[\w-]*\/)*\w+$/;function Am(e){return typeof e==`string`&&km.test(e)}var jm={any:`Type_any`,void:`Type_void`,null:`Type_null`,bool:`Type_bool`,num:`Type_num`,text:`Type_text`,list:`Type_list`,map:`Type_map`,tuple:`Type_tuple`,obj:`Type_object`,optional:`Type_optional`,nullable:`Type_nullable`,not:`Type_not`,or:`Type_or`,and:`Type_and`,enum:`Type_enum`,literal:`Type_literal`,fn:`Type_function`,interface:`Type_interface`,typ:`Type_typ`,date:`Type_date`,timestamp:`Type_timestamp`,duration:`Type_duration`,color:`Type_color`},Mm=()=>R.string().pattern(km.source).describe(`A type name: an identifier, optionally namespaced as ns/Name.`);function Nm(e,t){let n=jm[t],r=e.typeClass(t);return r!==void 0&&n!==void 0&&e.namedTypeList().every(e=>e.name!==t)?R.ref(n):r===void 0?R.object({name:R.literal(t)}):r.toA?.()??R.object({name:R.literal(t)})}function Pm(){return R.object({name:Mm()}).strict().describe(`A named type, by its name.`)}function Fm(e){return R.object({name:Mm(),extends:e.length>0?R.enum([...new Set(e)]):R.never(),docs:R.string().optional(),satisfies:R.array(Mm()).optional(),generic:R.ref(`Generic`).optional(),options:R.record(R.unknown()).optional(),props:R.record(R.ref(`PropDef`)).optional(),get:R.ref(`GetSetDef`).optional(),call:R.ref(`CallDef`).optional(),init:R.ref(`InitDef`).optional(),constraint:R.ref(`Expr`).optional()}).describe(`A NEW named type declared inline: a name, the type it extends, and what it adds.`)}var Im=R.ref(`TypeDef`),z=R.ref(`Expr`),Lm=R.string().optional().describe("Optional one-line note explaining why this expression exists. Travels with the node, surfaces in `toCode` as a `/* … */` annotation, and shows up in error paths. Use for non-obvious steps; skip for trivial reads."),Rm={Generic:R.record(Im).describe(`Generic-parameter bindings: parameter name → TypeDef.`),PathStep:R.union([R.object({prop:R.string().describe("Named-property access. First step looks up a scope variable by name; subsequent steps read the previous value's prop / method. Reject if the name isn't on the type's `props()`.")}).describe("PROP step — `.<name>` access (scope var on first step, prop/method on later steps)."),R.object({args:R.record(z).describe("Map of arg-name → ExprDef. Calls the previous step (a method or any callable). Each arg expression is evaluated in the caller scope before the call; the result obj is bound as `args` inside the call body."),generic:R.ref(`Generic`).optional().describe("Optional generic-parameter map for parameterized callables (e.g. `list.map<R>` binds `R` to the element type of the result list). Usually unnecessary — most callables infer generics."),catch:z.optional().describe("Optional handler expression evaluated if this call throws. The thrown value is bound under `error` in the handler scope.")}).describe("CALL step — invoke the previous step, as its OWN step. Comes after a method (e.g. `list.push`) or any callable value; never fused into the prop step as `{prop, args}`."),R.object({key:z.describe("Indexed-access key expression. Evaluated at run time and passed to the previous value's `[key]` get/set surface.")}).describe("INDEX step — `[<key>]` access for types with index signatures (lists by `num`, maps by their key type).")]),PropDef:R.object({docs:R.string().optional(),type:Im,get:z.optional(),default:z.optional(),set:z.optional()}),GetSetDef:R.object({docs:R.string().optional(),key:Im,value:Im,get:z.optional(),set:z.optional(),loop:z.optional(),loopDynamic:R.boolean().optional().describe("When true, `loop over: <this-typed value>` re-evaluates the expression each iteration and exits when the result's raw is falsy. Bool uses this for while-loop semantics. The type may have either `loop` (for static iterables) OR `loopDynamic` set; with loopDynamic, no `loop` ExprDef is required.")}),CallDef:R.object({docs:R.string().optional(),types:R.record(Im).optional().describe('Call-local type aliases. Declare reusable named types here ONCE and reference them inside `args` / `returns` / `throws` / `get` / `set` as a bare `{name: "<alias>"}`. Aliases process AFTER any enclosing generics (so they may reference generic placeholders) and BEFORE the call slots — the call slots resolve them at parse time. Sequential: later aliases may reference earlier ones. Use this whenever the same composite type appears more than once in a signature — instead of writing `num{whole:true, min:1}` four times, declare `{ counter: { name:"num", options:{whole:true,min:1} } }` once and reference `{name:"counter"}`.'),args:Im,returns:Im.optional(),throws:Im.optional(),get:z.optional(),set:z.optional()}),InitDef:R.object({docs:R.string().optional(),args:Im,run:z})},zm=[`any`,`void`,`null`,`bool`,`num`,`text`,`list`,`map`,`tuple`,`obj`,`optional`,`nullable`,`not`,`or`,`and`,`enum`,`literal`,`fn`,`interface`,`typ`,`date`,`timestamp`,`duration`,`color`],Bm={Type_any:R.object({name:R.literal(`any`)}),Type_void:R.object({name:R.literal(`void`)}),Type_null:R.object({name:R.literal(`null`)}),Type_bool:R.object({name:R.literal(`bool`),options:R.object({trueText:R.string().optional(),falseText:R.string().optional()}).optional()}),Type_num:R.object({name:R.literal(`num`),options:R.object({min:R.number().optional().describe('Only set when a real lower bound is part of the spec — e.g. "positive count" → min: 1, "age" → min: 0. Do NOT add `min: 0` to every num just because most numbers happen to be non-negative.'),max:R.number().optional().describe(`Only set when there is an actual upper bound — a percentage capped at 100, a year capped at 9999. Do NOT pick a generic ceiling like 1000/9999 to fill the field.`),whole:R.boolean().optional().describe(`Only set to true when the value is genuinely integral (counts, indices, ids). Leave unset (allow fractions) for measurements, ratios, etc.`),minPrecision:R.number().optional().describe(`Decimal-place floor. Almost never needed; omit unless the spec explicitly requires N decimal places.`),maxPrecision:R.number().optional().describe(`Decimal-place ceiling. Same rule as minPrecision — omit unless explicitly required.`),prefix:R.string().optional().describe(`Display-only prefix (e.g. "$"). Has no effect on validation. Omit unless rendering needs it.`),suffix:R.string().optional().describe(`Display-only suffix (e.g. "%"). Same as prefix — omit unless rendering needs it.`)}).optional().describe(`Omit entirely for ordinary numbers. Only include when the value has a real, named constraint worth enforcing on every parse.`)}),Type_text:R.object({name:R.literal(`text`),options:R.object({minLength:R.number().optional().describe(`Only set when a real lower bound is part of the spec — e.g. "non-empty input" → minLength: 1. Do NOT default to 0.`),maxLength:R.number().optional().describe(`Only set when there is an actual upper bound — a database column width, an API limit, an explicit "no longer than X chars" rule. Do NOT pick a generic ceiling like 100/200/1000 just to fill the field.`),pattern:R.string().optional().describe(`Only set for actual format constraints (UUID, ISO date, slug, etc.). Do NOT use ".*" or other accept-anything patterns — they add zero validation and clutter the schema.`),flags:R.string().optional().describe('Regex flags (e.g. "i"). Omit unless `pattern` is set AND requires flags.')}).optional().describe(`Omit entirely for ordinary strings. Only include when the value has a real, named constraint worth enforcing on every parse.`)}),Type_list:R.object({name:R.literal(`list`),generic:R.object({V:Im}).optional(),options:R.object({minLength:R.number().optional(),maxLength:R.number().optional()}).optional()}),Type_map:R.object({name:R.literal(`map`),generic:R.object({K:Im,V:Im}).optional()}),Type_tuple:R.object({name:R.literal(`tuple`),options:R.object({elements:R.array(Im)})}),Type_object:R.object({name:R.literal(`obj`),props:R.record(R.ref(`PropDef`)).optional()}),Type_optional:R.object({name:R.literal(`optional`),generic:R.object({T:Im}).optional()}),Type_nullable:R.object({name:R.literal(`nullable`),generic:R.object({T:Im}).optional()}),Type_not:R.object({name:R.literal(`not`),options:R.object({excluded:Im})}),Type_or:R.object({name:R.literal(`or`),options:R.object({types:R.array(Im)})}),Type_and:R.object({name:R.literal(`and`),options:R.object({types:R.array(Im)})}),Type_enum:R.object({name:R.literal(`enum`),generic:R.object({V:Im}).optional(),options:R.object({values:R.record(R.unknown())})}),Type_literal:R.object({name:R.literal(`literal`),generic:R.object({T:Im}).optional(),options:R.object({value:R.unknown()})}),Type_function:R.object({name:R.literal(`fn`),call:R.ref(`CallDef`).optional()}),Type_interface:R.object({name:R.literal(`interface`),props:R.record(R.ref(`PropDef`)).optional(),get:R.ref(`GetSetDef`).optional(),call:R.ref(`CallDef`).optional()}),Type_typ:R.object({name:R.literal(`typ`),generic:R.object({T:Im}).optional()}),Type_date:R.object({name:R.literal(`date`),options:R.object({min:R.string().optional(),max:R.string().optional(),utc:R.boolean().optional()}).optional()}),Type_timestamp:R.object({name:R.literal(`timestamp`),options:R.object({min:R.string().optional(),max:R.string().optional(),utc:R.boolean().optional(),precision:R.enum([`ms`,`s`,`us`]).optional()}).optional()}),Type_duration:R.object({name:R.literal(`duration`)}),Type_color:R.object({name:R.literal(`color`),options:R.object({hasAlpha:R.boolean().optional()}).optional()})},Vm={Expr_block:R.object({kind:R.literal(`block`),comment:Lm,lines:R.array(z).describe(`Sequence of expressions evaluated in order. The block's value is the LAST line's value (an empty block returns void). Earlier lines run for their side effects (set, fns.fetch, etc.).`)}),Expr_define:R.object({kind:R.literal(`define`),comment:Lm,vars:R.array(R.object({name:R.string().describe(`Variable name. Must NOT be a reserved name (args, recurse, this, super, key, value, yield, error) and must NOT shadow anything already in scope.`),type:Im.optional().describe("Optional declared type. OMIT this field when the value already determines the type — every value Expr (`new`, `get`, `if`, ...) is typed, and the var inherits that type. Set this only when you need to widen / narrow / annotate beyond what the value alone produces; a mismatch with the value's inferred type is reported as `define.var.type-mismatch`."),value:z.describe("The expression whose result is bound under `name`. May reference any earlier var in this define — each var is added to scope before the next var's value is evaluated.")})).describe("Bindings introduced before `body`. Evaluated sequentially, so `vars[i].value` may reference any of `vars[0..i-1]`."),body:z}),Expr_flow:R.object({kind:R.literal(`flow`),action:R.enum([`break`,`continue`,`return`,`exit`,`throw`]).describe("Which control-flow signal to raise. `break`/`continue` only valid inside a loop. `return` only valid inside a fn body / lambda; unwinds to the enclosing call with `value`. `exit` unwinds all the way to `engine.run`, returning `value` as the program result. `throw` raises `error` (caught by a path step's `catch:` handler)."),value:z.optional().describe("Required for `return` and `exit` (the value being returned). Ignored by `break` / `continue` / `throw`."),error:z.optional().describe("Required for `throw` — the value to raise. Ignored otherwise.")}),Expr_get:R.object({kind:R.literal(`get`),path:R.array(R.ref(`PathStep`)).describe('Steps walked left-to-right starting from a scope variable. Step shapes: `{prop:"name"}` for prop/method access, `{args:{…}}` to call the previous step, `{key:Expr}` for index access. The first step MUST be a prop step (the scope-var name). A step names exactly ONE shape — a call is its own step, so a method with arguments is `[{"prop":"m"},{"args":{…}}]` and never `{"prop":"m","args":{…}}`. Result is the final step\'s value.')}),Expr_if:R.object({kind:R.literal(`if`),comment:Lm,ifs:R.array(R.object({condition:z.describe("Bool-typed expression. First branch whose condition is `true` wins; the rest are skipped."),body:z.describe(`Evaluated when this branch's condition is true. The if-expression's value is this body's value.`)})).describe("Ordered list of `{condition, body}` branches — first true condition wins. Each `condition` must be bool-typed (warned otherwise). With multiple branches this is the gin equivalent of `if / else if / else if`."),else:z.optional().describe("Optional fallback evaluated when every `ifs[i].condition` is false. Without an else, a no-match if-expression evaluates to void.")}),Expr_lambda:R.object({kind:R.literal(`lambda`),comment:Lm,type:Im.describe('The lambda\'s function type — `{ name: "fn", call: { args, returns } }` (or a registered named fn type). The `args` obj defines what the body sees under the `args` scope variable; `returns` is what the body must produce.'),body:z.describe('The lambda body. At runtime, scope contains the lexical scope at definition site PLUS `args` (the call arguments) and `recurse` (this same lambda, for self-calls). Read params via `[{prop:"args"},{prop:"<name>"}]`.'),constraint:z.optional().describe("Optional bool-typed precondition evaluated before the body on every call (with `args` in scope). If it returns false, the call throws. Use for input invariants you want enforced regardless of caller.")}),Expr_loop:R.object({kind:R.literal(`loop`),comment:Lm,over:z.describe("The iterable expression. Two evaluation modes: (1) iterable types (list, map, etc. — anything whose `get().loop` is defined) iterate once; the expression is evaluated ONCE at the start. (2) bool — while-loop semantics: the expression is RE-EVALUATED each iteration; the loop continues while the value is `true` and exits the moment it becomes `false`. Use `flow:break` / `flow:continue` inside the body to control iteration regardless of mode."),body:z.describe("Evaluated once per iteration with the current `key` and `value` bound in scope. Use `{kind:'flow', action:'break'}` or `'continue'` for early-exit. The loop expression itself returns void."),key:R.string().optional().describe("Override the scope-variable name the iteration index/key is bound under (default: `key`). Must NOT be reserved or shadow an outer scope var. Use to disambiguate when looping inside another loop."),value:R.string().optional().describe("Override the scope-variable name the iteration value is bound under (default: `value`). Same rules as `key`."),parallel:R.object({concurrent:z.optional().describe(`Max in-flight iterations as a num (omit / 1 → strictly sequential). Use when iterations are independent I/O — e.g. fetching N URLs concurrently.`),rate:z.optional().describe(`Minimum interval between iteration starts. Accepts a num (milliseconds) or a duration. Use to rate-limit fan-out (e.g. avoid hammering an API).`)}).optional().describe("Opt-in parallelism. Both fields are optional and independent: `concurrent` caps fan-out width, `rate` paces start times. Iterations may finish out of order; the body should not assume sequential ordering. Composes with dynamic (bool while-loop) iteration: the body fans out up to `concurrent`, and `over` is re-evaluated against the outer scope each time a task completes — so accumulating side effects of earlier tasks decide whether more tasks spawn.")}),Expr_native:R.object({kind:R.literal(`native`),comment:Lm,id:R.string().describe("Identifier of a native impl registered via `registry.setNative(id, fn)` (e.g. `list.push`, `num.add`). The model should NOT generate `native` expressions directly — methods on built-in types are reached via `get` paths, which gin resolves to natives internally."),type:Im.optional().describe("Optional type to wrap the native's raw return value with when the impl returns a non-Value. Defaults to `any` if omitted.")}),Expr_set:R.object({kind:R.literal(`set`),comment:Lm,path:R.array(R.ref(`PathStep`)).describe('Steps walked left-to-right to a writable target. Single-step `[{prop:"x"}]` re-assigns scope variable `x`. Multi-step targets need the type to support set on the final step (a prop with a `set` ExprDef, an indexed slot, or a method whose call has `set:`).'),value:z.describe("The expression evaluated and assigned to the path target. Its type must be compatible with the target's declared type — checked statically as `set.type-mismatch`.")}),Expr_switch:R.object({kind:R.literal(`switch`),comment:Lm,value:z.describe("Expression whose result is compared against each case's `equals` candidates. Evaluated once."),cases:R.array(R.object({equals:R.array(z).describe("Candidate values for this case. The case wins if `value` equals ANY one of them (logical OR). Each candidate's type must be compatible with `value`'s type — checked as `switch.case.type`."),body:z.describe(`Evaluated when this case wins. The switch expression's value is this body's value.`)})).describe(`Ordered list of cases — first match wins. Cases are NOT fall-through; only the matching case's body runs.`),else:z.optional().describe(`Optional fallback evaluated when no case matches. Without an else, a no-match switch evaluates to void.`)}),Expr_template:R.object({kind:R.literal(`template`),template:R.union([z,R.string()]).describe("The template string — either a literal string (auto-wrapped as `new text`) or an Expr that evaluates to text. Placeholders use `{name}` syntax; each `name` is looked up first in `params` (when supplied) and then in the surrounding scope."),params:z.optional().describe("Optional obj-typed expression supplying placeholder values. When omitted or when a key is missing, `{name}` falls back to a scope lookup of the same name — so a `${baseUrl}` placeholder resolves to a surrounding `define baseUrl = ...`. Provide `params` only when placeholders need values not already in scope (or to override scope values).")})},Hm=[`new`,`get`,`set`,`define`,`block`,`if`,`switch`,`loop`,`lambda`,`template`,`flow`,`native`],Um={any:R.unknown(),void:R.null(),null:R.null(),bool:R.boolean(),num:R.number(),text:R.string(),list:R.array(z),map:R.array(R.object({key:z,value:z})),tuple:R.array(z),obj:R.record(z),optional:z,nullable:R.nullable(z),not:R.unknown(),or:z,and:z,enum:R.union([R.string(),R.number()]),literal:R.unknown(),fn:R.union([R.string(),R.object({kind:R.string()})]),interface:R.record(z),typ:Im,date:R.string().pattern(`^\\d{4}-\\d{2}-\\d{2}`),timestamp:R.string().pattern(`^\\d{4}-\\d{2}-\\d{2}[T ]\\d{2}:\\d{2}(:\\d{2}(\\.\\d+)?)?(Z|[+-]\\d{2}:?\\d{2})?$`),duration:R.object({days:R.number().optional(),hours:R.number().optional(),minutes:R.number().optional(),seconds:R.number().optional(),ms:R.number().optional()}),color:R.object({r:R.int().min(0).max(255),g:R.int().min(0).max(255),b:R.int().min(0).max(255),a:R.number().min(0).max(1).optional()})},Wm=(e,t,n)=>R.object({kind:R.literal(`new`),type:t.describe(`Full TypeDef for a \`${e}\` instance (name + options + per-class fields).`),value:R.optional(n).describe(`Initial value matching this \`${e}\` instance. Composites accept Expr slots; primitives accept their raw form.`)}),Gm=Object.fromEntries(zm.map(e=>[`New_${e}`,Wm(e,R.ref(jm[e]),Um[e])])),Km=R.object({kind:R.literal(`new`),type:Im.describe("TypeDef of the value being constructed. The `value` field is interpreted relative to this type — primitives take their raw form (`new num` → number), composites take Expr slots (`new list` → Expr[])."),value:R.unknown().optional().describe("Initial value matching `type`. Optional when the type has a defined `init` constructor or a sensible default (empty list, zero num with no constraints, etc.).")}),qm=new Set([...Object.keys(Rm),...Object.keys(Bm),...Object.keys(Vm),...Object.keys(Gm),`TypeDef`,`Type_Extension`,`Expr_new`,`Expr`]),Jm=(e,t)=>t.length===0?R.never():t.length===1?t[0]:R.discriminatedUnion(e,t);function Ym(e,t){let n=new Map;for(let e of t?.types??[])n.set(e.name,e);for(let t of e.namedTypeList())n.has(t.name)||n.set(t.name,t);return n}function Xm(e,t){let n=Ym(e,t),r=[...n.keys()],i=e.typeClasses(),a=[...r.map(e=>R.object({name:R.literal(e)}).describe(`The registered named type \`${e}\`, by name.`)),...i.map(t=>Nm(e,t.NAME)),R.ref(`Type_Extension`)];t?.namedRefs&&a.push(Pm());let o=Fm([...i.map(e=>e.NAME),...r]),s=e.exprClassList().map(e=>Hm.includes(e.KIND)&&e.KIND!==`new`?R.ref(`Expr_${e.KIND}`):e.KIND===`new`?R.ref(`Expr_new`):e.toA?.()??R.object({kind:R.literal(e.KIND)}).describe(`A \`${e.KIND}\` expression.`)),c=Km,l={};if(t?.newStrict){let t=[...n].map(([e,t])=>{let r=R.object({kind:R.literal(`new`),type:R.object({name:R.literal(e)}).describe(`Reference to the registered named type \`${e}\` \u2014 name-only, the registry resolves it to its full definition.`),value:R.optional(t.toNewA()).describe(`Initial value for the new \`${e}\` instance. Each composite slot accepts an Expr (Get, NewExpr, etc.); per-slot type correctness is enforced at runtime.`)});return qm.has(`New_${e}`)||n.has(`New_${e}`)?r:(l[`New_${e}`]=r,R.ref(`New_${e}`))}),r=i.map(t=>jm[t.NAME]!==void 0&&zm.includes(t.NAME)?R.ref(`New_${t.NAME}`):Wm(t.NAME,Nm(e,t.NAME),t.toNewA?.()??R.unknown()));c=R.union([...t,...r])}let u={};for(let[e,t]of n)qm.has(e)||(u[e]=t.defineA({includeDocs:`all`}));return{...u,...l,TypeDef:Jm(`name`,a),Type_Extension:o,Expr_new:c,Expr:Jm(`kind`,s)}}var Zm=new WeakMap,Qm=0,$m=e=>{let t=Zm.get(e);return t===void 0&&Zm.set(e,t=++Qm),t},eh=(e,t)=>`${$m(e)}:${e.version}|${t?.newStrict?`s`:``}${t?.namedRefs?`r`:``}|${(t?.types??[]).map(e=>e.name).join(`,`)}`,th=R.define(Rm).define(Bm).define(Vm).define(Gm).declare(),nh=th.dynamic((e,t)=>Xm(e,t),{key:eh,cacheSize:8});nh.result(`TypeDef`),nh.result(`Expr`);var rh=class{list=[];stack=[];enter(e){return Array.isArray(e)?this.stack.push(...e):this.stack.push(e),this}leave(e=1){return this.stack.length=Math.max(0,this.stack.length-e),this}at(e,t){let n=Array.isArray(e)?e.length:1;this.enter(e);try{return t()}finally{this.leave(n)}}push(e,t,n=`error`,r){this.list.push({path:this.stack.slice(),code:e,message:t,severity:n,source:r})}error(e,t,n){this.push(e,t,`error`,n)}warn(e,t,n){this.push(e,t,`warning`,n)}info(e,t,n){this.push(e,t,`info`,n)}get hasErrors(){return this.list.some(e=>e.severity===`error`)}},ih=class extends Error{constructor(e){super(`${e.code}: ${e.message} at ${e.path.join(`.`)}`),this.problem=e,this.name=`TypeError`}problem},B={NONE:0,STATE:1,SYSTEM:2,EXTERNAL:4};function ah(...e){let t=B.NONE;for(let n of e)t|=n;return t}var V=class e{constructor(e,t=[]){this.text=e,this.spans=t}text;spans;toString(){return this.text}concat(t){if(typeof t==`string`)return new e(this.text+t,this.spans);let n=this.text.length,r=t.spans.map(e=>({...e,start:e.start+n,end:e.end+n}));return new e(this.text+t.text,[...this.spans,...r])}indent(t){if(!t||!this.text.includes(`
|
|
72
72
|
`))return this;let n=this.text.length,r=new Int32Array(n+1),i=0;for(let e=0;e<n;e++)r[e]=i,this.text[e]===`
|
|
73
73
|
`&&(i+=t.length);r[n]=i;let a=this.text.replace(/\n/g,`
|
|
74
|
-
${t}`),o=this.spans.map(e=>({...e,start:e.start+r[e.start],end:e.end+r[e.end]}));return new e(a,o)}static jsonObject(t,n,r=0,i=2){let a=t.filter(e=>e.value!==void 0);if(a.length===0)return
|
|
75
|
-
`)}\n${s}}`,n)}static jsonArray(t,n,r=0,i=2){if(t.length===0)return
|
|
76
|
-
`)}\n${o}]`,n)}static jsonString(e){return JSON.stringify(e)}formatProblems(e,t={}){return
|
|
77
|
-
`),n=0;for(let r=0;r<t.length;r++){let i=t[r],a=n,o=n+i.length,s=[];for(let e of this.spans){if(e.end<=a||e.start>=o)continue;let t=Math.max(e.start,a)-a,n=Math.min(e.end,o)-a;s.push({...e,start:t,end:n})}e.push({text:i,spans:s,lineNum:r+1}),n=o+1}return e}};function
|
|
78
|
-
`)}var
|
|
74
|
+
${t}`),o=this.spans.map(e=>({...e,start:e.start+r[e.start],end:e.end+r[e.end]}));return new e(a,o)}static jsonObject(t,n,r=0,i=2){let a=t.filter(e=>e.value!==void 0);if(a.length===0)return oh(`{}`,n);let o=` `.repeat((r+1)*i),s=` `.repeat(r*i);return oh(H`{\n${sh(a.map(({key:t,value:n})=>{let r=typeof n==`string`?new e(n):n;return H`${o}${JSON.stringify(t)}: ${r}`}),`,
|
|
75
|
+
`)}\n${s}}`,n)}static jsonArray(t,n,r=0,i=2){if(t.length===0)return oh(`[]`,n);let a=` `.repeat((r+1)*i),o=` `.repeat(r*i);return oh(H`[\n${sh(t.map(t=>{let n=typeof t==`string`?new e(t):t;return H`${a}${n}`}),`,
|
|
76
|
+
`)}\n${o}]`,n)}static jsonString(e){return JSON.stringify(e)}formatProblems(e,t={}){return fh(this,e.list,t)}formatProblem(e,t={}){return fh(this,[e],{...t,sectionHeaders:!1,lineNumbers:!1,contextLines:0})}spanFor(e){let t,n=-1,r=1/0;for(let i of this.spans){if(!gh(i.path,e))continue;let a=i.end-i.start;(i.path.length>n||i.path.length===n&&a<r)&&(t=i,n=i.path.length,r=a)}return t}toLines(){let e=[],t=this.text.split(`
|
|
77
|
+
`),n=0;for(let r=0;r<t.length;r++){let i=t[r],a=n,o=n+i.length,s=[];for(let e of this.spans){if(e.end<=a||e.start>=o)continue;let t=Math.max(e.start,a)-a,n=Math.min(e.end,o)-a;s.push({...e,start:t,end:n})}e.push({text:i,spans:s,lineNum:r+1}),n=o+1}return e}};function oh(e,t){let n=typeof e==`string`?new V(e):e,r={start:0,end:n.text.length,path:t.path,expr:t.expr,type:t.type};return new V(n.text,[r,...n.spans])}function H(e,...t){let n=``,r=[];for(let i=0;i<e.length;i++)if(n+=e[i],i<t.length){let e=t[i];if(typeof e==`string`)n+=e;else{let t=n.length;n+=e.text;for(let n of e.spans)r.push({...n,start:n.start+t,end:n.end+t})}}return new V(n,r)}function sh(e,t=``){if(e.length===0)return new V(``);let n=typeof t==`string`?new V(t):t,r=typeof e[0]==`string`?new V(e[0]):e[0];for(let t=1;t<e.length;t++)r=r.concat(n).concat(e[t]);return r}function ch(e){return sh(e,`
|
|
78
|
+
`)}var lh={reset:`\x1B[0m`,bold:`\x1B[1m`,dim:`\x1B[2m`,red:`\x1B[31m`,yellow:`\x1B[33m`,blue:`\x1B[34m`,cyan:`\x1B[36m`},uh={error:`error`,warning:`warning`,info:`info`},dh={error:lh.red,warning:lh.yellow,info:lh.blue};function fh(e,t,n){if(t.length===0)return``;let r=n.color??!1,i=n.contextLines??2,a=n.sectionHeaders??!0,o=n.lineNumbers??!0,s=n.maxProblems??1/0,c=(e,t)=>r?`${e}${t}${lh.reset}`:t,l=e.toLines(),u=[],d=[],f=0;for(let n=0;n<t.length;n++){if(n>=s){f=t.length-n;break}let r=t[n],i=ph(e,l,r);if(i)u.push(i);else{let e=dh[r.severity],t=`${uh[r.severity]}:`,n=r.path.length>0?` @ ${r.path.join(`.`)}`:``;d.push(`${c(e,t)} ${r.message}${n}`)}}let p=mh(u,l.length,i),m=l.length,h=o?String(m).length:0,ee=p.map(e=>hh(e,l,{color:r,sectionHeaders:a,lineNumbers:o,gutterWidth:h,c}));return d.length>0&&ee.push(d.join(`
|
|
79
79
|
`)),f>0&&ee.push(`\u2026 (${f} more problem${f===1?``:`s`} suppressed)`),ee.join(`
|
|
80
80
|
|
|
81
|
-
`)}function
|
|
82
|
-
`)}function
|
|
83
|
-
`:`/* ${this.comment} */ `}withCommentOn(e){return this.comment?{...e,comment:this.comment}:e}validate(e,t){let n=new
|
|
84
|
-
${
|
|
81
|
+
`)}function ph(e,t,n){let r=e.spanFor(n.path);if(!r)return null;let i=new Map,a=0,o=-1,s=-1;for(let e=0;e<t.length;e++){let n=t[e].text,c=a,l=a+n.length;if(r.end>c&&r.start<=l){let t=Math.max(r.start,c)-c,n=Math.min(r.end,l)-c;i.set(e,{startCol:t,endCol:n}),o<0&&(o=e),s=e}a=l+1}return o<0?null:{problem:n,firstLine:o,lastLine:s,hits:i}}function mh(e,t,n){if(e.length===0)return[];let r=[...e].sort((e,t)=>e.firstLine-t.firstLine),i=[];for(let e of r){let r=Math.max(0,e.firstLine-n),a=Math.min(t-1,e.lastLine+n),o=i[i.length-1];o&&r<=o.lastLine+1?(o.lastLine=Math.max(o.lastLine,a),o.problems.push(e)):i.push({firstLine:r,lastLine:a,problems:[e]})}return i}function hh(e,t,n){let{color:r,sectionHeaders:i,lineNumbers:a,gutterWidth:o,c:s}=n,c=[],l=e=>a?s(lh.dim,`${String(e).padStart(o)} \u2502 `):``,u=()=>a?s(lh.dim,`${` `.repeat(o)} \u2502 `):``;if(i){let t=e.firstLine===e.lastLine?`line ${e.firstLine+1}`:`lines ${e.firstLine+1}-${e.lastLine+1}`,n=`─`.repeat(Math.max(3,60-t.length-4));c.push(s(lh.dim,`\u2500\u2500 ${t} ${n}`))}let d={error:0,warning:1,info:2};for(let n=e.firstLine;n<=e.lastLine;n++){c.push(l(n+1)+t[n].text);let r=new Map;for(let t of e.problems){let e=t.hits.get(n);if(!e)continue;let i=`${e.startCol}:${e.endCol}`,a=r.get(i);(!a||d[t.problem.severity]<d[a])&&r.set(i,t.problem.severity)}for(let[e,t]of r){let[n,r]=e.split(`:`),i=Number(n),a=Number(r),o=` `.repeat(i)+`^`.repeat(Math.max(1,a-i));c.push(u()+s(dh[t],o))}for(let t of e.problems){if(t.lastLine!==n)continue;let e=t.problem.severity,r=s(dh[e],`${uh[e]}:`);c.push(u()+`${r} ${t.problem.message}`)}}return c.join(`
|
|
82
|
+
`)}function gh(e,t){if(e.length>t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function _h(e){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}var vh=new WeakMap,yh=0,bh=e=>{let t=vh.get(e);return t===void 0&&vh.set(e,t=++yh),t},xh=new WeakMap;function Sh(e){let t=xh.get(e);return t===void 0&&(t=e instanceof Ch?`${Sh(e.parent)}/${bh(e.bindingsRecord)}`:String(bh(e)),xh.set(e,t)),t}var Ch=class{parent;registry;local;constructor(e,t={}){this.parent=e,this.registry=e.registry,this.local=t}lookup(e){return this.local[e]??this.parent.lookup(e)}localLookup(e){return this.local[e]}get bindingsRecord(){return this.local}parse(e){return this.registry.parse(e,this)}parseExpr(e){return this.registry.parseExpr(e,this)}bind(e,t){this.local[e]=t}ownNames(){return Object.keys(this.local)}},wh=class e{comment;withComment(e){return e&&(this.comment=e),this}useLineComment(e={}){return e.expectsValue===!1}commentPrefix(e={}){return!this.comment||e.includeComments===!1?``:this.useLineComment(e)?`// ${this.comment}
|
|
83
|
+
`:`/* ${this.comment} */ `}withCommentOn(e){return this.comment?{...e,comment:this.comment}:e}validate(e,t){let n=new rh,r=t??e.globalTypeScope();return this.validateWalk(e,r,n,{inLoop:!1,inLambda:!1}),n}toCode(e,t){return this.toGinCode(e,t).toString()}toGinCode(e,t,n=[]){return oh(this._toCodeFallback(e,t),{path:n,expr:this})}renderStatementBody(e,t={},n=!1){let r=this.kind;if(r===`flow`)return`${this.toCode(e,{...t,expectsValue:!1})};`;if(n&&r===`if`)return this.toCode(e,{...t,expectsValue:!1});if(r===`block`){let n=this.toCode(e,{...t,expectsValue:!1});return n.startsWith(`{`)?n:`{
|
|
84
|
+
${Th(n)}
|
|
85
85
|
}`}return r===`if`||r===`switch`||r===`loop`?`{
|
|
86
|
-
${
|
|
86
|
+
${Th(this.toCode(e,{...t,expectsValue:!1}))}
|
|
87
87
|
}`:`{
|
|
88
|
-
${
|
|
88
|
+
${Th(this.toCode(e,{...t,expectsValue:!0}))};
|
|
89
89
|
}`}renderStatementBodyRich(e,t={},n=[],r=!1){let i=this.kind;if(i===`flow`)return H`${this.toGinCode(e,{...t,expectsValue:!1},n)};`;if(r&&i===`if`)return this.toGinCode(e,{...t,expectsValue:!1},n);if(i===`block`){let r=this.toGinCode(e,{...t,expectsValue:!1},n);return r.text.startsWith(`{`)?r:H`{\n ${r.indent(` `)}\n}`}return i===`if`||i===`switch`||i===`loop`?H`{\n ${this.toGinCode(e,{...t,expectsValue:!1},n).indent(` `)}\n}`:H`{\n ${this.toGinCode(e,{...t,expectsValue:!0},n).indent(` `)};\n}`}toJSONCode(e=[],t=2,n=0){let r=JSON.stringify(this.toJSON(),null,t);if(n>0){let e=` `.repeat(n*t);r=r.replace(/\n/g,`
|
|
90
|
-
`+e)}return
|
|
91
|
-
`)}var rh=new Set([`args`,`recurse`,`this`,`super`,`key`,`value`,`yield`,`error`]),ih=class e{parent;vars;control;constructor(e=null,t,n){this.parent=e,this.vars=new Map(t?Object.entries(t):[]),this.control=n??e?.control}async checkpoint(){this.control&&await this.control.checkpoint()}get(e){let t=this.vars.get(e);return t===void 0?this.parent?.get(e):t}set(e,t){this.vars.has(e)?this.vars.set(e,t):this.parent&&this.parent.has(e)?this.parent.set(e,t):this.vars.set(e,t)}has(e){return this.vars.has(e)?!0:this.parent?.has(e)??!1}child(t){return new e(this,t)}names(){let e=new Set;for(let t=this;t;t=t.parent)for(let n of t.vars.keys())e.add(n);return[...e]}};function ah(e,t,n){let r=t instanceof th?t:oh(e,t);return r?r.typeOf(e,n):e.registry.any()}function oh(e,t){try{return e.registry.parseExpr(t)}catch{return}}function sh(e,t,n,r={inLoop:!1,inLambda:!1}){let i=new Pm;return ch(e,t,n,i,r),i}function ch(e,t,n,r,i){let a;if(t instanceof th)a=t;else try{a=e.registry.parseExpr(t)}catch{return r.warn(`expr.unknown-kind`,`unknown expr kind '${t.kind}'`),e.registry.any()}return a.validateWalk(e,n,r,i)}function lh(e,t,n){rh.has(e)?n.error(`binding.reserved`,`'${e}' is a reserved name (gin binds it automatically in fn/loop/path contexts) \u2014 pick a different name`):t.has(e)&&n.error(`binding.shadow`,`'${e}' is already in scope \u2014 pick a different name to avoid shadowing`)}var uh=class{constructor(e){this.action=e}action},dh=class extends uh{constructor(){super(`break`)}},fh=class extends uh{constructor(){super(`continue`)}},ph=class extends uh{constructor(e){super(`return`),this.value=e}value},mh=class extends uh{constructor(e){super(`exit`),this.value=e}value},hh=class extends uh{constructor(e){super(`throw`),this.error=e}error};function gh(e,t){let n=new bh(t);n.type(e,yh);let r=new Set(n.defines);return{refs:n.refs.filter(e=>!r.has(e)),defines:n.defines}}function _h(e,t,n){let r=new Map,i=[],a=[],o=new Map,s=new Set;for(let n of e)for(let e of gh(n,t).defines)s.add(e);let c=e=>{if(o.has(e)||s.has(e))return;let l=n(e);if(!l)o.set(e,`done`),i.push(e);else{o.set(e,`visiting`),r.set(e,l);for(let e of gh(l,t).refs)c(e);o.set(e,`done`),a.push(e)}};for(let n of e)for(let e of gh(n,t).refs)c(e);return{order:a,defs:r,missing:i}}var vh=new Set([`enum`,`literal`]),yh=new Set,bh=class{constructor(e){this.registry=e}registry;refs=[];defines=[];seenRefs=new Set;seenDefines=new Set;type(e,t){let n=this.registry.typeClass(e.name),r=e.extends!==void 0||n?.declaresGenerics===!0;e.extends===void 0?n||this.name(e.name,t):(this.define(e.name),this.name(e.extends,t));for(let n of e.satisfies??[])this.name(n,t);let i=r&&e.generic?Ch(t,Object.keys(e.generic)):t;for(let t of Object.values(e.generic??{}))this.type(t,i);n&&vh.has(n.NAME)||this.options(e.options,i);for(let t of Object.values(e.props??{}))this.prop(t,i);e.get&&this.getSet(e.get,i),e.call&&this.call(e.call,i),e.init&&(this.type(e.init.args,i),this.expr(e.init.run,i)),e.constraint&&this.expr(e.constraint,i)}name(e,t){t.has(e)||this.registry.typeClass(e)||this.seenRefs.has(e)||(this.seenRefs.add(e),this.refs.push(e))}define(e){this.seenDefines.has(e)||(this.seenDefines.add(e),this.defines.push(e))}options(e,t){if(xh(e))for(let n of Object.values(e))if(Array.isArray(n))for(let e of n)Sh(e)&&this.type(e,t);else Sh(n)&&this.type(n,t)}prop(e,t){this.type(e.type,t),this.expr(e.get,t),this.expr(e.set,t),this.expr(e.default,t)}getSet(e,t){this.type(e.key,t),this.type(e.value,t),this.expr(e.get,t),this.expr(e.set,t),this.expr(e.loop,t)}call(e,t){let n=t;for(let[t,r]of Object.entries(e.types??{}))this.type(r,n),n=Ch(n,[t]);this.type(e.args,n),e.returns&&this.type(e.returns,n),e.throws&&this.type(e.throws,n),this.expr(e.get,n),this.expr(e.set,n)}expr(e,t){if(Array.isArray(e)){for(let n of e)this.expr(n,t);return}if(!xh(e))return;let n=Sh(e.type)&&this.registry.typeClass(e.type.name)?.valuesAreTypes===!0;for(let[r,i]of Object.entries(e))if(r===`type`&&Sh(i))this.type(i,t);else if(r===`generic`&&xh(i))for(let e of Object.values(i))Sh(e)&&this.type(e,t);else r===`value`?n&&Sh(i)?this.type(i,t):this.data(i,t):this.expr(i,t)}data(e,t){if(Array.isArray(e))for(let n of e)this.data(n,t);else if(xh(e)){if(this.isExpr(e))this.expr(e,t);else for(let n of Object.values(e))this.data(n,t)}}isExpr(e){return typeof e.kind==`string`&&this.registry.exprClass(e.kind)!==void 0}};function xh(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Sh(e){return xh(e)&&typeof e.name==`string`}function Ch(e,t){return t.length===0?e:new Set([...e,...t])}function wh(e,t,n){if(e===t||e.compatible(t,void 0,n))return!0;for(let r=Th(t);r;r=Th(r))if(e.compatible(r,void 0,n))return!0;return!1}function Th(e){let t=e.base;return t instanceof U&&t!==e?t:void 0}function Eh(e){if(e.name!==`or`)return;let t=e.variants;if(Array.isArray(t)&&t.every(e=>e instanceof U))return t}function Dh(e){if(e.name!==`and`)return;let t=e.parts;if(Array.isArray(t)&&t.every(e=>e instanceof U))return t}function Oh(e,t,n){let r=e.type.encodeAs(e.raw,t,n);return t.form===`logical`?r:{type:e.type.toJSONRef(t),value:r}}function kh(e,t,n,r,i){n instanceof W&&n.raw!==void 0&&(e[t]=Oh(n,r,i))}var Ah={form:`envelope`,typeRefs:`definition`};function jh(e){return!!e&&typeof e==`object`&&!Array.isArray(e)&&!(e instanceof W)}function Mh(e,t){if(!e||typeof e!=`object`||Array.isArray(e))return;let n=e.kind;if(typeof n==`string`&&t.registry.exprClass(n))try{return t.registry.parseExpr(e,t)}catch{return}}var Nh=class e{type;get;set;default;docs;constructor(e){this.type=e.type,this.get=e.get,this.set=e.set,this.default=e.default,this.docs=e.docs}static from(t,n,r){if(t instanceof U)return new e({type:t});t instanceof e||Kp(r?`prop '${r}'`:`prop`,t,Vp,rm,n?.registry);let i=t.type,a=i instanceof U?i:(()=>{if(!n)throw Error(`Prop.from: type is TypeDef but no scope provided to parse it`);return n.parse(i)})(),o=e=>e instanceof th?e:n?.parseExpr(e),s=o(t.get),c=o(t.set),l=o(t.default);return t instanceof e&&t.type===a&&t.get===s&&t.set===c&&t.default===l?t:new e({type:a,get:s,set:c,default:l,docs:t.docs})}static fromMap(t,n){let r={};for(let[i,a]of Object.entries(t))r[i]=e.from(a,n,i);return r}static toJSONMap(t){let n={};for(let[r,i]of Object.entries(t))n[r]=e.from(i).toJSON();return n}toJSON(){return Jm({docs:this.docs,type:this.type.toJSON(),get:this.get?.toJSON(),default:this.default?.toJSON(),set:this.set?.toJSON()})}async read(e,t,n,r,i=this.type){if(this.get){let i={this:e},a=e.type.propSuperFor(e,t,`get`,n,r);return a&&(i.super=a),this.get.evaluate(r,n.child(i))}return e.type.propGet(e,t,i)}async write(e,t,n,r,i){if(this.set){let a={this:e,value:n},o=e.type.propSuperFor(e,t,`set`,r,i);o&&(a.super=o),await this.set.evaluate(i,r.child(a))}else{if(this.get&&!this.type.call())throw Error(`path: prop '${t}' is computed (has 'get', no 'set') \u2014 cannot assign to it`);e.type.propSet(e,t,n)}}async invokeMethod(e,t,n,r,i,a){let o=a??this.type;if(!this.get){let a=e.raw?.[t],o=a instanceof W?a.raw:a;if(typeof o==`function`)return await o(n);if(o&&typeof o==`object`&&`kind`in o){let e=await i.evaluate(o,r);if(typeof e.raw==`function`)return await e.raw(n)}throw Error(`path: callable prop '${t}' has no get expression and raw is not a callable`)}let s=this.get,c=async n=>{let a={this:e,args:n,recurse:new W(o,c)},l=e.type.propSuperFor(e,t,`get`,r,i);l&&(a.super=l);try{return await s.evaluate(i,r.child(a))}catch(e){if(e instanceof ph)return e.value??new W(i.registry.void(),void 0);throw e}};return c(n)}async invokeMethodSet(e,t,n,r,i,a,o){let s=o??this.type,c=s.call?.();if(!c?.set)throw Error(`path: method '${t}' has no call.set`);let l=async n=>{let o={this:e,args:n,value:r,recurse:new W(s,l)},u=e.type.propSuperFor(e,t,`callSet`,i,a);return u&&(o.super=u),await c.set.evaluate(a,i.child(o)),G(a.registry.void(),void 0)};await l(n)}},Ph=class e{key;value;get;set;loop;loopDynamic;docs;constructor(e){this.key=e.key,this.value=e.value,this.get=e.get,this.set=e.set,this.loop=e.loop,this.loopDynamic=e.loopDynamic,this.docs=e.docs}static from(t,n){t instanceof e||Kp(`get/set surface`,t,Hp);let r=t.key,i=t.value,a=r instanceof U?r:(()=>{if(!n)throw Error(`GetSet.from: key is TypeDef but no scope provided`);return n.parse(r)})(),o=i instanceof U?i:(()=>{if(!n)throw Error(`GetSet.from: value is TypeDef but no scope provided`);return n.parse(i)})(),s=e=>e instanceof th?e:n?.parseExpr(e),c=s(t.get),l=s(t.set),u=s(t.loop);return t instanceof e&&t.key===a&&t.value===o&&t.get===c&&t.set===l&&t.loop===u?t:new e({key:a,value:o,get:c,set:l,loop:u,loopDynamic:t.loopDynamic,docs:t.docs})}toJSON(){return Jm({docs:this.docs,key:this.key.toJSON(),value:this.value.toJSON(),get:this.get?.toJSON(),set:this.set?.toJSON(),loop:this.loop?.toJSON(),loopDynamic:this.loopDynamic})}async indexRead(e,t,n,r){if(!this.get)throw Error(`path: type '${e.type.name}' has no index get`);let i={this:e,key:t},a=e.type.indexSuperFor(e,`get`,n,r);return a&&(i.super=a),this.get.evaluate(r,n.child(i))}async indexWrite(e,t,n,r,i){if(!this.set)throw Error(`path: type '${e.type.name}' has no index set`);let a={this:e,key:t,value:n},o=e.type.indexSuperFor(e,`set`,r,i);o&&(a.super=o),await this.set.evaluate(i,r.child(a))}},Fh=class e{args;returns;throws;get;set;docs;types;constructor(e){this.args=e.args,this.returns=e.returns,this.throws=e.throws,this.get=e.get,this.set=e.set,this.docs=e.docs,this.types=e.types}static from(t,n){t instanceof e||Kp(`call signature`,t,Up,qp);let r=t.types,i=n,a;if(r&&Object.keys(r).length>0){if(Object.values(r).every(e=>e instanceof U))a=r;else{if(!n)throw Error(`Call.from: types contain TypeDef but no scope provided`);let e=new eh(n);i=e,a={};for(let[t,n]of Object.entries(r)){let r=n instanceof U?n:e.parse(n);e.bind(t,r),a[t]=r}}}let o=t.args,s=t.returns,c=t.throws,l=o instanceof U?o:(()=>{if(!i)throw Error(`Call.from: args is TypeDef but no scope provided`);return i.parse(o)})(),u=s===void 0?void 0:s instanceof U?s:(()=>{if(!i)throw Error(`Call.from: returns is TypeDef but no scope provided`);return i.parse(s)})(),d=c===void 0?void 0:c instanceof U?c:(()=>{if(!i)throw Error(`Call.from: throws is TypeDef but no scope provided`);return i.parse(c)})(),f=e=>e instanceof th?e:i?.parseExpr(e),p=f(t.get),m=f(t.set),h=t.docs;return t instanceof e&&t.args===l&&t.returns===u&&t.throws===d&&t.get===p&&t.set===m&&t.types===a?t:new e({args:l,returns:u,throws:d,get:p,set:m,docs:h,types:a})}toJSON(){let e=this.types&&Object.keys(this.types).length>0?Object.fromEntries(Object.entries(this.types).map(([e,t])=>[e,t.toJSON()])):void 0;return Jm({docs:this.docs,types:e,args:this.args.toJSON(),returns:this.returns?.toJSON(),throws:this.throws?.toJSON(),get:this.get?.toJSON(),set:this.set?.toJSON()})}renderTypes(e){if(!this.types)return``;let t=Object.keys(this.types);return t.length===0?``:`{${Hh(t.map(t=>`${t}: ${this.types[t].toCode(void 0,e)}`),{sep:`; `})}}`}effects(){let e=0;return this.get&&(e|=this.get.effects()),this.set&&(e|=this.set.effects()),e}},Ih=class e{args;run;docs;constructor(e){this.args=e.args,this.run=e.run,this.docs=e.docs}static from(t,n){t instanceof e||Kp(`init constructor`,t,Wp);let r=t.args,i=r instanceof U?r:(()=>{if(!n)throw Error(`Init.from: args is TypeDef but no scope provided`);return n.parse(r)})(),a=t.run,o=a instanceof th?a:(()=>{if(!n)throw Error(`Init.from: run is ExprDef but no scope provided`);return n.parseExpr(a)})();return t instanceof e&&t.args===i&&t.run===o?t:new e({args:i,run:o,docs:t.docs})}toJSON(){return Jm({docs:this.docs,args:this.args.toJSON(),run:this.run.toJSON()})}},U=class e{constructor(e,t,n={}){this.scope=e,this.options=t,this.generic=n}scope;options;generic;get registry(){return this.scope.registry}priority=0;docs;parsesExprValue(e){return!1}encodeAs(e,t,n){return this.encode(e,n)}toJSONRef(e){if(e?.typeRefs!==`name`)return this.toJSON();if(this.registry.lookup(this.name)===this)return{name:this.name};let t=this.toJSON(),n=Object.keys(this.generic);if(n.length===0)return t;let r={...t.generic??{}};for(let t of n)r[t]=this.generic[t].toJSONRef(e);return{...t,generic:r}}toDefinitionJSON(){let e=zh.depth;zh.active++,zh.depth=this.registry.lookup(this.name)===this?0:1;try{return this.toJSON()}finally{zh.active--,zh.depth=e}}references(){return gh(this.toDefinitionJSON(),this.registry)}closure(e=this.scope){return _h([this.toDefinitionJSON()],this.registry,t=>e.lookup(t)?.toDefinitionJSON())}compatibleWithParts(e,t,n){let r=Dh(e);if(!r)return!1;if(r.some(e=>this.compatible(e,t,n)))return!0;let i=e.simplify(n);return i!==e&&this.compatible(i,t,n)}compatible(e,t,n){for(let t=0;e.name===`alias`&&t<8;t++){let t=e.simplify(n);if(t===e)break;e=t}if(e===this)return!0;let r=Lh,i=Rh(t,n),a=r.active.get(this)?.get(e);if(a!==void 0&&a.key===i)return r.lowWater=Math.min(r.lowWater,a.depth),!0;let o=r.memo.get(this)?.get(e)?.get(i);if(o!==void 0)return o;let s=r.depth++,c=r.active.get(this);c||r.active.set(this,c=new Map),c.set(e,{depth:s,key:i});let l=r.lowWater;r.lowWater=1/0;let u=!1;try{let a=Eh(e);if(u=a?a.every(e=>this.compatible(e,t,n)):this.compatibleType(e,t,n)||this.compatibleWithParts(e,t,n)||this.compatibleWithBase(e,t,n),!u||r.lowWater>=s){let t=r.memo.get(this);t||r.memo.set(this,t=new Map);let n=t.get(e);n||t.set(e,n=new Map),n.set(i,u)}return u}finally{c.delete(e),r.lowWater=Math.min(l,r.lowWater),--r.depth===0&&(r.memo=new Map,r.active=new Map,r.lowWater=1/0)}}compatibleWithBase(t,n,r){if(n?.strict||n?.exact)return!1;let i=t.base;return i instanceof e&&i!==t&&this.compatible(i,n,r)}accepts(e,t){return this.compatible(e,{strict:!0},t)}exact(e,t){return this.compatible(e,{strict:!0,exact:!0},t)}flexible(){return!1}like(e,t){return this}isUniversal(){return!1}simplify(e){return this}required(){return this}isOptional(){return!1}props(e){let t={toAny:this.registry.method({},this.registry.any(),`type.toAny`)},n=this.registry.augmentation(this.name);return n?.props?{...t,...n.props}:t}static UNIVERSAL_PROP_NAMES=new Set([`toAny`]);constraints(){return[]}get(e){return this.registry.augmentation(this.name)?.get}call(e){return this.registry.augmentation(this.name)?.call}init(e){return this.registry.augmentation(this.name)?.init}prop(e,t){let n=this.props(t)[e];return n?Nh.from(n):void 0}follow(e,t){if(`prop`in e)return this.prop(e.prop,t)?.type;if(`args`in e)return this.call(t)?.returns;if(`key`in e)return this.get(t)?.value}at(e,t){let n=this;for(let r of e){if(!n)return;n=n.follow(r,t)}return n}toA(e){return e?.override?.(this)||(this.isRegisteredNamed()?R.ref(this.name):this.defineA(e))}defineA(e){return this.describeA(this.valueA(e),e)}valueA(e){return R.unknown()}toNewA(e){let t=this.init(e?.scope);return t?this.describeA(t.args.toA(e),e):this.toA(e)}isRegisteredNamed(){let e=this.registry;return e.typeClass(this.name)===void 0&&e.namedTypeList().includes(this)}objectA(e,t){let n=R.object(e);return t?.unknownKeys===`refuse`?n.strict():n}describeA(e,t){let n=t?.includeDocs??`none`,r=[];n!==`none`&&this.docs&&r.push(this.docs);let i=this.constraints();return i.length>0&&r.push(i.map(e=>`must satisfy ${e.toCode(this.registry,{expectsValue:!0})}`).join(`; `)),r.length>0?e.describe(r.join(` — `)):e}newEffects(e){let t=this.initEffects();return this.forEachNewSlot(e,{slot:(e,n)=>{t|=e.newEffects(n)},missing:e=>{t|=e.effects()}})?t:t|this.exprValueEffects(e)}exprValueEffects(e){if(!e||typeof e!=`object`||Array.isArray(e))return B.NONE;let t=e.kind;if(typeof t!=`string`||!this.registry.exprClass(t))return B.NONE;try{return this.registry.parseExpr(e,this.scope).effects()}catch{return B.NONE}}initEffects(){let e=this.init();if(!e)return B.NONE;try{return this.registry.parseExpr(e.run,this.scope).effects()}catch{return B.NONE}}newComplexity(e){let t=1+this.initComplexity();return this.forEachNewSlot(e,{slot:(e,n)=>{t+=e.elementComplexity(n)},missing:e=>{t+=e.complexity()}})?t:t+this.exprValueComplexity(e)}exprValueComplexity(e){if(!e||typeof e!=`object`||Array.isArray(e))return 0;let t=e.kind;if(typeof t!=`string`||!this.registry.exprClass(t))return 0;try{return this.registry.parseExpr(e,this.scope).complexity()}catch{return 0}}initComplexity(){let e=this.init();if(!e)return 0;try{return this.registry.parseExpr(e.run,this.scope).complexity()}catch{return 0}}elementComplexity(e){let t=this.exprValueComplexity(e);return t>0?t:1}forEachNewSlot(e,t){return!1}validateNewValue(e,t,n,r,i){if(this.forEachNewSlot(e,{slot:(e,a,o)=>{r.at([o],()=>e.validateNewValue(a,t,n,r,i))}}))return;let a=Mh(e,this.scope);if(!a)return;let o=a.validateWalk(t,n,r,i);o.name!==`any`&&(wh(this,o)||r.error(`new.slot.type`,`this slot is declared \`${this.toCode()}\` but the expression here produces \`${o.toCode()}\``))}async newFill(e,t,n){let r=Mh(e,this.scope);return r?r.evaluate(t,n):e}toGinCode(e,t,n=[]){return Lm(this.toCode(e,t),{path:n,type:this})}toJSONCode(e=[],t=2,n=0){return Xh(this.toJSON(),this.registry,e,t,n,this)}docsPrefix(e){return``}extendsClause(e){return``}toCodeRef(e,t){return this.toCode(e,t)}refProps(){return{}}refGet(){}refCall(){}static renderGenerics(e,t){let n=Object.keys(e);return n.length===0?``:`<${Hh(n.map(n=>{let r=e[n],i=r.name===`alias`&&r.options?.name===n;return r.name===`any`||i?n:`${n}: ${r.toCode(void 0,t)}`}),{indent:Uh(t)})}>`}static renderGenericArgs(t,n){let r=Object.keys(t);return r.length===0||!r.some(n=>!e.isGenericPlaceholder(n,t[n]))?``:`<${Hh(r.map(e=>t[e].toCode(void 0,n)),{indent:Uh(n)})}>`}static isGenericPlaceholder(e,t){return t.name===`any`||t.name===`alias`&&t.options?.name===e}static formatParams(e,t,n=`auto`){let r=e.fields;if(!r)return e.name===`void`||e.name===`any`?``:`args: ${e.toCode(void 0,t)}`;let i=Object.entries(r).map(([e,n])=>{let r=n.type.isOptional(),i=r?n.type.required():n.type;return`${n.docs&&t?.includeComments!==!1?`/* ${n.docs} */ `:``}${e}${r?`?`:``}: ${i.toCode(void 0,t)}`}),a=Uh(t);return n===`auto`?Hh(i,{indent:a}):i.length<=1?i.join(``):`
|
|
92
|
-
${i.map(e=>
|
|
90
|
+
`+e)}return oh(r,{path:e,expr:this})}_toCodeFallback(t,n){let r=Object.getPrototypeOf(this).toCode;return r&&r!==e.prototype.toCode?r.call(this,t,n):`<unrendered:${this.kind??`?`}>`}forEachChild(e){}};function Th(e){return e.replace(/\n/g,`
|
|
91
|
+
`)}var Eh=new Set([`args`,`recurse`,`this`,`super`,`key`,`value`,`yield`,`error`]),Dh=class e{parent;vars;control;constructor(e=null,t,n){this.parent=e,this.vars=new Map(t?Object.entries(t):[]),this.control=n??e?.control}async checkpoint(){this.control&&await this.control.checkpoint()}get(e){let t=this.vars.get(e);return t===void 0?this.parent?.get(e):t}set(e,t){this.vars.has(e)?this.vars.set(e,t):this.parent&&this.parent.has(e)?this.parent.set(e,t):this.vars.set(e,t)}has(e){return this.vars.has(e)?!0:this.parent?.has(e)??!1}child(t){return new e(this,t)}names(){let e=new Set;for(let t=this;t;t=t.parent)for(let n of t.vars.keys())e.add(n);return[...e]}};function Oh(e,t,n){let r=t instanceof wh?t:kh(e,t);return r?r.typeOf(e,n):e.registry.any()}function kh(e,t){try{return e.registry.parseExpr(t)}catch{return}}function Ah(e,t,n,r={inLoop:!1,inLambda:!1}){let i=new rh;return jh(e,t,n,i,r),i}function jh(e,t,n,r,i){let a;if(t instanceof wh)a=t;else try{a=e.registry.parseExpr(t)}catch{return r.warn(`expr.unknown-kind`,`unknown expr kind '${t.kind}'`),e.registry.any()}return a.validateWalk(e,n,r,i)}function Mh(e,t,n){Eh.has(e)?n.error(`binding.reserved`,`'${e}' is a reserved name (gin binds it automatically in fn/loop/path contexts) \u2014 pick a different name`):t.has(e)&&n.error(`binding.shadow`,`'${e}' is already in scope \u2014 pick a different name to avoid shadowing`)}var Nh=class{constructor(e){this.action=e}action},Ph=class extends Nh{constructor(){super(`break`)}},Fh=class extends Nh{constructor(){super(`continue`)}},Ih=class extends Nh{constructor(e){super(`return`),this.value=e}value},Lh=class extends Nh{constructor(e){super(`exit`),this.value=e}value},Rh=class extends Nh{constructor(e){super(`throw`),this.error=e}error};function zh(e,t){let n=new Uh(t);n.type(e,Hh);let r=new Set(n.defines);return{refs:n.refs.filter(e=>!r.has(e)),defines:n.defines}}function Bh(e,t,n){let r=new Map,i=[],a=[],o=new Map,s=new Set;for(let n of e)for(let e of zh(n,t).defines)s.add(e);let c=e=>{if(o.has(e)||s.has(e))return;let l=n(e);if(!l)o.set(e,`done`),i.push(e);else{o.set(e,`visiting`),r.set(e,l);for(let e of zh(l,t).refs)c(e);o.set(e,`done`),a.push(e)}};for(let n of e)for(let e of zh(n,t).refs)c(e);return{order:a,defs:r,missing:i}}var Vh=new Set([`enum`,`literal`]),Hh=new Set,Uh=class{constructor(e){this.registry=e}registry;refs=[];defines=[];seenRefs=new Set;seenDefines=new Set;type(e,t){let n=this.registry.typeClass(e.name),r=e.extends!==void 0||n?.declaresGenerics===!0;e.extends===void 0?n||this.name(e.name,t):(this.define(e.name),this.name(e.extends,t));for(let n of e.satisfies??[])this.name(n,t);let i=r&&e.generic?Kh(t,Object.keys(e.generic)):t;for(let t of Object.values(e.generic??{}))this.type(t,i);n&&Vh.has(n.NAME)||this.options(e.options,i);for(let t of Object.values(e.props??{}))this.prop(t,i);e.get&&this.getSet(e.get,i),e.call&&this.call(e.call,i),e.init&&(this.type(e.init.args,i),this.expr(e.init.run,i)),e.constraint&&this.expr(e.constraint,i)}name(e,t){t.has(e)||this.registry.typeClass(e)||this.seenRefs.has(e)||(this.seenRefs.add(e),this.refs.push(e))}define(e){this.seenDefines.has(e)||(this.seenDefines.add(e),this.defines.push(e))}options(e,t){if(Wh(e))for(let n of Object.values(e))if(Array.isArray(n))for(let e of n)Gh(e)&&this.type(e,t);else Gh(n)&&this.type(n,t)}prop(e,t){this.type(e.type,t),this.expr(e.get,t),this.expr(e.set,t),this.expr(e.default,t)}getSet(e,t){this.type(e.key,t),this.type(e.value,t),this.expr(e.get,t),this.expr(e.set,t),this.expr(e.loop,t)}call(e,t){let n=t;for(let[t,r]of Object.entries(e.types??{}))this.type(r,n),n=Kh(n,[t]);this.type(e.args,n),e.returns&&this.type(e.returns,n),e.throws&&this.type(e.throws,n),this.expr(e.get,n),this.expr(e.set,n)}expr(e,t){if(Array.isArray(e)){for(let n of e)this.expr(n,t);return}if(!Wh(e))return;let n=Gh(e.type)&&this.registry.typeClass(e.type.name)?.valuesAreTypes===!0;for(let[r,i]of Object.entries(e))if(r===`type`&&Gh(i))this.type(i,t);else if(r===`generic`&&Wh(i))for(let e of Object.values(i))Gh(e)&&this.type(e,t);else r===`value`?n&&Gh(i)?this.type(i,t):this.data(i,t):this.expr(i,t)}data(e,t){if(Array.isArray(e))for(let n of e)this.data(n,t);else if(Wh(e)){if(this.isExpr(e))this.expr(e,t);else for(let n of Object.values(e))this.data(n,t)}}isExpr(e){return typeof e.kind==`string`&&this.registry.exprClass(e.kind)!==void 0}};function Wh(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Gh(e){return Wh(e)&&typeof e.name==`string`}function Kh(e,t){return t.length===0?e:new Set([...e,...t])}function qh(e,t,n){if(e===t||e.compatible(t,void 0,n))return!0;for(let r=Jh(t);r;r=Jh(r))if(e.compatible(r,void 0,n))return!0;return!1}function Jh(e){let t=e.base;return t instanceof U&&t!==e?t:void 0}function Yh(e){if(e.name!==`or`)return;let t=e.variants;if(Array.isArray(t)&&t.every(e=>e instanceof U))return t}function Xh(e){if(e.name!==`and`)return;let t=e.parts;if(Array.isArray(t)&&t.every(e=>e instanceof U))return t}function Zh(e,t,n){let r=e.type.encodeAs(e.raw,t,n);return t.form===`logical`?r:{type:e.type.toJSONRef(t),value:r}}function Qh(e,t,n,r,i){n instanceof W&&n.raw!==void 0&&(e[t]=Zh(n,r,i))}var $h={form:`envelope`,typeRefs:`definition`};function eg(e){return!!e&&typeof e==`object`&&!Array.isArray(e)&&!(e instanceof W)}function tg(e,t){if(!e||typeof e!=`object`||Array.isArray(e))return;let n=e.kind;if(typeof n==`string`&&t.registry.exprClass(n))try{return t.registry.parseExpr(e,t)}catch{return}}var ng=class e{type;get;set;default;docs;constructor(e){this.type=e.type,this.get=e.get,this.set=e.set,this.default=e.default,this.docs=e.docs}static from(t,n,r){if(t instanceof U)return new e({type:t});t instanceof e||hm(r?`prop '${r}'`:`prop`,t,um,Em,n?.registry);let i=t.type,a=i instanceof U?i:(()=>{if(!n)throw Error(`Prop.from: type is TypeDef but no scope provided to parse it`);return n.parse(i)})(),o=e=>e instanceof wh?e:n?.parseExpr(e),s=o(t.get),c=o(t.set),l=o(t.default);return t instanceof e&&t.type===a&&t.get===s&&t.set===c&&t.default===l?t:new e({type:a,get:s,set:c,default:l,docs:t.docs})}static fromMap(t,n){let r={};for(let[i,a]of Object.entries(t))r[i]=e.from(a,n,i);return r}static toJSONMap(t){let n={};for(let[r,i]of Object.entries(t))n[r]=e.from(i).toJSON();return n}toJSON(){return _h({docs:this.docs,type:this.type.toJSON(),get:this.get?.toJSON(),default:this.default?.toJSON(),set:this.set?.toJSON()})}async read(e,t,n,r,i=this.type){if(this.get){let i={this:e},a=e.type.propSuperFor(e,t,`get`,n,r);return a&&(i.super=a),this.get.evaluate(r,n.child(i))}return e.type.propGet(e,t,i)}async write(e,t,n,r,i){if(this.set){let a={this:e,value:n},o=e.type.propSuperFor(e,t,`set`,r,i);o&&(a.super=o),await this.set.evaluate(i,r.child(a))}else{if(this.get&&!this.type.call())throw Error(`path: prop '${t}' is computed (has 'get', no 'set') \u2014 cannot assign to it`);e.type.propSet(e,t,n)}}async invokeMethod(e,t,n,r,i,a){let o=a??this.type;if(!this.get){let a=e.raw?.[t],o=a instanceof W?a.raw:a;if(typeof o==`function`)return await o(n);if(o&&typeof o==`object`&&`kind`in o){let e=await i.evaluate(o,r);if(typeof e.raw==`function`)return await e.raw(n)}throw Error(`path: callable prop '${t}' has no get expression and raw is not a callable`)}let s=this.get,c=async n=>{let a={this:e,args:n,recurse:new W(o,c)},l=e.type.propSuperFor(e,t,`get`,r,i);l&&(a.super=l);try{return await s.evaluate(i,r.child(a))}catch(e){if(e instanceof Ih)return e.value??new W(i.registry.void(),void 0);throw e}};return c(n)}async invokeMethodSet(e,t,n,r,i,a,o){let s=o??this.type,c=s.call?.();if(!c?.set)throw Error(`path: method '${t}' has no call.set`);let l=async n=>{let o={this:e,args:n,value:r,recurse:new W(s,l)},u=e.type.propSuperFor(e,t,`callSet`,i,a);return u&&(o.super=u),await c.set.evaluate(a,i.child(o)),G(a.registry.void(),void 0)};await l(n)}},rg=class e{key;value;get;set;loop;loopDynamic;docs;constructor(e){this.key=e.key,this.value=e.value,this.get=e.get,this.set=e.set,this.loop=e.loop,this.loopDynamic=e.loopDynamic,this.docs=e.docs}static from(t,n){t instanceof e||hm(`get/set surface`,t,dm);let r=t.key,i=t.value,a=r instanceof U?r:(()=>{if(!n)throw Error(`GetSet.from: key is TypeDef but no scope provided`);return n.parse(r)})(),o=i instanceof U?i:(()=>{if(!n)throw Error(`GetSet.from: value is TypeDef but no scope provided`);return n.parse(i)})(),s=e=>e instanceof wh?e:n?.parseExpr(e),c=s(t.get),l=s(t.set),u=s(t.loop);return t instanceof e&&t.key===a&&t.value===o&&t.get===c&&t.set===l&&t.loop===u?t:new e({key:a,value:o,get:c,set:l,loop:u,loopDynamic:t.loopDynamic,docs:t.docs})}toJSON(){return _h({docs:this.docs,key:this.key.toJSON(),value:this.value.toJSON(),get:this.get?.toJSON(),set:this.set?.toJSON(),loop:this.loop?.toJSON(),loopDynamic:this.loopDynamic})}async indexRead(e,t,n,r){if(!this.get)throw Error(`path: type '${e.type.name}' has no index get`);let i={this:e,key:t},a=e.type.indexSuperFor(e,`get`,n,r);return a&&(i.super=a),this.get.evaluate(r,n.child(i))}async indexWrite(e,t,n,r,i){if(!this.set)throw Error(`path: type '${e.type.name}' has no index set`);let a={this:e,key:t,value:n},o=e.type.indexSuperFor(e,`set`,r,i);o&&(a.super=o),await this.set.evaluate(i,r.child(a))}},ig=class e{args;returns;throws;get;set;docs;types;constructor(e){this.args=e.args,this.returns=e.returns,this.throws=e.throws,this.get=e.get,this.set=e.set,this.docs=e.docs,this.types=e.types}static from(t,n){t instanceof e||hm(`call signature`,t,fm,gm);let r=t.types,i=n,a;if(r&&Object.keys(r).length>0){if(Object.values(r).every(e=>e instanceof U))a=r;else{if(!n)throw Error(`Call.from: types contain TypeDef but no scope provided`);let e=new Ch(n);i=e,a={};for(let[t,n]of Object.entries(r)){let r=n instanceof U?n:e.parse(n);e.bind(t,r),a[t]=r}}}let o=t.args,s=t.returns,c=t.throws,l=o instanceof U?o:(()=>{if(!i)throw Error(`Call.from: args is TypeDef but no scope provided`);return i.parse(o)})(),u=s===void 0?void 0:s instanceof U?s:(()=>{if(!i)throw Error(`Call.from: returns is TypeDef but no scope provided`);return i.parse(s)})(),d=c===void 0?void 0:c instanceof U?c:(()=>{if(!i)throw Error(`Call.from: throws is TypeDef but no scope provided`);return i.parse(c)})(),f=e=>e instanceof wh?e:i?.parseExpr(e),p=f(t.get),m=f(t.set),h=t.docs;return t instanceof e&&t.args===l&&t.returns===u&&t.throws===d&&t.get===p&&t.set===m&&t.types===a?t:new e({args:l,returns:u,throws:d,get:p,set:m,docs:h,types:a})}toJSON(){let e=this.types&&Object.keys(this.types).length>0?Object.fromEntries(Object.entries(this.types).map(([e,t])=>[e,t.toJSON()])):void 0;return _h({docs:this.docs,types:e,args:this.args.toJSON(),returns:this.returns?.toJSON(),throws:this.throws?.toJSON(),get:this.get?.toJSON(),set:this.set?.toJSON()})}renderTypes(e){if(!this.types)return``;let t=Object.keys(this.types);return t.length===0?``:`{${dg(t.map(t=>`${t}: ${this.types[t].toCode(void 0,e)}`),{sep:`; `})}}`}effects(){let e=0;return this.get&&(e|=this.get.effects()),this.set&&(e|=this.set.effects()),e}},ag=class e{args;run;docs;constructor(e){this.args=e.args,this.run=e.run,this.docs=e.docs}static from(t,n){t instanceof e||hm(`init constructor`,t,pm);let r=t.args,i=r instanceof U?r:(()=>{if(!n)throw Error(`Init.from: args is TypeDef but no scope provided`);return n.parse(r)})(),a=t.run,o=a instanceof wh?a:(()=>{if(!n)throw Error(`Init.from: run is ExprDef but no scope provided`);return n.parseExpr(a)})();return t instanceof e&&t.args===i&&t.run===o?t:new e({args:i,run:o,docs:t.docs})}toJSON(){return _h({docs:this.docs,args:this.args.toJSON(),run:this.run.toJSON()})}},U=class e{constructor(e,t,n={}){this.scope=e,this.options=t,this.generic=n}scope;options;generic;get registry(){return this.scope.registry}priority=0;docs;parsesExprValue(e){return!1}encodeAs(e,t,n){return this.encode(e,n)}toJSONRef(e){if(e?.typeRefs!==`name`)return this.toJSON();if(this.registry.lookup(this.name)===this)return{name:this.name};let t=this.toJSON(),n=Object.keys(this.generic);if(n.length===0)return t;let r={...t.generic??{}};for(let t of n)r[t]=this.generic[t].toJSONRef(e);return{...t,generic:r}}toDefinitionJSON(){let e=cg.depth;cg.active++,cg.depth=this.registry.lookup(this.name)===this?0:1;try{return this.toJSON()}finally{cg.active--,cg.depth=e}}references(){return zh(this.toDefinitionJSON(),this.registry)}closure(e=this.scope){return Bh([this.toDefinitionJSON()],this.registry,t=>e.lookup(t)?.toDefinitionJSON())}compatibleWithParts(e,t,n){let r=Xh(e);if(!r)return!1;if(r.some(e=>this.compatible(e,t,n)))return!0;let i=e.simplify(n);return i!==e&&this.compatible(i,t,n)}compatible(e,t,n){for(let t=0;e.name===`alias`&&t<8;t++){let t=e.simplify(n);if(t===e)break;e=t}if(e===this)return!0;let r=og,i=sg(t,n),a=r.active.get(this)?.get(e);if(a!==void 0&&a.key===i)return r.lowWater=Math.min(r.lowWater,a.depth),!0;let o=r.memo.get(this)?.get(e)?.get(i);if(o!==void 0)return o;let s=r.depth++,c=r.active.get(this);c||r.active.set(this,c=new Map),c.set(e,{depth:s,key:i});let l=r.lowWater;r.lowWater=1/0;let u=!1;try{let a=Yh(e);if(u=a?a.every(e=>this.compatible(e,t,n)):this.compatibleType(e,t,n)||this.compatibleWithParts(e,t,n)||this.compatibleWithBase(e,t,n),!u||r.lowWater>=s){let t=r.memo.get(this);t||r.memo.set(this,t=new Map);let n=t.get(e);n||t.set(e,n=new Map),n.set(i,u)}return u}finally{c.delete(e),r.lowWater=Math.min(l,r.lowWater),--r.depth===0&&(r.memo=new Map,r.active=new Map,r.lowWater=1/0)}}compatibleWithBase(t,n,r){if(n?.strict||n?.exact)return!1;let i=t.base;return i instanceof e&&i!==t&&this.compatible(i,n,r)}accepts(e,t){return this.compatible(e,{strict:!0},t)}exact(e,t){return this.compatible(e,{strict:!0,exact:!0},t)}flexible(){return!1}like(e,t){return this}isUniversal(){return!1}simplify(e){return this}required(){return this}isOptional(){return!1}props(e){let t={toAny:this.registry.method({},this.registry.any(),`type.toAny`)},n=this.registry.augmentation(this.name);return n?.props?{...t,...n.props}:t}static UNIVERSAL_PROP_NAMES=new Set([`toAny`]);constraints(){return[]}get(e){return this.registry.augmentation(this.name)?.get}call(e){return this.registry.augmentation(this.name)?.call}init(e){return this.registry.augmentation(this.name)?.init}prop(e,t){let n=this.props(t)[e];return n?ng.from(n):void 0}follow(e,t){if(`prop`in e)return this.prop(e.prop,t)?.type;if(`args`in e)return this.call(t)?.returns;if(`key`in e)return this.get(t)?.value}at(e,t){let n=this;for(let r of e){if(!n)return;n=n.follow(r,t)}return n}toA(e){return e?.override?.(this)||(this.isRegisteredNamed()?R.ref(this.name):this.defineA(e))}defineA(e){return this.describeA(this.valueA(e),e)}valueA(e){return R.unknown()}toNewA(e){let t=this.init(e?.scope);return t?this.describeA(t.args.toA(e),e):this.toA(e)}isRegisteredNamed(){let e=this.registry;return e.typeClass(this.name)===void 0&&e.namedTypeList().includes(this)}objectA(e,t){let n=R.object(e);return t?.unknownKeys===`refuse`?n.strict():n}describeA(e,t){let n=t?.includeDocs??`none`,r=[];n!==`none`&&this.docs&&r.push(this.docs);let i=this.constraints();return i.length>0&&r.push(i.map(e=>`must satisfy ${e.toCode(this.registry,{expectsValue:!0})}`).join(`; `)),r.length>0?e.describe(r.join(` — `)):e}newEffects(e){let t=this.initEffects();return this.forEachNewSlot(e,{slot:(e,n)=>{t|=e.newEffects(n)},missing:e=>{t|=e.effects()}})?t:t|this.exprValueEffects(e)}exprValueEffects(e){if(!e||typeof e!=`object`||Array.isArray(e))return B.NONE;let t=e.kind;if(typeof t!=`string`||!this.registry.exprClass(t))return B.NONE;try{return this.registry.parseExpr(e,this.scope).effects()}catch{return B.NONE}}initEffects(){let e=this.init();if(!e)return B.NONE;try{return this.registry.parseExpr(e.run,this.scope).effects()}catch{return B.NONE}}newComplexity(e){let t=1+this.initComplexity();return this.forEachNewSlot(e,{slot:(e,n)=>{t+=e.elementComplexity(n)},missing:e=>{t+=e.complexity()}})?t:t+this.exprValueComplexity(e)}exprValueComplexity(e){if(!e||typeof e!=`object`||Array.isArray(e))return 0;let t=e.kind;if(typeof t!=`string`||!this.registry.exprClass(t))return 0;try{return this.registry.parseExpr(e,this.scope).complexity()}catch{return 0}}initComplexity(){let e=this.init();if(!e)return 0;try{return this.registry.parseExpr(e.run,this.scope).complexity()}catch{return 0}}elementComplexity(e){let t=this.exprValueComplexity(e);return t>0?t:1}forEachNewSlot(e,t){return!1}validateNewValue(e,t,n,r,i){if(this.forEachNewSlot(e,{slot:(e,a,o)=>{r.at([o],()=>e.validateNewValue(a,t,n,r,i))}}))return;let a=tg(e,this.scope);if(!a)return;let o=a.validateWalk(t,n,r,i);o.name!==`any`&&(qh(this,o)||r.error(`new.slot.type`,`this slot is declared \`${this.toCode()}\` but the expression here produces \`${o.toCode()}\``))}async newFill(e,t,n){let r=tg(e,this.scope);return r?r.evaluate(t,n):e}toGinCode(e,t,n=[]){return oh(this.toCode(e,t),{path:n,type:this})}toJSONCode(e=[],t=2,n=0){return yg(this.toJSON(),this.registry,e,t,n,this)}docsPrefix(e){return``}extendsClause(e){return``}toCodeRef(e,t){return this.toCode(e,t)}refProps(){return{}}refGet(){}refCall(){}static renderGenerics(e,t){let n=Object.keys(e);return n.length===0?``:`<${dg(n.map(n=>{let r=e[n],i=r.name===`alias`&&r.options?.name===n;return r.name===`any`||i?n:`${n}: ${r.toCode(void 0,t)}`}),{indent:fg(t)})}>`}static renderGenericArgs(t,n){let r=Object.keys(t);return r.length===0||!r.some(n=>!e.isGenericPlaceholder(n,t[n]))?``:`<${dg(r.map(e=>t[e].toCode(void 0,n)),{indent:fg(n)})}>`}static isGenericPlaceholder(e,t){return t.name===`any`||t.name===`alias`&&t.options?.name===e}static formatParams(e,t,n=`auto`){let r=e.fields;if(!r)return e.name===`void`||e.name===`any`?``:`args: ${e.toCode(void 0,t)}`;let i=Object.entries(r).map(([e,n])=>{let r=n.type.isOptional(),i=r?n.type.required():n.type;return`${n.docs&&t?.includeComments!==!1?`/* ${n.docs} */ `:``}${e}${r?`?`:``}: ${i.toCode(void 0,t)}`}),a=fg(t);return n===`auto`?dg(i,{indent:a}):i.length<=1?i.join(``):`
|
|
92
|
+
${i.map(e=>pg(e,a)).join(`
|
|
93
93
|
`)}
|
|
94
|
-
`}definitionInit(){return this.init()}definitionCall(){return this.call()}definitionGet(){return this.get()}definitionProps(){return this.props()}toCodeDefinition(t){let n=[],r=t?.includeComments!==!1,i=
|
|
94
|
+
`}definitionInit(){return this.init()}definitionCall(){return this.call()}definitionGet(){return this.get()}definitionProps(){return this.props()}toCodeDefinition(t){let n=[],r=t?.includeComments!==!1,i=fg(t),a=e=>`/// ${e}`,o=this.definitionCall();if(o?.types)for(let[e,r]of Object.entries(o.types))n.push(`type ${e} = ${r.toCode(void 0,t)};`);let s=this.definitionInit();if(s&&(s.docs&&r&&n.push(a(s.docs)),n.push(`new(${e.formatParams(s.args,t,`lines`)})`)),o){let r=o.returns?.toCode(void 0,t)??`void`;n.push(`(${e.formatParams(o.args,t,`lines`)}): ${r}`)}let c=this.definitionGet();c&&n.push(`[key: ${c.key.toCode(void 0,t)}]: ${c.value.toCode(void 0,t)}`);let l=new Set(Object.keys(this.generic));for(let[i,o]of Object.entries(this.definitionProps())){let s=o instanceof ng?o:ng.from(o);s.docs&&r&&n.push(a(s.docs));let c=s.type.isOptional(),u=c?s.type.required():s.type,d=c?`?`:``,f=u.call(),p=Object.keys(u.props()).filter(t=>!e.UNIVERSAL_PROP_NAMES.has(t));if(f&&!u.get()&&p.length===0){let r=f.returns?.toCode(void 0,t)??`void`,a=Object.fromEntries(Object.entries(u.generic).filter(([e])=>!l.has(e))),o=e.renderGenerics(a,t);n.push(`${i}${d}${o}(${e.formatParams(f.args,t,`lines`)}): ${r}`)}else n.push(`${i}${d}: ${u.toCode(void 0,t)}`)}let u=`${this.docs&&r?`${a(this.docs)}
|
|
95
95
|
`:``}type ${this.name}${e.renderGenerics(this.generic,t)}${this.extendsClause(t)}`;return n.length===0?`${u} {}`:`${u} {
|
|
96
|
-
${n.map(e=>
|
|
96
|
+
${n.map(e=>pg(e,i)).join(`
|
|
97
97
|
`)}
|
|
98
|
-
}`}propSuperFor(e,t,n,r,i){}indexSuperFor(e,t,n,r){}propGet(e,t,n){let r=e.raw&&typeof e.raw==`object`?e.raw[t]:void 0;return r instanceof W?r:G(n,r)}propSet(e,t,n){if(e.raw&&typeof e.raw==`object`)e.raw[t]=n;else throw Error(`type '${this.name}': cannot set prop '${t}' \u2014 value's raw is not an object`)}validate(e){let t=new
|
|
98
|
+
}`}propSuperFor(e,t,n,r,i){}indexSuperFor(e,t,n,r){}propGet(e,t,n){let r=e.raw&&typeof e.raw==`object`?e.raw[t]:void 0;return r instanceof W?r:G(n,r)}propSet(e,t,n){if(e.raw&&typeof e.raw==`object`)e.raw[t]=n;else throw Error(`type '${this.name}': cannot set prop '${t}' \u2014 value's raw is not an object`)}validate(e){let t=new rh;try{this.registry.parse(this.toDefinitionJSON())}catch(e){t.error(`type.invalid`,e.message)}return mg(this,e,t),t}},og={depth:0,lowWater:1/0,active:new Map,memo:new Map};function sg(e,t){return`${+!!e?.strict}${+!!e?.value}${+!!e?.exact}:${t?Sh(t):``}`}var cg={active:0,depth:0};function lg(e,t){if(!e)return``;let n=Object.entries(e).filter(([e,n])=>!(n===void 0||n===``||t&&e in t&&ug(t[e],n)));return n.length===0?``:`{${dg(n.map(([e,t])=>`${e}=${typeof t==`string`?JSON.stringify(t):typeof t==`number`||typeof t==`boolean`?String(t):t===null?`null`:JSON.stringify(t)}`))}}`}function ug(e,t){if(e===t)return!0;try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}function dg(e,t={}){if(e.length===0)return``;let n=t.sep??`, `,r=t.threshold??32,i=t.totalThreshold??80,a=e.join(n);if(!(a.length>i||e.some(e=>e.length>r||e.includes(`
|
|
99
99
|
`))))return a;let o=n.replace(/\s+$/,``),s=t.indent??` `;return`
|
|
100
|
-
${e.map(e=>
|
|
100
|
+
${e.map(e=>pg(e,s)).join(`${o}
|
|
101
101
|
`)}
|
|
102
|
-
`}function
|
|
103
|
-
${t}`)}function
|
|
104
|
-
`+e)}return Lm(i,{path:t})}var W=class{type;raw;constructor(e,t){this.type=e,this.raw=t}toLogical(){return ag(this.raw)}encode(){return this.type.encode(this.raw)}toJSON(e=Ah){return{type:this.type.toJSONRef(e),value:this.type.encodeAs(this.raw,e)}}encodeLogical(){return this.type.encodeAs(this.raw,cg)}toJSONRefs(){return this.toJSON({form:`envelope`,typeRefs:`name`})}toJSONLogical(){return this.toJSON(cg)}};function ag(e){if(e instanceof W)return e.toLogical();if(Array.isArray(e))return e.map(ag);if(e instanceof Map){let t=new Map;for(let n of e.values())og(n)&&t.set(n[0].toLogical(),n[1].toLogical());return t}if(sg(e)){let t={};for(let[n,r]of Object.entries(e))t[n]=ag(r);return t}return e}function og(e){return Array.isArray(e)&&e.length===2&&e[0]instanceof W&&e[1]instanceof W}function sg(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}var cg={form:`logical`,typeRefs:`name`};function G(e,t){return new W(e,t)}var lg=class extends Error{constructor(){super(`The run was stopped.`),this.name=`RunStoppedError`}},ug=class{signal;slice;#e=Date.now();constructor(e={}){this.signal=e.signal,this.slice=e.slice??10}check(){let e=this.signal;if(e?.aborted!==!0)return;let t=e.reason;throw t instanceof Error?t:new lg}async checkpoint(){this.check(),Date.now()-this.#e<this.slice||(await new Promise(e=>{setTimeout(e,0)}),this.#e=Date.now(),this.check())}},dg=new Set([`text`,`num`,`bool`,`enum`,`literal`,`date`,`timestamp`,`duration`,`color`,`null`]);function fg(e){let t=e;for(let e=0;e<16;e+=1){let e=t.inner??t.base;if(e===void 0||e===t)return t;t=e}return t}function pg(e){return dg.has(fg(e).name)}function mg(e,t){let n=e.isOptional()?e.inner??e:e;return pg(n)?R.union([n.toA(t),R.ref(`Expr`)]):R.ref(`Expr`)}function hg(e,t){if(e===t)return!0;if(typeof e!=`object`||!e||typeof t!=`object`||!t)return!1;let n=e,r=t,i=Object.keys(n);return i.length===Object.keys(r).length&&i.every(e=>n[e]===r[e])}function gg(e,t,n){let r=Object.keys(e);return r.length===0?t?Nh.toJSONMap(t):void 0:{...n&&Object.keys(n).length===r.length&&r.every(e=>e in n)?n:Nh.toJSONMap(e),...t?Nh.toJSONMap(t):{}}}function _g(e,t){return{...e,props:e.props?Nh.fromMap(e.props,t):void 0,get:e.get?Ph.from(e.get,t):void 0,call:e.call?Fh.from(e.call,t):void 0,init:e.init?Ih.from(e.init,t):void 0}}var vg=class e extends U{name;docs;base;original;local;bindings;constructor(e,t,n,r,i){let a=n.options?t.narrow(n.options):t.options,o=n.options&&!hg(a,t.options)?e.parse({...t.toJSON(),options:a},i):t;super(r??e,a,n.generic??{}),this.original=t,this.base=o,this.local=_g(n,e),this.name=n.name,this.docs=n.docs;let s=Object.entries(n.generic??{}).filter(([e,t])=>!U.isGenericPlaceholder(e,t));this.bindings=s.length>0?Object.fromEntries(s):void 0}storedLocalProps(){let e=[];for(let[t,n]of Object.entries(this.local.props??{})){let r=n instanceof Nh?n:Nh.from(n);r.get||r.type.call()||e.push([t,r])}return e}valid(e,t){let n=this.bindScope(t);if(!this.base.valid(e,n))return!1;let r=this.storedLocalProps();if(r.length===0||!jh(e))return!0;let i=e;for(let[e,t]of r){let r=i[e];if(!(r instanceof W))return t.type.isOptional();if(!r.type.valid(r.raw,n)||!wh(t.type,r.type,n))return!1}return!0}parse(e,t){let n=this.bindScope(t),r=this.base.parse(e,n),i=this.storedLocalProps();if(i.length===0||!jh(r.raw))return new W(this,r.raw);let a=jh(e)?e:{},o={...r.raw};for(let[e,t]of i)o[e]=this.registry.parseValue(a[e],t.type,n);return new W(this,o)}parsesExprValue(e){return this.base.parsesExprValue(this.bindScope(e))}encode(e,t){return this.encodeAs(e,Ah,t)}encodeAs(e,t,n){let r=this.bindScope(n),i=this.base.encodeAs(e,t,r),a=this.storedLocalProps();if(a.length===0||!jh(i)||!jh(e))return i;let o=e,s={...i};for(let[e]of a)kh(s,e,o[e],t,r);return s}create(){return this.withLocalSlots(this.base.create(),e=>e.create())}random(e){return this.withLocalSlots(this.base.random(e),t=>t.random(e))}withLocalSlots(e,t){let n=this.storedLocalProps();if(n.length===0||!jh(e))return e;let r={...e};for(let[e,i]of n)r[e]=new W(i.type,t(i.type));return r}forEachNewSlot(e,t){let n=this.base.forEachNewSlot(e,t),r=this.storedLocalProps();if(r.length===0||!jh(e))return n;let i=e;for(let[e,n]of r)e in i?t.slot(n.type,i[e],e):n.default!==void 0&&t.missing?.(n.default,e);return!0}async newFill(e,t,n){let r=await this.base.newFill(e,t,n),i=this.storedLocalProps();if(i.length===0||!jh(r))return r;let a=r,o;for(let[e,r]of i)if(e in a){let i=await r.type.newFill(a[e],t,n);i!==a[e]&&(o??={...a},o[e]=i)}else r.default!==void 0&&(o??={...a},o[e]=await r.default.evaluate(t,n));return o??a}compatibleType(t,n,r){return n?.exact?t instanceof e&&t.name===this.name&&this.base.compatible(t.base,n,r):t instanceof e?this.base.compatible(t.base,n,r):this.base.compatible(t,n,r)}or(t){if(t instanceof e&&t.name===this.name){let n={name:this.name,docs:this.docs??t.docs,options:{...this.local.options??{},...t.local.options??{}},props:{...this.local.props??{},...t.local.props??{}},get:this.local.get??t.local.get,call:this.local.call??t.local.call,init:this.local.init??t.local.init};return new e(this.registry,this.original,n)}return this.base.or(t)}simplify(){return this}required(){return this.base.required()}isOptional(){return this.base.isOptional()}narrow(e){return this.base.narrow(e)}props(e){let t=this.registry.augmentation(this.name);return{...this.base.props(this.bindScope(e)),...t?.props??{},...this.local.props??{}}}get(e){return this.local.get??this.registry.augmentation(this.name)?.get??this.base.get(this.bindScope(e))}call(e){return this.local.call??this.registry.augmentation(this.name)?.call??this.base.call(this.bindScope(e))}init(e){return this.local.init??this.registry.augmentation(this.name)?.init??this.base.init(this.bindScope(e))}toJSON(){if(zh.active>0&&zh.depth>0&&!this.local.useSite&&this.registry.lookup(this.name)!==void 0&&(this.registry.lookup(this.name)===this||this.bindings)){let e=Object.entries(this.bindings??{});return e.length>0?{name:this.name,generic:Object.fromEntries(e.map(([e,t])=>[e,t.toJSON()]))}:{name:this.name}}zh.depth++;try{return this.toJSONInner()}finally{zh.depth--}}toJSONInner(){if(this.local.useSite){let e=Object.entries(this.bindings??{});return{name:this.name,...e.length>0?{generic:Object.fromEntries(e.map(([e,t])=>[e,t.toJSON()]))}:{},options:{...this.local.options}}}let e=this.original.toJSON(),t=this.original.name!==this.name,n={...e.options,...this.local.options},r={...e.generic??{}};if(this.local.generic)for(let[e,t]of Object.entries(this.local.generic))r[e]=t.toJSON();return Jm({name:this.name,extends:t?this.original.name:void 0,docs:this.docs,generic:Object.keys(r).length>0?r:void 0,options:n&&Object.keys(n).length>0?n:void 0,props:gg(t?this.original.refProps():{},this.local.props,e.props),get:(this.local.get??(t?this.original.refGet():void 0))?.toJSON(),call:(this.local.call??(t?this.original.refCall():void 0))?.toJSON(),init:this.local.init?.toJSON(),constraint:this.local.constraint?this.local.constraint.toJSON():void 0})}clone(){let t=this.local.generic?Object.fromEntries(Object.entries(this.local.generic).map(([e,t])=>[e,t.clone()])):void 0;return new e(this.registry,this.original.clone(),{name:this.local.name,docs:this.local.docs,options:this.local.options?{...this.local.options}:void 0,generic:t,props:this.local.props?{...this.local.props}:void 0,get:this.local.get,call:this.local.call,init:this.local.init,constraint:this.local.constraint?.clone(),useSite:this.local.useSite},this.bindings?this.scope:void 0)}toCode(e,t){return this.docsPrefix(t)+this.name+U.renderGenericArgs(this.generic,t)+(this.local.useSite?Bh(this.local.options):``)}extendsClause(e){return` extends ${this.base.toCodeRef(void 0,e)}`}baseMembersElided(e){return this.base.toCodeRef(void 0,e)!==this.base.toCode(void 0,e)}ownAugmentation(){return this.registry.augmentation(this.name)}definitionInit(){return this.local.init??this.ownAugmentation()?.init}definitionCall(){return this.local.call??this.ownAugmentation()?.call??(this.baseMembersElided()?this.base.refCall():void 0)}definitionGet(){return this.local.get??this.ownAugmentation()?.get??(this.baseMembersElided()?this.base.refGet():void 0)}definitionProps(){return{...this.baseMembersElided()?this.base.refProps():{},...this.ownAugmentation()?.props??{},...this.local.props??{}}}specialize(t){let n={...this.local.generic??{}},r={};for(let e of Object.keys(this.local.generic??{})){let i=t[e];i&&(n[e]=i,r[e]=i)}return Object.keys(r).length===0?this:new e(this.registry,this.original,{...this.local,generic:n},new eh(this.scope,r))}bindScope(e){return this.bindings?e?new eh(e,this.bindings):this.scope:e}constraints(){let e=this.base.constraints();return this.local.constraint?[this.local.constraint,...e]:e}valueA(e){return this.mergeLocalPropsA(this.base.defineA(e),e,t=>t.type.toA(e))}toNewA(e){return this.describeA(this.mergeLocalPropsA(this.base.toNewA(e),e,t=>mg(t.type,e)),e)}mergeLocalPropsA(e,t,n){if(!(e instanceof hf))return e;let r=t?.includeDocs??`none`,i={};for(let[e,t]of this.storedLocalProps()){let a=n(t);r===`all`&&t.docs&&(a=a.describe(t.docs)),i[e]=t.type.isOptional()&&a.kind!==`optional`?R.optional(a):a}return Object.keys(i).length===0?e:e.extend(i)}propSuperFor(e,t,n,r,i){let a=this.local.props;if(!(a&&Object.hasOwn(a,t)))return;let o=this.base.prop(t);if(!o)return;let s=new W(this.base,e.raw);if(n===`get`){if(o.type.call()&&o.get){let e=o.type;return new W(e,async e=>{let n={this:s,args:e},a=s.type.propSuperFor(s,t,`get`,r,i);return a&&(n.super=a),i.evaluate(o.get,r.child(n))})}return new W(i.registry.fn({args:i.registry.obj({}),returns:o.type}),async e=>{if(!o.get)return G(o.type,s.raw?.[t]);let n={this:s},a=s.type.propSuperFor(s,t,`get`,r,i);return a&&(n.super=a),i.evaluate(o.get,r.child(n))})}if(n===`set`)return o.set?new W(i.registry.fn({args:i.registry.obj({value:{type:o.type}}),returns:i.registry.void()}),async e=>{let n=e.raw.value,a={this:s,value:n},c=s.type.propSuperFor(s,t,`set`,r,i);return c&&(a.super=c),await i.evaluate(o.set,r.child(a)),G(i.registry.void(),void 0)}):void 0;let c=o.type.call();return c?.set?new W(i.registry.fn({args:i.registry.obj({args:{type:c.args},value:{type:c.returns??i.registry.any()}}),returns:i.registry.void()}),async e=>{let n=e.raw,a={this:s,args:n.args,value:n.value},o=s.type.propSuperFor(s,t,`callSet`,r,i);return o&&(a.super=o),await i.evaluate(c.set,r.child(a)),G(i.registry.void(),void 0)}):void 0}indexSuperFor(e,t,n,r){let i=this.local.get;if(!i)return;let a=this.base.get();if(!a)return;let o=new W(this.base,e.raw);return t===`get`?!i.get||!a.get?void 0:new W(r.registry.fn({args:r.registry.obj({key:{type:a.key}}),returns:a.value}),async e=>{let t=e.raw.key,n=r.createRootScope();return n.vars.set(`this`,o),n.vars.set(`key`,t),r.evaluate(a.get,n)}):!i.set||!a.set?void 0:new W(r.registry.fn({args:r.registry.obj({key:{type:a.key},value:{type:a.value}}),returns:r.registry.void()}),async e=>{let t=e.raw,n=r.createRootScope();return n.vars.set(`this`,o),n.vars.set(`key`,t.key),n.vars.set(`value`,t.value),await r.evaluate(a.set,n),G(r.registry.void(),void 0)})}},yg=class e extends U{static NAME=`any`;name=e.NAME;static optionKeys=[];static genericKeys=[];static from(t,n){return n.registry,new e(n,{})}valid(e){return!0}parse(e){return new W(this,e)}encode(e){return e}create(){return null}random(e){return null}compatibleType(e,t){return!0}flexible(){return!0}isUniversal(){return!0}or(e){return this}narrow(e){if(e&&Object.keys(e).length>0)throw new Fm({path:[],code:`any.no-options`,message:`any has no narrowable options`,severity:`error`});return{}}props(){let e=this.registry;return{...super.props(),typeOf:e.method({},e.text(),`any.typeOf`),is:e.method({},e.bool(),`any.is`,{generic:{T:e.any()}}),as:e.method({},e.optional(e.alias(`T`)),`any.as`,{generic:{T:e.any()}}),toText:e.method({},e.text(),`any.toText`),toBool:e.method({},e.bool(),`any.toBool`),eq:e.method({other:e.any()},e.bool(),`any.eq`),neq:e.method({other:e.any()},e.bool(),`any.neq`)}}toJSON(){return{name:e.NAME}}clone(){return new e(this.registry,{})}toCode(e,t){return this.docsPrefix(t)+`any`}valueA(){return R.unknown()}},bg=class e extends U{static NAME=`obj`;static consumes=[`props`];name=e.NAME;static optionKeys=[];static genericKeys=[];fields;static from(t,n){let r=Nh.fromMap(t.props??{},n);return new e(n,r)}constructor(e,t){super(e,{});let n={};for(let[e,r]of Object.entries(t))n[e]=Nh.from(r);this.fields=n}valid(e,t){if(typeof e!=`object`||!e||Array.isArray(e))return!1;for(let[n,r]of Object.entries(this.fields)){let i=e[n];if(!(i instanceof W)||!i.type.valid(i.raw,t)||!wh(r.type,i.type,t))return!1}return!0}parse(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw new Fm({path:[],code:`object.invalid`,message:`object.parse: expected object, got ${typeof e}`,severity:`error`});let n={};for(let[r,i]of Object.entries(this.fields)){let a=e[r];n[r]=this.registry.parseValue(a,i.type,t)}return new W(this,n)}encode(e,t){return this.encodeAs(e,Ah,t)}encodeAs(e,t,n){let r=e,i={};for(let[e]of Object.entries(this.fields))kh(i,e,r[e],t,n);return i}create(){let e={};for(let[t,n]of Object.entries(this.fields))e[t]=new W(n.type,n.type.create());return e}random(e){let t={};for(let[n,r]of Object.entries(this.fields))t[n]=new W(r.type,r.type.random(e));return t}forEachNewSlot(e,t){if(!xg(e)||Mh(e,this.scope))return!1;let n=e;for(let[e,r]of Object.entries(this.fields))e in n?t.slot(r.type,n[e],e):r.default!==void 0&&t.missing?.(r.default,e);return!0}async newFill(e,t,n){if(!xg(e)||Mh(e,this.scope))return super.newFill(e,t,n);let r=e,i;for(let[e,a]of Object.entries(this.fields))if(e in r){let o=await a.type.newFill(r[e],t,n);o!==r[e]&&(i??={...r},i[e]=o)}else a.default!==void 0&&(i??={...r},i[e]=await a.default.evaluate(t,n));return i??r}like(t){if(!(t instanceof e))return this;let n={};for(let[e,r]of Object.entries(t.fields)){let t=this.registry.like(r.type);if(t.name===`null`)return this.registry.null();n[e]={type:t}}return this.registry.obj(n)}compatibleType(t,n,r){if(!(t instanceof e))return!1;for(let[e,i]of Object.entries(this.fields)){let a=t.fields[e];if(!a){if(n?.exact)return!1;if(i.type.isOptional())continue;return!1}if(!i.type.compatible(a.type,n,r))return!1}if(n?.exact){let e=new Set(Object.keys(this.fields));for(let n of Object.keys(t.fields))if(!e.has(n))return!1}return!0}or(t){if(!(t instanceof e))return this;let n={};for(let[e,r]of Object.entries(this.fields)){let i=t.fields[e];i&&(n[e]={type:r.type.or(i.type)})}return new e(this.registry,n)}narrow(e){return{}}props(){let e=this.registry,t=Object.values(this.fields).map(e=>e.type),n=t.length===0?e.any():t.length===1?t[0]:e.or(t),r={keys:e.method({},e.list(e.text()),`object.keys`),values:e.method({},e.list(n),`object.values`),entries:e.method({},e.list(e.tuple([e.text(),n])),`object.entries`),has:e.method({key:e.text()},e.bool(),`object.has`),eq:e.method({other:e.any()},e.bool(),`object.eq`),neq:e.method({other:e.any()},e.bool(),`object.neq`),toText:e.method({},e.text(),`object.toText`)};return{...super.props(),...r,...this.fields}}get(){let e=Object.keys(this.fields);if(e.length===0)return;let t=this.registry.text(),n=e.map(e=>this.registry.literal(t,e)),r=n.length===1?n[0]:this.registry.or(n),i=Object.values(this.fields).map(e=>e.type),a=i.length===1?i[0]:this.registry.or(i),o=this.registry;return new Ph({key:r,value:a,get:o.nativeExpr(`object.indexGet`),set:o.nativeExpr(`object.indexSet`),loop:o.nativeExpr(`object.iterate`)})}toJSON(){return{name:e.NAME,props:Nh.toJSONMap(this.fields)}}clone(){let t={};for(let[e,n]of Object.entries(this.fields))t[e]={...n,type:n.type.clone()};return new e(this.registry,t)}toCode(e,t){let n=Object.entries(this.fields);if(n.length===0)return this.docsPrefix(t)+`obj`;let r=t?.includeComments!==!1,i=n.map(([e,n])=>{let i=n.type.isOptional(),a=i?n.type.required():n.type,o=i?`${e}?`:e;return`${n.docs&&r?`/* ${n.docs} */ `:``}${o}: ${a.toCode(void 0,t)}`});return this.docsPrefix(t)+`obj{${Hh(i,{indent:Uh(t)})}}`}toCodeRef(e,t){return this.docsPrefix(t)+`obj`}refProps(){return this.fields}valueA(e){let t=e?.includeDocs??`none`,n={};for(let[r,i]of Object.entries(this.fields)){let a=i.type.toA(e);t===`all`&&i.docs&&(a=a.describe(i.docs)),n[r]=a}return this.objectA(n,e)}toNewA(e){let t=e?.includeDocs??`none`,n={};for(let[r,i]of Object.entries(this.fields)){let a=mg(i.type,e);t===`all`&&i.docs&&(a=a.describe(i.docs)),n[r]=i.type.isOptional()?R.optional(a):a}return this.describeA(R.object(n),e)}describe(t){if(typeof t!=`object`||!t||Array.isArray(t))return;let n={};for(let[e,r]of Object.entries(t))n[e]={type:this.registry.any().describe?.(r)??this.registry.any()};return new e(this.registry,n)}};function xg(e){return jh(e)}var Sg=class e extends U{static NAME=`and`;name=e.NAME;static optionKeys=[`types`];static genericKeys=[];static from(t,n){n.registry;let r=(t.options?.types??[]).map(e=>n.parse(e));return new e(n,r)}constructor(e,t){super(e,{parts:t})}get parts(){return this.options.parts}valid(e,t){return this.parts.every(n=>n.valid(e,t))}effective(){let e=this.parts;if(e.length===0)return;if(e.length===1)return e[0];let t=this.mergedObjFields();return t?this.registry.obj(t):e[0]}mergedObjFields(){let e=[];for(let t of this.parts){if(!(t instanceof bg))return;e.push(t)}let t={};for(let n of e)for(let[e,r]of Object.entries(n.fields)){let n=t[e];t[e]=n?{type:this.registry.and([n.type,r.type])}:r}return t}parse(e,t){let n=this.effective();if(!n)return new W(this,e);let r=n.parse(e,t).raw;for(let e of this.parts)if(!e.valid(r,t))throw new Fm({path:[],code:`and.constraint`,message:`and: value fails part ${e.name}`,severity:`error`});return new W(this,r)}encode(e,t){return this.effective()?.encode(e,t)??e}parsesExprValue(e){return this.effective()?.parsesExprValue(e)??!1}encodeAs(e,t,n){return this.effective()?.encodeAs(e,t,n)??e}forEachNewSlot(e,t){return this.effective()?.forEachNewSlot(e,t)??!1}async newFill(e,t,n){let r=this.effective();return r?r.newFill(e,t,n):super.newFill(e,t,n)}create(){let e=this.effective();if(!e)return null;for(let t of[e,...this.parts]){let e=t.create();if(this.valid(e))return e}return e.create()}random(e){let t=this.effective();if(!t)return null;for(let n of[t,...this.parts]){let t=n.random(e);if(this.valid(t))return t}return t.random(e)}like(t){if(!(t instanceof e))return this;let n=t.parts.map(e=>this.registry.like(e)).filter(e=>e.name!==`null`);return n.length===0?this.registry.null():n.length===1?n[0]:this.registry.and(n)}compatibleType(e,t,n){return this.parts.every(r=>r.compatible(e,t,n))}isUniversal(){return this.parts.length===0||this.parts.every(e=>e.isUniversal())}or(t){return t instanceof e?new e(this.registry,[...this.parts,...t.parts]):this}simplify(){if(this.parts.length===1)return this.parts[0];if(this.parts.length===0)return this;let e=this.mergedObjFields();return e?this.registry.obj(e):this}narrow(e){return this.options}props(){let e={};for(let t of this.parts)for(let[n,r]of Object.entries(t.props()))e[n]=n in e?{type:this.registry.and([e[n].type,r.type])}:r;return e}get(){let e=this.parts.map(e=>e.get()).filter(e=>!!e);if(e.length!==0)return new Ph({key:this.registry.or(e.map(e=>e.key)),value:this.registry.and(e.map(e=>e.value))})}call(){let e=this.parts.map(e=>e.call()).filter(e=>!!e);if(e.length===0)return;let t=e.map(e=>e.returns).filter(e=>!!e);return new Fh({args:this.registry.or(e.map(e=>e.args)),returns:t.length>0?this.registry.and(t):void 0})}toJSON(){return{name:e.NAME,options:{types:this.parts.map(e=>e.toJSON())}}}clone(){return new e(this.registry,this.parts.map(e=>e.clone()))}toCode(e,t){return this.docsPrefix(t)+`and<${this.parts.map(e=>e.toCode(void 0,t)).join(`, `)}>`}valueA(e){return this.parts.length===0?R.unknown():this.parts.length===1?this.parts[0].toA(e):R.intersection(this.parts.map(t=>t.toA(e)))}toNewA(e){return this.parts.length===0?this.describeA(R.unknown(),e):this.parts.length===1?this.describeA(this.parts[0].toNewA(e),e):this.describeA(R.intersection(this.parts.map(t=>t.toNewA(e))),e)}},Cg=new Set,wg=class e extends U{static NAME=`alias`;name=e.NAME;constructor(e,t,n={}){super(e,t,n)}get hasUse(){return Object.keys(this.generic).length>0||this.options.options!==void 0}applied;static from(t,n){return new e(n,{name:t.name})}resolve(e){let t=(e?e.lookup(this.options.name):void 0)??this.scope.lookup(this.options.name);if(!t||!this.hasUse)return t;this.applied??=new WeakMap;let n=this.applied.get(t);return n||(n=this.registry.applyUse(t,this.generic,this.options.options),this.applied.set(t,n)),n}valid(e,t){let n=this.resolve(t);return!n||n.valid(e,t)}parse(e,t){let n=this.resolve(t);if(!n)return new W(this,e);let r=n.parse(e,t);return new W(this,r.raw)}encode(e,t){let n=this.resolve(t);return n?n.encode(e,t):e}parsesExprValue(e){return this.resolve(e)?.parsesExprValue(e)??!1}encodeAs(e,t,n){let r=this.resolve(n);return r?r.encodeAs(e,t,n):e}create(){let e=this.resolve();return e?e.create():null}random(e){let t=this.resolve();return t?t.random(e):null}compatibleType(e,t,n){let r=this.resolve(n);return!r||r.compatible(e,t,n)}flexible(){return!0}isUniversal(){let e=this.resolve();return!e||e.isUniversal()}or(e){let t=this.resolve();return t?t.or(e):this}simplify(e){return this.resolve(e)??this}narrow(e){return{...this.options,name:e.name??this.options.name}}props(e){let t=this.resolve(e);return t?t.props(e):super.props(e)}get(e){return this.resolve(e)?.get(e)}call(e){return this.resolve(e)?.call(e)}init(e){return this.resolve(e)?.init(e)}follow(e,t){return this.resolve(t)?.follow(e,t)}forEachNewSlot(e,t){return this.resolve()?.forEachNewSlot(e,t)??!1}async newFill(e,t,n){let r=this.resolve();return r?r.newFill(e,t,n):super.newFill(e,t,n)}toJSON(){if(!this.hasUse)return{name:this.options.name};let e=Object.entries(this.generic);return{name:this.options.name,...e.length>0?{generic:Object.fromEntries(e.map(([e,t])=>[e,t.toJSON()]))}:{},...this.options.options===void 0?{}:{options:{...this.options.options}}}}clone(){return new e(this.scope,{...this.options},{...this.generic})}toCode(e,t){return this.docsPrefix(t)+this.options.name+U.renderGenericArgs(this.generic,t)+Bh(this.options.options)}valueA(e){let t=this.resolve(e?.scope);if(!t)return R.unknown();if(Cg.has(this.options.name))return R.json().describe(`A value of the named type ${this.options.name}.`);Cg.add(this.options.name);try{return t.toA(e)}finally{Cg.delete(this.options.name)}}toNewA(e){let t=this.resolve(e?.scope);if(!t)return R.unknown();if(Cg.has(this.options.name))return R.ref(`Expr`);Cg.add(this.options.name);try{return t.toNewA(e)}finally{Cg.delete(this.options.name)}}},Tg=class e extends U{static NAME=`bool`;name=e.NAME;static optionKeys=[`trueText`,`falseText`];static genericKeys=[];static from(t,n){return n.registry,new e(n,t.options??{})}valid(e){return typeof e==`boolean`}parse(e){if(typeof e==`boolean`)return new W(this,e);if(e===this.options.trueText)return new W(this,!0);if(e===this.options.falseText)return new W(this,!1);throw Error(`bool.parse: expected boolean, got ${typeof e}`)}encode(e){return e}create(){return!1}random(e){return e(0,1,!0)===1}compatibleType(t,n){return t instanceof e}or(t){return t instanceof e?new e(this.registry,{trueText:this.options.trueText??t.options.trueText,falseText:this.options.falseText??t.options.falseText}):this}narrow(e){return{...this.options,...e}}props(){let e=this.registry;return{...super.props(),eq:e.method({other:e.bool()},e.bool(),`bool.eq`),neq:e.method({other:e.bool()},e.bool(),`bool.neq`),and:e.method({other:e.bool()},e.bool(),`bool.and`),or:e.method({other:e.bool()},e.bool(),`bool.or`),xor:e.method({other:e.bool()},e.bool(),`bool.xor`),not:e.method({},e.bool(),`bool.not`),toText:e.method({},e.text(),`bool.toText`),toNum:e.method({},e.num(),`bool.toNum`)}}get(){let e=this.registry;return new Ph({key:e.num({whole:!0,min:0}),value:e.bool(),loopDynamic:!0})}toJSON(){return Jm({name:e.NAME,options:Object.keys(this.options).length>0?{...this.options}:void 0})}clone(){return new e(this.registry,{...this.options})}toCode(e,t){return this.docsPrefix(t)+`bool`+Bh(this.options)}valueA(){return R.boolean()}describe(e){return typeof e==`boolean`?this:void 0}},Eg=class e extends U{static NAME=`color`;name=e.NAME;static optionKeys=[`hasAlpha`];static genericKeys=[];static from(t,n){return n.registry,new e(n,t.options??{})}valid(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0&&e<=4294967295}parse(e){let t=typeof e==`number`?e:Number(e);if(!this.valid(t))throw new Fm({path:[],code:`color.invalid`,message:`color.parse: not a valid 32-bit color int: ${String(e)}`,severity:`error`});return new W(this,t)}encode(e){return e}create(){return 255}random(e){return e(0,4294967295,!0)}compatibleType(t,n){return t instanceof e}or(t){return t instanceof e?new e(this.registry,{hasAlpha:this.options.hasAlpha===t.options.hasAlpha?this.options.hasAlpha:void 0}):this}narrow(e){return{...this.options,...e}}init(){let e=this.registry,t=e.num({whole:!0,min:0,max:255}),n=e.optional(e.num({min:0,max:1}));return new Ih({args:e.obj({r:{type:t},g:{type:t},b:{type:t},a:{type:n}}),run:e.nativeExpr(`color.init`)})}props(){let e=this.registry,t=e.num(),n=e.bool(),r=e.text(),i=e.color();return{...super.props(),r:e.prop(t,`color.r`),g:e.prop(t,`color.g`),b:e.prop(t,`color.b`),a:e.prop(t,`color.a`),hue:e.prop(t,`color.hue`),saturation:e.prop(t,`color.saturation`),lightness:e.prop(t,`color.lightness`),eq:e.method({other:i},n,`color.eq`),neq:e.method({other:i},n,`color.neq`),lighten:e.method({amount:t},i,`color.lighten`),darken:e.method({amount:t},i,`color.darken`),saturate:e.method({amount:t},i,`color.saturate`),desaturate:e.method({amount:t},i,`color.desaturate`),opacity:e.method({alpha:t},i,`color.opacity`),invert:e.method({},i,`color.invert`),mix:e.method({other:i,weight:e.optional(t)},i,`color.mix`),complement:e.method({},i,`color.complement`),toHex:e.method({},r,`color.toHex`),toRgb:e.method({},r,`color.toRgb`),toHsl:e.method({},r,`color.toHsl`),toText:e.method({},r,`color.toText`)}}toJSON(){return Jm({name:e.NAME,options:Object.keys(this.options).length>0?{...this.options}:void 0})}clone(){return new e(this.registry,{...this.options})}toCode(e,t){return this.docsPrefix(t)+`color`+Bh(this.options)}valueA(){return R.int().min(0).max(4294967295).describe(this.options.hasAlpha?`A color as a 32-bit integer 0xRRGGBBAA.`:`A color as an integer 0xRRGGBB.`)}},Dg=class e extends U{static NAME=`date`;name=e.NAME;static optionKeys=[`min`,`max`,`utc`];static genericKeys=[];static from(t,n){return n.registry,new e(n,t.options??{})}boundDate(e){return e?new Date(e):void 0}valid(e){if(!(e instanceof Date)||Number.isNaN(e.getTime()))return!1;let t=this.boundDate(this.options.min),n=this.boundDate(this.options.max);return!(t&&e<t||n&&e>n)}parse(e){let t=e instanceof Date?e:typeof e==`string`?new Date(e):new Date(NaN);if(!this.valid(t))throw new Fm({path:[],code:`date.invalid`,message:`date.parse: invalid or out-of-range: ${String(e)}`,severity:`error`});return new W(this,t)}encode(e){return e.toISOString().slice(0,10)}create(){return new Date}random(e){let t=this.boundDate(this.options.min)?.getTime()??Date.UTC(2e3,0,1),n=this.boundDate(this.options.max)?.getTime()??Date.UTC(2050,11,31);return new Date(e(t,n,!0))}compatibleType(t,n){return t instanceof e}or(t){if(!(t instanceof e))return this;let n=this.options,r=t.options;return new e(this.registry,{min:n.min&&r.min?n.min<r.min?n.min:r.min:void 0,max:n.max&&r.max?n.max>r.max?n.max:r.max:void 0,utc:n.utc===r.utc?n.utc:void 0})}narrow(e){let t=this.options,n=(e,t)=>{throw new Fm({path:[],code:e,message:t,severity:`error`})},r={...t};return e.min!==void 0&&(t.min&&e.min<t.min&&n(`date.widen.min`,`cannot move min earlier`),r.min=e.min),e.max!==void 0&&(t.max&&e.max>t.max&&n(`date.widen.max`,`cannot move max later`),r.max=e.max),e.utc!==void 0&&(r.utc=e.utc),r}props(){let e=this.registry,t=e.num({whole:!0}),n=e.bool(),r=e.text(),i=e.date();return{...super.props(),year:e.prop(t,`date.year`),month:e.prop(t,`date.month`),day:e.prop(t,`date.day`),dayOfWeek:e.prop(t,`date.dayOfWeek`),dayOfYear:e.prop(t,`date.dayOfYear`),eq:e.method({other:i},n,`date.eq`),neq:e.method({other:i},n,`date.neq`),before:e.method({other:i},n,`date.before`),after:e.method({other:i},n,`date.after`),addDays:e.method({days:t},i,`date.addDays`),addMonths:e.method({months:t},i,`date.addMonths`),addYears:e.method({years:t},i,`date.addYears`),diffDays:e.method({other:i},t,`date.diffDays`),diffMonths:e.method({other:i},t,`date.diffMonths`),diffYears:e.method({other:i},t,`date.diffYears`),toText:e.method({format:e.optional(r)},r,`date.toText`)}}toJSON(){return Jm({name:e.NAME,options:Object.keys(this.options).length>0?{...this.options}:void 0})}clone(){return new e(this.registry,{...this.options})}toCode(e,t){return this.docsPrefix(t)+`date`+Bh(this.options)}valueA(){return R.string().pattern(`^\\d{4}-\\d{2}-\\d{2}`).describe(`An ISO 8601 date (YYYY-MM-DD).`)}describe(e){return e instanceof Date?this:void 0}},Og=class e extends U{static NAME=`duration`;name=e.NAME;static optionKeys=[];static genericKeys=[];static from(t,n){return n.registry,new e(n,{})}valid(e){return typeof e==`number`&&!Number.isNaN(e)}parse(e){let t=typeof e==`number`?e:Number(e);return new W(this,t)}encode(e){return e}create(){return 0}random(e){return e(0,864e5,!0)}compatibleType(t,n){return t instanceof e}or(e){return this}narrow(e){return{}}init(){let e=this.registry,t=e.num();return new Ih({args:e.obj({days:{type:e.optional(t)},hours:{type:e.optional(t)},minutes:{type:e.optional(t)},seconds:{type:e.optional(t)},ms:{type:e.optional(t)}}),run:e.nativeExpr(`duration.init`)})}props(){let e=this.registry,t=e.num({whole:!0}),n=e.text();return{...super.props(),totalSeconds:e.prop(e.num(),`duration.totalSeconds`),totalMinutes:e.prop(e.num(),`duration.totalMinutes`),totalHours:e.prop(e.num(),`duration.totalHours`),totalDays:e.prop(e.num(),`duration.totalDays`),days:e.prop(t,`duration.days`),hours:e.prop(t,`duration.hours`),minutes:e.prop(t,`duration.minutes`),seconds:e.prop(t,`duration.seconds`),ms:e.prop(t,`duration.ms`),toText:e.method({format:e.optional(n)},n,`duration.toText`)}}toJSON(){return{name:e.NAME}}clone(){return new e(this.registry,{})}toCode(e,t){return this.docsPrefix(t)+`duration`}valueA(){return R.number().describe(`A duration in milliseconds.`)}},kg=class e extends U{static NAME=`enum`;name=e.NAME;static optionKeys=[`values`];static genericKeys=[`V`];static from(t,n){let r=n.registry,i=t.generic?.V?n.parse(t.generic.V):r.text(),a=t.options?.values??{};return new e(n,i,{values:a})}constructor(e,t,n){super(e,n,{V:t})}get value(){return this.generic.V}valid(e,t){return this.value.valid(e,t)?Object.values(this.options.values).some(t=>t===e):!1}parse(e,t){let n=this.value.parse(e,t);if(!this.valid(n.raw,t))throw new Fm({path:[],code:`enum.not-a-member`,message:`enum.parse: ${String(n.raw)} is not one of ${Object.values(this.options.values).join(`, `)}`,severity:`error`});return new W(this,n.raw)}encode(e,t){return this.value.encode(e,t)}encodeAs(e,t,n){return this.value.encodeAs(e,t,n)}create(){let e=Object.values(this.options.values)[0];return e===void 0?this.value.create():e}random(e){let t=Object.values(this.options.values);return t.length===0?this.value.random(e):t[e(0,t.length-1,!0)]}like(t){if(!(t instanceof e))return this;let n=this.registry.like(t.value);return n.name===`null`?this.registry.null():this.registry.enum(t.options.values,n)}compatibleType(t,n,r){return!(t instanceof e)||!this.value.compatible(t.value,n,r)?!1:!n?.value||Object.values(t.options.values).every(e=>Object.values(this.options.values).some(t=>t===e))}or(t){return t instanceof e?new e(this.registry,this.value.or(t.value),{values:{...t.options.values,...this.options.values}}):this}narrow(e){let t=this.options.values;if(e.values===void 0)return this.options;for(let[n,r]of Object.entries(e.values))if(!Object.values(t).some(e=>e===r))throw new Fm({path:[],code:`enum.widen`,message:`enum.narrow: ${n}=${String(r)} not in base values`,severity:`error`});return{values:e.values}}props(){let e=this.registry,t=this.value;return{...super.props(),name:e.prop(e.text(),`enum.name`),value:e.prop(t,`enum.value`),eq:e.method({other:t},e.bool(),`enum.eq`),neq:e.method({other:t},e.bool(),`enum.neq`),toText:e.method({},e.text(),`enum.toText`)}}toJSON(){return{name:e.NAME,generic:{V:this.value.toJSON()},options:{values:this.options.values}}}clone(){return new e(this.registry,this.value.clone(),{values:{...this.options.values}})}toCode(e,t){let n=`enum<${this.value.toCode(void 0,t)}>`+jg(this.options.values,t);return this.docsPrefix(t)+n}valueA(){let e=Object.values(this.options.values);return e.length>0&&e.every(e=>typeof e==`string`)?R.enum(e):R.union(e.map(e=>R.literal(e)))}},Ag=/^[A-Za-z_$][A-Za-z0-9_$]*$/;function jg(e,t){let n=Object.entries(e);return n.length===0?``:`{${Hh(n.map(([e,t])=>{let n=Ag.test(e)?e:JSON.stringify(e);return t===e?n:`${n}=${typeof t==`number`||typeof t==`boolean`?String(t):JSON.stringify(t??null)}`}),{indent:Uh(t)})}}`}var Mg=class e extends U{static NAME=`fn`;static consumes=[`call`];name=e.NAME;static optionKeys=[];static declaresGenerics=!0;_call;static from(t,n){let r=n.registry,i={},a=new eh(n);if(t.generic)for(let[e,n]of Object.entries(t.generic))i[e]=a.parse(n);return t.call?new e(a,Fh.from(t.call,a),i):new e(a,new Fh({args:r.any(),returns:r.any()}),i)}constructor(e,t,n={}){super(e,{},n),this._call=t instanceof Fh?t:new Fh(t)}parsesExprValue(e){return!0}valid(e,t){return!!(typeof e==`function`||typeof e==`string`||e&&typeof e==`object`&&`kind`in e)}parse(e,t){return typeof e==`string`||e&&typeof e==`object`&&`kind`in e||typeof e==`function`?new W(this,e):new W(this,null)}encode(e,t){return typeof e==`function`?null:e}create(){return{kind:`new`,type:(this._call.returns??this.registry.void()).toJSON()}}random(e){return this.create()}like(t){if(!(t instanceof e))return this;let n=this.registry,r=n.like(t._call.args);if(r.name===`null`)return n.null();let i=t._call.returns?n.like(t._call.returns):void 0;if(i&&i.name===`null`)return n.null();let a=t._call.throws?n.like(t._call.throws):void 0;return a&&a.name===`null`?n.null():n.fn({args:r,returns:i,throws:a,generic:this.generic})}compatibleType(t,n,r){return!(!(t instanceof e)||!this._call.args.compatible(t._call.args,n,r)||this._call.returns&&t._call.returns&&!this._call.returns.compatible(t._call.returns,n,r))}or(t){return t instanceof e?new e(this.registry,{args:this._call.args.or(t._call.args),returns:this._call.returns&&t._call.returns?this._call.returns.or(t._call.returns):this._call.returns??t._call.returns,throws:this._call.throws&&t._call.throws?this._call.throws.or(t._call.throws):this._call.throws??t._call.throws}):this}narrow(e){return{}}call(e){return this._call}props(e){return super.props(e)}toJSON(){let t=Object.keys(this.generic),n=t.length===0?void 0:Object.fromEntries(t.map(e=>[e,this.generic[e].toJSON()]));return Jm({name:e.NAME,call:this._call.toJSON(),generic:n})}clone(){let t={};for(let[e,n]of Object.entries(this.generic))t[e]=n.clone();return new e(this.registry,{args:this._call.args.clone(),returns:this._call.returns?.clone(),throws:this._call.throws?.clone(),get:this._call.get,set:this._call.set},t)}toCode(e,t){let n=this._call.returns?.toCode(void 0,t)??`void`;return this.docsPrefix(t)+`${U.renderGenerics(this.generic,t)}${this._call.renderTypes(t)}(${U.formatParams(this._call.args,t)}): ${n}`}valueA(){return R.union([R.string(),R.ref(`Expr`)])}},Ng=class e extends U{static NAME=`interface`;static consumes=[`props`,`get`,`call`];name=e.NAME;static optionKeys=[];static genericKeys=[];_props;_get;_call;static from(t,n){return n.registry,new e(n,{props:t.props?Nh.fromMap(t.props,n):{},get:t.get?Ph.from(t.get,n):void 0,call:t.call?Fh.from(t.call,n):void 0})}constructor(e,t){super(e,{});let n={};if(t.props)for(let[e,r]of Object.entries(t.props))n[e]=Nh.from(r);this._props=n,this._get=t.get,this._call=t.call}valid(e,t){return!0}parse(e,t){return new W(this,e)}encode(e,t){return e}create(){return null}random(e){return null}like(t){if(!(t instanceof e))return this;let n=this.registry,r={};for(let[e,i]of Object.entries(t._props)){let t=n.like(i.type);if(t.name===`null`)return n.null();r[e]={type:t}}let i;if(t._get){let e=n.like(t._get.key),r=n.like(t._get.value);if(e.name===`null`||r.name===`null`)return n.null();i=new Ph({key:e,value:r})}let a;if(t._call){let e=n.like(t._call.args);if(e.name===`null`)return n.null();let r=t._call.returns?n.like(t._call.returns):void 0;if(r&&r.name===`null`)return n.null();a=new Fh({args:e,returns:r})}return new e(n,{props:r,get:i,call:a})}compatibleType(e,t,n){let r=e.props(n);for(let[e,i]of Object.entries(this._props)){let a=r[e];if(!a||!i.type.compatible(a.type,t,n))return!1}if(this._get){let r=e.get(n);if(!r||!this._get.key.compatible(r.key,t,n)||!this._get.value.compatible(r.value,t,n))return!1}if(this._call){let r=e.call(n);if(!r||!this._call.args.compatible(r.args,t,n)||this._call.returns&&r.returns&&!this._call.returns.compatible(r.returns,t,n))return!1}return!0}flexible(){return!0}isUniversal(){return Object.keys(this._props).length===0&&!this._get&&!this._call}or(t){if(!(t instanceof e))return this;let n={};for(let e of Object.keys(this._props))e in t._props&&(n[e]={type:this._props[e].type.or(t._props[e].type)});return new e(this.registry,{props:n})}narrow(e){return{}}props(e){return{...super.props(e),...this._props}}get(e){return this._get}call(e){return this._call}toJSON(){return Jm({name:e.NAME,props:Object.keys(this._props).length>0?Nh.toJSONMap(this._props):void 0,get:this._get?.toJSON(),call:this._call?.toJSON()})}clone(){let t={};for(let[e,n]of Object.entries(this._props))t[e]={...n,type:n.type.clone()};return new e(this.registry,{props:t,get:this._get,call:this._call})}toCode(e,t){let n=t?.includeComments!==!1,r=[];for(let[e,i]of Object.entries(this._props)){let a=i.type.isOptional(),o=a?i.type.required():i.type,s=a?`${e}?`:e,c=i.docs&&n?`/* ${i.docs} */ `:``;r.push(`${c}${s}: ${o.toCode(void 0,t)}`)}if(this._get&&r.push(`[key: ${this._get.key.toCode(void 0,t)}]: ${this._get.value.toCode(void 0,t)}`),this._call){let e=this._call.returns?.toCode(void 0,t)??`void`;r.push(`(${this._call.args.toCode(void 0,t)}): ${e}`)}let i=r.length===0?`iface`:`iface{${Hh(r,{indent:Uh(t)})}}`;return this.docsPrefix(t)+i}toCodeRef(e,t){return this.docsPrefix(t)+`iface`}refProps(){return this._props}refGet(){return this._get}refCall(){return this._call}valueA(e){let t=e?.includeDocs??`none`,n={};for(let[r,i]of Object.entries(this._props)){let a=i.type.toA(e);t===`all`&&i.docs&&(a=a.describe(i.docs)),n[r]=a}return this.objectA(n,e)}toNewA(e){let t=e?.includeDocs??`none`,n={};for(let[e,r]of Object.entries(this._props)){let i=R.ref(`Expr`);t===`all`&&r.docs&&(i=i.describe(r.docs)),n[e]=i}return this.describeA(R.object(n),e)}},Pg=class e extends U{static NAME=`literal`;name=e.NAME;static optionKeys=[`value`];static genericKeys=[`T`];inner;static from(t,n){let r=n.registry,i=t.generic?.T?n.parse(t.generic.T):r.any(),a=t.options?.value;return new e(n,i,a)}constructor(e,t,n){super(e,{value:n},{T:t}),this.inner=t}get literal(){return this.options.value}valid(e,t){return this.inner.valid(e,t)&&e===this.literal}parse(e,t){let n=this.inner.parse(e,t);if(n.raw!==this.literal)throw new Fm({path:[],code:`literal.not-match`,message:`literal: expected ${String(this.literal)}, got ${String(n.raw)}`,severity:`error`});return new W(this,n.raw)}encode(e,t){return this.inner.encode(e,t)}encodeAs(e,t,n){return this.inner.encodeAs(e,t,n)}create(){return this.literal}random(e){return this.literal}compatibleType(t,n,r){return t instanceof e?this.inner.compatible(t.inner,n,r)&&this.literal===t.literal:!n?.exact&&this.inner.compatible(t,n,r)}isUniversal(){return this.inner.isUniversal()}or(t){return t instanceof e&&(t.literal,this.literal),this}narrow(e){if(e.value!==void 0&&e.value!==this.literal)throw new Fm({path:[],code:`literal.narrow`,message:`literal value cannot change via narrow`,severity:`error`});return this.options}props(){return this.inner.props()}toJSON(){return{name:e.NAME,generic:{T:this.inner.toJSON()},options:{value:this.literal}}}clone(){return new e(this.registry,this.inner.clone(),this.literal)}toCode(e,t){return this.docsPrefix(t)+`literal<${this.inner.toCode(void 0,t)}>`+Bh({value:this.literal})}valueA(){return R.literal(this.literal)}},Fg=class e extends U{static NAME=`list`;name=e.NAME;static optionKeys=[`minLength`,`maxLength`];static genericKeys=[`V`];static from(t,n){let r=n.registry,i=t.generic?.V?n.parse(t.generic.V):r.any();return new e(n,i,t.options??{})}constructor(e,t,n={}){super(e,n,{V:t})}get item(){return this.generic.V}valid(e,t){if(!Array.isArray(e))return!1;let{minLength:n,maxLength:r}=this.options;return n!==void 0&&e.length<n||r!==void 0&&e.length>r?!1:e.every(e=>e instanceof W&&e.type.valid(e.raw,t)&&wh(this.item,e.type,t))}parse(e,t){if(!Array.isArray(e))throw new Fm({path:[],code:`list.invalid`,message:`list.parse: expected array, got ${typeof e}`,severity:`error`});let n=e.map(e=>this.registry.parseValue(e,this.item,t));if(!this.valid(n,t))throw new Fm({path:[],code:`list.constraint`,message:`list.parse: length constraints violated`,severity:`error`});return new W(this,n)}encode(e,t){return this.encodeAs(e,Ah,t)}encodeAs(e,t,n){return e.map(e=>Oh(e,t,n))}create(){let e=this.options.minLength??0;return Array.from({length:e},()=>new W(this.item,this.item.create()))}random(e){let t=this.options.minLength??0,n=e(t,this.options.maxLength??Math.max(t,5),!0);return Array.from({length:n},()=>new W(this.item,this.item.random(e)))}forEachNewSlot(e,t){if(!Array.isArray(e))return!1;for(let n=0;n<e.length;n++)t.slot(this.item,e[n],n);return!0}async newFill(e,t,n){if(!Array.isArray(e))return super.newFill(e,t,n);let r=[];for(let i of e)r.push(await this.item.newFill(i,t,n));return r}like(t){if(!(t instanceof e))return this;let n=this.registry.like(t.item);return n.name===`null`?n:this.registry.list(n)}compatibleType(t,n,r){if(!(t instanceof e)||!this.item.compatible(t.item,n,r))return!1;if(!n?.value)return!0;let i=this.options,a=t.options;return!(i.minLength!==void 0&&(a.minLength===void 0||a.minLength<i.minLength)||i.maxLength!==void 0&&(a.maxLength===void 0||a.maxLength>i.maxLength))}or(t){if(!(t instanceof e))return this;let n=this.options,r=t.options;return new e(this.registry,this.item.or(t.item),{minLength:n.minLength!==void 0&&r.minLength!==void 0?Math.min(n.minLength,r.minLength):void 0,maxLength:n.maxLength!==void 0&&r.maxLength!==void 0?Math.max(n.maxLength,r.maxLength):void 0})}narrow(e){let t=this.options,n=(e,t)=>{throw new Fm({path:[],code:e,message:t,severity:`error`})},r={...t};return e.minLength!==void 0&&(t.minLength!==void 0&&e.minLength<t.minLength&&n(`list.widen.minLength`,`local ${e.minLength} < base ${t.minLength}`),r.minLength=e.minLength),e.maxLength!==void 0&&(t.maxLength!==void 0&&e.maxLength>t.maxLength&&n(`list.widen.maxLength`,`local ${e.maxLength} > base ${t.maxLength}`),r.maxLength=e.maxLength),r}get(){let e=this.registry;return new Ph({key:e.num({whole:!0,min:0}),value:this.item,get:e.nativeExpr(`list.indexGet`),set:e.nativeExpr(`list.indexSet`),loop:e.nativeExpr(`list.iterate`)})}props(){let e=this.registry,t=this.item,n=e.num(),r=e.bool(),i=e.text(),a=e.void(),o=e.optional(t),s=e.list(t),c=r=>e.fn({args:e.obj({value:{type:t},index:{type:n}}),returns:r});return{...super.props(),length:e.prop(n,`list.length`),at:e.method({index:n},o,`list.at`),push:e.method({value:t},a,`list.push`),pop:e.method({},o,`list.pop`),shift:e.method({},o,`list.shift`),unshift:e.method({value:t},a,`list.unshift`),insert:e.method({index:n,value:t},a,`list.insert`),remove:e.method({index:n},t,`list.remove`),clear:e.method({},a,`list.clear`),slice:e.method({start:e.optional(n),end:e.optional(n)},s,`list.slice`),concat:e.method({other:s},s,`list.concat`),reverse:e.method({},s,`list.reverse`),join:e.method({separator:e.optional(i)},i,`list.join`),indexOf:e.method({value:t},n,`list.indexOf`),contains:e.method({value:t},r,`list.contains`),unique:e.method({},s,`list.unique`),duplicates:e.method({},s,`list.duplicates`),map:e.method({fn:c(e.alias(`R`))},e.list(e.alias(`R`)),`list.map`,{generic:{R:e.any()}}),filter:e.method({fn:c(r)},s,`list.filter`),find:e.method({fn:c(r)},o,`list.find`),reduce:e.method({fn:e.fn({args:e.obj({acc:{type:e.alias(`R`)},value:{type:t},index:{type:n}}),returns:e.alias(`R`)}),initial:e.alias(`R`)},e.alias(`R`),`list.reduce`,{generic:{R:e.any()}}),some:e.method({fn:c(r)},r,`list.some`),every:e.method({fn:c(r)},r,`list.every`),sort:e.method({fn:e.optional(e.fn({args:e.obj({a:{type:t},b:{type:t}}),returns:n}))},s,`list.sort`),isEmpty:e.method({},r,`list.isEmpty`),isNotEmpty:e.method({},r,`list.isNotEmpty`),first:e.prop(o,`list.first`),last:e.prop(o,`list.last`)}}toJSON(){return Jm({name:e.NAME,generic:{V:this.item.toJSON()},options:Object.keys(this.options).length>0?{...this.options}:void 0})}clone(){return new e(this.registry,this.item.clone(),{...this.options})}toCode(e,t){return this.docsPrefix(t)+`list<${this.item.toCode(void 0,t)}>`+Bh(this.options,{minLength:0})}valueA(e){let t=R.array(this.item.toA(e));return this.options.minLength!==void 0&&(t=t.min(this.options.minLength)),this.options.maxLength!==void 0&&(t=t.max(this.options.maxLength)),t}toNewA(e){let t=R.array(R.ref(`Expr`));return this.options.minLength!==void 0&&(t=t.min(this.options.minLength)),this.options.maxLength!==void 0&&(t=t.max(this.options.maxLength)),this.describeA(t,e)}describe(t){if(Array.isArray(t))return new e(this.registry,this.registry.any(),{})}};function Ig(e){return Array.isArray(e)&&e.length===2&&e[0]instanceof W&&e[1]instanceof W}function Lg(e){if(Array.isArray(e))return[e[0],e[1]];let t=e;return[t?.key,t?.value]}function Rg(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Map)}var zg=class e extends U{static NAME=`map`;name=e.NAME;static optionKeys=[];static genericKeys=[`K`,`V`];static from(t,n){let r=n.registry,i=t.generic?.K?n.parse(t.generic.K):r.text(),a=t.generic?.V?n.parse(t.generic.V):r.any();return new e(n,i,a)}constructor(e,t,n){super(e,{},{K:t,V:n})}get key(){return this.generic.K}get value(){return this.generic.V}valid(e,t){if(!(e instanceof Map))return!1;for(let[,n]of e){if(!Array.isArray(n)||n.length!==2)return!1;let[e,r]=n;if(!(e instanceof W)||!(r instanceof W)||!e.type.valid(e.raw,t)||!r.type.valid(r.raw,t)||!wh(this.key,e.type,t)||!wh(this.value,r.type,t))return!1}return!0}parse(e,t){let n=e instanceof Map?Array.from(e,([e,t])=>Ig(t)?t:[e,t]):this.textKeyed()&&Rg(e)?Object.entries(e):e;if(!Array.isArray(n))throw new Fm({path:[],code:`map.invalid`,message:`map.parse: expected array of [key, value] pairs`,severity:`error`});let r=new Map;for(let e of n){let[n,i]=Array.isArray(e)?e:[e.key,e.value],a=this.registry.parseValue(n,this.key,t),o=this.registry.parseValue(i,this.value,t);r.set(a.raw,[a,o])}return new W(this,r)}encode(e,t){return this.encodeAs(e,Ah,t)}encodeAs(e,t,n){return t.form===`logical`&&this.textKeyed()?Object.fromEntries(Array.from(e,([,[e,r]])=>[String(Oh(e,t,n)),Oh(r,t,n)])):Array.from(e,([,[e,r]])=>({key:Oh(e,t,n),value:Oh(r,t,n)}))}textKeyed(){return this.key.name===`text`}create(){return new Map}forEachNewSlot(e,t){if(!Array.isArray(e))return!1;for(let n=0;n<e.length;n++){let[r,i]=Lg(e[n]);t.slot(this.key,r,`${n}.key`),t.slot(this.value,i,`${n}.value`)}return!0}async newFill(e,t,n){if(!Array.isArray(e))return super.newFill(e,t,n);let r=[];for(let i of e){let[e,a]=Lg(i);r.push({key:await this.key.newFill(e,t,n),value:await this.value.newFill(a,t,n)})}return r}random(e){let t=e(0,5,!0),n=new Map;for(let r=0;r<t;r++){let t=this.key.random(e),r=this.value.random(e);n.set(t,[new W(this.key,t),new W(this.value,r)])}return n}like(t){if(!(t instanceof e))return this;let n=this.registry.like(t.key),r=this.registry.like(t.value);return n.name===`null`||r.name===`null`?this.registry.null():this.registry.map(n,r)}compatibleType(t,n,r){return t instanceof e&&this.key.compatible(t.key,n,r)&&this.value.compatible(t.value,n,r)}or(t){return t instanceof e?new e(this.registry,this.key.or(t.key),this.value.or(t.value)):this}narrow(e){return{}}get(){let e=this.registry;return new Ph({key:this.key,value:this.value,get:e.nativeExpr(`map.indexGet`),set:e.nativeExpr(`map.indexSet`),loop:e.nativeExpr(`map.iterate`)})}props(){let e=this.registry,t=this.key,n=this.value,r=e.num(),i=e.bool(),a=e.void(),o=e.optional(n);return{...super.props(),size:e.prop(r,`map.size`),at:e.method({key:t},o,`map.at`),has:e.method({key:t},i,`map.has`),delete:e.method({key:t},i,`map.delete`),clear:e.method({},a,`map.clear`),keys:e.method({},e.list(t),`map.keys`),values:e.method({},e.list(n),`map.values`),isEmpty:e.method({},i,`map.isEmpty`),isNotEmpty:e.method({},i,`map.isNotEmpty`)}}toJSON(){return{name:e.NAME,generic:{K:this.key.toJSON(),V:this.value.toJSON()}}}clone(){return new e(this.registry,this.key.clone(),this.value.clone())}toCode(e,t){return this.docsPrefix(t)+`map<${this.key.toCode(void 0,t)}, ${this.value.toCode(void 0,t)}>`}valueA(e){return this.key.name===`text`?R.record(this.value.toA(e)):R.array(this.objectA({key:this.key.toA(e),value:this.value.toA(e)},e))}toNewA(e){return this.describeA(R.array(R.object({key:R.ref(`Expr`),value:R.ref(`Expr`)})),e)}describe(t){return t instanceof Map?new e(this.registry,this.registry.any(),this.registry.any()):void 0}},Bg=class e extends U{constructor(e,t){super(e,{excluded:t.toJSON()}),this.excluded=t}excluded;static NAME=`not`;name=e.NAME;static optionKeys=[`excluded`];static genericKeys=[];static from(t,n){let r=n.registry,i=t.options?.excluded?n.parse(t.options.excluded):r.any();return new e(n,i)}valid(e,t){return!this.excluded.valid(e,t)}parse(e,t){if(this.excluded.valid(e,t))throw new Fm({path:[],code:`not.excluded`,message:`not: value matches excluded type ${this.excluded.name}`,severity:`error`});return new W(this,e)}encode(e,t){return e}create(){return null}random(e){return null}like(t){if(!(t instanceof e))return this;let n=this.registry.like(t.excluded);return n.name===`null`?n:this.registry.not(n)}compatibleType(t,n,r){return n?.exact?t instanceof e&&this.excluded.exact(t.excluded,r):!this.excluded.compatible(t,n,r)}flexible(){return!0}or(t){return t instanceof e?new e(this.registry,this.registry.or([this.excluded,t.excluded])):this}narrow(e){return{excluded:e.excluded??this.options.excluded}}props(){let e=this.registry;return{...super.props(),typeOf:e.method({},e.text(),`not.typeOf`),toText:e.method({},e.text(),`not.toText`)}}toJSON(){return{name:e.NAME,options:{excluded:this.excluded.toJSON()}}}clone(){return new e(this.registry,this.excluded.clone())}toCode(e,t){return this.docsPrefix(t)+`not<${this.excluded.toCode(void 0,t)}>`}valueA(e){return R.not(this.excluded.toA(e))}},Vg=class e extends U{static NAME=`null`;name=e.NAME;static optionKeys=[];static genericKeys=[];static from(t,n){return n.registry,new e(n,{})}valid(e){return e===null}parse(e){if(e!==null)throw new Fm({path:[],code:`null.invalid`,message:`null expects null, got ${typeof e}`,severity:`error`});return new W(this,null)}encode(e){return null}create(){return null}random(e){return null}compatibleType(t,n){return t instanceof e}or(e){return this}narrow(e){if(e&&Object.keys(e).length>0)throw new Fm({path:[],code:`null.no-options`,message:`null has no narrowable options`,severity:`error`});return{}}props(){let e=this.registry;return{...super.props(),toText:e.method({},e.text(),`null.toText`),toBool:e.method({},e.bool(),`null.toBool`)}}toJSON(){return{name:e.NAME}}clone(){return new e(this.registry,{})}toCode(e,t){return this.docsPrefix(t)+`null`}valueA(){return R.null()}},Hg=class e extends U{constructor(e,t){super(e,{},{T:t}),this.inner=t}inner;static NAME=`nullable`;name=e.NAME;static optionKeys=[];static genericKeys=[`T`];static from(t,n){let r=n.registry,i=t.generic?.T?n.parse(t.generic.T):r.any();return new e(n,i)}valid(e,t){return e===null||this.inner.valid(e,t)}parse(e,t){if(e===null)return new W(this,null);let n=this.inner.parse(e,t);return new W(this,n.raw)}parsesExprValue(e){return this.inner.parsesExprValue(e)}encode(e,t){return this.encodeAs(e,Ah,t)}encodeAs(e,t,n){return e===null?null:this.inner.encodeAs(e,t,n)}forEachNewSlot(e,t){return e!=null&&this.inner.forEachNewSlot(e,t)}async newFill(e,t,n){return e==null?e:this.inner.newFill(e,t,n)}create(){return null}random(e){return e(0,9,!0)<3?null:this.inner.random(e)}like(t){if(!(t instanceof e))return this;let n=this.registry.like(t.inner);return n.name===`null`?n:this.registry.nullable(n)}compatibleType(t,n,r){return t instanceof e?this.inner.compatible(t.inner,n,r):!n?.exact&&this.inner.compatible(t,n,r)}or(t){return t instanceof e?new e(this.registry,this.inner.or(t.inner)):this}required(){return this.inner}isUniversal(){return this.inner.isUniversal()}narrow(e){if(e&&Object.keys(e).length>0)throw new Fm({path:[],code:`nullable.no-options`,message:`nullable has no narrowable options`,severity:`error`});return{}}props(){let e=this.registry,t=this.inner;return{...super.props(),value:e.prop(t,`nullable.value`),isNull:e.method({},e.bool(),`nullable.isNull`),or:e.method({fallback:t},t,`nullable.or`),map:e.method({fn:e.fn({args:e.obj({value:{type:t}}),returns:e.alias(`R`)})},e.nullable(e.alias(`R`)),`nullable.map`,{generic:{R:e.any()}})}}toJSON(){return{name:e.NAME,generic:{T:this.inner.toJSON()}}}clone(){return new e(this.registry,this.inner.clone())}toCode(e,t){return this.docsPrefix(t)+`nullable<${this.inner.toCode(void 0,t)}>`}valueA(e){return R.nullable(this.inner.toA(e))}toNewA(e){return this.describeA(R.nullable(this.inner.toNewA(e)),e)}},Ug=class e extends U{static NAME=`num`;name=e.NAME;static optionKeys=[`min`,`max`,`whole`,`minPrecision`,`maxPrecision`,`prefix`,`suffix`];static genericKeys=[];static from(t,n){return n.registry,new e(n,t.options??{})}valid(e){if(typeof e!=`number`||Number.isNaN(e))return!1;let{min:t,max:n,whole:r}=this.options;return!(t!==void 0&&e<t||n!==void 0&&e>n||r&&!Number.isInteger(e))}parse(e){let t=typeof e==`string`?Number(e):e;if(typeof t!=`number`||Number.isNaN(t))throw new Fm({path:[],code:`num.invalid`,message:`num.parse: not a number \u2014 ${String(e)}`,severity:`error`});if(!this.valid(t))throw new Fm({path:[],code:`num.out-of-range`,message:`num.parse: ${t} violates options ${JSON.stringify(this.options)}`,severity:`error`});return new W(this,t)}encode(e){return e}create(){let{min:e,max:t,whole:n}=this.options,r=0;if(e!==void 0&&r<e&&(r=e),t!==void 0&&r>t&&(r=t),n&&!Number.isInteger(r)){let e=Math.ceil(r);r=t!==void 0&&e>t?Math.floor(r):e}return r}random(e){return e(this.options.min??0,this.options.max??100,this.options.whole??!1)}compatibleType(t,n){if(!(t instanceof e))return!1;if(!n?.value)return!0;let r=this.options,i=t.options;return!(r.min!==void 0&&(i.min===void 0||i.min<r.min)||r.max!==void 0&&(i.max===void 0||i.max>r.max)||r.whole&&!i.whole)}or(t){if(!(t instanceof e))return this;let n=this.options,r=t.options;return new e(this.registry,{min:n.min!==void 0&&r.min!==void 0?Math.min(n.min,r.min):void 0,max:n.max!==void 0&&r.max!==void 0?Math.max(n.max,r.max):void 0,whole:n.whole&&r.whole,minPrecision:n.minPrecision!==void 0&&r.minPrecision!==void 0?Math.min(n.minPrecision,r.minPrecision):void 0,maxPrecision:n.maxPrecision!==void 0&&r.maxPrecision!==void 0?Math.max(n.maxPrecision,r.maxPrecision):void 0,prefix:n.prefix===r.prefix?n.prefix:void 0,suffix:n.suffix===r.suffix?n.suffix:void 0})}narrow(e){let t=this.options,n=(e,t)=>{throw new Fm({path:[],code:e,message:t,severity:`error`})},r={...t};return e.min!==void 0&&(t.min!==void 0&&e.min<t.min&&n(`num.widen.min`,`local.min ${e.min} < base.min ${t.min}`),r.min=e.min),e.max!==void 0&&(t.max!==void 0&&e.max>t.max&&n(`num.widen.max`,`local.max ${e.max} > base.max ${t.max}`),r.max=e.max),e.whole!==void 0&&(t.whole===!0&&!e.whole&&n(`num.widen.whole`,`base requires whole; local cannot remove`),r.whole=e.whole),e.minPrecision!==void 0&&(t.minPrecision!==void 0&&e.minPrecision<t.minPrecision&&n(`num.widen.minPrecision`,`minPrecision cannot decrease`),r.minPrecision=e.minPrecision),e.maxPrecision!==void 0&&(t.maxPrecision!==void 0&&e.maxPrecision>t.maxPrecision&&n(`num.widen.maxPrecision`,`maxPrecision cannot increase`),r.maxPrecision=e.maxPrecision),e.prefix!==void 0&&(r.prefix=e.prefix),e.suffix!==void 0&&(r.suffix=e.suffix),r}get(){let e=this.registry;return new Ph({key:e.num({whole:!0,min:0}),value:e.num(),loop:e.nativeExpr(`num.loop`)})}props(){let e=this.registry,t=e.num(),n=e.bool(),r=e.text(),i=e.optional(t);return{...super.props(),eq:e.method({other:t,epsilon:i},n,`num.eq`),neq:e.method({other:t,epsilon:i},n,`num.neq`),lt:e.method({other:t},n,`num.lt`),lte:e.method({other:t},n,`num.lte`),gt:e.method({other:t},n,`num.gt`),gte:e.method({other:t},n,`num.gte`),add:e.method({other:t},t,`num.add`),sub:e.method({other:t},t,`num.sub`),mul:e.method({other:t},t,`num.mul`),div:e.method({other:t},t,`num.div`),mod:e.method({other:t},t,`num.mod`),pow:e.method({other:t},t,`num.pow`),abs:e.method({},t,`num.abs`),neg:e.method({},t,`num.neg`),sign:e.method({},t,`num.sign`),sqrt:e.method({},t,`num.sqrt`),min:e.method({other:t},t,`num.min`),max:e.method({other:t},t,`num.max`),clamp:e.method({min:t,max:t},t,`num.clamp`),floor:e.method({},t,`num.floor`),ceil:e.method({},t,`num.ceil`),round:e.method({},t,`num.round`),isZero:e.method({},n,`num.isZero`),isPositive:e.method({},n,`num.isPositive`),isNegative:e.method({},n,`num.isNegative`),isInteger:e.method({},n,`num.isInteger`),isEven:e.method({},n,`num.isEven`),isOdd:e.method({},n,`num.isOdd`),toText:e.method({precision:i},r,`num.toText`),toBool:e.method({},n,`num.toBool`)}}toJSON(){return Jm({name:e.NAME,options:Object.keys(this.options).length>0?{...this.options}:void 0})}clone(){return new e(this.registry,{...this.options})}toCode(e,t){return this.docsPrefix(t)+`num`+Bh(this.options,{minPrecision:1,maxPrecision:7,prefix:``,suffix:``})}valueA(){let e=this.options.whole?R.int():R.number();return this.options.min!==void 0&&(e=e.min(this.options.min)),this.options.max!==void 0&&(e=e.max(this.options.max)),e}describe(t){if(!(typeof t!=`number`||Number.isNaN(t)))return new e(this.registry,{whole:Number.isInteger(t)})}},Wg=class e extends U{constructor(e,t){super(e,{},{T:t}),this.inner=t}inner;static NAME=`optional`;name=e.NAME;static optionKeys=[];static genericKeys=[`T`];static from(t,n){let r=n.registry,i=t.generic?.T?n.parse(t.generic.T):r.any();return new e(n,i)}valid(e,t){return e===void 0||this.inner.valid(e,t)}parse(e,t){if(e==null)return new W(this,void 0);let n=this.inner.parse(e,t);return new W(this,n.raw)}parsesExprValue(e){return this.inner.parsesExprValue(e)}encode(e,t){return this.encodeAs(e,Ah,t)}encodeAs(e,t,n){return e===void 0?null:this.inner.encodeAs(e,t,n)}forEachNewSlot(e,t){return e!=null&&this.inner.forEachNewSlot(e,t)}async newFill(e,t,n){return e==null?e:this.inner.newFill(e,t,n)}create(){}random(e){if(!(e(0,9,!0)<3))return this.inner.random(e)}like(t){if(!(t instanceof e))return this;let n=this.registry.like(t.inner);return n.name===`null`?n:this.registry.optional(n)}compatibleType(t,n,r){return t instanceof e?this.inner.compatible(t.inner,n,r):!n?.exact&&this.inner.compatible(t,n,r)}or(t){return t instanceof e?new e(this.registry,this.inner.or(t.inner)):this}required(){return this.inner}isOptional(){return!0}isUniversal(){return this.inner.isUniversal()}narrow(e){if(e&&Object.keys(e).length>0)throw new Fm({path:[],code:`optional.no-options`,message:`optional has no narrowable options`,severity:`error`});return{}}props(){let e=this.registry,t=this.inner;return{...super.props(),value:e.prop(t,`optional.value`),has:e.method({},e.bool(),`optional.has`),or:e.method({fallback:t},t,`optional.or`),map:e.method({fn:e.fn({args:e.obj({value:{type:t}}),returns:e.alias(`R`)})},e.optional(e.alias(`R`)),`optional.map`,{generic:{R:e.any()}})}}toJSON(){return{name:e.NAME,generic:{T:this.inner.toJSON()}}}clone(){return new e(this.registry,this.inner.clone())}toCode(e,t){return this.docsPrefix(t)+`optional<${this.inner.toCode(void 0,t)}>`}valueA(e){return R.optional(this.inner.toA(e))}toNewA(e){return this.describeA(R.optional(this.inner.toNewA(e)),e)}},Gg=class e extends U{static NAME=`or`;name=e.NAME;static optionKeys=[`types`];static genericKeys=[];static from(t,n){n.registry;let r=(t.options?.types??[]).map(e=>n.parse(e));return new e(n,r)}constructor(e,t){super(e,{variants:t})}get variants(){return this.options.variants}valid(e,t){return this.variants.some(n=>n.valid(e,t))}parse(e,t){for(let n of this.variants)try{let r=n.parse(e,t);return new W(this,r.raw)}catch{continue}throw new Fm({path:[],code:`or.no-match`,message:`or: no variant matched (${this.variants.map(e=>e.name).join(` | `)})`,severity:`error`})}encode(e,t){let n=this.variants.find(n=>n.valid(e,t));if(!n)throw new Fm({path:[],code:`or.dump.no-match`,message:`or.dump: value does not satisfy any variant`,severity:`error`});return n.encode(e,t)}parsesExprValue(e){return this.variants.some(t=>t.parsesExprValue(e))}encodeAs(e,t,n){let r=this.variants.find(t=>t.valid(e,n));if(!r)throw new Fm({path:[],code:`or.dump.no-match`,message:`or.dump: value does not satisfy any variant`,severity:`error`});return r.encodeAs(e,t,n)}create(){return this.variants[0]?.create()??null}random(e){let t=e(0,this.variants.length-1,!0);return this.variants[t]?.random(e)??null}like(t){if(!(t instanceof e))return this;let n=t.variants.map(e=>this.registry.like(e)).filter(e=>e.name!==`null`);return n.length===0?this.registry.null():n.length===1?n[0]:this.registry.or(n)}compatibleType(e,t,n){return this.variants.some(r=>r.compatible(e,t,n))}or(t){return t instanceof e?new e(this.registry,[...this.variants,...t.variants]):new e(this.registry,[...this.variants,t])}simplify(){return this.variants.length===1?this.variants[0]:this}narrow(e){return this.options}props(){let e=super.props();if(this.variants.length===0)return e;let t=this.variants.map(e=>e.props()),n=Object.keys(t[0]).filter(e=>t.every(t=>e in t)),r={...e};for(let e of n){let n=t.map(t=>t[e].type);r[e]={type:this.registry.or(n)}}return r}get(){let e=this.variants.map(e=>e.get());if(e.some(e=>!e))return;let t=e;return new Ph({key:this.registry.and(t.map(e=>e.key)),value:this.registry.or(t.map(e=>e.value))})}call(){let e=this.variants.map(e=>e.call());if(e.some(e=>!e))return;let t=e,n=t.map(e=>e.returns).filter(e=>!!e),r=t.map(e=>e.throws).filter(e=>!!e);return new Fh({args:this.registry.and(t.map(e=>e.args)),returns:n.length===t.length?this.registry.or(n):void 0,throws:r.length>0?this.registry.or(r):void 0})}toJSON(){return{name:e.NAME,options:{types:this.variants.map(e=>e.toJSON())}}}clone(){return new e(this.registry,this.variants.map(e=>e.clone()))}toCode(e,t){return this.docsPrefix(t)+`or<${this.variants.map(e=>e.toCode(void 0,t)).join(`, `)}>`}valueA(e){return this.variants.length===0?R.never():this.variants.length===1?this.variants[0].toA(e):R.union(this.variants.map(t=>t.toA(e)))}toNewA(e){return this.variants.length===0?this.describeA(R.never(),e):this.variants.length===1?this.describeA(this.variants[0].toNewA(e),e):this.describeA(R.union(this.variants.map(t=>t.toNewA(e))),e)}},Kg=class e extends U{static NAME=`text`;name=e.NAME;static optionKeys=[`minLength`,`maxLength`,`pattern`,`flags`];static genericKeys=[];_regex;static from(t,n){return n.registry,new e(n,t.options??{})}regex(){if(this._regex)return this._regex;if(this.options.pattern)return this._regex=new RegExp(this.options.pattern,this.options.flags),this._regex}valid(e){if(typeof e!=`string`)return!1;let{minLength:t,maxLength:n}=this.options;if(t!==void 0&&e.length<t||n!==void 0&&e.length>n)return!1;let r=this.regex();return!(r&&!r.test(e))}parse(e){if(typeof e!=`string`)throw new Fm({path:[],code:`text.invalid`,message:`text.parse: expected string, got ${typeof e}`,severity:`error`});if(!this.valid(e))throw new Fm({path:[],code:`text.constraint`,message:`text.parse: value violates constraints`,severity:`error`});return new W(this,e)}encode(e){return e}create(){let e=this.options.minLength??0;return e>0?`a`.repeat(e):``}random(e){let t=e(this.options.minLength??0,this.options.maxLength??16,!0),n=``;for(let r=0;r<t;r++)n+=`abcdefghijklmnopqrstuvwxyz0123456789`[e(0,35,!0)];return n}compatibleType(t,n){if(!(t instanceof e))return!1;if(!n?.value)return!0;let r=this.options,i=t.options;return!(r.minLength!==void 0&&(i.minLength===void 0||i.minLength<r.minLength)||r.maxLength!==void 0&&(i.maxLength===void 0||i.maxLength>r.maxLength)||r.pattern&&r.pattern!==i.pattern)}or(t){if(!(t instanceof e))return this;let n=this.options,r=t.options;return new e(this.registry,{minLength:n.minLength!==void 0&&r.minLength!==void 0?Math.min(n.minLength,r.minLength):void 0,maxLength:n.maxLength!==void 0&&r.maxLength!==void 0?Math.max(n.maxLength,r.maxLength):void 0,pattern:n.pattern===r.pattern?n.pattern:void 0,flags:n.pattern===r.pattern?n.flags:void 0})}narrow(e){let t=this.options,n=(e,t)=>{throw new Fm({path:[],code:e,message:t,severity:`error`})},r={...t};return e.minLength!==void 0&&(t.minLength!==void 0&&e.minLength<t.minLength&&n(`text.widen.minLength`,`local ${e.minLength} < base ${t.minLength}`),r.minLength=e.minLength),e.maxLength!==void 0&&(t.maxLength!==void 0&&e.maxLength>t.maxLength&&n(`text.widen.maxLength`,`local ${e.maxLength} > base ${t.maxLength}`),r.maxLength=e.maxLength),e.pattern!==void 0&&(t.pattern!==void 0&&(e.pattern!==t.pattern||e.flags!==t.flags)&&n(`text.widen.pattern`,`pattern narrowing is only allowed when base has no pattern or matches exactly`),r.pattern=e.pattern,r.flags=e.flags),r}get(){let e=this.registry;return new Ph({key:e.num(),value:e.text({minLength:1,maxLength:1}),get:e.nativeExpr(`text.charAt`),loop:e.nativeExpr(`text.chars`)})}props(){let e=this.registry,t=e.text(),n=e.num(),r=e.bool(),i=e.optional(n);return{...super.props(),length:e.prop(n,`text.length`),eq:e.method({other:t},r,`text.eq`),neq:e.method({other:t},r,`text.neq`),contains:e.method({search:t},r,`text.contains`),startsWith:e.method({prefix:t},r,`text.startsWith`),endsWith:e.method({suffix:t},r,`text.endsWith`),trim:e.method({},t,`text.trim`),trimStart:e.method({},t,`text.trimStart`),trimEnd:e.method({},t,`text.trimEnd`),upper:e.method({},t,`text.upper`),lower:e.method({},t,`text.lower`),slice:e.method({start:n,end:i},t,`text.slice`),replace:e.method({search:t,replacement:t},t,`text.replace`),split:e.method({separator:t},e.list(t),`text.split`),concat:e.method({other:t},t,`text.concat`),repeat:e.method({count:n},t,`text.repeat`),indexOf:e.method({search:t,from:i},n,`text.indexOf`),lastIndexOf:e.method({search:t,from:i},n,`text.lastIndexOf`),match:e.method({pattern:t},e.list(t),`text.match`),test:e.method({pattern:t},r,`text.test`),isEmpty:e.method({},r,`text.isEmpty`),isNotEmpty:e.method({},r,`text.isNotEmpty`),toNum:e.method({},n,`text.toNum`),toBool:e.method({},r,`text.toBool`)}}toJSON(){return Jm({name:e.NAME,options:Object.keys(this.options).length>0?{...this.options}:void 0})}clone(){return new e(this.registry,{...this.options})}toCode(e,t){return this.docsPrefix(t)+`text`+Bh(this.options)}valueA(){let e=R.string();return this.options.minLength!==void 0&&(e=e.min(this.options.minLength)),this.options.maxLength!==void 0&&(e=e.max(this.options.maxLength)),this.options.pattern&&(e=e.pattern(this.options.pattern,this.options.flags)),e}describe(e){return typeof e==`string`?this:void 0}},qg=class e extends U{static NAME=`timestamp`;name=e.NAME;static optionKeys=[`min`,`max`,`utc`,`precision`];static genericKeys=[];static from(t,n){return n.registry,new e(n,t.options??{})}valid(e){return e instanceof Date&&!Number.isNaN(e.getTime())}parse(e){let t=e instanceof Date?e:typeof e==`string`?new Date(e):new Date(NaN);if(!this.valid(t))throw new Fm({path:[],code:`timestamp.invalid`,message:`timestamp.parse: invalid: ${String(e)}`,severity:`error`});return new W(this,t)}encode(e){return e.toISOString()}create(){return new Date}random(e){return new Date(e(Date.UTC(2e3,0,1),Date.UTC(2050,11,31),!0))}compatibleType(t,n){return t instanceof e}or(t){return t instanceof e,this}narrow(e){return this.options}props(){let e=this.registry,t=e.num({whole:!0}),n=e.bool(),r=e.text(),i=e.timestamp(),a=e.duration();return{...super.props(),year:e.prop(t,`timestamp.year`),month:e.prop(t,`timestamp.month`),day:e.prop(t,`timestamp.day`),hour:e.prop(t,`timestamp.hour`),minute:e.prop(t,`timestamp.minute`),second:e.prop(t,`timestamp.second`),millisecond:e.prop(t,`timestamp.millisecond`),eq:e.method({other:i},n,`timestamp.eq`),before:e.method({other:i},n,`timestamp.before`),after:e.method({other:i},n,`timestamp.after`),addDuration:e.method({duration:a},i,`timestamp.addDuration`),subDuration:e.method({duration:a},i,`timestamp.subDuration`),diff:e.method({other:i},a,`timestamp.diff`),toDate:e.method({},e.date(),`timestamp.toDate`),toEpoch:e.method({},t,`timestamp.toEpoch`),toText:e.method({format:e.optional(r)},r,`timestamp.toText`)}}toJSON(){return Jm({name:e.NAME,options:Object.keys(this.options).length>0?{...this.options}:void 0})}clone(){return new e(this.registry,{...this.options})}toCode(e,t){return this.docsPrefix(t)+`timestamp`+Bh(this.options)}valueA(){return R.string().pattern(`^\\d{4}-\\d{2}-\\d{2}[T ]\\d{2}:\\d{2}(:\\d{2}(\\.\\d+)?)?(Z|[+-]\\d{2}:?\\d{2})?$`).describe(`An ISO 8601 timestamp (YYYY-MM-DD HH:MM[:SS][Z]).`)}describe(e){return e instanceof Date?this:void 0}};function Jg(e){let t,n={};return Object.defineProperty(n,"elements",{enumerable:!0,get:()=>t??=e.map(e=>e.toJSON())}),n}var Yg=class e extends U{static NAME=`tuple`;name=e.NAME;static optionKeys=[`elements`];static genericKeys=[];elements;static from(t,n){n.registry;let r=(t.options?.elements??[]).map(e=>n.parse(e));return new e(n,r)}constructor(e,t){super(e,Jg(t)),this.elements=t}valid(e,t){return!Array.isArray(e)||e.length!==this.elements.length?!1:e.every((e,n)=>e instanceof W&&e.type.valid(e.raw,t)&&wh(this.elements[n],e.type,t))}parse(e,t){if(!Array.isArray(e)||e.length!==this.elements.length)throw new Fm({path:[],code:`tuple.invalid`,message:`tuple.parse: expected array of length ${this.elements.length}`,severity:`error`});let n=this.elements.map((n,r)=>this.registry.parseValue(e[r],n,t));return new W(this,n)}encode(e,t){return this.encodeAs(e,Ah,t)}encodeAs(e,t,n){if(!Array.isArray(e))throw new Fm({path:[],code:`tuple.invalid`,message:`tuple.encode: expected an array of cells`,severity:`error`});return e.map(e=>Oh(e,t,n))}create(){return this.elements.map(e=>new W(e,e.create()))}forEachNewSlot(e,t){if(!Array.isArray(e))return!1;for(let n=0;n<this.elements.length&&n<e.length;n++)t.slot(this.elements[n],e[n],n);return!0}async newFill(e,t,n){if(!Array.isArray(e))return super.newFill(e,t,n);let r=[];for(let i=0;i<e.length;i++){let a=this.elements[i];r.push(a?await a.newFill(e[i],t,n):e[i])}return r}random(e){return this.elements.map(t=>new W(t,t.random(e)))}like(t){if(!(t instanceof e)||t.elements.length!==this.elements.length)return this;let n=t.elements.map(e=>this.registry.like(e));return n.some(e=>e.name===`null`)?this.registry.null():this.registry.tuple(n)}compatibleType(t,n,r){return!(t instanceof e)||t.elements.length!==this.elements.length?!1:this.elements.every((e,i)=>e.compatible(t.elements[i],n,r))}or(t){return!(t instanceof e)||t.elements.length!==this.elements.length?this:new e(this.registry,this.elements.map((e,n)=>e.or(t.elements[n])))}narrow(e){return e.elements===void 0?this.options:{elements:e.elements}}get(){let e=this.elements.length===1?this.elements[0]:this.registry.or(this.elements),t=this.registry;return new Ph({key:t.num({whole:!0,min:0,max:this.elements.length-1}),value:e,get:t.nativeExpr(`tuple.at`),set:t.nativeExpr(`tuple.setAt`),loop:t.nativeExpr(`tuple.iterate`)})}follow(e,t){if(`key`in e&&!(`args`in e)){let t=e.key,n=t?.kind===`new`?t.value:void 0;if(typeof n==`number`&&Number.isInteger(n))return this.elements[n]}return super.follow(e,t)}props(){let e=this.registry;e.num();let t=this.elements[0]??e.any(),n=this.elements[this.elements.length-1]??e.any();return{...super.props(),length:e.prop(e.num({whole:!0,min:this.elements.length,max:this.elements.length}),`tuple.length`),first:e.prop(t,`tuple.first`),last:e.prop(n,`tuple.last`),toList:e.method({},e.list(this.elements.length===0?e.any():e.or(this.elements)),`tuple.toList`)}}toJSON(){return{name:e.NAME,options:{elements:this.elements.map(e=>e.toJSON())}}}clone(){return new e(this.registry,this.elements.map(e=>e.clone()))}toCode(e,t){return this.docsPrefix(t)+`tuple<${this.elements.map(e=>e.toCode(void 0,t)).join(`, `)}>`}valueA(e){let t=this.elements.map(t=>t.toA(e));return t.length>0?R.tuple(t):R.array(R.unknown()).max(0)}toNewA(e){let t=this.elements.map(()=>R.ref(`Expr`));return this.describeA(t.length>0?R.tuple(t):R.array(R.ref(`Expr`)).max(0),e)}},Xg=class e extends U{constructor(e,t){super(e,{},{T:t}),this.constraint=t}constraint;static NAME=`typ`;name=e.NAME;static optionKeys=[];static genericKeys=[`T`];static valuesAreTypes=!0;static from(t,n){let r=n.registry,i=t.generic?.T?n.parse(t.generic.T):r.any();return new e(n,i)}valid(e,t){return e instanceof U?e.compatible(this.constraint,void 0,t)||this.constraint.compatible(e,void 0,t):!1}parse(t,n){if(t instanceof W&&t.type instanceof e)return t;if(t instanceof U){if(!this.valid(t,n))throw Error(`typ.parse: Type '${t.name}' is not compatible with ${this.constraint.toCode()}`);return new W(this,t)}if(!t||typeof t!=`object`||Array.isArray(t))throw Error(`typ.parse: expected TypeDef or Type, got ${typeof t}`);if(!(`name`in t)||typeof t.name!=`string`)throw Error(`typ.parse: TypeDef missing 'name' field`);let r;try{r=this.registry.parse(t,n)}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`typ.parse: ${t}`)}if(!this.valid(r,n))throw Error(`typ.parse: Type '${r.name}' is not compatible with ${this.constraint.toCode()}`);let i=n??this.registry,a=r.references().refs.filter(e=>i.lookup(e)===void 0);if(a.length>0)throw Error(`typ.parse: no type named ${a.join(`, `)}`);return new W(this,r)}encode(e,t){return e.toJSON()}create(){return this.constraint}random(e){return this.constraint}compatibleType(t,n,r){return t instanceof e&&this.constraint.compatible(t.constraint,n,r)}or(t){return t instanceof e?new e(this.registry,this.registry.or([this.constraint,t.constraint])):this}narrow(e){return{}}props(){return{...super.props()}}toJSON(){return{name:e.NAME,generic:{T:this.constraint.toJSON()}}}clone(){return new e(this.registry,this.constraint.clone())}toCode(e,t){return this.docsPrefix(t)+`typ<${this.constraint.toCode(void 0,t)}>`}valueA(e){let t=this.registry.compatible(this.constraint);if(t.length===0&&this.constraint.name!==`any`)return R.never();let n;if(this.constraint.name===`any`)n=R.ref(`TypeDef`);else{let e=t.map(e=>um(this.registry,e.name));e.push(dm()),e.push(fm(t.map(e=>e.name))),n=R.union(e).describe(`A gin type definition ({ "name": ..., ... }) whose type fits ${this.constraint.toCode()}.`)}return n.refine(t=>{try{return this.parse(t,e?.scope),!0}catch(e){return e instanceof Error?e.message:String(e)}})}toNewA(e){return this.describeA(this.toA(e),e)}},Zg=class e extends U{static NAME=`void`;name=e.NAME;static optionKeys=[];static genericKeys=[];static from(t,n){return n.registry,new e(n,{})}valid(e){return e===void 0}parse(e){if(e!=null)throw new Fm({path:[],code:`void.invalid`,message:`void expects undefined/null, got ${typeof e}`,severity:`error`});return new W(this,void 0)}encode(e){return null}create(){}random(e){}compatibleType(t,n){return t instanceof e}or(e){return this}narrow(e){if(e&&Object.keys(e).length>0)throw new Fm({path:[],code:`void.no-options`,message:`void has no narrowable options`,severity:`error`});return{}}props(){let e=this.registry;return{...super.props(),toText:e.method({},e.text(),`void.toText`),toBool:e.method({},e.bool(),`void.toBool`)}}toJSON(){return{name:e.NAME}}clone(){return new e(this.registry,{})}toCode(e,t){return this.docsPrefix(t)+`void`}valueA(){return R.null()}};function K(e){return e.get(`this`).raw}function Qg(e){return e.get(`this`)}function q(e,t){let n=e.get(`args`);if(!n)return;let r=n.raw?.[t];return r==null?r:t_(r)?r.raw:r}function $g(e,t){let n=e.get(`args`);if(!n)return;let r=n.raw?.[t];if(t_(r))return r}function e_(e){let t=q(e,`epsilon`);return typeof t==`number`?t:0}function t_(e){return!!e&&typeof e==`object`&&`type`in e&&`raw`in e}function n_(e,t,n,r){let i=e.get(`yield`).raw,a=t.obj({key:{type:n},value:{type:r}});return(e,t)=>i(new W(a,{key:e,value:t}))}var r_={"type.toAny":(e,t)=>G(t.any(),K(e)),"any.typeOf":(e,t)=>G(t.text(),Qg(e).type.name),"any.is":(e,t)=>G(t.bool(),!0),"any.as":(e,t)=>{let n=Qg(e);return G(t.optional(n.type),n.raw)},"any.toText":(e,t)=>G(t.text(),String(K(e))),"any.toBool":(e,t)=>G(t.bool(),!!K(e)),"any.eq":(e,t)=>G(t.bool(),K(e)===q(e,`other`)),"any.neq":(e,t)=>G(t.bool(),K(e)!==q(e,`other`))},i_={"void.toText":(e,t)=>G(t.text(),`void`),"void.toBool":(e,t)=>G(t.bool(),!1)},a_={"null.toText":(e,t)=>G(t.text(),`null`),"null.toBool":(e,t)=>G(t.bool(),!1)},o_={"bool.eq":(e,t)=>G(t.bool(),K(e)===q(e,`other`)),"bool.neq":(e,t)=>G(t.bool(),K(e)!==q(e,`other`)),"bool.and":(e,t)=>G(t.bool(),K(e)&&q(e,`other`)),"bool.or":(e,t)=>G(t.bool(),K(e)||q(e,`other`)),"bool.xor":(e,t)=>G(t.bool(),K(e)!==q(e,`other`)),"bool.not":(e,t)=>G(t.bool(),!K(e)),"bool.toText":(e,t)=>{let n=K(e),r=q(e,`trueText`),i=q(e,`falseText`);return G(t.text(),n?r??`true`:i??`false`)},"bool.toNum":(e,t)=>{let n=K(e),r=q(e,`trueValue`),i=q(e,`falseValue`);return G(t.num(),n?r??1:i??0)}},s_={"num.eq":(e,t)=>G(t.bool(),Math.abs(K(e)-q(e,`other`))<=e_(e)),"num.neq":(e,t)=>G(t.bool(),Math.abs(K(e)-q(e,`other`))>e_(e)),"num.lt":(e,t)=>G(t.bool(),K(e)<q(e,`other`)),"num.lte":(e,t)=>G(t.bool(),K(e)<=q(e,`other`)),"num.gt":(e,t)=>G(t.bool(),K(e)>q(e,`other`)),"num.gte":(e,t)=>G(t.bool(),K(e)>=q(e,`other`)),"num.add":(e,t)=>G(t.num(),K(e)+q(e,`other`)),"num.sub":(e,t)=>G(t.num(),K(e)-q(e,`other`)),"num.mul":(e,t)=>G(t.num(),K(e)*q(e,`other`)),"num.div":(e,t)=>G(t.num(),K(e)/q(e,`other`)),"num.mod":(e,t)=>G(t.num(),K(e)%q(e,`other`)),"num.pow":(e,t)=>G(t.num(),K(e)**q(e,`other`)),"num.abs":(e,t)=>G(t.num(),Math.abs(K(e))),"num.neg":(e,t)=>G(t.num(),-K(e)),"num.sign":(e,t)=>G(t.num(),Math.sign(K(e))),"num.sqrt":(e,t)=>G(t.num(),Math.sqrt(K(e))),"num.min":(e,t)=>G(t.num(),Math.min(K(e),q(e,`other`))),"num.max":(e,t)=>G(t.num(),Math.max(K(e),q(e,`other`))),"num.clamp":(e,t)=>G(t.num(),Math.min(Math.max(K(e),q(e,`min`)),q(e,`max`))),"num.floor":(e,t)=>G(t.num(),Math.floor(K(e))),"num.ceil":(e,t)=>G(t.num(),Math.ceil(K(e))),"num.round":(e,t)=>G(t.num(),Math.round(K(e))),"num.isZero":(e,t)=>G(t.bool(),Math.abs(K(e))<=e_(e)),"num.isPositive":(e,t)=>G(t.bool(),K(e)>e_(e)),"num.isNegative":(e,t)=>G(t.bool(),K(e)<-e_(e)),"num.isInteger":(e,t)=>G(t.bool(),Number.isInteger(K(e))),"num.isEven":(e,t)=>G(t.bool(),K(e)%2==0),"num.isOdd":(e,t)=>G(t.bool(),Math.abs(K(e))%2==1),"num.toText":(e,t)=>{let n=q(e,`precision`),r=n==null?String(K(e)):K(e).toFixed(n);return G(t.text(),r)},"num.toBool":(e,t)=>G(t.bool(),K(e)!==0),"num.loop":async(e,t)=>{let n=K(e),r=t.num(),i=n_(e,t,r,r),a=Math.abs(Math.trunc(n)),o=n<0?-1:1;for(let e=0;e<a;e++){let t=e*o,n=Object.is(t,-0)?0:t;await i(G(r,e),G(r,n))}return G(t.void(),void 0)}},c_={"text.length":(e,t)=>G(t.num({whole:!0,min:0}),K(e).length),"text.eq":(e,t)=>G(t.bool(),K(e)===q(e,`other`)),"text.neq":(e,t)=>G(t.bool(),K(e)!==q(e,`other`)),"text.contains":(e,t)=>G(t.bool(),K(e).includes(q(e,`search`))),"text.startsWith":(e,t)=>G(t.bool(),K(e).startsWith(q(e,`prefix`))),"text.endsWith":(e,t)=>G(t.bool(),K(e).endsWith(q(e,`suffix`))),"text.trim":(e,t)=>G(t.text(),K(e).trim()),"text.trimStart":(e,t)=>G(t.text(),K(e).trimStart()),"text.trimEnd":(e,t)=>G(t.text(),K(e).trimEnd()),"text.upper":(e,t)=>G(t.text(),K(e).toUpperCase()),"text.lower":(e,t)=>G(t.text(),K(e).toLowerCase()),"text.slice":(e,t)=>{let n=q(e,`start`),r=q(e,`end`);return G(t.text(),K(e).slice(n,r))},"text.replace":(e,t)=>{let n=q(e,`search`),r=q(e,`replacement`);return G(t.text(),K(e).split(n).join(r))},"text.split":(e,t)=>{let n=K(e).split(q(e,`separator`));return G(t.list(t.text()),n.map(e=>G(t.text(),e)))},"text.concat":(e,t)=>G(t.text(),K(e)+q(e,`other`)),"text.repeat":(e,t)=>G(t.text(),K(e).repeat(q(e,`count`))),"text.indexOf":(e,t)=>{let n=q(e,`from`);return G(t.num(),K(e).indexOf(q(e,`search`),n))},"text.lastIndexOf":(e,t)=>{let n=q(e,`from`);return G(t.num(),K(e).lastIndexOf(q(e,`search`),n))},"text.match":(e,t)=>{let n=q(e,`pattern`),r=K(e).match(new RegExp(n,`g`))??[];return G(t.list(t.text()),r.map(e=>G(t.text(),e)))},"text.test":(e,t)=>{let n=q(e,`pattern`);return G(t.bool(),new RegExp(n).test(K(e)))},"text.isEmpty":(e,t)=>G(t.bool(),K(e).length===0),"text.isNotEmpty":(e,t)=>G(t.bool(),K(e).length>0),"text.toNum":(e,t)=>G(t.num(),Number(K(e))),"text.toBool":(e,t)=>G(t.bool(),K(e).length>0),"text.charAt":(e,t)=>{let n=e.get(`key`).raw,r=K(e)[n];if(r===void 0)throw Error(`text[${n}]: index out of range`);return G(t.text({minLength:1,maxLength:1}),r)},"text.chars":async(e,t)=>{let n=K(e),r=t.num({whole:!0,min:0}),i=t.text({minLength:1,maxLength:1}),a=n_(e,t,r,i);for(let e=0;e<n.length;e++)await a(G(r,e),G(i,n[e]));return G(t.void(),void 0)}},l_=e=>Qg(e).type.item,u_={"list.length":(e,t)=>G(t.num({whole:!0,min:0}),K(e).length),"list.indexGet":e=>{let t=e.get(`key`).raw,n=K(e);if(t<0||t>=n.length)throw Error(`list[${t}]: index out of range`);return n[t]},"list.indexSet":(e,t)=>{let n=e.get(`key`).raw,r=e.get(`value`),i=K(e);if(n<0||n>=i.length)throw Error(`list[${n}] =: index out of range`);return i[n]=r,G(t.void(),void 0)},"list.iterate":async(e,t)=>{let n=K(e),r=t.num({whole:!0,min:0}),i=n_(e,t,r,l_(e)),a=G(t.void(),void 0);for(let e=0;e<n.length;e++)await i(G(r,e),n[e]);return a},"list.at":(e,t)=>{let n=q(e,`index`),r=K(e);return n<0||n>=r.length?G(t.optional(l_(e)),void 0):G(t.optional(l_(e)),r[n].raw)},"list.push":(e,t)=>(K(e).push($g(e,`value`)),G(t.void(),void 0)),"list.pop":(e,t)=>{let n=K(e).pop();return G(t.optional(l_(e)),n?n.raw:void 0)},"list.shift":(e,t)=>{let n=K(e).shift();return G(t.optional(l_(e)),n?n.raw:void 0)},"list.unshift":(e,t)=>(K(e).unshift($g(e,`value`)),G(t.void(),void 0)),"list.insert":(e,t)=>(K(e).splice(q(e,`index`),0,$g(e,`value`)),G(t.void(),void 0)),"list.remove":e=>K(e).splice(q(e,`index`),1)[0],"list.clear":(e,t)=>(K(e).length=0,G(t.void(),void 0)),"list.slice":e=>{let t=Qg(e).type,n=q(e,`start`),r=q(e,`end`);return G(t,K(e).slice(n,r))},"list.concat":e=>{let t=Qg(e).type,n=q(e,`other`);return G(t,K(e).concat(n))},"list.reverse":e=>{let t=Qg(e).type;return G(t,[...K(e)].reverse())},"list.join":(e,t)=>{let n=q(e,`separator`)??`,`;return G(t.text(),K(e).map(e=>String(e.raw)).join(n))},"list.indexOf":(e,t)=>{let n=$g(e,`value`).raw,r=K(e).findIndex(e=>e.raw===n);return G(t.num(),r)},"list.contains":(e,t)=>{let n=$g(e,`value`).raw,r=K(e);return G(t.bool(),r.some(e=>e.raw===n))},"list.unique":e=>{let t=Qg(e).type,n=new Set,r=[];for(let t of K(e))n.has(t.raw)||(n.add(t.raw),r.push(t));return G(t,r)},"list.duplicates":e=>{let t=Qg(e).type,n=new Set,r=new Set,i=[];for(let t of K(e))n.has(t.raw)?r.has(t.raw)||(r.add(t.raw),i.push(t)):n.add(t.raw);return G(t,i)},"list.map":async(e,t)=>{let n=K(e),r=$g(e,`fn`).raw,i=l_(e),a=[],o=t.obj({value:{type:i},index:{type:t.num()}});for(let e=0;e<n.length;e++){let i=new W(o,{value:n[e],index:G(t.num(),e)});a.push(await r(i))}return G(t.list(t.any()),a)},"list.filter":async e=>{let t=Qg(e).type,n=K(e),r=$g(e,`fn`).raw,i=[],a=t.registry.obj({value:{type:t.item},index:{type:t.registry.num()}});for(let e=0;e<n.length;e++)(await r(new W(a,{value:n[e],index:G(t.registry.num(),e)}))).raw&&i.push(n[e]);return G(t,i)},"list.find":async(e,t)=>{let n=K(e),r=$g(e,`fn`).raw,i=l_(e),a=t.obj({value:{type:i},index:{type:t.num()}});for(let e=0;e<n.length;e++)if((await r(new W(a,{value:n[e],index:G(t.num(),e)}))).raw)return G(t.optional(i),n[e].raw);return G(t.optional(i),void 0)},"list.reduce":async(e,t)=>{let n=K(e),r=$g(e,`fn`),i=$g(e,`initial`),a=r.raw,o=l_(e),s=i,c=t.obj({acc:{type:t.any()},value:{type:o},index:{type:t.num()}});for(let e=0;e<n.length;e++)s=await a(new W(c,{acc:s,value:n[e],index:G(t.num(),e)}));return s},"list.some":async(e,t)=>{let n=K(e),r=$g(e,`fn`).raw,i=l_(e),a=t.obj({value:{type:i},index:{type:t.num()}});for(let e=0;e<n.length;e++)if((await r(new W(a,{value:n[e],index:G(t.num(),e)}))).raw)return G(t.bool(),!0);return G(t.bool(),!1)},"list.every":async(e,t)=>{let n=K(e),r=$g(e,`fn`).raw,i=l_(e),a=t.obj({value:{type:i},index:{type:t.num()}});for(let e=0;e<n.length;e++)if(!(await r(new W(a,{value:n[e],index:G(t.num(),e)}))).raw)return G(t.bool(),!1);return G(t.bool(),!0)},"list.sort":async e=>{let t=Qg(e).type,n=[...K(e)],r=$g(e,`fn`);if(r&&typeof r.raw==`function`){let e=r.raw,i=t.registry.obj({a:{type:t.item},b:{type:t.item}}),a=[];for(let t=0;t<n.length;t++){let r=0;for(let a=0;a<n.length;a++)t!==a&&(await e(new W(i,{a:n[t],b:n[a]}))).raw>0&&r++;a.push({index:t,key:r})}return a.sort((e,t)=>e.key-t.key),G(t,a.map(e=>n[e.index]))}return G(t,n.sort((e,t)=>{let n=e.raw,r=t.raw;return n<r?-1:+(n>r)}))},"list.isEmpty":(e,t)=>G(t.bool(),K(e).length===0),"list.isNotEmpty":(e,t)=>G(t.bool(),K(e).length>0),"list.first":(e,t)=>{let n=K(e);return G(t.optional(l_(e)),n.length>0?n[0].raw:void 0)},"list.last":(e,t)=>{let n=K(e);return G(t.optional(l_(e)),n.length>0?n[n.length-1].raw:void 0)}},d_={"list.indexSet":B.STATE,"list.push":B.STATE,"list.pop":B.STATE,"list.shift":B.STATE,"list.unshift":B.STATE,"list.insert":B.STATE,"list.remove":B.STATE,"list.clear":B.STATE},f_=e=>Qg(e).type.value,p_={"map.size":(e,t)=>G(t.num({whole:!0,min:0}),K(e).size),"map.indexGet":e=>{let t=e.get(`key`).raw,n=K(e).get(t);if(!n)throw Error(`map[${String(t)}]: key not found`);return n[1]},"map.indexSet":(e,t)=>{let n=e.get(`key`),r=e.get(`value`);return K(e).set(n.raw,[n,r]),G(t.void(),void 0)},"map.iterate":async(e,t)=>{let n=K(e),r=n.values().next().value,i=n_(e,t,r?r[0].type:t.any(),r?r[1].type:t.any());for(let[,[e,t]]of n)await i(e,t);return G(t.void(),void 0)},"map.at":(e,t)=>{let n=q(e,`key`),r=K(e).get(n);return G(t.optional(f_(e)),r?r[1].raw:void 0)},"map.has":(e,t)=>G(t.bool(),K(e).has(q(e,`key`))),"map.delete":(e,t)=>G(t.bool(),K(e).delete(q(e,`key`))),"map.clear":(e,t)=>(K(e).clear(),G(t.void(),void 0)),"map.keys":(e,t)=>{let n=K(e),r=Qg(e).type.key,i=[];for(let[,[e]]of n)i.push(e);return G(t.list(r),i)},"map.values":(e,t)=>{let n=K(e),r=Qg(e).type.value,i=[];for(let[,[,e]]of n)i.push(e);return G(t.list(r),i)},"map.isEmpty":(e,t)=>G(t.bool(),K(e).size===0),"map.isNotEmpty":(e,t)=>G(t.bool(),K(e).size>0)},m_={"map.indexSet":B.STATE,"map.delete":B.STATE,"map.clear":B.STATE},h_=e=>Qg(e).type.elements,g_={"tuple.at":e=>{let t=e.get(`key`).raw,n=K(e)[t];return n instanceof W?n:G(h_(e)[t]??G.prototype,n)},"tuple.setAt":(e,t)=>{let n=e.get(`key`).raw,r=e.get(`value`);return K(e)[n]=r,G(t.void(),void 0)},"tuple.iterate":async(e,t)=>{let n=K(e),r=t.num({whole:!0,min:0}),i=n.map(e=>e.type),a=n_(e,t,r,i.length===0?t.any():i.length===1?i[0]:t.or(i));for(let e=0;e<n.length;e++)await a(G(r,e),n[e]);return G(t.void(),void 0)},"tuple.length":(e,t)=>G(t.num({whole:!0}),K(e).length),"tuple.first":e=>{let t=K(e),n=h_(e),r=t[0];return r instanceof W?r:G(n[0],r)},"tuple.last":e=>{let t=K(e),n=h_(e),r=t[t.length-1];return r instanceof W?r:G(n[n.length-1],r)},"tuple.toList":(e,t)=>G(t.list(t.any()),[...K(e)])},__={"tuple.setAt":B.STATE},v_=e=>Qg(e).type.fields,y_={"object.indexGet":e=>{let t=e.get(`key`).raw,n=v_(e)[t];if(!n)throw Error(`object[${t}]: no such field`);let r=K(e)[t];return r instanceof W?r:G(n.type,r)},"object.indexSet":(e,t)=>{let n=e.get(`key`).raw,r=e.get(`value`);return K(e)[n]=r,G(t.void(),void 0)},"object.iterate":async(e,t)=>{let n=K(e),r=v_(e),i=t.text(),a=Object.values(r).map(e=>e.type),o=n_(e,t,i,a.length===0?t.any():a.length===1?a[0]:t.or(a));for(let[e]of Object.entries(r)){let t=n[e];t instanceof W&&await o(G(i,e),t)}return G(t.void(),void 0)},"object.keys":(e,t)=>{let n=Object.keys(v_(e));return G(t.list(t.text()),n.map(e=>G(t.text(),e)))},"object.values":(e,t)=>{let n=K(e),r=Object.keys(v_(e)).map(e=>n[e]??G(t.any(),void 0));return G(t.list(t.any()),r)},"object.entries":(e,t)=>{let n=K(e),r=Object.keys(v_(e)).map(e=>G(t.any(),[e,n[e]?.raw]));return G(t.list(t.any()),r)},"object.has":(e,t)=>G(t.bool(),Object.hasOwn(v_(e),q(e,`key`))),"object.eq":(e,t)=>G(t.bool(),x_(Qg(e),e.get(`args`).raw)),"object.neq":(e,t)=>G(t.bool(),!x_(Qg(e),e.get(`args`).raw)),"object.toText":(e,t)=>{let n=K(e),r=v_(e),i={};for(let[e]of Object.entries(r)){let t=n[e];i[e]=t?t.type.encode(t.raw):void 0}return G(t.text(),JSON.stringify(i))}},b_={"object.indexSet":B.STATE};function x_(e,t){let n=t.other,r=n instanceof W?n.raw:n;return S_(e.raw,r)}function S_(e,t){if(e instanceof W&&(e=e.raw),t instanceof W&&(t=t.raw),e===t)return!0;if(typeof e!=`object`||typeof t!=`object`||e===null||t===null||Array.isArray(e)!==Array.isArray(t))return!1;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!S_(e[n],t[n]))return!1;return!0}let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let r of n)if(!S_(e[r],t[r]))return!1;return!0}var C_={"optional.value":e=>{let t=K(e);if(t===void 0)throw Error(`optional.value: value is undefined`);return G(Qg(e).type.inner,t)},"optional.has":(e,t)=>G(t.bool(),K(e)!==void 0),"optional.or":e=>{let t=K(e),n=Qg(e).type.inner;return t===void 0?$g(e,`fallback`)??G(n,q(e,`fallback`)):G(n,t)},"optional.map":async(e,t)=>{let n=K(e),r=Qg(e).type.inner;if(n===void 0)return G(t.optional(t.any()),void 0);let i=$g(e,`fn`).raw,a=await i(new W(t.obj({value:{type:r}}),{value:G(r,n)}));return G(t.optional(t.any()),a.raw)}},w_={"nullable.value":e=>{let t=K(e);if(t===null)throw Error(`nullable.value: value is null`);return G(Qg(e).type.inner,t)},"nullable.isNull":(e,t)=>G(t.bool(),K(e)===null),"nullable.or":e=>{let t=K(e),n=Qg(e).type.inner;return t===null?$g(e,`fallback`)??G(n,q(e,`fallback`)):G(n,t)},"nullable.map":async(e,t)=>{let n=K(e),r=Qg(e).type.inner;if(n===null)return G(t.nullable(t.any()),null);let i=$g(e,`fn`).raw,a=await i(new W(t.obj({value:{type:r}}),{value:G(r,n)}));return G(t.nullable(t.any()),a.raw)}},T_={"not.typeOf":(e,t)=>G(t.text(),Qg(e).type.name),"not.toText":(e,t)=>G(t.text(),String(K(e)))},E_={"enum.name":(e,t)=>{let n=K(e),r=Qg(e).type,i=Object.entries(r.options.values).find(([,e])=>e===n);return G(t.text(),i?i[0]:``)},"enum.value":e=>{let t=Qg(e).type;return G(t.value,K(e))},"enum.eq":(e,t)=>G(t.bool(),K(e)===q(e,`other`)),"enum.neq":(e,t)=>G(t.bool(),K(e)!==q(e,`other`)),"enum.toText":(e,t)=>G(t.text(),String(K(e)))},D_={"date.year":(e,t)=>G(t.num({whole:!0}),K(e).getUTCFullYear()),"date.month":(e,t)=>G(t.num({whole:!0,min:1,max:12}),K(e).getUTCMonth()+1),"date.day":(e,t)=>G(t.num({whole:!0,min:1,max:31}),K(e).getUTCDate()),"date.dayOfWeek":(e,t)=>G(t.num({whole:!0,min:0,max:6}),K(e).getUTCDay()),"date.dayOfYear":(e,t)=>{let n=K(e),r=Date.UTC(n.getUTCFullYear(),0,0);return G(t.num({whole:!0,min:1,max:366}),Math.floor((n.getTime()-r)/864e5))},"date.eq":(e,t)=>G(t.bool(),K(e).getTime()===q(e,`other`).getTime()),"date.neq":(e,t)=>G(t.bool(),K(e).getTime()!==q(e,`other`).getTime()),"date.before":(e,t)=>G(t.bool(),K(e)<q(e,`other`)),"date.after":(e,t)=>G(t.bool(),K(e)>q(e,`other`)),"date.addDays":(e,t)=>{let n=new Date(K(e));return n.setUTCDate(n.getUTCDate()+q(e,`days`)),G(t.date(),n)},"date.addMonths":(e,t)=>{let n=new Date(K(e));return n.setUTCMonth(n.getUTCMonth()+q(e,`months`)),G(t.date(),n)},"date.addYears":(e,t)=>{let n=new Date(K(e));return n.setUTCFullYear(n.getUTCFullYear()+q(e,`years`)),G(t.date(),n)},"date.diffDays":(e,t)=>G(t.num({whole:!0}),Math.round((K(e).getTime()-q(e,`other`).getTime())/864e5)),"date.diffMonths":(e,t)=>{let n=K(e),r=q(e,`other`);return G(t.num({whole:!0}),(n.getUTCFullYear()-r.getUTCFullYear())*12+(n.getUTCMonth()-r.getUTCMonth()))},"date.diffYears":(e,t)=>G(t.num({whole:!0}),K(e).getUTCFullYear()-q(e,`other`).getUTCFullYear()),"date.toText":(e,t)=>G(t.text(),K(e).toISOString().slice(0,10))},O_={"timestamp.year":(e,t)=>G(t.num({whole:!0}),K(e).getUTCFullYear()),"timestamp.month":(e,t)=>G(t.num({whole:!0}),K(e).getUTCMonth()+1),"timestamp.day":(e,t)=>G(t.num({whole:!0}),K(e).getUTCDate()),"timestamp.hour":(e,t)=>G(t.num({whole:!0,min:0,max:23}),K(e).getUTCHours()),"timestamp.minute":(e,t)=>G(t.num({whole:!0,min:0,max:59}),K(e).getUTCMinutes()),"timestamp.second":(e,t)=>G(t.num({whole:!0,min:0,max:59}),K(e).getUTCSeconds()),"timestamp.millisecond":(e,t)=>G(t.num({whole:!0,min:0,max:999}),K(e).getUTCMilliseconds()),"timestamp.eq":(e,t)=>G(t.bool(),K(e).getTime()===q(e,`other`).getTime()),"timestamp.before":(e,t)=>G(t.bool(),K(e)<q(e,`other`)),"timestamp.after":(e,t)=>G(t.bool(),K(e)>q(e,`other`)),"timestamp.addDuration":(e,t)=>G(t.timestamp(),new Date(K(e).getTime()+q(e,`duration`))),"timestamp.subDuration":(e,t)=>G(t.timestamp(),new Date(K(e).getTime()-q(e,`duration`))),"timestamp.diff":(e,t)=>G(t.duration(),K(e).getTime()-q(e,`other`).getTime()),"timestamp.toDate":(e,t)=>G(t.date(),new Date(K(e).toISOString().slice(0,10))),"timestamp.toEpoch":(e,t)=>G(t.num(),K(e).getTime()),"timestamp.toText":(e,t)=>G(t.text(),K(e).toISOString())},k_=864e5,A_=36e5,j_=6e4,M_=1e3,N_={"duration.init":(e,t)=>{let n=q(e,`days`)??0,r=q(e,`hours`)??0,i=q(e,`minutes`)??0,a=q(e,`seconds`)??0,o=q(e,`ms`)??0;return G(t.duration(),n*k_+r*A_+i*j_+a*M_+o)},"duration.totalSeconds":(e,t)=>G(t.num(),K(e)/1e3),"duration.totalMinutes":(e,t)=>G(t.num(),K(e)/6e4),"duration.totalHours":(e,t)=>G(t.num(),K(e)/36e5),"duration.totalDays":(e,t)=>G(t.num(),K(e)/864e5),"duration.days":(e,t)=>G(t.num({whole:!0}),Math.trunc(K(e)/k_)),"duration.hours":(e,t)=>G(t.num({whole:!0}),Math.trunc(K(e)/A_)%24),"duration.minutes":(e,t)=>G(t.num({whole:!0}),Math.trunc(K(e)/j_)%60),"duration.seconds":(e,t)=>G(t.num({whole:!0}),Math.trunc(K(e)/M_)%60),"duration.ms":(e,t)=>G(t.num({whole:!0}),K(e)%M_),"duration.toText":(e,t)=>{let n=K(e),r=Math.trunc(n/k_),i=Math.trunc(n%k_/A_),a=Math.trunc(n%A_/j_),o=Math.trunc(n%j_/M_),s=[];return r&&s.push(`${r}d`),i&&s.push(`${i}h`),a&&s.push(`${a}m`),(o||s.length===0)&&s.push(`${o}s`),G(t.text(),s.join(` `))}},P_=e=>e>>>24&255,F_=e=>e>>>16&255,I_=e=>e>>>8&255,L_=e=>(e&255)/255,R_=(e,t,n,r)=>(Math.round(e)&255)<<24|(Math.round(t)&255)<<16|(Math.round(n)&255)<<8|Math.round(r*255)&255,z_={"color.init":(e,t)=>{let n=q(e,`r`),r=q(e,`g`),i=q(e,`b`),a=q(e,`a`)??1;return G(t.color(),R_(n,r,i,a)>>>0)},"color.r":(e,t)=>G(t.num(),P_(K(e))),"color.g":(e,t)=>G(t.num(),F_(K(e))),"color.b":(e,t)=>G(t.num(),I_(K(e))),"color.a":(e,t)=>G(t.num(),L_(K(e))),"color.hue":(e,t)=>G(t.num(),B_(K(e)).h),"color.saturation":(e,t)=>G(t.num(),B_(K(e)).s),"color.lightness":(e,t)=>G(t.num(),B_(K(e)).l),"color.eq":(e,t)=>G(t.bool(),K(e)===q(e,`other`)),"color.neq":(e,t)=>G(t.bool(),K(e)!==q(e,`other`)),"color.lighten":(e,t)=>G(t.color(),H_(K(e),q(e,`amount`))),"color.darken":(e,t)=>G(t.color(),H_(K(e),-q(e,`amount`))),"color.saturate":(e,t)=>G(t.color(),U_(K(e),q(e,`amount`))),"color.desaturate":(e,t)=>G(t.color(),U_(K(e),-q(e,`amount`))),"color.opacity":(e,t)=>G(t.color(),K(e)&4294967040|Math.round(q(e,`alpha`)*255)&255),"color.invert":(e,t)=>{let n=K(e);return G(t.color(),R_(255-P_(n),255-F_(n),255-I_(n),L_(n))>>>0)},"color.mix":(e,t)=>{let n=K(e),r=q(e,`other`),i=q(e,`weight`)??.5;return G(t.color(),R_(P_(n)*(1-i)+P_(r)*i,F_(n)*(1-i)+F_(r)*i,I_(n)*(1-i)+I_(r)*i,L_(n)*(1-i)+L_(r)*i)>>>0)},"color.complement":(e,t)=>G(t.color(),W_(K(e),180)),"color.toHex":(e,t)=>G(t.text(),`#`+K(e).toString(16).padStart(8,`0`)),"color.toRgb":(e,t)=>{let n=K(e);return G(t.text(),`rgb(${P_(n)},${F_(n)},${I_(n)})`)},"color.toHsl":(e,t)=>{let{h:n,s:r,l:i}=B_(K(e));return G(t.text(),`hsl(${Math.round(n)},${Math.round(r*100)}%,${Math.round(i*100)}%)`)},"color.toText":(e,t)=>G(t.text(),`#`+K(e).toString(16).padStart(8,`0`))};function B_(e){let t=P_(e)/255,n=F_(e)/255,r=I_(e)/255,i=Math.max(t,n,r),a=Math.min(t,n,r),o=(i+a)/2,s=0,c=0;if(i!==a){let e=i-a;switch(c=o>.5?e/(2-i-a):e/(i+a),i){case t:s=(n-r)/e+(n<r?6:0);break;case n:s=(r-t)/e+2;break;case r:s=(t-n)/e+4}s*=60}return{h:s,s:c,l:o}}function V_(e,t,n,r){let i=(1-Math.abs(2*n-1))*t,a=i*(1-Math.abs(e/60%2-1)),o=n-i/2,s=0,c=0,l=0;return e<60?[s,c,l]=[i,a,0]:e<120?[s,c,l]=[a,i,0]:e<180?[s,c,l]=[0,i,a]:e<240?[s,c,l]=[0,a,i]:e<300?[s,c,l]=[a,0,i]:[s,c,l]=[i,0,a],R_((s+o)*255,(c+o)*255,(l+o)*255,r)}function H_(e,t){let{h:n,s:r,l:i}=B_(e);return V_(n,r,Math.max(0,Math.min(1,i+t)),L_(e))>>>0}function U_(e,t){let{h:n,s:r,l:i}=B_(e);return V_(n,Math.max(0,Math.min(1,r+t)),i,L_(e))>>>0}function W_(e,t){let{h:n,s:r,l:i}=B_(e);return V_((n+t+360)%360,r,i,L_(e))>>>0}function G_(e){let t=[{impls:r_},{impls:i_},{impls:a_},{impls:o_},{impls:s_},{impls:c_},{impls:u_,effects:d_},{impls:p_,effects:m_},{impls:g_,effects:__},{impls:y_,effects:b_},{impls:C_},{impls:w_},{impls:T_},{impls:E_},{impls:D_},{impls:O_},{impls:N_},{impls:z_}];for(let n of t)for(let[t,r]of Object.entries(n.impls)){let i=n.effects?.[t]??B.NONE;e.setNative(t,r,i)}return e}var K_=class e extends th{constructor(e,t){super(),this.type=e,this.value=t}type;value;static KIND=`new`;kind=e.KIND;static from(t,n){return new e(n.registry.parse(t.type,n),t.value).withComment(t.comment)}async evaluate(e,t){let n=this.type,r=n.init();if(this.value!==void 0){if(r){let i=r.args.parse(this.value),a=G(n,n.create()),o=t.child({this:a,args:i}),s=await r.run.evaluate(e,o);return s===void 0||s.raw===void 0?a:new W(n,s.raw)}let i=await n.newFill(this.value,e,t);if(i instanceof W)return e.registry.parseValue(i,n);let a=n.parse(i);return a.type===n?a:new W(n,a.raw)}return G(n,n.create())}typeOf(e,t){return this.type}validateWalk(e,t,n,r){return this.value===void 0&&X_(this.type)&&n.warn(`new.value.missing`,`\`new ${this.type.name}\` has no \`value\` \u2014 every field will fall to its type default (0 / "" / null). Provide a \`value\` matching the type's shape.`),this.value!==void 0&&n.at([`value`],()=>this.type.validateNewValue(this.value,e,t,n,r)),this.type}toCode(e,t={}){let n=this.type.toCode(void 0,t),r;return r=this.value===void 0?this.type.isOptional()?`undefined`:`new ${n}()`:typeof this.value==`number`||typeof this.value==`boolean`?String(this.value):typeof this.value==`string`?JSON.stringify(this.value):this.value===null?`null`:q_(this.value,e,this.type,t),this.commentPrefix(t)+r}toJSON(){return this.withCommentOn({kind:`new`,type:this.type.toJSON(),value:this.value})}toJSONCode(e=[],t=2,n=0){let r=this.type.toJSONCode([...e,`type`],t,n+1),i=this.value===void 0?void 0:(()=>{let e=JSON.stringify(this.value,null,t),r=n+1;return r>0?e.replace(/\n/g,`
|
|
105
|
-
`+` `.repeat(r*t)):e})(),a=i===void 0?void 0:
|
|
106
|
-
`),`[${a}]`}if(e&&typeof e==`object`){let a=n?.fields,o=Object.entries(e);if(o.length===0)return`new ${i}()`;let s=
|
|
107
|
-
`)?`new ${i} {${s}}`:`new ${i} { ${s} }`}return JSON.stringify(e)}function
|
|
108
|
-
`)?H`({\n ${
|
|
109
|
-
`)}\n})`:H`({ ${
|
|
110
|
-
`+` `.repeat(r*n))}),e.catch_&&a.push({key:`catch`,value:e.catch_.toJSONCode([...t,`catch`],n,r+1)}),V.jsonObject(a,{path:t},r,n)}return e instanceof
|
|
111
|
-
`,1)[0].length<=80?c:H`let ${r.name}${o} =\n ${s.indent(` `)};`});if(r){let r=this.body.toGinCode(e,i,[...n,`body`]),a=o.map(e=>H` ${e}`),s=H` return ${r.indent(` `)};`,c=
|
|
112
|
-
`)}function
|
|
113
|
-
`} ${a} (${s}) return ${c.indent(` `)};`}let r=``;return this.otherwise&&(r=H`\n return ${this.otherwise.toGinCode(e,o,[...n,`else`]).indent(` `)};`),
|
|
114
|
-
break;`}`})),u=``;return this.otherwise&&(u=H`\n default:\n ${c(this.otherwise,[...n,`else`]).indent(` `)}`),
|
|
115
|
-
${
|
|
116
|
-
}`,d=this.commentPrefix(t);return n?d+`(() => { ${u}; return undefined; })()`:d+u}toJSON(){let e={kind:`loop`,over:this.over.toJSON(),body:this.body.toJSON()};return this.keyName!==void 0&&(e.key=this.keyName),this.valueName!==void 0&&(e.value=this.valueName),this.parallel&&(e.parallel={concurrent:this.parallel.concurrent?.toJSON(),rate:this.parallel.rate?.toJSON()}),this.withCommentOn(e)}toJSONCode(e=[],t=2,n=0){let r=this.over.toJSONCode([...e,`over`],t,n+1),i=this.body.toJSONCode([...e,`body`],t,n+1),a=this.parallel?V.jsonObject([{key:`concurrent`,value:this.parallel.concurrent?.toJSONCode([...e,`parallel`,`concurrent`],t,n+2)},{key:`rate`,value:this.parallel.rate?.toJSONCode([...e,`parallel`,`rate`],t,n+2)}],{path:[...e,`parallel`]},n+1,t):void 0;return V.jsonObject([{key:`kind`,value:V.jsonString(`loop`)},{key:`over`,value:r},{key:`body`,value:i},{key:`key`,value:this.keyName===void 0?void 0:V.jsonString(this.keyName)},{key:`value`,value:this.valueName===void 0?void 0:V.jsonString(this.valueName)},{key:`parallel`,value:a},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}clone(){return new e(this.over.clone(),this.body.clone(),this.keyName,this.valueName,this.parallel?{concurrent:this.parallel.concurrent?.clone(),rate:this.parallel.rate?.clone()}:void 0).withComment(this.comment)}forEachChild(e){e(this.over,`inherit`),e(this.body,`loop`),this.parallel?.concurrent&&e(this.parallel.concurrent,`inherit`),this.parallel?.rate&&e(this.parallel.rate,`inherit`)}effects(){return this.over.effects()|this.body.effects()|(this.parallel?.concurrent?.effects()??B.NONE)|(this.parallel?.rate?.effects()??B.NONE)}complexity(){return 6+this.over.complexity()+this.body.complexity()+(this.parallel?.concurrent?.complexity()??0)+(this.parallel?.rate?.complexity()??0)}};async function
|
|
117
|
-
`)?H`${o} => {\n ${s.indent(` `)}\n}`:H`${o} => ${s}`,
|
|
118
|
-
`)?new V(e.text.replace(/\n\s*/g,` `),e.spans):e}function
|
|
102
|
+
`}function fg(e){return e?.indent??` `}function pg(e,t){return t+e.replace(/\n/g,`
|
|
103
|
+
${t}`)}function mg(e,t,n){let r=e.registry,i={inLoop:!1,inLambda:!1},a=e.props();for(let[o,s]of Object.entries(a)){let a=s instanceof ng?s:ng.from(s);n.at([`props`,o],()=>{vg(a.get,hg(a,e,r),_g(a),`get`,t,n,i),vg(a.set,gg(a,e,r),r.void(),`set`,t,n,i),vg(a.default,new Map,a.type,`default`,t,n,i)})}let o=e.get();o&&n.at(`get`,()=>{let a=new Map([[`this`,e],[`key`,o.key]]),s=new Map([[`this`,e],[`key`,o.key],[`value`,o.value]]);vg(o.get,a,o.value,`get`,t,n,i),vg(o.set,s,r.void(),`set`,t,n,i),vg(o.loop,a,void 0,`loop`,t,n,i)});let s=e.call();s&&n.at(`call`,()=>{let a=new Map([[`this`,e],[`args`,s.args],[`recurse`,r.fn({args:s.args,returns:s.returns??r.any()})]]);vg(s.get,a,s.returns,`get`,t,n,{...i,inLambda:!0});let o=new Map([[`this`,e],[`args`,s.args],[`value`,s.returns??r.any()],[`recurse`,r.fn({args:s.args,returns:s.returns??r.any()})]]);vg(s.set,o,r.void(),`set`,t,n,{...i,inLambda:!0})});let c=e.init();c&&n.at(`init`,()=>{let r=new Map([[`this`,e],[`args`,c.args]]);vg(c.run,r,void 0,`run`,t,n,i)});for(let a of e.constraints())n.at(`constraint`,()=>{let o=jh(t,a,new Map([[`this`,e]]),n,i),s=r.bool();o.name!==`any`&&!s.compatible(o)&&n.warn(`type.surface.return-type`,`constraint must return bool, got '${o.name}'`)})}function hg(e,t,n){let r=new Map([[`this`,t]]),i=e.type.call?.();return i&&(r.set(`args`,i.args),r.set(`recurse`,n.fn({args:i.args,returns:i.returns??n.any()}))),r}function gg(e,t,n){return new Map([[`this`,t],[`value`,e.type]])}function _g(e){let t=e.type.call?.();return t?t.returns:e.type}function vg(e,t,n,r,i,a,o){e&&a.at(r,()=>{let s=jh(i,e,t,a,o);n&&s.name!==`any`&&!n.compatible(s)&&a.warn(`type.surface.return-type`,`${r} body returns '${s.name}', not compatible with declared '${n.name}'`)})}function yg(e,t,n,r,i,a){let o=i+1,s=[];return e.name!==void 0&&s.push({key:`name`,value:V.jsonString(e.name)}),e.extends!==void 0&&s.push({key:`extends`,value:V.jsonString(e.extends)}),e.satisfies!==void 0&&e.satisfies.length>0&&s.push({key:`satisfies`,value:Dg(e.satisfies,[...n,`satisfies`],r,o)}),e.docs!==void 0&&s.push({key:`docs`,value:V.jsonString(e.docs)}),e.options!==void 0&&Object.keys(e.options).length>0&&s.push({key:`options`,value:Dg(e.options,[...n,`options`],r,o)}),e.generic!==void 0&&Object.keys(e.generic).length>0&&s.push({key:`generic`,value:bg(e.generic,t,[...n,`generic`],r,o)}),e.props!==void 0&&Object.keys(e.props).length>0&&s.push({key:`props`,value:xg(e.props,t,[...n,`props`],r,o)}),e.get!==void 0&&s.push({key:`get`,value:Cg(e.get,t,[...n,`get`],r,o)}),e.call!==void 0&&s.push({key:`call`,value:wg(e.call,t,[...n,`call`],r,o)}),e.init!==void 0&&s.push({key:`init`,value:Tg(e.init,t,[...n,`init`],r,o)}),e.constraint!==void 0&&s.push({key:`constraint`,value:Eg(e.constraint,t,[...n,`constraint`],r,o)}),V.jsonObject(s,{path:n,type:a},i,r)}function bg(e,t,n,r,i){let a=Object.entries(e).map(([e,a])=>({key:e,value:yg(a,t,[...n,e],r,i+1,void 0)}));return V.jsonObject(a,{path:n},i,r)}function xg(e,t,n,r,i){let a=Object.entries(e).map(([e,a])=>({key:e,value:Sg(a,t,[...n,e],r,i+1)}));return V.jsonObject(a,{path:n},i,r)}function Sg(e,t,n,r,i){let a=i+1,o=[];return e.docs!==void 0&&o.push({key:`docs`,value:V.jsonString(e.docs)}),o.push({key:`type`,value:yg(e.type,t,[...n,`type`],r,a,void 0)}),e.get!==void 0&&o.push({key:`get`,value:Eg(e.get,t,[...n,`get`],r,a)}),e.set!==void 0&&o.push({key:`set`,value:Eg(e.set,t,[...n,`set`],r,a)}),e.default!==void 0&&o.push({key:`default`,value:Eg(e.default,t,[...n,`default`],r,a)}),V.jsonObject(o,{path:n},i,r)}function Cg(e,t,n,r,i){let a=i+1,o=[];return e.docs!==void 0&&o.push({key:`docs`,value:V.jsonString(e.docs)}),o.push({key:`key`,value:yg(e.key,t,[...n,`key`],r,a,void 0)}),o.push({key:`value`,value:yg(e.value,t,[...n,`value`],r,a,void 0)}),e.get!==void 0&&o.push({key:`get`,value:Eg(e.get,t,[...n,`get`],r,a)}),e.set!==void 0&&o.push({key:`set`,value:Eg(e.set,t,[...n,`set`],r,a)}),e.loop!==void 0&&o.push({key:`loop`,value:Eg(e.loop,t,[...n,`loop`],r,a)}),e.loopDynamic!==void 0&&o.push({key:`loopDynamic`,value:String(e.loopDynamic)}),V.jsonObject(o,{path:n},i,r)}function wg(e,t,n,r,i){let a=i+1,o=[];return e.docs!==void 0&&o.push({key:`docs`,value:V.jsonString(e.docs)}),e.types!==void 0&&Object.keys(e.types).length>0&&o.push({key:`types`,value:bg(e.types,t,[...n,`types`],r,a)}),o.push({key:`args`,value:yg(e.args,t,[...n,`args`],r,a,void 0)}),e.returns!==void 0&&o.push({key:`returns`,value:yg(e.returns,t,[...n,`returns`],r,a,void 0)}),e.throws!==void 0&&o.push({key:`throws`,value:yg(e.throws,t,[...n,`throws`],r,a,void 0)}),e.get!==void 0&&o.push({key:`get`,value:Eg(e.get,t,[...n,`get`],r,a)}),e.set!==void 0&&o.push({key:`set`,value:Eg(e.set,t,[...n,`set`],r,a)}),V.jsonObject(o,{path:n},i,r)}function Tg(e,t,n,r,i){let a=i+1,o=[];return e.docs!==void 0&&o.push({key:`docs`,value:V.jsonString(e.docs)}),o.push({key:`args`,value:yg(e.args,t,[...n,`args`],r,a,void 0)}),o.push({key:`run`,value:Eg(e.run,t,[...n,`run`],r,a)}),V.jsonObject(o,{path:n},i,r)}function Eg(e,t,n,r,i){try{return t.parseExpr(e).toJSONCode(n,r,i)}catch{return Dg(e,n,r,i)}}function Dg(e,t,n,r){let i=JSON.stringify(e,null,n);if(r>0){let e=` `.repeat(r*n);i=i.replace(/\n/g,`
|
|
104
|
+
`+e)}return oh(i,{path:t})}var W=class{type;raw;constructor(e,t){this.type=e,this.raw=t}toLogical(){return Og(this.raw)}encode(){return this.type.encode(this.raw)}toJSON(e=$h){return{type:this.type.toJSONRef(e),value:this.type.encodeAs(this.raw,e)}}encodeLogical(){return this.type.encodeAs(this.raw,jg)}toJSONRefs(){return this.toJSON({form:`envelope`,typeRefs:`name`})}toJSONLogical(){return this.toJSON(jg)}};function Og(e){if(e instanceof W)return e.toLogical();if(Array.isArray(e))return e.map(Og);if(e instanceof Map){let t=new Map;for(let n of e.values())kg(n)&&t.set(n[0].toLogical(),n[1].toLogical());return t}if(Ag(e)){let t={};for(let[n,r]of Object.entries(e))t[n]=Og(r);return t}return e}function kg(e){return Array.isArray(e)&&e.length===2&&e[0]instanceof W&&e[1]instanceof W}function Ag(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}var jg={form:`logical`,typeRefs:`name`};function G(e,t){return new W(e,t)}var Mg=class extends Error{constructor(){super(`The run was stopped.`),this.name=`RunStoppedError`}},Ng=class{signal;slice;#e=Date.now();constructor(e={}){this.signal=e.signal,this.slice=e.slice??10}check(){let e=this.signal;if(e?.aborted!==!0)return;let t=e.reason;throw t instanceof Error?t:new Mg}async checkpoint(){this.check(),Date.now()-this.#e<this.slice||(await new Promise(e=>{setTimeout(e,0)}),this.#e=Date.now(),this.check())}},Pg=new Set([`text`,`num`,`bool`,`enum`,`literal`,`date`,`timestamp`,`duration`,`color`,`null`]);function Fg(e){let t=e;for(let e=0;e<16;e+=1){let e=t.inner??t.base;if(e===void 0||e===t)return t;t=e}return t}function Ig(e){return Pg.has(Fg(e).name)}function Lg(e,t){let n=e.isOptional()?e.inner??e:e;return Ig(n)?R.union([n.toA(t),R.ref(`Expr`)]):R.ref(`Expr`)}function Rg(e,t){if(e===t)return!0;if(typeof e!=`object`||!e||typeof t!=`object`||!t)return!1;let n=e,r=t,i=Object.keys(n);return i.length===Object.keys(r).length&&i.every(e=>n[e]===r[e])}function zg(e,t,n){let r=Object.keys(e);return r.length===0?t?ng.toJSONMap(t):void 0:{...n&&Object.keys(n).length===r.length&&r.every(e=>e in n)?n:ng.toJSONMap(e),...t?ng.toJSONMap(t):{}}}function Bg(e,t){return{...e,props:e.props?ng.fromMap(e.props,t):void 0,get:e.get?rg.from(e.get,t):void 0,call:e.call?ig.from(e.call,t):void 0,init:e.init?ag.from(e.init,t):void 0}}var Vg=class e extends U{name;docs;base;original;local;bindings;constructor(e,t,n,r,i){let a=n.options?t.narrow(n.options):t.options,o=n.options&&!Rg(a,t.options)?e.parse({...t.toJSON(),options:a},i):t;super(r??e,a,n.generic??{}),this.original=t,this.base=o,this.local=Bg(n,e),this.name=n.name,this.docs=n.docs;let s=Object.entries(n.generic??{}).filter(([e,t])=>!U.isGenericPlaceholder(e,t));this.bindings=s.length>0?Object.fromEntries(s):void 0}storedLocalProps(){let e=[];for(let[t,n]of Object.entries(this.local.props??{})){let r=n instanceof ng?n:ng.from(n);r.get||r.type.call()||e.push([t,r])}return e}valid(e,t){let n=this.bindScope(t);if(!this.base.valid(e,n))return!1;let r=this.storedLocalProps();if(r.length===0||!eg(e))return!0;let i=e;for(let[e,t]of r){let r=i[e];if(!(r instanceof W))return t.type.isOptional();if(!r.type.valid(r.raw,n)||!qh(t.type,r.type,n))return!1}return!0}parse(e,t){let n=this.bindScope(t),r=this.base.parse(e,n),i=this.storedLocalProps();if(i.length===0||!eg(r.raw))return new W(this,r.raw);let a=eg(e)?e:{},o={...r.raw};for(let[e,t]of i)o[e]=this.registry.parseValue(a[e],t.type,n);return new W(this,o)}parsesExprValue(e){return this.base.parsesExprValue(this.bindScope(e))}encode(e,t){return this.encodeAs(e,$h,t)}encodeAs(e,t,n){let r=this.bindScope(n),i=this.base.encodeAs(e,t,r),a=this.storedLocalProps();if(a.length===0||!eg(i)||!eg(e))return i;let o=e,s={...i};for(let[e]of a)Qh(s,e,o[e],t,r);return s}create(){return this.withLocalSlots(this.base.create(),e=>e.create())}random(e){return this.withLocalSlots(this.base.random(e),t=>t.random(e))}withLocalSlots(e,t){let n=this.storedLocalProps();if(n.length===0||!eg(e))return e;let r={...e};for(let[e,i]of n)r[e]=new W(i.type,t(i.type));return r}forEachNewSlot(e,t){let n=this.base.forEachNewSlot(e,t),r=this.storedLocalProps();if(r.length===0||!eg(e))return n;let i=e;for(let[e,n]of r)e in i?t.slot(n.type,i[e],e):n.default!==void 0&&t.missing?.(n.default,e);return!0}async newFill(e,t,n){let r=await this.base.newFill(e,t,n),i=this.storedLocalProps();if(i.length===0||!eg(r))return r;let a=r,o;for(let[e,r]of i)if(e in a){let i=await r.type.newFill(a[e],t,n);i!==a[e]&&(o??={...a},o[e]=i)}else r.default!==void 0&&(o??={...a},o[e]=await r.default.evaluate(t,n));return o??a}compatibleType(t,n,r){return n?.exact?t instanceof e&&t.name===this.name&&this.base.compatible(t.base,n,r):t instanceof e?this.base.compatible(t.base,n,r):this.base.compatible(t,n,r)}or(t){if(t instanceof e&&t.name===this.name){let n={name:this.name,docs:this.docs??t.docs,options:{...this.local.options??{},...t.local.options??{}},props:{...this.local.props??{},...t.local.props??{}},get:this.local.get??t.local.get,call:this.local.call??t.local.call,init:this.local.init??t.local.init};return new e(this.registry,this.original,n)}return this.base.or(t)}simplify(){return this}required(){return this.base.required()}isOptional(){return this.base.isOptional()}narrow(e){return this.base.narrow(e)}props(e){let t=this.registry.augmentation(this.name);return{...this.base.props(this.bindScope(e)),...t?.props??{},...this.local.props??{}}}get(e){return this.local.get??this.registry.augmentation(this.name)?.get??this.base.get(this.bindScope(e))}call(e){return this.local.call??this.registry.augmentation(this.name)?.call??this.base.call(this.bindScope(e))}init(e){return this.local.init??this.registry.augmentation(this.name)?.init??this.base.init(this.bindScope(e))}toJSON(){if(cg.active>0&&cg.depth>0&&!this.local.useSite&&this.registry.lookup(this.name)!==void 0&&(this.registry.lookup(this.name)===this||this.bindings)){let e=Object.entries(this.bindings??{});return e.length>0?{name:this.name,generic:Object.fromEntries(e.map(([e,t])=>[e,t.toJSON()]))}:{name:this.name}}cg.depth++;try{return this.toJSONInner()}finally{cg.depth--}}toJSONInner(){if(this.local.useSite){let e=Object.entries(this.bindings??{});return{name:this.name,...e.length>0?{generic:Object.fromEntries(e.map(([e,t])=>[e,t.toJSON()]))}:{},options:{...this.local.options}}}let e=this.original.toJSON(),t=this.original.name!==this.name,n={...e.options,...this.local.options},r={...e.generic??{}};if(this.local.generic)for(let[e,t]of Object.entries(this.local.generic))r[e]=t.toJSON();return _h({name:this.name,extends:t?this.original.name:void 0,docs:this.docs,generic:Object.keys(r).length>0?r:void 0,options:n&&Object.keys(n).length>0?n:void 0,props:zg(t?this.original.refProps():{},this.local.props,e.props),get:(this.local.get??(t?this.original.refGet():void 0))?.toJSON(),call:(this.local.call??(t?this.original.refCall():void 0))?.toJSON(),init:this.local.init?.toJSON(),constraint:this.local.constraint?this.local.constraint.toJSON():void 0})}clone(){let t=this.local.generic?Object.fromEntries(Object.entries(this.local.generic).map(([e,t])=>[e,t.clone()])):void 0;return new e(this.registry,this.original.clone(),{name:this.local.name,docs:this.local.docs,options:this.local.options?{...this.local.options}:void 0,generic:t,props:this.local.props?{...this.local.props}:void 0,get:this.local.get,call:this.local.call,init:this.local.init,constraint:this.local.constraint?.clone(),useSite:this.local.useSite},this.bindings?this.scope:void 0)}toCode(e,t){return this.docsPrefix(t)+this.name+U.renderGenericArgs(this.generic,t)+(this.local.useSite?lg(this.local.options):``)}extendsClause(e){return` extends ${this.base.toCodeRef(void 0,e)}`}baseMembersElided(e){return this.base.toCodeRef(void 0,e)!==this.base.toCode(void 0,e)}ownAugmentation(){return this.registry.augmentation(this.name)}definitionInit(){return this.local.init??this.ownAugmentation()?.init}definitionCall(){return this.local.call??this.ownAugmentation()?.call??(this.baseMembersElided()?this.base.refCall():void 0)}definitionGet(){return this.local.get??this.ownAugmentation()?.get??(this.baseMembersElided()?this.base.refGet():void 0)}definitionProps(){return{...this.baseMembersElided()?this.base.refProps():{},...this.ownAugmentation()?.props??{},...this.local.props??{}}}specialize(t){let n={...this.local.generic??{}},r={};for(let e of Object.keys(this.local.generic??{})){let i=t[e];i&&(n[e]=i,r[e]=i)}return Object.keys(r).length===0?this:new e(this.registry,this.original,{...this.local,generic:n},new Ch(this.scope,r))}bindScope(e){return this.bindings?e?new Ch(e,this.bindings):this.scope:e}constraints(){let e=this.base.constraints();return this.local.constraint?[this.local.constraint,...e]:e}valueA(e){return this.mergeLocalPropsA(this.base.defineA(e),e,t=>t.type.toA(e))}toNewA(e){return this.describeA(this.mergeLocalPropsA(this.base.toNewA(e),e,t=>Lg(t.type,e)),e)}mergeLocalPropsA(e,t,n){if(!(e instanceof xf))return e;let r=t?.includeDocs??`none`,i={};for(let[e,t]of this.storedLocalProps()){let a=n(t);r===`all`&&t.docs&&(a=a.describe(t.docs)),i[e]=t.type.isOptional()&&a.kind!==`optional`?R.optional(a):a}return Object.keys(i).length===0?e:e.extend(i)}propSuperFor(e,t,n,r,i){let a=this.local.props;if(!(a&&Object.hasOwn(a,t)))return;let o=this.base.prop(t);if(!o)return;let s=new W(this.base,e.raw);if(n===`get`){if(o.type.call()&&o.get){let e=o.type;return new W(e,async e=>{let n={this:s,args:e},a=s.type.propSuperFor(s,t,`get`,r,i);return a&&(n.super=a),i.evaluate(o.get,r.child(n))})}return new W(i.registry.fn({args:i.registry.obj({}),returns:o.type}),async e=>{if(!o.get)return G(o.type,s.raw?.[t]);let n={this:s},a=s.type.propSuperFor(s,t,`get`,r,i);return a&&(n.super=a),i.evaluate(o.get,r.child(n))})}if(n===`set`)return o.set?new W(i.registry.fn({args:i.registry.obj({value:{type:o.type}}),returns:i.registry.void()}),async e=>{let n=e.raw.value,a={this:s,value:n},c=s.type.propSuperFor(s,t,`set`,r,i);return c&&(a.super=c),await i.evaluate(o.set,r.child(a)),G(i.registry.void(),void 0)}):void 0;let c=o.type.call();return c?.set?new W(i.registry.fn({args:i.registry.obj({args:{type:c.args},value:{type:c.returns??i.registry.any()}}),returns:i.registry.void()}),async e=>{let n=e.raw,a={this:s,args:n.args,value:n.value},o=s.type.propSuperFor(s,t,`callSet`,r,i);return o&&(a.super=o),await i.evaluate(c.set,r.child(a)),G(i.registry.void(),void 0)}):void 0}indexSuperFor(e,t,n,r){let i=this.local.get;if(!i)return;let a=this.base.get();if(!a)return;let o=new W(this.base,e.raw);return t===`get`?!i.get||!a.get?void 0:new W(r.registry.fn({args:r.registry.obj({key:{type:a.key}}),returns:a.value}),async e=>{let t=e.raw.key,n=r.createRootScope();return n.vars.set(`this`,o),n.vars.set(`key`,t),r.evaluate(a.get,n)}):!i.set||!a.set?void 0:new W(r.registry.fn({args:r.registry.obj({key:{type:a.key},value:{type:a.value}}),returns:r.registry.void()}),async e=>{let t=e.raw,n=r.createRootScope();return n.vars.set(`this`,o),n.vars.set(`key`,t.key),n.vars.set(`value`,t.value),await r.evaluate(a.set,n),G(r.registry.void(),void 0)})}},Hg=class e extends U{static NAME=`any`;name=e.NAME;static optionKeys=[];static genericKeys=[];static from(t,n){return n.registry,new e(n,{})}valid(e){return!0}parse(e){return new W(this,e)}encode(e){return e}create(){return null}random(e){return null}compatibleType(e,t){return!0}flexible(){return!0}isUniversal(){return!0}or(e){return this}narrow(e){if(e&&Object.keys(e).length>0)throw new ih({path:[],code:`any.no-options`,message:`any has no narrowable options`,severity:`error`});return{}}props(){let e=this.registry;return{...super.props(),typeOf:e.method({},e.text(),`any.typeOf`),is:e.method({},e.bool(),`any.is`,{generic:{T:e.any()}}),as:e.method({},e.optional(e.alias(`T`)),`any.as`,{generic:{T:e.any()}}),toText:e.method({},e.text(),`any.toText`),toBool:e.method({},e.bool(),`any.toBool`),eq:e.method({other:e.any()},e.bool(),`any.eq`),neq:e.method({other:e.any()},e.bool(),`any.neq`)}}toJSON(){return{name:e.NAME}}clone(){return new e(this.registry,{})}toCode(e,t){return this.docsPrefix(t)+`any`}valueA(){return R.unknown()}},Ug=class e extends U{static NAME=`obj`;static consumes=[`props`];name=e.NAME;static optionKeys=[];static genericKeys=[];fields;static from(t,n){let r=ng.fromMap(t.props??{},n);return new e(n,r)}constructor(e,t){super(e,{});let n={};for(let[e,r]of Object.entries(t))n[e]=ng.from(r);this.fields=n}valid(e,t){if(typeof e!=`object`||!e||Array.isArray(e))return!1;for(let[n,r]of Object.entries(this.fields)){let i=e[n];if(!(i instanceof W)||!i.type.valid(i.raw,t)||!qh(r.type,i.type,t))return!1}return!0}parse(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw new ih({path:[],code:`object.invalid`,message:`object.parse: expected object, got ${typeof e}`,severity:`error`});let n={};for(let[r,i]of Object.entries(this.fields)){let a=e[r];n[r]=this.registry.parseValue(a,i.type,t)}return new W(this,n)}encode(e,t){return this.encodeAs(e,$h,t)}encodeAs(e,t,n){let r=e,i={};for(let[e]of Object.entries(this.fields))Qh(i,e,r[e],t,n);return i}create(){let e={};for(let[t,n]of Object.entries(this.fields))e[t]=new W(n.type,n.type.create());return e}random(e){let t={};for(let[n,r]of Object.entries(this.fields))t[n]=new W(r.type,r.type.random(e));return t}forEachNewSlot(e,t){if(!Wg(e)||tg(e,this.scope))return!1;let n=e;for(let[e,r]of Object.entries(this.fields))e in n?t.slot(r.type,n[e],e):r.default!==void 0&&t.missing?.(r.default,e);return!0}async newFill(e,t,n){if(!Wg(e)||tg(e,this.scope))return super.newFill(e,t,n);let r=e,i;for(let[e,a]of Object.entries(this.fields))if(e in r){let o=await a.type.newFill(r[e],t,n);o!==r[e]&&(i??={...r},i[e]=o)}else a.default!==void 0&&(i??={...r},i[e]=await a.default.evaluate(t,n));return i??r}like(t){if(!(t instanceof e))return this;let n={};for(let[e,r]of Object.entries(t.fields)){let t=this.registry.like(r.type);if(t.name===`null`)return this.registry.null();n[e]={type:t}}return this.registry.obj(n)}compatibleType(t,n,r){if(!(t instanceof e))return!1;for(let[e,i]of Object.entries(this.fields)){let a=t.fields[e];if(!a){if(n?.exact)return!1;if(i.type.isOptional())continue;return!1}if(!i.type.compatible(a.type,n,r))return!1}if(n?.exact){let e=new Set(Object.keys(this.fields));for(let n of Object.keys(t.fields))if(!e.has(n))return!1}return!0}or(t){if(!(t instanceof e))return this;let n={};for(let[e,r]of Object.entries(this.fields)){let i=t.fields[e];i&&(n[e]={type:r.type.or(i.type)})}return new e(this.registry,n)}narrow(e){return{}}props(){let e=this.registry,t=Object.values(this.fields).map(e=>e.type),n=t.length===0?e.any():t.length===1?t[0]:e.or(t),r={keys:e.method({},e.list(e.text()),`object.keys`),values:e.method({},e.list(n),`object.values`),entries:e.method({},e.list(e.tuple([e.text(),n])),`object.entries`),has:e.method({key:e.text()},e.bool(),`object.has`),eq:e.method({other:e.any()},e.bool(),`object.eq`),neq:e.method({other:e.any()},e.bool(),`object.neq`),toText:e.method({},e.text(),`object.toText`)};return{...super.props(),...r,...this.fields}}get(){let e=Object.keys(this.fields);if(e.length===0)return;let t=this.registry.text(),n=e.map(e=>this.registry.literal(t,e)),r=n.length===1?n[0]:this.registry.or(n),i=Object.values(this.fields).map(e=>e.type),a=i.length===1?i[0]:this.registry.or(i),o=this.registry;return new rg({key:r,value:a,get:o.nativeExpr(`object.indexGet`),set:o.nativeExpr(`object.indexSet`),loop:o.nativeExpr(`object.iterate`)})}toJSON(){return{name:e.NAME,props:ng.toJSONMap(this.fields)}}clone(){let t={};for(let[e,n]of Object.entries(this.fields))t[e]={...n,type:n.type.clone()};return new e(this.registry,t)}toCode(e,t){let n=Object.entries(this.fields);if(n.length===0)return this.docsPrefix(t)+`obj`;let r=t?.includeComments!==!1,i=n.map(([e,n])=>{let i=n.type.isOptional(),a=i?n.type.required():n.type,o=i?`${e}?`:e;return`${n.docs&&r?`/* ${n.docs} */ `:``}${o}: ${a.toCode(void 0,t)}`});return this.docsPrefix(t)+`obj{${dg(i,{indent:fg(t)})}}`}toCodeRef(e,t){return this.docsPrefix(t)+`obj`}refProps(){return this.fields}valueA(e){let t=e?.includeDocs??`none`,n={};for(let[r,i]of Object.entries(this.fields)){let a=i.type.toA(e);t===`all`&&i.docs&&(a=a.describe(i.docs)),n[r]=a}return this.objectA(n,e)}toNewA(e){let t=e?.includeDocs??`none`,n={};for(let[r,i]of Object.entries(this.fields)){let a=Lg(i.type,e);t===`all`&&i.docs&&(a=a.describe(i.docs)),n[r]=i.type.isOptional()?R.optional(a):a}return this.describeA(R.object(n),e)}describe(t){if(typeof t!=`object`||!t||Array.isArray(t))return;let n={};for(let[e,r]of Object.entries(t))n[e]={type:this.registry.any().describe?.(r)??this.registry.any()};return new e(this.registry,n)}};function Wg(e){return eg(e)}var Gg=class e extends U{static NAME=`and`;name=e.NAME;static optionKeys=[`types`];static genericKeys=[];static from(t,n){n.registry;let r=(t.options?.types??[]).map(e=>n.parse(e));return new e(n,r)}constructor(e,t){super(e,{parts:t})}get parts(){return this.options.parts}valid(e,t){return this.parts.every(n=>n.valid(e,t))}effective(){let e=this.parts;if(e.length===0)return;if(e.length===1)return e[0];let t=this.mergedObjFields();return t?this.registry.obj(t):e[0]}mergedObjFields(){let e=[];for(let t of this.parts){if(!(t instanceof Ug))return;e.push(t)}let t={};for(let n of e)for(let[e,r]of Object.entries(n.fields)){let n=t[e];t[e]=n?{type:this.registry.and([n.type,r.type])}:r}return t}parse(e,t){let n=this.effective();if(!n)return new W(this,e);let r=n.parse(e,t).raw;for(let e of this.parts)if(!e.valid(r,t))throw new ih({path:[],code:`and.constraint`,message:`and: value fails part ${e.name}`,severity:`error`});return new W(this,r)}encode(e,t){return this.effective()?.encode(e,t)??e}parsesExprValue(e){return this.effective()?.parsesExprValue(e)??!1}encodeAs(e,t,n){return this.effective()?.encodeAs(e,t,n)??e}forEachNewSlot(e,t){return this.effective()?.forEachNewSlot(e,t)??!1}async newFill(e,t,n){let r=this.effective();return r?r.newFill(e,t,n):super.newFill(e,t,n)}create(){let e=this.effective();if(!e)return null;for(let t of[e,...this.parts]){let e=t.create();if(this.valid(e))return e}return e.create()}random(e){let t=this.effective();if(!t)return null;for(let n of[t,...this.parts]){let t=n.random(e);if(this.valid(t))return t}return t.random(e)}like(t){if(!(t instanceof e))return this;let n=t.parts.map(e=>this.registry.like(e)).filter(e=>e.name!==`null`);return n.length===0?this.registry.null():n.length===1?n[0]:this.registry.and(n)}compatibleType(e,t,n){return this.parts.every(r=>r.compatible(e,t,n))}isUniversal(){return this.parts.length===0||this.parts.every(e=>e.isUniversal())}or(t){return t instanceof e?new e(this.registry,[...this.parts,...t.parts]):this}simplify(){if(this.parts.length===1)return this.parts[0];if(this.parts.length===0)return this;let e=this.mergedObjFields();return e?this.registry.obj(e):this}narrow(e){return this.options}props(){let e={};for(let t of this.parts)for(let[n,r]of Object.entries(t.props()))e[n]=n in e?{type:this.registry.and([e[n].type,r.type])}:r;return e}get(){let e=this.parts.map(e=>e.get()).filter(e=>!!e);if(e.length!==0)return new rg({key:this.registry.or(e.map(e=>e.key)),value:this.registry.and(e.map(e=>e.value))})}call(){let e=this.parts.map(e=>e.call()).filter(e=>!!e);if(e.length===0)return;let t=e.map(e=>e.returns).filter(e=>!!e);return new ig({args:this.registry.or(e.map(e=>e.args)),returns:t.length>0?this.registry.and(t):void 0})}toJSON(){return{name:e.NAME,options:{types:this.parts.map(e=>e.toJSON())}}}clone(){return new e(this.registry,this.parts.map(e=>e.clone()))}toCode(e,t){return this.docsPrefix(t)+`and<${this.parts.map(e=>e.toCode(void 0,t)).join(`, `)}>`}valueA(e){return this.parts.length===0?R.unknown():this.parts.length===1?this.parts[0].toA(e):R.intersection(this.parts.map(t=>t.toA(e)))}toNewA(e){return this.parts.length===0?this.describeA(R.unknown(),e):this.parts.length===1?this.describeA(this.parts[0].toNewA(e),e):this.describeA(R.intersection(this.parts.map(t=>t.toNewA(e))),e)}},Kg=new Set,qg=class e extends U{static NAME=`alias`;name=e.NAME;constructor(e,t,n={}){super(e,t,n)}get hasUse(){return Object.keys(this.generic).length>0||this.options.options!==void 0}applied;static from(t,n){return new e(n,{name:t.name})}resolve(e){let t=(e?e.lookup(this.options.name):void 0)??this.scope.lookup(this.options.name);if(!t||!this.hasUse)return t;this.applied??=new WeakMap;let n=this.applied.get(t);return n||(n=this.registry.applyUse(t,this.generic,this.options.options),this.applied.set(t,n)),n}valid(e,t){let n=this.resolve(t);return!n||n.valid(e,t)}parse(e,t){let n=this.resolve(t);if(!n)return new W(this,e);let r=n.parse(e,t);return new W(this,r.raw)}encode(e,t){let n=this.resolve(t);return n?n.encode(e,t):e}parsesExprValue(e){return this.resolve(e)?.parsesExprValue(e)??!1}encodeAs(e,t,n){let r=this.resolve(n);return r?r.encodeAs(e,t,n):e}create(){let e=this.resolve();return e?e.create():null}random(e){let t=this.resolve();return t?t.random(e):null}compatibleType(e,t,n){let r=this.resolve(n);return!r||r.compatible(e,t,n)}flexible(){return!0}isUniversal(){let e=this.resolve();return!e||e.isUniversal()}or(e){let t=this.resolve();return t?t.or(e):this}simplify(e){return this.resolve(e)??this}narrow(e){return{...this.options,name:e.name??this.options.name}}props(e){let t=this.resolve(e);return t?t.props(e):super.props(e)}get(e){return this.resolve(e)?.get(e)}call(e){return this.resolve(e)?.call(e)}init(e){return this.resolve(e)?.init(e)}follow(e,t){return this.resolve(t)?.follow(e,t)}forEachNewSlot(e,t){return this.resolve()?.forEachNewSlot(e,t)??!1}async newFill(e,t,n){let r=this.resolve();return r?r.newFill(e,t,n):super.newFill(e,t,n)}toJSON(){if(!this.hasUse)return{name:this.options.name};let e=Object.entries(this.generic);return{name:this.options.name,...e.length>0?{generic:Object.fromEntries(e.map(([e,t])=>[e,t.toJSON()]))}:{},...this.options.options===void 0?{}:{options:{...this.options.options}}}}clone(){return new e(this.scope,{...this.options},{...this.generic})}toCode(e,t){return this.docsPrefix(t)+this.options.name+U.renderGenericArgs(this.generic,t)+lg(this.options.options)}valueA(e){let t=this.resolve(e?.scope);if(!t)return R.unknown();if(Kg.has(this.options.name))return R.json().describe(`A value of the named type ${this.options.name}.`);Kg.add(this.options.name);try{return t.toA(e)}finally{Kg.delete(this.options.name)}}toNewA(e){let t=this.resolve(e?.scope);if(!t)return R.unknown();if(Kg.has(this.options.name))return R.ref(`Expr`);Kg.add(this.options.name);try{return t.toNewA(e)}finally{Kg.delete(this.options.name)}}},Jg=class e extends U{static NAME=`bool`;name=e.NAME;static optionKeys=[`trueText`,`falseText`];static genericKeys=[];static from(t,n){return n.registry,new e(n,t.options??{})}valid(e){return typeof e==`boolean`}parse(e){if(typeof e==`boolean`)return new W(this,e);if(e===this.options.trueText)return new W(this,!0);if(e===this.options.falseText)return new W(this,!1);throw Error(`bool.parse: expected boolean, got ${typeof e}`)}encode(e){return e}create(){return!1}random(e){return e(0,1,!0)===1}compatibleType(t,n){return t instanceof e}or(t){return t instanceof e?new e(this.registry,{trueText:this.options.trueText??t.options.trueText,falseText:this.options.falseText??t.options.falseText}):this}narrow(e){return{...this.options,...e}}props(){let e=this.registry;return{...super.props(),eq:e.method({other:e.bool()},e.bool(),`bool.eq`),neq:e.method({other:e.bool()},e.bool(),`bool.neq`),and:e.method({other:e.bool()},e.bool(),`bool.and`),or:e.method({other:e.bool()},e.bool(),`bool.or`),xor:e.method({other:e.bool()},e.bool(),`bool.xor`),not:e.method({},e.bool(),`bool.not`),toText:e.method({},e.text(),`bool.toText`),toNum:e.method({},e.num(),`bool.toNum`)}}get(){let e=this.registry;return new rg({key:e.num({whole:!0,min:0}),value:e.bool(),loopDynamic:!0})}toJSON(){return _h({name:e.NAME,options:Object.keys(this.options).length>0?{...this.options}:void 0})}clone(){return new e(this.registry,{...this.options})}toCode(e,t){return this.docsPrefix(t)+`bool`+lg(this.options)}valueA(){return R.boolean()}describe(e){return typeof e==`boolean`?this:void 0}},Yg=class e extends U{static NAME=`color`;name=e.NAME;static optionKeys=[`hasAlpha`];static genericKeys=[];static from(t,n){return n.registry,new e(n,t.options??{})}valid(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0&&e<=4294967295}parse(e){let t=typeof e==`number`?e:Number(e);if(!this.valid(t))throw new ih({path:[],code:`color.invalid`,message:`color.parse: not a valid 32-bit color int: ${String(e)}`,severity:`error`});return new W(this,t)}encode(e){return e}create(){return 255}random(e){return e(0,4294967295,!0)}compatibleType(t,n){return t instanceof e}or(t){return t instanceof e?new e(this.registry,{hasAlpha:this.options.hasAlpha===t.options.hasAlpha?this.options.hasAlpha:void 0}):this}narrow(e){return{...this.options,...e}}init(){let e=this.registry,t=e.num({whole:!0,min:0,max:255}),n=e.optional(e.num({min:0,max:1}));return new ag({args:e.obj({r:{type:t},g:{type:t},b:{type:t},a:{type:n}}),run:e.nativeExpr(`color.init`)})}props(){let e=this.registry,t=e.num(),n=e.bool(),r=e.text(),i=e.color();return{...super.props(),r:e.prop(t,`color.r`),g:e.prop(t,`color.g`),b:e.prop(t,`color.b`),a:e.prop(t,`color.a`),hue:e.prop(t,`color.hue`),saturation:e.prop(t,`color.saturation`),lightness:e.prop(t,`color.lightness`),eq:e.method({other:i},n,`color.eq`),neq:e.method({other:i},n,`color.neq`),lighten:e.method({amount:t},i,`color.lighten`),darken:e.method({amount:t},i,`color.darken`),saturate:e.method({amount:t},i,`color.saturate`),desaturate:e.method({amount:t},i,`color.desaturate`),opacity:e.method({alpha:t},i,`color.opacity`),invert:e.method({},i,`color.invert`),mix:e.method({other:i,weight:e.optional(t)},i,`color.mix`),complement:e.method({},i,`color.complement`),toHex:e.method({},r,`color.toHex`),toRgb:e.method({},r,`color.toRgb`),toHsl:e.method({},r,`color.toHsl`),toText:e.method({},r,`color.toText`)}}toJSON(){return _h({name:e.NAME,options:Object.keys(this.options).length>0?{...this.options}:void 0})}clone(){return new e(this.registry,{...this.options})}toCode(e,t){return this.docsPrefix(t)+`color`+lg(this.options)}valueA(){return R.int().min(0).max(4294967295).describe(this.options.hasAlpha?`A color as a 32-bit integer 0xRRGGBBAA.`:`A color as an integer 0xRRGGBB.`)}},Xg=class e extends U{static NAME=`date`;name=e.NAME;static optionKeys=[`min`,`max`,`utc`];static genericKeys=[];static from(t,n){return n.registry,new e(n,t.options??{})}boundDate(e){return e?new Date(e):void 0}valid(e){if(!(e instanceof Date)||Number.isNaN(e.getTime()))return!1;let t=this.boundDate(this.options.min),n=this.boundDate(this.options.max);return!(t&&e<t||n&&e>n)}parse(e){let t=e instanceof Date?e:typeof e==`string`?new Date(e):new Date(NaN);if(!this.valid(t))throw new ih({path:[],code:`date.invalid`,message:`date.parse: invalid or out-of-range: ${String(e)}`,severity:`error`});return new W(this,t)}encode(e){return e.toISOString().slice(0,10)}create(){return new Date}random(e){let t=this.boundDate(this.options.min)?.getTime()??Date.UTC(2e3,0,1),n=this.boundDate(this.options.max)?.getTime()??Date.UTC(2050,11,31);return new Date(e(t,n,!0))}compatibleType(t,n){return t instanceof e}or(t){if(!(t instanceof e))return this;let n=this.options,r=t.options;return new e(this.registry,{min:n.min&&r.min?n.min<r.min?n.min:r.min:void 0,max:n.max&&r.max?n.max>r.max?n.max:r.max:void 0,utc:n.utc===r.utc?n.utc:void 0})}narrow(e){let t=this.options,n=(e,t)=>{throw new ih({path:[],code:e,message:t,severity:`error`})},r={...t};return e.min!==void 0&&(t.min&&e.min<t.min&&n(`date.widen.min`,`cannot move min earlier`),r.min=e.min),e.max!==void 0&&(t.max&&e.max>t.max&&n(`date.widen.max`,`cannot move max later`),r.max=e.max),e.utc!==void 0&&(r.utc=e.utc),r}props(){let e=this.registry,t=e.num({whole:!0}),n=e.bool(),r=e.text(),i=e.date();return{...super.props(),year:e.prop(t,`date.year`),month:e.prop(t,`date.month`),day:e.prop(t,`date.day`),dayOfWeek:e.prop(t,`date.dayOfWeek`),dayOfYear:e.prop(t,`date.dayOfYear`),eq:e.method({other:i},n,`date.eq`),neq:e.method({other:i},n,`date.neq`),before:e.method({other:i},n,`date.before`),after:e.method({other:i},n,`date.after`),addDays:e.method({days:t},i,`date.addDays`),addMonths:e.method({months:t},i,`date.addMonths`),addYears:e.method({years:t},i,`date.addYears`),diffDays:e.method({other:i},t,`date.diffDays`),diffMonths:e.method({other:i},t,`date.diffMonths`),diffYears:e.method({other:i},t,`date.diffYears`),toText:e.method({format:e.optional(r)},r,`date.toText`)}}toJSON(){return _h({name:e.NAME,options:Object.keys(this.options).length>0?{...this.options}:void 0})}clone(){return new e(this.registry,{...this.options})}toCode(e,t){return this.docsPrefix(t)+`date`+lg(this.options)}valueA(){return R.string().pattern(`^\\d{4}-\\d{2}-\\d{2}`).describe(`An ISO 8601 date (YYYY-MM-DD).`)}describe(e){return e instanceof Date?this:void 0}},Zg=class e extends U{static NAME=`duration`;name=e.NAME;static optionKeys=[];static genericKeys=[];static from(t,n){return n.registry,new e(n,{})}valid(e){return typeof e==`number`&&!Number.isNaN(e)}parse(e){let t=typeof e==`number`?e:Number(e);return new W(this,t)}encode(e){return e}create(){return 0}random(e){return e(0,864e5,!0)}compatibleType(t,n){return t instanceof e}or(e){return this}narrow(e){return{}}init(){let e=this.registry,t=e.num();return new ag({args:e.obj({days:{type:e.optional(t)},hours:{type:e.optional(t)},minutes:{type:e.optional(t)},seconds:{type:e.optional(t)},ms:{type:e.optional(t)}}),run:e.nativeExpr(`duration.init`)})}props(){let e=this.registry,t=e.num({whole:!0}),n=e.text();return{...super.props(),totalSeconds:e.prop(e.num(),`duration.totalSeconds`),totalMinutes:e.prop(e.num(),`duration.totalMinutes`),totalHours:e.prop(e.num(),`duration.totalHours`),totalDays:e.prop(e.num(),`duration.totalDays`),days:e.prop(t,`duration.days`),hours:e.prop(t,`duration.hours`),minutes:e.prop(t,`duration.minutes`),seconds:e.prop(t,`duration.seconds`),ms:e.prop(t,`duration.ms`),toText:e.method({format:e.optional(n)},n,`duration.toText`)}}toJSON(){return{name:e.NAME}}clone(){return new e(this.registry,{})}toCode(e,t){return this.docsPrefix(t)+`duration`}valueA(){return R.number().describe(`A duration in milliseconds.`)}},Qg=class e extends U{static NAME=`enum`;name=e.NAME;static optionKeys=[`values`];static genericKeys=[`V`];static from(t,n){let r=n.registry,i=t.generic?.V?n.parse(t.generic.V):r.text(),a=t.options?.values??{};return new e(n,i,{values:a})}constructor(e,t,n){super(e,n,{V:t})}get value(){return this.generic.V}valid(e,t){return this.value.valid(e,t)?Object.values(this.options.values).some(t=>t===e):!1}parse(e,t){let n=this.value.parse(e,t);if(!this.valid(n.raw,t))throw new ih({path:[],code:`enum.not-a-member`,message:`enum.parse: ${String(n.raw)} is not one of ${Object.values(this.options.values).join(`, `)}`,severity:`error`});return new W(this,n.raw)}encode(e,t){return this.value.encode(e,t)}encodeAs(e,t,n){return this.value.encodeAs(e,t,n)}create(){let e=Object.values(this.options.values)[0];return e===void 0?this.value.create():e}random(e){let t=Object.values(this.options.values);return t.length===0?this.value.random(e):t[e(0,t.length-1,!0)]}like(t){if(!(t instanceof e))return this;let n=this.registry.like(t.value);return n.name===`null`?this.registry.null():this.registry.enum(t.options.values,n)}compatibleType(t,n,r){return!(t instanceof e)||!this.value.compatible(t.value,n,r)?!1:!n?.value||Object.values(t.options.values).every(e=>Object.values(this.options.values).some(t=>t===e))}or(t){return t instanceof e?new e(this.registry,this.value.or(t.value),{values:{...t.options.values,...this.options.values}}):this}narrow(e){let t=this.options.values;if(e.values===void 0)return this.options;for(let[n,r]of Object.entries(e.values))if(!Object.values(t).some(e=>e===r))throw new ih({path:[],code:`enum.widen`,message:`enum.narrow: ${n}=${String(r)} not in base values`,severity:`error`});return{values:e.values}}props(){let e=this.registry,t=this.value;return{...super.props(),name:e.prop(e.text(),`enum.name`),value:e.prop(t,`enum.value`),eq:e.method({other:t},e.bool(),`enum.eq`),neq:e.method({other:t},e.bool(),`enum.neq`),toText:e.method({},e.text(),`enum.toText`)}}toJSON(){return{name:e.NAME,generic:{V:this.value.toJSON()},options:{values:this.options.values}}}clone(){return new e(this.registry,this.value.clone(),{values:{...this.options.values}})}toCode(e,t){let n=`enum<${this.value.toCode(void 0,t)}>`+e_(this.options.values,t);return this.docsPrefix(t)+n}valueA(){let e=Object.values(this.options.values);return e.length>0&&e.every(e=>typeof e==`string`)?R.enum(e):R.union(e.map(e=>R.literal(e)))}},$g=/^[A-Za-z_$][A-Za-z0-9_$]*$/;function e_(e,t){let n=Object.entries(e);return n.length===0?``:`{${dg(n.map(([e,t])=>{let n=$g.test(e)?e:JSON.stringify(e);return t===e?n:`${n}=${typeof t==`number`||typeof t==`boolean`?String(t):JSON.stringify(t??null)}`}),{indent:fg(t)})}}`}var t_=class e extends U{static NAME=`fn`;static consumes=[`call`];name=e.NAME;static optionKeys=[];static declaresGenerics=!0;_call;static from(t,n){let r=n.registry,i={},a=new Ch(n);if(t.generic)for(let[e,n]of Object.entries(t.generic))i[e]=a.parse(n);return t.call?new e(a,ig.from(t.call,a),i):new e(a,new ig({args:r.any(),returns:r.any()}),i)}constructor(e,t,n={}){super(e,{},n),this._call=t instanceof ig?t:new ig(t)}parsesExprValue(e){return!0}valid(e,t){return!!(typeof e==`function`||typeof e==`string`||e&&typeof e==`object`&&`kind`in e)}parse(e,t){return typeof e==`string`||e&&typeof e==`object`&&`kind`in e||typeof e==`function`?new W(this,e):new W(this,null)}encode(e,t){return typeof e==`function`?null:e}create(){return{kind:`new`,type:(this._call.returns??this.registry.void()).toJSON()}}random(e){return this.create()}like(t){if(!(t instanceof e))return this;let n=this.registry,r=n.like(t._call.args);if(r.name===`null`)return n.null();let i=t._call.returns?n.like(t._call.returns):void 0;if(i&&i.name===`null`)return n.null();let a=t._call.throws?n.like(t._call.throws):void 0;return a&&a.name===`null`?n.null():n.fn({args:r,returns:i,throws:a,generic:this.generic})}compatibleType(t,n,r){return!(!(t instanceof e)||!this._call.args.compatible(t._call.args,n,r)||this._call.returns&&t._call.returns&&!this._call.returns.compatible(t._call.returns,n,r))}or(t){return t instanceof e?new e(this.registry,{args:this._call.args.or(t._call.args),returns:this._call.returns&&t._call.returns?this._call.returns.or(t._call.returns):this._call.returns??t._call.returns,throws:this._call.throws&&t._call.throws?this._call.throws.or(t._call.throws):this._call.throws??t._call.throws}):this}narrow(e){return{}}call(e){return this._call}props(e){return super.props(e)}toJSON(){let t=Object.keys(this.generic),n=t.length===0?void 0:Object.fromEntries(t.map(e=>[e,this.generic[e].toJSON()]));return _h({name:e.NAME,call:this._call.toJSON(),generic:n})}clone(){let t={};for(let[e,n]of Object.entries(this.generic))t[e]=n.clone();return new e(this.registry,{args:this._call.args.clone(),returns:this._call.returns?.clone(),throws:this._call.throws?.clone(),get:this._call.get,set:this._call.set},t)}toCode(e,t){let n=this._call.returns?.toCode(void 0,t)??`void`;return this.docsPrefix(t)+`${U.renderGenerics(this.generic,t)}${this._call.renderTypes(t)}(${U.formatParams(this._call.args,t)}): ${n}`}valueA(){return R.union([R.string(),R.ref(`Expr`)])}},n_=class e extends U{static NAME=`interface`;static consumes=[`props`,`get`,`call`];name=e.NAME;static optionKeys=[];static genericKeys=[];_props;_get;_call;static from(t,n){return n.registry,new e(n,{props:t.props?ng.fromMap(t.props,n):{},get:t.get?rg.from(t.get,n):void 0,call:t.call?ig.from(t.call,n):void 0})}constructor(e,t){super(e,{});let n={};if(t.props)for(let[e,r]of Object.entries(t.props))n[e]=ng.from(r);this._props=n,this._get=t.get,this._call=t.call}valid(e,t){return!0}parse(e,t){return new W(this,e)}encode(e,t){return e}create(){return null}random(e){return null}like(t){if(!(t instanceof e))return this;let n=this.registry,r={};for(let[e,i]of Object.entries(t._props)){let t=n.like(i.type);if(t.name===`null`)return n.null();r[e]={type:t}}let i;if(t._get){let e=n.like(t._get.key),r=n.like(t._get.value);if(e.name===`null`||r.name===`null`)return n.null();i=new rg({key:e,value:r})}let a;if(t._call){let e=n.like(t._call.args);if(e.name===`null`)return n.null();let r=t._call.returns?n.like(t._call.returns):void 0;if(r&&r.name===`null`)return n.null();a=new ig({args:e,returns:r})}return new e(n,{props:r,get:i,call:a})}compatibleType(e,t,n){let r=e.props(n);for(let[e,i]of Object.entries(this._props)){let a=r[e];if(!a||!i.type.compatible(a.type,t,n))return!1}if(this._get){let r=e.get(n);if(!r||!this._get.key.compatible(r.key,t,n)||!this._get.value.compatible(r.value,t,n))return!1}if(this._call){let r=e.call(n);if(!r||!this._call.args.compatible(r.args,t,n)||this._call.returns&&r.returns&&!this._call.returns.compatible(r.returns,t,n))return!1}return!0}flexible(){return!0}isUniversal(){return Object.keys(this._props).length===0&&!this._get&&!this._call}or(t){if(!(t instanceof e))return this;let n={};for(let e of Object.keys(this._props))e in t._props&&(n[e]={type:this._props[e].type.or(t._props[e].type)});return new e(this.registry,{props:n})}narrow(e){return{}}props(e){return{...super.props(e),...this._props}}get(e){return this._get}call(e){return this._call}toJSON(){return _h({name:e.NAME,props:Object.keys(this._props).length>0?ng.toJSONMap(this._props):void 0,get:this._get?.toJSON(),call:this._call?.toJSON()})}clone(){let t={};for(let[e,n]of Object.entries(this._props))t[e]={...n,type:n.type.clone()};return new e(this.registry,{props:t,get:this._get,call:this._call})}toCode(e,t){let n=t?.includeComments!==!1,r=[];for(let[e,i]of Object.entries(this._props)){let a=i.type.isOptional(),o=a?i.type.required():i.type,s=a?`${e}?`:e,c=i.docs&&n?`/* ${i.docs} */ `:``;r.push(`${c}${s}: ${o.toCode(void 0,t)}`)}if(this._get&&r.push(`[key: ${this._get.key.toCode(void 0,t)}]: ${this._get.value.toCode(void 0,t)}`),this._call){let e=this._call.returns?.toCode(void 0,t)??`void`;r.push(`(${this._call.args.toCode(void 0,t)}): ${e}`)}let i=r.length===0?`iface`:`iface{${dg(r,{indent:fg(t)})}}`;return this.docsPrefix(t)+i}toCodeRef(e,t){return this.docsPrefix(t)+`iface`}refProps(){return this._props}refGet(){return this._get}refCall(){return this._call}valueA(e){let t=e?.includeDocs??`none`,n={};for(let[r,i]of Object.entries(this._props)){let a=i.type.toA(e);t===`all`&&i.docs&&(a=a.describe(i.docs)),n[r]=a}return this.objectA(n,e)}toNewA(e){let t=e?.includeDocs??`none`,n={};for(let[e,r]of Object.entries(this._props)){let i=R.ref(`Expr`);t===`all`&&r.docs&&(i=i.describe(r.docs)),n[e]=i}return this.describeA(R.object(n),e)}},r_=class e extends U{static NAME=`literal`;name=e.NAME;static optionKeys=[`value`];static genericKeys=[`T`];inner;static from(t,n){let r=n.registry,i=t.generic?.T?n.parse(t.generic.T):r.any(),a=t.options?.value;return new e(n,i,a)}constructor(e,t,n){super(e,{value:n},{T:t}),this.inner=t}get literal(){return this.options.value}valid(e,t){return this.inner.valid(e,t)&&e===this.literal}parse(e,t){let n=this.inner.parse(e,t);if(n.raw!==this.literal)throw new ih({path:[],code:`literal.not-match`,message:`literal: expected ${String(this.literal)}, got ${String(n.raw)}`,severity:`error`});return new W(this,n.raw)}encode(e,t){return this.inner.encode(e,t)}encodeAs(e,t,n){return this.inner.encodeAs(e,t,n)}create(){return this.literal}random(e){return this.literal}compatibleType(t,n,r){return t instanceof e?this.inner.compatible(t.inner,n,r)&&this.literal===t.literal:!n?.exact&&this.inner.compatible(t,n,r)}isUniversal(){return this.inner.isUniversal()}or(t){return t instanceof e&&(t.literal,this.literal),this}narrow(e){if(e.value!==void 0&&e.value!==this.literal)throw new ih({path:[],code:`literal.narrow`,message:`literal value cannot change via narrow`,severity:`error`});return this.options}props(){return this.inner.props()}toJSON(){return{name:e.NAME,generic:{T:this.inner.toJSON()},options:{value:this.literal}}}clone(){return new e(this.registry,this.inner.clone(),this.literal)}toCode(e,t){return this.docsPrefix(t)+`literal<${this.inner.toCode(void 0,t)}>`+lg({value:this.literal})}valueA(){return R.literal(this.literal)}},i_=class e extends U{static NAME=`list`;name=e.NAME;static optionKeys=[`minLength`,`maxLength`];static genericKeys=[`V`];static from(t,n){let r=n.registry,i=t.generic?.V?n.parse(t.generic.V):r.any();return new e(n,i,t.options??{})}constructor(e,t,n={}){super(e,n,{V:t})}get item(){return this.generic.V}valid(e,t){if(!Array.isArray(e))return!1;let{minLength:n,maxLength:r}=this.options;return n!==void 0&&e.length<n||r!==void 0&&e.length>r?!1:e.every(e=>e instanceof W&&e.type.valid(e.raw,t)&&qh(this.item,e.type,t))}parse(e,t){if(!Array.isArray(e))throw new ih({path:[],code:`list.invalid`,message:`list.parse: expected array, got ${typeof e}`,severity:`error`});let n=e.map(e=>this.registry.parseValue(e,this.item,t));if(!this.valid(n,t))throw new ih({path:[],code:`list.constraint`,message:`list.parse: length constraints violated`,severity:`error`});return new W(this,n)}encode(e,t){return this.encodeAs(e,$h,t)}encodeAs(e,t,n){return e.map(e=>Zh(e,t,n))}create(){let e=this.options.minLength??0;return Array.from({length:e},()=>new W(this.item,this.item.create()))}random(e){let t=this.options.minLength??0,n=e(t,this.options.maxLength??Math.max(t,5),!0);return Array.from({length:n},()=>new W(this.item,this.item.random(e)))}forEachNewSlot(e,t){if(!Array.isArray(e))return!1;for(let n=0;n<e.length;n++)t.slot(this.item,e[n],n);return!0}async newFill(e,t,n){if(!Array.isArray(e))return super.newFill(e,t,n);let r=[];for(let i of e)r.push(await this.item.newFill(i,t,n));return r}like(t){if(!(t instanceof e))return this;let n=this.registry.like(t.item);return n.name===`null`?n:this.registry.list(n)}compatibleType(t,n,r){if(!(t instanceof e)||!this.item.compatible(t.item,n,r))return!1;if(!n?.value)return!0;let i=this.options,a=t.options;return!(i.minLength!==void 0&&(a.minLength===void 0||a.minLength<i.minLength)||i.maxLength!==void 0&&(a.maxLength===void 0||a.maxLength>i.maxLength))}or(t){if(!(t instanceof e))return this;let n=this.options,r=t.options;return new e(this.registry,this.item.or(t.item),{minLength:n.minLength!==void 0&&r.minLength!==void 0?Math.min(n.minLength,r.minLength):void 0,maxLength:n.maxLength!==void 0&&r.maxLength!==void 0?Math.max(n.maxLength,r.maxLength):void 0})}narrow(e){let t=this.options,n=(e,t)=>{throw new ih({path:[],code:e,message:t,severity:`error`})},r={...t};return e.minLength!==void 0&&(t.minLength!==void 0&&e.minLength<t.minLength&&n(`list.widen.minLength`,`local ${e.minLength} < base ${t.minLength}`),r.minLength=e.minLength),e.maxLength!==void 0&&(t.maxLength!==void 0&&e.maxLength>t.maxLength&&n(`list.widen.maxLength`,`local ${e.maxLength} > base ${t.maxLength}`),r.maxLength=e.maxLength),r}get(){let e=this.registry;return new rg({key:e.num({whole:!0,min:0}),value:this.item,get:e.nativeExpr(`list.indexGet`),set:e.nativeExpr(`list.indexSet`),loop:e.nativeExpr(`list.iterate`)})}props(){let e=this.registry,t=this.item,n=e.num(),r=e.bool(),i=e.text(),a=e.void(),o=e.optional(t),s=e.list(t),c=r=>e.fn({args:e.obj({value:{type:t},index:{type:n}}),returns:r});return{...super.props(),length:e.prop(n,`list.length`),at:e.method({index:n},o,`list.at`),push:e.method({value:t},a,`list.push`),pop:e.method({},o,`list.pop`),shift:e.method({},o,`list.shift`),unshift:e.method({value:t},a,`list.unshift`),insert:e.method({index:n,value:t},a,`list.insert`),remove:e.method({index:n},t,`list.remove`),clear:e.method({},a,`list.clear`),slice:e.method({start:e.optional(n),end:e.optional(n)},s,`list.slice`),concat:e.method({other:s},s,`list.concat`),reverse:e.method({},s,`list.reverse`),join:e.method({separator:e.optional(i)},i,`list.join`),indexOf:e.method({value:t},n,`list.indexOf`),contains:e.method({value:t},r,`list.contains`),unique:e.method({},s,`list.unique`),duplicates:e.method({},s,`list.duplicates`),map:e.method({fn:c(e.alias(`R`))},e.list(e.alias(`R`)),`list.map`,{generic:{R:e.any()}}),filter:e.method({fn:c(r)},s,`list.filter`),find:e.method({fn:c(r)},o,`list.find`),reduce:e.method({fn:e.fn({args:e.obj({acc:{type:e.alias(`R`)},value:{type:t},index:{type:n}}),returns:e.alias(`R`)}),initial:e.alias(`R`)},e.alias(`R`),`list.reduce`,{generic:{R:e.any()}}),some:e.method({fn:c(r)},r,`list.some`),every:e.method({fn:c(r)},r,`list.every`),sort:e.method({fn:e.optional(e.fn({args:e.obj({a:{type:t},b:{type:t}}),returns:n}))},s,`list.sort`),isEmpty:e.method({},r,`list.isEmpty`),isNotEmpty:e.method({},r,`list.isNotEmpty`),first:e.prop(o,`list.first`),last:e.prop(o,`list.last`)}}toJSON(){return _h({name:e.NAME,generic:{V:this.item.toJSON()},options:Object.keys(this.options).length>0?{...this.options}:void 0})}clone(){return new e(this.registry,this.item.clone(),{...this.options})}toCode(e,t){return this.docsPrefix(t)+`list<${this.item.toCode(void 0,t)}>`+lg(this.options,{minLength:0})}valueA(e){let t=R.array(this.item.toA(e));return this.options.minLength!==void 0&&(t=t.min(this.options.minLength)),this.options.maxLength!==void 0&&(t=t.max(this.options.maxLength)),t}toNewA(e){let t=R.array(R.ref(`Expr`));return this.options.minLength!==void 0&&(t=t.min(this.options.minLength)),this.options.maxLength!==void 0&&(t=t.max(this.options.maxLength)),this.describeA(t,e)}describe(t){if(Array.isArray(t))return new e(this.registry,this.registry.any(),{})}};function a_(e){return Array.isArray(e)&&e.length===2&&e[0]instanceof W&&e[1]instanceof W}function o_(e){if(Array.isArray(e))return[e[0],e[1]];let t=e;return[t?.key,t?.value]}function s_(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Map)}var c_=class e extends U{static NAME=`map`;name=e.NAME;static optionKeys=[];static genericKeys=[`K`,`V`];static from(t,n){let r=n.registry,i=t.generic?.K?n.parse(t.generic.K):r.text(),a=t.generic?.V?n.parse(t.generic.V):r.any();return new e(n,i,a)}constructor(e,t,n){super(e,{},{K:t,V:n})}get key(){return this.generic.K}get value(){return this.generic.V}valid(e,t){if(!(e instanceof Map))return!1;for(let[,n]of e){if(!Array.isArray(n)||n.length!==2)return!1;let[e,r]=n;if(!(e instanceof W)||!(r instanceof W)||!e.type.valid(e.raw,t)||!r.type.valid(r.raw,t)||!qh(this.key,e.type,t)||!qh(this.value,r.type,t))return!1}return!0}parse(e,t){let n=e instanceof Map?Array.from(e,([e,t])=>a_(t)?t:[e,t]):this.textKeyed()&&s_(e)?Object.entries(e):e;if(!Array.isArray(n))throw new ih({path:[],code:`map.invalid`,message:`map.parse: expected array of [key, value] pairs`,severity:`error`});let r=new Map;for(let e of n){let[n,i]=Array.isArray(e)?e:[e.key,e.value],a=this.registry.parseValue(n,this.key,t),o=this.registry.parseValue(i,this.value,t);r.set(a.raw,[a,o])}return new W(this,r)}encode(e,t){return this.encodeAs(e,$h,t)}encodeAs(e,t,n){return t.form===`logical`&&this.textKeyed()?Object.fromEntries(Array.from(e,([,[e,r]])=>[String(Zh(e,t,n)),Zh(r,t,n)])):Array.from(e,([,[e,r]])=>({key:Zh(e,t,n),value:Zh(r,t,n)}))}textKeyed(){return this.key.name===`text`}create(){return new Map}forEachNewSlot(e,t){if(!Array.isArray(e))return!1;for(let n=0;n<e.length;n++){let[r,i]=o_(e[n]);t.slot(this.key,r,`${n}.key`),t.slot(this.value,i,`${n}.value`)}return!0}async newFill(e,t,n){if(!Array.isArray(e))return super.newFill(e,t,n);let r=[];for(let i of e){let[e,a]=o_(i);r.push({key:await this.key.newFill(e,t,n),value:await this.value.newFill(a,t,n)})}return r}random(e){let t=e(0,5,!0),n=new Map;for(let r=0;r<t;r++){let t=this.key.random(e),r=this.value.random(e);n.set(t,[new W(this.key,t),new W(this.value,r)])}return n}like(t){if(!(t instanceof e))return this;let n=this.registry.like(t.key),r=this.registry.like(t.value);return n.name===`null`||r.name===`null`?this.registry.null():this.registry.map(n,r)}compatibleType(t,n,r){return t instanceof e&&this.key.compatible(t.key,n,r)&&this.value.compatible(t.value,n,r)}or(t){return t instanceof e?new e(this.registry,this.key.or(t.key),this.value.or(t.value)):this}narrow(e){return{}}get(){let e=this.registry;return new rg({key:this.key,value:this.value,get:e.nativeExpr(`map.indexGet`),set:e.nativeExpr(`map.indexSet`),loop:e.nativeExpr(`map.iterate`)})}props(){let e=this.registry,t=this.key,n=this.value,r=e.num(),i=e.bool(),a=e.void(),o=e.optional(n);return{...super.props(),size:e.prop(r,`map.size`),at:e.method({key:t},o,`map.at`),has:e.method({key:t},i,`map.has`),delete:e.method({key:t},i,`map.delete`),clear:e.method({},a,`map.clear`),keys:e.method({},e.list(t),`map.keys`),values:e.method({},e.list(n),`map.values`),isEmpty:e.method({},i,`map.isEmpty`),isNotEmpty:e.method({},i,`map.isNotEmpty`)}}toJSON(){return{name:e.NAME,generic:{K:this.key.toJSON(),V:this.value.toJSON()}}}clone(){return new e(this.registry,this.key.clone(),this.value.clone())}toCode(e,t){return this.docsPrefix(t)+`map<${this.key.toCode(void 0,t)}, ${this.value.toCode(void 0,t)}>`}valueA(e){return this.key.name===`text`?R.record(this.value.toA(e)):R.array(this.objectA({key:this.key.toA(e),value:this.value.toA(e)},e))}toNewA(e){return this.describeA(R.array(R.object({key:R.ref(`Expr`),value:R.ref(`Expr`)})),e)}describe(t){return t instanceof Map?new e(this.registry,this.registry.any(),this.registry.any()):void 0}},l_=class e extends U{constructor(e,t){super(e,{excluded:t.toJSON()}),this.excluded=t}excluded;static NAME=`not`;name=e.NAME;static optionKeys=[`excluded`];static genericKeys=[];static from(t,n){let r=n.registry,i=t.options?.excluded?n.parse(t.options.excluded):r.any();return new e(n,i)}valid(e,t){return!this.excluded.valid(e,t)}parse(e,t){if(this.excluded.valid(e,t))throw new ih({path:[],code:`not.excluded`,message:`not: value matches excluded type ${this.excluded.name}`,severity:`error`});return new W(this,e)}encode(e,t){return e}create(){return null}random(e){return null}like(t){if(!(t instanceof e))return this;let n=this.registry.like(t.excluded);return n.name===`null`?n:this.registry.not(n)}compatibleType(t,n,r){return n?.exact?t instanceof e&&this.excluded.exact(t.excluded,r):!this.excluded.compatible(t,n,r)}flexible(){return!0}or(t){return t instanceof e?new e(this.registry,this.registry.or([this.excluded,t.excluded])):this}narrow(e){return{excluded:e.excluded??this.options.excluded}}props(){let e=this.registry;return{...super.props(),typeOf:e.method({},e.text(),`not.typeOf`),toText:e.method({},e.text(),`not.toText`)}}toJSON(){return{name:e.NAME,options:{excluded:this.excluded.toJSON()}}}clone(){return new e(this.registry,this.excluded.clone())}toCode(e,t){return this.docsPrefix(t)+`not<${this.excluded.toCode(void 0,t)}>`}valueA(e){return R.not(this.excluded.toA(e))}},u_=class e extends U{static NAME=`null`;name=e.NAME;static optionKeys=[];static genericKeys=[];static from(t,n){return n.registry,new e(n,{})}valid(e){return e===null}parse(e){if(e!==null)throw new ih({path:[],code:`null.invalid`,message:`null expects null, got ${typeof e}`,severity:`error`});return new W(this,null)}encode(e){return null}create(){return null}random(e){return null}compatibleType(t,n){return t instanceof e}or(e){return this}narrow(e){if(e&&Object.keys(e).length>0)throw new ih({path:[],code:`null.no-options`,message:`null has no narrowable options`,severity:`error`});return{}}props(){let e=this.registry;return{...super.props(),toText:e.method({},e.text(),`null.toText`),toBool:e.method({},e.bool(),`null.toBool`)}}toJSON(){return{name:e.NAME}}clone(){return new e(this.registry,{})}toCode(e,t){return this.docsPrefix(t)+`null`}valueA(){return R.null()}},d_=class e extends U{constructor(e,t){super(e,{},{T:t}),this.inner=t}inner;static NAME=`nullable`;name=e.NAME;static optionKeys=[];static genericKeys=[`T`];static from(t,n){let r=n.registry,i=t.generic?.T?n.parse(t.generic.T):r.any();return new e(n,i)}valid(e,t){return e===null||this.inner.valid(e,t)}parse(e,t){if(e===null)return new W(this,null);let n=this.inner.parse(e,t);return new W(this,n.raw)}parsesExprValue(e){return this.inner.parsesExprValue(e)}encode(e,t){return this.encodeAs(e,$h,t)}encodeAs(e,t,n){return e===null?null:this.inner.encodeAs(e,t,n)}forEachNewSlot(e,t){return e!=null&&this.inner.forEachNewSlot(e,t)}async newFill(e,t,n){return e==null?e:this.inner.newFill(e,t,n)}create(){return null}random(e){return e(0,9,!0)<3?null:this.inner.random(e)}like(t){if(!(t instanceof e))return this;let n=this.registry.like(t.inner);return n.name===`null`?n:this.registry.nullable(n)}compatibleType(t,n,r){return t instanceof e?this.inner.compatible(t.inner,n,r):!n?.exact&&this.inner.compatible(t,n,r)}or(t){return t instanceof e?new e(this.registry,this.inner.or(t.inner)):this}required(){return this.inner}isUniversal(){return this.inner.isUniversal()}narrow(e){if(e&&Object.keys(e).length>0)throw new ih({path:[],code:`nullable.no-options`,message:`nullable has no narrowable options`,severity:`error`});return{}}props(){let e=this.registry,t=this.inner;return{...super.props(),value:e.prop(t,`nullable.value`),isNull:e.method({},e.bool(),`nullable.isNull`),or:e.method({fallback:t},t,`nullable.or`),map:e.method({fn:e.fn({args:e.obj({value:{type:t}}),returns:e.alias(`R`)})},e.nullable(e.alias(`R`)),`nullable.map`,{generic:{R:e.any()}})}}toJSON(){return{name:e.NAME,generic:{T:this.inner.toJSON()}}}clone(){return new e(this.registry,this.inner.clone())}toCode(e,t){return this.docsPrefix(t)+`nullable<${this.inner.toCode(void 0,t)}>`}valueA(e){return R.nullable(this.inner.toA(e))}toNewA(e){return this.describeA(R.nullable(this.inner.toNewA(e)),e)}},f_=class e extends U{static NAME=`num`;name=e.NAME;static optionKeys=[`min`,`max`,`whole`,`minPrecision`,`maxPrecision`,`prefix`,`suffix`];static genericKeys=[];static from(t,n){return n.registry,new e(n,t.options??{})}valid(e){if(typeof e!=`number`||Number.isNaN(e))return!1;let{min:t,max:n,whole:r}=this.options;return!(t!==void 0&&e<t||n!==void 0&&e>n||r&&!Number.isInteger(e))}parse(e){let t=typeof e==`string`?Number(e):e;if(typeof t!=`number`||Number.isNaN(t))throw new ih({path:[],code:`num.invalid`,message:`num.parse: not a number \u2014 ${String(e)}`,severity:`error`});if(!this.valid(t))throw new ih({path:[],code:`num.out-of-range`,message:`num.parse: ${t} violates options ${JSON.stringify(this.options)}`,severity:`error`});return new W(this,t)}encode(e){return e}create(){let{min:e,max:t,whole:n}=this.options,r=0;if(e!==void 0&&r<e&&(r=e),t!==void 0&&r>t&&(r=t),n&&!Number.isInteger(r)){let e=Math.ceil(r);r=t!==void 0&&e>t?Math.floor(r):e}return r}random(e){return e(this.options.min??0,this.options.max??100,this.options.whole??!1)}compatibleType(t,n){if(!(t instanceof e))return!1;if(!n?.value)return!0;let r=this.options,i=t.options;return!(r.min!==void 0&&(i.min===void 0||i.min<r.min)||r.max!==void 0&&(i.max===void 0||i.max>r.max)||r.whole&&!i.whole)}or(t){if(!(t instanceof e))return this;let n=this.options,r=t.options;return new e(this.registry,{min:n.min!==void 0&&r.min!==void 0?Math.min(n.min,r.min):void 0,max:n.max!==void 0&&r.max!==void 0?Math.max(n.max,r.max):void 0,whole:n.whole&&r.whole,minPrecision:n.minPrecision!==void 0&&r.minPrecision!==void 0?Math.min(n.minPrecision,r.minPrecision):void 0,maxPrecision:n.maxPrecision!==void 0&&r.maxPrecision!==void 0?Math.max(n.maxPrecision,r.maxPrecision):void 0,prefix:n.prefix===r.prefix?n.prefix:void 0,suffix:n.suffix===r.suffix?n.suffix:void 0})}narrow(e){let t=this.options,n=(e,t)=>{throw new ih({path:[],code:e,message:t,severity:`error`})},r={...t};return e.min!==void 0&&(t.min!==void 0&&e.min<t.min&&n(`num.widen.min`,`local.min ${e.min} < base.min ${t.min}`),r.min=e.min),e.max!==void 0&&(t.max!==void 0&&e.max>t.max&&n(`num.widen.max`,`local.max ${e.max} > base.max ${t.max}`),r.max=e.max),e.whole!==void 0&&(t.whole===!0&&!e.whole&&n(`num.widen.whole`,`base requires whole; local cannot remove`),r.whole=e.whole),e.minPrecision!==void 0&&(t.minPrecision!==void 0&&e.minPrecision<t.minPrecision&&n(`num.widen.minPrecision`,`minPrecision cannot decrease`),r.minPrecision=e.minPrecision),e.maxPrecision!==void 0&&(t.maxPrecision!==void 0&&e.maxPrecision>t.maxPrecision&&n(`num.widen.maxPrecision`,`maxPrecision cannot increase`),r.maxPrecision=e.maxPrecision),e.prefix!==void 0&&(r.prefix=e.prefix),e.suffix!==void 0&&(r.suffix=e.suffix),r}get(){let e=this.registry;return new rg({key:e.num({whole:!0,min:0}),value:e.num(),loop:e.nativeExpr(`num.loop`)})}props(){let e=this.registry,t=e.num(),n=e.bool(),r=e.text(),i=e.optional(t);return{...super.props(),eq:e.method({other:t,epsilon:i},n,`num.eq`),neq:e.method({other:t,epsilon:i},n,`num.neq`),lt:e.method({other:t},n,`num.lt`),lte:e.method({other:t},n,`num.lte`),gt:e.method({other:t},n,`num.gt`),gte:e.method({other:t},n,`num.gte`),add:e.method({other:t},t,`num.add`),sub:e.method({other:t},t,`num.sub`),mul:e.method({other:t},t,`num.mul`),div:e.method({other:t},t,`num.div`),mod:e.method({other:t},t,`num.mod`),pow:e.method({other:t},t,`num.pow`),abs:e.method({},t,`num.abs`),neg:e.method({},t,`num.neg`),sign:e.method({},t,`num.sign`),sqrt:e.method({},t,`num.sqrt`),min:e.method({other:t},t,`num.min`),max:e.method({other:t},t,`num.max`),clamp:e.method({min:t,max:t},t,`num.clamp`),floor:e.method({},t,`num.floor`),ceil:e.method({},t,`num.ceil`),round:e.method({},t,`num.round`),isZero:e.method({},n,`num.isZero`),isPositive:e.method({},n,`num.isPositive`),isNegative:e.method({},n,`num.isNegative`),isInteger:e.method({},n,`num.isInteger`),isEven:e.method({},n,`num.isEven`),isOdd:e.method({},n,`num.isOdd`),toText:e.method({precision:i},r,`num.toText`),toBool:e.method({},n,`num.toBool`)}}toJSON(){return _h({name:e.NAME,options:Object.keys(this.options).length>0?{...this.options}:void 0})}clone(){return new e(this.registry,{...this.options})}toCode(e,t){return this.docsPrefix(t)+`num`+lg(this.options,{minPrecision:1,maxPrecision:7,prefix:``,suffix:``})}valueA(){let e=this.options.whole?R.int():R.number();return this.options.min!==void 0&&(e=e.min(this.options.min)),this.options.max!==void 0&&(e=e.max(this.options.max)),e}describe(t){if(!(typeof t!=`number`||Number.isNaN(t)))return new e(this.registry,{whole:Number.isInteger(t)})}},p_=class e extends U{constructor(e,t){super(e,{},{T:t}),this.inner=t}inner;static NAME=`optional`;name=e.NAME;static optionKeys=[];static genericKeys=[`T`];static from(t,n){let r=n.registry,i=t.generic?.T?n.parse(t.generic.T):r.any();return new e(n,i)}valid(e,t){return e===void 0||this.inner.valid(e,t)}parse(e,t){if(e==null)return new W(this,void 0);let n=this.inner.parse(e,t);return new W(this,n.raw)}parsesExprValue(e){return this.inner.parsesExprValue(e)}encode(e,t){return this.encodeAs(e,$h,t)}encodeAs(e,t,n){return e===void 0?null:this.inner.encodeAs(e,t,n)}forEachNewSlot(e,t){return e!=null&&this.inner.forEachNewSlot(e,t)}async newFill(e,t,n){return e==null?e:this.inner.newFill(e,t,n)}create(){}random(e){if(!(e(0,9,!0)<3))return this.inner.random(e)}like(t){if(!(t instanceof e))return this;let n=this.registry.like(t.inner);return n.name===`null`?n:this.registry.optional(n)}compatibleType(t,n,r){return t instanceof e?this.inner.compatible(t.inner,n,r):!n?.exact&&this.inner.compatible(t,n,r)}or(t){return t instanceof e?new e(this.registry,this.inner.or(t.inner)):this}required(){return this.inner}isOptional(){return!0}isUniversal(){return this.inner.isUniversal()}narrow(e){if(e&&Object.keys(e).length>0)throw new ih({path:[],code:`optional.no-options`,message:`optional has no narrowable options`,severity:`error`});return{}}props(){let e=this.registry,t=this.inner;return{...super.props(),value:e.prop(t,`optional.value`),has:e.method({},e.bool(),`optional.has`),or:e.method({fallback:t},t,`optional.or`),map:e.method({fn:e.fn({args:e.obj({value:{type:t}}),returns:e.alias(`R`)})},e.optional(e.alias(`R`)),`optional.map`,{generic:{R:e.any()}})}}toJSON(){return{name:e.NAME,generic:{T:this.inner.toJSON()}}}clone(){return new e(this.registry,this.inner.clone())}toCode(e,t){return this.docsPrefix(t)+`optional<${this.inner.toCode(void 0,t)}>`}valueA(e){return R.optional(this.inner.toA(e))}toNewA(e){return this.describeA(R.optional(this.inner.toNewA(e)),e)}},m_=class e extends U{static NAME=`or`;name=e.NAME;static optionKeys=[`types`];static genericKeys=[];static from(t,n){n.registry;let r=(t.options?.types??[]).map(e=>n.parse(e));return new e(n,r)}constructor(e,t){super(e,{variants:t})}get variants(){return this.options.variants}valid(e,t){return this.variants.some(n=>n.valid(e,t))}parse(e,t){for(let n of this.variants)try{let r=n.parse(e,t);return new W(this,r.raw)}catch{continue}throw new ih({path:[],code:`or.no-match`,message:`or: no variant matched (${this.variants.map(e=>e.name).join(` | `)})`,severity:`error`})}encode(e,t){let n=this.variants.find(n=>n.valid(e,t));if(!n)throw new ih({path:[],code:`or.dump.no-match`,message:`or.dump: value does not satisfy any variant`,severity:`error`});return n.encode(e,t)}parsesExprValue(e){return this.variants.some(t=>t.parsesExprValue(e))}encodeAs(e,t,n){let r=this.variants.find(t=>t.valid(e,n));if(!r)throw new ih({path:[],code:`or.dump.no-match`,message:`or.dump: value does not satisfy any variant`,severity:`error`});return r.encodeAs(e,t,n)}create(){return this.variants[0]?.create()??null}random(e){let t=e(0,this.variants.length-1,!0);return this.variants[t]?.random(e)??null}like(t){if(!(t instanceof e))return this;let n=t.variants.map(e=>this.registry.like(e)).filter(e=>e.name!==`null`);return n.length===0?this.registry.null():n.length===1?n[0]:this.registry.or(n)}compatibleType(e,t,n){return this.variants.some(r=>r.compatible(e,t,n))}or(t){return t instanceof e?new e(this.registry,[...this.variants,...t.variants]):new e(this.registry,[...this.variants,t])}simplify(){return this.variants.length===1?this.variants[0]:this}narrow(e){return this.options}props(){let e=super.props();if(this.variants.length===0)return e;let t=this.variants.map(e=>e.props()),n=Object.keys(t[0]).filter(e=>t.every(t=>e in t)),r={...e};for(let e of n){let n=t.map(t=>t[e].type);r[e]={type:this.registry.or(n)}}return r}get(){let e=this.variants.map(e=>e.get());if(e.some(e=>!e))return;let t=e;return new rg({key:this.registry.and(t.map(e=>e.key)),value:this.registry.or(t.map(e=>e.value))})}call(){let e=this.variants.map(e=>e.call());if(e.some(e=>!e))return;let t=e,n=t.map(e=>e.returns).filter(e=>!!e),r=t.map(e=>e.throws).filter(e=>!!e);return new ig({args:this.registry.and(t.map(e=>e.args)),returns:n.length===t.length?this.registry.or(n):void 0,throws:r.length>0?this.registry.or(r):void 0})}toJSON(){return{name:e.NAME,options:{types:this.variants.map(e=>e.toJSON())}}}clone(){return new e(this.registry,this.variants.map(e=>e.clone()))}toCode(e,t){return this.docsPrefix(t)+`or<${this.variants.map(e=>e.toCode(void 0,t)).join(`, `)}>`}valueA(e){return this.variants.length===0?R.never():this.variants.length===1?this.variants[0].toA(e):R.union(this.variants.map(t=>t.toA(e)))}toNewA(e){return this.variants.length===0?this.describeA(R.never(),e):this.variants.length===1?this.describeA(this.variants[0].toNewA(e),e):this.describeA(R.union(this.variants.map(t=>t.toNewA(e))),e)}},h_=class e extends U{static NAME=`text`;name=e.NAME;static optionKeys=[`minLength`,`maxLength`,`pattern`,`flags`];static genericKeys=[];_regex;static from(t,n){return n.registry,new e(n,t.options??{})}regex(){if(this._regex)return this._regex;if(this.options.pattern)return this._regex=new RegExp(this.options.pattern,this.options.flags),this._regex}valid(e){if(typeof e!=`string`)return!1;let{minLength:t,maxLength:n}=this.options;if(t!==void 0&&e.length<t||n!==void 0&&e.length>n)return!1;let r=this.regex();return!(r&&!r.test(e))}parse(e){if(typeof e!=`string`)throw new ih({path:[],code:`text.invalid`,message:`text.parse: expected string, got ${typeof e}`,severity:`error`});if(!this.valid(e))throw new ih({path:[],code:`text.constraint`,message:`text.parse: value violates constraints`,severity:`error`});return new W(this,e)}encode(e){return e}create(){let e=this.options.minLength??0;return e>0?`a`.repeat(e):``}random(e){let t=e(this.options.minLength??0,this.options.maxLength??16,!0),n=``;for(let r=0;r<t;r++)n+=`abcdefghijklmnopqrstuvwxyz0123456789`[e(0,35,!0)];return n}compatibleType(t,n){if(!(t instanceof e))return!1;if(!n?.value)return!0;let r=this.options,i=t.options;return!(r.minLength!==void 0&&(i.minLength===void 0||i.minLength<r.minLength)||r.maxLength!==void 0&&(i.maxLength===void 0||i.maxLength>r.maxLength)||r.pattern&&r.pattern!==i.pattern)}or(t){if(!(t instanceof e))return this;let n=this.options,r=t.options;return new e(this.registry,{minLength:n.minLength!==void 0&&r.minLength!==void 0?Math.min(n.minLength,r.minLength):void 0,maxLength:n.maxLength!==void 0&&r.maxLength!==void 0?Math.max(n.maxLength,r.maxLength):void 0,pattern:n.pattern===r.pattern?n.pattern:void 0,flags:n.pattern===r.pattern?n.flags:void 0})}narrow(e){let t=this.options,n=(e,t)=>{throw new ih({path:[],code:e,message:t,severity:`error`})},r={...t};return e.minLength!==void 0&&(t.minLength!==void 0&&e.minLength<t.minLength&&n(`text.widen.minLength`,`local ${e.minLength} < base ${t.minLength}`),r.minLength=e.minLength),e.maxLength!==void 0&&(t.maxLength!==void 0&&e.maxLength>t.maxLength&&n(`text.widen.maxLength`,`local ${e.maxLength} > base ${t.maxLength}`),r.maxLength=e.maxLength),e.pattern!==void 0&&(t.pattern!==void 0&&(e.pattern!==t.pattern||e.flags!==t.flags)&&n(`text.widen.pattern`,`pattern narrowing is only allowed when base has no pattern or matches exactly`),r.pattern=e.pattern,r.flags=e.flags),r}get(){let e=this.registry;return new rg({key:e.num(),value:e.text({minLength:1,maxLength:1}),get:e.nativeExpr(`text.charAt`),loop:e.nativeExpr(`text.chars`)})}props(){let e=this.registry,t=e.text(),n=e.num(),r=e.bool(),i=e.optional(n);return{...super.props(),length:e.prop(n,`text.length`),eq:e.method({other:t},r,`text.eq`),neq:e.method({other:t},r,`text.neq`),contains:e.method({search:t},r,`text.contains`),startsWith:e.method({prefix:t},r,`text.startsWith`),endsWith:e.method({suffix:t},r,`text.endsWith`),trim:e.method({},t,`text.trim`),trimStart:e.method({},t,`text.trimStart`),trimEnd:e.method({},t,`text.trimEnd`),upper:e.method({},t,`text.upper`),lower:e.method({},t,`text.lower`),slice:e.method({start:n,end:i},t,`text.slice`),replace:e.method({search:t,replacement:t},t,`text.replace`),split:e.method({separator:t},e.list(t),`text.split`),concat:e.method({other:t},t,`text.concat`),repeat:e.method({count:n},t,`text.repeat`),indexOf:e.method({search:t,from:i},n,`text.indexOf`),lastIndexOf:e.method({search:t,from:i},n,`text.lastIndexOf`),match:e.method({pattern:t},e.list(t),`text.match`),test:e.method({pattern:t},r,`text.test`),isEmpty:e.method({},r,`text.isEmpty`),isNotEmpty:e.method({},r,`text.isNotEmpty`),toNum:e.method({},n,`text.toNum`),toBool:e.method({},r,`text.toBool`)}}toJSON(){return _h({name:e.NAME,options:Object.keys(this.options).length>0?{...this.options}:void 0})}clone(){return new e(this.registry,{...this.options})}toCode(e,t){return this.docsPrefix(t)+`text`+lg(this.options)}valueA(){let e=R.string();return this.options.minLength!==void 0&&(e=e.min(this.options.minLength)),this.options.maxLength!==void 0&&(e=e.max(this.options.maxLength)),this.options.pattern&&(e=e.pattern(this.options.pattern,this.options.flags)),e}describe(e){return typeof e==`string`?this:void 0}},g_=class e extends U{static NAME=`timestamp`;name=e.NAME;static optionKeys=[`min`,`max`,`utc`,`precision`];static genericKeys=[];static from(t,n){return n.registry,new e(n,t.options??{})}valid(e){return e instanceof Date&&!Number.isNaN(e.getTime())}parse(e){let t=e instanceof Date?e:typeof e==`string`?new Date(e):new Date(NaN);if(!this.valid(t))throw new ih({path:[],code:`timestamp.invalid`,message:`timestamp.parse: invalid: ${String(e)}`,severity:`error`});return new W(this,t)}encode(e){return e.toISOString()}create(){return new Date}random(e){return new Date(e(Date.UTC(2e3,0,1),Date.UTC(2050,11,31),!0))}compatibleType(t,n){return t instanceof e}or(t){return t instanceof e,this}narrow(e){return this.options}props(){let e=this.registry,t=e.num({whole:!0}),n=e.bool(),r=e.text(),i=e.timestamp(),a=e.duration();return{...super.props(),year:e.prop(t,`timestamp.year`),month:e.prop(t,`timestamp.month`),day:e.prop(t,`timestamp.day`),hour:e.prop(t,`timestamp.hour`),minute:e.prop(t,`timestamp.minute`),second:e.prop(t,`timestamp.second`),millisecond:e.prop(t,`timestamp.millisecond`),eq:e.method({other:i},n,`timestamp.eq`),before:e.method({other:i},n,`timestamp.before`),after:e.method({other:i},n,`timestamp.after`),addDuration:e.method({duration:a},i,`timestamp.addDuration`),subDuration:e.method({duration:a},i,`timestamp.subDuration`),diff:e.method({other:i},a,`timestamp.diff`),toDate:e.method({},e.date(),`timestamp.toDate`),toEpoch:e.method({},t,`timestamp.toEpoch`),toText:e.method({format:e.optional(r)},r,`timestamp.toText`)}}toJSON(){return _h({name:e.NAME,options:Object.keys(this.options).length>0?{...this.options}:void 0})}clone(){return new e(this.registry,{...this.options})}toCode(e,t){return this.docsPrefix(t)+`timestamp`+lg(this.options)}valueA(){return R.string().pattern(`^\\d{4}-\\d{2}-\\d{2}[T ]\\d{2}:\\d{2}(:\\d{2}(\\.\\d+)?)?(Z|[+-]\\d{2}:?\\d{2})?$`).describe(`An ISO 8601 timestamp (YYYY-MM-DD HH:MM[:SS][Z]).`)}describe(e){return e instanceof Date?this:void 0}};function __(e){let t,n={};return Object.defineProperty(n,"elements",{enumerable:!0,get:()=>t??=e.map(e=>e.toJSON())}),n}var v_=class e extends U{static NAME=`tuple`;name=e.NAME;static optionKeys=[`elements`];static genericKeys=[];elements;static from(t,n){n.registry;let r=(t.options?.elements??[]).map(e=>n.parse(e));return new e(n,r)}constructor(e,t){super(e,__(t)),this.elements=t}valid(e,t){return!Array.isArray(e)||e.length!==this.elements.length?!1:e.every((e,n)=>e instanceof W&&e.type.valid(e.raw,t)&&qh(this.elements[n],e.type,t))}parse(e,t){if(!Array.isArray(e)||e.length!==this.elements.length)throw new ih({path:[],code:`tuple.invalid`,message:`tuple.parse: expected array of length ${this.elements.length}`,severity:`error`});let n=this.elements.map((n,r)=>this.registry.parseValue(e[r],n,t));return new W(this,n)}encode(e,t){return this.encodeAs(e,$h,t)}encodeAs(e,t,n){if(!Array.isArray(e))throw new ih({path:[],code:`tuple.invalid`,message:`tuple.encode: expected an array of cells`,severity:`error`});return e.map(e=>Zh(e,t,n))}create(){return this.elements.map(e=>new W(e,e.create()))}forEachNewSlot(e,t){if(!Array.isArray(e))return!1;for(let n=0;n<this.elements.length&&n<e.length;n++)t.slot(this.elements[n],e[n],n);return!0}async newFill(e,t,n){if(!Array.isArray(e))return super.newFill(e,t,n);let r=[];for(let i=0;i<e.length;i++){let a=this.elements[i];r.push(a?await a.newFill(e[i],t,n):e[i])}return r}random(e){return this.elements.map(t=>new W(t,t.random(e)))}like(t){if(!(t instanceof e)||t.elements.length!==this.elements.length)return this;let n=t.elements.map(e=>this.registry.like(e));return n.some(e=>e.name===`null`)?this.registry.null():this.registry.tuple(n)}compatibleType(t,n,r){return!(t instanceof e)||t.elements.length!==this.elements.length?!1:this.elements.every((e,i)=>e.compatible(t.elements[i],n,r))}or(t){return!(t instanceof e)||t.elements.length!==this.elements.length?this:new e(this.registry,this.elements.map((e,n)=>e.or(t.elements[n])))}narrow(e){return e.elements===void 0?this.options:{elements:e.elements}}get(){let e=this.elements.length===1?this.elements[0]:this.registry.or(this.elements),t=this.registry;return new rg({key:t.num({whole:!0,min:0,max:this.elements.length-1}),value:e,get:t.nativeExpr(`tuple.at`),set:t.nativeExpr(`tuple.setAt`),loop:t.nativeExpr(`tuple.iterate`)})}follow(e,t){if(`key`in e&&!(`args`in e)){let t=e.key,n=t?.kind===`new`?t.value:void 0;if(typeof n==`number`&&Number.isInteger(n))return this.elements[n]}return super.follow(e,t)}props(){let e=this.registry;e.num();let t=this.elements[0]??e.any(),n=this.elements[this.elements.length-1]??e.any();return{...super.props(),length:e.prop(e.num({whole:!0,min:this.elements.length,max:this.elements.length}),`tuple.length`),first:e.prop(t,`tuple.first`),last:e.prop(n,`tuple.last`),toList:e.method({},e.list(this.elements.length===0?e.any():e.or(this.elements)),`tuple.toList`)}}toJSON(){return{name:e.NAME,options:{elements:this.elements.map(e=>e.toJSON())}}}clone(){return new e(this.registry,this.elements.map(e=>e.clone()))}toCode(e,t){return this.docsPrefix(t)+`tuple<${this.elements.map(e=>e.toCode(void 0,t)).join(`, `)}>`}valueA(e){let t=this.elements.map(t=>t.toA(e));return t.length>0?R.tuple(t):R.array(R.unknown()).max(0)}toNewA(e){let t=this.elements.map(()=>R.ref(`Expr`));return this.describeA(t.length>0?R.tuple(t):R.array(R.ref(`Expr`)).max(0),e)}},y_=class e extends U{constructor(e,t){super(e,{},{T:t}),this.constraint=t}constraint;static NAME=`typ`;name=e.NAME;static optionKeys=[];static genericKeys=[`T`];static valuesAreTypes=!0;static from(t,n){let r=n.registry,i=t.generic?.T?n.parse(t.generic.T):r.any();return new e(n,i)}valid(e,t){return e instanceof U?e.compatible(this.constraint,void 0,t)||this.constraint.compatible(e,void 0,t):!1}parse(t,n){if(t instanceof W&&t.type instanceof e)return t;if(t instanceof U){if(!this.valid(t,n))throw Error(`typ.parse: Type '${t.name}' is not compatible with ${this.constraint.toCode()}`);return new W(this,t)}if(!t||typeof t!=`object`||Array.isArray(t))throw Error(`typ.parse: expected TypeDef or Type, got ${typeof t}`);if(!(`name`in t)||typeof t.name!=`string`)throw Error(`typ.parse: TypeDef missing 'name' field`);let r;try{r=this.registry.parse(t,n)}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`typ.parse: ${t}`)}if(!this.valid(r,n))throw Error(`typ.parse: Type '${r.name}' is not compatible with ${this.constraint.toCode()}`);let i=n??this.registry,a=r.references().refs.filter(e=>i.lookup(e)===void 0);if(a.length>0)throw Error(`typ.parse: no type named ${a.join(`, `)}`);return new W(this,r)}encode(e,t){return e.toJSON()}create(){return this.constraint}random(e){return this.constraint}compatibleType(t,n,r){return t instanceof e&&this.constraint.compatible(t.constraint,n,r)}or(t){return t instanceof e?new e(this.registry,this.registry.or([this.constraint,t.constraint])):this}narrow(e){return{}}props(){return{...super.props()}}toJSON(){return{name:e.NAME,generic:{T:this.constraint.toJSON()}}}clone(){return new e(this.registry,this.constraint.clone())}toCode(e,t){return this.docsPrefix(t)+`typ<${this.constraint.toCode(void 0,t)}>`}valueA(e){let t=this.registry.compatible(this.constraint);if(t.length===0&&this.constraint.name!==`any`)return R.never();let n;if(this.constraint.name===`any`)n=R.ref(`TypeDef`);else{let e=t.map(e=>Nm(this.registry,e.name));e.push(Pm()),e.push(Fm(t.map(e=>e.name))),n=R.union(e).describe(`A gin type definition ({ "name": ..., ... }) whose type fits ${this.constraint.toCode()}.`)}return n.refine(t=>{try{return this.parse(t,e?.scope),!0}catch(e){return e instanceof Error?e.message:String(e)}})}toNewA(e){return this.describeA(this.toA(e),e)}},b_=class e extends U{static NAME=`void`;name=e.NAME;static optionKeys=[];static genericKeys=[];static from(t,n){return n.registry,new e(n,{})}valid(e){return e===void 0}parse(e){if(e!=null)throw new ih({path:[],code:`void.invalid`,message:`void expects undefined/null, got ${typeof e}`,severity:`error`});return new W(this,void 0)}encode(e){return null}create(){}random(e){}compatibleType(t,n){return t instanceof e}or(e){return this}narrow(e){if(e&&Object.keys(e).length>0)throw new ih({path:[],code:`void.no-options`,message:`void has no narrowable options`,severity:`error`});return{}}props(){let e=this.registry;return{...super.props(),toText:e.method({},e.text(),`void.toText`),toBool:e.method({},e.bool(),`void.toBool`)}}toJSON(){return{name:e.NAME}}clone(){return new e(this.registry,{})}toCode(e,t){return this.docsPrefix(t)+`void`}valueA(){return R.null()}};function K(e){return e.get(`this`).raw}function x_(e){return e.get(`this`)}function q(e,t){let n=e.get(`args`);if(!n)return;let r=n.raw?.[t];return r==null?r:w_(r)?r.raw:r}function S_(e,t){let n=e.get(`args`);if(!n)return;let r=n.raw?.[t];if(w_(r))return r}function C_(e){let t=q(e,`epsilon`);return typeof t==`number`?t:0}function w_(e){return!!e&&typeof e==`object`&&`type`in e&&`raw`in e}function T_(e,t,n,r){let i=e.get(`yield`).raw,a=t.obj({key:{type:n},value:{type:r}});return(e,t)=>i(new W(a,{key:e,value:t}))}var E_={"type.toAny":(e,t)=>G(t.any(),K(e)),"any.typeOf":(e,t)=>G(t.text(),x_(e).type.name),"any.is":(e,t)=>G(t.bool(),!0),"any.as":(e,t)=>{let n=x_(e);return G(t.optional(n.type),n.raw)},"any.toText":(e,t)=>G(t.text(),String(K(e))),"any.toBool":(e,t)=>G(t.bool(),!!K(e)),"any.eq":(e,t)=>G(t.bool(),K(e)===q(e,`other`)),"any.neq":(e,t)=>G(t.bool(),K(e)!==q(e,`other`))},D_={"void.toText":(e,t)=>G(t.text(),`void`),"void.toBool":(e,t)=>G(t.bool(),!1)},O_={"null.toText":(e,t)=>G(t.text(),`null`),"null.toBool":(e,t)=>G(t.bool(),!1)},k_={"bool.eq":(e,t)=>G(t.bool(),K(e)===q(e,`other`)),"bool.neq":(e,t)=>G(t.bool(),K(e)!==q(e,`other`)),"bool.and":(e,t)=>G(t.bool(),K(e)&&q(e,`other`)),"bool.or":(e,t)=>G(t.bool(),K(e)||q(e,`other`)),"bool.xor":(e,t)=>G(t.bool(),K(e)!==q(e,`other`)),"bool.not":(e,t)=>G(t.bool(),!K(e)),"bool.toText":(e,t)=>{let n=K(e),r=q(e,`trueText`),i=q(e,`falseText`);return G(t.text(),n?r??`true`:i??`false`)},"bool.toNum":(e,t)=>{let n=K(e),r=q(e,`trueValue`),i=q(e,`falseValue`);return G(t.num(),n?r??1:i??0)}},A_={"num.eq":(e,t)=>G(t.bool(),Math.abs(K(e)-q(e,`other`))<=C_(e)),"num.neq":(e,t)=>G(t.bool(),Math.abs(K(e)-q(e,`other`))>C_(e)),"num.lt":(e,t)=>G(t.bool(),K(e)<q(e,`other`)),"num.lte":(e,t)=>G(t.bool(),K(e)<=q(e,`other`)),"num.gt":(e,t)=>G(t.bool(),K(e)>q(e,`other`)),"num.gte":(e,t)=>G(t.bool(),K(e)>=q(e,`other`)),"num.add":(e,t)=>G(t.num(),K(e)+q(e,`other`)),"num.sub":(e,t)=>G(t.num(),K(e)-q(e,`other`)),"num.mul":(e,t)=>G(t.num(),K(e)*q(e,`other`)),"num.div":(e,t)=>G(t.num(),K(e)/q(e,`other`)),"num.mod":(e,t)=>G(t.num(),K(e)%q(e,`other`)),"num.pow":(e,t)=>G(t.num(),K(e)**q(e,`other`)),"num.abs":(e,t)=>G(t.num(),Math.abs(K(e))),"num.neg":(e,t)=>G(t.num(),-K(e)),"num.sign":(e,t)=>G(t.num(),Math.sign(K(e))),"num.sqrt":(e,t)=>G(t.num(),Math.sqrt(K(e))),"num.min":(e,t)=>G(t.num(),Math.min(K(e),q(e,`other`))),"num.max":(e,t)=>G(t.num(),Math.max(K(e),q(e,`other`))),"num.clamp":(e,t)=>G(t.num(),Math.min(Math.max(K(e),q(e,`min`)),q(e,`max`))),"num.floor":(e,t)=>G(t.num(),Math.floor(K(e))),"num.ceil":(e,t)=>G(t.num(),Math.ceil(K(e))),"num.round":(e,t)=>G(t.num(),Math.round(K(e))),"num.isZero":(e,t)=>G(t.bool(),Math.abs(K(e))<=C_(e)),"num.isPositive":(e,t)=>G(t.bool(),K(e)>C_(e)),"num.isNegative":(e,t)=>G(t.bool(),K(e)<-C_(e)),"num.isInteger":(e,t)=>G(t.bool(),Number.isInteger(K(e))),"num.isEven":(e,t)=>G(t.bool(),K(e)%2==0),"num.isOdd":(e,t)=>G(t.bool(),Math.abs(K(e))%2==1),"num.toText":(e,t)=>{let n=q(e,`precision`),r=n==null?String(K(e)):K(e).toFixed(n);return G(t.text(),r)},"num.toBool":(e,t)=>G(t.bool(),K(e)!==0),"num.loop":async(e,t)=>{let n=K(e),r=t.num(),i=T_(e,t,r,r),a=Math.abs(Math.trunc(n)),o=n<0?-1:1;for(let e=0;e<a;e++){let t=e*o,n=Object.is(t,-0)?0:t;await i(G(r,e),G(r,n))}return G(t.void(),void 0)}},j_={"text.length":(e,t)=>G(t.num({whole:!0,min:0}),K(e).length),"text.eq":(e,t)=>G(t.bool(),K(e)===q(e,`other`)),"text.neq":(e,t)=>G(t.bool(),K(e)!==q(e,`other`)),"text.contains":(e,t)=>G(t.bool(),K(e).includes(q(e,`search`))),"text.startsWith":(e,t)=>G(t.bool(),K(e).startsWith(q(e,`prefix`))),"text.endsWith":(e,t)=>G(t.bool(),K(e).endsWith(q(e,`suffix`))),"text.trim":(e,t)=>G(t.text(),K(e).trim()),"text.trimStart":(e,t)=>G(t.text(),K(e).trimStart()),"text.trimEnd":(e,t)=>G(t.text(),K(e).trimEnd()),"text.upper":(e,t)=>G(t.text(),K(e).toUpperCase()),"text.lower":(e,t)=>G(t.text(),K(e).toLowerCase()),"text.slice":(e,t)=>{let n=q(e,`start`),r=q(e,`end`);return G(t.text(),K(e).slice(n,r))},"text.replace":(e,t)=>{let n=q(e,`search`),r=q(e,`replacement`);return G(t.text(),K(e).split(n).join(r))},"text.split":(e,t)=>{let n=K(e).split(q(e,`separator`));return G(t.list(t.text()),n.map(e=>G(t.text(),e)))},"text.concat":(e,t)=>G(t.text(),K(e)+q(e,`other`)),"text.repeat":(e,t)=>G(t.text(),K(e).repeat(q(e,`count`))),"text.indexOf":(e,t)=>{let n=q(e,`from`);return G(t.num(),K(e).indexOf(q(e,`search`),n))},"text.lastIndexOf":(e,t)=>{let n=q(e,`from`);return G(t.num(),K(e).lastIndexOf(q(e,`search`),n))},"text.match":(e,t)=>{let n=q(e,`pattern`),r=K(e).match(new RegExp(n,`g`))??[];return G(t.list(t.text()),r.map(e=>G(t.text(),e)))},"text.test":(e,t)=>{let n=q(e,`pattern`);return G(t.bool(),new RegExp(n).test(K(e)))},"text.isEmpty":(e,t)=>G(t.bool(),K(e).length===0),"text.isNotEmpty":(e,t)=>G(t.bool(),K(e).length>0),"text.toNum":(e,t)=>G(t.num(),Number(K(e))),"text.toBool":(e,t)=>G(t.bool(),K(e).length>0),"text.charAt":(e,t)=>{let n=e.get(`key`).raw,r=K(e)[n];if(r===void 0)throw Error(`text[${n}]: index out of range`);return G(t.text({minLength:1,maxLength:1}),r)},"text.chars":async(e,t)=>{let n=K(e),r=t.num({whole:!0,min:0}),i=t.text({minLength:1,maxLength:1}),a=T_(e,t,r,i);for(let e=0;e<n.length;e++)await a(G(r,e),G(i,n[e]));return G(t.void(),void 0)}},M_=e=>x_(e).type.item,N_={"list.length":(e,t)=>G(t.num({whole:!0,min:0}),K(e).length),"list.indexGet":e=>{let t=e.get(`key`).raw,n=K(e);if(t<0||t>=n.length)throw Error(`list[${t}]: index out of range`);return n[t]},"list.indexSet":(e,t)=>{let n=e.get(`key`).raw,r=e.get(`value`),i=K(e);if(n<0||n>=i.length)throw Error(`list[${n}] =: index out of range`);return i[n]=r,G(t.void(),void 0)},"list.iterate":async(e,t)=>{let n=K(e),r=t.num({whole:!0,min:0}),i=T_(e,t,r,M_(e)),a=G(t.void(),void 0);for(let e=0;e<n.length;e++)await i(G(r,e),n[e]);return a},"list.at":(e,t)=>{let n=q(e,`index`),r=K(e);return n<0||n>=r.length?G(t.optional(M_(e)),void 0):G(t.optional(M_(e)),r[n].raw)},"list.push":(e,t)=>(K(e).push(S_(e,`value`)),G(t.void(),void 0)),"list.pop":(e,t)=>{let n=K(e).pop();return G(t.optional(M_(e)),n?n.raw:void 0)},"list.shift":(e,t)=>{let n=K(e).shift();return G(t.optional(M_(e)),n?n.raw:void 0)},"list.unshift":(e,t)=>(K(e).unshift(S_(e,`value`)),G(t.void(),void 0)),"list.insert":(e,t)=>(K(e).splice(q(e,`index`),0,S_(e,`value`)),G(t.void(),void 0)),"list.remove":e=>K(e).splice(q(e,`index`),1)[0],"list.clear":(e,t)=>(K(e).length=0,G(t.void(),void 0)),"list.slice":e=>{let t=x_(e).type,n=q(e,`start`),r=q(e,`end`);return G(t,K(e).slice(n,r))},"list.concat":e=>{let t=x_(e).type,n=q(e,`other`);return G(t,K(e).concat(n))},"list.reverse":e=>{let t=x_(e).type;return G(t,[...K(e)].reverse())},"list.join":(e,t)=>{let n=q(e,`separator`)??`,`;return G(t.text(),K(e).map(e=>String(e.raw)).join(n))},"list.indexOf":(e,t)=>{let n=S_(e,`value`).raw,r=K(e).findIndex(e=>e.raw===n);return G(t.num(),r)},"list.contains":(e,t)=>{let n=S_(e,`value`).raw,r=K(e);return G(t.bool(),r.some(e=>e.raw===n))},"list.unique":e=>{let t=x_(e).type,n=new Set,r=[];for(let t of K(e))n.has(t.raw)||(n.add(t.raw),r.push(t));return G(t,r)},"list.duplicates":e=>{let t=x_(e).type,n=new Set,r=new Set,i=[];for(let t of K(e))n.has(t.raw)?r.has(t.raw)||(r.add(t.raw),i.push(t)):n.add(t.raw);return G(t,i)},"list.map":async(e,t)=>{let n=K(e),r=S_(e,`fn`).raw,i=M_(e),a=[],o=t.obj({value:{type:i},index:{type:t.num()}});for(let e=0;e<n.length;e++){let i=new W(o,{value:n[e],index:G(t.num(),e)});a.push(await r(i))}return G(t.list(t.any()),a)},"list.filter":async e=>{let t=x_(e).type,n=K(e),r=S_(e,`fn`).raw,i=[],a=t.registry.obj({value:{type:t.item},index:{type:t.registry.num()}});for(let e=0;e<n.length;e++)(await r(new W(a,{value:n[e],index:G(t.registry.num(),e)}))).raw&&i.push(n[e]);return G(t,i)},"list.find":async(e,t)=>{let n=K(e),r=S_(e,`fn`).raw,i=M_(e),a=t.obj({value:{type:i},index:{type:t.num()}});for(let e=0;e<n.length;e++)if((await r(new W(a,{value:n[e],index:G(t.num(),e)}))).raw)return G(t.optional(i),n[e].raw);return G(t.optional(i),void 0)},"list.reduce":async(e,t)=>{let n=K(e),r=S_(e,`fn`),i=S_(e,`initial`),a=r.raw,o=M_(e),s=i,c=t.obj({acc:{type:t.any()},value:{type:o},index:{type:t.num()}});for(let e=0;e<n.length;e++)s=await a(new W(c,{acc:s,value:n[e],index:G(t.num(),e)}));return s},"list.some":async(e,t)=>{let n=K(e),r=S_(e,`fn`).raw,i=M_(e),a=t.obj({value:{type:i},index:{type:t.num()}});for(let e=0;e<n.length;e++)if((await r(new W(a,{value:n[e],index:G(t.num(),e)}))).raw)return G(t.bool(),!0);return G(t.bool(),!1)},"list.every":async(e,t)=>{let n=K(e),r=S_(e,`fn`).raw,i=M_(e),a=t.obj({value:{type:i},index:{type:t.num()}});for(let e=0;e<n.length;e++)if(!(await r(new W(a,{value:n[e],index:G(t.num(),e)}))).raw)return G(t.bool(),!1);return G(t.bool(),!0)},"list.sort":async e=>{let t=x_(e).type,n=[...K(e)],r=S_(e,`fn`);if(r&&typeof r.raw==`function`){let e=r.raw,i=t.registry.obj({a:{type:t.item},b:{type:t.item}}),a=[];for(let t=0;t<n.length;t++){let r=0;for(let a=0;a<n.length;a++)t!==a&&(await e(new W(i,{a:n[t],b:n[a]}))).raw>0&&r++;a.push({index:t,key:r})}return a.sort((e,t)=>e.key-t.key),G(t,a.map(e=>n[e.index]))}return G(t,n.sort((e,t)=>{let n=e.raw,r=t.raw;return n<r?-1:+(n>r)}))},"list.isEmpty":(e,t)=>G(t.bool(),K(e).length===0),"list.isNotEmpty":(e,t)=>G(t.bool(),K(e).length>0),"list.first":(e,t)=>{let n=K(e);return G(t.optional(M_(e)),n.length>0?n[0].raw:void 0)},"list.last":(e,t)=>{let n=K(e);return G(t.optional(M_(e)),n.length>0?n[n.length-1].raw:void 0)}},P_={"list.indexSet":B.STATE,"list.push":B.STATE,"list.pop":B.STATE,"list.shift":B.STATE,"list.unshift":B.STATE,"list.insert":B.STATE,"list.remove":B.STATE,"list.clear":B.STATE},F_=e=>x_(e).type.value,I_={"map.size":(e,t)=>G(t.num({whole:!0,min:0}),K(e).size),"map.indexGet":e=>{let t=e.get(`key`).raw,n=K(e).get(t);if(!n)throw Error(`map[${String(t)}]: key not found`);return n[1]},"map.indexSet":(e,t)=>{let n=e.get(`key`),r=e.get(`value`);return K(e).set(n.raw,[n,r]),G(t.void(),void 0)},"map.iterate":async(e,t)=>{let n=K(e),r=n.values().next().value,i=T_(e,t,r?r[0].type:t.any(),r?r[1].type:t.any());for(let[,[e,t]]of n)await i(e,t);return G(t.void(),void 0)},"map.at":(e,t)=>{let n=q(e,`key`),r=K(e).get(n);return G(t.optional(F_(e)),r?r[1].raw:void 0)},"map.has":(e,t)=>G(t.bool(),K(e).has(q(e,`key`))),"map.delete":(e,t)=>G(t.bool(),K(e).delete(q(e,`key`))),"map.clear":(e,t)=>(K(e).clear(),G(t.void(),void 0)),"map.keys":(e,t)=>{let n=K(e),r=x_(e).type.key,i=[];for(let[,[e]]of n)i.push(e);return G(t.list(r),i)},"map.values":(e,t)=>{let n=K(e),r=x_(e).type.value,i=[];for(let[,[,e]]of n)i.push(e);return G(t.list(r),i)},"map.isEmpty":(e,t)=>G(t.bool(),K(e).size===0),"map.isNotEmpty":(e,t)=>G(t.bool(),K(e).size>0)},L_={"map.indexSet":B.STATE,"map.delete":B.STATE,"map.clear":B.STATE},R_=e=>x_(e).type.elements,z_={"tuple.at":e=>{let t=e.get(`key`).raw,n=K(e)[t];return n instanceof W?n:G(R_(e)[t]??G.prototype,n)},"tuple.setAt":(e,t)=>{let n=e.get(`key`).raw,r=e.get(`value`);return K(e)[n]=r,G(t.void(),void 0)},"tuple.iterate":async(e,t)=>{let n=K(e),r=t.num({whole:!0,min:0}),i=n.map(e=>e.type),a=T_(e,t,r,i.length===0?t.any():i.length===1?i[0]:t.or(i));for(let e=0;e<n.length;e++)await a(G(r,e),n[e]);return G(t.void(),void 0)},"tuple.length":(e,t)=>G(t.num({whole:!0}),K(e).length),"tuple.first":e=>{let t=K(e),n=R_(e),r=t[0];return r instanceof W?r:G(n[0],r)},"tuple.last":e=>{let t=K(e),n=R_(e),r=t[t.length-1];return r instanceof W?r:G(n[n.length-1],r)},"tuple.toList":(e,t)=>G(t.list(t.any()),[...K(e)])},B_={"tuple.setAt":B.STATE},V_=e=>x_(e).type.fields,H_={"object.indexGet":e=>{let t=e.get(`key`).raw,n=V_(e)[t];if(!n)throw Error(`object[${t}]: no such field`);let r=K(e)[t];return r instanceof W?r:G(n.type,r)},"object.indexSet":(e,t)=>{let n=e.get(`key`).raw,r=e.get(`value`);return K(e)[n]=r,G(t.void(),void 0)},"object.iterate":async(e,t)=>{let n=K(e),r=V_(e),i=t.text(),a=Object.values(r).map(e=>e.type),o=T_(e,t,i,a.length===0?t.any():a.length===1?a[0]:t.or(a));for(let[e]of Object.entries(r)){let t=n[e];t instanceof W&&await o(G(i,e),t)}return G(t.void(),void 0)},"object.keys":(e,t)=>{let n=Object.keys(V_(e));return G(t.list(t.text()),n.map(e=>G(t.text(),e)))},"object.values":(e,t)=>{let n=K(e),r=Object.keys(V_(e)).map(e=>n[e]??G(t.any(),void 0));return G(t.list(t.any()),r)},"object.entries":(e,t)=>{let n=K(e),r=Object.keys(V_(e)).map(e=>G(t.any(),[e,n[e]?.raw]));return G(t.list(t.any()),r)},"object.has":(e,t)=>G(t.bool(),Object.hasOwn(V_(e),q(e,`key`))),"object.eq":(e,t)=>G(t.bool(),W_(x_(e),e.get(`args`).raw)),"object.neq":(e,t)=>G(t.bool(),!W_(x_(e),e.get(`args`).raw)),"object.toText":(e,t)=>{let n=K(e),r=V_(e),i={};for(let[e]of Object.entries(r)){let t=n[e];i[e]=t?t.type.encode(t.raw):void 0}return G(t.text(),JSON.stringify(i))}},U_={"object.indexSet":B.STATE};function W_(e,t){let n=t.other,r=n instanceof W?n.raw:n;return G_(e.raw,r)}function G_(e,t){if(e instanceof W&&(e=e.raw),t instanceof W&&(t=t.raw),e===t)return!0;if(typeof e!=`object`||typeof t!=`object`||e===null||t===null||Array.isArray(e)!==Array.isArray(t))return!1;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!G_(e[n],t[n]))return!1;return!0}let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let r of n)if(!G_(e[r],t[r]))return!1;return!0}var K_={"optional.value":e=>{let t=K(e);if(t===void 0)throw Error(`optional.value: value is undefined`);return G(x_(e).type.inner,t)},"optional.has":(e,t)=>G(t.bool(),K(e)!==void 0),"optional.or":e=>{let t=K(e),n=x_(e).type.inner;return t===void 0?S_(e,`fallback`)??G(n,q(e,`fallback`)):G(n,t)},"optional.map":async(e,t)=>{let n=K(e),r=x_(e).type.inner;if(n===void 0)return G(t.optional(t.any()),void 0);let i=S_(e,`fn`).raw,a=await i(new W(t.obj({value:{type:r}}),{value:G(r,n)}));return G(t.optional(t.any()),a.raw)}},q_={"nullable.value":e=>{let t=K(e);if(t===null)throw Error(`nullable.value: value is null`);return G(x_(e).type.inner,t)},"nullable.isNull":(e,t)=>G(t.bool(),K(e)===null),"nullable.or":e=>{let t=K(e),n=x_(e).type.inner;return t===null?S_(e,`fallback`)??G(n,q(e,`fallback`)):G(n,t)},"nullable.map":async(e,t)=>{let n=K(e),r=x_(e).type.inner;if(n===null)return G(t.nullable(t.any()),null);let i=S_(e,`fn`).raw,a=await i(new W(t.obj({value:{type:r}}),{value:G(r,n)}));return G(t.nullable(t.any()),a.raw)}},J_={"not.typeOf":(e,t)=>G(t.text(),x_(e).type.name),"not.toText":(e,t)=>G(t.text(),String(K(e)))},Y_={"enum.name":(e,t)=>{let n=K(e),r=x_(e).type,i=Object.entries(r.options.values).find(([,e])=>e===n);return G(t.text(),i?i[0]:``)},"enum.value":e=>{let t=x_(e).type;return G(t.value,K(e))},"enum.eq":(e,t)=>G(t.bool(),K(e)===q(e,`other`)),"enum.neq":(e,t)=>G(t.bool(),K(e)!==q(e,`other`)),"enum.toText":(e,t)=>G(t.text(),String(K(e)))},X_={"date.year":(e,t)=>G(t.num({whole:!0}),K(e).getUTCFullYear()),"date.month":(e,t)=>G(t.num({whole:!0,min:1,max:12}),K(e).getUTCMonth()+1),"date.day":(e,t)=>G(t.num({whole:!0,min:1,max:31}),K(e).getUTCDate()),"date.dayOfWeek":(e,t)=>G(t.num({whole:!0,min:0,max:6}),K(e).getUTCDay()),"date.dayOfYear":(e,t)=>{let n=K(e),r=Date.UTC(n.getUTCFullYear(),0,0);return G(t.num({whole:!0,min:1,max:366}),Math.floor((n.getTime()-r)/864e5))},"date.eq":(e,t)=>G(t.bool(),K(e).getTime()===q(e,`other`).getTime()),"date.neq":(e,t)=>G(t.bool(),K(e).getTime()!==q(e,`other`).getTime()),"date.before":(e,t)=>G(t.bool(),K(e)<q(e,`other`)),"date.after":(e,t)=>G(t.bool(),K(e)>q(e,`other`)),"date.addDays":(e,t)=>{let n=new Date(K(e));return n.setUTCDate(n.getUTCDate()+q(e,`days`)),G(t.date(),n)},"date.addMonths":(e,t)=>{let n=new Date(K(e));return n.setUTCMonth(n.getUTCMonth()+q(e,`months`)),G(t.date(),n)},"date.addYears":(e,t)=>{let n=new Date(K(e));return n.setUTCFullYear(n.getUTCFullYear()+q(e,`years`)),G(t.date(),n)},"date.diffDays":(e,t)=>G(t.num({whole:!0}),Math.round((K(e).getTime()-q(e,`other`).getTime())/864e5)),"date.diffMonths":(e,t)=>{let n=K(e),r=q(e,`other`);return G(t.num({whole:!0}),(n.getUTCFullYear()-r.getUTCFullYear())*12+(n.getUTCMonth()-r.getUTCMonth()))},"date.diffYears":(e,t)=>G(t.num({whole:!0}),K(e).getUTCFullYear()-q(e,`other`).getUTCFullYear()),"date.toText":(e,t)=>G(t.text(),K(e).toISOString().slice(0,10))},Z_={"timestamp.year":(e,t)=>G(t.num({whole:!0}),K(e).getUTCFullYear()),"timestamp.month":(e,t)=>G(t.num({whole:!0}),K(e).getUTCMonth()+1),"timestamp.day":(e,t)=>G(t.num({whole:!0}),K(e).getUTCDate()),"timestamp.hour":(e,t)=>G(t.num({whole:!0,min:0,max:23}),K(e).getUTCHours()),"timestamp.minute":(e,t)=>G(t.num({whole:!0,min:0,max:59}),K(e).getUTCMinutes()),"timestamp.second":(e,t)=>G(t.num({whole:!0,min:0,max:59}),K(e).getUTCSeconds()),"timestamp.millisecond":(e,t)=>G(t.num({whole:!0,min:0,max:999}),K(e).getUTCMilliseconds()),"timestamp.eq":(e,t)=>G(t.bool(),K(e).getTime()===q(e,`other`).getTime()),"timestamp.before":(e,t)=>G(t.bool(),K(e)<q(e,`other`)),"timestamp.after":(e,t)=>G(t.bool(),K(e)>q(e,`other`)),"timestamp.addDuration":(e,t)=>G(t.timestamp(),new Date(K(e).getTime()+q(e,`duration`))),"timestamp.subDuration":(e,t)=>G(t.timestamp(),new Date(K(e).getTime()-q(e,`duration`))),"timestamp.diff":(e,t)=>G(t.duration(),K(e).getTime()-q(e,`other`).getTime()),"timestamp.toDate":(e,t)=>G(t.date(),new Date(K(e).toISOString().slice(0,10))),"timestamp.toEpoch":(e,t)=>G(t.num(),K(e).getTime()),"timestamp.toText":(e,t)=>G(t.text(),K(e).toISOString())},Q_=864e5,$_=36e5,ev=6e4,tv=1e3,nv={"duration.init":(e,t)=>{let n=q(e,`days`)??0,r=q(e,`hours`)??0,i=q(e,`minutes`)??0,a=q(e,`seconds`)??0,o=q(e,`ms`)??0;return G(t.duration(),n*Q_+r*$_+i*ev+a*tv+o)},"duration.totalSeconds":(e,t)=>G(t.num(),K(e)/1e3),"duration.totalMinutes":(e,t)=>G(t.num(),K(e)/6e4),"duration.totalHours":(e,t)=>G(t.num(),K(e)/36e5),"duration.totalDays":(e,t)=>G(t.num(),K(e)/864e5),"duration.days":(e,t)=>G(t.num({whole:!0}),Math.trunc(K(e)/Q_)),"duration.hours":(e,t)=>G(t.num({whole:!0}),Math.trunc(K(e)/$_)%24),"duration.minutes":(e,t)=>G(t.num({whole:!0}),Math.trunc(K(e)/ev)%60),"duration.seconds":(e,t)=>G(t.num({whole:!0}),Math.trunc(K(e)/tv)%60),"duration.ms":(e,t)=>G(t.num({whole:!0}),K(e)%tv),"duration.toText":(e,t)=>{let n=K(e),r=Math.trunc(n/Q_),i=Math.trunc(n%Q_/$_),a=Math.trunc(n%$_/ev),o=Math.trunc(n%ev/tv),s=[];return r&&s.push(`${r}d`),i&&s.push(`${i}h`),a&&s.push(`${a}m`),(o||s.length===0)&&s.push(`${o}s`),G(t.text(),s.join(` `))}},rv=e=>e>>>24&255,iv=e=>e>>>16&255,av=e=>e>>>8&255,ov=e=>(e&255)/255,sv=(e,t,n,r)=>(Math.round(e)&255)<<24|(Math.round(t)&255)<<16|(Math.round(n)&255)<<8|Math.round(r*255)&255,cv={"color.init":(e,t)=>{let n=q(e,`r`),r=q(e,`g`),i=q(e,`b`),a=q(e,`a`)??1;return G(t.color(),sv(n,r,i,a)>>>0)},"color.r":(e,t)=>G(t.num(),rv(K(e))),"color.g":(e,t)=>G(t.num(),iv(K(e))),"color.b":(e,t)=>G(t.num(),av(K(e))),"color.a":(e,t)=>G(t.num(),ov(K(e))),"color.hue":(e,t)=>G(t.num(),lv(K(e)).h),"color.saturation":(e,t)=>G(t.num(),lv(K(e)).s),"color.lightness":(e,t)=>G(t.num(),lv(K(e)).l),"color.eq":(e,t)=>G(t.bool(),K(e)===q(e,`other`)),"color.neq":(e,t)=>G(t.bool(),K(e)!==q(e,`other`)),"color.lighten":(e,t)=>G(t.color(),dv(K(e),q(e,`amount`))),"color.darken":(e,t)=>G(t.color(),dv(K(e),-q(e,`amount`))),"color.saturate":(e,t)=>G(t.color(),fv(K(e),q(e,`amount`))),"color.desaturate":(e,t)=>G(t.color(),fv(K(e),-q(e,`amount`))),"color.opacity":(e,t)=>G(t.color(),K(e)&4294967040|Math.round(q(e,`alpha`)*255)&255),"color.invert":(e,t)=>{let n=K(e);return G(t.color(),sv(255-rv(n),255-iv(n),255-av(n),ov(n))>>>0)},"color.mix":(e,t)=>{let n=K(e),r=q(e,`other`),i=q(e,`weight`)??.5;return G(t.color(),sv(rv(n)*(1-i)+rv(r)*i,iv(n)*(1-i)+iv(r)*i,av(n)*(1-i)+av(r)*i,ov(n)*(1-i)+ov(r)*i)>>>0)},"color.complement":(e,t)=>G(t.color(),pv(K(e),180)),"color.toHex":(e,t)=>G(t.text(),`#`+K(e).toString(16).padStart(8,`0`)),"color.toRgb":(e,t)=>{let n=K(e);return G(t.text(),`rgb(${rv(n)},${iv(n)},${av(n)})`)},"color.toHsl":(e,t)=>{let{h:n,s:r,l:i}=lv(K(e));return G(t.text(),`hsl(${Math.round(n)},${Math.round(r*100)}%,${Math.round(i*100)}%)`)},"color.toText":(e,t)=>G(t.text(),`#`+K(e).toString(16).padStart(8,`0`))};function lv(e){let t=rv(e)/255,n=iv(e)/255,r=av(e)/255,i=Math.max(t,n,r),a=Math.min(t,n,r),o=(i+a)/2,s=0,c=0;if(i!==a){let e=i-a;switch(c=o>.5?e/(2-i-a):e/(i+a),i){case t:s=(n-r)/e+(n<r?6:0);break;case n:s=(r-t)/e+2;break;case r:s=(t-n)/e+4}s*=60}return{h:s,s:c,l:o}}function uv(e,t,n,r){let i=(1-Math.abs(2*n-1))*t,a=i*(1-Math.abs(e/60%2-1)),o=n-i/2,s=0,c=0,l=0;return e<60?[s,c,l]=[i,a,0]:e<120?[s,c,l]=[a,i,0]:e<180?[s,c,l]=[0,i,a]:e<240?[s,c,l]=[0,a,i]:e<300?[s,c,l]=[a,0,i]:[s,c,l]=[i,0,a],sv((s+o)*255,(c+o)*255,(l+o)*255,r)}function dv(e,t){let{h:n,s:r,l:i}=lv(e);return uv(n,r,Math.max(0,Math.min(1,i+t)),ov(e))>>>0}function fv(e,t){let{h:n,s:r,l:i}=lv(e);return uv(n,Math.max(0,Math.min(1,r+t)),i,ov(e))>>>0}function pv(e,t){let{h:n,s:r,l:i}=lv(e);return uv((n+t+360)%360,r,i,ov(e))>>>0}function mv(e){let t=[{impls:E_},{impls:D_},{impls:O_},{impls:k_},{impls:A_},{impls:j_},{impls:N_,effects:P_},{impls:I_,effects:L_},{impls:z_,effects:B_},{impls:H_,effects:U_},{impls:K_},{impls:q_},{impls:J_},{impls:Y_},{impls:X_},{impls:Z_},{impls:nv},{impls:cv}];for(let n of t)for(let[t,r]of Object.entries(n.impls)){let i=n.effects?.[t]??B.NONE;e.setNative(t,r,i)}return e}var hv=class e extends wh{constructor(e,t){super(),this.type=e,this.value=t}type;value;static KIND=`new`;kind=e.KIND;static from(t,n){return new e(n.registry.parse(t.type,n),t.value).withComment(t.comment)}async evaluate(e,t){let n=this.type,r=n.init();if(this.value!==void 0){if(r){let i=r.args.parse(this.value),a=G(n,n.create()),o=t.child({this:a,args:i}),s=await r.run.evaluate(e,o);return s===void 0||s.raw===void 0?a:new W(n,s.raw)}let i=await n.newFill(this.value,e,t);if(i instanceof W)return e.registry.parseValue(i,n);let a=n.parse(i);return a.type===n?a:new W(n,a.raw)}return G(n,n.create())}typeOf(e,t){return this.type}validateWalk(e,t,n,r){return this.value===void 0&&yv(this.type)&&n.warn(`new.value.missing`,`\`new ${this.type.name}\` has no \`value\` \u2014 every field will fall to its type default (0 / "" / null). Provide a \`value\` matching the type's shape.`),this.value!==void 0&&n.at([`value`],()=>this.type.validateNewValue(this.value,e,t,n,r)),this.type}toCode(e,t={}){let n=this.type.toCode(void 0,t),r;return r=this.value===void 0?this.type.isOptional()?`undefined`:`new ${n}()`:typeof this.value==`number`||typeof this.value==`boolean`?String(this.value):typeof this.value==`string`?JSON.stringify(this.value):this.value===null?`null`:gv(this.value,e,this.type,t),this.commentPrefix(t)+r}toJSON(){return this.withCommentOn({kind:`new`,type:this.type.toJSON(),value:this.value})}toJSONCode(e=[],t=2,n=0){let r=this.type.toJSONCode([...e,`type`],t,n+1),i=this.value===void 0?void 0:(()=>{let e=JSON.stringify(this.value,null,t),r=n+1;return r>0?e.replace(/\n/g,`
|
|
105
|
+
`+` `.repeat(r*t)):e})(),a=i===void 0?void 0:oh(i,{path:[...e,`value`]});return V.jsonObject([{key:`kind`,value:V.jsonString(`new`)},{key:`type`,value:r},{key:`value`,value:a},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}clone(){return new e(this.type.clone(),this.value).withComment(this.comment)}effects(){return this.type.newEffects(this.value)}complexity(){return this.type.newComplexity(this.value)}};function gv(e,t,n,r={}){if(t&&e&&typeof e==`object`&&!Array.isArray(e)&&`kind`in e&&typeof e.kind==`string`){let n=e.kind;if(t.exprClass(n))try{return t.parseExpr(e).toCode(t,{...r,expectsValue:!0})}catch{}}let i=n?n.toCode(void 0,r):`<inferred>`;if(Array.isArray(e)){let i=n?.item,a=dg(e.map(e=>_v(e,t,i,r)));return a.startsWith(`
|
|
106
|
+
`),`[${a}]`}if(e&&typeof e==`object`){let a=n?.fields,o=Object.entries(e);if(o.length===0)return`new ${i}()`;let s=dg(o.map(([e,n])=>`${e}: ${_v(n,t,a?.[e]?.type,r)}`));return s.startsWith(`
|
|
107
|
+
`)?`new ${i} {${s}}`:`new ${i} { ${s} }`}return JSON.stringify(e)}function _v(e,t,n,r={}){return e===null?`null`:e===void 0?`undefined`:typeof e==`string`?JSON.stringify(e):typeof e==`number`||typeof e==`boolean`?String(e):gv(e,t,n,r)}function vv(e){if(e instanceof Ug)return e;let t=e.base;return t?vv(t):void 0}function yv(e){let t=vv(e);if(!t)return!1;for(let e of Object.values(t.fields))if(!e.type.isOptional())return!0;return!1}function bv(e,t){let n=e.call(t);if(!n)return!1;let r=n.args;if(!(r instanceof Ug))return!0;for(let e of Object.values(r.fields))if(!e.type.isOptional())return!1;return!0}function xv(e,t,n,r){if(!e)return;let i=e.args;if(i instanceof Ug)for(let[e,a]of Object.entries(i.fields))a.type.isOptional()||e in t||n.at(r,()=>n.error(`call.missing-arg`,`missing required argument '${e}'`))}function Sv(e,t){return t.type instanceof qg?t.type.simplify(e.scope):t.type}function Cv(e,t){let n=e.raw;if(!n||typeof n!=`object`)return;let r=n[t];return r instanceof W?r:void 0}function wv(e){return e instanceof Ug||e instanceof n_||e instanceof Vg&&wv(e.base)}function Tv(e,t,n){let r=[];for(let e=n;e<t.length;e++){let n=t[e];if(n instanceof Dv)r.push(n.prop);else break}if(r.length===0)return``;let i=cm(e,e=>Object.keys(e.props()),e=>{let t=[];for(let n of Object.keys(e.props())){let r=e.prop(n)?.type;r&&wv(r)&&t.push([n,r])}return t},r);if(!i||i.length===0)return``;if(i.length===1)return` \u2014 did you mean \`${i[0]}\`?`;let a=[];for(let e=0;e<n;e++){let n=t[e];if(n instanceof Dv)a.push(n.prop);else{a.length=0;break}}return` \u2014 did you mean \`${[...a,...i].join(`.`)}\`?`}var Ev=class{static from(e,t){if(vm(e),`prop`in e)return new Dv(e.prop);let n=t.registry;if(`args`in e){let r={};for(let[i,a]of Object.entries(e.args??{}))r[i]=n.parseExpr(a,t);return new Ov(r,e.generic,e.catch?n.parseExpr(e.catch,t):void 0)}if(`key`in e)return new kv(n.parseExpr(e.key,t));throw Error(`PathStep.from: unknown step shape`)}},Dv=class e extends Ev{constructor(e){super(),this.prop=e}prop;toJSON(){return{prop:this.prop}}clone(){return new e(this.prop)}complexity(){return 1}},Ov=class e extends Ev{constructor(e,t,n){super(),this.args=e,this.generic=t,this.catch_=n}args;generic;catch_;resolvedEffects;toJSON(){let e={};for(let[t,n]of Object.entries(this.args))e[t]=n.toJSON();let t={args:e};return this.generic&&(t.generic=this.generic),this.catch_&&(t.catch=this.catch_.toJSON()),t}clone(){let t={};for(let[e,n]of Object.entries(this.args))t[e]=n.clone();return new e(t,this.generic,this.catch_?.clone())}callSiteScope(e){if(!this.generic||Object.keys(this.generic).length===0)return e.scope;let t={},n=e.generic??{};for(let[r,i]of Object.entries(this.generic)){let a=e.scope.parse(i),o=n[r];if(o&&(o.name!==`alias`||o.options?.name!==r)&&!o.compatible(a))throw Error(`path: generic '${r}' binding '${a.toCode()}' does not satisfy constraint '${o.toCode()}'`);t[r]=a}return new Ch(e.scope,t)}complexity(){let e=1;for(let t of Object.values(this.args))e+=t.complexity();return this.catch_&&(e+=this.catch_.complexity()),e}async buildArgsValue(e,t,n){let r=this.callSiteScope(e),i=e.call?.(r)?.args??n.registry.obj({}),a={};for(let[e,r]of Object.entries(this.args))a[e]=await r.evaluate(n,t);return new W(i,a)}},kv=class e extends Ev{constructor(e){super(),this.key=e}key;toJSON(){return{key:this.key.toJSON()}}clone(){return new e(this.key.clone())}complexity(){return 1+this.key.complexity()}},Av=class e{constructor(e){this.steps=e}steps;static from(t,n){return new e(t.map(e=>Ev.from(e,n)))}toJSON(){return this.steps.map(e=>e.toJSON())}toJSONCode(e=[],t=2,n=0){let r=this.steps.map((r,i)=>Mv(r,[...e,i],t,n+1));return V.jsonArray(r,{path:e},n,t)}clone(){return new e(this.steps.map(e=>e.clone()))}complexity(){let e=0;for(let t of this.steps)e+=t.complexity();return e}forEachExpr(e){for(let t of this.steps)if(t instanceof Ov){for(let n of Object.values(t.args))e(n);t.catch_&&e(t.catch_)}else t instanceof kv&&e(t.key)}toCode(e,t={}){return this.toGinCode(e,t).toString()}toGinCode(e,t={},n=[]){if(this.steps.length===0)return new V(``);let r=new V(``);for(let i=0;i<this.steps.length;i++){let a=this.steps[i],o=[...n,`path`,i];if(a instanceof Dv){let e=i===0?a.prop:`.${a.prop}`;r=i===0?oh(e,{path:o}):H`${r}${oh(e,{path:o})}`}else if(a instanceof Ov){let n=Object.entries(a.args),i;if(n.length===0)i=new V(`()`);else{let r=n.map(([n,r])=>{let i=[...o,`args`,n];return H`${n}: ${r.toGinCode(e,{...t,expectsValue:!0},i)}`});i=dg(r.map(e=>e.toString())).startsWith(`
|
|
108
|
+
`)?H`({\n ${sh(r,`,
|
|
109
|
+
`)}\n})`:H`({ ${sh(r,`, `)} })`}if(r=H`${r}${oh(i,{path:o})}`,a.catch_){let n=a.catch_.toGinCode(e,{...t,expectsValue:!0},[...o,`catch`]);r=H`${r}.catch((error) => ${n})`}}else if(a instanceof kv){let n=a.key.toGinCode(e,{...t,expectsValue:!0},[...o,`key`]);r=H`${r}${oh(H`[${n}]`,{path:o})}`}}return r}async walk(e,t,n={mode:`get`}){if(this.steps.length===0)throw Error(`Path.walk: empty path`);let r=()=>G(t.registry.bool(),!1),i=()=>G(t.registry.bool(),!0),a=null,o=0;for(;o<this.steps.length;){let s=this.steps[o],c=o===this.steps.length-1;if(n.mode===`set`&&a!==null&&jv(a)&&!(s instanceof Ov))return r();if(s instanceof Dv){if(a===null){let t=e.get(s.prop);if(t===void 0)throw Error(`path: unknown variable '${s.prop}'${am(s.prop,e.names())}`);a=t,o++;continue}let r=a.type.prop(s.prop);if(!r){let e=n.mode===`get`?Cv(a,s.prop):void 0;if(e){a=e,o++;continue}throw Error(`path: no prop '${s.prop}' on type '${a.type.name}'${Tv(a.type,this.steps,o)}`)}let l=Sv(a.type,r),u=this.steps[o+1],d=u instanceof Ov;if(d&&l.call()){let c=await u.buildArgsValue(l,e,t);if(o+1===this.steps.length-1&&n.mode===`set`)return await r.invokeMethodSet(a,s.prop,c,n.setValue,e,t,l),i();try{a=await r.invokeMethod(a,s.prop,c,e,t,l)}catch(n){if(n instanceof Rh&&u.catch_){let r=e.child({error:n.error});a=await u.catch_.evaluate(t,r)}else throw n}o+=2;continue}if(!d&&bv(l)){let u=await new Ov({},void 0,void 0).buildArgsValue(l,e,t);if(c&&n.mode===`set`)return await r.invokeMethodSet(a,s.prop,u,n.setValue,e,t,l),i();a=await r.invokeMethod(a,s.prop,u,e,t,l),o++;continue}if(c&&n.mode===`set`)return await r.write(a,s.prop,n.setValue,e,t),i();a=await r.read(a,s.prop,e,t,l),o++}else if(s instanceof kv){if(a===null)throw Error(`path: [key] cannot be the first step`);let r=a.type.get();if(!r)throw Error(`path: type '${a.type.name}' has no indexed access`);let l=await s.key.evaluate(t,e);if(c&&n.mode===`set`)return await r.indexWrite(a,l,n.setValue,e,t),i();a=await r.indexRead(a,l,e,t),o++}else if(s instanceof Ov){if(a===null)throw Error(`path: (args) cannot be the first step`);let r=a.raw,l=a.type,u=l.call(),d=await s.buildArgsValue(l,e,t);if(c&&n.mode===`set`){if(!u?.set)throw Error(`path: call on type '${l.name}' has no call.set`);let r=u.set,a=async i=>{let o=new W(l,a);return await r.evaluate(t,e.child({args:i,value:n.setValue,recurse:o})),G(t.registry.void(),void 0)};return await a(d),i()}try{if(typeof r==`function`)a=await r(d);else if(u?.get){let n=u.get,r=async i=>{let a=new W(l,r);try{return await n.evaluate(t,e.child({args:i,recurse:a}))}catch(e){if(e instanceof Ih)return e.value??G(t.registry.void(),void 0);throw e}};a=await r(d)}else throw Error(`path: value of type '${l.name}' is not callable`)}catch(n){if(n instanceof Rh&&s.catch_){let r=e.child({error:n.error});a=await s.catch_.evaluate(t,r)}else throw n}o++}else throw Error(`path: unknown step at index ${o}`)}return a}typeOf(e,t){if(this.steps.length===0)return e.registry.any();let n=null,r=0;for(;r<this.steps.length;){let i=this.steps[r];if(i instanceof Dv){if(n===null){n=t.get(i.prop)??e.registry.any(),r++;continue}let a=n.prop(i.prop);if(!a)return e.registry.any();let o=Sv(n,a),s=this.steps[r+1];if(s instanceof Ov&&o.call()){let t=s.callSiteScope(o),i=o.call(t)?.returns;n=i?.simplify(t)??i??e.registry.any(),r+=2;continue}if(!(s instanceof Ov)&&bv(o)){n=o.call()?.returns??e.registry.any(),r++;continue}n=o,r++}else if(i instanceof kv)n=n?.get()?.value??e.registry.any(),r++;else if(i instanceof Ov){if(n){let t=i.callSiteScope(n),r=n.call(t)?.returns;n=r?.simplify(t)??r??e.registry.any()}else n=e.registry.any();r++}else r++}return n??e.registry.any()}validateWalk(e,t,n,r,i=`get`){if(this.steps.length===0)return n.error(`path.empty`,`path is empty`),e.registry.any();if(i===`set`&&this.steps.length===1&&this.steps[0]instanceof Dv)return e.registry.any();let a=null,o=0;for(;o<this.steps.length;){let s=this.steps[o],c=o===this.steps.length-1;if(s instanceof Dv){if(a===null){let r=t.get(s.prop);r?a=r:(n.at([`path`,o],()=>n.error(`var.unknown`,`unknown variable '${s.prop}'${am(s.prop,[...t.keys()])}`)),a=e.registry.any()),o++;continue}let l=a.prop(s.prop);if(!l){n.at([`path`,o],()=>n.error(`prop.unknown`,`no prop '${s.prop}' on type '${a.name}'${Tv(a,this.steps,o)}`)),a=e.registry.any(),o++;continue}let u=Sv(a,l),d=this.steps[o+1];if(d instanceof Ov&&u.call()){for(let[i,a]of Object.entries(d.args))n.at([`path`,o+1,`args`,i],()=>a.validateWalk(e,t,n,r));d.catch_&&n.at([`path`,o+1,`catch`],()=>d.catch_.validateWalk(e,t,n,r));let c=d.callSiteScope(u),l=u.call(c);xv(l,d.args,n,[`path`,o+1]),i===`set`&&o+1===this.steps.length-1&&(l?.set||n.at([`path`,o+1],()=>n.error(`set.call.no-set`,`method '${s.prop}' has no call.set`))),d.resolvedEffects=l?.effects()??0;let f=l?.returns;a=f?.simplify(c)??f??e.registry.any(),o+=2;continue}if(!(d instanceof Ov)&&bv(u)){a=u.call()?.returns??e.registry.any(),o++;continue}i===`set`&&c&&!l.set&&l.get&&!u.call()&&n.at([`path`,o],()=>n.error(`set.prop.computed`,`prop '${s.prop}' is computed (read-only); cannot assign to it`));let f=i===`get`?u.call():void 0;if(f&&!bv(u)){n.at([`path`,o],()=>n.error(`call.uncalled`,`method '${s.prop}' needs arguments \u2014 add an {args:{\u2026}} step to call it`)),a=f.returns??e.registry.any(),o++;continue}a=u,o++}else if(s instanceof kv){n.at([`path`,o,`key`],()=>s.key.validateWalk(e,t,n,r));let l=a?.get();i===`set`&&c?l?.set||n.at([`path`,o],()=>n.error(`set.index.no-set`,`type '${a?.name??`?`}' has no index set`)):l?.get||n.at([`path`,o],()=>n.error(`index.unsupported`,`type '${a?.name??`?`}' has no indexed access`)),a=l?.value??e.registry.any(),o++}else if(s instanceof Ov){for(let[i,a]of Object.entries(s.args))n.at([`path`,o,`args`,i],()=>a.validateWalk(e,t,n,r));if(a){let t=s.callSiteScope(a),r=a.call(t);xv(r,s.args,n,[`path`,o]),i===`set`&&c&&(r?.set||n.at([`path`,o],()=>n.error(`set.call.no-set`,`call on type '${a?.name??`?`}' has no call.set`))),s.resolvedEffects=r?.effects()??0;let l=r?.returns;a=l?.simplify(t)??l??e.registry.any()}else s.resolvedEffects=0,a=e.registry.any();o++}else o++}return a??e.registry.any()}};function jv(e){return e.raw===null||e.raw===void 0}function Mv(e,t,n,r){if(e instanceof Dv)return V.jsonObject([{key:`prop`,value:V.jsonString(e.prop)}],{path:t},r,n);if(e instanceof Ov){let i=Object.entries(e.args).map(([e,i])=>({key:e,value:i.toJSONCode([...t,`args`,e],n,r+2)})),a=[{key:`args`,value:V.jsonObject(i,{path:[...t,`args`]},r+1,n)}];return e.generic&&a.push({key:`generic`,value:JSON.stringify(e.generic,null,n).replace(/\n/g,`
|
|
110
|
+
`+` `.repeat(r*n))}),e.catch_&&a.push({key:`catch`,value:e.catch_.toJSONCode([...t,`catch`],n,r+1)}),V.jsonObject(a,{path:t},r,n)}return e instanceof kv?V.jsonObject([{key:`key`,value:e.key.toJSONCode([...t,`key`],n,r+1)}],{path:t},r,n):new V(JSON.stringify(e.toJSON(),null,n))}var Nv=class e extends wh{constructor(e){super(),this.path=e}path;static KIND=`get`;kind=e.KIND;static from(t,n){return new e(Av.from(t.path,n)).withComment(t.comment)}async evaluate(e,t){return this.path.walk(t,e,{mode:`get`})}typeOf(e,t){return this.path.typeOf(e,t)}validateWalk(e,t,n,r){return this.path.validateWalk(e,t,n,r,`get`)}toGinCode(e,t={},n=[]){let r=this.path.toGinCode(e,t,n);return oh(H`${this.commentPrefix(t)}${r}`,{path:n,expr:this})}toJSON(){return this.withCommentOn({kind:`get`,path:this.path.toJSON()})}toJSONCode(e=[],t=2,n=0){let r=this.path.toJSONCode([...e,`path`],t,n+1);return V.jsonObject([{key:`kind`,value:V.jsonString(`get`)},{key:`path`,value:r},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}clone(){return new e(this.path.clone()).withComment(this.comment)}forEachChild(e){this.path.forEachExpr(t=>e(t,`inherit`))}effects(){let e=[];this.path.forEachExpr(t=>{e.push(t.effects())});for(let t of this.path.steps)t instanceof Ov&&t.resolvedEffects!==void 0&&e.push(t.resolvedEffects);return ah(...e)}complexity(){return this.path.complexity()}},Pv=class e extends wh{constructor(e,t){super(),this.path=e,this.value=t}path;value;static KIND=`set`;kind=e.KIND;useLineComment(e={}){return!e.expectsValue}static from(t,n){return new e(Av.from(t.path,n),n.registry.parseExpr(t.value,n)).withComment(t.comment)}async evaluate(e,t){let n=await this.value.evaluate(e,t);return this.path.steps.length===1&&this.path.steps[0]instanceof Dv?(t.set(this.path.steps[0].prop,n),G(e.registry.bool(),!0)):this.path.walk(t,e,{mode:`set`,setValue:n})}typeOf(e,t){return e.registry.bool()}validateWalk(e,t,n,r){let i=n.at(`value`,()=>this.value.validateWalk(e,t,n,r)),a=this.path.validateWalk(e,t,n,r,`set`);return a.name!==`any`&&!a.compatible(i)&&n.at(`value`,()=>n.warn(`set.type-mismatch`,`value type '${i.name}' not compatible with target '${a.name}'`)),e.registry.bool()}toGinCode(e,t={},n=[]){let r=this.path.toGinCode(e,t,n),i=this.value.toGinCode(e,{...t,expectsValue:!0},[...n,`value`]);return oh(H`${this.commentPrefix(t)}${r} = ${i}`,{path:n,expr:this})}toJSON(){return this.withCommentOn({kind:`set`,path:this.path.toJSON(),value:this.value.toJSON()})}toJSONCode(e=[],t=2,n=0){let r=this.path.toJSONCode([...e,`path`],t,n+1),i=this.value.toJSONCode([...e,`value`],t,n+1);return V.jsonObject([{key:`kind`,value:V.jsonString(`set`)},{key:`path`,value:r},{key:`value`,value:i},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}clone(){return new e(this.path.clone(),this.value.clone()).withComment(this.comment)}forEachChild(e){this.path.forEachExpr(t=>e(t,`inherit`)),e(this.value,`inherit`)}effects(){let e=B.STATE|this.value.effects();this.path.forEachExpr(t=>{e|=t.effects()});for(let t of this.path.steps)t instanceof Ov&&t.resolvedEffects!==void 0&&(e|=t.resolvedEffects);return e}complexity(){return this.path.complexity()+this.value.complexity()}},Fv=class e extends wh{constructor(e,t){super(),this.vars=e,this.body=t}vars;body;static KIND=`define`;kind=e.KIND;useLineComment(e={}){return!e.expectsValue}static from(t,n){let r=n.registry,i=t.vars.map(e=>({name:e.name,type:e.type?r.parse(e.type,n):void 0,value:r.parseExpr(e.value,n)}));return new e(i,r.parseExpr(t.body,n)).withComment(t.comment)}async evaluate(e,t){let n=t.child();for(let t of this.vars){let r=await t.value.evaluate(e,n);n.vars.set(t.name,r)}return this.body.evaluate(e,n)}typeOf(e,t){let n=new Map(t);for(let t of this.vars){let r=t.type??Oh(e,t.value,n);n.set(t.name,r)}return Oh(e,this.body,n)}validateWalk(e,t,n,r){let i=new Map(t);for(let t=0;t<this.vars.length;t++){let a=this.vars[t];n.at([`vars`,t,`name`],()=>Mh(a.name,i,n));let o=n.at([`vars`,t,`value`],()=>jh(e,a.value,i,n,r));if(a.type&&!o.isUniversal()&&!a.type.compatible(o)){let e=Iv(a.type),r=Iv(o),i=o.name===`alias`?` (hint: '${r}' is an unbound generic \u2014 either bind it via \`generic: {${r}: ...}\` on the call site, pass \`output: typ<...>\`, or omit the declared type so the alias flows through)`:``;n.at([`vars`,t,`value`],()=>n.error(`define.var.type-mismatch`,`var '${a.name}' value type '${r}' not compatible with declared '${e}'${i}`))}i.set(a.name,a.type??o)}return n.at(`body`,()=>jh(e,this.body,i,n,r))}toGinCode(e,t={},n=[]){let r=t.expectsValue??!1,i={...t,expectsValue:!0},a={...t,expectsValue:!1},o=this.vars.map((r,a)=>{let o=r.type?H`: ${r.type.toGinCode(void 0,t,[...n,`vars`,a,`type`])}`:``,s=r.value.toGinCode(e,i,[...n,`vars`,a,`value`]),c=H`let ${r.name}${o} = ${s};`;return c.text.split(`
|
|
111
|
+
`,1)[0].length<=80?c:H`let ${r.name}${o} =\n ${s.indent(` `)};`});if(r){let r=this.body.toGinCode(e,i,[...n,`body`]),a=o.map(e=>H` ${e}`),s=H` return ${r.indent(` `)};`,c=ch([...a,s]);return oh(H`${this.commentPrefix(t)}(() => {\n${c}\n})()`,{path:n,expr:this})}let s=this.body.kind,c=this.body.toGinCode(e,a,[...n,`body`]),l=s===`if`||s===`switch`||s===`loop`||s===`block`?c:H`${c};`;return oh(H`${this.commentPrefix(t)}${ch([...o,l])}`,{path:n,expr:this})}toJSON(){return this.withCommentOn({kind:`define`,vars:this.vars.map(e=>{let t={name:e.name,value:e.value.toJSON()};return e.type&&(t.type=e.type.toJSON()),t}),body:this.body.toJSON()})}toJSONCode(e=[],t=2,n=0){let r=this.vars.map((r,i)=>{let a=[...e,`vars`,i],o=r.value.toJSONCode([...a,`value`],t,n+3),s=r.type?r.type.toJSONCode([...a,`type`],t,n+3):void 0;return V.jsonObject([{key:`name`,value:V.jsonString(r.name)},{key:`value`,value:o},{key:`type`,value:s}],{path:a},n+2,t)}),i=this.body.toJSONCode([...e,`body`],t,n+1);return V.jsonObject([{key:`kind`,value:V.jsonString(`define`)},{key:`vars`,value:V.jsonArray(r,{path:[...e,`vars`]},n+1,t)},{key:`body`,value:i},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}clone(){return new e(this.vars.map(e=>({name:e.name,type:e.type?.clone(),value:e.value.clone()})),this.body.clone()).withComment(this.comment)}forEachChild(e){for(let t of this.vars)e(t.value,`inherit`);e(this.body,`inherit`)}effects(){let e=this.body.effects();for(let t of this.vars)e|=t.value.effects();return e}complexity(){let e=1+this.body.complexity();for(let t of this.vars)e+=1+t.value.complexity();return e}};function Iv(e){try{return e.toCode()}catch{return e.name}}var Lv=class e extends wh{constructor(e){super(),this.lines=e}lines;static KIND=`block`;kind=e.KIND;useLineComment(e={}){return!e.expectsValue}static from(t,n){let r=n.registry;return new e(t.lines.map(e=>r.parseExpr(e,n))).withComment(t.comment)}async evaluate(e,t){let n=G(e.registry.void(),void 0);for(let r of this.lines)n=await r.evaluate(e,t);return n}typeOf(e,t){return this.lines.length===0?e.registry.void():Oh(e,this.lines[this.lines.length-1],t)}validateWalk(e,t,n,r){let i=e.registry.void();for(let a=0;a<this.lines.length;a++)i=n.at(a,()=>jh(e,this.lines[a],t,n,r));return i}toGinCode(e,t={},n=[]){let r=t.expectsValue??!1;if(this.lines.length===0)return oh(r?`undefined`:``,{path:n,expr:this});if(this.lines.length===1)return oh(this.lines[0].toGinCode(e,t,[...n,0]),{path:n,expr:this});let i=this.commentPrefix(t);return oh(r?H`${i}(() => {\n${ch(this.lines.map((r,i)=>{let a=i===this.lines.length-1,o=r.toGinCode(e,{...t,expectsValue:a},[...n,i]).indent(` `);return a?H` return ${o};`:H` ${o};`}))}\n})()`:H`${i}${ch(this.lines.map((r,i)=>{let a=r.kind,o=r.toGinCode(e,{...t,expectsValue:!1},[...n,i]);return a===`if`||a===`switch`||a===`loop`||a===`block`?o:H`${o};`}))}`,{path:n,expr:this})}toJSON(){return this.withCommentOn({kind:`block`,lines:this.lines.map(e=>e.toJSON())})}toJSONCode(e=[],t=2,n=0){let r=this.lines.map((r,i)=>r.toJSONCode([...e,i],t,n+2));return V.jsonObject([{key:`kind`,value:V.jsonString(`block`)},{key:`lines`,value:V.jsonArray(r,{path:[...e,`lines`]},n+1,t)},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}clone(){return new e(this.lines.map(e=>e.clone())).withComment(this.comment)}forEachChild(e){for(let t of this.lines)e(t,`inherit`)}effects(){let e=B.NONE;for(let t of this.lines)e|=t.effects();return e}complexity(){let e=1;for(let t of this.lines)e+=t.complexity();return e}},Rv=class e extends wh{constructor(e,t,n){super(),this.action=e,this.value=t,this.error=n}action;value;error;static KIND=`flow`;kind=e.KIND;useLineComment(e={}){return!e.expectsValue}static from(t,n){let r=n.registry;return new e(t.action,t.value?r.parseExpr(t.value,n):void 0,t.error?r.parseExpr(t.error,n):void 0).withComment(t.comment)}async evaluate(e,t){switch(this.action){case`break`:throw new Ph;case`continue`:throw new Fh;case`return`:throw new Ih(this.value?await this.value.evaluate(e,t):void 0);case`exit`:throw new Lh(this.value?await this.value.evaluate(e,t):void 0);case`throw`:throw this.error?new Rh(await this.error.evaluate(e,t)):Error("flow.throw requires `error`")}}typeOf(e,t){return e.registry.void()}validateWalk(e,t,n,r){return this.action!==`break`&&this.action!==`continue`||r.inLoop||n.error(`flow.outside-loop`,`${this.action} used outside a loop`),this.action===`return`&&!r.inLambda&&n.warn(`flow.outside-lambda`,`return used outside a lambda`),this.action===`throw`&&!this.error&&n.error(`flow.throw.no-error`,"throw requires an `error` expression"),this.value&&n.at(`value`,()=>jh(e,this.value,t,n,r)),this.error&&n.at(`error`,()=>jh(e,this.error,t,n,r)),e.registry.void()}toGinCode(e,t={},n=[]){let r=this.commentPrefix(t),i={...t,expectsValue:!0},a;switch(this.action){case`break`:a=new V(`break`);break;case`continue`:a=new V(`continue`);break;case`return`:a=this.value?H`return ${this.value.toGinCode(e,i,[...n,`value`])}`:new V(`return`);break;case`throw`:a=this.error?H`throw ${this.error.toGinCode(e,i,[...n,`error`])}`:new V(`throw`);break;case`exit`:a=this.value?H`exit ${this.value.toGinCode(e,i,[...n,`value`])}`:new V(`exit`);break;default:a=new V(``)}return oh(H`${r}${a}`,{path:n,expr:this})}toJSONCode(e=[],t=2,n=0){let r=this.value?this.value.toJSONCode([...e,`value`],t,n+1):void 0,i=this.error?this.error.toJSONCode([...e,`error`],t,n+1):void 0;return V.jsonObject([{key:`kind`,value:V.jsonString(`flow`)},{key:`action`,value:V.jsonString(this.action)},{key:`value`,value:r},{key:`error`,value:i},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}toJSON(){let e={kind:`flow`,action:this.action};return this.value&&(e.value=this.value.toJSON()),this.error&&(e.error=this.error.toJSON()),this.withCommentOn(e)}clone(){return new e(this.action,this.value?.clone(),this.error?.clone()).withComment(this.comment)}forEachChild(e){this.value&&e(this.value,`inherit`),this.error&&e(this.error,`inherit`)}effects(){return B.STATE|(this.value?.effects()??B.NONE)|(this.error?.effects()??B.NONE)}complexity(){return 1+(this.value?.complexity()??0)+(this.error?.complexity()??0)}};function zv(e){return e.replace(/\n/g,`
|
|
112
|
+
`)}function Bv(e,t=`inherit`){if(e instanceof Rv)return e.action===`throw`||e.action===`exit`?e:e.action===`return`?t===`lambda`?void 0:e:e.action===`break`||e.action===`continue`?t===`loop`?void 0:e:void 0;let n;return e.forEachChild((e,r)=>{if(n)return;let i=Bv(e,r===`inherit`?t:r);i&&(n=i)}),n}var Vv=class e extends wh{constructor(e,t){super(),this.ifs=e,this.otherwise=t}ifs;otherwise;static KIND=`if`;kind=e.KIND;useLineComment(e={}){return!e.expectsValue}static from(t,n){let r=n.registry,i=t.ifs.map(e=>({condition:r.parseExpr(e.condition,n),body:r.parseExpr(e.body,n)}));return new e(i,t.else?r.parseExpr(t.else,n):void 0).withComment(t.comment)}async evaluate(e,t){for(let n of this.ifs)if((await n.condition.evaluate(e,t)).raw)return n.body.evaluate(e,t);return this.otherwise?this.otherwise.evaluate(e,t):G(e.registry.void(),void 0)}typeOf(e,t){let n=this.ifs.map(n=>Oh(e,n.body,t));return this.otherwise&&n.push(Oh(e,this.otherwise,t)),n.length===1?n[0]:e.registry.or(n)}validateWalk(e,t,n,r){let i=e.registry.bool(),a=[];for(let o=0;o<this.ifs.length;o++){let s=this.ifs[o],c=n.at([`ifs`,o,`condition`],()=>jh(e,s.condition,t,n,r));if(!i.compatible(c)){let e;try{e=c.toCode()}catch{e=c.name}n.at([`ifs`,o,`condition`],()=>n.warn(`if.condition.type`,`if condition should be bool, got '${e}' (did you forget to call a method?)`))}a.push(n.at([`ifs`,o,`body`],()=>jh(e,s.body,t,n,r)))}for(let e=0;e<this.ifs.length;e++)this.ifs[e].body.effects()===B.NONE&&n.at([`ifs`,e,`body`],()=>n.warn(`if.branch.no-effect`,"if branch body has no observable effect — when this branch matches, nothing happens. Either give it a `set`/`flow`/native call, or drop the branch entirely"));return this.otherwise&&(a.push(n.at(`else`,()=>jh(e,this.otherwise,t,n,r))),this.otherwise.effects()===B.NONE&&n.at(`else`,()=>n.warn(`if.else.no-effect`,"else arm has no observable effect — `else` is optional; OMIT it entirely when its only purpose is producing a placeholder value"))),a.length===1?a[0]:e.registry.or(a)}toGinCode(e,t={},n=[]){let r=t.expectsValue??!1,i=this.ifs.some(e=>!!Bv(e.body))||(this.otherwise?!!Bv(this.otherwise):!1),a=this.commentPrefix(t),o={...t,expectsValue:!0};if(r&&!i){if(this.ifs.length===1&&this.otherwise){let t=this.ifs[0];return oh(H`${a}(${t.condition.toGinCode(e,o,[...n,`ifs`,0,`condition`])} ? ${t.body.toGinCode(e,o,[...n,`ifs`,0,`body`])} : ${this.otherwise.toGinCode(e,o,[...n,`else`])})`,{path:n,expr:this})}let t=H``;for(let r=0;r<this.ifs.length;r++){let i=this.ifs[r],a=r===0?`if`:`else if`,s=i.condition.toGinCode(e,o,[...n,`ifs`,r,`condition`]),c=i.body.toGinCode(e,o,[...n,`ifs`,r,`body`]);t=H`${t}${r===0?``:`
|
|
113
|
+
`} ${a} (${s}) return ${c.indent(` `)};`}let r=``;return this.otherwise&&(r=H`\n return ${this.otherwise.toGinCode(e,o,[...n,`else`]).indent(` `)};`),oh(H`${a}(() => {\n${t}${r}\n})()`,{path:n,expr:this})}let s=H``;for(let r=0;r<this.ifs.length;r++){let i=this.ifs[r],a=r===0?`if`:`else if`,c=r===0?``:` `,l=i.condition.toGinCode(e,o,[...n,`ifs`,r,`condition`]),u=i.body.renderStatementBodyRich(e,t,[...n,`ifs`,r,`body`]);s=H`${s}${c}${a} (${l}) ${u}`}if(this.otherwise){let r=this.otherwise.renderStatementBodyRich(e,t,[...n,`else`],!0);s=H`${s} else ${r}`}return oh(H`${a}${s}`,{path:n,expr:this})}toJSON(){return this.withCommentOn({kind:`if`,ifs:this.ifs.map(e=>({condition:e.condition.toJSON(),body:e.body.toJSON()})),else:this.otherwise?.toJSON()})}toJSONCode(e=[],t=2,n=0){let r=this.ifs.map((r,i)=>{let a=[...e,`ifs`,i];return V.jsonObject([{key:`condition`,value:r.condition.toJSONCode([...a,`condition`],t,n+3)},{key:`body`,value:r.body.toJSONCode([...a,`body`],t,n+3)}],{path:a},n+2,t)}),i=this.otherwise?this.otherwise.toJSONCode([...e,`else`],t,n+1):void 0;return V.jsonObject([{key:`kind`,value:V.jsonString(`if`)},{key:`ifs`,value:V.jsonArray(r,{path:[...e,`ifs`]},n+1,t)},{key:`else`,value:i},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}clone(){return new e(this.ifs.map(e=>({condition:e.condition.clone(),body:e.body.clone()})),this.otherwise?.clone()).withComment(this.comment)}forEachChild(e){for(let t of this.ifs)e(t.condition,`inherit`),e(t.body,`inherit`);this.otherwise&&e(this.otherwise,`inherit`)}effects(){let e=B.NONE;for(let t of this.ifs)e|=t.condition.effects()|t.body.effects();return this.otherwise&&(e|=this.otherwise.effects()),e}complexity(){let e=1;for(let t of this.ifs)e+=t.condition.complexity()+t.body.complexity();return this.otherwise&&(e+=this.otherwise.complexity()),e}},Hv=class e extends wh{constructor(e,t,n){super(),this.value=e,this.cases=t,this.otherwise=n}value;cases;otherwise;static KIND=`switch`;kind=e.KIND;useLineComment(e={}){return!e.expectsValue}static from(t,n){let r=n.registry;return new e(r.parseExpr(t.value,n),t.cases.map(e=>({equals:e.equals.map(e=>r.parseExpr(e,n)),body:r.parseExpr(e.body,n)})),t.else?r.parseExpr(t.else,n):void 0).withComment(t.comment)}async evaluate(e,t){let n=await this.value.evaluate(e,t);for(let r of this.cases)for(let i of r.equals)if((await i.evaluate(e,t)).raw===n.raw)return r.body.evaluate(e,t);return this.otherwise?this.otherwise.evaluate(e,t):G(e.registry.void(),void 0)}typeOf(e,t){let n=this.cases.map(n=>Oh(e,n.body,t));return this.otherwise&&n.push(Oh(e,this.otherwise,t)),n.length===0?e.registry.void():n.length===1?n[0]:e.registry.or(n)}validateWalk(e,t,n,r){let i=n.at(`value`,()=>jh(e,this.value,t,n,r)),a=[];for(let o=0;o<this.cases.length;o++){let s=this.cases[o];for(let a=0;a<s.equals.length;a++){let c=n.at([`cases`,o,`equals`,a],()=>jh(e,s.equals[a],t,n,r));i.compatible(c)||n.at([`cases`,o,`equals`,a],()=>n.warn(`switch.case.type`,`case value type '${c.name}' not compatible with switch value '${i.name}'`))}a.push(n.at([`cases`,o,`body`],()=>jh(e,s.body,t,n,r))),s.body.effects()===B.NONE&&n.at([`cases`,o,`body`],()=>n.warn(`switch.case.no-effect`,"switch case body has no observable effect — when this case matches, nothing happens. Either give it a `set`/`flow`/native call, or drop the case"))}return this.otherwise&&(a.push(n.at(`else`,()=>jh(e,this.otherwise,t,n,r))),this.otherwise.effects()===B.NONE&&n.at(`else`,()=>n.warn(`switch.else.no-effect`,`switch default has no observable effect — OMIT it instead of carrying a placeholder fallback`))),a.length===0?e.registry.void():a.length===1?a[0]:e.registry.or(a)}toGinCode(e,t={},n=[]){let r=t.expectsValue??!1,i=this.cases.some(e=>!!Bv(e.body))||(this.otherwise?!!Bv(this.otherwise):!1),a={...t,expectsValue:!0},o=this.value.toGinCode(e,a,[...n,`value`]),s=this.commentPrefix(t);if(r&&!i){let t=ch(this.cases.map((t,r)=>H`${ch(t.equals.map((t,i)=>H` case ${t.toGinCode(e,a,[...n,`cases`,r,`equals`,i])}:`))}\n return ${t.body.toGinCode(e,a,[...n,`cases`,r,`body`]).indent(` `)};`)),r=``;return this.otherwise&&(r=H`\n default:\n return ${this.otherwise.toGinCode(e,a,[...n,`else`]).indent(` `)};`),oh(H`${s}(() => {\n switch (${o}) {\n${t}${r}\n }\n})()`,{path:n,expr:this})}let c=(n,r)=>{let i=n.kind;return n instanceof Rv?H`${n.toGinCode(e,{...t,expectsValue:!1},r)};`:i===`block`||i===`if`||i===`switch`||i===`loop`?n.toGinCode(e,{...t,expectsValue:!1},r):H`${n.toGinCode(e,{...t,expectsValue:!0},r)};`},l=ch(this.cases.map((t,r)=>{let i=ch(t.equals.map((t,i)=>H` case ${t.toGinCode(e,a,[...n,`cases`,r,`equals`,i])}:`)),o=[...n,`cases`,r,`body`];return H`${i}\n ${c(t.body,o).indent(` `)}${t.body instanceof Rv?``:`
|
|
114
|
+
break;`}`})),u=``;return this.otherwise&&(u=H`\n default:\n ${c(this.otherwise,[...n,`else`]).indent(` `)}`),oh(H`${s}switch (${o}) {\n${l}${u}\n}`,{path:n,expr:this})}toJSON(){return this.withCommentOn({kind:`switch`,value:this.value.toJSON(),cases:this.cases.map(e=>({equals:e.equals.map(e=>e.toJSON()),body:e.body.toJSON()})),else:this.otherwise?.toJSON()})}toJSONCode(e=[],t=2,n=0){let r=this.value.toJSONCode([...e,`value`],t,n+1),i=this.cases.map((r,i)=>{let a=[...e,`cases`,i],o=r.equals.map((e,r)=>e.toJSONCode([...a,`equals`,r],t,n+4));return V.jsonObject([{key:`equals`,value:V.jsonArray(o,{path:[...a,`equals`]},n+3,t)},{key:`body`,value:r.body.toJSONCode([...a,`body`],t,n+3)}],{path:a},n+2,t)}),a=this.otherwise?this.otherwise.toJSONCode([...e,`else`],t,n+1):void 0;return V.jsonObject([{key:`kind`,value:V.jsonString(`switch`)},{key:`value`,value:r},{key:`cases`,value:V.jsonArray(i,{path:[...e,`cases`]},n+1,t)},{key:`else`,value:a},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}clone(){return new e(this.value.clone(),this.cases.map(e=>({equals:e.equals.map(e=>e.clone()),body:e.body.clone()})),this.otherwise?.clone()).withComment(this.comment)}forEachChild(e){e(this.value,`inherit`);for(let t of this.cases){for(let n of t.equals)e(n,`inherit`);e(t.body,`inherit`)}this.otherwise&&e(this.otherwise,`inherit`)}effects(){let e=this.value.effects();for(let t of this.cases){for(let n of t.equals)e|=n.effects();e|=t.body.effects()}return this.otherwise&&(e|=this.otherwise.effects()),e}complexity(){let e=1+this.value.complexity();for(let t of this.cases){for(let n of t.equals)e+=n.complexity();e+=t.body.complexity()}return this.otherwise&&(e+=this.otherwise.complexity()),e}},Uv=class e extends wh{constructor(e,t,n,r,i){super(),this.over=e,this.body=t,this.keyName=n,this.valueName=r,this.parallel=i}over;body;keyName;valueName;parallel;static KIND=`loop`;kind=e.KIND;useLineComment(e={}){return!e.expectsValue}static from(t,n){let r=n.registry,i=t.parallel?{concurrent:t.parallel.concurrent?r.parseExpr(t.parallel.concurrent,n):void 0,rate:t.parallel.rate?r.parseExpr(t.parallel.rate,n):void 0}:void 0;return new e(r.parseExpr(t.over,n),r.parseExpr(t.body,n),t.key,t.value,i).withComment(t.comment)}async evaluate(e,t){let n=await this.over.evaluate(e,t),r=n.type.get();if(!(r?.loop||r?.loopDynamic))throw Error(`loop: type '${n.type.name}' has no loop or loopDynamic defined on its GetSet`);let i=this.keyName??`key`,a=this.valueName??`value`,o=this.parallel?.concurrent?Number((await this.parallel.concurrent.evaluate(e,t)).raw):void 0,s=this.parallel?.rate?Number((await this.parallel.rate.evaluate(e,t)).raw):void 0,c=o!==void 0||s!==void 0;if(r.loopDynamic){let r=e.registry.num({whole:!0,min:0});if(!c){let o=n,s=0;for(;o.raw;){await t.checkpoint();let n=t.child({[i]:G(r,s),[a]:o});try{await this.body.evaluate(e,n)}catch(e){if(e instanceof Ph)break;if(!(e instanceof Fh))throw e}s++,o=await this.over.evaluate(e,t)}return G(e.registry.void(),void 0)}let l=new Set,u=o??1/0,d=!1,f=0,p=0,m=async()=>{if(d)return!1;await t.checkpoint();let n=await this.over.evaluate(e,t);if(!n.raw)return!1;if(s&&s>0){let e=Date.now()-f;e<s&&await new Promise(t=>setTimeout(t,s-e)),f=Date.now()}let o=t.child({[i]:G(r,p),[a]:n}),c=(async()=>{try{await this.body.evaluate(e,o)}catch(e){if(e instanceof Fh)return;if(e instanceof Ph){d=!0;return}throw e}})().finally(()=>l.delete(c));return l.add(c),p++,!0},h=Number.isFinite(u)?u:1;for(;l.size<h&&await m(););for(;l.size>0;)for(await Promise.race(l);!d&&l.size<h&&await m(););return G(e.registry.void(),void 0)}let l=r.loop;if(!l)throw Error(`loop: type '${n.type.name}' has no loop ExprDef on its GetSet`);if(!c)return await Wv(l,t,e,n,async(n,r)=>{let o=t.child({[i]:n,[a]:r});try{return await this.body.evaluate(e,o)}catch(t){if(t instanceof Fh)return G(e.registry.void(),void 0);throw t}}),G(e.registry.void(),void 0);let u=new Set,d=o??1/0,f=!1,p=0;return await Wv(r.loop,t,e,n,async(n,r)=>{if(f)return G(e.registry.void(),void 0);if(s&&s>0){let e=Date.now()-p;e<s&&await new Promise(t=>setTimeout(t,s-e)),p=Date.now()}for(;u.size>=d;)await Promise.race(u);let o=t.child({[i]:n,[a]:r}),c=(async()=>{try{await this.body.evaluate(e,o)}catch(e){if(e instanceof Fh)return;if(e instanceof Ph){f=!0;return}throw e}})().finally(()=>u.delete(c));return u.add(c),G(e.registry.void(),void 0)}),await Promise.all(u),G(e.registry.void(),void 0)}typeOf(e,t){return e.registry.void()}validateWalk(e,t,n,r){let i=n.at(`over`,()=>jh(e,this.over,t,n,r)),a=i.get();if(a?.loop||a?.loopDynamic||n.error(`loop.not-iterable`,`type '${i.name}' has no loop defined`),this.parallel?.concurrent){let i=n.at([`parallel`,`concurrent`],()=>jh(e,this.parallel.concurrent,t,n,r));e.registry.num().compatible(i)||n.at([`parallel`,`concurrent`],()=>n.error(`loop.parallel.concurrent.type`,`parallel.concurrent must be a number, got '${i.name}'`))}if(this.parallel?.rate){let i=n.at([`parallel`,`rate`],()=>jh(e,this.parallel.rate,t,n,r)),a=e.registry.num().compatible(i),o=e.registry.duration().compatible(i);!a&&!o&&n.at([`parallel`,`rate`],()=>n.error(`loop.parallel.rate.type`,`parallel.rate must be a number or duration, got '${i.name}'`))}this.keyName===void 0?t.has(`key`)&&n.error(`loop.key.shadow`,`loop's default 'key' is already in scope from an enclosing loop — set the \`key\` field on this loop to a distinct name (e.g. "i", "j", "outerKey") so the inner loop doesn't shadow the outer iteration index`):n.at(`key`,()=>Mh(this.keyName,t,n)),this.valueName===void 0?t.has(`value`)&&n.error(`loop.value.shadow`,`loop's default 'value' is already in scope from an enclosing loop — set the \`value\` field on this loop to a distinct name (e.g. "v", "row", "outerValue") so the inner loop doesn't shadow the outer iteration value`):n.at(`value`,()=>Mh(this.valueName,t,n));let o=a?.key??e.registry.any(),s=a?.value??e.registry.any(),c=new Map(t);return c.set(this.keyName??`key`,o),c.set(this.valueName??`value`,s),n.at(`body`,()=>jh(e,this.body,c,n,{...r,inLoop:!0})),this.body.effects()===B.NONE&&n.at(`body`,()=>n.warn(`loop.body.no-effect`,"loop body has no observable effect — the iteration's computed value is discarded. Add a `set` to accumulate into an outer var, a `flow` to control iteration, or invoke a side-effecting native (e.g. `fns.log`, `fns.fetch`)")),e.registry.void()}toCode(e,t={}){let n=t.expectsValue??!1,r={...t,expectsValue:!0},i={...t,expectsValue:!1},a=this.over.toCode(e,r),o=this.keyName??`key`,s=this.valueName??`value`,c=``;t.includeComments!==!1&&(this.parallel?.concurrent&&(c+=`/* parallel.concurrent: ${this.parallel.concurrent.toCode(e,r)} */ `),this.parallel?.rate&&(c+=`/* parallel.rate: ${this.parallel.rate.toCode(e,r)} */ `));let l=(()=>{let t=this.body.kind;if(t===`flow`)return`${this.body.toCode(e,i)};`;if(t===`block`){let t=this.body.toCode(e,i);return t.startsWith(`{`)?t.slice(1,-1).trim():t}return t===`if`||t===`switch`||t===`loop`?this.body.toCode(e,i):`${this.body.toCode(e,i)};`})(),u=`${c}for (const [${o}, ${s}] of ${a}) {
|
|
115
|
+
${zv(l)}
|
|
116
|
+
}`,d=this.commentPrefix(t);return n?d+`(() => { ${u}; return undefined; })()`:d+u}toJSON(){let e={kind:`loop`,over:this.over.toJSON(),body:this.body.toJSON()};return this.keyName!==void 0&&(e.key=this.keyName),this.valueName!==void 0&&(e.value=this.valueName),this.parallel&&(e.parallel={concurrent:this.parallel.concurrent?.toJSON(),rate:this.parallel.rate?.toJSON()}),this.withCommentOn(e)}toJSONCode(e=[],t=2,n=0){let r=this.over.toJSONCode([...e,`over`],t,n+1),i=this.body.toJSONCode([...e,`body`],t,n+1),a=this.parallel?V.jsonObject([{key:`concurrent`,value:this.parallel.concurrent?.toJSONCode([...e,`parallel`,`concurrent`],t,n+2)},{key:`rate`,value:this.parallel.rate?.toJSONCode([...e,`parallel`,`rate`],t,n+2)}],{path:[...e,`parallel`]},n+1,t):void 0;return V.jsonObject([{key:`kind`,value:V.jsonString(`loop`)},{key:`over`,value:r},{key:`body`,value:i},{key:`key`,value:this.keyName===void 0?void 0:V.jsonString(this.keyName)},{key:`value`,value:this.valueName===void 0?void 0:V.jsonString(this.valueName)},{key:`parallel`,value:a},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}clone(){return new e(this.over.clone(),this.body.clone(),this.keyName,this.valueName,this.parallel?{concurrent:this.parallel.concurrent?.clone(),rate:this.parallel.rate?.clone()}:void 0).withComment(this.comment)}forEachChild(e){e(this.over,`inherit`),e(this.body,`loop`),this.parallel?.concurrent&&e(this.parallel.concurrent,`inherit`),this.parallel?.rate&&e(this.parallel.rate,`inherit`)}effects(){return this.over.effects()|this.body.effects()|(this.parallel?.concurrent?.effects()??B.NONE)|(this.parallel?.rate?.effects()??B.NONE)}complexity(){return 6+this.over.complexity()+this.body.complexity()+(this.parallel?.concurrent?.complexity()??0)+(this.parallel?.rate?.complexity()??0)}};async function Wv(e,t,n,r,i){let a=n.registry,o=new W(a.fn({args:a.obj({key:{type:a.any()},value:{type:a.any()}}),returns:a.void()}),async e=>{let t=e.raw;if(!t)throw Error(`yield: missing args`);return await s.checkpoint(),i(t.key,t.value)}),s=t.child({this:r,yield:o});try{await e.evaluate(n,s)}catch(e){if(!(e instanceof Ph))throw e}}var Gv=class e extends wh{constructor(e,t,n){super(),this.fnType=e,this.body=t,this.constraint=n}fnType;body;constraint;static KIND=`lambda`;kind=e.KIND;useLineComment(e={}){return!e.expectsValue}static from(t,n){let r=n.registry,i=r.parse(t.type,n),a=Jv(n,i),o=r.parseExpr(t.body,a),s=t.constraint?r.parseExpr(t.constraint,a):void 0;return new e(i,o,s).withComment(t.comment)}async evaluate(e,t){let n=this.fnType,r=this.body,i=t,a=this.constraint,o=async t=>{await i.checkpoint();let s=new W(n,o),c=i.child({args:t,recurse:s});if(a&&(await a.evaluate(e,c)).raw!==!0)throw Error(`lambda constraint failed: ${a.toCode(e.registry,{expectsValue:!0})}`);try{return await r.evaluate(e,c)}catch(t){if(t instanceof Ih)return t.value??new W(e.registry.void(),void 0);throw t}};return new W(n,o)}typeOf(e,t){return this.fnType}validateWalk(e,t,n,r){let i=this.fnType.call(),a=new Map(t);a.set(`args`,i?.args??e.registry.any());let o=n.at(`body`,()=>jh(e,this.body,a,n,{...r,inLambda:!0}));if(i?.returns&&!i.returns.compatible(o)&&n.at(`body`,()=>n.warn(`lambda.returns.type`,`body type '${o.name}' not compatible with declared returns '${i.returns.name}'`)),this.constraint){let t=e.registry.bool(),i=n.at(`constraint`,()=>jh(e,this.constraint,a,n,{...r,inLambda:!0}));t.compatible(i)||n.at(`constraint`,()=>n.warn(`lambda.constraint.type`,`constraint must return bool, got '${i.name}'`))}return this.fnType}toGinCode(e,t={},n=[]){let r=this.fnType.call(),i={...t,expectsValue:!0},a=this.commentPrefix(t),o=`(${Kv(r?.args,t)})${r?.returns?`: ${r.returns.toCode(void 0,t)}`:``}`,s=this.body.toGinCode(e,i,[...n,`body`]),c=s.text,l;return l=this.constraint?H`${o} => {\n if (!(${qv(this.constraint.toGinCode(e,i,[...n,`constraint`]))})) throw new Error('constraint');\n return ${s.indent(` `)};\n}`:c.includes(`
|
|
117
|
+
`)?H`${o} => {\n ${s.indent(` `)}\n}`:H`${o} => ${s}`,oh(a?H`${a}${l}`:l,{path:n,expr:this})}toCode(e,t={}){return this.toGinCode(e,t).toString()}toJSON(){return this.withCommentOn({kind:`lambda`,type:this.fnType.toJSON(),body:this.body.toJSON(),constraint:this.constraint?.toJSON()})}toJSONCode(e=[],t=2,n=0){let r=this.fnType.toJSONCode([...e,`type`],t,n+1),i=this.body.toJSONCode([...e,`body`],t,n+1),a=this.constraint?this.constraint.toJSONCode([...e,`constraint`],t,n+1):void 0;return V.jsonObject([{key:`kind`,value:V.jsonString(`lambda`)},{key:`type`,value:r},{key:`body`,value:i},{key:`constraint`,value:a},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}clone(){return new e(this.fnType.clone(),this.body.clone(),this.constraint?.clone()).withComment(this.comment)}forEachChild(e){e(this.body,`lambda`),this.constraint&&e(this.constraint,`lambda`)}effects(){return B.NONE}complexity(){return 10+this.body.complexity()+(this.constraint?.complexity()??0)}};function Kv(e,t){if(!e||e.name===`void`||e.name===`any`)return``;let n=e.fields;if(!n)return`args: ${e.toCode(void 0,t)}`;let r=Object.entries(n);return r.length===0?``:r.map(([e,n])=>{let r=n.type.isOptional?.()??!1,i=r&&typeof n.type.required==`function`?n.type.required():n.type;return`${n.docs&&t.includeComments!==!1?`/* ${n.docs} */ `:``}${e}${r?`?`:``}: ${i.toCode(void 0,t)}`}).join(`, `)}function qv(e){return e.text.includes(`
|
|
118
|
+
`)?new V(e.text.replace(/\n\s*/g,` `),e.spans):e}function Jv(e,t){let n=new Ch(e),r=t.call();if(r?.types)for(let[e,t]of Object.entries(r.types))n.bind(e,t);return n}var Yv=class e extends wh{constructor(e,t){super(),this.template=e,this.params=t}template;params;static KIND=`template`;kind=e.KIND;static from(t,n){let r=n.registry,i=t.template,a=i&&typeof i==`object`&&`kind`in i?r.parseExpr(i,n):r.parseExpr({kind:`new`,type:{name:`text`},value:String(i)},n),o=t.params?r.parseExpr(t.params,n):void 0;return new e(a,o).withComment(t.comment)}async evaluate(e,t){let n=await this.template.evaluate(e,t),r=String(n.raw),i;this.params&&(i=(await this.params.evaluate(e,t)).raw);let a=r.replace(/\{(\w+)\}/g,(e,n)=>{if(i&&Object.prototype.hasOwnProperty.call(i,n)){let e=i[n];return e==null?``:e instanceof W?String(e.raw??``):String(e)}let r=t.get(n);return r===void 0?``:r instanceof W?String(r.raw??``):String(r)});return G(e.registry.text(),a)}typeOf(e,t){return e.registry.text()}validateWalk(e,t,n,r){let i=e.registry.text(),a=n.at(`template`,()=>jh(e,this.template,t,n,r));i.compatible(a)||n.at(`template`,()=>n.warn(`template.template.type`,`template should resolve to text, got '${a.name}'`));let o,s=!1;if(this.params){let i=n.at(`params`,()=>jh(e,this.params,t,n,r));if(i.name===`any`)s=!0;else if(i.name===`obj`||i.name===`iface`){let e=i.props(),t=Object.entries(e).filter(([,e])=>!e.type.call()).map(([e])=>e);o=new Set(t)}else n.at(`params`,()=>n.warn(`template.params.type`,`template params should be an object, got '${i.name}'`)),s=!0}let c=this.template instanceof hv&&typeof this.template.value==`string`?this.template.value:void 0;if(c!==void 0){let e=new Set,r=/\{(\w+)\}/g,i;for(;(i=r.exec(c))!==null;){let r=i[1];if(e.has(r))continue;e.add(r);let a=o?.has(r)??!1,c=t.has(r);s?c||n.error(`template.placeholder.unresolved`,`placeholder '{${r}}' isn't a scope variable; either define '${r}' in scope or pass a typed obj as \`params\` so it can be checked`):!a&&!c&&n.error(`template.placeholder.unresolved`,this.params?`placeholder '{${r}}' is not a key of \`params\` (keys: [${[...o??[]].join(`, `)||`none`}]) and not a scope variable`:`placeholder '{${r}}' does not match any scope variable; either \`define ${r} = ...\` first or pass it via \`params\``)}}return e.registry.text()}toCode(e,t={}){let n=this.commentPrefix(t),r=this.template instanceof hv&&typeof this.template.value==`string`?this.template.value:void 0;if(r===void 0){let r=e.toCode(this.template,{...t,expectsValue:!0});return this.params?`${n}template(${r}, ${e.toCode(this.params,{...t,expectsValue:!0})})`:`${n}template(${r})`}let i=this.params?Xv(this.params,e):void 0;return`${n}${`\`${r.replace(/\{(\w+)\}/g,(e,t)=>{if(i&&Object.prototype.hasOwnProperty.call(i,t)){let e=i[t];return e.length>64?`\${
|
|
119
119
|
`+e+`
|
|
120
|
-
}`:"${"+e+`}`}return"${"+t+`}`}).replace(/`/g,"\\`")}\``}`}toJSON(){return this.withCommentOn({kind:`template`,template:this.template.toJSON(),...this.params?{params:this.params.toJSON()}:{}})}toJSONCode(e=[],t=2,n=0){let r=this.template.toJSONCode([...e,`template`],t,n+1),i=this.params?this.params.toJSONCode([...e,`params`],t,n+1):void 0;return V.jsonObject([{key:`kind`,value:V.jsonString(`template`)},{key:`template`,value:r},{key:`params`,value:i},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}clone(){return new e(this.template.clone(),this.params?.clone()).withComment(this.comment)}forEachChild(e){e(this.template,`inherit`),this.params&&e(this.params,`inherit`)}effects(){return this.template.effects()|(this.params?.effects()??B.NONE)}complexity(){return 1+this.template.complexity()+(this.params?.complexity()??0)}};function Dv(e,t){if(!(e instanceof K_))return;let n=e.value;if(!n||typeof n!=`object`||Array.isArray(n))return;let r={};for(let[e,i]of Object.entries(n))if(typeof i==`string`)r[e]=JSON.stringify(i);else if(typeof i==`number`||typeof i==`boolean`)r[e]=String(i);else if(i===null)r[e]=`null`;else if(i&&typeof i==`object`&&`kind`in i&&typeof i.kind==`string`&&t.exprClass(i.kind))try{r[e]=t.parseExpr(i).toCode(t,{expectsValue:!0})}catch{return}else return;return r}var Ov=class e extends th{constructor(e,t,n=B.STATE|B.SYSTEM|B.EXTERNAL){super(),this.id=e,this.type=t,this.resolvedEffects=n}id;type;resolvedEffects;static KIND=`native`;kind=e.KIND;static from(t,n){return new e(t.id,t.type?n.registry.parse(t.type,n):void 0,n.registry.nativeEffects(t.id)).withComment(t.comment)}async evaluate(e,t){let n=e.registry.getNative(this.id);if(!n)throw Error(`native: no impl registered for '${this.id}'`);let r=await n(t,e.registry);return r instanceof W?r:G(this.type??e.registry.any(),r)}typeOf(e,t){return this.type??e.registry.any()}validateWalk(e,t,n,r){return e.registry.getNative(this.id)||n.warn(`native.unknown`,`native impl '${this.id}' is not registered`),this.type??e.registry.any()}toCode(e,t={}){return this.commentPrefix(t)+`/* native: ${this.id} */`}toJSON(){let e={kind:`native`,id:this.id};return this.type&&(e.type=this.type.toJSON()),this.withCommentOn(e)}toJSONCode(e=[],t=2,n=0){let r=this.type?this.type.toJSONCode([...e,`type`],t,n+1):void 0;return V.jsonObject([{key:`kind`,value:V.jsonString(`native`)},{key:`id`,value:V.jsonString(this.id)},{key:`type`,value:r},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}clone(){return new e(this.id,this.type?.clone(),this.resolvedEffects).withComment(this.comment)}effects(){return this.resolvedEffects}complexity(){return 1}},kv=[`props`,`get`,`call`,`init`],Av=class{classes=new Map;namedTypes=new Map;natives=new Map;nativeEffectsMap=new Map;exprClasses=new Map;augments=new Map;_version=0;get version(){return this._version}parent=void 0;get registry(){return this}define(e){return this.classes.set(e.NAME,e),this._version++,this}register(e){return this.namedTypes.set(e.name,e),this._version++,this}scope(e){return new eh(this,{...e})}augment(e,t){this._version++;let n={props:t.props?Nh.fromMap(t.props,this):void 0,get:t.get?Ph.from(t.get,this):void 0,call:t.call?Fh.from(t.call,this):void 0,init:t.init?Ih.from(t.init,this):void 0},r=this.augments.get(e);return r?(this.augments.set(e,{props:n.props?{...r.props??{},...n.props}:r.props,get:r.get??n.get,call:r.call??n.call,init:r.init??n.init}),this):(this.augments.set(e,{props:n.props?{...n.props}:void 0,get:n.get,call:n.call,init:n.init}),this)}augmentation(e){return this.augments.get(e)}lookup(e){if(this.namedTypes.has(e))return this.namedTypes.get(e);let t=this.classes.get(e);if(t)return t.from({name:e},this)}localLookup(e){}setNative(e,t,n=B.STATE|B.SYSTEM|B.EXTERNAL){return this.natives.set(e,t),this.nativeEffectsMap.set(e,n),this}getNative(e){return this.natives.get(e)}nativeEffects(e){let t=this.nativeEffectsMap.get(e);return t===void 0?B.STATE|B.SYSTEM|B.EXTERNAL:t}defineExpr(e){return this.exprClasses.set(e.KIND,e),this._version++,this}exprClass(e){return this.exprClasses.get(e)}typeClasses(){return Array.from(this.classes.values())}typeClass(e){return this.classes.get(e)}namedTypeList(){return Array.from(this.namedTypes.values())}exprClassList(){return Array.from(this.exprClasses.values())}typeNameCandidates(){return[...this.typeClasses().map(e=>e.NAME),...this.namedTypeList().map(e=>e.name)]}parseExpr(e,t=this){if(e==null)return;if(e instanceof th)return e;if(typeof e!=`object`||!(`kind`in e))throw Error(`registry.parseExpr: expected ExprDef with kind, got ${typeof e}`);let n=e,r=this.exprClasses.get(n.kind);if(!r)throw Error(`registry.parseExpr: unknown expr kind '${n.kind}'`);return r.from(n,t)}toCode(e,t){return(e instanceof th?e:this.parseExpr(e)).toCode(this,t)}toGinCode(e,t){return(e instanceof th?e:this.parseExpr(e)).toGinCode(this,t,[])}toJSONCode(e,t=2){return(e instanceof th?e:this.parseExpr(e)).toJSONCode([],t)}validate(e){let t=new Pm,n=new Set,r=(r,i)=>{if(n.has(r))return;n.add(r);let a=i.validate(e);for(let e of a.list)t.list.push({...e,path:[r,...e.path]})};for(let[e,t]of this.namedTypes)r(e,t);for(let e of this.augments.keys()){let t=this.lookup(e);t&&r(e,t)}return t}parseValue(e,t,n=this){if(e instanceof W)return this.checkSlot(e,t,n);if(t?.parsesExprValue(n)&&this.exprShaped(e))return t.parse(e,n);if(e&&typeof e==`object`&&`type`in e&&`value`in e&&this.typeDefShaped(e.type)){let r=e.kind;if(typeof r==`string`&&this.exprClass(r))throw TypeError(`registry.parseValue: this node is an EXPRESSION (kind:'${r}'), not a value envelope \u2014 an Expr only evaluates inside a program (\`Engine.run\`/\`Engine.evaluate\`); a bare \`parse\` takes data. Drop the \`kind\` to mean the literal ${JSON.stringify(e.type)} value.`+(t?` (This slot is declared \`${t.toCode()}\`.)`:``));return this.checkSlot(this.parse(e.type,n).parse(e.value,n),t,n)}if(!t)throw TypeError(`registry.parseValue: expected Value or JSONValue, got ${typeof e}`);return t.parse(e,n)}typeDefShaped(e){return!!e&&typeof e==`object`&&!Array.isArray(e)&&typeof e.name==`string`}exprShaped(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e.kind;return typeof t==`string`&&!!this.exprClass(t)}checkSlot(e,t,n){if(!t||wh(t,e.type,n))return e;throw TypeError(`registry.parseValue: this slot is declared \`${t.toCode()}\` but the value carries \`${e.type.toCode()}\``)}parse(e,t=this){if(!e||typeof e!=`object`)throw Error(`registry.parse: expected object, got ${typeof e}`);if(e instanceof U)throw Error(`registry.parse: expected a serialized TypeDef, got a LIVE ${e.constructor.name} instance (\`${e.name}\`) \u2014 pass \`type.toJSON()\`, or use the type as it stands.`);let n=e;if(!sm(n.name))throw Error(`registry.parse: type 'name' must match ${om}, got ${JSON.stringify(n.name)}`);if(n.extends!==void 0&&!sm(n.extends))throw Error(`registry.parse: type 'extends' must match ${om}, got ${JSON.stringify(n.extends)}`);if(n.satisfies){for(let e of n.satisfies)if(!sm(e))throw Error(`registry.parse: 'satisfies' entries must match ${om}, got ${JSON.stringify(e)}`)}let r=n.extends??n.name;Gp(n,this.namedTypes.has(r)?void 0:this.classes.get(r),n.extends===void 0,this);let i=this.parseInner(n,t);if(n.satisfies&&n.satisfies.length>0)for(let e of n.satisfies){let r=t.lookup(e)??this.lookup(e);if(!r)throw Error(`registry.parse: satisfies references unknown interface '${e}'${Ip(e,this.typeNameCandidates())}`);if(!r.compatible(i))throw Error(`registry.parse: type '${n.name}' claims to satisfy '${e}' but does not structurally match`)}return i}isUseSiteDef(e){return e.generic===void 0&&e.options===void 0?!1:[`extends`,`satisfies`,`init`,`props`,`get`,`call`,`constraint`].every(t=>e[t]===void 0)}boundAboveRegistry(e,t){for(let n=t;n&&n!==this;n=n.parent)if(n.localLookup(e)!==void 0)return!0;return!1}parseGenericArgs(e,t){return Object.fromEntries(Object.entries(e.generic??{}).map(([e,n])=>[e,this.parse(n,t)]))}useSiteAlias(e,t){return new wg(t,e.options===void 0?{name:e.name}:{name:e.name,options:e.options},this.parseGenericArgs(e,t))}applyUse(e,t,n,r){let i=e;return Object.keys(t).length>0&&i instanceof vg&&(i=i.specialize(t)),n!==void 0&&Object.keys(n).length>0&&!hg(i.narrow(n),i.options)&&(i=new vg(this,i,{name:i.name,docs:i.docs,options:n,generic:i instanceof vg?i.local.generic:void 0,useSite:!0},i instanceof vg&&i.bindings?i.scope:void 0,r)),i}nearBuiltin(e){return e[0]===e[0]?.toLowerCase()&&Ip(e,this.typeClasses().map(e=>e.NAME))!==``}isBareNameDef(e){for(let t of[`extends`,`satisfies`,`generic`,`options`,`init`,`props`,`get`,`call`,`constraint`])if(e[t]!==void 0)return!1;return!0}parseInner(e,t){if(e.extends){let n=t.lookup(e.extends)??this.lookup(e.extends);if(!n)throw Error(`registry.parse: extends references unknown type '${e.extends}'${Ip(e.extends,this.typeNameCandidates())}`);let r=this.classes.get(e.extends),i=e.generic!==void 0&&Object.keys(e.generic).length>0,a=r&&!i?kv.filter(t=>e[t]!==void 0&&(r.consumes??[]).includes(t)):[];if(r&&a.length>0){let n={name:e.extends,...a.includes(`props`)?{props:e.props}:{},...a.includes(`get`)?{get:e.get}:{},...a.includes(`call`)?{call:e.call}:{},...a.includes(`init`)?{init:e.init}:{}},i=r.from(n,t),o={...e};delete o.extends;for(let e of a)delete o[e];return new vg(this,i,this.buildLocal(o,t))}return new vg(this,n,this.buildLocal(e,t))}if(this.isBareNameDef(e)){let n=t;for(;n&&n!==this;){if(n.localLookup(e.name)!==void 0)return new wg(t,{name:e.name});n=n.parent}if(this.namedTypes.has(e.name))return this.namedTypes.get(e.name);let r=this.classes.get(e.name);return r?r.from(e,t):new wg(t,{name:e.name})}let n=this.isUseSiteDef(e);if(n&&this.boundAboveRegistry(e.name,t))return this.useSiteAlias(e,t);if(this.namedTypes.has(e.name)){let r=this.namedTypes.get(e.name);return n?this.applyUse(r,this.parseGenericArgs(e,t),e.options,t):e.generic&&r instanceof vg?r.specialize(this.parseGenericArgs(e,t)):r}let r=this.classes.get(e.name);if(!r){if(n&&!this.nearBuiltin(e.name))return this.useSiteAlias(e,t);throw Error(`registry.parse: unknown type '${e.name}'${Ip(e.name,this.typeNameCandidates())}`)}let i=new Set(r.consumes??[]),a=kv.filter(t=>e[t]!==void 0&&!i.has(t));if(a.length===0)return r.from(e,t);let o={...e};for(let e of a)delete o[e];let s=r.from(o,t),c={name:e.name,docs:e.docs,props:a.includes(`props`)&&e.props?Nh.fromMap(e.props,t):void 0,get:a.includes(`get`)&&e.get?Ph.from(e.get,t):void 0,call:a.includes(`call`)&&e.call?Fh.from(e.call,t):void 0,init:a.includes(`init`)&&e.init?Ih.from(e.init,t):void 0};return new vg(this,s,c)}getTypesFor(e){let t=this.lookup(e);if(!t)return[];let n=[];for(let e of this.namedTypes.values())if(e!==t)try{t.compatible(e)&&n.push(e)}catch{}for(let[r,i]of this.classes){if(r===e)continue;let a;try{a=i.from({name:r},this)}catch{continue}try{t.compatible(a)&&n.push(a)}catch{}}return n}buildLocal(e,t){let n=e.generic?Object.fromEntries(Object.entries(e.generic).map(([e,n])=>[e,this.parse(n,t)])):void 0;return{name:e.name,docs:e.docs,options:e.options,generic:n,props:e.props?Nh.fromMap(e.props,t):void 0,get:e.get?Ph.from(e.get,t):void 0,call:e.call?Fh.from(e.call,t):void 0,init:e.init?Ih.from(e.init,t):void 0,constraint:e.constraint?this.parseExpr(e.constraint,t):void 0}}any(){return new yg(this,{})}void(){return new Zg(this,{})}null(){return new Vg(this,{})}bool(e){return new Tg(this,e??{})}num(e){return new Ug(this,e??{})}text(e){return new Kg(this,e??{})}list(e,t){return new Fg(this,e,t??{})}map(e,t){return new zg(this,e,t)}tuple(e){return new Yg(this,[...e])}obj(e){return new bg(this,e)}field(e,t){return{type:e,docs:t?.docs,default:t?.default===void 0?void 0:this.parseExpr(t.default)}}optional(e){return new Wg(this,e)}nullable(e){return new Hg(this,e)}not(e){return new Bg(this,e)}or(e){return new Gg(this,[...e])}and(e){return new Sg(this,[...e])}enum(e,t){return jv(e)?new kg(this,this.text(),{values:Object.fromEntries(e.map(e=>[e,e]))}):new kg(this,t??this.text(),{values:e})}literal(e,t){if(e instanceof U)return new Pg(this,e,t);let n=this.primitiveOf(e);return new Pg(this,n,e)}primitiveOf(e){switch(typeof e){case`string`:return this.text();case`number`:return this.num();case`boolean`:return this.bool()}}date(e){return new Dg(this,e??{})}timestamp(e){return new qg(this,e??{})}duration(){return new Og(this,{})}color(e){return new Eg(this,e??{})}fn(e){return new Mg(this,{args:e.args,returns:e.returns,throws:e.throws,get:e.call},e.generic??{})}iface(e){return new Ng(this,{props:e.props?Nh.fromMap(e.props,this):{},get:e.get?Ph.from(e.get,this):void 0,call:e.call?Fh.from(e.call,this):void 0})}alias(e){return new wg(this,{name:e})}typ(e){return new Xg(this,e)}compatible(e){let t=[],n=new Set,r=e=>{n.has(e.name)||(n.add(e.name),t.push(e))};for(let t of this.typeClasses()){let n;try{n=t.from({name:t.NAME},this)}catch{continue}if(!(n.isUniversal()&&e.name!==t.NAME))try{n.compatible(e)&&r(n)}catch{continue}}for(let t of this.namedTypeList())try{t.compatible(e)&&r(t)}catch{continue}return t}like(e){let t=this.compatible(e).map(t=>t.like(e));return t.length===0?this.null():t.length===1?t[0]:this.or(t)}extend(e,t){let n=typeof e==`string`?this.lookup(e)??(()=>{throw Error(`extend: unknown base '${e}'`)})():e;return new vg(this,n,t)}nativeExpr(e){return this.parseExpr({kind:`native`,id:e})}prop(e,t,n){return Mv(new Nh({type:e,get:this.nativeExpr(t),docs:n}))}method(e,t,n,r){return Mv(new Nh({type:this.fn({args:this.obj(e),returns:t,generic:r?.generic}),get:this.nativeExpr(n),docs:r?.docs}))}};function jv(e){return Array.isArray(e)}function Mv(e){if(!Nv(e))throw Error(`registry: a computed prop must carry a get expression`);return e}function Nv(e){return e.get!==void 0}var Pv=[yg,Zg,Vg,Tg,Ug,Kg,Fg,zg,Yg,bg,Wg,Hg,Bg,Gg,Sg,kg,Pg,Mg,Ng,Xg,Dg,qg,Og,Eg],Fv=[K_,uv,dv,fv,mv,vv,yv,bv,Sv,Ev,hv,Ov];function Iv(){let e=new Av;for(let t of Pv)e.define(t);for(let t of Fv)e.defineExpr(t);return G_(e),e}var Lv={$Exit:{code:"/** gin `flow: exit` — unwinds to the outermost exported function, whose result becomes `value`. */\nclass $Exit {\n constructor(readonly value: unknown) {}\n}"},$Throw:{code:"/** gin `flow: throw` — a thrown gin value; a call step's `catch` handler receives `error`. */\nclass $Throw extends Error {\n constructor(readonly error: unknown) { super(typeof error === 'string' ? error : 'gin throw'); }\n}"},$str:{code:"/** Template placeholder text — `null`/`undefined` read as the empty string. */\nfunction $str(v: unknown): string {\n return v === undefined || v === null ? '' : String(v);\n}"},$template:{code:`/** A template whose text is only known at run time: \`{name}\` reads \`params.name\`. */
|
|
120
|
+
}`:"${"+e+`}`}return"${"+t+`}`}).replace(/`/g,"\\`")}\``}`}toJSON(){return this.withCommentOn({kind:`template`,template:this.template.toJSON(),...this.params?{params:this.params.toJSON()}:{}})}toJSONCode(e=[],t=2,n=0){let r=this.template.toJSONCode([...e,`template`],t,n+1),i=this.params?this.params.toJSONCode([...e,`params`],t,n+1):void 0;return V.jsonObject([{key:`kind`,value:V.jsonString(`template`)},{key:`template`,value:r},{key:`params`,value:i},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}clone(){return new e(this.template.clone(),this.params?.clone()).withComment(this.comment)}forEachChild(e){e(this.template,`inherit`),this.params&&e(this.params,`inherit`)}effects(){return this.template.effects()|(this.params?.effects()??B.NONE)}complexity(){return 1+this.template.complexity()+(this.params?.complexity()??0)}};function Xv(e,t){if(!(e instanceof hv))return;let n=e.value;if(!n||typeof n!=`object`||Array.isArray(n))return;let r={};for(let[e,i]of Object.entries(n))if(typeof i==`string`)r[e]=JSON.stringify(i);else if(typeof i==`number`||typeof i==`boolean`)r[e]=String(i);else if(i===null)r[e]=`null`;else if(i&&typeof i==`object`&&`kind`in i&&typeof i.kind==`string`&&t.exprClass(i.kind))try{r[e]=t.parseExpr(i).toCode(t,{expectsValue:!0})}catch{return}else return;return r}var Zv=class e extends wh{constructor(e,t,n=B.STATE|B.SYSTEM|B.EXTERNAL){super(),this.id=e,this.type=t,this.resolvedEffects=n}id;type;resolvedEffects;static KIND=`native`;kind=e.KIND;static from(t,n){return new e(t.id,t.type?n.registry.parse(t.type,n):void 0,n.registry.nativeEffects(t.id)).withComment(t.comment)}async evaluate(e,t){let n=e.registry.getNative(this.id);if(!n)throw Error(`native: no impl registered for '${this.id}'`);let r=await n(t,e.registry);return r instanceof W?r:G(this.type??e.registry.any(),r)}typeOf(e,t){return this.type??e.registry.any()}validateWalk(e,t,n,r){return e.registry.getNative(this.id)||n.warn(`native.unknown`,`native impl '${this.id}' is not registered`),this.type??e.registry.any()}toCode(e,t={}){return this.commentPrefix(t)+`/* native: ${this.id} */`}toJSON(){let e={kind:`native`,id:this.id};return this.type&&(e.type=this.type.toJSON()),this.withCommentOn(e)}toJSONCode(e=[],t=2,n=0){let r=this.type?this.type.toJSONCode([...e,`type`],t,n+1):void 0;return V.jsonObject([{key:`kind`,value:V.jsonString(`native`)},{key:`id`,value:V.jsonString(this.id)},{key:`type`,value:r},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}clone(){return new e(this.id,this.type?.clone(),this.resolvedEffects).withComment(this.comment)}effects(){return this.resolvedEffects}complexity(){return 1}},Qv=[`props`,`get`,`call`,`init`],$v=class{classes=new Map;namedTypes=new Map;natives=new Map;nativeEffectsMap=new Map;exprClasses=new Map;augments=new Map;_version=0;get version(){return this._version}parent=void 0;get registry(){return this}define(e){return this.classes.set(e.NAME,e),this._version++,this}register(e){return this.namedTypes.set(e.name,e),this._version++,this}scope(e){return new Ch(this,{...e})}augment(e,t){this._version++;let n={props:t.props?ng.fromMap(t.props,this):void 0,get:t.get?rg.from(t.get,this):void 0,call:t.call?ig.from(t.call,this):void 0,init:t.init?ag.from(t.init,this):void 0},r=this.augments.get(e);return r?(this.augments.set(e,{props:n.props?{...r.props??{},...n.props}:r.props,get:r.get??n.get,call:r.call??n.call,init:r.init??n.init}),this):(this.augments.set(e,{props:n.props?{...n.props}:void 0,get:n.get,call:n.call,init:n.init}),this)}augmentation(e){return this.augments.get(e)}lookup(e){if(this.namedTypes.has(e))return this.namedTypes.get(e);let t=this.classes.get(e);if(t)return t.from({name:e},this)}localLookup(e){}setNative(e,t,n=B.STATE|B.SYSTEM|B.EXTERNAL){return this.natives.set(e,t),this.nativeEffectsMap.set(e,n),this}getNative(e){return this.natives.get(e)}nativeEffects(e){let t=this.nativeEffectsMap.get(e);return t===void 0?B.STATE|B.SYSTEM|B.EXTERNAL:t}defineExpr(e){return this.exprClasses.set(e.KIND,e),this._version++,this}exprClass(e){return this.exprClasses.get(e)}typeClasses(){return Array.from(this.classes.values())}typeClass(e){return this.classes.get(e)}namedTypeList(){return Array.from(this.namedTypes.values())}exprClassList(){return Array.from(this.exprClasses.values())}typeNameCandidates(){return[...this.typeClasses().map(e=>e.NAME),...this.namedTypeList().map(e=>e.name)]}parseExpr(e,t=this){if(e==null)return;if(e instanceof wh)return e;if(typeof e!=`object`||!(`kind`in e))throw Error(`registry.parseExpr: expected ExprDef with kind, got ${typeof e}`);let n=e,r=this.exprClasses.get(n.kind);if(!r)throw Error(`registry.parseExpr: unknown expr kind '${n.kind}'`);return r.from(n,t)}toCode(e,t){return(e instanceof wh?e:this.parseExpr(e)).toCode(this,t)}toGinCode(e,t){return(e instanceof wh?e:this.parseExpr(e)).toGinCode(this,t,[])}toJSONCode(e,t=2){return(e instanceof wh?e:this.parseExpr(e)).toJSONCode([],t)}validate(e){let t=new rh,n=new Set,r=(r,i)=>{if(n.has(r))return;n.add(r);let a=i.validate(e);for(let e of a.list)t.list.push({...e,path:[r,...e.path]})};for(let[e,t]of this.namedTypes)r(e,t);for(let e of this.augments.keys()){let t=this.lookup(e);t&&r(e,t)}return t}parseValue(e,t,n=this){if(e instanceof W)return this.checkSlot(e,t,n);if(t?.parsesExprValue(n)&&this.exprShaped(e))return t.parse(e,n);if(e&&typeof e==`object`&&`type`in e&&`value`in e&&this.typeDefShaped(e.type)){let r=e.kind;if(typeof r==`string`&&this.exprClass(r))throw TypeError(`registry.parseValue: this node is an EXPRESSION (kind:'${r}'), not a value envelope \u2014 an Expr only evaluates inside a program (\`Engine.run\`/\`Engine.evaluate\`); a bare \`parse\` takes data. Drop the \`kind\` to mean the literal ${JSON.stringify(e.type)} value.`+(t?` (This slot is declared \`${t.toCode()}\`.)`:``));return this.checkSlot(this.parse(e.type,n).parse(e.value,n),t,n)}if(!t)throw TypeError(`registry.parseValue: expected Value or JSONValue, got ${typeof e}`);return t.parse(e,n)}typeDefShaped(e){return!!e&&typeof e==`object`&&!Array.isArray(e)&&typeof e.name==`string`}exprShaped(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e.kind;return typeof t==`string`&&!!this.exprClass(t)}checkSlot(e,t,n){if(!t||qh(t,e.type,n))return e;throw TypeError(`registry.parseValue: this slot is declared \`${t.toCode()}\` but the value carries \`${e.type.toCode()}\``)}parse(e,t=this){if(!e||typeof e!=`object`)throw Error(`registry.parse: expected object, got ${typeof e}`);if(e instanceof U)throw Error(`registry.parse: expected a serialized TypeDef, got a LIVE ${e.constructor.name} instance (\`${e.name}\`) \u2014 pass \`type.toJSON()\`, or use the type as it stands.`);let n=e;if(!Am(n.name))throw Error(`registry.parse: type 'name' must match ${km}, got ${JSON.stringify(n.name)}`);if(n.extends!==void 0&&!Am(n.extends))throw Error(`registry.parse: type 'extends' must match ${km}, got ${JSON.stringify(n.extends)}`);if(n.satisfies){for(let e of n.satisfies)if(!Am(e))throw Error(`registry.parse: 'satisfies' entries must match ${km}, got ${JSON.stringify(e)}`)}let r=n.extends??n.name;mm(n,this.namedTypes.has(r)?void 0:this.classes.get(r),n.extends===void 0,this);let i=this.parseInner(n,t);if(n.satisfies&&n.satisfies.length>0)for(let e of n.satisfies){let r=t.lookup(e)??this.lookup(e);if(!r)throw Error(`registry.parse: satisfies references unknown interface '${e}'${am(e,this.typeNameCandidates())}`);if(!r.compatible(i))throw Error(`registry.parse: type '${n.name}' claims to satisfy '${e}' but does not structurally match`)}return i}isUseSiteDef(e){return e.generic===void 0&&e.options===void 0?!1:[`extends`,`satisfies`,`init`,`props`,`get`,`call`,`constraint`].every(t=>e[t]===void 0)}boundAboveRegistry(e,t){for(let n=t;n&&n!==this;n=n.parent)if(n.localLookup(e)!==void 0)return!0;return!1}parseGenericArgs(e,t){return Object.fromEntries(Object.entries(e.generic??{}).map(([e,n])=>[e,this.parse(n,t)]))}useSiteAlias(e,t){return new qg(t,e.options===void 0?{name:e.name}:{name:e.name,options:e.options},this.parseGenericArgs(e,t))}applyUse(e,t,n,r){let i=e;return Object.keys(t).length>0&&i instanceof Vg&&(i=i.specialize(t)),n!==void 0&&Object.keys(n).length>0&&!Rg(i.narrow(n),i.options)&&(i=new Vg(this,i,{name:i.name,docs:i.docs,options:n,generic:i instanceof Vg?i.local.generic:void 0,useSite:!0},i instanceof Vg&&i.bindings?i.scope:void 0,r)),i}nearBuiltin(e){return e[0]===e[0]?.toLowerCase()&&am(e,this.typeClasses().map(e=>e.NAME))!==``}isBareNameDef(e){for(let t of[`extends`,`satisfies`,`generic`,`options`,`init`,`props`,`get`,`call`,`constraint`])if(e[t]!==void 0)return!1;return!0}parseInner(e,t){if(e.extends){let n=t.lookup(e.extends)??this.lookup(e.extends);if(!n)throw Error(`registry.parse: extends references unknown type '${e.extends}'${am(e.extends,this.typeNameCandidates())}`);let r=this.classes.get(e.extends),i=e.generic!==void 0&&Object.keys(e.generic).length>0,a=r&&!i?Qv.filter(t=>e[t]!==void 0&&(r.consumes??[]).includes(t)):[];if(r&&a.length>0){let n={name:e.extends,...a.includes(`props`)?{props:e.props}:{},...a.includes(`get`)?{get:e.get}:{},...a.includes(`call`)?{call:e.call}:{},...a.includes(`init`)?{init:e.init}:{}},i=r.from(n,t),o={...e};delete o.extends;for(let e of a)delete o[e];return new Vg(this,i,this.buildLocal(o,t))}return new Vg(this,n,this.buildLocal(e,t))}if(this.isBareNameDef(e)){let n=t;for(;n&&n!==this;){if(n.localLookup(e.name)!==void 0)return new qg(t,{name:e.name});n=n.parent}if(this.namedTypes.has(e.name))return this.namedTypes.get(e.name);let r=this.classes.get(e.name);return r?r.from(e,t):new qg(t,{name:e.name})}let n=this.isUseSiteDef(e);if(n&&this.boundAboveRegistry(e.name,t))return this.useSiteAlias(e,t);if(this.namedTypes.has(e.name)){let r=this.namedTypes.get(e.name);return n?this.applyUse(r,this.parseGenericArgs(e,t),e.options,t):e.generic&&r instanceof Vg?r.specialize(this.parseGenericArgs(e,t)):r}let r=this.classes.get(e.name);if(!r){if(n&&!this.nearBuiltin(e.name))return this.useSiteAlias(e,t);throw Error(`registry.parse: unknown type '${e.name}'${am(e.name,this.typeNameCandidates())}`)}let i=new Set(r.consumes??[]),a=Qv.filter(t=>e[t]!==void 0&&!i.has(t));if(a.length===0)return r.from(e,t);let o={...e};for(let e of a)delete o[e];let s=r.from(o,t),c={name:e.name,docs:e.docs,props:a.includes(`props`)&&e.props?ng.fromMap(e.props,t):void 0,get:a.includes(`get`)&&e.get?rg.from(e.get,t):void 0,call:a.includes(`call`)&&e.call?ig.from(e.call,t):void 0,init:a.includes(`init`)&&e.init?ag.from(e.init,t):void 0};return new Vg(this,s,c)}getTypesFor(e){let t=this.lookup(e);if(!t)return[];let n=[];for(let e of this.namedTypes.values())if(e!==t)try{t.compatible(e)&&n.push(e)}catch{}for(let[r,i]of this.classes){if(r===e)continue;let a;try{a=i.from({name:r},this)}catch{continue}try{t.compatible(a)&&n.push(a)}catch{}}return n}buildLocal(e,t){let n=e.generic?Object.fromEntries(Object.entries(e.generic).map(([e,n])=>[e,this.parse(n,t)])):void 0;return{name:e.name,docs:e.docs,options:e.options,generic:n,props:e.props?ng.fromMap(e.props,t):void 0,get:e.get?rg.from(e.get,t):void 0,call:e.call?ig.from(e.call,t):void 0,init:e.init?ag.from(e.init,t):void 0,constraint:e.constraint?this.parseExpr(e.constraint,t):void 0}}any(){return new Hg(this,{})}void(){return new b_(this,{})}null(){return new u_(this,{})}bool(e){return new Jg(this,e??{})}num(e){return new f_(this,e??{})}text(e){return new h_(this,e??{})}list(e,t){return new i_(this,e,t??{})}map(e,t){return new c_(this,e,t)}tuple(e){return new v_(this,[...e])}obj(e){return new Ug(this,e)}field(e,t){return{type:e,docs:t?.docs,default:t?.default===void 0?void 0:this.parseExpr(t.default)}}optional(e){return new p_(this,e)}nullable(e){return new d_(this,e)}not(e){return new l_(this,e)}or(e){return new m_(this,[...e])}and(e){return new Gg(this,[...e])}enum(e,t){return ey(e)?new Qg(this,this.text(),{values:Object.fromEntries(e.map(e=>[e,e]))}):new Qg(this,t??this.text(),{values:e})}literal(e,t){if(e instanceof U)return new r_(this,e,t);let n=this.primitiveOf(e);return new r_(this,n,e)}primitiveOf(e){switch(typeof e){case`string`:return this.text();case`number`:return this.num();case`boolean`:return this.bool()}}date(e){return new Xg(this,e??{})}timestamp(e){return new g_(this,e??{})}duration(){return new Zg(this,{})}color(e){return new Yg(this,e??{})}fn(e){return new t_(this,{args:e.args,returns:e.returns,throws:e.throws,get:e.call},e.generic??{})}iface(e){return new n_(this,{props:e.props?ng.fromMap(e.props,this):{},get:e.get?rg.from(e.get,this):void 0,call:e.call?ig.from(e.call,this):void 0})}alias(e){return new qg(this,{name:e})}typ(e){return new y_(this,e)}compatible(e){let t=[],n=new Set,r=e=>{n.has(e.name)||(n.add(e.name),t.push(e))};for(let t of this.typeClasses()){let n;try{n=t.from({name:t.NAME},this)}catch{continue}if(!(n.isUniversal()&&e.name!==t.NAME))try{n.compatible(e)&&r(n)}catch{continue}}for(let t of this.namedTypeList())try{t.compatible(e)&&r(t)}catch{continue}return t}like(e){let t=this.compatible(e).map(t=>t.like(e));return t.length===0?this.null():t.length===1?t[0]:this.or(t)}extend(e,t){let n=typeof e==`string`?this.lookup(e)??(()=>{throw Error(`extend: unknown base '${e}'`)})():e;return new Vg(this,n,t)}nativeExpr(e){return this.parseExpr({kind:`native`,id:e})}prop(e,t,n){return ty(new ng({type:e,get:this.nativeExpr(t),docs:n}))}method(e,t,n,r){return ty(new ng({type:this.fn({args:this.obj(e),returns:t,generic:r?.generic}),get:this.nativeExpr(n),docs:r?.docs}))}};function ey(e){return Array.isArray(e)}function ty(e){if(!ny(e))throw Error(`registry: a computed prop must carry a get expression`);return e}function ny(e){return e.get!==void 0}var ry=[Hg,b_,u_,Jg,f_,h_,i_,c_,v_,Ug,p_,d_,l_,m_,Gg,Qg,r_,t_,n_,y_,Xg,g_,Zg,Yg],iy=[hv,Nv,Pv,Fv,Lv,Vv,Hv,Uv,Gv,Yv,Rv,Zv];function ay(){let e=new $v;for(let t of ry)e.define(t);for(let t of iy)e.defineExpr(t);return mv(e),e}var oy={$Exit:{code:"/** gin `flow: exit` — unwinds to the outermost exported function, whose result becomes `value`. */\nclass $Exit {\n constructor(readonly value: unknown) {}\n}"},$Throw:{code:"/** gin `flow: throw` — a thrown gin value; a call step's `catch` handler receives `error`. */\nclass $Throw extends Error {\n constructor(readonly error: unknown) { super(typeof error === 'string' ? error : 'gin throw'); }\n}"},$str:{code:"/** Template placeholder text — `null`/`undefined` read as the empty string. */\nfunction $str(v: unknown): string {\n return v === undefined || v === null ? '' : String(v);\n}"},$template:{code:`/** A template whose text is only known at run time: \`{name}\` reads \`params.name\`. */
|
|
121
121
|
function $template(tmpl: string, params: Record<string, unknown> | undefined): string {
|
|
122
122
|
return tmpl.replace(/\\{(\\w+)\\}/g, (_, name: string) =>
|
|
123
123
|
params && Object.prototype.hasOwnProperty.call(params, name) ? $str(params[name]) : '');
|
|
@@ -366,37 +366,37 @@ const $color = {
|
|
|
366
366
|
const { h, s, l } = $color.hsl(c);
|
|
367
367
|
return \`hsl(\${Math.round(h)},\${Math.round(s * 100)}%,\${Math.round(l * 100)}%)\`;
|
|
368
368
|
},
|
|
369
|
-
};`}},Rv=new Set(`any.unknown.never.object.string.number.boolean.symbol.bigint.undefined.null.void.true.false.this.keyof.typeof.infer.is.asserts.readonly.unique.type.interface.enum.class.function.let.const.var.new.in.of.as.extends.implements.namespace.module.declare.abstract.async.await.yield.import.export.default.return.if.else.for.while.do.switch.case.break.continue.try.catch.finally.throw.delete.instanceof.super.with.debugger.package.private.protected.public.static.global.require.Array.ArrayBuffer.ArrayLike.AsyncGenerator.AsyncIterable.AsyncIterator.Atomics.Awaited.BigInt.BigInt64Array.BigUint64Array.Boolean.Capitalize.ConstructorParameters.DataView.Date.Error.EvalError.Exclude.Extract.Float32Array.Float64Array.Function.Generator.Infinity.InstanceType.Int16Array.Int32Array.Int8Array.Intl.Iterable.IterableIterator.Iterator.JSON.Lowercase.Map.Math.NaN.NonNullable.Number.Object.Omit.OmitThisParameter.Parameters.Partial.Pick.Promise.PromiseLike.PropertyKey.Proxy.RangeError.Readonly.ReadonlyArray.ReadonlyMap.ReadonlySet.Record.ReferenceError.Reflect.RegExp.Required.ReturnType.Set.SharedArrayBuffer.String.Symbol.SyntaxError.TemplateStringsArray.ThisParameterType.ThisType.TypeError.URIError.Uint16Array.Uint32Array.Uint8Array.Uint8ClampedArray.Uncapitalize.Uppercase.WeakMap.WeakRef.WeakSet.globalThis.console.eval.arguments`.split(`.`));function zv(e){return/^[A-Za-z_][\w$]*$/.test(e)&&!Rv.has(e)&&!(e in Lv)}function Bv(e){let t=e.replace(/[^\w]/g,`_`);return/^[A-Za-z_]/.test(t)||(t=`_`+t),zv(t)?t:`${t}_`}var Vv=class{taken=new Set;types=new Map;data=new Map;constructor(e,t){let n=e.namedTypeList().filter(e=>e instanceof vg&&!e.local.useSite).sort((e,t)=>e.name<t.name?-1:+(e.name>t.name));for(let e of n)zv(e.name)&&!this.taken.has(e.name)&&this.claim(this.types,e.name,e.name);for(let e of n)this.types.has(e.name)||this.type(e.name);for(let e of n){let n=!1;try{n=t(e)}catch{n=!1}n&&this.dataName(e.name)}}claim(e,t,n){let r=n;for(let e=2;this.taken.has(r);e++)r=`${n.replace(/_$/,``)}_${e}`;return this.taken.add(r),e.set(t,r),r}type(e){return this.types.get(e)??this.claim(this.types,e,Bv(e))}dataName(e){return this.data.get(e)??this.claim(this.data,e,`${this.type(e)}Data`)}fresh(e){return this.claim(new Map,e,Bv(e))}},Hv=(e,t)=>e===void 0||e===`undefined`||e===`null`?t:/^(-?\d[\d.e+-]*|"(?:[^"\\]|\\.)*"|true|false)$/.test(e)?e:`(${e} ?? ${t})`,J=(e,t)=>e.arg(t)??`undefined`,Uv=e=>t=>`(${t.self()} ${e} ${J(t,`other`)})`,Wv=(e,...t)=>n=>`${e}(${[n.self(),...t.map(e=>J(n,e))].join(`, `)})`,Gv=(e,...t)=>n=>`${n.self()}.${e}(${t.map(e=>J(n,e)).join(`, `)})`,Kv=e=>t=>`${t.self()}.${e}`,qv=e=>t=>`void ${e(t)}`,Jv=(e,...t)=>{let n=t.map(t=>e.arg(t));for(;n.length>0&&n[n.length-1]===void 0;)n.pop();return n.map(e=>e??`undefined`).join(`, `)},Yv=(e,...t)=>n=>{let r=n.fn(`fn`),i=t.map(e=>J(n,e));return r?r.sync?`${n.helper(`$`+e)}(${[n.self(),r.code,...i].join(`, `)})`:n.aw(`${n.helper(`$`+e+`Async`)}(${[n.self(),r.code,...i].join(`, `)})`):`${n.helper(`$`+e)}(${[n.self(),`undefined as any`,...i].join(`, `)})`},Xv=e=>t=>{let n=t.once(),r=t.fn(`fn`);if(!r)return n;let i=`(${r.code})({ value: ${n} })`;return`(${n} === ${e} ? ${e} : ${r.sync?i:t.aw(i)})`},Zv={"type.toAny":e=>e.self(),"any.typeOf":e=>{let t=e.staticTypeName();return t===void 0?`${e.helper(`$typeOf`)}(${e.self()})`:(e.discard(),JSON.stringify(t))},"any.is":e=>{let t=e.guard();return t?`${t}(${e.self()})`:(e.discard(),`true`)},"any.as":e=>{let t=e.guard();if(!t)return e.self();let n=e.once();return`(${t}(${n}) ? ${n} : undefined)`},"any.toText":e=>`String(${e.self()})`,"any.toBool":e=>`Boolean(${e.self()})`,"any.eq":Uv(`===`),"any.neq":Uv(`!==`),"void.toText":e=>(e.discard(),`"void"`),"void.toBool":e=>(e.discard(),`false`),"null.toText":e=>(e.discard(),`"null"`),"null.toBool":e=>(e.discard(),`false`),"not.typeOf":e=>`${e.helper(`$typeOf`)}(${e.self()})`,"not.toText":e=>`String(${e.self()})`,"bool.eq":Uv(`===`),"bool.neq":Uv(`!==`),"bool.and":Uv(`&&`),"bool.or":Uv(`||`),"bool.xor":Uv(`!==`),"bool.not":e=>`!${e.self()}`,"bool.toText":e=>{let t=e.arg(`trueText`),n=e.arg(`falseText`);return t===void 0&&n===void 0?`String(${e.self()})`:`(${e.self()} ? ${Hv(t,`"true"`)} : ${Hv(n,`"false"`)})`},"bool.toNum":e=>{let t=e.arg(`trueValue`),n=e.arg(`falseValue`);return`(${e.self()} ? ${Hv(t,`1`)} : ${Hv(n,`0`)})`},"num.eq":e=>e.arg(`epsilon`)===void 0?`${e.helper(`$numEq`)}(${e.self()}, ${J(e,`other`)})`:`${e.helper(`$numEq`)}(${e.self()}, ${J(e,`other`)}, ${e.arg(`epsilon`)})`,"num.neq":e=>e.arg(`epsilon`)===void 0?`!${e.helper(`$numEq`)}(${e.self()}, ${J(e,`other`)})`:`!${e.helper(`$numEq`)}(${e.self()}, ${J(e,`other`)}, ${e.arg(`epsilon`)})`,"num.lt":Uv(`<`),"num.lte":Uv(`<=`),"num.gt":Uv(`>`),"num.gte":Uv(`>=`),"num.add":Uv(`+`),"num.sub":Uv(`-`),"num.mul":Uv(`*`),"num.div":Uv(`/`),"num.mod":Uv(`%`),"num.pow":Uv(`**`),"num.abs":Wv(`Math.abs`),"num.neg":e=>`(-${e.self()})`,"num.sign":Wv(`Math.sign`),"num.sqrt":Wv(`Math.sqrt`),"num.min":Wv(`Math.min`,`other`),"num.max":Wv(`Math.max`,`other`),"num.clamp":e=>`Math.min(Math.max(${e.self()}, ${J(e,`min`)}), ${J(e,`max`)})`,"num.floor":Wv(`Math.floor`),"num.ceil":Wv(`Math.ceil`),"num.round":Wv(`Math.round`),"num.isZero":e=>`(Math.abs(${e.self()}) <= 0)`,"num.isPositive":e=>`(${e.self()} > 0)`,"num.isNegative":e=>`(${e.self()} < 0)`,"num.isInteger":Wv(`Number.isInteger`),"num.isEven":e=>`(${e.self()} % 2 === 0)`,"num.isOdd":e=>`(Math.abs(${e.self()}) % 2 === 1)`,"num.toText":e=>e.arg(`precision`)===void 0?`String(${e.self()})`:`${e.helper(`$numText`)}(${e.self()}, ${e.arg(`precision`)})`,"num.toBool":e=>`(${e.self()} !== 0)`,"text.length":Kv(`length`),"text.eq":Uv(`===`),"text.neq":Uv(`!==`),"text.contains":Gv(`includes`,`search`),"text.startsWith":Gv(`startsWith`,`prefix`),"text.endsWith":Gv(`endsWith`,`suffix`),"text.trim":Gv(`trim`),"text.trimStart":Gv(`trimStart`),"text.trimEnd":Gv(`trimEnd`),"text.upper":Gv(`toUpperCase`),"text.lower":Gv(`toLowerCase`),"text.slice":e=>`${e.self()}.slice(${Jv(e,`start`,`end`)})`,"text.replace":e=>`${e.self()}.split(${J(e,`search`)}).join(${J(e,`replacement`)})`,"text.split":Gv(`split`,`separator`),"text.concat":Uv(`+`),"text.repeat":Gv(`repeat`,`count`),"text.indexOf":e=>`${e.self()}.indexOf(${Jv(e,`search`,`from`)})`,"text.lastIndexOf":e=>`${e.self()}.lastIndexOf(${Jv(e,`search`,`from`)})`,"text.match":e=>`(${e.self()}.match(new RegExp(${J(e,`pattern`)}, "g")) ?? [] as string[])`,"text.test":e=>`new RegExp(${J(e,`pattern`)}).test(${e.self()})`,"text.isEmpty":e=>`(${e.self()}.length === 0)`,"text.isNotEmpty":e=>`(${e.self()}.length > 0)`,"text.toNum":Wv(`Number`),"text.toBool":e=>`(${e.self()}.length > 0)`,"list.length":Kv(`length`),"list.at":e=>`${e.helper(`$listAt`)}(${e.self()}, ${J(e,`index`)})`,"list.push":qv(Gv(`push`,`value`)),"list.pop":Gv(`pop`),"list.shift":Gv(`shift`),"list.unshift":qv(Gv(`unshift`,`value`)),"list.insert":e=>`void ${e.self()}.splice(${J(e,`index`)}, 0, ${J(e,`value`)})`,"list.remove":e=>`${e.self()}.splice(${J(e,`index`)}, 1)[0]!`,"list.clear":e=>`void (${e.self()}.length = 0)`,"list.slice":e=>`${e.self()}.slice(${Jv(e,`start`,`end`)})`,"list.concat":Gv(`concat`,`other`),"list.reverse":e=>`[...${e.self()}].reverse()`,"list.join":e=>`${e.self()}.map(String).join(${Hv(e.arg(`separator`),`","`)})`,"list.indexOf":Gv(`indexOf`,`value`),"list.contains":e=>`(${e.self()}.indexOf(${J(e,`value`)}) !== -1)`,"list.unique":e=>`[...new Set(${e.self()})]`,"list.duplicates":e=>`${e.helper(`$duplicates`)}(${e.self()})`,"list.map":Yv(`map`),"list.filter":Yv(`filter`),"list.find":Yv(`find`),"list.reduce":Yv(`reduce`,`initial`),"list.some":Yv(`some`),"list.every":Yv(`every`),"list.sort":e=>e.arg(`fn`)===void 0?`${e.helper(`$sortNatural`)}(${e.self()})`:Yv(`sort`)(e),"list.isEmpty":e=>`(${e.self()}.length === 0)`,"list.isNotEmpty":e=>`(${e.self()}.length > 0)`,"list.first":e=>`${e.self()}[0]`,"list.last":e=>`${e.self()}.at(-1)`,"map.size":Kv(`size`),"map.at":Gv(`get`,`key`),"map.has":Gv(`has`,`key`),"map.delete":Gv(`delete`,`key`),"map.clear":qv(Gv(`clear`)),"map.keys":e=>`[...${e.self()}.keys()]`,"map.values":e=>`[...${e.self()}.values()]`,"map.isEmpty":e=>`(${e.self()}.size === 0)`,"map.isNotEmpty":e=>`(${e.self()}.size > 0)`,"object.keys":e=>(e.discard(),JSON.stringify(e.fields())),"object.values":e=>{let t=e.once();return`[${e.fields().map(e=>ey(t,e)).join(`, `)}]`},"object.entries":e=>{let t=e.once();return`[${e.fields().map(e=>`[${JSON.stringify(e)}, ${ey(t,e)}] as [string, unknown]`).join(`, `)}]`},"object.has":e=>(e.discard(),`(${JSON.stringify(e.fields())} as string[]).includes(${J(e,`key`)})`),"object.eq":e=>`${e.helper(`$deepEq`)}(${e.self()}, ${J(e,`other`)})`,"object.neq":e=>`!${e.helper(`$deepEq`)}(${e.self()}, ${J(e,`other`)})`,"object.toText":e=>`${e.helper(`$objText`)}(${e.self()} as any, ${JSON.stringify(e.fields())})`,"tuple.length":Kv(`length`),"tuple.first":e=>`${e.self()}[0]`,"tuple.last":e=>{let t=e.once();return`${t}[${t}.length - 1]`},"tuple.toList":e=>`[...${e.self()}]`,"optional.value":e=>`${e.helper(`$optValue`)}(${e.self()})`,"optional.has":e=>`(${e.self()} !== undefined)`,"optional.or":e=>{let t=e.once();return`(${t} !== undefined ? ${t} : ${J(e,`fallback`)})`},"optional.map":Xv(`undefined`),"nullable.value":e=>`${e.helper(`$nullValue`)}(${e.self()})`,"nullable.isNull":e=>`(${e.self()} === null)`,"nullable.or":e=>{let t=e.once();return`(${t} !== null ? ${t} : ${J(e,`fallback`)})`},"nullable.map":Xv(`null`),"enum.name":e=>{let t=ny(e.selfType),n={};for(let[e,r]of Object.entries(t?.options.values??{}))n[String(r)]=e;return`((${JSON.stringify(n)} as Record<string, string>)[String(${e.self()})] ?? "")`},"enum.value":e=>e.self(),"enum.eq":Uv(`===`),"enum.neq":Uv(`!==`),"enum.toText":e=>`String(${e.self()})`,"date.year":Gv(`getUTCFullYear`),"date.month":e=>`(${e.self()}.getUTCMonth() + 1)`,"date.day":Gv(`getUTCDate`),"date.dayOfWeek":Gv(`getUTCDay`),"date.dayOfYear":e=>`${e.helper(`$date`)}.dayOfYear(${e.self()})`,"date.eq":e=>`(${e.self()}.getTime() === ${J(e,`other`)}.getTime())`,"date.neq":e=>`(${e.self()}.getTime() !== ${J(e,`other`)}.getTime())`,"date.before":e=>`(${e.self()}.getTime() < ${J(e,`other`)}.getTime())`,"date.after":e=>`(${e.self()}.getTime() > ${J(e,`other`)}.getTime())`,"date.addDays":e=>`${e.helper(`$date`)}.addDays(${e.self()}, ${J(e,`days`)})`,"date.addMonths":e=>`${e.helper(`$date`)}.addMonths(${e.self()}, ${J(e,`months`)})`,"date.addYears":e=>`${e.helper(`$date`)}.addYears(${e.self()}, ${J(e,`years`)})`,"date.diffDays":e=>`${e.helper(`$date`)}.diffDays(${e.self()}, ${J(e,`other`)})`,"date.diffMonths":e=>`${e.helper(`$date`)}.diffMonths(${e.self()}, ${J(e,`other`)})`,"date.diffYears":e=>`(${e.self()}.getUTCFullYear() - ${J(e,`other`)}.getUTCFullYear())`,"date.toText":e=>`${e.self()}.toISOString().slice(0, 10)`,"timestamp.year":Gv(`getUTCFullYear`),"timestamp.month":e=>`(${e.self()}.getUTCMonth() + 1)`,"timestamp.day":Gv(`getUTCDate`),"timestamp.hour":Gv(`getUTCHours`),"timestamp.minute":Gv(`getUTCMinutes`),"timestamp.second":Gv(`getUTCSeconds`),"timestamp.millisecond":Gv(`getUTCMilliseconds`),"timestamp.eq":e=>`(${e.self()}.getTime() === ${J(e,`other`)}.getTime())`,"timestamp.before":e=>`(${e.self()}.getTime() < ${J(e,`other`)}.getTime())`,"timestamp.after":e=>`(${e.self()}.getTime() > ${J(e,`other`)}.getTime())`,"timestamp.addDuration":e=>`new Date(${e.self()}.getTime() + ${J(e,`duration`)})`,"timestamp.subDuration":e=>`new Date(${e.self()}.getTime() - ${J(e,`duration`)})`,"timestamp.diff":e=>`(${e.self()}.getTime() - ${J(e,`other`)}.getTime())`,"timestamp.toDate":e=>`${e.helper(`$date`)}.toDate(${e.self()})`,"timestamp.toEpoch":Gv(`getTime`),"timestamp.toText":Gv(`toISOString`),"duration.init":e=>`${e.helper(`$duration`)}.init(${e.self()})`,"duration.totalSeconds":e=>`(${e.self()} / 1000)`,"duration.totalMinutes":e=>`(${e.self()} / 60000)`,"duration.totalHours":e=>`(${e.self()} / 3600000)`,"duration.totalDays":e=>`(${e.self()} / 86400000)`,"duration.days":e=>`Math.trunc(${e.self()} / 86400000)`,"duration.hours":e=>`(Math.trunc(${e.self()} / 3600000) % 24)`,"duration.minutes":e=>`(Math.trunc(${e.self()} / 60000) % 60)`,"duration.seconds":e=>`(Math.trunc(${e.self()} / 1000) % 60)`,"duration.ms":e=>`(${e.self()} % 1000)`,"duration.toText":e=>`${e.helper(`$duration`)}.toText(${e.self()})`,"color.init":e=>`${e.helper(`$color`)}.init(${e.self()})`,"color.hue":e=>`${e.helper(`$color`)}.hsl(${e.self()}).h`,"color.saturation":e=>`${e.helper(`$color`)}.hsl(${e.self()}).s`,"color.lightness":e=>`${e.helper(`$color`)}.hsl(${e.self()}).l`,"color.eq":Uv(`===`),"color.neq":Uv(`!==`),"color.lighten":e=>`${e.helper(`$color`)}.lighten(${e.self()}, ${J(e,`amount`)})`,"color.darken":e=>`${e.helper(`$color`)}.lighten(${e.self()}, -${J(e,`amount`)})`,"color.saturate":e=>`${e.helper(`$color`)}.saturate(${e.self()}, ${J(e,`amount`)})`,"color.desaturate":e=>`${e.helper(`$color`)}.saturate(${e.self()}, -${J(e,`amount`)})`,"color.opacity":e=>`${e.helper(`$color`)}.opacity(${e.self()}, ${J(e,`alpha`)})`,"color.invert":e=>`${e.helper(`$color`)}.invert(${e.self()})`,"color.mix":e=>`${e.helper(`$color`)}.mix(${e.self()}, ${Jv(e,`other`,`weight`)})`,"color.complement":e=>`${e.helper(`$color`)}.complement(${e.self()})`,"color.toHex":e=>`${e.helper(`$color`)}.toHex(${e.self()})`,"color.toRgb":e=>`${e.helper(`$color`)}.toRgb(${e.self()})`,"color.toHsl":e=>`${e.helper(`$color`)}.toHsl(${e.self()})`,"color.toText":e=>`${e.helper(`$color`)}.toHex(${e.self()})`};for(let e of[`color.r`,`color.g`,`color.b`,`color.a`]){let t=e.slice(-1);Zv[e]=e=>`${e.helper(`$color`)}.${t}(${e.self()})`}var Qv={"list.indexGet":e=>`${e.helper(`$listGet`)}(${e.self}, ${e.key})`,"text.charAt":e=>`${e.helper(`$charAt`)}(${e.self}, ${e.key})`,"map.indexGet":e=>`${e.helper(`$mapGet`)}(${e.self}, ${e.key})`,"object.indexGet":e=>`(${e.self} as any)[${e.key}]`,"tuple.at":e=>`${e.self}[${e.key}]`},$v={"list.indexSet":e=>`${e.helper(`$listSet`)}(${e.self}, ${e.key}, ${e.value})`,"map.indexSet":e=>`${e.self}.set(${e.key}, ${e.value})`,"object.indexSet":e=>`(${e.self} as any)[${e.key}] = ${e.value}`,"tuple.setAt":e=>`${e.self}[${e.key}] = ${e.value}`};function ey(e,t){return ty(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function ty(e){return/^[A-Za-z_$][\w$]*$/.test(e)}function ny(e){let t=e;for(let e=0;e<10&&t;e++){if(t instanceof kg)return t;t=t.base}}var ry=class extends Error{constructor(e){super(`gin \u2192 TypeScript: ${e.length} problem${e.length===1?``:`s`}
|
|
369
|
+
};`}},sy=new Set(`any.unknown.never.object.string.number.boolean.symbol.bigint.undefined.null.void.true.false.this.keyof.typeof.infer.is.asserts.readonly.unique.type.interface.enum.class.function.let.const.var.new.in.of.as.extends.implements.namespace.module.declare.abstract.async.await.yield.import.export.default.return.if.else.for.while.do.switch.case.break.continue.try.catch.finally.throw.delete.instanceof.super.with.debugger.package.private.protected.public.static.global.require.Array.ArrayBuffer.ArrayLike.AsyncGenerator.AsyncIterable.AsyncIterator.Atomics.Awaited.BigInt.BigInt64Array.BigUint64Array.Boolean.Capitalize.ConstructorParameters.DataView.Date.Error.EvalError.Exclude.Extract.Float32Array.Float64Array.Function.Generator.Infinity.InstanceType.Int16Array.Int32Array.Int8Array.Intl.Iterable.IterableIterator.Iterator.JSON.Lowercase.Map.Math.NaN.NonNullable.Number.Object.Omit.OmitThisParameter.Parameters.Partial.Pick.Promise.PromiseLike.PropertyKey.Proxy.RangeError.Readonly.ReadonlyArray.ReadonlyMap.ReadonlySet.Record.ReferenceError.Reflect.RegExp.Required.ReturnType.Set.SharedArrayBuffer.String.Symbol.SyntaxError.TemplateStringsArray.ThisParameterType.ThisType.TypeError.URIError.Uint16Array.Uint32Array.Uint8Array.Uint8ClampedArray.Uncapitalize.Uppercase.WeakMap.WeakRef.WeakSet.globalThis.console.eval.arguments`.split(`.`));function cy(e){return/^[A-Za-z_][\w$]*$/.test(e)&&!sy.has(e)&&!(e in oy)}function ly(e){let t=e.replace(/[^\w]/g,`_`);return/^[A-Za-z_]/.test(t)||(t=`_`+t),cy(t)?t:`${t}_`}var uy=class{taken=new Set;types=new Map;data=new Map;constructor(e,t){let n=e.namedTypeList().filter(e=>e instanceof Vg&&!e.local.useSite).sort((e,t)=>e.name<t.name?-1:+(e.name>t.name));for(let e of n)cy(e.name)&&!this.taken.has(e.name)&&this.claim(this.types,e.name,e.name);for(let e of n)this.types.has(e.name)||this.type(e.name);for(let e of n){let n=!1;try{n=t(e)}catch{n=!1}n&&this.dataName(e.name)}}claim(e,t,n){let r=n;for(let e=2;this.taken.has(r);e++)r=`${n.replace(/_$/,``)}_${e}`;return this.taken.add(r),e.set(t,r),r}type(e){return this.types.get(e)??this.claim(this.types,e,ly(e))}dataName(e){return this.data.get(e)??this.claim(this.data,e,`${this.type(e)}Data`)}fresh(e){return this.claim(new Map,e,ly(e))}},dy=(e,t)=>e===void 0||e===`undefined`||e===`null`?t:/^(-?\d[\d.e+-]*|"(?:[^"\\]|\\.)*"|true|false)$/.test(e)?e:`(${e} ?? ${t})`,J=(e,t)=>e.arg(t)??`undefined`,fy=e=>t=>`(${t.self()} ${e} ${J(t,`other`)})`,py=(e,...t)=>n=>`${e}(${[n.self(),...t.map(e=>J(n,e))].join(`, `)})`,my=(e,...t)=>n=>`${n.self()}.${e}(${t.map(e=>J(n,e)).join(`, `)})`,hy=e=>t=>`${t.self()}.${e}`,gy=e=>t=>`void ${e(t)}`,_y=(e,...t)=>{let n=t.map(t=>e.arg(t));for(;n.length>0&&n[n.length-1]===void 0;)n.pop();return n.map(e=>e??`undefined`).join(`, `)},vy=(e,...t)=>n=>{let r=n.fn(`fn`),i=t.map(e=>J(n,e));return r?r.sync?`${n.helper(`$`+e)}(${[n.self(),r.code,...i].join(`, `)})`:n.aw(`${n.helper(`$`+e+`Async`)}(${[n.self(),r.code,...i].join(`, `)})`):`${n.helper(`$`+e)}(${[n.self(),`undefined as any`,...i].join(`, `)})`},yy=e=>t=>{let n=t.once(),r=t.fn(`fn`);if(!r)return n;let i=`(${r.code})({ value: ${n} })`;return`(${n} === ${e} ? ${e} : ${r.sync?i:t.aw(i)})`},by={"type.toAny":e=>e.self(),"any.typeOf":e=>{let t=e.staticTypeName();return t===void 0?`${e.helper(`$typeOf`)}(${e.self()})`:(e.discard(),JSON.stringify(t))},"any.is":e=>{let t=e.guard();return t?`${t}(${e.self()})`:(e.discard(),`true`)},"any.as":e=>{let t=e.guard();if(!t)return e.self();let n=e.once();return`(${t}(${n}) ? ${n} : undefined)`},"any.toText":e=>`String(${e.self()})`,"any.toBool":e=>`Boolean(${e.self()})`,"any.eq":fy(`===`),"any.neq":fy(`!==`),"void.toText":e=>(e.discard(),`"void"`),"void.toBool":e=>(e.discard(),`false`),"null.toText":e=>(e.discard(),`"null"`),"null.toBool":e=>(e.discard(),`false`),"not.typeOf":e=>`${e.helper(`$typeOf`)}(${e.self()})`,"not.toText":e=>`String(${e.self()})`,"bool.eq":fy(`===`),"bool.neq":fy(`!==`),"bool.and":fy(`&&`),"bool.or":fy(`||`),"bool.xor":fy(`!==`),"bool.not":e=>`!${e.self()}`,"bool.toText":e=>{let t=e.arg(`trueText`),n=e.arg(`falseText`);return t===void 0&&n===void 0?`String(${e.self()})`:`(${e.self()} ? ${dy(t,`"true"`)} : ${dy(n,`"false"`)})`},"bool.toNum":e=>{let t=e.arg(`trueValue`),n=e.arg(`falseValue`);return`(${e.self()} ? ${dy(t,`1`)} : ${dy(n,`0`)})`},"num.eq":e=>e.arg(`epsilon`)===void 0?`${e.helper(`$numEq`)}(${e.self()}, ${J(e,`other`)})`:`${e.helper(`$numEq`)}(${e.self()}, ${J(e,`other`)}, ${e.arg(`epsilon`)})`,"num.neq":e=>e.arg(`epsilon`)===void 0?`!${e.helper(`$numEq`)}(${e.self()}, ${J(e,`other`)})`:`!${e.helper(`$numEq`)}(${e.self()}, ${J(e,`other`)}, ${e.arg(`epsilon`)})`,"num.lt":fy(`<`),"num.lte":fy(`<=`),"num.gt":fy(`>`),"num.gte":fy(`>=`),"num.add":fy(`+`),"num.sub":fy(`-`),"num.mul":fy(`*`),"num.div":fy(`/`),"num.mod":fy(`%`),"num.pow":fy(`**`),"num.abs":py(`Math.abs`),"num.neg":e=>`(-${e.self()})`,"num.sign":py(`Math.sign`),"num.sqrt":py(`Math.sqrt`),"num.min":py(`Math.min`,`other`),"num.max":py(`Math.max`,`other`),"num.clamp":e=>`Math.min(Math.max(${e.self()}, ${J(e,`min`)}), ${J(e,`max`)})`,"num.floor":py(`Math.floor`),"num.ceil":py(`Math.ceil`),"num.round":py(`Math.round`),"num.isZero":e=>`(Math.abs(${e.self()}) <= 0)`,"num.isPositive":e=>`(${e.self()} > 0)`,"num.isNegative":e=>`(${e.self()} < 0)`,"num.isInteger":py(`Number.isInteger`),"num.isEven":e=>`(${e.self()} % 2 === 0)`,"num.isOdd":e=>`(Math.abs(${e.self()}) % 2 === 1)`,"num.toText":e=>e.arg(`precision`)===void 0?`String(${e.self()})`:`${e.helper(`$numText`)}(${e.self()}, ${e.arg(`precision`)})`,"num.toBool":e=>`(${e.self()} !== 0)`,"text.length":hy(`length`),"text.eq":fy(`===`),"text.neq":fy(`!==`),"text.contains":my(`includes`,`search`),"text.startsWith":my(`startsWith`,`prefix`),"text.endsWith":my(`endsWith`,`suffix`),"text.trim":my(`trim`),"text.trimStart":my(`trimStart`),"text.trimEnd":my(`trimEnd`),"text.upper":my(`toUpperCase`),"text.lower":my(`toLowerCase`),"text.slice":e=>`${e.self()}.slice(${_y(e,`start`,`end`)})`,"text.replace":e=>`${e.self()}.split(${J(e,`search`)}).join(${J(e,`replacement`)})`,"text.split":my(`split`,`separator`),"text.concat":fy(`+`),"text.repeat":my(`repeat`,`count`),"text.indexOf":e=>`${e.self()}.indexOf(${_y(e,`search`,`from`)})`,"text.lastIndexOf":e=>`${e.self()}.lastIndexOf(${_y(e,`search`,`from`)})`,"text.match":e=>`(${e.self()}.match(new RegExp(${J(e,`pattern`)}, "g")) ?? [] as string[])`,"text.test":e=>`new RegExp(${J(e,`pattern`)}).test(${e.self()})`,"text.isEmpty":e=>`(${e.self()}.length === 0)`,"text.isNotEmpty":e=>`(${e.self()}.length > 0)`,"text.toNum":py(`Number`),"text.toBool":e=>`(${e.self()}.length > 0)`,"list.length":hy(`length`),"list.at":e=>`${e.helper(`$listAt`)}(${e.self()}, ${J(e,`index`)})`,"list.push":gy(my(`push`,`value`)),"list.pop":my(`pop`),"list.shift":my(`shift`),"list.unshift":gy(my(`unshift`,`value`)),"list.insert":e=>`void ${e.self()}.splice(${J(e,`index`)}, 0, ${J(e,`value`)})`,"list.remove":e=>`${e.self()}.splice(${J(e,`index`)}, 1)[0]!`,"list.clear":e=>`void (${e.self()}.length = 0)`,"list.slice":e=>`${e.self()}.slice(${_y(e,`start`,`end`)})`,"list.concat":my(`concat`,`other`),"list.reverse":e=>`[...${e.self()}].reverse()`,"list.join":e=>`${e.self()}.map(String).join(${dy(e.arg(`separator`),`","`)})`,"list.indexOf":my(`indexOf`,`value`),"list.contains":e=>`(${e.self()}.indexOf(${J(e,`value`)}) !== -1)`,"list.unique":e=>`[...new Set(${e.self()})]`,"list.duplicates":e=>`${e.helper(`$duplicates`)}(${e.self()})`,"list.map":vy(`map`),"list.filter":vy(`filter`),"list.find":vy(`find`),"list.reduce":vy(`reduce`,`initial`),"list.some":vy(`some`),"list.every":vy(`every`),"list.sort":e=>e.arg(`fn`)===void 0?`${e.helper(`$sortNatural`)}(${e.self()})`:vy(`sort`)(e),"list.isEmpty":e=>`(${e.self()}.length === 0)`,"list.isNotEmpty":e=>`(${e.self()}.length > 0)`,"list.first":e=>`${e.self()}[0]`,"list.last":e=>`${e.self()}.at(-1)`,"map.size":hy(`size`),"map.at":my(`get`,`key`),"map.has":my(`has`,`key`),"map.delete":my(`delete`,`key`),"map.clear":gy(my(`clear`)),"map.keys":e=>`[...${e.self()}.keys()]`,"map.values":e=>`[...${e.self()}.values()]`,"map.isEmpty":e=>`(${e.self()}.size === 0)`,"map.isNotEmpty":e=>`(${e.self()}.size > 0)`,"object.keys":e=>(e.discard(),JSON.stringify(e.fields())),"object.values":e=>{let t=e.once();return`[${e.fields().map(e=>Cy(t,e)).join(`, `)}]`},"object.entries":e=>{let t=e.once();return`[${e.fields().map(e=>`[${JSON.stringify(e)}, ${Cy(t,e)}] as [string, unknown]`).join(`, `)}]`},"object.has":e=>(e.discard(),`(${JSON.stringify(e.fields())} as string[]).includes(${J(e,`key`)})`),"object.eq":e=>`${e.helper(`$deepEq`)}(${e.self()}, ${J(e,`other`)})`,"object.neq":e=>`!${e.helper(`$deepEq`)}(${e.self()}, ${J(e,`other`)})`,"object.toText":e=>`${e.helper(`$objText`)}(${e.self()} as any, ${JSON.stringify(e.fields())})`,"tuple.length":hy(`length`),"tuple.first":e=>`${e.self()}[0]`,"tuple.last":e=>{let t=e.once();return`${t}[${t}.length - 1]`},"tuple.toList":e=>`[...${e.self()}]`,"optional.value":e=>`${e.helper(`$optValue`)}(${e.self()})`,"optional.has":e=>`(${e.self()} !== undefined)`,"optional.or":e=>{let t=e.once();return`(${t} !== undefined ? ${t} : ${J(e,`fallback`)})`},"optional.map":yy(`undefined`),"nullable.value":e=>`${e.helper(`$nullValue`)}(${e.self()})`,"nullable.isNull":e=>`(${e.self()} === null)`,"nullable.or":e=>{let t=e.once();return`(${t} !== null ? ${t} : ${J(e,`fallback`)})`},"nullable.map":yy(`null`),"enum.name":e=>{let t=Ty(e.selfType),n={};for(let[e,r]of Object.entries(t?.options.values??{}))n[String(r)]=e;return`((${JSON.stringify(n)} as Record<string, string>)[String(${e.self()})] ?? "")`},"enum.value":e=>e.self(),"enum.eq":fy(`===`),"enum.neq":fy(`!==`),"enum.toText":e=>`String(${e.self()})`,"date.year":my(`getUTCFullYear`),"date.month":e=>`(${e.self()}.getUTCMonth() + 1)`,"date.day":my(`getUTCDate`),"date.dayOfWeek":my(`getUTCDay`),"date.dayOfYear":e=>`${e.helper(`$date`)}.dayOfYear(${e.self()})`,"date.eq":e=>`(${e.self()}.getTime() === ${J(e,`other`)}.getTime())`,"date.neq":e=>`(${e.self()}.getTime() !== ${J(e,`other`)}.getTime())`,"date.before":e=>`(${e.self()}.getTime() < ${J(e,`other`)}.getTime())`,"date.after":e=>`(${e.self()}.getTime() > ${J(e,`other`)}.getTime())`,"date.addDays":e=>`${e.helper(`$date`)}.addDays(${e.self()}, ${J(e,`days`)})`,"date.addMonths":e=>`${e.helper(`$date`)}.addMonths(${e.self()}, ${J(e,`months`)})`,"date.addYears":e=>`${e.helper(`$date`)}.addYears(${e.self()}, ${J(e,`years`)})`,"date.diffDays":e=>`${e.helper(`$date`)}.diffDays(${e.self()}, ${J(e,`other`)})`,"date.diffMonths":e=>`${e.helper(`$date`)}.diffMonths(${e.self()}, ${J(e,`other`)})`,"date.diffYears":e=>`(${e.self()}.getUTCFullYear() - ${J(e,`other`)}.getUTCFullYear())`,"date.toText":e=>`${e.self()}.toISOString().slice(0, 10)`,"timestamp.year":my(`getUTCFullYear`),"timestamp.month":e=>`(${e.self()}.getUTCMonth() + 1)`,"timestamp.day":my(`getUTCDate`),"timestamp.hour":my(`getUTCHours`),"timestamp.minute":my(`getUTCMinutes`),"timestamp.second":my(`getUTCSeconds`),"timestamp.millisecond":my(`getUTCMilliseconds`),"timestamp.eq":e=>`(${e.self()}.getTime() === ${J(e,`other`)}.getTime())`,"timestamp.before":e=>`(${e.self()}.getTime() < ${J(e,`other`)}.getTime())`,"timestamp.after":e=>`(${e.self()}.getTime() > ${J(e,`other`)}.getTime())`,"timestamp.addDuration":e=>`new Date(${e.self()}.getTime() + ${J(e,`duration`)})`,"timestamp.subDuration":e=>`new Date(${e.self()}.getTime() - ${J(e,`duration`)})`,"timestamp.diff":e=>`(${e.self()}.getTime() - ${J(e,`other`)}.getTime())`,"timestamp.toDate":e=>`${e.helper(`$date`)}.toDate(${e.self()})`,"timestamp.toEpoch":my(`getTime`),"timestamp.toText":my(`toISOString`),"duration.init":e=>`${e.helper(`$duration`)}.init(${e.self()})`,"duration.totalSeconds":e=>`(${e.self()} / 1000)`,"duration.totalMinutes":e=>`(${e.self()} / 60000)`,"duration.totalHours":e=>`(${e.self()} / 3600000)`,"duration.totalDays":e=>`(${e.self()} / 86400000)`,"duration.days":e=>`Math.trunc(${e.self()} / 86400000)`,"duration.hours":e=>`(Math.trunc(${e.self()} / 3600000) % 24)`,"duration.minutes":e=>`(Math.trunc(${e.self()} / 60000) % 60)`,"duration.seconds":e=>`(Math.trunc(${e.self()} / 1000) % 60)`,"duration.ms":e=>`(${e.self()} % 1000)`,"duration.toText":e=>`${e.helper(`$duration`)}.toText(${e.self()})`,"color.init":e=>`${e.helper(`$color`)}.init(${e.self()})`,"color.hue":e=>`${e.helper(`$color`)}.hsl(${e.self()}).h`,"color.saturation":e=>`${e.helper(`$color`)}.hsl(${e.self()}).s`,"color.lightness":e=>`${e.helper(`$color`)}.hsl(${e.self()}).l`,"color.eq":fy(`===`),"color.neq":fy(`!==`),"color.lighten":e=>`${e.helper(`$color`)}.lighten(${e.self()}, ${J(e,`amount`)})`,"color.darken":e=>`${e.helper(`$color`)}.lighten(${e.self()}, -${J(e,`amount`)})`,"color.saturate":e=>`${e.helper(`$color`)}.saturate(${e.self()}, ${J(e,`amount`)})`,"color.desaturate":e=>`${e.helper(`$color`)}.saturate(${e.self()}, -${J(e,`amount`)})`,"color.opacity":e=>`${e.helper(`$color`)}.opacity(${e.self()}, ${J(e,`alpha`)})`,"color.invert":e=>`${e.helper(`$color`)}.invert(${e.self()})`,"color.mix":e=>`${e.helper(`$color`)}.mix(${e.self()}, ${_y(e,`other`,`weight`)})`,"color.complement":e=>`${e.helper(`$color`)}.complement(${e.self()})`,"color.toHex":e=>`${e.helper(`$color`)}.toHex(${e.self()})`,"color.toRgb":e=>`${e.helper(`$color`)}.toRgb(${e.self()})`,"color.toHsl":e=>`${e.helper(`$color`)}.toHsl(${e.self()})`,"color.toText":e=>`${e.helper(`$color`)}.toHex(${e.self()})`};for(let e of[`color.r`,`color.g`,`color.b`,`color.a`]){let t=e.slice(-1);by[e]=e=>`${e.helper(`$color`)}.${t}(${e.self()})`}var xy={"list.indexGet":e=>`${e.helper(`$listGet`)}(${e.self}, ${e.key})`,"text.charAt":e=>`${e.helper(`$charAt`)}(${e.self}, ${e.key})`,"map.indexGet":e=>`${e.helper(`$mapGet`)}(${e.self}, ${e.key})`,"object.indexGet":e=>`(${e.self} as any)[${e.key}]`,"tuple.at":e=>`${e.self}[${e.key}]`},Sy={"list.indexSet":e=>`${e.helper(`$listSet`)}(${e.self}, ${e.key}, ${e.value})`,"map.indexSet":e=>`${e.self}.set(${e.key}, ${e.value})`,"object.indexSet":e=>`(${e.self} as any)[${e.key}] = ${e.value}`,"tuple.setAt":e=>`${e.self}[${e.key}] = ${e.value}`};function Cy(e,t){return wy(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function wy(e){return/^[A-Za-z_$][\w$]*$/.test(e)}function Ty(e){let t=e;for(let e=0;e<10&&t;e++){if(t instanceof Qg)return t;t=t.base}}var Ey=class extends Error{constructor(e){super(`gin \u2192 TypeScript: ${e.length} problem${e.length===1?``:`s`}
|
|
370
370
|
- ${e.join(`
|
|
371
|
-
- `)}`),this.problems=e,this.name=`TypeScriptExportError`}problems},
|
|
372
|
-
`));return t.length===1?`/** ${
|
|
371
|
+
- `)}`),this.problems=e,this.name=`TypeScriptExportError`}problems},Dy=class{constructor(e){this.ctxAllowed=e}ctxAllowed;awaited=!1;loops=[]},Oy=new Set(`break.case.catch.class.const.continue.debugger.default.delete.do.else.enum.export.extends.false.finally.for.function.if.import.in.instanceof.new.null.return.super.switch.this.throw.true.try.typeof.var.void.while.with.as.implements.interface.let.package.private.protected.public.static.yield.await.async.undefined.arguments.eval.ctx.args.self.Promise.Math.Number.String.Boolean.Date.Map.Set.Array.Object.JSON.Error.RegExp`.split(`.`)),ky=/^(-?\d[\d.e+-]*|"(?:[^"\\]|\\.)*"|true|false|null|undefined)$/,Ay=class{constructor(e,t={}){this.engine=e,this.registry=e.registry,this.opt={types:t.types??`referenced`,includeComments:t.includeComments??!0,prelude:t.prelude??`separate`,async:t.async??`always`,export:t.export??!1,scope:t.scope??{}},this.names=new uy(this.registry,e=>this.splits(this.decl(e)))}engine;registry;types=new Map;helpers=new Map;problems=new Set;opt;names;defined=new Set;makers=new Map;guards=new Map;used=new Set;ctxVars=new Map;usesExit=!1;get always(){return this.opt.async===`always`}get exp(){return this.opt.export?`export `:``}problem(e){this.problems.add(e)}check(){if(this.problems.size>0)throw new Ey([...this.problems])}uniq(e){let t=e.replace(/[^\w$]/g,`_`);/^[A-Za-z_$]/.test(t)||(t=`_`+t),(/^make[A-Z]/.test(t)||/^is[A-Z]/.test(t)||t.startsWith(`$`))&&(t=`_`+t);let n=Oy.has(t)||this.used.has(t)?`${t}_1`:t;for(let e=2;this.used.has(n);e++)n=`${t}_${e}`;return this.used.add(n),n}tsName(e){return this.names.type(e)}helper(e){if(this.helpers.has(e))return e;let t=oy[e];if(!t)throw Error(`gin \u2192 TypeScript: no prelude helper '${e}'`);for(let e of t.deps??[])this.helper(e);return this.helpers.set(e,t.code),e}ref(e,t={generics:new Set}){if(e instanceof qg){let n=e.options.name;if(t.generics.has(n))return n;let r=e.simplify();if(r!==e&&!(r instanceof qg))return this.ref(r,t);let i=this.registry.lookup(n);return i&&!(i instanceof qg)?this.ref(i,t):`any`}if(e instanceof Vg)return this.namedRef(e,t);if(e instanceof Hg)return`any`;if(e instanceof b_)return`void`;if(e instanceof u_)return`null`;if(e instanceof Jg)return`boolean`;if(e instanceof f_||e instanceof Zg||e instanceof Yg)return`number`;if(e instanceof h_)return`string`;if(e instanceof Xg||e instanceof g_)return`Date`;if(e instanceof i_)return Jy(this.ref(e.item,t));if(e instanceof c_)return`Map<${this.ref(e.key,t)}, ${this.ref(e.value,t)}>`;if(e instanceof v_)return`[${e.elements.map(e=>this.ref(e,t)).join(`, `)}]`;if(e instanceof p_)return qy([this.ref(e.inner,t),`undefined`]);if(e instanceof d_)return qy([this.ref(e.inner,t),`null`]);if(e instanceof m_)return qy(e.variants.map(e=>this.ref(e,t)));if(e instanceof Gg)return e.parts.map(e=>Ky(this.ref(e,t))).join(` & `)||`unknown`;if(e instanceof Qg){let t=Object.values(e.options.values).map(e=>JSON.stringify(e));return t.length?t.join(` | `):`never`}if(e instanceof r_)return JSON.stringify(e.literal);if(e instanceof t_){let n=e.call();return n?this.fnSig(n,t,`unknown`,e.generic):`(...args: any[]) => any`}if(e instanceof Ug)return this.objLiteralType(Object.entries(e.fields),t);if(e instanceof n_){let n=this.members(Object.entries(e._props),t,void 0);return e._call&&n.push(`(${this.params(e._call.args,t)}): ${this.returns(e._call,t,`unknown`)}`),Gy(n)}return e instanceof l_||e instanceof y_?`unknown`:`any`}decl(e){let t=this.registry.lookup(e.name);return t instanceof Vg&&t.name===e.name?t:e}namedRef(e,t,n=!1){if(e.local.useSite)return e.original instanceof Vg?this.namedRef(e.original,t,n):this.ref(e.original,t);let r=this.decl(e);this.define(r);let i=n&&this.splits(r)?this.dataName(r):this.tsName(r.name),a=Object.keys(r.generic??{});if(a.length===0)return i;let o=a.map(n=>{let r=e.generic?.[n];return r&&!U.isGenericPlaceholder(n,r)?this.ref(r,t):t.generics.has(n)?n:`any`});return o.every(e=>e===`any`)?i:`${i}<${o.join(`, `)}>`}define(e){if(this.defined.has(e.name))return;this.defined.add(e.name);let t=this.maker(e);this.declaration(e,t)}surface(e){let t=e.definitionProps();return Object.entries(t).map(([e,t])=>[e,ng.from(t)])}definitionCall(e){return e.definitionCall()}splits(e){if(!Ny(e.base))return!1;if(this.definitionCall(e)||this.surface(e).some(([,e])=>My(e)))return!0;let t=e.original;return t instanceof Vg&&!t.local.useSite&&this.splits(this.decl(t))}carriedMembers(e){let t=new Map,n=new Set;for(let r=e;r instanceof Vg&&!r.local.useSite;r=r.original)for(let[e,i]of this.surface(this.decl(r)))n.has(e)||(n.add(e),My(i)&&(!i.get||i.get instanceof Zv)&&t.set(e,i));return[...t]}dataName(e){return this.names.dataName(e.name)}declaration(e,t){if(this.opt.types===`none`)return;let n=this.tsName(e.name),r=e.generic??{},i={generics:new Set(Object.keys(r))},a=this.genericParams(r,i);if(!this.splits(e)){this.types.set(n,this.singleDeclaration(e,t));return}let o=Object.keys(r).length?`<${Object.keys(r).join(`, `)}>`:``,s=e.original,c=s instanceof Vg&&!s.local.useSite,l=this.surface(e),u=this.members(l.filter(([,e])=>!My(e)),i,t),d=this.members(l.filter(([,e])=>My(e)),i,t),f=this.definitionCall(e);f&&d.push(`(${this.params(f.args,i)}): ${this.returns(f,i,`unknown`)}`);let p=this.dataName(e),m=[];c&&m.push(this.namedRef(s,i,!0)),(u.length||m.length===0)&&m.push(Gy(u));let h=[`The stored fields of ${n}${t?` \u2014 what \`${t.name}\` takes`:``}.`];this.types.set(p,`${this.docBlock(h)}${this.exp}type ${p}${a} = ${m.join(` & `)};`);let ee=[];c&&ee.push(this.namedRef(s,i)),ee.push(`${p}${o}`),d.length&&ee.push(Gy(d)),this.types.set(n,`${this.docBlock(this.typeDocs(e))}${this.exp}type ${n}${a} = ${ee.join(` & `)};`)}typeDocs(e){let t=[];return e.docs&&t.push(e.docs),e.local.options&&Object.keys(e.local.options).length>0&&t.push(`gin: ${e.base.toCode(void 0,{includeComments:!1})}`),e.local.constraint&&t.push(`constraint: ${e.local.constraint.toCode(this.registry,{expectsValue:!0,includeComments:!1})}`),t}singleDeclaration(e,t){let n=this.tsName(e.name),r=e.generic??{},i={generics:new Set(Object.keys(r))},a=this.genericParams(r,i),o=this.typeDocs(e),s=e.original,c=s instanceof Vg&&!s.local.useSite,l=Ny(e.base),u=this.definitionCall(e),d=l||c?this.members(this.surface(e),i,t):[];u&&d.push(`(${this.params(u.args,i)}): ${this.returns(u,i,`unknown`)}`);let f;if(c){let e=this.ref(s,i);f=d.length?`${e} & ${Gy(d)}`:e}else l?f=Gy(d):(f=this.ref(e.base,i),d.length&&(f=`${Ky(f)} & ${Gy(d)}`));return`${this.docBlock(o)}${this.exp}type ${n}${a} = ${f};`}genericParams(e,t){let n=Object.keys(e);return n.length===0?``:`<${n.map(n=>{let r=e[n];if(U.isGenericPlaceholder(n,r))return`${n} = any`;let i=this.ref(r,t);return`${n} extends ${i} = ${i}`}).join(`, `)}>`}members(e,t,n){let r=[];for(let[i,a]of e){let e=wy(i)?i:JSON.stringify(i),o=[];a.docs&&o.push(a.docs);let s=a.type.call(),c=n?.members.get(i);if(s&&(a.get||a.type instanceof t_)){let n=c?c.async===!1?`sync`:`async`:this.hostMemberKind(a);r.push(`${this.docLine(o)}${e}: ${this.fnSig(s,t,n,a.type.generic)}`);continue}if(a.get){let n=this.ref(a.type,t);r.push(`${this.docLine(o)}readonly ${e}: ${c?.async===!0?`Promise<${n}>`:n}`);continue}let l=a.type.isOptional(),u=l?a.type.required():a.type,d=Hy(u);d&&o.push(d),r.push(`${this.docLine(o)}${e}${l?`?`:``}: ${this.ref(u,t)}`)}return r}hostMemberKind(e){return this.always?`async`:e.get instanceof Zv&&!by[e.get.id]?e.get.effects()&(B.EXTERNAL|B.SYSTEM)?`async`:`sync`:e.get instanceof Zv?`sync`:`unknown`}objLiteralType(e,t){return Gy(this.members(e,t,void 0))}fnSig(e,t,n,r){let i=Object.keys(r??{}),a=i.length?{generics:new Set([...t.generics,...i])}:t;return`${i.length?this.genericParams(r,a):``}(${this.params(e.args,a)}) => ${this.returns(e,a,n)}`}returns(e,t,n){let r=e.returns?this.ref(e.returns,t):`any`;return n===`sync`?r:n===`async`||this.always?`Promise<${r}>`:`${Ky(r)} | Promise<${r}>`}params(e,t){if(e instanceof Ug){let n=Object.entries(e.fields);return n.length===0?``:`args${n.every(([,e])=>e.type.isOptional()||e.default!==void 0)?`?`:``}: ${this.objLiteralType(n,t)}`}return e instanceof Hg||e instanceof b_?``:`args: ${this.ref(e,t)}`}defParams(e,t){let n=this.params(e,t);return n.startsWith(`args?:`)?`args:${n.slice(6)} = {}`:n}docBlock(e){if(!this.opt.includeComments||e.length===0)return``;let t=e.flatMap(e=>e.split(`
|
|
372
|
+
`));return t.length===1?`/** ${Xy(t[0])} */
|
|
373
373
|
`:`/**
|
|
374
|
-
${t.map(e=>` * ${
|
|
374
|
+
${t.map(e=>` * ${Xy(e)}`).join(`
|
|
375
375
|
`)}
|
|
376
376
|
*/
|
|
377
|
-
`}docLine(e){return!this.opt.includeComments||e.length===0?``:`/** ${
|
|
378
|
-
`);return this.helpers.set(i.name,h),this.declaration(e,i),i}guard(e){let t=this.ref(e),n=t,r=this.guards.get(n);if(r)return r;let i=e instanceof
|
|
377
|
+
`}docLine(e){return!this.opt.includeComments||e.length===0?``:`/** ${Xy(e.join(` · `).replace(/\n/g,` `))} */ `}maker(e){if(this.makers.has(e.name))return this.makers.get(e.name)??void 0;let t=e.definitionProps(),n=Object.entries(t).map(([e,t])=>[e,ng.from(t)]).filter(([,e])=>e.get&&!(e.get instanceof Zv)),r=e.original instanceof Vg&&!e.original.local.useSite?this.maker(this.decl(e.original)):void 0;if(n.length===0&&!r){this.makers.set(e.name,null);return}if(!Ny(e.base)){this.problem(`type '${e.name}': members written in gin on a non-object type are not supported`),this.makers.set(e.name,null);return}let i={name:`make${this.tsName(e.name)}`,members:new Map(r?.members??[])};for(let[e,t]of n)i.members.set(e,{kind:t.type.call()?`method`:`computed`,async:`pending`});this.makers.set(e.name,i);let a=e.generic??{},o={generics:new Set(Object.keys(a))},s=this.genericParams(a,o),c=Object.keys(a).length?`<${Object.keys(a).join(`, `)}>`:``,l=`${this.tsName(e.name)}${c}`;this.define(e);let u=new Set(this.used);this.used.clear();let d=`self`,f=[];f.push(r?`const ${d} = ${r.name}(data) as ${l};`:`const ${d} = data as ${l};`);for(let[t,r]of n){let n=new Dy(!1),a=[],s=new Map([[`this`,{ts:d,type:e}]]),c=r.type.call();if(c){let e=this.uniq(t);s.set(`args`,{ts:`args`,type:c.args}),s.set(`recurse`,{ts:e,type:r.type}),this.stmt(r.get,s,n,a,{kind:`return`});let l=this.always||n.awaited;i.members.set(t,{kind:`method`,async:l});let u=this.defParams(c.args,o);f.push(`${Cy(d,t)} = ${l?`async `:``}function ${e}(${u}) {`),f.push(...Uy(a),`};`)}else this.stmt(r.get,s,n,a,{kind:`return`}),i.members.set(t,{kind:`computed`,async:n.awaited}),f.push(`Object.defineProperty(${d}, ${JSON.stringify(t)}, {`),f.push(` get: ${n.awaited?`async `:``}() => {`,...Uy(Uy(a)),` },`),f.push(` enumerable: false,`,` configurable: true,`,`});`)}f.push(`return ${d};`),this.used.clear();for(let e of u)this.used.add(e);let p=this.members(this.carriedMembers(e),o,i),m=`${this.dataName(e)}${c}${p.length?` & ${Gy(p)}`:``}`,h=[`/** Attach ${e.name}'s gin-written members to its data. */`,`${this.exp}function ${i.name}${s}(data: ${m}): ${l} {`,...Uy(f),`}`].join(`
|
|
378
|
+
`);return this.helpers.set(i.name,h),this.declaration(e,i),i}guard(e){let t=this.ref(e),n=t,r=this.guards.get(n);if(r)return r;let i=e instanceof Vg?`$is${this.tsName(this.decl(e).name)}`:`$is_${$y(t)}`;this.guards.set(n,i);let a=this.checkExpr(e,`v`,0,!0);return this.helpers.set(i,`function ${i}(v: unknown): v is ${t} {
|
|
379
379
|
return ${a};
|
|
380
|
-
}`),i}checkExpr(e,t,n,r=!1){let i=`x${n}`;if(e instanceof
|
|
380
|
+
}`),i}checkExpr(e,t,n,r=!1){let i=`x${n}`;if(e instanceof qg){let r=e.simplify();return r===e?`true`:this.checkExpr(r,t,n)}if(e instanceof Vg)return r?this.checkExpr(e.base,t,n):`${this.guard(e)}(${t})`;if(e instanceof f_||e instanceof Zg||e instanceof Yg)return`typeof ${t} === "number"`;if(e instanceof h_)return`typeof ${t} === "string"`;if(e instanceof Jg)return`typeof ${t} === "boolean"`;if(e instanceof u_)return`${t} === null`;if(e instanceof b_)return`${t} === undefined`;if(e instanceof Xg||e instanceof g_)return`${t} instanceof Date`;if(e instanceof t_)return`typeof ${t} === "function"`;if(e instanceof c_)return`${t} instanceof Map`;if(e instanceof i_){let r=this.checkExpr(e.item,i,n+1);return r===`true`?`Array.isArray(${t})`:`(Array.isArray(${t}) && ${t}.every((${i}: unknown) => ${r}))`}if(e instanceof v_){let r=e.elements.map((e,r)=>this.checkExpr(e,`${t}[${r}]`,n+1));return`(Array.isArray(${t}) && ${t}.length === ${e.elements.length}${r.map(e=>` && ${e}`).join(``)})`}if(e instanceof p_)return`(${t} === undefined || ${this.checkExpr(e.inner,t,n)})`;if(e instanceof d_)return`(${t} === null || ${this.checkExpr(e.inner,t,n)})`;if(e instanceof m_)return`(${e.variants.map(e=>this.checkExpr(e,t,n)).join(` || `)})`;if(e instanceof Gg)return`(${e.parts.map(e=>this.checkExpr(e,t,n)).join(` && `)})`;if(e instanceof Qg)return`${JSON.stringify(Object.values(e.options.values))}.includes(${t} as any)`;if(e instanceof r_)return`${t} === ${JSON.stringify(e.literal)}`;if(e instanceof Ug||e instanceof n_){let r=e instanceof Ug?Object.entries(e.fields):Object.entries(e._props),i=[`typeof ${t} === "object"`,`${t} !== null`];for(let[e,a]of r){if(a.get||a.type.call())continue;let r=`(${t} as any)${wy(e)?`.`+e:`[${JSON.stringify(e)}]`}`;i.push(a.type.isOptional()?`(${r} === undefined || ${this.checkExpr(a.type.required(),r,n+1)})`:this.checkExpr(a.type,r,n+1))}return`(${i.join(` && `)})`}return`true`}exportFunction(e,t){this.ctxVars=new Map,this.usesExit=!1,(!wy(t)||Oy.has(t))&&this.problem(`'${t}' is not usable as a function name`);let n=t;this.used.add(t);let r=new Dy(!0),i=[],a=[],o=``;if(e instanceof Gv){let t=e.fnType.call(),s={generics:new Set(Object.keys(e.fnType.generic??{}))},c=new Map([[`args`,{ts:`args`,type:t?.args??this.registry.obj({})}],[`recurse`,{ts:n,type:e.fnType}]]);e.constraint&&this.constraint(e.constraint,c,r,i),this.stmt(e.body,c,r,i,{kind:`return`}),a=[(t?this.defParams(t.args,s):``)||`args: {} = {}`],t?.returns&&(o=this.ref(t.returns,s))}else this.stmt(e,new Map,r,i,{kind:`return`});let s=this.always||r.awaited;if(this.ctxVars.size>0){let e=this.names.fresh(`${Qy(t)}Ctx`),n=[...this.ctxVars].map(([e,t])=>{let n=this.engine.getGlobal(e),r=n?.docs?[n.docs]:[];return`${this.docLine(r)}${wy(e)?e:JSON.stringify(e)}: ${this.ref(t)}`});this.types.set(e,`${this.docBlock([`Free variables ${t} reads (engine globals and run extras).`])}${this.exp}type ${e} = ${Gy(n)};`),a.push(`ctx: ${e}`)}let c=i;if(this.usesExit){let e=this.helper(`$Exit`);c=[`try {`,...Uy(i),`} catch ($exit) {`,` if ($exit instanceof ${e}) return $exit.value as any;`,` throw $exit;`,`}`]}let l=o?`: ${s?`Promise<${o}>`:o}`:``;return[`${e.comment?this.docBlock([e.comment]):``}${this.exp}${s?`async `:``}function ${n}(${a.join(`, `)})${l} {`,...Uy(c),`}`].join(`
|
|
381
381
|
`)}constraint(e,t,n,r){let i=this.val(e,t,n,r),a=JSON.stringify(`lambda constraint failed: ${e.toCode(this.registry,{expectsValue:!0,includeComments:!1})}`);r.push(`if (${i.code} !== true) throw new Error(${a});`)}stmt(e,t,n,r,i){if(e.comment&&this.opt.includeComments&&r.push(...e.comment.split(`
|
|
382
|
-
`).map(e=>`// ${e}`)),e instanceof
|
|
382
|
+
`).map(e=>`// ${e}`)),e instanceof Lv){if(e.lines.length===0)return this.finish(`undefined`,r,i,!0);e.lines.forEach((a,o)=>this.stmt(a,t,n,r,o===e.lines.length-1?i:{kind:`discard`}));return}if(e instanceof Fv){let a=this.defineVars(e,t,n,r);return this.stmt(e.body,a,n,r,i)}if(e instanceof Vv)return this.ifStmt(e,t,n,r,i);if(e instanceof Hv)return this.switchStmt(e,t,n,r,i);if(e instanceof Uv){this.loop(e,t,n,r),i.kind===`assign`&&r.push(`${i.name} = undefined;`);return}if(e instanceof Rv)return this.flow(e,t,n,r);if(e instanceof Pv)return this.set(e,t,n,r),this.finish(`true`,r,i,!0);let a=this.val(e,t,n,r);this.finish(a.code,r,i,a.pure)}finish(e,t,n,r){n.kind===`return`?e!==`undefined`&&t.push(`return ${Yy(e)};`):n.kind===`assign`?t.push(`${n.name} = ${Yy(e)};`):r||t.push(`${Yy(e)};`)}defineVars(e,t,n,r){let i=new Map(t);for(let t of e.vars){let e=this.val(t.value,i,n,r),a=this.uniq(t.name),o=t.type??e.type,s=t.type?`: ${this.ref(t.type)}`:``;r.push(`let ${a}${s} = ${Yy(e.code)};`),i.set(t.name,{ts:a,type:o,sync:e.sync})}return i}ifStmt(e,t,n,r,i){let a=(r,o)=>{if(r>=e.ifs.length){e.otherwise&&this.stmt(e.otherwise,t,n,o,i);return}let s=e.ifs[r],c=this.val(s.condition,t,n,o),l=[];this.stmt(s.body,t,n,l,i),o.push(`if (${Yy(c.code)}) {`,...Uy(l),`}`);let u=[];a(r+1,u),u.length!==0&&(u[0].startsWith(`if (`)&&Wy(u)?(o[o.length-1]=`} else ${u[0]}`,o.push(...u.slice(1))):(o[o.length-1]=`} else {`,o.push(...Uy(u),`}`)))};a(0,r)}switchStmt(e,t,n,r,i){let a=this.spill(this.val(e.value,t,n,r),r,`sw`),o=[];if(e.cases.forEach((e,r)=>{let s=[],c=e.equals.map(e=>this.val(e,t,n,s).code);s.length&&this.problem(`switch: a case value that needs statements is not supported`);let l=[];this.stmt(e.body,t,n,l,i);let u=c.length?c.map(e=>`${a} === ${e}`).join(` || `):`false`;o.push(`${r===0?`if`:`} else if`} (${u}) {`,...Uy(l))}),e.otherwise){let a=[];if(this.stmt(e.otherwise,t,n,a,i),o.length===0){r.push(...a);return}o.push(`} else {`,...Uy(a))}o.length&&r.push(...o,`}`)}flow(e,t,n,r){let i=n.loops[n.loops.length-1];switch(e.action){case`break`:i===`for`?r.push(`break;`):this.problem(i===`parallel`?`flow: break inside a parallel loop is not supported`:`flow: break outside a loop`);return;case`continue`:i===`for`?r.push(`continue;`):i===`parallel`?r.push(`return;`):this.problem(`flow: continue outside a loop`);return;case`return`:{i===`parallel`&&this.problem(`flow: return inside a parallel loop is not supported`);let a=e.value?this.val(e.value,t,n,r).code:void 0;r.push(a&&a!==`undefined`?`return ${Yy(a)};`:`return;`);return}case`exit`:{let i=e.value?this.val(e.value,t,n,r).code:`undefined`;this.usesExit=!0,r.push(`throw new ${this.helper(`$Exit`)}(${Yy(i)});`);return}case`throw`:{let i=e.error?this.val(e.error,t,n,r).code:`undefined`;r.push(`throw new ${this.helper(`$Throw`)}(${Yy(i)});`);return}}}loop(e,t,n,r){let i=this.registry.any(),a=this.typeOfExpr(e.over,t),o=a.get(),s=o?.loop instanceof Zv?o.loop.id:void 0,c=e.keyName??`key`,l=e.valueName??`value`,u=this.uniq(c),d=this.uniq(l),f=new Map(t);if(f.set(c,{ts:u,type:o?.key??i}),f.set(l,{ts:d,type:o?.value??i}),e.parallel)return this.parallelLoop(e,t,n,r,f,s,u,d,!!o?.loopDynamic);let p=[];if(n.loops.push(`for`),this.stmt(e.body,f,n,p,{kind:`discard`}),n.loops.pop(),o?.loopDynamic){let i=[],a=this.val(e.over,t,n,i);r.push(`for (let ${u} = 0; ; ${u}++) {`,...Uy(i),` const ${d} = ${Yy(a.code)};`,` if (!${d}) break;`,...Uy(p),`}`);return}let m=this.spill(this.val(e.over,t,n,r),r,`over`);switch(s){case`list.iterate`:case`tuple.iterate`:r.push(`for (let ${u} = 0; ${u} < ${m}.length; ${u}++) {`,` const ${d} = ${m}[${u}];`,...Uy(p),`}`);return;case`text.chars`:r.push(`for (let ${u} = 0; ${u} < ${m}.length; ${u}++) {`,` const ${d} = ${m}[${u}]!;`,...Uy(p),`}`);return;case`map.iterate`:r.push(`for (const [${u}, ${d}] of ${m}) {`,...Uy(p),`}`);return;case`num.loop`:{let e=this.uniq(`count`);r.push(`for (let ${u} = 0, ${e} = Math.abs(Math.trunc(${m})); ${u} < ${e}; ${u}++) {`,` const ${d} = ${m} < 0 ? -${u} : ${u};`,...Uy(p),`}`);return}case`object.iterate`:{let e=JSON.stringify(Fy(a));r.push(`for (const ${u} of ${e}) {`,` const ${d} = (${m} as any)[${u}];`,` if (${d} === undefined) continue;`,...Uy(p),`}`);return}default:this.problem(`loop: iterating '${a.toCode()}' is not supported (only built-in iterables)`)}}parallelLoop(e,t,n,r,i,a,o,s,c){if(c){this.problem(`loop: a parallel while-loop is not supported`);return}let l=e.parallel?.concurrent?this.val(e.parallel.concurrent,t,n,r).code:`undefined`,u=e.parallel?.rate?this.val(e.parallel.rate,t,n,r).code:`undefined`,d=this.typeOfExpr(e.over,t),f=this.spill(this.val(e.over,t,n,r),r,`over`),p;switch(a){case`list.iterate`:case`tuple.iterate`:p=`${f}.entries()`;break;case`text.chars`:p=`${f}.split("").entries()`;break;case`map.iterate`:p=f;break;case`num.loop`:p=`Array.from({ length: Math.abs(Math.trunc(${f})) }, (_, i) => [i, ${f} < 0 ? -i : i] as [number, number])`;break;case`object.iterate`:p=`${JSON.stringify(Fy(d))}.map((f) => [f, (${f} as any)[f]] as [string, any]).filter((e) => e[1] !== undefined)`;break;default:this.problem(`loop: iterating '${d.toCode()}' is not supported (only built-in iterables)`);return}let m=[],h=new Dy(n.ctxAllowed);h.loops.push(`parallel`),this.stmt(e.body,i,h,m,{kind:`discard`}),n.awaited=!0,r.push(`await ${this.helper(`$parallel`)}(${p}, ${l}, ${u}, async (${o}, ${s}) => {`,...Uy(m),`});`)}val(e,t,n,r){if(e instanceof hv)return this.newValue(e,t,n,r);if(e instanceof Nv)return this.path(e.path.steps,t,n,r);if(e instanceof Pv)return this.set(e,t,n,r),{code:`true`,type:this.registry.bool(),pure:!0};if(e instanceof Gv)return this.lambda(e,t,n);if(e instanceof Yv)return this.template(e,t,n,r);if(e instanceof Lv){if(e.lines.length===0)return{code:`undefined`,type:this.registry.void(),pure:!0};for(let i of e.lines.slice(0,-1))this.stmt(i,t,n,r,{kind:`discard`});return this.val(e.lines[e.lines.length-1],t,n,r)}if(e instanceof Fv)return this.val(e.body,this.defineVars(e,t,n,r),n,r);if(e instanceof Vv)return this.ifValue(e,t,n,r);if(e instanceof Hv||e instanceof Uv){let i=this.uniq(`v`);return r.push(`let ${i};`),this.stmt(e,t,n,r,{kind:`assign`,name:i}),{code:i,type:this.typeOfExpr(e,t),pure:!0}}return e instanceof Rv?(this.flow(e,t,n,r),{code:`undefined as never`,type:this.registry.void(),pure:!0}):e instanceof Zv?(this.problem(`native '${e.id}' used directly as an expression is not supported`),{code:`undefined as any`,type:this.registry.any(),pure:!0}):(this.problem(`expression kind '${e.kind}' is not supported`),{code:`undefined as any`,type:this.registry.any(),pure:!0})}ifValue(e,t,n,r){let i=[],a=e.ifs.map(e=>{let r=[],a=this.val(e.condition,t,n,r),o=[],s=this.val(e.body,t,n,o);return i.push(r,o),{cb:r,c:a,bb:o,v:s}}),o=[],s=e.otherwise?this.val(e.otherwise,t,n,o):void 0;i.push(o);let c=this.typeOfExpr(e,t);if(i.every(e=>e.length===0)){let e=s?s.code:`undefined`;for(let t=a.length-1;t>=0;t--)e=`${a[t].c.code} ? ${a[t].v.code} : ${e}`;return{code:`(${e})`,type:c,pure:a.every(e=>e.c.pure&&e.v.pure)&&(s?.pure??!0)}}let l=this.uniq(`v`);r.push(`let ${l};`);let u=(e,t)=>{if(e>=a.length){s&&t.push(...o,`${l} = ${Yy(s.code)};`);return}let n=a[e];t.push(...n.cb,`if (${Yy(n.c.code)}) {`,...Uy([...n.bb,`${l} = ${Yy(n.v.code)};`]),`}`);let r=[];u(e+1,r),r.length&&(t[t.length-1]=`} else {`,t.push(...Uy(r),`}`))};return u(0,r),{code:l,type:c,pure:!0}}template(e,t,n,r){let i=this.registry.text(),a=e.params?this.val(e.params,t,n,r):void 0,o=a?this.spill(a,r,`params`):void 0,s=e.template instanceof hv&&typeof e.template.value==`string`?e.template.value:void 0;if(s===void 0){let a=this.val(e.template,t,n,r);return{code:`${this.helper(`$template`)}(${a.code}, ${o??`undefined`} as any)`,type:i,pure:!1}}let c=a?Iy(a.type):void 0,l="`",u=0;for(let e of s.matchAll(/\{(\w+)\}/g)){l+=Zy(s.slice(u,e.index)),u=e.index+e[0].length;let r=e[1],i;if(o&&c?.has(r))i={code:Cy(o,r),type:c.get(r)};else if(o&&!c)i={code:`(${o} as any)[${JSON.stringify(r)}]`,type:this.registry.any()};else{let e=this.lookup(r,t,n);e&&(i={code:e.ts,type:e.type})}i&&(l+="${"+(Ry(i.type)?i.code:`${this.helper(`$str`)}(${i.code})`)+`}`)}return l+=Zy(s.slice(u))+"`",{code:l,type:i,pure:!0}}lambda(e,t,n){let r=e.fnType.call(),i={generics:new Set(Object.keys(e.fnType.generic??{}))},a=this.uniq(`recurse`),o=new Dy(n.ctxAllowed),s=new Map(t);s.set(`args`,{ts:`args`,type:r?.args??this.registry.obj({})}),s.set(`recurse`,{ts:a,type:e.fnType});let c=[];e.constraint&&this.constraint(e.constraint,s,o,c),this.stmt(e.body,s,o,c,{kind:`return`});let l=this.always||o.awaited,u=r?this.defParams(r.args,i):``,d=r?.returns?`: ${l?`Promise<${this.ref(r.returns,i)}>`:this.ref(r.returns,i)}`:``,f=Object.keys(e.fnType.generic??{}).length?this.genericParams(e.fnType.generic,i):``,p=c.some(e=>RegExp(`\\b${a.replace(/\$/g,`\\$`)}\\b`).test(e)),m;if(p)m=[`${l?`async `:``}function ${a}${f}(${u})${d} {`,...Uy(c),`}`].join(`
|
|
383
383
|
`);else if(c.length===1&&c[0].startsWith(`return `)&&!c[0].includes(`
|
|
384
|
-
`)){let e=c[0].slice(7,-1);e.startsWith(`{`)&&(e=`(${e})`),m=`${l?`async `:``}${f}(${u})${d} => ${e}`}else m=[`${l?`async `:``}${f}(${u})${d} => {`,...
|
|
385
|
-
`);return{code:`(${m})`,type:e.fnType,pure:!0,sync:!l}}newValue(e,t,n,r){let i=e.type,a=i.init();if(e.value!==void 0&&a){let t=a.run instanceof Ov?a.run.id:void 0;if(t!==`duration.init`&&t!==`color.init`)return this.problem(`new ${i.toCode()}: a constructor written in gin is not supported`),{code:`undefined as any`,type:i,pure:!0};let n=this.literal(a.args.parse(e.value).toLogical(),a.args);return{code:`${this.helper(t===`duration.init`?`$duration`:`$color`)}.init(${n})`,type:i,pure:!0}}if(e.value===void 0){let e=this.construct(i,this.literal(new W(i,i.create()).toLogical(),i));return{code:e,type:i,pure:!e.startsWith(`make`)}}let o=this.fill(e.value,i,t,n,r);return{code:o.code,type:i,pure:o.pure}}fill(e,t,n,r,i){let a=e instanceof th?e:Mh(e,t.scope??this.registry);if(a){let e=this.val(a,n,r,i);return{code:e.code,pure:e.pure}}if(!_y(e,this.registry))try{let n=this.construct(t,this.literal(t.parse(e).toLogical(),t));return{code:n,pure:!n.startsWith(`make`)}}catch(e){return this.problem(`new ${t.toCode()}: ${e instanceof Error?e.message:String(e)}`),{code:`undefined as any`,pure:!0}}if(t instanceof wg)return this.fill(e,t.simplify(),n,r,i);if(t instanceof Wg||t instanceof Hg)return e===void 0?{code:`undefined`,pure:!0}:e===null?{code:`null`,pure:!0}:this.fill(e,t.inner,n,r,i);let o=e=>this.ordered(e.map(([e,t,i])=>a=>{let o=this.fill(t,i,n,r,a);return{code:o.code,pure:o.pure,key:e}}),i);if(t instanceof Fg&&Array.isArray(e))return{code:`[${o(e.map(e=>[void 0,e,t.item])).map(e=>e.code).join(`, `)}]`,pure:!1};if(t instanceof Yg&&Array.isArray(e))return{code:`[${o(e.map((e,n)=>[void 0,e,t.elements[n]??this.registry.any()])).map(e=>e.code).join(`, `)}] as ${this.ref(t)}`,pure:!1};if(t instanceof zg&&Array.isArray(e)){let n=[];for(let r of e){let[e,i]=Array.isArray(r)?r:[r?.key,r?.value];n.push([void 0,e,t.key],[void 0,i,t.value])}let r=o(n),i=[];for(let e=0;e<r.length;e+=2)i.push(`[${r[e].code}, ${r[e+1].code}]`);return{code:`new Map<${this.ref(t.key)}, ${this.ref(t.value)}>([${i.join(`, `)}])`,pure:!1}}let s=dy(t);if(s&&e&&typeof e==`object`&&!Array.isArray(e)){let a=e,c=[],l=[];for(let[e,t]of s)e in a?c.push([e,a[e],t.type]):t.default&&l.push([e,t.default]);let u=o(c);for(let[e,t]of l)u.push({key:e,code:this.val(t,n,r,i).code});let d=u.map(e=>`${ty(e.key)?e.key:JSON.stringify(e.key)}: ${e.code}`);return{code:this.construct(t,`{ ${d.join(`, `)} }`),pure:!1}}return this.problem(`new ${t.toCode()}: payload shape not supported`),{code:`undefined as any`,pure:!0}}construct(e,t){let n=e instanceof vg&&!e.local.useSite?this.decl(e):void 0;if(n){this.define(n);let e=this.carriedMembers(n).map(([e])=>e);e.length&&this.problem(`new ${n.name}: its host member${e.length>1?`s`:``} ${e.join(`, `)} cannot be supplied in TypeScript \u2014 build the value on the host (\`make${this.tsName(n.name)}\` / \`${this.dataName(n)}\`) and pass it in`);let r=this.maker(n);if(r)return`${r.name}(${t})`}return t.startsWith(`[`)||t.startsWith(`{`)||n?`(${t} as ${this.ref(e)})`:t}literal(e,t){if(e===void 0)return`undefined`;if(e===null)return`null`;if(typeof e==`number`)return Object.is(e,-0)?`-0`:Number.isFinite(e)?String(e):e>0?`Infinity`:e<0?`-Infinity`:`NaN`;if(typeof e==`string`||typeof e==`boolean`)return JSON.stringify(e);if(e instanceof Date)return`new Date(${JSON.stringify(e.toISOString())})`;let n=t instanceof vg?t.base:t instanceof Wg||t instanceof Hg?t.inner:t;if(e instanceof Map){let t=n instanceof zg?n.key:this.registry.any(),r=n instanceof zg?n.value:this.registry.any(),i=[...e].map(([e,n])=>`[${this.literal(e,t)}, ${this.literal(n,r)}]`);return`new Map<${this.ref(t)}, ${this.ref(r)}>([${i.join(`, `)}])`}if(Array.isArray(e)){if(n instanceof Yg)return`[${e.map((e,t)=>this.literal(e,n.elements[t]??this.registry.any())).join(`, `)}]`;let t=n instanceof Fg?n.item:this.registry.any();return`[${e.map(e=>this.literal(e,t)).join(`, `)}]`}if(typeof e==`object`){let n=new Map(dy(t)??[]);return`{ ${Object.entries(e).filter(([,e])=>e!==void 0).map(([e,t])=>`${ty(e)?e:JSON.stringify(e)}: ${this.literal(t,n.get(e)?.type??this.registry.any())}`).join(`, `)} }`}return`undefined`}set(e,t,n,r){let i=e.path.steps,a=this.val(e.value,t,n,r);if(i.length===1&&i[0]instanceof iv){let e=i[0].prop,o=this.lookup(e,t,n);if(!o){this.problem(`set: unknown variable '${e}'`);return}r.push(`${o.ts} = ${Ey(a.code)};`);return}let o=oy.test(a.code)?a.code:this.spill(a,r,`value`),s=i[i.length-1];if(s instanceof av){this.problem(`set: assigning through a method call is not supported`);return}let c=this.path(i.slice(0,-1),t,n,r);if(s instanceof iv){let e=c.type.prop(s.prop);if(e?.set){this.problem(`set: prop '${s.prop}' has a gin setter, which is not supported`);return}if(e?.get&&!e.type.call()){this.problem(`set: prop '${s.prop}' is computed and cannot be assigned`);return}r.push(`${ey(c.code,s.prop)} = ${o};`)}else if(s instanceof ov){let e=this.val(s.key,t,n,r).code,i=c.type.get(),a=i?.set instanceof Ov?i.set.id:void 0,l=a?$v[a]:void 0;if(!l){this.problem(`set: indexed assignment on '${c.type.toCode()}' is not supported`);return}r.push(`${l({self:c.code,key:e,value:o,helper:e=>this.helper(e)})};`)}}lookup(e,t,n){let r=t.get(e);if(r)return r;let i=this.engine.getGlobal(e),a=this.opt.scope[e]??i?.type;if(a)return n.ctxAllowed?(this.ctxVars.set(e,a),{ts:ey(`ctx`,e),type:a}):(this.problem(`'${e}' is read inside a gin-written member, where only this / args / recurse are in scope`),{ts:`undefined as any`,type:a})}path(e,t,n,r){let i;for(let a=0;a<e.length;a++){let o=e[a];if(o instanceof iv){if(!i){let e=this.lookup(o.prop,t,n);e?i={code:e.ts,type:e.type,pure:!0,sync:e.sync}:(this.problem(`unknown variable '${o.prop}'`),i={code:`undefined as any`,type:this.registry.any(),pure:!0});continue}this.touch(i.type);let s=i.type.prop(o.prop);if(!s){this.problem(`no prop '${o.prop}' on '${i.type.toCode()}' (the TypeScript export dispatches on the static type)`),i={code:ey(i.code,o.prop),type:this.registry.any(),pure:!1};continue}let c=s.type instanceof wg?s.type.simplify(i.type.scope):s.type,l=e[a+1];if(l instanceof av&&c.call()){i=this.invoke(i,o.prop,s,c,l,t,n,r),a++;continue}if(!(l instanceof av)&&cy(c)){i=this.invoke(i,o.prop,s,c,new av({}),t,n,r);continue}i=this.readProp(i,o.prop,s,c,n,r)}else{if(!i)return this.problem(`path: must start with a variable`),{code:`undefined as any`,type:this.registry.any(),pure:!0};if(o instanceof ov){this.touch(i.type);let e=i,a=[],s=this.val(o.key,t,n,a),c=a.length||!s.pure?this.spill(e,r,`recv`):e.code;r.push(...a);let l=e.type.get(),u=l?.get instanceof Ov?l.get.id:void 0,d=u?Qv[u]:void 0;d||this.problem(`indexing '${e.type.toCode()}' is not supported`),i={code:d?d({self:c,key:s.code,helper:e=>this.helper(e)}):`undefined as any`,type:l?.value??this.registry.any(),pure:!1}}else if(o instanceof av){let e=i.type,a=e.scope;try{a=o.callSiteScope(e)}catch(e){this.problem(String(e instanceof Error?e.message:e))}let s=e.call(a);s?.get&&this.problem(`calling a '${e.toCode()}' value implemented in gin is not supported`);let{recv:c,args:l}=this.orderedArgs(i,o.args,t,n,r),u=`${c}(${vy(l,s)})`;i.sync!==!0&&(u=this.aw(u,n));let d=s?.returns?.simplify(a)??s?.returns??this.registry.any();i=o.catch_?this.withCatch(u,o.catch_,d,t,n,r):{code:u,type:d,pure:!1}}}}return i??{code:`undefined as any`,type:this.registry.any(),pure:!0}}touch(e){e instanceof vg&&!e.local.useSite&&this.define(this.decl(e))}readProp(e,t,n,r,i,a){let o=n.get instanceof Ov?n.get.id:void 0,s=o?Zv[o]:void 0;if(s)return{code:s(this.nativeCtx(e,{},void 0,i,a)),type:r,pure:e.pure};let c=ey(e.code,t);return n.get&&this.memberAsync(e.type,t,n,`computed`)&&(c=this.aw(c,i)),{code:c,type:r,pure:e.pure&&!n.get}}invoke(e,t,n,r,i,a,o,s){let c=r.scope;try{c=i.callSiteScope(r)}catch(e){this.problem(String(e instanceof Error?e.message:e))}let l=r.call(c),u=l?.returns?.simplify(c)??l?.returns??this.registry.any(),d=n.get instanceof Ov?n.get.id:void 0,f=d?Zv[d]:void 0,{recv:p,args:m}=this.orderedArgs(e,i.args,a,o,s),h;if(f){let t=i.generic?.T?this.registry.parse(i.generic.T,c):void 0;h=f(this.nativeCtx({...e,code:p},m,t,o,s))}else h=`${ey(p,t)}(${vy(m,l)})`,this.memberAsync(e.type,t,n,`method`)&&(h=this.aw(h,o));return i.catch_?this.withCatch(h,i.catch_,u,a,o,s):{code:h,type:u,pure:!!f&&e.pure&&Object.values(m).every(e=>e.pure)&&!(d&&gy(d))}}memberAsync(e,t,n,r){if(n.get&&!(n.get instanceof Ov)){let n=e instanceof vg?this.decl(e):void 0,i=this.findMember(n,t);return i?i.async!==!1:r===`method`}return r!==`computed`&&this.hostMemberKind(n)!==`sync`}findMember(e,t){for(let n=e;n instanceof vg;n=n.original){let e=this.makers.get(this.decl(n).name)?.members.get(t);if(e)return e}}orderedArgs(e,t,n,r,i){let a=Object.entries(t).map(([e,t])=>{let i=[];return{k:e,r:this.val(t,n,r,i),buf:i}}),o=a.some(e=>e.buf.length>0||!e.r.pure),s=o&&!oy.test(e.code)?this.spill(e,i,`recv`):e.code,c={};for(let e of a)i.push(...e.buf),c[e.k]=o&&!e.r.pure&&e.r.sync===void 0?{...e.r,code:this.spill(e.r,i,e.k),pure:!0}:e.r;return{recv:s,args:c}}ordered(e,t){let n=e.map(e=>{let t=[];return{r:e(t),buf:t}}),r=n.reduce((e,t,n)=>t.buf.length?n:e,-1);return n.map((e,n)=>{if(t.push(...e.buf),n<r&&!e.r.pure&&!oy.test(e.r.code)){let n=this.uniq(`slot`);return t.push(`const ${n} = ${Ey(e.r.code)};`),{...e.r,code:n,pure:!0}}return e.r})}nativeCtx(e,t,n,r,i){let a=e.code,o={};for(let[e,n]of Object.entries(t))o[e]=n.code;return{self:()=>a,once:()=>(ty(a)||(a=this.spill({...e,code:a},i,`recv`)),a),discard:()=>{e.pure||i.push(`${Ey(a)};`)},arg:e=>o[e],argOnce:e=>{let n=o[e];return n===void 0||ty(n)?n:(o[e]=this.spill({...t[e],code:n},i,e),o[e])},fn:e=>{let n=t[e];if(n)return{code:n.code,sync:!this.always&&n.sync===!0}},helper:e=>this.helper(e),aw:e=>this.aw(e,r),selfType:e.type,fields:()=>fy(e.type),guard:()=>n?this.guard(n):void 0,staticTypeName:()=>my(e.type)}}withCatch(e,t,n,r,i,a){let o=this.uniq(`result`),s=this.uniq(`e`),c=this.uniq(`error`),l=this.helper(`$Throw`);a.push(`let ${o};`,`try {`,` ${o} = ${Ey(e)};`,`} catch (${s}) {`,` if (!(${s} instanceof ${l})) throw ${s};`);let u=[`const ${c} = ${s}.error as any;`],d=new Map(r);d.set(`error`,{ts:c,type:this.registry.any()});let f=this.val(t,d,i,u);return u.push(`${o} = ${Ey(f.code)};`),a.push(...by(u),`}`),{code:o,type:n,pure:!0}}aw(e,t){return t.awaited=!0,`(await ${e})`}spill(e,t,n){if(ty(e.code)||oy.test(e.code))return e.code;let r=this.uniq(n);return t.push(`const ${r} = ${Ey(e.code)};`),r}typeOfExpr(e,t){let n=new Map;for(let[e,t]of this.engine.getGlobals())n.set(e,t.type);for(let[e,t]of Object.entries(this.opt.scope))n.set(e,t);for(let[e,r]of t)n.set(e,r.type);try{return e.typeOf(this.engine,n)}catch{return this.registry.any()}}};function cy(e){let t=e.call();return t?t.args instanceof bg?Object.values(t.args.fields).every(e=>e.type.isOptional()):!0:!1}function ly(e){return!!e.get||e.type instanceof Mg}function uy(e){return e instanceof bg||e instanceof Ng||e instanceof vg&&uy(e.base)}function dy(e){if(e instanceof bg)return Object.entries(e.fields);if(e instanceof Ng)return Object.entries(e._props);if(e instanceof vg){let t=dy(e.base);if(!t)return;let n=new Map(t);for(let[t,r]of Object.entries(e.local.props??{}))n.set(t,Nh.from(r));return[...n]}}function fy(e){return(dy(e)??[]).filter(([,e])=>!e.get&&!e.type.call()).map(([e])=>e)}function py(e){let t=dy(e);if(t)return new Map(t.filter(([,e])=>!e.get).map(([e,t])=>[e,t.type]))}function my(e){if(!(e instanceof yg||e instanceof Gg||e instanceof Sg||e instanceof Bg||e instanceof wg||e instanceof Wg||e instanceof Hg))return e.name}function hy(e){let t=e instanceof vg?e.base:e;return t instanceof Kg||t instanceof Ug||t instanceof Tg||t instanceof kg}function gy(e){return/\.(push|pop|shift|unshift|insert|remove|clear|delete|indexSet|setAt)$/.test(e)}function _y(e,t){return e instanceof th?!0:!e||typeof e!=`object`?!1:!Array.isArray(e)&&typeof e.kind==`string`&&t.exprClass(e.kind)?!0:Object.values(e).some(e=>_y(e,t))}function vy(e,t){let n=Object.entries(e);return n.length===0?(t?.args instanceof bg?Object.values(t.args.fields):[]).some(e=>!e.type.isOptional()&&e.default===void 0)?`{} as any`:``:`{ ${n.map(([e,t])=>e===t.code?e:`${ty(e)?e:JSON.stringify(e)}: ${Ey(t.code)}`).join(`, `)} }`}function yy(e){let t=e.options;if(t&&typeof t==`object`&&Object.keys(t).length!==0&&(e instanceof Ug||e instanceof Kg||e instanceof Fg||e instanceof Dg||e instanceof qg))return`gin: ${e.toCode(void 0,{includeComments:!1})}`}function by(e){return e.flatMap(e=>e.split(`
|
|
386
|
-
`)).map(e=>e&&` ${e}`)}function
|
|
384
|
+
`)){let e=c[0].slice(7,-1);e.startsWith(`{`)&&(e=`(${e})`),m=`${l?`async `:``}${f}(${u})${d} => ${e}`}else m=[`${l?`async `:``}${f}(${u})${d} => {`,...Uy(c),`}`].join(`
|
|
385
|
+
`);return{code:`(${m})`,type:e.fnType,pure:!0,sync:!l}}newValue(e,t,n,r){let i=e.type,a=i.init();if(e.value!==void 0&&a){let t=a.run instanceof Zv?a.run.id:void 0;if(t!==`duration.init`&&t!==`color.init`)return this.problem(`new ${i.toCode()}: a constructor written in gin is not supported`),{code:`undefined as any`,type:i,pure:!0};let n=this.literal(a.args.parse(e.value).toLogical(),a.args);return{code:`${this.helper(t===`duration.init`?`$duration`:`$color`)}.init(${n})`,type:i,pure:!0}}if(e.value===void 0){let e=this.construct(i,this.literal(new W(i,i.create()).toLogical(),i));return{code:e,type:i,pure:!e.startsWith(`make`)}}let o=this.fill(e.value,i,t,n,r);return{code:o.code,type:i,pure:o.pure}}fill(e,t,n,r,i){let a=e instanceof wh?e:tg(e,t.scope??this.registry);if(a){let e=this.val(a,n,r,i);return{code:e.code,pure:e.pure}}if(!By(e,this.registry))try{let n=this.construct(t,this.literal(t.parse(e).toLogical(),t));return{code:n,pure:!n.startsWith(`make`)}}catch(e){return this.problem(`new ${t.toCode()}: ${e instanceof Error?e.message:String(e)}`),{code:`undefined as any`,pure:!0}}if(t instanceof qg)return this.fill(e,t.simplify(),n,r,i);if(t instanceof p_||t instanceof d_)return e===void 0?{code:`undefined`,pure:!0}:e===null?{code:`null`,pure:!0}:this.fill(e,t.inner,n,r,i);let o=e=>this.ordered(e.map(([e,t,i])=>a=>{let o=this.fill(t,i,n,r,a);return{code:o.code,pure:o.pure,key:e}}),i);if(t instanceof i_&&Array.isArray(e))return{code:`[${o(e.map(e=>[void 0,e,t.item])).map(e=>e.code).join(`, `)}]`,pure:!1};if(t instanceof v_&&Array.isArray(e))return{code:`[${o(e.map((e,n)=>[void 0,e,t.elements[n]??this.registry.any()])).map(e=>e.code).join(`, `)}] as ${this.ref(t)}`,pure:!1};if(t instanceof c_&&Array.isArray(e)){let n=[];for(let r of e){let[e,i]=Array.isArray(r)?r:[r?.key,r?.value];n.push([void 0,e,t.key],[void 0,i,t.value])}let r=o(n),i=[];for(let e=0;e<r.length;e+=2)i.push(`[${r[e].code}, ${r[e+1].code}]`);return{code:`new Map<${this.ref(t.key)}, ${this.ref(t.value)}>([${i.join(`, `)}])`,pure:!1}}let s=Py(t);if(s&&e&&typeof e==`object`&&!Array.isArray(e)){let a=e,c=[],l=[];for(let[e,t]of s)e in a?c.push([e,a[e],t.type]):t.default&&l.push([e,t.default]);let u=o(c);for(let[e,t]of l)u.push({key:e,code:this.val(t,n,r,i).code});let d=u.map(e=>`${wy(e.key)?e.key:JSON.stringify(e.key)}: ${e.code}`);return{code:this.construct(t,`{ ${d.join(`, `)} }`),pure:!1}}return this.problem(`new ${t.toCode()}: payload shape not supported`),{code:`undefined as any`,pure:!0}}construct(e,t){let n=e instanceof Vg&&!e.local.useSite?this.decl(e):void 0;if(n){this.define(n);let e=this.carriedMembers(n).map(([e])=>e);e.length&&this.problem(`new ${n.name}: its host member${e.length>1?`s`:``} ${e.join(`, `)} cannot be supplied in TypeScript \u2014 build the value on the host (\`make${this.tsName(n.name)}\` / \`${this.dataName(n)}\`) and pass it in`);let r=this.maker(n);if(r)return`${r.name}(${t})`}return t.startsWith(`[`)||t.startsWith(`{`)||n?`(${t} as ${this.ref(e)})`:t}literal(e,t){if(e===void 0)return`undefined`;if(e===null)return`null`;if(typeof e==`number`)return Object.is(e,-0)?`-0`:Number.isFinite(e)?String(e):e>0?`Infinity`:e<0?`-Infinity`:`NaN`;if(typeof e==`string`||typeof e==`boolean`)return JSON.stringify(e);if(e instanceof Date)return`new Date(${JSON.stringify(e.toISOString())})`;let n=t instanceof Vg?t.base:t instanceof p_||t instanceof d_?t.inner:t;if(e instanceof Map){let t=n instanceof c_?n.key:this.registry.any(),r=n instanceof c_?n.value:this.registry.any(),i=[...e].map(([e,n])=>`[${this.literal(e,t)}, ${this.literal(n,r)}]`);return`new Map<${this.ref(t)}, ${this.ref(r)}>([${i.join(`, `)}])`}if(Array.isArray(e)){if(n instanceof v_)return`[${e.map((e,t)=>this.literal(e,n.elements[t]??this.registry.any())).join(`, `)}]`;let t=n instanceof i_?n.item:this.registry.any();return`[${e.map(e=>this.literal(e,t)).join(`, `)}]`}if(typeof e==`object`){let n=new Map(Py(t)??[]);return`{ ${Object.entries(e).filter(([,e])=>e!==void 0).map(([e,t])=>`${wy(e)?e:JSON.stringify(e)}: ${this.literal(t,n.get(e)?.type??this.registry.any())}`).join(`, `)} }`}return`undefined`}set(e,t,n,r){let i=e.path.steps,a=this.val(e.value,t,n,r);if(i.length===1&&i[0]instanceof Dv){let e=i[0].prop,o=this.lookup(e,t,n);if(!o){this.problem(`set: unknown variable '${e}'`);return}r.push(`${o.ts} = ${Yy(a.code)};`);return}let o=ky.test(a.code)?a.code:this.spill(a,r,`value`),s=i[i.length-1];if(s instanceof Ov){this.problem(`set: assigning through a method call is not supported`);return}let c=this.path(i.slice(0,-1),t,n,r);if(s instanceof Dv){let e=c.type.prop(s.prop);if(e?.set){this.problem(`set: prop '${s.prop}' has a gin setter, which is not supported`);return}if(e?.get&&!e.type.call()){this.problem(`set: prop '${s.prop}' is computed and cannot be assigned`);return}r.push(`${Cy(c.code,s.prop)} = ${o};`)}else if(s instanceof kv){let e=this.val(s.key,t,n,r).code,i=c.type.get(),a=i?.set instanceof Zv?i.set.id:void 0,l=a?Sy[a]:void 0;if(!l){this.problem(`set: indexed assignment on '${c.type.toCode()}' is not supported`);return}r.push(`${l({self:c.code,key:e,value:o,helper:e=>this.helper(e)})};`)}}lookup(e,t,n){let r=t.get(e);if(r)return r;let i=this.engine.getGlobal(e),a=this.opt.scope[e]??i?.type;if(a)return n.ctxAllowed?(this.ctxVars.set(e,a),{ts:Cy(`ctx`,e),type:a}):(this.problem(`'${e}' is read inside a gin-written member, where only this / args / recurse are in scope`),{ts:`undefined as any`,type:a})}path(e,t,n,r){let i;for(let a=0;a<e.length;a++){let o=e[a];if(o instanceof Dv){if(!i){let e=this.lookup(o.prop,t,n);e?i={code:e.ts,type:e.type,pure:!0,sync:e.sync}:(this.problem(`unknown variable '${o.prop}'`),i={code:`undefined as any`,type:this.registry.any(),pure:!0});continue}this.touch(i.type);let s=i.type.prop(o.prop);if(!s){this.problem(`no prop '${o.prop}' on '${i.type.toCode()}' (the TypeScript export dispatches on the static type)`),i={code:Cy(i.code,o.prop),type:this.registry.any(),pure:!1};continue}let c=s.type instanceof qg?s.type.simplify(i.type.scope):s.type,l=e[a+1];if(l instanceof Ov&&c.call()){i=this.invoke(i,o.prop,s,c,l,t,n,r),a++;continue}if(!(l instanceof Ov)&&jy(c)){i=this.invoke(i,o.prop,s,c,new Ov({}),t,n,r);continue}i=this.readProp(i,o.prop,s,c,n,r)}else{if(!i)return this.problem(`path: must start with a variable`),{code:`undefined as any`,type:this.registry.any(),pure:!0};if(o instanceof kv){this.touch(i.type);let e=i,a=[],s=this.val(o.key,t,n,a),c=a.length||!s.pure?this.spill(e,r,`recv`):e.code;r.push(...a);let l=e.type.get(),u=l?.get instanceof Zv?l.get.id:void 0,d=u?xy[u]:void 0;d||this.problem(`indexing '${e.type.toCode()}' is not supported`),i={code:d?d({self:c,key:s.code,helper:e=>this.helper(e)}):`undefined as any`,type:l?.value??this.registry.any(),pure:!1}}else if(o instanceof Ov){let e=i.type,a=e.scope;try{a=o.callSiteScope(e)}catch(e){this.problem(String(e instanceof Error?e.message:e))}let s=e.call(a);s?.get&&this.problem(`calling a '${e.toCode()}' value implemented in gin is not supported`);let{recv:c,args:l}=this.orderedArgs(i,o.args,t,n,r),u=`${c}(${Vy(l,s)})`;i.sync!==!0&&(u=this.aw(u,n));let d=s?.returns?.simplify(a)??s?.returns??this.registry.any();i=o.catch_?this.withCatch(u,o.catch_,d,t,n,r):{code:u,type:d,pure:!1}}}}return i??{code:`undefined as any`,type:this.registry.any(),pure:!0}}touch(e){e instanceof Vg&&!e.local.useSite&&this.define(this.decl(e))}readProp(e,t,n,r,i,a){let o=n.get instanceof Zv?n.get.id:void 0,s=o?by[o]:void 0;if(s)return{code:s(this.nativeCtx(e,{},void 0,i,a)),type:r,pure:e.pure};let c=Cy(e.code,t);return n.get&&this.memberAsync(e.type,t,n,`computed`)&&(c=this.aw(c,i)),{code:c,type:r,pure:e.pure&&!n.get}}invoke(e,t,n,r,i,a,o,s){let c=r.scope;try{c=i.callSiteScope(r)}catch(e){this.problem(String(e instanceof Error?e.message:e))}let l=r.call(c),u=l?.returns?.simplify(c)??l?.returns??this.registry.any(),d=n.get instanceof Zv?n.get.id:void 0,f=d?by[d]:void 0,{recv:p,args:m}=this.orderedArgs(e,i.args,a,o,s),h;if(f){let t=i.generic?.T?this.registry.parse(i.generic.T,c):void 0;h=f(this.nativeCtx({...e,code:p},m,t,o,s))}else h=`${Cy(p,t)}(${Vy(m,l)})`,this.memberAsync(e.type,t,n,`method`)&&(h=this.aw(h,o));return i.catch_?this.withCatch(h,i.catch_,u,a,o,s):{code:h,type:u,pure:!!f&&e.pure&&Object.values(m).every(e=>e.pure)&&!(d&&zy(d))}}memberAsync(e,t,n,r){if(n.get&&!(n.get instanceof Zv)){let n=e instanceof Vg?this.decl(e):void 0,i=this.findMember(n,t);return i?i.async!==!1:r===`method`}return r!==`computed`&&this.hostMemberKind(n)!==`sync`}findMember(e,t){for(let n=e;n instanceof Vg;n=n.original){let e=this.makers.get(this.decl(n).name)?.members.get(t);if(e)return e}}orderedArgs(e,t,n,r,i){let a=Object.entries(t).map(([e,t])=>{let i=[];return{k:e,r:this.val(t,n,r,i),buf:i}}),o=a.some(e=>e.buf.length>0||!e.r.pure),s=o&&!ky.test(e.code)?this.spill(e,i,`recv`):e.code,c={};for(let e of a)i.push(...e.buf),c[e.k]=o&&!e.r.pure&&e.r.sync===void 0?{...e.r,code:this.spill(e.r,i,e.k),pure:!0}:e.r;return{recv:s,args:c}}ordered(e,t){let n=e.map(e=>{let t=[];return{r:e(t),buf:t}}),r=n.reduce((e,t,n)=>t.buf.length?n:e,-1);return n.map((e,n)=>{if(t.push(...e.buf),n<r&&!e.r.pure&&!ky.test(e.r.code)){let n=this.uniq(`slot`);return t.push(`const ${n} = ${Yy(e.r.code)};`),{...e.r,code:n,pure:!0}}return e.r})}nativeCtx(e,t,n,r,i){let a=e.code,o={};for(let[e,n]of Object.entries(t))o[e]=n.code;return{self:()=>a,once:()=>(wy(a)||(a=this.spill({...e,code:a},i,`recv`)),a),discard:()=>{e.pure||i.push(`${Yy(a)};`)},arg:e=>o[e],argOnce:e=>{let n=o[e];return n===void 0||wy(n)?n:(o[e]=this.spill({...t[e],code:n},i,e),o[e])},fn:e=>{let n=t[e];if(n)return{code:n.code,sync:!this.always&&n.sync===!0}},helper:e=>this.helper(e),aw:e=>this.aw(e,r),selfType:e.type,fields:()=>Fy(e.type),guard:()=>n?this.guard(n):void 0,staticTypeName:()=>Ly(e.type)}}withCatch(e,t,n,r,i,a){let o=this.uniq(`result`),s=this.uniq(`e`),c=this.uniq(`error`),l=this.helper(`$Throw`);a.push(`let ${o};`,`try {`,` ${o} = ${Yy(e)};`,`} catch (${s}) {`,` if (!(${s} instanceof ${l})) throw ${s};`);let u=[`const ${c} = ${s}.error as any;`],d=new Map(r);d.set(`error`,{ts:c,type:this.registry.any()});let f=this.val(t,d,i,u);return u.push(`${o} = ${Yy(f.code)};`),a.push(...Uy(u),`}`),{code:o,type:n,pure:!0}}aw(e,t){return t.awaited=!0,`(await ${e})`}spill(e,t,n){if(wy(e.code)||ky.test(e.code))return e.code;let r=this.uniq(n);return t.push(`const ${r} = ${Yy(e.code)};`),r}typeOfExpr(e,t){let n=new Map;for(let[e,t]of this.engine.getGlobals())n.set(e,t.type);for(let[e,t]of Object.entries(this.opt.scope))n.set(e,t);for(let[e,r]of t)n.set(e,r.type);try{return e.typeOf(this.engine,n)}catch{return this.registry.any()}}};function jy(e){let t=e.call();return t?t.args instanceof Ug?Object.values(t.args.fields).every(e=>e.type.isOptional()):!0:!1}function My(e){return!!e.get||e.type instanceof t_}function Ny(e){return e instanceof Ug||e instanceof n_||e instanceof Vg&&Ny(e.base)}function Py(e){if(e instanceof Ug)return Object.entries(e.fields);if(e instanceof n_)return Object.entries(e._props);if(e instanceof Vg){let t=Py(e.base);if(!t)return;let n=new Map(t);for(let[t,r]of Object.entries(e.local.props??{}))n.set(t,ng.from(r));return[...n]}}function Fy(e){return(Py(e)??[]).filter(([,e])=>!e.get&&!e.type.call()).map(([e])=>e)}function Iy(e){let t=Py(e);if(t)return new Map(t.filter(([,e])=>!e.get).map(([e,t])=>[e,t.type]))}function Ly(e){if(!(e instanceof Hg||e instanceof m_||e instanceof Gg||e instanceof l_||e instanceof qg||e instanceof p_||e instanceof d_))return e.name}function Ry(e){let t=e instanceof Vg?e.base:e;return t instanceof h_||t instanceof f_||t instanceof Jg||t instanceof Qg}function zy(e){return/\.(push|pop|shift|unshift|insert|remove|clear|delete|indexSet|setAt)$/.test(e)}function By(e,t){return e instanceof wh?!0:!e||typeof e!=`object`?!1:!Array.isArray(e)&&typeof e.kind==`string`&&t.exprClass(e.kind)?!0:Object.values(e).some(e=>By(e,t))}function Vy(e,t){let n=Object.entries(e);return n.length===0?(t?.args instanceof Ug?Object.values(t.args.fields):[]).some(e=>!e.type.isOptional()&&e.default===void 0)?`{} as any`:``:`{ ${n.map(([e,t])=>e===t.code?e:`${wy(e)?e:JSON.stringify(e)}: ${Yy(t.code)}`).join(`, `)} }`}function Hy(e){let t=e.options;if(t&&typeof t==`object`&&Object.keys(t).length!==0&&(e instanceof f_||e instanceof h_||e instanceof i_||e instanceof Xg||e instanceof g_))return`gin: ${e.toCode(void 0,{includeComments:!1})}`}function Uy(e){return e.flatMap(e=>e.split(`
|
|
386
|
+
`)).map(e=>e&&` ${e}`)}function Wy(e){return e[e.length-1]===`}`}function Gy(e){if(e.length===0)return`{}`;let t=`{ ${e.join(`; `)} }`;return t.length<=80&&!t.includes(`
|
|
387
387
|
`)&&!t.includes(`/**`)?t:`{
|
|
388
|
-
${
|
|
388
|
+
${Uy(e.map(e=>`${e};`)).join(`
|
|
389
389
|
`)}
|
|
390
|
-
}`}function
|
|
390
|
+
}`}function Ky(e){return e.includes(`=>`)||e.includes(` | `)||e.includes(` & `)?`(${e})`:e}function qy(e){let t=[];for(let n of e.map(e=>e.includes(`=>`)?`(${e})`:e))t.includes(n)||t.push(n);return t.join(` | `)}function Jy(e){return/^[\w$.]+(<.*>)?$/.test(e)&&!e.includes(` `)?`${e}[]`:`Array<${e}>`}function Yy(e){if(!e.startsWith(`(`)||!e.endsWith(`)`))return e;let t=0;for(let n=0;n<e.length;n++){let r=e[n];if(r===`(`)t++;else if(r===`)`){if(t--,t===0&&n<e.length-1)return e}else if(r===`"`||r==="`"||r===`'`)return e}return e.slice(1,-1)}function Xy(e){return e.replace(/\*\//g,`*\\/`)}function Zy(e){return e.replace(/\\/g,`\\\\`).replace(/`/g,"\\`").replace(/\$\{/g,"\\${")}function Qy(e){let t=e.replace(/[^\w$]+(.)/g,(e,t)=>t.toUpperCase());return t.charAt(0).toUpperCase()+t.slice(1)}function $y(e){let t=5381;for(let n=0;n<e.length;n++)t=(t<<5)+t+e.charCodeAt(n)>>>0;return t.toString(36)}function eb(e,t,n={}){let r=e.registry.parseExpr(t),i=new Ay(e,n),a=n.name??`main`,o=i.exportFunction(r,a);i.helpers.has(a)&&i.problem(`function name '${a}' is also the name of a helper the code needs \u2014 pick another`),i.check();let s=new Map(i.helpers);return n.prelude===`inline`&&s.size>0&&(o=`${[...s.values()].join(`
|
|
391
391
|
|
|
392
392
|
`)}
|
|
393
393
|
|
|
394
|
-
${o}`,s.clear()),{code:o,types:new Map(i.types),helpers:s,functions:[a]}}var My=class{constructor(e){this.registry=e}registry;globals=new Map;registerGlobal(e,t){return this.globals.set(e,t),this}getGlobal(e){return this.globals.get(e)}getGlobals(){return this.globals}parse(e){if(!e||typeof e!=`object`||!(`kind`in e))throw Error(`engine.parse: expected ExprDef with kind, got ${typeof e}`);return e}createRootScope(e,t){let n=new ih(null,void 0,t);for(let[e,t]of this.globals)n.vars.set(e,G(t.type,t.value));if(e)for(let[t,r]of Object.entries(e))n.vars.set(t,r);return n}async run(e,t,n){let r=n?new ug(n):void 0;r?.check();let i=this.createRootScope(t,r);try{return await this.evaluate(e,i)}catch(e){if(e instanceof mh)return e.value??G(this.registry.void(),void 0);throw e}}typeOf(e,t){let n=t??this.globalTypeScope();return ah(this,e,n)}validate(e,t,n){let r=t??this.globalTypeScope();return sh(this,e,r,n)}toCode(e,t){return this.registry.toCode(e,t)}toGinCode(e,t){return this.registry.toGinCode(e,t)}toJSONCode(e,t=2){return this.registry.toJSONCode(e,t)}toTypeScript(e,t){return jy(this,e,t)}globalTypeScope(){let e=new Map;for(let[t,n]of this.globals)e.set(t,n.type);return e}async evaluate(e,t){return(e instanceof th?e:this.registry.parseExpr(e)).evaluate(this,t)}async validateValue(e,t){let n=new Pm,r=e.type.constraints();if(r.length===0)return n;let i=t??this.createRootScope();for(let t=0;t<r.length;t++){let a=r[t],o=i.child({this:e});try{(await a.evaluate(this,o)).raw!==!0&&n.at(`constraint[${t}]`,()=>n.error(`constraint.failed`,`value failed constraint: ${a.toCode(this.registry,{expectsValue:!0})}`))}catch(e){n.at(`constraint[${t}]`,()=>n.error(`constraint.threw`,`constraint threw: ${e.message}`))}}return n}};function Ny(e){return new My(e)}var Py=`^[a-z]\\S*$`,Fy=`A fn's name, as your tools spell it.`;function Iy(e){if(e.name!==`text`)return!1;let t=e.options;return typeof t==`object`&&!!t&&`pattern`in t&&t.pattern===`^[a-z]\\S*$`}var Ly=R.string().pattern(Py).describe(Fy);function Ry(e){return R.codec(Ly,{decode:t=>e.fn(t)??Error(`${t} names no fn: write a fn's name as your tools spell it.`),encode:t=>e.name(t)})}var zy=new WeakMap,By=0;function Vy(e){if(e===void 0)return 0;let t=zy.get(e);return t===void 0&&zy.set(e,t=++By),t}var Hy=Mm.declare().dynamic((e,t,n)=>({...Dm(e,n),FnName:t===void 0?Ly:Ry(t)}),{key:(e,t,n)=>`${jm(e,n)}|${Vy(t)}`,cacheSize:4}),Uy={result:e=>Hy.result(e)},Wy=e=>Iy(e)?R.ref(`FnName`):void 0;function Gy(e,t={}){return e.toA({...t.scope===void 0?{}:{scope:t.scope},...t.includeDocs===void 0?{}:{includeDocs:t.includeDocs},...t.unknownKeys===void 0?{}:{unknownKeys:t.unknownKeys},override:Wy})}function Ky(e,t={}){return Uy.result(Gy(e,t))}var qy=new WeakMap,Jy=new WeakMap;function Yy(e,t){let n=t.unknownKeys??`strip`,r=qy;t.scope!==void 0&&(r=Jy.get(t.scope)??new WeakMap,Jy.set(t.scope,r));let i=r.get(e)??new Map;r.set(e,i);let a=i.get(n);if(a!==void 0)return a;let o=Ky(e,{...t,includeDocs:`none`});return i.set(n,o),o}function Xy(e,t={}){return Yy(e,t).bind(e.registry)}function Zy(e){return e.map(String).join(`.`)}function Qy(e,t,n={}){let r=Xy(e,n).render(Ql).parse(t,{inPlace:!1,...n.repair===void 0?{}:{repair:n.repair},...n.label===void 0?{}:{label:n.label}});return r.ok?{ok:!0,value:r.value}:{ok:!1,problems:r.issues.map(e=>({path:Zy(e.codePath),message:e.message})),message:r.message}}var $y=v().regex(/^[a-z][A-Za-z0-9_-]{0,63}$/).brand(),eb=`[A-Za-z0-9](?:[A-Za-z0-9-]|_(?![_.]|$))*`,tb=RegExp(`^${eb}(?:\\.${eb})*$`),nb=v().regex(tb,"a fn name is letters, digits, `_` and `-` in dot-separated parts, each starting with a letter or digit, with no `__` and no part ending in `_`");function rb(e){if(!tb.test(e))return e.includes(`__`)?`${e} holds \`__\`, which separates the parts of the name the model calls it by: write one \`_\``:/(?:^|\.)_|_(?:\.|$)/.test(e)?`a part of ${e} starts or ends with \`_\`: start each part with a letter or digit and end it with no \`_\``:`${e} is not a fn name: letters, digits, \`_\` and \`-\` in dot-separated parts, each starting with a letter or digit`}function ib(e){let{system:t,local:n}=Fl(e);return`${t}__${n.replaceAll(`.`,`__`)}`}function ab(e){return e.length===64&&/_x[0-9a-f]{8}$/.test(e)}function ob(e){return ib(e).length>64}function sb(e){if(ab(e))return;let t=e.indexOf(`__`);if(t<=0)return;let n=e.slice(0,t),r=e.slice(t+2).split(`__`).join(`.`);if(!Ml.test(n)||!tb.test(r))return;let i=I.safeParse(`${n}/${r}`);return i.success&&!ob(i.data)&&ib(i.data)===e?i.data:void 0}function cb(e,t){let n=I.safeParse(e);if(n.success)return n.data;let r=t?.(e);return r===void 0?e.includes(`--`)?lb(e)??sb(e):sb(e)??lb(e):r}function lb(e){if(e.length>=64)return;let t=I.safeParse(e.replace(`__`,`/`).replaceAll(`--`,`.`));if(t.success)return t.data.replaceAll(`/`,`__`).replaceAll(`.`,`--`).replace(/[^A-Za-z0-9_-]/g,`_`).slice(0,64)===e?t.data:void 0}S({model:$y,fn:I,until:N}),S({model:$y,fn:I,system:F});var ub=I.describe(Fy),db=v().min(1).regex(/^\S+$/,`a type's name, with no spaces`);Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);var fb=/^https?:\/\/[^\s\u0000-\u001f\u007f]+$/i;function pb(e){try{let{protocol:t}=new URL(e);return t===`http:`||t===`https:`}catch{return!1}}var mb=v().regex(fb,`expected an http or https URL`).refine(pb,`expected an http or https URL`);function hb(e){return mb.safeParse(e).success}var gb=`outsideImages`,_b=E([`ask`,`always`]),vb=S({value:_b,setBy:M.optional(),updatedAt:N.optional()}),yb=`https`,bb={der:`/harness-ca.crt`,pem:`/harness-ca.pem`},xb=E([`own`,`files`]),Sb=S({on:b(),source:xb,setBy:M.optional(),updatedAt:N.optional(),fingerprint:v().optional(),authorityName:v().optional(),host:v(),links:x(v())}),Cb=v().regex(/^(?:\*|[a-z*][a-z0-9*-]*\/[A-Za-z0-9_*][A-Za-z0-9_.*-]*)$/,`an agent's name (crm/reviewer) or a pattern (hub/chat*, crm/*, *)`).refine(e=>!e.includes(`**`),`write one *`),wb=S({into:x(Cb).min(1),order:y().int().min(0).max(1e3).default(100),requires:x(I).default([]),mode:E([`tools`,`static`]).optional(),replaces:x(I).optional()}),Tb=C([D(`none`),S({detail:E([`full`,`summary`]).default(`full`),maxTokens:y().int().min(1).optional()})]),Eb=S({target:Cb,agents:x(I)}),Db=E([`approved`,`pending`,`declined`]);S({context:I,system:F,title:v(),inject:wb,fns:x(I),targets:x(Eb),agents:x(I),review:Db,off:b(),dynamic:b()}),S({hook:I,system:F,explains:v(),review:Db});var Ob=S({section:E([`context`,`hooks`]),name:I,title:v(),change:E([`added`,`changed`,`removed`]),tokens:y().int().min(0).optional(),targets:x(Eb),agents:x(I),replaces:x(I).optional()});S({agent:I,context:I,on:b(),order:y().int().min(0).max(1e3).optional(),by:M,at:N});var kb=E([`off`,`pending`,`declined`,`system-off`,`fns-unusable`,`mode`,`replaced`,`no-fit`]),Ab=S({agent:I,context:I,source:w(`type`,[S({type:D(`context`)}),S({type:D(`hook`),hook:I})]),system:F,via:Cb,title:v(),detail:E([`full`,`summary`]),text:v(),tokens:y().int().min(0),order:y().int(),on:b(),leftOut:S({why:kb,reason:v()}).optional(),switched:S({by:M,at:N}).optional()}),jb=S({injections:x(Ab),targets:x(Eb)}),Mb=S({agent:I,context:I,on:b().optional(),order:y().int().min(0).max(1e3).nullable().optional()}),Nb=[`listed`,`signature`,`full`],Pb=E(Nb),Fb=S({fn:I,detail:Pb}),Ib=S({type:D(`tools`)}),Lb=E([`auto`,`native`,`text`]),Rb=E([`system-end`,`tail`]),zb=w(`type`,[Ib,S({type:D(`static`),protocol:Lb.default(`auto`),placement:Rb.default(`system-end`),loadDetail:Pb.default(`full`)})]),Bb=E(zb.options.map(e=>e.shape.type.value));E([`find`,`find_ctx`,`inspect`,`load`,`unload`,`run`]);var Vb=S({fn:v().min(1).describe(`The fn to run, by its qualified name (fs/read).`),args:T(v(),Zc()).default({}).describe(`Its args, as its card shows them.`),on:L.optional().describe(`For a system with several machines connected, which one runs it (laptop).`)}),Hb=S({type:D(`plain`)}),Ub=S({type:D(`suggest`),topN:y().int().min(0).default(6),autoInject:S({tokens:y().int().min(0),items:y().int().min(0)}).optional()}),Wb=E([`embedding`,`words`,`turnsAgo`,`age`,`selectedBefore`,`used`]),Gb=S({weight:y().min(0),target:y().optional(),k:y().positive().optional()}),Kb=E([`perMessage`,`perIteration`]),qb=[`history`,`context`,`fns`],Jb=E(qb),Yb=T(Jb,y().min(0)),Xb=w(`type`,[Hb,Ub,S({type:D(`graph`),metrics:bc(Wb,Gb).default({}),spread:S({damping:y().min(0).max(.95).default(.5),hops:y().int().min(0).max(4).default(2)}).prefault({}),floorExchanges:y().int().min(0).default(1),shares:Yb.default({history:.45,context:.35,fns:.2}),threshold:y().min(0).default(.15),evaluate:Kb.default(`perMessage`)})]),Zb=E(Xb.options.map(e=>e.shape.type.value)),Qb=S({contextWindow:y().int().min(256).optional(),maxOutputTokens:y().int().min(16).optional(),reasoningTokens:y().int().min(0).optional(),charsPerToken:y().min(1).max(8).optional()}),$b=Qb.keyof();$b.options;var ex=Qb.required(),tx=E([`admin`,`probe`,`model-info`,`default`]),nx=S({model:v(),limits:ex,sources:T($b,tx),ratio:y()});S({model:v(),limits:Qb,setBy:M,updatedAt:N}),S({model:v(),ratio:y().min(.5).max(2),samples:y().int().min(0),updatedAt:N});var rx=S({asked:y().int().min(0),got:y().int().min(0)}),ix=S({window:y().int().min(0),output:y().int().min(0),reasoning:y().int().min(0),margin:y().int().min(0),fixed:y().int().min(0),pools:T(Jb,rx),estimate:y().int().min(0),cut:x(S({what:v(),why:v()}))}),ax=S({name:I,detail:Pb,activation:y().min(0)}),ox=S({tokens:y().int().min(0),items:x(S({name:I,detail:E([`full`,`summary`,`listed`]),tokens:y().int().min(0)})),leftOut:x(S({name:I,why:kb,reason:v()})),rebuilt:S({added:x(I),dropped:x(I)}).optional()}),sx=S({contextor:Zb,mode:Bb,context:x(ax),fns:x(ax),linear:y().int().min(0),earlier:x(y().int().min(0)),budget:ix,injected:ox.optional()}),cx=S({session:j,text:v().min(1),model:v().min(1).optional(),count:x(v()).max(200).optional()}),lx=S({agent:I,model:v(),window:y().int().min(0),maxTokens:y().int().min(0),estimate:y().int().min(0),system:v(),tools:x(S({name:v(),description:v(),parameters:Zc(),tokens:y().int().min(0)})),messages:x(S({role:v(),content:v(),tokens:y().int().min(0)})),parts:S({instructions:v(),injected:v(),context:v(),guide:v(),tokens:S({instructions:y().int(),injected:y().int(),context:y().int(),guide:y().int(),system:y().int()})}),counts:x(y().int().min(0)),report:sx}),ux=S({turn:sl,items:x(ax),at:N}),dx=[`none`,`read`,`write`,`delete`,`auto`],fx=E(dx),px=S({name:v().optional(),sheetName:v().optional(),sheetIndex:y().int().nonnegative().optional(),headers:x(v()),rows:x(x(v()))});E([`empty`,`boolean`,`integer`,`number`,`date`,`text`]);var mx=E([`file`,`folder`,`link`,`other`]);S({entries:x(S({name:v(),location:v(),kind:mx,type:v().optional(),size:y().nonnegative().optional(),modifiedAt:y().optional()})),truncated:b(),total:y().int().nonnegative()});var hx={converter:v(),from:v(),title:v().optional(),metadata:T(v(),sc()).optional()},gx=w(`kind`,[S({kind:D(`markdown`),...hx,text:v()}),S({kind:D(`text`),...hx,text:v()}),S({kind:D(`code`),...hx,language:v(),text:v()}),S({kind:D(`pages`),...hx,pages:x(v())}),S({kind:D(`table`),...hx,tables:x(px)})]),_x=gx.options.map(e=>e.shape.kind.value),vx=/^(?:true|false|yes|no)$/i,yx=/^[-+]?\d{1,15}$/,bx=/^[-+]?(?:\d{1,3}(?:,\d{3})+|\d+)?(?:\.\d+)?(?:e[-+]?\d+)?%?$/i,xx=/^\d{4}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[-+]\d{2}:?\d{2})?)?$|^\d{1,2}\/\d{1,2}\/\d{2,4}$/;function Sx(e){return vx.test(e)?`boolean`:yx.test(e)?`integer`:/\d/.test(e)&&bx.test(e)?`number`:xx.test(e)&&!Number.isNaN(Date.parse(e))?`date`:`text`}function Cx(e,t){return e===`empty`||e===t?t:e===`integer`&&t===`number`||e===`number`&&t===`integer`?`number`:`text`}function wx(e){let t=Math.max(e.headers.length,...e.rows.map(e=>e.length));return Array.from({length:t},(t,n)=>{let r=`empty`;for(let t of e.rows){let e=(t[n]??``).trim();e!==``&&(r=Cx(r,Sx(e)))}return r})}var Tx=Wc([v().regex(/^[a-z][a-z0-9+.-]*$/),`://`,v()]),Ex=v().min(1).brand(),Dx=`^[0-9a-f]{64}$`,Ox=new RegExp(Dx),kx=S({hash:v().regex(Ox),size:y().int().min(0),mime:v()});S({content:kx,mime:v(),finalUrl:v(),status:y().int(),rendered:b(),title:v().optional()});var Ax=S({uri:Tx,name:v(),description:v(),index:E([`all`,`on-read`,`none`]),ignore:x(v()),watch:b()}),jx=S({uri:Tx,name:v(),type:E([`folder`,`file`,`page`,`record`,`other`]),mime:v().optional(),format:v().optional(),size:y().int().min(0).optional(),modifiedAt:N.optional(),version:v()}),Mx=S({uri:Tx.optional(),raw:v(),kind:E([`child`,`import`,`link`,`embed`,`external`]),title:v().optional()}),Nx=E([`links`,`text`,`bytes`]),Px=C([S({inline:v()}),S({ref:kx})]),Fx=S({stat:jx,links:x(Mx).optional(),text:Px.optional(),bytes:kx.optional()});E(_x);var Ix=[`description`,`ocr`,`transcript`,`thumbnail`];E(Ix);var Lx=E([..._x,...Ix]),Rx=S({key:Ex,path:x(v()),title:v(),start:y().int().min(0),end:y().int().min(0),embedText:v().optional(),form:Lx.optional()}),zx=S({uri:Tx,change:E([`added`,`changed`,`removed`]),version:v().optional()}),Bx=S({format:v().optional(),mime:v().optional(),glob:v().optional(),form:Lx.optional()}),Vx=C([S({resource:Tx,section:Ex.optional(),title:v().optional()}),S({url:mb,title:v()}),S({file:kx,title:v()}),S({run:A,title:v()})]),Hx=S({uri:Tx,section:Ex.optional(),title:v(),preview:v(),rank:y()}),Ux=Gi();function Wx(e,t){return Ux.add(e,{why:t}),e}function Gx(e){let t=e;for(;t!==void 0;){if(Ux.has(t))return!0;t=t instanceof Tc||t instanceof jc||t instanceof Nc||t instanceof kc||t instanceof Vc?t.unwrap():void 0}return!1}function Kx(e){let t=e.shape;return Object.entries(t).filter(([,e])=>Gx(e)).map(([e])=>e)}var qx=new WeakMap;function Jx(e,t){return qx.set(e,{schema:t}),e}var Yx=w(`to`,[S({to:D(`session`),session:j}),S({to:D(`user`),user:M}),S({to:D(`everyone`)})]),Xx=E([`live`,`snapshot`]),Zx=w(`type`,[S({type:D(`system`)}),S({type:D(`memory`),scope:Yx,author:M,run:A.optional()}),S({type:D(`resource`),uri:Tx,section:Ex.optional(),version:v(),copy:Xx})]),Qx=[`system`,`memory`,`resource`],$x=S({full:y().int().min(0),summary:y().int().min(0)}),eS=E([`imports`,`brings`,`suggests`,`parent`,`next`,`related`,`mentions`,`about`,`learned`]),tS=[`imports`,`brings`,`suggests`,`parent`,`next`,`related`,`about`],nS=E(tS),rS=w(`kind`,[S({kind:D(`context`),name:I}),S({kind:D(`fn`),name:ub}),S({kind:D(`type`),name:I}),S({kind:D(`resource`),uri:Tx,section:Ex.optional()})]),iS=[`fn`,`context`,`resource`,`type`],aS=S({to:rS,relation:nS,weight:y().min(0).max(1).default(.5)}),oS=E([`declared`,`mentioned`,`resource`,`learned`,`authored`]),sS=S({from:I,to:rS,toKey:v(),relation:eS,weight:y().min(0).max(1),source:oS,uses:y().min(0).optional(),by:M.optional(),updatedAt:N}),cS=S({weight:y().min(0).max(2).optional(),summary:v().optional(),tags:x(v().min(1)).optional(),fns:x(ub).optional(),suggestFns:x(ub).optional(),inject:Wx(wb.optional(),`a model never writes text that lands in later prompts`),command:v().regex(/^[a-z][a-z0-9-]*$/).optional(),visible:Rl.optional(),suggest:Rl.optional(),parent:I.optional()}),lS=S({text:v().min(1),title:v().optional(),scope:E([`session`,`user`,`everyone`]).default(`session`),about:x(rS).optional(),question:v().min(1).max(500).optional(),when:v().min(1).max(500).optional()}).extend(cS.shape),uS=cS.keyof().exclude(cS.keyof().options.filter(e=>Kx(cS).includes(e))),dS=lS.omit({scope:!0}).partial().extend({name:I,clear:Jx(x(cS.keyof()).optional(),x(uS).optional())}),fS=S({uri:Tx,sections:x(Ex).optional(),copy:Xx.default(`live`)}).extend(cS.omit({summary:!0,parent:!0}).shape),pS=S({created:x(I),updated:x(I),links:y().int().min(0)}),mS={maxDepth:3,maxDecisions:256,maxTokens:8e3},hS=[`active`,`hidden`,`not_applicable`,`pending_approval`,`pending_removal`,`pending_plan`],gS=E(hS),_S=E([`active`,`hidden`,`not_applicable`,`pending_approval`,`pending_removal`]);function vS(e){return e===`active`||e===`pending_removal`}var yS=[`person`,`system`,`research`],bS=E(yS),xS=S({status:gS,from:gS.optional(),by:M,reason:v().optional(),at:N}),SS=S({of:I,similarity:y().min(0).max(1).optional(),reason:v(),at:N}),CS=E([`question`,`when`,`askedBy`,`validUntil`]),wS=S({model:v(),at:N,contentHash:v(),fields:x(CS)}),TS=S({from:I.optional(),into:x(I).optional()}),ES=`newContextStatus`,DS=E([`active`,`pending_approval`,`hidden`]),OS=S({value:DS,setBy:M.optional(),updatedAt:N.optional()}),kS=E([`question`,`content`]),AS=S({statuses:x(_S).min(1).optional(),returnNotApplicable:b().optional(),semanticOver:kS.optional()}),jS=[`approve`,`hide`,`restore`,`confirm_removal`],MS=E(jS),NS=S({names:x(I).min(1).max(200),action:MS,reason:v().min(1).max(500).optional()}),PS=S({changed:x(S({name:I,status:C([gS,D(`removed`)])})),skipped:x(S({name:I,reason:v()}))}),FS=[`duplicate`,`contradiction`,`pending_approval`,`pending_removal`],IS=E(FS),LS=S({kinds:x(IS).min(1).optional(),systems:x(v().min(1)).min(1).optional(),limit:y().int().min(1).max(200).optional(),cursor:v().optional()}),RS=S({name:I,system:v(),title:v(),question:v().optional(),status:gS,statusReason:v().optional(),lastModified:N,excerpt:v().optional()}),zS=S({items:x(S({kind:IS,item:RS,other:RS.optional(),flag:SS.optional()})),next:v().optional(),counts:S({duplicate:y().int().min(0),contradiction:y().int().min(0),pending_approval:y().int().min(0),pending_removal:y().int().min(0)})}),BS=S({keep:I,drop:I,reason:v().min(1).max(500).optional()}),VS=S({kept:I,hidden:I,links:y().int().min(0),mentions:y().int().min(0)}),HS=S({name:I,of:I}),US=S({names:x(I).min(1).max(20)}),WS=S({done:x(S({name:I,fields:x(CS),split:x(I).optional()})),failed:x(S({name:I,reason:v()}))}),GS=S({name:I,question:v().optional(),when:v().optional(),askedBy:bS.optional(),validUntil:N.optional(),lastModified:N,status:gS,statusReason:v().optional(),statusHistory:x(xS),metadata:wS.optional(),metadataStale:b(),duplicate:SS.optional(),contradiction:SS.optional(),notDuplicates:x(I),split:TS.optional()}),KS={openQuestions:60,depth:6,minutes:10,cost:2},qS=S({openQuestions:y().int().min(1).max(500).optional().describe(`The most open (unanswered) questions the plan may hold; planning stops when it is reached. Default 60.`),depth:y().int().min(1).max(12).optional().describe(`How many levels of questions deep the plan may go (1: only the first questions and their options). Default 6.`),minutes:y().min(.1).max(120).optional().describe(`The most minutes planning may take. Default 10.`),cost:y().min(0).max(100).optional().describe(`The most US dollars the model calls may cost. Default 2.`)}),JS=S({openQuestions:y().int().min(1),depth:y().int().min(1),minutes:y().min(0),cost:y().min(0)}),YS=E([`complete`,`open_questions`,`depth`,`time`,`cost`,`stopped`]),XS={complete:`Every question has its options`,open_questions:`Stopped at the open-question limit`,depth:`Stopped at the depth limit`,time:`Stopped at the time limit`,cost:`Stopped at the cost limit`,stopped:`Stopped before it finished`},ZS=v().regex(/^o\d+$/),QS=S({id:ZS,label:v().min(1).max(200),detail:v().max(1e3).optional(),raises:x(I),later:x(v().min(1).max(500)).optional()}),$S=S({question:I,option:ZS}),eC=S({name:I,question:v().min(1),askedBy:bS.optional(),depth:y().int().min(1),parents:x($S),options:x(QS),planned:b(),known:b().optional(),picked:x(ZS),text:v().max(4e3).optional(),answeredBy:M.optional(),answeredAt:N.optional(),status:gS,statusReason:v().optional(),reasonEdited:b().optional()}),tC=S({questions:y().int().min(0),answered:y().int().min(0),open:y().int().min(0),ruledOut:y().int().min(0),decide:y().int().min(0)}),nC=S({description:v().min(1),limits:JS,stop:YS,cost:P,time:y().min(0),startedAt:N,updatedAt:N,roots:x(I),questions:x(eC),counts:tC,revision:y().int().min(0)}),rC=S({description:v().trim().min(1).max(4e3).describe(`What is to be planned, in the person's words with whatever they said about it: the more it says, the better the questions.`),limits:qS.optional()}),iC=S({run:A.describe(`The run of hub/ctx_plan that made the plan (its id, such as run_01HZX3).`)}),aC=iC.extend({format:E([`plan`,`markdown`]).optional().describe("`plan` (the default): the plan itself; `markdown`: the questions, answers and what was ruled out, as markdown to read or share.")}),oC=S({run:A,plan:nC,markdown:v().optional()}),sC=S({question:I.describe(`The question, by its context name as the plan gives it.`),picked:x(v().min(1)).max(20).describe(`The options chosen, by id (o1) or label; several when more than one applies. Empty with no text clears the answer.`),text:v().max(4e3).optional().describe(`The person's own words with the answer: a detail, a condition, or an answer none of the options gives.`)}),cC=S({question:I,reason:v().trim().min(1).max(500)}),lC=iC.extend({answers:x(sC).max(100).optional(),reasons:x(cC).max(100).optional()}),uC=S({run:A,plan:nC,changed:x(S({name:I,status:gS})),deeper:x(I),skipped:x(S({question:v(),reason:v()}))}),dC=iC.extend({under:I.optional().describe(`The question to plan deeper under, by its context name; leave out to go on with the whole plan.`),replan:b().optional().describe(`Write the options of the open questions under it again, taking the answers given since into account (after an answer changed).`),limits:qS.optional().describe("Limits of its own. Its `depth` is counted from the question it plans under (1: only the questions right under it), or, without `under`, from the deepest level that already has options.")}),fC=S({run:A,description:v(),counts:tC,stop:YS.optional(),running:b(),actor:M,session:v().optional(),createdAt:N,updatedAt:N}),pC=S({limit:y().int().min(1).max(100).optional()}),mC=S({items:x(fC)});function hC(e){return e.known===!0||e.picked.length>0||(e.text??``).trim()!==``}function gC(e){return e.options.filter(t=>e.picked.includes(t.id)).map(e=>e.label)}function _C(e){let t=gC(e).map(e=>`"${e}"`);return`${t.length>0?t.join(` and `):`none of the options`} for '${e.question}'`}function vC(e){return`You chose ${_C(e)}`}function yC(e,t){return`'${e.question}' no longer applies${t===void 0?``:`: you chose ${_C(t)}`}`}function bC(e,t){return e.picked.length===0||e.picked.includes(t)}function xC(e,t){let n=new Set(t),r=[...t];for(let t=r.shift();t!==void 0;t=r.shift()){let i=e.get(t);if(i!==void 0){for(let t of i.options)if(bC(i,t.id))for(let i of t.raises)!n.has(i)&&e.has(i)&&(n.add(i),r.push(i))}}return n}function SC(e,t){return e.picked.length>0&&!e.picked.includes(t)}function CC(e){let t=new Map(e.questions.map(e=>[e.name,e])),n=xC(t,e.roots.filter(e=>{let n=(t.get(e)?.parents??[]).filter(n=>n.question!==e&&t.has(n.question));return n.length===0?t.has(e):!n.every(e=>{let n=t.get(e.question);return n!==void 0&&SC(n,e.option)})})),r=e=>e.parents.flatMap(n=>{let r=t.get(n.question);return r===void 0||n.question===e.name?[]:[{edge:n,parent:r}]}),i=e=>{let t=r(e).filter(e=>SC(e.parent,e.edge.option)).map(e=>e.parent);return t.find(e=>n.has(e.name))??t[0]},a=(e,t)=>{if(t.has(e.name))return;t.add(e.name);let n=i(e);if(n!==void 0)return n;for(let{parent:n}of r(e)){let e=a(n,t);if(e!==void 0)return e}},o=new Map;for(let t of e.questions){if(n.has(t.name)){o.set(t.name,{live:!0});continue}let e=i(t);if(e!==void 0){o.set(t.name,{live:!1,reason:vC(e)});continue}let s=r(t)[0]?.parent;s===void 0?o.set(t.name,{live:!1,reason:`It no longer sits under any question of the plan`}):o.set(t.name,{live:!1,reason:yC(s,a(s,new Set([t.name])))})}return o}function wC(e){return`${e.answered} answered · ${e.open} open · ${e.decide} ${e.decide===1?`decision`:`decisions`} to make now`}y().int().min(1).max(65535).default({hub:4300,web:4310,mockHub:4320}.hub);function TC(e){return e.split(`/`).filter((e,t)=>t!==0||e!==``).map(e=>e.startsWith(`:`)?{t:`param`,k:e.slice(1)}:{t:`lit`,v:e})}function EC(e){return`/`+e.map(e=>e.t===`param`?`:${e.k}`:e.v).join(`/`)}function DC(e,t){return`/`+e.map(e=>{if(e.t===`lit`)return e.v;let n=t[e.k];if(n===void 0)throw Error(`path is missing a value for ":${e.k}"`);return encodeURIComponent(String(n))}).join(`/`)}function OC(e){return e.filter(e=>e.t===`param`).map(e=>e.k)}var kC=class extends Error{status;code;data;constructor(e,t,n,r){super(n??t),this.status=e,this.code=t,this.data=r,this.name=`ApiError`}},AC=()=>{let e=globalThis.navigator;return typeof e?.onLine==`boolean`?e.onLine:void 0};function jC(e={}){let t=new Set,n=e.initial??(AC()===!1?`offline`:`online`),r=e=>{if(e!==n){n=e;for(let n of[...t])n(e)}},i=e=>(t.add(e),()=>void t.delete(e)),a=()=>{},o=globalThis;if((e.browser??!0)&&typeof o.addEventListener==`function`&&typeof o.removeEventListener==`function`){let e=()=>r(`online`),t=()=>r(`offline`);o.addEventListener(`online`,e),o.addEventListener(`offline`,t),a=()=>{o.removeEventListener(`online`,e),o.removeEventListener(`offline`,t)}}return{get status(){return n},subscribe:i,whenOnline:(e,t)=>new Promise((r,a)=>{if(n===`online`){r();return}if(e?.aborted){a(e.reason);return}let o=null,s=t=>{l(),o&&clearTimeout(o),e?.removeEventListener(`abort`,c),t()};function c(){s(()=>a(e.reason))}let l=i(e=>{e===`online`&&s(r)});t?.timeout!==void 0&&(o=setTimeout(()=>s(r),t.timeout)),e?.addEventListener(`abort`,c,{once:!0})}),report:r,dispose:()=>{a(),a=()=>{}}}}var MC=e=>{if(Array.isArray(e))return e.map(MC);if(e&&typeof e==`object`){let t={};for(let n of Object.keys(e).sort())t[n]=MC(e[n]);return t}return e},NC=e=>JSON.stringify(MC(e))??`null`,PC=e=>{try{return JSON.stringify(e)!==void 0}catch{return!1}},FC=(e,t)=>({get:n=>e.getItem(t+n)??void 0,set:(n,r)=>e.setItem(t+n,r),delete:n=>{let r=t+n,i=e.getItem(r)!==null;return e.removeItem(r),i},keys:function*(){for(let n=0;n<e.length;n++){let r=e.key(n);r!==null&&r.startsWith(t)&&(yield r.slice(t.length))}}}),IC=(e,t)=>{if(typeof e==`object`)return e;if(e!==`memory`)try{let n=e===`local`?globalThis.localStorage:globalThis.sessionStorage;if(n)return FC(n,t)}catch{}let n=new Map;return{get:e=>n.get(e),set:(e,t)=>void n.set(e,t),delete:e=>n.delete(e),keys:()=>n.keys()}};function LC(e={}){let t=e.max??500,n=e.ttl??0,r=e.now??Date.now,i=IC(e.store??`memory`,e.prefix??`ayepi:cache:`),a=new Map;for(let e of i.keys())a.set(e,!0);let o=e=>{a.delete(e),a.set(e,!0)},s=e=>{let t=i.get(e);if(t!==void 0)try{return JSON.parse(t)}catch{i.delete(e);return}},c=e=>(a.delete(e),i.delete(e)),l=()=>{for(;a.size>t;)c(a.keys().next().value)};return{read:e=>{let t=s(e);if(!t)return;let n=r();if(t.exp&&n>=t.exp){if(!t.stale||n>=t.stale){c(e);return}return o(e),{value:t.v,stale:!0}}return o(e),{value:t.v,stale:!1}},write:(e,t,a)=>{if(!PC(t))return;let s=a?.ttl??n,c=s>0?r()+s:0,u={v:t,exp:c,stale:c&&a?.staleWhileRevalidate?c+a.staleWhileRevalidate:0,tags:a?.tags??[]};i.set(e,JSON.stringify(u)),o(e),l()},remove:e=>void c(e),removeWhere:e=>{let t=0;for(let n of[...i.keys()])e(n)&&c(n)&&(t+=1);return t},invalidateTags:e=>{if(e.length===0)return 0;let t=new Set(e),n=0;for(let e of[...i.keys()]){let r=s(e);r&&r.tags.some(e=>t.has(e))&&c(e)&&(n+=1)}return n},clear:()=>{for(let e of[...i.keys()])i.delete(e);a.clear()}}}function RC(e={},t=jC()){let n=new Map,r=t=>{let r=t??e.store??`memory`,i=n.get(r);return i||(i=LC({...e,store:r}),n.set(r,i)),i};return{cacheFor:r,invalidateTags:e=>{r(void 0);for(let t of n.values())t.invalidateTags(e)},connectivity:t}}var zC=class extends Error{constructor(e=`caller rate limit exceeded`){super(e),this.name=`CallerRateLimited`}},BC=`\0`,VC=e=>new DOMException(e,`AbortError`),HC=e=>{let t=e.filter(e=>e!==void 0);if(t.length===1)return t[0];let n=new AbortController,r=()=>{n.abort();for(let e of t)e.removeEventListener(`abort`,r)};for(let e of t){if(e.aborted)return n.abort(),n.signal;e.addEventListener(`abort`,r,{once:!0})}return n.signal},UC=(e,t)=>new Promise((n,r)=>{if(t.aborted){r(VC(`aborted`));return}let i=()=>{clearTimeout(a),r(VC(`aborted`))},a=setTimeout(()=>{t.removeEventListener(`abort`,i),n()},e);t.addEventListener(`abort`,i,{once:!0})}),WC=(e,t)=>t.reduceRight((e,t)=>t(e),e),GC=(e,t,n)=>e===void 0?[]:typeof e==`function`?e(t,n):e,KC=(e,t)=>n=>async(r,i)=>{t.n+=1,e.onStart?.(r.data);try{let t=await n(r,i);return e.onSuccess?.(t,r.data),t}catch(t){throw e.onError?.(t,r.data),t}finally{--t.n,e.onSettled?.(r.data)}},qC=(e,t,n)=>r=>async(i,a)=>{t!==`success`&&n.invalidateTags(GC(e,i.data,void 0));let o=await r(i,a);return t!==`start`&&n.invalidateTags(GC(e,i.data,o)),o},JC=(e,t,n)=>r=>async(i,a)=>{let o=n(i.data),s=n=>t.write(o,n,{ttl:e.ttl,staleWhileRevalidate:e.staleWhileRevalidate,tags:GC(e.tags,i.data,n)}),c=t.read(o);if(c&&!c.stale)return c.value;if(c&&c.stale)return r(i,a).then(s).catch(()=>{}),c.value;let l=await r(i,a);return s(l),l},YC=e=>{let t=new Map;return n=>(r,i)=>{let a=e(r.data),o=t.get(a);if(o)return o;let s=n(r,i).finally(()=>t.delete(a));return t.set(a,s),s}},XC=()=>{let e=null;return t=>(n,r)=>{e?.abort(VC(`superseded`));let i=new AbortController;e=i;let a=HC([r,i.signal]);return new Promise((e,r)=>{a.addEventListener(`abort`,()=>r(VC(`superseded`)),{once:!0}),t(n,a).then(e,r)}).finally(()=>{e===i&&(e=null)})}},ZC=e=>{let t=e.onLimit??`wait`,n=e.window/e.limit,r=e.limit,i=Date.now(),a=()=>{let t=Date.now(),n=(t-i)/e.window*e.limit;n>0&&(r=Math.min(e.limit,r+n),i=t)};return e=>async(i,o)=>{if(a(),r<1){if(t===`throw`||t===`drop`)throw new zC;await UC((1-r)*n,o),a()}return--r,e(i,o)}},QC=e=>{let t=e.attempts??3,n=e.base??200,r=e.factor??2,i=e.max??3e4,a=e.jitter??.5;return e=>async(o,s)=>{let c;for(let l=1;l<=t;l+=1)try{return await e(o,s)}catch(e){if(c=e,l>=t)break;await UC(Math.min(i,n*r**(l-1))*(1-a*Math.random()),s)}throw c}},$C=e=>e instanceof kC&&e.status===0&&e.code===`DISCONNECTED`,ew=(e,t)=>{let n=e.maxRetries??1/0,r=e.backoff??1e3;return i=>async(a,o)=>{let s=e.timeout===void 0?1/0:Date.now()+e.timeout,c=0;for(;;)try{return await i(a,o)}catch(e){if(!$C(e)||c>=n)throw e;let i=s-Date.now();if(i<=0)throw e;c+=1,await t.connectivity.whenOnline(o,{timeout:Math.min(r,i)})}}},tw=(e,t)=>{let n=null,r=[],i=0;return a=>{let o=t=>{n&&=(clearTimeout(n),null);let o=r;r=[],i=0;let s=o.map(e=>e.call.data);a(e.accumulate?{data:e.accumulate(s),opts:o[o.length-1].call.opts}:o[o.length-1].call,t).then(t=>{let n=e.spread?e.spread(t,s):null;o.forEach((e,r)=>e.resolve(n?n[r]:t))},e=>o.forEach(t=>t.reject(e)))};return t.push(()=>{n&&=(clearTimeout(n),null);let e=r;r=[],i=0;for(let t of e)t.reject(VC(`cancelled`))}),(t,a)=>new Promise((s,c)=>{let l=Date.now();r.length===0&&(i=l),r.push({call:t,resolve:s,reject:c});let u=e.leading&&n===null&&r.length===1;n&&clearTimeout(n);let d=e.maxWait!==void 0&&l-i>=e.maxWait;if(u||d){o(a);return}let f=e.maxWait===void 0?e.wait:Math.min(e.wait,i+e.maxWait-l);n=setTimeout(()=>o(a),f)})}};function nw(e,t,n,r,i){if(t.items||t.itemsIn||t.streamIn!==null||t.streamOut!==null)return{call:(...e)=>n(...e),cancel:()=>{},invalidate:()=>{},pending:0};let a=t.p.length>0||t.q.length>0||t.hasBody||t.f.length>0,o=i.cache===!0||i.cache===void 0||i.cache===!1?{}:i.cache,s=e=>o.key?o.key(e):NC(e),c=t=>`${e}${BC}${s(t)}`,l=i.cache?r.cacheFor(o.store):null,u={n:0},d=[],f=new AbortController,p=(e,t)=>{let r={...e.opts??{},signal:t};return Promise.resolve(a?n(e.data,r):n(r))},m=[];if((i.onStart||i.onSuccess||i.onError||i.onSettled)&&m.push(KC(i,u)),i.invalidates&&m.push(qC(i.invalidates,i.invalidateOn??`success`,r)),l&&m.push(JC(o,l,c)),i.dedupe&&m.push(YC(c)),i.lastOnly&&m.push(XC()),i.debounce!==void 0){let e=typeof i.debounce==`number`?{wait:i.debounce}:i.debounce;m.push(tw(e,d))}i.rateLimit&&m.push(ZC(i.rateLimit)),i.retry&&m.push(QC(i.retry));let h=t.sideEffects===!1||t.sideEffects===void 0&&t.method===`GET`,ee=i.replay===!1?null:i.replay===void 0?h?{}:null:typeof i.replay==`object`?i.replay:{};ee&&(h||ee.force)&&m.push(ew(ee,r)),(i.onOnline||i.onOffline)&&r.connectivity.subscribe(e=>e===`online`?i.onOnline?.():i.onOffline?.());let te=WC(p,m);return{call:(...e)=>{let t=a?e[0]:void 0,n=a?e[1]:e[0],r=HC([n?.signal,f.signal]);return te({data:t,opts:n},r)},cancel:()=>{f.abort(VC(`cancelled`)),f=new AbortController;for(let e of d)e()},invalidate:()=>void l?.removeWhere(t=>t.startsWith(`${e}${BC}`)),get pending(){return u.n}}}function rw(e){try{let t=JSON.parse(e);return typeof t==`object`&&t&&!Array.isArray(t)?t:null}catch{return null}}function iw(e){let{id:t,...n}=e;return JSON.stringify({rid:typeof t==`string`?t:null,...n})}function aw(e){let{rid:t,...n}=e;return JSON.stringify(typeof t==`string`?{id:t,...n}:n)}function ow(e,t){return JSON.stringify({id:e,$status:0,$code:`DISCONNECTED`,$error:t})}function sw(e){return`$status`in e||e.end===!0}var cw=class{#e=new Set;add(e){this.#e.add(e)}settle(e){typeof e.id==`string`&&sw(e)&&this.#e.delete(e.id)}fail(e,t){let n=[...this.#e];this.#e.clear();for(let r of n)e(ow(r,t))}},lw={$status:501,$code:`NOT_SERVED`,$error:`this client serves no spec`};function uw(e,t){let n=e.rid;typeof n==`string`&&typeof e.type==`string`&&t(JSON.stringify({rid:n,...lw}))}var dw=class{app;send;request;#e=null;constructor(e,t,n){this.app=e,this.send=t,this.request=n}receive(e){let t=this.#e??this.#t();this.app.ws.message(t,aw(e))}drop(){let e=this.#e;e&&(this.#e=null,this.app.ws.close(e))}#t(){let e=this.app.ws.open(t=>{let n=rw(t);n&&this.#e===e&&this.send(iw(n))},this.request());return this.#e=e,e}},fw=new Set([101,204,205,304]);function pw(e,t,n,r,i,a){return new Promise((o,s)=>{if(i?.aborted){s(new DOMException(`The operation was aborted.`,`AbortError`));return}let c=new XMLHttpRequest;c.open(e,t,!0),c.responseType=`arraybuffer`;for(let[e,t]of Object.entries(n))c.setRequestHeader(e,t);c.upload.onprogress=e=>{e.lengthComputable&&a({loaded:e.loaded,total:e.total})};let l=()=>c.abort(),u=()=>i?.removeEventListener(`abort`,l);c.onload=()=>{u();let e=fw.has(c.status)?null:c.response;o(new Response(e,{status:c.status,statusText:c.statusText}))},c.onerror=()=>{u(),s(TypeError(`Network request failed`))},c.onabort=()=>{u(),s(new DOMException(`The operation was aborted.`,`AbortError`))},i?.addEventListener(`abort`,l,{once:!0}),c.send(r)})}function mw(e){return!!e&&typeof e.parse==`function`}function hw(e){let t=gw(e);return t?t():e}function gw(e){let t=e[Symbol.for(`ayepi.manifest`)];return typeof t==`function`?t:void 0}function _w(e){return typeof e==`number`&&e>=200&&e<300}var vw={400:`Bad Request`,401:`Unauthorized`,403:`Forbidden`,404:`Not Found`,405:`Method Not Allowed`,409:`Conflict`,410:`Gone`,422:`Unprocessable Entity`,429:`Too Many Requests`,500:`Internal Server Error`,502:`Bad Gateway`,503:`Service Unavailable`};function yw(e){let t=Number(e.$status);return new kC(t,typeof e.$code==`string`?e.$code:`ERROR`,typeof e.$error==`string`?e.$error:vw[t]??`Request failed with status ${t}`,e.data)}function bw(e){let t=hw(e.manifest),n=e.fetchImpl??(e=>fetch(e)),r=jC(),i=RC(e.cache,r);e.ws?.onState?.(e=>r.report(e===`open`?`online`:`offline`));let a=()=>typeof e.headers==`function`?e.headers():e.headers??{},o=t=>e.unauthorized!==void 0&&Object.keys(t).some(e=>e.toLowerCase()===`authorization`),s=null,c=()=>{let t=e.unauthorized;return t?(s??=t().catch(()=>!1).finally(()=>{s=null}),s):Promise.resolve(!1)},l=t=>e.validate?.endpoints[t]?.cfg,u=(e,t)=>{let n=l(e);return n?.response?n.response.parse(t):t},d=(e,t)=>{let n=l(e);return n&&mw(n.streamOut)?n.streamOut.parse(t):t},f=(e,t,n)=>{let r=l(e)?.responses?.[t];return r?r.parse(n):n},p=0,m=new Map,h=new Map,ee=new Map,te=new Map,ne=new Map,re=(t,n,r)=>{r&&o(a())&&ne.set(t,n),e.ws?.send(n)},ie=e=>{let t=te.get(e);t&&(te.delete(e),t())},ae=(t,n,r)=>{if(!n)return;let i=()=>{te.delete(t),ne.delete(t),r(n.reason)&&e.ws?.send(JSON.stringify({id:t,abort:!0}))};n.aborted?i():(n.addEventListener(`abort`,i,{once:!0}),te.set(t,()=>n.removeEventListener(`abort`,i)))},oe=e=>JSON.stringify(e??{},Object.keys(e??{}).sort());if(e.ws){let t=e.ws,n=e=>t.send(e),r=e.serve?new dw(e.serve,n,()=>new Request(new URL(e.baseUrl,`http://peer.invalid/`))):null;r&&t.onState?.(e=>{e!==`open`&&r.drop()}),t.onMessage(e=>{let i=rw(e);if(!i)return;if(`rid`in i){r?r.receive(i):uw(i,n);return}if(typeof i.id!=`string`){if(typeof i.type==`string`){let e=`${i.type}|${oe(i.params)}`;for(let t of ee.get(e)??[])t(i.data)}return}let a=i.id,o=ne.get(a);ne.delete(a),o!==void 0&&i.$status===401?c().then(e=>{(m.has(a)||h.has(a))&&(e?t.send(o):se(a,i))}):se(a,i)})}function se(e,t){let n=`$status`in t&&!_w(t.$status);if(h.has(e)){let r=h.get(e);`chunk`in t?r.push(t.chunk):t.end===!0?(h.delete(e),ie(e),r.end()):n&&(h.delete(e),ie(e),r.fail(yw(t)))}else if(m.has(e)){let r=m.get(e);m.delete(e),ie(e),n?r.reject(yw(t)):r.resolve(t.data)}}function ce(){let e=[],t=!1,n,r=null;return{push(t){e.push(t),r?.()},end(){t=!0,r?.()},fail(e){n=e,t=!0,r?.()},async*iterate(){for(;;)if(e.length>0)yield e.shift();else{if(n!==void 0)throw n;if(t)return;await new Promise(e=>r=e),r=null}}}}function le(t,n){let r=typeof n==`function`?n():n;(async()=>{try{for await(let n of r)e.ws.send(JSON.stringify({id:t,chunk:n}));e.ws.send(JSON.stringify({id:t,end:!0}))}catch{e.ws.send(JSON.stringify({id:t,end:!0}))}})()}function ue(e,t,n){return JSON.stringify(t.ws===null?{id:e,type:t.path,method:t.method,data:n}:{id:e,type:t.ws,data:n})}function de(t,n,r,i,a){if(!e.ws){let e=Error(`no websocket transport configured`);if(!n.items)return Promise.reject(e);throw e}let o=`c${++p}`;if(n.items){let e=ce();return h.set(o,e),ae(o,a,t=>h.delete(o)?(e.fail(t),!0):!1),re(o,ue(o,n,r),!n.itemsIn),n.itemsIn&&le(o,i),(async function*(){for await(let n of e.iterate())yield d(t,n)})()}let s=new Promise((e,t)=>{m.set(o,{resolve:e,reject:t}),ae(o,a,e=>{let t=m.get(o);return t?(m.delete(o),t.reject(e),!0):!1}),re(o,ue(o,n,r),!1)});return n.itemsIn&&le(o,i),s.then(e=>n.multi?e:u(t,e))}function fe(t,n){if(!e.ws)return Promise.reject(Error(`no websocket transport configured`));let r=`c${++p}`;return new Promise((e,i)=>{m.set(r,{resolve:e,reject:i}),ae(r,n,e=>{let t=m.get(r);return t?(m.delete(r),t.reject(e),!0):!1}),re(r,JSON.stringify({id:r,...t}),!0)})}function g(e,t){if(e.b===`raw`)return{p:{},q:{},b:t,f:{}};let n={},r={},i={},a={},o=new Set(e.p),s=new Set(e.q),c=new Set(e.b??[]),l=new Set(e.f);for(let[e,u]of Object.entries(t??{}))if(o.has(e))n[e]=u;else if(s.has(e))r[e]=u;else if(c.has(e))i[e]=u;else if(l.has(e))a[e]=u;else throw Error(`key "${e}" does not belong to endpoint data`);return{p:n,q:r,b:e.hasBody?i:void 0,f:a}}function pe(t,n,r){let i=DC(TC(t.path),n),a=new URL(i.slice(1),e.baseUrl.endsWith(`/`)?e.baseUrl:e.baseUrl+`/`);for(let[e,t]of Object.entries(r))if(t!==void 0){if(Array.isArray(t))for(let n of t)a.searchParams.append(e,String(n));else a.searchParams.set(e,String(t))}return a}function me(e){let t=(typeof e==`function`?e():e)[Symbol.asyncIterator](),n=new TextEncoder;return new ReadableStream({async pull(e){let{done:r,value:i}=await t.next();if(r)return e.close();e.enqueue(n.encode(JSON.stringify(i)+`
|
|
395
|
-
`))},async cancel(){await t.return?.(void 0)}})}async function he(e,t,i,s=!1){let{p:l,q:u,b:d,f}=g(e,t),p=i?.stream,m=pe(e,l,u),h={...a(),...i?.headers??{}},ee=null,te=!1;if(e.streamIn)h[`content-type`]=e.streamIn,e.itemsIn?(ee=me(p),te=!0):(ee=p,te=p instanceof ReadableStream);else if(e.f.length>0){let e=new FormData;d!==void 0&&e.set(`body`,JSON.stringify(d));for(let[t,n]of Object.entries(f))if(n!==void 0){if(Array.isArray(n))for(let r of n)e.append(t,r);else e.set(t,n)}ee=e}else if(e.hasBody){if(e.bodyEnc===`urlencoded`){h[`content-type`]=`application/x-www-form-urlencoded`;let e=new URLSearchParams;for(let[t,n]of Object.entries(d??{}))if(n!==void 0){if(Array.isArray(n))for(let r of n)e.append(t,String(r));else e.set(t,String(n))}ee=e.toString()}else h[`content-type`]=`application/json`,ee=JSON.stringify(d)}let ne={method:e.method,headers:h,body:ee,signal:i?.signal};te&&(ne.duplex=`half`);let re=i?.onUploadProgress,ie;try{ie=re&&!e.streamIn&&!e.streamOut&&typeof XMLHttpRequest<`u`?await
|
|
394
|
+
${o}`,s.clear()),{code:o,types:new Map(i.types),helpers:s,functions:[a]}}var tb=class{constructor(e){this.registry=e}registry;globals=new Map;registerGlobal(e,t){return this.globals.set(e,t),this}getGlobal(e){return this.globals.get(e)}getGlobals(){return this.globals}parse(e){if(!e||typeof e!=`object`||!(`kind`in e))throw Error(`engine.parse: expected ExprDef with kind, got ${typeof e}`);return e}createRootScope(e,t){let n=new Dh(null,void 0,t);for(let[e,t]of this.globals)n.vars.set(e,G(t.type,t.value));if(e)for(let[t,r]of Object.entries(e))n.vars.set(t,r);return n}async run(e,t,n){let r=n?new Ng(n):void 0;r?.check();let i=this.createRootScope(t,r);try{return await this.evaluate(e,i)}catch(e){if(e instanceof Lh)return e.value??G(this.registry.void(),void 0);throw e}}typeOf(e,t){let n=t??this.globalTypeScope();return Oh(this,e,n)}validate(e,t,n){let r=t??this.globalTypeScope();return Ah(this,e,r,n)}toCode(e,t){return this.registry.toCode(e,t)}toGinCode(e,t){return this.registry.toGinCode(e,t)}toJSONCode(e,t=2){return this.registry.toJSONCode(e,t)}toTypeScript(e,t){return eb(this,e,t)}globalTypeScope(){let e=new Map;for(let[t,n]of this.globals)e.set(t,n.type);return e}async evaluate(e,t){return(e instanceof wh?e:this.registry.parseExpr(e)).evaluate(this,t)}async validateValue(e,t){let n=new rh,r=e.type.constraints();if(r.length===0)return n;let i=t??this.createRootScope();for(let t=0;t<r.length;t++){let a=r[t],o=i.child({this:e});try{(await a.evaluate(this,o)).raw!==!0&&n.at(`constraint[${t}]`,()=>n.error(`constraint.failed`,`value failed constraint: ${a.toCode(this.registry,{expectsValue:!0})}`))}catch(e){n.at(`constraint[${t}]`,()=>n.error(`constraint.threw`,`constraint threw: ${e.message}`))}}return n}};function nb(e){return new tb(e)}var rb=`^[a-z]\\S*$`,ib=`A fn's name, as your tools spell it.`;function ab(e){if(e.name!==`text`)return!1;let t=e.options;return typeof t==`object`&&!!t&&`pattern`in t&&t.pattern===`^[a-z]\\S*$`}var ob=R.string().pattern(rb).describe(ib);function sb(e){return R.codec(ob,{decode:t=>e.fn(t)??Error(`${t} names no fn: write a fn's name as your tools spell it.`),encode:t=>e.name(t)})}var cb=new WeakMap,lb=0;function ub(e){if(e===void 0)return 0;let t=cb.get(e);return t===void 0&&cb.set(e,t=++lb),t}var db=th.declare().dynamic((e,t,n)=>({...Xm(e,n),FnName:t===void 0?ob:sb(t)}),{key:(e,t,n)=>`${eh(e,n)}|${ub(t)}`,cacheSize:4}),fb={result:e=>db.result(e)},pb=e=>ab(e)?R.ref(`FnName`):void 0;function mb(e,t={}){return e.toA({...t.scope===void 0?{}:{scope:t.scope},...t.includeDocs===void 0?{}:{includeDocs:t.includeDocs},...t.unknownKeys===void 0?{}:{unknownKeys:t.unknownKeys},override:pb})}function hb(e,t={}){return fb.result(mb(e,t))}var gb=new WeakMap,_b=new WeakMap;function vb(e,t){let n=t.unknownKeys??`strip`,r=gb;t.scope!==void 0&&(r=_b.get(t.scope)??new WeakMap,_b.set(t.scope,r));let i=r.get(e)??new Map;r.set(e,i);let a=i.get(n);if(a!==void 0)return a;let o=hb(e,{...t,includeDocs:`none`});return i.set(n,o),o}function yb(e,t={}){let{namedRefs:n,...r}=t;return vb(e,r).bind(e.registry,void 0,n===!0?{namedRefs:!0}:void 0)}function bb(e){return e.map(String).join(`.`)}function xb(e,t,n={}){let r=yb(e,n).render($l).parse(t,{inPlace:!1,...n.repair===void 0?{}:{repair:n.repair},...n.label===void 0?{}:{label:n.label}});return r.ok?{ok:!0,value:r.value}:{ok:!1,problems:r.issues.map(e=>({path:bb(e.codePath),message:e.message})),message:r.message}}var Sb=v().regex(/^[a-z][A-Za-z0-9_-]{0,63}$/).brand(),Cb=`[A-Za-z0-9](?:[A-Za-z0-9-]|_(?![_.]|$))*`,wb=RegExp(`^${Cb}(?:\\.${Cb})*$`);v().regex(wb,"a fn name is letters, digits, `_` and `-` in dot-separated parts, each starting with a letter or digit, with no `__` and no part ending in `_`");function Tb(e){if(!wb.test(e))return e.includes(`__`)?`${e} holds \`__\`, which separates the parts of the name the model calls it by: write one \`_\``:/(?:^|\.)_|_(?:\.|$)/.test(e)?`a part of ${e} starts or ends with \`_\`: start each part with a letter or digit and end it with no \`_\``:`${e} is not a fn name: letters, digits, \`_\` and \`-\` in dot-separated parts, each starting with a letter or digit`}function Eb(e){let{system:t,local:n}=Il(e);return`${t}__${n.replaceAll(`.`,`__`)}`}function Db(e){return e.length===64&&/_x[0-9a-f]{8}$/.test(e)}function Ob(e){return Eb(e).length>64}function kb(e){if(Db(e))return;let t=e.indexOf(`__`);if(t<=0)return;let n=e.slice(0,t),r=e.slice(t+2).split(`__`).join(`.`);if(!Nl.test(n)||!wb.test(r))return;let i=I.safeParse(`${n}/${r}`);return i.success&&!Ob(i.data)&&Eb(i.data)===e?i.data:void 0}function Ab(e,t){let n=I.safeParse(e);if(n.success)return n.data;let r=t?.(e);return r===void 0?e.includes(`--`)?jb(e)??kb(e):kb(e)??jb(e):r}function jb(e){if(e.length>=64)return;let t=I.safeParse(e.replace(`__`,`/`).replaceAll(`--`,`.`));if(t.success)return t.data.replaceAll(`/`,`__`).replaceAll(`.`,`--`).replace(/[^A-Za-z0-9_-]/g,`_`).slice(0,64)===e?t.data:void 0}S({model:Sb,fn:I,until:N}),S({model:Sb,fn:I,system:F});var Mb=I.describe(ib),Nb=v().min(1).regex(/^\S+$/,`a type's name, with no spaces`);Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);var Pb=/^https?:\/\/[^\s\u0000-\u001f\u007f]+$/i;function Fb(e){try{let{protocol:t}=new URL(e);return t===`http:`||t===`https:`}catch{return!1}}var Ib=v().regex(Pb,`expected an http or https URL`).refine(Fb,`expected an http or https URL`);function Lb(e){return Ib.safeParse(e).success}var Rb=`outsideImages`,zb=E([`ask`,`always`]),Bb=S({value:zb,setBy:M.optional(),updatedAt:N.optional()}),Vb=`https`,Hb={der:`/harness-ca.crt`,pem:`/harness-ca.pem`},Ub=E([`own`,`files`]),Wb=S({on:b(),source:Ub,setBy:M.optional(),updatedAt:N.optional(),fingerprint:v().optional(),authorityName:v().optional(),host:v(),links:x(v())}),Gb=v().regex(/^(?:\*|[a-z*][a-z0-9*-]*\/[A-Za-z0-9_*][A-Za-z0-9_.*-]*)$/,`an agent's name (crm/reviewer) or a pattern (hub/chat*, crm/*, *)`).refine(e=>!e.includes(`**`),`write one *`),Kb=S({into:x(Gb).min(1),order:y().int().min(0).max(1e3).default(100),requires:x(I).default([]),mode:E([`tools`,`static`]).optional(),replaces:x(I).optional()}),qb=C([D(`none`),S({detail:E([`full`,`summary`]).default(`full`),maxTokens:y().int().min(1).optional()})]),Jb=S({target:Gb,agents:x(I)}),Yb=E([`approved`,`pending`,`declined`]);S({context:I,system:F,title:v(),inject:Kb,fns:x(I),targets:x(Jb),agents:x(I),review:Yb,off:b(),dynamic:b()}),S({hook:I,system:F,explains:v(),review:Yb});var Xb=S({section:E([`context`,`hooks`]),name:I,title:v(),change:E([`added`,`changed`,`removed`]),tokens:y().int().min(0).optional(),targets:x(Jb),agents:x(I),replaces:x(I).optional()});S({agent:I,context:I,on:b(),order:y().int().min(0).max(1e3).optional(),by:M,at:N});var Zb=E([`off`,`pending`,`declined`,`system-off`,`fns-unusable`,`mode`,`replaced`,`no-fit`]),Qb=S({agent:I,context:I,source:w(`type`,[S({type:D(`context`)}),S({type:D(`hook`),hook:I})]),system:F,via:Gb,title:v(),detail:E([`full`,`summary`]),text:v(),tokens:y().int().min(0),order:y().int(),on:b(),leftOut:S({why:Zb,reason:v()}).optional(),switched:S({by:M,at:N}).optional()}),$b=S({injections:x(Qb),targets:x(Jb)}),ex=S({agent:I,context:I,on:b().optional(),order:y().int().min(0).max(1e3).nullable().optional()}),tx=[`listed`,`signature`,`full`],nx=E(tx),rx=S({fn:I,detail:nx}),ix=S({type:D(`tools`)}),ax=E([`auto`,`native`,`text`]),ox=E([`system-end`,`tail`]),sx=w(`type`,[ix,S({type:D(`static`),protocol:ax.default(`auto`),placement:ox.default(`system-end`),loadDetail:nx.default(`full`)})]),cx=E(sx.options.map(e=>e.shape.type.value));E([`find`,`find_ctx`,`inspect`,`load`,`unload`,`run`]);var lx=S({fn:v().min(1).describe(`The fn to run, by its qualified name (fs/read).`),args:T(v(),Zc()).default({}).describe(`Its args, as its card shows them.`),on:L.optional().describe(`For a system with several machines connected, which one runs it (laptop).`)}),ux=S({type:D(`plain`)}),dx=S({type:D(`suggest`),topN:y().int().min(0).default(6),autoInject:S({tokens:y().int().min(0),items:y().int().min(0)}).optional()}),fx=E([`embedding`,`words`,`turnsAgo`,`age`,`selectedBefore`,`used`]),px=S({weight:y().min(0),target:y().optional(),k:y().positive().optional()}),mx=E([`perMessage`,`perIteration`]),hx=[`history`,`context`,`fns`],gx=E(hx),_x=T(gx,y().min(0)),vx=w(`type`,[ux,dx,S({type:D(`graph`),metrics:bc(fx,px).default({}),spread:S({damping:y().min(0).max(.95).default(.5),hops:y().int().min(0).max(4).default(2)}).prefault({}),floorExchanges:y().int().min(0).default(1),shares:_x.default({history:.45,context:.35,fns:.2}),threshold:y().min(0).default(.15),evaluate:mx.default(`perMessage`)})]),yx=E(vx.options.map(e=>e.shape.type.value)),bx=S({contextWindow:y().int().min(256).optional(),maxOutputTokens:y().int().min(16).optional(),reasoningTokens:y().int().min(0).optional(),charsPerToken:y().min(1).max(8).optional()}),xx=bx.keyof();xx.options;var Sx=bx.required(),Cx=E([`admin`,`probe`,`model-info`,`default`]),wx=S({model:v(),limits:Sx,sources:T(xx,Cx),ratio:y()});S({model:v(),limits:bx,setBy:M,updatedAt:N}),S({model:v(),ratio:y().min(.5).max(2),samples:y().int().min(0),updatedAt:N});var Tx=S({asked:y().int().min(0),got:y().int().min(0)}),Ex=S({window:y().int().min(0),output:y().int().min(0),reasoning:y().int().min(0),margin:y().int().min(0),fixed:y().int().min(0),pools:T(gx,Tx),estimate:y().int().min(0),cut:x(S({what:v(),why:v()}))}),Dx=S({name:I,detail:nx,activation:y().min(0)}),Ox=S({tokens:y().int().min(0),items:x(S({name:I,detail:E([`full`,`summary`,`listed`]),tokens:y().int().min(0)})),leftOut:x(S({name:I,why:Zb,reason:v()})),rebuilt:S({added:x(I),dropped:x(I)}).optional()}),kx=S({contextor:yx,mode:cx,context:x(Dx),fns:x(Dx),linear:y().int().min(0),earlier:x(y().int().min(0)),budget:Ex,injected:Ox.optional()}),Ax=S({session:j,text:v().min(1),model:v().min(1).optional(),count:x(v()).max(200).optional()}),jx=S({agent:I,model:v(),window:y().int().min(0),maxTokens:y().int().min(0),estimate:y().int().min(0),system:v(),tools:x(S({name:v(),description:v(),parameters:Zc(),tokens:y().int().min(0)})),messages:x(S({role:v(),content:v(),tokens:y().int().min(0)})),parts:S({instructions:v(),injected:v(),context:v(),guide:v(),tokens:S({instructions:y().int(),injected:y().int(),context:y().int(),guide:y().int(),system:y().int()})}),counts:x(y().int().min(0)),report:kx}),Mx=S({turn:cl,items:x(Dx),at:N}),Nx=[`none`,`read`,`write`,`delete`,`auto`],Px=E(Nx),Fx=S({name:v().optional(),sheetName:v().optional(),sheetIndex:y().int().nonnegative().optional(),headers:x(v()),rows:x(x(v()))});E([`empty`,`boolean`,`integer`,`number`,`date`,`text`]);var Ix=E([`file`,`folder`,`link`,`other`]);S({entries:x(S({name:v(),location:v(),kind:Ix,type:v().optional(),size:y().nonnegative().optional(),modifiedAt:y().optional()})),truncated:b(),total:y().int().nonnegative()});var Lx={converter:v(),from:v(),title:v().optional(),metadata:T(v(),sc()).optional()},Rx=w(`kind`,[S({kind:D(`markdown`),...Lx,text:v()}),S({kind:D(`text`),...Lx,text:v()}),S({kind:D(`code`),...Lx,language:v(),text:v()}),S({kind:D(`pages`),...Lx,pages:x(v())}),S({kind:D(`table`),...Lx,tables:x(Fx)})]),zx=Rx.options.map(e=>e.shape.kind.value),Bx=/^(?:true|false|yes|no)$/i,Vx=/^[-+]?\d{1,15}$/,Hx=/^[-+]?(?:\d{1,3}(?:,\d{3})+|\d+)?(?:\.\d+)?(?:e[-+]?\d+)?%?$/i,Ux=/^\d{4}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[-+]\d{2}:?\d{2})?)?$|^\d{1,2}\/\d{1,2}\/\d{2,4}$/;function Wx(e){return Bx.test(e)?`boolean`:Vx.test(e)?`integer`:/\d/.test(e)&&Hx.test(e)?`number`:Ux.test(e)&&!Number.isNaN(Date.parse(e))?`date`:`text`}function Gx(e,t){return e===`empty`||e===t?t:e===`integer`&&t===`number`||e===`number`&&t===`integer`?`number`:`text`}function Kx(e){let t=Math.max(e.headers.length,...e.rows.map(e=>e.length));return Array.from({length:t},(t,n)=>{let r=`empty`;for(let t of e.rows){let e=(t[n]??``).trim();e!==``&&(r=Gx(r,Wx(e)))}return r})}var qx=Wc([v().regex(/^[a-z][a-z0-9+.-]*$/),`://`,v()]),Jx=v().min(1).brand(),Yx=`^[0-9a-f]{64}$`,Xx=new RegExp(Yx),Zx=S({hash:v().regex(Xx),size:y().int().min(0),mime:v()});S({content:Zx,mime:v(),finalUrl:v(),status:y().int(),rendered:b(),title:v().optional()});var Qx=S({uri:qx,name:v(),description:v(),index:E([`all`,`on-read`,`none`]),ignore:x(v()),watch:b()}),$x=S({uri:qx,name:v(),type:E([`folder`,`file`,`page`,`record`,`other`]),mime:v().optional(),format:v().optional(),size:y().int().min(0).optional(),modifiedAt:N.optional(),version:v()}),eS=S({uri:qx.optional(),raw:v(),kind:E([`child`,`import`,`link`,`embed`,`external`]),title:v().optional()}),tS=E([`links`,`text`,`bytes`]),nS=C([S({inline:v()}),S({ref:Zx})]),rS=S({stat:$x,links:x(eS).optional(),text:nS.optional(),bytes:Zx.optional()});E(zx);var iS=[`description`,`ocr`,`transcript`,`thumbnail`];E(iS);var aS=E([...zx,...iS]),oS=S({key:Jx,path:x(v()),title:v(),start:y().int().min(0),end:y().int().min(0),embedText:v().optional(),form:aS.optional()}),sS=S({uri:qx,change:E([`added`,`changed`,`removed`]),version:v().optional()}),cS=S({format:v().optional(),mime:v().optional(),glob:v().optional(),form:aS.optional()}),lS=C([S({resource:qx,section:Jx.optional(),title:v().optional()}),S({url:Ib,title:v()}),S({file:Zx,title:v()}),S({run:A,title:v()})]),uS=S({uri:qx,section:Jx.optional(),title:v(),preview:v(),rank:y()}),dS=Gi();function fS(e,t){return dS.add(e,{why:t}),e}function pS(e){let t=e;for(;t!==void 0;){if(dS.has(t))return!0;t=t instanceof Tc||t instanceof jc||t instanceof Nc||t instanceof kc||t instanceof Vc?t.unwrap():void 0}return!1}function mS(e){let t=e.shape;return Object.entries(t).filter(([,e])=>pS(e)).map(([e])=>e)}var hS=new WeakMap;function gS(e,t){return hS.set(e,{schema:t}),e}var _S=w(`to`,[S({to:D(`session`),session:j}),S({to:D(`user`),user:M}),S({to:D(`everyone`)})]),vS=E([`live`,`snapshot`]),yS=w(`type`,[S({type:D(`system`)}),S({type:D(`memory`),scope:_S,author:M,run:A.optional()}),S({type:D(`resource`),uri:qx,section:Jx.optional(),version:v(),copy:vS})]),bS=[`system`,`memory`,`resource`],xS=S({full:y().int().min(0),summary:y().int().min(0)}),SS=E([`imports`,`brings`,`suggests`,`parent`,`next`,`related`,`mentions`,`about`,`learned`]),CS=[`imports`,`brings`,`suggests`,`parent`,`next`,`related`,`about`],wS=E(CS),TS=w(`kind`,[S({kind:D(`context`),name:I}),S({kind:D(`fn`),name:Mb}),S({kind:D(`type`),name:I}),S({kind:D(`resource`),uri:qx,section:Jx.optional()})]),ES=[`fn`,`context`,`resource`,`type`],DS=S({to:TS,relation:wS,weight:y().min(0).max(1).default(.5)}),OS=E([`declared`,`mentioned`,`resource`,`learned`,`authored`]),kS=S({from:I,to:TS,toKey:v(),relation:SS,weight:y().min(0).max(1),source:OS,uses:y().min(0).optional(),by:M.optional(),updatedAt:N}),AS=S({weight:y().min(0).max(2).optional(),summary:v().optional(),tags:x(v().min(1)).optional(),fns:x(Mb).optional(),suggestFns:x(Mb).optional(),inject:fS(Kb.optional(),`a model never writes text that lands in later prompts`),command:v().regex(/^[a-z][a-z0-9-]*$/).optional(),visible:zl.optional(),suggest:zl.optional(),parent:I.optional()}),jS=S({text:v().min(1),title:v().optional(),scope:E([`session`,`user`,`everyone`]).default(`session`),about:x(TS).optional(),question:v().min(1).max(500).optional(),when:v().min(1).max(500).optional()}).extend(AS.shape),MS=AS.keyof().exclude(AS.keyof().options.filter(e=>mS(AS).includes(e))),NS=jS.omit({scope:!0}).partial().extend({name:I,clear:gS(x(AS.keyof()).optional(),x(MS).optional())}),PS=S({uri:qx,sections:x(Jx).optional(),copy:vS.default(`live`)}).extend(AS.omit({summary:!0,parent:!0}).shape),FS=S({created:x(I),updated:x(I),links:y().int().min(0)}),IS={maxDepth:3,maxDecisions:256,maxTokens:8e3},LS=[`active`,`hidden`,`not_applicable`,`pending_approval`,`pending_removal`,`pending_plan`],RS=E(LS),zS=E([`active`,`hidden`,`not_applicable`,`pending_approval`,`pending_removal`]);function BS(e){return e===`active`||e===`pending_removal`}var VS=[`person`,`system`,`research`],HS=E(VS),US=S({status:RS,from:RS.optional(),by:M,reason:v().optional(),at:N}),WS=S({of:I,similarity:y().min(0).max(1).optional(),reason:v(),at:N}),GS=E([`question`,`when`,`askedBy`,`validUntil`]),KS=S({model:v(),at:N,contentHash:v(),fields:x(GS)}),qS=S({from:I.optional(),into:x(I).optional()}),JS=`newContextStatus`,YS=E([`active`,`pending_approval`,`hidden`]),XS=S({value:YS,setBy:M.optional(),updatedAt:N.optional()}),ZS=E([`question`,`content`]),QS=S({statuses:x(zS).min(1).optional(),returnNotApplicable:b().optional(),semanticOver:ZS.optional()}),$S=[`approve`,`hide`,`restore`,`confirm_removal`],eC=E($S),tC=S({names:x(I).min(1).max(200),action:eC,reason:v().min(1).max(500).optional()}),nC=S({changed:x(S({name:I,status:C([RS,D(`removed`)])})),skipped:x(S({name:I,reason:v()}))}),rC=[`duplicate`,`contradiction`,`pending_approval`,`pending_removal`],iC=E(rC),aC=S({kinds:x(iC).min(1).optional(),systems:x(v().min(1)).min(1).optional(),limit:y().int().min(1).max(200).optional(),cursor:v().optional()}),oC=S({name:I,system:v(),title:v(),question:v().optional(),status:RS,statusReason:v().optional(),lastModified:N,excerpt:v().optional()}),sC=S({items:x(S({kind:iC,item:oC,other:oC.optional(),flag:WS.optional()})),next:v().optional(),counts:S({duplicate:y().int().min(0),contradiction:y().int().min(0),pending_approval:y().int().min(0),pending_removal:y().int().min(0)})}),cC=S({keep:I,drop:I,reason:v().min(1).max(500).optional()}),lC=S({kept:I,hidden:I,links:y().int().min(0),mentions:y().int().min(0)}),uC=S({name:I,of:I}),dC=S({names:x(I).min(1).max(20)}),fC=S({done:x(S({name:I,fields:x(GS),split:x(I).optional()})),failed:x(S({name:I,reason:v()}))}),pC=S({name:I,question:v().optional(),when:v().optional(),askedBy:HS.optional(),validUntil:N.optional(),lastModified:N,status:RS,statusReason:v().optional(),statusHistory:x(US),metadata:KS.optional(),metadataStale:b(),duplicate:WS.optional(),contradiction:WS.optional(),notDuplicates:x(I),split:qS.optional()}),mC={openQuestions:60,depth:6,minutes:10,cost:2},hC=S({openQuestions:y().int().min(1).max(500).optional().describe(`The most open (unanswered) questions the plan may hold; planning stops when it is reached. Default 60.`),depth:y().int().min(1).max(12).optional().describe(`How many levels of questions deep the plan may go (1: only the first questions and their options). Default 6.`),minutes:y().min(.1).max(120).optional().describe(`The most minutes planning may take. Default 10.`),cost:y().min(0).max(100).optional().describe(`The most US dollars the model calls may cost. Default 2.`)}),gC=S({openQuestions:y().int().min(1),depth:y().int().min(1),minutes:y().min(0),cost:y().min(0)}),_C=E([`complete`,`open_questions`,`depth`,`time`,`cost`,`stopped`]),vC={complete:`Every question has its options`,open_questions:`Stopped at the open-question limit`,depth:`Stopped at the depth limit`,time:`Stopped at the time limit`,cost:`Stopped at the cost limit`,stopped:`Stopped before it finished`},yC=v().regex(/^o\d+$/),bC=S({id:yC,label:v().min(1).max(200),detail:v().max(1e3).optional(),raises:x(I),later:x(v().min(1).max(500)).optional()}),xC=S({question:I,option:yC}),SC=S({name:I,question:v().min(1),askedBy:HS.optional(),depth:y().int().min(1),parents:x(xC),options:x(bC),planned:b(),known:b().optional(),picked:x(yC),text:v().max(4e3).optional(),answeredBy:M.optional(),answeredAt:N.optional(),status:RS,statusReason:v().optional(),reasonEdited:b().optional()}),CC=S({questions:y().int().min(0),answered:y().int().min(0),open:y().int().min(0),ruledOut:y().int().min(0),decide:y().int().min(0)}),wC=S({description:v().min(1),limits:gC,stop:_C,cost:P,time:y().min(0),startedAt:N,updatedAt:N,roots:x(I),questions:x(SC),counts:CC,revision:y().int().min(0)}),TC=S({description:v().trim().min(1).max(4e3).describe(`What is to be planned, in the person's words with whatever they said about it: the more it says, the better the questions.`),limits:hC.optional()}),EC=S({run:A.describe(`The run of hub/ctx_plan that made the plan (its id, such as run_01HZX3).`)}),DC=EC.extend({format:E([`plan`,`markdown`]).optional().describe("`plan` (the default): the plan itself; `markdown`: the questions, answers and what was ruled out, as markdown to read or share.")}),OC=S({run:A,plan:wC,markdown:v().optional()}),kC=S({question:I.describe(`The question, by its context name as the plan gives it.`),picked:x(v().min(1)).max(20).describe(`The options chosen, by id (o1) or label; several when more than one applies. Empty with no text clears the answer.`),text:v().max(4e3).optional().describe(`The person's own words with the answer: a detail, a condition, or an answer none of the options gives.`)}),AC=S({question:I,reason:v().trim().min(1).max(500)}),jC=EC.extend({answers:x(kC).max(100).optional(),reasons:x(AC).max(100).optional()}),MC=S({run:A,plan:wC,changed:x(S({name:I,status:RS})),deeper:x(I),skipped:x(S({question:v(),reason:v()}))}),NC=EC.extend({under:I.optional().describe(`The question to plan deeper under, by its context name; leave out to go on with the whole plan.`),replan:b().optional().describe(`Write the options of the open questions under it again, taking the answers given since into account (after an answer changed).`),limits:hC.optional().describe("Limits of its own. Its `depth` is counted from the question it plans under (1: only the questions right under it), or, without `under`, from the deepest level that already has options.")}),PC=S({run:A,description:v(),counts:CC,stop:_C.optional(),running:b(),actor:M,session:v().optional(),createdAt:N,updatedAt:N}),FC=S({limit:y().int().min(1).max(100).optional()}),IC=S({items:x(PC)});function LC(e){return e.known===!0||e.picked.length>0||(e.text??``).trim()!==``}function RC(e){return e.options.filter(t=>e.picked.includes(t.id)).map(e=>e.label)}function zC(e){let t=RC(e).map(e=>`"${e}"`);return`${t.length>0?t.join(` and `):`none of the options`} for '${e.question}'`}function BC(e){return`You chose ${zC(e)}`}function VC(e,t){return`'${e.question}' no longer applies${t===void 0?``:`: you chose ${zC(t)}`}`}function HC(e,t){return e.picked.length===0||e.picked.includes(t)}function UC(e,t){let n=new Set(t),r=[...t];for(let t=r.shift();t!==void 0;t=r.shift()){let i=e.get(t);if(i!==void 0){for(let t of i.options)if(HC(i,t.id))for(let i of t.raises)!n.has(i)&&e.has(i)&&(n.add(i),r.push(i))}}return n}function WC(e,t){return e.picked.length>0&&!e.picked.includes(t)}function GC(e){let t=new Map(e.questions.map(e=>[e.name,e])),n=UC(t,e.roots.filter(e=>{let n=(t.get(e)?.parents??[]).filter(n=>n.question!==e&&t.has(n.question));return n.length===0?t.has(e):!n.every(e=>{let n=t.get(e.question);return n!==void 0&&WC(n,e.option)})})),r=e=>e.parents.flatMap(n=>{let r=t.get(n.question);return r===void 0||n.question===e.name?[]:[{edge:n,parent:r}]}),i=e=>{let t=r(e).filter(e=>WC(e.parent,e.edge.option)).map(e=>e.parent);return t.find(e=>n.has(e.name))??t[0]},a=(e,t)=>{if(t.has(e.name))return;t.add(e.name);let n=i(e);if(n!==void 0)return n;for(let{parent:n}of r(e)){let e=a(n,t);if(e!==void 0)return e}},o=new Map;for(let t of e.questions){if(n.has(t.name)){o.set(t.name,{live:!0});continue}let e=i(t);if(e!==void 0){o.set(t.name,{live:!1,reason:BC(e)});continue}let s=r(t)[0]?.parent;s===void 0?o.set(t.name,{live:!1,reason:`It no longer sits under any question of the plan`}):o.set(t.name,{live:!1,reason:VC(s,a(s,new Set([t.name])))})}return o}function KC(e){return`${e.answered} answered · ${e.open} open · ${e.decide} ${e.decide===1?`decision`:`decisions`} to make now`}y().int().min(1).max(65535).default({hub:4300,web:4310,mockHub:4320}.hub);function qC(e){return e.split(`/`).filter((e,t)=>t!==0||e!==``).map(e=>e.startsWith(`:`)?{t:`param`,k:e.slice(1)}:{t:`lit`,v:e})}function JC(e){return`/`+e.map(e=>e.t===`param`?`:${e.k}`:e.v).join(`/`)}function YC(e,t){return`/`+e.map(e=>{if(e.t===`lit`)return e.v;let n=t[e.k];if(n===void 0)throw Error(`path is missing a value for ":${e.k}"`);return encodeURIComponent(String(n))}).join(`/`)}function XC(e){return e.filter(e=>e.t===`param`).map(e=>e.k)}var ZC=class extends Error{status;code;data;constructor(e,t,n,r){super(n??t),this.status=e,this.code=t,this.data=r,this.name=`ApiError`}},QC=()=>{let e=globalThis.navigator;return typeof e?.onLine==`boolean`?e.onLine:void 0};function $C(e={}){let t=new Set,n=e.initial??(QC()===!1?`offline`:`online`),r=e=>{if(e!==n){n=e;for(let n of[...t])n(e)}},i=e=>(t.add(e),()=>void t.delete(e)),a=()=>{},o=globalThis;if((e.browser??!0)&&typeof o.addEventListener==`function`&&typeof o.removeEventListener==`function`){let e=()=>r(`online`),t=()=>r(`offline`);o.addEventListener(`online`,e),o.addEventListener(`offline`,t),a=()=>{o.removeEventListener(`online`,e),o.removeEventListener(`offline`,t)}}return{get status(){return n},subscribe:i,whenOnline:(e,t)=>new Promise((r,a)=>{if(n===`online`){r();return}if(e?.aborted){a(e.reason);return}let o=null,s=t=>{l(),o&&clearTimeout(o),e?.removeEventListener(`abort`,c),t()};function c(){s(()=>a(e.reason))}let l=i(e=>{e===`online`&&s(r)});t?.timeout!==void 0&&(o=setTimeout(()=>s(r),t.timeout)),e?.addEventListener(`abort`,c,{once:!0})}),report:r,dispose:()=>{a(),a=()=>{}}}}var ew=e=>{if(Array.isArray(e))return e.map(ew);if(e&&typeof e==`object`){let t={};for(let n of Object.keys(e).sort())t[n]=ew(e[n]);return t}return e},tw=e=>JSON.stringify(ew(e))??`null`,nw=e=>{try{return JSON.stringify(e)!==void 0}catch{return!1}},rw=(e,t)=>({get:n=>e.getItem(t+n)??void 0,set:(n,r)=>e.setItem(t+n,r),delete:n=>{let r=t+n,i=e.getItem(r)!==null;return e.removeItem(r),i},keys:function*(){for(let n=0;n<e.length;n++){let r=e.key(n);r!==null&&r.startsWith(t)&&(yield r.slice(t.length))}}}),iw=(e,t)=>{if(typeof e==`object`)return e;if(e!==`memory`)try{let n=e===`local`?globalThis.localStorage:globalThis.sessionStorage;if(n)return rw(n,t)}catch{}let n=new Map;return{get:e=>n.get(e),set:(e,t)=>void n.set(e,t),delete:e=>n.delete(e),keys:()=>n.keys()}};function aw(e={}){let t=e.max??500,n=e.ttl??0,r=e.now??Date.now,i=iw(e.store??`memory`,e.prefix??`ayepi:cache:`),a=new Map;for(let e of i.keys())a.set(e,!0);let o=e=>{a.delete(e),a.set(e,!0)},s=e=>{let t=i.get(e);if(t!==void 0)try{return JSON.parse(t)}catch{i.delete(e);return}},c=e=>(a.delete(e),i.delete(e)),l=()=>{for(;a.size>t;)c(a.keys().next().value)};return{read:e=>{let t=s(e);if(!t)return;let n=r();if(t.exp&&n>=t.exp){if(!t.stale||n>=t.stale){c(e);return}return o(e),{value:t.v,stale:!0}}return o(e),{value:t.v,stale:!1}},write:(e,t,a)=>{if(!nw(t))return;let s=a?.ttl??n,c=s>0?r()+s:0,u={v:t,exp:c,stale:c&&a?.staleWhileRevalidate?c+a.staleWhileRevalidate:0,tags:a?.tags??[]};i.set(e,JSON.stringify(u)),o(e),l()},remove:e=>void c(e),removeWhere:e=>{let t=0;for(let n of[...i.keys()])e(n)&&c(n)&&(t+=1);return t},invalidateTags:e=>{if(e.length===0)return 0;let t=new Set(e),n=0;for(let e of[...i.keys()]){let r=s(e);r&&r.tags.some(e=>t.has(e))&&c(e)&&(n+=1)}return n},clear:()=>{for(let e of[...i.keys()])i.delete(e);a.clear()}}}function ow(e={},t=$C()){let n=new Map,r=t=>{let r=t??e.store??`memory`,i=n.get(r);return i||(i=aw({...e,store:r}),n.set(r,i)),i};return{cacheFor:r,invalidateTags:e=>{r(void 0);for(let t of n.values())t.invalidateTags(e)},connectivity:t}}var sw=class extends Error{constructor(e=`caller rate limit exceeded`){super(e),this.name=`CallerRateLimited`}},cw=`\0`,lw=e=>new DOMException(e,`AbortError`),uw=e=>{let t=e.filter(e=>e!==void 0);if(t.length===1)return t[0];let n=new AbortController,r=()=>{n.abort();for(let e of t)e.removeEventListener(`abort`,r)};for(let e of t){if(e.aborted)return n.abort(),n.signal;e.addEventListener(`abort`,r,{once:!0})}return n.signal},dw=(e,t)=>new Promise((n,r)=>{if(t.aborted){r(lw(`aborted`));return}let i=()=>{clearTimeout(a),r(lw(`aborted`))},a=setTimeout(()=>{t.removeEventListener(`abort`,i),n()},e);t.addEventListener(`abort`,i,{once:!0})}),fw=(e,t)=>t.reduceRight((e,t)=>t(e),e),pw=(e,t,n)=>e===void 0?[]:typeof e==`function`?e(t,n):e,mw=(e,t)=>n=>async(r,i)=>{t.n+=1,e.onStart?.(r.data);try{let t=await n(r,i);return e.onSuccess?.(t,r.data),t}catch(t){throw e.onError?.(t,r.data),t}finally{--t.n,e.onSettled?.(r.data)}},hw=(e,t,n)=>r=>async(i,a)=>{t!==`success`&&n.invalidateTags(pw(e,i.data,void 0));let o=await r(i,a);return t!==`start`&&n.invalidateTags(pw(e,i.data,o)),o},gw=(e,t,n)=>r=>async(i,a)=>{let o=n(i.data),s=n=>t.write(o,n,{ttl:e.ttl,staleWhileRevalidate:e.staleWhileRevalidate,tags:pw(e.tags,i.data,n)}),c=t.read(o);if(c&&!c.stale)return c.value;if(c&&c.stale)return r(i,a).then(s).catch(()=>{}),c.value;let l=await r(i,a);return s(l),l},_w=e=>{let t=new Map;return n=>(r,i)=>{let a=e(r.data),o=t.get(a);if(o)return o;let s=n(r,i).finally(()=>t.delete(a));return t.set(a,s),s}},vw=()=>{let e=null;return t=>(n,r)=>{e?.abort(lw(`superseded`));let i=new AbortController;e=i;let a=uw([r,i.signal]);return new Promise((e,r)=>{a.addEventListener(`abort`,()=>r(lw(`superseded`)),{once:!0}),t(n,a).then(e,r)}).finally(()=>{e===i&&(e=null)})}},yw=e=>{let t=e.onLimit??`wait`,n=e.window/e.limit,r=e.limit,i=Date.now(),a=()=>{let t=Date.now(),n=(t-i)/e.window*e.limit;n>0&&(r=Math.min(e.limit,r+n),i=t)};return e=>async(i,o)=>{if(a(),r<1){if(t===`throw`||t===`drop`)throw new sw;await dw((1-r)*n,o),a()}return--r,e(i,o)}},bw=e=>{let t=e.attempts??3,n=e.base??200,r=e.factor??2,i=e.max??3e4,a=e.jitter??.5;return e=>async(o,s)=>{let c;for(let l=1;l<=t;l+=1)try{return await e(o,s)}catch(e){if(c=e,l>=t)break;await dw(Math.min(i,n*r**(l-1))*(1-a*Math.random()),s)}throw c}},xw=e=>e instanceof ZC&&e.status===0&&e.code===`DISCONNECTED`,Sw=(e,t)=>{let n=e.maxRetries??1/0,r=e.backoff??1e3;return i=>async(a,o)=>{let s=e.timeout===void 0?1/0:Date.now()+e.timeout,c=0;for(;;)try{return await i(a,o)}catch(e){if(!xw(e)||c>=n)throw e;let i=s-Date.now();if(i<=0)throw e;c+=1,await t.connectivity.whenOnline(o,{timeout:Math.min(r,i)})}}},Cw=(e,t)=>{let n=null,r=[],i=0;return a=>{let o=t=>{n&&=(clearTimeout(n),null);let o=r;r=[],i=0;let s=o.map(e=>e.call.data);a(e.accumulate?{data:e.accumulate(s),opts:o[o.length-1].call.opts}:o[o.length-1].call,t).then(t=>{let n=e.spread?e.spread(t,s):null;o.forEach((e,r)=>e.resolve(n?n[r]:t))},e=>o.forEach(t=>t.reject(e)))};return t.push(()=>{n&&=(clearTimeout(n),null);let e=r;r=[],i=0;for(let t of e)t.reject(lw(`cancelled`))}),(t,a)=>new Promise((s,c)=>{let l=Date.now();r.length===0&&(i=l),r.push({call:t,resolve:s,reject:c});let u=e.leading&&n===null&&r.length===1;n&&clearTimeout(n);let d=e.maxWait!==void 0&&l-i>=e.maxWait;if(u||d){o(a);return}let f=e.maxWait===void 0?e.wait:Math.min(e.wait,i+e.maxWait-l);n=setTimeout(()=>o(a),f)})}};function ww(e,t,n,r,i){if(t.items||t.itemsIn||t.streamIn!==null||t.streamOut!==null)return{call:(...e)=>n(...e),cancel:()=>{},invalidate:()=>{},pending:0};let a=t.p.length>0||t.q.length>0||t.hasBody||t.f.length>0,o=i.cache===!0||i.cache===void 0||i.cache===!1?{}:i.cache,s=e=>o.key?o.key(e):tw(e),c=t=>`${e}${cw}${s(t)}`,l=i.cache?r.cacheFor(o.store):null,u={n:0},d=[],f=new AbortController,p=(e,t)=>{let r={...e.opts??{},signal:t};return Promise.resolve(a?n(e.data,r):n(r))},m=[];if((i.onStart||i.onSuccess||i.onError||i.onSettled)&&m.push(mw(i,u)),i.invalidates&&m.push(hw(i.invalidates,i.invalidateOn??`success`,r)),l&&m.push(gw(o,l,c)),i.dedupe&&m.push(_w(c)),i.lastOnly&&m.push(vw()),i.debounce!==void 0){let e=typeof i.debounce==`number`?{wait:i.debounce}:i.debounce;m.push(Cw(e,d))}i.rateLimit&&m.push(yw(i.rateLimit)),i.retry&&m.push(bw(i.retry));let h=t.sideEffects===!1||t.sideEffects===void 0&&t.method===`GET`,ee=i.replay===!1?null:i.replay===void 0?h?{}:null:typeof i.replay==`object`?i.replay:{};ee&&(h||ee.force)&&m.push(Sw(ee,r)),(i.onOnline||i.onOffline)&&r.connectivity.subscribe(e=>e===`online`?i.onOnline?.():i.onOffline?.());let te=fw(p,m);return{call:(...e)=>{let t=a?e[0]:void 0,n=a?e[1]:e[0],r=uw([n?.signal,f.signal]);return te({data:t,opts:n},r)},cancel:()=>{f.abort(lw(`cancelled`)),f=new AbortController;for(let e of d)e()},invalidate:()=>void l?.removeWhere(t=>t.startsWith(`${e}${cw}`)),get pending(){return u.n}}}function Tw(e){try{let t=JSON.parse(e);return typeof t==`object`&&t&&!Array.isArray(t)?t:null}catch{return null}}function Ew(e){let{id:t,...n}=e;return JSON.stringify({rid:typeof t==`string`?t:null,...n})}function Dw(e){let{rid:t,...n}=e;return JSON.stringify(typeof t==`string`?{id:t,...n}:n)}function Ow(e,t){return JSON.stringify({id:e,$status:0,$code:`DISCONNECTED`,$error:t})}function kw(e){return`$status`in e||e.end===!0}var Aw=class{#e=new Set;add(e){this.#e.add(e)}settle(e){typeof e.id==`string`&&kw(e)&&this.#e.delete(e.id)}fail(e,t){let n=[...this.#e];this.#e.clear();for(let r of n)e(Ow(r,t))}},jw={$status:501,$code:`NOT_SERVED`,$error:`this client serves no spec`};function Mw(e,t){let n=e.rid;typeof n==`string`&&typeof e.type==`string`&&t(JSON.stringify({rid:n,...jw}))}var Nw=class{app;send;request;#e=null;constructor(e,t,n){this.app=e,this.send=t,this.request=n}receive(e){let t=this.#e??this.#t();this.app.ws.message(t,Dw(e))}drop(){let e=this.#e;e&&(this.#e=null,this.app.ws.close(e))}#t(){let e=this.app.ws.open(t=>{let n=Tw(t);n&&this.#e===e&&this.send(Ew(n))},this.request());return this.#e=e,e}},Pw=new Set([101,204,205,304]);function Fw(e,t,n,r,i,a){return new Promise((o,s)=>{if(i?.aborted){s(new DOMException(`The operation was aborted.`,`AbortError`));return}let c=new XMLHttpRequest;c.open(e,t,!0),c.responseType=`arraybuffer`;for(let[e,t]of Object.entries(n))c.setRequestHeader(e,t);c.upload.onprogress=e=>{e.lengthComputable&&a({loaded:e.loaded,total:e.total})};let l=()=>c.abort(),u=()=>i?.removeEventListener(`abort`,l);c.onload=()=>{u();let e=Pw.has(c.status)?null:c.response;o(new Response(e,{status:c.status,statusText:c.statusText}))},c.onerror=()=>{u(),s(TypeError(`Network request failed`))},c.onabort=()=>{u(),s(new DOMException(`The operation was aborted.`,`AbortError`))},i?.addEventListener(`abort`,l,{once:!0}),c.send(r)})}function Iw(e){return!!e&&typeof e.parse==`function`}function Lw(e){let t=Rw(e);return t?t():e}function Rw(e){let t=e[Symbol.for(`ayepi.manifest`)];return typeof t==`function`?t:void 0}function zw(e){return typeof e==`number`&&e>=200&&e<300}var Bw={400:`Bad Request`,401:`Unauthorized`,403:`Forbidden`,404:`Not Found`,405:`Method Not Allowed`,409:`Conflict`,410:`Gone`,422:`Unprocessable Entity`,429:`Too Many Requests`,500:`Internal Server Error`,502:`Bad Gateway`,503:`Service Unavailable`};function Vw(e){let t=Number(e.$status);return new ZC(t,typeof e.$code==`string`?e.$code:`ERROR`,typeof e.$error==`string`?e.$error:Bw[t]??`Request failed with status ${t}`,e.data)}function Hw(e){let t=Lw(e.manifest),n=e.fetchImpl??(e=>fetch(e)),r=$C(),i=ow(e.cache,r);e.ws?.onState?.(e=>r.report(e===`open`?`online`:`offline`));let a=()=>typeof e.headers==`function`?e.headers():e.headers??{},o=t=>e.unauthorized!==void 0&&Object.keys(t).some(e=>e.toLowerCase()===`authorization`),s=null,c=()=>{let t=e.unauthorized;return t?(s??=t().catch(()=>!1).finally(()=>{s=null}),s):Promise.resolve(!1)},l=t=>e.validate?.endpoints[t]?.cfg,u=(e,t)=>{let n=l(e);return n?.response?n.response.parse(t):t},d=(e,t)=>{let n=l(e);return n&&Iw(n.streamOut)?n.streamOut.parse(t):t},f=(e,t,n)=>{let r=l(e)?.responses?.[t];return r?r.parse(n):n},p=0,m=new Map,h=new Map,ee=new Map,te=new Map,ne=new Map,re=(t,n,r)=>{r&&o(a())&&ne.set(t,n),e.ws?.send(n)},ie=e=>{let t=te.get(e);t&&(te.delete(e),t())},ae=(t,n,r)=>{if(!n)return;let i=()=>{te.delete(t),ne.delete(t),r(n.reason)&&e.ws?.send(JSON.stringify({id:t,abort:!0}))};n.aborted?i():(n.addEventListener(`abort`,i,{once:!0}),te.set(t,()=>n.removeEventListener(`abort`,i)))},oe=e=>JSON.stringify(e??{},Object.keys(e??{}).sort());if(e.ws){let t=e.ws,n=e=>t.send(e),r=e.serve?new Nw(e.serve,n,()=>new Request(new URL(e.baseUrl,`http://peer.invalid/`))):null;r&&t.onState?.(e=>{e!==`open`&&r.drop()}),t.onMessage(e=>{let i=Tw(e);if(!i)return;if(`rid`in i){r?r.receive(i):Mw(i,n);return}if(typeof i.id!=`string`){if(typeof i.type==`string`){let e=`${i.type}|${oe(i.params)}`;for(let t of ee.get(e)??[])t(i.data)}return}let a=i.id,o=ne.get(a);ne.delete(a),o!==void 0&&i.$status===401?c().then(e=>{(m.has(a)||h.has(a))&&(e?t.send(o):se(a,i))}):se(a,i)})}function se(e,t){let n=`$status`in t&&!zw(t.$status);if(h.has(e)){let r=h.get(e);`chunk`in t?r.push(t.chunk):t.end===!0?(h.delete(e),ie(e),r.end()):n&&(h.delete(e),ie(e),r.fail(Vw(t)))}else if(m.has(e)){let r=m.get(e);m.delete(e),ie(e),n?r.reject(Vw(t)):r.resolve(t.data)}}function ce(){let e=[],t=!1,n,r=null;return{push(t){e.push(t),r?.()},end(){t=!0,r?.()},fail(e){n=e,t=!0,r?.()},async*iterate(){for(;;)if(e.length>0)yield e.shift();else{if(n!==void 0)throw n;if(t)return;await new Promise(e=>r=e),r=null}}}}function le(t,n){let r=typeof n==`function`?n():n;(async()=>{try{for await(let n of r)e.ws.send(JSON.stringify({id:t,chunk:n}));e.ws.send(JSON.stringify({id:t,end:!0}))}catch{e.ws.send(JSON.stringify({id:t,end:!0}))}})()}function ue(e,t,n){return JSON.stringify(t.ws===null?{id:e,type:t.path,method:t.method,data:n}:{id:e,type:t.ws,data:n})}function de(t,n,r,i,a){if(!e.ws){let e=Error(`no websocket transport configured`);if(!n.items)return Promise.reject(e);throw e}let o=`c${++p}`;if(n.items){let e=ce();return h.set(o,e),ae(o,a,t=>h.delete(o)?(e.fail(t),!0):!1),re(o,ue(o,n,r),!n.itemsIn),n.itemsIn&&le(o,i),(async function*(){for await(let n of e.iterate())yield d(t,n)})()}let s=new Promise((e,t)=>{m.set(o,{resolve:e,reject:t}),ae(o,a,e=>{let t=m.get(o);return t?(m.delete(o),t.reject(e),!0):!1}),re(o,ue(o,n,r),!1)});return n.itemsIn&&le(o,i),s.then(e=>n.multi?e:u(t,e))}function fe(t,n){if(!e.ws)return Promise.reject(Error(`no websocket transport configured`));let r=`c${++p}`;return new Promise((e,i)=>{m.set(r,{resolve:e,reject:i}),ae(r,n,e=>{let t=m.get(r);return t?(m.delete(r),t.reject(e),!0):!1}),re(r,JSON.stringify({id:r,...t}),!0)})}function g(e,t){if(e.b===`raw`)return{p:{},q:{},b:t,f:{}};let n={},r={},i={},a={},o=new Set(e.p),s=new Set(e.q),c=new Set(e.b??[]),l=new Set(e.f);for(let[e,u]of Object.entries(t??{}))if(o.has(e))n[e]=u;else if(s.has(e))r[e]=u;else if(c.has(e))i[e]=u;else if(l.has(e))a[e]=u;else throw Error(`key "${e}" does not belong to endpoint data`);return{p:n,q:r,b:e.hasBody?i:void 0,f:a}}function pe(t,n,r){let i=YC(qC(t.path),n),a=new URL(i.slice(1),e.baseUrl.endsWith(`/`)?e.baseUrl:e.baseUrl+`/`);for(let[e,t]of Object.entries(r))if(t!==void 0){if(Array.isArray(t))for(let n of t)a.searchParams.append(e,String(n));else a.searchParams.set(e,String(t))}return a}function me(e){let t=(typeof e==`function`?e():e)[Symbol.asyncIterator](),n=new TextEncoder;return new ReadableStream({async pull(e){let{done:r,value:i}=await t.next();if(r)return e.close();e.enqueue(n.encode(JSON.stringify(i)+`
|
|
395
|
+
`))},async cancel(){await t.return?.(void 0)}})}async function he(e,t,i,s=!1){let{p:l,q:u,b:d,f}=g(e,t),p=i?.stream,m=pe(e,l,u),h={...a(),...i?.headers??{}},ee=null,te=!1;if(e.streamIn)h[`content-type`]=e.streamIn,e.itemsIn?(ee=me(p),te=!0):(ee=p,te=p instanceof ReadableStream);else if(e.f.length>0){let e=new FormData;d!==void 0&&e.set(`body`,JSON.stringify(d));for(let[t,n]of Object.entries(f))if(n!==void 0){if(Array.isArray(n))for(let r of n)e.append(t,r);else e.set(t,n)}ee=e}else if(e.hasBody){if(e.bodyEnc===`urlencoded`){h[`content-type`]=`application/x-www-form-urlencoded`;let e=new URLSearchParams;for(let[t,n]of Object.entries(d??{}))if(n!==void 0){if(Array.isArray(n))for(let r of n)e.append(t,String(r));else e.set(t,String(n))}ee=e.toString()}else h[`content-type`]=`application/json`,ee=JSON.stringify(d)}let ne={method:e.method,headers:h,body:ee,signal:i?.signal};te&&(ne.duplex=`half`);let re=i?.onUploadProgress,ie;try{ie=re&&!e.streamIn&&!e.streamOut&&typeof XMLHttpRequest<`u`?await Fw(e.method,m.toString(),h,ee,i?.signal,re):await n(new Request(m,ne))}catch(e){throw e instanceof TypeError?(r.report(`offline`),new ZC(0,`DISCONNECTED`,`network request failed`)):e}if(r.report(`online`),ie.status===401&&!s&&e.streamIn===null&&o(h)&&await c())return await ie.body?.cancel().catch(()=>{}),he(e,t,i,!0);if(!ie.ok){let e=await ie.json().catch(()=>({})),t=e?.error;throw new ZC(ie.status,t?.code??`ERROR`,t?.message,e)}return ie}async function ge(e,t,n,r){let i=await he(t,n,r);if(t.streamOut)return i.body??new ReadableStream({start:e=>e.close()});if(t.multi)return{status:i.status,data:f(e,i.status,await i.json())};if(i.status!==204)return u(e,await i.json())}async function*_e(e,t,n,r){let i=await he(t,n,r);if(!i.body)return;let a=t.streamOut===`text/event-stream`,o=a?`
|
|
396
396
|
|
|
397
397
|
`:`
|
|
398
398
|
`,s=t=>{let n=a?t.split(`
|
|
399
399
|
`).filter(e=>e.startsWith(`data:`)).map(e=>e.slice(5).trimStart()).join(`
|
|
400
|
-
`):t;if(n.trim())return d(e,JSON.parse(n))},c=i.body.getReader(),l=new TextDecoder,u=``;try{for(;;){let{done:e,value:t}=await c.read();if(e)break;u+=l.decode(t,{stream:!0});let n;for(;(n=u.indexOf(o))>=0;){let e=u.slice(0,n);u=u.slice(n+o.length);let t=s(e);t!==void 0&&(yield t)}}u+=l.decode();let e=s(u);e!==void 0&&(yield e)}finally{await c.cancel().catch(()=>{})}}function ve(n,...r){let i=t.endpoints[n];if(!i)return Promise.reject(Error(`unknown endpoint "${n}"`));let a=i.p.length>0||i.q.length>0||i.hasBody||i.f.length>0||i.streamIn!==null,o=a?r[0]:void 0,s=a?r[1]:r[0],c=s?.transport??(e.prefer===`ws`&&!i.httpOnly&&e.ws?`ws`:`http`);if(c===`ws`&&i.httpOnly){let e=Error(`endpoint "${n}" is http-only`);if(i.items)throw e;return Promise.reject(e)}return i.items||i.itemsIn?c===`ws`?de(n,i,o,s?.stream,s?.signal):i.items?_e(n,i,o,s):ge(n,i,o,s):c===`ws`?fe(i.ws===null?{type:i.path,method:i.method,data:o}:{type:i.ws,data:o},s?.signal).then(e=>i.multi?e:u(n,e)):ge(n,i,o,s)}function ye(e,...n){let r=t.endpoints[e];if(!r)throw Error(`unknown endpoint "${e}"`);if(r.method!==`GET`)throw Error(`url() requires a GET endpoint; "${e}" is ${r.method}`);let{p:i,q:a}=g(r,n[0]);return pe(r,i,a).toString()}function be(n,...r){let i=t.events[n];if(!i)throw Error(`unknown event "${n}"`);if(!e.ws)throw Error(`no websocket transport configured`);let a=i.hasParams?r[0]:void 0,o=i.hasParams?r[1]:r[0],s=`${i.ws}|${oe(a)}`,c=ee.get(s);return c||ee.set(s,c=new Set),c.add(o),fe({sub:i.ws,params:a}),()=>{c.delete(o),c.size===0&&fe({unsub:i.ws,params:a})}}function xe(e,n){let r=t.endpoints[e];if(!r)throw Error(`unknown endpoint "${e}"`);return nw(e,r,(...t)=>ve(e,...t),i,n??{})}return{call:ve,on:be,url:ye,caller:xe,connection:{get status(){return r.status},subscribe:e=>r.subscribe(e)}}}var xw={initial:500,max:3e4,factor:2,jitter:!0},Sw={interval:3e4,timeout:1e4};function Cw(e,t={}){let n=t.WebSocket??globalThis.WebSocket;if(!n)throw Error(`wsTransport: no WebSocket implementation available; pass opts.WebSocket`);let r=n,i=t.whileDisconnected??`fail`,a={...xw,...t.backoff},o=t.heartbeat===!1?null:{...Sw,...t.heartbeat??{}},s=t.maxRetries??1/0,c=null,l=`closed`,u=null,d=0,f=!1,p=!1,m=null,h=null,ee=null,te=[],ne=new Map,re=new cw,ie=new Set,ae=e=>{if(e!==l){l=e,t.onStateChange?.(e);for(let t of[...ie])t(e)}},oe=e=>u?.(e),se=e=>JSON.stringify(e??{},Object.keys(e??{}).sort());function ce(){re.fail(oe,`connection closed`)}function le(){h&&clearInterval(h),ee&&clearTimeout(ee),h=ee=null}function ue(){o&&(le(),h=setInterval(()=>{l===`open`&&c&&(c.send(JSON.stringify({ping:!0})),ee&&clearTimeout(ee),ee=setTimeout(()=>c?.close(),o.timeout))},o.interval))}function de(e){let t=null;try{t=JSON.parse(e)}catch{oe(e);return}t&&t.pong===!0?ee&&=(clearTimeout(ee),null):(t&&re.settle(t),oe(e))}function fe(){if(p)return;f=!0,d=0,ae(`open`);for(let e of ne.values())c?.send(e);let e=te.splice(0);for(let t of e)c?.send(t);ue()}function g(){le(),c=null,ce(),p?ae(`closed`):pe()}function pe(){if(p)return;if(d>=s){ae(`closed`);return}let e=Math.min(a.max,a.initial*a.factor**+d),t=a.jitter?e/2+e/2*Math.random():e;d++,ae(`connecting`),m=setTimeout(me,t)}function me(){if(p||c)return;m&&=(clearTimeout(m),null),ae(`connecting`);let n;try{n=new r(typeof e==`function`?e():e,typeof t.protocols==`function`?t.protocols():t.protocols)}catch(e){t.onError?.(e),pe();return}c=n;let i=!1,a=()=>{c===n&&g()};n.addEventListener(`open`,()=>{i=!0,fe()}),n.addEventListener(`message`,e=>de(String(e.data))),n.addEventListener(`close`,a),n.addEventListener(`error`,e=>{t.onError?.(e),i||a()})}function he(e){let t={};try{t=JSON.parse(e)}catch{}typeof t.sub==`string`?ne.set(`${t.sub}|${se(t.params)}`,e):typeof t.unsub==`string`&&ne.delete(`${t.unsub}|${se(t.params)}`),typeof t.id==`string`&&typeof t.type==`string`&&re.add(t.id);let n=typeof t.sub==`string`||typeof t.unsub==`string`;l===`open`&&c?c.send(e):`rid`in t||(me(),n||(!f||i===`queue`?te.push(e):typeof t.id==`string`&&oe(ow(t.id,`not connected`))))}return{send:he,onMessage(e){u=e},connect:me,reconnect(){if(p)return;let e=c;c=null,le(),ce(),e?.close(),d=0,me()},close(){p=!0,m&&clearTimeout(m),m=null,le(),ce(),c?.close(),c=null,ae(`closed`)},get state(){return l},onState(e){return ie.add(e),()=>void ie.delete(e)}}}function ww(e,t,n){return{kind:`endpoint`,cfg:e,mws:t,prefixes:n}}function Tw(e){return ww(e,[],[])}function Y(e){for(let[t,n]of Object.entries(e.endpoints)){let e=n.cfg;if(e.streamIn&&(e.body||e.files))throw Error(`endpoint "${t}": streamIn excludes body/files`);if(e.files&&`body`in e.files)throw Error(`endpoint "${t}": "body" is reserved as the multipart JSON field name`);if(e.streamOut&&e.response)throw Error(`endpoint "${t}": streamOut excludes response`);if(e.responses&&e.response)throw Error(`endpoint "${t}": responses (multi-status) excludes response`);if(e.responses&&e.streamOut)throw Error(`endpoint "${t}": responses excludes streamOut`);if(e.streamEncoding&&!(e.streamOut instanceof ws))throw Error(`endpoint "${t}": streamEncoding requires a typed (schema) streamOut`);if(e.bodyEncoding===`urlencoded`&&!(e.body instanceof dc))throw Error(`endpoint "${t}": urlencoded bodies must be z.object(...)`);if(e.download&&typeof e.streamOut!=`string`)throw Error(`endpoint "${t}": download requires a raw (content-type) streamOut`);for(let n of[`params`,`query`,`headers`,`cookies`]){let r=e[n];if(r&&!(r instanceof dc))throw Error(`endpoint "${t}": ${n} must be a z.object(...)`)}kw(t,n)}let t;return Object.defineProperty(e,Ew,{value:()=>t??=Dw(e),enumerable:!1,configurable:!0}),e}var Ew=Symbol.for(`ayepi.manifest`);function Dw(e){let t=Object.entries(e.endpoints).map(([e,t])=>kw(e,t));return{endpoints:Object.fromEntries(t.map(e=>[e.name,{method:e.method,path:e.path,ws:e.ws,httpOnly:e.httpOnly,streamIn:e.streamInCt,itemsIn:e.itemsIn,streamOut:e.streamOutCt,items:e.items,p:e.p,q:e.q,b:e.bRaw?`raw`:e.b,f:e.f,hasBody:!!e.def.cfg.body,hasHeaders:!!e.def.cfg.headers,multi:e.multi,bodyEnc:e.bodyEnc,sideEffects:e.def.cfg.sideEffects}])),events:Object.fromEntries(Object.entries(e.events??{}).map(([e,t])=>[e,{ws:t.ws??e,hasParams:!!t.params}]))}}function Ow(e){return e&&e instanceof dc?Object.keys(e.shape):null}function kw(e,t){let n=t.cfg,r=Lw(t.mws),i=t=>{throw Error(`endpoint "${e}": ${t}`)},a=new Map;for(let e of r)e.paramKey&&e.paramSchema&&a.set(e.paramKey,e.paramSchema);let o=new Map,s=(e,t)=>{for(let n of e.keys)(a.has(n)||o.has(n))&&i(`param ":${n}" is declared more than once (${t})`),o.set(n,e.schemas[n])};for(let e of t.prefixes)typeof e!=`string`&&s(e,`prefix path`);let c=typeof n.path==`object`&&n.path!==null?n.path:null;c&&s(c,`endpoint path`);let l=Ow(n.params)??[];for(let e of l)(a.has(e)||o.has(e))&&i(`param ":${e}" is declared more than once (params schema)`);let u=new Set([...a.keys(),...o.keys(),...l]),d=[];for(let e of t.prefixes)d.push(...typeof e==`string`?TC(e):e.parts);if(c)d.push(...c.parts);else if(typeof n.path==`string`)d.push(...TC(n.path));else{d.push({t:`lit`,v:e});let t=new Set(OC(d));for(let e of u)t.has(e)||d.push({t:`param`,k:e})}let f=OC(d),p=new Set(f);f.length!==p.size&&i(`path positions a param more than once: ${EC(d)}`);for(let e of f)u.has(e)||i(`path references undeclared param ":${e}"`);for(let e of u)p.has(e)||i(`declared param ":${e}" has no position in path ${EC(d)}`);let m=[...u],h=Ow(n.query)??[],ee=n.body?Ow(n.body):null,te=!!n.body&&ee===null,ne=Object.keys(n.files??{}),re=new Map;for(let[e,t]of[[`path`,m],[`query`,h],[`body`,ee??[]],[`files`,ne]])for(let n of t){let t=re.get(n);t&&i(`key "${n}" appears in both ${t} and ${e} — kinds must be disjoint`),re.set(n,e)}te&&(m.length>0||h.length>0||ne.length>0)&&i(`a non-object body is the entire data payload — params/query/files are not allowed alongside it`);let ie=n.streamIn instanceof ws,ae=typeof n.streamIn==`string`?n.streamIn:ie?`application/x-ndjson`:null,oe=n.streamOut instanceof ws,se=oe&&n.streamEncoding===`sse`,ce=typeof n.streamOut==`string`?n.streamOut:oe?se?`text/event-stream`:`application/x-ndjson`:null,le=!!(n.httpOnly||typeof n.streamIn==`string`||typeof n.streamOut==`string`||ne.length>0);return{name:e,def:t,method:n.method??`POST`,parts:d,path:EC(d),ws:n.ws??null,wsEligible:!le,httpOnly:le,streamInCt:ae,itemsIn:ie,streamOutCt:ce,items:oe,sse:se,multi:!!(n.responses&&Object.keys(n.responses).length>0),bodyEnc:n.body?n.bodyEncoding??`json`:null,p:m,q:h,b:ee,bRaw:te,f:ne,loaders:a,tplSchemas:o,chain:r}}function Aw(){return{}}function jw(e){return()=>{throw Error(`middleware "${e}" has no implementation — bind it with implement(api).middleware(def, impl)`)}}function Mw(e,t,n,r,i,a){let o={kind:`middleware`,name:e,requires:t,optional:n,paramKey:r,paramSchema:i,doc:a,run:jw(e),with(...e){return Nw([o,...e],[])},path(e){return Nw([o],[e])},endpoint(e){return Nw([o],[]).endpoint(e)},group(e){return Nw([o],[]).group(e)}};return o}function Nw(e,t){return{kind:`stack`,mws:e,prefixes:t,with(...n){return Nw([...e,...n],t)},path(n){return Nw(e,[...t,n])},endpoint(n){return ww(n,e,t)},group(n){let r={};for(let[i,a]of Object.entries(n))r[i]=ww(a,e,t);return r}}}function X(...e){return Nw([...e],[])}function Pw(e,t){return Mw(e,t?.requires??[],t?.optional??[],void 0,void 0,t?.doc)}function Fw(e,t,n){return Mw(e,n?.requires??[],n?.optional??[],e,t,n?.doc)}var Iw=Object.assign(Pw,{loader:Fw});function Lw(e){let t=new Set,n=[],r=(e,i)=>{if(!t.has(e)){if(i.has(e))throw Error(`middleware cycle involving "${e.name}"`);i.add(e);for(let t of e.requires)r(t,i);i.delete(e),t.add(e),n.push(e)}};for(let t of e)r(t,new Set);let i=new Map(n.map((e,t)=>[e,t]));return[...n].sort((e,t)=>e.optional.includes(t)?1:t.optional.includes(e)?-1:i.get(e)-i.get(t))}function Rw(...e){let t={},n={};for(let r of e){for(let[e,n]of Object.entries(r.endpoints)){if(Object.hasOwn(t,e))throw Error(`mergeSpecs: endpoint "${e}" is in more than one spec`);t[e]=n}for(let[e,t]of Object.entries(r.events??{})){if(Object.hasOwn(n,e))throw Error(`mergeSpecs: event "${e}" is in more than one spec`);n[e]=t}}return Y({endpoints:t,events:n})}var zw=new WeakMap;function Bw(e,t){return zw.set(e._zod.def,{source:t}),e}function Vw(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Map)}var Hw=class e extends U{static NAME=`record`;name=e.NAME;static optionKeys=[];static genericKeys=[`V`];static from(t,n){let r=t.generic?.V;return new e(n,r===void 0?n.registry.any():n.parse(r))}static toA(){return R.object({name:R.literal(e.NAME),generic:R.object({V:R.ref(`TypeDef`)}).optional()}).describe(`A record: an object with any text keys, each value a V.`)}constructor(e,t){super(e,{},{V:t})}get value(){let e=this.generic.V;if(e===void 0)throw Error(`record has no value type`);return e}valid(e,t){return Vw(e)&&Object.values(e).every(e=>{try{return this.value.parse(e,t),!0}catch{return!1}})}parse(e,t){if(!Vw(e))throw new Fm({path:[],code:`record.invalid`,message:`record.parse: expected an object of values by key`,severity:`error`});for(let[n,r]of Object.entries(e))try{this.value.parse(r,t)}catch(e){throw new Fm({path:[n],code:`record.value`,message:`record.parse: ${n}: ${e instanceof Error?e.message:String(e)}`,severity:`error`})}return new W(this,e)}encode(e){return e}create(){return{}}random(e){return{}}compatibleType(t){return t instanceof e&&this.value.compatibleType(t.value)}or(t){return t instanceof e&&this.value.compatibleType(t.value)?this:t}narrow(){return{}}toJSON(){return{name:e.NAME,generic:{V:this.value.toJSON()}}}clone(){return new e(this.scope,this.value)}toCode(e,t){return`${this.docsPrefix(t)}record<${this.value.toCode(void 0,t)}>`}valueA(e){return R.record(this.value.toA(e))}toNewA(){return R.record(R.ref(`Expr`))}};function Uw(e){return e.typeClass(Hw.NAME)===void 0&&e.define(Hw),e}function Ww(){return Uw(Iv())}var Gw;function Kw(){return Gw??=Ww(),Gw}var qw=Uy.result(`TypeDef`),Jw=Uy.result(`Expr`);function Yw(e){return()=>{let{description:t,...n}=e(Kw()).render(Ql).jsonSchema;return n}}function Xw(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Zw(e){return Xw(e)&&`name`in e&&typeof e.name==`string`}var Z=Bw(Jc(Zw,{message:`Expected a gin type definition ({ name, ... }).`}),Yw(e=>qw.bind(e,void 0,{namedRefs:!0})));function Qw(e){return Zw(e)}var $w=Bw(Jc(Qw,{message:`Expected a gin object type definition ({ name: "obj", props: { ... } }).`}),Yw(e=>Ky(e.typ(e.obj({}))).bind(e,void 0,{namedRefs:!0})));function eT(e){return Xw(e)&&`kind`in e&&typeof e.kind==`string`}var tT=Bw(Jc(eT,{message:`Expected a gin expression ({ kind, ... }).`}),Yw(e=>Jw.bind(e,void 0,{namedRefs:!0}))),nT=new Set(`id.uuid.guid.url.uri.api.json.csv.tsv.xml.html.css.yaml.sql.pdf.svg.png.jpg.ip.dns.http.https.ssh.tls.ssl.tcp.udp.vpn.os.cpu.gpu.ram.ui.ux.ai.llm.sku.sms.otp.jwt.utc.iso.gmt.ssn.vat.faq.crm.rgb.db.mime.ttl.oauth.sso.mfa`.split(`.`)),rT=new Map([[`ctx`,`context`]]);function iT(e,t){let n=e.toLowerCase();if(nT.has(n))return n.toUpperCase();let r=rT.get(n);return r===void 0?n.endsWith(`s`)&&nT.has(n.slice(0,-1))?`${n.slice(0,-1).toUpperCase()}s`:t?e:n:t?lT(r):r}function aT(e){return lT((/[\s._/:-]/.test(e)&&!/[a-z]/.test(e)?e.toLowerCase():e).replace(/([A-Z]+)([A-Z][a-z])/g,`$1 $2`).replace(/([a-z0-9])([A-Z])/g,`$1 $2`).split(/[\s._/:-]+/).filter(e=>e!==``).map((e,t)=>iT(e,t===0)).join(` `))||e}function oT(e){return e.label??aT(e.name)}function sT(e){return aT(Fl(e).local)}function cT(e){return/^[A-Z][a-z]/.test(e)?`${e.charAt(0).toLowerCase()}${e.slice(1)}`:e}function lT(e){return e===``?e:`${e.charAt(0).toUpperCase()}${e.slice(1)}`}function uT(e,t){let n=e.replace(/\s+/g,` `).trim();if(n.length<=t)return n;let r=n.slice(0,t-1),i=r.lastIndexOf(` `);return`${i>t*.6?r.slice(0,i):r}…`}var dT=[`path`,`file`,`uri`,`query`,`command`,`url`,`name`,`title`,`text`,`pattern`,`message`];function fT(e,t=60){if(e==null)return``;if(typeof e==`string`)return uT(e,t);if(typeof e==`number`||typeof e==`boolean`)return String(e);if(Array.isArray(e))return e.length===0?``:`${e.length} item${e.length===1?``:`s`}`;let n=dT.map(t=>e[t]).find(e=>typeof e==`string`&&e!==``);if(typeof n==`string`)return uT(n,t);for(let[n,r]of Object.entries(e))if(typeof r==`string`||typeof r==`number`||typeof r==`boolean`)return uT(`${n}: ${String(r)}`,t);return``}var pT=[`active`,`retry`,`done`,`failed`],mT=E(pT),hT=S({one:v().min(1),many:v().min(1)}),gT=S({active:hT,retry:hT,done:hT,failed:hT}),_T=S({phase:mT,one:v(),many:v()}),vT={active:{one:`{fn}…`,many:`{fn} ×{n}…`},retry:{one:`Retrying {fn}…`,many:`Retrying {fn} ×{n}…`},done:{one:`{fn} done`,many:`{fn} ×{n} done`},failed:{one:`{fn} failed`,many:`{fn} ×{n} failed`}};function yT(e,t){switch(e){case`queued`:case`running`:case`waiting`:return t>1?`retry`:`active`;case`invalid-input`:return`retry`;case`done`:return`done`;case`failed`:return`failed`;case`awaiting-approval`:case`paused`:case`cancelled`:case`undone`:return}}var bT=60,xT=3,ST=/\{([^{}|]+)(?:\|([^{}]*))?\}/g;function CT(e,t,n){for(let r of e){if(r===void 0)continue;let e=TT(r[t].one,n,!1),i=TT(r[t].many,n,!0);if(e!==void 0&&i!==void 0)return{phase:t,one:e,many:i}}let r=vT[t];return{phase:t,one:TT(r.one,n,!1)??r.one,many:TT(r.many,n,!0)??r.many}}function wT(e,t){return t===1?e.one:e.many.replaceAll(`{n}`,String(t))}function TT(e,t,n){let r=[],i=e.replace(ST,(e,i,a)=>{let o=ET(i.trim(),t,n);return o===void 0?a===void 0?(r.push(i),e):a:o});return r.length>0?void 0:lT(i.replace(/…{2,}/g,`…`))}function ET(e,t,n){if(e===`fn`)return cT(sT(t.fn));if(e===`n`)return n?`{n}`:void 0;let[r,...i]=e.split(`.`),a=r===`args`?t.args:r===`output`?t.output:void 0;return a===void 0?void 0:OT(DT(a,i))}function DT(e,t){let n=e;for(let e of t){if(typeof n!=`object`||!n)return;n=Array.isArray(n)?n[Number(e)]:n[e]}return n}function OT(e){if(e!=null){if(typeof e==`string`)return e===``?void 0:AT(e);if(typeof e==`number`||typeof e==`boolean`)return String(e);if(Array.isArray(e)){let t=e.map(OT).filter(e=>e!==void 0);if(t.length===0)return;let n=t.slice(0,xT),r=t.length-n.length;return kT(r>0?[...n,`${r} more`]:n)}for(let t of[`title`,`name`,`id`]){let n=e[t];if(typeof n==`string`&&n!==``)return AT(n)}}}function kT(e){return e.length<=2?e.join(` and `):`${e.slice(0,-1).join(`, `)} and ${e.at(-1)??``}`}function AT(e){let t=e.split(`
|
|
401
|
-
`)[0]??``;return t.length>bT?`${t.slice(0,59)}…`:t}var jT=E([`system-needs-config`,`system-disconnected`,`system-removed`,`kind-missing`,`kind-system-disconnected`,`dep-unavailable`,`disabled`,`held`,`paused`,`role-unset`]),MT=C([D(!0),S({unavailable:jT,detail:v()})]),NT=S({code:E([...jT.options,`no-such-fn`,`not-a-name`,`other-system`,`not-for-model`,`connect-account`]),reason:v().min(1),system:F.optional()}),PT=NT.extend({fn:v()}),FT=NT.extend({name:v()}),IT=S({id:M,name:v(),email:v(),role:E([`admin`,`member`]),groups:x(S({id:M,name:v()})),timeZone:v(),locale:v()}),LT=S({now:N,timeZone:v(),local:v()}),RT=S({name:v(),instance:L,boot:v(),from:S({system:v(),fn:I,run:A}).optional()}),zT=S({id:A,fn:I,parent:A.optional(),turn:sl,session:j.optional(),user:IT,time:LT,system:RT,caller:M,attempt:y().int().min(1),priority:Ll,watched:b().optional(),inChat:b().optional()}),BT=S({timeZone:v(),locale:v(),now:N}),VT=E([`card`,`message`,`hidden`]),HT=S({cancel:b(),pause:b(),undo:b(),background:b()}),UT=HT.pick({cancel:!0,pause:!0,background:!0}),WT=S({timeout:jl.optional(),retries:y().int().min(0).optional(),cost:P.optional()}),GT=w(`type`,[S({type:D(`none`)}),S({type:D(`linear`)}),S({type:D(`steps`),steps:T(v(),v())})]),KT=E([`pending`,`active`,`done`,`failed`,`skipped`]),qT=C([S({fraction:y().min(0).max(1),message:v().optional()}),S({steps:T(v(),S({status:KT,detail:v().optional()}))})]),JT=C([S({fraction:y().min(0).max(1),message:v().optional()}),S({step:v(),status:KT,detail:v().optional()})]),YT=[`retry`,`caller`,`fatal`],XT=S({class:E(YT),message:v(),code:v().optional(),data:O.optional()}),ZT=E([`json`,`schema`,`validation`,`unavailable`,`result`]),QT=S({path:v(),message:v()}),$T=S({path:v(),repair:E([`json-string`])});function eE(e){return e.path===``?e.message:`${e.path}: ${e.message}`}var tE=S({source:ZT,problems:x(QT).min(1),raw:v().optional(),blocked:NT.optional()}),nE=[`awaiting-approval`,`queued`,`running`,`waiting`,`paused`,`done`,`invalid-input`,`failed`,`cancelled`,`undone`],rE=E(nE),iE={"awaiting-approval":!1,queued:!1,running:!1,waiting:!1,paused:!1,done:!0,"invalid-input":!0,failed:!0,cancelled:!0,undone:!0},aE={"awaiting-approval":`Needs approval`,queued:`Queued`,running:`Running`,waiting:`Waiting`,paused:`Paused`,done:`Done`,"invalid-input":`Thinking harder`,failed:`Failed`,cancelled:`Cancelled`,undone:`Undone`};function oE(e){return iE[e]}function sE(e){return!iE[e]}var cE=nE.filter(oE),lE=nE.filter(sE),uE=w(`type`,[S({type:D(`status`),status:rE,text:_T.optional()}),S({type:D(`progress`),progress:qT}),S({type:D(`allowed`),operations:UT}),S({type:D(`cost`),cost:P,total:P}),S({type:D(`background`)}),S({type:D(`result`),revision:y().int().min(1)})]),dE=w(`status`,[S({status:D(`done`),result:O,undo:O.optional(),cost:P.optional(),expose:x(Fb).optional()}),S({status:D(`invalid-input`),invalid:tE,undo:O.optional(),cost:P.optional()}),S({status:D(`paused`),resume:O,cost:P.optional()}),S({status:D(`failed`),error:XT,undo:O.optional(),cost:P.optional()}),S({status:D(`cancelled`),partial:O.optional(),undo:O.optional(),cost:P.optional(),error:XT.optional()})]),fE=w(`status`,[S({status:D(`done`),result:O}),S({status:D(`failed`),error:XT}),S({status:D(`cancelled`),error:XT.optional()}),S({status:D(`background`),run:A})]),pE=w(`status`,[S({status:D(`undone`),summary:v()}),S({status:D(`failed`),error:XT}),S({status:D(`gone`)})]),mE=w(`ok`,[S({ok:D(!0),value:O}),S({ok:D(!1),error:XT})]),hE=S({cost:P,time:jl,limitedBy:v()}),gE=gx,_E=S({hash:v().regex(Ox),kind:Lx,converter:v().min(1),content:kx,chars:y().int().min(0),tokens:y().int().min(0),call:Dl.optional(),createdAt:N}),vE=S({kind:Lx,model:v().optional(),estimate:y().min(0).optional()}),yE=w(`from`,[S({from:D(`system`),system:F,served:E([`bytes`,`text`]).optional()}),S({from:D(`upload`),by:M}),S({from:D(`web`),url:mb,finalUrl:mb.optional(),fetchedAt:N,rendered:b()}),S({from:D(`run`),run:A,fn:I})]),bE=[`system`,`upload`,`web`,`run`],xE=E([`auto`,`always`,`never`]),SE=`hub://resources/`,CE=[`document`,`code`,`image`,`table`,`audio`,`video`,`web`,`data`,`archive`,`folder`,`other`],wE=E(CE),TE={markdown:`document`,text:`document`,pdf:`document`,docx:`document`,pptx:`document`,rtf:`document`,odt:`document`,notebook:`document`,html:`web`,json:`data`,jsonl:`data`,yaml:`data`,toml:`data`,xml:`data`,ini:`data`,csv:`table`,tsv:`table`,excel:`table`,ods:`table`,image:`image`,svg:`image`,mermaid:`image`,audio:`audio`,video:`video`,zip:`archive`,folder:`folder`,...Object.fromEntries(`typescript.javascript.jsx.tsx.vue.python.ruby.go.rust.java.c.cpp.csharp.php.swift.kotlin.scala.css.scss.less.shell.sql.dockerfile.graphql.lua.r.dart`.split(`.`).map(e=>[e,`code`]))};function EE(e,t){let n=e===void 0?void 0:TE[e];if(n!==void 0)return n;let r=t?.split(`/`)[0];return r===`image`||r===`audio`||r===`video`?r:`other`}var DE=E([`type`,`source`,`path`,`date`]),OE=S({value:v(),label:v(),count:y().int().min(0)}),kE=Vl.extend({search:v().optional(),system:F.optional(),family:wE.optional(),source:E(bE).optional(),under:v().optional(),form:Lx.optional(),missing:Lx.optional(),group:DE.optional(),in:v().optional()}),AE=S({uri:Tx}),jE=S({uri:Tx,section:Ex.optional()}),ME=S({image:Tx,question:v().trim().min(1).max(2e3),page:y().int().min(1).optional()}),NE=S({answer:v(),model:v(),image:S({id:Tx,name:v()})}),PE=S({uri:Tx,form:C([Lx,D(`raw`)]).optional(),section:Ex.optional(),offset:y().int().min(0).optional(),maxChars:y().int().min(1).max(2e5).optional(),rows:S({table:v(),from:y().int().min(0),to:y().int().min(0)}).optional()}),FE=S({uri:Tx,form:C([Lx,D(`raw`)]),text:v(),offset:y().int().min(0),total:y().int().min(0),truncated:b(),partial:v().optional(),note:v().optional(),forms:x(Lx),offers:x(vE)}),IE=C([S({url:mb,render:xE.optional(),name:v().optional(),folder:v().min(1).optional()}),S({content:kx,name:v().min(1),path:v().optional()})]),LE=C([S({model:v().min(1)}),S({category:v().min(1)}),S({auto:S({cost:y().min(0).optional(),speed:y().min(0).optional(),accuracy:y().min(0).optional()})})]),RE=S({id:v(),name:v(),arguments:v(),invalid:v().optional()}),zE=S({type:E([`text`,`image`,`file`,`audio`,`video`]),content:v(),format:v().optional(),name:v().optional()}),BE=S({role:E([`system`,`user`,`assistant`,`tool`]),content:C([v(),x(zE)]),name:v().optional(),toolCallId:v().optional(),toolCalls:x(RE).optional(),refusal:v().optional(),tokens:y().int().optional()}),VE=S({input:y().int().min(0),output:y().int().min(0),cached:y().int().min(0).optional(),reasoning:y().int().min(0).optional()}),HE=E([`stop`,`length`,`tool_calls`,`content_filter`,`refusal`]),UE=S({content:v().optional(),reasoning:v().optional(),toolCallNamed:RE.optional(),toolCallArguments:RE.optional(),toolCallMore:RE.optional(),toolCall:RE.optional(),finishReason:HE.optional(),refusal:v().optional(),usage:VE.optional()}),WE=C([b(),y().positive()]),GE=E([`summary`,`list`,`markers`,`full`]),KE=C([GE,S({detail:GE.optional(),maxErrors:y().int().min(0).optional(),maxChars:y().int().min(0).optional(),suggestions:b().optional(),expected:b().optional(),context:y().int().min(0).optional(),depth:y().int().min(0).optional(),header:b().optional()})]),qE=S({name:v(),description:v().optional(),parameters:O,strict:WE.optional(),errorFormat:KE.optional()}),JE=C([D(`text`),D(`json`),S({schema:O,strict:WE,errorFormat:KE.optional(),schemaDelivery:E([`auto`,`structured`,`json`,`prompt`]).optional()})]),YE=S({messages:x(BE),temperature:y().optional(),maxTokens:y().int().optional(),stop:x(v()).optional(),tools:x(qE).optional(),toolChoice:C([E([`auto`,`none`,`required`]),S({tool:v()})]).optional(),responseFormat:JE.optional(),errorFormat:KE.optional()}),XE=S({run:A.optional(),request:YE,model:LE.optional(),stream:b()}),ZE=w(`type`,[S({type:D(`chunk`),chunk:UE}),S({type:D(`done`),usage:VE,cost:P,interaction:dl,model:v()}),S({type:D(`error`),message:v(),kind:E([`model`,`tool`,`limit`,`provider`])})]),QE=S({id:v().min(1),text:v().min(1),score:y().min(0).max(1)}),$E=S({run:A,question:v().min(1),candidates:x(QE).min(1).max(50),max:y().int().min(1).max(20)}),eD=w(`by`,[S({by:D(`decision`),picked:x(S({id:v(),why:v().optional()})),note:v().optional(),call:Dl.optional()}),S({by:D(`off`)}),S({by:D(`failed`),message:v()})]),tD=w(`type`,[S({type:D(`predicate`),instructions:v().min(1)}),S({type:D(`choice`),instructions:v().min(1),choices:T(v(),v())}),S({type:D(`score`),instructions:v().min(1),levels:x(v()).min(1)})]),nD=C([v().min(1),x(BE).min(1)]),rD=T(v().min(1),tD),iD=y().min(0).max(1),aD=w(`type`,[S({type:D(`predicate`),probability:iD}),S({type:D(`choice`),choice:v(),probabilities:T(v(),iD),confidence:iD}),S({type:D(`score`),score:y(),probabilities:x(iD),confidence:iD}),S({type:D(`refusal`)})]),oD=T(v(),aD),sD=.5,cD=[`chat`,`embed`,`image`,`transcribe`,`speech`,`decide`];E(cD);var lD=E([`yes`,`no`,`unknown`]),uD=S({modality:D(`chat`),input:y().int().min(0),output:y().int().min(0),cached:y().int().min(0).optional(),reasoning:y().int().min(0).optional(),caching:lD.optional()}),dD=S({modality:D(`embed`),texts:y().int().min(0),characters:y().int().min(0),images:y().int().min(1).optional(),tokens:y().int().min(0).optional(),dimensions:y().int().min(1)}),fD=S({modality:D(`image`),images:y().int().min(0),size:v().optional()}),pD=S({modality:D(`transcribe`),seconds:y().min(0),bytes:y().int().min(0)}),mD=S({modality:D(`speech`),characters:y().int().min(0),seconds:y().min(0).optional()}),hD=S({modality:D(`decide`),questions:y().int().min(0),characters:y().int().min(0),images:y().int().min(0).optional(),tokens:y().int().min(0).optional()});w(`modality`,[uD,dD,fD,pD,mD,hD]);var gD=E([`mp3`,`wav`,`ogg`]),_D=E([`running`,`done`,`failed`,`aborted`]),vD=S({id:Dl,provider:v(),model:v(),run:A.optional(),turn:sl.optional(),session:j.optional(),system:F.optional(),fn:I.optional(),purpose:v().optional(),interaction:dl.optional(),cost:P,status:_D,error:v().optional(),priority:Ll.optional(),sent:y().int().min(0),received:y().int().min(0),queued:jl,firstByte:jl.optional(),total:jl.optional(),startedAt:N,endedAt:N.optional()}),yD=e=>S({modality:e.shape.modality,units:e}),bD=w(`modality`,[yD(uD),yD(dD),yD(fD),yD(pD),yD(mD),yD(hD)]),xD=e=>vD.extend(e.shape),SD=w(`modality`,[xD(bD.options[0]),xD(bD.options[1]),xD(bD.options[2]),xD(bD.options[3]),xD(bD.options[4]),xD(bD.options[5])]),CD=w(`modality`,[S({modality:D(`embed`),texts:x(v()).min(1),model:LE.optional()}),S({modality:D(`image`),prompt:v().min(1),model:LE.optional(),size:v().optional(),count:y().int().min(1).max(10).optional()}),S({modality:D(`transcribe`),audio:kx,model:LE.optional(),language:v().optional()}),S({modality:D(`speech`),text:v().min(1),model:LE.optional(),voice:v().optional(),format:gD.optional()}),S({modality:D(`decide`),input:nD,questions:rD,model:LE.optional()})]).and(S({run:A.optional()})),wD=w(`modality`,[S({modality:D(`embed`),vectors:x(x(y()))}),S({modality:D(`image`),images:x(kx)}),S({modality:D(`transcribe`),text:v(),segments:x(S({start:y().min(0),end:y().min(0),text:v()})).optional()}),S({modality:D(`speech`),audio:kx}),S({modality:D(`decide`),answers:oD})]).and(S({call:Dl,cost:P,model:v()})),TD=E([`chat`,`transcribe`,`dictate`,`speak`,`describe`,`ocr`,`decide`,`metadata`,`plan`]),ED={chat:`chat`,transcribe:`hearing`,dictate:`hearing`,speak:`audio`,describe:`vision`,ocr:`vision`,decide:`decision`,metadata:`chat`,plan:`chat`},DD=S({model:LE,provider:wl.optional()}),OD=w(`engine`,[S({engine:D(`browser`)}),DD.extend({engine:D(`model`)})]),kD=[`browser`,`model`],AD=TD.exclude([`dictate`,`decide`]),jD=DD.extend({role:D(`decide`),threshold:y().min(0).max(1).default(sD)}),MD=w(`role`,[S({role:D(`dictate`),engine:OD,language:v().optional()}),jD,DD.extend({role:AD,language:v().optional()})]);S({choice:MD,setBy:M,updatedAt:N});var ND=C([S({model:v(),provider:v()}),S({problem:v()})]),PD=S({role:TD,choice:MD.optional(),from:E([`setting`,`env`,`none`]),resolved:ND.optional(),fallback:S({role:TD,reason:v()}).optional()}),FD=[`done`,`invalid-input`,`failed`,`cancelled`],ID=T(E(FD),y().int().min(0));function LD(){return{done:0,"invalid-input":0,failed:0,cancelled:0}}function RD(e){return FD.reduce((t,n)=>t+e[n],0)}var zD=v().regex(/^\d{4}-\d{2}-\d{2}$/),BD=[50,100,250,500,1e3,2500,5e3,1e4,3e4,6e4,3e5],VD=S({count:y().int().min(0),sum:jl,max:jl,histogram:x(y().int().min(0)).length(BD.length+1)}),HD=S({fn:I,system:F,day:zD,outcomes:ID,queued:VD,approval:VD,ran:VD,cost:P,tokens:y().int().min(0),retries:y().int().min(0),modelCalls:y().int().min(0),updatedAt:N}),UD=S({fn:I,system:F,from:zD,to:zD,runs:y().int().min(0),outcomes:ID,p50:jl.optional(),p95:jl.optional(),averageQueued:jl.optional(),averageCost:P,cost:P,tokens:y().int().min(0),retries:y().int().min(0),lastRunAt:N.optional()}),WD=S({fn:ub.optional(),system:F.optional(),days:y().int().min(1).max(365).optional()}),GD=E([`private`,`shared`,`public`]),KD={private:`Only me`,shared:`Me and chosen people`,public:`Everyone`},qD=S({owner:M,visibility:GD,with:x(M)});E([`system`,`fn`,`context`,`root`,`connection`]);var JD=w(`kind`,[S({kind:D(`system`),system:F}),S({kind:D(`fn`),fn:I}),S({kind:D(`context`),context:I}),S({kind:D(`root`),uri:v().min(1)}),S({kind:D(`connection`),connection:Al})]);function YD(e){switch(e.kind){case`system`:return`system:${e.system}`;case`fn`:return`fn:${e.fn}`;case`context`:return`context:${e.context}`;case`root`:return`root:${e.uri}`;case`connection`:return`connection:${e.connection}`}}S({key:v(),target:JD,sharing:qD,scoped:b().optional(),setBy:M,updatedAt:N});var XD=S({target:JD,sharing:qD,editable:b()}),ZD=S({multiUser:b()}),QD=qD.omit({owner:!0}),$D=S({run:A,fn:k,share:QD}),eO=S({run:A,fns:x(k).max(1e3)}),tO=S({source:E([`fn`,`context`,`system`,`person`,`group`,`model`,`resource`,`type`,`kind`]),text:v().optional(),values:x(v()).max(200).optional(),limit:y().int().min(1).max(50).optional()}),nO=S({value:v(),label:v(),hint:v().optional(),icon:v().optional(),missing:b().optional()}),rO=E([`shared`,`person`]),iO=v().regex(/^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/),aO=T(iO,v()),oO=S({kind:D(`none`)}),sO=S({kind:D(`bearer`),per:rO,token:v().min(1).optional()}),cO=S({kind:D(`headers`),per:rO,names:x(iO).min(1),values:aO.optional()}),lO=w(`kind`,[oO,sO,cO,S({kind:D(`oauth`),per:rO,scopes:x(v().min(1)).optional(),clientId:v().min(1).optional(),clientSecret:v().min(1).optional()})]),uO=w(`kind`,[oO,sO,cO]),dO=w(`kind`,[oO,sO.omit({token:!0}),cO.omit({values:!0})]),fO=[`auth.token`,`auth.values`],pO=[`auth.token`,`auth.values`,`auth.clientSecret`];function mO(e){if(e.kind===`oauth`)return`oauth`;if(e.kind!==`none`&&e.per!==`shared`)return`form`}var hO=C([S({token:v().min(1)}),S({headers:aO}),S({accessToken:v().min(1),refreshToken:v().min(1).optional(),tokenType:v().default(`Bearer`),clientId:v().min(1).optional()})]),gO=S({on:b(),ask:b()}),_O=w(`flow`,[S({flow:D(`oauth`)}),S({flow:D(`form`),form:Z})]),vO=S({flow:_O.optional(),share:b().default(!1),title:v().min(1)}),yO=v().regex(Ml).brand();fc({name:yO,label:v().min(1),auth:lO,baseUrl:Ls().optional(),privateTo:M.optional()});var bO=C([yO,S({arg:k})]),xO=S({title:v(),description:v(),icon:v().optional(),how:_O,settings:Z,fns:T(k,gO),scope:E([`system`,`instance`,`key`]).optional(),keys:S({type:I}).optional(),defaults:gO.optional()}),SO=E([`pending`,`connected`,`expired`,`failed`]),CO=S({label:v(),detail:v().optional(),choices:T(v(),x(nO)).optional()}),wO=S({id:Al,system:F,instance:L.optional(),key:yO.optional(),owner:M,status:SO,account:CO.optional(),credentials:Sl.optional(),expiresAt:N.optional(),settings:O,fns:T(k,gO),share:QD,problem:v().optional(),createdAt:N,updatedAt:N}).omit({credentials:!0}),TO=S({system:F,decl:xO,ready:b(),connections:x(wO),instances:x(S({instance:L,label:v(),connect:vO})).optional(),keys:x(S({key:yO,label:v(),connect:vO,host:v().optional()})).optional()}),EO=S({id:Al,owner:M,credentials:O,settings:O}),DO=S({connection:Al,owner:M,redirect:Ls(),state:v(),instance:L.optional(),key:yO.optional()}),OO=S({connection:Al,owner:M,instance:L.optional(),key:yO.optional(),redirect:Ls(),answer:C([S({params:T(v(),v())}),S({form:O})])}),kO=C([S({account:CO,credentials:O,expiresAt:N.optional()}),S({problem:v()})]),AO=S({connection:Al,update:C([S({credentials:O,expiresAt:N.optional()}),S({expired:v()})])}),jO=S({connection:Al,settings:O.optional(),fns:T(k,gO).optional(),share:QD.optional()}),MO=[`embedding`,`imageEmbedding`],NO=S({input:P,output:P,cached:P.optional(),cacheWrite:P.optional()}),PO=S({id:v().min(1),name:v().optional(),capabilities:x(v()),contextWindow:y().int().min(1),maxOutput:y().int().min(1).optional(),pricing:NO,caching:b(),dimensions:y().int().min(1).optional(),maxInput:y().int().min(1).optional(),maxQuestions:y().int().min(1).optional(),maxRequestBytes:y().int().min(1).optional()}).refine(e=>!MO.some(t=>e.capabilities.includes(t))||e.dimensions!==void 0,{message:`An embedding model says how many dimensions its vectors have.`,path:[`dimensions`]}),FO=S({name:k,description:v(),models:x(PO),runtime:D(!0).optional(),instance:L.optional()}),IO=S({provider:k,model:v(),request:YE,stream:b(),run:A.optional()}),LO=w(`type`,[S({type:D(`chunk`),chunk:UE}),S({type:D(`done`),usage:VE}),S({type:D(`error`),message:v(),kind:E([`model`,`limit`,`provider`,`auth`])})]),RO=S({id:v().min(1),contextWindow:y().int().min(1).optional(),maxOutput:y().int().min(1).optional(),maxQuestions:y().int().min(1).optional(),maxRequestBytes:y().int().min(1).optional()}),zO=S({provider:k}),BO=w(`listed`,[S({listed:D(!0),models:x(RO)}),S({listed:D(!1)})]),VO=S({provider:k,model:v(),input:nD,questions:rD}),HO=S({answers:oD,tokens:y().int().min(0).optional()}),UO=S({image:v().regex(/^(https?:|data:)/,`an http(s) or data URL`),mimeType:v().optional()}),WO=C([v(),UO]),GO=S({provider:k,model:v(),inputs:x(WO).min(1)}),KO=S({vectors:x(x(y())),tokens:y().int().min(0).optional()});function qO(e){return S({provider:D(`aws`),region:v().min(1),auth:w(`kind`,[S({kind:D(`keys`),accessKeyId:v().min(1),secretAccessKey:e,sessionToken:e.optional()}),S({kind:D(`apiKey`),apiKey:e})]),profilePrefix:v().optional()})}var JO=S({input:b(),output:b()}),YO=C([S({ok:D(!0)}),S({ok:D(!1),reason:v().min(1)})]),XO=C([S({ok:D(!0)}),S({ok:D(!1),action:E([`retry`,`stop`]),reason:v().min(1)})]),ZO=w(`phase`,[S({phase:D(`input`),run:zT,fn:v(),args:O}),S({phase:D(`output`),run:zT,fn:v(),args:O,result:O,attempt:y().int().min(1)})]),QO=C([XO,YO]),$O=S({kind:E([`builtin`,`dynamic-import`,`dynamic-require`,`eval`,`new-function`]),line:y().int().min(1),detail:v(),code:v()}),ek=S({size:y().int().min(0),builtins:x(v()),concerns:x($O),urls:x(v()),hosts:x(v())}),tk=E([`passed`,`failed`,`skipped`]),nk=S({file:v().min(1),name:v().min(1),status:tk,duration:jl,real:b().optional(),error:v().max(4e3).optional()}),rk=[`phone`,`desktop`],ik=E(rk);E([`empty`,`loading`,`error`,`typical`,`long`]);var ak=S({component:v().min(1),state:v().min(1),viewport:ik,theme:E([`light`,`dark`]),image:kx}),ok=S({scan:ek,tests:S({system:F,version:v().min(1),ranAt:N,duration:jl,passed:y().int().min(0),failed:y().int().min(0),skipped:y().int().min(0),cases:x(nk).max(500),more:y().int().min(0).optional(),previews:x(ak).max(200).optional()}).optional()}),sk=E([`ai`,`embed`,`resources`,`fns`,`search`,`decide`,`approvals`,`connections`,`settings`,`state`,`data`,`runs`]),ck=S({roles:x(TD).optional(),models:x(v().min(1)).optional(),perRun:P.optional(),perDay:P.optional()}),lk=S({read:x(v().min(1)),write:x(v().min(1))}),uk=S({hub:x(sk),models:ck.optional(),secrets:x(v().min(1)).optional(),calls:x(C([I,F])).optional(),network:x(v().min(1)).optional(),files:lk.optional()}),dk=S({component:v().min(1),mode:E([`replace`,`beside`])}),fk=[`installed`,`live`],pk=E(fk),mk=[`text`,`integer`,`number`,`boolean`,`date`,`datetime`,`time`,`uuid`,`json`,`binary`],hk=E(mk),gk=E([`group`,`measure`,`attribute`]),_k=S({name:k,label:v().min(1),accepts:x(hk).min(1),required:b(),many:b(),min:y().int().min(1).optional(),role:E([`group`,`measure`]).optional()}),vk=w(`rule`,[S({rule:D(`distinct`),channel:k,max:y().int().min(1)}),S({rule:D(`non-negative`),channel:k}),S({rule:D(`bounded`),channel:k}),S({rule:D(`distinct-columns`),channels:x(k).min(2)}),S({rule:D(`links`),from:k,to:k})]),yk=E([`window`,`top-n`,`partition`,`aggregate`]),bk=S({name:k,label:v().min(1),whole:D(!0).optional(),needs:x(k).optional()}),xk=S({claim:D(`range`),channel:k}),Sk=E([`floor`,`structural`,`encoded`,`time-encoded`]),Ck=E([`temporal-key`,`low-cardinality`,`enum-key`,`high-null`,`many-categories`]),wk=S({channels:x(_k).min(1),rows:S({min:y().int().min(0),max:y().int().min(1).optional()}),whole:b(),rules:x(vk).default([]),size:yk.optional(),styles:x(bk).min(1).default([{name:`default`,label:`Default`}]),claims:x(xk).default([]),priority:S({band:Sk,terms:x(Ck)}).default({band:`structural`,terms:[]}),pageSize:y().int().min(1).max(500).optional()}),Tk=S({name:k,description:v(),data:Z}),Ek=S({registry:I,name:k,label:v().min(1),description:v().optional(),icon:v().optional(),shape:wk.optional()}),Dk=Ek.extend({system:F}),Ok=S({name:v().min(1),label:v().optional(),kind:hk,nullable:b(),type:Z.optional(),ref:I.optional(),role:gk.optional(),key:b().optional(),editable:b().optional()}),kk=S({column:v().min(1),dir:E([`asc`,`desc`])}),Ak=S({fn:I,args:T(v(),O),keys:x(v().min(1))}),jk=S({columns:x(Ok),rows:x(x(O)),offset:y().int().min(0),limit:y().int().min(1).optional(),total:y().int().min(0).optional(),truncated:b(),sort:x(kk),write:S({affected:y().int().min(0)}).optional(),records:S({type:I,id:v().min(1)}).optional(),drill:Ak.optional()}),Mk=S({flag:E([`delete-fns`,`write-fns`,`runs`,`injects`,`effects`,`capabilities`,`secrets`,`hosts`,`files`,`calls`,`models`]),line:v().min(1),items:x(v().min(1)),lead:v().min(1).optional(),tail:v().min(1).optional()}),Nk=S({section:v().min(1),added:y().int().min(0),changed:y().int().min(0),removed:y().int().min(0)}),Pk=E([`widened`,`narrowed`,`changed`,`added`]),Fk=S({line:v(),counts:x(Nk),flags:x(Mk),grants:Pk.optional(),config:E([`added`,`changed`,`removed`]).optional()}),Ik=E([`gitignored`,`env`,`key`,`credential`,`token`,`secret-content`,`runs-code`,`unknown-path`]),Lk=E([`allow`,`ask`,`refuse`]),Rk=E([`ask`,`refuse`]),zk=w(`type`,[S({type:D(`glob`),glob:v().min(1)}),S({type:D(`content`),pattern:v().min(1)}),S({type:D(`gitignored`)})]);S({name:v().min(1),kind:Ik,match:zk,except:x(v().min(1)).optional(),read:Lk,write:Rk,why:v().min(1)});var Bk=S({path:v().min(1),kind:Ik,rule:v().min(1),access:E([`read`,`write`]),action:E([`allow`,`ask`,`refuse`]),why:v().min(1),certain:b()}),Vk=S({flags:x(Bk)}),Hk=w(`type`,[S({type:D(`text`),text:v()}),S({type:D(`code`),language:v(),code:v(),title:v().optional()}),S({type:D(`table`),title:v(),table:jk}),S({type:D(`type-diff`),name:v(),before:Z.optional(),after:Z.optional(),changes:x(v()),breaks:x(S({fn:v(),why:v()}))}),S({type:D(`flags`),flags:x(Bk).min(1)})]),Uk=S({kind:D(`system-install`),system:F,instance:L,version:v().min(1),manifestHash:v().min(1),bundleHash:v().min(1),sourceHash:v().min(1),host:Kl,source:v().min(1).optional(),grants:uk.optional(),replaces:S({version:v().min(1),manifestHash:v().min(1)}).optional()}),Wk=w(`kind`,[Uk]),Gk=S({title:v().min(1),parts:x(Hk),irreversible:b(),subject:Wk.optional(),checks:ok.optional(),summary:Fk.optional()}),Kk=E([`person`,`admins`]),qk=S({preview:b(),remember:b(),approver:Kk.optional()}),Jk=S({run:A,fn:k,args:O,user:IT,kind:Nl.optional(),payload:O.optional()}),Yk=S({run:A,fn:k,args:O,user:IT,deadline:N}),Xk=S({problems:x(QT)}),Zk=S({type:Z,into:k,label:v().min(1).max(80).optional()}),Qk=S({fn:k,args:O,key:v().min(1),parent:A.optional(),approver:Kk,for:M.optional(),chat:j.optional(),ask:Zk.optional(),preview:Gk}).refine(e=>e.parent!==void 0||e.approver===`admins`||e.for!==void 0,{message:"A run proposed outside a run waits for an admin, or for the person named in `for`.",path:[`approver`]}),$k=S({by:M,preview:Gk}),eA=S({run:A,subject:Uk}),tA=S({token:v().min(1),expiresAt:N}),nA=S({run:A,approval:hl}),rA=v().regex(/^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)*$/),iA=x(rA),aA=`•••• kept`,oA=S({$secret:Sl,json:D(!0).optional()}),sA=v().regex(/^[a-z][a-z0-9-]{0,39}$/,`a page segment is lowercase letters, digits and dashes, starting with a letter (at most 40)`),cA=E([`main`,`hidden`]),lA=E([`everyone`,`admin`]),uA=S({segment:sA,title:v().trim().min(1).max(40),description:v().optional(),icon:v().min(1).optional(),nav:cA.default(`main`),access:lA.default(`everyone`),component:v().min(1)});function dA(e){let t=new Set;return e.flatMap(e=>t.has(e.segment)?[`page ${e.segment} is declared twice`]:(t.add(e.segment),[]))}var fA=x(uA).superRefine((e,t)=>{for(let n of dA(e))t.addIssue({code:`custom`,message:n})}),pA=uA.extend({system:F,client:S({url:v().min(1),hash:v().min(1)})}),mA=S({instance:L,description:v(),online:b(),version:v()}),hA=`http://127.0.0.1:11434`;function gA(e){return w(`provider`,[S({provider:D(`openai`),apiKey:e,baseURL:Ls().optional()}),S({provider:D(`openrouter`),apiKey:e}),S({provider:D(`ollama`),baseURL:Ls().default(hA),contextWindow:y().int().min(256).optional(),decisionModels:x(v().min(1)).optional()}),qO(e)])}var _A=gA(Sl),vA=E(_A.options.map(e=>e.shape.provider.value));S({id:wl,config:_A,createdAt:N}),S({id:Sl,name:v(),owner:M,ciphertext:v(),createdAt:N});var yA=S({id:Cl,name:v(),description:v(),models:x(v())}),bA=w(`scope`,[S({scope:D(`hub`)}),S({scope:D(`group`),group:M}),S({scope:D(`user`),user:M}),S({scope:D(`session`),session:j}),S({scope:D(`turn`),turn:sl}),S({scope:D(`system`),system:F}),S({scope:D(`fn`),fn:I}),S({scope:D(`model`),model:v()})]),xA=E([`hub`,`group`,`user`,`session`,`turn`]),SA=w(`scope`,[S({scope:D(`hub`)}),S({scope:D(`group`),group:M}),S({scope:D(`user`),user:M}),S({scope:D(`session`),session:j}),S({scope:D(`turn`),turn:sl})]),CA=S({id:gl,target:bA,period:C([S({window:jl}),D(`all-time`),D(`per-turn`)]),maxCost:P,maxTokens:y().int().optional(),maxCalls:y().int().optional(),maxTime:jl.optional(),share:E([`pooled`,`each`]).optional(),onLimit:E([`wait`,`refuse`,`ask`]),setBy:M}),wA=S({id:_l,target:SA,default:Ll.optional(),max:Ll.optional(),setBy:M}),TA=S({priority:Ll,priorityFrom:S({default:xA,cappedBy:xA.optional()}),turn:S({cost:P,time:jl}),budgets:x(S({rule:gl,scope:bA,remaining:P})),limitedBy:gl.optional()});S({id:vl,budgets:x(gl),estimate:P,createdAt:N,settled:S({cost:P,at:N}).optional()}),S({id:yl,at:N,cost:P,tokens:y().int().min(0),actor:M,system:F.optional(),session:j.optional(),fn:I,model:v().optional(),llmCall:dl.optional(),modelCall:Dl.optional(),run:A});var EA=E([`chat`,`admin`,`disconnected`,`needs-config`,`held`,`removed`]),DA=S({prompt:x(S({name:F,label:v(),description:v(),summary:v().optional()})),on:x(F),off:x(S({name:F,why:EA}))}),OA=S({name:F,reason:v(),label:v().optional(),description:v().optional()}),kA=RegExp(`(\\d+)`,`g`);function AA(e,t=[]){let n=new Map(t.map(e=>[e.index,e.number]));return e.replace(kA,(e,t)=>{let r=n.get(Number(t));return r===void 0?``:`[${r}]`})}function jA(e){let t=e.trim().replace(/^\$\.?/,``);if(t===``)return[];let n=[],r=/\[\s*(?:"([^"]*)"|'([^']*)'|(\d+))\s*\]|([^.[\]]+)/y,i=0;for(;i<t.length;){if(t[i]===`.`){i+=1;continue}r.lastIndex=i;let e=r.exec(t);if(e===null)return;n.push(e[1]??e[2]??e[3]??e[4]??``),i=r.lastIndex}return n}function MA(e){try{return O.parse(JSON.parse(e))}catch{return}}function NA(e,t){let n=jA(t);if(n===void 0)return;let r=e;for(let e of n){let t=typeof r==`string`?MA(r):r;if(Array.isArray(t)){if(!/^\d+$/.test(e))return;let n=t[Number(e)];if(n===void 0)return;r=n}else if(typeof t==`object`&&t){if(!Object.hasOwn(t,e))return;let n=t[e];if(n===void 0)return;r=n}else return}return{value:r}}var PA=S({index:y().int().min(1),number:y().int().min(1),tool:v(),path:v(),note:v()}),FA=E([`result`,`reply`]),IA=PA.extend({run:A.optional(),fn:I.optional(),found:FA.optional(),value:O.optional(),large:D(!0).optional(),problem:v().optional()}),LA=S({prompt:b(),on:b()}),RA=y().int().min(0).max(3),zA=S({agent:I,model:LE.optional(),mode:zb.optional(),contextor:Xb.optional(),fnMode:fx.optional(),systems:C([x(F),D(`all`)]),instructions:v().optional(),citations:b().optional()}),BA=zA.partial(),VA=x(S({label:v().trim().min(1).max(40).optional(),settings:BA})).min(2).max(4),HA=S({turn:sl,variant:RA,label:v()}),UA=S({variant:RA,label:v(),settings:BA,session:j,turn:sl}),WA=S({run:A,fn:I}),GA=S({variant:RA,effects:x(WA)}),KA=S({variant:RA,label:v(),effects:x(WA).min(1)}),qA=S({variants:x(UA).min(2).max(4),reserved:P,chosen:RA.optional(),chosenBy:M.optional(),chosenAt:N.optional(),discarded:x(GA)}),JA=S({field:v(),type:v(),before:O.optional(),after:O.optional()}),YA=S({id:A,fn:I,fnVersion:v(),kind:Nl,system:F,instance:L.optional(),parent:A.optional(),root:A,turn:sl,session:j.optional(),key:v(),actor:M,caller:M,connection:Al.optional(),llmCall:dl.optional(),toolCallId:v().optional(),args:O,repairs:x($T).optional(),test:b().optional(),status:rE,awaitingSystem:b().optional(),text:_T.optional(),outcome:dE.optional(),progress:qT.optional(),allowed:UT,cost:P,totalCost:P,priority:Ll,background:b(),attempt:y().int().min(1),errors:x(S({attempt:y().int(),error:XT,cost:P,at:N})),undo:O.optional(),resume:O.optional(),stateChanges:x(JA),tokens:y().int().min(0).optional(),createdAt:N,approvedAt:N.optional(),startedAt:N.optional(),endedAt:N.optional(),resultRevision:y().int().min(1).optional(),resultUpdatedAt:N.optional(),resultUpdatedBy:M.optional()}),XA=YA.pick({id:!0,fn:!0,status:!0,cost:!0,totalCost:!0,startedAt:!0,endedAt:!0}),ZA=S({session:j,system:F,name:v(),type:v(),def:Z,value:O,version:y().int().min(1),updatedBy:C([S({run:A}),S({delivery:ll})]),updatedAt:N}).pick({name:!0,type:!0}).extend({value:O.optional()}),QA=E([`queued`,`delivered`,`done`,`failed`,`expired`]),$A=S({id:ll,system:F,kind:C([S({action:v(),input:O}),S({form:A,value:O})]),session:j,actor:M,run:A.optional(),status:QA,result:O.optional(),error:XT.optional(),attempts:y().int().min(0),createdAt:N,deliveredAt:N.optional(),doneAt:N.optional(),expiresAt:N.optional()}).pick({id:!0,status:!0,result:!0,error:!0}),ej=S({id:ul,run:A,handler:v(),args:O,decl:S({description:v(),args:Z,returns:Z}),answerer:C([S({user:M}),S({system:F,run:A})]),status:E([`pending`,`answered`,`failed`]),result:O.optional(),createdAt:N}),tj=E([`running`,`done`,`failed`,`cancelled`,`paused`,`undone`]),nj=S({transcript:y().int().min(0),tools:x(I),context:x(I),selection:ux.optional(),suggested:x(I).optional(),announcedSystems:DA.optional(),citationsTold:LA.optional()});S({id:sl,session:j.optional(),message:cl.optional(),actor:M,user:IT,time:LT,client:BT.optional(),root:A.optional(),status:tj,limits:TA,cost:P,errors:C([S({max:y().int().min(1)}),D(`feed-back`)]),start:nj.optional(),compare:qA.optional(),createdAt:N,continuedAt:N.optional(),endedAt:N.optional()});var rj=E([`queued`,`streaming`,`done`,`failed`,`aborted`]),ij=S({content:v(),reasoning:v().optional(),toolCalls:x(UE.shape.toolCall.unwrap()).optional(),finishReason:UE.shape.finishReason.unwrap(),refusal:v().optional()}),aj=S({id:dl,turn:sl,run:A,session:j.optional(),system:F.optional(),iteration:y().int().min(0),provider:v(),model:v(),request:YE,response:ij.optional(),usage:VE.optional(),cost:P,status:rj,error:v().optional(),priority:Ll,selection:sx.optional(),modelCall:Dl.optional(),queuedAt:N,startedAt:N.optional(),firstTokenAt:N.optional(),endedAt:N.optional()}),oj=Kc(()=>S({run:XA,llmCalls:x(aj.pick({id:!0,model:!0,cost:!0,status:!0})),children:x(oj)})),sj=S({turn:sl,undone:x(S({run:A,fn:I,summary:v()})),failed:x(S({run:A,fn:I,error:XT})),notUndoable:x(S({run:A,fn:I})),kept:x(KA).optional(),session:S({messages:y().int().min(0),unloaded:x(I),reloaded:x(I)}).optional()});S({run:A,turn:sl,session:j.optional(),iteration:y().int().min(0),priority:Ll}),S({run:A,priority:Ll});var cj=[`system`,`instance`,`fn`,`context`,`type`,`kind`,`resource`,`root`,`component`,`registry`,`command`,`provider`],lj=E(cj),uj=[`brings`,`names`,`loads`,`next`,`reads`,`writes`,`calls`,`uses`,`kind`,`creates`,`updates`,`removes`,`refers`,`renders`,`contributes`,`belongs`],dj=E(uj),fj=[...fk,`pending`];E(fj);var pj=E([`text`,`enum`,`number`,`date`,`boolean`]);E([`is`,`isNot`,`in`,`notIn`,`gt`,`gte`,`lt`,`lte`,`between`,`empty`,`notEmpty`,`contains`]);var mj={text:[`contains`,`is`,`isNot`,`in`,`notIn`,`empty`,`notEmpty`],enum:[`is`,`isNot`,`in`,`notIn`,`empty`,`notEmpty`],number:[`gt`,`gte`,`lt`,`lte`,`between`,`is`,`isNot`,`empty`,`notEmpty`],date:[`gt`,`gte`,`lt`,`lte`,`between`,`empty`,`notEmpty`],boolean:[`is`]},hj={is:`is`,isNot:`is not`,in:`in`,notIn:`not in`,gt:`>`,gte:`≥`,lt:`<`,lte:`≤`,between:`between`,empty:`is empty`,notEmpty:`is not empty`,contains:`contains`},gj=C([v(),y(),b()]),_j=E([`usd`,`ms`,`tokens`,`bytes`,`count`]);S({label:v(),type:pj,sortable:b(),filterable:b(),values:x(v()).readonly().optional(),dynamic:b().optional(),unit:_j.optional()});var vj=v().min(1),yj=w(`op`,[S({field:vj,op:E([`is`,`isNot`,`gt`,`gte`,`lt`,`lte`,`contains`]),value:gj}),S({field:vj,op:E([`in`,`notIn`]),values:x(gj).min(1)}),S({field:vj,op:D(`between`),from:gj,to:gj}),S({field:vj,op:E([`empty`,`notEmpty`])})]),bj=S({field:vj,dir:E([`asc`,`desc`])}),xj=Vl.extend({text:v().optional(),filters:x(yj).max(20).optional(),sort:x(bj).max(3).optional()}),Sj=(e,t={})=>({label:e,type:`text`,sortable:!0,filterable:!0,...t}),Cj=(e,t)=>({label:e,type:`enum`,sortable:!0,filterable:!0,values:t}),wj=e=>({label:e,type:`enum`,sortable:!0,filterable:!0,dynamic:!0}),Tj=(e,t)=>({label:e,type:`number`,sortable:!0,filterable:!0,unit:t}),Ej=e=>({label:e,type:`date`,sortable:!0,filterable:!0}),Dj=e=>({label:e,type:`boolean`,sortable:!1,filterable:!0}),Oj=e=>({...e,sortable:!1}),kj=[`resources`,`fns`,`runs`,`modelCalls`,`llmCalls`,`sessions`,`contexts`,`notifications`,`systems`,`types`,`graph`,`users`,`groups`],Aj=E(kj),jj={resources:{fields:{name:Sj(`Name`),system:wj(`System`),family:Cj(`Type`,CE),source:Cj(`Source`,bE),forms:{...Cj(`Forms`,Lx.options),sortable:!1},size:Tj(`Size`,`bytes`),seenAt:Ej(`Seen`),modifiedAt:Ej(`Modified`)},defaultSort:[{field:`seenAt`,dir:`desc`}]},fns:{fields:{name:Sj(`Name`),system:wj(`System`),kind:wj(`Kind`),available:Dj(`Available`),paused:Dj(`Paused`),disabled:Dj(`Disabled`),runs:Tj(`Runs`,`count`),failures:Tj(`Failures`,`count`),averageCost:Tj(`Avg cost`,`usd`),averageTime:Tj(`Avg time`,`ms`),lastRunAt:Ej(`Last run`),updatedAt:Ej(`Updated`)},defaultSort:[{field:`name`,dir:`asc`}]},runs:{fields:{fn:wj(`Fn`),system:wj(`System`),status:Cj(`Status`,nE),session:wj(`Session`),actor:wj(`By`),cost:Tj(`Cost`,`usd`),duration:Tj(`Duration`,`ms`),createdAt:Ej(`Started`),endedAt:Ej(`Ended`)},defaultSort:[{field:`createdAt`,dir:`desc`}]},modelCalls:{fields:{modality:Cj(`Modality`,cD),model:wj(`Model`),provider:wj(`Provider`),system:wj(`System`),status:Cj(`Status`,_D.options),session:wj(`Session`),cost:Tj(`Cost`,`usd`),tokens:Tj(`Tokens`,`tokens`),duration:Tj(`Duration`,`ms`),createdAt:Ej(`Started`)},defaultSort:[{field:`createdAt`,dir:`desc`}]},llmCalls:{fields:{model:wj(`Model`),system:wj(`System`),status:Cj(`Status`,rj.options),session:wj(`Session`),cost:Tj(`Cost`,`usd`),tokens:Tj(`Tokens`,`tokens`),duration:Tj(`Duration`,`ms`),createdAt:Ej(`Started`)},defaultSort:[{field:`createdAt`,dir:`desc`}]},sessions:{fields:{title:Sj(`Title`),agent:wj(`Agent`),status:Cj(`Status`,[`idle`,`running`,`paused`]),archived:Dj(`Archived`),createdAt:Ej(`Created`),updatedAt:Ej(`Updated`)},defaultSort:[{field:`updatedAt`,dir:`desc`}]},contexts:{fields:{name:Sj(`Name`),system:wj(`System`),origin:Cj(`Origin`,Qx),tags:wj(`Tag`),status:Cj(`Status`,hS),askedBy:Cj(`Asked by`,yS),stale:Dj(`Stale`),tokens:Tj(`Tokens`,`tokens`),lastModified:Ej(`Last modified`),updatedAt:Ej(`Updated`)},defaultSort:[{field:`updatedAt`,dir:`desc`}]},notifications:{fields:{kind:wj(`Kind`),read:Dj(`Read`),createdAt:Ej(`Received`)},defaultSort:[{field:`createdAt`,dir:`desc`}]},systems:{fields:{name:Sj(`Name`),status:wj(`Status`),version:Sj(`Version`),instances:Tj(`Instances`,`count`),fns:Tj(`Fns`,`count`),context:Tj(`Context`,`count`),types:Tj(`Types`,`count`),parts:Tj(`Other parts`,`count`),pending:Tj(`Pending changes`,`count`),refusals:Tj(`Refusals`,`count`),lastSeenAt:Ej(`Last seen`)},defaultSort:[{field:`name`,dir:`asc`}]},types:{fields:{name:Sj(`Name`),system:wj(`System`),instance:wj(`Instance`),references:Tj(`Refers to`,`count`),updatedAt:Ej(`Updated`)},defaultSort:[{field:`name`,dir:`asc`}]},graph:{fields:{name:Oj(Sj(`Name`)),system:Oj(wj(`System`)),nodeKind:Oj(Cj(`Item`,cj)),edgeKind:Oj(Cj(`Link`,uj)),fnKind:Oj(wj(`Fn kind`)),mode:Oj(wj(`Mode`)),effect:Oj(wj(`Effect on`)),visibility:Oj(Cj(`Visible to`,Rl.options)),stage:Oj(Cj(`Stage`,fj)),on:Dj(`On`)},defaultSort:[]},users:{fields:{name:Sj(`Name`),email:Sj(`Email`),role:Cj(`Role`,[`admin`,`member`]),disabled:Dj(`Disabled`),createdAt:Ej(`Added`)},defaultSort:[{field:`name`,dir:`asc`}]},groups:{fields:{name:Sj(`Name`),createdAt:Ej(`Added`)},defaultSort:[{field:`name`,dir:`asc`}]}};function Mj(e,t){return t.sort!==void 0&&t.sort.length>0?t.sort:jj[e].defaultSort}var Nj=S({value:gj,label:v().optional(),count:y().int().min(0)}),Pj=S({list:Aj,field:vj,prefix:v().optional(),limit:y().int().min(1).max(50).optional()}),Fj=S({list:Aj,query:xj.default({})}),Ij=Bl(Zc()).extend({sort:x(bj),total:y().int().min(0).optional(),partial:D(!0).optional().describe(`More rows than the hub reads at once: more may match; narrow the filters for a full answer.`)}),Lj=ol.record,Rj=S({shape:E([`table`,`value`]),owner:E([`shared`,`person`]),writers:D(`admins`).optional(),search:S({text:x(v().min(1)),embed:b()})}),zj=S({id:Lj,type:I,value:O,owner:M.optional(),title:v(),version:y().int().min(1),createdAt:N,updatedAt:N,updatedBy:M.optional(),updatedBySystem:F.optional(),run:A.optional()}),Bj=S({id:v().min(1),record:Lj,type:I,number:y().int().min(1),change:E([`created`,`updated`,`removed`]),value:O,by:M.optional(),bySystem:F.optional(),run:A.optional(),at:N}),Vj=S({type:I,query:xj.optional(),search:v().min(1).optional(),run:A.optional()}),Hj=Bl(zj),Uj=Vj.extend({query:xj.omit({cursor:!0,limit:!0}).optional(),offset:y().int().min(0).optional(),limit:y().int().min(1).max(500).optional()}),Wj=S({type:I,id:Lj,run:A.optional()}),Gj=S({type:I,id:Lj.optional(),value:O,expect:y().int().min(1).optional(),run:A.optional(),owner:M.optional()}),Kj=S({type:I,id:Lj,set:T(v().min(1),O).refine(e=>Object.keys(e).length>0,`set at least one field`),expect:y().int().min(1).optional(),run:A.optional()}),qj=S({type:I,id:Lj,run:A.optional()}),Jj=Vl.extend({type:I,id:Lj}),Yj=Bl(Bj),Xj=S({type:I,system:F,description:v(),storage:Rj,records:y().int().min(0),updatedAt:N.optional()}),Zj=Vl.extend({text:v().optional(),system:F.optional()}),Qj=Bl(Xj),$j=`general`,eM=S({name:k,title:v().min(1),description:v().min(1)}),tM=E([`sqlite`,`postgres`,`sqlserver`]),nM=tM.options,rM=S({description:v().min(1).max(500),vectors:b().default(!1),engines:x(tM).min(1).default([...nM])}),iM=v().regex(/^[A-Za-z0-9][A-Za-z0-9_.-]{0,99}$/,`A migration id is letters, digits, dots, dashes and underscores, starting with a letter or digit.`),aM=v().regex(/^[A-Za-z_][A-Za-z0-9_]{0,62}$/,`A schema name is letters, digits and underscores, starting with a letter or underscore.`),oM=E([`postgres`,`sqlserver`]);E([`system`,`hub`,`external`]);var sM=`system`,cM=w(`placement`,[S({placement:D(`system`)}),S({placement:D(`hub`)}),S({placement:D(`external`),engine:oM,connection:oA,schema:aM})]),lM=w(`placement`,[S({placement:D(`system`)}),S({placement:D(`hub`)}),S({placement:D(`external`),engine:oM,connection:v().min(1).max(4e3),schema:aM})]),uM=w(`placement`,[S({placement:D(`system`)}),S({placement:D(`hub`)}),S({placement:D(`external`),engine:oM,connection:v().min(1),schema:aM})]),dM=[`sqlite`,`postgres`,`sqlserver`],fM={postgres:`Postgres with the pgvector extension installed (CREATE EXTENSION vector)`,sqlserver:`SQL Server 2025 or newer, which has the VECTOR type`};function pM(e){return e.placement===`external`&&e.engine!==void 0?e.engine:`sqlite`}function mM(e,t){let n=pM(t),r=t.placement===`external`?`an external ${n} database`:`the ${t.placement===`hub`?`hub`:`system`} (SQLite)`;return e.engines.includes(n)?e.vectors&&!dM.includes(n)?[`This store keeps vectors, which ${r} can't hold.`]:[]:[`This store runs only on ${e.engines.join(`, `)}, so it can't be kept in ${r}.`]}var hM=E([`preparing`,`migrating`,`ready`,`moving`,`failed`]),gM=S({applied:x(S({id:iM,checksum:v().min(1),at:N})),pending:x(iM)}),_M=S({name:v().min(1).max(200),rows:y().int().min(0)}),vM=S({bytes:y().int().min(0).optional(),tables:x(_M).max(200),at:N,more:b().optional()}),yM=S({state:hM,engine:tM,migrations:gM,error:v().max(4e3).optional(),measure:vM.optional()}),bM=yM.extend({at:N}),xM=w(`placement`,[S({placement:D(`system`)}),S({placement:D(`hub`)}),S({placement:D(`external`),engine:oM,schema:aM})]),SM=v().regex(/^[0-9a-z][0-9a-z_.-]{0,120}$/),CM=S({id:SM,system:v(),instance:v(),where:xM,bytes:y().int().min(0).optional(),at:N,reason:E([`move`,`removed`]),orphaned:b().default(!1)}),wM=v().regex(/^move_[0-9a-z]{8,40}$/),TM=E([`draining`,`waiting`,`copying`,`switching`,`done`,`failed`]),EM=E([`ask`,`cancel`,`wait`]),DM=E([`cancel`,`wait`]),OM=S({step:E([`exporting`,`transferring`,`migrating`,`copying`,`checking`]).optional(),tables:S({done:y().int().min(0),total:y().int().min(0)}),table:v().max(200).optional(),rows:y().int().min(0),bytes:S({done:y().int().min(0),total:y().int().min(0)})}),kM=S({move:wM,system:v(),instance:v(),from:xM,to:xM,phase:TM,runs:EM,running:x(v()),asking:N.optional(),progress:OM,startedAt:N,endedAt:N.optional(),by:v(),backups:x(CM),error:v().max(4e3).optional()}),AM=S({placement:cM,status:bM.optional(),backups:x(CM).optional()}),jM=S({system:v(),instance:v(),decl:rM,placement:xM,status:bM.optional(),holding:b(),measure:vM.optional(),file:S({bytes:y().int().min(0),snapshots:x(S({name:v(),bytes:y().int().min(0),at:N}))}).optional(),backups:x(CM).default([]),move:kM.optional()}),MM=v().regex(/^lease_[0-9a-z]{8,40}$/),NM=S({$bytes:v()}),PM=C([v(),y(),ic(),NM]),FM=S({sql:v().min(1).max(1e6),params:x(PM).max(32766),lease:MM.optional()}),IM=S({rows:x(T(v(),PM)),changes:y().int().min(0).optional(),insertId:y().int().optional()}),LM=S({lease:MM,expiresAt:N}),RM=v().regex(/^[0-9a-z][0-9a-z_.-]{0,120}\.db$/);function zM(e){for(let t of e.matchAll(ST)){let n=(t[1]??``).trim();if(!n.startsWith(`args.`))return`the claim "${e}" uses {${n}}: a claim reads only its call's args ({args.path})`}}var BM=v().min(1).max(500).superRefine((e,t)=>{let n=zM(e);n!==void 0&&t.addIssue({code:`custom`,message:n})}),VM=S({fn:k,args:O,user:IT,caller:A,session:j.optional()}),HM=S({claims:x(v().min(1))});function UM(e){return e==null||e===``?[]:typeof e==`string`?[e]:typeof e==`number`||typeof e==`boolean`?[String(e)]:Array.isArray(e)?e.flatMap(e=>Array.isArray(e)?[JSON.stringify(e)]:UM(e)):[JSON.stringify(e)]}function WM(e,t){let n=[],r=[],i=0;for(let a of e.matchAll(ST)){n.push(e.slice(i,a.index)),i=a.index+a[0].length;let[o,...s]=(a[1]??``).trim().split(`.`),c=o===`args`?UM(DT(t,s)):[],l=a[2],u=c.length>0?c:l===void 0?[]:[l];if(u.length===0)return[];r.push(u)}n.push(e.slice(i));let a=[n[0]??``];return r.forEach((e,t)=>{let r=n[t+1]??``;a=a.flatMap(t=>e.map(e=>`${t}${e}${r}`))}),a}function GM(e,t){return[...new Set(e.flatMap(e=>WM(e,t)))]}var KM=S({label:v(),plural:v().optional(),icon:v().optional(),color:v().optional(),title:v().optional(),subtitle:v().optional()}),qM=S({name:k,description:v(),def:Z,display:KM,methods:x(k),instance:L.optional(),audience:QD.optional(),meta:T(v(),O).optional(),records:Rj.optional()}),JM=E([`user-wins`,`union`,`intersect`,`most-restrictive`]),YM=E([`self`,`fns`]),XM=S({name:k,description:v(),type:Z,appliesTo:x(zl),merge:JM,editableBy:x(YM)}),ZM=S({name:k,description:v(),data:Z}),QM=S({name:k,description:v(),applicability:v(),payload:Z,approveChanges:b(),status:gT.optional(),estimates:b().optional(),approval:qk.optional()}),$M=S({description:v(),args:Z,returns:Z,required:b()}),eN=w(`to`,[S({to:D(`instance`),instance:L}),S({to:D(`any`)})]),tN=S({args:O,result:O.optional(),note:v().optional()}),nN=E([`read`,`write`,`delete`]),rN=E([`fns`,`types`,`context`,`resources`,`kinds`,`components`,`examples`,`approvals`,`secrets`,`connections`,`records`]),iN=[`create`,`update`,`remove`],aN=E(iN),oN=S({thing:rN,action:aN,kind:Nl.optional()}).refine(e=>e.kind===void 0||e.thing===`fns`,{message:`only fns have a kind`,path:[`kind`]}),sN=E([`resources`]),cN=S({mode:nN.optional(),reads:x(I).optional(),writes:x(I).optional(),free:b().optional(),registry:x(oN).optional(),keeps:x(sN).min(1).optional()}),lN=S({language:v().min(1),code:v()}),uN=S({every:jl.min(1e3)}),dN=E([`developer`,`admin`,`reference`]),fN=S({deps:x(I)}),pN=S({name:k,description:v(),instructions:v().optional(),kind:Nl,payload:O.optional(),readable:lN.optional(),args:Z,returns:Z,deps:x(I),handlers:T(v(),$M),progress:GT,status:gT.optional(),operations:HT,undo:Z.optional(),resume:Z.optional(),state:Z.optional(),form:Z.optional(),display:VT,limits:WT,visibility:Rl,tags:x(v()),niche:dN.optional(),examples:x(tN).optional(),validate:JO.optional(),approval:qk.optional(),routing:eN.optional(),connectKey:bO.optional(),effects:cN.optional(),promptExamples:y().int().min(0).max(20).optional(),group:k.optional(),flags:b().optional(),roles:x(TD).optional(),live:uN.optional(),parallelClaims:x(BM).optional(),dynamicClaims:b().optional(),check:fN.optional()}),mN=S({name:v(),hint:v(),required:b()}),hN=S({to:I,when:v().min(1).max(200)}),gN=S({name:k,title:v().min(1).optional(),description:v(),content:v().optional(),command:S({name:v(),args:x(mN)}).optional(),imports:x(I),fns:x(I),suggestFns:x(I),suggest:Rl,visible:Rl,inject:wb.optional(),tags:x(v()),niche:dN.optional(),weight:y().min(0).max(2).optional(),summary:v().optional(),parent:I.optional(),next:I.optional(),choices:x(hN).optional(),links:x(aS).optional(),question:v().min(1).max(500).optional(),when:v().min(1).max(500).optional(),lastModified:N.optional(),askedBy:bS.optional()}),_N=S({name:k,description:v(),explains:v().min(1).max(2e3).optional(),order:y(),timeout:jl}),vN=S({name:k,title:v(),description:v(),target:Z,of:I.optional()}),yN=S({name:k,description:v(),match:Bx}),bN=S({name:k,description:v(),input:Z,returns:Z,state:Z.optional(),expires:jl.optional()}),xN=[`message`,`run`,`resources`,`system`,`fns`],SN=E(xN),CN=S({entry:v(),hash:v(),files:x(S({path:v(),size:y().int().min(0),hash:v()}))}),wN=E([`types`,`settings`,`attachments`,`kinds`,`fns`,`context`,`hooks`,`mentions`,`sectioners`,`actions`]),TN={types:x(qM),settings:x(XM),attachments:x(ZM),kinds:x(QM),fns:x(pN),context:x(gN),hooks:x(_N),mentions:x(vN),sectioners:x(yN),actions:x(bN)},EN=S({name:F,version:v(),description:v(),about:v().optional(),hash:v(),...TN,events:x(SN),resources:b(),client:CN.optional(),config:Z,requires:x(F),providers:x(FO).optional(),connect:xO.optional(),registries:x(Tk).optional(),contributes:x(Ek).optional(),configSecrets:iA.optional(),runtime:bc(wN,x(k)).optional(),grants:uk.optional(),configComponent:dk.optional(),pages:fA.optional(),groups:x(eM).optional(),store:rM.optional()}),DN=S({hash:v(),upsert:S(TN).partial(),remove:bc(wN,x(k)),lists:EN.pick({providers:!0,registries:!0,contributes:!0}).optional(),roots:D(!0).optional()}),ON=S({added:x(I),updated:x(I),removed:x(I),refused:x(S({name:v(),problems:x(v())}))}),kN=S({args:Z,returns:Z,description:v(),mode:nN}),AN=S({args:Z,returns:Z,deps:x(I),types:x(I).optional(),refs:x(v()).optional(),operations:HT,handlers:T(v(),$M).optional(),progress:GT.optional(),status:gT.optional(),limits:WT.optional(),display:VT.optional(),approval:qk.optional(),effects:cN.optional(),readable:lN.optional(),connectKey:yO.optional(),parallelClaims:x(BM).optional(),examples:x(tN).min(1)});function jN(e){return e===`native`||e.startsWith(`hub/`)}function MN(e){return jN(e.kind)&&(e.examples??[]).length===0}var NN=S({session:j,turn:sl,text:v(),user:IT,time:LT}),PN=y(),FN=S({label:v(),mode:nN,blocked:v().optional(),args:v().optional(),returns:v().optional(),instructions:v().optional(),examples:x(tN).optional(),moreExamples:y().int().positive().optional()}),IN={toolset:Bb.optional()},LN=w(`type`,[S({type:D(`text`),tag:v(),text:v()}),S({type:D(`suggest-context`),...IN,items:x(S({context:I,title:v().optional(),why:v().optional(),score:PN.optional()}))}),S({type:D(`suggest-fns`),...IN,items:x(S({fn:I,why:v().optional(),score:PN.optional(),card:FN.optional()}))}),S({type:D(`load`),context:x(I).optional(),fns:x(I).optional()})]),RN=S({label:v(),hint:v().optional(),icon:v().optional(),target:O}),zN=S({title:v(),subtitle:v().optional(),fields:x(S({label:v(),value:v()})).optional(),body:v().optional(),open:Vx.optional(),value:O.optional()});gN.omit({name:!0,content:!0}).extend({key:k,summary:v().min(1).max(300),imports:x(I).default([]),fns:x(I).default([]),suggestFns:x(I).default([]),suggest:Rl.default(`both`),visible:Rl.default(`both`),tags:x(v()).default([]),lastModified:C([N,$c().transform(e=>Date.parse(e)),Qc({offset:!0}).transform(e=>Date.parse(e))]).optional()}).strict();var BN=E([`header`,`duplicate-key`,`broken-link`,`cycle`,`missing-summary`]);S({file:v().min(1),line:y().int().min(1),column:y().int().min(1),code:BN,message:v().min(1)});var VN=S({loaded:x(I),fns:x(I),fnsRefused:x(PT),refused:x(S({context:v(),reason:v().min(1),closest:x(I)})),cards:v()}),HN=S({context:x(v().min(1)).min(1),guidance:v().min(1).max(4e3),maxDepth:y().int().min(0).max(10).default(mS.maxDepth),maxDecisions:y().int().min(1).max(4096).default(mS.maxDecisions),maxTokens:y().int().min(1).max(1e6).default(mS.maxTokens),metadataOnly:b().default(!1)}),UN=E([`start`,`import`,`choice`]),WN=S({name:I,title:v().optional(),description:v(),depth:y().int().min(0),via:UN,from:I.optional(),probability:y().min(0).max(1).optional(),tokens:y().int().min(0),content:v().optional()}),GN=E([`declined`,`max-tokens`,`max-decisions`,`max-depth`,`unavailable`,`failed`]),KN=S({context:v(),from:I.optional(),depth:y().int().min(0),reason:GN,probability:y().min(0).max(1).optional()}),qN=E([`complete`,`max-depth`,`max-decisions`,`max-tokens`,`failed`]),JN=VN.extend({crawled:x(WN),skipped:x(KN),stop:S({reason:qN,detail:v().optional()}),depth:y().int().min(0),decisions:y().int().min(0),tokens:y().int().min(0),calls:x(Dl),metadataOnly:b()}),YN=S({loaded:x(I),refused:x(PT),cards:v()});C([YN.strict(),VN.strict(),JN.strict()]);var XN=S({expiresIn:jl.nullable().optional()}),ZN=S({id:kl,secret:v().min(32),expiresAt:N.optional()}),QN=ZN.pick({id:!0,secret:!0}),$N=S({id:kl,system:F,instance:L,secretHash:v(),previousHash:v().optional(),createdBy:M,createdAt:N,expiresAt:N.optional(),lastUsedAt:N.optional(),uses:y().int().min(0),revokedAt:N.optional()}).omit({secretHash:!0,previousHash:!0}),eP=E([`pairing`,`needs-config`,`connected`,`disconnected`,`removed`]),tP=C([S({path:v()}),S({package:v(),version:v()}),S({git:v(),ref:v()}),S({zip:v().regex(Ox),file:v()})]),nP=S({policy:E([`always`,`on-failure`,`never`]),backoff:jl,maxPerHour:y().int().min(1)}),rP=E([`installing`,`stopped`,`starting`,`running`,`crashed`,`disabled`]),iP=S({name:F,instance:L,source:tP,dir:v(),command:S({run:v(),args:x(v()),env:T(v(),v()),cwd:v().optional()}),version:v(),goodVersion:v().optional(),autoStart:b(),restart:nP,status:rP,pid:y().int().optional(),lastExit:S({code:y().int(),at:N,output:v()}).optional(),installedBy:M,installedAt:N}),aP=S({functions:b(),renderers:b(),context:b().optional()}),oP=S({value:O,version:y().int().min(1),setBy:M,setAt:N}),sP=S({keyFingerprint:v().optional(),publicKey:v().optional(),config:oP.optional(),pairedAt:N.optional(),pairedBy:M.optional(),lastSeenAt:N.optional(),address:v().optional()}),cP=E([`one`,`many`]),lP=S({name:F,description:v(),about:v().optional(),status:eP,enabled:aP,version:v(),manifestHash:v(),defaultInstance:L.optional(),actor:M,stage:pk.optional(),instances:cP.optional()}).extend(sP.shape),uP=S({id:fl,name:F,keyFingerprint:v(),publicKey:v(),version:v(),address:v(),method:E([`code`,`token`]),code:v().optional(),replaces:F.optional(),description:v().optional(),instance:L.optional(),configType:Z.optional(),configSecrets:iA.optional(),store:rM.optional(),status:E([`pending`,`approved`,`rejected`,`expired`]),createdAt:N,expiresAt:N});S({id:pl,name:F.optional(),tokenHash:v(),createdBy:M,expiresAt:N,usedAt:N.optional(),autoPair:XN.optional(),boundTo:S({instance:L,manifestHash:v().min(1),host:Kl,run:A}).optional()}),S({system:F,manifest:EN,importedAt:N});var dP=UD.pick({averageCost:!0,averageQueued:!0,p95:!0,lastRunAt:!0}).extend({outcomes:ID.default(LD),averageTime:jl,tokens:UD.shape.tokens.default(0)}),fP=E([`contract`,`runtime`]),pP=S({name:I,system:F,decl:pN,version:v(),origin:fP,addedBy:M.optional(),available:MT,paused:b(),disabled:b(),stats:dP,updatedAt:N});S({name:I,system:F,decl:QM});var mP=qM.omit({name:!0,methods:!0}).extend({name:I,system:F,references:x(I),declaredBy:fP.optional(),version:v().optional(),updatedAt:N}),hP=S({types:x(mP),missing:x(I)}),gP=gN.extend({alwaysFor:x(I).optional()}),_P=S({name:I,system:F,origin:Zx.optional(),declaredBy:fP.optional(),version:v().optional(),decl:gP,tokens:$x.optional(),status:gS.default(`active`),statusReason:v().optional(),statusHistory:x(xS).optional(),disabled:b().optional(),systemOff:b().optional(),lastModified:N.optional(),duplicate:SS.optional(),contradiction:SS.optional(),notDuplicates:x(I).optional(),checked:S({contentHash:v(),at:N}).optional(),metadata:wS.optional(),split:TS.optional(),validUntil:N.optional(),askedBy:bS.optional(),mentions:S({context:x(I),fns:x(I)}),stale:b(),updatedAt:N,wantsMetadata:b().optional(),wantsCheck:b().optional(),inReview:b().optional()});function vP(e){return e.systemOff===!0||!vS(e.status)}function yP(e){return e.lastModified??e.updatedAt}var bP=[`kinds`,`commands`,`mentions`,`hooks`,`actions`,`settings`,`attachments`,`embedders`,`sectioners`,`providers`,`registries`,`components`,`examples`],xP=E(bP),SP=S({section:xP,name:v().min(1),about:v(),origin:fP,version:v(),visibility:Rl.optional(),owner:I.optional(),decl:O,on:b().optional()}),CP=S({system:F}),wP=S({parts:x(SP),more:bc(xP,y().int().min(0))});function TP(e){return Iw(e?.name??`otel`,{requires:e?.requires??[]})}var EP=v().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/),DP=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i,OP=e=>e!==``&&e!==`.`&&e!==`..`&&!DP.test(e),kP=v().min(1).refine(e=>!e.includes(`\\`)&&!e.includes(`:`)&&e.split(`/`).every(OP),`A package path is relative, uses forward slashes and stays inside the package.`),AP=S({childProcess:b(),workers:b()});S({format:D(1),name:F,version:EP,description:v(),protocol:y().int().min(1),server:S({entry:kP,external:T(v(),v()).default({}),node:v().optional()}),client:S({entry:kP}).optional(),instances:cP.default(`one`),files:T(kP,v().regex(Ox)).optional(),permissions:AP.partial().optional()});var jP=S({state:v(),data:v(),cache:v()}),MP=S({host:Kl,path:v().min(1),bundleHash:v().min(1),approval:hl}),NP=S({system:F,instance:L,description:v(),status:eP,keyFingerprint:v(),publicKey:v(),version:v(),manifestHash:v(),config:oP.optional(),installed:iP.optional(),host:MP.optional(),dirs:jP.optional(),pairedAt:N.optional(),pairedBy:M.optional(),lastSeenAt:N.optional(),address:v().optional(),connect:vO.optional(),store:AM.optional()}),PP=S({instance:L,description:v(),online:b(),config:O,types:x(S({name:I,description:v()}))}),FP=S({pairing:fl,description:v(),instance:L,configType:Z.optional(),configSecrets:iA.optional(),store:rM.optional()});S({format:D(1),system:F,instance:L,version:v(),exportedAt:N,exportedBy:M,withSecrets:b()});var IP=S({system:F,instance:L,description:v().optional(),config:O,store:lM.optional()}),LP=S({at:N,stream:E([`stdout`,`stderr`,`hub`]),text:v()}),RP=S({meaning:b(),items:y().int().min(0),pending:y().int().min(0),embedding:b(),retrying:b(),lastError:S({at:N,message:v()}).optional()}),zP=C([vA,I]),BP=S({id:v(),provider:zP,name:v(),contextWindow:y().int().min(0).optional(),pricing:S({input:P,output:P}).optional(),capabilities:x(v()),maxQuestions:y().int().min(1).optional(),maxRequestBytes:y().int().min(1).optional()}),VP=BP.extend({tier:E([`flagship`,`efficient`,`legacy`,`experimental`]),maxOutputTokens:y().int().min(1).optional(),roles:x(TD)}),HP=CA.extend({spent:P}),UP=S({setting:I,system:F,decl:XM}),WP=aj.omit({request:!0,response:!0}),GP=w(`kind`,[S({kind:D(`budget`),id:gl}),S({kind:D(`priority`),id:_l}),S({kind:D(`policy`),id:ml}),S({kind:D(`category`),id:Cl}),S({kind:D(`provider`),id:wl})]),KP=S({uri:Tx,system:F,stat:jx,links:x(Mx),indexedVersion:v().optional(),sectioner:I.optional(),source:yE.optional(),raw:kx.optional(),forms:x(Lx).optional(),primary:Lx.optional(),seenAt:N});S({id:Tl,match:Bx,sectioner:I,setBy:M}),S({uri:Tx,from:v(),to:v(),added:x(Ex),changed:x(Ex),removed:x(Ex)});var qP=E([`fn`,`context`,`section`,`message`,`type`,`example`,`record`,`contextSection`,`image`,`contextContent`]);S({kind:qP,key:v(),system:F.optional(),text:v(),embedText:v().optional(),hash:v(),vectorHash:v().optional(),embedder:I,updatedAt:N,parent:v().optional(),image:v().optional()});var JP=E([`words`,`meaning`,`both`]);S({kind:qP,key:v(),rank:y().min(0).max(1),similarity:y().min(-1).max(1).optional(),matched:JP.optional(),parent:v().optional(),text:v()});var YP=E([`approval-needed`,`input-needed`,`config-needed`,`message`,`replied`,`turn-finished`,`turn-failed`,`pairing-requested`,`system-disconnected`,`spend-limit`,`system-paused`,`system-notice`,`system-message`]),XP=S({system:F,segment:v().min(1),path:x(v().min(1)).optional(),query:T(v(),v()).optional()}).strict(),ZP=C([S({session:j}),S({approval:hl}),S({pairing:fl}),S({run:A}),S({system:F}),S({page:XP})]),QP=E([`ok`,`failed`,`info`]),$P=S({label:v().min(1).max(24),link:ZP}),eF=S({id:bl,user:M,reason:YP,title:v(),body:v(),link:ZP,read:b(),pushed:b(),resolved:v().optional(),tone:QP.optional(),also:$P.optional(),key:v().min(1).max(200).optional(),createdAt:N}),tF=S({id:xl,user:M,endpoint:Ls(),keys:S({p256dh:v(),auth:v()}),device:v(),createdAt:N}),nF=ol.fnExample;tN.extend({id:nF,fn:I,system:F,source:E([`decl`,`added`,`runtime`]),key:v().min(1).max(200).optional(),order:y().int().min(0),text:v(),addedBy:M.optional(),createdAt:N});var rF=S({fn:k,upsert:x(tN.extend({key:v().min(1).max(200)})),remove:x(v().min(1).max(200))}),iF=S({fn:ub,query:v().optional(),offset:y().int().min(0).optional(),limit:y().int().min(1).max(50).optional()}),aF=S({fn:I,items:x(tN.extend({id:nF,rank:y().optional()})),total:y().int().min(0),next:y().int().min(0).optional()}),oF=E([`text`,`semantic`,`hybrid`]),sF=[`session`,`user`,`everyone`],cF=E([`fn`,`context`]),lF=S({text:v().optional(),match:oF.optional(),items:x(cF).min(1).optional(),kinds:x(C([D(`native`),I])).min(1).optional(),systems:x(F).min(1).optional(),instance:L.optional(),visibility:E([`mine`,`shared`,`public`]).optional(),types:S({reads:x(db).optional(),writes:x(db).optional()}).optional(),modes:x(nN).min(1).optional(),effects:x(S({thing:rN,action:aN.optional(),kind:v().min(1).optional()})).min(1).optional(),names:x(I).min(1).max(100).optional(),filters:x(yj).max(20).optional(),off:b().optional(),statuses:AS.shape.statuses,returnNotApplicable:AS.shape.returnNotApplicable,semanticOver:AS.shape.semanticOver,scopes:x(E(sF)).min(1).optional(),available:b().optional(),niches:x(dN).min(1).optional(),order:E([`rank`,`name`]).optional(),offset:y().int().min(0).optional(),limit:y().int().min(1).max(100).optional()}),uF=lF.omit({items:!0,match:!0,filters:!0,off:!0,scopes:!0,statuses:!0,returnNotApplicable:!0,semanticOver:!0}).extend({kinds:lF.shape.kinds.describe("Leave `kinds` out unless the person asks for a kind of fn by name: you can't know how a fn was made, and a search by what it does finds every kind."),names:x(ub).min(1).max(100).optional().describe(`Only these fns, by name, spelled as your tools and search hits spell them: to look up fns whose names you know. Leave it out to search by what a fn does.`),types:S({reads:x(db).optional(),writes:x(db).optional()}).optional().describe("Only fns that read (`reads`) or write (`writes`) any of these types: a table's name (`tasks`), or a type's name exactly as a result gave it. Leave it out unless you know the type.")}),dF=S({text:lF.shape.text,systems:lF.shape.systems,origins:x(E(Qx)).min(1).optional(),scopes:lF.shape.scopes,tags:x(v().min(1)).min(1).max(20).optional(),names:lF.shape.names,niches:lF.shape.niches,returnNotApplicable:b().optional().describe(`Also find questions a plan ruled out (status not_applicable), each with why it was ruled out; only ones that have an answer come back. Leave it out unless you need to know what was decided against.`),semanticOver:lF.shape.semanticOver.describe("What the meaning of `text` is compared with: `question` (the default: each item is worded as the question it answers, so ask in plain words) or `content` (the item's text itself, for a phrase you expect inside it)."),order:lF.shape.order,offset:lF.shape.offset,limit:lF.shape.limit}),fF=S({key:Ex,path:x(v()),title:v()}),pF=S({item:cF,name:I,system:F,description:v(),kind:v().optional(),mode:nN.optional(),signature:v().optional(),effects:v().optional(),instance:L.optional(),rank:y().optional(),similarity:y().optional(),matched:JP.optional(),section:fF.optional(),question:v().optional(),answer:v().optional(),status:gS.optional(),statusReason:v().optional(),niche:dN.optional(),available:b(),blocked:NT.optional(),inPrompt:E([`injected`,`loaded`]).optional(),exact:D(!0).optional()}),mF=pF.pick({rank:!0,similarity:!0,matched:!0,section:!0}),hF=_P.extend({found:mF.optional(),metadataStale:b().optional()}),gF=S({item:cF,by:E([`decision`,`llm`]),dropped:x(S({name:I,note:v().optional()})),calls:x(Dl).min(1).optional(),failed:v().optional(),action:D(`load`).optional()}),_F=S({fns:x(I),context:x(I),note:v()}),vF=S({items:x(pF),next:y().int().min(0).optional(),filtered:x(gF).optional(),loaded:_F.optional(),missing:S({names:x(I).min(1),note:v()}).optional()}),yF=S({min:P,typical:P,max:P,basis:E([`free`,`history`,`payload`,`unknown`]),runs:y().int().min(0)}),bF=S({runs:y().int().min(0),typical:jl,slow:jl,longest:jl}),xF=S({fn:I,kind:v(),mode:nN,reads:x(I),writes:x(I),uses:x(I),free:b(),registry:x(oN),cost:yF,times:bF.optional(),longRunning:b(),notice:v().optional()}),SF=S({kind:v().min(1),payload:O,args:O.optional(),history:yF.optional()}),CF=S({estimate:yF.optional()}),wF=S({model:DD.optional(),messages:y().int().min(0).max(20).default(4)}),TF=S({value:wF,setBy:M.optional(),updatedAt:N.optional()}),EF=S({entries:x(w(`type`,[S({type:D(`log`),at:N,level:E([`debug`,`info`,`warn`,`error`]),message:v().max(4e3),fields:T(v(),O).optional()}),S({type:D(`traffic`),at:N,method:v().max(16),endpoint:v().max(300),status:y().int(),duration:jl})])).min(1).max(500),page:v().max(300).optional()}),DF=S({uri:Tx,written:y().int().min(0)});xF.pick({fn:!0,kind:!0,mode:!0,reads:!0,writes:!0,uses:!0,free:!0}).extend({registry:x(oN).optional(),system:F,instance:L.optional(),updatedAt:N}),S({fn:I,type:I,use:E([`read`,`write`])}),S({fn:I,type:I,kind:Nl,system:F}),S({fn:I,to:I,link:E([`dep`,`kind`,`role`]),system:F}),S({fn:I,uses:I}),S({id:v(),fn:I,number:y().int().min(1),decl:pN,savedBy:M.optional(),savedAt:N}),S({id:v(),type:I,number:y().int().min(1),decl:qM,instance:L.optional(),savedAt:N});var OF={fns:`fns`,types:`types`,context:`context`,resources:`resources`,kinds:`kinds`,components:`components`,examples:`examples`,approvals:`runs awaiting approval`,secrets:`secrets`,connections:`connections`,records:`records`},kF={create:`Creates`,update:`Updates`,remove:`Removes`};function AF(e){let t=[];for(let n of iN){let r=new Map;for(let t of e){if(t.action!==n)continue;let e=r.has(t.thing)?r.get(t.thing):new Set;e===void 0||t.kind===void 0?r.set(t.thing,void 0):(e.add(t.kind),r.set(t.thing,e))}if(r.size===0)continue;let i=[...r.entries()].map(([e,t])=>t===void 0||t.size===0?OF[e]:`${OF[e]} (${[...t].sort().join(`, `)})`);t.push(`${kF[n]} ${i.join(`, `)}.`)}return t.length===0?void 0:t.join(` `)}var jF=ol.refusal,MF=[`fns`,`context`,`types`,`roots`,...bP],NF=E(MF),PF=S({section:NF,name:v().min(1)});PF.extend({system:F,by:M,at:N});var FF=S({version:v(),hash:v().min(1),grants:uk,runtime:x(PF),by:M,at:N}),IF=S({section:C([NF,E([`grants`,`config`])]),name:v().min(1),change:E([`added`,`changed`,`removed`]),origin:fP,before:O.optional(),after:O.optional()}),LF=IF.pick({section:!0,name:!0}),RF=LF.extend({change:IF.shape.change,origin:fP,version:v(),by:M,at:N}),zF=S({version:v(),hash:v().min(1),by:fP,changes:x(IF),since:N});S({system:F,live:FF.optional(),pending:zF.optional(),checks:ok.optional(),declined:x(RF).optional(),updatedAt:N});var BF=S({mode:nN,effects:v().optional(),reads:x(I),writes:x(I),deps:x(I),cost:P.optional(),free:b().optional()}),VF=S({name:v().min(1),before:BF.optional(),after:BF.optional()}),HF=zF.extend({summary:Fk,fns:x(VF),injections:x(Ob).default([])}),UF=[`stage`,`effects`,`mode`,`types`,`capability`,`models`,`budget`,`secrets`,`calls`,`network`,`files`,`visibility`],WF=E(UF),GF=S({id:jF,system:F,instance:L,rule:WF,attempt:v().min(1),detail:v().min(1),run:A.optional(),fn:I.optional(),at:N}),KF=S({instance:Kl,rule:WF.extract([`network`,`files`]),attempt:v().min(1).max(1e3),detail:v().min(1).max(2e3)}),qF=S({system:F.optional(),rule:WF.optional(),cursor:v().optional(),limit:y().int().min(1).max(200).optional()}),JF=S({items:x(GF),next:v().optional()}),YF=S({system:F,stage:pk,manifest:EN,facts:x(xF),checks:ok.optional(),live:FF.optional(),pending:HF.optional(),declined:x(RF).default([]),off:x(PF),refusals:S({total:y().int().min(0),last:x(GF).max(10)}),previewUrls:T(v(),v()).optional(),clientApproved:b().optional()}),XF=S({system:F,hash:v().min(1),off:x(PF).default([])}),ZF=S({system:F,hash:v().min(1),approve:x(LF).default([]),decline:x(LF).default([]),off:x(PF).default([])}).refine(e=>e.approve.length+e.decline.length>0,{message:`approve or decline at least one change`,path:[`approve`]}),QF=S({hash:v(),waiting:y().int().min(0)}),$F=C([S({preview:Gk,contract:EN.optional(),ask:Zk.optional()}),S({refused:v().min(1)})]),eI=S({fn:I,args:O,instance:L.optional()}),tI=ol.mentionRequest,nI=S({request:tI,query:v(),roots:x(Tx).max(20).optional(),limit:y().int().min(1).max(50)}),rI=S({hits:x(Hx)}),iI=2e3,aI=S({kind:I,changedSince:N.optional(),cursor:v().optional(),limit:y().int().min(1).max(100).optional()}),oI=S({items:x(S({fn:I,kind:I,owner:M,title:v(),version:y().int().min(1),payload:O,removed:b(),updatedAt:N})),cursor:v().optional()}),sI=S({fn:I,args:O,key:v().min(1).max(200),priority:Ll.extract([`background`,`interactive`]).optional(),maxSpend:P.positive().optional()}),cI=S({run:A,turn:sl,status:rE}),lI=S({title:v().min(1).max(120),body:v().max(iI),tone:QP.optional(),link:ZP.optional(),also:$P.optional(),key:v().min(1).max(136).optional()}),uI=`fnloom`,dI=`hub.name`,fI=v().trim().min(1).max(40).refine(e=>!/[\r\n]/.test(e),{message:`One line only.`}),pI=S({name:fI,source:E([`setting`,`env`,`default`]),version:v()}),mI=S({name:fI.nullable()}),hI=[`off`,`text`,`model`];E(hI);var gI=w(`use`,[S({use:D(`off`)}),S({use:D(`text`)}),S({use:D(`model`),embedder:I})]),_I={use:`text`},vI=S({text:b(),images:b(),crossModal:b()}).extend({embedder:I,name:v(),dimensions:y().int().min(1)}),yI=w(`space`,[S({space:D(`none`),reason:v()}),S({space:D(`shared`),embedder:I}),S({space:D(`own`),embedder:I,crossModal:b()})]),bI=S({value:gI,setBy:M.optional(),updatedAt:N.optional(),text:I,options:x(vI),state:yI}),xI={id:M,name:v(),about:v(),createdAt:N,disabled:b()},SI=E([`admin`,`member`]),CI=S({...xI,kind:D(`user`),email:v(),role:SI,timeZone:v().optional()}),wI=w(`kind`,[CI,S({...xI,kind:D(`group`)}),S({...xI,kind:D(`agent`),fn:I}),S({...xI,kind:D(`system`),system:F}),S({...xI,kind:D(`mcp`),mcp:Ol})]),TI=CI.pick({id:!0,kind:!0,name:!0,email:!0,role:!0,timeZone:!0});S({group:M,user:M,addedBy:M,addedAt:N,provider:v().optional()}),S({user:M,kind:E([`password`,`passkey`]),secretHash:v(),createdAt:N}),S({id:El,user:M,version:y().int().min(1),refreshHash:v(),rotatedHashes:x(v()).optional(),device:v(),createdAt:N,lastSeenAt:N,actingAs:M.optional()}),S({actor:M,session:El,version:y().int().min(1)});var EI=S({setting:I,actor:M,value:O,setBy:M,run:A.optional(),updatedAt:N}),DI=C([S({actor:M}),S({group:M}),S({kind:zl}),S({everyone:D(!0)})]),OI=S({fn:v().optional(),system:F.optional(),kind:Nl.optional(),tags:x(v()).optional(),when:tT.optional(),via:I.optional()}),kI=w(`by`,[S({by:D(`turn-user`)}),S({by:D(`actor`),actor:M}),S({by:D(`group`),group:M,quorum:y().int().min(1).optional()}),S({by:D(`admins`)}),S({by:D(`judge`),fn:I}),S({by:D(`hub`)})]);S({fn:I,args:O,actor:M}),S({approve:b(),reason:v()});var AI=w(`effect`,[S({effect:D(`allow`)}),S({effect:D(`deny`),reason:v()}),S({effect:D(`ask`),approver:kI})]),jI=S({id:ml,description:v(),subject:DI,target:OI,decision:AI,priority:y().int(),expiresAt:N.optional(),createdBy:M,createdAt:N,yields:b().optional()}),MI=E([`once`,`session`,`always`]),NI=S({id:hl,run:A,fn:I,policy:ml.optional(),approver:kI,status:E([`pending`,`approved`,`denied`,`expired`]),decisions:x(S({by:M,approve:b(),remember:MI,reason:v().optional(),at:N})),createdAt:N,preview:Gk.optional(),proposed:b().optional(),ask:Zk.optional(),variant:HA.optional()}),PI=v().regex(/^[a-z0-9][a-z0-9-]{0,31}$/,`lower case letters, digits and dashes, starting with a letter or digit`),FI=S({role:v().min(1).default(`groups`).describe(`The claim whose values pick the role (default "groups").`),admin:x(v().min(1)).default([]).describe(`Values of the role claim that make an admin.`),member:x(v().min(1)).optional().describe(`When given, values of the role claim one of which (or an admin value) is needed to sign in.`),groups:v().min(1).optional().describe(`The claim whose values are hub group names to sync the person into.`)}),II=S({id:PI,label:v().min(1).max(60),issuer:Ls(),clientId:v().min(1),clientSecret:v().min(1).optional(),scope:v().min(1).default(`openid email profile`),userinfo:b().default(!0),claims:FI.prefault({})});x(II).refine(e=>new Set(e.map(e=>e.id)).size===e.length,`each provider needs its own id`);var LI=v().trim().toLowerCase().regex(/^(?=.{1,253}$)([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/,`a domain such as example.com`),RI=w(`mode`,[S({mode:D(`invite`)}),S({mode:D(`domains`),domains:x(LI).min(1).max(50)}),S({mode:D(`anyone`)})]),zI=`signInPolicy`,BI=S({limit:y().int().min(1).max(1e5),window:y().int().min(1e3).max(864e5)}),VI=S({account:BI,address:BI}),HI=`signInLimits`,UI=S({proxies:y().int().min(0).max(5)}),WI=`proxyTrust`;S({issuer:v(),sub:v(),provider:PI,user:M,email:v().optional(),linkedAt:N,lastSignInAt:N});var GI=II.pick({id:!0,label:!0}),KI=S({providers:x(II.omit({clientSecret:!0}).extend({confidential:b()})),policy:RI,breakGlass:TI.optional(),callbackUrl:v(),limits:VI,proxy:UI}),qI=S({ok:b(),detail:v()}),JI=S({provider:PI,ok:b(),discovery:qI,keys:qI,checkedAt:N}),YI=E([`linked`,`email`,`new`,`none`]),XI=S({allowed:b(),reason:v(),link:YI,user:TI.optional(),role:SI.optional(),groups:x(v()),unknownGroups:x(v())}),ZI=S({id:v(),provider:PI,at:N,problem:v().optional(),subject:v().optional(),email:v().optional(),emailVerified:b(),claims:T(v(),O),outcome:XI.optional()}),QI=S({provider:PI,label:v(),email:v().optional(),lastSignInAt:N}),$I=TI.extend({disabled:b(),createdAt:N,breakGlass:b(),password:b(),identities:x(QI),groups:x(S({id:M,name:v(),synced:b()}))}),eL=S({id:M,name:v(),about:v(),createdAt:N,members:y().int().min(0)}),tL=S({user:M,name:v().trim().min(1).max(120).optional(),role:SI.optional(),disabled:b().optional()}),nL=S({group:M,user:M,member:b()});function rL(e){return`/auth/sso/${encodeURIComponent(e)}/start`}var iL=`harness_sso_handoff`,aL=E([`score`,`decision`,`graph`]),oL=E([`below-threshold`,`top-n`,`declined`,`budget`,`rule`,`failed`]),sL={"below-threshold":`Score under the threshold`,"top-n":`Others scored higher`,declined:`The decision model declined it`,budget:`No room in the token budget`,rule:`Hidden by a rule`,failed:`Decision model failed; the score decided`},cL=[`suggest`,`load`],lL=E(cL);function uL(e){return e.by===`none`?`suggest`:e.action??`suggest`}var dL=E([`loaded`,`budget`,`blocked`]),fL={loaded:`Loaded for the turn`,budget:`No room to load it, so suggested`,blocked:`Can't be loaded now, so suggested`},pL=w(`used`,[S({used:D(!0),kind:E([`fn`,`context`]),name:I,score:y().optional(),broughtBy:I.optional(),note:v().optional(),load:dL.optional()}),S({used:D(!1),kind:E([`fn`,`context`]),name:I,score:y().optional(),broughtBy:I.optional(),reason:oL,note:v().optional()})]),mL=S({by:aL,threshold:y().optional(),calls:x(Dl).min(1).optional(),action:D(`load`).optional(),items:x(pL)}),hL=S({messages:y().int().min(1).max(20).default(3),candidates:y().int().min(1).max(50).default(20),cap:y().int().min(0).max(20).default(6),floor:y().min(0).max(1).default(.2)}),gL=[`decision`,`llm`,`none`];E(gL);var _L=w(`by`,[S({by:D(`none`)}),hL.extend({by:D(`decision`),model:DD.optional(),action:lL.optional()}),hL.extend({by:D(`llm`),model:DD,action:lL.optional()})]),vL={by:`none`},yL=hL.extend({enabled:b(),model:DD.optional()});function bL(e){let{enabled:t,model:n,...r}=e;return t&&n!==void 0?{by:`llm`,model:n,...r}:vL}var xL=C([_L,yL.transform(bL)]),SL=S({value:_L,setBy:M.optional(),updatedAt:N.optional()}),CL=[`none`,`decision`,`llm`];E(CL);var wL=w(`by`,[S({by:D(`none`)}),S({by:D(`decision`),model:DD.optional(),action:lL.optional()}),S({by:D(`llm`),model:DD,action:lL.optional()})]),TL={by:`none`},EL={fn:`fnsSearchDecision`,context:`contextSearchDecision`},DL=S({value:wL,setBy:M.optional(),updatedAt:N.optional()}),OL=S({fn:DL,context:DL}),kL=S({item:cF,value:wL});w(`key`,[S({key:D(`suggestDecision`),value:xL,setBy:M,updatedAt:N}),S({key:D(`autoClassifier`),value:wF,setBy:M,updatedAt:N}),S({key:D(EL.fn),value:wL,setBy:M,updatedAt:N}),S({key:D(EL.context),value:wL,setBy:M,updatedAt:N}),S({key:D(dI),value:fI,setBy:M,updatedAt:N}),S({key:D(`imageEmbedding`),value:gI,setBy:M,updatedAt:N}),S({key:D(zI),value:RI,setBy:M,updatedAt:N}),S({key:D(gb),value:_b,setBy:M,updatedAt:N}),S({key:D(HI),value:VI,setBy:M,updatedAt:N}),S({key:D(WI),value:UI,setBy:M,updatedAt:N}),S({key:D(yb),value:b(),setBy:M,updatedAt:N}),S({key:D(ES),value:DS,setBy:M,updatedAt:N})]);var AL=E([`all`,`replies`,`none`]),jL=S({actor:M,role:E([`owner`,`member`,`agent`]),notify:AL,joinedAt:N}),ML=E([`idle`,`running`,`paused`]),NL=S({hash:v(),injected:x(I),at:sl}),PL=S({id:j,title:v(),owner:M,...zA.shape,selection:ux.optional(),participants:x(jL),forkOf:j.optional(),fork:HA.optional(),tools:x(I),context:x(I),suggested:x(I).optional(),announcedSystems:DA.optional(),citationsTold:LA.optional(),fixed:NL.optional(),status:ML,transcript:x(BE),createdAt:N,updatedAt:N,archived:b()}),FL=PL.pick({id:!0,title:!0,owner:!0,agent:!0,status:!0,createdAt:!0,updatedAt:!0,archived:!0}),IL=E([`local-time`,`suggested-context`,`suggested-fns`]),LL=S({type:D(`text`),text:v()}),RL=S({type:D(`mention`),provider:I,label:v(),target:O,text:v()}),zL=S({type:D(`command`),context:I,args:T(v(),v())}),BL=S({type:D(`file`),ref:kx,name:v(),uri:Tx.optional(),text:v().optional(),truncated:b().optional()}),VL=S({type:D(`input-answer`),run:A,title:v(),value:O,text:v()}),HL=`input-answer`,UL=S({type:D(`loaded-for-you`),by:E([`decision`,`llm`,`recall`]),toolset:Bb.optional(),fns:x(S({fn:I,label:v(),why:v().optional(),broughtBy:I.optional()})),context:x(S({context:I,title:v().optional(),why:v().optional(),text:v(),fns:x(I).optional()}))}),WL=w(`type`,[LL,S({type:D(`reasoning`),text:v()}),RL,zL,S({type:D(`invocation`),run:A,fn:I}),S({type:D(`call`),run:A,fn:I}),BL,VL,S({type:D(`extra`),extra:IL,blocks:x(LN)}),S({type:D(`hook`),hook:I,blocks:x(LN)}),S({type:D(`attachment`),attachment:I,data:O,title:v()}),S({type:D(`link`),link:Vx}),S({type:D(`systems-changed`),on:x(OA),off:x(OA)}),S({type:D(`kept-effects`),variants:x(KA)}),UL]),GL=new Set([`extra`,`hook`,`input-answer`,`systems-changed`,`loaded-for-you`]);function KL(e){return GL.has(e.type)}var qL=w(`type`,[LL,RL.omit({text:!0}),zL,BL,VL]),JL=S({id:cl,session:j,turn:sl,author:M,role:E([`user`,`assistant`,`note`]),parts:x(WL),runs:x(A),status:E([`streaming`,`done`,`failed`]),replyTo:cl.optional(),replyAll:b(),answerers:x(M),suggestions:mL.optional(),compared:D(!0).optional(),cacheMiss:S({call:Dl,at:N}).optional(),citations:x(IA).optional(),createdAt:N}),YL=E([`pause`,`resume`,`cancel`]),XL=S({run:A,fn:I,status:rE,pause:b(),resume:b(),cancel:b()}),ZL=S({pause:b(),cancel:b(),uncancellable:x(A),undoLastTurn:b(),continueLastTurn:b().optional(),runs:x(XL).optional()}),QL=S({session:j,user:M,focused:b(),typing:b(),lastActiveAt:N}),$L=S({voiceInput:b(),voiceOutput:b(),dictation:S({engine:E(kD),language:v().optional()}).optional(),uploads:b(),meaning:b(),mentions:x(S({provider:I,title:v(),of:I.optional()})),commands:x(S({name:v(),context:I,args:x(mN),description:v(),unavailable:v().optional()})),agents:x(S({fn:I,description:v()})),display:T(v(),VT),invocations:x(S({fn:I,description:v(),args:Z})),methods:x(S({type:I,method:v(),fn:I,description:v(),args:Z})),clients:x(S({system:F,url:v(),hash:v()})),systems:x(S({name:F,status:eP,enabled:b()})),models:x(BP)}),eR=JL.pick({id:!0,session:!0,author:!0,role:!0,replyTo:!0,replyAll:!0,createdAt:!0}).extend({text:v()}),tR=eP.extract([`connected`,`disconnected`,`removed`]),nR=w(`type`,[S({type:D(`message`),message:eR}),S({type:D(`run`),run:A,fn:I,update:uE,notified:b().optional()}),S({type:D(`resources`),changes:x(zx)}),S({type:D(`system`),system:F,status:tR}),S({type:D(`fns`),added:x(I),removed:x(I),changed:x(I).default([])})]),rR=S({protocol:D(1),name:F,version:v(),instance:L.default(Gl),instances:cP.optional(),boot:v(),publicKey:v(),manifestHash:v(),contractHash:v().optional(),pairingToken:v().optional(),autoPair:QN.optional()}),iR=w(`kind`,[S({kind:D(`challenge`),nonce:v()}),S({kind:D(`pairing`),pairing:fl,code:v().optional(),url:v(),expiresAt:N})]),aR=S({signature:v()}),oR=S({maxFrame:y().int().min(1024),maxChunk:y().int().min(1024),heartbeat:jl}),sR=S({value:O,version:y().int().min(1)}),cR=S({instance:L,config:sR.optional(),start:S({first:b(),upgradedFrom:v().optional()}),token:v(),sendManifest:b(),limits:oR,autoPair:ZN.optional(),store:uM.optional()});S({system:F,instance:L,boot:v()});var lR=Iw(`linkSession`,{provides:Aw()}),uR=TP({name:`linkTel`}),dR=S({state:O,calls:T(v(),fE),reason:E([`resumed`,`restart`])}),fR=S({run:zT,fn:v(),kind:Nl,payload:O.optional(),args:O,budget:hE,handlers:x(v()),resume:dR.optional(),deadline:N,configVersion:y().int().min(0),connection:EO.optional(),approved:$k.optional()}),pR=C([S({run:A}),S({delivery:ll})]),mR=S({session:j,actor:M,user:IT,time:LT}),hR=S({level:E([`debug`,`info`,`warn`,`error`]),key:v(),fields:el}),gR=S({run:A,action:E([`cancel`,`pause`])}),_R=S({accepted:b(),reason:v().optional()}),vR=E([`restart`,`upgrade`,`shutdown`,`removed`]),yR=S({title:v().min(1).max(120),body:v().max(2e3)}),bR=X(uR,lR).group({manifest:{body:EN,response:ON,ws:`mf`},patch:{body:DN,response:ON,ws:`mp`},call:{body:S({parent:A,fn:I,args:O,key:v(),budget:S({cost:P.optional(),time:jl.optional()}).optional(),handlers:x(v()),background:b(),on:L.optional()}),response:fE,ws:`call`},handle:{body:S({run:A,handler:v(),args:O}),response:mE,ws:`ha`},control:{body:gR,response:_R,ws:`cl`},progress:{body:S({run:A,progress:JT}),ws:`pg`},allow:{body:S({run:A,operations:UT.partial()}),ws:`al`},undoWith:{body:S({run:A,undo:O}),ws:`uw`},updateResult:{body:S({run:A,result:O}),response:S({revision:y().int().min(1)}),ws:`ur`},attach:{body:S({run:A,item:C([S({attachment:I,data:O,title:v()}),S({link:Vx})])}),ws:`at`},types:{body:S({names:x(I).min(1),run:A.optional()}),response:hP,ws:`ty`},fnShape:{body:S({name:I}),response:S({fn:kN.optional()}),ws:`fsh`},resourcesChanged:{body:S({changes:x(zx)}),ws:`rc`},llm:{body:XE,streamOut:ZE,ws:`llm`},model:{body:CD,response:wD,ws:`mdl`},resource:{body:S({uri:Tx,want:x(Nx),run:A.optional(),sections:x(Ex).min(1).optional()}),response:Fx,ws:`rs`},resourceSections:{body:S({uri:Tx,run:A.optional()}),response:x(Rx),ws:`rsc`},content:{body:S({ref:kx,offset:y().int().min(0),length:y().int().min(1),run:A.optional()}),response:S({chunk:v()}),ws:`ct`},upload:{body:S({upload:v(),chunk:v(),last:b(),mime:v()}),response:S({ref:kx.optional()}),ws:`up`},setting:{body:S({run:A,setting:I}),response:S({value:O.optional()}),ws:`st`},stateGet:{body:S({owner:pR}),response:S({values:el,version:y().int()}),ws:`sg`},stateSet:{body:S({owner:pR,patch:el,clear:x(v()),version:y().int().optional()}),response:C([S({version:y().int()}),S({conflict:D(!0)})]),ws:`ss`},log:{body:hR,ws:`lg`},connectionUpdate:{body:AO,ws:`cu`},instanceConnect:{body:vO,ws:`ic`},shareFn:{body:$D,ws:`sh`},usableFns:{body:eO,response:S({fns:x(k)}),ws:`uf`},propose:{body:Qk,response:nA,ws:`po`},decide:{body:$E,response:eD,ws:`de`},fleet:{body:S({}),response:x(PP),ws:`fl`},searchFns:{body:lF.extend({run:A.optional()}),response:vF,ws:`sf`},fnExamples:{body:iF,response:aF,ws:`fx`},examples:{body:rF,response:S({added:y().int().min(0),removed:y().int().min(0)}),ws:`xp`},models:{body:S({}),response:x(VP),ws:`mo`},grantPairing:{body:eA,response:tA,ws:`gp`},notifyAdmins:{body:yR,ws:`na`},notify:{body:S({run:A,notice:lI}),ws:`nf`},kindFns:{body:aI,response:oI,ws:`kf`},startRun:{body:sI,response:cI,ws:`sru`},notifyOwner:{body:S({fn:I,notice:lI}),ws:`nfo`},reportRefusal:{body:KF,ws:`rx`},mentionResources:{body:nI,response:rI,ws:`mr`},records:{body:Vj,response:Hj,ws:`rq`},record:{body:Wj,response:S({record:zj.optional()}),ws:`rg`},recordTable:{body:Uj,response:jk,ws:`rtb`},saveRecord:{body:Gj,response:zj,ws:`rsv`},removeRecord:{body:qj,response:S({removed:b()}),ws:`rrm`},storeOpen:{body:S({}),response:S({bytes:y().int().min(0)}),ws:`sto`},storeRun:{body:FM,response:IM,ws:`stq`},storeBegin:{body:S({}),response:LM,ws:`stb`},storeCommit:{body:S({lease:MM}),ws:`stc`},storeRollback:{body:S({lease:MM}),ws:`str`},storeSnapshot:{body:S({}),response:S({snapshot:RM}),ws:`stn`},storeRestore:{body:S({snapshot:RM}),ws:`stx`},storeStatus:{body:yM,ws:`sts`},storeExport:{body:S({move:wM}),response:S({bytes:y().int().min(0),hash:v().regex(/^[0-9a-f]{64}$/)}),ws:`ste`},storeDownload:{body:S({move:wM,offset:y().int().min(0),length:y().int().min(1).max(4e6)}),response:S({chunk:v()}),ws:`std`},storeUpload:{body:S({move:wM,offset:y().int().min(0),chunk:v().max(6e6)}),ws:`stu`},storeUploadDone:{body:S({move:wM,bytes:y().int().min(0),hash:v().regex(/^[0-9a-f]{64}$/)}),ws:`stud`},storeMoveProgress:{body:S({move:wM,progress:OM}),ws:`stmp`}});Y({endpoints:{...X(uR).group({hello:{body:rR,response:iR,ws:`hi`},prove:{body:aR,response:cR,ws:`pr`},pairingInfo:{body:FP,ws:`pi`}}),...bR}}),Y({endpoints:{paired:Tw({body:S({pairing:fl}),ws:`pd`}),run:Tw({body:fR,response:dE,ws:`run`}),control:Tw({body:gR,response:_R,ws:`ctl`}),undo:Tw({body:S({run:zT,fn:v(),kind:Nl,fnPayload:O.optional(),payload:O}),response:pE,ws:`un`}),handler:Tw({body:S({call:ul,run:A,key:v(),handler:v(),args:O}),response:mE,ws:`hd`}),child:Tw({body:S({parent:A,key:v(),run:A,update:uE.optional()}),ws:`ch`}),check:Tw({body:S({kind:v(),payload:O}),response:S({problems:x(v()),description:AN.optional()}),ws:`ck`}),context:Tw({body:mR.partial({session:!0}).extend({name:v(),args:T(v(),v())}),response:S({text:v()}),ws:`cx`}),roots:Tw({response:x(Ax),ws:`ro`}),list:Tw({body:S({uri:Tx,cursor:v().optional()}),response:Bl(jx),ws:`ls`}),stat:Tw({body:S({uri:Tx}),response:S({stat:jx.optional()}),ws:`sa`}),read:Tw({body:S({uri:Tx,want:x(Nx)}),response:Fx,ws:`rd`}),sections:Tw({body:S({sectioner:v(),uri:Tx,version:v()}),response:x(Rx),ws:`sc`}),watch:Tw({body:S({uris:x(Tx),on:b()}),ws:`wa`}),content:Tw({body:S({ref:kx,offset:y().int().min(0),length:y().int().min(1)}),response:S({chunk:v()}),ws:`ct`}),hook:Tw({body:S({hook:v(),message:NN}),response:x(LN),ws:`hk`}),mentions:Tw({body:mR.extend({provider:v(),query:v(),request:tI}),response:x(RN),ws:`mn`}),mentionHover:Tw({body:mR.extend({provider:v(),target:O}),response:S({hover:zN.optional()}),ws:`mh`}),mentionText:Tw({body:mR.extend({provider:v(),target:O}),response:S({text:v()}),ws:`mt`}),event:Tw({body:nR,ws:`ev`}),action:Tw({body:mR.extend({delivery:ll,action:v(),input:O,run:A.optional()}),response:S({result:O}),ws:`ac`}),form:Tw({body:S({delivery:ll,run:A,value:O}),ws:`fm`}),restart:Tw({body:S({reason:v()}),ws:`rt`}),stop:Tw({body:S({reason:vR,timeout:jl}),ws:`sp`}),configure:Tw({body:sR.extend({previous:O.optional()}),ws:`cf`}),export:Tw({body:S({timeout:jl}),response:S({data:v()}),ws:`ex`}),validate:Tw({body:ZO,response:QO,ws:`vl`}),preview:Tw({body:Jk,response:$F,ws:`pv`}),estimate:Tw({body:SF,response:CF,ws:`es`}),providerChat:Tw({body:IO,streamOut:LO,ws:`pc`}),providerEmbed:Tw({body:GO,response:KO,ws:`pe`}),providerDecide:Tw({body:VO,response:HO,ws:`pdc`}),providerModels:Tw({body:zO,response:BO,ws:`pml`}),connectStart:Tw({body:DO,response:S({url:mb}),ws:`cs`}),connectFinish:Tw({body:OO,response:kO,ws:`cn`}),disconnect:Tw({body:EO.pick({id:!0,owner:!0,credentials:!0}),ws:`dc`}),flags:Tw({body:Jk,response:Vk,ws:`fg`}),claims:Tw({body:VM,response:HM,ws:`pcl`}),checkArgs:Tw({body:Yk,response:Xk,ws:`cka`}),storeProbe:Tw({body:S({to:uM}),response:S({problems:x(v())}),ws:`spb`}),storeMove:Tw({body:S({move:wM,from:uM,to:uM}),response:S({tables:y().int().min(0),rows:y().int().min(0),bytes:y().int().min(0)}),ws:`smv`}),storeMoveEnd:Tw({body:S({move:wM,outcome:E([`switched`,`aborted`]),from:uM,to:uM}),response:S({backups:x(S({id:SM,bytes:y().int().min(0)}))}),ws:`sme`}),storeDiscard:Tw({body:w(`what`,[S({what:D(`store`)}),S({what:D(`backup`),backup:SM})]),ws:`sdc`})}});var xR=S({session:j,parts:x(qL).min(1),variants:VA,client:BT}),SR=UA.extend({status:tj,spent:P,tokens:y().int().min(0),startedAt:N,endedAt:N.optional(),time:jl,messages:x(JL),approvals:x(NI)}),CR=qA.omit({variants:!0}).extend({turn:sl,session:j,message:cl,status:tj,variants:x(SR)}),wR=S({turn:sl,variant:RA,adopt:b().optional()}),TR=v().regex(Ml).max(64).brand(),ER=S({uri:v(),system:F.optional(),instance:L.optional()}),DR=S({systems:x(F).optional(),fns:x(OI).optional(),types:x(ql).optional(),context:x(ql).optional(),resources:x(ER).optional()}),OR=S({include:DR,exclude:DR}),kR=E([`each`,`static`]),AR=S({id:Ol,slug:TR,name:v().min(1),instructions:v(),rules:OR,toolMode:kR,user:M,actor:M,secretDigest:v(),grantees:x(F),origins:x(v()),enabled:b(),createdBy:M,createdAt:N,updatedAt:N}),jR=AR.pick({slug:!0,name:!0,instructions:!0,rules:!0,toolMode:!0,user:!0,grantees:!0,origins:!0,enabled:!0});S({mcp:Ol,label:v().min(1),exp:y().int()});var MR=S({mcp:Ol,label:v().min(1),ttl:y().int().min(1e3).optional()}),NR=S({fns:x(I),types:x(I),closure:x(I),context:x(I),resources:x(ER),reach:x(I),warnings:x(v())}),PR=S({mcp:Ol,session:v(),label:v(),client:S({name:v(),version:v()}).optional(),since:N,lastCallAt:N.optional(),calls:y().int().min(0)}),FR=AR.omit({secretDigest:!0}).extend({url:v(),sessions:y().int().min(0),callsToday:y().int().min(0)}),IR=E([`added`,`changed`,`removed`]),LR=S({id:v().min(1),system:F,section:NF,name:v().min(1),number:y().int().min(1),change:IR,decl:O,hash:v().min(1),declaredBy:fP.optional(),instance:L.optional(),savedBy:M.optional(),savedAt:N}),RR=Vl.extend({system:F,section:NF,name:v().min(1)}),zR=Bl(LR);Rx.extend({uri:Tx,version:v(),hash:v()});var BR=(...e)=>e.join(`\0`),VR=`bearerAuth`,HR={security:{[VR]:{type:`http`,scheme:`bearer`,bearerFormat:`JWT`}}};function UR(e){let t=e?.name??VR,n=e?.doc??HR;return Iw(t,{provides:Aw(),requires:e?.requires??[],doc:n})}var WR=v().regex(/^[a-z]+:.+$/),GR=S({fnKind:Nl.optional(),mode:nN.optional(),effects:x(oN).optional(),reads:x(I).optional(),writes:x(I).optional(),visibility:Rl.optional(),on:b(),stage:pk.optional(),pending:b().optional(),examples:y().int().min(0).optional()}),KR=S({id:WR,kind:lj,name:v().min(1),about:v(),system:F.optional(),external:b(),collapsed:y().int().min(0).optional(),facts:GR}),qR=S({from:WR,to:WR,kind:dj,label:v().min(1),weight:y().min(0).max(1).optional()}),JR=S({node:WR,kind:lj,count:y().int().min(1)}),YR=xj.pick({text:!0,filters:!0}).extend({systems:x(F).min(1).optional(),external:b().optional(),focus:S({node:WR,hops:y().int().min(1).max(4).optional()}).optional(),collapse:x(F).min(1).optional(),limit:y().int().min(1).max(1e3).optional()}),XR=S({nodes:x(KR),edges:x(qR),more:x(JR),total:S({nodes:y().int().min(0),edges:y().int().min(0)})}),ZR=`hub/visuals`,QR=S({columns:x(S({name:v().min(1),kind:hk,role:gk,numeric:b(),temporal:b(),day:b(),categorical:b(),key:b(),opaque:b(),distinct:y().int().min(0),nulls:y().min(0).max(1),nonNegative:b(),min:C([y(),v()]).optional(),max:C([y(),v()]).optional(),bound:S({min:y(),max:y()}).optional(),members:x(v()).optional()})),rows:y().int().min(0),whole:b()}),$R=new Set([`integer`,`number`]),ez=new Set([`date`,`datetime`]),tz=new Set([`text`,`boolean`]),nz=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function rz(e){return $R.has(e)?`measure`:ez.has(e)||tz.has(e)?`group`:`attribute`}function iz(e,t,n){return e===void 0||typeof e==typeof t&&(n===`min`?t<e:t>e)?t:e}function az(e,t){return{columns:e.columns.map((n,r)=>{let i=new Set,a=0,o=0,s=0,c=!0,l,u;for(let t of e.rows){let e=t[r];e==null?a+=1:(s+=1,i.add(typeof e==`object`?JSON.stringify(e):String(e)),typeof e==`string`&&nz.test(e)&&(o+=1),(typeof e==`number`||typeof e==`string`)&&(l=iz(l,e,`min`),u=iz(u,e,`max`)),(typeof e!=`number`||e<0)&&(c=!1))}let d=n.kind,f=n.key===!0,p=d===`uuid`||s>0&&o===s||n.ref!==void 0||d===`binary`;return{name:n.name,kind:d,role:n.role??rz(d),numeric:$R.has(d),temporal:ez.has(d),day:d===`date`,categorical:tz.has(d),key:f,opaque:p,distinct:i.size,nulls:e.rows.length===0?0:a/e.rows.length,nonNegative:c&&s>0,...l===void 0?{}:{min:l},...u===void 0?{}:{max:u},...t?.(n)??{}}}),rows:e.rows.length,whole:e.offset===0&&!e.truncated}}var oz=T(k,x(v().min(1)).min(1));S({visual:k,coverage:y().int().min(0),priority:y(),bind:oz,styles:x(k).min(1),because:x(v())});var sz={floor:0,structural:10,encoded:20,"time-encoded":30},cz={"temporal-key":15,"low-cardinality":10,"enum-key":8,"high-null":-10,"many-categories":-10},lz=.5;function uz(e){return e.columns.filter(e=>!e.opaque)}function dz(e,t){return e.accepts.includes(t.kind)&&(e.role===void 0||e.role===t.role)}function fz(e,t,n){return!e.required&&e.role===`group`&&n>1&&t.distinct>=n}function pz(e,t,n){let r={},i=new Set;for(let a of e.channels){let e=t.filter(e=>!i.has(e.name)&&dz(a,e)&&!fz(a,e,n)).map(e=>e.name),o=a.many?e:e.slice(0,1);if(o.length<(a.many?a.min??1:1)){if(a.required)return`No column fits ${a.label} (${a.accepts.join(`, `)}).`;continue}let[s,...c]=o;if(s!==void 0){r[a.name]=[s,...c];for(let e of o)i.add(e)}}return r}function mz(e,t,n){return(e[t]??[]).flatMap(e=>n.columns.filter(t=>t.name===e))}function hz(e,t,n,r,i){switch(e.rule){case`distinct`:return mz(t,e.channel,n).some(t=>t.distinct>e.max)?`${e.channel} has more than ${String(e.max)} values.`:void 0;case`non-negative`:return mz(t,e.channel,n).every(e=>e.nonNegative)?void 0:`${e.channel} has values below 0.`;case`bounded`:return mz(t,e.channel,n).every(e=>e.bound!==void 0)||t.max!==void 0?void 0:`${e.channel} has no known range.`;case`distinct-columns`:{let n=e.channels.flatMap(e=>t[e]??[]);return new Set(n).size===n.length?void 0:`${e.channels.join(` and `)} need different columns.`}case`links`:{if(r===void 0||i===void 0)return;let n=e=>i.findIndex(n=>n.name===t[e]?.[0]),a=n(e.from),o=n(e.to);if(a<0||o<0)return`${e.to} must name values of ${e.from}.`;let s=new Set(r.map(e=>JSON.stringify(e[a]??null)));return r.every(e=>e[o]===null||s.has(JSON.stringify(e[o]??null)))?void 0:`${e.to} names values that are not ${e.from} values.`}}}function gz(e,t,n){let r=Object.values(t).flat().flatMap(e=>n.columns.filter(t=>t.name===e)),i=r.filter(e=>e.role===`group`),a={"temporal-key":i.some(e=>e.temporal),"low-cardinality":i.length>0&&i.every(e=>e.distinct<=8),"enum-key":i.some(e=>e.members!==void 0),"high-null":r.some(e=>e.nulls>lz),"many-categories":i.some(e=>e.distinct>5)},o=e.priority.terms.filter(e=>a[e]);return{priority:sz[e.priority.band]+o.reduce((e,t)=>e+cz[t],0),because:o.map(e=>`${e} (${String(cz[e])})`)}}function _z(e,t,n){return e.styles.filter(e=>(e.whole!==!0||n)&&(e.needs??[]).every(e=>t[e]!==void 0)).map(e=>e.name)}function vz(e,t,n,r){let i=[];for(let r of e.channels){let e=t[r.name]??[];if(e.length===0)r.required&&i.push(`${r.label} is not bound.`);else{!r.many&&e.length>1&&i.push(`${r.label} takes one column.`),r.many&&e.length<(r.min??1)&&i.push(`${r.label} needs at least ${String(r.min??1)} columns.`);for(let t of e){let e=n.columns.find(e=>e.name===t);e===void 0?i.push(`${r.label}: there is no column ${t}.`):(e.opaque&&i.push(`${r.label}: ${t} holds nothing a person reads.`),r.accepts.includes(e.kind)||i.push(`${r.label}: ${t} is ${e.kind}, not ${r.accepts.join(` or `)}.`))}}}n.rows<e.rows.min&&i.push(`Needs at least ${String(e.rows.min)} rows.`),e.rows.max!==void 0&&n.rows>e.rows.max&&e.size===void 0&&i.push(`Draws at most ${String(e.rows.max)} rows.`),e.whole&&!n.whole&&i.push(`Only draws a whole result, and this is one page of it.`);for(let a of e.rules){let e=hz(a,t,n,r?.rows,r?.columns);e!==void 0&&i.push(e)}return i}function yz(e,t,n){let r=uz(t);return e.flatMap((e,i)=>{let a=pz(e.shape,r.length>0?r:t.columns,t.rows);if(typeof a==`string`||vz(e.shape,a,t,n).length>0)return[];let[o,...s]=_z(e.shape,a,t.whole);if(o===void 0)return[];let{priority:c,because:l}=gz(e.shape,a,t),u=new Set(Object.values(a).flat().filter(e=>r.some(t=>t.name===e))).size;return[{rank:{visual:e.name,coverage:u,priority:c,bind:a,styles:[o,...s],because:[`covers ${String(u)}`,...l]},index:i}]}).sort((e,t)=>t.rank.coverage-e.rank.coverage||t.rank.priority-e.rank.priority||e.index-t.index).map(e=>e.rank)}var bz=[`integer`,`number`],xz=[`date`,`datetime`],Sz=[`text`,`boolean`],Cz=[`text`,`boolean`,`date`,`datetime`];function wz(e,t,n,r={}){return{name:e,label:t,accepts:[...n],required:r.required??!0,many:r.many??!1,...r.min===void 0?{}:{min:r.min},...r.role===void 0?{}:{role:r.role}}}var Tz=[`table`,`value`,`part`,`category`,`time`,`distribution`,`crosstab`,`calendar`,`timeline`,`network`,`hierarchy`,`gauge`,`finance`];E(Tz);var Ez={table:{label:`Table`,icon:`table`,description:`Every readable column and row, sortable and paged; cards on a phone.`,shape:wk.parse({channels:[wz(`columns`,`Columns`,mk,{required:!1,many:!0})],rows:{min:0},whole:!1,size:`window`,pageSize:10,styles:[{name:`table`,label:`Table`},{name:`compact`,label:`Compact`},{name:`cards`,label:`Cards`}],priority:{band:`floor`,terms:[]}})},value:{label:`Value`,icon:`hash`,description:`One to four rows of numbers as cards, each titled by a text column or named by its column.`,shape:wk.parse({channels:[wz(`value`,`Values`,bz,{many:!0,role:`measure`}),wz(`title`,`Title`,[`text`],{required:!1})],rows:{min:1,max:4},whole:!0,styles:[{name:`cards`,label:`Cards`},{name:`single`,label:`Single`}],priority:{band:`encoded`,terms:[]}})},part:{label:`Part of a whole`,icon:`chart`,description:`Slices of a whole: one per category, sized by a measure.`,shape:wk.parse({channels:[wz(`itemName`,`Slice`,Cz,{role:`group`}),wz(`value`,`Size`,bz,{role:`measure`})],rows:{min:1,max:100},whole:!0,size:`partition`,rules:[{rule:`non-negative`,channel:`value`}],styles:[{name:`pie`,label:`Pie`},{name:`doughnut`,label:`Doughnut`},{name:`rose`,label:`Rose`},{name:`half`,label:`Half doughnut`},{name:`funnel`,label:`Funnel`}],priority:{band:`encoded`,terms:[`low-cardinality`,`enum-key`,`many-categories`]}})},category:{label:`Bars`,icon:`chart`,description:`Measures per category, with an optional second key as series.`,shape:wk.parse({channels:[wz(`x`,`Category`,Cz,{role:`group`}),wz(`y`,`Values`,bz,{many:!0,role:`measure`}),wz(`series`,`Series`,Sz,{required:!1,role:`group`})],rows:{min:1,max:50},whole:!1,size:`top-n`,styles:[{name:`bar`,label:`Bars`},{name:`stacked`,label:`Stacked`},{name:`percent`,label:`100%`,whole:!0},{name:`horizontal`,label:`Horizontal`},{name:`line`,label:`Line`},{name:`area`,label:`Area`},{name:`radar`,label:`Radar`},{name:`polar`,label:`Polar bars`},{name:`pictorial`,label:`Pictorial`}],priority:{band:`encoded`,terms:[`low-cardinality`,`enum-key`,`high-null`]}})},time:{label:`Over time`,icon:`chart`,description:`Measures along a date axis, zoomable; zooming can set the from/to args.`,shape:wk.parse({channels:[wz(`x`,`Date`,xz,{role:`group`}),wz(`y`,`Values`,bz,{many:!0,role:`measure`}),wz(`series`,`Series`,Sz,{required:!1,role:`group`})],rows:{min:2},whole:!1,size:`window`,claims:[{claim:`range`,channel:`x`}],styles:[{name:`line`,label:`Line`},{name:`smooth`,label:`Smooth`},{name:`area`,label:`Area`},{name:`stacked`,label:`Stacked area`},{name:`step`,label:`Step`},{name:`bar`,label:`Bars`},{name:`river`,label:`Stream`,needs:[`series`]}],priority:{band:`time-encoded`,terms:[`temporal-key`,`high-null`]}})},distribution:{label:`Distribution`,icon:`chart`,description:`How numbers spread: points, bubbles, bins, boxes or parallel axes.`,shape:wk.parse({channels:[wz(`x`,`X`,bz),wz(`y`,`Y`,bz,{required:!1}),wz(`size`,`Size`,bz,{required:!1}),wz(`group`,`Group`,Sz,{required:!1}),wz(`dims`,`More axes`,bz,{required:!1,many:!0,min:1})],rows:{min:2,max:5e3},whole:!1,styles:[{name:`scatter`,label:`Points`,needs:[`y`]},{name:`bubble`,label:`Bubbles`,needs:[`y`,`size`]},{name:`pulse`,label:`Rippling points`,needs:[`y`]},{name:`histogram`,label:`Histogram`,whole:!0},{name:`boxplot`,label:`Box plot`,whole:!0},{name:`parallel`,label:`Parallel axes`,needs:[`y`,`dims`]}],priority:{band:`structural`,terms:[`high-null`]}})},crosstab:{label:`Cross-tab`,icon:`grid`,description:`A measure for each pair of two keys: a heatmap, value cells or small charts.`,shape:wk.parse({channels:[wz(`x`,`Columns`,Cz,{role:`group`}),wz(`y`,`Rows`,Cz,{role:`group`}),wz(`value`,`Value`,bz,{role:`measure`})],rows:{min:2},whole:!1,size:`top-n`,rules:[{rule:`distinct-columns`,channels:[`x`,`y`]},{rule:`distinct`,channel:`x`,max:50},{rule:`distinct`,channel:`y`,max:50}],styles:[{name:`heatmap`,label:`Heatmap`},{name:`cells`,label:`Value cells`},{name:`multiples`,label:`Small charts`}],priority:{band:`encoded`,terms:[`low-cardinality`]}})},calendar:{label:`Calendar`,icon:`calendar`,description:`Days on a calendar, shaded by a measure; the month shown can set the from/to args.`,shape:wk.parse({channels:[wz(`time`,`Date`,xz,{role:`group`}),wz(`value`,`Intensity`,bz,{required:!1,role:`measure`}),wz(`label`,`Label`,Sz,{required:!1})],rows:{min:1},whole:!1,claims:[{claim:`range`,channel:`time`}],styles:[{name:`month`,label:`Month`},{name:`year`,label:`Year`}],priority:{band:`structural`,terms:[`temporal-key`]}})},timeline:{label:`Timeline`,icon:`calendar`,description:`Bars from a start to an end date, one row each: a gantt chart.`,shape:wk.parse({channels:[wz(`start`,`Start`,xz),wz(`end`,`End`,xz),wz(`label`,`Label`,Sz),wz(`series`,`Lane`,Sz,{required:!1})],rows:{min:1,max:500},whole:!1,size:`window`,rules:[{rule:`distinct-columns`,channels:[`start`,`end`]}],claims:[{claim:`range`,channel:`start`}],styles:[{name:`gantt`,label:`Gantt`},{name:`timeline`,label:`Timeline`}],priority:{band:`time-encoded`,terms:[]}})},network:{label:`Network`,icon:`graph`,description:`Links between things: each row is an edge from a source to a target.`,shape:wk.parse({channels:[wz(`source`,`From`,Sz),wz(`target`,`To`,Sz),wz(`value`,`Weight`,bz,{required:!1,role:`measure`})],rows:{min:1,max:2e3},whole:!0,rules:[{rule:`distinct-columns`,channels:[`source`,`target`]}],styles:[{name:`force`,label:`Graph`},{name:`circular`,label:`Circle`},{name:`sankey`,label:`Flow`},{name:`chord`,label:`Chord`}],priority:{band:`structural`,terms:[]}})},hierarchy:{label:`Hierarchy`,icon:`tree`,description:`A tree from a name and its parent column, sized by a measure.`,shape:wk.parse({channels:[wz(`name`,`Name`,Sz),wz(`parent`,`Parent`,Sz),wz(`value`,`Size`,bz,{required:!1,role:`measure`})],rows:{min:2,max:5e3},whole:!0,rules:[{rule:`distinct-columns`,channels:[`name`,`parent`]},{rule:`links`,from:`name`,to:`parent`}],styles:[{name:`tree`,label:`Tree`},{name:`radial`,label:`Radial tree`},{name:`treemap`,label:`Treemap`},{name:`sunburst`,label:`Sunburst`}],priority:{band:`structural`,terms:[]}})},gauge:{label:`Gauge`,icon:`gauge`,description:`One value against its known range.`,shape:wk.parse({channels:[wz(`value`,`Value`,bz,{role:`measure`}),wz(`max`,`Maximum`,bz,{required:!1})],rows:{min:1,max:1},whole:!0,rules:[{rule:`bounded`,channel:`value`}],styles:[{name:`gauge`,label:`Gauge`},{name:`progress`,label:`Progress ring`}],priority:{band:`encoded`,terms:[]}})},finance:{label:`Candlestick`,icon:`chart`,description:`Open, high, low and close per period, with optional volume.`,shape:wk.parse({channels:[wz(`x`,`Period`,Cz,{role:`group`}),wz(`open`,`Open`,bz),wz(`close`,`Close`,bz),wz(`low`,`Low`,bz),wz(`high`,`High`,bz),wz(`volume`,`Volume`,bz,{required:!1})],rows:{min:2},whole:!1,size:`window`,claims:[{claim:`range`,channel:`x`}],styles:[{name:`candlestick`,label:`Candles`},{name:`volume`,label:`Candles and volume`,needs:[`volume`]}],priority:{band:`time-encoded`,terms:[`temporal-key`]}})}};Tz.map(e=>({name:e,shape:Ez[e].shape}));var Dz=`widgets`,Oz=`widgets/widget`,kz=[`today`,`today-1d`,`today+1d`,`today-7d`,`today-30d`,`today+7d`,`startOf(week)`,`endOf(week)`,`startOf(month)`,`endOf(month)`,`startOf(month,today-1mo)`,`startOf(quarter)`,`startOf(year)`,`now`,`now-1h`,`now-24h`],Az=E(kz),jz={today:{label:`Today`,yields:`day`},"today-1d":{label:`Yesterday`,yields:`day`},"today+1d":{label:`Tomorrow`,yields:`day`},"today-7d":{label:`7 days ago`,yields:`day`},"today-30d":{label:`30 days ago`,yields:`day`},"today+7d":{label:`In 7 days`,yields:`day`},"startOf(week)":{label:`Start of this week`,yields:`day`},"endOf(week)":{label:`End of this week`,yields:`day`},"startOf(month)":{label:`Start of this month`,yields:`day`},"endOf(month)":{label:`End of this month`,yields:`day`},"startOf(month,today-1mo)":{label:`Start of last month`,yields:`day`},"startOf(quarter)":{label:`Start of this quarter`,yields:`day`},"startOf(year)":{label:`Start of this year`,yields:`day`},now:{label:`Now`,yields:`instant`},"now-1h":{label:`An hour ago`,yields:`instant`},"now-24h":{label:`24 hours ago`,yields:`instant`}},Mz=C([S({literal:O}),S({relative:Az})]),Nz=S({label:v().min(1),value:Mz.optional()}),Pz=w(`show`,[S({show:D(`control`),label:v().min(1).optional(),choices:x(Nz).min(1).optional(),custom:b().optional(),default:Mz.optional()}),S({show:D(`pinned`),value:Mz}),S({show:D(`hidden`)})]),Fz=S({label:v().min(1),sets:T(k,Mz)}),Iz=S({from:k,to:k}),Lz=S({offset:k,limit:k}),Rz=S({visual:k,style:k,label:v().min(1).optional(),bind:oz}),zz=E([`open`,`refresh`,`status`]),Bz=S({fn:I,label:v().min(1).optional(),confirm:D(!0).optional(),bind:T(k,v().min(1)),then:zz.optional()}),Vz=S({fn:I,label:v().min(1),bind:T(k,v().min(1))}),Hz=S({title:v().min(1),source:I,visuals:x(Rz).min(1),args:T(k,Pz),presets:x(Fz),range:Iz.optional(),paging:Lz.optional(),actions:x(Bz).optional(),drill:Vz.optional(),live:D(!0).optional()}),Uz=S({arg:k,label:v().min(1),argType:Z,optional:b(),defaulted:b().optional(),choices:x(Nz).min(1).optional(),custom:b(),relative:b(),value:Mz.optional()}),Wz=S({offset:k,limit:k,window:y().int().min(1),more:b()}),Gz=S({fn:I,label:v().min(1),mode:nN,confirm:b(),bind:T(k,v().min(1)),form:Z.optional(),then:zz}),Kz=S({title:v().min(1),table:jk,facts:QR,source:S({fn:I,run:A,args:T(v(),O)}),visuals:x(Rz).min(1),problems:x(v()),controls:x(Uz),presets:x(Fz),range:Iz.optional(),paging:Wz.optional(),actions:x(Gz),drill:Vz.optional(),readOnly:b(),live:S({every:y().int().min(1)}).optional(),summary:v().min(1)}),qz=S({types:x(I).max(20),narrow:x(Bz).optional()}).refine(e=>e.types.length>0||(e.narrow?.length??0)>0,{message:`name a row type or an action to offer`}),Jz=S({fn:I,args:T(v(),O)}),Yz=Jz.extend({on:L.optional()});S({source:ub,request:v().min(1),args:T(v(),O).optional(),fns:x(ub).max(10).optional(),widget:ub.optional(),show:b()});var Xz=S({name:k,description:v().min(1),spec:Hz,preview:Kz,replaces:ub.optional(),show:b()});S({name:k,description:v().min(1),spec:Hz,replace:I.optional()});var Zz=S({fn:I,args:v(),offset:k,limit:k,format:D(`csv`)});S({summary:v(),columns:x(v()),rows:x(x(O)),more:y().int().min(0),partial:v().optional()});function Qz(e,t){return e!==`read`||t===!0}function $z(e,t){return t?`open`:e===`read`?`status`:`refresh`}function eB(e){return aT(e.split(/[/.]/).pop()??e)||e}var Q=TP(),$=UR(),tB=Iw(`adminOnly`,{requires:[$]}),nB=S({access:v(),refresh:v(),expiresIn:jl,user:TI}),rB=pI.pick({name:!0,version:!0}).extend({needsAdmin:b(),sso:x(GI)}),iB=S({kind:E([`fn`,`context`]),name:I,description:v(),score:PN,why:v().optional()}),aB=gA(v().min(1)),oB=S({approvals:x(NI),handlers:x(ej)}),sB=NP.omit({publicKey:!0}),cB=S({fns:y().int().min(0),context:y().int().min(0),types:y().int().min(0),parts:y().int().min(0),instances:y().int().min(0),pending:y().int().min(0),refusals:y().int().min(0)}),lB=lP.omit({keyFingerprint:!0,publicKey:!0,config:!0,pairedAt:!0,pairedBy:!0,lastSeenAt:!0,address:!0,instances:!0}).extend(NP.pick({keyFingerprint:!0,config:!0,installed:!0,host:!0,pairedAt:!0,pairedBy:!0,lastSeenAt:!0,address:!0}).shape).extend({counts:cB,instanceMode:cP,needsConfig:b(),configType:O.optional(),configSecrets:iA.optional(),store:rM.optional(),instances:x(sB)}),uB=w(`type`,[S({type:D(`message`),message:JL}),S({type:D(`token`),message:cl,text:v()}),S({type:D(`reasoning`),message:cl,text:v()}),S({type:D(`cite`),message:cl,cite:PA}),S({type:D(`controls`),controls:ZL}),S({type:D(`run`),run:A,fn:I,update:uE}),S({type:D(`state`),system:F,fields:x(ZA)}),S({type:D(`delivery`),delivery:$A}),S({type:D(`handler`),call:ej}),S({type:D(`approval`),approval:NI}),S({type:D(`budget`),run:A,budget:CA,reason:v()}),S({type:D(`presence`),presence:QL}),S({type:D(`session`),session:FL}),S({type:D(`compare`),turn:sl})]),dB=w(`type`,[S({type:D(`notification`),notification:eF}),S({type:D(`approval`),approval:NI}),S({type:D(`system`),system:F,status:eP}),S({type:D(`pairing`),pairing:uP}),S({type:D(`capabilities`)}),S({type:D(`session`),session:FL}),S({type:D(`session-deleted`),session:j}),S({type:D(`fn`),fn:I,system:F,stats:dP}),S({type:D(`resource`),uri:Tx,forms:x(Lx)}),S({type:D(`context`),name:I}),S({type:D(`identity`),identity:pI})]),fB=Rw(Y({endpoints:X(Q).group({setup:{method:`GET`,response:rB,ws:`setup`},createAdmin:{body:S({email:Ns(),name:v().min(1),password:v().min(8),setup:v().trim().min(1)}),response:nB,ws:`createAdmin`},signIn:{body:S({email:Ns(),password:v()}),response:nB,errors:{401:S({reason:v()})},ws:`signIn`},refresh:{body:S({refresh:v()}),response:nB,ws:`refresh`},redeemSso:{body:S({code:v().min(1)}),cookies:S({[iL]:v().optional()}),response:nB,ws:`redeemSso`,httpOnly:!0}})}),Y({endpoints:X(Q,$).group({signOut:{ws:`signOut`},me:{method:`GET`,response:TI,ws:`me`},account:{method:`GET`,response:$I,ws:`account`}})})),pB=Vl.extend({query:xj.optional()}),mB=Vl.extend({session:j}),hB=Vl.extend({unread:b().optional(),query:xj.optional()}),gB=PL.pick({title:!0,systems:!0,agent:!0,archived:!0}).partial().extend({priority:Ll.optional(),notify:AL.optional(),model:PL.shape.model.unwrap().nullable().optional(),mode:PL.shape.mode.unwrap().nullable().optional(),contextor:PL.shape.contextor.unwrap().nullable().optional(),fnMode:PL.shape.fnMode.unwrap().nullable().optional(),instructions:PL.shape.instructions.unwrap().nullable().optional(),citations:PL.shape.citations}),_B=Y({endpoints:X(Q,$).group({capabilities:{body:S({session:j.optional()}),response:$L,ws:`capabilities`},types:{body:S({names:x(I).min(1)}),response:hP,ws:`types`},sessions:{body:pB,response:Bl(FL),ws:`sessions`},session:{body:S({session:j}),response:PL,ws:`session`},createSession:{body:PL.pick({agent:!0,systems:!0,title:!0}).partial(),response:PL,ws:`createSession`},updateSession:{body:gB.extend({session:j}),response:PL,ws:`updateSession`},deleteSession:{body:S({session:j}),response:S({deleted:b()}),ws:`deleteSession`},limits:{body:S({session:j}),response:TA,ws:`limits`},messages:{body:mB,response:Bl(JL),ws:`messages`},send:{body:S({session:j,parts:x(qL).min(1),replyTo:cl.optional(),replyAll:b().optional(),client:BT}),response:S({turn:sl,message:JL}),ws:`send`},compare:{body:xR,response:S({turn:sl,message:JL}),ws:`compare`},compareView:{body:S({turn:sl}),response:CR,ws:`compareView`},chooseVariant:{body:wR,response:CR,ws:`chooseVariant`},invoke:{body:S({session:j,fn:I,args:O,on:L.optional(),client:BT}),response:S({turn:sl,run:A}),ws:`invoke`},control:{body:S({session:j,action:YL,runs:x(A).min(1).optional()}),response:ZL,ws:`control`},controls:{body:S({session:j}),response:ZL,ws:`controls`},presence:{body:QL.omit({user:!0,lastActiveAt:!0}),ws:`presence`}})}),vB=Y({endpoints:X(Q,$).group({background:{body:S({run:A}),response:S({accepted:b()}),ws:`background`},undoTurn:{body:S({turn:sl}),response:sj,ws:`undoTurn`},continueTurn:{body:S({turn:sl}),response:S({turn:sl,run:A}),ws:`continueTurn`},tree:{body:S({turn:sl}),response:oj,ws:`tree`},run:{body:S({run:A}),response:YA,ws:`run`},llmCall:{body:S({id:dl}),response:aj,ws:`llmCall`},waiting:{body:S({session:j}),response:oB,ws:`waiting`},approve:{body:S({approval:hl,approve:b(),remember:MI,reason:v().optional(),answer:O.optional()}),response:NI,ws:`approve`},answer:{body:S({call:ul,value:O}),ws:`answer`},act:{body:S({session:j,system:F,action:v(),input:O,run:A.optional(),client:BT}),response:S({delivery:ll}),ws:`act`},submit:{body:S({run:A,value:O}),response:S({delivery:ll}),ws:`submit`},state:{body:S({run:A}),response:S({system:F,fields:x(ZA)}),ws:`state`}})}),yB=Y({endpoints:X(Q,$).group({suggest:{body:S({session:j,text:v(),limit:y().int().min(1).max(20).optional()}),response:x(iB),ws:`suggest`},mentions:{body:S({session:j,provider:I,query:v()}),response:x(RN),ws:`mentions`},mentionHover:{body:S({session:j,provider:I,target:O}),response:S({hover:zN.optional()}),ws:`mentionHover`},resource:{body:S({uri:Tx,want:x(Nx)}),response:Fx,ws:`resource`}})}),bB=Y({endpoints:X(Q,$).group({notifications:{body:hB,response:Bl(eF),ws:`notifications`},readNotifications:{body:S({ids:x(eF.shape.id)}),ws:`readNotifications`},pushKey:{method:`GET`,response:S({publicKey:v()}),ws:`pushKey`},subscribePush:{body:tF.pick({endpoint:!0,keys:!0,device:!0}),response:tF.pick({id:!0}),ws:`subscribePush`}})}),xB=Y({endpoints:X(Q,$).group({upload:{body:S({name:v(),mime:v(),size:y().int().min(0)}),response:S({url:v(),upload:v()}),ws:`upload`},uploaded:{body:S({upload:v()}),response:kx,ws:`uploaded`},transcribe:{body:S({audio:kx}),response:S({text:v()}),ws:`transcribe`}})}),SB=S({section:E([`fns`,`context`]),name:I,on:b()}),CB=S({system:F,section:NF.exclude([`fns`,`context`]),name:v().min(1),on:b()}),wB=Y({endpoints:X(Q,$,tB).group({systems:{body:S({query:xj.optional()}),response:x(lB),ws:`systems`},system:{body:S({system:F}),response:lB,ws:`system`},pairings:{body:S({status:uP.shape.status.optional()}),response:x(uP),ws:`pairings`},approvePairing:{body:S({pairing:fl,approve:b(),instance:L.optional(),config:O.optional(),autoPair:XN.optional(),store:lM.optional()}),response:S({system:F.optional()}),ws:`approvePairing`},createPairingToken:{body:S({name:F.optional(),expiresIn:jl,autoPair:XN.optional()}),response:S({token:v(),expiresAt:N}),ws:`createPairingToken`},configureSystem:{body:S({system:F,config:O,instance:L.optional()}),response:C([S({version:y().int()}),S({problems:x(v())})]),ws:`configureSystem`},enableSystem:{body:S({system:F,functions:b().optional(),renderers:b().optional(),context:b().optional()}),response:S({enabled:aP}),ws:`enableSystem`},switchItem:{body:SB,response:S({on:b()}),ws:`switchItem`},switchPart:{body:CB,response:S({on:b()}),ws:`switchPart`},removeSystem:{body:S({system:F,keepStore:b().optional()}),response:S({fnsUnavailable:y().int()}),ws:`removeSystem`},installSystem:{body:S({source:tP,config:O.optional(),autoStart:b().optional(),store:lM.optional()}),response:S({name:F}),ws:`installSystem`},systemStore:{body:S({system:F,instance:L.optional()}),response:jM,ws:`systemStore`},systemStoreMove:{body:S({system:F,instance:L.optional(),to:lM,runs:EM.optional()}),response:kM,ws:`systemStoreMove`},systemStoreMoveState:{body:S({system:F,instance:L.optional()}),response:S({move:kM.optional()}),ws:`systemStoreMoveState`},systemStoreMoveAnswer:{body:S({system:F,instance:L.optional(),answer:DM}),response:kM,ws:`systemStoreMoveAnswer`},systemStoreBackups:{body:S({system:F,instance:L.optional()}),response:x(CM),ws:`systemStoreBackups`},systemStoreBackupDelete:{body:S({system:F,instance:L.optional(),backup:SM}),response:S({deleted:D(!0),note:v().optional()}),ws:`systemStoreBackupDelete`},startSystem:{body:S({system:F,instance:L.optional()}),response:S({ok:b()}),ws:`startSystem`},stopSystem:{body:S({system:F,instance:L.optional()}),response:S({ok:b()}),ws:`stopSystem`},restartSystem:{body:S({system:F,instance:L.optional(),reason:v().min(1).max(200)}),response:S({ok:b()}),ws:`restartSystem`},upgradeSystem:{body:S({system:F,version:v().optional()}),response:S({from:v(),to:v()}),ws:`upgradeSystem`},reimport:{body:S({system:F}),response:ON,ws:`reimport`}})}),TB=Y({endpoints:X(Q,$,tB).group({configureProvider:{body:aB,response:S({models:y().int()}),ws:`configureProvider`},providers:{body:S({}),response:x(S({id:wl,provider:vA,models:y().int()})),ws:`providers`},setModelCategory:{body:yA.partial({id:!0}),response:yA.pick({id:!0}),ws:`setModelCategory`},setBudget:{body:CA.omit({setBy:!0}).partial({id:!0}),response:CA.pick({id:!0}),ws:`setBudget`},setPriority:{body:wA.omit({setBy:!0}).partial({id:!0}),response:wA.pick({id:!0}),ws:`setPriority`},setPolicy:{body:jI.omit({createdBy:!0,createdAt:!0}).partial({id:!0}),response:jI.pick({id:!0}),ws:`setPolicy`},setActorSetting:{body:S({setting:I,actor:M,value:O}),response:S({ok:b()}),ws:`setActorSetting`},addUser:{body:S({email:Ns(),name:v(),role:SI,groups:x(M).optional()}),response:S({id:M}),ws:`addUser`},addGroup:{body:S({name:v(),about:v(),members:x(M).optional()}),response:S({id:M}),ws:`addGroup`},updateUser:{body:tL,response:S({id:M}),ws:`updateUser`},setMembership:{body:nL,response:S({ok:b()}),ws:`setMembership`},setSignInPolicy:{body:RI,response:RI,ws:`setSignInPolicy`},setSignInLimits:{body:VI,response:VI,ws:`setSignInLimits`},setProxyTrust:{body:UI,response:UI,ws:`setProxyTrust`}})}),EB=Y({endpoints:X(Q,$,tB).group({systemFns:{body:S({system:F}),response:x(pP),ws:`systemFns`},systemParts:{body:CP,response:wP,ws:`systemParts`},systemLogs:{body:S({system:F,limit:y().int().min(1).max(2e3).optional()}),response:x(LP),ws:`systemLogs`},models:{body:S({provider:wl.optional()}),response:x(BP),ws:`models`},modelCategories:{body:S({}),response:x(yA),ws:`modelCategories`},budgets:{body:S({}),response:x(HP),ws:`budgets`},priorityRules:{body:S({}),response:x(wA),ws:`priorityRules`},resolveLimits:{body:S({user:M,session:j.optional()}),response:TA,ws:`resolveLimits`},policies:{body:S({}),response:x(jI),ws:`policies`},actors:{body:S({kind:zl.optional()}),response:x(wI),ws:`actors`},actorSettings:{body:S({}),response:S({declared:x(UP),values:x(EI)}),ws:`actorSettings`},runs:{body:Vl.extend({query:xj.optional()}),response:Bl(YA),ws:`runs`},llmCalls:{body:Vl.extend({query:xj.optional()}),response:Bl(WP),ws:`llmCalls`},resources:{body:Vl.extend({query:xj.optional()}),response:Bl(KP),ws:`resources`},removeRule:{body:GP,response:S({ok:b()}),ws:`removeRule`},indexStatus:{body:S({}),response:RP,ws:`indexStatus`}}),events:{systemLog:{params:S({system:F}),data:LP,guard:[$,tB],ws:`on.systemLog`}}}),DB=Iw(`ownEvents`,{requires:[$]}),OB=Iw(`sessionWatch`,{requires:[$]}),kB=S({user:M}),AB=Y({endpoints:{},events:{session:{params:S({session:j}),data:uB,guard:[$,OB],ws:`on.session`},user:{params:kB,data:dB,guard:[$,DB],ws:`on.user`}}}),jB=Bl(KP).extend({facets:x(OE)}),MB=S({record:KP,forms:x(_E),offers:x(vE)}),NB=Y({endpoints:X(Q,$).group({browseResources:{body:kE.extend({query:xj.optional()}),response:jB,ws:`browseResources`},resourceForms:{body:S({uri:Tx}),response:MB,ws:`resourceForms`},readResource:{body:PE,response:FE,ws:`readResource`},convertResource:{body:S({uri:Tx,kind:Lx}),response:_E,ws:`convertResource`},downloadResource:{body:S({uri:Tx,form:Lx.optional()}),response:S({url:v(),mime:v(),size:y().int().min(0)}),ws:`downloadResource`},importResource:{body:IE,response:KP,ws:`importResource`},renameResource:{body:S({uri:Tx,name:v().min(1)}),response:KP,ws:`renameResource`},deleteResource:{body:S({uri:Tx}),response:S({deleted:b(),referencedBy:y().int().min(0)}),ws:`deleteResource`},contextFromResource:{body:fS,response:pS,ws:`contextFromResource`}})}),PB=Vl.extend({query:xj.optional()}),FB=S({record:_P,links:x(sS),backlinks:x(sS),text:v().optional()}),IB=Y({endpoints:X(Q,$).group({contexts:{body:PB,response:Bl(hF),ws:`contexts`},contextItem:{body:S({name:I}),response:FB,ws:`contextItem`},remember:{body:lS,response:S({name:I}),ws:`remember`},updateMemory:{body:dS,response:S({name:I}),ws:`updateMemory`},forget:{body:S({name:I}),response:S({ok:b()}),ws:`forget`},linkContext:{body:S({from:I,to:rS,relation:nS,weight:y().min(0).max(1)}),response:sS,ws:`linkContext`},unlinkContext:{body:sS.pick({from:!0,toKey:!0,relation:!0}),response:S({ok:b()}),ws:`unlinkContext`}})}),LB=Rw(Y({endpoints:X(Q,$).group({contextMetadata:{body:S({name:I}),response:GS,ws:`contextMetadata`},setContextStatus:{body:NS,response:PS,ws:`setContextStatus`}})}),Y({endpoints:X(Q,$,tB).group({contextReview:{body:LS,response:zS,ws:`contextReview`},mergeContext:{body:BS,response:VS,ws:`mergeContext`},notDuplicate:{body:HS,response:S({ok:b()}),ws:`notDuplicate`},reextractContext:{body:US,response:WS,ws:`reextractContext`},newContextStatus:{body:S({}),response:OS,ws:`newContextStatus`},setNewContextStatus:{body:S({value:DS}),response:OS,ws:`setNewContextStatus`}})})),RB=Y({endpoints:X(Q,$).group({contextPlans:{body:pC,response:mC,ws:`contextPlans`},contextPlan:{body:aC,response:oC,ws:`contextPlan`},answerPlan:{body:lC,response:uC,ws:`answerPlan`}})}),zB=Rw(Y({endpoints:X(Q,$).group({modelLimits:{body:S({model:v().optional()}),response:x(nx),ws:`modelLimits`},previewSelection:{body:S({session:j,text:v()}),response:sx,ws:`previewSelection`}})}),Y({endpoints:X(Q,$,tB).group({setModelLimits:{body:S({model:v().min(1),limits:Qb}),response:nx,ws:`setModelLimits`},previewPrompt:{body:cx,response:lx,ws:`previewPrompt`}})})),BB=Y({endpoints:X(Q,$,tB).group({modelRoles:{body:S({}),response:x(PD),ws:`modelRoles`},setModelRole:{body:MD,response:PD,ws:`setModelRole`},clearModelRole:{body:S({role:TD}),response:PD,ws:`clearModelRole`}})}),VB=Vl.extend({run:A.optional(),query:xj.optional()}),HB=Y({endpoints:X(Q,$,tB).group({modelCalls:{body:VB,response:Bl(SD),ws:`modelCalls`},modelCall:{body:S({id:Dl}),response:SD,ws:`modelCall`},fnMetrics:{body:WD,response:x(UD),ws:`fnMetrics`},fnMetricsDays:{body:S({fn:I,days:y().int().min(1).max(365).optional()}),response:x(HD),ws:`fnMetricsDays`}})}),UB=Y({endpoints:X(Q,$,tB).group({mcps:{body:S({}),response:x(FR),ws:`mcps`},mcp:{body:S({mcp:Ol}),response:FR,ws:`mcp`},createMcp:{body:jR,response:S({mcp:FR,secret:v()}),ws:`createMcp`},updateMcp:{body:jR.partial().extend({mcp:Ol}),response:FR,ws:`updateMcp`},rotateMcpSecret:{body:S({mcp:Ol}),response:S({secret:v()}),ws:`rotateMcpSecret`},deleteMcp:{body:S({mcp:Ol}),response:S({ok:b()}),ws:`deleteMcp`},previewMcp:{body:S({rules:OR}),response:NR,ws:`previewMcp`},mcpSessions:{body:S({mcp:Ol}),response:x(PR),ws:`mcpSessions`}})}),WB=Y({endpoints:X(Q,$,tB).group({pairing:{body:S({pairing:fl}),response:uP,ws:`pairing`},instances:{body:S({system:F}),response:x(sB),ws:`instances`},installPackage:{body:S({zip:kx,instance:L.optional(),config:O.optional(),data:kx.optional(),autoStart:b().optional(),store:lM.optional()}),response:Kl,ws:`installPackage`},removeInstance:{body:Kl.extend({keepStore:b().optional()}),response:S({ok:b()}),ws:`removeInstance`},addInstance:{body:IP,response:Kl,ws:`addInstance`},exportSystemData:{body:Kl.extend({withSecrets:b().optional()}),response:kx.extend({url:v()}),ws:`exportSystemData`}})}),GB=Rw(Y({endpoints:X(Q,$).group({query:{body:Fj,response:Ij,ws:`query`},listValues:{body:Pj,response:x(Nj),ws:`listValues`}})}),Y({endpoints:X(Q,$,tB).group({fns:{body:xj,response:Bl(pP),ws:`fns`}})})),KB=Y({endpoints:X(Q,$,tB).group({suggestDecision:{body:S({}),response:SL,ws:`suggestDecision`},setSuggestDecision:{body:_L,response:SL,ws:`setSuggestDecision`},searchDecisions:{body:S({}),response:OL,ws:`searchDecisions`},setSearchDecision:{body:kL,response:OL,ws:`setSearchDecision`},previewSuggestions:{body:S({session:j,text:v().min(1)}),response:mL,ws:`previewSuggestions`}})}),qB=Y({endpoints:X(Q,$,tB).group({imageEmbedding:{body:S({}),response:bI,ws:`imageEmbedding`},setImageEmbedding:{body:gI,response:bI,ws:`setImageEmbedding`}})}),JB=Rw(Y({endpoints:X(Q,$).group({outsideImages:{body:S({}),response:vb,ws:`outsideImages`}})}),Y({endpoints:X(Q,$,tB).group({setOutsideImages:{body:S({value:_b}),response:vb,ws:`setOutsideImages`}})})),YB=Rw(Y({endpoints:X(Q,$).group({https:{body:S({}),response:Sb,ws:`https`}})}),Y({endpoints:X(Q,$,tB).group({setHttps:{body:S({on:b()}),response:Sb,ws:`setHttps`}})})),XB=Y({endpoints:X(Q,$,tB).group({autoPairs:{body:S({system:F.optional()}),response:x($N),ws:`autoPairs`},revokeAutoPair:{body:S({id:kl}),response:S({ok:b()}),ws:`revokeAutoPair`}})}),ZB=Y({endpoints:X(Q,$).group({accessInfo:{body:S({}),response:ZD,ws:`accessInfo`},access:{body:S({targets:x(JD).min(1).max(200)}),response:x(XD),ws:`access`},setAccess:{body:S({target:JD,sharing:qD.omit({owner:!0})}),response:XD,ws:`setAccess`}})}),QB=Y({endpoints:X(Q,$).group({connectPages:{body:S({}),response:x(TO),ws:`connectPages`},connect:{body:S({system:F,instance:L.optional(),key:yO.optional(),form:O.optional()}),response:C([S({url:mb}),S({connection:wO})]),ws:`connect`,httpOnly:!0},updateConnection:{body:jO,response:wO,ws:`updateConnection`},disconnect:{body:S({connection:Al}),response:S({ok:b()}),ws:`disconnect`}})}),$B=Y({endpoints:X(Q,$).group({pick:{body:tO,response:x(nO),ws:`pick`}})}),eV=Y({endpoints:X(Q,$).group({approvals:{body:S({runs:x(A).min(1).max(200)}),response:x(NI),ws:`approvals`}})}),tV=Y({endpoints:X(Q,$).group({contributions:{body:S({registry:I}),response:x(Dk),ws:`contributions`},systemPages:{body:S({}),response:x(pA),ws:`systemPages`},systemInstances:{body:S({system:F}),response:x(mA),ws:`systemInstances`}})}),nV=Rw(Y({endpoints:X(Q,$).group({searchFns:{body:lF,response:vF,ws:`searchFns`},fnExamples:{body:iF,response:aF,ws:`fnExamples`},fnFacts:{body:S({fn:I,args:O.optional()}),response:xF,ws:`fnFacts`},fnsOfModelNames:{body:S({names:x(v().min(1).max(64)).min(1).max(200)}),response:T(v(),I),ws:`fnsOfModelNames`},clientLogs:{body:EF,response:DF,ws:`clientLogs`}})}),Y({endpoints:X(Q,$,tB).group({autoClassifier:{body:S({}),response:TF,ws:`autoClassifier`},setAutoClassifier:{body:wF,response:TF,ws:`setAutoClassifier`}})})),rV=Y({endpoints:X(Q,$).group({exploreRoots:{body:S({system:F,instance:L.optional()}),response:x(Ax),ws:`exploreRoots`},exploreList:{body:S({uri:Tx,cursor:v().optional()}),response:Bl(jx),ws:`exploreList`},exploreRead:{body:S({uri:Tx,want:x(Nx).min(1)}),response:Fx,ws:`exploreRead`}})}),iV=Y({endpoints:X(Q,$,tB).group({systemReview:{body:S({system:F}),response:YF,ws:`systemReview`},goLive:{body:XF,response:S({stage:pk,hash:v()}),ws:`goLive`},approveReview:{body:XF,response:S({hash:v()}),ws:`approveReview`},rejectReview:{body:S({system:F,hash:v().min(1)}),response:S({ok:b()}),ws:`rejectReview`},decideReview:{body:ZF,response:QF,ws:`decideReview`},testCall:{body:eI,response:S({run:A}),ws:`testCall`},refusals:{body:qF,response:JF,ws:`refusals`}})}),aV=Y({endpoints:X(Q,$).group({graph:{body:YR,response:XR,ws:`graph`}})}),oV=S({agent:I.optional(),context:I.optional(),mode:Bb.optional(),fnMode:fx.optional()}),sV=Y({endpoints:X(Q,$,tB).group({injections:{body:oV,response:jb,ws:`injections`},setInjection:{body:Mb,response:Ab,ws:`setInjection`}})}),cV=Rw(Y({endpoints:X(Q).group({identity:{method:`GET`,response:pI,ws:`identity`}})}),Y({endpoints:X(Q,$,tB).group({setHubName:{body:mI,response:pI,ws:`setHubName`}})})),lV=Y({endpoints:X(Q,$,tB).group({people:{body:xj,response:Bl($I),ws:`people`},groups:{body:xj,response:Bl(eL),ws:`groups`},groupMembers:{body:Vl.extend({group:M}),response:Bl(TI).extend({group:eL}),ws:`groupMembers`},signInSettings:{body:S({}),response:KI,ws:`signInSettings`},checkSsoProvider:{body:S({provider:PI}),response:JI,ws:`checkSsoProvider`},testSsoSignIn:{body:S({provider:PI}),response:S({url:mb,test:v()}),ws:`testSsoSignIn`,httpOnly:!0},ssoTestResult:{body:S({test:v()}),response:ZI,ws:`ssoTestResult`}})}),uV=Y({endpoints:X(Q,$).group({itemVersions:{body:RR,response:zR,ws:`itemVersions`}})}),dV=Y({endpoints:X(Q,$).group({dataSets:{body:Zj,response:Qj,ws:`dataSets`},records:{body:Vj,response:Hj,ws:`records`},record:{body:Wj,response:S({record:zj.optional()}),ws:`record`},recordTable:{body:Uj,response:jk,ws:`recordTable`},saveRecord:{body:Gj,response:zj,ws:`saveRecord`},updateRecord:{body:Kj,response:zj,ws:`updateRecord`},removeRecord:{body:qj,response:S({removed:b()}),ws:`removeRecord`},recordVersions:{body:Jj,response:Yj,ws:`recordVersions`}})}),fV=Rw(fB,_B,vB,yB,bB,xB,wB,TB,EB,AB,NB,IB,LB,RB,zB,BB,HB,UB,WB,GB,KB,XB,qB,JB,YB,ZB,QB,$B,eV,tV,nV,rV,iV,aV,sV,cV,uV,dV,Y({endpoints:X(Q,$).group({rowActions:{body:qz,response:x(Gz),ws:`rowActions`},readFn:{body:Yz,response:O,ws:`readFn`}})}),Y({endpoints:X(Q,$).group({export:{method:`GET`,query:Zz,streamOut:`text/csv`,download:`export.csv`}})}),lV),pV={load_fns:`fns_load`,drop_fns:`fns_drop`,fn_examples:`fns_examples`,fn_get:`fns_get`,save_fn:`fns_save`,fn_metrics:`fns_metrics`,load_context:`ctx_load`,context_get:`ctx_get`,context_crawl:`ctx_crawl`,context_from_resource:`ctx_from_resource`,context_link:`ctx_link`,context_unlink:`ctx_unlink`};new Map(Object.entries(pV).map(([e,t])=>[`hub/${e}`,`hub/${t}`])),new Map(Object.entries(pV));var mV=E([`added`,`modified`,`deleted`,`renamed`]),hV=E([`binary`,`large`,`sensitive`,`not-in-git`]),gV=S({path:v().min(1),root:v().min(1),status:mV,from:v().min(1).optional(),size:y().int().min(0).optional(),diff:v().optional(),added:y().int().min(0).optional(),removed:y().int().min(0).optional(),noDiff:hV.optional(),sensitive:Ik.optional(),certain:b()}),_V=S({source:E([`git`,`watcher`]),cwd:v().min(1),files:x(gV),ignored:y().int().min(0),truncated:b()}),vV=S({arg:k,label:v().min(1).optional(),choices:x(O).min(1).optional(),custom:b().optional(),pinned:O.optional(),hidden:b().optional()}),yV=S({offset:k.optional(),limit:k.optional(),size:y().int().min(1).max(500)}),bV=S({visual:k,label:v().min(1).optional(),bind:T(k,x(v().min(1)).min(1))}),xV=E([`refresh`,`show`,`none`]),SV=S({fn:I,label:v().min(1).optional(),confirm:D(!0).optional(),bind:T(k,v().min(1)),then:xV});S({title:v().min(1),source:I,visuals:x(bV).min(1),controls:x(vV),paging:yV.optional(),actions:x(SV).optional()});var CV=v().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),wV=w(`type`,[S({type:D(`stdio`),command:v().min(1),args:x(v()).default([]),env:T(CV,v()).optional(),cwd:v().min(1).optional()}),S({type:D(`http`),url:Ls()}),S({type:D(`sse`),url:Ls()})]),TV=E([`always`,`writes`,`never`]),EV=S({label:v().min(1),description:v().optional(),transport:wV,auth:lO.default({kind:`none`}),trusted:b().default(!1),approval:TV.default(`writes`),prompts:b().default(!0),resources:b().default(!0),maxTools:y().int().min(1).max(1e3).default(200),timeout:y().int().min(1e3).default(12e4)}),DV=[`transport.env`,...pO],OV=S({instance:L,state:E([`connecting`,`connected`,`needs-auth`,`unreachable`,`failed`]),server:S({name:v(),version:v(),protocol:v(),instructions:v().optional()}).optional(),tools:y().int().min(0),prompts:y().int().min(0),resources:y().int().min(0),degraded:x(v()),leftOut:y().int().min(0),problem:v().optional(),checkedAt:N}),kV=S({title:v().optional(),readOnlyHint:b().optional(),destructiveHint:b().optional(),idempotentHint:b().optional(),openWorldHint:b().optional()});S({tool:v().min(1),description:v(),inputSchema:O,outputSchema:O.optional(),args:Z,returns:Z.optional(),annotations:kV.optional(),degraded:v().optional()});function AV(e,t){let n=`${e}_${t.replace(/[^A-Za-z0-9_.-]/g,`_`)}`.replace(/-/g,`_`);return nb.parse(n.split(`.`).map(e=>e.replace(/_+/g,`_`).replace(/^_+|_+$/g,``)||`x`).join(`.`))}function jV(e){return`mcp://${e}/`}S({args:Z,returns:Z,program:tT}),S({service:yO,args:Z,returns:Z,request:tT,responseType:Z.optional(),output:tT.optional()});var MV=E([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`,`HEAD`,`OPTIONS`]),NV=yO,PV=`api/Service`,FV=S({name:NV,label:v().min(1),description:v().optional(),baseUrl:Ls(),allowPrivate:b().default(!1),privateTo:M.optional(),auth:dO.default({kind:`none`}),headers:aO.optional(),openapi:Ls().optional(),timeout:y().int().min(1e3).default(6e4),maxBody:y().int().min(1024).default(2097152)});S({label:v().min(1),description:v().optional(),baseUrl:Ls(),auth:uO.default({kind:`none`}),headers:aO.optional(),openapi:Ls().optional(),timeout:y().int().min(1e3).default(6e4),maxBody:y().int().min(1024).default(2097152)}),[...fO],S({method:MV,url:v(),headers:x(S({key:v(),value:v()})),body:v().optional(),response:S({status:y().int(),headers:x(S({key:v(),value:v()})),body:O.optional(),ms:y().int().min(0)}).optional()});var IV=eF.pick({id:!0,title:!0,body:!0,link:!0,reason:!0,also:!0,key:!0,tone:!0}),LV=`open`,RV=E([`link`,`also`]),zV=`also`;function BV(e,t=`link`){return`/inbox?${LV}=${encodeURIComponent(e.id)}${t===`also`?`&via=also`:``}`}function VV(e){return e.key??e.id}function HV(e){return e.also===void 0?{link:BV(e)}:{link:BV(e),also:BV(e,`also`)}}function UV(e,t){let n=e=>typeof e==`string`&&e.startsWith(`/`)&&!e.startsWith(`//`);if(n(e))return e;if(typeof e==`object`&&e){let r=Reflect.get(e,`also`),i=Reflect.get(e,`link`);if(t===`also`&&n(r))return r;if(n(i))return i}return`/inbox`}export{Kz as $,zl as $a,Tg as $i,PO as $n,D as $o,Cw as $r,$P as $t,sV as A,Yg as Aa,qb as Ai,jj as An,xc as Ao,NT as Ar,hL as At,wB as B,Ql as Ba,hb as Bi,vA as Bn,Nc as Bo,sT as Br,uI as Bt,LB as C,Gg as Ca,Gx as Ci,mM as Cn,Fl as Co,YT as Cr,fL as Ct,rV as D,Ev as Da,Rx as Di,Lj as Dn,Lc as Do,oE as Dr,gL as Dt,dV as E,yv as Ea,Tx as Ei,zj as En,nc as Eo,cE as Er,sL as Et,GB as F,_h as Fa,Qb as Fi,cj as Fn,kc as Fo,wT as Fr,rL as Ft,kz as G,Of as Ga,Py as Gi,Ek as Gn,ws as Go,tT as Gr,dF as Gt,zz as H,kf as Ha,cb as Hi,dA as Hn,yc as Ho,oT as Hr,MF as Ht,NB as I,pf as Ia,Vb as Ii,QA as In,$s as Io,yT as Ir,OI as It,Dz as J,rf as Ja,Gy as Ji,kk as Jn,E as Jo,Zw as Jr,uF as Jt,Jz as K,gf as Ka,Uy as Ki,Dk as Kn,pc as Ko,$w as Kr,aF as Kt,vB as L,Df as La,Tb as Li,BA as Ln,dc as Lo,CT as Lr,_I as Lt,HB as M,Zg as Ma,zb as Mi,mj as Mn,Sc as Mo,FT as Mr,LI as Mt,BB as N,Ny as Na,Xb as Ni,hj as Nn,Fc as No,vT as Nr,UI as Nt,aV as O,Kg as Oa,Ex as Oi,Rj as On,qc as Oo,sE as Or,vL as Ot,WB as P,sm as Pa,Nb as Pi,Mj as Pn,rc as Po,pT as Pr,VI as Pt,Xz as Q,M as Qa,mv as Qi,rk as Qn,Zc as Qo,bw as Qr,AF as Qt,TB as R,lf as Ra,wb as Ri,AA as Rn,Tc as Ro,fT as Rr,hI as Rt,QB as S,Wg as Sa,qx as Si,fM as Sn,Pl as So,lE as Sr,cL as St,zB as T,dv as Ta,Lx as Ti,$j as Tn,uc as To,aE as Tr,CL as Tt,Zz as U,af as Ua,ab as Ui,rA as Un,Es as Uo,cT as Ur,UF as Ut,uV as V,cf as Va,rb as Vi,uA as Vn,Vc as Vo,aT as Vr,fI as Vt,jz as W,hf as Wa,Fy as Wi,aA as Wn,Uc as Wo,lT as Wr,wF as Wt,Gz as X,R as Xa,wg as Xi,dk as Xn,x as Xo,Ww as Xr,vF as Xt,Oz as Y,vf as Ya,Ky as Yi,jk as Yn,ic as Yo,Hw as Yr,pF as Yt,Lz as Z,Wl as Za,yg as Zi,uk as Zn,b as Zo,kC as Zr,cF as Zt,nB as _,K_ as _a,aS as _i,GM as _n,F as _o,NE as _r,ER as _t,UV as a,kg as aa,aC as ai,yP as an,k as ao,KD as ar,vc as as,ZR as at,XB as b,Ug as ba,lS as bi,lM as bn,tl as bo,jE as br,FL as bt,PV as c,uv as ca,XS as ci,VN as cn,Dl as co,RD as cr,az as ct,EV as d,Sv as da,CC as di,uN as dn,Il as do,MD as dr,YR as dt,av as ea,lC as ei,bP as en,Rl as eo,xO as er,y as es,Hz as et,OV as f,Fg as fa,FS as fi,eN as fn,fl as fo,sD as fr,BR as ft,aB as g,Ov as ga,tS as gi,MN as gn,j as go,ME as gr,MR as gt,_V as h,zg as ha,cS as hi,jN as hn,A as ho,SE as hr,TR as ht,IV as i,Og as ia,dC as ii,vP as in,dl as io,QD as ir,v as is,Ez as it,UB as j,U as ja,dx as ji,kj as jn,Gc as jo,PT as jr,uL as jt,fV as k,qg as ka,wx as ki,yj as kn,jc as ko,eE as kr,_L as kt,FV as l,vv as la,wC as li,YN as ln,ql as lo,TD as lr,yz as lt,AV as m,bv as ma,fS as mi,xN as mn,Ul as mo,gE as mr,DR as mt,RV as n,Dg as na,nC as ni,tP as nn,L as no,hO as nr,Ec as ns,Qz as nt,VV as o,vg as oa,oC as oi,HN as on,Gl as oo,YD as or,C as os,Tz as ot,jV as p,Pg as pa,jS as pi,EN as pn,I as po,zE as pr,jR as pt,qz as q,Af as qa,Qy as qi,Ok as qn,oc as qo,Z as qr,iF as qt,LV as r,fv as ra,rC as ri,mP as rn,O as ro,mO as rr,T as rs,$z as rt,HV as s,hv as sa,KS as si,JN as sn,cl as so,BD as sr,sc as ss,vz as st,zV as t,Eg as ta,uC as ti,_P as tn,Ol as to,yO as tr,S as ts,eB as tt,DV as u,ov as ua,hC as ui,tN as un,bl as uo,ED as ur,WR as ut,ZB as v,Vg as va,iS as vi,sM as vn,N as vo,DE as vr,HL as vt,IB as w,iv as wa,Dx as wi,eM as wn,ac as wo,nE as wr,TL as wt,_B as x,bg as xa,dS as xi,aM as xn,Hl as xo,EE as xr,KL as xt,EB as y,Hg as ya,rS as yi,rM as yn,sl as yo,AE as yr,qL as yt,KB as z,yf as za,bb as zi,NA as zn,zc as zo,uT as zr,gI as zt};
|
|
402
|
-
//# sourceMappingURL=push-payload-
|
|
400
|
+
`):t;if(n.trim())return d(e,JSON.parse(n))},c=i.body.getReader(),l=new TextDecoder,u=``;try{for(;;){let{done:e,value:t}=await c.read();if(e)break;u+=l.decode(t,{stream:!0});let n;for(;(n=u.indexOf(o))>=0;){let e=u.slice(0,n);u=u.slice(n+o.length);let t=s(e);t!==void 0&&(yield t)}}u+=l.decode();let e=s(u);e!==void 0&&(yield e)}finally{await c.cancel().catch(()=>{})}}function ve(n,...r){let i=t.endpoints[n];if(!i)return Promise.reject(Error(`unknown endpoint "${n}"`));let a=i.p.length>0||i.q.length>0||i.hasBody||i.f.length>0||i.streamIn!==null,o=a?r[0]:void 0,s=a?r[1]:r[0],c=s?.transport??(e.prefer===`ws`&&!i.httpOnly&&e.ws?`ws`:`http`);if(c===`ws`&&i.httpOnly){let e=Error(`endpoint "${n}" is http-only`);if(i.items)throw e;return Promise.reject(e)}return i.items||i.itemsIn?c===`ws`?de(n,i,o,s?.stream,s?.signal):i.items?_e(n,i,o,s):ge(n,i,o,s):c===`ws`?fe(i.ws===null?{type:i.path,method:i.method,data:o}:{type:i.ws,data:o},s?.signal).then(e=>i.multi?e:u(n,e)):ge(n,i,o,s)}function ye(e,...n){let r=t.endpoints[e];if(!r)throw Error(`unknown endpoint "${e}"`);if(r.method!==`GET`)throw Error(`url() requires a GET endpoint; "${e}" is ${r.method}`);let{p:i,q:a}=g(r,n[0]);return pe(r,i,a).toString()}function be(n,...r){let i=t.events[n];if(!i)throw Error(`unknown event "${n}"`);if(!e.ws)throw Error(`no websocket transport configured`);let a=i.hasParams?r[0]:void 0,o=i.hasParams?r[1]:r[0],s=`${i.ws}|${oe(a)}`,c=ee.get(s);return c||ee.set(s,c=new Set),c.add(o),fe({sub:i.ws,params:a}),()=>{c.delete(o),c.size===0&&fe({unsub:i.ws,params:a})}}function xe(e,n){let r=t.endpoints[e];if(!r)throw Error(`unknown endpoint "${e}"`);return ww(e,r,(...t)=>ve(e,...t),i,n??{})}return{call:ve,on:be,url:ye,caller:xe,connection:{get status(){return r.status},subscribe:e=>r.subscribe(e)}}}var Uw={initial:500,max:3e4,factor:2,jitter:!0},Ww={interval:3e4,timeout:1e4};function Gw(e,t={}){let n=t.WebSocket??globalThis.WebSocket;if(!n)throw Error(`wsTransport: no WebSocket implementation available; pass opts.WebSocket`);let r=n,i=t.whileDisconnected??`fail`,a={...Uw,...t.backoff},o=t.heartbeat===!1?null:{...Ww,...t.heartbeat??{}},s=t.maxRetries??1/0,c=null,l=`closed`,u=null,d=0,f=!1,p=!1,m=null,h=null,ee=null,te=[],ne=new Map,re=new Aw,ie=new Set,ae=e=>{if(e!==l){l=e,t.onStateChange?.(e);for(let t of[...ie])t(e)}},oe=e=>u?.(e),se=e=>JSON.stringify(e??{},Object.keys(e??{}).sort());function ce(){re.fail(oe,`connection closed`)}function le(){h&&clearInterval(h),ee&&clearTimeout(ee),h=ee=null}function ue(){o&&(le(),h=setInterval(()=>{l===`open`&&c&&(c.send(JSON.stringify({ping:!0})),ee&&clearTimeout(ee),ee=setTimeout(()=>c?.close(),o.timeout))},o.interval))}function de(e){let t=null;try{t=JSON.parse(e)}catch{oe(e);return}t&&t.pong===!0?ee&&=(clearTimeout(ee),null):(t&&re.settle(t),oe(e))}function fe(){if(p)return;f=!0,d=0,ae(`open`);for(let e of ne.values())c?.send(e);let e=te.splice(0);for(let t of e)c?.send(t);ue()}function g(){le(),c=null,ce(),p?ae(`closed`):pe()}function pe(){if(p)return;if(d>=s){ae(`closed`);return}let e=Math.min(a.max,a.initial*a.factor**+d),t=a.jitter?e/2+e/2*Math.random():e;d++,ae(`connecting`),m=setTimeout(me,t)}function me(){if(p||c)return;m&&=(clearTimeout(m),null),ae(`connecting`);let n;try{n=new r(typeof e==`function`?e():e,typeof t.protocols==`function`?t.protocols():t.protocols)}catch(e){t.onError?.(e),pe();return}c=n;let i=!1,a=()=>{c===n&&g()};n.addEventListener(`open`,()=>{i=!0,fe()}),n.addEventListener(`message`,e=>de(String(e.data))),n.addEventListener(`close`,a),n.addEventListener(`error`,e=>{t.onError?.(e),i||a()})}function he(e){let t={};try{t=JSON.parse(e)}catch{}typeof t.sub==`string`?ne.set(`${t.sub}|${se(t.params)}`,e):typeof t.unsub==`string`&&ne.delete(`${t.unsub}|${se(t.params)}`),typeof t.id==`string`&&typeof t.type==`string`&&re.add(t.id);let n=typeof t.sub==`string`||typeof t.unsub==`string`;l===`open`&&c?c.send(e):`rid`in t||(me(),n||(!f||i===`queue`?te.push(e):typeof t.id==`string`&&oe(Ow(t.id,`not connected`))))}return{send:he,onMessage(e){u=e},connect:me,reconnect(){if(p)return;let e=c;c=null,le(),ce(),e?.close(),d=0,me()},close(){p=!0,m&&clearTimeout(m),m=null,le(),ce(),c?.close(),c=null,ae(`closed`)},get state(){return l},onState(e){return ie.add(e),()=>void ie.delete(e)}}}function Kw(e,t,n){return{kind:`endpoint`,cfg:e,mws:t,prefixes:n}}function Y(e){return Kw(e,[],[])}function X(e){for(let[t,n]of Object.entries(e.endpoints)){let e=n.cfg;if(e.streamIn&&(e.body||e.files))throw Error(`endpoint "${t}": streamIn excludes body/files`);if(e.files&&`body`in e.files)throw Error(`endpoint "${t}": "body" is reserved as the multipart JSON field name`);if(e.streamOut&&e.response)throw Error(`endpoint "${t}": streamOut excludes response`);if(e.responses&&e.response)throw Error(`endpoint "${t}": responses (multi-status) excludes response`);if(e.responses&&e.streamOut)throw Error(`endpoint "${t}": responses excludes streamOut`);if(e.streamEncoding&&!(e.streamOut instanceof ws))throw Error(`endpoint "${t}": streamEncoding requires a typed (schema) streamOut`);if(e.bodyEncoding===`urlencoded`&&!(e.body instanceof dc))throw Error(`endpoint "${t}": urlencoded bodies must be z.object(...)`);if(e.download&&typeof e.streamOut!=`string`)throw Error(`endpoint "${t}": download requires a raw (content-type) streamOut`);for(let n of[`params`,`query`,`headers`,`cookies`]){let r=e[n];if(r&&!(r instanceof dc))throw Error(`endpoint "${t}": ${n} must be a z.object(...)`)}Xw(t,n)}let t;return Object.defineProperty(e,qw,{value:()=>t??=Jw(e),enumerable:!1,configurable:!0}),e}var qw=Symbol.for(`ayepi.manifest`);function Jw(e){let t=Object.entries(e.endpoints).map(([e,t])=>Xw(e,t));return{endpoints:Object.fromEntries(t.map(e=>[e.name,{method:e.method,path:e.path,ws:e.ws,httpOnly:e.httpOnly,streamIn:e.streamInCt,itemsIn:e.itemsIn,streamOut:e.streamOutCt,items:e.items,p:e.p,q:e.q,b:e.bRaw?`raw`:e.b,f:e.f,hasBody:!!e.def.cfg.body,hasHeaders:!!e.def.cfg.headers,multi:e.multi,bodyEnc:e.bodyEnc,sideEffects:e.def.cfg.sideEffects}])),events:Object.fromEntries(Object.entries(e.events??{}).map(([e,t])=>[e,{ws:t.ws??e,hasParams:!!t.params}]))}}function Yw(e){return e&&e instanceof dc?Object.keys(e.shape):null}function Xw(e,t){let n=t.cfg,r=iT(t.mws),i=t=>{throw Error(`endpoint "${e}": ${t}`)},a=new Map;for(let e of r)e.paramKey&&e.paramSchema&&a.set(e.paramKey,e.paramSchema);let o=new Map,s=(e,t)=>{for(let n of e.keys)(a.has(n)||o.has(n))&&i(`param ":${n}" is declared more than once (${t})`),o.set(n,e.schemas[n])};for(let e of t.prefixes)typeof e!=`string`&&s(e,`prefix path`);let c=typeof n.path==`object`&&n.path!==null?n.path:null;c&&s(c,`endpoint path`);let l=Yw(n.params)??[];for(let e of l)(a.has(e)||o.has(e))&&i(`param ":${e}" is declared more than once (params schema)`);let u=new Set([...a.keys(),...o.keys(),...l]),d=[];for(let e of t.prefixes)d.push(...typeof e==`string`?qC(e):e.parts);if(c)d.push(...c.parts);else if(typeof n.path==`string`)d.push(...qC(n.path));else{d.push({t:`lit`,v:e});let t=new Set(XC(d));for(let e of u)t.has(e)||d.push({t:`param`,k:e})}let f=XC(d),p=new Set(f);f.length!==p.size&&i(`path positions a param more than once: ${JC(d)}`);for(let e of f)u.has(e)||i(`path references undeclared param ":${e}"`);for(let e of u)p.has(e)||i(`declared param ":${e}" has no position in path ${JC(d)}`);let m=[...u],h=Yw(n.query)??[],ee=n.body?Yw(n.body):null,te=!!n.body&&ee===null,ne=Object.keys(n.files??{}),re=new Map;for(let[e,t]of[[`path`,m],[`query`,h],[`body`,ee??[]],[`files`,ne]])for(let n of t){let t=re.get(n);t&&i(`key "${n}" appears in both ${t} and ${e} — kinds must be disjoint`),re.set(n,e)}te&&(m.length>0||h.length>0||ne.length>0)&&i(`a non-object body is the entire data payload — params/query/files are not allowed alongside it`);let ie=n.streamIn instanceof ws,ae=typeof n.streamIn==`string`?n.streamIn:ie?`application/x-ndjson`:null,oe=n.streamOut instanceof ws,se=oe&&n.streamEncoding===`sse`,ce=typeof n.streamOut==`string`?n.streamOut:oe?se?`text/event-stream`:`application/x-ndjson`:null,le=!!(n.httpOnly||typeof n.streamIn==`string`||typeof n.streamOut==`string`||ne.length>0);return{name:e,def:t,method:n.method??`POST`,parts:d,path:JC(d),ws:n.ws??null,wsEligible:!le,httpOnly:le,streamInCt:ae,itemsIn:ie,streamOutCt:ce,items:oe,sse:se,multi:!!(n.responses&&Object.keys(n.responses).length>0),bodyEnc:n.body?n.bodyEncoding??`json`:null,p:m,q:h,b:ee,bRaw:te,f:ne,loaders:a,tplSchemas:o,chain:r}}function Zw(){return{}}function Qw(e){return()=>{throw Error(`middleware "${e}" has no implementation — bind it with implement(api).middleware(def, impl)`)}}function $w(e,t,n,r,i,a){let o={kind:`middleware`,name:e,requires:t,optional:n,paramKey:r,paramSchema:i,doc:a,run:Qw(e),with(...e){return eT([o,...e],[])},path(e){return eT([o],[e])},endpoint(e){return eT([o],[]).endpoint(e)},group(e){return eT([o],[]).group(e)}};return o}function eT(e,t){return{kind:`stack`,mws:e,prefixes:t,with(...n){return eT([...e,...n],t)},path(n){return eT(e,[...t,n])},endpoint(n){return Kw(n,e,t)},group(n){let r={};for(let[i,a]of Object.entries(n))r[i]=Kw(a,e,t);return r}}}function Z(...e){return eT([...e],[])}function tT(e,t){return $w(e,t?.requires??[],t?.optional??[],void 0,void 0,t?.doc)}function nT(e,t,n){return $w(e,n?.requires??[],n?.optional??[],e,t,n?.doc)}var rT=Object.assign(tT,{loader:nT});function iT(e){let t=new Set,n=[],r=(e,i)=>{if(!t.has(e)){if(i.has(e))throw Error(`middleware cycle involving "${e.name}"`);i.add(e);for(let t of e.requires)r(t,i);i.delete(e),t.add(e),n.push(e)}};for(let t of e)r(t,new Set);let i=new Map(n.map((e,t)=>[e,t]));return[...n].sort((e,t)=>e.optional.includes(t)?1:t.optional.includes(e)?-1:i.get(e)-i.get(t))}function aT(...e){let t={},n={};for(let r of e){for(let[e,n]of Object.entries(r.endpoints)){if(Object.hasOwn(t,e))throw Error(`mergeSpecs: endpoint "${e}" is in more than one spec`);t[e]=n}for(let[e,t]of Object.entries(r.events??{})){if(Object.hasOwn(n,e))throw Error(`mergeSpecs: event "${e}" is in more than one spec`);n[e]=t}}return X({endpoints:t,events:n})}var oT=new WeakMap;function sT(e,t){return oT.set(e._zod.def,{source:t}),e}function cT(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Map)}var lT=class e extends U{static NAME=`record`;name=e.NAME;static optionKeys=[];static genericKeys=[`V`];static from(t,n){let r=t.generic?.V;return new e(n,r===void 0?n.registry.any():n.parse(r))}static toA(){return R.object({name:R.literal(e.NAME),generic:R.object({V:R.ref(`TypeDef`)}).optional()}).describe(`A record: an object with any text keys, each value a V.`)}constructor(e,t){super(e,{},{V:t})}get value(){let e=this.generic.V;if(e===void 0)throw Error(`record has no value type`);return e}valid(e,t){return cT(e)&&Object.values(e).every(e=>{try{return this.value.parse(e,t),!0}catch{return!1}})}parse(e,t){if(!cT(e))throw new ih({path:[],code:`record.invalid`,message:`record.parse: expected an object of values by key`,severity:`error`});for(let[n,r]of Object.entries(e))try{this.value.parse(r,t)}catch(e){throw new ih({path:[n],code:`record.value`,message:`record.parse: ${n}: ${e instanceof Error?e.message:String(e)}`,severity:`error`})}return new W(this,e)}encode(e){return e}create(){return{}}random(e){return{}}compatibleType(t){return t instanceof e&&this.value.compatibleType(t.value)}or(t){return t instanceof e&&this.value.compatibleType(t.value)?this:t}narrow(){return{}}toJSON(){return{name:e.NAME,generic:{V:this.value.toJSON()}}}clone(){return new e(this.scope,this.value)}toCode(e,t){return`${this.docsPrefix(t)}record<${this.value.toCode(void 0,t)}>`}valueA(e){return R.record(this.value.toA(e))}toNewA(){return R.record(R.ref(`Expr`))}};function uT(e){return e.typeClass(lT.NAME)===void 0&&e.define(lT),e}function dT(){return uT(ay())}var fT;function pT(){return fT??=dT(),fT}var mT=fb.result(`TypeDef`),hT=fb.result(`Expr`);function gT(e){return()=>{let{description:t,...n}=e(pT()).render($l).jsonSchema;return n}}function _T(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function vT(e){return _T(e)&&`name`in e&&typeof e.name==`string`}var yT=sT(Jc(vT,{message:`Expected a gin type definition ({ name, ... }).`}),gT(e=>mT.bind(e,void 0,{namedRefs:!0})));function bT(e){return vT(e)}var xT=sT(Jc(bT,{message:`Expected a gin object type definition ({ name: "obj", props: { ... } }).`}),gT(e=>hb(e.typ(e.obj({}))).bind(e,void 0,{namedRefs:!0})));function ST(e){return _T(e)&&`kind`in e&&typeof e.kind==`string`}var CT=sT(Jc(ST,{message:`Expected a gin expression ({ kind, ... }).`}),gT(e=>hT.bind(e,void 0,{namedRefs:!0}))),wT=new Set(`id.uuid.guid.url.uri.api.json.csv.tsv.xml.html.css.yaml.sql.pdf.svg.png.jpg.ip.dns.http.https.ssh.tls.ssl.tcp.udp.vpn.os.cpu.gpu.ram.ui.ux.ai.llm.sku.sms.otp.jwt.utc.iso.gmt.ssn.vat.faq.crm.rgb.db.mime.ttl.oauth.sso.mfa`.split(`.`)),TT=new Map([[`ctx`,`context`]]);function ET(e,t){let n=e.toLowerCase();if(wT.has(n))return n.toUpperCase();let r=TT.get(n);return r===void 0?n.endsWith(`s`)&&wT.has(n.slice(0,-1))?`${n.slice(0,-1).toUpperCase()}s`:t?e:n:t?jT(r):r}function DT(e){return jT((/[\s._/:-]/.test(e)&&!/[a-z]/.test(e)?e.toLowerCase():e).replace(/([A-Z]+)([A-Z][a-z])/g,`$1 $2`).replace(/([a-z0-9])([A-Z])/g,`$1 $2`).split(/[\s._/:-]+/).filter(e=>e!==``).map((e,t)=>ET(e,t===0)).join(` `))||e}function OT(e){return e.label??DT(e.name)}function kT(e){return DT(Il(e).local)}function AT(e){return/^[A-Z][a-z]/.test(e)?`${e.charAt(0).toLowerCase()}${e.slice(1)}`:e}function jT(e){return e===``?e:`${e.charAt(0).toUpperCase()}${e.slice(1)}`}function MT(e,t){let n=e.replace(/\s+/g,` `).trim();if(n.length<=t)return n;let r=n.slice(0,t-1),i=r.lastIndexOf(` `);return`${i>t*.6?r.slice(0,i):r}…`}var NT=[`path`,`file`,`uri`,`query`,`command`,`url`,`name`,`title`,`text`,`pattern`,`message`];function PT(e,t=60){if(e==null)return``;if(typeof e==`string`)return MT(e,t);if(typeof e==`number`||typeof e==`boolean`)return String(e);if(Array.isArray(e))return e.length===0?``:`${e.length} item${e.length===1?``:`s`}`;let n=NT.map(t=>e[t]).find(e=>typeof e==`string`&&e!==``);if(typeof n==`string`)return MT(n,t);for(let[n,r]of Object.entries(e))if(typeof r==`string`||typeof r==`number`||typeof r==`boolean`)return MT(`${n}: ${String(r)}`,t);return``}var FT=[`active`,`retry`,`done`,`failed`],IT=E(FT),LT=S({one:v().min(1),many:v().min(1)}),RT=S({active:LT,retry:LT,done:LT,failed:LT}),zT=S({phase:IT,one:v(),many:v()}),BT={active:{one:`{fn}…`,many:`{fn} ×{n}…`},retry:{one:`Retrying {fn}…`,many:`Retrying {fn} ×{n}…`},done:{one:`{fn} done`,many:`{fn} ×{n} done`},failed:{one:`{fn} failed`,many:`{fn} ×{n} failed`}};function VT(e,t){switch(e){case`queued`:case`running`:case`waiting`:return t>1?`retry`:`active`;case`invalid-input`:return`retry`;case`done`:return`done`;case`failed`:return`failed`;case`awaiting-approval`:case`paused`:case`cancelled`:case`undone`:return}}var HT=60,UT=3,WT=/\{([^{}|]+)(?:\|([^{}]*))?\}/g;function GT(e,t,n){for(let r of e){if(r===void 0)continue;let e=qT(r[t].one,n,!1),i=qT(r[t].many,n,!0);if(e!==void 0&&i!==void 0)return{phase:t,one:e,many:i}}let r=BT[t];return{phase:t,one:qT(r.one,n,!1)??r.one,many:qT(r.many,n,!0)??r.many}}function KT(e,t){return t===1?e.one:e.many.replaceAll(`{n}`,String(t))}function qT(e,t,n){let r=[],i=e.replace(WT,(e,i,a)=>{let o=JT(i.trim(),t,n);return o===void 0?a===void 0?(r.push(i),e):a:o});return r.length>0?void 0:jT(i.replace(/…{2,}/g,`…`))}function JT(e,t,n){if(e===`fn`)return AT(kT(t.fn));if(e===`n`)return n?`{n}`:void 0;let[r,...i]=e.split(`.`),a=r===`args`?t.args:r===`output`?t.output:void 0;return a===void 0?void 0:XT(YT(a,i))}function YT(e,t){let n=e;for(let e of t){if(typeof n!=`object`||!n)return;n=Array.isArray(n)?n[Number(e)]:n[e]}return n}function XT(e){if(e!=null){if(typeof e==`string`)return e===``?void 0:QT(e);if(typeof e==`number`||typeof e==`boolean`)return String(e);if(Array.isArray(e)){let t=e.map(XT).filter(e=>e!==void 0);if(t.length===0)return;let n=t.slice(0,UT),r=t.length-n.length;return ZT(r>0?[...n,`${r} more`]:n)}for(let t of[`title`,`name`,`id`]){let n=e[t];if(typeof n==`string`&&n!==``)return QT(n)}}}function ZT(e){return e.length<=2?e.join(` and `):`${e.slice(0,-1).join(`, `)} and ${e.at(-1)??``}`}function QT(e){let t=e.split(`
|
|
401
|
+
`)[0]??``;return t.length>HT?`${t.slice(0,59)}…`:t}var $T=E([`system-needs-config`,`system-disconnected`,`system-removed`,`kind-missing`,`kind-system-disconnected`,`dep-unavailable`,`disabled`,`held`,`paused`,`role-unset`]),eE=C([D(!0),S({unavailable:$T,detail:v()})]),tE=S({code:E([...$T.options,`no-such-fn`,`not-a-name`,`other-system`,`not-for-model`,`connect-account`]),reason:v().min(1),system:F.optional()}),nE=tE.extend({fn:v()}),rE=tE.extend({name:v()}),iE=S({id:M,name:v(),email:v(),role:E([`admin`,`member`]),groups:x(S({id:M,name:v()})),timeZone:v(),locale:v()}),aE=S({now:N,timeZone:v(),local:v()}),oE=S({name:v(),instance:L,boot:v(),from:S({system:v(),fn:I,run:A}).optional()}),sE=S({id:A,fn:I,parent:A.optional(),turn:cl,session:j.optional(),user:iE,time:aE,system:oE,caller:M,attempt:y().int().min(1),priority:Rl,watched:b().optional(),inChat:b().optional()}),cE=S({timeZone:v(),locale:v(),now:N}),lE=E([`card`,`message`,`hidden`]),uE=S({cancel:b(),pause:b(),undo:b(),background:b()}),dE=uE.pick({cancel:!0,pause:!0,background:!0}),fE=S({timeout:Ml.optional(),retries:y().int().min(0).optional(),cost:P.optional()}),pE=w(`type`,[S({type:D(`none`)}),S({type:D(`linear`)}),S({type:D(`steps`),steps:T(v(),v())})]),mE=E([`pending`,`active`,`done`,`failed`,`skipped`]),hE=C([S({fraction:y().min(0).max(1),message:v().optional()}),S({steps:T(v(),S({status:mE,detail:v().optional()}))})]),gE=C([S({fraction:y().min(0).max(1),message:v().optional()}),S({step:v(),status:mE,detail:v().optional()})]),_E=[`retry`,`caller`,`fatal`],vE=S({class:E(_E),message:v(),code:v().optional(),data:O.optional()}),yE=E([`json`,`schema`,`validation`,`unavailable`,`result`]),bE=S({path:v(),message:v()}),xE=S({path:v(),repair:E([`json-string`])});function SE(e){return e.path===``?e.message:`${e.path}: ${e.message}`}var CE=S({source:yE,problems:x(bE).min(1),raw:v().optional(),blocked:tE.optional()}),wE=[`awaiting-approval`,`queued`,`running`,`waiting`,`paused`,`done`,`invalid-input`,`failed`,`cancelled`,`undone`],TE=E(wE),EE={"awaiting-approval":!1,queued:!1,running:!1,waiting:!1,paused:!1,done:!0,"invalid-input":!0,failed:!0,cancelled:!0,undone:!0},DE={"awaiting-approval":`Needs approval`,queued:`Queued`,running:`Running`,waiting:`Waiting`,paused:`Paused`,done:`Done`,"invalid-input":`Thinking harder`,failed:`Failed`,cancelled:`Cancelled`,undone:`Undone`};function OE(e){return EE[e]}function kE(e){return!EE[e]}var AE=wE.filter(OE),jE=wE.filter(kE),ME=w(`type`,[S({type:D(`status`),status:TE,text:zT.optional()}),S({type:D(`progress`),progress:hE}),S({type:D(`allowed`),operations:dE}),S({type:D(`cost`),cost:P,total:P}),S({type:D(`background`)}),S({type:D(`result`),revision:y().int().min(1)})]),NE=w(`status`,[S({status:D(`done`),result:O,undo:O.optional(),cost:P.optional(),expose:x(rx).optional()}),S({status:D(`invalid-input`),invalid:CE,undo:O.optional(),cost:P.optional()}),S({status:D(`paused`),resume:O,cost:P.optional()}),S({status:D(`failed`),error:vE,undo:O.optional(),cost:P.optional()}),S({status:D(`cancelled`),partial:O.optional(),undo:O.optional(),cost:P.optional(),error:vE.optional()})]),PE=w(`status`,[S({status:D(`done`),result:O}),S({status:D(`failed`),error:vE}),S({status:D(`cancelled`),error:vE.optional()}),S({status:D(`background`),run:A})]),FE=w(`status`,[S({status:D(`undone`),summary:v()}),S({status:D(`failed`),error:vE}),S({status:D(`gone`)})]),IE=w(`ok`,[S({ok:D(!0),value:O}),S({ok:D(!1),error:vE})]),LE=S({cost:P,time:Ml,limitedBy:v()}),RE=Rx,zE=S({hash:v().regex(Xx),kind:aS,converter:v().min(1),content:Zx,chars:y().int().min(0),tokens:y().int().min(0),call:Ol.optional(),createdAt:N}),BE=S({kind:aS,model:v().optional(),estimate:y().min(0).optional()}),VE=w(`from`,[S({from:D(`system`),system:F,served:E([`bytes`,`text`]).optional()}),S({from:D(`upload`),by:M}),S({from:D(`web`),url:Ib,finalUrl:Ib.optional(),fetchedAt:N,rendered:b()}),S({from:D(`run`),run:A,fn:I})]),HE=[`system`,`upload`,`web`,`run`],UE=E([`auto`,`always`,`never`]),WE=`hub://resources/`,GE=[`document`,`code`,`image`,`table`,`audio`,`video`,`web`,`data`,`archive`,`folder`,`other`],KE=E(GE),qE={markdown:`document`,text:`document`,pdf:`document`,docx:`document`,pptx:`document`,rtf:`document`,odt:`document`,notebook:`document`,html:`web`,json:`data`,jsonl:`data`,yaml:`data`,toml:`data`,xml:`data`,ini:`data`,csv:`table`,tsv:`table`,excel:`table`,ods:`table`,image:`image`,svg:`image`,mermaid:`image`,audio:`audio`,video:`video`,zip:`archive`,folder:`folder`,...Object.fromEntries(`typescript.javascript.jsx.tsx.vue.python.ruby.go.rust.java.c.cpp.csharp.php.swift.kotlin.scala.css.scss.less.shell.sql.dockerfile.graphql.lua.r.dart`.split(`.`).map(e=>[e,`code`]))};function JE(e,t){let n=e===void 0?void 0:qE[e];if(n!==void 0)return n;let r=t?.split(`/`)[0];return r===`image`||r===`audio`||r===`video`?r:`other`}var YE=E([`type`,`source`,`path`,`date`]),XE=S({value:v(),label:v(),count:y().int().min(0)}),ZE=Hl.extend({search:v().optional(),system:F.optional(),family:KE.optional(),source:E(HE).optional(),under:v().optional(),form:aS.optional(),missing:aS.optional(),group:YE.optional(),in:v().optional()}),QE=S({uri:qx}),$E=S({uri:qx,section:Jx.optional()}),eD=S({image:qx,question:v().trim().min(1).max(2e3),page:y().int().min(1).optional()}),tD=S({answer:v(),model:v(),image:S({id:qx,name:v()})}),nD=S({uri:qx,form:C([aS,D(`raw`)]).optional(),section:Jx.optional(),offset:y().int().min(0).optional(),maxChars:y().int().min(1).max(2e5).optional(),rows:S({table:v(),from:y().int().min(0),to:y().int().min(0)}).optional()}),rD=S({uri:qx,form:C([aS,D(`raw`)]),text:v(),offset:y().int().min(0),total:y().int().min(0),truncated:b(),partial:v().optional(),note:v().optional(),forms:x(aS),offers:x(BE)}),iD=C([S({url:Ib,render:UE.optional(),name:v().optional(),folder:v().min(1).optional()}),S({content:Zx,name:v().min(1),path:v().optional()})]),aD=C([S({model:v().min(1)}),S({category:v().min(1)}),S({auto:S({cost:y().min(0).optional(),speed:y().min(0).optional(),accuracy:y().min(0).optional()})})]),oD=S({id:v(),name:v(),arguments:v(),invalid:v().optional()}),sD=S({type:E([`text`,`image`,`file`,`audio`,`video`]),content:v(),format:v().optional(),name:v().optional()}),cD=S({role:E([`system`,`user`,`assistant`,`tool`]),content:C([v(),x(sD)]),name:v().optional(),toolCallId:v().optional(),toolCalls:x(oD).optional(),refusal:v().optional(),tokens:y().int().optional()}),lD=S({input:y().int().min(0),output:y().int().min(0),cached:y().int().min(0).optional(),reasoning:y().int().min(0).optional()}),uD=E([`stop`,`length`,`tool_calls`,`content_filter`,`refusal`]),dD=S({content:v().optional(),reasoning:v().optional(),toolCallNamed:oD.optional(),toolCallArguments:oD.optional(),toolCallMore:oD.optional(),toolCall:oD.optional(),finishReason:uD.optional(),refusal:v().optional(),usage:lD.optional()}),fD=C([b(),y().positive()]),pD=E([`summary`,`list`,`markers`,`full`]),mD=C([pD,S({detail:pD.optional(),maxErrors:y().int().min(0).optional(),maxChars:y().int().min(0).optional(),suggestions:b().optional(),expected:b().optional(),context:y().int().min(0).optional(),depth:y().int().min(0).optional(),header:b().optional()})]),hD=S({name:v(),description:v().optional(),parameters:O,strict:fD.optional(),errorFormat:mD.optional()}),gD=C([D(`text`),D(`json`),S({schema:O,strict:fD,errorFormat:mD.optional(),schemaDelivery:E([`auto`,`structured`,`json`,`prompt`]).optional()})]),_D=S({messages:x(cD),temperature:y().optional(),maxTokens:y().int().optional(),stop:x(v()).optional(),tools:x(hD).optional(),toolChoice:C([E([`auto`,`none`,`required`]),S({tool:v()})]).optional(),responseFormat:gD.optional(),errorFormat:mD.optional()}),vD=S({run:A.optional(),request:_D,model:aD.optional(),stream:b()}),yD=w(`type`,[S({type:D(`chunk`),chunk:dD}),S({type:D(`done`),usage:lD,cost:P,interaction:fl,model:v()}),S({type:D(`error`),message:v(),kind:E([`model`,`tool`,`limit`,`provider`])})]),bD=S({id:v().min(1),text:v().min(1),score:y().min(0).max(1)}),xD=S({run:A,question:v().min(1),candidates:x(bD).min(1).max(50),max:y().int().min(1).max(20)}),SD=w(`by`,[S({by:D(`decision`),picked:x(S({id:v(),why:v().optional()})),note:v().optional(),call:Ol.optional()}),S({by:D(`off`)}),S({by:D(`failed`),message:v()})]),CD=w(`type`,[S({type:D(`predicate`),instructions:v().min(1)}),S({type:D(`choice`),instructions:v().min(1),choices:T(v(),v())}),S({type:D(`score`),instructions:v().min(1),levels:x(v()).min(1)})]),wD=C([v().min(1),x(cD).min(1)]),TD=T(v().min(1),CD),ED=y().min(0).max(1),DD=w(`type`,[S({type:D(`predicate`),probability:ED}),S({type:D(`choice`),choice:v(),probabilities:T(v(),ED),confidence:ED}),S({type:D(`score`),score:y(),probabilities:x(ED),confidence:ED}),S({type:D(`refusal`)})]),OD=T(v(),DD),kD=.5,AD=[`chat`,`embed`,`image`,`transcribe`,`speech`,`decide`];E(AD);var jD=E([`yes`,`no`,`unknown`]),MD=S({modality:D(`chat`),input:y().int().min(0),output:y().int().min(0),cached:y().int().min(0).optional(),reasoning:y().int().min(0).optional(),caching:jD.optional()}),ND=S({modality:D(`embed`),texts:y().int().min(0),characters:y().int().min(0),images:y().int().min(1).optional(),tokens:y().int().min(0).optional(),dimensions:y().int().min(1)}),PD=S({modality:D(`image`),images:y().int().min(0),size:v().optional()}),FD=S({modality:D(`transcribe`),seconds:y().min(0),bytes:y().int().min(0)}),ID=S({modality:D(`speech`),characters:y().int().min(0),seconds:y().min(0).optional()}),LD=S({modality:D(`decide`),questions:y().int().min(0),characters:y().int().min(0),images:y().int().min(0).optional(),tokens:y().int().min(0).optional()});w(`modality`,[MD,ND,PD,FD,ID,LD]);var RD=E([`mp3`,`wav`,`ogg`]),zD=E([`running`,`done`,`failed`,`aborted`]),BD=S({id:Ol,provider:v(),model:v(),run:A.optional(),turn:cl.optional(),session:j.optional(),system:F.optional(),fn:I.optional(),purpose:v().optional(),interaction:fl.optional(),cost:P,status:zD,error:v().optional(),priority:Rl.optional(),sent:y().int().min(0),received:y().int().min(0),queued:Ml,firstByte:Ml.optional(),total:Ml.optional(),startedAt:N,endedAt:N.optional()}),VD=e=>S({modality:e.shape.modality,units:e}),HD=w(`modality`,[VD(MD),VD(ND),VD(PD),VD(FD),VD(ID),VD(LD)]),UD=e=>BD.extend(e.shape),WD=w(`modality`,[UD(HD.options[0]),UD(HD.options[1]),UD(HD.options[2]),UD(HD.options[3]),UD(HD.options[4]),UD(HD.options[5])]),GD=w(`modality`,[S({modality:D(`embed`),texts:x(v()).min(1),model:aD.optional()}),S({modality:D(`image`),prompt:v().min(1),model:aD.optional(),size:v().optional(),count:y().int().min(1).max(10).optional()}),S({modality:D(`transcribe`),audio:Zx,model:aD.optional(),language:v().optional()}),S({modality:D(`speech`),text:v().min(1),model:aD.optional(),voice:v().optional(),format:RD.optional()}),S({modality:D(`decide`),input:wD,questions:TD,model:aD.optional()})]).and(S({run:A.optional()})),KD=w(`modality`,[S({modality:D(`embed`),vectors:x(x(y()))}),S({modality:D(`image`),images:x(Zx)}),S({modality:D(`transcribe`),text:v(),segments:x(S({start:y().min(0),end:y().min(0),text:v()})).optional()}),S({modality:D(`speech`),audio:Zx}),S({modality:D(`decide`),answers:OD})]).and(S({call:Ol,cost:P,model:v()})),qD=E([`chat`,`transcribe`,`dictate`,`speak`,`describe`,`ocr`,`decide`,`metadata`,`plan`]),JD={chat:`chat`,transcribe:`hearing`,dictate:`hearing`,speak:`audio`,describe:`vision`,ocr:`vision`,decide:`decision`,metadata:`chat`,plan:`chat`},YD=S({model:aD,provider:Tl.optional()}),XD=w(`engine`,[S({engine:D(`browser`)}),YD.extend({engine:D(`model`)})]),ZD=[`browser`,`model`],QD=qD.exclude([`dictate`,`decide`]),$D=YD.extend({role:D(`decide`),threshold:y().min(0).max(1).default(kD)}),eO=w(`role`,[S({role:D(`dictate`),engine:XD,language:v().optional()}),$D,YD.extend({role:QD,language:v().optional()})]);S({choice:eO,setBy:M,updatedAt:N});var tO=C([S({model:v(),provider:v()}),S({problem:v()})]),nO=S({role:qD,choice:eO.optional(),from:E([`setting`,`env`,`none`]),resolved:tO.optional(),fallback:S({role:qD,reason:v()}).optional()}),rO=[`done`,`invalid-input`,`failed`,`cancelled`],iO=T(E(rO),y().int().min(0));function aO(){return{done:0,"invalid-input":0,failed:0,cancelled:0}}function oO(e){return rO.reduce((t,n)=>t+e[n],0)}var sO=v().regex(/^\d{4}-\d{2}-\d{2}$/),cO=[50,100,250,500,1e3,2500,5e3,1e4,3e4,6e4,3e5],lO=S({count:y().int().min(0),sum:Ml,max:Ml,histogram:x(y().int().min(0)).length(cO.length+1)}),uO=S({fn:I,system:F,day:sO,outcomes:iO,queued:lO,approval:lO,ran:lO,cost:P,tokens:y().int().min(0),retries:y().int().min(0),modelCalls:y().int().min(0),updatedAt:N}),dO=S({fn:I,system:F,from:sO,to:sO,runs:y().int().min(0),outcomes:iO,p50:Ml.optional(),p95:Ml.optional(),averageQueued:Ml.optional(),averageCost:P,cost:P,tokens:y().int().min(0),retries:y().int().min(0),lastRunAt:N.optional()}),fO=S({fn:Mb.optional(),system:F.optional(),days:y().int().min(1).max(365).optional()}),pO=E([`private`,`shared`,`public`]),mO={private:`Only me`,shared:`Me and chosen people`,public:`Everyone`},hO=S({owner:M,visibility:pO,with:x(M)});E([`system`,`fn`,`context`,`root`,`connection`]);var gO=w(`kind`,[S({kind:D(`system`),system:F}),S({kind:D(`fn`),fn:I}),S({kind:D(`context`),context:I}),S({kind:D(`root`),uri:v().min(1)}),S({kind:D(`connection`),connection:jl})]);function _O(e){switch(e.kind){case`system`:return`system:${e.system}`;case`fn`:return`fn:${e.fn}`;case`context`:return`context:${e.context}`;case`root`:return`root:${e.uri}`;case`connection`:return`connection:${e.connection}`}}S({key:v(),target:gO,sharing:hO,scoped:b().optional(),setBy:M,updatedAt:N});var vO=S({target:gO,sharing:hO,editable:b()}),yO=S({multiUser:b()}),bO=hO.omit({owner:!0}),xO=S({run:A,fn:k,share:bO}),SO=S({run:A,fns:x(k).max(1e3)}),CO=S({source:E([`fn`,`context`,`system`,`person`,`group`,`model`,`resource`,`type`,`kind`]),text:v().optional(),values:x(v()).max(200).optional(),limit:y().int().min(1).max(50).optional()}),wO=S({value:v(),label:v(),hint:v().optional(),icon:v().optional(),missing:b().optional()}),TO=S({on:b(),ask:b()}),EO=w(`flow`,[S({flow:D(`oauth`)}),S({flow:D(`form`),form:yT})]),DO=S({flow:EO.optional(),share:b().default(!1),title:v().min(1)}),OO=v().regex(Nl).brand(),kO=C([OO,S({arg:k})]),AO=S({title:v(),description:v(),icon:v().optional(),how:EO,settings:yT,fns:T(k,TO),scope:E([`system`,`instance`,`key`]).optional(),keys:S({type:I}).optional(),defaults:TO.optional()}),jO=E([`pending`,`connected`,`expired`,`failed`]),MO=S({label:v(),detail:v().optional(),choices:T(v(),x(wO)).optional()}),NO=S({id:jl,system:F,instance:L.optional(),key:OO.optional(),owner:M,status:jO,account:MO.optional(),credentials:Cl.optional(),expiresAt:N.optional(),settings:O,fns:T(k,TO),share:bO,problem:v().optional(),createdAt:N,updatedAt:N}).omit({credentials:!0}),PO=S({system:F,decl:AO,ready:b(),connections:x(NO),instances:x(S({instance:L,label:v(),connect:DO})).optional(),keys:x(S({key:OO,label:v(),connect:DO,host:v().optional()})).optional()}),FO=S({id:jl,owner:M,credentials:O,settings:O}),IO=S({connection:jl,owner:M,redirect:Ls(),state:v(),instance:L.optional(),key:OO.optional()}),LO=S({connection:jl,owner:M,instance:L.optional(),key:OO.optional(),redirect:Ls(),answer:C([S({params:T(v(),v())}),S({form:O})])}),RO=C([S({account:MO,credentials:O,expiresAt:N.optional()}),S({problem:v()})]),zO=S({connection:jl,update:C([S({credentials:O,expiresAt:N.optional()}),S({expired:v()})])}),BO=S({connection:jl,settings:O.optional(),fns:T(k,TO).optional(),share:bO.optional()}),VO=[`embedding`,`imageEmbedding`],HO=S({input:P,output:P,cached:P.optional(),cacheWrite:P.optional()}),UO=S({id:v().min(1),name:v().optional(),capabilities:x(v()),contextWindow:y().int().min(1),maxOutput:y().int().min(1).optional(),pricing:HO,caching:b(),dimensions:y().int().min(1).optional(),maxInput:y().int().min(1).optional(),maxQuestions:y().int().min(1).optional(),maxRequestBytes:y().int().min(1).optional()}).refine(e=>!VO.some(t=>e.capabilities.includes(t))||e.dimensions!==void 0,{message:`An embedding model says how many dimensions its vectors have.`,path:[`dimensions`]}),WO=S({name:k,description:v(),models:x(UO),runtime:D(!0).optional(),instance:L.optional()}),GO=S({provider:k,model:v(),request:_D,stream:b(),run:A.optional()}),KO=w(`type`,[S({type:D(`chunk`),chunk:dD}),S({type:D(`done`),usage:lD}),S({type:D(`error`),message:v(),kind:E([`model`,`limit`,`provider`,`auth`])})]),qO=S({id:v().min(1),contextWindow:y().int().min(1).optional(),maxOutput:y().int().min(1).optional(),maxQuestions:y().int().min(1).optional(),maxRequestBytes:y().int().min(1).optional()}),JO=S({provider:k}),YO=w(`listed`,[S({listed:D(!0),models:x(qO)}),S({listed:D(!1)})]),XO=S({provider:k,model:v(),input:wD,questions:TD}),ZO=S({answers:OD,tokens:y().int().min(0).optional()}),QO=S({image:v().regex(/^(https?:|data:)/,`an http(s) or data URL`),mimeType:v().optional()}),$O=C([v(),QO]),ek=S({provider:k,model:v(),inputs:x($O).min(1)}),tk=S({vectors:x(x(y())),tokens:y().int().min(0).optional()});function nk(e){return S({provider:D(`aws`),region:v().min(1),auth:w(`kind`,[S({kind:D(`keys`),accessKeyId:v().min(1),secretAccessKey:e,sessionToken:e.optional()}),S({kind:D(`apiKey`),apiKey:e})]),profilePrefix:v().optional()})}var rk=S({input:b(),output:b()}),ik=C([S({ok:D(!0)}),S({ok:D(!1),reason:v().min(1)})]),ak=C([S({ok:D(!0)}),S({ok:D(!1),action:E([`retry`,`stop`]),reason:v().min(1)})]),ok=w(`phase`,[S({phase:D(`input`),run:sE,fn:v(),args:O}),S({phase:D(`output`),run:sE,fn:v(),args:O,result:O,attempt:y().int().min(1)})]),sk=C([ak,ik]),ck=S({kind:E([`builtin`,`dynamic-import`,`dynamic-require`,`eval`,`new-function`]),line:y().int().min(1),detail:v(),code:v()}),lk=S({size:y().int().min(0),builtins:x(v()),concerns:x(ck),urls:x(v()),hosts:x(v())}),uk=E([`passed`,`failed`,`skipped`]),dk=S({file:v().min(1),name:v().min(1),status:uk,duration:Ml,real:b().optional(),error:v().max(4e3).optional()}),fk=[`phone`,`desktop`],pk=E(fk);E([`empty`,`loading`,`error`,`typical`,`long`]);var mk=S({component:v().min(1),state:v().min(1),viewport:pk,theme:E([`light`,`dark`]),image:Zx}),hk=S({scan:lk,tests:S({system:F,version:v().min(1),ranAt:N,duration:Ml,passed:y().int().min(0),failed:y().int().min(0),skipped:y().int().min(0),cases:x(dk).max(500),more:y().int().min(0).optional(),previews:x(mk).max(200).optional()}).optional()}),gk=E([`ai`,`embed`,`resources`,`fns`,`search`,`decide`,`approvals`,`connections`,`settings`,`state`,`data`,`runs`]),_k=S({roles:x(qD).optional(),models:x(v().min(1)).optional(),perRun:P.optional(),perDay:P.optional()}),vk=S({read:x(v().min(1)),write:x(v().min(1))}),yk=S({hub:x(gk),models:_k.optional(),secrets:x(v().min(1)).optional(),calls:x(C([I,F])).optional(),network:x(v().min(1)).optional(),files:vk.optional()}),bk=S({component:v().min(1),mode:E([`replace`,`beside`])}),xk=[`installed`,`live`],Sk=E(xk),Ck=[`text`,`integer`,`number`,`boolean`,`date`,`datetime`,`time`,`uuid`,`json`,`binary`],wk=E(Ck),Tk=E([`group`,`measure`,`attribute`]),Ek=S({name:k,label:v().min(1),accepts:x(wk).min(1),required:b(),many:b(),min:y().int().min(1).optional(),role:E([`group`,`measure`]).optional()}),Dk=w(`rule`,[S({rule:D(`distinct`),channel:k,max:y().int().min(1),min:y().int().min(1).optional()}),S({rule:D(`non-negative`),channel:k}),S({rule:D(`bounded`),channel:k}),S({rule:D(`distinct-columns`),channels:x(k).min(2)}),S({rule:D(`links`),from:k,to:k})]),Ok=E([`window`,`top-n`,`partition`,`aggregate`]),kk=S({name:k,label:v().min(1),whole:D(!0).optional(),needs:x(k).optional(),columns:T(k,S({min:y().int().min(0).optional(),max:y().int().min(0).optional()})).optional(),rules:x(Dk).optional()}),Ak=S({claim:D(`range`),channel:k}),jk=E([`floor`,`structural`,`encoded`,`time-encoded`]),Mk=E([`temporal-key`,`low-cardinality`,`enum-key`,`high-null`,`many-categories`]),Nk=S({channels:x(Ek).min(1),rows:S({min:y().int().min(0),max:y().int().min(1).optional()}),whole:b(),rules:x(Dk).default([]),size:Ok.optional(),styles:x(kk).min(1).default([{name:`default`,label:`Default`}]),claims:x(Ak).default([]),priority:S({band:jk,terms:x(Mk)}).default({band:`structural`,terms:[]}),pageSize:y().int().min(1).max(500).optional()}),Pk=S({name:k,description:v(),data:yT}),Fk=S({registry:I,name:k,label:v().min(1),description:v().optional(),icon:v().optional(),shape:Nk.optional()}),Ik=Fk.extend({system:F}),Lk=S({name:v().min(1),label:v().optional(),kind:wk,nullable:b(),type:yT.optional(),ref:I.optional(),role:Tk.optional(),key:b().optional(),editable:b().optional()}),Rk=S({column:v().min(1),dir:E([`asc`,`desc`])}),zk=S({fn:I,args:T(v(),O),keys:x(v().min(1))}),Bk=S({columns:x(Lk),rows:x(x(O)),offset:y().int().min(0),limit:y().int().min(1).optional(),total:y().int().min(0).optional(),truncated:b(),sort:x(Rk),write:S({affected:y().int().min(0)}).optional(),records:S({type:I,id:v().min(1)}).optional(),drill:zk.optional()}),Vk=S({flag:E([`delete-fns`,`write-fns`,`runs`,`injects`,`effects`,`capabilities`,`secrets`,`hosts`,`files`,`calls`,`models`]),line:v().min(1),items:x(v().min(1)),lead:v().min(1).optional(),tail:v().min(1).optional()}),Hk=S({section:v().min(1),added:y().int().min(0),changed:y().int().min(0),removed:y().int().min(0)}),Uk=E([`widened`,`narrowed`,`changed`,`added`]),Wk=S({line:v(),counts:x(Hk),flags:x(Vk),grants:Uk.optional(),config:E([`added`,`changed`,`removed`]).optional()}),Gk=E([`gitignored`,`env`,`key`,`credential`,`token`,`secret-content`,`runs-code`,`unknown-path`]),Kk=E([`allow`,`ask`,`refuse`]),qk=E([`ask`,`refuse`]),Jk=w(`type`,[S({type:D(`glob`),glob:v().min(1)}),S({type:D(`content`),pattern:v().min(1)}),S({type:D(`gitignored`)})]);S({name:v().min(1),kind:Gk,match:Jk,except:x(v().min(1)).optional(),read:Kk,write:qk,why:v().min(1)});var Yk=S({path:v().min(1),kind:Gk,rule:v().min(1),access:E([`read`,`write`]),action:E([`allow`,`ask`,`refuse`]),why:v().min(1),certain:b()}),Xk=S({flags:x(Yk)}),Zk=w(`type`,[S({type:D(`text`),text:v()}),S({type:D(`code`),language:v(),code:v(),title:v().optional()}),S({type:D(`table`),title:v(),table:Bk}),S({type:D(`type-diff`),name:v(),before:yT.optional(),after:yT.optional(),changes:x(v()),breaks:x(S({fn:v(),why:v()}))}),S({type:D(`flags`),flags:x(Yk).min(1)})]),Qk=S({kind:D(`system-install`),system:F,instance:L,version:v().min(1),manifestHash:v().min(1),bundleHash:v().min(1),sourceHash:v().min(1),host:ql,source:v().min(1).optional(),grants:yk.optional(),replaces:S({version:v().min(1),manifestHash:v().min(1)}).optional()}),$k=w(`kind`,[Qk]),eA=S({title:v().min(1),parts:x(Zk),irreversible:b(),subject:$k.optional(),checks:hk.optional(),summary:Wk.optional()}),tA=E([`person`,`admins`]),nA=S({preview:b(),remember:b(),approver:tA.optional()}),rA=S({run:A,fn:k,args:O,user:iE,kind:Pl.optional(),payload:O.optional()}),iA=S({run:A,fn:k,args:O,user:iE,deadline:N}),aA=S({problems:x(bE)}),oA=S({type:yT,into:k,label:v().min(1).max(80).optional()}),sA=S({fn:k,args:O,key:v().min(1),parent:A.optional(),approver:tA,for:M.optional(),chat:j.optional(),ask:oA.optional(),preview:eA}).refine(e=>e.parent!==void 0||e.approver===`admins`||e.for!==void 0,{message:"A run proposed outside a run waits for an admin, or for the person named in `for`.",path:[`approver`]}),cA=S({by:M,preview:eA}),lA=S({run:A,subject:Qk}),uA=S({token:v().min(1),expiresAt:N}),dA=S({run:A,approval:gl}),fA=v().regex(/^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)*$/),pA=x(fA),mA=`•••• kept`,hA=S({$secret:Cl,json:D(!0).optional()}),gA=v().regex(/^[a-z][a-z0-9-]{0,39}$/,`a page segment is lowercase letters, digits and dashes, starting with a letter (at most 40)`),_A=E([`main`,`hidden`]),vA=E([`app`,`admin`]),yA=E([`everyone`,`admin`]),bA=S({segment:gA,title:v().trim().min(1).max(40),description:v().optional(),icon:v().min(1).optional(),nav:_A.default(`main`),access:yA.default(`everyone`),area:vA.optional(),component:v().min(1)});function xA(e){let t=new Set;return e.flatMap(e=>t.has(e.segment)?[`page ${e.segment} is declared twice`]:(t.add(e.segment),[]))}var SA=x(bA).superRefine((e,t)=>{for(let n of xA(e))t.addIssue({code:`custom`,message:n})}),CA=bA.extend({system:F,client:S({url:v().min(1),hash:v().min(1)})}),wA=S({instance:L,description:v(),online:b(),version:v()}),TA=`http://127.0.0.1:11434`;function EA(e){return w(`provider`,[S({provider:D(`openai`),apiKey:e,baseURL:Ls().optional()}),S({provider:D(`anthropic`),apiKey:e}),S({provider:D(`google`),apiKey:e}),S({provider:D(`openrouter`),apiKey:e}),S({provider:D(`ollama`),baseURL:Ls().default(TA),contextWindow:y().int().min(256).optional(),decisionModels:x(v().min(1)).optional()}),nk(e)])}var DA=EA(Cl),OA=E(DA.options.map(e=>e.shape.provider.value));S({id:Tl,config:DA,createdAt:N}),S({id:Cl,name:v(),owner:M,ciphertext:v(),createdAt:N});var kA=S({id:wl,name:v(),description:v(),models:x(v())}),AA=w(`scope`,[S({scope:D(`hub`)}),S({scope:D(`group`),group:M}),S({scope:D(`user`),user:M}),S({scope:D(`session`),session:j}),S({scope:D(`turn`),turn:cl}),S({scope:D(`system`),system:F}),S({scope:D(`fn`),fn:I}),S({scope:D(`model`),model:v()})]),jA=E([`hub`,`group`,`user`,`session`,`turn`]),MA=w(`scope`,[S({scope:D(`hub`)}),S({scope:D(`group`),group:M}),S({scope:D(`user`),user:M}),S({scope:D(`session`),session:j}),S({scope:D(`turn`),turn:cl})]),NA=S({id:_l,target:AA,period:C([S({window:Ml}),D(`all-time`),D(`per-turn`)]),maxCost:P,maxTokens:y().int().optional(),maxCalls:y().int().optional(),maxTime:Ml.optional(),share:E([`pooled`,`each`]).optional(),onLimit:E([`wait`,`refuse`,`ask`]),setBy:M}),PA=S({id:vl,target:MA,default:Rl.optional(),max:Rl.optional(),setBy:M}),FA=S({priority:Rl,priorityFrom:S({default:jA,cappedBy:jA.optional()}),turn:S({cost:P,time:Ml}),budgets:x(S({rule:_l,scope:AA,remaining:P})),limitedBy:_l.optional()});S({id:yl,budgets:x(_l),estimate:P,createdAt:N,settled:S({cost:P,at:N}).optional()}),S({id:bl,at:N,cost:P,tokens:y().int().min(0),actor:M,system:F.optional(),session:j.optional(),fn:I,model:v().optional(),llmCall:fl.optional(),modelCall:Ol.optional(),run:A});var IA=E([`chat`,`admin`,`disconnected`,`needs-config`,`held`,`removed`]),LA=S({prompt:x(S({name:F,label:v(),description:v(),summary:v().optional()})),on:x(F),off:x(S({name:F,why:IA}))}),RA=S({name:F,reason:v(),label:v().optional(),description:v().optional()}),zA=RegExp(`(\\d+)`,`g`);function BA(e,t=[]){let n=new Map(t.map(e=>[e.index,e.number]));return e.replace(zA,(e,t)=>{let r=n.get(Number(t));return r===void 0?``:`[${r}]`})}function VA(e){let t=e.trim().replace(/^\$\.?/,``);if(t===``)return[];let n=[],r=/\[\s*(?:"([^"]*)"|'([^']*)'|(\d+))\s*\]|([^.[\]]+)/y,i=0;for(;i<t.length;){if(t[i]===`.`){i+=1;continue}r.lastIndex=i;let e=r.exec(t);if(e===null)return;n.push(e[1]??e[2]??e[3]??e[4]??``),i=r.lastIndex}return n}function HA(e){try{return O.parse(JSON.parse(e))}catch{return}}function UA(e,t){let n=VA(t);if(n===void 0)return;let r=e;for(let e of n){let t=typeof r==`string`?HA(r):r;if(Array.isArray(t)){if(!/^\d+$/.test(e))return;let n=t[Number(e)];if(n===void 0)return;r=n}else if(typeof t==`object`&&t){if(!Object.hasOwn(t,e))return;let n=t[e];if(n===void 0)return;r=n}else return}return{value:r}}var WA=S({index:y().int().min(1),number:y().int().min(1),tool:v(),path:v(),note:v()}),GA=E([`result`,`reply`]),KA=WA.extend({run:A.optional(),fn:I.optional(),found:GA.optional(),value:O.optional(),large:D(!0).optional(),problem:v().optional()}),qA=S({prompt:b(),on:b()}),JA=y().int().min(0).max(3),YA=S({agent:I,model:aD.optional(),mode:sx.optional(),contextor:vx.optional(),fnMode:Px.optional(),systems:C([x(F),D(`all`)]),instructions:v().optional(),citations:b().optional()}),XA=YA.partial(),ZA=x(S({label:v().trim().min(1).max(40).optional(),settings:XA})).min(2).max(4),QA=S({turn:cl,variant:JA,label:v()}),$A=S({variant:JA,label:v(),settings:XA,session:j,turn:cl}),ej=S({run:A,fn:I}),tj=S({variant:JA,effects:x(ej)}),nj=S({variant:JA,label:v(),effects:x(ej).min(1)}),rj=S({variants:x($A).min(2).max(4),reserved:P,chosen:JA.optional(),chosenBy:M.optional(),chosenAt:N.optional(),discarded:x(tj)}),ij=S({field:v(),type:v(),before:O.optional(),after:O.optional()}),aj=S({id:A,fn:I,fnVersion:v(),kind:Pl,system:F,instance:L.optional(),parent:A.optional(),root:A,turn:cl,session:j.optional(),key:v(),actor:M,caller:M,connection:jl.optional(),llmCall:fl.optional(),toolCallId:v().optional(),args:O,repairs:x(xE).optional(),test:b().optional(),status:TE,awaitingSystem:b().optional(),text:zT.optional(),outcome:NE.optional(),progress:hE.optional(),allowed:dE,cost:P,totalCost:P,priority:Rl,background:b(),attempt:y().int().min(1),errors:x(S({attempt:y().int(),error:vE,cost:P,at:N})),undo:O.optional(),resume:O.optional(),stateChanges:x(ij),tokens:y().int().min(0).optional(),createdAt:N,approvedAt:N.optional(),startedAt:N.optional(),endedAt:N.optional(),resultRevision:y().int().min(1).optional(),resultUpdatedAt:N.optional(),resultUpdatedBy:M.optional()}),oj=aj.pick({id:!0,fn:!0,status:!0,cost:!0,totalCost:!0,startedAt:!0,endedAt:!0}),sj=S({session:j,system:F,name:v(),type:v(),def:yT,value:O,version:y().int().min(1),updatedBy:C([S({run:A}),S({delivery:ul})]),updatedAt:N}).pick({name:!0,type:!0}).extend({value:O.optional()}),cj=E([`queued`,`delivered`,`done`,`failed`,`expired`]),lj=S({id:ul,system:F,kind:C([S({action:v(),input:O}),S({form:A,value:O})]),session:j,actor:M,run:A.optional(),status:cj,result:O.optional(),error:vE.optional(),attempts:y().int().min(0),createdAt:N,deliveredAt:N.optional(),doneAt:N.optional(),expiresAt:N.optional()}).pick({id:!0,status:!0,result:!0,error:!0}),uj=S({id:dl,run:A,handler:v(),args:O,decl:S({description:v(),args:yT,returns:yT}),answerer:C([S({user:M}),S({system:F,run:A})]),status:E([`pending`,`answered`,`failed`]),result:O.optional(),createdAt:N}),dj=E([`running`,`done`,`failed`,`cancelled`,`paused`,`undone`]),fj=S({transcript:y().int().min(0),tools:x(I),context:x(I),selection:Mx.optional(),suggested:x(I).optional(),announcedSystems:LA.optional(),citationsTold:qA.optional()});S({id:cl,session:j.optional(),message:ll.optional(),actor:M,user:iE,time:aE,client:cE.optional(),root:A.optional(),status:dj,limits:FA,cost:P,errors:C([S({max:y().int().min(1)}),D(`feed-back`)]),start:fj.optional(),compare:rj.optional(),createdAt:N,continuedAt:N.optional(),endedAt:N.optional()});var pj=E([`queued`,`streaming`,`done`,`failed`,`aborted`]),mj=S({content:v(),reasoning:v().optional(),toolCalls:x(dD.shape.toolCall.unwrap()).optional(),finishReason:dD.shape.finishReason.unwrap(),refusal:v().optional()}),hj=S({id:fl,turn:cl,run:A,session:j.optional(),system:F.optional(),iteration:y().int().min(0),provider:v(),model:v(),request:_D,response:mj.optional(),usage:lD.optional(),cost:P,status:pj,error:v().optional(),priority:Rl,selection:kx.optional(),modelCall:Ol.optional(),queuedAt:N,startedAt:N.optional(),firstTokenAt:N.optional(),endedAt:N.optional()}),gj=Kc(()=>S({run:oj,llmCalls:x(hj.pick({id:!0,model:!0,cost:!0,status:!0})),children:x(gj)})),_j=S({turn:cl,undone:x(S({run:A,fn:I,summary:v()})),failed:x(S({run:A,fn:I,error:vE})),notUndoable:x(S({run:A,fn:I})),kept:x(nj).optional(),session:S({messages:y().int().min(0),unloaded:x(I),reloaded:x(I)}).optional()});S({run:A,turn:cl,session:j.optional(),iteration:y().int().min(0),priority:Rl}),S({run:A,priority:Rl});var vj=[`system`,`instance`,`fn`,`context`,`type`,`kind`,`resource`,`root`,`component`,`registry`,`command`,`provider`],yj=E(vj),bj=[`brings`,`names`,`loads`,`next`,`reads`,`writes`,`calls`,`uses`,`kind`,`creates`,`updates`,`removes`,`refers`,`renders`,`contributes`,`belongs`],xj=E(bj),Sj=[...xk,`pending`];E(Sj);var Cj=E([`text`,`enum`,`number`,`date`,`boolean`]);E([`is`,`isNot`,`in`,`notIn`,`gt`,`gte`,`lt`,`lte`,`between`,`empty`,`notEmpty`,`contains`]);var wj={text:[`contains`,`is`,`isNot`,`in`,`notIn`,`empty`,`notEmpty`],enum:[`is`,`isNot`,`in`,`notIn`,`empty`,`notEmpty`],number:[`gt`,`gte`,`lt`,`lte`,`between`,`is`,`isNot`,`empty`,`notEmpty`],date:[`gt`,`gte`,`lt`,`lte`,`between`,`empty`,`notEmpty`],boolean:[`is`]},Tj={is:`is`,isNot:`is not`,in:`in`,notIn:`not in`,gt:`>`,gte:`≥`,lt:`<`,lte:`≤`,between:`between`,empty:`is empty`,notEmpty:`is not empty`,contains:`contains`},Ej=C([v(),y(),b()]),Dj=E([`usd`,`ms`,`tokens`,`bytes`,`count`]);S({label:v(),type:Cj,sortable:b(),filterable:b(),values:x(v()).readonly().optional(),dynamic:b().optional(),unit:Dj.optional()});var Oj=v().min(1),kj=w(`op`,[S({field:Oj,op:E([`is`,`isNot`,`gt`,`gte`,`lt`,`lte`,`contains`]),value:Ej}),S({field:Oj,op:E([`in`,`notIn`]),values:x(Ej).min(1)}),S({field:Oj,op:D(`between`),from:Ej,to:Ej}),S({field:Oj,op:E([`empty`,`notEmpty`])})]),Aj=S({field:Oj,dir:E([`asc`,`desc`])}),jj=Hl.extend({text:v().optional(),filters:x(kj).max(20).optional(),sort:x(Aj).max(3).optional()}),Mj=(e,t={})=>({label:e,type:`text`,sortable:!0,filterable:!0,...t}),Nj=(e,t)=>({label:e,type:`enum`,sortable:!0,filterable:!0,values:t}),Pj=e=>({label:e,type:`enum`,sortable:!0,filterable:!0,dynamic:!0}),Fj=(e,t)=>({label:e,type:`number`,sortable:!0,filterable:!0,unit:t}),Ij=e=>({label:e,type:`date`,sortable:!0,filterable:!0}),Lj=e=>({label:e,type:`boolean`,sortable:!1,filterable:!0}),Rj=e=>({...e,sortable:!1}),zj=[`resources`,`fns`,`runs`,`modelCalls`,`llmCalls`,`sessions`,`contexts`,`notifications`,`systems`,`types`,`graph`,`users`,`groups`],Bj=E(zj),Vj={resources:{fields:{name:Mj(`Name`),system:Pj(`System`),family:Nj(`Type`,GE),source:Nj(`Source`,HE),forms:{...Nj(`Forms`,aS.options),sortable:!1},size:Fj(`Size`,`bytes`),seenAt:Ij(`Seen`),modifiedAt:Ij(`Modified`)},defaultSort:[{field:`seenAt`,dir:`desc`}]},fns:{fields:{name:Mj(`Name`),system:Pj(`System`),kind:Pj(`Kind`),available:Lj(`Available`),paused:Lj(`Paused`),disabled:Lj(`Disabled`),runs:Fj(`Runs`,`count`),failures:Fj(`Failures`,`count`),averageCost:Fj(`Avg cost`,`usd`),averageTime:Fj(`Avg time`,`ms`),lastRunAt:Ij(`Last run`),updatedAt:Ij(`Updated`)},defaultSort:[{field:`name`,dir:`asc`}]},runs:{fields:{fn:Pj(`Fn`),system:Pj(`System`),status:Nj(`Status`,wE),session:Pj(`Session`),actor:Pj(`By`),cost:Fj(`Cost`,`usd`),duration:Fj(`Duration`,`ms`),createdAt:Ij(`Started`),endedAt:Ij(`Ended`)},defaultSort:[{field:`createdAt`,dir:`desc`}]},modelCalls:{fields:{modality:Nj(`Modality`,AD),model:Pj(`Model`),provider:Pj(`Provider`),system:Pj(`System`),status:Nj(`Status`,zD.options),session:Pj(`Session`),cost:Fj(`Cost`,`usd`),tokens:Fj(`Tokens`,`tokens`),duration:Fj(`Duration`,`ms`),createdAt:Ij(`Started`)},defaultSort:[{field:`createdAt`,dir:`desc`}]},llmCalls:{fields:{model:Pj(`Model`),system:Pj(`System`),status:Nj(`Status`,pj.options),session:Pj(`Session`),cost:Fj(`Cost`,`usd`),tokens:Fj(`Tokens`,`tokens`),duration:Fj(`Duration`,`ms`),createdAt:Ij(`Started`)},defaultSort:[{field:`createdAt`,dir:`desc`}]},sessions:{fields:{title:Mj(`Title`),agent:Pj(`Agent`),status:Nj(`Status`,[`idle`,`running`,`paused`]),archived:Lj(`Archived`),createdAt:Ij(`Created`),updatedAt:Ij(`Updated`)},defaultSort:[{field:`updatedAt`,dir:`desc`}]},contexts:{fields:{name:Mj(`Name`),system:Pj(`System`),origin:Nj(`Origin`,bS),tags:Pj(`Tag`),status:Nj(`Status`,LS),askedBy:Nj(`Asked by`,VS),stale:Lj(`Stale`),tokens:Fj(`Tokens`,`tokens`),lastModified:Ij(`Last modified`),updatedAt:Ij(`Updated`)},defaultSort:[{field:`updatedAt`,dir:`desc`}]},notifications:{fields:{kind:Pj(`Kind`),read:Lj(`Read`),createdAt:Ij(`Received`)},defaultSort:[{field:`createdAt`,dir:`desc`}]},systems:{fields:{name:Mj(`Name`),status:Pj(`Status`),version:Mj(`Version`),instances:Fj(`Instances`,`count`),fns:Fj(`Fns`,`count`),context:Fj(`Context`,`count`),types:Fj(`Types`,`count`),parts:Fj(`Other parts`,`count`),pending:Fj(`Pending changes`,`count`),refusals:Fj(`Refusals`,`count`),lastSeenAt:Ij(`Last seen`)},defaultSort:[{field:`name`,dir:`asc`}]},types:{fields:{name:Mj(`Name`),system:Pj(`System`),instance:Pj(`Instance`),references:Fj(`Refers to`,`count`),updatedAt:Ij(`Updated`)},defaultSort:[{field:`name`,dir:`asc`}]},graph:{fields:{name:Rj(Mj(`Name`)),system:Rj(Pj(`System`)),nodeKind:Rj(Nj(`Item`,vj)),edgeKind:Rj(Nj(`Link`,bj)),fnKind:Rj(Pj(`Fn kind`)),mode:Rj(Pj(`Mode`)),effect:Rj(Pj(`Effect on`)),visibility:Rj(Nj(`Visible to`,zl.options)),stage:Rj(Nj(`Stage`,Sj)),on:Lj(`On`)},defaultSort:[]},users:{fields:{name:Mj(`Name`),email:Mj(`Email`),role:Nj(`Role`,[`admin`,`member`]),disabled:Lj(`Disabled`),createdAt:Ij(`Added`)},defaultSort:[{field:`name`,dir:`asc`}]},groups:{fields:{name:Mj(`Name`),createdAt:Ij(`Added`)},defaultSort:[{field:`name`,dir:`asc`}]}};function Hj(e,t){return t.sort!==void 0&&t.sort.length>0?t.sort:Vj[e].defaultSort}var Uj=S({value:Ej,label:v().optional(),count:y().int().min(0)}),Wj=S({list:Bj,field:Oj,prefix:v().optional(),limit:y().int().min(1).max(50).optional()}),Gj=S({list:Bj,query:jj.default({})}),Kj=Vl(Zc()).extend({sort:x(Aj),total:y().int().min(0).optional(),partial:D(!0).optional().describe(`More rows than the hub reads at once: more may match; narrow the filters for a full answer.`)}),qj=sl.record,Jj=S({shape:E([`table`,`value`]),owner:E([`shared`,`person`]),writers:D(`admins`).optional(),search:S({text:x(v().min(1)),embed:b()})}),Yj=S({id:qj,type:I,value:O,owner:M.optional(),title:v(),version:y().int().min(1),createdAt:N,updatedAt:N,updatedBy:M.optional(),updatedBySystem:F.optional(),run:A.optional()}),Xj=S({id:v().min(1),record:qj,type:I,number:y().int().min(1),change:E([`created`,`updated`,`removed`]),value:O,by:M.optional(),bySystem:F.optional(),run:A.optional(),at:N}),Zj=S({type:I,query:jj.optional(),search:v().min(1).optional(),run:A.optional()}),Qj=Vl(Yj),$j=Zj.extend({query:jj.omit({cursor:!0,limit:!0}).optional(),offset:y().int().min(0).optional(),limit:y().int().min(1).max(500).optional()}),eM=S({type:I,id:qj,run:A.optional()}),tM=S({type:I,id:qj.optional(),value:O,expect:y().int().min(1).optional(),run:A.optional(),owner:M.optional()}),nM=S({type:I,id:qj,set:T(v().min(1),O).refine(e=>Object.keys(e).length>0,`set at least one field`),expect:y().int().min(1).optional(),run:A.optional()}),rM=S({type:I,id:qj,run:A.optional()}),iM=Hl.extend({type:I,id:qj}),aM=Vl(Xj),oM=S({type:I,system:F,description:v(),storage:Jj,records:y().int().min(0),updatedAt:N.optional()}),sM=Hl.extend({text:v().optional(),system:F.optional()}),cM=Vl(oM),lM=`general`,uM=S({name:k,title:v().min(1),description:v().min(1)}),dM=E([`sqlite`,`postgres`,`sqlserver`]),fM=dM.options,pM=S({description:v().min(1).max(500),vectors:b().default(!1),engines:x(dM).min(1).default([...fM])}),mM=v().regex(/^[A-Za-z0-9][A-Za-z0-9_.-]{0,99}$/,`A migration id is letters, digits, dots, dashes and underscores, starting with a letter or digit.`),hM=v().regex(/^[A-Za-z_][A-Za-z0-9_]{0,62}$/,`A schema name is letters, digits and underscores, starting with a letter or underscore.`),gM=E([`postgres`,`sqlserver`]);E([`system`,`hub`,`external`]);var _M=`system`,vM=w(`placement`,[S({placement:D(`system`)}),S({placement:D(`hub`)}),S({placement:D(`external`),engine:gM,connection:hA,schema:hM})]),yM=w(`placement`,[S({placement:D(`system`)}),S({placement:D(`hub`)}),S({placement:D(`external`),engine:gM,connection:v().min(1).max(4e3),schema:hM})]),bM=w(`placement`,[S({placement:D(`system`)}),S({placement:D(`hub`)}),S({placement:D(`external`),engine:gM,connection:v().min(1),schema:hM})]),xM=[`sqlite`,`postgres`,`sqlserver`],SM={postgres:`Postgres with the pgvector extension installed (CREATE EXTENSION vector)`,sqlserver:`SQL Server 2025 or newer, which has the VECTOR type`};function CM(e){return e.placement===`external`&&e.engine!==void 0?e.engine:`sqlite`}function wM(e,t){let n=CM(t),r=t.placement===`external`?`an external ${n} database`:`the ${t.placement===`hub`?`hub`:`system`} (SQLite)`;return e.engines.includes(n)?e.vectors&&!xM.includes(n)?[`This store keeps vectors, which ${r} can't hold.`]:[]:[`This store runs only on ${e.engines.join(`, `)}, so it can't be kept in ${r}.`]}var TM=E([`preparing`,`migrating`,`ready`,`moving`,`failed`]),EM=S({applied:x(S({id:mM,checksum:v().min(1),at:N})),pending:x(mM)}),DM=S({name:v().min(1).max(200),rows:y().int().min(0)}),OM=S({bytes:y().int().min(0).optional(),tables:x(DM).max(200),at:N,more:b().optional()}),kM=S({state:TM,engine:dM,migrations:EM,error:v().max(4e3).optional(),measure:OM.optional()}),AM=kM.extend({at:N}),jM=w(`placement`,[S({placement:D(`system`)}),S({placement:D(`hub`)}),S({placement:D(`external`),engine:gM,schema:hM})]),MM=v().regex(/^[0-9a-z][0-9a-z_.-]{0,120}$/),NM=S({id:MM,system:v(),instance:v(),where:jM,bytes:y().int().min(0).optional(),at:N,reason:E([`move`,`removed`]),orphaned:b().default(!1)}),PM=v().regex(/^move_[0-9a-z]{8,40}$/),FM=E([`draining`,`waiting`,`copying`,`switching`,`done`,`failed`]),IM=E([`ask`,`cancel`,`wait`]),LM=E([`cancel`,`wait`]),RM=S({step:E([`exporting`,`transferring`,`migrating`,`copying`,`checking`]).optional(),tables:S({done:y().int().min(0),total:y().int().min(0)}),table:v().max(200).optional(),rows:y().int().min(0),bytes:S({done:y().int().min(0),total:y().int().min(0)})}),zM=S({move:PM,system:v(),instance:v(),from:jM,to:jM,phase:FM,runs:IM,running:x(v()),asking:N.optional(),progress:RM,startedAt:N,endedAt:N.optional(),by:v(),backups:x(NM),error:v().max(4e3).optional()}),BM=S({placement:vM,status:AM.optional(),backups:x(NM).optional()}),VM=S({system:v(),instance:v(),decl:pM,placement:jM,status:AM.optional(),holding:b(),measure:OM.optional(),file:S({bytes:y().int().min(0),snapshots:x(S({name:v(),bytes:y().int().min(0),at:N}))}).optional(),backups:x(NM).default([]),move:zM.optional()}),HM=v().regex(/^lease_[0-9a-z]{8,40}$/),UM=S({$bytes:v()}),WM=C([v(),y(),ic(),UM]),GM=S({sql:v().min(1).max(1e6),params:x(WM).max(32766),lease:HM.optional()}),KM=S({rows:x(T(v(),WM)),changes:y().int().min(0).optional(),insertId:y().int().optional()}),qM=S({lease:HM,expiresAt:N}),JM=v().regex(/^[0-9a-z][0-9a-z_.-]{0,120}\.db$/);function YM(e){for(let t of e.matchAll(WT)){let n=(t[1]??``).trim();if(!n.startsWith(`args.`))return`the claim "${e}" uses {${n}}: a claim reads only its call's args ({args.path})`}}var XM=v().min(1).max(500).superRefine((e,t)=>{let n=YM(e);n!==void 0&&t.addIssue({code:`custom`,message:n})}),ZM=S({fn:k,args:O,user:iE,caller:A,session:j.optional()}),QM=S({claims:x(v().min(1))});function $M(e){return e==null||e===``?[]:typeof e==`string`?[e]:typeof e==`number`||typeof e==`boolean`?[String(e)]:Array.isArray(e)?e.flatMap(e=>Array.isArray(e)?[JSON.stringify(e)]:$M(e)):[JSON.stringify(e)]}function eN(e,t){let n=[],r=[],i=0;for(let a of e.matchAll(WT)){n.push(e.slice(i,a.index)),i=a.index+a[0].length;let[o,...s]=(a[1]??``).trim().split(`.`),c=o===`args`?$M(YT(t,s)):[],l=a[2],u=c.length>0?c:l===void 0?[]:[l];if(u.length===0)return[];r.push(u)}n.push(e.slice(i));let a=[n[0]??``];return r.forEach((e,t)=>{let r=n[t+1]??``;a=a.flatMap(t=>e.map(e=>`${t}${e}${r}`))}),a}function tN(e,t){return[...new Set(e.flatMap(e=>eN(e,t)))]}var nN=S({label:v(),plural:v().optional(),icon:v().optional(),color:v().optional(),title:v().optional(),subtitle:v().optional()}),rN=S({name:k,description:v(),def:yT,display:nN,methods:x(k),instance:L.optional(),audience:bO.optional(),meta:T(v(),O).optional(),records:Jj.optional()}),iN=E([`user-wins`,`union`,`intersect`,`most-restrictive`]),aN=E([`self`,`fns`]),oN=S({name:k,description:v(),type:yT,appliesTo:x(Bl),merge:iN,editableBy:x(aN)}),sN=S({name:k,description:v(),data:yT}),cN=S({name:k,description:v(),applicability:v(),payload:yT,approveChanges:b(),status:RT.optional(),estimates:b().optional(),approval:nA.optional()}),lN=S({description:v(),args:yT,returns:yT,required:b()}),uN=w(`to`,[S({to:D(`instance`),instance:L}),S({to:D(`any`)})]),dN=S({args:O,result:O.optional(),note:v().optional()}),fN=E([`read`,`write`,`delete`]),pN=E([`fns`,`types`,`context`,`resources`,`kinds`,`components`,`examples`,`approvals`,`secrets`,`connections`,`records`]),mN=[`create`,`update`,`remove`],hN=E(mN),gN=S({thing:pN,action:hN,kind:Pl.optional()}).refine(e=>e.kind===void 0||e.thing===`fns`,{message:`only fns have a kind`,path:[`kind`]}),_N=E([`resources`]),vN=S({mode:fN.optional(),reads:x(I).optional(),writes:x(I).optional(),free:b().optional(),registry:x(gN).optional(),keeps:x(_N).min(1).optional()}),yN=S({language:v().min(1),code:v()}),bN=S({every:Ml.min(1e3)}),xN=E([`developer`,`admin`,`reference`]),SN=S({deps:x(I)}),CN=S({name:k,description:v(),instructions:v().optional(),kind:Pl,payload:O.optional(),readable:yN.optional(),args:yT,returns:yT,deps:x(I),handlers:T(v(),lN),progress:pE,status:RT.optional(),operations:uE,undo:yT.optional(),resume:yT.optional(),state:yT.optional(),form:yT.optional(),display:lE,limits:fE,visibility:zl,tags:x(v()),niche:xN.optional(),examples:x(dN).optional(),validate:rk.optional(),approval:nA.optional(),routing:uN.optional(),connectKey:kO.optional(),effects:vN.optional(),promptExamples:y().int().min(0).max(20).optional(),group:k.optional(),flags:b().optional(),roles:x(qD).optional(),live:bN.optional(),parallelClaims:x(XM).optional(),dynamicClaims:b().optional(),check:SN.optional()}),wN=S({name:v(),hint:v(),required:b()}),TN=S({to:I,when:v().min(1).max(200)}),EN=S({name:k,title:v().min(1).optional(),description:v(),content:v().optional(),command:S({name:v(),args:x(wN)}).optional(),imports:x(I),fns:x(I),suggestFns:x(I),suggest:zl,visible:zl,inject:Kb.optional(),tags:x(v()),niche:xN.optional(),weight:y().min(0).max(2).optional(),summary:v().optional(),parent:I.optional(),next:I.optional(),choices:x(TN).optional(),links:x(DS).optional(),question:v().min(1).max(500).optional(),when:v().min(1).max(500).optional(),lastModified:N.optional(),askedBy:HS.optional()}),DN=S({name:k,description:v(),explains:v().min(1).max(2e3).optional(),order:y(),timeout:Ml}),ON=S({name:k,title:v(),description:v(),target:yT,of:I.optional()}),kN=S({name:k,description:v(),match:cS}),AN=S({name:k,description:v(),input:yT,returns:yT,state:yT.optional(),expires:Ml.optional()}),jN=[`message`,`run`,`resources`,`system`,`fns`],MN=E(jN),NN=S({entry:v(),hash:v(),files:x(S({path:v(),size:y().int().min(0),hash:v()}))}),PN=E([`types`,`settings`,`attachments`,`kinds`,`fns`,`context`,`hooks`,`mentions`,`sectioners`,`actions`]),FN={types:x(rN),settings:x(oN),attachments:x(sN),kinds:x(cN),fns:x(CN),context:x(EN),hooks:x(DN),mentions:x(ON),sectioners:x(kN),actions:x(AN)},IN=S({name:F,version:v(),description:v(),about:v().optional(),hash:v(),...FN,events:x(MN),resources:b(),client:NN.optional(),config:yT,requires:x(F),providers:x(WO).optional(),connect:AO.optional(),registries:x(Pk).optional(),contributes:x(Fk).optional(),configSecrets:pA.optional(),runtime:bc(PN,x(k)).optional(),grants:yk.optional(),configComponent:bk.optional(),pages:SA.optional(),groups:x(uM).optional(),store:pM.optional()}),LN=S({hash:v(),upsert:S(FN).partial(),remove:bc(PN,x(k)),lists:IN.pick({providers:!0,registries:!0,contributes:!0}).optional(),roots:D(!0).optional()}),RN=S({added:x(I),updated:x(I),removed:x(I),refused:x(S({name:v(),problems:x(v())}))}),zN=S({args:yT,returns:yT,description:v(),mode:fN}),BN=S({args:yT,returns:yT,deps:x(I),types:x(I).optional(),refs:x(v()).optional(),operations:uE,handlers:T(v(),lN).optional(),progress:pE.optional(),status:RT.optional(),limits:fE.optional(),display:lE.optional(),approval:nA.optional(),effects:vN.optional(),readable:yN.optional(),connectKey:OO.optional(),parallelClaims:x(XM).optional(),examples:x(dN).min(1)});function VN(e){return e===`native`||e.startsWith(`hub/`)}function HN(e){return VN(e.kind)&&(e.examples??[]).length===0}var UN=S({session:j,turn:cl,text:v(),user:iE,time:aE}),WN=y(),GN=S({label:v(),mode:fN,blocked:v().optional(),args:v().optional(),returns:v().optional(),instructions:v().optional(),examples:x(dN).optional(),moreExamples:y().int().positive().optional()}),KN={toolset:cx.optional()},qN=w(`type`,[S({type:D(`text`),tag:v(),text:v()}),S({type:D(`suggest-context`),...KN,items:x(S({context:I,title:v().optional(),why:v().optional(),score:WN.optional()}))}),S({type:D(`suggest-fns`),...KN,items:x(S({fn:I,why:v().optional(),score:WN.optional(),card:GN.optional()}))}),S({type:D(`load`),context:x(I).optional(),fns:x(I).optional()})]),JN=S({label:v(),hint:v().optional(),icon:v().optional(),target:O}),YN=S({title:v(),subtitle:v().optional(),fields:x(S({label:v(),value:v()})).optional(),body:v().optional(),open:lS.optional(),value:O.optional()});EN.omit({name:!0,content:!0}).extend({key:k,summary:v().min(1).max(300),imports:x(I).default([]),fns:x(I).default([]),suggestFns:x(I).default([]),suggest:zl.default(`both`),visible:zl.default(`both`),tags:x(v()).default([]),lastModified:C([N,$c().transform(e=>Date.parse(e)),Qc({offset:!0}).transform(e=>Date.parse(e))]).optional()}).strict();var XN=E([`header`,`duplicate-key`,`broken-link`,`cycle`,`missing-summary`]);S({file:v().min(1),line:y().int().min(1),column:y().int().min(1),code:XN,message:v().min(1)});var ZN=S({loaded:x(I),fns:x(I),fnsRefused:x(nE),refused:x(S({context:v(),reason:v().min(1),closest:x(I)})),cards:v()}),QN=S({context:x(v().min(1)).min(1),guidance:v().min(1).max(4e3),maxDepth:y().int().min(0).max(10).default(IS.maxDepth),maxDecisions:y().int().min(1).max(4096).default(IS.maxDecisions),maxTokens:y().int().min(1).max(1e6).default(IS.maxTokens),metadataOnly:b().default(!1)}),$N=E([`start`,`import`,`choice`]),eP=S({name:I,title:v().optional(),description:v(),depth:y().int().min(0),via:$N,from:I.optional(),probability:y().min(0).max(1).optional(),tokens:y().int().min(0),content:v().optional()}),tP=E([`declined`,`max-tokens`,`max-decisions`,`max-depth`,`unavailable`,`failed`]),nP=S({context:v(),from:I.optional(),depth:y().int().min(0),reason:tP,probability:y().min(0).max(1).optional()}),rP=E([`complete`,`max-depth`,`max-decisions`,`max-tokens`,`failed`]),iP=ZN.extend({crawled:x(eP),skipped:x(nP),stop:S({reason:rP,detail:v().optional()}),depth:y().int().min(0),decisions:y().int().min(0),tokens:y().int().min(0),calls:x(Ol),metadataOnly:b()}),aP=S({loaded:x(I),refused:x(nE),cards:v()});C([aP.strict(),ZN.strict(),iP.strict()]);var oP=S({expiresIn:Ml.nullable().optional()}),sP=S({id:Al,secret:v().min(32),expiresAt:N.optional()}),cP=sP.pick({id:!0,secret:!0}),lP=S({id:Al,system:F,instance:L,secretHash:v(),previousHash:v().optional(),createdBy:M,createdAt:N,expiresAt:N.optional(),lastUsedAt:N.optional(),uses:y().int().min(0),revokedAt:N.optional()}).omit({secretHash:!0,previousHash:!0}),uP=E([`pairing`,`needs-config`,`connected`,`disconnected`,`removed`]),dP=C([S({path:v()}),S({package:v(),version:v()}),S({git:v(),ref:v()}),S({zip:v().regex(Xx),file:v()})]),fP=S({policy:E([`always`,`on-failure`,`never`]),backoff:Ml,maxPerHour:y().int().min(1)}),pP=E([`installing`,`stopped`,`starting`,`running`,`crashed`,`disabled`]),mP=S({name:F,instance:L,source:dP,dir:v(),command:S({run:v(),args:x(v()),env:T(v(),v()),cwd:v().optional()}),version:v(),goodVersion:v().optional(),autoStart:b(),restart:fP,status:pP,pid:y().int().optional(),lastExit:S({code:y().int(),at:N,output:v()}).optional(),installedBy:M,installedAt:N}),hP=S({functions:b(),renderers:b(),context:b().optional()}),gP=S({value:O,version:y().int().min(1),setBy:M,setAt:N}),_P=S({keyFingerprint:v().optional(),publicKey:v().optional(),config:gP.optional(),pairedAt:N.optional(),pairedBy:M.optional(),lastSeenAt:N.optional(),address:v().optional()}),vP=E([`one`,`many`]),yP=S({name:F,description:v(),about:v().optional(),status:uP,enabled:hP,version:v(),manifestHash:v(),defaultInstance:L.optional(),actor:M,stage:Sk.optional(),instances:vP.optional()}).extend(_P.shape),bP=S({id:pl,name:F,keyFingerprint:v(),publicKey:v(),version:v(),address:v(),method:E([`code`,`token`]),code:v().optional(),replaces:F.optional(),description:v().optional(),instance:L.optional(),configType:yT.optional(),configSecrets:pA.optional(),store:pM.optional(),status:E([`pending`,`approved`,`rejected`,`expired`]),createdAt:N,expiresAt:N});S({id:ml,name:F.optional(),tokenHash:v(),createdBy:M,expiresAt:N,usedAt:N.optional(),autoPair:oP.optional(),boundTo:S({instance:L,manifestHash:v().min(1),host:ql,run:A}).optional()}),S({system:F,manifest:IN,importedAt:N});var xP=dO.pick({averageCost:!0,averageQueued:!0,p95:!0,lastRunAt:!0}).extend({outcomes:iO.default(aO),averageTime:Ml,tokens:dO.shape.tokens.default(0)}),SP=E([`contract`,`runtime`]),CP=S({name:I,system:F,decl:CN,version:v(),origin:SP,addedBy:M.optional(),available:eE,paused:b(),disabled:b(),stats:xP,updatedAt:N});S({name:I,system:F,decl:cN});var wP=rN.omit({name:!0,methods:!0}).extend({name:I,system:F,references:x(I),declaredBy:SP.optional(),version:v().optional(),updatedAt:N}),TP=S({types:x(wP),missing:x(I)}),EP=EN.extend({alwaysFor:x(I).optional()}),DP=S({name:I,system:F,origin:yS.optional(),declaredBy:SP.optional(),version:v().optional(),decl:EP,tokens:xS.optional(),status:RS.default(`active`),statusReason:v().optional(),statusHistory:x(US).optional(),disabled:b().optional(),systemOff:b().optional(),lastModified:N.optional(),duplicate:WS.optional(),contradiction:WS.optional(),notDuplicates:x(I).optional(),checked:S({contentHash:v(),at:N}).optional(),metadata:KS.optional(),split:qS.optional(),validUntil:N.optional(),askedBy:HS.optional(),mentions:S({context:x(I),fns:x(I)}),stale:b(),updatedAt:N,wantsMetadata:b().optional(),wantsCheck:b().optional(),inReview:b().optional()});function OP(e){return e.systemOff===!0||!BS(e.status)}function kP(e){return e.lastModified??e.updatedAt}var AP=[`kinds`,`commands`,`mentions`,`hooks`,`actions`,`settings`,`attachments`,`embedders`,`sectioners`,`providers`,`registries`,`components`,`examples`],jP=E(AP),MP=S({section:jP,name:v().min(1),about:v(),origin:SP,version:v(),visibility:zl.optional(),owner:I.optional(),decl:O,on:b().optional()}),NP=S({system:F}),PP=S({parts:x(MP),more:bc(jP,y().int().min(0))});function FP(e){return rT(e?.name??`otel`,{requires:e?.requires??[]})}var IP=v().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/),LP=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i,RP=e=>e!==``&&e!==`.`&&e!==`..`&&!LP.test(e),zP=v().min(1).refine(e=>!e.includes(`\\`)&&!e.includes(`:`)&&e.split(`/`).every(RP),`A package path is relative, uses forward slashes and stays inside the package.`),BP=S({childProcess:b(),workers:b()});S({format:D(1),name:F,version:IP,description:v(),protocol:y().int().min(1),server:S({entry:zP,external:T(v(),v()).default({}),node:v().optional()}),client:S({entry:zP}).optional(),instances:vP.default(`one`),files:T(zP,v().regex(Xx)).optional(),permissions:BP.partial().optional()});var VP=S({state:v(),data:v(),cache:v()}),HP=S({host:ql,path:v().min(1),bundleHash:v().min(1),approval:gl}),UP=S({system:F,instance:L,description:v(),status:uP,keyFingerprint:v(),publicKey:v(),version:v(),manifestHash:v(),config:gP.optional(),installed:mP.optional(),host:HP.optional(),dirs:VP.optional(),pairedAt:N.optional(),pairedBy:M.optional(),lastSeenAt:N.optional(),address:v().optional(),connect:DO.optional(),store:BM.optional()}),WP=S({instance:L,description:v(),online:b(),config:O,types:x(S({name:I,description:v()}))}),GP=S({pairing:pl,description:v(),instance:L,configType:yT.optional(),configSecrets:pA.optional(),store:pM.optional()});S({format:D(1),system:F,instance:L,version:v(),exportedAt:N,exportedBy:M,withSecrets:b()});var KP=S({system:F,instance:L,description:v().optional(),config:O,store:yM.optional()}),qP=S({at:N,stream:E([`stdout`,`stderr`,`hub`]),text:v()}),JP=S({meaning:b(),items:y().int().min(0),pending:y().int().min(0),embedding:b(),retrying:b(),lastError:S({at:N,message:v()}).optional()}),YP=C([OA,I]),XP=S({id:v(),provider:YP,name:v(),contextWindow:y().int().min(0).optional(),pricing:S({input:P,output:P}).optional(),capabilities:x(v()),maxQuestions:y().int().min(1).optional(),maxRequestBytes:y().int().min(1).optional()}),ZP=XP.extend({tier:E([`flagship`,`efficient`,`legacy`,`experimental`]),maxOutputTokens:y().int().min(1).optional(),roles:x(qD)}),QP=NA.extend({spent:P}),$P=S({setting:I,system:F,decl:oN}),eF=hj.omit({request:!0,response:!0}),tF=w(`kind`,[S({kind:D(`budget`),id:_l}),S({kind:D(`priority`),id:vl}),S({kind:D(`policy`),id:hl}),S({kind:D(`category`),id:wl}),S({kind:D(`provider`),id:Tl})]),nF=S({uri:qx,system:F,stat:$x,links:x(eS),indexedVersion:v().optional(),sectioner:I.optional(),source:VE.optional(),raw:Zx.optional(),forms:x(aS).optional(),primary:aS.optional(),seenAt:N});S({id:El,match:cS,sectioner:I,setBy:M}),S({uri:qx,from:v(),to:v(),added:x(Jx),changed:x(Jx),removed:x(Jx)});var rF=E([`fn`,`context`,`section`,`message`,`type`,`example`,`record`,`contextSection`,`image`,`contextContent`]);S({kind:rF,key:v(),system:F.optional(),text:v(),embedText:v().optional(),hash:v(),vectorHash:v().optional(),embedder:I,updatedAt:N,parent:v().optional(),image:v().optional()});var iF=E([`words`,`meaning`,`both`]);S({kind:rF,key:v(),rank:y().min(0).max(1),similarity:y().min(-1).max(1).optional(),matched:iF.optional(),parent:v().optional(),text:v()});var aF=E([`approval-needed`,`input-needed`,`config-needed`,`message`,`replied`,`turn-finished`,`turn-failed`,`pairing-requested`,`system-disconnected`,`spend-limit`,`system-paused`,`system-notice`,`system-message`]),oF=S({system:F,segment:v().min(1),path:x(v().min(1)).optional(),query:T(v(),v()).optional()}).strict(),sF=C([S({session:j}),S({approval:gl}),S({pairing:pl}),S({run:A}),S({system:F}),S({page:oF})]),cF=E([`ok`,`failed`,`info`]),lF=S({label:v().min(1).max(24),link:sF}),uF=S({id:xl,user:M,reason:aF,title:v(),body:v(),link:sF,read:b(),pushed:b(),resolved:v().optional(),tone:cF.optional(),also:lF.optional(),key:v().min(1).max(200).optional(),createdAt:N}),dF=S({id:Sl,user:M,endpoint:Ls(),keys:S({p256dh:v(),auth:v()}),device:v(),createdAt:N}),fF=sl.fnExample;dN.extend({id:fF,fn:I,system:F,source:E([`decl`,`added`,`runtime`]),key:v().min(1).max(200).optional(),order:y().int().min(0),text:v(),addedBy:M.optional(),createdAt:N});var pF=S({fn:k,upsert:x(dN.extend({key:v().min(1).max(200)})),remove:x(v().min(1).max(200))}),mF=S({fn:Mb,query:v().optional(),offset:y().int().min(0).optional(),limit:y().int().min(1).max(50).optional()}),hF=S({fn:I,items:x(dN.extend({id:fF,rank:y().optional()})),total:y().int().min(0),next:y().int().min(0).optional()}),gF=E([`text`,`semantic`,`hybrid`]),_F=[`session`,`user`,`everyone`],vF=E([`fn`,`context`]),yF=S({text:v().optional(),match:gF.optional(),items:x(vF).min(1).optional(),kinds:x(C([D(`native`),I])).min(1).optional(),systems:x(F).min(1).optional(),instance:L.optional(),visibility:E([`mine`,`shared`,`public`]).optional(),types:S({reads:x(Nb).optional(),writes:x(Nb).optional()}).optional(),modes:x(fN).min(1).optional(),effects:x(S({thing:pN,action:hN.optional(),kind:v().min(1).optional()})).min(1).optional(),names:x(I).min(1).max(100).optional(),filters:x(kj).max(20).optional(),off:b().optional(),statuses:QS.shape.statuses,returnNotApplicable:QS.shape.returnNotApplicable,semanticOver:QS.shape.semanticOver,scopes:x(E(_F)).min(1).optional(),available:b().optional(),niches:x(xN).min(1).optional(),order:E([`rank`,`name`]).optional(),offset:y().int().min(0).optional(),limit:y().int().min(1).max(100).optional()}),bF=yF.omit({items:!0,match:!0,filters:!0,off:!0,scopes:!0,statuses:!0,returnNotApplicable:!0,semanticOver:!0}).extend({kinds:yF.shape.kinds.describe("Leave `kinds` out unless the person asks for a kind of fn by name: you can't know how a fn was made, and a search by what it does finds every kind."),names:x(Mb).min(1).max(100).optional().describe(`Only these fns, by name, spelled as your tools and search hits spell them: to look up fns whose names you know. Leave it out to search by what a fn does.`),types:S({reads:x(Nb).optional(),writes:x(Nb).optional()}).optional().describe("Only fns that read (`reads`) or write (`writes`) any of these types: a table's name (`tasks`), or a type's name exactly as a result gave it. Leave it out unless you know the type.")}),xF=S({text:yF.shape.text,systems:yF.shape.systems,origins:x(E(bS)).min(1).optional(),scopes:yF.shape.scopes,tags:x(v().min(1)).min(1).max(20).optional(),names:yF.shape.names,niches:yF.shape.niches,returnNotApplicable:b().optional().describe(`Also find questions a plan ruled out (status not_applicable), each with why it was ruled out; only ones that have an answer come back. Leave it out unless you need to know what was decided against.`),semanticOver:yF.shape.semanticOver.describe("What the meaning of `text` is compared with: `question` (the default: each item is worded as the question it answers, so ask in plain words) or `content` (the item's text itself, for a phrase you expect inside it)."),order:yF.shape.order,offset:yF.shape.offset,limit:yF.shape.limit}),SF=S({key:Jx,path:x(v()),title:v()}),CF=S({item:vF,name:I,system:F,description:v(),kind:v().optional(),mode:fN.optional(),signature:v().optional(),effects:v().optional(),instance:L.optional(),rank:y().optional(),similarity:y().optional(),matched:iF.optional(),section:SF.optional(),question:v().optional(),answer:v().optional(),status:RS.optional(),statusReason:v().optional(),niche:xN.optional(),available:b(),blocked:tE.optional(),inPrompt:E([`injected`,`loaded`]).optional(),exact:D(!0).optional()}),wF=CF.pick({rank:!0,similarity:!0,matched:!0,section:!0}),TF=DP.extend({found:wF.optional(),metadataStale:b().optional()}),EF=S({item:vF,by:E([`decision`,`llm`]),dropped:x(S({name:I,note:v().optional()})),calls:x(Ol).min(1).optional(),failed:v().optional(),action:D(`load`).optional()}),DF=S({fns:x(I),context:x(I),note:v()}),OF=S({items:x(CF),next:y().int().min(0).optional(),filtered:x(EF).optional(),loaded:DF.optional(),missing:S({names:x(I).min(1),note:v()}).optional()}),kF=S({min:P,typical:P,max:P,basis:E([`free`,`history`,`payload`,`unknown`]),runs:y().int().min(0)}),AF=S({runs:y().int().min(0),typical:Ml,slow:Ml,longest:Ml}),jF=S({fn:I,kind:v(),mode:fN,reads:x(I),writes:x(I),uses:x(I),free:b(),registry:x(gN),cost:kF,times:AF.optional(),longRunning:b(),notice:v().optional()}),MF=S({kind:v().min(1),payload:O,args:O.optional(),history:kF.optional()}),NF=S({estimate:kF.optional()}),PF=S({model:YD.optional(),messages:y().int().min(0).max(20).default(4)}),FF=S({value:PF,setBy:M.optional(),updatedAt:N.optional()}),IF=S({entries:x(w(`type`,[S({type:D(`log`),at:N,level:E([`debug`,`info`,`warn`,`error`]),message:v().max(4e3),fields:T(v(),O).optional()}),S({type:D(`traffic`),at:N,method:v().max(16),endpoint:v().max(300),status:y().int(),duration:Ml})])).min(1).max(500),page:v().max(300).optional()}),LF=S({uri:qx,written:y().int().min(0)});jF.pick({fn:!0,kind:!0,mode:!0,reads:!0,writes:!0,uses:!0,free:!0}).extend({registry:x(gN).optional(),system:F,instance:L.optional(),updatedAt:N}),S({fn:I,type:I,use:E([`read`,`write`])}),S({fn:I,type:I,kind:Pl,system:F}),S({fn:I,to:I,link:E([`dep`,`kind`,`role`]),system:F}),S({fn:I,uses:I}),S({id:v(),fn:I,number:y().int().min(1),decl:CN,savedBy:M.optional(),savedAt:N}),S({id:v(),type:I,number:y().int().min(1),decl:rN,instance:L.optional(),savedAt:N});var RF={fns:`fns`,types:`types`,context:`context`,resources:`resources`,kinds:`kinds`,components:`components`,examples:`examples`,approvals:`runs awaiting approval`,secrets:`secrets`,connections:`connections`,records:`records`},zF={create:`Creates`,update:`Updates`,remove:`Removes`};function BF(e){let t=[];for(let n of mN){let r=new Map;for(let t of e){if(t.action!==n)continue;let e=r.has(t.thing)?r.get(t.thing):new Set;e===void 0||t.kind===void 0?r.set(t.thing,void 0):(e.add(t.kind),r.set(t.thing,e))}if(r.size===0)continue;let i=[...r.entries()].map(([e,t])=>t===void 0||t.size===0?RF[e]:`${RF[e]} (${[...t].sort().join(`, `)})`);t.push(`${zF[n]} ${i.join(`, `)}.`)}return t.length===0?void 0:t.join(` `)}var VF=sl.refusal,HF=[`fns`,`context`,`types`,`roots`,...AP],UF=E(HF),WF=S({section:UF,name:v().min(1)});WF.extend({system:F,by:M,at:N});var GF=S({version:v(),hash:v().min(1),grants:yk,runtime:x(WF),by:M,at:N}),KF=S({section:C([UF,E([`grants`,`config`])]),name:v().min(1),change:E([`added`,`changed`,`removed`]),origin:SP,before:O.optional(),after:O.optional()}),qF=KF.pick({section:!0,name:!0}),JF=qF.extend({change:KF.shape.change,origin:SP,version:v(),by:M,at:N}),YF=S({version:v(),hash:v().min(1),by:SP,changes:x(KF),since:N});S({system:F,live:GF.optional(),pending:YF.optional(),checks:hk.optional(),declined:x(JF).optional(),updatedAt:N});var XF=S({mode:fN,effects:v().optional(),reads:x(I),writes:x(I),deps:x(I),cost:P.optional(),free:b().optional()}),ZF=S({name:v().min(1),before:XF.optional(),after:XF.optional()}),QF=YF.extend({summary:Wk,fns:x(ZF),injections:x(Xb).default([])}),$F=[`stage`,`effects`,`mode`,`types`,`capability`,`models`,`budget`,`secrets`,`calls`,`network`,`files`,`visibility`],eI=E($F),tI=S({id:VF,system:F,instance:L,rule:eI,attempt:v().min(1),detail:v().min(1),run:A.optional(),fn:I.optional(),at:N}),nI=S({instance:ql,rule:eI.extract([`network`,`files`]),attempt:v().min(1).max(1e3),detail:v().min(1).max(2e3)}),rI=S({system:F.optional(),rule:eI.optional(),cursor:v().optional(),limit:y().int().min(1).max(200).optional()}),iI=S({items:x(tI),next:v().optional()}),aI=S({system:F,stage:Sk,manifest:IN,facts:x(jF),checks:hk.optional(),live:GF.optional(),pending:QF.optional(),declined:x(JF).default([]),off:x(WF),refusals:S({total:y().int().min(0),last:x(tI).max(10)}),previewUrls:T(v(),v()).optional(),clientApproved:b().optional()}),oI=S({system:F,hash:v().min(1),off:x(WF).default([])}),sI=S({system:F,hash:v().min(1),approve:x(qF).default([]),decline:x(qF).default([]),off:x(WF).default([])}).refine(e=>e.approve.length+e.decline.length>0,{message:`approve or decline at least one change`,path:[`approve`]}),cI=S({hash:v(),waiting:y().int().min(0)}),lI=C([S({preview:eA,contract:IN.optional(),ask:oA.optional()}),S({refused:v().min(1)})]),uI=S({fn:I,args:O,instance:L.optional()}),dI=sl.mentionRequest,fI=S({request:dI,query:v(),roots:x(qx).max(20).optional(),limit:y().int().min(1).max(50)}),pI=S({hits:x(uS)}),mI=2e3,hI=S({kind:I,changedSince:N.optional(),cursor:v().optional(),limit:y().int().min(1).max(100).optional()}),gI=S({items:x(S({fn:I,kind:I,owner:M,title:v(),version:y().int().min(1),payload:O,removed:b(),updatedAt:N})),cursor:v().optional()}),_I=S({fn:I,args:O,key:v().min(1).max(200),priority:Rl.extract([`background`,`interactive`]).optional(),maxSpend:P.positive().optional()}),vI=S({run:A,turn:cl,status:TE}),yI=S({title:v().min(1).max(120),body:v().max(mI),tone:cF.optional(),link:sF.optional(),also:lF.optional(),key:v().min(1).max(136).optional()}),bI=`fnloom`,xI=`hub.name`,SI=v().trim().min(1).max(40).refine(e=>!/[\r\n]/.test(e),{message:`One line only.`}),CI=S({name:SI,source:E([`setting`,`env`,`default`]),version:v()}),wI=S({name:SI.nullable()}),TI=[`off`,`text`,`model`];E(TI);var EI=w(`use`,[S({use:D(`off`)}),S({use:D(`text`)}),S({use:D(`model`),embedder:I})]),DI={use:`text`},OI=S({text:b(),images:b(),crossModal:b()}).extend({embedder:I,name:v(),dimensions:y().int().min(1)}),kI=w(`space`,[S({space:D(`none`),reason:v()}),S({space:D(`shared`),embedder:I}),S({space:D(`own`),embedder:I,crossModal:b()})]),AI=S({value:EI,setBy:M.optional(),updatedAt:N.optional(),text:I,options:x(OI),state:kI}),jI={id:M,name:v(),about:v(),createdAt:N,disabled:b()},MI=E([`admin`,`member`]),NI=S({...jI,kind:D(`user`),email:v(),role:MI,timeZone:v().optional()}),PI=w(`kind`,[NI,S({...jI,kind:D(`group`)}),S({...jI,kind:D(`agent`),fn:I}),S({...jI,kind:D(`system`),system:F}),S({...jI,kind:D(`mcp`),mcp:kl})]),FI=NI.pick({id:!0,kind:!0,name:!0,email:!0,role:!0,timeZone:!0});S({group:M,user:M,addedBy:M,addedAt:N,provider:v().optional()}),S({user:M,kind:E([`password`,`passkey`]),secretHash:v(),createdAt:N}),S({id:Dl,user:M,version:y().int().min(1),refreshHash:v(),rotatedHashes:x(v()).optional(),device:v(),createdAt:N,lastSeenAt:N,actingAs:M.optional()}),S({actor:M,session:Dl,version:y().int().min(1)});var II=S({setting:I,actor:M,value:O,setBy:M,run:A.optional(),updatedAt:N}),LI=C([S({actor:M}),S({group:M}),S({kind:Bl}),S({everyone:D(!0)})]),RI=S({fn:v().optional(),system:F.optional(),kind:Pl.optional(),tags:x(v()).optional(),when:CT.optional(),via:I.optional()}),zI=w(`by`,[S({by:D(`turn-user`)}),S({by:D(`actor`),actor:M}),S({by:D(`group`),group:M,quorum:y().int().min(1).optional()}),S({by:D(`admins`)}),S({by:D(`judge`),fn:I}),S({by:D(`hub`)})]);S({fn:I,args:O,actor:M}),S({approve:b(),reason:v()});var BI=w(`effect`,[S({effect:D(`allow`)}),S({effect:D(`deny`),reason:v()}),S({effect:D(`ask`),approver:zI})]),VI=S({id:hl,description:v(),subject:LI,target:RI,decision:BI,priority:y().int(),expiresAt:N.optional(),createdBy:M,createdAt:N,yields:b().optional()}),HI=E([`once`,`session`,`always`]),UI=S({id:gl,run:A,fn:I,policy:hl.optional(),approver:zI,status:E([`pending`,`approved`,`denied`,`expired`]),decisions:x(S({by:M,approve:b(),remember:HI,reason:v().optional(),at:N})),createdAt:N,preview:eA.optional(),proposed:b().optional(),ask:oA.optional(),variant:QA.optional()}),WI=v().regex(/^[a-z0-9][a-z0-9-]{0,31}$/,`lower case letters, digits and dashes, starting with a letter or digit`),GI=S({role:v().min(1).default(`groups`).describe(`The claim whose values pick the role (default "groups").`),admin:x(v().min(1)).default([]).describe(`Values of the role claim that make an admin.`),member:x(v().min(1)).optional().describe(`When given, values of the role claim one of which (or an admin value) is needed to sign in.`),groups:v().min(1).optional().describe(`The claim whose values are hub group names to sync the person into.`)}),KI=S({id:WI,label:v().min(1).max(60),issuer:Ls(),clientId:v().min(1),clientSecret:v().min(1).optional(),scope:v().min(1).default(`openid email profile`),userinfo:b().default(!0),claims:GI.prefault({})});x(KI).refine(e=>new Set(e.map(e=>e.id)).size===e.length,`each provider needs its own id`);var qI=v().trim().toLowerCase().regex(/^(?=.{1,253}$)([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/,`a domain such as example.com`),JI=w(`mode`,[S({mode:D(`invite`)}),S({mode:D(`domains`),domains:x(qI).min(1).max(50)}),S({mode:D(`anyone`)})]),YI=`signInPolicy`,XI=S({limit:y().int().min(1).max(1e5),window:y().int().min(1e3).max(864e5)}),ZI=S({account:XI,address:XI}),QI=`signInLimits`,$I=S({proxies:y().int().min(0).max(5)}),eL=`proxyTrust`;S({issuer:v(),sub:v(),provider:WI,user:M,email:v().optional(),linkedAt:N,lastSignInAt:N});var tL=KI.pick({id:!0,label:!0}),nL=S({providers:x(KI.omit({clientSecret:!0}).extend({confidential:b()})),policy:JI,breakGlass:FI.optional(),callbackUrl:v(),limits:ZI,proxy:$I}),rL=S({ok:b(),detail:v()}),iL=S({provider:WI,ok:b(),discovery:rL,keys:rL,checkedAt:N}),aL=E([`linked`,`email`,`new`,`none`]),oL=S({allowed:b(),reason:v(),link:aL,user:FI.optional(),role:MI.optional(),groups:x(v()),unknownGroups:x(v())}),sL=S({id:v(),provider:WI,at:N,problem:v().optional(),subject:v().optional(),email:v().optional(),emailVerified:b(),claims:T(v(),O),outcome:oL.optional()}),cL=S({provider:WI,label:v(),email:v().optional(),lastSignInAt:N}),lL=FI.extend({disabled:b(),createdAt:N,breakGlass:b(),password:b(),identities:x(cL),groups:x(S({id:M,name:v(),synced:b()}))}),uL=S({id:M,name:v(),about:v(),createdAt:N,members:y().int().min(0)}),dL=S({user:M,name:v().trim().min(1).max(120).optional(),role:MI.optional(),disabled:b().optional()}),fL=S({group:M,user:M,member:b()});function pL(e){return`/auth/sso/${encodeURIComponent(e)}/start`}var mL=`harness_sso_handoff`,hL=E([`score`,`decision`,`graph`]),gL=E([`below-threshold`,`top-n`,`declined`,`budget`,`rule`,`failed`]),_L={"below-threshold":`Score under the threshold`,"top-n":`Others scored higher`,declined:`The decision model declined it`,budget:`No room in the token budget`,rule:`Hidden by a rule`,failed:`Decision model failed; the score decided`},vL=[`suggest`,`load`],yL=E(vL);function bL(e){return e.by===`none`?`suggest`:e.action??`suggest`}var xL=E([`loaded`,`budget`,`blocked`]),SL={loaded:`Loaded for the turn`,budget:`No room to load it, so suggested`,blocked:`Can't be loaded now, so suggested`},CL=w(`used`,[S({used:D(!0),kind:E([`fn`,`context`]),name:I,score:y().optional(),broughtBy:I.optional(),note:v().optional(),load:xL.optional()}),S({used:D(!1),kind:E([`fn`,`context`]),name:I,score:y().optional(),broughtBy:I.optional(),reason:gL,note:v().optional()})]),wL=S({by:hL,threshold:y().optional(),calls:x(Ol).min(1).optional(),action:D(`load`).optional(),items:x(CL)}),TL=S({messages:y().int().min(1).max(20).default(3),candidates:y().int().min(1).max(50).default(20),cap:y().int().min(0).max(20).default(6),floor:y().min(0).max(1).default(.2)}),EL=[`decision`,`llm`,`none`];E(EL);var DL=w(`by`,[S({by:D(`none`)}),TL.extend({by:D(`decision`),model:YD.optional(),action:yL.optional()}),TL.extend({by:D(`llm`),model:YD,action:yL.optional()})]),OL={by:`none`},kL=TL.extend({enabled:b(),model:YD.optional()});function AL(e){let{enabled:t,model:n,...r}=e;return t&&n!==void 0?{by:`llm`,model:n,...r}:OL}var jL=C([DL,kL.transform(AL)]),ML=S({value:DL,setBy:M.optional(),updatedAt:N.optional()}),NL=[`none`,`decision`,`llm`];E(NL);var PL=w(`by`,[S({by:D(`none`)}),S({by:D(`decision`),model:YD.optional(),action:yL.optional()}),S({by:D(`llm`),model:YD,action:yL.optional()})]),FL={by:`none`},IL={fn:`fnsSearchDecision`,context:`contextSearchDecision`},LL=S({value:PL,setBy:M.optional(),updatedAt:N.optional()}),RL=S({fn:LL,context:LL}),zL=S({item:vF,value:PL});w(`key`,[S({key:D(`suggestDecision`),value:jL,setBy:M,updatedAt:N}),S({key:D(`autoClassifier`),value:PF,setBy:M,updatedAt:N}),S({key:D(IL.fn),value:PL,setBy:M,updatedAt:N}),S({key:D(IL.context),value:PL,setBy:M,updatedAt:N}),S({key:D(xI),value:SI,setBy:M,updatedAt:N}),S({key:D(`imageEmbedding`),value:EI,setBy:M,updatedAt:N}),S({key:D(YI),value:JI,setBy:M,updatedAt:N}),S({key:D(Rb),value:zb,setBy:M,updatedAt:N}),S({key:D(QI),value:ZI,setBy:M,updatedAt:N}),S({key:D(eL),value:$I,setBy:M,updatedAt:N}),S({key:D(Vb),value:b(),setBy:M,updatedAt:N}),S({key:D(JS),value:YS,setBy:M,updatedAt:N})]);var BL=E([`all`,`replies`,`none`]),VL=S({actor:M,role:E([`owner`,`member`,`agent`]),notify:BL,joinedAt:N}),HL=E([`idle`,`running`,`paused`]),UL=S({hash:v(),injected:x(I),at:cl}),WL=S({id:j,title:v(),owner:M,...YA.shape,selection:Mx.optional(),participants:x(VL),forkOf:j.optional(),fork:QA.optional(),tools:x(I),context:x(I),suggested:x(I).optional(),announcedSystems:LA.optional(),citationsTold:qA.optional(),fixed:UL.optional(),status:HL,transcript:x(cD),createdAt:N,updatedAt:N,archived:b()}),GL=WL.pick({id:!0,title:!0,owner:!0,agent:!0,status:!0,createdAt:!0,updatedAt:!0,archived:!0}),KL=E([`local-time`,`suggested-context`,`suggested-fns`]),qL=S({type:D(`text`),text:v()}),JL=S({type:D(`mention`),provider:I,label:v(),target:O,text:v()}),YL=S({type:D(`command`),context:I,args:T(v(),v())}),XL=S({type:D(`file`),ref:Zx,name:v(),uri:qx.optional(),text:v().optional(),truncated:b().optional()}),ZL=S({type:D(`input-answer`),run:A,title:v(),value:O,text:v()}),QL=`input-answer`,$L=S({type:D(`loaded-for-you`),by:E([`decision`,`llm`,`recall`]),toolset:cx.optional(),fns:x(S({fn:I,label:v(),why:v().optional(),broughtBy:I.optional()})),context:x(S({context:I,title:v().optional(),why:v().optional(),text:v(),fns:x(I).optional()}))}),eR=w(`type`,[qL,S({type:D(`reasoning`),text:v()}),JL,YL,S({type:D(`invocation`),run:A,fn:I}),S({type:D(`call`),run:A,fn:I}),XL,ZL,S({type:D(`extra`),extra:KL,blocks:x(qN)}),S({type:D(`hook`),hook:I,blocks:x(qN)}),S({type:D(`attachment`),attachment:I,data:O,title:v()}),S({type:D(`link`),link:lS}),S({type:D(`systems-changed`),on:x(RA),off:x(RA)}),S({type:D(`kept-effects`),variants:x(nj)}),$L]),tR=new Set([`extra`,`hook`,`input-answer`,`systems-changed`,`loaded-for-you`]);function nR(e){return tR.has(e.type)}var rR=w(`type`,[qL,JL.omit({text:!0}),YL,XL,ZL]),iR=S({id:ll,session:j,turn:cl,author:M,role:E([`user`,`assistant`,`note`]),parts:x(eR),runs:x(A),status:E([`streaming`,`done`,`failed`]),replyTo:ll.optional(),replyAll:b(),answerers:x(M),suggestions:wL.optional(),compared:D(!0).optional(),cacheMiss:S({call:Ol,at:N}).optional(),citations:x(KA).optional(),createdAt:N}),aR=E([`pause`,`resume`,`cancel`]),oR=S({run:A,fn:I,status:TE,pause:b(),resume:b(),cancel:b()}),sR=S({pause:b(),cancel:b(),uncancellable:x(A),undoLastTurn:b(),continueLastTurn:b().optional(),runs:x(oR).optional()}),cR=S({session:j,user:M,focused:b(),typing:b(),lastActiveAt:N}),lR=S({voiceInput:b(),voiceOutput:b(),dictation:S({engine:E(ZD),language:v().optional()}).optional(),uploads:b(),meaning:b(),mentions:x(S({provider:I,title:v(),of:I.optional()})),commands:x(S({name:v(),context:I,args:x(wN),description:v(),unavailable:v().optional()})),agents:x(S({fn:I,description:v()})),display:T(v(),lE),invocations:x(S({fn:I,description:v(),args:yT})),methods:x(S({type:I,method:v(),fn:I,description:v(),args:yT})),clients:x(S({system:F,url:v(),hash:v()})),systems:x(S({name:F,status:uP,enabled:b()})),models:x(XP)}),uR=iR.pick({id:!0,session:!0,author:!0,role:!0,replyTo:!0,replyAll:!0,createdAt:!0}).extend({text:v()}),dR=uP.extract([`connected`,`disconnected`,`removed`]),fR=w(`type`,[S({type:D(`message`),message:uR}),S({type:D(`run`),run:A,fn:I,update:ME,notified:b().optional()}),S({type:D(`resources`),changes:x(sS)}),S({type:D(`system`),system:F,status:dR}),S({type:D(`fns`),added:x(I),removed:x(I),changed:x(I).default([])})]),pR=S({protocol:D(1),name:F,version:v(),instance:L.default(Kl),instances:vP.optional(),boot:v(),publicKey:v(),manifestHash:v(),contractHash:v().optional(),pairingToken:v().optional(),autoPair:cP.optional()}),mR=w(`kind`,[S({kind:D(`challenge`),nonce:v()}),S({kind:D(`pairing`),pairing:pl,code:v().optional(),url:v(),expiresAt:N})]),hR=S({signature:v()}),gR=S({maxFrame:y().int().min(1024),maxChunk:y().int().min(1024),heartbeat:Ml}),_R=S({value:O,version:y().int().min(1)}),vR=S({instance:L,config:_R.optional(),start:S({first:b(),upgradedFrom:v().optional()}),token:v(),sendManifest:b(),limits:gR,autoPair:sP.optional(),store:bM.optional()});S({system:F,instance:L,boot:v()});var yR=rT(`linkSession`,{provides:Zw()}),bR=FP({name:`linkTel`}),xR=S({state:O,calls:T(v(),PE),reason:E([`resumed`,`restart`])}),SR=S({run:sE,fn:v(),kind:Pl,payload:O.optional(),args:O,budget:LE,handlers:x(v()),resume:xR.optional(),deadline:N,configVersion:y().int().min(0),connection:FO.optional(),approved:cA.optional()}),CR=C([S({run:A}),S({delivery:ul})]),wR=S({session:j,actor:M,user:iE,time:aE}),TR=S({level:E([`debug`,`info`,`warn`,`error`]),key:v(),fields:el}),ER=S({run:A,action:E([`cancel`,`pause`])}),DR=S({accepted:b(),reason:v().optional()}),OR=E([`restart`,`upgrade`,`shutdown`,`removed`]),kR=S({title:v().min(1).max(120),body:v().max(2e3)}),AR=Z(bR,yR).group({manifest:{body:IN,response:RN,ws:`mf`},patch:{body:LN,response:RN,ws:`mp`},call:{body:S({parent:A,fn:I,args:O,key:v(),budget:S({cost:P.optional(),time:Ml.optional()}).optional(),handlers:x(v()),background:b(),on:L.optional()}),response:PE,ws:`call`},handle:{body:S({run:A,handler:v(),args:O}),response:IE,ws:`ha`},control:{body:ER,response:DR,ws:`cl`},progress:{body:S({run:A,progress:gE}),ws:`pg`},allow:{body:S({run:A,operations:dE.partial()}),ws:`al`},undoWith:{body:S({run:A,undo:O}),ws:`uw`},updateResult:{body:S({run:A,result:O}),response:S({revision:y().int().min(1)}),ws:`ur`},attach:{body:S({run:A,item:C([S({attachment:I,data:O,title:v()}),S({link:lS})])}),ws:`at`},types:{body:S({names:x(I).min(1),run:A.optional()}),response:TP,ws:`ty`},fnShape:{body:S({name:I}),response:S({fn:zN.optional()}),ws:`fsh`},resourcesChanged:{body:S({changes:x(sS)}),ws:`rc`},llm:{body:vD,streamOut:yD,ws:`llm`},model:{body:GD,response:KD,ws:`mdl`},resource:{body:S({uri:qx,want:x(tS),run:A.optional(),sections:x(Jx).min(1).optional()}),response:rS,ws:`rs`},resourceSections:{body:S({uri:qx,run:A.optional()}),response:x(oS),ws:`rsc`},content:{body:S({ref:Zx,offset:y().int().min(0),length:y().int().min(1),run:A.optional()}),response:S({chunk:v()}),ws:`ct`},upload:{body:S({upload:v(),chunk:v(),last:b(),mime:v()}),response:S({ref:Zx.optional()}),ws:`up`},setting:{body:S({run:A,setting:I}),response:S({value:O.optional()}),ws:`st`},stateGet:{body:S({owner:CR}),response:S({values:el,version:y().int()}),ws:`sg`},stateSet:{body:S({owner:CR,patch:el,clear:x(v()),version:y().int().optional()}),response:C([S({version:y().int()}),S({conflict:D(!0)})]),ws:`ss`},log:{body:TR,ws:`lg`},connectionUpdate:{body:zO,ws:`cu`},instanceConnect:{body:DO,ws:`ic`},shareFn:{body:xO,ws:`sh`},usableFns:{body:SO,response:S({fns:x(k)}),ws:`uf`},propose:{body:sA,response:dA,ws:`po`},decide:{body:xD,response:SD,ws:`de`},fleet:{body:S({}),response:x(WP),ws:`fl`},searchFns:{body:yF.extend({run:A.optional()}),response:OF,ws:`sf`},fnExamples:{body:mF,response:hF,ws:`fx`},examples:{body:pF,response:S({added:y().int().min(0),removed:y().int().min(0)}),ws:`xp`},models:{body:S({}),response:x(ZP),ws:`mo`},grantPairing:{body:lA,response:uA,ws:`gp`},notifyAdmins:{body:kR,ws:`na`},notify:{body:S({run:A,notice:yI}),ws:`nf`},kindFns:{body:hI,response:gI,ws:`kf`},startRun:{body:_I,response:vI,ws:`sru`},notifyOwner:{body:S({fn:I,notice:yI}),ws:`nfo`},reportRefusal:{body:nI,ws:`rx`},mentionResources:{body:fI,response:pI,ws:`mr`},records:{body:Zj,response:Qj,ws:`rq`},record:{body:eM,response:S({record:Yj.optional()}),ws:`rg`},recordTable:{body:$j,response:Bk,ws:`rtb`},saveRecord:{body:tM,response:Yj,ws:`rsv`},removeRecord:{body:rM,response:S({removed:b()}),ws:`rrm`},storeOpen:{body:S({}),response:S({bytes:y().int().min(0)}),ws:`sto`},storeRun:{body:GM,response:KM,ws:`stq`},storeBegin:{body:S({}),response:qM,ws:`stb`},storeCommit:{body:S({lease:HM}),ws:`stc`},storeRollback:{body:S({lease:HM}),ws:`str`},storeSnapshot:{body:S({}),response:S({snapshot:JM}),ws:`stn`},storeRestore:{body:S({snapshot:JM}),ws:`stx`},storeStatus:{body:kM,ws:`sts`},storeExport:{body:S({move:PM}),response:S({bytes:y().int().min(0),hash:v().regex(/^[0-9a-f]{64}$/)}),ws:`ste`},storeDownload:{body:S({move:PM,offset:y().int().min(0),length:y().int().min(1).max(4e6)}),response:S({chunk:v()}),ws:`std`},storeUpload:{body:S({move:PM,offset:y().int().min(0),chunk:v().max(6e6)}),ws:`stu`},storeUploadDone:{body:S({move:PM,bytes:y().int().min(0),hash:v().regex(/^[0-9a-f]{64}$/)}),ws:`stud`},storeMoveProgress:{body:S({move:PM,progress:RM}),ws:`stmp`}});X({endpoints:{...Z(bR).group({hello:{body:pR,response:mR,ws:`hi`},prove:{body:hR,response:vR,ws:`pr`},pairingInfo:{body:GP,ws:`pi`}}),...AR}}),X({endpoints:{paired:Y({body:S({pairing:pl}),ws:`pd`}),run:Y({body:SR,response:NE,ws:`run`}),control:Y({body:ER,response:DR,ws:`ctl`}),undo:Y({body:S({run:sE,fn:v(),kind:Pl,fnPayload:O.optional(),payload:O}),response:FE,ws:`un`}),handler:Y({body:S({call:dl,run:A,key:v(),handler:v(),args:O}),response:IE,ws:`hd`}),child:Y({body:S({parent:A,key:v(),run:A,update:ME.optional()}),ws:`ch`}),check:Y({body:S({kind:v(),payload:O}),response:S({problems:x(v()),description:BN.optional()}),ws:`ck`}),context:Y({body:wR.partial({session:!0}).extend({name:v(),args:T(v(),v())}),response:S({text:v()}),ws:`cx`}),roots:Y({response:x(Qx),ws:`ro`}),list:Y({body:S({uri:qx,cursor:v().optional()}),response:Vl($x),ws:`ls`}),stat:Y({body:S({uri:qx}),response:S({stat:$x.optional()}),ws:`sa`}),read:Y({body:S({uri:qx,want:x(tS)}),response:rS,ws:`rd`}),sections:Y({body:S({sectioner:v(),uri:qx,version:v()}),response:x(oS),ws:`sc`}),watch:Y({body:S({uris:x(qx),on:b()}),ws:`wa`}),content:Y({body:S({ref:Zx,offset:y().int().min(0),length:y().int().min(1)}),response:S({chunk:v()}),ws:`ct`}),hook:Y({body:S({hook:v(),message:UN}),response:x(qN),ws:`hk`}),mentions:Y({body:wR.extend({provider:v(),query:v(),request:dI}),response:x(JN),ws:`mn`}),mentionHover:Y({body:wR.extend({provider:v(),target:O}),response:S({hover:YN.optional()}),ws:`mh`}),mentionText:Y({body:wR.extend({provider:v(),target:O}),response:S({text:v()}),ws:`mt`}),event:Y({body:fR,ws:`ev`}),action:Y({body:wR.extend({delivery:ul,action:v(),input:O,run:A.optional()}),response:S({result:O}),ws:`ac`}),form:Y({body:S({delivery:ul,run:A,value:O}),ws:`fm`}),restart:Y({body:S({reason:v()}),ws:`rt`}),stop:Y({body:S({reason:OR,timeout:Ml}),ws:`sp`}),configure:Y({body:_R.extend({previous:O.optional()}),ws:`cf`}),export:Y({body:S({timeout:Ml}),response:S({data:v()}),ws:`ex`}),validate:Y({body:ok,response:sk,ws:`vl`}),preview:Y({body:rA,response:lI,ws:`pv`}),estimate:Y({body:MF,response:NF,ws:`es`}),providerChat:Y({body:GO,streamOut:KO,ws:`pc`}),providerEmbed:Y({body:ek,response:tk,ws:`pe`}),providerDecide:Y({body:XO,response:ZO,ws:`pdc`}),providerModels:Y({body:JO,response:YO,ws:`pml`}),connectStart:Y({body:IO,response:S({url:Ib}),ws:`cs`}),connectFinish:Y({body:LO,response:RO,ws:`cn`}),disconnect:Y({body:FO.pick({id:!0,owner:!0,credentials:!0}),ws:`dc`}),flags:Y({body:rA,response:Xk,ws:`fg`}),claims:Y({body:ZM,response:QM,ws:`pcl`}),checkArgs:Y({body:iA,response:aA,ws:`cka`}),storeProbe:Y({body:S({to:bM}),response:S({problems:x(v())}),ws:`spb`}),storeMove:Y({body:S({move:PM,from:bM,to:bM}),response:S({tables:y().int().min(0),rows:y().int().min(0),bytes:y().int().min(0)}),ws:`smv`}),storeMoveEnd:Y({body:S({move:PM,outcome:E([`switched`,`aborted`]),from:bM,to:bM}),response:S({backups:x(S({id:MM,bytes:y().int().min(0)}))}),ws:`sme`}),storeDiscard:Y({body:w(`what`,[S({what:D(`store`)}),S({what:D(`backup`),backup:MM})]),ws:`sdc`})}});var jR=S({session:j,parts:x(rR).min(1),variants:ZA,client:cE}),MR=$A.extend({status:dj,spent:P,tokens:y().int().min(0),startedAt:N,endedAt:N.optional(),time:Ml,messages:x(iR),approvals:x(UI)}),NR=rj.omit({variants:!0}).extend({turn:cl,session:j,message:ll,status:dj,variants:x(MR)}),PR=S({turn:cl,variant:JA,adopt:b().optional()}),FR=v().regex(Nl).max(64).brand(),IR=S({uri:v(),system:F.optional(),instance:L.optional()}),LR=S({systems:x(F).optional(),fns:x(RI).optional(),types:x(Jl).optional(),context:x(Jl).optional(),resources:x(IR).optional()}),RR=S({include:LR,exclude:LR}),zR=E([`each`,`static`]),BR=S({id:kl,slug:FR,name:v().min(1),instructions:v(),rules:RR,toolMode:zR,user:M,actor:M,secretDigest:v(),grantees:x(F),origins:x(v()),enabled:b(),createdBy:M,createdAt:N,updatedAt:N}),VR=BR.pick({slug:!0,name:!0,instructions:!0,rules:!0,toolMode:!0,user:!0,grantees:!0,origins:!0,enabled:!0});S({mcp:kl,label:v().min(1),exp:y().int()});var HR=S({mcp:kl,label:v().min(1),ttl:y().int().min(1e3).optional()}),UR=S({fns:x(I),types:x(I),closure:x(I),context:x(I),resources:x(IR),reach:x(I),warnings:x(v())}),WR=S({mcp:kl,session:v(),label:v(),client:S({name:v(),version:v()}).optional(),since:N,lastCallAt:N.optional(),calls:y().int().min(0)}),GR=BR.omit({secretDigest:!0}).extend({url:v(),sessions:y().int().min(0),callsToday:y().int().min(0)}),KR=E([`added`,`changed`,`removed`]),qR=S({id:v().min(1),system:F,section:UF,name:v().min(1),number:y().int().min(1),change:KR,decl:O,hash:v().min(1),declaredBy:SP.optional(),instance:L.optional(),savedBy:M.optional(),savedAt:N}),JR=Hl.extend({system:F,section:UF,name:v().min(1)}),YR=Vl(qR);oS.extend({uri:qx,version:v(),hash:v()});var XR=(...e)=>e.join(`\0`),ZR=`bearerAuth`,QR={security:{[ZR]:{type:`http`,scheme:`bearer`,bearerFormat:`JWT`}}};function $R(e){let t=e?.name??ZR,n=e?.doc??QR;return rT(t,{provides:Zw(),requires:e?.requires??[],doc:n})}var ez=v().regex(/^[a-z]+:.+$/),tz=S({fnKind:Pl.optional(),mode:fN.optional(),effects:x(gN).optional(),reads:x(I).optional(),writes:x(I).optional(),visibility:zl.optional(),on:b(),stage:Sk.optional(),pending:b().optional(),examples:y().int().min(0).optional()}),nz=S({id:ez,kind:yj,name:v().min(1),about:v(),system:F.optional(),external:b(),collapsed:y().int().min(0).optional(),facts:tz}),rz=S({from:ez,to:ez,kind:xj,label:v().min(1),weight:y().min(0).max(1).optional()}),iz=S({node:ez,kind:yj,count:y().int().min(1)}),az=jj.pick({text:!0,filters:!0}).extend({systems:x(F).min(1).optional(),external:b().optional(),focus:S({node:ez,hops:y().int().min(1).max(4).optional()}).optional(),collapse:x(F).min(1).optional(),limit:y().int().min(1).max(1e3).optional()}),oz=S({nodes:x(nz),edges:x(rz),more:x(iz),total:S({nodes:y().int().min(0),edges:y().int().min(0)})}),sz=`hub/visuals`,cz=S({columns:x(S({name:v().min(1),kind:wk,role:Tk,numeric:b(),temporal:b(),day:b(),categorical:b(),key:b(),opaque:b(),distinct:y().int().min(0),nulls:y().min(0).max(1),nonNegative:b(),min:C([y(),v()]).optional(),max:C([y(),v()]).optional(),bound:S({min:y(),max:y()}).optional(),members:x(v()).optional()})),rows:y().int().min(0),whole:b()}),lz=new Set([`integer`,`number`]),uz=new Set([`date`,`datetime`]),dz=new Set([`text`,`boolean`]),fz=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function pz(e){return lz.has(e)?`measure`:uz.has(e)||dz.has(e)?`group`:`attribute`}function mz(e,t,n){return e===void 0||typeof e==typeof t&&(n===`min`?t<e:t>e)?t:e}function hz(e,t){return{columns:e.columns.map((n,r)=>{let i=new Set,a=0,o=0,s=0,c=!0,l,u;for(let t of e.rows){let e=t[r];e==null?a+=1:(s+=1,i.add(typeof e==`object`?JSON.stringify(e):String(e)),typeof e==`string`&&fz.test(e)&&(o+=1),(typeof e==`number`||typeof e==`string`)&&(l=mz(l,e,`min`),u=mz(u,e,`max`)),(typeof e!=`number`||e<0)&&(c=!1))}let d=n.kind,f=n.key===!0,p=d===`uuid`||s>0&&o===s||n.ref!==void 0||d===`binary`;return{name:n.name,kind:d,role:n.role??pz(d),numeric:lz.has(d),temporal:uz.has(d),day:d===`date`,categorical:dz.has(d),key:f,opaque:p,distinct:i.size,nulls:e.rows.length===0?0:a/e.rows.length,nonNegative:c&&s>0,...l===void 0?{}:{min:l},...u===void 0?{}:{max:u},...t?.(n)??{}}}),rows:e.rows.length,whole:e.offset===0&&!e.truncated}}var gz=T(k,x(v().min(1)).min(1));S({visual:k,coverage:y().int().min(0),priority:y(),bind:gz,styles:x(k).min(1),because:x(v())});var _z={floor:0,structural:10,encoded:20,"time-encoded":30},vz={"temporal-key":15,"low-cardinality":10,"enum-key":8,"high-null":-10,"many-categories":-10},yz=.5;function bz(e){return e.columns.filter(e=>!e.opaque)}function xz(e,t){return e.accepts.includes(t.kind)&&(e.role===void 0||e.role===t.role)}function Sz(e,t,n){return!e.required&&e.role===`group`&&n>1&&t.distinct>=n}function Cz(e,t,n){let r={},i=new Set;for(let a of e.channels){let e=t.filter(e=>!i.has(e.name)&&xz(a,e)&&!Sz(a,e,n)).map(e=>e.name),o=a.many?e:e.slice(0,1);if(o.length<(a.many?a.min??1:1)){if(a.required)return`No column fits ${a.label} (${a.accepts.join(`, `)}).`;continue}let[s,...c]=o;if(s!==void 0){r[a.name]=[s,...c];for(let e of o)i.add(e)}}return r}function wz(e,t,n){return(e[t]??[]).flatMap(e=>n.columns.filter(t=>t.name===e))}function Tz(e,t,n,r,i){switch(e.rule){case`distinct`:{let r=wz(t,e.channel,n);return r.some(t=>t.distinct>e.max)?`${e.channel} has more than ${String(e.max)} values.`:e.min!==void 0&&r.some(t=>t.distinct<(e.min??0))?`${e.channel} has fewer than ${String(e.min)} values.`:void 0}case`non-negative`:return wz(t,e.channel,n).every(e=>e.nonNegative)?void 0:`${e.channel} has values below 0.`;case`bounded`:return wz(t,e.channel,n).every(e=>e.bound!==void 0)||t.max!==void 0?void 0:`${e.channel} has no known range.`;case`distinct-columns`:{let n=e.channels.flatMap(e=>t[e]??[]);return new Set(n).size===n.length?void 0:`${e.channels.join(` and `)} need different columns.`}case`links`:{if(r===void 0||i===void 0)return;let n=e=>i.findIndex(n=>n.name===t[e]?.[0]),a=n(e.from),o=n(e.to);if(a<0||o<0)return`${e.to} must name values of ${e.from}.`;let s=new Set(r.map(e=>JSON.stringify(e[a]??null)));return r.every(e=>e[o]===null||s.has(JSON.stringify(e[o]??null)))?void 0:`${e.to} names values that are not ${e.from} values.`}}}function Ez(e,t,n){let r=Object.values(t).flat().flatMap(e=>n.columns.filter(t=>t.name===e)),i=r.filter(e=>e.role===`group`),a={"temporal-key":i.some(e=>e.temporal),"low-cardinality":i.length>0&&i.every(e=>e.distinct<=8),"enum-key":i.some(e=>e.members!==void 0),"high-null":r.some(e=>e.nulls>yz),"many-categories":i.some(e=>e.distinct>5)},o=e.priority.terms.filter(e=>a[e]);return{priority:_z[e.priority.band]+o.reduce((e,t)=>e+vz[t],0),because:o.map(e=>`${e} (${String(vz[e])})`)}}function Dz(e,t,n,r){let i=[];e.whole===!0&&!n.whole&&i.push(`style ${e.name} only draws a whole result.`);for(let n of e.needs??[])t[n]===void 0&&i.push(`style ${e.name} needs ${n} bound.`);for(let[n,r]of Object.entries(e.columns??{})){let a=t[n]?.length??0;r.min!==void 0&&a<r.min&&i.push(`style ${e.name} needs at least ${String(r.min)} ${n} columns.`),r.max!==void 0&&a>r.max&&i.push(r.max===0?`style ${e.name} draws no ${n}.`:`style ${e.name} draws at most ${String(r.max)} ${n} columns.`)}for(let a of e.rules??[]){let o=Tz(a,t,n,r?.rows,r?.columns);o!==void 0&&i.push(`style ${e.name}: ${o}`)}return i}function Oz(e,t,n,r){return e.styles.filter(e=>Dz(e,t,n,r).length===0).map(e=>e.name)}function kz(e,t,n,r){let i=[];for(let r of e.channels){let e=t[r.name]??[];if(e.length===0)r.required&&i.push(`${r.label} is not bound.`);else{!r.many&&e.length>1&&i.push(`${r.label} takes one column.`),r.many&&e.length<(r.min??1)&&i.push(`${r.label} needs at least ${String(r.min??1)} columns.`);for(let t of e){let e=n.columns.find(e=>e.name===t);e===void 0?i.push(`${r.label}: there is no column ${t}.`):(e.opaque&&i.push(`${r.label}: ${t} holds nothing a person reads.`),r.accepts.includes(e.kind)||i.push(`${r.label}: ${t} is ${e.kind}, not ${r.accepts.join(` or `)}.`))}}}n.rows<e.rows.min&&i.push(`Needs at least ${String(e.rows.min)} rows.`),e.rows.max!==void 0&&n.rows>e.rows.max&&e.size===void 0&&i.push(`Draws at most ${String(e.rows.max)} rows.`),e.whole&&!n.whole&&i.push(`Only draws a whole result, and this is one page of it.`);for(let a of e.rules){let e=Tz(a,t,n,r?.rows,r?.columns);e!==void 0&&i.push(e)}return i}function Az(e,t,n){let r=bz(t);return e.flatMap((e,i)=>{let a=Cz(e.shape,r.length>0?r:t.columns,t.rows);if(typeof a==`string`||kz(e.shape,a,t,n).length>0)return[];let[o,...s]=Oz(e.shape,a,t,n);if(o===void 0)return[];let{priority:c,because:l}=Ez(e.shape,a,t),u=new Set(Object.values(a).flat().filter(e=>r.some(t=>t.name===e))).size;return[{rank:{visual:e.name,coverage:u,priority:c,bind:a,styles:[o,...s],because:[`covers ${String(u)}`,...l]},index:i}]}).sort((e,t)=>t.rank.coverage-e.rank.coverage||t.rank.priority-e.rank.priority||e.index-t.index).map(e=>e.rank)}var jz=[`integer`,`number`];function Mz(e,t,n,r={}){return{name:e,label:t,accepts:[...n],required:r.required??!0,many:r.many??!1,...r.min===void 0?{}:{min:r.min},...r.role===void 0?{}:{role:r.role}}}var Nz=[`table`,`value`];E(Nz);var Pz={table:{label:`Table`,icon:`table`,description:`Every readable column and row, sortable and paged; cards on a phone.`,shape:Nk.parse({channels:[Mz(`columns`,`Columns`,Ck,{required:!1,many:!0})],rows:{min:0},whole:!1,size:`window`,pageSize:10,styles:[{name:`table`,label:`Table`},{name:`compact`,label:`Compact`},{name:`cards`,label:`Cards`}],priority:{band:`floor`,terms:[]}})},value:{label:`Value`,icon:`hash`,description:`One to four rows of numbers as cards, each titled by a text column or named by its column.`,shape:Nk.parse({channels:[Mz(`value`,`Values`,jz,{many:!0,role:`measure`}),Mz(`title`,`Title`,[`text`],{required:!1})],rows:{min:1,max:4},whole:!0,styles:[{name:`cards`,label:`Cards`},{name:`single`,label:`Single`}],priority:{band:`encoded`,terms:[]}})}};Nz.map(e=>({name:e,shape:Pz[e].shape}));var Fz=S({from:k,to:k}),Iz=S({offset:k,limit:k}),Lz=S({visual:k,style:k,label:v().min(1).optional(),bind:gz}),Rz=E([`open`,`refresh`,`status`]),zz=S({fn:I,label:v().min(1).optional(),confirm:D(!0).optional(),bind:T(k,v().min(1)),then:Rz.optional()}),Bz=S({fn:I,label:v().min(1),bind:T(k,v().min(1))}),Vz=S({offset:k,limit:k,window:y().int().min(1),more:b()}),Hz=S({fn:I,label:v().min(1),mode:fN,confirm:b(),bind:T(k,v().min(1)),form:yT.optional(),then:Rz}),Uz=S({title:v().min(1),table:Bk,facts:cz,source:S({fn:I,run:A,args:T(v(),O)}),visuals:x(Lz).min(1),problems:x(v()),range:Fz.optional(),paging:Vz.optional(),actions:x(Hz),drill:Bz.optional(),readOnly:b(),live:S({every:y().int().min(1)}).optional(),summary:v().min(1)}),Wz=S({name:k,description:v().min(1),preview:Uz,replaces:v().min(1).optional()}),Gz=S({types:x(I).max(20),narrow:x(zz).optional()}).refine(e=>e.types.length>0||(e.narrow?.length??0)>0,{message:`name a row type or an action to offer`}),Kz=S({fn:I,args:T(v(),O)}),qz=Kz.extend({on:L.optional()}),Jz=S({fn:I,args:v(),offset:k,limit:k,format:D(`csv`)});S({summary:v(),columns:x(v()),rows:x(x(O)),more:y().int().min(0),partial:v().optional()});function Yz(e,t){return e!==`read`||t===!0}function Xz(e,t){return t?`open`:e===`read`?`status`:`refresh`}function Zz(e){return DT(e.split(/[/.]/).pop()??e)||e}var Q=FP(),$=$R(),Qz=rT(`adminOnly`,{requires:[$]}),$z=S({access:v(),refresh:v(),expiresIn:Ml,user:FI}),eB=CI.pick({name:!0,version:!0}).extend({needsAdmin:b(),sso:x(tL)}),tB=S({kind:E([`fn`,`context`]),name:I,description:v(),score:WN,why:v().optional()}),nB=EA(v().min(1)),rB=S({approvals:x(UI),handlers:x(uj)}),iB=UP.omit({publicKey:!0}),aB=S({fns:y().int().min(0),context:y().int().min(0),types:y().int().min(0),parts:y().int().min(0),instances:y().int().min(0),pending:y().int().min(0),refusals:y().int().min(0)}),oB=yP.omit({keyFingerprint:!0,publicKey:!0,config:!0,pairedAt:!0,pairedBy:!0,lastSeenAt:!0,address:!0,instances:!0}).extend(UP.pick({keyFingerprint:!0,config:!0,installed:!0,host:!0,pairedAt:!0,pairedBy:!0,lastSeenAt:!0,address:!0}).shape).extend({counts:aB,instanceMode:vP,needsConfig:b(),configType:O.optional(),configSecrets:pA.optional(),store:pM.optional(),instances:x(iB)}),sB=w(`type`,[S({type:D(`message`),message:iR}),S({type:D(`token`),message:ll,text:v()}),S({type:D(`reasoning`),message:ll,text:v()}),S({type:D(`cite`),message:ll,cite:WA}),S({type:D(`controls`),controls:sR}),S({type:D(`run`),run:A,fn:I,update:ME}),S({type:D(`state`),system:F,fields:x(sj)}),S({type:D(`delivery`),delivery:lj}),S({type:D(`handler`),call:uj}),S({type:D(`approval`),approval:UI}),S({type:D(`budget`),run:A,budget:NA,reason:v()}),S({type:D(`presence`),presence:cR}),S({type:D(`session`),session:GL}),S({type:D(`compare`),turn:cl})]),cB=w(`type`,[S({type:D(`notification`),notification:uF}),S({type:D(`approval`),approval:UI}),S({type:D(`system`),system:F,status:uP}),S({type:D(`pairing`),pairing:bP}),S({type:D(`capabilities`)}),S({type:D(`session`),session:GL}),S({type:D(`session-deleted`),session:j}),S({type:D(`fn`),fn:I,system:F,stats:xP}),S({type:D(`resource`),uri:qx,forms:x(aS)}),S({type:D(`context`),name:I}),S({type:D(`identity`),identity:CI})]),lB=aT(X({endpoints:Z(Q).group({setup:{method:`GET`,response:eB,ws:`setup`},createAdmin:{body:S({email:Ns(),name:v().min(1),password:v().min(8),setup:v().trim().min(1)}),response:$z,ws:`createAdmin`},signIn:{body:S({email:Ns(),password:v()}),response:$z,errors:{401:S({reason:v()})},ws:`signIn`},refresh:{body:S({refresh:v()}),response:$z,ws:`refresh`},redeemSso:{body:S({code:v().min(1)}),cookies:S({[mL]:v().optional()}),response:$z,ws:`redeemSso`,httpOnly:!0}})}),X({endpoints:Z(Q,$).group({signOut:{ws:`signOut`},me:{method:`GET`,response:FI,ws:`me`},account:{method:`GET`,response:lL,ws:`account`}})})),uB=Hl.extend({query:jj.optional()}),dB=Hl.extend({session:j}),fB=Hl.extend({unread:b().optional(),query:jj.optional()}),pB=WL.pick({title:!0,systems:!0,agent:!0,archived:!0}).partial().extend({priority:Rl.optional(),notify:BL.optional(),model:WL.shape.model.unwrap().nullable().optional(),mode:WL.shape.mode.unwrap().nullable().optional(),contextor:WL.shape.contextor.unwrap().nullable().optional(),fnMode:WL.shape.fnMode.unwrap().nullable().optional(),instructions:WL.shape.instructions.unwrap().nullable().optional(),citations:WL.shape.citations}),mB=X({endpoints:Z(Q,$).group({capabilities:{body:S({session:j.optional()}),response:lR,ws:`capabilities`},types:{body:S({names:x(I).min(1)}),response:TP,ws:`types`},sessions:{body:uB,response:Vl(GL),ws:`sessions`},session:{body:S({session:j}),response:WL,ws:`session`},createSession:{body:WL.pick({agent:!0,systems:!0,title:!0}).partial(),response:WL,ws:`createSession`},updateSession:{body:pB.extend({session:j}),response:WL,ws:`updateSession`},deleteSession:{body:S({session:j}),response:S({deleted:b()}),ws:`deleteSession`},limits:{body:S({session:j}),response:FA,ws:`limits`},messages:{body:dB,response:Vl(iR),ws:`messages`},send:{body:S({session:j,parts:x(rR).min(1),replyTo:ll.optional(),replyAll:b().optional(),client:cE}),response:S({turn:cl,message:iR}),ws:`send`},compare:{body:jR,response:S({turn:cl,message:iR}),ws:`compare`},compareView:{body:S({turn:cl}),response:NR,ws:`compareView`},chooseVariant:{body:PR,response:NR,ws:`chooseVariant`},invoke:{body:S({session:j,fn:I,args:O,on:L.optional(),client:cE}),response:S({turn:cl,run:A}),ws:`invoke`},control:{body:S({session:j,action:aR,runs:x(A).min(1).optional()}),response:sR,ws:`control`},controls:{body:S({session:j}),response:sR,ws:`controls`},presence:{body:cR.omit({user:!0,lastActiveAt:!0}),ws:`presence`}})}),hB=X({endpoints:Z(Q,$).group({background:{body:S({run:A}),response:S({accepted:b()}),ws:`background`},undoTurn:{body:S({turn:cl}),response:_j,ws:`undoTurn`},continueTurn:{body:S({turn:cl}),response:S({turn:cl,run:A}),ws:`continueTurn`},tree:{body:S({turn:cl}),response:gj,ws:`tree`},run:{body:S({run:A}),response:aj,ws:`run`},llmCall:{body:S({id:fl}),response:hj,ws:`llmCall`},waiting:{body:S({session:j}),response:rB,ws:`waiting`},approve:{body:S({approval:gl,approve:b(),remember:HI,reason:v().optional(),answer:O.optional()}),response:UI,ws:`approve`},answer:{body:S({call:dl,value:O}),ws:`answer`},act:{body:S({session:j,system:F,action:v(),input:O,run:A.optional(),client:cE}),response:S({delivery:ul}),ws:`act`},submit:{body:S({run:A,value:O}),response:S({delivery:ul}),ws:`submit`},state:{body:S({run:A}),response:S({system:F,fields:x(sj)}),ws:`state`}})}),gB=X({endpoints:Z(Q,$).group({suggest:{body:S({session:j,text:v(),limit:y().int().min(1).max(20).optional()}),response:x(tB),ws:`suggest`},mentions:{body:S({session:j,provider:I,query:v()}),response:x(JN),ws:`mentions`},mentionHover:{body:S({session:j,provider:I,target:O}),response:S({hover:YN.optional()}),ws:`mentionHover`},resource:{body:S({uri:qx,want:x(tS)}),response:rS,ws:`resource`}})}),_B=X({endpoints:Z(Q,$).group({notifications:{body:fB,response:Vl(uF),ws:`notifications`},readNotifications:{body:S({ids:x(uF.shape.id)}),ws:`readNotifications`},pushKey:{method:`GET`,response:S({publicKey:v()}),ws:`pushKey`},subscribePush:{body:dF.pick({endpoint:!0,keys:!0,device:!0}),response:dF.pick({id:!0}),ws:`subscribePush`}})}),vB=X({endpoints:Z(Q,$).group({upload:{body:S({name:v(),mime:v(),size:y().int().min(0)}),response:S({url:v(),upload:v()}),ws:`upload`},uploaded:{body:S({upload:v()}),response:Zx,ws:`uploaded`},transcribe:{body:S({audio:Zx}),response:S({text:v()}),ws:`transcribe`}})}),yB=S({section:E([`fns`,`context`]),name:I,on:b()}),bB=S({system:F,section:UF.exclude([`fns`,`context`]),name:v().min(1),on:b()}),xB=X({endpoints:Z(Q,$,Qz).group({systems:{body:S({query:jj.optional()}),response:x(oB),ws:`systems`},system:{body:S({system:F}),response:oB,ws:`system`},pairings:{body:S({status:bP.shape.status.optional()}),response:x(bP),ws:`pairings`},approvePairing:{body:S({pairing:pl,approve:b(),instance:L.optional(),config:O.optional(),autoPair:oP.optional(),store:yM.optional()}),response:S({system:F.optional()}),ws:`approvePairing`},createPairingToken:{body:S({name:F.optional(),expiresIn:Ml,autoPair:oP.optional()}),response:S({token:v(),expiresAt:N}),ws:`createPairingToken`},configureSystem:{body:S({system:F,config:O,instance:L.optional()}),response:C([S({version:y().int()}),S({problems:x(v())})]),ws:`configureSystem`},enableSystem:{body:S({system:F,functions:b().optional(),renderers:b().optional(),context:b().optional()}),response:S({enabled:hP}),ws:`enableSystem`},switchItem:{body:yB,response:S({on:b()}),ws:`switchItem`},switchPart:{body:bB,response:S({on:b()}),ws:`switchPart`},removeSystem:{body:S({system:F,keepStore:b().optional()}),response:S({fnsUnavailable:y().int()}),ws:`removeSystem`},installSystem:{body:S({source:dP,config:O.optional(),autoStart:b().optional(),store:yM.optional()}),response:S({name:F}),ws:`installSystem`},systemStore:{body:S({system:F,instance:L.optional()}),response:VM,ws:`systemStore`},systemStoreMove:{body:S({system:F,instance:L.optional(),to:yM,runs:IM.optional()}),response:zM,ws:`systemStoreMove`},systemStoreMoveState:{body:S({system:F,instance:L.optional()}),response:S({move:zM.optional()}),ws:`systemStoreMoveState`},systemStoreMoveAnswer:{body:S({system:F,instance:L.optional(),answer:LM}),response:zM,ws:`systemStoreMoveAnswer`},systemStoreBackups:{body:S({system:F,instance:L.optional()}),response:x(NM),ws:`systemStoreBackups`},systemStoreBackupDelete:{body:S({system:F,instance:L.optional(),backup:MM}),response:S({deleted:D(!0),note:v().optional()}),ws:`systemStoreBackupDelete`},startSystem:{body:S({system:F,instance:L.optional()}),response:S({ok:b()}),ws:`startSystem`},stopSystem:{body:S({system:F,instance:L.optional()}),response:S({ok:b()}),ws:`stopSystem`},restartSystem:{body:S({system:F,instance:L.optional(),reason:v().min(1).max(200)}),response:S({ok:b()}),ws:`restartSystem`},upgradeSystem:{body:S({system:F,version:v().optional()}),response:S({from:v(),to:v()}),ws:`upgradeSystem`},reimport:{body:S({system:F}),response:RN,ws:`reimport`}})}),SB=X({endpoints:Z(Q,$,Qz).group({configureProvider:{body:nB,response:S({models:y().int()}),ws:`configureProvider`},providers:{body:S({}),response:x(S({id:Tl,provider:OA,models:y().int()})),ws:`providers`},setModelCategory:{body:kA.partial({id:!0}),response:kA.pick({id:!0}),ws:`setModelCategory`},setBudget:{body:NA.omit({setBy:!0}).partial({id:!0}),response:NA.pick({id:!0}),ws:`setBudget`},setPriority:{body:PA.omit({setBy:!0}).partial({id:!0}),response:PA.pick({id:!0}),ws:`setPriority`},setPolicy:{body:VI.omit({createdBy:!0,createdAt:!0}).partial({id:!0}),response:VI.pick({id:!0}),ws:`setPolicy`},setActorSetting:{body:S({setting:I,actor:M,value:O}),response:S({ok:b()}),ws:`setActorSetting`},addUser:{body:S({email:Ns(),name:v(),role:MI,groups:x(M).optional()}),response:S({id:M}),ws:`addUser`},addGroup:{body:S({name:v(),about:v(),members:x(M).optional()}),response:S({id:M}),ws:`addGroup`},updateUser:{body:dL,response:S({id:M}),ws:`updateUser`},setMembership:{body:fL,response:S({ok:b()}),ws:`setMembership`},setSignInPolicy:{body:JI,response:JI,ws:`setSignInPolicy`},setSignInLimits:{body:ZI,response:ZI,ws:`setSignInLimits`},setProxyTrust:{body:$I,response:$I,ws:`setProxyTrust`}})}),CB=X({endpoints:Z(Q,$,Qz).group({systemFns:{body:S({system:F}),response:x(CP),ws:`systemFns`},systemParts:{body:NP,response:PP,ws:`systemParts`},systemLogs:{body:S({system:F,limit:y().int().min(1).max(2e3).optional()}),response:x(qP),ws:`systemLogs`},models:{body:S({provider:Tl.optional()}),response:x(XP),ws:`models`},modelCategories:{body:S({}),response:x(kA),ws:`modelCategories`},budgets:{body:S({}),response:x(QP),ws:`budgets`},priorityRules:{body:S({}),response:x(PA),ws:`priorityRules`},resolveLimits:{body:S({user:M,session:j.optional()}),response:FA,ws:`resolveLimits`},policies:{body:S({}),response:x(VI),ws:`policies`},actors:{body:S({kind:Bl.optional()}),response:x(PI),ws:`actors`},actorSettings:{body:S({}),response:S({declared:x($P),values:x(II)}),ws:`actorSettings`},runs:{body:Hl.extend({query:jj.optional()}),response:Vl(aj),ws:`runs`},llmCalls:{body:Hl.extend({query:jj.optional()}),response:Vl(eF),ws:`llmCalls`},resources:{body:Hl.extend({query:jj.optional()}),response:Vl(nF),ws:`resources`},removeRule:{body:tF,response:S({ok:b()}),ws:`removeRule`},indexStatus:{body:S({}),response:JP,ws:`indexStatus`}}),events:{systemLog:{params:S({system:F}),data:qP,guard:[$,Qz],ws:`on.systemLog`}}}),wB=rT(`ownEvents`,{requires:[$]}),TB=rT(`sessionWatch`,{requires:[$]}),EB=S({user:M}),DB=X({endpoints:{},events:{session:{params:S({session:j}),data:sB,guard:[$,TB],ws:`on.session`},user:{params:EB,data:cB,guard:[$,wB],ws:`on.user`}}}),OB=Vl(nF).extend({facets:x(XE)}),kB=S({record:nF,forms:x(zE),offers:x(BE)}),AB=X({endpoints:Z(Q,$).group({browseResources:{body:ZE.extend({query:jj.optional()}),response:OB,ws:`browseResources`},resourceForms:{body:S({uri:qx}),response:kB,ws:`resourceForms`},readResource:{body:nD,response:rD,ws:`readResource`},convertResource:{body:S({uri:qx,kind:aS}),response:zE,ws:`convertResource`},downloadResource:{body:S({uri:qx,form:aS.optional()}),response:S({url:v(),mime:v(),size:y().int().min(0)}),ws:`downloadResource`},importResource:{body:iD,response:nF,ws:`importResource`},renameResource:{body:S({uri:qx,name:v().min(1)}),response:nF,ws:`renameResource`},deleteResource:{body:S({uri:qx}),response:S({deleted:b(),referencedBy:y().int().min(0)}),ws:`deleteResource`},contextFromResource:{body:PS,response:FS,ws:`contextFromResource`}})}),jB=Hl.extend({query:jj.optional()}),MB=S({record:DP,links:x(kS),backlinks:x(kS),text:v().optional()}),NB=X({endpoints:Z(Q,$).group({contexts:{body:jB,response:Vl(TF),ws:`contexts`},contextItem:{body:S({name:I}),response:MB,ws:`contextItem`},remember:{body:jS,response:S({name:I}),ws:`remember`},updateMemory:{body:NS,response:S({name:I}),ws:`updateMemory`},forget:{body:S({name:I}),response:S({ok:b()}),ws:`forget`},linkContext:{body:S({from:I,to:TS,relation:wS,weight:y().min(0).max(1)}),response:kS,ws:`linkContext`},unlinkContext:{body:kS.pick({from:!0,toKey:!0,relation:!0}),response:S({ok:b()}),ws:`unlinkContext`}})}),PB=aT(X({endpoints:Z(Q,$).group({contextMetadata:{body:S({name:I}),response:pC,ws:`contextMetadata`},setContextStatus:{body:tC,response:nC,ws:`setContextStatus`}})}),X({endpoints:Z(Q,$,Qz).group({contextReview:{body:aC,response:sC,ws:`contextReview`},mergeContext:{body:cC,response:lC,ws:`mergeContext`},notDuplicate:{body:uC,response:S({ok:b()}),ws:`notDuplicate`},reextractContext:{body:dC,response:fC,ws:`reextractContext`},newContextStatus:{body:S({}),response:XS,ws:`newContextStatus`},setNewContextStatus:{body:S({value:YS}),response:XS,ws:`setNewContextStatus`}})})),FB=X({endpoints:Z(Q,$).group({contextPlans:{body:FC,response:IC,ws:`contextPlans`},contextPlan:{body:DC,response:OC,ws:`contextPlan`},answerPlan:{body:jC,response:MC,ws:`answerPlan`}})}),IB=aT(X({endpoints:Z(Q,$).group({modelLimits:{body:S({model:v().optional()}),response:x(wx),ws:`modelLimits`},previewSelection:{body:S({session:j,text:v()}),response:kx,ws:`previewSelection`}})}),X({endpoints:Z(Q,$,Qz).group({setModelLimits:{body:S({model:v().min(1),limits:bx}),response:wx,ws:`setModelLimits`},previewPrompt:{body:Ax,response:jx,ws:`previewPrompt`}})})),LB=X({endpoints:Z(Q,$,Qz).group({modelRoles:{body:S({}),response:x(nO),ws:`modelRoles`},setModelRole:{body:eO,response:nO,ws:`setModelRole`},clearModelRole:{body:S({role:qD}),response:nO,ws:`clearModelRole`}})}),RB=Hl.extend({run:A.optional(),query:jj.optional()}),zB=X({endpoints:Z(Q,$,Qz).group({modelCalls:{body:RB,response:Vl(WD),ws:`modelCalls`},modelCall:{body:S({id:Ol}),response:WD,ws:`modelCall`},fnMetrics:{body:fO,response:x(dO),ws:`fnMetrics`},fnMetricsDays:{body:S({fn:I,days:y().int().min(1).max(365).optional()}),response:x(uO),ws:`fnMetricsDays`}})}),BB=X({endpoints:Z(Q,$,Qz).group({mcps:{body:S({}),response:x(GR),ws:`mcps`},mcp:{body:S({mcp:kl}),response:GR,ws:`mcp`},createMcp:{body:VR,response:S({mcp:GR,secret:v()}),ws:`createMcp`},updateMcp:{body:VR.partial().extend({mcp:kl}),response:GR,ws:`updateMcp`},rotateMcpSecret:{body:S({mcp:kl}),response:S({secret:v()}),ws:`rotateMcpSecret`},deleteMcp:{body:S({mcp:kl}),response:S({ok:b()}),ws:`deleteMcp`},previewMcp:{body:S({rules:RR}),response:UR,ws:`previewMcp`},mcpSessions:{body:S({mcp:kl}),response:x(WR),ws:`mcpSessions`}})}),VB=X({endpoints:Z(Q,$,Qz).group({pairing:{body:S({pairing:pl}),response:bP,ws:`pairing`},instances:{body:S({system:F}),response:x(iB),ws:`instances`},installPackage:{body:S({zip:Zx,instance:L.optional(),config:O.optional(),data:Zx.optional(),autoStart:b().optional(),store:yM.optional()}),response:ql,ws:`installPackage`},removeInstance:{body:ql.extend({keepStore:b().optional()}),response:S({ok:b()}),ws:`removeInstance`},addInstance:{body:KP,response:ql,ws:`addInstance`},exportSystemData:{body:ql.extend({withSecrets:b().optional()}),response:Zx.extend({url:v()}),ws:`exportSystemData`}})}),HB=aT(X({endpoints:Z(Q,$).group({query:{body:Gj,response:Kj,ws:`query`},listValues:{body:Wj,response:x(Uj),ws:`listValues`}})}),X({endpoints:Z(Q,$,Qz).group({fns:{body:jj,response:Vl(CP),ws:`fns`}})})),UB=X({endpoints:Z(Q,$,Qz).group({suggestDecision:{body:S({}),response:ML,ws:`suggestDecision`},setSuggestDecision:{body:DL,response:ML,ws:`setSuggestDecision`},searchDecisions:{body:S({}),response:RL,ws:`searchDecisions`},setSearchDecision:{body:zL,response:RL,ws:`setSearchDecision`},previewSuggestions:{body:S({session:j,text:v().min(1)}),response:wL,ws:`previewSuggestions`}})}),WB=X({endpoints:Z(Q,$,Qz).group({imageEmbedding:{body:S({}),response:AI,ws:`imageEmbedding`},setImageEmbedding:{body:EI,response:AI,ws:`setImageEmbedding`}})}),GB=aT(X({endpoints:Z(Q,$).group({outsideImages:{body:S({}),response:Bb,ws:`outsideImages`}})}),X({endpoints:Z(Q,$,Qz).group({setOutsideImages:{body:S({value:zb}),response:Bb,ws:`setOutsideImages`}})})),KB=aT(X({endpoints:Z(Q,$).group({https:{body:S({}),response:Wb,ws:`https`}})}),X({endpoints:Z(Q,$,Qz).group({setHttps:{body:S({on:b()}),response:Wb,ws:`setHttps`}})})),qB=X({endpoints:Z(Q,$,Qz).group({autoPairs:{body:S({system:F.optional()}),response:x(lP),ws:`autoPairs`},revokeAutoPair:{body:S({id:Al}),response:S({ok:b()}),ws:`revokeAutoPair`}})}),JB=X({endpoints:Z(Q,$).group({accessInfo:{body:S({}),response:yO,ws:`accessInfo`},access:{body:S({targets:x(gO).min(1).max(200)}),response:x(vO),ws:`access`},setAccess:{body:S({target:gO,sharing:hO.omit({owner:!0})}),response:vO,ws:`setAccess`}})}),YB=X({endpoints:Z(Q,$).group({connectPages:{body:S({}),response:x(PO),ws:`connectPages`},connect:{body:S({system:F,instance:L.optional(),key:OO.optional(),form:O.optional()}),response:C([S({url:Ib}),S({connection:NO})]),ws:`connect`,httpOnly:!0},updateConnection:{body:BO,response:NO,ws:`updateConnection`},disconnect:{body:S({connection:jl}),response:S({ok:b()}),ws:`disconnect`}})}),XB=X({endpoints:Z(Q,$).group({pick:{body:CO,response:x(wO),ws:`pick`}})}),ZB=X({endpoints:Z(Q,$).group({approvals:{body:S({runs:x(A).min(1).max(200)}),response:x(UI),ws:`approvals`}})}),QB=X({endpoints:Z(Q,$).group({contributions:{body:S({registry:I}),response:x(Ik),ws:`contributions`},systemPages:{body:S({}),response:x(CA),ws:`systemPages`},systemInstances:{body:S({system:F}),response:x(wA),ws:`systemInstances`}})}),$B=aT(X({endpoints:Z(Q,$).group({searchFns:{body:yF,response:OF,ws:`searchFns`},fnExamples:{body:mF,response:hF,ws:`fnExamples`},fnFacts:{body:S({fn:I,args:O.optional()}),response:jF,ws:`fnFacts`},fnsOfModelNames:{body:S({names:x(v().min(1).max(64)).min(1).max(200)}),response:T(v(),I),ws:`fnsOfModelNames`},clientLogs:{body:IF,response:LF,ws:`clientLogs`}})}),X({endpoints:Z(Q,$,Qz).group({autoClassifier:{body:S({}),response:FF,ws:`autoClassifier`},setAutoClassifier:{body:PF,response:FF,ws:`setAutoClassifier`}})})),eV=X({endpoints:Z(Q,$).group({exploreRoots:{body:S({system:F,instance:L.optional()}),response:x(Qx),ws:`exploreRoots`},exploreList:{body:S({uri:qx,cursor:v().optional()}),response:Vl($x),ws:`exploreList`},exploreRead:{body:S({uri:qx,want:x(tS).min(1)}),response:rS,ws:`exploreRead`}})}),tV=X({endpoints:Z(Q,$,Qz).group({systemReview:{body:S({system:F}),response:aI,ws:`systemReview`},goLive:{body:oI,response:S({stage:Sk,hash:v()}),ws:`goLive`},approveReview:{body:oI,response:S({hash:v()}),ws:`approveReview`},rejectReview:{body:S({system:F,hash:v().min(1)}),response:S({ok:b()}),ws:`rejectReview`},decideReview:{body:sI,response:cI,ws:`decideReview`},testCall:{body:uI,response:S({run:A}),ws:`testCall`},refusals:{body:rI,response:iI,ws:`refusals`}})}),nV=X({endpoints:Z(Q,$).group({graph:{body:az,response:oz,ws:`graph`}})}),rV=S({agent:I.optional(),context:I.optional(),mode:cx.optional(),fnMode:Px.optional()}),iV=X({endpoints:Z(Q,$,Qz).group({injections:{body:rV,response:$b,ws:`injections`},setInjection:{body:ex,response:Qb,ws:`setInjection`}})}),aV=aT(X({endpoints:Z(Q).group({identity:{method:`GET`,response:CI,ws:`identity`}})}),X({endpoints:Z(Q,$,Qz).group({setHubName:{body:wI,response:CI,ws:`setHubName`}})})),oV=X({endpoints:Z(Q,$,Qz).group({people:{body:jj,response:Vl(lL),ws:`people`},groups:{body:jj,response:Vl(uL),ws:`groups`},groupMembers:{body:Hl.extend({group:M}),response:Vl(FI).extend({group:uL}),ws:`groupMembers`},signInSettings:{body:S({}),response:nL,ws:`signInSettings`},checkSsoProvider:{body:S({provider:WI}),response:iL,ws:`checkSsoProvider`},testSsoSignIn:{body:S({provider:WI}),response:S({url:Ib,test:v()}),ws:`testSsoSignIn`,httpOnly:!0},ssoTestResult:{body:S({test:v()}),response:sL,ws:`ssoTestResult`}})}),sV=X({endpoints:Z(Q,$).group({itemVersions:{body:JR,response:YR,ws:`itemVersions`}})}),cV=X({endpoints:Z(Q,$).group({dataSets:{body:sM,response:cM,ws:`dataSets`},records:{body:Zj,response:Qj,ws:`records`},record:{body:eM,response:S({record:Yj.optional()}),ws:`record`},recordTable:{body:$j,response:Bk,ws:`recordTable`},saveRecord:{body:tM,response:Yj,ws:`saveRecord`},updateRecord:{body:nM,response:Yj,ws:`updateRecord`},removeRecord:{body:rM,response:S({removed:b()}),ws:`removeRecord`},recordVersions:{body:iM,response:aM,ws:`recordVersions`}})}),lV=aT(lB,mB,hB,gB,_B,vB,xB,SB,CB,DB,AB,NB,PB,FB,IB,LB,zB,BB,VB,HB,UB,qB,WB,GB,KB,JB,YB,XB,ZB,QB,$B,eV,tV,nV,iV,aV,sV,cV,X({endpoints:Z(Q,$).group({rowActions:{body:Gz,response:x(Hz),ws:`rowActions`},readFn:{body:qz,response:O,ws:`readFn`}})}),X({endpoints:Z(Q,$).group({export:{method:`GET`,query:Jz,streamOut:`text/csv`,download:`export.csv`}})}),oV),uV={load_fns:`fns_load`,drop_fns:`fns_drop`,fn_examples:`fns_examples`,fn_get:`fns_get`,save_fn:`fns_save`,fn_metrics:`fns_metrics`,load_context:`ctx_load`,context_get:`ctx_get`,context_crawl:`ctx_crawl`,context_from_resource:`ctx_from_resource`,context_link:`ctx_link`,context_unlink:`ctx_unlink`};new Map(Object.entries(uV).map(([e,t])=>[`hub/${e}`,`hub/${t}`])),new Map(Object.entries(uV));var dV=E([`added`,`modified`,`deleted`,`renamed`]),fV=E([`binary`,`large`,`sensitive`,`not-in-git`]),pV=S({path:v().min(1),root:v().min(1),status:dV,from:v().min(1).optional(),size:y().int().min(0).optional(),diff:v().optional(),added:y().int().min(0).optional(),removed:y().int().min(0).optional(),noDiff:fV.optional(),sensitive:Gk.optional(),certain:b()}),mV=S({source:E([`git`,`watcher`]),cwd:v().min(1),files:x(pV),ignored:y().int().min(0),truncated:b()}),hV=S({arg:k,label:v().min(1).optional(),choices:x(O).min(1).optional(),custom:b().optional(),pinned:O.optional(),hidden:b().optional()}),gV=S({offset:k.optional(),limit:k.optional(),size:y().int().min(1).max(500)}),_V=S({visual:k,label:v().min(1).optional(),bind:T(k,x(v().min(1)).min(1))}),vV=E([`refresh`,`show`,`none`]),yV=S({fn:I,label:v().min(1).optional(),confirm:D(!0).optional(),bind:T(k,v().min(1)),then:vV});S({title:v().min(1),source:I,visuals:x(_V).min(1),controls:x(hV),paging:gV.optional(),actions:x(yV).optional()});var bV=uF.pick({id:!0,title:!0,body:!0,link:!0,reason:!0,also:!0,key:!0,tone:!0}),xV=`open`,SV=E([`link`,`also`]),CV=`also`;function wV(e,t=`link`){return`/inbox?${xV}=${encodeURIComponent(e.id)}${t===`also`?`&via=also`:``}`}function TV(e){return e.key??e.id}function EV(e){return e.also===void 0?{link:wV(e)}:{link:wV(e),also:wV(e,`also`)}}function DV(e,t){let n=e=>typeof e==`string`&&e.startsWith(`/`)&&!e.startsWith(`//`);if(n(e))return e;if(typeof e==`object`&&e){let r=Reflect.get(e,`also`),i=Reflect.get(e,`link`);if(t===`also`&&n(r))return r;if(n(i))return i}return`/inbox`}export{VR as $,cl as $a,hv as $i,WE as $n,AS as $r,IN as $t,hB as A,wf as Aa,xb as Ai,mA as An,ic as Ao,xT as Ar,PF as At,Gz as B,Kl as Ba,Zg as Bi,AO as Bn,T as Bo,wC as Br,AP as Bt,iV as C,Ff as Ca,Hb as Ci,XA as Cn,yc as Co,MT as Cr,DI as Ct,VB as D,Sf as Da,Db as Di,bA as Dn,pc as Do,AT as Dr,SI as Dt,LB as E,Pf as Ea,Ab as Ei,OA as En,ws as Eo,OT as Er,bI as Et,Jz as F,kl as Fa,Jg as Fi,Bk as Fn,D as Fo,ZC as Fr,CF as Ft,Pz as G,Ll as Ga,Vv as Gi,cO as Gn,Ls as Go,mC as Gr,kP as Gt,Zz as H,Ol as Ha,Vg as Hi,bO as Hn,vc as Ho,NC as Hr,dP as Ht,Iz as I,L as Ia,Ov as Ii,bk as In,fc as Io,Hw as Ir,OF as It,hz as J,Wl as Ja,i_ as Ji,JD as Jn,LC as Jr,ZN as Jt,Nz as K,pl as Ka,kv as Ki,oO as Kn,vC as Kr,QN as Kt,Wz as L,O as La,Yg as Li,yk as Ln,y as Lo,Gw as Lr,vF as Lt,UB as M,M as Ma,qg as Mi,Ik as Mn,b as Mo,vT as Mr,hF as Mt,xB as N,Bl as Na,Hg as Ni,Lk as Nn,w as No,lT as Nr,mF as Nt,HB as O,If as Oa,ib as Oi,xA as On,oc as Oo,jT as Or,HF as Ot,sV as P,zl as Pa,Lv as Pi,Rk as Pn,Zc as Po,dT as Pr,bF as Pt,XR as Q,N as Qa,Zv as Qi,RE as Qn,PS as Qr,uN as Qt,Kz as R,fl as Ra,Xg as Ri,fk as Rn,S as Ro,jC as Rr,BF as Rt,lV as S,mf as Sa,Kb as Si,cj as Sn,Vc as So,PT as Sr,RI as St,zB as T,xf as Ta,Tb as Ti,UA as Tn,Uc as To,DT as Tr,EI as Tt,Yz as U,Jl as Ua,Rv as Ui,mO as Un,C as Uo,DC as Ur,wP as Ut,Uz as V,ll as Va,Qg as Vi,OO as Vn,v as Vo,TC as Vr,DP as Vt,Xz as W,xl as Wa,Nv as Wi,_O as Wn,sc as Wo,OC as Wr,OP as Wt,ez as X,j as Xa,Uv as Xi,kD as Xn,rC as Xr,dN as Xt,Az as Y,A as Ya,r_ as Yi,eO as Yn,GC as Yr,aP as Yt,az as Z,F as Za,c_ as Zi,sD as Zn,$S as Zr,bN as Zt,NB as _,Bh as _a,vx as _i,zj as _n,$s as _o,BT as _r,bL as _t,DV as a,m_ as aa,NS as ai,pM as an,ac as ao,JE as ar,rR as at,eV as b,hf as ba,lx as bi,Hj as bn,zc as bo,VT as br,ZI as bt,mV as c,Hv as ca,Yx as ci,SM as cn,Lc as co,wE as cr,vL as ct,JB as d,g_ as da,oS as di,lM as dn,xc as do,OE as dr,NL as dt,u_ as ea,CS as ei,jN as en,nl as eo,eD as er,LR as et,CB as f,v_ as fa,Jx as fi,Yj as fn,Gc as fo,kE as fr,_L as ft,PB as g,Am as ga,sx as gi,Vj as gn,kc as go,rE as gr,TL as gt,YB as h,nb as ha,Nx as hi,kj as hn,rc as ho,nE as hr,DL as ht,bV as i,p_ as ia,jS as ii,_M as in,Il as io,$E as ir,QL as it,SB as j,Gl as ja,hb as ji,Fk as jn,x as jo,yT as jr,xF as jt,AB as k,uf as ka,rb as ki,fA as kn,E as ko,CT as kr,$F as kt,nB as l,Yv as la,aS as li,wM as ln,qc as lo,DE as lr,SL as lt,mB as m,b_ as ma,hx as mi,Jj as mn,Fc as mo,tE as mr,OL as mt,SV as n,f_ as na,ES as ni,HN as nn,Ul as no,YE as nr,HR as nt,TV as o,Dv as oa,hS as oi,yM as on,uc as oo,jE as or,GL as ot,qB as p,U as pa,Kx as pi,qj as pn,Sc as po,SE as pr,EL as pt,sz as q,I as qa,Gv as qi,qD as qn,KC as qr,iP as qt,xV as r,Ug as ra,TS as ri,tN as rn,Fl as ro,QE as rr,IR as rt,EV as s,Pv as sa,pS as si,hM as sn,nc as so,_E as sr,nR as st,CV as t,d_ as ta,DS as ti,VN as tn,tl as to,tD as tr,FR as tt,$z as u,h_ as ua,qx as ui,uM as un,jc as uo,AE as ur,FL as ut,IB as v,yf as va,tx as vi,wj as vn,dc as vo,FT as vr,qI as vt,BB as w,df as wa,Lb as wi,BA as wn,Es as wo,kT as wr,TI as wt,nV as x,Tf as xa,qb as xi,vj as xn,Nc as xo,GT as xr,pL as xt,cV as y,Nf as ya,bx as yi,Tj as yn,Tc as yo,KT as yr,$I as yt,Hz as z,k as za,Fv as zi,UO as zn,Ec as zo,MC as zr,lF as zt};
|
|
402
|
+
//# sourceMappingURL=push-payload-C1ppI5V2.js.map
|