@objectstack/console 17.0.0-rc.0 → 17.0.0-rc.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/CHANGELOG.md +1096 -0
- package/README.md +8 -3
- package/dist/.objectui-sha +1 -1
- package/dist/assets/{AdapterProvider-ClCj6PTd.js → AdapterProvider-DCL4oNgv.js} +1 -1
- package/dist/assets/{AiPendingActionsPage-bedYcbz0.js → AiPendingActionsPage-BvvDIWEC.js} +1 -1
- package/dist/assets/{ApiConsolePage-DdUlsQNo.js → ApiConsolePage-Dvr5-g2X.js} +1 -1
- package/dist/assets/{AppDocsIndex-DySIC06n.js → AppDocsIndex-Ohwtpos8.js} +1 -1
- package/dist/assets/{AppManagementPage-8S-uDSdv.js → AppManagementPage-DhsvWTeZ.js} +1 -1
- package/dist/assets/ApprovalsInboxPage-BfaGtcxV.js +1 -0
- package/dist/assets/AuditLogPage-D_09WrLX.js +1 -0
- package/dist/assets/{ComponentNavView-BOxZS4Hn.js → ComponentNavView-C6J3w2IE.js} +1 -1
- package/dist/assets/CreateViewDialog-R7kwDoaF.js +1 -0
- package/dist/assets/{DashboardView-Co21jHAg.js → DashboardView-B-5HkqOl.js} +1 -1
- package/dist/assets/{DeveloperHubPage-B3CL_2_R.js → DeveloperHubPage-p9oQnZuU.js} +1 -1
- package/dist/assets/{DocShell-Bswx8gyj.js → DocShell-B8d7-ARz.js} +1 -1
- package/dist/assets/ExpressionProvider-BLhGrCBw.js +1 -0
- package/dist/assets/FlowRunsPage-DzZmtrDe.js +1 -0
- package/dist/assets/{IntegrationsPage-DwRFenrv.js → IntegrationsPage-DzBKAEgn.js} +2 -2
- package/dist/assets/InterfaceListPage-C_M0U8ns.js +1 -0
- package/dist/assets/{ManagedByBadge-BuKzVw4f.js → ManagedByBadge-DWtOXcFq.js} +1 -1
- package/dist/assets/MarketplaceAccessDenied-C4Yrv4Q7.js +1 -0
- package/dist/assets/{MarketplaceInstalledPage-zxinYFxx.js → MarketplaceInstalledPage-B6cbDzf8.js} +1 -1
- package/dist/assets/MarketplacePackagePage-D0dT7D3x.js +4 -0
- package/dist/assets/{MarketplacePage-C2tmfrC4.js → MarketplacePage-CtvxvBmw.js} +1 -1
- package/dist/assets/{MetadataInspector-BT_WB0Z2.js → MetadataInspector-9pMeoWpd.js} +1 -1
- package/dist/assets/{MetadataProvider-CaobQzBK.js → MetadataProvider-Y0oNNDXh.js} +1 -1
- package/dist/assets/ObjectDataPage-B8pGSNRJ.js +1 -0
- package/dist/assets/PageView-BBJl1RzL.js +1 -0
- package/dist/assets/ProfilePage-BL4aVTUO.js +1 -0
- package/dist/assets/PublicFormsPage-C-BWDI8O.js +1 -0
- package/dist/assets/RecordDetailView-BYYpDJSj.js +9 -0
- package/dist/assets/RecordFormPage-SLtEal-m.js +1 -0
- package/dist/assets/ReportDefaultInspector-B3KEMC9M.js +3 -0
- package/dist/assets/{ReportView-BPnukjAJ.js → ReportView-B3kMHgHe.js} +1 -1
- package/dist/assets/{SearchResultsPage-BrU2uBVw.js → SearchResultsPage-0eeyyaj-.js} +1 -1
- package/dist/assets/{SettingsHub-Be1x-xx5.js → SettingsHub-BVhaidAC.js} +1 -1
- package/dist/assets/SettingsView-D2klvVKS.js +1 -0
- package/dist/assets/{SystemHubPage-C7E2MVCX.js → SystemHubPage-CHcrvd-n.js} +1 -1
- package/dist/assets/{abnfDiagram-VRR7QNED-Hg1RYCKu.js → abnfDiagram-VRR7QNED-D2Rn6aHa.js} +1 -1
- package/dist/assets/{architectureDiagram-ZJ3FMSHR-DwfUOkLv.js → architectureDiagram-ZJ3FMSHR-DX6q2vGN.js} +1 -1
- package/dist/assets/{blockDiagram-677ZJIJ3-BDc1qSIS.js → blockDiagram-677ZJIJ3-T2IDNrvJ.js} +1 -1
- package/dist/assets/{c4Diagram-LMCZKHZV-B3uEgabN.js → c4Diagram-LMCZKHZV-B98pIIbx.js} +1 -1
- package/dist/assets/channel-BovwC1_7.js +1 -0
- package/dist/assets/{chunk-32BRIVSS-BX7QYsQG.js → chunk-32BRIVSS-CYNomNWc.js} +1 -1
- package/dist/assets/{chunk-52WLFC77-Cx4AaJIv.js → chunk-52WLFC77-DtGIB0uV.js} +2 -2
- package/dist/assets/{chunk-C7G6YPKG-HNW9cqtI.js → chunk-C7G6YPKG-yJXKQ2Sz.js} +1 -1
- package/dist/assets/{chunk-EX3LRPZG-CBmf4uVW.js → chunk-EX3LRPZG-BtAjfq6C.js} +1 -1
- package/dist/assets/{chunk-FWX5IMBZ-Dt6Lwztc.js → chunk-FWX5IMBZ-C4k19ShS.js} +1 -1
- package/dist/assets/{chunk-HOUHSVGY-BiLG0Jtx.js → chunk-HOUHSVGY-BuKclK6G.js} +1 -1
- package/dist/assets/{chunk-ICXQ74PX-V7Gv_S2c.js → chunk-ICXQ74PX-OP102czk.js} +1 -1
- package/dist/assets/{chunk-MOJQB5TN-zlBuobC7.js → chunk-MOJQB5TN-CToOzrGu.js} +1 -1
- package/dist/assets/{chunk-OGEWGWER-D9fNq6KM.js → chunk-OGEWGWER-9rMC3Zdz.js} +1 -1
- package/dist/assets/{chunk-PUDLZKDR-BufZGozB.js → chunk-PUDLZKDR-Bte-Y5BM.js} +1 -1
- package/dist/assets/{chunk-Q4XR5HBZ-C1v9xwSj.js → chunk-Q4XR5HBZ-B1-bRF4T.js} +1 -1
- package/dist/assets/{chunk-RYQCIY6F-Cuf3Er4p.js → chunk-RYQCIY6F-DX0uHAt-.js} +1 -1
- package/dist/assets/{chunk-V7JOEXUC-Bsulk3KW.js → chunk-V7JOEXUC-3Qai_qvf.js} +1 -1
- package/dist/assets/chunk-VAUOI2AC-B2LdZG5j.js +1 -0
- package/dist/assets/{chunk-VR4S4FIN-Cxz-AOSl.js → chunk-VR4S4FIN-C8tYB3zk.js} +1 -1
- package/dist/assets/{chunk-WYO6CB5R-BBCHPFWt.js → chunk-WYO6CB5R-chyhiVml.js} +1 -1
- package/dist/assets/chunk-XXDRQBXY-mZd7tFTQ.js +1 -0
- package/dist/assets/{chunk-ZGVPDNZ5-0VawavzG.js → chunk-ZGVPDNZ5-BHJQa9Yh.js} +1 -1
- package/dist/assets/classDiagram-OUVF2IWQ-opUQX7yT.js +1 -0
- package/dist/assets/classDiagram-v2-EOCWNBFH-opUQX7yT.js +1 -0
- package/dist/assets/{cose-bilkent-JH36ORCC-zGun_nYq.js → cose-bilkent-JH36ORCC-wNn6_7gi.js} +1 -1
- package/dist/assets/{createDerive-DGPok8w-.js → createDerive-DDuw-xzg.js} +1 -1
- package/dist/assets/{cynefinDiagram-TSTJHNR4-DAMk8Cyg.js → cynefinDiagram-TSTJHNR4-BpiN-sI9.js} +1 -1
- package/dist/assets/{dagre-VKFMJZFB-CcgN1PqH.js → dagre-VKFMJZFB-D4jpVOw8.js} +1 -1
- package/dist/assets/data-adapter-DJl5PvjF.js +17 -0
- package/dist/assets/{diagram-FQU43EPY-CQVlA0TA.js → diagram-FQU43EPY-DnGyLgYE.js} +1 -1
- package/dist/assets/{diagram-G47NLZAW-0UcUFyIH.js → diagram-G47NLZAW-BSDChPeN.js} +1 -1
- package/dist/assets/{diagram-NH7WQ7WH-B8E52D9k.js → diagram-NH7WQ7WH-Jir-M8yF.js} +1 -1
- package/dist/assets/{diagram-OA4YK3LP-CAJcB6Ez.js → diagram-OA4YK3LP-DG1np1W1.js} +1 -1
- package/dist/assets/{diagram-WEI45ONY-DWe95hfc.js → diagram-WEI45ONY-DRm_SlrH.js} +1 -1
- package/dist/assets/{ebnfDiagram-CCIWWBDH-vV-mO9pC.js → ebnfDiagram-CCIWWBDH-twfLoKY3.js} +1 -1
- package/dist/assets/{erDiagram-Q63AITRT-C37YlMu-.js → erDiagram-Q63AITRT-CABXVpgy.js} +1 -1
- package/dist/assets/flowDiagram-23GEKE2U-DxGbSmxA.js +1 -0
- package/dist/assets/framework-xOBpLspS.js +8 -0
- package/dist/assets/{ganttDiagram-NO4QXBWP-BbLQFz0H.js → ganttDiagram-NO4QXBWP-DRXGi_1T.js} +2 -2
- package/dist/assets/getIcon-yTDDbwhX.js +1 -0
- package/dist/assets/{gitGraphDiagram-IHSO6WYX-B4EJMjM2.js → gitGraphDiagram-IHSO6WYX-BtlNUS9M.js} +1 -1
- package/dist/assets/{highlighted-body-OFNGDK62-BURNftRE.js → highlighted-body-OFNGDK62-BNY8_Ou8.js} +1 -1
- package/dist/assets/{i18n-B4M18fi2.js → i18n-CWXRbuYk.js} +2 -2
- package/dist/assets/index-ByFHLPS0.js +2 -0
- package/dist/assets/index-QgmPkr95.css +2 -0
- package/dist/assets/{infoDiagram-FWYZ7A6U-ChMO4rou.js → infoDiagram-FWYZ7A6U-CrCNJ5GX.js} +1 -1
- package/dist/assets/infrastructure-EMqAhl6J.js +3 -0
- package/dist/assets/{ishikawaDiagram-FXEZZL3T-B5_tQUWs.js → ishikawaDiagram-FXEZZL3T-aBCt2dnS.js} +1 -1
- package/dist/assets/{journeyDiagram-5HDEW3XC-MxmpMgQO.js → journeyDiagram-5HDEW3XC-CQrIuFhF.js} +1 -1
- package/dist/assets/{kanban-definition-HUTT4EX6-x1u6yhTC.js → kanban-definition-HUTT4EX6-Bm4snCw1.js} +1 -1
- package/dist/assets/mermaid-GHXKKRXX-BN2PjcSK.js +1 -0
- package/dist/assets/{mermaid.core-Bo862wyf.js → mermaid.core-C5ZaZqXX.js} +2 -2
- package/dist/assets/metadata-admin-lW4yChcf.js +25 -0
- package/dist/assets/{mindmap-definition-LN4V7U3C-gv5cgZkr.js → mindmap-definition-LN4V7U3C-CzSOJVqY.js} +1 -1
- package/dist/assets/{pegDiagram-2B236MQR-BUvOaGez.js → pegDiagram-2B236MQR-DPkw74l3.js} +1 -1
- package/dist/assets/{pieDiagram-ENE6RG2P-CYsklKtm.js → pieDiagram-ENE6RG2P-Bnny8SeQ.js} +1 -1
- package/dist/assets/plugin-calendar-Dikj_A8Y.js +1 -0
- package/dist/assets/plugin-charts-_11K-vFF.js +7 -0
- package/dist/assets/plugin-chatbot-D5bVXJ_O.js +120 -0
- package/dist/assets/plugin-dashboard-QnlQx94Y.js +6 -0
- package/dist/assets/plugin-form-C8ibDrVW.js +1 -0
- package/dist/assets/plugin-gantt-ION4WU11.js +63 -0
- package/dist/assets/plugin-grid-BbCjdxhg.js +8 -0
- package/dist/assets/plugin-kanban-DMXe4mrr.js +1 -0
- package/dist/assets/plugin-map-ZzwBPooc.js +1 -0
- package/dist/assets/{plugin-markdown-CwKhoguC.js → plugin-markdown-DWlAZYfS.js} +1 -1
- package/dist/assets/plugin-report-4ufmhN37.js +59 -0
- package/dist/assets/plugin-timeline-CxuwO6Sj.js +1 -0
- package/dist/assets/plugin-tree-CqFsNYBt.js +1 -0
- package/dist/assets/plugin-view-BtrrVg8d.js +1 -0
- package/dist/assets/plugins-views-DuVwtJw-.js +4 -0
- package/dist/assets/{quadrantDiagram-ABIIQ3AL-DkdTo6wC.js → quadrantDiagram-ABIIQ3AL-DUB4EjfP.js} +1 -1
- package/dist/assets/{railroadDiagram-RFXS5EU6-CIvl_CtD.js → railroadDiagram-RFXS5EU6-DSfLwOL9.js} +1 -1
- package/dist/assets/{requirementDiagram-TGXJPOKE-BrmGcoHH.js → requirementDiagram-TGXJPOKE-BUoxthLY.js} +1 -1
- package/dist/assets/{runtime-metadata-persistence-C6n6ChsE.js → runtime-metadata-persistence-D0qPKjRP.js} +1 -1
- package/dist/assets/{sankeyDiagram-HTMAVEWB-DAhnVEku.js → sankeyDiagram-HTMAVEWB-CkjIusFl.js} +2 -2
- package/dist/assets/{sequenceDiagram-DBY2YBRQ-CmnHwkE8.js → sequenceDiagram-DBY2YBRQ-DlUPbsBe.js} +1 -1
- package/dist/assets/{skeletons-D3Ug_cFP.js → skeletons-DBVC-R2R.js} +1 -1
- package/dist/assets/{src-BGaMRjVN.js → src-CEjEbVE_.js} +1 -1
- package/dist/assets/src-CLs1ObAx.js +19 -0
- package/dist/assets/{src-DmkSCLdx.js → src-CQ-hf48v.js} +1 -1
- package/dist/assets/src-Cz3xMnYk.js +1 -0
- package/dist/assets/{src-BvgQ2BWs.js → src-DMTCYJgx.js} +1 -1
- package/dist/assets/{stateDiagram-2N3HPSRC-C4fJzxRx.js → stateDiagram-2N3HPSRC-vPDzyRlO.js} +1 -1
- package/dist/assets/stateDiagram-v2-6OUMAXLB-USH3Z7UN.js +1 -0
- package/dist/assets/{swimlanes-5IMT3BWC-DlIs3eSd.js → swimlanes-5IMT3BWC-mtpJqEnb.js} +1 -1
- package/dist/assets/swimlanesDiagram-G3AALYLV-CJNfyMoX.js +8 -0
- package/dist/assets/{timeline-definition-FHXFAJF6-B6xJ_8dh.js → timeline-definition-FHXFAJF6-vFc3MiyA.js} +1 -1
- package/dist/assets/ui-components-C5rSjsFE.js +72 -0
- package/dist/assets/{ui-layout-fGjoW3uv.js → ui-layout-D13CmhwI.js} +1 -1
- package/dist/assets/{use-book-data-BHNW-mtj.js → use-book-data-BJgo-RvZ.js} +1 -1
- package/dist/assets/useSettingsLabel-BJ1_MAmi.js +1 -0
- package/dist/assets/{vendor-charts-C9Rg4sGZ.js → vendor-charts-BbCFozUm.js} +3 -3
- package/dist/assets/{vendor-i18n-CJQUqRO0.js → vendor-i18n-ign3ofvT.js} +1 -1
- package/dist/assets/vendor-objectstack-ChpQDQzo.js +160 -0
- package/dist/assets/{vennDiagram-L72KCM5P-CL2kA9j_.js → vennDiagram-L72KCM5P-NYy-CpuJ.js} +1 -1
- package/dist/assets/{wardleyDiagram-EHGQE667-C2amdvDW.js → wardleyDiagram-EHGQE667-CB-LOOnu.js} +1 -1
- package/dist/assets/{xychartDiagram-FW5EYKEG-BgaF79Q6.js → xychartDiagram-FW5EYKEG-C04Hz7Q2.js} +2 -2
- package/dist/index.html +4 -4
- package/package.json +3 -2
- package/dist/assets/ApprovalsInboxPage-BezeS0Ba.js +0 -1
- package/dist/assets/AuditLogPage-BU6pDzCM.js +0 -1
- package/dist/assets/CreateViewDialog-CbODG8cr.js +0 -1
- package/dist/assets/ExpressionProvider-rrd8nTWz.js +0 -1
- package/dist/assets/FlowRunsPage-BUoUJIcB.js +0 -1
- package/dist/assets/InterfaceListPage-MefSdQ3L.js +0 -1
- package/dist/assets/MarketplaceAccessDenied-CXpRKhbs.js +0 -1
- package/dist/assets/MarketplacePackagePage-CfD4P1wE.js +0 -4
- package/dist/assets/ObjectDataPage-wTA2HFI2.js +0 -1
- package/dist/assets/PageView-C9Hwdfsl.js +0 -1
- package/dist/assets/ProfilePage-BQwxaOB7.js +0 -1
- package/dist/assets/PublicFormsPage-geV1om2C.js +0 -1
- package/dist/assets/RecordDetailView-BzGkapku.js +0 -9
- package/dist/assets/RecordFormPage-DBo0eZ72.js +0 -1
- package/dist/assets/ReportDefaultInspector-B7Nn-A6p.js +0 -3
- package/dist/assets/SettingsView-CrgWUS7G.js +0 -1
- package/dist/assets/channel-DWZQ9vnS.js +0 -1
- package/dist/assets/chunk-VAUOI2AC-C6BaCKWp.js +0 -1
- package/dist/assets/chunk-XXDRQBXY-DzukX8IV.js +0 -1
- package/dist/assets/classDiagram-OUVF2IWQ-DSs52z7w.js +0 -1
- package/dist/assets/classDiagram-v2-EOCWNBFH-DSs52z7w.js +0 -1
- package/dist/assets/data-adapter-ZwwuAvBG.js +0 -15
- package/dist/assets/flowDiagram-23GEKE2U-DkFOQ3_z.js +0 -1
- package/dist/assets/framework-DAbnem-u.js +0 -8
- package/dist/assets/getIcon-BLwvtaQI.js +0 -1
- package/dist/assets/index-BOGrThXK.css +0 -2
- package/dist/assets/index-C-dRvT9u.js +0 -2
- package/dist/assets/infrastructure-VRE-mbZZ.js +0 -3
- package/dist/assets/mermaid-GHXKKRXX-cZg7E0Lp.js +0 -1
- package/dist/assets/metadata-admin-CKjub8vw.js +0 -25
- package/dist/assets/plugin-calendar-DJdKEkjk.js +0 -1
- package/dist/assets/plugin-charts-DHSgUtpJ.js +0 -7
- package/dist/assets/plugin-chatbot-BjhIyyNM.js +0 -120
- package/dist/assets/plugin-dashboard-CjPCmbr_.js +0 -6
- package/dist/assets/plugin-form-BZooMe4v.js +0 -1
- package/dist/assets/plugin-gantt-C90gyywF.js +0 -63
- package/dist/assets/plugin-grid-UMSBKycd.js +0 -8
- package/dist/assets/plugin-kanban-CTnqV9IW.js +0 -1
- package/dist/assets/plugin-map-DjnC4ang.js +0 -1
- package/dist/assets/plugin-report-BgaatGo3.js +0 -59
- package/dist/assets/plugin-timeline-CqKcdOFC.js +0 -1
- package/dist/assets/plugin-tree-D73sSC3j.js +0 -1
- package/dist/assets/plugin-view-DG76zFsz.js +0 -1
- package/dist/assets/plugins-views-UwSroJxp.js +0 -4
- package/dist/assets/src-DTHo8Eqq.js +0 -1
- package/dist/assets/src-DjmHjms3.js +0 -19
- package/dist/assets/stateDiagram-v2-6OUMAXLB-CCWWu2-O.js +0 -1
- package/dist/assets/swimlanesDiagram-G3AALYLV-C8YV1J6I.js +0 -8
- package/dist/assets/ui-components-Xu43SW6A.js +0 -72
- package/dist/assets/useSettingsLabel-CgY3RtGh.js +0 -1
- package/dist/assets/vendor-objectstack-Bs6C4qGH.js +0 -122
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import{t as e}from"./rolldown-runtime-DAXXjFlN.js";import{Fn as t,Yt as n,_t as r,in as i,t as a}from"./framework-xOBpLspS.js";import{n as o}from"./vendor-zod-DNgwlUUI.js";var s=e((e=>{var t=o();function n(e){if(typeof process<`u`&&{}.OS_EAGER_SCHEMAS===`1`)return e();let t,n=()=>(t===void 0&&(t=e()),t),r=function(){},i,a=e=>{let t=e._zod;if(!t||typeof t.processJSONSchema!=`function`)return t;let n=t.processJSONSchema;return Object.create(t,{processJSONSchema:{enumerable:!0,value:(t,r,i)=>{let a=t?.seen;if(a&&typeof a.get==`function`){let t=a.get(o);t!==void 0&&!a.has(e)&&a.set(e,t)}return n(t,r,i)}}})},o=new Proxy(r,{get(e,t){let r=n();if(t===`_zod`)return i??=a(r),i;let o=r[t];return typeof o==`function`?o.bind(r):o},set(e,t,r){let i=n();return i[t]=r,!0},has(e,t){return t in n()},ownKeys(){return Reflect.ownKeys(n())},getOwnPropertyDescriptor(e,t){return Reflect.getOwnPropertyDescriptor(n(),t)},getPrototypeOf(){return Reflect.getPrototypeOf(n())}});return o}var r=n(()=>t.z.object({$field:t.z.string().describe(`Field Reference/Column Name`)})),i=n(()=>t.z.object({$eq:t.z.any().optional(),$ne:t.z.any().optional()})),a=n(()=>t.z.object({$gt:t.z.union([t.z.number(),t.z.date(),r]).optional(),$gte:t.z.union([t.z.number(),t.z.date(),r]).optional(),$lt:t.z.union([t.z.number(),t.z.date(),r]).optional(),$lte:t.z.union([t.z.number(),t.z.date(),r]).optional()})),s=n(()=>t.z.object({$in:t.z.array(t.z.any()).optional(),$nin:t.z.array(t.z.any()).optional()})),c=n(()=>t.z.object({$between:t.z.tuple([t.z.union([t.z.number(),t.z.date(),r]),t.z.union([t.z.number(),t.z.date(),r])]).optional()})),l=n(()=>t.z.object({$contains:t.z.string().optional(),$notContains:t.z.string().optional(),$startsWith:t.z.string().optional(),$endsWith:t.z.string().optional()})),u=n(()=>t.z.object({$null:t.z.boolean().optional(),$exists:t.z.boolean().optional()})),d=n(()=>t.z.object({$eq:t.z.any().optional(),$ne:t.z.any().optional(),$gt:t.z.union([t.z.number(),t.z.date(),r]).optional(),$gte:t.z.union([t.z.number(),t.z.date(),r]).optional(),$lt:t.z.union([t.z.number(),t.z.date(),r]).optional(),$lte:t.z.union([t.z.number(),t.z.date(),r]).optional(),$in:t.z.array(t.z.any()).optional(),$nin:t.z.array(t.z.any()).optional(),$between:t.z.tuple([t.z.union([t.z.number(),t.z.date(),r]),t.z.union([t.z.number(),t.z.date(),r])]).optional(),$contains:t.z.string().optional(),$notContains:t.z.string().optional(),$startsWith:t.z.string().optional(),$endsWith:t.z.string().optional(),$null:t.z.boolean().optional(),$exists:t.z.boolean().optional()})),f=t.z.lazy(()=>t.z.record(t.z.string(),t.z.unknown()).and(t.z.object({$and:t.z.array(f).optional(),$or:t.z.array(f).optional(),$not:f.optional()}))),p=n(()=>t.z.object({where:f.optional()})),m=t.z.lazy(()=>t.z.object({$and:t.z.array(t.z.union([t.z.record(t.z.string(),d),m])).optional(),$or:t.z.array(t.z.union([t.z.record(t.z.string(),d),m])).optional(),$not:t.z.union([t.z.record(t.z.string(),d),m]).optional()})),h={"=":`$eq`,"==":`$eq`,equals:`$eq`,eq:`$eq`,"!=":`$ne`,"<>":`$ne`,ne:`$ne`,neq:`$ne`,not_equals:`$ne`,notequals:`$ne`,">":`$gt`,gt:`$gt`,greater_than:`$gt`,greaterthan:`$gt`,">=":`$gte`,gte:`$gte`,greater_than_or_equal:`$gte`,greaterthanorequal:`$gte`,greaterorequal:`$gte`,"<":`$lt`,lt:`$lt`,less_than:`$lt`,lessthan:`$lt`,"<=":`$lte`,lte:`$lte`,less_than_or_equal:`$lte`,lessthanorequal:`$lte`,lessorequal:`$lte`,before:`$lt`,after:`$gt`,in:`$in`,nin:`$nin`,not_in:`$nin`,notin:`$nin`,contains:`$contains`,notcontains:`$notContains`,not_contains:`$notContains`,like:`$contains`,startswith:`$startsWith`,starts_with:`$startsWith`,endswith:`$endsWith`,ends_with:`$endsWith`,between:`$between`,is_null:`$null`,is_not_null:`$null`,isnull:`$null`,isnotnull:`$null`,is_empty:`$null`,is_not_empty:`$null`,isempty:`$null`,isnotempty:`$null`},g=new Set(Object.keys(h)),_={$eq:`=`,$ne:`!=`,$gt:`>`,$gte:`>=`,$lt:`<`,$lte:`<=`,$in:`in`,$nin:`nin`,$contains:`contains`,$notContains:`not_contains`,$startsWith:`starts_with`,$endsWith:`ends_with`,$between:`between`};function v(e){let t=String(e).toLowerCase();if(t===`is_null`||t===`isnull`||t===`is_empty`||t===`isempty`)return`is_null`;if(t===`is_not_null`||t===`isnotnull`||t===`is_not_empty`||t===`isnotempty`)return`is_not_null`;if(t===`like`||t===`ilike`)return t;let n=h[t];return n?_[n]??t:t}function y(e){if(!Array.isArray(e)||e.length===0)return!1;let t=e[0];if(typeof t==`string`){let n=t.toLowerCase();if(n===`and`||n===`or`)return e.length>=2&&e.slice(1).every(e=>y(e));if(e.length>=2&&typeof e[1]==`string`)return g.has(e[1].toLowerCase())}return e.every(e=>y(e))?e.length>0:!1}function b(e){let[t,n,r]=e,i=n.toLowerCase();if(i===`=`||i===`==`||i===`equals`||i===`eq`)return{[t]:r};if(i===`is_null`||i===`isnull`||i===`is_empty`||i===`isempty`)return{[t]:{$null:!0}};if(i===`is_not_null`||i===`isnotnull`||i===`is_not_empty`||i===`isnotempty`)return{[t]:{$null:!1}};let a=h[i];return a?{[t]:{[a]:r}}:{[t]:{[`$${i}`]:r}}}function x(e){if(e==null)return;if(!Array.isArray(e))return e;if(e.length===0)return;let t=e[0];if(typeof t==`string`&&(t.toLowerCase()===`and`||t.toLowerCase()===`or`)){let n=`$${t.toLowerCase()}`,r=e.slice(1).map(e=>x(e)).filter(Boolean);return r.length===0?void 0:r.length===1?r[0]:{[n]:r}}if(e.length>=2&&typeof t==`string`)return b(e);if(e.every(e=>Array.isArray(e))){let t=e.map(e=>x(e)).filter(Boolean);return t.length===0?void 0:t.length===1?t[0]:{$and:t}}}var S=[`$eq`,`$ne`,`$gt`,`$gte`,`$lt`,`$lte`,`$in`,`$nin`,`$between`,`$contains`,`$notContains`,`$startsWith`,`$endsWith`,`$null`,`$exists`],C=[`$and`,`$or`,`$not`],ee=[...S,...C];function w(e){return t.z.never({error:()=>e}).optional().describe(`[REMOVED] ${e}`)}var T=n(()=>t.z.object({field:t.z.string(),order:t.z.enum([`asc`,`desc`]).default(`asc`)})),te=t.z.enum([`count`,`sum`,`avg`,`min`,`max`,`count_distinct`,`array_agg`,`string_agg`]),E=t.z.enum([`day`,`week`,`month`,`quarter`,`year`]),ne=n(()=>t.z.union([t.z.string(),t.z.object({field:t.z.string().describe(`Field to group by`),dateGranularity:E.optional().describe(`Bucket date values into uniform periods (day/week/month/quarter/year)`),alias:t.z.string().optional().describe(`Alias for the projected group value`)})])),re=n(()=>t.z.object({function:te.describe(`Aggregation function`),field:t.z.string().optional().describe(`Field to aggregate (optional for COUNT(*))`),alias:t.z.string().describe(`Result column alias`),distinct:t.z.boolean().optional().describe(`Apply DISTINCT before aggregation`),filter:f.optional().describe("[EXPERIMENTAL — not enforced] Per-aggregation filter (SQL FILTER (WHERE …)). Neither the SQL builders nor the in-memory fallback applies it (#4286); filter the whole query with `where` instead.")})),ie="A `fields[]` entry is a field name (string). The nested-select object form `{ field, fields, alias }` was removed in @objectstack/spec 17 (#4196, ADR-0049) — nothing ever produced it and nothing ever read `.fields`/`.alias`: every consumer on this path treats the list as `string[]`, so the object form was dropped by the SQL and memory drivers, projected as a column literally named \"[object Object]\" by MongoDB, and refused as an unknown field by the REST ingress. Select related records with `expand` — `expand: { owner: { object: 'user', fields: ['name'] } }` — or name a single related column with a dotted path (`fields: ['owner.name']`). `alias` has no replacement here; an aliased projection is an `aggregations` or `windowFunctions` entry, which carry their own `alias`.",D=t.z.string({error:e=>e.code===`invalid_type`&&typeof e.input==`object`&&e.input!==null&&!Array.isArray(e.input)?ie:void 0}),O="`query.joins` was removed in @objectstack/spec 17 (#4286, ADR-0049) — no engine or driver ever read it: a query carrying `joins` behaved exactly as if the key were absent, while its name squatted on the reserved REST parameter set. Delete the key. Related records are read through `expand` — `expand: { owner: { object: 'user', fields: ['name'] } }` — which the engine resolves via batch $in queries, and a single related column is a dotted `fields` path (`fields: ['owner.name']`).",k='`query.cursor` was removed in @objectstack/spec 17 (#4286, ADR-0049) — no driver ever implemented keyset pagination, so the cursor was accepted and ignored and every page came back identical (a caller looping "until hasMore is false" never terminates). Delete the key; `QueryBuilder.cursor()` was removed with it. Express the keyset as an ordinary `where` predicate on your sort key — `where: { created_at: { $gt: last.created_at } }` with the matching `orderBy` — which every driver executes with canonicalised comparands. A first-class cursor, if ever built, will be a response-minted opaque token, not this caller-built record.',A="`query.distinct` was removed in @objectstack/spec 17 (#4286, ADR-0049 / ADR-0078) — no driver ever rendered SELECT DISTINCT; the flag's only observable effect was MIS-WIRED: the REST list path treated a distinct query as not countable and silently degraded `total`/`hasMore` to a page-local estimate while still returning duplicate rows. Delete the key; `QueryBuilder.distinct()` was removed with it, and the count suppression is gone (`total` is truthful again). For unique values of one column use the SQL/memory drivers' `distinct(object, field)` door; for unique combinations, `groupBy`; for a deduplicated count, the `count_distinct` aggregation.",ae="`query.windowFunctions` was removed in @objectstack/spec 17 (#4286, ADR-0049) — `find()` never applied it: no engine or driver read the key on the query path, so every OVER clause it declared was silently dropped. Delete the key. Window functions are a SQL-driver capability behind `SqlDriver.findWithWindowFunctions(object, query)` (embedder-level; not on the `IDataDriver` contract or the REST surface); request-level analytics are `aggregations` + `groupBy`.",oe=n(()=>t.z.object({query:t.z.string().describe(`Search query text`),fields:t.z.array(t.z.string()).optional().describe(`Fields to search in (if not specified, searches all text fields)`),fuzzy:t.z.boolean().optional().default(!1).describe("[EXPERIMENTAL — not enforced] Fuzzy matching (tolerate typos). The ADR-0061 expansion reads only `query` + `fields`; no executor receives this flag (#4286)."),operator:t.z.enum([`and`,`or`]).optional().default(`or`).describe(`[EXPERIMENTAL — not enforced] Logical operator between terms. The ADR-0061 expansion applies its own term semantics; no executor receives this flag (#4286).`),boost:t.z.record(t.z.string(),t.z.number()).optional().describe(`[EXPERIMENTAL — not enforced] Field-specific relevance boosting (field name -> boost factor). No executor scores results (#4286).`),minScore:t.z.number().optional().describe(`[EXPERIMENTAL — not enforced] Minimum relevance score threshold. No executor scores results (#4286).`),language:t.z.string().optional().describe(`[EXPERIMENTAL — not enforced] Language for text analysis (e.g., "en", "zh", "es"). No executor selects an analyzer (#4286).`),highlight:t.z.boolean().optional().default(!1).describe(`[EXPERIMENTAL — not enforced] Search result highlighting. No executor emits highlights (#4286).`)})),se=t.z.object({object:t.z.string().describe(`Object name (e.g. account)`),fields:t.z.array(D).optional().describe("Fields to retrieve — field names, optionally dotted to reach through a relationship (`owner.name`). Related *records* are selected with `expand`, not from inside this list."),where:f.optional().describe(`Filtering criteria (WHERE)`),search:t.z.union([t.z.string(),oe]).optional().describe(`Full-text search — the query text (canonical, ADR-0061 D1), or a structured FullTextSearch configuration`),searchFields:t.z.array(t.z.string()).optional().describe(`Narrow the search to these fields (server-intersected with the allowed searchable set — can only narrow, never widen; ADR-0061 D1)`),orderBy:t.z.array(T).optional().describe(`Sorting instructions (ORDER BY)`),limit:t.z.number().optional().describe(`Max records to return (LIMIT)`),offset:t.z.number().optional().describe(`Records to skip (OFFSET)`),top:t.z.number().optional().describe(`Alias for limit (OData compatibility)`),cursor:w(k),joins:w(O),aggregations:t.z.array(re).optional().describe(`Aggregation functions`),groupBy:t.z.array(ne).optional().describe("GROUP BY targets (strings or `{field, dateGranularity?}` objects for date bucketing)"),having:f.optional().describe(`HAVING — filter over the AGGREGATED rows (aggregation aliases + groupBy projections); applied engine-side after aggregation`),windowFunctions:w(ae),distinct:w(A)}),j=n(()=>se.extend({expand:t.z.lazy(()=>t.z.record(t.z.string(),j)).optional().describe("Recursive relation loading map. Keys are lookup/master_detail field names; values are nested QueryAST objects that control select (`fields`) and filter (`where`, AND-merged with the batch $in), plus further expansion on the related object. The engine resolves expand via batch $in queries (driver-agnostic) with a default max depth of 3; per-parent `limit`/`offset`/`orderBy` are NOT applied on this path.")})),ce=[{id:`1`,a:`x`,b:`y`,c:`z`,owner:`u1`,status:`active`,parent_object:`case`,parent_id:`c1`},{id:`2`,a:`x`,b:`zz`,c:`z`,owner:`u1`,status:`archived`,parent_object:`case`,parent_id:`c2`},{id:`3`,a:`qq`,b:`y`,c:`z`,owner:`u2`,status:`active`,parent_object:`todo`,parent_id:`t1`},{id:`4`,a:`qq`,b:`zz`,c:`z`,owner:`u2`,status:`archived`,parent_object:`todo`,parent_id:`c1`}],le=[{name:`multi-key $or branch ANDs its own keys`,filter:{$or:[{a:`x`,b:`y`}]},expected:[`1`],note:"#3774: compiled to `a = x OR b = y`, matching 1,2,3."},{name:`each $or branch ANDs independently`,filter:{$or:[{a:`x`,b:`y`},{a:`qq`,b:`zz`}]},expected:[`1`,`4`]},{name:`top-level multi-key ANDs`,filter:{a:`x`,b:`y`},expected:[`1`]},{name:`a $or AND-s with a sibling top-level key`,filter:{$or:[{a:`x`},{b:`y`}],b:`zz`},expected:[`2`]},{name:`multiple operators on one field AND within a branch`,filter:{$or:[{a:{$ne:`qq`,$eq:`x`},b:`y`}]},expected:[`1`],note:`#3774: a single-key branch is miscompilable too — the operator map is looped with the same flag.`},{name:`an abutting $gte/$lt window ANDs its bounds`,filter:{$or:[{b:{$gte:`y`,$lt:`z`}}]},expected:[`1`,`3`],note:`The multi-tier scheduled-flow window pattern. OR-ing the bounds matches every row.`},{name:`$and branch OR-s against a sibling multi-key branch`,filter:{$or:[{$and:[{a:`x`},{b:`y`}]},{a:`qq`,b:`zz`}]},expected:[`1`,`4`]},{name:`multi-key branch OR-s against a sibling $and branch`,filter:{$or:[{a:`x`,b:`y`},{$and:[{a:`qq`},{b:`zz`}]}]},expected:[`1`,`4`]},{name:`$and ANDs with a key that FOLLOWS it in the same branch`,filter:{$or:[{c:`nope`},{$and:[{a:`qq`}],b:`y`}]},expected:[`3`],note:`Key order must not matter; this ordering and the next must agree.`},{name:`$and ANDs with a key that PRECEDES it in the same branch`,filter:{$or:[{c:`nope`},{b:`y`,$and:[{a:`qq`}]}]},expected:[`3`]},{name:`keys AND inside a $or nested in a $or branch`,filter:{$or:[{$or:[{a:`x`,b:`zz`}]}]},expected:[`2`]},{name:`a $or nested under a top-level $and`,filter:{$and:[{$or:[{a:`x`},{b:`y`}]},{b:`y`}]},expected:[`1`,`3`]},{name:`$not ANDs with its sibling keys inside a branch`,filter:{$or:[{c:`nope`},{$not:{a:`x`},b:`zz`}]},expected:[`4`]},{name:`single-key $or branches stay a plain OR`,filter:{$or:[{a:`x`},{b:`y`}]},expected:[`1`,`2`,`3`],note:`The control: the shape that was always correct must stay correct.`},{name:`read scope: own AND active, OR another owner's row`,filter:{$or:[{owner:`u1`,status:`active`},{owner:`u2`,status:`active`}]},expected:[`1`,`3`],note:`Widening here returns rows the scope excludes — an unauthorized read, not a wrong count.`},{name:`read scope: owner $in AND status`,filter:{$or:[{owner:{$in:[`u1`]},status:`active`},{owner:`u2`,status:`archived`}]},expected:[`1`,`4`]},{name:`read scope: parent type paired with its own id list`,filter:{$or:[{parent_object:`case`,parent_id:{$in:[`c1`]}},{parent_object:`todo`,parent_id:{$in:[`t1`]}}]},expected:[`1`,`3`],note:`Row 4 is parent_object=todo with parent_id=c1 — it matches neither pairing, and is the row a widened compile leaks.`}],ue=`2026-07-28T12:00:00.000Z`,de=[{id:`a_epoch`,at:`1969-12-31T23:00:00.000Z`,on:`1969-12-31`,writerForm:`wire`,why:`pre-epoch instant (negative epoch ms) — any surface assuming a non-negative epoch, or reading one as a Julian day (#3773), breaks here first`},{id:`a_old`,at:`2026-04-19T10:00:00.000Z`,on:`2026-04-19`,writerForm:`wire`,why:`well before any window here`},{id:`b_prev`,at:`2026-07-27T14:00:00.000Z`,on:`2026-07-27`,writerForm:`native`,why:`the day before the boundary day`},{id:`c_open`,at:`2026-07-28T00:00:00.000Z`,on:`2026-07-28`,writerForm:`native`,why:`boundary day at exactly 00:00 — the only instant a midnight-anchored bound keeps`},{id:`d_mid`,at:`2026-07-28T09:15:00.000Z`,on:`2026-07-28`,writerForm:`wire`,why:`boundary day, morning — dropped by the #3777 bug`},{id:`e_late`,at:`2026-07-28T21:40:00.000Z`,on:`2026-07-28`,writerForm:`wire`,why:`boundary day, evening — dropped by the #3777 bug`},{id:`f_next`,at:`2026-07-29T00:00:00.000Z`,on:`2026-07-29`,writerForm:`native`,why:`next midnight — the exclusive edge a half-open bound must NOT keep`},{id:`g_eom`,at:`2026-07-31T23:59:59.999Z`,on:`2026-07-31`,writerForm:`wire`,why:`last representable instant of a month — month rollover`},{id:`h_leap`,at:`2024-02-29T12:00:00.000Z`,on:`2024-02-29`,writerForm:`native`,why:`leap day — February rollover`}],M=[{name:`datetime: bare-day $lte keeps the whole final day`,field:`at`,kind:`datetime`,filter:{at:{$gte:`2026-04-29`,$lte:`2026-07-28`}},tokenFilter:{at:{$gte:`{90_days_ago}`,$lte:`{today}`}},dateRange:[`{90_days_ago}`,`{today}`],expected:[`b_prev`,`c_open`,`d_mid`,`e_late`],note:`#3777: the default dashboard window. Pre-fix returned only b_prev + c_open — everything after 00:00 on the final day vanished.`},{name:`date: the same window is unchanged (already whole-day)`,field:`on`,kind:`date`,filter:{on:{$gte:`2026-04-29`,$lte:`2026-07-28`}},tokenFilter:{on:{$gte:`{90_days_ago}`,$lte:`{today}`}},dateRange:[`{90_days_ago}`,`{today}`],expected:[`b_prev`,`c_open`,`d_mid`,`e_late`],note:"A `date` column compares as calendar-day text, so `<= day` was always right there. The two rows must agree — that is the invariant."},{name:`datetime: a bare-day $lte alone stops at the next midnight`,field:`at`,kind:`datetime`,filter:{at:{$lte:`2026-07-28`}},tokenFilter:{at:{$lte:`{today}`}},expected:[`a_epoch`,`a_old`,`b_prev`,`c_open`,`d_mid`,`e_late`,`h_leap`],note:`f_next sits exactly on the exclusive edge and must stay out — a half-open bound, never an inclusive 23:59:59.999.`},{name:`datetime: $between inherits the rule on its max`,field:`at`,kind:`datetime`,filter:{at:{$between:[`2026-04-29`,`2026-07-28`]}},tokenFilter:{at:{$between:[`{90_days_ago}`,`{today}`]}},expected:[`b_prev`,`c_open`,`d_mid`,`e_late`],note:`knex whereBetween is inclusive on both ends, so it had the same midnight-anchored upper bound $lte had.`},{name:`datetime: $between still bounds its min`,field:`at`,kind:`datetime`,filter:{at:{$between:[`2026-07-28`,`2026-07-28`]}},tokenFilter:{at:{$between:[`{today}`,`{today}`]}},dateRange:[`{today}`,`{today}`],expected:[`c_open`,`d_mid`,`e_late`],note:`The "today" preset degenerates to a single day: the min stays midnight-anchored while the max spans the day.`},{name:`datetime: bare-day $gte is that midnight`,field:`at`,kind:`datetime`,filter:{at:{$gte:`2026-07-28`}},tokenFilter:{at:{$gte:`{today}`}},expected:[`c_open`,`d_mid`,`e_late`,`f_next`,`g_eom`],note:`A LOWER bound anchors to 00:00 — c_open is included precisely because the bound is inclusive of that instant.`},{name:`datetime: bare-day $lt is that midnight`,field:`at`,kind:`datetime`,filter:{at:{$lt:`2026-07-28`}},tokenFilter:{at:{$lt:`{today}`}},expected:[`a_epoch`,`a_old`,`b_prev`,`h_leap`],note:`Strict-less keeps its anchoring: c_open is AT midnight, so it is excluded.`},{name:`date: bare-day $gt excludes the bound day`,field:`on`,kind:`date`,filter:{on:{$gt:`2026-07-28`}},tokenFilter:{on:{$gt:`{today}`}},expected:[`f_next`,`g_eom`],note:`The boundary day itself is out; the mirror-image of widening a lower bound.`},{name:`datetime: a full-ISO $lte keeps exact-instant semantics`,field:`at`,kind:`datetime`,filter:{at:{$lte:`2026-07-28T12:00:00.000Z`}},expected:[`a_epoch`,`a_old`,`b_prev`,`c_open`,`d_mid`,`h_leap`],note:`Only the day-granular STRING carries whole-day intent. e_late (21:40) is after noon and must stay out.`},{name:`datetime: a full-ISO $gte is exact too`,field:`at`,kind:`datetime`,filter:{at:{$gte:`2026-07-28T09:15:00.000Z`}},expected:[`d_mid`,`e_late`,`f_next`,`g_eom`],note:`d_mid is exactly the bound and inclusive.`},{name:`datetime: month-end $lte spans to the next month`,field:`at`,kind:`datetime`,filter:{at:{$gte:`2026-07-29`,$lte:`2026-07-31`}},tokenFilter:{at:{$gte:`{tomorrow}`,$lte:`{current_month_end}`}},dateRange:[`{tomorrow}`,`{current_month_end}`],expected:[`f_next`,`g_eom`],note:`g_eom is 23:59:59.999 on the 31st — kept only if the bound rolled to 2026-08-01.`},{name:`datetime: leap-day $lte includes Feb 29`,field:`at`,kind:`datetime`,filter:{at:{$gte:`2024-02-01`,$lte:`2024-02-29`}},expected:[`h_leap`],note:`The next day is 2024-03-01; a naive month-increment would produce 2024-02-30.`},{name:`datetime: the day BEFORE the leap day excludes it`,field:`at`,kind:`datetime`,filter:{at:{$gte:`2024-02-01`,$lte:`2024-02-28`}},expected:[],note:`Guards the opposite error: rolling 02-28 to 03-01 (skipping the 29th) would wrongly include h_leap.`},{name:`datetime: a pre-epoch day is an ordinary calendar day`,field:`at`,kind:`datetime`,filter:{at:{$gte:`1969-12-31`,$lte:`1969-12-31`}},expected:[`a_epoch`],note:`Negative epoch ms. The #3773 family: any surface that assumes a datetime is a non-negative epoch, or reads one as a Julian day, breaks here first.`},{name:`date: equality against a resolved day matches the whole day`,field:`on`,kind:`date`,filter:{on:`2026-07-28`},tokenFilter:{on:`{today}`},expected:[`c_open`,`d_mid`,`e_late`],note:"#1874: `date == today` silently matched nothing while dates were stored as instants. Equality on a date column is plain calendar-day text equality — Phase 1's whole point."},{name:`date: $in of two resolved days`,field:`on`,kind:`date`,filter:{on:{$in:[`2026-07-28`,`2026-07-27`]}},tokenFilter:{on:{$in:[`{today}`,`{yesterday}`]}},expected:[`b_prev`,`c_open`,`d_mid`,`e_late`],note:"The `expires_on: { $in: [daysFromNow(30)] }` template shape from the #1874 family — element-wise, order-independent."}],fe=[{id:`a_midnight`,at:`00:00:00`,writerForm:`native`,why:`the day's lower extreme, written as a Date — epoch 0 on SQLite, which sorts before every TEXT row`},{id:`b_early`,at:`08:00:00`,writerForm:`wire`,why:`before opening — the row a business-hours lower bound must exclude`},{id:`c_open`,at:`09:00:00`,writerForm:`native`,why:`exactly the opening bound, which is inclusive`},{id:`d_mid`,at:`14:30:00`,writerForm:`wire`,why:"mid-afternoon, zero milliseconds — the `HH:MM:SS` spelling every dialect's native TIME emits"},{id:`e_mid_ms`,at:`14:30:00.500`,writerForm:`native`,why:`the same wall clock plus 500ms: the width change lexicographic order has to survive, and what MySQL bare TIME rounded away`},{id:`f_close`,at:`18:00:00`,writerForm:`wire`,why:`exactly the closing bound, which is inclusive`},{id:`g_last`,at:`23:59:59.999`,writerForm:`native`,why:`the day's upper extreme — the last representable wall clock`}],N=[{name:`time: a business-hours window keeps both bounds`,filter:{at:{$gte:`09:00:00`,$lte:`18:00:00`}},expected:[`c_open`,`d_mid`,`e_mid_ms`,`f_close`],note:"#3994, measured: 4 of 7 rows silently dropped. An epoch-ms row failed `>= 09:00:00` outright (INTEGER < TEXT on SQLite) and a full-timestamp row failed `<= 18:00:00` lexicographically."},{name:`time: an inclusive upper bound is EXACT, not widened`,filter:{at:{$lte:`14:30:00`}},expected:[`a_midnight`,`b_early`,`c_open`,`d_mid`],note:"The bare-day whole-day rule (D-D) must not reach a time column: `nextUtcCalendarDay` widens only a `YYYY-MM-DD` string. If it leaked, e_mid_ms (14:30:00.500) would appear."},{name:`time: the millisecond suffix sorts after its zero-ms twin`,filter:{at:{$gt:`14:30:00`}},expected:[`e_mid_ms`,`f_close`,`g_last`],note:"The variable-width canon (D-C1) only works because `.` sorts below every digit; d_mid is excluded by strict-greater and e_mid_ms is kept."},{name:`time: a sub-second window bounds the millisecond row`,filter:{at:{$gte:`14:30:00.100`,$lt:`14:30:01`}},expected:[`e_mid_ms`],note:"Guards the same ordering from the other side — `14:30:00.500` must fall inside a window whose bounds differ only after the decimal point."},{name:`time: equality on a canonical wall clock`,filter:{at:`14:30:00`},expected:[`d_mid`],note:`Determinism is what equality and distinct() rest on: one wall clock has exactly one canonical spelling, so e_mid_ms is a DIFFERENT value, not a near-match.`},{name:`time: $in of two canonical wall clocks`,filter:{at:{$in:[`09:00:00`,`18:00:00`]}},expected:[`c_open`,`f_close`]},{name:`time: $between spans the working day inclusively`,filter:{at:{$between:[`08:00:00`,`18:00:00`]}},expected:[`b_early`,`c_open`,`d_mid`,`e_mid_ms`,`f_close`],note:`Both ends inclusive, and — like the $lte case — NOT widened by the calendar-day rule.`},{name:`time: midnight is an ordinary wall clock, not a null`,filter:{at:{$lt:`09:00:00`}},expected:[`a_midnight`,`b_early`],note:"A `00:00:00` write that became INTEGER 0 (a bound `Date` at UTC midnight) sorted before every TEXT row on SQLite and was reachable by no text bound at all."},{name:`time: the last wall clock of the day is reachable`,filter:{at:{$gte:`23:59:59`}},expected:[`g_last`],note:`The upper extreme, where an implementation that truncates or rounds the millisecond suffix (MySQL bare TIME did) loses the row.`}],pe=[{id:`r07`,status:`open`,rank:2,name:`Alpha`},{id:`r03`,status:`done`,rank:1,name:`Bravo`},{id:`r11`,status:`open`,rank:3,name:`Charlie`},{id:`r01`,status:`hold`,rank:2,name:`Delta`},{id:`r09`,status:`done`,rank:3,name:`Echo`},{id:`r05`,status:`open`,rank:1,name:`Foxtrot`},{id:`r12`,status:`hold`,rank:1,name:`Golf`},{id:`r02`,status:`done`,rank:2,name:`Hotel`},{id:`r08`,status:`hold`,rank:3,name:`India`},{id:`r04`,status:`open`,rank:2,name:`Juliett`},{id:`r10`,status:`done`,rank:1,name:`Kilo`},{id:`r06`,status:`hold`,rank:3,name:`Lima`}],me=[{name:`single ascending key with 4-row ties`,orderBy:[{field:`status`,order:`asc`}],pageSize:5},{name:`single descending key with 4-row ties`,orderBy:[{field:`status`,order:`desc`}],pageSize:5},{name:`numeric key with 4-row ties`,orderBy:[{field:`rank`,order:`asc`}],pageSize:4},{name:`page size 1 walks every boundary`,orderBy:[{field:`status`,order:`asc`}],pageSize:1},{name:`multi-key sort with residual ties`,orderBy:[{field:`status`,order:`asc`},{field:`rank`,order:`desc`}],pageSize:5}],he=[{name:`page size 5 over 12 rows`,pageSize:5},{name:`page size 7 leaves a short last page`,pageSize:7},{name:`page size 1 walks every boundary`,pageSize:1}],ge=pe.map(e=>e.id),_e=[`today`,`yesterday`,`tomorrow`,`now`],ve=[`current_week_start`,`current_week_end`,`current_month_start`,`current_month_end`,`current_quarter_start`,`current_quarter_end`,`current_year_start`,`current_year_end`,`last_week_start`,`last_week_end`,`last_month_start`,`last_month_end`,`last_quarter_start`,`last_quarter_end`,`last_year_start`,`last_year_end`,`next_week_start`,`next_week_end`,`next_month_start`,`next_month_end`,`next_quarter_start`,`next_quarter_end`,`next_year_start`,`next_year_end`],ye=[`week_start`,`week_end`,`month_start`,`month_end`,`quarter_start`,`quarter_end`,`year_start`,`year_end`],be=[..._e,...ve,...ye],xe=/^(\d+)_(minutes?|hours?|days?|weeks?|months?|years?)_(ago|from_now)$/,Se=[`minute`,`hour`,`day`,`week`,`month`,`year`];function P(e){return be.includes(e)||xe.test(e)}function Ce(e){let t=e.match(xe);if(!t)return null;let n=t[2].replace(/s$/,``);return{n:parseInt(t[1],10),unit:n,direction:t[3]}}var we=t.z.string().refine(P,{message:`Unknown date macro. Must be a fixed token (see DATE_MACRO_TOKENS) or match {N_<unit>_(ago|from_now)} where unit is one of: `+Se.join(`, `)}),Te=/^\$?\{([a-zA-Z0-9_]+)\}$/,Ee=t.z.string().refine(e=>{let t=e.match(Te);return!!t&&P(t[1])},{message:`Not a recognised {date-macro} placeholder`}),De={today:`Start of today (YYYY-MM-DD).`,yesterday:`Start of yesterday.`,tomorrow:`Start of tomorrow.`,now:`Current timestamp (full ISO).`,current_week_start:`Monday 00:00 of this week.`,current_week_end:`Sunday of this week.`,current_month_start:`1st of this month.`,current_month_end:`Last day of this month.`,current_quarter_start:`1st day of this quarter.`,current_quarter_end:`Last day of this quarter.`,current_year_start:`Jan 1 of this year.`,current_year_end:`Dec 31 of this year.`,last_week_start:`Monday of last week.`,last_week_end:`Sunday of last week.`,last_month_start:`1st of last month.`,last_month_end:`Last day of last month.`,last_quarter_start:`1st day of last quarter.`,last_quarter_end:`Last day of last quarter.`,last_year_start:`Jan 1 of last year.`,last_year_end:`Dec 31 of last year.`,next_week_start:`Monday of next week.`,next_week_end:`Sunday of next week.`,next_month_start:`1st of next month.`,next_month_end:`Last day of next month.`,next_quarter_start:`1st day of next quarter.`,next_quarter_end:`Last day of next quarter.`,next_year_start:`Jan 1 of next year.`,next_year_end:`Dec 31 of next year.`,week_start:`Alias for current_week_start.`,week_end:`Alias for current_week_end.`,month_start:`Alias for current_month_start.`,month_end:`Alias for current_month_end.`,quarter_start:`Alias for current_quarter_start.`,quarter_end:`Alias for current_quarter_end.`,year_start:`Alias for current_year_start.`,year_end:`Alias for current_year_end.`};function Oe(e){if(typeof e!=`string`)return null;let t=e.trim(),n=/^(\d{4})-(\d{2})-(\d{2})$/.exec(t);if(!n)return null;let[r,i,a]=[Number(n[1]),Number(n[2]),Number(n[3])];return Ae(new Date(Date.UTC(r,i-1,a)))===t?Ae(new Date(Date.UTC(r,i-1,a+1))):null}function ke(e){if(e instanceof Date){let t=e.getTime();return Number.isNaN(t)?null:t}if(typeof e==`number`)return Number.isFinite(e)?e:null;if(typeof e!=`string`)return null;let t=e.trim();if(/^\d{4}-\d{2}-\d{2}$/.test(t))return Oe(t)===null?null:Date.parse(`${t}T00:00:00.000Z`);let n=/^(\d{4}-\d{2}-\d{2})[ T](\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?)(Z|[+-]\d{2}:?\d{2})?$/.exec(t);if(!n)return null;let r=Date.parse(`${n[1]}T${n[2]}${n[3]??`Z`}`);return Number.isNaN(r)?null:r}function Ae(e){return`${String(e.getUTCFullYear()).padStart(4,`0`)}-${String(e.getUTCMonth()+1).padStart(2,`0`)}-${String(e.getUTCDate()).padStart(2,`0`)}`}var je=[`current_user_id`,`current_org_id`];function F(e){return je.includes(e)}var Me=Te,Ne=t.z.string().refine(F,{message:`Unknown context token. Must be one of: ${je.join(`, `)}`}),Pe=t.z.string().refine(e=>{let t=e.match(Me);return!!t&&F(t[1])},{message:`Not a recognised {context-token} placeholder`}),Fe={current_user_id:"The signed-in user's id (`sys_user.id`).",current_org_id:`The active organization id.`},Ie={current_user:`current_user_id`,current_user_email:`current_user_id`,user_id:`current_user_id`,userid:`current_user_id`,me:`current_user_id`,current_organization_id:`current_org_id`,org_id:`current_org_id`,organization_id:`current_org_id`,current_tenant_id:`current_org_id`};function Le(e){return F(e)||P(e)}function Re(e){if(typeof e!=`string`)return null;let t=e.match(Me);if(!t)return null;let n=t[1];return F(n)?{kind:`context`,token:n}:P(n)?{kind:`date-macro`,token:n}:{kind:`unknown`,token:n,suggestion:Ie[n.toLowerCase()]}}var ze=n(()=>t.z.string().min(2,{message:`System identifier must be at least 2 characters`}).regex(/^[a-z][a-z0-9_.]*$/,{message:`System identifier must be lowercase, starting with a letter, and may contain letters, numbers, underscores, or dots (e.g., "user_profile" or "order.created")`}).describe(`System identifier (lowercase with underscores or dots)`)),I=n(()=>t.z.string().min(2,{message:`Identifier must be at least 2 characters`}).regex(/^[a-z][a-z0-9_]*$/,{message:`Identifier must be lowercase snake_case, starting with a letter, and may contain only letters, numbers, and underscores (e.g., "user_profile")`}).describe(`Snake case identifier (lowercase with underscores only)`));n(()=>t.z.string().min(3,{message:`Event name must be at least 3 characters`}).regex(/^[a-z][a-z0-9_.]*$/,{message:`Event name must be lowercase with dots for namespacing (e.g., "user.created", "order.paid")`}).describe(`Event name (lowercase with dot notation for namespacing)`));var Be=t.z.enum([`cel`,`cron`,`template`]),Ve=t.z.object({rationale:t.z.string().optional(),generatedBy:t.z.string().optional()}),He=t.z.object({dialect:Be,source:t.z.string().min(1).optional(),ast:t.z.unknown().optional(),meta:Ve.optional()}).refine(e=>e.source!==void 0||e.ast!==void 0,{message:"Expression requires at least one of `source` or `ast`"}),L=t.z.union([t.z.string().min(1).transform(e=>({dialect:`cel`,source:e})),He]);t.z.union([t.z.string().min(1).transform(e=>({dialect:`cron`,source:e})),He]);var Ue=t.z.union([t.z.string().min(1).transform(e=>({dialect:`template`,source:e})),He]),We=t.z.enum(`text.textarea.email.url.phone.password.secret.markdown.html.richtext.number.currency.percent.date.datetime.time.boolean.toggle.select.multiselect.radio.checkboxes.lookup.master_detail.tree.user.image.file.avatar.video.audio.formula.summary.autonumber.composite.repeater.record.location.address.code.json.color.rating.slider.signature.qrcode.progress.tags.vector`.split(`.`)),Ge=n(()=>t.z.object({label:t.z.string().describe(`Display label (human-readable, any case allowed)`),value:ze.describe(`Stored value (lowercase machine identifier)`),color:t.z.string().optional().describe(`Color code for badges/charts`),default:t.z.boolean().optional().describe(`Is default option`),visibleWhen:L.optional().describe("Per-option visibility predicate (CEL) — option is offered only when TRUE (else omitted). Same env as field visibleWhen (record + current_user). e.g. P`record.country == 'cn'` or P`'admin' in current_user.positions`")})),Ke=n(()=>t.z.object({latitude:t.z.number().min(-90).max(90).describe(`Latitude coordinate`),longitude:t.z.number().min(-180).max(180).describe(`Longitude coordinate`),altitude:t.z.number().optional().describe(`Altitude in meters`),accuracy:t.z.number().optional().describe(`Accuracy in meters`)})),qe=n(()=>t.z.object({precision:t.z.number().int().min(0).max(10).default(2).describe(`Decimal precision (default: 2)`),currencyMode:t.z.enum([`dynamic`,`fixed`]).default(`dynamic`).describe(`Currency mode: dynamic (user selectable) or fixed (single currency)`),defaultCurrency:t.z.string().length(3).default(`CNY`).describe(`Default or fixed currency code (ISO 4217, e.g., USD, CNY, EUR)`)})),Je=n(()=>t.z.object({value:t.z.number().describe(`Monetary amount`),currency:t.z.string().length(3).describe(`Currency code (ISO 4217)`)})),Ye=n(()=>t.z.object({street:t.z.string().optional().describe(`Street address`),city:t.z.string().optional().describe(`City name`),state:t.z.string().optional().describe(`State/Province`),postalCode:t.z.string().optional().describe(`Postal/ZIP code`),country:t.z.string().optional().describe(`Country name or code`),countryCode:t.z.string().optional().describe(`ISO country code (e.g., US, GB)`),formatted:t.z.string().optional().describe(`Formatted address string`)})),Xe=n(()=>t.z.union([t.z.boolean(),t.z.literal(`global`)]));function Ze(e){return e===`global`}function Qe(e){return e===!0||e===`global`}var $e=n(()=>t.z.object({name:t.z.string().regex(/^[a-z_][a-z0-9_]*$/).describe(`Machine name (snake_case)`).optional(),label:t.z.string().optional().describe(`Human readable label`),type:We.describe(`Field Data Type`),description:t.z.string().optional().describe(`Tooltip/Help text`),format:t.z.string().optional().describe(`Format string (e.g. email, phone)`),required:t.z.boolean().default(!1).describe("Write-time contract (ADR-0113): an insert must provide a non-null value, and an update may not null it out. NOT a column constraint — the physical NOT NULL is a separate explicit opt-in (`storage.notNull`), so tightening this on a deployed object is safe: existing null rows stay readable, and editable as long as the write does not touch this field."),storage:t.z.object({notNull:t.z.boolean().optional().describe("Emit a physical NOT NULL on the column (ADR-0113). Absent = the column stays nullable even under `required: true` — the write contract is enforced at the engine, the only sanctioned write path, not by the database. Declaring this over existing null rows is a destructive migration gated by the schema-drift ceremony. Incompatible with `requiredWhen` (a conditional contract cannot be an unconditional column constraint).")}).strict().optional().describe(`Physical storage constraints (ADR-0113). Owns the DDL the write contract deliberately does not imply. Absent = no storage-level constraint requested.`),searchable:t.z.boolean().default(!1).describe(`Is searchable`),multiple:t.z.boolean().default(!1).describe(`Allow multiple values (Stores as Array/JSON). Applicable for select, lookup, file, image.`),unique:Xe.default(!1).describe(`Unique constraint. true = unique within the tenant (composite with the tenant column on tenant-scoped objects); 'global' = unique platform-wide across all tenants`),defaultValue:t.z.unknown().optional().describe(`Default value`),maxLength:t.z.number().optional().describe(`Max character length`),minLength:t.z.number().optional().describe(`Min character length`),precision:t.z.number().optional().describe(`Total digits`),scale:t.z.number().optional().describe(`Decimal places`),min:t.z.number().optional().describe(`Minimum value`),max:t.z.number().optional().describe(`Maximum value`),accept:t.z.array(t.z.string()).optional().describe(`Permitted upload types for media fields, as MIME types or extensions (e.g. ["image/*", ".pdf"]). Offered to the file picker AND enforced on write.`),maxSize:t.z.number().int().positive().optional().describe(`Maximum permitted file size in BYTES for media fields. Enforced on write against the stored file size, not just checked in the browser.`),options:t.z.array(Ge).optional().describe(`Static options for select/multiselect`),reference:t.z.string().optional().describe(`Target object name (snake_case) for lookup/master_detail fields. Required for relationship types. Used by $expand to resolve foreign key IDs into full objects.`),deleteBehavior:t.z.enum([`set_null`,`cascade`,`restrict`]).optional().default(`set_null`).describe(`What happens if referenced record is deleted`),inlineEdit:t.z.union([t.z.boolean(),t.z.enum([`grid`,`form`])]).optional().describe(`Edit these child records inline within the parent's form (atomic master-detail). true = auto-pick grid/form by child shape; 'grid' = editable line-item grid; 'form' = list + per-row full form.`),inlineTitle:t.z.string().optional().describe(`Title for the inline master-detail grid`),inlineColumns:t.z.array(t.z.any()).optional().describe(`Explicit columns for the inline grid (derived from the child object when omitted)`),inlineAmountField:t.z.string().optional().describe(`Numeric child field summed for the inline grid total`),relatedList:t.z.union([t.z.boolean(),t.z.literal(`primary`)]).optional().describe(`Show this child collection as a related list on the parent's detail page (read-side mirror of inlineEdit). false = suppress; true/absent = shown (stacked under the shared "Related" tab); 'primary' = core relationship, promoted to its own tab. Prominence intent, not a layout switch (ADR-0085).`),relatedListTitle:t.z.string().optional().describe(`Title for the detail-page related list`),relatedListColumns:t.z.array(t.z.any()).optional().describe(`Explicit columns for the detail-page related list (derived from the child object when omitted)`),displayField:t.z.string().optional().describe(`Field shown as each candidate's label in the picker/popover (defaults to the referenced object's name/title).`),descriptionField:t.z.string().optional().describe(`Secondary field shown under the label in the quick-select popover.`),lookupColumns:t.z.array(t.z.union([t.z.string(),t.z.object({field:t.z.string(),label:t.z.string().optional(),width:t.z.string().optional(),type:t.z.string().optional()})])).optional().describe(`Explicit columns for the record-picker table; auto-derived from the referenced object when omitted.`),lookupPageSize:t.z.number().int().positive().optional().describe(`Rows per page in the record-picker dialog (default 10).`),lookupFilters:t.z.array(t.z.object({field:t.z.string(),operator:t.z.enum([`eq`,`ne`,`gt`,`lt`,`gte`,`lte`,`contains`,`in`,`notIn`]),value:t.z.any()})).optional().describe(`Base filters restricting which records are selectable (e.g. only active). The structured, picker-honoured lookup filter.`),dependsOn:t.z.array(t.z.union([t.z.string(),t.z.object({field:t.z.string(),param:t.z.string().optional()})])).optional().describe("Declares that this field's available values depend on the value of other field(s) on the same record — the form gates the field until they are set and re-evaluates as they change. For `lookup`/`master_detail` it scopes the candidate query (string = same local/remote key; {field,param} when the remote filter key differs — the {field,param} form is lookup-only). For `select`/`multiselect`/`radio` the actual per-option rule lives in each option's `visibleWhen`; list the referenced fields here (string form) so the option list gates and refreshes with the parent."),allowCreate:t.z.boolean().optional().describe(`Allow inline quick-create from the record picker: when no match exists the user can create a record from the typed text (optimistic dataSource.create with the display field). Best for simple objects whose only required field is the display field.`),expression:L.optional().describe("Formula expression (CEL). e.g. F`record.amount * 0.1`"),returnType:t.z.enum([`number`,`text`,`boolean`,`date`]).optional().describe(`Inferred value type of a formula field (number/text/boolean/date)`),summaryOperations:t.z.object({object:t.z.string().describe(`Source child object name for roll-up`),field:t.z.string().describe(`Field on child object to aggregate (ignored for count)`),function:t.z.enum([`count`,`sum`,`min`,`max`,`avg`]).describe(`Aggregation function to apply`),relationshipField:t.z.string().optional().describe(`FK field on the child pointing back to this parent. Auto-detected from the child's lookup/master_detail field referencing this object when omitted; set explicitly only when the child has more than one such reference.`),filter:f.optional().describe("Predicate restricting which child rows are aggregated (a query `where` FilterCondition, e.g. { status: 'received' } or { type: { $in: ['signup','trial'] } }). Omit to aggregate all children. Lets one child object feed multiple filtered roll-ups.")}).optional().describe(`Roll-up summary definition. The engine recomputes the value when child records are inserted/updated/deleted.`),language:t.z.string().optional().describe(`Programming language for syntax highlighting (e.g., javascript, python, sql)`),step:t.z.number().optional().describe(`Step increment for slider (default: 1)`),currencyConfig:qe.optional().describe(`Configuration for currency field type`),dimensions:t.z.number().int().min(1).max(1e4).optional().describe(`Vector dimensionality (e.g., 1536 for OpenAI embeddings)`),trackHistory:t.z.boolean().optional().describe(`Render this field's value changes as human-readable entries on the record activity timeline (ADR-0052 §5b). Opt-in per field.`),group:t.z.string().optional().describe(`Field group name for organizing fields in forms and layouts (e.g., "contact_info", "billing", "system")`),visibleWhen:L.optional().describe("Predicate (CEL) — field is shown only when TRUE (else hidden). e.g. P`record.type == 'invoice'`"),readonlyWhen:L.optional().describe("Predicate (CEL) — field is read-only when TRUE. e.g. P`record.status == 'paid'`"),requiredWhen:L.optional().describe("Predicate (CEL) — field is required when TRUE. The only slot; the `conditionalRequired` alias was removed in protocol 17 (#3855)."),conditionalRequired:w("`conditionalRequired` was removed in @objectstack/spec 17 (#3855) — use `requiredWhen`. Rename the key; the value (a CEL predicate) is unchanged. Run `os migrate meta --from 16` to rewrite it automatically."),widget:t.z.string().optional().describe('Form widget override — names a registered field component (resolved as `field:<widget>`) to render this field instead of the `type` default. Degrades to the `type` renderer when unregistered. e.g. "object-ref", "filter-condition", "recipient-picker".'),hidden:t.z.boolean().default(!1).describe(`Hidden from default UI`),readonly:t.z.boolean().default(!1).describe('Read-only — never editable in forms, AND server-enforced on BOTH write paths: a non-system write to this field is silently dropped from the payload on UPDATE (#2948/#3003) and on INSERT (#3043; a create can no longer directly seed e.g. `approval_status: "approved"`), symmetric with `readonlyWhen`. A stripped INSERT field still falls back to its `defaultValue`. Exempt from the strip: `isSystem` writes (seed replay, migration), and an opt-in "historical" import (`preserveAudit`, #3493) — which admits a whitelist (the audit/timestamp family plus author-declared business `readonly` fields). A normal (non-system) import is NOT system-context and still strips.'),requiredPermissions:t.z.array(t.z.string()).optional().describe(`[ADR-0066 D3] Capabilities required to read/edit this field (mask on read, deny on write; AND-gate).`),ackPlaintextMasking:t.z.boolean().optional().describe("[ADR-0100] Affirm a generic `password` field's plaintext-at-rest / masked-on-read contract is intended, silencing the author-time warning (#3420). No effect on non-password fields."),system:t.z.boolean().optional().describe(`Auto-injected system/audit field (e.g. created_at, updated_by, organization_id). Tools that surface system fields separately from author-declared business fields should branch on this flag.`),sortable:t.z.boolean().optional().default(!0).describe(`Whether field is sortable in list views`),inlineHelpText:t.z.string().optional().describe(`Help text displayed below the field in forms`),autonumberFormat:t.z.string().optional().describe(`Auto-number format: literal text + {0000} counter, {YYYY}/{MM}/{DD}/{YYYYMMDD} date tokens (business tz), and {field_name} interpolation. Counter resets per rendered prefix (e.g. AD{YYYYMMDD}{0000} resets daily).`),externalId:t.z.boolean().default(!1).describe(`Is external ID for upsert operations`)}).superRefine((e,t)=>{e.storage?.notNull===!0&&e.requiredWhen!==void 0&&t.addIssue({code:`custom`,path:[`storage`,`notNull`],message:"`storage.notNull` cannot be combined with `requiredWhen` (ADR-0113): when the condition is false the write contract permits null, but the column would refuse it. Use `required: true` + `storage.notNull` for an unconditional constraint, or `requiredWhen` alone for a conditional write contract (the column stays nullable)."})})),et={text:(e={})=>({type:`text`,...e}),textarea:(e={})=>({type:`textarea`,...e}),number:(e={})=>({type:`number`,...e}),boolean:(e={})=>({type:`boolean`,...e}),date:(e={})=>({type:`date`,...e}),datetime:(e={})=>({type:`datetime`,...e}),currency:(e={})=>({type:`currency`,...e}),percent:(e={})=>({type:`percent`,...e}),url:(e={})=>({type:`url`,...e}),email:(e={})=>({type:`email`,...e}),phone:(e={})=>({type:`phone`,...e}),image:(e={})=>({type:`image`,...e}),file:(e={})=>({type:`file`,...e}),avatar:(e={})=>({type:`avatar`,...e}),formula:(e={})=>({type:`formula`,...e}),summary:(e={})=>({type:`summary`,...e}),autonumber:(e={})=>({type:`autonumber`,...e}),markdown:(e={})=>({type:`markdown`,...e}),html:(e={})=>({type:`html`,...e}),password:(e={})=>({type:`password`,...e}),secret:(e={})=>({type:`secret`,...e}),select:(e,t)=>{let n=e=>e.toLowerCase().replace(/\s+/g,`_`).replace(/[^a-z0-9_]/g,``),r,i;if(Array.isArray(e))r=e.map(e=>typeof e==`string`?{label:e,value:n(e)}:{...e,value:e.value.toLowerCase()}),i=t||{};else{r=(e.options||[]).map(e=>typeof e==`string`?{label:e,value:n(e)}:{...e,value:e.value.toLowerCase()});let{options:t,...a}=e;i=a}return{type:`select`,options:r,...i}},lookup:(e,t={})=>({type:`lookup`,reference:e,...t}),masterDetail:(e,t={})=>({type:`master_detail`,reference:e,...t}),user:(e={})=>({type:`user`,reference:`sys_user`,...e}),location:(e={})=>({type:`location`,...e}),address:(e={})=>({type:`address`,...e}),richtext:(e={})=>({type:`richtext`,...e}),code:(e,t={})=>({type:`code`,language:e,...t}),color:(e={})=>({type:`color`,...e}),rating:(e=5,t={})=>({type:`rating`,max:e,...t}),signature:(e={})=>({type:`signature`,...e}),slider:(e={})=>({type:`slider`,...e}),qrcode:(e={})=>({type:`qrcode`,...e}),json:(e={})=>({type:`json`,...e}),vector:(e,t={})=>({type:`vector`,dimensions:e,...t})},R=t.z.object({name:t.z.string().regex(/^[a-z_][a-z0-9_]*$/).describe(`Unique rule name (snake_case)`),label:t.z.string().optional().describe(`Human-readable label for the rule listing`),description:t.z.string().optional().describe(`Administrative notes explaining the business reason`),active:t.z.boolean().default(!0),events:t.z.array(t.z.enum([`insert`,`update`])).default([`insert`,`update`]).describe("Write contexts the rule runs on. `delete` is intentionally absent — the evaluator only runs on the insert/update write path; guard deletions with a `beforeDelete` lifecycle hook"),priority:t.z.number().int().min(0).max(9999).default(100).describe(`Execution priority (lower runs first, default: 100)`),tags:t.z.array(t.z.string()).optional().describe(`Categorization tags (e.g., "compliance", "billing")`),severity:t.z.enum([`error`,`warning`,`info`]).default(`error`),message:t.z.string().describe(`Error message to display to the user`)}),tt=n(()=>R.extend({type:t.z.literal(`script`),condition:L.describe("Predicate (CEL). If TRUE, validation fails. e.g. P`record.amount < 0`")})),nt=n(()=>R.extend({type:t.z.literal(`state_machine`),field:t.z.string().describe(`State field (e.g. status)`),transitions:t.z.record(t.z.string(),t.z.array(t.z.string())).describe(`Map of { OldState: [AllowedNewStates] }`),initialStates:t.z.array(t.z.string()).optional().describe("States a record may be CREATED in. When set, an INSERT whose state field carries a value outside this list is rejected (server-enforced) — the FSM entry point. `transitions` only governs UPDATE, and a `select` field permits ANY declared option as an initial value, so without this a record could be born mid-flow (e.g. created already `approved`). Omit to keep the legacy behavior (no initial-state check on insert). #3165.")})),rt=n(()=>R.extend({type:t.z.literal(`format`),field:t.z.string(),regex:t.z.string().optional(),format:t.z.enum([`email`,`url`,`phone`,`json`]).optional()})),it=n(()=>R.extend({type:t.z.literal(`cross_field`),condition:L.describe("Predicate (CEL) comparing fields. e.g. P`record.end_date > record.start_date`"),fields:t.z.array(t.z.string()).describe(`Fields involved. Only fields[0] is read (labels which field the violation attaches to); the rest are advisory. Shares script’s evaluation path.`)})),at=n(()=>R.extend({type:t.z.literal(`json_schema`),field:t.z.string().describe(`JSON field to validate`),schema:t.z.record(t.z.string(),t.z.unknown()).describe(`JSON Schema object definition`)})),z=t.z.lazy(()=>t.z.discriminatedUnion(`type`,[tt,nt,rt,it,at,ot])),ot=n(()=>R.extend({type:t.z.literal(`conditional`),when:L.describe("Predicate (CEL). e.g. P`record.type == 'enterprise'`"),then:z.describe(`Validation rule to apply when condition is true`),otherwise:z.optional().describe(`Validation rule to apply when condition is false`)}));n(()=>t.z.object({key:t.z.string().describe(`Translation key (e.g., "views.task_list.label")`),defaultValue:t.z.string().optional().describe(`Fallback value when translation key is not found`),params:t.z.record(t.z.string(),t.z.union([t.z.string(),t.z.number(),t.z.boolean()])).optional().describe(`Interpolation parameters (e.g., { count: 5 })`)}));var B=n(()=>t.z.string().describe(`Display label (plain string; i18n keys are auto-generated by the framework)`)),st=n(()=>t.z.object({ariaLabel:B.optional().describe(`Accessible label for screen readers (WAI-ARIA aria-label)`),ariaDescribedBy:t.z.string().optional().describe(`ID of element providing additional description (WAI-ARIA aria-describedby)`),role:t.z.string().optional().describe(`WAI-ARIA role attribute (e.g., "dialog", "navigation", "alert")`)}).describe(`ARIA accessibility attributes`));n(()=>t.z.object({key:t.z.string().describe(`Translation key`),zero:t.z.string().optional().describe(`Zero form (e.g., "No items")`),one:t.z.string().optional().describe(`Singular form (e.g., "{count} item")`),two:t.z.string().optional().describe(`Dual form (e.g., "{count} items" for exactly 2)`),few:t.z.string().optional().describe(`Few form (e.g., for 2-4 in some languages)`),many:t.z.string().optional().describe(`Many form (e.g., for 5+ in some languages)`),other:t.z.string().describe(`Default plural form (e.g., "{count} items")`)}).describe(`ICU plural rules for a translation key`));var ct=n(()=>t.z.object({style:t.z.enum([`decimal`,`currency`,`percent`,`unit`]).default(`decimal`).describe(`Number formatting style`),currency:t.z.string().optional().describe(`ISO 4217 currency code (e.g., "USD", "EUR")`),unit:t.z.string().optional().describe(`Unit for unit formatting (e.g., "kilometer", "liter")`),minimumFractionDigits:t.z.number().optional().describe(`Minimum number of fraction digits`),maximumFractionDigits:t.z.number().optional().describe(`Maximum number of fraction digits`),useGrouping:t.z.boolean().optional().describe(`Whether to use grouping separators (e.g., 1,000)`)}).describe(`Number formatting rules`)),lt=n(()=>t.z.object({dateStyle:t.z.enum([`full`,`long`,`medium`,`short`]).optional().describe(`Date display style`),timeStyle:t.z.enum([`full`,`long`,`medium`,`short`]).optional().describe(`Time display style`),timeZone:t.z.string().optional().describe(`IANA time zone (e.g., "America/New_York")`),hour12:t.z.boolean().optional().describe(`Use 12-hour format`)}).describe(`Date/time formatting rules`));n(()=>t.z.object({code:t.z.string().describe(`BCP 47 language code (e.g., "en-US", "zh-CN")`),fallbackChain:t.z.array(t.z.string()).optional().describe(`Fallback language codes in priority order (e.g., ["zh-TW", "en"])`),direction:t.z.enum([`ltr`,`rtl`]).default(`ltr`).describe(`Text direction: left-to-right or right-to-left`),numberFormat:ct.optional().describe(`Default number formatting rules`),dateFormat:lt.optional().describe(`Default date/time formatting rules`)}).describe(`Locale configuration`));function ut(e,t){let n=e.length,r=t.length;if(n===0)return r;if(r===0)return n;let i=Array(r+1),a=Array(r+1);for(let e=0;e<=r;e++)i[e]=e;for(let o=1;o<=n;o++){a[0]=o;for(let n=1;n<=r;n++){let r=e[o-1]===t[n-1]?0:1;a[n]=Math.min(i[n]+1,a[n-1]+1,i[n-1]+r)}[i,a]=[a,i]}return i[r]}function dt(e,t,n=3,r=3){let i=e.toLowerCase().replace(/[-\s]/g,`_`);return t.map(e=>({value:e,distance:ut(i,e)})).filter(e=>e.distance<=n&&e.distance>0).sort((e,t)=>e.distance-t.distance).slice(0,r).map(e=>e.value)}var ft=e=>e.toLowerCase().replace(/[_\-\s]/g,``);function V(e){let{surface:t,knownKeys:n,guidance:r={},history:i}=e,a={};for(let[t,n]of Object.entries(e.aliases??{}))a[ft(t)]=n;return e=>{if(e.code!==`unrecognized_keys`)return;let o=e.keys??[],s=[],c=[];for(let e of o){let t=r[e];if(t){c.push(t);continue}let i=Math.max(2,Math.floor(e.length/3)),o=a[ft(e)]??dt(e,n,i,1)[0];o&&o!==e&&s.push(`\`${e}\` \u2192 \`${o}\``)}let l=`Unrecognized key(s) on ${t}: ${o.map(e=>`\`${e}\``).join(`, `)}. ${i}`;return s.length&&(l+=` Did you mean ${s.join(`, `)}?`),c.length&&(l+=`
|
|
2
|
+
${c.map(e=>` \u2022 ${e}`).join(`
|
|
3
|
+
`)}`),l}}var pt=t.z.enum([`api.read`,`api.write`,`api.transaction`,`crypto.uuid`,`crypto.hash`,`log`]),mt=[`language`,`source`],ht=[`language`,`source`,`capabilities`,`timeoutMs`,`memoryMb`],gt='is an L2 key — it only applies to `language: "js"`. An expression body is a pure formula: it performs no IO, so it has nothing to grant and no sandbox to bound.',_t=V({surface:`this expression (L1) hook body`,knownKeys:mt,aliases:{expression:`source`,formula:`source`,code:`source`,script:`source`},guidance:{capabilities:`\`capabilities\` ${gt}`,timeoutMs:`\`timeoutMs\` ${gt}`,memoryMb:`\`memoryMb\` ${gt}`},history:`Until #4001 these were dropped silently.`}),vt=V({surface:`this sandboxed JS (L2) hook body`,knownKeys:ht,aliases:{capability:`capabilities`,caps:`capabilities`,permissions:`capabilities`,timeout:`timeoutMs`,timeoutms:`timeoutMs`,memory:`memoryMb`,memorymb:`memoryMb`,code:`source`,script:`source`,body:`source`},history:`Until #4001 these were dropped silently — the body still ran, just not under the limits or grants that were written.`}),yt=t.z.object({language:t.z.literal(`expression`),source:t.z.string().min(1).describe(`Formula expression source`)},{error:_t}).strict().describe(`L1 expression body — pure formula, no IO`),bt=t.z.object({language:t.z.literal(`js`),source:t.z.string().min(1).describe(`Function body source`),capabilities:t.z.array(pt).default([]).describe(`Granted capability tokens`),timeoutMs:t.z.number().int().positive().max(3e4).optional().describe(`Per-invocation timeout (ms)`),memoryMb:t.z.number().int().positive().max(256).optional().describe(`Per-invocation memory cap (MB)`)},{error:vt}).strict().describe(`L2 sandboxed JS body — runs inside an isolated VM with declared capabilities`),xt=t.z.discriminatedUnion(`language`,[yt,bt]).describe(`Hook/Action body — expression (L1) or sandboxed JS (L2)`),St={twoFactor:{surface:`crud`,semantics:`opt-in`,gatedInputs:[`sys_user.actions.enable_two_factor`,`sys_user.actions.disable_two_factor`,`sys_user.actions.generate_backup_codes`,`sys_two_factor.actions.enable_two_factor`,`sys_two_factor.actions.disable_two_factor`,`sys_two_factor.actions.regenerate_backup_codes`],notes:`Login-surface 2FA challenge is server-driven remediation (ADR-0069), so the flag is intentionally unread by objectui LoginForm.`},passkeys:{surface:`login`,semantics:`opt-in`,exempt:{reason:`No spec input to gate. Typed in objectui (auth/src/types.ts) but no passkey UI exists yet — advertised-but-unconsumed gap tracked in objectui#2514 (#2874 P2②).`}},magicLink:{surface:`login`,semantics:`opt-in`,exempt:{reason:`No spec input to gate. Typed in objectui (auth/src/types.ts) but no magic-link UI exists yet — advertised-but-unconsumed gap tracked in objectui#2514 (#2874 P2②).`}},organization:{surface:`crud`,semantics:`default-on`,gatedInputs:[`sys_user.actions.invite_user`,`sys_member.actions.add_member`,`sys_member.actions.update_member_role`,`sys_member.actions.remove_member`,`sys_member.actions.transfer_ownership`,`sys_invitation.actions.invite_user`,`sys_invitation.actions.cancel_invitation`,`sys_invitation.actions.resend_invitation`,`sys_team.actions.create_team`,`sys_team.actions.update_team`,`sys_team.actions.remove_team`,`sys_team_member.actions.add_team_member`,`sys_team_member.actions.remove_team_member`],notes:`Org CAPABILITY gate, not multi-org (ADR-0081 D1).`},multiOrgEnabled:{surface:`crud`,semantics:`default-on`,gatedInputs:[`sys_organization.actions.create_organization`,`sys_organization.actions.update_organization`,`sys_organization.actions.delete_organization`,`sys_organization.actions.set_active_organization`,`sys_organization.actions.leave_organization`,`sys_organization.actions.change_slug`],notes:"Reflects ACTUAL multi-tenancy capability (the tenancy posture enforces an organization wall — `group` or `isolated`, ADR-0093 D4 / ADR-0105 D1), not just the requested posture."},degradedTenancy:{surface:`status`,semantics:`opt-in`,exempt:{reason:`Operator status banner (ADR-0093 D5) — signals degraded tenant isolation, not an input capability gate.`}},oidcProvider:{surface:`crud`,semantics:`default-on`,gatedInputs:[`sys_oauth_application.actions.create_oauth_application`,`sys_oauth_application.actions.delete_oauth_application`,`sys_oauth_application.actions.disable_oauth_application`,`sys_oauth_application.actions.enable_oauth_application`,`sys_oauth_application.actions.rotate_client_secret`],notes:`Default-ON: the embedded OIDC authorization server follows the default-on MCP surface (resolveOidcProviderEnabled). Login surface consumes the socialProviders[] array (per-provider enabled), not this flag.`},sso:{surface:`login`,semantics:`opt-in`,exempt:{reason:`Deliberately ungated on the CRUD surface: the served value is refined to "usable" (≥1 provider configured) via isSsoUsable() at /auth/config, so gating sys_sso_provider registration actions on it would deadlock first-provider setup. Login consumption verified: objectui LoginForm gates the "Sign in with SSO" button.`}},ssoEnforced:{surface:`login`,semantics:`opt-in`,exempt:{reason:`Login-surface only: objectui LoginForm hides the password form and self-registration (break-glass link remains). No spec input to gate.`}},deviceAuthorization:{surface:`login`,semantics:`opt-in`,exempt:{reason:`No spec input (sys_device_code declares no actions). Known gap: objectui DeviceAuthPage hits the device-auth endpoints without checking this flag (absent from its client type) — tracked in objectui#2513 (#2874 P2②).`}},admin:{surface:`crud`,semantics:`opt-in`,gatedInputs:[`sys_user.actions.create_user`,`sys_user.actions.ban_user`,`sys_user.actions.unban_user`,`sys_user.actions.unlock_user`,`sys_user.actions.set_user_password`,`sys_user.actions.set_user_role`,`sys_user.actions.impersonate_user`],notes:`SCIM forces the admin plugin (and this flag) on — ADR-0071.`},phoneNumber:{surface:`crud`,semantics:`opt-in`,gatedInputs:[`sys_user.actions.create_user.params.phoneNumber`],notes:`The original #2871 fix. Also read by objectui LoginForm for the phone+password sign-in mode.`},phoneNumberOtp:{surface:`login`,semantics:`opt-in`,exempt:{reason:`Login-surface only: gates the "sign in with verification code" link (LoginForm) and the phone branch of forgot-password. Only advertised when SMS is actually deliverable (#2780).`}}},Ct=Object.keys(St);function wt(e){return`features.${e} ${St[e].semantics===`opt-in`?`== true`:`!= false`}`}function Tt(e,t){let{requiresFeature:n,...r}=e;if(n===void 0)return r;let i=wt(n),a=r.visible;return a===void 0?{...r,visible:{dialect:`cel`,source:i}}:a.dialect!==`cel`||typeof a.source!=`string`?(t.addIssue({code:`custom`,path:[`requiresFeature`],message:"`requiresFeature` composes only with a CEL `visible` carrying a `source` string; this expression is AST-only or non-CEL — write the combined predicate by hand."}),r):{...r,visible:{...a,source:`(${a.source}) && ${i}`}}}var Et=V({surface:`this action param`,knownKeys:[`name`,`field`,`objectOverride`,`label`,`type`,`required`,`options`,`placeholder`,`helpText`,`defaultValue`,`multiple`,`accept`,`maxSize`,`reference`,`defaultFromRow`,`visible`,`requiresFeature`],aliases:{referenceto:`reference`,referenceobject:`reference`,referencedobject:`reference`,targetobject:`reference`,visiblewhen:`visible`,visibleon:`visible`,visibility:`visible`,description:`helpText`,help:`helpText`,default:`defaultValue`},history:`Until #3405 these were dropped silently — the param still parsed, so a mis-spelled config shipped as a control that quietly ignored it.`}),Dt=n(()=>t.z.object({name:t.z.string().optional(),field:I.optional(),objectOverride:I.optional(),label:B.optional(),type:We.optional(),required:t.z.boolean().optional().default(!1),options:t.z.array(t.z.object({label:B,value:t.z.string()})).optional(),placeholder:t.z.string().optional(),helpText:t.z.string().optional(),defaultValue:t.z.unknown().optional(),multiple:t.z.boolean().optional().describe(`Allow multiple values (array value shape); mirrors FieldSchema.multiple.`),accept:t.z.array(t.z.string()).optional().describe(`Accepted upload types (MIME types / extensions) for file/image params.`),maxSize:t.z.number().int().positive().optional().describe(`Max upload size in bytes for file/image params.`),reference:I.optional().describe(`Reference target object for inline lookup/master_detail params; mirrors FieldSchema.reference.`),defaultFromRow:t.z.boolean().optional(),visible:L.optional().describe(`Param visibility predicate (CEL); omits the param when false.`),requiresFeature:t.z.enum(Ct).optional().describe("Public auth feature flag gating this param; lowered into `visible` at parse time.")},{error:Et}).strict().refine(e=>!!e.name||!!e.field,{message:`ActionParam requires either "name" or "field"`}).refine(e=>!(!e.field&&(e.type===`lookup`||e.type===`master_detail`)&&!e.reference),{path:[`reference`],message:`ActionParam with type "lookup"/"master_detail" requires "reference" (the target object) when declared inline — without it the param dialog degrades to a raw record-id text input. Set \`reference: '<object>'\`, or use a field-backed param (\`{ field: '<lookup_field>' }\`) to inherit it.`}).transform((e,t)=>Tt(e,t))),Ot=t.z.enum([`script`,`url`,`modal`,`flow`,`api`,`form`]),kt=new Set(Ot.options.filter(e=>e!==`script`)),At=t.z.enum([`list_toolbar`,`list_item`,`record_header`,`record_more`,`record_related`,`record_section`,`global_nav`]),jt=t.z.enum([`data`,`action`,`flow`,`integration`,`vector_search`,`analytics`,`utility`]),Mt=t.z.object({exposed:t.z.boolean().default(!1).describe("Expose this action to AI agents. Requires `description` when true."),description:t.z.string().min(40).optional().describe(`LLM-facing description (≥40 chars). Required when exposed.`),category:jt.optional().describe(`Tool category override (defaults to "action").`),paramHints:t.z.record(t.z.string(),t.z.object({description:t.z.string().optional(),enum:t.z.array(t.z.union([t.z.string(),t.z.number()])).optional(),examples:t.z.array(t.z.unknown()).optional()})).optional().describe(`Per-parameter AI hints keyed by param name.`),outputSchema:t.z.record(t.z.string(),t.z.unknown()).optional().describe(`JSON Schema for the action return value.`),requiresConfirmation:t.z.boolean().optional().describe(`Override HITL confirmation for AI invocations.`)}),Nt=()=>t.z.object({name:I.describe(`Machine name (lowercase snake_case)`),label:B.describe(`Display label`),objectName:t.z.string().regex(/^[a-z_][a-z0-9_]*$/).optional().describe(`Target object this action belongs to. When set, the action is auto-merged into the object's actions array by defineStack().`),icon:t.z.string().optional().describe(`Icon name`),locations:t.z.array(At).optional().describe(`Locations where this action is visible`),component:t.z.enum([`action:button`,`action:icon`,`action:menu`,`action:group`]).optional().describe(`Visual component override`),type:Ot.default(`script`).describe(`Action functionality type`),target:t.z.string().optional().describe("URL, Script Name, Flow ID, or API Endpoint. Supports ${param.X} and ${ctx.X} interpolation."),openIn:t.z.enum([`self`,`new-tab`]).optional().describe("For type:'url' — where to open `target`. 'new-tab' opens a new browser tab; 'self' navigates in place. When omitted, external/absolute URLs open in a new tab and relative URLs navigate in place. Static execution option — keep it OUT of `params` (which is user-input-collection only)."),body:xt.optional().describe("Action body — expression (L1) or sandboxed JS (L2). Only used when type is `script`."),execute:w("`execute` was removed in @objectstack/spec 17 (#3855) — use `target`. Rename the key; the value (a handler / flow / URL ref) is unchanged. Run `os migrate meta --from 16` to rewrite it automatically."),params:t.z.array(Dt).optional().describe(`Input parameters required from user`),variant:t.z.enum([`primary`,`secondary`,`danger`,`ghost`,`link`]).optional().describe(`Button visual variant for styling (primary = highlighted, danger = destructive, ghost = transparent)`),order:t.z.number().optional().describe("Sort order within a location group (lower = higher). Promotes/demotes an action toward the record_header primary button; stable, so actions without `order` keep their registration order."),confirmText:B.optional().describe(`Confirmation message before execution`),successMessage:B.optional().describe(`Success message to show after execution`),errorMessage:B.optional().describe(`Error message to show when the action fails (overrides the raw error).`),refreshAfter:t.z.boolean().default(!1).describe(`Refresh view after execution`),undoable:t.z.boolean().optional().describe(`Offer an Undo affordance after this single-record update action succeeds.`),resultDialog:t.z.object({title:B.optional(),description:B.optional(),acknowledge:B.optional().describe(`Acknowledge button label, e.g. "I have saved this"`),format:t.z.enum([`qrcode`,`code-list`,`secret`,`text`,`json`]).optional().describe(`Default format for fields without their own format. Defaults to json when omitted.`),fields:t.z.array(t.z.object({path:t.z.string().describe(`Dot path into result.data (e.g. "totpURI", "client.client_secret").`),label:B.optional(),format:t.z.enum([`qrcode`,`code-list`,`secret`,`text`,`json`]).optional().describe(`Per-field format override.`)})).optional().describe(`Which fields from result.data to render. Omit to dump full JSON.`)}).optional().describe(`Render API response in a one-shot reveal dialog (suppresses successMessage when set).`),visible:L.optional().describe(`Visibility predicate (CEL).`),requiresFeature:t.z.enum(Ct).optional().describe("Public auth feature flag gating this action; lowered into `visible` at parse time."),disabled:t.z.union([t.z.boolean(),L]).optional().describe(`Boolean or predicate (CEL) — action is disabled when TRUE.`),requiredPermissions:t.z.array(t.z.string()).optional().describe("[ADR-0066 D4] Capabilities required to invoke this action. Enforced with 403 on the platform action route (script/flow/modal + MCP) and mirrored as a UI hide; a `type: api` action pointed at a custom endpoint must re-check it there."),shortcut:w("`action.shortcut` was removed in @objectstack/spec 17.0.0 (#3896 audit close-out) — it never triggered anything: no keydown listener feeds ActionEngine.getShortcuts(), and objectui's keyboard stack (useKeyboardShortcuts) is hand-registered and never consults action metadata. Delete the key. For a real shortcut, register the key in the Console keyboard stack and have its handler invoke the action by name."),bulkEnabled:w("`action.bulkEnabled` was removed in @objectstack/spec 17.0.0 (#3896 audit close-out) — the multi-select toolbar is driven by the LIST VIEW's `bulkActions` / `bulkActionDefs`, never by this flag, so setting it changed nothing. Delete the key and declare the action in the view's `bulkActions` instead."),ai:Mt.optional().describe(`AI exposure (opt-in). Set ai.exposed=true + ai.description to make this callable by agents.`),recordIdParam:t.z.string().optional().describe(`Body key to inject the row id into when running from a list_item context.`),recordIdField:t.z.string().optional().describe(`Row field whose value seeds recordIdParam. Defaults to "id".`),bodyShape:t.z.union([t.z.literal(`flat`),t.z.object({wrap:t.z.string()})]).optional().describe(`Body wrapping: flat (default) or { wrap: key } to nest user-collected params under a key.`),method:t.z.enum([`POST`,`PATCH`,`PUT`,`DELETE`]).optional().describe(`HTTP method for type:"api" actions. Defaults to POST.`),bodyExtra:t.z.record(t.z.string(),t.z.unknown()).optional().describe(`Constant body fields merged into the API request (applied last; overrides user params).`),mode:t.z.enum([`create`,`edit`,`delete`,`custom`]).optional().describe(`Semantic mode of the action.`),opensInNewTab:t.z.boolean().optional().describe(`Open the action result in a new tab. The renderer pre-opens the tab synchronously on click (popup-blocker-safe) and navigates it to the handler's redirectUrl.`),newTabUrl:t.z.string().optional().describe(`Direct new-tab URL template ({recordId} placeholder). When set with opensInNewTab, the renderer navigates the pre-opened tab here immediately — no action POST. The endpoint must enforce auth itself.`),aria:st.optional().describe(`ARIA accessibility attributes`)}),Pt=n(()=>Nt().refine(e=>!(kt.has(e.type)&&!e.target),{message:`Action 'target' is required when type is 'url', 'flow', 'modal', 'api', or 'form'.`,path:[`target`]}).refine(e=>!(e.type===`script`&&!e.body&&!e.target),{message:"A 'script' action requires either an inline `body` (sandboxed L1/L2 handler) or a `target` (a registered bundle function name).",path:[`body`]}).refine(e=>!(e.type!==`script`&&e.body),{message:"`body` only runs for `type: 'script'` — a non-script action dispatches on `target` and silently ignores its body. To collect `params` and then run the body, use `type: 'script'`; to open a page/modal, drop the `body` and keep `type: 'modal'` with `target` naming the page.",path:[`body`]}).refine(e=>!(e.ai?.exposed===!0&&!e.ai.description),{message:`ai.description is required (≥40 chars) when ai.exposed is true.`,path:[`ai`,`description`]}).refine(e=>{let t=e.ai?.paramHints;if(!t)return!0;let n=new Set([`recordId`]);for(let t of e.params??[]){let e=t.name??t.field;e&&n.add(e)}return Object.keys(t).every(e=>n.has(e))},{message:`ai.paramHints keys must match a declared param name (or "recordId").`,path:[`ai`,`paramHints`]}).transform((e,t)=>Tt(e,t)));function Ft(e){if(!e||typeof e!=`object`||Array.isArray(e))return e;let t=e,n=t.type===`navigation`,r=t.target===void 0&&typeof t.to==`string`;if(!n&&!r&&!(`to`in t))return e;let i={...t};return n&&(i.type=`url`),r&&(i.target=t.to),delete i.to,i}n(()=>t.z.preprocess(Ft,Nt().pick({type:!0,name:!0,label:!0,target:!0,openIn:!0,method:!0,params:!0,confirmText:!0,successMessage:!0,errorMessage:!0,refreshAfter:!0,opensInNewTab:!0}).partial({name:!0,label:!0}).refine(e=>!(kt.has(e.type)&&!e.target),{message:"Inline action 'target' is required when type is 'url', 'flow', 'modal', 'api', or 'form' (`to` is accepted as a legacy spelling).",path:[`target`]})));var It=t.z.enum([`none`,`no-overlay`,`no-delete`,`full`]),Lt=t.z.enum([`artifact`,`package`,`env-forced`]),Rt=t.z.enum([`package`,`org`,`env-forced`]),H={_lock:It.optional().describe(`Item-level lock — controls overlay & delete (ADR-0010).`),_lockReason:t.z.string().max(500).optional().describe(`Human-readable reason shown when a write is refused by _lock.`),_lockSource:Lt.optional().describe(`Layer that set _lock (artifact | package | env-forced).`),_provenance:Rt.optional().describe(`Origin of the item (package | org | env-forced).`),_packageId:t.z.string().optional().describe(`Owning package machine id.`),_packageVersion:t.z.string().optional().describe(`Owning package version.`),_lockDocsUrl:t.z.string().optional().describe(`Optional documentation link surfaced next to _lockReason.`)},U=t.z.object({lock:It.describe(`Lock policy — none | no-overlay | no-delete | full.`),reason:t.z.string().min(1).max(500).describe(`User-visible reason shown when the lock blocks an action.`),docsUrl:t.z.string().url().optional().describe(`Optional URL the Studio banner links to for more context.`)}).strict();function zt(e){let{visibleOn:t,visibility:n,...r}=e,i=r.visibleWhen===void 0?t===void 0?n:t:r.visibleWhen;return i===void 0?r:{...r,visibleWhen:i}}function Bt(e){return/vis|conceal|hidden|show.?when/i.test(e)}var Vt=e=>{if(e.code!==`unrecognized_keys`)return;let t=e.keys??[],n=`Unrecognized key(s) on this view/page schema: ${t.map(e=>`\`${e}\``).join(`, `)}. Before ADR-0089 D3a these were dropped silently, shipping inert metadata; a mis-layered or stale key is now a loud parse error.`;return t.some(Bt)?n+" If this is the conditional-visibility predicate, the canonical key is `visibleWhen` (ADR-0089) — `visibleOn` (view form) and `visibility` (page component) are still accepted as deprecated aliases.":n},Ht=n(()=>t.z.enum([`bar`,`horizontal-bar`,`column`,`line`,`area`,`pie`,`donut`,`funnel`,`scatter`,`treemap`,`sankey`,`combo`,`gauge`,`solid-gauge`,`metric`,`kpi`,`bullet`,`radar`,`table`,`pivot`])),Ut=n(()=>t.z.object({field:t.z.string().describe(`Data field key`),title:B.optional().describe(`Axis display title`),format:t.z.string().optional().describe(`Value format string (e.g., "$0,0.00")`),min:t.z.number().optional().describe(`Minimum value`),max:t.z.number().optional().describe(`Maximum value`),stepSize:t.z.number().optional().describe(`Step size for ticks`),showGridLines:t.z.boolean().default(!0),position:t.z.enum([`left`,`right`,`top`,`bottom`]).optional().describe(`Axis position`),logarithmic:t.z.boolean().default(!1)})),Wt=n(()=>t.z.object({name:t.z.string().describe(`Field name or series identifier`),label:B.optional().describe(`Series display label`),type:Ht.optional().describe(`Override chart type for this series`),color:t.z.string().optional().describe(`Series color (hex/rgb/token)`),stack:t.z.string().optional().describe(`Stack identifier to group series`),yAxis:t.z.enum([`left`,`right`]).default(`left`).describe(`Bind to specific Y-Axis`),variant:t.z.enum([`primary`,`comparison`]).default(`primary`).optional().describe(`Series visual role`),dashArray:t.z.string().optional().describe(`SVG stroke-dasharray override`),opacity:t.z.number().min(0).max(1).optional().describe(`Series opacity override`)})),Gt=n(()=>t.z.object({type:t.z.enum([`line`,`region`]).default(`line`),axis:t.z.enum([`x`,`y`]).default(`y`),value:t.z.union([t.z.number(),t.z.string()]).describe(`Start value`),endValue:t.z.union([t.z.number(),t.z.string()]).optional().describe(`End value for regions`),color:t.z.string().optional(),label:B.optional(),style:t.z.enum([`solid`,`dashed`,`dotted`]).default(`dashed`)})),Kt=n(()=>t.z.object({tooltips:t.z.boolean().default(!0).describe(`Show the hover tooltip`),brush:t.z.boolean().default(!1).describe(`Show the range selector under the plot`)}));n(()=>t.z.object({type:Ht,title:B.optional().describe(`Chart title`),subtitle:B.optional().describe(`Chart subtitle`),description:B.optional().describe(`Accessibility description — announced to screen readers as the chart’s label`),xAxis:Ut.optional().describe(`X-Axis configuration`),yAxis:t.z.array(Ut).optional().describe(`Y-Axis configuration (support dual axis)`),series:t.z.array(Wt).optional().describe(`Defined series configuration`),colors:t.z.union([t.z.array(t.z.string()),t.z.record(t.z.string(),t.z.string())]).optional().describe(`Color palette (string[]) or value→color map ({ value: color })`),height:t.z.number().optional().describe(`Fixed plot height in pixels (overrides the container default)`),showLegend:t.z.boolean().default(!0).describe(`Display legend`),showDataLabels:t.z.boolean().default(!1).describe(`Display data labels`),annotations:t.z.array(Gt).optional().describe(`Reference lines/bands drawn over the plot: { type: "line" | "region", axis: "x" | "y", value, endValue?, color?, label?, style? }`),interaction:Kt.optional().describe(`Interaction toggles: { tooltips?, brush? }`),aria:st.optional().describe(`ARIA accessibility attributes`)}));var qt=n(()=>t.z.enum([`count`,`sum`,`avg`,`min`,`max`])),Jt=n(()=>t.z.union([t.z.string().describe(`Field to group by`),t.z.object({field:t.z.string().describe(`Field to group by`),dateGranularity:t.z.enum([`day`,`week`,`month`,`quarter`,`year`]).optional().describe(`Bucket date values into uniform periods`),alias:t.z.string().optional().describe("Alias for the projected group value (defaults to `field`) — this becomes the category column")})]));n(()=>t.z.object({field:t.z.string().optional().describe(`Field to aggregate — required for sum/avg/min/max, optional for count`),function:qt.describe(`Aggregation function`),groupBy:Jt.describe(`Field the rows are grouped by — the chart category axis`)}).superRefine((e,t)=>{e.function!==`count`&&!e.field&&t.addIssue({code:`custom`,path:[`field`],message:`aggregate.function "${e.function}" needs a "field" to aggregate (only "count" may omit it).`})}).describe(`Inline aggregation for an object-bound chart`));var Yt=n(()=>t.z.object({enabled:t.z.boolean().default(!1).describe(`Enable public sharing`),publicLink:t.z.string().optional().describe(`Generated public share URL`),password:t.z.string().optional().describe(`Password required to access shared link`),allowedDomains:t.z.array(t.z.string()).optional().describe(`Restrict access to specific email domains (e.g. ["example.com"])`),expiresAt:t.z.string().optional().describe(`Expiration date/time in ISO 8601 format`),allowAnonymous:t.z.boolean().optional().default(!1).describe(`Allow access without authentication`)}));n(()=>t.z.object({enabled:t.z.boolean().default(!1).describe(`Enable iframe embedding`),allowedOrigins:t.z.array(t.z.string()).optional().describe(`Allowed iframe parent origins (e.g. ["https://example.com"])`),width:t.z.string().optional().default(`100%`).describe(`Embed width (CSS value)`),height:t.z.string().optional().default(`600px`).describe(`Embed height (CSS value)`),showHeader:t.z.boolean().optional().default(!0).describe(`Show interface header in embed`),showNavigation:t.z.boolean().optional().default(!1).describe(`Show navigation in embed`),responsive:t.z.boolean().optional().default(!0).describe(`Enable responsive resizing`)}));var Xt=t.z.enum([`GET`,`POST`,`PUT`,`DELETE`,`PATCH`,`HEAD`,`OPTIONS`]),Zt=n(()=>t.z.enum([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`])),Qt=n(()=>t.z.object({url:t.z.string().describe(`API endpoint URL`),method:Zt.optional().default(`GET`).describe(`HTTP method`),headers:t.z.record(t.z.string(),t.z.string()).optional().describe(`Custom HTTP headers`),params:t.z.record(t.z.string(),t.z.unknown()).optional().describe(`Query parameters`),body:t.z.unknown().optional().describe(`Request body for POST/PUT/PATCH`)}));n(()=>t.z.object({enabled:t.z.boolean().default(!0).describe(`Enable CORS`),origins:t.z.union([t.z.string(),t.z.array(t.z.string())]).default(`*`).describe(`Allowed origins (* for all)`),methods:t.z.array(Xt).optional().describe(`Allowed HTTP methods`),credentials:t.z.boolean().default(!1).describe(`Allow credentials (cookies, authorization headers)`),maxAge:t.z.number().int().optional().describe(`Preflight cache duration in seconds`)})),n(()=>t.z.object({enabled:t.z.boolean().default(!1).describe(`Enable rate limiting`),windowMs:t.z.number().int().default(6e4).describe(`Time window in milliseconds`),maxRequests:t.z.number().int().default(100).describe(`Max requests per window`)})),n(()=>t.z.object({path:t.z.string().describe(`URL path to serve from`),directory:t.z.string().describe(`Physical directory to serve`),cacheControl:t.z.string().optional().describe(`Cache-Control header value`)}));var $t=n(()=>t.z.discriminatedUnion(`provider`,[t.z.object({provider:t.z.literal(`object`),object:t.z.string().describe(`Target object name`)}),t.z.object({provider:t.z.literal(`api`),read:Qt.optional().describe(`Configuration for fetching data`),write:Qt.optional().describe(`Configuration for submitting data (for forms/editable tables)`)}),t.z.object({provider:t.z.literal(`value`),items:t.z.array(t.z.unknown()).describe(`Static data array`)}),t.z.object({provider:t.z.literal(`schema`),schemaId:t.z.string().describe(`Schema identifier — typically the metadata type name`),schema:t.z.record(t.z.string(),t.z.unknown()).optional().describe(`Inline JSON Schema (Draft 2020-12). Optional when schemaId is resolvable.`)})])),en=[`equals`,`not_equals`,`contains`,`not_contains`,`starts_with`,`ends_with`,`greater_than`,`less_than`,`greater_than_or_equal`,`less_than_or_equal`,`in`,`not_in`,`is_empty`,`is_not_empty`,`is_null`,`is_not_null`,`before`,`after`,`between`],tn={eq:`equals`,ne:`not_equals`,neq:`not_equals`,notequals:`not_equals`,notEquals:`not_equals`,notcontains:`not_contains`,notContains:`not_contains`,startswith:`starts_with`,startsWith:`starts_with`,endswith:`ends_with`,endsWith:`ends_with`,gt:`greater_than`,greaterthan:`greater_than`,greaterThan:`greater_than`,lt:`less_than`,lessthan:`less_than`,lessThan:`less_than`,gte:`greater_than_or_equal`,greaterorequal:`greater_than_or_equal`,greaterOrEqual:`greater_than_or_equal`,greaterThanOrEqual:`greater_than_or_equal`,lte:`less_than_or_equal`,lessorequal:`less_than_or_equal`,lessOrEqual:`less_than_or_equal`,lessThanOrEqual:`less_than_or_equal`,nin:`not_in`,notin:`not_in`,notIn:`not_in`,isempty:`is_empty`,isEmpty:`is_empty`,isnotempty:`is_not_empty`,isNotEmpty:`is_not_empty`,isnull:`is_null`,isNull:`is_null`,isnotnull:`is_not_null`,isNotNull:`is_not_null`};function nn(e){return typeof e!=`string`||en.includes(e)?e:tn[e]??tn[e.toLowerCase()]??e}var rn=n(()=>t.z.object({field:t.z.string().describe(`Field name to filter on`),operator:t.z.preprocess(nn,t.z.enum(en)).describe(`Filter operator`),value:t.z.union([t.z.string(),t.z.number(),t.z.boolean(),t.z.null(),t.z.array(t.z.union([t.z.string(),t.z.number()]))]).optional().describe(`Filter value`)}).describe(`View filter rule`)),an=n(()=>t.z.enum([`none`,`count`,`count_empty`,`count_filled`,`count_unique`,`percent_empty`,`percent_filled`,`sum`,`avg`,`min`,`max`]).describe(`Aggregation function for column footer summary`)),on=n(()=>t.z.object({type:an.describe(`Aggregation function`),field:t.z.string().optional().describe(`Field to aggregate (defaults to the column field)`)}).describe(`Column footer summary configuration`)),sn=n(()=>t.z.object({field:t.z.string().describe(`Field whose value renders before the cell value`),type:t.z.enum([`badge`,`text`]).default(`text`).describe(`How the prefix value is rendered`)}).describe(`Compound-cell prefix configuration`)),cn=n(()=>t.z.object({field:t.z.string().describe(`Field name (snake_case)`),label:B.optional().describe(`Display label override`),width:t.z.number().positive().optional().describe(`Column width in pixels`),align:t.z.enum([`left`,`center`,`right`]).optional().describe(`Text alignment`),hidden:t.z.boolean().optional().describe(`Hide column by default`),sortable:t.z.boolean().optional().describe(`Allow sorting by this column`),resizable:t.z.boolean().optional().describe(`Allow resizing this column`),wrap:t.z.boolean().optional().describe(`Allow text wrapping`),type:t.z.string().optional().describe(`Renderer type override (e.g., "currency", "date")`),pinned:t.z.enum([`left`,`right`]).optional().describe(`Pin/freeze column to left or right side`),summary:t.z.union([an,on]).optional().describe(`Footer aggregation for this column — the function alone, or { type, field } to aggregate another field`),prefix:sn.optional().describe(`Field rendered inline before this cell value`),link:t.z.boolean().optional().describe(`Functions as the primary navigation link (triggers View navigation)`),action:t.z.string().optional().describe(`Registered Action ID to execute when clicked`)})),ln=n(()=>t.z.object({type:t.z.enum([`none`,`single`,`multiple`]).default(`none`).describe(`Selection mode`)})),un=n(()=>t.z.object({pageSize:t.z.number().int().positive().default(25).describe(`Number of records per page`),pageSizeOptions:t.z.array(t.z.number().int().positive()).optional().describe(`Available page size options`)})),dn=n(()=>t.z.enum([`compact`,`short`,`medium`,`tall`,`extra_tall`]).describe(`Row height / density setting for list view`)),fn=n(()=>t.z.object({field:t.z.string().describe(`Field name to group by`),order:t.z.enum([`asc`,`desc`]).default(`asc`).describe(`Group sort order`),collapsed:t.z.boolean().default(!1).describe(`Collapse groups by default`)})),pn=n(()=>t.z.object({fields:t.z.array(fn).min(1).describe(`Fields to group by (supports up to 3 levels)`)}).describe(`Record grouping configuration`)),mn=n(()=>t.z.object({coverField:t.z.string().optional().describe(`Attachment/image field to display as card cover`),coverFit:t.z.enum([`cover`,`contain`]).default(`cover`).describe(`Image fit mode for card cover`),cardSize:t.z.enum([`small`,`medium`,`large`]).default(`medium`).describe(`Card size in gallery view`),titleField:t.z.string().optional().describe(`Field to display as card title`),visibleFields:t.z.array(t.z.string()).optional().describe(`Fields to display on card body`)}).describe(`Gallery/card view configuration`)),hn=n(()=>t.z.object({startDateField:t.z.string().describe(`Field for timeline item start date`),endDateField:t.z.string().optional().describe(`Field for timeline item end date`),titleField:t.z.string().describe(`Field to display as timeline item title`),groupByField:t.z.string().optional().describe(`Field to group timeline rows`),colorField:t.z.string().optional().describe(`Field to determine item color`),scale:t.z.enum([`hour`,`day`,`week`,`month`,`quarter`,`year`]).default(`week`).describe(`Default timeline scale`)}).describe(`Timeline view configuration`)),gn=n(()=>t.z.object({type:t.z.enum([`personal`,`collaborative`]).default(`collaborative`).describe(`View ownership type`),lockedBy:t.z.string().optional().describe(`User who locked the view configuration`)}).describe(`View sharing and access configuration`)),_n=n(()=>t.z.object({field:t.z.string().describe(`Field to derive color from (typically a select/status field)`),colors:t.z.record(t.z.string(),t.z.string()).optional().describe(`Map of field value to color (hex/token)`)}).describe(`Row color configuration based on field values`)),vn=n(()=>t.z.enum([`grid`,`kanban`,`gallery`,`calendar`,`timeline`,`gantt`,`map`,`chart`,`tree`]).describe(`Visualization type that users can switch to`)),yn=n(()=>t.z.object({sort:t.z.boolean().default(!0).describe(`Allow users to sort records`),search:t.z.boolean().default(!0).describe(`Allow users to search records`),filter:t.z.boolean().default(!0).describe(`Allow users to filter records`),refresh:t.z.boolean().default(!0).describe(`Allow users to reload the view data from the backend without a full page reload`),rowHeight:t.z.boolean().default(!0).describe(`Allow users to toggle row height/density`),addRecordForm:t.z.boolean().default(!1).describe(`Add records through a form instead of inline`),editInline:t.z.boolean().default(!1).describe(`Allow users to edit records inline — click a cell to edit it with the field's type-aware widget (the same control the form uses). Off by default: the list is read-only unless the author opts in.`),buttons:t.z.array(t.z.string()).optional().describe(`Custom action button IDs to show in the toolbar`)}).describe(`User action toggles for the view toolbar`)),bn=n(()=>t.z.object({showDescription:t.z.boolean().default(!0).describe(`Show the view description text`),allowedVisualizations:t.z.array(vn).optional().describe(`Whitelist of visualization types users can switch between (e.g. ["grid", "gallery", "kanban"])`)}).describe(`Appearance and visualization configuration`)),xn=n(()=>t.z.object({name:I.describe(`Tab identifier (snake_case)`),label:B.optional().describe(`Display label`),icon:t.z.string().optional().describe(`Tab icon name`),view:t.z.string().optional().describe(`Referenced list view name from listViews`),filter:t.z.array(rn).optional().describe(`Tab-specific filter criteria`),order:t.z.number().int().min(0).optional().describe(`Tab display order`),pinned:t.z.boolean().default(!1).describe(`Pin tab (cannot be removed by users)`),isDefault:t.z.boolean().default(!1).describe(`Set as the default active tab`),visible:t.z.boolean().default(!0).describe(`Tab visibility`)}).describe(`Tab configuration for multi-tab view interface`)),Sn=n(()=>t.z.object({field:t.z.string().describe(`Field name on the source object (must exist — checked by reference diagnostics)`),label:B.optional().describe(`Display label override (defaults to the field label)`),type:t.z.enum([`select`,`multi-select`,`boolean`,`date-range`,`text`]).optional().describe(`Filter control type. Omit to infer from the field definition`),options:t.z.array(t.z.object({value:t.z.union([t.z.string(),t.z.number(),t.z.boolean()]).describe(`Option value`),label:B.describe(`Option label`),color:t.z.string().optional().describe(`Option color token/hex`)})).optional().describe(`Static options. Omit to derive from the field definition (select options / lookup records)`),showCount:t.z.boolean().optional().describe(`Show per-option record counts`),defaultValues:t.z.array(t.z.union([t.z.string(),t.z.number(),t.z.boolean()])).optional().describe(`Pre-selected values when the view loads`)}).describe(`Quick-filter field configuration`)),Cn=n(()=>t.z.object({element:t.z.enum([`dropdown`,`tabs`,`toggle`]).default(`dropdown`).describe(`Filter control style: "dropdown" (per-field value selectors) or "tabs" (named presets). "toggle" is deprecated.`),fields:t.z.array(Sn).optional().describe(`Fields exposed as quick filters (dropdown/toggle elements)`),tabs:t.z.array(xn).optional().describe(`Named filter presets rendered as tabs (tabs element). Reuses ViewTabSchema`),showAllRecords:t.z.boolean().optional().describe(`Show an "All records" tab before the presets (tabs element)`)}).describe(`End-user quick-filter configuration (Airtable "User filters" parity)`)),wn=n(()=>t.z.object({enabled:t.z.boolean().default(!0).describe(`Show the add record entry point`),position:t.z.enum([`top`,`bottom`,`both`]).default(`bottom`).describe(`Position of the add record button`),mode:t.z.enum([`inline`,`form`,`modal`]).default(`inline`).describe(`How to add a new record`),formView:t.z.string().optional().describe(`Named form view to use when mode is "form" or "modal"`)}).describe(`Add record entry point configuration`)),Tn=n(()=>t.z.object({groupByField:t.z.string().describe(`Field to group columns by (usually status/select)`),summarizeField:t.z.string().optional().describe(`Field to sum at top of column (e.g. amount)`),columns:t.z.array(t.z.string()).describe(`Fields to show on cards`)})),En=n(()=>t.z.object({chartType:Ht.extract([`bar`,`line`,`pie`,`area`,`scatter`]).default(`bar`).describe(`Chart visualisation type`),dataset:I.describe(`Dataset name to bind (ADR-0021)`),dimensions:t.z.array(t.z.string()).optional().describe(`Dimension names — X/group/split`),values:t.z.array(t.z.string()).min(1).describe(`Measure names — Y (at least one)`)}).describe(`List chart view configuration`)),Dn=n(()=>t.z.object({startDateField:t.z.string().describe(`Field providing the event start date/time`),endDateField:t.z.string().optional().describe(`Field providing the event end date/time (defaults to a single-day event)`),titleField:t.z.string().describe(`Field displayed as the event title`),colorField:t.z.string().optional().describe(`Field whose value determines the event color`)})),On=n(()=>t.z.object({field:t.z.string().describe(`Record field / dot-path the dimension filters on`),label:t.z.string().optional().describe(`Trigger label (falls back to the field label)`),options:t.z.array(t.z.union([t.z.string(),t.z.object({value:t.z.union([t.z.string(),t.z.number()]),label:t.z.string().optional()})])).optional().describe(`Explicit option override for fixed enums`)})),kn=n(()=>t.z.object({startDateField:t.z.string().describe(`Field providing the task start date`),endDateField:t.z.string().describe(`Field providing the task end date`),titleField:t.z.string().describe(`Field displayed as the task title`),progressField:t.z.string().optional().describe(`Field providing the task completion percentage`),dependenciesField:t.z.string().optional().describe(`Field listing the task's predecessor (dependency) record ids`),colorField:t.z.string().optional().describe(`Field that drives the bar color`),parentField:t.z.string().optional().describe(`Field holding the parent task id (builds the summary → step tree)`),typeField:t.z.string().optional().describe(`Field whose value maps to task/summary/milestone`),baselineStartField:t.z.string().optional().describe(`Baseline (planned) start field`),baselineEndField:t.z.string().optional().describe(`Baseline (planned) end field`),groupByField:t.z.string().optional().describe(`Field to group leaf tasks by (synthesized summary rows)`),resourceView:t.z.boolean().optional().describe(`Render a per-resource workload histogram instead of the timeline`),assigneeField:t.z.string().optional().describe(`Resource field to bucket load by (resource view)`),effortField:t.z.string().optional().describe(`Per-task load units (resource view; default 1)`),capacity:t.z.number().optional().describe(`Per-resource capacity ceiling; loads above this flag overload`),tooltipFields:t.z.array(t.z.union([t.z.string(),t.z.object({field:t.z.string(),label:t.z.string().optional()})])).optional().describe(`Fields to surface in the hover tooltip, in display order`),quickFilters:t.z.array(On).optional().describe(`Multi-select filter dropdowns rendered above the chart`),autoZoomToFilter:t.z.boolean().optional().describe(`When true (default), filtering zooms the range to the filtered tasks`)}).passthrough()),An=n(()=>t.z.object({parentField:t.z.string().optional().describe(`Single-parent pointer field (auto-detected from the object schema when omitted)`),labelField:t.z.string().optional().describe(`Field rendered indented in the first column (defaults to "name")`),fields:t.z.array(t.z.string()).optional().describe(`Additional fields rendered as flat columns alongside the label`),defaultExpandedDepth:t.z.number().int().min(0).optional().describe(`Initial expansion depth (0 = roots only; omit = expand all)`)}).passthrough()),jn=n(()=>t.z.enum([`page`,`drawer`,`modal`,`split`,`popover`,`new_window`,`none`])),Mn=n(()=>t.z.object({mode:jn.default(`page`),view:t.z.string().optional().describe(`Name of the form view to use for details (e.g. "summary_view", "edit_form")`),preventNavigation:t.z.boolean().default(!1).describe(`Disable standard navigation entirely`),openNewTab:t.z.boolean().default(!1).describe(`Force open in new tab (applies to page mode)`),size:t.z.enum([`auto`,`sm`,`md`,`lg`,`xl`,`full`]).default(`auto`).describe("[#2578] Overlay size bucket for drawer/modal detail: 'auto' (default — renderer derives from field count + viewport; AI writes nothing) or a coarse override sm/md/lg/xl/full. Prefer this over the pixel `width`; page mode ignores it."),width:t.z.union([t.z.string(),t.z.number()]).optional().describe('[DEPRECATED → size] Pixel/percent width of the drawer/modal (e.g. "600px"). A pixel width cannot be chosen at authoring time without knowing the client viewport — use the `size` bucket.')})),Nn=n(()=>t.z.object({name:I.optional().describe(`Internal view name (lowercase snake_case)`),label:B.optional(),type:t.z.enum([`grid`,`kanban`,`gallery`,`calendar`,`timeline`,`gantt`,`map`,`chart`,`tree`]).default(`grid`),data:$t.optional().describe(`Data source configuration (defaults to "object" provider)`),columns:t.z.union([t.z.array(t.z.string()),t.z.array(cn)]).describe(`Fields to display as columns`),filter:t.z.array(rn).optional().describe(`Filter criteria (JSON Rules)`),sort:t.z.union([t.z.string(),t.z.array(t.z.object({field:t.z.string(),order:t.z.enum([`asc`,`desc`])}))]).optional(),searchableFields:t.z.array(t.z.string()).optional().describe(`Fields enabled for search`),filterableFields:t.z.array(t.z.string()).optional().describe(`Legacy shorthand for userFilters.fields — bare field names enabled for end-user filtering. Prefer userFilters`),userFilters:Cn.optional().describe(`End-user quick-filter bar: dropdown/toggle fields or tab presets. Omit to let the renderer derive filters from select/boolean fields`),resizable:t.z.boolean().optional().describe(`Enable column resizing`),striped:t.z.boolean().optional().describe(`Striped row styling`),bordered:t.z.boolean().optional().describe(`Show borders`),compactToolbar:t.z.boolean().optional().describe(`Collapse Group/Color/Density/Hide-fields into a single View settings popover`),selection:ln.optional().describe(`Row selection configuration`),navigation:Mn.optional().describe(`Configuration for item click navigation (page, drawer, modal, etc.)`),pagination:un.optional().describe(`Pagination configuration`),kanban:Tn.optional().describe(`Kanban-board configuration — applies when the view renders as a kanban layout`),calendar:Dn.optional().describe(`Calendar configuration — applies when the view renders as a calendar layout`),gantt:kn.optional().describe(`Gantt-timeline configuration — applies when the view renders as a gantt layout`),gallery:mn.optional(),timeline:hn.optional(),chart:En.optional(),tree:An.optional().describe(`Tree/hierarchy configuration — applies when the view renders as a tree layout`),description:B.optional().describe(`View description for documentation/tooltips`),sharing:gn.optional().describe(`View sharing and access configuration`),rowHeight:dn.optional().describe(`Row height / density setting`),grouping:pn.optional().describe(`Group records by one or more fields`),rowColor:_n.optional().describe(`Color rows based on field value`),hiddenFields:t.z.array(t.z.string()).optional().describe(`Fields to hide in this specific view`),fieldOrder:t.z.array(t.z.string()).optional().describe(`Explicit field display order for this view`),rowActions:t.z.array(t.z.string()).optional().describe(`Actions available for individual row items`),bulkActions:t.z.array(t.z.string()).optional().describe(`Actions available when multiple rows are selected`),bulkActionDefs:t.z.array(t.z.record(t.z.string(),t.z.any())).optional().describe(`Rich bulk action definitions (schema-driven, executed via BulkActionDialog)`),virtualScroll:t.z.boolean().optional().describe(`Enable virtual scrolling for large datasets`),conditionalFormatting:t.z.array(t.z.object({condition:L.describe(`Predicate (CEL) to evaluate.`),style:t.z.record(t.z.string(),t.z.string()).describe(`CSS styles to apply when condition is true`)})).optional().describe(`Conditional formatting rules for list rows`),inlineEdit:t.z.boolean().optional().describe(`Allow inline editing of records directly in the list view`),exportOptions:t.z.array(t.z.enum([`csv`,`xlsx`,`pdf`,`json`])).optional().describe(`Available export format options`),userActions:yn.optional().describe(`User action toggles for the view toolbar`),appearance:bn.optional().describe(`Appearance and visualization configuration`),tabs:t.z.array(xn).optional().describe(`Tab definitions for multi-tab view interface`),addRecord:wn.optional().describe(`Add record entry point configuration`),showRecordCount:t.z.boolean().optional().describe(`Show record count at the bottom of the list`),allowPrinting:t.z.boolean().optional().describe(`Allow users to print the view`),emptyState:t.z.object({title:B.optional(),message:B.optional(),icon:t.z.string().optional()}).optional().describe(`Empty state configuration when no records found`),aria:st.optional().describe(`ARIA accessibility attributes for the list view`),responsive:w("`view.responsive` was removed in @objectstack/spec 17.0.0 (#3896 audit close-out) — no renderer ever read it; the grid is responsive by its own layout rules. Delete the key."),performance:w("`view.performance` was removed in @objectstack/spec 17.0.0 (#3896 audit close-out) — no renderer or runtime read it; list-view performance tuning was never implemented. Delete the key.")})),Pn=n(()=>t.z.object({field:t.z.string().describe(`Field name (snake_case)`),type:We.optional().describe(`Field type (auto-infers widget if omitted)`),options:t.z.array(Ge).optional().describe(`Options for select/multiselect/radio/checkboxes fields`),reference:t.z.string().optional().describe(`Target object name for lookup/master_detail fields`),maxLength:t.z.number().optional().describe(`Maximum character length (for text/textarea/email/url/phone)`),minLength:t.z.number().optional().describe(`Minimum character length`),min:t.z.number().optional().describe(`Minimum value (for number/currency/percent/slider)`),max:t.z.number().optional().describe(`Maximum value`),precision:t.z.number().optional().describe(`Total digits (for number/currency)`),scale:t.z.number().optional().describe(`Decimal places`),multiple:t.z.boolean().optional().describe(`Allow multiple values (for select/lookup/file/image)`),label:B.optional().describe(`Display label override`),placeholder:B.optional().describe(`Placeholder text`),helpText:B.optional().describe(`Help/hint text`),readonly:t.z.boolean().optional().describe(`Read-only override`),immutable:t.z.boolean().optional().describe(`Editable on create, locked once the record exists (e.g. machine names).`),required:t.z.boolean().optional().describe(`Required override`),hidden:t.z.boolean().optional().describe(`Hidden override`),colSpan:t.z.number().int().min(1).max(4).optional().describe("[legacy — prefer `span`] Absolute column span (1-4). Fragile when the column count is derived per surface (mobile 1 / modal 2 / page 3-4): a fixed span only lines up at the width the author imagined. The renderer clamps it to the current column count. Prefer `span`."),span:t.z.enum([`auto`,`full`]).default(`auto`).describe("Relative field width. 'auto' (default — omit it): the renderer sizes the field from its widget type × the current column count (wide widgets like textarea/richtext/json/file/subform take the whole row). 'full': whole row at any column count. Prefer this over the absolute `colSpan`."),widget:t.z.string().optional().describe(`Custom widget/component name (overrides type-based inference)`),language:t.z.string().optional().describe(`Code editor language (for type=code)`),keyField:t.z.object({field:t.z.string().default(`name`).describe(`Property name that holds the key inside each item (defaults to "name")`),label:B.optional().describe(`Display label for the key column`),placeholder:B.optional().describe(`Placeholder when entering a new key`),helpText:B.optional().describe(`Help text under the key input`),regex:t.z.string().optional().describe(`JS regex source string the key must match (no flags)`),immutable:t.z.boolean().default(!0).describe(`If true, the key is read-only after creation`)}).optional().describe(`Key column config for record-typed fields`),dependsOn:t.z.string().optional().describe(`Parent field name for cascading`),visibleWhen:L.optional().describe("Visibility predicate (CEL) — field shown only when TRUE. Root: `record`+`current_user` (runtime forms) or `data` (metadata forms). e.g. P`record.priority == 'urgent'`"),visibleOn:L.optional().describe("[DEPRECATED → `visibleWhen`] Visibility predicate (CEL). Normalized to `visibleWhen` at parse."),disclosure:t.z.enum([`inline`,`popover`]).optional().describe(`Composite rendering: inline bordered box (default) or a summary line + gear popover (progressive disclosure).`)},{error:Vt})),Fn=n(()=>Pn.extend({fields:t.z.array(t.z.lazy(()=>Fn)).optional().describe(`Sub-fields for composite/repeater/record types`)}).strict().transform(zt)),In=n(()=>t.z.object({name:t.z.string().optional().describe(`Stable section identifier for i18n lookup (snake_case)`),label:B.optional(),description:t.z.string().optional().describe(`Optional description rendered under the section header.`),collapsible:t.z.boolean().default(!1),collapsed:t.z.boolean().default(!1),visibleWhen:L.optional().describe("Visibility predicate (CEL) — section shown only when TRUE. Root: `record`+`current_user` (runtime forms) or `data` (metadata forms)."),visibleOn:L.optional().describe("[DEPRECATED → `visibleWhen`] Visibility predicate (CEL). Hides the whole section when false. Normalized to `visibleWhen` at parse."),columns:t.z.union([t.z.enum([`1`,`2`,`3`,`4`]),t.z.literal(1),t.z.literal(2),t.z.literal(3),t.z.literal(4)]).default(1).transform(e=>typeof e==`string`?parseInt(e):e),pane:t.z.enum([`primary`,`secondary`]).optional().describe(`Split pane this section renders in (split forms only; a parse error elsewhere). Omitted → first section 'primary', others 'secondary'.`),fields:t.z.array(t.z.union([t.z.string(),Fn]))},{error:Vt}).strict().transform(zt)),Ln=n(()=>t.z.object({show:t.z.boolean().optional().describe(`Whether the button is rendered (renderer default applies when omitted)`),label:B.optional().describe(`Button label (i18n-capable; renderer default when omitted)`)}).strict()),W=n(()=>t.z.object({type:t.z.enum([`simple`,`tabbed`,`wizard`,`split`,`drawer`,`modal`]).default(`simple`),layout:t.z.enum([`vertical`,`horizontal`,`inline`,`grid`]).optional().describe(`Field layout direction`),columns:t.z.number().int().min(1).optional().describe(`Number of columns for the form body`),title:t.z.string().optional().describe(`Form title`),description:t.z.string().optional().describe(`Form description`),defaultTab:t.z.string().optional().describe(`Initially active tab (tabbed forms)`),tabPosition:t.z.enum([`top`,`bottom`,`left`,`right`]).optional().describe(`Tab strip position (tabbed forms)`),allowSkip:t.z.boolean().optional().describe(`Allow skipping steps (wizard forms)`),showStepIndicator:t.z.boolean().optional().describe(`Show the step indicator (wizard forms)`),splitDirection:t.z.enum([`horizontal`,`vertical`]).optional().describe(`Split orientation (split forms)`),splitSize:t.z.number().optional().describe(`Primary split panel size, % (split forms)`),splitResizable:t.z.boolean().optional().describe(`Whether the split is resizable (split forms)`),drawerSide:t.z.enum([`top`,`bottom`,`left`,`right`]).optional().describe(`Drawer side (drawer forms)`),drawerWidth:t.z.string().optional().describe(`[DEPRECATED → size buckets] Drawer width, e.g. "480px". A pixel width cannot be chosen without knowing the client viewport — the renderer derives it.`),modalSize:t.z.enum([`sm`,`default`,`lg`,`xl`,`full`]).optional().describe(`Modal size (modal forms)`),data:$t.optional().describe(`Data source configuration (defaults to "object" provider)`),sections:t.z.array(In).optional(),groups:t.z.array(In).optional(),subforms:t.z.array(t.z.object({childObject:t.z.string().describe(`Child object whose records are entered inline`),relationshipField:t.z.string().optional().describe(`FK on the child pointing back to the parent (auto-detected when omitted)`),columns:t.z.array(t.z.any()).optional().describe(`Editable grid columns (derived from the child object when omitted)`),amountField:t.z.string().optional().describe(`Numeric child column summed for the running total`),totalField:t.z.string().optional().describe(`Parent field to receive the rolled-up sum`),title:t.z.string().optional().describe(`Section title`),addLabel:t.z.string().optional().describe(`Add-row button label`),minRows:t.z.number().optional(),maxRows:t.z.number().optional()})).optional().describe(`Inline master-detail child collections`),defaultSort:w("`form.defaultSort` was removed in @objectstack/spec 17.0.0 (#3896 audit close-out) — nothing read it: a related list inside a form sorts by its own list view's `sort`. Delete the key and set the sort on the related list view instead."),sharing:Yt.optional().describe(`Public sharing configuration for this form`),submitBehavior:t.z.union([t.z.object({kind:t.z.literal(`thank-you`),title:t.z.string().optional(),message:t.z.string().optional()}),t.z.object({kind:t.z.literal(`redirect`),url:t.z.string(),delayMs:t.z.number().int().min(0).optional()}),t.z.object({kind:t.z.literal(`continue`)}),t.z.object({kind:t.z.literal(`next-record`)})]).optional().describe(`Post-submit behavior`),buttons:t.z.object({submit:Ln.optional().describe(`Submit button`),cancel:Ln.optional().describe(`Cancel button`),reset:Ln.optional().describe(`Reset button`)}).strict().optional().describe(`Form action-button visibility & labels; folded onto the flat renderer props by ObjectUI ObjectForm (framework#1894 / #2998).`),defaults:t.z.record(t.z.string(),t.z.unknown()).optional().describe(`Initial field values for create-mode forms (folded into ObjectUI ObjectForm initial values; framework#1894 / #2998).`),aria:w("`form.aria` was removed in @objectstack/spec 17.0.0 (#3896 audit close-out) — no form renderer ever applied it, so declared ARIA attributes silently did not reach the DOM. Delete the key. The form renderer emits its own semantic markup; report gaps as renderer issues rather than per-view attribute overrides.")}).superRefine((e,t)=>{if(e.type!==`split`)for(let[n,r]of[[`sections`,e.sections],[`groups`,e.groups]])r?.forEach((r,i)=>{r?.pane!=null&&t.addIssue({code:`custom`,path:[n,i,`pane`],message:`\`pane\` places a section in a split pane and is only valid on \`type: 'split'\` form views (this form is '${e.type}'). Remove the key or change the form type.`})})})),Rn=n(()=>Cn.omit({tabs:!0,showAllRecords:!0}).extend({element:t.z.enum([`dropdown`,`toggle`]).default(`dropdown`).describe('Filter control style on object views: "dropdown" (per-field value chips). "toggle" is deprecated. "tabs" is page-only — use `listViews` for named presets.')})),zn=n(()=>Nn.omit({userFilters:!0}).extend({userFilters:Rn.optional()})),Bn=n(()=>t.z.object({list:zn.optional(),form:W.optional(),listViews:t.z.record(t.z.string(),zn).optional().describe(`Additional named list views (views mode — dropdown userFilters allowed, no tabs; ADR-0047)`),formViews:t.z.record(t.z.string(),W).optional().describe(`Additional named form views`),protection:U.optional().describe(`Package author protection block — lock policy for this view.`),...H})),Vn=t.z.string().regex(/^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)+$/,`View item name must be a dotted snake_case qualified name, e.g. "crm_lead.pipeline".`).describe("Globally-unique view id, `<object>.<viewKey>`."),Hn=t.z.enum([`package`,`shared`,`personal`]).describe(`View identity layer: package | shared | personal.`),Un=t.z.enum([`list`,`form`]).describe("Whether `config` is a ListView (list family) or a FormView.");function Wn(){return{name:Vn,object:t.z.string().describe(`Bound object name — the foreign key used to aggregate views.`),label:B.optional().describe(`Display label (supports i18n).`),isDefault:t.z.boolean().optional().describe(`Whether this is the object's default view in the switcher.`),order:t.z.number().int().optional().describe(`Sort order within the object's view switcher / left rail.`),scope:Hn.optional().describe("Identity layer (defaults to `package` for source-loaded views)."),owner:t.z.string().optional().describe("Owner user id — set when `scope` is `personal`."),hidden:t.z.boolean().optional().describe(`Hidden from the switcher (per-user / per-org declutter).`),protection:U.optional().describe(`Package author protection block — lock policy for this view.`),...H}}var Gn=n(()=>t.z.discriminatedUnion(`viewKind`,[t.z.object({viewKind:t.z.literal(`list`),config:Nn.describe(`List-family view configuration.`),...Wn()}),t.z.object({viewKind:t.z.literal(`form`),config:W.describe(`Form view configuration.`),...Wn()})]));function Kn(){return{name:t.z.string().optional().describe(`Save name / qualified view id (stamped by the write path).`),object:t.z.string().optional().describe(`Bound object name (inherited from the shadowed entry — #2555).`),viewKind:Un.optional().describe(`View family (inherited from the shadowed entry — #2555).`),label:B.optional().describe(`Display label (inherited from the shadowed entry — #2555).`),isDefault:t.z.boolean().optional(),order:t.z.number().int().optional(),scope:Hn.optional(),owner:t.z.string().optional(),hidden:t.z.boolean().optional(),protection:U.optional(),...H,config:t.z.undefined().optional(),list:t.z.undefined().optional(),form:t.z.undefined().optional(),listViews:t.z.undefined().optional(),formViews:t.z.undefined().optional()}}function qn(e){if(!e||typeof e!=`object`)return!1;let t=e;return!!(t.list||t.form||t.listViews&&typeof t.listViews==`object`&&Object.keys(t.listViews).length>0||t.formViews&&typeof t.formViews==`object`&&Object.keys(t.formViews).length>0)}n(()=>t.z.union([Gn,Bn.refine(qn,{message:"A view container must define at least one of `list`, `form`, `listViews`, or `formViews`."}),Nn.extend(Kn()),W.extend(Kn())]));function Jn(e){let{schemaId:t,...n}=e;return W.parse({...n,data:{provider:`schema`,schemaId:t}})}var Yn=t.z.enum([`get`,`list`,`create`,`update`,`delete`,`bulk`]),G=[`upsert`,`aggregate`,`history`,`search`,`restore`,`purge`,`import`,`export`],Xn={upsert:"declare ['create','update'] — `upsert` derives from create ∧ update",aggregate:"declare ['list'] — `aggregate` derives from list",history:"declare ['get'] with `enable.trackHistory: true` — `history` derives from get ∧ trackHistory",search:"declare ['list'] (with `searchable` not false) — `search` derives from list ∧ searchable",restore:"delete the value — `restore` never derives (`enable.trash` retired, #2377); it returns only with a real recycle bin (#1893)",purge:"delete the value — `purge` never derives (`enable.trash` retired, #2377)",import:"declare ['create'] and/or ['update'] — `import` derives from create ∨ update (writeMode-precise at the gate)",export:"declare ['list'] — `export` derives from list"},K=[`get`,`list`,`create`,`update`,`delete`,`upsert`,`bulk`,`aggregate`,`history`,`search`,`restore`,`purge`,`import`,`export`],Zn=t.z.enum(K),Qn=new Set(G),$n=new Set;function er(e,t){if(!Array.isArray(e))return e;let n=[...new Set(e.filter(e=>typeof e==`string`&&Qn.has(e)))];if(n.length===0)return e;let r=e.filter(e=>!(typeof e==`string`&&Qn.has(e))),i=`${[...n].sort().join(`,`)}${r.length===0?`|deny-all`:``}`;return $n.has(i)||($n.add(i),(t?.warn??(e=>console.warn(e)))(`[spec] enable.apiMethods declares retired legacy value(s) [${n.join(`, `)}] \u2014 the ApiMethod enum is the six primitives get/list/create/update/delete/bulk (#3543). Legacy values are stripped at parse; their semantics are DERIVED from the primitives:
|
|
4
|
+
`+n.map(e=>` \u2022 \`${e}\`: ${Xn[e]}`).join(`
|
|
5
|
+
`)+(r.length===0?"\n ⚠ After stripping, this whitelist is EMPTY — `[]` means DENY-ALL (fully closed API). Declare the underlying primitives if the object should stay reachable.":``)+`
|
|
6
|
+
Codemod: node scripts/codemod/apimethods-legacy-to-primitives.mjs`)),r}var tr={trash:"`enable.trash` was removed from @objectstack/spec in the 16.x line (#2377, ADR-0049) — it never had a runtime consumer: every delete has always been a hard delete, and a default-true flag promising a recycle bin was a false affordance (authors wrote `trash: false` believing they were opting out of a soft-delete that never ran). Delete the key. For recoverability use per-field `trackHistory` (audit trail) or a `lifecycle` policy; a real recycle bin, if built, returns as a live enforced flag (#1893 prune-or-build).",mru:"`enable.mru` was removed from @objectstack/spec in the 16.x line (#2377, ADR-0049) — Most-Recently-Used tracking was never implemented; no reader existed, so the flag changed nothing. Delete the key. If MRU tracking is built it returns as a live enforced flag (#1893 prune-or-build)."},nr=t.z.object({trackHistory:t.z.boolean().default(!1).describe(`Show the record History tab (audit-trail UI). Pair with per-field trackHistory to pick which field diffs are summarized; audit capture itself is always on for compliance`),searchable:t.z.boolean().default(!0).describe(`Index records for global search`),apiEnabled:t.z.boolean().default(!0).describe(`Expose object via automatic APIs`),apiMethods:t.z.preprocess(e=>er(e),t.z.array(Yn)).optional().describe(`Whitelist of allowed API operations (six primitives; undefined = all, [] = none)`),files:t.z.boolean().default(!1).describe(`Generic record Attachments panel (sys_attachment). Opt-in: true surfaces the panel and permits attachments targeting this object; otherwise creation is rejected. Field.file/Field.image are independent`),feeds:t.z.boolean().default(!0).describe(`Record comments/collaboration feed. Default on; explicit false hides the feed UI and rejects new comments for this object`),activities:t.z.boolean().default(!0).describe(`Record activity timeline (sys_activity mirror of CRUD). Default on; explicit false stops mirroring and hides the timeline`),clone:t.z.boolean().default(!0).describe(`Allow record deep cloning`)},{error:e=>{if(e.code!==`unrecognized_keys`)return;let t=e.keys??[],n=t.map(e=>tr[e]??`\`${e}\` is not an \`enable\` capability flag.`);return`Unrecognized key(s) on \`enable\`: ${t.map(e=>`\`${e}\``).join(`, `)}.
|
|
7
|
+
`+n.map(e=>` \u2022 ${e}`).join(`
|
|
8
|
+
`)}}).strict(),rr=n(()=>t.z.object({name:t.z.string().optional().describe(`Index name (auto-generated if not provided)`),fields:t.z.array(t.z.string()).describe(`Fields included in the index`),type:t.z.enum([`btree`,`hash`,`gin`,`gist`,`fulltext`]).optional().default(`btree`).describe(`Index algorithm type`),unique:Xe.optional().default(!1).describe("Whether the index enforces uniqueness. Materialized over exactly `fields` — no tenant column is injected; list the tenant column explicitly for a per-tenant index. 'global' is a synonym of true, for symmetry with field-level `unique`"),partial:t.z.string().optional().describe(`Partial index condition (SQL WHERE clause for conditional indexes)`)})),ir={strategy:"`tenancy.strategy` was removed from @objectstack/spec after v15.0 (#2763) — it never had a consumer. The platform has exactly two tenancy modes and neither is object-level config: database-per-tenant isolation is an environment/deployment choice (each environment carries its own database URL), and row-level isolation is `tenancy.enabled` + `tenancy.tenantField`. Delete the key.",crossTenantAccess:"`tenancy.crossTenantAccess` was removed from @objectstack/spec after v15.0 (#2763) — it never had a consumer; setting it granted nothing. Cross-tenant visibility is governed by sharing rules / OWD (ADR-0056), `externalSharingModel` (ADR-0090 D11), and the object access posture. Delete the key."},ar=e=>{if(e.code!==`unrecognized_keys`)return;let t=e.keys??[],n=t.map(e=>ir[e]??`\`${e}\` is not a \`tenancy\` key.`);return`Unrecognized key(s) on \`tenancy\`: ${t.map(e=>`\`${e}\``).join(`, `)}. The two supported tenancy modes are: database-per-tenant = environment-level deployment (no object config); row-level isolation = \`tenancy.enabled\` + \`tenancy.tenantField\`.
|
|
9
|
+
`+n.map(e=>` \u2022 ${e}`).join(`
|
|
10
|
+
`)},or=n(()=>t.z.object({enabled:t.z.boolean().describe(`Enable multi-tenancy for this object`),tenantField:t.z.string().default(`tenant_id`).describe(`Field name for tenant identifier`)},{error:ar}).strict());function sr(e){return e?.tenancy?.enabled===!1}var cr=n(()=>t.z.object({default:t.z.enum([`public`,`private`]).default(`public`).describe(`Default exposure posture: public (covered by wildcard grants) | private (needs explicit grant; exempt from wildcard RLS).`)})),lr=t.z.object({read:t.z.array(t.z.string()).optional().describe(`Capabilities required to read (find/findOne/count/aggregate).`),create:t.z.array(t.z.string()).optional().describe(`Capabilities required to create (insert).`),update:t.z.array(t.z.string()).optional().describe(`Capabilities required to update (update/transfer/restore).`),delete:t.z.array(t.z.string()).optional().describe(`Capabilities required to delete (delete/purge).`)}).strict(),ur=t.z.union([t.z.array(t.z.string()),lr]),dr=t.z.enum([`record`,`audit`,`telemetry`,`transient`,`event`]),fr=/^\d+(h|d|w|y)$/,pr=e=>t.z.string().regex(fr,`${e} must be a duration literal like '6h', '14d', '12w' or '7y'`),mr=n(()=>t.z.object({class:dr.describe(`Persistence contract: record (business truth, permanent) | audit (compliance ledger) | telemetry (high-freq log) | transient (ephemeral state) | event (bus messages).`),retention:t.z.object({maxAge:pr(`retention.maxAge`).describe("Rows older than this (by created_at) are deleted by the Reaper — or archived first when `archive` is set."),onlyWhen:t.z.record(t.z.string(),t.z.union([t.z.string(),t.z.number(),t.z.boolean(),t.z.object({$in:t.z.array(t.z.union([t.z.string(),t.z.number()])).min(1)}).strict()])).optional().describe(`Row filter the retention applies to — per-field equality or {$in: [...]} (e.g. { status: { $in: ["completed", "failed"] } }). Rows OUTSIDE the filter are retained regardless of age: for tables that interleave live workflow state with terminal history (sys_automation_run). Incompatible with rotation storage and archive, which act on whole shards / age alone.`)}).optional().describe(`Age-based retention window enforced by the LifecycleService Reaper.`),ttl:t.z.object({field:t.z.string().describe(`Timestamp field the TTL is measured from (e.g. created_at, expires_at).`),expireAfter:pr(`ttl.expireAfter`).describe("Rows expire this long after `field` and are deleted by the Reaper.")}).optional().describe(`Per-row TTL auto-expiry (transient/event classes).`),storage:t.z.object({strategy:t.z.literal(`rotation`).describe(`Time-shard the table; rotate by DROPping the oldest shard (O(1) reclaim).`),shards:t.z.number().int().min(2).describe(`Number of shards retained; total window = shards × unit.`),unit:t.z.enum([`day`,`week`,`month`]).describe(`Time width of one shard.`)}).optional().describe(`Physical storage strategy for high-frequency telemetry (LifecycleService Rotator).`),archive:t.z.object({after:pr(`archive.after`).describe(`Rows older than this are copied to the archive datasource before hot deletion.`),to:t.z.string().describe(`Target datasource name for cold storage. When it is not registered, the Archiver skips (audit rows are then retained, never dropped unarchived).`),keep:pr(`archive.keep`).optional().describe(`How long archived rows are kept in cold storage (undefined = forever).`)}).optional().describe(`Cold-store archival (LifecycleService Archiver) — audit-class hot→cold hand-off.`),reclaim:t.z.boolean().optional().describe(`Run driver space reclamation (SQLite incremental_vacuum) after sweeping this object. Default true for non-record classes.`)}).superRefine((e,n)=>{e.class!==`record`&&!e.retention&&!e.ttl&&!e.storage&&n.addIssue({code:t.z.ZodIssueCode.custom,message:`lifecycle.class '${e.class}' requires at least one bounding policy: retention, ttl, or storage (rotation) \u2014 ADR-0057 \xA73.5`}),e.class===`record`&&(e.retention||e.ttl||e.storage||e.archive)&&n.addIssue({code:t.z.ZodIssueCode.custom,message:`lifecycle.class 'record' is permanent business truth — retention/ttl/storage/archive policies are not allowed on it (ADR-0057 §3.1)`}),e.archive&&e.retention&&e.archive.after!==e.retention.maxAge&&n.addIssue({code:t.z.ZodIssueCode.custom,message:`lifecycle.archive.after ('${e.archive.after}') must equal retention.maxAge ('${e.retention.maxAge}') \u2014 the hot window ends where the archive begins`}),e.retention?.onlyWhen&&e.storage?.strategy===`rotation`&&n.addIssue({code:t.z.ZodIssueCode.custom,message:`lifecycle.retention.onlyWhen cannot be combined with rotation storage — the Rotator DROPs whole shards and would destroy rows the filter protects`}),e.retention?.onlyWhen&&e.archive&&n.addIssue({code:t.z.ZodIssueCode.custom,message:`lifecycle.retention.onlyWhen cannot be combined with archive — the Archiver moves rows by age alone and would archive rows the filter protects`})})),hr=n(()=>t.z.object({key:t.z.string().regex(/^[a-z_][a-z0-9_]*$/,{message:`Field group key must be lowercase snake_case (e.g., "contact_info", "billing", "system")`}).describe(`Group machine key (snake_case). Referenced by Field.group.`),label:t.z.string().describe(`Group display label`),icon:t.z.string().optional().describe(`Icon name (Lucide/Material) for the group header`),description:t.z.string().optional().describe(`Optional description shown under the group header`),collapse:t.z.enum([`none`,`expanded`,`collapsed`]).optional().default(`none`).describe(`[ADR-0085] Section collapse behaviour: 'none' (always open, no toggle), 'expanded' (collapsible, starts open), 'collapsed' (collapsible, starts closed).`),defaultExpanded:t.z.boolean().optional().describe(`[DEPRECATED → collapse] true → 'expanded', false → 'collapsed'.`),collapsible:t.z.boolean().optional().describe("[DEPRECATED → collapse] Boolean pair with `collapsed`; use the `collapse` enum."),collapsed:t.z.boolean().optional().describe("[DEPRECATED → collapse] Boolean pair with `collapsible`; use the `collapse` enum.")})),gr=t.z.object({remoteName:t.z.string().optional().describe(`Remote table/view name. Defaults to object.name.`),remoteSchema:t.z.string().optional().describe(`Remote schema/database qualifier.`),writable:t.z.boolean().default(!1).describe(`Per-object write opt-in (also requires datasource.external.allowWrites).`),columnMap:t.z.record(t.z.string(),t.z.string()).optional().describe(`Remote column name → local field name.`),introspectedAt:t.z.string().datetime().optional().describe("Set by `os datasource introspect`; informational."),ignoreColumns:t.z.array(t.z.string()).optional().describe(`Remote columns to skip during validation (dev convenience).`)}).describe(`External datasource binding (ADR-0015)`),_r=t.z.object({enabled:t.z.boolean().optional().describe(`Object-level on/off for the generic affordance; same meaning as the bare boolean form. Omitted → managedBy bucket default.`),visibleWhen:L.optional().describe(`Per-record CEL predicate; false → hide the row button for that record. Fail-closed.`),disabledWhen:L.optional().describe(`Per-record CEL predicate; true → render the row button disabled for that record. Fail-soft.`)}).strict().describe(`Boolean-or-predicates override for a built-in row CRUD affordance.`),q=t.z.object({name:t.z.string().regex(/^[a-z_][a-z0-9_]*$/).describe(`Machine unique key (snake_case). Immutable.`),label:t.z.string().optional().describe(`Human readable singular label (e.g. "Account")`),pluralLabel:t.z.string().optional().describe(`Human readable plural label (e.g. "Accounts")`),description:t.z.string().optional().describe(`Developer documentation / description`),icon:t.z.string().optional().describe(`Icon name (Lucide/Material) for UI representation`),isSystem:t.z.boolean().optional().default(!1).describe(`Is system object (protected from deletion; defaults its org-wide sharing to public when no sharingModel is set — plugin-sharing)`),managedBy:t.z.enum([`platform`,`config`,`system`,`engine-owned`,`append-only`,`better-auth`]).optional().describe(`Lifecycle bucket — platform (user CRUD) | config (admin authored) | system (engine-managed schema, writable via userActions) | engine-owned (engine owns the lifecycle, no user writes) | append-only (audit) | better-auth (identity). UI clients honour the resolved affordance matrix.`),ownership:t.z.enum([`user`,`org`,`none`],{error:"`ownership` is the record-ownership model — one of 'user' (default) | 'org' | 'none'. The package-contribution kind 'own'/'extend' is set via registerObject, not on the object schema."}).optional().describe(`Record-ownership model: user (default — injects reassignable owner_id) | org | none (no per-record owner, skips owner_id). Distinct from the package own/extend contribution kind.`),userActions:t.z.object({create:t.z.boolean().optional().describe(`Show generic "New" button.`),import:t.z.boolean().optional().describe(`Show CSV import wizard entry.`),edit:t.z.union([t.z.boolean(),_r]).optional().describe(`Allow inline / form edit of existing rows. Boolean, or an object adding per-record visibleWhen/disabledWhen CEL predicates.`),delete:t.z.union([t.z.boolean(),_r]).optional().describe(`Show row-level delete + bulk delete. Boolean, or an object adding per-record visibleWhen/disabledWhen CEL predicates.`),exportCsv:t.z.boolean().optional().describe(`Show CSV export entry.`)}).optional().describe(`Per-object override of the resolved CRUD affordance matrix.`),systemFields:t.z.union([t.z.literal(!1),t.z.object({tenant:t.z.boolean().optional().describe(`Inject the organization_id column. Default true (the column is always provisioned; the multi-tenant flag governs only its index).`),audit:t.z.boolean().optional().describe(`Inject the audit columns (created_at/created_by/updated_at/updated_by). Default true.`)})]).optional().describe(`Opt out of, or selectively disable, registry-level system-field auto-injection.`),datasource:t.z.string().optional().default(`default`).describe(`Target Datasource ID. "default" is the primary DB.`),external:gr.optional().describe(`Remote table binding for federated (external) objects.`),fields:t.z.record(t.z.string().regex(/^[a-z_][a-z0-9_]*$/,{message:`Field names must be lowercase snake_case (e.g., "first_name", "company", "annual_revenue")`}),$e).describe(`Field definitions map. Keys must be snake_case identifiers.`),indexes:t.z.array(rr).optional().describe(`Database performance indexes`),fieldGroups:t.z.array(hr).refine(e=>new Set(e.map(e=>e.key)).size===e.length,{message:`fieldGroups[].key must be unique within an object`}).optional().describe(`Ordered list of field groups (array order = display order). See ObjectFieldGroupSchema.`),tenancy:or.optional().describe(`Multi-tenancy configuration for SaaS applications`),access:cr.optional().describe(`[ADR-0066 D2] Object exposure posture (public-by-default vs private secure-by-default).`),requiredPermissions:ur.optional().describe("[ADR-0066 D3/⑤] Capabilities required to access this object (AND-gate) — `string[]` gates all CRUD, or a `{read,create,update,delete}` map gates per operation."),lifecycle:mr.optional().describe(`Data lifecycle contract (ADR-0057): class + retention/ttl/rotation/archive policies enforced by the platform LifecycleService.`),fileAccessDelegate:t.z.string().optional().describe(`Kernel service that authorizes downloads of files owned by this object's media fields, instead of testing whether the caller can read the owning row. For objects whose access is mediated by a service (e.g. sys_approval_action → approvals). Fails closed.`),validations:t.z.array(z).optional().describe(`Object-level validation rules`),activityMilestones:t.z.array(t.z.object({field:t.z.string().describe(`Field to watch (typically a status/stage select).`),value:t.z.string().describe(`The value the field must transition INTO to fire the milestone.`),summary:t.z.string().describe(`Activity summary template; {field} tokens interpolate the record value. e.g. "Deal won: {name}".`),type:t.z.string().optional().describe(`Activity type for the emitted row (default "completed").`)})).optional().describe(`Declarative semantic activity milestones — emit a templated timeline row when a field transitions into a value, no hook code (ADR-0052 §5b.2).`),nameField:t.z.string().optional().describe(`[ADR-0079] Canonical primary title field — the stored field used as the record display name (e.g. "name", "title").`),displayNameField:t.z.string().optional().describe(`[DEPRECATED → nameField] Field to use as the record display name (e.g., "name", "title"). Accepted as an alias for nameField.`),titleFormat:Ue.optional().describe(`[DEPRECATED → nameField (ADR-0079)] Render-only title template; the server cannot return or query it, and an explicit nameField now takes precedence. Migrate a single-field title to nameField, a composite to a formula field designated as nameField.`),highlightFields:t.z.array(t.z.string()).optional().describe(`[ADR-0085] Ordered most-important fields; first entry wins where only one fits. Drives default columns, cards, previews, detail highlight strip. Renamed from compactLayout.`),stageField:t.z.union([t.z.string(),t.z.literal(!1)]).optional().describe(`[ADR-0085] Lifecycle stage field (linear/ordered), or false to declare the status field non-linear and suppress stage heuristics. Absent = heuristic detection allowed.`),listViews:t.z.record(t.z.string(),zn).optional().describe(`Built-in named list views (segmented tabs) shipped with the object schema — "views" mode, dropdown userFilters allowed, no page-only tabs (ADR-0047)`),searchableFields:t.z.array(t.z.string()).optional().describe("Fields the `$search` query matches against (ADR-0061). Canonical default for the record picker, list quick-search and global search; views may narrow it. When unset, search auto-defaults to the name/title field plus short-text fields."),enable:nr.optional().describe(`Enabled system features modules`),sharingModel:t.z.enum([`private`,`public_read`,`public_read_write`,`controlled_by_parent`]).optional().describe(`Org-Wide Default record visibility (OWD) for INTERNAL users. Canonical four only (legacy aliases removed, ADR-0090 D4): private (owner-only) | public_read (everyone reads, owner writes) | public_read_write (everyone reads+writes) | controlled_by_parent (derived from the master record). A CUSTOM object that omits this resolves to private at runtime (ADR-0090 D1).`),externalSharingModel:t.z.enum([`private`,`public_read`,`public_read_write`,`controlled_by_parent`]).optional().describe(`[ADR-0090 D11] OWD for external (portal/partner) principals. Defaults to private; must be <= sharingModel in openness.`),publicSharing:t.z.object({enabled:t.z.boolean().default(!1).describe(`Allow records of this object to be published via share link`),allowedAudiences:t.z.array(t.z.enum([`public`,`link_only`,`signed_in`,`email`])).optional().describe(`Audiences callers may select when creating a link`),allowedPermissions:t.z.array(t.z.enum([`view`,`comment`,`edit`])).optional().describe(`Permission levels selectable on the share dialog`),maxExpiryDays:t.z.number().int().positive().optional().describe(`Reject links with expiry beyond this many days`),redactFields:t.z.array(t.z.string()).optional().describe(`Field names removed from records served via a share token`),eligibility:t.z.string().optional().describe(`CEL expression that must evaluate to true on the target record`)}).optional().describe(`Public share-link policy (Notion/Figma-style link sharing)`),actions:t.z.array(Pt).optional().describe(`Actions associated with this object (auto-populated from top-level actions via objectName)`),protection:U.optional().describe(`Package author protection block — lock policy for this object.`),...H});function vr(e){return e.split(`_`).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `)}var yr={workflows:"`workflows` is not an ObjectSchema field. Object-level, record-triggered automation is authored as a lifecycle hook (`src/objects/<name>.hook.ts`, wrapped in `defineHook()` from `@objectstack/spec/data`) or as a top-level `record_change` flow — not as `workflows[]` on the object schema.",workflow:"`workflow` is not an ObjectSchema field. Record-triggered automation is authored as a lifecycle hook (`src/objects/<name>.hook.ts`) or a top-level `record_change` flow.",hooks:"`hooks` is not an ObjectSchema field. Lifecycle hooks live in their own `src/objects/<name>.hook.ts` module, wrapped in `defineHook()` from `@objectstack/spec/data`.",triggers:"`triggers` is not an ObjectSchema field. Use a lifecycle hook (`src/objects/<name>.hook.ts`) or a top-level `record_change` flow.",compactLayout:"`compactLayout` was renamed to `highlightFields` in @objectstack/spec 11.7.0 (ADR-0085 semantic roles) and the alias was retired in 11.9.1 (#2536). Rename the key — the value shape (ordered field-name list) is unchanged.",detail:"The `detail` UI-hints block was removed by ADR-0085 (spec 11.7.0). Its jobs moved to top-level semantic roles: `detail.stageField` → `stageField` (string | false), `detail.highlightFields` → `highlightFields`, section layout → `fieldGroups` + `Field.group`. Whole-page customization is done by assigning a custom Page schema instead of per-page hint keys.",views:"`views` is not an ObjectSchema field: the object-level `views.form/*` and `views.detail/*` UI-hint dialect was never part of the spec and its renderer support was removed (ADR-0085). Use the semantic roles (`highlightFields`, `stageField`, `fieldGroups`) for hints and `listViews` for named list views.",defaultDetailForm:"`defaultDetailForm` was never implemented and was removed from the spec (#2402). Curate the record page by assigning a custom Page schema; form layout derives from `fieldGroups` + `Field.group`.",softDelete:"`softDelete` was removed from the spec in 16.0 (#2377, ADR-0049 enforce-or-remove) — there is no soft-delete/recycle-bin runtime, so it stored nothing and implied restore semantics that do not exist. Deletes are hard deletes; remove the key.",versioning:"`versioning` was removed from the spec in 16.0 (#2377, ADR-0049) — no record-versioning engine ever read it (it snapshotted no history). Use per-field `Field.trackHistory` for field-level history, or a data lifecycle policy (`lifecycle`) for retention.",search:"`search` (the SearchConfig block) was removed from the spec in 16.0 (#2377, ADR-0049) — no search-engine config was consumed. Declare the indexed fields with `searchableFields` (ADR-0061); records stay queryable via the normal data API regardless.",recordName:"`recordName` was removed from the spec in 16.0 (#2377, ADR-0049) — it was never read. Auto-naming is modelled as a `Field` of type 'autonumber' (with `autonumberFormat`) designated as the object's `nameField`.",keyPrefix:"`keyPrefix` was removed from the spec in 16.0 (#2377, ADR-0049) — record ids are not prefixed from it (no Salesforce-style key-prefix runtime). Remove the key; it had no effect.",tags:"`tags` (object-level categorization) was removed from the spec (#2377, ADR-0049) — it had no runtime reader. Remove the key; use `managedBy` for lifecycle bucketing or a real field for per-record tagging.",active:'`active` was removed from the spec (#2377, ADR-0049) — no runtime reader gated on it, so an "inactive" object was still fully queryable and usable. Remove the key; gate availability with permissions/sharing instead.',abstract:"`abstract` was removed from the spec (#2377, ADR-0049) — object inheritance/abstraction is not implemented, so an abstract object still got a table and was instantiable. Remove the key."};function br(e,t){let n=Array.from({length:e.length+1},()=>Array(t.length+1).fill(0));for(let t=0;t<=e.length;t++)n[t][0]=t;for(let e=0;e<=t.length;e++)n[0][e]=e;for(let r=1;r<=e.length;r++)for(let i=1;i<=t.length;i++)n[r][i]=e[r-1]===t[i-1]?n[r-1][i-1]:1+Math.min(n[r-1][i],n[r][i-1],n[r-1][i-1]);return n[e.length][t.length]}function xr(e,t){let n,r=1/0;for(let i of t){let t=br(e.toLowerCase(),i.toLowerCase());t<r&&(r=t,n=i)}return n!==void 0&&r<=Math.max(2,Math.floor(e.length/3))?n:void 0}function Sr(e,t,n){let r=typeof e==`string`&&e.length>0?e:`<unnamed>`,i=t.map(e=>{let t=yr[e];if(t)return` \u2022 ${t}`;let r=xr(e,n);return r?` \u2022 \`${e}\` is not an ObjectSchema field \u2014 did you mean \`${r}\`?`:` \u2022 \`${e}\` is not an ObjectSchema field.`});return Error(`ObjectSchema.create('${r}'): unknown key(s) \u2014 ${t.join(`, `)}.
|
|
11
|
+
These keys would previously have been stripped silently at build, shipping dead metadata with no diagnostic (ADR-0032 "no silent failure", issue #1535).
|
|
12
|
+
|
|
13
|
+
${i.join(`
|
|
14
|
+
`)}
|
|
15
|
+
|
|
16
|
+
Remove the unknown key(s), fix the typo, or move the logic to a supported mechanism.`)}var Cr=new Set;function wr(e,t,n){if(n===`better-auth`||!t||typeof t!=`object`)return;let r=Object.entries(t).filter(([,e])=>e&&e.type===`password`&&e.ackPlaintextMasking!==!0).map(([e])=>e);if(r.length===0)return;let i=typeof e==`string`&&e.length>0?e:`<unnamed>`;Cr.has(i)||(Cr.add(i),console.warn(`ObjectSchema.create('${i}'): field(s) ${r.map(e=>`\`${e}\``).join(`, `)} use type 'password' on a non-auth object. The generic CRUD path stores a password field as plaintext at rest and masks it to \u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022 on read (ADR-0100) \u2014 it is NOT one-way hashed (that is owned by the auth subsystem, for its identity tables only). Use \`Field.secret(...)\` for reversible machine credentials, or model login credentials on the auth user object. If this is intended, the masking contract applies \u2014 affirm it with \`ackPlaintextMasking: true\` on the field to silence this warning.`))}function Tr(e){if(!e||typeof e!=`object`||Array.isArray(e))return e;let t=e;return t.nameField==null&&typeof t.displayNameField==`string`?{...t,nameField:t.displayNameField}:e}function Er(e){if(!e||typeof e!=`object`||Array.isArray(e))return e;let t=e,n=t;if(Array.isArray(t.fieldGroups)){let e=!1,r=t.fieldGroups.map(t=>{if(!t||typeof t!=`object`||Array.isArray(t))return t;let n=t;if(n.collapse!=null)return t;let r;return typeof n.collapsible==`boolean`||typeof n.collapsed==`boolean`?r=n.collapsed===!0?`collapsed`:n.collapsible===!0?`expanded`:`none`:typeof n.defaultExpanded==`boolean`&&(r=n.defaultExpanded?`expanded`:`collapsed`),r===void 0?t:(e=!0,{...n,collapse:r})});e&&(n={...n,fieldGroups:r})}return n}var Dr=n(()=>{let e=q.parse.bind(q),t=q.safeParse.bind(q);return Object.assign(q,{parse(t,n){return e(Er(Tr(t)),n)},safeParse(e,n){return t(Er(Tr(e)),n)},create:e=>{let t=e,n=Object.keys(q.shape),r=Object.keys(t).filter(e=>!n.includes(e));if(r.length>0)throw Sr(t.name,r,n);wr(t.name,t.fields,t.managedBy);let i={...t,label:t.label??vr(t.name)};return q.parse(i)}})}),Or={platform:{create:!0,import:!0,edit:!0,delete:!0,exportCsv:!0},config:{create:!0,import:!1,edit:!0,delete:!0,exportCsv:!0},system:{create:!1,import:!1,edit:!1,delete:!1,exportCsv:!0},"engine-owned":{create:!1,import:!1,edit:!1,delete:!1,exportCsv:!0},"append-only":{create:!1,import:!1,edit:!1,delete:!1,exportCsv:!0},"better-auth":{create:!1,import:!1,edit:!1,delete:!1,exportCsv:!0}};function kr(e){let t=Or[e?.managedBy??`platform`]??Or.platform,n=e?.userActions??{},r=Ar(n.edit,t.edit),i=Ar(n.delete,t.delete),a={create:n.create??t.create,import:n.import??t.import,edit:r.enabled,delete:i.enabled,exportCsv:n.exportCsv??t.exportCsv};return r.predicates&&(a.editPredicates=r.predicates),i.predicates&&(a.deletePredicates=i.predicates),a}function Ar(e,t){if(e==null)return{enabled:t};if(typeof e==`boolean`)return{enabled:e};let n=e.enabled??t,r=e.visibleWhen,i=e.disabledWhen;if(r==null&&i==null)return{enabled:n};let a={};return r!=null&&(a.visibleWhen=r),i!=null&&(a.disabledWhen=i),{enabled:n,predicates:a}}var jr=t.z.enum([`own`,`extend`]),Mr=n(()=>t.z.object({extend:t.z.string().describe(`Target object name (FQN) to extend`),fields:t.z.record(t.z.string(),$e).optional().describe(`Fields to add/override`),label:t.z.string().optional().describe(`Override label for the extended object`),pluralLabel:t.z.string().optional().describe(`Override plural label for the extended object`),description:t.z.string().optional().describe(`Override description for the extended object`),validations:t.z.array(z).optional().describe(`Additional validation rules to merge into the target object`),indexes:t.z.array(rr).optional().describe(`Additional indexes to merge into the target object`),priority:t.z.number().int().min(0).max(999).default(200).describe(`Merge priority (higher = applied later)`)}));function Nr(e){return Mr.parse(e)}var Pr=[`get`,`list`,`create`,`update`,`delete`,`bulk`],Fr=K,Ir=new Set(Pr),Lr=new Set(G);function Rr(e){return Ir.has(e)}function zr(e){return Lr.has(e)}var Br={upsert:{all:[`create`,`update`]},import:{any:[`create`,`update`]},export:{all:[`list`]},aggregate:{all:[`list`]},search:{all:[`list`],flag:e=>e.searchable!==!1},history:{all:[`get`],flag:e=>e.trackHistory===!0},restore:{all:[`delete`],flag:()=>!1},purge:{all:[`delete`],flag:()=>!1}},Vr={get:`get`,query:`list`,find:`list`,list:`list`,create:`create`,update:`update`,delete:`delete`,batch:`bulk`,bulk:`bulk`,upsert:`upsert`,aggregate:`aggregate`,history:`history`,search:`search`,restore:`restore`,purge:`purge`,import:`import`,export:`export`};function Hr(e,t,n,r){let i=Br[e];return i.flag&&!i.flag(n)||e===`export`&&!r?!1:i.all?i.all.every(e=>t.has(e)):i.any?i.any.some(e=>t.has(e)):!1}function Ur(e,t,n,r){let i=new Set;if(e===`deny-all`)return i;for(let e of t)i.add(e);for(let e of G)Hr(e,t,n,r)&&i.add(e);return i}function Wr(e,t){let n=t?.userExportAllowed!==!1,r=e??{},i=r.apiMethods;if(i==null){let e=new Set(Pr);return{mode:`unrestricted`,primitives:e,operations:Ur(`unrestricted`,e,r,n),userExportAllowed:n}}let a=Array.isArray(i)?new Set(i.map(e=>String(e)).filter(Rr)):new Set;return a.size===0?{mode:`deny-all`,primitives:new Set,operations:new Set,userExportAllowed:n}:{mode:`restricted`,primitives:a,operations:Ur(`restricted`,a,r,n),userExportAllowed:n}}function Gr(e,t,n){if(e.mode===`deny-all`)return!1;let r=e.mode===`unrestricted`;if(t===`bulk`&&n?.bulkChild)return!r&&!e.primitives.has(`bulk`)?!1:Gr(e,n.bulkChild,{writeMode:n.writeMode});if(Rr(t))return r||e.primitives.has(t);if(zr(t)){if(t===`import`&&n?.writeMode&&!r){let t=n.writeMode;if(t===`insert`)return e.primitives.has(`create`);if(t===`update`)return e.primitives.has(`update`);if(t===`upsert`)return e.primitives.has(`create`)&&e.primitives.has(`update`)}return e.operations.has(t)}return!0}function Kr(e){return K.filter(t=>e.operations.has(t))}var qr=Object.freeze({referenceFilter:{to:`lookupFilters`},cascadeDelete:{to:`deleteBehavior`},formula:{to:`expression`},displayFormat:{to:`autonumberFormat`},summaryType:{to:`summaryOperations`},summaryField:{to:`summaryOperations`},index:{why:"field-level index flags built no index and were removed in the 16.x line (#2377, ADR-0049) — declare the index in the object's `indexes[]` instead."},indexed:{why:"never a FieldSchema key; a field-level index flag built no index (#2377). Declare the index in the object's `indexes[]`."},immutable:{why:"never a FieldSchema key. Use the `readonlyWhen` predicate to lock a field after creation."},filterable:{why:"never a FieldSchema key — every declared column is filterable. `sortable` and `searchable` are the real knobs."},placeholder:{why:"never a FieldSchema key. Author hint text through `inlineHelpText` or `description`."},startingNumber:{why:"never a FieldSchema key. An autonumber counter resets per rendered prefix, which `autonumberFormat` itself determines."},validation:{why:"field-level predicates are not a FieldSchema key — author a `validation` metadata item on the object, which carries its own message."},errorMessage:{why:"pairs with the `validation` key that never existed; a `validation` metadata item carries its own message."},audit:{why:"the `auditTrail` family was pruned in 2026-06 as dead in both layers. Use `trackHistory` for the activity timeline."},auditTrail:{why:"pruned in 2026-06 as dead in both layers. Use `trackHistory` for the activity timeline."},pii:{why:"the `dataQuality` governance family was pruned in 2026-06 as dead in both layers — it enforced nothing."},dataQuality:{why:`pruned in 2026-06 as dead in both layers (#3726) — it enforced nothing.`},encrypted:{why:"the `encryptionConfig` family was pruned in 2026-06: it implied at-rest protection that never happened. The real channel is `type: 'secret'`."},encryptionConfig:{why:"pruned in 2026-06 — it implied at-rest protection that never happened. The real channel is `type: 'secret'`."},maskingRule:{why:`pruned in 2026-06 as dead in both layers — masking was never applied.`},cached:{why:`computed-field caching was pruned in 2026-06 (#3733); nothing read it.`}}),Jr=Object.freeze({capabilities:{to:`enable`},features:{to:`enable`},namespace:{why:"deprecated and removed — the object `name` is the canonical id everywhere. For module grouping embed a prefix in the name (`sys_user`)."},tableName:{why:"removed — the table name always equals the object `name`."}}),Yr=Object.freeze({storage:{why:`the file-storage backend is a deployment concern, not an application declaration. Configure it with the OS_STORAGE_* environment variables, or per-deployment in Setup → Settings → Storage (which also holds credentials — a stack definition would commit them to git and to any published artifact).`}}),Xr=Object.freeze([`onEnable`,`functions`]);function Zr(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function Qr(e,t,n,r,i,a){let o=[...t];for(let s of Object.keys(e)){if(t.has(s)||s.startsWith(`_`))continue;let e=n[s],c=e?.to??(e?.why?void 0:dt(s,o,3,1)[0]);a.push({path:`${i}.${s}`,surface:r,key:s,...c?{suggestion:c}:{},...e?.why?{guidance:e.why}:{}})}}function $r(e){let t=`${e.path}: '${e.key}' is not a declared ${e.surface} key, so its value is dropped at load`;return e.guidance?`${t} \u2014 ${e.guidance}`:e.suggestion?`${t} \u2014 did you mean '${e.suggestion}'?`:`${t}.`}var ei=new Set([`text`,`textarea`,`email`,`url`,`phone`,`password`,`secret`,`markdown`,`html`,`richtext`,`code`,`color`,`signature`,`qrcode`]),ti=new Set([`number`,`currency`,`percent`,`rating`,`slider`,`progress`,`summary`]),ni=new Set([`boolean`,`toggle`]),ri=new Set([`date`]),ii=new Set([`datetime`]),ai=new Set([`time`]),oi=new Set([`select`,`radio`]),si=new Set([`multiselect`,`checkboxes`,`tags`]),ci=new Set([`lookup`,`master_detail`,`user`,`tree`]),li=new Set([`image`,`file`,`avatar`,`video`,`audio`]);function ui(e){return typeof e==`string`&&/^[A-Za-z0-9_-]{1,64}$/.test(e)}var di=`__rawFileValues`,fi=new Set([`json`,`composite`,`repeater`,`record`,`location`,`address`,`vector`]),pi=new Set([`formula`,`summary`,`autonumber`]),mi=new Set([`select`,`radio`,`lookup`,`user`,`file`,`image`]);function hi(e){return si.has(e.type)?!0:mi.has(e.type)&&e.multiple===!0}var gi=n(()=>t.z.string().regex(/^\d{4}-\d{2}-\d{2}$/,`expected YYYY-MM-DD (calendar day, not an instant)`)),_i=n(()=>t.z.string().refine(e=>!Number.isNaN(Date.parse(e))&&(/[Zz]$/.test(e)||/[+-]\d{2}:?\d{2}$/.test(e.slice(10))),`expected an ISO-8601 instant with explicit zone (e.g. 2026-03-15T14:30:00.000Z)`)),vi=n(()=>t.z.string().regex(/^([01]\d|2[0-3]):[0-5]\d(:[0-5]\d(\.\d+)?)?(Z|[+-]([01]\d|2[0-3]):?[0-5]\d)?$/,`expected HH:MM or HH:MM:SS (wall-clock time of day)`)),yi=n(()=>t.z.object({lat:t.z.number().min(-90).max(90).describe(`Latitude`),lng:t.z.number().min(-180).max(180).describe(`Longitude`),altitude:t.z.number().optional().describe(`Altitude in meters`),accuracy:t.z.number().optional().describe(`Accuracy in meters`)})),bi=Ye,xi=n(()=>t.z.looseObject({url:t.z.string(),name:t.z.string().optional(),size:t.z.number().optional(),mimeType:t.z.string().optional(),alt:t.z.string().optional(),duration:t.z.number().optional()})),Si=n(()=>t.z.string().regex(/^[A-Za-z0-9_-]{1,64}$/,`Expected an opaque sys_file id`)),Ci=n(()=>t.z.union([t.z.string().min(1),xi])),wi=n(()=>t.z.string().min(1));function Ti(e){return Array.isArray(e.options)?e.options.map(e=>String(typeof e==`object`&&e?e.value:e)):[]}function Ei(e,n=`stored`){let r=e.type,i=(()=>{if(ei.has(r))return t.z.string();if(ti.has(r))return t.z.number().finite();if(ni.has(r))return t.z.boolean();if(ri.has(r))return gi;if(ii.has(r))return _i;if(ai.has(r))return vi;if(oi.has(r)||si.has(r)){let n=Ti(e);return n.length>0?t.z.enum(n):t.z.string()}return ci.has(r)?n===`expanded`?t.z.union([wi,t.z.record(t.z.string(),t.z.unknown())]):wi:li.has(r)?n===`expanded`?t.z.union([Si,xi]):Si:r===`location`?yi:r===`address`?bi:r===`composite`||r===`record`?t.z.record(t.z.string(),t.z.unknown()):r===`repeater`?t.z.array(t.z.record(t.z.string(),t.z.unknown())):r===`vector`?t.z.array(t.z.number()):t.z.unknown()})();return hi(e)?t.z.array(i):i}var Di=new Set([`true`,`t`,`yes`,`y`,`1`,`on`,`是`,`对`,`✓`,`√`]),Oi=new Set([`false`,`f`,`no`,`n`,`0`,`off`,`否`,`错`,`✗`,`×`]),ki=new Set([...ci,`reference`]),Ai=new Set([`YYYY`,`YY`,`MM`,`DD`,`YYYYMMDD`]);function ji(e){let t=[];if(!e)return t;let n=/\{([^{}]*)\}/g,r=0,i,a=!1;for(;(i=n.exec(e))!==null;){i.index>r&&t.push({kind:`literal`,text:e.slice(r,i.index)});let o=i[1];/^0+$/.test(o)&&!a?(t.push({kind:`seq`,width:o.length}),a=!0):Ai.has(o)?t.push({kind:`date`,pattern:o}):/^[A-Za-z_][A-Za-z0-9_]*$/.test(o)?t.push({kind:`field`,field:o}):t.push({kind:`literal`,text:i[0]}),r=n.lastIndex}return r<e.length&&t.push({kind:`literal`,text:e.slice(r)}),t}function Mi(e){return e.some(e=>e.kind===`date`||e.kind===`field`)}function Ni(e,t=4){let n=e.find(e=>e.kind===`seq`);return n&&n.kind===`seq`?n.width:t}function Pi(e){return e.filter(e=>e.kind===`field`).map(e=>e.field)}function Fi(e,t){let n=[];for(let r of Pi(e)){let e=t?t[r]:void 0;(e==null||e===``)&&!n.includes(r)&&n.push(r)}return n}function Ii(e,t){let n,r,i;try{let a=new Intl.DateTimeFormat(`en-CA`,{timeZone:t||`UTC`,year:`numeric`,month:`2-digit`,day:`2-digit`}).formatToParts(e);n=a.find(e=>e.type===`year`)?.value??`0000`,r=a.find(e=>e.type===`month`)?.value??`01`,i=a.find(e=>e.type===`day`)?.value??`01`}catch{n=String(e.getUTCFullYear()).padStart(4,`0`),r=String(e.getUTCMonth()+1).padStart(2,`0`),i=String(e.getUTCDate()).padStart(2,`0`)}return{YYYY:n,YY:n.slice(-2),MM:r,DD:i}}function Li(e,t){switch(e){case`YYYY`:return t.YYYY;case`YY`:return t.YY;case`MM`:return t.MM;case`DD`:return t.DD;case`YYYYMMDD`:return`${t.YYYY}${t.MM}${t.DD}`;default:return``}}function Ri(e){let{tokens:t,seq:n,record:r,now:i,timezone:a}=e,o=Ii(i,a),s=``,c=``,l=null;for(let e of t){if(e.kind===`seq`){l=e.width;continue}let t=``;if(e.kind===`literal`)t=e.text;else if(e.kind===`date`)t=Li(e.pattern,o);else if(e.kind===`field`){let n=r?r[e.field]:void 0;t=n==null?``:String(n)}l===null?s+=t:c+=t}let u=Mi(t)?s:``,d=l===null?`${s}${n}`:`${s}${String(n).padStart(l,`0`)}${c}`;return{prefix:s,suffix:c,scope:u,value:d}}var zi="A hook `object` target must name at least one object. An empty target is not \"no target\": until #4001 `''` and `[]` were widened to the wildcard `'*'`, registering the hook on EVERY object, and `['']` registered it on an object name nothing matches, so it could never fire. Name the object(s) — `object: 'account'` or `object: ['account', 'contact']` — or, if firing on every object really is the intent, write the wildcard explicitly: `object: '*'`.",Bi=[`name`,`label`,`object`,`events`,`handler`,`body`,`priority`,`async`,`condition`,`description`,`retryPolicy`,`timeout`,`onError`],Vi=[`maxRetries`,`backoffMs`],Hi=V({surface:`this hook`,knownKeys:Bi,aliases:{hookname:`name`,objectname:`object`,objects:`object`,event:`events`,fn:`handler`,callback:`handler`,order:`priority`,sequence:`priority`,background:`async`,isasync:`async`,when:`condition`,predicate:`condition`,retry:`retryPolicy`,timeoutms:`timeout`,errorpolicy:`onError`,onfailure:`onError`},guidance:{enabled:"`enabled` is not a hook key — a hook has no on/off switch. Gate it with `condition` (the hook is skipped when the predicate is false), or remove the hook.",active:"`active` is not a hook key — a hook has no on/off switch. Gate it with `condition`, or remove the hook."},history:`Until #4001 these were dropped silently — the hook still registered and ran.`}),Ui=V({surface:`this hook's retryPolicy`,knownKeys:Vi,aliases:{retries:`maxRetries`,attempts:`maxRetries`,basedelayms:`backoffMs`,backoff:`backoffMs`,delayms:`backoffMs`},history:"Until #4001 these were dropped silently — the hook retried on the defaults rather than the policy that was written. Note a datasource retryPolicy spells its delay `baseDelayMs`; a hook spells it `backoffMs`."}),Wi=t.z.enum([`beforeFind`,`afterFind`,`beforeInsert`,`afterInsert`,`beforeUpdate`,`afterUpdate`,`beforeDelete`,`afterDelete`]),Gi=n(()=>t.z.object({name:t.z.string().regex(/^[a-z_][a-z0-9_]*$/).describe(`Hook unique name (snake_case)`),label:t.z.string().optional().describe(`Description of what this hook does`),object:t.z.union([t.z.string(),t.z.array(t.z.string())]).refine(e=>Array.isArray(e)?e.length>0&&e.every(e=>e.trim().length>0):e.trim().length>0,{error:zi}).describe(`Target object(s)`),events:t.z.array(Wi).describe(`Lifecycle events`),handler:t.z.union([t.z.string(),t.z.custom(e=>typeof e==`function`,{message:`Expected function`})]).optional().describe("Handler function name (string, post-build) or inline function (pre-build) — DEPRECATED, prefer `body`"),body:xt.optional().describe(`Hook body — expression (L1) or sandboxed JS (L2)`),priority:t.z.number().default(100).describe(`Execution priority`),async:t.z.boolean().default(!1).describe(`Run specifically as fire-and-forget`),condition:L.optional().describe('Predicate (CEL); hook runs only when TRUE. e.g. P`record.status == "closed" && record.amount > 1000`'),description:t.z.string().optional().describe(`Human-readable description of what this hook does`),retryPolicy:t.z.object({maxRetries:t.z.number().default(3).describe(`Maximum retry attempts on failure`),backoffMs:t.z.number().default(1e3).describe(`Backoff delay between retries in milliseconds`)},{error:Ui}).strict().optional().describe(`Retry policy for failed hook executions`),timeout:t.z.number().optional().describe(`Maximum execution time in milliseconds before the hook is aborted`),onError:t.z.enum([`abort`,`log`]).default(`abort`).describe(`Error handling strategy`)},{error:Hi}).strict()),Ki=n(()=>t.z.object({id:t.z.string().optional().describe(`Unique execution ID for tracing`),object:t.z.string(),event:Wi,input:t.z.record(t.z.string(),t.z.unknown()).describe(`Mutable input parameters`),result:t.z.unknown().optional().describe(`Operation result (After hooks only)`),previous:t.z.record(t.z.string(),t.z.unknown()).optional().describe(`Record state before operation`),session:t.z.object({userId:t.z.string().optional(),actor:t.z.string().optional().describe(`Service-principal label for audit attribution when the caller is not a real user (e.g. svc:flow:<flowName>)`),organizationId:t.z.string().optional().describe(`Active organization ID (blessed developer-facing name)`),roles:t.z.array(t.z.string()).optional(),accessToken:t.z.string().optional(),isSystem:t.z.boolean().optional().describe(`True when the call was made with an elevated system context (engine self-writes)`),skipTriggers:t.z.boolean().optional().describe(`True when record-change automation (flow triggers) must be suppressed for this write — e.g. package seed replay. Lifecycle hooks still run.`),skipAutomations:t.z.boolean().optional().describe(`True when metadata-bound automation hooks must be suppressed for this write — e.g. data import with "run automations" unchecked, or import undo. Implies skipTriggers; code-registered system hooks (audit, security) still run.`)}).optional().describe(`Current session context`),provenance:t.z.object({flowRunId:t.z.string().optional().describe(`Id of the automation flow run performing this write, when it originates from a flow data node. Lets a hook recognize the run that OWNS state that run itself opened — the approvals record lock exempts the run holding the pending request (#3456).`)}).optional().describe(`Server-stamped write provenance (never client-supplied, never an authorization input)`),transaction:t.z.unknown().optional().describe(`Database transaction handle`),ql:t.z.unknown().describe(`ObjectQL Engine Reference`),api:t.z.unknown().optional().describe(`Cross-object data access (ScopedContext)`),user:t.z.object({id:t.z.string().optional(),name:t.z.string().optional(),email:t.z.string().optional(),organizationId:t.z.string().optional().describe(`Active organization ID of the acting user (equals session.organizationId)`)}).optional().describe(`Current user info shortcut`)}));function qi(e){return Gi.parse(e)}var Ji=t.z.enum([`none`,`constant`,`lookup`,`split`,`join`,`javascript`,`map`]),Yi=n(()=>t.z.object({source:t.z.union([t.z.string(),t.z.array(t.z.string())]).describe(`Source column header(s)`),target:t.z.union([t.z.string(),t.z.array(t.z.string())]).describe(`Target object field(s)`),transform:Ji.default(`none`),params:t.z.object({value:t.z.unknown().optional(),object:t.z.string().optional(),fromField:t.z.string().optional(),toField:t.z.string().optional(),autoCreate:t.z.boolean().optional(),valueMap:t.z.record(t.z.string(),t.z.unknown()).optional(),separator:t.z.string().optional()}).optional()})),Xi=n(()=>t.z.object({name:I.describe(`Mapping unique name (lowercase snake_case)`),label:t.z.string().optional(),sourceFormat:t.z.enum([`csv`,`json`,`xml`,`sql`]).default(`csv`),targetObject:t.z.string().describe(`Target Object Name`),fieldMapping:t.z.array(Yi),mode:t.z.enum([`insert`,`update`,`upsert`]).default(`insert`),upsertKey:t.z.array(t.z.string()).optional().describe(`Fields to match for upsert (e.g. email)`),extractQuery:j.optional().describe(`Query to run for export only`),errorPolicy:t.z.enum([`skip`,`abort`,`retry`]).default(`skip`),batchSize:t.z.number().default(1e3)}));function Zi(e){return Xi.parse(e)}var Qi=t.z.enum([`read`,`create`,`update`,`delete`,`transfer`,`restore`,`purge`,`export`]),$i=t.z.enum([`PLATFORM_ADMIN`,`TENANT_ADMIN`,`MEMBER`,`EXTERNAL`]).describe(`ADR-0095 D2 posture rung — PLATFORM_ADMIN crosses the tenant wall where object posture permits; TENANT_ADMIN sees all rows in the org; MEMBER gets business RLS; EXTERNAL sees only explicitly shared rows.`),ea=n(()=>t.z.object({kind:t.z.enum([`tenant_filter`,`owd_baseline`,`ownership`,`record_share`,`sharing_rule`,`team`,`territory`,`rls_policy`]).describe(`The row-visibility source kind evaluated for this record at this layer.`),name:t.z.string().describe(`Stable identifier of the concrete rule, share, or policy that was evaluated.`),grants:t.z.enum([`read`,`edit`,`full`]).optional().describe("Access level a sharing source grants on the record (authorable: read/edit; `full` appears only for legacy rows pending normalisation)."),via:t.z.string().optional().describe(`How the rule reached the principal — recipient group/position, ownership, or the matching criteria.`),predicate:t.z.unknown().optional().describe(`The row predicate this rule contributed, when it is filter-shaped (null = unrestricted).`),effect:t.z.enum([`admits`,`excludes`,`neutral`]).describe(`The rule's effect on THIS record: admits, excludes, or neutral.`)})),ta=n(()=>t.z.object({outcome:t.z.enum([`admitted`,`excluded`,`not_evaluated`]).describe(`This layer's row-level outcome for the record: admitted, excluded, or not_evaluated (skipped/not row-scoped).`),rowFilter:t.z.unknown().optional().describe(`The effective row predicate this layer contributed for the record set (null = unrestricted, __deny_all__ = zero rows).`),matchesRecord:t.z.boolean().optional().describe(`Whether the specific record satisfies rowFilter — the judgement behind outcome.`),rules:t.z.array(ea).default([]).describe(`Concrete rules, shares, or policies this layer evaluated against the record, in evaluation order.`),detail:t.z.string().optional().describe(`Human-readable, record-specific explanation of this layer's outcome.`)})),na=n(()=>t.z.object({layer:t.z.enum([`tenant_isolation`,`principal`,`required_permissions`,`object_crud`,`fls`,`owd_baseline`,`depth`,`sharing`,`vama_bypass`,`rls`]),kernelTier:t.z.enum([`layer_0_tenant`,`layer_1_business`]).optional().describe(`ADR-0095 kernel layer: layer_0_tenant = the always-first org wall; layer_1_business = business RLS/sharing/ownership.`),verdict:t.z.enum([`grants`,`denies`,`narrows`,`widens`,`neutral`,`not_applicable`]),detail:t.z.string(),contributors:t.z.array(t.z.object({kind:t.z.enum([`permission_set`,`position`,`system`]),name:t.z.string(),via:t.z.string().optional(),state:t.z.enum([`active`,`expired`]).optional()})).default([]),record:ta.optional().describe(`Row-level determination for the specific record under explanation; set only for record-grained requests.`)}));n(()=>t.z.object({object:t.z.string(),operation:Qi,recordId:t.z.string().optional().describe(`Optional id of one concrete record to explain at row granularity; omitted = object-level (pre-C2) request.`),userId:t.z.string().optional()})),n(()=>t.z.object({allowed:t.z.boolean(),object:t.z.string(),operation:Qi,principal:t.z.object({userId:t.z.string().nullable(),positions:t.z.array(t.z.string()).default([]),permissionSets:t.z.array(t.z.string()).default([]),principalKind:t.z.enum([`human`,`agent`,`service`,`guest`,`system`]).optional(),onBehalfOf:t.z.object({userId:t.z.string()}).optional(),posture:$i.optional()}),layers:t.z.array(na),readFilter:t.z.unknown().optional(),record:n(()=>t.z.object({recordId:t.z.string().describe(`The concrete record id this verdict is about (echoes the request recordId).`),visible:t.z.boolean().describe(`Whether the operation is permitted on this specific record after all layers.`),decidedBy:t.z.enum([`tenant_isolation`,`principal`,`required_permissions`,`object_crud`,`fls`,`owd_baseline`,`depth`,`sharing`,`vama_bypass`,`rls`]).optional().describe(`The pipeline layer that decided the record-level outcome (excluded it, or last admitted it).`)})).optional().describe(`Row-level verdict for the specific record; set only for record-grained requests.`)}));var ra=n(()=>t.z.object({permissionSet:t.z.string(),object:t.z.string(),create:t.z.boolean(),read:t.z.boolean(),edit:t.z.boolean(),delete:t.z.boolean(),viewAllRecords:t.z.boolean(),modifyAllRecords:t.z.boolean(),readScope:t.z.string().optional(),writeScope:t.z.string().optional(),sharingModel:t.z.string().optional()}));n(()=>t.z.object({version:t.z.literal(1).default(1),entries:t.z.array(ra).default([])}));var ia=n(()=>t.z.object({userId:t.z.string().optional(),actor:t.z.string().optional(),email:t.z.string().optional(),tenantId:t.z.string().optional(),timezone:t.z.string().optional(),locale:t.z.string().optional(),currency:t.z.string().optional(),positions:t.z.array(t.z.string()).default([]),principalKind:t.z.enum([`human`,`agent`,`service`,`guest`,`system`]).optional(),audience:t.z.enum([`internal`,`external`]).optional(),posture:$i.optional(),onBehalfOf:t.z.object({userId:t.z.string(),principalKind:t.z.enum([`human`,`agent`,`service`,`guest`,`system`]).optional()}).optional(),permissions:t.z.array(t.z.string()).default([]),systemPermissions:t.z.array(t.z.string()).optional(),tabPermissions:t.z.record(t.z.string(),t.z.enum([`visible`,`hidden`,`default_on`,`default_off`])).optional(),org_user_ids:t.z.array(t.z.string()).optional(),accessible_org_ids:t.z.array(t.z.string()).optional(),rlsMembership:t.z.record(t.z.string(),t.z.array(t.z.string())).optional(),isSystem:t.z.boolean().default(!1),flowRunId:t.z.string().optional(),skipTriggers:t.z.boolean().optional(),skipAutomations:t.z.boolean().optional(),seedReplay:t.z.boolean().optional(),skipStateMachine:t.z.boolean().optional(),preserveAudit:t.z.boolean().optional(),oauthScopes:t.z.array(t.z.string()).optional(),accessToken:t.z.string().optional(),transaction:t.z.unknown().optional(),traceId:t.z.string().optional()})),J=n(()=>t.z.union([t.z.record(t.z.string(),t.z.unknown()),f]).describe(`Data Engine query filter conditions`)),aa=n(()=>t.z.union([t.z.record(t.z.string(),t.z.enum([`asc`,`desc`])),t.z.record(t.z.string(),t.z.union([t.z.literal(1),t.z.literal(-1)])),t.z.array(T)]).describe(`Sort order definition`)),Y=n(()=>t.z.object({context:ia.partial().optional()})),oa=n(()=>Y.extend({where:t.z.union([t.z.record(t.z.string(),t.z.unknown()),f]).optional(),fields:t.z.array(D).optional(),orderBy:t.z.array(T).optional(),limit:t.z.number().optional(),offset:t.z.number().optional(),top:t.z.number().optional(),cursor:w(k),search:oe.optional(),searchFields:t.z.array(t.z.string()).optional(),expand:t.z.lazy(()=>t.z.record(t.z.string(),j)).optional(),distinct:w(A)}).describe(`QueryAST-aligned query options for IDataEngine.find() operations`)),sa=n(()=>Y.extend({filter:J.optional(),select:t.z.array(t.z.string()).optional(),sort:aa.optional(),limit:t.z.number().int().min(1).optional(),skip:t.z.number().int().min(0).optional(),top:t.z.number().int().min(1).optional(),populate:t.z.array(t.z.string()).optional()}).describe(`Query options for IDataEngine.find() operations`)),ca=n(()=>Y.extend({returning:t.z.boolean().default(!0).optional()}).describe(`Options for DataEngine.insert operations`)),la=n(()=>Y.extend({where:t.z.union([t.z.record(t.z.string(),t.z.unknown()),f]).optional(),upsert:t.z.boolean().default(!1).optional(),multi:t.z.boolean().default(!1).optional(),returning:t.z.boolean().default(!1).optional()}).describe(`QueryAST-aligned options for DataEngine.update operations`)),ua=n(()=>t.z.object({object:t.z.string().describe(`Object the write targeted (resolved object name)`),fields:t.z.array(t.z.string()).describe(`Caller-supplied field names the engine removed from the write payload`),reason:t.z.enum([`readonly`,`readonly_when`]).describe(`Why the fields were dropped: static readonly (#2948) or a TRUE readonlyWhen predicate (#3042)`)}).describe(`A write-path strip event: caller-supplied fields legally dropped from the payload (#3407)`)),da=n(()=>Y.extend({filter:J.optional(),upsert:t.z.boolean().default(!1).optional(),multi:t.z.boolean().default(!1).optional(),returning:t.z.boolean().default(!1).optional()}).describe(`Options for DataEngine.update operations`)),fa=n(()=>Y.extend({where:t.z.union([t.z.record(t.z.string(),t.z.unknown()),f]).optional(),multi:t.z.boolean().default(!1).optional()}).describe(`QueryAST-aligned options for DataEngine.delete operations`)),pa=n(()=>Y.extend({filter:J.optional(),multi:t.z.boolean().default(!1).optional()}).describe(`Options for DataEngine.delete operations`)),ma=n(()=>Y.extend({where:t.z.union([t.z.record(t.z.string(),t.z.unknown()),f]).optional(),groupBy:t.z.array(t.z.string()).optional(),aggregations:t.z.array(re).optional(),having:f.optional().describe(`HAVING — filter over the aggregated rows (aggregation aliases + groupBy projections); applied engine-side after aggregation`),timezone:t.z.string().optional()}).describe(`QueryAST-aligned options for DataEngine.aggregate operations`)),ha=n(()=>Y.extend({filter:J.optional(),groupBy:t.z.array(t.z.string()).optional(),aggregations:t.z.array(t.z.object({field:t.z.string(),method:t.z.enum([`count`,`sum`,`avg`,`min`,`max`,`count_distinct`]),alias:t.z.string().optional()})).optional()}).describe(`Options for DataEngine.aggregate operations`)),ga=n(()=>Y.extend({where:t.z.union([t.z.record(t.z.string(),t.z.unknown()),f]).optional()}).describe(`QueryAST-aligned options for DataEngine.count operations`)),_a=n(()=>Y.extend({filter:J.optional()}).describe(`Options for DataEngine.count operations`)),va=n(()=>t.z.object({find:t.z.function().input(t.z.tuple([t.z.string(),oa.optional()])).output(t.z.promise(t.z.array(t.z.unknown()))),findOne:t.z.function().input(t.z.tuple([t.z.string(),oa.optional()])).output(t.z.promise(t.z.unknown())),insert:t.z.function().input(t.z.tuple([t.z.string(),t.z.union([t.z.record(t.z.string(),t.z.unknown()),t.z.array(t.z.record(t.z.string(),t.z.unknown()))]),ca.optional()])).output(t.z.promise(t.z.unknown())),update:t.z.function().input(t.z.tuple([t.z.string(),t.z.record(t.z.string(),t.z.unknown()),la.optional()])).output(t.z.promise(t.z.unknown())),delete:t.z.function().input(t.z.tuple([t.z.string(),fa.optional()])).output(t.z.promise(t.z.unknown())),count:t.z.function().input(t.z.tuple([t.z.string(),ga.optional()])).output(t.z.promise(t.z.number())),aggregate:t.z.function().input(t.z.tuple([t.z.string(),ma])).output(t.z.promise(t.z.array(t.z.unknown())))}).describe(`Standard Data Engine Contract`)),ya=[{canonical:`where`,aliases:[`filter`]},{canonical:`fields`,aliases:[`select`]},{canonical:`orderBy`,aliases:[`sort`]},{canonical:`offset`,aliases:[`skip`]},{canonical:`expand`,aliases:[`populate`]},{canonical:`limit`,aliases:[`top`]}];function ba(e,t,n){let r={};for(let i of t){let t=[i.canonical,...i.aliases],a=t.filter(t=>e[t]!=null);if(a.length>1&&new Set(a.map(t=>JSON.stringify(e[t]))).size>1){n({canonical:i.canonical,spellings:a});continue}if(a.length>0){let t=e[a[0]];e[i.canonical]=t,r[i.canonical]=a[0]}for(let n of t)n!==i.canonical&&delete e[n]}return r}var xa=ya.filter(e=>e.canonical===`where`);function Sa(e){return{code:`custom`,path:[e.canonical],message:`Conflicting query parameters: ${e.spellings.map(e=>`'${e}'`).join(`, `)} are spellings of the same parameter (canonical '${e.canonical}') and were given different values. Send exactly one.`}}var X={filter:J.optional()};function Ca(e,t){let n={...e};return ba(n,xa,e=>t.addIssue(Sa(e))),n}function wa(e,t){let n={...e};return ba(n,ya,e=>t.addIssue(Sa(e))),n.orderBy!==void 0&&n.orderBy!==null&&!Array.isArray(n.orderBy)&&(n.orderBy=Object.entries(n.orderBy).map(([e,t])=>({field:e,order:t===`asc`||t===1?`asc`:`desc`}))),Array.isArray(n.expand)&&(n.expand=Object.fromEntries(n.expand.map(e=>[e,{object:e}]))),n}var Ta=oa.extend({...X,select:t.z.array(t.z.string()).optional(),sort:aa.optional(),skip:t.z.number().int().min(0).optional(),populate:t.z.array(t.z.string()).optional()}).transform((e,t)=>wa(e,t)),Ea=n(()=>t.z.object({method:t.z.literal(`find`),object:t.z.string(),query:Ta.optional()})),Da=n(()=>t.z.object({method:t.z.literal(`findOne`),object:t.z.string(),query:Ta.optional()})),Oa=n(()=>t.z.object({method:t.z.literal(`insert`),object:t.z.string(),data:t.z.union([t.z.record(t.z.string(),t.z.unknown()),t.z.array(t.z.record(t.z.string(),t.z.unknown()))]),options:ca.optional()})),ka=n(()=>t.z.object({method:t.z.literal(`update`),object:t.z.string(),data:t.z.record(t.z.string(),t.z.unknown()),id:t.z.union([t.z.string(),t.z.number()]).optional().describe(`ID for single update, or use where in options`),options:la.extend(X).transform((e,t)=>Ca(e,t)).optional()})),Aa=n(()=>t.z.object({method:t.z.literal(`delete`),object:t.z.string(),id:t.z.union([t.z.string(),t.z.number()]).optional().describe(`ID for single delete, or use where in options`),options:fa.extend(X).transform((e,t)=>Ca(e,t)).optional()})),ja=n(()=>t.z.object({method:t.z.literal(`count`),object:t.z.string(),query:ga.extend(X).transform((e,t)=>Ca(e,t)).optional()})),Ma=n(()=>t.z.object({method:t.z.literal(`aggregate`),object:t.z.string(),query:ma.extend(X).transform((e,t)=>Ca(e,t))})),Na=n(()=>t.z.object({method:t.z.literal(`execute`),command:t.z.unknown(),options:t.z.record(t.z.string(),t.z.unknown()).optional()})),Pa=n(()=>t.z.object({method:t.z.literal(`vectorFind`),object:t.z.string(),vector:t.z.array(t.z.number()),where:t.z.union([t.z.record(t.z.string(),t.z.unknown()),f]).optional(),fields:t.z.array(t.z.string()).optional(),limit:t.z.number().int().default(5).optional(),threshold:t.z.number().optional()})),Fa=n(()=>t.z.object({method:t.z.literal(`batch`),requests:t.z.array(t.z.discriminatedUnion(`method`,[Ea,Da,Oa,ka,Aa,ja,Ma,Na,Pa])),transaction:t.z.boolean().default(!0).optional()})),Ia=n(()=>t.z.discriminatedUnion(`method`,[Ea,Da,Oa,ka,Aa,ja,Ma,Fa,Na,Pa]).describe(`Virtual ObjectQL Request Protocol`)),La=t.z.enum([`asc`,`desc`]).describe(`Sort order direction`);n(()=>t.z.object({field:t.z.string().describe(`Field name to sort by`),order:La.describe(`Sort direction`)}).describe(`Sort field and direction pair`)),t.z.enum([`insert`,`update`,`delete`,`upsert`]).describe(`Data mutation event types`);var Ra=t.z.enum([`read_uncommitted`,`read_committed`,`repeatable_read`,`serializable`,`snapshot`]).describe(`Transaction isolation levels (snake_case standard)`);t.z.enum([`lru`,`lfu`,`ttl`,`fifo`]).describe(`Cache eviction strategy`);var Z=n(()=>t.z.object({transaction:t.z.unknown().optional().describe(`Transaction handle`),timeout:t.z.number().optional().describe(`Timeout in ms`),skipCache:t.z.boolean().optional().describe(`Bypass cache`),traceContext:t.z.record(t.z.string(),t.z.string()).optional().describe(`OpenTelemetry context or request ID`),tenantId:t.z.string().optional().describe(`Tenant Isolation identifier`),tenantIds:t.z.array(t.z.string()).optional().describe(`Union tenant access set (group posture): native read scoping widens to organization_id IN (...); inserts still stamp from tenantId`),timezone:t.z.string().optional().describe(`Business reference timezone (IANA) for date-dependent generation, e.g. autonumber date tokens`),preserveAudit:t.z.boolean().optional().describe(`Historical import: keep a supplied updated_at instead of force-stamping now (from ExecutionContext.preserveAudit)`),bypassTenantAudit:t.z.boolean().optional().describe(`Suppress the driver tenant-audit warning for a deliberately global write on a tenant-scoped object (diagnostics only — never changes what the write touches)`)})),za=n(()=>t.z.object({create:t.z.boolean().default(!0).describe(`Supports CREATE operations`),read:t.z.boolean().default(!0).describe(`Supports READ operations`),update:t.z.boolean().default(!0).describe(`Supports UPDATE operations`),delete:t.z.boolean().default(!0).describe(`Supports DELETE operations`),bulkCreate:t.z.boolean().default(!1).describe(`Supports bulk CREATE operations`),bulkUpdate:t.z.boolean().default(!1).describe(`Supports bulk UPDATE operations`),bulkDelete:t.z.boolean().default(!1).describe(`Supports bulk DELETE operations`),transactions:t.z.boolean().default(!1).describe(`Supports ACID transactions`),savepoints:t.z.boolean().default(!1).describe(`Supports transaction savepoints`),isolationLevels:t.z.array(Ra).optional().describe(`Supported isolation levels`),queryFilters:t.z.boolean().default(!0).describe(`Supports WHERE clause filtering`),queryAggregations:t.z.boolean().default(!1).describe(`Supports GROUP BY and aggregation functions`),queryDateGranularity:t.z.record(E,t.z.boolean()).optional().describe(`Per-granularity native date bucketing (day/week/month/quarter/year). Missing keys fall back to in-memory bucketing.`),querySorting:t.z.boolean().default(!0).describe(`Supports ORDER BY sorting`),queryPagination:t.z.boolean().default(!0).describe(`Supports LIMIT/OFFSET pagination`),queryWindowFunctions:t.z.boolean().default(!1).describe(`Supports window functions with OVER clause`),querySubqueries:t.z.boolean().default(!1).describe(`Supports subqueries`),queryCTE:t.z.boolean().default(!1).describe(`Supports Common Table Expressions (WITH clause)`),joins:t.z.boolean().default(!1).describe(`Supports SQL joins`),fullTextSearch:t.z.boolean().default(!1).describe(`Supports full-text search`),jsonQuery:t.z.boolean().default(!1).describe(`Supports JSON field querying`),geospatialQuery:t.z.boolean().default(!1).describe(`Supports geospatial queries`),streaming:t.z.boolean().default(!1).describe(`Supports result streaming (cursors/iterators)`),jsonFields:t.z.boolean().default(!1).describe(`Supports JSON field types`),arrayFields:t.z.boolean().default(!1).describe(`Supports array field types`),vectorSearch:t.z.boolean().default(!1).describe(`Supports vector embeddings and similarity search`),autonumber:t.z.boolean().optional().describe(`Driver natively generates persistent autonumber/sequence values`),schemaSync:t.z.boolean().default(!1).describe(`Supports automatic schema synchronization`),batchSchemaSync:t.z.boolean().default(!1).describe(`Supports batched schema sync to reduce schema DDL round-trips`),migrations:t.z.boolean().default(!1).describe(`Supports database migrations`),indexes:t.z.boolean().default(!1).describe(`Supports index creation and management`),connectionPooling:t.z.boolean().default(!1).describe(`Supports connection pooling`),preparedStatements:t.z.boolean().default(!1).describe(`Supports prepared statements (SQL injection prevention)`),queryCache:t.z.boolean().default(!1).describe(`Supports query result caching`)})),Ba=n(()=>t.z.object({name:t.z.string().describe(`Driver unique name`),version:t.z.string().describe(`Driver version`),supports:za,connect:t.z.function().input(t.z.tuple([])).output(t.z.promise(t.z.void())).describe(`Establish connection`),disconnect:t.z.function().input(t.z.tuple([])).output(t.z.promise(t.z.void())).describe(`Close connection`),checkHealth:t.z.function().input(t.z.tuple([])).output(t.z.promise(t.z.boolean())).describe(`Health check`),getPoolStats:t.z.function().input(t.z.tuple([])).output(t.z.object({total:t.z.number(),idle:t.z.number(),active:t.z.number(),waiting:t.z.number()}).optional()).optional().describe(`Get connection pool statistics`),execute:t.z.function().input(t.z.tuple([t.z.unknown(),t.z.array(t.z.unknown()).optional(),Z.optional()])).output(t.z.promise(t.z.unknown())).describe(`Execute raw command`),find:t.z.function().input(t.z.tuple([t.z.string(),j,Z.optional()])).output(t.z.promise(t.z.array(t.z.record(t.z.string(),t.z.unknown())))).describe(`Find records`),findStream:t.z.function().input(t.z.tuple([t.z.string(),j,Z.optional()])).output(t.z.unknown()).describe(`Stream records (AsyncIterable)`),findOne:t.z.function().input(t.z.tuple([t.z.string(),j,Z.optional()])).output(t.z.promise(t.z.record(t.z.string(),t.z.unknown()).nullable())).describe(`Find one record`),create:t.z.function().input(t.z.tuple([t.z.string(),t.z.record(t.z.string(),t.z.unknown()),Z.optional()])).output(t.z.promise(t.z.record(t.z.string(),t.z.unknown()))).describe(`Create record`),update:t.z.function().input(t.z.tuple([t.z.string(),t.z.string().or(t.z.number()),t.z.record(t.z.string(),t.z.unknown()),Z.optional()])).output(t.z.promise(t.z.record(t.z.string(),t.z.unknown()))).describe(`Update record`),upsert:t.z.function().input(t.z.tuple([t.z.string(),t.z.record(t.z.string(),t.z.unknown()),t.z.array(t.z.string()).optional(),Z.optional()])).output(t.z.promise(t.z.record(t.z.string(),t.z.unknown()))).describe(`Upsert record`),delete:t.z.function().input(t.z.tuple([t.z.string(),t.z.string().or(t.z.number()),Z.optional()])).output(t.z.promise(t.z.boolean())).describe(`Delete record`),count:t.z.function().input(t.z.tuple([t.z.string(),j.optional(),Z.optional()])).output(t.z.promise(t.z.number())).describe(`Count records`),bulkCreate:t.z.function().input(t.z.tuple([t.z.string(),t.z.array(t.z.record(t.z.string(),t.z.unknown())),Z.optional()])).output(t.z.promise(t.z.array(t.z.record(t.z.string(),t.z.unknown())))),bulkUpdate:t.z.function().input(t.z.tuple([t.z.string(),t.z.array(t.z.object({id:t.z.string().or(t.z.number()),data:t.z.record(t.z.string(),t.z.unknown())})),Z.optional()])).output(t.z.promise(t.z.array(t.z.record(t.z.string(),t.z.unknown())))),bulkDelete:t.z.function().input(t.z.tuple([t.z.string(),t.z.array(t.z.string().or(t.z.number())),Z.optional()])).output(t.z.promise(t.z.void())),updateMany:t.z.function().input(t.z.tuple([t.z.string(),j,t.z.record(t.z.string(),t.z.unknown()),Z.optional()])).output(t.z.promise(t.z.number())).optional(),deleteMany:t.z.function().input(t.z.tuple([t.z.string(),j,Z.optional()])).output(t.z.promise(t.z.number())).optional(),beginTransaction:t.z.function().input(t.z.tuple([t.z.object({isolationLevel:Ra.optional()}).optional()])).output(t.z.promise(t.z.unknown())).describe(`Start transaction`),commit:t.z.function().input(t.z.tuple([t.z.unknown()])).output(t.z.promise(t.z.void())).describe(`Commit transaction`),rollback:t.z.function().input(t.z.tuple([t.z.unknown()])).output(t.z.promise(t.z.void())).describe(`Rollback transaction`),syncSchema:t.z.function().input(t.z.tuple([t.z.string(),t.z.unknown(),Z.optional()])).output(t.z.promise(t.z.void())).describe(`Sync object schema to DB`),syncSchemasBatch:t.z.function().input(t.z.tuple([t.z.array(t.z.object({object:t.z.string(),schema:t.z.unknown()})),Z.optional()])).output(t.z.promise(t.z.void())).optional().describe(`Batch sync multiple schemas in one round-trip`),dropTable:t.z.function().input(t.z.tuple([t.z.string(),Z.optional()])).output(t.z.promise(t.z.void())),explain:t.z.function().input(t.z.tuple([t.z.string(),j,Z.optional()])).output(t.z.promise(t.z.unknown())).optional()})),Va=n(()=>t.z.object({min:t.z.number().min(0).default(2).describe(`Minimum number of connections in pool`),max:t.z.number().min(1).default(10).describe(`Maximum number of connections in pool`),idleTimeoutMillis:t.z.number().min(0).default(3e4).describe(`Time in ms before idle connection is closed`),connectionTimeoutMillis:t.z.number().min(0).default(5e3).describe(`Time in ms to wait for available connection`)})),Ha=n(()=>t.z.object({name:t.z.string().describe(`Driver instance name`),type:t.z.enum([`sql`,`nosql`,`cache`,`search`,`graph`,`timeseries`]).describe(`Driver type category`),capabilities:za.describe(`Driver capability flags`),connectionString:t.z.string().optional().describe(`Database connection string (driver-specific format)`),poolConfig:Va.optional().describe(`Connection pool configuration`)})),Ua=n(()=>t.z.enum([`postgresql`,`mysql`,`sqlite`,`mssql`,`oracle`,`mariadb`])),Wa=n(()=>t.z.object({text:t.z.string().describe(`SQL type for text fields (e.g., VARCHAR, TEXT)`),number:t.z.string().describe(`SQL type for number fields (e.g., NUMERIC, DECIMAL, INT)`),boolean:t.z.string().describe(`SQL type for boolean fields (e.g., BOOLEAN, BIT)`),date:t.z.string().describe(`SQL type for date fields (e.g., DATE)`),datetime:t.z.string().describe(`SQL type for datetime fields (e.g., TIMESTAMP, DATETIME)`),json:t.z.string().optional().describe(`SQL type for JSON fields (e.g., JSON, JSONB)`),uuid:t.z.string().optional().describe(`SQL type for UUID fields (e.g., UUID, CHAR(36))`),binary:t.z.string().optional().describe(`SQL type for binary fields (e.g., BLOB, BYTEA)`)})),Ga=n(()=>t.z.object({rejectUnauthorized:t.z.boolean().default(!0).describe(`Reject connections with invalid certificates`),ca:t.z.string().optional().describe(`CA certificate file path or content`),cert:t.z.string().optional().describe(`Client certificate file path or content`),key:t.z.string().optional().describe(`Client private key file path or content`)}).refine(e=>e.cert!==void 0==(e.key!==void 0),{message:`Client certificate (cert) and private key (key) must be provided together`})),Ka=n(()=>Ha.extend({type:t.z.literal(`sql`).describe(`Driver type must be "sql"`),dialect:Ua.describe(`SQL database dialect`),dataTypeMapping:Wa.describe(`SQL data type mapping configuration`),ssl:t.z.boolean().default(!1).describe(`Enable SSL/TLS connection`),sslConfig:Ga.optional().describe(`SSL/TLS configuration (required when ssl is true)`)}).refine(e=>!(e.ssl&&!e.sslConfig),{message:`sslConfig is required when ssl is true`})),qa={text:`TEXT`,number:`REAL`,boolean:`INTEGER`,date:`TEXT`,datetime:`TEXT`,json:`TEXT`,uuid:`TEXT`,binary:`BLOB`},Ja={supportsAddColumn:!0,supportsRenameColumn:!0,supportsDropColumn:!0,supportsModifyColumn:!1,supportsAddConstraint:!1,rebuildStrategy:`create_copy_drop_rename`},Ya=n(()=>t.z.enum([`mongodb`,`couchdb`,`dynamodb`,`cassandra`,`redis`,`elasticsearch`,`neo4j`,`orientdb`])),Xa=n(()=>t.z.enum([`find`,`findOne`,`insert`,`update`,`delete`,`aggregate`,`mapReduce`,`count`,`distinct`,`createIndex`,`dropIndex`])),Za=n(()=>t.z.enum([`all`,`quorum`,`one`,`local_quorum`,`each_quorum`,`eventual`])),Qa=n(()=>t.z.enum([`single`,`compound`,`unique`,`text`,`geospatial`,`hashed`,`ttl`,`sparse`])),$a=n(()=>t.z.object({enabled:t.z.boolean().default(!1).describe(`Enable sharding`),shardKey:t.z.string().optional().describe(`Field to use as shard key`),shardingStrategy:t.z.enum([`hash`,`range`,`zone`]).optional().describe(`Sharding strategy`),numShards:t.z.number().int().positive().optional().describe(`Number of shards`)})),eo=n(()=>t.z.object({enabled:t.z.boolean().default(!1).describe(`Enable replication`),replicaSetName:t.z.string().optional().describe(`Replica set name`),replicas:t.z.number().int().positive().optional().describe(`Number of replicas`),readPreference:t.z.enum([`primary`,`primaryPreferred`,`secondary`,`secondaryPreferred`,`nearest`]).optional().describe(`Read preference for replica set`),writeConcern:t.z.enum([`majority`,`acknowledged`,`unacknowledged`]).optional().describe(`Write concern level`)})),to=n(()=>t.z.object({enabled:t.z.boolean().default(!1).describe(`Enable schema validation`),validationLevel:t.z.enum([`strict`,`moderate`,`off`]).optional().describe(`Validation strictness`),validationAction:t.z.enum([`error`,`warn`]).optional().describe(`Action on validation failure`),jsonSchema:t.z.record(t.z.string(),t.z.unknown()).optional().describe(`JSON Schema for validation`)})),no=n(()=>t.z.object({text:t.z.string().describe(`NoSQL type for text fields`),number:t.z.string().describe(`NoSQL type for number fields`),boolean:t.z.string().describe(`NoSQL type for boolean fields`),date:t.z.string().describe(`NoSQL type for date fields`),datetime:t.z.string().describe(`NoSQL type for datetime fields`),json:t.z.string().optional().describe(`NoSQL type for JSON/object fields`),uuid:t.z.string().optional().describe(`NoSQL type for UUID fields`),binary:t.z.string().optional().describe(`NoSQL type for binary fields`),array:t.z.string().optional().describe(`NoSQL type for array fields`),objectId:t.z.string().optional().describe(`NoSQL type for ObjectID fields (MongoDB)`),geopoint:t.z.string().optional().describe(`NoSQL type for geospatial point fields`)})),ro=n(()=>Ha.extend({type:t.z.literal(`nosql`).describe(`Driver type must be "nosql"`),databaseType:Ya.describe(`Specific NoSQL database type`),dataTypeMapping:no.describe(`NoSQL data type mapping configuration`),consistency:Za.optional().describe(`Consistency level for operations`),replication:eo.optional().describe(`Replication configuration`),sharding:$a.optional().describe(`Sharding configuration`),schemaValidation:to.optional().describe(`Document schema validation`),region:t.z.string().optional().describe(`AWS region (for managed NoSQL services)`),accessKeyId:t.z.string().optional().describe(`AWS access key ID`),secretAccessKey:t.z.string().optional().describe(`AWS secret access key`),ttlField:t.z.string().optional().describe(`Field name for TTL (auto-deletion)`),maxDocumentSize:t.z.number().int().positive().optional().describe(`Maximum document size in bytes`),collectionPrefix:t.z.string().optional().describe(`Prefix for collection/table names`)})),io=n(()=>t.z.object({consistency:Za.optional().describe(`Consistency level override`),readFromSecondary:t.z.boolean().optional().describe(`Allow reading from secondary replicas`),projection:t.z.record(t.z.string(),t.z.union([t.z.literal(0),t.z.literal(1)])).optional().describe(`Field projection`),timeout:t.z.number().int().positive().optional().describe(`Query timeout (ms)`),useCursor:t.z.boolean().optional().describe(`Use cursor instead of loading all results`),batchSize:t.z.number().int().positive().optional().describe(`Cursor batch size`),profile:t.z.boolean().optional().describe(`Enable query profiling`),hint:t.z.string().optional().describe(`Index hint for query optimization`)})),ao=n(()=>t.z.object({operator:t.z.string().describe(`Aggregation operator (e.g., $match, $group, $sort)`),options:t.z.record(t.z.string(),t.z.unknown()).describe(`Stage-specific options`)})),oo=n(()=>t.z.object({collection:t.z.string().describe(`Collection/table name`),stages:t.z.array(ao).describe(`Aggregation pipeline stages`),options:io.optional().describe(`Query options`)})),so=n(()=>t.z.object({name:t.z.string().describe(`Index name`),type:Qa.describe(`Index type`),fields:t.z.array(t.z.object({field:t.z.string().describe(`Field name`),order:t.z.enum([`asc`,`desc`,`text`,`2dsphere`]).optional().describe(`Index order or type`)})).describe(`Fields to index`),unique:t.z.boolean().default(!1).describe(`Enforce uniqueness`),sparse:t.z.boolean().default(!1).describe(`Sparse index`),expireAfterSeconds:t.z.number().int().positive().optional().describe(`TTL in seconds`),partialFilterExpression:t.z.record(t.z.string(),t.z.unknown()).optional().describe(`Partial index filter`),background:t.z.boolean().default(!1).describe(`Create index in background`)})),co=n(()=>t.z.object({readConcern:t.z.enum([`local`,`majority`,`linearizable`,`snapshot`]).optional().describe(`Read concern level`),writeConcern:t.z.enum([`majority`,`acknowledged`,`unacknowledged`]).optional().describe(`Write concern level`),readPreference:t.z.enum([`primary`,`primaryPreferred`,`secondary`,`secondaryPreferred`,`nearest`]).optional().describe(`Read preference`),maxCommitTimeMS:t.z.number().int().positive().optional().describe(`Transaction commit timeout (ms)`)})),lo=t.z.enum([`insert`,`update`,`upsert`,`replace`,`ignore`]),uo=n(()=>t.z.object({object:t.z.string().regex(/^[a-z_][a-z0-9_]*$/).describe(`Target Object Name`),externalId:t.z.union([t.z.string(),t.z.array(t.z.string()).min(1)]).default(`name`).describe(`Field (or composite list of fields) matched for the uniqueness check`),mode:lo.default(`upsert`).describe(`Conflict resolution strategy`),env:t.z.array(t.z.enum([`prod`,`dev`,`test`])).default([`prod`,`dev`,`test`]).describe(`Applicable environments`),records:t.z.array(t.z.record(t.z.string(),t.z.unknown())).describe(`Data records`)}));function fo(e,t){return uo.parse({...t,object:e.name})}var po=Jn({schemaId:`object`,type:`simple`,sections:[{name:`basics`,label:`Basics`,description:`Identity, labels, and taxonomy.`,columns:2,fields:[{field:`name`,type:`text`,required:!0,immutable:!0,colSpan:1,helpText:`snake_case unique identifier (immutable after creation)`},{field:`label`,type:`text`,colSpan:1,helpText:`Singular display name (e.g. "Account")`},{field:`pluralLabel`,type:`text`,colSpan:1,helpText:`Plural display name (e.g. "Accounts")`},{field:`icon`,type:`text`,colSpan:1,helpText:`Lucide icon name (e.g. "building", "users")`},{field:`description`,type:`textarea`,colSpan:2,helpText:`Developer documentation`},{field:`isSystem`,type:`boolean`,colSpan:1,helpText:`System object (protected from deletion; defaults sharing to public)`}]},{name:`fields`,label:`Fields`,description:`Define the data model — each entry becomes a column in the database table.`,fields:[{field:`fields`,type:`record`,required:!0,helpText:`Add the columns this object will store`,keyField:{field:`name`,label:`Name`,placeholder:`snake_case_identifier`,helpText:`snake_case machine name (used as column name and API key)`,regex:`^[a-z_][a-z0-9_]*$`,immutable:!0},fields:[{field:`label`,type:`text`,helpText:`Display label`},{field:`type`,type:`select`,required:!0,helpText:`Field type`,options:[{label:`Text`,value:`text`},{label:`Textarea`,value:`textarea`},{label:`Email`,value:`email`},{label:`URL`,value:`url`},{label:`Phone`,value:`phone`},{label:`Password`,value:`password`},{label:`Markdown`,value:`markdown`},{label:`HTML`,value:`html`},{label:`Rich Text`,value:`richtext`},{label:`Number`,value:`number`},{label:`Currency`,value:`currency`},{label:`Percent`,value:`percent`},{label:`Date`,value:`date`},{label:`Date & Time`,value:`datetime`},{label:`Time`,value:`time`},{label:`Boolean`,value:`boolean`},{label:`Toggle`,value:`toggle`},{label:`Select`,value:`select`},{label:`Multiselect`,value:`multiselect`},{label:`Radio`,value:`radio`},{label:`Checkboxes`,value:`checkboxes`},{label:`Lookup (reference)`,value:`lookup`},{label:`Master–Detail`,value:`master_detail`},{label:`Tree`,value:`tree`},{label:`Image`,value:`image`},{label:`File`,value:`file`},{label:`Avatar`,value:`avatar`},{label:`Video`,value:`video`},{label:`Audio`,value:`audio`},{label:`Formula (computed)`,value:`formula`},{label:`Summary (rollup)`,value:`summary`},{label:`Autonumber`,value:`autonumber`},{label:`Composite (embedded)`,value:`composite`},{label:`Repeater (embedded array)`,value:`repeater`},{label:`Record (keyed map)`,value:`record`},{label:`Location (GPS)`,value:`location`},{label:`Address`,value:`address`},{label:`Code`,value:`code`},{label:`JSON`,value:`json`},{label:`Color`,value:`color`},{label:`Rating`,value:`rating`},{label:`Slider`,value:`slider`},{label:`Signature`,value:`signature`},{label:`QR / Barcode`,value:`qrcode`},{label:`Progress`,value:`progress`},{label:`Tags`,value:`tags`},{label:`Vector embedding`,value:`vector`}]},{field:`description`,type:`textarea`,helpText:`Developer documentation for this column`},{field:`required`,type:`boolean`,helpText:`Must be set on every record`},{field:`unique`,type:`boolean`,helpText:`Disallow duplicate values`},{field:`readonly`,type:`boolean`,helpText:`Visible but never user-editable`},{field:`hidden`,type:`boolean`,helpText:`Hidden from default UI`},{field:`searchable`,type:`boolean`,helpText:`Include in full-text search`},{field:`sortable`,type:`boolean`,helpText:`Allow sorting on this column`},{field:`defaultValue`,type:`text`,helpText:`Default value for new records (JSON literal)`},{field:`maxLength`,type:`number`,helpText:`Max characters`,visibleWhen:`type in ['text','textarea','email','url','phone','password','markdown','html','richtext']`},{field:`minLength`,type:`number`,helpText:`Min characters`,visibleWhen:`type in ['text','textarea','email','url','phone','password','markdown','html','richtext']`},{field:`min`,type:`number`,helpText:`Minimum value`,visibleWhen:`type in ['number','currency','percent','rating','slider','progress']`},{field:`max`,type:`number`,helpText:`Maximum value`,visibleWhen:`type in ['number','currency','percent','rating','slider','progress']`},{field:`precision`,type:`number`,helpText:`Total digits`,visibleWhen:`type in ['number','currency','percent']`},{field:`scale`,type:`number`,helpText:`Decimal places`,visibleWhen:`type in ['number','currency','percent']`},{field:`options`,type:`repeater`,helpText:`Available choices`,visibleWhen:`type in ['select','multiselect','radio','checkboxes']`,fields:[{field:`label`,type:`text`,required:!0},{field:`value`,type:`text`,required:!0},{field:`color`,type:`color`},{field:`icon`,type:`text`,helpText:`Lucide icon name`},{field:`description`,type:`text`}]},{field:`reference`,type:`text`,helpText:`Target object name`,visibleWhen:`type in ['lookup','master_detail','tree']`},{field:`lookupFilters`,widget:`json`,helpText:`Filter rules applied to the picker ({field, operator, value})`,visibleWhen:`type in ['lookup','master_detail']`},{field:`deleteBehavior`,type:`select`,helpText:`What happens when the referenced record is deleted`,visibleWhen:`type in ['lookup','master_detail']`,options:[{label:`Set null`,value:`set_null`},{label:`Cascade (delete children)`,value:`cascade`},{label:`Restrict (block the delete)`,value:`restrict`}]},{field:`multiple`,type:`boolean`,helpText:`Allow selecting multiple records`,visibleWhen:`type in ['lookup']`},{field:`expression`,type:`code`,language:`expression`,helpText:`CEL formula expression`,visibleWhen:`type == 'formula'`},{field:`returnType`,type:`select`,helpText:`Result type for formulas`,visibleWhen:`type == 'formula'`,options:[{label:`Text`,value:`text`},{label:`Number`,value:`number`},{label:`Boolean`,value:`boolean`},{label:`Date`,value:`date`},{label:`Datetime`,value:`datetime`},{label:`Currency`,value:`currency`}]},{field:`summaryOperations`,type:`composite`,helpText:`Roll-up: which child object, which field, which aggregation`,visibleWhen:`type == 'summary'`,fields:[{field:`object`,type:`text`,required:!0,helpText:`Source child object name`},{field:`field`,type:`text`,required:!0,helpText:`Field on the child object to aggregate (ignored for count)`},{field:`function`,type:`select`,required:!0,helpText:`Aggregation function`,options:[{label:`Count`,value:`count`},{label:`Sum`,value:`sum`},{label:`Avg`,value:`avg`},{label:`Min`,value:`min`},{label:`Max`,value:`max`}]}]},{field:`autonumberFormat`,type:`text`,helpText:`e.g. "INV-{0000}"; date tokens {YYYY}/{MM}/{DD} and {field_name} interpolation supported`,visibleWhen:`type == 'autonumber'`},{field:`language`,type:`text`,helpText:`Editor language (e.g. sql, javascript)`,visibleWhen:`type == 'code'`},{field:`trackHistory`,type:`boolean`,helpText:`Summarize this field on the record activity timeline`},{field:`visibleWhen`,type:`code`,language:`expression`,helpText:`CEL predicate — field is shown only when TRUE`},{field:`readonlyWhen`,type:`code`,language:`expression`,helpText:`CEL predicate — field is read-only when TRUE (enforced server-side)`},{field:`requiredWhen`,type:`code`,language:`expression`,helpText:`CEL predicate — field is required when TRUE (enforced server-side)`}]}]},{name:`capabilities`,label:`Capabilities`,description:`System features and API exposure.`,collapsible:!0,collapsed:!0,fields:[{field:`enable`,type:`composite`,helpText:`Enable/disable system features`,fields:[{field:`trackHistory`,type:`boolean`},{field:`searchable`,type:`boolean`},{field:`apiEnabled`,type:`boolean`},{field:`files`,type:`boolean`},{field:`feeds`,type:`boolean`},{field:`activities`,type:`boolean`},{field:`clone`,type:`boolean`}]}]},{name:`advanced`,label:`Advanced`,description:`State machines, actions, and storage.`,collapsible:!0,collapsed:!0,fields:[{field:`datasource`,type:`text`,helpText:`Target datasource ID (default: "default")`},{field:`lifecycle`,type:`composite`,helpText:`Data lifecycle contract (ADR-0057): how long rows live and how space is reclaimed. Leave empty for permanent record semantics. Non-record classes require at least one bounding policy (retention, TTL, or rotation).`,fields:[{field:`class`,type:`select`,helpText:`Persistence contract for the rows of this object`,options:[{label:`Record (business truth — permanent)`,value:`record`},{label:`Audit (compliance ledger — retain → archive → delete)`,value:`audit`},{label:`Telemetry (high-frequency log — short retention)`,value:`telemetry`},{label:`Transient (ephemeral state — TTL expiry)`,value:`transient`},{label:`Event (bus messages — very short TTL)`,value:`event`}]},{field:`retention`,type:`composite`,helpText:`Age-based retention window`,fields:[{field:`maxAge`,type:`text`,helpText:`Rows older than this (by created_at) are reaped. Duration literal: h/d/w/y, e.g. "30d"`}]},{field:`ttl`,type:`composite`,helpText:`Per-row TTL expiry`,fields:[{field:`field`,type:`text`,helpText:`Timestamp field the TTL is measured from (e.g. expires_at)`},{field:`expireAfter`,type:`text`,helpText:`Rows expire this long after the field, e.g. "1d"`}]},{field:`storage`,type:`composite`,helpText:`Physical rotation for high-frequency telemetry (SQLite: O(1) shard DROP)`,fields:[{field:`strategy`,type:`select`,helpText:`Storage strategy`,options:[{label:`Rotation (time-shard + drop oldest)`,value:`rotation`}]},{field:`shards`,type:`number`,min:2,helpText:`Shards retained; total window = shards × unit`},{field:`unit`,type:`select`,helpText:`Time width of one shard`,options:[{label:`Day`,value:`day`},{label:`Week`,value:`week`},{label:`Month`,value:`month`}]}]},{field:`archive`,type:`composite`,helpText:`Cold-store hand-off (audit class). Rows are never hot-deleted before the archive copy succeeded.`,fields:[{field:`after`,type:`text`,helpText:`Archive rows older than this — must equal retention.maxAge`},{field:`to`,type:`text`,helpText:`Target datasource name for cold storage`},{field:`keep`,type:`text`,helpText:`How long the archive keeps rows (empty = forever), e.g. "7y"`}]},{field:`reclaim`,type:`boolean`,helpText:`Reclaim driver space after sweeps (default on for non-record classes)`}]}]}]}),mo=Jn({schemaId:`field`,type:`simple`,sections:[{name:`basics`,label:`Basics`,description:`Core field identity and constraints.`,columns:2,fields:[{field:`name`,required:!0,immutable:!0,colSpan:1,helpText:`Unique identifier (snake_case, immutable after creation)`},{field:`label`,required:!0,colSpan:1,helpText:`Display name for users`},{field:`type`,required:!0,colSpan:1,helpText:`Data type of this field`},{field:`group`,colSpan:1,helpText:`Group name for form layout`},{field:`description`,widget:`textarea`,colSpan:2,helpText:`Help text shown to users`},{field:`required`,colSpan:1,helpText:`User must provide a value`},{field:`unique`,colSpan:1,helpText:`No two records can have the same value`},{field:`multiple`,colSpan:1,helpText:`Allow multiple values (for select/lookup)`}]},{name:`configuration`,label:`Configuration`,description:`Field-type specific settings (visible blocks depend on the chosen type).`,fields:[{field:`defaultValue`,helpText:`Default value for new records`},{field:`minLength`,visibleWhen:`data.type == 'text' || data.type == 'textarea' || data.type == 'email'`,helpText:`Minimum character length`},{field:`maxLength`,visibleWhen:`data.type == 'text' || data.type == 'textarea' || data.type == 'email'`,helpText:`Maximum character length`},{field:`min`,visibleWhen:`data.type == 'number' || data.type == 'currency'`,helpText:`Minimum value`},{field:`max`,visibleWhen:`data.type == 'number' || data.type == 'currency'`,helpText:`Maximum value`},{field:`precision`,visibleWhen:`data.type == 'currency' || data.type == 'number'`,helpText:`Decimal places (e.g., 2 for $10.50)`},{field:`scale`,visibleWhen:`data.type == 'number'`,helpText:`Number of decimal digits`},{field:`options`,type:`repeater`,visibleWhen:`data.type == 'select' || data.type == 'multiselect'`,helpText:`Available options (label/value pairs)`},{field:`reference`,widget:`ref:object`,visibleWhen:`data.type == 'lookup' || data.type == 'master_detail'`,helpText:`Referenced object name`},{field:`deleteBehavior`,visibleWhen:`data.type == 'lookup' || data.type == 'master_detail'`,helpText:`What happens when referenced record is deleted`}]},{name:`formula`,label:`Formula & Computed`,description:`Calculated values and roll-up summaries.`,collapsible:!0,collapsed:!0,fields:[{field:`expression`,widget:`textarea`,helpText:`CEL expression to calculate this field (makes it read-only)`},{field:`summaryOperations`,type:`composite`,visibleWhen:`data.type == 'summary'`,helpText:`Roll-up summary configuration (for parent-child relationships)`,fields:[{field:`object`,widget:`ref:object`,required:!0,helpText:`Child object to aggregate`},{field:`function`,type:`select`,required:!0,options:[{label:`Count`,value:`count`},{label:`Sum`,value:`sum`},{label:`Min`,value:`min`},{label:`Max`,value:`max`},{label:`Average`,value:`avg`}],helpText:`Aggregation function`},{field:`field`,required:!0,helpText:`Child field to aggregate (ignored for count)`},{field:`relationshipField`,helpText:`Child FK back to this parent (auto-detected when omitted)`},{field:`filter`,widget:`filter-condition`,helpText:`Only child rows matching this predicate are aggregated (e.g. status == received)`}]}]},{name:`advanced`,label:`Advanced`,description:`Database, UI, audit, and security settings.`,collapsible:!0,collapsed:!0,columns:2,fields:[{field:`externalId`,colSpan:1,helpText:`Mark as external ID for upsert operations`},{field:`readonly`,colSpan:1,helpText:`Field is read-only in forms`},{field:`hidden`,colSpan:1,helpText:`Hide field from default UI views`},{field:`searchable`,colSpan:1,helpText:`Include in global search results`},{field:`sortable`,colSpan:1,helpText:`Allow sorting lists by this field`}]}]}),ho=Jn({schemaId:`hook`,type:`simple`,sections:[{label:`Identity`,description:`What this hook is and when it fires.`,columns:2,fields:[{field:`name`,type:`text`,required:!0,immutable:!0,colSpan:1,helpText:`snake_case identifier (immutable after creation)`},{field:`label`,type:`text`,colSpan:1},{field:`description`,type:`textarea`,colSpan:2},{field:`object`,type:`text`,required:!0,colSpan:1,helpText:`Target object name (or "*" for global)`},{field:`events`,type:`tags`,required:!0,colSpan:1,helpText:`Lifecycle events (e.g. beforeInsert, afterUpdate)`},{field:`priority`,type:`number`,colSpan:1,helpText:`Lower numbers run first`}]},{label:`Body`,description:`Inline expression or sandboxed JavaScript executed when the hook fires.`,fields:[{field:`body`,type:`composite`,helpText:`Either an L1 expression or an L2 sandboxed JS body`,fields:[{field:`language`,type:`select`,required:!0,helpText:`expression = pure formula; js = sandboxed JavaScript`,options:[{label:`Expression (L1)`,value:`expression`},{label:`JavaScript (L2 sandboxed)`,value:`js`}]},{field:`source`,type:`code`,language:`javascript`,required:!0,helpText:`Function body source — no top-level imports`},{field:`capabilities`,type:`tags`,helpText:`Allowed ctx APIs (api.read, api.write, crypto.uuid, log, …)`},{field:`timeoutMs`,type:`number`,helpText:`Per-invocation timeout (ms)`},{field:`memoryMb`,type:`number`,helpText:`Per-invocation memory cap (MB, max 256)`}]}]},{label:`Legacy handler`,description:`Function name reference — deprecated in favour of body.`,collapsible:!0,collapsed:!0,fields:[{field:`handler`,type:`text`,helpText:"Handler function name (deprecated — prefer `body`)"}]},{label:`Execution`,collapsible:!0,collapsed:!0,columns:2,fields:[{field:`async`,type:`boolean`,colSpan:1,helpText:`Run in background, do not block the transaction`},{field:`onError`,type:`select`,colSpan:1,options:[{label:`Abort`,value:`abort`},{label:`Log`,value:`log`}]},{field:`timeout`,type:`number`,colSpan:1,helpText:`Abort the hook after N milliseconds`},{field:`condition`,type:`code`,language:`javascript`,colSpan:2,helpText:`Optional formula — skip the hook when this evaluates to false`},{field:`retryPolicy`,type:`composite`,colSpan:2,helpText:`Retry on failure — most useful for async hooks`,fields:[{field:`maxRetries`,type:`number`,helpText:`Maximum retry attempts`},{field:`backoffMs`,type:`number`,helpText:`Delay between retries (ms)`}]}]}]}),go=n(()=>t.z.object({field:t.z.string().describe(`Source field name containing the reference value`),targetObject:t.z.string().regex(/^[a-z_][a-z0-9_]*$/).describe(`Target object name (snake_case)`),targetField:t.z.string().default(`name`).describe(`Field on target object used for matching`),fieldType:t.z.enum([`lookup`,`master_detail`,`user`]).describe(`Relationship field type`),multiple:t.z.boolean().optional().describe(`Field stores an array of references (multiple: true)`)}).describe(`Describes how a field reference is resolved during seed loading`)),_o=n(()=>t.z.object({object:t.z.string().regex(/^[a-z_][a-z0-9_]*$/).describe(`Object name (snake_case)`),dependsOn:t.z.array(t.z.string()).describe(`Objects this object depends on`),references:t.z.array(go).describe(`Field-level reference details`)}).describe(`Object node in the seed data dependency graph`)),vo=n(()=>t.z.object({nodes:t.z.array(_o).describe(`All objects in the dependency graph`),insertOrder:t.z.array(t.z.string()).describe(`Topologically sorted insert order`),circularDependencies:t.z.array(t.z.array(t.z.string())).default([]).describe(`Circular dependency chains (e.g., [["a", "b", "a"]])`)}).describe(`Complete object dependency graph for seed data loading`)),yo=n(()=>t.z.object({sourceObject:t.z.string().describe(`Object with the broken reference`),field:t.z.string().describe(`Field name with unresolved reference`),targetObject:t.z.string().describe(`Target object searched for the reference`),targetField:t.z.string().describe(`ExternalId field used for matching`),attemptedValue:t.z.unknown().describe(`Value that failed to resolve`),recordIndex:t.z.number().int().min(0).describe(`Index of the record in the dataset`),message:t.z.string().describe(`Human-readable error description`)}).describe(`Actionable error for a failed reference resolution`)),bo=t.z.object({user:t.z.object({id:t.z.string().min(1),role:t.z.string().optional(),email:t.z.string().optional()}).optional().describe(`Subject bound to os.user in seed CEL expressions`),org:t.z.object({id:t.z.string().min(1),tier:t.z.string().optional()}).optional().describe(`Organization bound to os.org in seed CEL expressions`)}).describe(`Identity context for resolving os.user / os.org in seed CEL values`),xo=n(()=>t.z.object({dryRun:t.z.boolean().default(!1).describe(`Validate references without writing data`),haltOnError:t.z.boolean().default(!1).describe(`Stop on first reference resolution error`),multiPass:t.z.boolean().default(!0).describe(`Enable multi-pass loading for circular dependencies`),defaultMode:lo.default(`upsert`).describe(`Default conflict resolution strategy`),batchSize:t.z.number().int().min(1).default(1e3).describe(`Maximum records per batch insert/upsert`),transaction:t.z.boolean().default(!1).describe(`Wrap entire load in a transaction (all-or-nothing)`),env:t.z.enum([`prod`,`dev`,`test`]).optional().describe(`Only load datasets matching this environment`),organizationId:t.z.string().min(1).optional().describe(`Target organization id for per-tenant seed replay`),identity:bo.optional().describe(`Identity bound to os.user / os.org when resolving CEL seed values`)}).describe(`Seed data loader configuration`)),So=n(()=>t.z.object({object:t.z.string().describe(`Object that was loaded`),mode:lo.describe(`Import mode used`),inserted:t.z.number().int().min(0).describe(`Records inserted`),updated:t.z.number().int().min(0).describe(`Records updated`),skipped:t.z.number().int().min(0).describe(`Records skipped`),errored:t.z.number().int().min(0).describe(`Records with errors`),total:t.z.number().int().min(0).describe(`Total records in dataset`),referencesResolved:t.z.number().int().min(0).describe(`References resolved via externalId`),referencesDeferred:t.z.number().int().min(0).describe(`References deferred to second pass`),referencesDropped:t.z.number().int().min(0).default(0).describe(`Reference fields dropped from records that were still written`),errors:t.z.array(yo).default([]).describe(`Reference resolution errors`)}).describe(`Result of loading a single dataset`)),Co=n(()=>t.z.object({success:t.z.boolean().describe(`Overall success status`),dryRun:t.z.boolean().describe(`Whether this was a dry-run`),dependencyGraph:vo.describe(`Object dependency graph`),results:t.z.array(So).describe(`Per-object load results`),errors:t.z.array(yo).describe(`All reference resolution errors`),summary:t.z.object({objectsProcessed:t.z.number().int().min(0).describe(`Total objects processed`),totalRecords:t.z.number().int().min(0).describe(`Total records across all objects`),totalInserted:t.z.number().int().min(0).describe(`Total records inserted`),totalUpdated:t.z.number().int().min(0).describe(`Total records updated`),totalSkipped:t.z.number().int().min(0).describe(`Total records skipped`),totalErrored:t.z.number().int().min(0).describe(`Total records with errors`),totalReferencesResolved:t.z.number().int().min(0).describe(`Total references resolved`),totalReferencesDeferred:t.z.number().int().min(0).describe(`Total references deferred`),totalReferencesDropped:t.z.number().int().min(0).default(0).describe(`Total reference fields dropped from written records`),circularDependencyCount:t.z.number().int().min(0).describe(`Circular dependency chains detected`),durationMs:t.z.number().min(0).describe(`Load duration in milliseconds`)}).describe(`Summary statistics`)}).describe(`Complete seed loader result`)),wo=n(()=>t.z.object({seeds:t.z.array(uo).min(1).describe(`Seeds to load`),config:xo.default(()=>xo.parse({})).describe(`Loader configuration`)}).describe(`Seed loader request with datasets and configuration`)),To=n(()=>t.z.object({versionNumber:t.z.number().describe(`Version number`),createdAt:t.z.number().describe(`Creation timestamp`),createdBy:t.z.string().describe(`Creator user ID`),size:t.z.number().describe(`File size in bytes`),checksum:t.z.string().describe(`File checksum`),downloadUrl:t.z.string().url().describe(`Download URL`),isLatest:t.z.boolean().optional().default(!1).describe(`Is latest version`)})),Eo=n(()=>t.z.object({id:t.z.string().describe(`Template ID`),name:t.z.string().describe(`Template name`),description:t.z.string().optional().describe(`Template description`),fileUrl:t.z.string().url().describe(`Template file URL`),fileType:t.z.string().describe(`File MIME type`),placeholders:t.z.array(t.z.object({key:t.z.string().describe(`Placeholder key`),label:t.z.string().describe(`Placeholder label`),type:t.z.enum([`text`,`number`,`date`,`image`]).describe(`Placeholder type`),required:t.z.boolean().optional().default(!1).describe(`Is required`)})).describe(`Template placeholders`)})),Do=n(()=>t.z.object({provider:t.z.enum([`docusign`,`adobe-sign`,`hellosign`,`custom`]).describe(`E-signature provider`),enabled:t.z.boolean().optional().default(!1).describe(`E-signature enabled`),signers:t.z.array(t.z.object({email:t.z.string().email().describe(`Signer email`),name:t.z.string().describe(`Signer name`),role:t.z.string().describe(`Signer role`),order:t.z.number().describe(`Signing order`)})).describe(`Document signers`),expirationDays:t.z.number().optional().default(30).describe(`Expiration days`),reminderDays:t.z.number().optional().default(7).describe(`Reminder interval days`)})),Oo=n(()=>t.z.object({id:t.z.string().describe(`Document ID`),name:t.z.string().describe(`Document name`),description:t.z.string().optional().describe(`Document description`),fileType:t.z.string().describe(`File MIME type`),fileSize:t.z.number().describe(`File size in bytes`),category:t.z.string().optional().describe(`Document category`),tags:t.z.array(t.z.string()).optional().describe(`Document tags`),versioning:t.z.object({enabled:t.z.boolean().describe(`Versioning enabled`),versions:t.z.array(To).describe(`Version history`),majorVersion:t.z.number().describe(`Major version`),minorVersion:t.z.number().describe(`Minor version`)}).optional().describe(`Version control`),template:Eo.optional().describe(`Document template`),eSignature:Do.optional().describe(`E-signature config`),access:t.z.object({isPublic:t.z.boolean().optional().default(!1).describe(`Public access`),sharedWith:t.z.array(t.z.string()).optional().describe(`Shared with`),expiresAt:t.z.number().optional().describe(`Access expiration`)}).optional().describe(`Access control`),metadata:t.z.record(t.z.string(),t.z.unknown()).optional().describe(`Custom metadata`)})),ko=n(()=>t.z.discriminatedUnion(`type`,[t.z.object({type:t.z.literal(`constant`),value:t.z.unknown().describe(`Constant value to use`)}).describe(`Set a constant value`),t.z.object({type:t.z.literal(`cast`),targetType:t.z.enum([`string`,`number`,`boolean`,`date`]).describe(`Target data type`)}).describe(`Cast to a specific data type`),t.z.object({type:t.z.literal(`lookup`),table:t.z.string().describe(`Lookup table name`),keyField:t.z.string().describe(`Field to match on`),valueField:t.z.string().describe(`Field to retrieve`)}).describe(`Lookup value from another table`),t.z.object({type:t.z.literal(`javascript`),expression:L.describe(`JS expression (dialect="js" recommended). e.g. value.toUpperCase()`)}).describe(`Custom JavaScript transformation`),t.z.object({type:t.z.literal(`map`),mappings:t.z.record(t.z.string(),t.z.unknown()).describe(`Value mappings (e.g., {"Active": "active"})`)}).describe(`Map values using a dictionary`)])),Ao=n(()=>t.z.object({source:t.z.string().describe(`Source field name`),target:t.z.string().describe(`Target field name`),transform:ko.optional().describe(`Transformation to apply`),defaultValue:t.z.unknown().optional().describe(`Default if source is null/undefined`)})),jo=n(()=>t.z.object({id:t.z.string().describe(`Data source ID`),name:t.z.string().describe(`Data source name`),type:t.z.enum([`odata`,`rest-api`,`graphql`,`custom`]).describe(`Protocol type`),endpoint:t.z.string().url().describe(`API endpoint URL`),authentication:t.z.object({type:t.z.enum([`oauth2`,`api-key`,`basic`,`none`]).describe(`Auth type`),config:t.z.record(t.z.string(),t.z.unknown()).describe(`Auth configuration`)}).describe(`Authentication`)})),Mo=n(()=>Ao.extend({type:t.z.string().optional().describe(`Field type`),readonly:t.z.boolean().optional().default(!0).describe(`Read-only field`)})),No=n(()=>t.z.object({fieldName:t.z.string().describe(`Field name`),dataSource:jo.describe(`External data source`),query:t.z.object({endpoint:t.z.string().describe(`Query endpoint path`),method:t.z.enum([`GET`,`POST`]).optional().default(`GET`).describe(`HTTP method`),parameters:t.z.record(t.z.string(),t.z.unknown()).optional().describe(`Query parameters`)}).describe(`Query configuration`),fieldMappings:t.z.array(Mo).describe(`Field mappings`),caching:t.z.object({enabled:t.z.boolean().optional().default(!0).describe(`Cache enabled`),ttl:t.z.number().optional().default(300).describe(`Cache TTL (seconds)`),strategy:t.z.enum([`lru`,`lfu`,`ttl`]).optional().default(`ttl`).describe(`Cache strategy`)}).optional().describe(`Caching configuration`),fallback:t.z.object({enabled:t.z.boolean().optional().default(!0).describe(`Fallback enabled`),defaultValue:t.z.unknown().optional().describe(`Default fallback value`),showError:t.z.boolean().optional().default(!0).describe(`Show error to user`)}).optional().describe(`Fallback configuration`),rateLimit:t.z.object({requestsPerSecond:t.z.number().describe(`Requests per second limit`),burstSize:t.z.number().optional().describe(`Burst size`)}).optional().describe(`Rate limiting`),retry:t.z.object({maxRetries:t.z.number().min(0).default(3).describe(`Maximum retry attempts`),initialDelayMs:t.z.number().default(1e3).describe(`Initial retry delay in milliseconds`),maxDelayMs:t.z.number().default(3e4).describe(`Maximum retry delay in milliseconds`),backoffMultiplier:t.z.number().default(2).describe(`Exponential backoff multiplier`),retryableStatusCodes:t.z.array(t.z.number()).default([429,500,502,503,504]).describe(`HTTP status codes that are retryable`)}).optional().describe(`Retry configuration with exponential backoff`),transform:t.z.object({request:t.z.object({headers:t.z.record(t.z.string(),t.z.string()).optional().describe(`Additional request headers`),queryParams:t.z.record(t.z.string(),t.z.string()).optional().describe(`Additional query parameters`)}).optional().describe(`Request transformation`),response:t.z.object({dataPath:t.z.string().optional().describe(`JSONPath to extract data (e.g., "$.data.results")`),totalPath:t.z.string().optional().describe(`JSONPath to extract total count (e.g., "$.meta.total")`)}).optional().describe(`Response transformation`)}).optional().describe(`Request/response transformation pipeline`),pagination:t.z.object({type:t.z.enum([`offset`,`cursor`,`page`]).default(`offset`).describe(`Pagination type`),pageSize:t.z.number().default(100).describe(`Items per page`),maxPages:t.z.number().optional().describe(`Maximum number of pages to fetch`)}).optional().describe(`Pagination configuration for external data`)})),Po=[`id`,`label`,`description`,`icon`,`configSchema`,`capabilities`],Fo=[`label`,`allowedSchemas`,`allowWrites`,`validation`,`credentialsRef`,`queryTimeoutMs`,`requirePermission`],Io=[`onMismatch`,`checkOnBoot`,`checkIntervalMs`],Lo=[`name`,`label`,`driver`,`config`,`pool`,`readReplicas`,`capabilities`,`healthCheck`,`ssl`,`retryPolicy`,`description`,`active`,`autoConnect`,`schemaMode`,`external`,`origin`],Ro=[`min`,`max`,`idleTimeoutMillis`,`connectionTimeoutMillis`],zo=[`enabled`,`intervalMs`,`timeoutMs`],Bo=[`enabled`,`rejectUnauthorized`,`ca`,`cert`,`key`],Vo=[`maxRetries`,`baseDelayMs`,`maxDelayMs`,`backoffMultiplier`],Q=e=>`\`${e}\` is a driver connection detail \u2014 it belongs inside \`config\`, not at the top level. Move it to \`config: { ${e}: \u2026 }\`, matching your driver's config shape (\`PostgresConfigSchema\` / \`MongoConfigSchema\` / \`MemoryConfigSchema\` in \`data/driver/\`).`,Ho=V({surface:`this driver definition`,knownKeys:Po,aliases:{name:`id`,driver:`id`,title:`label`,config:`configSchema`,schema:`configSchema`,capability:`capabilities`},history:`Until #4001 these were dropped silently — the driver still registered.`}),Uo=V({surface:`this datasource's external settings`,knownKeys:Fo,aliases:{schemas:`allowedSchemas`,allowedschema:`allowedSchemas`,writable:`allowWrites`,allowwrite:`allowWrites`,credentials:`credentialsRef`,secretref:`credentialsRef`,timeoutms:`queryTimeoutMs`,querytimeout:`queryTimeoutMs`,permission:`requirePermission`},guidance:{password:'`password` must never be inlined. Put the secret in the secrets store and reference it with `credentialsRef` (e.g. `credentialsRef: "secret:warehouse/password"`).',readOnly:"`readOnly` is not an external-settings key. Use `allowWrites: false` here for the datasource-wide gate, or `capabilities.readOnly` to describe the driver."},history:`Until #4001 these were dropped silently — federation ran on the defaults instead.`}),Wo=V({surface:`this datasource's external validation policy`,knownKeys:Io,aliases:{onmismatch:`onMismatch`,mismatch:`onMismatch`,checkonboot:`checkOnBoot`,validateonboot:`checkOnBoot`,interval:`checkIntervalMs`,checkinterval:`checkIntervalMs`},history:`Until #4001 these were dropped silently — drift checking ran on the defaults (fail on mismatch, check at boot) regardless of what was written.`}),Go=V({surface:`this datasource`,knownKeys:Lo,aliases:{type:`driver`,connection:`config`,connectionconfig:`config`,options:`config`,enabled:`active`,pooling:`pool`,replicas:`readReplicas`,mode:`schemaMode`,schema_mode:`schemaMode`,federation:`external`,retry:`retryPolicy`,tls:`ssl`},guidance:{host:Q(`host`),port:Q(`port`),database:Q(`database`),user:Q(`user`),username:Q(`username`),filename:Q(`filename`),url:Q(`url`),connectionString:Q(`connectionString`),password:"`password` must never be inlined on a datasource. Interpolate it from the environment inside `config`, or for an external datasource reference the secrets store via `external.credentialsRef`."},history:`Until #4001 these were dropped silently — a connection key written one level too high left the datasource connecting on driver defaults rather than failing.`}),Ko=V({surface:`this datasource's pool config`,knownKeys:Ro,aliases:{minimum:`min`,maximum:`max`,minconnections:`min`,maxconnections:`max`,idletimeout:`idleTimeoutMillis`,idletimeoutms:`idleTimeoutMillis`,connectiontimeout:`connectionTimeoutMillis`,connectiontimeoutms:`connectionTimeoutMillis`,acquiretimeoutmillis:`connectionTimeoutMillis`},history:"Until #4001 these were dropped silently — the pool ran on its defaults (min 0, max 10) no matter what was written. Note both timeouts end in `Millis`, not `Ms`."}),qo=V({surface:`this datasource's healthCheck config`,knownKeys:zo,aliases:{active:`enabled`,interval:`intervalMs`,intervalmillis:`intervalMs`,timeout:`timeoutMs`,timeoutmillis:`timeoutMs`},history:`Until #4001 these were dropped silently — health checks ran on the defaults.`}),Jo=V({surface:`this datasource's ssl config`,knownKeys:Bo,aliases:{active:`enabled`,ssl:`enabled`,tls:`enabled`,rejectunauthorised:`rejectUnauthorized`,cacert:`ca`,certificate:`cert`,clientcert:`cert`,privatekey:`key`,clientkey:`key`},guidance:{insecure:"`insecure` is not an ssl key. To accept a self-signed certificate set `rejectUnauthorized: false` — deliberately, and never against a production database."},history:`Until #4001 these were dropped silently — which meant a TLS setting that never took effect looked identical to one that did.`}),Yo=V({surface:`this datasource's retryPolicy`,knownKeys:Vo,aliases:{retries:`maxRetries`,attempts:`maxRetries`,backoffms:`baseDelayMs`,basedelay:`baseDelayMs`,delayms:`baseDelayMs`,maxdelay:`maxDelayMs`,multiplier:`backoffMultiplier`,backoff:`backoffMultiplier`},history:"Until #4001 these were dropped silently — reconnects ran on the defaults. Note a hook retryPolicy spells its delay `backoffMs`; a datasource spells it `baseDelayMs`."}),Xo=V({surface:`these datasource capabilities`,knownKeys:[`transactions`,`queryFilters`,`queryAggregations`,`querySorting`,`queryPagination`,`queryWindowFunctions`,`querySubqueries`,`joins`,`fullTextSearch`,`readOnly`,`dynamicSchema`],aliases:{transaction:`transactions`,filters:`queryFilters`,filtering:`queryFilters`,aggregations:`queryAggregations`,aggregation:`queryAggregations`,sorting:`querySorting`,sort:`querySorting`,pagination:`queryPagination`,windowfunctions:`queryWindowFunctions`,subqueries:`querySubqueries`,join:`joins`,fulltext:`fullTextSearch`,search:`fullTextSearch`,readonly:`readOnly`,schemaless:`dynamicSchema`},history:`Until #4001 these were dropped silently — and a capability that fails to register reads as FALSE, so the engine quietly stopped pushing that work down to the driver and recomputed it in memory instead.`}),Zo=t.z.string().describe(`Underlying driver identifier`),Qo=n(()=>t.z.object({id:t.z.string().describe(`Unique driver identifier (e.g. "postgres")`),label:t.z.string().describe(`Display label (e.g. "PostgreSQL")`),description:t.z.string().optional(),icon:t.z.string().optional(),configSchema:t.z.record(t.z.string(),t.z.unknown()).describe(`JSON Schema for connection configuration`),capabilities:t.z.lazy(()=>$o).optional()},{error:Ho}).strict()),$o=t.z.object({transactions:t.z.boolean().default(!1),queryFilters:t.z.boolean().default(!1),queryAggregations:t.z.boolean().default(!1),querySorting:t.z.boolean().default(!1),queryPagination:t.z.boolean().default(!1),queryWindowFunctions:t.z.boolean().default(!1),querySubqueries:t.z.boolean().default(!1),joins:t.z.boolean().default(!1),fullTextSearch:t.z.boolean().default(!1),readOnly:t.z.boolean().default(!1),dynamicSchema:t.z.boolean().default(!1)},{error:Xo}).strict(),es=t.z.enum([`managed`,`external`,`validate-only`]).describe(`Schema ownership mode`),ts=t.z.object({label:t.z.string().optional().describe(`Display label, e.g. "Snowflake — ANALYTICS / PROD"`),allowedSchemas:t.z.array(t.z.string()).optional().describe(`Whitelist of remote schemas/databases that may be exposed.`),allowWrites:t.z.boolean().default(!1).describe(`Global write gate. Individual objects must also opt in via object.external.writable.`),validation:t.z.object({onMismatch:t.z.enum([`fail`,`warn`,`ignore`]).default(`fail`).describe(`What to do when a federated object diverges from the remote table.`),checkOnBoot:t.z.boolean().default(!0).describe(`Validate federated objects against the remote schema at boot.`),checkIntervalMs:t.z.number().optional().describe(`Optional background drift-check interval in milliseconds.`)},{error:Wo}).strict().default({onMismatch:`fail`,checkOnBoot:!0}).describe(`Boot/drift validation policy`),credentialsRef:t.z.string().optional().describe(`Reference into the secrets store; never inline credentials.`),queryTimeoutMs:t.z.number().default(3e4).describe(`Hard cap on per-query execution time.`),requirePermission:t.z.string().optional().describe(`Optional convenience: gate the entire datasource behind a single role.`)},{error:Uo}).strict().describe(`External datasource federation settings (schemaMode != "managed")`),ns=n(()=>t.z.object({name:t.z.string().regex(/^[a-z_][a-z0-9_]*$/).describe(`Unique datasource identifier`),label:t.z.string().optional().describe(`Display label`),driver:Zo.describe(`Underlying driver type`),config:t.z.record(t.z.string(),t.z.unknown()).describe(`Driver specific configuration`),pool:t.z.object({min:t.z.number().default(0).describe(`Minimum connections`),max:t.z.number().default(10).describe(`Maximum connections`),idleTimeoutMillis:t.z.number().default(3e4).describe(`Idle timeout`),connectionTimeoutMillis:t.z.number().default(3e3).describe(`Connection establishment timeout`)},{error:Ko}).strict().optional().describe(`Connection pool settings`),readReplicas:t.z.array(t.z.record(t.z.string(),t.z.unknown())).optional().describe(`Read-only replica configurations`),capabilities:$o.optional().describe(`Capability overrides`),healthCheck:t.z.object({enabled:t.z.boolean().default(!0).describe(`Enable health check endpoint`),intervalMs:t.z.number().default(3e4).describe(`Health check interval in milliseconds`),timeoutMs:t.z.number().default(5e3).describe(`Health check timeout in milliseconds`)},{error:qo}).strict().optional().describe(`Datasource health check configuration`),ssl:t.z.object({enabled:t.z.boolean().default(!1).describe(`Enable SSL/TLS for database connection`),rejectUnauthorized:t.z.boolean().default(!0).describe(`Reject connections with invalid/self-signed certificates`),ca:t.z.string().optional().describe(`CA certificate (PEM format or path to file)`),cert:t.z.string().optional().describe(`Client certificate (PEM format or path to file)`),key:t.z.string().optional().describe(`Client private key (PEM format or path to file)`)},{error:Jo}).strict().optional().describe(`SSL/TLS configuration for secure database connections`),retryPolicy:t.z.object({maxRetries:t.z.number().default(3).describe(`Maximum number of retry attempts`),baseDelayMs:t.z.number().default(1e3).describe(`Base delay between retries in milliseconds`),maxDelayMs:t.z.number().default(3e4).describe(`Maximum delay between retries in milliseconds`),backoffMultiplier:t.z.number().default(2).describe(`Exponential backoff multiplier`)},{error:Yo}).strict().optional().describe(`Connection retry policy for transient failures`),description:t.z.string().optional().describe(`Internal description`),active:t.z.boolean().default(!0).describe(`Is datasource enabled`),autoConnect:t.z.boolean().default(!1).describe(`Force a live driver connection at boot even when managed + unrouted (ADR-0062 D2).`),schemaMode:es.default(`managed`),external:ts.optional(),origin:t.z.enum([`code`,`runtime`]).default(`code`).describe(`Datasource provenance (server-managed, read-only)`)},{error:Go}).strict().superRefine((e,t)=>{e.schemaMode!==`managed`&&!e.external&&t.addIssue({code:`custom`,path:[`external`],message:`schemaMode='${e.schemaMode}' requires 'external' settings.`}),e.schemaMode===`managed`&&e.external&&t.addIssue({code:`custom`,path:[`external`],message:`'external' settings only apply when schemaMode != 'managed'.`})}));function rs(e){return ns.parse(e)}var is={postgres:{int2:`integer`,int4:`integer`,int8:`bigint`,serial:`integer`,bigserial:`bigint`,float4:`float`,float8:`float`,numeric:`decimal`,bool:`boolean`,timestamptz:`datetime`,timestamp:`datetime`,timetz:`time`,jsonb:`json`,json:`json`,uuid:`uuid`,bytea:`binary`,bpchar:`text`,citext:`text`,vector:`vector`},mysql:{tinyint:`integer`,smallint:`integer`,mediumint:`integer`,int:`integer`,bigint:`bigint`,double:`float`,real:`float`,decimal:`decimal`,datetime:`datetime`,timestamp:`datetime`,tinytext:`text`,mediumtext:`text`,longtext:`text`,json:`json`,blob:`binary`,longblob:`binary`,enum:`enum`},sqlite:{integer:`integer`,int:`integer`,real:`float`,numeric:`decimal`,text:`text`,blob:`binary`},snowflake:{number:`decimal`,int:`integer`,integer:`integer`,bigint:`bigint`,float:`float`,double:`float`,string:`text`,varchar:`text`,variant:`json`,object:`json`,array:`array`,boolean:`boolean`,timestamp_ntz:`datetime`,timestamp_tz:`datetime`,timestamp_ltz:`datetime`,binary:`binary`},bigquery:{int64:`bigint`,float64:`float`,numeric:`decimal`,bignumeric:`decimal`,string:`text`,bytes:`binary`,bool:`boolean`,boolean:`boolean`,timestamp:`datetime`,datetime:`datetime`,struct:`json`,json:`json`,array:`array`,record:`json`},mongo:{objectid:`text`,string:`text`,double:`float`,int:`integer`,long:`bigint`,decimal:`decimal`,bool:`boolean`,boolean:`boolean`,date:`datetime`,object:`json`,array:`array`,bindata:`binary`}},as={text:`text`,varchar:`text`,char:`text`,character:`text`,string:`text`,"character varying":`text`,nvarchar:`text`,nchar:`text`,clob:`text`,integer:`integer`,int:`integer`,smallint:`integer`,tinyint:`integer`,bigint:`bigint`,decimal:`decimal`,numeric:`decimal`,number:`decimal`,money:`decimal`,float:`float`,double:`float`,"double precision":`float`,real:`float`,boolean:`boolean`,bool:`boolean`,bit:`boolean`,date:`date`,time:`time`,datetime:`datetime`,timestamp:`datetime`,json:`json`,jsonb:`json`,uuid:`uuid`,guid:`uuid`,binary:`binary`,varbinary:`binary`,blob:`binary`,bytes:`binary`,enum:`enum`,array:`array`,vector:`vector`},os={text:{suggested:`text`,exact:[`text`,`textarea`,`email`,`url`,`phone`,`markdown`,`html`,`richtext`,`code`,`select`,`color`],lossy:[]},integer:{suggested:`number`,exact:[`number`,`autonumber`,`rating`,`percent`],lossy:[`currency`,`boolean`]},bigint:{suggested:`number`,exact:[`number`,`autonumber`],lossy:[`currency`]},decimal:{suggested:`number`,exact:[`number`,`currency`,`percent`],lossy:[`rating`]},float:{suggested:`number`,exact:[`number`,`currency`,`percent`,`slider`],lossy:[]},boolean:{suggested:`boolean`,exact:[`boolean`,`toggle`],lossy:[]},date:{suggested:`date`,exact:[`date`],lossy:[`datetime`]},time:{suggested:`time`,exact:[`time`],lossy:[]},datetime:{suggested:`datetime`,exact:[`datetime`],lossy:[`date`]},json:{suggested:`json`,exact:[`json`,`composite`,`repeater`,`record`,`location`,`address`,`tags`,`multiselect`],lossy:[`text`]},uuid:{suggested:`text`,exact:[`text`,`lookup`,`master_detail`,`user`],lossy:[]},binary:{suggested:`file`,exact:[`file`,`image`,`signature`],lossy:[`text`]},enum:{suggested:`select`,exact:[`select`,`radio`,`text`],lossy:[]},array:{suggested:`multiselect`,exact:[`multiselect`,`checkboxes`,`tags`,`json`],lossy:[`text`]},vector:{suggested:`vector`,exact:[`vector`],lossy:[`json`]},unknown:{suggested:`text`,exact:[],lossy:[`text`,`json`]}};function ss(e,t){if(!e)return`unknown`;let n=e.trim().toLowerCase();if(n.endsWith(`[]`)||n.startsWith(`_`))return`array`;let r=n.indexOf(`(`);r!==-1&&(n=n.slice(0,r).trim());for(let e of[` without time zone`,` with time zone`,` unsigned`,` signed`])if(n.endsWith(e)){n=n.slice(0,n.length-e.length).trim();break}let i=t?is[t]:void 0;return i&&i[n]?i[n]:as[n]?as[n]:`unknown`}function cs(e,t){let n=ss(e,t);if(n!==`unknown`)return os[n].suggested}function ls(e,t,n){let r=os[ss(e,n)];return r.exact.includes(t)?!0:r.lossy.includes(t)?`lossy`:!1}var us=t.z.object({name:t.z.string().describe(`Remote column name`),sqlType:t.z.string().describe(`Raw remote SQL type (e.g. "numeric(10,2)")`),nullable:t.z.boolean().describe(`Whether the remote column is nullable`),primaryKey:t.z.boolean().default(!1).describe(`Part of the remote primary key`),suggestedFieldType:t.z.string().optional().describe(`ObjectStack field type suggested by the type-compat matrix`)}),ds=t.z.object({remoteSchema:t.z.string().optional().describe(`Remote schema/database qualifier`),remoteName:t.z.string().describe(`Remote table/view name`),columns:t.z.array(us).describe(`Remote columns`),indexes:t.z.array(t.z.object({name:t.z.string(),columns:t.z.array(t.z.string()),unique:t.z.boolean()})).optional().describe(`Remote indexes, when introspectable`),rowCountEstimate:t.z.number().optional().describe(`Approximate row count`)}),fs=n(()=>t.z.object({name:t.z.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Catalog id, conventionally `<datasource>_catalog`."),datasource:t.z.string().describe(`Datasource.name this catalog snapshots.`),snapshotAt:t.z.string().datetime().describe(`When the snapshot was taken (ISO 8601).`),dialect:t.z.string().optional().describe(`Remote SQL dialect, when known.`),tables:t.z.array(ds).describe(`Snapshotted remote tables.`)})),ps=t.z.enum([`count`,`sum`,`avg`,`min`,`max`,`count_distinct`,`number`,`string`,`boolean`]),ms=t.z.enum([`string`,`number`,`boolean`,`time`,`geo`]),hs=t.z.enum([`second`,`minute`,`hour`,`day`,`week`,`month`,`quarter`,`year`]),gs=n(()=>t.z.object({name:t.z.string().regex(/^[a-z_][a-z0-9_]*$/).describe(`Unique metric ID`),label:t.z.string().describe(`Human readable label`),description:t.z.string().optional(),type:ps,sql:t.z.string().describe(`SQL expression or field reference`),filters:t.z.array(t.z.object({sql:t.z.string()})).optional(),format:t.z.string().optional()})),_s=n(()=>t.z.object({name:t.z.string().regex(/^[a-z_][a-z0-9_]*$/).describe(`Unique dimension ID`),label:t.z.string().describe(`Human readable label`),description:t.z.string().optional(),type:ms,sql:t.z.string().describe(`SQL expression or column reference`),granularities:t.z.array(hs).optional()})),vs=n(()=>t.z.object({name:t.z.string().describe(`Target cube name`),relationship:t.z.enum([`one_to_one`,`one_to_many`,`many_to_one`]).default(`many_to_one`),sql:t.z.string().describe(`Join condition (ON clause)`)})),ys=n(()=>t.z.object({name:t.z.string().regex(/^[a-z_][a-z0-9_]*$/).describe(`Cube name (snake_case)`),title:t.z.string().optional(),description:t.z.string().optional(),sql:t.z.string().describe(`Base SQL statement or Table Name`),measures:t.z.record(t.z.string(),gs).describe(`Quantitative metrics`),dimensions:t.z.record(t.z.string(),_s).describe(`Qualitative attributes`),joins:t.z.record(t.z.string(),vs).optional(),refreshKey:t.z.object({every:t.z.string().optional(),sql:t.z.string().optional()}).optional(),public:t.z.boolean().default(!1)})),bs=n(()=>t.z.object({cube:t.z.string().optional().describe(`Target cube name (optional when provided externally, e.g. in API request wrapper)`),measures:t.z.array(t.z.string()).describe(`List of metrics to calculate`),dimensions:t.z.array(t.z.string()).optional().describe(`List of dimensions to group by`),where:f.optional().describe(`Filtering criteria (canonical Query DSL FilterCondition)`),timeDimensions:t.z.array(t.z.object({dimension:t.z.string(),granularity:hs.optional(),dateRange:t.z.union([t.z.string(),t.z.array(t.z.string())]).optional()})).optional(),order:t.z.record(t.z.string(),t.z.enum([`asc`,`desc`])).optional(),limit:t.z.number().optional(),offset:t.z.number().optional(),timezone:t.z.string().optional().default(`UTC`)}));function xs(e){return ys.parse(e)}var Ss=new Set([`number`,`currency`,`percent`]);function Cs(e){return e===`percent`?`avg`:`sum`}function ws(e,t){return t===`percent`&&(e===`sum`||e===`count_distinct`)}var Ts=new Set(`date.datetime.time.number.currency.percent.boolean.toggle.file.image.avatar.video.audio.attachment.signature.qrcode.json.code.composite.repeater.record.address.vector.geolocation.location.select.multiselect.multi_select.radio.checkboxes.checkbox.tags.color.rating.slider.progress.lookup.master_detail.tree.user.autonumber.password.secret.phone`.split(`.`)),Es=new Set([`text`,`textarea`,`email`,`url`,`markdown`,`html`,`richtext`]),Ds=Es;function $(e){if(!e)return!1;let t=e.type;return t?t===`formula`?(e.returnType??e.valueType)===`text`:!Ts.has(t)&&Es.has(t):!1}var Os=new Set([`name`,`title`,`subject`,`label`,`full_name`,`display_name`]),ks=[`_name`,`_title`],As=[`name_`];function js(e){return Os.has(e.toLowerCase())}function Ms(e){let t=e.toLowerCase();return Os.has(t)?!1:ks.some(e=>t.endsWith(e))||As.some(e=>t.startsWith(e))}function Ns(e){if(!e)return;let t=Object.keys(e);for(let n of[`name`,`title`,`subject`,`label`,`full_name`,`display_name`])for(let r of t)if(r.toLowerCase()===n&&$(e[r]))return r;for(let n of t)if(Ms(n)&&$(e[n]))return n;for(let n of t)if(!js(n)&&$(e[n]))return n}function Ps(e){return e?(e.nameField??e.displayNameField)||Ns(e.fields):void 0}function Fs(e){return e==null||typeof e==`string`&&e.trim()===``}function Is(e,t,n){let r=t??{},i=n?.viewTitleField??Ps(e),a=i?r[i]:void 0;return Fs(a)?`Record #${r.id??r._id??``}`.trimEnd():String(a)}function Ls(e,t){let n=Ps(e);if(n)return e.nameField===n?e:{...e,nameField:n};if(t?.synthesize===!1)return e;let r={...e.fields??{}};return r.name||={type:`text`,label:`Name`,required:!0},{...e,fields:r,nameField:`name`}}function Rs(e){if(!e)return{status:`none`};let t=e.nameField??e.displayNameField;if(t)return{status:e.fields&&Object.prototype.hasOwnProperty.call(e.fields,t)?`explicit`:`synthesized`,field:t};let n=Ns(e.fields);return n?{status:`derived`,field:n}:{status:`none`}}var zs=new Set([`text`,`email`,`phone`,`url`,`autonumber`,`textarea`,`markdown`]),Bs=new Set([`select`,`status`]),Vs=new Set([`id`,`_id`,`created`,`modified`,`created_at`,`updated_at`,`created_by`,`updated_by`,`owner_id`,`organization_id`,`space`,`company_id`]),Hs=new Set([`json`,`object`,`grid`,`image`,`file`,`avatar`,`vector`,`location`,`geometry`,`secret`,`password`,`encrypted`,`boolean`,`lookup`,`master_detail`]);function Us(e,t){let n=Object.keys(e).filter(t=>{if(Vs.has(t))return!1;let n=e[t];if(!n||n.hidden)return!1;let r=n.type;return!r||Hs.has(r)?!1:zs.has(r)||Bs.has(r)}),r=t&&e[t]?t:e.name?`name`:e.title?`title`:void 0;return r?[r,...n.filter(e=>e!==r)]:n}function Ws(e){let t=e.fields||{},n=e.searchableFields?.filter(e=>t[e]);return n&&n.length>0?{allowed:n,source:`declared`}:{allowed:Us(t,e.displayField),source:`auto`}}function Gs(e){let{allowed:t}=Ws(e),n=typeof e.requestedFields==`string`?e.requestedFields.split(`,`).map(e=>e.trim()).filter(Boolean):e.requestedFields;if(n&&n.length>0){let e=new Set(t),r=n.filter(t=>e.has(t));if(r.length>0)return r}return t}var Ks=Object.freeze([`created_at`,`created_by`,`updated_at`,`updated_by`]),qs=new Set([...Ks,`organization_id`,`tenant_id`,`is_deleted`,`deleted_at`]);function Js(e){if(!e||typeof e!=`object`||Array.isArray(e))return null;let t=e;if(typeof t.key!=`string`||t.key.length===0)return null;let n=`none`;return t.collapse===`expanded`||t.collapse===`collapsed`||t.collapse===`none`?n=t.collapse:typeof t.collapsible==`boolean`||typeof t.collapsed==`boolean`?n=t.collapsed===!0?`collapsed`:t.collapsible===!0?`expanded`:`none`:typeof t.defaultExpanded==`boolean`&&(n=t.defaultExpanded?`expanded`:`collapsed`),{key:t.key,label:typeof t.label==`string`?t.label:void 0,icon:typeof t.icon==`string`?t.icon:void 0,description:typeof t.description==`string`?t.description:void 0,collapse:n}}function Ys(e){if(!e||typeof e!=`object`||Array.isArray(e))return null;let t=e,n=(Array.isArray(t.fieldGroups)?t.fieldGroups:[]).map(Js).filter(e=>e!==null);if(n.length===0)return null;let r=new Set(n.map(e=>e.key)),i=t.fields&&typeof t.fields==`object`&&!Array.isArray(t.fields)?t.fields:{},a=new Map;for(let e of n)a.set(e.key,[]);let o=[],s=!1;for(let[e,t]of Object.entries(i)){if(t?.hidden===!0)continue;let n=typeof t?.group==`string`&&r.has(t.group)?t.group:null;n?(a.get(n).push(e),s=!0):qs.has(e)||o.push(e)}if(!s)return null;let c=[];for(let e of n){let t=a.get(e.key);t.length!==0&&c.push({key:e.key,label:e.label??e.key,...e.icon===void 0?{}:{icon:e.icon},...e.description===void 0?{}:{description:e.description},collapse:e.collapse,fields:t})}return o.length>0&&c.push({collapse:`none`,fields:o}),c.length>0?c:null}var Xs=12;function Zs(e){if(!e||typeof e!=`object`||Array.isArray(e))return 0;let t=e.fields;if(!t||typeof t!=`object`||Array.isArray(t))return 0;let n=0;for(let[e,r]of Object.entries(t))r?.hidden!==!0&&(qs.has(e)||n++);return n}function Qs(e,t={}){if(t.viewport===`mobile`)return`page`;let n=t.pageThreshold??Xs;return Zs(e)>=n?`page`:`drawer`}function $s(e,t,n={}){let r=Qs(e,n);return t===`view`?{container:r===`page`?`route`:`overlay`,surface:r,size:`auto`}:r===`page`?{container:`overlay`,surface:`modal`,size:`full`}:{container:`overlay`,surface:r,size:`auto`}}var ec=t.z.enum([`comment`,`field_change`,`task`,`event`,`email`,`call`,`note`,`file`,`record_create`,`record_delete`,`approval`,`sharing`,`system`]),tc=t.z.enum([`all`,`comments_only`,`changes_only`,`tasks_only`]);e.ALL_OPERATORS=ee,e.API_METHOD_DERIVATION=Br,e.API_METHOD_ORDER=Fr,e.API_OPERATION_ORDER=K,e.API_PRIMITIVES=Pr,e.AUDIT_PROVENANCE_FIELDS=Ks,e.AddressSchema=Ye,e.AddressValueSchema=bi,e.AggregationFunction=te,e.AggregationMetricType=ps,e.AggregationNodeSchema=re,e.AggregationPipelineSchema=oo,e.AggregationStageSchema=ao,e.AnalyticsQuerySchema=bs,e.ApiMethod=Yn,e.ApiOperationSchema=Zn,e.BOOLEAN_VALUE_TYPES=ni,e.BaseEngineOptionsSchema=Y,e.CALENDAR_DATE_TYPES=ri,e.CLOCK_TIME_TYPES=ai,e.COMPUTED_VALUE_TYPES=pi,e.CONTEXT_TOKENS=je,e.CONTEXT_TOKEN_DESCRIPTIONS=Fe,e.CONTEXT_TOKEN_SUGGESTIONS=Ie,e.CONTEXT_TOKEN_WRAPPED_RE=Me,e.CalendarDateValueSchema=gi,e.ClockTimeValueSchema=vi,e.ComparisonOperatorSchema=a,e.ConditionalValidationSchema=ot,e.ConsistencyLevelSchema=Za,e.ContextTokenPlaceholderSchema=Pe,e.ContextTokenSchema=Ne,e.CrossFieldValidationSchema=it,e.CubeJoinSchema=vs,e.CubeSchema=ys,e.CurrencyConfigSchema=qe,e.CurrencyValueSchema=Je,e.DATA_ACTION_TO_API_OPERATION=Vr,e.DATE_MACRO_ALIAS_TOKENS=ye,e.DATE_MACRO_DESCRIPTIONS=De,e.DATE_MACRO_INSTANT_TOKENS=_e,e.DATE_MACRO_PARAM_RE=xe,e.DATE_MACRO_PERIOD_TOKENS=ve,e.DATE_MACRO_TOKENS=be,e.DATE_MACRO_UNITS=Se,e.DATE_MACRO_WRAPPED_RE=Te,e.DataEngineAggregateOptionsSchema=ha,e.DataEngineAggregateRequestSchema=Ma,e.DataEngineBatchRequestSchema=Fa,e.DataEngineContractSchema=va,e.DataEngineCountOptionsSchema=_a,e.DataEngineCountRequestSchema=ja,e.DataEngineDeleteOptionsSchema=pa,e.DataEngineDeleteRequestSchema=Aa,e.DataEngineExecuteRequestSchema=Na,e.DataEngineFilterSchema=J,e.DataEngineFindOneRequestSchema=Da,e.DataEngineFindRequestSchema=Ea,e.DataEngineInsertOptionsSchema=ca,e.DataEngineInsertRequestSchema=Oa,e.DataEngineQueryOptionsSchema=sa,e.DataEngineRequestSchema=Ia,e.DataEngineSortSchema=aa,e.DataEngineUpdateOptionsSchema=da,e.DataEngineUpdateRequestSchema=ka,e.DataEngineVectorFindRequestSchema=Pa,e.DataTypeMappingSchema=Wa,e.DatasourceCapabilities=$o,e.DatasourceSchema=ns,e.DateGranularity=E,e.DateMacroPlaceholderSchema=Ee,e.DateMacroTokenSchema=we,e.DimensionSchema=_s,e.DimensionType=ms,e.DocumentSchema=Oo,e.DocumentSchemaValidationSchema=to,e.DocumentTemplateSchema=Eo,e.DocumentVersionSchema=To,e.DriverCapabilitiesSchema=za,e.DriverConfigSchema=Ha,e.DriverDefinitionSchema=Qo,e.DriverInterfaceSchema=Ba,e.DriverOptionsSchema=Z,e.DriverType=Zo,e.DroppedFieldsEventSchema=ua,e.ESignatureConfigSchema=Do,e.EngineAggregateOptionsSchema=ma,e.EngineCountOptionsSchema=ga,e.EngineDeleteOptionsSchema=fa,e.EngineQueryOptionsSchema=oa,e.EngineUpdateOptionsSchema=la,e.EqualityOperatorSchema=i,e.ExpressionBodySchema=yt,e.ExternalCatalogSchema=fs,e.ExternalColumnSchema=us,e.ExternalDataSourceSchema=jo,e.ExternalDatasourceSettingsSchema=ts,e.ExternalFieldMappingSchema=Mo,e.ExternalLookupSchema=No,e.ExternalTableSchema=ds,e.FIELD_GROUP_SYSTEM_FIELDS=qs,e.FIELD_KEY_GUIDANCE=qr,e.FILE_REFERENCE_TYPES=li,e.FILTER_LOGIC_CASES=le,e.FILTER_LOGIC_ROWS=ce,e.FILTER_OPERATORS=S,e.FeedFilterMode=tc,e.FeedItemType=ec,e.Field=et,e.FieldMappingSchema=Yi,e.FieldNodeSchema=D,e.FieldOperatorsSchema=d,e.FieldReferenceSchema=r,e.FieldSchema=$e,e.FieldType=We,e.FileLikeValueSchema=Ci,e.FileReferenceIdValueSchema=Si,e.FileValueSchema=xi,e.FilterConditionSchema=f,e.FormatValidationSchema=rt,e.FullTextSearchSchema=oe,e.GroupByNodeSchema=ne,e.HookBodyCapability=pt,e.HookBodySchema=xt,e.HookContextSchema=Ki,e.HookEvent=Wi,e.HookSchema=Gi,e.IMPORT_BOOLEAN_FALSE_TOKENS=Oi,e.IMPORT_BOOLEAN_TRUE_TOKENS=Di,e.IMPORT_REFERENCE_TYPES=ki,e.INSTANT_TYPES=ii,e.IndexSchema=rr,e.InstantValueSchema=_i,e.JSONValidationSchema=at,e.LEGACY_API_METHODS=G,e.LEGACY_API_METHOD_GUIDANCE=Xn,e.LIFECYCLE_DURATION_REGEX=fr,e.LOGICAL_OPERATORS=C,e.LifecycleClassSchema=dr,e.LifecycleSchema=mr,e.LocationCoordinatesSchema=Ke,e.LocationValueSchema=yi,e.MEASURE_FIELD_TYPES=Ss,e.MULTI_CAPABLE_TYPES=mi,e.MULTI_OPTION_TYPES=si,e.MappingSchema=Xi,e.MetricSchema=gs,e.NUMERIC_VALUE_TYPES=ti,e.NoSQLDataTypeMappingSchema=no,e.NoSQLDatabaseTypeSchema=Ya,e.NoSQLDriverConfigSchema=ro,e.NoSQLIndexSchema=so,e.NoSQLIndexTypeSchema=Qa,e.NoSQLOperationTypeSchema=Xa,e.NoSQLQueryOptionsSchema=io,e.NoSQLTransactionOptionsSchema=co,e.NormalizedFilterSchema=m,e.OBJECT_KEY_GUIDANCE=Jr,e.ObjectAccessConfigSchema=cr,e.ObjectCapabilities=nr,e.ObjectDependencyGraphSchema=vo,e.ObjectDependencyNodeSchema=_o,e.ObjectExtensionSchema=Mr,e.ObjectExternalBindingSchema=gr,e.ObjectFieldGroupSchema=hr,e.ObjectOwnershipEnum=jr,e.ObjectRequiredPermissionsSchema=ur,e.ObjectSchema=Dr,e.PAGINATION_ALL_IDS=ge,e.PAGINATION_CASES=me,e.PAGINATION_ROWS=pe,e.PAGINATION_UNORDERED_CASES=he,e.PerOperationRequiredPermissionsSchema=lr,e.PoolConfigSchema=Va,e.QUERY_CURSOR_REMOVED=k,e.QUERY_DISTINCT_REMOVED=A,e.QueryFilterSchema=p,e.QuerySchema=j,e.RAW_FILE_VALUES_CONTEXT_KEY=di,e.RECORD_SURFACE_PAGE_THRESHOLD=Xs,e.REFERENCE_VALUE_TYPES=ci,e.RPC_QUERY_ALIAS_SLOTS=ya,e.RangeOperatorSchema=c,e.ReferenceIdValueSchema=wi,e.ReferenceResolutionErrorSchema=yo,e.ReferenceResolutionSchema=go,e.ReplicationConfigSchema=eo,e.RowCrudActionOverrideSchema=_r,e.SEARCHABLE_ENUM_TYPES=Bs,e.SEARCHABLE_TEXTUAL_TYPES=zs,e.SEARCH_AUTO_EXCLUDED_FIELDS=Vs,e.SEARCH_AUTO_EXCLUDED_TYPES=Hs,e.SINGLE_OPTION_TYPES=oi,e.SQLDialectSchema=Ua,e.SQLDriverConfigSchema=Ka,e.SQLiteAlterTableLimitations=Ja,e.SQLiteDataTypeMappingDefaults=qa,e.SSLConfigSchema=Ga,e.STACK_KEY_GUIDANCE=Yr,e.STACK_RUNTIME_MEMBERS=Xr,e.STRING_VALUE_TYPES=ei,e.STRUCTURED_JSON_TYPES=fi,e.SchemaModeSchema=es,e.ScriptBodySchema=bt,e.ScriptValidationSchema=tt,e.SeedIdentitySchema=bo,e.SeedLoadResultSchema=So,e.SeedLoaderConfigSchema=xo,e.SeedLoaderRequestSchema=wo,e.SeedLoaderResultSchema=Co,e.SeedMode=lo,e.SeedSchema=uo,e.SelectOptionSchema=Ge,e.SetOperatorSchema=s,e.ShardingConfigSchema=$a,e.SortNodeSchema=T,e.SpecialOperatorSchema=u,e.StateMachineValidationSchema=nt,e.StringOperatorSchema=l,e.TEMPORAL_CASES=M,e.TEMPORAL_NOW=ue,e.TEMPORAL_ROWS=de,e.TEMPORAL_TIME_CASES=N,e.TEMPORAL_TIME_ROWS=fe,e.TITLE_ELIGIBLE=Ds,e.TITLE_ELIGIBLE_TYPES=Es,e.TITLE_INELIGIBLE_TYPES=Ts,e.TenancyConfigSchema=or,e.TimeUpdateInterval=hs,e.TransformType=Ji,e.UniqueScopeSchema=Xe,e.VALID_AST_OPERATORS=g,e.ValidationRuleSchema=z,e.canonicalAstOperator=v,e.canonicalizeSqlType=ss,e.classifyFilterToken=Re,e.countAuthorableFields=Zs,e.defaultAggregateFor=Cs,e.defineCube=xs,e.defineDatasource=rs,e.defineHook=qi,e.defineMapping=Zi,e.defineObjectExtension=Nr,e.defineSeed=fo,e.deriveFieldGroupLayout=Ys,e.deriveRecordFlowSurface=$s,e.deriveRecordSurface=Qs,e.effectiveOperationsArray=Kr,e.fieldForm=mo,e.foldQueryAliasSlots=ba,e.formatUnknownAuthoringKey=$r,e.hasDynamicTokens=Mi,e.hookForm=ho,e.isApiOperationAllowed=Gr,e.isApiPrimitive=Rr,e.isCompatible=ls,e.isContextToken=F,e.isDateMacroToken=P,e.isFileIdToken=ui,e.isFilterAST=y,e.isGlobalUnique=Ze,e.isIncoherentAggregate=ws,e.isKnownFilterToken=Le,e.isLegacyApiMethod=zr,e.isMultiValueField=hi,e.isPlainRecord=Zr,e.isTenancyDisabled=sr,e.isTitleEligible=$,e.isUniqueDeclared=Qe,e.lintAuthoredRecordKeys=Qr,e.missingFieldValues=Fi,e.nextUtcCalendarDay=Oe,e.objectForm=po,e.objectTitleCompleteness=Rs,e.parseAutonumberFormat=ji,e.parseDateMacroParam=Ce,e.parseFilterAST=x,e.provisionPrimary=Ls,e.referencedFields=Pi,e.renderAutonumber=Ri,e.resolveCrudAffordances=kr,e.resolveDisplayField=Ps,e.resolveEffectiveApiMethods=Wr,e.resolveRecordDisplayName=Is,e.resolveSearchFieldResolution=Ws,e.resolveSearchFields=Gs,e.sequenceWidth=Ni,e.stripLegacyApiMethods=er,e.suggestFieldType=cs,e.utcInstantMs=ke,e.valueSchemaFor=Ei})),c=e(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,o=Object.prototype.hasOwnProperty,c=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},l=(e,t,a,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!o.call(e,c)&&c!==a&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},u=e=>l(n({},`__esModule`,{value:!0}),e),d={};c(d,{FilterBuilder:()=>h,ObjectStackClient:()=>S,QueryBuilder:()=>g,RealtimeAPI:()=>m,ScopedProjectClient:()=>C,createFilter:()=>v,createQuery:()=>_}),t.exports=u(d);var f=s(),p=a(),m=class{constructor(e,t){this.subscriptions=new Map,this.eventBuffer=[],this._baseUrl=e,this._token=t}subscribeMetadata(e,t,n){let r=`metadata-${e}-${Date.now()}`;return this.subscriptions.set(r,{filter:{type:e,packageId:n?.packageId,eventTypes:[`metadata.${e}.created`,`metadata.${e}.updated`,`metadata.${e}.deleted`]},handler:e=>{e.type.startsWith(`metadata.`)&&t(e)}}),this.startPolling(),()=>{this.subscriptions.delete(r),this.subscriptions.size===0&&this.stopPolling()}}subscribeData(e,t,n){let r=`data-${e}-${Date.now()}`;return this.subscriptions.set(r,{filter:{type:e,recordId:n?.recordId,eventTypes:[`data.record.created`,`data.record.updated`,`data.record.deleted`]},handler:r=>{r.type.startsWith(`data.`)&&r.object===e&&(!n?.recordId||r.payload?.recordId===n.recordId)&&t(r)}}),this.startPolling(),()=>{this.subscriptions.delete(r),this.subscriptions.size===0&&this.stopPolling()}}emitEvent(e){for(let t of this.subscriptions.values()){let n=!t.filter.type||e.type.includes(t.filter.type)||e.object===t.filter.type,r=!t.filter.eventTypes?.length||t.filter.eventTypes.includes(e.type),i=!t.filter.packageId||e.payload?.packageId===t.filter.packageId;if(n&&r&&i)try{t.handler(e)}catch(e){console.error(`Error in realtime event handler:`,e)}}}startPolling(){this.pollInterval||=setInterval(()=>{for(;this.eventBuffer.length>0;){let e=this.eventBuffer.shift();e&&this.emitEvent(e)}},2e3)}stopPolling(){this.pollInterval&&=(clearInterval(this.pollInterval),void 0)}_bufferEvent(e){this.eventBuffer.push(e)}disconnect(){this.stopPolling(),this.subscriptions.clear(),this.eventBuffer=[]}},h=class{constructor(){this.conditions=[]}equals(e,t){return this.conditions.push([e,`=`,t]),this}notEquals(e,t){return this.conditions.push([e,`!=`,t]),this}greaterThan(e,t){return this.conditions.push([e,`>`,t]),this}greaterThanOrEqual(e,t){return this.conditions.push([e,`>=`,t]),this}lessThan(e,t){return this.conditions.push([e,`<`,t]),this}lessThanOrEqual(e,t){return this.conditions.push([e,`<=`,t]),this}in(e,t){return this.conditions.push([e,`in`,t]),this}notIn(e,t){return this.conditions.push([e,`not_in`,t]),this}like(e,t){return this.conditions.push([e,`like`,t]),this}isNull(e){return this.conditions.push([e,`is_null`,null]),this}isNotNull(e){return this.conditions.push([e,`is_not_null`,null]),this}between(e,t,n){return this.conditions.push([`and`,[e,`>=`,t],[e,`<=`,n]]),this}contains(e,t){return this.conditions.push([e,`like`,`%${t}%`]),this}startsWith(e,t){return this.conditions.push([e,`like`,`${t}%`]),this}endsWith(e,t){return this.conditions.push([e,`like`,`%${t}`]),this}exists(e){return this.conditions.push([e,`is_not_null`,null]),this}build(){if(this.conditions.length===0)throw Error(`Filter builder has no conditions`);return this.conditions.length===1?this.conditions[0]:[`and`,...this.conditions]}getConditions(){return this.conditions}},g=class{constructor(e){this.query={},this._object=e,this.query.object=e}select(...e){return this.query.fields=e,this}where(e){let t=new h;e(t);let n=t.getConditions();return n.length===1?this.query.where=n[0]:n.length>1&&(this.query.where=[`and`,...n]),this}filter(e){return this.query.where=e,this}orderBy(e,t=`asc`){return this.query.orderBy||(this.query.orderBy=[]),this.query.orderBy.push({field:e,order:t}),this}limit(e){return this.query.limit=e,this}skip(e){return this.query.offset=e,this}offset(e){return this.query.offset=e,this}paginate(e,t){return this.query.limit=t,this.query.offset=(e-1)*t,this}groupBy(...e){return this.query.groupBy=e,this}expand(e,t){return this.query.expand||(this.query.expand={}),this.query.expand[e]=t||{},this}search(e,t){return this.query.search={query:e,...t},this}build(){return{object:this._object,...this.query}}getQuery(){return{...this.query}}};function _(e){return new g(e)}function v(){return new h}async function*y(e){let t=e.body;if(!t)throw Error("Streaming response carried no body — this runtime's fetch does not expose `Response.body`");let n=new TextDecoder,r=``,i=function*(e){r+=e;let t;for(;(t=r.indexOf(`
|
|
17
|
+
`))!==-1;){let e=r.slice(0,t).trim();if(r=r.slice(t+1),!e.startsWith(`data:`))continue;let n=e.slice(5).trim();if(!(!n||n===`[DONE]`))try{yield JSON.parse(n)}catch{}}};if(typeof t.getReader==`function`){let e=t.getReader();try{for(;;){let{done:t,value:r}=await e.read();if(t)break;yield*i(n.decode(r,{stream:!0}))}}finally{e.releaseLock?.()}}else for await(let e of t)yield*i(n.decode(e,{stream:!0}));yield*i(n.decode())}function b(e){return typeof e==`string`&&e?e:typeof e?.message==`string`&&e.message?e.message:`Action failed`}function x(e){let t=new Set([`success`,`data`,`error`,`code`,`fields`]);return e&&typeof e==`object`&&!Array.isArray(e)&&typeof e.success==`boolean`&&Object.keys(e).every(e=>t.has(e))?e.success===!1?{success:!1,error:b(e.error)}:{success:!0,data:e.data}:{success:!0,data:e}}var S=class{constructor(e){this.meta={getTypes:async()=>{let e=this.getRoute(`metadata`),t=await this.fetch(`${this.baseUrl}${e}`);return this.unwrapResponse(t)},getItems:async(e,t)=>{let n=this.getRoute(`metadata`),r=new URLSearchParams;t?.packageId&&r.set(`package`,t.packageId);let i=r.toString(),a=`${this.baseUrl}${n}/${e}${i?`?${i}`:``}`,o=await this.fetch(a);return this.unwrapResponse(o)},getItem:async(e,t,n)=>{let r=this.getRoute(`metadata`),i=new URLSearchParams;n?.packageId&&i.set(`package`,n.packageId);let a=i.toString(),o=`${this.baseUrl}${r}/${e}/${t}${a?`?${a}`:``}`,s=await this.fetch(o);return this.unwrapResponse(s)},saveItem:async(e,t,n)=>{let r=this.getRoute(`metadata`),i=await this.fetch(`${this.baseUrl}${r}/${e}/${t}`,{method:`PUT`,body:JSON.stringify(n)});return this.unwrapResponse(i)},deleteItem:async(e,t)=>{let n=this.getRoute(`metadata`),r=await this.fetch(`${this.baseUrl}${n}/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{method:`DELETE`});return this.unwrapResponse(r)},getHistory:async(e,t,n)=>{let r=this.getRoute(`metadata`),i=new URLSearchParams;n?.sinceSeq!==void 0&&i.set(`sinceSeq`,String(n.sinceSeq)),n?.limit!==void 0&&i.set(`limit`,String(n.limit));let a=i.toString(),o=`${this.baseUrl}${r}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/history${a?`?${a}`:``}`,s=await this.fetch(o);return this.unwrapResponse(s)},getCached:async(e,t)=>{let n=this.getRoute(`metadata`),r={};t?.ifNoneMatch&&(r[`If-None-Match`]=t.ifNoneMatch),t?.ifModifiedSince&&(r[`If-Modified-Since`]=t.ifModifiedSince);let i=await this.fetch(`${this.baseUrl}${n}/object/${e}`,{headers:r});if(i.status===304)return{notModified:!0,etag:t?.ifNoneMatch?{value:t.ifNoneMatch.replace(/^W\/|"/g,``),weak:t.ifNoneMatch.startsWith(`W/`)}:void 0};let a=await i.json(),o=i.headers.get(`ETag`),s=i.headers.get(`Last-Modified`);return{data:a,etag:o?{value:o.replace(/^W\/|"/g,``),weak:o.startsWith(`W/`)}:void 0,lastModified:s||void 0,notModified:!1}},getView:async(e,t=`list`)=>{let n=this.getRoute(`ui`),r=await this.fetch(`${this.baseUrl}${n}/view/${encodeURIComponent(e)}/${t}`);return this.unwrapResponse(r)},getPublished:async(e,t)=>{let n=this.getRoute(`metadata`),r=await this.fetch(`${this.baseUrl}${n}/${e}/${t}/published`);return this.unwrapResponse(r)},listDrafts:async e=>{let t=this.getRoute(`metadata`),n=new URLSearchParams;e?.packageId&&n.set(`packageId`,e.packageId),e?.type&&n.set(`type`,e.type);let r=n.toString(),i=await this.fetch(`${this.baseUrl}${t}/_drafts${r?`?${r}`:``}`);return this.unwrapResponse(i)},getLegalNextStates:async(e,t,n)=>{let r=this.getRoute(`metadata`),i=n===void 0?``:`?from=${encodeURIComponent(n)}`,a=await this.fetch(`${this.baseUrl}${r}/objects/${encodeURIComponent(e)}/state/${encodeURIComponent(t)}${i}`);return this.unwrapResponse(a)},getDiagnostics:async e=>{let t=this.getRoute(`metadata`),n=new URLSearchParams;e?.type&&n.set(`type`,e.type),e?.severity&&n.set(`severity`,e.severity),e?.packageId&&n.set(`package`,e.packageId);let r=n.toString(),i=await this.fetch(`${this.baseUrl}${t}/diagnostics${r?`?${r}`:``}`);return this.unwrapResponse(i)},getReferences:async(e,t)=>{let n=this.getRoute(`metadata`),r=await this.fetch(`${this.baseUrl}${n}/${e}/${t}/references`);return this.unwrapResponse(r)},getBookTree:async(e,t)=>{let n=this.getRoute(`metadata`),r=t?.packageId?`?package=${encodeURIComponent(t.packageId)}`:``,i=await this.fetch(`${this.baseUrl}${n}/book/${encodeURIComponent(e)}/tree${r}`);return this.unwrapResponse(i)},getAudit:async(e,t,n)=>{let r=this.getRoute(`metadata`),i=n?.limit===void 0?``:`?limit=${n.limit}`,a=await this.fetch(`${this.baseUrl}${r}/${e}/${t}/audit${i}`);return this.unwrapResponse(a)},publishItem:async(e,t,n)=>{let r=this.getRoute(`metadata`),i=await this.fetch(`${this.baseUrl}${r}/${e}/${t}/publish`,{method:`POST`,body:JSON.stringify(n?.message?{message:n.message}:{})});return this.unwrapResponse(i)},rollbackItem:async(e,t,n,r)=>{let i=this.getRoute(`metadata`),a=await this.fetch(`${this.baseUrl}${i}/${e}/${t}/rollback`,{method:`POST`,body:JSON.stringify({toVersion:n,...r?.message?{message:r.message}:{}})});return this.unwrapResponse(a)},diffItem:async(e,t,n)=>{let r=this.getRoute(`metadata`),i=new URLSearchParams;n?.from!==void 0&&i.set(`from`,String(n.from)),n?.to!==void 0&&i.set(`to`,String(n.to));let a=i.toString(),o=await this.fetch(`${this.baseUrl}${r}/${e}/${t}/diff${a?`?${a}`:``}`);return this.unwrapResponse(o)}},this.analytics={query:async e=>{let t=this.getRoute(`analytics`);return(await this.fetch(`${this.baseUrl}${t}/query`,{method:`POST`,body:JSON.stringify(e)})).json()},meta:async e=>{let t=this.getRoute(`analytics`),n=e?`?cube=${encodeURIComponent(e)}`:``;return(await this.fetch(`${this.baseUrl}${t}/meta${n}`)).json()},explain:async e=>{let t=this.getRoute(`analytics`);return(await this.fetch(`${this.baseUrl}${t}/sql`,{method:`POST`,body:JSON.stringify(e)})).json()},queryDataset:async e=>{let t=this.getRoute(`analytics`);return(await this.fetch(`${this.baseUrl}${t}/dataset/query`,{method:`POST`,body:JSON.stringify(e)})).json()}},this.email={send:async e=>{let t=await this.fetch(`${this.baseUrl}/api/v1/email/send`,{method:`POST`,body:JSON.stringify(e)});return this.unwrapResponse(t)}},this.datasources={external:{listTables:async(e,t)=>{let n=t?.schema?`?schema=${encodeURIComponent(t.schema)}`:``,r=await this.fetch(`${this.baseUrl}/api/v1/datasources/${encodeURIComponent(e)}/external/tables${n}`);return this.unwrapResponse(r)},draft:async(e,t,n)=>{let r=await this.fetch(`${this.baseUrl}/api/v1/datasources/${encodeURIComponent(e)}/external/tables/${encodeURIComponent(t)}/draft`,{method:`POST`,body:JSON.stringify(n??{})});return this.unwrapResponse(r)},import:async(e,t,n)=>{let r=await this.fetch(`${this.baseUrl}/api/v1/datasources/${encodeURIComponent(e)}/external/tables/${encodeURIComponent(t)}/import`,{method:`POST`,body:JSON.stringify(n??{})});return this.unwrapResponse(r)},refreshCatalog:async e=>{let t=await this.fetch(`${this.baseUrl}/api/v1/datasources/${encodeURIComponent(e)}/external/refresh-catalog`,{method:`POST`,body:JSON.stringify({})});return this.unwrapResponse(t)},validate:async e=>{let t=await this.fetch(`${this.baseUrl}/api/v1/datasources/${encodeURIComponent(e)}/external/validate`,{method:`POST`,body:JSON.stringify({})});return this.unwrapResponse(t)}}},this.packages={list:async e=>{let t=this.getRoute(`packages`),n=new URLSearchParams;e?.status&&n.set(`status`,e.status),e?.type&&n.set(`type`,e.type),e?.enabled!==void 0&&n.set(`enabled`,String(e.enabled));let r=n.toString(),i=`${this.baseUrl}${t}${r?`?`+r:``}`,a=await this.fetch(i);return this.unwrapResponse(a)},get:async e=>{let t=this.getRoute(`packages`),n=await this.fetch(`${this.baseUrl}${t}/${encodeURIComponent(e)}`);return this.unwrapResponse(n)},install:async(e,t)=>{let n=this.getRoute(`packages`),r=await this.fetch(`${this.baseUrl}${n}`,{method:`POST`,body:JSON.stringify({manifest:e,settings:t?.settings,enableOnInstall:t?.enableOnInstall,...t?.overwrite===void 0?{}:{overwrite:t.overwrite}})});return this.unwrapResponse(r)},uninstall:async e=>{let t=this.getRoute(`packages`),n=await this.fetch(`${this.baseUrl}${t}/${encodeURIComponent(e)}`,{method:`DELETE`});return this.unwrapResponse(n)},enable:async e=>{let t=this.getRoute(`packages`),n=await this.fetch(`${this.baseUrl}${t}/${encodeURIComponent(e)}/enable`,{method:`PATCH`});return this.unwrapResponse(n)},disable:async e=>{let t=this.getRoute(`packages`),n=await this.fetch(`${this.baseUrl}${t}/${encodeURIComponent(e)}/disable`,{method:`PATCH`});return this.unwrapResponse(n)},update:async(e,t)=>{let n=this.getRoute(`packages`),r=await this.fetch(`${this.baseUrl}${n}/${encodeURIComponent(e)}`,{method:`PATCH`,body:JSON.stringify(t)});return this.unwrapResponse(r)},publish:async(e,t)=>{let n=this.getRoute(`packages`),r=await this.fetch(`${this.baseUrl}${n}/${encodeURIComponent(e)}/publish`,{method:`POST`,body:JSON.stringify(t??{})});return this.unwrapResponse(r)},publishDrafts:async(e,t)=>{let n=this.getRoute(`packages`),r=await this.fetch(`${this.baseUrl}${n}/${encodeURIComponent(e)}/publish-drafts`,{method:`POST`,body:JSON.stringify(t??{})});return this.unwrapResponse(r)},discardDrafts:async(e,t)=>{let n=this.getRoute(`packages`),r=await this.fetch(`${this.baseUrl}${n}/${encodeURIComponent(e)}/discard-drafts`,{method:`POST`,body:JSON.stringify(t??{})});return this.unwrapResponse(r)},listCommits:async e=>{let t=this.getRoute(`packages`),n=await this.fetch(`${this.baseUrl}${t}/${encodeURIComponent(e)}/commits`);return this.unwrapResponse(n)},revertCommit:async(e,t,n)=>{let r=this.getRoute(`packages`),i=await this.fetch(`${this.baseUrl}${r}/${encodeURIComponent(e)}/commits/${encodeURIComponent(t)}/revert`,{method:`POST`,body:JSON.stringify(n??{})});return this.unwrapResponse(i)},rollback:async(e,t,n)=>{let r=this.getRoute(`packages`),i=await this.fetch(`${this.baseUrl}${r}/${encodeURIComponent(e)}/rollback`,{method:`POST`,body:JSON.stringify({commitId:t,...n??{}})});return this.unwrapResponse(i)},revert:async e=>{let t=this.getRoute(`packages`),n=await this.fetch(`${this.baseUrl}${t}/${encodeURIComponent(e)}/revert`,{method:`POST`});return this.unwrapResponse(n)},export:async e=>{let t=this.getRoute(`packages`),n=await this.fetch(`${this.baseUrl}${t}/${encodeURIComponent(e)}/export`);return this.unwrapResponse(n)},adoptOrphans:async(e,t)=>{let n=this.getRoute(`packages`),r=await this.fetch(`${this.baseUrl}${n}/${encodeURIComponent(e)}/adopt-orphans`,{method:`POST`,body:JSON.stringify(t??{})});return this.unwrapResponse(r)},duplicate:async(e,t,n)=>{let r=this.getRoute(`packages`),i=await this.fetch(`${this.baseUrl}${r}/${encodeURIComponent(e)}/duplicate`,{method:`POST`,body:JSON.stringify({targetPackageId:t,...n??{}})});return this.unwrapResponse(i)}},this.projects={list:async e=>{let t=new URLSearchParams;e?.organization_id&&t.set(`organizationId`,e.organization_id),e?.env_type&&t.set(`envType`,e.env_type),e?.status&&t.set(`status`,e.status);let n=t.toString(),r=`${this.baseUrl}/api/v1/cloud/environments${n?`?`+n:``}`,i=await this.fetch(r);return this.unwrapResponse(i)},get:async e=>{let t=await this.fetch(`${this.baseUrl}/api/v1/cloud/environments/${encodeURIComponent(e)}`);return this.unwrapResponse(t)},create:async e=>{let t=await this.fetch(`${this.baseUrl}/api/v1/cloud/environments`,{method:`POST`,body:JSON.stringify(e)});return this.unwrapResponse(t)},update:async(e,t)=>{let n=await this.fetch(`${this.baseUrl}/api/v1/cloud/environments/${encodeURIComponent(e)}`,{method:`PATCH`,body:JSON.stringify(t)});return this.unwrapResponse(n)},delete:async(e,t)=>{let n=t?.force?`?force=1`:``,r=await this.fetch(`${this.baseUrl}/api/v1/cloud/environments/${encodeURIComponent(e)}${n}`,{method:`DELETE`});return this.unwrapResponse(r)},activate:async e=>{let t=await this.fetch(`${this.baseUrl}/api/v1/cloud/environments/${encodeURIComponent(e)}/activate`,{method:`POST`});return this.unwrapResponse(t)},rotateCredential:async(e,t)=>{let n=await this.fetch(`${this.baseUrl}/api/v1/cloud/environments/${encodeURIComponent(e)}/credentials/rotate`,{method:`POST`,body:JSON.stringify({plaintext:t})});return this.unwrapResponse(n)},updateHostname:async(e,t)=>{let n=await this.fetch(`${this.baseUrl}/api/v1/cloud/environments/${encodeURIComponent(e)}/hostname`,{method:`POST`,body:JSON.stringify({hostname:t})});return this.unwrapResponse(n)},updateVisibility:async(e,t)=>{let n=await this.fetch(`${this.baseUrl}/api/v1/cloud/environments/${encodeURIComponent(e)}`,{method:`PATCH`,body:JSON.stringify({visibility:t})});return this.unwrapResponse(n)},listRevisions:async(e,t)=>{let n=new URLSearchParams;t?.limit&&n.set(`limit`,String(t.limit)),t?.cursor&&n.set(`cursor`,t.cursor),t?.branch&&n.set(`branch`,t.branch);let r=n.toString(),i=await this.fetch(`${this.baseUrl}/api/v1/cloud/environments/${encodeURIComponent(e)}/revisions${r?`?${r}`:``}`);return this.unwrapResponse(i)},listBranches:async e=>{let t=await this.fetch(`${this.baseUrl}/api/v1/cloud/environments/${encodeURIComponent(e)}/branches`);return this.unwrapResponse(t)},renameBranch:async(e,t,n)=>{let r=await this.fetch(`${this.baseUrl}/api/v1/cloud/environments/${encodeURIComponent(e)}/branches/${encodeURIComponent(t)}/rename`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({newName:n})});return this.unwrapResponse(r)},deleteBranch:async(e,t)=>{let n=await this.fetch(`${this.baseUrl}/api/v1/cloud/environments/${encodeURIComponent(e)}/branches/${encodeURIComponent(t)}`,{method:`DELETE`});return this.unwrapResponse(n)},retryProvisioning:async e=>{let t=await this.fetch(`${this.baseUrl}/api/v1/cloud/environments/${encodeURIComponent(e)}/retry`,{method:`POST`});return this.unwrapResponse(t)},listDrivers:async()=>{let e=await this.fetch(`${this.baseUrl}/api/v1/cloud/drivers`);return this.unwrapResponse(e)},packages:{list:async e=>{let t=await this.fetch(`${this.baseUrl}/api/v1/cloud/environments/${encodeURIComponent(e)}/packages`);return this.unwrapResponse(t)},install:async(e,t)=>{let n=await this.fetch(`${this.baseUrl}/api/v1/cloud/environments/${encodeURIComponent(e)}/packages`,{method:`POST`,body:JSON.stringify(t)});return this.unwrapResponse(n)},get:async(e,t)=>{let n=await this.fetch(`${this.baseUrl}/api/v1/cloud/environments/${encodeURIComponent(e)}/packages/${encodeURIComponent(t)}`);return this.unwrapResponse(n)},enable:async(e,t)=>{let n=await this.fetch(`${this.baseUrl}/api/v1/cloud/environments/${encodeURIComponent(e)}/packages/${encodeURIComponent(t)}/enable`,{method:`PATCH`});return this.unwrapResponse(n)},disable:async(e,t)=>{let n=await this.fetch(`${this.baseUrl}/api/v1/cloud/environments/${encodeURIComponent(e)}/packages/${encodeURIComponent(t)}/disable`,{method:`PATCH`});return this.unwrapResponse(n)},uninstall:async(e,t)=>{let n=await this.fetch(`${this.baseUrl}/api/v1/cloud/environments/${encodeURIComponent(e)}/packages/${encodeURIComponent(t)}`,{method:`DELETE`});return this.unwrapResponse(n)},upgrade:async(e,t,n)=>{let r=await this.fetch(`${this.baseUrl}/api/v1/cloud/environments/${encodeURIComponent(e)}/packages/${encodeURIComponent(t)}/upgrade`,{method:`POST`,body:JSON.stringify({targetVersion:n})});return this.unwrapResponse(r)}}},this.organizations={list:async()=>{let e=this.getRoute(`auth`),t=await(await this.fetch(`${this.baseUrl}${e}/organization/list`)).json();return{organizations:Array.isArray(t)?t:t?.data??[]}},create:async e=>{let t=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${t}/organization/create`,{method:`POST`,body:JSON.stringify(e)})).json()},update:async(e,t)=>{let n=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${n}/organization/update`,{method:`POST`,body:JSON.stringify({organizationId:e,data:t})})).json()},setActive:async e=>{let t=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${t}/organization/set-active`,{method:`POST`,body:JSON.stringify({organizationId:e})})).json()},get:async e=>{let t=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${t}/organization/get-full-organization?organizationId=${encodeURIComponent(e)}`)).json()},listMembers:async e=>{let t=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${t}/organization/list-members?organizationId=${encodeURIComponent(e)}`)).json()},invite:async e=>{let t=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${t}/organization/invite-member`,{method:`POST`,body:JSON.stringify(e)})).json()},leave:async e=>{let t=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${t}/organization/leave`,{method:`POST`,body:JSON.stringify({organizationId:e})})).json()},delete:async e=>{let t=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${t}/organization/delete`,{method:`POST`,body:JSON.stringify({organizationId:e})})).json()},removeMember:async(e,t)=>{let n=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${n}/organization/remove-member`,{method:`POST`,body:JSON.stringify({memberIdOrEmail:t.memberIdOrEmail,organizationId:e})})).json()},updateMemberRole:async(e,t)=>{let n=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${n}/organization/update-member-role`,{method:`POST`,body:JSON.stringify({memberId:t.memberId,role:t.role,organizationId:e})})).json()},getActiveMember:async e=>{let t=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${t}/organization/get-active-member?organizationId=${encodeURIComponent(e)}`)).json()},invitations:{list:async e=>{let t=this.getRoute(`auth`),n=await(await this.fetch(`${this.baseUrl}${t}/organization/list-invitations?organizationId=${encodeURIComponent(e)}`)).json();return{invitations:Array.isArray(n)?n:n?.data??n?.invitations??[]}},listMine:async()=>{let e=this.getRoute(`auth`),t=await(await this.fetch(`${this.baseUrl}${e}/organization/list-user-invitations`)).json();return{invitations:Array.isArray(t)?t:t?.data??t?.invitations??[]}},cancel:async e=>{let t=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${t}/organization/cancel-invitation`,{method:`POST`,body:JSON.stringify({invitationId:e})})).json()},accept:async e=>{let t=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${t}/organization/accept-invitation`,{method:`POST`,body:JSON.stringify({invitationId:e})})).json()},reject:async e=>{let t=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${t}/organization/reject-invitation`,{method:`POST`,body:JSON.stringify({invitationId:e})})).json()},resend:async e=>{if(e.id)try{await this.organizations.invitations.cancel(e.id)}catch{}return this.organizations.invite({email:e.email,role:e.role??`member`,organizationId:e.organizationId})}},teams:{list:async e=>{let t=this.getRoute(`auth`),n=await(await this.fetch(`${this.baseUrl}${t}/organization/list-teams?organizationId=${encodeURIComponent(e)}`)).json();return{teams:Array.isArray(n)?n:n?.data??n?.teams??[]}},create:async e=>{let t=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${t}/organization/create-team`,{method:`POST`,body:JSON.stringify(e)})).json()},update:async e=>{let t=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${t}/organization/update-team`,{method:`POST`,body:JSON.stringify(e)})).json()},delete:async e=>{let t=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${t}/organization/remove-team`,{method:`POST`,body:JSON.stringify(e)})).json()},listMembers:async e=>{let t=this.getRoute(`auth`),n=await(await this.fetch(`${this.baseUrl}${t}/organization/list-team-members?teamId=${encodeURIComponent(e)}`)).json();return{members:Array.isArray(n)?n:n?.data??n?.members??[]}},addMember:async e=>{let t=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${t}/organization/add-team-member`,{method:`POST`,body:JSON.stringify(e)})).json()},removeMember:async e=>{let t=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${t}/organization/remove-team-member`,{method:`POST`,body:JSON.stringify(e)})).json()}}},this.oauth={applications:{register:async e=>{let t=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${t}/oauth2/create-client`,{method:`POST`,body:JSON.stringify(e)})).json()},get:async e=>{let t=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${t}/oauth2/get-client?client_id=${encodeURIComponent(e)}`)).json()},getPublic:async e=>{let t=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${t}/oauth2/public-client?client_id=${encodeURIComponent(e)}`)).json()},list:async()=>{let e=this.getRoute(`auth`),t=await(await this.fetch(`${this.baseUrl}${e}/oauth2/get-clients`)).json();return{applications:Array.isArray(t)?t:t?.clients??t?.data??[]}},delete:async e=>{let t=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${t}/oauth2/delete-client`,{method:`POST`,body:JSON.stringify({client_id:e})})).json()}},consent:async e=>{let t=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${t}/oauth2/consent`,{method:`POST`,body:JSON.stringify(e)})).json()}},this.auth={getConfig:async()=>{let e=this.getRoute(`auth`),t=await this.fetch(`${this.baseUrl}${e}/config`);return this.unwrapResponse(t)},login:async e=>{let t=this.getRoute(`auth`),n=await this.fetch(`${this.baseUrl}${t}/sign-in/email`,{method:`POST`,headers:{Origin:this.baseUrl},body:JSON.stringify(e)}),r=await n.json().catch(()=>({}));if(!n.ok){let e=r?.message||r?.error?.message||`Login failed (HTTP ${n.status})`,t=Error(e);throw r?.code&&(t.code=r.code),t.status=n.status,t}let i=r&&(r.data??(r.token||r.user?{token:r.token,user:r.user}:void 0)),a=i?{...r,data:i}:r;return a.data?.token&&(this.token=a.data.token),a},logout:async()=>{let e=this.getRoute(`auth`);await this.fetch(`${this.baseUrl}${e}/sign-out`,{method:`POST`,headers:{"Content-Type":`application/json`,Origin:this.baseUrl},body:`{}`}),this.token=void 0},me:async()=>{let e=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${e}/get-session`,{headers:{Origin:this.baseUrl}})).json()},register:async e=>{let t=this.getRoute(`auth`),n=await(await this.fetch(`${this.baseUrl}${t}/sign-up/email`,{method:`POST`,headers:{Origin:this.baseUrl},body:JSON.stringify(e)})).json(),r=n&&(n.data??(n.token||n.user?{token:n.token,user:n.user}:void 0)),i=r?{...n,data:r}:n;return i.data?.token&&(this.token=i.data.token),i},signInWithProvider:async(e,t)=>{if(typeof window>`u`)throw Error(`signInWithProvider requires a browser environment`);let n=this.getRoute(`auth`),r=t?.callbackURL??window.location.href,i=t?.type===`oidc`,a=i?`/sign-in/oauth2`:`/sign-in/social`,o=i?{providerId:e,callbackURL:r}:{provider:e,callbackURL:r};t?.errorCallbackURL&&(o.errorCallbackURL=t.errorCallbackURL);let s=await(await this.fetch(`${this.baseUrl}${n}${a}`,{method:`POST`,body:JSON.stringify(o)})).json(),c=s?.url??s?.data?.url;if(c)window.location.assign(c);else throw Error(`signInWithProvider: no redirect URL returned for provider "${e}"`)},refreshToken:async e=>{let t=this.getRoute(`auth`),n=await(await this.fetch(`${this.baseUrl}${t}/get-session`,{method:`GET`})).json();return n.data?.token&&(this.token=n.data.token),n},bootstrapStatus:async()=>{let e=this.getRoute(`auth`),t=await(await this.fetch(`${this.baseUrl}${e}/bootstrap-status`)).json();return{hasOwner:!!(t?.data??t)?.hasOwner}},updateUser:async e=>{let t=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${t}/update-user`,{method:`POST`,body:JSON.stringify(e)})).json()},changePassword:async e=>{let t=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${t}/change-password`,{method:`POST`,body:JSON.stringify(e)})).json()},changeEmail:async e=>{let t=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${t}/change-email`,{method:`POST`,body:JSON.stringify(e)})).json()},sendVerificationEmail:async e=>{let t=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${t}/send-verification-email`,{method:`POST`,body:JSON.stringify(e)})).json()},verifyEmail:async e=>{let t=this.getRoute(`auth`),n=new URL(`${this.baseUrl}${t}/verify-email`);return n.searchParams.set(`token`,e.token),e.callbackURL&&n.searchParams.set(`callbackURL`,e.callbackURL),(await this.fetch(n.toString())).json()},deleteUser:async e=>{let t=this.getRoute(`auth`),n=await this.fetch(`${this.baseUrl}${t}/delete-user`,{method:`POST`,body:JSON.stringify(e)});return this.token=void 0,n.json()},sessions:{list:async()=>{let e=this.getRoute(`auth`),t=await(await this.fetch(`${this.baseUrl}${e}/list-sessions`)).json();return{sessions:Array.isArray(t)?t:t?.data??t?.sessions??[]}},revoke:async e=>{let t=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${t}/revoke-session`,{method:`POST`,body:JSON.stringify({token:e})})).json()},revokeOthers:async()=>{let e=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${e}/revoke-other-sessions`,{method:`POST`,body:`{}`})).json()},revokeAll:async()=>{let e=this.getRoute(`auth`),t=await this.fetch(`${this.baseUrl}${e}/revoke-sessions`,{method:`POST`,body:`{}`});return this.token=void 0,t.json()}},twoFactor:{enable:async e=>{let t=this.getRoute(`auth`),n=await(await this.fetch(`${this.baseUrl}${t}/two-factor/enable`,{method:`POST`,body:JSON.stringify(e)})).json();return n?.data??n},verifyTotp:async e=>{let t=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${t}/two-factor/verify-totp`,{method:`POST`,body:JSON.stringify(e)})).json()},disable:async e=>{let t=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${t}/two-factor/disable`,{method:`POST`,body:JSON.stringify(e)})).json()},generateBackupCodes:async e=>{let t=this.getRoute(`auth`),n=await(await this.fetch(`${this.baseUrl}${t}/two-factor/generate-backup-codes`,{method:`POST`,body:JSON.stringify(e)})).json();return n?.data??n},verifyBackupCode:async e=>{let t=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${t}/two-factor/verify-backup-code`,{method:`POST`,body:JSON.stringify(e)})).json()}},accounts:{list:async()=>{let e=this.getRoute(`auth`),t=await(await this.fetch(`${this.baseUrl}${e}/list-accounts`)).json();return{accounts:Array.isArray(t)?t:t?.data??t?.accounts??[]}},unlink:async e=>{let t=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${t}/unlink-account`,{method:`POST`,body:JSON.stringify(e)})).json()},linkSocial:async e=>{let t=this.getRoute(`auth`),n=e.callbackURL??(typeof window<`u`?window.location.href:void 0),r=await(await this.fetch(`${this.baseUrl}${t}/link-social`,{method:`POST`,body:JSON.stringify({provider:e.provider,callbackURL:n})})).json();return r?.data??r}}},this.storage={upload:async(e,t=`user`)=>{let n={filename:e.name,mimeType:e.type,size:e.size,scope:t},r=this.getRoute(`storage`),{data:i}=await(await this.fetch(`${this.baseUrl}${r}/upload/presigned`,{method:`POST`,body:JSON.stringify(n)})).json(),a=await this.fetchImpl(i.uploadUrl,{method:i.method,headers:i.headers,body:e});if(!a.ok)throw Error(`Storage Upload Failed: ${a.statusText}`);let o={fileId:i.fileId},s=await(await this.fetch(`${this.baseUrl}${r}/upload/complete`,{method:`POST`,body:JSON.stringify(o)})).json();return s?.data&&s.data.fileId==null&&(s.data.fileId=i.fileId),s},getDownloadUrl:async e=>{let t=this.getRoute(`storage`),n=await this.fetch(`${this.baseUrl}${t}/files/${e}/url`),{url:r}=await this.unwrapResponse(n);return r},getPresignedUrl:async e=>{let t=this.getRoute(`storage`);return(await this.fetch(`${this.baseUrl}${t}/upload/presigned`,{method:`POST`,body:JSON.stringify(e)})).json()},initChunkedUpload:async e=>{let t=this.getRoute(`storage`);return(await this.fetch(`${this.baseUrl}${t}/upload/chunked`,{method:`POST`,body:JSON.stringify(e)})).json()},uploadPart:async(e,t,n,r)=>{let i=this.getRoute(`storage`);return(await this.fetch(`${this.baseUrl}${i}/upload/chunked/${e}/chunk/${t}`,{method:`PUT`,headers:{"x-resume-token":n},body:r})).json()},completeChunkedUpload:async e=>{let t=this.getRoute(`storage`);return(await this.fetch(`${this.baseUrl}${t}/upload/chunked/${e.uploadId}/complete`,{method:`POST`,body:JSON.stringify(e)})).json()},resumeUpload:async(e,t,n,r)=>{let i=this.getRoute(`storage`),{totalChunks:a,uploadedChunks:o}=(await(await this.fetch(`${this.baseUrl}${i}/upload/chunked/${e}/progress`)).json()).data,s=[],c=t instanceof ArrayBuffer?t:await t.arrayBuffer();for(let t=o;t<a;t++){let i=t*n,a=Math.min(i+n,c.byteLength),o=new Blob([c.slice(i,a)]),l=await this.storage.uploadPart(e,t,r,o);s.push({chunkIndex:t,eTag:l.data.eTag})}return this.storage.completeChunkedUpload({uploadId:e,parts:s})}},this.automation={trigger:async(e,t)=>{let n=this.getRoute(`automation`);return(await this.fetch(`${this.baseUrl}${n}/trigger/${e}`,{method:`POST`,body:JSON.stringify(t)})).json()},list:async()=>{let e=this.getRoute(`automation`),t=await this.fetch(`${this.baseUrl}${e}`);return this.unwrapResponse(t)},get:async e=>{let t=this.getRoute(`automation`),n=await this.fetch(`${this.baseUrl}${t}/${e}`);return this.unwrapResponse(n)},create:async(e,t)=>{let n=this.getRoute(`automation`),r=await this.fetch(`${this.baseUrl}${n}`,{method:`POST`,body:JSON.stringify({name:e,...t})});return this.unwrapResponse(r)},update:async(e,t)=>{let n=this.getRoute(`automation`),r=await this.fetch(`${this.baseUrl}${n}/${e}`,{method:`PUT`,body:JSON.stringify({definition:t})});return this.unwrapResponse(r)},delete:async e=>{let t=this.getRoute(`automation`),n=await this.fetch(`${this.baseUrl}${t}/${e}`,{method:`DELETE`});return this.unwrapResponse(n)},listActions:async e=>{let t=this.getRoute(`automation`),n=new URLSearchParams;e?.paradigm&&n.set(`paradigm`,e.paradigm),e?.source&&n.set(`source`,e.source),e?.category&&n.set(`category`,e.category);let r=n.toString(),i=await this.fetch(`${this.baseUrl}${t}/actions${r?`?${r}`:``}`);return this.unwrapResponse(i)},listConnectors:async e=>{let t=this.getRoute(`automation`),n=e?.type?`?type=${encodeURIComponent(e.type)}`:``,r=await this.fetch(`${this.baseUrl}${t}/connectors${n}`);return this.unwrapResponse(r)},getRuntimeStatus:async()=>{let e=this.getRoute(`automation`),t=await this.fetch(`${this.baseUrl}${e}/_status`);return this.unwrapResponse(t)},toggle:async(e,t)=>{let n=this.getRoute(`automation`),r=await this.fetch(`${this.baseUrl}${n}/${e}/toggle`,{method:`POST`,body:JSON.stringify({enabled:t})});return this.unwrapResponse(r)},runs:{list:async(e,t)=>{let n=this.getRoute(`automation`),r=new URLSearchParams;t?.limit&&r.set(`limit`,String(t.limit)),t?.cursor&&r.set(`cursor`,t.cursor);let i=r.toString(),a=await this.fetch(`${this.baseUrl}${n}/${e}/runs${i?`?${i}`:``}`);return this.unwrapResponse(a)},get:async(e,t)=>{let n=this.getRoute(`automation`),r=await this.fetch(`${this.baseUrl}${n}/${e}/runs/${t}`);return this.unwrapResponse(r)}},getFlow:async e=>{let t=this.getRoute(`automation`),n=await this.fetch(`${this.baseUrl}${t}/${encodeURIComponent(e)}`);return this.unwrapResponse(n)},execute:async(e,t)=>{let n=this.getRoute(`automation`),r=await this.fetch(`${this.baseUrl}${n}/${encodeURIComponent(e)}/trigger`,{method:`POST`,body:JSON.stringify(t??{})});return this.unwrapResponse(r)},listRuns:async(e,t)=>{let n=this.getRoute(`automation`),r=new URLSearchParams;t?.limit!=null&&r.set(`limit`,String(t.limit)),t?.cursor&&r.set(`cursor`,t.cursor);let i=r.toString(),a=await this.fetch(`${this.baseUrl}${n}/${encodeURIComponent(e)}/runs${i?`?${i}`:``}`);return this.unwrapResponse(a)},getRun:async(e,t)=>{let n=this.getRoute(`automation`),r=await this.fetch(`${this.baseUrl}${n}/${encodeURIComponent(e)}/runs/${encodeURIComponent(t)}`);return this.unwrapResponse(r)},resume:async(e,t,n)=>{let r=this.getRoute(`automation`),i=await this.fetch(`${this.baseUrl}${r}/${encodeURIComponent(e)}/runs/${encodeURIComponent(t)}/resume`,{method:`POST`,body:JSON.stringify(n??{})});return this.unwrapResponse(i)},getScreen:async(e,t)=>{let n=this.getRoute(`automation`),r=await this.fetch(`${this.baseUrl}${n}/${encodeURIComponent(e)}/runs/${encodeURIComponent(t)}/screen`);return this.unwrapResponse(r)}},this.actions={invoke:async(e,t,n)=>{try{let r=await this.fetch(`${this.baseUrl}/api/v1/actions/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{method:`POST`,body:JSON.stringify({recordId:n?.recordId,params:n?.params??{}})});return x(await this.unwrapResponse(r))}catch(e){return{success:!1,error:b(e)}}},invokeGlobal:async(e,t)=>this.actions.invoke(`global`,e,t)},this.keys={create:async e=>{let t=await this.fetch(`${this.baseUrl}/api/v1/keys`,{method:`POST`,body:JSON.stringify({...e?.name==null?{}:{name:e.name},...e?.expiresAt==null?{}:{expires_at:e.expiresAt}})});return this.unwrapResponse(t)}},this.shareLinks={create:async(e,t,n)=>{let r=await this.fetch(`${this.baseUrl}/api/v1/share-links`,{method:`POST`,body:JSON.stringify({object:e,recordId:t,...n??{}})});return this.unwrapResponse(r)},list:async e=>{let t=new URLSearchParams;e?.object&&t.set(`object`,e.object),e?.recordId&&t.set(`recordId`,e.recordId),e?.includeRevoked&&t.set(`includeRevoked`,`true`);let n=t.toString(),r=await this.fetch(`${this.baseUrl}/api/v1/share-links${n?`?${n}`:``}`);return this.unwrapResponse(r)},revoke:async e=>{let t=await this.fetch(`${this.baseUrl}/api/v1/share-links/${encodeURIComponent(e)}`,{method:`DELETE`});return this.unwrapResponse(t)}},this.security={explain:async e=>{let t=await this.fetch(`${this.baseUrl}/api/v1/security/explain`,{method:`POST`,body:JSON.stringify(e)});return this.unwrapResponse(t)},describeDelegableScope:async()=>{let e=await this.fetch(`${this.baseUrl}/api/v1/security/my-delegable-scope`);return this.unwrapResponse(e)},suggestedBindings:{list:async e=>{let t=new URLSearchParams;e?.status&&t.set(`status`,e.status),e?.packageId&&t.set(`packageId`,e.packageId);let n=t.toString(),r=await this.fetch(`${this.baseUrl}/api/v1/security/suggested-bindings${n?`?${n}`:``}`);return this.unwrapResponse(r)},confirm:async e=>{let t=await this.fetch(`${this.baseUrl}/api/v1/security/suggested-bindings/${encodeURIComponent(e)}/confirm`,{method:`POST`});return this.unwrapResponse(t)},dismiss:async e=>{let t=await this.fetch(`${this.baseUrl}/api/v1/security/suggested-bindings/${encodeURIComponent(e)}/dismiss`,{method:`POST`});return this.unwrapResponse(t)}}},this.approvals={listRequests:async e=>{let t=this.getRoute(`approvals`),n=new URLSearchParams;e?.object&&n.set(`object`,e.object),e?.recordId&&n.set(`recordId`,e.recordId),e?.status&&n.set(`status`,Array.isArray(e.status)?e.status.join(`,`):e.status),e?.approverId&&n.set(`approverId`,Array.isArray(e.approverId)?e.approverId.join(`,`):e.approverId),e?.submitterId&&n.set(`submitterId`,e.submitterId);let r=n.toString(),i=await this.fetch(`${this.baseUrl}${t}/requests${r?`?${r}`:``}`),a=await this.unwrapResponse(i);return Array.isArray(a)?a:a?.data??[]},getRequest:async e=>{let t=this.getRoute(`approvals`),n=await this.fetch(`${this.baseUrl}${t}/requests/${encodeURIComponent(e)}`);return this.unwrapResponse(n)},approve:async(e,t)=>{let n=this.getRoute(`approvals`),r=await this.fetch(`${this.baseUrl}${n}/requests/${encodeURIComponent(e)}/approve`,{method:`POST`,body:JSON.stringify({actorId:t?.actorId,comment:t?.comment,attachments:t?.attachments})});return this.unwrapResponse(r)},reject:async(e,t)=>{let n=this.getRoute(`approvals`),r=await this.fetch(`${this.baseUrl}${n}/requests/${encodeURIComponent(e)}/reject`,{method:`POST`,body:JSON.stringify({actorId:t?.actorId,comment:t?.comment,attachments:t?.attachments})});return this.unwrapResponse(r)},reassign:async(e,t)=>{let n=this.getRoute(`approvals`),r=await this.fetch(`${this.baseUrl}${n}/requests/${encodeURIComponent(e)}/reassign`,{method:`POST`,body:JSON.stringify({to:t.to,from:t.from,actorId:t.actorId,comment:t.comment})});return this.unwrapResponse(r)},recall:async(e,t)=>{let n=this.getRoute(`approvals`),r=await this.fetch(`${this.baseUrl}${n}/requests/${encodeURIComponent(e)}/recall`,{method:`POST`,body:JSON.stringify({actorId:t?.actorId,comment:t?.comment})});return this.unwrapResponse(r)},revise:async(e,t)=>{let n=this.getRoute(`approvals`),r=await this.fetch(`${this.baseUrl}${n}/requests/${encodeURIComponent(e)}/revise`,{method:`POST`,body:JSON.stringify({actorId:t?.actorId,comment:t?.comment})});return this.unwrapResponse(r)},resubmit:async(e,t)=>{let n=this.getRoute(`approvals`),r=await this.fetch(`${this.baseUrl}${n}/requests/${encodeURIComponent(e)}/resubmit`,{method:`POST`,body:JSON.stringify({actorId:t?.actorId,comment:t?.comment})});return this.unwrapResponse(r)},remind:async(e,t)=>{let n=this.getRoute(`approvals`),r=await this.fetch(`${this.baseUrl}${n}/requests/${encodeURIComponent(e)}/remind`,{method:`POST`,body:JSON.stringify({actorId:t?.actorId,comment:t?.comment})});return this.unwrapResponse(r)},requestInfo:async(e,t)=>{let n=this.getRoute(`approvals`),r=await this.fetch(`${this.baseUrl}${n}/requests/${encodeURIComponent(e)}/request-info`,{method:`POST`,body:JSON.stringify({actorId:t?.actorId,comment:t?.comment})});return this.unwrapResponse(r)},comment:async(e,t)=>{let n=this.getRoute(`approvals`),r=await this.fetch(`${this.baseUrl}${n}/requests/${encodeURIComponent(e)}/comment`,{method:`POST`,body:JSON.stringify({actorId:t.actorId,comment:t.comment,attachments:t.attachments})});return this.unwrapResponse(r)},listActions:async e=>{let t=this.getRoute(`approvals`),n=await this.fetch(`${this.baseUrl}${t}/requests/${encodeURIComponent(e)}/actions`),r=await this.unwrapResponse(n);return Array.isArray(r)?r:r?.data??[]}},this.shares={list:async(e,t)=>{let n=this.getRoute(`data`),r=await this.fetch(`${this.baseUrl}${n}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/shares`),i=await this.unwrapResponse(r);return Array.isArray(i)?i:i?.data??[]},grant:async(e,t,n)=>{let r=this.getRoute(`data`),i=await this.fetch(`${this.baseUrl}${r}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/shares`,{method:`POST`,body:JSON.stringify(n)});return this.unwrapResponse(i)},revoke:async(e,t,n)=>{let r=this.getRoute(`data`),i=await this.fetch(`${this.baseUrl}${r}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/shares/${encodeURIComponent(n)}`,{method:`DELETE`});return i.status===204?{deleted:!0}:this.unwrapResponse(i)},rules:{list:async e=>{let t=new URLSearchParams;e?.object&&t.set(`object`,e.object),e?.activeOnly!==void 0&&t.set(`activeOnly`,String(e.activeOnly));let n=t.toString(),r=await this.fetch(`${this.baseUrl}/api/v1/sharing/rules${n?`?${n}`:``}`),i=await this.unwrapResponse(r);return Array.isArray(i)?i:i?.data??[]},save:async e=>{let t=await this.fetch(`${this.baseUrl}/api/v1/sharing/rules`,{method:`POST`,body:JSON.stringify(e)});return this.unwrapResponse(t)},get:async e=>{let t=await this.fetch(`${this.baseUrl}/api/v1/sharing/rules/${encodeURIComponent(e)}`);return this.unwrapResponse(t)},delete:async e=>{let t=await this.fetch(`${this.baseUrl}/api/v1/sharing/rules/${encodeURIComponent(e)}`,{method:`DELETE`});return t.status===204?{deleted:!0}:this.unwrapResponse(t)},evaluate:async e=>{let t=await this.fetch(`${this.baseUrl}/api/v1/sharing/rules/${encodeURIComponent(e)}/evaluate`,{method:`POST`,body:JSON.stringify({})});return this.unwrapResponse(t)}}},this.search=async(e,t)=>{let n=new URLSearchParams;n.set(`q`,e),t?.objects?.length&&n.set(`objects`,t.objects.join(`,`)),t?.limit!==void 0&&n.set(`limit`,String(t.limit)),t?.perObject!==void 0&&n.set(`perObject`,String(t.perObject));let r=await this.fetch(`${this.baseUrl}/api/v1/search?${n.toString()}`);return this.unwrapResponse(r)},this.reports={list:async e=>{let t=new URLSearchParams;e?.object&&t.set(`object`,e.object),e?.ownerId&&t.set(`ownerId`,e.ownerId);let n=t.toString(),r=await this.fetch(`${this.baseUrl}/api/v1/reports${n?`?${n}`:``}`),i=await this.unwrapResponse(r);return Array.isArray(i)?i:i?.data??[]},save:async e=>{let t=await this.fetch(`${this.baseUrl}/api/v1/reports`,{method:`POST`,body:JSON.stringify(e??{})});return this.unwrapResponse(t)},get:async e=>{let t=await this.fetch(`${this.baseUrl}/api/v1/reports/${encodeURIComponent(e)}`);return this.unwrapResponse(t)},delete:async e=>{let t=await this.fetch(`${this.baseUrl}/api/v1/reports/${encodeURIComponent(e)}`,{method:`DELETE`});return t.status===204?{deleted:!0}:this.unwrapResponse(t)},run:async e=>{let t=await this.fetch(`${this.baseUrl}/api/v1/reports/${encodeURIComponent(e)}/run`,{method:`POST`,body:JSON.stringify({})});return this.unwrapResponse(t)},schedule:async(e,t)=>{let n=await this.fetch(`${this.baseUrl}/api/v1/reports/${encodeURIComponent(e)}/schedule`,{method:`POST`,body:JSON.stringify(t)});return this.unwrapResponse(n)},listSchedules:async e=>{let t=await this.fetch(`${this.baseUrl}/api/v1/reports/${encodeURIComponent(e)}/schedules`),n=await this.unwrapResponse(t);return Array.isArray(n)?n:n?.data??[]},unschedule:async e=>{let t=await this.fetch(`${this.baseUrl}/api/v1/reports/schedules/${encodeURIComponent(e)}`,{method:`DELETE`});return t.status===204?{deleted:!0}:this.unwrapResponse(t)}},this.notifications={list:async e=>{let t=this.getRoute(`notifications`),n=new URLSearchParams;e?.read!==void 0&&n.set(`read`,String(e.read)),e?.type&&n.set(`type`,e.type),e?.limit&&n.set(`limit`,String(e.limit)),e?.cursor&&n.set(`cursor`,e.cursor);let r=n.toString(),i=await this.fetch(`${this.baseUrl}${t}${r?`?${r}`:``}`);return this.unwrapResponse(i)},markRead:async e=>{let t=this.getRoute(`notifications`),n=await this.fetch(`${this.baseUrl}${t}/read`,{method:`POST`,body:JSON.stringify({ids:e})});return this.unwrapResponse(n)},markAllRead:async()=>{let e=this.getRoute(`notifications`),t=await this.fetch(`${this.baseUrl}${e}/read/all`,{method:`POST`});return this.unwrapResponse(t)}},this.ai={chat:async e=>{let t=this.getRoute(`ai`),n=await this.fetch(`${this.baseUrl}${t}/chat`,{method:`POST`,body:JSON.stringify({...e,stream:!1})});return this.unwrapResponse(n)},chatStream:async e=>{let t=this.getRoute(`ai`);return y(await this.fetch(`${this.baseUrl}${t}/chat`,{method:`POST`,headers:{Accept:`text/event-stream`},body:JSON.stringify({...e,stream:!0})}))},complete:async e=>{let t=this.getRoute(`ai`),n=await this.fetch(`${this.baseUrl}${t}/complete`,{method:`POST`,body:JSON.stringify(e)});return this.unwrapResponse(n)},models:async()=>{let e=this.getRoute(`ai`),t=await this.fetch(`${this.baseUrl}${e}/models`);return this.unwrapResponse(t)},conversations:{create:async e=>{let t=this.getRoute(`ai`),n=await this.fetch(`${this.baseUrl}${t}/conversations`,{method:`POST`,body:JSON.stringify(e??{})});return this.unwrapResponse(n)},list:async e=>{let t=this.getRoute(`ai`),n=new URLSearchParams;e?.agentId&&n.set(`agentId`,e.agentId),e?.limit!==void 0&&n.set(`limit`,String(e.limit)),e?.cursor&&n.set(`cursor`,e.cursor);let r=n.toString(),i=await this.fetch(`${this.baseUrl}${t}/conversations${r?`?${r}`:``}`);return(await this.unwrapResponse(i))?.conversations??[]},get:async e=>{let t=this.getRoute(`ai`),n=await this.fetch(`${this.baseUrl}${t}/conversations/${encodeURIComponent(e)}`);return this.unwrapResponse(n)},update:async(e,t)=>{let n=this.getRoute(`ai`),r=await this.fetch(`${this.baseUrl}${n}/conversations/${encodeURIComponent(e)}`,{method:`PATCH`,body:JSON.stringify(t)});return this.unwrapResponse(r)},delete:async e=>{let t=this.getRoute(`ai`),n=await this.fetch(`${this.baseUrl}${t}/conversations/${encodeURIComponent(e)}`,{method:`DELETE`});return n.status===204?{deleted:!0}:this.unwrapResponse(n)},addMessage:async(e,t)=>{let n=this.getRoute(`ai`),r=await this.fetch(`${this.baseUrl}${n}/conversations/${encodeURIComponent(e)}/messages`,{method:`POST`,body:JSON.stringify(t)});return this.unwrapResponse(r)}},agents:{list:async()=>{let e=this.getRoute(`ai`),t=await this.fetch(`${this.baseUrl}${e}/agents`);return(await this.unwrapResponse(t))?.agents??[]},chat:async(e,t)=>{let n=this.getRoute(`ai`),r=await this.fetch(`${this.baseUrl}${n}/agents/${encodeURIComponent(e)}/chat`,{method:`POST`,body:JSON.stringify({...t,stream:!1})});return this.unwrapResponse(r)},chatStream:async(e,t)=>{let n=this.getRoute(`ai`);return y(await this.fetch(`${this.baseUrl}${n}/agents/${encodeURIComponent(e)}/chat`,{method:`POST`,headers:{Accept:`text/event-stream`},body:JSON.stringify({...t,stream:!0})}))}},pendingActions:{list:async e=>{let t=this.getRoute(`ai`),n=new URLSearchParams;e?.status&&n.set(`status`,e.status),e?.conversationId&&n.set(`conversationId`,e.conversationId),e?.limit!==void 0&&n.set(`limit`,String(e.limit));let r=n.toString(),i=await this.fetch(`${this.baseUrl}${t}/pending-actions${r?`?${r}`:``}`);return(await this.unwrapResponse(i))?.items??[]},get:async e=>{let t=this.getRoute(`ai`),n=await this.fetch(`${this.baseUrl}${t}/pending-actions/${encodeURIComponent(e)}`);return this.unwrapResponse(n)},approve:async e=>{let t=this.getRoute(`ai`),n=await this.fetch(`${this.baseUrl}${t}/pending-actions/${encodeURIComponent(e)}/approve`,{method:`POST`,body:JSON.stringify({})});return this.unwrapResponse(n)},reject:async(e,t)=>{let n=this.getRoute(`ai`),r=await this.fetch(`${this.baseUrl}${n}/pending-actions/${encodeURIComponent(e)}/reject`,{method:`POST`,body:JSON.stringify(t===void 0?{}:{reason:t})});return this.unwrapResponse(r)}}},this.i18n={getLocales:async()=>{let e=this.getRoute(`i18n`),t=await this.fetch(`${this.baseUrl}${e}/locales`);return this.unwrapResponse(t)},getTranslations:async e=>{let t=this.getRoute(`i18n`),n=await this.fetch(`${this.baseUrl}${t}/translations/${encodeURIComponent(e)}`);return this.unwrapResponse(n)},getFieldLabels:async(e,t)=>{let n=this.getRoute(`i18n`),r=await this.fetch(`${this.baseUrl}${n}/labels/${encodeURIComponent(e)}/${encodeURIComponent(t)}`);return this.unwrapResponse(r)}},this.data={query:async(e,t)=>{let n=this.getRoute(`data`),r=await this.fetch(`${this.baseUrl}${n}/${e}/query`,{method:`POST`,body:JSON.stringify(t)});return this.unwrapResponse(r)},find:async(e,t={})=>{let n=this.getRoute(`data`),r=new URLSearchParams,i=t,a={};if(`where`in t||`fields`in t||`orderBy`in t||`offset`in t?(i.where&&(a.filter=i.where),i.fields&&(a.select=i.fields),i.orderBy&&(a.sort=i.orderBy),i.limit!=null&&(a.top=i.limit),i.offset!=null&&(a.skip=i.offset),i.aggregations&&(a.aggregations=i.aggregations),i.groupBy&&(a.groupBy=i.groupBy)):Object.assign(a,t),a.top&&r.set(`top`,a.top.toString()),a.skip&&r.set(`skip`,a.skip.toString()),a.sort)if(Array.isArray(a.sort)&&typeof a.sort[0]==`object`)r.set(`sort`,JSON.stringify(a.sort));else{let e=Array.isArray(a.sort)?a.sort.join(`,`):a.sort;r.set(`sort`,e)}a.select&&r.set(`select`,a.select.join(`,`));let o=a.filter??a.filters;o&&(this.isFilterAST(o)||Array.isArray(o)?r.set(`filter`,JSON.stringify(o)):typeof o==`object`&&o&&Object.entries(o).forEach(([e,t])=>{t!=null&&r.append(e,String(t))})),a.aggregations&&r.set(`aggregations`,JSON.stringify(a.aggregations)),a.groupBy&&r.set(`groupBy`,a.groupBy.join(`,`));let s=await this.fetch(`${this.baseUrl}${n}/${e}?${r.toString()}`);return this.unwrapResponse(s)},get:async(e,t)=>{let n=this.getRoute(`data`),r=await this.fetch(`${this.baseUrl}${n}/${e}/${t}`);return this.unwrapResponse(r)},create:async(e,t)=>{let n=this.getRoute(`data`),r=await this.fetch(`${this.baseUrl}${n}/${e}`,{method:`POST`,body:JSON.stringify(t)});return this.unwrapResponse(r)},createMany:async(e,t)=>{let n=this.getRoute(`data`),r=await this.fetch(`${this.baseUrl}${n}/${e}/createMany`,{method:`POST`,body:JSON.stringify(t)});return this.unwrapResponse(r)},import:async(e,t)=>{let n=this.getRoute(`data`),r=await this.fetch(`${this.baseUrl}${n}/${e}/import`,{method:`POST`,body:JSON.stringify(t)});return this.unwrapResponse(r)},createImportJob:async(e,t)=>{let n=this.getRoute(`data`),r=await this.fetch(`${this.baseUrl}${n}/${e}/import/jobs`,{method:`POST`,body:JSON.stringify(t)});return this.unwrapResponse(r)},getImportJobProgress:async e=>{let t=this.getRoute(`data`),n=await this.fetch(`${this.baseUrl}${t}/import/jobs/${encodeURIComponent(e)}`);return this.unwrapResponse(n)},getImportJobResults:async e=>{let t=this.getRoute(`data`),n=await this.fetch(`${this.baseUrl}${t}/import/jobs/${encodeURIComponent(e)}/results`);return this.unwrapResponse(n)},listImportJobs:async(e={})=>{let t=this.getRoute(`data`),n=new URLSearchParams;e.object&&n.set(`object`,e.object),e.status&&n.set(`status`,e.status),e.limit!=null&&n.set(`limit`,String(e.limit)),e.offset!=null&&n.set(`offset`,String(e.offset));let r=n.toString()?`?${n.toString()}`:``,i=await this.fetch(`${this.baseUrl}${t}/import/jobs${r}`);return(await this.unwrapResponse(i)).jobs},cancelImportJob:async e=>{let t=this.getRoute(`data`),n=await this.fetch(`${this.baseUrl}${t}/import/jobs/${encodeURIComponent(e)}/cancel`,{method:`POST`});return this.unwrapResponse(n)},undoImportJob:async e=>{let t=this.getRoute(`data`),n=await this.fetch(`${this.baseUrl}${t}/import/jobs/${encodeURIComponent(e)}/undo`,{method:`POST`});return this.unwrapResponse(n)},update:async(e,t,n,r)=>{let i=this.getRoute(`data`),a={};r?.ifMatch&&(a[`If-Match`]=String(r.ifMatch));let o=await this.fetch(`${this.baseUrl}${i}/${e}/${t}`,{method:`PATCH`,body:JSON.stringify(n),...Object.keys(a).length?{headers:a}:{}});return this.unwrapResponse(o)},batch:async(e,t)=>{let n=this.getRoute(`data`),r=await this.fetch(`${this.baseUrl}${n}/${e}/batch`,{method:`POST`,body:JSON.stringify(t)});return this.unwrapResponse(r)},batchTransaction:async e=>{let t=this.getRoute(`data`).replace(/\/[^/]+\/?$/,``)||`/api/v1`,n={operations:e,atomic:!0},r=await this.fetch(`${this.baseUrl}${t}/batch`,{method:`POST`,body:JSON.stringify(n)});return this.unwrapResponse(r)},updateMany:async(e,t,n)=>{let r=this.getRoute(`data`),i={records:t,options:n},a=await this.fetch(`${this.baseUrl}${r}/${e}/updateMany`,{method:`POST`,body:JSON.stringify(i)});return this.unwrapResponse(a)},delete:async(e,t,n)=>{let r=this.getRoute(`data`),i={};n?.ifMatch&&(i[`If-Match`]=String(n.ifMatch));let a=await this.fetch(`${this.baseUrl}${r}/${e}/${t}`,{method:`DELETE`,...Object.keys(i).length?{headers:i}:{}});return this.unwrapResponse(a)},deleteMany:async(e,t,n)=>{let r=this.getRoute(`data`),i={ids:t,options:n},a=await this.fetch(`${this.baseUrl}${r}/${e}/deleteMany`,{method:`POST`,body:JSON.stringify(i)});return this.unwrapResponse(a)},clone:async(e,t,n)=>{let r=this.getRoute(`data`),i=await this.fetch(`${this.baseUrl}${r}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/clone`,{method:`POST`,body:JSON.stringify(n?{overrides:n}:{})});return this.unwrapResponse(i)},export:async(e,t)=>{let n=this.getRoute(`data`),r=new URLSearchParams;t?.format&&r.set(`format`,t.format),t?.limit!==void 0&&r.set(`limit`,String(t.limit)),t?.filter!==void 0&&r.set(`filter`,typeof t.filter==`string`?t.filter:JSON.stringify(t.filter)),t?.orderby!==void 0&&r.set(`orderby`,typeof t.orderby==`string`?t.orderby:JSON.stringify(t.orderby)),t?.header!==void 0&&r.set(`header`,String(t.header));let i=r.toString();return this.fetch(`${this.baseUrl}${n}/${encodeURIComponent(e)}/export${i?`?${i}`:``}`)}},this.baseUrl=e.baseUrl.replace(/\/$/,``),this.token=e.token,this.environmentId=e.environmentId,this.locale=e.locale,this.fetchImpl=e.fetch||globalThis.fetch.bind(globalThis),this.logger=e.logger||(0,p.createLogger)({level:e.debug?`debug`:`info`,format:`pretty`}),this.realtimeAPI=new m(this.baseUrl,this.token),this.logger.debug(`ObjectStack client created`,{baseUrl:this.baseUrl})}async connect(){this.logger.debug(`Connecting to ObjectStack server`,{baseUrl:this.baseUrl});try{let e;try{let t=`${this.baseUrl}/api/v1/discovery`;this.logger.debug(`Probing protocol-standard discovery endpoint`,{url:t});let n=await this.fetchImpl(t);if(n.ok){let t=await n.json();e=t.data||t,this.logger.debug(`Discovered via /api/v1/discovery`)}}catch(e){this.logger.debug(`Protocol-standard discovery probe failed`,{error:e.message})}if(!e){let t;try{t=`${new URL(this.baseUrl).origin}/.well-known/objectstack`}catch{t=`/.well-known/objectstack`}this.logger.debug(`Falling back to .well-known discovery`,{url:t});let n=await this.fetchImpl(t);if(!n.ok)throw Error(`Failed to connect to ${t}: ${n.statusText}`);let r=await n.json();e=r.data||r}if(!e)throw Error(`Connection failed: No discovery data returned`);return this.discoveryInfo=e,this.logger.info(`Connected to ObjectStack server`,{version:e.version,apiName:e.apiName,services:e.services}),e}catch(e){throw this.logger.error(`Failed to connect to ObjectStack server`,e,{baseUrl:this.baseUrl}),e}}get capabilities(){let e=this.discoveryInfo?.capabilities;if(!e)return;let t={};for(let[n,r]of Object.entries(e))t[n]=typeof r==`object`&&r?!!r.enabled:!!r;return t}project(e){if(!e)throw Error(`[ObjectStack] project(id): environmentId is required`);return new C(this,e)}_baseUrl(){return this.baseUrl}_fetch(e,t){return this.fetch(e,t)}_unwrap(e){return this.unwrapResponse(e)}_isFilterAST(e){return this.isFilterAST(e)}setProjectId(e){this.environmentId=e,this.logger.debug(`Active project changed`,{environmentId:e})}getProjectId(){return this.environmentId}setLocale(e){this.locale=e,this.logger.debug(`Active locale changed`,{locale:e})}getLocale(){return this.locale}get events(){return this.realtimeAPI}isFilterAST(e){return(0,f.isFilterAST)(e)}async unwrapResponse(e){let t=await e.json();return t&&typeof t.success==`boolean`&&`data`in t?t.data:t}async fetch(e,t={}){this.logger.debug(`HTTP request`,{method:t.method||`GET`,url:e,hasBody:!!t.body});let n={"Content-Type":`application/json`,...t.headers||{}};this.token&&(n.Authorization=`Bearer ${this.token}`),this.environmentId&&(n[`X-Environment-Id`]=this.environmentId),this.locale&&!Object.keys(n).some(e=>e.toLowerCase()===`accept-language`)&&(n[`Accept-Language`]=this.locale);let r=await this.fetchImpl(e,{...t,headers:n});if(this.logger.debug(`HTTP response`,{method:t.method||`GET`,url:e,status:r.status,ok:r.ok}),!r.ok){let n;try{n=await r.json()}catch{n={message:r.statusText}}this.logger.error(`HTTP request failed`,void 0,{method:t.method||`GET`,url:e,status:r.status,error:n});let i=n?.message??n?.error?.message??(typeof n?.error==`string`?n.error:void 0)??r.statusText,a=e=>typeof e==`string`&&e?e:void 0,o=a(n?.code)??a(n?.error?.code),s=Array.isArray(n?.fields)?n.fields:Array.isArray(n?.error?.details?.fields)?n.error.details.fields:void 0,c=Error(i);throw c.code=o,c.category=n?.error?.category,c.httpStatus=r.status,c.retryable=n?.error?.retryable,c.details=n?.details??n?.error?.details??n,s&&(c.fields=s),c}return r}getRoute(e){let t=this.discoveryInfo?.routes;if(t){let n=t[e];if(n)return n}return{data:`/api/v1/data`,metadata:`/api/v1/meta`,discovery:`/api/v1/discovery`,ui:`/api/v1/ui`,auth:`/api/v1/auth`,analytics:`/api/v1/analytics`,storage:`/api/v1/storage`,automation:`/api/v1/automation`,packages:`/api/v1/packages`,realtime:`/api/v1/realtime`,workflow:`/api/v1/workflow`,approvals:`/api/v1/approvals`,notifications:`/api/v1/notifications`,ai:`/api/v1/ai`,i18n:`/api/v1/i18n`}[e]||`/api/v1/${e}`}},C=class{constructor(e,t){this.meta={getTypes:async()=>{let e=await this.parent._fetch(this.url(`/meta`));return this.parent._unwrap(e)},getItems:async(e,t)=>{let n=new URLSearchParams;t?.packageId&&n.set(`package`,t.packageId);let r=n.toString(),i=await this.parent._fetch(this.url(`/meta/${e}${r?`?${r}`:``}`));return this.parent._unwrap(i)},getItem:async(e,t,n)=>{let r=new URLSearchParams;n?.packageId&&r.set(`package`,n.packageId);let i=r.toString(),a=await this.parent._fetch(this.url(`/meta/${e}/${t}${i?`?${i}`:``}`));return this.parent._unwrap(a)},saveItem:async(e,t,n)=>{let r=await this.parent._fetch(this.url(`/meta/${e}/${t}`),{method:`PUT`,body:JSON.stringify(n)});return this.parent._unwrap(r)},deleteItem:async(e,t)=>{let n=await this.parent._fetch(this.url(`/meta/${encodeURIComponent(e)}/${encodeURIComponent(t)}`),{method:`DELETE`});return this.parent._unwrap(n)},getHistory:async(e,t,n)=>{let r=new URLSearchParams;n?.sinceSeq!==void 0&&r.set(`sinceSeq`,String(n.sinceSeq)),n?.limit!==void 0&&r.set(`limit`,String(n.limit));let i=r.toString(),a=await this.parent._fetch(this.url(`/meta/${encodeURIComponent(e)}/${encodeURIComponent(t)}/history${i?`?${i}`:``}`));return this.parent._unwrap(a)}},this.data={query:async(e,t)=>{let n=await this.parent._fetch(this.url(`/data/${e}/query`),{method:`POST`,body:JSON.stringify(t)});return this.parent._unwrap(n)},find:async(e,t={})=>{let n=new URLSearchParams,r=t,i={};if(`where`in t||`fields`in t||`orderBy`in t||`offset`in t?(r.where&&(i.filter=r.where),r.fields&&(i.select=r.fields),r.orderBy&&(i.sort=r.orderBy),r.limit!=null&&(i.top=r.limit),r.offset!=null&&(i.skip=r.offset),r.aggregations&&(i.aggregations=r.aggregations),r.groupBy&&(i.groupBy=r.groupBy)):Object.assign(i,t),i.top&&n.set(`top`,i.top.toString()),i.skip&&n.set(`skip`,i.skip.toString()),i.sort)if(Array.isArray(i.sort)&&typeof i.sort[0]==`object`)n.set(`sort`,JSON.stringify(i.sort));else{let e=Array.isArray(i.sort)?i.sort.join(`,`):i.sort;n.set(`sort`,e)}i.select&&n.set(`select`,i.select.join(`,`));let a=i.filter??i.filters;a&&(this.parent._isFilterAST(a)||Array.isArray(a)?n.set(`filter`,JSON.stringify(a)):typeof a==`object`&&a&&Object.entries(a).forEach(([e,t])=>{t!=null&&n.append(e,String(t))})),i.aggregations&&n.set(`aggregations`,JSON.stringify(i.aggregations)),i.groupBy&&n.set(`groupBy`,i.groupBy.join(`,`));let o=n.toString(),s=await this.parent._fetch(this.url(`/data/${e}${o?`?${o}`:``}`));return this.parent._unwrap(s)},get:async(e,t)=>{let n=await this.parent._fetch(this.url(`/data/${e}/${t}`));return this.parent._unwrap(n)},create:async(e,t)=>{let n=await this.parent._fetch(this.url(`/data/${e}`),{method:`POST`,body:JSON.stringify(t)});return this.parent._unwrap(n)},createMany:async(e,t)=>{let n=await this.parent._fetch(this.url(`/data/${e}/createMany`),{method:`POST`,body:JSON.stringify(t)});return this.parent._unwrap(n)},import:async(e,t)=>{let n=await this.parent._fetch(this.url(`/data/${e}/import`),{method:`POST`,body:JSON.stringify(t)});return this.parent._unwrap(n)},createImportJob:async(e,t)=>{let n=await this.parent._fetch(this.url(`/data/${e}/import/jobs`),{method:`POST`,body:JSON.stringify(t)});return this.parent._unwrap(n)},getImportJobProgress:async e=>{let t=await this.parent._fetch(this.url(`/data/import/jobs/${encodeURIComponent(e)}`));return this.parent._unwrap(t)},getImportJobResults:async e=>{let t=await this.parent._fetch(this.url(`/data/import/jobs/${encodeURIComponent(e)}/results`));return this.parent._unwrap(t)},listImportJobs:async(e={})=>{let t=new URLSearchParams;e.object&&t.set(`object`,e.object),e.status&&t.set(`status`,e.status),e.limit!=null&&t.set(`limit`,String(e.limit)),e.offset!=null&&t.set(`offset`,String(e.offset));let n=t.toString()?`?${t.toString()}`:``,r=await this.parent._fetch(this.url(`/data/import/jobs${n}`));return(await this.parent._unwrap(r)).jobs},cancelImportJob:async e=>{let t=await this.parent._fetch(this.url(`/data/import/jobs/${encodeURIComponent(e)}/cancel`),{method:`POST`});return this.parent._unwrap(t)},undoImportJob:async e=>{let t=await this.parent._fetch(this.url(`/data/import/jobs/${encodeURIComponent(e)}/undo`),{method:`POST`});return this.parent._unwrap(t)},update:async(e,t,n)=>{let r=await this.parent._fetch(this.url(`/data/${e}/${t}`),{method:`PATCH`,body:JSON.stringify(n)});return this.parent._unwrap(r)},batch:async(e,t)=>{let n=await this.parent._fetch(this.url(`/data/${e}/batch`),{method:`POST`,body:JSON.stringify(t)});return this.parent._unwrap(n)},batchTransaction:async e=>{let t={operations:e,atomic:!0},n=await this.parent._fetch(this.url(`/batch`),{method:`POST`,body:JSON.stringify(t)});return this.parent._unwrap(n)},updateMany:async(e,t,n)=>{let r={records:t,options:n},i=await this.parent._fetch(this.url(`/data/${e}/updateMany`),{method:`POST`,body:JSON.stringify(r)});return this.parent._unwrap(i)},delete:async(e,t)=>{let n=await this.parent._fetch(this.url(`/data/${e}/${t}`),{method:`DELETE`});return this.parent._unwrap(n)},deleteMany:async(e,t,n)=>{let r={ids:t,options:n},i=await this.parent._fetch(this.url(`/data/${e}/deleteMany`),{method:`POST`,body:JSON.stringify(r)});return this.parent._unwrap(i)}},this.packages={list:async()=>{let e=await this.parent._fetch(this.url(`/packages`));return this.parent._unwrap(e)},get:async(e,t)=>{let n=t?`?version=${encodeURIComponent(t)}`:``,r=await this.parent._fetch(this.url(`/packages/${encodeURIComponent(e)}${n}`));return this.parent._unwrap(r)}},this.automation={getFlow:async e=>{let t=await this.parent._fetch(this.url(`/automation/${encodeURIComponent(e)}`));return this.parent._unwrap(t)},execute:async(e,t)=>{let n=await this.parent._fetch(this.url(`/automation/${encodeURIComponent(e)}/trigger`),{method:`POST`,body:JSON.stringify(t??{})});return this.parent._unwrap(n)},listRuns:async(e,t)=>{let n=new URLSearchParams;t?.limit!=null&&n.set(`limit`,String(t.limit)),t?.cursor&&n.set(`cursor`,t.cursor);let r=n.toString(),i=await this.parent._fetch(this.url(`/automation/${encodeURIComponent(e)}/runs${r?`?${r}`:``}`));return this.parent._unwrap(i)},getRun:async(e,t)=>{let n=await this.parent._fetch(this.url(`/automation/${encodeURIComponent(e)}/runs/${encodeURIComponent(t)}`));return this.parent._unwrap(n)},resume:async(e,t,n)=>{let r=await this.parent._fetch(this.url(`/automation/${encodeURIComponent(e)}/runs/${encodeURIComponent(t)}/resume`),{method:`POST`,body:JSON.stringify(n??{})});return this.parent._unwrap(r)},getScreen:async(e,t)=>{let n=await this.parent._fetch(this.url(`/automation/${encodeURIComponent(e)}/runs/${encodeURIComponent(t)}/screen`));return this.parent._unwrap(n)}},this.parent=e,this.environmentId=t}getProjectId(){return this.environmentId}scope(){return`/api/v1/environments/${encodeURIComponent(this.environmentId)}`}url(e){return`${this.parent._baseUrl()}${this.scope()}${e}`}};0&&(t.exports={FilterBuilder:h,ObjectStackClient:S,QueryBuilder:g,RealtimeAPI:m,ScopedProjectClient:C,createFilter:v,createQuery:_})}))(),l=class{cache;inflight;maxSize;ttl;stats;constructor(e={}){this.cache=new Map,this.inflight=new Map,this.maxSize=e.maxSize||100,this.ttl=e.ttl||300*1e3,this.stats={hits:0,misses:0,evictions:0,coalesced:0}}async get(e,t){let n=Date.now(),r=this.cache.get(e);if(r){if(n-r.timestamp<this.ttl)return r.accessCount++,r.lastAccessed=n,this.stats.hits++,this.cache.delete(e),this.cache.set(e,r),r.data;this.cache.delete(e)}let i=this.inflight.get(e);if(i)return this.stats.coalesced++,i;this.stats.misses++;let a=(async()=>{try{let n=await t();return this.set(e,n),n}finally{this.inflight.delete(e)}})();return this.inflight.set(e,a),a}prime(e,t){this.set(e,t)}set(e,t){let n=Date.now();this.cache.size>=this.maxSize&&!this.cache.has(e)&&this.evictLRU(),this.cache.set(e,{data:t,timestamp:n,accessCount:1,lastAccessed:n})}evictLRU(){let e=this.cache.keys().next().value;e!==void 0&&(this.cache.delete(e),this.stats.evictions++)}invalidate(e){e?this.cache.delete(e):this.cache.clear()}clear(){this.cache.clear(),this.inflight.clear(),this.stats={hits:0,misses:0,evictions:0,coalesced:0}}getStats(){let e=this.stats.hits+this.stats.misses,t=e>0?this.stats.hits/e:0;return{size:this.cache.size,maxSize:this.maxSize,hits:this.stats.hits,misses:this.stats.misses,evictions:this.stats.evictions,coalesced:this.stats.coalesced,hitRate:t}}getCachedSync(e){let t=this.cache.get(e);if(t){if(this.ttl>0&&Date.now()-t.timestamp>this.ttl){this.cache.delete(e);return}return this.cache.delete(e),this.cache.set(e,t),this.stats.hits++,t.data}}has(e){let t=this.cache.get(e);return t?Date.now()-t.timestamp>=this.ttl?(this.cache.delete(e),!1):!0:!1}},u=`/meta`,d=`/api/v1`;function f(e){let t=e.baseUrl.replace(/\/+$/,``),n=e.environmentId?`${d}/environments/${encodeURIComponent(e.environmentId)}${u}`:`${d}${u}`;return/\/api\/v\d+$/i.test(t)?`${t.replace(/\/api\/v\d+$/i,``)}${e.environmentId?`${d}/environments/${encodeURIComponent(e.environmentId)}${u}`:`${d}${u}`}`:`${t}${n}`}async function p(e){let t;try{t=await e.json()}catch{t=await e.text().catch(()=>void 0)}let n=t&&typeof t==`object`?t:void 0,r=n?.error,i=(r&&typeof r==`object`?r.message:r)??n?.message??`Metadata request failed: ${e.status} ${e.statusText}`,a=Error(String(i));a.status=e.status,a.body=t;let o=r&&typeof r==`object`?r.details:void 0,s=o?.issues??(r&&typeof r==`object`?r.issues:void 0)??n?.issues;Array.isArray(s)&&(a.issues=s);let c=o?.code??(r&&typeof r==`object`?r.code:void 0)??n?.code;return c!=null&&(a.code=String(c)),a}var m=class e{base;fetchImpl;headers;previewDrafts;constructor(e){this.base=f(e),this.fetchImpl=e.fetch??globalThis.fetch.bind(globalThis),this.headers={Accept:`application/json`,...e.headers??{}},this.previewDrafts=e.previewDrafts===!0}withEnvironment(t){return new e({baseUrl:this.base.replace(/\/api\/v\d+(?:\/environments\/[^/]+)?\/meta$/,``).replace(/\/+$/,``),environmentId:t,fetch:this.fetchImpl,headers:this.headers,previewDrafts:this.previewDrafts})}withPreviewDrafts(t){if(t===this.previewDrafts)return this;let n=this.base.match(/\/api\/v\d+\/environments\/([^/]+)\/meta$/);return new e({baseUrl:this.base.replace(/\/api\/v\d+(?:\/environments\/[^/]+)?\/meta$/,``).replace(/\/+$/,``),...n?{environmentId:decodeURIComponent(n[1])}:{},fetch:this.fetchImpl,headers:this.headers,previewDrafts:t})}async listTypes(){let e=await this.fetchImpl(this.base,{method:`GET`,headers:this.headers,cache:`no-store`});if(!e.ok)throw await p(e);let t=await e.json();return Array.isArray(t)?t:t&&Array.isArray(t.entries)?t.entries:t&&Array.isArray(t.items)?t.items:t&&Array.isArray(t.types)?t.types.map(e=>({type:e})):[]}async list(e,t={}){let n=[];t.packageId&&n.push(`package=${encodeURIComponent(t.packageId)}`),this.previewDrafts&&n.push(`preview=draft`);let r=n.length?`?${n.join(`&`)}`:``,i=`${this.base}/${encodeURIComponent(e)}${r}`,a=await this.fetchImpl(i,{method:`GET`,headers:this.headers,cache:`no-store`});if(!a.ok)throw await p(a);let o=await a.json();return Array.isArray(o)?o:o&&Array.isArray(o.items)?o.items:[]}async listDrafts(e={}){let t=[];e.packageId&&t.push(`packageId=${encodeURIComponent(e.packageId)}`),e.type&&t.push(`type=${encodeURIComponent(e.type)}`);let n=t.length?`?${t.join(`&`)}`:``,r=`${this.base}/_drafts${n}`,i=await this.fetchImpl(r,{method:`GET`,headers:this.headers,cache:`no-store`});if(!i.ok)throw await p(i);let a=await i.json();return Array.isArray(a)?a:a?.drafts??a?.data?.drafts??[]}async get(e,t,n={}){let r=[];n.state===`draft`?r.push(`state=draft`):this.previewDrafts&&r.push(`preview=draft`),n.packageId&&r.push(`package=${encodeURIComponent(n.packageId)}`);let i=r.length?`?${r.join(`&`)}`:``,a=`${this.base}/${encodeURIComponent(e)}/${encodeURIComponent(t)}${i}`,o=await this.fetchImpl(a,{method:`GET`,headers:this.headers,cache:`no-store`});if(o.status===404)return null;if(!o.ok)throw await p(o);return await o.json()}async getDraft(e,t,n={}){return this.get(e,t,{state:`draft`,...n.packageId?{packageId:n.packageId}:{}})}async save(e,t,n,r={}){if(!t||!String(t).trim())throw Error(`MetadataClient.save: name must be non-empty (type="${e}"). The PUT /meta/:type/:name route requires a name segment.`);let i=[];r.force&&i.push(`force=true`),r.mode===`draft`&&i.push(`mode=draft`),r.packageId&&i.push(`package=${encodeURIComponent(r.packageId)}`);let a=i.length?`?${i.join(`&`)}`:``,o=`${this.base}/${encodeURIComponent(e)}/${encodeURIComponent(t)}${a}`,s={...this.headers,"Content-Type":`application/json`};r.ifMatch&&(s[`If-Match`]=r.ifMatch),r.actor&&(s[`X-Actor`]=r.actor);let c=await this.fetchImpl(o,{method:`PUT`,headers:s,body:JSON.stringify(n)});if(!c.ok)throw await p(c);return await c.json()}async publishDraft(e,t){let n=`${this.base}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/publish`,r=await this.fetchImpl(n,{method:`POST`,headers:{...this.headers,"Content-Type":`application/json`,Accept:`application/json`},body:`{}`});if(!r.ok)throw await p(r);let i=await r.json().catch(()=>({}));return i?.data&&typeof i.data==`object`?i.data:i}async layered(e,t,n={}){let r=n.packageId?`&package=${encodeURIComponent(n.packageId)}`:``,i=`${this.base}/${encodeURIComponent(e)}/${encodeURIComponent(t)}?layers=true${r}`,a=await this.fetchImpl(i,{method:`GET`,headers:this.headers,cache:`no-store`});if(a.status===404)return{code:null,overlay:null,overlayScope:null,effective:null};if(!a.ok)throw await p(a);let o=await a.json();return o&&(`code`in o||`overlay`in o||`effective`in o)?{code:o.code??null,overlay:o.overlay??null,overlayScope:o.overlayScope??null,effective:o.effective??null,...o._diagnostics?{_diagnostics:o._diagnostics}:{},...o.lock===void 0?{}:{lock:o.lock},...o.lockReason===void 0?{}:{lockReason:o.lockReason},...o.lockSource===void 0?{}:{lockSource:o.lockSource},...o.lockDocsUrl===void 0?{}:{lockDocsUrl:o.lockDocsUrl},...o.provenance===void 0?{}:{provenance:o.provenance},...o.packageId===void 0?{}:{packageId:o.packageId},...o.packageVersion===void 0?{}:{packageVersion:o.packageVersion},...o.editable===void 0?{}:{editable:o.editable},...o.deletable===void 0?{}:{deletable:o.deletable},...o.resettable===void 0?{}:{resettable:o.resettable}}:{code:null,overlay:null,overlayScope:null,effective:o}}async diagnostics(e={}){let t=[];e.type&&t.push(`type=${encodeURIComponent(e.type)}`),e.severity&&t.push(`severity=${encodeURIComponent(e.severity)}`),e.packageId&&t.push(`package=${encodeURIComponent(e.packageId)}`);let n=t.length?`?${t.join(`&`)}`:``,r=`${this.base}/diagnostics${n}`,i=await this.fetchImpl(r,{method:`GET`,headers:this.headers,cache:`no-store`});if(i.status===404)return{entries:[],total:0,scannedTypes:0,scannedItems:0,stats:{}};if(!i.ok)throw await p(i);let a=await i.json();return{entries:Array.isArray(a.entries)?a.entries:[],total:typeof a.total==`number`?a.total:0,scannedTypes:typeof a.scannedTypes==`number`?a.scannedTypes:0,scannedItems:typeof a.scannedItems==`number`?a.scannedItems:0,stats:a.stats&&typeof a.stats==`object`?a.stats:{}}}async references(e,t){let n=`${this.base}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/references`,r=await this.fetchImpl(n,{method:`GET`,headers:this.headers,cache:`no-store`});if(r.status===404)return[];if(!r.ok)throw await p(r);let i=await r.json();return Array.isArray(i)?i:i?.items??[]}async reset(e,t,n={}){let r=n.state===`draft`?`?state=draft`:``,i=`${this.base}/${encodeURIComponent(e)}/${encodeURIComponent(t)}${r}`,a={...this.headers};n.ifMatch&&(a[`If-Match`]=n.ifMatch),n.actor&&(a[`X-Actor`]=n.actor);let o=await this.fetchImpl(i,{method:`DELETE`,headers:a});if(!o.ok)throw await p(o);return await o.json()}async publish(e,t,n={}){let r=`${this.base}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/publish`,i={...this.headers,"Content-Type":`application/json`};n.actor&&(i[`X-Actor`]=n.actor);let a=await this.fetchImpl(r,{method:`POST`,headers:i,body:JSON.stringify(n.message?{message:n.message}:{})});if(!a.ok)throw await p(a);return await a.json()}async rollback(e,t,n,r={}){let i=`${this.base}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/rollback`,a={...this.headers,"Content-Type":`application/json`};r.actor&&(a[`X-Actor`]=r.actor);let o=await this.fetchImpl(i,{method:`POST`,headers:a,body:JSON.stringify({toVersion:n,...r.message?{message:r.message}:{}})});if(!o.ok)throw await p(o);return await o.json()}async diff(e,t,n,r){let i=new URLSearchParams;n!==void 0&&i.set(`from`,String(n)),r!==void 0&&i.set(`to`,String(r));let a=i.toString(),o=`${this.base}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/diff${a?`?${a}`:``}`,s=await this.fetchImpl(o,{method:`GET`,headers:this.headers,cache:`no-store`});if(!s.ok)throw await p(s);return await s.json()}async history(e,t,n={}){let r=new URLSearchParams;n.sinceSeq!==void 0&&r.set(`sinceSeq`,String(n.sinceSeq)),n.limit!==void 0&&r.set(`limit`,String(n.limit));let i=r.toString(),a=`${this.base}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/history${i?`?${i}`:``}`,o=await this.fetchImpl(a,{method:`GET`,headers:this.headers,cache:`no-store`});if(!o.ok)throw await p(o);return await o.json()}async audit(e,t,n={}){let r=new URLSearchParams;n.limit!==void 0&&r.set(`limit`,String(n.limit));let i=r.toString(),a=`${this.base}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/audit${i?`?${i}`:``}`,o=await this.fetchImpl(a,{method:`GET`,headers:this.headers,cache:`no-store`});if(!o.ok)throw await p(o);return await o.json()}},h=class extends Error{code;statusCode;details;constructor(e,t,n,r){super(e),this.code=t,this.statusCode=n,this.details=r,this.name=`ObjectStackError`,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,message:this.message,code:this.code,statusCode:this.statusCode,details:this.details,stack:this.stack}}},g=class extends h{constructor(e,t){super(`Metadata not found for object: ${e}`,`METADATA_NOT_FOUND`,404,{objectName:e,...t}),this.name=`MetadataNotFoundError`}},_=class extends h{successCount;failureCount;errors;constructor(e,t,n,r,i){super(`Bulk ${e} operation failed: ${t} succeeded, ${n} failed`,`BULK_OPERATION_ERROR`,500,{operation:e,successCount:t,failureCount:n,errors:r,...i}),this.successCount=t,this.failureCount=n,this.errors=r,this.name=`BulkOperationError`}getSummary(){let e=this.successCount+this.failureCount,t=e>0?this.failureCount/e:0;return{operation:this.details?.operation,total:e,successful:this.successCount,failed:this.failureCount,failureRate:t,errors:this.errors}}},v=class extends h{url;constructor(e,t,n,r){super(`Connection error: ${e}`,`CONNECTION_ERROR`,r||503,{url:t,...n}),this.url=t,this.name=`ConnectionError`}},y=class extends h{constructor(e=`Authentication failed`,t,n){super(e,`AUTHENTICATION_ERROR`,n||401,t),this.name=`AuthenticationError`}},b=class extends h{field;validationErrors;constructor(e,t,n,r){super(e,`VALIDATION_ERROR`,400,{field:t,validationErrors:n,...r}),this.field=t,this.validationErrors=n,this.name=`ValidationError`}getValidationErrors(){return this.validationErrors||[]}};function x(e,t){let n=e?.status||e?.statusCode||500,r=e?.message||e?.statusText||`Unknown error`,i={context:t,response:{status:n,data:e?.data,headers:e?.headers}};switch(n){case 401:return new y(r,i,401);case 403:return new y(r,i,403);case 404:return t?.includes(`metadata`)||t?.includes(`schema`)||t?.includes(`getObjectSchema`)?new g(S(t),i):new h(r,`NOT_FOUND`,404,i);case 400:return new b(r,void 0,e?.data?.errors,i);case 503:return new v(r,e?.config?.url,i,503);case 504:return new v(r,e?.config?.url,i,504);default:return new h(r,`UNKNOWN_ERROR`,n,i)}}function S(e){if(!e)return`unknown`;let t=e.match(/\(([^)]+)\)/);return t?t[1]:`unknown`}var C=`sys_user_preference`;function ee(e){let{dataSource:t,userId:n,key:r,resource:i=C,onError:a=()=>{}}=e,o=null,s=Promise.resolve(),c=async()=>{let e={$filter:{user_id:n,key:r},$top:1};return((await t.find(i,e))?.data??[]).find(e=>{if(!e)return!1;let t=e.user_id!==void 0&&e.user_id!==n,i=e.key!==void 0&&e.key!==r;return!t&&!i})??null},l=e=>{if(Array.isArray(e))return e;if(typeof e==`string`)try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}return[]},u=async e=>{if(o!==null)try{await t.update(i,o,{value:e});return}catch(e){o=null,a(`save`,e)}let s=await c();if(s&&s.id!==void 0&&s.id!==null){o=s.id,await t.update(i,s.id,{value:e});return}try{let a=(await t.create(i,{user_id:n,key:r,value:e}))?.id;a!=null&&(o=a)}catch(n){let r=await c();if(r&&r.id!==void 0&&r.id!==null){o=r.id,await t.update(i,r.id,{value:e});return}throw n}};return{async load(){try{let e=await c();return e?(e.id!==void 0&&e.id!==null&&(o=e.id),l(e.value)):(o=null,[])}catch(e){return a(`load`,e),[]}},async save(e){let t=s.then(()=>u(e)).catch(e=>{a(`save`,e)});return s=t,t}}}var w={equals:`=`,eq:`=`,"==":`=`,not_equals:`!=`,notequals:`!=`,ne:`!=`,greater_than:`>`,greaterthan:`>`,gt:`>`,greater_than_or_equal:`>=`,greater_than_or_equals:`>=`,greaterthanorequal:`>=`,gte:`>=`,less_than:`<`,lessthan:`<`,lt:`<`,less_than_or_equal:`<=`,less_than_or_equals:`<=`,lessthanorequal:`<=`,lte:`<=`,in:`in`,not_in:`nin`,notin:`nin`,nin:`nin`,contains:`contains`,not_contains:`notcontains`,notcontains:`notcontains`,starts_with:`startswith`,startswith:`startswith`,ends_with:`endswith`,endswith:`endswith`,between:`between`,is_null:`isnull`,isnull:`isnull`,is_not_null:`isnotnull`,isnotnull:`isnotnull`,before:`<`,after:`>`};function T(e){return typeof e==`string`?w[e.toLowerCase()]??w[e]??e:null}var te=class extends Error{code=`INVALID_FILTER`;httpStatus=400;entry;index;constructor(e,t){let n=JSON.stringify(e)??String(e);super(`Filter entry ${t} is not a usable filter rule (${n}). Expected { field, operator, value } with a non-empty field.`),this.name=`MalformedFilterError`,this.entry=e,this.index=t}};function E(e){if(!e||typeof e!=`object`)return null;let t=e.field,n=T(e.operator??e.op??`=`);return!t||!n?null:[String(t),n,e.value]}function ne(e){let t=e[0];return e.length>0&&typeof t==`object`&&!!t&&!Array.isArray(t)&&t.field!==void 0}function re(e){let t=e.map((e,t)=>{if(Array.isArray(e))return O(e);let n=E(e);if(!n)throw new te(e,t);return n});return t.length===1?t[0]:[`and`,...t]}var ie=new Set([`and`,`or`]);function D(e){if(ne(e))return re(e);let t=e[0];return typeof t==`string`&&ie.has(t.toLowerCase())?[t,...e.slice(1).map(O)]:e.every(e=>Array.isArray(e))?e.map(O):e}function O(e){if(Array.isArray(e))return e.length>0?D(e):e;if(e&&typeof e==`object`&&e.field!==void 0){let t=E(e);if(t)return t}return e}function k(e){if(e!=null){if(Array.isArray(e))return e.length===0?void 0:D(e);if(typeof e==`object`)return Object.keys(e).length===0?void 0:t(e)}}function A(e){if(e==null)return;if(typeof e==`string`){let t=e.trim();return t.length>0?t:void 0}let t=(e,t)=>String(t).toLowerCase()===`desc`?`-${e}`:e;if(Array.isArray(e)){let n=e.map(e=>typeof e==`string`?e.trim():t(e.field,e.order)).filter(e=>e.length>0);return n.length>0?n.join(`,`):void 0}if(typeof e==`object`){let n=Object.entries(e).map(([e,n])=>t(e,n));return n.length>0?n.join(`,`):void 0}}var ae=new Map;async function oe(e,t){let n=e||`<default>`,r=ae.get(n);if(r)return r;let i=t().catch(e=>{throw ae.delete(n),e});return ae.set(n,i),i}function se(e){let t=e?.capabilities;if(!t||typeof t!=`object`)return;let n=t.transactionalBatch;if(typeof n==`boolean`)return n;if(n&&typeof n==`object`&&typeof n.enabled==`boolean`)return n.enabled}function j(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.httpStatus===404||t.status===404||t.statusCode===404||i({code:typeof t.code==`string`?t.code:``},[`OBJECT_NOT_FOUND`,`RECORD_NOT_FOUND`])}var ce=class extends Error{code=`ANALYTICS_NOT_INSTALLED`;surface;constructor(e,t){super(`Analytics capability is not installed on this deployment — ${e} is unavailable. Install @objectstack/service-analytics and mount AnalyticsServicePlugin to enable it.`+(t?` (server said: ${t})`:``)),this.name=`AnalyticsNotInstalledError`,this.surface=e}},le=class extends Error{code=`ANALYTICS_QUERY_REJECTED`;serverCode;constructor(e,t){super(`Analytics rejected the query: ${e??`the request body does not match the AnalyticsQuery contract`}`),this.name=`AnalyticsQueryRejectedError`,this.serverCode=t}};function ue(e){let t=e??{},n=typeof t.code==`string`?t.code:void 0,r=typeof t.message==`string`?t.message:void 0,i=typeof t.httpStatus==`number`?t.httpStatus:typeof t.status==`number`?t.status:typeof t.statusCode==`number`?t.statusCode:void 0;return n===`VALIDATION_FAILED`||i===400?{kind:`rejected`,code:n,message:r}:i===404||i===501||n===`NOT_IMPLEMENTED`||n===`ROUTE_NOT_FOUND`?{kind:`not-installed`,code:n,message:r}:{kind:`unknown`,code:n,message:r}}var de=class extends Error{code=`CONCURRENT_UPDATE`;httpStatus=409;currentVersion;currentRecord;constructor(e){super(e.message??`Record was modified by another user`),this.name=`ConcurrentUpdateError`,this.currentVersion=e.currentVersion,this.currentRecord=e.currentRecord}};function M(e){if(!e||typeof e!=`object`)return e;let t=e,n=t.details??{};if(t.code===`VALIDATION_FAILED`||t.name===`ValidationError`){let e=Array.isArray(n.fields)?n.fields:Array.isArray(t.fields)?t.fields:[],r=e.map(e=>{let t=e??{},n=typeof t.field==`string`?t.field:void 0;return n?{field:n,message:typeof t.message==`string`&&t.message.trim()?t.message:typeof t.code==`string`?t.code:``}:null}).filter(e=>e!==null);return new b(typeof t.message==`string`?t.message:`Validation failed`,r[0]?.field,r,{fields:e})}return t.code!==`CONCURRENT_UPDATE`&&t.httpStatus!==409||t.code!==`CONCURRENT_UPDATE`?e:new de({currentVersion:typeof n.currentVersion==`string`?n.currentVersion:null,currentRecord:n.currentRecord??null,message:typeof t.message==`string`?t.message:void 0})}function fe(){let e=e=>{if(!e||typeof e!=`object`)return!1;if(e.status===404||e.statusCode===404)return!0;let t=e.error;if(t&&typeof t==`object`){let e=t.code;if(i({code:e},[`OBJECT_NOT_FOUND`,`RECORD_NOT_FOUND`]))return!0}return!1},t={debug:(e,t)=>console.debug(e,t??``),info:(e,t)=>console.info(e,t??``),warn:(e,t)=>console.warn(e,t??``),error:(t,n,r)=>{if(e(r)){console.debug(`[ObjectStack] ${t} (suppressed expected 404)`,r);return}console.error(t,n??``,r??``)},fatal:(e,t,n)=>console.error(e,t??``,n??``),log:(e,...t)=>console.log(e,...t),child:()=>t,withTrace:()=>t};return t}function N(e){if(typeof e!=`object`||!e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(N).join(`,`)}]`;let t=e;return`{${Object.keys(t).sort().map(e=>`${JSON.stringify(e)}:${N(t[e])}`).join(`,`)}}`}var pe=class{client;connected=!1;connectPromise=null;metadataCache;connectionState=`disconnected`;connectionStateListeners=[];batchProgressListeners=[];autoReconnect;maxReconnectAttempts;reconnectDelay;reconnectAttempts=0;baseUrl;token;analyticsCapabilityWarned=!1;fetchImpl;inflightFinds=new Map;missingResources=new Set;batchUnsupported=!1;atomicBatchCapability;mutationListeners=new Set;writeWarningListeners=new Set;constructor(e){this.client=new c.ObjectStackClient({...e,logger:fe()}),this.metadataCache=new l(e.cache),this.autoReconnect=e.autoReconnect??!0,this.maxReconnectAttempts=e.maxReconnectAttempts??3,this.reconnectDelay=e.reconnectDelay??1e3,this.baseUrl=e.baseUrl,this.token=e.token,this.fetchImpl=e.fetch||globalThis.fetch.bind(globalThis)}async connect(){if(!this.connected)return this.connectPromise?this.connectPromise:(this.setConnectionState(`connecting`),this.connectPromise=(async()=>{try{let e=this.baseUrl||``,t=e?`${e.replace(/\/$/,``)}/api/v1/discovery`:`/api/v1/discovery`,n=await oe(e,async()=>{let e=await this.fetchImpl(t,{method:`GET`,headers:this.token?{Authorization:`Bearer ${this.token}`}:void 0});if(!e.ok)throw Error(`discovery ${e.status} ${e.statusText}`);let n=await e.json();return n&&typeof n.success==`boolean`&&`data`in n?n.data:n});this.client.discoveryInfo=n,this.atomicBatchCapability=se(n),this.connected=!0,this.reconnectAttempts=0,this.setConnectionState(`connected`)}catch(e){let t=new v(e instanceof Error?e.message:`Failed to connect to ObjectStack server`,void 0,{originalError:e});if(this.setConnectionState(`error`,t),this.autoReconnect&&this.reconnectAttempts<this.maxReconnectAttempts)await this.attemptReconnect();else throw t}finally{this.connectPromise=null}})(),this.connectPromise)}async attemptReconnect(){this.reconnectAttempts++,this.setConnectionState(`reconnecting`);let e=this.reconnectDelay*2**(this.reconnectAttempts-1);await new Promise(t=>setTimeout(t,e)),this.connected=!1,await this.connect()}getConnectionState(){return this.connectionState}isConnected(){return this.connected&&this.connectionState===`connected`}onConnectionStateChange(e){return this.connectionStateListeners.push(e),()=>{let t=this.connectionStateListeners.indexOf(e);t>-1&&this.connectionStateListeners.splice(t,1)}}onBatchProgress(e){return this.batchProgressListeners.push(e),()=>{let t=this.batchProgressListeners.indexOf(e);t>-1&&this.batchProgressListeners.splice(t,1)}}setConnectionState(e,t){this.connectionState=e;let n={state:e,timestamp:Date.now(),error:t};this.connectionStateListeners.forEach(e=>{try{e(n)}catch(e){console.error(`Error in connection state listener:`,e)}})}emitBatchProgress(e){this.batchProgressListeners.forEach(t=>{try{t(e)}catch(e){console.error(`Error in batch progress listener:`,e)}})}async find(e,t){if(this.missingResources.has(e))return{data:[],total:0};let n=`${e}::${N(t)}`,r=this.inflightFinds.get(n);if(r)return r;let i=(async()=>{if(await this.connect(),t?.$expand&&t.$expand.length>0||t?.$search!=null&&String(t.$search).trim()!==``){let n=await this.rawFindWithPopulate(e,t);return this.normalizeQueryResult(n,t)}let n=this.convertQueryParams(t);try{let r=await this.client.data.find(e,n);return this.normalizeQueryResult(r,t)}catch(t){if(j(t))return this.missingResources.add(e),{data:[],total:0};throw t}})();this.inflightFinds.set(n,i);let a=()=>{this.inflightFinds.get(n)===i&&this.inflightFinds.delete(n)};return i.then(a,a),i}async searchAll(e,t){let n=(e??``).trim();if(n===``)return{query:``,hits:[]};await this.connect();let r=new URLSearchParams;r.set(`q`,n),t?.limit!=null&&t.limit>0&&r.set(`limit`,String(t.limit)),t?.objects&&t.objects.length>0&&r.set(`objects`,t.objects.join(`,`));let i=(this.baseUrl||``).replace(/\/$/,``),a=`${i}${/\/api\/v\d+$/i.test(i)?`/search`:`/api/v1/search`}?${r.toString()}`,o={"Content-Type":`application/json`};this.token&&(o.Authorization=`Bearer ${this.token}`);let s=await this.fetchImpl(a,{method:`GET`,headers:o});if(!s.ok){if(s.status===404)return{query:n,hits:[]};let e=await s.json().catch(()=>({message:s.statusText})),t=Error(e?.error?.message||e?.message||s.statusText);throw t.status=s.status,t}let c=await s.json(),l=c&&typeof c==`object`&&typeof c.success==`boolean`&&`data`in c?c.data:c,u=Array.isArray(l?.hits)?l.hits:Array.isArray(l)?l:[],d=[];for(let e of u){if(!e||typeof e!=`object`)continue;let t=e,n=t.object??t.objectName??t.object_name,r=t.id??t.record?.id??t.record?._id;typeof n!=`string`||r==null||d.push({object:n,id:String(r),title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:void 0,record:t.record&&typeof t.record==`object`?t.record:void 0})}return{query:typeof l?.query==`string`?l.query:n,hits:d}}async findOne(e,t,n){if(await this.connect(),n?.$expand&&n.$expand.length>0)try{let r={...n,$filter:{id:String(t)},$top:1},i=await this.rawFindWithPopulate(e,r);if(Array.isArray(i))return i[0]||null;let a=i;return(a.records||a.value||[])[0]||null}catch(e){if(j(e))return null}try{return(await this.client.data.get(e,String(t))).record}catch(e){if(j(e))return null;throw e}}emitMutation(e){for(let t of this.mutationListeners)try{t(e)}catch(e){console.warn(`ObjectStackAdapter: mutation listener error`,e)}}onMutation(e){return this.mutationListeners.add(e),()=>{this.mutationListeners.delete(e)}}emitWriteWarning(e){for(let t of this.writeWarningListeners)try{t(e)}catch(e){console.warn(`ObjectStackAdapter: write-warning listener error`,e)}}notifyDroppedFields(e,t,n,r){let i=n?.droppedFields;if(!Array.isArray(i)||i.length===0)return;let a=i.filter(e=>!!e&&typeof e==`object`&&Array.isArray(e.fields)&&e.fields.length>0);a.length!==0&&this.emitWriteWarning({operation:e,resource:t,...r===void 0?{}:{id:r},droppedFields:a})}notifyBatchDroppedFields(e,t){let n=t?.droppedFields;if(!(!Array.isArray(n)||n.length===0))for(let t of n){if(!t||typeof t!=`object`)continue;let n=t;if(!Array.isArray(n.fields)||n.fields.length===0)continue;let r=typeof n.index==`number`?e[n.index]:void 0,i=(r?.action??`create`)===`create`?`create`:`update`;this.emitWriteWarning({operation:i,resource:n.object??r?.object??``,...r?.id!==void 0&&r?.id!==null?{id:r.id}:{},droppedFields:[{object:n.object,fields:n.fields,reason:n.reason}]})}}onWriteWarning(e){return this.writeWarningListeners.add(e),()=>{this.writeWarningListeners.delete(e)}}async create(e,t){await this.connect();try{let n=await this.client.data.create(e,t);return this.emitMutation({type:`create`,resource:e,record:{...n.record}}),this.notifyDroppedFields(`create`,e,n,n.record?.id),n.record}catch(e){throw M(e)}}async update(e,t,n,r){await this.connect();try{let i=await this.client.data.update(e,String(t),n,r?.ifMatch?{ifMatch:r.ifMatch}:void 0);return this.emitMutation({type:`update`,resource:e,id:t,record:{...i.record}}),this.notifyDroppedFields(`update`,e,i,t),i.record}catch(e){throw M(e)}}async delete(e,t,n){await this.connect();try{let r=await this.client.data.delete(e,String(t),n?.ifMatch?{ifMatch:n.ifMatch}:void 0);return r.deleted&&this.emitMutation({type:`delete`,resource:e,id:t}),r.deleted}catch(e){throw M(e)}}async bulkUpdate(e,t,n){if(await this.connect(),!t||t.length===0)return 0;let r=t.map(e=>({id:String(e),data:n})),i=t=>(t>0&&this.emitMutation({type:`update`,resource:e}),t),a=this.client.data.updateMany;if(typeof a==`function`)try{let n=await a(e,r,{continueOnError:!0});return n&&typeof n==`object`&&typeof n.succeeded==`number`?i(n.succeeded):i(Array.isArray(n)?n.length:t.length)}catch(e){throw M(e)}let o=0;for(let r of t)try{await this.client.data.update(e,String(r),n),o++}catch{}return i(o)}async bulkDelete(e,t){if(await this.connect(),!t||t.length===0)return 0;let n=t.map(e=>String(e)),r=t=>(t>0&&this.emitMutation({type:`delete`,resource:e}),t),i=this.client.data.deleteMany;if(typeof i==`function`)try{let t=await i(e,n,{continueOnError:!0});return t&&typeof t==`object`&&typeof t.succeeded==`number`?r(t.succeeded):r(Array.isArray(t)?t.length:n.length)}catch(e){throw M(e)}let a=0;for(let t of n)try{await this.client.data.delete(e,t),a++}catch{}return r(a)}async batchTransaction(e){await this.connect();let t=this.atomicBatchCapability===!0;if(!t&&this.batchUnsupported)return n(this,e);try{let t=await this.client.data.batchTransaction(e);return this.emitBatchMutations(e,t?.results),this.notifyBatchDroppedFields(e,t),t}catch(n){let r=this.errorStatusOf(n);if(!t&&this.batchStatusUnsupported(r))return this.fallbackToEmulation(e,r);throw n}}batchStatusUnsupported(e){return e===404||e===405||e===501}errorStatusOf(e){if(!e||typeof e!=`object`)return;let t=e,n=t.httpStatus??t.status??t.statusCode;return typeof n==`number`?n:void 0}fallbackToEmulation(e,t){return this.batchUnsupported||(this.batchUnsupported=!0,console.warn(`ObjectStackAdapter: POST /api/v1/batch unavailable (HTTP ${t??`?`}) — falling back to non-atomic client-side batch emulation. Cross-object saves on this backend are best-effort, not transactional.`)),n(this,e)}emitBatchMutations(e,t){let n=Array.isArray(t)?t:[];e.forEach((e,t)=>{let r=e.action??`create`,i=n[t];r===`create`?this.emitMutation({type:`create`,resource:e.object,record:i}):r===`update`?this.emitMutation({type:`update`,resource:e.object,id:e.id??i?.id??i?._id,record:i}):r===`delete`&&this.emitMutation({type:`delete`,resource:e.object,id:e.id})})}async bulk(e,t,n){if(await this.connect(),!n||n.length===0)return[];let r=n.length,i=0,a=0,o=()=>{this.emitBatchProgress({operation:t,total:r,completed:i,failed:a,percentage:r>0?(i+a)/r*100:0})};try{switch(t){case`create`:{o();let t=await this.client.data.createMany(e,n);return i=t.length,a=r-i,o(),i>0&&this.emitMutation({type:`create`,resource:e}),t}case`delete`:{let t=n.map(e=>e.id).filter(Boolean);if(t.length===0){let e=n.map((e,t)=>({index:t,error:`Missing ID for item at index ${t}`}));throw a=n.length,o(),new _(`delete`,0,n.length,e)}return o(),await this.client.data.deleteMany(e,t),i=t.length,a=r-i,o(),i>0&&this.emitMutation({type:`delete`,resource:e}),[]}case`update`:{if(typeof this.client.data.updateMany==`function`)try{o();let t=this.client.data.updateMany,s=await t(e,n);return i=s.length,a=r-i,o(),i>0&&this.emitMutation({type:`update`,resource:e}),s}catch{}let t=[],s=[];for(let r=0;r<n.length;r++){let c=n[r],l=c.id;if(!l){s.push({index:r,error:`Missing ID`}),a++,o();continue}try{let n=await this.client.data.update(e,String(l),c);t.push(n.record),i++,o()}catch(e){let t=e instanceof Error?e.message:String(e);s.push({index:r,error:t}),a++,o()}}if(i>0&&this.emitMutation({type:`update`,resource:e}),s.length>0)throw new _(`update`,t.length,s.length,s,{resource:e,totalRecords:n.length});return t}default:throw new h(`Unsupported bulk operation: ${t}`,`UNSUPPORTED_OPERATION`,400)}}catch(r){if(o(),r instanceof _||r instanceof h)throw r;let i=r instanceof Error?r.message:String(r),a=n.map((e,t)=>({index:t,error:i}));throw new _(t,0,n.length,a,{resource:e,originalError:r})}}async importRecords(e,t){await this.connect();let n=this.client.data.import;if(typeof n!=`function`)throw new h(`The connected @objectstack/client does not support data.import(). Upgrade the client, or import via a per-row create fallback.`,`UNSUPPORTED_OPERATION`,400);try{return await n.call(this.client.data,e,t)}catch(e){throw M(e)}}importJobApi(){let e=this.client.data;if(typeof e.createImportJob==`function`)return e}async createImportJob(e,t){await this.connect();let n=this.importJobApi();if(!n)throw new h(`The connected @objectstack/client does not support async import jobs (data.createImportJob). Upgrade the client, or use the synchronous importRecords() path.`,`UNSUPPORTED_OPERATION`,400);try{return await n.createImportJob.call(this.client.data,e,t)}catch(e){throw M(e)}}async getImportJobProgress(e){await this.connect();let t=this.importJobApi();if(!t)throw new h(`The connected @objectstack/client does not support async import jobs.`,`UNSUPPORTED_OPERATION`,400);try{return await t.getImportJobProgress.call(this.client.data,e)}catch(e){throw M(e)}}async getImportJobResults(e){await this.connect();let t=this.importJobApi();if(!t)throw new h(`The connected @objectstack/client does not support async import jobs.`,`UNSUPPORTED_OPERATION`,400);try{return await t.getImportJobResults.call(this.client.data,e)}catch(e){throw M(e)}}async listImportJobs(e={}){await this.connect();let t=this.importJobApi();if(!t)throw new h(`The connected @objectstack/client does not support async import jobs.`,`UNSUPPORTED_OPERATION`,400);try{return await t.listImportJobs.call(this.client.data,e)}catch(e){throw M(e)}}async cancelImportJob(e){await this.connect();let t=this.importJobApi();if(!t)throw new h(`The connected @objectstack/client does not support async import jobs.`,`UNSUPPORTED_OPERATION`,400);try{await t.cancelImportJob.call(this.client.data,e)}catch(e){throw M(e)}}async undoImportJob(e){await this.connect();let t=this.importJobApi();if(!t||typeof t.undoImportJob!=`function`)throw new h(`The connected @objectstack/client does not support undoing import jobs (data.undoImportJob).`,`UNSUPPORTED_OPERATION`,400);try{return await t.undoImportJob.call(this.client.data,e)}catch(e){throw M(e)}}normalizeQueryResult(e,t){if(Array.isArray(e))return{data:e,total:e.length,page:1,pageSize:e.length,hasMore:!1};let n=e,r=n.records||n.value||[],i=n.total??n.count??r.length,a=typeof n.hasMore==`boolean`?n.hasMore:t?.$top?r.length===t.$top:!1;return{data:r,total:i,page:t?.$skip&&t.$top?Math.floor(t.$skip/t.$top)+1:1,pageSize:t?.$top,hasMore:a}}async rawFindWithPopulate(e,t){let n=new URLSearchParams;if(t.$expand&&t.$expand.length>0&&n.set(`populate`,t.$expand.join(`,`)),t.$top!==void 0&&n.set(`top`,String(t.$top)),t.$skip!==void 0&&n.set(`skip`,String(t.$skip)),t.$search!=null&&String(t.$search).trim()!==``&&n.set(`search`,String(t.$search).trim()),t.$searchFields&&t.$searchFields.length>0&&n.set(`searchFields`,t.$searchFields.join(`,`)),t.$select&&t.$select.length>0){let e=t.$select.includes(`id`)?t.$select:[`id`,...t.$select];n.set(`select`,e.join(`,`))}let r=A(t.$orderby);if(r&&n.set(`sort`,r),t.$filter!==void 0&&t.$filter!==null){let e=k(t.$filter);e!==void 0&&n.set(`filter`,JSON.stringify(e))}let i=this.baseUrl.replace(/\/$/,``),a=n.toString(),o=`${i}${/\/api\/v\d+$/i.test(i)?`/data`:`/api/v1/data`}/${e}${a?`?${a}`:``}`,s={"Content-Type":`application/json`};this.token&&(s.Authorization=`Bearer ${this.token}`);let c=await this.fetchImpl(o,{method:`GET`,headers:s});if(!c.ok){let e=await c.json().catch(()=>({message:c.statusText})),t=Error(e?.error?.message||e?.message||c.statusText);throw t.status=c.status,t}let l=await c.json();return l&&typeof l.success==`boolean`&&`data`in l?l.data:l}async exportDownload(e,t={}){let n=new URLSearchParams,r=t.format===`xlsx`?`xlsx`:t.format===`json`?`json`:`csv`;if(n.set(`format`,r),t.fields&&t.fields.length>0&&n.set(`fields`,t.fields.join(`,`)),t.limit&&t.limit>0&&n.set(`limit`,String(t.limit)),t.includeHeaders===!1&&n.set(`header`,`false`),t.sort&&t.sort.length>0){let e=t.sort.filter(e=>e&&e.field).map(e=>`${e.field}:${e.direction===`desc`?`desc`:`asc`}`).join(`,`);e&&n.set(`orderby`,e)}if(t.filter!==void 0&&t.filter!==null){let e=k(t.filter);e!==void 0&&n.set(`filter`,JSON.stringify(e))}let i=typeof t.search==`string`?t.search.trim():``;i&&(n.set(`search`,i),t.searchFields&&t.searchFields.length>0&&n.set(`searchFields`,t.searchFields.join(`,`)));let a=this.baseUrl.replace(/\/$/,``),o=`${a}${/\/api\/v\d+$/i.test(a)?`/data`:`/api/v1/data`}/${encodeURIComponent(e)}/export?${n.toString()}`,s={...this.getAuthHeaders()},c=await this.fetchImpl(o,{method:`GET`,headers:s,credentials:`include`});if(!c.ok){let e=await c.json().catch(()=>({message:c.statusText})),t=Error(e?.error?.message||e?.message||c.statusText);throw t.status=c.status,t}return await c.blob()}convertQueryParams(e){if(!e)return{};let n={};e.$select&&(n.select=e.$select.includes(`id`)?e.$select:[`id`,...e.$select]),e.$filter!==void 0&&e.$filter!==null&&((Array.isArray(e.$filter)?e.$filter.length===0:typeof e.$filter==`object`&&Object.keys(e.$filter).length===0)||(Array.isArray(e.$filter)?n.filters=D(e.$filter):n.filters=t(e.$filter)));let r=A(e.$orderby);return r&&(n.sort=r),e.$skip!==void 0&&(n.skip=e.$skip),e.$top!==void 0&&(n.top=e.$top),e.$search!=null&&String(e.$search).trim()!==``&&(n.search=String(e.$search).trim()),e.$searchFields&&e.$searchFields.length>0&&(n.searchFields=e.$searchFields),n}async getObjectSchema(e){await this.connect();try{let t=await this.metadataCache.get(e,()=>this.fetchObjectSchemaFresh(e));return r(t),this.applyFieldWidgetOverrides(e,t),t}catch(t){let n=t;throw j(n)?new g(e,{originalError:t}):t instanceof h?t:x(n,`getObjectSchema(${e})`)}}applyFieldWidgetOverrides(e,t){let n={sys_permission_set:{object_permissions:`permission-facet-link`,field_permissions:`permission-facet-link`,system_permissions:`permission-facet-link`,row_level_security:`permission-facet-link`,tab_permissions:`permission-facet-link`,admin_scope:`permission-facet-link`}}[e],r=t&&typeof t==`object`?t.fields:null;if(!(!n||!r))for(let[e,t]of Object.entries(n))if(Array.isArray(r)){let n=r.find(t=>t?.name===e);n&&!n.widget&&(n.widget=t)}else{let n=r[e];n&&!n.widget&&(n.widget=t)}}async fetchObjectSchemaFresh(e){let t=(this.baseUrl||``).replace(/\/$/,``),n=`${t}${/\/api\/v\d+$/i.test(t)?`/meta`:`/api/v1/meta`}/object/${encodeURIComponent(e)}`,r={"Content-Type":`application/json`};this.token&&(r.Authorization=`Bearer ${this.token}`);let i=await this.fetchImpl(n,{method:`GET`,headers:r,cache:`no-cache`});if(!i.ok){let e=await i.json().catch(()=>({message:i.statusText})),t=Error(e?.error?.message||e?.message||i.statusText);throw t.status=i.status,t}let a=await i.json(),o=a&&typeof a==`object`&&`success`in a&&`data`in a?a.data:a;return o&&typeof o==`object`&&`item`in o?o.item:o}async getObjects(){try{await this.connect();let e=(this.baseUrl||``).replace(/\/$/,``),t=`${e}${/\/api\/v\d+$/i.test(e)?`/meta`:`/api/v1/meta`}/object`,n={"Content-Type":`application/json`};this.token&&(n.Authorization=`Bearer ${this.token}`);let r=await this.fetchImpl(t,{method:`GET`,headers:n});if(!r.ok)return[];let i=await r.json(),a=i&&typeof i==`object`&&`success`in i&&`data`in i?i.data:i;return(Array.isArray(a)?a:Array.isArray(a?.items)?a.items:[]).map(e=>({name:String(e?.name??``),label:e?.label==null?void 0:String(e.label)})).filter(e=>e.name)}catch{return[]}}getClient(){return this.client}async getDiscovery(){try{return await this.connect(),this.client.discoveryInfo||null}catch{return null}}async listViewOverrides(e){await this.connect();try{let t=`view-overrides:${e}`;return await this.metadataCache.get(t,async()=>{let t=await this.client.meta.getItems(e),n=Array.isArray(t?.items)?t.items:[],r={};for(let e of n){if(!e||typeof e!=`object`)continue;let t=e.name??e.id??e._name;typeof t==`string`&&t&&(r[t]=e)}return r})}catch{return{}}}async getView(e,t){await this.connect();try{let n=`view:${e}:${t}`;return await this.metadataCache.get(n,async()=>{let e=await this.client.meta.getItem(`view`,t);return e&&e.item?e.item:e??null})}catch{return null}}async updateViewConfig(e,t,n){await this.connect();let r={...n||{},object:n?.object||e,name:t},i=await this.client.meta.saveItem(`view`,t,r),a=`view:${e}:${t}`;return this.metadataCache.invalidate?.(a),this.metadataCache.invalidate?.(`view-overrides:${e}`),this.metadataCache.invalidate?.(`views:${e}`),i&&i.item?i.item:i??void 0}async listViews(e,t){await this.connect();try{let n;if(t?.previewDrafts){let e=await this.metadataClient().withPreviewDrafts(!0).list(`view`);n=Array.isArray(e)?e:[]}else{let e=await this.client.meta.getItems(`view`);n=Array.isArray(e?.items)?e.items:Array.isArray(e)?e:[]}let r=new Set([`form`,`detail`]);return n.filter(t=>{if(!t)return!1;let n=t.list??t;if((n?.data?.object??n?.object??n?.objectName)!==e)return!1;let i=t.viewKind??n?.viewKind;return!(i&&r.has(i))}).map(e=>{let t=e.list??e,n=e._draft===!0||t?._draft===!0;return t&&t.config&&typeof t.config==`object`?{...t.config,name:t.name??t.config.name,label:t.label??t.config.label,isDefault:!!t.isDefault,...n?{_draft:!0}:{}}:n?{...t,_draft:!0}:t})}catch(e){return console.warn(`[OBJECTSTACKDataSource] listViews failed:`,e),[]}}metadataClient(){return new m({baseUrl:this.baseUrl,fetch:this.fetchImpl,...this.token?{headers:{Authorization:`Bearer ${this.token}`}}:{}})}async listImportMappings(e){await this.connect();try{let t=await this.client.meta.getItems(`mapping`);return(Array.isArray(t?.items)?t.items:Array.isArray(t)?t:[]).filter(t=>t&&t.targetObject===e)}catch(e){return console.warn(`[OBJECTSTACKDataSource] listImportMappings failed:`,e),[]}}async createView(e,t){await this.connect();let n=String(t?.name||``).trim();if(!n){let r=String(t?.label||e||`view`).toLowerCase().replace(/[^a-z0-9_]+/g,`_`).replace(/^_+|_+$/g,``).slice(0,40);(!r||/^[0-9]/.test(r))&&(r=r?`view_${r}`:`view`);let i=Date.now().toString(36);n=`${r}_${i}`}let r={...t,name:n,object:t?.object||e,data:t?.data||{provider:`object`,object:e}},i=await this.client.meta.saveItem(`view`,n,r);return this.metadataCache.invalidate?.(`views:${e}`),i&&i.item?i.item:r}async updateView(e,t,n){await this.connect();let r={};try{let e=await this.client.meta.getItem(`view`,t);r=e&&(e.item||e)||{},r?.list&&(r=r.list)}catch{}let i={...r,...n,name:t,object:r?.object||r?.data?.object||e},a=await this.client.meta.saveItem(`view`,t,i);return this.metadataCache.invalidate?.(`views:${e}`),this.metadataCache.invalidate?.(`view:${e}:${t}`),a&&a.item?a.item:i}async deleteView(e,t){await this.connect();let n=await this.client.meta.deleteItem(`view`,t);return this.metadataCache.invalidate?.(`views:${e}`),this.metadataCache.invalidate?.(`view:${e}:${t}`),{deleted:!!(n?.deleted??n?.reset??!0)}}async getApp(e){await this.connect();try{let t=`app:${e}`;return await this.metadataCache.get(t,async()=>{let t=await this.client.meta.getItem(`apps`,e);return t&&t.item?t.item:t??null})}catch{return null}}async getPage(e){await this.connect();try{let t=`page:${e}`;return await this.metadataCache.get(t,async()=>{let t=await this.client.meta.getItem(`pages`,e);return t&&t.item?t.item:t??null})}catch{return null}}async updateDashboard(e,t){await this.connect();let n=await this.client.meta.saveItem(`dashboard`,e,t);return this.metadataCache.invalidate?.(`dashboards`),this.metadataCache.invalidate?.(`dashboard:${e}`),n&&n.item?n.item:n??void 0}async aggregate(e,t){if(await this.connect(),t!=null&&(Array.isArray(t.groupBy)||Array.isArray(t.aggregations)||t.where!==void 0)){let n={};Array.isArray(t.groupBy)&&(n.groupBy=t.groupBy),Array.isArray(t.aggregations)&&(n.aggregations=t.aggregations),t.where!==void 0&&(n.where=t.where),typeof t.limit==`number`&&(n.limit=t.limit);let r=await this.client.data.query(e,n);return Array.isArray(r)?r:Array.isArray(r?.records)?r.records:Array.isArray(r?.data)?r.data:[]}try{let n=t.function===`count`?`count`:`${t.field}_${t.function}`,r=this.aggregateValueKey(t),i={cube:e,measures:[n],dimensions:t.groupBy&&t.groupBy!==`_all`?[t.groupBy]:[]};t.filter&&(i.where=t.filter);let a=await this.client.analytics.query(i),o=Array.isArray(a)?a:a?.rows&&Array.isArray(a.rows)?a.rows:a?.data&&Array.isArray(a.data)?a.data:a?.data?.rows&&Array.isArray(a.data.rows)?a.data.rows:a?.results&&Array.isArray(a.results)?a.results:[];return o.length>0&&o.every(e=>e==null||!(n in e&&e[n]!=null||r in e&&e[r]!=null))?await this.aggregateViaFind(e,t):o.map(e=>{let t={...e};return n!==r&&n in t&&(t[r]=t[n],delete t[n]),t})}catch(n){let r=ue(n);if(r.kind===`rejected`)throw new le(r.message,r.code);return r.kind===`not-installed`&&this.warnAnalyticsCapabilityOnce(r.message),await this.aggregateViaFind(e,t)}}async aggregateViaFind(e,t){let n=(await this.find(e,t.filter?{$filter:t.filter}:void 0)).data||[];return n.length===0?[]:this.aggregateClientSide(n,t)}warnAnalyticsCapabilityOnce(e){this.analyticsCapabilityWarned||(this.analyticsCapabilityWarned=!0,console.warn(`[OBJECTSTACKDataSource] analytics capability unavailable — aggregating client-side from a scoped find(). Numbers stay correct but the semantic layer (cubes, joins, server-side rollups) is off. Install @objectstack/service-analytics to enable it.`+(e?` Server said: ${e}`:``)))}async queryDataset(e,t){await this.connect();let n=`${(this.baseUrl||``).replace(/\/$/,``)}/api/v1/analytics/dataset/query`,r=typeof window<`u`&&new URLSearchParams(window.location.search).get(`preview`)===`draft`,i=typeof e==`string`?{datasetName:e,selection:t,...r?{previewDrafts:!0}:{}}:{dataset:e,selection:t,...r?{previewDrafts:!0}:{}},a=await this.fetchImpl(n,{method:`POST`,headers:{"Content-Type":`application/json`,...this.token?{Authorization:`Bearer ${this.token}`}:{}},body:JSON.stringify(i)});if(!a.ok){let e=``;try{let t=await a.json();e=t?.message||t?.error||JSON.stringify(t)}catch{}throw a.status===501||a.status===404?new ce(`POST /analytics/dataset/query`,e||void 0):Error(`Dataset query failed: ${a.status} ${a.statusText}${e?` — ${e}`:``}`)}let o=await a.json(),s=o&&typeof o==`object`&&`success`in o&&`data`in o?o.data:o;return{rows:Array.isArray(s?.rows)?s.rows:Array.isArray(s)?s:[],fields:Array.isArray(s?.fields)?s.fields:[],object:typeof s?.object==`string`?s.object:void 0,dimensionFields:s?.dimensionFields&&typeof s.dimensionFields==`object`?s.dimensionFields:void 0,drillRawRows:Array.isArray(s?.drillRawRows)?s.drillRawRows:void 0,totals:Array.isArray(s?.totals)?s.totals:void 0}}aggregateValueKey(e){return e.field||e.function||`count`}aggregateClientSide(e,t){let{field:n,function:r,groupBy:i}=t,a=this.aggregateValueKey(t),o={};for(let t of e){let e=String(t[i]??`Unknown`);o[e]||(o[e]=[]),o[e].push(t)}return Object.entries(o).map(([e,t])=>{let o=n?t.map(e=>Number(e[n])||0):[],s;switch(r){case`count`:s=t.length;break;case`avg`:s=o.length>0?o.reduce((e,t)=>e+t,0)/o.length:0;break;case`min`:s=o.length>0?Math.min(...o):0;break;case`max`:s=o.length>0?Math.max(...o):0;break;default:s=o.reduce((e,t)=>e+t,0);break}return{[i]:e,[a]:s}})}async getItems(e,t){return await this.connect(),await Promise.all(t.map(async t=>{let n=`${e}:${t}`;return this.metadataCache.get(n,async()=>{let n=await this.client.meta.getItem(e,t);return n&&n.item?n.item:n})}))}getCached(e){return this.metadataCache.getCachedSync(e)}getCacheStats(){return this.metadataCache.getStats()}invalidateCache(e){this.metadataCache.invalidate(e)}clearCache(){this.metadataCache.clear()}async uploadFile(e,t,n){await this.connect();let r=new FormData;r.append(`file`,t),n?.recordId&&r.append(`recordId`,n.recordId),n?.fieldName&&r.append(`fieldName`,n.fieldName),n?.metadata&&r.append(`metadata`,JSON.stringify(n.metadata));let i=`${this.baseUrl}/api/data/${encodeURIComponent(e)}/upload`,a=await fetch(i,{method:`POST`,body:r,headers:{...this.getAuthHeaders()}});if(!a.ok)throw new h((await a.json().catch(()=>({message:a.statusText}))).message||`Upload failed with status ${a.status}`,`UPLOAD_ERROR`,a.status);return a.json()}async uploadFiles(e,t,n){await this.connect();let r=new FormData;t.forEach((e,t)=>{r.append(`files`,e,e.name||`file-${t}`)}),n?.recordId&&r.append(`recordId`,n.recordId),n?.fieldName&&r.append(`fieldName`,n.fieldName),n?.metadata&&r.append(`metadata`,JSON.stringify(n.metadata));let i=`${this.baseUrl}/api/data/${encodeURIComponent(e)}/upload`,a=await fetch(i,{method:`POST`,body:r,headers:{...this.getAuthHeaders()}});if(!a.ok)throw new h((await a.json().catch(()=>({message:a.statusText}))).message||`Upload failed with status ${a.status}`,`UPLOAD_ERROR`,a.status);return a.json()}async cancelPendingApproval(e,t){await this.connect();let n=`${this.baseUrl}/api/v1/approvals/requests?recordId=${encodeURIComponent(t)}&object=${encodeURIComponent(e)}`,r=await this.fetchImpl(n,{method:`GET`,headers:{"Content-Type":`application/json`,...this.getAuthHeaders()}});if(!r.ok)throw new h(`Failed to look up approval requests (status ${r.status})`,`APPROVAL_LOOKUP_FAILED`,r.status);let i=await r.json().catch(()=>({})),a=(Array.isArray(i)?i:i?.data??[]).find(e=>e?.status===`pending`||e?.status===`in_approval`);if(!a?.id)throw new h(`No pending approval request found for this record`,`NO_PENDING_REQUEST`,404);let o=`${this.baseUrl}/api/v1/approvals/requests/${encodeURIComponent(a.id)}/recall`,s=await this.fetchImpl(o,{method:`POST`,headers:{"Content-Type":`application/json`,...this.getAuthHeaders()},body:JSON.stringify({})});if(!s.ok){let e=await s.json().catch(()=>({}));throw new h(e?.error||e?.message||`Recall failed with status ${s.status}`,e?.code||`APPROVAL_RECALL_FAILED`,s.status)}let c=await s.json().catch(()=>({}));return{requestId:a.id,status:c?.data?.request?.status??`recalled`}}getAuthHeaders(){let e={};return this.token&&(e.Authorization=`Bearer ${this.token}`),e}};export{ee as n,m as r,pe as t};
|