@objectstack/console 10.3.0 → 11.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{AdapterProvider-BNg96rLB.js → AdapterProvider-BTAMdG2T.js} +1 -1
- package/dist/assets/{AiPendingActionsPage-DX6zBTm5.js → AiPendingActionsPage-BtiQFQw8.js} +1 -1
- package/dist/assets/ApiConsolePage-CQJbzAsw.js +1 -0
- package/dist/assets/{AppDocsIndex-CFievvEN.js → AppDocsIndex-CbHC6KGX.js} +1 -1
- package/dist/assets/AppManagementPage-DOoQrTPO.js +1 -0
- package/dist/assets/ApprovalsInboxPage-D6eWYxCu.js +1 -0
- package/dist/assets/AuditLogPage-F85cQBBY.js +1 -0
- package/dist/assets/{ComponentNavView-BlIradDc.js → ComponentNavView-g9qw3mhW.js} +1 -1
- package/dist/assets/ConsoleFloatingChatbot-Cy-Ny_TS.js +1 -0
- package/dist/assets/DashboardView-mIWO-jW_.js +1 -0
- package/dist/assets/DashboardWidgetInspector-DOnyBhGN.js +1 -0
- package/dist/assets/{DeveloperHubPage-CQ2_nCOl.js → DeveloperHubPage-Ci0wA8GZ.js} +1 -1
- package/dist/assets/ExpressionProvider-NqLS0ljf.js +1 -0
- package/dist/assets/FlowRunsPage-CNz2_VFK.js +1 -0
- package/dist/assets/{IntegrationsPage-Ch5OmIKz.js → IntegrationsPage-CAZ3nsKJ.js} +2 -2
- package/dist/assets/{InterfaceListPage-B5-dEiYQ.js → InterfaceListPage-D1BbH0Iy.js} +1 -1
- package/dist/assets/{ManagedByBadge-DdytxDlp.js → ManagedByBadge-6DwSVsdr.js} +1 -1
- package/dist/assets/{MarketplaceAccessDenied-BRaR8_1a.js → MarketplaceAccessDenied-Cyx7lSjy.js} +1 -1
- package/dist/assets/{MarketplaceInstalledPage-BtW9YVL_.js → MarketplaceInstalledPage-C41H1YlB.js} +1 -1
- package/dist/assets/MarketplacePackagePage-Bihb2q1b.js +4 -0
- package/dist/assets/MarketplacePage-C2B6TMNM.js +1 -0
- package/dist/assets/MetadataInspector-COEBMw6y.js +1 -0
- package/dist/assets/{MetadataProvider-QdHbK1P5.js → MetadataProvider-D234gTjV.js} +1 -1
- package/dist/assets/PageView-DuiaqvzN.js +1 -0
- package/dist/assets/ProfilePage-B1oCou0F.js +1 -0
- package/dist/assets/{PublicFormsPage-Dc2X36T6.js → PublicFormsPage-C2prdsH6.js} +1 -1
- package/dist/assets/RecordDetailView-B-AuOKPI.js +9 -0
- package/dist/assets/{RecordFormPage-Hs6Ml27g.js → RecordFormPage-CpKMoOCj.js} +1 -1
- package/dist/assets/ReportDefaultInspector-DxP-Ac7I.js +11 -0
- package/dist/assets/{ReportView-BM3Ai6gG.js → ReportView-Cw9Ompki.js} +1 -1
- package/dist/assets/{SearchResultsPage-CmNe7LEF.js → SearchResultsPage-CZ038ncU.js} +1 -1
- package/dist/assets/{SettingsHub-E8tuZ4eC.js → SettingsHub-BXe-fVlJ.js} +1 -1
- package/dist/assets/{SettingsView-Zy-v0lBl.js → SettingsView-DxPgTnlF.js} +1 -1
- package/dist/assets/{SystemHubPage-BAzCcy5f.js → SystemHubPage-CJq_1ITt.js} +1 -1
- package/dist/assets/{data-adapter-dGnCpoPP.js → data-adapter-02g96tfY.js} +1 -1
- package/dist/assets/exceljs.min-HZhgX9lC.js +28 -0
- package/dist/assets/framework-h98DIM1k.js +35 -0
- package/dist/assets/{highlighted-body-OFNGDK62-DQgrzYjA.js → highlighted-body-OFNGDK62-DO9p_wSr.js} +1 -1
- package/dist/assets/index-BQhiWf8_.js +2 -0
- package/dist/assets/index-WhD62Q-7.css +2 -0
- package/dist/assets/infrastructure-B1z73d-r.js +3 -0
- package/dist/assets/{marketplaceApi-BEwXWaVr.js → marketplaceApi-B_Gmytip.js} +1 -1
- package/dist/assets/mermaid-GHXKKRXX-DEmtnxCC.js +1 -0
- package/dist/assets/metadata-admin-DStYGsRM.js +22 -0
- package/dist/assets/plugin-calendar-BYmYEyQk.js +1 -0
- package/dist/assets/plugin-charts-BDFf0TCn.js +7 -0
- package/dist/assets/plugin-chatbot-CnuZn8AC.js +120 -0
- package/dist/assets/plugin-dashboard-CuwYQhsg.js +6 -0
- package/dist/assets/plugin-form-CH8ruD9E.js +1 -0
- package/dist/assets/plugin-gantt-BB8ZeREv.js +93 -0
- package/dist/assets/plugin-grid-D414NLNP.js +6 -0
- package/dist/assets/plugin-kanban-BRFJEEAA.js +1 -0
- package/dist/assets/plugin-map-rEWoyyKa.js +1 -0
- package/dist/assets/{plugin-markdown-4BcL1bu0.js → plugin-markdown-BgV76qm3.js} +1 -1
- package/dist/assets/plugin-report-C-YPOtvZ.js +59 -0
- package/dist/assets/{plugin-timeline-C2lZtCO1.js → plugin-timeline-CC91-fmI.js} +1 -1
- package/dist/assets/plugin-tree-D2QWz1x1.js +1 -0
- package/dist/assets/plugin-view-C6iEzx93.js +1 -0
- package/dist/assets/plugins-views-CcoNygsH.js +4 -0
- package/dist/assets/recordFormNavigation-CXt3jCB4.js +1 -0
- package/dist/assets/{skeletons-B4Te484-.js → skeletons-BQ5aRDUn.js} +1 -1
- package/dist/assets/{src-Bw-Pk_Bz.js → src-C4OnKiir.js} +1 -1
- package/dist/assets/src-CKHT6scJ.js +2 -0
- package/dist/assets/types-BUZu4QOP.js +1 -0
- package/dist/assets/ui-components-C9egdVxV.js +42 -0
- package/dist/assets/ui-layout-BwokMuBv.js +1 -0
- package/dist/assets/useActionModal-ChUaxcEW.js +1 -0
- package/dist/assets/{useOpenRecordList-D2EZK86D.js → useOpenRecordList-BkSEs2q6.js} +1 -1
- package/dist/assets/{useReconcileOnError-CGxw9vPi.js → useReconcileOnError-FPUCNTHc.js} +1 -1
- package/dist/assets/utils-6HhVlFkm.js +1 -0
- package/dist/assets/vendor-objectstack-BTQLr7T3.js +96 -0
- package/dist/index.html +4 -4
- package/package.json +1 -1
- package/LICENSE.apache +0 -202
- package/dist/assets/ApiConsolePage-BV6fdN_d.js +0 -1
- package/dist/assets/AppManagementPage-BwMda0Jw.js +0 -1
- package/dist/assets/ApprovalsInboxPage-CLB_n_w1.js +0 -1
- package/dist/assets/AuditLogPage-B5jAkCIM.js +0 -1
- package/dist/assets/ConsoleFloatingChatbot-Bn99Z39a.js +0 -1
- package/dist/assets/DashboardView-BQ1jDkNk.js +0 -1
- package/dist/assets/DashboardWidgetInspector-BR98NQH8.js +0 -1
- package/dist/assets/ExpressionProvider-Tm4jr_3p.js +0 -1
- package/dist/assets/FlowRunsPage-B179CDQR.js +0 -1
- package/dist/assets/MarketplacePackagePage-CHWrggYQ.js +0 -4
- package/dist/assets/MarketplacePage-D9egwY6W.js +0 -1
- package/dist/assets/MetadataInspector-Cx8ePTT_.js +0 -1
- package/dist/assets/PageView-Cz5sZQ5t.js +0 -1
- package/dist/assets/ProfilePage-COEmwLJ3.js +0 -1
- package/dist/assets/RecordDetailView-BgaxhKDF.js +0 -9
- package/dist/assets/ReportDefaultInspector-CoX9gMMh.js +0 -7
- package/dist/assets/framework-D5XqsLzE.js +0 -35
- package/dist/assets/index-DOshzaoZ.css +0 -2
- package/dist/assets/index-DnQZFTk9.js +0 -2
- package/dist/assets/infrastructure-HR_Bc4bJ.js +0 -3
- package/dist/assets/mermaid-GHXKKRXX-BhYOzfYs.js +0 -1
- package/dist/assets/metadata-admin-B-J5LjrF.js +0 -21
- package/dist/assets/plugin-calendar-BRaVMiNC.js +0 -1
- package/dist/assets/plugin-charts-lC1nlc8y.js +0 -7
- package/dist/assets/plugin-chatbot-DiZuqXNz.js +0 -120
- package/dist/assets/plugin-dashboard-Bru0NpLD.js +0 -6
- package/dist/assets/plugin-form-CnIr9O51.js +0 -1
- package/dist/assets/plugin-gantt-DjNJ3XF1.js +0 -93
- package/dist/assets/plugin-grid-CLR5UBO-.js +0 -6
- package/dist/assets/plugin-kanban-C_oukMvw.js +0 -1
- package/dist/assets/plugin-map-7UTNE-o1.js +0 -1
- package/dist/assets/plugin-report-DnFF3lpC.js +0 -59
- package/dist/assets/plugin-tree-Ch_JGKmm.js +0 -1
- package/dist/assets/plugin-view-XyXvMY2E.js +0 -1
- package/dist/assets/plugins-views-Ck67hsjt.js +0 -4
- package/dist/assets/src-DzwWvy9u.js +0 -2
- package/dist/assets/types-aLjHZGFr.js +0 -1
- package/dist/assets/ui-components-DiLX53DV.js +0 -42
- package/dist/assets/ui-layout-s7dWTKAK.js +0 -1
- package/dist/assets/useActionModal-DjfU9Nzh.js +0 -1
- package/dist/assets/utils-29quoGQV.js +0 -1
- package/dist/assets/vendor-objectstack-C1teU2a6.js +0 -96
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import{i as e,r as t}from"./rolldown-runtime-CMxvf4Kt.js";var n=class extends Error{#e;#t;#n;#r;constructor({name:e,code:t,message:n,node:r,cause:i,range:a}){super(n,i?{cause:i}:void 0),this.name=e,this.#t=t,this.#r=n,this.#e=r,this.#n=a&&u(a)||u(r),r?.input&&(this.message=ee(this.#r,r,this.#n))}get node(){return this.#e}get code(){return this.#t}get range(){return this.#n}get summary(){return this.#r}withAst(e){return this.#e||!e?.input?this:(this.#e=e,this.#n??=u(e),this.message=ee(this.#r,e,this.#n),this)}};function r(e,t,n,r,i){if(typeof n==`string`)return{name:e,code:t,message:n,node:r,cause:i};let a=n;if(typeof a!=`object`)throw Error(`First param to error must be a string or object`);return{name:e,code:a.code||t,message:a.message,node:a.node,cause:a.cause,range:a.range}}var i=class extends n{constructor(e,t,n){super(r(`ParseError`,`parse_error`,e,t,n))}},a=class extends n{constructor(e,t,n){super(r(`EvaluationError`,`evaluation_error`,e,t,n))}},o=class extends n{constructor(e,t,n){super(r(`TypeError`,`type_error`,e,t,n))}};function s(e,t,n){return typeof e==`object`?new i(e):new i({code:e,message:t,node:n})}function c(e,t,n){return typeof e==`object`?new a(e):new a({code:e,message:t,node:n})}function l(e,t,n){return typeof e==`object`?new o(e):new o({code:e,message:t,node:n})}function u(e){let t=e?.pos??e?.start;if(typeof t==`number`)return{start:t,end:typeof e.end==`number`?e.end:t}}function ee(e,t,n){let r=t.pos??n?.start;if(typeof r!=`number`)return e;let i=t.input,a=1,o=0,s=0;for(;o<r;)i[o]===`
|
|
2
|
+
`?(a++,s=0):s++,o++;let c=r,l=r;for(;c>0&&i[c-1]!==`
|
|
3
|
+
`;)c--;for(;l<i.length&&i[l]!==`
|
|
4
|
+
`;)l++;let u=i.slice(c,l);return`${e}\n\n${`> ${`${a}`.padStart(4,` `)} | ${u}\n${` `.repeat(9+s)}^`}`}function te(e,t){return e instanceof n?e.withAst(t):e}var ne=class e{#e;constructor(e){this.#e=e}static of(t){return t===void 0?re:new e(t)}static none(){return re}hasValue(){return this.#e!==void 0}value(){if(this.#e===void 0)throw c(`optional_value_missing`,`Optional value is not present`);return this.#e}or(t){if(this.#e!==void 0)return this;if(t instanceof e)return t;throw c(`invalid_optional_argument`,`Optional.or must be called with an Optional argument`)}orValue(e){return this.#e===void 0?e:this.#e}get[Symbol.toStringTag](){return`optional`}[Symbol.for(`nodejs.util.inspect.custom`)](){return this.#e===void 0?`Optional { none }`:`Optional { value: ${JSON.stringify(this.#e)} }`}},re=Object.freeze(new ne),ie=class{},ae=new ie;function oe(e,t){let n=t?ae:void 0;e.deleteVariable(`optional`),e.registerConstant(`optional`,`OptionalNamespace`,n)}function se(e){let t={async:!1},n=(n,r)=>e.registerFunctionOverload(n,r,t),r=e.enableOptionalTypes?ae:void 0;e.registerType(`OptionalNamespace`,ie),e.registerConstant(`optional`,`OptionalNamespace`,r),n(`optional.hasValue(): bool`,e=>e.hasValue()),n(`optional<A>.value(): A`,e=>e.value()),e.registerFunctionOverload(`OptionalNamespace.none(): optional<T>`,()=>ne.none()),n(`OptionalNamespace.of(A): optional<A>`,(e,t)=>ne.of(t));function i(e,t,n){if(e instanceof ne)return e;throw c(`optional_expected`,`${n} must be optional`,t)}function a(e,t,n){let r=e.eval(t.receiver,n);return r instanceof Promise?r.then(r=>o(r,e,t,n)):o(r,e,t,n)}function o(e,t,n,r){let a=i(e,n.receiver,`${n.functionDesc} receiver`);return a.hasValue()?n.onHasValue(a):n.onEmpty(t,n,r)}function s(e,t,n,r){let i=e.check(t,n);if(i.kind===`optional`)return i;if(i.kind===`dyn`)return e.getType(`optional`);throw e.createError(`optional_expected`,`${r} must be optional, got '${i}'`,t)}function l({functionDesc:e,evaluate:t,typeCheck:n,onHasValue:r,onEmpty:i}){return({ast:a,args:o,receiver:s})=>({ast:a,functionDesc:e,receiver:s,arg:o[0],evaluate:t,typeCheck:n,onHasValue:r,onEmpty:i})}let u=`optional.or(optional) argument`;e.registerFunctionOverload(`optional.or(ast): optional<dyn>`,l({functionDesc:`optional.or(optional)`,evaluate:a,typeCheck(e,t,n){let r=s(e,t.receiver,n,`optional.or(optional) receiver`),i=s(e,t.arg,n,u);t.receiver.maybeAsync||t.arg.maybeAsync||t.ast.setMeta(`async`,!1);let a=r.unify(e.registry,i);if(a)return a;throw e.createError(`incompatible_argument_type`,`${t.functionDesc} argument must be compatible type, got '${r}' and '${i}'`,t.arg)},onHasValue:e=>e,onEmpty(e,t,n){let r=t.arg,a=e.eval(r,n);return a instanceof Promise?a.then(e=>i(e,r,u)):i(a,r,u)}})),e.registerFunctionOverload(`optional.orValue(ast): dyn`,l({functionDesc:`optional.orValue(value)`,onHasValue:e=>e.value(),onEmpty(e,t,n){return e.eval(t.arg,n)},evaluate:a,typeCheck(e,t,n){let r=s(e,t.receiver,n,`optional.orValue() receiver`).valueType,i=e.check(t.arg,n);t.receiver.maybeAsync||t.arg.maybeAsync||t.ast.setMeta(`async`,!1);let a=r.unify(e.registry,i);if(a)return a;throw e.createError(`incompatible_argument_type`,`${t.functionDesc} argument must be compatible type, got '${r}' and '${i}'`,t.arg)}}))}var ce=Object.hasOwn,le=Object.keys,ue=Object.freeze,de=Object.entries,fe=Array.isArray,pe=Array.from;function me(e,t){return e?.[Symbol.toStringTag]===`AsyncFunction`?!0:typeof t==`boolean`?t:!0}var he=new Set([`as`,`break`,`const`,`continue`,`else`,`for`,`function`,`if`,`import`,`let`,`loop`,`package`,`namespace`,`return`,`var`,`void`,`while`,`__proto__`,`prototype`]),ge=class{#e;constructor(e){this.verify(typeof e==`bigint`?e:BigInt(e))}get value(){return this.#e}valueOf(){return this.#e}toString(){return`${this.#e}`}verify(e){if(e<0n||e>18446744073709551615n)throw c(`numeric_overflow`,`Unsigned integer overflow`);this.#e=e}get[Symbol.toStringTag](){return`value = ${this.#e}`}[Symbol.for(`nodejs.util.inspect.custom`)](){return`UnsignedInteger { value: ${this.#e} }`}},_e=1e9,ve=1000000000n,ye={h:3600000000000n,m:60000000000n,s:ve,ms:1000000n,us:1000n,µs:1000n,ns:1n},be=class e{#e;#t;constructor(e,t=0){this.#e=BigInt(e),this.#t=t}get seconds(){return this.#e}get nanos(){return this.#t}valueOf(){return Number(this.#e)*1e3+this.#t/1e6}static fromMilliseconds(t){let n=BigInt(Math.trunc(t*1e6));return new e(n/ve,Number(n%ve))}addDuration(t){let n=this.#t+t.nanos;return new e(this.#e+t.seconds+BigInt(Math.floor(n/_e)),n%_e)}subtractDuration(t){let n=this.#t-t.nanos;return new e(this.#e-t.seconds+BigInt(Math.floor(n/_e)),(n+_e)%_e)}extendTimestamp(e){return new Date(e.getTime()+Number(this.#e)*1e3+Math.floor(this.#t/1e6))}subtractTimestamp(e){return new Date(e.getTime()-Number(this.#e)*1e3-Math.floor(this.#t/1e6))}toString(){let e=this.#t?(this.#t/_e).toLocaleString(`en-US`,{useGrouping:!1,maximumFractionDigits:9}).slice(1):``;return`${this.#e}${e}s`}getHours(){return this.#e/3600n}getMinutes(){return this.#e/60n}getSeconds(){return this.#e}getMilliseconds(){return this.#e*1000n+BigInt(Math.floor(this.#t/1e6))}get[Symbol.toStringTag](){return`google.protobuf.Duration`}[Symbol.for(`nodejs.util.inspect.custom`)](){return`google.protobuf.Duration { seconds: ${this.#e}, nanos: ${this.#t} }`}};function xe(e){let t={async:!1},n=(n,r)=>e.registerFunctionOverload(n,r,t),r=e=>e;n(`dyn(dyn): dyn`,r);for(let e in we){let t=we[e];t instanceof Ce&&n(`type(${t.name}): type`,()=>t)}n(`bool(bool): bool`,r),n(`bool(string): bool`,e=>{switch(e){case`1`:case`t`:case`true`:case`TRUE`:case`True`:return!0;case`0`:case`f`:case`false`:case`FALSE`:case`False`:return!1;default:throw c(`bool_conversion_error`,`bool() conversion error: invalid string value "${e}"`)}}),n(`size(string): int`,e=>BigInt(Se(e))),n(`size(bytes): int`,e=>BigInt(e.length)),n(`size(list): int`,e=>BigInt(e.length??e.size)),n(`size(map): int`,e=>BigInt(e instanceof Map?e.size:le(e).length)),n(`string.size(): int`,e=>BigInt(Se(e))),n(`bytes.size(): int`,e=>BigInt(e.length)),n(`list.size(): int`,e=>BigInt(e.length??e.size)),n(`map.size(): int`,e=>BigInt(e instanceof Map?e.size:le(e).length)),n(`bytes(string): bytes`,e=>o.fromString(e)),n(`bytes(bytes): bytes`,r),n(`double(double): double`,r),n(`double(int): double`,e=>Number(e)),n(`double(uint): double`,e=>Number(e)),n(`double(string): double`,e=>{if(!e||e!==e.trim())throw c(`double_conversion_error`,`double() type error: cannot convert to double`);switch(e.toLowerCase()){case`inf`:case`+inf`:case`infinity`:case`+infinity`:return 1/0;case`-inf`:case`-infinity`:return-1/0;case`nan`:return NaN;default:{let t=Number(e);if(!Number.isNaN(t))return t;throw c(`double_conversion_error`,`double() type error: cannot convert to double`)}}}),n(`int(int): int`,r),n(`int(double): int`,e=>{if(Number.isFinite(e))return BigInt(Math.trunc(e));throw c(`numeric_overflow`,`int() type error: integer overflow`)}),n(`int(string): int`,e=>{if(e!==e.trim()||e.length>20||e.includes(`0x`))throw c(`int_conversion_error`,`int() type error: cannot convert to int`);try{let t=BigInt(e);if(t<=9223372036854775807n&&t>=-9223372036854775808n)return t}catch{}throw c(`int_conversion_error`,`int() type error: cannot convert to int`)}),n(`uint(uint): uint`,r),n(`uint(int): uint`,e=>{try{return new ge(e)}catch{throw c(`uint_conversion_error`,`uint() type error: cannot convert to uint`)}}),n(`uint(double): uint`,e=>{try{return new ge(Math.trunc(e))}catch{throw c(`numeric_overflow`,`uint() type error: unsigned integer overflow`)}}),n(`uint(string): uint`,e=>{if(e!==e.trim()||e.length>20||e.includes(`0x`))throw c(`uint_conversion_error`,`uint() type error: cannot convert to uint`);try{return new ge(e)}catch{throw c(`uint_conversion_error`,`uint() type error: cannot convert to uint`)}}),n(`string(string): string`,r),n(`string(bool): string`,e=>`${e}`),n(`string(int): string`,e=>`${e}`),n(`string(uint): string`,e=>`${e}`),n(`string(bytes): string`,e=>o.toUtf8(e)),n(`string(double): string`,e=>e===1/0?`+Inf`:e===-1/0?`-Inf`:`${e}`),n(`string.startsWith(string): bool`,(e,t)=>e.startsWith(t)),n(`string.endsWith(string): bool`,(e,t)=>e.endsWith(t)),n(`string.contains(string): bool`,(e,t)=>e.includes(t)),n(`string.lowerAscii(): string`,e=>e.toLowerCase()),n(`string.upperAscii(): string`,e=>e.toUpperCase()),n(`string.trim(): string`,e=>e.trim()),n(`string.indexOf(string): int`,(e,t)=>BigInt(e.indexOf(t))),n(`string.indexOf(string, int): int`,(e,t,n)=>{if(t===``)return n;if(n=Number(n),n<0||n>=e.length)throw c(`index_out_of_range`,`string.indexOf(search, fromIndex): fromIndex out of range`);return BigInt(e.indexOf(t,n))}),n(`string.lastIndexOf(string): int`,(e,t)=>BigInt(e.lastIndexOf(t))),n(`string.lastIndexOf(string, int): int`,(e,t,n)=>{if(t===``)return n;if(n=Number(n),n<0||n>=e.length)throw c(`index_out_of_range`,`string.lastIndexOf(search, fromIndex): fromIndex out of range`);return BigInt(e.lastIndexOf(t,n))}),n(`string.substring(int): string`,(e,t)=>{if(t=Number(t),t<0||t>e.length)throw c(`index_out_of_range`,`string.substring(start, end): start index out of range`);return e.substring(t)}),n(`string.substring(int, int): string`,(e,t,n)=>{if(t=Number(t),t<0||t>e.length)throw c(`index_out_of_range`,`string.substring(start, end): start index out of range`);if(n=Number(n),n<t||n>e.length)throw c(`index_out_of_range`,`string.substring(start, end): end index out of range`);return e.substring(t,n)}),n(`string.matches(string): bool`,(e,t)=>{try{return new RegExp(t).test(e)}catch{throw c(`invalid_regular_expression`,`Invalid regular expression: ${t}`)}}),n(`string.split(string): list<string>`,(e,t)=>e.split(t)),n(`string.split(string, int): list<string>`,(e,t,n)=>{if(n=Number(n),n===0)return[];let r=e.split(t);if(n<0||r.length<=n)return r;let i=r.slice(0,n-1);return i.push(r.slice(n-1).join(t)),i}),n(`list<string>.join(): string`,e=>{for(let t=0;t<e.length;t++)if(typeof e[t]!=`string`)throw c(`invalid_list_element_type`,`string.join(): list must contain only strings`);return e.join(``)}),n(`list<string>.join(string): string`,(e,t)=>{for(let t=0;t<e.length;t++)if(typeof e[t]!=`string`)throw c(`invalid_list_element_type`,`string.join(separator): list must contain only strings`);return e.join(t)});let i=new TextEncoder(`utf8`),a=new TextDecoder(`utf8`),o=typeof Buffer<`u`?{byteLength:e=>Buffer.byteLength(e),fromString:e=>Buffer.from(e,`utf8`),toHex:e=>Buffer.prototype.hexSlice.call(e,0,e.length),toBase64:e=>Buffer.prototype.base64Slice.call(e,0,e.length),toUtf8:e=>Buffer.prototype.utf8Slice.call(e,0,e.length),jsonParse:e=>JSON.parse(e)}:{textEncoder:new TextEncoder(`utf8`),byteLength:e=>i.encode(e).length,fromString:e=>i.encode(e),toHex:Uint8Array.prototype.toHex?e=>e.toHex():e=>pe(e,e=>e.toString(16).padStart(2,`0`)).join(``),toBase64:Uint8Array.prototype.toBase64?e=>e.toBase64():e=>btoa(pe(e,e=>String.fromCodePoint(e)).join(``)),toUtf8:e=>a.decode(e),jsonParse:e=>JSON.parse(i.decode(e))};n(`bytes.json(): map`,o.jsonParse),n(`bytes.hex(): string`,o.toHex),n(`bytes.string(): string`,o.toUtf8),n(`bytes.base64(): string`,o.toBase64),n(`bytes.at(int): int`,(e,t)=>{if(t<0||t>=e.length)throw c(`index_out_of_range`,`Bytes index out of range`);return BigInt(e[t])});let s=`google.protobuf.Timestamp`,l=e.registerType(s,Date).typeType,u=e.registerType(`google.protobuf.Duration`,be).typeType;e.registerConstant(`google`,`map<string, map<string, type>>`,{protobuf:{Duration:u,Timestamp:l}});function ee(e,t){return new Date(e.toLocaleString(`en-US`,{timeZone:t}))}function te(e,t){let n=t?ee(e,t):new Date(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()),r=new Date(n.getFullYear(),0,0);return BigInt(Math.floor((n-r)/864e5)-1)}n(`timestamp(string): ${s}`,e=>{if(e.length<20||e.length>30)throw c(`invalid_timestamp`,`timestamp() requires a string in ISO 8601 format`);let t=new Date(e);if(t<=0xe677d21fdbff&&t>=-621355968e5)return t;throw c(`invalid_timestamp`,`timestamp() requires a string in ISO 8601 format`)}),n(`timestamp(int): ${s}`,e=>{if(e=Number(e)*1e3,e<=0xe677d21fdbff&&e>=-621355968e5)return new Date(e);throw c(`invalid_timestamp`,`timestamp() requires a valid integer unix timestamp`)}),n(`${s}.getDate(): int`,e=>BigInt(e.getUTCDate())),n(`${s}.getDate(string): int`,(e,t)=>BigInt(ee(e,t).getDate())),n(`${s}.getDayOfMonth(): int`,e=>BigInt(e.getUTCDate()-1)),n(`${s}.getDayOfMonth(string): int`,(e,t)=>BigInt(ee(e,t).getDate()-1)),n(`${s}.getDayOfWeek(): int`,e=>BigInt(e.getUTCDay())),n(`${s}.getDayOfWeek(string): int`,(e,t)=>BigInt(ee(e,t).getDay())),n(`${s}.getDayOfYear(): int`,te),n(`${s}.getDayOfYear(string): int`,te),n(`${s}.getFullYear(): int`,e=>BigInt(e.getUTCFullYear())),n(`${s}.getFullYear(string): int`,(e,t)=>BigInt(ee(e,t).getFullYear())),n(`${s}.getHours(): int`,e=>BigInt(e.getUTCHours())),n(`${s}.getHours(string): int`,(e,t)=>BigInt(ee(e,t).getHours())),n(`${s}.getMilliseconds(): int`,e=>BigInt(e.getUTCMilliseconds())),n(`${s}.getMilliseconds(string): int`,e=>BigInt(e.getUTCMilliseconds())),n(`${s}.getMinutes(): int`,e=>BigInt(e.getUTCMinutes())),n(`${s}.getMinutes(string): int`,(e,t)=>BigInt(ee(e,t).getMinutes())),n(`${s}.getMonth(): int`,e=>BigInt(e.getUTCMonth())),n(`${s}.getMonth(string): int`,(e,t)=>BigInt(ee(e,t).getMonth())),n(`${s}.getSeconds(): int`,e=>BigInt(e.getUTCSeconds())),n(`${s}.getSeconds(string): int`,(e,t)=>BigInt(ee(e,t).getSeconds()));let ne=/(\d*\.?\d*)(ns|us|µs|ms|s|m|h)/;function re(e){if(!e)throw c(`invalid_duration`,`Invalid duration string: ''`);let t=e[0]===`-`;(e[0]===`-`||e[0]===`+`)&&(e=e.slice(1));let n=BigInt(0);for(;;){let t=ne.exec(e);if(!t||t.index!==0)throw c(`invalid_duration`,`Invalid duration string: ${e}`);e=e.slice(t[0].length);let r=ye[t[2]],[i=`0`,a=``]=t[1].split(`.`),o=BigInt(i)*r,s=a?BigInt(a.slice(0,13).padEnd(13,`0`))*r/10000000000000n:0n;if(n+=o+s,e===``)break}let r=n>=ve?n/ve:0n,i=Number(n%ve);return t?new be(-r,-i):new be(r,i)}n(`duration(string): google.protobuf.Duration`,e=>re(e)),n(`google.protobuf.Duration.getHours(): int`,e=>e.getHours()),n(`google.protobuf.Duration.getMinutes(): int`,e=>e.getMinutes()),n(`google.protobuf.Duration.getSeconds(): int`,e=>e.getSeconds()),n(`google.protobuf.Duration.getMilliseconds(): int`,e=>e.getMilliseconds()),se(e)}function Se(e){let t=0;for(let n of e)t++;return t}var Ce=class{#e;constructor(e){this.#e=e,ue(this)}get name(){return this.#e}get[Symbol.toStringTag](){return`Type<${this.#e}>`}toString(){return`Type<${this.#e}>`}},we={string:new Ce(`string`),bool:new Ce(`bool`),int:new Ce(`int`),uint:new Ce(`uint`),double:new Ce(`double`),map:new Ce(`map`),list:new Ce(`list`),bytes:new Ce(`bytes`),null_type:new Ce(`null`),type:new Ce(`type`)},Te=new Ce(`optional`),Ee={dyn(e,t){switch(typeof e){case`string`:case`bigint`:case`number`:case`boolean`:return!0;case`object`:switch(e&&e.constructor){case null:case void 0:case Object:case Map:case Array:case Set:return!0;default:if(t.objectTypesByConstructor.get(e.constructor))return!0}}return!!t.debugType(e)},string(e){return typeof e==`string`},int(e){return typeof e==`bigint`},double(e){return typeof e==`number`},bool(e){return typeof e==`boolean`},null(e){return e===null},bytes(e){return e instanceof Uint8Array},uint(e){return e instanceof ge},type(e){return e instanceof Ce},list(e){switch(e?.constructor){case Array:case Set:return!0;default:return!1}},map(e){switch(typeof e==`object`&&e?e.constructor:null){case void 0:case Object:case Map:return!0;default:return!1}},optional(e){return e instanceof ne},message(e,t){return this===t.debugType(e)}};Ee.param=Ee.dyn;var De=class{#e=new WeakMap;constructor({kind:e,type:t,name:n,keyType:r,valueType:i}){this.kind=e,this.type=t,this.name=n,this.keyType=r,this.valueType=i,this.unwrappedType=e===`dyn`&&i?i.unwrappedType:this,this.wrappedType=e===`dyn`?this:Le(this.unwrappedType),this.hasDynType=this.kind===`dyn`||this.valueType?.hasDynType||this.keyType?.hasDynType||!1,this.hasPlaceholderType=this.kind===`param`||this.keyType?.hasPlaceholderType||this.valueType?.hasPlaceholderType||!1,e===`list`?this.fieldLazy=this.#a:e===`map`?this.fieldLazy=this.#r:e===`message`?this.fieldLazy=this.#n:e===`optional`&&(this.fieldLazy=this.#t),this.matchesValueType=Ee[n]||Ee[e],ue(this)}isDynOrBool(){return this.type===`bool`||this.kind===`dyn`}isEmpty(){return this.valueType&&this.valueType.kind===`param`}unify(e,t){let n=this;if(n===t||n.kind===`dyn`||t.kind===`param`)return n;if(t.kind===`dyn`||n.kind===`param`)return t;if(n.kind!==t.kind||!(n.hasPlaceholderType||t.hasPlaceholderType||n.hasDynType||t.hasDynType))return null;let r=n.valueType.unify(e,t.valueType);if(!r)return null;switch(n.kind){case`optional`:return e.getOptionalType(r);case`list`:return e.getListType(r);case`map`:let i=n.keyType.unify(e,t.keyType);return i?e.getMapType(i,r):null}}templated(e,t){if(!this.hasPlaceholderType)return this;switch(this.kind){case`dyn`:return this.valueType.templated(e,t);case`param`:return t?.get(this.name)||this;case`map`:return e.getMapType(this.keyType.templated(e,t),this.valueType.templated(e,t));case`list`:return e.getListType(this.valueType.templated(e,t));case`optional`:return e.getOptionalType(this.valueType.templated(e,t));default:return this}}toString(){return this.name}#t(e,t,n,r){if(e=e instanceof ne?e.orValue():e,e===void 0)return re;let i=r.debugType(e);try{return ne.of(i.fieldLazy(e,t,n,r))}catch(e){if(e instanceof a)return re;throw e}}#n(e,t,n,r){let i=e?r.objectTypesByConstructor.get(e.constructor):void 0;if(!i)return;let a=i.fields?i.fields[t]:Ve;if(!a)return;let o=e instanceof Map?e.get(t):e[t];if(o!==void 0){if(a.matchesValueType(o,r))return o;throw c(`field_type_mismatch`,`Field '${t}' is not of type '${a}', got '${r.debugType(o)}'`,n)}}#r(e,t,n,r){let i=e instanceof Map?e.get(t):e&&ce(e,t)?e[t]:void 0;if(i!==void 0){if(this.valueType.matchesValueType(i,r))return i;throw c(`field_type_mismatch`,`Field '${t}' is not of type '${this.valueType}', got '${r.debugType(i)}'`,n)}}#i(e,t){switch(e?.constructor){case Array:return e[t];case Set:{let n=0;for(let r of e)if(n++===t)return r}}}#a(e,t,n,r){if(typeof t==`bigint`)t=Number(t);else if(typeof t!=`number`)return;let i=this.#i(e,t);if(i===void 0){if(!e)return;throw c(`index_out_of_bounds`,`No such key: index out of bounds, index ${t} ${t<0?`< 0`:`>= size ${e.length||e.size}`}`,n)}if(this.valueType.matchesValueType(i,r))return i;throw c(`list_item_type_mismatch`,`List item with index '${t}' is not of type '${this.valueType}', got '${r.debugType(i)}'`,n)}fieldLazy(){}field(e,t,n,r){let i=this.fieldLazy(e,t,n,r);if(i!==void 0)return i;throw c(`no_such_key`,`No such key: ${t}`,n)}matchesBoth(e){return this.matches(e)&&e.matches(this)}matches(e){let t=this.unwrappedType;return e=e.unwrappedType,t===e||t.kind===`dyn`||e.kind===`dyn`||e.kind===`param`?!0:this.#e.get(e)??this.#e.set(e,this.#o(t,e)).get(e)}#o(e,t){switch(e.kind){case`dyn`:case`param`:return!0;case`list`:return t.kind===`list`&&e.valueType.matches(t.valueType);case`map`:return t.kind===`map`&&e.keyType.matches(t.keyType)&&e.valueType.matches(t.valueType);case`optional`:return t.kind===`optional`&&e.valueType.matches(t.valueType);default:return e.name===t.name}}},Oe=`have a .callAst property or .evaluate(checker, macro, ctx) method.`,ke=`have a .callAst property or .typeCheck(checker, macro, ctx) method.`;function Ae(e,t){let n=`Macro '${e}' must`;return function(e){let r=t(e);if(!r||typeof r!=`object`)throw Error(`${n} return an object.`);if(r.callAst)return r;if(!r.evaluate)throw Error(`${n} ${Oe}`);if(!r.typeCheck)throw Error(`${n} ${ke}`);return r}}var je=class{constructor(e,t,n,r){this.name=e,this.type=t,this.description=n??null,this.constant=r!==void 0,this.value=r,ue(this)}},Me=class{constructor({name:e,receiverType:t,returnType:n,handler:r,description:i,params:a,async:o}){if(typeof e!=`string`)throw Error(`name must be a string`);if(typeof r!=`function`)throw Error(`handler must be a function`);this.name=e,this.async=me(r,o),this.receiverType=t??null,this.returnType=n,this.description=i??null,this.params=a,this.argTypes=a.map(e=>e.type),this.macro=this.argTypes.includes(He);let s=t?`${t}.`:``;this.signature=`${s}${e}(${this.argTypes.join(`, `)}): ${n}`,this.handler=this.macro?Ae(this.signature,r):r,this.partitionKey=`${t?`rcall`:`call`}:${e}:${a.length}`,this.hasPlaceholderType=this.returnType.hasPlaceholderType||this.receiverType?.hasPlaceholderType||this.argTypes.some(e=>e.hasPlaceholderType)||!1,ue(this)}matchesArgs(e){return e.length===this.argTypes.length&&this.argTypes.every((t,n)=>t.matches(e[n]))?this:null}},Ne=class{constructor({op:e,leftType:t,rightType:n,handler:r,returnType:i,async:a}){this.operator=e,this.leftType=t,this.rightType=n||null,this.handler=r,this.async=me(r,a),this.returnType=i,n?this.signature=`${t} ${e} ${n}: ${i}`:this.signature=`${e}${t}: ${i}`,this.hasPlaceholderType=this.leftType.hasPlaceholderType||this.rightType?.hasPlaceholderType||!1,ue(this)}equals(e){return this.operator===e.operator&&this.leftType===e.leftType&&this.rightType===e.rightType}};function Pe(e){return new De({kind:`list`,name:`list<${e}>`,type:`list`,valueType:e})}function Fe(e){return new De({kind:`primitive`,name:e,type:e})}function Ie(e){return new De({kind:`message`,name:e,type:e})}function Le(e){let t=e?`dyn<${e}>`:`dyn`;return new De({kind:`dyn`,name:t,type:t,valueType:e})}function Re(e){return new De({kind:`optional`,name:`optional<${e}>`,type:`optional`,valueType:e})}function ze(e,t){return new De({kind:`map`,name:`map<${e}, ${t}>`,type:`map`,keyType:e,valueType:t})}function Be(e){return new De({kind:`param`,name:e,type:e})}var Ve=Le(),He=Fe(`ast`),Ue=Pe(Ve),We=ze(Ve,Ve),Ge={string:Fe(`string`),bool:Fe(`bool`),int:Fe(`int`),uint:Fe(`uint`),double:Fe(`double`),bytes:Fe(`bytes`),dyn:Ve,null:Fe(`null`),type:Fe(`type`),optional:Re(Ve),list:Ue,"list<dyn>":Ue,map:We,"map<dyn, dyn>":We};for(let e of[Ge.string,Ge.double,Ge.int]){let t=Pe(e),n=ze(Ge.string,e);Ge[t.name]=t,Ge[n.name]=n}Object.freeze(Ge);var Ke=class{returnType=null;async=!1;macro=!1;#e=null;#t=null;declarations=[];constructor(e){this.registry=e}[Symbol.iterator](){return this.declarations[Symbol.iterator]()}add(e){this.returnType=(this.returnType||e.returnType).unify(this.registry,e.returnType)||Ve,e.macro&&(this.macro=e),e.async&&!this.async&&(this.async=!0),this.declarations.push(e),this.#e?.clear(),this.#t?.clear()}findFunction(e,t=null){for(let n=0;n<this.declarations.length;n++){let r=this.#s(this.declarations[n],e,t);if(r)return r}return null}findUnaryOverload(e){let t=(this.#e??=new Map).get(e);if(t!==void 0)return t;let n=!1;for(let t of this.declarations)if(t.leftType===e){n=t;break}return this.#e.set(e,n),n}findBinaryOverload(e,t){return e.kind===`dyn`&&e.valueType?t=t.wrappedType:t.kind===`dyn`&&t.valueType&&(e=e.wrappedType),(this.#e??=new Map).get(e)?.get(t)??this.#n(this.#e,e,t,this.#r(e,t))}checkBinaryOverload(e,t){return(this.#t??=new Map).get(e)?.get(t)??this.#n(this.#t,e,t,this.#i(e,t))}#n(e,t,n,r){return(e.get(t)||e.set(t,new Map).get(t)).set(n,r),r}#r(e,t){let n=this.#a(e,t);if(n.length===0)return!1;if(n.length===1)return n[0];throw Error(`Operator overload '${n[0].signature}' overlaps with '${n[1].signature}'.`)}#i(e,t){let n=this.#a(e,t);if(n.length===0)return!1;let r=n[0].returnType;for(let e=1;e<n.length;e++)r=r.unify(this.registry,n[e].returnType)||Ve;return r}#a(e,t){let n=[];for(let r of this.declarations){if(r.leftType===e&&r.rightType===t)return[r];let i=this.#o(r,e,t);i&&n.push(i)}if(n.length===0){let t=this.declarations[0]?.operator;if((t===`==`||t===`!=`)&&e.kind===`dyn`)return $e[t]}return n}#o(e,t,n){let r=e.hasPlaceholderType?new Map:null,i=this.#l(e.leftType,t,r);if(!i)return;let a=this.#l(e.rightType,n,r);if(a)return(e.operator===`==`||e.operator===`!=`)&&e.leftType.kind===`dyn`&&e.leftType.valueType&&t.kind!==`dyn`&&n.kind!==`dyn`?!1:e.hasPlaceholderType?{async:e.async,signature:e.signature,handler:e.handler,leftType:i,rightType:a,returnType:e.returnType.templated(this.registry,r)}:e}#s(e,t,n){if(e.hasPlaceholderType)return this.#c(e,t,n);if(!(n&&e.receiverType&&!n.matches(e.receiverType)))return e.matchesArgs(t)}#c(e,t,n){let r=new Map;if(n&&e.receiverType&&!this.#l(e.receiverType,n,r))return null;for(let n=0;n<t.length;n++)if(!this.#l(e.argTypes[n],t[n],r))return null;return{async:e.async,handler:e.handler,signature:e.signature,returnType:e.returnType.templated(this.registry,r)}}#l(e,t,n){if(!e.hasPlaceholderType)return t.matches(e)?t:null;let r=t.kind===`dyn`;return this.#u(e,t,n,r)&&(r||t.matches(e.templated(this.registry,n)))?t:null}#u(e,t,n,r=!1){if(!e.hasPlaceholderType)return!0;if(!t)return!1;let i=r||t.kind===`dyn`;switch(t=t.unwrappedType,e.kind){case`param`:{let r=i?Ve:t,a=n.get(e.name);return a?a.kind===`dyn`||r.kind===`dyn`?!0:a.matchesBoth(r):n.set(e.name,r)&&!0}case`list`:return t.name===`dyn`&&(t=e),t.kind===`list`?this.#u(e.valueType,t.valueType,n,i):!1;case`map`:return t.name===`dyn`&&(t=e),t.kind===`map`?this.#u(e.keyType,t.keyType,n,i)&&this.#u(e.valueType,t.valueType,n,i):!1;case`optional`:return t.name===`dyn`&&(t=e),t.kind===`optional`?this.#u(e.valueType,t.valueType,n,i):!1}return!0}};function qe(e){let t=[],n=``,r=0;for(let i of e){if(i===`<`)r++;else if(i===`>`)r--;else if(i===`,`&&r===0){t.push(n.trim()),n=``;continue}n+=i}return n&&t.push(n.trim()),t}var Je=[[ge,`uint`,we.uint,Ge.uint],[Ce,`type`,we.type,Ge.type],[ne,`optional`,Te,Ge.optional],[Uint8Array,`bytes`,we.bytes,Ge.bytes],...typeof Buffer<`u`?[[Buffer,`bytes`,we.bytes,Ge.bytes]]:[]].map(([e,t,n,r])=>Object.freeze({name:t,typeType:n,type:r,ctor:e})),Ye=Je.map(e=>[e.name,e]),Xe=Je.map(e=>[e.ctor,e]),Ze=e=>Error(`Invalid variable declaration: ${e}`),Qe=e=>Error(`Invalid type declaration: ${e}`),$e={"==":[{handler:(e,t)=>e===t,returnType:Ge.bool}],"!=":[{handler:(e,t)=>e!==t,returnType:Ge.bool}]},et=class e{#e=null;#t;#n=!0;#r=null;#i=null;#a=null;#o=null;#s=null;#c=null;#l=null;#u=null;#d=!1;constructor(t={}){this.enableOptionalTypes=t.enableOptionalTypes??!1,this.unlistedVariablesAreDyn=t.unlistedVariablesAreDyn??!1;let n=t.parent instanceof e?t.parent:null;if(n){this.#e=n;let e=n;for(;e&&!e.#r;)e=e.#e;let t=n;for(;t&&!t.#i;)t=t.#e;this.#a=n.#a,this.#o=n.#o,this.#u={operators:e.#r,functions:t.#i},this.objectTypes=new Map(n.objectTypes),this.objectTypesByConstructor=new Map(n.objectTypesByConstructor),this.variables=n.variables,this.#n=!1,this.#t=n.#t,this.#s=n.#s,this.#c=n.#c,this.#l=n.#l,(this.enableOptionalTypes!==n.enableOptionalTypes||this.unlistedVariablesAreDyn!==n.unlistedVariablesAreDyn)&&oe(this,this.enableOptionalTypes)}else{this.#r=[],this.#i=[],this.objectTypes=new Map(Ye),this.objectTypesByConstructor=new Map(Xe),this.#t=new Map(de(Ge)),this.#s=new Map,this.#c=new Map,this.#l=new Map,this.variables=new Map,this.variables.dyn=this.unlistedVariablesAreDyn;for(let e in we)this.registerConstant(e,`type`,we[e])}}#f(){this.#n||=(this.variables=new Map(this.variables),this.variables.dyn=this.unlistedVariablesAreDyn,!0)}deleteVariable(e){this.#f(),this.variables.delete(e)}#p(e){this.#r||(this.#a=null),this.operatorCandidates(e.operator).add(e),this.#r.push(e)}#m(e){this.#i||(this.#o=null),this.#v(e.partitionKey).add(e),this.#i.push(e)}#h(e,t){return e.get(t)||e.set(t,new Ke(this)).get(t)}#g(){return this.#r?this.#r:this.#r=[...this.#u.operators]}#_(){return this.#i?this.#i:this.#i=[...this.#u.functions]}operatorCandidates(e){if(this.#a)return this.#h(this.#a,e);let t=this.#a=new Map;for(let e of this.#g())this.#h(t,e.operator).add(e);return this.#h(t,e)}functionCandidates(e,t,n){return this.#v(`${e?`rcall`:`call`}:${t}:${n}`)}#v(e){if(this.#o)return this.#h(this.#o,e);let t=this.#o=new Map;for(let e of this.#_())this.#h(t,e.partitionKey).add(e);return this.#h(t,e)}registerVariable(e,t,n){if(this.#d)throw Error(`Cannot modify frozen registry`);let r=n?.description,i;if(typeof e==`string`&&typeof t==`object`&&!(t instanceof De)?(r=t.description,i=t.value,t=t.schema?this.registerType({name:`$${e}`,schema:t.schema}).type:t.type):typeof e==`object`&&(t=e.schema?this.registerType({name:`$${e.name}`,schema:e.schema}).type:e.type,r=e.description,i=e.value,e=e.name),typeof e!=`string`||!e)throw Ze(`name must be a string`);if(he.has(e))throw Ze(`'${e}' is a reserved name`);if(this.variables.get(e)!==void 0)throw Ze(`'${e}' is already registered`);if(typeof t==`string`)t=this.getType(t);else if(!(t instanceof De))throw Ze(`type is required`);return this.#f(),this.variables.set(e,new je(e,t,r,i)),this}#y(e,t){let n=Object.create(null);for(let r of le(t)){let i=t[r];if(typeof i==`object`&&i)n[r]=this.registerType({name:`${e}.${r}`,schema:i}).type.name;else if(typeof i==`string`)n[r]=i;else throw Error(`Invalid field definition for '${e}.${r}'`)}return n}registerConstant(e,t,n){return typeof e==`object`?this.registerVariable(e):this.registerVariable({name:e,type:t,value:n}),this}getType(e){return this.#b(e,!0)}getListType(e){return this.#s.get(e)||this.#s.set(e,this.#b(`list<${e}>`,!0)).get(e)}getMapType(e,t){return this.#c.get(e)?.get(t)||(this.#c.get(e)||this.#c.set(e,new Map).get(e)).set(t,this.#b(`map<${e}, ${t}>`,!0)).get(t)}getOptionalType(e){return this.#l.get(e)||this.#l.set(e,this.#b(`optional<${e}>`,!0)).get(e)}assertType(e,t,n){try{return this.#b(e,!0)}catch(r){throw r.message=`Invalid ${t} '${r.unknownType||e}' in '${n}'`,r}}getFunctionType(e){if(e===`ast`)return He;let t=this.#b(e,!0);if(t.kind===`dyn`&&t.valueType)throw Error(`type '${t.name}' is not supported`);return t}registerType(e,t){if(this.#d)throw Error(`Cannot modify frozen registry`);if(typeof e==`object`&&(t=e,e=t.fullName||t.name||t.ctor?.name),typeof e==`string`&&e[0]===`.`&&(e=e.slice(1)),typeof e!=`string`||e.length<2||he.has(e))throw Qe(`name '${e}' is not valid`);if(this.objectTypes.has(e))throw Qe(`type '${e}' already registered`);let n=this.#b(e,!1);if(n.kind!==`message`)throw Qe(`type '${e}' is not valid`);let r={name:e,typeType:new Ce(e),type:n,ctor:typeof t==`function`?t:t?.ctor,convert:typeof t==`function`?void 0:t?.convert,fields:typeof t?.schema==`object`?this.#w(e,this.#y(e,t.schema)):this.#w(e,typeof t==`function`?void 0:t?.fields)};if(typeof r.ctor!=`function`){if(!r.fields)throw Qe(`type '${e}' requires a constructor or fields`);Object.assign(r,this.#T(e,r.fields))}return this.objectTypes.set(e,Object.freeze(r)),this.objectTypesByConstructor.set(r.ctor,r),this.registerFunctionOverload(`type(${e}): type`,()=>r.typeType,{async:!1}),r}#b(e,t=!0){let n=this.#t.get(e);if(n)return n;if(typeof e!=`string`||!e.length)throw Error(`Invalid type: must be a string`);if(n=e.match(/^[A-Z]$/),n)return this.#x(Be,e,e);if(n=e.match(/^(dyn|list|map|optional)<(.+)>$/),!n){if(t){let t=Error(`Unknown type: ${e}`);throw t.unknownType=e,t}return this.#x(Ie,e,e)}let r=n[1],i=n[2].trim();switch(r){case`dyn`:{let e=this.#b(i,t).wrappedType;return this.#t.set(e.name,e),e}case`list`:{let e=this.#b(i,t);return this.#x(Pe,`list<${e}>`,e)}case`map`:{let n=qe(i);if(n.length!==2)throw Error(`Invalid map type: ${e}`);let r=this.#b(n[0],t),a=this.#b(n[1],t);return this.#x(ze,`map<${r}, ${a}>`,r,a)}case`optional`:{let e=this.#b(i,t);return this.#x(Re,`optional<${e}>`,e)}}}#x(e,t,...n){return this.#t.get(t)||this.#t.set(t,e(...n)).get(t)}findMacro(e,t,n){return this.functionCandidates(t,e,n).macro}findUnaryOverload(e,t){return this.operatorCandidates(e).findUnaryOverload(t)}findBinaryOverload(e,t,n){return this.operatorCandidates(e).findBinaryOverload(t,n)}#S(e){return typeof e==`string`?{type:e}:e.id?at(e):e}#C(e,t,n,r=!1){try{let e=this.#S(t[n]);if(typeof e?.type!=`string`)throw Error(`unsupported declaration`);return this.#b(e.type,r)}catch(r){throw r.message=`Field '${n}' in type '${e}' has unsupported declaration: ${JSON.stringify(t[n])}`,r}}#w(e,t){if(!t)return;let n=Object.create(null);for(let r of le(t))n[r]=this.#C(e,t,r);return n}#T(e,t){let n=le(t),r=Object.create(null);for(let e of n){let n=t[e],i=n.kind===`message`&&this.objectTypes.get(n.name);i===!1?r[e]=!1:r[e]=i.convert?i:!1}let i={[e]:class extends Map{#M;constructor(e){super(),this.#M=e}[Symbol.iterator](){if(this.size!==n.length)for(let e of n)this.get(e);return super[Symbol.iterator]()}get(e){let t=super.get(e);if(t!==void 0||this.has(e))return t;let n=r[e];if(n!==void 0){if(t=this.#M instanceof Map?this.#M.get(e):this.#M?.[e],n&&t&&typeof t==`object`)switch(t.constructor){case void 0:case Object:case Map:t=n.convert(t)}return super.set(e,t),t}}}}[e];return{ctor:i,convert(e){if(e)return e.constructor===i?e:new i(e)}}}clone(t){return this.#d=!0,new e({parent:this,unlistedVariablesAreDyn:t.unlistedVariablesAreDyn,enableOptionalTypes:t.enableOptionalTypes})}getDefinitions(){let e=[],t=[];for(let[,t]of this.variables)t&&e.push({name:t.name,description:t.description||null,type:t.type.name});for(let e of this.#_())t.push({signature:e.signature,name:e.name,description:e.description,receiverType:e.receiverType?e.receiverType.name:null,returnType:e.returnType.name,params:e.params.map(e=>({name:e.name,type:e.type.name,description:e.description}))});return{variables:e,functions:t}}#E(e){if(typeof e!=`string`)throw Error(`Invalid signature: must be a string`);let t=e.match(/^(?:([a-zA-Z0-9.<>]+)\.)?(\w+)\(([^)]*)\):(.*)$/);if(!t)throw Error(`Invalid signature: ${e}`);let n=t[4].trim();if(!n)throw Error(`Invalid signature: ${e}`);return{receiverType:t[1]||null,name:t[2],argTypes:qe(t[3]),returnType:n}}#D(e,t){return e.name!==t.name||e.argTypes.length!==t.argTypes.length||(e.receiverType||t.receiverType)&&(!e.receiverType||!t.receiverType)?!1:!(e.receiverType!==t.receiverType&&e.receiverType!==Ve&&t.receiverType!==Ve)&&(t.macro||e.macro||t.argTypes.every((t,n)=>{let r=e.argTypes[n];return t===r||t===Ve||r===Ve}))}#O(e){for(let t of this.#v(e.partitionKey))if(this.#D(t,e))throw Error(`Function signature '${e.signature}' overlaps with existing overload '${t.signature}'.`)}#k(e,t,n){if(!n)return{type:this.getFunctionType(t),name:`arg${e}`,description:null};let r=n.type||t;if(!r)throw Error(`params[${e}].type is required`);if(t&&r!==t)throw Error(`params[${e}].type not equal to signature type`);return{name:n.name||`arg${e}`,type:this.getFunctionType(r),description:n.description??null}}registerFunctionOverload(e,t,n){if(this.#d)throw Error(`Cannot modify frozen registry`);typeof e==`object`?n=e:typeof t==`object`?n=t:n||={};let r=typeof e==`string`?e:n.signature??void 0,i=r===void 0?void 0:this.#E(r),a=i?.name||n.name,o=i?.receiverType||n.receiverType,s=i?.argTypes,c=i?.returnType||n.returnType,l=n.params;t=typeof t==`function`?t:n.handler;let u;try{if(!a)throw Error(`signature or name are required`);if(!c)throw Error(`must have a returnType`);if(l){if(s&&l.length!==s.length)throw Error(`mismatched length in params and args in signature`)}else if(!s)throw Error(`signature or params are required`);u=new Me({name:a,async:n?.async,receiverType:o?this.getType(o):null,returnType:this.getType(c),handler:t,description:n.description,params:(s||l).map((e,t)=>this.#k(t,s?.[t],l?.[t]))})}catch(e){throw typeof r==`string`?e.message=`Invalid function declaration '${r}': ${e.message}`:a?e.message=`Invalid function declaration '${a}': ${e.message}`:e.message=`Invalid function declaration: ${e.message}`,e}this.#O(u),this.#m(u)}registerOperatorOverload(e,t,n){let r=e.match(/^([-!])([\w.<>]+)(?::\s*([\w.<>]+))?$/);if(r){let[,e,i,a]=r;return this.unaryOverload(e,i,t,a,n?.async)}let i=e.match(/^([\w.<>]+) ([-+*%/]|==|!=|<|<=|>|>=|in) ([\w.<>]+)(?::\s*([\w.<>]+))?$/);if(!i)throw Error(`Operator overload invalid: ${e}`);let[,a,o,s,c]=i;return this.binaryOverload(a,o,s,t,c)}unaryOverload(e,t,n,r,i){if(this.#d)throw Error(`Cannot modify frozen registry`);let a=this.assertType(t,`type`,`${e}${t}`),o=this.assertType(r||t,`return type`,`${e}${t}: ${r||t}`),s=new Ne({op:`${e}_`,leftType:a,returnType:o,handler:n,async:i});this.#p(this.#j(s))}#A(e){for(let t of this.operatorCandidates(e.operator))if(e.equals(t))return!0;return!1}#j(e){if(!this.#A(e))return e;throw Error(`Operator overload already registered: ${e.signature}`)}binaryOverload(e,t,n,r,i,a){if(this.#d)throw Error(`Cannot modify frozen registry`);i??=tt.has(t)?`bool`:e;let o=`${e} ${t} ${n}: ${i}`,s=this.assertType(e,`left type`,o),c=this.assertType(n,`right type`,o),l=this.assertType(i,`return type`,o);if(s.kind===`dyn`&&s.valueType?c=c.wrappedType:c.kind===`dyn`&&c.valueType&&(s=s.wrappedType),tt.has(t)&&l.type!==`bool`)throw Error(`Comparison operator '${t}' must return 'bool', got '${l.type}'`);let u=new Ne({op:t,leftType:s,rightType:c,returnType:l,handler:r,async:a});if(u.hasPlaceholderType&&!(c.hasPlaceholderType&&s.hasPlaceholderType))throw Error(`Operator overload with placeholders must use them in both left and right types: ${o}`);if(this.#j(u),t===`==`){let e=[new Ne({op:`!=`,leftType:s,rightType:c,handler(e,t,n,i){return!r(e,t,n,i)},returnType:l,async:a})];s!==c&&e.push(new Ne({op:`==`,leftType:c,rightType:s,handler(e,t,n,i){return r(t,e,n,i)},returnType:l,async:a}),new Ne({op:`!=`,leftType:c,rightType:s,handler(e,t,n,i){return!r(t,e,n,i)},returnType:l,async:a}));for(let t of e)this.#j(t);for(let t of e)this.#p(t)}this.#p(u)}},tt=new Set([`<`,`<=`,`>`,`>=`,`==`,`!=`,`in`]);function nt(e){return new et(e)}var rt=class{#e;#t;#n;#r;constructor(e,t){if(this.#e=e.variables,t!=null){if(typeof t!=`object`)throw c(`invalid_context`,`Context must be an object`);t instanceof Map?this.#n=t:this.#t=t}}getValue(e){return this.#r?.get(e)||(this.#t?this.#t[e]:this.#n?.get(e))}getVariable(e){return this.#e.get(e)??(this.#e.dyn&&!he.has(e)?new je(e,Ve):void 0)}getCheckedValue(e,t){let n=this.getValue(t.args);if(n===void 0)throw e.createError(`unknown_variable`,`Unknown variable: ${t.args}`,t);if(t.checkedType.matchesValueType(n,e))return n;let r=t.checkedType,i=e.debugType(n);if(r.kind===`message`&&i.kind===`map`){let i=e.objectTypes.get(r.name)?.convert?.(n);if(i)return(this.#r??=new Map).set(t.args,i),i}throw e.createError(`variable_type_mismatch`,`Variable '${t.args}' is not of type '${r}', got '${i}'`,t)}forkWithVariable(e,t){return new it(this,e,t)}},it=class e{#e;accuType;accuValue;iterValue;constructor(e,t,n){this.#e=e,this.iterVar=t,this.iterType=n}forkWithVariable(t,n){return new e(this,t,n)}reuse(t){if(!this.async)return this.#e=t,this;let n=new e(t,this.iterVar,this.iterType);return n.accuType=this.accuType,n}setIterValue(e,t){if(this.iterType.matchesValueType(e,t))return this.iterValue=e,this;let n=this.iterType,r=t.debugType(e);if(n.kind===`message`&&r.kind===`map`){let r=t.objectTypes.get(n.name)?.convert?.(e);if(r)return this.iterValue=r,this}throw t.createError(`variable_type_mismatch`,`Variable '${this.iterVar}' is not of type '${n}', got '${r}'`)}setAccuType(e){return this.accuType=e,this}setAccuValue(e){return this.accuValue=e,this}getValue(e){return this.iterVar===e?this.iterValue:this.#e.getValue(e)}getCheckedValue(e,t){return this.iterVar===t.args?this.iterValue:this.#e.getCheckedValue(e,t)}getVariable(e){return this.iterVar===e?new je(e,this.iterType):this.#e.getVariable(e)}};function at(e){let t;return t=e.map?`map<${ot(e.keyType,e.resolvedKeyType)}, ${ot(e.type,e.resolvedType)}>`:ot(e.type,e.resolvedType),{type:e.repeated?`list<${t}>`:t}}function ot(e,t){switch(e){case`string`:return`string`;case`bytes`:return`bytes`;case`bool`:return`bool`;case`double`:case`float`:case`int32`:case`int64`:case`sint32`:case`sint64`:case`sfixed32`:case`sfixed64`:case`uint32`:case`uint64`:case`fixed32`:case`fixed64`:return`double`;default:switch(t?.constructor.name){case`Type`:return t.fullName.slice(1);case`Enum`:return`int`}return e?.includes(`.`)?e:`dyn`}}var st=Ge.dyn,ct=class{dynType=Ge.dyn;optionalType=Ge.optional;stringType=Ge.string;intType=Ge.int;doubleType=Ge.double;boolType=Ge.bool;nullType=Ge.null;listType=Ge.list;mapType=Ge.map;constructor(e){this.opts=e.opts,this.registry=e.registry,this.objectTypes=this.registry.objectTypes,this.objectTypesByConstructor=this.registry.objectTypesByConstructor}getType(e){return this.registry.getType(e)}debugType(e){switch(typeof e){case`string`:return this.stringType;case`bigint`:return this.intType;case`number`:return this.doubleType;case`boolean`:return this.boolType;case`object`:if(e===null)return this.nullType;switch(e.constructor){case void 0:case Object:case Map:return this.mapType;case Array:case Set:return this.listType;default:return this.objectTypesByConstructor.get(e.constructor)?.type||lt(this,e.constructor?.name||typeof e)}default:lt(this,typeof e)}}};function lt(e,t){throw e.createError(`unsupported_type`,`Unsupported type: ${t}`)}var ut=e=>Array.isArray(e)?e.some(e=>e.maybeAsync):!1;function dt(e,t,n){return t===!0||t&&(t?.maybeAsync||ut(t))?ft(n):e===!0||e&&(e?.maybeAsync||ut(e))?pt(n):n}function ft(e){return e.__asyncBoth??=function(t,n,r,i){return t instanceof Promise||n instanceof Promise?n instanceof Promise?t instanceof Promise?Promise.all([t,n]).then(t=>e(t[0],t[1],r,i)):n.then(n=>e(t,n,r,i)):t.then(t=>e(t,n,r,i)):e(t,n,r,i)}}function pt(e){return e.__asyncFirst??=function(t,n,r,i){return t instanceof Promise?t.then(t=>e(t,n,r,i)):e(t,n,r,i)}}function mt(e,t,n){t.right=t.args[1];let r=e.check(t.left=t.args[0],n);return t.op===`[]`&&e.check(t.right,n),t.handle=dt(t.left,t.op===`[]`?t.right:!1,r===st?Yt:qt),r.kind===`optional`?e.registry.getOptionalType(e.checkAccessOnType(t,n,r.valueType,!0)):e.checkAccessOnType(t,n,r)}function ht(e,t,n){t.right=t.args[1];let r=e.check(t.left=t.args[0],n);t.op===`[?]`&&e.check(t.right,n),t.handle=dt(t.left,t.op===`[?]`?t.right:!1,Kt);let i=r.kind===`optional`?r.valueType:r;return e.registry.getOptionalType(e.checkAccessOnType(t,n,i,!0))}var gt={heterogeneous_list_element:`List elements must have the same type,`,heterogeneous_map_key:`Map key uses wrong type,`,heterogeneous_map_value:`Map value uses wrong type,`};function _t(e,t,n,r,i){let a=e.check(r,t);if(a===n||n.isEmpty())return a;if(a.isEmpty())return n;throw e.createError(i,`${gt[i]} expected type '${e.formatType(n)}' but found '${e.formatType(a)}'`,r)}function vt(e,t,n,r){return n.unify(e.registry,e.check(r,t))||st}function yt(e,t,n){let r=e.debugRuntimeType(t);return e.createError(`invalid_condition_type`,`${n.meta.label||`Ternary condition must be bool`}, got '${r}'`,n)}function bt(e,t,n,r){if(e===!0)return t.eval(n.left,r);if(e===!1)return t.eval(n.right,r);throw yt(t,e,n.condition)}function xt(e,t,n){let r=e.debugRuntimeType(t);return e.createError(`invalid_logical_operand`,`Logical operator requires bool operands, got '${r}'`,n)}function St(e,t,n){return t instanceof Error?t:xt(e,t,n)}function Ct(e,t,n,r,i){if(i===e)return e;if(i===!e){if(r===i)return i;throw St(t,r,n.left)}if(i instanceof Promise)return i.then(i=>wt(e,t,n,r,i));throw xt(t,i,n.left)}function wt(e,t,n,r,i){if(i===e)return e;if(typeof i!=`boolean`)throw xt(t,i,n.right);if(typeof r!=`boolean`)throw St(t,r,n.left);return!e}function Tt(e,t,n){let r=e.check(t.left=t.args[0],n),i=e.check(t.right=t.args[1],n);if(!r.isDynOrBool())throw e.createError(`invalid_logical_operand`,`Logical operator requires bool operands, got '${e.formatType(r)}'`,t);if(!i.isDynOrBool())throw e.createError(`invalid_logical_operand`,`Logical operator requires bool operands, got '${e.formatType(i)}'`,t);return e.boolType}function Et(e,t,n){let r=t.op,i=e.check(t.args,n);if(t.candidates=e.registry.operatorCandidates(r),i.kind===`dyn`)return t.handle=dt(t.args,!1,Dt),t.candidates.returnType;let a=t.candidates.findUnaryOverload(i);if(!a)throw e.createError(`no_such_overload`,`no such overload: ${r[0]}${e.formatType(i)}`,t);return t.handle=dt(t.args,!1,a.handler),a.returnType}function Dt(e,t,n){let r=n.debugRuntimeType(e,t.args.checkedType),i=t.candidates.findUnaryOverload(r);if(i)return i.handler(e);throw n.createError(`no_such_overload`,`no such overload: ${t.op[0]}${r}`,t)}function Ot(e,t,n){return t.handle(e.eval(t.args,n),t,e)}function kt(e,t,n){let r=t.op,i=e.check(t.left=t.args[0],n),a=e.check(t.right=t.args[1],n);t.candidates=e.registry.operatorCandidates(r);let o=i.hasDynType||a.hasDynType?void 0:t.candidates.findBinaryOverload(i,a);if(t.handle=dt(t.left,t.right,o?.handler||Mt),o)return o.returnType;let s=t.candidates.checkBinaryOverload(i,a);if(i.hasDynType||(t.leftStaticType=i),a.hasDynType||(t.rightStaticType=a),s)return s;throw e.createError(`no_such_overload`,`no such overload: ${e.formatType(i)} ${r} ${e.formatType(a)}`,t)}function At(e,t,n){return t.handle(e.eval(t.left,n),e.eval(t.right,n),t,e)}function jt(e,t,n){return t.handle(e.eval(t.left,n),t.right,t,e)}function Mt(e,t,n,r){let i=n.leftStaticType||r.debugTypeDeep(e).wrappedType,a=n.rightStaticType||r.debugTypeDeep(t).wrappedType,o=n.candidates.findBinaryOverload(i,a);if(o)return o.handler(e,t,n,r);throw r.createError(`no_such_overload`,`no such overload: ${i} ${n.op} ${a}`,n)}function Nt(e,t,n,r){try{let i=e.apply(t,n);return i instanceof Promise?i.catch(e=>{throw te(e,r)}):i}catch(e){throw te(e,r)}}function Pt(e,t,n){let r=t.args[1],i=t.argTypes,a=r.length;for(;a--;)i[a]=n.debugRuntimeType(e[a],r[a].checkedType);let o=t.candidates.findFunction(i);if(o)return Nt(o.handler,n,e,t);throw n.createError(`no_matching_overload`,`found no matching overload for '${t.args[0]}(${i.map(e=>e.unwrappedType).join(`, `)})'`,t)}function Ft(e,t,n){let[,r,i]=n.args,a=n.argTypes;for(let n=0;n<a.length;n++)a[n]=t.debugRuntimeType(e[n+1],i[n].checkedType);let o=t.debugRuntimeType(e[0],r.checkedType),s=n.candidates.findFunction(a,o);if(s)return Nt(s.handler,t,e,n);throw t.createError(`no_matching_overload`,`found no matching overload for '${o.type}.${n.args[0]}(${a.map(e=>e.unwrappedType).join(`, `)})'`,n)}function It(e,t,n,r=t.length){if(r===0)return[];let i,a=Array(r);for(;r--;)(a[r]=e.eval(t[r],n))instanceof Promise&&(i??=!0);return i?Promise.all(a):a}function Lt(e){let t={};for(let n=0;n<e.length;n++){let[r,i]=e[n];r===`__proto__`||r===`constructor`||r===`prototype`||(t[r]=i)}return t}function Rt(e,t,n){let r=e.check(t,n);if(r.kind===`dyn`)return r;if(r.kind===`list`)return r.valueType;if(r.kind===`map`)return r.keyType;throw e.createError(`invalid_comprehension_range`,`Expression of type '${e.formatType(r)}' cannot be range of a comprehension (must be list, map, or dynamic).`,t)}function zt(e,t,n){if(n instanceof Set)return[...n];if(n instanceof Map)return[...n.keys()];if(n&&typeof n==`object`)return le(n);throw e.createError(`invalid_comprehension_range`,`Expression of type '${e.debugType(n)}' cannot be range of a comprehension (must be list, map, or dynamic).`,t.iterable)}function Bt(e,t,n,r){fe(e)||(e=zt(n,t,e));let i=n.eval(t.init,r=t.iterCtx.reuse(r));return r.accuValue=i,r===t.iterCtx?Wt(n,r,t,e,i,0):Gt(n,r,t,e,i,0)}function Vt(e,t,n,r){fe(e)||(e=zt(n,t,e));let i=n.eval(t.init,r=t.iterCtx.reuse(r));return r.accuValue=i,r===t.iterCtx?Ht(n,r,t,e,i,0):Ut(n,r,t,e,i,0)}function Ht(e,t,n,r,i,a){let o=n.condition,s=n.step,c=r.length;for(;a<c&&!(o&&!o(i));)if(i=e.eval(s,t.setIterValue(r[a++],e)),i instanceof Promise)return Ut(e,t,n,r,i,a);return n.result(i)}async function Ut(e,t,n,r,i,a){t===n.iterCtx&&(t.async=!0);let o=n.condition,s=n.step,c=r.length;for(i=await i;a<c;){if(o&&!o(i))return n.result(i);i=e.eval(s,t.setIterValue(r[a++],e)),i instanceof Promise&&(i=await i)}return n.result(i)}function Wt(e,t,n,r,i,a,o,s){let c=n.condition,l=n.step,u=r.length;for(;a<u;){if(!c(i))return n.result(i);if(s=e.tryEval(l,t.setIterValue(r[a++],e)),s instanceof Promise)return Gt(e,t,n,r,i,a,o,s);s instanceof Error&&(o??=s)||(i=s)}if(o&&c(i))throw o;return n.result(i)}async function Gt(e,t,n,r,i,a,o,s){t===n.iterCtx&&(t.async=!0);let c=n.condition,l=n.step,u=r.length;for(s=await s,s instanceof Error?o??=s:i=s;a<u;){if(!c(i))return n.result(i);s=e.tryEval(l,t.setIterValue(r[a++],e)),s instanceof Promise&&(s=await s),!(s instanceof Error&&(o??=s))&&(i=s)}if(o&&c(i))throw o;return n.result(i)}function Kt(e,t,n,r){return r.optionalType.field(e,t,n,r)}function qt(e,t,n,r){return n.left.checkedType.field(e,t,n,r)}var Jt=Object.create(null);function Yt(e,t,n,r){switch(e?.constructor){case void 0:case Object:{let n=ce(e||Jt,t)?e[t]:void 0;if(n!==void 0)return r.debugType(n),n;break}case Map:{let n=e.get(t);if(n!==void 0)return r.debugType(n),n;break}case Array:case Set:return r.listType.field(e,t,n,r);default:let i=r.objectTypesByConstructor.get(e.constructor);if(i)return i.type.field(e,t,n,r);typeof e==`object`&<(r,e.constructor.name)}throw r.createError(`no_such_key`,`No such key: ${t}`,n)}var Xt=()=>[],Zt=()=>({}),d={value:{check(e,t){return e.debugType(t.args)},evaluate(e,t){return t.args}},id:{check(e,t,n){let r=n.getVariable(t.args);if(!r)throw e.createError(`unknown_variable`,`Unknown variable: ${t.args}`,t);if(r.constant){let i=t.clone(d.value,r.value);return t.setMeta(`alternate`,i),e.check(i,n)}return r.type},evaluate(e,t,n){return n.getCheckedValue(e,t)}},".":{alias:`fieldAccess`,check:mt,evaluate:jt},".?":{alias:`optionalFieldAccess`,check:ht,evaluate:jt},"[]":{alias:`bracketAccess`,check:mt,evaluate:At},"[?]":{alias:`optionalBracketAccess`,check:ht,evaluate:At},call:{check(e,t,n){let[r,i]=t.args,a=t.candidates=e.registry.functionCandidates(!1,r,i.length),o=t.argTypes=i.map(t=>e.check(t,n)),s=a.findFunction(o);if(!s)throw e.createError(`no_matching_overload`,`found no matching overload for '${r}(${e.formatTypeList(o)})'`,t);return t.handle=dt(i,!1,o.some(e=>e.hasDynType)?Pt:s.handler.__handle??=(e,t,n)=>Nt(s.handler,n,e,t)),s.returnType},evaluate(e,t,n){return t.handle(It(e,t.args[1],n),t,e)}},rcall:{check(e,t,n){let[r,i,a]=t.args,o=e.check(i,n),s=t.candidates=e.registry.functionCandidates(!0,r,a.length),c=t.argTypes=a.map(t=>e.check(t,n));if(t.receiverWithArgs=[i,...a],t.handle=dt(t.receiverWithArgs,!1,Ft),o.kind===`dyn`&&s.returnType)return s.returnType;let l=s.findFunction(c,o);if(!l)throw e.createError(`no_matching_overload`,`found no matching overload for '${o.type}.${r}(${e.formatTypeList(c)})'`,t);if(!o.hasPlaceholderType&&!c.some(e=>e.hasDynType)){let e=l.handler,n=e.__handle??=(t,n,r)=>Nt(e,n,t,r);t.handle=dt(t.receiverWithArgs,!1,n)}return l.returnType},evaluate(e,t,n){return t.handle(It(e,t.receiverWithArgs,n),e,t)}},list:{check(e,t,n){let r=t.args,i=r.length;if(i===0)return t.setMeta(`evaluate`,Xt)&&e.getType(`list<T>`);let a=e.check(r[0],n),o=e.opts.homogeneousAggregateLiterals?_t:vt;for(let t=1;t<i;t++)a=o(e,n,a,r[t],`heterogeneous_list_element`);return e.registry.getListType(a)},evaluate(e,t,n){return It(e,t.args,n)}},map:{check(e,t,n){let r=t.args,i=r.length;if(i===0)return t.setMeta(`evaluate`,Zt)&&e.getType(`map<K, V>`);let a=e.opts.homogeneousAggregateLiterals?_t:vt,o=e.check(r[0][0],n),s=e.check(r[0][1],n);for(let t=1;t<i;t++){let i=r[t];o=a(e,n,o,i[0],`heterogeneous_map_key`),s=a(e,n,s,i[1],`heterogeneous_map_value`)}return e.registry.getMapType(o,s)},evaluate(e,t,n){let r=t.args,i=r.length,a=Array(i),o;for(let t=0;t<i;t++){let i=r[t],s=e.eval(i[0],n),c=e.eval(i[1],n);s instanceof Promise||c instanceof Promise?(a[t]=Promise.all([s,c]),o??=!0):a[t]=[s,c]}return o?Promise.all(a).then(Lt):Lt(a)}},comprehension:{check(e,t,n){let r=t.args;r.iterCtx=n.forkWithVariable(r.iterVarName,Rt(e,r.iterable,n)).setAccuType(e.check(r.init,n));let i=e.check(r.step,r.iterCtx),a=r.errorsAreFatal?Vt:Bt;return t.handle=dt(r.iterable,!1,a),r.kind===`quantifier`?e.boolType:i},evaluate(e,t,n){return t.handle(e.eval(t.args.iterable,n),t.args,e,n)}},accuValue:{check(e,t,n){return n.accuType},evaluate(e,t,n){return n.accuValue}},accuInc:{check(e,t,n){return n.accuType},evaluate(e,t,n){return n.accuValue+=1}},accuPush:{check(e,t,n){let r=n.accuType,i=e.check(t.args,n);return t.args.maybeAsync||t.setMeta(`evaluate`,d.accuPush.evaluateSync),r.kind===`list`&&r.valueType.kind!==`param`?r:e.registry.getListType(i)},evaluateSync(e,t,n){return n.accuValue.push(e.eval(t.args,n)),n.accuValue},evaluate(e,t,n){let r=n.accuValue,i=e.eval(t.args,n);return i instanceof Promise?i.then(e=>r.push(e)&&r):(r.push(i),r)}},"?:":{alias:`ternary`,check(e,t,n){let r=t.condition=t.args[0],i=t.left=t.args[1],a=t.right=t.args[2],o=e.check(r,n);if(!o.isDynOrBool())throw e.createError(`invalid_condition_type`,`${r.meta.label||`Ternary condition must be bool`}, got '${e.formatType(o)}'`,r);let s=e.check(i,n),c=e.check(a,n),l=s.unify(e.registry,c);if(t.handle=dt(r,!1,bt),l)return l;throw e.createError(`incompatible_ternary_branches`,`Ternary branches must have the same type, got '${e.formatType(s)}' and '${e.formatType(c)}'`,t)},evaluate(e,t,n){return t.handle(e.eval(t.condition,n),e,t,n)}},"||":{check:Tt,evaluate(e,t,n){let r=e.tryEval(t.left,n);if(r===!0)return!0;if(r===!1){let i=e.eval(t.right,n);return typeof i==`boolean`?i:Ct(!0,e,t,r,i)}return r instanceof Promise?r.then(r=>r===!0?r:Ct(!0,e,t,r,e.eval(t.right,n))):Ct(!0,e,t,r,e.eval(t.right,n))}},"&&":{check:Tt,evaluate(e,t,n){let r=e.tryEval(t.left,n);if(r===!1)return!1;if(r===!0){let i=e.eval(t.right,n);return typeof i==`boolean`?i:Ct(!1,e,t,r,i)}return r instanceof Promise?r.then(r=>r===!1?r:Ct(!1,e,t,r,e.eval(t.right,n))):Ct(!1,e,t,r,e.eval(t.right,n))}},"!_":{alias:`unaryNot`,check:Et,evaluate:Ot},"-_":{alias:`unaryMinus`,check:Et,evaluate:Ot}};for(let e of[`!=`,`==`,`in`,`+`,`-`,`*`,`/`,`%`,`<`,`<=`,`>`,`>=`])d[e]={check:kt,evaluate:At};for(let e of le(d)){let t=d[e];t.name=e,t.alias&&(d[t.alias]=t)}var Qt=e=>e;function $t(e,t){if(e.op===`id`)return e.args;throw s(`invalid_macro_argument`,t,e)}function en(e){let t=e?`map(var, filter, transform)`:`map(var, transform)`,n=`${t} invalid predicate iteration variable`,r=`${t} filter predicate must return bool`;return({args:t,receiver:i,ast:a})=>{let[o,s,c]=e?t:[t[0],null,t[1]],l=c.clone(d.accuPush,c);if(s){let e=s.clone(d.accuValue);l=s.clone(d.ternary,[s.setMeta(`label`,r),l,e])}return{callAst:a.clone(d.comprehension,{errorsAreFatal:!0,iterable:i,iterVarName:$t(o,n),init:a.clone(d.list,[]),step:l,result:Qt})}}}function tn(){let e=`filter(var, predicate)`,t=`${e} invalid predicate iteration variable`,n=`${e} predicate must return bool`;return({args:e,receiver:r,ast:i})=>{let a=$t(e[0],t),o=i.clone(d.accuValue),s=e[1].setMeta(`label`,n),c=i.clone(d.accuPush,i.clone(d.id,a)),l=s.clone(d.ternary,[s,c,o]);return{callAst:i.clone(d.comprehension,{errorsAreFatal:!0,iterable:r,iterVarName:a,init:i.clone(d.list,[]),step:l,result:Qt})}}}function nn(e){let t=`${e.name}(var, predicate) invalid predicate iteration variable`,n=`${e.name}(var, predicate) predicate must return bool`;return({args:r,receiver:i,ast:a})=>{let o=r[1].setMeta(`label`,n),s=e.transform({args:r,ast:a,predicate:o,opts:e});return{callAst:a.clone(d.comprehension,{kind:`quantifier`,errorsAreFatal:e.errorsAreFatal||!1,iterable:i,iterVarName:$t(r[0],t),init:s.init,condition:s.condition,step:s.step,result:s.result||Qt})}}}function rn(){let e=`has() invalid argument`;function t(e,t,n){let r=t.macroHasProps,i=r.length,a=e.eval(r[--i],n),o;for(;i--;){let t=r[i];if(t.op===`.?`&&(o??=!0),a=e.debugType(a).fieldLazy(a,t.args[1],t,e),a===void 0){if(!(!o&&i&&t.op===`.`))break;throw c(`no_such_key`,`No such key: ${t.args[1]}`,t)}}return a!==void 0}function n(t,n,r){let i=n.args[0];if(i.op!==`.`)throw t.createError(`invalid_macro_argument`,e,i);if(!n.macroHasProps){let a=[];for(;i.op===`.`||i.op===`.?`;)i=a.push(i)&&i.args[0];if(i.op!==`id`)throw t.createError(`invalid_macro_argument`,e,i);t.check(i,r),a.push(i),n.macroHasProps=a}return t.getType(`bool`)}return function({args:e}){return{args:e,evaluate:t,typeCheck:n,async:!1}}}function an(e){let t=(t,n)=>e.registerFunctionOverload(t,n);t(`has(ast): bool`,rn()),t(`list.all(ast, ast): bool`,nn({name:`all`,transform({ast:e,predicate:t,opts:n}){return{init:e.clone(d.value,!0),condition:Qt,step:t.clone(d.ternary,[t,t.clone(d.value,!0),t.clone(d.value,!1)])}}})),t(`list.exists(ast, ast): bool`,nn({name:`exists`,condition(e){return!e},transform({ast:e,predicate:t,opts:n}){return{init:e.clone(d.value,!1),condition:n.condition,step:t.clone(d.ternary,[t,t.clone(d.value,!0),t.clone(d.value,!1)])}}})),t(`list.exists_one(ast, ast): bool`,nn({name:`exists_one`,errorsAreFatal:!0,result(e){return e===1},transform({ast:e,predicate:t,opts:n}){let r=e.clone(d.accuValue);return{init:e.clone(d.value,0),step:t.clone(d.ternary,[t,e.clone(d.accuInc),r]),result:n.result}}})),t(`list.map(ast, ast): list<dyn>`,en(!1)),t(`list.map(ast, ast, ast): list<dyn>`,en(!0)),t(`list.filter(ast, ast): list<dyn>`,tn());class n{}let r=new n;e.registerType(`CelNamespace`,n),e.registerConstant(`cel`,`CelNamespace`,r);function i(e,t,n){t.bindCtx=n.forkWithVariable(t.var,e.check(t.val,n));let r=e.check(t.exp,t.bindCtx);return t.val.maybeAsync||t.exp.maybeAsync?r:(t.ast.setMeta(`async`,!1),t.evaluate=s,r)}function a(e,t,n,r,i){let a=e.eval(t,r=n.reuse(r).setIterValue(i,e));return a instanceof Promise&&r===n&&(r.async=!0),a}function o(e,{val:t,exp:n,bindCtx:r},i){let o=e.eval(t,i);return o instanceof Promise?o.then(t=>a(e,n,r,i,t)):a(e,n,r,i,o)}function s(e,{val:t,exp:n,bindCtx:r},i){return e.eval(n,r.reuse(i).setIterValue(e.eval(t,i),e))}t(`CelNamespace.bind(ast, dyn, ast): dyn`,({ast:e,args:t})=>({ast:e,var:$t(t[0],`invalid variable argument`),val:t[1],exp:t[2],bindCtx:void 0,typeCheck:i,evaluate:o}))}function on(e){let t=(t,n,r,i)=>e.unaryOverload(t,n,r,i,!1),n=(t,n,r,i,a)=>e.binaryOverload(t,n,r,i,a,!1);function r(e,t){if(e<=9223372036854775807n&&e>=-9223372036854775808n)return e;throw c(`numeric_overflow`,`integer overflow: ${e}`,t)}function i(e){throw c(`division_by_zero`,`division by zero`,e)}function a(e){throw c(`modulo_by_zero`,`modulo by zero`,e)}t(`!`,`bool`,e=>!e),t(`-`,`int`,e=>-e),n(`dyn<int>`,`==`,`double`,(e,t)=>e==t),n(`dyn<int>`,`==`,`uint`,(e,t)=>e==t.valueOf()),n(`int`,`*`,`int`,(e,t,n)=>r(e*t,n)),n(`int`,`+`,`int`,(e,t,n)=>r(e+t,n)),n(`int`,`-`,`int`,(e,t,n)=>r(e-t,n)),n(`int`,`/`,`int`,(e,t,n)=>t===0n?i(n):e/t),n(`int`,`%`,`int`,(e,t,n)=>t===0n?a(n):e%t),t(`-`,`double`,e=>-e),n(`double`,`*`,`double`,(e,t)=>e*t),n(`double`,`+`,`double`,(e,t)=>e+t),n(`double`,`-`,`double`,(e,t)=>e-t),n(`double`,`/`,`double`,(e,t)=>e/t),n(`string`,`+`,`string`,(e,t)=>e+t),n(`list<V>`,`+`,`list<V>`,(e,t)=>[...e,...t]),n(`bytes`,`+`,`bytes`,(e,t)=>{if(!e.length)return t;if(!t.length)return e;let n=new Uint8Array(e.length+t.length);return n.set(e,0),n.set(t,e.length),n});let o=`google.protobuf.Duration`;n(o,`+`,o,(e,t)=>e.addDuration(t)),n(o,`-`,o,(e,t)=>e.subtractDuration(t)),n(o,`==`,o,(e,t)=>e.seconds===t.seconds&&e.nanos===t.nanos);let s=`google.protobuf.Timestamp`;n(s,`==`,s,(e,t)=>e.getTime()===t.getTime()),n(s,`-`,s,(e,t)=>be.fromMilliseconds(e.getTime()-t.getTime()),o),n(s,`-`,o,(e,t)=>t.subtractTimestamp(e)),n(s,`+`,o,(e,t)=>t.extendTimestamp(e)),n(o,`+`,s,(e,t)=>e.extendTimestamp(t));function l(e,t,n,r){if(t instanceof Set&&t.has(e))return!0;for(let i of t)if(sn(e,i,n,r))return!0;return!1}function u(e,t){return t instanceof Map?t.get(e)!==void 0:ce(t,e)?t[e]!==void 0:!1}function ee(e,t,n,r){return l(e,t,n,r)}n(`V`,`in`,`list<V>`,ee),n(`K`,`in`,`map<K, V>`,u);for(let e of[`type`,`null`,`bool`,`string`,`int`,`double`])n(e,`==`,e,(e,t)=>e===t);n(`bytes`,`==`,`bytes`,(e,t)=>{if(e===t)return!0;let n=e.length;if(n!==t.length)return!1;for(;n--;)if(e[n]!==t[n])return!1;return!0}),n(`list<V>`,`==`,`list<V>`,(e,t,n,r)=>{if(e===t)return!0;if(fe(e)&&fe(t)){let i=e.length;if(i!==t.length)return!1;for(let a=0;a<i;a++)if(!sn(e[a],t[a],n,r))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}let i=e instanceof Set?t:e,a=e instanceof Set?e:t;if(!fe(i)||i.length!==a?.size)return!1;for(let e=0;e<i.length;e++)if(!a.has(i[e]))return!1;return!0}),n(`map<K, V>`,`==`,`map<K, V>`,(e,t,n,r)=>{if(e===t)return!0;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(let[i,a]of e)if(!(t.has(i)&&sn(a,t.get(i),n,r)))return!1;return!0}if(e instanceof Map||t instanceof Map){let i=e instanceof Map?t:e,a=e instanceof Map?e:t,o=le(i);if(a.size!==o.length)return!1;for(let[e,t]of a)if(!(e in i&&sn(t,i[e],n,r)))return!1;return!0}let i=le(e),a=le(t);if(i.length!==a.length)return!1;for(let a=0;a<i.length;a++){let o=i[a];if(!(o in t&&sn(e[o],t[o],n,r)))return!1}return!0}),n(`uint`,`==`,`uint`,(e,t)=>e.valueOf()===t.valueOf()),n(`dyn<uint>`,`==`,`double`,(e,t)=>e.valueOf()==t),n(`uint`,`+`,`uint`,(e,t)=>new ge(e.valueOf()+t.valueOf())),n(`uint`,`-`,`uint`,(e,t)=>new ge(e.valueOf()-t.valueOf())),n(`uint`,`*`,`uint`,(e,t)=>new ge(e.valueOf()*t.valueOf())),n(`uint`,`/`,`uint`,(e,t,n)=>t.valueOf()===0n?i(n):new ge(e.valueOf()/t.valueOf())),n(`uint`,`%`,`uint`,(e,t,n)=>t.valueOf()===0n?a(n):new ge(e.valueOf()%t.valueOf()));for(let[e,t]of[[`bool`,`bool`],[`int`,`int`],[`uint`,`uint`],[`double`,`double`],[`string`,`string`],[`google.protobuf.Timestamp`,`google.protobuf.Timestamp`],[`google.protobuf.Duration`,`google.protobuf.Duration`],[`int`,`uint`],[`int`,`double`],[`double`,`int`],[`double`,`uint`],[`uint`,`int`],[`uint`,`double`]])n(e,`<`,t,(e,t)=>e<t),n(e,`<=`,t,(e,t)=>e<=t),n(e,`>`,t,(e,t)=>e>t),n(e,`>=`,t,(e,t)=>e>=t)}function sn(e,t,n,r){if(e===t)return!0;switch(typeof e){case`undefined`:case`string`:case`boolean`:return!1;case`bigint`:return typeof t==`number`?e==t:!1;case`number`:return typeof t==`bigint`?e==t:!1;case`object`:if(typeof t!=`object`)return!1;let i=r.debugType(e),a=r.debugType(t);if(i!==a)return!1;let o=r.registry.findBinaryOverload(`==`,i,a);return o?o.handler(e,t,n,r):!1}throw c(`invalid_comparison_type`,`Cannot compare values of type ${typeof e}`,n)}var cn=new Map().set(`A`,`dyn`).set(`T`,`dyn`).set(`K`,`dyn`).set(`V`,`dyn`),ln=class extends ct{constructor(e,t){super(e),this.createError=t?c:l}check(e,t){try{return e.checkedType??=e.check(this,e,t)}catch(t){throw te(t,e)}}checkAccessOnType(e,t,n,r=!1){if(n===this.dynType)return n;let i=(e.op===`[]`||e.op===`[?]`?this.check(e.args[1],t):this.stringType).type;if(n.kind===`list`){if(i===`int`||i===`dyn`)return n.valueType;throw this.createError(`invalid_index_type`,`List index must be int, got '${i}'`,e)}if(n.kind===`map`)return n.valueType;let a=this.objectTypes.get(n.name);if(a){if(!(i===`string`||i===`dyn`))throw this.createError(`invalid_index_type`,`Cannot index type '${n.name}' with type '${i}'`,e);if(a.fields){let t;if(e.op===`.`||e.op===`.?`?t=e.args[1]:e.args[1].op===`value`&&(t=e.args[1].args),typeof t==`string`){let n=a.fields[t];if(n)return n;if(r)return this.dynType;throw this.createError(`no_such_key`,`No such key: ${t}`,e)}}return this.dynType}throw this.createError(`cannot_index_type`,`Cannot index type '${this.formatType(n)}'`,e)}formatType(e){return e.hasPlaceholderType?e.templated(this.registry,cn).name:e.name}formatTypeList(e){return e.map(e=>this.formatType(e)).join(`, `)}},f={EOF:0,NUMBER:1,STRING:2,BOOLEAN:3,NULL:4,IDENTIFIER:5,PLUS:6,MINUS:7,MULTIPLY:8,DIVIDE:9,MODULO:10,EQ:11,NE:12,LT:13,LE:14,GT:15,GE:16,AND:17,OR:18,NOT:19,IN:20,LPAREN:21,RPAREN:22,LBRACKET:23,RBRACKET:24,LBRACE:25,RBRACE:26,DOT:27,COMMA:28,COLON:29,QUESTION:30,BYTES:31},un={[f.EQ]:d[`==`],[f.PLUS]:d[`+`],[f.MINUS]:d[`-`],[f.MULTIPLY]:d[`*`],[f.DIVIDE]:d[`/`],[f.MODULO]:d[`%`],[f.LE]:d[`<=`],[f.LT]:d[`<`],[f.GE]:d[`>=`],[f.GT]:d[`>`],[f.NE]:d[`!=`],[f.IN]:d.in},dn={};for(let e in f)dn[f[e]]=e;var fn=new Uint8Array(128);for(let e of`0123456789abcdefABCDEF`)fn[e.charCodeAt(0)]=1;var pn={bytes_unicode_escape:e=>`\\${e} not allowed in bytes literals`,invalid_unicode_escape:e=>`Invalid Unicode escape: \\${e}`,invalid_unicode_surrogate:e=>`Invalid Unicode surrogate: \\${e}`,invalid_hex_escape:e=>`Invalid hex escape: \\${e}`,invalid_octal_escape:()=>`Octal escape must be 3 digits`,octal_escape_out_of_range:e=>`Octal escape out of range: \\${e}`,invalid_escape_sequence:e=>`Invalid escape sequence: \\${e}`},mn={"\\":`\\`,"?":`?`,'"':`"`,"'":`'`,"`":"`",a:`\x07`,b:`\b`,f:`\f`,n:`
|
|
5
|
+
`,r:`\r`,t:` `,v:`\v`},hn=class e{#e;#t;constructor(e,t,n,r,i,a){this.#e={check:i.check,evaluate:i.evaluate},this.#t=e,this.op=i.name,this.args=a,this.pos=t,this.start=n,this.end=r}clone(t,n){return new e(this.#t,this.pos,this.start,this.end,t,n)}get meta(){return this.#e}get input(){return this.#t}#n(){let e=this.#e.alternate??this;switch(e.op){case`value`:case`id`:case`accuValue`:case`accuInc`:return!1;case`accuPush`:return e.args.maybeAsync;case`!_`:case`-_`:return e.candidates?.async===!1?e.args.maybeAsync:!0;case`!=`:case`==`:case`in`:case`+`:case`-`:case`*`:case`/`:case`%`:case`<`:case`<=`:case`>`:case`>=`:return e.candidates?.async===!1?e.args.some(e=>e.maybeAsync):!0;case`call`:case`rcall`:return e.candidates?.async===!1?(e.receiverWithArgs||e.args[1]).some(e=>e.maybeAsync):!0;case`comprehension`:return e.args.iterable.maybeAsync||e.args.step.maybeAsync;case`.`:case`.?`:return e.args[0].maybeAsync;case`?:`:case`list`:case`[]`:case`[?]`:return e.args.some(e=>e.maybeAsync);case`||`:case`&&`:return e.args.some(e=>e.maybeAsync);case`map`:return e.args.some(e=>e[0].maybeAsync||e[1].maybeAsync);default:return!0}}get maybeAsync(){return this.#e.async??=this.#n()}check(e,t,n){let r=this.#e;return r.alternate?e.check(r.alternate,n):r.macro?r.macro.typeCheck(e,r.macro,n):r.check(e,t,n)}evaluate(e,t,n){let r=this.#e;return r.alternate?this.evaluate=this.#r:r.macro?this.evaluate=this.#i:this.evaluate=r.evaluate,this.evaluate(e,t,n)}#r(e,t,n){return(t=this.#e.alternate).evaluate(e,t,n)}#i(e,t,n){return(t=this.#e.macro).evaluate(e,t,n)}setMeta(e,t){return this.#e[e]=t,this}get range(){return{start:this.start,end:this.end}}toOldStructure(){let t=Array.isArray(this.args)?this.args:[this.args];return[this.op,...t.map(t=>t instanceof e?t.toOldStructure():t)]}},gn=new class{input;pos;length;tokenPos;tokenType;tokenValue;reset(e){return this.pos=0,this.input=e,this.length=e.length,e}token(e,t,n){return this.tokenPos=e,this.tokenType=t,this.tokenValue=n,this}nextToken(){for(;;){let{pos:e,input:t,length:n}=this;if(e>=n)return this.token(e,f.EOF);let r=t[e];switch(r){case` `:case` `:case`
|
|
6
|
+
`:case`\r`:this.pos++;continue;case`=`:if(t[e+1]!==`=`)break;return this.token((this.pos+=2)-2,f.EQ);case`&`:if(t[e+1]!==`&`)break;return this.token((this.pos+=2)-2,f.AND);case`|`:if(t[e+1]!==`|`)break;return this.token((this.pos+=2)-2,f.OR);case`+`:return this.token(this.pos++,f.PLUS);case`-`:return this.token(this.pos++,f.MINUS);case`*`:return this.token(this.pos++,f.MULTIPLY);case`/`:if(t[e+1]===`/`){for(;this.pos<n&&this.input[this.pos]!==`
|
|
7
|
+
`;)this.pos++;continue}return this.token(this.pos++,f.DIVIDE);case`%`:return this.token(this.pos++,f.MODULO);case`<`:return t[e+1]===`=`?this.token((this.pos+=2)-2,f.LE):this.token(this.pos++,f.LT);case`>`:return t[e+1]===`=`?this.token((this.pos+=2)-2,f.GE):this.token(this.pos++,f.GT);case`!`:return t[e+1]===`=`?this.token((this.pos+=2)-2,f.NE):this.token(this.pos++,f.NOT);case`(`:return this.token(this.pos++,f.LPAREN);case`)`:return this.token(this.pos++,f.RPAREN);case`[`:return this.token(this.pos++,f.LBRACKET);case`]`:return this.token(this.pos++,f.RBRACKET);case`{`:return this.token(this.pos++,f.LBRACE);case`}`:return this.token(this.pos++,f.RBRACE);case`.`:return this.token(this.pos++,f.DOT);case`,`:return this.token(this.pos++,f.COMMA);case`:`:return this.token(this.pos++,f.COLON);case`?`:return this.token(this.pos++,f.QUESTION);case`"`:case`'`:return this.readString(r);case`b`:case`B`:case`r`:case`R`:{let n=t[e+1];return n===`"`||n===`'`?++this.pos&&this.readString(n,r):this.readIdentifier()}default:{let e=r.charCodeAt(0);if(e<=57&&e>=48)return this.readNumber();if(this._isIdentifierCharCode(e))return this.readIdentifier()}}throw s(`unexpected_character`,`Unexpected character: ${r}`,{pos:e,start:e,end:e+1,input:t})}}_isIdentifierCharCode(e){return e<48||e>122?!1:e>=97||e>=65&&e<=90||e<=57||e===95}_parseAsDouble(e,t){let n=Number(this.input.substring(e,t));if(Number.isFinite(n))return this.token(e,f.NUMBER,n);throw s(`invalid_number`,`Invalid number: ${n}`,{pos:e,start:e,end:t,input:this.input})}_parseAsBigInt(e,t,n,r){let i=this.input.substring(e,t);if(r===`u`||r===`U`){this.pos++;try{return this.token(e,f.NUMBER,new ge(i))}catch{}}else try{return this.token(e,f.NUMBER,BigInt(i))}catch{}throw s(n?`invalid_hex_integer`:`invalid_integer`,n?`Invalid hex integer: ${i}`:`Invalid integer: ${i}`,{pos:e,start:e,end:this.pos,input:this.input})}_readDigits(e,t,n,r){for(;n<t&&(r=e.charCodeAt(n))&&!(r>57||r<48);)n++;return n}_readExponent(e,t,n){let r=n<t&&e[n];if(r===`e`||r===`E`){r=++n<t&&e[n],(r===`-`||r===`+`)&&n++;let i=n;if(n=this._readDigits(e,t,n),i===n)throw s(`invalid_exponent`,`Invalid exponent`,{pos:n,start:n,end:Math.min(n+1,e.length),input:e})}return n}readNumber(){let{input:e,length:t,pos:n}=this,r=n;if(e[r]===`0`&&(e[r+1]===`x`||e[r+1]===`X`)){for(r+=2;r<t&&fn[e[r].charCodeAt(0)];)r++;return this._parseAsBigInt(n,this.pos=r,!0,e[r])}if(r=this._readDigits(e,t,r),r+1<t){let i=!1,a=e[r]===`.`?this._readDigits(e,t,r+1):r+1;if(a!==r+1&&(i=!0)&&(r=a),a=this._readExponent(e,t,r),a!==r&&(i=!0)&&(r=a),i)return this._parseAsDouble(n,this.pos=r)}return this._parseAsBigInt(n,this.pos=r,!1,e[r])}readString(e,t){let{input:n,pos:r}=this;return n[r+1]===e&&n[r+2]===e?this.readTripleQuotedString(e,t):this.readSingleQuotedString(e,t)}_closeQuotedString(e,t,n,r){switch(n){case`b`:case`B`:{let n=this.processEscapes(e,t,!0),i=new Uint8Array(n.length);for(let e=0;e<n.length;e++)i[e]=n.charCodeAt(e)&255;return this.token(r-1,f.BYTES,i)}case`r`:case`R`:return this.token(r-1,f.STRING,t);default:{let n=this.processEscapes(e,t,!1);return this.token(r,f.STRING,n)}}}readSingleQuotedString(e,t){let{input:n,length:r,pos:i}=this,a,o=this.pos+1;for(;o<r&&(a=n[o]);){switch(a){case e:let r=i+1,a=n.slice(r,o);return this.pos=++o,this._closeQuotedString(r,a,t,i);case`
|
|
8
|
+
`:case`\r`:throw s(`newline_in_string`,`Newlines not allowed in single-quoted strings`,{pos:o,start:o,end:o+1,input:n});case`\\`:o++}o++}throw s(`unterminated_string`,`Unterminated string`,{pos:i,start:i,end:n.length,input:n})}readTripleQuotedString(e,t){let{input:n,length:r,pos:i}=this,a,o=this.pos+3;for(;o<r&&(a=n[o]);){switch(a){case e:if(n[o+1]===e&&n[o+2]===e){let e=i+3,r=n.slice(e,o);return this.pos=o+3,this._closeQuotedString(e,r,t,i)}break;case`\\`:o++}o++}throw s(`unterminated_triple_quoted_string`,`Unterminated triple-quoted string`,{pos:i,start:i,end:n.length,input:n})}#e(e,t,n,r,i,a){let o=t+r;return s(e,pn[e](a),{input:this.input,pos:o,start:o,end:Math.min(o+i,t+n)})}processEscapes(e,t,n){if(!t.includes(`\\`))return t;let r=t.length,i=``,a=0;for(;a<r;){if(t[a]!==`\\`||a+1>=r){i+=t[a++];continue}let o=t[a+1];if(mn[o])i+=mn[o],a+=2;else if(o===`u`||o===`U`){if(n)throw this.#e(`bytes_unicode_escape`,e,r,a,2,o);let s=o===`u`?4:8,c=t.substring(a+2,a+2+s),l=Number.parseInt(c,16);if(c.length!==s||!/^[0-9a-fA-F]+$/.test(c)||l>1114111)throw this.#e(`invalid_unicode_escape`,e,r,a,2+s,o+c);if(l>=55296&&l<=57343)throw this.#e(`invalid_unicode_surrogate`,e,r,a,2+s,o+c);i+=String.fromCodePoint(l),a+=2+s}else if(o===`x`||o===`X`){let n=t.substring(a+2,a+4);if(!/^[0-9a-fA-F]{2}$/.test(n))throw this.#e(`invalid_hex_escape`,e,r,a,4,o+n);i+=String.fromCharCode(Number.parseInt(n,16)),a+=4}else if(o>=`0`&&o<=`7`){let n=t.substring(a+1,a+4);if(!/^[0-7]{3}$/.test(n))throw this.#e(`invalid_octal_escape`,e,r,a,4);let o=Number.parseInt(n,8);if(o>255)throw this.#e(`octal_escape_out_of_range`,e,r,a,4,n);i+=String.fromCharCode(o),a+=4}else throw this.#e(`invalid_escape_sequence`,e,r,a,2,o)}return i}readIdentifier(){let{pos:e,input:t,length:n}=this,r=e;for(;r<n&&this._isIdentifierCharCode(t[r].charCodeAt(0));)r++;let i=t.substring(e,this.pos=r);switch(i){case`true`:return this.token(e,f.BOOLEAN,!0);case`false`:return this.token(e,f.BOOLEAN,!1);case`null`:return this.token(e,f.NULL,null);case`in`:return this.token(e,f.IN);default:return this.token(e,f.IDENTIFIER,i)}}},_n=class{lexer=gn;input=null;maxDepthRemaining=null;astNodesRemaining=null;type=null;pos=null;constructor(e,t){this.limits=e,this.registry=t}#e(e,t=this.pos){throw s(`limit_exceeded`,`Exceeded ${e} (${this.limits[e]})`,{pos:t,start:t,end:t,input:this.input})}#t(e,t,n,r,i=e){let a=new hn(this.input,i,e,t,n,r);return this.astNodesRemaining--||this.#e(`maxAstNodes`,i),a}#n(e,t,n){return this.#t(t.start,n.end,e,[t,n])}#r(e,t,n){return this.#t(e.start,n.end,d.ternary,[e,t,n])}#i(e,t,n){return this.#t(e,n.end,t,n)}#a(e,t,n,r,i=t.start){return this.#t(t.start,r,e,[t,n],i)}#o(e=this.pos){let t=this.lexer.nextToken();return this.pos=t.tokenPos,this.type=t.tokenType,e}get value(){return this.lexer.tokenValue}consume(e){if(this.type===e)return this.#o();throw s(`expected_token`,`Expected ${dn[e]}, got ${dn[this.type]}`,{pos:this.pos,start:this.pos,end:this.lexer.pos,input:this.input})}match(e){return this.type===e}parse(e){if(typeof e!=`string`)throw s(`expression_must_be_string`,`Expression must be a string`);this.input=this.lexer.reset(e),this.#o(),this.maxDepthRemaining=this.limits.maxDepth,this.astNodesRemaining=this.limits.maxAstNodes;let t=this.parseExpression();if(this.match(f.EOF))return t;throw s(`unexpected_character`,`Unexpected character: '${this.input[this.lexer.pos-1]}'`,{pos:this.pos,start:this.pos,end:this.lexer.pos,input:this.input})}#s(e,t,n,r){let i=r[0],a=n===d.rcall?r[1]:null,o=n===d.rcall?r[2]:r[1],s=this.registry.findMacro(i,!!a,o.length),c=this.#t(e,t,n,r);if(!s)return c;let l=s.handler({ast:c,args:o,receiver:a,methodName:i,parser:this});return l.callAst?c.setMeta(`alternate`,l.callAst):c.setMeta(`macro`,l).setMeta(`async`,me(l.evaluate,l.async))}parseExpression(){this.maxDepthRemaining--||this.#e(`maxDepth`);let e=this.parseLogicalOr();if(!this.match(f.QUESTION))return++this.maxDepthRemaining&&e;this.#o();let t=this.parseExpression();this.consume(f.COLON);let n=this.parseExpression();return this.maxDepthRemaining++,this.#r(e,t,n)}parseLogicalOr(){let e=this.parseLogicalAnd();for(;this.match(f.OR);)this.#o(),e=this.#n(d[`||`],e,this.parseLogicalAnd());return e}parseLogicalAnd(){let e=this.parseEquality();for(;this.match(f.AND);)this.#o(),e=this.#n(d[`&&`],e,this.parseEquality());return e}parseEquality(){let e=this.parseRelational();for(;this.match(f.EQ)||this.match(f.NE);){let t=un[this.type];this.#o(),e=this.#n(t,e,this.parseRelational())}return e}parseRelational(){let e=this.parseAdditive();for(;this.match(f.LT)||this.match(f.LE)||this.match(f.GT)||this.match(f.GE)||this.match(f.IN);){let t=un[this.type];this.#o(),e=this.#n(t,e,this.parseAdditive())}return e}parseAdditive(){let e=this.parseMultiplicative();for(;this.match(f.PLUS)||this.match(f.MINUS);){let t=un[this.type];this.#o(),e=this.#n(t,e,this.parseMultiplicative())}return e}parseMultiplicative(){let e=this.parseUnary();for(;this.match(f.MULTIPLY)||this.match(f.DIVIDE)||this.match(f.MODULO);){let t=un[this.type];this.#o(),e=this.#n(t,e,this.parseUnary())}return e}parseUnary(){return this.type===f.NOT?this.#i(this.#o(),d.unaryNot,this.parseUnary()):this.type===f.MINUS?this.#i(this.#o(),d.unaryMinus,this.parseUnary()):this.parsePostfix()}parsePostfix(){let e=this.parsePrimary(),t=this.maxDepthRemaining;for(;;){if(this.match(f.DOT)){let t=this.#o();this.maxDepthRemaining--||this.#e(`maxDepth`,t);let n=this.match(f.QUESTION)&&this.registry.enableOptionalTypes&&this.#o()?d.optionalFieldAccess:d.fieldAccess,r=this.value,i=this.pos,a=this.lexer.pos;if(this.consume(f.IDENTIFIER),n===d.fieldAccess&&this.match(f.LPAREN)&&this.#o()){let t=this.parseArgumentList(),n=this.lexer.pos;this.consume(f.RPAREN),e=this.#s(e.start,n,d.rcall,[r,e,t])}else e=this.#a(n,e,r,a,i);continue}if(this.match(f.LBRACKET)){let t=this.#o();this.maxDepthRemaining--||this.#e(`maxDepth`,t);let n=this.match(f.QUESTION)&&this.registry.enableOptionalTypes&&this.#o()?d.optionalBracketAccess:d.bracketAccess,r=this.parseExpression(),i=this.lexer.pos;this.consume(f.RBRACKET),e=this.#a(n,e,r,i);continue}break}return this.maxDepthRemaining=t,e}parsePrimary(){switch(this.type){case f.NUMBER:case f.STRING:case f.BYTES:case f.BOOLEAN:case f.NULL:return this.#c();case f.IDENTIFIER:return this.#l();case f.LPAREN:return this.#u();case f.LBRACKET:return this.parseList();case f.LBRACE:return this.parseMap()}throw s(`unexpected_token`,`Unexpected token: ${dn[this.type]}`,{pos:this.pos,start:this.pos,end:this.lexer.pos,input:this.input})}#c(){return this.#o(this.#t(this.pos,this.lexer.pos,d.value,this.value))}#l(){let e=this.value,t=this.lexer.pos,n=this.consume(f.IDENTIFIER);if(he.has(e))throw s(`reserved_identifier`,`Reserved identifier: ${e}`,{pos:n,start:n,end:t,input:this.input});if(!this.match(f.LPAREN))return this.#t(n,t,d.id,e);this.#o();let r=this.parseArgumentList(),i=this.lexer.pos;return this.consume(f.RPAREN),this.#s(n,i,d.call,[e,r])}#u(){this.consume(f.LPAREN);let e=this.parseExpression();return this.consume(f.RPAREN),e}parseList(){let e=this.consume(f.LBRACKET),t=[],n=this.limits.maxListElements;if(!this.match(f.RBRACKET))for(t.push(this.parseExpression()),n--||this.#e(`maxListElements`,t.at(-1).pos);this.match(f.COMMA)&&(this.#o(),!this.match(f.RBRACKET));)t.push(this.parseExpression()),n--||this.#e(`maxListElements`,t.at(-1).pos);let r=this.lexer.pos;return this.consume(f.RBRACKET),this.#t(e,r,d.list,t)}parseMap(){let e=this.consume(f.LBRACE),t=[],n=this.limits.maxMapEntries;if(!this.match(f.RBRACE))for(t.push(this.parseProperty()),n--||this.#e(`maxMapEntries`,t.at(-1)[0].pos);this.match(f.COMMA)&&(this.#o(),!this.match(f.RBRACE));)t.push(this.parseProperty()),n--||this.#e(`maxMapEntries`,t.at(-1)[0].pos);let r=this.lexer.pos;return this.consume(f.RBRACE),this.#t(e,r,d.map,t)}parseProperty(){return[this.parseExpression(),(this.consume(f.COLON),this.parseExpression())]}parseArgumentList(){let e=[],t=this.limits.maxCallArguments;if(!this.match(f.RPAREN))for(e.push(this.parseExpression()),t--||this.#e(`maxCallArguments`,e.at(-1).pos);this.match(f.COMMA)&&(this.#o(),!this.match(f.RPAREN));)e.push(this.parseExpression()),t--||this.#e(`maxCallArguments`,e.at(-1).pos);return e}},vn=ue({maxAstNodes:1e5,maxDepth:250,maxListElements:1e3,maxMapEntries:1e3,maxCallArguments:32}),yn=new Set(le(vn));function bn(e,t=vn){let n=e?le(e):void 0;if(!n?.length)return t;let r={...t};for(let t of n){if(!yn.has(t))throw TypeError(`Unknown limits option: ${t}`);let n=e[t];typeof n==`number`&&(r[t]=n)}return ue(r)}var xn=ue({unlistedVariablesAreDyn:!1,homogeneousAggregateLiterals:!0,enableOptionalTypes:!1,limits:vn});function Sn(e,t,n){let r=e?.[n]??t?.[n];if(typeof r!=`boolean`)throw TypeError(`Invalid option: ${n}`);return r}function Cn(e,t=xn){return e?ue({unlistedVariablesAreDyn:Sn(e,t,`unlistedVariablesAreDyn`),homogeneousAggregateLiterals:Sn(e,t,`homogeneousAggregateLiterals`),enableOptionalTypes:Sn(e,t,`enableOptionalTypes`),limits:bn(e.limits,t.limits)}):t}var wn=nt({enableOptionalTypes:!1});xe(wn),on(wn),an(wn);var Tn=class e{#e;#t;#n;#r;#i;constructor(t,n){this.opts=Cn(t,n?.opts),this.#e=(n instanceof e?n.#e:wn).clone(this.opts);let r={registry:this.#e,opts:this.opts};this.#n=new ln(r),this.#r=new ln(r,!0),this.#t=new En(r),this.#i=new _n(this.opts.limits,this.#e),Object.freeze(this)}clone(t){return new e(t,this)}registerFunction(e,t,n){return this.#e.registerFunctionOverload(e,t,n),this}registerOperator(e,t,n){return this.#e.registerOperatorOverload(e,t,n),this}registerType(e,t){return this.#e.registerType(e,t),this}registerVariable(e,t,n){return this.#e.registerVariable(e,t,n),this}registerConstant(e,t,n){return this.#e.registerConstant(e,t,n),this}hasVariable(e){return this.#e.variables.has(e)}getDefinitions(){return this.#e.getDefinitions()}check(e){try{return this.#a(this.#i.parse(e))}catch(e){return{valid:!1,error:e}}}#a(e){try{let t=this.#n.check(e,new rt(this.#e));return{valid:!0,type:this.#o(t)}}catch(e){return{valid:!1,error:e}}}#o(e){return e.name===`list<dyn>`?`list`:e.name===`map<dyn, dyn>`?`map`:e.name}parse(e){let t=this.#i.parse(e),n=this.#s.bind(this,t);return n.check=this.#a.bind(this,t),n.ast=t,n}evaluate(e,t){return this.#s(this.#i.parse(e),t)}#s(e,t){return e.checkedType?e.evaluate(this.#t,e,new rt(this.#e,t)):(this.#r.check(e,t=new rt(this.#e,t)),e.evaluate(this.#t,e,t))}},En=class extends ct{constructor(e){super(e),this.createError=c}#e(e){if(e instanceof Map)return e.entries().next().value;for(let t in e)return[t,e[t]]}debugRuntimeType(e,t){return t?.hasDynType===!1?t:this.debugTypeDeep(e)}debugTypeDeep(e){let t=this.debugType(e);switch(t.kind){case`list`:{let n=e instanceof Array?e[0]:e.values().next().value;return n===void 0?t:this.registry.getListType(this.debugTypeDeep(n))}case`map`:{let n=this.#e(e);return n?this.registry.getMapType(t.keyType.hasDynType?this.debugTypeDeep(n[0]):t.keyType,t.valueType.hasDynType?this.debugTypeDeep(n[1]):t.valueType):t}default:return t}}tryEval(e,t){try{let n=this.eval(e,t);return n instanceof Promise?n.catch(e=>e):n}catch(e){return e}}eval(e,t){return e.evaluate(this,e,t)}};new Tn({unlistedVariablesAreDyn:!0});var Dn;function p(e,t,n){function r(n,r){if(n._zod||Object.defineProperty(n,"_zod",{value:{def:r,constr:o,traits:new Set},enumerable:!1}),n._zod.traits.has(e))return;n._zod.traits.add(e),t(n,r);let i=o.prototype,a=Object.keys(i);for(let e=0;e<a.length;e++){let t=a[e];t in n||(n[t]=i[t].bind(n))}}let i=n?.Parent??Object;class a extends i{}Object.defineProperty(a,"name",{value:e});function o(e){var t;let i=n?.Parent?new a:this;r(i,e),(t=i._zod).deferred??(t.deferred=[]);for(let e of i._zod.deferred)e();return i}return Object.defineProperty(o,"init",{value:r}),Object.defineProperty(o,Symbol.hasInstance,{value:t=>n?.Parent&&t instanceof n.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(o,"name",{value:e}),o}var On=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},kn=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};(Dn=globalThis).__zod_globalConfig??(Dn.__zod_globalConfig={});var An=globalThis.__zod_globalConfig;function jn(e){return e&&Object.assign(An,e),An}function Mn(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function Nn(e,t){return typeof t==`bigint`?t.toString():t}function Pn(e){return{get value(){{let t=e();return Object.defineProperty(this,"value",{value:t}),t}throw Error(`cached value already set`)}}}function Fn(e){return e==null}function In(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function Ln(e,t){let n=e/t,r=Math.round(n),i=2**-52*Math.max(Math.abs(n),1);return Math.abs(n-r)<i?0:n-r}var Rn=Symbol(`evaluating`);function m(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==Rn)return r===void 0&&(r=Rn,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function zn(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Bn(...e){let t={};for(let n of e)Object.assign(t,Object.getOwnPropertyDescriptors(n));return Object.defineProperties({},t)}function Vn(e){return JSON.stringify(e)}function Hn(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,``).replace(/[\s_-]+/g,`-`).replace(/^-+|-+$/g,``)}var Un=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function Wn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Gn=Pn(()=>{if(An.jitless||typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function Kn(e){if(Wn(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return!(Wn(n)===!1||Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)===!1)}function qn(e){return Kn(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}var Jn=new Set([`string`,`number`,`symbol`]);function Yn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Xn(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function h(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function Zn(e){return Object.keys(e).filter(t=>e[t]._zod.optin===`optional`&&e[t]._zod.optout===`optional`)}var Qn={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function $n(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.pick() cannot be used on object schemas containing refinements`);return Xn(e,Bn(e._zod.def,{get shape(){let e={};for(let r in t){if(!(r in n.shape))throw Error(`Unrecognized key: "${r}"`);t[r]&&(e[r]=n.shape[r])}return zn(this,`shape`,e),e},checks:[]}))}function er(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.omit() cannot be used on object schemas containing refinements`);return Xn(e,Bn(e._zod.def,{get shape(){let r={...e._zod.def.shape};for(let e in t){if(!(e in n.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return zn(this,`shape`,r),r},checks:[]}))}function tr(e,t){if(!Kn(t))throw Error(`Invalid input to extend: expected a plain object`);let n=e._zod.def.checks;if(n&&n.length>0){let n=e._zod.def.shape;for(let e in t)if(Object.getOwnPropertyDescriptor(n,e)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return Xn(e,Bn(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return zn(this,`shape`,n),n}}))}function nr(e,t){if(!Kn(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return Xn(e,Bn(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return zn(this,`shape`,n),n}}))}function rr(e,t){if(e._zod.def.checks?.length)throw Error(`.merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.`);return Xn(e,Bn(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return zn(this,`shape`,n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))}function ir(e,t,n){let r=t._zod.def.checks;if(r&&r.length>0)throw Error(`.partial() cannot be used on object schemas containing refinements`);return Xn(t,Bn(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in r))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t])}else for(let t in r)i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t];return zn(this,`shape`,i),i},checks:[]}))}function ar(e,t,n){return Xn(t,Bn(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in i))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=new e({type:`nonoptional`,innerType:r[t]}))}else for(let t in r)i[t]=new e({type:`nonoptional`,innerType:r[t]});return zn(this,`shape`,i),i}}))}function or(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function sr(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function cr(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function lr(e){return typeof e==`string`?e:e?.message}function ur(e,t,n){let r=e.message?e.message:lr(e.inst?._zod.def?.error?.(e))??lr(t?.error?.(e))??lr(n.customError?.(e))??lr(n.localeError?.(e))??`Invalid input`,{inst:i,continue:a,input:o,...s}=e;return s.path??=[],s.message=r,t?.reportInput&&(s.input=o),s}function dr(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function fr(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}var pr=(e,t)=>{e.name=`$ZodError`,Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,Nn,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},mr=p(`$ZodError`,pr),hr=p(`$ZodError`,pr,{Parent:Error});function gr(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function _r(e,t=e=>e.message){let n={_errors:[]},r=(e,i=[])=>{for(let a of e.issues)if(a.code===`invalid_union`&&a.errors.length)a.errors.map(e=>r({issues:e},[...i,...a.path]));else if(a.code===`invalid_key`)r({issues:a.issues},[...i,...a.path]);else if(a.code===`invalid_element`)r({issues:a.issues},[...i,...a.path]);else{let e=[...i,...a.path];if(e.length===0)n._errors.push(t(a));else{let r=n,i=0;for(;i<e.length;){let n=e[i];i===e.length-1?(r[n]=r[n]||{_errors:[]},r[n]._errors.push(t(a))):r[n]=r[n]||{_errors:[]},r=r[n],i++}}}};return r(e),n}var vr=e=>(t,n,r,i)=>{let a=r?{...r,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new On;if(o.issues.length){let t=new(i?.Err??e)(o.issues.map(e=>ur(e,a,jn())));throw Un(t,i?.callee),t}return o.value},yr=vr(hr),br=e=>async(t,n,r,i)=>{let a=r?{...r,async:!0}:{async:!0},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){let t=new(i?.Err??e)(o.issues.map(e=>ur(e,a,jn())));throw Un(t,i?.callee),t}return o.value},xr=br(hr),Sr=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new On;return a.issues.length?{success:!1,error:new(e??mr)(a.issues.map(e=>ur(e,i,jn())))}:{success:!0,data:a.value}},Cr=Sr(hr),wr=e=>async(t,n,r)=>{let i=r?{...r,async:!0}:{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(e=>ur(e,i,jn())))}:{success:!0,data:a.value}},Tr=wr(hr),Er=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return vr(e)(t,n,i)},Dr=e=>(t,n,r)=>vr(e)(t,n,r),Or=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return br(e)(t,n,i)},kr=e=>async(t,n,r)=>br(e)(t,n,r),Ar=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Sr(e)(t,n,i)},jr=e=>(t,n,r)=>Sr(e)(t,n,r),Mr=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return wr(e)(t,n,i)},Nr=e=>async(t,n,r)=>wr(e)(t,n,r),Pr=/^[cC][0-9a-z]{6,}$/,Fr=/^[0-9a-z]+$/,Ir=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Lr=/^[0-9a-vA-V]{20}$/,Rr=/^[A-Za-z0-9]{27}$/,zr=/^[a-zA-Z0-9_-]{21}$/,Br=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Vr=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Hr=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,Ur=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Wr=`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;function Gr(){return new RegExp(Wr,`u`)}var Kr=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,qr=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,Jr=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Yr=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Xr=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Zr=/^[A-Za-z0-9_-]*$/,Qr=/^https?$/,$r=/^\+[1-9]\d{6,14}$/,ei=`(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`,ti=RegExp(`^${ei}$`);function ni(e){let t=`(?:[01]\\d|2[0-3]):[0-5]\\d`;return typeof e.precision==`number`?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function ri(e){return RegExp(`^${ni(e)}$`)}function ii(e){let t=ni({precision:e.precision}),n=[`Z`];e.local&&n.push(``),e.offset&&n.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);let r=`${t}(?:${n.join(`|`)})`;return RegExp(`^${ei}T(?:${r})$`)}var ai=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},oi=/^-?\d+n?$/,si=/^-?\d+$/,ci=/^-?\d+(?:\.\d+)?$/,li=/^(?:true|false)$/i,ui=/^null$/i,di=/^[^A-Z]*$/,fi=/^[^a-z]*$/,pi=p(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),mi={number:`number`,bigint:`bigint`,object:`date`},hi=p(`$ZodCheckLessThan`,(e,t)=>{pi.init(e,t);let n=mi[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??1/0;t.value<r&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:`too_big`,maximum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),gi=p(`$ZodCheckGreaterThan`,(e,t)=>{pi.init(e,t);let n=mi[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??-1/0;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:`too_small`,minimum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),_i=p(`$ZodCheckMultipleOf`,(e,t)=>{pi.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw Error(`Cannot mix number and bigint in multiple_of check.`);(typeof n.value==`bigint`?n.value%t.value===BigInt(0):Ln(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:`not_multiple_of`,divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),vi=p(`$ZodCheckNumberFormat`,(e,t)=>{pi.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=Qn[t.format];e._zod.onattach.push(e=>{let r=e._zod.bag;r.format=t.format,r.minimum=i,r.maximum=a,n&&(r.pattern=si)}),e._zod.check=o=>{let s=o.value;if(n){if(!Number.isInteger(s)){o.issues.push({expected:r,format:t.format,code:`invalid_type`,continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,code:`too_big`,maximum:2**53-1,note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort}):o.issues.push({input:s,code:`too_small`,minimum:-(2**53-1),note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}s<i&&o.issues.push({origin:`number`,input:s,code:`too_small`,minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>a&&o.issues.push({origin:`number`,input:s,code:`too_big`,maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),yi=p(`$ZodCheckMaxLength`,(e,t)=>{var n;pi.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!Fn(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.maximum??1/0;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let r=n.value;if(r.length<=t.maximum)return;let i=dr(r);n.issues.push({origin:i,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),bi=p(`$ZodCheckMinLength`,(e,t)=>{var n;pi.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!Fn(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.minimum??-1/0;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let r=n.value;if(r.length>=t.minimum)return;let i=dr(r);n.issues.push({origin:i,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),xi=p(`$ZodCheckLengthEquals`,(e,t)=>{var n;pi.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!Fn(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{let r=n.value,i=r.length;if(i===t.length)return;let a=dr(r),o=i>t.length;n.issues.push({origin:a,...o?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Si=p(`$ZodCheckStringFormat`,(e,t)=>{var n,r;pi.init(e,t),e._zod.onattach.push(e=>{let n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??=new Set,n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),Ci=p(`$ZodCheckRegex`,(e,t)=>{Si.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),wi=p(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=di,Si.init(e,t)}),Ti=p(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=fi,Si.init(e,t)}),Ei=p(`$ZodCheckIncludes`,(e,t)=>{pi.init(e,t);let n=Yn(t.includes),r=new RegExp(typeof t.position==`number`?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),Di=p(`$ZodCheckStartsWith`,(e,t)=>{pi.init(e,t);let n=RegExp(`^${Yn(t.prefix)}.*`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Oi=p(`$ZodCheckEndsWith`,(e,t)=>{pi.init(e,t);let n=RegExp(`.*${Yn(t.suffix)}$`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),ki=p(`$ZodCheckOverwrite`,(e,t)=>{pi.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}}),Ai=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),--this.indent}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(`
|
|
9
|
+
`).filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>` `.repeat(this.indent*2)+e);for(let e of r)this.content.push(e)}compile(){let e=Function,t=this?.args,n=[...(this?.content??[``]).map(e=>` ${e}`)];return new e(...t,n.join(`
|
|
10
|
+
`))}},ji={major:4,minor:4,patch:3},g=p(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=ji;let r=[...e._zod.def.checks??[]];e._zod.traits.has(`$ZodCheck`)&&r.unshift(e);for(let t of r)for(let n of t._zod.onattach)n(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(e,t,n)=>{let r=or(e),i;for(let a of t){if(a._zod.def.when){if(sr(e)||!a._zod.def.when(e))continue}else if(r)continue;let t=e.issues.length,o=a._zod.check(e);if(o instanceof Promise&&n?.async===!1)throw new On;if(i||o instanceof Promise)i=(i??Promise.resolve()).then(async()=>{await o,e.issues.length!==t&&(r||=or(e,t))});else{if(e.issues.length===t)continue;r||=or(e,t)}}return i?i.then(()=>e):e},n=(n,i,a)=>{if(or(n))return n.aborted=!0,n;let o=t(i,r,a);if(o instanceof Promise){if(a.async===!1)throw new On;return o.then(t=>e._zod.parse(t,a))}return e._zod.parse(o,a)};e._zod.run=(i,a)=>{if(a.skipChecks)return e._zod.parse(i,a);if(a.direction===`backward`){let t=e._zod.parse({value:i.value,issues:[]},{...a,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,i,a)):n(t,i,a)}let o=e._zod.parse(i,a);if(o instanceof Promise){if(a.async===!1)throw new On;return o.then(e=>t(e,r,a))}return t(o,r,a)}}m(e,`~standard`,()=>({validate:t=>{try{let n=Cr(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch{return Tr(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:`zod`,version:1}))}),Mi=p(`$ZodString`,(e,t)=>{g.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??ai(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value==`string`||n.issues.push({expected:`string`,code:`invalid_type`,input:n.value,inst:e}),n}}),Ni=p(`$ZodStringFormat`,(e,t)=>{Si.init(e,t),Mi.init(e,t)}),Pi=p(`$ZodGUID`,(e,t)=>{t.pattern??=Vr,Ni.init(e,t)}),Fi=p(`$ZodUUID`,(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(e===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??=Hr(e)}else t.pattern??=Hr();Ni.init(e,t)}),Ii=p(`$ZodEmail`,(e,t)=>{t.pattern??=Ur,Ni.init(e,t)}),Li=p(`$ZodURL`,(e,t)=>{Ni.init(e,t),e._zod.check=n=>{try{let r=n.value.trim();if(!t.normalize&&t.protocol?.source===Qr.source&&!/^https?:\/\//i.test(r)){n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid URL format`,input:n.value,inst:e,continue:!t.abort});return}let i=new URL(r);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid hostname`,pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(`:`)?i.protocol.slice(0,-1):i.protocol)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid protocol`,pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),t.normalize?n.value=i.href:n.value=r;return}catch{n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort})}}}),Ri=p(`$ZodEmoji`,(e,t)=>{t.pattern??=Gr(),Ni.init(e,t)}),zi=p(`$ZodNanoID`,(e,t)=>{t.pattern??=zr,Ni.init(e,t)}),Bi=p(`$ZodCUID`,(e,t)=>{t.pattern??=Pr,Ni.init(e,t)}),Vi=p(`$ZodCUID2`,(e,t)=>{t.pattern??=Fr,Ni.init(e,t)}),Hi=p(`$ZodULID`,(e,t)=>{t.pattern??=Ir,Ni.init(e,t)}),Ui=p(`$ZodXID`,(e,t)=>{t.pattern??=Lr,Ni.init(e,t)}),Wi=p(`$ZodKSUID`,(e,t)=>{t.pattern??=Rr,Ni.init(e,t)}),Gi=p(`$ZodISODateTime`,(e,t)=>{t.pattern??=ii(t),Ni.init(e,t)}),Ki=p(`$ZodISODate`,(e,t)=>{t.pattern??=ti,Ni.init(e,t)}),qi=p(`$ZodISOTime`,(e,t)=>{t.pattern??=ri(t),Ni.init(e,t)}),Ji=p(`$ZodISODuration`,(e,t)=>{t.pattern??=Br,Ni.init(e,t)}),Yi=p(`$ZodIPv4`,(e,t)=>{t.pattern??=Kr,Ni.init(e,t),e._zod.bag.format=`ipv4`}),Xi=p(`$ZodIPv6`,(e,t)=>{t.pattern??=qr,Ni.init(e,t),e._zod.bag.format=`ipv6`,e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:`invalid_format`,format:`ipv6`,input:n.value,inst:e,continue:!t.abort})}}}),Zi=p(`$ZodCIDRv4`,(e,t)=>{t.pattern??=Jr,Ni.init(e,t)}),Qi=p(`$ZodCIDRv6`,(e,t)=>{t.pattern??=Yr,Ni.init(e,t),e._zod.check=n=>{let r=n.value.split(`/`);try{if(r.length!==2)throw Error();let[e,t]=r;if(!t)throw Error();let n=Number(t);if(`${n}`!==t||n<0||n>128)throw Error();new URL(`http://[${e}]`)}catch{n.issues.push({code:`invalid_format`,format:`cidrv6`,input:n.value,inst:e,continue:!t.abort})}}});function $i(e){if(e===``)return!0;if(/\s/.test(e)||e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}var ea=p(`$ZodBase64`,(e,t)=>{t.pattern??=Xr,Ni.init(e,t),e._zod.bag.contentEncoding=`base64`,e._zod.check=n=>{$i(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}});function ta(e){if(!Zr.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return $i(t.padEnd(Math.ceil(t.length/4)*4,`=`))}var na=p(`$ZodBase64URL`,(e,t)=>{t.pattern??=Zr,Ni.init(e,t),e._zod.bag.contentEncoding=`base64url`,e._zod.check=n=>{ta(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),ra=p(`$ZodE164`,(e,t)=>{t.pattern??=$r,Ni.init(e,t)});function ia(e,t=null){try{let n=e.split(`.`);if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let i=JSON.parse(atob(r));return!(`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&(!(`alg`in i)||i.alg!==t))}catch{return!1}}var aa=p(`$ZodJWT`,(e,t)=>{Ni.init(e,t),e._zod.check=n=>{ia(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),oa=p(`$ZodNumber`,(e,t)=>{g.init(e,t),e._zod.pattern=e._zod.bag.pattern??ci,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let i=n.value;if(typeof i==`number`&&!Number.isNaN(i)&&Number.isFinite(i))return n;let a=typeof i==`number`?Number.isNaN(i)?`NaN`:Number.isFinite(i)?void 0:`Infinity`:void 0;return n.issues.push({expected:`number`,code:`invalid_type`,input:i,inst:e,...a?{received:a}:{}}),n}}),sa=p(`$ZodNumberFormat`,(e,t)=>{vi.init(e,t),oa.init(e,t)}),ca=p(`$ZodBoolean`,(e,t)=>{g.init(e,t),e._zod.pattern=li,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}let i=n.value;return typeof i==`boolean`||n.issues.push({expected:`boolean`,code:`invalid_type`,input:i,inst:e}),n}}),la=p(`$ZodBigInt`,(e,t)=>{g.init(e,t),e._zod.pattern=oi,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=BigInt(n.value)}catch{}return typeof n.value==`bigint`||n.issues.push({expected:`bigint`,code:`invalid_type`,input:n.value,inst:e}),n}}),ua=p(`$ZodNull`,(e,t)=>{g.init(e,t),e._zod.pattern=ui,e._zod.values=new Set([null]),e._zod.parse=(t,n)=>{let r=t.value;return r===null||t.issues.push({expected:`null`,code:`invalid_type`,input:r,inst:e}),t}}),da=p(`$ZodAny`,(e,t)=>{g.init(e,t),e._zod.parse=e=>e}),fa=p(`$ZodUnknown`,(e,t)=>{g.init(e,t),e._zod.parse=e=>e}),pa=p(`$ZodNever`,(e,t)=>{g.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)}),ma=p(`$ZodVoid`,(e,t)=>{g.init(e,t),e._zod.parse=(t,n)=>{let r=t.value;return r===void 0||t.issues.push({expected:`void`,code:`invalid_type`,input:r,inst:e}),t}}),ha=p(`$ZodDate`,(e,t)=>{g.init(e,t),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=new Date(n.value)}catch{}let i=n.value,a=i instanceof Date;return a&&!Number.isNaN(i.getTime())||n.issues.push({expected:`date`,code:`invalid_type`,input:i,...a?{received:`Invalid Date`}:{},inst:e}),n}});function ga(e,t,n){e.issues.length&&t.issues.push(...cr(n,e.issues)),t.value[n]=e.value}var _a=p(`$ZodArray`,(e,t)=>{g.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!Array.isArray(i))return n.issues.push({expected:`array`,code:`invalid_type`,input:i,inst:e}),n;n.value=Array(i.length);let a=[];for(let e=0;e<i.length;e++){let o=i[e],s=t.element._zod.run({value:o,issues:[]},r);s instanceof Promise?a.push(s.then(t=>ga(t,n,e))):ga(s,n,e)}return a.length?Promise.all(a).then(()=>n):n}});function va(e,t,n,r,i,a){let o=n in r;if(e.issues.length){if(i&&a&&!o)return;t.issues.push(...cr(n,e.issues))}if(!o&&!i){e.issues.length||t.issues.push({code:`invalid_type`,expected:`nonoptional`,input:void 0,path:[n]});return}e.value===void 0?o&&(t.value[n]=void 0):t.value[n]=e.value}function ya(e){let t=Object.keys(e.shape);for(let n of t)if(!e.shape?.[n]?._zod?.traits?.has(`$ZodType`))throw Error(`Invalid element at key "${n}": expected a Zod schema`);let n=Zn(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function ba(e,t,n,r,i,a){let o=[],s=i.keySet,c=i.catchall._zod,l=c.def.type,u=c.optin===`optional`,ee=c.optout===`optional`;for(let i in t){if(i===`__proto__`||s.has(i))continue;if(l===`never`){o.push(i);continue}let a=c.run({value:t[i],issues:[]},r);a instanceof Promise?e.push(a.then(e=>va(e,n,i,t,u,ee))):va(a,n,i,t,u,ee)}return o.length&&n.issues.push({code:`unrecognized_keys`,keys:o,input:t,inst:a}),e.length?Promise.all(e).then(()=>n):n}var xa=p(`$ZodObject`,(e,t)=>{if(g.init(e,t),!Object.getOwnPropertyDescriptor(t,`shape`)?.get){let e=t.shape;Object.defineProperty(t,"shape",{get:()=>{let n={...e};return Object.defineProperty(t,"shape",{value:n}),n}})}let n=Pn(()=>ya(t));m(e._zod,`propValues`,()=>{let e=t.shape,n={};for(let t in e){let r=e[t]._zod;if(r.values){n[t]??(n[t]=new Set);for(let e of r.values)n[t].add(e)}}return n});let r=Wn,i=t.catchall,a;e._zod.parse=(t,o)=>{a??=n.value;let s=t.value;if(!r(s))return t.issues.push({expected:`object`,code:`invalid_type`,input:s,inst:e}),t;t.value={};let c=[],l=a.shape;for(let e of a.keys){let n=l[e],r=n._zod.optin===`optional`,i=n._zod.optout===`optional`,a=n._zod.run({value:s[e],issues:[]},o);a instanceof Promise?c.push(a.then(n=>va(n,t,e,s,r,i))):va(a,t,e,s,r,i)}return i?ba(c,s,t,o,n.value,e):c.length?Promise.all(c).then(()=>t):t}}),Sa=p(`$ZodObjectJIT`,(e,t)=>{xa.init(e,t);let n=e._zod.parse,r=Pn(()=>ya(t)),i=e=>{let t=new Ai([`shape`,`payload`,`ctx`]),n=r.value,i=e=>{let t=Vn(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write(`const input = payload.value;`);let a=Object.create(null),o=0;for(let e of n.keys)a[e]=`key_${o++}`;t.write(`const newResult = {};`);for(let r of n.keys){let n=a[r],o=Vn(r),s=e[r],c=s?._zod?.optin===`optional`,l=s?._zod?.optout===`optional`;t.write(`const ${n} = ${i(r)};`),c&&l?t.write(`
|
|
11
|
+
if (${n}.issues.length) {
|
|
12
|
+
if (${o} in input) {
|
|
13
|
+
payload.issues = payload.issues.concat(${n}.issues.map(iss => ({
|
|
14
|
+
...iss,
|
|
15
|
+
path: iss.path ? [${o}, ...iss.path] : [${o}]
|
|
16
|
+
})));
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
if (${n}.value === undefined) {
|
|
21
|
+
if (${o} in input) {
|
|
22
|
+
newResult[${o}] = undefined;
|
|
23
|
+
}
|
|
24
|
+
} else {
|
|
25
|
+
newResult[${o}] = ${n}.value;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
`):c?t.write(`
|
|
29
|
+
if (${n}.issues.length) {
|
|
30
|
+
payload.issues = payload.issues.concat(${n}.issues.map(iss => ({
|
|
31
|
+
...iss,
|
|
32
|
+
path: iss.path ? [${o}, ...iss.path] : [${o}]
|
|
33
|
+
})));
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
if (${n}.value === undefined) {
|
|
37
|
+
if (${o} in input) {
|
|
38
|
+
newResult[${o}] = undefined;
|
|
39
|
+
}
|
|
40
|
+
} else {
|
|
41
|
+
newResult[${o}] = ${n}.value;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
`):t.write(`
|
|
45
|
+
const ${n}_present = ${o} in input;
|
|
46
|
+
if (${n}.issues.length) {
|
|
47
|
+
payload.issues = payload.issues.concat(${n}.issues.map(iss => ({
|
|
48
|
+
...iss,
|
|
49
|
+
path: iss.path ? [${o}, ...iss.path] : [${o}]
|
|
50
|
+
})));
|
|
51
|
+
}
|
|
52
|
+
if (!${n}_present && !${n}.issues.length) {
|
|
53
|
+
payload.issues.push({
|
|
54
|
+
code: "invalid_type",
|
|
55
|
+
expected: "nonoptional",
|
|
56
|
+
input: undefined,
|
|
57
|
+
path: [${o}]
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
if (${n}_present) {
|
|
62
|
+
if (${n}.value === undefined) {
|
|
63
|
+
newResult[${o}] = undefined;
|
|
64
|
+
} else {
|
|
65
|
+
newResult[${o}] = ${n}.value;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
`)}t.write(`payload.value = newResult;`),t.write(`return payload;`);let s=t.compile();return(t,n)=>s(e,t,n)},a,o=Wn,s=!An.jitless,c=s&&Gn.value,l=t.catchall,u;e._zod.parse=(ee,te)=>{u??=r.value;let ne=ee.value;return o(ne)?s&&c&&te?.async===!1&&te.jitless!==!0?(a||=i(t.shape),ee=a(ee,te),l?ba([],ne,ee,te,u,e):ee):n(ee,te):(ee.issues.push({expected:`object`,code:`invalid_type`,input:ne,inst:e}),ee)}});function Ca(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;let i=e.filter(e=>!or(e));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>ur(e,r,jn())))}),t)}var wa=p(`$ZodUnion`,(e,t)=>{g.init(e,t),m(e._zod,`optin`,()=>t.options.some(e=>e._zod.optin===`optional`)?`optional`:void 0),m(e._zod,`optout`,()=>t.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),m(e._zod,`values`,()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),m(e._zod,`pattern`,()=>{if(t.options.every(e=>e._zod.pattern)){let e=t.options.map(e=>e._zod.pattern);return RegExp(`^(${e.map(e=>In(e.source)).join(`|`)})$`)}});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let a=!1,o=[];for(let e of t.options){let t=e._zod.run({value:r.value,issues:[]},i);if(t instanceof Promise)o.push(t),a=!0;else{if(t.issues.length===0)return t;o.push(t)}}return a?Promise.all(o).then(t=>Ca(t,r,e,i)):Ca(o,r,e,i)}}),Ta=p(`$ZodDiscriminatedUnion`,(e,t)=>{t.inclusive=!1,wa.init(e,t);let n=e._zod.parse;m(e._zod,`propValues`,()=>{let e={};for(let n of t.options){let r=n._zod.propValues;if(!r||Object.keys(r).length===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(n)}"`);for(let[t,n]of Object.entries(r)){e[t]||(e[t]=new Set);for(let r of n)e[t].add(r)}}return e});let r=Pn(()=>{let e=t.options,n=new Map;for(let r of e){let e=r._zod.propValues?.[t.discriminator];if(!e||e.size===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(r)}"`);for(let t of e){if(n.has(t))throw Error(`Duplicate discriminator value "${String(t)}"`);n.set(t,r)}}return n});e._zod.parse=(i,a)=>{let o=i.value;if(!Wn(o))return i.issues.push({code:`invalid_type`,expected:`object`,input:o,inst:e}),i;let s=r.value.get(o?.[t.discriminator]);return s?s._zod.run(i,a):t.unionFallback||a.direction===`backward`?n(i,a):(i.issues.push({code:`invalid_union`,errors:[],note:`No matching discriminator`,discriminator:t.discriminator,options:Array.from(r.value.keys()),input:o,path:[t.discriminator],inst:e}),i)}}),Ea=p(`$ZodIntersection`,(e,t)=>{g.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>Oa(e,t,n)):Oa(e,i,a)}});function Da(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Kn(e)&&Kn(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=Da(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=Da(i,a);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Oa(e,t,n){let r=new Map,i;for(let n of t.issues)if(n.code===`unrecognized_keys`){i??=n;for(let e of n.keys)r.has(e)||r.set(e,{}),r.get(e).l=!0}else e.issues.push(n);for(let t of n.issues)if(t.code===`unrecognized_keys`)for(let e of t.keys)r.has(e)||r.set(e,{}),r.get(e).r=!0;else e.issues.push(t);let a=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(a.length&&i&&e.issues.push({...i,keys:a}),or(e))return e;let o=Da(t.value,n.value);if(!o.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return e.value=o.data,e}var ka=p(`$ZodTuple`,(e,t)=>{g.init(e,t);let n=t.items;e._zod.parse=(r,i)=>{let a=r.value;if(!Array.isArray(a))return r.issues.push({input:a,inst:e,expected:`tuple`,code:`invalid_type`}),r;r.value=[];let o=[],s=Aa(n,`optin`),c=Aa(n,`optout`);if(!t.rest){if(a.length<s)return r.issues.push({code:`too_small`,minimum:s,inclusive:!0,input:a,inst:e,origin:`array`}),r;a.length>n.length&&r.issues.push({code:`too_big`,maximum:n.length,inclusive:!0,input:a,inst:e,origin:`array`})}let l=Array(n.length);for(let e=0;e<n.length;e++){let t=n[e]._zod.run({value:a[e],issues:[]},i);t instanceof Promise?o.push(t.then(t=>{l[e]=t})):l[e]=t}if(t.rest){let e=n.length-1,s=a.slice(n.length);for(let n of s){e++;let a=t.rest._zod.run({value:n,issues:[]},i);a instanceof Promise?o.push(a.then(t=>ja(t,r,e))):ja(a,r,e)}}return o.length?Promise.all(o).then(()=>Ma(l,r,n,a,c)):Ma(l,r,n,a,c)}});function Aa(e,t){for(let n=e.length-1;n>=0;n--)if(e[n]._zod[t]!==`optional`)return n+1;return 0}function ja(e,t,n){e.issues.length&&t.issues.push(...cr(n,e.issues)),t.value[n]=e.value}function Ma(e,t,n,r,i){for(let a=0;a<n.length;a++){let n=e[a],o=a<r.length;if(n.issues.length){if(!o&&a>=i){t.value.length=a;break}t.issues.push(...cr(a,n.issues))}t.value[a]=n.value}for(let e=t.value.length-1;e>=r.length&&n[e]._zod.optout===`optional`&&t.value[e]===void 0;e--)t.value.length=e;return t}var Na=p(`$ZodRecord`,(e,t)=>{g.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!Kn(i))return n.issues.push({expected:`record`,code:`invalid_type`,input:i,inst:e}),n;let a=[],o=t.keyType._zod.values;if(o){n.value={};let s=new Set;for(let c of o)if(typeof c==`string`||typeof c==`number`||typeof c==`symbol`){s.add(typeof c==`number`?c.toString():c);let o=t.keyType._zod.run({value:c,issues:[]},r);if(o instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(o.issues.length){n.issues.push({code:`invalid_key`,origin:`record`,issues:o.issues.map(e=>ur(e,r,jn())),input:c,path:[c],inst:e});continue}let l=o.value,u=t.valueType._zod.run({value:i[c],issues:[]},r);u instanceof Promise?a.push(u.then(e=>{e.issues.length&&n.issues.push(...cr(c,e.issues)),n.value[l]=e.value})):(u.issues.length&&n.issues.push(...cr(c,u.issues)),n.value[l]=u.value)}let c;for(let e in i)s.has(e)||(c??=[],c.push(e));c&&c.length>0&&n.issues.push({code:`unrecognized_keys`,input:i,inst:e,keys:c})}else{n.value={};for(let o of Reflect.ownKeys(i)){if(o===`__proto__`||!Object.prototype.propertyIsEnumerable.call(i,o))continue;let s=t.keyType._zod.run({value:o,issues:[]},r);if(s instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(typeof o==`string`&&ci.test(o)&&s.issues.length){let e=t.keyType._zod.run({value:Number(o),issues:[]},r);if(e instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);e.issues.length===0&&(s=e)}if(s.issues.length){t.mode===`loose`?n.value[o]=i[o]:n.issues.push({code:`invalid_key`,origin:`record`,issues:s.issues.map(e=>ur(e,r,jn())),input:o,path:[o],inst:e});continue}let c=t.valueType._zod.run({value:i[o],issues:[]},r);c instanceof Promise?a.push(c.then(e=>{e.issues.length&&n.issues.push(...cr(o,e.issues)),n.value[s.value]=e.value})):(c.issues.length&&n.issues.push(...cr(o,c.issues)),n.value[s.value]=c.value)}}return a.length?Promise.all(a).then(()=>n):n}}),Pa=p(`$ZodEnum`,(e,t)=>{g.init(e,t);let n=Mn(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=RegExp(`^(${n.filter(e=>Jn.has(typeof e)).map(e=>typeof e==`string`?Yn(e):e.toString()).join(`|`)})$`),e._zod.parse=(t,i)=>{let a=t.value;return r.has(a)||t.issues.push({code:`invalid_value`,values:n,input:a,inst:e}),t}}),Fa=p(`$ZodLiteral`,(e,t)=>{if(g.init(e,t),t.values.length===0)throw Error(`Cannot create literal schema with no valid values`);let n=new Set(t.values);e._zod.values=n,e._zod.pattern=RegExp(`^(${t.values.map(e=>typeof e==`string`?Yn(e):e?Yn(e.toString()):String(e)).join(`|`)})$`),e._zod.parse=(r,i)=>{let a=r.value;return n.has(a)||r.issues.push({code:`invalid_value`,values:t.values,input:a,inst:e}),r}}),Ia=p(`$ZodTransform`,(e,t)=>{g.init(e,t),e._zod.optin=`optional`,e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new kn(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(n.value=e,n.fallback=!0,n));if(i instanceof Promise)throw new On;return n.value=i,n.fallback=!0,n}});function La(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}var Ra=p(`$ZodOptional`,(e,t)=>{g.init(e,t),e._zod.optin=`optional`,e._zod.optout=`optional`,m(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),m(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${In(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(t.innerType._zod.optin===`optional`){let r=e.value,i=t.innerType._zod.run(e,n);return i instanceof Promise?i.then(e=>La(e,r)):La(i,r)}return e.value===void 0?e:t.innerType._zod.run(e,n)}}),za=p(`$ZodExactOptional`,(e,t)=>{Ra.init(e,t),m(e._zod,`values`,()=>t.innerType._zod.values),m(e._zod,`pattern`,()=>t.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),Ba=p(`$ZodNullable`,(e,t)=>{g.init(e,t),m(e._zod,`optin`,()=>t.innerType._zod.optin),m(e._zod,`optout`,()=>t.innerType._zod.optout),m(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${In(e.source)}|null)$`):void 0}),m(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),Va=p(`$ZodDefault`,(e,t)=>{g.init(e,t),e._zod.optin=`optional`,m(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>Ha(e,t)):Ha(r,t)}});function Ha(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var Ua=p(`$ZodPrefault`,(e,t)=>{g.init(e,t),e._zod.optin=`optional`,m(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>(n.direction===`backward`||e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),Wa=p(`$ZodNonOptional`,(e,t)=>{g.init(e,t),m(e._zod,`values`,()=>{let e=t.innerType._zod.values;return e?new Set([...e].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>Ga(t,e)):Ga(i,e)}});function Ga(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}var Ka=p(`$ZodCatch`,(e,t)=>{g.init(e,t),e._zod.optin=`optional`,m(e._zod,`optout`,()=>t.innerType._zod.optout),m(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>ur(e,n,jn()))},input:e.value}),e.issues=[],e.fallback=!0),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>ur(e,n,jn()))},input:e.value}),e.issues=[],e.fallback=!0),e)}}),qa=p(`$ZodPipe`,(e,t)=>{g.init(e,t),m(e._zod,`values`,()=>t.in._zod.values),m(e._zod,`optin`,()=>t.in._zod.optin),m(e._zod,`optout`,()=>t.out._zod.optout),m(e._zod,`propValues`,()=>t.in._zod.propValues),e._zod.parse=(e,n)=>{if(n.direction===`backward`){let r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>Ja(e,t.in,n)):Ja(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>Ja(e,t.out,n)):Ja(r,t.out,n)}});function Ja(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}var Ya=p(`$ZodReadonly`,(e,t)=>{g.init(e,t),m(e._zod,`propValues`,()=>t.innerType._zod.propValues),m(e._zod,`values`,()=>t.innerType._zod.values),m(e._zod,`optin`,()=>t.innerType?._zod?.optin),m(e._zod,`optout`,()=>t.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(Xa):Xa(r)}});function Xa(e){return e.value=Object.freeze(e.value),e}var Za=p(`$ZodFunction`,(e,t)=>(g.init(e,t),e._def=t,e._zod.def=t,e.implement=t=>{if(typeof t!=`function`)throw Error(`implement() must be called with a function`);return function(...n){let r=e._def.input?yr(e._def.input,n):n,i=Reflect.apply(t,this,r);return e._def.output?yr(e._def.output,i):i}},e.implementAsync=t=>{if(typeof t!=`function`)throw Error(`implementAsync() must be called with a function`);return async function(...n){let r=e._def.input?await xr(e._def.input,n):n,i=await Reflect.apply(t,this,r);return e._def.output?await xr(e._def.output,i):i}},e._zod.parse=(t,n)=>typeof t.value==`function`?(e._def.output&&e._def.output._zod.def.type===`promise`?t.value=e.implementAsync(t.value):t.value=e.implement(t.value),t):(t.issues.push({code:`invalid_type`,expected:`function`,input:t.value,inst:e}),t),e.input=(...t)=>{let n=e.constructor;return Array.isArray(t[0])?new n({type:`function`,input:new ka({type:`tuple`,items:t[0],rest:t[1]}),output:e._def.output}):new n({type:`function`,input:t[0],output:e._def.output})},e.output=t=>{let n=e.constructor;return new n({type:`function`,input:e._def.input,output:t})},e)),Qa=p(`$ZodPromise`,(e,t)=>{g.init(e,t),e._zod.parse=(e,n)=>Promise.resolve(e.value).then(e=>t.innerType._zod.run({value:e,issues:[]},n))}),$a=p(`$ZodLazy`,(e,t)=>{g.init(e,t),m(e._zod,`innerType`,()=>{let e=t;return e._cachedInner||=t.getter(),e._cachedInner}),m(e._zod,`pattern`,()=>e._zod.innerType?._zod?.pattern),m(e._zod,`propValues`,()=>e._zod.innerType?._zod?.propValues),m(e._zod,`optin`,()=>e._zod.innerType?._zod?.optin??void 0),m(e._zod,`optout`,()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(t,n)=>e._zod.innerType._zod.run(t,n)}),eo=p(`$ZodCustom`,(e,t)=>{pi.init(e,t),g.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>to(t,n,r,e));to(i,n,r,e)}});function to(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(fr(e))}}var no,ro=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];return this._map.set(e,n),n&&typeof n==`object`&&`id`in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function io(){return new ro}(no=globalThis).__zod_globalRegistry??(no.__zod_globalRegistry=io());var ao=globalThis.__zod_globalRegistry;function oo(e,t){return new e({type:`string`,...h(t)})}function so(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...h(t)})}function co(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...h(t)})}function lo(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...h(t)})}function uo(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...h(t)})}function fo(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...h(t)})}function po(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...h(t)})}function mo(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...h(t)})}function ho(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...h(t)})}function go(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...h(t)})}function _o(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...h(t)})}function vo(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...h(t)})}function yo(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...h(t)})}function bo(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...h(t)})}function xo(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...h(t)})}function So(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...h(t)})}function Co(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...h(t)})}function wo(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...h(t)})}function To(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...h(t)})}function Eo(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...h(t)})}function Do(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...h(t)})}function Oo(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...h(t)})}function ko(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...h(t)})}function Ao(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...h(t)})}function jo(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...h(t)})}function Mo(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...h(t)})}function No(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...h(t)})}function Po(e,t){return new e({type:`number`,checks:[],...h(t)})}function Fo(e,t){return new e({type:`number`,coerce:!0,checks:[],...h(t)})}function Io(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...h(t)})}function Lo(e,t){return new e({type:`boolean`,...h(t)})}function Ro(e,t){return new e({type:`boolean`,coerce:!0,...h(t)})}function zo(e,t){return new e({type:`bigint`,...h(t)})}function Bo(e,t){return new e({type:`null`,...h(t)})}function Vo(e){return new e({type:`any`})}function Ho(e){return new e({type:`unknown`})}function Uo(e,t){return new e({type:`never`,...h(t)})}function Wo(e,t){return new e({type:`void`,...h(t)})}function Go(e,t){return new e({type:`date`,...h(t)})}function Ko(e,t){return new hi({check:`less_than`,...h(t),value:e,inclusive:!1})}function qo(e,t){return new hi({check:`less_than`,...h(t),value:e,inclusive:!0})}function Jo(e,t){return new gi({check:`greater_than`,...h(t),value:e,inclusive:!1})}function Yo(e,t){return new gi({check:`greater_than`,...h(t),value:e,inclusive:!0})}function Xo(e,t){return new _i({check:`multiple_of`,...h(t),value:e})}function Zo(e,t){return new yi({check:`max_length`,...h(t),maximum:e})}function Qo(e,t){return new bi({check:`min_length`,...h(t),minimum:e})}function $o(e,t){return new xi({check:`length_equals`,...h(t),length:e})}function es(e,t){return new Ci({check:`string_format`,format:`regex`,...h(t),pattern:e})}function ts(e){return new wi({check:`string_format`,format:`lowercase`,...h(e)})}function ns(e){return new Ti({check:`string_format`,format:`uppercase`,...h(e)})}function rs(e,t){return new Ei({check:`string_format`,format:`includes`,...h(t),includes:e})}function is(e,t){return new Di({check:`string_format`,format:`starts_with`,...h(t),prefix:e})}function as(e,t){return new Oi({check:`string_format`,format:`ends_with`,...h(t),suffix:e})}function os(e){return new ki({check:`overwrite`,tx:e})}function ss(e){return os(t=>t.normalize(e))}function cs(){return os(e=>e.trim())}function ls(){return os(e=>e.toLowerCase())}function us(){return os(e=>e.toUpperCase())}function ds(){return os(e=>Hn(e))}function fs(e,t,n){return new e({type:`array`,element:t,...h(n)})}function ps(e,t,n){let r=h(n);return r.abort??=!0,new e({type:`custom`,check:`custom`,fn:t,...r})}function ms(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...h(n)})}function hs(e,t){let n=gs(t=>(t.addIssue=e=>{if(typeof e==`string`)t.issues.push(fr(e,t.value,n._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,r.input??=t.value,r.inst??=n,r.continue??=!n._zod.def.abort,t.issues.push(fr(r))}},e(t.value,t)),t);return n}function gs(e,t){let n=new pi({check:`custom`,...h(t)});return n._zod.check=e,n}function _s(e){let t=e?.target??`draft-2020-12`;return t===`draft-4`&&(t=`draft-04`),t===`draft-7`&&(t=`draft-07`),{processors:e.processors??{},metadataRegistry:e?.metadata??ao,target:t,unrepresentable:e?.unrepresentable??`throw`,override:e?.override??(()=>{}),io:e?.io??`output`,counter:0,seen:new Map,cycles:e?.cycles??`ref`,reused:e?.reused??`inline`,external:e?.external??void 0}}function vs(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,a=t.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o);let s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{let r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,r);else{let n=o.schema,a=t.processors[i.type];if(!a)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);a(e,t,n,r)}let a=e._zod.parent;a&&(o.ref||=a,vs(a,t,r),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&Object.assign(o.schema,c),t.io===`input`&&xs(e)&&(delete o.schema.examples,delete o.schema.default),t.io===`input`&&`_prefault`in o.schema&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function ys(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=new Map;for(let t of e.seen.entries()){let n=e.metadataRegistry.get(t[0])?.id;if(n){let e=r.get(n);if(e&&e!==t[0])throw Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}let i=t=>{let r=e.target===`draft-2020-12`?`$defs`:`definitions`;if(e.external){let n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};let a=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=a,{defId:a,ref:`${i(`__shared`)}#/${r}/${a}`}}if(t[1]===n)return{ref:`#`};let i=`#/${r}/`,a=t[1].schema.id??`__schema${e.counter++}`;return{defId:a,ref:i+a}},a=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:n,defId:r}=i(e);t.def={...t.schema},r&&(t.defId=r);let a=t.schema;for(let e in a)delete a[e];a.$ref=n};if(e.cycles===`throw`)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join(`/`)}/<root>
|
|
70
|
+
|
|
71
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0]){a(n);continue}if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}if(e.metadataRegistry.get(n[0])?.id){a(n);continue}if(r.cycle){a(n);continue}if(r.count>1&&e.reused===`ref`){a(n);continue}}}function bs(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):Object.assign(i,s),Object.assign(i,a),t._zod.parent===o)for(let e in i)e===`$ref`||e===`allOf`||e in a||delete i[e];if(s.$ref&&n.def)for(let e in i)e===`$ref`||e===`allOf`||e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e===`$ref`||e===`allOf`||e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};for(let t of[...e.seen.entries()].reverse())r(t[0]);let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}Object.assign(i,n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,o[e.defId]=e.def)}e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t[`~standard`],jsonSchema:{input:Cs(t,`input`,e.processors),output:Cs(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function xs(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return xs(r.element,n);if(r.type===`set`)return xs(r.valueType,n);if(r.type===`lazy`)return xs(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`)return xs(r.innerType,n);if(r.type===`intersection`)return xs(r.left,n)||xs(r.right,n);if(r.type===`record`||r.type===`map`)return xs(r.keyType,n)||xs(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:xs(r.in,n)||xs(r.out,n);if(r.type===`object`){for(let e in r.shape)if(xs(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(xs(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(xs(e,n))return!0;return!!(r.rest&&xs(r.rest,n))}return!1}var Ss=(e,t={})=>n=>{let r=_s({...n,processors:t});return vs(e,r),ys(r,e),bs(r,e)},Cs=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=_s({...i??{},target:a,io:t,processors:n});return vs(e,o),ys(o,e),bs(o,e)},ws={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},Ts=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l}=e._zod.bag;if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=ws[s]??s,i.format===``&&delete i.format,s===`time`&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c];e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},Es=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,format:s,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:u}=e._zod.bag;typeof s==`string`&&s.includes(`int`)?i.type=`integer`:i.type=`number`;let ee=typeof u==`number`&&u>=(a??-1/0),te=typeof l==`number`&&l<=(o??1/0),ne=t.target===`draft-04`||t.target===`openapi-3.0`;ee?ne?(i.minimum=u,i.exclusiveMinimum=!0):i.exclusiveMinimum=u:typeof a==`number`&&(i.minimum=a),te?ne?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l:typeof o==`number`&&(i.maximum=o),typeof c==`number`&&(i.multipleOf=c)},Ds=(e,t,n,r)=>{n.type=`boolean`},Os=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`BigInt cannot be represented in JSON Schema`)},ks=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Symbols cannot be represented in JSON Schema`)},As=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},js=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Undefined cannot be represented in JSON Schema`)},Ms=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Void cannot be represented in JSON Schema`)},Ns=(e,t,n,r)=>{n.not={}},Ps=(e,t,n,r)=>{},Fs=(e,t,n,r)=>{},Is=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Date cannot be represented in JSON Schema`)},Ls=(e,t,n,r)=>{let i=e._zod.def,a=Mn(i.entries);a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},Rs=(e,t,n,r)=>{let i=e._zod.def,a=[];for(let e of i.values)if(e===void 0){if(t.unrepresentable===`throw`)throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof e==`bigint`){if(t.unrepresentable===`throw`)throw Error(`BigInt literals cannot be represented in JSON Schema`);a.push(Number(e))}else a.push(e);if(a.length!==0)if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a},zs=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`NaN cannot be represented in JSON Schema`)},Bs=(e,t,n,r)=>{let i=n,a=e._zod.pattern;if(!a)throw Error(`Pattern not found in template literal`);i.type=`string`,i.pattern=a.source},Vs=(e,t,n,r)=>{let i=n,a={type:`string`,format:`binary`,contentEncoding:`binary`},{minimum:o,maximum:s,mime:c}=e._zod.bag;o!==void 0&&(a.minLength=o),s!==void 0&&(a.maxLength=s),c?c.length===1?(a.contentMediaType=c[0],Object.assign(i,a)):(Object.assign(i,a),i.anyOf=c.map(e=>({contentMediaType:e}))):Object.assign(i,a)},Hs=(e,t,n,r)=>{n.type=`boolean`},Us=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Custom types cannot be represented in JSON Schema`)},Ws=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Function types cannot be represented in JSON Schema`)},Gs=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Transforms cannot be represented in JSON Schema`)},Ks=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Map cannot be represented in JSON Schema`)},qs=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Set cannot be represented in JSON Schema`)},Js=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=e._zod.bag;typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=vs(a.element,t,{...r,path:[...r.path,`items`]})},Ys=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`,i.properties={};let o=a.shape;for(let e in o)i.properties[e]=vs(o[e],t,{...r,path:[...r.path,`properties`,e]});let s=new Set(Object.keys(o)),c=new Set([...s].filter(e=>{let n=a.shape[e]._zod;return t.io===`input`?n.optin===void 0:n.optout===void 0}));c.size>0&&(i.required=Array.from(c)),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=vs(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},Xs=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>vs(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},Zs=(e,t,n,r)=>{let i=e._zod.def,a=vs(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=vs(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1;n.allOf=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]]},Qs=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`array`;let o=t.target===`draft-2020-12`?`prefixItems`:`items`,s=t.target===`draft-2020-12`||t.target===`openapi-3.0`?`items`:`additionalItems`,c=a.items.map((e,n)=>vs(e,t,{...r,path:[...r.path,o,n]})),l=a.rest?vs(a.rest,t,{...r,path:[...r.path,s,...t.target===`openapi-3.0`?[a.items.length]:[]]}):null;t.target===`draft-2020-12`?(i.prefixItems=c,l&&(i.items=l)):t.target===`openapi-3.0`?(i.items={anyOf:c},l&&i.items.anyOf.push(l),i.minItems=c.length,l||(i.maxItems=c.length)):(i.items=c,l&&(i.additionalItems=l));let{minimum:u,maximum:ee}=e._zod.bag;typeof u==`number`&&(i.minItems=u),typeof ee==`number`&&(i.maxItems=ee)},$s=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=o._zod.bag?.patterns;if(a.mode===`loose`&&s&&s.size>0){let e=vs(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)i.patternProperties[t.source]=e}else (t.target===`draft-07`||t.target===`draft-2020-12`)&&(i.propertyNames=vs(a.keyType,t,{...r,path:[...r.path,`propertyNames`]})),i.additionalProperties=vs(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]});let c=o._zod.values;if(c){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e)}},ec=(e,t,n,r)=>{let i=e._zod.def,a=vs(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},tc=(e,t,n,r)=>{let i=e._zod.def;vs(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},nc=(e,t,n,r)=>{let i=e._zod.def;vs(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},rc=(e,t,n,r)=>{let i=e._zod.def;vs(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,t.io===`input`&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},ic=(e,t,n,r)=>{let i=e._zod.def;vs(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{throw Error(`Dynamic catch values are not supported in JSON Schema`)}n.default=o},ac=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;vs(o,t,r);let s=t.seen.get(e);s.ref=o},oc=(e,t,n,r)=>{let i=e._zod.def;vs(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},sc=(e,t,n,r)=>{let i=e._zod.def;vs(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},cc=(e,t,n,r)=>{let i=e._zod.def;vs(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},lc=(e,t,n,r)=>{let i=e._zod.innerType;vs(i,t,r);let a=t.seen.get(e);a.ref=i},uc={string:Ts,number:Es,boolean:Ds,bigint:Os,symbol:ks,null:As,undefined:js,void:Ms,never:Ns,any:Ps,unknown:Fs,date:Is,enum:Ls,literal:Rs,nan:zs,template_literal:Bs,file:Vs,success:Hs,custom:Us,function:Ws,transform:Gs,map:Ks,set:qs,array:Js,object:Ys,union:Xs,intersection:Zs,tuple:Qs,record:$s,nullable:ec,nonoptional:tc,default:nc,prefault:rc,catch:ic,pipe:ac,readonly:oc,promise:sc,optional:cc,lazy:lc};function dc(e,t){if(`_idmap`in e){let n=e,r=_s({...t,processors:uc}),i={};for(let e of n._idmap.entries()){let[t,n]=e;vs(n,r)}let a={};r.external={registry:n,uri:t?.uri,defs:i};for(let e of n._idmap.entries()){let[t,n]=e;ys(r,n),a[t]=bs(r,n)}return Object.keys(i).length>0&&(a.__shared={[r.target===`draft-2020-12`?`$defs`:`definitions`]:i}),{schemas:a}}let n=_s({...t,processors:uc});return vs(e,n),ys(n,e),bs(n,e)}var fc=p(`ZodISODateTime`,(e,t)=>{Gi.init(e,t),Lc.init(e,t)});function pc(e){return Ao(fc,e)}var mc=p(`ZodISODate`,(e,t)=>{Ki.init(e,t),Lc.init(e,t)});function hc(e){return jo(mc,e)}var gc=p(`ZodISOTime`,(e,t)=>{qi.init(e,t),Lc.init(e,t)});function _c(e){return Mo(gc,e)}var vc=p(`ZodISODuration`,(e,t)=>{Ji.init(e,t),Lc.init(e,t)});function yc(e){return No(vc,e)}var bc=p(`ZodError`,(e,t)=>{mr.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>_r(e,t)},flatten:{value:t=>gr(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,Nn,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,Nn,2)}},isEmpty:{get(){return e.issues.length===0}}})},{Parent:Error}),xc=vr(bc),Sc=br(bc),Cc=Sr(bc),wc=wr(bc),Tc=Er(bc),Ec=Dr(bc),Dc=Or(bc),Oc=kr(bc),kc=Ar(bc),Ac=jr(bc),jc=Mr(bc),Mc=Nr(bc),Nc=new WeakMap;function Pc(e,t,n){let r=Object.getPrototypeOf(e),i=Nc.get(r);if(i||(i=new Set,Nc.set(r,i)),!i.has(t)){i.add(t);for(let e in n){let t=n[e];Object.defineProperty(r,e,{configurable:!0,enumerable:!1,get(){let n=t.bind(this);return Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:n}),n},set(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:t})}})}}}var _=p(`ZodType`,(e,t)=>(g.init(e,t),Object.assign(e[`~standard`],{jsonSchema:{input:Cs(e,`input`),output:Cs(e,`output`)}}),e.toJSONSchema=Ss(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(t,n)=>xc(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>Cc(e,t,n),e.parseAsync=async(t,n)=>Sc(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>wc(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>Tc(e,t,n),e.decode=(t,n)=>Ec(e,t,n),e.encodeAsync=async(t,n)=>Dc(e,t,n),e.decodeAsync=async(t,n)=>Oc(e,t,n),e.safeEncode=(t,n)=>kc(e,t,n),e.safeDecode=(t,n)=>Ac(e,t,n),e.safeEncodeAsync=async(t,n)=>jc(e,t,n),e.safeDecodeAsync=async(t,n)=>Mc(e,t,n),Pc(e,`ZodType`,{check(...e){let t=this.def;return this.clone(Bn(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return Xn(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(eu(e,t))},superRefine(e,t){return this.check(tu(e,t))},overwrite(e){return this.check(os(e))},optional(){return Ml(this)},exactOptional(){return Pl(this)},nullable(){return Il(this)},nullish(){return Ml(Il(this))},nonoptional(e){return Hl(this,e)},array(){return w(this)},or(e){return E([this,e])},and(e){return wl(this,e)},transform(e){return Kl(this,Al(e))},default(e){return Rl(this,e)},prefault(e){return Bl(this,e)},catch(e){return Wl(this,e)},pipe(e){return Kl(this,e)},readonly(){return Jl(this)},describe(e){let t=this.clone();return ao.add(t,{description:e}),t},meta(...e){if(e.length===0)return ao.get(this);let t=this.clone();return ao.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e){return e(this)}}),Object.defineProperty(e,"description",{get(){return ao.get(e)?.description},configurable:!0}),e)),Fc=p(`_ZodString`,(e,t)=>{Mi.init(e,t),_.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ts(e,t,n,r);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,Pc(e,`_ZodString`,{regex(...e){return this.check(es(...e))},includes(...e){return this.check(rs(...e))},startsWith(...e){return this.check(is(...e))},endsWith(...e){return this.check(as(...e))},min(...e){return this.check(Qo(...e))},max(...e){return this.check(Zo(...e))},length(...e){return this.check($o(...e))},nonempty(...e){return this.check(Qo(1,...e))},lowercase(e){return this.check(ts(e))},uppercase(e){return this.check(ns(e))},trim(){return this.check(cs())},normalize(...e){return this.check(ss(...e))},toLowerCase(){return this.check(ls())},toUpperCase(){return this.check(us())},slugify(){return this.check(ds())}})}),Ic=p(`ZodString`,(e,t)=>{Mi.init(e,t),Fc.init(e,t),e.email=t=>e.check(so(Rc,t)),e.url=t=>e.check(mo(Vc,t)),e.jwt=t=>e.check(ko(nl,t)),e.emoji=t=>e.check(ho(Hc,t)),e.guid=t=>e.check(co(zc,t)),e.uuid=t=>e.check(lo(Bc,t)),e.uuidv4=t=>e.check(uo(Bc,t)),e.uuidv6=t=>e.check(fo(Bc,t)),e.uuidv7=t=>e.check(po(Bc,t)),e.nanoid=t=>e.check(go(Uc,t)),e.guid=t=>e.check(co(zc,t)),e.cuid=t=>e.check(_o(Wc,t)),e.cuid2=t=>e.check(vo(Gc,t)),e.ulid=t=>e.check(yo(Kc,t)),e.base64=t=>e.check(Eo($c,t)),e.base64url=t=>e.check(Do(el,t)),e.xid=t=>e.check(bo(qc,t)),e.ksuid=t=>e.check(xo(Jc,t)),e.ipv4=t=>e.check(So(Yc,t)),e.ipv6=t=>e.check(Co(Xc,t)),e.cidrv4=t=>e.check(wo(Zc,t)),e.cidrv6=t=>e.check(To(Qc,t)),e.e164=t=>e.check(Oo(tl,t)),e.datetime=t=>e.check(pc(t)),e.date=t=>e.check(hc(t)),e.time=t=>e.check(_c(t)),e.duration=t=>e.check(yc(t))});function v(e){return oo(Ic,e)}var Lc=p(`ZodStringFormat`,(e,t)=>{Ni.init(e,t),Fc.init(e,t)}),Rc=p(`ZodEmail`,(e,t)=>{Ii.init(e,t),Lc.init(e,t)}),zc=p(`ZodGUID`,(e,t)=>{Pi.init(e,t),Lc.init(e,t)}),Bc=p(`ZodUUID`,(e,t)=>{Fi.init(e,t),Lc.init(e,t)}),Vc=p(`ZodURL`,(e,t)=>{Li.init(e,t),Lc.init(e,t)}),Hc=p(`ZodEmoji`,(e,t)=>{Ri.init(e,t),Lc.init(e,t)}),Uc=p(`ZodNanoID`,(e,t)=>{zi.init(e,t),Lc.init(e,t)}),Wc=p(`ZodCUID`,(e,t)=>{Bi.init(e,t),Lc.init(e,t)}),Gc=p(`ZodCUID2`,(e,t)=>{Vi.init(e,t),Lc.init(e,t)}),Kc=p(`ZodULID`,(e,t)=>{Hi.init(e,t),Lc.init(e,t)}),qc=p(`ZodXID`,(e,t)=>{Ui.init(e,t),Lc.init(e,t)}),Jc=p(`ZodKSUID`,(e,t)=>{Wi.init(e,t),Lc.init(e,t)}),Yc=p(`ZodIPv4`,(e,t)=>{Yi.init(e,t),Lc.init(e,t)}),Xc=p(`ZodIPv6`,(e,t)=>{Xi.init(e,t),Lc.init(e,t)}),Zc=p(`ZodCIDRv4`,(e,t)=>{Zi.init(e,t),Lc.init(e,t)}),Qc=p(`ZodCIDRv6`,(e,t)=>{Qi.init(e,t),Lc.init(e,t)}),$c=p(`ZodBase64`,(e,t)=>{ea.init(e,t),Lc.init(e,t)}),el=p(`ZodBase64URL`,(e,t)=>{na.init(e,t),Lc.init(e,t)}),tl=p(`ZodE164`,(e,t)=>{ra.init(e,t),Lc.init(e,t)}),nl=p(`ZodJWT`,(e,t)=>{aa.init(e,t),Lc.init(e,t)}),rl=p(`ZodNumber`,(e,t)=>{oa.init(e,t),_.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Es(e,t,n,r),Pc(e,`ZodNumber`,{gt(e,t){return this.check(Jo(e,t))},gte(e,t){return this.check(Yo(e,t))},min(e,t){return this.check(Yo(e,t))},lt(e,t){return this.check(Ko(e,t))},lte(e,t){return this.check(qo(e,t))},max(e,t){return this.check(qo(e,t))},int(e){return this.check(al(e))},safe(e){return this.check(al(e))},positive(e){return this.check(Jo(0,e))},nonnegative(e){return this.check(Yo(0,e))},negative(e){return this.check(Ko(0,e))},nonpositive(e){return this.check(qo(0,e))},multipleOf(e,t){return this.check(Xo(e,t))},step(e,t){return this.check(Xo(e,t))},finite(){return this}});let n=e._zod.bag;e.minValue=Math.max(n.minimum??-1/0,n.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(n.maximum??1/0,n.exclusiveMaximum??1/0)??null,e.isInt=(n.format??``).includes(`int`)||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function y(e){return Po(rl,e)}var il=p(`ZodNumberFormat`,(e,t)=>{sa.init(e,t),rl.init(e,t)});function al(e){return Io(il,e)}var ol=p(`ZodBoolean`,(e,t)=>{ca.init(e,t),_.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ds(e,t,n,r)});function b(e){return Lo(ol,e)}var sl=p(`ZodBigInt`,(e,t)=>{la.init(e,t),_.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Os(e,t,n,r),e.gte=(t,n)=>e.check(Yo(t,n)),e.min=(t,n)=>e.check(Yo(t,n)),e.gt=(t,n)=>e.check(Jo(t,n)),e.gte=(t,n)=>e.check(Yo(t,n)),e.min=(t,n)=>e.check(Yo(t,n)),e.lt=(t,n)=>e.check(Ko(t,n)),e.lte=(t,n)=>e.check(qo(t,n)),e.max=(t,n)=>e.check(qo(t,n)),e.positive=t=>e.check(Jo(BigInt(0),t)),e.negative=t=>e.check(Ko(BigInt(0),t)),e.nonpositive=t=>e.check(qo(BigInt(0),t)),e.nonnegative=t=>e.check(Yo(BigInt(0),t)),e.multipleOf=(t,n)=>e.check(Xo(t,n));let n=e._zod.bag;e.minValue=n.minimum??null,e.maxValue=n.maximum??null,e.format=n.format??null});function cl(e){return zo(sl,e)}var ll=p(`ZodNull`,(e,t)=>{ua.init(e,t),_.init(e,t),e._zod.processJSONSchema=(t,n,r)=>As(e,t,n,r)});function ul(e){return Bo(ll,e)}var dl=p(`ZodAny`,(e,t)=>{da.init(e,t),_.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function x(){return Vo(dl)}var fl=p(`ZodUnknown`,(e,t)=>{fa.init(e,t),_.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function S(){return Ho(fl)}var pl=p(`ZodNever`,(e,t)=>{pa.init(e,t),_.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ns(e,t,n,r)});function ml(e){return Uo(pl,e)}var hl=p(`ZodVoid`,(e,t)=>{ma.init(e,t),_.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ms(e,t,n,r)});function gl(e){return Wo(hl,e)}var _l=p(`ZodDate`,(e,t)=>{ha.init(e,t),_.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Is(e,t,n,r),e.min=(t,n)=>e.check(Yo(t,n)),e.max=(t,n)=>e.check(qo(t,n));let n=e._zod.bag;e.minDate=n.minimum?new Date(n.minimum):null,e.maxDate=n.maximum?new Date(n.maximum):null});function C(e){return Go(_l,e)}var vl=p(`ZodArray`,(e,t)=>{_a.init(e,t),_.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Js(e,t,n,r),e.element=t.element,Pc(e,`ZodArray`,{min(e,t){return this.check(Qo(e,t))},nonempty(e){return this.check(Qo(1,e))},max(e,t){return this.check(Zo(e,t))},length(e,t){return this.check($o(e,t))},unwrap(){return this.element}})});function w(e,t){return fs(vl,e,t)}var yl=p(`ZodObject`,(e,t)=>{Sa.init(e,t),_.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ys(e,t,n,r),m(e,`shape`,()=>t.shape),Pc(e,`ZodObject`,{keyof(){return A(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:S()})},loose(){return this.clone({...this._zod.def,catchall:S()})},strict(){return this.clone({...this._zod.def,catchall:ml()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return tr(this,e)},safeExtend(e){return nr(this,e)},merge(e){return rr(this,e)},pick(e){return $n(this,e)},omit(e){return er(this,e)},partial(...e){return ir(jl,this,e[0])},required(...e){return ar(Vl,this,e[0])}})});function T(e,t){return new yl({type:`object`,shape:e??{},...h(t)})}function bl(e,t){return new yl({type:`object`,shape:e,catchall:ml(),...h(t)})}var xl=p(`ZodUnion`,(e,t)=>{wa.init(e,t),_.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Xs(e,t,n,r),e.options=t.options});function E(e,t){return new xl({type:`union`,options:e,...h(t)})}var Sl=p(`ZodDiscriminatedUnion`,(e,t)=>{xl.init(e,t),Ta.init(e,t)});function D(e,t,n){return new Sl({type:`union`,options:t,discriminator:e,...h(n)})}var Cl=p(`ZodIntersection`,(e,t)=>{Ea.init(e,t),_.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Zs(e,t,n,r)});function wl(e,t){return new Cl({type:`intersection`,left:e,right:t})}var Tl=p(`ZodTuple`,(e,t)=>{ka.init(e,t),_.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Qs(e,t,n,r),e.rest=t=>e.clone({...e._zod.def,rest:t})});function O(e,t,n){let r=t instanceof g;return new Tl({type:`tuple`,items:e,rest:r?t:null,...h(r?n:t)})}var El=p(`ZodRecord`,(e,t)=>{Na.init(e,t),_.init(e,t),e._zod.processJSONSchema=(t,n,r)=>$s(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function k(e,t,n){return!t||!t._zod?new El({type:`record`,keyType:v(),valueType:e,...h(t)}):new El({type:`record`,keyType:e,valueType:t,...h(n)})}var Dl=p(`ZodEnum`,(e,t)=>{Pa.init(e,t),_.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ls(e,t,n,r),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new Dl({...t,checks:[],...h(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new Dl({...t,checks:[],...h(r),entries:i})}});function A(e,t){return new Dl({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...h(t)})}var Ol=p(`ZodLiteral`,(e,t)=>{Fa.init(e,t),_.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Rs(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function j(e,t){return new Ol({type:`literal`,values:Array.isArray(e)?e:[e],...h(t)})}var kl=p(`ZodTransform`,(e,t)=>{Ia.init(e,t),_.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Gs(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new kn(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(fr(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,t.input??=n.value,t.inst??=e,n.issues.push(fr(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n.fallback=!0,n)):(n.value=i,n.fallback=!0,n)}});function Al(e){return new kl({type:`transform`,transform:e})}var jl=p(`ZodOptional`,(e,t)=>{Ra.init(e,t),_.init(e,t),e._zod.processJSONSchema=(t,n,r)=>cc(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ml(e){return new jl({type:`optional`,innerType:e})}var Nl=p(`ZodExactOptional`,(e,t)=>{za.init(e,t),_.init(e,t),e._zod.processJSONSchema=(t,n,r)=>cc(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Pl(e){return new Nl({type:`optional`,innerType:e})}var Fl=p(`ZodNullable`,(e,t)=>{Ba.init(e,t),_.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ec(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Il(e){return new Fl({type:`nullable`,innerType:e})}var Ll=p(`ZodDefault`,(e,t)=>{Va.init(e,t),_.init(e,t),e._zod.processJSONSchema=(t,n,r)=>nc(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Rl(e,t){return new Ll({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():qn(t)}})}var zl=p(`ZodPrefault`,(e,t)=>{Ua.init(e,t),_.init(e,t),e._zod.processJSONSchema=(t,n,r)=>rc(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Bl(e,t){return new zl({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():qn(t)}})}var Vl=p(`ZodNonOptional`,(e,t)=>{Wa.init(e,t),_.init(e,t),e._zod.processJSONSchema=(t,n,r)=>tc(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Hl(e,t){return new Vl({type:`nonoptional`,innerType:e,...h(t)})}var Ul=p(`ZodCatch`,(e,t)=>{Ka.init(e,t),_.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ic(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Wl(e,t){return new Ul({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}var Gl=p(`ZodPipe`,(e,t)=>{qa.init(e,t),_.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ac(e,t,n,r),e.in=t.in,e.out=t.out});function Kl(e,t){return new Gl({type:`pipe`,in:e,out:t})}var ql=p(`ZodReadonly`,(e,t)=>{Ya.init(e,t),_.init(e,t),e._zod.processJSONSchema=(t,n,r)=>oc(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Jl(e){return new ql({type:`readonly`,innerType:e})}var Yl=p(`ZodLazy`,(e,t)=>{$a.init(e,t),_.init(e,t),e._zod.processJSONSchema=(t,n,r)=>lc(e,t,n,r),e.unwrap=()=>e._zod.def.getter()});function M(e){return new Yl({type:`lazy`,getter:e})}var Xl=p(`ZodPromise`,(e,t)=>{Qa.init(e,t),_.init(e,t),e._zod.processJSONSchema=(t,n,r)=>sc(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function N(e){return new Xl({type:`promise`,innerType:e})}var Zl=p(`ZodFunction`,(e,t)=>{Za.init(e,t),_.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ws(e,t,n,r)});function P(e){return new Zl({type:`function`,input:Array.isArray(e?.input)?O(e?.input):e?.input??w(S()),output:e?.output??S()})}var Ql=p(`ZodCustom`,(e,t)=>{eo.init(e,t),_.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Us(e,t,n,r)});function $l(e,t){return ps(Ql,e??(()=>!0),t)}function eu(e,t={}){return ms(Ql,e,t)}function tu(e,t){return hs(e,t)}function nu(e,t={}){let n=new Ql({type:`custom`,check:`custom`,fn:t=>t instanceof e,abort:!0,...h(t)});return n._zod.bag.Class=e,n._zod.check=t=>{t.value instanceof e||t.issues.push({code:`invalid_type`,expected:e.name,input:t.value,inst:n,path:[...n._zod.def.path??[]]})},n}var ru={invalid_type:`invalid_type`,too_big:`too_big`,too_small:`too_small`,invalid_format:`invalid_format`,not_multiple_of:`not_multiple_of`,unrecognized_keys:`unrecognized_keys`,invalid_union:`invalid_union`,invalid_key:`invalid_key`,invalid_element:`invalid_element`,invalid_value:`invalid_value`,custom:`custom`},iu;iu||={};function au(e){return Fo(rl,e)}function ou(e){return Ro(ol,e)}function F(e){if(typeof process<`u`&&{}.OS_EAGER_SCHEMAS===`1`)return e();let t,n=()=>(t===void 0&&(t=e()),t);return new Proxy(function(){},{get(e,t){let r=n(),i=r[t];return typeof i==`function`?i.bind(r):i},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())}})}var su=F(()=>A([`full`,`partial`,`experimental`,`deprecated`]).describe(`Level of protocol conformance`)),cu=F(()=>T({major:y().int().min(0),minor:y().int().min(0),patch:y().int().min(0)}).describe(`Semantic version of the protocol`)),lu=F(()=>T({id:v().regex(/^([a-z][a-z0-9]*\.)+protocol\.[a-z][a-z0-9._]*\.v\d+$/).describe(`Unique protocol identifier (e.g., com.objectstack.protocol.storage.v1)`),label:v(),version:cu,specification:v().optional().describe(`URL or path to protocol specification`),description:v().optional()})),uu=F(()=>T({name:v().describe(`Feature identifier within the protocol`),enabled:b().default(!0),description:v().optional(),sinceVersion:v().optional().describe(`Version when this feature was added`),deprecatedSince:v().optional().describe(`Version when deprecated`)})),du=F(()=>T({protocol:lu,conformance:su.default(`full`),implementedFeatures:w(v()).optional().describe(`List of implemented feature names`),features:w(uu).optional(),metadata:k(v(),S()).optional(),certified:b().default(!1).describe(`Has passed official conformance tests`),certificationDate:v().datetime().optional()})),fu=F(()=>T({id:v().regex(/^([a-z][a-z0-9]*\.)+interface\.[a-z][a-z0-9._]+$/).describe(`Unique interface identifier`),name:v(),description:v().optional(),version:cu,methods:w(T({name:v().describe(`Method name`),description:v().optional(),parameters:w(T({name:v(),type:v().describe(`Type notation (e.g., string, number, User)`),required:b().default(!0),description:v().optional()})).optional(),returnType:v().optional().describe(`Return value type`),async:b().default(!1).describe(`Whether method returns a Promise`)})),events:w(T({name:v().describe(`Event name`),description:v().optional(),payload:v().optional().describe(`Event payload type`)})).optional(),stability:A([`stable`,`beta`,`alpha`,`experimental`]).default(`stable`)})),pu=F(()=>T({pluginId:v().regex(/^([a-z][a-z0-9]*\.)+[a-z][a-z0-9-]+$/).describe(`Required plugin identifier`),version:v().describe(`Semantic version constraint`),optional:b().default(!1),reason:v().optional(),requiredCapabilities:w(v()).optional().describe(`Protocol IDs the dependency must support`)})),mu=F(()=>T({id:v().regex(/^([a-z][a-z0-9]*\.)+extension\.[a-z][a-z0-9._]+$/).describe(`Unique extension point identifier`),name:v(),description:v().optional(),type:A([`action`,`hook`,`widget`,`provider`,`transformer`,`validator`,`decorator`]),contract:T({input:v().optional().describe(`Input type/schema`),output:v().optional().describe(`Output type/schema`),signature:v().optional().describe(`Function signature if applicable`)}).optional(),cardinality:A([`single`,`multiple`]).default(`multiple`).describe(`Whether multiple extensions can register to this point`)})),hu=F(()=>T({implements:w(du).optional().describe(`List of protocols this plugin conforms to`),provides:w(fu).optional().describe(`Services/APIs this plugin offers to others`),requires:w(pu).optional().describe(`Required plugins and their capabilities`),extensionPoints:w(mu).optional().describe(`Points where other plugins can extend this plugin`),extensions:w(T({targetPluginId:v().describe(`Plugin ID being extended`),extensionPointId:v().describe(`Extension point identifier`),implementation:v().describe(`Path to implementation module`),priority:y().int().default(100).describe(`Registration priority (lower = higher priority)`)})).optional().describe(`Extensions contributed to other plugins`)})),gu=F(()=>A([`eager`,`lazy`,`parallel`,`deferred`,`on-demand`]).describe(`Plugin loading strategy`)),_u=F(()=>T({enabled:b().default(!1),priority:y().int().min(0).default(100),resources:w(A([`metadata`,`dependencies`,`assets`,`code`,`services`])).optional(),conditions:T({routes:w(v()).optional(),roles:w(v()).optional(),deviceType:w(A([`desktop`,`mobile`,`tablet`])).optional(),minNetworkSpeed:A([`slow-2g`,`2g`,`3g`,`4g`]).optional()}).optional()}).describe(`Plugin preloading configuration`)),vu=F(()=>T({enabled:b().default(!0),strategy:A([`route`,`feature`,`size`,`custom`]).default(`feature`),chunkNaming:A([`hashed`,`named`,`sequential`]).default(`hashed`),maxChunkSize:y().int().min(10).optional().describe(`Max chunk size in KB`),sharedDependencies:T({enabled:b().default(!0),minChunks:y().int().min(1).default(2)}).optional()}).describe(`Plugin code splitting configuration`)),yu=F(()=>T({enabled:b().default(!0),mode:A([`async`,`sync`,`eager`,`lazy`]).default(`async`),prefetch:b().default(!1).describe(`Prefetch module in idle time`),preload:b().default(!1).describe(`Preload module in parallel with parent`),webpackChunkName:v().optional().describe(`Custom chunk name for webpack`),timeout:y().int().min(100).default(3e4).describe(`Dynamic import timeout (ms)`),retry:T({enabled:b().default(!0),maxAttempts:y().int().min(1).max(10).default(3),backoffMs:y().int().min(0).default(1e3).describe(`Exponential backoff base delay`)}).optional()}).describe(`Plugin dynamic import configuration`)),bu=F(()=>T({mode:A([`sync`,`async`,`parallel`,`sequential`]).default(`async`),timeout:y().int().min(100).default(3e4),priority:y().int().min(0).default(100),critical:b().default(!1).describe(`If true, kernel bootstrap fails if plugin fails`),retry:T({enabled:b().default(!1),maxAttempts:y().int().min(1).max(5).default(3),backoffMs:y().int().min(0).default(1e3)}).optional(),healthCheckInterval:y().int().min(0).optional().describe(`Health check interval in ms (0 = disabled)`)}).describe(`Plugin initialization configuration`)),xu=F(()=>T({strategy:A([`strict`,`compatible`,`latest`,`pinned`]).default(`compatible`),peerDependencies:T({resolve:b().default(!0),onMissing:A([`error`,`warn`,`ignore`]).default(`warn`),onMismatch:A([`error`,`warn`,`ignore`]).default(`warn`)}).optional(),optionalDependencies:T({load:b().default(!0),onFailure:A([`warn`,`ignore`]).default(`warn`)}).optional(),conflictResolution:A([`fail`,`latest`,`oldest`,`manual`]).default(`latest`),circularDependencies:A([`error`,`warn`,`allow`]).default(`warn`)}).describe(`Plugin dependency resolution configuration`)),Su=F(()=>T({enabled:b().default(!1),environment:A([`development`,`staging`,`production`]).default(`development`).describe(`Target environment controlling safety level`),strategy:A([`full`,`partial`,`state-preserve`]).default(`full`),watchPatterns:w(v()).optional().describe(`Glob patterns for files to watch`),ignorePatterns:w(v()).optional().describe(`Glob patterns for files to ignore`),debounceMs:y().int().min(0).default(300),preserveState:b().default(!1),stateSerialization:T({enabled:b().default(!1),handler:v().optional()}).optional(),hooks:T({beforeReload:v().optional().describe(`Function to call before reload`),afterReload:v().optional().describe(`Function to call after reload`),onError:v().optional().describe(`Function to call on reload error`)}).optional(),productionSafety:T({healthValidation:b().default(!0).describe(`Run health checks after reload before accepting traffic`),rollbackOnFailure:b().default(!0).describe(`Auto-rollback if reloaded plugin fails health check`),healthTimeout:y().int().min(1e3).default(3e4).describe(`Health check timeout after reload in ms`),drainConnections:b().default(!0).describe(`Gracefully drain active requests before reloading`),drainTimeout:y().int().min(0).default(15e3).describe(`Max wait time for connection draining in ms`),maxConcurrentReloads:y().int().min(1).default(1).describe(`Limit concurrent reloads to prevent system instability`),minReloadInterval:y().int().min(1e3).default(5e3).describe(`Cooldown period between reloads of the same plugin`)}).optional()}).describe(`Plugin hot reload configuration`)),Cu=F(()=>T({enabled:b().default(!0),storage:A([`memory`,`disk`,`indexeddb`,`hybrid`]).default(`memory`),keyStrategy:A([`version`,`hash`,`timestamp`]).default(`version`),ttl:y().int().min(0).optional().describe(`Time to live in seconds (0 = infinite)`),maxSize:y().int().min(1).optional().describe(`Max cache size in MB`),invalidateOn:w(A([`version-change`,`dependency-change`,`manual`,`error`])).optional(),compression:T({enabled:b().default(!1),algorithm:A([`gzip`,`brotli`,`deflate`]).default(`gzip`)}).optional()}).describe(`Plugin caching configuration`)),wu=F(()=>T({enabled:b().default(!1),scope:A([`automation-only`,`untrusted-only`,`all-plugins`]).default(`automation-only`).describe(`Which plugins are subject to isolation`),isolationLevel:A([`none`,`process`,`vm`,`iframe`,`web-worker`]).default(`none`),allowedCapabilities:w(v()).optional().describe(`List of allowed capability IDs`),resourceQuotas:T({maxMemoryMB:y().int().min(1).optional(),maxCpuTimeMs:y().int().min(100).optional(),maxFileDescriptors:y().int().min(1).optional(),maxNetworkKBps:y().int().min(1).optional()}).optional(),permissions:T({allowedAPIs:w(v()).optional(),allowedPaths:w(v()).optional(),allowedEndpoints:w(v()).optional(),allowedEnvVars:w(v()).optional()}).optional(),ipc:T({enabled:b().default(!0).describe(`Allow sandboxed plugins to communicate via IPC`),transport:A([`message-port`,`unix-socket`,`tcp`,`memory`]).default(`message-port`).describe(`IPC transport for cross-boundary communication`),maxMessageSize:y().int().min(1024).default(1048576).describe(`Maximum IPC message size in bytes (default 1MB)`),timeout:y().int().min(100).default(3e4).describe(`IPC message response timeout in ms`),allowedServices:w(v()).optional().describe(`Service names the sandboxed plugin may invoke via IPC`)}).optional()}).describe(`Plugin sandboxing configuration`)),Tu=F(()=>T({enabled:b().default(!1),metrics:w(A([`load-time`,`init-time`,`memory-usage`,`cpu-usage`,`api-calls`,`error-rate`,`cache-hit-rate`])).optional(),samplingRate:y().min(0).max(1).default(1),reportingInterval:y().int().min(1).default(60),budgets:T({maxLoadTimeMs:y().int().min(0).optional(),maxInitTimeMs:y().int().min(0).optional(),maxMemoryMB:y().int().min(0).optional()}).optional(),onBudgetViolation:A([`warn`,`error`,`ignore`]).default(`warn`)}).describe(`Plugin performance monitoring configuration`)),Eu=F(()=>T({strategy:gu.default(`lazy`),preload:_u.optional(),codeSplitting:vu.optional(),dynamicImport:yu.optional(),initialization:bu.optional(),dependencyResolution:xu.optional(),hotReload:Su.optional(),caching:Cu.optional(),sandboxing:wu.optional(),monitoring:Tu.optional()}).describe(`Complete plugin loading configuration`));F(()=>T({type:A([`load-started`,`load-completed`,`load-failed`,`init-started`,`init-completed`,`init-failed`,`preload-started`,`preload-completed`,`cache-hit`,`cache-miss`,`hot-reload`,`dynamic-load`,`dynamic-unload`,`dynamic-discover`]),pluginId:v(),timestamp:y().int().min(0),durationMs:y().int().min(0).optional(),metadata:k(v(),S()).optional(),error:T({message:v(),code:v().optional(),stack:v().optional()}).optional()}).describe(`Plugin loading lifecycle event`)),F(()=>T({pluginId:v(),state:A([`pending`,`loading`,`loaded`,`initializing`,`ready`,`failed`,`reloading`,`unloading`,`unloaded`]),progress:y().min(0).max(100).default(0),startedAt:y().int().min(0).optional(),completedAt:y().int().min(0).optional(),lastError:v().optional(),retryCount:y().int().min(0).default(0)}).describe(`Plugin loading state`)),F(()=>T({ql:T({object:P().describe(`Get object handle for method chaining`),query:P().describe(`Execute a query`)}).passthrough().describe(`ObjectQL Engine Interface`),os:T({getCurrentUser:P().describe(`Get the current authenticated user`),getConfig:P().describe(`Get platform configuration`)}).passthrough().describe(`ObjectStack Kernel Interface`),logger:T({debug:P().describe(`Log debug message`),info:P().describe(`Log info message`),warn:P().describe(`Log warning message`),error:P().describe(`Log error message`)}).passthrough().describe(`Logger Interface`),storage:T({get:P().describe(`Get a value from storage`),set:P().describe(`Set a value in storage`),delete:P().describe(`Delete a value from storage`)}).passthrough().describe(`Storage Interface`),i18n:T({t:P().describe(`Translate a key`),getLocale:P().describe(`Get current locale`)}).passthrough().describe(`Internationalization Interface`),metadata:k(v(),S()),events:k(v(),S()),app:T({router:T({get:P().describe(`Register GET route handler`),post:P().describe(`Register POST route handler`),use:P().describe(`Register middleware`)}).passthrough()}).passthrough().describe(`App Framework Interface`),drivers:T({register:P().describe(`Register a driver`)}).passthrough().describe(`Driver Registry`)})),F(()=>T({previousVersion:v().describe(`Version before upgrade`),newVersion:v().describe(`Version after upgrade`),isMajorUpgrade:b().describe(`Whether this is a major version bump`),previousMetadata:k(v(),S()).optional().describe(`Metadata snapshot before upgrade`)}).describe(`Version migration context for onUpgrade hook`));var Du=F(()=>T({onInstall:P().optional().describe(`Called when plugin is installed`),onEnable:P().optional().describe(`Called when plugin is enabled`),onDisable:P().optional().describe(`Called when plugin is disabled`),onUninstall:P().optional().describe(`Called when plugin is uninstalled`),onUpgrade:P().optional().describe(`Called when plugin is upgraded. Receives UpgradeContext with previousVersion, newVersion, and isMajorUpgrade`)})),Ou=[`ui`,`driver`,`server`,`app`,`theme`,`agent`,`objectql`];F(()=>Du.extend({id:v().min(1).optional().describe(`Unique Plugin ID (e.g. com.example.crm)`),type:A([`standard`,...Ou]).default(`standard`).optional().describe(`Plugin Type categorization for runtime behavior`),staticPath:v().optional().describe(`Absolute path to static assets (Required for type="ui-plugin")`),slug:v().regex(/^[a-z0-9-_]+$/).optional().describe(`URL path segment (Required for type="ui-plugin")`),default:b().optional().describe(`Serve at root path (Only one "ui-plugin" can be default)`),version:v().regex(/^\d+\.\d+\.\d+$/).optional().describe(`Semantic Version`),description:v().optional(),author:v().optional(),homepage:v().url().optional()}));var ku=A([`insert`,`update`,`upsert`,`replace`,`ignore`]),Au=F(()=>T({object:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Target Object Name`),externalId:v().default(`name`).describe(`Field match for uniqueness check`),mode:ku.default(`upsert`).describe(`Conflict resolution strategy`),env:w(A([`prod`,`dev`,`test`])).default([`prod`,`dev`,`test`]).describe(`Applicable environments`),records:w(k(v(),S())).describe(`Data records`)})),ju=F(()=>v().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=F(()=>v().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)`));F(()=>v().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 Mu=A([`cel`,`js`,`cron`,`template`]),Nu=T({rationale:v().optional(),generatedBy:v().optional()}),Pu=T({dialect:Mu,source:v().min(1).optional(),ast:S().optional(),meta:Nu.optional()}).refine(e=>e.source!==void 0||e.ast!==void 0,{message:"Expression requires at least one of `source` or `ast`"}),Fu=E([v().min(1).transform(e=>({dialect:`cel`,source:e})),Pu]),Iu=E([v().min(1).transform(e=>({dialect:`cron`,source:e})),Pu]),Lu=E([v().min(1).transform(e=>({dialect:`template`,source:e})),Pu]);F(()=>T({key:v().describe(`Translation key (e.g., "views.task_list.label")`),defaultValue:v().optional().describe(`Fallback value when translation key is not found`),params:k(v(),E([v(),y(),b()])).optional().describe(`Interpolation parameters (e.g., { count: 5 })`)}));var L=F(()=>v().describe(`Display label (plain string; i18n keys are auto-generated by the framework)`)),Ru=F(()=>T({ariaLabel:L.optional().describe(`Accessible label for screen readers (WAI-ARIA aria-label)`),ariaDescribedBy:v().optional().describe(`ID of element providing additional description (WAI-ARIA aria-describedby)`),role:v().optional().describe(`WAI-ARIA role attribute (e.g., "dialog", "navigation", "alert")`)}).describe(`ARIA accessibility attributes`));F(()=>T({key:v().describe(`Translation key`),zero:v().optional().describe(`Zero form (e.g., "No items")`),one:v().optional().describe(`Singular form (e.g., "{count} item")`),two:v().optional().describe(`Dual form (e.g., "{count} items" for exactly 2)`),few:v().optional().describe(`Few form (e.g., for 2-4 in some languages)`),many:v().optional().describe(`Many form (e.g., for 5+ in some languages)`),other:v().describe(`Default plural form (e.g., "{count} items")`)}).describe(`ICU plural rules for a translation key`));var zu=F(()=>T({style:A([`decimal`,`currency`,`percent`,`unit`]).default(`decimal`).describe(`Number formatting style`),currency:v().optional().describe(`ISO 4217 currency code (e.g., "USD", "EUR")`),unit:v().optional().describe(`Unit for unit formatting (e.g., "kilometer", "liter")`),minimumFractionDigits:y().optional().describe(`Minimum number of fraction digits`),maximumFractionDigits:y().optional().describe(`Maximum number of fraction digits`),useGrouping:b().optional().describe(`Whether to use grouping separators (e.g., 1,000)`)}).describe(`Number formatting rules`)),Bu=F(()=>T({dateStyle:A([`full`,`long`,`medium`,`short`]).optional().describe(`Date display style`),timeStyle:A([`full`,`long`,`medium`,`short`]).optional().describe(`Time display style`),timeZone:v().optional().describe(`IANA time zone (e.g., "America/New_York")`),hour12:b().optional().describe(`Use 12-hour format`)}).describe(`Date/time formatting rules`));F(()=>T({code:v().describe(`BCP 47 language code (e.g., "en-US", "zh-CN")`),fallbackChain:w(v()).optional().describe(`Fallback language codes in priority order (e.g., ["zh-TW", "en"])`),direction:A([`ltr`,`rtl`]).default(`ltr`).describe(`Text direction: left-to-right or right-to-left`),numberFormat:zu.optional().describe(`Default number formatting rules`),dateFormat:Bu.optional().describe(`Default date/time formatting rules`)}).describe(`Locale configuration`));var Vu=F(()=>T({enabled:b().default(!1).describe(`Enable public sharing`),publicLink:v().optional().describe(`Generated public share URL`),password:v().optional().describe(`Password required to access shared link`),allowedDomains:w(v()).optional().describe(`Restrict access to specific email domains (e.g. ["example.com"])`),expiresAt:v().optional().describe(`Expiration date/time in ISO 8601 format`),allowAnonymous:b().optional().default(!1).describe(`Allow access without authentication`)})),Hu=F(()=>T({enabled:b().default(!1).describe(`Enable iframe embedding`),allowedOrigins:w(v()).optional().describe(`Allowed iframe parent origins (e.g. ["https://example.com"])`),width:v().optional().default(`100%`).describe(`Embed width (CSS value)`),height:v().optional().default(`600px`).describe(`Embed height (CSS value)`),showHeader:b().optional().default(!0).describe(`Show interface header in embed`),showNavigation:b().optional().default(!1).describe(`Show navigation in embed`),responsive:b().optional().default(!0).describe(`Enable responsive resizing`)})),Uu=A([`none`,`no-overlay`,`no-delete`,`full`]),Wu=A([`artifact`,`package`,`env-forced`]),Gu=A([`package`,`org`,`env-forced`]),Ku={_lock:Uu.optional().describe(`Item-level lock — controls overlay & delete (ADR-0010).`),_lockReason:v().max(500).optional().describe(`Human-readable reason shown when a write is refused by _lock.`),_lockSource:Wu.optional().describe(`Layer that set _lock (artifact | package | env-forced).`),_provenance:Gu.optional().describe(`Origin of the item (package | org | env-forced).`),_packageId:v().optional().describe(`Owning package machine id.`),_packageVersion:v().optional().describe(`Owning package version.`),_lockDocsUrl:v().optional().describe(`Optional documentation link surfaced next to _lockReason.`)},qu=T({lock:Uu.describe(`Lock policy — none | no-overlay | no-delete | full.`),reason:v().min(1).max(500).describe(`User-visible reason shown when the lock blocks an action.`),docsUrl:v().url().optional().describe(`Optional URL the Studio banner links to for more context.`)}).strict(),Ju=T({id:I.describe(`Unique identifier for this navigation item (lowercase snake_case)`),label:L.describe(`Display proper label`),icon:v().optional().describe(`Icon name`),order:y().optional().describe(`Sort order within the same level (lower = first)`),badge:E([v(),y()]).optional().describe(`Badge text or count displayed on the item`),visible:Fu.optional().describe("Visibility predicate (CEL). e.g. P`'org_admin' in current_user.roles`"),requiredPermissions:w(v()).optional().describe(`Permissions required to access this item`),requiresObject:v().optional().describe(`Hide/disable this entry unless the named object is registered in the runtime`),requiresService:v().optional().describe(`Hide/disable this entry unless the named kernel service is registered`)}),Yu=F(()=>Ju.extend({type:j(`object`),objectName:v().describe(`Target object name`),viewName:v().optional().describe('Default list view to open. Defaults to "all". Ignored when `recordId` is set.'),recordId:v().optional().describe(`Navigate directly to this record id instead of the list view. Supports template vars: {current_user_id}, {current_org_id}.`),recordMode:A([`view`,`edit`]).optional().describe("Open the record in view (default) or edit mode. Only meaningful when `recordId` is set.")})),Xu=F(()=>Ju.extend({type:j(`dashboard`),dashboardName:v().describe(`Target dashboard name`)})),Zu=F(()=>Ju.extend({type:j(`page`),pageName:v().describe(`Target custom page component name`),params:k(v(),S()).optional().describe(`Parameters passed to the page context`)})),Qu=F(()=>Ju.extend({type:j(`url`),url:v().describe(`Target external URL`),target:A([`_self`,`_blank`]).default(`_self`).describe(`Link target window`)})),$u=F(()=>Ju.extend({type:j(`report`),reportName:v().describe(`Target report name`)})),ed=F(()=>Ju.extend({type:j(`action`),actionDef:T({actionName:v().describe(`Action machine name to execute`),params:k(v(),S()).optional().describe(`Parameters passed to the action`)}).describe(`Action definition to execute when clicked`)})),td=F(()=>Ju.extend({type:j(`component`),componentRef:v().describe(`Component registry key (e.g. "metadata:directory")`),params:k(v(),S()).optional().describe(`Props passed to the component`)})),nd=F(()=>Ju.extend({type:j(`group`),expanded:b().default(!1).describe(`Default expansion state in sidebar`)})),rd=M(()=>E([Yu.extend({children:w(rd).optional().describe(`Child navigation items (e.g. specific views)`)}),Xu,Zu,Qu,$u,ed,td,nd.extend({children:w(rd).describe(`Child navigation items`)})])),id=F(()=>T({app:I.describe(`Target app name to contribute navigation into (e.g. "setup")`),group:I.optional().describe(`Target group nav-item id to append into (e.g. "group_integrations"); omit to append at the app top level`),priority:y().int().min(0).default(200).describe(`Merge priority within the target group — lower applied first (matches object extender priority)`),items:w(rd).describe(`Navigation items contributed into the target app/group`)}).describe(`A navigation contribution: a package injecting nav items into an app it does not own (ADR-0029 D7)`)),ad=F(()=>T({primaryColor:v().optional().describe(`Primary theme color hex code`),logo:v().optional().describe(`Custom logo URL for this app`),favicon:v().optional().describe(`Custom favicon URL for this app`)})),od=F(()=>T({id:I.describe(`Unique area identifier (lowercase snake_case)`),label:L.describe(`Area display label`),icon:v().optional().describe(`Area icon name`),order:y().optional().describe(`Sort order among areas (lower = first)`),description:L.optional().describe(`Area description`),visible:Fu.optional().describe(`Visibility predicate (CEL) for this area.`),requiredPermissions:w(v()).optional().describe(`Permissions required to access this area`),navigation:w(rd).describe(`Navigation items within this area`)})),sd=F(()=>T({id:I.describe(`Selector id; selected value is exposed as the nav template var {<id>}`),label:L.describe(`Dropdown label`),icon:v().optional().describe(`Icon name`),optionsSource:T({endpoint:v().describe(`REST endpoint returning the option rows (e.g. /api/v1/packages)`),valueKey:v().default(`id`).describe(`Row property used as the option value (dotted path allowed, e.g. "manifest.id")`),labelKey:v().default(`name`).describe(`Row property used as the option label (dotted path allowed, e.g. "manifest.name")`),filter:w(T({key:v().describe(`Dotted path on each row to compare (e.g. "manifest.scope")`),op:A([`eq`,`ne`,`in`,`nin`]).default(`eq`).describe(`Comparison operator: eq | ne | in | nin`),value:E([v(),w(v())]).describe(`Comparison value (string for eq/ne, string[] for in/nin)`)})).optional().describe(`Predicates (AND) each option row must satisfy`)}).describe(`Option data source`),includeAll:b().default(!0).describe(`Prepend an "All" option that clears the scope`),allValue:v().default(``).describe(`Template value when "All" is selected (empty = no filter)`),persist:A([`query`,`session`,`none`]).default(`query`).describe(`Persist selection via URL query, sessionStorage, or not at all`),placement:A([`sidebar_header`,`topbar`]).default(`sidebar_header`).describe(`Render location in the app chrome`)})),cd=F(()=>T({name:I.describe(`App unique machine name (lowercase snake_case)`),label:L.describe(`App display label`),version:v().optional().describe(`App version`),description:L.optional().describe(`App description`),icon:v().optional().describe(`App icon used in the App Launcher`),branding:ad.optional().describe(`App-specific branding`),active:b().optional().default(!0).describe(`Whether the app is enabled`),isDefault:b().optional().default(!1).describe(`Is default app`),hidden:b().optional().describe(`Hide from the App Switcher; the shell surfaces hidden apps via the avatar menu instead`),navigation:w(rd).optional().describe(`Full navigation tree for the app sidebar`),areas:w(od).optional().describe(`Navigation areas for partitioning navigation by business domain`),contextSelectors:w(sd).optional().describe(`App-level scope dropdowns whose value is injected into nav items as {<id>} template vars`),homePageId:v().optional().describe(`ID of the navigation item to serve as landing page`),requiredPermissions:w(v()).optional().describe(`Permissions required to access this app`),objects:w(S()).optional().describe(`Objects belonging to this app`),apis:w(S()).optional().describe(`Custom APIs belonging to this app`),sharing:Vu.optional().describe(`Public sharing configuration`),embed:Hu.optional().describe(`Iframe embedding configuration`),mobileNavigation:T({mode:A([`drawer`,`bottom_nav`,`hamburger`]).default(`drawer`).describe(`Mobile navigation mode: drawer sidebar, bottom navigation bar, or hamburger menu`),bottomNavItems:w(v()).optional().describe(`Navigation item IDs to show in bottom nav (max 5)`)}).optional().describe(`Mobile-specific navigation configuration`),defaultAgent:I.optional().describe(`Name of the default AI agent for this app (used by the ambient chat endpoint)`),aria:Ru.optional().describe(`ARIA accessibility attributes for the application`),protection:qu.optional().describe(`Package author protection block — lock policy for this app.`),...Ku})),ld=T({services:w(v()).optional().describe(`Platform services the plugin may resolve (e.g. "object", "http")`),hooks:w(v()).optional().describe(`Lifecycle hooks the plugin may register (e.g. "record.beforeInsert")`),network:w(v()).optional().describe(`Network hosts the plugin may reach (e.g. "api.acme.com")`),fs:w(v()).optional().describe(`Filesystem paths the plugin may access`)}).strict().describe(`Structured plugin permission grants (ADR-0025 §3.2)`),ud=E([w(v()),ld]),dd=T({platform:v().optional().describe(`ObjectStack platform release range (SemVer, e.g. ">=4.0 <5")`),protocol:v().optional().describe(`Runtime/metadata protocol range, checked first (ADR §3.10 #3)`)}).describe(`Plugin compatibility ranges (ADR-0025 §3.2)`),fd=A([`node`,`sandbox`,`worker`]).describe(`Plugin trust tier (ADR-0025 §3.6)`),pd=A([`bundled`,`manifest-deps`]).describe(`Dependency packaging strategy (ADR-0025 §3.3)`),md=k(v(),v()).describe(`Per-file content digests of the plugin artifact (ADR-0025 §3.2)`),hd=T({id:v().describe(`Unique package identifier (reverse domain style)`),namespace:v().regex(/^[a-z][a-z0-9_]{1,19}$/,`Namespace must be 2-20 chars, lowercase alphanumeric + underscore`).optional().describe(`Short namespace identifier; also the mandatory prefix of every object name (e.g. "todo" → object names "todo_task", "todo_project")`),defaultDatasource:v().optional().default(`default`).describe(`Default datasource for all objects in this package`),version:v().regex(/^\d+\.\d+\.\d+$/).describe(`Package version (semantic versioning)`),type:A([`plugin`,...Ou,`module`,`gateway`,`adapter`]).describe(`Type of package`),scope:A([`cloud`,`system`,`project`]).default(`project`).describe(`Deployment scope: cloud | system | project`),name:v().describe(`Human-readable package name`),description:v().optional().describe(`Package description`),permissions:ud.optional().describe(`Required permissions: legacy string[] or structured plugin block (ADR-0025 §3.2)`),objects:w(v()).optional().describe(`Glob patterns for ObjectQL schemas files`),datasources:w(v()).optional().describe(`Glob patterns for Datasource definitions`),dependencies:k(v(),v()).optional().describe(`Package dependencies`),configuration:T({title:v().optional(),properties:k(v(),T({type:A([`string`,`number`,`boolean`,`array`,`object`]).describe(`Data type of the setting`),default:S().optional().describe(`Default value`),description:v().optional().describe(`Tooltip description`),required:b().optional().describe(`Is this setting required?`),secret:b().optional().describe(`If true, value is encrypted/masked (e.g. API Keys)`),enum:w(v()).optional().describe(`Allowed values for select inputs`)})).describe(`Map of configuration keys to their definitions`)}).optional().describe(`Plugin configuration settings`),contributes:T({kinds:w(T({id:v().describe(`The generic identifier of the kind (e.g., "sys.bi.report")`),globs:w(v()).describe(`File patterns to watch (e.g., ["**/*.report.ts"])`),description:v().optional().describe(`Description of what this kind represents`)})).optional().describe(`New Metadata Types to recognize`),events:w(v()).optional().describe(`Events this plugin listens to`),menus:k(v(),w(T({id:v(),label:v(),command:v().optional()}))).optional().describe(`UI Menu contributions`),themes:w(T({id:v(),label:v(),path:v()})).optional().describe(`Theme contributions`),translations:w(T({locale:v(),path:v()})).optional().describe(`Translation resources`),actions:w(T({name:v().describe(`Unique action name`),label:v().optional(),description:v().optional(),input:S().optional().describe(`Input validation schema`),output:S().optional().describe(`Output schema`)})).optional().describe(`Exposed server actions`),drivers:w(T({id:v().describe(`Driver unique identifier (e.g. "postgres", "mongo")`),label:v().describe(`Human readable name`),description:v().optional()})).optional().describe(`Driver contributions`),fieldTypes:w(T({name:v().describe(`Unique field type name (e.g. "vector")`),label:v().describe(`Display label`),description:v().optional()})).optional().describe(`Field Type contributions`),functions:w(T({name:v().describe(`Function name (e.g. "distance")`),description:v().optional(),args:w(v()).optional().describe(`Argument types`),returnType:v().optional()})).optional().describe(`Query Function contributions`),routes:w(T({prefix:v().regex(/^\//).describe(`API path prefix`),service:v().describe(`Service name this plugin provides`),methods:w(v()).optional().describe(`Protocol method names implemented (e.g. ["aiNlq", "aiChat"])`)})).optional().describe(`API route contributions to HttpDispatcher`),commands:w(T({name:v().regex(/^[a-z][a-z0-9-]*$/,`Command name must be lowercase alphanumeric with hyphens`).describe(`CLI command name`),description:v().optional().describe(`Command description for help text`),module:v().optional().describe(`Module path exporting Commander.js commands`)})).optional().describe(`CLI command contributions`)}).optional().describe(`Platform contributions`),data:w(Au).optional().describe(`Initial seed data (prefer top-level data field)`),capabilities:hu.optional().describe(`Plugin capability declarations for interoperability`),extensions:k(v(),S()).optional().describe(`Extension points and contributions`),navigationContributions:w(id).optional().describe(`Navigation items this package contributes into apps owned by other packages`),loading:Eu.optional().describe(`Plugin loading and runtime behavior configuration`),engine:T({objectstack:v().regex(/^[><=~^]*\d+\.\d+\.\d+/).describe(`ObjectStack platform version requirement (SemVer range, e.g. ">=3.0.0")`)}).optional().describe("Platform compatibility requirements (legacy; superseded by `engines`)"),engines:dd.optional().describe("Plugin compatibility ranges (ADR-0025 §3.2; supersedes `engine`)"),runtime:fd.optional().describe(`Plugin trust tier (ADR-0025 §3.6)`),packaging:pd.optional().describe(`Dependency packaging strategy (ADR-0025 §3.3)`),integrity:md.optional().describe(`Per-file content digests of the plugin artifact (ADR-0025 §3.2)`)}),gd=A([`local`,`cluster`,`tenant`]).describe(`Where the event must be delivered: local process, whole cluster, or tenant-scoped.`),_d=A([`best-effort`,`at-least-once`,`exactly-once`]).describe(`Delivery guarantee offered by the transport.`);F(()=>T({scope:gd.optional().default(`local`).describe("Delivery scope. Default `local` for backward compatibility."),deliverySemantics:_d.optional().describe(`Delivery guarantee. Default depends on scope.`),partitionKey:v().min(1).optional().describe(`Stable key that guarantees emit-order delivery for same-key events.`)}).describe(`Per-emit cluster routing & ordering options.`));var vd=A([`node`,`cluster`]).describe(`Whether this service runs on every node or as a cluster singleton.`),yd=A([`leader-elected`,`partitioned`,`idempotent-broadcast`]).describe(`How the cluster-singleton invariant is enforced at runtime.`);F(()=>T({clusterScope:vd.optional().default(`node`).describe(`Per-node vs cluster-singleton presence.`),leaderStrategy:yd.optional().describe(`How the cluster-singleton invariant is maintained.`),clusterId:v().min(1).optional().describe(`Logical cluster identity used for leader election (defaults to service name).`)}).describe(`Service-registration annotations governing cluster behaviour.`));var bd=A([`memory`,`redis`,`postgres`,`nats`,`custom`]).describe(`Cluster transport driver.`),xd=A([`channel-prefix`,`none`]).describe(`How tenant traffic is separated on shared transports.`),Sd=F(()=>T({driver:bd.optional().default(`memory`).describe(`Cluster transport driver. Defaults to in-memory single-process.`),url:v().url().optional().describe(`Driver-specific connection URL.`),useExistingPool:b().optional().default(!0).describe(`Reuse the main DB pool for the postgres driver.`),nodeId:v().min(1).optional().describe(`Stable node identifier. Auto-generated when absent.`),heartbeatMs:y().int().min(100).optional().default(5e3).describe(`Leader-election heartbeat interval in milliseconds.`),lockTtlMs:y().int().min(100).optional().default(15e3).describe(`Leader-election lock TTL in milliseconds (≥ 3× heartbeatMs).`),tenantIsolation:xd.optional().default(`channel-prefix`).describe(`Channel/key namespacing strategy for multi-tenant deployments.`),driverOptions:k(v(),S()).optional().describe(`Driver-specific opaque options.`)}).describe(`Cluster capability configuration for the stack.`)),Cd=A([`create`,`update`,`delete`,`publish`]).describe(`Persistence operation that triggered the change.`);F(()=>T({type:v().min(1).describe(`Metadata type (e.g. "object", "view").`),name:v().min(1).describe(`Machine name of the metadata item.`),tenantId:v().optional().describe(`Tenant id when the change is overlay-scoped.`),version:cl().describe(`Monotonic version of the record after the change.`),operation:Cd,correlationId:v().optional().describe(`Trace correlation id of the originating request.`)}).describe(`Canonical payload for the metadata:changed cluster event.`));var wd=v().describe(`Underlying driver identifier`);F(()=>T({id:v().describe(`Unique driver identifier (e.g. "postgres")`),label:v().describe(`Display label (e.g. "PostgreSQL")`),description:v().optional(),icon:v().optional(),configSchema:k(v(),S()).describe(`JSON Schema for connection configuration`),capabilities:M(()=>Td).optional()}));var Td=T({transactions:b().default(!1),queryFilters:b().default(!1),queryAggregations:b().default(!1),querySorting:b().default(!1),queryPagination:b().default(!1),queryWindowFunctions:b().default(!1),querySubqueries:b().default(!1),joins:b().default(!1),fullTextSearch:b().default(!1),readOnly:b().default(!1),dynamicSchema:b().default(!1)}),Ed=A([`managed`,`external`,`validate-only`]).describe(`Schema ownership mode`),Dd=T({label:v().optional().describe(`Display label, e.g. "Snowflake — ANALYTICS / PROD"`),allowedSchemas:w(v()).optional().describe(`Whitelist of remote schemas/databases that may be exposed.`),allowWrites:b().default(!1).describe(`Global write gate. Individual objects must also opt in via object.external.writable.`),validation:T({onMismatch:A([`fail`,`warn`,`ignore`]).default(`fail`).describe(`What to do when a federated object diverges from the remote table.`),checkOnBoot:b().default(!0).describe(`Validate federated objects against the remote schema at boot.`),checkIntervalMs:y().optional().describe(`Optional background drift-check interval in milliseconds.`)}).default({onMismatch:`fail`,checkOnBoot:!0}).describe(`Boot/drift validation policy`),credentialsRef:v().optional().describe(`Reference into the secrets store; never inline credentials.`),queryTimeoutMs:y().default(3e4).describe(`Hard cap on per-query execution time.`),requirePermission:v().optional().describe(`Optional convenience: gate the entire datasource behind a single role.`)}).describe(`External datasource federation settings (schemaMode != "managed")`),Od=F(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Unique datasource identifier`),label:v().optional().describe(`Display label`),driver:wd.describe(`Underlying driver type`),config:k(v(),S()).describe(`Driver specific configuration`),pool:T({min:y().default(0).describe(`Minimum connections`),max:y().default(10).describe(`Maximum connections`),idleTimeoutMillis:y().default(3e4).describe(`Idle timeout`),connectionTimeoutMillis:y().default(3e3).describe(`Connection establishment timeout`)}).optional().describe(`Connection pool settings`),readReplicas:w(k(v(),S())).optional().describe(`Read-only replica configurations`),capabilities:Td.optional().describe(`Capability overrides`),healthCheck:T({enabled:b().default(!0).describe(`Enable health check endpoint`),intervalMs:y().default(3e4).describe(`Health check interval in milliseconds`),timeoutMs:y().default(5e3).describe(`Health check timeout in milliseconds`)}).optional().describe(`Datasource health check configuration`),ssl:T({enabled:b().default(!1).describe(`Enable SSL/TLS for database connection`),rejectUnauthorized:b().default(!0).describe(`Reject connections with invalid/self-signed certificates`),ca:v().optional().describe(`CA certificate (PEM format or path to file)`),cert:v().optional().describe(`Client certificate (PEM format or path to file)`),key:v().optional().describe(`Client private key (PEM format or path to file)`)}).optional().describe(`SSL/TLS configuration for secure database connections`),retryPolicy:T({maxRetries:y().default(3).describe(`Maximum number of retry attempts`),baseDelayMs:y().default(1e3).describe(`Base delay between retries in milliseconds`),maxDelayMs:y().default(3e4).describe(`Maximum delay between retries in milliseconds`),backoffMultiplier:y().default(2).describe(`Exponential backoff multiplier`)}).optional().describe(`Connection retry policy for transient failures`),description:v().optional().describe(`Internal description`),active:b().default(!0).describe(`Is datasource enabled`),autoConnect:b().default(!1).describe(`Force a live driver connection at boot even when managed + unrouted (ADR-0062 D2).`),schemaMode:Ed.default(`managed`),external:Dd.optional(),origin:A([`code`,`runtime`]).default(`code`).describe(`Datasource provenance (server-managed, read-only)`)}).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'.`})})),kd=F(()=>v().describe(`BCP-47 Language Tag (e.g. en-US, zh-CN)`)),Ad=F(()=>T({label:v().optional().describe(`Translated field label`),help:v().optional().describe(`Translated help text`),placeholder:v().optional().describe(`Translated placeholder text for form inputs`),options:k(v(),v()).optional().describe(`Option value to translated label map`)}).describe(`Translation data for a single field`)),jd=F(()=>T({label:v().describe(`Translated singular label`),pluralLabel:v().optional().describe(`Translated plural label`),description:v().optional().describe(`Translated object description`),fields:k(v(),Ad).optional().describe(`Field-level translations`),_views:k(v(),T({label:v().optional().describe(`Translated view label`),description:v().optional().describe(`Translated view description`)})).optional().describe(`View translations keyed by view name`),_actions:k(v(),T({label:v().optional().describe(`Translated action label`),confirmText:v().optional().describe(`Translated confirmation prompt`),successMessage:v().optional().describe(`Translated success toast/message`),params:k(v(),T({label:v().optional().describe(`Translated action parameter label`),helpText:v().optional().describe(`Translated action parameter help/hint text`),placeholder:v().optional().describe(`Translated action parameter placeholder`),options:k(v(),v()).optional().describe(`Param select option value to translated label`)})).optional().describe(`Action parameter translations keyed by parameter name`)})).optional().describe(`Action translations keyed by action name`),_sections:k(v(),T({label:v().optional().describe(`Translated section label`),description:v().optional().describe(`Translated section description`)})).optional().describe(`Section translations keyed by section name`)}).describe(`Translation data for a single object`)),Md=F(()=>T({objects:k(v(),jd).optional().describe(`Object translations keyed by object name`),apps:k(v(),T({label:v().describe(`Translated app label`),description:v().optional().describe(`Translated app description`),navigation:k(v(),T({label:v().describe(`Translated navigation group label`)})).optional().describe(`Navigation group translations keyed by group ID`)})).optional().describe(`App translations keyed by app name`),messages:k(v(),v()).optional().describe(`UI message translations keyed by message ID`),validationMessages:k(v(),v()).optional().describe(`Translatable validation error messages keyed by rule name (e.g., {"discount_limit": "折扣不能超过40%"})`),globalActions:k(v(),T({label:v().optional().describe(`Translated action label`),confirmText:v().optional().describe(`Translated confirmation prompt`),successMessage:v().optional().describe(`Translated success toast/message`),params:k(v(),T({label:v().optional().describe(`Translated action parameter label`),helpText:v().optional().describe(`Translated action parameter help/hint text`),placeholder:v().optional().describe(`Translated action parameter placeholder`),options:k(v(),v()).optional().describe(`Param select option value to translated label`)})).optional().describe(`Action parameter translations keyed by parameter name`)})).optional().describe(`Global action translations keyed by action name`),dashboards:k(v(),T({label:v().optional().describe(`Translated dashboard title`),description:v().optional().describe(`Translated dashboard description`),actions:k(v(),T({label:v().optional().describe(`Translated header action label`)})).optional().describe(`Header action label translations keyed by action url/key`),widgets:k(v(),T({title:v().optional().describe(`Translated widget title`),description:v().optional().describe(`Translated widget description`)})).optional().describe(`Widget translations keyed by widget id`)})).optional().describe(`Dashboard translations keyed by dashboard name`),settings:k(v(),T({title:v().optional().describe(`Translated settings manifest title`),description:v().optional().describe(`Translated settings manifest description`),groups:k(v(),T({title:v().optional().describe(`Translated group title`),description:v().optional().describe(`Translated group description`)})).optional().describe(`Group translations keyed by group key`),keys:k(v(),T({label:v().optional().describe(`Translated setting label`),help:v().optional().describe(`Translated setting help text`),placeholder:v().optional().describe(`Translated input placeholder`),options:k(v(),v()).optional().describe(`Enum option value → translated label`)})).optional().describe(`Per-setting field translations keyed by setting key`),actions:k(v(),T({label:v().optional().describe(`Translated action label`),confirmText:v().optional().describe(`Translated confirmation prompt`),successMessage:v().optional().describe(`Translated success toast/message`)})).optional().describe(`Action button translations keyed by action id`)})).optional().describe(`Settings manifest translations keyed by namespace`),metadataForms:k(v(),T({label:v().optional().describe(`Translated metadata-type display label (overrides registry label)`),description:v().optional().describe(`Translated metadata-type description`),sections:k(v(),T({label:v().optional().describe(`Translated section label`),description:v().optional().describe(`Translated section description`)})).optional().describe(`Section translations keyed by section.name`),fields:k(v(),T({label:v().optional().describe(`Translated field label`),helpText:v().optional().describe(`Translated field help/hint text`),placeholder:v().optional().describe(`Translated field placeholder text`)})).optional().describe(`Field translations keyed by field path (dot-notation for nested fields)`)})).optional().describe(`Translations for metadata-type configuration forms keyed by metadata type`),settingsCommon:T({sourceLabels:T({env:v().optional(),global:v().optional(),tenant:v().optional(),user:v().optional(),default:v().optional()}).optional().describe(`Source badge labels by resolution layer`)}).optional().describe(`Cross-namespace Settings UI strings`)}).describe(`Translation data for objects, apps, and UI messages`)),Nd=F(()=>k(kd,Md).describe(`Map of locale codes to translation data`)),Pd=F(()=>A([`bundled`,`per_locale`,`per_namespace`]).describe(`Translation file organization strategy`)),Fd=F(()=>A([`icu`,`simple`]).describe(`Message interpolation format: ICU MessageFormat or simple {variable} replacement`)),Id=F(()=>T({defaultLocale:kd.describe(`Default locale (e.g., "en")`),supportedLocales:w(kd).describe(`Supported BCP-47 locale codes`),fallbackLocale:kd.optional().describe(`Fallback locale code`),fileOrganization:Pd.default(`per_locale`).describe(`File organization strategy`),messageFormat:Fd.default(`simple`).describe(`Message interpolation format (ICU MessageFormat or simple)`),lazyLoad:b().default(!1).describe(`Load translations on demand`),cache:b().default(!0).describe(`Cache loaded translations`)}).describe(`Internationalization configuration`)),Ld=k(v(),v()).describe(`Option value to translated label map`),Rd=F(()=>T({label:v().describe(`Translated singular label`),pluralLabel:v().optional().describe(`Translated plural label`),description:v().optional().describe(`Translated object description`),helpText:v().optional().describe(`Translated help text for the object`),fields:k(v(),Ad).optional().describe(`Field translations keyed by field name`),_options:k(v(),Ld).optional().describe(`Object-scoped picklist option translations keyed by field name`),_views:k(v(),T({label:v().optional().describe(`Translated view label`),description:v().optional().describe(`Translated view description`)})).optional().describe(`View translations keyed by view name`),_sections:k(v(),T({label:v().optional().describe(`Translated section label`)})).optional().describe(`Section translations keyed by section name`),_actions:k(v(),T({label:v().optional().describe(`Translated action label`),confirmMessage:v().optional().describe(`Translated confirmation message`),params:k(v(),T({label:v().optional().describe(`Translated action parameter label`),helpText:v().optional().describe(`Translated action parameter help/hint text`),placeholder:v().optional().describe(`Translated action parameter placeholder`),options:k(v(),v()).optional().describe(`Param select option value to translated label`)})).optional().describe(`Action parameter translations keyed by parameter name`)})).optional().describe(`Action translations keyed by action name`),_notifications:k(v(),T({title:v().optional().describe(`Translated notification title`),body:v().optional().describe(`Translated notification body (supports ICU MessageFormat when enabled)`)})).optional().describe(`Notification translations keyed by notification name`),_errors:k(v(),v()).optional().describe(`Error message translations keyed by error code`)}).describe(`Object-first aggregated translation node`));F(()=>T({_meta:T({locale:v().optional().describe(`BCP-47 locale code for this bundle`),direction:A([`ltr`,`rtl`]).optional().describe(`Text direction: left-to-right or right-to-left`)}).optional().describe(`Bundle-level metadata (locale, bidi direction)`),namespace:v().optional().describe(`Namespace for plugin isolation to avoid translation key collisions`),o:k(v(),Rd).optional().describe(`Object-first translations keyed by object name`),_globalOptions:k(v(),Ld).optional().describe(`Global picklist option translations keyed by option set name`),app:k(v(),T({label:v().describe(`Translated app label`),description:v().optional().describe(`Translated app description`)})).optional().describe(`App translations keyed by app name`),nav:k(v(),v()).optional().describe(`Navigation item translations keyed by nav item name`),dashboard:k(v(),T({label:v().optional().describe(`Translated dashboard label`),description:v().optional().describe(`Translated dashboard description`)})).optional().describe(`Dashboard translations keyed by dashboard name`),reports:k(v(),T({label:v().optional().describe(`Translated report label`),description:v().optional().describe(`Translated report description`)})).optional().describe(`Report translations keyed by report name`),pages:k(v(),T({title:v().optional().describe(`Translated page title`),description:v().optional().describe(`Translated page description`)})).optional().describe(`Page translations keyed by page name`),messages:k(v(),v()).optional().describe(`UI message translations keyed by message ID (supports ICU MessageFormat)`),validationMessages:k(v(),v()).optional().describe(`Validation error message translations keyed by rule name (supports ICU MessageFormat)`),notifications:k(v(),T({title:v().optional().describe(`Translated notification title`),body:v().optional().describe(`Translated notification body (supports ICU MessageFormat when enabled)`)})).optional().describe(`Global notification translations keyed by notification name`),errors:k(v(),v()).optional().describe(`Global error message translations keyed by error code`)}).describe(`Object-first application translation bundle for a single locale`));var zd=F(()=>A([`missing`,`redundant`,`stale`]).describe(`Translation diff status: missing from bundle, redundant (no matching metadata), or stale (metadata changed)`)),Bd=F(()=>T({key:v().describe(`Dot-path translation key`),status:zd.describe(`Diff status of this translation key`),objectName:v().optional().describe(`Associated object name (snake_case)`),locale:v().describe(`BCP-47 locale code`),sourceHash:v().optional().describe(`Hash of source metadata for precise stale detection`),aiSuggested:v().optional().describe(`AI-suggested translation for this key`),aiConfidence:y().min(0).max(1).optional().describe(`AI suggestion confidence score (0–1)`)}).describe(`A single translation diff item`)),Vd=F(()=>T({group:v().describe(`Translation group category`),totalKeys:y().int().nonnegative().describe(`Total keys in this group`),translatedKeys:y().int().nonnegative().describe(`Translated keys in this group`),coveragePercent:y().min(0).max(100).describe(`Coverage percentage for this group`)}).describe(`Coverage breakdown for a single translation group`));F(()=>T({locale:v().describe(`BCP-47 locale code`),objectName:v().optional().describe(`Object name scope (omit for full bundle)`),totalKeys:y().int().nonnegative().describe(`Total translatable keys from metadata`),translatedKeys:y().int().nonnegative().describe(`Number of translated keys`),missingKeys:y().int().nonnegative().describe(`Number of missing translations`),redundantKeys:y().int().nonnegative().describe(`Number of redundant translations`),staleKeys:y().int().nonnegative().describe(`Number of stale translations`),coveragePercent:y().min(0).max(100).describe(`Translation coverage percentage`),items:w(Bd).describe(`Detailed diff items`),breakdown:w(Vd).optional().describe(`Per-group coverage breakdown`)}).describe(`Aggregated translation coverage result`));var Hd=A(`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(`.`)),Ud=F(()=>T({label:v().describe(`Display label (human-readable, any case allowed)`),value:ju.describe(`Stored value (lowercase machine identifier)`),color:v().optional().describe(`Color code for badges/charts`),default:b().optional().describe(`Is default option`)}));F(()=>T({latitude:y().min(-90).max(90).describe(`Latitude coordinate`),longitude:y().min(-180).max(180).describe(`Longitude coordinate`),altitude:y().optional().describe(`Altitude in meters`),accuracy:y().optional().describe(`Accuracy in meters`)}));var Wd=F(()=>T({precision:y().int().min(0).max(10).default(2).describe(`Decimal precision (default: 2)`),currencyMode:A([`dynamic`,`fixed`]).default(`dynamic`).describe(`Currency mode: dynamic (user selectable) or fixed (single currency)`),defaultCurrency:v().length(3).default(`CNY`).describe(`Default or fixed currency code (ISO 4217, e.g., USD, CNY, EUR)`)}));F(()=>T({value:y().describe(`Monetary amount`),currency:v().length(3).describe(`Currency code (ISO 4217)`)})),F(()=>T({street:v().optional().describe(`Street address`),city:v().optional().describe(`City name`),state:v().optional().describe(`State/Province`),postalCode:v().optional().describe(`Postal/ZIP code`),country:v().optional().describe(`Country name or code`),countryCode:v().optional().describe(`ISO country code (e.g., US, GB)`),formatted:v().optional().describe(`Formatted address string`)}));var Gd=F(()=>T({dimensions:y().int().min(1).max(1e4).describe(`Vector dimensionality (e.g., 1536 for OpenAI embeddings)`),distanceMetric:A([`cosine`,`euclidean`,`dotProduct`,`manhattan`]).default(`cosine`).describe(`Distance/similarity metric for vector search`),normalized:b().default(!1).describe(`Whether vectors are normalized (unit length)`),indexed:b().default(!0).describe(`Whether to create a vector index for fast similarity search`),indexType:A([`hnsw`,`ivfflat`,`flat`]).optional().describe(`Vector index algorithm (HNSW for high accuracy, IVFFlat for large datasets)`)})),Kd=F(()=>T({minSize:y().min(0).optional().describe(`Minimum file size in bytes`),maxSize:y().min(1).optional().describe(`Maximum file size in bytes (e.g., 10485760 = 10MB)`),allowedTypes:w(v()).optional().describe(`Allowed file extensions (e.g., [".pdf", ".docx", ".jpg"])`),blockedTypes:w(v()).optional().describe(`Blocked file extensions (e.g., [".exe", ".bat", ".sh"])`),allowedMimeTypes:w(v()).optional().describe(`Allowed MIME types (e.g., ["image/jpeg", "application/pdf"])`),blockedMimeTypes:w(v()).optional().describe(`Blocked MIME types`),virusScan:b().default(!1).describe(`Enable virus scanning for uploaded files`),virusScanProvider:A([`clamav`,`virustotal`,`metadefender`,`custom`]).optional().describe(`Virus scanning service provider`),virusScanOnUpload:b().default(!0).describe(`Scan files immediately on upload`),quarantineOnThreat:b().default(!0).describe(`Quarantine files if threat detected`),storageProvider:v().optional().describe(`Object storage provider name (references ObjectStorageConfig)`),storageBucket:v().optional().describe(`Target bucket name`),storagePrefix:v().optional().describe(`Storage path prefix (e.g., "uploads/documents/")`),imageValidation:T({minWidth:y().min(1).optional().describe(`Minimum image width in pixels`),maxWidth:y().min(1).optional().describe(`Maximum image width in pixels`),minHeight:y().min(1).optional().describe(`Minimum image height in pixels`),maxHeight:y().min(1).optional().describe(`Maximum image height in pixels`),aspectRatio:v().optional().describe(`Required aspect ratio (e.g., "16:9", "1:1")`),generateThumbnails:b().default(!1).describe(`Auto-generate thumbnails`),thumbnailSizes:w(T({name:v().describe(`Thumbnail variant name (e.g., "small", "medium", "large")`),width:y().min(1).describe(`Thumbnail width in pixels`),height:y().min(1).describe(`Thumbnail height in pixels`),crop:b().default(!1).describe(`Crop to exact dimensions`)})).optional().describe(`Thumbnail size configurations`),preserveMetadata:b().default(!1).describe(`Preserve EXIF metadata`),autoRotate:b().default(!0).describe(`Auto-rotate based on EXIF orientation`)}).optional().describe(`Image-specific validation rules`),allowMultiple:b().default(!1).describe(`Allow multiple file uploads (overrides field.multiple)`),allowReplace:b().default(!0).describe(`Allow replacing existing files`),allowDelete:b().default(!0).describe(`Allow deleting uploaded files`),requireUpload:b().default(!1).describe(`Require at least one file when field is required`),extractMetadata:b().default(!0).describe(`Extract file metadata (name, size, type, etc.)`),extractText:b().default(!1).describe(`Extract text content from documents (OCR/parsing)`),versioningEnabled:b().default(!1).describe(`Keep previous versions of replaced files`),maxVersions:y().min(1).optional().describe(`Maximum number of versions to retain`),publicRead:b().default(!1).describe(`Allow public read access to uploaded files`),presignedUrlExpiry:y().min(60).max(604800).default(3600).describe(`Presigned URL expiration in seconds (default: 1 hour)`)}).refine(e=>!(e.minSize!==void 0&&e.maxSize!==void 0&&e.minSize>e.maxSize),{message:`minSize must be less than or equal to maxSize`}).refine(e=>!(e.virusScanProvider!==void 0&&e.virusScan!==!0),{message:`virusScanProvider requires virusScan to be enabled`}));F(()=>T({uniqueness:b().default(!1).describe(`Enforce unique values across all records`),completeness:y().min(0).max(1).default(0).describe(`Minimum ratio of non-null values (0-1, default: 0 = no requirement)`),accuracy:T({source:v().describe(`Reference data source for validation (e.g., "api.verify.com", "master_data")`),threshold:y().min(0).max(1).describe(`Minimum accuracy threshold (0-1, e.g., 0.95 = 95% match required)`)}).optional().describe(`Accuracy validation configuration`)})),F(()=>T({enabled:b().describe(`Enable caching for computed field results`),ttl:y().min(0).describe(`Cache TTL in seconds (0 = no expiration)`),invalidateOn:w(v()).describe(`Field paths that invalidate cache (e.g., ["inventory.quantity", "pricing.base_price"])`)}));var qd=F(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Machine name (snake_case)`).optional(),label:v().optional().describe(`Human readable label`),type:Hd.describe(`Field Data Type`),description:v().optional().describe(`Tooltip/Help text`),format:v().optional().describe(`Format string (e.g. email, phone)`),columnName:v().optional().describe(`Physical column name in the target datasource. Defaults to the field key when not set.`),required:b().default(!1).describe(`Is required`),searchable:b().default(!1).describe(`Is searchable`),multiple:b().default(!1).describe(`Allow multiple values (Stores as Array/JSON). Applicable for select, lookup, file, image.`),unique:b().default(!1).describe(`Is unique constraint`),defaultValue:S().optional().describe(`Default value`),maxLength:y().optional().describe(`Max character length`),minLength:y().optional().describe(`Min character length`),precision:y().optional().describe(`Total digits`),scale:y().optional().describe(`Decimal places`),min:y().optional().describe(`Minimum value`),max:y().optional().describe(`Maximum value`),options:w(Ud).optional().describe(`Static options for select/multiselect`),reference:v().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.`),referenceFilters:w(v()).optional().describe(`Filters applied to lookup dialogs (e.g. "active = true")`),deleteBehavior:A([`set_null`,`cascade`,`restrict`]).optional().default(`set_null`).describe(`What happens if referenced record is deleted`),inlineEdit:E([b(),A([`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:v().optional().describe(`Title for the inline master-detail grid`),inlineColumns:w(x()).optional().describe(`Explicit columns for the inline grid (derived from the child object when omitted)`),inlineAmountField:v().optional().describe(`Numeric child field summed for the inline grid total`),relatedList:b().optional().describe(`Show this child collection as a related list on the parent's detail page (read-side mirror of inlineEdit). Defaults to shown for master_detail/lookup; set false to suppress.`),relatedListTitle:v().optional().describe(`Title for the detail-page related list`),relatedListColumns:w(x()).optional().describe(`Explicit columns for the detail-page related list (derived from the child object when omitted)`),displayField:v().optional().describe(`Field shown as each candidate's label in the picker/popover (defaults to the referenced object's name/title).`),descriptionField:v().optional().describe(`Secondary field shown under the label in the quick-select popover.`),lookupColumns:w(E([v(),T({field:v(),label:v().optional(),width:v().optional(),type:v().optional()})])).optional().describe(`Explicit columns for the record-picker table; auto-derived from the referenced object when omitted.`),lookupPageSize:y().int().positive().optional().describe(`Rows per page in the record-picker dialog (default 10).`),lookupFilters:w(T({field:v(),operator:A([`eq`,`ne`,`gt`,`lt`,`gte`,`lte`,`contains`,`in`,`notIn`]),value:x()})).optional().describe(`Base filters restricting which records are selectable (e.g. only active). Structured, picker-honoured form of referenceFilters.`),dependsOn:w(E([v(),T({field:v(),param:v().optional()})])).optional().describe(`Dependent lookup: restrict candidates by the value of other field(s) on the same record. String = same local/remote key; {field,param} when the remote filter key differs.`),allowCreate:b().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:Fu.optional().describe("Formula expression (CEL). e.g. F`record.amount * 0.1`"),returnType:A([`number`,`text`,`boolean`,`date`]).optional().describe(`Inferred value type of a formula field (number/text/boolean/date)`),summaryOperations:T({object:v().describe(`Source child object name for roll-up`),field:v().describe(`Field on child object to aggregate (ignored for count)`),function:A([`count`,`sum`,`min`,`max`,`avg`]).describe(`Aggregation function to apply`),relationshipField:v().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.`)}).optional().describe(`Roll-up summary definition. The engine recomputes the value when child records are inserted/updated/deleted.`),language:v().optional().describe(`Programming language for syntax highlighting (e.g., javascript, python, sql)`),maxRating:y().optional().describe(`Maximum rating value (default: 5)`),step:y().optional().describe(`Step increment for slider (default: 1)`),currencyConfig:Wd.optional().describe(`Configuration for currency field type`),dimensions:y().int().min(1).max(1e4).optional().describe(`Vector dimensionality (e.g., 1536 for OpenAI embeddings)`),vectorConfig:Gd.optional().describe(`Configuration for vector field type (AI/ML embeddings)`),fileAttachmentConfig:Kd.optional().describe(`Configuration for file and attachment field types`),trackHistory:b().optional().describe(`Render this field's value changes as human-readable entries on the record activity timeline (ADR-0052 §5b). Opt-in per field.`),dependencies:w(v()).optional().describe(`Array of field names that this field depends on (for formulas, visibility rules, etc.)`),group:v().optional().describe(`Field group name for organizing fields in forms and layouts (e.g., "contact_info", "billing", "system")`),visibleWhen:Fu.optional().describe("Predicate (CEL) — field is shown only when TRUE (else hidden). e.g. P`record.type == 'invoice'`"),readonlyWhen:Fu.optional().describe("Predicate (CEL) — field is read-only when TRUE. e.g. P`record.status == 'paid'`"),requiredWhen:Fu.optional().describe("Predicate (CEL) — field is required when TRUE. Canonical name for `conditionalRequired`."),conditionalRequired:Fu.optional().describe("Predicate (CEL) — field is required when TRUE. Alias of `requiredWhen`."),hidden:b().default(!1).describe(`Hidden from default UI`),readonly:b().default(!1).describe(`Read-only in UI`),requiredPermissions:w(v()).optional().describe(`[ADR-0066 D3] Capabilities required to read/edit this field (mask on read, deny on write; AND-gate).`),system:b().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:b().optional().default(!0).describe(`Whether field is sortable in list views`),inlineHelpText:v().optional().describe(`Help text displayed below the field in forms`),caseSensitive:b().optional().describe(`Whether text comparisons are case-sensitive`),autonumberFormat:v().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).`),index:b().default(!1).describe(`Create standard database index`),externalId:b().default(!1).describe(`Is external ID for upsert operations`)}));Object.fromEntries(Object.entries({objects:`object`,apps:`app`,pages:`page`,dashboards:`dashboard`,reports:`report`,datasets:`dataset`,actions:`action`,themes:`theme`,flows:`flow`,jobs:`job`,roles:`role`,permissions:`permission`,profiles:`profile`,sharingRules:`sharing_rule`,policies:`policy`,apis:`api`,webhooks:`webhook`,agents:`agent`,tools:`tool`,skills:`skill`,ragPipelines:`rag_pipeline`,hooks:`hook`,mappings:`mapping`,analyticsCubes:`analytics_cube`,connectors:`connector`,datasources:`datasource`,views:`view`,emailTemplates:`email_template`,docs:`doc`,books:`book`}).map(([e,t])=>[t,e]));var Jd=T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Unique rule name (snake_case)`),label:v().optional().describe(`Human-readable label for the rule listing`),description:v().optional().describe(`Administrative notes explaining the business reason`),active:b().default(!0),events:w(A([`insert`,`update`,`delete`])).default([`insert`,`update`]).describe(`Validation contexts`),priority:y().int().min(0).max(9999).default(100).describe(`Execution priority (lower runs first, default: 100)`),tags:w(v()).optional().describe(`Categorization tags (e.g., "compliance", "billing")`),severity:A([`error`,`warning`,`info`]).default(`error`),message:v().describe(`Error message to display to the user`)}),Yd=F(()=>Jd.extend({type:j(`script`),condition:Fu.describe("Predicate (CEL). If TRUE, validation fails. e.g. P`record.amount < 0`")})),Xd=F(()=>Jd.extend({type:j(`state_machine`),field:v().describe(`State field (e.g. status)`),transitions:k(v(),w(v())).describe(`Map of { OldState: [AllowedNewStates] }`)})),Zd=F(()=>Jd.extend({type:j(`format`),field:v(),regex:v().optional(),format:A([`email`,`url`,`phone`,`json`]).optional()})),Qd=F(()=>Jd.extend({type:j(`cross_field`),condition:Fu.describe("Predicate (CEL) comparing fields. e.g. P`record.end_date > record.start_date`"),fields:w(v()).describe(`Fields involved in the validation`)})),$d=F(()=>Jd.extend({type:j(`json_schema`),field:v().describe(`JSON field to validate`),schema:k(v(),S()).describe(`JSON Schema object definition`)})),ef=M(()=>D(`type`,[Yd,Xd,Zd,Qd,$d,tf])),tf=F(()=>Jd.extend({type:j(`conditional`),when:Fu.describe("Predicate (CEL). e.g. P`record.type == 'enterprise'`"),then:ef.describe(`Validation rule to apply when condition is true`),otherwise:ef.optional().describe(`Validation rule to apply when condition is false`)})),nf=A([`api.read`,`api.write`,`api.transaction`,`crypto.uuid`,`crypto.hash`,`log`]),rf=D(`language`,[T({language:j(`expression`),source:v().min(1).describe(`Formula expression source`)}).describe(`L1 expression body — pure formula, no IO`),T({language:j(`js`),source:v().min(1).describe(`Function body source`),capabilities:w(nf).default([]).describe(`Granted capability tokens`),timeoutMs:y().int().positive().max(3e4).optional().describe(`Per-invocation timeout (ms)`),memoryMb:y().int().positive().max(256).optional().describe(`Per-invocation memory cap (MB)`)}).describe(`L2 sandboxed JS body — runs inside an isolated VM with declared capabilities`)]).describe(`Hook/Action body — expression (L1) or sandboxed JS (L2)`),af=F(()=>T({name:v().optional(),field:I.optional(),objectOverride:I.optional(),label:L.optional(),type:Hd.optional(),required:b().optional().default(!1),options:w(T({label:L,value:v()})).optional(),placeholder:v().optional(),helpText:v().optional(),defaultValue:S().optional(),defaultFromRow:b().optional()}).refine(e=>!!e.name||!!e.field,{message:`ActionParam requires either "name" or "field"`})),of=A([`script`,`url`,`modal`,`flow`,`api`,`form`]),sf=new Set(of.options.filter(e=>e!==`script`)),cf=A([`list_toolbar`,`list_item`,`record_header`,`record_more`,`record_related`,`record_section`,`global_nav`]),lf=A([`data`,`action`,`flow`,`integration`,`vector_search`,`analytics`,`utility`]),uf=T({exposed:b().default(!1).describe("Expose this action to AI agents. Requires `description` when true."),description:v().min(40).optional().describe(`LLM-facing description (≥40 chars). Required when exposed.`),category:lf.optional().describe(`Tool category override (defaults to "action").`),paramHints:k(v(),T({description:v().optional(),enum:w(E([v(),y()])).optional(),examples:w(S()).optional()})).optional().describe(`Per-parameter AI hints keyed by param name.`),outputSchema:k(v(),S()).optional().describe(`JSON Schema for the action return value.`),requiresConfirmation:b().optional().describe(`Override HITL confirmation for AI invocations.`)}),df=F(()=>T({name:I.describe(`Machine name (lowercase snake_case)`),label:L.describe(`Display label`),objectName:v().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:v().optional().describe(`Icon name`),locations:w(cf).optional().describe(`Locations where this action is visible`),component:A([`action:button`,`action:icon`,`action:menu`,`action:group`]).optional().describe(`Visual component override`),type:of.default(`script`).describe(`Action functionality type`),target:v().optional().describe("URL, Script Name, Flow ID, or API Endpoint. Supports ${param.X} and ${ctx.X} interpolation."),body:rf.optional().describe("Action body — expression (L1) or sandboxed JS (L2). Only used when type is `script`."),execute:v().optional().describe(`@deprecated — Use target instead. Auto-migrated to target during parsing.`),params:w(af).optional().describe(`Input parameters required from user`),variant:A([`primary`,`secondary`,`danger`,`ghost`,`link`]).optional().describe(`Button visual variant for styling (primary = highlighted, danger = destructive, ghost = transparent)`),confirmText:L.optional().describe(`Confirmation message before execution`),successMessage:L.optional().describe(`Success message to show after execution`),errorMessage:L.optional().describe(`Error message to show when the action fails (overrides the raw error).`),refreshAfter:b().default(!1).describe(`Refresh view after execution`),undoable:b().optional().describe(`Offer an Undo affordance after this single-record update action succeeds.`),resultDialog:T({title:L.optional(),description:L.optional(),acknowledge:L.optional().describe(`Acknowledge button label, e.g. "I have saved this"`),format:A([`qrcode`,`code-list`,`secret`,`text`,`json`]).optional().describe(`Default format for fields without their own format. Defaults to json when omitted.`),fields:w(T({path:v().describe(`Dot path into result.data (e.g. "totpURI", "client.client_secret").`),label:L.optional(),format:A([`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:Fu.optional().describe(`Visibility predicate (CEL).`),disabled:E([b(),Fu]).optional().describe(`Boolean or predicate (CEL) — action is disabled when TRUE.`),requiredPermissions:w(v()).optional().describe(`[ADR-0066 D4] Capabilities required to invoke this action (server-enforced 403 + UI hide/disable).`),shortcut:v().optional().describe(`Keyboard shortcut to trigger this action (e.g., "Ctrl+S")`),bulkEnabled:b().optional().describe(`Whether this action can be applied to multiple selected records`),ai:uf.optional().describe(`AI exposure (opt-in). Set ai.exposed=true + ai.description to make this callable by agents.`),recordIdParam:v().optional().describe(`Body key to inject the row id into when running from a list_item context.`),recordIdField:v().optional().describe(`Row field whose value seeds recordIdParam. Defaults to "id".`),bodyShape:E([j(`flat`),T({wrap:v()})]).optional().describe(`Body wrapping: flat (default) or { wrap: key } to nest user-collected params under a key.`),method:A([`POST`,`PATCH`,`PUT`,`DELETE`]).optional().describe(`HTTP method for type:"api" actions. Defaults to POST.`),bodyExtra:k(v(),S()).optional().describe(`Constant body fields merged into the API request (applied last; overrides user params).`),mode:A([`create`,`edit`,`delete`,`custom`]).optional().describe(`Semantic mode of the action.`),opensInNewTab:b().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:v().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.`),timeout:y().optional().describe(`Maximum execution time in milliseconds for the action`),aria:Ru.optional().describe(`ARIA accessibility attributes`)}).transform(e=>e.execute&&!e.target?{...e,target:e.execute}:e).refine(e=>!(sf.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.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`]})),ff=A([`xs`,`sm`,`md`,`lg`,`xl`,`2xl`]),pf=F(()=>T({xs:y().min(1).max(12).optional(),sm:y().min(1).max(12).optional(),md:y().min(1).max(12).optional(),lg:y().min(1).max(12).optional(),xl:y().min(1).max(12).optional(),"2xl":y().min(1).max(12).optional()}).describe(`Grid columns per breakpoint (1-12)`)),mf=F(()=>T({xs:y().optional(),sm:y().optional(),md:y().optional(),lg:y().optional(),xl:y().optional(),"2xl":y().optional()}).describe(`Display order per breakpoint`)),hf=F(()=>T({breakpoint:ff.optional().describe(`Minimum breakpoint for visibility`),hiddenOn:w(ff).optional().describe(`Hide on these breakpoints`),columns:pf.optional().describe(`Grid columns per breakpoint`),order:mf.optional().describe(`Display order per breakpoint`)}).describe(`Responsive layout configuration`)),gf=F(()=>k(v(),E([v(),y()])).describe(`CSS property → value map (camelCase keys; design tokens encouraged)`)),_f=F(()=>T({large:gf.optional().describe(`Unconditional base (desktop-first)`),medium:gf.optional().describe(`Applied at ≤ medium breakpoint`),small:gf.optional().describe(`Applied at ≤ small breakpoint`),xsmall:gf.optional().describe(`Applied at ≤ xsmall breakpoint`)}).describe(`Per-breakpoint scoped style maps (ADR-0065)`)),vf=F(()=>T({lazyLoad:b().optional().describe(`Enable lazy loading (defer rendering until visible)`),virtualScroll:T({enabled:b().default(!1).describe(`Enable virtual scrolling`),itemHeight:y().optional().describe(`Fixed item height in pixels (for estimation)`),overscan:y().optional().describe(`Number of extra items to render outside viewport`)}).optional().describe(`Virtual scrolling configuration`),cacheStrategy:A([`none`,`cache-first`,`network-first`,`stale-while-revalidate`]).optional().describe(`Client-side data caching strategy`),prefetch:b().optional().describe(`Prefetch data before component is visible`),pageSize:y().optional().describe(`Number of items per page for pagination`),debounceMs:y().optional().describe(`Debounce interval for user interactions in milliseconds`)}).describe(`Performance optimization configuration`)),yf=A([`GET`,`POST`,`PUT`,`DELETE`,`PATCH`,`HEAD`,`OPTIONS`]),bf=F(()=>A([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`])),xf=F(()=>T({url:v().describe(`API endpoint URL`),method:bf.optional().default(`GET`).describe(`HTTP method`),headers:k(v(),v()).optional().describe(`Custom HTTP headers`),params:k(v(),S()).optional().describe(`Query parameters`),body:S().optional().describe(`Request body for POST/PUT/PATCH`)}));F(()=>T({enabled:b().default(!0).describe(`Enable CORS`),origins:E([v(),w(v())]).default(`*`).describe(`Allowed origins (* for all)`),methods:w(yf).optional().describe(`Allowed HTTP methods`),credentials:b().default(!1).describe(`Allow credentials (cookies, authorization headers)`),maxAge:y().int().optional().describe(`Preflight cache duration in seconds`)}));var Sf=F(()=>T({enabled:b().default(!1).describe(`Enable rate limiting`),windowMs:y().int().default(6e4).describe(`Time window in milliseconds`),maxRequests:y().int().default(100).describe(`Max requests per window`)}));F(()=>T({path:v().describe(`URL path to serve from`),directory:v().describe(`Physical directory to serve`),cacheControl:v().optional().describe(`Cache-Control header value`)}));var Cf=F(()=>D(`provider`,[T({provider:j(`object`),object:v().describe(`Target object name`)}),T({provider:j(`api`),read:xf.optional().describe(`Configuration for fetching data`),write:xf.optional().describe(`Configuration for submitting data (for forms/editable tables)`)}),T({provider:j(`value`),items:w(S()).describe(`Static data array`)}),T({provider:j(`schema`),schemaId:v().describe(`Schema identifier — typically the metadata type name`),schema:k(v(),S()).optional().describe(`Inline JSON Schema (Draft 2020-12). Optional when schemaId is resolvable.`)})])),wf=F(()=>T({field:v().describe(`Field name to filter on`),operator:v().describe(`Filter operator (e.g. equals, not_equals, contains, this_quarter)`),value:E([v(),y(),b(),ul(),w(E([v(),y()]))]).optional().describe(`Filter value`)}).describe(`View filter rule`)),Tf=F(()=>A([`none`,`count`,`count_empty`,`count_filled`,`count_unique`,`percent_empty`,`percent_filled`,`sum`,`avg`,`min`,`max`]).describe(`Aggregation function for column footer summary`)),Ef=F(()=>T({field:v().describe(`Field name (snake_case)`),label:L.optional().describe(`Display label override`),width:y().positive().optional().describe(`Column width in pixels`),align:A([`left`,`center`,`right`]).optional().describe(`Text alignment`),hidden:b().optional().describe(`Hide column by default`),sortable:b().optional().describe(`Allow sorting by this column`),resizable:b().optional().describe(`Allow resizing this column`),wrap:b().optional().describe(`Allow text wrapping`),type:v().optional().describe(`Renderer type override (e.g., "currency", "date")`),pinned:A([`left`,`right`]).optional().describe(`Pin/freeze column to left or right side`),summary:Tf.optional().describe(`Footer aggregation function for this column`),link:b().optional().describe(`Functions as the primary navigation link (triggers View navigation)`),action:v().optional().describe(`Registered Action ID to execute when clicked`)})),Df=F(()=>T({type:A([`none`,`single`,`multiple`]).default(`none`).describe(`Selection mode`)})),Of=F(()=>T({pageSize:y().int().positive().default(25).describe(`Number of records per page`),pageSizeOptions:w(y().int().positive()).optional().describe(`Available page size options`)})),kf=F(()=>A([`compact`,`short`,`medium`,`tall`,`extra_tall`]).describe(`Row height / density setting for list view`)),Af=F(()=>T({field:v().describe(`Field name to group by`),order:A([`asc`,`desc`]).default(`asc`).describe(`Group sort order`),collapsed:b().default(!1).describe(`Collapse groups by default`)})),jf=F(()=>T({fields:w(Af).min(1).describe(`Fields to group by (supports up to 3 levels)`)}).describe(`Record grouping configuration`)),Mf=F(()=>T({coverField:v().optional().describe(`Attachment/image field to display as card cover`),coverFit:A([`cover`,`contain`]).default(`cover`).describe(`Image fit mode for card cover`),cardSize:A([`small`,`medium`,`large`]).default(`medium`).describe(`Card size in gallery view`),titleField:v().optional().describe(`Field to display as card title`),visibleFields:w(v()).optional().describe(`Fields to display on card body`)}).describe(`Gallery/card view configuration`)),Nf=F(()=>T({startDateField:v().describe(`Field for timeline item start date`),endDateField:v().optional().describe(`Field for timeline item end date`),titleField:v().describe(`Field to display as timeline item title`),groupByField:v().optional().describe(`Field to group timeline rows`),colorField:v().optional().describe(`Field to determine item color`),scale:A([`hour`,`day`,`week`,`month`,`quarter`,`year`]).default(`week`).describe(`Default timeline scale`)}).describe(`Timeline view configuration`)),Pf=F(()=>T({type:A([`personal`,`collaborative`]).default(`collaborative`).describe(`View ownership type`),lockedBy:v().optional().describe(`User who locked the view configuration`)}).describe(`View sharing and access configuration`)),Ff=F(()=>T({field:v().describe(`Field to derive color from (typically a select/status field)`),colors:k(v(),v()).optional().describe(`Map of field value to color (hex/token)`)}).describe(`Row color configuration based on field values`)),If=F(()=>A([`grid`,`kanban`,`gallery`,`calendar`,`timeline`,`gantt`,`map`,`chart`,`tree`]).describe(`Visualization type that users can switch to`)),Lf=F(()=>T({sort:b().default(!0).describe(`Allow users to sort records`),search:b().default(!0).describe(`Allow users to search records`),filter:b().default(!0).describe(`Allow users to filter records`),rowHeight:b().default(!0).describe(`Allow users to toggle row height/density`),addRecordForm:b().default(!1).describe(`Add records through a form instead of inline`),buttons:w(v()).optional().describe(`Custom action button IDs to show in the toolbar`)}).describe(`User action toggles for the view toolbar`)),Rf=F(()=>T({showDescription:b().default(!0).describe(`Show the view description text`),allowedVisualizations:w(If).optional().describe(`Whitelist of visualization types users can switch between (e.g. ["grid", "gallery", "kanban"])`)}).describe(`Appearance and visualization configuration`)),zf=F(()=>T({name:I.describe(`Tab identifier (snake_case)`),label:L.optional().describe(`Display label`),icon:v().optional().describe(`Tab icon name`),view:v().optional().describe(`Referenced list view name from listViews`),filter:w(wf).optional().describe(`Tab-specific filter criteria`),order:y().int().min(0).optional().describe(`Tab display order`),pinned:b().default(!1).describe(`Pin tab (cannot be removed by users)`),isDefault:b().default(!1).describe(`Set as the default active tab`),visible:b().default(!0).describe(`Tab visibility`)}).describe(`Tab configuration for multi-tab view interface`)),Bf=F(()=>T({field:v().describe(`Field name on the source object (must exist — checked by reference diagnostics)`),label:L.optional().describe(`Display label override (defaults to the field label)`),type:A([`select`,`multi-select`,`boolean`,`date-range`,`text`]).optional().describe(`Filter control type. Omit to infer from the field definition`),options:w(T({value:E([v(),y(),b()]).describe(`Option value`),label:L.describe(`Option label`),color:v().optional().describe(`Option color token/hex`)})).optional().describe(`Static options. Omit to derive from the field definition (select options / lookup records)`),showCount:b().optional().describe(`Show per-option record counts`),defaultValues:w(E([v(),y(),b()])).optional().describe(`Pre-selected values when the view loads`)}).describe(`Quick-filter field configuration`)),Vf=F(()=>T({element:A([`dropdown`,`tabs`,`toggle`]).default(`dropdown`).describe(`Filter control style: "dropdown" (per-field value selectors) or "tabs" (named presets). "toggle" is deprecated.`),fields:w(Bf).optional().describe(`Fields exposed as quick filters (dropdown/toggle elements)`),tabs:w(zf).optional().describe(`Named filter presets rendered as tabs (tabs element). Reuses ViewTabSchema`),showAllRecords:b().optional().describe(`Show an "All records" tab before the presets (tabs element)`)}).describe(`End-user quick-filter configuration (Airtable "User filters" parity)`)),Hf=F(()=>T({enabled:b().default(!0).describe(`Show the add record entry point`),position:A([`top`,`bottom`,`both`]).default(`bottom`).describe(`Position of the add record button`),mode:A([`inline`,`form`,`modal`]).default(`inline`).describe(`How to add a new record`),formView:v().optional().describe(`Named form view to use when mode is "form" or "modal"`)}).describe(`Add record entry point configuration`)),Uf=F(()=>T({groupByField:v().describe(`Field to group columns by (usually status/select)`),summarizeField:v().optional().describe(`Field to sum at top of column (e.g. amount)`),columns:w(v()).describe(`Fields to show on cards`)})),Wf=F(()=>T({chartType:A([`bar`,`line`,`pie`,`area`,`scatter`]).default(`bar`).describe(`Chart visualisation type`),dataset:I.describe(`Dataset name to bind (ADR-0021)`),dimensions:w(v()).optional().describe(`Dimension names — X/group/split`),values:w(v()).min(1).describe(`Measure names — Y (at least one)`)}).describe(`List chart view configuration`)),Gf=F(()=>T({startDateField:v(),endDateField:v().optional(),titleField:v(),colorField:v().optional()})),Kf=F(()=>T({field:v().describe(`Record field / dot-path the dimension filters on`),label:v().optional().describe(`Trigger label (falls back to the field label)`),options:w(E([v(),T({value:E([v(),y()]),label:v().optional()})])).optional().describe(`Explicit option override for fixed enums`)})),qf=F(()=>T({startDateField:v(),endDateField:v(),titleField:v(),progressField:v().optional(),dependenciesField:v().optional(),colorField:v().optional().describe(`Field that drives the bar color`),parentField:v().optional().describe(`Field holding the parent task id (builds the summary → step tree)`),typeField:v().optional().describe(`Field whose value maps to task/summary/milestone`),baselineStartField:v().optional().describe(`Baseline (planned) start field`),baselineEndField:v().optional().describe(`Baseline (planned) end field`),groupByField:v().optional().describe(`Field to group leaf tasks by (synthesized summary rows)`),resourceView:b().optional().describe(`Render a per-resource workload histogram instead of the timeline`),assigneeField:v().optional().describe(`Resource field to bucket load by (resource view)`),effortField:v().optional().describe(`Per-task load units (resource view; default 1)`),capacity:y().optional().describe(`Per-resource capacity ceiling; loads above this flag overload`),tooltipFields:w(E([v(),T({field:v(),label:v().optional()})])).optional().describe(`Fields to surface in the hover tooltip, in display order`),quickFilters:w(Kf).optional().describe(`Multi-select filter dropdowns rendered above the chart`),autoZoomToFilter:b().optional().describe(`When true (default), filtering zooms the range to the filtered tasks`)}).passthrough()),Jf=F(()=>T({parentField:v().optional().describe(`Single-parent pointer field (auto-detected from the object schema when omitted)`),labelField:v().optional().describe(`Field rendered indented in the first column (defaults to "name")`),fields:w(v()).optional().describe(`Additional fields rendered as flat columns alongside the label`),defaultExpandedDepth:y().int().min(0).optional().describe(`Initial expansion depth (0 = roots only; omit = expand all)`)}).passthrough()),Yf=F(()=>A([`page`,`drawer`,`modal`,`split`,`popover`,`new_window`,`none`])),Xf=F(()=>T({mode:Yf.default(`page`),view:v().optional().describe(`Name of the form view to use for details (e.g. "summary_view", "edit_form")`),preventNavigation:b().default(!1).describe(`Disable standard navigation entirely`),openNewTab:b().default(!1).describe(`Force open in new tab (applies to page mode)`),width:E([v(),y()]).optional().describe(`Width of the drawer/modal (e.g. "600px", "50%")`)})),Zf=F(()=>T({name:I.optional().describe(`Internal view name (lowercase snake_case)`),label:L.optional(),type:A([`grid`,`kanban`,`gallery`,`calendar`,`timeline`,`gantt`,`map`,`chart`,`tree`]).default(`grid`),data:Cf.optional().describe(`Data source configuration (defaults to "object" provider)`),columns:E([w(v()),w(Ef)]).describe(`Fields to display as columns`),filter:w(wf).optional().describe(`Filter criteria (JSON Rules)`),sort:E([v(),w(T({field:v(),order:A([`asc`,`desc`])}))]).optional(),searchableFields:w(v()).optional().describe(`Fields enabled for search`),filterableFields:w(v()).optional().describe(`Legacy shorthand for userFilters.fields — bare field names enabled for end-user filtering. Prefer userFilters`),userFilters:Vf.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:b().optional().describe(`Enable column resizing`),striped:b().optional().describe(`Striped row styling`),bordered:b().optional().describe(`Show borders`),compactToolbar:b().optional().describe(`Collapse Group/Color/Density/Hide-fields into a single View settings popover`),selection:Df.optional().describe(`Row selection configuration`),navigation:Xf.optional().describe(`Configuration for item click navigation (page, drawer, modal, etc.)`),pagination:Of.optional().describe(`Pagination configuration`),kanban:Uf.optional(),calendar:Gf.optional(),gantt:qf.optional(),gallery:Mf.optional(),timeline:Nf.optional(),chart:Wf.optional(),tree:Jf.optional(),description:L.optional().describe(`View description for documentation/tooltips`),sharing:Pf.optional().describe(`View sharing and access configuration`),rowHeight:kf.optional().describe(`Row height / density setting`),grouping:jf.optional().describe(`Group records by one or more fields`),rowColor:Ff.optional().describe(`Color rows based on field value`),hiddenFields:w(v()).optional().describe(`Fields to hide in this specific view`),fieldOrder:w(v()).optional().describe(`Explicit field display order for this view`),rowActions:w(v()).optional().describe(`Actions available for individual row items`),bulkActions:w(v()).optional().describe(`Actions available when multiple rows are selected`),bulkActionDefs:w(k(v(),x())).optional().describe(`Rich bulk action definitions (schema-driven, executed via BulkActionDialog)`),virtualScroll:b().optional().describe(`Enable virtual scrolling for large datasets`),conditionalFormatting:w(T({condition:Fu.describe(`Predicate (CEL) to evaluate.`),style:k(v(),v()).describe(`CSS styles to apply when condition is true`)})).optional().describe(`Conditional formatting rules for list rows`),inlineEdit:b().optional().describe(`Allow inline editing of records directly in the list view`),exportOptions:w(A([`csv`,`xlsx`,`pdf`,`json`])).optional().describe(`Available export format options`),userActions:Lf.optional().describe(`User action toggles for the view toolbar`),appearance:Rf.optional().describe(`Appearance and visualization configuration`),tabs:w(zf).optional().describe(`Tab definitions for multi-tab view interface`),addRecord:Hf.optional().describe(`Add record entry point configuration`),showRecordCount:b().optional().describe(`Show record count at the bottom of the list`),allowPrinting:b().optional().describe(`Allow users to print the view`),emptyState:T({title:L.optional(),message:L.optional(),icon:v().optional()}).optional().describe(`Empty state configuration when no records found`),aria:Ru.optional().describe(`ARIA accessibility attributes for the list view`),responsive:hf.optional().describe(`Responsive layout configuration`),performance:vf.optional().describe(`Performance optimization settings`)})),Qf=F(()=>T({field:v().describe(`Field name (snake_case)`),type:Hd.optional().describe(`Field type (auto-infers widget if omitted)`),options:w(Ud).optional().describe(`Options for select/multiselect/radio/checkboxes fields`),reference:v().optional().describe(`Target object name for lookup/master_detail fields`),maxLength:y().optional().describe(`Maximum character length (for text/textarea/email/url/phone)`),minLength:y().optional().describe(`Minimum character length`),min:y().optional().describe(`Minimum value (for number/currency/percent/slider)`),max:y().optional().describe(`Maximum value`),precision:y().optional().describe(`Total digits (for number/currency)`),scale:y().optional().describe(`Decimal places`),multiple:b().optional().describe(`Allow multiple values (for select/lookup/file/image)`),label:L.optional().describe(`Display label override`),placeholder:L.optional().describe(`Placeholder text`),helpText:L.optional().describe(`Help/hint text`),readonly:b().optional().describe(`Read-only override`),immutable:b().optional().describe(`Editable on create, locked once the record exists (e.g. machine names).`),required:b().optional().describe(`Required override`),hidden:b().optional().describe(`Hidden override`),colSpan:y().int().min(1).max(4).optional().describe(`Column span in grid layout (1-4)`),widget:v().optional().describe(`Custom widget/component name (overrides type-based inference)`),language:v().optional().describe(`Code editor language (for type=code)`),fields:w(M(()=>Qf)).optional().describe(`Sub-fields for composite/repeater/record types`),keyField:T({field:v().default(`name`).describe(`Property name that holds the key inside each item (defaults to "name")`),label:L.optional().describe(`Display label for the key column`),placeholder:L.optional().describe(`Placeholder when entering a new key`),helpText:L.optional().describe(`Help text under the key input`),regex:v().optional().describe(`JS regex source string the key must match (no flags)`),immutable:b().default(!0).describe(`If true, the key is read-only after creation`)}).optional().describe(`Key column config for record-typed fields`),dependsOn:v().optional().describe(`Parent field name for cascading`),visibleOn:Fu.optional().describe(`Visibility predicate (CEL).`),disclosure:A([`inline`,`popover`]).optional().describe(`Composite rendering: inline bordered box (default) or a summary line + gear popover (progressive disclosure).`)})),$f=F(()=>T({name:v().optional().describe(`Stable section identifier for i18n lookup (snake_case)`),label:L.optional(),description:v().optional().describe(`Optional description rendered under the section header.`),collapsible:b().default(!1),collapsed:b().default(!1),visibleOn:Fu.optional().describe(`Visibility predicate (CEL). Hides the whole section when false.`),columns:E([A([`1`,`2`,`3`,`4`]),j(1),j(2),j(3),j(4)]).default(1).transform(e=>typeof e==`string`?parseInt(e):e),fields:w(E([v(),Qf]))})),ep=F(()=>T({type:A([`simple`,`tabbed`,`wizard`,`split`,`drawer`,`modal`]).default(`simple`),data:Cf.optional().describe(`Data source configuration (defaults to "object" provider)`),sections:w($f).optional(),groups:w($f).optional(),subforms:w(T({childObject:v().describe(`Child object whose records are entered inline`),relationshipField:v().optional().describe(`FK on the child pointing back to the parent (auto-detected when omitted)`),columns:w(x()).optional().describe(`Editable grid columns (derived from the child object when omitted)`),amountField:v().optional().describe(`Numeric child column summed for the running total`),totalField:v().optional().describe(`Parent field to receive the rolled-up sum`),title:v().optional().describe(`Section title`),addLabel:v().optional().describe(`Add-row button label`),minRows:y().optional(),maxRows:y().optional()})).optional().describe(`Inline master-detail child collections`),defaultSort:w(T({field:v().describe(`Field name to sort by`),order:A([`asc`,`desc`]).default(`desc`).describe(`Sort direction`)})).optional().describe(`Default sort order for related list views within this form`),sharing:Vu.optional().describe(`Public sharing configuration for this form`),submitBehavior:E([T({kind:j(`thank-you`),title:v().optional(),message:v().optional()}),T({kind:j(`redirect`),url:v(),delayMs:y().int().min(0).optional()}),T({kind:j(`continue`)}),T({kind:j(`next-record`)})]).optional().describe(`Post-submit behavior`),aria:Ru.optional().describe(`ARIA accessibility attributes for the form view`)})),tp=F(()=>T({list:Zf.optional(),form:ep.optional(),listViews:k(v(),Zf).optional().describe(`Additional named list views`),formViews:k(v(),ep).optional().describe(`Additional named form views`),protection:qu.optional().describe(`Package author protection block — lock policy for this view.`),...Ku})),np=v().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>`."),rp=A([`package`,`shared`,`personal`]).describe(`View identity layer: package | shared | personal.`);A([`list`,`form`]).describe("Whether `config` is a ListView (list family) or a FormView.");function ip(){return{name:np,object:v().describe(`Bound object name — the foreign key used to aggregate views.`),label:L.optional().describe(`Display label (supports i18n).`),isDefault:b().optional().describe(`Whether this is the object's default view in the switcher.`),order:y().int().optional().describe(`Sort order within the object's view switcher / left rail.`),scope:rp.optional().describe("Identity layer (defaults to `package` for source-loaded views)."),owner:v().optional().describe("Owner user id — set when `scope` is `personal`."),hidden:b().optional().describe(`Hidden from the switcher (per-user / per-org declutter).`),protection:qu.optional().describe(`Package author protection block — lock policy for this view.`),...Ku}}F(()=>D(`viewKind`,[T({viewKind:j(`list`),config:Zf.describe(`List-family view configuration.`),...ip()}),T({viewKind:j(`form`),config:ep.describe(`Form view configuration.`),...ip()})]));var ap=A([`get`,`list`,`create`,`update`,`delete`,`upsert`,`bulk`,`aggregate`,`history`,`search`,`restore`,`purge`,`import`,`export`]),op=T({trackHistory:b().default(!1).describe(`Enable field history tracking for audit compliance`),searchable:b().default(!0).describe(`Index records for global search`),apiEnabled:b().default(!0).describe(`Expose object via automatic APIs`),apiMethods:w(ap).optional().describe(`Whitelist of allowed API operations`),files:b().default(!1).describe(`Enable file attachments and document management`),feeds:b().default(!1).describe(`Enable social feed, comments, and mentions (Chatter-like)`),activities:b().default(!1).describe(`Enable standard tasks and events tracking`),trash:b().default(!0).describe(`Enable soft-delete with restore capability`),mru:b().default(!0).describe(`Track Most Recently Used (MRU) list for users`),clone:b().default(!0).describe(`Allow record deep cloning`)}),sp=F(()=>T({name:v().optional().describe(`Index name (auto-generated if not provided)`),fields:w(v()).describe(`Fields included in the index`),type:A([`btree`,`hash`,`gin`,`gist`,`fulltext`]).optional().default(`btree`).describe(`Index algorithm type`),unique:b().optional().default(!1).describe(`Whether the index enforces uniqueness`),partial:v().optional().describe(`Partial index condition (SQL WHERE clause for conditional indexes)`)})),cp=F(()=>T({fields:w(v()).describe(`Fields to index for full-text search weighting`),displayFields:w(v()).optional().describe(`Fields to display in search result cards`),filters:w(v()).optional().describe(`Default filters for search results`)})),lp=F(()=>T({enabled:b().describe(`Enable multi-tenancy for this object`),strategy:A([`shared`,`isolated`,`hybrid`]).describe(`Tenant isolation strategy: shared (single DB, row-level), isolated (separate DB per tenant), hybrid (mix)`),tenantField:v().default(`tenant_id`).describe(`Field name for tenant identifier`),crossTenantAccess:b().default(!1).describe(`Allow cross-tenant data access (with explicit permission)`)})),up=F(()=>T({default:A([`public`,`private`]).default(`public`).describe(`Default exposure posture: public (covered by wildcard grants) | private (needs explicit grant; exempt from wildcard RLS).`)})),dp=F(()=>T({enabled:b().describe(`Enable soft delete (trash/recycle bin)`),field:v().default(`deleted_at`).describe(`Field name for soft delete timestamp`),cascadeDelete:b().default(!1).describe(`Cascade soft delete to related records`)})),fp=F(()=>T({enabled:b().describe(`Enable record versioning`),strategy:A([`snapshot`,`delta`,`event-sourcing`]).describe(`Versioning strategy: snapshot (full copy), delta (changes only), event-sourcing (event log)`),retentionDays:y().min(1).optional().describe(`Number of days to retain old versions (undefined = infinite)`),versionField:v().default(`version`).describe(`Field name for version number/timestamp`)})),pp=F(()=>T({enabled:b().describe(`Enable table partitioning`),strategy:A([`range`,`hash`,`list`]).describe(`Partitioning strategy: range (date ranges), hash (consistent hashing), list (predefined values)`),key:v().describe(`Field name to partition by`),interval:v().optional().describe(`Partition interval for range strategy (e.g., "1 month", "1 year")`)}).refine(e=>!(e.strategy===`range`&&!e.interval),{message:`interval is required when strategy is "range"`})),mp=F(()=>T({key:v().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:v().describe(`Group display label`),icon:v().optional().describe(`Icon name (Lucide/Material) for the group header`),description:v().optional().describe(`Optional description shown under the group header`),defaultExpanded:b().optional().default(!0).describe(`Whether the group is expanded by default`),visibleOn:Fu.optional().describe(`Visibility predicate (CEL); group is hidden when FALSE.`)})),hp=T({remoteName:v().optional().describe(`Remote table/view name. Defaults to object.name.`),remoteSchema:v().optional().describe(`Remote schema/database qualifier.`),writable:b().default(!1).describe(`Per-object write opt-in (also requires datasource.external.allowWrites).`),columnMap:k(v(),v()).optional().describe(`Remote column name → local field name.`),introspectedAt:v().datetime().optional().describe("Set by `os datasource introspect`; informational."),ignoreColumns:w(v()).optional().describe(`Remote columns to skip during validation (dev convenience).`)}).describe(`External datasource binding (ADR-0015)`),gp=T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Machine unique key (snake_case). Immutable.`),label:v().optional().describe(`Human readable singular label (e.g. "Account")`),pluralLabel:v().optional().describe(`Human readable plural label (e.g. "Accounts")`),description:v().optional().describe(`Developer documentation / description`),icon:v().optional().describe(`Icon name (Lucide/Material) for UI representation`),tags:w(v()).optional().describe(`Categorization tags (e.g. "sales", "system", "reference")`),active:b().optional().default(!0).describe(`Is the object active and usable`),isSystem:b().optional().default(!1).describe(`Is system object (protected from deletion)`),abstract:b().optional().default(!1).describe(`Is abstract base object (cannot be instantiated)`),managedBy:A([`platform`,`config`,`system`,`append-only`,`better-auth`]).optional().describe(`Lifecycle bucket — platform (user CRUD) | config (admin authored) | system (engine-managed) | append-only (audit) | better-auth (identity). UI clients honour the resolved affordance matrix.`),userActions:T({create:b().optional().describe(`Show generic "New" button.`),import:b().optional().describe(`Show CSV import wizard entry.`),edit:b().optional().describe(`Allow inline / form edit of existing rows.`),delete:b().optional().describe(`Show row-level delete + bulk delete.`),exportCsv:b().optional().describe(`Show CSV export entry.`)}).optional().describe(`Per-object override of the resolved CRUD affordance matrix.`),systemFields:E([j(!1),T({tenant:b().optional().describe(`Inject organization_id (multi-tenant only). Default true.`),owner:b().optional().describe(`Reserved for future owner_id auto-injection.`),audit:b().optional().describe(`Reserved for future created_by/updated_by auto-injection.`)})]).optional().describe(`Opt out of, or selectively disable, registry-level system-field auto-injection.`),datasource:v().optional().default(`default`).describe(`Target Datasource ID. "default" is the primary DB.`),external:hp.optional().describe(`Remote table binding for federated (external) objects.`),fields:k(v().regex(/^[a-z_][a-z0-9_]*$/,{message:`Field names must be lowercase snake_case (e.g., "first_name", "company", "annual_revenue")`}),qd).describe(`Field definitions map. Keys must be snake_case identifiers.`),indexes:w(sp).optional().describe(`Database performance indexes`),fieldGroups:w(mp).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:lp.optional().describe(`Multi-tenancy configuration for SaaS applications`),access:up.optional().describe(`[ADR-0066 D2] Object exposure posture (public-by-default vs private secure-by-default).`),requiredPermissions:w(v()).optional().describe(`[ADR-0066 D3] Capabilities required to access this object (AND-gate, checked alongside CRUD grants).`),softDelete:dp.optional().describe(`Soft delete (trash/recycle bin) configuration`),versioning:fp.optional().describe(`Record versioning and history tracking configuration`),partitioning:pp.optional().describe(`Table partitioning configuration for performance`),validations:w(ef).optional().describe(`Object-level validation rules`),activityMilestones:w(T({field:v().describe(`Field to watch (typically a status/stage select).`),value:v().describe(`The value the field must transition INTO to fire the milestone.`),summary:v().describe(`Activity summary template; {field} tokens interpolate the record value. e.g. "Deal won: {name}".`),type:v().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).`),displayNameField:v().optional().describe(`Field to use as the record display name (e.g., "name", "title"). Defaults to "name" if present.`),recordName:T({type:A([`text`,`autonumber`]).describe(`Record name type: text (user-entered) or autonumber (system-generated)`),displayFormat:v().optional().describe(`Auto-number format pattern (e.g., "CASE-{0000}", "INV-{YYYY}-{0000}")`),startNumber:y().int().min(0).optional().describe(`Starting number for autonumber (default: 1)`)}).optional().describe(`Record name generation configuration (Salesforce pattern)`),titleFormat:Lu.optional().describe(`Title template — supports {{record.field}} interpolation. Overrides displayNameField.`),compactLayout:w(v()).optional().describe(`Primary fields for hover/cards/lookups`),listViews:k(v(),Zf).optional().describe(`Built-in named list views (segmented tabs) shipped with the object schema`),defaultDetailForm:v().optional().describe(`Name of the default FormView for record detail / edit screens`),searchableFields:w(v()).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."),search:cp.optional().describe(`Search engine configuration`),enable:op.optional().describe(`Enabled system features modules`),sharingModel:A([`private`,`public_read`,`public_read_write`,`controlled_by_parent`,`read`,`read_write`,`full`]).optional().describe(`Org-Wide Default record visibility (OWD). Canonical: private (owner-only) | public_read (everyone reads, owner writes) | public_read_write (everyone reads+writes) | controlled_by_parent (derived from the master record). Legacy aliases: read=public_read, read_write/full=public_read_write. ADR-0056 D1.`),publicSharing:T({enabled:b().default(!1).describe(`Allow records of this object to be published via share link`),allowedAudiences:w(A([`public`,`link_only`,`signed_in`,`email`])).optional().describe(`Audiences callers may select when creating a link`),allowedPermissions:w(A([`view`,`comment`,`edit`])).optional().describe(`Permission levels selectable on the share dialog`),maxExpiryDays:y().int().positive().optional().describe(`Reject links with expiry beyond this many days`),redactFields:w(v()).optional().describe(`Field names removed from records served via a share token`),eligibility:v().optional().describe(`CEL expression that must evaluate to true on the target record`)}).optional().describe(`Public share-link policy (Notion/Figma-style link sharing)`),keyPrefix:v().max(5).optional().describe(`Short prefix for record IDs (e.g., "001" for Account)`),detail:T({renderViaSchema:b().optional().describe(`Opt this object out of the schema-driven detail renderer`),hideReferenceRail:b().optional().describe(`Suppress the right-hand reference-rail on the detail page`),hideRelatedTab:b().optional().describe(`Suppress the Related tab on the detail page`)}).passthrough().optional().describe(`Detail-page UI hints consumed by @object-ui/plugin-detail synth`),actions:w(df).optional().describe(`Actions associated with this object (auto-populated from top-level actions via objectName)`),protection:qu.optional().describe(`Package author protection block — lock policy for this object.`),...Ku});function _p(e){return e.split(`_`).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `)}var vp={workflows:"`workflows` is not an ObjectSchema field. Object-level, record-triggered automation is authored as a lifecycle hook (`src/objects/<name>.hook.ts`, registered via `defineHook()`) 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, registered via `defineHook()`.",triggers:"`triggers` is not an ObjectSchema field. Use a lifecycle hook (`src/objects/<name>.hook.ts`) or a top-level `record_change` flow."};function yp(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 bp(e,t){let n,r=1/0;for(let i of t){let t=yp(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 xp(e,t,n){let r=typeof e==`string`&&e.length>0?e:`<unnamed>`,i=t.map(e=>{let t=vp[e];if(t)return` \u2022 ${t}`;let r=bp(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(`, `)}.
|
|
72
|
+
These keys would previously have been stripped silently at build, shipping dead metadata with no diagnostic (ADR-0032 "no silent failure", issue #1535).
|
|
73
|
+
|
|
74
|
+
${i.join(`
|
|
75
|
+
`)}
|
|
76
|
+
|
|
77
|
+
Remove the unknown key(s), fix the typo, or move the logic to a supported mechanism.`)}var Sp=F(()=>Object.assign(gp,{create:e=>{let t=e,n=Object.keys(gp.shape),r=Object.keys(t).filter(e=>!n.includes(e));if(r.length>0)throw xp(t.name,r,n);let i={...t,label:t.label??_p(t.name)};return gp.parse(i)}}));A([`own`,`extend`]);var Cp=F(()=>T({extend:v().describe(`Target object name (FQN) to extend`),fields:k(v(),qd).optional().describe(`Fields to add/override`),label:v().optional().describe(`Override label for the extended object`),pluralLabel:v().optional().describe(`Override plural label for the extended object`),description:v().optional().describe(`Override description for the extended object`),validations:w(ef).optional().describe(`Additional validation rules to merge into the target object`),indexes:w(sp).optional().describe(`Additional indexes to merge into the target object`),priority:y().int().min(0).max(999).default(200).describe(`Merge priority (higher = applied later)`)})),wp=F(()=>T({primaryColor:v().optional().describe(`Primary brand color (hex, rgb, hsl). Mapped to --portal-primary.`),accentColor:v().optional().describe(`Accent color used for highlights and CTAs.`),backgroundColor:v().optional().describe(`Page background color.`),surfaceColor:v().optional().describe(`Card / surface background color.`),textColor:v().optional().describe(`Primary text color.`),logoUrl:v().optional().describe(`Absolute or relative URL to the portal header logo (SVG or PNG).`),faviconUrl:v().optional().describe(`Absolute or relative URL to the portal favicon.`),fontFamily:v().optional().describe(`CSS font-family stack for the portal.`),customCss:v().optional().describe(`OPTIONAL escape hatch: raw CSS appended last. Discouraged; prefer tokens.`)})),Tp=T({id:I.describe(`Unique identifier for this portal nav item (lowercase snake_case).`),label:L.describe(`Display label.`),icon:v().optional().describe(`Icon name (Lucide).`),order:y().optional().describe(`Sort order; lower appears first.`),badge:E([v(),y()]).optional().describe(`Optional badge (e.g. unread count).`)}),Ep=D(`type`,[Tp.extend({type:j(`view`),viewRef:v().describe(`Reference to an existing view, e.g. "helpdesk_ticket.list.my_tickets".`)}),Tp.extend({type:j(`action`),actionRef:v().describe(`Reference to an existing action, e.g. "helpdesk_ticket.create".`)}),Tp.extend({type:j(`dashboard`),dashboardName:I.describe(`Existing dashboard id.`)}),Tp.extend({type:j(`url`),url:v().describe(`Absolute or root-relative URL.`),target:A([`_self`,`_blank`]).optional().default(`_self`)})]),Dp=F(()=>T({rule:v().describe(`Rate-limit rule string, e.g. "5/hour/ip", "100/day/tenant".`),scope:A([`ip`,`tenant`,`route`]).default(`ip`).describe(`Counter scope. "ip" buckets per requester; "tenant" per portal owner; "route" global per route.`)})),Op=F(()=>T({path:v().describe(`Path within the portal, e.g. "/submit" or "/kb".`),viewRef:v().optional().describe(`Reference to a public view (read-only).`),actionRef:v().optional().describe(`Reference to an action to perform anonymously (mutation).`),rateLimit:Dp.optional().describe(`Rate-limit for anonymous traffic on this route.`),captcha:b().optional().default(!1).describe(`Require CAPTCHA / proof-of-work challenge before invoking.`),bindIdentityFromField:v().optional().describe(`Field name on the action input to use for magic-link identity binding (e.g. "customer_email").`)})),kp=F(()=>T({routes:w(Op).describe(`List of anonymous-accessible routes.`),defaultRateLimit:Dp.optional()})),Ap=F(()=>T({title:v().optional().describe(`Default <title>.`),description:v().optional().describe(`Default <meta name="description">.`),openGraphImage:v().optional().describe(`Default og:image URL.`),robots:A([`index`,`noindex`]).optional().default(`index`)})),jp=F(()=>E([j(`authenticated`),j(`magic-link`),j(`anonymous`),v().regex(/^sso:[a-z][a-z0-9_-]*(?::[a-z0-9_-]+)?$/i,`SSO mode must be "sso:<provider>" or "sso:<protocol>:<idp-id>"`)])),Mp=F(()=>E([j(`console`),j(`minimal`),j(`embedded`),v().regex(/^custom:[a-z][a-z0-9_-]*(?:\/[a-z0-9_-]+)?$/i,`Custom layout must be "custom:<plugin-id>" or "custom:<plugin-id>/<layout-id>"`)])),Np=F(()=>T({kind:j(`portal`).describe(`Metadata kind discriminator.`),id:I.describe(`Portal unique machine name (lowercase snake_case).`),label:L.describe(`Portal display label.`),description:L.optional(),routePrefix:v().regex(/^\/[a-z0-9/_-]*$/i,`routePrefix must start with "/" and be url-safe`).describe(`Root URL path for the portal (must start with "/").`),domain:v().optional().describe(`Optional vanity domain (e.g. "support.acme.com").`),layout:Mp.default(`minimal`).describe(`Shell layout for the portal.`),theme:wp.optional().describe(`Theme tokens.`),locale:E([j(`auto`),v()]).optional().default(`auto`).describe(`Locale resolution strategy.`),seo:Ap.optional(),authMode:jp.default(`authenticated`).describe(`Authentication mode for the portal.`),profiles:w(I).min(1,`A portal must admit at least one profile (use a dedicated profile for "anonymous-only" portals).`).describe(`Profiles admitted to the portal.`),anonymousEntry:kp.optional(),navigation:w(Ep).describe(`Flat list of portal entry points (references to existing metadata).`),defaultRoute:T({viewRef:v().optional(),actionRef:v().optional(),dashboardName:I.optional()}).optional().describe(`Landing surface when the user hits the portal root.`),embeddable:b().optional().default(!1),allowedEmbedOrigins:w(v()).optional(),active:b().optional().default(!0)}));A([`count`,`sum`,`avg`,`min`,`max`,`count_distinct`,`percentile`,`median`,`stddev`,`variance`]).describe(`Standard aggregation functions`);var Pp=A([`asc`,`desc`]).describe(`Sort order direction`),Fp=F(()=>T({field:v().describe(`Field name to sort by`),order:Pp.describe(`Sort direction`)}).describe(`Sort field and direction pair`));A([`insert`,`update`,`delete`,`upsert`]).describe(`Data mutation event types`),A([`read_uncommitted`,`read_committed`,`repeatable_read`,`serializable`,`snapshot`]).describe(`Transaction isolation levels (snake_case standard)`),A([`lru`,`lfu`,`ttl`,`fifo`]).describe(`Cache eviction strategy`);var Ip=F(()=>T({$field:v().describe(`Field Reference/Column Name`)}));F(()=>T({$eq:x().optional(),$ne:x().optional()})),F(()=>T({$gt:E([y(),C(),Ip]).optional(),$gte:E([y(),C(),Ip]).optional(),$lt:E([y(),C(),Ip]).optional(),$lte:E([y(),C(),Ip]).optional()})),F(()=>T({$in:w(x()).optional(),$nin:w(x()).optional()})),F(()=>T({$between:O([E([y(),C(),Ip]),E([y(),C(),Ip])]).optional()})),F(()=>T({$contains:v().optional(),$notContains:v().optional(),$startsWith:v().optional(),$endsWith:v().optional()})),F(()=>T({$null:b().optional(),$exists:b().optional()}));var Lp=F(()=>T({$eq:x().optional(),$ne:x().optional(),$gt:E([y(),C(),Ip]).optional(),$gte:E([y(),C(),Ip]).optional(),$lt:E([y(),C(),Ip]).optional(),$lte:E([y(),C(),Ip]).optional(),$in:w(x()).optional(),$nin:w(x()).optional(),$between:O([E([y(),C(),Ip]),E([y(),C(),Ip])]).optional(),$contains:v().optional(),$notContains:v().optional(),$startsWith:v().optional(),$endsWith:v().optional(),$null:b().optional(),$exists:b().optional()})),Rp=M(()=>k(v(),S()).and(T({$and:w(Rp).optional(),$or:w(Rp).optional(),$not:Rp.optional()})));F(()=>T({where:Rp.optional()}));var zp=M(()=>T({$and:w(E([k(v(),Lp),zp])).optional(),$or:w(E([k(v(),Lp),zp])).optional(),$not:E([k(v(),Lp),zp]).optional()})),Bp=F(()=>T({name:v().describe(`Region name (e.g. "sidebar", "main", "header")`),width:A([`small`,`medium`,`large`,`full`]).optional(),components:w(M(()=>Up)).describe(`Components in this region`)})),Vp=A(`page:header.page:footer.page:sidebar.page:tabs.page:accordion.page:card.page:section.record:details.record:highlights.record:related_list.record:activity.record:chatter.record:path.record:alert.record:quick_actions.record:reference_rail.record:history.app:launcher.nav:menu.nav:breadcrumb.global:search.global:notifications.user:profile.ai:chat_window.ai:suggestion.element:text.element:number.element:image.element:divider.element:button.element:filter.element:form.element:record_picker.element:text_input`.split(`.`)),Hp=F(()=>T({object:v().describe(`Object to query`),view:v().optional().describe(`Named view to apply`),filter:Rp.optional().describe(`Additional filter criteria`),sort:w(Fp).optional().describe(`Sort order`),limit:y().int().positive().optional().describe(`Max records to display`)})),Up=F(()=>T({type:E([Vp,v()]).describe(`Component Type (Standard enum or custom string)`),id:v().optional().describe(`Unique instance ID`),label:L.optional(),properties:k(v(),S()).optional().default({}).describe(`Component props passed to the widget. See component.zod.ts for schemas.`),events:k(v(),v()).optional().describe(`Event handlers map`),style:k(v(),v()).optional().describe(`Inline styles or utility classes`),className:v().optional().describe(`CSS class names`),responsiveStyles:_f.optional().describe(`Per-breakpoint scoped style maps (ADR-0065)`),visibility:Fu.optional().describe(`Visibility predicate (CEL).`),dataSource:Hp.optional().describe(`Per-element data binding for multi-object pages`),responsive:hf.optional().describe(`Responsive layout configuration`),aria:Ru.optional().describe(`ARIA accessibility attributes`)})),Wp=F(()=>T({name:v().describe("Variable name. Exposed to expressions as `page.<name>`."),type:A([`string`,`number`,`boolean`,`object`,`array`,`record_id`]).default(`string`),defaultValue:S().optional().describe(`Initial value. Defaults to a type-appropriate empty value when omitted.`),source:v().optional().describe("Component id that writes this variable (e.g. an element:record_picker whose `id` matches).")})),Gp=F(()=>A([`record`,`home`,`app`,`utility`,`list`]).describe(`Page type — the page KIND. Only types with a dedicated renderer are authorizable; visualizations of a list page live in interfaceConfig, not here.`)),Kp=F(()=>T({source:v().optional().describe(`Source object name for the page`),columns:E([w(v()),w(Ef)]).optional().describe(`Columns shown by the page. Blank = all object fields. Defined directly on the page (no view inheritance).`),sort:w(Fp).optional().describe(`Default sort order for the page, defined directly on the page.`),filterBy:w(wf).optional().describe(`Always-on page filter (base filter).`),levels:y().int().min(1).optional().describe(`Number of hierarchy levels to display`),sourceView:v().optional().describe(`@deprecated Legacy named-view inheritance. Define columns/sort/filterBy on the page instead.`),appearance:Rf.optional().describe(`Appearance and visualization configuration`),userFilters:Vf.optional().describe(`End-user quick-filter bar for this page (overrides the source view's userFilters)`),userActions:Lf.optional().describe(`User action toggles`),addRecord:Hf.optional().describe(`Add record entry point configuration`),buttons:w(v()).optional().describe(`Toolbar buttons — names of the source object's actions to surface in the page toolbar`),recordAction:A([`drawer`,`page`,`modal`,`none`]).optional().describe(`How clicking a record opens its detail (drawer | page | modal | none). Default: drawer`),showRecordCount:b().optional().describe(`Show record count at page bottom`),allowPrinting:b().optional().describe(`Allow users to print the page`)}).describe(`Interface-level page configuration (Airtable parity)`)),qp=F(()=>T({name:I.describe(`Page unique name (lowercase snake_case)`),label:L,description:L.optional(),icon:v().optional().describe(`Page icon name`),type:Gp.default(`record`).describe(`Page type`),variables:w(Wp).optional().describe("Local page state, exposed to expressions as `page.<name>` and writable by interactive elements via `source` (master/detail, filtered dashboards)."),object:v().optional().describe(`Bound object (for Record pages)`),template:v().default(`default`).describe(`Layout template name (e.g. "header-sidebar-main")`),regions:w(Bp).optional().default([]).describe(`Layout regions (header, main, sidebar, footer) with their components. Optional — list pages use interfaceConfig, slotted pages use slots, and an empty full page falls back to the synthesized default layout.`),isDefault:b().default(!1),assignedProfiles:w(v()).optional(),interfaceConfig:Kp.optional().describe(`Interface-level page configuration (for Airtable-style interface pages)`),aria:Ru.optional().describe(`ARIA accessibility attributes`),kind:A([`full`,`slotted`]).default(`full`).describe(`Page override mode: full (default) or slotted (partial overrides)`),slots:T({header:E([Up,w(Up)]).optional(),actions:E([Up,w(Up)]).optional(),alerts:E([Up,w(Up)]).optional(),highlights:E([Up,w(Up)]).optional(),details:E([Up,w(Up)]).optional(),tabs:E([Up,w(Up)]).optional(),discussion:E([Up,w(Up)]).optional()}).optional().describe(`Slot override map for slotted pages`)})),Jp=F(()=>A([`bar`,`horizontal-bar`,`column`,`line`,`area`,`pie`,`donut`,`funnel`,`scatter`,`treemap`,`sankey`,`gauge`,`solid-gauge`,`metric`,`kpi`,`bullet`,`radar`,`table`,`pivot`])),Yp=F(()=>T({field:v().describe(`Data field key`),title:L.optional().describe(`Axis display title`),format:v().optional().describe(`Value format string (e.g., "$0,0.00")`),min:y().optional().describe(`Minimum value`),max:y().optional().describe(`Maximum value`),stepSize:y().optional().describe(`Step size for ticks`),showGridLines:b().default(!0),position:A([`left`,`right`,`top`,`bottom`]).optional().describe(`Axis position`),logarithmic:b().default(!1)})),Xp=F(()=>T({name:v().describe(`Field name or series identifier`),label:L.optional().describe(`Series display label`),type:Jp.optional().describe(`Override chart type for this series`),color:v().optional().describe(`Series color (hex/rgb/token)`),stack:v().optional().describe(`Stack identifier to group series`),yAxis:A([`left`,`right`]).default(`left`).describe(`Bind to specific Y-Axis`),variant:A([`primary`,`comparison`]).default(`primary`).optional().describe(`Series visual role`),dashArray:v().optional().describe(`SVG stroke-dasharray override`),opacity:y().min(0).max(1).optional().describe(`Series opacity override`)})),Zp=F(()=>T({type:A([`line`,`region`]).default(`line`),axis:A([`x`,`y`]).default(`y`),value:E([y(),v()]).describe(`Start value`),endValue:E([y(),v()]).optional().describe(`End value for regions`),color:v().optional(),label:L.optional(),style:A([`solid`,`dashed`,`dotted`]).default(`dashed`)})),Qp=F(()=>T({tooltips:b().default(!0),zoom:b().default(!1),brush:b().default(!1),clickAction:v().optional().describe(`Action ID to trigger on click`)})),$p=F(()=>T({type:Jp,title:L.optional().describe(`Chart title`),subtitle:L.optional().describe(`Chart subtitle`),description:L.optional().describe(`Accessibility description`),xAxis:Yp.optional().describe(`X-Axis configuration`),yAxis:w(Yp).optional().describe(`Y-Axis configuration (support dual axis)`),series:w(Xp).optional().describe(`Defined series configuration`),colors:E([w(v()),k(v(),v())]).optional().describe(`Color palette (string[]) or value→color map ({ value: color })`),height:y().optional().describe(`Fixed height in pixels`),showLegend:b().default(!0).describe(`Display legend`),showDataLabels:b().default(!1).describe(`Display data labels`),annotations:w(Zp).optional(),interaction:Qp.optional(),aria:Ru.optional().describe(`ARIA accessibility attributes`)})),em=F(()=>A([`default`,`blue`,`teal`,`orange`,`purple`,`success`,`warning`,`danger`]).describe(`Widget color variant`)),tm=F(()=>A([`script`,`url`,`modal`,`flow`,`api`]).describe(`Widget action type`)),nm=F(()=>T({label:L.describe(`Action button label`),actionUrl:v().describe(`URL or target for the action`),actionType:tm.optional().describe(`Type of action`),icon:v().optional().describe(`Icon identifier for the action button`)}).describe(`Dashboard header action`)),rm=F(()=>T({showTitle:b().default(!0).describe(`Show dashboard title in header`),showDescription:b().default(!0).describe(`Show dashboard description in header`),actions:w(nm).optional().describe(`Header action buttons`)}).describe(`Dashboard header configuration`)),im=F(()=>T({id:I.describe(`Unique widget identifier (snake_case)`),title:L.optional().describe(`Widget title`),description:L.optional().describe(`Widget description text below the header`),type:Jp.default(`metric`).describe(`Visualization type`),chartConfig:$p.optional().describe(`Chart visualization configuration`),colorVariant:em.optional().describe(`Widget color variant for theming`),requiresObject:v().optional().describe(`Hide the widget unless the named object is registered`),requiresService:v().optional().describe(`Hide the widget unless the named kernel service is registered`),actionUrl:v().optional().describe(`URL or target for the widget action button`),actionType:tm.optional().describe(`Type of action for the widget action button`),actionIcon:v().optional().describe(`Icon identifier for the widget action button`),filter:Rp.optional().describe(`Presentation-scope filter (runtimeFilter)`),compareTo:E([j(`previousPeriod`),j(`previousYear`),T({offset:v().regex(/^\d+[dwMy]$/,`Offset must match <N>(d|w|M|y), e.g. "7d", "1M", "1y"`)})]).optional().describe(`Period-over-period comparison window`),dataset:I.describe(`Dataset name to bind (ADR-0021)`),dimensions:w(v()).optional().describe(`Dimension names — X/group/split`),values:w(v()).min(1).describe(`Measure names — Y (at least one)`),layout:T({x:y(),y:y(),w:y(),h:y()}).optional().describe(`Grid layout position (auto-flowed when omitted)`),options:S().optional().describe(`Widget specific configuration`),suppressWarnings:w(v()).optional().describe(`Build diagnostic rule ids suppressed on this widget`),responsive:hf.optional().describe(`Responsive layout configuration`),aria:Ru.optional().describe(`ARIA accessibility attributes`)})),am=F(()=>T({object:v().describe(`Source object name`),valueField:v().describe(`Field to use as option value`),labelField:v().describe(`Field to use as option label`),filter:Rp.optional().describe(`Filter to apply to source object`)}).describe(`Dynamic filter options from object`)),om=F(()=>T({field:v().describe(`Field name to filter on`),label:L.optional().describe(`Display label for the filter`),type:A([`text`,`select`,`date`,`number`,`lookup`]).optional().describe(`Filter input type`),options:w(T({value:E([v(),y(),b()]).describe(`Option value`),label:L})).optional().describe(`Static filter options`),optionsFrom:am.optional().describe(`Dynamic filter options from object`),defaultValue:E([v(),y(),b()]).optional().describe(`Default filter value`),scope:A([`dashboard`,`widget`]).default(`dashboard`).describe(`Filter application scope`),targetWidgets:w(v()).optional().describe(`Widget IDs to apply this filter to`)})),sm=F(()=>T({name:I.describe(`Dashboard unique name`),label:L.describe(`Dashboard label`),description:L.optional().describe(`Dashboard description`),header:rm.optional().describe(`Dashboard header configuration`),widgets:w(im).describe(`Widgets to display`),columns:y().int().min(1).max(24).optional().describe(`Number of grid columns (default 12)`),gap:y().int().min(0).optional().describe(`Grid gap in Tailwind spacing units`),refreshInterval:y().optional().describe(`Auto-refresh interval in seconds`),dateRange:T({field:v().optional().describe(`Default date field name for time-based filtering`),defaultRange:A([`today`,`yesterday`,`this_week`,`last_week`,`this_month`,`last_month`,`this_quarter`,`last_quarter`,`this_year`,`last_year`,`last_7_days`,`last_30_days`,`last_90_days`,`custom`]).default(`this_month`).describe(`Default date range preset`),allowCustomRange:b().default(!0).describe(`Allow users to pick a custom date range`)}).optional().describe(`Global dashboard date range filter configuration`),globalFilters:w(om).optional().describe(`Global filters that apply to all widgets in the dashboard`),aria:Ru.optional().describe(`ARIA accessibility attributes`),performance:vf.optional().describe(`Performance optimization settings`),protection:qu.optional().describe(`Package author protection block — lock policy for this dashboard.`),...Ku})),cm=A([`tabular`,`summary`,`matrix`,`joined`]);F(()=>T({field:v().describe(`Field name`),label:L.optional().describe(`Override label`),aggregate:A([`sum`,`avg`,`max`,`min`,`count`,`unique`]).optional().describe(`Aggregation function`),responsive:hf.optional().describe(`Responsive visibility for this column`)})),F(()=>T({field:v().describe(`Field to group by`),sortOrder:A([`asc`,`desc`]).default(`asc`),dateGranularity:A([`day`,`week`,`month`,`quarter`,`year`]).optional().describe(`For date fields`)}));var lm=F(()=>$p.extend({xAxis:v().describe(`Grouping field for X-Axis`),yAxis:v().describe(`Summary field for Y-Axis`),groupBy:v().optional().describe(`Additional grouping field`)})),um=F(()=>T({name:I,label:L.optional(),description:L.optional(),type:A([`tabular`,`summary`,`matrix`]).default(`tabular`),chart:lm.optional(),dataset:I.optional().describe(`Dataset name to bind (ADR-0021)`),rows:w(v()).optional().describe(`Dimension names down (dataset-bound)`),columns:w(v()).optional().describe(`Dimension names across (matrix, dataset-bound)`),values:w(v()).optional().describe(`Measure names to show (dataset-bound)`),runtimeFilter:Rp.optional().describe(`Render-time scope filter (dataset-bound)`)})),dm=F(()=>T({name:I.describe(`Report unique name`),label:L.describe(`Report label`),description:L.optional(),type:cm.default(`tabular`).describe(`Report format type`),dataset:I.optional().describe(`Dataset name to bind (ADR-0021)`),rows:w(v()).optional().describe(`Dimension names down`),columns:w(v()).optional().describe(`Dimension names across (matrix)`),values:w(v()).optional().describe(`Measure names to show`),runtimeFilter:Rp.optional().describe(`Render-time scope filter`),drilldown:b().default(!0).describe(`Click-through to underlying records`),chart:lm.optional().describe(`Embedded chart configuration`),aria:Ru.optional().describe(`ARIA accessibility attributes`),performance:vf.optional().describe(`Performance optimization settings`),blocks:w(um).optional().describe(`Sub-reports for type=joined`),protection:qu.optional().describe(`Package author protection block — lock policy for this report.`),...Ku}).superRefine((e,t)=>{e.type===`joined`?(!e.blocks||e.blocks.length===0)&&t.addIssue({code:`custom`,message:"a `joined` report needs `blocks`.",path:[`blocks`]}):(!e.dataset||!e.values||e.values.length===0)&&t.addIssue({code:`custom`,message:"a report needs `dataset` + `values` (measure names).",path:[`dataset`]})})),fm=F(()=>T({field:v(),order:A([`asc`,`desc`]).default(`asc`)})),pm=A([`count`,`sum`,`avg`,`min`,`max`,`count_distinct`,`array_agg`,`string_agg`]),mm=A([`day`,`week`,`month`,`quarter`,`year`]),hm=F(()=>E([v(),T({field:v().describe(`Field to group by`),dateGranularity:mm.optional().describe(`Bucket date values into uniform periods (day/week/month/quarter/year)`),alias:v().optional().describe(`Alias for the projected group value`)})])),gm=F(()=>T({function:pm.describe(`Aggregation function`),field:v().optional().describe(`Field to aggregate (optional for COUNT(*))`),alias:v().describe(`Result column alias`),distinct:b().optional().describe(`Apply DISTINCT before aggregation`),filter:Rp.optional().describe(`Filter/Condition to apply to the aggregation (FILTER WHERE clause)`)})),_m=A([`inner`,`left`,`right`,`full`]),vm=A([`auto`,`database`,`hash`,`loop`]),ym=M(()=>T({type:_m.describe(`Join type`),strategy:vm.optional().describe(`Execution strategy hint`),object:v().describe(`Object/table to join`),alias:v().optional().describe(`Table alias`),on:Rp.describe(`Join condition`),subquery:M(()=>Em).optional().describe(`Subquery instead of object`)})),bm=A([`row_number`,`rank`,`dense_rank`,`percent_rank`,`lag`,`lead`,`first_value`,`last_value`,`sum`,`avg`,`count`,`min`,`max`]),xm=F(()=>T({partitionBy:w(v()).optional().describe(`PARTITION BY fields`),orderBy:w(fm).optional().describe(`ORDER BY specification`),frame:T({type:A([`rows`,`range`]).optional(),start:v().optional().describe(`Frame start (e.g., "UNBOUNDED PRECEDING", "1 PRECEDING")`),end:v().optional().describe(`Frame end (e.g., "CURRENT ROW", "1 FOLLOWING")`)}).optional().describe(`Window frame specification`)})),Sm=F(()=>T({function:bm.describe(`Window function name`),field:v().optional().describe(`Field to operate on (for aggregate window functions)`),alias:v().describe(`Result column alias`),over:xm.describe(`Window specification (OVER clause)`)})),Cm=M(()=>E([v(),T({field:v(),fields:w(Cm).optional(),alias:v().optional()})])),wm=F(()=>T({query:v().describe(`Search query text`),fields:w(v()).optional().describe(`Fields to search in (if not specified, searches all text fields)`),fuzzy:b().optional().default(!1).describe(`Enable fuzzy matching (tolerates typos)`),operator:A([`and`,`or`]).optional().default(`or`).describe(`Logical operator between terms`),boost:k(v(),y()).optional().describe(`Field-specific relevance boosting (field name -> boost factor)`),minScore:y().optional().describe(`Minimum relevance score threshold`),language:v().optional().describe(`Language for text analysis (e.g., "en", "zh", "es")`),highlight:b().optional().default(!1).describe(`Enable search result highlighting`)})),Tm=T({object:v().describe(`Object name (e.g. account)`),fields:w(Cm).optional().describe(`Fields to retrieve`),where:Rp.optional().describe(`Filtering criteria (WHERE)`),search:wm.optional().describe(`Full-text search configuration ($search parameter)`),orderBy:w(fm).optional().describe(`Sorting instructions (ORDER BY)`),limit:y().optional().describe(`Max records to return (LIMIT)`),offset:y().optional().describe(`Records to skip (OFFSET)`),top:y().optional().describe(`Alias for limit (OData compatibility)`),cursor:k(v(),S()).optional().describe(`Cursor for keyset pagination`),joins:w(ym).optional().describe(`Explicit Table Joins`),aggregations:w(gm).optional().describe(`Aggregation functions`),groupBy:w(hm).optional().describe("GROUP BY targets (strings or `{field, dateGranularity?}` objects for date bucketing)"),having:Rp.optional().describe(`HAVING clause for aggregation filtering`),windowFunctions:w(Sm).optional().describe(`Window functions with OVER clause`),distinct:b().optional().describe(`SELECT DISTINCT flag`)}),Em=F(()=>Tm.extend({expand:M(()=>k(v(),Em)).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.")})),Dm=F(()=>T({name:I.describe(`Dimension name — referenced by presentations`),label:L.optional(),field:v().describe("Base field, or `relationship[.relationship].field` path"),type:A([`string`,`number`,`date`,`boolean`,`lookup`]).optional(),dateGranularity:mm.optional()})),Om=A([`ratio`,`sum`,`difference`,`product`]),km=F(()=>T({name:I.describe(`Measure name — e.g. "revenue"; defined once`),label:L.optional(),aggregate:pm.optional().describe("Aggregation (sum/avg/count/...); omit when `derived` is set"),field:v().optional().describe(`Aggregated field; optional for count(*)`),filter:Rp.optional(),format:v().optional(),currency:v().length(3).optional().describe(`Display currency code (ISO 4217)`),certified:b().default(!1).describe(`Blessed metric (governance checkpoint)`),derived:T({op:Om,of:w(I).min(1)}).optional()})),Am=F(()=>T({name:I.describe(`Dataset unique name`),label:L.describe(`Dataset label`),description:L.optional(),object:v().describe(`Base object name`),include:w(v().refine(e=>e.split(`.`).length<=3,{message:`include path exceeds the 3-hop limit (ADR-0071)`})).optional().describe(`Relationship names/paths to join (derived from object graph; max 3 hops)`),filter:Rp.optional().describe(`Intrinsic dataset scope filter`),dimensions:w(Dm).describe(`Groupable axes`),measures:w(km).describe(`Aggregatable values`),protection:qu.optional().describe(`Package author protection block — lock policy for this dataset.`),...Ku}).superRefine((e,t)=>{let n=new Set;for(let r of e.measures)n.has(r.name)&&t.addIssue({code:`custom`,message:`duplicate measure name "${r.name}"`,path:[`measures`]}),n.add(r.name);let r=new Set;for(let n of e.dimensions)r.has(n.name)&&t.addIssue({code:`custom`,message:`duplicate dimension name "${n.name}"`,path:[`dimensions`]}),r.add(n.name);for(let r of e.measures){if(!r.derived){r.aggregate?!r.field&&r.aggregate!==`count`&&t.addIssue({code:`custom`,message:`measure "${r.name}" requires \`field\` (only \`count\` may omit it)`,path:[`measures`]}):t.addIssue({code:`custom`,message:`measure "${r.name}" requires \`aggregate\` (or a \`derived\` spec)`,path:[`measures`]});continue}for(let e of r.derived.of)e===r.name?t.addIssue({code:`custom`,message:`derived measure "${r.name}" cannot reference itself`,path:[`measures`]}):n.has(e)||t.addIssue({code:`custom`,message:`derived measure "${r.name}" references unknown measure "${e}"`,path:[`measures`]})}})),jm=F(()=>T({minWidth:y().default(44).describe(`Minimum touch target width in pixels (WCAG 2.5.5: 44px)`),minHeight:y().default(44).describe(`Minimum touch target height in pixels (WCAG 2.5.5: 44px)`),padding:y().optional().describe(`Additional padding around touch target in pixels`),hitSlop:T({top:y().optional().describe(`Extra hit area above the element`),right:y().optional().describe(`Extra hit area to the right of the element`),bottom:y().optional().describe(`Extra hit area below the element`),left:y().optional().describe(`Extra hit area to the left of the element`)}).optional().describe(`Invisible hit area extension beyond the visible bounds`)}).describe(`Touch target sizing configuration (WCAG accessible)`)),Mm=F(()=>A([`swipe`,`pinch`,`long_press`,`double_tap`,`drag`,`rotate`,`pan`]).describe(`Touch gesture type`)),Nm=F(()=>A([`up`,`down`,`left`,`right`])),Pm=F(()=>T({direction:w(Nm).describe(`Allowed swipe directions`),threshold:y().optional().describe(`Minimum distance in pixels to recognize swipe`),velocity:y().optional().describe(`Minimum velocity (px/ms) to trigger swipe`)}).describe(`Swipe gesture recognition settings`)),Fm=F(()=>T({minScale:y().optional().describe(`Minimum scale factor (e.g., 0.5 for 50%)`),maxScale:y().optional().describe(`Maximum scale factor (e.g., 3.0 for 300%)`)}).describe(`Pinch/zoom gesture recognition settings`)),Im=F(()=>T({duration:y().default(500).describe(`Hold duration in milliseconds to trigger long press`),moveTolerance:y().optional().describe(`Max movement in pixels allowed during press`)}).describe(`Long press gesture recognition settings`)),Lm=F(()=>T({type:Mm.describe(`Gesture type to configure`),label:L.optional().describe(`Descriptive label for the gesture action`),enabled:b().default(!0).describe(`Whether this gesture is active`),swipe:Pm.optional().describe(`Swipe gesture settings (when type is swipe)`),pinch:Fm.optional().describe(`Pinch gesture settings (when type is pinch)`),longPress:Im.optional().describe(`Long press settings (when type is long_press)`)}).describe(`Per-gesture configuration`));F(()=>T({gestures:w(Lm).optional().describe(`Configured gesture recognizers`),touchTarget:jm.optional().describe(`Touch target sizing and hit area`),hapticFeedback:b().optional().describe(`Enable haptic feedback on touch interactions`)}).merge(Ru.partial()).describe(`Touch and gesture interaction configuration`));var Rm=F(()=>T({enabled:b().default(!1).describe(`Enable focus trapping within this container`),initialFocus:v().optional().describe(`CSS selector for the element to focus on activation`),returnFocus:b().default(!0).describe(`Return focus to trigger element on deactivation`),escapeDeactivates:b().default(!0).describe(`Allow Escape key to deactivate the focus trap`)}).describe(`Focus trap configuration for modal-like containers`)),zm=F(()=>T({key:v().describe(`Key combination (e.g., "Ctrl+S", "Alt+N", "Escape")`),action:v().describe(`Action identifier to invoke when shortcut is triggered`),description:L.optional().describe(`Human-readable description of what the shortcut does`),scope:A([`global`,`view`,`form`,`modal`,`list`]).default(`global`).describe(`Scope in which this shortcut is active`)}).describe(`Keyboard shortcut binding`)),Bm=F(()=>T({tabOrder:A([`auto`,`manual`]).default(`auto`).describe(`Tab order strategy: auto (DOM order) or manual (explicit tabIndex)`),skipLinks:b().default(!1).describe(`Provide skip-to-content navigation links`),focusVisible:b().default(!0).describe(`Show visible focus indicators for keyboard users`),focusTrap:Rm.optional().describe(`Focus trap settings`),arrowNavigation:b().default(!1).describe(`Enable arrow key navigation between focusable items`)}).describe(`Focus and tab navigation management`));F(()=>T({shortcuts:w(zm).optional().describe(`Registered keyboard shortcuts`),focusManagement:Bm.optional().describe(`Focus and tab order management`),rovingTabindex:b().default(!1).describe(`Enable roving tabindex pattern for composite widgets`)}).merge(Ru.partial()).describe(`Keyboard navigation and shortcut configuration`));var Vm=F(()=>T({primary:v().describe(`Primary brand color (hex, rgb, or hsl)`),secondary:v().optional().describe(`Secondary brand color`),accent:v().optional().describe(`Accent color for highlights`),success:v().optional().describe(`Success state color (default: green)`),warning:v().optional().describe(`Warning state color (default: yellow)`),error:v().optional().describe(`Error state color (default: red)`),info:v().optional().describe(`Info state color (default: blue)`),background:v().optional().describe(`Background color`),surface:v().optional().describe(`Surface/card background color`),text:v().optional().describe(`Primary text color`),textSecondary:v().optional().describe(`Secondary text color`),border:v().optional().describe(`Border color`),disabled:v().optional().describe(`Disabled state color`),primaryLight:v().optional().describe(`Lighter shade of primary`),primaryDark:v().optional().describe(`Darker shade of primary`),secondaryLight:v().optional().describe(`Lighter shade of secondary`),secondaryDark:v().optional().describe(`Darker shade of secondary`)})),Hm=F(()=>T({fontFamily:T({base:v().optional().describe(`Base font family (default: system fonts)`),heading:v().optional().describe(`Heading font family`),mono:v().optional().describe(`Monospace font family for code`)}).optional(),fontSize:T({xs:v().optional().describe(`Extra small font size (e.g., 0.75rem)`),sm:v().optional().describe(`Small font size (e.g., 0.875rem)`),base:v().optional().describe(`Base font size (e.g., 1rem)`),lg:v().optional().describe(`Large font size (e.g., 1.125rem)`),xl:v().optional().describe(`Extra large font size (e.g., 1.25rem)`),"2xl":v().optional().describe(`2X large font size (e.g., 1.5rem)`),"3xl":v().optional().describe(`3X large font size (e.g., 1.875rem)`),"4xl":v().optional().describe(`4X large font size (e.g., 2.25rem)`)}).optional(),fontWeight:T({light:y().optional().describe(`Light weight (default: 300)`),normal:y().optional().describe(`Normal weight (default: 400)`),medium:y().optional().describe(`Medium weight (default: 500)`),semibold:y().optional().describe(`Semibold weight (default: 600)`),bold:y().optional().describe(`Bold weight (default: 700)`)}).optional(),lineHeight:T({tight:v().optional().describe(`Tight line height (e.g., 1.25)`),normal:v().optional().describe(`Normal line height (e.g., 1.5)`),relaxed:v().optional().describe(`Relaxed line height (e.g., 1.75)`),loose:v().optional().describe(`Loose line height (e.g., 2)`)}).optional(),letterSpacing:T({tighter:v().optional().describe(`Tighter letter spacing (e.g., -0.05em)`),tight:v().optional().describe(`Tight letter spacing (e.g., -0.025em)`),normal:v().optional().describe(`Normal letter spacing (e.g., 0)`),wide:v().optional().describe(`Wide letter spacing (e.g., 0.025em)`),wider:v().optional().describe(`Wider letter spacing (e.g., 0.05em)`)}).optional()})),Um=F(()=>T({0:v().optional().describe(`0 spacing (0)`),1:v().optional().describe(`Spacing unit 1 (e.g., 0.25rem)`),2:v().optional().describe(`Spacing unit 2 (e.g., 0.5rem)`),3:v().optional().describe(`Spacing unit 3 (e.g., 0.75rem)`),4:v().optional().describe(`Spacing unit 4 (e.g., 1rem)`),5:v().optional().describe(`Spacing unit 5 (e.g., 1.25rem)`),6:v().optional().describe(`Spacing unit 6 (e.g., 1.5rem)`),8:v().optional().describe(`Spacing unit 8 (e.g., 2rem)`),10:v().optional().describe(`Spacing unit 10 (e.g., 2.5rem)`),12:v().optional().describe(`Spacing unit 12 (e.g., 3rem)`),16:v().optional().describe(`Spacing unit 16 (e.g., 4rem)`),20:v().optional().describe(`Spacing unit 20 (e.g., 5rem)`),24:v().optional().describe(`Spacing unit 24 (e.g., 6rem)`)})),Wm=F(()=>T({none:v().optional().describe(`No border radius (0)`),sm:v().optional().describe(`Small border radius (e.g., 0.125rem)`),base:v().optional().describe(`Base border radius (e.g., 0.25rem)`),md:v().optional().describe(`Medium border radius (e.g., 0.375rem)`),lg:v().optional().describe(`Large border radius (e.g., 0.5rem)`),xl:v().optional().describe(`Extra large border radius (e.g., 0.75rem)`),"2xl":v().optional().describe(`2X large border radius (e.g., 1rem)`),full:v().optional().describe(`Full border radius (50%)`)})),Gm=F(()=>T({none:v().optional().describe(`No shadow`),sm:v().optional().describe(`Small shadow`),base:v().optional().describe(`Base shadow`),md:v().optional().describe(`Medium shadow`),lg:v().optional().describe(`Large shadow`),xl:v().optional().describe(`Extra large shadow`),"2xl":v().optional().describe(`2X large shadow`),inner:v().optional().describe(`Inner shadow (inset)`)})),Km=F(()=>T({xs:v().optional().describe(`Extra small breakpoint (e.g., 480px)`),sm:v().optional().describe(`Small breakpoint (e.g., 640px)`),md:v().optional().describe(`Medium breakpoint (e.g., 768px)`),lg:v().optional().describe(`Large breakpoint (e.g., 1024px)`),xl:v().optional().describe(`Extra large breakpoint (e.g., 1280px)`),"2xl":v().optional().describe(`2X large breakpoint (e.g., 1536px)`)})),qm=F(()=>T({duration:T({fast:v().optional().describe(`Fast animation (e.g., 150ms)`),base:v().optional().describe(`Base animation (e.g., 300ms)`),slow:v().optional().describe(`Slow animation (e.g., 500ms)`)}).optional(),timing:T({linear:v().optional().describe(`Linear timing function`),ease:v().optional().describe(`Ease timing function`),ease_in:v().optional().describe(`Ease-in timing function`),ease_out:v().optional().describe(`Ease-out timing function`),ease_in_out:v().optional().describe(`Ease-in-out timing function`)}).optional()})),Jm=F(()=>T({base:y().optional().describe(`Base z-index (e.g., 0)`),dropdown:y().optional().describe(`Dropdown z-index (e.g., 1000)`),sticky:y().optional().describe(`Sticky z-index (e.g., 1020)`),fixed:y().optional().describe(`Fixed z-index (e.g., 1030)`),modalBackdrop:y().optional().describe(`Modal backdrop z-index (e.g., 1040)`),modal:y().optional().describe(`Modal z-index (e.g., 1050)`),popover:y().optional().describe(`Popover z-index (e.g., 1060)`),tooltip:y().optional().describe(`Tooltip z-index (e.g., 1070)`)})),Ym=F(()=>A([`light`,`dark`,`auto`])),Xm=F(()=>A([`compact`,`regular`,`spacious`])),Zm=F(()=>A([`AA`,`AAA`])),Qm=F(()=>T({name:I.describe(`Unique theme identifier (snake_case)`),label:v().describe(`Human-readable theme name`),description:v().optional().describe(`Theme description`),mode:Ym.default(`light`).describe(`Theme mode (light, dark, or auto)`),colors:Vm.describe(`Color palette configuration`),typography:Hm.optional().describe(`Typography settings`),spacing:Um.optional().describe(`Spacing scale`),borderRadius:Wm.optional().describe(`Border radius scale`),shadows:Gm.optional().describe(`Box shadow effects`),breakpoints:Km.optional().describe(`Responsive breakpoints`),animation:qm.optional().describe(`Animation settings`),zIndex:Jm.optional().describe(`Z-index scale for layering`),customVars:k(v(),v()).optional().describe(`Custom CSS variables (key-value pairs)`),logo:T({light:v().optional().describe(`Logo URL for light mode`),dark:v().optional().describe(`Logo URL for dark mode`),favicon:v().optional().describe(`Favicon URL`)}).optional().describe(`Logo assets`),extends:v().optional().describe(`Base theme to extend from`),density:Xm.optional().describe(`Display density: compact, regular, or spacious`),wcagContrast:Zm.optional().describe(`WCAG color contrast level (AA or AAA)`),rtl:b().optional().describe(`Enable right-to-left layout direction`),touchTarget:jm.optional().describe(`Touch target sizing defaults`),keyboardNavigation:Bm.optional().describe(`Keyboard focus management settings`)}));A([`start`,`end`,`decision`,`assignment`,`loop`,`create_record`,`update_record`,`delete_record`,`get_record`,`http`,`notify`,`script`,`screen`,`wait`,`subflow`,`map`,`connector_action`,`parallel_gateway`,`join_gateway`,`boundary_event`]).options;var $m=F(()=>T({name:v().describe(`Variable name`),type:v().describe(`Data type (text, number, boolean, object, list)`),isInput:b().default(!1).describe(`Is input parameter`),isOutput:b().default(!1).describe(`Is output parameter`)})),eh=F(()=>T({id:v().describe(`Node unique ID`),type:v().min(1).describe(`Action type — a built-in FlowNodeAction id or a plugin-registered node type. Validated against the live action registry at registerFlow() (ADR-0018), not by a closed enum.`),label:v().describe(`Node label`),config:k(v(),S()).optional().describe(`Node configuration`),connectorConfig:T({connectorId:v(),actionId:v(),input:k(v(),S()).describe(`Mapped inputs for the action`)}).optional(),position:T({x:y(),y:y()}).optional(),timeoutMs:y().int().min(0).optional().describe(`Maximum execution time for this node in milliseconds`),inputSchema:k(v(),T({type:A([`string`,`number`,`boolean`,`object`,`array`]).describe(`Parameter type`),required:b().default(!1).describe(`Whether the parameter is required`),description:v().optional().describe(`Parameter description`)})).optional().describe(`Input parameter schema for this node`),outputSchema:k(v(),T({type:A([`string`,`number`,`boolean`,`object`,`array`]).describe(`Output type`),description:v().optional().describe(`Output description`)})).optional().describe(`Output schema declaration for this node`),waitEventConfig:T({eventType:A([`timer`,`signal`,`webhook`,`manual`,`condition`]).describe(`What kind of event resumes the execution`),timerDuration:v().optional().describe(`ISO 8601 duration (e.g., "PT1H") or wait time for timer events`),signalName:v().optional().describe(`Named signal or webhook event to wait for`),timeoutMs:y().int().min(0).optional().describe(`Maximum wait time before timeout (ms)`),onTimeout:A([`fail`,`continue`]).default(`fail`).describe(`Behavior when the wait times out`)}).optional().describe(`Configuration for wait node event resumption`),boundaryConfig:T({attachedToNodeId:v().describe(`Host node ID this boundary event monitors`),eventType:A([`error`,`timer`,`signal`,`cancel`]).describe(`Boundary event trigger type`),interrupting:b().default(!0).describe(`If true, the host activity is cancelled when this event fires`),errorCode:v().optional().describe(`Specific error code to catch (empty = catch all errors)`),timerDuration:v().optional().describe(`ISO 8601 duration for timer boundary events`),signalName:v().optional().describe(`Named signal to catch`)}).optional().describe(`Configuration for boundary events attached to host nodes`)})),th=F(()=>T({id:v().describe(`Edge unique ID`),source:v().describe(`Source Node ID`),target:v().describe(`Target Node ID`),condition:Fu.optional().describe(`Predicate (CEL) returning boolean used for branching.`),type:A([`default`,`fault`,`conditional`,`back`]).default(`default`).describe(`Connection type: default (normal flow), fault (error path), conditional (expression-guarded), or back (ADR-0044 declared back-edge — traversed normally at run time, but excluded from DAG cycle validation so a revise/rework loop can re-enter an earlier node)`),label:v().optional().describe(`Label on the connector`),isDefault:b().default(!1).describe(`Marks this edge as the default path when no other conditions match`)})),nh=F(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Machine name`),label:v().describe(`Flow label`),description:v().optional(),successMessage:v().optional().describe(`Toast shown when a screen flow completes (defaults to a generic "Done").`),errorMessage:v().optional().describe(`Toast shown when a screen flow fails (defaults to the raw error).`),version:y().int().default(1).describe(`Version number`),status:A([`draft`,`active`,`obsolete`,`invalid`]).default(`draft`).describe(`Deployment status`),template:b().default(!1).describe(`Is logic template (Subflow)`),type:A([`autolaunched`,`record_change`,`schedule`,`screen`,`api`]).describe(`Flow type`),variables:w($m).optional().describe(`Flow variables`),nodes:w(eh).describe(`Flow nodes`),edges:w(th).describe(`Flow connections`),active:b().default(!1).describe(`Is active (Deprecated: use status)`),runAs:A([`system`,`user`]).default(`user`).describe(`Execution identity for the run: system = elevated (bypasses RLS), user = the triggering user (RLS-respecting). A schedule-triggered run has no trigger user, so under user it runs UNSCOPED (elevated) — declare system to make that explicit.`),errorHandling:T({strategy:A([`fail`,`retry`,`continue`]).default(`fail`).describe(`How to handle node execution errors`),maxRetries:y().int().min(0).max(10).default(0).describe(`Number of retry attempts (only for retry strategy)`),retryDelayMs:y().int().min(0).default(1e3).describe(`Delay between retries in milliseconds`),backoffMultiplier:y().min(1).default(1).describe(`Multiplier for exponential backoff between retries`),maxRetryDelayMs:y().int().min(0).default(3e4).describe(`Maximum delay between retries in milliseconds`),jitter:b().default(!1).describe(`Add random jitter to retry delay to avoid thundering herd`),fallbackNodeId:v().optional().describe(`Node ID to jump to on unrecoverable error`)}).optional().describe(`Flow-level error handling configuration`),protection:qu.optional().describe(`Package author protection block — lock policy for this flow.`),...Ku}));F(()=>T({flowName:v().describe(`Flow machine name`),version:y().int().min(1).describe(`Version number`),definition:nh.describe(`Complete flow definition snapshot`),createdAt:v().datetime().describe(`When this version was created`),createdBy:v().optional().describe(`User who created this version`),changeNote:v().optional().describe(`Description of what changed in this version`)}));var rh=F(()=>T({type:j(`cron`),expression:Iu.describe('Cron expression — cron`0 0 * * *` for daily at midnight. Build emits {dialect:"cron",source} envelope.'),timezone:v().optional().default(`UTC`).describe(`Timezone for cron execution (e.g., "America/New_York")`)})),ih=F(()=>T({type:j(`interval`),intervalMs:y().int().positive().describe(`Interval in milliseconds`)})),ah=F(()=>T({type:j(`once`),at:v().datetime().describe(`ISO 8601 datetime when to execute`)})),oh=F(()=>D(`type`,[rh,ih,ah])),sh=F(()=>T({maxRetries:y().int().min(0).default(3).describe(`Maximum number of retry attempts`),backoffMs:y().int().positive().default(1e3).describe(`Initial backoff delay in milliseconds`),backoffMultiplier:y().positive().default(2).describe(`Multiplier for exponential backoff`)})),ch=F(()=>T({id:v().optional().describe("Unique job identifier (defaults to `name` when omitted)"),name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Job name (snake_case)`),label:v().optional().describe(`Human-readable label`),description:v().optional().describe(`Job description / purpose`),schedule:oh.describe(`Job schedule configuration`),handler:v().describe("Handler function name (must match a key in `defineStack({ functions })`)"),retryPolicy:sh.optional().describe(`Retry policy configuration`),timeout:y().int().positive().optional().describe(`Timeout in milliseconds`),enabled:b().default(!0).describe(`Whether the job is enabled`)})),lh=A([`running`,`success`,`failed`,`timeout`]);F(()=>T({jobId:v().describe(`Job identifier`),startedAt:v().datetime().describe(`ISO 8601 datetime when execution started`),completedAt:v().datetime().optional().describe(`ISO 8601 datetime when execution completed`),status:lh.describe(`Execution status`),error:v().optional().describe(`Error message if failed`),duration:y().int().optional().describe(`Execution duration in milliseconds`)}));var uh=F(()=>T({name:I.describe(`Unique role name (lowercase snake_case)`),label:v().describe(`Display label (e.g. VP of Sales)`),parent:v().optional().describe(`Parent Role ID (Reports To)`),description:v().optional()})),dh=A([`select`,`insert`,`update`,`delete`,`all`]),fh=F(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Policy unique identifier (snake_case)`),label:v().optional().describe(`Human-readable policy label`),description:v().optional().describe(`Policy description and business justification`),object:v().describe(`Target object name`),operation:dh.describe(`Database operation this policy applies to`),using:v().optional().describe("Filter condition for SELECT/UPDATE/DELETE. One of the four compiler-supported forms: `field = current_user.<prop>`, `field = 'literal'`, `field IN (current_user.<array>)`, or `1 = 1`. Optional for INSERT-only policies."),check:v().optional().describe(`Validation condition for INSERT/UPDATE (defaults to USING clause if not specified - enforced at application level)`),roles:w(v()).optional().describe(`Roles this policy applies to (omit for all roles)`),enabled:b().default(!0).describe(`Whether this policy is active`),priority:y().int().default(0).describe(`Policy evaluation priority (higher = evaluated first)`),tags:w(v()).optional().describe(`Policy categorization tags`)}).superRefine((e,t)=>{!e.using&&!e.check&&t.addIssue({code:ru.custom,message:`At least one of "using" or "check" must be specified. For SELECT/UPDATE/DELETE operations, provide "using". For INSERT operations, provide "check".`})}));F(()=>T({timestamp:v().describe(`ISO 8601 timestamp of the evaluation`),userId:v().describe(`User ID whose access was evaluated`),operation:A([`select`,`insert`,`update`,`delete`]).describe(`Database operation being performed`),object:v().describe(`Target object name`),policyName:v().describe(`Name of the RLS policy evaluated`),granted:b().describe(`Whether access was granted`),evaluationDurationMs:y().describe(`Policy evaluation duration in milliseconds`),matchedCondition:v().optional().describe(`Which USING/CHECK clause matched`),rowCount:y().optional().describe(`Number of rows affected`),metadata:k(v(),S()).optional().describe(`Additional audit event metadata`)}));var ph=F(()=>T({enabled:b().describe(`Enable RLS audit logging`),logLevel:A([`all`,`denied_only`,`granted_only`,`none`]).describe(`Which evaluations to log`),destination:A([`system_log`,`audit_trail`,`external`]).describe(`Audit log destination`),sampleRate:y().min(0).max(1).describe(`Sampling rate (0-1) for high-traffic environments`),retentionDays:y().int().default(90).describe(`Audit log retention period in days`),includeRowData:b().default(!1).describe(`Include row data in audit logs (security-sensitive)`),alertOnDenied:b().default(!0).describe(`Send alerts when access is denied`)}));F(()=>T({enabled:b().default(!0).describe(`Enable RLS enforcement globally`),defaultPolicy:A([`deny`,`allow`]).default(`deny`).describe(`Default action when no policies match`),allowSuperuserBypass:b().default(!0).describe(`Allow superusers to bypass RLS`),bypassRoles:w(v()).optional().describe(`Roles that bypass RLS (see all data)`),logEvaluations:b().default(!1).describe(`Log RLS policy evaluations for debugging`),cacheResults:b().default(!0).describe(`Cache RLS evaluation results`),cacheTtlSeconds:y().int().positive().default(300).describe(`Cache TTL in seconds`),prefetchUserContext:b().default(!0).describe(`Pre-fetch user context for performance`),audit:ph.optional().describe(`RLS audit logging configuration`)})),F(()=>T({id:v().describe(`User ID`),email:v().email().optional().describe(`User email`),tenantId:v().optional().describe(`Tenant/Organization ID`),role:E([v(),w(v())]).optional().describe(`User role(s)`),department:v().optional().describe(`User department`),attributes:k(v(),S()).optional().describe(`Additional custom user attributes`)})),F(()=>T({policyName:v().describe(`Policy name`),granted:b().describe(`Whether access was granted`),durationMs:y().optional().describe(`Evaluation duration in milliseconds`),error:v().optional().describe(`Error message if evaluation failed`),usingResult:b().optional().describe(`USING clause evaluation result`),checkResult:b().optional().describe(`CHECK clause evaluation result`)}));var mh=A([`own`,`own_and_reports`,`unit`,`unit_and_below`,`org`]),hh=F(()=>T({allowCreate:b().default(!1).describe(`Create permission`),allowRead:b().default(!1).describe(`Read permission`),allowEdit:b().default(!1).describe(`Edit permission`),allowDelete:b().default(!1).describe(`Delete permission`),allowTransfer:b().default(!1).describe(`[EXPERIMENTAL — not enforced] Change record ownership`),allowRestore:b().default(!1).describe(`[EXPERIMENTAL — not enforced] Restore from trash (Undelete)`),allowPurge:b().default(!1).describe(`[EXPERIMENTAL — not enforced] Permanently delete (Hard Delete/GDPR)`),viewAllRecords:b().default(!1).describe(`View All Data (Bypass Sharing)`),modifyAllRecords:b().default(!1).describe(`Modify All Data (Bypass Sharing)`),readScope:mh.optional().describe(`[ADR-0057 D1] Read depth: own|unit|unit_and_below|org`),writeScope:mh.optional().describe(`[ADR-0057 D1] Write depth: own|unit|unit_and_below|org`)})),gh=F(()=>T({readable:b().default(!0).describe(`Field read access`),editable:b().default(!1).describe(`Field edit access`)})),_h=F(()=>T({name:I.describe(`Permission set unique name (lowercase snake_case)`),label:v().optional().describe(`Display label`),isProfile:b().default(!1).describe(`Whether this is a user profile`),isDefault:b().default(!1).describe(`[ADR-0056 D7] When true, this profile is the FALLBACK assigned to authenticated users who have no explicit grants — an app declares its default access posture here instead of relying on the built-in member_default. Foundation for SSO/JIT provisioning.`),objects:k(v(),hh).describe(`Entity permissions`),fields:k(v(),gh).optional().describe(`Field level security`),systemPermissions:w(v()).optional().describe(`System level capabilities`),tabPermissions:k(v(),A([`visible`,`hidden`,`default_on`,`default_off`])).optional().describe(`App/tab visibility: visible, hidden, default_on (shown by default), default_off (available but hidden initially)`),rowLevelSecurity:w(fh).optional().describe(`Row-level security policies (see rls.zod.ts for full spec)`),contextVariables:k(v(),S()).optional().describe(`Context variables for RLS evaluation`)}));A([`private`,`public_read`,`public_read_write`,`controlled_by_parent`]),A([`owner`,`criteria`]);var vh=A([`read`,`edit`,`full`]),yh=A([`user`,`group`,`role`,`role_and_subordinates`,`guest`]),bh=T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Unique rule name (snake_case)`),label:v().optional().describe(`Human-readable label`),description:v().optional().describe(`Administrative notes`),object:v().describe(`Target Object Name`),active:b().default(!0),accessLevel:vh.default(`read`),sharedWith:T({type:yh,value:v().describe(`ID or Code of the User/Group/Role`)}).describe(`The recipient of the shared access`)}),xh=F(()=>bh.extend({type:j(`criteria`),condition:Fu.describe('Predicate (CEL). e.g. P`record.department == "Sales"`')})),Sh=F(()=>bh.extend({type:j(`owner`),ownedBy:T({type:yh,value:v()}).describe(`Source group/role whose records are being shared`)})),Ch=F(()=>D(`type`,[xh,Sh])),wh=F(()=>T({minLength:y().default(8).describe(`[EXPERIMENTAL — not enforced] Minimum password length`),requireUppercase:b().default(!0).describe(`[EXPERIMENTAL — not enforced] Require an uppercase letter`),requireLowercase:b().default(!0).describe(`[EXPERIMENTAL — not enforced] Require a lowercase letter`),requireNumbers:b().default(!0).describe(`[EXPERIMENTAL — not enforced] Require a number`),requireSymbols:b().default(!1).describe(`[EXPERIMENTAL — not enforced] Require a symbol`),expirationDays:y().optional().describe(`[EXPERIMENTAL — not enforced] Force password change every X days`),historyCount:y().default(3).describe(`[EXPERIMENTAL — not enforced] Prevent reusing last X passwords`)})),Th=F(()=>T({trustedRanges:w(v()).describe(`[EXPERIMENTAL — not enforced] CIDR ranges allowed to access (e.g. 10.0.0.0/8)`),blockUnknown:b().default(!1).describe(`[EXPERIMENTAL — not enforced] Block all IPs not in trusted ranges`),vpnRequired:b().default(!1).describe(`[EXPERIMENTAL — not enforced] Require VPN to access`)})),Eh=F(()=>T({idleTimeout:y().default(30).describe(`[EXPERIMENTAL — not enforced] Minutes before idle session logout`),absoluteTimeout:y().default(480).describe(`[EXPERIMENTAL — not enforced] Max session duration (minutes)`),forceMfa:b().default(!1).describe(`[EXPERIMENTAL — not enforced] Require 2FA for all users`)})),Dh=F(()=>T({logRetentionDays:y().default(180).describe(`[EXPERIMENTAL — not enforced] Days to retain audit logs`),sensitiveFields:w(v()).describe(`[EXPERIMENTAL — not enforced] Fields to redact in logs (e.g. password, ssn)`),captureRead:b().default(!1).describe(`[EXPERIMENTAL — not enforced] Log read access (High volume!)`)})),Oh=F(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`[EXPERIMENTAL — not enforced] Policy Name`),password:wh.optional(),network:Th.optional(),session:Eh.optional(),audit:Dh.optional(),isDefault:b().default(!1).describe(`[EXPERIMENTAL — not enforced] Apply to all users by default`),assignedProfiles:w(v()).optional().describe(`[EXPERIMENTAL — not enforced] Apply to specific profiles`)})),kh=F(()=>T({source:v().describe(`Source field/path`),target:v().describe(`Target field/path`),transform:v().optional().describe(`Transformation function name`)})),Ah=T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Unique endpoint ID`),path:v().regex(/^\//).describe(`URL Path (e.g. /api/v1/customers)`),method:yf.describe(`HTTP Method`),summary:v().optional(),description:v().optional(),type:A([`flow`,`script`,`object_operation`,`proxy`]).describe(`Implementation type`),target:v().describe(`Target Flow ID, Script Name, or Proxy URL`),objectParams:T({object:v().optional(),operation:A([`find`,`get`,`create`,`update`,`delete`]).optional()}).optional().describe(`For object_operation type`),inputMapping:w(kh).optional().describe(`Map Request Body to Internal Params`),outputMapping:w(kh).optional().describe(`Map Internal Result to Response Body`),authRequired:b().default(!0).describe(`Require authentication`),rateLimit:Sf.optional().describe(`Rate limiting policy`),cacheTtl:y().optional().describe(`Response cache TTL in seconds`)});Object.assign(Ah,{create:e=>e});var jh=A([`boolean`,`percentage`,`user_list`,`group`,`custom`]),Mh=F(()=>T({name:I.describe(`Feature key (snake_case)`),label:v().optional().describe(`Display label`),description:v().optional(),enabled:b().default(!1).describe(`Is globally enabled`),strategy:jh.default(`boolean`),conditions:T({percentage:y().min(0).max(100).optional(),users:w(v()).optional(),groups:w(v()).optional(),expression:Fu.optional().describe(`Custom predicate (CEL).`)}).optional(),environment:A([`dev`,`staging`,`prod`,`all`]).default(`all`).describe(`Environment validity`),expiresAt:v().datetime().optional().describe(`Feature flag expiration date`)}));Object.assign(Mh,{create:e=>e});var Nh=F(()=>E([v().describe(`Action Name`),T({type:v(),params:k(v(),S()).optional()})])),Ph=F(()=>E([v().describe(`Guard Name (e.g., "isManager", "amountGT1000")`),T({type:v(),params:k(v(),S()).optional()})])),Fh=F(()=>T({target:v().optional().describe(`Target State ID`),cond:Ph.optional().describe(`Condition (Guard) required to take this path`),actions:w(Nh).optional().describe(`Actions to execute during transition`),description:v().optional().describe(`Human readable description of this rule`)}));F(()=>T({type:v().describe(`Event Type (e.g. "APPROVE", "REJECT", "Submit")`),schema:k(v(),S()).optional().describe(`Expected event payload structure`)}));var Ih=M(()=>T({type:A([`atomic`,`compound`,`parallel`,`final`,`history`]).default(`atomic`),entry:w(Nh).optional().describe(`Actions to run when entering this state`),exit:w(Nh).optional().describe(`Actions to run when leaving this state`),on:k(v(),E([v(),Fh,w(Fh)])).optional().describe(`Map of Event Type -> Transition Definition`),always:w(Fh).optional(),initial:v().optional().describe(`Initial child state (if compound)`),states:k(v(),Ih).optional(),meta:T({label:v().optional(),description:v().optional(),color:v().optional(),aiInstructions:v().optional().describe(`Specific instructions for AI when in this state`)}).optional()})),Lh=F(()=>T({id:I.describe(`Unique Machine ID`),description:v().optional(),contextSchema:k(v(),S()).optional().describe(`Zod Schema for the machine context/memory`),initial:v().describe(`Initial State ID`),states:k(v(),Ih).describe(`State Nodes`),on:k(v(),E([v(),Fh,w(Fh)])).optional()})),Rh=F(()=>T({provider:A([`openai`,`azure_openai`,`anthropic`,`local`]).default(`openai`),model:v().describe(`Model name (e.g. gpt-4, claude-3-opus)`),temperature:y().min(0).max(2).default(.7),maxTokens:y().optional(),topP:y().optional()})),zh=F(()=>T({type:A([`action`,`flow`,`query`,`vector_search`]),name:v().describe(`Reference name (Action Name, Flow Name)`),description:v().optional().describe(`Override description for the LLM`)})),Bh=F(()=>T({topics:w(v()).describe(`Topics/Tags to recruit knowledge from`),indexes:w(v()).describe(`Vector Store Indexes`)})),Vh=F(()=>A([`json_object`,`json_schema`,`regex`,`grammar`,`xml`]).describe(`Output format for structured agent responses`)),Hh=F(()=>A([`trim`,`parse_json`,`validate`,`coerce_types`]).describe(`Post-processing step for structured output`)),Uh=F(()=>T({format:Vh.describe(`Expected output format`),schema:k(v(),S()).optional().describe(`JSON Schema definition for output`),strict:b().default(!1).describe(`Enforce exact schema compliance`),retryOnValidationFailure:b().default(!0).describe(`Retry generation when output fails validation`),maxRetries:y().int().min(0).default(3).describe(`Maximum retries on validation failure`),fallbackFormat:Vh.optional().describe(`Fallback format if primary format fails`),transformPipeline:w(Hh).optional().describe(`Post-processing steps applied to output`)}).describe(`Structured output configuration for agent responses`)),Wh=F(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Agent unique identifier`),label:v().describe(`Agent display name`),avatar:v().optional(),role:v().describe(`The persona/role (e.g. "Senior Support Engineer")`),instructions:v().describe(`System Prompt / Prime Directives`),model:Rh.optional(),lifecycle:Lh.optional().describe(`State machine defining the agent conversation follow and constraints`),surface:A([`ask`,`build`]).default(`ask`).describe(`Product surface this agent binds ('ask' | 'build') — ADR-0063 §1`),skills:w(v().regex(/^[a-z_][a-z0-9_]*$/)).optional().describe(`Skill names to attach (Agent→Skill→Tool architecture)`),tools:w(zh).optional().describe(`Direct tool references (legacy fallback)`),knowledge:Bh.optional().describe(`RAG access`),active:b().default(!0),access:w(v()).optional().describe(`Who can chat with this agent`),permissions:w(v()).optional().describe(`Required permissions or roles`),tenantId:v().optional().describe(`Tenant/Organization ID`),visibility:A([`global`,`organization`,`private`]).default(`organization`),planning:T({strategy:A([`react`,`plan_and_execute`,`reflexion`,`tree_of_thought`]).default(`react`).describe(`Autonomous reasoning strategy`),maxIterations:y().int().min(1).max(100).default(10).describe(`Maximum planning loop iterations`),allowReplan:b().default(!0).describe(`Allow dynamic re-planning based on intermediate results`)}).optional().describe(`Autonomous reasoning and planning configuration`),memory:T({longTerm:T({enabled:b().default(!1).describe(`Enable long-term memory persistence`),store:A([`vector`,`database`,`redis`]).default(`vector`).describe(`Long-term memory storage backend`),maxEntries:y().int().min(1).optional().describe(`Max entries in long-term memory`)}).optional().describe(`Long-term / persistent memory`),reflectionInterval:y().int().min(1).optional().describe(`Reflect every N interactions to improve behavior`)}).optional().describe(`Agent memory management`),guardrails:T({maxTokensPerInvocation:y().int().min(1).optional().describe(`Token budget per single invocation`),maxExecutionTimeSec:y().int().min(1).optional().describe(`Max execution time in seconds`),blockedTopics:w(v()).optional().describe(`Forbidden topics or action names`)}).optional().describe(`Safety guardrails for the agent`),structuredOutput:Uh.optional().describe(`Structured output format and validation configuration`),protection:qu.optional().describe(`Package author protection block — lock policy for this agent.`),...Ku})),Gh=F(()=>T({field:v().describe(`Context field to evaluate`),operator:A([`eq`,`neq`,`in`,`not_in`,`contains`]).describe(`Comparison operator`),value:E([v(),w(v())]).describe(`Expected value or values`)})),Kh=F(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Skill unique identifier (snake_case)`),label:v().describe(`Skill display name`),description:v().optional().describe(`Skill description`),surface:A([`ask`,`build`,`both`]).default(`ask`).describe(`Agent surface this skill binds to ('ask' | 'build' | 'both') — ADR-0063 §3`),instructions:v().optional().describe(`LLM instructions when skill is active`),tools:w(v().regex(/^[a-z_][a-z0-9_]*\*?$/)).describe("Tool names belonging to this skill (supports trailing wildcard, e.g. `action_*`)"),triggerPhrases:w(v()).optional().describe(`Phrases that activate this skill`),triggerConditions:w(Gh).optional().describe(`Programmatic activation conditions`),permissions:w(v()).optional().describe(`Required permissions or roles`),active:b().default(!0).describe(`Whether the skill is enabled`),protection:qu.optional().describe(`Package author protection block — lock policy for this skill.`),...Ku})),qh=F(()=>A([`data`,`action`,`flow`,`integration`,`vector_search`,`analytics`,`utility`]).describe(`Tool operational category`)),Jh=F(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Tool unique identifier (snake_case)`),label:v().describe(`Tool display name`),description:v().describe(`Tool description for LLM function calling`),category:qh.optional().describe(`Tool category for grouping and filtering`),parameters:k(v(),S()).describe(`JSON Schema for tool parameters`),outputSchema:k(v(),S()).optional().describe(`JSON Schema for tool output`),objectName:v().regex(/^[a-z_][a-z0-9_]*$/).optional().describe(`Target object name (snake_case)`),requiresConfirmation:b().default(!1).describe(`Require user confirmation before execution`),permissions:w(v()).optional().describe(`Required permissions or roles`),active:b().default(!0).describe(`Whether the tool is enabled`),builtIn:b().default(!1).describe(`Platform built-in tool flag`),protection:qu.optional().describe(`Package author protection block — lock policy for this tool.`),...Ku})),Yh=A([`beforeFind`,`afterFind`,`beforeFindOne`,`afterFindOne`,`beforeCount`,`afterCount`,`beforeAggregate`,`afterAggregate`,`beforeInsert`,`afterInsert`,`beforeUpdate`,`afterUpdate`,`beforeDelete`,`afterDelete`,`beforeUpdateMany`,`afterUpdateMany`,`beforeDeleteMany`,`afterDeleteMany`]),Xh=F(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Hook unique name (snake_case)`),label:v().optional().describe(`Description of what this hook does`),object:E([v(),w(v())]).describe(`Target object(s)`),events:w(Yh).describe(`Lifecycle events`),handler:E([v(),$l(e=>typeof e==`function`,{message:`Expected function`})]).optional().describe("Handler function name (string, post-build) or inline function (pre-build) — DEPRECATED, prefer `body`"),body:rf.optional().describe(`Hook body — expression (L1) or sandboxed JS (L2)`),priority:y().default(100).describe(`Execution priority`),async:b().default(!1).describe(`Run specifically as fire-and-forget`),condition:Fu.optional().describe('Predicate (CEL); hook runs only when TRUE. e.g. P`record.status == "closed" && record.amount > 1000`'),description:v().optional().describe(`Human-readable description of what this hook does`),retryPolicy:T({maxRetries:y().default(3).describe(`Maximum retry attempts on failure`),backoffMs:y().default(1e3).describe(`Backoff delay between retries in milliseconds`)}).optional().describe(`Retry policy for failed hook executions`),timeout:y().optional().describe(`Maximum execution time in milliseconds before the hook is aborted`),onError:A([`abort`,`log`]).default(`abort`).describe(`Error handling strategy`)}));F(()=>T({id:v().optional().describe(`Unique execution ID for tracing`),object:v(),event:Yh,input:k(v(),S()).describe(`Mutable input parameters`),result:S().optional().describe(`Operation result (After hooks only)`),previous:k(v(),S()).optional().describe(`Record state before operation`),session:T({userId:v().optional(),tenantId:v().optional(),roles:w(v()).optional(),accessToken:v().optional(),isSystem:b().optional().describe(`True when the call was made with an elevated system context (engine self-writes)`)}).optional().describe(`Current session context`),transaction:S().optional().describe(`Database transaction handle`),ql:S().describe(`ObjectQL Engine Reference`),api:S().optional().describe(`Cross-object data access (ScopedContext)`),user:T({id:v().optional(),name:v().optional(),email:v().optional()}).optional().describe(`Current user info shortcut`)}));var Zh=A([`none`,`constant`,`lookup`,`split`,`join`,`javascript`,`map`]),Qh=F(()=>T({source:E([v(),w(v())]).describe(`Source column header(s)`),target:E([v(),w(v())]).describe(`Target object field(s)`),transform:Zh.default(`none`),params:T({value:S().optional(),object:v().optional(),fromField:v().optional(),toField:v().optional(),autoCreate:b().optional(),valueMap:k(v(),S()).optional(),separator:v().optional()}).optional()})),$h=F(()=>T({name:I.describe(`Mapping unique name (lowercase snake_case)`),label:v().optional(),sourceFormat:A([`csv`,`json`,`xml`,`sql`]).default(`csv`),targetObject:v().describe(`Target Object Name`),fieldMapping:w(Qh),mode:A([`insert`,`update`,`upsert`]).default(`insert`),upsertKey:w(v()).optional().describe(`Fields to match for upsert (e.g. email)`),extractQuery:Em.optional().describe(`Query to run for export only`),errorPolicy:A([`skip`,`abort`,`retry`]).default(`skip`),batchSize:y().default(1e3)})),eg=A([`count`,`sum`,`avg`,`min`,`max`,`count_distinct`,`number`,`string`,`boolean`]),tg=A([`string`,`number`,`boolean`,`time`,`geo`]),ng=A([`second`,`minute`,`hour`,`day`,`week`,`month`,`quarter`,`year`]),rg=F(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Unique metric ID`),label:v().describe(`Human readable label`),description:v().optional(),type:eg,sql:v().describe(`SQL expression or field reference`),filters:w(T({sql:v()})).optional(),format:v().optional()})),ig=F(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Unique dimension ID`),label:v().describe(`Human readable label`),description:v().optional(),type:tg,sql:v().describe(`SQL expression or column reference`),granularities:w(ng).optional()})),ag=F(()=>T({name:v().describe(`Target cube name`),relationship:A([`one_to_one`,`one_to_many`,`many_to_one`]).default(`many_to_one`),sql:v().describe(`Join condition (ON clause)`)})),og=F(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Cube name (snake_case)`),title:v().optional(),description:v().optional(),sql:v().describe(`Base SQL statement or Table Name`),measures:k(v(),rg).describe(`Quantitative metrics`),dimensions:k(v(),ig).describe(`Qualitative attributes`),joins:k(v(),ag).optional(),refreshKey:T({every:v().optional(),sql:v().optional()}).optional(),public:b().default(!1)}));F(()=>T({cube:v().optional().describe(`Target cube name (optional when provided externally, e.g. in API request wrapper)`),measures:w(v()).describe(`List of metrics to calculate`),dimensions:w(v()).optional().describe(`List of dimensions to group by`),where:Rp.optional().describe(`Filtering criteria (canonical Query DSL FilterCondition)`),timeDimensions:w(T({dimension:v(),granularity:ng.optional(),dateRange:E([v(),w(v())]).optional()})).optional(),order:k(v(),A([`asc`,`desc`])).optional(),limit:y().optional(),offset:y().optional(),timezone:v().optional().default(`UTC`)}));var sg=A([`create`,`update`,`delete`,`undelete`,`api`]),cg=F(()=>T({name:I.describe(`Webhook unique name (lowercase snake_case)`),label:v().optional().describe(`Human-readable webhook label`),object:v().optional().describe(`Object to listen to (optional for manual webhooks)`),triggers:w(sg).optional().describe(`Events that trigger execution`),url:v().url().describe(`External webhook endpoint URL`),method:A([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`]).default(`POST`).describe(`HTTP method`),headers:k(v(),v()).optional().describe(`Custom HTTP headers`),body:S().optional().describe(`Request body payload (if not using default record data)`),payloadFields:w(v()).optional().describe(`Fields to include. Empty = All`),includeSession:b().default(!1).describe(`Include user session info`),authentication:T({type:A([`none`,`bearer`,`basic`,`api-key`]).describe(`Authentication type`),credentials:k(v(),v()).optional().describe(`Authentication credentials`)}).optional().describe(`Authentication configuration`),retryPolicy:T({maxRetries:y().int().min(0).max(10).default(3).describe(`Maximum retry attempts`),backoffStrategy:A([`exponential`,`linear`,`fixed`]).default(`exponential`).describe(`Backoff strategy`),initialDelayMs:y().int().min(100).default(1e3).describe(`Initial retry delay in milliseconds`),maxDelayMs:y().int().min(1e3).default(6e4).describe(`Maximum retry delay in milliseconds`)}).optional().describe(`Retry policy configuration`),timeoutMs:y().int().min(1e3).max(3e5).default(3e4).describe(`Request timeout in milliseconds`),secret:v().optional().describe(`Signing secret for HMAC signature verification`),isActive:b().default(!0).describe(`Whether webhook is active`),description:v().optional().describe(`Webhook description`),tags:w(v()).optional().describe(`Tags for organization`)}));F(()=>T({name:I.describe(`Webhook receiver unique name (lowercase snake_case)`),path:v().describe(`URL Path (e.g. /webhooks/stripe)`),verificationType:A([`none`,`header_token`,`hmac`,`ip_whitelist`]).default(`none`),verificationParams:T({header:v().optional(),secret:v().optional(),ips:w(v()).optional()}).optional(),action:A([`trigger_flow`,`script`,`upsert_record`]).default(`trigger_flow`),target:v().describe(`Flow ID or Script name`)}));var lg=F(()=>A([`auth`,`notification`,`workflow`,`marketing`,`custom`])),ug=F(()=>T({name:v().describe(`Variable name as referenced in placeholders (snake_case or dotted path)`),type:A([`string`,`number`,`boolean`,`date`,`url`,`user`,`record`]).default(`string`),required:b().default(!1),description:v().optional().describe(`Author hint shown in Studio`)})),dg=F(()=>T({name:v().regex(/^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)*$/,`name must be dotted snake_case`).describe(`Template identifier (dotted snake_case)`),label:v().describe(`Display label`),category:lg.default(`custom`),locale:v().default(`en-US`).describe(`BCP-47 locale (e.g. en-US, zh-CN)`),subject:v().describe(`Subject template`),bodyHtml:v().describe(`HTML body template`),bodyText:v().optional().describe(`Plain-text body template (auto-derived from HTML when omitted)`),variables:w(ug).default([]),fromOverride:fg().optional(),replyTo:v().optional(),active:b().default(!0),isSystem:b().default(!1),description:v().optional(),protection:qu.optional().describe(`Package author protection block — lock policy for this email template.`),...Ku}));function fg(){return T({name:v().optional(),address:v().email()})}var pg=F(()=>T({name:v().regex(/^[a-z][a-z0-9_]*$/,`name must be lowercase snake_case`).describe(`Doc name (= filename stem, snake_case; namespace prefix recommended, not required)`),label:v().optional().describe("Display title; defaults to the first `#` heading, then the name"),description:v().optional().describe("One-line summary for listings; from frontmatter `description:`"),content:v().describe(`Raw Markdown content (CommonMark + GFM)`),order:y().optional().describe(`Sort key within a book group (ADR-0046 §6)`),group:v().optional().describe(`Explicit book-group key (ADR-0046 §6); rules usually suffice`),translations:k(v(),T({label:v().optional(),description:v().optional(),content:v()})).optional().describe(`Per-locale {label?,description?,content} variants; the base doc is the fallback`)})),mg=F(()=>E([v(),T({doc:v().optional().describe(`Doc name to reference`),href:v().optional().describe("External link (use instead of `doc`)"),label:v().optional().describe(`Optional label override; title authority stays in the doc`),badge:v().optional().describe(`e.g. "beta" | "new"`),icon:v().optional()})])),hg=F(()=>E([v().describe(`Glob over doc names, e.g. "crm_guide_*"`),T({tag:v()}).describe(`Match by doc tag (§5 vocabulary)`)])),gg=F(()=>T({key:v().regex(/^[a-z][a-z0-9_]*$/,`group key must be lowercase snake_case`).describe("Stable group key (used by overrides, deep links, explicit `doc.group`)"),label:v().describe(`Section title — first-class, i18n-homed`),translations:k(v(),T({label:v()})).optional().describe(`Per-locale label variants`),order:y().optional().describe(`Order of THIS group within the book`),include:hg.optional().describe(`Rule that derives membership (glob or tag)`),package:v().optional().describe(`Scope the rule to a package id (default: the book package; cross-package via ADR-0048)`),pages:w(mg).optional().describe("OPTIONAL explicit override — hand-pin a curated order; wins over `include`")})),_g=F(()=>E([j(`org`),j(`public`),T({profile:v()})])),vg=F(()=>T({name:v().regex(/^[a-z][a-z0-9_]*$/,`name must be lowercase snake_case`).describe(`Book name (namespace prefix recommended, like every metadata name)`),label:v().optional().describe(`Display title`),description:v().optional(),translations:k(v(),T({label:v().optional(),description:v().optional()})).optional(),slug:v().optional().describe(`Portal URL segment; defaults to name sans prefix`),icon:v().optional(),order:y().optional().describe(`Orders books within the portal`),audience:_g.optional().describe(`Access audience; defaults to 'org' (inherits package grant)`),groups:w(gg).describe(`The spine: ordered sections. Two levels total.`)})),yg=F(()=>T({type:j(`oauth2`),authorizationUrl:v().url().describe(`OAuth2 authorization endpoint`),tokenUrl:v().url().describe(`OAuth2 token endpoint`),clientId:v().describe(`OAuth2 client ID`),clientSecret:v().describe(`OAuth2 client secret (typically from ENV)`),scopes:w(v()).optional().describe(`Requested OAuth2 scopes`),redirectUri:v().url().optional().describe(`OAuth2 redirect URI`),refreshToken:v().optional().describe(`Refresh token for token renewal`),tokenExpiry:y().optional().describe(`Token expiry timestamp`)})),bg=F(()=>T({type:j(`api-key`),key:v().describe(`API key value`),headerName:v().default(`X-API-Key`).describe(`HTTP header name for API key`),paramName:v().optional().describe(`Query parameter name (alternative to header)`)})),xg=F(()=>T({type:j(`basic`),username:v().describe(`Username`),password:v().describe(`Password`)})),Sg=F(()=>T({type:j(`bearer`),token:v().describe(`Bearer token`)})),Cg=F(()=>T({type:j(`none`)})),wg=F(()=>D(`type`,[yg,bg,xg,Sg,Cg])),Tg=F(()=>D(`type`,[T({type:j(`constant`),value:S().describe(`Constant value to use`)}).describe(`Set a constant value`),T({type:j(`cast`),targetType:A([`string`,`number`,`boolean`,`date`]).describe(`Target data type`)}).describe(`Cast to a specific data type`),T({type:j(`lookup`),table:v().describe(`Lookup table name`),keyField:v().describe(`Field to match on`),valueField:v().describe(`Field to retrieve`)}).describe(`Lookup value from another table`),T({type:j(`javascript`),expression:Fu.describe(`JS expression (dialect="js" recommended). e.g. value.toUpperCase()`)}).describe(`Custom JavaScript transformation`),T({type:j(`map`),mappings:k(v(),S()).describe(`Value mappings (e.g., {"Active": "active"})`)}).describe(`Map values using a dictionary`)])),Eg=F(()=>T({source:v().describe(`Source field name`),target:v().describe(`Target field name`),transform:Tg.optional().describe(`Transformation to apply`),defaultValue:S().optional().describe(`Default if source is null/undefined`)})),Dg=F(()=>Eg.extend({dataType:A([`string`,`number`,`boolean`,`date`,`datetime`,`json`,`array`]).optional().describe(`Target data type`),required:b().default(!1).describe(`Field is required`),syncMode:A([`read_only`,`write_only`,`bidirectional`]).default(`bidirectional`).describe(`Sync mode`)})),Og=F(()=>A([`full`,`incremental`,`upsert`,`append_only`]).describe(`Synchronization strategy`)),kg=F(()=>A([`source_wins`,`target_wins`,`latest_wins`,`manual`]).describe(`Conflict resolution strategy`)),Ag=F(()=>T({strategy:Og.optional().default(`incremental`),direction:A([`import`,`export`,`bidirectional`]).optional().default(`import`).describe(`Sync direction`),schedule:Iu.optional().describe("Cron expression for scheduled sync — cron`0 */15 * * *`"),realtimeSync:b().optional().default(!1).describe(`Enable real-time sync`),timestampField:v().optional().describe(`Field to track last modification time`),conflictResolution:kg.optional().default(`latest_wins`),batchSize:y().min(1).max(1e4).optional().default(1e3).describe(`Records per batch`),deleteMode:A([`hard_delete`,`soft_delete`,`ignore`]).optional().default(`soft_delete`).describe(`Delete handling mode`),filters:k(v(),S()).optional().describe(`Filter criteria for selective sync`)})),jg=F(()=>A([`record.created`,`record.updated`,`record.deleted`,`sync.started`,`sync.completed`,`sync.failed`,`auth.expired`,`rate_limit.exceeded`]).describe(`Webhook event type`)),Mg=F(()=>A([`hmac_sha256`,`hmac_sha512`,`none`]).describe(`Webhook signature algorithm`)),Ng=F(()=>cg.extend({events:w(jg).optional().describe(`Connector events to subscribe to`),signatureAlgorithm:Mg.optional().default(`hmac_sha256`)})),Pg=F(()=>A([`fixed_window`,`sliding_window`,`token_bucket`,`leaky_bucket`]).describe(`Rate limiting strategy`)),Fg=F(()=>T({strategy:Pg.optional().default(`token_bucket`),maxRequests:y().min(1).describe(`Maximum requests per window`),windowSeconds:y().min(1).describe(`Time window in seconds`),burstCapacity:y().min(1).optional().describe(`Burst capacity`),respectUpstreamLimits:b().optional().default(!0).describe(`Respect external rate limit headers`),rateLimitHeaders:T({remaining:v().optional().default(`X-RateLimit-Remaining`).describe(`Header for remaining requests`),limit:v().optional().default(`X-RateLimit-Limit`).describe(`Header for rate limit`),reset:v().optional().default(`X-RateLimit-Reset`).describe(`Header for reset time`)}).optional().describe(`Custom rate limit headers`)})),Ig=F(()=>A([`exponential_backoff`,`linear_backoff`,`fixed_delay`,`no_retry`]).describe(`Retry strategy`)),Lg=F(()=>T({strategy:Ig.optional().default(`exponential_backoff`),maxAttempts:y().min(0).max(10).optional().default(3).describe(`Maximum retry attempts`),initialDelayMs:y().min(100).optional().default(1e3).describe(`Initial retry delay in ms`),maxDelayMs:y().min(1e3).optional().default(6e4).describe(`Maximum retry delay in ms`),backoffMultiplier:y().min(1).optional().default(2).describe(`Exponential backoff multiplier`),retryableStatusCodes:w(y()).optional().default([408,429,500,502,503,504]).describe(`HTTP status codes to retry`),retryOnNetworkError:b().optional().default(!0).describe(`Retry on network errors`),jitter:b().optional().default(!0).describe(`Add jitter to retry delays`)})),Rg=F(()=>A([`validation`,`authorization`,`not_found`,`conflict`,`rate_limit`,`timeout`,`server_error`,`integration_error`]).describe(`Standard error category`)),zg=F(()=>T({sourceCode:E([v(),y()]).describe(`External system error code`),sourceMessage:v().optional().describe(`Pattern to match against error message`),targetCode:v().describe(`ObjectStack standard error code`),targetCategory:Rg.describe(`Error category`),severity:A([`low`,`medium`,`high`,`critical`]).describe(`Error severity level`),retryable:b().describe(`Whether the error is retryable`),userMessage:v().optional().describe(`Human-readable message to show users`)}).describe(`Error mapping rule`)),Bg=F(()=>T({rules:w(zg).describe(`Error mapping rules`),defaultCategory:Rg.optional().default(`integration_error`).describe(`Default category for unmapped errors`),unmappedBehavior:A([`passthrough`,`generic_error`,`throw`]).describe(`What to do with unmapped errors`),logUnmapped:b().optional().default(!0).describe(`Log unmapped errors`)}).describe(`Error mapping configuration`)),Vg=F(()=>T({enabled:b().describe(`Enable health checks`),intervalMs:y().optional().default(6e4).describe(`Health check interval in milliseconds`),timeoutMs:y().optional().default(5e3).describe(`Health check timeout in milliseconds`),endpoint:v().optional().describe(`Health check endpoint path`),method:A([`GET`,`HEAD`,`OPTIONS`]).optional().describe(`HTTP method for health check`),expectedStatus:y().optional().default(200).describe(`Expected HTTP status code`),unhealthyThreshold:y().optional().default(3).describe(`Consecutive failures before marking unhealthy`),healthyThreshold:y().optional().default(1).describe(`Consecutive successes before marking healthy`)}).describe(`Health check configuration`)),Hg=F(()=>T({enabled:b().describe(`Enable circuit breaker`),failureThreshold:y().optional().default(5).describe(`Failures before opening circuit`),resetTimeoutMs:y().optional().default(3e4).describe(`Time in open state before half-open`),halfOpenMaxRequests:y().optional().default(1).describe(`Requests allowed in half-open state`),monitoringWindow:y().optional().default(6e4).describe(`Rolling window for failure count in ms`),fallbackStrategy:A([`cache`,`default_value`,`error`,`queue`]).optional().describe(`Fallback strategy when circuit is open`)}).describe(`Circuit breaker configuration`)),Ug=F(()=>T({healthCheck:Vg.optional().describe(`Health check configuration`),circuitBreaker:Hg.optional().describe(`Circuit breaker configuration`)}).describe(`Connector health configuration`)),Wg=F(()=>A([`saas`,`database`,`file_storage`,`message_queue`,`api`,`custom`]).describe(`Connector type`)),Gg=F(()=>A([`active`,`inactive`,`error`,`configuring`]).describe(`Connector status`)),Kg=F(()=>T({key:v().describe(`Action key (machine name)`),label:v().describe(`Human readable label`),description:v().optional(),inputSchema:k(v(),S()).optional().describe(`Input parameters schema (JSON Schema)`),outputSchema:k(v(),S()).optional().describe(`Output schema (JSON Schema)`)})),qg=F(()=>T({key:v().describe(`Trigger key`),label:v().describe(`Trigger label`),description:v().optional(),type:A([`polling`,`webhook`]).describe(`Trigger type`),interval:y().optional().describe(`Polling interval in seconds`)})),Jg=F(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Unique connector identifier`),label:v().describe(`Display label`),type:Wg.describe(`Connector type`),description:v().optional().describe(`Connector description`),icon:v().optional().describe(`Icon identifier`),authentication:wg.describe(`Authentication configuration`),actions:w(Kg).optional(),triggers:w(qg).optional(),syncConfig:Ag.optional().describe(`Data sync configuration`),fieldMappings:w(Dg).optional().describe(`Field mapping rules`),webhooks:w(Ng).optional().describe(`Webhook configurations`),rateLimitConfig:Fg.optional().describe(`Rate limiting configuration`),retryConfig:Lg.optional().describe(`Retry configuration`),connectionTimeoutMs:y().min(1e3).max(3e5).optional().default(3e4).describe(`Connection timeout in ms`),requestTimeoutMs:y().min(1e3).max(3e5).optional().default(3e4).describe(`Request timeout in ms`),status:Gg.optional().default(`inactive`).describe(`Connector status`),enabled:b().optional().default(!0).describe(`Enable connector`),errorMapping:Bg.optional().describe(`Error mapping configuration`),health:Ug.optional().describe(`Health and resilience configuration`),metadata:k(v(),S()).optional().describe(`Custom connector metadata`)})),Yg=F(()=>T({namespace:v().optional().describe(`Match objects by namespace`),package:v().optional().describe(`Match objects by package ID`),objectPattern:v().optional().describe(`Match objects by name pattern (glob-style)`),default:b().optional().describe(`Default fallback rule`),datasource:v().describe(`Target datasource name`),priority:y().optional().describe(`Rule priority (lower = higher priority)`)}).describe(`Datasource routing rule`)),Xg=F(()=>T({manifest:hd.optional().describe(`Project Package Configuration`),datasources:w(Od).optional().describe(`External Data Connections`),datasourceMapping:w(Yg).optional().describe(`Centralized datasource routing rules for packages/namespaces/objects`),translations:w(Nd).optional().describe(`I18n Translation Bundles`),i18n:Id.optional().describe(`Internationalization configuration`),objects:w(Sp).optional().describe(`Business Objects definition (owned by this package)`),objectExtensions:w(Cp).optional().describe(`Extensions to objects owned by other packages`),apps:w(cd).optional().describe(`Applications`),portals:w(Np).optional().describe(`External-user UI portals (projections of apps/views/actions)`),views:w(tp).optional().describe(`List Views`),pages:w(qp).optional().describe(`Custom Pages`),dashboards:w(sm).optional().describe(`Dashboards`),reports:w(dm).optional().describe(`Analytics Reports`),datasets:w(Am).optional().describe(`Analytics semantic-layer datasets (ADR-0021)`),actions:w(df).optional().describe(`Global and Object Actions`),themes:w(Qm).optional().describe(`UI Themes`),flows:w(nh).optional().describe(`Screen Flows`),jobs:w(ch).optional().describe(`Background / Scheduled Jobs (run by IJobService on cron/interval/once schedules)`),emailTemplates:w(dg).optional().describe(`Email Templates resolved by IEmailService.sendTemplate({ template, locale })`),docs:w(pg).optional().describe(`Package documentation — flat Markdown items compiled from src/docs/*.md (ADR-0046)`),books:w(vg).optional().describe(`Documentation navigation spines — ordered groups with derived membership (ADR-0046 §6)`),roles:w(uh).optional().describe(`User Roles hierarchy`),permissions:w(_h).optional().describe(`Permission Sets and Profiles`),sharingRules:w(Ch).optional().describe(`Record Sharing Rules`),policies:w(Oh).optional().describe(`Security & Compliance Policies`),apis:w(Ah).optional().describe(`API Endpoints`),webhooks:w(cg).optional().describe(`Outbound Webhooks`),agents:w(Wh).optional().describe(`AI Agents and Assistants`),tools:w(Jh).optional().describe(`AI Tools (callable functions referenced by Skills/Agents)`),skills:w(Kh).optional().describe(`AI Skills (reusable capability bundles referenced by Agents)`),hooks:w(Xh).optional().describe(`Object Lifecycle Hooks`),functions:E([k(v(),P()),w(T({name:v(),handler:P(),packageId:v().optional()}))]).optional().describe(`Named handler functions referenced by hooks/actions`),mappings:w($h).optional().describe(`Data Import/Export Mappings`),analyticsCubes:w(og).optional().describe(`Analytics Semantic Layer Cubes`),connectors:w(Jg).optional().describe(`External System Connectors`),data:w(Au).optional().describe(`Seed Data / Fixtures for bootstrapping`),plugins:w(S()).optional().describe(`Plugins to load`),requires:w(v()).optional().describe(`Capability names this stack requires from the platform`),tiers:w(v()).optional().describe(`Plugin tier presets to enable; overrides --preset`),devPlugins:w(E([hd,v()])).optional().describe(`Plugins to load only in development (CLI dev command)`),runtimeModule:v().optional().describe("Path (relative to the artifact JSON) of the compiled runtime ESM bundle. Set by `objectstack build`; do not author by hand.")}));F(()=>Xg);var Zg=F(()=>A([`error`,`override`,`merge`]));F(()=>T({objectConflict:Zg.default(`error`),manifest:E([A([`first`,`last`]),y().int().min(0)]).default(`last`),namespace:v().optional()}));var Qg=F(()=>T({queryFilters:b().default(!0).describe(`Supports WHERE clause filtering`),queryAggregations:b().default(!0).describe(`Supports GROUP BY and aggregation functions`),querySorting:b().default(!0).describe(`Supports ORDER BY sorting`),queryPagination:b().default(!0).describe(`Supports LIMIT/OFFSET pagination`),queryWindowFunctions:b().default(!1).describe(`Supports window functions with OVER clause`),querySubqueries:b().default(!1).describe(`Supports subqueries`),queryDistinct:b().default(!0).describe(`Supports SELECT DISTINCT`),queryHaving:b().default(!1).describe(`Supports HAVING clause for aggregations`),queryJoins:b().default(!1).describe(`Supports SQL-style joins`),fullTextSearch:b().default(!1).describe(`Supports full-text search`),vectorSearch:b().default(!1).describe(`Supports vector embeddings and similarity search for AI/RAG`),geoSpatial:b().default(!1).describe(`Supports geospatial queries and location fields`),jsonFields:b().default(!0).describe(`Supports JSON field types`),arrayFields:b().default(!1).describe(`Supports array field types`),validationRules:b().default(!0).describe(`Supports validation rules`),workflows:b().default(!0).describe(`Supports workflow automation`),triggers:b().default(!0).describe(`Supports database triggers`),formulas:b().default(!0).describe(`Supports formula fields`),transactions:b().default(!0).describe(`Supports database transactions`),bulkOperations:b().default(!0).describe(`Supports bulk create/update/delete`),supportedDrivers:w(v()).optional().describe(`Available database drivers (e.g., postgresql, mongodb, excel)`)})),$g=F(()=>T({listView:b().default(!0).describe(`Supports list/grid views`),formView:b().default(!0).describe(`Supports form views`),kanbanView:b().default(!1).describe(`Supports kanban board views`),calendarView:b().default(!1).describe(`Supports calendar views`),ganttView:b().default(!1).describe(`Supports Gantt chart views`),dashboards:b().default(!0).describe(`Supports dashboard creation`),reports:b().default(!0).describe(`Supports report generation`),charts:b().default(!0).describe(`Supports chart widgets`),customPages:b().default(!0).describe(`Supports custom page creation`),customThemes:b().default(!1).describe(`Supports custom theme creation`),customComponents:b().default(!1).describe(`Supports custom UI components/widgets`),customActions:b().default(!0).describe(`Supports custom button actions`),screenFlows:b().default(!1).describe(`Supports interactive screen flows`),mobileOptimized:b().default(!1).describe(`UI optimized for mobile devices`),accessibility:b().default(!1).describe(`WCAG accessibility support`)})),e_=F(()=>T({version:v().describe(`ObjectOS Kernel Version`),environment:A([`development`,`test`,`staging`,`production`]),restApi:b().default(!0).describe(`REST API available`),graphqlApi:b().default(!1).describe(`GraphQL API available`),odataApi:b().default(!1).describe(`OData API available`),websockets:b().default(!1).describe(`WebSocket support for real-time updates`),serverSentEvents:b().default(!1).describe(`Server-Sent Events support`),eventBus:b().default(!1).describe(`Internal event bus for pub/sub`),webhooks:b().default(!0).describe(`Outbound webhook support`),apiContracts:b().default(!1).describe(`API contract definitions`),authentication:b().default(!0).describe(`Authentication system`),rbac:b().default(!0).describe(`Role-Based Access Control`),fieldLevelSecurity:b().default(!1).describe(`Field-level permissions`),rowLevelSecurity:b().default(!1).describe(`Row-level security/sharing rules`),multiTenant:b().default(!1).describe(`Multi-tenant architecture support`),backgroundJobs:b().default(!1).describe(`Background job scheduling`),auditLogging:b().default(!1).describe(`Audit trail logging`),fileStorage:b().default(!0).describe(`File upload and storage`),i18n:b().default(!0).describe(`Internationalization support`),pluginSystem:b().default(!1).describe(`Plugin/extension system`),cluster:Sd.optional().describe(`Cluster transport & semantics configuration.`),features:w(Mh).optional().describe(`Active Feature Flags`),apis:w(Ah).optional().describe(`Available System & Business APIs`),network:T({graphql:b().default(!1),search:b().default(!1),websockets:b().default(!1),files:b().default(!0),analytics:b().default(!1).describe(`Is the Analytics/BI engine enabled?`),ai:b().default(!1).describe(`Is the AI engine enabled?`),workflow:b().default(!1).describe(`Is the Workflow engine enabled?`),notifications:b().default(!1).describe(`Is the Notification service enabled?`),i18n:b().default(!1).describe(`Is the i18n service enabled?`)}).optional().describe(`Network Capabilities (GraphQL, WS, etc.)`),systemObjects:w(v()).optional().describe(`List of globally available System Objects`),limits:T({maxObjects:y().optional(),maxFieldsPerObject:y().optional(),maxRecordsPerQuery:y().optional(),apiRateLimit:y().optional(),fileUploadSizeLimit:y().optional().describe(`Max file size in bytes`)}).optional()}));F(()=>T({data:Qg.describe(`Data Layer capabilities`),ui:$g.describe(`UI Layer capabilities`),system:e_.describe(`System/Runtime Layer capabilities`)}));var t_=`platform_admin`;F(()=>T({id:v().describe(`User ID`),name:v().optional().describe(`Display name`),email:v().optional().describe(`Email address`),roles:w(v()).default([]).describe(`Canonical role names assigned to the user (scope-resolved)`),isPlatformAdmin:b().optional().describe(`DERIVED alias of 'platform_admin' in roles. Deprecated.`),organizationId:v().nullable().optional().describe(`Active organization ID (null = platform/unscoped)`)}));function n_(e){let t=Array.from(new Set((e.roles??[]).map(e=>String(e).trim()).filter(Boolean)));return{id:e.id,...e.name==null?{}:{name:e.name},...e.email==null?{}:{email:e.email},roles:t,isPlatformAdmin:t.includes(t_),...e.organizationId===void 0?{}:{organizationId:e.organizationId}}}function r_(e,t){let n=new Intl.DateTimeFormat(`en-US`,{timeZone:t,year:`numeric`,month:`2-digit`,day:`2-digit`}).formatToParts(e),r=e=>Number(n.find(t=>t.type===e)?.value);return{y:r(`year`),m:r(`month`),day:r(`day`)}}function i_(e,t){if(t&&t!==`UTC`)try{let{y:n,m:r,day:i}=r_(e,t);return new Date(Date.UTC(n,r-1,i))}catch{}return a_(e)}function a_(e){let t=new Date(e.getTime());return t.setUTCHours(0,0,0,0),t}function o_(e){return e instanceof Date?e:typeof e==`number`||typeof e==`bigint`?new Date(Number(e)):new Date(String(e))}var s_=864e5;function c_(e,t){let n=new Date(e.getTime());return n.setUTCDate(n.getUTCDate()+t),n}function l_(e,t){let n=new Date(e.getTime()),r=n.getUTCDate();n.setUTCDate(1),n.setUTCMonth(n.getUTCMonth()+t);let i=new Date(Date.UTC(n.getUTCFullYear(),n.getUTCMonth()+1,0)).getUTCDate();return n.setUTCDate(Math.min(r,i)),n}function u_(e,t,n=`UTC`){return e.registerFunction(`now(): google.protobuf.Timestamp`,()=>t()).registerFunction(`today(): google.protobuf.Timestamp`,()=>i_(t(),n)).registerFunction(`daysFromNow(int): google.protobuf.Timestamp`,e=>c_(i_(t(),n),Number(e))).registerFunction(`daysAgo(int): google.protobuf.Timestamp`,e=>c_(i_(t(),n),-Number(e))).registerFunction(`isBlank(dyn): bool`,e=>e==null?!0:typeof e==`string`||Array.isArray(e)?e.length===0:!1).registerFunction(`coalesce(dyn, dyn): dyn`,(e,t)=>e??t).registerFunction(`trim(dyn): string`,e=>e==null?``:String(e).trim()).registerFunction(`joinNonEmpty(list, string): string`,(e,t)=>{let n=Array.isArray(e)?e:[],r=typeof t==`string`?t:` `,i=[];for(let e of n){if(e==null)continue;let t=String(e).trim();t.length>0&&i.push(t)}return i.join(r)}).registerFunction(`daysBetween(dyn, dyn): int`,(e,t)=>BigInt(Math.round((o_(t).getTime()-o_(e).getTime())/s_))).registerFunction(`addDays(dyn, dyn): google.protobuf.Timestamp`,(e,t)=>c_(o_(e),Math.trunc(Number(t)))).registerFunction(`addMonths(dyn, dyn): google.protobuf.Timestamp`,(e,t)=>l_(o_(e),Math.trunc(Number(t)))).registerFunction(`date(dyn): google.protobuf.Timestamp`,e=>o_(e)).registerFunction(`datetime(dyn): google.protobuf.Timestamp`,e=>o_(e)).registerFunction(`abs(dyn): double`,e=>Math.abs(Number(e))).registerFunction(`round(dyn): int`,e=>BigInt(Math.round(Number(e)))).registerFunction(`min(dyn, dyn): dyn`,(e,t)=>Number(e)<=Number(t)?e:t).registerFunction(`max(dyn, dyn): dyn`,(e,t)=>Number(e)>=Number(t)?e:t).registerFunction(`upper(dyn): string`,e=>String(e??``).toUpperCase()).registerFunction(`lower(dyn): string`,e=>String(e??``).toLowerCase()).registerFunction(`contains(dyn, dyn): bool`,(e,t)=>String(e??``).includes(String(t??``))).registerFunction(`startsWith(dyn, dyn): bool`,(e,t)=>String(e??``).startsWith(String(t??``))).registerFunction(`endsWith(dyn, dyn): bool`,(e,t)=>String(e??``).endsWith(String(t??``))).registerFunction(`matches(dyn, dyn): bool`,(e,t)=>new RegExp(String(t??``)).test(String(e??``))).registerFunction(`len(dyn): int`,e=>BigInt(d_(e))).registerFunction(`isEmpty(dyn): bool`,e=>e==null||d_(e)===0)}function d_(e){return e==null?0:typeof e==`string`||Array.isArray(e)?e.length:typeof e==`object`?Object.keys(e).length:0}function f_(e){let t={"+":(e,t)=>e+t,"-":(e,t)=>e-t,"*":(e,t)=>e*t,"/":(e,t)=>e/t,"%":(e,t)=>e%t};for(let[n,r]of Object.entries(t)){let t=(e,t)=>r(Number(e),Number(t));e.registerOperator(`double ${n} int`,t),e.registerOperator(`int ${n} double`,t)}return e}function p_(e){let t=typeof e.role==`string`&&e.role?[e.role]:[],n=Array.isArray(e.roles)?e.roles:[],r=n_({id:e.id,name:typeof e.name==`string`?e.name:void 0,email:typeof e.email==`string`?e.email:void 0,roles:[...n,...t],organizationId:typeof e.organizationId==`string`||e.organizationId===null?e.organizationId:void 0});return typeof e.role==`string`&&e.role&&(r.role=e.role),r}function m_(e){let t={};e.record!==void 0&&(t.record=e.record),e.previous!==void 0&&(t.previous=e.previous),e.input!==void 0&&(t.input=e.input);let n={};if(e.user!==void 0){let r=p_(e.user);t.current_user=r,t.user=r,t.ctx={...typeof t.ctx==`object`&&t.ctx!==null?t.ctx:{},user:r},n.user=r}return e.org!==void 0&&(n.org=e.org),e.env!==void 0&&(n.env=e.env),Object.keys(n).length>0&&(t.os=n),e.extra!==void 0&&Object.assign(t,e.extra),t}var h_={maxAstNodes:256,maxDepth:32,maxListElements:64,maxMapEntries:64,maxCallArguments:16};function g_(e,t=`UTC`){return f_(u_(new Tn({unlistedVariablesAreDyn:!0,enableOptionalTypes:!0,limits:h_}),e,t))}function __(e){if(typeof e==`bigint`)return e>=BigInt(-(2**53-1))&&e<=BigInt(2**53-1)?Number(e):e.toString();if(Array.isArray(e))return e.map(__);if(e&&typeof e==`object`&&!(e instanceof Date)){let t={};for(let[n,r]of Object.entries(e))t[n]=__(r);return t}return e}var v_=/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/,y_=/^\d{4}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2}(?::\d{2})?(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})?)?$/;function b_(e){let t=e instanceof Error?e.message:String(e);return/no such overload/i.test(t)}function x_(e){if(typeof e==`string`){let t=e.trim();if(t.length>0){if(v_.test(t)){let e=Number(t);if(Number.isFinite(e))return e}else if(y_.test(t)){let e=Date.parse(t);if(!Number.isNaN(e))return new Date(e)}}return e}if(Array.isArray(e))return e.map(x_);if(e&&typeof e==`object`&&!(e instanceof Date)){let t={};for(let[n,r]of Object.entries(e))t[n]=x_(r);return t}return e}function S_(e){let t=e instanceof Error?e.message:String(e),n=`runtime`;return/Exceeded max/i.test(t)?n=`bounds`:/parse|unexpected|syntax/i.test(t)?n=`parse`:/type|unknown variable|undeclared/i.test(t)&&(n=`type`),{ok:!1,error:{kind:n,message:t}}}var C_={dialect:`cel`,compile(e){try{let t=g_(()=>new Date(0)).parse(e),n=t.check?.();return n&&n.valid===!1?{ok:!1,error:{kind:`type`,message:n.error?.message??`expression failed type checking`}}:{ok:!0,value:t.ast}}catch(e){return S_(e)}},evaluate(e,t){if(e.dialect!==`cel`)return{ok:!1,error:{kind:`dialect`,message:`celEngine cannot evaluate dialect '${e.dialect}'`}};let n=e.source;if(typeof n!=`string`||n.length===0)return{ok:!1,error:{kind:`parse`,message:"AST-only evaluation not yet supported; persist `source`"}};let r=()=>t.now??new Date;try{let e=g_(r,t.timezone??`UTC`),i=m_(t);try{return{ok:!0,value:__(e.evaluate(n,i))}}catch(t){if(!b_(t))throw t;let r=x_(i);try{return{ok:!0,value:__(e.evaluate(n,r))}}catch{throw t}}}catch(e){return S_(e)}}},w_=new Set([`@yearly`,`@annually`,`@monthly`,`@weekly`,`@daily`,`@hourly`,`@reboot`]);function T_(e){let t=e.trim();if(t.length===0)return{ok:!1,error:{kind:`parse`,message:`cron source is empty`}};if(t.startsWith(`@`))return w_.has(t)?{ok:!0,value:t}:{ok:!1,error:{kind:`parse`,message:`unknown cron alias '${t}'`}};let n=t.split(/\s+/);if(n.length!==5&&n.length!==6)return{ok:!1,error:{kind:`parse`,message:`cron requires 5 or 6 space-separated fields, got ${n.length}`}};let r=/^[\d*/,\-?LWA-Z#]+$/i;for(let e=0;e<n.length;e++)if(!r.test(n[e]))return{ok:!1,error:{kind:`parse`,message:`cron field ${e+1} contains invalid characters: '${n[e]}'`}};return{ok:!0,value:t}}var E_={dialect:`cron`,compile(e){return T_(e)},evaluate(e,t){if(e.dialect!==`cron`)return{ok:!1,error:{kind:`dialect`,message:`cronEngine cannot evaluate dialect '${e.dialect}'`}};if(typeof e.source!=`string`)return{ok:!1,error:{kind:`parse`,message:`cron Expression.source required`}};let n=T_(e.source);return n.ok?{ok:!0,value:n.value}:n}},D_=/\{\{([^}]*)\}\}/g;function O_(e){if(typeof e==`number`)return e;if(typeof e==`bigint`||typeof e==`string`&&e.trim()!==``&&!Number.isNaN(Number(e)))return Number(e)}function k_(e){if(e instanceof Date)return e;if(typeof e==`number`)return new Date(e);if(typeof e==`string`){let t=new Date(e);if(!Number.isNaN(t.getTime()))return t}}var A_={upper:e=>M_(e).toUpperCase(),lower:e=>M_(e).toLowerCase(),trim:e=>M_(e).trim(),number:(e,t,n)=>{let r=O_(e);if(r===void 0)return M_(e);let i=t===void 0?void 0:Number(t);return new Intl.NumberFormat(n,i!==void 0&&!Number.isNaN(i)?{minimumFractionDigits:i,maximumFractionDigits:i}:{}).format(r)},currency:(e,t,n)=>{let r=O_(e);if(r===void 0)return M_(e);let i=t&&t.trim()||`USD`;try{return new Intl.NumberFormat(n,{style:`currency`,currency:i}).format(r)}catch{return new Intl.NumberFormat(n,{style:`currency`,currency:`USD`}).format(r)}},percent:(e,t,n)=>{let r=O_(e);if(r===void 0)return M_(e);let i=t===void 0?0:Number(t);return new Intl.NumberFormat(n,{style:`percent`,minimumFractionDigits:Number.isNaN(i)?0:i,maximumFractionDigits:Number.isNaN(i)?0:i}).format(r)},date:(e,t,n)=>{let r=k_(e);if(!r)return M_(e);if(t===`iso`)return r.toISOString().slice(0,10);let i=t===`long`?`long`:t===`medium`?`medium`:`short`;return new Intl.DateTimeFormat(n,{dateStyle:i}).format(r)},datetime:(e,t,n,r)=>{let i=k_(e);if(!i)return M_(e);if(t===`iso`)return i.toISOString();let a=t===`long`?`long`:t===`medium`?`medium`:`short`;return new Intl.DateTimeFormat(n,{dateStyle:a,timeStyle:a,...r?{timeZone:r}:{}}).format(i)},truncate:(e,t)=>{let n=M_(e),r=t===void 0?80:Number(t);return Number.isNaN(r)||n.length<=r?n:n.slice(0,Math.max(0,r-1))+`…`},default:(e,t)=>{let n=M_(e);return n===``?t??``:n},json:e=>{try{return JSON.stringify(e)}catch{return String(e)}}},j_=Object.keys(A_);function M_(e){if(e==null)return``;if(e instanceof Date)return e.toISOString();if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`)return String(e);if(typeof e==`bigint`)return e.toString();try{return JSON.stringify(e)}catch{return String(e)}}function N_(e,t){let n=t.replace(/\[(\w+)\]/g,`.$1`).split(`.`).filter(Boolean),r=e;for(let e of n){if(typeof r!=`object`||!r)return;r=r[e]}return r}var P_=/^[\w.[\]]+$/;function F_(e){let t=e.indexOf(`|`);if(t===-1){let t=e.trim();return P_.test(t)?{path:t}:null}let n=e.slice(0,t).trim();if(!P_.test(n))return null;let r=e.slice(t+1).trim(),i=r.indexOf(`:`),a=r,o;return i!==-1&&(a=r.slice(0,i).trim(),o=r.slice(i+1).trim().replace(/^['"]|['"]$/g,``)),A_[a]?{path:n,filter:{name:a,arg:o}}:null}function I_(e){if((e.match(/\{\{/g)??[]).length!==(e.match(/\}\}/g)??[]).length)return{ok:!1,error:{kind:`parse`,message:`template has unbalanced {{ }} delimiters`}};let t=[],n;for(D_.lastIndex=0;(n=D_.exec(e))!==null;){let e=F_(n[1]);if(!e)return{ok:!1,error:{kind:`parse`,message:`invalid template hole \`{{ ${n[1]} }}\` \u2014 holes are a field path with an optional formatter (\`{{ record.amount | currency }}\`), not arbitrary logic. Move logic into a CEL field. Known formatters: ${j_.join(`, `)}.`}};t.push(e)}return{ok:!0,value:t}}var L_={dialect:`template`,compile(e){return I_(e)},evaluate(e,t){if(e.dialect!==`template`)return{ok:!1,error:{kind:`dialect`,message:`templateEngine cannot evaluate dialect '${e.dialect}'`}};if(typeof e.source!=`string`)return{ok:!1,error:{kind:`parse`,message:`template Expression.source required`}};let n=I_(e.source);if(!n.ok)return n;let r=m_(t),i=t.extra&&typeof t.extra.locale==`string`&&t.extra.locale||typeof t.locale==`string`&&t.locale||`en-US`,a=typeof t.timezone==`string`?t.timezone:void 0;return{ok:!0,value:e.source.replace(D_,(e,t)=>{let n=F_(String(t));if(!n)return e;let o=N_(r,n.path);return n.filter?A_[n.filter.name](o,n.filter.arg,i,a):M_(o)})}}},R_=new Map;function z_(e){R_.set(e.dialect,e)}function B_(e){return R_.get(e)}function V_(e){return R_.has(e)&&!R_.get(e).dialect.startsWith(`stub:`)}function H_(e,t){return{dialect:e,compile:()=>({ok:!1,error:{kind:`dialect`,message:t}}),evaluate:()=>({ok:!1,error:{kind:`dialect`,message:t}})}}z_(C_),z_(E_),z_(L_),z_(H_(`js`,`dialect 'js' not registered. Install @objectstack/plugin-js-vm`));var U_={register:z_,getEngine:B_,hasDialect:V_,compile(e){let t=R_.get(e.dialect);return t?typeof e.source==`string`?t.compile(e.source):{ok:!1,error:{kind:`parse`,message:`Expression.source required for compile()`}}:{ok:!1,error:{kind:`dialect`,message:`No engine registered for dialect '${e.dialect}'`}}},evaluate(e,t){let n=R_.get(e.dialect);return n?n.evaluate(e,t):{ok:!1,error:{kind:`dialect`,message:`No engine registered for dialect '${e.dialect}'`}}}},W_=t({ACTION_LOCATIONS:()=>fb,AIChatWindowProps:()=>Yb,ActionAiSchema:()=>hb,ActionLocationSchema:()=>pb,ActionNavItemSchema:()=>wv,ActionParamSchema:()=>lb,ActionSchema:()=>gb,ActionType:()=>ub,AddRecordConfigSchema:()=>oy,AnimationSchema:()=>xx,AnimationTriggerSchema:()=>Ix,AppBrandingSchema:()=>Ov,AppContextSelectorSchema:()=>Av,AppSchema:()=>jv,AppearanceConfigSchema:()=>ny,AriaPropsSchema:()=>B,BorderRadiusSchema:()=>vx,BreakpointColumnMapSchema:()=>ev,BreakpointName:()=>$_,BreakpointOrderMapSchema:()=>tv,BreakpointsSchema:()=>bx,CalendarConfigSchema:()=>ly,ChartAnnotationSchema:()=>X_,ChartAxisSchema:()=>J_,ChartConfigSchema:()=>Q_,ChartInteractionSchema:()=>Z_,ChartSeriesSchema:()=>Y_,ChartTypeSchema:()=>q_,ColorPaletteSchema:()=>hx,ColumnSummarySchema:()=>Uv,ComponentAnimationSchema:()=>Lx,ComponentNavItemSchema:()=>Tv,ConflictResolutionSchema:()=>Ox,DashboardHeaderActionSchema:()=>Ay,DashboardHeaderSchema:()=>jy,DashboardNavItemSchema:()=>bv,DashboardSchema:()=>Fy,DashboardWidgetSchema:()=>My,DatasetDimensionSchema:()=>tb,DatasetMeasureSchema:()=>rb,DateFormatSchema:()=>K_,DensityModeSchema:()=>wx,DerivedMeasureOp:()=>nb,DragConstraintSchema:()=>Gx,DragHandleSchema:()=>Ux,DragItemSchema:()=>qx,DropEffectSchema:()=>Wx,DropZoneSchema:()=>Kx,EasingFunctionSchema:()=>Px,ElementButtonPropsSchema:()=>ex,ElementDataSourceSchema:()=>xb,ElementFilterPropsSchema:()=>tx,ElementFormPropsSchema:()=>nx,ElementImagePropsSchema:()=>Qb,ElementMetadataViewerPropsSchema:()=>$b,ElementNumberPropsSchema:()=>Zb,ElementRecordPickerPropsSchema:()=>rx,ElementTextInputPropsSchema:()=>ix,ElementTextPropsSchema:()=>Xb,EmbedConfigSchema:()=>fv,EvictionPolicySchema:()=>jx,FocusManagementSchema:()=>mx,FocusTrapConfigSchema:()=>fx,FormFieldSchema:()=>gy,FormSectionSchema:()=>_y,FormViewSchema:()=>vy,GalleryConfigSchema:()=>Xv,GanttConfigSchema:()=>dy,GanttQuickFilterSchema:()=>uy,GestureConfigSchema:()=>dx,GestureTypeSchema:()=>ox,GlobalFilterOptionsFromSchema:()=>Ny,GlobalFilterSchema:()=>Py,GroupNavItemSchema:()=>Ev,GroupingConfigSchema:()=>Yv,GroupingFieldSchema:()=>Jv,HttpMethodSchema:()=>zv,HttpRequestSchema:()=>Bv,I18nLabelSchema:()=>z,InterfacePageConfigSchema:()=>Tb,JoinedReportBlockSchema:()=>Ry,KanbanConfigSchema:()=>sy,KeyboardShortcutSchema:()=>px,ListChartConfigSchema:()=>cy,ListColumnSchema:()=>Wv,ListViewSchema:()=>hy,LongPressGestureConfigSchema:()=>ux,NavigationAreaSchema:()=>kv,NavigationConfigSchema:()=>my,NavigationItemSchema:()=>Dv,NavigationModeSchema:()=>py,NotificationActionSchema:()=>Hx,NotificationPositionSchema:()=>Vx,NotificationSeveritySchema:()=>Bx,NotificationTypeSchema:()=>zx,NumberFormatSchema:()=>G_,ObjectNavItemSchema:()=>yv,OfflineCacheConfigSchema:()=>Mx,OfflineStrategySchema:()=>Dx,PageAccordionProps:()=>Jb,PageCardProps:()=>Bb,PageComponentSchema:()=>Sb,PageComponentType:()=>bb,PageHeaderProps:()=>Rb,PageNavItemSchema:()=>xv,PageRegionSchema:()=>yb,PageSchema:()=>Eb,PageTabsProps:()=>zb,PageTransitionSchema:()=>Rx,PageTypeSchema:()=>wb,PageVariableSchema:()=>Cb,PaginationConfigSchema:()=>Kv,PerformanceConfigSchema:()=>av,PersistStorageSchema:()=>Ax,PinchGestureConfigSchema:()=>lx,PortalActionNavItemSchema:()=>Zx,PortalAnonymousEntrySchema:()=>rS,PortalAnonymousRouteSchema:()=>nS,PortalAuthModeSchema:()=>aS,PortalDashboardNavItemSchema:()=>Qx,PortalLayoutSchema:()=>oS,PortalNavItemSchema:()=>eS,PortalRateLimitSchema:()=>tS,PortalSeoSchema:()=>iS,PortalThemeSchema:()=>Jx,PortalUrlNavItemSchema:()=>$x,PortalViewNavItemSchema:()=>Xx,RecordActivityProps:()=>Gb,RecordChatterProps:()=>Kb,RecordDetailsProps:()=>Vb,RecordHighlightsField:()=>Ub,RecordHighlightsProps:()=>Wb,RecordPathProps:()=>qb,RecordRelatedListProps:()=>Hb,ReportChartSchema:()=>Ly,ReportNavItemSchema:()=>Cv,ReportSchema:()=>zy,ReportType:()=>Iy,ResponsiveConfigSchema:()=>nv,ResponsiveStylesSchema:()=>iv,RowColorConfigSchema:()=>$v,RowHeightSchema:()=>qv,SelectionConfigSchema:()=>Gv,ShadowSchema:()=>yx,SharingConfigSchema:()=>dv,SpacingSchema:()=>_x,StyleMapSchema:()=>rv,SwipeDirectionSchema:()=>sx,SwipeGestureConfigSchema:()=>cx,SyncConfigSchema:()=>kx,ThemeModeSchema:()=>Cx,ThemeSchema:()=>Ex,TimelineConfigSchema:()=>Zv,TouchTargetConfigSchema:()=>ax,TransitionConfigSchema:()=>Fx,TransitionPresetSchema:()=>Nx,TreeConfigSchema:()=>fy,TypographySchema:()=>gx,UrlNavItemSchema:()=>Sv,UserActionsConfigSchema:()=>ty,UserFilterFieldSchema:()=>iy,UserFiltersSchema:()=>ay,ViewDataSchema:()=>Vv,ViewFilterRuleSchema:()=>Hv,ViewItemNameSchema:()=>by,ViewSchema:()=>yy,ViewScopeSchema:()=>xy,ViewSharingSchema:()=>Qv,ViewTabSchema:()=>ry,VisualizationTypeSchema:()=>ey,WcagContrastLevelSchema:()=>Tx,WidgetActionTypeSchema:()=>ky,WidgetColorVariantSchema:()=>Oy,WidgetEventSchema:()=>Ob,WidgetLifecycleSchema:()=>Db,WidgetPropertySchema:()=>kb,WidgetSourceSchema:()=>Ab,ZIndexSchema:()=>Sx,dashboardForm:()=>ob,defineForm:()=>Cy,reportForm:()=>ib,viewForm:()=>ab});function R(e){if(typeof process<`u`&&{}.OS_EAGER_SCHEMAS===`1`)return e();let t,n=()=>(t===void 0&&(t=e()),t);return new Proxy(function(){},{get(e,t){let r=n(),i=r[t];return typeof i==`function`?i.bind(r):i},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())}})}R(()=>T({key:v().describe(`Translation key (e.g., "views.task_list.label")`),defaultValue:v().optional().describe(`Fallback value when translation key is not found`),params:k(v(),E([v(),y(),b()])).optional().describe(`Interpolation parameters (e.g., { count: 5 })`)}));var z=R(()=>v().describe(`Display label (plain string; i18n keys are auto-generated by the framework)`)),B=R(()=>T({ariaLabel:z.optional().describe(`Accessible label for screen readers (WAI-ARIA aria-label)`),ariaDescribedBy:v().optional().describe(`ID of element providing additional description (WAI-ARIA aria-describedby)`),role:v().optional().describe(`WAI-ARIA role attribute (e.g., "dialog", "navigation", "alert")`)}).describe(`ARIA accessibility attributes`));R(()=>T({key:v().describe(`Translation key`),zero:v().optional().describe(`Zero form (e.g., "No items")`),one:v().optional().describe(`Singular form (e.g., "{count} item")`),two:v().optional().describe(`Dual form (e.g., "{count} items" for exactly 2)`),few:v().optional().describe(`Few form (e.g., for 2-4 in some languages)`),many:v().optional().describe(`Many form (e.g., for 5+ in some languages)`),other:v().describe(`Default plural form (e.g., "{count} items")`)}).describe(`ICU plural rules for a translation key`));var G_=R(()=>T({style:A([`decimal`,`currency`,`percent`,`unit`]).default(`decimal`).describe(`Number formatting style`),currency:v().optional().describe(`ISO 4217 currency code (e.g., "USD", "EUR")`),unit:v().optional().describe(`Unit for unit formatting (e.g., "kilometer", "liter")`),minimumFractionDigits:y().optional().describe(`Minimum number of fraction digits`),maximumFractionDigits:y().optional().describe(`Maximum number of fraction digits`),useGrouping:b().optional().describe(`Whether to use grouping separators (e.g., 1,000)`)}).describe(`Number formatting rules`)),K_=R(()=>T({dateStyle:A([`full`,`long`,`medium`,`short`]).optional().describe(`Date display style`),timeStyle:A([`full`,`long`,`medium`,`short`]).optional().describe(`Time display style`),timeZone:v().optional().describe(`IANA time zone (e.g., "America/New_York")`),hour12:b().optional().describe(`Use 12-hour format`)}).describe(`Date/time formatting rules`));R(()=>T({code:v().describe(`BCP 47 language code (e.g., "en-US", "zh-CN")`),fallbackChain:w(v()).optional().describe(`Fallback language codes in priority order (e.g., ["zh-TW", "en"])`),direction:A([`ltr`,`rtl`]).default(`ltr`).describe(`Text direction: left-to-right or right-to-left`),numberFormat:G_.optional().describe(`Default number formatting rules`),dateFormat:K_.optional().describe(`Default date/time formatting rules`)}).describe(`Locale configuration`));var q_=R(()=>A([`bar`,`horizontal-bar`,`column`,`line`,`area`,`pie`,`donut`,`funnel`,`scatter`,`treemap`,`sankey`,`gauge`,`solid-gauge`,`metric`,`kpi`,`bullet`,`radar`,`table`,`pivot`])),J_=R(()=>T({field:v().describe(`Data field key`),title:z.optional().describe(`Axis display title`),format:v().optional().describe(`Value format string (e.g., "$0,0.00")`),min:y().optional().describe(`Minimum value`),max:y().optional().describe(`Maximum value`),stepSize:y().optional().describe(`Step size for ticks`),showGridLines:b().default(!0),position:A([`left`,`right`,`top`,`bottom`]).optional().describe(`Axis position`),logarithmic:b().default(!1)})),Y_=R(()=>T({name:v().describe(`Field name or series identifier`),label:z.optional().describe(`Series display label`),type:q_.optional().describe(`Override chart type for this series`),color:v().optional().describe(`Series color (hex/rgb/token)`),stack:v().optional().describe(`Stack identifier to group series`),yAxis:A([`left`,`right`]).default(`left`).describe(`Bind to specific Y-Axis`),variant:A([`primary`,`comparison`]).default(`primary`).optional().describe(`Series visual role`),dashArray:v().optional().describe(`SVG stroke-dasharray override`),opacity:y().min(0).max(1).optional().describe(`Series opacity override`)})),X_=R(()=>T({type:A([`line`,`region`]).default(`line`),axis:A([`x`,`y`]).default(`y`),value:E([y(),v()]).describe(`Start value`),endValue:E([y(),v()]).optional().describe(`End value for regions`),color:v().optional(),label:z.optional(),style:A([`solid`,`dashed`,`dotted`]).default(`dashed`)})),Z_=R(()=>T({tooltips:b().default(!0),zoom:b().default(!1),brush:b().default(!1),clickAction:v().optional().describe(`Action ID to trigger on click`)})),Q_=R(()=>T({type:q_,title:z.optional().describe(`Chart title`),subtitle:z.optional().describe(`Chart subtitle`),description:z.optional().describe(`Accessibility description`),xAxis:J_.optional().describe(`X-Axis configuration`),yAxis:w(J_).optional().describe(`Y-Axis configuration (support dual axis)`),series:w(Y_).optional().describe(`Defined series configuration`),colors:E([w(v()),k(v(),v())]).optional().describe(`Color palette (string[]) or value→color map ({ value: color })`),height:y().optional().describe(`Fixed height in pixels`),showLegend:b().default(!0).describe(`Display legend`),showDataLabels:b().default(!1).describe(`Display data labels`),annotations:w(X_).optional(),interaction:Z_.optional(),aria:B.optional().describe(`ARIA accessibility attributes`)})),$_=A([`xs`,`sm`,`md`,`lg`,`xl`,`2xl`]),ev=R(()=>T({xs:y().min(1).max(12).optional(),sm:y().min(1).max(12).optional(),md:y().min(1).max(12).optional(),lg:y().min(1).max(12).optional(),xl:y().min(1).max(12).optional(),"2xl":y().min(1).max(12).optional()}).describe(`Grid columns per breakpoint (1-12)`)),tv=R(()=>T({xs:y().optional(),sm:y().optional(),md:y().optional(),lg:y().optional(),xl:y().optional(),"2xl":y().optional()}).describe(`Display order per breakpoint`)),nv=R(()=>T({breakpoint:$_.optional().describe(`Minimum breakpoint for visibility`),hiddenOn:w($_).optional().describe(`Hide on these breakpoints`),columns:ev.optional().describe(`Grid columns per breakpoint`),order:tv.optional().describe(`Display order per breakpoint`)}).describe(`Responsive layout configuration`)),rv=R(()=>k(v(),E([v(),y()])).describe(`CSS property → value map (camelCase keys; design tokens encouraged)`)),iv=R(()=>T({large:rv.optional().describe(`Unconditional base (desktop-first)`),medium:rv.optional().describe(`Applied at ≤ medium breakpoint`),small:rv.optional().describe(`Applied at ≤ small breakpoint`),xsmall:rv.optional().describe(`Applied at ≤ xsmall breakpoint`)}).describe(`Per-breakpoint scoped style maps (ADR-0065)`)),av=R(()=>T({lazyLoad:b().optional().describe(`Enable lazy loading (defer rendering until visible)`),virtualScroll:T({enabled:b().default(!1).describe(`Enable virtual scrolling`),itemHeight:y().optional().describe(`Fixed item height in pixels (for estimation)`),overscan:y().optional().describe(`Number of extra items to render outside viewport`)}).optional().describe(`Virtual scrolling configuration`),cacheStrategy:A([`none`,`cache-first`,`network-first`,`stale-while-revalidate`]).optional().describe(`Client-side data caching strategy`),prefetch:b().optional().describe(`Prefetch data before component is visible`),pageSize:y().optional().describe(`Number of items per page for pagination`),debounceMs:y().optional().describe(`Debounce interval for user interactions in milliseconds`)}).describe(`Performance optimization configuration`)),ov=R(()=>v().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)`)),V=R(()=>v().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)`));R(()=>v().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 sv=A([`cel`,`js`,`cron`,`template`]),cv=T({rationale:v().optional(),generatedBy:v().optional()}),lv=T({dialect:sv,source:v().min(1).optional(),ast:S().optional(),meta:cv.optional()}).refine(e=>e.source!==void 0||e.ast!==void 0,{message:"Expression requires at least one of `source` or `ast`"}),uv=E([v().min(1).transform(e=>({dialect:`cel`,source:e})),lv]);E([v().min(1).transform(e=>({dialect:`cron`,source:e})),lv]),E([v().min(1).transform(e=>({dialect:`template`,source:e})),lv]);var dv=R(()=>T({enabled:b().default(!1).describe(`Enable public sharing`),publicLink:v().optional().describe(`Generated public share URL`),password:v().optional().describe(`Password required to access shared link`),allowedDomains:w(v()).optional().describe(`Restrict access to specific email domains (e.g. ["example.com"])`),expiresAt:v().optional().describe(`Expiration date/time in ISO 8601 format`),allowAnonymous:b().optional().default(!1).describe(`Allow access without authentication`)})),fv=R(()=>T({enabled:b().default(!1).describe(`Enable iframe embedding`),allowedOrigins:w(v()).optional().describe(`Allowed iframe parent origins (e.g. ["https://example.com"])`),width:v().optional().default(`100%`).describe(`Embed width (CSS value)`),height:v().optional().default(`600px`).describe(`Embed height (CSS value)`),showHeader:b().optional().default(!0).describe(`Show interface header in embed`),showNavigation:b().optional().default(!1).describe(`Show navigation in embed`),responsive:b().optional().default(!0).describe(`Enable responsive resizing`)})),pv=A([`none`,`no-overlay`,`no-delete`,`full`]),mv=A([`artifact`,`package`,`env-forced`]),hv=A([`package`,`org`,`env-forced`]),gv={_lock:pv.optional().describe(`Item-level lock — controls overlay & delete (ADR-0010).`),_lockReason:v().max(500).optional().describe(`Human-readable reason shown when a write is refused by _lock.`),_lockSource:mv.optional().describe(`Layer that set _lock (artifact | package | env-forced).`),_provenance:hv.optional().describe(`Origin of the item (package | org | env-forced).`),_packageId:v().optional().describe(`Owning package machine id.`),_packageVersion:v().optional().describe(`Owning package version.`),_lockDocsUrl:v().optional().describe(`Optional documentation link surfaced next to _lockReason.`)},_v=T({lock:pv.describe(`Lock policy — none | no-overlay | no-delete | full.`),reason:v().min(1).max(500).describe(`User-visible reason shown when the lock blocks an action.`),docsUrl:v().url().optional().describe(`Optional URL the Studio banner links to for more context.`)}).strict(),vv=T({id:V.describe(`Unique identifier for this navigation item (lowercase snake_case)`),label:z.describe(`Display proper label`),icon:v().optional().describe(`Icon name`),order:y().optional().describe(`Sort order within the same level (lower = first)`),badge:E([v(),y()]).optional().describe(`Badge text or count displayed on the item`),visible:uv.optional().describe("Visibility predicate (CEL). e.g. P`'org_admin' in current_user.roles`"),requiredPermissions:w(v()).optional().describe(`Permissions required to access this item`),requiresObject:v().optional().describe(`Hide/disable this entry unless the named object is registered in the runtime`),requiresService:v().optional().describe(`Hide/disable this entry unless the named kernel service is registered`)}),yv=R(()=>vv.extend({type:j(`object`),objectName:v().describe(`Target object name`),viewName:v().optional().describe('Default list view to open. Defaults to "all". Ignored when `recordId` is set.'),recordId:v().optional().describe(`Navigate directly to this record id instead of the list view. Supports template vars: {current_user_id}, {current_org_id}.`),recordMode:A([`view`,`edit`]).optional().describe("Open the record in view (default) or edit mode. Only meaningful when `recordId` is set.")})),bv=R(()=>vv.extend({type:j(`dashboard`),dashboardName:v().describe(`Target dashboard name`)})),xv=R(()=>vv.extend({type:j(`page`),pageName:v().describe(`Target custom page component name`),params:k(v(),S()).optional().describe(`Parameters passed to the page context`)})),Sv=R(()=>vv.extend({type:j(`url`),url:v().describe(`Target external URL`),target:A([`_self`,`_blank`]).default(`_self`).describe(`Link target window`)})),Cv=R(()=>vv.extend({type:j(`report`),reportName:v().describe(`Target report name`)})),wv=R(()=>vv.extend({type:j(`action`),actionDef:T({actionName:v().describe(`Action machine name to execute`),params:k(v(),S()).optional().describe(`Parameters passed to the action`)}).describe(`Action definition to execute when clicked`)})),Tv=R(()=>vv.extend({type:j(`component`),componentRef:v().describe(`Component registry key (e.g. "metadata:directory")`),params:k(v(),S()).optional().describe(`Props passed to the component`)})),Ev=R(()=>vv.extend({type:j(`group`),expanded:b().default(!1).describe(`Default expansion state in sidebar`)})),Dv=M(()=>E([yv.extend({children:w(Dv).optional().describe(`Child navigation items (e.g. specific views)`)}),bv,xv,Sv,Cv,wv,Tv,Ev.extend({children:w(Dv).describe(`Child navigation items`)})]));R(()=>T({app:V.describe(`Target app name to contribute navigation into (e.g. "setup")`),group:V.optional().describe(`Target group nav-item id to append into (e.g. "group_integrations"); omit to append at the app top level`),priority:y().int().min(0).default(200).describe(`Merge priority within the target group — lower applied first (matches object extender priority)`),items:w(Dv).describe(`Navigation items contributed into the target app/group`)}).describe(`A navigation contribution: a package injecting nav items into an app it does not own (ADR-0029 D7)`));var Ov=R(()=>T({primaryColor:v().optional().describe(`Primary theme color hex code`),logo:v().optional().describe(`Custom logo URL for this app`),favicon:v().optional().describe(`Custom favicon URL for this app`)})),kv=R(()=>T({id:V.describe(`Unique area identifier (lowercase snake_case)`),label:z.describe(`Area display label`),icon:v().optional().describe(`Area icon name`),order:y().optional().describe(`Sort order among areas (lower = first)`),description:z.optional().describe(`Area description`),visible:uv.optional().describe(`Visibility predicate (CEL) for this area.`),requiredPermissions:w(v()).optional().describe(`Permissions required to access this area`),navigation:w(Dv).describe(`Navigation items within this area`)})),Av=R(()=>T({id:V.describe(`Selector id; selected value is exposed as the nav template var {<id>}`),label:z.describe(`Dropdown label`),icon:v().optional().describe(`Icon name`),optionsSource:T({endpoint:v().describe(`REST endpoint returning the option rows (e.g. /api/v1/packages)`),valueKey:v().default(`id`).describe(`Row property used as the option value (dotted path allowed, e.g. "manifest.id")`),labelKey:v().default(`name`).describe(`Row property used as the option label (dotted path allowed, e.g. "manifest.name")`),filter:w(T({key:v().describe(`Dotted path on each row to compare (e.g. "manifest.scope")`),op:A([`eq`,`ne`,`in`,`nin`]).default(`eq`).describe(`Comparison operator: eq | ne | in | nin`),value:E([v(),w(v())]).describe(`Comparison value (string for eq/ne, string[] for in/nin)`)})).optional().describe(`Predicates (AND) each option row must satisfy`)}).describe(`Option data source`),includeAll:b().default(!0).describe(`Prepend an "All" option that clears the scope`),allValue:v().default(``).describe(`Template value when "All" is selected (empty = no filter)`),persist:A([`query`,`session`,`none`]).default(`query`).describe(`Persist selection via URL query, sessionStorage, or not at all`),placement:A([`sidebar_header`,`topbar`]).default(`sidebar_header`).describe(`Render location in the app chrome`)})),jv=R(()=>T({name:V.describe(`App unique machine name (lowercase snake_case)`),label:z.describe(`App display label`),version:v().optional().describe(`App version`),description:z.optional().describe(`App description`),icon:v().optional().describe(`App icon used in the App Launcher`),branding:Ov.optional().describe(`App-specific branding`),active:b().optional().default(!0).describe(`Whether the app is enabled`),isDefault:b().optional().default(!1).describe(`Is default app`),hidden:b().optional().describe(`Hide from the App Switcher; the shell surfaces hidden apps via the avatar menu instead`),navigation:w(Dv).optional().describe(`Full navigation tree for the app sidebar`),areas:w(kv).optional().describe(`Navigation areas for partitioning navigation by business domain`),contextSelectors:w(Av).optional().describe(`App-level scope dropdowns whose value is injected into nav items as {<id>} template vars`),homePageId:v().optional().describe(`ID of the navigation item to serve as landing page`),requiredPermissions:w(v()).optional().describe(`Permissions required to access this app`),objects:w(S()).optional().describe(`Objects belonging to this app`),apis:w(S()).optional().describe(`Custom APIs belonging to this app`),sharing:dv.optional().describe(`Public sharing configuration`),embed:fv.optional().describe(`Iframe embedding configuration`),mobileNavigation:T({mode:A([`drawer`,`bottom_nav`,`hamburger`]).default(`drawer`).describe(`Mobile navigation mode: drawer sidebar, bottom navigation bar, or hamburger menu`),bottomNavItems:w(v()).optional().describe(`Navigation item IDs to show in bottom nav (max 5)`)}).optional().describe(`Mobile-specific navigation configuration`),defaultAgent:V.optional().describe(`Name of the default AI agent for this app (used by the ambient chat endpoint)`),aria:B.optional().describe(`ARIA accessibility attributes for the application`),protection:_v.optional().describe(`Package author protection block — lock policy for this app.`),...gv})),Mv=A(`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(`.`)),Nv=R(()=>T({label:v().describe(`Display label (human-readable, any case allowed)`),value:ov.describe(`Stored value (lowercase machine identifier)`),color:v().optional().describe(`Color code for badges/charts`),default:b().optional().describe(`Is default option`)}));R(()=>T({latitude:y().min(-90).max(90).describe(`Latitude coordinate`),longitude:y().min(-180).max(180).describe(`Longitude coordinate`),altitude:y().optional().describe(`Altitude in meters`),accuracy:y().optional().describe(`Accuracy in meters`)}));var Pv=R(()=>T({precision:y().int().min(0).max(10).default(2).describe(`Decimal precision (default: 2)`),currencyMode:A([`dynamic`,`fixed`]).default(`dynamic`).describe(`Currency mode: dynamic (user selectable) or fixed (single currency)`),defaultCurrency:v().length(3).default(`CNY`).describe(`Default or fixed currency code (ISO 4217, e.g., USD, CNY, EUR)`)}));R(()=>T({value:y().describe(`Monetary amount`),currency:v().length(3).describe(`Currency code (ISO 4217)`)})),R(()=>T({street:v().optional().describe(`Street address`),city:v().optional().describe(`City name`),state:v().optional().describe(`State/Province`),postalCode:v().optional().describe(`Postal/ZIP code`),country:v().optional().describe(`Country name or code`),countryCode:v().optional().describe(`ISO country code (e.g., US, GB)`),formatted:v().optional().describe(`Formatted address string`)}));var Fv=R(()=>T({dimensions:y().int().min(1).max(1e4).describe(`Vector dimensionality (e.g., 1536 for OpenAI embeddings)`),distanceMetric:A([`cosine`,`euclidean`,`dotProduct`,`manhattan`]).default(`cosine`).describe(`Distance/similarity metric for vector search`),normalized:b().default(!1).describe(`Whether vectors are normalized (unit length)`),indexed:b().default(!0).describe(`Whether to create a vector index for fast similarity search`),indexType:A([`hnsw`,`ivfflat`,`flat`]).optional().describe(`Vector index algorithm (HNSW for high accuracy, IVFFlat for large datasets)`)})),Iv=R(()=>T({minSize:y().min(0).optional().describe(`Minimum file size in bytes`),maxSize:y().min(1).optional().describe(`Maximum file size in bytes (e.g., 10485760 = 10MB)`),allowedTypes:w(v()).optional().describe(`Allowed file extensions (e.g., [".pdf", ".docx", ".jpg"])`),blockedTypes:w(v()).optional().describe(`Blocked file extensions (e.g., [".exe", ".bat", ".sh"])`),allowedMimeTypes:w(v()).optional().describe(`Allowed MIME types (e.g., ["image/jpeg", "application/pdf"])`),blockedMimeTypes:w(v()).optional().describe(`Blocked MIME types`),virusScan:b().default(!1).describe(`Enable virus scanning for uploaded files`),virusScanProvider:A([`clamav`,`virustotal`,`metadefender`,`custom`]).optional().describe(`Virus scanning service provider`),virusScanOnUpload:b().default(!0).describe(`Scan files immediately on upload`),quarantineOnThreat:b().default(!0).describe(`Quarantine files if threat detected`),storageProvider:v().optional().describe(`Object storage provider name (references ObjectStorageConfig)`),storageBucket:v().optional().describe(`Target bucket name`),storagePrefix:v().optional().describe(`Storage path prefix (e.g., "uploads/documents/")`),imageValidation:T({minWidth:y().min(1).optional().describe(`Minimum image width in pixels`),maxWidth:y().min(1).optional().describe(`Maximum image width in pixels`),minHeight:y().min(1).optional().describe(`Minimum image height in pixels`),maxHeight:y().min(1).optional().describe(`Maximum image height in pixels`),aspectRatio:v().optional().describe(`Required aspect ratio (e.g., "16:9", "1:1")`),generateThumbnails:b().default(!1).describe(`Auto-generate thumbnails`),thumbnailSizes:w(T({name:v().describe(`Thumbnail variant name (e.g., "small", "medium", "large")`),width:y().min(1).describe(`Thumbnail width in pixels`),height:y().min(1).describe(`Thumbnail height in pixels`),crop:b().default(!1).describe(`Crop to exact dimensions`)})).optional().describe(`Thumbnail size configurations`),preserveMetadata:b().default(!1).describe(`Preserve EXIF metadata`),autoRotate:b().default(!0).describe(`Auto-rotate based on EXIF orientation`)}).optional().describe(`Image-specific validation rules`),allowMultiple:b().default(!1).describe(`Allow multiple file uploads (overrides field.multiple)`),allowReplace:b().default(!0).describe(`Allow replacing existing files`),allowDelete:b().default(!0).describe(`Allow deleting uploaded files`),requireUpload:b().default(!1).describe(`Require at least one file when field is required`),extractMetadata:b().default(!0).describe(`Extract file metadata (name, size, type, etc.)`),extractText:b().default(!1).describe(`Extract text content from documents (OCR/parsing)`),versioningEnabled:b().default(!1).describe(`Keep previous versions of replaced files`),maxVersions:y().min(1).optional().describe(`Maximum number of versions to retain`),publicRead:b().default(!1).describe(`Allow public read access to uploaded files`),presignedUrlExpiry:y().min(60).max(604800).default(3600).describe(`Presigned URL expiration in seconds (default: 1 hour)`)}).refine(e=>!(e.minSize!==void 0&&e.maxSize!==void 0&&e.minSize>e.maxSize),{message:`minSize must be less than or equal to maxSize`}).refine(e=>!(e.virusScanProvider!==void 0&&e.virusScan!==!0),{message:`virusScanProvider requires virusScan to be enabled`}));R(()=>T({uniqueness:b().default(!1).describe(`Enforce unique values across all records`),completeness:y().min(0).max(1).default(0).describe(`Minimum ratio of non-null values (0-1, default: 0 = no requirement)`),accuracy:T({source:v().describe(`Reference data source for validation (e.g., "api.verify.com", "master_data")`),threshold:y().min(0).max(1).describe(`Minimum accuracy threshold (0-1, e.g., 0.95 = 95% match required)`)}).optional().describe(`Accuracy validation configuration`)})),R(()=>T({enabled:b().describe(`Enable caching for computed field results`),ttl:y().min(0).describe(`Cache TTL in seconds (0 = no expiration)`),invalidateOn:w(v()).describe(`Field paths that invalidate cache (e.g., ["inventory.quantity", "pricing.base_price"])`)}));var Lv=R(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Machine name (snake_case)`).optional(),label:v().optional().describe(`Human readable label`),type:Mv.describe(`Field Data Type`),description:v().optional().describe(`Tooltip/Help text`),format:v().optional().describe(`Format string (e.g. email, phone)`),columnName:v().optional().describe(`Physical column name in the target datasource. Defaults to the field key when not set.`),required:b().default(!1).describe(`Is required`),searchable:b().default(!1).describe(`Is searchable`),multiple:b().default(!1).describe(`Allow multiple values (Stores as Array/JSON). Applicable for select, lookup, file, image.`),unique:b().default(!1).describe(`Is unique constraint`),defaultValue:S().optional().describe(`Default value`),maxLength:y().optional().describe(`Max character length`),minLength:y().optional().describe(`Min character length`),precision:y().optional().describe(`Total digits`),scale:y().optional().describe(`Decimal places`),min:y().optional().describe(`Minimum value`),max:y().optional().describe(`Maximum value`),options:w(Nv).optional().describe(`Static options for select/multiselect`),reference:v().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.`),referenceFilters:w(v()).optional().describe(`Filters applied to lookup dialogs (e.g. "active = true")`),deleteBehavior:A([`set_null`,`cascade`,`restrict`]).optional().default(`set_null`).describe(`What happens if referenced record is deleted`),inlineEdit:E([b(),A([`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:v().optional().describe(`Title for the inline master-detail grid`),inlineColumns:w(x()).optional().describe(`Explicit columns for the inline grid (derived from the child object when omitted)`),inlineAmountField:v().optional().describe(`Numeric child field summed for the inline grid total`),relatedList:b().optional().describe(`Show this child collection as a related list on the parent's detail page (read-side mirror of inlineEdit). Defaults to shown for master_detail/lookup; set false to suppress.`),relatedListTitle:v().optional().describe(`Title for the detail-page related list`),relatedListColumns:w(x()).optional().describe(`Explicit columns for the detail-page related list (derived from the child object when omitted)`),displayField:v().optional().describe(`Field shown as each candidate's label in the picker/popover (defaults to the referenced object's name/title).`),descriptionField:v().optional().describe(`Secondary field shown under the label in the quick-select popover.`),lookupColumns:w(E([v(),T({field:v(),label:v().optional(),width:v().optional(),type:v().optional()})])).optional().describe(`Explicit columns for the record-picker table; auto-derived from the referenced object when omitted.`),lookupPageSize:y().int().positive().optional().describe(`Rows per page in the record-picker dialog (default 10).`),lookupFilters:w(T({field:v(),operator:A([`eq`,`ne`,`gt`,`lt`,`gte`,`lte`,`contains`,`in`,`notIn`]),value:x()})).optional().describe(`Base filters restricting which records are selectable (e.g. only active). Structured, picker-honoured form of referenceFilters.`),dependsOn:w(E([v(),T({field:v(),param:v().optional()})])).optional().describe(`Dependent lookup: restrict candidates by the value of other field(s) on the same record. String = same local/remote key; {field,param} when the remote filter key differs.`),allowCreate:b().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:uv.optional().describe("Formula expression (CEL). e.g. F`record.amount * 0.1`"),returnType:A([`number`,`text`,`boolean`,`date`]).optional().describe(`Inferred value type of a formula field (number/text/boolean/date)`),summaryOperations:T({object:v().describe(`Source child object name for roll-up`),field:v().describe(`Field on child object to aggregate (ignored for count)`),function:A([`count`,`sum`,`min`,`max`,`avg`]).describe(`Aggregation function to apply`),relationshipField:v().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.`)}).optional().describe(`Roll-up summary definition. The engine recomputes the value when child records are inserted/updated/deleted.`),language:v().optional().describe(`Programming language for syntax highlighting (e.g., javascript, python, sql)`),maxRating:y().optional().describe(`Maximum rating value (default: 5)`),step:y().optional().describe(`Step increment for slider (default: 1)`),currencyConfig:Pv.optional().describe(`Configuration for currency field type`),dimensions:y().int().min(1).max(1e4).optional().describe(`Vector dimensionality (e.g., 1536 for OpenAI embeddings)`),vectorConfig:Fv.optional().describe(`Configuration for vector field type (AI/ML embeddings)`),fileAttachmentConfig:Iv.optional().describe(`Configuration for file and attachment field types`),trackHistory:b().optional().describe(`Render this field's value changes as human-readable entries on the record activity timeline (ADR-0052 §5b). Opt-in per field.`),dependencies:w(v()).optional().describe(`Array of field names that this field depends on (for formulas, visibility rules, etc.)`),group:v().optional().describe(`Field group name for organizing fields in forms and layouts (e.g., "contact_info", "billing", "system")`),visibleWhen:uv.optional().describe("Predicate (CEL) — field is shown only when TRUE (else hidden). e.g. P`record.type == 'invoice'`"),readonlyWhen:uv.optional().describe("Predicate (CEL) — field is read-only when TRUE. e.g. P`record.status == 'paid'`"),requiredWhen:uv.optional().describe("Predicate (CEL) — field is required when TRUE. Canonical name for `conditionalRequired`."),conditionalRequired:uv.optional().describe("Predicate (CEL) — field is required when TRUE. Alias of `requiredWhen`."),hidden:b().default(!1).describe(`Hidden from default UI`),readonly:b().default(!1).describe(`Read-only in UI`),requiredPermissions:w(v()).optional().describe(`[ADR-0066 D3] Capabilities required to read/edit this field (mask on read, deny on write; AND-gate).`),system:b().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:b().optional().default(!0).describe(`Whether field is sortable in list views`),inlineHelpText:v().optional().describe(`Help text displayed below the field in forms`),caseSensitive:b().optional().describe(`Whether text comparisons are case-sensitive`),autonumberFormat:v().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).`),index:b().default(!1).describe(`Create standard database index`),externalId:b().default(!1).describe(`Is external ID for upsert operations`)})),Rv=A([`GET`,`POST`,`PUT`,`DELETE`,`PATCH`,`HEAD`,`OPTIONS`]),zv=R(()=>A([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`])),Bv=R(()=>T({url:v().describe(`API endpoint URL`),method:zv.optional().default(`GET`).describe(`HTTP method`),headers:k(v(),v()).optional().describe(`Custom HTTP headers`),params:k(v(),S()).optional().describe(`Query parameters`),body:S().optional().describe(`Request body for POST/PUT/PATCH`)}));R(()=>T({enabled:b().default(!0).describe(`Enable CORS`),origins:E([v(),w(v())]).default(`*`).describe(`Allowed origins (* for all)`),methods:w(Rv).optional().describe(`Allowed HTTP methods`),credentials:b().default(!1).describe(`Allow credentials (cookies, authorization headers)`),maxAge:y().int().optional().describe(`Preflight cache duration in seconds`)})),R(()=>T({enabled:b().default(!1).describe(`Enable rate limiting`),windowMs:y().int().default(6e4).describe(`Time window in milliseconds`),maxRequests:y().int().default(100).describe(`Max requests per window`)})),R(()=>T({path:v().describe(`URL path to serve from`),directory:v().describe(`Physical directory to serve`),cacheControl:v().optional().describe(`Cache-Control header value`)}));var Vv=R(()=>D(`provider`,[T({provider:j(`object`),object:v().describe(`Target object name`)}),T({provider:j(`api`),read:Bv.optional().describe(`Configuration for fetching data`),write:Bv.optional().describe(`Configuration for submitting data (for forms/editable tables)`)}),T({provider:j(`value`),items:w(S()).describe(`Static data array`)}),T({provider:j(`schema`),schemaId:v().describe(`Schema identifier — typically the metadata type name`),schema:k(v(),S()).optional().describe(`Inline JSON Schema (Draft 2020-12). Optional when schemaId is resolvable.`)})])),Hv=R(()=>T({field:v().describe(`Field name to filter on`),operator:v().describe(`Filter operator (e.g. equals, not_equals, contains, this_quarter)`),value:E([v(),y(),b(),ul(),w(E([v(),y()]))]).optional().describe(`Filter value`)}).describe(`View filter rule`)),Uv=R(()=>A([`none`,`count`,`count_empty`,`count_filled`,`count_unique`,`percent_empty`,`percent_filled`,`sum`,`avg`,`min`,`max`]).describe(`Aggregation function for column footer summary`)),Wv=R(()=>T({field:v().describe(`Field name (snake_case)`),label:z.optional().describe(`Display label override`),width:y().positive().optional().describe(`Column width in pixels`),align:A([`left`,`center`,`right`]).optional().describe(`Text alignment`),hidden:b().optional().describe(`Hide column by default`),sortable:b().optional().describe(`Allow sorting by this column`),resizable:b().optional().describe(`Allow resizing this column`),wrap:b().optional().describe(`Allow text wrapping`),type:v().optional().describe(`Renderer type override (e.g., "currency", "date")`),pinned:A([`left`,`right`]).optional().describe(`Pin/freeze column to left or right side`),summary:Uv.optional().describe(`Footer aggregation function for this column`),link:b().optional().describe(`Functions as the primary navigation link (triggers View navigation)`),action:v().optional().describe(`Registered Action ID to execute when clicked`)})),Gv=R(()=>T({type:A([`none`,`single`,`multiple`]).default(`none`).describe(`Selection mode`)})),Kv=R(()=>T({pageSize:y().int().positive().default(25).describe(`Number of records per page`),pageSizeOptions:w(y().int().positive()).optional().describe(`Available page size options`)})),qv=R(()=>A([`compact`,`short`,`medium`,`tall`,`extra_tall`]).describe(`Row height / density setting for list view`)),Jv=R(()=>T({field:v().describe(`Field name to group by`),order:A([`asc`,`desc`]).default(`asc`).describe(`Group sort order`),collapsed:b().default(!1).describe(`Collapse groups by default`)})),Yv=R(()=>T({fields:w(Jv).min(1).describe(`Fields to group by (supports up to 3 levels)`)}).describe(`Record grouping configuration`)),Xv=R(()=>T({coverField:v().optional().describe(`Attachment/image field to display as card cover`),coverFit:A([`cover`,`contain`]).default(`cover`).describe(`Image fit mode for card cover`),cardSize:A([`small`,`medium`,`large`]).default(`medium`).describe(`Card size in gallery view`),titleField:v().optional().describe(`Field to display as card title`),visibleFields:w(v()).optional().describe(`Fields to display on card body`)}).describe(`Gallery/card view configuration`)),Zv=R(()=>T({startDateField:v().describe(`Field for timeline item start date`),endDateField:v().optional().describe(`Field for timeline item end date`),titleField:v().describe(`Field to display as timeline item title`),groupByField:v().optional().describe(`Field to group timeline rows`),colorField:v().optional().describe(`Field to determine item color`),scale:A([`hour`,`day`,`week`,`month`,`quarter`,`year`]).default(`week`).describe(`Default timeline scale`)}).describe(`Timeline view configuration`)),Qv=R(()=>T({type:A([`personal`,`collaborative`]).default(`collaborative`).describe(`View ownership type`),lockedBy:v().optional().describe(`User who locked the view configuration`)}).describe(`View sharing and access configuration`)),$v=R(()=>T({field:v().describe(`Field to derive color from (typically a select/status field)`),colors:k(v(),v()).optional().describe(`Map of field value to color (hex/token)`)}).describe(`Row color configuration based on field values`)),ey=R(()=>A([`grid`,`kanban`,`gallery`,`calendar`,`timeline`,`gantt`,`map`,`chart`,`tree`]).describe(`Visualization type that users can switch to`)),ty=R(()=>T({sort:b().default(!0).describe(`Allow users to sort records`),search:b().default(!0).describe(`Allow users to search records`),filter:b().default(!0).describe(`Allow users to filter records`),rowHeight:b().default(!0).describe(`Allow users to toggle row height/density`),addRecordForm:b().default(!1).describe(`Add records through a form instead of inline`),buttons:w(v()).optional().describe(`Custom action button IDs to show in the toolbar`)}).describe(`User action toggles for the view toolbar`)),ny=R(()=>T({showDescription:b().default(!0).describe(`Show the view description text`),allowedVisualizations:w(ey).optional().describe(`Whitelist of visualization types users can switch between (e.g. ["grid", "gallery", "kanban"])`)}).describe(`Appearance and visualization configuration`)),ry=R(()=>T({name:V.describe(`Tab identifier (snake_case)`),label:z.optional().describe(`Display label`),icon:v().optional().describe(`Tab icon name`),view:v().optional().describe(`Referenced list view name from listViews`),filter:w(Hv).optional().describe(`Tab-specific filter criteria`),order:y().int().min(0).optional().describe(`Tab display order`),pinned:b().default(!1).describe(`Pin tab (cannot be removed by users)`),isDefault:b().default(!1).describe(`Set as the default active tab`),visible:b().default(!0).describe(`Tab visibility`)}).describe(`Tab configuration for multi-tab view interface`)),iy=R(()=>T({field:v().describe(`Field name on the source object (must exist — checked by reference diagnostics)`),label:z.optional().describe(`Display label override (defaults to the field label)`),type:A([`select`,`multi-select`,`boolean`,`date-range`,`text`]).optional().describe(`Filter control type. Omit to infer from the field definition`),options:w(T({value:E([v(),y(),b()]).describe(`Option value`),label:z.describe(`Option label`),color:v().optional().describe(`Option color token/hex`)})).optional().describe(`Static options. Omit to derive from the field definition (select options / lookup records)`),showCount:b().optional().describe(`Show per-option record counts`),defaultValues:w(E([v(),y(),b()])).optional().describe(`Pre-selected values when the view loads`)}).describe(`Quick-filter field configuration`)),ay=R(()=>T({element:A([`dropdown`,`tabs`,`toggle`]).default(`dropdown`).describe(`Filter control style: "dropdown" (per-field value selectors) or "tabs" (named presets). "toggle" is deprecated.`),fields:w(iy).optional().describe(`Fields exposed as quick filters (dropdown/toggle elements)`),tabs:w(ry).optional().describe(`Named filter presets rendered as tabs (tabs element). Reuses ViewTabSchema`),showAllRecords:b().optional().describe(`Show an "All records" tab before the presets (tabs element)`)}).describe(`End-user quick-filter configuration (Airtable "User filters" parity)`)),oy=R(()=>T({enabled:b().default(!0).describe(`Show the add record entry point`),position:A([`top`,`bottom`,`both`]).default(`bottom`).describe(`Position of the add record button`),mode:A([`inline`,`form`,`modal`]).default(`inline`).describe(`How to add a new record`),formView:v().optional().describe(`Named form view to use when mode is "form" or "modal"`)}).describe(`Add record entry point configuration`)),sy=R(()=>T({groupByField:v().describe(`Field to group columns by (usually status/select)`),summarizeField:v().optional().describe(`Field to sum at top of column (e.g. amount)`),columns:w(v()).describe(`Fields to show on cards`)})),cy=R(()=>T({chartType:A([`bar`,`line`,`pie`,`area`,`scatter`]).default(`bar`).describe(`Chart visualisation type`),dataset:V.describe(`Dataset name to bind (ADR-0021)`),dimensions:w(v()).optional().describe(`Dimension names — X/group/split`),values:w(v()).min(1).describe(`Measure names — Y (at least one)`)}).describe(`List chart view configuration`)),ly=R(()=>T({startDateField:v(),endDateField:v().optional(),titleField:v(),colorField:v().optional()})),uy=R(()=>T({field:v().describe(`Record field / dot-path the dimension filters on`),label:v().optional().describe(`Trigger label (falls back to the field label)`),options:w(E([v(),T({value:E([v(),y()]),label:v().optional()})])).optional().describe(`Explicit option override for fixed enums`)})),dy=R(()=>T({startDateField:v(),endDateField:v(),titleField:v(),progressField:v().optional(),dependenciesField:v().optional(),colorField:v().optional().describe(`Field that drives the bar color`),parentField:v().optional().describe(`Field holding the parent task id (builds the summary → step tree)`),typeField:v().optional().describe(`Field whose value maps to task/summary/milestone`),baselineStartField:v().optional().describe(`Baseline (planned) start field`),baselineEndField:v().optional().describe(`Baseline (planned) end field`),groupByField:v().optional().describe(`Field to group leaf tasks by (synthesized summary rows)`),resourceView:b().optional().describe(`Render a per-resource workload histogram instead of the timeline`),assigneeField:v().optional().describe(`Resource field to bucket load by (resource view)`),effortField:v().optional().describe(`Per-task load units (resource view; default 1)`),capacity:y().optional().describe(`Per-resource capacity ceiling; loads above this flag overload`),tooltipFields:w(E([v(),T({field:v(),label:v().optional()})])).optional().describe(`Fields to surface in the hover tooltip, in display order`),quickFilters:w(uy).optional().describe(`Multi-select filter dropdowns rendered above the chart`),autoZoomToFilter:b().optional().describe(`When true (default), filtering zooms the range to the filtered tasks`)}).passthrough()),fy=R(()=>T({parentField:v().optional().describe(`Single-parent pointer field (auto-detected from the object schema when omitted)`),labelField:v().optional().describe(`Field rendered indented in the first column (defaults to "name")`),fields:w(v()).optional().describe(`Additional fields rendered as flat columns alongside the label`),defaultExpandedDepth:y().int().min(0).optional().describe(`Initial expansion depth (0 = roots only; omit = expand all)`)}).passthrough()),py=R(()=>A([`page`,`drawer`,`modal`,`split`,`popover`,`new_window`,`none`])),my=R(()=>T({mode:py.default(`page`),view:v().optional().describe(`Name of the form view to use for details (e.g. "summary_view", "edit_form")`),preventNavigation:b().default(!1).describe(`Disable standard navigation entirely`),openNewTab:b().default(!1).describe(`Force open in new tab (applies to page mode)`),width:E([v(),y()]).optional().describe(`Width of the drawer/modal (e.g. "600px", "50%")`)})),hy=R(()=>T({name:V.optional().describe(`Internal view name (lowercase snake_case)`),label:z.optional(),type:A([`grid`,`kanban`,`gallery`,`calendar`,`timeline`,`gantt`,`map`,`chart`,`tree`]).default(`grid`),data:Vv.optional().describe(`Data source configuration (defaults to "object" provider)`),columns:E([w(v()),w(Wv)]).describe(`Fields to display as columns`),filter:w(Hv).optional().describe(`Filter criteria (JSON Rules)`),sort:E([v(),w(T({field:v(),order:A([`asc`,`desc`])}))]).optional(),searchableFields:w(v()).optional().describe(`Fields enabled for search`),filterableFields:w(v()).optional().describe(`Legacy shorthand for userFilters.fields — bare field names enabled for end-user filtering. Prefer userFilters`),userFilters:ay.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:b().optional().describe(`Enable column resizing`),striped:b().optional().describe(`Striped row styling`),bordered:b().optional().describe(`Show borders`),compactToolbar:b().optional().describe(`Collapse Group/Color/Density/Hide-fields into a single View settings popover`),selection:Gv.optional().describe(`Row selection configuration`),navigation:my.optional().describe(`Configuration for item click navigation (page, drawer, modal, etc.)`),pagination:Kv.optional().describe(`Pagination configuration`),kanban:sy.optional(),calendar:ly.optional(),gantt:dy.optional(),gallery:Xv.optional(),timeline:Zv.optional(),chart:cy.optional(),tree:fy.optional(),description:z.optional().describe(`View description for documentation/tooltips`),sharing:Qv.optional().describe(`View sharing and access configuration`),rowHeight:qv.optional().describe(`Row height / density setting`),grouping:Yv.optional().describe(`Group records by one or more fields`),rowColor:$v.optional().describe(`Color rows based on field value`),hiddenFields:w(v()).optional().describe(`Fields to hide in this specific view`),fieldOrder:w(v()).optional().describe(`Explicit field display order for this view`),rowActions:w(v()).optional().describe(`Actions available for individual row items`),bulkActions:w(v()).optional().describe(`Actions available when multiple rows are selected`),bulkActionDefs:w(k(v(),x())).optional().describe(`Rich bulk action definitions (schema-driven, executed via BulkActionDialog)`),virtualScroll:b().optional().describe(`Enable virtual scrolling for large datasets`),conditionalFormatting:w(T({condition:uv.describe(`Predicate (CEL) to evaluate.`),style:k(v(),v()).describe(`CSS styles to apply when condition is true`)})).optional().describe(`Conditional formatting rules for list rows`),inlineEdit:b().optional().describe(`Allow inline editing of records directly in the list view`),exportOptions:w(A([`csv`,`xlsx`,`pdf`,`json`])).optional().describe(`Available export format options`),userActions:ty.optional().describe(`User action toggles for the view toolbar`),appearance:ny.optional().describe(`Appearance and visualization configuration`),tabs:w(ry).optional().describe(`Tab definitions for multi-tab view interface`),addRecord:oy.optional().describe(`Add record entry point configuration`),showRecordCount:b().optional().describe(`Show record count at the bottom of the list`),allowPrinting:b().optional().describe(`Allow users to print the view`),emptyState:T({title:z.optional(),message:z.optional(),icon:v().optional()}).optional().describe(`Empty state configuration when no records found`),aria:B.optional().describe(`ARIA accessibility attributes for the list view`),responsive:nv.optional().describe(`Responsive layout configuration`),performance:av.optional().describe(`Performance optimization settings`)})),gy=R(()=>T({field:v().describe(`Field name (snake_case)`),type:Mv.optional().describe(`Field type (auto-infers widget if omitted)`),options:w(Nv).optional().describe(`Options for select/multiselect/radio/checkboxes fields`),reference:v().optional().describe(`Target object name for lookup/master_detail fields`),maxLength:y().optional().describe(`Maximum character length (for text/textarea/email/url/phone)`),minLength:y().optional().describe(`Minimum character length`),min:y().optional().describe(`Minimum value (for number/currency/percent/slider)`),max:y().optional().describe(`Maximum value`),precision:y().optional().describe(`Total digits (for number/currency)`),scale:y().optional().describe(`Decimal places`),multiple:b().optional().describe(`Allow multiple values (for select/lookup/file/image)`),label:z.optional().describe(`Display label override`),placeholder:z.optional().describe(`Placeholder text`),helpText:z.optional().describe(`Help/hint text`),readonly:b().optional().describe(`Read-only override`),immutable:b().optional().describe(`Editable on create, locked once the record exists (e.g. machine names).`),required:b().optional().describe(`Required override`),hidden:b().optional().describe(`Hidden override`),colSpan:y().int().min(1).max(4).optional().describe(`Column span in grid layout (1-4)`),widget:v().optional().describe(`Custom widget/component name (overrides type-based inference)`),language:v().optional().describe(`Code editor language (for type=code)`),fields:w(M(()=>gy)).optional().describe(`Sub-fields for composite/repeater/record types`),keyField:T({field:v().default(`name`).describe(`Property name that holds the key inside each item (defaults to "name")`),label:z.optional().describe(`Display label for the key column`),placeholder:z.optional().describe(`Placeholder when entering a new key`),helpText:z.optional().describe(`Help text under the key input`),regex:v().optional().describe(`JS regex source string the key must match (no flags)`),immutable:b().default(!0).describe(`If true, the key is read-only after creation`)}).optional().describe(`Key column config for record-typed fields`),dependsOn:v().optional().describe(`Parent field name for cascading`),visibleOn:uv.optional().describe(`Visibility predicate (CEL).`),disclosure:A([`inline`,`popover`]).optional().describe(`Composite rendering: inline bordered box (default) or a summary line + gear popover (progressive disclosure).`)})),_y=R(()=>T({name:v().optional().describe(`Stable section identifier for i18n lookup (snake_case)`),label:z.optional(),description:v().optional().describe(`Optional description rendered under the section header.`),collapsible:b().default(!1),collapsed:b().default(!1),visibleOn:uv.optional().describe(`Visibility predicate (CEL). Hides the whole section when false.`),columns:E([A([`1`,`2`,`3`,`4`]),j(1),j(2),j(3),j(4)]).default(1).transform(e=>typeof e==`string`?parseInt(e):e),fields:w(E([v(),gy]))})),vy=R(()=>T({type:A([`simple`,`tabbed`,`wizard`,`split`,`drawer`,`modal`]).default(`simple`),data:Vv.optional().describe(`Data source configuration (defaults to "object" provider)`),sections:w(_y).optional(),groups:w(_y).optional(),subforms:w(T({childObject:v().describe(`Child object whose records are entered inline`),relationshipField:v().optional().describe(`FK on the child pointing back to the parent (auto-detected when omitted)`),columns:w(x()).optional().describe(`Editable grid columns (derived from the child object when omitted)`),amountField:v().optional().describe(`Numeric child column summed for the running total`),totalField:v().optional().describe(`Parent field to receive the rolled-up sum`),title:v().optional().describe(`Section title`),addLabel:v().optional().describe(`Add-row button label`),minRows:y().optional(),maxRows:y().optional()})).optional().describe(`Inline master-detail child collections`),defaultSort:w(T({field:v().describe(`Field name to sort by`),order:A([`asc`,`desc`]).default(`desc`).describe(`Sort direction`)})).optional().describe(`Default sort order for related list views within this form`),sharing:dv.optional().describe(`Public sharing configuration for this form`),submitBehavior:E([T({kind:j(`thank-you`),title:v().optional(),message:v().optional()}),T({kind:j(`redirect`),url:v(),delayMs:y().int().min(0).optional()}),T({kind:j(`continue`)}),T({kind:j(`next-record`)})]).optional().describe(`Post-submit behavior`),aria:B.optional().describe(`ARIA accessibility attributes for the form view`)})),yy=R(()=>T({list:hy.optional(),form:vy.optional(),listViews:k(v(),hy).optional().describe(`Additional named list views`),formViews:k(v(),vy).optional().describe(`Additional named form views`),protection:_v.optional().describe(`Package author protection block — lock policy for this view.`),...gv})),by=v().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>`."),xy=A([`package`,`shared`,`personal`]).describe(`View identity layer: package | shared | personal.`);A([`list`,`form`]).describe("Whether `config` is a ListView (list family) or a FormView.");function Sy(){return{name:by,object:v().describe(`Bound object name — the foreign key used to aggregate views.`),label:z.optional().describe(`Display label (supports i18n).`),isDefault:b().optional().describe(`Whether this is the object's default view in the switcher.`),order:y().int().optional().describe(`Sort order within the object's view switcher / left rail.`),scope:xy.optional().describe("Identity layer (defaults to `package` for source-loaded views)."),owner:v().optional().describe("Owner user id — set when `scope` is `personal`."),hidden:b().optional().describe(`Hidden from the switcher (per-user / per-org declutter).`),protection:_v.optional().describe(`Package author protection block — lock policy for this view.`),...gv}}R(()=>D(`viewKind`,[T({viewKind:j(`list`),config:hy.describe(`List-family view configuration.`),...Sy()}),T({viewKind:j(`form`),config:vy.describe(`Form view configuration.`),...Sy()})]));function Cy(e){let{schemaId:t,...n}=e;return vy.parse({...n,data:{provider:`schema`,schemaId:t}})}var wy=R(()=>T({$field:v().describe(`Field Reference/Column Name`)}));R(()=>T({$eq:x().optional(),$ne:x().optional()})),R(()=>T({$gt:E([y(),C(),wy]).optional(),$gte:E([y(),C(),wy]).optional(),$lt:E([y(),C(),wy]).optional(),$lte:E([y(),C(),wy]).optional()})),R(()=>T({$in:w(x()).optional(),$nin:w(x()).optional()})),R(()=>T({$between:O([E([y(),C(),wy]),E([y(),C(),wy])]).optional()})),R(()=>T({$contains:v().optional(),$notContains:v().optional(),$startsWith:v().optional(),$endsWith:v().optional()})),R(()=>T({$null:b().optional(),$exists:b().optional()}));var Ty=R(()=>T({$eq:x().optional(),$ne:x().optional(),$gt:E([y(),C(),wy]).optional(),$gte:E([y(),C(),wy]).optional(),$lt:E([y(),C(),wy]).optional(),$lte:E([y(),C(),wy]).optional(),$in:w(x()).optional(),$nin:w(x()).optional(),$between:O([E([y(),C(),wy]),E([y(),C(),wy])]).optional(),$contains:v().optional(),$notContains:v().optional(),$startsWith:v().optional(),$endsWith:v().optional(),$null:b().optional(),$exists:b().optional()})),Ey=M(()=>k(v(),S()).and(T({$and:w(Ey).optional(),$or:w(Ey).optional(),$not:Ey.optional()})));R(()=>T({where:Ey.optional()}));var Dy=M(()=>T({$and:w(E([k(v(),Ty),Dy])).optional(),$or:w(E([k(v(),Ty),Dy])).optional(),$not:E([k(v(),Ty),Dy]).optional()})),Oy=R(()=>A([`default`,`blue`,`teal`,`orange`,`purple`,`success`,`warning`,`danger`]).describe(`Widget color variant`)),ky=R(()=>A([`script`,`url`,`modal`,`flow`,`api`]).describe(`Widget action type`)),Ay=R(()=>T({label:z.describe(`Action button label`),actionUrl:v().describe(`URL or target for the action`),actionType:ky.optional().describe(`Type of action`),icon:v().optional().describe(`Icon identifier for the action button`)}).describe(`Dashboard header action`)),jy=R(()=>T({showTitle:b().default(!0).describe(`Show dashboard title in header`),showDescription:b().default(!0).describe(`Show dashboard description in header`),actions:w(Ay).optional().describe(`Header action buttons`)}).describe(`Dashboard header configuration`)),My=R(()=>T({id:V.describe(`Unique widget identifier (snake_case)`),title:z.optional().describe(`Widget title`),description:z.optional().describe(`Widget description text below the header`),type:q_.default(`metric`).describe(`Visualization type`),chartConfig:Q_.optional().describe(`Chart visualization configuration`),colorVariant:Oy.optional().describe(`Widget color variant for theming`),requiresObject:v().optional().describe(`Hide the widget unless the named object is registered`),requiresService:v().optional().describe(`Hide the widget unless the named kernel service is registered`),actionUrl:v().optional().describe(`URL or target for the widget action button`),actionType:ky.optional().describe(`Type of action for the widget action button`),actionIcon:v().optional().describe(`Icon identifier for the widget action button`),filter:Ey.optional().describe(`Presentation-scope filter (runtimeFilter)`),compareTo:E([j(`previousPeriod`),j(`previousYear`),T({offset:v().regex(/^\d+[dwMy]$/,`Offset must match <N>(d|w|M|y), e.g. "7d", "1M", "1y"`)})]).optional().describe(`Period-over-period comparison window`),dataset:V.describe(`Dataset name to bind (ADR-0021)`),dimensions:w(v()).optional().describe(`Dimension names — X/group/split`),values:w(v()).min(1).describe(`Measure names — Y (at least one)`),layout:T({x:y(),y:y(),w:y(),h:y()}).optional().describe(`Grid layout position (auto-flowed when omitted)`),options:S().optional().describe(`Widget specific configuration`),suppressWarnings:w(v()).optional().describe(`Build diagnostic rule ids suppressed on this widget`),responsive:nv.optional().describe(`Responsive layout configuration`),aria:B.optional().describe(`ARIA accessibility attributes`)})),Ny=R(()=>T({object:v().describe(`Source object name`),valueField:v().describe(`Field to use as option value`),labelField:v().describe(`Field to use as option label`),filter:Ey.optional().describe(`Filter to apply to source object`)}).describe(`Dynamic filter options from object`)),Py=R(()=>T({field:v().describe(`Field name to filter on`),label:z.optional().describe(`Display label for the filter`),type:A([`text`,`select`,`date`,`number`,`lookup`]).optional().describe(`Filter input type`),options:w(T({value:E([v(),y(),b()]).describe(`Option value`),label:z})).optional().describe(`Static filter options`),optionsFrom:Ny.optional().describe(`Dynamic filter options from object`),defaultValue:E([v(),y(),b()]).optional().describe(`Default filter value`),scope:A([`dashboard`,`widget`]).default(`dashboard`).describe(`Filter application scope`),targetWidgets:w(v()).optional().describe(`Widget IDs to apply this filter to`)})),Fy=R(()=>T({name:V.describe(`Dashboard unique name`),label:z.describe(`Dashboard label`),description:z.optional().describe(`Dashboard description`),header:jy.optional().describe(`Dashboard header configuration`),widgets:w(My).describe(`Widgets to display`),columns:y().int().min(1).max(24).optional().describe(`Number of grid columns (default 12)`),gap:y().int().min(0).optional().describe(`Grid gap in Tailwind spacing units`),refreshInterval:y().optional().describe(`Auto-refresh interval in seconds`),dateRange:T({field:v().optional().describe(`Default date field name for time-based filtering`),defaultRange:A([`today`,`yesterday`,`this_week`,`last_week`,`this_month`,`last_month`,`this_quarter`,`last_quarter`,`this_year`,`last_year`,`last_7_days`,`last_30_days`,`last_90_days`,`custom`]).default(`this_month`).describe(`Default date range preset`),allowCustomRange:b().default(!0).describe(`Allow users to pick a custom date range`)}).optional().describe(`Global dashboard date range filter configuration`),globalFilters:w(Py).optional().describe(`Global filters that apply to all widgets in the dashboard`),aria:B.optional().describe(`ARIA accessibility attributes`),performance:av.optional().describe(`Performance optimization settings`),protection:_v.optional().describe(`Package author protection block — lock policy for this dashboard.`),...gv})),Iy=A([`tabular`,`summary`,`matrix`,`joined`]);R(()=>T({field:v().describe(`Field name`),label:z.optional().describe(`Override label`),aggregate:A([`sum`,`avg`,`max`,`min`,`count`,`unique`]).optional().describe(`Aggregation function`),responsive:nv.optional().describe(`Responsive visibility for this column`)})),R(()=>T({field:v().describe(`Field to group by`),sortOrder:A([`asc`,`desc`]).default(`asc`),dateGranularity:A([`day`,`week`,`month`,`quarter`,`year`]).optional().describe(`For date fields`)}));var Ly=R(()=>Q_.extend({xAxis:v().describe(`Grouping field for X-Axis`),yAxis:v().describe(`Summary field for Y-Axis`),groupBy:v().optional().describe(`Additional grouping field`)})),Ry=R(()=>T({name:V,label:z.optional(),description:z.optional(),type:A([`tabular`,`summary`,`matrix`]).default(`tabular`),chart:Ly.optional(),dataset:V.optional().describe(`Dataset name to bind (ADR-0021)`),rows:w(v()).optional().describe(`Dimension names down (dataset-bound)`),columns:w(v()).optional().describe(`Dimension names across (matrix, dataset-bound)`),values:w(v()).optional().describe(`Measure names to show (dataset-bound)`),runtimeFilter:Ey.optional().describe(`Render-time scope filter (dataset-bound)`)})),zy=R(()=>T({name:V.describe(`Report unique name`),label:z.describe(`Report label`),description:z.optional(),type:Iy.default(`tabular`).describe(`Report format type`),dataset:V.optional().describe(`Dataset name to bind (ADR-0021)`),rows:w(v()).optional().describe(`Dimension names down`),columns:w(v()).optional().describe(`Dimension names across (matrix)`),values:w(v()).optional().describe(`Measure names to show`),runtimeFilter:Ey.optional().describe(`Render-time scope filter`),drilldown:b().default(!0).describe(`Click-through to underlying records`),chart:Ly.optional().describe(`Embedded chart configuration`),aria:B.optional().describe(`ARIA accessibility attributes`),performance:av.optional().describe(`Performance optimization settings`),blocks:w(Ry).optional().describe(`Sub-reports for type=joined`),protection:_v.optional().describe(`Package author protection block — lock policy for this report.`),...gv}).superRefine((e,t)=>{e.type===`joined`?(!e.blocks||e.blocks.length===0)&&t.addIssue({code:`custom`,message:"a `joined` report needs `blocks`.",path:[`blocks`]}):(!e.dataset||!e.values||e.values.length===0)&&t.addIssue({code:`custom`,message:"a report needs `dataset` + `values` (measure names).",path:[`dataset`]})})),By=R(()=>T({field:v(),order:A([`asc`,`desc`]).default(`asc`)})),Vy=A([`count`,`sum`,`avg`,`min`,`max`,`count_distinct`,`array_agg`,`string_agg`]),Hy=A([`day`,`week`,`month`,`quarter`,`year`]),Uy=R(()=>E([v(),T({field:v().describe(`Field to group by`),dateGranularity:Hy.optional().describe(`Bucket date values into uniform periods (day/week/month/quarter/year)`),alias:v().optional().describe(`Alias for the projected group value`)})])),Wy=R(()=>T({function:Vy.describe(`Aggregation function`),field:v().optional().describe(`Field to aggregate (optional for COUNT(*))`),alias:v().describe(`Result column alias`),distinct:b().optional().describe(`Apply DISTINCT before aggregation`),filter:Ey.optional().describe(`Filter/Condition to apply to the aggregation (FILTER WHERE clause)`)})),Gy=A([`inner`,`left`,`right`,`full`]),Ky=A([`auto`,`database`,`hash`,`loop`]),qy=M(()=>T({type:Gy.describe(`Join type`),strategy:Ky.optional().describe(`Execution strategy hint`),object:v().describe(`Object/table to join`),alias:v().optional().describe(`Table alias`),on:Ey.describe(`Join condition`),subquery:M(()=>eb).optional().describe(`Subquery instead of object`)})),Jy=A([`row_number`,`rank`,`dense_rank`,`percent_rank`,`lag`,`lead`,`first_value`,`last_value`,`sum`,`avg`,`count`,`min`,`max`]),Yy=R(()=>T({partitionBy:w(v()).optional().describe(`PARTITION BY fields`),orderBy:w(By).optional().describe(`ORDER BY specification`),frame:T({type:A([`rows`,`range`]).optional(),start:v().optional().describe(`Frame start (e.g., "UNBOUNDED PRECEDING", "1 PRECEDING")`),end:v().optional().describe(`Frame end (e.g., "CURRENT ROW", "1 FOLLOWING")`)}).optional().describe(`Window frame specification`)})),Xy=R(()=>T({function:Jy.describe(`Window function name`),field:v().optional().describe(`Field to operate on (for aggregate window functions)`),alias:v().describe(`Result column alias`),over:Yy.describe(`Window specification (OVER clause)`)})),Zy=M(()=>E([v(),T({field:v(),fields:w(Zy).optional(),alias:v().optional()})])),Qy=R(()=>T({query:v().describe(`Search query text`),fields:w(v()).optional().describe(`Fields to search in (if not specified, searches all text fields)`),fuzzy:b().optional().default(!1).describe(`Enable fuzzy matching (tolerates typos)`),operator:A([`and`,`or`]).optional().default(`or`).describe(`Logical operator between terms`),boost:k(v(),y()).optional().describe(`Field-specific relevance boosting (field name -> boost factor)`),minScore:y().optional().describe(`Minimum relevance score threshold`),language:v().optional().describe(`Language for text analysis (e.g., "en", "zh", "es")`),highlight:b().optional().default(!1).describe(`Enable search result highlighting`)})),$y=T({object:v().describe(`Object name (e.g. account)`),fields:w(Zy).optional().describe(`Fields to retrieve`),where:Ey.optional().describe(`Filtering criteria (WHERE)`),search:Qy.optional().describe(`Full-text search configuration ($search parameter)`),orderBy:w(By).optional().describe(`Sorting instructions (ORDER BY)`),limit:y().optional().describe(`Max records to return (LIMIT)`),offset:y().optional().describe(`Records to skip (OFFSET)`),top:y().optional().describe(`Alias for limit (OData compatibility)`),cursor:k(v(),S()).optional().describe(`Cursor for keyset pagination`),joins:w(qy).optional().describe(`Explicit Table Joins`),aggregations:w(Wy).optional().describe(`Aggregation functions`),groupBy:w(Uy).optional().describe("GROUP BY targets (strings or `{field, dateGranularity?}` objects for date bucketing)"),having:Ey.optional().describe(`HAVING clause for aggregation filtering`),windowFunctions:w(Xy).optional().describe(`Window functions with OVER clause`),distinct:b().optional().describe(`SELECT DISTINCT flag`)}),eb=R(()=>$y.extend({expand:M(()=>k(v(),eb)).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.")})),tb=R(()=>T({name:V.describe(`Dimension name — referenced by presentations`),label:z.optional(),field:v().describe("Base field, or `relationship[.relationship].field` path"),type:A([`string`,`number`,`date`,`boolean`,`lookup`]).optional(),dateGranularity:Hy.optional()})),nb=A([`ratio`,`sum`,`difference`,`product`]),rb=R(()=>T({name:V.describe(`Measure name — e.g. "revenue"; defined once`),label:z.optional(),aggregate:Vy.optional().describe("Aggregation (sum/avg/count/...); omit when `derived` is set"),field:v().optional().describe(`Aggregated field; optional for count(*)`),filter:Ey.optional(),format:v().optional(),currency:v().length(3).optional().describe(`Display currency code (ISO 4217)`),certified:b().default(!1).describe(`Blessed metric (governance checkpoint)`),derived:T({op:nb,of:w(V).min(1)}).optional()}));R(()=>T({name:V.describe(`Dataset unique name`),label:z.describe(`Dataset label`),description:z.optional(),object:v().describe(`Base object name`),include:w(v().refine(e=>e.split(`.`).length<=3,{message:`include path exceeds the 3-hop limit (ADR-0071)`})).optional().describe(`Relationship names/paths to join (derived from object graph; max 3 hops)`),filter:Ey.optional().describe(`Intrinsic dataset scope filter`),dimensions:w(tb).describe(`Groupable axes`),measures:w(rb).describe(`Aggregatable values`),protection:_v.optional().describe(`Package author protection block — lock policy for this dataset.`),...gv}).superRefine((e,t)=>{let n=new Set;for(let r of e.measures)n.has(r.name)&&t.addIssue({code:`custom`,message:`duplicate measure name "${r.name}"`,path:[`measures`]}),n.add(r.name);let r=new Set;for(let n of e.dimensions)r.has(n.name)&&t.addIssue({code:`custom`,message:`duplicate dimension name "${n.name}"`,path:[`dimensions`]}),r.add(n.name);for(let r of e.measures){if(!r.derived){r.aggregate?!r.field&&r.aggregate!==`count`&&t.addIssue({code:`custom`,message:`measure "${r.name}" requires \`field\` (only \`count\` may omit it)`,path:[`measures`]}):t.addIssue({code:`custom`,message:`measure "${r.name}" requires \`aggregate\` (or a \`derived\` spec)`,path:[`measures`]});continue}for(let e of r.derived.of)e===r.name?t.addIssue({code:`custom`,message:`derived measure "${r.name}" cannot reference itself`,path:[`measures`]}):n.has(e)||t.addIssue({code:`custom`,message:`derived measure "${r.name}" references unknown measure "${e}"`,path:[`measures`]})}}));var ib=Cy({schemaId:`report`,type:`simple`,sections:[{label:`Basics`,description:`Identity and report type.`,columns:2,fields:[{field:`name`,type:`text`,colSpan:1,required:!0,helpText:`snake_case unique identifier`},{field:`label`,type:`text`,colSpan:1,required:!0},{field:`description`,type:`textarea`,colSpan:2},{field:`type`,colSpan:2,helpText:`Report type: tabular/summary/matrix/joined`}]},{label:`Dataset binding`,description:`The semantic-layer dataset this report renders. Values are the dataset’s measures; rows are its dimensions.`,visibleOn:`data.type != 'joined'`,fields:[{field:`dataset`,widget:`ref:dataset`,helpText:`Dataset to bind (measures/dimensions come from its semantic layer)`},{field:`values`,widget:`string-tags`,helpText:`Measure names (from the dataset) to display`},{field:`rows`,widget:`string-tags`,helpText:`Dimension names (from the dataset) to group rows by`},{field:`columns`,widget:`string-tags`,visibleOn:`data.type == 'matrix'`,helpText:`Dimension names across (matrix only)`},{field:`drilldown`,helpText:`Click an aggregated row/cell to open the underlying records`}]},{label:`Joined blocks`,description:`Additional dataset-bound blocks stacked into a single report (joined reports only).`,visibleOn:`data.type == 'joined'`,fields:[{field:`blocks`,type:`repeater`,helpText:`Dataset-bound sub-reports (joined report only)`}]},{label:`Filter & chart`,description:`Render-time scope filter and chart presentation.`,collapsible:!0,collapsed:!0,fields:[{field:`runtimeFilter`,widget:`json`,helpText:`Render-time scope filter, ANDed at query time`},{field:`chart`,type:`composite`,helpText:`Chart config (type, legend, colors)`}]},{label:`Advanced`,description:`Accessibility and performance tuning.`,collapsible:!0,collapsed:!0,fields:[{field:`aria`,type:`composite`,helpText:`Accessibility labels`},{field:`performance`,type:`composite`,helpText:`Caching and optimization`}]}]}),ab=Cy({schemaId:`view`,type:`simple`,sections:[{name:`basics`,label:`Basics`,description:`Identity and primary surface.`,columns:2,fields:[{field:`name`,type:`text`,required:!0,colSpan:1,helpText:`snake_case, unique per environment`},{field:`label`,type:`text`,required:!0,colSpan:1},{field:`description`,type:`textarea`,colSpan:2},{field:`type`,required:!0,colSpan:1,helpText:`Primary view surface`},{field:`data`,widget:`json`,colSpan:2,helpText:`Data source — e.g. {"provider":"object","object":"task"}`}]},{name:`columns_filters`,label:`Columns & filters`,description:`What rows show and how users filter them.`,fields:[{field:`columns`,type:`repeater`,required:!0,helpText:`Columns to display (field names from selected object)`},{field:`filter`,type:`repeater`,helpText:`Filter conditions`},{field:`sort`,type:`repeater`,helpText:`Default sort order`},{field:`searchableFields`,widget:`string-tags`,helpText:`Field names available for quick search`},{field:`filterableFields`,widget:`string-tags`,helpText:`Field names available for filtering`}]},{name:`table_options`,label:`Table options`,description:`Grid-only display options.`,visibleOn:`data.type == 'grid' || data.type == null`,collapsible:!0,collapsed:!0,columns:2,fields:[{field:`resizable`,colSpan:1},{field:`striped`,colSpan:1},{field:`bordered`,colSpan:1},{field:`compactToolbar`,colSpan:1},{field:`rowHeight`,colSpan:1},{field:`selection`,type:`composite`,colSpan:2},{field:`pagination`,type:`composite`,colSpan:2}]},{name:`kanban`,label:`Kanban`,description:`Kanban-specific board configuration.`,visibleOn:`data.type == 'kanban'`,fields:[{field:`kanban`,type:`composite`}]},{name:`calendar`,label:`Calendar`,description:`Calendar-specific configuration.`,visibleOn:`data.type == 'calendar'`,fields:[{field:`calendar`,type:`composite`}]},{name:`gantt`,label:`Gantt`,description:`Gantt-specific configuration.`,visibleOn:`data.type == 'gantt'`,fields:[{field:`gantt`,type:`composite`}]},{name:`gallery`,label:`Gallery`,description:`Gallery-specific configuration.`,visibleOn:`data.type == 'gallery'`,fields:[{field:`gallery`,type:`composite`}]},{name:`timeline`,label:`Timeline`,description:`Timeline-specific configuration.`,visibleOn:`data.type == 'timeline'`,fields:[{field:`timeline`,type:`composite`}]},{name:`chart`,label:`Chart`,description:`Chart-specific configuration.`,visibleOn:`data.type == 'chart'`,fields:[{field:`chart`,type:`composite`}]},{name:`end_user_controls`,label:`End-user controls`,description:`What end users can do on this view — quick filters, filter tabs, visualization switching (ADR-0047, Airtable Interface parity).`,collapsible:!0,collapsed:!0,fields:[{field:`userFilters`,type:`composite`,helpText:`Quick-filter bar: element style (dropdown / tabs / toggle) + exposed fields or tab presets`},{field:`tabs`,type:`repeater`,helpText:`In-view filter tabs — each tab applies its own filter rules`},{field:`appearance`,type:`composite`,helpText:`allowedVisualizations: which renderers users may switch between`},{field:`userActions`,type:`composite`,helpText:`Toolbar toggles: sort / search / filter / row height`},{field:`addRecord`,type:`composite`},{field:`showRecordCount`}]},{name:`navigation_sharing`,label:`Navigation & sharing`,description:`Where this view appears and who can see it.`,collapsible:!0,collapsed:!0,fields:[{field:`navigation`,type:`composite`},{field:`sharing`,type:`composite`}]}]});Cy({schemaId:`app`,type:`simple`,sections:[{label:`Basics`,description:`App identity and activation.`,columns:2,fields:[{field:`name`,type:`text`,required:!0,colSpan:1,helpText:`snake_case, unique`},{field:`label`,type:`text`,required:!0,colSpan:1},{field:`description`,type:`textarea`,colSpan:2},{field:`version`,type:`text`,colSpan:1},{field:`icon`,type:`text`,colSpan:1,helpText:`Lucide icon name (e.g. "users", "briefcase")`},{field:`active`,type:`boolean`,colSpan:1},{field:`isDefault`,type:`boolean`,colSpan:1,helpText:`Make this the default app for new users`}]},{label:`Navigation`,description:`Sidebar items and area grouping.`,fields:[{field:`navigation`,type:`composite`,helpText:`Nav tree — recursive structure`},{field:`areas`,type:`repeater`,helpText:`Group items into collapsible areas`},{field:`homePageId`,type:`text`,helpText:`Landing page when app opens`},{field:`mobileNavigation`,type:`composite`,helpText:`Bottom tab bar config for mobile`}]},{label:`Content`,description:`Objects and APIs this app uses.`,fields:[{field:`objects`,widget:`object-selector`,multiple:!0,helpText:`Object names this app exposes`},{field:`apis`,type:`composite`,helpText:`API endpoint definitions`},{field:`defaultAgent`,type:`text`,helpText:`AI agent for the ambient assistant button`}]},{label:`Branding`,description:`Theme colors and logo.`,collapsible:!0,collapsed:!0,fields:[{field:`branding`,type:`composite`,helpText:`Primary/secondary colors, logo, theme`}]},{label:`Access & sharing`,description:`Who can access this app and how it can be embedded.`,collapsible:!0,collapsed:!0,fields:[{field:`requiredPermissions`,widget:`string-tags`,helpText:`Permissions needed to access this app`},{field:`sharing`,type:`composite`,helpText:`Public/internal/restricted access control`},{field:`embed`,type:`composite`,helpText:`iFrame embed configuration`},{field:`aria`,type:`composite`,helpText:`Accessibility labels`}]}]});var ob=Cy({schemaId:`dashboard`,type:`simple`,sections:[{label:`Basics`,description:`Dashboard identity and description.`,columns:2,fields:[{field:`name`,type:`text`,required:!0,colSpan:1,helpText:`snake_case unique identifier`},{field:`label`,type:`text`,required:!0,colSpan:1,helpText:`Display name`},{field:`description`,type:`textarea`,colSpan:2}]},{label:`Layout`,description:`Grid sizing and refresh cadence.`,columns:3,fields:[{field:`columns`,type:`number`,colSpan:1,helpText:`Grid columns (default 12)`},{field:`gap`,type:`number`,colSpan:1,helpText:`Grid gap (Tailwind units)`},{field:`refreshInterval`,type:`number`,colSpan:1,helpText:`Auto-refresh (seconds)`},{field:`header`,type:`composite`,colSpan:3,helpText:`Dashboard header config (title, subtitle, actions)`}]},{label:`Widgets`,description:`Cards and charts placed on the grid.`,fields:[{field:`widgets`,type:`repeater`,required:!0,helpText:`Dashboard widgets with position and sizing`}]},{label:`Filters`,description:`Default and global filters applied across widgets.`,collapsible:!0,collapsed:!0,fields:[{field:`dateRange`,type:`composite`,helpText:`Default date range selector`},{field:`globalFilters`,type:`repeater`,helpText:`Filters applied to all widgets`}]},{label:`Advanced`,description:`Accessibility and performance tuning.`,collapsible:!0,collapsed:!0,fields:[{field:`aria`,type:`composite`,helpText:`Accessibility labels`},{field:`performance`,type:`composite`,helpText:`Caching and optimization config`}]}]});Cy({schemaId:`dataset`,type:`simple`,sections:[{name:`basics`,label:`Basics`,description:`Dataset identity.`,columns:2,fields:[{field:`name`,type:`text`,colSpan:1,required:!0,immutable:!0,helpText:`snake_case unique identifier`},{field:`label`,type:`text`,colSpan:1,required:!0,helpText:`Display name`},{field:`description`,type:`textarea`,colSpan:2,helpText:`What this dataset measures`}]},{name:`source`,label:`Source`,description:`The base object, the relationships to join, and the dataset’s intrinsic scope. Joins are derived from the object graph — pick relationship (lookup / master_detail) names, never write an ON clause.`,fields:[{field:`object`,widget:`ref:object`,required:!0,helpText:`Base object — the FROM`},{field:`include`,widget:`string-tags`,helpText:'Relationship (lookup / master_detail) field names to join — enables `relationship.field` dimensions/measures (e.g. include "account" → group by account.region)'},{field:`filter`,widget:`filter-builder`,dependsOn:`object`,helpText:`Intrinsic scope filter (e.g. exclude soft-deleted records), ANDed into every query`}]},{name:`dimensions`,label:`Dimensions`,description:"Groupable axes. Use a base field, or `relationship.field` (e.g. account.region) for a relationship included above.",fields:[{field:`dimensions`,type:`repeater`,required:!0,helpText:`Each: name (referenced by presentations), field, type, and — for dates — a default bucketing granularity`}]},{name:`measures`,label:`Measures`,description:`Aggregatable values defined once and referenced by name. A measure is sum/avg/count/… of a field; a derived measure combines other measures (ratio/sum/difference/product). Measure-scoped filters and derived ops are edited per-row in the dataset designer.`,fields:[{field:`measures`,type:`repeater`,required:!0,helpText:`Each: name, aggregate, field (optional for count), display format/currency, and a “certified” governance flag`}]}]}),Cy({schemaId:`action`,type:`simple`,sections:[{label:`Basics`,description:`Action identity and presentation.`,columns:2,fields:[{field:`name`,required:!0,colSpan:1,helpText:`Unique identifier (snake_case)`},{field:`label`,required:!0,colSpan:1,helpText:`Button text shown to users`},{field:`objectName`,widget:`ref:object`,colSpan:1,helpText:`Object this action belongs to (optional)`},{field:`icon`,colSpan:1,helpText:`Lucide icon name (e.g., "check", "x-circle")`},{field:`type`,required:!0,colSpan:1,helpText:`What happens when clicked`},{field:`variant`,colSpan:1,helpText:`Button style (primary=blue, danger=red, ghost=transparent)`}]},{label:`Behavior`,description:`Configure what happens when the action is triggered.`,fields:[{field:`target`,visibleOn:`data.type != 'script'`,helpText:`URL, flow name, or API endpoint to call`},{field:`method`,visibleOn:`data.type == 'api'`,helpText:`HTTP method (GET, POST, PUT, DELETE)`},{field:`body`,type:`composite`,visibleOn:`data.type == 'script'`,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:`params`,type:`repeater`,helpText:`User input parameters (show form before executing)`},{field:`confirmText`,helpText:`Confirmation message (e.g., "Are you sure?")`},{field:`successMessage`,helpText:`Success message after completion`},{field:`refreshAfter`,helpText:`Refresh the list/page after action completes`}]},{label:`Placement`,description:`Where and when the action button appears.`,collapsible:!0,collapsed:!0,fields:[{field:`locations`,type:`repeater`,helpText:`Where to show this action (toolbar, row menu, etc.)`},{field:`component`,helpText:`How to render (button, icon, menu item)`},{field:`visible`,widget:`textarea`,helpText:`CEL expression: show only when condition is true`},{field:`disabled`,widget:`textarea`,helpText:`CEL expression: disable when condition is true`},{field:`shortcut`,helpText:`Keyboard shortcut (e.g., "Ctrl+S", "Cmd+Enter")`}]},{label:`Advanced`,description:`Bulk operations, AI exposure, and API request shape.`,collapsible:!0,collapsed:!0,columns:2,fields:[{field:`bulkEnabled`,colSpan:1,helpText:`Allow applying to multiple selected records`},{field:`ai`,colSpan:2,helpText:`AI exposure (opt-in): set ai.exposed=true and write ai.description (≥40 chars) to make this callable by agents.`},{field:`recordIdParam`,visibleOn:`data.type == 'api'`,colSpan:1,helpText:`Body parameter name for record ID`},{field:`recordIdField`,visibleOn:`data.type == 'api' && data.recordIdParam`,colSpan:1,helpText:`Field to use as record ID (default: "id")`},{field:`bodyShape`,visibleOn:`data.type == 'api'`,colSpan:2,helpText:`Request body structure (flat or nested)`}]}]}),Cy({schemaId:`page`,type:`simple`,sections:[{label:`Basics`,description:`Page identity and template.`,columns:2,fields:[{field:`name`,required:!0,colSpan:1,helpText:`Unique identifier (snake_case)`},{field:`label`,required:!0,colSpan:1,helpText:`Page title shown to users`},{field:`icon`,widget:`icon`,colSpan:1,helpText:`Icon for navigation menu`},{field:`type`,colSpan:1,options:[{label:`List / Interface page`,value:`list`},{label:`Record page`,value:`record`},{label:`Home page`,value:`home`},{label:`App page`,value:`app`},{label:`Utility panel`,value:`utility`}],helpText:`Page kind. "List / Interface" binds a source view into a curated surface — how it looks (grid / kanban / calendar / …) is a visualization set under Interface, not a page type.`},{field:`template`,colSpan:2,visibleOn:`data.type != 'list'`,helpText:`Layout template (e.g., "header-sidebar-main")`},{field:`description`,widget:`textarea`,colSpan:2,helpText:`Page description for navigation`}]},{label:`Data Context`,description:`Record binding and page-local state.`,visibleOn:`data.type != 'list'`,fields:[{field:`object`,widget:`ref:object`,helpText:`Bound object (for Record pages)`},{field:`variables`,type:`repeater`,helpText:`Local page state variables`}]},{label:`Layout`,description:`Page regions and components placed within them.`,visibleOn:`data.type != 'list'`,fields:[{field:`regions`,type:`repeater`,helpText:`Layout regions (header, main, sidebar, footer) with components`}]},{name:`interface`,label:`Interface (list pages)`,description:`Interface mode (Airtable parity): the page defines its own data surface directly — columns, filters, visualizations and toolbar — no inheriting from a separate view.`,collapsible:!0,collapsed:!1,visibleOn:`data.type == 'list'`,fields:[{field:`interfaceConfig`,type:`composite`,helpText:`The page IS the view: source picks the object, columns/filterBy are defined directly here; appearance.allowedVisualizations whitelists renderers (one entry = locked); userActions toggles the toolbar.`,fields:[{field:`source`,widget:`ref:object`,helpText:`Object this page reads from`},{field:`columns`,widget:`field-multi`,dependsOn:`source`,helpText:`Columns to show — defined directly on the page (blank = all object fields)`},{field:`filterBy`,widget:`filter-builder`,dependsOn:`source`,helpText:`Always-on base filter for the page — same visual builder as the list toolbar.`},{field:`levels`,helpText:`Hierarchy levels to display (tree-like sources)`},{field:`appearance`,type:`composite`,disclosure:`popover`,helpText:`Allowed visualizations (Grid / Kanban / Calendar / …) and description visibility`},{field:`userFilters`,widget:`filter-mode`,helpText:`End-user filter bar: None (no bar) / Tabs (named presets) / Dropdown (per-field). None removes the config.`},{field:`userActions`,type:`composite`,disclosure:`popover`,helpText:`Toolbar toggles (search, sort, filter, row height)`},{field:`addRecord`,type:`composite`,disclosure:`popover`,helpText:`Add-record entry point`},{field:`buttons`,widget:`action-multi`,dependsOn:`source`,helpText:`Toolbar buttons — pick from this object's actions`},{field:`recordAction`,options:[{label:`Drawer (right-side peek)`,value:`drawer`},{label:`Full page`,value:`page`},{label:`Modal`,value:`modal`},{label:`Not clickable`,value:`none`}],helpText:`How clicking a record opens its detail`},{field:`showRecordCount`,helpText:`Show the record count bar`},{field:`allowPrinting`,helpText:`Allow users to print this page`}]}]},{label:`Advanced`,description:`Activation, audience, and accessibility.`,collapsible:!0,collapsed:!0,fields:[{field:`isDefault`,helpText:`Set as default page for this page type`},{field:`kind`,helpText:`Page override mode: full or slotted (for record pages)`},{field:`assignedProfiles`,widget:`string-tags`,helpText:`Profiles that can access this page`},{field:`aria`,type:`composite`,helpText:`Accessibility attributes (ARIA labels, roles)`}]}]});var sb=A([`api.read`,`api.write`,`api.transaction`,`crypto.uuid`,`crypto.hash`,`log`]),cb=D(`language`,[T({language:j(`expression`),source:v().min(1).describe(`Formula expression source`)}).describe(`L1 expression body — pure formula, no IO`),T({language:j(`js`),source:v().min(1).describe(`Function body source`),capabilities:w(sb).default([]).describe(`Granted capability tokens`),timeoutMs:y().int().positive().max(3e4).optional().describe(`Per-invocation timeout (ms)`),memoryMb:y().int().positive().max(256).optional().describe(`Per-invocation memory cap (MB)`)}).describe(`L2 sandboxed JS body — runs inside an isolated VM with declared capabilities`)]).describe(`Hook/Action body — expression (L1) or sandboxed JS (L2)`),lb=R(()=>T({name:v().optional(),field:V.optional(),objectOverride:V.optional(),label:z.optional(),type:Mv.optional(),required:b().optional().default(!1),options:w(T({label:z,value:v()})).optional(),placeholder:v().optional(),helpText:v().optional(),defaultValue:S().optional(),defaultFromRow:b().optional()}).refine(e=>!!e.name||!!e.field,{message:`ActionParam requires either "name" or "field"`})),ub=A([`script`,`url`,`modal`,`flow`,`api`,`form`]),db=new Set(ub.options.filter(e=>e!==`script`)),fb=[`list_toolbar`,`list_item`,`record_header`,`record_more`,`record_related`,`record_section`,`global_nav`],pb=A(fb),mb=A([`data`,`action`,`flow`,`integration`,`vector_search`,`analytics`,`utility`]),hb=T({exposed:b().default(!1).describe("Expose this action to AI agents. Requires `description` when true."),description:v().min(40).optional().describe(`LLM-facing description (≥40 chars). Required when exposed.`),category:mb.optional().describe(`Tool category override (defaults to "action").`),paramHints:k(v(),T({description:v().optional(),enum:w(E([v(),y()])).optional(),examples:w(S()).optional()})).optional().describe(`Per-parameter AI hints keyed by param name.`),outputSchema:k(v(),S()).optional().describe(`JSON Schema for the action return value.`),requiresConfirmation:b().optional().describe(`Override HITL confirmation for AI invocations.`)}),gb=R(()=>T({name:V.describe(`Machine name (lowercase snake_case)`),label:z.describe(`Display label`),objectName:v().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:v().optional().describe(`Icon name`),locations:w(pb).optional().describe(`Locations where this action is visible`),component:A([`action:button`,`action:icon`,`action:menu`,`action:group`]).optional().describe(`Visual component override`),type:ub.default(`script`).describe(`Action functionality type`),target:v().optional().describe("URL, Script Name, Flow ID, or API Endpoint. Supports ${param.X} and ${ctx.X} interpolation."),body:cb.optional().describe("Action body — expression (L1) or sandboxed JS (L2). Only used when type is `script`."),execute:v().optional().describe(`@deprecated — Use target instead. Auto-migrated to target during parsing.`),params:w(lb).optional().describe(`Input parameters required from user`),variant:A([`primary`,`secondary`,`danger`,`ghost`,`link`]).optional().describe(`Button visual variant for styling (primary = highlighted, danger = destructive, ghost = transparent)`),confirmText:z.optional().describe(`Confirmation message before execution`),successMessage:z.optional().describe(`Success message to show after execution`),errorMessage:z.optional().describe(`Error message to show when the action fails (overrides the raw error).`),refreshAfter:b().default(!1).describe(`Refresh view after execution`),undoable:b().optional().describe(`Offer an Undo affordance after this single-record update action succeeds.`),resultDialog:T({title:z.optional(),description:z.optional(),acknowledge:z.optional().describe(`Acknowledge button label, e.g. "I have saved this"`),format:A([`qrcode`,`code-list`,`secret`,`text`,`json`]).optional().describe(`Default format for fields without their own format. Defaults to json when omitted.`),fields:w(T({path:v().describe(`Dot path into result.data (e.g. "totpURI", "client.client_secret").`),label:z.optional(),format:A([`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:uv.optional().describe(`Visibility predicate (CEL).`),disabled:E([b(),uv]).optional().describe(`Boolean or predicate (CEL) — action is disabled when TRUE.`),requiredPermissions:w(v()).optional().describe(`[ADR-0066 D4] Capabilities required to invoke this action (server-enforced 403 + UI hide/disable).`),shortcut:v().optional().describe(`Keyboard shortcut to trigger this action (e.g., "Ctrl+S")`),bulkEnabled:b().optional().describe(`Whether this action can be applied to multiple selected records`),ai:hb.optional().describe(`AI exposure (opt-in). Set ai.exposed=true + ai.description to make this callable by agents.`),recordIdParam:v().optional().describe(`Body key to inject the row id into when running from a list_item context.`),recordIdField:v().optional().describe(`Row field whose value seeds recordIdParam. Defaults to "id".`),bodyShape:E([j(`flat`),T({wrap:v()})]).optional().describe(`Body wrapping: flat (default) or { wrap: key } to nest user-collected params under a key.`),method:A([`POST`,`PATCH`,`PUT`,`DELETE`]).optional().describe(`HTTP method for type:"api" actions. Defaults to POST.`),bodyExtra:k(v(),S()).optional().describe(`Constant body fields merged into the API request (applied last; overrides user params).`),mode:A([`create`,`edit`,`delete`,`custom`]).optional().describe(`Semantic mode of the action.`),opensInNewTab:b().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:v().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.`),timeout:y().optional().describe(`Maximum execution time in milliseconds for the action`),aria:B.optional().describe(`ARIA accessibility attributes`)}).transform(e=>e.execute&&!e.target?{...e,target:e.execute}:e).refine(e=>!(db.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.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`]}));A([`count`,`sum`,`avg`,`min`,`max`,`count_distinct`,`percentile`,`median`,`stddev`,`variance`]).describe(`Standard aggregation functions`);var _b=A([`asc`,`desc`]).describe(`Sort order direction`),vb=R(()=>T({field:v().describe(`Field name to sort by`),order:_b.describe(`Sort direction`)}).describe(`Sort field and direction pair`));A([`insert`,`update`,`delete`,`upsert`]).describe(`Data mutation event types`),A([`read_uncommitted`,`read_committed`,`repeatable_read`,`serializable`,`snapshot`]).describe(`Transaction isolation levels (snake_case standard)`),A([`lru`,`lfu`,`ttl`,`fifo`]).describe(`Cache eviction strategy`);var yb=R(()=>T({name:v().describe(`Region name (e.g. "sidebar", "main", "header")`),width:A([`small`,`medium`,`large`,`full`]).optional(),components:w(M(()=>Sb)).describe(`Components in this region`)})),bb=A(`page:header.page:footer.page:sidebar.page:tabs.page:accordion.page:card.page:section.record:details.record:highlights.record:related_list.record:activity.record:chatter.record:path.record:alert.record:quick_actions.record:reference_rail.record:history.app:launcher.nav:menu.nav:breadcrumb.global:search.global:notifications.user:profile.ai:chat_window.ai:suggestion.element:text.element:number.element:image.element:divider.element:button.element:filter.element:form.element:record_picker.element:text_input`.split(`.`)),xb=R(()=>T({object:v().describe(`Object to query`),view:v().optional().describe(`Named view to apply`),filter:Ey.optional().describe(`Additional filter criteria`),sort:w(vb).optional().describe(`Sort order`),limit:y().int().positive().optional().describe(`Max records to display`)})),Sb=R(()=>T({type:E([bb,v()]).describe(`Component Type (Standard enum or custom string)`),id:v().optional().describe(`Unique instance ID`),label:z.optional(),properties:k(v(),S()).optional().default({}).describe(`Component props passed to the widget. See component.zod.ts for schemas.`),events:k(v(),v()).optional().describe(`Event handlers map`),style:k(v(),v()).optional().describe(`Inline styles or utility classes`),className:v().optional().describe(`CSS class names`),responsiveStyles:iv.optional().describe(`Per-breakpoint scoped style maps (ADR-0065)`),visibility:uv.optional().describe(`Visibility predicate (CEL).`),dataSource:xb.optional().describe(`Per-element data binding for multi-object pages`),responsive:nv.optional().describe(`Responsive layout configuration`),aria:B.optional().describe(`ARIA accessibility attributes`)})),Cb=R(()=>T({name:v().describe("Variable name. Exposed to expressions as `page.<name>`."),type:A([`string`,`number`,`boolean`,`object`,`array`,`record_id`]).default(`string`),defaultValue:S().optional().describe(`Initial value. Defaults to a type-appropriate empty value when omitted.`),source:v().optional().describe("Component id that writes this variable (e.g. an element:record_picker whose `id` matches).")})),wb=R(()=>A([`record`,`home`,`app`,`utility`,`list`]).describe(`Page type — the page KIND. Only types with a dedicated renderer are authorizable; visualizations of a list page live in interfaceConfig, not here.`)),Tb=R(()=>T({source:v().optional().describe(`Source object name for the page`),columns:E([w(v()),w(Wv)]).optional().describe(`Columns shown by the page. Blank = all object fields. Defined directly on the page (no view inheritance).`),sort:w(vb).optional().describe(`Default sort order for the page, defined directly on the page.`),filterBy:w(Hv).optional().describe(`Always-on page filter (base filter).`),levels:y().int().min(1).optional().describe(`Number of hierarchy levels to display`),sourceView:v().optional().describe(`@deprecated Legacy named-view inheritance. Define columns/sort/filterBy on the page instead.`),appearance:ny.optional().describe(`Appearance and visualization configuration`),userFilters:ay.optional().describe(`End-user quick-filter bar for this page (overrides the source view's userFilters)`),userActions:ty.optional().describe(`User action toggles`),addRecord:oy.optional().describe(`Add record entry point configuration`),buttons:w(v()).optional().describe(`Toolbar buttons — names of the source object's actions to surface in the page toolbar`),recordAction:A([`drawer`,`page`,`modal`,`none`]).optional().describe(`How clicking a record opens its detail (drawer | page | modal | none). Default: drawer`),showRecordCount:b().optional().describe(`Show record count at page bottom`),allowPrinting:b().optional().describe(`Allow users to print the page`)}).describe(`Interface-level page configuration (Airtable parity)`)),Eb=R(()=>T({name:V.describe(`Page unique name (lowercase snake_case)`),label:z,description:z.optional(),icon:v().optional().describe(`Page icon name`),type:wb.default(`record`).describe(`Page type`),variables:w(Cb).optional().describe("Local page state, exposed to expressions as `page.<name>` and writable by interactive elements via `source` (master/detail, filtered dashboards)."),object:v().optional().describe(`Bound object (for Record pages)`),template:v().default(`default`).describe(`Layout template name (e.g. "header-sidebar-main")`),regions:w(yb).optional().default([]).describe(`Layout regions (header, main, sidebar, footer) with their components. Optional — list pages use interfaceConfig, slotted pages use slots, and an empty full page falls back to the synthesized default layout.`),isDefault:b().default(!1),assignedProfiles:w(v()).optional(),interfaceConfig:Tb.optional().describe(`Interface-level page configuration (for Airtable-style interface pages)`),aria:B.optional().describe(`ARIA accessibility attributes`),kind:A([`full`,`slotted`]).default(`full`).describe(`Page override mode: full (default) or slotted (partial overrides)`),slots:T({header:E([Sb,w(Sb)]).optional(),actions:E([Sb,w(Sb)]).optional(),alerts:E([Sb,w(Sb)]).optional(),highlights:E([Sb,w(Sb)]).optional(),details:E([Sb,w(Sb)]).optional(),tabs:E([Sb,w(Sb)]).optional(),discussion:E([Sb,w(Sb)]).optional()}).optional().describe(`Slot override map for slotted pages`)})),Db=R(()=>T({onMount:v().optional().describe(`Initialization code when widget mounts`),onUpdate:v().optional().describe(`Code to run when props change`),onUnmount:v().optional().describe(`Cleanup code when widget unmounts`),onValidate:v().optional().describe(`Custom validation logic`),onFocus:v().optional().describe(`Code to run on focus`),onBlur:v().optional().describe(`Code to run on blur`),onError:v().optional().describe(`Error handling code`)})),Ob=R(()=>T({name:v().describe(`Event name`),label:z.optional().describe(`Human-readable event label`),description:z.optional().describe(`Event description and usage`),bubbles:b().default(!1).describe(`Whether event bubbles`),cancelable:b().default(!1).describe(`Whether event is cancelable`),payload:k(v(),S()).optional().describe(`Event payload schema`)})),kb=R(()=>T({name:v().describe(`Property name (camelCase)`),label:z.optional().describe(`Human-readable label`),type:A([`string`,`number`,`boolean`,`array`,`object`,`function`,`any`]).describe(`TypeScript type`),required:b().default(!1).describe(`Whether property is required`),default:S().optional().describe(`Default value`),description:z.optional().describe(`Property description`),validation:k(v(),S()).optional().describe(`Validation rules`),category:v().optional().describe(`Property category`)})),Ab=R(()=>D(`type`,[T({type:j(`npm`),packageName:v().describe(`NPM package name`),version:v().default(`latest`),exportName:v().optional().describe(`Named export (default: default)`)}),T({type:j(`remote`),url:v().url().describe(`Remote entry URL (.js)`),moduleName:v().describe(`Exposed module name`),scope:v().describe(`Remote scope name`)}),T({type:j(`inline`),code:v().describe(`JavaScript code body`)})]));R(()=>T({name:V.describe(`Widget identifier (snake_case)`),label:z.describe(`Widget display name`),description:z.optional().describe(`Widget description`),version:v().optional().describe(`Widget version (semver)`),author:v().optional().describe(`Widget author`),icon:v().optional().describe(`Widget icon`),fieldTypes:w(v()).optional().describe(`Supported field types`),category:A([`input`,`display`,`picker`,`editor`,`custom`]).default(`custom`).describe(`Widget category`),lifecycle:Db.optional().describe(`Lifecycle hooks`),events:w(Ob).optional().describe(`Custom events`),properties:w(kb).optional().describe(`Configuration properties`),implementation:Ab.optional().describe(`Widget implementation source`),dependencies:w(T({name:v(),version:v().optional(),url:v().url().optional()})).optional().describe(`Widget dependencies`),screenshots:w(v().url()).optional().describe(`Screenshot URLs`),documentation:v().url().optional().describe(`Documentation URL`),license:v().optional().describe(`License (SPDX identifier)`),tags:w(v()).optional().describe(`Tags for categorization`),aria:B.optional().describe(`ARIA accessibility attributes`),performance:av.optional().describe(`Performance optimization settings`)})),R(()=>T({value:S().describe(`Current field value`),onChange:P().input(O([S()])).output(gl()).describe(`Callback to update field value`),readonly:b().default(!1).describe(`Read-only mode flag`),required:b().default(!1).describe(`Required field flag`),error:v().optional().describe(`Validation error message`),field:Lv.describe(`Field schema definition`),record:k(v(),S()).optional().describe(`Complete record data`),options:k(v(),S()).optional().describe(`Custom widget options`)}));var jb=A([`comment`,`field_change`,`task`,`event`,`email`,`call`,`note`,`file`,`record_create`,`record_delete`,`approval`,`sharing`,`system`]),Mb=R(()=>T({type:A([`user`,`team`,`record`]).describe(`Mention target type`),id:v().describe(`Target ID`),name:v().describe(`Display name for rendering`),offset:y().int().min(0).describe(`Character offset in body text`),length:y().int().min(1).describe(`Length of mention token in body text`)})),Nb=R(()=>T({field:v().describe(`Field machine name`),fieldLabel:v().optional().describe(`Field display label`),oldValue:S().optional().describe(`Previous value`),newValue:S().optional().describe(`New value`),oldDisplayValue:v().optional().describe(`Human-readable old value`),newDisplayValue:v().optional().describe(`Human-readable new value`)})),Pb=R(()=>T({emoji:v().describe(`Emoji character or shortcode (e.g., "👍", ":thumbsup:")`),userIds:w(v()).describe(`Users who reacted`),count:y().int().min(1).describe(`Total reaction count`)})),Fb=R(()=>T({type:A([`user`,`system`,`service`,`automation`]).describe(`Actor type`),id:v().describe(`Actor ID`),name:v().optional().describe(`Actor display name`),avatarUrl:v().url().optional().describe(`Actor avatar URL`),source:v().optional().describe(`Source application (e.g., "Omni", "API", "Studio")`)})),Ib=A([`public`,`internal`,`private`]);R(()=>T({id:v().describe(`Feed item ID`),type:jb.describe(`Activity type`),object:v().describe(`Object name (e.g., "account")`),recordId:v().describe(`Record ID this feed item belongs to`),actor:Fb.describe(`Who performed this action`),body:v().optional().describe(`Rich text body (Markdown supported)`),mentions:w(Mb).optional().describe(`Mentioned users/teams/records`),changes:w(Nb).optional().describe(`Field-level changes`),reactions:w(Pb).optional().describe(`Emoji reactions on this item`),parentId:v().optional().describe(`Parent feed item ID for threaded replies`),replyCount:y().int().min(0).default(0).describe(`Number of replies`),pinned:b().default(!1).describe(`Whether the feed item is pinned to the top of the timeline`),pinnedAt:v().datetime().optional().describe(`Timestamp when the item was pinned`),pinnedBy:v().optional().describe(`User ID who pinned the item`),starred:b().default(!1).describe(`Whether the feed item is starred/bookmarked by the current user`),starredAt:v().datetime().optional().describe(`Timestamp when the item was starred`),visibility:Ib.default(`public`).describe(`Visibility: public (all users), internal (team only), private (author + mentioned)`),createdAt:v().datetime().describe(`Creation timestamp`),updatedAt:v().datetime().optional().describe(`Last update timestamp`),editedAt:v().datetime().optional().describe(`When comment was last edited`),isEdited:b().default(!1).describe(`Whether comment has been edited`)}));var Lb=A([`all`,`comments_only`,`changes_only`,`tasks_only`]);T({});var Rb=T({title:z.describe(`Page title`),subtitle:z.optional().describe(`Page subtitle`),icon:v().optional().describe(`Icon name`),breadcrumb:b().default(!0).describe(`Show breadcrumb`),actions:w(v()).optional().describe(`Action IDs to show in header`),aria:B.optional().describe(`ARIA accessibility attributes`)}),zb=T({type:A([`line`,`card`,`pill`]).default(`line`),position:A([`top`,`left`]).default(`top`),items:w(T({label:z,icon:v().optional(),children:w(S()).describe(`Child components`)})),aria:B.optional().describe(`ARIA accessibility attributes`)}),Bb=T({title:z.optional(),bordered:b().default(!0),actions:w(v()).optional(),body:w(S()).optional().describe(`Card content components (slot)`),footer:w(S()).optional().describe(`Card footer components (slot)`),aria:B.optional().describe(`ARIA accessibility attributes`)}),Vb=T({columns:A([`1`,`2`,`3`,`4`]).default(`2`).describe(`Number of columns for field layout (1-4)`),layout:A([`auto`,`custom`]).default(`auto`).describe(`Layout mode: auto uses object compactLayout, custom uses explicit sections`),sections:w(v()).optional().describe(`Section IDs to show (required when layout is "custom")`),fields:w(v()).optional().describe(`Explicit field list to display (optional, overrides compactLayout)`),aria:B.optional().describe(`ARIA accessibility attributes`)}),Hb=T({objectName:v().describe(`Related object name (e.g., "task", "opportunity")`),relationshipField:v().describe(`Field on related object that points to this record (e.g., "account_id")`),columns:w(v()).describe(`Fields to display in the related list`),sort:E([v(),w(T({field:v(),order:A([`asc`,`desc`])}))]).optional().describe(`Sort order for related records`),limit:y().int().positive().default(5).describe(`Number of records to display initially`),filter:w(Hv).optional().describe(`Additional filter criteria for related records`),title:z.optional().describe(`Custom title for the related list`),showViewAll:b().default(!0).describe(`Show "View All" link to see all related records`),actions:w(v()).optional().describe(`Action IDs available for related records`),add:T({picker:T({object:v().describe(`Object to pick records from (the far side of an m2m, or the child object for a 1:m re-parent).`),valueField:v().default(`id`).describe("Field on the picked record used as the link value (default `id`)."),labelField:v().optional().describe(`Field shown in the picker rows (defaults to the object title field).`),filter:w(Hv).optional().describe(`Restrict which records the picker offers.`)}).describe(`Where the Add affordance sources records from.`),linkField:v().optional().describe("Field on `objectName` that stores the picked record id (junction case). Omit for a 1:m re-parent."),label:z.optional().describe(`Label for the Add button (default "Add").`)}).optional().describe(`Add-existing-via-picker config (generic m2m/junction assignment).`),aria:B.optional().describe(`ARIA accessibility attributes`)}),Ub=E([v(),T({name:v().describe(`Field name on the record`),label:v().optional().describe(`Display label (overrides schema label)`),icon:v().optional().describe(`Icon name (lucide icon key)`),type:v().optional().describe(`Override cell renderer type (rare)`)})]).describe(`Highlight field: bare name, or {name,label?,icon?,type?}`),Wb=T({fields:w(Ub).min(1).max(7).describe(`Key fields to highlight (1-7 fields max, typically displayed as prominent cards). Each item may be a bare field name or {name, label?, icon?, type?} for inline overrides.`),layout:A([`horizontal`,`vertical`]).default(`horizontal`).describe(`Layout orientation for highlight fields`),aria:B.optional().describe(`ARIA accessibility attributes`)}),Gb=T({types:w(jb).optional().describe(`Feed item types to show (default: all)`),filterMode:Lb.default(`all`).describe(`Default activity filter`),showFilterToggle:b().default(!0).describe(`Show filter dropdown in panel header`),limit:y().int().positive().default(20).describe(`Number of items to load per page`),showCompleted:b().default(!1).describe(`Include completed activities`),unifiedTimeline:b().default(!0).describe(`Mix field changes and comments in one timeline (Airtable style)`),showCommentInput:b().default(!0).describe(`Show "Leave a comment" input at the bottom`),enableMentions:b().default(!0).describe(`Enable @mentions in comments`),enableReactions:b().default(!1).describe(`Enable emoji reactions on feed items`),enableThreading:b().default(!1).describe(`Enable threaded replies on comments`),showSubscriptionToggle:b().default(!0).describe(`Show bell icon for record-level notification subscription`),aria:B.optional().describe(`ARIA accessibility attributes`)}),Kb=T({position:A([`sidebar`,`inline`,`drawer`]).default(`sidebar`).describe(`Where to render the chatter panel`),width:E([v(),y()]).optional().describe(`Panel width (e.g., "350px", "30%")`),collapsible:b().default(!0).describe(`Whether the panel can be collapsed`),defaultCollapsed:b().default(!1).describe(`Whether the panel starts collapsed`),feed:Gb.optional().describe(`Embedded activity feed configuration`),aria:B.optional().describe(`ARIA accessibility attributes`)}),qb=T({statusField:v().describe(`Field name representing the current status/stage`),stages:w(T({value:v(),label:z})).optional().describe(`Explicit stage definitions (if not using field metadata)`),aria:B.optional().describe(`ARIA accessibility attributes`)}),Jb=T({items:w(T({label:z,icon:v().optional(),collapsed:b().default(!1),children:w(S()).describe(`Child components`)})),allowMultiple:b().default(!1).describe(`Allow multiple panels to be expanded simultaneously`),aria:B.optional().describe(`ARIA accessibility attributes`)}),Yb=T({mode:A([`float`,`sidebar`,`inline`]).default(`float`).describe(`Display mode for the chat window`),agentId:v().optional().describe(`Specific AI agent to use`),context:k(v(),S()).optional().describe(`Contextual data to pass to the AI`),aria:B.optional().describe(`ARIA accessibility attributes`)}),Xb=R(()=>T({content:v().describe(`Text or Markdown content`),variant:A([`heading`,`subheading`,`body`,`caption`]).optional().default(`body`).describe(`Text style variant`),align:A([`left`,`center`,`right`]).optional().default(`left`).describe(`Text alignment`),aria:B.optional().describe(`ARIA accessibility attributes`)})),Zb=R(()=>T({object:v().describe(`Source object`),field:v().optional().describe(`Field to aggregate`),aggregate:A([`count`,`sum`,`avg`,`min`,`max`]).describe(`Aggregation function`),filter:Ey.optional().describe(`Filter criteria`),format:A([`number`,`currency`,`percent`]).optional().describe(`Number display format`),prefix:v().optional().describe(`Prefix text (e.g. "$")`),suffix:v().optional().describe(`Suffix text (e.g. "%")`),aria:B.optional().describe(`ARIA accessibility attributes`)})),Qb=R(()=>T({src:v().describe(`Image URL or attachment field`),alt:v().optional().describe(`Alt text for accessibility`),fit:A([`cover`,`contain`,`fill`]).optional().default(`cover`).describe(`Image object-fit mode`),height:y().optional().describe(`Fixed height in pixels`),aria:B.optional().describe(`ARIA accessibility attributes`)})),$b=R(()=>T({type:A([`state_machine`,`flow`,`permission`]).describe(`Metadata view kind (ADR-0051): state_machine | flow | permission`),name:v().describe(`Target metadata item name; resolved package-scoped (ADR-0048), then dependencies (ADR-0046 §3.3)`),object:v().optional().describe(`Owning object — required for object-scoped kinds: state_machine is a rule ON an object (ADR-0020), permission renders a matrix FOR one; omit for top-level flow`),mode:A([`diagram`,`matrix`,`summary`]).optional().describe(`Render form; defaults per type (diagram for flow/state_machine, matrix for permission)`),detail:A([`business`,`technical`]).optional().default(`business`).describe(`Authoring altitude (ADR-0051 §3.4): business collapses technical flow nodes to business steps + approvals. NOT access (cf. book.audience); permission projection is automatic and render-time, never set here`),aria:B.optional().describe(`ARIA accessibility attributes`)})),ex=R(()=>T({label:z.describe(`Button display label`),variant:A([`primary`,`secondary`,`danger`,`ghost`,`link`]).optional().default(`primary`).describe(`Button visual variant`),size:A([`small`,`medium`,`large`]).optional().default(`medium`).describe(`Button size`),icon:v().optional().describe(`Icon name (Lucide icon)`),iconPosition:A([`left`,`right`]).optional().default(`left`).describe(`Icon position relative to label`),disabled:b().optional().default(!1).describe(`Disable the button`),aria:B.optional().describe(`ARIA accessibility attributes`)})),tx=R(()=>T({object:v().describe(`Object to filter`),fields:w(v()).describe(`Filterable field names`),targetVariable:v().optional().describe(`Page variable to store filter state`),layout:A([`inline`,`dropdown`,`sidebar`]).optional().default(`inline`).describe(`Filter display layout`),showSearch:b().optional().default(!0).describe(`Show search input`),aria:B.optional().describe(`ARIA accessibility attributes`)})),nx=R(()=>T({object:v().describe(`Object for the form`),fields:w(v()).optional().describe(`Fields to display (defaults to all editable fields)`),mode:A([`create`,`edit`]).optional().default(`create`).describe(`Form mode`),submitLabel:z.optional().describe(`Submit button label`),onSubmit:uv.optional().describe(`Action expression on form submit (CEL)`),aria:B.optional().describe(`ARIA accessibility attributes`)})),rx=R(()=>T({object:v().describe(`Object to pick records from`),displayField:v().describe(`Field to display as the record label`),searchFields:w(v()).optional().describe(`Fields to search against`),filter:Ey.optional().describe(`Filter criteria for available records`),multiple:b().optional().default(!1).describe(`Allow multiple record selection`),targetVariable:v().optional().describe(`Page variable to bind selected record ID(s)`),placeholder:z.optional().describe(`Placeholder text`),aria:B.optional().describe(`ARIA accessibility attributes`)})),ix=R(()=>T({inputType:A([`text`,`email`,`number`,`tel`,`url`,`password`]).optional().default(`text`).describe(`Native input type — drives keyboard/validation affordance and how the bound value is coerced (number → numeric).`),label:z.optional().describe(`Field label shown above the input`),placeholder:z.optional().describe(`Placeholder text shown when empty`),defaultValue:E([v(),y()]).optional().describe(`Initial value; seeds the bound page variable on mount`),required:b().optional().default(!1).describe(`Mark the field as required`),disabled:b().optional().default(!1).describe(`Disable the input`),description:z.optional().describe(`Helper text shown below the input`),targetVariable:v().optional().describe("Page variable this input writes to. Declarative hint; the live binding resolves via the variable whose `source` equals this component id (see PageVariableSchema)."),aria:B.optional().describe(`ARIA accessibility attributes`)}));T({context:v().optional()});var ax=R(()=>T({minWidth:y().default(44).describe(`Minimum touch target width in pixels (WCAG 2.5.5: 44px)`),minHeight:y().default(44).describe(`Minimum touch target height in pixels (WCAG 2.5.5: 44px)`),padding:y().optional().describe(`Additional padding around touch target in pixels`),hitSlop:T({top:y().optional().describe(`Extra hit area above the element`),right:y().optional().describe(`Extra hit area to the right of the element`),bottom:y().optional().describe(`Extra hit area below the element`),left:y().optional().describe(`Extra hit area to the left of the element`)}).optional().describe(`Invisible hit area extension beyond the visible bounds`)}).describe(`Touch target sizing configuration (WCAG accessible)`)),ox=R(()=>A([`swipe`,`pinch`,`long_press`,`double_tap`,`drag`,`rotate`,`pan`]).describe(`Touch gesture type`)),sx=R(()=>A([`up`,`down`,`left`,`right`])),cx=R(()=>T({direction:w(sx).describe(`Allowed swipe directions`),threshold:y().optional().describe(`Minimum distance in pixels to recognize swipe`),velocity:y().optional().describe(`Minimum velocity (px/ms) to trigger swipe`)}).describe(`Swipe gesture recognition settings`)),lx=R(()=>T({minScale:y().optional().describe(`Minimum scale factor (e.g., 0.5 for 50%)`),maxScale:y().optional().describe(`Maximum scale factor (e.g., 3.0 for 300%)`)}).describe(`Pinch/zoom gesture recognition settings`)),ux=R(()=>T({duration:y().default(500).describe(`Hold duration in milliseconds to trigger long press`),moveTolerance:y().optional().describe(`Max movement in pixels allowed during press`)}).describe(`Long press gesture recognition settings`)),dx=R(()=>T({type:ox.describe(`Gesture type to configure`),label:z.optional().describe(`Descriptive label for the gesture action`),enabled:b().default(!0).describe(`Whether this gesture is active`),swipe:cx.optional().describe(`Swipe gesture settings (when type is swipe)`),pinch:lx.optional().describe(`Pinch gesture settings (when type is pinch)`),longPress:ux.optional().describe(`Long press settings (when type is long_press)`)}).describe(`Per-gesture configuration`));R(()=>T({gestures:w(dx).optional().describe(`Configured gesture recognizers`),touchTarget:ax.optional().describe(`Touch target sizing and hit area`),hapticFeedback:b().optional().describe(`Enable haptic feedback on touch interactions`)}).merge(B.partial()).describe(`Touch and gesture interaction configuration`));var fx=R(()=>T({enabled:b().default(!1).describe(`Enable focus trapping within this container`),initialFocus:v().optional().describe(`CSS selector for the element to focus on activation`),returnFocus:b().default(!0).describe(`Return focus to trigger element on deactivation`),escapeDeactivates:b().default(!0).describe(`Allow Escape key to deactivate the focus trap`)}).describe(`Focus trap configuration for modal-like containers`)),px=R(()=>T({key:v().describe(`Key combination (e.g., "Ctrl+S", "Alt+N", "Escape")`),action:v().describe(`Action identifier to invoke when shortcut is triggered`),description:z.optional().describe(`Human-readable description of what the shortcut does`),scope:A([`global`,`view`,`form`,`modal`,`list`]).default(`global`).describe(`Scope in which this shortcut is active`)}).describe(`Keyboard shortcut binding`)),mx=R(()=>T({tabOrder:A([`auto`,`manual`]).default(`auto`).describe(`Tab order strategy: auto (DOM order) or manual (explicit tabIndex)`),skipLinks:b().default(!1).describe(`Provide skip-to-content navigation links`),focusVisible:b().default(!0).describe(`Show visible focus indicators for keyboard users`),focusTrap:fx.optional().describe(`Focus trap settings`),arrowNavigation:b().default(!1).describe(`Enable arrow key navigation between focusable items`)}).describe(`Focus and tab navigation management`));R(()=>T({shortcuts:w(px).optional().describe(`Registered keyboard shortcuts`),focusManagement:mx.optional().describe(`Focus and tab order management`),rovingTabindex:b().default(!1).describe(`Enable roving tabindex pattern for composite widgets`)}).merge(B.partial()).describe(`Keyboard navigation and shortcut configuration`));var hx=R(()=>T({primary:v().describe(`Primary brand color (hex, rgb, or hsl)`),secondary:v().optional().describe(`Secondary brand color`),accent:v().optional().describe(`Accent color for highlights`),success:v().optional().describe(`Success state color (default: green)`),warning:v().optional().describe(`Warning state color (default: yellow)`),error:v().optional().describe(`Error state color (default: red)`),info:v().optional().describe(`Info state color (default: blue)`),background:v().optional().describe(`Background color`),surface:v().optional().describe(`Surface/card background color`),text:v().optional().describe(`Primary text color`),textSecondary:v().optional().describe(`Secondary text color`),border:v().optional().describe(`Border color`),disabled:v().optional().describe(`Disabled state color`),primaryLight:v().optional().describe(`Lighter shade of primary`),primaryDark:v().optional().describe(`Darker shade of primary`),secondaryLight:v().optional().describe(`Lighter shade of secondary`),secondaryDark:v().optional().describe(`Darker shade of secondary`)})),gx=R(()=>T({fontFamily:T({base:v().optional().describe(`Base font family (default: system fonts)`),heading:v().optional().describe(`Heading font family`),mono:v().optional().describe(`Monospace font family for code`)}).optional(),fontSize:T({xs:v().optional().describe(`Extra small font size (e.g., 0.75rem)`),sm:v().optional().describe(`Small font size (e.g., 0.875rem)`),base:v().optional().describe(`Base font size (e.g., 1rem)`),lg:v().optional().describe(`Large font size (e.g., 1.125rem)`),xl:v().optional().describe(`Extra large font size (e.g., 1.25rem)`),"2xl":v().optional().describe(`2X large font size (e.g., 1.5rem)`),"3xl":v().optional().describe(`3X large font size (e.g., 1.875rem)`),"4xl":v().optional().describe(`4X large font size (e.g., 2.25rem)`)}).optional(),fontWeight:T({light:y().optional().describe(`Light weight (default: 300)`),normal:y().optional().describe(`Normal weight (default: 400)`),medium:y().optional().describe(`Medium weight (default: 500)`),semibold:y().optional().describe(`Semibold weight (default: 600)`),bold:y().optional().describe(`Bold weight (default: 700)`)}).optional(),lineHeight:T({tight:v().optional().describe(`Tight line height (e.g., 1.25)`),normal:v().optional().describe(`Normal line height (e.g., 1.5)`),relaxed:v().optional().describe(`Relaxed line height (e.g., 1.75)`),loose:v().optional().describe(`Loose line height (e.g., 2)`)}).optional(),letterSpacing:T({tighter:v().optional().describe(`Tighter letter spacing (e.g., -0.05em)`),tight:v().optional().describe(`Tight letter spacing (e.g., -0.025em)`),normal:v().optional().describe(`Normal letter spacing (e.g., 0)`),wide:v().optional().describe(`Wide letter spacing (e.g., 0.025em)`),wider:v().optional().describe(`Wider letter spacing (e.g., 0.05em)`)}).optional()})),_x=R(()=>T({0:v().optional().describe(`0 spacing (0)`),1:v().optional().describe(`Spacing unit 1 (e.g., 0.25rem)`),2:v().optional().describe(`Spacing unit 2 (e.g., 0.5rem)`),3:v().optional().describe(`Spacing unit 3 (e.g., 0.75rem)`),4:v().optional().describe(`Spacing unit 4 (e.g., 1rem)`),5:v().optional().describe(`Spacing unit 5 (e.g., 1.25rem)`),6:v().optional().describe(`Spacing unit 6 (e.g., 1.5rem)`),8:v().optional().describe(`Spacing unit 8 (e.g., 2rem)`),10:v().optional().describe(`Spacing unit 10 (e.g., 2.5rem)`),12:v().optional().describe(`Spacing unit 12 (e.g., 3rem)`),16:v().optional().describe(`Spacing unit 16 (e.g., 4rem)`),20:v().optional().describe(`Spacing unit 20 (e.g., 5rem)`),24:v().optional().describe(`Spacing unit 24 (e.g., 6rem)`)})),vx=R(()=>T({none:v().optional().describe(`No border radius (0)`),sm:v().optional().describe(`Small border radius (e.g., 0.125rem)`),base:v().optional().describe(`Base border radius (e.g., 0.25rem)`),md:v().optional().describe(`Medium border radius (e.g., 0.375rem)`),lg:v().optional().describe(`Large border radius (e.g., 0.5rem)`),xl:v().optional().describe(`Extra large border radius (e.g., 0.75rem)`),"2xl":v().optional().describe(`2X large border radius (e.g., 1rem)`),full:v().optional().describe(`Full border radius (50%)`)})),yx=R(()=>T({none:v().optional().describe(`No shadow`),sm:v().optional().describe(`Small shadow`),base:v().optional().describe(`Base shadow`),md:v().optional().describe(`Medium shadow`),lg:v().optional().describe(`Large shadow`),xl:v().optional().describe(`Extra large shadow`),"2xl":v().optional().describe(`2X large shadow`),inner:v().optional().describe(`Inner shadow (inset)`)})),bx=R(()=>T({xs:v().optional().describe(`Extra small breakpoint (e.g., 480px)`),sm:v().optional().describe(`Small breakpoint (e.g., 640px)`),md:v().optional().describe(`Medium breakpoint (e.g., 768px)`),lg:v().optional().describe(`Large breakpoint (e.g., 1024px)`),xl:v().optional().describe(`Extra large breakpoint (e.g., 1280px)`),"2xl":v().optional().describe(`2X large breakpoint (e.g., 1536px)`)})),xx=R(()=>T({duration:T({fast:v().optional().describe(`Fast animation (e.g., 150ms)`),base:v().optional().describe(`Base animation (e.g., 300ms)`),slow:v().optional().describe(`Slow animation (e.g., 500ms)`)}).optional(),timing:T({linear:v().optional().describe(`Linear timing function`),ease:v().optional().describe(`Ease timing function`),ease_in:v().optional().describe(`Ease-in timing function`),ease_out:v().optional().describe(`Ease-out timing function`),ease_in_out:v().optional().describe(`Ease-in-out timing function`)}).optional()})),Sx=R(()=>T({base:y().optional().describe(`Base z-index (e.g., 0)`),dropdown:y().optional().describe(`Dropdown z-index (e.g., 1000)`),sticky:y().optional().describe(`Sticky z-index (e.g., 1020)`),fixed:y().optional().describe(`Fixed z-index (e.g., 1030)`),modalBackdrop:y().optional().describe(`Modal backdrop z-index (e.g., 1040)`),modal:y().optional().describe(`Modal z-index (e.g., 1050)`),popover:y().optional().describe(`Popover z-index (e.g., 1060)`),tooltip:y().optional().describe(`Tooltip z-index (e.g., 1070)`)})),Cx=R(()=>A([`light`,`dark`,`auto`])),wx=R(()=>A([`compact`,`regular`,`spacious`])),Tx=R(()=>A([`AA`,`AAA`])),Ex=R(()=>T({name:V.describe(`Unique theme identifier (snake_case)`),label:v().describe(`Human-readable theme name`),description:v().optional().describe(`Theme description`),mode:Cx.default(`light`).describe(`Theme mode (light, dark, or auto)`),colors:hx.describe(`Color palette configuration`),typography:gx.optional().describe(`Typography settings`),spacing:_x.optional().describe(`Spacing scale`),borderRadius:vx.optional().describe(`Border radius scale`),shadows:yx.optional().describe(`Box shadow effects`),breakpoints:bx.optional().describe(`Responsive breakpoints`),animation:xx.optional().describe(`Animation settings`),zIndex:Sx.optional().describe(`Z-index scale for layering`),customVars:k(v(),v()).optional().describe(`Custom CSS variables (key-value pairs)`),logo:T({light:v().optional().describe(`Logo URL for light mode`),dark:v().optional().describe(`Logo URL for dark mode`),favicon:v().optional().describe(`Favicon URL`)}).optional().describe(`Logo assets`),extends:v().optional().describe(`Base theme to extend from`),density:wx.optional().describe(`Display density: compact, regular, or spacious`),wcagContrast:Tx.optional().describe(`WCAG color contrast level (AA or AAA)`),rtl:b().optional().describe(`Enable right-to-left layout direction`),touchTarget:ax.optional().describe(`Touch target sizing defaults`),keyboardNavigation:mx.optional().describe(`Keyboard focus management settings`)})),Dx=R(()=>A([`cache_first`,`network_first`,`stale_while_revalidate`,`network_only`,`cache_only`]).describe(`Data fetching strategy for offline/online transitions`)),Ox=R(()=>A([`client_wins`,`server_wins`,`manual`,`last_write_wins`]).describe(`How to resolve conflicts when syncing offline changes`)),kx=R(()=>T({strategy:Dx.default(`network_first`).describe(`Sync fetch strategy`),conflictResolution:Ox.default(`last_write_wins`).describe(`Conflict resolution policy`),retryInterval:y().optional().describe(`Retry interval in milliseconds between sync attempts`),maxRetries:y().optional().describe(`Maximum number of sync retry attempts`),batchSize:y().optional().describe(`Number of mutations to sync per batch`)}).describe(`Offline-to-online synchronization configuration`)),Ax=R(()=>A([`indexeddb`,`localstorage`,`sqlite`]).describe(`Client-side storage backend for offline cache`)),jx=R(()=>A([`lru`,`lfu`,`fifo`]).describe(`Cache eviction policy`)),Mx=R(()=>T({maxSize:y().optional().describe(`Maximum cache size in bytes`),ttl:y().optional().describe(`Time-to-live for cached entries in milliseconds`),persistStorage:Ax.default(`indexeddb`).describe(`Storage backend`),evictionPolicy:jx.default(`lru`).describe(`Cache eviction policy when full`)}).describe(`Client-side offline cache configuration`));R(()=>T({enabled:b().default(!1).describe(`Enable offline support`),strategy:Dx.default(`network_first`).describe(`Default offline fetch strategy`),cache:Mx.optional().describe(`Cache settings for offline data`),sync:kx.optional().describe(`Sync settings for offline mutations`),offlineIndicator:b().default(!0).describe(`Show a visual indicator when offline`),offlineMessage:z.optional().describe(`Customizable offline status message shown to users`),queueMaxSize:y().optional().describe(`Maximum number of queued offline mutations`)}).describe(`Offline support configuration`));var Nx=R(()=>A([`fade`,`slide_up`,`slide_down`,`slide_left`,`slide_right`,`scale`,`rotate`,`flip`,`none`]).describe(`Transition preset type`)),Px=R(()=>A([`linear`,`ease`,`ease_in`,`ease_out`,`ease_in_out`,`spring`]).describe(`Animation easing function`)),Fx=R(()=>T({preset:Nx.optional().describe(`Transition preset to apply`),duration:y().optional().describe(`Transition duration in milliseconds`),easing:Px.optional().describe(`Easing function for the transition`),delay:y().optional().describe(`Delay before transition starts in milliseconds`),customKeyframes:v().optional().describe(`CSS @keyframes name for custom animations`),themeToken:v().optional().describe(`Reference to a theme animation token (e.g. "animation.duration.fast")`)}).describe(`Animation transition configuration`)),Ix=R(()=>A([`on_mount`,`on_unmount`,`on_hover`,`on_focus`,`on_click`,`on_scroll`,`on_visible`]).describe(`Event that triggers the animation`)),Lx=R(()=>T({label:z.optional().describe(`Descriptive label for this animation configuration`),enter:Fx.optional().describe(`Enter/mount animation`),exit:Fx.optional().describe(`Exit/unmount animation`),hover:Fx.optional().describe(`Hover state animation`),trigger:Ix.optional().describe(`When to trigger the animation`),reducedMotion:A([`respect`,`disable`,`alternative`]).default(`respect`).describe(`Accessibility: how to handle prefers-reduced-motion`)}).merge(B.partial()).describe(`Component-level animation configuration`)),Rx=R(()=>T({type:Nx.default(`fade`).describe(`Page transition type`),duration:y().default(300).describe(`Transition duration in milliseconds`),easing:Px.default(`ease_in_out`).describe(`Easing function for the transition`),crossFade:b().default(!1).describe(`Whether to cross-fade between pages`)}).describe(`Page-level transition configuration`));R(()=>T({label:z.optional().describe(`Descriptive label for the motion configuration`),defaultTransition:Fx.optional().describe(`Default transition applied to all animations`),pageTransitions:Rx.optional().describe(`Page navigation transition settings`),componentAnimations:k(v(),Lx).optional().describe(`Component name to animation configuration mapping`),reducedMotion:b().default(!1).describe(`When true, respect prefers-reduced-motion and suppress animations globally`),enabled:b().default(!0).describe(`Enable or disable all animations globally`)}).describe(`Top-level motion and animation design configuration`));var zx=R(()=>A([`toast`,`snackbar`,`banner`,`alert`,`inline`]).describe(`Notification presentation style`)),Bx=R(()=>A([`info`,`success`,`warning`,`error`]).describe(`Notification severity level`)),Vx=R(()=>A([`top_left`,`top_center`,`top_right`,`bottom_left`,`bottom_center`,`bottom_right`]).describe(`Screen position for notification placement`)),Hx=R(()=>T({label:z.describe(`Action button label`),action:v().describe(`Action identifier to execute`),variant:A([`primary`,`secondary`,`link`]).default(`primary`).describe(`Button variant style`)}).describe(`Notification action button`));R(()=>T({type:zx.default(`toast`).describe(`Notification presentation style`),severity:Bx.default(`info`).describe(`Notification severity level`),title:z.optional().describe(`Notification title`),message:z.describe(`Notification message body`),icon:v().optional().describe(`Icon name override`),duration:y().optional().describe(`Auto-dismiss duration in ms, omit for persistent`),dismissible:b().default(!0).describe(`Allow user to dismiss the notification`),actions:w(Hx).optional().describe(`Action buttons`),position:Vx.optional().describe(`Override default position`)}).merge(B.partial()).describe(`Notification instance definition`)),R(()=>T({defaultPosition:Vx.default(`top_right`).describe(`Default screen position for notifications`),defaultDuration:y().default(5e3).describe(`Default auto-dismiss duration in ms`),maxVisible:y().default(5).describe(`Maximum number of notifications visible at once`),stackDirection:A([`up`,`down`]).default(`down`).describe(`Stack direction for multiple notifications`),pauseOnHover:b().default(!0).describe(`Pause auto-dismiss timer on hover`)}).describe(`Global notification system configuration`));var Ux=R(()=>A([`element`,`handle`,`grip_icon`]).describe(`Drag initiation method`)),Wx=R(()=>A([`move`,`copy`,`link`,`none`]).describe(`Drop operation effect`)),Gx=R(()=>T({axis:A([`x`,`y`,`both`]).default(`both`).describe(`Constrain drag axis`),bounds:A([`parent`,`viewport`,`none`]).default(`none`).describe(`Constrain within bounds`),grid:O([y(),y()]).optional().describe(`Snap to grid [x, y] in pixels`)}).describe(`Drag movement constraints`)),Kx=R(()=>T({label:z.optional().describe(`Accessible label for the drop zone`),accept:w(v()).describe(`Accepted drag item types`),maxItems:y().optional().describe(`Maximum items allowed in drop zone`),highlightOnDragOver:b().default(!0).describe(`Highlight drop zone when dragging over`),dropEffect:Wx.default(`move`).describe(`Visual effect on drop`)}).merge(B.partial()).describe(`Drop zone configuration`)),qx=R(()=>T({type:v().describe(`Drag item type identifier for matching with drop zones`),label:z.optional().describe(`Accessible label describing the draggable item`),handle:Ux.default(`element`).describe(`How to initiate drag`),constraint:Gx.optional().describe(`Drag movement constraints`),preview:A([`element`,`custom`,`none`]).default(`element`).describe(`Drag preview type`),disabled:b().default(!1).describe(`Disable dragging`)}).merge(B.partial()).describe(`Draggable item configuration`));R(()=>T({enabled:b().default(!1).describe(`Enable drag and drop`),dragItem:qx.optional().describe(`Configuration for draggable item`),dropZone:Kx.optional().describe(`Configuration for drop target`),sortable:b().default(!1).describe(`Enable sortable list behavior`),autoScroll:b().default(!0).describe(`Auto-scroll during drag near edges`),touchDelay:y().default(200).describe(`Delay in ms before drag starts on touch devices`)}).describe(`Drag and drop interaction configuration`));var Jx=R(()=>T({primaryColor:v().optional().describe(`Primary brand color (hex, rgb, hsl). Mapped to --portal-primary.`),accentColor:v().optional().describe(`Accent color used for highlights and CTAs.`),backgroundColor:v().optional().describe(`Page background color.`),surfaceColor:v().optional().describe(`Card / surface background color.`),textColor:v().optional().describe(`Primary text color.`),logoUrl:v().optional().describe(`Absolute or relative URL to the portal header logo (SVG or PNG).`),faviconUrl:v().optional().describe(`Absolute or relative URL to the portal favicon.`),fontFamily:v().optional().describe(`CSS font-family stack for the portal.`),customCss:v().optional().describe(`OPTIONAL escape hatch: raw CSS appended last. Discouraged; prefer tokens.`)})),Yx=T({id:V.describe(`Unique identifier for this portal nav item (lowercase snake_case).`),label:z.describe(`Display label.`),icon:v().optional().describe(`Icon name (Lucide).`),order:y().optional().describe(`Sort order; lower appears first.`),badge:E([v(),y()]).optional().describe(`Optional badge (e.g. unread count).`)}),Xx=Yx.extend({type:j(`view`),viewRef:v().describe(`Reference to an existing view, e.g. "helpdesk_ticket.list.my_tickets".`)}),Zx=Yx.extend({type:j(`action`),actionRef:v().describe(`Reference to an existing action, e.g. "helpdesk_ticket.create".`)}),Qx=Yx.extend({type:j(`dashboard`),dashboardName:V.describe(`Existing dashboard id.`)}),$x=Yx.extend({type:j(`url`),url:v().describe(`Absolute or root-relative URL.`),target:A([`_self`,`_blank`]).optional().default(`_self`)}),eS=D(`type`,[Xx,Zx,Qx,$x]),tS=R(()=>T({rule:v().describe(`Rate-limit rule string, e.g. "5/hour/ip", "100/day/tenant".`),scope:A([`ip`,`tenant`,`route`]).default(`ip`).describe(`Counter scope. "ip" buckets per requester; "tenant" per portal owner; "route" global per route.`)})),nS=R(()=>T({path:v().describe(`Path within the portal, e.g. "/submit" or "/kb".`),viewRef:v().optional().describe(`Reference to a public view (read-only).`),actionRef:v().optional().describe(`Reference to an action to perform anonymously (mutation).`),rateLimit:tS.optional().describe(`Rate-limit for anonymous traffic on this route.`),captcha:b().optional().default(!1).describe(`Require CAPTCHA / proof-of-work challenge before invoking.`),bindIdentityFromField:v().optional().describe(`Field name on the action input to use for magic-link identity binding (e.g. "customer_email").`)})),rS=R(()=>T({routes:w(nS).describe(`List of anonymous-accessible routes.`),defaultRateLimit:tS.optional()})),iS=R(()=>T({title:v().optional().describe(`Default <title>.`),description:v().optional().describe(`Default <meta name="description">.`),openGraphImage:v().optional().describe(`Default og:image URL.`),robots:A([`index`,`noindex`]).optional().default(`index`)})),aS=R(()=>E([j(`authenticated`),j(`magic-link`),j(`anonymous`),v().regex(/^sso:[a-z][a-z0-9_-]*(?::[a-z0-9_-]+)?$/i,`SSO mode must be "sso:<provider>" or "sso:<protocol>:<idp-id>"`)])),oS=R(()=>E([j(`console`),j(`minimal`),j(`embedded`),v().regex(/^custom:[a-z][a-z0-9_-]*(?:\/[a-z0-9_-]+)?$/i,`Custom layout must be "custom:<plugin-id>" or "custom:<plugin-id>/<layout-id>"`)]));R(()=>T({kind:j(`portal`).describe(`Metadata kind discriminator.`),id:V.describe(`Portal unique machine name (lowercase snake_case).`),label:z.describe(`Portal display label.`),description:z.optional(),routePrefix:v().regex(/^\/[a-z0-9/_-]*$/i,`routePrefix must start with "/" and be url-safe`).describe(`Root URL path for the portal (must start with "/").`),domain:v().optional().describe(`Optional vanity domain (e.g. "support.acme.com").`),layout:oS.default(`minimal`).describe(`Shell layout for the portal.`),theme:Jx.optional().describe(`Theme tokens.`),locale:E([j(`auto`),v()]).optional().default(`auto`).describe(`Locale resolution strategy.`),seo:iS.optional(),authMode:aS.default(`authenticated`).describe(`Authentication mode for the portal.`),profiles:w(V).min(1,`A portal must admit at least one profile (use a dedicated profile for "anonymous-only" portals).`).describe(`Profiles admitted to the portal.`),anonymousEntry:rS.optional(),navigation:w(eS).describe(`Flat list of portal entry points (references to existing metadata).`),defaultRoute:T({viewRef:v().optional(),actionRef:v().optional(),dashboardName:V.optional()}).optional().describe(`Landing surface when the user hits the portal root.`),embeddable:b().optional().default(!1),allowedEmbedOrigins:w(v()).optional(),active:b().optional().default(!0)}));var sS=t({AggregationFunction:()=>_S,AggregationMetricType:()=>YT,AggregationNodeSchema:()=>bS,AggregationStageSchema:()=>ET,ApiMethod:()=>vw,BaseEngineOptionsSchema:()=>Ww,ConditionalValidationSchema:()=>aC,ConsistencyLevelSchema:()=>yT,CrossFieldValidationSchema:()=>nC,CubeJoinSchema:()=>eE,CubeSchema:()=>tE,CurrencyConfigSchema:()=>JS,DATE_MACRO_ALIAS_TOKENS:()=>NS,DATE_MACRO_INSTANT_TOKENS:()=>jS,DATE_MACRO_PARAM_RE:()=>FS,DATE_MACRO_PERIOD_TOKENS:()=>MS,DATE_MACRO_TOKENS:()=>PS,DATE_MACRO_UNITS:()=>IS,DATE_MACRO_WRAPPED_RE:()=>RS,DataEngineAggregateRequestSchema:()=>aT,DataEngineBatchRequestSchema:()=>cT,DataEngineCountRequestSchema:()=>iT,DataEngineDeleteRequestSchema:()=>rT,DataEngineExecuteRequestSchema:()=>oT,DataEngineFilterSchema:()=>Hw,DataEngineFindOneRequestSchema:()=>eT,DataEngineFindRequestSchema:()=>$w,DataEngineInsertOptionsSchema:()=>Kw,DataEngineInsertRequestSchema:()=>tT,DataEngineSortSchema:()=>Uw,DataEngineUpdateRequestSchema:()=>nT,DataEngineVectorFindRequestSchema:()=>sT,DataTypeMappingSchema:()=>gT,DatasourceCapabilities:()=>WT,DateGranularity:()=>vS,DimensionSchema:()=>$T,DimensionType:()=>XT,DocumentSchemaValidationSchema:()=>CT,DocumentTemplateSchema:()=>LT,DocumentVersionSchema:()=>IT,DriverCapabilitiesSchema:()=>fT,DriverConfigSchema:()=>mT,DriverOptionsSchema:()=>dT,DriverType:()=>UT,ESignatureConfigSchema:()=>RT,EngineAggregateOptionsSchema:()=>Yw,EngineCountOptionsSchema:()=>Xw,EngineDeleteOptionsSchema:()=>Jw,EngineQueryOptionsSchema:()=>Gw,EngineUpdateOptionsSchema:()=>qw,ExpressionBodySchema:()=>dC,ExternalColumnSchema:()=>qT,ExternalDataSourceSchema:()=>VT,ExternalDatasourceSettingsSchema:()=>KT,ExternalFieldMappingSchema:()=>HT,ExternalTableSchema:()=>JT,FILTER_OPERATORS:()=>mS,FeedActorSchema:()=>oE,FeedItemType:()=>nE,FeedVisibility:()=>sE,FieldChangeEntrySchema:()=>iE,FieldMappingSchema:()=>zw,FieldNodeSchema:()=>DS,FieldOperatorsSchema:()=>lS,FieldReferenceSchema:()=>cS,FieldSchema:()=>ZS,FieldType:()=>KS,FileAttachmentConfigSchema:()=>XS,FilterConditionSchema:()=>uS,FormatValidationSchema:()=>tC,FullTextSearchSchema:()=>OS,GroupByNodeSchema:()=>yS,HookBodyCapability:()=>uC,HookBodySchema:()=>pC,HookEvent:()=>Iw,HookSchema:()=>Lw,IndexSchema:()=>bw,JSONValidationSchema:()=>rC,JoinNodeSchema:()=>CS,JoinStrategy:()=>SS,JoinType:()=>xS,LOGICAL_OPERATORS:()=>hS,MappingSchema:()=>Bw,MentionSchema:()=>rE,MetricSchema:()=>QT,NoSQLDataTypeMappingSchema:()=>wT,NoSQLDatabaseTypeSchema:()=>vT,NoSQLIndexTypeSchema:()=>bT,NoSQLQueryOptionsSchema:()=>TT,NormalizedFilterSchema:()=>dS,NotificationChannel:()=>lE,ObjectAccessConfigSchema:()=>Cw,ObjectCapabilities:()=>yw,ObjectDependencyGraphSchema:()=>jT,ObjectDependencyNodeSchema:()=>AT,ObjectExternalBindingSchema:()=>Ow,ObjectFieldGroupSchema:()=>Dw,ObjectSchema:()=>Fw,PartitioningConfigSchema:()=>Ew,PoolConfigSchema:()=>pT,QuerySchema:()=>AS,ReactionSchema:()=>aE,ReferenceResolutionErrorSchema:()=>MT,ReferenceResolutionSchema:()=>kT,ReplicationConfigSchema:()=>ST,SQLDialectSchema:()=>hT,SSLConfigSchema:()=>_T,SchemaModeSchema:()=>GT,ScriptBodySchema:()=>fC,ScriptValidationSchema:()=>$S,SearchConfigSchema:()=>xw,SeedIdentitySchema:()=>NT,SeedLoadResultSchema:()=>FT,SeedLoaderConfigSchema:()=>PT,SeedMode:()=>DT,SeedSchema:()=>OT,SelectOptionSchema:()=>qS,ShardingConfigSchema:()=>xT,SoftDeleteConfigSchema:()=>ww,SortNodeSchema:()=>gS,StateMachineValidationSchema:()=>eC,SubscriptionEventType:()=>cE,TenancyConfigSchema:()=>Sw,TimeUpdateInterval:()=>ZT,TransformType:()=>Rw,VALID_AST_OPERATORS:()=>fS,ValidationRuleSchema:()=>iC,VectorConfigSchema:()=>YS,VersioningConfigSchema:()=>Tw,WindowFunction:()=>wS,WindowFunctionNodeSchema:()=>ES,WindowSpecSchema:()=>TS,isDateMacroToken:()=>LS,isFilterAST:()=>pS});function H(e){if(typeof process<`u`&&{}.OS_EAGER_SCHEMAS===`1`)return e();let t,n=()=>(t===void 0&&(t=e()),t);return new Proxy(function(){},{get(e,t){let r=n(),i=r[t];return typeof i==`function`?i.bind(r):i},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())}})}var cS=H(()=>T({$field:v().describe(`Field Reference/Column Name`)}));H(()=>T({$eq:x().optional(),$ne:x().optional()})),H(()=>T({$gt:E([y(),C(),cS]).optional(),$gte:E([y(),C(),cS]).optional(),$lt:E([y(),C(),cS]).optional(),$lte:E([y(),C(),cS]).optional()})),H(()=>T({$in:w(x()).optional(),$nin:w(x()).optional()})),H(()=>T({$between:O([E([y(),C(),cS]),E([y(),C(),cS])]).optional()})),H(()=>T({$contains:v().optional(),$notContains:v().optional(),$startsWith:v().optional(),$endsWith:v().optional()})),H(()=>T({$null:b().optional(),$exists:b().optional()}));var lS=H(()=>T({$eq:x().optional(),$ne:x().optional(),$gt:E([y(),C(),cS]).optional(),$gte:E([y(),C(),cS]).optional(),$lt:E([y(),C(),cS]).optional(),$lte:E([y(),C(),cS]).optional(),$in:w(x()).optional(),$nin:w(x()).optional(),$between:O([E([y(),C(),cS]),E([y(),C(),cS])]).optional(),$contains:v().optional(),$notContains:v().optional(),$startsWith:v().optional(),$endsWith:v().optional(),$null:b().optional(),$exists:b().optional()})),uS=M(()=>k(v(),S()).and(T({$and:w(uS).optional(),$or:w(uS).optional(),$not:uS.optional()})));H(()=>T({where:uS.optional()}));var dS=M(()=>T({$and:w(E([k(v(),lS),dS])).optional(),$or:w(E([k(v(),lS),dS])).optional(),$not:E([k(v(),lS),dS]).optional()})),fS=new Set([`=`,`==`,`!=`,`<>`,`>`,`>=`,`<`,`<=`,`in`,`nin`,`not_in`,`contains`,`notcontains`,`not_contains`,`like`,`startswith`,`starts_with`,`endswith`,`ends_with`,`between`,`is_null`,`is_not_null`]);function pS(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=>pS(e));if(e.length>=2&&typeof e[1]==`string`)return fS.has(e[1].toLowerCase())}return e.every(e=>pS(e))?e.length>0:!1}var mS=[`$eq`,`$ne`,`$gt`,`$gte`,`$lt`,`$lte`,`$in`,`$nin`,`$between`,`$contains`,`$notContains`,`$startsWith`,`$endsWith`,`$null`,`$exists`],hS=[`$and`,`$or`,`$not`];[...mS,...hS];var gS=H(()=>T({field:v(),order:A([`asc`,`desc`]).default(`asc`)})),_S=A([`count`,`sum`,`avg`,`min`,`max`,`count_distinct`,`array_agg`,`string_agg`]),vS=A([`day`,`week`,`month`,`quarter`,`year`]),yS=H(()=>E([v(),T({field:v().describe(`Field to group by`),dateGranularity:vS.optional().describe(`Bucket date values into uniform periods (day/week/month/quarter/year)`),alias:v().optional().describe(`Alias for the projected group value`)})])),bS=H(()=>T({function:_S.describe(`Aggregation function`),field:v().optional().describe(`Field to aggregate (optional for COUNT(*))`),alias:v().describe(`Result column alias`),distinct:b().optional().describe(`Apply DISTINCT before aggregation`),filter:uS.optional().describe(`Filter/Condition to apply to the aggregation (FILTER WHERE clause)`)})),xS=A([`inner`,`left`,`right`,`full`]),SS=A([`auto`,`database`,`hash`,`loop`]),CS=M(()=>T({type:xS.describe(`Join type`),strategy:SS.optional().describe(`Execution strategy hint`),object:v().describe(`Object/table to join`),alias:v().optional().describe(`Table alias`),on:uS.describe(`Join condition`),subquery:M(()=>AS).optional().describe(`Subquery instead of object`)})),wS=A([`row_number`,`rank`,`dense_rank`,`percent_rank`,`lag`,`lead`,`first_value`,`last_value`,`sum`,`avg`,`count`,`min`,`max`]),TS=H(()=>T({partitionBy:w(v()).optional().describe(`PARTITION BY fields`),orderBy:w(gS).optional().describe(`ORDER BY specification`),frame:T({type:A([`rows`,`range`]).optional(),start:v().optional().describe(`Frame start (e.g., "UNBOUNDED PRECEDING", "1 PRECEDING")`),end:v().optional().describe(`Frame end (e.g., "CURRENT ROW", "1 FOLLOWING")`)}).optional().describe(`Window frame specification`)})),ES=H(()=>T({function:wS.describe(`Window function name`),field:v().optional().describe(`Field to operate on (for aggregate window functions)`),alias:v().describe(`Result column alias`),over:TS.describe(`Window specification (OVER clause)`)})),DS=M(()=>E([v(),T({field:v(),fields:w(DS).optional(),alias:v().optional()})])),OS=H(()=>T({query:v().describe(`Search query text`),fields:w(v()).optional().describe(`Fields to search in (if not specified, searches all text fields)`),fuzzy:b().optional().default(!1).describe(`Enable fuzzy matching (tolerates typos)`),operator:A([`and`,`or`]).optional().default(`or`).describe(`Logical operator between terms`),boost:k(v(),y()).optional().describe(`Field-specific relevance boosting (field name -> boost factor)`),minScore:y().optional().describe(`Minimum relevance score threshold`),language:v().optional().describe(`Language for text analysis (e.g., "en", "zh", "es")`),highlight:b().optional().default(!1).describe(`Enable search result highlighting`)})),kS=T({object:v().describe(`Object name (e.g. account)`),fields:w(DS).optional().describe(`Fields to retrieve`),where:uS.optional().describe(`Filtering criteria (WHERE)`),search:OS.optional().describe(`Full-text search configuration ($search parameter)`),orderBy:w(gS).optional().describe(`Sorting instructions (ORDER BY)`),limit:y().optional().describe(`Max records to return (LIMIT)`),offset:y().optional().describe(`Records to skip (OFFSET)`),top:y().optional().describe(`Alias for limit (OData compatibility)`),cursor:k(v(),S()).optional().describe(`Cursor for keyset pagination`),joins:w(CS).optional().describe(`Explicit Table Joins`),aggregations:w(bS).optional().describe(`Aggregation functions`),groupBy:w(yS).optional().describe("GROUP BY targets (strings or `{field, dateGranularity?}` objects for date bucketing)"),having:uS.optional().describe(`HAVING clause for aggregation filtering`),windowFunctions:w(ES).optional().describe(`Window functions with OVER clause`),distinct:b().optional().describe(`SELECT DISTINCT flag`)}),AS=H(()=>kS.extend({expand:M(()=>k(v(),AS)).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.")})),jS=[`today`,`yesterday`,`tomorrow`,`now`],MS=[`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`],NS=[`week_start`,`week_end`,`month_start`,`month_end`,`quarter_start`,`quarter_end`,`year_start`,`year_end`],PS=[...jS,...MS,...NS],FS=/^(\d+)_(minutes?|hours?|days?|weeks?|months?|years?)_(ago|from_now)$/,IS=[`minute`,`hour`,`day`,`week`,`month`,`year`];function LS(e){return PS.includes(e)||FS.test(e)}v().refine(LS,{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: `+IS.join(`, `)});var RS=/^\$?\{([a-zA-Z0-9_]+)\}$/;v().refine(e=>{let t=e.match(RS);return!!t&&LS(t[1])},{message:`Not a recognised {date-macro} placeholder`});var zS=H(()=>v().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)`)),BS=H(()=>v().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)`));H(()=>v().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 VS=A([`cel`,`js`,`cron`,`template`]),HS=T({rationale:v().optional(),generatedBy:v().optional()}),US=T({dialect:VS,source:v().min(1).optional(),ast:S().optional(),meta:HS.optional()}).refine(e=>e.source!==void 0||e.ast!==void 0,{message:"Expression requires at least one of `source` or `ast`"}),WS=E([v().min(1).transform(e=>({dialect:`cel`,source:e})),US]);E([v().min(1).transform(e=>({dialect:`cron`,source:e})),US]);var GS=E([v().min(1).transform(e=>({dialect:`template`,source:e})),US]),KS=A(`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(`.`)),qS=H(()=>T({label:v().describe(`Display label (human-readable, any case allowed)`),value:zS.describe(`Stored value (lowercase machine identifier)`),color:v().optional().describe(`Color code for badges/charts`),default:b().optional().describe(`Is default option`)}));H(()=>T({latitude:y().min(-90).max(90).describe(`Latitude coordinate`),longitude:y().min(-180).max(180).describe(`Longitude coordinate`),altitude:y().optional().describe(`Altitude in meters`),accuracy:y().optional().describe(`Accuracy in meters`)}));var JS=H(()=>T({precision:y().int().min(0).max(10).default(2).describe(`Decimal precision (default: 2)`),currencyMode:A([`dynamic`,`fixed`]).default(`dynamic`).describe(`Currency mode: dynamic (user selectable) or fixed (single currency)`),defaultCurrency:v().length(3).default(`CNY`).describe(`Default or fixed currency code (ISO 4217, e.g., USD, CNY, EUR)`)}));H(()=>T({value:y().describe(`Monetary amount`),currency:v().length(3).describe(`Currency code (ISO 4217)`)})),H(()=>T({street:v().optional().describe(`Street address`),city:v().optional().describe(`City name`),state:v().optional().describe(`State/Province`),postalCode:v().optional().describe(`Postal/ZIP code`),country:v().optional().describe(`Country name or code`),countryCode:v().optional().describe(`ISO country code (e.g., US, GB)`),formatted:v().optional().describe(`Formatted address string`)}));var YS=H(()=>T({dimensions:y().int().min(1).max(1e4).describe(`Vector dimensionality (e.g., 1536 for OpenAI embeddings)`),distanceMetric:A([`cosine`,`euclidean`,`dotProduct`,`manhattan`]).default(`cosine`).describe(`Distance/similarity metric for vector search`),normalized:b().default(!1).describe(`Whether vectors are normalized (unit length)`),indexed:b().default(!0).describe(`Whether to create a vector index for fast similarity search`),indexType:A([`hnsw`,`ivfflat`,`flat`]).optional().describe(`Vector index algorithm (HNSW for high accuracy, IVFFlat for large datasets)`)})),XS=H(()=>T({minSize:y().min(0).optional().describe(`Minimum file size in bytes`),maxSize:y().min(1).optional().describe(`Maximum file size in bytes (e.g., 10485760 = 10MB)`),allowedTypes:w(v()).optional().describe(`Allowed file extensions (e.g., [".pdf", ".docx", ".jpg"])`),blockedTypes:w(v()).optional().describe(`Blocked file extensions (e.g., [".exe", ".bat", ".sh"])`),allowedMimeTypes:w(v()).optional().describe(`Allowed MIME types (e.g., ["image/jpeg", "application/pdf"])`),blockedMimeTypes:w(v()).optional().describe(`Blocked MIME types`),virusScan:b().default(!1).describe(`Enable virus scanning for uploaded files`),virusScanProvider:A([`clamav`,`virustotal`,`metadefender`,`custom`]).optional().describe(`Virus scanning service provider`),virusScanOnUpload:b().default(!0).describe(`Scan files immediately on upload`),quarantineOnThreat:b().default(!0).describe(`Quarantine files if threat detected`),storageProvider:v().optional().describe(`Object storage provider name (references ObjectStorageConfig)`),storageBucket:v().optional().describe(`Target bucket name`),storagePrefix:v().optional().describe(`Storage path prefix (e.g., "uploads/documents/")`),imageValidation:T({minWidth:y().min(1).optional().describe(`Minimum image width in pixels`),maxWidth:y().min(1).optional().describe(`Maximum image width in pixels`),minHeight:y().min(1).optional().describe(`Minimum image height in pixels`),maxHeight:y().min(1).optional().describe(`Maximum image height in pixels`),aspectRatio:v().optional().describe(`Required aspect ratio (e.g., "16:9", "1:1")`),generateThumbnails:b().default(!1).describe(`Auto-generate thumbnails`),thumbnailSizes:w(T({name:v().describe(`Thumbnail variant name (e.g., "small", "medium", "large")`),width:y().min(1).describe(`Thumbnail width in pixels`),height:y().min(1).describe(`Thumbnail height in pixels`),crop:b().default(!1).describe(`Crop to exact dimensions`)})).optional().describe(`Thumbnail size configurations`),preserveMetadata:b().default(!1).describe(`Preserve EXIF metadata`),autoRotate:b().default(!0).describe(`Auto-rotate based on EXIF orientation`)}).optional().describe(`Image-specific validation rules`),allowMultiple:b().default(!1).describe(`Allow multiple file uploads (overrides field.multiple)`),allowReplace:b().default(!0).describe(`Allow replacing existing files`),allowDelete:b().default(!0).describe(`Allow deleting uploaded files`),requireUpload:b().default(!1).describe(`Require at least one file when field is required`),extractMetadata:b().default(!0).describe(`Extract file metadata (name, size, type, etc.)`),extractText:b().default(!1).describe(`Extract text content from documents (OCR/parsing)`),versioningEnabled:b().default(!1).describe(`Keep previous versions of replaced files`),maxVersions:y().min(1).optional().describe(`Maximum number of versions to retain`),publicRead:b().default(!1).describe(`Allow public read access to uploaded files`),presignedUrlExpiry:y().min(60).max(604800).default(3600).describe(`Presigned URL expiration in seconds (default: 1 hour)`)}).refine(e=>!(e.minSize!==void 0&&e.maxSize!==void 0&&e.minSize>e.maxSize),{message:`minSize must be less than or equal to maxSize`}).refine(e=>!(e.virusScanProvider!==void 0&&e.virusScan!==!0),{message:`virusScanProvider requires virusScan to be enabled`}));H(()=>T({uniqueness:b().default(!1).describe(`Enforce unique values across all records`),completeness:y().min(0).max(1).default(0).describe(`Minimum ratio of non-null values (0-1, default: 0 = no requirement)`),accuracy:T({source:v().describe(`Reference data source for validation (e.g., "api.verify.com", "master_data")`),threshold:y().min(0).max(1).describe(`Minimum accuracy threshold (0-1, e.g., 0.95 = 95% match required)`)}).optional().describe(`Accuracy validation configuration`)})),H(()=>T({enabled:b().describe(`Enable caching for computed field results`),ttl:y().min(0).describe(`Cache TTL in seconds (0 = no expiration)`),invalidateOn:w(v()).describe(`Field paths that invalidate cache (e.g., ["inventory.quantity", "pricing.base_price"])`)}));var ZS=H(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Machine name (snake_case)`).optional(),label:v().optional().describe(`Human readable label`),type:KS.describe(`Field Data Type`),description:v().optional().describe(`Tooltip/Help text`),format:v().optional().describe(`Format string (e.g. email, phone)`),columnName:v().optional().describe(`Physical column name in the target datasource. Defaults to the field key when not set.`),required:b().default(!1).describe(`Is required`),searchable:b().default(!1).describe(`Is searchable`),multiple:b().default(!1).describe(`Allow multiple values (Stores as Array/JSON). Applicable for select, lookup, file, image.`),unique:b().default(!1).describe(`Is unique constraint`),defaultValue:S().optional().describe(`Default value`),maxLength:y().optional().describe(`Max character length`),minLength:y().optional().describe(`Min character length`),precision:y().optional().describe(`Total digits`),scale:y().optional().describe(`Decimal places`),min:y().optional().describe(`Minimum value`),max:y().optional().describe(`Maximum value`),options:w(qS).optional().describe(`Static options for select/multiselect`),reference:v().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.`),referenceFilters:w(v()).optional().describe(`Filters applied to lookup dialogs (e.g. "active = true")`),deleteBehavior:A([`set_null`,`cascade`,`restrict`]).optional().default(`set_null`).describe(`What happens if referenced record is deleted`),inlineEdit:E([b(),A([`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:v().optional().describe(`Title for the inline master-detail grid`),inlineColumns:w(x()).optional().describe(`Explicit columns for the inline grid (derived from the child object when omitted)`),inlineAmountField:v().optional().describe(`Numeric child field summed for the inline grid total`),relatedList:b().optional().describe(`Show this child collection as a related list on the parent's detail page (read-side mirror of inlineEdit). Defaults to shown for master_detail/lookup; set false to suppress.`),relatedListTitle:v().optional().describe(`Title for the detail-page related list`),relatedListColumns:w(x()).optional().describe(`Explicit columns for the detail-page related list (derived from the child object when omitted)`),displayField:v().optional().describe(`Field shown as each candidate's label in the picker/popover (defaults to the referenced object's name/title).`),descriptionField:v().optional().describe(`Secondary field shown under the label in the quick-select popover.`),lookupColumns:w(E([v(),T({field:v(),label:v().optional(),width:v().optional(),type:v().optional()})])).optional().describe(`Explicit columns for the record-picker table; auto-derived from the referenced object when omitted.`),lookupPageSize:y().int().positive().optional().describe(`Rows per page in the record-picker dialog (default 10).`),lookupFilters:w(T({field:v(),operator:A([`eq`,`ne`,`gt`,`lt`,`gte`,`lte`,`contains`,`in`,`notIn`]),value:x()})).optional().describe(`Base filters restricting which records are selectable (e.g. only active). Structured, picker-honoured form of referenceFilters.`),dependsOn:w(E([v(),T({field:v(),param:v().optional()})])).optional().describe(`Dependent lookup: restrict candidates by the value of other field(s) on the same record. String = same local/remote key; {field,param} when the remote filter key differs.`),allowCreate:b().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:WS.optional().describe("Formula expression (CEL). e.g. F`record.amount * 0.1`"),returnType:A([`number`,`text`,`boolean`,`date`]).optional().describe(`Inferred value type of a formula field (number/text/boolean/date)`),summaryOperations:T({object:v().describe(`Source child object name for roll-up`),field:v().describe(`Field on child object to aggregate (ignored for count)`),function:A([`count`,`sum`,`min`,`max`,`avg`]).describe(`Aggregation function to apply`),relationshipField:v().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.`)}).optional().describe(`Roll-up summary definition. The engine recomputes the value when child records are inserted/updated/deleted.`),language:v().optional().describe(`Programming language for syntax highlighting (e.g., javascript, python, sql)`),maxRating:y().optional().describe(`Maximum rating value (default: 5)`),step:y().optional().describe(`Step increment for slider (default: 1)`),currencyConfig:JS.optional().describe(`Configuration for currency field type`),dimensions:y().int().min(1).max(1e4).optional().describe(`Vector dimensionality (e.g., 1536 for OpenAI embeddings)`),vectorConfig:YS.optional().describe(`Configuration for vector field type (AI/ML embeddings)`),fileAttachmentConfig:XS.optional().describe(`Configuration for file and attachment field types`),trackHistory:b().optional().describe(`Render this field's value changes as human-readable entries on the record activity timeline (ADR-0052 §5b). Opt-in per field.`),dependencies:w(v()).optional().describe(`Array of field names that this field depends on (for formulas, visibility rules, etc.)`),group:v().optional().describe(`Field group name for organizing fields in forms and layouts (e.g., "contact_info", "billing", "system")`),visibleWhen:WS.optional().describe("Predicate (CEL) — field is shown only when TRUE (else hidden). e.g. P`record.type == 'invoice'`"),readonlyWhen:WS.optional().describe("Predicate (CEL) — field is read-only when TRUE. e.g. P`record.status == 'paid'`"),requiredWhen:WS.optional().describe("Predicate (CEL) — field is required when TRUE. Canonical name for `conditionalRequired`."),conditionalRequired:WS.optional().describe("Predicate (CEL) — field is required when TRUE. Alias of `requiredWhen`."),hidden:b().default(!1).describe(`Hidden from default UI`),readonly:b().default(!1).describe(`Read-only in UI`),requiredPermissions:w(v()).optional().describe(`[ADR-0066 D3] Capabilities required to read/edit this field (mask on read, deny on write; AND-gate).`),system:b().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:b().optional().default(!0).describe(`Whether field is sortable in list views`),inlineHelpText:v().optional().describe(`Help text displayed below the field in forms`),caseSensitive:b().optional().describe(`Whether text comparisons are case-sensitive`),autonumberFormat:v().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).`),index:b().default(!1).describe(`Create standard database index`),externalId:b().default(!1).describe(`Is external ID for upsert operations`)})),QS=T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Unique rule name (snake_case)`),label:v().optional().describe(`Human-readable label for the rule listing`),description:v().optional().describe(`Administrative notes explaining the business reason`),active:b().default(!0),events:w(A([`insert`,`update`,`delete`])).default([`insert`,`update`]).describe(`Validation contexts`),priority:y().int().min(0).max(9999).default(100).describe(`Execution priority (lower runs first, default: 100)`),tags:w(v()).optional().describe(`Categorization tags (e.g., "compliance", "billing")`),severity:A([`error`,`warning`,`info`]).default(`error`),message:v().describe(`Error message to display to the user`)}),$S=H(()=>QS.extend({type:j(`script`),condition:WS.describe("Predicate (CEL). If TRUE, validation fails. e.g. P`record.amount < 0`")})),eC=H(()=>QS.extend({type:j(`state_machine`),field:v().describe(`State field (e.g. status)`),transitions:k(v(),w(v())).describe(`Map of { OldState: [AllowedNewStates] }`)})),tC=H(()=>QS.extend({type:j(`format`),field:v(),regex:v().optional(),format:A([`email`,`url`,`phone`,`json`]).optional()})),nC=H(()=>QS.extend({type:j(`cross_field`),condition:WS.describe("Predicate (CEL) comparing fields. e.g. P`record.end_date > record.start_date`"),fields:w(v()).describe(`Fields involved in the validation`)})),rC=H(()=>QS.extend({type:j(`json_schema`),field:v().describe(`JSON field to validate`),schema:k(v(),S()).describe(`JSON Schema object definition`)})),iC=M(()=>D(`type`,[$S,eC,tC,nC,rC,aC])),aC=H(()=>QS.extend({type:j(`conditional`),when:WS.describe("Predicate (CEL). e.g. P`record.type == 'enterprise'`"),then:iC.describe(`Validation rule to apply when condition is true`),otherwise:iC.optional().describe(`Validation rule to apply when condition is false`)}));H(()=>T({key:v().describe(`Translation key (e.g., "views.task_list.label")`),defaultValue:v().optional().describe(`Fallback value when translation key is not found`),params:k(v(),E([v(),y(),b()])).optional().describe(`Interpolation parameters (e.g., { count: 5 })`)}));var oC=H(()=>v().describe(`Display label (plain string; i18n keys are auto-generated by the framework)`)),sC=H(()=>T({ariaLabel:oC.optional().describe(`Accessible label for screen readers (WAI-ARIA aria-label)`),ariaDescribedBy:v().optional().describe(`ID of element providing additional description (WAI-ARIA aria-describedby)`),role:v().optional().describe(`WAI-ARIA role attribute (e.g., "dialog", "navigation", "alert")`)}).describe(`ARIA accessibility attributes`));H(()=>T({key:v().describe(`Translation key`),zero:v().optional().describe(`Zero form (e.g., "No items")`),one:v().optional().describe(`Singular form (e.g., "{count} item")`),two:v().optional().describe(`Dual form (e.g., "{count} items" for exactly 2)`),few:v().optional().describe(`Few form (e.g., for 2-4 in some languages)`),many:v().optional().describe(`Many form (e.g., for 5+ in some languages)`),other:v().describe(`Default plural form (e.g., "{count} items")`)}).describe(`ICU plural rules for a translation key`));var cC=H(()=>T({style:A([`decimal`,`currency`,`percent`,`unit`]).default(`decimal`).describe(`Number formatting style`),currency:v().optional().describe(`ISO 4217 currency code (e.g., "USD", "EUR")`),unit:v().optional().describe(`Unit for unit formatting (e.g., "kilometer", "liter")`),minimumFractionDigits:y().optional().describe(`Minimum number of fraction digits`),maximumFractionDigits:y().optional().describe(`Maximum number of fraction digits`),useGrouping:b().optional().describe(`Whether to use grouping separators (e.g., 1,000)`)}).describe(`Number formatting rules`)),lC=H(()=>T({dateStyle:A([`full`,`long`,`medium`,`short`]).optional().describe(`Date display style`),timeStyle:A([`full`,`long`,`medium`,`short`]).optional().describe(`Time display style`),timeZone:v().optional().describe(`IANA time zone (e.g., "America/New_York")`),hour12:b().optional().describe(`Use 12-hour format`)}).describe(`Date/time formatting rules`));H(()=>T({code:v().describe(`BCP 47 language code (e.g., "en-US", "zh-CN")`),fallbackChain:w(v()).optional().describe(`Fallback language codes in priority order (e.g., ["zh-TW", "en"])`),direction:A([`ltr`,`rtl`]).default(`ltr`).describe(`Text direction: left-to-right or right-to-left`),numberFormat:cC.optional().describe(`Default number formatting rules`),dateFormat:lC.optional().describe(`Default date/time formatting rules`)}).describe(`Locale configuration`));var uC=A([`api.read`,`api.write`,`api.transaction`,`crypto.uuid`,`crypto.hash`,`log`]),dC=T({language:j(`expression`),source:v().min(1).describe(`Formula expression source`)}).describe(`L1 expression body — pure formula, no IO`),fC=T({language:j(`js`),source:v().min(1).describe(`Function body source`),capabilities:w(uC).default([]).describe(`Granted capability tokens`),timeoutMs:y().int().positive().max(3e4).optional().describe(`Per-invocation timeout (ms)`),memoryMb:y().int().positive().max(256).optional().describe(`Per-invocation memory cap (MB)`)}).describe(`L2 sandboxed JS body — runs inside an isolated VM with declared capabilities`),pC=D(`language`,[dC,fC]).describe(`Hook/Action body — expression (L1) or sandboxed JS (L2)`),mC=H(()=>T({name:v().optional(),field:BS.optional(),objectOverride:BS.optional(),label:oC.optional(),type:KS.optional(),required:b().optional().default(!1),options:w(T({label:oC,value:v()})).optional(),placeholder:v().optional(),helpText:v().optional(),defaultValue:S().optional(),defaultFromRow:b().optional()}).refine(e=>!!e.name||!!e.field,{message:`ActionParam requires either "name" or "field"`})),hC=A([`script`,`url`,`modal`,`flow`,`api`,`form`]),gC=new Set(hC.options.filter(e=>e!==`script`)),_C=A([`list_toolbar`,`list_item`,`record_header`,`record_more`,`record_related`,`record_section`,`global_nav`]),vC=A([`data`,`action`,`flow`,`integration`,`vector_search`,`analytics`,`utility`]),yC=T({exposed:b().default(!1).describe("Expose this action to AI agents. Requires `description` when true."),description:v().min(40).optional().describe(`LLM-facing description (≥40 chars). Required when exposed.`),category:vC.optional().describe(`Tool category override (defaults to "action").`),paramHints:k(v(),T({description:v().optional(),enum:w(E([v(),y()])).optional(),examples:w(S()).optional()})).optional().describe(`Per-parameter AI hints keyed by param name.`),outputSchema:k(v(),S()).optional().describe(`JSON Schema for the action return value.`),requiresConfirmation:b().optional().describe(`Override HITL confirmation for AI invocations.`)}),bC=H(()=>T({name:BS.describe(`Machine name (lowercase snake_case)`),label:oC.describe(`Display label`),objectName:v().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:v().optional().describe(`Icon name`),locations:w(_C).optional().describe(`Locations where this action is visible`),component:A([`action:button`,`action:icon`,`action:menu`,`action:group`]).optional().describe(`Visual component override`),type:hC.default(`script`).describe(`Action functionality type`),target:v().optional().describe("URL, Script Name, Flow ID, or API Endpoint. Supports ${param.X} and ${ctx.X} interpolation."),body:pC.optional().describe("Action body — expression (L1) or sandboxed JS (L2). Only used when type is `script`."),execute:v().optional().describe(`@deprecated — Use target instead. Auto-migrated to target during parsing.`),params:w(mC).optional().describe(`Input parameters required from user`),variant:A([`primary`,`secondary`,`danger`,`ghost`,`link`]).optional().describe(`Button visual variant for styling (primary = highlighted, danger = destructive, ghost = transparent)`),confirmText:oC.optional().describe(`Confirmation message before execution`),successMessage:oC.optional().describe(`Success message to show after execution`),errorMessage:oC.optional().describe(`Error message to show when the action fails (overrides the raw error).`),refreshAfter:b().default(!1).describe(`Refresh view after execution`),undoable:b().optional().describe(`Offer an Undo affordance after this single-record update action succeeds.`),resultDialog:T({title:oC.optional(),description:oC.optional(),acknowledge:oC.optional().describe(`Acknowledge button label, e.g. "I have saved this"`),format:A([`qrcode`,`code-list`,`secret`,`text`,`json`]).optional().describe(`Default format for fields without their own format. Defaults to json when omitted.`),fields:w(T({path:v().describe(`Dot path into result.data (e.g. "totpURI", "client.client_secret").`),label:oC.optional(),format:A([`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:WS.optional().describe(`Visibility predicate (CEL).`),disabled:E([b(),WS]).optional().describe(`Boolean or predicate (CEL) — action is disabled when TRUE.`),requiredPermissions:w(v()).optional().describe(`[ADR-0066 D4] Capabilities required to invoke this action (server-enforced 403 + UI hide/disable).`),shortcut:v().optional().describe(`Keyboard shortcut to trigger this action (e.g., "Ctrl+S")`),bulkEnabled:b().optional().describe(`Whether this action can be applied to multiple selected records`),ai:yC.optional().describe(`AI exposure (opt-in). Set ai.exposed=true + ai.description to make this callable by agents.`),recordIdParam:v().optional().describe(`Body key to inject the row id into when running from a list_item context.`),recordIdField:v().optional().describe(`Row field whose value seeds recordIdParam. Defaults to "id".`),bodyShape:E([j(`flat`),T({wrap:v()})]).optional().describe(`Body wrapping: flat (default) or { wrap: key } to nest user-collected params under a key.`),method:A([`POST`,`PATCH`,`PUT`,`DELETE`]).optional().describe(`HTTP method for type:"api" actions. Defaults to POST.`),bodyExtra:k(v(),S()).optional().describe(`Constant body fields merged into the API request (applied last; overrides user params).`),mode:A([`create`,`edit`,`delete`,`custom`]).optional().describe(`Semantic mode of the action.`),opensInNewTab:b().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:v().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.`),timeout:y().optional().describe(`Maximum execution time in milliseconds for the action`),aria:sC.optional().describe(`ARIA accessibility attributes`)}).transform(e=>e.execute&&!e.target?{...e,target:e.execute}:e).refine(e=>!(gC.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.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`]})),xC=A([`none`,`no-overlay`,`no-delete`,`full`]),SC=A([`artifact`,`package`,`env-forced`]),CC=A([`package`,`org`,`env-forced`]),wC={_lock:xC.optional().describe(`Item-level lock — controls overlay & delete (ADR-0010).`),_lockReason:v().max(500).optional().describe(`Human-readable reason shown when a write is refused by _lock.`),_lockSource:SC.optional().describe(`Layer that set _lock (artifact | package | env-forced).`),_provenance:CC.optional().describe(`Origin of the item (package | org | env-forced).`),_packageId:v().optional().describe(`Owning package machine id.`),_packageVersion:v().optional().describe(`Owning package version.`),_lockDocsUrl:v().optional().describe(`Optional documentation link surfaced next to _lockReason.`)},TC=T({lock:xC.describe(`Lock policy — none | no-overlay | no-delete | full.`),reason:v().min(1).max(500).describe(`User-visible reason shown when the lock blocks an action.`),docsUrl:v().url().optional().describe(`Optional URL the Studio banner links to for more context.`)}).strict(),EC=H(()=>T({enabled:b().default(!1).describe(`Enable public sharing`),publicLink:v().optional().describe(`Generated public share URL`),password:v().optional().describe(`Password required to access shared link`),allowedDomains:w(v()).optional().describe(`Restrict access to specific email domains (e.g. ["example.com"])`),expiresAt:v().optional().describe(`Expiration date/time in ISO 8601 format`),allowAnonymous:b().optional().default(!1).describe(`Allow access without authentication`)}));H(()=>T({enabled:b().default(!1).describe(`Enable iframe embedding`),allowedOrigins:w(v()).optional().describe(`Allowed iframe parent origins (e.g. ["https://example.com"])`),width:v().optional().default(`100%`).describe(`Embed width (CSS value)`),height:v().optional().default(`600px`).describe(`Embed height (CSS value)`),showHeader:b().optional().default(!0).describe(`Show interface header in embed`),showNavigation:b().optional().default(!1).describe(`Show navigation in embed`),responsive:b().optional().default(!0).describe(`Enable responsive resizing`)}));var DC=A([`xs`,`sm`,`md`,`lg`,`xl`,`2xl`]),OC=H(()=>T({xs:y().min(1).max(12).optional(),sm:y().min(1).max(12).optional(),md:y().min(1).max(12).optional(),lg:y().min(1).max(12).optional(),xl:y().min(1).max(12).optional(),"2xl":y().min(1).max(12).optional()}).describe(`Grid columns per breakpoint (1-12)`)),kC=H(()=>T({xs:y().optional(),sm:y().optional(),md:y().optional(),lg:y().optional(),xl:y().optional(),"2xl":y().optional()}).describe(`Display order per breakpoint`)),AC=H(()=>T({breakpoint:DC.optional().describe(`Minimum breakpoint for visibility`),hiddenOn:w(DC).optional().describe(`Hide on these breakpoints`),columns:OC.optional().describe(`Grid columns per breakpoint`),order:kC.optional().describe(`Display order per breakpoint`)}).describe(`Responsive layout configuration`)),jC=H(()=>k(v(),E([v(),y()])).describe(`CSS property → value map (camelCase keys; design tokens encouraged)`));H(()=>T({large:jC.optional().describe(`Unconditional base (desktop-first)`),medium:jC.optional().describe(`Applied at ≤ medium breakpoint`),small:jC.optional().describe(`Applied at ≤ small breakpoint`),xsmall:jC.optional().describe(`Applied at ≤ xsmall breakpoint`)}).describe(`Per-breakpoint scoped style maps (ADR-0065)`));var MC=H(()=>T({lazyLoad:b().optional().describe(`Enable lazy loading (defer rendering until visible)`),virtualScroll:T({enabled:b().default(!1).describe(`Enable virtual scrolling`),itemHeight:y().optional().describe(`Fixed item height in pixels (for estimation)`),overscan:y().optional().describe(`Number of extra items to render outside viewport`)}).optional().describe(`Virtual scrolling configuration`),cacheStrategy:A([`none`,`cache-first`,`network-first`,`stale-while-revalidate`]).optional().describe(`Client-side data caching strategy`),prefetch:b().optional().describe(`Prefetch data before component is visible`),pageSize:y().optional().describe(`Number of items per page for pagination`),debounceMs:y().optional().describe(`Debounce interval for user interactions in milliseconds`)}).describe(`Performance optimization configuration`)),NC=A([`GET`,`POST`,`PUT`,`DELETE`,`PATCH`,`HEAD`,`OPTIONS`]),PC=H(()=>A([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`])),FC=H(()=>T({url:v().describe(`API endpoint URL`),method:PC.optional().default(`GET`).describe(`HTTP method`),headers:k(v(),v()).optional().describe(`Custom HTTP headers`),params:k(v(),S()).optional().describe(`Query parameters`),body:S().optional().describe(`Request body for POST/PUT/PATCH`)}));H(()=>T({enabled:b().default(!0).describe(`Enable CORS`),origins:E([v(),w(v())]).default(`*`).describe(`Allowed origins (* for all)`),methods:w(NC).optional().describe(`Allowed HTTP methods`),credentials:b().default(!1).describe(`Allow credentials (cookies, authorization headers)`),maxAge:y().int().optional().describe(`Preflight cache duration in seconds`)})),H(()=>T({enabled:b().default(!1).describe(`Enable rate limiting`),windowMs:y().int().default(6e4).describe(`Time window in milliseconds`),maxRequests:y().int().default(100).describe(`Max requests per window`)})),H(()=>T({path:v().describe(`URL path to serve from`),directory:v().describe(`Physical directory to serve`),cacheControl:v().optional().describe(`Cache-Control header value`)}));var IC=H(()=>D(`provider`,[T({provider:j(`object`),object:v().describe(`Target object name`)}),T({provider:j(`api`),read:FC.optional().describe(`Configuration for fetching data`),write:FC.optional().describe(`Configuration for submitting data (for forms/editable tables)`)}),T({provider:j(`value`),items:w(S()).describe(`Static data array`)}),T({provider:j(`schema`),schemaId:v().describe(`Schema identifier — typically the metadata type name`),schema:k(v(),S()).optional().describe(`Inline JSON Schema (Draft 2020-12). Optional when schemaId is resolvable.`)})])),LC=H(()=>T({field:v().describe(`Field name to filter on`),operator:v().describe(`Filter operator (e.g. equals, not_equals, contains, this_quarter)`),value:E([v(),y(),b(),ul(),w(E([v(),y()]))]).optional().describe(`Filter value`)}).describe(`View filter rule`)),RC=H(()=>A([`none`,`count`,`count_empty`,`count_filled`,`count_unique`,`percent_empty`,`percent_filled`,`sum`,`avg`,`min`,`max`]).describe(`Aggregation function for column footer summary`)),zC=H(()=>T({field:v().describe(`Field name (snake_case)`),label:oC.optional().describe(`Display label override`),width:y().positive().optional().describe(`Column width in pixels`),align:A([`left`,`center`,`right`]).optional().describe(`Text alignment`),hidden:b().optional().describe(`Hide column by default`),sortable:b().optional().describe(`Allow sorting by this column`),resizable:b().optional().describe(`Allow resizing this column`),wrap:b().optional().describe(`Allow text wrapping`),type:v().optional().describe(`Renderer type override (e.g., "currency", "date")`),pinned:A([`left`,`right`]).optional().describe(`Pin/freeze column to left or right side`),summary:RC.optional().describe(`Footer aggregation function for this column`),link:b().optional().describe(`Functions as the primary navigation link (triggers View navigation)`),action:v().optional().describe(`Registered Action ID to execute when clicked`)})),BC=H(()=>T({type:A([`none`,`single`,`multiple`]).default(`none`).describe(`Selection mode`)})),VC=H(()=>T({pageSize:y().int().positive().default(25).describe(`Number of records per page`),pageSizeOptions:w(y().int().positive()).optional().describe(`Available page size options`)})),HC=H(()=>A([`compact`,`short`,`medium`,`tall`,`extra_tall`]).describe(`Row height / density setting for list view`)),UC=H(()=>T({field:v().describe(`Field name to group by`),order:A([`asc`,`desc`]).default(`asc`).describe(`Group sort order`),collapsed:b().default(!1).describe(`Collapse groups by default`)})),WC=H(()=>T({fields:w(UC).min(1).describe(`Fields to group by (supports up to 3 levels)`)}).describe(`Record grouping configuration`)),GC=H(()=>T({coverField:v().optional().describe(`Attachment/image field to display as card cover`),coverFit:A([`cover`,`contain`]).default(`cover`).describe(`Image fit mode for card cover`),cardSize:A([`small`,`medium`,`large`]).default(`medium`).describe(`Card size in gallery view`),titleField:v().optional().describe(`Field to display as card title`),visibleFields:w(v()).optional().describe(`Fields to display on card body`)}).describe(`Gallery/card view configuration`)),KC=H(()=>T({startDateField:v().describe(`Field for timeline item start date`),endDateField:v().optional().describe(`Field for timeline item end date`),titleField:v().describe(`Field to display as timeline item title`),groupByField:v().optional().describe(`Field to group timeline rows`),colorField:v().optional().describe(`Field to determine item color`),scale:A([`hour`,`day`,`week`,`month`,`quarter`,`year`]).default(`week`).describe(`Default timeline scale`)}).describe(`Timeline view configuration`)),qC=H(()=>T({type:A([`personal`,`collaborative`]).default(`collaborative`).describe(`View ownership type`),lockedBy:v().optional().describe(`User who locked the view configuration`)}).describe(`View sharing and access configuration`)),JC=H(()=>T({field:v().describe(`Field to derive color from (typically a select/status field)`),colors:k(v(),v()).optional().describe(`Map of field value to color (hex/token)`)}).describe(`Row color configuration based on field values`)),YC=H(()=>A([`grid`,`kanban`,`gallery`,`calendar`,`timeline`,`gantt`,`map`,`chart`,`tree`]).describe(`Visualization type that users can switch to`)),XC=H(()=>T({sort:b().default(!0).describe(`Allow users to sort records`),search:b().default(!0).describe(`Allow users to search records`),filter:b().default(!0).describe(`Allow users to filter records`),rowHeight:b().default(!0).describe(`Allow users to toggle row height/density`),addRecordForm:b().default(!1).describe(`Add records through a form instead of inline`),buttons:w(v()).optional().describe(`Custom action button IDs to show in the toolbar`)}).describe(`User action toggles for the view toolbar`)),ZC=H(()=>T({showDescription:b().default(!0).describe(`Show the view description text`),allowedVisualizations:w(YC).optional().describe(`Whitelist of visualization types users can switch between (e.g. ["grid", "gallery", "kanban"])`)}).describe(`Appearance and visualization configuration`)),QC=H(()=>T({name:BS.describe(`Tab identifier (snake_case)`),label:oC.optional().describe(`Display label`),icon:v().optional().describe(`Tab icon name`),view:v().optional().describe(`Referenced list view name from listViews`),filter:w(LC).optional().describe(`Tab-specific filter criteria`),order:y().int().min(0).optional().describe(`Tab display order`),pinned:b().default(!1).describe(`Pin tab (cannot be removed by users)`),isDefault:b().default(!1).describe(`Set as the default active tab`),visible:b().default(!0).describe(`Tab visibility`)}).describe(`Tab configuration for multi-tab view interface`)),$C=H(()=>T({field:v().describe(`Field name on the source object (must exist — checked by reference diagnostics)`),label:oC.optional().describe(`Display label override (defaults to the field label)`),type:A([`select`,`multi-select`,`boolean`,`date-range`,`text`]).optional().describe(`Filter control type. Omit to infer from the field definition`),options:w(T({value:E([v(),y(),b()]).describe(`Option value`),label:oC.describe(`Option label`),color:v().optional().describe(`Option color token/hex`)})).optional().describe(`Static options. Omit to derive from the field definition (select options / lookup records)`),showCount:b().optional().describe(`Show per-option record counts`),defaultValues:w(E([v(),y(),b()])).optional().describe(`Pre-selected values when the view loads`)}).describe(`Quick-filter field configuration`)),ew=H(()=>T({element:A([`dropdown`,`tabs`,`toggle`]).default(`dropdown`).describe(`Filter control style: "dropdown" (per-field value selectors) or "tabs" (named presets). "toggle" is deprecated.`),fields:w($C).optional().describe(`Fields exposed as quick filters (dropdown/toggle elements)`),tabs:w(QC).optional().describe(`Named filter presets rendered as tabs (tabs element). Reuses ViewTabSchema`),showAllRecords:b().optional().describe(`Show an "All records" tab before the presets (tabs element)`)}).describe(`End-user quick-filter configuration (Airtable "User filters" parity)`)),tw=H(()=>T({enabled:b().default(!0).describe(`Show the add record entry point`),position:A([`top`,`bottom`,`both`]).default(`bottom`).describe(`Position of the add record button`),mode:A([`inline`,`form`,`modal`]).default(`inline`).describe(`How to add a new record`),formView:v().optional().describe(`Named form view to use when mode is "form" or "modal"`)}).describe(`Add record entry point configuration`)),nw=H(()=>T({groupByField:v().describe(`Field to group columns by (usually status/select)`),summarizeField:v().optional().describe(`Field to sum at top of column (e.g. amount)`),columns:w(v()).describe(`Fields to show on cards`)})),rw=H(()=>T({chartType:A([`bar`,`line`,`pie`,`area`,`scatter`]).default(`bar`).describe(`Chart visualisation type`),dataset:BS.describe(`Dataset name to bind (ADR-0021)`),dimensions:w(v()).optional().describe(`Dimension names — X/group/split`),values:w(v()).min(1).describe(`Measure names — Y (at least one)`)}).describe(`List chart view configuration`)),iw=H(()=>T({startDateField:v(),endDateField:v().optional(),titleField:v(),colorField:v().optional()})),aw=H(()=>T({field:v().describe(`Record field / dot-path the dimension filters on`),label:v().optional().describe(`Trigger label (falls back to the field label)`),options:w(E([v(),T({value:E([v(),y()]),label:v().optional()})])).optional().describe(`Explicit option override for fixed enums`)})),ow=H(()=>T({startDateField:v(),endDateField:v(),titleField:v(),progressField:v().optional(),dependenciesField:v().optional(),colorField:v().optional().describe(`Field that drives the bar color`),parentField:v().optional().describe(`Field holding the parent task id (builds the summary → step tree)`),typeField:v().optional().describe(`Field whose value maps to task/summary/milestone`),baselineStartField:v().optional().describe(`Baseline (planned) start field`),baselineEndField:v().optional().describe(`Baseline (planned) end field`),groupByField:v().optional().describe(`Field to group leaf tasks by (synthesized summary rows)`),resourceView:b().optional().describe(`Render a per-resource workload histogram instead of the timeline`),assigneeField:v().optional().describe(`Resource field to bucket load by (resource view)`),effortField:v().optional().describe(`Per-task load units (resource view; default 1)`),capacity:y().optional().describe(`Per-resource capacity ceiling; loads above this flag overload`),tooltipFields:w(E([v(),T({field:v(),label:v().optional()})])).optional().describe(`Fields to surface in the hover tooltip, in display order`),quickFilters:w(aw).optional().describe(`Multi-select filter dropdowns rendered above the chart`),autoZoomToFilter:b().optional().describe(`When true (default), filtering zooms the range to the filtered tasks`)}).passthrough()),sw=H(()=>T({parentField:v().optional().describe(`Single-parent pointer field (auto-detected from the object schema when omitted)`),labelField:v().optional().describe(`Field rendered indented in the first column (defaults to "name")`),fields:w(v()).optional().describe(`Additional fields rendered as flat columns alongside the label`),defaultExpandedDepth:y().int().min(0).optional().describe(`Initial expansion depth (0 = roots only; omit = expand all)`)}).passthrough()),cw=H(()=>A([`page`,`drawer`,`modal`,`split`,`popover`,`new_window`,`none`])),lw=H(()=>T({mode:cw.default(`page`),view:v().optional().describe(`Name of the form view to use for details (e.g. "summary_view", "edit_form")`),preventNavigation:b().default(!1).describe(`Disable standard navigation entirely`),openNewTab:b().default(!1).describe(`Force open in new tab (applies to page mode)`),width:E([v(),y()]).optional().describe(`Width of the drawer/modal (e.g. "600px", "50%")`)})),uw=H(()=>T({name:BS.optional().describe(`Internal view name (lowercase snake_case)`),label:oC.optional(),type:A([`grid`,`kanban`,`gallery`,`calendar`,`timeline`,`gantt`,`map`,`chart`,`tree`]).default(`grid`),data:IC.optional().describe(`Data source configuration (defaults to "object" provider)`),columns:E([w(v()),w(zC)]).describe(`Fields to display as columns`),filter:w(LC).optional().describe(`Filter criteria (JSON Rules)`),sort:E([v(),w(T({field:v(),order:A([`asc`,`desc`])}))]).optional(),searchableFields:w(v()).optional().describe(`Fields enabled for search`),filterableFields:w(v()).optional().describe(`Legacy shorthand for userFilters.fields — bare field names enabled for end-user filtering. Prefer userFilters`),userFilters:ew.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:b().optional().describe(`Enable column resizing`),striped:b().optional().describe(`Striped row styling`),bordered:b().optional().describe(`Show borders`),compactToolbar:b().optional().describe(`Collapse Group/Color/Density/Hide-fields into a single View settings popover`),selection:BC.optional().describe(`Row selection configuration`),navigation:lw.optional().describe(`Configuration for item click navigation (page, drawer, modal, etc.)`),pagination:VC.optional().describe(`Pagination configuration`),kanban:nw.optional(),calendar:iw.optional(),gantt:ow.optional(),gallery:GC.optional(),timeline:KC.optional(),chart:rw.optional(),tree:sw.optional(),description:oC.optional().describe(`View description for documentation/tooltips`),sharing:qC.optional().describe(`View sharing and access configuration`),rowHeight:HC.optional().describe(`Row height / density setting`),grouping:WC.optional().describe(`Group records by one or more fields`),rowColor:JC.optional().describe(`Color rows based on field value`),hiddenFields:w(v()).optional().describe(`Fields to hide in this specific view`),fieldOrder:w(v()).optional().describe(`Explicit field display order for this view`),rowActions:w(v()).optional().describe(`Actions available for individual row items`),bulkActions:w(v()).optional().describe(`Actions available when multiple rows are selected`),bulkActionDefs:w(k(v(),x())).optional().describe(`Rich bulk action definitions (schema-driven, executed via BulkActionDialog)`),virtualScroll:b().optional().describe(`Enable virtual scrolling for large datasets`),conditionalFormatting:w(T({condition:WS.describe(`Predicate (CEL) to evaluate.`),style:k(v(),v()).describe(`CSS styles to apply when condition is true`)})).optional().describe(`Conditional formatting rules for list rows`),inlineEdit:b().optional().describe(`Allow inline editing of records directly in the list view`),exportOptions:w(A([`csv`,`xlsx`,`pdf`,`json`])).optional().describe(`Available export format options`),userActions:XC.optional().describe(`User action toggles for the view toolbar`),appearance:ZC.optional().describe(`Appearance and visualization configuration`),tabs:w(QC).optional().describe(`Tab definitions for multi-tab view interface`),addRecord:tw.optional().describe(`Add record entry point configuration`),showRecordCount:b().optional().describe(`Show record count at the bottom of the list`),allowPrinting:b().optional().describe(`Allow users to print the view`),emptyState:T({title:oC.optional(),message:oC.optional(),icon:v().optional()}).optional().describe(`Empty state configuration when no records found`),aria:sC.optional().describe(`ARIA accessibility attributes for the list view`),responsive:AC.optional().describe(`Responsive layout configuration`),performance:MC.optional().describe(`Performance optimization settings`)})),dw=H(()=>T({field:v().describe(`Field name (snake_case)`),type:KS.optional().describe(`Field type (auto-infers widget if omitted)`),options:w(qS).optional().describe(`Options for select/multiselect/radio/checkboxes fields`),reference:v().optional().describe(`Target object name for lookup/master_detail fields`),maxLength:y().optional().describe(`Maximum character length (for text/textarea/email/url/phone)`),minLength:y().optional().describe(`Minimum character length`),min:y().optional().describe(`Minimum value (for number/currency/percent/slider)`),max:y().optional().describe(`Maximum value`),precision:y().optional().describe(`Total digits (for number/currency)`),scale:y().optional().describe(`Decimal places`),multiple:b().optional().describe(`Allow multiple values (for select/lookup/file/image)`),label:oC.optional().describe(`Display label override`),placeholder:oC.optional().describe(`Placeholder text`),helpText:oC.optional().describe(`Help/hint text`),readonly:b().optional().describe(`Read-only override`),immutable:b().optional().describe(`Editable on create, locked once the record exists (e.g. machine names).`),required:b().optional().describe(`Required override`),hidden:b().optional().describe(`Hidden override`),colSpan:y().int().min(1).max(4).optional().describe(`Column span in grid layout (1-4)`),widget:v().optional().describe(`Custom widget/component name (overrides type-based inference)`),language:v().optional().describe(`Code editor language (for type=code)`),fields:w(M(()=>dw)).optional().describe(`Sub-fields for composite/repeater/record types`),keyField:T({field:v().default(`name`).describe(`Property name that holds the key inside each item (defaults to "name")`),label:oC.optional().describe(`Display label for the key column`),placeholder:oC.optional().describe(`Placeholder when entering a new key`),helpText:oC.optional().describe(`Help text under the key input`),regex:v().optional().describe(`JS regex source string the key must match (no flags)`),immutable:b().default(!0).describe(`If true, the key is read-only after creation`)}).optional().describe(`Key column config for record-typed fields`),dependsOn:v().optional().describe(`Parent field name for cascading`),visibleOn:WS.optional().describe(`Visibility predicate (CEL).`),disclosure:A([`inline`,`popover`]).optional().describe(`Composite rendering: inline bordered box (default) or a summary line + gear popover (progressive disclosure).`)})),fw=H(()=>T({name:v().optional().describe(`Stable section identifier for i18n lookup (snake_case)`),label:oC.optional(),description:v().optional().describe(`Optional description rendered under the section header.`),collapsible:b().default(!1),collapsed:b().default(!1),visibleOn:WS.optional().describe(`Visibility predicate (CEL). Hides the whole section when false.`),columns:E([A([`1`,`2`,`3`,`4`]),j(1),j(2),j(3),j(4)]).default(1).transform(e=>typeof e==`string`?parseInt(e):e),fields:w(E([v(),dw]))})),pw=H(()=>T({type:A([`simple`,`tabbed`,`wizard`,`split`,`drawer`,`modal`]).default(`simple`),data:IC.optional().describe(`Data source configuration (defaults to "object" provider)`),sections:w(fw).optional(),groups:w(fw).optional(),subforms:w(T({childObject:v().describe(`Child object whose records are entered inline`),relationshipField:v().optional().describe(`FK on the child pointing back to the parent (auto-detected when omitted)`),columns:w(x()).optional().describe(`Editable grid columns (derived from the child object when omitted)`),amountField:v().optional().describe(`Numeric child column summed for the running total`),totalField:v().optional().describe(`Parent field to receive the rolled-up sum`),title:v().optional().describe(`Section title`),addLabel:v().optional().describe(`Add-row button label`),minRows:y().optional(),maxRows:y().optional()})).optional().describe(`Inline master-detail child collections`),defaultSort:w(T({field:v().describe(`Field name to sort by`),order:A([`asc`,`desc`]).default(`desc`).describe(`Sort direction`)})).optional().describe(`Default sort order for related list views within this form`),sharing:EC.optional().describe(`Public sharing configuration for this form`),submitBehavior:E([T({kind:j(`thank-you`),title:v().optional(),message:v().optional()}),T({kind:j(`redirect`),url:v(),delayMs:y().int().min(0).optional()}),T({kind:j(`continue`)}),T({kind:j(`next-record`)})]).optional().describe(`Post-submit behavior`),aria:sC.optional().describe(`ARIA accessibility attributes for the form view`)}));H(()=>T({list:uw.optional(),form:pw.optional(),listViews:k(v(),uw).optional().describe(`Additional named list views`),formViews:k(v(),pw).optional().describe(`Additional named form views`),protection:TC.optional().describe(`Package author protection block — lock policy for this view.`),...wC}));var mw=v().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>`."),hw=A([`package`,`shared`,`personal`]).describe(`View identity layer: package | shared | personal.`);A([`list`,`form`]).describe("Whether `config` is a ListView (list family) or a FormView.");function gw(){return{name:mw,object:v().describe(`Bound object name — the foreign key used to aggregate views.`),label:oC.optional().describe(`Display label (supports i18n).`),isDefault:b().optional().describe(`Whether this is the object's default view in the switcher.`),order:y().int().optional().describe(`Sort order within the object's view switcher / left rail.`),scope:hw.optional().describe("Identity layer (defaults to `package` for source-loaded views)."),owner:v().optional().describe("Owner user id — set when `scope` is `personal`."),hidden:b().optional().describe(`Hidden from the switcher (per-user / per-org declutter).`),protection:TC.optional().describe(`Package author protection block — lock policy for this view.`),...wC}}H(()=>D(`viewKind`,[T({viewKind:j(`list`),config:uw.describe(`List-family view configuration.`),...gw()}),T({viewKind:j(`form`),config:pw.describe(`Form view configuration.`),...gw()})]));function _w(e){let{schemaId:t,...n}=e;return pw.parse({...n,data:{provider:`schema`,schemaId:t}})}var vw=A([`get`,`list`,`create`,`update`,`delete`,`upsert`,`bulk`,`aggregate`,`history`,`search`,`restore`,`purge`,`import`,`export`]),yw=T({trackHistory:b().default(!1).describe(`Enable field history tracking for audit compliance`),searchable:b().default(!0).describe(`Index records for global search`),apiEnabled:b().default(!0).describe(`Expose object via automatic APIs`),apiMethods:w(vw).optional().describe(`Whitelist of allowed API operations`),files:b().default(!1).describe(`Enable file attachments and document management`),feeds:b().default(!1).describe(`Enable social feed, comments, and mentions (Chatter-like)`),activities:b().default(!1).describe(`Enable standard tasks and events tracking`),trash:b().default(!0).describe(`Enable soft-delete with restore capability`),mru:b().default(!0).describe(`Track Most Recently Used (MRU) list for users`),clone:b().default(!0).describe(`Allow record deep cloning`)}),bw=H(()=>T({name:v().optional().describe(`Index name (auto-generated if not provided)`),fields:w(v()).describe(`Fields included in the index`),type:A([`btree`,`hash`,`gin`,`gist`,`fulltext`]).optional().default(`btree`).describe(`Index algorithm type`),unique:b().optional().default(!1).describe(`Whether the index enforces uniqueness`),partial:v().optional().describe(`Partial index condition (SQL WHERE clause for conditional indexes)`)})),xw=H(()=>T({fields:w(v()).describe(`Fields to index for full-text search weighting`),displayFields:w(v()).optional().describe(`Fields to display in search result cards`),filters:w(v()).optional().describe(`Default filters for search results`)})),Sw=H(()=>T({enabled:b().describe(`Enable multi-tenancy for this object`),strategy:A([`shared`,`isolated`,`hybrid`]).describe(`Tenant isolation strategy: shared (single DB, row-level), isolated (separate DB per tenant), hybrid (mix)`),tenantField:v().default(`tenant_id`).describe(`Field name for tenant identifier`),crossTenantAccess:b().default(!1).describe(`Allow cross-tenant data access (with explicit permission)`)})),Cw=H(()=>T({default:A([`public`,`private`]).default(`public`).describe(`Default exposure posture: public (covered by wildcard grants) | private (needs explicit grant; exempt from wildcard RLS).`)})),ww=H(()=>T({enabled:b().describe(`Enable soft delete (trash/recycle bin)`),field:v().default(`deleted_at`).describe(`Field name for soft delete timestamp`),cascadeDelete:b().default(!1).describe(`Cascade soft delete to related records`)})),Tw=H(()=>T({enabled:b().describe(`Enable record versioning`),strategy:A([`snapshot`,`delta`,`event-sourcing`]).describe(`Versioning strategy: snapshot (full copy), delta (changes only), event-sourcing (event log)`),retentionDays:y().min(1).optional().describe(`Number of days to retain old versions (undefined = infinite)`),versionField:v().default(`version`).describe(`Field name for version number/timestamp`)})),Ew=H(()=>T({enabled:b().describe(`Enable table partitioning`),strategy:A([`range`,`hash`,`list`]).describe(`Partitioning strategy: range (date ranges), hash (consistent hashing), list (predefined values)`),key:v().describe(`Field name to partition by`),interval:v().optional().describe(`Partition interval for range strategy (e.g., "1 month", "1 year")`)}).refine(e=>!(e.strategy===`range`&&!e.interval),{message:`interval is required when strategy is "range"`})),Dw=H(()=>T({key:v().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:v().describe(`Group display label`),icon:v().optional().describe(`Icon name (Lucide/Material) for the group header`),description:v().optional().describe(`Optional description shown under the group header`),defaultExpanded:b().optional().default(!0).describe(`Whether the group is expanded by default`),visibleOn:WS.optional().describe(`Visibility predicate (CEL); group is hidden when FALSE.`)})),Ow=T({remoteName:v().optional().describe(`Remote table/view name. Defaults to object.name.`),remoteSchema:v().optional().describe(`Remote schema/database qualifier.`),writable:b().default(!1).describe(`Per-object write opt-in (also requires datasource.external.allowWrites).`),columnMap:k(v(),v()).optional().describe(`Remote column name → local field name.`),introspectedAt:v().datetime().optional().describe("Set by `os datasource introspect`; informational."),ignoreColumns:w(v()).optional().describe(`Remote columns to skip during validation (dev convenience).`)}).describe(`External datasource binding (ADR-0015)`),kw=T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Machine unique key (snake_case). Immutable.`),label:v().optional().describe(`Human readable singular label (e.g. "Account")`),pluralLabel:v().optional().describe(`Human readable plural label (e.g. "Accounts")`),description:v().optional().describe(`Developer documentation / description`),icon:v().optional().describe(`Icon name (Lucide/Material) for UI representation`),tags:w(v()).optional().describe(`Categorization tags (e.g. "sales", "system", "reference")`),active:b().optional().default(!0).describe(`Is the object active and usable`),isSystem:b().optional().default(!1).describe(`Is system object (protected from deletion)`),abstract:b().optional().default(!1).describe(`Is abstract base object (cannot be instantiated)`),managedBy:A([`platform`,`config`,`system`,`append-only`,`better-auth`]).optional().describe(`Lifecycle bucket — platform (user CRUD) | config (admin authored) | system (engine-managed) | append-only (audit) | better-auth (identity). UI clients honour the resolved affordance matrix.`),userActions:T({create:b().optional().describe(`Show generic "New" button.`),import:b().optional().describe(`Show CSV import wizard entry.`),edit:b().optional().describe(`Allow inline / form edit of existing rows.`),delete:b().optional().describe(`Show row-level delete + bulk delete.`),exportCsv:b().optional().describe(`Show CSV export entry.`)}).optional().describe(`Per-object override of the resolved CRUD affordance matrix.`),systemFields:E([j(!1),T({tenant:b().optional().describe(`Inject organization_id (multi-tenant only). Default true.`),owner:b().optional().describe(`Reserved for future owner_id auto-injection.`),audit:b().optional().describe(`Reserved for future created_by/updated_by auto-injection.`)})]).optional().describe(`Opt out of, or selectively disable, registry-level system-field auto-injection.`),datasource:v().optional().default(`default`).describe(`Target Datasource ID. "default" is the primary DB.`),external:Ow.optional().describe(`Remote table binding for federated (external) objects.`),fields:k(v().regex(/^[a-z_][a-z0-9_]*$/,{message:`Field names must be lowercase snake_case (e.g., "first_name", "company", "annual_revenue")`}),ZS).describe(`Field definitions map. Keys must be snake_case identifiers.`),indexes:w(bw).optional().describe(`Database performance indexes`),fieldGroups:w(Dw).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:Sw.optional().describe(`Multi-tenancy configuration for SaaS applications`),access:Cw.optional().describe(`[ADR-0066 D2] Object exposure posture (public-by-default vs private secure-by-default).`),requiredPermissions:w(v()).optional().describe(`[ADR-0066 D3] Capabilities required to access this object (AND-gate, checked alongside CRUD grants).`),softDelete:ww.optional().describe(`Soft delete (trash/recycle bin) configuration`),versioning:Tw.optional().describe(`Record versioning and history tracking configuration`),partitioning:Ew.optional().describe(`Table partitioning configuration for performance`),validations:w(iC).optional().describe(`Object-level validation rules`),activityMilestones:w(T({field:v().describe(`Field to watch (typically a status/stage select).`),value:v().describe(`The value the field must transition INTO to fire the milestone.`),summary:v().describe(`Activity summary template; {field} tokens interpolate the record value. e.g. "Deal won: {name}".`),type:v().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).`),displayNameField:v().optional().describe(`Field to use as the record display name (e.g., "name", "title"). Defaults to "name" if present.`),recordName:T({type:A([`text`,`autonumber`]).describe(`Record name type: text (user-entered) or autonumber (system-generated)`),displayFormat:v().optional().describe(`Auto-number format pattern (e.g., "CASE-{0000}", "INV-{YYYY}-{0000}")`),startNumber:y().int().min(0).optional().describe(`Starting number for autonumber (default: 1)`)}).optional().describe(`Record name generation configuration (Salesforce pattern)`),titleFormat:GS.optional().describe(`Title template — supports {{record.field}} interpolation. Overrides displayNameField.`),compactLayout:w(v()).optional().describe(`Primary fields for hover/cards/lookups`),listViews:k(v(),uw).optional().describe(`Built-in named list views (segmented tabs) shipped with the object schema`),defaultDetailForm:v().optional().describe(`Name of the default FormView for record detail / edit screens`),searchableFields:w(v()).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."),search:xw.optional().describe(`Search engine configuration`),enable:yw.optional().describe(`Enabled system features modules`),sharingModel:A([`private`,`public_read`,`public_read_write`,`controlled_by_parent`,`read`,`read_write`,`full`]).optional().describe(`Org-Wide Default record visibility (OWD). Canonical: private (owner-only) | public_read (everyone reads, owner writes) | public_read_write (everyone reads+writes) | controlled_by_parent (derived from the master record). Legacy aliases: read=public_read, read_write/full=public_read_write. ADR-0056 D1.`),publicSharing:T({enabled:b().default(!1).describe(`Allow records of this object to be published via share link`),allowedAudiences:w(A([`public`,`link_only`,`signed_in`,`email`])).optional().describe(`Audiences callers may select when creating a link`),allowedPermissions:w(A([`view`,`comment`,`edit`])).optional().describe(`Permission levels selectable on the share dialog`),maxExpiryDays:y().int().positive().optional().describe(`Reject links with expiry beyond this many days`),redactFields:w(v()).optional().describe(`Field names removed from records served via a share token`),eligibility:v().optional().describe(`CEL expression that must evaluate to true on the target record`)}).optional().describe(`Public share-link policy (Notion/Figma-style link sharing)`),keyPrefix:v().max(5).optional().describe(`Short prefix for record IDs (e.g., "001" for Account)`),detail:T({renderViaSchema:b().optional().describe(`Opt this object out of the schema-driven detail renderer`),hideReferenceRail:b().optional().describe(`Suppress the right-hand reference-rail on the detail page`),hideRelatedTab:b().optional().describe(`Suppress the Related tab on the detail page`)}).passthrough().optional().describe(`Detail-page UI hints consumed by @object-ui/plugin-detail synth`),actions:w(bC).optional().describe(`Actions associated with this object (auto-populated from top-level actions via objectName)`),protection:TC.optional().describe(`Package author protection block — lock policy for this object.`),...wC});function Aw(e){return e.split(`_`).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `)}var jw={workflows:"`workflows` is not an ObjectSchema field. Object-level, record-triggered automation is authored as a lifecycle hook (`src/objects/<name>.hook.ts`, registered via `defineHook()`) 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, registered via `defineHook()`.",triggers:"`triggers` is not an ObjectSchema field. Use a lifecycle hook (`src/objects/<name>.hook.ts`) or a top-level `record_change` flow."};function Mw(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 Nw(e,t){let n,r=1/0;for(let i of t){let t=Mw(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 Pw(e,t,n){let r=typeof e==`string`&&e.length>0?e:`<unnamed>`,i=t.map(e=>{let t=jw[e];if(t)return` \u2022 ${t}`;let r=Nw(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(`, `)}.
|
|
78
|
+
These keys would previously have been stripped silently at build, shipping dead metadata with no diagnostic (ADR-0032 "no silent failure", issue #1535).
|
|
79
|
+
|
|
80
|
+
${i.join(`
|
|
81
|
+
`)}
|
|
82
|
+
|
|
83
|
+
Remove the unknown key(s), fix the typo, or move the logic to a supported mechanism.`)}var Fw=H(()=>Object.assign(kw,{create:e=>{let t=e,n=Object.keys(kw.shape),r=Object.keys(t).filter(e=>!n.includes(e));if(r.length>0)throw Pw(t.name,r,n);let i={...t,label:t.label??Aw(t.name)};return kw.parse(i)}}));A([`own`,`extend`]),H(()=>T({extend:v().describe(`Target object name (FQN) to extend`),fields:k(v(),ZS).optional().describe(`Fields to add/override`),label:v().optional().describe(`Override label for the extended object`),pluralLabel:v().optional().describe(`Override plural label for the extended object`),description:v().optional().describe(`Override description for the extended object`),validations:w(iC).optional().describe(`Additional validation rules to merge into the target object`),indexes:w(bw).optional().describe(`Additional indexes to merge into the target object`),priority:y().int().min(0).max(999).default(200).describe(`Merge priority (higher = applied later)`)}));var Iw=A([`beforeFind`,`afterFind`,`beforeFindOne`,`afterFindOne`,`beforeCount`,`afterCount`,`beforeAggregate`,`afterAggregate`,`beforeInsert`,`afterInsert`,`beforeUpdate`,`afterUpdate`,`beforeDelete`,`afterDelete`,`beforeUpdateMany`,`afterUpdateMany`,`beforeDeleteMany`,`afterDeleteMany`]),Lw=H(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Hook unique name (snake_case)`),label:v().optional().describe(`Description of what this hook does`),object:E([v(),w(v())]).describe(`Target object(s)`),events:w(Iw).describe(`Lifecycle events`),handler:E([v(),$l(e=>typeof e==`function`,{message:`Expected function`})]).optional().describe("Handler function name (string, post-build) or inline function (pre-build) — DEPRECATED, prefer `body`"),body:pC.optional().describe(`Hook body — expression (L1) or sandboxed JS (L2)`),priority:y().default(100).describe(`Execution priority`),async:b().default(!1).describe(`Run specifically as fire-and-forget`),condition:WS.optional().describe('Predicate (CEL); hook runs only when TRUE. e.g. P`record.status == "closed" && record.amount > 1000`'),description:v().optional().describe(`Human-readable description of what this hook does`),retryPolicy:T({maxRetries:y().default(3).describe(`Maximum retry attempts on failure`),backoffMs:y().default(1e3).describe(`Backoff delay between retries in milliseconds`)}).optional().describe(`Retry policy for failed hook executions`),timeout:y().optional().describe(`Maximum execution time in milliseconds before the hook is aborted`),onError:A([`abort`,`log`]).default(`abort`).describe(`Error handling strategy`)}));H(()=>T({id:v().optional().describe(`Unique execution ID for tracing`),object:v(),event:Iw,input:k(v(),S()).describe(`Mutable input parameters`),result:S().optional().describe(`Operation result (After hooks only)`),previous:k(v(),S()).optional().describe(`Record state before operation`),session:T({userId:v().optional(),tenantId:v().optional(),roles:w(v()).optional(),accessToken:v().optional(),isSystem:b().optional().describe(`True when the call was made with an elevated system context (engine self-writes)`)}).optional().describe(`Current session context`),transaction:S().optional().describe(`Database transaction handle`),ql:S().describe(`ObjectQL Engine Reference`),api:S().optional().describe(`Cross-object data access (ScopedContext)`),user:T({id:v().optional(),name:v().optional(),email:v().optional()}).optional().describe(`Current user info shortcut`)}));var Rw=A([`none`,`constant`,`lookup`,`split`,`join`,`javascript`,`map`]),zw=H(()=>T({source:E([v(),w(v())]).describe(`Source column header(s)`),target:E([v(),w(v())]).describe(`Target object field(s)`),transform:Rw.default(`none`),params:T({value:S().optional(),object:v().optional(),fromField:v().optional(),toField:v().optional(),autoCreate:b().optional(),valueMap:k(v(),S()).optional(),separator:v().optional()}).optional()})),Bw=H(()=>T({name:BS.describe(`Mapping unique name (lowercase snake_case)`),label:v().optional(),sourceFormat:A([`csv`,`json`,`xml`,`sql`]).default(`csv`),targetObject:v().describe(`Target Object Name`),fieldMapping:w(zw),mode:A([`insert`,`update`,`upsert`]).default(`insert`),upsertKey:w(v()).optional().describe(`Fields to match for upsert (e.g. email)`),extractQuery:AS.optional().describe(`Query to run for export only`),errorPolicy:A([`skip`,`abort`,`retry`]).default(`skip`),batchSize:y().default(1e3)})),Vw=H(()=>T({userId:v().optional(),actor:v().optional(),email:v().optional(),tenantId:v().optional(),timezone:v().optional(),locale:v().optional(),currency:v().optional(),roles:w(v()).default([]),permissions:w(v()).default([]),systemPermissions:w(v()).optional(),tabPermissions:k(v(),A([`visible`,`hidden`,`default_on`,`default_off`])).optional(),org_user_ids:w(v()).optional(),rlsMembership:k(v(),w(v())).optional(),isSystem:b().default(!1),accessToken:v().optional(),transaction:S().optional(),traceId:v().optional()})),Hw=H(()=>E([k(v(),S()),uS]).describe(`Data Engine query filter conditions`)),Uw=H(()=>E([k(v(),A([`asc`,`desc`])),k(v(),E([j(1),j(-1)])),w(gS)]).describe(`Sort order definition`)),Ww=H(()=>T({context:Vw.optional()})),Gw=H(()=>Ww.extend({where:E([k(v(),S()),uS]).optional(),fields:w(DS).optional(),orderBy:w(gS).optional(),limit:y().optional(),offset:y().optional(),top:y().optional(),cursor:k(v(),S()).optional(),search:OS.optional(),expand:M(()=>k(v(),AS)).optional(),distinct:b().optional()}).describe(`QueryAST-aligned query options for IDataEngine.find() operations`));H(()=>Ww.extend({filter:Hw.optional(),select:w(v()).optional(),sort:Uw.optional(),limit:y().int().min(1).optional(),skip:y().int().min(0).optional(),top:y().int().min(1).optional(),populate:w(v()).optional()}).describe(`Query options for IDataEngine.find() operations`));var Kw=H(()=>Ww.extend({returning:b().default(!0).optional()}).describe(`Options for DataEngine.insert operations`)),qw=H(()=>Ww.extend({where:E([k(v(),S()),uS]).optional(),upsert:b().default(!1).optional(),multi:b().default(!1).optional(),returning:b().default(!1).optional()}).describe(`QueryAST-aligned options for DataEngine.update operations`));H(()=>Ww.extend({filter:Hw.optional(),upsert:b().default(!1).optional(),multi:b().default(!1).optional(),returning:b().default(!1).optional()}).describe(`Options for DataEngine.update operations`));var Jw=H(()=>Ww.extend({where:E([k(v(),S()),uS]).optional(),multi:b().default(!1).optional()}).describe(`QueryAST-aligned options for DataEngine.delete operations`));H(()=>Ww.extend({filter:Hw.optional(),multi:b().default(!1).optional()}).describe(`Options for DataEngine.delete operations`));var Yw=H(()=>Ww.extend({where:E([k(v(),S()),uS]).optional(),groupBy:w(v()).optional(),aggregations:w(bS).optional(),timezone:v().optional()}).describe(`QueryAST-aligned options for DataEngine.aggregate operations`));H(()=>Ww.extend({filter:Hw.optional(),groupBy:w(v()).optional(),aggregations:w(T({field:v(),method:A([`count`,`sum`,`avg`,`min`,`max`,`count_distinct`]),alias:v().optional()})).optional()}).describe(`Options for DataEngine.aggregate operations`));var Xw=H(()=>Ww.extend({where:E([k(v(),S()),uS]).optional()}).describe(`QueryAST-aligned options for DataEngine.count operations`));H(()=>Ww.extend({filter:Hw.optional()}).describe(`Options for DataEngine.count operations`)),H(()=>T({find:P().input(O([v(),Gw.optional()])).output(N(w(S()))),findOne:P().input(O([v(),Gw.optional()])).output(N(S())),insert:P().input(O([v(),E([k(v(),S()),w(k(v(),S()))]),Kw.optional()])).output(N(S())),update:P().input(O([v(),k(v(),S()),qw.optional()])).output(N(S())),delete:P().input(O([v(),Jw.optional()])).output(N(S())),count:P().input(O([v(),Xw.optional()])).output(N(y())),aggregate:P().input(O([v(),Yw])).output(N(w(S())))}).describe(`Standard Data Engine Contract`));var Zw={filter:Hw.optional()},Qw=Gw.extend({...Zw,select:w(v()).optional(),sort:Uw.optional(),skip:y().int().min(0).optional(),populate:w(v()).optional()}),$w=H(()=>T({method:j(`find`),object:v(),query:Qw.optional()})),eT=H(()=>T({method:j(`findOne`),object:v(),query:Qw.optional()})),tT=H(()=>T({method:j(`insert`),object:v(),data:E([k(v(),S()),w(k(v(),S()))]),options:Kw.optional()})),nT=H(()=>T({method:j(`update`),object:v(),data:k(v(),S()),id:E([v(),y()]).optional().describe(`ID for single update, or use where in options`),options:qw.extend(Zw).optional()})),rT=H(()=>T({method:j(`delete`),object:v(),id:E([v(),y()]).optional().describe(`ID for single delete, or use where in options`),options:Jw.extend(Zw).optional()})),iT=H(()=>T({method:j(`count`),object:v(),query:Xw.extend(Zw).optional()})),aT=H(()=>T({method:j(`aggregate`),object:v(),query:Yw.extend(Zw)})),oT=H(()=>T({method:j(`execute`),command:S(),options:k(v(),S()).optional()})),sT=H(()=>T({method:j(`vectorFind`),object:v(),vector:w(y()),where:E([k(v(),S()),uS]).optional(),fields:w(v()).optional(),limit:y().int().default(5).optional(),threshold:y().optional()})),cT=H(()=>T({method:j(`batch`),requests:w(D(`method`,[$w,eT,tT,nT,rT,iT,aT,oT,sT])),transaction:b().default(!0).optional()}));H(()=>D(`method`,[$w,eT,tT,nT,rT,iT,aT,cT,oT,sT]).describe(`Virtual ObjectQL Request Protocol`)),A([`count`,`sum`,`avg`,`min`,`max`,`count_distinct`,`percentile`,`median`,`stddev`,`variance`]).describe(`Standard aggregation functions`);var lT=A([`asc`,`desc`]).describe(`Sort order direction`);H(()=>T({field:v().describe(`Field name to sort by`),order:lT.describe(`Sort direction`)}).describe(`Sort field and direction pair`)),A([`insert`,`update`,`delete`,`upsert`]).describe(`Data mutation event types`);var uT=A([`read_uncommitted`,`read_committed`,`repeatable_read`,`serializable`,`snapshot`]).describe(`Transaction isolation levels (snake_case standard)`);A([`lru`,`lfu`,`ttl`,`fifo`]).describe(`Cache eviction strategy`);var dT=H(()=>T({transaction:S().optional().describe(`Transaction handle`),timeout:y().optional().describe(`Timeout in ms`),skipCache:b().optional().describe(`Bypass cache`),traceContext:k(v(),v()).optional().describe(`OpenTelemetry context or request ID`),tenantId:v().optional().describe(`Tenant Isolation identifier`),timezone:v().optional().describe(`Business reference timezone (IANA) for date-dependent generation, e.g. autonumber date tokens`)})),fT=H(()=>T({create:b().default(!0).describe(`Supports CREATE operations`),read:b().default(!0).describe(`Supports READ operations`),update:b().default(!0).describe(`Supports UPDATE operations`),delete:b().default(!0).describe(`Supports DELETE operations`),bulkCreate:b().default(!1).describe(`Supports bulk CREATE operations`),bulkUpdate:b().default(!1).describe(`Supports bulk UPDATE operations`),bulkDelete:b().default(!1).describe(`Supports bulk DELETE operations`),transactions:b().default(!1).describe(`Supports ACID transactions`),savepoints:b().default(!1).describe(`Supports transaction savepoints`),isolationLevels:w(uT).optional().describe(`Supported isolation levels`),queryFilters:b().default(!0).describe(`Supports WHERE clause filtering`),queryAggregations:b().default(!1).describe(`Supports GROUP BY and aggregation functions`),queryDateGranularity:k(vS,b()).optional().describe(`Per-granularity native date bucketing (day/week/month/quarter/year). Missing keys fall back to in-memory bucketing.`),querySorting:b().default(!0).describe(`Supports ORDER BY sorting`),queryPagination:b().default(!0).describe(`Supports LIMIT/OFFSET pagination`),queryWindowFunctions:b().default(!1).describe(`Supports window functions with OVER clause`),querySubqueries:b().default(!1).describe(`Supports subqueries`),queryCTE:b().default(!1).describe(`Supports Common Table Expressions (WITH clause)`),joins:b().default(!1).describe(`Supports SQL joins`),fullTextSearch:b().default(!1).describe(`Supports full-text search`),jsonQuery:b().default(!1).describe(`Supports JSON field querying`),geospatialQuery:b().default(!1).describe(`Supports geospatial queries`),streaming:b().default(!1).describe(`Supports result streaming (cursors/iterators)`),jsonFields:b().default(!1).describe(`Supports JSON field types`),arrayFields:b().default(!1).describe(`Supports array field types`),vectorSearch:b().default(!1).describe(`Supports vector embeddings and similarity search`),autonumber:b().optional().describe(`Driver natively generates persistent autonumber/sequence values`),schemaSync:b().default(!1).describe(`Supports automatic schema synchronization`),batchSchemaSync:b().default(!1).describe(`Supports batched schema sync to reduce schema DDL round-trips`),migrations:b().default(!1).describe(`Supports database migrations`),indexes:b().default(!1).describe(`Supports index creation and management`),connectionPooling:b().default(!1).describe(`Supports connection pooling`),preparedStatements:b().default(!1).describe(`Supports prepared statements (SQL injection prevention)`),queryCache:b().default(!1).describe(`Supports query result caching`)}));H(()=>T({name:v().describe(`Driver unique name`),version:v().describe(`Driver version`),supports:fT,connect:P().input(O([])).output(N(gl())).describe(`Establish connection`),disconnect:P().input(O([])).output(N(gl())).describe(`Close connection`),checkHealth:P().input(O([])).output(N(b())).describe(`Health check`),getPoolStats:P().input(O([])).output(T({total:y(),idle:y(),active:y(),waiting:y()}).optional()).optional().describe(`Get connection pool statistics`),execute:P().input(O([S(),w(S()).optional(),dT.optional()])).output(N(S())).describe(`Execute raw command`),find:P().input(O([v(),AS,dT.optional()])).output(N(w(k(v(),S())))).describe(`Find records`),findStream:P().input(O([v(),AS,dT.optional()])).output(S()).describe(`Stream records (AsyncIterable)`),findOne:P().input(O([v(),AS,dT.optional()])).output(N(k(v(),S()).nullable())).describe(`Find one record`),create:P().input(O([v(),k(v(),S()),dT.optional()])).output(N(k(v(),S()))).describe(`Create record`),update:P().input(O([v(),v().or(y()),k(v(),S()),dT.optional()])).output(N(k(v(),S()))).describe(`Update record`),upsert:P().input(O([v(),k(v(),S()),w(v()).optional(),dT.optional()])).output(N(k(v(),S()))).describe(`Upsert record`),delete:P().input(O([v(),v().or(y()),dT.optional()])).output(N(b())).describe(`Delete record`),count:P().input(O([v(),AS.optional(),dT.optional()])).output(N(y())).describe(`Count records`),bulkCreate:P().input(O([v(),w(k(v(),S())),dT.optional()])).output(N(w(k(v(),S())))),bulkUpdate:P().input(O([v(),w(T({id:v().or(y()),data:k(v(),S())})),dT.optional()])).output(N(w(k(v(),S())))),bulkDelete:P().input(O([v(),w(v().or(y())),dT.optional()])).output(N(gl())),updateMany:P().input(O([v(),AS,k(v(),S()),dT.optional()])).output(N(y())).optional(),deleteMany:P().input(O([v(),AS,dT.optional()])).output(N(y())).optional(),beginTransaction:P().input(O([T({isolationLevel:uT.optional()}).optional()])).output(N(S())).describe(`Start transaction`),commit:P().input(O([S()])).output(N(gl())).describe(`Commit transaction`),rollback:P().input(O([S()])).output(N(gl())).describe(`Rollback transaction`),syncSchema:P().input(O([v(),S(),dT.optional()])).output(N(gl())).describe(`Sync object schema to DB`),syncSchemasBatch:P().input(O([w(T({object:v(),schema:S()})),dT.optional()])).output(N(gl())).optional().describe(`Batch sync multiple schemas in one round-trip`),dropTable:P().input(O([v(),dT.optional()])).output(N(gl())),explain:P().input(O([v(),AS,dT.optional()])).output(N(S())).optional()}));var pT=H(()=>T({min:y().min(0).default(2).describe(`Minimum number of connections in pool`),max:y().min(1).default(10).describe(`Maximum number of connections in pool`),idleTimeoutMillis:y().min(0).default(3e4).describe(`Time in ms before idle connection is closed`),connectionTimeoutMillis:y().min(0).default(5e3).describe(`Time in ms to wait for available connection`)})),mT=H(()=>T({name:v().describe(`Driver instance name`),type:A([`sql`,`nosql`,`cache`,`search`,`graph`,`timeseries`]).describe(`Driver type category`),capabilities:fT.describe(`Driver capability flags`),connectionString:v().optional().describe(`Database connection string (driver-specific format)`),poolConfig:pT.optional().describe(`Connection pool configuration`)})),hT=H(()=>A([`postgresql`,`mysql`,`sqlite`,`mssql`,`oracle`,`mariadb`])),gT=H(()=>T({text:v().describe(`SQL type for text fields (e.g., VARCHAR, TEXT)`),number:v().describe(`SQL type for number fields (e.g., NUMERIC, DECIMAL, INT)`),boolean:v().describe(`SQL type for boolean fields (e.g., BOOLEAN, BIT)`),date:v().describe(`SQL type for date fields (e.g., DATE)`),datetime:v().describe(`SQL type for datetime fields (e.g., TIMESTAMP, DATETIME)`),json:v().optional().describe(`SQL type for JSON fields (e.g., JSON, JSONB)`),uuid:v().optional().describe(`SQL type for UUID fields (e.g., UUID, CHAR(36))`),binary:v().optional().describe(`SQL type for binary fields (e.g., BLOB, BYTEA)`)})),_T=H(()=>T({rejectUnauthorized:b().default(!0).describe(`Reject connections with invalid certificates`),ca:v().optional().describe(`CA certificate file path or content`),cert:v().optional().describe(`Client certificate file path or content`),key:v().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`}));H(()=>mT.extend({type:j(`sql`).describe(`Driver type must be "sql"`),dialect:hT.describe(`SQL database dialect`),dataTypeMapping:gT.describe(`SQL data type mapping configuration`),ssl:b().default(!1).describe(`Enable SSL/TLS connection`),sslConfig:_T.optional().describe(`SSL/TLS configuration (required when ssl is true)`)}).refine(e=>!(e.ssl&&!e.sslConfig),{message:`sslConfig is required when ssl is true`}));var vT=H(()=>A([`mongodb`,`couchdb`,`dynamodb`,`cassandra`,`redis`,`elasticsearch`,`neo4j`,`orientdb`]));H(()=>A([`find`,`findOne`,`insert`,`update`,`delete`,`aggregate`,`mapReduce`,`count`,`distinct`,`createIndex`,`dropIndex`]));var yT=H(()=>A([`all`,`quorum`,`one`,`local_quorum`,`each_quorum`,`eventual`])),bT=H(()=>A([`single`,`compound`,`unique`,`text`,`geospatial`,`hashed`,`ttl`,`sparse`])),xT=H(()=>T({enabled:b().default(!1).describe(`Enable sharding`),shardKey:v().optional().describe(`Field to use as shard key`),shardingStrategy:A([`hash`,`range`,`zone`]).optional().describe(`Sharding strategy`),numShards:y().int().positive().optional().describe(`Number of shards`)})),ST=H(()=>T({enabled:b().default(!1).describe(`Enable replication`),replicaSetName:v().optional().describe(`Replica set name`),replicas:y().int().positive().optional().describe(`Number of replicas`),readPreference:A([`primary`,`primaryPreferred`,`secondary`,`secondaryPreferred`,`nearest`]).optional().describe(`Read preference for replica set`),writeConcern:A([`majority`,`acknowledged`,`unacknowledged`]).optional().describe(`Write concern level`)})),CT=H(()=>T({enabled:b().default(!1).describe(`Enable schema validation`),validationLevel:A([`strict`,`moderate`,`off`]).optional().describe(`Validation strictness`),validationAction:A([`error`,`warn`]).optional().describe(`Action on validation failure`),jsonSchema:k(v(),S()).optional().describe(`JSON Schema for validation`)})),wT=H(()=>T({text:v().describe(`NoSQL type for text fields`),number:v().describe(`NoSQL type for number fields`),boolean:v().describe(`NoSQL type for boolean fields`),date:v().describe(`NoSQL type for date fields`),datetime:v().describe(`NoSQL type for datetime fields`),json:v().optional().describe(`NoSQL type for JSON/object fields`),uuid:v().optional().describe(`NoSQL type for UUID fields`),binary:v().optional().describe(`NoSQL type for binary fields`),array:v().optional().describe(`NoSQL type for array fields`),objectId:v().optional().describe(`NoSQL type for ObjectID fields (MongoDB)`),geopoint:v().optional().describe(`NoSQL type for geospatial point fields`)}));H(()=>mT.extend({type:j(`nosql`).describe(`Driver type must be "nosql"`),databaseType:vT.describe(`Specific NoSQL database type`),dataTypeMapping:wT.describe(`NoSQL data type mapping configuration`),consistency:yT.optional().describe(`Consistency level for operations`),replication:ST.optional().describe(`Replication configuration`),sharding:xT.optional().describe(`Sharding configuration`),schemaValidation:CT.optional().describe(`Document schema validation`),region:v().optional().describe(`AWS region (for managed NoSQL services)`),accessKeyId:v().optional().describe(`AWS access key ID`),secretAccessKey:v().optional().describe(`AWS secret access key`),ttlField:v().optional().describe(`Field name for TTL (auto-deletion)`),maxDocumentSize:y().int().positive().optional().describe(`Maximum document size in bytes`),collectionPrefix:v().optional().describe(`Prefix for collection/table names`)}));var TT=H(()=>T({consistency:yT.optional().describe(`Consistency level override`),readFromSecondary:b().optional().describe(`Allow reading from secondary replicas`),projection:k(v(),E([j(0),j(1)])).optional().describe(`Field projection`),timeout:y().int().positive().optional().describe(`Query timeout (ms)`),useCursor:b().optional().describe(`Use cursor instead of loading all results`),batchSize:y().int().positive().optional().describe(`Cursor batch size`),profile:b().optional().describe(`Enable query profiling`),hint:v().optional().describe(`Index hint for query optimization`)})),ET=H(()=>T({operator:v().describe(`Aggregation operator (e.g., $match, $group, $sort)`),options:k(v(),S()).describe(`Stage-specific options`)}));H(()=>T({collection:v().describe(`Collection/table name`),stages:w(ET).describe(`Aggregation pipeline stages`),options:TT.optional().describe(`Query options`)})),H(()=>T({name:v().describe(`Index name`),type:bT.describe(`Index type`),fields:w(T({field:v().describe(`Field name`),order:A([`asc`,`desc`,`text`,`2dsphere`]).optional().describe(`Index order or type`)})).describe(`Fields to index`),unique:b().default(!1).describe(`Enforce uniqueness`),sparse:b().default(!1).describe(`Sparse index`),expireAfterSeconds:y().int().positive().optional().describe(`TTL in seconds`),partialFilterExpression:k(v(),S()).optional().describe(`Partial index filter`),background:b().default(!1).describe(`Create index in background`)})),H(()=>T({readConcern:A([`local`,`majority`,`linearizable`,`snapshot`]).optional().describe(`Read concern level`),writeConcern:A([`majority`,`acknowledged`,`unacknowledged`]).optional().describe(`Write concern level`),readPreference:A([`primary`,`primaryPreferred`,`secondary`,`secondaryPreferred`,`nearest`]).optional().describe(`Read preference`),maxCommitTimeMS:y().int().positive().optional().describe(`Transaction commit timeout (ms)`)}));var DT=A([`insert`,`update`,`upsert`,`replace`,`ignore`]),OT=H(()=>T({object:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Target Object Name`),externalId:v().default(`name`).describe(`Field match for uniqueness check`),mode:DT.default(`upsert`).describe(`Conflict resolution strategy`),env:w(A([`prod`,`dev`,`test`])).default([`prod`,`dev`,`test`]).describe(`Applicable environments`),records:w(k(v(),S())).describe(`Data records`)}));_w({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:`tags`,type:`tags`,colSpan:2,helpText:`Categorization tags (e.g. "sales", "system")`},{field:`active`,type:`boolean`,colSpan:1,helpText:`Is the object active and usable`},{field:`isSystem`,type:`boolean`,colSpan:1,helpText:`System object (protected from deletion)`},{field:`abstract`,type:`boolean`,colSpan:1,helpText:`Abstract base (cannot be instantiated)`}]},{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:`indexed`,type:`boolean`,helpText:`Create a database index for faster querying`},{field:`readonly`,type:`boolean`,helpText:`Visible but never user-editable`},{field:`immutable`,type:`boolean`,helpText:`Editable on create, locked thereafter`},{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:`filterable`,type:`boolean`,helpText:`Allow filtering on this column`},{field:`defaultValue`,type:`text`,helpText:`Default value for new records (JSON literal)`},{field:`placeholder`,type:`text`,helpText:`Placeholder hint`},{field:`maxLength`,type:`number`,helpText:`Max characters`,visibleOn:`type in ['text','textarea','email','url','phone','password','markdown','html','richtext']`},{field:`minLength`,type:`number`,helpText:`Min characters`,visibleOn:`type in ['text','textarea','email','url','phone','password','markdown','html','richtext']`},{field:`min`,type:`number`,helpText:`Minimum value`,visibleOn:`type in ['number','currency','percent','rating','slider','progress']`},{field:`max`,type:`number`,helpText:`Maximum value`,visibleOn:`type in ['number','currency','percent','rating','slider','progress']`},{field:`precision`,type:`number`,helpText:`Total digits`,visibleOn:`type in ['number','currency','percent']`},{field:`scale`,type:`number`,helpText:`Decimal places`,visibleOn:`type in ['number','currency','percent']`},{field:`options`,type:`repeater`,helpText:`Available choices`,visibleOn:`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`,visibleOn:`type in ['lookup','master_detail','tree']`},{field:`referenceFilter`,type:`code`,language:`expression`,helpText:`CEL filter applied to the picker`,visibleOn:`type in ['lookup','master_detail']`},{field:`cascadeDelete`,type:`boolean`,helpText:`Delete children when parent is deleted`,visibleOn:`type == 'master_detail'`},{field:`multiple`,type:`boolean`,helpText:`Allow selecting multiple records`,visibleOn:`type in ['lookup']`},{field:`formula`,type:`code`,language:`expression`,helpText:`CEL formula expression`,visibleOn:`type == 'formula'`},{field:`returnType`,type:`select`,helpText:`Result type for formulas`,visibleOn:`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:`summaryType`,type:`select`,helpText:`Aggregation`,visibleOn:`type == 'summary'`,options:[{label:`Count`,value:`count`},{label:`Sum`,value:`sum`},{label:`Avg`,value:`avg`},{label:`Min`,value:`min`},{label:`Max`,value:`max`}]},{field:`summaryField`,type:`text`,helpText:`Field on child object to aggregate`,visibleOn:`type == 'summary'`},{field:`displayFormat`,type:`text`,helpText:`e.g. "INV-{0000}"`,visibleOn:`type == 'autonumber'`},{field:`startingNumber`,type:`number`,helpText:`Starting sequence value`,visibleOn:`type == 'autonumber'`},{field:`language`,type:`text`,helpText:`Editor language (e.g. sql, javascript)`,visibleOn:`type == 'code'`},{field:`validation`,type:`code`,language:`expression`,helpText:`CEL predicate — must evaluate true`},{field:`errorMessage`,type:`text`,helpText:`Shown when validation fails`},{field:`audit`,type:`boolean`,helpText:`Audit changes to this field`},{field:`trackHistory`,type:`boolean`,helpText:`Keep change history`},{field:`pii`,type:`boolean`,helpText:`Personally identifiable information`},{field:`encrypted`,type:`boolean`,helpText:`Encrypt at rest`}]}]},{name:`capabilities`,label:`Capabilities`,description:`System features and API exposure.`,collapsible:!0,collapsed:!0,fields:[{field:`capabilities`,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:`trash`,type:`boolean`},{field:`mru`,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")`}]}]}),_w({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`,visibleOn:`data.type == 'text' || data.type == 'textarea' || data.type == 'email'`,helpText:`Minimum character length`},{field:`maxLength`,visibleOn:`data.type == 'text' || data.type == 'textarea' || data.type == 'email'`,helpText:`Maximum character length`},{field:`min`,visibleOn:`data.type == 'number' || data.type == 'currency'`,helpText:`Minimum value`},{field:`max`,visibleOn:`data.type == 'number' || data.type == 'currency'`,helpText:`Maximum value`},{field:`precision`,visibleOn:`data.type == 'currency' || data.type == 'number'`,helpText:`Decimal places (e.g., 2 for $10.50)`},{field:`scale`,visibleOn:`data.type == 'number'`,helpText:`Number of decimal digits`},{field:`options`,type:`repeater`,visibleOn:`data.type == 'select' || data.type == 'multiselect'`,helpText:`Available options (label/value pairs)`},{field:`reference`,widget:`ref:object`,visibleOn:`data.type == 'lookup' || data.type == 'master_detail'`,helpText:`Referenced object name`},{field:`referenceFilters`,widget:`string-tags`,visibleOn:`data.type == 'lookup' || data.type == 'master_detail'`,helpText:`Filter expressions (e.g., "active = true")`},{field:`deleteBehavior`,visibleOn:`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`,helpText:`Roll-up summary configuration (for parent-child relationships)`}]},{name:`advanced`,label:`Advanced`,description:`Database, UI, audit, and security settings.`,collapsible:!0,collapsed:!0,columns:2,fields:[{field:`columnName`,colSpan:2,helpText:`Physical column name in database (defaults to field name)`},{field:`index`,colSpan:1,helpText:`Create database index for faster queries`},{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`}]}]}),_w({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)`}]}]},{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)`}]}]}]});var kT=H(()=>T({field:v().describe(`Source field name containing the reference value`),targetObject:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Target object name (snake_case)`),targetField:v().default(`name`).describe(`Field on target object used for matching`),fieldType:A([`lookup`,`master_detail`,`user`]).describe(`Relationship field type`)}).describe(`Describes how a field reference is resolved during seed loading`)),AT=H(()=>T({object:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Object name (snake_case)`),dependsOn:w(v()).describe(`Objects this object depends on`),references:w(kT).describe(`Field-level reference details`)}).describe(`Object node in the seed data dependency graph`)),jT=H(()=>T({nodes:w(AT).describe(`All objects in the dependency graph`),insertOrder:w(v()).describe(`Topologically sorted insert order`),circularDependencies:w(w(v())).default([]).describe(`Circular dependency chains (e.g., [["a", "b", "a"]])`)}).describe(`Complete object dependency graph for seed data loading`)),MT=H(()=>T({sourceObject:v().describe(`Object with the broken reference`),field:v().describe(`Field name with unresolved reference`),targetObject:v().describe(`Target object searched for the reference`),targetField:v().describe(`ExternalId field used for matching`),attemptedValue:S().describe(`Value that failed to resolve`),recordIndex:y().int().min(0).describe(`Index of the record in the dataset`),message:v().describe(`Human-readable error description`)}).describe(`Actionable error for a failed reference resolution`)),NT=T({user:T({id:v().min(1),role:v().optional(),email:v().optional()}).optional().describe(`Subject bound to os.user in seed CEL expressions`),org:T({id:v().min(1),tier:v().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`),PT=H(()=>T({dryRun:b().default(!1).describe(`Validate references without writing data`),haltOnError:b().default(!1).describe(`Stop on first reference resolution error`),multiPass:b().default(!0).describe(`Enable multi-pass loading for circular dependencies`),defaultMode:DT.default(`upsert`).describe(`Default conflict resolution strategy`),batchSize:y().int().min(1).default(1e3).describe(`Maximum records per batch insert/upsert`),transaction:b().default(!1).describe(`Wrap entire load in a transaction (all-or-nothing)`),env:A([`prod`,`dev`,`test`]).optional().describe(`Only load datasets matching this environment`),organizationId:v().min(1).optional().describe(`Target organization id for per-tenant seed replay`),identity:NT.optional().describe(`Identity bound to os.user / os.org when resolving CEL seed values`)}).describe(`Seed data loader configuration`)),FT=H(()=>T({object:v().describe(`Object that was loaded`),mode:DT.describe(`Import mode used`),inserted:y().int().min(0).describe(`Records inserted`),updated:y().int().min(0).describe(`Records updated`),skipped:y().int().min(0).describe(`Records skipped`),errored:y().int().min(0).describe(`Records with errors`),total:y().int().min(0).describe(`Total records in dataset`),referencesResolved:y().int().min(0).describe(`References resolved via externalId`),referencesDeferred:y().int().min(0).describe(`References deferred to second pass`),errors:w(MT).default([]).describe(`Reference resolution errors`)}).describe(`Result of loading a single dataset`));H(()=>T({success:b().describe(`Overall success status`),dryRun:b().describe(`Whether this was a dry-run`),dependencyGraph:jT.describe(`Object dependency graph`),results:w(FT).describe(`Per-object load results`),errors:w(MT).describe(`All reference resolution errors`),summary:T({objectsProcessed:y().int().min(0).describe(`Total objects processed`),totalRecords:y().int().min(0).describe(`Total records across all objects`),totalInserted:y().int().min(0).describe(`Total records inserted`),totalUpdated:y().int().min(0).describe(`Total records updated`),totalSkipped:y().int().min(0).describe(`Total records skipped`),totalErrored:y().int().min(0).describe(`Total records with errors`),totalReferencesResolved:y().int().min(0).describe(`Total references resolved`),totalReferencesDeferred:y().int().min(0).describe(`Total references deferred`),circularDependencyCount:y().int().min(0).describe(`Circular dependency chains detected`),durationMs:y().min(0).describe(`Load duration in milliseconds`)}).describe(`Summary statistics`)}).describe(`Complete seed loader result`)),H(()=>T({seeds:w(OT).min(1).describe(`Seeds to load`),config:PT.default(()=>PT.parse({})).describe(`Loader configuration`)}).describe(`Seed loader request with datasets and configuration`));var IT=H(()=>T({versionNumber:y().describe(`Version number`),createdAt:y().describe(`Creation timestamp`),createdBy:v().describe(`Creator user ID`),size:y().describe(`File size in bytes`),checksum:v().describe(`File checksum`),downloadUrl:v().url().describe(`Download URL`),isLatest:b().optional().default(!1).describe(`Is latest version`)})),LT=H(()=>T({id:v().describe(`Template ID`),name:v().describe(`Template name`),description:v().optional().describe(`Template description`),fileUrl:v().url().describe(`Template file URL`),fileType:v().describe(`File MIME type`),placeholders:w(T({key:v().describe(`Placeholder key`),label:v().describe(`Placeholder label`),type:A([`text`,`number`,`date`,`image`]).describe(`Placeholder type`),required:b().optional().default(!1).describe(`Is required`)})).describe(`Template placeholders`)})),RT=H(()=>T({provider:A([`docusign`,`adobe-sign`,`hellosign`,`custom`]).describe(`E-signature provider`),enabled:b().optional().default(!1).describe(`E-signature enabled`),signers:w(T({email:v().email().describe(`Signer email`),name:v().describe(`Signer name`),role:v().describe(`Signer role`),order:y().describe(`Signing order`)})).describe(`Document signers`),expirationDays:y().optional().default(30).describe(`Expiration days`),reminderDays:y().optional().default(7).describe(`Reminder interval days`)}));H(()=>T({id:v().describe(`Document ID`),name:v().describe(`Document name`),description:v().optional().describe(`Document description`),fileType:v().describe(`File MIME type`),fileSize:y().describe(`File size in bytes`),category:v().optional().describe(`Document category`),tags:w(v()).optional().describe(`Document tags`),versioning:T({enabled:b().describe(`Versioning enabled`),versions:w(IT).describe(`Version history`),majorVersion:y().describe(`Major version`),minorVersion:y().describe(`Minor version`)}).optional().describe(`Version control`),template:LT.optional().describe(`Document template`),eSignature:RT.optional().describe(`E-signature config`),access:T({isPublic:b().optional().default(!1).describe(`Public access`),sharedWith:w(v()).optional().describe(`Shared with`),expiresAt:y().optional().describe(`Access expiration`)}).optional().describe(`Access control`),metadata:k(v(),S()).optional().describe(`Custom metadata`)}));var zT=H(()=>D(`type`,[T({type:j(`constant`),value:S().describe(`Constant value to use`)}).describe(`Set a constant value`),T({type:j(`cast`),targetType:A([`string`,`number`,`boolean`,`date`]).describe(`Target data type`)}).describe(`Cast to a specific data type`),T({type:j(`lookup`),table:v().describe(`Lookup table name`),keyField:v().describe(`Field to match on`),valueField:v().describe(`Field to retrieve`)}).describe(`Lookup value from another table`),T({type:j(`javascript`),expression:WS.describe(`JS expression (dialect="js" recommended). e.g. value.toUpperCase()`)}).describe(`Custom JavaScript transformation`),T({type:j(`map`),mappings:k(v(),S()).describe(`Value mappings (e.g., {"Active": "active"})`)}).describe(`Map values using a dictionary`)])),BT=H(()=>T({source:v().describe(`Source field name`),target:v().describe(`Target field name`),transform:zT.optional().describe(`Transformation to apply`),defaultValue:S().optional().describe(`Default if source is null/undefined`)})),VT=H(()=>T({id:v().describe(`Data source ID`),name:v().describe(`Data source name`),type:A([`odata`,`rest-api`,`graphql`,`custom`]).describe(`Protocol type`),endpoint:v().url().describe(`API endpoint URL`),authentication:T({type:A([`oauth2`,`api-key`,`basic`,`none`]).describe(`Auth type`),config:k(v(),S()).describe(`Auth configuration`)}).describe(`Authentication`)})),HT=H(()=>BT.extend({type:v().optional().describe(`Field type`),readonly:b().optional().default(!0).describe(`Read-only field`)}));H(()=>T({fieldName:v().describe(`Field name`),dataSource:VT.describe(`External data source`),query:T({endpoint:v().describe(`Query endpoint path`),method:A([`GET`,`POST`]).optional().default(`GET`).describe(`HTTP method`),parameters:k(v(),S()).optional().describe(`Query parameters`)}).describe(`Query configuration`),fieldMappings:w(HT).describe(`Field mappings`),caching:T({enabled:b().optional().default(!0).describe(`Cache enabled`),ttl:y().optional().default(300).describe(`Cache TTL (seconds)`),strategy:A([`lru`,`lfu`,`ttl`]).optional().default(`ttl`).describe(`Cache strategy`)}).optional().describe(`Caching configuration`),fallback:T({enabled:b().optional().default(!0).describe(`Fallback enabled`),defaultValue:S().optional().describe(`Default fallback value`),showError:b().optional().default(!0).describe(`Show error to user`)}).optional().describe(`Fallback configuration`),rateLimit:T({requestsPerSecond:y().describe(`Requests per second limit`),burstSize:y().optional().describe(`Burst size`)}).optional().describe(`Rate limiting`),retry:T({maxRetries:y().min(0).default(3).describe(`Maximum retry attempts`),initialDelayMs:y().default(1e3).describe(`Initial retry delay in milliseconds`),maxDelayMs:y().default(3e4).describe(`Maximum retry delay in milliseconds`),backoffMultiplier:y().default(2).describe(`Exponential backoff multiplier`),retryableStatusCodes:w(y()).default([429,500,502,503,504]).describe(`HTTP status codes that are retryable`)}).optional().describe(`Retry configuration with exponential backoff`),transform:T({request:T({headers:k(v(),v()).optional().describe(`Additional request headers`),queryParams:k(v(),v()).optional().describe(`Additional query parameters`)}).optional().describe(`Request transformation`),response:T({dataPath:v().optional().describe(`JSONPath to extract data (e.g., "$.data.results")`),totalPath:v().optional().describe(`JSONPath to extract total count (e.g., "$.meta.total")`)}).optional().describe(`Response transformation`)}).optional().describe(`Request/response transformation pipeline`),pagination:T({type:A([`offset`,`cursor`,`page`]).default(`offset`).describe(`Pagination type`),pageSize:y().default(100).describe(`Items per page`),maxPages:y().optional().describe(`Maximum number of pages to fetch`)}).optional().describe(`Pagination configuration for external data`)}));var UT=v().describe(`Underlying driver identifier`);H(()=>T({id:v().describe(`Unique driver identifier (e.g. "postgres")`),label:v().describe(`Display label (e.g. "PostgreSQL")`),description:v().optional(),icon:v().optional(),configSchema:k(v(),S()).describe(`JSON Schema for connection configuration`),capabilities:M(()=>WT).optional()}));var WT=T({transactions:b().default(!1),queryFilters:b().default(!1),queryAggregations:b().default(!1),querySorting:b().default(!1),queryPagination:b().default(!1),queryWindowFunctions:b().default(!1),querySubqueries:b().default(!1),joins:b().default(!1),fullTextSearch:b().default(!1),readOnly:b().default(!1),dynamicSchema:b().default(!1)}),GT=A([`managed`,`external`,`validate-only`]).describe(`Schema ownership mode`),KT=T({label:v().optional().describe(`Display label, e.g. "Snowflake — ANALYTICS / PROD"`),allowedSchemas:w(v()).optional().describe(`Whitelist of remote schemas/databases that may be exposed.`),allowWrites:b().default(!1).describe(`Global write gate. Individual objects must also opt in via object.external.writable.`),validation:T({onMismatch:A([`fail`,`warn`,`ignore`]).default(`fail`).describe(`What to do when a federated object diverges from the remote table.`),checkOnBoot:b().default(!0).describe(`Validate federated objects against the remote schema at boot.`),checkIntervalMs:y().optional().describe(`Optional background drift-check interval in milliseconds.`)}).default({onMismatch:`fail`,checkOnBoot:!0}).describe(`Boot/drift validation policy`),credentialsRef:v().optional().describe(`Reference into the secrets store; never inline credentials.`),queryTimeoutMs:y().default(3e4).describe(`Hard cap on per-query execution time.`),requirePermission:v().optional().describe(`Optional convenience: gate the entire datasource behind a single role.`)}).describe(`External datasource federation settings (schemaMode != "managed")`);H(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Unique datasource identifier`),label:v().optional().describe(`Display label`),driver:UT.describe(`Underlying driver type`),config:k(v(),S()).describe(`Driver specific configuration`),pool:T({min:y().default(0).describe(`Minimum connections`),max:y().default(10).describe(`Maximum connections`),idleTimeoutMillis:y().default(3e4).describe(`Idle timeout`),connectionTimeoutMillis:y().default(3e3).describe(`Connection establishment timeout`)}).optional().describe(`Connection pool settings`),readReplicas:w(k(v(),S())).optional().describe(`Read-only replica configurations`),capabilities:WT.optional().describe(`Capability overrides`),healthCheck:T({enabled:b().default(!0).describe(`Enable health check endpoint`),intervalMs:y().default(3e4).describe(`Health check interval in milliseconds`),timeoutMs:y().default(5e3).describe(`Health check timeout in milliseconds`)}).optional().describe(`Datasource health check configuration`),ssl:T({enabled:b().default(!1).describe(`Enable SSL/TLS for database connection`),rejectUnauthorized:b().default(!0).describe(`Reject connections with invalid/self-signed certificates`),ca:v().optional().describe(`CA certificate (PEM format or path to file)`),cert:v().optional().describe(`Client certificate (PEM format or path to file)`),key:v().optional().describe(`Client private key (PEM format or path to file)`)}).optional().describe(`SSL/TLS configuration for secure database connections`),retryPolicy:T({maxRetries:y().default(3).describe(`Maximum number of retry attempts`),baseDelayMs:y().default(1e3).describe(`Base delay between retries in milliseconds`),maxDelayMs:y().default(3e4).describe(`Maximum delay between retries in milliseconds`),backoffMultiplier:y().default(2).describe(`Exponential backoff multiplier`)}).optional().describe(`Connection retry policy for transient failures`),description:v().optional().describe(`Internal description`),active:b().default(!0).describe(`Is datasource enabled`),autoConnect:b().default(!1).describe(`Force a live driver connection at boot even when managed + unrouted (ADR-0062 D2).`),schemaMode:GT.default(`managed`),external:KT.optional(),origin:A([`code`,`runtime`]).default(`code`).describe(`Datasource provenance (server-managed, read-only)`)}).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'.`})}));var qT=T({name:v().describe(`Remote column name`),sqlType:v().describe(`Raw remote SQL type (e.g. "numeric(10,2)")`),nullable:b().describe(`Whether the remote column is nullable`),primaryKey:b().default(!1).describe(`Part of the remote primary key`),suggestedFieldType:v().optional().describe(`ObjectStack field type suggested by the type-compat matrix`)}),JT=T({remoteSchema:v().optional().describe(`Remote schema/database qualifier`),remoteName:v().describe(`Remote table/view name`),columns:w(qT).describe(`Remote columns`),indexes:w(T({name:v(),columns:w(v()),unique:b()})).optional().describe(`Remote indexes, when introspectable`),rowCountEstimate:y().optional().describe(`Approximate row count`)});H(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe("Catalog id, conventionally `<datasource>_catalog`."),datasource:v().describe(`Datasource.name this catalog snapshots.`),snapshotAt:v().datetime().describe(`When the snapshot was taken (ISO 8601).`),dialect:v().optional().describe(`Remote SQL dialect, when known.`),tables:w(JT).describe(`Snapshotted remote tables.`)}));var YT=A([`count`,`sum`,`avg`,`min`,`max`,`count_distinct`,`number`,`string`,`boolean`]),XT=A([`string`,`number`,`boolean`,`time`,`geo`]),ZT=A([`second`,`minute`,`hour`,`day`,`week`,`month`,`quarter`,`year`]),QT=H(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Unique metric ID`),label:v().describe(`Human readable label`),description:v().optional(),type:YT,sql:v().describe(`SQL expression or field reference`),filters:w(T({sql:v()})).optional(),format:v().optional()})),$T=H(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Unique dimension ID`),label:v().describe(`Human readable label`),description:v().optional(),type:XT,sql:v().describe(`SQL expression or column reference`),granularities:w(ZT).optional()})),eE=H(()=>T({name:v().describe(`Target cube name`),relationship:A([`one_to_one`,`one_to_many`,`many_to_one`]).default(`many_to_one`),sql:v().describe(`Join condition (ON clause)`)})),tE=H(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Cube name (snake_case)`),title:v().optional(),description:v().optional(),sql:v().describe(`Base SQL statement or Table Name`),measures:k(v(),QT).describe(`Quantitative metrics`),dimensions:k(v(),$T).describe(`Qualitative attributes`),joins:k(v(),eE).optional(),refreshKey:T({every:v().optional(),sql:v().optional()}).optional(),public:b().default(!1)}));H(()=>T({cube:v().optional().describe(`Target cube name (optional when provided externally, e.g. in API request wrapper)`),measures:w(v()).describe(`List of metrics to calculate`),dimensions:w(v()).optional().describe(`List of dimensions to group by`),where:uS.optional().describe(`Filtering criteria (canonical Query DSL FilterCondition)`),timeDimensions:w(T({dimension:v(),granularity:ZT.optional(),dateRange:E([v(),w(v())]).optional()})).optional(),order:k(v(),A([`asc`,`desc`])).optional(),limit:y().optional(),offset:y().optional(),timezone:v().optional().default(`UTC`)}));var nE=A([`comment`,`field_change`,`task`,`event`,`email`,`call`,`note`,`file`,`record_create`,`record_delete`,`approval`,`sharing`,`system`]),rE=H(()=>T({type:A([`user`,`team`,`record`]).describe(`Mention target type`),id:v().describe(`Target ID`),name:v().describe(`Display name for rendering`),offset:y().int().min(0).describe(`Character offset in body text`),length:y().int().min(1).describe(`Length of mention token in body text`)})),iE=H(()=>T({field:v().describe(`Field machine name`),fieldLabel:v().optional().describe(`Field display label`),oldValue:S().optional().describe(`Previous value`),newValue:S().optional().describe(`New value`),oldDisplayValue:v().optional().describe(`Human-readable old value`),newDisplayValue:v().optional().describe(`Human-readable new value`)})),aE=H(()=>T({emoji:v().describe(`Emoji character or shortcode (e.g., "👍", ":thumbsup:")`),userIds:w(v()).describe(`Users who reacted`),count:y().int().min(1).describe(`Total reaction count`)})),oE=H(()=>T({type:A([`user`,`system`,`service`,`automation`]).describe(`Actor type`),id:v().describe(`Actor ID`),name:v().optional().describe(`Actor display name`),avatarUrl:v().url().optional().describe(`Actor avatar URL`),source:v().optional().describe(`Source application (e.g., "Omni", "API", "Studio")`)})),sE=A([`public`,`internal`,`private`]);H(()=>T({id:v().describe(`Feed item ID`),type:nE.describe(`Activity type`),object:v().describe(`Object name (e.g., "account")`),recordId:v().describe(`Record ID this feed item belongs to`),actor:oE.describe(`Who performed this action`),body:v().optional().describe(`Rich text body (Markdown supported)`),mentions:w(rE).optional().describe(`Mentioned users/teams/records`),changes:w(iE).optional().describe(`Field-level changes`),reactions:w(aE).optional().describe(`Emoji reactions on this item`),parentId:v().optional().describe(`Parent feed item ID for threaded replies`),replyCount:y().int().min(0).default(0).describe(`Number of replies`),pinned:b().default(!1).describe(`Whether the feed item is pinned to the top of the timeline`),pinnedAt:v().datetime().optional().describe(`Timestamp when the item was pinned`),pinnedBy:v().optional().describe(`User ID who pinned the item`),starred:b().default(!1).describe(`Whether the feed item is starred/bookmarked by the current user`),starredAt:v().datetime().optional().describe(`Timestamp when the item was starred`),visibility:sE.default(`public`).describe(`Visibility: public (all users), internal (team only), private (author + mentioned)`),createdAt:v().datetime().describe(`Creation timestamp`),updatedAt:v().datetime().optional().describe(`Last update timestamp`),editedAt:v().datetime().optional().describe(`When comment was last edited`),isEdited:b().default(!1).describe(`Whether comment has been edited`)})),A([`all`,`comments_only`,`changes_only`,`tasks_only`]);var cE=A([`comment`,`mention`,`field_change`,`task`,`approval`,`all`]),lE=A([`in_app`,`email`,`push`,`slack`]);H(()=>T({object:v().describe(`Object name`),recordId:v().describe(`Record ID`),userId:v().describe(`Subscribing user ID`),events:w(cE).default([`all`]).describe(`Event types to receive notifications for`),channels:w(lE).default([`in_app`]).describe(`Notification delivery channels`),active:b().default(!0).describe(`Whether the subscription is active`),createdAt:v().datetime().describe(`Subscription creation timestamp`)}));var uE=(t=>e===void 0?typeof Proxy<`u`?new Proxy(t,{get:(t,n)=>(e===void 0?t:e)[n]}):t:e)(function(t){if(e!==void 0)return e.apply(this,arguments);throw Error(`Dynamic require of "`+t+`" is not supported`)}),dE={debug:0,info:1,warn:2,error:3,fatal:4,silent:5},fE={debug:`\x1B[36m`,info:`\x1B[32m`,warn:`\x1B[33m`,error:`\x1B[31m`,fatal:`\x1B[35m`,silent:``},pE=`\x1B[0m`,mE=class e{constructor(e={},t={}){this.config={name:e.name,level:e.level??`info`,format:e.format??`pretty`,redact:e.redact??[`password`,`token`,`secret`,`key`],sourceLocation:e.sourceLocation??!1,file:e.file,rotation:e.rotation??{maxSize:`10m`,maxFiles:5}},this.bindings=t,this.config.file&&typeof process<`u`&&this.openFileStream(this.config.file)}openFileStream(e){try{let t=uE(`fs`),n=uE(`path`).dirname(e);t.mkdirSync(n,{recursive:!0}),this.fileStream=t.createWriteStream(e,{flags:`a`})}catch{}}isEnabled(e){return dE[e]>=dE[this.config.level]}redactSensitive(e){if(!e||typeof e!=`object`)return e;let t=Array.isArray(e)?[...e]:{...e};for(let e in t){let n=e.toLowerCase();this.config.redact.some(e=>n.includes(e.toLowerCase()))?t[e]=`***REDACTED***`:typeof t[e]==`object`&&t[e]!==null&&(t[e]=this.redactSensitive(t[e]))}return t}write(e,t,n,r){if(!this.isEnabled(e))return;let i=this.redactSensitive({...this.bindings,...n,...r?{error:{message:r.message,stack:r.stack}}:{}}),a=Object.keys(i).length>0,o=new Date().toISOString(),s;if(this.config.format===`json`)s=JSON.stringify({time:o,level:e,...this.config.name?{name:this.config.name}:{},msg:t,...i});else if(this.config.format===`text`){let n=[o,e.toUpperCase(),t];a&&n.push(JSON.stringify(i)),s=n.join(` | `)}else{let n=fE[e]||``,r=this.config.name?`[${this.config.name}] `:``;s=`${n}${o} ${e.toUpperCase()}${pE} ${r}${t}`,a&&(s+=` ${JSON.stringify(i)}`)}let c=s+`
|
|
84
|
+
`;typeof process<`u`&&process.stderr?e===`error`||e===`fatal`?process.stderr.write(c):process.stdout?.write(c):typeof console<`u`&&(e===`error`||e===`fatal`?console.error:e===`warn`?console.warn:e===`debug`?console.debug:console.log)(s),this.fileStream&&this.fileStream.write(c)}debug(e,t){this.write(`debug`,e,t)}info(e,t){this.write(`info`,e,t)}warn(e,t){this.write(`warn`,e,t)}error(e,t,n){t instanceof Error?this.write(`error`,e,n,t):this.write(`error`,e,t)}fatal(e,t,n){t instanceof Error?this.write(`fatal`,e,n,t):this.write(`fatal`,e,t)}log(e,...t){this.info(e,t.length>0?{args:t}:void 0)}child(t){let n=new e(this.config,{...this.bindings,...t});return n.fileStream=this.fileStream,n}withTrace(e,t){return this.child({traceId:e,spanId:t})}async destroy(){this.fileStream&&=(await new Promise(e=>this.fileStream.end(e)),void 0)}};function hE(e){return new mE(e)}var gE=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=[]}},_E=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/${e}?type=${t}`);return this.unwrapResponse(r)}},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`);return(await this.fetch(`${this.baseUrl}${t}/meta/${e}`)).json()},explain:async e=>{let t=this.getRoute(`analytics`);return(await this.fetch(`${this.baseUrl}${t}/explain`,{method:`POST`,body:JSON.stringify(e)})).json()}},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})});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)}},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)},listTemplates:async()=>{let e=await this.fetch(`${this.baseUrl}/api/v1/cloud/templates`);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.origin+`/login`,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};return(await this.fetch(`${this.baseUrl}${r}/upload/complete`,{method:`POST`,body:JSON.stringify(o)})).json()},getDownloadUrl:async e=>{let t=this.getRoute(`storage`);return(await(await this.fetch(`${this.baseUrl}${t}/files/${e}/url`)).json()).url},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)},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)}},this.permissions={check:async e=>{let t=this.getRoute(`permissions`),n=new URLSearchParams({object:e.object,action:e.action});e.recordId!==void 0&&n.set(`recordId`,e.recordId),e.field!==void 0&&n.set(`field`,e.field);let r=await this.fetch(`${this.baseUrl}${t}/check?${n.toString()}`);return this.unwrapResponse(r)},getObjectPermissions:async e=>{let t=this.getRoute(`permissions`),n=await this.fetch(`${this.baseUrl}${t}/objects/${encodeURIComponent(e)}`);return this.unwrapResponse(n)},getEffectivePermissions:async()=>{let e=this.getRoute(`permissions`),t=await this.fetch(`${this.baseUrl}${e}/effective`);return this.unwrapResponse(t)}},this.realtime={connect:async e=>{let t=this.getRoute(`realtime`),n=await this.fetch(`${this.baseUrl}${t}/connect`,{method:`POST`,body:JSON.stringify(e||{})});return this.unwrapResponse(n)},disconnect:async()=>{let e=this.getRoute(`realtime`);await this.fetch(`${this.baseUrl}${e}/disconnect`,{method:`POST`})},subscribe:async e=>{let t=this.getRoute(`realtime`),n=await this.fetch(`${this.baseUrl}${t}/subscribe`,{method:`POST`,body:JSON.stringify(e)});return this.unwrapResponse(n)},unsubscribe:async e=>{let t=this.getRoute(`realtime`);await this.fetch(`${this.baseUrl}${t}/unsubscribe`,{method:`POST`,body:JSON.stringify({subscriptionId:e})})},setPresence:async(e,t)=>{let n=this.getRoute(`realtime`);await this.fetch(`${this.baseUrl}${n}/presence`,{method:`PUT`,body:JSON.stringify({channel:e,state:t})})},getPresence:async e=>{let t=this.getRoute(`realtime`),n=await this.fetch(`${this.baseUrl}${t}/presence/${encodeURIComponent(e)}`);return this.unwrapResponse(n)}},this.workflow={getConfig:async e=>{let t=this.getRoute(`workflow`),n=await this.fetch(`${this.baseUrl}${t}/${encodeURIComponent(e)}/config`);return this.unwrapResponse(n)},getState:async(e,t)=>{let n=this.getRoute(`workflow`),r=await this.fetch(`${this.baseUrl}${n}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/state`);return this.unwrapResponse(r)},transition:async e=>{let t=this.getRoute(`workflow`),n=await this.fetch(`${this.baseUrl}${t}/${encodeURIComponent(e.object)}/${encodeURIComponent(e.recordId)}/transition`,{method:`POST`,body:JSON.stringify({transition:e.transition,comment:e.comment,data:e.data})});return this.unwrapResponse(n)}},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})});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})});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.views={list:async(e,t)=>{let n=this.getRoute(`views`),r=new URLSearchParams;t&&r.set(`type`,t);let i=r.toString(),a=await this.fetch(`${this.baseUrl}${n}/${encodeURIComponent(e)}${i?`?${i}`:``}`);return this.unwrapResponse(a)},get:async(e,t)=>{let n=this.getRoute(`views`),r=await this.fetch(`${this.baseUrl}${n}/${encodeURIComponent(e)}/${encodeURIComponent(t)}`);return this.unwrapResponse(r)},create:async(e,t)=>{let n=this.getRoute(`views`),r=await this.fetch(`${this.baseUrl}${n}/${encodeURIComponent(e)}`,{method:`POST`,body:JSON.stringify({object:e,data:t})});return this.unwrapResponse(r)},update:async(e,t,n)=>{let r=this.getRoute(`views`),i=await this.fetch(`${this.baseUrl}${r}/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{method:`PUT`,body:JSON.stringify({object:e,viewId:t,data:n})});return this.unwrapResponse(i)},delete:async(e,t)=>{let n=this.getRoute(`views`),r=await this.fetch(`${this.baseUrl}${n}/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{method:`DELETE`});return this.unwrapResponse(r)}},this.notifications={registerDevice:async e=>{let t=this.getRoute(`notifications`),n=await this.fetch(`${this.baseUrl}${t}/devices`,{method:`POST`,body:JSON.stringify(e)});return this.unwrapResponse(n)},unregisterDevice:async e=>{let t=this.getRoute(`notifications`),n=await this.fetch(`${this.baseUrl}${t}/devices/${encodeURIComponent(e)}`,{method:`DELETE`});return this.unwrapResponse(n)},getPreferences:async()=>{let e=this.getRoute(`notifications`),t=await this.fetch(`${this.baseUrl}${e}/preferences`);return this.unwrapResponse(t)},updatePreferences:async e=>{let t=this.getRoute(`notifications`),n=await this.fetch(`${this.baseUrl}${t}/preferences`,{method:`PUT`,body:JSON.stringify({preferences:e})});return this.unwrapResponse(n)},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={nlq:async e=>{let t=this.getRoute(`ai`),n=await this.fetch(`${this.baseUrl}${t}/nlq`,{method:`POST`,body:JSON.stringify(e)});return this.unwrapResponse(n)},suggest:async e=>{let t=this.getRoute(`ai`),n=await this.fetch(`${this.baseUrl}${t}/suggest`,{method:`POST`,body:JSON.stringify(e)});return this.unwrapResponse(n)},insights:async e=>{let t=this.getRoute(`ai`),n=await this.fetch(`${this.baseUrl}${t}/insights`,{method:`POST`,body:JSON.stringify(e)});return this.unwrapResponse(n)}},this.i18n={getLocales:async()=>{let e=this.getRoute(`i18n`),t=await this.fetch(`${this.baseUrl}${e}/locales`);return this.unwrapResponse(t)},getTranslations:async(e,t)=>{let n=this.getRoute(`i18n`),r=new URLSearchParams;r.set(`locale`,e),t?.namespace&&r.set(`namespace`,t.namespace),t?.keys&&r.set(`keys`,t.keys.join(`,`));let i=await this.fetch(`${this.baseUrl}${n}/translations?${r.toString()}`);return this.unwrapResponse(i)},getFieldLabels:async(e,t)=>{let n=this.getRoute(`i18n`),r=await this.fetch(`${this.baseUrl}${n}/labels/${encodeURIComponent(e)}?locale=${encodeURIComponent(t)}`);return this.unwrapResponse(r)}},this.feed={list:async(e,t,n)=>{let r=this.getRoute(`data`),i=new URLSearchParams;n?.type&&i.set(`type`,n.type),n?.limit&&i.set(`limit`,String(n.limit)),n?.cursor&&i.set(`cursor`,n.cursor);let a=i.toString(),o=await this.fetch(`${this.baseUrl}${r}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/feed${a?`?${a}`:``}`);return this.unwrapResponse(o)},create:async(e,t,n)=>{let r=this.getRoute(`data`),i=await this.fetch(`${this.baseUrl}${r}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/feed`,{method:`POST`,body:JSON.stringify(n)});return this.unwrapResponse(i)},update:async(e,t,n,r)=>{let i=this.getRoute(`data`),a=await this.fetch(`${this.baseUrl}${i}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/feed/${encodeURIComponent(n)}`,{method:`PUT`,body:JSON.stringify(r)});return this.unwrapResponse(a)},delete:async(e,t,n)=>{let r=this.getRoute(`data`),i=await this.fetch(`${this.baseUrl}${r}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/feed/${encodeURIComponent(n)}`,{method:`DELETE`});return this.unwrapResponse(i)},addReaction:async(e,t,n,r)=>{let i=this.getRoute(`data`),a=await this.fetch(`${this.baseUrl}${i}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/feed/${encodeURIComponent(n)}/reactions`,{method:`POST`,body:JSON.stringify({emoji:r})});return this.unwrapResponse(a)},removeReaction:async(e,t,n,r)=>{let i=this.getRoute(`data`),a=await this.fetch(`${this.baseUrl}${i}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/feed/${encodeURIComponent(n)}/reactions/${encodeURIComponent(r)}`,{method:`DELETE`});return this.unwrapResponse(a)},pin:async(e,t,n)=>{let r=this.getRoute(`data`),i=await this.fetch(`${this.baseUrl}${r}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/feed/${encodeURIComponent(n)}/pin`,{method:`POST`});return this.unwrapResponse(i)},unpin:async(e,t,n)=>{let r=this.getRoute(`data`),i=await this.fetch(`${this.baseUrl}${r}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/feed/${encodeURIComponent(n)}/pin`,{method:`DELETE`});return this.unwrapResponse(i)},star:async(e,t,n)=>{let r=this.getRoute(`data`),i=await this.fetch(`${this.baseUrl}${r}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/feed/${encodeURIComponent(n)}/star`,{method:`POST`});return this.unwrapResponse(i)},unstar:async(e,t,n)=>{let r=this.getRoute(`data`),i=await this.fetch(`${this.baseUrl}${r}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/feed/${encodeURIComponent(n)}/star`,{method:`DELETE`});return this.unwrapResponse(i)},search:async(e,t,n,r)=>{let i=this.getRoute(`data`),a=new URLSearchParams;a.set(`query`,n),r?.type&&a.set(`type`,r.type),r?.actorId&&a.set(`actorId`,r.actorId),r?.dateFrom&&a.set(`dateFrom`,r.dateFrom),r?.dateTo&&a.set(`dateTo`,r.dateTo),r?.limit&&a.set(`limit`,String(r.limit)),r?.cursor&&a.set(`cursor`,r.cursor);let o=await this.fetch(`${this.baseUrl}${i}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/feed/search?${a.toString()}`);return this.unwrapResponse(o)},getChangelog:async(e,t,n)=>{let r=this.getRoute(`data`),i=new URLSearchParams;n?.field&&i.set(`field`,n.field),n?.actorId&&i.set(`actorId`,n.actorId),n?.dateFrom&&i.set(`dateFrom`,n.dateFrom),n?.dateTo&&i.set(`dateTo`,n.dateTo),n?.limit&&i.set(`limit`,String(n.limit)),n?.cursor&&i.set(`cursor`,n.cursor);let a=i.toString(),o=await this.fetch(`${this.baseUrl}${r}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/changelog${a?`?${a}`:``}`);return this.unwrapResponse(o)},subscribe:async(e,t,n)=>{let r=this.getRoute(`data`),i=await this.fetch(`${this.baseUrl}${r}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/subscribe`,{method:`POST`,body:JSON.stringify(n||{})});return this.unwrapResponse(i)},unsubscribe:async(e,t)=>{let n=this.getRoute(`data`),r=await this.fetch(`${this.baseUrl}${n}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/subscribe`,{method:`DELETE`});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)},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)},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)}},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||hE({level:e.debug?`debug`:`info`,format:`pretty`}),this.realtimeAPI=new gE(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 vE(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 pS(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=n?.code||n?.error?.code,o=Error(`[ObjectStack] ${a?`${a}: `:``}${i}`);throw o.code=a,o.category=n?.category,o.httpStatus=r.status,o.retryable=n?.retryable,o.details=n?.details||n,o}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`,permissions:`/api/v1/permissions`,realtime:`/api/v1/realtime`,workflow:`/api/v1/workflow`,approvals:`/api/v1/approvals`,views:`/api/v1/ui/views`,notifications:`/api/v1/notifications`,ai:`/api/v1/ai`,i18n:`/api/v1/i18n`,feed:`/api/v1/feed`,graphql:`/graphql`}[e]||`/api/v1/${e}`}},vE=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)},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)},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)}},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}`}},yE=t({AIKnowledgeSchema:()=>PE,AIModelConfigSchema:()=>ME,AIToolSchema:()=>NE,AgentSchema:()=>RE,BlueprintAppSchema:()=>NO,BlueprintDashboardSchema:()=>jO,BlueprintFieldSchema:()=>OO,BlueprintNavItemSchema:()=>MO,BlueprintObjectSchema:()=>kO,BlueprintSeedSchema:()=>PO,BlueprintViewSchema:()=>AO,CodeContentSchema:()=>eO,ConversationContextSchema:()=>cO,ConversationMessageSchema:()=>iO,EmbeddingModelSchema:()=>vO,FileContentSchema:()=>$D,FileKnowledgeSourceSchema:()=>wO,FunctionCallSchema:()=>nO,HttpKnowledgeSourceSchema:()=>TO,ImageContentSchema:()=>QD,KnowledgeRefreshPolicySchema:()=>SO,KnowledgeSourceKindSchema:()=>EO,MCPApprovalPolicySchema:()=>xO,MCPTransportSchema:()=>bO,MessageContentSchema:()=>tO,MessageRoleSchema:()=>XD,ModelCapabilitySchema:()=>uO,ModelConfigSchema:()=>pO,ModelLimitsSchema:()=>dO,ModelPricingSchema:()=>fO,ModelProviderSchema:()=>lO,ModelRegistryEntrySchema:()=>gO,ObjectKnowledgeSourceSchema:()=>CO,PromptTemplateSchema:()=>hO,PromptVariableSchema:()=>mO,SkillSchema:()=>JD,SkillTriggerConditionSchema:()=>qD,StructuredOutputConfigSchema:()=>LE,StructuredOutputFormatSchema:()=>FE,TextContentSchema:()=>ZD,TokenBudgetConfigSchema:()=>oO,TokenBudgetStrategySchema:()=>aO,TokenUsageSchema:()=>YD,TokenUsageStatsSchema:()=>sO,ToolCallSchema:()=>rO,ToolCategorySchema:()=>GD,ToolSchema:()=>KD,TransformPipelineStepSchema:()=>IE,VectorStoreProviderSchema:()=>_O,VectorStoreSchema:()=>yO}),bE=A([`none`,`no-overlay`,`no-delete`,`full`]),xE=A([`artifact`,`package`,`env-forced`]),SE=A([`package`,`org`,`env-forced`]),CE={_lock:bE.optional().describe(`Item-level lock — controls overlay & delete (ADR-0010).`),_lockReason:v().max(500).optional().describe(`Human-readable reason shown when a write is refused by _lock.`),_lockSource:xE.optional().describe(`Layer that set _lock (artifact | package | env-forced).`),_provenance:SE.optional().describe(`Origin of the item (package | org | env-forced).`),_packageId:v().optional().describe(`Owning package machine id.`),_packageVersion:v().optional().describe(`Owning package version.`),_lockDocsUrl:v().optional().describe(`Optional documentation link surfaced next to _lockReason.`)},wE=T({lock:bE.describe(`Lock policy — none | no-overlay | no-delete | full.`),reason:v().min(1).max(500).describe(`User-visible reason shown when the lock blocks an action.`),docsUrl:v().url().optional().describe(`Optional URL the Studio banner links to for more context.`)}).strict();function U(e){if(typeof process<`u`&&{}.OS_EAGER_SCHEMAS===`1`)return e();let t,n=()=>(t===void 0&&(t=e()),t);return new Proxy(function(){},{get(e,t){let r=n(),i=r[t];return typeof i==`function`?i.bind(r):i},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())}})}var TE=U(()=>v().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)`)),EE=U(()=>v().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)`));U(()=>v().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 DE=U(()=>E([v().describe(`Action Name`),T({type:v(),params:k(v(),S()).optional()})])),OE=U(()=>E([v().describe(`Guard Name (e.g., "isManager", "amountGT1000")`),T({type:v(),params:k(v(),S()).optional()})])),kE=U(()=>T({target:v().optional().describe(`Target State ID`),cond:OE.optional().describe(`Condition (Guard) required to take this path`),actions:w(DE).optional().describe(`Actions to execute during transition`),description:v().optional().describe(`Human readable description of this rule`)}));U(()=>T({type:v().describe(`Event Type (e.g. "APPROVE", "REJECT", "Submit")`),schema:k(v(),S()).optional().describe(`Expected event payload structure`)}));var AE=M(()=>T({type:A([`atomic`,`compound`,`parallel`,`final`,`history`]).default(`atomic`),entry:w(DE).optional().describe(`Actions to run when entering this state`),exit:w(DE).optional().describe(`Actions to run when leaving this state`),on:k(v(),E([v(),kE,w(kE)])).optional().describe(`Map of Event Type -> Transition Definition`),always:w(kE).optional(),initial:v().optional().describe(`Initial child state (if compound)`),states:k(v(),AE).optional(),meta:T({label:v().optional(),description:v().optional(),color:v().optional(),aiInstructions:v().optional().describe(`Specific instructions for AI when in this state`)}).optional()})),jE=U(()=>T({id:EE.describe(`Unique Machine ID`),description:v().optional(),contextSchema:k(v(),S()).optional().describe(`Zod Schema for the machine context/memory`),initial:v().describe(`Initial State ID`),states:k(v(),AE).describe(`State Nodes`),on:k(v(),E([v(),kE,w(kE)])).optional()})),ME=U(()=>T({provider:A([`openai`,`azure_openai`,`anthropic`,`local`]).default(`openai`),model:v().describe(`Model name (e.g. gpt-4, claude-3-opus)`),temperature:y().min(0).max(2).default(.7),maxTokens:y().optional(),topP:y().optional()})),NE=U(()=>T({type:A([`action`,`flow`,`query`,`vector_search`]),name:v().describe(`Reference name (Action Name, Flow Name)`),description:v().optional().describe(`Override description for the LLM`)})),PE=U(()=>T({topics:w(v()).describe(`Topics/Tags to recruit knowledge from`),indexes:w(v()).describe(`Vector Store Indexes`)})),FE=U(()=>A([`json_object`,`json_schema`,`regex`,`grammar`,`xml`]).describe(`Output format for structured agent responses`)),IE=U(()=>A([`trim`,`parse_json`,`validate`,`coerce_types`]).describe(`Post-processing step for structured output`)),LE=U(()=>T({format:FE.describe(`Expected output format`),schema:k(v(),S()).optional().describe(`JSON Schema definition for output`),strict:b().default(!1).describe(`Enforce exact schema compliance`),retryOnValidationFailure:b().default(!0).describe(`Retry generation when output fails validation`),maxRetries:y().int().min(0).default(3).describe(`Maximum retries on validation failure`),fallbackFormat:FE.optional().describe(`Fallback format if primary format fails`),transformPipeline:w(IE).optional().describe(`Post-processing steps applied to output`)}).describe(`Structured output configuration for agent responses`)),RE=U(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Agent unique identifier`),label:v().describe(`Agent display name`),avatar:v().optional(),role:v().describe(`The persona/role (e.g. "Senior Support Engineer")`),instructions:v().describe(`System Prompt / Prime Directives`),model:ME.optional(),lifecycle:jE.optional().describe(`State machine defining the agent conversation follow and constraints`),surface:A([`ask`,`build`]).default(`ask`).describe(`Product surface this agent binds ('ask' | 'build') — ADR-0063 §1`),skills:w(v().regex(/^[a-z_][a-z0-9_]*$/)).optional().describe(`Skill names to attach (Agent→Skill→Tool architecture)`),tools:w(NE).optional().describe(`Direct tool references (legacy fallback)`),knowledge:PE.optional().describe(`RAG access`),active:b().default(!0),access:w(v()).optional().describe(`Who can chat with this agent`),permissions:w(v()).optional().describe(`Required permissions or roles`),tenantId:v().optional().describe(`Tenant/Organization ID`),visibility:A([`global`,`organization`,`private`]).default(`organization`),planning:T({strategy:A([`react`,`plan_and_execute`,`reflexion`,`tree_of_thought`]).default(`react`).describe(`Autonomous reasoning strategy`),maxIterations:y().int().min(1).max(100).default(10).describe(`Maximum planning loop iterations`),allowReplan:b().default(!0).describe(`Allow dynamic re-planning based on intermediate results`)}).optional().describe(`Autonomous reasoning and planning configuration`),memory:T({longTerm:T({enabled:b().default(!1).describe(`Enable long-term memory persistence`),store:A([`vector`,`database`,`redis`]).default(`vector`).describe(`Long-term memory storage backend`),maxEntries:y().int().min(1).optional().describe(`Max entries in long-term memory`)}).optional().describe(`Long-term / persistent memory`),reflectionInterval:y().int().min(1).optional().describe(`Reflect every N interactions to improve behavior`)}).optional().describe(`Agent memory management`),guardrails:T({maxTokensPerInvocation:y().int().min(1).optional().describe(`Token budget per single invocation`),maxExecutionTimeSec:y().int().min(1).optional().describe(`Max execution time in seconds`),blockedTopics:w(v()).optional().describe(`Forbidden topics or action names`)}).optional().describe(`Safety guardrails for the agent`),structuredOutput:LE.optional().describe(`Structured output format and validation configuration`),protection:wE.optional().describe(`Package author protection block — lock policy for this agent.`),...CE})),zE=A([`cel`,`js`,`cron`,`template`]),BE=T({rationale:v().optional(),generatedBy:v().optional()}),VE=T({dialect:zE,source:v().min(1).optional(),ast:S().optional(),meta:BE.optional()}).refine(e=>e.source!==void 0||e.ast!==void 0,{message:"Expression requires at least one of `source` or `ast`"}),HE=E([v().min(1).transform(e=>({dialect:`cel`,source:e})),VE]);E([v().min(1).transform(e=>({dialect:`cron`,source:e})),VE]);var UE=E([v().min(1).transform(e=>({dialect:`template`,source:e})),VE]);U(()=>T({key:v().describe(`Translation key (e.g., "views.task_list.label")`),defaultValue:v().optional().describe(`Fallback value when translation key is not found`),params:k(v(),E([v(),y(),b()])).optional().describe(`Interpolation parameters (e.g., { count: 5 })`)}));var WE=U(()=>v().describe(`Display label (plain string; i18n keys are auto-generated by the framework)`)),GE=U(()=>T({ariaLabel:WE.optional().describe(`Accessible label for screen readers (WAI-ARIA aria-label)`),ariaDescribedBy:v().optional().describe(`ID of element providing additional description (WAI-ARIA aria-describedby)`),role:v().optional().describe(`WAI-ARIA role attribute (e.g., "dialog", "navigation", "alert")`)}).describe(`ARIA accessibility attributes`));U(()=>T({key:v().describe(`Translation key`),zero:v().optional().describe(`Zero form (e.g., "No items")`),one:v().optional().describe(`Singular form (e.g., "{count} item")`),two:v().optional().describe(`Dual form (e.g., "{count} items" for exactly 2)`),few:v().optional().describe(`Few form (e.g., for 2-4 in some languages)`),many:v().optional().describe(`Many form (e.g., for 5+ in some languages)`),other:v().describe(`Default plural form (e.g., "{count} items")`)}).describe(`ICU plural rules for a translation key`));var KE=U(()=>T({style:A([`decimal`,`currency`,`percent`,`unit`]).default(`decimal`).describe(`Number formatting style`),currency:v().optional().describe(`ISO 4217 currency code (e.g., "USD", "EUR")`),unit:v().optional().describe(`Unit for unit formatting (e.g., "kilometer", "liter")`),minimumFractionDigits:y().optional().describe(`Minimum number of fraction digits`),maximumFractionDigits:y().optional().describe(`Maximum number of fraction digits`),useGrouping:b().optional().describe(`Whether to use grouping separators (e.g., 1,000)`)}).describe(`Number formatting rules`)),qE=U(()=>T({dateStyle:A([`full`,`long`,`medium`,`short`]).optional().describe(`Date display style`),timeStyle:A([`full`,`long`,`medium`,`short`]).optional().describe(`Time display style`),timeZone:v().optional().describe(`IANA time zone (e.g., "America/New_York")`),hour12:b().optional().describe(`Use 12-hour format`)}).describe(`Date/time formatting rules`));U(()=>T({code:v().describe(`BCP 47 language code (e.g., "en-US", "zh-CN")`),fallbackChain:w(v()).optional().describe(`Fallback language codes in priority order (e.g., ["zh-TW", "en"])`),direction:A([`ltr`,`rtl`]).default(`ltr`).describe(`Text direction: left-to-right or right-to-left`),numberFormat:KE.optional().describe(`Default number formatting rules`),dateFormat:qE.optional().describe(`Default date/time formatting rules`)}).describe(`Locale configuration`));var JE=U(()=>T({enabled:b().default(!1).describe(`Enable public sharing`),publicLink:v().optional().describe(`Generated public share URL`),password:v().optional().describe(`Password required to access shared link`),allowedDomains:w(v()).optional().describe(`Restrict access to specific email domains (e.g. ["example.com"])`),expiresAt:v().optional().describe(`Expiration date/time in ISO 8601 format`),allowAnonymous:b().optional().default(!1).describe(`Allow access without authentication`)}));U(()=>T({enabled:b().default(!1).describe(`Enable iframe embedding`),allowedOrigins:w(v()).optional().describe(`Allowed iframe parent origins (e.g. ["https://example.com"])`),width:v().optional().default(`100%`).describe(`Embed width (CSS value)`),height:v().optional().default(`600px`).describe(`Embed height (CSS value)`),showHeader:b().optional().default(!0).describe(`Show interface header in embed`),showNavigation:b().optional().default(!1).describe(`Show navigation in embed`),responsive:b().optional().default(!0).describe(`Enable responsive resizing`)}));var YE=A([`xs`,`sm`,`md`,`lg`,`xl`,`2xl`]),XE=U(()=>T({xs:y().min(1).max(12).optional(),sm:y().min(1).max(12).optional(),md:y().min(1).max(12).optional(),lg:y().min(1).max(12).optional(),xl:y().min(1).max(12).optional(),"2xl":y().min(1).max(12).optional()}).describe(`Grid columns per breakpoint (1-12)`)),ZE=U(()=>T({xs:y().optional(),sm:y().optional(),md:y().optional(),lg:y().optional(),xl:y().optional(),"2xl":y().optional()}).describe(`Display order per breakpoint`)),QE=U(()=>T({breakpoint:YE.optional().describe(`Minimum breakpoint for visibility`),hiddenOn:w(YE).optional().describe(`Hide on these breakpoints`),columns:XE.optional().describe(`Grid columns per breakpoint`),order:ZE.optional().describe(`Display order per breakpoint`)}).describe(`Responsive layout configuration`)),$E=U(()=>k(v(),E([v(),y()])).describe(`CSS property → value map (camelCase keys; design tokens encouraged)`));U(()=>T({large:$E.optional().describe(`Unconditional base (desktop-first)`),medium:$E.optional().describe(`Applied at ≤ medium breakpoint`),small:$E.optional().describe(`Applied at ≤ small breakpoint`),xsmall:$E.optional().describe(`Applied at ≤ xsmall breakpoint`)}).describe(`Per-breakpoint scoped style maps (ADR-0065)`));var eD=U(()=>T({lazyLoad:b().optional().describe(`Enable lazy loading (defer rendering until visible)`),virtualScroll:T({enabled:b().default(!1).describe(`Enable virtual scrolling`),itemHeight:y().optional().describe(`Fixed item height in pixels (for estimation)`),overscan:y().optional().describe(`Number of extra items to render outside viewport`)}).optional().describe(`Virtual scrolling configuration`),cacheStrategy:A([`none`,`cache-first`,`network-first`,`stale-while-revalidate`]).optional().describe(`Client-side data caching strategy`),prefetch:b().optional().describe(`Prefetch data before component is visible`),pageSize:y().optional().describe(`Number of items per page for pagination`),debounceMs:y().optional().describe(`Debounce interval for user interactions in milliseconds`)}).describe(`Performance optimization configuration`)),tD=A(`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(`.`)),nD=U(()=>T({label:v().describe(`Display label (human-readable, any case allowed)`),value:TE.describe(`Stored value (lowercase machine identifier)`),color:v().optional().describe(`Color code for badges/charts`),default:b().optional().describe(`Is default option`)}));U(()=>T({latitude:y().min(-90).max(90).describe(`Latitude coordinate`),longitude:y().min(-180).max(180).describe(`Longitude coordinate`),altitude:y().optional().describe(`Altitude in meters`),accuracy:y().optional().describe(`Accuracy in meters`)}));var rD=U(()=>T({precision:y().int().min(0).max(10).default(2).describe(`Decimal precision (default: 2)`),currencyMode:A([`dynamic`,`fixed`]).default(`dynamic`).describe(`Currency mode: dynamic (user selectable) or fixed (single currency)`),defaultCurrency:v().length(3).default(`CNY`).describe(`Default or fixed currency code (ISO 4217, e.g., USD, CNY, EUR)`)}));U(()=>T({value:y().describe(`Monetary amount`),currency:v().length(3).describe(`Currency code (ISO 4217)`)})),U(()=>T({street:v().optional().describe(`Street address`),city:v().optional().describe(`City name`),state:v().optional().describe(`State/Province`),postalCode:v().optional().describe(`Postal/ZIP code`),country:v().optional().describe(`Country name or code`),countryCode:v().optional().describe(`ISO country code (e.g., US, GB)`),formatted:v().optional().describe(`Formatted address string`)}));var iD=U(()=>T({dimensions:y().int().min(1).max(1e4).describe(`Vector dimensionality (e.g., 1536 for OpenAI embeddings)`),distanceMetric:A([`cosine`,`euclidean`,`dotProduct`,`manhattan`]).default(`cosine`).describe(`Distance/similarity metric for vector search`),normalized:b().default(!1).describe(`Whether vectors are normalized (unit length)`),indexed:b().default(!0).describe(`Whether to create a vector index for fast similarity search`),indexType:A([`hnsw`,`ivfflat`,`flat`]).optional().describe(`Vector index algorithm (HNSW for high accuracy, IVFFlat for large datasets)`)})),aD=U(()=>T({minSize:y().min(0).optional().describe(`Minimum file size in bytes`),maxSize:y().min(1).optional().describe(`Maximum file size in bytes (e.g., 10485760 = 10MB)`),allowedTypes:w(v()).optional().describe(`Allowed file extensions (e.g., [".pdf", ".docx", ".jpg"])`),blockedTypes:w(v()).optional().describe(`Blocked file extensions (e.g., [".exe", ".bat", ".sh"])`),allowedMimeTypes:w(v()).optional().describe(`Allowed MIME types (e.g., ["image/jpeg", "application/pdf"])`),blockedMimeTypes:w(v()).optional().describe(`Blocked MIME types`),virusScan:b().default(!1).describe(`Enable virus scanning for uploaded files`),virusScanProvider:A([`clamav`,`virustotal`,`metadefender`,`custom`]).optional().describe(`Virus scanning service provider`),virusScanOnUpload:b().default(!0).describe(`Scan files immediately on upload`),quarantineOnThreat:b().default(!0).describe(`Quarantine files if threat detected`),storageProvider:v().optional().describe(`Object storage provider name (references ObjectStorageConfig)`),storageBucket:v().optional().describe(`Target bucket name`),storagePrefix:v().optional().describe(`Storage path prefix (e.g., "uploads/documents/")`),imageValidation:T({minWidth:y().min(1).optional().describe(`Minimum image width in pixels`),maxWidth:y().min(1).optional().describe(`Maximum image width in pixels`),minHeight:y().min(1).optional().describe(`Minimum image height in pixels`),maxHeight:y().min(1).optional().describe(`Maximum image height in pixels`),aspectRatio:v().optional().describe(`Required aspect ratio (e.g., "16:9", "1:1")`),generateThumbnails:b().default(!1).describe(`Auto-generate thumbnails`),thumbnailSizes:w(T({name:v().describe(`Thumbnail variant name (e.g., "small", "medium", "large")`),width:y().min(1).describe(`Thumbnail width in pixels`),height:y().min(1).describe(`Thumbnail height in pixels`),crop:b().default(!1).describe(`Crop to exact dimensions`)})).optional().describe(`Thumbnail size configurations`),preserveMetadata:b().default(!1).describe(`Preserve EXIF metadata`),autoRotate:b().default(!0).describe(`Auto-rotate based on EXIF orientation`)}).optional().describe(`Image-specific validation rules`),allowMultiple:b().default(!1).describe(`Allow multiple file uploads (overrides field.multiple)`),allowReplace:b().default(!0).describe(`Allow replacing existing files`),allowDelete:b().default(!0).describe(`Allow deleting uploaded files`),requireUpload:b().default(!1).describe(`Require at least one file when field is required`),extractMetadata:b().default(!0).describe(`Extract file metadata (name, size, type, etc.)`),extractText:b().default(!1).describe(`Extract text content from documents (OCR/parsing)`),versioningEnabled:b().default(!1).describe(`Keep previous versions of replaced files`),maxVersions:y().min(1).optional().describe(`Maximum number of versions to retain`),publicRead:b().default(!1).describe(`Allow public read access to uploaded files`),presignedUrlExpiry:y().min(60).max(604800).default(3600).describe(`Presigned URL expiration in seconds (default: 1 hour)`)}).refine(e=>!(e.minSize!==void 0&&e.maxSize!==void 0&&e.minSize>e.maxSize),{message:`minSize must be less than or equal to maxSize`}).refine(e=>!(e.virusScanProvider!==void 0&&e.virusScan!==!0),{message:`virusScanProvider requires virusScan to be enabled`}));U(()=>T({uniqueness:b().default(!1).describe(`Enforce unique values across all records`),completeness:y().min(0).max(1).default(0).describe(`Minimum ratio of non-null values (0-1, default: 0 = no requirement)`),accuracy:T({source:v().describe(`Reference data source for validation (e.g., "api.verify.com", "master_data")`),threshold:y().min(0).max(1).describe(`Minimum accuracy threshold (0-1, e.g., 0.95 = 95% match required)`)}).optional().describe(`Accuracy validation configuration`)})),U(()=>T({enabled:b().describe(`Enable caching for computed field results`),ttl:y().min(0).describe(`Cache TTL in seconds (0 = no expiration)`),invalidateOn:w(v()).describe(`Field paths that invalidate cache (e.g., ["inventory.quantity", "pricing.base_price"])`)})),U(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Machine name (snake_case)`).optional(),label:v().optional().describe(`Human readable label`),type:tD.describe(`Field Data Type`),description:v().optional().describe(`Tooltip/Help text`),format:v().optional().describe(`Format string (e.g. email, phone)`),columnName:v().optional().describe(`Physical column name in the target datasource. Defaults to the field key when not set.`),required:b().default(!1).describe(`Is required`),searchable:b().default(!1).describe(`Is searchable`),multiple:b().default(!1).describe(`Allow multiple values (Stores as Array/JSON). Applicable for select, lookup, file, image.`),unique:b().default(!1).describe(`Is unique constraint`),defaultValue:S().optional().describe(`Default value`),maxLength:y().optional().describe(`Max character length`),minLength:y().optional().describe(`Min character length`),precision:y().optional().describe(`Total digits`),scale:y().optional().describe(`Decimal places`),min:y().optional().describe(`Minimum value`),max:y().optional().describe(`Maximum value`),options:w(nD).optional().describe(`Static options for select/multiselect`),reference:v().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.`),referenceFilters:w(v()).optional().describe(`Filters applied to lookup dialogs (e.g. "active = true")`),deleteBehavior:A([`set_null`,`cascade`,`restrict`]).optional().default(`set_null`).describe(`What happens if referenced record is deleted`),inlineEdit:E([b(),A([`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:v().optional().describe(`Title for the inline master-detail grid`),inlineColumns:w(x()).optional().describe(`Explicit columns for the inline grid (derived from the child object when omitted)`),inlineAmountField:v().optional().describe(`Numeric child field summed for the inline grid total`),relatedList:b().optional().describe(`Show this child collection as a related list on the parent's detail page (read-side mirror of inlineEdit). Defaults to shown for master_detail/lookup; set false to suppress.`),relatedListTitle:v().optional().describe(`Title for the detail-page related list`),relatedListColumns:w(x()).optional().describe(`Explicit columns for the detail-page related list (derived from the child object when omitted)`),displayField:v().optional().describe(`Field shown as each candidate's label in the picker/popover (defaults to the referenced object's name/title).`),descriptionField:v().optional().describe(`Secondary field shown under the label in the quick-select popover.`),lookupColumns:w(E([v(),T({field:v(),label:v().optional(),width:v().optional(),type:v().optional()})])).optional().describe(`Explicit columns for the record-picker table; auto-derived from the referenced object when omitted.`),lookupPageSize:y().int().positive().optional().describe(`Rows per page in the record-picker dialog (default 10).`),lookupFilters:w(T({field:v(),operator:A([`eq`,`ne`,`gt`,`lt`,`gte`,`lte`,`contains`,`in`,`notIn`]),value:x()})).optional().describe(`Base filters restricting which records are selectable (e.g. only active). Structured, picker-honoured form of referenceFilters.`),dependsOn:w(E([v(),T({field:v(),param:v().optional()})])).optional().describe(`Dependent lookup: restrict candidates by the value of other field(s) on the same record. String = same local/remote key; {field,param} when the remote filter key differs.`),allowCreate:b().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:HE.optional().describe("Formula expression (CEL). e.g. F`record.amount * 0.1`"),returnType:A([`number`,`text`,`boolean`,`date`]).optional().describe(`Inferred value type of a formula field (number/text/boolean/date)`),summaryOperations:T({object:v().describe(`Source child object name for roll-up`),field:v().describe(`Field on child object to aggregate (ignored for count)`),function:A([`count`,`sum`,`min`,`max`,`avg`]).describe(`Aggregation function to apply`),relationshipField:v().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.`)}).optional().describe(`Roll-up summary definition. The engine recomputes the value when child records are inserted/updated/deleted.`),language:v().optional().describe(`Programming language for syntax highlighting (e.g., javascript, python, sql)`),maxRating:y().optional().describe(`Maximum rating value (default: 5)`),step:y().optional().describe(`Step increment for slider (default: 1)`),currencyConfig:rD.optional().describe(`Configuration for currency field type`),dimensions:y().int().min(1).max(1e4).optional().describe(`Vector dimensionality (e.g., 1536 for OpenAI embeddings)`),vectorConfig:iD.optional().describe(`Configuration for vector field type (AI/ML embeddings)`),fileAttachmentConfig:aD.optional().describe(`Configuration for file and attachment field types`),trackHistory:b().optional().describe(`Render this field's value changes as human-readable entries on the record activity timeline (ADR-0052 §5b). Opt-in per field.`),dependencies:w(v()).optional().describe(`Array of field names that this field depends on (for formulas, visibility rules, etc.)`),group:v().optional().describe(`Field group name for organizing fields in forms and layouts (e.g., "contact_info", "billing", "system")`),visibleWhen:HE.optional().describe("Predicate (CEL) — field is shown only when TRUE (else hidden). e.g. P`record.type == 'invoice'`"),readonlyWhen:HE.optional().describe("Predicate (CEL) — field is read-only when TRUE. e.g. P`record.status == 'paid'`"),requiredWhen:HE.optional().describe("Predicate (CEL) — field is required when TRUE. Canonical name for `conditionalRequired`."),conditionalRequired:HE.optional().describe("Predicate (CEL) — field is required when TRUE. Alias of `requiredWhen`."),hidden:b().default(!1).describe(`Hidden from default UI`),readonly:b().default(!1).describe(`Read-only in UI`),requiredPermissions:w(v()).optional().describe(`[ADR-0066 D3] Capabilities required to read/edit this field (mask on read, deny on write; AND-gate).`),system:b().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:b().optional().default(!0).describe(`Whether field is sortable in list views`),inlineHelpText:v().optional().describe(`Help text displayed below the field in forms`),caseSensitive:b().optional().describe(`Whether text comparisons are case-sensitive`),autonumberFormat:v().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).`),index:b().default(!1).describe(`Create standard database index`),externalId:b().default(!1).describe(`Is external ID for upsert operations`)}));var oD=A([`GET`,`POST`,`PUT`,`DELETE`,`PATCH`,`HEAD`,`OPTIONS`]),sD=U(()=>A([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`])),cD=U(()=>T({url:v().describe(`API endpoint URL`),method:sD.optional().default(`GET`).describe(`HTTP method`),headers:k(v(),v()).optional().describe(`Custom HTTP headers`),params:k(v(),S()).optional().describe(`Query parameters`),body:S().optional().describe(`Request body for POST/PUT/PATCH`)}));U(()=>T({enabled:b().default(!0).describe(`Enable CORS`),origins:E([v(),w(v())]).default(`*`).describe(`Allowed origins (* for all)`),methods:w(oD).optional().describe(`Allowed HTTP methods`),credentials:b().default(!1).describe(`Allow credentials (cookies, authorization headers)`),maxAge:y().int().optional().describe(`Preflight cache duration in seconds`)})),U(()=>T({enabled:b().default(!1).describe(`Enable rate limiting`),windowMs:y().int().default(6e4).describe(`Time window in milliseconds`),maxRequests:y().int().default(100).describe(`Max requests per window`)})),U(()=>T({path:v().describe(`URL path to serve from`),directory:v().describe(`Physical directory to serve`),cacheControl:v().optional().describe(`Cache-Control header value`)}));var lD=U(()=>D(`provider`,[T({provider:j(`object`),object:v().describe(`Target object name`)}),T({provider:j(`api`),read:cD.optional().describe(`Configuration for fetching data`),write:cD.optional().describe(`Configuration for submitting data (for forms/editable tables)`)}),T({provider:j(`value`),items:w(S()).describe(`Static data array`)}),T({provider:j(`schema`),schemaId:v().describe(`Schema identifier — typically the metadata type name`),schema:k(v(),S()).optional().describe(`Inline JSON Schema (Draft 2020-12). Optional when schemaId is resolvable.`)})])),uD=U(()=>T({field:v().describe(`Field name to filter on`),operator:v().describe(`Filter operator (e.g. equals, not_equals, contains, this_quarter)`),value:E([v(),y(),b(),ul(),w(E([v(),y()]))]).optional().describe(`Filter value`)}).describe(`View filter rule`)),dD=U(()=>A([`none`,`count`,`count_empty`,`count_filled`,`count_unique`,`percent_empty`,`percent_filled`,`sum`,`avg`,`min`,`max`]).describe(`Aggregation function for column footer summary`)),fD=U(()=>T({field:v().describe(`Field name (snake_case)`),label:WE.optional().describe(`Display label override`),width:y().positive().optional().describe(`Column width in pixels`),align:A([`left`,`center`,`right`]).optional().describe(`Text alignment`),hidden:b().optional().describe(`Hide column by default`),sortable:b().optional().describe(`Allow sorting by this column`),resizable:b().optional().describe(`Allow resizing this column`),wrap:b().optional().describe(`Allow text wrapping`),type:v().optional().describe(`Renderer type override (e.g., "currency", "date")`),pinned:A([`left`,`right`]).optional().describe(`Pin/freeze column to left or right side`),summary:dD.optional().describe(`Footer aggregation function for this column`),link:b().optional().describe(`Functions as the primary navigation link (triggers View navigation)`),action:v().optional().describe(`Registered Action ID to execute when clicked`)})),pD=U(()=>T({type:A([`none`,`single`,`multiple`]).default(`none`).describe(`Selection mode`)})),mD=U(()=>T({pageSize:y().int().positive().default(25).describe(`Number of records per page`),pageSizeOptions:w(y().int().positive()).optional().describe(`Available page size options`)})),hD=U(()=>A([`compact`,`short`,`medium`,`tall`,`extra_tall`]).describe(`Row height / density setting for list view`)),gD=U(()=>T({field:v().describe(`Field name to group by`),order:A([`asc`,`desc`]).default(`asc`).describe(`Group sort order`),collapsed:b().default(!1).describe(`Collapse groups by default`)})),_D=U(()=>T({fields:w(gD).min(1).describe(`Fields to group by (supports up to 3 levels)`)}).describe(`Record grouping configuration`)),vD=U(()=>T({coverField:v().optional().describe(`Attachment/image field to display as card cover`),coverFit:A([`cover`,`contain`]).default(`cover`).describe(`Image fit mode for card cover`),cardSize:A([`small`,`medium`,`large`]).default(`medium`).describe(`Card size in gallery view`),titleField:v().optional().describe(`Field to display as card title`),visibleFields:w(v()).optional().describe(`Fields to display on card body`)}).describe(`Gallery/card view configuration`)),yD=U(()=>T({startDateField:v().describe(`Field for timeline item start date`),endDateField:v().optional().describe(`Field for timeline item end date`),titleField:v().describe(`Field to display as timeline item title`),groupByField:v().optional().describe(`Field to group timeline rows`),colorField:v().optional().describe(`Field to determine item color`),scale:A([`hour`,`day`,`week`,`month`,`quarter`,`year`]).default(`week`).describe(`Default timeline scale`)}).describe(`Timeline view configuration`)),bD=U(()=>T({type:A([`personal`,`collaborative`]).default(`collaborative`).describe(`View ownership type`),lockedBy:v().optional().describe(`User who locked the view configuration`)}).describe(`View sharing and access configuration`)),xD=U(()=>T({field:v().describe(`Field to derive color from (typically a select/status field)`),colors:k(v(),v()).optional().describe(`Map of field value to color (hex/token)`)}).describe(`Row color configuration based on field values`)),SD=U(()=>A([`grid`,`kanban`,`gallery`,`calendar`,`timeline`,`gantt`,`map`,`chart`,`tree`]).describe(`Visualization type that users can switch to`)),CD=U(()=>T({sort:b().default(!0).describe(`Allow users to sort records`),search:b().default(!0).describe(`Allow users to search records`),filter:b().default(!0).describe(`Allow users to filter records`),rowHeight:b().default(!0).describe(`Allow users to toggle row height/density`),addRecordForm:b().default(!1).describe(`Add records through a form instead of inline`),buttons:w(v()).optional().describe(`Custom action button IDs to show in the toolbar`)}).describe(`User action toggles for the view toolbar`)),wD=U(()=>T({showDescription:b().default(!0).describe(`Show the view description text`),allowedVisualizations:w(SD).optional().describe(`Whitelist of visualization types users can switch between (e.g. ["grid", "gallery", "kanban"])`)}).describe(`Appearance and visualization configuration`)),TD=U(()=>T({name:EE.describe(`Tab identifier (snake_case)`),label:WE.optional().describe(`Display label`),icon:v().optional().describe(`Tab icon name`),view:v().optional().describe(`Referenced list view name from listViews`),filter:w(uD).optional().describe(`Tab-specific filter criteria`),order:y().int().min(0).optional().describe(`Tab display order`),pinned:b().default(!1).describe(`Pin tab (cannot be removed by users)`),isDefault:b().default(!1).describe(`Set as the default active tab`),visible:b().default(!0).describe(`Tab visibility`)}).describe(`Tab configuration for multi-tab view interface`)),ED=U(()=>T({field:v().describe(`Field name on the source object (must exist — checked by reference diagnostics)`),label:WE.optional().describe(`Display label override (defaults to the field label)`),type:A([`select`,`multi-select`,`boolean`,`date-range`,`text`]).optional().describe(`Filter control type. Omit to infer from the field definition`),options:w(T({value:E([v(),y(),b()]).describe(`Option value`),label:WE.describe(`Option label`),color:v().optional().describe(`Option color token/hex`)})).optional().describe(`Static options. Omit to derive from the field definition (select options / lookup records)`),showCount:b().optional().describe(`Show per-option record counts`),defaultValues:w(E([v(),y(),b()])).optional().describe(`Pre-selected values when the view loads`)}).describe(`Quick-filter field configuration`)),DD=U(()=>T({element:A([`dropdown`,`tabs`,`toggle`]).default(`dropdown`).describe(`Filter control style: "dropdown" (per-field value selectors) or "tabs" (named presets). "toggle" is deprecated.`),fields:w(ED).optional().describe(`Fields exposed as quick filters (dropdown/toggle elements)`),tabs:w(TD).optional().describe(`Named filter presets rendered as tabs (tabs element). Reuses ViewTabSchema`),showAllRecords:b().optional().describe(`Show an "All records" tab before the presets (tabs element)`)}).describe(`End-user quick-filter configuration (Airtable "User filters" parity)`)),OD=U(()=>T({enabled:b().default(!0).describe(`Show the add record entry point`),position:A([`top`,`bottom`,`both`]).default(`bottom`).describe(`Position of the add record button`),mode:A([`inline`,`form`,`modal`]).default(`inline`).describe(`How to add a new record`),formView:v().optional().describe(`Named form view to use when mode is "form" or "modal"`)}).describe(`Add record entry point configuration`)),kD=U(()=>T({groupByField:v().describe(`Field to group columns by (usually status/select)`),summarizeField:v().optional().describe(`Field to sum at top of column (e.g. amount)`),columns:w(v()).describe(`Fields to show on cards`)})),AD=U(()=>T({chartType:A([`bar`,`line`,`pie`,`area`,`scatter`]).default(`bar`).describe(`Chart visualisation type`),dataset:EE.describe(`Dataset name to bind (ADR-0021)`),dimensions:w(v()).optional().describe(`Dimension names — X/group/split`),values:w(v()).min(1).describe(`Measure names — Y (at least one)`)}).describe(`List chart view configuration`)),jD=U(()=>T({startDateField:v(),endDateField:v().optional(),titleField:v(),colorField:v().optional()})),MD=U(()=>T({field:v().describe(`Record field / dot-path the dimension filters on`),label:v().optional().describe(`Trigger label (falls back to the field label)`),options:w(E([v(),T({value:E([v(),y()]),label:v().optional()})])).optional().describe(`Explicit option override for fixed enums`)})),ND=U(()=>T({startDateField:v(),endDateField:v(),titleField:v(),progressField:v().optional(),dependenciesField:v().optional(),colorField:v().optional().describe(`Field that drives the bar color`),parentField:v().optional().describe(`Field holding the parent task id (builds the summary → step tree)`),typeField:v().optional().describe(`Field whose value maps to task/summary/milestone`),baselineStartField:v().optional().describe(`Baseline (planned) start field`),baselineEndField:v().optional().describe(`Baseline (planned) end field`),groupByField:v().optional().describe(`Field to group leaf tasks by (synthesized summary rows)`),resourceView:b().optional().describe(`Render a per-resource workload histogram instead of the timeline`),assigneeField:v().optional().describe(`Resource field to bucket load by (resource view)`),effortField:v().optional().describe(`Per-task load units (resource view; default 1)`),capacity:y().optional().describe(`Per-resource capacity ceiling; loads above this flag overload`),tooltipFields:w(E([v(),T({field:v(),label:v().optional()})])).optional().describe(`Fields to surface in the hover tooltip, in display order`),quickFilters:w(MD).optional().describe(`Multi-select filter dropdowns rendered above the chart`),autoZoomToFilter:b().optional().describe(`When true (default), filtering zooms the range to the filtered tasks`)}).passthrough()),PD=U(()=>T({parentField:v().optional().describe(`Single-parent pointer field (auto-detected from the object schema when omitted)`),labelField:v().optional().describe(`Field rendered indented in the first column (defaults to "name")`),fields:w(v()).optional().describe(`Additional fields rendered as flat columns alongside the label`),defaultExpandedDepth:y().int().min(0).optional().describe(`Initial expansion depth (0 = roots only; omit = expand all)`)}).passthrough()),FD=U(()=>A([`page`,`drawer`,`modal`,`split`,`popover`,`new_window`,`none`])),ID=U(()=>T({mode:FD.default(`page`),view:v().optional().describe(`Name of the form view to use for details (e.g. "summary_view", "edit_form")`),preventNavigation:b().default(!1).describe(`Disable standard navigation entirely`),openNewTab:b().default(!1).describe(`Force open in new tab (applies to page mode)`),width:E([v(),y()]).optional().describe(`Width of the drawer/modal (e.g. "600px", "50%")`)})),LD=U(()=>T({name:EE.optional().describe(`Internal view name (lowercase snake_case)`),label:WE.optional(),type:A([`grid`,`kanban`,`gallery`,`calendar`,`timeline`,`gantt`,`map`,`chart`,`tree`]).default(`grid`),data:lD.optional().describe(`Data source configuration (defaults to "object" provider)`),columns:E([w(v()),w(fD)]).describe(`Fields to display as columns`),filter:w(uD).optional().describe(`Filter criteria (JSON Rules)`),sort:E([v(),w(T({field:v(),order:A([`asc`,`desc`])}))]).optional(),searchableFields:w(v()).optional().describe(`Fields enabled for search`),filterableFields:w(v()).optional().describe(`Legacy shorthand for userFilters.fields — bare field names enabled for end-user filtering. Prefer userFilters`),userFilters:DD.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:b().optional().describe(`Enable column resizing`),striped:b().optional().describe(`Striped row styling`),bordered:b().optional().describe(`Show borders`),compactToolbar:b().optional().describe(`Collapse Group/Color/Density/Hide-fields into a single View settings popover`),selection:pD.optional().describe(`Row selection configuration`),navigation:ID.optional().describe(`Configuration for item click navigation (page, drawer, modal, etc.)`),pagination:mD.optional().describe(`Pagination configuration`),kanban:kD.optional(),calendar:jD.optional(),gantt:ND.optional(),gallery:vD.optional(),timeline:yD.optional(),chart:AD.optional(),tree:PD.optional(),description:WE.optional().describe(`View description for documentation/tooltips`),sharing:bD.optional().describe(`View sharing and access configuration`),rowHeight:hD.optional().describe(`Row height / density setting`),grouping:_D.optional().describe(`Group records by one or more fields`),rowColor:xD.optional().describe(`Color rows based on field value`),hiddenFields:w(v()).optional().describe(`Fields to hide in this specific view`),fieldOrder:w(v()).optional().describe(`Explicit field display order for this view`),rowActions:w(v()).optional().describe(`Actions available for individual row items`),bulkActions:w(v()).optional().describe(`Actions available when multiple rows are selected`),bulkActionDefs:w(k(v(),x())).optional().describe(`Rich bulk action definitions (schema-driven, executed via BulkActionDialog)`),virtualScroll:b().optional().describe(`Enable virtual scrolling for large datasets`),conditionalFormatting:w(T({condition:HE.describe(`Predicate (CEL) to evaluate.`),style:k(v(),v()).describe(`CSS styles to apply when condition is true`)})).optional().describe(`Conditional formatting rules for list rows`),inlineEdit:b().optional().describe(`Allow inline editing of records directly in the list view`),exportOptions:w(A([`csv`,`xlsx`,`pdf`,`json`])).optional().describe(`Available export format options`),userActions:CD.optional().describe(`User action toggles for the view toolbar`),appearance:wD.optional().describe(`Appearance and visualization configuration`),tabs:w(TD).optional().describe(`Tab definitions for multi-tab view interface`),addRecord:OD.optional().describe(`Add record entry point configuration`),showRecordCount:b().optional().describe(`Show record count at the bottom of the list`),allowPrinting:b().optional().describe(`Allow users to print the view`),emptyState:T({title:WE.optional(),message:WE.optional(),icon:v().optional()}).optional().describe(`Empty state configuration when no records found`),aria:GE.optional().describe(`ARIA accessibility attributes for the list view`),responsive:QE.optional().describe(`Responsive layout configuration`),performance:eD.optional().describe(`Performance optimization settings`)})),RD=U(()=>T({field:v().describe(`Field name (snake_case)`),type:tD.optional().describe(`Field type (auto-infers widget if omitted)`),options:w(nD).optional().describe(`Options for select/multiselect/radio/checkboxes fields`),reference:v().optional().describe(`Target object name for lookup/master_detail fields`),maxLength:y().optional().describe(`Maximum character length (for text/textarea/email/url/phone)`),minLength:y().optional().describe(`Minimum character length`),min:y().optional().describe(`Minimum value (for number/currency/percent/slider)`),max:y().optional().describe(`Maximum value`),precision:y().optional().describe(`Total digits (for number/currency)`),scale:y().optional().describe(`Decimal places`),multiple:b().optional().describe(`Allow multiple values (for select/lookup/file/image)`),label:WE.optional().describe(`Display label override`),placeholder:WE.optional().describe(`Placeholder text`),helpText:WE.optional().describe(`Help/hint text`),readonly:b().optional().describe(`Read-only override`),immutable:b().optional().describe(`Editable on create, locked once the record exists (e.g. machine names).`),required:b().optional().describe(`Required override`),hidden:b().optional().describe(`Hidden override`),colSpan:y().int().min(1).max(4).optional().describe(`Column span in grid layout (1-4)`),widget:v().optional().describe(`Custom widget/component name (overrides type-based inference)`),language:v().optional().describe(`Code editor language (for type=code)`),fields:w(M(()=>RD)).optional().describe(`Sub-fields for composite/repeater/record types`),keyField:T({field:v().default(`name`).describe(`Property name that holds the key inside each item (defaults to "name")`),label:WE.optional().describe(`Display label for the key column`),placeholder:WE.optional().describe(`Placeholder when entering a new key`),helpText:WE.optional().describe(`Help text under the key input`),regex:v().optional().describe(`JS regex source string the key must match (no flags)`),immutable:b().default(!0).describe(`If true, the key is read-only after creation`)}).optional().describe(`Key column config for record-typed fields`),dependsOn:v().optional().describe(`Parent field name for cascading`),visibleOn:HE.optional().describe(`Visibility predicate (CEL).`),disclosure:A([`inline`,`popover`]).optional().describe(`Composite rendering: inline bordered box (default) or a summary line + gear popover (progressive disclosure).`)})),zD=U(()=>T({name:v().optional().describe(`Stable section identifier for i18n lookup (snake_case)`),label:WE.optional(),description:v().optional().describe(`Optional description rendered under the section header.`),collapsible:b().default(!1),collapsed:b().default(!1),visibleOn:HE.optional().describe(`Visibility predicate (CEL). Hides the whole section when false.`),columns:E([A([`1`,`2`,`3`,`4`]),j(1),j(2),j(3),j(4)]).default(1).transform(e=>typeof e==`string`?parseInt(e):e),fields:w(E([v(),RD]))})),BD=U(()=>T({type:A([`simple`,`tabbed`,`wizard`,`split`,`drawer`,`modal`]).default(`simple`),data:lD.optional().describe(`Data source configuration (defaults to "object" provider)`),sections:w(zD).optional(),groups:w(zD).optional(),subforms:w(T({childObject:v().describe(`Child object whose records are entered inline`),relationshipField:v().optional().describe(`FK on the child pointing back to the parent (auto-detected when omitted)`),columns:w(x()).optional().describe(`Editable grid columns (derived from the child object when omitted)`),amountField:v().optional().describe(`Numeric child column summed for the running total`),totalField:v().optional().describe(`Parent field to receive the rolled-up sum`),title:v().optional().describe(`Section title`),addLabel:v().optional().describe(`Add-row button label`),minRows:y().optional(),maxRows:y().optional()})).optional().describe(`Inline master-detail child collections`),defaultSort:w(T({field:v().describe(`Field name to sort by`),order:A([`asc`,`desc`]).default(`desc`).describe(`Sort direction`)})).optional().describe(`Default sort order for related list views within this form`),sharing:JE.optional().describe(`Public sharing configuration for this form`),submitBehavior:E([T({kind:j(`thank-you`),title:v().optional(),message:v().optional()}),T({kind:j(`redirect`),url:v(),delayMs:y().int().min(0).optional()}),T({kind:j(`continue`)}),T({kind:j(`next-record`)})]).optional().describe(`Post-submit behavior`),aria:GE.optional().describe(`ARIA accessibility attributes for the form view`)}));U(()=>T({list:LD.optional(),form:BD.optional(),listViews:k(v(),LD).optional().describe(`Additional named list views`),formViews:k(v(),BD).optional().describe(`Additional named form views`),protection:wE.optional().describe(`Package author protection block — lock policy for this view.`),...CE}));var VD=v().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>`."),HD=A([`package`,`shared`,`personal`]).describe(`View identity layer: package | shared | personal.`);A([`list`,`form`]).describe("Whether `config` is a ListView (list family) or a FormView.");function UD(){return{name:VD,object:v().describe(`Bound object name — the foreign key used to aggregate views.`),label:WE.optional().describe(`Display label (supports i18n).`),isDefault:b().optional().describe(`Whether this is the object's default view in the switcher.`),order:y().int().optional().describe(`Sort order within the object's view switcher / left rail.`),scope:HD.optional().describe("Identity layer (defaults to `package` for source-loaded views)."),owner:v().optional().describe("Owner user id — set when `scope` is `personal`."),hidden:b().optional().describe(`Hidden from the switcher (per-user / per-org declutter).`),protection:wE.optional().describe(`Package author protection block — lock policy for this view.`),...CE}}U(()=>D(`viewKind`,[T({viewKind:j(`list`),config:LD.describe(`List-family view configuration.`),...UD()}),T({viewKind:j(`form`),config:BD.describe(`Form view configuration.`),...UD()})]));function WD(e){let{schemaId:t,...n}=e;return BD.parse({...n,data:{provider:`schema`,schemaId:t}})}WD({schemaId:`agent`,type:`simple`,sections:[{name:`identity`,label:`Identity`,description:`How users see and reference this agent.`,columns:2,fields:[{field:`name`,required:!0,colSpan:1,helpText:`Unique identifier (snake_case)`},{field:`label`,required:!0,colSpan:1,helpText:`Display name (e.g., "Sales Assistant")`},{field:`role`,required:!0,colSpan:2,helpText:`Agent persona (e.g., "Customer Support Specialist")`},{field:`avatar`,colSpan:1,helpText:`Avatar image URL`},{field:`active`,colSpan:1,helpText:`Enable/disable this agent`}]},{name:`ai_configuration`,label:`AI Configuration`,description:`Model selection, instructions, planning, and memory.`,fields:[{field:`instructions`,required:!0,widget:`textarea`,helpText:`System prompt — tell the agent how to behave and what it can do`},{field:`model`,type:`composite`,helpText:`AI model configuration (provider, model name, temperature, etc.)`},{field:`planning`,type:`composite`,helpText:`Autonomous reasoning configuration (strategy, max iterations, replan)`},{field:`memory`,type:`composite`,helpText:`Memory management (short-term, long-term, reflection)`},{field:`lifecycle`,type:`composite`,helpText:`State machine defining conversation flow`}]},{name:`capabilities`,label:`Capabilities`,description:`Skills, tools, and knowledge sources the agent can use.`,fields:[{field:`skills`,widget:`string-tags`,helpText:`Skill names (Agent→Skill→Tool architecture)`},{field:`tools`,type:`repeater`,helpText:`Direct tool references (legacy mode)`},{field:`knowledge`,type:`composite`,helpText:`RAG knowledge access configuration`}]},{name:`access`,label:`Access & Security`,description:`Who can use this agent and what safeguards apply.`,collapsible:!0,collapsed:!0,fields:[{field:`visibility`,helpText:`Scope: global, organization, or private`},{field:`access`,widget:`string-tags`,helpText:`User IDs or role names who can chat with this agent`},{field:`permissions`,widget:`string-tags`,helpText:`Required permissions to use this agent`},{field:`tenantId`,helpText:`Restrict to specific organization ID`},{field:`guardrails`,type:`composite`,helpText:`Safety rules and content policies`}]}]});var GD=U(()=>A([`data`,`action`,`flow`,`integration`,`vector_search`,`analytics`,`utility`]).describe(`Tool operational category`)),KD=U(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Tool unique identifier (snake_case)`),label:v().describe(`Tool display name`),description:v().describe(`Tool description for LLM function calling`),category:GD.optional().describe(`Tool category for grouping and filtering`),parameters:k(v(),S()).describe(`JSON Schema for tool parameters`),outputSchema:k(v(),S()).optional().describe(`JSON Schema for tool output`),objectName:v().regex(/^[a-z_][a-z0-9_]*$/).optional().describe(`Target object name (snake_case)`),requiresConfirmation:b().default(!1).describe(`Require user confirmation before execution`),permissions:w(v()).optional().describe(`Required permissions or roles`),active:b().default(!0).describe(`Whether the tool is enabled`),builtIn:b().default(!1).describe(`Platform built-in tool flag`),protection:wE.optional().describe(`Package author protection block — lock policy for this tool.`),...CE}));WD({schemaId:`tool`,type:`simple`,sections:[{label:`Basics`,description:`Tool identity and AI-facing description.`,columns:2,fields:[{field:`name`,required:!0,colSpan:1,helpText:`Unique identifier (snake_case)`},{field:`label`,required:!0,colSpan:1,helpText:`Display name for Studio UI`},{field:`description`,required:!0,widget:`textarea`,colSpan:2,helpText:`Tell AI when to use this tool — be specific!`},{field:`category`,colSpan:1,helpText:`Tool category (data, action, flow, integration, etc.)`},{field:`objectName`,widget:`ref:object`,colSpan:1,helpText:`Related object (if this tool operates on a specific object)`},{field:`active`,colSpan:1,helpText:`Enable/disable this tool`},{field:`builtIn`,colSpan:1,helpText:`Platform built-in tool (vs user-defined)`}]},{label:`Schemas`,description:`Inputs the tool accepts and the shape of its output.`,fields:[{field:`parameters`,type:`composite`,required:!0,helpText:`Input parameters — define properties like: {name: {type: "string", description: "..."}}`},{field:`outputSchema`,type:`composite`,helpText:`Output schema for validation (optional)`}]},{label:`Access & safety`,description:`Permissions and confirmation requirements.`,collapsible:!0,collapsed:!0,fields:[{field:`requiresConfirmation`,helpText:`Ask user to approve before executing (for destructive actions)`},{field:`permissions`,widget:`string-tags`,helpText:`Required permissions to use this tool`}]}]});var qD=U(()=>T({field:v().describe(`Context field to evaluate`),operator:A([`eq`,`neq`,`in`,`not_in`,`contains`]).describe(`Comparison operator`),value:E([v(),w(v())]).describe(`Expected value or values`)})),JD=U(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Skill unique identifier (snake_case)`),label:v().describe(`Skill display name`),description:v().optional().describe(`Skill description`),surface:A([`ask`,`build`,`both`]).default(`ask`).describe(`Agent surface this skill binds to ('ask' | 'build' | 'both') — ADR-0063 §3`),instructions:v().optional().describe(`LLM instructions when skill is active`),tools:w(v().regex(/^[a-z_][a-z0-9_]*\*?$/)).describe("Tool names belonging to this skill (supports trailing wildcard, e.g. `action_*`)"),triggerPhrases:w(v()).optional().describe(`Phrases that activate this skill`),triggerConditions:w(qD).optional().describe(`Programmatic activation conditions`),permissions:w(v()).optional().describe(`Required permissions or roles`),active:b().default(!0).describe(`Whether the skill is enabled`),protection:wE.optional().describe(`Package author protection block — lock policy for this skill.`),...CE}));WD({schemaId:`skill`,type:`simple`,sections:[{label:`Basics`,description:`Skill identity and human-readable description.`,columns:2,fields:[{field:`name`,required:!0,colSpan:1,helpText:`Unique identifier (snake_case)`},{field:`label`,required:!0,colSpan:1,helpText:`Display name (e.g., "Case Management")`},{field:`description`,widget:`textarea`,colSpan:2,helpText:`What this skill does`},{field:`active`,colSpan:1,helpText:`Enable/disable this skill`}]},{label:`AI Instructions`,description:`How the agent should reason with this skill.`,fields:[{field:`instructions`,widget:`textarea`,helpText:`Instructions for AI — tell it how to use these tools together`},{field:`tools`,widget:`string-tags`,required:!0,helpText:`Tool names (supports wildcard: action_*)`}]},{label:`Triggers`,description:`When this skill should activate.`,collapsible:!0,collapsed:!0,fields:[{field:`triggerPhrases`,widget:`string-tags`,helpText:`Natural language phrases that activate this skill`},{field:`triggerConditions`,type:`repeater`,helpText:`Programmatic conditions (e.g., objectName == "case")`}]},{label:`Access`,description:`Required permissions to use this skill.`,collapsible:!0,collapsed:!0,fields:[{field:`permissions`,widget:`string-tags`,helpText:`Required permissions to use this skill`}]}]});var YD=U(()=>T({promptTokens:y().int().nonnegative().describe(`Tokens consumed by the prompt`),completionTokens:y().int().nonnegative().describe(`Tokens generated in the completion`),totalTokens:y().int().nonnegative().describe(`Total tokens (prompt + completion)`)}));U(()=>T({model:v(),usage:YD,costUsd:y().nonnegative().describe(`Computed cost in USD`),latencyMs:y().nonnegative().optional(),timestamp:v().datetime().optional()}));var XD=U(()=>A([`system`,`user`,`assistant`,`function`,`tool`]));U(()=>A([`text`,`image`,`file`,`code`,`structured`]));var ZD=U(()=>T({type:j(`text`),text:v().describe(`Text content`),metadata:k(v(),S()).optional()})),QD=U(()=>T({type:j(`image`),imageUrl:v().url().describe(`Image URL`),detail:A([`low`,`high`,`auto`]).optional().default(`auto`),metadata:k(v(),S()).optional()})),$D=U(()=>T({type:j(`file`),fileUrl:v().url().describe(`File attachment URL`),mimeType:v().describe(`MIME type`),fileName:v().optional(),metadata:k(v(),S()).optional()})),eO=U(()=>T({type:j(`code`),text:v().describe(`Code snippet`),language:v().optional().default(`text`),metadata:k(v(),S()).optional()})),tO=U(()=>E([ZD,QD,$D,eO])),nO=U(()=>T({name:v().describe(`Function name`),arguments:v().describe(`JSON string of function arguments`),result:v().optional().describe(`Function execution result`)})),rO=U(()=>T({id:v().describe(`Tool call ID`),type:A([`function`]).default(`function`),function:nO})),iO=U(()=>T({id:v().describe(`Unique message ID`),timestamp:v().datetime().describe(`ISO 8601 timestamp`),role:XD,content:w(tO).describe(`Message content (multimodal array)`),functionCall:nO.optional().describe(`Legacy function call`),toolCalls:w(rO).optional().describe(`Tool calls`),toolCallId:v().optional().describe(`Tool call ID this message responds to`),name:v().optional().describe(`Name of the function/user`),tokens:YD.optional().describe(`Token usage for this message`),cost:y().nonnegative().optional().describe(`Cost for this message in USD`),pinned:b().optional().default(!1).describe(`Prevent removal during pruning`),importance:y().min(0).max(1).optional().describe(`Importance score for pruning`),embedding:w(y()).optional().describe(`Vector embedding for semantic search`),metadata:k(v(),S()).optional()})),aO=U(()=>A([`fifo`,`importance`,`semantic`,`sliding_window`,`summary`])),oO=U(()=>T({maxTokens:y().int().positive().describe(`Maximum total tokens`),maxPromptTokens:y().int().positive().optional().describe(`Max tokens for prompt`),maxCompletionTokens:y().int().positive().optional().describe(`Max tokens for completion`),reserveTokens:y().int().nonnegative().default(500).describe(`Reserve tokens for system messages`),bufferPercentage:y().min(0).max(1).default(.1).describe(`Buffer percentage (0.1 = 10%)`),strategy:aO.default(`sliding_window`),slidingWindowSize:y().int().positive().optional().describe(`Number of recent messages to keep`),minImportanceScore:y().min(0).max(1).optional().describe(`Minimum importance to keep`),semanticThreshold:y().min(0).max(1).optional().describe(`Semantic similarity threshold`),enableSummarization:b().default(!1).describe(`Enable context summarization`),summarizationThreshold:y().int().positive().optional().describe(`Trigger summarization at N tokens`),summaryModel:v().optional().describe(`Model ID for summarization`),warnThreshold:y().min(0).max(1).default(.8).describe(`Warn at % of budget (0.8 = 80%)`)})),sO=U(()=>T({promptTokens:y().int().nonnegative().default(0),completionTokens:y().int().nonnegative().default(0),totalTokens:y().int().nonnegative().default(0),budgetLimit:y().int().positive(),budgetUsed:y().int().nonnegative().default(0),budgetRemaining:y().int().nonnegative(),budgetPercentage:y().min(0).max(1).describe(`Usage as percentage of budget`),messageCount:y().int().nonnegative().default(0),prunedMessageCount:y().int().nonnegative().default(0),summarizedMessageCount:y().int().nonnegative().default(0)})),cO=U(()=>T({sessionId:v().describe(`Conversation session ID`),userId:v().optional().describe(`User identifier`),agentId:v().optional().describe(`AI agent identifier`),object:v().optional().describe(`Related object (e.g., "case", "project")`),recordId:v().optional().describe(`Related record ID`),scope:k(v(),S()).optional().describe(`Additional context scope`),systemMessage:v().optional().describe(`System prompt/instructions`),metadata:k(v(),S()).optional()}));U(()=>T({id:v().describe(`Unique session ID`),name:v().optional().describe(`Session name/title`),context:cO,modelId:v().optional().describe(`AI model ID`),tokenBudget:oO,messages:w(iO).default([]),tokens:sO.optional(),totalTokens:YD.optional().describe(`Total tokens across all messages`),totalCost:y().nonnegative().optional().describe(`Total cost for this session in USD`),status:A([`active`,`paused`,`completed`,`archived`]).default(`active`),createdAt:v().datetime().describe(`ISO 8601 timestamp`),updatedAt:v().datetime().describe(`ISO 8601 timestamp`),expiresAt:v().datetime().optional().describe(`ISO 8601 timestamp`),metadata:k(v(),S()).optional()})),U(()=>T({summary:v().describe(`Conversation summary`),keyPoints:w(v()).optional().describe(`Key discussion points`),originalTokens:y().int().nonnegative().describe(`Original token count`),summaryTokens:y().int().nonnegative().describe(`Summary token count`),tokensSaved:y().int().nonnegative().describe(`Tokens saved`),messageRange:T({startIndex:y().int().nonnegative(),endIndex:y().int().nonnegative()}).describe(`Range of messages summarized`),generatedAt:v().datetime().describe(`ISO 8601 timestamp`),modelId:v().optional().describe(`Model used for summarization`)})),U(()=>T({timestamp:v().datetime().describe(`Event timestamp`),prunedMessages:w(T({messageId:v(),role:XD,tokens:y().int().nonnegative(),importance:y().min(0).max(1).optional()})),tokensFreed:y().int().nonnegative(),messagesRemoved:y().int().nonnegative(),remainingTokens:y().int().nonnegative(),remainingMessages:y().int().nonnegative()})),U(()=>T({sessionId:v(),totalMessages:y().int().nonnegative(),userMessages:y().int().nonnegative(),assistantMessages:y().int().nonnegative(),systemMessages:y().int().nonnegative(),totalTokens:y().int().nonnegative(),averageTokensPerMessage:y().nonnegative(),peakTokenUsage:y().int().nonnegative(),pruningEvents:y().int().nonnegative().default(0),summarizationEvents:y().int().nonnegative().default(0),tokensSavedByPruning:y().int().nonnegative().default(0),tokensSavedBySummarization:y().int().nonnegative().default(0),duration:y().nonnegative().optional().describe(`Session duration in seconds`),firstMessageAt:v().datetime().optional().describe(`ISO 8601 timestamp`),lastMessageAt:v().datetime().optional().describe(`ISO 8601 timestamp`)}));var lO=U(()=>A([`openai`,`azure_openai`,`anthropic`,`google`,`cohere`,`huggingface`,`local`,`custom`])),uO=U(()=>T({textGeneration:b().optional().default(!0).describe(`Supports text generation`),textEmbedding:b().optional().default(!1).describe(`Supports text embedding`),imageGeneration:b().optional().default(!1).describe(`Supports image generation`),imageUnderstanding:b().optional().default(!1).describe(`Supports image understanding`),functionCalling:b().optional().default(!1).describe(`Supports function calling`),codeGeneration:b().optional().default(!1).describe(`Supports code generation`),reasoning:b().optional().default(!1).describe(`Supports advanced reasoning`)})),dO=U(()=>T({maxTokens:y().int().positive().describe(`Maximum tokens per request`),contextWindow:y().int().positive().describe(`Context window size`),maxOutputTokens:y().int().positive().optional().describe(`Maximum output tokens`),rateLimit:T({requestsPerMinute:y().int().positive().optional(),tokensPerMinute:y().int().positive().optional()}).optional()})),fO=U(()=>T({currency:v().optional().default(`USD`),inputCostPer1kTokens:y().optional().describe(`Cost per 1K input tokens`),outputCostPer1kTokens:y().optional().describe(`Cost per 1K output tokens`),embeddingCostPer1kTokens:y().optional().describe(`Cost per 1K embedding tokens`)})),pO=U(()=>T({id:v().describe(`Unique model identifier`),name:v().describe(`Model display name`),version:v().describe(`Model version (e.g., "gpt-4-turbo-2024-04-09")`),provider:lO,capabilities:uO,limits:dO,pricing:fO.optional(),endpoint:v().url().optional().describe(`Custom API endpoint`),apiKey:v().optional().describe(`API key (Warning: Prefer secretRef)`),secretRef:v().optional().describe(`Reference to stored secret (e.g. system:openai_api_key)`),region:v().optional().describe(`Deployment region (e.g., "us-east-1")`),description:v().optional(),tags:w(v()).optional().describe(`Tags for categorization`),deprecated:b().optional().default(!1),recommendedFor:w(v()).optional().describe(`Use case recommendations`)})),mO=U(()=>T({name:v().describe(`Variable name (e.g., "user_name", "context")`),type:A([`string`,`number`,`boolean`,`object`,`array`]).default(`string`),required:b().default(!1),defaultValue:S().optional(),description:v().optional(),validation:T({minLength:y().optional(),maxLength:y().optional(),pattern:v().optional(),enum:w(S()).optional()}).optional()})),hO=U(()=>T({id:v().describe(`Unique template identifier`),name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Template name (snake_case)`),label:v().describe(`Display name`),system:UE.optional().describe(`System prompt — supports {{var}} interpolation`),user:UE.describe(`User prompt template — supports {{var}} interpolation`),assistant:v().optional().describe(`Assistant message prefix`),variables:w(mO).optional().describe(`Template variables`),modelId:v().optional().describe(`Recommended model ID`),temperature:y().min(0).max(2).optional(),maxTokens:y().optional(),topP:y().optional(),frequencyPenalty:y().optional(),presencePenalty:y().optional(),stopSequences:w(v()).optional(),version:v().optional().default(`1.0.0`),description:v().optional(),category:v().optional().describe(`Template category (e.g., "code_generation", "support")`),tags:w(v()).optional(),examples:w(T({input:k(v(),S()).describe(`Example variable values`),output:v().describe(`Expected output`)})).optional()})),gO=U(()=>T({model:pO,status:A([`active`,`deprecated`,`experimental`,`disabled`]).default(`active`),priority:y().int().default(0).describe(`Priority for model selection`),fallbackModels:w(v()).optional().describe(`Fallback model IDs`),healthCheck:T({enabled:b().default(!0),intervalSeconds:y().int().default(300),lastChecked:v().optional().describe(`ISO timestamp`),status:A([`healthy`,`unhealthy`,`unknown`]).default(`unknown`)}).optional()}));U(()=>T({name:v().describe(`Registry name`),models:k(v(),gO).describe(`Model entries by ID`),promptTemplates:k(v(),hO).optional().describe(`Prompt templates by name`),defaultModel:v().optional().describe(`Default model ID`),enableAutoFallback:b().default(!0).describe(`Auto-fallback on errors`)})),U(()=>T({capabilities:w(v()).optional().describe(`Required capabilities`),maxCostPer1kTokens:y().optional().describe(`Maximum acceptable cost`),minContextWindow:y().optional().describe(`Minimum context window size`),provider:lO.optional(),tags:w(v()).optional(),excludeDeprecated:b().default(!0)}));var _O=U(()=>A([`pgvector`,`chroma`,`qdrant`,`pinecone`,`weaviate`,`milvus`,`redis`,`opensearch`,`elasticsearch`,`custom`])),vO=U(()=>T({provider:A([`openai`,`cohere`,`azure_openai`,`huggingface`,`local`,`custom`]),model:v().describe(`Provider-specific model identifier`),dimensions:y().int().positive().describe(`Embedding vector dimensions`),endpoint:v().url().optional().describe(`Custom endpoint URL`),secretRef:v().optional().describe(`Reference to stored API key secret`)})),yO=U(()=>T({provider:_O,collection:v().describe(`Collection / index / namespace name`),endpoint:v().optional().describe(`Connection string or endpoint URL`),secretRef:v().optional().describe(`Reference to stored credential secret`),dimensions:y().int().positive().optional()})),bO=U(()=>A([`stdio`,`http`,`websocket`]));U(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Machine name (snake_case)`),label:v().describe(`Display label`),transport:bO,endpoint:v().describe(`Command (stdio) or URL (http/websocket)`),secretRef:v().optional(),active:b().default(!0)}));var xO=U(()=>A([`always`,`never`,`first_call`]));U(()=>T({server:v(),toolName:v(),aliasAs:v().optional(),approval:xO.default(`never`)}));var SO=U(()=>T({onRecordChange:b().default(!0).optional(),cron:v().optional()})),CO=U(()=>T({kind:j(`object`),object:v().describe(`Short object name to index`),contentFields:w(v()).min(1).describe(`Fields contributing to document content`),metadataFields:w(v()).default([]).optional(),where:k(v(),S()).optional()})),wO=U(()=>T({kind:j(`file`),prefix:v().describe(`Storage prefix`),mimeTypes:w(v()).default([]).optional()})),TO=U(()=>T({kind:j(`http`),urls:w(v().url()).min(1),userAgent:v().optional()})),EO=U(()=>D(`kind`,[CO,wO,TO]));U(()=>T({id:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Snake_case source id`),label:v(),description:v().optional(),adapter:v().describe(`Adapter id`),adapterConfig:k(v(),S()).default({}).optional(),source:EO,embedding:vO.optional(),vectorStore:yO.optional(),refresh:SO.default({}).optional(),aiExposed:b().default(!0).optional()})),U(()=>T({id:v().describe(`Document id`),sourceId:v().describe(`Owning KnowledgeSource id`),sourceRecordId:v().optional(),content:v(),title:v().optional(),metadata:k(v(),S()).default({}).optional(),permissions:w(v()).optional()})),U(()=>T({id:v(),documentId:v(),index:y().int().nonnegative(),content:v(),metadata:k(v(),S()).optional()})),U(()=>T({chunkId:v(),documentId:v(),sourceId:v(),sourceRecordId:v().optional(),score:y(),snippet:v(),title:v().optional(),metadata:k(v(),S()).default({}).optional()}));var DO=/^[a-z_][a-z0-9_]*$/,OO=U(()=>T({name:v().regex(DO).describe(`Field machine name (snake_case)`),label:v().optional().describe(`Human-readable field label`),type:tD.describe(`Field data type`),required:b().optional().describe(`Whether the field is required`),reference:v().regex(DO).optional().describe(`Target object name for lookup / master_detail relationship fields`),options:w(T({label:v(),value:v().regex(DO)})).optional().describe(`Choices for select / multiselect / radio fields`)})),kO=U(()=>T({name:v().regex(DO).describe(`Object machine name (snake_case)`),label:v().optional().describe(`Human-readable singular label`),description:v().optional().describe(`What this object represents`),fields:w(OO).describe(`Fields to create on the object`)})),AO=U(()=>T({object:v().regex(DO).describe(`Object this view displays (snake_case)`),name:v().regex(DO).describe(`View machine name (snake_case)`),label:v().optional().describe(`Human-readable view label`),type:A([`list`,`form`,`kanban`,`calendar`]).default(`list`).describe(`View kind`),columns:w(v().regex(DO)).optional().describe(`Field names shown as columns (in order)`),groupBy:v().regex(DO).optional().describe(`REQUIRED for kanban views: the select/status field whose options become the board columns (e.g. "stage", "status"). Without it a kanban renders as a plain list.`)})),jO=U(()=>T({name:v().regex(DO).describe(`Dashboard machine name (snake_case)`),label:v().optional().describe(`Human-readable dashboard label`),widgets:w(T({id:v().regex(DO).describe(`Widget id (snake_case)`),title:v().optional().describe(`Widget title`),object:v().regex(DO).optional().describe(`Source object for the widget`),chart:A([`metric`,`bar`,`line`,`pie`,`table`]).optional().describe(`Widget visualization`),measure:v().regex(DO).optional().describe(`The field this widget aggregates (e.g. "amount", "probability"), or "count" to count records. The aggregation is chosen automatically from the field type — a money field SUMs, a percentage/rate AVERAGEs — so name the FIELD, not "total_amount". A "total revenue" widget sets measure:"amount"; an "average win rate" widget sets measure:"win_rate"; a "number of deals" widget sets measure:"count". Omit to let the builder infer from the title.`),groupBy:v().regex(DO).optional().describe(`The field to break the widget down by — the category or time axis (e.g. "stage", "created_at"). A "by status" chart MUST set this to the status field; the title and this field MUST name the SAME field. Omit for a single-number metric.`)})).optional().describe(`Widgets to place on the dashboard`)})),MO=U(()=>T({type:A([`object`,`dashboard`]).default(`object`).describe(`What this nav entry opens`),target:v().regex(DO).describe(`Object or dashboard machine name to surface (snake_case)`),label:v().optional().describe(`Nav entry label (defaults to the target label/name)`),icon:v().optional().describe(`Lucide icon name for the nav entry`)})),NO=U(()=>T({name:v().regex(DO).describe(`App machine name (snake_case)`),label:v().optional().describe(`App display label`),icon:v().optional().describe(`Lucide icon for the App Launcher`),nav:w(MO).optional().describe(`Navigation entries; omit to auto-surface every created object and dashboard`)})),PO=U(()=>T({object:v().regex(DO).describe(`Target object name (snake_case)`),records:w(k(v(),S())).describe(`Rows to seed`)}));U(()=>T({summary:v().describe(`One-line description of the proposed solution`),assumptions:w(v()).default([]).describe(`Design assumptions made from the underspecified goal`),questions:w(v()).max(2).optional().describe(`At most 1-2 structure-deciding questions to confirm before building`),objects:w(kO).describe(`Objects (tables) to create`),views:w(AO).optional().describe(`Views to create`),dashboards:w(jO).optional().describe(`Dashboards to create`),app:NO.optional().describe(`The navigation shell (app) that surfaces the created objects/dashboards to end users`),seedData:w(PO).optional().describe(`Suggested seed data (reported, not auto-applied in Phase C)`)}));var FO=T({name:v().describe(`Field machine name (snake_case)`),label:v().nullable().describe(`Human-readable field label, or null`),type:tD.describe(`Field data type`),required:b().nullable().describe(`Whether the field is required, or null`),reference:v().nullable().describe(`Target object for lookup/master_detail, or null`),options:w(T({label:v(),value:v()})).nullable().describe(`Choices for select-family fields, or null`)}),IO=T({name:v().describe(`Object machine name (snake_case)`),label:v().nullable().describe(`Human-readable singular label, or null`),description:v().nullable().describe(`What this object represents, or null`),fields:w(FO).describe(`Fields to create on the object`)}),LO=T({object:v().describe(`Object this view displays (snake_case)`),name:v().describe(`View machine name (snake_case)`),label:v().nullable().describe(`Human-readable view label, or null`),type:A([`list`,`form`,`kanban`,`calendar`]).nullable().describe(`View kind, or null for list`),columns:w(v()).nullable().describe(`Field names shown as columns, or null`),groupBy:v().nullable().describe(`REQUIRED for kanban: the select/status field whose options become the board columns (e.g. "stage"). Null for non-kanban views.`)}),RO=T({name:v().describe(`Dashboard machine name (snake_case)`),label:v().nullable().describe(`Human-readable dashboard label, or null`),widgets:w(T({id:v().describe(`Widget id (snake_case)`),title:v().nullable().describe(`Widget title, or null`),object:v().nullable().describe(`Source object, or null`),chart:A([`metric`,`bar`,`line`,`pie`,`table`]).nullable().describe(`Visualization, or null`),measure:v().nullable().describe(`The field this widget aggregates (e.g. "amount", "probability"), or "count" to count records, or null to infer from the title. The aggregation (sum vs average) is chosen automatically from the field type — name the FIELD, not "total_amount". "total revenue" → "amount"; "average win rate" → "win_rate"; "number of deals" → "count".`),groupBy:v().nullable().describe(`The field to break the widget down by — the category or time axis (e.g. "stage", "created_at"), or null for a single-number metric. A "by status" chart MUST set this to the status field; the title and this field MUST name the SAME field.`)})).nullable().describe(`Widgets to place on the dashboard, or null`)}),zO=T({type:A([`object`,`dashboard`]).describe(`What this nav entry opens`),target:v().describe(`Object or dashboard machine name to surface (snake_case)`),label:v().nullable().describe(`Nav entry label, or null`),icon:v().nullable().describe(`Lucide icon name, or null`)}),BO=T({name:v().describe(`App machine name (snake_case)`),label:v().nullable().describe(`App display label, or null`),icon:v().nullable().describe(`Lucide icon for the App Launcher, or null`),nav:w(zO).nullable().describe(`Navigation entries; null to auto-surface every created object and dashboard`)});T({summary:v().describe(`One-line description of the proposed solution`),assumptions:w(v()).describe(`Design assumptions made from the underspecified goal`),questions:w(v()).nullable().describe(`At most 1-2 structure-deciding questions to confirm before building, or null`),objects:w(IO).describe(`Objects (tables) to create`),views:w(LO).nullable().describe(`Views to create, or null`),dashboards:w(RO).nullable().describe(`Dashboards to create, or null`),app:BO.nullable().describe(`The navigation shell (app) that surfaces the created objects/dashboards, or null`)});var VO=t({AckMessageSchema:()=>dA,ApiChangelogEntrySchema:()=>hP,ApiDiscoveryQuerySchema:()=>sP,ApiDocumentationConfigSchema:()=>_P,ApiEndpointRegistrationSchema:()=>nP,ApiEndpointSchema:()=>Dk,ApiErrorSchema:()=>sk,ApiMappingSchema:()=>Ek,ApiMetadataSchema:()=>rP,ApiParameterSchema:()=>eP,ApiProtocolType:()=>ZN,ApiRegistryEntrySchema:()=>iP,ApiRegistrySchema:()=>oP,ApiResponseSchema:()=>tP,ApiRoutesSchema:()=>Ak,ApiTestCollectionSchema:()=>mP,ApiTestRequestSchema:()=>pP,ApiTestingUiConfigSchema:()=>fP,ApiTestingUiType:()=>dP,AuthEndpointPaths:()=>MP,AuthFeaturesConfigSchema:()=>FP,AuthProviderInfoSchema:()=>NP,AutomationFlowPathParamsSchema:()=>QI,AutomationRunPathParamsSchema:()=>$I,BasePresenceSchema:()=>Lk,BaseResponseSchema:()=>G,BatchEndpointsConfigSchema:()=>WN,BatchLoadingStrategySchema:()=>yk,BatchOperationResultSchema:()=>qA,BatchOperationType:()=>UA,BatchOptionsSchema:()=>GA,BatchRecordSchema:()=>WA,BatchUpdateRequestSchema:()=>KA,BatchUpdateResponseSchema:()=>JA,BulkRequestSchema:()=>dk,BulkResponseSchema:()=>gk,CacheControlSchema:()=>XA,CacheDirective:()=>YA,CacheInvalidationTarget:()=>ej,CallbackSchema:()=>qN,ChangelogEntrySchema:()=>OI,CodeGenerationTemplateSchema:()=>gP,ConflictResolutionStrategy:()=>aP,CreateExportJobRequestSchema:()=>jI,CreateExportJobResponseSchema:()=>MI,CreateRequestSchema:()=>lk,CrudEndpointPatternSchema:()=>VN,CrudEndpointsConfigSchema:()=>HN,CrudOperation:()=>BN,CursorMessageSchema:()=>lA,CursorPositionSchema:()=>tA,DataEventType:()=>Pk,DataLoaderConfigSchema:()=>vk,DeduplicationStrategy:()=>FI,DeleteResponseSchema:()=>_k,DiscoverySchema:()=>jk,DispatcherRouteSchema:()=>YF,ETagSchema:()=>ZA,EditMessageSchema:()=>uA,EditOperationSchema:()=>rA,EditOperationType:()=>nA,EmailPasswordConfigPublicSchema:()=>PP,EnhancedApiErrorSchema:()=>aj,ErrorCategory:()=>tj,ErrorHandlingConfigSchema:()=>sI,ErrorMessageSchema:()=>fA,EventFilterCondition:()=>Jk,EventFilterSchema:()=>Yk,EventMessageSchema:()=>sA,EventPatternSchema:()=>Xk,EventSubscriptionSchema:()=>Zk,ExportFormat:()=>kI,ExportJobProgressSchema:()=>NI,ExportJobStatus:()=>AI,ExportJobSummarySchema:()=>BI,FederationEntityKeySchema:()=>FA,FederationEntitySchema:()=>zA,FederationExternalFieldSchema:()=>IA,FederationGatewaySchema:()=>VA,FederationProvidesSchema:()=>RA,FederationRequiresSchema:()=>LA,FeedItemPathParamsSchema:()=>EI,FeedListFilterType:()=>DI,FeedPathParamsSchema:()=>TI,FieldErrorSchema:()=>ij,FieldMappingEntrySchema:()=>II,FilterOperator:()=>qk,FlowSummarySchema:()=>eL,GeneratedEndpointSchema:()=>XN,GetExportJobDownloadRequestSchema:()=>LI,GetExportJobDownloadResponseSchema:()=>RI,GraphQLConfigSchema:()=>HA,GraphQLDataLoaderConfigSchema:()=>OA,GraphQLDirectiveConfigSchema:()=>AA,GraphQLDirectiveLocation:()=>kA,GraphQLMutationConfigSchema:()=>TA,GraphQLPersistedQuerySchema:()=>PA,GraphQLQueryAdapterSchema:()=>pI,GraphQLQueryComplexitySchema:()=>MA,GraphQLQueryConfigSchema:()=>wA,GraphQLQueryDepthLimitSchema:()=>jA,GraphQLRateLimitSchema:()=>NA,GraphQLResolverConfigSchema:()=>DA,GraphQLSubscriptionConfigSchema:()=>EA,GraphQLTypeConfigSchema:()=>CA,HandlerStatusSchema:()=>tI,HttpMethod:()=>bk,HttpStatusCode:()=>QN,IdRequestSchema:()=>mk,ImportValidationMode:()=>PI,ListExportJobsRequestSchema:()=>zI,ListExportJobsResponseSchema:()=>VI,ListRecordResponseSchema:()=>pk,LoginType:()=>jP,MetadataCacheRequestSchema:()=>QA,MetadataCacheResponseSchema:()=>$A,MetadataEndpointsConfigSchema:()=>UN,MetadataEventType:()=>Nk,ModificationResultSchema:()=>hk,NotificationPreferencesSchema:()=>LN,NotificationSchema:()=>RN,ODataMetadataSchema:()=>gA,ODataQueryAdapterSchema:()=>mI,ObjectQLReferenceSchema:()=>$N,OpenApi31ExtensionsSchema:()=>JN,OpenApiGenerationConfigSchema:()=>cI,OpenApiSecuritySchemeSchema:()=>lP,OpenApiServerSchema:()=>cP,OpenApiSpecSchema:()=>uP,OperatorMappingSchema:()=>dI,PackagePathParamsSchema:()=>wL,PingMessageSchema:()=>pA,PongMessageSchema:()=>mA,PresenceMessageSchema:()=>cA,PresenceStateSchema:()=>eA,PresenceStatus:()=>Fk,RealtimeEventType:()=>zk,RealtimePresenceSchema:()=>Hk,RealtimeRecordAction:()=>Ik,RecordDataSchema:()=>ck,RequestValidationConfigSchema:()=>aI,ResponseEnvelopeConfigSchema:()=>oI,RestApiConfigSchema:()=>zN,RestApiEndpointSchema:()=>nI,RestApiPluginConfigSchema:()=>lI,RestApiRouteCategory:()=>eI,RestApiRouteRegistrationSchema:()=>rI,RestQueryAdapterSchema:()=>fI,RestServerConfigSchema:()=>YN,RetryStrategy:()=>rj,RouteCategory:()=>hA,RouteCoverageEntrySchema:()=>uI,RouteGenerationConfigSchema:()=>GN,RouteHealthEntrySchema:()=>Mk,ScheduleExportRequestSchema:()=>HI,ScheduleExportResponseSchema:()=>UI,ServiceInfoSchema:()=>kk,ServiceStatus:()=>Ok,SessionSchema:()=>AP,SessionUserSchema:()=>kP,SingleRecordResponseSchema:()=>fk,StandardErrorCode:()=>nj,SubgraphConfigSchema:()=>BA,SubscribeMessageSchema:()=>aA,SubscriptionEventSchema:()=>Bk,SubscriptionSchema:()=>Vk,TransportProtocol:()=>Rk,UnsubscribeMessageSchema:()=>oA,UnsubscribeRequestSchema:()=>Qk,UpdateRequestSchema:()=>uk,ValidationMode:()=>iI,VersionDefinitionSchema:()=>OP,VersionStatus:()=>DP,VersioningStrategy:()=>EP,WebSocketMessageType:()=>Kk,WebSocketPresenceStatus:()=>$k,WebhookEventSchema:()=>KN,WorkflowStateSchema:()=>IN});function W(e){if(typeof process<`u`&&{}.OS_EAGER_SCHEMAS===`1`)return e();let t,n=()=>(t===void 0&&(t=e()),t);return new Proxy(function(){},{get(e,t){let r=n(),i=r[t];return typeof i==`function`?i.bind(r):i},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())}})}var HO=W(()=>T({$field:v().describe(`Field Reference/Column Name`)}));W(()=>T({$eq:x().optional(),$ne:x().optional()})),W(()=>T({$gt:E([y(),C(),HO]).optional(),$gte:E([y(),C(),HO]).optional(),$lt:E([y(),C(),HO]).optional(),$lte:E([y(),C(),HO]).optional()})),W(()=>T({$in:w(x()).optional(),$nin:w(x()).optional()})),W(()=>T({$between:O([E([y(),C(),HO]),E([y(),C(),HO])]).optional()})),W(()=>T({$contains:v().optional(),$notContains:v().optional(),$startsWith:v().optional(),$endsWith:v().optional()})),W(()=>T({$null:b().optional(),$exists:b().optional()}));var UO=W(()=>T({$eq:x().optional(),$ne:x().optional(),$gt:E([y(),C(),HO]).optional(),$gte:E([y(),C(),HO]).optional(),$lt:E([y(),C(),HO]).optional(),$lte:E([y(),C(),HO]).optional(),$in:w(x()).optional(),$nin:w(x()).optional(),$between:O([E([y(),C(),HO]),E([y(),C(),HO])]).optional(),$contains:v().optional(),$notContains:v().optional(),$startsWith:v().optional(),$endsWith:v().optional(),$null:b().optional(),$exists:b().optional()})),WO=M(()=>k(v(),S()).and(T({$and:w(WO).optional(),$or:w(WO).optional(),$not:WO.optional()})));W(()=>T({where:WO.optional()}));var GO=M(()=>T({$and:w(E([k(v(),UO),GO])).optional(),$or:w(E([k(v(),UO),GO])).optional(),$not:E([k(v(),UO),GO]).optional()})),KO=W(()=>T({field:v(),order:A([`asc`,`desc`]).default(`asc`)})),qO=A([`count`,`sum`,`avg`,`min`,`max`,`count_distinct`,`array_agg`,`string_agg`]),JO=A([`day`,`week`,`month`,`quarter`,`year`]),YO=W(()=>E([v(),T({field:v().describe(`Field to group by`),dateGranularity:JO.optional().describe(`Bucket date values into uniform periods (day/week/month/quarter/year)`),alias:v().optional().describe(`Alias for the projected group value`)})])),XO=W(()=>T({function:qO.describe(`Aggregation function`),field:v().optional().describe(`Field to aggregate (optional for COUNT(*))`),alias:v().describe(`Result column alias`),distinct:b().optional().describe(`Apply DISTINCT before aggregation`),filter:WO.optional().describe(`Filter/Condition to apply to the aggregation (FILTER WHERE clause)`)})),ZO=A([`inner`,`left`,`right`,`full`]),QO=A([`auto`,`database`,`hash`,`loop`]),$O=M(()=>T({type:ZO.describe(`Join type`),strategy:QO.optional().describe(`Execution strategy hint`),object:v().describe(`Object/table to join`),alias:v().optional().describe(`Table alias`),on:WO.describe(`Join condition`),subquery:M(()=>ok).optional().describe(`Subquery instead of object`)})),ek=A([`row_number`,`rank`,`dense_rank`,`percent_rank`,`lag`,`lead`,`first_value`,`last_value`,`sum`,`avg`,`count`,`min`,`max`]),tk=W(()=>T({partitionBy:w(v()).optional().describe(`PARTITION BY fields`),orderBy:w(KO).optional().describe(`ORDER BY specification`),frame:T({type:A([`rows`,`range`]).optional(),start:v().optional().describe(`Frame start (e.g., "UNBOUNDED PRECEDING", "1 PRECEDING")`),end:v().optional().describe(`Frame end (e.g., "CURRENT ROW", "1 FOLLOWING")`)}).optional().describe(`Window frame specification`)})),nk=W(()=>T({function:ek.describe(`Window function name`),field:v().optional().describe(`Field to operate on (for aggregate window functions)`),alias:v().describe(`Result column alias`),over:tk.describe(`Window specification (OVER clause)`)})),rk=M(()=>E([v(),T({field:v(),fields:w(rk).optional(),alias:v().optional()})])),ik=W(()=>T({query:v().describe(`Search query text`),fields:w(v()).optional().describe(`Fields to search in (if not specified, searches all text fields)`),fuzzy:b().optional().default(!1).describe(`Enable fuzzy matching (tolerates typos)`),operator:A([`and`,`or`]).optional().default(`or`).describe(`Logical operator between terms`),boost:k(v(),y()).optional().describe(`Field-specific relevance boosting (field name -> boost factor)`),minScore:y().optional().describe(`Minimum relevance score threshold`),language:v().optional().describe(`Language for text analysis (e.g., "en", "zh", "es")`),highlight:b().optional().default(!1).describe(`Enable search result highlighting`)})),ak=T({object:v().describe(`Object name (e.g. account)`),fields:w(rk).optional().describe(`Fields to retrieve`),where:WO.optional().describe(`Filtering criteria (WHERE)`),search:ik.optional().describe(`Full-text search configuration ($search parameter)`),orderBy:w(KO).optional().describe(`Sorting instructions (ORDER BY)`),limit:y().optional().describe(`Max records to return (LIMIT)`),offset:y().optional().describe(`Records to skip (OFFSET)`),top:y().optional().describe(`Alias for limit (OData compatibility)`),cursor:k(v(),S()).optional().describe(`Cursor for keyset pagination`),joins:w($O).optional().describe(`Explicit Table Joins`),aggregations:w(XO).optional().describe(`Aggregation functions`),groupBy:w(YO).optional().describe("GROUP BY targets (strings or `{field, dateGranularity?}` objects for date bucketing)"),having:WO.optional().describe(`HAVING clause for aggregation filtering`),windowFunctions:w(nk).optional().describe(`Window functions with OVER clause`),distinct:b().optional().describe(`SELECT DISTINCT flag`)}),ok=W(()=>ak.extend({expand:M(()=>k(v(),ok)).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.")})),sk=W(()=>T({code:v().describe(`Error code (e.g. validation_error)`),message:v().describe(`Readable error message`),category:v().optional().describe(`Error category (e.g. validation, authorization)`),details:S().optional().describe(`Additional error context (e.g. field validation errors)`),requestId:v().optional().describe(`Request ID for tracking`)})),G=W(()=>T({success:b().describe(`Operation success status`),error:sk.optional().describe(`Error details if success is false`),meta:T({timestamp:v(),duration:y().optional(),requestId:v().optional(),traceId:v().optional()}).optional().describe(`Response metadata`)})),ck=W(()=>k(v(),S()).describe(`Key-value map of record data`)),lk=W(()=>T({data:ck.describe(`Record data to insert`)})),uk=W(()=>T({data:ck.describe(`Partial record data to update`)})),dk=W(()=>T({records:w(ck).describe(`Array of records to process`),allOrNone:b().default(!0).describe(`If true, rollback entire transaction on any failure`)}));W(()=>wl(ok,T({format:A([`csv`,`json`,`xlsx`]).default(`csv`)})));var fk=W(()=>G.extend({data:ck.describe(`The requested or modified record`)})),pk=W(()=>G.extend({data:w(ck).describe(`Array of matching records`),pagination:T({total:y().optional().describe(`Total matching records count`),limit:y().optional().describe(`Page size`),offset:y().optional().describe(`Page offset`),cursor:v().optional().describe(`Cursor for next page`),nextCursor:v().optional().describe(`Next cursor for pagination`),hasMore:b().describe(`Are there more pages?`)}).describe(`Pagination info`)})),mk=W(()=>T({id:v().describe(`Record ID`)})),hk=W(()=>T({id:v().optional().describe(`Record ID if processed`),success:b(),errors:w(sk).optional(),index:y().optional().describe(`Index in original request`),data:S().optional().describe(`Result data (e.g. created record)`)})),gk=W(()=>G.extend({data:w(hk).describe(`Results for each item in the batch`)})),_k=W(()=>G.extend({id:v().describe(`ID of the deleted record`)}));T({ids:w(v())});var vk=W(()=>T({maxBatchSize:y().int().default(100).describe(`Maximum number of keys per batch load`),batchScheduleFn:A([`microtask`,`timeout`,`manual`]).default(`microtask`).describe(`Scheduling strategy for collecting batch keys`),cacheEnabled:b().default(!0).describe(`Enable per-request result caching`),cacheKeyFn:v().optional().describe(`Name or identifier of the cache key function`),cacheTtl:y().min(0).optional().describe(`Cache time-to-live in seconds (0 = no expiration)`),coalesceRequests:b().default(!0).describe(`Deduplicate identical requests within a batch window`),maxConcurrency:y().int().optional().describe(`Maximum parallel batch requests`)})),yk=W(()=>T({strategy:A([`dataloader`,`windowed`,`prefetch`]).describe(`Batch loading strategy type`),windowMs:y().optional().describe(`Collection window duration in milliseconds (for windowed strategy)`),prefetchDepth:y().int().optional().describe(`Depth of relation prefetching (for prefetch strategy)`),associationLoading:A([`lazy`,`eager`,`batch`]).default(`batch`).describe(`How to load related associations`)}));W(()=>T({preventNPlusOne:b().describe(`Enable N+1 query detection and prevention`),dataLoader:vk.optional().describe(`DataLoader batch loading configuration`),batchStrategy:yk.optional().describe(`Batch loading strategy configuration`),maxQueryDepth:y().int().describe(`Maximum depth for nested relation queries`),queryComplexityLimit:y().optional().describe(`Maximum allowed query complexity score`),enableQueryPlan:b().default(!1).describe(`Log query execution plans for debugging`)}));var bk=A([`GET`,`POST`,`PUT`,`DELETE`,`PATCH`,`HEAD`,`OPTIONS`]),xk=W(()=>A([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`])),Sk=W(()=>T({url:v().describe(`API endpoint URL`),method:xk.optional().default(`GET`).describe(`HTTP method`),headers:k(v(),v()).optional().describe(`Custom HTTP headers`),params:k(v(),S()).optional().describe(`Query parameters`),body:S().optional().describe(`Request body for POST/PUT/PATCH`)})),Ck=W(()=>T({enabled:b().default(!0).describe(`Enable CORS`),origins:E([v(),w(v())]).default(`*`).describe(`Allowed origins (* for all)`),methods:w(bk).optional().describe(`Allowed HTTP methods`),credentials:b().default(!1).describe(`Allow credentials (cookies, authorization headers)`),maxAge:y().int().optional().describe(`Preflight cache duration in seconds`)})),wk=W(()=>T({enabled:b().default(!1).describe(`Enable rate limiting`),windowMs:y().int().default(6e4).describe(`Time window in milliseconds`),maxRequests:y().int().default(100).describe(`Max requests per window`)})),Tk=W(()=>T({path:v().describe(`URL path to serve from`),directory:v().describe(`Physical directory to serve`),cacheControl:v().optional().describe(`Cache-Control header value`)})),Ek=W(()=>T({source:v().describe(`Source field/path`),target:v().describe(`Target field/path`),transform:v().optional().describe(`Transformation function name`)})),Dk=T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Unique endpoint ID`),path:v().regex(/^\//).describe(`URL Path (e.g. /api/v1/customers)`),method:bk.describe(`HTTP Method`),summary:v().optional(),description:v().optional(),type:A([`flow`,`script`,`object_operation`,`proxy`]).describe(`Implementation type`),target:v().describe(`Target Flow ID, Script Name, or Proxy URL`),objectParams:T({object:v().optional(),operation:A([`find`,`get`,`create`,`update`,`delete`]).optional()}).optional().describe(`For object_operation type`),inputMapping:w(Ek).optional().describe(`Map Request Body to Internal Params`),outputMapping:w(Ek).optional().describe(`Map Internal Result to Response Body`),authRequired:b().default(!0).describe(`Require authentication`),rateLimit:wk.optional().describe(`Rate limiting policy`),cacheTtl:y().optional().describe(`Response cache TTL in seconds`)});Object.assign(Dk,{create:e=>e});var Ok=A([`available`,`registered`,`unavailable`,`degraded`,`stub`]).describe(`available = fully operational, registered = route declared but handler unverified, unavailable = not installed, degraded = partial, stub = placeholder that returns 501`),kk=W(()=>T({enabled:b(),status:Ok,handlerReady:b().optional().describe(`Whether the HTTP handler is confirmed to be mounted. Omitted = readiness unknown/unverified; true = handler mounted; false = handler missing or stub (likely 501).`),route:v().optional().describe(`e.g. /api/v1/analytics`),provider:v().optional().describe(`e.g. "objectql", "plugin-redis", "driver-memory"`),version:v().optional().describe(`Semantic version of the service implementation (e.g. "3.0.6")`),message:v().optional().describe(`e.g. "Install plugin-workflow to enable"`),rateLimit:T({requestsPerMinute:y().int().optional().describe(`Maximum requests per minute`),requestsPerHour:y().int().optional().describe(`Maximum requests per hour`),burstLimit:y().int().optional().describe(`Maximum burst request count`),retryAfterMs:y().int().optional().describe(`Suggested retry-after delay in milliseconds when rate-limited`)}).optional().describe(`Rate limit and quota info for this service`)})),Ak=W(()=>T({data:v().describe(`e.g. /api/v1/data`),metadata:v().describe(`e.g. /api/v1/meta`),discovery:v().optional().describe(`e.g. /api/v1/discovery`),ui:v().optional().describe(`e.g. /api/v1/ui`),auth:v().optional().describe(`e.g. /api/v1/auth`),automation:v().optional().describe(`e.g. /api/v1/automation`),storage:v().optional().describe(`e.g. /api/v1/storage`),analytics:v().optional().describe(`e.g. /api/v1/analytics`),graphql:v().optional().describe(`e.g. /graphql`),packages:v().optional().describe(`e.g. /api/v1/packages`),workflow:v().optional().describe(`e.g. /api/v1/workflow`),approvals:v().optional().describe(`e.g. /api/v1/approvals`),realtime:v().optional().describe(`e.g. /api/v1/realtime`),notifications:v().optional().describe(`e.g. /api/v1/notifications`),ai:v().optional().describe(`e.g. /api/v1/ai`),i18n:v().optional().describe(`e.g. /api/v1/i18n`),feed:v().optional().describe(`e.g. /api/v1/feed`)})),jk=W(()=>T({name:v(),version:v(),environment:A([`production`,`sandbox`,`development`]),routes:Ak,locale:T({default:v(),supported:w(v()),timezone:v()}),services:k(v(),kk).describe(`Per-service availability map keyed by CoreServiceName`),capabilities:k(v(),T({enabled:b().describe(`Whether this capability is available`),features:k(v(),b()).optional().describe(`Sub-feature flags within this capability`),description:v().optional().describe(`Human-readable capability description`)})).optional().describe(`Hierarchical capability descriptors for frontend intelligent adaptation`),schemaDiscovery:T({openapi:v().optional().describe(`URL to OpenAPI (Swagger) specification (e.g., "/api/v1/openapi.json")`),graphql:v().optional().describe(`URL to GraphQL schema endpoint (e.g., "/graphql")`),jsonSchema:v().optional().describe(`URL to JSON Schema definitions`)}).optional().describe(`Schema discovery endpoints for API toolchain integration`),metadata:k(v(),S()).optional().describe(`Custom metadata key-value pairs for extensibility`)}));W(()=>T({feed:b().describe(`Whether the backend supports Feed / Chatter API`),comments:b().describe(`Whether the backend supports comments (a subset of Feed)`),automation:b().describe(`Whether the backend supports Automation CRUD (flows, triggers)`),cron:b().describe(`Whether the backend supports cron scheduling`),search:b().describe(`Whether the backend supports full-text search`),export:b().describe(`Whether the backend supports async export`),chunkedUpload:b().describe(`Whether the backend supports chunked (multipart) uploads`)}).describe(`Well-known capability flags for frontend intelligent adaptation`));var Mk=W(()=>T({route:v().describe(`Route path pattern`),method:bk.describe(`HTTP method (GET, POST, etc.)`),service:v().describe(`Target service name`),declared:b().describe(`Whether the route is declared in discovery/metadata`),handlerRegistered:b().describe(`Whether the HTTP handler is registered`),healthStatus:A([`pass`,`fail`,`missing`,`skip`]).describe(`pass = handler responds, fail = 501/503, missing = no handler (404), skip = not checked`),message:v().optional().describe(`Diagnostic message`)}));W(()=>T({timestamp:v().describe(`ISO 8601 timestamp of report generation`),adapter:v().describe(`Adapter or runtime that produced this report`),totalDeclared:y().int().describe(`Total routes declared in discovery`),totalRegistered:y().int().describe(`Routes with confirmed handler`),totalMissing:y().int().describe(`Routes missing a handler`),routes:w(Mk).describe(`Per-route health entries`)}));var Nk=A(`metadata.object.created,metadata.object.updated,metadata.object.deleted,metadata.field.created,metadata.field.updated,metadata.field.deleted,metadata.view.created,metadata.view.updated,metadata.view.deleted,metadata.app.created,metadata.app.updated,metadata.app.deleted,metadata.agent.created,metadata.agent.updated,metadata.agent.deleted,metadata.tool.created,metadata.tool.updated,metadata.tool.deleted,metadata.flow.created,metadata.flow.updated,metadata.flow.deleted,metadata.action.created,metadata.action.updated,metadata.action.deleted,metadata.workflow.created,metadata.workflow.updated,metadata.workflow.deleted,metadata.dashboard.created,metadata.dashboard.updated,metadata.dashboard.deleted,metadata.report.created,metadata.report.updated,metadata.report.deleted,metadata.role.created,metadata.role.updated,metadata.role.deleted,metadata.permission.created,metadata.permission.updated,metadata.permission.deleted`.split(`,`)),Pk=A([`data.record.created`,`data.record.updated`,`data.record.deleted`,`data.field.changed`]);W(()=>T({id:v().uuid().describe(`Unique event identifier`),type:Nk.describe(`Event type`),metadataType:v().describe(`Metadata type (object, view, agent, etc.)`),name:v().describe(`Metadata item name`),packageId:v().optional().describe(`Package ID`),definition:S().optional().describe(`Full definition (create/update only)`),userId:v().optional().describe(`User who triggered the event`),timestamp:v().datetime().describe(`Event timestamp`)})),W(()=>T({id:v().uuid().describe(`Unique event identifier`),type:Pk.describe(`Event type`),object:v().describe(`Object name`),recordId:v().describe(`Record ID`),changes:k(v(),S()).optional().describe(`Changed fields`),before:k(v(),S()).optional().describe(`Before state`),after:k(v(),S()).optional().describe(`After state`),userId:v().optional().describe(`User who triggered the event`),timestamp:v().datetime().describe(`Event timestamp`)}));var Fk=A([`online`,`away`,`busy`,`offline`]),Ik=A([`created`,`updated`,`deleted`]),Lk=W(()=>T({userId:v().describe(`User identifier`),status:Fk.describe(`Current presence status`),lastSeen:v().datetime().describe(`ISO 8601 datetime of last activity`),metadata:k(v(),S()).optional().describe(`Custom presence data (e.g., current page, custom status)`)})),Rk=A([`websocket`,`sse`,`polling`]),zk=A([`record.created`,`record.updated`,`record.deleted`,`field.changed`]),Bk=W(()=>T({type:zk.describe(`Type of event to subscribe to`),object:v().optional().describe(`Object name to subscribe to`),filters:S().optional().describe(`Filter conditions`)})),Vk=W(()=>T({id:v().uuid().describe(`Unique subscription identifier`),events:w(Bk).describe(`Array of events to subscribe to`),transport:Rk.describe(`Transport protocol to use`),channel:v().optional().describe(`Optional channel name for grouping subscriptions`)})),Hk=W(()=>Lk);W(()=>T({id:v().uuid().describe(`Unique event identifier`),type:v().describe(`Event type (e.g., record.created, record.updated)`),object:v().optional().describe(`Object name the event relates to`),action:Ik.optional().describe(`Action performed`),payload:k(v(),S()).describe(`Event payload data`),timestamp:v().datetime().describe(`ISO 8601 datetime when event occurred`),userId:v().optional().describe(`User who triggered the event`),sessionId:v().optional().describe(`Session identifier`)})),W(()=>T({enabled:b().default(!0).describe(`Enable realtime synchronization`),transport:Rk.default(`websocket`).describe(`Transport protocol`),subscriptions:w(Vk).optional().describe(`Default subscriptions`)}).passthrough());var Uk=W(()=>v().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)`)),Wk=W(()=>v().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)`)),Gk=W(()=>v().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)`)),Kk=A([`subscribe`,`unsubscribe`,`event`,`ping`,`pong`,`ack`,`error`,`presence`,`cursor`,`edit`]),qk=A([`eq`,`ne`,`gt`,`gte`,`lt`,`lte`,`in`,`nin`,`contains`,`startsWith`,`endsWith`,`exists`,`regex`]),Jk=T({field:v().describe(`Field path to filter on (supports dot notation, e.g., "user.email")`),operator:qk.describe(`Comparison operator`),value:S().optional().describe(`Value to compare against (not needed for "exists" operator)`)}),Yk=W(()=>T({conditions:w(Jk).optional().describe(`Array of filter conditions`),and:M(()=>w(Yk)).optional().describe(`AND logical combination of filters`),or:M(()=>w(Yk)).optional().describe(`OR logical combination of filters`),not:M(()=>Yk).optional().describe(`NOT logical negation of filter`)})),Xk=W(()=>v().min(1).regex(/^[a-z*][a-z0-9_.*]*$/,{message:`Event pattern must be lowercase and may contain letters, numbers, underscores, dots, or wildcards (e.g., "record.*", "*.created", "user.login")`}).describe(`Event pattern (supports wildcards like "record.*" or "*.created")`)),Zk=W(()=>T({subscriptionId:v().uuid().describe(`Unique subscription identifier`),events:w(Xk).describe(`Event patterns to subscribe to (supports wildcards, e.g., "record.*", "user.created")`),objects:w(v()).optional().describe(`Object names to filter events by (e.g., ["account", "contact"])`),filters:Yk.optional().describe(`Advanced filter conditions for event payloads`),channels:w(v()).optional().describe(`Channel names for scoped subscriptions`)})),Qk=W(()=>T({subscriptionId:v().uuid().describe(`Subscription ID to unsubscribe from`)})),$k=Fk,eA=W(()=>T({userId:v().describe(`User identifier`),sessionId:v().uuid().describe(`Unique session identifier`),status:$k.describe(`Current presence status`),lastSeen:v().datetime().describe(`ISO 8601 datetime of last activity`),currentLocation:v().optional().describe(`Current page/route user is viewing`),device:A([`desktop`,`mobile`,`tablet`,`other`]).optional().describe(`Device type`),customStatus:v().optional().describe(`Custom user status message`),metadata:k(v(),S()).optional().describe(`Additional custom presence data`)}));W(()=>T({status:$k.optional().describe(`Updated presence status`),currentLocation:v().optional().describe(`Updated current location`),customStatus:v().optional().describe(`Updated custom status message`),metadata:k(v(),S()).optional().describe(`Updated metadata`)}));var tA=W(()=>T({userId:v().describe(`User identifier`),sessionId:v().uuid().describe(`Session identifier`),documentId:v().describe(`Document identifier being edited`),position:T({line:y().int().nonnegative().describe(`Line number (0-indexed)`),column:y().int().nonnegative().describe(`Column number (0-indexed)`)}).optional().describe(`Cursor position in document`),selection:T({start:T({line:y().int().nonnegative(),column:y().int().nonnegative()}),end:T({line:y().int().nonnegative(),column:y().int().nonnegative()})}).optional().describe(`Selection range (if text is selected)`),color:v().optional().describe(`Cursor color for visual representation`),userName:v().optional().describe(`Display name of user`),lastUpdate:v().datetime().describe(`ISO 8601 datetime of last cursor update`)})),nA=A([`insert`,`delete`,`replace`]),rA=W(()=>T({operationId:v().uuid().describe(`Unique operation identifier`),documentId:v().describe(`Document identifier`),userId:v().describe(`User who performed the edit`),sessionId:v().uuid().describe(`Session identifier`),type:nA.describe(`Type of edit operation`),position:T({line:y().int().nonnegative().describe(`Line number (0-indexed)`),column:y().int().nonnegative().describe(`Column number (0-indexed)`)}).describe(`Starting position of the operation`),endPosition:T({line:y().int().nonnegative(),column:y().int().nonnegative()}).optional().describe(`Ending position (for delete/replace operations)`),content:v().optional().describe(`Content to insert/replace`),version:y().int().nonnegative().describe(`Document version before this operation`),timestamp:v().datetime().describe(`ISO 8601 datetime when operation was created`),baseOperationId:v().uuid().optional().describe(`Previous operation ID this builds upon (for OT)`)}));W(()=>T({documentId:v().describe(`Document identifier`),version:y().int().nonnegative().describe(`Current document version`),content:v().describe(`Current document content`),lastModified:v().datetime().describe(`ISO 8601 datetime of last modification`),activeSessions:w(v().uuid()).describe(`Active editing session IDs`),checksum:v().optional().describe(`Content checksum for integrity verification`)}));var iA=T({messageId:v().uuid().describe(`Unique message identifier`),type:Kk.describe(`Message type`),timestamp:v().datetime().describe(`ISO 8601 datetime when message was sent`)}),aA=W(()=>iA.extend({type:j(`subscribe`),subscription:Zk.describe(`Subscription configuration`)})),oA=W(()=>iA.extend({type:j(`unsubscribe`),request:Qk.describe(`Unsubscribe request`)})),sA=W(()=>iA.extend({type:j(`event`),subscriptionId:v().uuid().describe(`Subscription ID this event belongs to`),eventName:Gk.describe(`Event name`),object:v().optional().describe(`Object name the event relates to`),payload:S().describe(`Event payload data`),userId:v().optional().describe(`User who triggered the event`)})),cA=W(()=>iA.extend({type:j(`presence`),presence:eA.describe(`Presence state`)})),lA=W(()=>iA.extend({type:j(`cursor`),cursor:tA.describe(`Cursor position`)})),uA=W(()=>iA.extend({type:j(`edit`),operation:rA.describe(`Edit operation`)})),dA=W(()=>iA.extend({type:j(`ack`),ackMessageId:v().uuid().describe(`ID of the message being acknowledged`),success:b().describe(`Whether the operation was successful`),error:v().optional().describe(`Error message if operation failed`)})),fA=W(()=>iA.extend({type:j(`error`),code:v().describe(`Error code`),message:v().describe(`Error message`),details:S().optional().describe(`Additional error details`)})),pA=W(()=>iA.extend({type:j(`ping`)})),mA=W(()=>iA.extend({type:j(`pong`),pingMessageId:v().uuid().optional().describe(`ID of ping message being responded to`)}));W(()=>D(`type`,[aA,oA,sA,cA,lA,uA,dA,fA,pA,mA])),W(()=>T({url:v().url().describe(`WebSocket server URL`),protocols:w(v()).optional().describe(`WebSocket sub-protocols`),reconnect:b().optional().default(!0).describe(`Enable automatic reconnection`),reconnectInterval:y().int().positive().optional().default(1e3).describe(`Reconnection interval in milliseconds`),maxReconnectAttempts:y().int().positive().optional().default(5).describe(`Maximum reconnection attempts`),pingInterval:y().int().positive().optional().default(3e4).describe(`Ping interval in milliseconds`),timeout:y().int().positive().optional().default(5e3).describe(`Message timeout in milliseconds`),headers:k(v(),v()).optional().describe(`Custom headers for WebSocket handshake`)})),W(()=>T({type:A([`subscribe`,`unsubscribe`,`data-change`,`presence-update`,`cursor-update`,`error`]).describe(`Event type`),channel:v().describe(`Channel identifier (e.g., "record.account.123", "user.456")`),payload:S().describe(`Event payload data`),timestamp:y().describe(`Unix timestamp in milliseconds`)})),W(()=>T({userId:v().describe(`User identifier`),userName:v().describe(`User display name`),status:A([`online`,`away`,`offline`]).describe(`User presence status`),lastSeen:y().describe(`Unix timestamp of last activity in milliseconds`),metadata:k(v(),S()).optional().describe(`Additional presence metadata (e.g., current page, custom status)`)})),W(()=>T({userId:v().describe(`User identifier`),recordId:v().describe(`Record identifier being edited`),fieldName:v().describe(`Field name being edited`),position:y().describe(`Cursor position (character offset from start)`),selection:T({start:y().describe(`Selection start position`),end:y().describe(`Selection end position`)}).optional().describe(`Text selection range (if text is selected)`)})),W(()=>T({enabled:b().default(!1).describe(`Enable WebSocket server`),path:v().default(`/ws`).describe(`WebSocket endpoint path`),heartbeatInterval:y().default(3e4).describe(`Heartbeat interval in milliseconds`),reconnectAttempts:y().default(5).describe(`Maximum reconnection attempts for clients`),presence:b().default(!1).describe(`Enable presence tracking`),cursorSharing:b().default(!1).describe(`Enable collaborative cursor sharing`)}));var hA=A([`system`,`api`,`auth`,`static`,`webhook`,`plugin`]);W(()=>T({method:bk,path:v().describe(`URL Path pattern`),category:hA.default(`api`),handler:v().describe(`Unique handler identifier`),summary:v().optional().describe(`OpenAPI summary`),description:v().optional().describe(`OpenAPI description`),public:b().default(!1).describe(`Is publicly accessible`),permissions:w(v()).optional().describe(`Required permissions`),timeout:y().int().optional().describe(`Execution timeout in ms`),rateLimit:v().optional().describe(`Rate limit policy name`)})),W(()=>T({basePath:v().default(`/api`).describe(`Global API prefix`),mounts:T({data:v().default(`/data`).describe(`Data Protocol (CRUD)`),metadata:v().default(`/meta`).describe(`Metadata Protocol (Schemas)`),auth:v().default(`/auth`).describe(`Auth Protocol`),automation:v().default(`/automation`).describe(`Automation Protocol`),storage:v().default(`/storage`).describe(`Storage Protocol`),analytics:v().default(`/analytics`).describe(`Analytics Protocol`),graphql:v().default(`/graphql`).describe(`GraphQL Endpoint`),ui:v().default(`/ui`).describe(`UI Metadata Protocol (Views, Layouts)`),workflow:v().default(`/workflow`).describe(`Workflow Engine Protocol`),realtime:v().default(`/realtime`).describe(`Realtime/WebSocket Protocol`),notifications:v().default(`/notifications`).describe(`Notification Protocol`),ai:v().default(`/ai`).describe(`AI Engine Protocol (NLQ, Chat, Suggest)`),i18n:v().default(`/i18n`).describe(`Internationalization Protocol`),packages:v().default(`/packages`).describe(`Package Management Protocol`)}).default({data:`/data`,metadata:`/meta`,auth:`/auth`,automation:`/automation`,storage:`/storage`,analytics:`/analytics`,graphql:`/graphql`,ui:`/ui`,workflow:`/workflow`,realtime:`/realtime`,notifications:`/notifications`,ai:`/ai`,i18n:`/i18n`,packages:`/packages`}),cors:Ck.optional(),staticMounts:w(Tk).optional()})),W(()=>T({$select:E([v(),w(v())]).optional().describe(`Fields to select`),$filter:v().optional().describe(`Filter expression (OData filter syntax)`),$orderby:E([v(),w(v())]).optional().describe(`Sort order`),$top:y().int().min(0).optional().describe(`Max results to return`),$skip:y().int().min(0).optional().describe(`Results to skip`),$expand:E([v(),w(v())]).optional().describe(`Navigation properties to expand (lookup/master_detail fields)`),$count:b().optional().describe(`Include total count`),$search:v().optional().describe(`Search expression`),$format:A([`json`,`xml`,`atom`]).optional().describe(`Response format`),$apply:v().optional().describe(`Aggregation expression`)})),W(()=>A([`eq`,`ne`,`lt`,`le`,`gt`,`ge`,`and`,`or`,`not`,`(`,`)`,`in`,`has`])),W(()=>A(`contains.startswith.endswith.length.indexof.substring.tolower.toupper.trim.concat.year.month.day.hour.minute.second.date.time.now.maxdatetime.mindatetime.round.floor.ceiling.cast.isof.any.all`.split(`.`))),W(()=>T({"@odata.context":v().url().optional().describe(`Metadata context URL`),"@odata.count":y().int().optional().describe(`Total results count`),"@odata.nextLink":v().url().optional().describe(`Next page URL`),value:w(k(v(),S())).describe(`Results array`)})),W(()=>T({error:T({code:v().describe(`Error code`),message:v().describe(`Error message`),target:v().optional().describe(`Error target`),details:w(T({code:v(),message:v(),target:v().optional()})).optional().describe(`Error details`),innererror:k(v(),S()).optional().describe(`Inner error details`)})}));var gA=W(()=>T({namespace:v().describe(`Service namespace`),entityTypes:w(T({name:v().describe(`Entity type name`),key:w(v()).describe(`Key fields`),properties:w(T({name:v(),type:v().describe(`OData type (Edm.String, Edm.Int32, etc.)`),nullable:b().default(!0)})),navigationProperties:w(T({name:v(),type:v(),partner:v().optional()})).optional()})).describe(`Entity types`),entitySets:w(T({name:v().describe(`Entity set name`),entityType:v().describe(`Entity type`)})).describe(`Entity sets`)}));W(()=>T({enabled:b().default(!0).describe(`Enable OData API`),path:v().default(`/odata`).describe(`OData endpoint path`),metadata:gA.optional().describe(`OData metadata configuration`)}).passthrough());var _A=A([`cel`,`js`,`cron`,`template`]),vA=T({rationale:v().optional(),generatedBy:v().optional()}),yA=T({dialect:_A,source:v().min(1).optional(),ast:S().optional(),meta:vA.optional()}).refine(e=>e.source!==void 0||e.ast!==void 0,{message:"Expression requires at least one of `source` or `ast`"}),bA=E([v().min(1).transform(e=>({dialect:`cel`,source:e})),yA]),xA=E([v().min(1).transform(e=>({dialect:`cron`,source:e})),yA]),SA=E([v().min(1).transform(e=>({dialect:`template`,source:e})),yA]);A([`ID`,`String`,`Int`,`Float`,`Boolean`,`DateTime`,`Date`,`Time`,`JSON`,`JSONObject`,`Upload`,`URL`,`Email`,`PhoneNumber`,`Currency`,`Decimal`,`BigInt`,`Long`,`UUID`,`Base64`,`Void`]);var CA=W(()=>T({name:v().describe(`GraphQL type name (PascalCase recommended)`),object:v().describe(`Source ObjectQL object name`),description:v().optional().describe(`Type description`),fields:T({include:w(v()).optional().describe(`Fields to include`),exclude:w(v()).optional().describe(`Fields to exclude (e.g., sensitive fields)`),mappings:k(v(),T({graphqlName:v().optional().describe(`Custom GraphQL field name`),graphqlType:v().optional().describe(`Override GraphQL type`),description:v().optional().describe(`Field description`),deprecationReason:v().optional().describe(`Why field is deprecated`),nullable:b().optional().describe(`Override nullable`)})).optional().describe(`Field-level customizations`)}).optional().describe(`Field configuration`),interfaces:w(v()).optional().describe(`GraphQL interface names`),isInterface:b().optional().default(!1).describe(`Define as GraphQL interface`),directives:w(T({name:v().describe(`Directive name`),args:k(v(),S()).optional().describe(`Directive arguments`)})).optional().describe(`GraphQL directives`)})),wA=W(()=>T({name:v().describe(`Query field name (camelCase recommended)`),object:v().describe(`Source ObjectQL object name`),type:A([`get`,`list`,`search`]).describe(`Query type`),description:v().optional().describe(`Query description`),args:k(v(),T({type:v().describe(`GraphQL type (e.g., "ID!", "String", "Int")`),description:v().optional().describe(`Argument description`),defaultValue:S().optional().describe(`Default value`)})).optional().describe(`Query arguments`),filtering:T({enabled:b().default(!0).describe(`Allow filtering`),fields:w(v()).optional().describe(`Filterable fields`),operators:w(A([`eq`,`ne`,`gt`,`gte`,`lt`,`lte`,`in`,`notIn`,`contains`,`startsWith`,`endsWith`,`isNull`,`isNotNull`])).optional().describe(`Allowed filter operators`)}).optional().describe(`Filtering capabilities`),sorting:T({enabled:b().default(!0).describe(`Allow sorting`),fields:w(v()).optional().describe(`Sortable fields`),defaultSort:T({field:v(),direction:A([`ASC`,`DESC`])}).optional().describe(`Default sort order`)}).optional().describe(`Sorting capabilities`),pagination:T({enabled:b().default(!0).describe(`Enable pagination`),type:A([`offset`,`cursor`,`relay`]).default(`offset`).describe(`Pagination style`),defaultLimit:y().int().min(1).default(20).describe(`Default page size`),maxLimit:y().int().min(1).default(100).describe(`Maximum page size`),cursors:T({field:v().default(`id`).describe(`Field to use for cursor pagination`)}).optional()}).optional().describe(`Pagination configuration`),fields:T({required:w(v()).optional().describe(`Required fields (always returned)`),selectable:w(v()).optional().describe(`Selectable fields`)}).optional().describe(`Field selection configuration`),authRequired:b().default(!0).describe(`Require authentication`),permissions:w(v()).optional().describe(`Required permissions`),cache:T({enabled:b().default(!1).describe(`Enable caching`),ttl:y().int().min(0).optional().describe(`Cache TTL in seconds`),key:SA.optional().describe(`Cache key template — supports {{var}} interpolation`)}).optional().describe(`Query caching`)})),TA=W(()=>T({name:v().describe(`Mutation field name (camelCase recommended)`),object:v().describe(`Source ObjectQL object name`),type:A([`create`,`update`,`delete`,`upsert`,`custom`]).describe(`Mutation type`),description:v().optional().describe(`Mutation description`),input:T({typeName:v().optional().describe(`Custom input type name`),fields:T({include:w(v()).optional().describe(`Fields to include`),exclude:w(v()).optional().describe(`Fields to exclude`),required:w(v()).optional().describe(`Required input fields`)}).optional().describe(`Input field configuration`),validation:T({enabled:b().default(!0).describe(`Enable input validation`),rules:w(v()).optional().describe(`Custom validation rules`)}).optional().describe(`Input validation`)}).optional().describe(`Input configuration`),output:T({type:A([`object`,`payload`,`boolean`,`custom`]).default(`object`).describe(`Output type`),includeEnvelope:b().optional().default(!1).describe(`Wrap in success/error payload`),customType:v().optional().describe(`Custom output type name`)}).optional().describe(`Output configuration`),transaction:T({enabled:b().default(!0).describe(`Use database transaction`),isolationLevel:A([`read_uncommitted`,`read_committed`,`repeatable_read`,`serializable`]).optional().describe(`Transaction isolation level`)}).optional().describe(`Transaction configuration`),authRequired:b().default(!0).describe(`Require authentication`),permissions:w(v()).optional().describe(`Required permissions`),hooks:T({before:w(v()).optional().describe(`Pre-mutation hooks`),after:w(v()).optional().describe(`Post-mutation hooks`)}).optional().describe(`Lifecycle hooks`)})),EA=W(()=>T({name:v().describe(`Subscription field name (camelCase recommended)`),object:v().describe(`Source ObjectQL object name`),events:w(A([`created`,`updated`,`deleted`,`custom`])).describe(`Events to subscribe to`),description:v().optional().describe(`Subscription description`),filter:T({enabled:b().default(!0).describe(`Allow filtering subscriptions`),fields:w(v()).optional().describe(`Filterable fields`)}).optional().describe(`Subscription filtering`),payload:T({includeEntity:b().default(!0).describe(`Include entity in payload`),includePreviousValues:b().optional().default(!1).describe(`Include previous field values`),includeMeta:b().optional().default(!0).describe(`Include metadata (timestamp, user, etc.)`)}).optional().describe(`Payload configuration`),authRequired:b().default(!0).describe(`Require authentication`),permissions:w(v()).optional().describe(`Required permissions`),rateLimit:T({enabled:b().default(!0).describe(`Enable rate limiting`),maxSubscriptionsPerUser:y().int().min(1).default(10).describe(`Max concurrent subscriptions per user`),throttleMs:y().int().min(0).optional().describe(`Throttle interval in milliseconds`)}).optional().describe(`Subscription rate limiting`)})),DA=W(()=>T({path:v().describe(`Resolver path (Type.field)`),type:A([`datasource`,`computed`,`script`,`proxy`]).describe(`Resolver implementation type`),implementation:T({datasource:v().optional().describe(`Datasource ID`),query:v().optional().describe(`Query/SQL to execute`),expression:bA.optional().describe('Computation expression — CEL formula, e.g. F`record.firstName + " " + record.lastName`'),dependencies:w(v()).optional().describe(`Dependent fields`),script:v().optional().describe(`Script ID or inline code`),url:v().optional().describe(`Proxy URL`),method:A([`GET`,`POST`,`PUT`,`DELETE`]).optional().describe(`HTTP method`)}).optional().describe(`Implementation configuration`),cache:T({enabled:b().default(!1).describe(`Enable resolver caching`),ttl:y().int().min(0).optional().describe(`Cache TTL in seconds`),keyArgs:w(v()).optional().describe(`Arguments to include in cache key`)}).optional().describe(`Resolver caching`)})),OA=W(()=>T({name:v().describe(`DataLoader name`),source:v().describe(`Source object or datasource`),batchFunction:T({type:A([`findByIds`,`query`,`script`,`custom`]).describe(`Batch function type`),keyField:v().optional().describe(`Field to batch on (e.g., "id")`),query:v().optional().describe(`Query template`),script:v().optional().describe(`Script ID`),maxBatchSize:y().int().min(1).optional().default(100).describe(`Maximum batch size`)}).describe(`Batch function configuration`),cache:T({enabled:b().default(!0).describe(`Enable per-request caching`),keyFn:v().optional().describe(`Custom cache key function`)}).optional().describe(`DataLoader caching`),options:T({batch:b().default(!0).describe(`Enable batching`),cache:b().default(!0).describe(`Enable caching`),maxCacheSize:y().int().min(0).optional().describe(`Max cache entries`)}).optional().describe(`DataLoader options`)})),kA=A([`QUERY`,`MUTATION`,`SUBSCRIPTION`,`FIELD`,`FRAGMENT_DEFINITION`,`FRAGMENT_SPREAD`,`INLINE_FRAGMENT`,`VARIABLE_DEFINITION`,`SCHEMA`,`SCALAR`,`OBJECT`,`FIELD_DEFINITION`,`ARGUMENT_DEFINITION`,`INTERFACE`,`UNION`,`ENUM`,`ENUM_VALUE`,`INPUT_OBJECT`,`INPUT_FIELD_DEFINITION`]),AA=W(()=>T({name:v().regex(/^[a-z][a-zA-Z0-9]*$/).describe(`Directive name (camelCase)`),description:v().optional().describe(`Directive description`),locations:w(kA).describe(`Directive locations`),args:k(v(),T({type:v().describe(`Argument type`),description:v().optional().describe(`Argument description`),defaultValue:S().optional().describe(`Default value`)})).optional().describe(`Directive arguments`),repeatable:b().optional().default(!1).describe(`Can be applied multiple times`),implementation:T({type:A([`auth`,`validation`,`transform`,`cache`,`deprecation`,`custom`]).describe(`Directive type`),handler:v().optional().describe(`Handler function name or script`)}).optional().describe(`Directive implementation`)})),jA=W(()=>T({enabled:b().default(!0).describe(`Enable query depth limiting`),maxDepth:y().int().min(1).default(10).describe(`Maximum query depth`),ignoreFields:w(v()).optional().describe(`Fields excluded from depth calculation`),onDepthExceeded:A([`reject`,`log`,`warn`]).default(`reject`).describe(`Action when depth exceeded`),errorMessage:v().optional().describe(`Custom error message for depth violations`)})),MA=W(()=>T({enabled:b().default(!0).describe(`Enable query complexity limiting`),maxComplexity:y().int().min(1).default(1e3).describe(`Maximum query complexity`),defaultFieldComplexity:y().int().min(0).default(1).describe(`Default complexity per field`),fieldComplexity:k(v(),E([y().int().min(0),T({base:y().int().min(0).describe(`Base complexity`),multiplier:v().optional().describe(`Argument multiplier (e.g., "limit")`),calculator:v().optional().describe(`Custom calculator function`)})])).optional().describe(`Per-field complexity configuration`),listMultiplier:y().min(0).default(10).describe(`Multiplier for list fields`),onComplexityExceeded:A([`reject`,`log`,`warn`]).default(`reject`).describe(`Action when complexity exceeded`),errorMessage:v().optional().describe(`Custom error message for complexity violations`)})),NA=W(()=>T({enabled:b().default(!0).describe(`Enable rate limiting`),strategy:A([`token_bucket`,`fixed_window`,`sliding_window`,`cost_based`]).default(`token_bucket`).describe(`Rate limiting strategy`),global:T({maxRequests:y().int().min(1).default(1e3).describe(`Maximum requests per window`),windowMs:y().int().min(1e3).default(6e4).describe(`Time window in milliseconds`)}).optional().describe(`Global rate limits`),perUser:T({maxRequests:y().int().min(1).default(100).describe(`Maximum requests per user per window`),windowMs:y().int().min(1e3).default(6e4).describe(`Time window in milliseconds`)}).optional().describe(`Per-user rate limits`),costBased:T({enabled:b().default(!1).describe(`Enable cost-based rate limiting`),maxCost:y().int().min(1).default(1e4).describe(`Maximum cost per window`),windowMs:y().int().min(1e3).default(6e4).describe(`Time window in milliseconds`),useComplexityAsCost:b().default(!0).describe(`Use query complexity as cost`)}).optional().describe(`Cost-based rate limiting`),operations:k(v(),T({maxRequests:y().int().min(1).describe(`Max requests for this operation`),windowMs:y().int().min(1e3).describe(`Time window`)})).optional().describe(`Per-operation rate limits`),onLimitExceeded:A([`reject`,`queue`,`log`]).default(`reject`).describe(`Action when rate limit exceeded`),errorMessage:v().optional().describe(`Custom error message for rate limit violations`),includeHeaders:b().default(!0).describe(`Include rate limit headers in response`)})),PA=W(()=>T({enabled:b().default(!1).describe(`Enable persisted queries`),mode:A([`optional`,`required`]).default(`optional`).describe(`Persisted query mode (optional: allow both, required: only persisted)`),store:T({type:A([`memory`,`redis`,`database`,`file`]).default(`memory`).describe(`Query store type`),connection:v().optional().describe(`Store connection string or path`),ttl:y().int().min(0).optional().describe(`TTL in seconds for stored queries`)}).optional().describe(`Query store configuration`),apq:T({enabled:b().default(!0).describe(`Enable Automatic Persisted Queries`),hashAlgorithm:A([`sha256`,`sha1`,`md5`]).default(`sha256`).describe(`Hash algorithm for query IDs`),cache:T({ttl:y().int().min(0).default(3600).describe(`Cache TTL in seconds`),maxSize:y().int().min(1).optional().describe(`Maximum number of cached queries`)}).optional().describe(`APQ cache configuration`)}).optional().describe(`Automatic Persisted Queries configuration`),allowlist:T({enabled:b().default(!1).describe(`Enable query allow list (reject queries not in list)`),queries:w(T({id:v().describe(`Query ID or hash`),operation:v().optional().describe(`Operation name`),query:v().optional().describe(`Query string`)})).optional().describe(`Allowed queries`),source:v().optional().describe(`External allow list source (file path or URL)`)}).optional().describe(`Query allow list configuration`),security:T({maxQuerySize:y().int().min(1).optional().describe(`Maximum query string size in bytes`),rejectIntrospection:b().default(!1).describe(`Reject introspection queries`)}).optional().describe(`Security configuration`)})),FA=W(()=>T({fields:v().describe(`Selection set of fields composing the entity key`),resolvable:b().optional().default(!0).describe(`Whether entities can be resolved from this subgraph`)})),IA=W(()=>T({field:v().describe(`Field name marked as external`),ownerSubgraph:v().optional().describe(`Subgraph that owns this field`)})),LA=W(()=>T({field:v().describe(`Field with the requirement`),fields:v().describe(`Selection set of required fields (e.g., "price weight")`)})),RA=W(()=>T({field:v().describe(`Field that provides additional entity fields`),fields:v().describe(`Selection set of provided fields (e.g., "name price")`)})),zA=W(()=>T({typeName:v().describe(`GraphQL type name for this entity`),keys:w(FA).min(1).describe(`Entity key definitions`),externalFields:w(IA).optional().describe(`Fields owned by other subgraphs`),requires:w(LA).optional().describe(`Required external fields for computed fields`),provides:w(RA).optional().describe(`Fields provided during resolution`),owner:b().optional().default(!1).describe(`Whether this subgraph is the owner of this entity`)})),BA=W(()=>T({name:v().describe(`Unique subgraph identifier`),url:v().describe(`Subgraph endpoint URL`),schemaSource:A([`introspection`,`file`,`registry`]).default(`introspection`).describe(`How to obtain the subgraph schema`),schemaPath:v().optional().describe(`Path to schema file (SDL format)`),entities:w(zA).optional().describe(`Entity definitions for this subgraph`),healthCheck:T({enabled:b().default(!0).describe(`Enable health checking`),path:v().default(`/health`).describe(`Health check endpoint path`),intervalMs:y().int().min(1e3).default(3e4).describe(`Health check interval in milliseconds`)}).optional().describe(`Subgraph health check configuration`),forwardHeaders:w(v()).optional().describe(`HTTP headers to forward to this subgraph`)})),VA=W(()=>T({enabled:b().default(!1).describe(`Enable GraphQL Federation gateway mode`),version:A([`v1`,`v2`]).default(`v2`).describe(`Federation specification version`),subgraphs:w(BA).describe(`Subgraph configurations`),serviceDiscovery:T({type:A([`static`,`dns`,`consul`,`kubernetes`]).default(`static`).describe(`Service discovery method`),pollIntervalMs:y().int().min(1e3).optional().describe(`Discovery poll interval in milliseconds`),namespace:v().optional().describe(`Kubernetes namespace for subgraph discovery`)}).optional().describe(`Service discovery configuration`),queryPlanning:T({strategy:A([`parallel`,`sequential`,`adaptive`]).default(`parallel`).describe(`Query execution strategy across subgraphs`),maxDepth:y().int().min(1).optional().describe(`Max query depth in federated execution`),dryRun:b().optional().default(!1).describe(`Log query plans without executing`)}).optional().describe(`Query planning configuration`),composition:T({conflictResolution:A([`error`,`first_wins`,`last_wins`]).default(`error`).describe(`Strategy for resolving schema conflicts`),validate:b().default(!0).describe(`Validate composed supergraph schema`)}).optional().describe(`Schema composition configuration`),errorHandling:T({includeSubgraphName:b().default(!1).describe(`Include subgraph name in error responses`),partialErrors:A([`propagate`,`nullify`,`reject`]).default(`propagate`).describe(`Behavior when a subgraph returns partial errors`)}).optional().describe(`Error handling configuration`)})),HA=W(()=>T({enabled:b().default(!0).describe(`Enable GraphQL API`),path:v().default(`/graphql`).describe(`GraphQL endpoint path`),playground:T({enabled:b().default(!0).describe(`Enable GraphQL Playground`),path:v().default(`/playground`).describe(`Playground path`)}).optional().describe(`GraphQL Playground configuration`),schema:T({autoGenerateTypes:b().default(!0).describe(`Auto-generate types from Objects`),types:w(CA).optional().describe(`Type configurations`),queries:w(wA).optional().describe(`Query configurations`),mutations:w(TA).optional().describe(`Mutation configurations`),subscriptions:w(EA).optional().describe(`Subscription configurations`),resolvers:w(DA).optional().describe(`Custom resolver configurations`),directives:w(AA).optional().describe(`Custom directive configurations`)}).optional().describe(`Schema generation configuration`),dataLoaders:w(OA).optional().describe(`DataLoader configurations`),security:T({depthLimit:jA.optional().describe(`Query depth limiting`),complexity:MA.optional().describe(`Query complexity calculation`),rateLimit:NA.optional().describe(`Rate limiting`),persistedQueries:PA.optional().describe(`Persisted queries`)}).optional().describe(`Security configuration`),federation:VA.optional().describe(`GraphQL Federation gateway configuration`)}));Object.assign(HA,{create:e=>e});var UA=A([`create`,`update`,`upsert`,`delete`]),WA=W(()=>T({id:v().optional().describe(`Record ID (required for update/delete)`),data:ck.optional().describe(`Record data (required for create/update/upsert)`),externalId:v().optional().describe(`External ID for upsert matching`)})),GA=W(()=>T({atomic:b().optional().default(!0).describe(`If true, rollback entire batch on any failure (transaction mode)`),returnRecords:b().optional().default(!1).describe(`If true, return full record data in response`),continueOnError:b().optional().default(!1).describe(`If true (and atomic=false), continue processing remaining records after errors`),validateOnly:b().optional().default(!1).describe(`If true, validate records without persisting changes (dry-run mode)`)})),KA=W(()=>T({operation:UA.describe(`Type of batch operation`),records:w(WA).min(1).max(200).describe(`Array of records to process (max 200 per batch)`),options:GA.optional().describe(`Batch operation options`)}));W(()=>T({records:w(WA).min(1).max(200).describe(`Array of records to update (max 200 per batch)`),options:GA.optional().describe(`Update options`)}));var qA=W(()=>T({id:v().optional().describe(`Record ID if operation succeeded`),success:b().describe(`Whether this record was processed successfully`),errors:w(sk).optional().describe(`Array of errors if operation failed`),data:ck.optional().describe(`Full record data (if returnRecords=true)`),index:y().optional().describe(`Index of the record in the request array`)})),JA=W(()=>G.extend({operation:UA.optional().describe(`Operation type that was performed`),total:y().describe(`Total number of records in the batch`),succeeded:y().describe(`Number of records that succeeded`),failed:y().describe(`Number of records that failed`),results:w(qA).describe(`Detailed results for each record`)}));W(()=>T({ids:w(v()).min(1).max(200).describe(`Array of record IDs to delete (max 200)`),options:GA.optional().describe(`Delete options`)})),W(()=>T({enabled:b().default(!0).describe(`Enable batch operations`),maxRecordsPerBatch:y().int().min(1).max(1e3).default(200).describe(`Maximum records per batch`),defaultOptions:GA.optional().describe(`Default batch options`)}).passthrough());var YA=A([`public`,`private`,`no-cache`,`no-store`,`must-revalidate`,`max-age`]),XA=W(()=>T({directives:w(YA).describe(`Cache control directives`),maxAge:y().optional().describe(`Maximum cache age in seconds`),staleWhileRevalidate:y().optional().describe(`Allow serving stale content while revalidating (seconds)`),staleIfError:y().optional().describe(`Allow serving stale content on error (seconds)`)})),ZA=W(()=>T({value:v().describe(`ETag value (hash or version identifier)`),weak:b().optional().default(!1).describe(`Whether this is a weak ETag`)})),QA=W(()=>T({ifNoneMatch:v().optional().describe(`ETag value for conditional request (If-None-Match header)`),ifModifiedSince:v().datetime().optional().describe(`Timestamp for conditional request (If-Modified-Since header)`),cacheControl:XA.optional().describe(`Client cache control preferences`)})),$A=W(()=>T({data:S().optional().describe(`Metadata payload (omitted for 304 Not Modified)`),etag:ZA.optional().describe(`ETag for this resource version`),lastModified:v().datetime().optional().describe(`Last modification timestamp`),cacheControl:XA.optional().describe(`Cache control directives`),notModified:b().optional().default(!1).describe(`True if resource has not been modified (304 response)`),version:v().optional().describe(`Metadata version identifier`)})),ej=A([`all`,`object`,`field`,`permission`,`layout`,`custom`]);W(()=>T({target:ej.describe(`What to invalidate`),identifiers:w(v()).optional().describe(`Specific resources to invalidate (e.g., object names)`),cascade:b().optional().default(!1).describe(`If true, invalidate dependent resources`),pattern:v().optional().describe(`Pattern for custom invalidation (supports wildcards)`)})),W(()=>T({success:b().describe(`Whether invalidation succeeded`),invalidated:y().describe(`Number of cache entries invalidated`),targets:w(v()).optional().describe(`List of invalidated resources`)}));var tj=A([`validation`,`authentication`,`authorization`,`not_found`,`conflict`,`rate_limit`,`server`,`external`,`maintenance`]),nj=A(`validation_error.invalid_field.missing_required_field.invalid_format.value_too_long.value_too_short.value_out_of_range.invalid_reference.duplicate_value.invalid_query.invalid_filter.invalid_sort.max_records_exceeded.unauthenticated.invalid_credentials.expired_token.invalid_token.session_expired.mfa_required.email_not_verified.permission_denied.insufficient_privileges.field_not_accessible.record_not_accessible.license_required.ip_restricted.time_restricted.resource_not_found.object_not_found.record_not_found.field_not_found.endpoint_not_found.resource_conflict.concurrent_modification.delete_restricted.duplicate_record.lock_conflict.rate_limit_exceeded.quota_exceeded.concurrent_limit_exceeded.internal_error.database_error.timeout.service_unavailable.not_implemented.external_service_error.integration_error.webhook_delivery_failed.batch_partial_failure.batch_complete_failure.transaction_failed`.split(`.`)),rj=A([`no_retry`,`retry_immediate`,`retry_backoff`,`retry_after`]),ij=W(()=>T({field:v().describe(`Field path (supports dot notation)`),code:nj.describe(`Error code for this field`),message:v().describe(`Human-readable error message`),value:S().optional().describe(`The invalid value that was provided`),constraint:S().optional().describe(`The constraint that was violated (e.g., max length)`)})),aj=W(()=>T({code:nj.describe(`Machine-readable error code`),message:v().describe(`Human-readable error message`),category:tj.optional().describe(`Error category`),httpStatus:y().optional().describe(`HTTP status code`),retryable:b().default(!1).describe(`Whether the request can be retried`),retryStrategy:rj.optional().describe(`Recommended retry strategy`),retryAfter:y().optional().describe(`Seconds to wait before retrying`),details:S().optional().describe(`Additional error context`),fieldErrors:w(ij).optional().describe(`Field-specific validation errors`),timestamp:v().datetime().optional().describe(`When the error occurred`),requestId:v().optional().describe(`Request ID for tracking`),traceId:v().optional().describe(`Distributed trace ID`),documentation:v().url().optional().describe(`URL to error documentation`),helpText:v().optional().describe(`Suggested actions to resolve the error`)}));W(()=>T({success:j(!1).describe(`Always false for error responses`),error:aj.describe(`Error details`),meta:T({timestamp:v().datetime().optional(),requestId:v().optional(),traceId:v().optional()}).optional().describe(`Response metadata`)}));var oj=A([`none`,`no-overlay`,`no-delete`,`full`]),sj=A([`artifact`,`package`,`env-forced`]),cj=A([`package`,`org`,`env-forced`]),lj={_lock:oj.optional().describe(`Item-level lock — controls overlay & delete (ADR-0010).`),_lockReason:v().max(500).optional().describe(`Human-readable reason shown when a write is refused by _lock.`),_lockSource:sj.optional().describe(`Layer that set _lock (artifact | package | env-forced).`),_provenance:cj.optional().describe(`Origin of the item (package | org | env-forced).`),_packageId:v().optional().describe(`Owning package machine id.`),_packageVersion:v().optional().describe(`Owning package version.`),_lockDocsUrl:v().optional().describe(`Optional documentation link surfaced next to _lockReason.`)},uj=T({lock:oj.describe(`Lock policy — none | no-overlay | no-delete | full.`),reason:v().min(1).max(500).describe(`User-visible reason shown when the lock blocks an action.`),docsUrl:v().url().optional().describe(`Optional URL the Studio banner links to for more context.`)}).strict();W(()=>T({key:v().describe(`Translation key (e.g., "views.task_list.label")`),defaultValue:v().optional().describe(`Fallback value when translation key is not found`),params:k(v(),E([v(),y(),b()])).optional().describe(`Interpolation parameters (e.g., { count: 5 })`)}));var K=W(()=>v().describe(`Display label (plain string; i18n keys are auto-generated by the framework)`)),dj=W(()=>T({ariaLabel:K.optional().describe(`Accessible label for screen readers (WAI-ARIA aria-label)`),ariaDescribedBy:v().optional().describe(`ID of element providing additional description (WAI-ARIA aria-describedby)`),role:v().optional().describe(`WAI-ARIA role attribute (e.g., "dialog", "navigation", "alert")`)}).describe(`ARIA accessibility attributes`));W(()=>T({key:v().describe(`Translation key`),zero:v().optional().describe(`Zero form (e.g., "No items")`),one:v().optional().describe(`Singular form (e.g., "{count} item")`),two:v().optional().describe(`Dual form (e.g., "{count} items" for exactly 2)`),few:v().optional().describe(`Few form (e.g., for 2-4 in some languages)`),many:v().optional().describe(`Many form (e.g., for 5+ in some languages)`),other:v().describe(`Default plural form (e.g., "{count} items")`)}).describe(`ICU plural rules for a translation key`));var fj=W(()=>T({style:A([`decimal`,`currency`,`percent`,`unit`]).default(`decimal`).describe(`Number formatting style`),currency:v().optional().describe(`ISO 4217 currency code (e.g., "USD", "EUR")`),unit:v().optional().describe(`Unit for unit formatting (e.g., "kilometer", "liter")`),minimumFractionDigits:y().optional().describe(`Minimum number of fraction digits`),maximumFractionDigits:y().optional().describe(`Maximum number of fraction digits`),useGrouping:b().optional().describe(`Whether to use grouping separators (e.g., 1,000)`)}).describe(`Number formatting rules`)),pj=W(()=>T({dateStyle:A([`full`,`long`,`medium`,`short`]).optional().describe(`Date display style`),timeStyle:A([`full`,`long`,`medium`,`short`]).optional().describe(`Time display style`),timeZone:v().optional().describe(`IANA time zone (e.g., "America/New_York")`),hour12:b().optional().describe(`Use 12-hour format`)}).describe(`Date/time formatting rules`));W(()=>T({code:v().describe(`BCP 47 language code (e.g., "en-US", "zh-CN")`),fallbackChain:w(v()).optional().describe(`Fallback language codes in priority order (e.g., ["zh-TW", "en"])`),direction:A([`ltr`,`rtl`]).default(`ltr`).describe(`Text direction: left-to-right or right-to-left`),numberFormat:fj.optional().describe(`Default number formatting rules`),dateFormat:pj.optional().describe(`Default date/time formatting rules`)}).describe(`Locale configuration`));var mj=W(()=>T({enabled:b().default(!1).describe(`Enable public sharing`),publicLink:v().optional().describe(`Generated public share URL`),password:v().optional().describe(`Password required to access shared link`),allowedDomains:w(v()).optional().describe(`Restrict access to specific email domains (e.g. ["example.com"])`),expiresAt:v().optional().describe(`Expiration date/time in ISO 8601 format`),allowAnonymous:b().optional().default(!1).describe(`Allow access without authentication`)})),hj=W(()=>T({enabled:b().default(!1).describe(`Enable iframe embedding`),allowedOrigins:w(v()).optional().describe(`Allowed iframe parent origins (e.g. ["https://example.com"])`),width:v().optional().default(`100%`).describe(`Embed width (CSS value)`),height:v().optional().default(`600px`).describe(`Embed height (CSS value)`),showHeader:b().optional().default(!0).describe(`Show interface header in embed`),showNavigation:b().optional().default(!1).describe(`Show navigation in embed`),responsive:b().optional().default(!0).describe(`Enable responsive resizing`)})),gj=A([`xs`,`sm`,`md`,`lg`,`xl`,`2xl`]),_j=W(()=>T({xs:y().min(1).max(12).optional(),sm:y().min(1).max(12).optional(),md:y().min(1).max(12).optional(),lg:y().min(1).max(12).optional(),xl:y().min(1).max(12).optional(),"2xl":y().min(1).max(12).optional()}).describe(`Grid columns per breakpoint (1-12)`)),vj=W(()=>T({xs:y().optional(),sm:y().optional(),md:y().optional(),lg:y().optional(),xl:y().optional(),"2xl":y().optional()}).describe(`Display order per breakpoint`)),yj=W(()=>T({breakpoint:gj.optional().describe(`Minimum breakpoint for visibility`),hiddenOn:w(gj).optional().describe(`Hide on these breakpoints`),columns:_j.optional().describe(`Grid columns per breakpoint`),order:vj.optional().describe(`Display order per breakpoint`)}).describe(`Responsive layout configuration`)),bj=W(()=>k(v(),E([v(),y()])).describe(`CSS property → value map (camelCase keys; design tokens encouraged)`));W(()=>T({large:bj.optional().describe(`Unconditional base (desktop-first)`),medium:bj.optional().describe(`Applied at ≤ medium breakpoint`),small:bj.optional().describe(`Applied at ≤ small breakpoint`),xsmall:bj.optional().describe(`Applied at ≤ xsmall breakpoint`)}).describe(`Per-breakpoint scoped style maps (ADR-0065)`));var xj=W(()=>T({lazyLoad:b().optional().describe(`Enable lazy loading (defer rendering until visible)`),virtualScroll:T({enabled:b().default(!1).describe(`Enable virtual scrolling`),itemHeight:y().optional().describe(`Fixed item height in pixels (for estimation)`),overscan:y().optional().describe(`Number of extra items to render outside viewport`)}).optional().describe(`Virtual scrolling configuration`),cacheStrategy:A([`none`,`cache-first`,`network-first`,`stale-while-revalidate`]).optional().describe(`Client-side data caching strategy`),prefetch:b().optional().describe(`Prefetch data before component is visible`),pageSize:y().optional().describe(`Number of items per page for pagination`),debounceMs:y().optional().describe(`Debounce interval for user interactions in milliseconds`)}).describe(`Performance optimization configuration`)),Sj=A(`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(`.`)),Cj=W(()=>T({label:v().describe(`Display label (human-readable, any case allowed)`),value:Uk.describe(`Stored value (lowercase machine identifier)`),color:v().optional().describe(`Color code for badges/charts`),default:b().optional().describe(`Is default option`)}));W(()=>T({latitude:y().min(-90).max(90).describe(`Latitude coordinate`),longitude:y().min(-180).max(180).describe(`Longitude coordinate`),altitude:y().optional().describe(`Altitude in meters`),accuracy:y().optional().describe(`Accuracy in meters`)}));var wj=W(()=>T({precision:y().int().min(0).max(10).default(2).describe(`Decimal precision (default: 2)`),currencyMode:A([`dynamic`,`fixed`]).default(`dynamic`).describe(`Currency mode: dynamic (user selectable) or fixed (single currency)`),defaultCurrency:v().length(3).default(`CNY`).describe(`Default or fixed currency code (ISO 4217, e.g., USD, CNY, EUR)`)}));W(()=>T({value:y().describe(`Monetary amount`),currency:v().length(3).describe(`Currency code (ISO 4217)`)})),W(()=>T({street:v().optional().describe(`Street address`),city:v().optional().describe(`City name`),state:v().optional().describe(`State/Province`),postalCode:v().optional().describe(`Postal/ZIP code`),country:v().optional().describe(`Country name or code`),countryCode:v().optional().describe(`ISO country code (e.g., US, GB)`),formatted:v().optional().describe(`Formatted address string`)}));var Tj=W(()=>T({dimensions:y().int().min(1).max(1e4).describe(`Vector dimensionality (e.g., 1536 for OpenAI embeddings)`),distanceMetric:A([`cosine`,`euclidean`,`dotProduct`,`manhattan`]).default(`cosine`).describe(`Distance/similarity metric for vector search`),normalized:b().default(!1).describe(`Whether vectors are normalized (unit length)`),indexed:b().default(!0).describe(`Whether to create a vector index for fast similarity search`),indexType:A([`hnsw`,`ivfflat`,`flat`]).optional().describe(`Vector index algorithm (HNSW for high accuracy, IVFFlat for large datasets)`)})),Ej=W(()=>T({minSize:y().min(0).optional().describe(`Minimum file size in bytes`),maxSize:y().min(1).optional().describe(`Maximum file size in bytes (e.g., 10485760 = 10MB)`),allowedTypes:w(v()).optional().describe(`Allowed file extensions (e.g., [".pdf", ".docx", ".jpg"])`),blockedTypes:w(v()).optional().describe(`Blocked file extensions (e.g., [".exe", ".bat", ".sh"])`),allowedMimeTypes:w(v()).optional().describe(`Allowed MIME types (e.g., ["image/jpeg", "application/pdf"])`),blockedMimeTypes:w(v()).optional().describe(`Blocked MIME types`),virusScan:b().default(!1).describe(`Enable virus scanning for uploaded files`),virusScanProvider:A([`clamav`,`virustotal`,`metadefender`,`custom`]).optional().describe(`Virus scanning service provider`),virusScanOnUpload:b().default(!0).describe(`Scan files immediately on upload`),quarantineOnThreat:b().default(!0).describe(`Quarantine files if threat detected`),storageProvider:v().optional().describe(`Object storage provider name (references ObjectStorageConfig)`),storageBucket:v().optional().describe(`Target bucket name`),storagePrefix:v().optional().describe(`Storage path prefix (e.g., "uploads/documents/")`),imageValidation:T({minWidth:y().min(1).optional().describe(`Minimum image width in pixels`),maxWidth:y().min(1).optional().describe(`Maximum image width in pixels`),minHeight:y().min(1).optional().describe(`Minimum image height in pixels`),maxHeight:y().min(1).optional().describe(`Maximum image height in pixels`),aspectRatio:v().optional().describe(`Required aspect ratio (e.g., "16:9", "1:1")`),generateThumbnails:b().default(!1).describe(`Auto-generate thumbnails`),thumbnailSizes:w(T({name:v().describe(`Thumbnail variant name (e.g., "small", "medium", "large")`),width:y().min(1).describe(`Thumbnail width in pixels`),height:y().min(1).describe(`Thumbnail height in pixels`),crop:b().default(!1).describe(`Crop to exact dimensions`)})).optional().describe(`Thumbnail size configurations`),preserveMetadata:b().default(!1).describe(`Preserve EXIF metadata`),autoRotate:b().default(!0).describe(`Auto-rotate based on EXIF orientation`)}).optional().describe(`Image-specific validation rules`),allowMultiple:b().default(!1).describe(`Allow multiple file uploads (overrides field.multiple)`),allowReplace:b().default(!0).describe(`Allow replacing existing files`),allowDelete:b().default(!0).describe(`Allow deleting uploaded files`),requireUpload:b().default(!1).describe(`Require at least one file when field is required`),extractMetadata:b().default(!0).describe(`Extract file metadata (name, size, type, etc.)`),extractText:b().default(!1).describe(`Extract text content from documents (OCR/parsing)`),versioningEnabled:b().default(!1).describe(`Keep previous versions of replaced files`),maxVersions:y().min(1).optional().describe(`Maximum number of versions to retain`),publicRead:b().default(!1).describe(`Allow public read access to uploaded files`),presignedUrlExpiry:y().min(60).max(604800).default(3600).describe(`Presigned URL expiration in seconds (default: 1 hour)`)}).refine(e=>!(e.minSize!==void 0&&e.maxSize!==void 0&&e.minSize>e.maxSize),{message:`minSize must be less than or equal to maxSize`}).refine(e=>!(e.virusScanProvider!==void 0&&e.virusScan!==!0),{message:`virusScanProvider requires virusScan to be enabled`}));W(()=>T({uniqueness:b().default(!1).describe(`Enforce unique values across all records`),completeness:y().min(0).max(1).default(0).describe(`Minimum ratio of non-null values (0-1, default: 0 = no requirement)`),accuracy:T({source:v().describe(`Reference data source for validation (e.g., "api.verify.com", "master_data")`),threshold:y().min(0).max(1).describe(`Minimum accuracy threshold (0-1, e.g., 0.95 = 95% match required)`)}).optional().describe(`Accuracy validation configuration`)})),W(()=>T({enabled:b().describe(`Enable caching for computed field results`),ttl:y().min(0).describe(`Cache TTL in seconds (0 = no expiration)`),invalidateOn:w(v()).describe(`Field paths that invalidate cache (e.g., ["inventory.quantity", "pricing.base_price"])`)}));var Dj=W(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Machine name (snake_case)`).optional(),label:v().optional().describe(`Human readable label`),type:Sj.describe(`Field Data Type`),description:v().optional().describe(`Tooltip/Help text`),format:v().optional().describe(`Format string (e.g. email, phone)`),columnName:v().optional().describe(`Physical column name in the target datasource. Defaults to the field key when not set.`),required:b().default(!1).describe(`Is required`),searchable:b().default(!1).describe(`Is searchable`),multiple:b().default(!1).describe(`Allow multiple values (Stores as Array/JSON). Applicable for select, lookup, file, image.`),unique:b().default(!1).describe(`Is unique constraint`),defaultValue:S().optional().describe(`Default value`),maxLength:y().optional().describe(`Max character length`),minLength:y().optional().describe(`Min character length`),precision:y().optional().describe(`Total digits`),scale:y().optional().describe(`Decimal places`),min:y().optional().describe(`Minimum value`),max:y().optional().describe(`Maximum value`),options:w(Cj).optional().describe(`Static options for select/multiselect`),reference:v().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.`),referenceFilters:w(v()).optional().describe(`Filters applied to lookup dialogs (e.g. "active = true")`),deleteBehavior:A([`set_null`,`cascade`,`restrict`]).optional().default(`set_null`).describe(`What happens if referenced record is deleted`),inlineEdit:E([b(),A([`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:v().optional().describe(`Title for the inline master-detail grid`),inlineColumns:w(x()).optional().describe(`Explicit columns for the inline grid (derived from the child object when omitted)`),inlineAmountField:v().optional().describe(`Numeric child field summed for the inline grid total`),relatedList:b().optional().describe(`Show this child collection as a related list on the parent's detail page (read-side mirror of inlineEdit). Defaults to shown for master_detail/lookup; set false to suppress.`),relatedListTitle:v().optional().describe(`Title for the detail-page related list`),relatedListColumns:w(x()).optional().describe(`Explicit columns for the detail-page related list (derived from the child object when omitted)`),displayField:v().optional().describe(`Field shown as each candidate's label in the picker/popover (defaults to the referenced object's name/title).`),descriptionField:v().optional().describe(`Secondary field shown under the label in the quick-select popover.`),lookupColumns:w(E([v(),T({field:v(),label:v().optional(),width:v().optional(),type:v().optional()})])).optional().describe(`Explicit columns for the record-picker table; auto-derived from the referenced object when omitted.`),lookupPageSize:y().int().positive().optional().describe(`Rows per page in the record-picker dialog (default 10).`),lookupFilters:w(T({field:v(),operator:A([`eq`,`ne`,`gt`,`lt`,`gte`,`lte`,`contains`,`in`,`notIn`]),value:x()})).optional().describe(`Base filters restricting which records are selectable (e.g. only active). Structured, picker-honoured form of referenceFilters.`),dependsOn:w(E([v(),T({field:v(),param:v().optional()})])).optional().describe(`Dependent lookup: restrict candidates by the value of other field(s) on the same record. String = same local/remote key; {field,param} when the remote filter key differs.`),allowCreate:b().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:bA.optional().describe("Formula expression (CEL). e.g. F`record.amount * 0.1`"),returnType:A([`number`,`text`,`boolean`,`date`]).optional().describe(`Inferred value type of a formula field (number/text/boolean/date)`),summaryOperations:T({object:v().describe(`Source child object name for roll-up`),field:v().describe(`Field on child object to aggregate (ignored for count)`),function:A([`count`,`sum`,`min`,`max`,`avg`]).describe(`Aggregation function to apply`),relationshipField:v().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.`)}).optional().describe(`Roll-up summary definition. The engine recomputes the value when child records are inserted/updated/deleted.`),language:v().optional().describe(`Programming language for syntax highlighting (e.g., javascript, python, sql)`),maxRating:y().optional().describe(`Maximum rating value (default: 5)`),step:y().optional().describe(`Step increment for slider (default: 1)`),currencyConfig:wj.optional().describe(`Configuration for currency field type`),dimensions:y().int().min(1).max(1e4).optional().describe(`Vector dimensionality (e.g., 1536 for OpenAI embeddings)`),vectorConfig:Tj.optional().describe(`Configuration for vector field type (AI/ML embeddings)`),fileAttachmentConfig:Ej.optional().describe(`Configuration for file and attachment field types`),trackHistory:b().optional().describe(`Render this field's value changes as human-readable entries on the record activity timeline (ADR-0052 §5b). Opt-in per field.`),dependencies:w(v()).optional().describe(`Array of field names that this field depends on (for formulas, visibility rules, etc.)`),group:v().optional().describe(`Field group name for organizing fields in forms and layouts (e.g., "contact_info", "billing", "system")`),visibleWhen:bA.optional().describe("Predicate (CEL) — field is shown only when TRUE (else hidden). e.g. P`record.type == 'invoice'`"),readonlyWhen:bA.optional().describe("Predicate (CEL) — field is read-only when TRUE. e.g. P`record.status == 'paid'`"),requiredWhen:bA.optional().describe("Predicate (CEL) — field is required when TRUE. Canonical name for `conditionalRequired`."),conditionalRequired:bA.optional().describe("Predicate (CEL) — field is required when TRUE. Alias of `requiredWhen`."),hidden:b().default(!1).describe(`Hidden from default UI`),readonly:b().default(!1).describe(`Read-only in UI`),requiredPermissions:w(v()).optional().describe(`[ADR-0066 D3] Capabilities required to read/edit this field (mask on read, deny on write; AND-gate).`),system:b().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:b().optional().default(!0).describe(`Whether field is sortable in list views`),inlineHelpText:v().optional().describe(`Help text displayed below the field in forms`),caseSensitive:b().optional().describe(`Whether text comparisons are case-sensitive`),autonumberFormat:v().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).`),index:b().default(!1).describe(`Create standard database index`),externalId:b().default(!1).describe(`Is external ID for upsert operations`)})),Oj=W(()=>D(`provider`,[T({provider:j(`object`),object:v().describe(`Target object name`)}),T({provider:j(`api`),read:Sk.optional().describe(`Configuration for fetching data`),write:Sk.optional().describe(`Configuration for submitting data (for forms/editable tables)`)}),T({provider:j(`value`),items:w(S()).describe(`Static data array`)}),T({provider:j(`schema`),schemaId:v().describe(`Schema identifier — typically the metadata type name`),schema:k(v(),S()).optional().describe(`Inline JSON Schema (Draft 2020-12). Optional when schemaId is resolvable.`)})])),kj=W(()=>T({field:v().describe(`Field name to filter on`),operator:v().describe(`Filter operator (e.g. equals, not_equals, contains, this_quarter)`),value:E([v(),y(),b(),ul(),w(E([v(),y()]))]).optional().describe(`Filter value`)}).describe(`View filter rule`)),Aj=W(()=>A([`none`,`count`,`count_empty`,`count_filled`,`count_unique`,`percent_empty`,`percent_filled`,`sum`,`avg`,`min`,`max`]).describe(`Aggregation function for column footer summary`)),jj=W(()=>T({field:v().describe(`Field name (snake_case)`),label:K.optional().describe(`Display label override`),width:y().positive().optional().describe(`Column width in pixels`),align:A([`left`,`center`,`right`]).optional().describe(`Text alignment`),hidden:b().optional().describe(`Hide column by default`),sortable:b().optional().describe(`Allow sorting by this column`),resizable:b().optional().describe(`Allow resizing this column`),wrap:b().optional().describe(`Allow text wrapping`),type:v().optional().describe(`Renderer type override (e.g., "currency", "date")`),pinned:A([`left`,`right`]).optional().describe(`Pin/freeze column to left or right side`),summary:Aj.optional().describe(`Footer aggregation function for this column`),link:b().optional().describe(`Functions as the primary navigation link (triggers View navigation)`),action:v().optional().describe(`Registered Action ID to execute when clicked`)})),Mj=W(()=>T({type:A([`none`,`single`,`multiple`]).default(`none`).describe(`Selection mode`)})),Nj=W(()=>T({pageSize:y().int().positive().default(25).describe(`Number of records per page`),pageSizeOptions:w(y().int().positive()).optional().describe(`Available page size options`)})),Pj=W(()=>A([`compact`,`short`,`medium`,`tall`,`extra_tall`]).describe(`Row height / density setting for list view`)),Fj=W(()=>T({field:v().describe(`Field name to group by`),order:A([`asc`,`desc`]).default(`asc`).describe(`Group sort order`),collapsed:b().default(!1).describe(`Collapse groups by default`)})),Ij=W(()=>T({fields:w(Fj).min(1).describe(`Fields to group by (supports up to 3 levels)`)}).describe(`Record grouping configuration`)),Lj=W(()=>T({coverField:v().optional().describe(`Attachment/image field to display as card cover`),coverFit:A([`cover`,`contain`]).default(`cover`).describe(`Image fit mode for card cover`),cardSize:A([`small`,`medium`,`large`]).default(`medium`).describe(`Card size in gallery view`),titleField:v().optional().describe(`Field to display as card title`),visibleFields:w(v()).optional().describe(`Fields to display on card body`)}).describe(`Gallery/card view configuration`)),Rj=W(()=>T({startDateField:v().describe(`Field for timeline item start date`),endDateField:v().optional().describe(`Field for timeline item end date`),titleField:v().describe(`Field to display as timeline item title`),groupByField:v().optional().describe(`Field to group timeline rows`),colorField:v().optional().describe(`Field to determine item color`),scale:A([`hour`,`day`,`week`,`month`,`quarter`,`year`]).default(`week`).describe(`Default timeline scale`)}).describe(`Timeline view configuration`)),zj=W(()=>T({type:A([`personal`,`collaborative`]).default(`collaborative`).describe(`View ownership type`),lockedBy:v().optional().describe(`User who locked the view configuration`)}).describe(`View sharing and access configuration`)),Bj=W(()=>T({field:v().describe(`Field to derive color from (typically a select/status field)`),colors:k(v(),v()).optional().describe(`Map of field value to color (hex/token)`)}).describe(`Row color configuration based on field values`)),Vj=W(()=>A([`grid`,`kanban`,`gallery`,`calendar`,`timeline`,`gantt`,`map`,`chart`,`tree`]).describe(`Visualization type that users can switch to`)),Hj=W(()=>T({sort:b().default(!0).describe(`Allow users to sort records`),search:b().default(!0).describe(`Allow users to search records`),filter:b().default(!0).describe(`Allow users to filter records`),rowHeight:b().default(!0).describe(`Allow users to toggle row height/density`),addRecordForm:b().default(!1).describe(`Add records through a form instead of inline`),buttons:w(v()).optional().describe(`Custom action button IDs to show in the toolbar`)}).describe(`User action toggles for the view toolbar`)),Uj=W(()=>T({showDescription:b().default(!0).describe(`Show the view description text`),allowedVisualizations:w(Vj).optional().describe(`Whitelist of visualization types users can switch between (e.g. ["grid", "gallery", "kanban"])`)}).describe(`Appearance and visualization configuration`)),Wj=W(()=>T({name:Wk.describe(`Tab identifier (snake_case)`),label:K.optional().describe(`Display label`),icon:v().optional().describe(`Tab icon name`),view:v().optional().describe(`Referenced list view name from listViews`),filter:w(kj).optional().describe(`Tab-specific filter criteria`),order:y().int().min(0).optional().describe(`Tab display order`),pinned:b().default(!1).describe(`Pin tab (cannot be removed by users)`),isDefault:b().default(!1).describe(`Set as the default active tab`),visible:b().default(!0).describe(`Tab visibility`)}).describe(`Tab configuration for multi-tab view interface`)),Gj=W(()=>T({field:v().describe(`Field name on the source object (must exist — checked by reference diagnostics)`),label:K.optional().describe(`Display label override (defaults to the field label)`),type:A([`select`,`multi-select`,`boolean`,`date-range`,`text`]).optional().describe(`Filter control type. Omit to infer from the field definition`),options:w(T({value:E([v(),y(),b()]).describe(`Option value`),label:K.describe(`Option label`),color:v().optional().describe(`Option color token/hex`)})).optional().describe(`Static options. Omit to derive from the field definition (select options / lookup records)`),showCount:b().optional().describe(`Show per-option record counts`),defaultValues:w(E([v(),y(),b()])).optional().describe(`Pre-selected values when the view loads`)}).describe(`Quick-filter field configuration`)),Kj=W(()=>T({element:A([`dropdown`,`tabs`,`toggle`]).default(`dropdown`).describe(`Filter control style: "dropdown" (per-field value selectors) or "tabs" (named presets). "toggle" is deprecated.`),fields:w(Gj).optional().describe(`Fields exposed as quick filters (dropdown/toggle elements)`),tabs:w(Wj).optional().describe(`Named filter presets rendered as tabs (tabs element). Reuses ViewTabSchema`),showAllRecords:b().optional().describe(`Show an "All records" tab before the presets (tabs element)`)}).describe(`End-user quick-filter configuration (Airtable "User filters" parity)`)),qj=W(()=>T({enabled:b().default(!0).describe(`Show the add record entry point`),position:A([`top`,`bottom`,`both`]).default(`bottom`).describe(`Position of the add record button`),mode:A([`inline`,`form`,`modal`]).default(`inline`).describe(`How to add a new record`),formView:v().optional().describe(`Named form view to use when mode is "form" or "modal"`)}).describe(`Add record entry point configuration`)),Jj=W(()=>T({groupByField:v().describe(`Field to group columns by (usually status/select)`),summarizeField:v().optional().describe(`Field to sum at top of column (e.g. amount)`),columns:w(v()).describe(`Fields to show on cards`)})),Yj=W(()=>T({chartType:A([`bar`,`line`,`pie`,`area`,`scatter`]).default(`bar`).describe(`Chart visualisation type`),dataset:Wk.describe(`Dataset name to bind (ADR-0021)`),dimensions:w(v()).optional().describe(`Dimension names — X/group/split`),values:w(v()).min(1).describe(`Measure names — Y (at least one)`)}).describe(`List chart view configuration`)),Xj=W(()=>T({startDateField:v(),endDateField:v().optional(),titleField:v(),colorField:v().optional()})),Zj=W(()=>T({field:v().describe(`Record field / dot-path the dimension filters on`),label:v().optional().describe(`Trigger label (falls back to the field label)`),options:w(E([v(),T({value:E([v(),y()]),label:v().optional()})])).optional().describe(`Explicit option override for fixed enums`)})),Qj=W(()=>T({startDateField:v(),endDateField:v(),titleField:v(),progressField:v().optional(),dependenciesField:v().optional(),colorField:v().optional().describe(`Field that drives the bar color`),parentField:v().optional().describe(`Field holding the parent task id (builds the summary → step tree)`),typeField:v().optional().describe(`Field whose value maps to task/summary/milestone`),baselineStartField:v().optional().describe(`Baseline (planned) start field`),baselineEndField:v().optional().describe(`Baseline (planned) end field`),groupByField:v().optional().describe(`Field to group leaf tasks by (synthesized summary rows)`),resourceView:b().optional().describe(`Render a per-resource workload histogram instead of the timeline`),assigneeField:v().optional().describe(`Resource field to bucket load by (resource view)`),effortField:v().optional().describe(`Per-task load units (resource view; default 1)`),capacity:y().optional().describe(`Per-resource capacity ceiling; loads above this flag overload`),tooltipFields:w(E([v(),T({field:v(),label:v().optional()})])).optional().describe(`Fields to surface in the hover tooltip, in display order`),quickFilters:w(Zj).optional().describe(`Multi-select filter dropdowns rendered above the chart`),autoZoomToFilter:b().optional().describe(`When true (default), filtering zooms the range to the filtered tasks`)}).passthrough()),$j=W(()=>T({parentField:v().optional().describe(`Single-parent pointer field (auto-detected from the object schema when omitted)`),labelField:v().optional().describe(`Field rendered indented in the first column (defaults to "name")`),fields:w(v()).optional().describe(`Additional fields rendered as flat columns alongside the label`),defaultExpandedDepth:y().int().min(0).optional().describe(`Initial expansion depth (0 = roots only; omit = expand all)`)}).passthrough()),eM=W(()=>A([`page`,`drawer`,`modal`,`split`,`popover`,`new_window`,`none`])),tM=W(()=>T({mode:eM.default(`page`),view:v().optional().describe(`Name of the form view to use for details (e.g. "summary_view", "edit_form")`),preventNavigation:b().default(!1).describe(`Disable standard navigation entirely`),openNewTab:b().default(!1).describe(`Force open in new tab (applies to page mode)`),width:E([v(),y()]).optional().describe(`Width of the drawer/modal (e.g. "600px", "50%")`)})),nM=W(()=>T({name:Wk.optional().describe(`Internal view name (lowercase snake_case)`),label:K.optional(),type:A([`grid`,`kanban`,`gallery`,`calendar`,`timeline`,`gantt`,`map`,`chart`,`tree`]).default(`grid`),data:Oj.optional().describe(`Data source configuration (defaults to "object" provider)`),columns:E([w(v()),w(jj)]).describe(`Fields to display as columns`),filter:w(kj).optional().describe(`Filter criteria (JSON Rules)`),sort:E([v(),w(T({field:v(),order:A([`asc`,`desc`])}))]).optional(),searchableFields:w(v()).optional().describe(`Fields enabled for search`),filterableFields:w(v()).optional().describe(`Legacy shorthand for userFilters.fields — bare field names enabled for end-user filtering. Prefer userFilters`),userFilters:Kj.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:b().optional().describe(`Enable column resizing`),striped:b().optional().describe(`Striped row styling`),bordered:b().optional().describe(`Show borders`),compactToolbar:b().optional().describe(`Collapse Group/Color/Density/Hide-fields into a single View settings popover`),selection:Mj.optional().describe(`Row selection configuration`),navigation:tM.optional().describe(`Configuration for item click navigation (page, drawer, modal, etc.)`),pagination:Nj.optional().describe(`Pagination configuration`),kanban:Jj.optional(),calendar:Xj.optional(),gantt:Qj.optional(),gallery:Lj.optional(),timeline:Rj.optional(),chart:Yj.optional(),tree:$j.optional(),description:K.optional().describe(`View description for documentation/tooltips`),sharing:zj.optional().describe(`View sharing and access configuration`),rowHeight:Pj.optional().describe(`Row height / density setting`),grouping:Ij.optional().describe(`Group records by one or more fields`),rowColor:Bj.optional().describe(`Color rows based on field value`),hiddenFields:w(v()).optional().describe(`Fields to hide in this specific view`),fieldOrder:w(v()).optional().describe(`Explicit field display order for this view`),rowActions:w(v()).optional().describe(`Actions available for individual row items`),bulkActions:w(v()).optional().describe(`Actions available when multiple rows are selected`),bulkActionDefs:w(k(v(),x())).optional().describe(`Rich bulk action definitions (schema-driven, executed via BulkActionDialog)`),virtualScroll:b().optional().describe(`Enable virtual scrolling for large datasets`),conditionalFormatting:w(T({condition:bA.describe(`Predicate (CEL) to evaluate.`),style:k(v(),v()).describe(`CSS styles to apply when condition is true`)})).optional().describe(`Conditional formatting rules for list rows`),inlineEdit:b().optional().describe(`Allow inline editing of records directly in the list view`),exportOptions:w(A([`csv`,`xlsx`,`pdf`,`json`])).optional().describe(`Available export format options`),userActions:Hj.optional().describe(`User action toggles for the view toolbar`),appearance:Uj.optional().describe(`Appearance and visualization configuration`),tabs:w(Wj).optional().describe(`Tab definitions for multi-tab view interface`),addRecord:qj.optional().describe(`Add record entry point configuration`),showRecordCount:b().optional().describe(`Show record count at the bottom of the list`),allowPrinting:b().optional().describe(`Allow users to print the view`),emptyState:T({title:K.optional(),message:K.optional(),icon:v().optional()}).optional().describe(`Empty state configuration when no records found`),aria:dj.optional().describe(`ARIA accessibility attributes for the list view`),responsive:yj.optional().describe(`Responsive layout configuration`),performance:xj.optional().describe(`Performance optimization settings`)})),rM=W(()=>T({field:v().describe(`Field name (snake_case)`),type:Sj.optional().describe(`Field type (auto-infers widget if omitted)`),options:w(Cj).optional().describe(`Options for select/multiselect/radio/checkboxes fields`),reference:v().optional().describe(`Target object name for lookup/master_detail fields`),maxLength:y().optional().describe(`Maximum character length (for text/textarea/email/url/phone)`),minLength:y().optional().describe(`Minimum character length`),min:y().optional().describe(`Minimum value (for number/currency/percent/slider)`),max:y().optional().describe(`Maximum value`),precision:y().optional().describe(`Total digits (for number/currency)`),scale:y().optional().describe(`Decimal places`),multiple:b().optional().describe(`Allow multiple values (for select/lookup/file/image)`),label:K.optional().describe(`Display label override`),placeholder:K.optional().describe(`Placeholder text`),helpText:K.optional().describe(`Help/hint text`),readonly:b().optional().describe(`Read-only override`),immutable:b().optional().describe(`Editable on create, locked once the record exists (e.g. machine names).`),required:b().optional().describe(`Required override`),hidden:b().optional().describe(`Hidden override`),colSpan:y().int().min(1).max(4).optional().describe(`Column span in grid layout (1-4)`),widget:v().optional().describe(`Custom widget/component name (overrides type-based inference)`),language:v().optional().describe(`Code editor language (for type=code)`),fields:w(M(()=>rM)).optional().describe(`Sub-fields for composite/repeater/record types`),keyField:T({field:v().default(`name`).describe(`Property name that holds the key inside each item (defaults to "name")`),label:K.optional().describe(`Display label for the key column`),placeholder:K.optional().describe(`Placeholder when entering a new key`),helpText:K.optional().describe(`Help text under the key input`),regex:v().optional().describe(`JS regex source string the key must match (no flags)`),immutable:b().default(!0).describe(`If true, the key is read-only after creation`)}).optional().describe(`Key column config for record-typed fields`),dependsOn:v().optional().describe(`Parent field name for cascading`),visibleOn:bA.optional().describe(`Visibility predicate (CEL).`),disclosure:A([`inline`,`popover`]).optional().describe(`Composite rendering: inline bordered box (default) or a summary line + gear popover (progressive disclosure).`)})),iM=W(()=>T({name:v().optional().describe(`Stable section identifier for i18n lookup (snake_case)`),label:K.optional(),description:v().optional().describe(`Optional description rendered under the section header.`),collapsible:b().default(!1),collapsed:b().default(!1),visibleOn:bA.optional().describe(`Visibility predicate (CEL). Hides the whole section when false.`),columns:E([A([`1`,`2`,`3`,`4`]),j(1),j(2),j(3),j(4)]).default(1).transform(e=>typeof e==`string`?parseInt(e):e),fields:w(E([v(),rM]))})),aM=W(()=>T({type:A([`simple`,`tabbed`,`wizard`,`split`,`drawer`,`modal`]).default(`simple`),data:Oj.optional().describe(`Data source configuration (defaults to "object" provider)`),sections:w(iM).optional(),groups:w(iM).optional(),subforms:w(T({childObject:v().describe(`Child object whose records are entered inline`),relationshipField:v().optional().describe(`FK on the child pointing back to the parent (auto-detected when omitted)`),columns:w(x()).optional().describe(`Editable grid columns (derived from the child object when omitted)`),amountField:v().optional().describe(`Numeric child column summed for the running total`),totalField:v().optional().describe(`Parent field to receive the rolled-up sum`),title:v().optional().describe(`Section title`),addLabel:v().optional().describe(`Add-row button label`),minRows:y().optional(),maxRows:y().optional()})).optional().describe(`Inline master-detail child collections`),defaultSort:w(T({field:v().describe(`Field name to sort by`),order:A([`asc`,`desc`]).default(`desc`).describe(`Sort direction`)})).optional().describe(`Default sort order for related list views within this form`),sharing:mj.optional().describe(`Public sharing configuration for this form`),submitBehavior:E([T({kind:j(`thank-you`),title:v().optional(),message:v().optional()}),T({kind:j(`redirect`),url:v(),delayMs:y().int().min(0).optional()}),T({kind:j(`continue`)}),T({kind:j(`next-record`)})]).optional().describe(`Post-submit behavior`),aria:dj.optional().describe(`ARIA accessibility attributes for the form view`)})),oM=W(()=>T({list:nM.optional(),form:aM.optional(),listViews:k(v(),nM).optional().describe(`Additional named list views`),formViews:k(v(),aM).optional().describe(`Additional named form views`),protection:uj.optional().describe(`Package author protection block — lock policy for this view.`),...lj})),sM=v().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>`."),cM=A([`package`,`shared`,`personal`]).describe(`View identity layer: package | shared | personal.`);A([`list`,`form`]).describe("Whether `config` is a ListView (list family) or a FormView.");function lM(){return{name:sM,object:v().describe(`Bound object name — the foreign key used to aggregate views.`),label:K.optional().describe(`Display label (supports i18n).`),isDefault:b().optional().describe(`Whether this is the object's default view in the switcher.`),order:y().int().optional().describe(`Sort order within the object's view switcher / left rail.`),scope:cM.optional().describe("Identity layer (defaults to `package` for source-loaded views)."),owner:v().optional().describe("Owner user id — set when `scope` is `personal`."),hidden:b().optional().describe(`Hidden from the switcher (per-user / per-org declutter).`),protection:uj.optional().describe(`Package author protection block — lock policy for this view.`),...lj}}W(()=>D(`viewKind`,[T({viewKind:j(`list`),config:nM.describe(`List-family view configuration.`),...lM()}),T({viewKind:j(`form`),config:aM.describe(`Form view configuration.`),...lM()})]));var uM=A([`select`,`insert`,`update`,`delete`,`all`]),dM=W(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Policy unique identifier (snake_case)`),label:v().optional().describe(`Human-readable policy label`),description:v().optional().describe(`Policy description and business justification`),object:v().describe(`Target object name`),operation:uM.describe(`Database operation this policy applies to`),using:v().optional().describe("Filter condition for SELECT/UPDATE/DELETE. One of the four compiler-supported forms: `field = current_user.<prop>`, `field = 'literal'`, `field IN (current_user.<array>)`, or `1 = 1`. Optional for INSERT-only policies."),check:v().optional().describe(`Validation condition for INSERT/UPDATE (defaults to USING clause if not specified - enforced at application level)`),roles:w(v()).optional().describe(`Roles this policy applies to (omit for all roles)`),enabled:b().default(!0).describe(`Whether this policy is active`),priority:y().int().default(0).describe(`Policy evaluation priority (higher = evaluated first)`),tags:w(v()).optional().describe(`Policy categorization tags`)}).superRefine((e,t)=>{!e.using&&!e.check&&t.addIssue({code:ru.custom,message:`At least one of "using" or "check" must be specified. For SELECT/UPDATE/DELETE operations, provide "using". For INSERT operations, provide "check".`})}));W(()=>T({timestamp:v().describe(`ISO 8601 timestamp of the evaluation`),userId:v().describe(`User ID whose access was evaluated`),operation:A([`select`,`insert`,`update`,`delete`]).describe(`Database operation being performed`),object:v().describe(`Target object name`),policyName:v().describe(`Name of the RLS policy evaluated`),granted:b().describe(`Whether access was granted`),evaluationDurationMs:y().describe(`Policy evaluation duration in milliseconds`),matchedCondition:v().optional().describe(`Which USING/CHECK clause matched`),rowCount:y().optional().describe(`Number of rows affected`),metadata:k(v(),S()).optional().describe(`Additional audit event metadata`)}));var fM=W(()=>T({enabled:b().describe(`Enable RLS audit logging`),logLevel:A([`all`,`denied_only`,`granted_only`,`none`]).describe(`Which evaluations to log`),destination:A([`system_log`,`audit_trail`,`external`]).describe(`Audit log destination`),sampleRate:y().min(0).max(1).describe(`Sampling rate (0-1) for high-traffic environments`),retentionDays:y().int().default(90).describe(`Audit log retention period in days`),includeRowData:b().default(!1).describe(`Include row data in audit logs (security-sensitive)`),alertOnDenied:b().default(!0).describe(`Send alerts when access is denied`)}));W(()=>T({enabled:b().default(!0).describe(`Enable RLS enforcement globally`),defaultPolicy:A([`deny`,`allow`]).default(`deny`).describe(`Default action when no policies match`),allowSuperuserBypass:b().default(!0).describe(`Allow superusers to bypass RLS`),bypassRoles:w(v()).optional().describe(`Roles that bypass RLS (see all data)`),logEvaluations:b().default(!1).describe(`Log RLS policy evaluations for debugging`),cacheResults:b().default(!0).describe(`Cache RLS evaluation results`),cacheTtlSeconds:y().int().positive().default(300).describe(`Cache TTL in seconds`),prefetchUserContext:b().default(!0).describe(`Pre-fetch user context for performance`),audit:fM.optional().describe(`RLS audit logging configuration`)})),W(()=>T({id:v().describe(`User ID`),email:v().email().optional().describe(`User email`),tenantId:v().optional().describe(`Tenant/Organization ID`),role:E([v(),w(v())]).optional().describe(`User role(s)`),department:v().optional().describe(`User department`),attributes:k(v(),S()).optional().describe(`Additional custom user attributes`)})),W(()=>T({policyName:v().describe(`Policy name`),granted:b().describe(`Whether access was granted`),durationMs:y().optional().describe(`Evaluation duration in milliseconds`),error:v().optional().describe(`Error message if evaluation failed`),usingResult:b().optional().describe(`USING clause evaluation result`),checkResult:b().optional().describe(`CHECK clause evaluation result`)}));var pM=A([`own`,`own_and_reports`,`unit`,`unit_and_below`,`org`]),mM=W(()=>T({allowCreate:b().default(!1).describe(`Create permission`),allowRead:b().default(!1).describe(`Read permission`),allowEdit:b().default(!1).describe(`Edit permission`),allowDelete:b().default(!1).describe(`Delete permission`),allowTransfer:b().default(!1).describe(`[EXPERIMENTAL — not enforced] Change record ownership`),allowRestore:b().default(!1).describe(`[EXPERIMENTAL — not enforced] Restore from trash (Undelete)`),allowPurge:b().default(!1).describe(`[EXPERIMENTAL — not enforced] Permanently delete (Hard Delete/GDPR)`),viewAllRecords:b().default(!1).describe(`View All Data (Bypass Sharing)`),modifyAllRecords:b().default(!1).describe(`Modify All Data (Bypass Sharing)`),readScope:pM.optional().describe(`[ADR-0057 D1] Read depth: own|unit|unit_and_below|org`),writeScope:pM.optional().describe(`[ADR-0057 D1] Write depth: own|unit|unit_and_below|org`)})),hM=W(()=>T({readable:b().default(!0).describe(`Field read access`),editable:b().default(!1).describe(`Field edit access`)}));W(()=>T({name:Wk.describe(`Permission set unique name (lowercase snake_case)`),label:v().optional().describe(`Display label`),isProfile:b().default(!1).describe(`Whether this is a user profile`),isDefault:b().default(!1).describe(`[ADR-0056 D7] When true, this profile is the FALLBACK assigned to authenticated users who have no explicit grants — an app declares its default access posture here instead of relying on the built-in member_default. Foundation for SSO/JIT provisioning.`),objects:k(v(),mM).describe(`Entity permissions`),fields:k(v(),hM).optional().describe(`Field level security`),systemPermissions:w(v()).optional().describe(`System level capabilities`),tabPermissions:k(v(),A([`visible`,`hidden`,`default_on`,`default_off`])).optional().describe(`App/tab visibility: visible, hidden, default_on (shown by default), default_off (available but hidden initially)`),rowLevelSecurity:w(dM).optional().describe(`Row-level security policies (see rls.zod.ts for full spec)`),contextVariables:k(v(),S()).optional().describe(`Context variables for RLS evaluation`)}));var gM=W(()=>E([v().describe(`Action Name`),T({type:v(),params:k(v(),S()).optional()})])),_M=W(()=>E([v().describe(`Guard Name (e.g., "isManager", "amountGT1000")`),T({type:v(),params:k(v(),S()).optional()})])),vM=W(()=>T({target:v().optional().describe(`Target State ID`),cond:_M.optional().describe(`Condition (Guard) required to take this path`),actions:w(gM).optional().describe(`Actions to execute during transition`),description:v().optional().describe(`Human readable description of this rule`)}));W(()=>T({type:v().describe(`Event Type (e.g. "APPROVE", "REJECT", "Submit")`),schema:k(v(),S()).optional().describe(`Expected event payload structure`)}));var yM=M(()=>T({type:A([`atomic`,`compound`,`parallel`,`final`,`history`]).default(`atomic`),entry:w(gM).optional().describe(`Actions to run when entering this state`),exit:w(gM).optional().describe(`Actions to run when leaving this state`),on:k(v(),E([v(),vM,w(vM)])).optional().describe(`Map of Event Type -> Transition Definition`),always:w(vM).optional(),initial:v().optional().describe(`Initial child state (if compound)`),states:k(v(),yM).optional(),meta:T({label:v().optional(),description:v().optional(),color:v().optional(),aiInstructions:v().optional().describe(`Specific instructions for AI when in this state`)}).optional()})),bM=W(()=>T({id:Wk.describe(`Unique Machine ID`),description:v().optional(),contextSchema:k(v(),S()).optional().describe(`Zod Schema for the machine context/memory`),initial:v().describe(`Initial State ID`),states:k(v(),yM).describe(`State Nodes`),on:k(v(),E([v(),vM,w(vM)])).optional()})),xM=W(()=>A([`timer`,`signal`,`webhook`,`manual`,`condition`]).describe(`Wait event type determining how a paused flow is resumed`));W(()=>T({executionId:v().describe(`Execution ID of the paused flow`),checkpointId:v().describe(`Checkpoint ID to resume from`),nodeId:v().describe(`Wait node ID being resumed`),eventType:xM.describe(`Event type that triggered resume`),signalName:v().optional().describe(`Signal name (when eventType is signal)`),webhookPayload:k(v(),S()).optional().describe(`Webhook request payload (when eventType is webhook)`),resumedBy:v().optional().describe(`User ID or system identifier that triggered resume`),resumedAt:v().datetime().describe(`ISO 8601 timestamp of the resume event`),variables:k(v(),S()).optional().describe(`Variables to merge into flow context upon resume`)}).describe(`Payload for resuming a paused wait node`));var SM=W(()=>A([`fail`,`continue`,`fallback`]).describe(`Behavior when a wait node exceeds its timeout`));W(()=>T({defaultTimeoutMs:y().int().min(0).default(864e5).describe(`Default timeout in ms (default: 24 hours)`),defaultTimeoutBehavior:SM.default(`fail`).describe(`Default behavior when wait timeout is exceeded`),conditionPollIntervalMs:y().int().min(1e3).default(3e4).describe(`Polling interval for condition waits in ms (default: 30s)`),conditionMaxPolls:y().int().min(0).default(0).describe(`Max polling attempts for condition waits (0 = unlimited)`),webhookUrlPattern:v().default(`/api/v1/automation/resume/{executionId}/{nodeId}`).describe(`URL pattern for webhook resume endpoints`),persistCheckpoints:b().default(!0).describe(`Persist wait checkpoints to durable storage`),maxPausedExecutions:y().int().min(0).default(0).describe(`Max concurrent paused executions (0 = unlimited)`)}).describe(`Wait node executor plugin configuration`)),W(()=>T({id:v().describe(`Unique executor plugin identifier`),name:v().describe(`Display name`),nodeTypes:w(v()).min(1).describe(`FlowNodeAction types this executor handles`),version:v().describe(`Plugin version (semver)`),description:v().optional().describe(`Executor description`),supportsPause:b().default(!1).describe(`Whether the executor supports async pause/resume`),supportsCancellation:b().default(!1).describe(`Whether the executor supports mid-execution cancellation`),supportsRetry:b().default(!0).describe(`Whether the executor supports retry on failure`),configSchemaRef:v().optional().describe(`JSON Schema $ref for executor-specific config`)}).describe(`Node executor plugin descriptor`));var CM=W(()=>A([`logic`,`data`,`io`,`human`,`control`,`custom`]).describe(`Action palette category`)),wM=W(()=>A([`flow`,`approval`]).describe(`Authoring paradigm that may offer this action`)),TM=W(()=>T({type:v().min(1).describe(`Registry action/node type (matches the executor type)`),version:v().describe(`Executor version (semver)`),name:v().describe(`Display label (or i18n key)`),description:v().optional().describe(`Action description`),icon:v().optional().describe(`Icon id resolved by the designer`),category:CM.default(`custom`).describe(`Palette category`),paradigms:w(wM).default([`flow`]).describe(`Authoring surfaces that may offer this action`),configSchema:S().optional().describe(`JSON Schema for the node config (drives form + parse validation)`),supportsPause:b().default(!1).describe(`Supports async pause/resume`),supportsCancellation:b().default(!1).describe(`Supports cancellation`),supportsRetry:b().default(!0).describe(`Supports retry on failure`),needsOutbox:b().default(!1).describe(`Dispatch via service-messaging outbox (retry/idempotency/dead-letter)`),isAsync:b().default(!1).describe(`Suspends the flow awaiting an external reply`),maturity:A([`ga`,`beta`,`reserved`]).default(`ga`).describe(`Runtime maturity: ga (shipped), beta, or reserved (contract only — designers grey this out)`),source:A([`builtin`,`plugin`]).default(`plugin`).describe(`builtin = platform baseline; plugin = third-party contributed`),deprecated:b().default(!1).describe(`Deprecated alias kept for back-compat`),aliasOf:v().optional().describe(`Canonical type this alias forwards to`)}).describe(`Canonical cross-paradigm action/node descriptor (ADR-0018)`)),EM=W(()=>v().describe(`BCP-47 Language Tag (e.g. en-US, zh-CN)`)),DM=W(()=>T({label:v().optional().describe(`Translated field label`),help:v().optional().describe(`Translated help text`),placeholder:v().optional().describe(`Translated placeholder text for form inputs`),options:k(v(),v()).optional().describe(`Option value to translated label map`)}).describe(`Translation data for a single field`)),OM=W(()=>T({label:v().describe(`Translated singular label`),pluralLabel:v().optional().describe(`Translated plural label`),description:v().optional().describe(`Translated object description`),fields:k(v(),DM).optional().describe(`Field-level translations`),_views:k(v(),T({label:v().optional().describe(`Translated view label`),description:v().optional().describe(`Translated view description`)})).optional().describe(`View translations keyed by view name`),_actions:k(v(),T({label:v().optional().describe(`Translated action label`),confirmText:v().optional().describe(`Translated confirmation prompt`),successMessage:v().optional().describe(`Translated success toast/message`),params:k(v(),T({label:v().optional().describe(`Translated action parameter label`),helpText:v().optional().describe(`Translated action parameter help/hint text`),placeholder:v().optional().describe(`Translated action parameter placeholder`),options:k(v(),v()).optional().describe(`Param select option value to translated label`)})).optional().describe(`Action parameter translations keyed by parameter name`)})).optional().describe(`Action translations keyed by action name`),_sections:k(v(),T({label:v().optional().describe(`Translated section label`),description:v().optional().describe(`Translated section description`)})).optional().describe(`Section translations keyed by section name`)}).describe(`Translation data for a single object`)),kM=W(()=>T({objects:k(v(),OM).optional().describe(`Object translations keyed by object name`),apps:k(v(),T({label:v().describe(`Translated app label`),description:v().optional().describe(`Translated app description`),navigation:k(v(),T({label:v().describe(`Translated navigation group label`)})).optional().describe(`Navigation group translations keyed by group ID`)})).optional().describe(`App translations keyed by app name`),messages:k(v(),v()).optional().describe(`UI message translations keyed by message ID`),validationMessages:k(v(),v()).optional().describe(`Translatable validation error messages keyed by rule name (e.g., {"discount_limit": "折扣不能超过40%"})`),globalActions:k(v(),T({label:v().optional().describe(`Translated action label`),confirmText:v().optional().describe(`Translated confirmation prompt`),successMessage:v().optional().describe(`Translated success toast/message`),params:k(v(),T({label:v().optional().describe(`Translated action parameter label`),helpText:v().optional().describe(`Translated action parameter help/hint text`),placeholder:v().optional().describe(`Translated action parameter placeholder`),options:k(v(),v()).optional().describe(`Param select option value to translated label`)})).optional().describe(`Action parameter translations keyed by parameter name`)})).optional().describe(`Global action translations keyed by action name`),dashboards:k(v(),T({label:v().optional().describe(`Translated dashboard title`),description:v().optional().describe(`Translated dashboard description`),actions:k(v(),T({label:v().optional().describe(`Translated header action label`)})).optional().describe(`Header action label translations keyed by action url/key`),widgets:k(v(),T({title:v().optional().describe(`Translated widget title`),description:v().optional().describe(`Translated widget description`)})).optional().describe(`Widget translations keyed by widget id`)})).optional().describe(`Dashboard translations keyed by dashboard name`),settings:k(v(),T({title:v().optional().describe(`Translated settings manifest title`),description:v().optional().describe(`Translated settings manifest description`),groups:k(v(),T({title:v().optional().describe(`Translated group title`),description:v().optional().describe(`Translated group description`)})).optional().describe(`Group translations keyed by group key`),keys:k(v(),T({label:v().optional().describe(`Translated setting label`),help:v().optional().describe(`Translated setting help text`),placeholder:v().optional().describe(`Translated input placeholder`),options:k(v(),v()).optional().describe(`Enum option value → translated label`)})).optional().describe(`Per-setting field translations keyed by setting key`),actions:k(v(),T({label:v().optional().describe(`Translated action label`),confirmText:v().optional().describe(`Translated confirmation prompt`),successMessage:v().optional().describe(`Translated success toast/message`)})).optional().describe(`Action button translations keyed by action id`)})).optional().describe(`Settings manifest translations keyed by namespace`),metadataForms:k(v(),T({label:v().optional().describe(`Translated metadata-type display label (overrides registry label)`),description:v().optional().describe(`Translated metadata-type description`),sections:k(v(),T({label:v().optional().describe(`Translated section label`),description:v().optional().describe(`Translated section description`)})).optional().describe(`Section translations keyed by section.name`),fields:k(v(),T({label:v().optional().describe(`Translated field label`),helpText:v().optional().describe(`Translated field help/hint text`),placeholder:v().optional().describe(`Translated field placeholder text`)})).optional().describe(`Field translations keyed by field path (dot-notation for nested fields)`)})).optional().describe(`Translations for metadata-type configuration forms keyed by metadata type`),settingsCommon:T({sourceLabels:T({env:v().optional(),global:v().optional(),tenant:v().optional(),user:v().optional(),default:v().optional()}).optional().describe(`Source badge labels by resolution layer`)}).optional().describe(`Cross-namespace Settings UI strings`)}).describe(`Translation data for objects, apps, and UI messages`));W(()=>k(EM,kM).describe(`Map of locale codes to translation data`));var AM=W(()=>A([`bundled`,`per_locale`,`per_namespace`]).describe(`Translation file organization strategy`)),jM=W(()=>A([`icu`,`simple`]).describe(`Message interpolation format: ICU MessageFormat or simple {variable} replacement`));W(()=>T({defaultLocale:EM.describe(`Default locale (e.g., "en")`),supportedLocales:w(EM).describe(`Supported BCP-47 locale codes`),fallbackLocale:EM.optional().describe(`Fallback locale code`),fileOrganization:AM.default(`per_locale`).describe(`File organization strategy`),messageFormat:jM.default(`simple`).describe(`Message interpolation format (ICU MessageFormat or simple)`),lazyLoad:b().default(!1).describe(`Load translations on demand`),cache:b().default(!0).describe(`Cache loaded translations`)}).describe(`Internationalization configuration`));var MM=k(v(),v()).describe(`Option value to translated label map`),NM=W(()=>T({label:v().describe(`Translated singular label`),pluralLabel:v().optional().describe(`Translated plural label`),description:v().optional().describe(`Translated object description`),helpText:v().optional().describe(`Translated help text for the object`),fields:k(v(),DM).optional().describe(`Field translations keyed by field name`),_options:k(v(),MM).optional().describe(`Object-scoped picklist option translations keyed by field name`),_views:k(v(),T({label:v().optional().describe(`Translated view label`),description:v().optional().describe(`Translated view description`)})).optional().describe(`View translations keyed by view name`),_sections:k(v(),T({label:v().optional().describe(`Translated section label`)})).optional().describe(`Section translations keyed by section name`),_actions:k(v(),T({label:v().optional().describe(`Translated action label`),confirmMessage:v().optional().describe(`Translated confirmation message`),params:k(v(),T({label:v().optional().describe(`Translated action parameter label`),helpText:v().optional().describe(`Translated action parameter help/hint text`),placeholder:v().optional().describe(`Translated action parameter placeholder`),options:k(v(),v()).optional().describe(`Param select option value to translated label`)})).optional().describe(`Action parameter translations keyed by parameter name`)})).optional().describe(`Action translations keyed by action name`),_notifications:k(v(),T({title:v().optional().describe(`Translated notification title`),body:v().optional().describe(`Translated notification body (supports ICU MessageFormat when enabled)`)})).optional().describe(`Notification translations keyed by notification name`),_errors:k(v(),v()).optional().describe(`Error message translations keyed by error code`)}).describe(`Object-first aggregated translation node`));W(()=>T({_meta:T({locale:v().optional().describe(`BCP-47 locale code for this bundle`),direction:A([`ltr`,`rtl`]).optional().describe(`Text direction: left-to-right or right-to-left`)}).optional().describe(`Bundle-level metadata (locale, bidi direction)`),namespace:v().optional().describe(`Namespace for plugin isolation to avoid translation key collisions`),o:k(v(),NM).optional().describe(`Object-first translations keyed by object name`),_globalOptions:k(v(),MM).optional().describe(`Global picklist option translations keyed by option set name`),app:k(v(),T({label:v().describe(`Translated app label`),description:v().optional().describe(`Translated app description`)})).optional().describe(`App translations keyed by app name`),nav:k(v(),v()).optional().describe(`Navigation item translations keyed by nav item name`),dashboard:k(v(),T({label:v().optional().describe(`Translated dashboard label`),description:v().optional().describe(`Translated dashboard description`)})).optional().describe(`Dashboard translations keyed by dashboard name`),reports:k(v(),T({label:v().optional().describe(`Translated report label`),description:v().optional().describe(`Translated report description`)})).optional().describe(`Report translations keyed by report name`),pages:k(v(),T({title:v().optional().describe(`Translated page title`),description:v().optional().describe(`Translated page description`)})).optional().describe(`Page translations keyed by page name`),messages:k(v(),v()).optional().describe(`UI message translations keyed by message ID (supports ICU MessageFormat)`),validationMessages:k(v(),v()).optional().describe(`Validation error message translations keyed by rule name (supports ICU MessageFormat)`),notifications:k(v(),T({title:v().optional().describe(`Translated notification title`),body:v().optional().describe(`Translated notification body (supports ICU MessageFormat when enabled)`)})).optional().describe(`Global notification translations keyed by notification name`),errors:k(v(),v()).optional().describe(`Global error message translations keyed by error code`)}).describe(`Object-first application translation bundle for a single locale`));var PM=W(()=>A([`missing`,`redundant`,`stale`]).describe(`Translation diff status: missing from bundle, redundant (no matching metadata), or stale (metadata changed)`)),FM=W(()=>T({key:v().describe(`Dot-path translation key`),status:PM.describe(`Diff status of this translation key`),objectName:v().optional().describe(`Associated object name (snake_case)`),locale:v().describe(`BCP-47 locale code`),sourceHash:v().optional().describe(`Hash of source metadata for precise stale detection`),aiSuggested:v().optional().describe(`AI-suggested translation for this key`),aiConfidence:y().min(0).max(1).optional().describe(`AI suggestion confidence score (0–1)`)}).describe(`A single translation diff item`)),IM=W(()=>T({group:v().describe(`Translation group category`),totalKeys:y().int().nonnegative().describe(`Total keys in this group`),translatedKeys:y().int().nonnegative().describe(`Translated keys in this group`),coveragePercent:y().min(0).max(100).describe(`Coverage percentage for this group`)}).describe(`Coverage breakdown for a single translation group`));W(()=>T({locale:v().describe(`BCP-47 locale code`),objectName:v().optional().describe(`Object name scope (omit for full bundle)`),totalKeys:y().int().nonnegative().describe(`Total translatable keys from metadata`),translatedKeys:y().int().nonnegative().describe(`Number of translated keys`),missingKeys:y().int().nonnegative().describe(`Number of missing translations`),redundantKeys:y().int().nonnegative().describe(`Number of redundant translations`),staleKeys:y().int().nonnegative().describe(`Number of stale translations`),coveragePercent:y().min(0).max(100).describe(`Translation coverage percentage`),items:w(FM).describe(`Detailed diff items`),breakdown:w(IM).optional().describe(`Per-group coverage breakdown`)}).describe(`Aggregated translation coverage result`));var LM=W(()=>A([`full`,`partial`,`experimental`,`deprecated`]).describe(`Level of protocol conformance`)),RM=W(()=>T({major:y().int().min(0),minor:y().int().min(0),patch:y().int().min(0)}).describe(`Semantic version of the protocol`)),zM=W(()=>T({id:v().regex(/^([a-z][a-z0-9]*\.)+protocol\.[a-z][a-z0-9._]*\.v\d+$/).describe(`Unique protocol identifier (e.g., com.objectstack.protocol.storage.v1)`),label:v(),version:RM,specification:v().optional().describe(`URL or path to protocol specification`),description:v().optional()})),BM=W(()=>T({name:v().describe(`Feature identifier within the protocol`),enabled:b().default(!0),description:v().optional(),sinceVersion:v().optional().describe(`Version when this feature was added`),deprecatedSince:v().optional().describe(`Version when deprecated`)})),VM=W(()=>T({protocol:zM,conformance:LM.default(`full`),implementedFeatures:w(v()).optional().describe(`List of implemented feature names`),features:w(BM).optional(),metadata:k(v(),S()).optional(),certified:b().default(!1).describe(`Has passed official conformance tests`),certificationDate:v().datetime().optional()})),HM=W(()=>T({id:v().regex(/^([a-z][a-z0-9]*\.)+interface\.[a-z][a-z0-9._]+$/).describe(`Unique interface identifier`),name:v(),description:v().optional(),version:RM,methods:w(T({name:v().describe(`Method name`),description:v().optional(),parameters:w(T({name:v(),type:v().describe(`Type notation (e.g., string, number, User)`),required:b().default(!0),description:v().optional()})).optional(),returnType:v().optional().describe(`Return value type`),async:b().default(!1).describe(`Whether method returns a Promise`)})),events:w(T({name:v().describe(`Event name`),description:v().optional(),payload:v().optional().describe(`Event payload type`)})).optional(),stability:A([`stable`,`beta`,`alpha`,`experimental`]).default(`stable`)})),UM=W(()=>T({pluginId:v().regex(/^([a-z][a-z0-9]*\.)+[a-z][a-z0-9-]+$/).describe(`Required plugin identifier`),version:v().describe(`Semantic version constraint`),optional:b().default(!1),reason:v().optional(),requiredCapabilities:w(v()).optional().describe(`Protocol IDs the dependency must support`)})),WM=W(()=>T({id:v().regex(/^([a-z][a-z0-9]*\.)+extension\.[a-z][a-z0-9._]+$/).describe(`Unique extension point identifier`),name:v(),description:v().optional(),type:A([`action`,`hook`,`widget`,`provider`,`transformer`,`validator`,`decorator`]),contract:T({input:v().optional().describe(`Input type/schema`),output:v().optional().describe(`Output type/schema`),signature:v().optional().describe(`Function signature if applicable`)}).optional(),cardinality:A([`single`,`multiple`]).default(`multiple`).describe(`Whether multiple extensions can register to this point`)})),GM=W(()=>T({implements:w(VM).optional().describe(`List of protocols this plugin conforms to`),provides:w(HM).optional().describe(`Services/APIs this plugin offers to others`),requires:w(UM).optional().describe(`Required plugins and their capabilities`),extensionPoints:w(WM).optional().describe(`Points where other plugins can extend this plugin`),extensions:w(T({targetPluginId:v().describe(`Plugin ID being extended`),extensionPointId:v().describe(`Extension point identifier`),implementation:v().describe(`Path to implementation module`),priority:y().int().default(100).describe(`Registration priority (lower = higher priority)`)})).optional().describe(`Extensions contributed to other plugins`)})),KM=W(()=>A([`eager`,`lazy`,`parallel`,`deferred`,`on-demand`]).describe(`Plugin loading strategy`)),qM=W(()=>T({enabled:b().default(!1),priority:y().int().min(0).default(100),resources:w(A([`metadata`,`dependencies`,`assets`,`code`,`services`])).optional(),conditions:T({routes:w(v()).optional(),roles:w(v()).optional(),deviceType:w(A([`desktop`,`mobile`,`tablet`])).optional(),minNetworkSpeed:A([`slow-2g`,`2g`,`3g`,`4g`]).optional()}).optional()}).describe(`Plugin preloading configuration`)),JM=W(()=>T({enabled:b().default(!0),strategy:A([`route`,`feature`,`size`,`custom`]).default(`feature`),chunkNaming:A([`hashed`,`named`,`sequential`]).default(`hashed`),maxChunkSize:y().int().min(10).optional().describe(`Max chunk size in KB`),sharedDependencies:T({enabled:b().default(!0),minChunks:y().int().min(1).default(2)}).optional()}).describe(`Plugin code splitting configuration`)),YM=W(()=>T({enabled:b().default(!0),mode:A([`async`,`sync`,`eager`,`lazy`]).default(`async`),prefetch:b().default(!1).describe(`Prefetch module in idle time`),preload:b().default(!1).describe(`Preload module in parallel with parent`),webpackChunkName:v().optional().describe(`Custom chunk name for webpack`),timeout:y().int().min(100).default(3e4).describe(`Dynamic import timeout (ms)`),retry:T({enabled:b().default(!0),maxAttempts:y().int().min(1).max(10).default(3),backoffMs:y().int().min(0).default(1e3).describe(`Exponential backoff base delay`)}).optional()}).describe(`Plugin dynamic import configuration`)),XM=W(()=>T({mode:A([`sync`,`async`,`parallel`,`sequential`]).default(`async`),timeout:y().int().min(100).default(3e4),priority:y().int().min(0).default(100),critical:b().default(!1).describe(`If true, kernel bootstrap fails if plugin fails`),retry:T({enabled:b().default(!1),maxAttempts:y().int().min(1).max(5).default(3),backoffMs:y().int().min(0).default(1e3)}).optional(),healthCheckInterval:y().int().min(0).optional().describe(`Health check interval in ms (0 = disabled)`)}).describe(`Plugin initialization configuration`)),ZM=W(()=>T({strategy:A([`strict`,`compatible`,`latest`,`pinned`]).default(`compatible`),peerDependencies:T({resolve:b().default(!0),onMissing:A([`error`,`warn`,`ignore`]).default(`warn`),onMismatch:A([`error`,`warn`,`ignore`]).default(`warn`)}).optional(),optionalDependencies:T({load:b().default(!0),onFailure:A([`warn`,`ignore`]).default(`warn`)}).optional(),conflictResolution:A([`fail`,`latest`,`oldest`,`manual`]).default(`latest`),circularDependencies:A([`error`,`warn`,`allow`]).default(`warn`)}).describe(`Plugin dependency resolution configuration`)),QM=W(()=>T({enabled:b().default(!1),environment:A([`development`,`staging`,`production`]).default(`development`).describe(`Target environment controlling safety level`),strategy:A([`full`,`partial`,`state-preserve`]).default(`full`),watchPatterns:w(v()).optional().describe(`Glob patterns for files to watch`),ignorePatterns:w(v()).optional().describe(`Glob patterns for files to ignore`),debounceMs:y().int().min(0).default(300),preserveState:b().default(!1),stateSerialization:T({enabled:b().default(!1),handler:v().optional()}).optional(),hooks:T({beforeReload:v().optional().describe(`Function to call before reload`),afterReload:v().optional().describe(`Function to call after reload`),onError:v().optional().describe(`Function to call on reload error`)}).optional(),productionSafety:T({healthValidation:b().default(!0).describe(`Run health checks after reload before accepting traffic`),rollbackOnFailure:b().default(!0).describe(`Auto-rollback if reloaded plugin fails health check`),healthTimeout:y().int().min(1e3).default(3e4).describe(`Health check timeout after reload in ms`),drainConnections:b().default(!0).describe(`Gracefully drain active requests before reloading`),drainTimeout:y().int().min(0).default(15e3).describe(`Max wait time for connection draining in ms`),maxConcurrentReloads:y().int().min(1).default(1).describe(`Limit concurrent reloads to prevent system instability`),minReloadInterval:y().int().min(1e3).default(5e3).describe(`Cooldown period between reloads of the same plugin`)}).optional()}).describe(`Plugin hot reload configuration`)),$M=W(()=>T({enabled:b().default(!0),storage:A([`memory`,`disk`,`indexeddb`,`hybrid`]).default(`memory`),keyStrategy:A([`version`,`hash`,`timestamp`]).default(`version`),ttl:y().int().min(0).optional().describe(`Time to live in seconds (0 = infinite)`),maxSize:y().int().min(1).optional().describe(`Max cache size in MB`),invalidateOn:w(A([`version-change`,`dependency-change`,`manual`,`error`])).optional(),compression:T({enabled:b().default(!1),algorithm:A([`gzip`,`brotli`,`deflate`]).default(`gzip`)}).optional()}).describe(`Plugin caching configuration`)),eN=W(()=>T({enabled:b().default(!1),scope:A([`automation-only`,`untrusted-only`,`all-plugins`]).default(`automation-only`).describe(`Which plugins are subject to isolation`),isolationLevel:A([`none`,`process`,`vm`,`iframe`,`web-worker`]).default(`none`),allowedCapabilities:w(v()).optional().describe(`List of allowed capability IDs`),resourceQuotas:T({maxMemoryMB:y().int().min(1).optional(),maxCpuTimeMs:y().int().min(100).optional(),maxFileDescriptors:y().int().min(1).optional(),maxNetworkKBps:y().int().min(1).optional()}).optional(),permissions:T({allowedAPIs:w(v()).optional(),allowedPaths:w(v()).optional(),allowedEndpoints:w(v()).optional(),allowedEnvVars:w(v()).optional()}).optional(),ipc:T({enabled:b().default(!0).describe(`Allow sandboxed plugins to communicate via IPC`),transport:A([`message-port`,`unix-socket`,`tcp`,`memory`]).default(`message-port`).describe(`IPC transport for cross-boundary communication`),maxMessageSize:y().int().min(1024).default(1048576).describe(`Maximum IPC message size in bytes (default 1MB)`),timeout:y().int().min(100).default(3e4).describe(`IPC message response timeout in ms`),allowedServices:w(v()).optional().describe(`Service names the sandboxed plugin may invoke via IPC`)}).optional()}).describe(`Plugin sandboxing configuration`)),tN=W(()=>T({enabled:b().default(!1),metrics:w(A([`load-time`,`init-time`,`memory-usage`,`cpu-usage`,`api-calls`,`error-rate`,`cache-hit-rate`])).optional(),samplingRate:y().min(0).max(1).default(1),reportingInterval:y().int().min(1).default(60),budgets:T({maxLoadTimeMs:y().int().min(0).optional(),maxInitTimeMs:y().int().min(0).optional(),maxMemoryMB:y().int().min(0).optional()}).optional(),onBudgetViolation:A([`warn`,`error`,`ignore`]).default(`warn`)}).describe(`Plugin performance monitoring configuration`)),nN=W(()=>T({strategy:KM.default(`lazy`),preload:qM.optional(),codeSplitting:JM.optional(),dynamicImport:YM.optional(),initialization:XM.optional(),dependencyResolution:ZM.optional(),hotReload:QM.optional(),caching:$M.optional(),sandboxing:eN.optional(),monitoring:tN.optional()}).describe(`Complete plugin loading configuration`));W(()=>T({type:A([`load-started`,`load-completed`,`load-failed`,`init-started`,`init-completed`,`init-failed`,`preload-started`,`preload-completed`,`cache-hit`,`cache-miss`,`hot-reload`,`dynamic-load`,`dynamic-unload`,`dynamic-discover`]),pluginId:v(),timestamp:y().int().min(0),durationMs:y().int().min(0).optional(),metadata:k(v(),S()).optional(),error:T({message:v(),code:v().optional(),stack:v().optional()}).optional()}).describe(`Plugin loading lifecycle event`)),W(()=>T({pluginId:v(),state:A([`pending`,`loading`,`loaded`,`initializing`,`ready`,`failed`,`reloading`,`unloading`,`unloaded`]),progress:y().min(0).max(100).default(0),startedAt:y().int().min(0).optional(),completedAt:y().int().min(0).optional(),lastError:v().optional(),retryCount:y().int().min(0).default(0)}).describe(`Plugin loading state`)),W(()=>T({ql:T({object:P().describe(`Get object handle for method chaining`),query:P().describe(`Execute a query`)}).passthrough().describe(`ObjectQL Engine Interface`),os:T({getCurrentUser:P().describe(`Get the current authenticated user`),getConfig:P().describe(`Get platform configuration`)}).passthrough().describe(`ObjectStack Kernel Interface`),logger:T({debug:P().describe(`Log debug message`),info:P().describe(`Log info message`),warn:P().describe(`Log warning message`),error:P().describe(`Log error message`)}).passthrough().describe(`Logger Interface`),storage:T({get:P().describe(`Get a value from storage`),set:P().describe(`Set a value in storage`),delete:P().describe(`Delete a value from storage`)}).passthrough().describe(`Storage Interface`),i18n:T({t:P().describe(`Translate a key`),getLocale:P().describe(`Get current locale`)}).passthrough().describe(`Internationalization Interface`),metadata:k(v(),S()),events:k(v(),S()),app:T({router:T({get:P().describe(`Register GET route handler`),post:P().describe(`Register POST route handler`),use:P().describe(`Register middleware`)}).passthrough()}).passthrough().describe(`App Framework Interface`),drivers:T({register:P().describe(`Register a driver`)}).passthrough().describe(`Driver Registry`)})),W(()=>T({previousVersion:v().describe(`Version before upgrade`),newVersion:v().describe(`Version after upgrade`),isMajorUpgrade:b().describe(`Whether this is a major version bump`),previousMetadata:k(v(),S()).optional().describe(`Metadata snapshot before upgrade`)}).describe(`Version migration context for onUpgrade hook`));var rN=W(()=>T({onInstall:P().optional().describe(`Called when plugin is installed`),onEnable:P().optional().describe(`Called when plugin is enabled`),onDisable:P().optional().describe(`Called when plugin is disabled`),onUninstall:P().optional().describe(`Called when plugin is uninstalled`),onUpgrade:P().optional().describe(`Called when plugin is upgraded. Receives UpgradeContext with previousVersion, newVersion, and isMajorUpgrade`)})),iN=[`ui`,`driver`,`server`,`app`,`theme`,`agent`,`objectql`],aN=[`app`];W(()=>rN.extend({id:v().min(1).optional().describe(`Unique Plugin ID (e.g. com.example.crm)`),type:A([`standard`,...iN]).default(`standard`).optional().describe(`Plugin Type categorization for runtime behavior`),staticPath:v().optional().describe(`Absolute path to static assets (Required for type="ui-plugin")`),slug:v().regex(/^[a-z0-9-_]+$/).optional().describe(`URL path segment (Required for type="ui-plugin")`),default:b().optional().describe(`Serve at root path (Only one "ui-plugin" can be default)`),version:v().regex(/^\d+\.\d+\.\d+$/).optional().describe(`Semantic Version`),description:v().optional(),author:v().optional(),homepage:v().url().optional()}));var oN=A([`insert`,`update`,`upsert`,`replace`,`ignore`]),sN=W(()=>T({object:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Target Object Name`),externalId:v().default(`name`).describe(`Field match for uniqueness check`),mode:oN.default(`upsert`).describe(`Conflict resolution strategy`),env:w(A([`prod`,`dev`,`test`])).default([`prod`,`dev`,`test`]).describe(`Applicable environments`),records:w(k(v(),S())).describe(`Data records`)})),cN=T({id:Wk.describe(`Unique identifier for this navigation item (lowercase snake_case)`),label:K.describe(`Display proper label`),icon:v().optional().describe(`Icon name`),order:y().optional().describe(`Sort order within the same level (lower = first)`),badge:E([v(),y()]).optional().describe(`Badge text or count displayed on the item`),visible:bA.optional().describe("Visibility predicate (CEL). e.g. P`'org_admin' in current_user.roles`"),requiredPermissions:w(v()).optional().describe(`Permissions required to access this item`),requiresObject:v().optional().describe(`Hide/disable this entry unless the named object is registered in the runtime`),requiresService:v().optional().describe(`Hide/disable this entry unless the named kernel service is registered`)}),lN=W(()=>cN.extend({type:j(`object`),objectName:v().describe(`Target object name`),viewName:v().optional().describe('Default list view to open. Defaults to "all". Ignored when `recordId` is set.'),recordId:v().optional().describe(`Navigate directly to this record id instead of the list view. Supports template vars: {current_user_id}, {current_org_id}.`),recordMode:A([`view`,`edit`]).optional().describe("Open the record in view (default) or edit mode. Only meaningful when `recordId` is set.")})),uN=W(()=>cN.extend({type:j(`dashboard`),dashboardName:v().describe(`Target dashboard name`)})),dN=W(()=>cN.extend({type:j(`page`),pageName:v().describe(`Target custom page component name`),params:k(v(),S()).optional().describe(`Parameters passed to the page context`)})),fN=W(()=>cN.extend({type:j(`url`),url:v().describe(`Target external URL`),target:A([`_self`,`_blank`]).default(`_self`).describe(`Link target window`)})),pN=W(()=>cN.extend({type:j(`report`),reportName:v().describe(`Target report name`)})),mN=W(()=>cN.extend({type:j(`action`),actionDef:T({actionName:v().describe(`Action machine name to execute`),params:k(v(),S()).optional().describe(`Parameters passed to the action`)}).describe(`Action definition to execute when clicked`)})),hN=W(()=>cN.extend({type:j(`component`),componentRef:v().describe(`Component registry key (e.g. "metadata:directory")`),params:k(v(),S()).optional().describe(`Props passed to the component`)})),gN=W(()=>cN.extend({type:j(`group`),expanded:b().default(!1).describe(`Default expansion state in sidebar`)})),_N=M(()=>E([lN.extend({children:w(_N).optional().describe(`Child navigation items (e.g. specific views)`)}),uN,dN,fN,pN,mN,hN,gN.extend({children:w(_N).describe(`Child navigation items`)})])),vN=W(()=>T({app:Wk.describe(`Target app name to contribute navigation into (e.g. "setup")`),group:Wk.optional().describe(`Target group nav-item id to append into (e.g. "group_integrations"); omit to append at the app top level`),priority:y().int().min(0).default(200).describe(`Merge priority within the target group — lower applied first (matches object extender priority)`),items:w(_N).describe(`Navigation items contributed into the target app/group`)}).describe(`A navigation contribution: a package injecting nav items into an app it does not own (ADR-0029 D7)`)),yN=W(()=>T({primaryColor:v().optional().describe(`Primary theme color hex code`),logo:v().optional().describe(`Custom logo URL for this app`),favicon:v().optional().describe(`Custom favicon URL for this app`)})),bN=W(()=>T({id:Wk.describe(`Unique area identifier (lowercase snake_case)`),label:K.describe(`Area display label`),icon:v().optional().describe(`Area icon name`),order:y().optional().describe(`Sort order among areas (lower = first)`),description:K.optional().describe(`Area description`),visible:bA.optional().describe(`Visibility predicate (CEL) for this area.`),requiredPermissions:w(v()).optional().describe(`Permissions required to access this area`),navigation:w(_N).describe(`Navigation items within this area`)})),xN=W(()=>T({id:Wk.describe(`Selector id; selected value is exposed as the nav template var {<id>}`),label:K.describe(`Dropdown label`),icon:v().optional().describe(`Icon name`),optionsSource:T({endpoint:v().describe(`REST endpoint returning the option rows (e.g. /api/v1/packages)`),valueKey:v().default(`id`).describe(`Row property used as the option value (dotted path allowed, e.g. "manifest.id")`),labelKey:v().default(`name`).describe(`Row property used as the option label (dotted path allowed, e.g. "manifest.name")`),filter:w(T({key:v().describe(`Dotted path on each row to compare (e.g. "manifest.scope")`),op:A([`eq`,`ne`,`in`,`nin`]).default(`eq`).describe(`Comparison operator: eq | ne | in | nin`),value:E([v(),w(v())]).describe(`Comparison value (string for eq/ne, string[] for in/nin)`)})).optional().describe(`Predicates (AND) each option row must satisfy`)}).describe(`Option data source`),includeAll:b().default(!0).describe(`Prepend an "All" option that clears the scope`),allValue:v().default(``).describe(`Template value when "All" is selected (empty = no filter)`),persist:A([`query`,`session`,`none`]).default(`query`).describe(`Persist selection via URL query, sessionStorage, or not at all`),placement:A([`sidebar_header`,`topbar`]).default(`sidebar_header`).describe(`Render location in the app chrome`)})),SN=W(()=>T({name:Wk.describe(`App unique machine name (lowercase snake_case)`),label:K.describe(`App display label`),version:v().optional().describe(`App version`),description:K.optional().describe(`App description`),icon:v().optional().describe(`App icon used in the App Launcher`),branding:yN.optional().describe(`App-specific branding`),active:b().optional().default(!0).describe(`Whether the app is enabled`),isDefault:b().optional().default(!1).describe(`Is default app`),hidden:b().optional().describe(`Hide from the App Switcher; the shell surfaces hidden apps via the avatar menu instead`),navigation:w(_N).optional().describe(`Full navigation tree for the app sidebar`),areas:w(bN).optional().describe(`Navigation areas for partitioning navigation by business domain`),contextSelectors:w(xN).optional().describe(`App-level scope dropdowns whose value is injected into nav items as {<id>} template vars`),homePageId:v().optional().describe(`ID of the navigation item to serve as landing page`),requiredPermissions:w(v()).optional().describe(`Permissions required to access this app`),objects:w(S()).optional().describe(`Objects belonging to this app`),apis:w(S()).optional().describe(`Custom APIs belonging to this app`),sharing:mj.optional().describe(`Public sharing configuration`),embed:hj.optional().describe(`Iframe embedding configuration`),mobileNavigation:T({mode:A([`drawer`,`bottom_nav`,`hamburger`]).default(`drawer`).describe(`Mobile navigation mode: drawer sidebar, bottom navigation bar, or hamburger menu`),bottomNavItems:w(v()).optional().describe(`Navigation item IDs to show in bottom nav (max 5)`)}).optional().describe(`Mobile-specific navigation configuration`),defaultAgent:Wk.optional().describe(`Name of the default AI agent for this app (used by the ambient chat endpoint)`),aria:dj.optional().describe(`ARIA accessibility attributes for the application`),protection:uj.optional().describe(`Package author protection block — lock policy for this app.`),...lj})),CN=T({services:w(v()).optional().describe(`Platform services the plugin may resolve (e.g. "object", "http")`),hooks:w(v()).optional().describe(`Lifecycle hooks the plugin may register (e.g. "record.beforeInsert")`),network:w(v()).optional().describe(`Network hosts the plugin may reach (e.g. "api.acme.com")`),fs:w(v()).optional().describe(`Filesystem paths the plugin may access`)}).strict().describe(`Structured plugin permission grants (ADR-0025 §3.2)`),wN=E([w(v()),CN]),TN=T({platform:v().optional().describe(`ObjectStack platform release range (SemVer, e.g. ">=4.0 <5")`),protocol:v().optional().describe(`Runtime/metadata protocol range, checked first (ADR §3.10 #3)`)}).describe(`Plugin compatibility ranges (ADR-0025 §3.2)`),EN=A([`node`,`sandbox`,`worker`]).describe(`Plugin trust tier (ADR-0025 §3.6)`),DN=A([`bundled`,`manifest-deps`]).describe(`Dependency packaging strategy (ADR-0025 §3.3)`),ON=k(v(),v()).describe(`Per-file content digests of the plugin artifact (ADR-0025 §3.2)`),kN=T({id:v().describe(`Unique package identifier (reverse domain style)`),namespace:v().regex(/^[a-z][a-z0-9_]{1,19}$/,`Namespace must be 2-20 chars, lowercase alphanumeric + underscore`).optional().describe(`Short namespace identifier; also the mandatory prefix of every object name (e.g. "todo" → object names "todo_task", "todo_project")`),defaultDatasource:v().optional().default(`default`).describe(`Default datasource for all objects in this package`),version:v().regex(/^\d+\.\d+\.\d+$/).describe(`Package version (semantic versioning)`),type:A([`plugin`,...iN,`module`,`gateway`,`adapter`]).describe(`Type of package`),scope:A([`cloud`,`system`,`project`]).default(`project`).describe(`Deployment scope: cloud | system | project`),name:v().describe(`Human-readable package name`),description:v().optional().describe(`Package description`),permissions:wN.optional().describe(`Required permissions: legacy string[] or structured plugin block (ADR-0025 §3.2)`),objects:w(v()).optional().describe(`Glob patterns for ObjectQL schemas files`),datasources:w(v()).optional().describe(`Glob patterns for Datasource definitions`),dependencies:k(v(),v()).optional().describe(`Package dependencies`),configuration:T({title:v().optional(),properties:k(v(),T({type:A([`string`,`number`,`boolean`,`array`,`object`]).describe(`Data type of the setting`),default:S().optional().describe(`Default value`),description:v().optional().describe(`Tooltip description`),required:b().optional().describe(`Is this setting required?`),secret:b().optional().describe(`If true, value is encrypted/masked (e.g. API Keys)`),enum:w(v()).optional().describe(`Allowed values for select inputs`)})).describe(`Map of configuration keys to their definitions`)}).optional().describe(`Plugin configuration settings`),contributes:T({kinds:w(T({id:v().describe(`The generic identifier of the kind (e.g., "sys.bi.report")`),globs:w(v()).describe(`File patterns to watch (e.g., ["**/*.report.ts"])`),description:v().optional().describe(`Description of what this kind represents`)})).optional().describe(`New Metadata Types to recognize`),events:w(v()).optional().describe(`Events this plugin listens to`),menus:k(v(),w(T({id:v(),label:v(),command:v().optional()}))).optional().describe(`UI Menu contributions`),themes:w(T({id:v(),label:v(),path:v()})).optional().describe(`Theme contributions`),translations:w(T({locale:v(),path:v()})).optional().describe(`Translation resources`),actions:w(T({name:v().describe(`Unique action name`),label:v().optional(),description:v().optional(),input:S().optional().describe(`Input validation schema`),output:S().optional().describe(`Output schema`)})).optional().describe(`Exposed server actions`),drivers:w(T({id:v().describe(`Driver unique identifier (e.g. "postgres", "mongo")`),label:v().describe(`Human readable name`),description:v().optional()})).optional().describe(`Driver contributions`),fieldTypes:w(T({name:v().describe(`Unique field type name (e.g. "vector")`),label:v().describe(`Display label`),description:v().optional()})).optional().describe(`Field Type contributions`),functions:w(T({name:v().describe(`Function name (e.g. "distance")`),description:v().optional(),args:w(v()).optional().describe(`Argument types`),returnType:v().optional()})).optional().describe(`Query Function contributions`),routes:w(T({prefix:v().regex(/^\//).describe(`API path prefix`),service:v().describe(`Service name this plugin provides`),methods:w(v()).optional().describe(`Protocol method names implemented (e.g. ["aiNlq", "aiChat"])`)})).optional().describe(`API route contributions to HttpDispatcher`),commands:w(T({name:v().regex(/^[a-z][a-z0-9-]*$/,`Command name must be lowercase alphanumeric with hyphens`).describe(`CLI command name`),description:v().optional().describe(`Command description for help text`),module:v().optional().describe(`Module path exporting Commander.js commands`)})).optional().describe(`CLI command contributions`)}).optional().describe(`Platform contributions`),data:w(sN).optional().describe(`Initial seed data (prefer top-level data field)`),capabilities:GM.optional().describe(`Plugin capability declarations for interoperability`),extensions:k(v(),S()).optional().describe(`Extension points and contributions`),navigationContributions:w(vN).optional().describe(`Navigation items this package contributes into apps owned by other packages`),loading:nN.optional().describe(`Plugin loading and runtime behavior configuration`),engine:T({objectstack:v().regex(/^[><=~^]*\d+\.\d+\.\d+/).describe(`ObjectStack platform version requirement (SemVer range, e.g. ">=3.0.0")`)}).optional().describe("Platform compatibility requirements (legacy; superseded by `engines`)"),engines:TN.optional().describe("Plugin compatibility ranges (ADR-0025 §3.2; supersedes `engine`)"),runtime:EN.optional().describe(`Plugin trust tier (ADR-0025 §3.6)`),packaging:DN.optional().describe(`Dependency packaging strategy (ADR-0025 §3.3)`),integrity:ON.optional().describe(`Per-file content digests of the plugin artifact (ADR-0025 §3.2)`)}),AN=A([`satisfied`,`needs_install`,`needs_upgrade`,`conflict`]).describe(`Resolution status for a dependency`),jN=W(()=>T({packageId:v().describe(`Dependency package identifier`),requiredRange:v().describe(`SemVer range required (e.g. "^2.0.0")`),resolvedVersion:v().optional().describe(`Actual version resolved from registry`),installedVersion:v().optional().describe(`Currently installed version`),status:AN.describe(`Resolution status`),conflictReason:v().optional().describe(`Explanation of the conflict`)}).describe(`Resolution result for a single dependency`)),MN=W(()=>T({type:A([`install`,`upgrade`,`confirm_conflict`]).describe(`Type of action required`),packageId:v().describe(`Target package identifier`),description:v().describe(`Human-readable action description`)}).describe(`Action required before installation can proceed`)),NN=W(()=>T({dependencies:w(jN).describe(`Resolution result for each dependency`),canProceed:b().describe(`Whether installation can proceed`),requiredActions:w(MN).describe(`Actions required before proceeding`),installOrder:w(v()).describe(`Topologically sorted package IDs for installation`),circularDependencies:w(w(v())).optional().describe(`Circular dependency chains detected (e.g. [["A", "B", "A"]])`)}).describe(`Complete dependency resolution result`)),PN=A([`installed`,`disabled`,`installing`,`upgrading`,`uninstalling`,`error`]).describe(`Package installation status`),FN=W(()=>T({manifest:kN.describe(`Full package manifest`),status:PN.default(`installed`).describe(`Package state: installed, disabled, installing, upgrading, uninstalling, or error`),enabled:b().default(!0).describe(`Whether the package is currently enabled`),installedAt:v().datetime().optional().describe(`Installation timestamp`),updatedAt:v().datetime().optional().describe(`Last update timestamp`),installedVersion:v().optional().describe(`Currently installed version for quick access`),previousVersion:v().optional().describe(`Version before the last upgrade`),statusChangedAt:v().datetime().optional().describe(`Status change timestamp`),errorMessage:v().optional().describe(`Error message when status is error`),settings:k(v(),S()).optional().describe(`User-provided configuration settings`),upgradeHistory:w(T({fromVersion:v().describe(`Version before upgrade`),toVersion:v().describe(`Version after upgrade`),upgradedAt:v().datetime().describe(`Upgrade timestamp`),status:A([`success`,`failed`,`rolled_back`]).describe(`Upgrade outcome`),migrationLog:w(v()).optional().describe(`Migration step logs`)})).optional().describe(`Version upgrade history`),registeredNamespaces:w(v()).optional().describe(`Namespace prefixes registered by this package`)}).describe(`Installed package with runtime lifecycle state`));W(()=>T({namespace:v().describe(`Namespace prefix`),packageId:v().describe(`Owning package ID`),registeredAt:v().datetime().describe(`Registration timestamp`),status:A([`active`,`disabled`,`reserved`]).describe(`Namespace status`)}).describe(`Namespace ownership entry in the registry`)),W(()=>T({type:j(`namespace_conflict`).describe(`Error type`),requestedNamespace:v().describe(`Requested namespace`),conflictingPackageId:v().describe(`Conflicting package ID`),conflictingPackageName:v().describe(`Conflicting package display name`),suggestion:v().optional().describe(`Suggested alternative namespace`)}).describe(`Namespace collision error during installation`)),W(()=>T({status:PN.optional().describe(`Filter by package status`),type:kN.shape.type.optional().describe(`Filter by package type`),enabled:b().optional().describe(`Filter by enabled state`)}).describe(`List packages request`)),W(()=>T({packages:w(FN).describe(`List of installed packages`),total:y().describe(`Total package count`)}).describe(`List packages response`)),W(()=>T({id:v().describe(`Package identifier`)}).describe(`Get package request`)),W(()=>T({package:FN.describe(`Package details`)}).describe(`Get package response`)),W(()=>T({manifest:kN.describe(`Package manifest to install`),settings:k(v(),S()).optional().describe(`User-provided settings at install time`),enableOnInstall:b().default(!0).describe(`Whether to enable immediately after install`),platformVersion:v().optional().describe(`Current platform version for compatibility verification`)}).describe(`Install package request`)),W(()=>T({package:FN.describe(`Installed package details`),message:v().optional().describe(`Installation status message`),dependencyResolution:NN.optional().describe(`Dependency resolution result from install analysis`)}).describe(`Install package response`)),W(()=>T({id:v().describe(`Package ID to uninstall`)}).describe(`Uninstall package request`)),W(()=>T({id:v().describe(`Uninstalled package ID`),success:b().describe(`Whether uninstall succeeded`),message:v().optional().describe(`Uninstall status message`)}).describe(`Uninstall package response`)),W(()=>T({id:v().describe(`Package ID to enable`)}).describe(`Enable package request`)),W(()=>T({package:FN.describe(`Enabled package details`),message:v().optional().describe(`Enable status message`)}).describe(`Enable package response`)),W(()=>T({id:v().describe(`Package ID to disable`)}).describe(`Disable package request`)),W(()=>T({package:FN.describe(`Disabled package details`),message:v().optional().describe(`Disable status message`)}).describe(`Disable package response`)),W(()=>T({trigger:v(),payload:k(v(),S())})),W(()=>T({success:b(),jobId:v().optional(),result:S().optional()})),W(()=>T({actions:w(TM).describe(`Registered action descriptors (built-in + plugin)`),total:y().int().nonnegative().describe(`Number of descriptors returned (after any filters)`)})),W(()=>T({})),W(()=>jk.partial().required({version:!0}).extend({apiName:v().optional().describe(`API name (deprecated — use name)`)})),W(()=>T({})),W(()=>T({types:w(v()).describe(`Available metadata type names (e.g., "object", "plugin", "view")`),entries:w(T({type:v().describe(`Singular type identifier`),label:v().describe(`Human-readable label`),description:v().optional().describe(`Brief description`),filePatterns:w(v()).describe(`Glob patterns used to discover artifacts of this type`),supportsOverlay:b().describe(`Loader can merge per-org overlays on top of artifact`),allowOrgOverride:b().describe(`Per-org overlay writes accepted at runtime (may be env-elevated)`),allowRuntimeCreate:b().describe(`New artifacts of this type can be created via runtime API`),supportsVersioning:b().describe(`History is tracked for this type`),executionPinned:b().describe(`Runtime transactions pin a specific historical version_hash (ADR-0009)`),loadOrder:y().int().describe(`Loading priority (lower = earlier)`),domain:A([`data`,`ui`,`automation`,`system`,`security`,`ai`]).describe(`Protocol domain`),overrideSource:A([`registry`,`env`]).describe(`Whether allowOrgOverride is set in the static registry or via OBJECTSTACK_METADATA_WRITABLE env var`),createSeed:S().optional().describe(`Authoritative minimal valid create seed for this type — Studio/CLI/API derive create defaults from it (single source of truth in @objectstack/spec). Absent for canvas-create types whose shape is built interactively.`)})).optional().describe(`Enriched per-type registry entries (Phase 3a)`)})),W(()=>T({type:v().describe(`Metadata type name (e.g., "object", "plugin")`),packageId:v().optional().describe(`Optional package ID to filter items by`)})),W(()=>T({type:v().describe(`Metadata type name`),items:w(S()).describe(`Array of metadata items`)})),W(()=>T({type:v().describe(`Metadata type name`),name:v().describe(`Item name (snake_case identifier)`),packageId:v().optional().describe(`Optional package ID to filter items by`)})),W(()=>T({type:v().describe(`Metadata type name`),name:v().describe(`Item name`),item:S().describe(`Metadata item definition`)})),W(()=>T({type:v().describe(`Metadata type name`),name:v().describe(`Item name`),item:S().describe(`Metadata item definition`)})),W(()=>T({success:b(),message:v().optional()})),W(()=>T({type:v().describe(`Metadata type name`),name:v().describe(`Item name`)})),W(()=>T({success:b(),reset:b().optional(),message:v().optional()})),W(()=>T({type:v().describe(`Metadata type name`),name:v().describe(`Item name`),cacheRequest:QA.optional().describe(`Cache validation parameters`),locale:v().optional().describe(`Resolved response locale. Folded into the ETag so a language switch never returns a stale-locale 304 — metadata is translated *after* the cache validator check (issue #1319).`)})),W(()=>$A),W(()=>T({object:v().describe(`Object name (snake_case)`),type:A([`list`,`form`]).describe(`View type`)})),W(()=>oM),W(()=>T({object:v().describe(`The unique machine name of the object to query (e.g. "account").`),query:ok.optional().describe(`Structured query definition (filter, sort, select, pagination).`)})),W(()=>T({object:v().describe(`The object name for the returned records.`),records:w(k(v(),S())).describe(`The list of matching records.`),total:y().optional().describe(`Total number of records matching the filter (if requested).`),nextCursor:v().optional().describe(`Cursor for the next page of results (cursor-based pagination).`),hasMore:b().optional().describe(`True if there are more records available (pagination).`)})),W(()=>T({filter:v().optional().describe(`JSON-encoded filter expression (canonical, singular).`),filters:v().optional().describe(`JSON-encoded filter expression (deprecated plural alias).`),select:v().optional().describe(`Comma-separated list of fields to retrieve.`),sort:v().optional().describe(`Sort expression (e.g. "name asc,created_at desc" or "-created_at").`),orderBy:v().optional().describe(`Alias for sort (OData compatibility).`),top:au().optional().describe(`Max records to return (limit).`),skip:au().optional().describe(`Records to skip (offset).`),expand:v().optional().describe(`Comma-separated list of lookup/master_detail field names to expand. Resolved to populate array and passed to the engine for batch $in expansion.`),search:v().optional().describe(`Full-text search query.`),distinct:ou().optional().describe(`SELECT DISTINCT flag.`),count:ou().optional().describe(`Include total count in response.`)})),W(()=>T({object:v().describe(`The object name.`),id:v().describe(`The unique record identifier (primary key).`),select:w(v()).optional().describe(`Fields to include in the response (allowlisted query param).`),expand:w(v()).optional().describe(`Lookup/master_detail field names to expand. The engine resolves these via batch $in queries, replacing foreign key IDs with full objects.`)})),W(()=>T({object:v().describe(`The object name.`),id:v().describe(`The record ID.`),record:k(v(),S()).describe(`The complete record data.`)})),W(()=>T({object:v().describe(`The object name.`),data:k(v(),S()).describe(`The dictionary of field values to insert.`)})),W(()=>T({object:v().describe(`The object name.`),id:v().describe(`The ID of the newly created record.`),record:k(v(),S()).describe(`The created record, including server-generated fields (created_at, owner).`)})),W(()=>T({object:v().describe(`The object name.`),id:v().describe(`The ID of the record to update.`),data:k(v(),S()).describe(`The fields to update (partial update).`),expectedVersion:v().optional().describe("Optimistic concurrency token (typically the `updated_at` value the client read). When provided, the server compares it against the current record version and returns 409 CONCURRENT_UPDATE if they differ. Optional — omit to skip the check.")})),W(()=>T({object:v().describe(`Object name`),id:v().describe(`Updated record ID`),record:k(v(),S()).describe(`Updated record`)})),W(()=>T({object:v().describe(`Object name`),id:v().describe(`Record ID to delete`),expectedVersion:v().optional().describe("Optimistic concurrency token (typically the `updated_at` value the client read). When provided, the server compares it against the current record version and returns 409 CONCURRENT_UPDATE if they differ. Optional — omit to skip the check.")})),W(()=>T({object:v().describe(`Object name`),id:v().describe(`Deleted record ID`),success:b().describe(`Whether deletion succeeded`)})),W(()=>T({object:v().describe(`Object name`),request:KA.describe(`Batch operation request`)})),W(()=>JA),W(()=>T({object:v().describe(`Object name`),records:w(k(v(),S())).describe(`Array of records to create`)})),W(()=>T({object:v().describe(`Object name`),records:w(k(v(),S())).describe(`Created records`),count:y().describe(`Number of records created`)})),W(()=>T({object:v().describe(`Object name`),records:w(T({id:v().describe(`Record ID`),data:k(v(),S()).describe(`Fields to update`)})).describe(`Array of updates`),options:GA.optional().describe(`Update options`)})),W(()=>JA),W(()=>T({object:v().describe(`Object name`),ids:w(v()).describe(`Array of record IDs to delete`),options:GA.optional().describe(`Delete options`)})),W(()=>JA),W(()=>T({object:v().describe(`Object name (snake_case)`),type:A([`list`,`form`]).optional().describe(`Filter by view type`)})),W(()=>T({object:v().describe(`Object name`),views:w(oM).describe(`Array of view definitions`)})),W(()=>T({object:v().describe(`Object name (snake_case)`),viewId:v().describe(`View identifier`)})),W(()=>T({object:v().describe(`Object name`),view:oM.describe(`View definition`)})),W(()=>T({object:v().describe(`Object name (snake_case)`),data:oM.describe(`View definition to create`)})),W(()=>T({object:v().describe(`Object name`),viewId:v().describe(`Created view identifier`),view:oM.describe(`Created view definition`)})),W(()=>T({object:v().describe(`Object name (snake_case)`),viewId:v().describe(`View identifier`),data:oM.partial().describe(`Partial view data to update`)})),W(()=>T({object:v().describe(`Object name`),viewId:v().describe(`Updated view identifier`),view:oM.describe(`Updated view definition`)})),W(()=>T({object:v().describe(`Object name (snake_case)`),viewId:v().describe(`View identifier to delete`)})),W(()=>T({object:v().describe(`Object name`),viewId:v().describe(`Deleted view identifier`),success:b().describe(`Whether deletion succeeded`)})),W(()=>T({object:v().describe(`Object name to check permissions for`),action:A([`create`,`read`,`edit`,`delete`,`transfer`,`restore`,`purge`]).describe(`Action to check`),recordId:v().optional().describe(`Specific record ID (for record-level checks)`),field:v().optional().describe(`Specific field name (for field-level checks)`)})),W(()=>T({allowed:b().describe(`Whether the action is permitted`),reason:v().optional().describe(`Reason if denied`)})),W(()=>T({object:v().describe(`Object name to get permissions for`)})),W(()=>T({object:v().describe(`Object name`),permissions:mM.describe(`Object-level permissions`),fieldPermissions:k(v(),hM).optional().describe(`Field-level permissions keyed by field name`)})),W(()=>T({})),W(()=>T({objects:k(v(),mM).describe(`Effective object permissions keyed by object name`),systemPermissions:w(v()).describe(`Effective system-level permissions`)})),W(()=>T({object:v().describe(`Object name to get workflow config for`)})),W(()=>T({object:v().describe(`Object name`),workflows:w(bM).describe(`Active state-machine workflows for this object`)}));var IN=W(()=>T({currentState:v().describe(`Current workflow state name`),availableTransitions:w(T({name:v().describe(`Transition name`),targetState:v().describe(`Target state after transition`),label:v().optional().describe(`Display label`),requiresApproval:b().default(!1).describe(`Whether transition requires approval`)})).describe(`Available transitions from current state`),history:w(T({fromState:v().describe(`Previous state`),toState:v().describe(`New state`),action:v().describe(`Action that triggered the transition`),userId:v().describe(`User who performed the action`),timestamp:v().datetime().describe(`When the transition occurred`),comment:v().optional().describe(`Optional comment`)})).optional().describe(`State transition history`)}));W(()=>T({object:v().describe(`Object name`),recordId:v().describe(`Record ID to get workflow state for`)})),W(()=>T({object:v().describe(`Object name`),recordId:v().describe(`Record ID`),state:IN.describe(`Current workflow state and available transitions`)})),W(()=>T({object:v().describe(`Object name`),recordId:v().describe(`Record ID`),transition:v().describe(`Transition name to execute`),comment:v().optional().describe(`Optional comment for the transition`),data:k(v(),S()).optional().describe(`Additional data for the transition`)})),W(()=>T({object:v().describe(`Object name`),recordId:v().describe(`Record ID`),success:b().describe(`Whether the transition succeeded`),state:IN.describe(`New workflow state after transition`)})),W(()=>T({transport:Rk.optional().describe(`Preferred transport protocol`),channels:w(v()).optional().describe(`Channels to subscribe to on connect`),token:v().optional().describe(`Authentication token`)})),W(()=>T({connectionId:v().describe(`Unique connection identifier`),transport:Rk.describe(`Negotiated transport protocol`),url:v().optional().describe(`WebSocket/SSE endpoint URL`)})),W(()=>T({connectionId:v().optional().describe(`Connection ID to disconnect`)})),W(()=>T({success:b().describe(`Whether disconnection succeeded`)})),W(()=>T({channel:v().describe(`Channel name to subscribe to`),events:w(v()).optional().describe(`Specific event types to listen for`),filter:k(v(),S()).optional().describe(`Event filter criteria`)})),W(()=>T({subscriptionId:v().describe(`Unique subscription identifier`),channel:v().describe(`Subscribed channel name`)})),W(()=>T({subscriptionId:v().describe(`Subscription ID to cancel`)})),W(()=>T({success:b().describe(`Whether unsubscription succeeded`)})),W(()=>T({channel:v().describe(`Channel to set presence in`),state:Hk.describe(`Presence state to set`)})),W(()=>T({success:b().describe(`Whether presence was set`)})),W(()=>T({channel:v().describe(`Channel to get presence for`)})),W(()=>T({channel:v().describe(`Channel name`),members:w(Hk).describe(`Active members and their presence state`)})),W(()=>T({token:v().describe(`Device push notification token`),platform:A([`ios`,`android`,`web`]).describe(`Device platform`),deviceId:v().optional().describe(`Unique device identifier`),name:v().optional().describe(`Device friendly name`)})),W(()=>T({deviceId:v().describe(`Registered device ID`),success:b().describe(`Whether registration succeeded`)})),W(()=>T({deviceId:v().describe(`Device ID to unregister`)})),W(()=>T({success:b().describe(`Whether unregistration succeeded`)}));var LN=W(()=>T({email:b().default(!0).describe(`Receive email notifications`),push:b().default(!0).describe(`Receive push notifications`),inApp:b().default(!0).describe(`Receive in-app notifications`),digest:A([`none`,`daily`,`weekly`]).default(`none`).describe(`Email digest frequency`),channels:k(v(),T({enabled:b().default(!0).describe(`Whether this channel is enabled`),email:b().optional().describe(`Override email setting`),push:b().optional().describe(`Override push setting`)})).optional().describe(`Per-channel notification preferences`)}));W(()=>T({})),W(()=>T({preferences:LN.describe(`Current notification preferences`)})),W(()=>T({preferences:LN.partial().describe(`Preferences to update`)})),W(()=>T({preferences:LN.describe(`Updated notification preferences`)}));var RN=W(()=>T({id:v().describe(`Notification ID`),type:v().describe(`Notification type`),title:v().describe(`Notification title`),body:v().describe(`Notification body text`),read:b().default(!1).describe(`Whether notification has been read`),data:k(v(),S()).optional().describe(`Additional notification data`),actionUrl:v().optional().describe(`URL to navigate to when clicked`),createdAt:v().datetime().describe(`When notification was created`)}));W(()=>T({read:b().optional().describe(`Filter by read status`),type:v().optional().describe(`Filter by notification type`),limit:y().default(20).describe(`Maximum number of notifications to return`),cursor:v().optional().describe(`Pagination cursor`)})),W(()=>T({notifications:w(RN).describe(`List of notifications`),unreadCount:y().describe(`Total number of unread notifications`),cursor:v().optional().describe(`Next page cursor`)})),W(()=>T({ids:w(v()).describe(`Notification IDs to mark as read`)})),W(()=>T({success:b().describe(`Whether the operation succeeded`),readCount:y().describe(`Number of notifications marked as read`)})),W(()=>T({})),W(()=>T({success:b().describe(`Whether the operation succeeded`),readCount:y().describe(`Number of notifications marked as read`)})),W(()=>T({query:v().describe(`Natural language query string`),object:v().optional().describe(`Target object context`),conversationId:v().optional().describe(`Conversation ID for multi-turn queries`)})),W(()=>T({query:S().describe(`Generated structured query (AST)`),explanation:v().optional().describe(`Human-readable explanation of the query`),confidence:y().min(0).max(1).optional().describe(`Confidence score (0-1)`),suggestions:w(v()).optional().describe(`Suggested follow-up queries`)})),W(()=>T({object:v().describe(`Object name for context`),field:v().optional().describe(`Field to suggest values for`),recordId:v().optional().describe(`Record ID for context`),partial:v().optional().describe(`Partial input for completion`)})),W(()=>T({suggestions:w(T({value:S().describe(`Suggested value`),label:v().describe(`Display label`),confidence:y().min(0).max(1).optional().describe(`Confidence score (0-1)`),reason:v().optional().describe(`Reason for this suggestion`)})).describe(`Suggested values`)})),W(()=>T({object:v().describe(`Object name to analyze`),recordId:v().optional().describe(`Specific record to analyze`),type:A([`summary`,`trends`,`anomalies`,`recommendations`]).optional().describe(`Type of insight`)})),W(()=>T({insights:w(T({type:v().describe(`Insight type`),title:v().describe(`Insight title`),description:v().describe(`Detailed description`),confidence:y().min(0).max(1).optional().describe(`Confidence score (0-1)`),data:k(v(),S()).optional().describe(`Supporting data`)})).describe(`Generated insights`)})),W(()=>T({})),W(()=>T({locales:w(T({code:v().describe(`BCP-47 locale code (e.g., en-US, zh-CN)`),label:v().describe(`Display name of the locale`),isDefault:b().default(!1).describe(`Whether this is the default locale`)})).describe(`Available locales`)})),W(()=>T({locale:v().describe(`BCP-47 locale code`),namespace:v().optional().describe(`Translation namespace (e.g., objects, apps, messages)`),keys:w(v()).optional().describe(`Specific translation keys to fetch`)})),W(()=>T({locale:v().describe(`Locale code`),translations:kM.describe(`Translation data`)})),W(()=>T({object:v().describe(`Object name`),locale:v().describe(`BCP-47 locale code`)})),W(()=>T({object:v().describe(`Object name`),locale:v().describe(`Locale code`),labels:k(v(),T({label:v().describe(`Translated field label`),help:v().optional().describe(`Translated help text`),options:k(v(),v()).optional().describe(`Translated option labels`)})).describe(`Field labels keyed by field name`)})),W(()=>T({getDiscovery:P().describe(`Get API discovery information`),getMetaTypes:P().describe(`Get available metadata types`),getMetaItems:P().describe(`Get all items of a metadata type`),getMetaItem:P().describe(`Get a specific metadata item`),saveMetaItem:P().describe(`Save metadata item`),deleteMetaItem:P().describe(`Delete a customization overlay row (reset to artifact default — ADR-0005)`),getMetaItemCached:P().describe(`Get a metadata item with cache validation`),getUiView:P().describe(`Get UI view definition`),analyticsQuery:P().describe(`Execute analytics query`),getAnalyticsMeta:P().describe(`Get analytics metadata (cubes)`),triggerAutomation:P().describe(`Trigger an automation flow or script`),listPackages:P().describe(`List installed packages with optional filters`),getPackage:P().describe(`Get a specific installed package by ID`),installPackage:P().describe(`Install a new package from manifest`),uninstallPackage:P().describe(`Uninstall a package by ID`),enablePackage:P().describe(`Enable a disabled package`),disablePackage:P().describe(`Disable an installed package`),findData:P().describe(`Find data records`),getData:P().describe(`Get single data record`),createData:P().describe(`Create a data record`),updateData:P().describe(`Update a data record`),deleteData:P().describe(`Delete a data record`),batchData:P().describe(`Perform batch operations`),createManyData:P().describe(`Create multiple records`),updateManyData:P().describe(`Update multiple records`),deleteManyData:P().describe(`Delete multiple records`),listViews:P().describe(`List views for an object`),getView:P().describe(`Get a specific view`),createView:P().describe(`Create a new view`),updateView:P().describe(`Update an existing view`),deleteView:P().describe(`Delete a view`),checkPermission:P().describe(`Check if an action is permitted`),getObjectPermissions:P().describe(`Get permissions for an object`),getEffectivePermissions:P().describe(`Get effective permissions for current user`),getWorkflowConfig:P().describe(`Get workflow configuration for an object`),getWorkflowState:P().describe(`Get workflow state for a record`),workflowTransition:P().describe(`Execute a workflow state transition`),realtimeConnect:P().describe(`Establish realtime connection`),realtimeDisconnect:P().describe(`Close realtime connection`),realtimeSubscribe:P().describe(`Subscribe to a realtime channel`),realtimeUnsubscribe:P().describe(`Unsubscribe from a realtime channel`),setPresence:P().describe(`Set user presence state`),getPresence:P().describe(`Get channel presence information`),registerDevice:P().describe(`Register a device for push notifications`),unregisterDevice:P().describe(`Unregister a device`),getNotificationPreferences:P().describe(`Get notification preferences`),updateNotificationPreferences:P().describe(`Update notification preferences`),listNotifications:P().describe(`List notifications`),markNotificationsRead:P().describe(`Mark specific notifications as read`),markAllNotificationsRead:P().describe(`Mark all notifications as read`),aiNlq:P().describe(`Natural language query`),aiChat:P().describe(`AI chat interaction`),aiSuggest:P().describe(`Get AI-powered suggestions`),aiInsights:P().describe(`Get AI-generated insights`),getLocales:P().describe(`Get available locales`),getTranslations:P().describe(`Get translations for a locale`),getFieldLabels:P().describe(`Get translated field labels for an object`),listFeed:P().describe(`List feed items for a record`),createFeedItem:P().describe(`Create a new feed item`),updateFeedItem:P().describe(`Update an existing feed item`),deleteFeedItem:P().describe(`Delete a feed item`),addReaction:P().describe(`Add an emoji reaction to a feed item`),removeReaction:P().describe(`Remove an emoji reaction from a feed item`),pinFeedItem:P().describe(`Pin a feed item`),unpinFeedItem:P().describe(`Unpin a feed item`),starFeedItem:P().describe(`Star a feed item`),unstarFeedItem:P().describe(`Unstar a feed item`),searchFeed:P().describe(`Search feed items`),getChangelog:P().describe(`Get field-level changelog for a record`),feedSubscribe:P().describe(`Subscribe to record notifications`),feedUnsubscribe:P().describe(`Unsubscribe from record notifications`)}));var zN=W(()=>T({version:v().regex(/^[a-zA-Z0-9_\-\.]+$/).default(`v1`).describe(`API version (e.g., v1, v2, 2024-01)`),basePath:v().default(`/api`).describe(`Base URL path for API`),apiPath:v().optional().describe(`Full API path (defaults to {basePath}/{version})`),enableCrud:b().default(!0).describe(`Enable automatic CRUD endpoint generation`),enableMetadata:b().default(!0).describe(`Enable metadata API endpoints`),enableUi:b().default(!0).describe(`Enable UI API endpoints (Views, Menus, Layouts)`),enableBatch:b().default(!0).describe(`Enable batch operation endpoints`),enableDiscovery:b().default(!0).describe(`Enable API discovery endpoint`),enableOpenApi:b().default(!0).describe(`Enable OpenAPI 3.1 spec & docs viewer endpoints`),enableProjectScoping:b().default(!1).describe(`Enable project-scoped routing for data/meta/AI APIs`),projectResolution:A([`required`,`optional`,`auto`]).default(`auto`).describe(`Project ID resolution strategy`),requireAuth:b().default(!1).describe(`Reject anonymous requests on /data/* with HTTP 401`),documentation:T({enabled:b().default(!0).describe(`Enable API documentation`),title:v().default(`ObjectStack API`).describe(`API documentation title`),description:v().optional().describe(`API description`),version:v().optional().describe(`Documentation version`),termsOfService:v().optional().describe(`Terms of service URL`),contact:T({name:v().optional(),url:v().optional(),email:v().optional()}).optional(),license:T({name:v(),url:v().optional()}).optional()}).optional().describe(`OpenAPI/Swagger documentation config`),responseFormat:T({envelope:b().default(!0).describe(`Wrap responses in standard envelope`),includeMetadata:b().default(!0).describe(`Include response metadata (timestamp, requestId)`),includePagination:b().default(!0).describe(`Include pagination info in list responses`)}).optional().describe(`Response format options`)})),BN=A([`create`,`read`,`update`,`delete`,`list`]),VN=W(()=>T({method:bk.describe(`HTTP method`),path:v().describe(`URL path pattern`),summary:v().optional().describe(`Operation summary`),description:v().optional().describe(`Operation description`)})),HN=W(()=>T({operations:T({create:b().default(!0).describe(`Enable create operation`),read:b().default(!0).describe(`Enable read operation`),update:b().default(!0).describe(`Enable update operation`),delete:b().default(!0).describe(`Enable delete operation`),list:b().default(!0).describe(`Enable list operation`)}).optional().describe(`Enable/disable operations`),patterns:k(BN,VN.optional()).optional().describe(`Custom URL patterns for operations`),dataPrefix:v().default(`/data`).describe(`URL prefix for data endpoints`),objectParamStyle:A([`path`,`query`]).default(`path`).describe(`How object name is passed (path param or query param)`)})),UN=W(()=>T({prefix:v().default(`/meta`).describe(`URL prefix for metadata endpoints`),enableCache:b().default(!0).describe(`Enable HTTP cache headers (ETag, Last-Modified)`),cacheTtl:y().int().default(3600).describe(`Cache TTL in seconds`),endpoints:T({types:b().default(!0).describe(`GET /meta - List all metadata types`),items:b().default(!0).describe(`GET /meta/:type - List items of type`),item:b().default(!0).describe(`GET /meta/:type/:name - Get specific item`),schema:b().default(!0).describe(`GET /meta/:type/:name/schema - Get JSON schema`)}).optional().describe(`Enable/disable specific endpoints`)})),WN=W(()=>T({maxBatchSize:y().int().min(1).max(1e3).default(200).describe(`Maximum records per batch operation`),enableBatchEndpoint:b().default(!0).describe(`Enable POST /data/:object/batch endpoint`),operations:T({createMany:b().default(!0).describe(`Enable POST /data/:object/createMany`),updateMany:b().default(!0).describe(`Enable POST /data/:object/updateMany`),deleteMany:b().default(!0).describe(`Enable POST /data/:object/deleteMany`),upsertMany:b().default(!0).describe(`Enable POST /data/:object/upsertMany`)}).optional().describe(`Enable/disable specific batch operations`),defaultAtomic:b().default(!0).describe(`Default atomic/transaction mode for batch operations`)})),GN=W(()=>T({includeObjects:w(v()).optional().describe(`Specific objects to generate routes for (empty = all)`),excludeObjects:w(v()).optional().describe(`Objects to exclude from route generation`),nameTransform:A([`none`,`plural`,`kebab-case`,`camelCase`]).default(`none`).describe(`Transform object names in URLs`),overrides:k(v(),T({enabled:b().optional().describe(`Enable/disable routes for this object`),basePath:v().optional().describe(`Custom base path`),operations:k(BN,b()).optional().describe(`Enable/disable specific operations`)})).optional().describe(`Per-object route customization`)})),KN=W(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Webhook event identifier (snake_case)`),description:v().describe(`Human-readable event description`),method:bk.default(`POST`).describe(`HTTP method for webhook delivery`),payloadSchema:v().describe(`JSON Schema $ref for the webhook payload`),headers:k(v(),v()).optional().describe(`Custom headers to include in webhook delivery`),security:w(A([`hmac_sha256`,`basic`,`bearer`,`api_key`])).describe(`Supported authentication methods for webhook verification`)}));W(()=>T({enabled:b().default(!1).describe(`Enable webhook support`),events:w(KN).describe(`Registered webhook events`),deliveryConfig:T({maxRetries:y().int().default(3).describe(`Maximum delivery retry attempts`),retryIntervalMs:y().int().default(5e3).describe(`Milliseconds between retry attempts`),timeoutMs:y().int().default(3e4).describe(`Delivery request timeout in milliseconds`),signatureHeader:v().default(`X-Signature-256`).describe(`Header name for webhook signature`)}).describe(`Webhook delivery configuration`),registrationEndpoint:v().default(`/webhooks`).describe(`URL path for webhook registration`)}));var qN=W(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Callback identifier (snake_case)`),expression:v().describe(`Runtime expression (e.g., {$request.body#/callbackUrl})`),method:bk.describe(`HTTP method for callback request`),url:v().describe(`Callback URL template with runtime expressions`)})),JN=W(()=>T({webhooks:k(v(),KN).optional().describe(`OpenAPI 3.1 webhooks (top-level webhook definitions)`),callbacks:k(v(),w(qN)).optional().describe(`OpenAPI 3.1 callbacks (async response definitions)`),jsonSchemaDialect:v().default(`https://json-schema.org/draft/2020-12/schema`).describe(`JSON Schema dialect for schema definitions`),pathItemReferences:b().default(!1).describe(`Allow $ref in path items (OpenAPI 3.1 feature)`)})),YN=W(()=>T({api:zN.optional().describe(`REST API configuration`),crud:HN.optional().describe(`CRUD endpoints configuration`),metadata:UN.optional().describe(`Metadata endpoints configuration`),batch:WN.optional().describe(`Batch endpoints configuration`),routes:GN.optional().describe(`Route generation configuration`),openApi31:JN.optional().describe(`OpenAPI 3.1 extensions configuration`)})),XN=W(()=>T({id:v().describe(`Unique endpoint identifier`),method:bk.describe(`HTTP method`),path:v().describe(`Full URL path`),object:v().describe(`Object name (snake_case)`),operation:E([BN,v()]).describe(`Operation type`),handler:v().describe(`Handler function identifier`),metadata:T({summary:v().optional(),description:v().optional(),tags:w(v()).optional(),deprecated:b().optional()}).optional()}));W(()=>T({endpoints:w(XN).describe(`All generated endpoints`),total:y().int().describe(`Total number of endpoints`),byObject:k(v(),w(XN)).optional().describe(`Endpoints grouped by object`),byOperation:k(v(),w(XN)).optional().describe(`Endpoints grouped by operation`)})),Object.assign(zN,{create:e=>e}),Object.assign(YN,{create:e=>e});var ZN=A([`rest`,`graphql`,`odata`,`websocket`,`file`,`auth`,`metadata`,`plugin`,`webhook`,`rpc`]),QN=E([y().int().min(100).max(599),A([`2xx`,`3xx`,`4xx`,`5xx`])]),$N=W(()=>T({objectId:Wk.describe(`Object name to reference`),includeFields:w(v()).optional().describe(`Include only these fields in the schema`),excludeFields:w(v()).optional().describe(`Exclude these fields from the schema`),includeRelated:w(v()).optional().describe(`Include related objects via lookup fields`)}));E([S().describe(`Static JSON Schema definition`),T({$ref:$N.describe(`Dynamic reference to ObjectQL object`)}).describe(`Dynamic ObjectQL reference`)]);var eP=W(()=>T({name:v().describe(`Parameter name`),in:A([`path`,`query`,`header`,`body`,`cookie`]).describe(`Parameter location`),description:v().optional().describe(`Parameter description`),required:b().default(!1).describe(`Whether parameter is required`),schema:E([T({type:A([`string`,`number`,`integer`,`boolean`,`array`,`object`]).describe(`Parameter type`),format:v().optional().describe(`Format (e.g., date-time, email, uuid)`),enum:w(S()).optional().describe(`Allowed values`),default:S().optional().describe(`Default value`),items:S().optional().describe(`Array item schema`),properties:k(v(),S()).optional().describe(`Object properties`)}).describe(`Static JSON Schema`),T({$ref:$N}).describe(`Dynamic ObjectQL reference`)]).describe(`Parameter schema definition`),example:S().optional().describe(`Example value`)})),tP=W(()=>T({statusCode:QN.describe(`HTTP status code`),description:v().describe(`Response description`),contentType:v().default(`application/json`).describe(`Response content type`),schema:E([S().describe(`Static JSON Schema`),T({$ref:$N}).describe(`Dynamic ObjectQL reference`)]).optional().describe(`Response body schema`),headers:k(v(),T({description:v().optional(),schema:S()})).optional().describe(`Response headers`),example:S().optional().describe(`Example response`)})),nP=W(()=>T({id:v().describe(`Unique endpoint identifier`),method:bk.optional().describe(`HTTP method`),path:v().describe(`URL path pattern`),summary:v().optional().describe(`Short endpoint summary`),description:v().optional().describe(`Detailed endpoint description`),operationId:v().optional().describe(`Unique operation identifier`),tags:w(v()).optional().default([]).describe(`Tags for categorization`),parameters:w(eP).optional().default([]).describe(`Endpoint parameters`),requestBody:T({description:v().optional(),required:b().default(!1),contentType:v().default(`application/json`),schema:S().optional(),example:S().optional()}).optional().describe(`Request body specification`),responses:w(tP).optional().default([]).describe(`Possible responses`),rateLimit:wk.optional().describe(`Endpoint specific rate limiting`),security:w(k(v(),w(v()))).optional().describe(`Security requirements (e.g. [{"bearerAuth": []}])`),requiredPermissions:w(v()).optional().default([]).describe(`Required RBAC permissions (e.g., "customer.read", "manage_users")`),priority:y().int().min(0).max(1e3).optional().default(100).describe(`Route priority for conflict resolution (0-1000, higher = more important)`),protocolConfig:k(v(),S()).optional().describe(`Protocol-specific configuration for custom protocols (gRPC, tRPC, etc.)`),deprecated:b().default(!1).describe(`Whether endpoint is deprecated`),externalDocs:T({description:v().optional(),url:v().url()}).optional().describe(`External documentation link`)})),rP=W(()=>T({owner:v().optional().describe(`Owner team or person`),status:A([`active`,`deprecated`,`experimental`,`beta`]).default(`active`).describe(`API lifecycle status`),tags:w(v()).optional().default([]).describe(`Classification tags`),pluginSource:v().optional().describe(`Source plugin name`),custom:k(v(),S()).optional().describe(`Custom metadata fields`)})),iP=W(()=>T({id:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Unique API identifier (snake_case)`),name:v().describe(`API display name`),type:ZN.describe(`API protocol type`),version:v().describe(`API version (e.g., v1, 2024-01)`),basePath:v().describe(`Base URL path for this API`),description:v().optional().describe(`API description`),endpoints:w(nP).describe(`Registered endpoints`),config:k(v(),S()).optional().describe(`Protocol-specific configuration`),metadata:rP.optional().describe(`Additional metadata`),termsOfService:v().url().optional().describe(`Terms of service URL`),contact:T({name:v().optional(),url:v().url().optional(),email:v().email().optional()}).optional().describe(`Contact information`),license:T({name:v(),url:v().url().optional()}).optional().describe(`License information`)})),aP=A([`error`,`priority`,`first-wins`,`last-wins`]),oP=W(()=>T({version:v().describe(`Registry version`),conflictResolution:aP.optional().default(`error`).describe(`Strategy for handling route conflicts`),apis:w(iP).describe(`All registered APIs`),totalApis:y().int().describe(`Total number of registered APIs`),totalEndpoints:y().int().describe(`Total number of endpoints`),byType:k(ZN,w(iP)).optional().describe(`APIs grouped by protocol type`),byStatus:k(v(),w(iP)).optional().describe(`APIs grouped by status`),updatedAt:v().datetime().optional().describe(`Last registry update time`)})),sP=W(()=>T({type:ZN.optional().describe(`Filter by API protocol type`),tags:w(v()).optional().describe(`Filter by tags (ANY match)`),status:A([`active`,`deprecated`,`experimental`,`beta`]).optional().describe(`Filter by lifecycle status`),pluginSource:v().optional().describe(`Filter by plugin name`),search:v().optional().describe(`Full-text search in name/description`),version:v().optional().describe(`Filter by specific version`)}));W(()=>T({apis:w(iP).describe(`Matching API entries`),total:y().int().describe(`Total matching APIs`),filters:sP.optional().describe(`Applied query filters`)})),Object.assign(nP,{create:e=>e}),Object.assign(iP,{create:e=>e}),Object.assign(oP,{create:e=>e});var cP=W(()=>T({url:v().url().describe(`Server base URL`),description:v().optional().describe(`Server description`),variables:k(v(),T({default:v(),description:v().optional(),enum:w(v()).optional()})).optional().describe(`URL template variables`)})),lP=W(()=>T({type:A([`apiKey`,`http`,`oauth2`,`openIdConnect`]).describe(`Security type`),scheme:v().optional().describe(`HTTP auth scheme (bearer, basic, etc.)`),bearerFormat:v().optional().describe(`Bearer token format (e.g., JWT)`),name:v().optional().describe(`API key parameter name`),in:A([`header`,`query`,`cookie`]).optional().describe(`API key location`),flows:T({implicit:S().optional(),password:S().optional(),clientCredentials:S().optional(),authorizationCode:S().optional()}).optional().describe(`OAuth2 flows`),openIdConnectUrl:v().url().optional().describe(`OpenID Connect discovery URL`),description:v().optional().describe(`Security scheme description`)})),uP=W(()=>T({openapi:v().default(`3.0.0`).describe(`OpenAPI specification version`),info:T({title:v().describe(`API title`),version:v().describe(`API version`),description:v().optional().describe(`API description`),termsOfService:v().url().optional().describe(`Terms of service URL`),contact:T({name:v().optional(),url:v().url().optional(),email:v().email().optional()}).optional(),license:T({name:v(),url:v().url().optional()}).optional()}).describe(`API metadata`),servers:w(cP).optional().default([]).describe(`API servers`),paths:k(v(),S()).describe(`API paths and operations`),components:T({schemas:k(v(),S()).optional(),responses:k(v(),S()).optional(),parameters:k(v(),S()).optional(),examples:k(v(),S()).optional(),requestBodies:k(v(),S()).optional(),headers:k(v(),S()).optional(),securitySchemes:k(v(),lP).optional(),links:k(v(),S()).optional(),callbacks:k(v(),S()).optional()}).optional().describe(`Reusable components`),security:w(k(v(),w(v()))).optional().describe(`Global security requirements`),tags:w(T({name:v(),description:v().optional(),externalDocs:T({description:v().optional(),url:v().url()}).optional()})).optional().describe(`Tag definitions`),externalDocs:T({description:v().optional(),url:v().url()}).optional().describe(`External documentation`)})),dP=A([`swagger-ui`,`redoc`,`rapidoc`,`stoplight`,`scalar`,`graphql-playground`,`graphiql`,`postman`,`custom`]),fP=W(()=>T({type:dP.describe(`Testing UI implementation`),path:v().default(`/api-docs`).describe(`URL path for documentation UI`),theme:A([`light`,`dark`,`auto`]).default(`light`).describe(`UI color theme`),enableTryItOut:b().default(!0).describe(`Enable interactive API testing`),enableFilter:b().default(!0).describe(`Enable endpoint filtering`),enableCors:b().default(!0).describe(`Enable CORS for browser testing`),defaultModelsExpandDepth:y().int().min(-1).default(1).describe(`Default expand depth for schemas (-1 = fully expand)`),displayRequestDuration:b().default(!0).describe(`Show request duration`),syntaxHighlighting:b().default(!0).describe(`Enable syntax highlighting`),customCssUrl:v().url().optional().describe(`Custom CSS stylesheet URL`),customJsUrl:v().url().optional().describe(`Custom JavaScript URL`),layout:T({showExtensions:b().default(!1).describe(`Show vendor extensions`),showCommonExtensions:b().default(!1).describe(`Show common extensions`),deepLinking:b().default(!0).describe(`Enable deep linking`),displayOperationId:b().default(!1).describe(`Display operation IDs`),defaultModelRendering:A([`example`,`model`]).default(`example`).describe(`Default model rendering mode`),defaultModelsExpandDepth:y().int().default(1).describe(`Models expand depth`),defaultModelExpandDepth:y().int().default(1).describe(`Single model expand depth`),docExpansion:A([`list`,`full`,`none`]).default(`list`).describe(`Documentation expansion mode`)}).optional().describe(`Layout configuration`)})),pP=W(()=>T({name:v().describe(`Test request name`),description:v().optional().describe(`Request description`),method:A([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`,`HEAD`,`OPTIONS`]).describe(`HTTP method`),url:v().describe(`Request URL (can include variables)`),headers:k(v(),v()).optional().default({}).describe(`Request headers`),queryParams:k(v(),E([v(),y(),b()])).optional().default({}).describe(`Query parameters`),body:S().optional().describe(`Request body`),variables:k(v(),S()).optional().default({}).describe(`Template variables`),expectedResponse:T({statusCode:y().int(),body:S().optional()}).optional().describe(`Expected response for validation`)})),mP=W(()=>T({name:v().describe(`Collection name`),description:v().optional().describe(`Collection description`),variables:k(v(),S()).optional().default({}).describe(`Shared variables`),requests:w(pP).describe(`Test requests in this collection`),folders:w(T({name:v(),description:v().optional(),requests:w(pP)})).optional().describe(`Request folders for organization`)})),hP=W(()=>T({version:v().describe(`API version`),date:v().date().describe(`Release date`),changes:T({added:w(v()).optional().default([]).describe(`New features`),changed:w(v()).optional().default([]).describe(`Changes`),deprecated:w(v()).optional().default([]).describe(`Deprecations`),removed:w(v()).optional().default([]).describe(`Removed features`),fixed:w(v()).optional().default([]).describe(`Bug fixes`),security:w(v()).optional().default([]).describe(`Security fixes`)}).describe(`Version changes`),migrationGuide:v().optional().describe(`Migration guide URL or text`)})),gP=W(()=>T({language:v().describe(`Target language/framework (e.g., typescript, python, curl)`),name:v().describe(`Template name`),template:v().describe(`Code template with placeholders`),variables:w(v()).optional().describe(`Required template variables`)})),_P=W(()=>T({enabled:b().default(!0).describe(`Enable API documentation`),title:v().default(`API Documentation`).describe(`Documentation title`),version:v().describe(`API version`),description:v().optional().describe(`API description`),servers:w(cP).optional().default([]).describe(`API server URLs`),ui:fP.optional().describe(`Testing UI configuration`),generateOpenApi:b().default(!0).describe(`Generate OpenAPI 3.0 specification`),generateTestCollections:b().default(!0).describe(`Generate API test collections`),testCollections:w(mP).optional().default([]).describe(`Predefined test collections`),changelog:w(hP).optional().default([]).describe(`API version changelog`),codeTemplates:w(gP).optional().default([]).describe(`Code generation templates`),termsOfService:v().url().optional().describe(`Terms of service URL`),contact:T({name:v().optional(),url:v().url().optional(),email:v().email().optional()}).optional().describe(`Contact information`),license:T({name:v(),url:v().url().optional()}).optional().describe(`API license`),externalDocs:T({description:v().optional(),url:v().url()}).optional().describe(`External documentation link`),securitySchemes:k(v(),lP).optional().describe(`Security scheme definitions`),tags:w(T({name:v(),description:v().optional(),externalDocs:T({description:v().optional(),url:v().url()}).optional()})).optional().describe(`Global tag definitions`)}));W(()=>T({openApiSpec:uP.optional().describe(`Generated OpenAPI specification`),testCollections:w(mP).optional().describe(`Generated test collections`),markdown:v().optional().describe(`Generated markdown documentation`),html:v().optional().describe(`Generated HTML documentation`),generatedAt:v().datetime().describe(`Generation timestamp`),sourceApis:w(v()).describe(`Source API IDs used for generation`)})),Object.assign(_P,{create:e=>e}),Object.assign(mP,{create:e=>e}),Object.assign(uP,{create:e=>e});var vP=A([`count`,`sum`,`avg`,`min`,`max`,`count_distinct`,`number`,`string`,`boolean`]),yP=A([`string`,`number`,`boolean`,`time`,`geo`]),bP=A([`second`,`minute`,`hour`,`day`,`week`,`month`,`quarter`,`year`]),xP=W(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Unique metric ID`),label:v().describe(`Human readable label`),description:v().optional(),type:vP,sql:v().describe(`SQL expression or field reference`),filters:w(T({sql:v()})).optional(),format:v().optional()})),SP=W(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Unique dimension ID`),label:v().describe(`Human readable label`),description:v().optional(),type:yP,sql:v().describe(`SQL expression or column reference`),granularities:w(bP).optional()})),CP=W(()=>T({name:v().describe(`Target cube name`),relationship:A([`one_to_one`,`one_to_many`,`many_to_one`]).default(`many_to_one`),sql:v().describe(`Join condition (ON clause)`)})),wP=W(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Cube name (snake_case)`),title:v().optional(),description:v().optional(),sql:v().describe(`Base SQL statement or Table Name`),measures:k(v(),xP).describe(`Quantitative metrics`),dimensions:k(v(),SP).describe(`Qualitative attributes`),joins:k(v(),CP).optional(),refreshKey:T({every:v().optional(),sql:v().optional()}).optional(),public:b().default(!1)})),TP=W(()=>T({cube:v().optional().describe(`Target cube name (optional when provided externally, e.g. in API request wrapper)`),measures:w(v()).describe(`List of metrics to calculate`),dimensions:w(v()).optional().describe(`List of dimensions to group by`),where:WO.optional().describe(`Filtering criteria (canonical Query DSL FilterCondition)`),timeDimensions:w(T({dimension:v(),granularity:bP.optional(),dateRange:E([v(),w(v())]).optional()})).optional(),order:k(v(),A([`asc`,`desc`])).optional(),limit:y().optional(),offset:y().optional(),timezone:v().optional().default(`UTC`)}));A([`/api/v1/analytics/query`,`/api/v1/analytics/meta`,`/api/v1/analytics/sql`]),W(()=>T({query:TP.describe(`The analytic query definition`),cube:v().describe(`Target cube name`),format:A([`json`,`csv`,`xlsx`]).default(`json`).describe(`Response format`)})),W(()=>G.extend({data:T({rows:w(k(v(),S())).describe(`Result rows`),fields:w(T({name:v(),type:v()})).describe(`Column metadata`),sql:v().optional().describe(`Executed SQL (if debug enabled)`)})})),W(()=>T({cube:v().optional().describe(`Optional cube name to filter`)})),W(()=>G.extend({data:T({cubes:w(wP).describe(`Available cubes`)})})),W(()=>G.extend({data:T({sql:v(),params:w(S())})}));var EP=A([`urlPath`,`header`,`queryParam`,`dateBased`]),DP=A([`preview`,`current`,`supported`,`deprecated`,`retired`]),OP=W(()=>T({version:v().describe(`Version identifier (e.g., "v1", "v2beta1", "2025-01-01")`),status:DP.describe(`Lifecycle status of this version`),releasedAt:v().describe(`Release date (ISO 8601, e.g., "2025-01-15")`),deprecatedAt:v().optional().describe(`Deprecation date (ISO 8601). Only set for deprecated/retired versions`),sunsetAt:v().optional().describe(`Sunset date (ISO 8601). After this date, the version returns 410 Gone`),migrationGuide:v().url().optional().describe(`URL to migration guide for upgrading from this version`),description:v().optional().describe(`Human-readable description or release notes summary`),breakingChanges:w(v()).optional().describe(`List of breaking changes (for preview/new versions)`)}));W(()=>T({strategy:EP.default(`urlPath`).describe(`How the API version is specified by clients`),current:v().describe(`The current/recommended API version identifier`),default:v().describe(`Fallback version when client does not specify one`),versions:w(OP).min(1).describe(`All available API versions with lifecycle metadata`),headerName:v().default(`ObjectStack-Version`).describe(`HTTP header name for version negotiation (header/dateBased strategies)`),queryParamName:v().default(`version`).describe(`Query parameter name for version specification (queryParam strategy)`),urlPrefix:v().default(`/api`).describe(`URL prefix before version segment (urlPath strategy)`),deprecation:T({warnHeader:b().default(!0).describe(`Include Deprecation header (RFC 8594) in responses`),sunsetHeader:b().default(!0).describe(`Include Sunset header (RFC 8594) with retirement date`),linkHeader:b().default(!0).describe(`Include Link header pointing to migration guide URL`),rejectRetired:b().default(!0).describe(`Return 410 Gone for retired API versions`),warningMessage:v().optional().describe(`Custom warning message for deprecated version responses`)}).optional().describe(`Deprecation lifecycle behavior`),includeInDiscovery:b().default(!0).describe(`Include version information in the API discovery endpoint`)})),W(()=>T({current:v().describe(`Current recommended API version`),requested:v().optional().describe(`Version requested by the client`),resolved:v().describe(`Resolved API version for this request`),supported:w(v()).describe(`All supported version identifiers`),deprecated:w(v()).optional().describe(`Deprecated version identifiers`),versions:w(OP).optional().describe(`Full version definitions with lifecycle metadata`)})),A([`local`,`google`,`github`,`microsoft`,`ldap`,`saml`]);var kP=W(()=>T({id:v().describe(`User ID`),email:v().email().describe(`Email address`),emailVerified:b().default(!1).describe(`Is email verified?`),name:v().describe(`Display name`),image:v().optional().describe(`Avatar URL`),username:v().optional().describe(`Username (optional)`),roles:w(v()).optional().default([]).describe(`Assigned role IDs`),tenantId:v().optional().describe(`Current tenant ID`),language:v().default(`en`).describe(`Preferred language`),timezone:v().optional().describe(`Preferred timezone`),createdAt:v().datetime().optional(),updatedAt:v().datetime().optional()})),AP=W(()=>T({id:v(),expiresAt:v().datetime(),token:v().optional(),ipAddress:v().optional(),userAgent:v().optional(),userId:v()})),jP=A([`email`,`username`,`phone`,`magic-link`,`social`]);W(()=>T({type:jP.default(`email`).describe(`Login method`),email:v().email().optional().describe(`Required for email/magic-link`),username:v().optional().describe(`Required for username login`),password:v().optional().describe(`Required for password login`),provider:v().optional().describe(`Required for social (google, github)`),redirectTo:v().optional().describe(`Redirect URL after successful login`)})),W(()=>T({email:v().email(),password:v(),name:v(),image:v().optional()})),W(()=>T({refreshToken:v().describe(`Refresh token`)})),W(()=>G.extend({data:T({session:AP.describe(`Active Session Info`),user:kP.describe(`Current User Details`),token:v().optional().describe(`Bearer token if not using cookies`)})})),W(()=>G.extend({data:kP}));var MP={signInEmail:`/sign-in/email`,signUpEmail:`/sign-up/email`,signOut:`/sign-out`,getSession:`/get-session`,forgetPassword:`/forget-password`,resetPassword:`/reset-password`,sendVerificationEmail:`/send-verification-email`,verifyEmail:`/verify-email`,twoFactorEnable:`/two-factor/enable`,twoFactorVerify:`/two-factor/verify`,passkeyRegister:`/passkey/register`,passkeyAuthenticate:`/passkey/authenticate`,magicLinkSend:`/magic-link/send`,magicLinkVerify:`/magic-link/verify`,deviceRequest:`/device/request`,deviceToken:`/device/token`,deviceApprove:`/device/approve`};W(()=>T({signInEmail:T({method:j(`POST`),path:j(MP.signInEmail),description:j(`Sign in with email and password`)}),signUpEmail:T({method:j(`POST`),path:j(MP.signUpEmail),description:j(`Register new user with email and password`)}),signOut:T({method:j(`POST`),path:j(MP.signOut),description:j(`Sign out current user`)}),getSession:T({method:j(`GET`),path:j(MP.getSession),description:j(`Get current user session`)}),forgetPassword:T({method:j(`POST`),path:j(MP.forgetPassword),description:j(`Request password reset email`)}),resetPassword:T({method:j(`POST`),path:j(MP.resetPassword),description:j(`Reset password with token`)}),sendVerificationEmail:T({method:j(`POST`),path:j(MP.sendVerificationEmail),description:j(`Send email verification link`)}),verifyEmail:T({method:j(`GET`),path:j(MP.verifyEmail),description:j(`Verify email with token`)})})),MP.signInEmail,MP.signUpEmail,MP.signOut,MP.getSession,MP.signInEmail,MP.signUpEmail,MP.signOut,MP.getSession,MP.getSession;var NP=W(()=>T({id:v().describe(`Provider ID (e.g., google, github, microsoft, okta)`),name:v().describe(`Display name (e.g., Google, GitHub)`),enabled:b().describe(`Whether this provider is enabled`),type:A([`social`,`oidc`]).default(`social`).describe(`Provider type`)})),PP=W(()=>T({enabled:b().describe(`Whether email/password auth is enabled`),disableSignUp:b().optional().describe(`Whether new user registration is disabled`),requireEmailVerification:b().optional().describe(`Whether email verification is required`)})),FP=W(()=>T({twoFactor:b().default(!1).describe(`Two-factor authentication enabled`),passkeys:b().default(!1).describe(`Passkey/WebAuthn support enabled`),magicLink:b().default(!1).describe(`Magic link login enabled`),organization:b().default(!1).describe(`Multi-tenant organization support enabled`),ssoEnforced:b().optional().describe(`SSO-only login enforced: the UI hides the local password form + self-registration (a break-glass "use a password" link remains)`)}));W(()=>T({emailPassword:PP.describe(`Email/password authentication config`),socialProviders:w(NP).describe(`Available social/OAuth providers`),features:FP.describe(`Enabled authentication features`)})),W(()=>T({code:v().describe(`Short-lived device code used for polling`),verificationUrl:v().url().describe(`URL the user should open in a browser`),expiresAt:v().datetime().describe(`ISO timestamp when the code expires`),interval:y().default(2).describe(`Recommended polling interval in seconds`)})),W(()=>D(`status`,[T({status:j(`pending`)}),T({status:j(`approved`),token:v().describe(`Bearer token to store in credentials file`),user:T({id:v(),email:v(),name:v().optional()})}),T({status:j(`expired`)})]));var IP=W(()=>A([`global`,`tenant`,`user`,`session`,`temp`,`cache`,`data`,`logs`,`config`,`public`]).describe(`Storage scope classification`)),LP=W(()=>T({path:v().describe(`File path`),name:v().describe(`File name`),size:y().int().describe(`File size in bytes`),mimeType:v().describe(`MIME type`),lastModified:v().datetime().describe(`Last modified timestamp`),created:v().datetime().describe(`Creation timestamp`),etag:v().optional().describe(`Entity tag`)})),RP=W(()=>A([`s3`,`azure_blob`,`gcs`,`minio`,`r2`,`spaces`,`wasabi`,`backblaze`,`local`]).describe(`Storage provider type`)),zP=W(()=>A([`private`,`public_read`,`public_read_write`,`authenticated_read`,`bucket_owner_read`,`bucket_owner_full_control`]).describe(`Storage access control level`)),BP=W(()=>A([`standard`,`intelligent`,`infrequent_access`,`glacier`,`deep_archive`]).describe(`Storage class/tier for cost optimization`)),VP=W(()=>A([`transition`,`delete`,`abort`]).describe(`Lifecycle policy action type`));W(()=>T({contentType:v().describe(`MIME type (e.g., image/jpeg, application/pdf)`),contentLength:y().min(0).describe(`File size in bytes`),contentEncoding:v().optional().describe(`Content encoding (e.g., gzip)`),contentDisposition:v().optional().describe(`Content disposition header`),contentLanguage:v().optional().describe(`Content language`),cacheControl:v().optional().describe(`Cache control directives`),etag:v().optional().describe(`Entity tag for versioning/caching`),lastModified:v().datetime().optional().describe(`Last modification timestamp`),versionId:v().optional().describe(`Object version identifier`),storageClass:BP.optional().describe(`Storage class/tier`),encryption:T({algorithm:v().describe(`Encryption algorithm (e.g., AES256, aws:kms)`),keyId:v().optional().describe(`KMS key ID if using managed encryption`)}).optional().describe(`Server-side encryption configuration`),custom:k(v(),v()).optional().describe(`Custom user-defined metadata`)})),W(()=>T({operation:A([`get`,`put`,`delete`,`head`]).describe(`Allowed operation`),expiresIn:y().min(1).max(604800).describe(`Expiration time in seconds (max 7 days)`),contentType:v().optional().describe(`Required content type for PUT operations`),maxSize:y().min(0).optional().describe(`Maximum file size in bytes for PUT operations`),responseContentType:v().optional().describe(`Override content-type for GET operations`),responseContentDisposition:v().optional().describe(`Override content-disposition for GET operations`)}));var HP=W(()=>T({enabled:b().default(!0).describe(`Enable multipart uploads`),partSize:y().min(5*1024*1024).max(5*1024*1024*1024).default(10*1024*1024).describe(`Part size in bytes (min 5MB, max 5GB)`),maxParts:y().min(1).max(1e4).default(1e4).describe(`Maximum number of parts (max 10,000)`),threshold:y().min(0).default(100*1024*1024).describe(`File size threshold to trigger multipart upload (bytes)`),maxConcurrent:y().min(1).max(100).default(4).describe(`Maximum concurrent part uploads`),abortIncompleteAfterDays:y().min(1).optional().describe(`Auto-abort incomplete uploads after N days`)})),UP=W(()=>T({acl:zP.default(`private`).describe(`Default access control level`),allowedOrigins:w(v()).optional().describe(`CORS allowed origins`),allowedMethods:w(A([`GET`,`PUT`,`POST`,`DELETE`,`HEAD`])).optional().describe(`CORS allowed HTTP methods`),allowedHeaders:w(v()).optional().describe(`CORS allowed headers`),exposeHeaders:w(v()).optional().describe(`CORS exposed headers`),maxAge:y().min(0).optional().describe(`CORS preflight cache duration in seconds`),corsEnabled:b().default(!1).describe(`Enable CORS configuration`),publicAccess:T({allowPublicRead:b().default(!1).describe(`Allow public read access`),allowPublicWrite:b().default(!1).describe(`Allow public write access`),allowPublicList:b().default(!1).describe(`Allow public bucket listing`)}).optional().describe(`Public access control`),allowedIps:w(v()).optional().describe(`Allowed IP addresses/CIDR blocks`),blockedIps:w(v()).optional().describe(`Blocked IP addresses/CIDR blocks`)})),WP=W(()=>T({id:Uk.describe(`Rule identifier`),enabled:b().default(!0).describe(`Enable this rule`),action:VP.describe(`Action to perform`),prefix:v().optional().describe(`Object key prefix filter (e.g., "uploads/")`),tags:k(v(),v()).optional().describe(`Object tag filters`),daysAfterCreation:y().min(0).optional().describe(`Days after object creation`),daysAfterModification:y().min(0).optional().describe(`Days after last modification`),targetStorageClass:BP.optional().describe(`Target storage class for transition action`)}).refine(e=>!(e.action===`transition`&&!e.targetStorageClass),{message:`targetStorageClass is required when action is "transition"`})),GP=W(()=>T({enabled:b().default(!1).describe(`Enable lifecycle policies`),rules:w(WP).default([]).describe(`Lifecycle rules`)})),KP=W(()=>T({name:Uk.describe(`Bucket identifier in ObjectStack (snake_case)`),label:v().describe(`Display label`),bucketName:v().describe(`Actual bucket/container name in storage provider`),region:v().optional().describe(`Storage region (e.g., us-east-1, westus)`),provider:RP.describe(`Storage provider`),endpoint:v().optional().describe(`Custom endpoint URL (for S3-compatible providers)`),pathStyle:b().default(!1).describe(`Use path-style URLs (for S3-compatible providers)`),versioning:b().default(!1).describe(`Enable object versioning`),encryption:T({enabled:b().default(!1).describe(`Enable server-side encryption`),algorithm:A([`AES256`,`aws:kms`,`azure:kms`,`gcp:kms`]).default(`AES256`).describe(`Encryption algorithm`),kmsKeyId:v().optional().describe(`KMS key ID for managed encryption`)}).optional().describe(`Server-side encryption configuration`),accessControl:UP.optional().describe(`Access control configuration`),lifecyclePolicy:GP.optional().describe(`Lifecycle policy configuration`),multipartConfig:HP.optional().describe(`Multipart upload configuration`),tags:k(v(),v()).optional().describe(`Bucket tags for organization`),description:v().optional().describe(`Bucket description`),enabled:b().default(!0).describe(`Enable this bucket`)})),qP=W(()=>T({accessKeyId:v().optional().describe(`AWS access key ID or MinIO access key`),secretAccessKey:v().optional().describe(`AWS secret access key or MinIO secret key`),sessionToken:v().optional().describe(`AWS session token for temporary credentials`),accountName:v().optional().describe(`Azure storage account name`),accountKey:v().optional().describe(`Azure storage account key`),sasToken:v().optional().describe(`Azure SAS token`),environmentId:v().optional().describe(`GCP project ID`),credentials:v().optional().describe(`GCP service account credentials JSON`),endpoint:v().optional().describe(`Custom endpoint URL`),region:v().optional().describe(`Default region`),useSSL:b().default(!0).describe(`Use SSL/TLS for connections`),timeout:y().min(0).optional().describe(`Connection timeout in milliseconds`)})),JP=W(()=>T({name:Uk.describe(`Storage configuration identifier`),label:v().describe(`Display label`),provider:RP.describe(`Primary storage provider`),scope:IP.optional().default(`global`).describe(`Storage scope`),connection:qP.describe(`Connection credentials`),buckets:w(KP).default([]).describe(`Configured buckets`),defaultBucket:v().optional().describe(`Default bucket name for operations`),location:v().optional().describe(`Root path (local) or base location`),quota:y().int().positive().optional().describe(`Max size in bytes`),options:k(v(),S()).optional().describe(`Provider-specific configuration options`),enabled:b().default(!0).describe(`Enable this storage configuration`),description:v().optional().describe(`Configuration description`)}));JP.parse({name:`aws_s3_storage`,label:`AWS S3 Production Storage`,provider:`s3`,connection:{accessKeyId:"${AWS_ACCESS_KEY_ID}",secretAccessKey:"${AWS_SECRET_ACCESS_KEY}",region:`us-east-1`},buckets:[{name:`user_uploads`,label:`User Uploads`,bucketName:`my-app-user-uploads`,region:`us-east-1`,provider:`s3`,versioning:!0,encryption:{enabled:!0,algorithm:`aws:kms`,kmsKeyId:"${AWS_KMS_KEY_ID}"},accessControl:{acl:`private`,corsEnabled:!0,allowedOrigins:[`https://app.example.com`],allowedMethods:[`GET`,`PUT`,`POST`]},lifecyclePolicy:{enabled:!0,rules:[{id:`archive_old_uploads`,enabled:!0,action:`transition`,daysAfterCreation:90,targetStorageClass:`glacier`}]},multipartConfig:{enabled:!0,partSize:10*1024*1024,threshold:100*1024*1024,maxConcurrent:4}}],defaultBucket:`user_uploads`,enabled:!0}),JP.parse({name:`minio_local`,label:`MinIO Local Storage`,provider:`minio`,connection:{accessKeyId:`minioadmin`,secretAccessKey:`minioadmin`,endpoint:`http://localhost:9000`,useSSL:!1},buckets:[{name:`development_files`,label:`Development Files`,bucketName:`dev-files`,provider:`minio`,endpoint:`http://localhost:9000`,pathStyle:!0,accessControl:{acl:`private`}}],defaultBucket:`development_files`,enabled:!0}),JP.parse({name:`azure_blob_storage`,label:`Azure Blob Storage`,provider:`azure_blob`,connection:{accountName:`mystorageaccount`,accountKey:"${AZURE_STORAGE_KEY}",endpoint:`https://mystorageaccount.blob.core.windows.net`},buckets:[{name:`media_files`,label:`Media Files`,bucketName:`media`,provider:`azure_blob`,region:`eastus`,accessControl:{acl:`public_read`,publicAccess:{allowPublicRead:!0,allowPublicWrite:!1,allowPublicList:!1}}}],defaultBucket:`media_files`,enabled:!0}),JP.parse({name:`gcs_storage`,label:`Google Cloud Storage`,provider:`gcs`,connection:{environmentId:`my-gcp-project`,credentials:"${GCP_SERVICE_ACCOUNT_JSON}"},buckets:[{name:`backup_storage`,label:`Backup Storage`,bucketName:`my-app-backups`,region:`us-central1`,provider:`gcs`,lifecyclePolicy:{enabled:!0,rules:[{id:`delete_old_backups`,enabled:!0,action:`delete`,daysAfterCreation:30}]}}],defaultBucket:`backup_storage`,enabled:!0}),W(()=>T({filename:v().describe(`Original filename`),mimeType:v().describe(`File MIME type`),size:y().describe(`File size in bytes`),scope:v().default(`user`).describe(`Target storage scope (e.g. user, private, public)`),bucket:v().optional().describe(`Specific bucket override (admin only)`)})),W(()=>T({fileId:v().describe(`File ID returned from presigned request`),eTag:v().optional().describe(`S3 ETag verification`)})),W(()=>G.extend({data:T({uploadUrl:v().describe(`PUT/POST URL for direct upload`),downloadUrl:v().optional().describe(`Public/Private preview URL`),fileId:v().describe(`Temporary File ID`),method:A([`PUT`,`POST`]).describe(`HTTP Method to use`),headers:k(v(),v()).optional().describe(`Required headers for upload`),expiresIn:y().describe(`URL expiry in seconds`)})})),W(()=>G.extend({data:LP.describe(`Uploaded file metadata`)})),W(()=>T({mode:A([`whitelist`,`blacklist`]).describe(`whitelist = only allow listed types, blacklist = block listed types`),mimeTypes:w(v()).min(1).describe(`List of MIME types to allow or block (e.g., "image/jpeg", "application/pdf")`),extensions:w(v()).optional().describe(`List of file extensions to allow or block (e.g., ".jpg", ".pdf")`),maxFileSize:y().int().min(1).optional().describe(`Maximum file size in bytes`),minFileSize:y().int().min(0).optional().describe(`Minimum file size in bytes (e.g., reject empty files)`)})),W(()=>T({filename:v().describe(`Original filename`),mimeType:v().describe(`File MIME type`),totalSize:y().int().min(1).describe(`Total file size in bytes`),chunkSize:y().int().min(5242880).default(5242880).describe(`Size of each chunk in bytes (minimum 5MB per S3 spec)`),scope:v().default(`user`).describe(`Target storage scope`),bucket:v().optional().describe(`Specific bucket override (admin only)`),metadata:k(v(),v()).optional().describe(`Custom metadata key-value pairs`)})),W(()=>G.extend({data:T({uploadId:v().describe(`Multipart upload session ID`),resumeToken:v().describe(`Opaque token for resuming interrupted uploads`),fileId:v().describe(`Assigned file ID`),totalChunks:y().int().min(1).describe(`Expected number of chunks`),chunkSize:y().int().describe(`Chunk size in bytes`),expiresAt:v().datetime().describe(`Upload session expiration timestamp`)})})),W(()=>T({uploadId:v().describe(`Multipart upload session ID`),chunkIndex:y().int().min(0).describe(`Zero-based chunk index`),resumeToken:v().describe(`Resume token from initiate response`)})),W(()=>G.extend({data:T({chunkIndex:y().int().describe(`Chunk index that was uploaded`),eTag:v().describe(`Chunk ETag for multipart completion`),bytesReceived:y().int().describe(`Bytes received for this chunk`)})})),W(()=>T({uploadId:v().describe(`Multipart upload session ID`),parts:w(T({chunkIndex:y().int().describe(`Chunk index`),eTag:v().describe(`ETag returned from chunk upload`)})).min(1).describe(`Ordered list of uploaded parts for assembly`)})),W(()=>G.extend({data:T({fileId:v().describe(`Final file ID`),key:v().describe(`Storage key/path of the assembled file`),size:y().int().describe(`Total file size in bytes`),mimeType:v().describe(`File MIME type`),eTag:v().optional().describe(`Final ETag of the assembled file`),url:v().optional().describe(`Download URL for the assembled file`)})})),W(()=>G.extend({data:T({uploadId:v().describe(`Multipart upload session ID`),fileId:v().describe(`Assigned file ID`),filename:v().describe(`Original filename`),totalSize:y().int().describe(`Total file size in bytes`),uploadedSize:y().int().describe(`Bytes uploaded so far`),totalChunks:y().int().describe(`Total expected chunks`),uploadedChunks:y().int().describe(`Number of chunks uploaded`),percentComplete:y().min(0).max(100).describe(`Upload progress percentage`),status:A([`in_progress`,`completing`,`completed`,`failed`,`expired`]).describe(`Current upload session status`),startedAt:v().datetime().describe(`Upload session start timestamp`),expiresAt:v().datetime().describe(`Session expiration timestamp`)})}));var YP=T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Unique rule name (snake_case)`),label:v().optional().describe(`Human-readable label for the rule listing`),description:v().optional().describe(`Administrative notes explaining the business reason`),active:b().default(!0),events:w(A([`insert`,`update`,`delete`])).default([`insert`,`update`]).describe(`Validation contexts`),priority:y().int().min(0).max(9999).default(100).describe(`Execution priority (lower runs first, default: 100)`),tags:w(v()).optional().describe(`Categorization tags (e.g., "compliance", "billing")`),severity:A([`error`,`warning`,`info`]).default(`error`),message:v().describe(`Error message to display to the user`)}),XP=W(()=>YP.extend({type:j(`script`),condition:bA.describe("Predicate (CEL). If TRUE, validation fails. e.g. P`record.amount < 0`")})),ZP=W(()=>YP.extend({type:j(`state_machine`),field:v().describe(`State field (e.g. status)`),transitions:k(v(),w(v())).describe(`Map of { OldState: [AllowedNewStates] }`)})),QP=W(()=>YP.extend({type:j(`format`),field:v(),regex:v().optional(),format:A([`email`,`url`,`phone`,`json`]).optional()})),$P=W(()=>YP.extend({type:j(`cross_field`),condition:bA.describe("Predicate (CEL) comparing fields. e.g. P`record.end_date > record.start_date`"),fields:w(v()).describe(`Fields involved in the validation`)})),eF=W(()=>YP.extend({type:j(`json_schema`),field:v().describe(`JSON field to validate`),schema:k(v(),S()).describe(`JSON Schema object definition`)})),tF=M(()=>D(`type`,[XP,ZP,QP,$P,eF,nF])),nF=W(()=>YP.extend({type:j(`conditional`),when:bA.describe("Predicate (CEL). e.g. P`record.type == 'enterprise'`"),then:tF.describe(`Validation rule to apply when condition is true`),otherwise:tF.optional().describe(`Validation rule to apply when condition is false`)})),rF=A([`api.read`,`api.write`,`api.transaction`,`crypto.uuid`,`crypto.hash`,`log`]),iF=D(`language`,[T({language:j(`expression`),source:v().min(1).describe(`Formula expression source`)}).describe(`L1 expression body — pure formula, no IO`),T({language:j(`js`),source:v().min(1).describe(`Function body source`),capabilities:w(rF).default([]).describe(`Granted capability tokens`),timeoutMs:y().int().positive().max(3e4).optional().describe(`Per-invocation timeout (ms)`),memoryMb:y().int().positive().max(256).optional().describe(`Per-invocation memory cap (MB)`)}).describe(`L2 sandboxed JS body — runs inside an isolated VM with declared capabilities`)]).describe(`Hook/Action body — expression (L1) or sandboxed JS (L2)`),aF=W(()=>T({name:v().optional(),field:Wk.optional(),objectOverride:Wk.optional(),label:K.optional(),type:Sj.optional(),required:b().optional().default(!1),options:w(T({label:K,value:v()})).optional(),placeholder:v().optional(),helpText:v().optional(),defaultValue:S().optional(),defaultFromRow:b().optional()}).refine(e=>!!e.name||!!e.field,{message:`ActionParam requires either "name" or "field"`})),oF=A([`script`,`url`,`modal`,`flow`,`api`,`form`]),sF=new Set(oF.options.filter(e=>e!==`script`)),cF=A([`list_toolbar`,`list_item`,`record_header`,`record_more`,`record_related`,`record_section`,`global_nav`]),lF=A([`data`,`action`,`flow`,`integration`,`vector_search`,`analytics`,`utility`]),uF=T({exposed:b().default(!1).describe("Expose this action to AI agents. Requires `description` when true."),description:v().min(40).optional().describe(`LLM-facing description (≥40 chars). Required when exposed.`),category:lF.optional().describe(`Tool category override (defaults to "action").`),paramHints:k(v(),T({description:v().optional(),enum:w(E([v(),y()])).optional(),examples:w(S()).optional()})).optional().describe(`Per-parameter AI hints keyed by param name.`),outputSchema:k(v(),S()).optional().describe(`JSON Schema for the action return value.`),requiresConfirmation:b().optional().describe(`Override HITL confirmation for AI invocations.`)}),dF=W(()=>T({name:Wk.describe(`Machine name (lowercase snake_case)`),label:K.describe(`Display label`),objectName:v().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:v().optional().describe(`Icon name`),locations:w(cF).optional().describe(`Locations where this action is visible`),component:A([`action:button`,`action:icon`,`action:menu`,`action:group`]).optional().describe(`Visual component override`),type:oF.default(`script`).describe(`Action functionality type`),target:v().optional().describe("URL, Script Name, Flow ID, or API Endpoint. Supports ${param.X} and ${ctx.X} interpolation."),body:iF.optional().describe("Action body — expression (L1) or sandboxed JS (L2). Only used when type is `script`."),execute:v().optional().describe(`@deprecated — Use target instead. Auto-migrated to target during parsing.`),params:w(aF).optional().describe(`Input parameters required from user`),variant:A([`primary`,`secondary`,`danger`,`ghost`,`link`]).optional().describe(`Button visual variant for styling (primary = highlighted, danger = destructive, ghost = transparent)`),confirmText:K.optional().describe(`Confirmation message before execution`),successMessage:K.optional().describe(`Success message to show after execution`),errorMessage:K.optional().describe(`Error message to show when the action fails (overrides the raw error).`),refreshAfter:b().default(!1).describe(`Refresh view after execution`),undoable:b().optional().describe(`Offer an Undo affordance after this single-record update action succeeds.`),resultDialog:T({title:K.optional(),description:K.optional(),acknowledge:K.optional().describe(`Acknowledge button label, e.g. "I have saved this"`),format:A([`qrcode`,`code-list`,`secret`,`text`,`json`]).optional().describe(`Default format for fields without their own format. Defaults to json when omitted.`),fields:w(T({path:v().describe(`Dot path into result.data (e.g. "totpURI", "client.client_secret").`),label:K.optional(),format:A([`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:bA.optional().describe(`Visibility predicate (CEL).`),disabled:E([b(),bA]).optional().describe(`Boolean or predicate (CEL) — action is disabled when TRUE.`),requiredPermissions:w(v()).optional().describe(`[ADR-0066 D4] Capabilities required to invoke this action (server-enforced 403 + UI hide/disable).`),shortcut:v().optional().describe(`Keyboard shortcut to trigger this action (e.g., "Ctrl+S")`),bulkEnabled:b().optional().describe(`Whether this action can be applied to multiple selected records`),ai:uF.optional().describe(`AI exposure (opt-in). Set ai.exposed=true + ai.description to make this callable by agents.`),recordIdParam:v().optional().describe(`Body key to inject the row id into when running from a list_item context.`),recordIdField:v().optional().describe(`Row field whose value seeds recordIdParam. Defaults to "id".`),bodyShape:E([j(`flat`),T({wrap:v()})]).optional().describe(`Body wrapping: flat (default) or { wrap: key } to nest user-collected params under a key.`),method:A([`POST`,`PATCH`,`PUT`,`DELETE`]).optional().describe(`HTTP method for type:"api" actions. Defaults to POST.`),bodyExtra:k(v(),S()).optional().describe(`Constant body fields merged into the API request (applied last; overrides user params).`),mode:A([`create`,`edit`,`delete`,`custom`]).optional().describe(`Semantic mode of the action.`),opensInNewTab:b().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:v().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.`),timeout:y().optional().describe(`Maximum execution time in milliseconds for the action`),aria:dj.optional().describe(`ARIA accessibility attributes`)}).transform(e=>e.execute&&!e.target?{...e,target:e.execute}:e).refine(e=>!(sF.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.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`]})),fF=A([`get`,`list`,`create`,`update`,`delete`,`upsert`,`bulk`,`aggregate`,`history`,`search`,`restore`,`purge`,`import`,`export`]),pF=T({trackHistory:b().default(!1).describe(`Enable field history tracking for audit compliance`),searchable:b().default(!0).describe(`Index records for global search`),apiEnabled:b().default(!0).describe(`Expose object via automatic APIs`),apiMethods:w(fF).optional().describe(`Whitelist of allowed API operations`),files:b().default(!1).describe(`Enable file attachments and document management`),feeds:b().default(!1).describe(`Enable social feed, comments, and mentions (Chatter-like)`),activities:b().default(!1).describe(`Enable standard tasks and events tracking`),trash:b().default(!0).describe(`Enable soft-delete with restore capability`),mru:b().default(!0).describe(`Track Most Recently Used (MRU) list for users`),clone:b().default(!0).describe(`Allow record deep cloning`)}),mF=W(()=>T({name:v().optional().describe(`Index name (auto-generated if not provided)`),fields:w(v()).describe(`Fields included in the index`),type:A([`btree`,`hash`,`gin`,`gist`,`fulltext`]).optional().default(`btree`).describe(`Index algorithm type`),unique:b().optional().default(!1).describe(`Whether the index enforces uniqueness`),partial:v().optional().describe(`Partial index condition (SQL WHERE clause for conditional indexes)`)})),hF=W(()=>T({fields:w(v()).describe(`Fields to index for full-text search weighting`),displayFields:w(v()).optional().describe(`Fields to display in search result cards`),filters:w(v()).optional().describe(`Default filters for search results`)})),gF=W(()=>T({enabled:b().describe(`Enable multi-tenancy for this object`),strategy:A([`shared`,`isolated`,`hybrid`]).describe(`Tenant isolation strategy: shared (single DB, row-level), isolated (separate DB per tenant), hybrid (mix)`),tenantField:v().default(`tenant_id`).describe(`Field name for tenant identifier`),crossTenantAccess:b().default(!1).describe(`Allow cross-tenant data access (with explicit permission)`)})),_F=W(()=>T({default:A([`public`,`private`]).default(`public`).describe(`Default exposure posture: public (covered by wildcard grants) | private (needs explicit grant; exempt from wildcard RLS).`)})),vF=W(()=>T({enabled:b().describe(`Enable soft delete (trash/recycle bin)`),field:v().default(`deleted_at`).describe(`Field name for soft delete timestamp`),cascadeDelete:b().default(!1).describe(`Cascade soft delete to related records`)})),yF=W(()=>T({enabled:b().describe(`Enable record versioning`),strategy:A([`snapshot`,`delta`,`event-sourcing`]).describe(`Versioning strategy: snapshot (full copy), delta (changes only), event-sourcing (event log)`),retentionDays:y().min(1).optional().describe(`Number of days to retain old versions (undefined = infinite)`),versionField:v().default(`version`).describe(`Field name for version number/timestamp`)})),bF=W(()=>T({enabled:b().describe(`Enable table partitioning`),strategy:A([`range`,`hash`,`list`]).describe(`Partitioning strategy: range (date ranges), hash (consistent hashing), list (predefined values)`),key:v().describe(`Field name to partition by`),interval:v().optional().describe(`Partition interval for range strategy (e.g., "1 month", "1 year")`)}).refine(e=>!(e.strategy===`range`&&!e.interval),{message:`interval is required when strategy is "range"`})),xF=W(()=>T({key:v().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:v().describe(`Group display label`),icon:v().optional().describe(`Icon name (Lucide/Material) for the group header`),description:v().optional().describe(`Optional description shown under the group header`),defaultExpanded:b().optional().default(!0).describe(`Whether the group is expanded by default`),visibleOn:bA.optional().describe(`Visibility predicate (CEL); group is hidden when FALSE.`)})),SF=T({remoteName:v().optional().describe(`Remote table/view name. Defaults to object.name.`),remoteSchema:v().optional().describe(`Remote schema/database qualifier.`),writable:b().default(!1).describe(`Per-object write opt-in (also requires datasource.external.allowWrites).`),columnMap:k(v(),v()).optional().describe(`Remote column name → local field name.`),introspectedAt:v().datetime().optional().describe("Set by `os datasource introspect`; informational."),ignoreColumns:w(v()).optional().describe(`Remote columns to skip during validation (dev convenience).`)}).describe(`External datasource binding (ADR-0015)`),CF=T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Machine unique key (snake_case). Immutable.`),label:v().optional().describe(`Human readable singular label (e.g. "Account")`),pluralLabel:v().optional().describe(`Human readable plural label (e.g. "Accounts")`),description:v().optional().describe(`Developer documentation / description`),icon:v().optional().describe(`Icon name (Lucide/Material) for UI representation`),tags:w(v()).optional().describe(`Categorization tags (e.g. "sales", "system", "reference")`),active:b().optional().default(!0).describe(`Is the object active and usable`),isSystem:b().optional().default(!1).describe(`Is system object (protected from deletion)`),abstract:b().optional().default(!1).describe(`Is abstract base object (cannot be instantiated)`),managedBy:A([`platform`,`config`,`system`,`append-only`,`better-auth`]).optional().describe(`Lifecycle bucket — platform (user CRUD) | config (admin authored) | system (engine-managed) | append-only (audit) | better-auth (identity). UI clients honour the resolved affordance matrix.`),userActions:T({create:b().optional().describe(`Show generic "New" button.`),import:b().optional().describe(`Show CSV import wizard entry.`),edit:b().optional().describe(`Allow inline / form edit of existing rows.`),delete:b().optional().describe(`Show row-level delete + bulk delete.`),exportCsv:b().optional().describe(`Show CSV export entry.`)}).optional().describe(`Per-object override of the resolved CRUD affordance matrix.`),systemFields:E([j(!1),T({tenant:b().optional().describe(`Inject organization_id (multi-tenant only). Default true.`),owner:b().optional().describe(`Reserved for future owner_id auto-injection.`),audit:b().optional().describe(`Reserved for future created_by/updated_by auto-injection.`)})]).optional().describe(`Opt out of, or selectively disable, registry-level system-field auto-injection.`),datasource:v().optional().default(`default`).describe(`Target Datasource ID. "default" is the primary DB.`),external:SF.optional().describe(`Remote table binding for federated (external) objects.`),fields:k(v().regex(/^[a-z_][a-z0-9_]*$/,{message:`Field names must be lowercase snake_case (e.g., "first_name", "company", "annual_revenue")`}),Dj).describe(`Field definitions map. Keys must be snake_case identifiers.`),indexes:w(mF).optional().describe(`Database performance indexes`),fieldGroups:w(xF).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:gF.optional().describe(`Multi-tenancy configuration for SaaS applications`),access:_F.optional().describe(`[ADR-0066 D2] Object exposure posture (public-by-default vs private secure-by-default).`),requiredPermissions:w(v()).optional().describe(`[ADR-0066 D3] Capabilities required to access this object (AND-gate, checked alongside CRUD grants).`),softDelete:vF.optional().describe(`Soft delete (trash/recycle bin) configuration`),versioning:yF.optional().describe(`Record versioning and history tracking configuration`),partitioning:bF.optional().describe(`Table partitioning configuration for performance`),validations:w(tF).optional().describe(`Object-level validation rules`),activityMilestones:w(T({field:v().describe(`Field to watch (typically a status/stage select).`),value:v().describe(`The value the field must transition INTO to fire the milestone.`),summary:v().describe(`Activity summary template; {field} tokens interpolate the record value. e.g. "Deal won: {name}".`),type:v().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).`),displayNameField:v().optional().describe(`Field to use as the record display name (e.g., "name", "title"). Defaults to "name" if present.`),recordName:T({type:A([`text`,`autonumber`]).describe(`Record name type: text (user-entered) or autonumber (system-generated)`),displayFormat:v().optional().describe(`Auto-number format pattern (e.g., "CASE-{0000}", "INV-{YYYY}-{0000}")`),startNumber:y().int().min(0).optional().describe(`Starting number for autonumber (default: 1)`)}).optional().describe(`Record name generation configuration (Salesforce pattern)`),titleFormat:SA.optional().describe(`Title template — supports {{record.field}} interpolation. Overrides displayNameField.`),compactLayout:w(v()).optional().describe(`Primary fields for hover/cards/lookups`),listViews:k(v(),nM).optional().describe(`Built-in named list views (segmented tabs) shipped with the object schema`),defaultDetailForm:v().optional().describe(`Name of the default FormView for record detail / edit screens`),searchableFields:w(v()).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."),search:hF.optional().describe(`Search engine configuration`),enable:pF.optional().describe(`Enabled system features modules`),sharingModel:A([`private`,`public_read`,`public_read_write`,`controlled_by_parent`,`read`,`read_write`,`full`]).optional().describe(`Org-Wide Default record visibility (OWD). Canonical: private (owner-only) | public_read (everyone reads, owner writes) | public_read_write (everyone reads+writes) | controlled_by_parent (derived from the master record). Legacy aliases: read=public_read, read_write/full=public_read_write. ADR-0056 D1.`),publicSharing:T({enabled:b().default(!1).describe(`Allow records of this object to be published via share link`),allowedAudiences:w(A([`public`,`link_only`,`signed_in`,`email`])).optional().describe(`Audiences callers may select when creating a link`),allowedPermissions:w(A([`view`,`comment`,`edit`])).optional().describe(`Permission levels selectable on the share dialog`),maxExpiryDays:y().int().positive().optional().describe(`Reject links with expiry beyond this many days`),redactFields:w(v()).optional().describe(`Field names removed from records served via a share token`),eligibility:v().optional().describe(`CEL expression that must evaluate to true on the target record`)}).optional().describe(`Public share-link policy (Notion/Figma-style link sharing)`),keyPrefix:v().max(5).optional().describe(`Short prefix for record IDs (e.g., "001" for Account)`),detail:T({renderViaSchema:b().optional().describe(`Opt this object out of the schema-driven detail renderer`),hideReferenceRail:b().optional().describe(`Suppress the right-hand reference-rail on the detail page`),hideRelatedTab:b().optional().describe(`Suppress the Related tab on the detail page`)}).passthrough().optional().describe(`Detail-page UI hints consumed by @object-ui/plugin-detail synth`),actions:w(dF).optional().describe(`Actions associated with this object (auto-populated from top-level actions via objectName)`),protection:uj.optional().describe(`Package author protection block — lock policy for this object.`),...lj});function wF(e){return e.split(`_`).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `)}var TF={workflows:"`workflows` is not an ObjectSchema field. Object-level, record-triggered automation is authored as a lifecycle hook (`src/objects/<name>.hook.ts`, registered via `defineHook()`) 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, registered via `defineHook()`.",triggers:"`triggers` is not an ObjectSchema field. Use a lifecycle hook (`src/objects/<name>.hook.ts`) or a top-level `record_change` flow."};function EF(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 DF(e,t){let n,r=1/0;for(let i of t){let t=EF(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 OF(e,t,n){let r=typeof e==`string`&&e.length>0?e:`<unnamed>`,i=t.map(e=>{let t=TF[e];if(t)return` \u2022 ${t}`;let r=DF(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(`, `)}.
|
|
85
|
+
These keys would previously have been stripped silently at build, shipping dead metadata with no diagnostic (ADR-0032 "no silent failure", issue #1535).
|
|
86
|
+
|
|
87
|
+
${i.join(`
|
|
88
|
+
`)}
|
|
89
|
+
|
|
90
|
+
Remove the unknown key(s), fix the typo, or move the logic to a supported mechanism.`)}var kF=W(()=>Object.assign(CF,{create:e=>{let t=e,n=Object.keys(CF.shape),r=Object.keys(t).filter(e=>!n.includes(e));if(r.length>0)throw OF(t.name,r,n);let i={...t,label:t.label??wF(t.name)};return CF.parse(i)}}));A([`own`,`extend`]),W(()=>T({extend:v().describe(`Target object name (FQN) to extend`),fields:k(v(),Dj).optional().describe(`Fields to add/override`),label:v().optional().describe(`Override label for the extended object`),pluralLabel:v().optional().describe(`Override plural label for the extended object`),description:v().optional().describe(`Override description for the extended object`),validations:w(tF).optional().describe(`Additional validation rules to merge into the target object`),indexes:w(mF).optional().describe(`Additional indexes to merge into the target object`),priority:y().int().min(0).max(999).default(200).describe(`Merge priority (higher = applied later)`)}));var AF=W(()=>A([`json`,`yaml`,`typescript`,`javascript`])),jF=W(()=>T({size:y().int().min(0).describe(`File size in bytes`),modifiedAt:v().datetime().describe(`Last modified date`),etag:v().describe(`Entity tag for cache validation`),format:AF.describe(`Serialization format`),path:v().optional().describe(`File system path`),metadata:k(v(),S()).optional().describe(`Provider-specific metadata`)}));W(()=>T({patterns:w(v()).optional().describe(`File glob patterns`),ifNoneMatch:v().optional().describe(`ETag for conditional request`),ifModifiedSince:v().datetime().optional().describe(`Only load if modified after this date`),validate:b().default(!0).describe(`Validate against schema`),useCache:b().default(!0).describe(`Enable caching`),filter:bA.optional().describe(`Filter predicate (CEL)`),limit:y().int().min(1).optional().describe(`Maximum items to load`),recursive:b().default(!0).describe(`Search subdirectories`)})),W(()=>T({format:AF.default(`typescript`).describe(`Output format`),prettify:b().default(!0).describe(`Format with indentation`),indent:y().int().min(0).max(8).default(2).describe(`Indentation spaces`),sortKeys:b().default(!1).describe(`Sort object keys`),includeDefaults:b().default(!1).describe(`Include default values`),backup:b().default(!1).describe(`Create backup file`),overwrite:b().default(!0).describe(`Overwrite existing file`),atomic:b().default(!0).describe(`Use atomic write operation`),path:v().optional().describe(`Custom output path`)})),W(()=>T({output:v().describe(`Output file path`),format:AF.default(`json`).describe(`Export format`),filter:bA.optional().describe(`Filter items to export (CEL)`),includeStats:b().default(!1).describe(`Include metadata statistics`),compress:b().default(!1).describe(`Compress output (gzip)`),prettify:b().default(!0).describe(`Pretty print output`)})),W(()=>T({conflictResolution:A([`skip`,`overwrite`,`merge`,`fail`]).default(`merge`).describe(`How to handle existing items`),validate:b().default(!0).describe(`Validate before import`),dryRun:b().default(!1).describe(`Simulate import without saving`),continueOnError:b().default(!1).describe(`Continue if validation fails`),transform:v().optional().describe(`Transform items before import`)})),W(()=>T({data:S().nullable().describe(`Loaded metadata`),fromCache:b().default(!1).describe(`Loaded from cache`),notModified:b().default(!1).describe(`Not modified since last request`),etag:v().optional().describe(`Entity tag`),stats:jF.optional().describe(`Metadata statistics`),loadTime:y().min(0).optional().describe(`Load duration in ms`)})),W(()=>T({success:b().describe(`Save successful`),path:v().describe(`Output path`),etag:v().optional().describe(`Generated entity tag`),size:y().int().min(0).optional().describe(`File size`),saveTime:y().min(0).optional().describe(`Save duration in ms`),backupPath:v().optional().describe(`Backup file path`)})),W(()=>T({type:A([`added`,`changed`,`deleted`]).describe(`Event type`),metadataType:v().describe(`Type of metadata`),name:v().describe(`Item identifier`),path:v().describe(`File path`),data:S().optional().describe(`Item data`),timestamp:v().datetime().describe(`Event timestamp`)})),W(()=>T({type:v().describe(`Collection type`),count:y().int().min(0).describe(`Number of items`),formats:w(AF).describe(`Formats in collection`),totalSize:y().int().min(0).optional().describe(`Total size in bytes`),lastModified:v().datetime().optional().describe(`Last modification date`),location:v().optional().describe(`Collection location`)})),W(()=>T({name:v().describe(`Loader identifier`),protocol:A([`file:`,`http:`,`s3:`,`datasource:`,`memory:`]).describe(`Protocol identifier`),capabilities:T({read:b().default(!0),write:b().default(!1),watch:b().default(!1),list:b().default(!0)}).describe(`Loader capabilities`),supportedFormats:w(AF).describe(`Supported formats`),supportsWatch:b().default(!1).describe(`Supports file watching`),supportsWrite:b().default(!0).describe(`Supports write operations`),supportsCache:b().default(!0).describe(`Supports caching`)}));var MF=W(()=>A([`filesystem`,`memory`,`none`])),NF=W(()=>T({datasource:v().optional().describe(`Datasource name reference for database persistence`),tableName:v().default(`sys_metadata`).describe(`Database table name for metadata storage`),fallback:MF.default(`none`).describe(`Fallback strategy when datasource is unavailable`),rootDir:v().optional().describe(`Root directory path`),formats:w(AF).default([`typescript`,`json`,`yaml`]).describe(`Enabled formats`),cache:T({enabled:b().default(!0).describe(`Enable caching`),ttl:y().int().min(0).default(3600).describe(`Cache TTL in seconds`),maxSize:y().int().min(0).optional().describe(`Max cache size in bytes`),databaseLoader:T({enabled:b().default(!0).describe(`Enable DatabaseLoader cache`),maxSize:y().int().min(0).default(500).describe(`Max cached entries`),ttl:y().int().min(0).default(6e4).describe(`Cache TTL in milliseconds`)}).optional().describe(`DatabaseLoader read-through cache`)}).optional().describe(`Cache settings`),watch:b().default(!1).describe(`Enable file watching`),watchOptions:T({ignored:w(v()).optional().describe(`Patterns to ignore`),persistent:b().default(!0).describe(`Keep process running`),ignoreInitial:b().default(!0).describe(`Ignore initial add events`)}).optional().describe(`File watcher options`),validation:T({strict:b().default(!0).describe(`Strict validation`),throwOnError:b().default(!0).describe(`Throw on validation error`)}).optional().describe(`Validation settings`),loaderOptions:k(v(),S()).optional().describe(`Loader-specific configuration`),persistence:T({writable:b().default(!0).describe(`Allow base metadata writes via register()`),overlayWritable:b().default(!0).describe(`Allow overlay writes via saveOverlay()`)}).optional().describe(`Persistence write gates`)}));W(()=>A([`package`,`admin`,`user`,`migration`,`api`]));var PF=W(()=>T({path:v().describe(`JSON path to the changed field`),originalValue:S().optional().describe(`Original value from the package`),currentValue:S().describe(`Current customized value`),changedBy:v().optional().describe(`User or admin who made this change`),changedAt:v().datetime().optional().describe(`Timestamp of the change`)})),FF=W(()=>T({id:v().describe(`Overlay record ID (UUID)`),baseType:v().describe(`Metadata type being customized`),baseName:v().describe(`Metadata name being customized`),packageId:v().optional().describe(`Package ID that delivered the base metadata`),packageVersion:v().optional().describe(`Package version when overlay was created`),scope:A([`platform`,`user`]).default(`platform`).describe(`Customization scope (platform=admin, user=personal)`),tenantId:v().optional().describe(`Tenant identifier`),owner:v().optional().describe(`Owner user ID for user-scope overlays`),patch:k(v(),S()).describe(`JSON Merge Patch payload (changed fields only)`),changes:w(PF).optional().describe(`Field-level change tracking for conflict detection`),active:b().default(!0).describe(`Whether this overlay is active`),createdAt:v().datetime().optional(),createdBy:v().optional(),updatedAt:v().datetime().optional(),updatedBy:v().optional()})),IF=W(()=>T({path:v().describe(`JSON path to the conflicting field`),baseValue:S().describe(`Value in the old package version`),incomingValue:S().describe(`Value in the new package version`),customValue:S().describe(`Customer customized value`),suggestedResolution:A([`keep-custom`,`accept-incoming`,`manual`]).describe(`Suggested resolution strategy`),reason:v().optional().describe(`Explanation for the suggested resolution`)})),LF=W(()=>T({defaultStrategy:A([`keep-custom`,`accept-incoming`,`three-way-merge`]).default(`three-way-merge`).describe(`Default merge strategy`),alwaysAcceptIncoming:w(v()).optional().describe(`Field paths that always accept package updates`),alwaysKeepCustom:w(v()).optional().describe(`Field paths where customer customizations always win`),autoResolveNonConflicting:b().default(!0).describe(`Auto-resolve changes that do not conflict`)}));W(()=>T({success:b().describe(`Whether merge completed without unresolved conflicts`),mergedMetadata:k(v(),S()).optional().describe(`Merged metadata result`),updatedOverlay:k(v(),S()).optional().describe(`Updated overlay after merge`),conflicts:w(IF).optional().describe(`Unresolved merge conflicts`),autoResolved:w(T({path:v(),resolution:v(),description:v().optional()})).optional().describe(`Summary of auto-resolved changes`),stats:T({totalFields:y().int().min(0).describe(`Total fields evaluated`),unchanged:y().int().min(0).describe(`Fields with no changes`),autoResolved:y().int().min(0).describe(`Fields auto-resolved`),conflicts:y().int().min(0).describe(`Fields with conflicts`)}).optional()}));var RF=W(()=>T({metadataType:v().describe(`Metadata type (e.g. "object", "view")`),allowCustomization:b().default(!0),lockedFields:w(v()).optional().describe(`Field paths that cannot be customized`),customizableFields:w(v()).optional().describe(`Field paths that can be customized (whitelist)`),allowAddFields:b().default(!0).describe(`Whether admins can add new fields to package objects`),allowDeleteFields:b().default(!1).describe(`Whether admins can delete package-delivered fields`)})),zF=W(()=>A(`object.field.trigger.validation.hook.seed.view.page.dashboard.app.action.report.dataset.flow.job.datasource.external_catalog.translation.router.function.service.email_template.doc.book.permission.profile.role.agent.tool.skill`.split(`.`))),BF=T({type:zF.describe(`Metadata type identifier`),label:v().describe(`Display label for the metadata type`),description:v().optional().describe(`Description of the metadata type`),filePatterns:w(v()).describe(`Glob patterns to discover files of this type`),supportsOverlay:b().default(!0).describe(`Whether overlay customization is supported`),allowOrgOverride:b().default(!1).describe(`Allow per-org overlay writes via runtime metadata API`),allowRuntimeCreate:b().default(!0).describe(`Allow runtime creation via API`),supportsVersioning:b().default(!1).describe(`Whether version history is tracked`),executionPinned:b().default(!1).describe(`Transaction rows reference a specific version_hash; history GC is disabled and getByHash() MUST resolve old hashes (ADR-0009)`),loadOrder:y().int().min(0).default(100).describe(`Loading priority (lower = earlier)`),domain:A([`data`,`ui`,`automation`,`system`,`security`,`ai`]).describe(`Protocol domain`),actions:w(dF).optional().describe(`Declarative type-level actions (e.g. datasource "Test connection"), reusing ActionSchema; merged with plugin-registered actions when emitted`)});W(()=>BF.superRefine((e,t)=>{e.executionPinned&&!e.supportsVersioning&&t.addIssue({code:ru.custom,path:[`executionPinned`],message:`executionPinned requires supportsVersioning: true (type '${e.type}')`})}));var VF=W(()=>T({types:w(zF).optional().describe(`Filter by metadata types`),namespaces:w(v()).optional().describe(`Filter by namespaces`),packageId:v().optional().describe(`Filter by owning package`),search:v().optional().describe(`Full-text search query`),scope:A([`system`,`platform`,`user`]).optional().describe(`Filter by scope`),state:A([`draft`,`active`,`archived`,`deprecated`]).optional().describe(`Filter by lifecycle state`),tags:w(v()).optional().describe(`Filter by tags`),sortBy:A([`name`,`type`,`updatedAt`,`createdAt`]).default(`name`).describe(`Sort field`),sortOrder:A([`asc`,`desc`]).default(`asc`).describe(`Sort direction`),page:y().int().min(1).default(1).describe(`Page number`),pageSize:y().int().min(1).max(500).default(50).describe(`Items per page`)})),HF=W(()=>T({items:w(T({type:v().describe(`Metadata type`),name:v().describe(`Item name`),namespace:v().optional().describe(`Namespace`),label:v().optional().describe(`Display label`),scope:A([`system`,`platform`,`user`]).optional(),state:A([`draft`,`active`,`archived`,`deprecated`]).optional(),packageId:v().optional(),updatedAt:v().datetime().optional()})).describe(`Matched metadata items`),total:y().int().min(0).describe(`Total matching items`),page:y().int().min(1).describe(`Current page`),pageSize:y().int().min(1).describe(`Page size`)}));W(()=>T({event:A([`metadata.registered`,`metadata.updated`,`metadata.unregistered`,`metadata.validated`,`metadata.deployed`,`metadata.overlay.applied`,`metadata.overlay.removed`,`metadata.imported`,`metadata.exported`]).describe(`Event type`),metadataType:zF.describe(`Metadata type`),name:v().describe(`Metadata item name`),namespace:v().optional().describe(`Namespace`),packageId:v().optional().describe(`Owning package ID`),timestamp:v().datetime().describe(`Event timestamp`),actor:v().optional().describe(`User or system that triggered the event`),payload:k(v(),S()).optional().describe(`Event-specific payload`)}));var UF=W(()=>T({valid:b().describe(`Whether the metadata is valid`),errors:w(T({path:v().describe(`JSON path to the invalid field`),message:v().describe(`Error description`),code:v().optional().describe(`Error code`)})).optional().describe(`Validation errors`),warnings:w(T({path:v().describe(`JSON path to the field`),message:v().describe(`Warning description`)})).optional().describe(`Validation warnings`)})),WF=W(()=>T({storage:NF.describe(`Storage backend configuration`),customizationPolicies:w(RF).optional().describe(`Default customization policies per type`),mergeStrategy:LF.optional().describe(`Merge strategy for package upgrades`),additionalTypes:w(BF.omit({type:!0}).extend({type:v().describe(`Custom metadata type identifier`)})).optional().describe(`Additional custom metadata types`),enableEvents:b().default(!0).describe(`Emit metadata change events`),validateOnWrite:b().default(!0).describe(`Validate metadata on write`),enableVersioning:b().default(!1).describe(`Track metadata version history`),cacheMaxItems:y().int().min(0).default(1e4).describe(`Max items in memory cache`),bootstrap:A([`eager`,`lazy`,`artifact-only`]).default(`eager`).describe(`How metadata is primed at plugin start (eager / lazy / artifact-only)`)}));W(()=>T({id:j(`com.objectstack.metadata`).describe(`Metadata plugin ID`),name:j(`ObjectStack Metadata Service`).describe(`Plugin name`),version:v().regex(/^\d+\.\d+\.\d+$/).describe(`Plugin version`),type:j(`standard`).describe(`Plugin type`),description:v().default(`Core metadata management service for ObjectStack platform`).describe(`Plugin description`),capabilities:T({crud:b().default(!0).describe(`Supports metadata CRUD`),query:b().default(!0).describe(`Supports metadata query`),overlay:b().default(!0).describe(`Supports customization overlays`),watch:b().default(!1).describe(`Supports file watching`),importExport:b().default(!0).describe(`Supports import/export`),validation:b().default(!0).describe(`Supports schema validation`),versioning:b().default(!1).describe(`Supports version history`),events:b().default(!0).describe(`Emits metadata events`)}).describe(`Plugin capabilities`),config:WF.optional().describe(`Plugin configuration`)})),W(()=>T({items:w(T({type:v().describe(`Metadata type`),name:v().describe(`Item name`),data:k(v(),S()).describe(`Metadata payload`),namespace:v().optional().describe(`Namespace`)})).min(1).describe(`Items to register`),continueOnError:b().default(!1).describe(`Continue if individual item fails`),validate:b().default(!0).describe(`Validate before register`)}));var GF=W(()=>T({total:y().int().min(0).describe(`Total items processed`),succeeded:y().int().min(0).describe(`Successfully processed`),failed:y().int().min(0).describe(`Failed items`),errors:w(T({type:v().describe(`Metadata type`),name:v().describe(`Item name`),error:v().describe(`Error message`)})).optional().describe(`Per-item errors`)})),KF=W(()=>T({sourceType:v().describe(`Dependent metadata type`),sourceName:v().describe(`Dependent metadata name`),targetType:v().describe(`Referenced metadata type`),targetName:v().describe(`Referenced metadata name`),kind:A([`reference`,`extends`,`includes`,`triggers`]).describe(`How the dependency is formed`)}));W(()=>G.extend({data:kF.describe(`Full Object Schema`)})),W(()=>G.extend({data:SN.describe(`Full App Configuration`)})),W(()=>G.extend({data:w(T({name:v(),label:v(),icon:v().optional(),description:v().optional()})).describe(`List of available concepts (Objects, Apps, Flows)`)})),W(()=>T({type:zF.describe(`Metadata type`),name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Item name (snake_case)`),data:k(v(),S()).describe(`Metadata payload`),namespace:v().optional().describe(`Optional namespace`)})),W(()=>G.extend({data:T({type:v().describe(`Metadata type`),name:v().describe(`Item name`),definition:k(v(),S()).describe(`Metadata definition payload`)}).describe(`Metadata item`)})),W(()=>G.extend({data:w(k(v(),S())).describe(`Array of metadata definitions`)})),W(()=>G.extend({data:w(v()).describe(`Array of metadata item names`)})),W(()=>G.extend({data:T({exists:b().describe(`Whether the item exists`)})})),W(()=>G.extend({data:T({type:v().describe(`Metadata type`),name:v().describe(`Deleted item name`)})})),W(()=>VF.describe(`Metadata query with filtering, sorting, and pagination`)),W(()=>G.extend({data:HF.describe(`Paginated query result`)})),W(()=>T({items:w(T({type:v().describe(`Metadata type`),name:v().describe(`Item name`),data:k(v(),S()).describe(`Metadata payload`)})).min(1).describe(`Items to register`),continueOnError:b().default(!1).describe(`Continue on individual failure`),validate:b().default(!0).describe(`Validate before registering`)})),W(()=>T({items:w(T({type:v().describe(`Metadata type`),name:v().describe(`Item name`)})).min(1).describe(`Items to unregister`)})),W(()=>G.extend({data:GF.describe(`Bulk operation result`)})),W(()=>G.extend({data:FF.optional().describe(`Overlay definition, undefined if none`)})),W(()=>FF.describe(`Overlay to save`)),W(()=>G.extend({data:k(v(),S()).optional().describe(`Effective metadata with all overlays applied`)})),W(()=>T({types:w(v()).optional().describe(`Filter by metadata types`),namespaces:w(v()).optional().describe(`Filter by namespaces`),format:A([`json`,`yaml`]).default(`json`).describe(`Export format`)})),W(()=>G.extend({data:S().describe(`Exported metadata bundle`)})),W(()=>T({data:S().describe(`Metadata bundle to import`),conflictResolution:A([`skip`,`overwrite`,`merge`]).default(`skip`).describe(`Conflict resolution strategy`),validate:b().default(!0).describe(`Validate before import`),dryRun:b().default(!1).describe(`Dry run (no save)`)})),W(()=>G.extend({data:T({total:y().int().min(0),imported:y().int().min(0),skipped:y().int().min(0),failed:y().int().min(0),errors:w(T({type:v(),name:v(),error:v()})).optional()}).describe(`Import result`)})),W(()=>T({type:v().describe(`Metadata type to validate against`),data:S().describe(`Metadata payload to validate`)})),W(()=>G.extend({data:UF.describe(`Validation result`)})),W(()=>G.extend({data:w(v()).describe(`Registered metadata type identifiers`)})),W(()=>G.extend({data:T({type:v().describe(`Metadata type identifier`),label:v().describe(`Display label`),description:v().optional().describe(`Description`),filePatterns:w(v()).describe(`File glob patterns`),supportsOverlay:b().describe(`Overlay support`),domain:v().describe(`Protocol domain`),actions:w(dF).optional().describe(`Declarative type-level actions (buttons) the metadata-admin UI renders for this type`)}).optional().describe(`Type info`)})),W(()=>G.extend({data:w(KF).describe(`Items this item depends on`)})),W(()=>G.extend({data:w(KF).describe(`Items that depend on this item`)}));var qF=A([`metadata`,`data`,`auth`,`file-storage`,`search`,`cache`,`queue`,`automation`,`graphql`,`analytics`,`realtime`,`job`,`notification`,`ai`,`i18n`,`ui`,`workflow`]),JF=W(()=>A([`required`,`core`,`optional`]));W(()=>T({name:qF,enabled:b(),status:A([`running`,`stopped`,`degraded`,`initializing`]),version:v().optional(),provider:v().optional().describe(`Implementation provider (e.g. "s3" for storage)`),features:w(v()).optional().describe(`List of supported sub-features`)})),W(()=>k(qF,S().describe(`Service Instance implementing the protocol interface`))),W(()=>T({id:v(),name:qF,options:k(v(),S()).optional()}));var YF=T({prefix:v().regex(/^\//).describe(`URL path prefix for routing (e.g. /api/v1/data)`),service:qF.describe(`Target core service name`),authRequired:b().default(!0).describe(`Whether authentication is required`),criticality:JF.default(`optional`).describe(`Service criticality level for unavailability handling`),permissions:w(v()).optional().describe(`Required permissions for this route namespace`)});T({routes:w(YF).describe(`Route-to-service mappings`),fallback:A([`404`,`proxy`,`custom`]).default(`404`).describe(`Behavior when no route matches`),proxyTarget:v().url().optional().describe(`Proxy target URL when fallback is "proxy"`)}),A([`404`,`405`,`501`,`503`]).describe(`404 = route not found, 405 = method not allowed, 501 = not implemented (stub), 503 = service unavailable`),T({success:j(!1),error:T({code:y().int().describe(`HTTP status code (404, 405, 501, 503, …)`),message:v().describe(`Human-readable error message`),type:A([`ROUTE_NOT_FOUND`,`METHOD_NOT_ALLOWED`,`NOT_IMPLEMENTED`,`SERVICE_UNAVAILABLE`]).optional().describe(`Machine-readable error type`),route:v().optional().describe(`Requested route path`),service:v().optional().describe(`Target service name, if resolvable`),hint:v().optional().describe(`Actionable hint for the developer (e.g., "Install plugin-workflow")`)})});var XF=W(()=>T({port:y().int().min(1).max(65535).default(3e3).describe(`Port number to listen on`),host:v().default(`0.0.0.0`).describe(`Host address to bind to`),cors:Ck.optional().describe(`CORS configuration`),requestTimeout:y().int().default(3e4).describe(`Request timeout in milliseconds`),bodyLimit:v().default(`10mb`).describe(`Maximum request body size`),compression:b().default(!0).describe(`Enable response compression`),security:T({helmet:b().default(!0).describe(`Enable security headers via helmet`),rateLimit:wk.optional().describe(`Global rate limiting configuration`)}).optional().describe(`Security configuration`),static:w(Tk).optional().describe(`Static file serving configuration`),trustProxy:b().default(!1).describe(`Trust X-Forwarded-* headers`)}));W(()=>T({method:bk.describe(`HTTP method`),path:v().describe(`URL path pattern`),handler:v().describe(`Handler identifier or name`),metadata:T({summary:v().optional().describe(`Route summary for documentation`),description:v().optional().describe(`Route description`),tags:w(v()).optional().describe(`Tags for grouping`),operationId:v().optional().describe(`Unique operation identifier`)}).optional(),security:T({authRequired:b().default(!0).describe(`Require authentication`),permissions:w(v()).optional().describe(`Required permissions`),rateLimit:v().optional().describe(`Rate limit policy override`)}).optional()}));var ZF=A([`authentication`,`authorization`,`logging`,`validation`,`transformation`,`error`,`custom`]),QF=W(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Middleware name (snake_case)`),type:ZF.describe(`Middleware type`),enabled:b().default(!0).describe(`Whether middleware is enabled`),order:y().int().default(100).describe(`Execution order priority`),config:k(v(),S()).optional().describe(`Middleware configuration object`),paths:T({include:w(v()).optional().describe(`Include path patterns (glob)`),exclude:w(v()).optional().describe(`Exclude path patterns (glob)`)}).optional().describe(`Path filtering`)})),$F=A([`starting`,`started`,`stopping`,`stopped`,`request`,`response`,`error`]);W(()=>T({type:$F.describe(`Event type`),timestamp:v().datetime().describe(`Event timestamp (ISO 8601)`),data:k(v(),S()).optional().describe(`Event-specific data`)})),W(()=>T({httpVersions:w(A([`1.0`,`1.1`,`2.0`,`3.0`])).default([`1.1`]).describe(`Supported HTTP versions`),websocket:b().default(!1).describe(`WebSocket support`),sse:b().default(!1).describe(`Server-Sent Events support`),serverPush:b().default(!1).describe(`HTTP/2 Server Push support`),streaming:b().default(!0).describe(`Response streaming support`),middleware:b().default(!0).describe(`Middleware chain support`),routeParams:b().default(!0).describe(`URL parameter support (/users/:id)`),compression:b().default(!0).describe(`Built-in compression support`)})),W(()=>T({state:A([`stopped`,`starting`,`running`,`stopping`,`error`]).describe(`Current server state`),uptime:y().int().optional().describe(`Server uptime in milliseconds`),server:T({port:y().int().describe(`Listening port`),host:v().describe(`Bound host`),url:v().optional().describe(`Full server URL`)}).optional(),connections:T({active:y().int().describe(`Active connections`),total:y().int().describe(`Total connections handled`)}).optional(),requests:T({total:y().int().describe(`Total requests processed`),success:y().int().describe(`Successful requests`),errors:y().int().describe(`Failed requests`)}).optional()})),Object.assign(XF,{create:e=>e}),Object.assign(QF,{create:e=>e});var eI=A([`discovery`,`metadata`,`data`,`batch`,`permission`,`analytics`,`automation`,`workflow`,`ui`,`realtime`,`notification`,`ai`,`i18n`]),tI=W(()=>A([`implemented`,`stub`,`planned`])),nI=W(()=>T({method:bk.describe(`HTTP method for this endpoint`),path:v().describe(`URL path pattern (e.g., /api/v1/data/:object/:id)`),handler:v().describe(`Protocol method name or handler identifier`),category:eI.describe(`Route category`),public:b().default(!1).describe(`Is publicly accessible without authentication`),permissions:w(v()).optional().describe(`Required permissions (e.g., ["data.read", "object.account.read"])`),summary:v().optional().describe(`Short description for OpenAPI`),description:v().optional().describe(`Detailed description for OpenAPI`),tags:w(v()).optional().describe(`OpenAPI tags for grouping`),requestSchema:v().optional().describe(`Request schema name (for validation)`),responseSchema:v().optional().describe(`Response schema name (for documentation)`),timeout:y().int().optional().describe(`Request timeout in milliseconds`),rateLimit:v().optional().describe(`Rate limit policy name`),cacheable:b().default(!1).describe(`Whether response can be cached`),cacheTtl:y().int().optional().describe(`Cache TTL in seconds`),handlerStatus:tI.optional().describe(`Handler implementation status: implemented (default if omitted), stub, or planned`)})),rI=T({prefix:v().regex(/^\//).describe(`URL path prefix for this route group`),service:v().describe(`Core service name (metadata, data, auth, etc.)`),category:eI.describe(`Primary category for this route group`),methods:w(v()).optional().describe(`Protocol method names implemented`),endpoints:w(nI).optional().describe(`Endpoint definitions`),middleware:w(QF).optional().describe(`Middleware stack for this route group`),authRequired:b().default(!0).describe(`Whether authentication is required by default`),documentation:T({title:v().optional().describe(`Route group title`),description:v().optional().describe(`Route group description`),tags:w(v()).optional().describe(`OpenAPI tags`)}).optional().describe(`Documentation metadata for this route group`)}),iI=A([`strict`,`permissive`,`strip`]),aI=T({enabled:b().default(!0).describe(`Enable automatic request validation`),mode:iI.default(`strict`).describe(`How to handle validation errors`),validateBody:b().default(!0).describe(`Validate request body against schema`),validateQuery:b().default(!0).describe(`Validate query string parameters`),validateParams:b().default(!0).describe(`Validate URL path parameters`),validateHeaders:b().default(!1).describe(`Validate request headers`),includeFieldErrors:b().default(!0).describe(`Include field-level error details in response`),errorPrefix:v().optional().describe(`Custom prefix for validation error messages`),schemaRegistry:v().optional().describe(`Schema registry name to use for validation`)}),oI=T({enabled:b().default(!0).describe(`Enable automatic response envelope wrapping`),includeMetadata:b().default(!0).describe(`Include meta object in responses`),includeTimestamp:b().default(!0).describe(`Include timestamp in response metadata`),includeRequestId:b().default(!0).describe(`Include requestId in response metadata`),includeDuration:b().default(!1).describe(`Include request duration in ms`),includeTraceId:b().default(!1).describe(`Include distributed traceId`),customMetadata:k(v(),S()).optional().describe(`Additional metadata fields to include`),skipIfWrapped:b().default(!0).describe(`Skip wrapping if response already has success field`)}),sI=T({enabled:b().default(!0).describe(`Enable standardized error handling`),includeStackTrace:b().default(!1).describe(`Include stack traces in error responses`),logErrors:b().default(!0).describe(`Log errors to system logger`),exposeInternalErrors:b().default(!1).describe(`Expose internal error details in responses`),includeRequestId:b().default(!0).describe(`Include requestId in error responses`),includeTimestamp:b().default(!0).describe(`Include timestamp in error responses`),includeDocumentation:b().default(!0).describe(`Include documentation URLs for errors`),documentationBaseUrl:v().url().optional().describe(`Base URL for error documentation`),customErrorMessages:k(v(),v()).optional().describe(`Custom error messages by error code`),redactFields:w(v()).optional().describe(`Field names to redact from error details`)}),cI=T({enabled:b().default(!0).describe(`Enable automatic OpenAPI documentation generation`),version:A([`3.0.0`,`3.0.1`,`3.0.2`,`3.0.3`,`3.1.0`]).default(`3.0.3`).describe(`OpenAPI specification version`),title:v().default(`ObjectStack API`).describe(`API title`),description:v().optional().describe(`API description`),apiVersion:v().default(`1.0.0`).describe(`API version`),outputPath:v().default(`/api/docs/openapi.json`).describe(`URL path to serve OpenAPI JSON`),uiPath:v().default(`/api/docs`).describe(`URL path to serve documentation UI`),uiFramework:A([`swagger-ui`,`redoc`,`rapidoc`,`elements`]).default(`swagger-ui`).describe(`Documentation UI framework`),includeInternal:b().default(!1).describe(`Include internal endpoints in documentation`),generateSchemas:b().default(!0).describe(`Auto-generate schemas from Zod definitions`),includeExamples:b().default(!0).describe(`Include request/response examples`),servers:w(T({url:v().describe(`Server URL`),description:v().optional().describe(`Server description`)})).optional().describe(`Server URLs for API`),contact:T({name:v().optional(),url:v().url().optional(),email:v().email().optional()}).optional().describe(`API contact information`),license:T({name:v().describe(`License name`),url:v().url().optional().describe(`License URL`)}).optional().describe(`API license information`),securitySchemes:k(v(),T({type:A([`apiKey`,`http`,`oauth2`,`openIdConnect`]),scheme:v().optional(),bearerFormat:v().optional()})).optional().describe(`Security scheme definitions`)}),lI=T({enabled:b().default(!0).describe(`Enable REST API plugin`),basePath:v().default(`/api`).describe(`Base path for all API routes`),version:v().default(`v1`).describe(`API version identifier`),routes:w(rI).describe(`Route registrations`),validation:aI.optional().describe(`Request validation configuration`),responseEnvelope:oI.optional().describe(`Response envelope configuration`),errorHandling:sI.optional().describe(`Error handling configuration`),openApi:cI.optional().describe(`OpenAPI documentation configuration`),globalMiddleware:w(QF).optional().describe(`Global middleware stack`),cors:T({enabled:b().default(!0),origins:w(v()).optional(),methods:w(bk).optional(),credentials:b().default(!0)}).optional().describe(`CORS configuration`),performance:T({enableCompression:b().default(!0).describe(`Enable response compression`),enableETag:b().default(!0).describe(`Enable ETag generation`),enableCaching:b().default(!0).describe(`Enable HTTP caching`),defaultCacheTtl:y().int().default(300).describe(`Default cache TTL in seconds`)}).optional().describe(`Performance optimization settings`)});Object.assign(lI,{create:e=>e}),Object.assign(rI,{create:e=>e});var uI=T({path:v().describe(`Full URL path (e.g. /api/v1/analytics/query)`),method:bk.describe(`HTTP method (GET, POST, etc.)`),category:eI.describe(`Route category`),handlerStatus:tI.describe(`Handler status`),service:v().describe(`Target service name`),healthCheckPassed:b().optional().describe(`Whether the health check probe succeeded`)});T({timestamp:v().describe(`ISO 8601 timestamp`),adapter:v().describe(`Adapter name (e.g. "hono", "express", "nextjs")`),summary:T({total:y().int().describe(`Total declared endpoints`),implemented:y().int().describe(`Endpoints with real handlers`),stub:y().int().describe(`Endpoints with stub handlers (501)`),planned:y().int().describe(`Endpoints not yet implemented`)}),entries:w(uI).describe(`Per-endpoint coverage entries`)}),W(()=>A([`rest`,`graphql`,`odata`]));var dI=W(()=>T({operator:v().describe(`Unified DSL operator`),rest:v().optional().describe(`REST query parameter template`),graphql:v().optional().describe(`GraphQL where clause template`),odata:v().optional().describe(`OData $filter expression template`)})),fI=W(()=>T({filterStyle:A([`bracket`,`dot`,`flat`,`rsql`]).default(`bracket`).describe(`REST filter parameter encoding style`),pagination:T({limitParam:v().default(`limit`).describe(`Page size parameter name`),offsetParam:v().default(`offset`).describe(`Offset parameter name`),cursorParam:v().default(`cursor`).describe(`Cursor parameter name`),pageParam:v().default(`page`).describe(`Page number parameter name`)}).optional().describe(`Pagination parameter name mappings`),sorting:T({param:v().default(`sort`).describe(`Sort parameter name`),format:A([`comma`,`array`,`pipe`]).default(`comma`).describe(`Sort parameter encoding format`)}).optional().describe(`Sort parameter mapping`),fieldsParam:v().default(`fields`).describe(`Field selection parameter name`)})),pI=W(()=>T({filterArgName:v().default(`where`).describe(`GraphQL filter argument name`),filterStyle:A([`nested`,`flat`,`array`]).default(`nested`).describe(`GraphQL filter nesting style`),pagination:T({limitArg:v().default(`limit`).describe(`Page size argument name`),offsetArg:v().default(`offset`).describe(`Offset argument name`),firstArg:v().default(`first`).describe(`Relay "first" argument name`),afterArg:v().default(`after`).describe(`Relay "after" cursor argument name`)}).optional().describe(`Pagination argument name mappings`),sorting:T({argName:v().default(`orderBy`).describe(`Sort argument name`),format:A([`enum`,`array`]).default(`enum`).describe(`Sort argument format`)}).optional().describe(`Sort argument mapping`)})),mI=W(()=>T({version:A([`v2`,`v4`]).default(`v4`).describe(`OData version`),usePrefix:b().default(!0).describe(`Use $ prefix for system query options ($filter vs filter)`),stringFunctions:w(A([`contains`,`startswith`,`endswith`,`tolower`,`toupper`,`trim`,`concat`,`substring`,`length`])).optional().describe(`Supported OData string functions`),expand:T({enabled:b().default(!0).describe(`Enable $expand support`),maxDepth:y().int().min(1).default(3).describe(`Maximum expand depth`)}).optional().describe(`$expand configuration`)}));W(()=>T({operatorMappings:w(dI).optional().describe(`Custom operator mappings`),rest:fI.optional().describe(`REST query adapter configuration`),graphql:pI.optional().describe(`GraphQL query adapter configuration`),odata:mI.optional().describe(`OData query adapter configuration`)}));var hI=A([`comment`,`field_change`,`task`,`event`,`email`,`call`,`note`,`file`,`record_create`,`record_delete`,`approval`,`sharing`,`system`]),gI=W(()=>T({type:A([`user`,`team`,`record`]).describe(`Mention target type`),id:v().describe(`Target ID`),name:v().describe(`Display name for rendering`),offset:y().int().min(0).describe(`Character offset in body text`),length:y().int().min(1).describe(`Length of mention token in body text`)})),_I=W(()=>T({field:v().describe(`Field machine name`),fieldLabel:v().optional().describe(`Field display label`),oldValue:S().optional().describe(`Previous value`),newValue:S().optional().describe(`New value`),oldDisplayValue:v().optional().describe(`Human-readable old value`),newDisplayValue:v().optional().describe(`Human-readable new value`)})),vI=W(()=>T({emoji:v().describe(`Emoji character or shortcode (e.g., "👍", ":thumbsup:")`),userIds:w(v()).describe(`Users who reacted`),count:y().int().min(1).describe(`Total reaction count`)})),yI=W(()=>T({type:A([`user`,`system`,`service`,`automation`]).describe(`Actor type`),id:v().describe(`Actor ID`),name:v().optional().describe(`Actor display name`),avatarUrl:v().url().optional().describe(`Actor avatar URL`),source:v().optional().describe(`Source application (e.g., "Omni", "API", "Studio")`)})),bI=A([`public`,`internal`,`private`]),xI=W(()=>T({id:v().describe(`Feed item ID`),type:hI.describe(`Activity type`),object:v().describe(`Object name (e.g., "account")`),recordId:v().describe(`Record ID this feed item belongs to`),actor:yI.describe(`Who performed this action`),body:v().optional().describe(`Rich text body (Markdown supported)`),mentions:w(gI).optional().describe(`Mentioned users/teams/records`),changes:w(_I).optional().describe(`Field-level changes`),reactions:w(vI).optional().describe(`Emoji reactions on this item`),parentId:v().optional().describe(`Parent feed item ID for threaded replies`),replyCount:y().int().min(0).default(0).describe(`Number of replies`),pinned:b().default(!1).describe(`Whether the feed item is pinned to the top of the timeline`),pinnedAt:v().datetime().optional().describe(`Timestamp when the item was pinned`),pinnedBy:v().optional().describe(`User ID who pinned the item`),starred:b().default(!1).describe(`Whether the feed item is starred/bookmarked by the current user`),starredAt:v().datetime().optional().describe(`Timestamp when the item was starred`),visibility:bI.default(`public`).describe(`Visibility: public (all users), internal (team only), private (author + mentioned)`),createdAt:v().datetime().describe(`Creation timestamp`),updatedAt:v().datetime().optional().describe(`Last update timestamp`),editedAt:v().datetime().optional().describe(`When comment was last edited`),isEdited:b().default(!1).describe(`Whether comment has been edited`)}));A([`all`,`comments_only`,`changes_only`,`tasks_only`]);var SI=A([`comment`,`mention`,`field_change`,`task`,`approval`,`all`]),CI=A([`in_app`,`email`,`push`,`slack`]),wI=W(()=>T({object:v().describe(`Object name`),recordId:v().describe(`Record ID`),userId:v().describe(`Subscribing user ID`),events:w(SI).default([`all`]).describe(`Event types to receive notifications for`),channels:w(CI).default([`in_app`]).describe(`Notification delivery channels`),active:b().default(!0).describe(`Whether the subscription is active`),createdAt:v().datetime().describe(`Subscription creation timestamp`)})),TI=W(()=>T({object:v().describe(`Object name (e.g., "account")`),recordId:v().describe(`Record ID`)})),EI=W(()=>TI.extend({feedId:v().describe(`Feed item ID`)})),DI=A([`all`,`comments_only`,`changes_only`,`tasks_only`]);W(()=>TI.extend({type:DI.default(`all`).describe(`Filter by feed item category`),limit:y().int().min(1).max(100).default(20).describe(`Maximum number of items to return`),cursor:v().optional().describe(`Cursor for pagination (opaque string from previous response)`)})),W(()=>G.extend({data:T({items:w(xI).describe(`Feed items in reverse chronological order`),total:y().int().optional().describe(`Total feed items matching filter`),nextCursor:v().optional().describe(`Cursor for the next page`),hasMore:b().describe(`Whether more items are available`)})})),W(()=>TI.extend({type:hI.describe(`Type of feed item to create`),body:v().optional().describe(`Rich text body (Markdown supported)`),mentions:w(gI).optional().describe(`Mentioned users, teams, or records`),parentId:v().optional().describe(`Parent feed item ID for threaded replies`),visibility:bI.default(`public`).describe(`Visibility: public, internal, or private`)})),W(()=>G.extend({data:xI.describe(`The created feed item`)})),W(()=>EI.extend({body:v().optional().describe(`Updated rich text body`),mentions:w(gI).optional().describe(`Updated mentions`),visibility:bI.optional().describe(`Updated visibility`)})),W(()=>G.extend({data:xI.describe(`The updated feed item`)})),W(()=>EI),W(()=>G.extend({data:T({feedId:v().describe(`ID of the deleted feed item`)})})),W(()=>EI.extend({emoji:v().describe(`Emoji character or shortcode (e.g., "👍", ":thumbsup:")`)})),W(()=>G.extend({data:T({reactions:w(vI).describe(`Updated reaction list for the feed item`)})})),W(()=>EI.extend({emoji:v().describe(`Emoji character or shortcode to remove`)})),W(()=>G.extend({data:T({reactions:w(vI).describe(`Updated reaction list for the feed item`)})})),W(()=>EI),W(()=>G.extend({data:T({feedId:v().describe(`ID of the pinned feed item`),pinned:b().describe(`Whether the item is now pinned`),pinnedAt:v().datetime().describe(`Timestamp when pinned`)})})),W(()=>EI),W(()=>G.extend({data:T({feedId:v().describe(`ID of the unpinned feed item`),pinned:b().describe(`Whether the item is now pinned (should be false)`)})})),W(()=>EI),W(()=>G.extend({data:T({feedId:v().describe(`ID of the starred feed item`),starred:b().describe(`Whether the item is now starred`),starredAt:v().datetime().describe(`Timestamp when starred`)})})),W(()=>EI),W(()=>G.extend({data:T({feedId:v().describe(`ID of the unstarred feed item`),starred:b().describe(`Whether the item is now starred (should be false)`)})})),W(()=>TI.extend({query:v().min(1).describe(`Full-text search query against feed body content`),type:DI.optional().describe(`Filter by feed item category`),actorId:v().optional().describe(`Filter by actor user ID`),dateFrom:v().datetime().optional().describe(`Filter feed items created after this timestamp`),dateTo:v().datetime().optional().describe(`Filter feed items created before this timestamp`),hasAttachments:b().optional().describe(`Filter for items with file attachments`),pinnedOnly:b().optional().describe(`Return only pinned items`),starredOnly:b().optional().describe(`Return only starred items`),limit:y().int().min(1).max(100).default(20).describe(`Maximum number of items to return`),cursor:v().optional().describe(`Cursor for pagination`)})),W(()=>G.extend({data:T({items:w(xI).describe(`Matching feed items sorted by relevance`),total:y().int().optional().describe(`Total matching items`),nextCursor:v().optional().describe(`Cursor for the next page`),hasMore:b().describe(`Whether more items are available`)})})),W(()=>TI.extend({field:v().optional().describe(`Filter changelog to a specific field name`),actorId:v().optional().describe(`Filter changelog by actor user ID`),dateFrom:v().datetime().optional().describe(`Filter changes after this timestamp`),dateTo:v().datetime().optional().describe(`Filter changes before this timestamp`),limit:y().int().min(1).max(200).default(50).describe(`Maximum number of changelog entries to return`),cursor:v().optional().describe(`Cursor for pagination`)}));var OI=W(()=>T({id:v().describe(`Changelog entry ID`),object:v().describe(`Object name`),recordId:v().describe(`Record ID`),actor:T({type:A([`user`,`system`,`service`,`automation`]).describe(`Actor type`),id:v().describe(`Actor ID`),name:v().optional().describe(`Actor display name`)}).describe(`Who made the change`),changes:w(_I).min(1).describe(`Field-level changes`),timestamp:v().datetime().describe(`When the change occurred`),source:v().optional().describe(`Change source (e.g., "API", "UI", "automation")`)}));W(()=>G.extend({data:T({entries:w(OI).describe(`Changelog entries in reverse chronological order`),total:y().int().optional().describe(`Total changelog entries matching filter`),nextCursor:v().optional().describe(`Cursor for the next page`),hasMore:b().describe(`Whether more entries are available`)})})),W(()=>TI.extend({events:w(SI).default([`all`]).describe(`Event types to subscribe to`),channels:w(CI).default([`in_app`]).describe(`Notification delivery channels`)})),W(()=>G.extend({data:wI.describe(`The created or updated subscription`)})),W(()=>TI),W(()=>G.extend({data:T({object:v().describe(`Object name`),recordId:v().describe(`Record ID`),unsubscribed:b().describe(`Whether the user was unsubscribed`)})})),A([`feed_item_not_found`,`feed_permission_denied`,`feed_item_not_editable`,`feed_invalid_parent`,`reaction_already_exists`,`reaction_not_found`,`subscription_already_exists`,`subscription_not_found`,`invalid_feed_type`,`feed_already_pinned`,`feed_not_pinned`,`feed_already_starred`,`feed_not_starred`,`feed_search_query_too_short`]);var kI=A([`csv`,`json`,`jsonl`,`xlsx`,`parquet`]),AI=A([`pending`,`processing`,`completed`,`failed`,`cancelled`,`expired`]),jI=W(()=>T({object:v().describe(`Object name to export`),format:kI.default(`csv`).describe(`Export file format`),fields:w(v()).optional().describe(`Specific fields to include (omit for all fields)`),filter:k(v(),S()).optional().describe(`Filter criteria for records to export`),sort:w(T({field:v().describe(`Field name to sort by`),direction:A([`asc`,`desc`]).default(`asc`).describe(`Sort direction`)})).optional().describe(`Sort order for exported records`),limit:y().int().min(1).optional().describe(`Maximum number of records to export`),includeHeaders:b().default(!0).describe(`Include header row (CSV/XLSX)`),encoding:v().default(`utf-8`).describe(`Character encoding for the export file`),templateId:v().optional().describe(`Export template ID for predefined field mappings`)})),MI=W(()=>G.extend({data:T({jobId:v().describe(`Export job ID`),status:AI.describe(`Initial job status`),estimatedRecords:y().int().optional().describe(`Estimated total records`),createdAt:v().datetime().describe(`Job creation timestamp`)})})),NI=W(()=>G.extend({data:T({jobId:v().describe(`Export job ID`),status:AI.describe(`Current job status`),format:kI.describe(`Export format`),totalRecords:y().int().optional().describe(`Total records to export`),processedRecords:y().int().describe(`Records processed so far`),percentComplete:y().min(0).max(100).describe(`Export progress percentage`),fileSize:y().int().optional().describe(`Current file size in bytes`),downloadUrl:v().optional().describe(`Presigned download URL (available when status is "completed")`),downloadExpiresAt:v().datetime().optional().describe(`Download URL expiration timestamp`),error:T({code:v().describe(`Error code`),message:v().describe(`Error message`)}).optional().describe(`Error details if job failed`),startedAt:v().datetime().optional().describe(`Processing start timestamp`),completedAt:v().datetime().optional().describe(`Completion timestamp`)})})),PI=A([`strict`,`lenient`,`dry_run`]),FI=A([`skip`,`update`,`create_new`,`fail`]);W(()=>T({mode:PI.default(`strict`).describe(`Validation mode for the import`),deduplication:T({strategy:FI.default(`skip`).describe(`How to handle duplicate records`),matchFields:w(v()).min(1).describe(`Fields used to identify duplicates (e.g., "email", "external_id")`)}).optional().describe(`Deduplication configuration`),maxErrors:y().int().min(1).default(100).describe(`Maximum validation errors before aborting`),trimWhitespace:b().default(!0).describe(`Trim leading/trailing whitespace from string fields`),dateFormat:v().optional().describe(`Expected date format in import data (e.g., "YYYY-MM-DD")`),nullValues:w(v()).optional().describe(`Strings to treat as null (e.g., ["", "N/A", "null"])`)})),W(()=>G.extend({data:T({totalRecords:y().int().describe(`Total records in import file`),validRecords:y().int().describe(`Records that passed validation`),invalidRecords:y().int().describe(`Records that failed validation`),duplicateRecords:y().int().describe(`Duplicate records detected`),errors:w(T({row:y().int().describe(`Row number in the import file`),field:v().optional().describe(`Field that failed validation`),code:v().describe(`Validation error code`),message:v().describe(`Validation error message`)})).describe(`List of validation errors`),preview:w(k(v(),S())).optional().describe(`Preview of first N valid records (for dry_run mode)`)})}));var II=W(()=>T({sourceField:v().describe(`Field name in the source data (import) or object (export)`),targetField:v().describe(`Field name in the target object (import) or file column (export)`),targetLabel:v().optional().describe(`Display label for the target column (export)`),transform:A([`none`,`uppercase`,`lowercase`,`trim`,`date_format`,`lookup`]).default(`none`).describe(`Transformation to apply during mapping`),defaultValue:S().optional().describe(`Default value if source field is null/empty`),required:b().default(!1).describe(`Whether this field is required (import validation)`)}));W(()=>T({id:v().optional().describe(`Template ID (generated on save)`),name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Template machine name (snake_case)`),label:v().describe(`Human-readable template label`),description:v().optional().describe(`Template description`),object:v().describe(`Target object name`),direction:A([`import`,`export`,`bidirectional`]).describe(`Template direction`),format:kI.optional().describe(`Default file format for this template`),mappings:w(II).min(1).describe(`Field mapping entries`),createdAt:v().datetime().optional().describe(`Template creation timestamp`),updatedAt:v().datetime().optional().describe(`Last update timestamp`),createdBy:v().optional().describe(`User who created the template`)})),W(()=>T({id:v().optional().describe(`Scheduled export ID`),name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Schedule name (snake_case)`),label:v().optional().describe(`Human-readable label`),object:v().describe(`Object name to export`),format:kI.default(`csv`).describe(`Export file format`),fields:w(v()).optional().describe(`Fields to include`),filter:k(v(),S()).optional().describe(`Record filter criteria`),templateId:v().optional().describe(`Export template ID for field mappings`),schedule:T({cronExpression:xA.describe(`Cron expression for schedule`),timezone:v().default(`UTC`).describe(`IANA timezone`)}).describe(`Schedule timing configuration`),delivery:T({method:A([`email`,`storage`,`webhook`]).describe(`How to deliver the export file`),recipients:w(v()).optional().describe(`Email recipients (for email delivery)`),storagePath:v().optional().describe(`Storage path (for storage delivery)`),webhookUrl:v().optional().describe(`Webhook URL (for webhook delivery)`)}).describe(`Export delivery configuration`),enabled:b().default(!0).describe(`Whether the scheduled export is active`),lastRunAt:v().datetime().optional().describe(`Last execution timestamp`),nextRunAt:v().datetime().optional().describe(`Next scheduled execution`),createdAt:v().datetime().optional().describe(`Creation timestamp`),createdBy:v().optional().describe(`User who created the schedule`)}));var LI=W(()=>T({jobId:v().describe(`Export job ID`)})),RI=W(()=>G.extend({data:T({jobId:v().describe(`Export job ID`),downloadUrl:v().describe(`Presigned download URL`),fileName:v().describe(`Suggested file name`),fileSize:y().int().describe(`File size in bytes`),format:kI.describe(`Export file format`),expiresAt:v().datetime().describe(`Download URL expiration timestamp`),checksum:v().optional().describe(`File checksum (SHA-256)`)})})),zI=W(()=>T({object:v().optional().describe(`Filter by object name`),status:AI.optional().describe(`Filter by job status`),limit:y().int().min(1).max(100).default(20).describe(`Maximum number of jobs to return`),cursor:v().optional().describe(`Pagination cursor from a previous response`)})),BI=W(()=>T({jobId:v().describe(`Export job ID`),object:v().describe(`Object name that was exported`),status:AI.describe(`Current job status`),format:kI.describe(`Export file format`),totalRecords:y().int().optional().describe(`Total records exported`),fileSize:y().int().optional().describe(`File size in bytes`),createdAt:v().datetime().describe(`Job creation timestamp`),completedAt:v().datetime().optional().describe(`Completion timestamp`),createdBy:v().optional().describe(`User who initiated the export`)})),VI=W(()=>G.extend({data:T({jobs:w(BI).describe(`List of export jobs`),nextCursor:v().optional().describe(`Cursor for the next page`),hasMore:b().describe(`Whether more jobs are available`)})})),HI=W(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Schedule name (snake_case)`),label:v().optional().describe(`Human-readable label`),object:v().describe(`Object name to export`),format:kI.default(`csv`).describe(`Export file format`),fields:w(v()).optional().describe(`Fields to include`),filter:k(v(),S()).optional().describe(`Record filter criteria`),templateId:v().optional().describe(`Export template ID for field mappings`),schedule:T({cronExpression:xA.describe(`Cron expression for schedule`),timezone:v().default(`UTC`).describe(`IANA timezone`)}).describe(`Schedule timing configuration`),delivery:T({method:A([`email`,`storage`,`webhook`]).describe(`How to deliver the export file`),recipients:w(v()).optional().describe(`Email recipients (for email delivery)`),storagePath:v().optional().describe(`Storage path (for storage delivery)`),webhookUrl:v().optional().describe(`Webhook URL (for webhook delivery)`)}).describe(`Export delivery configuration`)})),UI=W(()=>G.extend({data:T({id:v().describe(`Scheduled export ID`),name:v().describe(`Schedule name`),enabled:b().describe(`Whether the schedule is active`),nextRunAt:v().datetime().optional().describe(`Next scheduled execution`),createdAt:v().datetime().describe(`Creation timestamp`)})}));T({jobId:v()}),T({jobId:v()}),A([`start`,`end`,`decision`,`assignment`,`loop`,`create_record`,`update_record`,`delete_record`,`get_record`,`http`,`notify`,`script`,`screen`,`wait`,`subflow`,`map`,`connector_action`,`parallel_gateway`,`join_gateway`,`boundary_event`]).options;var WI=W(()=>T({name:v().describe(`Variable name`),type:v().describe(`Data type (text, number, boolean, object, list)`),isInput:b().default(!1).describe(`Is input parameter`),isOutput:b().default(!1).describe(`Is output parameter`)})),GI=W(()=>T({id:v().describe(`Node unique ID`),type:v().min(1).describe(`Action type — a built-in FlowNodeAction id or a plugin-registered node type. Validated against the live action registry at registerFlow() (ADR-0018), not by a closed enum.`),label:v().describe(`Node label`),config:k(v(),S()).optional().describe(`Node configuration`),connectorConfig:T({connectorId:v(),actionId:v(),input:k(v(),S()).describe(`Mapped inputs for the action`)}).optional(),position:T({x:y(),y:y()}).optional(),timeoutMs:y().int().min(0).optional().describe(`Maximum execution time for this node in milliseconds`),inputSchema:k(v(),T({type:A([`string`,`number`,`boolean`,`object`,`array`]).describe(`Parameter type`),required:b().default(!1).describe(`Whether the parameter is required`),description:v().optional().describe(`Parameter description`)})).optional().describe(`Input parameter schema for this node`),outputSchema:k(v(),T({type:A([`string`,`number`,`boolean`,`object`,`array`]).describe(`Output type`),description:v().optional().describe(`Output description`)})).optional().describe(`Output schema declaration for this node`),waitEventConfig:T({eventType:A([`timer`,`signal`,`webhook`,`manual`,`condition`]).describe(`What kind of event resumes the execution`),timerDuration:v().optional().describe(`ISO 8601 duration (e.g., "PT1H") or wait time for timer events`),signalName:v().optional().describe(`Named signal or webhook event to wait for`),timeoutMs:y().int().min(0).optional().describe(`Maximum wait time before timeout (ms)`),onTimeout:A([`fail`,`continue`]).default(`fail`).describe(`Behavior when the wait times out`)}).optional().describe(`Configuration for wait node event resumption`),boundaryConfig:T({attachedToNodeId:v().describe(`Host node ID this boundary event monitors`),eventType:A([`error`,`timer`,`signal`,`cancel`]).describe(`Boundary event trigger type`),interrupting:b().default(!0).describe(`If true, the host activity is cancelled when this event fires`),errorCode:v().optional().describe(`Specific error code to catch (empty = catch all errors)`),timerDuration:v().optional().describe(`ISO 8601 duration for timer boundary events`),signalName:v().optional().describe(`Named signal to catch`)}).optional().describe(`Configuration for boundary events attached to host nodes`)})),KI=W(()=>T({id:v().describe(`Edge unique ID`),source:v().describe(`Source Node ID`),target:v().describe(`Target Node ID`),condition:bA.optional().describe(`Predicate (CEL) returning boolean used for branching.`),type:A([`default`,`fault`,`conditional`,`back`]).default(`default`).describe(`Connection type: default (normal flow), fault (error path), conditional (expression-guarded), or back (ADR-0044 declared back-edge — traversed normally at run time, but excluded from DAG cycle validation so a revise/rework loop can re-enter an earlier node)`),label:v().optional().describe(`Label on the connector`),isDefault:b().default(!1).describe(`Marks this edge as the default path when no other conditions match`)})),qI=W(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Machine name`),label:v().describe(`Flow label`),description:v().optional(),successMessage:v().optional().describe(`Toast shown when a screen flow completes (defaults to a generic "Done").`),errorMessage:v().optional().describe(`Toast shown when a screen flow fails (defaults to the raw error).`),version:y().int().default(1).describe(`Version number`),status:A([`draft`,`active`,`obsolete`,`invalid`]).default(`draft`).describe(`Deployment status`),template:b().default(!1).describe(`Is logic template (Subflow)`),type:A([`autolaunched`,`record_change`,`schedule`,`screen`,`api`]).describe(`Flow type`),variables:w(WI).optional().describe(`Flow variables`),nodes:w(GI).describe(`Flow nodes`),edges:w(KI).describe(`Flow connections`),active:b().default(!1).describe(`Is active (Deprecated: use status)`),runAs:A([`system`,`user`]).default(`user`).describe(`Execution identity for the run: system = elevated (bypasses RLS), user = the triggering user (RLS-respecting). A schedule-triggered run has no trigger user, so under user it runs UNSCOPED (elevated) — declare system to make that explicit.`),errorHandling:T({strategy:A([`fail`,`retry`,`continue`]).default(`fail`).describe(`How to handle node execution errors`),maxRetries:y().int().min(0).max(10).default(0).describe(`Number of retry attempts (only for retry strategy)`),retryDelayMs:y().int().min(0).default(1e3).describe(`Delay between retries in milliseconds`),backoffMultiplier:y().min(1).default(1).describe(`Multiplier for exponential backoff between retries`),maxRetryDelayMs:y().int().min(0).default(3e4).describe(`Maximum delay between retries in milliseconds`),jitter:b().default(!1).describe(`Add random jitter to retry delay to avoid thundering herd`),fallbackNodeId:v().optional().describe(`Node ID to jump to on unrecoverable error`)}).optional().describe(`Flow-level error handling configuration`),protection:uj.optional().describe(`Package author protection block — lock policy for this flow.`),...lj}));W(()=>T({flowName:v().describe(`Flow machine name`),version:y().int().min(1).describe(`Version number`),definition:qI.describe(`Complete flow definition snapshot`),createdAt:v().datetime().describe(`When this version was created`),createdBy:v().optional().describe(`User who created this version`),changeNote:v().optional().describe(`Description of what changed in this version`)}));var JI=A([`pending`,`running`,`paused`,`completed`,`failed`,`cancelled`,`timed_out`,`retrying`]),YI=W(()=>T({nodeId:v().describe(`Node ID that was executed`),nodeType:v().describe(`Node action type (e.g., "decision", "http")`),nodeLabel:v().optional().describe(`Human-readable node label`),status:A([`success`,`failure`,`skipped`]).describe(`Step execution result`),startedAt:v().datetime().describe(`When the step started`),completedAt:v().datetime().optional().describe(`When the step completed`),durationMs:y().int().min(0).optional().describe(`Step execution duration in milliseconds`),input:k(v(),S()).optional().describe(`Input data passed to the node`),output:k(v(),S()).optional().describe(`Output data produced by the node`),error:T({code:v().describe(`Error code`),message:v().describe(`Error message`),stack:v().optional().describe(`Stack trace`)}).optional().describe(`Error details if step failed`),retryAttempt:y().int().min(0).optional().describe(`Retry attempt number (0 = first try)`),parentNodeId:v().optional().describe(`Enclosing structured-region container node ID (loop/parallel/try_catch)`),iteration:y().int().min(0).optional().describe(`Zero-based loop iteration or parallel branch index of the enclosing region`),regionKind:v().optional().describe(`Region kind the step ran in: loop-body | parallel-branch | try | catch`)})),XI=W(()=>T({id:v().describe(`Execution instance ID`),flowName:v().describe(`Machine name of the executed flow`),flowVersion:y().int().optional().describe(`Version of the flow that was executed`),status:JI.describe(`Current execution status`),trigger:T({type:v().describe(`Trigger type (e.g., "record_change", "schedule", "api", "manual")`),recordId:v().optional().describe(`Triggering record ID`),object:v().optional().describe(`Triggering object name`),userId:v().optional().describe(`User who triggered the execution`),metadata:k(v(),S()).optional().describe(`Additional trigger context`)}).describe(`What triggered this execution`),steps:w(YI).describe(`Ordered list of executed steps`),variables:k(v(),S()).optional().describe(`Final state of flow variables`),startedAt:v().datetime().describe(`Execution start timestamp`),completedAt:v().datetime().optional().describe(`Execution completion timestamp`),durationMs:y().int().min(0).optional().describe(`Total execution duration in milliseconds`),runAs:A([`system`,`user`]).optional().describe(`Execution context identity`),tenantId:v().optional().describe(`Tenant ID for multi-tenant isolation`)})),ZI=A([`warning`,`error`,`critical`]);W(()=>T({id:v().describe(`Error record ID`),executionId:v().describe(`Parent execution ID`),nodeId:v().optional().describe(`Node where the error occurred`),severity:ZI.describe(`Error severity level`),code:v().describe(`Machine-readable error code`),message:v().describe(`Human-readable error message`),stack:v().optional().describe(`Stack trace for debugging`),context:k(v(),S()).optional().describe(`Additional diagnostic context (input data, config snapshot)`),timestamp:v().datetime().describe(`When the error occurred`),retryable:b().default(!1).describe(`Whether this error can be retried`),resolvedAt:v().datetime().optional().describe(`When the error was resolved (e.g., after successful retry)`)})),W(()=>T({id:v().describe(`Checkpoint ID`),executionId:v().describe(`Parent execution ID`),flowName:v().describe(`Flow machine name`),currentNodeId:v().describe(`Node ID where execution is paused`),variables:k(v(),S()).describe(`Flow variable state at checkpoint`),completedNodeIds:w(v()).describe(`List of node IDs already executed`),createdAt:v().datetime().describe(`Checkpoint creation timestamp`),expiresAt:v().datetime().optional().describe(`Checkpoint expiration (auto-cleanup)`),reason:A([`wait`,`screen_input`,`approval`,`error`,`manual_pause`,`parallel_join`,`boundary_event`]).describe(`Why the execution was checkpointed`)})),W(()=>T({maxConcurrent:y().int().min(1).default(1).describe(`Maximum number of concurrent executions allowed`),onConflict:A([`queue`,`reject`,`cancel_existing`]).default(`queue`).describe(`queue = enqueue for later, reject = fail immediately, cancel_existing = stop running instance`),lockScope:A([`global`,`per_record`,`per_user`]).default(`global`).describe(`Scope of the concurrency lock`),queueTimeoutMs:y().int().min(0).optional().describe(`Maximum time to wait in queue before timing out (ms)`)})),W(()=>T({id:v().describe(`Schedule instance ID`),flowName:v().describe(`Flow machine name`),cronExpression:xA.describe("Cron expression — cron`0 9 * * MON-FRI`"),timezone:v().default(`UTC`).describe(`IANA timezone for cron evaluation`),status:A([`active`,`paused`,`disabled`,`expired`]).default(`active`).describe(`Current schedule status`),nextRunAt:v().datetime().optional().describe(`Next scheduled execution timestamp`),lastRunAt:v().datetime().optional().describe(`Last execution timestamp`),lastExecutionId:v().optional().describe(`Execution ID of the last run`),lastRunStatus:JI.optional().describe(`Status of the last run`),totalRuns:y().int().min(0).default(0).describe(`Total number of executions`),consecutiveFailures:y().int().min(0).default(0).describe(`Consecutive failed executions`),startDate:v().datetime().optional().describe(`Schedule effective start date`),endDate:v().datetime().optional().describe(`Schedule expiration date`),maxRuns:y().int().min(1).optional().describe(`Maximum total executions before auto-disable`),createdAt:v().datetime().describe(`Schedule creation timestamp`),updatedAt:v().datetime().optional().describe(`Last update timestamp`),createdBy:v().optional().describe(`User who created the schedule`)}));var QI=W(()=>T({name:v().describe(`Flow machine name (snake_case)`)})),$I=W(()=>QI.extend({runId:v().describe(`Execution run ID`)}));W(()=>T({status:A([`draft`,`active`,`obsolete`,`invalid`]).optional().describe(`Filter by flow status`),type:A([`autolaunched`,`record_change`,`schedule`,`screen`,`api`]).optional().describe(`Filter by flow type`),limit:y().int().min(1).max(100).default(50).describe(`Maximum number of flows to return`),cursor:v().optional().describe(`Cursor for pagination`)}));var eL=W(()=>T({name:v().describe(`Flow machine name`),label:v().describe(`Flow display label`),type:v().describe(`Flow type`),status:v().describe(`Flow deployment status`),version:y().int().describe(`Flow version number`),enabled:b().describe(`Whether the flow is enabled for execution`),nodeCount:y().int().optional().describe(`Number of nodes in the flow`),lastRunAt:v().datetime().optional().describe(`Last execution timestamp`)}));W(()=>G.extend({data:T({flows:w(eL).describe(`Flow summaries`),total:y().int().optional().describe(`Total matching flows`),nextCursor:v().optional().describe(`Cursor for the next page`),hasMore:b().describe(`Whether more flows are available`)})})),W(()=>QI),W(()=>G.extend({data:qI.describe(`Full flow definition`)})),W(()=>qI),W(()=>G.extend({data:qI.describe(`The created flow definition`)})),W(()=>QI.extend({definition:qI.partial().describe(`Partial flow definition to update`)})),W(()=>G.extend({data:qI.describe(`The updated flow definition`)})),W(()=>QI),W(()=>G.extend({data:T({name:v().describe(`Name of the deleted flow`),deleted:b().describe(`Whether the flow was deleted`)})})),W(()=>QI.extend({record:k(v(),S()).optional().describe(`Record that triggered the automation`),object:v().optional().describe(`Object name the record belongs to`),event:v().optional().describe(`Trigger event type`),userId:v().optional().describe(`User who triggered the automation`),params:k(v(),S()).optional().describe(`Additional contextual data`)})),W(()=>G.extend({data:T({success:b().describe(`Whether the automation completed successfully`),output:S().optional().describe(`Output data from the automation`),error:v().optional().describe(`Error message if execution failed`),durationMs:y().optional().describe(`Execution duration in milliseconds`)})})),W(()=>QI.extend({enabled:b().describe(`Whether to enable (true) or disable (false) the flow`)})),W(()=>G.extend({data:T({name:v().describe(`Flow name`),enabled:b().describe(`New enabled state`)})})),W(()=>QI.extend({status:A([`pending`,`running`,`paused`,`completed`,`failed`,`cancelled`,`timed_out`,`retrying`]).optional().describe(`Filter by execution status`),limit:y().int().min(1).max(100).default(20).describe(`Maximum number of runs to return`),cursor:v().optional().describe(`Cursor for pagination`)})),W(()=>G.extend({data:T({runs:w(XI).describe(`Execution run logs`),total:y().int().optional().describe(`Total matching runs`),nextCursor:v().optional().describe(`Cursor for the next page`),hasMore:b().describe(`Whether more runs are available`)})})),W(()=>$I),W(()=>G.extend({data:XI.describe(`Full execution log with step details`)})),A([`flow_not_found`,`flow_already_exists`,`flow_validation_failed`,`flow_disabled`,`execution_not_found`,`execution_failed`,`execution_timeout`,`node_executor_not_found`,`concurrent_execution_limit`]);var tL=W(()=>A([`added`,`modified`,`removed`,`renamed`]).describe(`Type of metadata change between package versions`)),nL=W(()=>T({type:v().describe(`Metadata type`),name:v().describe(`Metadata name`),changeType:tL.describe(`Category of metadata modification (added, modified, removed, or renamed)`),hasConflict:b().default(!1).describe(`Whether this change may conflict with customizations`),summary:v().optional().describe(`Human-readable change summary`),previousName:v().optional().describe(`Previous name if renamed`)}).describe(`Single metadata change between package versions`)),rL=W(()=>A([`none`,`low`,`medium`,`high`,`critical`]).describe(`Severity of upgrade impact`)),iL=W(()=>T({packageId:v().describe(`Package identifier`),fromVersion:v().describe(`Currently installed version`),toVersion:v().describe(`Target upgrade version`),impactLevel:rL.describe(`Severity assessment from none (seamless) to critical (breaking changes)`),changes:w(nL).describe(`All metadata changes`),affectedCustomizations:y().int().min(0).default(0).describe(`Count of customizations that may be affected`),requiresMigration:b().default(!1).describe(`Whether data migration scripts are needed`),migrationScripts:w(v()).optional().describe(`Paths to migration scripts`),dependencyUpgrades:w(T({packageId:v(),fromVersion:v(),toVersion:v()})).optional().describe(`Dependent packages that also need upgrading`),estimatedDuration:y().int().min(0).optional().describe(`Estimated upgrade duration in seconds`),summary:v().optional().describe(`Human-readable upgrade summary`)}).describe(`Upgrade analysis plan generated before execution`));W(()=>T({id:v().describe(`Snapshot identifier`),packageId:v().describe(`Package identifier`),fromVersion:v().describe(`Version before upgrade`),toVersion:v().describe(`Target upgrade version`),tenantId:v().optional().describe(`Tenant identifier`),previousManifest:kN.describe(`Complete manifest of the previous package version`),metadataSnapshot:w(T({type:v(),name:v(),metadata:k(v(),S())})).describe(`Snapshot of all package metadata`),customizationSnapshot:w(k(v(),S())).optional().describe(`Snapshot of customer customizations`),createdAt:v().datetime().describe(`Snapshot creation timestamp`),expiresAt:v().datetime().optional().describe(`Snapshot expiry timestamp`)}).describe(`Pre-upgrade state snapshot for rollback capability`)),W(()=>T({packageId:v().describe(`Package ID to upgrade`),targetVersion:v().optional().describe(`Target version (defaults to latest)`),manifest:kN.optional().describe(`New manifest (if installing from local)`),createSnapshot:b().default(!0).describe(`Whether to create a pre-upgrade backup snapshot`),mergeStrategy:A([`keep-custom`,`accept-incoming`,`three-way-merge`]).default(`three-way-merge`).describe(`How to handle customer customizations`),dryRun:b().default(!1).describe(`Preview upgrade without making changes`),skipValidation:b().default(!1).describe(`Skip pre-upgrade compatibility checks`)}).describe(`Upgrade package request`));var aL=W(()=>A([`pending`,`analyzing`,`snapshot`,`executing`,`migrating`,`validating`,`completed`,`failed`,`rolling-back`,`rolled-back`]).describe(`Current phase of the upgrade process`));W(()=>T({success:b().describe(`Whether the upgrade succeeded`),phase:aL.describe(`Current upgrade phase`),plan:iL.optional().describe(`Upgrade plan`),snapshotId:v().optional().describe(`Snapshot ID for rollback`),conflicts:w(T({path:v(),baseValue:S(),incomingValue:S(),customValue:S()})).optional().describe(`Unresolved merge conflicts`),errorMessage:v().optional().describe(`Error message if upgrade failed`),message:v().optional().describe(`Human-readable status message`)}).describe(`Upgrade package response`)),W(()=>T({packageId:v().describe(`Package ID to rollback`),snapshotId:v().describe(`Snapshot ID to restore from`),rollbackCustomizations:b().default(!0).describe(`Whether to restore pre-upgrade customizations`)}).describe(`Rollback package request`)),W(()=>T({success:b().describe(`Whether the rollback succeeded`),restoredVersion:v().optional().describe(`Version restored to`),message:v().optional().describe(`Rollback status message`)}).describe(`Rollback package response`));var oL=A([`objects`,`views`,`pages`,`flows`,`dashboards`,`permissions`,`agents`,`reports`,`actions`,`translations`,`themes`,`datasets`,`apis`,`triggers`,`workflows`]).describe(`Metadata category within the artifact`),sL=W(()=>T({path:v().describe(`Relative file path within the artifact`),size:y().int().nonnegative().describe(`File size in bytes`),category:oL.optional().describe(`Metadata category this file belongs to`)}).describe(`A single file entry within the artifact`)),cL=W(()=>T({algorithm:A([`sha256`,`sha384`,`sha512`]).default(`sha256`).describe(`Hash algorithm used for checksums`),files:k(v(),v().regex(/^[a-f0-9]+$/)).describe(`File path to hash value mapping`)}).describe(`Checksum manifest for artifact integrity verification`)),lL=W(()=>T({algorithm:A([`RSA-SHA256`,`RSA-SHA384`,`RSA-SHA512`,`ECDSA-SHA256`]).default(`RSA-SHA256`).describe(`Signing algorithm used`),publicKeyRef:v().describe(`Public key reference (URL or fingerprint) for signature verification`),signature:v().describe(`Base64-encoded digital signature`),signedAt:v().datetime().optional().describe(`ISO 8601 timestamp of when the artifact was signed`),signedBy:v().optional().describe(`Identity of the signer (publisher ID or email)`)}).describe(`Digital signature for artifact authenticity verification`)),uL=W(()=>T({formatVersion:v().regex(/^\d+\.\d+$/).default(`1.0`).describe(`Artifact format version (e.g. "1.0")`),packageId:v().describe(`Package identifier from manifest`),version:v().describe(`Package version from manifest`),format:A([`tgz`,`zip`]).default(`tgz`).describe(`Archive format of the artifact`),size:y().int().positive().optional().describe(`Total artifact file size in bytes`),builtAt:v().datetime().describe(`ISO 8601 timestamp of when the artifact was built`),builtWith:v().optional().describe(`Build tool identifier (e.g. "os-cli@3.2.0")`),files:w(sL).optional().describe(`List of files contained in the artifact`),metadataCategories:w(oL).optional().describe(`Metadata categories included in this artifact`),checksums:cL.optional().describe(`SHA256 checksums for artifact integrity verification`),signature:lL.optional().describe(`Digital signature for artifact authenticity verification`)}).describe(`Package artifact structure and metadata`)),dL=W(()=>A([`private`,`org`,`marketplace`]).describe(`Package visibility: private = owner org only; org = all envs in owner org; marketplace = public registry`)),fL=W(()=>v().min(1).describe(`Package category for marketplace discovery (e.g. "crm", "hr", "finance", "devtools")`)),pL=W(()=>A([`objectstack`,`partner`,`community`,`private`]).describe(`Package publisher provenance tier`)),mL=W(()=>v().regex(/^[a-z]{2,3}(-[A-Z]{2})?$/,`must be a BCP-47 locale (e.g. en, zh, zh-CN)`).describe(`BCP-47 locale tag`)),hL=W(()=>T({displayName:v().min(1).max(128).optional().describe(`Localized display name`),description:v().max(512).optional().describe(`Localized short description`),readme:v().optional().describe(`Localized long-form readme (markdown)`),tagline:v().max(120).optional().describe(`Localized short tagline (marketplace listing only)`),screenshotCaptions:k(v(),v()).optional().describe(`Per-index screenshot caption overrides`)}).describe(`Per-locale overrides for a package listing`)),gL=W(()=>k(mL,hL).describe(`Locale-keyed overrides; missing keys fall back to base columns`)),_L=W(()=>T({id:v().uuid().describe(`UUID of the package (stable, never reused)`),manifestId:v().regex(/^[a-z][a-z0-9-]*(\.[a-z][a-z0-9-]*)+$/).describe(`Globally unique reverse-domain package identifier (e.g. com.acme.crm)`),ownerOrgId:v().describe(`Organization ID of the package owner/publisher`),displayName:v().min(1).max(128).describe(`Display name shown in Studio and Marketplace`),description:v().max(512).optional().describe(`Short package description`),readme:v().optional().describe(`Long-form package documentation (markdown)`),visibility:dL.default(`private`),category:fL.optional(),tags:w(v()).optional().describe(`Search and filter tags`),iconUrl:v().url().optional().describe(`Package icon URL`),homepageUrl:v().url().optional().describe(`Package homepage URL`),license:v().optional().describe(`SPDX license identifier (e.g. MIT, Apache-2.0)`),publisher:pL.default(`private`),isStarter:b().default(!1).describe(`If true, surfaces in the Create Project blueprint picker as a starter template`),translations:gL.optional().describe(`Locale-keyed overrides for display_name / description / readme`),createdAt:v().datetime().describe(`Creation timestamp (ISO-8601)`),updatedAt:v().datetime().describe(`Last update timestamp (ISO-8601)`),createdBy:v().describe(`User ID that created the package`)}));W(()=>T({manifestId:_L.shape.manifestId,ownerOrgId:v().describe(`Owner organization ID`),displayName:_L.shape.displayName,description:_L.shape.description,visibility:dL.optional(),category:fL.optional(),tags:w(v()).optional(),iconUrl:v().url().optional(),homepageUrl:v().url().optional(),license:v().optional(),publisher:pL.optional(),isStarter:b().optional(),translations:gL.optional(),createdBy:v().describe(`User ID creating the package`)}).describe(`Register a new package in the Control Plane`)),W(()=>T({displayName:_L.shape.displayName.optional(),description:_L.shape.description,readme:_L.shape.readme,visibility:dL.optional(),category:fL.optional(),tags:w(v()).optional(),iconUrl:v().url().optional(),homepageUrl:v().url().optional(),license:v().optional(),publisher:pL.optional(),isStarter:b().optional(),translations:gL.optional()}).describe(`Update mutable package metadata`));var vL=W(()=>A([`unverified`,`pending`,`verified`,`trusted`,`partner`]).describe(`Publisher verification status`));W(()=>T({id:v().describe(`Publisher ID`),name:v().describe(`Publisher display name`),type:A([`individual`,`organization`]).describe(`Publisher type`),verification:vL.default(`unverified`).describe(`Publisher verification status`),email:v().email().optional().describe(`Contact email`),website:v().url().optional().describe(`Publisher website`),logoUrl:v().url().optional().describe(`Publisher logo URL`),description:v().optional().describe(`Publisher description`),registeredAt:v().datetime().optional().describe(`Publisher registration timestamp`)}).describe(`Developer or organization that publishes packages`));var yL=W(()=>T({url:v().url().describe(`Artifact download URL`),sha256:v().regex(/^[a-f0-9]{64}$/).describe(`SHA256 checksum`),size:y().int().positive().describe(`Artifact size in bytes`),format:A([`tgz`,`zip`]).default(`tgz`).describe(`Artifact format`),uploadedAt:v().datetime().describe(`Upload timestamp`)}).describe(`Reference to a downloadable package artifact`));W(()=>T({downloadUrl:v().url().describe(`Artifact download URL (may be pre-signed)`),sha256:v().regex(/^[a-f0-9]{64}$/).describe(`SHA256 checksum for verification`),size:y().int().positive().describe(`Artifact size in bytes`),format:A([`tgz`,`zip`]).describe(`Artifact format`),expiresAt:v().datetime().optional().describe(`URL expiration timestamp for pre-signed URLs`)}).describe(`Artifact download response with integrity metadata`));var bL=W(()=>A([`crm`,`erp`,`hr`,`finance`,`project`,`collaboration`,`analytics`,`integration`,`automation`,`ai`,`security`,`developer-tools`,`ui-theme`,`storage`,`other`]).describe(`Marketplace package category`)),xL=W(()=>A([`draft`,`submitted`,`in-review`,`approved`,`published`,`rejected`,`suspended`,`deprecated`,`unlisted`]).describe(`Marketplace listing status`)),SL=W(()=>A([`free`,`freemium`,`paid`,`subscription`,`usage-based`,`contact-sales`]).describe(`Package pricing model`)),CL=W(()=>T({id:v().describe(`Listing ID (matches package manifest ID)`),packageId:v().describe(`Package identifier`),packageType:A(aN).default(`app`).describe("Consumer-installable package type (ADR-0019: only `app` is listable)"),publisherId:v().describe(`Publisher ID`),status:xL.default(`draft`).describe(`Publication state: draft, published, under-review, suspended, deprecated, or unlisted`),name:v().describe(`Display name`),tagline:v().max(120).optional().describe(`Short tagline (max 120 chars)`),description:v().optional().describe(`Full description (Markdown)`),category:bL.describe(`Package category`),tags:w(v()).optional().describe(`Search tags`),iconUrl:v().url().optional().describe(`Package icon URL`),screenshots:w(T({url:v().url(),caption:v().optional()})).optional().describe(`Screenshots`),documentationUrl:v().url().optional().describe(`Documentation URL`),supportUrl:v().url().optional().describe(`Support URL`),repositoryUrl:v().url().optional().describe(`Source repository URL`),pricing:SL.default(`free`).describe(`Pricing model`),priceInCents:y().int().min(0).optional().describe(`Price in cents (e.g. 999 = $9.99)`),latestVersion:v().describe(`Latest published version`),minPlatformVersion:v().optional().describe(`Minimum ObjectStack platform version`),versions:w(T({version:v().describe(`Version string`),releaseDate:v().datetime().describe(`Release date`),releaseNotes:v().optional().describe(`Release notes`),minPlatformVersion:v().optional().describe(`Minimum platform version`),deprecated:b().default(!1).describe(`Whether this version is deprecated`),artifact:yL.optional().describe(`Downloadable artifact for this version`)})).optional().describe(`Published versions`),stats:T({totalInstalls:y().int().min(0).default(0).describe(`Total installs`),activeInstalls:y().int().min(0).default(0).describe(`Active installs`),averageRating:y().min(0).max(5).optional().describe(`Average user rating (0-5)`),totalRatings:y().int().min(0).default(0).describe(`Total ratings count`),totalReviews:y().int().min(0).default(0).describe(`Total reviews count`)}).optional().describe(`Aggregate marketplace statistics`),publishedAt:v().datetime().optional().describe(`First published timestamp`),updatedAt:v().datetime().optional().describe(`Last updated timestamp`),translations:gL.optional().describe(`Locale-keyed overrides for name / tagline / description / screenshot captions`)}).describe(`Public-facing package listing on the marketplace`));W(()=>T({id:v().describe(`Submission ID`),packageId:v().describe(`Package identifier`),version:v().describe(`Version being submitted`),publisherId:v().describe(`Publisher submitting`),status:A([`pending`,`scanning`,`in-review`,`changes-requested`,`approved`,`rejected`]).default(`pending`).describe(`Review status`),artifactUrl:v().describe(`Package artifact URL for review`),releaseNotes:v().optional().describe(`Release notes for this version`),isNewListing:b().default(!1).describe(`Whether this is a new listing submission`),scanResults:T({passed:b(),securityScore:y().min(0).max(100).optional(),compatibilityCheck:b().optional(),issues:w(T({severity:A([`critical`,`high`,`medium`,`low`,`info`]),message:v(),file:v().optional(),line:y().optional()})).optional()}).optional().describe(`Automated scan results`),reviewerNotes:v().optional().describe(`Notes from the platform reviewer`),submittedAt:v().datetime().optional().describe(`Submission timestamp`),reviewedAt:v().datetime().optional().describe(`Review completion timestamp`)}).describe(`Developer submission of a package version for review`)),W(()=>T({query:v().optional().describe(`Full-text search query`),category:bL.optional().describe(`Filter by category`),tags:w(v()).optional().describe(`Filter by tags`),pricing:SL.optional().describe(`Filter by pricing model`),publisherVerification:vL.optional().describe(`Filter by publisher verification level`),sortBy:A([`relevance`,`popularity`,`rating`,`newest`,`updated`,`name`]).default(`relevance`).describe(`Sort field`),sortDirection:A([`asc`,`desc`]).default(`desc`).describe(`Sort direction`),page:y().int().min(1).default(1).describe(`Page number`),pageSize:y().int().min(1).max(100).default(20).describe(`Items per page`),platformVersion:v().optional().describe(`Filter by platform version compatibility`)}).describe(`Marketplace search request`)),W(()=>T({items:w(CL).describe(`Search result listings`),total:y().int().min(0).describe(`Total matching results`),page:y().int().min(1).describe(`Current page number`),pageSize:y().int().min(1).describe(`Items per page`),facets:T({categories:w(T({category:bL,count:y().int().min(0)})).optional(),pricing:w(T({model:SL,count:y().int().min(0)})).optional()}).optional().describe(`Aggregation facets for refining search`)}).describe(`Marketplace search response`)),W(()=>T({listingId:v().describe(`Marketplace listing ID`),version:v().optional().describe(`Version to install`),licenseKey:v().optional().describe(`License key for paid packages`),settings:k(v(),S()).optional().describe(`User-provided settings at install time`),enableOnInstall:b().default(!0).describe(`Whether to enable immediately after install`),artifactRef:yL.optional().describe(`Artifact reference for direct installation`),tenantId:v().optional().describe(`Tenant identifier`)}).describe(`Install from marketplace request`)),W(()=>T({success:b().describe(`Whether installation succeeded`),packageId:v().optional().describe(`Installed package identifier`),version:v().optional().describe(`Installed version`),message:v().optional().describe(`Installation status message`)}).describe(`Install from marketplace response`));var wL=W(()=>T({packageId:v().describe(`Package identifier`)}));W(()=>T({status:A([`installed`,`disabled`,`installing`,`upgrading`,`uninstalling`,`error`]).optional().describe(`Filter by package status`),enabled:b().optional().describe(`Filter by enabled state`),limit:y().int().min(1).max(100).default(50).describe(`Maximum number of packages to return`),cursor:v().optional().describe(`Cursor for pagination`)}).describe(`List installed packages request`)),W(()=>G.extend({data:T({packages:w(FN).describe(`Installed packages`),total:y().int().optional().describe(`Total matching packages`),nextCursor:v().optional().describe(`Cursor for the next page`),hasMore:b().describe(`Whether more packages are available`)})}).describe(`List installed packages response`)),W(()=>wL),W(()=>G.extend({data:FN.describe(`Installed package details`)}).describe(`Get installed package response`)),W(()=>T({manifest:kN.describe(`Package manifest to install`),settings:k(v(),S()).optional().describe(`User-provided settings at install time`),enableOnInstall:b().default(!0).describe(`Whether to enable immediately after install`),platformVersion:v().optional().describe(`Current platform version for compatibility verification`),artifactRef:yL.optional().describe(`Artifact reference for marketplace installation`)}).describe(`Install package request`)),W(()=>G.extend({data:T({package:FN.describe(`Installed package details`),dependencyResolution:NN.optional().describe(`Dependency resolution result`),namespaceConflicts:w(T({type:j(`namespace_conflict`).describe(`Error type`),requestedNamespace:v().describe(`Requested namespace`),conflictingPackageId:v().describe(`Conflicting package ID`),conflictingPackageName:v().describe(`Conflicting package name`),suggestion:v().optional().describe(`Suggested alternative`)})).optional().describe(`Namespace conflicts detected`),message:v().optional().describe(`Installation status message`)})}).describe(`Install package response`)),W(()=>T({packageId:v().describe(`Package ID to upgrade`),targetVersion:v().optional().describe(`Target version (defaults to latest)`),manifest:kN.optional().describe(`New manifest for the target version`),createSnapshot:b().default(!0).describe(`Whether to create a pre-upgrade backup snapshot`),mergeStrategy:A([`keep-custom`,`accept-incoming`,`three-way-merge`]).default(`three-way-merge`).describe(`How to handle customer customizations`),dryRun:b().default(!1).describe(`Preview upgrade without making changes`),skipValidation:b().default(!1).describe(`Skip pre-upgrade compatibility checks`)}).describe(`Upgrade package request`)),W(()=>G.extend({data:T({success:b().describe(`Whether the upgrade succeeded`),phase:v().describe(`Current upgrade phase`),plan:iL.optional().describe(`Upgrade plan that was executed`),snapshotId:v().optional().describe(`Snapshot ID for rollback`),conflicts:w(T({path:v().describe(`Conflict path`),baseValue:S().describe(`Base value`),incomingValue:S().describe(`Incoming value`),customValue:S().describe(`Custom value`)})).optional().describe(`Unresolved merge conflicts`),errorMessage:v().optional().describe(`Error message if failed`),message:v().optional().describe(`Human-readable status message`)})}).describe(`Upgrade package response`)),W(()=>T({manifest:kN.describe(`Package manifest to resolve dependencies for`),platformVersion:v().optional().describe(`Current platform version for compatibility filtering`)}).describe(`Resolve dependencies request`)),W(()=>G.extend({data:NN.describe(`Dependency resolution result with topological sort`)}).describe(`Resolve dependencies response`)),W(()=>T({artifact:uL.describe(`Package artifact metadata`),sha256:v().regex(/^[a-f0-9]{64}$/).optional().describe(`SHA256 checksum of the uploaded file`),token:v().optional().describe(`Publisher authentication token`),releaseNotes:v().optional().describe(`Release notes for this version`)}).describe(`Upload artifact request`)),W(()=>G.extend({data:T({success:b().describe(`Whether the upload succeeded`),artifactRef:yL.optional().describe(`Artifact reference in the registry`),submissionId:v().optional().describe(`Marketplace submission ID for review tracking`),message:v().optional().describe(`Upload status message`)})}).describe(`Upload artifact response`)),W(()=>wL.extend({snapshotId:v().describe(`Snapshot ID to restore from`),rollbackCustomizations:b().default(!0).describe(`Whether to restore pre-upgrade customizations`)}).describe(`Rollback package request`)),W(()=>G.extend({data:T({success:b().describe(`Whether the rollback succeeded`),restoredVersion:v().optional().describe(`Restored version`),message:v().optional().describe(`Rollback status message`)})}).describe(`Rollback package response`)),W(()=>wL),W(()=>G.extend({data:T({packageId:v().describe(`Uninstalled package ID`),success:b().describe(`Whether uninstall succeeded`),message:v().optional().describe(`Uninstall status message`)})}).describe(`Uninstall package response`)),A([`package_not_found`,`package_already_installed`,`version_not_found`,`dependency_conflict`,`namespace_conflict`,`platform_incompatible`,`artifact_invalid`,`checksum_mismatch`,`signature_invalid`,`upgrade_failed`,`rollback_failed`,`snapshot_not_found`,`upload_failed`]);var TL=t({APPROVAL_NODE_TYPE:()=>APPROVAL_NODE_TYPE,ActionCategorySchema:()=>Mz,ActionParadigmSchema:()=>Nz,ActionRefSchema:()=>Ez,ApprovalEscalationSchema:()=>tz,ApprovalNodeApproverSchema:()=>ez,ApproverType:()=>$R,AuthFieldSchema:()=>dz,AuthenticationSchema:()=>pz,AuthenticationTypeSchema:()=>uz,BPMN_BOUNDARY_EVENT:()=>BPMN_BOUNDARY_EVENT,BPMN_JOIN_GATEWAY:()=>BPMN_JOIN_GATEWAY,BPMN_PARALLEL_GATEWAY:()=>BPMN_PARALLEL_GATEWAY,BpmnDiagnosticSchema:()=>Lz,BpmnElementMappingSchema:()=>Pz,BpmnUnmappedStrategySchema:()=>Fz,BpmnVersionSchema:()=>Iz,ConflictResolutionSchema:()=>Sz,ConnectorCategorySchema:()=>lz,ConnectorOperationSchema:()=>gz,ConnectorTriggerSchema:()=>_z,DataDestinationConfigSchema:()=>wz,DataSourceConfigSchema:()=>Cz,ETLDestinationSchema:()=>iz,ETLEndpointTypeSchema:()=>nz,ETLRunStatusSchema:()=>cz,ETLSourceSchema:()=>rz,ETLSyncModeSchema:()=>sz,ETLTransformationSchema:()=>oz,ETLTransformationTypeSchema:()=>az,ExecutionErrorSeverity:()=>XR,ExecutionStatus:()=>JR,ExecutionStepLogSchema:()=>YR,FlowEdgeSchema:()=>zL,FlowNodeAction:()=>IL,FlowNodeSchema:()=>RL,FlowRegionSchema:()=>HL,FlowSchema:()=>BL,FlowVariableSchema:()=>LL,GuardRefSchema:()=>Dz,LOOP_MAX_ITERATIONS_CEILING:()=>VL,LOOP_NODE_TYPE:()=>LOOP_NODE_TYPE,OAuth2ConfigSchema:()=>fz,OS_CONSTRUCT_EXT:()=>OS_CONSTRUCT_EXT,OperationParameterSchema:()=>hz,OperationTypeSchema:()=>mz,PARALLEL_NODE_TYPE:()=>PARALLEL_NODE_TYPE,ParallelBranchSchema:()=>UL,RetryPolicySchema:()=>WL,StateNodeSchema:()=>kz,SyncDirectionSchema:()=>bz,SyncExecutionStatusSchema:()=>Tz,SyncModeSchema:()=>xz,TRY_CATCH_NODE_TYPE:()=>TRY_CATCH_NODE_TYPE,TransitionSchema:()=>Oz,WaitEventTypeSchema:()=>Az,WaitTimeoutBehaviorSchema:()=>jz,WebhookSchema:()=>QR,WebhookTriggerType:()=>ZR}),EL=A([`none`,`no-overlay`,`no-delete`,`full`]),DL=A([`artifact`,`package`,`env-forced`]),OL=A([`package`,`org`,`env-forced`]),kL={_lock:EL.optional().describe(`Item-level lock — controls overlay & delete (ADR-0010).`),_lockReason:v().max(500).optional().describe(`Human-readable reason shown when a write is refused by _lock.`),_lockSource:DL.optional().describe(`Layer that set _lock (artifact | package | env-forced).`),_provenance:OL.optional().describe(`Origin of the item (package | org | env-forced).`),_packageId:v().optional().describe(`Owning package machine id.`),_packageVersion:v().optional().describe(`Owning package version.`),_lockDocsUrl:v().optional().describe(`Optional documentation link surfaced next to _lockReason.`)},AL=T({lock:EL.describe(`Lock policy — none | no-overlay | no-delete | full.`),reason:v().min(1).max(500).describe(`User-visible reason shown when the lock blocks an action.`),docsUrl:v().url().optional().describe(`Optional URL the Studio banner links to for more context.`)}).strict(),jL=A([`cel`,`js`,`cron`,`template`]),ML=T({rationale:v().optional(),generatedBy:v().optional()}),NL=T({dialect:jL,source:v().min(1).optional(),ast:S().optional(),meta:ML.optional()}).refine(e=>e.source!==void 0||e.ast!==void 0,{message:"Expression requires at least one of `source` or `ast`"}),PL=E([v().min(1).transform(e=>({dialect:`cel`,source:e})),NL]),FL=E([v().min(1).transform(e=>({dialect:`cron`,source:e})),NL]);E([v().min(1).transform(e=>({dialect:`template`,source:e})),NL]);function q(e){if(typeof process<`u`&&{}.OS_EAGER_SCHEMAS===`1`)return e();let t,n=()=>(t===void 0&&(t=e()),t);return new Proxy(function(){},{get(e,t){let r=n(),i=r[t];return typeof i==`function`?i.bind(r):i},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())}})}var IL=A([`start`,`end`,`decision`,`assignment`,`loop`,`create_record`,`update_record`,`delete_record`,`get_record`,`http`,`notify`,`script`,`screen`,`wait`,`subflow`,`map`,`connector_action`,`parallel_gateway`,`join_gateway`,`boundary_event`]);IL.options;var LL=q(()=>T({name:v().describe(`Variable name`),type:v().describe(`Data type (text, number, boolean, object, list)`),isInput:b().default(!1).describe(`Is input parameter`),isOutput:b().default(!1).describe(`Is output parameter`)})),RL=q(()=>T({id:v().describe(`Node unique ID`),type:v().min(1).describe(`Action type — a built-in FlowNodeAction id or a plugin-registered node type. Validated against the live action registry at registerFlow() (ADR-0018), not by a closed enum.`),label:v().describe(`Node label`),config:k(v(),S()).optional().describe(`Node configuration`),connectorConfig:T({connectorId:v(),actionId:v(),input:k(v(),S()).describe(`Mapped inputs for the action`)}).optional(),position:T({x:y(),y:y()}).optional(),timeoutMs:y().int().min(0).optional().describe(`Maximum execution time for this node in milliseconds`),inputSchema:k(v(),T({type:A([`string`,`number`,`boolean`,`object`,`array`]).describe(`Parameter type`),required:b().default(!1).describe(`Whether the parameter is required`),description:v().optional().describe(`Parameter description`)})).optional().describe(`Input parameter schema for this node`),outputSchema:k(v(),T({type:A([`string`,`number`,`boolean`,`object`,`array`]).describe(`Output type`),description:v().optional().describe(`Output description`)})).optional().describe(`Output schema declaration for this node`),waitEventConfig:T({eventType:A([`timer`,`signal`,`webhook`,`manual`,`condition`]).describe(`What kind of event resumes the execution`),timerDuration:v().optional().describe(`ISO 8601 duration (e.g., "PT1H") or wait time for timer events`),signalName:v().optional().describe(`Named signal or webhook event to wait for`),timeoutMs:y().int().min(0).optional().describe(`Maximum wait time before timeout (ms)`),onTimeout:A([`fail`,`continue`]).default(`fail`).describe(`Behavior when the wait times out`)}).optional().describe(`Configuration for wait node event resumption`),boundaryConfig:T({attachedToNodeId:v().describe(`Host node ID this boundary event monitors`),eventType:A([`error`,`timer`,`signal`,`cancel`]).describe(`Boundary event trigger type`),interrupting:b().default(!0).describe(`If true, the host activity is cancelled when this event fires`),errorCode:v().optional().describe(`Specific error code to catch (empty = catch all errors)`),timerDuration:v().optional().describe(`ISO 8601 duration for timer boundary events`),signalName:v().optional().describe(`Named signal to catch`)}).optional().describe(`Configuration for boundary events attached to host nodes`)})),zL=q(()=>T({id:v().describe(`Edge unique ID`),source:v().describe(`Source Node ID`),target:v().describe(`Target Node ID`),condition:PL.optional().describe(`Predicate (CEL) returning boolean used for branching.`),type:A([`default`,`fault`,`conditional`,`back`]).default(`default`).describe(`Connection type: default (normal flow), fault (error path), conditional (expression-guarded), or back (ADR-0044 declared back-edge — traversed normally at run time, but excluded from DAG cycle validation so a revise/rework loop can re-enter an earlier node)`),label:v().optional().describe(`Label on the connector`),isDefault:b().default(!1).describe(`Marks this edge as the default path when no other conditions match`)})),BL=q(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Machine name`),label:v().describe(`Flow label`),description:v().optional(),successMessage:v().optional().describe(`Toast shown when a screen flow completes (defaults to a generic "Done").`),errorMessage:v().optional().describe(`Toast shown when a screen flow fails (defaults to the raw error).`),version:y().int().default(1).describe(`Version number`),status:A([`draft`,`active`,`obsolete`,`invalid`]).default(`draft`).describe(`Deployment status`),template:b().default(!1).describe(`Is logic template (Subflow)`),type:A([`autolaunched`,`record_change`,`schedule`,`screen`,`api`]).describe(`Flow type`),variables:w(LL).optional().describe(`Flow variables`),nodes:w(RL).describe(`Flow nodes`),edges:w(zL).describe(`Flow connections`),active:b().default(!1).describe(`Is active (Deprecated: use status)`),runAs:A([`system`,`user`]).default(`user`).describe(`Execution identity for the run: system = elevated (bypasses RLS), user = the triggering user (RLS-respecting). A schedule-triggered run has no trigger user, so under user it runs UNSCOPED (elevated) — declare system to make that explicit.`),errorHandling:T({strategy:A([`fail`,`retry`,`continue`]).default(`fail`).describe(`How to handle node execution errors`),maxRetries:y().int().min(0).max(10).default(0).describe(`Number of retry attempts (only for retry strategy)`),retryDelayMs:y().int().min(0).default(1e3).describe(`Delay between retries in milliseconds`),backoffMultiplier:y().min(1).default(1).describe(`Multiplier for exponential backoff between retries`),maxRetryDelayMs:y().int().min(0).default(3e4).describe(`Maximum delay between retries in milliseconds`),jitter:b().default(!1).describe(`Add random jitter to retry delay to avoid thundering herd`),fallbackNodeId:v().optional().describe(`Node ID to jump to on unrecoverable error`)}).optional().describe(`Flow-level error handling configuration`),protection:AL.optional().describe(`Package author protection block — lock policy for this flow.`),...kL}));q(()=>T({flowName:v().describe(`Flow machine name`),version:y().int().min(1).describe(`Version number`),definition:BL.describe(`Complete flow definition snapshot`),createdAt:v().datetime().describe(`When this version was created`),createdBy:v().optional().describe(`User who created this version`),changeNote:v().optional().describe(`Description of what changed in this version`)}));var VL=1e5,HL=q(()=>T({nodes:w(RL).min(1).describe(`Region body nodes (single-entry/single-exit sub-graph)`),edges:w(zL).default([]).describe(`Region body edges`)}));q(()=>T({collection:v().min(1).describe(`Template/variable resolving to the array to iterate`),iteratorVariable:v().min(1).default(`item`).describe(`Loop variable holding the current item`),indexVariable:v().optional().describe(`Optional loop variable holding the current index`),maxIterations:y().int().min(1).max(VL).optional().describe(`Hard cap on iterations (clamped to the engine ceiling)`),body:HL.optional().describe(`Loop body region (omit for legacy flat-graph loops)`)}));var UL=q(()=>T({name:v().optional().describe(`Branch label`),nodes:w(RL).min(1).describe(`Branch body nodes`),edges:w(zL).default([]).describe(`Branch body edges`)}));q(()=>T({branches:w(UL).min(2).describe(`Branch regions executed concurrently; implicit join at block end`)}));var WL=q(()=>T({maxRetries:y().int().min(0).max(10).default(0).describe(`Retry attempts before giving up`),retryDelayMs:y().int().min(0).default(1e3).describe(`Base delay between retries (ms)`),backoffMultiplier:y().min(1).default(1).describe(`Exponential backoff multiplier`),maxRetryDelayMs:y().int().min(0).default(3e4).describe(`Maximum delay between retries (ms)`),jitter:b().default(!1).describe(`Add random jitter to retry delay`)}));q(()=>T({try:HL.describe(`Protected region`),catch:HL.optional().describe(`Handler region run when the try region fails`),errorVariable:v().default(`$error`).describe(`Variable holding the caught error in the catch region`),retry:WL.optional().describe(`Optional retry policy for the try region`)}));var GL=q(()=>v().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)`)),KL=q(()=>v().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)`));q(()=>v().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)`)),q(()=>T({key:v().describe(`Translation key (e.g., "views.task_list.label")`),defaultValue:v().optional().describe(`Fallback value when translation key is not found`),params:k(v(),E([v(),y(),b()])).optional().describe(`Interpolation parameters (e.g., { count: 5 })`)}));var qL=q(()=>v().describe(`Display label (plain string; i18n keys are auto-generated by the framework)`)),JL=q(()=>T({ariaLabel:qL.optional().describe(`Accessible label for screen readers (WAI-ARIA aria-label)`),ariaDescribedBy:v().optional().describe(`ID of element providing additional description (WAI-ARIA aria-describedby)`),role:v().optional().describe(`WAI-ARIA role attribute (e.g., "dialog", "navigation", "alert")`)}).describe(`ARIA accessibility attributes`));q(()=>T({key:v().describe(`Translation key`),zero:v().optional().describe(`Zero form (e.g., "No items")`),one:v().optional().describe(`Singular form (e.g., "{count} item")`),two:v().optional().describe(`Dual form (e.g., "{count} items" for exactly 2)`),few:v().optional().describe(`Few form (e.g., for 2-4 in some languages)`),many:v().optional().describe(`Many form (e.g., for 5+ in some languages)`),other:v().describe(`Default plural form (e.g., "{count} items")`)}).describe(`ICU plural rules for a translation key`));var YL=q(()=>T({style:A([`decimal`,`currency`,`percent`,`unit`]).default(`decimal`).describe(`Number formatting style`),currency:v().optional().describe(`ISO 4217 currency code (e.g., "USD", "EUR")`),unit:v().optional().describe(`Unit for unit formatting (e.g., "kilometer", "liter")`),minimumFractionDigits:y().optional().describe(`Minimum number of fraction digits`),maximumFractionDigits:y().optional().describe(`Maximum number of fraction digits`),useGrouping:b().optional().describe(`Whether to use grouping separators (e.g., 1,000)`)}).describe(`Number formatting rules`)),XL=q(()=>T({dateStyle:A([`full`,`long`,`medium`,`short`]).optional().describe(`Date display style`),timeStyle:A([`full`,`long`,`medium`,`short`]).optional().describe(`Time display style`),timeZone:v().optional().describe(`IANA time zone (e.g., "America/New_York")`),hour12:b().optional().describe(`Use 12-hour format`)}).describe(`Date/time formatting rules`));q(()=>T({code:v().describe(`BCP 47 language code (e.g., "en-US", "zh-CN")`),fallbackChain:w(v()).optional().describe(`Fallback language codes in priority order (e.g., ["zh-TW", "en"])`),direction:A([`ltr`,`rtl`]).default(`ltr`).describe(`Text direction: left-to-right or right-to-left`),numberFormat:YL.optional().describe(`Default number formatting rules`),dateFormat:XL.optional().describe(`Default date/time formatting rules`)}).describe(`Locale configuration`));var ZL=q(()=>T({enabled:b().default(!1).describe(`Enable public sharing`),publicLink:v().optional().describe(`Generated public share URL`),password:v().optional().describe(`Password required to access shared link`),allowedDomains:w(v()).optional().describe(`Restrict access to specific email domains (e.g. ["example.com"])`),expiresAt:v().optional().describe(`Expiration date/time in ISO 8601 format`),allowAnonymous:b().optional().default(!1).describe(`Allow access without authentication`)}));q(()=>T({enabled:b().default(!1).describe(`Enable iframe embedding`),allowedOrigins:w(v()).optional().describe(`Allowed iframe parent origins (e.g. ["https://example.com"])`),width:v().optional().default(`100%`).describe(`Embed width (CSS value)`),height:v().optional().default(`600px`).describe(`Embed height (CSS value)`),showHeader:b().optional().default(!0).describe(`Show interface header in embed`),showNavigation:b().optional().default(!1).describe(`Show navigation in embed`),responsive:b().optional().default(!0).describe(`Enable responsive resizing`)}));var QL=A([`xs`,`sm`,`md`,`lg`,`xl`,`2xl`]),$L=q(()=>T({xs:y().min(1).max(12).optional(),sm:y().min(1).max(12).optional(),md:y().min(1).max(12).optional(),lg:y().min(1).max(12).optional(),xl:y().min(1).max(12).optional(),"2xl":y().min(1).max(12).optional()}).describe(`Grid columns per breakpoint (1-12)`)),eR=q(()=>T({xs:y().optional(),sm:y().optional(),md:y().optional(),lg:y().optional(),xl:y().optional(),"2xl":y().optional()}).describe(`Display order per breakpoint`)),tR=q(()=>T({breakpoint:QL.optional().describe(`Minimum breakpoint for visibility`),hiddenOn:w(QL).optional().describe(`Hide on these breakpoints`),columns:$L.optional().describe(`Grid columns per breakpoint`),order:eR.optional().describe(`Display order per breakpoint`)}).describe(`Responsive layout configuration`)),nR=q(()=>k(v(),E([v(),y()])).describe(`CSS property → value map (camelCase keys; design tokens encouraged)`));q(()=>T({large:nR.optional().describe(`Unconditional base (desktop-first)`),medium:nR.optional().describe(`Applied at ≤ medium breakpoint`),small:nR.optional().describe(`Applied at ≤ small breakpoint`),xsmall:nR.optional().describe(`Applied at ≤ xsmall breakpoint`)}).describe(`Per-breakpoint scoped style maps (ADR-0065)`));var rR=q(()=>T({lazyLoad:b().optional().describe(`Enable lazy loading (defer rendering until visible)`),virtualScroll:T({enabled:b().default(!1).describe(`Enable virtual scrolling`),itemHeight:y().optional().describe(`Fixed item height in pixels (for estimation)`),overscan:y().optional().describe(`Number of extra items to render outside viewport`)}).optional().describe(`Virtual scrolling configuration`),cacheStrategy:A([`none`,`cache-first`,`network-first`,`stale-while-revalidate`]).optional().describe(`Client-side data caching strategy`),prefetch:b().optional().describe(`Prefetch data before component is visible`),pageSize:y().optional().describe(`Number of items per page for pagination`),debounceMs:y().optional().describe(`Debounce interval for user interactions in milliseconds`)}).describe(`Performance optimization configuration`)),iR=A(`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(`.`)),aR=q(()=>T({label:v().describe(`Display label (human-readable, any case allowed)`),value:GL.describe(`Stored value (lowercase machine identifier)`),color:v().optional().describe(`Color code for badges/charts`),default:b().optional().describe(`Is default option`)}));q(()=>T({latitude:y().min(-90).max(90).describe(`Latitude coordinate`),longitude:y().min(-180).max(180).describe(`Longitude coordinate`),altitude:y().optional().describe(`Altitude in meters`),accuracy:y().optional().describe(`Accuracy in meters`)}));var oR=q(()=>T({precision:y().int().min(0).max(10).default(2).describe(`Decimal precision (default: 2)`),currencyMode:A([`dynamic`,`fixed`]).default(`dynamic`).describe(`Currency mode: dynamic (user selectable) or fixed (single currency)`),defaultCurrency:v().length(3).default(`CNY`).describe(`Default or fixed currency code (ISO 4217, e.g., USD, CNY, EUR)`)}));q(()=>T({value:y().describe(`Monetary amount`),currency:v().length(3).describe(`Currency code (ISO 4217)`)})),q(()=>T({street:v().optional().describe(`Street address`),city:v().optional().describe(`City name`),state:v().optional().describe(`State/Province`),postalCode:v().optional().describe(`Postal/ZIP code`),country:v().optional().describe(`Country name or code`),countryCode:v().optional().describe(`ISO country code (e.g., US, GB)`),formatted:v().optional().describe(`Formatted address string`)}));var sR=q(()=>T({dimensions:y().int().min(1).max(1e4).describe(`Vector dimensionality (e.g., 1536 for OpenAI embeddings)`),distanceMetric:A([`cosine`,`euclidean`,`dotProduct`,`manhattan`]).default(`cosine`).describe(`Distance/similarity metric for vector search`),normalized:b().default(!1).describe(`Whether vectors are normalized (unit length)`),indexed:b().default(!0).describe(`Whether to create a vector index for fast similarity search`),indexType:A([`hnsw`,`ivfflat`,`flat`]).optional().describe(`Vector index algorithm (HNSW for high accuracy, IVFFlat for large datasets)`)})),cR=q(()=>T({minSize:y().min(0).optional().describe(`Minimum file size in bytes`),maxSize:y().min(1).optional().describe(`Maximum file size in bytes (e.g., 10485760 = 10MB)`),allowedTypes:w(v()).optional().describe(`Allowed file extensions (e.g., [".pdf", ".docx", ".jpg"])`),blockedTypes:w(v()).optional().describe(`Blocked file extensions (e.g., [".exe", ".bat", ".sh"])`),allowedMimeTypes:w(v()).optional().describe(`Allowed MIME types (e.g., ["image/jpeg", "application/pdf"])`),blockedMimeTypes:w(v()).optional().describe(`Blocked MIME types`),virusScan:b().default(!1).describe(`Enable virus scanning for uploaded files`),virusScanProvider:A([`clamav`,`virustotal`,`metadefender`,`custom`]).optional().describe(`Virus scanning service provider`),virusScanOnUpload:b().default(!0).describe(`Scan files immediately on upload`),quarantineOnThreat:b().default(!0).describe(`Quarantine files if threat detected`),storageProvider:v().optional().describe(`Object storage provider name (references ObjectStorageConfig)`),storageBucket:v().optional().describe(`Target bucket name`),storagePrefix:v().optional().describe(`Storage path prefix (e.g., "uploads/documents/")`),imageValidation:T({minWidth:y().min(1).optional().describe(`Minimum image width in pixels`),maxWidth:y().min(1).optional().describe(`Maximum image width in pixels`),minHeight:y().min(1).optional().describe(`Minimum image height in pixels`),maxHeight:y().min(1).optional().describe(`Maximum image height in pixels`),aspectRatio:v().optional().describe(`Required aspect ratio (e.g., "16:9", "1:1")`),generateThumbnails:b().default(!1).describe(`Auto-generate thumbnails`),thumbnailSizes:w(T({name:v().describe(`Thumbnail variant name (e.g., "small", "medium", "large")`),width:y().min(1).describe(`Thumbnail width in pixels`),height:y().min(1).describe(`Thumbnail height in pixels`),crop:b().default(!1).describe(`Crop to exact dimensions`)})).optional().describe(`Thumbnail size configurations`),preserveMetadata:b().default(!1).describe(`Preserve EXIF metadata`),autoRotate:b().default(!0).describe(`Auto-rotate based on EXIF orientation`)}).optional().describe(`Image-specific validation rules`),allowMultiple:b().default(!1).describe(`Allow multiple file uploads (overrides field.multiple)`),allowReplace:b().default(!0).describe(`Allow replacing existing files`),allowDelete:b().default(!0).describe(`Allow deleting uploaded files`),requireUpload:b().default(!1).describe(`Require at least one file when field is required`),extractMetadata:b().default(!0).describe(`Extract file metadata (name, size, type, etc.)`),extractText:b().default(!1).describe(`Extract text content from documents (OCR/parsing)`),versioningEnabled:b().default(!1).describe(`Keep previous versions of replaced files`),maxVersions:y().min(1).optional().describe(`Maximum number of versions to retain`),publicRead:b().default(!1).describe(`Allow public read access to uploaded files`),presignedUrlExpiry:y().min(60).max(604800).default(3600).describe(`Presigned URL expiration in seconds (default: 1 hour)`)}).refine(e=>!(e.minSize!==void 0&&e.maxSize!==void 0&&e.minSize>e.maxSize),{message:`minSize must be less than or equal to maxSize`}).refine(e=>!(e.virusScanProvider!==void 0&&e.virusScan!==!0),{message:`virusScanProvider requires virusScan to be enabled`}));q(()=>T({uniqueness:b().default(!1).describe(`Enforce unique values across all records`),completeness:y().min(0).max(1).default(0).describe(`Minimum ratio of non-null values (0-1, default: 0 = no requirement)`),accuracy:T({source:v().describe(`Reference data source for validation (e.g., "api.verify.com", "master_data")`),threshold:y().min(0).max(1).describe(`Minimum accuracy threshold (0-1, e.g., 0.95 = 95% match required)`)}).optional().describe(`Accuracy validation configuration`)})),q(()=>T({enabled:b().describe(`Enable caching for computed field results`),ttl:y().min(0).describe(`Cache TTL in seconds (0 = no expiration)`),invalidateOn:w(v()).describe(`Field paths that invalidate cache (e.g., ["inventory.quantity", "pricing.base_price"])`)})),q(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Machine name (snake_case)`).optional(),label:v().optional().describe(`Human readable label`),type:iR.describe(`Field Data Type`),description:v().optional().describe(`Tooltip/Help text`),format:v().optional().describe(`Format string (e.g. email, phone)`),columnName:v().optional().describe(`Physical column name in the target datasource. Defaults to the field key when not set.`),required:b().default(!1).describe(`Is required`),searchable:b().default(!1).describe(`Is searchable`),multiple:b().default(!1).describe(`Allow multiple values (Stores as Array/JSON). Applicable for select, lookup, file, image.`),unique:b().default(!1).describe(`Is unique constraint`),defaultValue:S().optional().describe(`Default value`),maxLength:y().optional().describe(`Max character length`),minLength:y().optional().describe(`Min character length`),precision:y().optional().describe(`Total digits`),scale:y().optional().describe(`Decimal places`),min:y().optional().describe(`Minimum value`),max:y().optional().describe(`Maximum value`),options:w(aR).optional().describe(`Static options for select/multiselect`),reference:v().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.`),referenceFilters:w(v()).optional().describe(`Filters applied to lookup dialogs (e.g. "active = true")`),deleteBehavior:A([`set_null`,`cascade`,`restrict`]).optional().default(`set_null`).describe(`What happens if referenced record is deleted`),inlineEdit:E([b(),A([`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:v().optional().describe(`Title for the inline master-detail grid`),inlineColumns:w(x()).optional().describe(`Explicit columns for the inline grid (derived from the child object when omitted)`),inlineAmountField:v().optional().describe(`Numeric child field summed for the inline grid total`),relatedList:b().optional().describe(`Show this child collection as a related list on the parent's detail page (read-side mirror of inlineEdit). Defaults to shown for master_detail/lookup; set false to suppress.`),relatedListTitle:v().optional().describe(`Title for the detail-page related list`),relatedListColumns:w(x()).optional().describe(`Explicit columns for the detail-page related list (derived from the child object when omitted)`),displayField:v().optional().describe(`Field shown as each candidate's label in the picker/popover (defaults to the referenced object's name/title).`),descriptionField:v().optional().describe(`Secondary field shown under the label in the quick-select popover.`),lookupColumns:w(E([v(),T({field:v(),label:v().optional(),width:v().optional(),type:v().optional()})])).optional().describe(`Explicit columns for the record-picker table; auto-derived from the referenced object when omitted.`),lookupPageSize:y().int().positive().optional().describe(`Rows per page in the record-picker dialog (default 10).`),lookupFilters:w(T({field:v(),operator:A([`eq`,`ne`,`gt`,`lt`,`gte`,`lte`,`contains`,`in`,`notIn`]),value:x()})).optional().describe(`Base filters restricting which records are selectable (e.g. only active). Structured, picker-honoured form of referenceFilters.`),dependsOn:w(E([v(),T({field:v(),param:v().optional()})])).optional().describe(`Dependent lookup: restrict candidates by the value of other field(s) on the same record. String = same local/remote key; {field,param} when the remote filter key differs.`),allowCreate:b().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:PL.optional().describe("Formula expression (CEL). e.g. F`record.amount * 0.1`"),returnType:A([`number`,`text`,`boolean`,`date`]).optional().describe(`Inferred value type of a formula field (number/text/boolean/date)`),summaryOperations:T({object:v().describe(`Source child object name for roll-up`),field:v().describe(`Field on child object to aggregate (ignored for count)`),function:A([`count`,`sum`,`min`,`max`,`avg`]).describe(`Aggregation function to apply`),relationshipField:v().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.`)}).optional().describe(`Roll-up summary definition. The engine recomputes the value when child records are inserted/updated/deleted.`),language:v().optional().describe(`Programming language for syntax highlighting (e.g., javascript, python, sql)`),maxRating:y().optional().describe(`Maximum rating value (default: 5)`),step:y().optional().describe(`Step increment for slider (default: 1)`),currencyConfig:oR.optional().describe(`Configuration for currency field type`),dimensions:y().int().min(1).max(1e4).optional().describe(`Vector dimensionality (e.g., 1536 for OpenAI embeddings)`),vectorConfig:sR.optional().describe(`Configuration for vector field type (AI/ML embeddings)`),fileAttachmentConfig:cR.optional().describe(`Configuration for file and attachment field types`),trackHistory:b().optional().describe(`Render this field's value changes as human-readable entries on the record activity timeline (ADR-0052 §5b). Opt-in per field.`),dependencies:w(v()).optional().describe(`Array of field names that this field depends on (for formulas, visibility rules, etc.)`),group:v().optional().describe(`Field group name for organizing fields in forms and layouts (e.g., "contact_info", "billing", "system")`),visibleWhen:PL.optional().describe("Predicate (CEL) — field is shown only when TRUE (else hidden). e.g. P`record.type == 'invoice'`"),readonlyWhen:PL.optional().describe("Predicate (CEL) — field is read-only when TRUE. e.g. P`record.status == 'paid'`"),requiredWhen:PL.optional().describe("Predicate (CEL) — field is required when TRUE. Canonical name for `conditionalRequired`."),conditionalRequired:PL.optional().describe("Predicate (CEL) — field is required when TRUE. Alias of `requiredWhen`."),hidden:b().default(!1).describe(`Hidden from default UI`),readonly:b().default(!1).describe(`Read-only in UI`),requiredPermissions:w(v()).optional().describe(`[ADR-0066 D3] Capabilities required to read/edit this field (mask on read, deny on write; AND-gate).`),system:b().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:b().optional().default(!0).describe(`Whether field is sortable in list views`),inlineHelpText:v().optional().describe(`Help text displayed below the field in forms`),caseSensitive:b().optional().describe(`Whether text comparisons are case-sensitive`),autonumberFormat:v().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).`),index:b().default(!1).describe(`Create standard database index`),externalId:b().default(!1).describe(`Is external ID for upsert operations`)}));var lR=A([`GET`,`POST`,`PUT`,`DELETE`,`PATCH`,`HEAD`,`OPTIONS`]),uR=q(()=>A([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`])),dR=q(()=>T({url:v().describe(`API endpoint URL`),method:uR.optional().default(`GET`).describe(`HTTP method`),headers:k(v(),v()).optional().describe(`Custom HTTP headers`),params:k(v(),S()).optional().describe(`Query parameters`),body:S().optional().describe(`Request body for POST/PUT/PATCH`)}));q(()=>T({enabled:b().default(!0).describe(`Enable CORS`),origins:E([v(),w(v())]).default(`*`).describe(`Allowed origins (* for all)`),methods:w(lR).optional().describe(`Allowed HTTP methods`),credentials:b().default(!1).describe(`Allow credentials (cookies, authorization headers)`),maxAge:y().int().optional().describe(`Preflight cache duration in seconds`)})),q(()=>T({enabled:b().default(!1).describe(`Enable rate limiting`),windowMs:y().int().default(6e4).describe(`Time window in milliseconds`),maxRequests:y().int().default(100).describe(`Max requests per window`)})),q(()=>T({path:v().describe(`URL path to serve from`),directory:v().describe(`Physical directory to serve`),cacheControl:v().optional().describe(`Cache-Control header value`)}));var fR=q(()=>D(`provider`,[T({provider:j(`object`),object:v().describe(`Target object name`)}),T({provider:j(`api`),read:dR.optional().describe(`Configuration for fetching data`),write:dR.optional().describe(`Configuration for submitting data (for forms/editable tables)`)}),T({provider:j(`value`),items:w(S()).describe(`Static data array`)}),T({provider:j(`schema`),schemaId:v().describe(`Schema identifier — typically the metadata type name`),schema:k(v(),S()).optional().describe(`Inline JSON Schema (Draft 2020-12). Optional when schemaId is resolvable.`)})])),pR=q(()=>T({field:v().describe(`Field name to filter on`),operator:v().describe(`Filter operator (e.g. equals, not_equals, contains, this_quarter)`),value:E([v(),y(),b(),ul(),w(E([v(),y()]))]).optional().describe(`Filter value`)}).describe(`View filter rule`)),mR=q(()=>A([`none`,`count`,`count_empty`,`count_filled`,`count_unique`,`percent_empty`,`percent_filled`,`sum`,`avg`,`min`,`max`]).describe(`Aggregation function for column footer summary`)),hR=q(()=>T({field:v().describe(`Field name (snake_case)`),label:qL.optional().describe(`Display label override`),width:y().positive().optional().describe(`Column width in pixels`),align:A([`left`,`center`,`right`]).optional().describe(`Text alignment`),hidden:b().optional().describe(`Hide column by default`),sortable:b().optional().describe(`Allow sorting by this column`),resizable:b().optional().describe(`Allow resizing this column`),wrap:b().optional().describe(`Allow text wrapping`),type:v().optional().describe(`Renderer type override (e.g., "currency", "date")`),pinned:A([`left`,`right`]).optional().describe(`Pin/freeze column to left or right side`),summary:mR.optional().describe(`Footer aggregation function for this column`),link:b().optional().describe(`Functions as the primary navigation link (triggers View navigation)`),action:v().optional().describe(`Registered Action ID to execute when clicked`)})),gR=q(()=>T({type:A([`none`,`single`,`multiple`]).default(`none`).describe(`Selection mode`)})),_R=q(()=>T({pageSize:y().int().positive().default(25).describe(`Number of records per page`),pageSizeOptions:w(y().int().positive()).optional().describe(`Available page size options`)})),vR=q(()=>A([`compact`,`short`,`medium`,`tall`,`extra_tall`]).describe(`Row height / density setting for list view`)),yR=q(()=>T({field:v().describe(`Field name to group by`),order:A([`asc`,`desc`]).default(`asc`).describe(`Group sort order`),collapsed:b().default(!1).describe(`Collapse groups by default`)})),bR=q(()=>T({fields:w(yR).min(1).describe(`Fields to group by (supports up to 3 levels)`)}).describe(`Record grouping configuration`)),xR=q(()=>T({coverField:v().optional().describe(`Attachment/image field to display as card cover`),coverFit:A([`cover`,`contain`]).default(`cover`).describe(`Image fit mode for card cover`),cardSize:A([`small`,`medium`,`large`]).default(`medium`).describe(`Card size in gallery view`),titleField:v().optional().describe(`Field to display as card title`),visibleFields:w(v()).optional().describe(`Fields to display on card body`)}).describe(`Gallery/card view configuration`)),SR=q(()=>T({startDateField:v().describe(`Field for timeline item start date`),endDateField:v().optional().describe(`Field for timeline item end date`),titleField:v().describe(`Field to display as timeline item title`),groupByField:v().optional().describe(`Field to group timeline rows`),colorField:v().optional().describe(`Field to determine item color`),scale:A([`hour`,`day`,`week`,`month`,`quarter`,`year`]).default(`week`).describe(`Default timeline scale`)}).describe(`Timeline view configuration`)),CR=q(()=>T({type:A([`personal`,`collaborative`]).default(`collaborative`).describe(`View ownership type`),lockedBy:v().optional().describe(`User who locked the view configuration`)}).describe(`View sharing and access configuration`)),wR=q(()=>T({field:v().describe(`Field to derive color from (typically a select/status field)`),colors:k(v(),v()).optional().describe(`Map of field value to color (hex/token)`)}).describe(`Row color configuration based on field values`)),TR=q(()=>A([`grid`,`kanban`,`gallery`,`calendar`,`timeline`,`gantt`,`map`,`chart`,`tree`]).describe(`Visualization type that users can switch to`)),ER=q(()=>T({sort:b().default(!0).describe(`Allow users to sort records`),search:b().default(!0).describe(`Allow users to search records`),filter:b().default(!0).describe(`Allow users to filter records`),rowHeight:b().default(!0).describe(`Allow users to toggle row height/density`),addRecordForm:b().default(!1).describe(`Add records through a form instead of inline`),buttons:w(v()).optional().describe(`Custom action button IDs to show in the toolbar`)}).describe(`User action toggles for the view toolbar`)),DR=q(()=>T({showDescription:b().default(!0).describe(`Show the view description text`),allowedVisualizations:w(TR).optional().describe(`Whitelist of visualization types users can switch between (e.g. ["grid", "gallery", "kanban"])`)}).describe(`Appearance and visualization configuration`)),OR=q(()=>T({name:KL.describe(`Tab identifier (snake_case)`),label:qL.optional().describe(`Display label`),icon:v().optional().describe(`Tab icon name`),view:v().optional().describe(`Referenced list view name from listViews`),filter:w(pR).optional().describe(`Tab-specific filter criteria`),order:y().int().min(0).optional().describe(`Tab display order`),pinned:b().default(!1).describe(`Pin tab (cannot be removed by users)`),isDefault:b().default(!1).describe(`Set as the default active tab`),visible:b().default(!0).describe(`Tab visibility`)}).describe(`Tab configuration for multi-tab view interface`)),kR=q(()=>T({field:v().describe(`Field name on the source object (must exist — checked by reference diagnostics)`),label:qL.optional().describe(`Display label override (defaults to the field label)`),type:A([`select`,`multi-select`,`boolean`,`date-range`,`text`]).optional().describe(`Filter control type. Omit to infer from the field definition`),options:w(T({value:E([v(),y(),b()]).describe(`Option value`),label:qL.describe(`Option label`),color:v().optional().describe(`Option color token/hex`)})).optional().describe(`Static options. Omit to derive from the field definition (select options / lookup records)`),showCount:b().optional().describe(`Show per-option record counts`),defaultValues:w(E([v(),y(),b()])).optional().describe(`Pre-selected values when the view loads`)}).describe(`Quick-filter field configuration`)),AR=q(()=>T({element:A([`dropdown`,`tabs`,`toggle`]).default(`dropdown`).describe(`Filter control style: "dropdown" (per-field value selectors) or "tabs" (named presets). "toggle" is deprecated.`),fields:w(kR).optional().describe(`Fields exposed as quick filters (dropdown/toggle elements)`),tabs:w(OR).optional().describe(`Named filter presets rendered as tabs (tabs element). Reuses ViewTabSchema`),showAllRecords:b().optional().describe(`Show an "All records" tab before the presets (tabs element)`)}).describe(`End-user quick-filter configuration (Airtable "User filters" parity)`)),jR=q(()=>T({enabled:b().default(!0).describe(`Show the add record entry point`),position:A([`top`,`bottom`,`both`]).default(`bottom`).describe(`Position of the add record button`),mode:A([`inline`,`form`,`modal`]).default(`inline`).describe(`How to add a new record`),formView:v().optional().describe(`Named form view to use when mode is "form" or "modal"`)}).describe(`Add record entry point configuration`)),MR=q(()=>T({groupByField:v().describe(`Field to group columns by (usually status/select)`),summarizeField:v().optional().describe(`Field to sum at top of column (e.g. amount)`),columns:w(v()).describe(`Fields to show on cards`)})),NR=q(()=>T({chartType:A([`bar`,`line`,`pie`,`area`,`scatter`]).default(`bar`).describe(`Chart visualisation type`),dataset:KL.describe(`Dataset name to bind (ADR-0021)`),dimensions:w(v()).optional().describe(`Dimension names — X/group/split`),values:w(v()).min(1).describe(`Measure names — Y (at least one)`)}).describe(`List chart view configuration`)),PR=q(()=>T({startDateField:v(),endDateField:v().optional(),titleField:v(),colorField:v().optional()})),FR=q(()=>T({field:v().describe(`Record field / dot-path the dimension filters on`),label:v().optional().describe(`Trigger label (falls back to the field label)`),options:w(E([v(),T({value:E([v(),y()]),label:v().optional()})])).optional().describe(`Explicit option override for fixed enums`)})),IR=q(()=>T({startDateField:v(),endDateField:v(),titleField:v(),progressField:v().optional(),dependenciesField:v().optional(),colorField:v().optional().describe(`Field that drives the bar color`),parentField:v().optional().describe(`Field holding the parent task id (builds the summary → step tree)`),typeField:v().optional().describe(`Field whose value maps to task/summary/milestone`),baselineStartField:v().optional().describe(`Baseline (planned) start field`),baselineEndField:v().optional().describe(`Baseline (planned) end field`),groupByField:v().optional().describe(`Field to group leaf tasks by (synthesized summary rows)`),resourceView:b().optional().describe(`Render a per-resource workload histogram instead of the timeline`),assigneeField:v().optional().describe(`Resource field to bucket load by (resource view)`),effortField:v().optional().describe(`Per-task load units (resource view; default 1)`),capacity:y().optional().describe(`Per-resource capacity ceiling; loads above this flag overload`),tooltipFields:w(E([v(),T({field:v(),label:v().optional()})])).optional().describe(`Fields to surface in the hover tooltip, in display order`),quickFilters:w(FR).optional().describe(`Multi-select filter dropdowns rendered above the chart`),autoZoomToFilter:b().optional().describe(`When true (default), filtering zooms the range to the filtered tasks`)}).passthrough()),LR=q(()=>T({parentField:v().optional().describe(`Single-parent pointer field (auto-detected from the object schema when omitted)`),labelField:v().optional().describe(`Field rendered indented in the first column (defaults to "name")`),fields:w(v()).optional().describe(`Additional fields rendered as flat columns alongside the label`),defaultExpandedDepth:y().int().min(0).optional().describe(`Initial expansion depth (0 = roots only; omit = expand all)`)}).passthrough()),RR=q(()=>A([`page`,`drawer`,`modal`,`split`,`popover`,`new_window`,`none`])),zR=q(()=>T({mode:RR.default(`page`),view:v().optional().describe(`Name of the form view to use for details (e.g. "summary_view", "edit_form")`),preventNavigation:b().default(!1).describe(`Disable standard navigation entirely`),openNewTab:b().default(!1).describe(`Force open in new tab (applies to page mode)`),width:E([v(),y()]).optional().describe(`Width of the drawer/modal (e.g. "600px", "50%")`)})),BR=q(()=>T({name:KL.optional().describe(`Internal view name (lowercase snake_case)`),label:qL.optional(),type:A([`grid`,`kanban`,`gallery`,`calendar`,`timeline`,`gantt`,`map`,`chart`,`tree`]).default(`grid`),data:fR.optional().describe(`Data source configuration (defaults to "object" provider)`),columns:E([w(v()),w(hR)]).describe(`Fields to display as columns`),filter:w(pR).optional().describe(`Filter criteria (JSON Rules)`),sort:E([v(),w(T({field:v(),order:A([`asc`,`desc`])}))]).optional(),searchableFields:w(v()).optional().describe(`Fields enabled for search`),filterableFields:w(v()).optional().describe(`Legacy shorthand for userFilters.fields — bare field names enabled for end-user filtering. Prefer userFilters`),userFilters:AR.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:b().optional().describe(`Enable column resizing`),striped:b().optional().describe(`Striped row styling`),bordered:b().optional().describe(`Show borders`),compactToolbar:b().optional().describe(`Collapse Group/Color/Density/Hide-fields into a single View settings popover`),selection:gR.optional().describe(`Row selection configuration`),navigation:zR.optional().describe(`Configuration for item click navigation (page, drawer, modal, etc.)`),pagination:_R.optional().describe(`Pagination configuration`),kanban:MR.optional(),calendar:PR.optional(),gantt:IR.optional(),gallery:xR.optional(),timeline:SR.optional(),chart:NR.optional(),tree:LR.optional(),description:qL.optional().describe(`View description for documentation/tooltips`),sharing:CR.optional().describe(`View sharing and access configuration`),rowHeight:vR.optional().describe(`Row height / density setting`),grouping:bR.optional().describe(`Group records by one or more fields`),rowColor:wR.optional().describe(`Color rows based on field value`),hiddenFields:w(v()).optional().describe(`Fields to hide in this specific view`),fieldOrder:w(v()).optional().describe(`Explicit field display order for this view`),rowActions:w(v()).optional().describe(`Actions available for individual row items`),bulkActions:w(v()).optional().describe(`Actions available when multiple rows are selected`),bulkActionDefs:w(k(v(),x())).optional().describe(`Rich bulk action definitions (schema-driven, executed via BulkActionDialog)`),virtualScroll:b().optional().describe(`Enable virtual scrolling for large datasets`),conditionalFormatting:w(T({condition:PL.describe(`Predicate (CEL) to evaluate.`),style:k(v(),v()).describe(`CSS styles to apply when condition is true`)})).optional().describe(`Conditional formatting rules for list rows`),inlineEdit:b().optional().describe(`Allow inline editing of records directly in the list view`),exportOptions:w(A([`csv`,`xlsx`,`pdf`,`json`])).optional().describe(`Available export format options`),userActions:ER.optional().describe(`User action toggles for the view toolbar`),appearance:DR.optional().describe(`Appearance and visualization configuration`),tabs:w(OR).optional().describe(`Tab definitions for multi-tab view interface`),addRecord:jR.optional().describe(`Add record entry point configuration`),showRecordCount:b().optional().describe(`Show record count at the bottom of the list`),allowPrinting:b().optional().describe(`Allow users to print the view`),emptyState:T({title:qL.optional(),message:qL.optional(),icon:v().optional()}).optional().describe(`Empty state configuration when no records found`),aria:JL.optional().describe(`ARIA accessibility attributes for the list view`),responsive:tR.optional().describe(`Responsive layout configuration`),performance:rR.optional().describe(`Performance optimization settings`)})),VR=q(()=>T({field:v().describe(`Field name (snake_case)`),type:iR.optional().describe(`Field type (auto-infers widget if omitted)`),options:w(aR).optional().describe(`Options for select/multiselect/radio/checkboxes fields`),reference:v().optional().describe(`Target object name for lookup/master_detail fields`),maxLength:y().optional().describe(`Maximum character length (for text/textarea/email/url/phone)`),minLength:y().optional().describe(`Minimum character length`),min:y().optional().describe(`Minimum value (for number/currency/percent/slider)`),max:y().optional().describe(`Maximum value`),precision:y().optional().describe(`Total digits (for number/currency)`),scale:y().optional().describe(`Decimal places`),multiple:b().optional().describe(`Allow multiple values (for select/lookup/file/image)`),label:qL.optional().describe(`Display label override`),placeholder:qL.optional().describe(`Placeholder text`),helpText:qL.optional().describe(`Help/hint text`),readonly:b().optional().describe(`Read-only override`),immutable:b().optional().describe(`Editable on create, locked once the record exists (e.g. machine names).`),required:b().optional().describe(`Required override`),hidden:b().optional().describe(`Hidden override`),colSpan:y().int().min(1).max(4).optional().describe(`Column span in grid layout (1-4)`),widget:v().optional().describe(`Custom widget/component name (overrides type-based inference)`),language:v().optional().describe(`Code editor language (for type=code)`),fields:w(M(()=>VR)).optional().describe(`Sub-fields for composite/repeater/record types`),keyField:T({field:v().default(`name`).describe(`Property name that holds the key inside each item (defaults to "name")`),label:qL.optional().describe(`Display label for the key column`),placeholder:qL.optional().describe(`Placeholder when entering a new key`),helpText:qL.optional().describe(`Help text under the key input`),regex:v().optional().describe(`JS regex source string the key must match (no flags)`),immutable:b().default(!0).describe(`If true, the key is read-only after creation`)}).optional().describe(`Key column config for record-typed fields`),dependsOn:v().optional().describe(`Parent field name for cascading`),visibleOn:PL.optional().describe(`Visibility predicate (CEL).`),disclosure:A([`inline`,`popover`]).optional().describe(`Composite rendering: inline bordered box (default) or a summary line + gear popover (progressive disclosure).`)})),HR=q(()=>T({name:v().optional().describe(`Stable section identifier for i18n lookup (snake_case)`),label:qL.optional(),description:v().optional().describe(`Optional description rendered under the section header.`),collapsible:b().default(!1),collapsed:b().default(!1),visibleOn:PL.optional().describe(`Visibility predicate (CEL). Hides the whole section when false.`),columns:E([A([`1`,`2`,`3`,`4`]),j(1),j(2),j(3),j(4)]).default(1).transform(e=>typeof e==`string`?parseInt(e):e),fields:w(E([v(),VR]))})),UR=q(()=>T({type:A([`simple`,`tabbed`,`wizard`,`split`,`drawer`,`modal`]).default(`simple`),data:fR.optional().describe(`Data source configuration (defaults to "object" provider)`),sections:w(HR).optional(),groups:w(HR).optional(),subforms:w(T({childObject:v().describe(`Child object whose records are entered inline`),relationshipField:v().optional().describe(`FK on the child pointing back to the parent (auto-detected when omitted)`),columns:w(x()).optional().describe(`Editable grid columns (derived from the child object when omitted)`),amountField:v().optional().describe(`Numeric child column summed for the running total`),totalField:v().optional().describe(`Parent field to receive the rolled-up sum`),title:v().optional().describe(`Section title`),addLabel:v().optional().describe(`Add-row button label`),minRows:y().optional(),maxRows:y().optional()})).optional().describe(`Inline master-detail child collections`),defaultSort:w(T({field:v().describe(`Field name to sort by`),order:A([`asc`,`desc`]).default(`desc`).describe(`Sort direction`)})).optional().describe(`Default sort order for related list views within this form`),sharing:ZL.optional().describe(`Public sharing configuration for this form`),submitBehavior:E([T({kind:j(`thank-you`),title:v().optional(),message:v().optional()}),T({kind:j(`redirect`),url:v(),delayMs:y().int().min(0).optional()}),T({kind:j(`continue`)}),T({kind:j(`next-record`)})]).optional().describe(`Post-submit behavior`),aria:JL.optional().describe(`ARIA accessibility attributes for the form view`)}));q(()=>T({list:BR.optional(),form:UR.optional(),listViews:k(v(),BR).optional().describe(`Additional named list views`),formViews:k(v(),UR).optional().describe(`Additional named form views`),protection:AL.optional().describe(`Package author protection block — lock policy for this view.`),...kL}));var WR=v().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>`."),GR=A([`package`,`shared`,`personal`]).describe(`View identity layer: package | shared | personal.`);A([`list`,`form`]).describe("Whether `config` is a ListView (list family) or a FormView.");function KR(){return{name:WR,object:v().describe(`Bound object name — the foreign key used to aggregate views.`),label:qL.optional().describe(`Display label (supports i18n).`),isDefault:b().optional().describe(`Whether this is the object's default view in the switcher.`),order:y().int().optional().describe(`Sort order within the object's view switcher / left rail.`),scope:GR.optional().describe("Identity layer (defaults to `package` for source-loaded views)."),owner:v().optional().describe("Owner user id — set when `scope` is `personal`."),hidden:b().optional().describe(`Hidden from the switcher (per-user / per-org declutter).`),protection:AL.optional().describe(`Package author protection block — lock policy for this view.`),...kL}}q(()=>D(`viewKind`,[T({viewKind:j(`list`),config:BR.describe(`List-family view configuration.`),...KR()}),T({viewKind:j(`form`),config:UR.describe(`Form view configuration.`),...KR()})]));function qR(e){let{schemaId:t,...n}=e;return UR.parse({...n,data:{provider:`schema`,schemaId:t}})}qR({schemaId:`flow`,type:`simple`,sections:[{name:`basics`,label:`Basics`,description:`Flow identity and how it starts.`,columns:2,fields:[{field:`name`,required:!0,colSpan:1,helpText:`Unique identifier (snake_case)`},{field:`label`,required:!0,colSpan:1,helpText:`Display name for users`},{field:`type`,required:!0,colSpan:1,helpText:`How the flow starts (autolaunched, record_change, schedule, screen, api)`},{field:`template`,colSpan:1,helpText:`Is this a reusable subflow (can be called from other flows)`},{field:`description`,widget:`textarea`,colSpan:2,helpText:`What this flow does`}]},{name:`canvas`,label:`Canvas`,description:`Nodes, edges, and flow variables — consider the visual designer for complex flows.`,fields:[{field:`nodes`,type:`repeater`,required:!0,helpText:`⚠️ Consider using Flow Designer visual editor instead of JSON`},{field:`edges`,type:`repeater`,required:!0,helpText:`Connections between nodes — use Flow Designer for easier editing`},{field:`variables`,type:`repeater`,helpText:`Flow variables (inputs/outputs)`}]},{name:`execution`,label:`Execution`,description:`Deployment status, identity, and error handling.`,collapsible:!0,collapsed:!0,columns:2,fields:[{field:`status`,required:!0,colSpan:1,helpText:`Deployment status: draft → active → obsolete`},{field:`version`,colSpan:1,helpText:`Version number (auto-incremented)`},{field:`runAs`,colSpan:1,helpText:`Execute as system (admin) or user (current user permissions)`},{field:`errorHandling`,type:`composite`,colSpan:2,helpText:`What to do when a node fails (fail, retry, continue)`}]}]});var JR=A([`pending`,`running`,`paused`,`completed`,`failed`,`cancelled`,`timed_out`,`retrying`]),YR=q(()=>T({nodeId:v().describe(`Node ID that was executed`),nodeType:v().describe(`Node action type (e.g., "decision", "http")`),nodeLabel:v().optional().describe(`Human-readable node label`),status:A([`success`,`failure`,`skipped`]).describe(`Step execution result`),startedAt:v().datetime().describe(`When the step started`),completedAt:v().datetime().optional().describe(`When the step completed`),durationMs:y().int().min(0).optional().describe(`Step execution duration in milliseconds`),input:k(v(),S()).optional().describe(`Input data passed to the node`),output:k(v(),S()).optional().describe(`Output data produced by the node`),error:T({code:v().describe(`Error code`),message:v().describe(`Error message`),stack:v().optional().describe(`Stack trace`)}).optional().describe(`Error details if step failed`),retryAttempt:y().int().min(0).optional().describe(`Retry attempt number (0 = first try)`),parentNodeId:v().optional().describe(`Enclosing structured-region container node ID (loop/parallel/try_catch)`),iteration:y().int().min(0).optional().describe(`Zero-based loop iteration or parallel branch index of the enclosing region`),regionKind:v().optional().describe(`Region kind the step ran in: loop-body | parallel-branch | try | catch`)}));q(()=>T({id:v().describe(`Execution instance ID`),flowName:v().describe(`Machine name of the executed flow`),flowVersion:y().int().optional().describe(`Version of the flow that was executed`),status:JR.describe(`Current execution status`),trigger:T({type:v().describe(`Trigger type (e.g., "record_change", "schedule", "api", "manual")`),recordId:v().optional().describe(`Triggering record ID`),object:v().optional().describe(`Triggering object name`),userId:v().optional().describe(`User who triggered the execution`),metadata:k(v(),S()).optional().describe(`Additional trigger context`)}).describe(`What triggered this execution`),steps:w(YR).describe(`Ordered list of executed steps`),variables:k(v(),S()).optional().describe(`Final state of flow variables`),startedAt:v().datetime().describe(`Execution start timestamp`),completedAt:v().datetime().optional().describe(`Execution completion timestamp`),durationMs:y().int().min(0).optional().describe(`Total execution duration in milliseconds`),runAs:A([`system`,`user`]).optional().describe(`Execution context identity`),tenantId:v().optional().describe(`Tenant ID for multi-tenant isolation`)}));var XR=A([`warning`,`error`,`critical`]);q(()=>T({id:v().describe(`Error record ID`),executionId:v().describe(`Parent execution ID`),nodeId:v().optional().describe(`Node where the error occurred`),severity:XR.describe(`Error severity level`),code:v().describe(`Machine-readable error code`),message:v().describe(`Human-readable error message`),stack:v().optional().describe(`Stack trace for debugging`),context:k(v(),S()).optional().describe(`Additional diagnostic context (input data, config snapshot)`),timestamp:v().datetime().describe(`When the error occurred`),retryable:b().default(!1).describe(`Whether this error can be retried`),resolvedAt:v().datetime().optional().describe(`When the error was resolved (e.g., after successful retry)`)})),q(()=>T({id:v().describe(`Checkpoint ID`),executionId:v().describe(`Parent execution ID`),flowName:v().describe(`Flow machine name`),currentNodeId:v().describe(`Node ID where execution is paused`),variables:k(v(),S()).describe(`Flow variable state at checkpoint`),completedNodeIds:w(v()).describe(`List of node IDs already executed`),createdAt:v().datetime().describe(`Checkpoint creation timestamp`),expiresAt:v().datetime().optional().describe(`Checkpoint expiration (auto-cleanup)`),reason:A([`wait`,`screen_input`,`approval`,`error`,`manual_pause`,`parallel_join`,`boundary_event`]).describe(`Why the execution was checkpointed`)})),q(()=>T({maxConcurrent:y().int().min(1).default(1).describe(`Maximum number of concurrent executions allowed`),onConflict:A([`queue`,`reject`,`cancel_existing`]).default(`queue`).describe(`queue = enqueue for later, reject = fail immediately, cancel_existing = stop running instance`),lockScope:A([`global`,`per_record`,`per_user`]).default(`global`).describe(`Scope of the concurrency lock`),queueTimeoutMs:y().int().min(0).optional().describe(`Maximum time to wait in queue before timing out (ms)`)})),q(()=>T({id:v().describe(`Schedule instance ID`),flowName:v().describe(`Flow machine name`),cronExpression:FL.describe("Cron expression — cron`0 9 * * MON-FRI`"),timezone:v().default(`UTC`).describe(`IANA timezone for cron evaluation`),status:A([`active`,`paused`,`disabled`,`expired`]).default(`active`).describe(`Current schedule status`),nextRunAt:v().datetime().optional().describe(`Next scheduled execution timestamp`),lastRunAt:v().datetime().optional().describe(`Last execution timestamp`),lastExecutionId:v().optional().describe(`Execution ID of the last run`),lastRunStatus:JR.optional().describe(`Status of the last run`),totalRuns:y().int().min(0).default(0).describe(`Total number of executions`),consecutiveFailures:y().int().min(0).default(0).describe(`Consecutive failed executions`),startDate:v().datetime().optional().describe(`Schedule effective start date`),endDate:v().datetime().optional().describe(`Schedule expiration date`),maxRuns:y().int().min(1).optional().describe(`Maximum total executions before auto-disable`),createdAt:v().datetime().describe(`Schedule creation timestamp`),updatedAt:v().datetime().optional().describe(`Last update timestamp`),createdBy:v().optional().describe(`User who created the schedule`)}));var ZR=A([`create`,`update`,`delete`,`undelete`,`api`]),QR=q(()=>T({name:KL.describe(`Webhook unique name (lowercase snake_case)`),label:v().optional().describe(`Human-readable webhook label`),object:v().optional().describe(`Object to listen to (optional for manual webhooks)`),triggers:w(ZR).optional().describe(`Events that trigger execution`),url:v().url().describe(`External webhook endpoint URL`),method:A([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`]).default(`POST`).describe(`HTTP method`),headers:k(v(),v()).optional().describe(`Custom HTTP headers`),body:S().optional().describe(`Request body payload (if not using default record data)`),payloadFields:w(v()).optional().describe(`Fields to include. Empty = All`),includeSession:b().default(!1).describe(`Include user session info`),authentication:T({type:A([`none`,`bearer`,`basic`,`api-key`]).describe(`Authentication type`),credentials:k(v(),v()).optional().describe(`Authentication credentials`)}).optional().describe(`Authentication configuration`),retryPolicy:T({maxRetries:y().int().min(0).max(10).default(3).describe(`Maximum retry attempts`),backoffStrategy:A([`exponential`,`linear`,`fixed`]).default(`exponential`).describe(`Backoff strategy`),initialDelayMs:y().int().min(100).default(1e3).describe(`Initial retry delay in milliseconds`),maxDelayMs:y().int().min(1e3).default(6e4).describe(`Maximum retry delay in milliseconds`)}).optional().describe(`Retry policy configuration`),timeoutMs:y().int().min(1e3).max(3e5).default(3e4).describe(`Request timeout in milliseconds`),secret:v().optional().describe(`Signing secret for HMAC signature verification`),isActive:b().default(!0).describe(`Whether webhook is active`),description:v().optional().describe(`Webhook description`),tags:w(v()).optional().describe(`Tags for organization`)}));q(()=>T({name:KL.describe(`Webhook receiver unique name (lowercase snake_case)`),path:v().describe(`URL Path (e.g. /webhooks/stripe)`),verificationType:A([`none`,`header_token`,`hmac`,`ip_whitelist`]).default(`none`),verificationParams:T({header:v().optional(),secret:v().optional(),ips:w(v()).optional()}).optional(),action:A([`trigger_flow`,`script`,`upsert_record`]).default(`trigger_flow`),target:v().describe(`Flow ID or Script name`)}));var $R=A([`user`,`role`,`team`,`department`,`manager`,`field`,`queue`]);A([`approve`,`reject`]);var ez=q(()=>T({type:$R,value:v().optional().meta({description:"User id / role / team / department / field / queue — per `type`",xRef:{kindFrom:`type`,objectSource:`$trigger`,map:{user:`user`,role:`role`,team:`team`,department:`department`,field:`object-field`,queue:`queue`}}})})),tz=q(()=>T({enabled:b().default(!1).describe(`Enable SLA-based escalation for this node`),timeoutHours:y().min(1).describe(`Hours before escalation triggers`),action:A([`reassign`,`auto_approve`,`auto_reject`,`notify`]).default(`notify`).describe(`Action on escalation timeout`),escalateTo:v().optional().meta({description:`User id, role, or manager level to escalate to`,xRef:{kind:`role`}}),notifySubmitter:b().default(!0).describe(`Notify the original submitter on escalation`)}));q(()=>T({approvers:w(ez).min(1).describe(`Allowed approvers for this node`),behavior:A([`first_response`,`unanimous`]).default(`first_response`).describe(`How to combine multiple approvers`),lockRecord:b().default(!0).describe(`Lock the record from editing while pending`),approvalStatusField:v().optional().meta({description:`Business-object field to mirror request status onto`,xRef:{kind:`object-field`,objectSource:`$trigger`}}),escalation:tz.optional().describe(`Per-node SLA escalation`),maxRevisions:y().int().min(0).default(3).describe(`Max send-backs for revision before auto-reject (0 = send-back disabled)`)}));var nz=q(()=>A([`database`,`api`,`file`,`stream`,`object`,`warehouse`,`storage`,`spreadsheet`])),rz=q(()=>T({type:nz.describe(`Source type`),connector:v().optional().describe(`Connector ID`),config:k(v(),S()).describe(`Source configuration`),incremental:T({enabled:b().default(!1),cursorField:v().describe(`Field to track progress (e.g., updated_at)`),cursorValue:S().optional().describe(`Last processed value`)}).optional().describe(`Incremental extraction config`)})),iz=q(()=>T({type:nz.describe(`Destination type`),connector:v().optional().describe(`Connector ID`),config:k(v(),S()).describe(`Destination configuration`),writeMode:A([`append`,`overwrite`,`upsert`,`merge`]).default(`append`).describe(`How to write data`),primaryKey:w(v()).optional().describe(`Primary key fields`)})),az=q(()=>A([`map`,`filter`,`aggregate`,`join`,`script`,`lookup`,`split`,`merge`,`normalize`,`deduplicate`])),oz=q(()=>T({name:v().optional().describe(`Transformation name`),type:az.describe(`Transformation type`),config:k(v(),S()).describe(`Transformation config`),continueOnError:b().default(!1).describe(`Continue on error`)})),sz=q(()=>A([`full`,`incremental`,`cdc`]));q(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Pipeline identifier (snake_case)`),label:v().optional().describe(`Pipeline display name`),description:v().optional().describe(`Pipeline description`),source:rz.describe(`Data source`),destination:iz.describe(`Data destination`),transformations:w(oz).optional().describe(`Transformation pipeline`),syncMode:sz.default(`full`).describe(`Sync mode`),schedule:FL.optional().describe(`Cron schedule expression`),enabled:b().default(!0).describe(`Pipeline enabled status`),retry:T({maxAttempts:y().int().min(0).default(3).describe(`Max retry attempts`),backoffMs:y().int().min(0).default(6e4).describe(`Backoff in milliseconds`)}).optional().describe(`Retry configuration`),notifications:T({onSuccess:w(v()).optional().describe(`Email addresses for success notifications`),onFailure:w(v()).optional().describe(`Email addresses for failure notifications`)}).optional().describe(`Notification settings`),tags:w(v()).optional().describe(`Pipeline tags`),metadata:k(v(),S()).optional().describe(`Custom metadata`)}));var cz=q(()=>A([`pending`,`running`,`succeeded`,`failed`,`cancelled`,`timeout`]));q(()=>T({id:v().describe(`Run identifier`),pipelineName:v().describe(`Pipeline name`),status:cz.describe(`Run status`),startedAt:v().datetime().describe(`Start time`),completedAt:v().datetime().optional().describe(`Completion time`),durationMs:y().optional().describe(`Duration in ms`),stats:T({recordsRead:y().int().default(0).describe(`Records extracted`),recordsWritten:y().int().default(0).describe(`Records loaded`),recordsErrored:y().int().default(0).describe(`Records with errors`),bytesProcessed:y().int().default(0).describe(`Bytes processed`)}).optional().describe(`Run statistics`),error:T({message:v().describe(`Error message`),code:v().optional().describe(`Error code`),details:S().optional().describe(`Error details`)}).optional().describe(`Error information`),logs:w(v()).optional().describe(`Execution logs`)}));var lz=q(()=>A([`crm`,`payment`,`communication`,`storage`,`analytics`,`database`,`marketing`,`accounting`,`hr`,`productivity`,`ecommerce`,`support`,`devtools`,`social`,`other`])),uz=q(()=>A([`none`,`apiKey`,`basic`,`bearer`,`oauth1`,`oauth2`,`custom`])),dz=q(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Field name (snake_case)`),label:v().describe(`Field label`),type:A([`text`,`password`,`url`,`select`]).default(`text`).describe(`Field type`),description:v().optional().describe(`Field description`),required:b().default(!0).describe(`Required field`),default:v().optional().describe(`Default value`),options:w(T({label:v(),value:v()})).optional().describe(`Select field options`),placeholder:v().optional().describe(`Placeholder text`)})),fz=q(()=>T({authorizationUrl:v().url().describe(`Authorization endpoint URL`),tokenUrl:v().url().describe(`Token endpoint URL`),scopes:w(v()).optional().describe(`OAuth scopes`),clientIdField:v().default(`client_id`).describe(`Client ID field name`),clientSecretField:v().default(`client_secret`).describe(`Client secret field name`)})),pz=q(()=>T({type:uz.describe(`Authentication type`),fields:w(dz).optional().describe(`Authentication fields`),oauth2:fz.optional().describe(`OAuth 2.0 configuration`),test:T({url:v().optional().describe(`Test endpoint URL`),method:A([`GET`,`POST`,`PUT`,`DELETE`]).default(`GET`).describe(`HTTP method`)}).optional().describe(`Authentication test configuration`)})),mz=q(()=>A([`read`,`write`,`delete`,`search`,`trigger`,`action`])),hz=q(()=>T({name:v().describe(`Parameter name`),label:v().describe(`Parameter label`),description:v().optional().describe(`Parameter description`),type:A([`string`,`number`,`boolean`,`array`,`object`,`date`,`file`]).describe(`Parameter type`),required:b().default(!1).describe(`Required parameter`),default:S().optional().describe(`Default value`),validation:k(v(),S()).optional().describe(`Validation rules`),dynamicOptions:v().optional().describe(`Function to load dynamic options`)})),gz=q(()=>T({id:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Operation ID (snake_case)`),name:v().describe(`Operation name`),description:v().optional().describe(`Operation description`),type:mz.describe(`Operation type`),inputSchema:w(hz).optional().describe(`Input parameters`),outputSchema:k(v(),S()).optional().describe(`Output schema`),sampleOutput:S().optional().describe(`Sample output`),supportsPagination:b().default(!1).describe(`Supports pagination`),supportsFiltering:b().default(!1).describe(`Supports filtering`)})),_z=q(()=>T({id:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Trigger ID (snake_case)`),name:v().describe(`Trigger name`),description:v().optional().describe(`Trigger description`),type:A([`webhook`,`polling`,`stream`]).describe(`Trigger mechanism`),config:k(v(),S()).optional().describe(`Trigger configuration`),outputSchema:k(v(),S()).optional().describe(`Event payload schema`),pollingIntervalMs:y().int().min(1e3).optional().describe(`Polling interval in ms`)}));q(()=>T({id:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Connector ID (snake_case)`),name:v().describe(`Connector name`),description:v().optional().describe(`Connector description`),version:v().optional().describe(`Connector version`),icon:v().optional().describe(`Connector icon`),category:lz.describe(`Connector category`),baseUrl:v().url().optional().describe(`API base URL`),authentication:pz.describe(`Authentication config`),operations:w(gz).optional().describe(`Connector operations`),triggers:w(_z).optional().describe(`Connector triggers`),rateLimit:T({requestsPerSecond:y().optional().describe(`Max requests per second`),requestsPerMinute:y().optional().describe(`Max requests per minute`),requestsPerHour:y().optional().describe(`Max requests per hour`)}).optional().describe(`Rate limiting`),author:v().optional().describe(`Connector author`),documentation:v().url().optional().describe(`Documentation URL`),homepage:v().url().optional().describe(`Homepage URL`),license:v().optional().describe(`License (SPDX identifier)`),tags:w(v()).optional().describe(`Connector tags`),verified:b().default(!1).describe(`Verified connector`),metadata:k(v(),S()).optional().describe(`Custom metadata`)})),q(()=>T({id:v().describe(`Instance ID`),connectorId:v().describe(`Connector ID`),name:v().describe(`Instance name`),description:v().optional().describe(`Instance description`),credentials:k(v(),S()).describe(`Encrypted credentials`),config:k(v(),S()).optional().describe(`Additional config`),active:b().default(!0).describe(`Instance active status`),createdAt:v().datetime().optional().describe(`Creation time`),lastTestedAt:v().datetime().optional().describe(`Last test time`),testStatus:A([`unknown`,`success`,`failed`]).default(`unknown`).describe(`Connection test status`)}));var vz=q(()=>D(`type`,[T({type:j(`constant`),value:S().describe(`Constant value to use`)}).describe(`Set a constant value`),T({type:j(`cast`),targetType:A([`string`,`number`,`boolean`,`date`]).describe(`Target data type`)}).describe(`Cast to a specific data type`),T({type:j(`lookup`),table:v().describe(`Lookup table name`),keyField:v().describe(`Field to match on`),valueField:v().describe(`Field to retrieve`)}).describe(`Lookup value from another table`),T({type:j(`javascript`),expression:PL.describe(`JS expression (dialect="js" recommended). e.g. value.toUpperCase()`)}).describe(`Custom JavaScript transformation`),T({type:j(`map`),mappings:k(v(),S()).describe(`Value mappings (e.g., {"Active": "active"})`)}).describe(`Map values using a dictionary`)])),yz=q(()=>T({source:v().describe(`Source field name`),target:v().describe(`Target field name`),transform:vz.optional().describe(`Transformation to apply`),defaultValue:S().optional().describe(`Default if source is null/undefined`)})),bz=q(()=>A([`push`,`pull`,`bidirectional`])),xz=q(()=>A([`full`,`incremental`,`realtime`])),Sz=q(()=>A([`source_wins`,`destination_wins`,`latest_wins`,`manual`,`merge`])),Cz=q(()=>T({object:v().optional().describe(`ObjectStack object name`),filters:S().optional().describe(`Filter conditions`),fields:w(v()).optional().describe(`Fields to sync`),connectorInstanceId:v().optional().describe(`Connector instance ID`),externalResource:v().optional().describe(`External resource ID`)})),wz=q(()=>T({object:v().optional().describe(`ObjectStack object name`),connectorInstanceId:v().optional().describe(`Connector instance ID`),operation:A([`insert`,`update`,`upsert`,`delete`,`sync`]).describe(`Sync operation`),mapping:E([k(v(),v()),w(yz)]).optional().describe(`Field mappings`),externalResource:v().optional().describe(`External resource ID`),matchKey:w(v()).optional().describe(`Match key fields`)}));q(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Sync configuration name (snake_case)`),label:v().optional().describe(`Sync display name`),description:v().optional().describe(`Sync description`),source:Cz.describe(`Data source`),destination:wz.describe(`Data destination`),direction:bz.default(`push`).describe(`Sync direction`),syncMode:xz.default(`incremental`).describe(`Sync mode`),conflictResolution:Sz.default(`latest_wins`).describe(`Conflict resolution`),schedule:FL.optional().describe(`Cron schedule`),enabled:b().default(!0).describe(`Sync enabled`),changeTrackingField:v().optional().describe(`Field for change tracking`),batchSize:y().int().min(1).max(1e4).default(100).describe(`Batch size for processing`),retry:T({maxAttempts:y().int().min(0).default(3).describe(`Max retries`),backoffMs:y().int().min(0).default(3e4).describe(`Backoff duration`)}).optional().describe(`Retry configuration`),validation:T({required:w(v()).optional().describe(`Required fields`),unique:w(v()).optional().describe(`Unique constraint fields`),custom:w(T({name:v(),condition:PL.describe(`Validation predicate (CEL).`),message:v().describe(`Error message`)})).optional().describe(`Custom validation rules`)}).optional().describe(`Validation rules`),errorHandling:T({onValidationError:A([`skip`,`fail`,`log`]).default(`skip`),onSyncError:A([`skip`,`fail`,`retry`]).default(`retry`),notifyOnError:w(v()).optional().describe(`Email notifications`)}).optional().describe(`Error handling`),optimization:T({parallelBatches:b().default(!1).describe(`Process batches in parallel`),cacheEnabled:b().default(!0).describe(`Enable caching`),compressionEnabled:b().default(!1).describe(`Enable compression`)}).optional().describe(`Performance optimization`),audit:T({logLevel:A([`none`,`error`,`warn`,`info`,`debug`]).default(`info`),retainLogsForDays:y().int().min(1).default(30),trackChanges:b().default(!0).describe(`Track all changes`)}).optional().describe(`Audit configuration`),tags:w(v()).optional().describe(`Sync tags`),metadata:k(v(),S()).optional().describe(`Custom metadata`)}));var Tz=q(()=>A([`pending`,`running`,`completed`,`partial`,`failed`,`cancelled`]));q(()=>T({id:v().describe(`Execution ID`),syncName:v().describe(`Sync name`),status:Tz.describe(`Execution status`),startedAt:v().datetime().describe(`Start time`),completedAt:v().datetime().optional().describe(`Completion time`),durationMs:y().optional().describe(`Duration in ms`),stats:T({recordsProcessed:y().int().default(0).describe(`Total records processed`),recordsInserted:y().int().default(0).describe(`Records inserted`),recordsUpdated:y().int().default(0).describe(`Records updated`),recordsDeleted:y().int().default(0).describe(`Records deleted`),recordsSkipped:y().int().default(0).describe(`Records skipped`),recordsErrored:y().int().default(0).describe(`Records with errors`),conflictsDetected:y().int().default(0).describe(`Conflicts detected`),conflictsResolved:y().int().default(0).describe(`Conflicts resolved`)}).optional().describe(`Execution statistics`),errors:w(T({recordId:v().optional().describe(`Record ID`),field:v().optional().describe(`Field name`),message:v().describe(`Error message`),code:v().optional().describe(`Error code`)})).optional().describe(`Errors`),logs:w(v()).optional().describe(`Execution logs`)}));var Ez=q(()=>E([v().describe(`Action Name`),T({type:v(),params:k(v(),S()).optional()})])),Dz=q(()=>E([v().describe(`Guard Name (e.g., "isManager", "amountGT1000")`),T({type:v(),params:k(v(),S()).optional()})])),Oz=q(()=>T({target:v().optional().describe(`Target State ID`),cond:Dz.optional().describe(`Condition (Guard) required to take this path`),actions:w(Ez).optional().describe(`Actions to execute during transition`),description:v().optional().describe(`Human readable description of this rule`)}));q(()=>T({type:v().describe(`Event Type (e.g. "APPROVE", "REJECT", "Submit")`),schema:k(v(),S()).optional().describe(`Expected event payload structure`)}));var kz=M(()=>T({type:A([`atomic`,`compound`,`parallel`,`final`,`history`]).default(`atomic`),entry:w(Ez).optional().describe(`Actions to run when entering this state`),exit:w(Ez).optional().describe(`Actions to run when leaving this state`),on:k(v(),E([v(),Oz,w(Oz)])).optional().describe(`Map of Event Type -> Transition Definition`),always:w(Oz).optional(),initial:v().optional().describe(`Initial child state (if compound)`),states:k(v(),kz).optional(),meta:T({label:v().optional(),description:v().optional(),color:v().optional(),aiInstructions:v().optional().describe(`Specific instructions for AI when in this state`)}).optional()}));q(()=>T({id:KL.describe(`Unique Machine ID`),description:v().optional(),contextSchema:k(v(),S()).optional().describe(`Zod Schema for the machine context/memory`),initial:v().describe(`Initial State ID`),states:k(v(),kz).describe(`State Nodes`),on:k(v(),E([v(),Oz,w(Oz)])).optional()}));var Az=q(()=>A([`timer`,`signal`,`webhook`,`manual`,`condition`]).describe(`Wait event type determining how a paused flow is resumed`));q(()=>T({executionId:v().describe(`Execution ID of the paused flow`),checkpointId:v().describe(`Checkpoint ID to resume from`),nodeId:v().describe(`Wait node ID being resumed`),eventType:Az.describe(`Event type that triggered resume`),signalName:v().optional().describe(`Signal name (when eventType is signal)`),webhookPayload:k(v(),S()).optional().describe(`Webhook request payload (when eventType is webhook)`),resumedBy:v().optional().describe(`User ID or system identifier that triggered resume`),resumedAt:v().datetime().describe(`ISO 8601 timestamp of the resume event`),variables:k(v(),S()).optional().describe(`Variables to merge into flow context upon resume`)}).describe(`Payload for resuming a paused wait node`));var jz=q(()=>A([`fail`,`continue`,`fallback`]).describe(`Behavior when a wait node exceeds its timeout`));q(()=>T({defaultTimeoutMs:y().int().min(0).default(864e5).describe(`Default timeout in ms (default: 24 hours)`),defaultTimeoutBehavior:jz.default(`fail`).describe(`Default behavior when wait timeout is exceeded`),conditionPollIntervalMs:y().int().min(1e3).default(3e4).describe(`Polling interval for condition waits in ms (default: 30s)`),conditionMaxPolls:y().int().min(0).default(0).describe(`Max polling attempts for condition waits (0 = unlimited)`),webhookUrlPattern:v().default(`/api/v1/automation/resume/{executionId}/{nodeId}`).describe(`URL pattern for webhook resume endpoints`),persistCheckpoints:b().default(!0).describe(`Persist wait checkpoints to durable storage`),maxPausedExecutions:y().int().min(0).default(0).describe(`Max concurrent paused executions (0 = unlimited)`)}).describe(`Wait node executor plugin configuration`)),q(()=>T({id:v().describe(`Unique executor plugin identifier`),name:v().describe(`Display name`),nodeTypes:w(v()).min(1).describe(`FlowNodeAction types this executor handles`),version:v().describe(`Plugin version (semver)`),description:v().optional().describe(`Executor description`),supportsPause:b().default(!1).describe(`Whether the executor supports async pause/resume`),supportsCancellation:b().default(!1).describe(`Whether the executor supports mid-execution cancellation`),supportsRetry:b().default(!0).describe(`Whether the executor supports retry on failure`),configSchemaRef:v().optional().describe(`JSON Schema $ref for executor-specific config`)}).describe(`Node executor plugin descriptor`));var Mz=q(()=>A([`logic`,`data`,`io`,`human`,`control`,`custom`]).describe(`Action palette category`)),Nz=q(()=>A([`flow`,`approval`]).describe(`Authoring paradigm that may offer this action`));q(()=>T({type:v().min(1).describe(`Registry action/node type (matches the executor type)`),version:v().describe(`Executor version (semver)`),name:v().describe(`Display label (or i18n key)`),description:v().optional().describe(`Action description`),icon:v().optional().describe(`Icon id resolved by the designer`),category:Mz.default(`custom`).describe(`Palette category`),paradigms:w(Nz).default([`flow`]).describe(`Authoring surfaces that may offer this action`),configSchema:S().optional().describe(`JSON Schema for the node config (drives form + parse validation)`),supportsPause:b().default(!1).describe(`Supports async pause/resume`),supportsCancellation:b().default(!1).describe(`Supports cancellation`),supportsRetry:b().default(!0).describe(`Supports retry on failure`),needsOutbox:b().default(!1).describe(`Dispatch via service-messaging outbox (retry/idempotency/dead-letter)`),isAsync:b().default(!1).describe(`Suspends the flow awaiting an external reply`),maturity:A([`ga`,`beta`,`reserved`]).default(`ga`).describe(`Runtime maturity: ga (shipped), beta, or reserved (contract only — designers grey this out)`),source:A([`builtin`,`plugin`]).default(`plugin`).describe(`builtin = platform baseline; plugin = third-party contributed`),deprecated:b().default(!1).describe(`Deprecated alias kept for back-compat`),aliasOf:v().optional().describe(`Canonical type this alias forwards to`)}).describe(`Canonical cross-paradigm action/node descriptor (ADR-0018)`));var Pz=q(()=>T({bpmnType:v().describe(`BPMN XML element type (e.g., "bpmn:parallelGateway")`),flowNodeAction:v().describe(`ObjectStack FlowNodeAction value`),bidirectional:b().default(!0).describe(`Whether the mapping supports both import and export`),notes:v().optional().describe(`Notes about mapping limitations`)}).describe(`Mapping between BPMN XML element and ObjectStack FlowNodeAction`)),Fz=q(()=>A([`skip`,`warn`,`error`,`comment`]).describe(`Strategy for unmapped BPMN elements during import`));q(()=>T({unmappedStrategy:Fz.default(`warn`).describe(`How to handle unmapped BPMN elements`),customMappings:w(Pz).optional().describe(`Custom element mappings to override or extend defaults`),importLayout:b().default(!0).describe(`Import BPMN DI layout positions into canvas node coordinates`),importDocumentation:b().default(!0).describe(`Import BPMN documentation elements as node descriptions`),flowName:v().optional().describe(`Override flow name (defaults to BPMN process name)`),validateAfterImport:b().default(!0).describe(`Validate imported flow against FlowSchema after import`)}).describe(`Options for importing BPMN 2.0 XML into an ObjectStack flow`));var Iz=q(()=>A([`2.0`,`2.0.2`]).describe(`BPMN specification version for export`));q(()=>T({version:Iz.default(`2.0`).describe(`Target BPMN specification version`),includeLayout:b().default(!0).describe(`Include BPMN DI layout data from canvas positions`),includeExtensions:b().default(!1).describe(`Include ObjectStack extensions in BPMN extensionElements`),customMappings:w(Pz).optional().describe(`Custom element mappings for export`),prettyPrint:b().default(!0).describe(`Pretty-print XML output with indentation`),namespacePrefix:v().default(`bpmn`).describe(`XML namespace prefix for BPMN elements`)}).describe(`Options for exporting an ObjectStack flow as BPMN 2.0 XML`));var Lz=q(()=>T({severity:A([`info`,`warning`,`error`]).describe(`Diagnostic severity`),message:v().describe(`Diagnostic message`),bpmnElementId:v().optional().describe(`BPMN element ID related to this diagnostic`),nodeId:v().optional().describe(`ObjectStack node ID related to this diagnostic`)}).describe(`Diagnostic message from BPMN import/export`));q(()=>T({success:b().describe(`Whether the operation completed successfully`),diagnostics:w(Lz).default([]).describe(`Diagnostic messages from the operation`),mappedCount:y().int().min(0).default(0).describe(`Number of elements successfully mapped`),unmappedCount:y().int().min(0).default(0).describe(`Number of elements that could not be mapped`)}).describe(`Result of a BPMN import/export operation`));var Rz=t({ADMIN_FULL_ACCESS:()=>ADMIN_FULL_ACCESS,BUILTIN_ROLE_ORG_ADMIN:()=>BUILTIN_ROLE_ORG_ADMIN,BUILTIN_ROLE_ORG_MEMBER:()=>BUILTIN_ROLE_ORG_MEMBER,BUILTIN_ROLE_ORG_OWNER:()=>BUILTIN_ROLE_ORG_OWNER,BUILTIN_ROLE_PLATFORM_ADMIN:()=>t_,InvitationStatus:()=>QB,RoleSchema:()=>Vz,SCIMAddressSchema:()=>iV,SCIMBulkOperationSchema:()=>dV,SCIMBulkResponseOperationSchema:()=>fV,SCIMEmailSchema:()=>nV,SCIMEnterpriseUserSchema:()=>oV,SCIMGroupReferenceSchema:()=>aV,SCIMGroupSchema:()=>lV,SCIMMemberReferenceSchema:()=>cV,SCIMMetaSchema:()=>eV,SCIMNameSchema:()=>tV,SCIMPatchOperationSchema:()=>uV,SCIMPhoneNumberSchema:()=>rV,SCIMUserSchema:()=>sV,SCIM_SCHEMAS:()=>$B});function J(e){if(typeof process<`u`&&{}.OS_EAGER_SCHEMAS===`1`)return e();let t,n=()=>(t===void 0&&(t=e()),t);return new Proxy(function(){},{get(e,t){let r=n(),i=r[t];return typeof i==`function`?i.bind(r):i},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())}})}J(()=>T({id:v().describe(`Unique user identifier`),email:v().email().describe(`User email address`),emailVerified:b().default(!1).describe(`Whether email is verified`),name:v().optional().describe(`User display name`),image:v().url().optional().describe(`Profile image URL`),createdAt:v().datetime().describe(`Account creation timestamp`),updatedAt:v().datetime().describe(`Last update timestamp`)})),J(()=>T({id:v().describe(`Unique account identifier`),userId:v().describe(`Associated user ID`),type:A([`oauth`,`oidc`,`email`,`credentials`,`saml`,`ldap`]).describe(`Account type`),provider:v().describe(`Provider name`),providerAccountId:v().describe(`Provider account ID`),refreshToken:v().optional().describe(`OAuth refresh token`),accessToken:v().optional().describe(`OAuth access token`),expiresAt:y().optional().describe(`Token expiry timestamp (Unix)`),tokenType:v().optional().describe(`OAuth token type`),scope:v().optional().describe(`OAuth scope`),idToken:v().optional().describe(`OAuth ID token`),sessionState:v().optional().describe(`Session state`),createdAt:v().datetime().describe(`Account creation timestamp`),updatedAt:v().datetime().describe(`Last update timestamp`)})),J(()=>T({id:v().describe(`Unique session identifier`),sessionToken:v().describe(`Session token`),userId:v().describe(`Associated user ID`),activeOrganizationId:v().optional().describe(`Active organization ID for context switching`),expires:v().datetime().describe(`Session expiry timestamp`),createdAt:v().datetime().describe(`Session creation timestamp`),updatedAt:v().datetime().describe(`Last update timestamp`),ipAddress:v().optional().describe(`IP address`),userAgent:v().optional().describe(`User agent string`),fingerprint:v().optional().describe(`Device fingerprint`)})),J(()=>T({identifier:v().describe(`Token identifier (email or phone)`),token:v().describe(`Verification token`),expires:v().datetime().describe(`Token expiry timestamp`),createdAt:v().datetime().describe(`Token creation timestamp`)})),J(()=>T({id:v().describe(`API key identifier`),name:v().describe(`API key display name`),start:v().optional().describe(`Key prefix for identification`),prefix:v().optional().describe(`Custom key prefix`),userId:v().describe(`Owner user ID`),organizationId:v().optional().describe(`Scoped organization ID`),expiresAt:v().datetime().optional().describe(`Expiration timestamp`),createdAt:v().datetime().describe(`Creation timestamp`),updatedAt:v().datetime().describe(`Last update timestamp`),lastUsedAt:v().datetime().optional().describe(`Last used timestamp`),lastRefetchAt:v().datetime().optional().describe(`Last refetch timestamp`),enabled:b().default(!0).describe(`Whether the key is active`),rateLimitEnabled:b().optional().describe(`Whether rate limiting is enabled`),rateLimitTimeWindow:y().int().min(0).optional().describe(`Rate limit window (ms)`),rateLimitMax:y().int().min(0).optional().describe(`Max requests per window`),remaining:y().int().min(0).optional().describe(`Remaining requests`),permissions:k(v(),b()).optional().describe(`Granular permission flags`),scopes:w(v()).optional().describe(`High-level access scopes`),metadata:k(v(),S()).optional().describe(`Custom metadata`)}));var zz=J(()=>v().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)`)),Bz=J(()=>v().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)`));J(()=>v().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 Vz=J(()=>T({name:Bz.describe(`Unique role name (lowercase snake_case)`),label:v().describe(`Display label (e.g. VP of Sales)`),parent:v().optional().describe(`Parent Role ID (Reports To)`),description:v().optional()})),Hz=A([`none`,`no-overlay`,`no-delete`,`full`]),Uz=A([`artifact`,`package`,`env-forced`]),Wz=A([`package`,`org`,`env-forced`]),Gz={_lock:Hz.optional().describe(`Item-level lock — controls overlay & delete (ADR-0010).`),_lockReason:v().max(500).optional().describe(`Human-readable reason shown when a write is refused by _lock.`),_lockSource:Uz.optional().describe(`Layer that set _lock (artifact | package | env-forced).`),_provenance:Wz.optional().describe(`Origin of the item (package | org | env-forced).`),_packageId:v().optional().describe(`Owning package machine id.`),_packageVersion:v().optional().describe(`Owning package version.`),_lockDocsUrl:v().optional().describe(`Optional documentation link surfaced next to _lockReason.`)},Kz=T({lock:Hz.describe(`Lock policy — none | no-overlay | no-delete | full.`),reason:v().min(1).max(500).describe(`User-visible reason shown when the lock blocks an action.`),docsUrl:v().url().optional().describe(`Optional URL the Studio banner links to for more context.`)}).strict(),qz=A([`cel`,`js`,`cron`,`template`]),Jz=T({rationale:v().optional(),generatedBy:v().optional()}),Yz=T({dialect:qz,source:v().min(1).optional(),ast:S().optional(),meta:Jz.optional()}).refine(e=>e.source!==void 0||e.ast!==void 0,{message:"Expression requires at least one of `source` or `ast`"}),Xz=E([v().min(1).transform(e=>({dialect:`cel`,source:e})),Yz]);E([v().min(1).transform(e=>({dialect:`cron`,source:e})),Yz]),E([v().min(1).transform(e=>({dialect:`template`,source:e})),Yz]),J(()=>T({key:v().describe(`Translation key (e.g., "views.task_list.label")`),defaultValue:v().optional().describe(`Fallback value when translation key is not found`),params:k(v(),E([v(),y(),b()])).optional().describe(`Interpolation parameters (e.g., { count: 5 })`)}));var Zz=J(()=>v().describe(`Display label (plain string; i18n keys are auto-generated by the framework)`)),Qz=J(()=>T({ariaLabel:Zz.optional().describe(`Accessible label for screen readers (WAI-ARIA aria-label)`),ariaDescribedBy:v().optional().describe(`ID of element providing additional description (WAI-ARIA aria-describedby)`),role:v().optional().describe(`WAI-ARIA role attribute (e.g., "dialog", "navigation", "alert")`)}).describe(`ARIA accessibility attributes`));J(()=>T({key:v().describe(`Translation key`),zero:v().optional().describe(`Zero form (e.g., "No items")`),one:v().optional().describe(`Singular form (e.g., "{count} item")`),two:v().optional().describe(`Dual form (e.g., "{count} items" for exactly 2)`),few:v().optional().describe(`Few form (e.g., for 2-4 in some languages)`),many:v().optional().describe(`Many form (e.g., for 5+ in some languages)`),other:v().describe(`Default plural form (e.g., "{count} items")`)}).describe(`ICU plural rules for a translation key`));var $z=J(()=>T({style:A([`decimal`,`currency`,`percent`,`unit`]).default(`decimal`).describe(`Number formatting style`),currency:v().optional().describe(`ISO 4217 currency code (e.g., "USD", "EUR")`),unit:v().optional().describe(`Unit for unit formatting (e.g., "kilometer", "liter")`),minimumFractionDigits:y().optional().describe(`Minimum number of fraction digits`),maximumFractionDigits:y().optional().describe(`Maximum number of fraction digits`),useGrouping:b().optional().describe(`Whether to use grouping separators (e.g., 1,000)`)}).describe(`Number formatting rules`)),eB=J(()=>T({dateStyle:A([`full`,`long`,`medium`,`short`]).optional().describe(`Date display style`),timeStyle:A([`full`,`long`,`medium`,`short`]).optional().describe(`Time display style`),timeZone:v().optional().describe(`IANA time zone (e.g., "America/New_York")`),hour12:b().optional().describe(`Use 12-hour format`)}).describe(`Date/time formatting rules`));J(()=>T({code:v().describe(`BCP 47 language code (e.g., "en-US", "zh-CN")`),fallbackChain:w(v()).optional().describe(`Fallback language codes in priority order (e.g., ["zh-TW", "en"])`),direction:A([`ltr`,`rtl`]).default(`ltr`).describe(`Text direction: left-to-right or right-to-left`),numberFormat:$z.optional().describe(`Default number formatting rules`),dateFormat:eB.optional().describe(`Default date/time formatting rules`)}).describe(`Locale configuration`));var tB=J(()=>T({enabled:b().default(!1).describe(`Enable public sharing`),publicLink:v().optional().describe(`Generated public share URL`),password:v().optional().describe(`Password required to access shared link`),allowedDomains:w(v()).optional().describe(`Restrict access to specific email domains (e.g. ["example.com"])`),expiresAt:v().optional().describe(`Expiration date/time in ISO 8601 format`),allowAnonymous:b().optional().default(!1).describe(`Allow access without authentication`)}));J(()=>T({enabled:b().default(!1).describe(`Enable iframe embedding`),allowedOrigins:w(v()).optional().describe(`Allowed iframe parent origins (e.g. ["https://example.com"])`),width:v().optional().default(`100%`).describe(`Embed width (CSS value)`),height:v().optional().default(`600px`).describe(`Embed height (CSS value)`),showHeader:b().optional().default(!0).describe(`Show interface header in embed`),showNavigation:b().optional().default(!1).describe(`Show navigation in embed`),responsive:b().optional().default(!0).describe(`Enable responsive resizing`)}));var nB=A([`xs`,`sm`,`md`,`lg`,`xl`,`2xl`]),rB=J(()=>T({xs:y().min(1).max(12).optional(),sm:y().min(1).max(12).optional(),md:y().min(1).max(12).optional(),lg:y().min(1).max(12).optional(),xl:y().min(1).max(12).optional(),"2xl":y().min(1).max(12).optional()}).describe(`Grid columns per breakpoint (1-12)`)),iB=J(()=>T({xs:y().optional(),sm:y().optional(),md:y().optional(),lg:y().optional(),xl:y().optional(),"2xl":y().optional()}).describe(`Display order per breakpoint`)),aB=J(()=>T({breakpoint:nB.optional().describe(`Minimum breakpoint for visibility`),hiddenOn:w(nB).optional().describe(`Hide on these breakpoints`),columns:rB.optional().describe(`Grid columns per breakpoint`),order:iB.optional().describe(`Display order per breakpoint`)}).describe(`Responsive layout configuration`)),oB=J(()=>k(v(),E([v(),y()])).describe(`CSS property → value map (camelCase keys; design tokens encouraged)`));J(()=>T({large:oB.optional().describe(`Unconditional base (desktop-first)`),medium:oB.optional().describe(`Applied at ≤ medium breakpoint`),small:oB.optional().describe(`Applied at ≤ small breakpoint`),xsmall:oB.optional().describe(`Applied at ≤ xsmall breakpoint`)}).describe(`Per-breakpoint scoped style maps (ADR-0065)`));var sB=J(()=>T({lazyLoad:b().optional().describe(`Enable lazy loading (defer rendering until visible)`),virtualScroll:T({enabled:b().default(!1).describe(`Enable virtual scrolling`),itemHeight:y().optional().describe(`Fixed item height in pixels (for estimation)`),overscan:y().optional().describe(`Number of extra items to render outside viewport`)}).optional().describe(`Virtual scrolling configuration`),cacheStrategy:A([`none`,`cache-first`,`network-first`,`stale-while-revalidate`]).optional().describe(`Client-side data caching strategy`),prefetch:b().optional().describe(`Prefetch data before component is visible`),pageSize:y().optional().describe(`Number of items per page for pagination`),debounceMs:y().optional().describe(`Debounce interval for user interactions in milliseconds`)}).describe(`Performance optimization configuration`)),cB=A(`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(`.`)),lB=J(()=>T({label:v().describe(`Display label (human-readable, any case allowed)`),value:zz.describe(`Stored value (lowercase machine identifier)`),color:v().optional().describe(`Color code for badges/charts`),default:b().optional().describe(`Is default option`)}));J(()=>T({latitude:y().min(-90).max(90).describe(`Latitude coordinate`),longitude:y().min(-180).max(180).describe(`Longitude coordinate`),altitude:y().optional().describe(`Altitude in meters`),accuracy:y().optional().describe(`Accuracy in meters`)}));var uB=J(()=>T({precision:y().int().min(0).max(10).default(2).describe(`Decimal precision (default: 2)`),currencyMode:A([`dynamic`,`fixed`]).default(`dynamic`).describe(`Currency mode: dynamic (user selectable) or fixed (single currency)`),defaultCurrency:v().length(3).default(`CNY`).describe(`Default or fixed currency code (ISO 4217, e.g., USD, CNY, EUR)`)}));J(()=>T({value:y().describe(`Monetary amount`),currency:v().length(3).describe(`Currency code (ISO 4217)`)})),J(()=>T({street:v().optional().describe(`Street address`),city:v().optional().describe(`City name`),state:v().optional().describe(`State/Province`),postalCode:v().optional().describe(`Postal/ZIP code`),country:v().optional().describe(`Country name or code`),countryCode:v().optional().describe(`ISO country code (e.g., US, GB)`),formatted:v().optional().describe(`Formatted address string`)}));var dB=J(()=>T({dimensions:y().int().min(1).max(1e4).describe(`Vector dimensionality (e.g., 1536 for OpenAI embeddings)`),distanceMetric:A([`cosine`,`euclidean`,`dotProduct`,`manhattan`]).default(`cosine`).describe(`Distance/similarity metric for vector search`),normalized:b().default(!1).describe(`Whether vectors are normalized (unit length)`),indexed:b().default(!0).describe(`Whether to create a vector index for fast similarity search`),indexType:A([`hnsw`,`ivfflat`,`flat`]).optional().describe(`Vector index algorithm (HNSW for high accuracy, IVFFlat for large datasets)`)})),fB=J(()=>T({minSize:y().min(0).optional().describe(`Minimum file size in bytes`),maxSize:y().min(1).optional().describe(`Maximum file size in bytes (e.g., 10485760 = 10MB)`),allowedTypes:w(v()).optional().describe(`Allowed file extensions (e.g., [".pdf", ".docx", ".jpg"])`),blockedTypes:w(v()).optional().describe(`Blocked file extensions (e.g., [".exe", ".bat", ".sh"])`),allowedMimeTypes:w(v()).optional().describe(`Allowed MIME types (e.g., ["image/jpeg", "application/pdf"])`),blockedMimeTypes:w(v()).optional().describe(`Blocked MIME types`),virusScan:b().default(!1).describe(`Enable virus scanning for uploaded files`),virusScanProvider:A([`clamav`,`virustotal`,`metadefender`,`custom`]).optional().describe(`Virus scanning service provider`),virusScanOnUpload:b().default(!0).describe(`Scan files immediately on upload`),quarantineOnThreat:b().default(!0).describe(`Quarantine files if threat detected`),storageProvider:v().optional().describe(`Object storage provider name (references ObjectStorageConfig)`),storageBucket:v().optional().describe(`Target bucket name`),storagePrefix:v().optional().describe(`Storage path prefix (e.g., "uploads/documents/")`),imageValidation:T({minWidth:y().min(1).optional().describe(`Minimum image width in pixels`),maxWidth:y().min(1).optional().describe(`Maximum image width in pixels`),minHeight:y().min(1).optional().describe(`Minimum image height in pixels`),maxHeight:y().min(1).optional().describe(`Maximum image height in pixels`),aspectRatio:v().optional().describe(`Required aspect ratio (e.g., "16:9", "1:1")`),generateThumbnails:b().default(!1).describe(`Auto-generate thumbnails`),thumbnailSizes:w(T({name:v().describe(`Thumbnail variant name (e.g., "small", "medium", "large")`),width:y().min(1).describe(`Thumbnail width in pixels`),height:y().min(1).describe(`Thumbnail height in pixels`),crop:b().default(!1).describe(`Crop to exact dimensions`)})).optional().describe(`Thumbnail size configurations`),preserveMetadata:b().default(!1).describe(`Preserve EXIF metadata`),autoRotate:b().default(!0).describe(`Auto-rotate based on EXIF orientation`)}).optional().describe(`Image-specific validation rules`),allowMultiple:b().default(!1).describe(`Allow multiple file uploads (overrides field.multiple)`),allowReplace:b().default(!0).describe(`Allow replacing existing files`),allowDelete:b().default(!0).describe(`Allow deleting uploaded files`),requireUpload:b().default(!1).describe(`Require at least one file when field is required`),extractMetadata:b().default(!0).describe(`Extract file metadata (name, size, type, etc.)`),extractText:b().default(!1).describe(`Extract text content from documents (OCR/parsing)`),versioningEnabled:b().default(!1).describe(`Keep previous versions of replaced files`),maxVersions:y().min(1).optional().describe(`Maximum number of versions to retain`),publicRead:b().default(!1).describe(`Allow public read access to uploaded files`),presignedUrlExpiry:y().min(60).max(604800).default(3600).describe(`Presigned URL expiration in seconds (default: 1 hour)`)}).refine(e=>!(e.minSize!==void 0&&e.maxSize!==void 0&&e.minSize>e.maxSize),{message:`minSize must be less than or equal to maxSize`}).refine(e=>!(e.virusScanProvider!==void 0&&e.virusScan!==!0),{message:`virusScanProvider requires virusScan to be enabled`}));J(()=>T({uniqueness:b().default(!1).describe(`Enforce unique values across all records`),completeness:y().min(0).max(1).default(0).describe(`Minimum ratio of non-null values (0-1, default: 0 = no requirement)`),accuracy:T({source:v().describe(`Reference data source for validation (e.g., "api.verify.com", "master_data")`),threshold:y().min(0).max(1).describe(`Minimum accuracy threshold (0-1, e.g., 0.95 = 95% match required)`)}).optional().describe(`Accuracy validation configuration`)})),J(()=>T({enabled:b().describe(`Enable caching for computed field results`),ttl:y().min(0).describe(`Cache TTL in seconds (0 = no expiration)`),invalidateOn:w(v()).describe(`Field paths that invalidate cache (e.g., ["inventory.quantity", "pricing.base_price"])`)})),J(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Machine name (snake_case)`).optional(),label:v().optional().describe(`Human readable label`),type:cB.describe(`Field Data Type`),description:v().optional().describe(`Tooltip/Help text`),format:v().optional().describe(`Format string (e.g. email, phone)`),columnName:v().optional().describe(`Physical column name in the target datasource. Defaults to the field key when not set.`),required:b().default(!1).describe(`Is required`),searchable:b().default(!1).describe(`Is searchable`),multiple:b().default(!1).describe(`Allow multiple values (Stores as Array/JSON). Applicable for select, lookup, file, image.`),unique:b().default(!1).describe(`Is unique constraint`),defaultValue:S().optional().describe(`Default value`),maxLength:y().optional().describe(`Max character length`),minLength:y().optional().describe(`Min character length`),precision:y().optional().describe(`Total digits`),scale:y().optional().describe(`Decimal places`),min:y().optional().describe(`Minimum value`),max:y().optional().describe(`Maximum value`),options:w(lB).optional().describe(`Static options for select/multiselect`),reference:v().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.`),referenceFilters:w(v()).optional().describe(`Filters applied to lookup dialogs (e.g. "active = true")`),deleteBehavior:A([`set_null`,`cascade`,`restrict`]).optional().default(`set_null`).describe(`What happens if referenced record is deleted`),inlineEdit:E([b(),A([`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:v().optional().describe(`Title for the inline master-detail grid`),inlineColumns:w(x()).optional().describe(`Explicit columns for the inline grid (derived from the child object when omitted)`),inlineAmountField:v().optional().describe(`Numeric child field summed for the inline grid total`),relatedList:b().optional().describe(`Show this child collection as a related list on the parent's detail page (read-side mirror of inlineEdit). Defaults to shown for master_detail/lookup; set false to suppress.`),relatedListTitle:v().optional().describe(`Title for the detail-page related list`),relatedListColumns:w(x()).optional().describe(`Explicit columns for the detail-page related list (derived from the child object when omitted)`),displayField:v().optional().describe(`Field shown as each candidate's label in the picker/popover (defaults to the referenced object's name/title).`),descriptionField:v().optional().describe(`Secondary field shown under the label in the quick-select popover.`),lookupColumns:w(E([v(),T({field:v(),label:v().optional(),width:v().optional(),type:v().optional()})])).optional().describe(`Explicit columns for the record-picker table; auto-derived from the referenced object when omitted.`),lookupPageSize:y().int().positive().optional().describe(`Rows per page in the record-picker dialog (default 10).`),lookupFilters:w(T({field:v(),operator:A([`eq`,`ne`,`gt`,`lt`,`gte`,`lte`,`contains`,`in`,`notIn`]),value:x()})).optional().describe(`Base filters restricting which records are selectable (e.g. only active). Structured, picker-honoured form of referenceFilters.`),dependsOn:w(E([v(),T({field:v(),param:v().optional()})])).optional().describe(`Dependent lookup: restrict candidates by the value of other field(s) on the same record. String = same local/remote key; {field,param} when the remote filter key differs.`),allowCreate:b().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:Xz.optional().describe("Formula expression (CEL). e.g. F`record.amount * 0.1`"),returnType:A([`number`,`text`,`boolean`,`date`]).optional().describe(`Inferred value type of a formula field (number/text/boolean/date)`),summaryOperations:T({object:v().describe(`Source child object name for roll-up`),field:v().describe(`Field on child object to aggregate (ignored for count)`),function:A([`count`,`sum`,`min`,`max`,`avg`]).describe(`Aggregation function to apply`),relationshipField:v().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.`)}).optional().describe(`Roll-up summary definition. The engine recomputes the value when child records are inserted/updated/deleted.`),language:v().optional().describe(`Programming language for syntax highlighting (e.g., javascript, python, sql)`),maxRating:y().optional().describe(`Maximum rating value (default: 5)`),step:y().optional().describe(`Step increment for slider (default: 1)`),currencyConfig:uB.optional().describe(`Configuration for currency field type`),dimensions:y().int().min(1).max(1e4).optional().describe(`Vector dimensionality (e.g., 1536 for OpenAI embeddings)`),vectorConfig:dB.optional().describe(`Configuration for vector field type (AI/ML embeddings)`),fileAttachmentConfig:fB.optional().describe(`Configuration for file and attachment field types`),trackHistory:b().optional().describe(`Render this field's value changes as human-readable entries on the record activity timeline (ADR-0052 §5b). Opt-in per field.`),dependencies:w(v()).optional().describe(`Array of field names that this field depends on (for formulas, visibility rules, etc.)`),group:v().optional().describe(`Field group name for organizing fields in forms and layouts (e.g., "contact_info", "billing", "system")`),visibleWhen:Xz.optional().describe("Predicate (CEL) — field is shown only when TRUE (else hidden). e.g. P`record.type == 'invoice'`"),readonlyWhen:Xz.optional().describe("Predicate (CEL) — field is read-only when TRUE. e.g. P`record.status == 'paid'`"),requiredWhen:Xz.optional().describe("Predicate (CEL) — field is required when TRUE. Canonical name for `conditionalRequired`."),conditionalRequired:Xz.optional().describe("Predicate (CEL) — field is required when TRUE. Alias of `requiredWhen`."),hidden:b().default(!1).describe(`Hidden from default UI`),readonly:b().default(!1).describe(`Read-only in UI`),requiredPermissions:w(v()).optional().describe(`[ADR-0066 D3] Capabilities required to read/edit this field (mask on read, deny on write; AND-gate).`),system:b().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:b().optional().default(!0).describe(`Whether field is sortable in list views`),inlineHelpText:v().optional().describe(`Help text displayed below the field in forms`),caseSensitive:b().optional().describe(`Whether text comparisons are case-sensitive`),autonumberFormat:v().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).`),index:b().default(!1).describe(`Create standard database index`),externalId:b().default(!1).describe(`Is external ID for upsert operations`)}));var pB=A([`GET`,`POST`,`PUT`,`DELETE`,`PATCH`,`HEAD`,`OPTIONS`]),mB=J(()=>A([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`])),hB=J(()=>T({url:v().describe(`API endpoint URL`),method:mB.optional().default(`GET`).describe(`HTTP method`),headers:k(v(),v()).optional().describe(`Custom HTTP headers`),params:k(v(),S()).optional().describe(`Query parameters`),body:S().optional().describe(`Request body for POST/PUT/PATCH`)}));J(()=>T({enabled:b().default(!0).describe(`Enable CORS`),origins:E([v(),w(v())]).default(`*`).describe(`Allowed origins (* for all)`),methods:w(pB).optional().describe(`Allowed HTTP methods`),credentials:b().default(!1).describe(`Allow credentials (cookies, authorization headers)`),maxAge:y().int().optional().describe(`Preflight cache duration in seconds`)})),J(()=>T({enabled:b().default(!1).describe(`Enable rate limiting`),windowMs:y().int().default(6e4).describe(`Time window in milliseconds`),maxRequests:y().int().default(100).describe(`Max requests per window`)})),J(()=>T({path:v().describe(`URL path to serve from`),directory:v().describe(`Physical directory to serve`),cacheControl:v().optional().describe(`Cache-Control header value`)}));var gB=J(()=>D(`provider`,[T({provider:j(`object`),object:v().describe(`Target object name`)}),T({provider:j(`api`),read:hB.optional().describe(`Configuration for fetching data`),write:hB.optional().describe(`Configuration for submitting data (for forms/editable tables)`)}),T({provider:j(`value`),items:w(S()).describe(`Static data array`)}),T({provider:j(`schema`),schemaId:v().describe(`Schema identifier — typically the metadata type name`),schema:k(v(),S()).optional().describe(`Inline JSON Schema (Draft 2020-12). Optional when schemaId is resolvable.`)})])),_B=J(()=>T({field:v().describe(`Field name to filter on`),operator:v().describe(`Filter operator (e.g. equals, not_equals, contains, this_quarter)`),value:E([v(),y(),b(),ul(),w(E([v(),y()]))]).optional().describe(`Filter value`)}).describe(`View filter rule`)),vB=J(()=>A([`none`,`count`,`count_empty`,`count_filled`,`count_unique`,`percent_empty`,`percent_filled`,`sum`,`avg`,`min`,`max`]).describe(`Aggregation function for column footer summary`)),yB=J(()=>T({field:v().describe(`Field name (snake_case)`),label:Zz.optional().describe(`Display label override`),width:y().positive().optional().describe(`Column width in pixels`),align:A([`left`,`center`,`right`]).optional().describe(`Text alignment`),hidden:b().optional().describe(`Hide column by default`),sortable:b().optional().describe(`Allow sorting by this column`),resizable:b().optional().describe(`Allow resizing this column`),wrap:b().optional().describe(`Allow text wrapping`),type:v().optional().describe(`Renderer type override (e.g., "currency", "date")`),pinned:A([`left`,`right`]).optional().describe(`Pin/freeze column to left or right side`),summary:vB.optional().describe(`Footer aggregation function for this column`),link:b().optional().describe(`Functions as the primary navigation link (triggers View navigation)`),action:v().optional().describe(`Registered Action ID to execute when clicked`)})),bB=J(()=>T({type:A([`none`,`single`,`multiple`]).default(`none`).describe(`Selection mode`)})),xB=J(()=>T({pageSize:y().int().positive().default(25).describe(`Number of records per page`),pageSizeOptions:w(y().int().positive()).optional().describe(`Available page size options`)})),SB=J(()=>A([`compact`,`short`,`medium`,`tall`,`extra_tall`]).describe(`Row height / density setting for list view`)),CB=J(()=>T({field:v().describe(`Field name to group by`),order:A([`asc`,`desc`]).default(`asc`).describe(`Group sort order`),collapsed:b().default(!1).describe(`Collapse groups by default`)})),wB=J(()=>T({fields:w(CB).min(1).describe(`Fields to group by (supports up to 3 levels)`)}).describe(`Record grouping configuration`)),TB=J(()=>T({coverField:v().optional().describe(`Attachment/image field to display as card cover`),coverFit:A([`cover`,`contain`]).default(`cover`).describe(`Image fit mode for card cover`),cardSize:A([`small`,`medium`,`large`]).default(`medium`).describe(`Card size in gallery view`),titleField:v().optional().describe(`Field to display as card title`),visibleFields:w(v()).optional().describe(`Fields to display on card body`)}).describe(`Gallery/card view configuration`)),EB=J(()=>T({startDateField:v().describe(`Field for timeline item start date`),endDateField:v().optional().describe(`Field for timeline item end date`),titleField:v().describe(`Field to display as timeline item title`),groupByField:v().optional().describe(`Field to group timeline rows`),colorField:v().optional().describe(`Field to determine item color`),scale:A([`hour`,`day`,`week`,`month`,`quarter`,`year`]).default(`week`).describe(`Default timeline scale`)}).describe(`Timeline view configuration`)),DB=J(()=>T({type:A([`personal`,`collaborative`]).default(`collaborative`).describe(`View ownership type`),lockedBy:v().optional().describe(`User who locked the view configuration`)}).describe(`View sharing and access configuration`)),OB=J(()=>T({field:v().describe(`Field to derive color from (typically a select/status field)`),colors:k(v(),v()).optional().describe(`Map of field value to color (hex/token)`)}).describe(`Row color configuration based on field values`)),kB=J(()=>A([`grid`,`kanban`,`gallery`,`calendar`,`timeline`,`gantt`,`map`,`chart`,`tree`]).describe(`Visualization type that users can switch to`)),AB=J(()=>T({sort:b().default(!0).describe(`Allow users to sort records`),search:b().default(!0).describe(`Allow users to search records`),filter:b().default(!0).describe(`Allow users to filter records`),rowHeight:b().default(!0).describe(`Allow users to toggle row height/density`),addRecordForm:b().default(!1).describe(`Add records through a form instead of inline`),buttons:w(v()).optional().describe(`Custom action button IDs to show in the toolbar`)}).describe(`User action toggles for the view toolbar`)),jB=J(()=>T({showDescription:b().default(!0).describe(`Show the view description text`),allowedVisualizations:w(kB).optional().describe(`Whitelist of visualization types users can switch between (e.g. ["grid", "gallery", "kanban"])`)}).describe(`Appearance and visualization configuration`)),MB=J(()=>T({name:Bz.describe(`Tab identifier (snake_case)`),label:Zz.optional().describe(`Display label`),icon:v().optional().describe(`Tab icon name`),view:v().optional().describe(`Referenced list view name from listViews`),filter:w(_B).optional().describe(`Tab-specific filter criteria`),order:y().int().min(0).optional().describe(`Tab display order`),pinned:b().default(!1).describe(`Pin tab (cannot be removed by users)`),isDefault:b().default(!1).describe(`Set as the default active tab`),visible:b().default(!0).describe(`Tab visibility`)}).describe(`Tab configuration for multi-tab view interface`)),NB=J(()=>T({field:v().describe(`Field name on the source object (must exist — checked by reference diagnostics)`),label:Zz.optional().describe(`Display label override (defaults to the field label)`),type:A([`select`,`multi-select`,`boolean`,`date-range`,`text`]).optional().describe(`Filter control type. Omit to infer from the field definition`),options:w(T({value:E([v(),y(),b()]).describe(`Option value`),label:Zz.describe(`Option label`),color:v().optional().describe(`Option color token/hex`)})).optional().describe(`Static options. Omit to derive from the field definition (select options / lookup records)`),showCount:b().optional().describe(`Show per-option record counts`),defaultValues:w(E([v(),y(),b()])).optional().describe(`Pre-selected values when the view loads`)}).describe(`Quick-filter field configuration`)),PB=J(()=>T({element:A([`dropdown`,`tabs`,`toggle`]).default(`dropdown`).describe(`Filter control style: "dropdown" (per-field value selectors) or "tabs" (named presets). "toggle" is deprecated.`),fields:w(NB).optional().describe(`Fields exposed as quick filters (dropdown/toggle elements)`),tabs:w(MB).optional().describe(`Named filter presets rendered as tabs (tabs element). Reuses ViewTabSchema`),showAllRecords:b().optional().describe(`Show an "All records" tab before the presets (tabs element)`)}).describe(`End-user quick-filter configuration (Airtable "User filters" parity)`)),FB=J(()=>T({enabled:b().default(!0).describe(`Show the add record entry point`),position:A([`top`,`bottom`,`both`]).default(`bottom`).describe(`Position of the add record button`),mode:A([`inline`,`form`,`modal`]).default(`inline`).describe(`How to add a new record`),formView:v().optional().describe(`Named form view to use when mode is "form" or "modal"`)}).describe(`Add record entry point configuration`)),IB=J(()=>T({groupByField:v().describe(`Field to group columns by (usually status/select)`),summarizeField:v().optional().describe(`Field to sum at top of column (e.g. amount)`),columns:w(v()).describe(`Fields to show on cards`)})),LB=J(()=>T({chartType:A([`bar`,`line`,`pie`,`area`,`scatter`]).default(`bar`).describe(`Chart visualisation type`),dataset:Bz.describe(`Dataset name to bind (ADR-0021)`),dimensions:w(v()).optional().describe(`Dimension names — X/group/split`),values:w(v()).min(1).describe(`Measure names — Y (at least one)`)}).describe(`List chart view configuration`)),RB=J(()=>T({startDateField:v(),endDateField:v().optional(),titleField:v(),colorField:v().optional()})),zB=J(()=>T({field:v().describe(`Record field / dot-path the dimension filters on`),label:v().optional().describe(`Trigger label (falls back to the field label)`),options:w(E([v(),T({value:E([v(),y()]),label:v().optional()})])).optional().describe(`Explicit option override for fixed enums`)})),BB=J(()=>T({startDateField:v(),endDateField:v(),titleField:v(),progressField:v().optional(),dependenciesField:v().optional(),colorField:v().optional().describe(`Field that drives the bar color`),parentField:v().optional().describe(`Field holding the parent task id (builds the summary → step tree)`),typeField:v().optional().describe(`Field whose value maps to task/summary/milestone`),baselineStartField:v().optional().describe(`Baseline (planned) start field`),baselineEndField:v().optional().describe(`Baseline (planned) end field`),groupByField:v().optional().describe(`Field to group leaf tasks by (synthesized summary rows)`),resourceView:b().optional().describe(`Render a per-resource workload histogram instead of the timeline`),assigneeField:v().optional().describe(`Resource field to bucket load by (resource view)`),effortField:v().optional().describe(`Per-task load units (resource view; default 1)`),capacity:y().optional().describe(`Per-resource capacity ceiling; loads above this flag overload`),tooltipFields:w(E([v(),T({field:v(),label:v().optional()})])).optional().describe(`Fields to surface in the hover tooltip, in display order`),quickFilters:w(zB).optional().describe(`Multi-select filter dropdowns rendered above the chart`),autoZoomToFilter:b().optional().describe(`When true (default), filtering zooms the range to the filtered tasks`)}).passthrough()),VB=J(()=>T({parentField:v().optional().describe(`Single-parent pointer field (auto-detected from the object schema when omitted)`),labelField:v().optional().describe(`Field rendered indented in the first column (defaults to "name")`),fields:w(v()).optional().describe(`Additional fields rendered as flat columns alongside the label`),defaultExpandedDepth:y().int().min(0).optional().describe(`Initial expansion depth (0 = roots only; omit = expand all)`)}).passthrough()),HB=J(()=>A([`page`,`drawer`,`modal`,`split`,`popover`,`new_window`,`none`])),UB=J(()=>T({mode:HB.default(`page`),view:v().optional().describe(`Name of the form view to use for details (e.g. "summary_view", "edit_form")`),preventNavigation:b().default(!1).describe(`Disable standard navigation entirely`),openNewTab:b().default(!1).describe(`Force open in new tab (applies to page mode)`),width:E([v(),y()]).optional().describe(`Width of the drawer/modal (e.g. "600px", "50%")`)})),WB=J(()=>T({name:Bz.optional().describe(`Internal view name (lowercase snake_case)`),label:Zz.optional(),type:A([`grid`,`kanban`,`gallery`,`calendar`,`timeline`,`gantt`,`map`,`chart`,`tree`]).default(`grid`),data:gB.optional().describe(`Data source configuration (defaults to "object" provider)`),columns:E([w(v()),w(yB)]).describe(`Fields to display as columns`),filter:w(_B).optional().describe(`Filter criteria (JSON Rules)`),sort:E([v(),w(T({field:v(),order:A([`asc`,`desc`])}))]).optional(),searchableFields:w(v()).optional().describe(`Fields enabled for search`),filterableFields:w(v()).optional().describe(`Legacy shorthand for userFilters.fields — bare field names enabled for end-user filtering. Prefer userFilters`),userFilters:PB.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:b().optional().describe(`Enable column resizing`),striped:b().optional().describe(`Striped row styling`),bordered:b().optional().describe(`Show borders`),compactToolbar:b().optional().describe(`Collapse Group/Color/Density/Hide-fields into a single View settings popover`),selection:bB.optional().describe(`Row selection configuration`),navigation:UB.optional().describe(`Configuration for item click navigation (page, drawer, modal, etc.)`),pagination:xB.optional().describe(`Pagination configuration`),kanban:IB.optional(),calendar:RB.optional(),gantt:BB.optional(),gallery:TB.optional(),timeline:EB.optional(),chart:LB.optional(),tree:VB.optional(),description:Zz.optional().describe(`View description for documentation/tooltips`),sharing:DB.optional().describe(`View sharing and access configuration`),rowHeight:SB.optional().describe(`Row height / density setting`),grouping:wB.optional().describe(`Group records by one or more fields`),rowColor:OB.optional().describe(`Color rows based on field value`),hiddenFields:w(v()).optional().describe(`Fields to hide in this specific view`),fieldOrder:w(v()).optional().describe(`Explicit field display order for this view`),rowActions:w(v()).optional().describe(`Actions available for individual row items`),bulkActions:w(v()).optional().describe(`Actions available when multiple rows are selected`),bulkActionDefs:w(k(v(),x())).optional().describe(`Rich bulk action definitions (schema-driven, executed via BulkActionDialog)`),virtualScroll:b().optional().describe(`Enable virtual scrolling for large datasets`),conditionalFormatting:w(T({condition:Xz.describe(`Predicate (CEL) to evaluate.`),style:k(v(),v()).describe(`CSS styles to apply when condition is true`)})).optional().describe(`Conditional formatting rules for list rows`),inlineEdit:b().optional().describe(`Allow inline editing of records directly in the list view`),exportOptions:w(A([`csv`,`xlsx`,`pdf`,`json`])).optional().describe(`Available export format options`),userActions:AB.optional().describe(`User action toggles for the view toolbar`),appearance:jB.optional().describe(`Appearance and visualization configuration`),tabs:w(MB).optional().describe(`Tab definitions for multi-tab view interface`),addRecord:FB.optional().describe(`Add record entry point configuration`),showRecordCount:b().optional().describe(`Show record count at the bottom of the list`),allowPrinting:b().optional().describe(`Allow users to print the view`),emptyState:T({title:Zz.optional(),message:Zz.optional(),icon:v().optional()}).optional().describe(`Empty state configuration when no records found`),aria:Qz.optional().describe(`ARIA accessibility attributes for the list view`),responsive:aB.optional().describe(`Responsive layout configuration`),performance:sB.optional().describe(`Performance optimization settings`)})),GB=J(()=>T({field:v().describe(`Field name (snake_case)`),type:cB.optional().describe(`Field type (auto-infers widget if omitted)`),options:w(lB).optional().describe(`Options for select/multiselect/radio/checkboxes fields`),reference:v().optional().describe(`Target object name for lookup/master_detail fields`),maxLength:y().optional().describe(`Maximum character length (for text/textarea/email/url/phone)`),minLength:y().optional().describe(`Minimum character length`),min:y().optional().describe(`Minimum value (for number/currency/percent/slider)`),max:y().optional().describe(`Maximum value`),precision:y().optional().describe(`Total digits (for number/currency)`),scale:y().optional().describe(`Decimal places`),multiple:b().optional().describe(`Allow multiple values (for select/lookup/file/image)`),label:Zz.optional().describe(`Display label override`),placeholder:Zz.optional().describe(`Placeholder text`),helpText:Zz.optional().describe(`Help/hint text`),readonly:b().optional().describe(`Read-only override`),immutable:b().optional().describe(`Editable on create, locked once the record exists (e.g. machine names).`),required:b().optional().describe(`Required override`),hidden:b().optional().describe(`Hidden override`),colSpan:y().int().min(1).max(4).optional().describe(`Column span in grid layout (1-4)`),widget:v().optional().describe(`Custom widget/component name (overrides type-based inference)`),language:v().optional().describe(`Code editor language (for type=code)`),fields:w(M(()=>GB)).optional().describe(`Sub-fields for composite/repeater/record types`),keyField:T({field:v().default(`name`).describe(`Property name that holds the key inside each item (defaults to "name")`),label:Zz.optional().describe(`Display label for the key column`),placeholder:Zz.optional().describe(`Placeholder when entering a new key`),helpText:Zz.optional().describe(`Help text under the key input`),regex:v().optional().describe(`JS regex source string the key must match (no flags)`),immutable:b().default(!0).describe(`If true, the key is read-only after creation`)}).optional().describe(`Key column config for record-typed fields`),dependsOn:v().optional().describe(`Parent field name for cascading`),visibleOn:Xz.optional().describe(`Visibility predicate (CEL).`),disclosure:A([`inline`,`popover`]).optional().describe(`Composite rendering: inline bordered box (default) or a summary line + gear popover (progressive disclosure).`)})),KB=J(()=>T({name:v().optional().describe(`Stable section identifier for i18n lookup (snake_case)`),label:Zz.optional(),description:v().optional().describe(`Optional description rendered under the section header.`),collapsible:b().default(!1),collapsed:b().default(!1),visibleOn:Xz.optional().describe(`Visibility predicate (CEL). Hides the whole section when false.`),columns:E([A([`1`,`2`,`3`,`4`]),j(1),j(2),j(3),j(4)]).default(1).transform(e=>typeof e==`string`?parseInt(e):e),fields:w(E([v(),GB]))})),qB=J(()=>T({type:A([`simple`,`tabbed`,`wizard`,`split`,`drawer`,`modal`]).default(`simple`),data:gB.optional().describe(`Data source configuration (defaults to "object" provider)`),sections:w(KB).optional(),groups:w(KB).optional(),subforms:w(T({childObject:v().describe(`Child object whose records are entered inline`),relationshipField:v().optional().describe(`FK on the child pointing back to the parent (auto-detected when omitted)`),columns:w(x()).optional().describe(`Editable grid columns (derived from the child object when omitted)`),amountField:v().optional().describe(`Numeric child column summed for the running total`),totalField:v().optional().describe(`Parent field to receive the rolled-up sum`),title:v().optional().describe(`Section title`),addLabel:v().optional().describe(`Add-row button label`),minRows:y().optional(),maxRows:y().optional()})).optional().describe(`Inline master-detail child collections`),defaultSort:w(T({field:v().describe(`Field name to sort by`),order:A([`asc`,`desc`]).default(`desc`).describe(`Sort direction`)})).optional().describe(`Default sort order for related list views within this form`),sharing:tB.optional().describe(`Public sharing configuration for this form`),submitBehavior:E([T({kind:j(`thank-you`),title:v().optional(),message:v().optional()}),T({kind:j(`redirect`),url:v(),delayMs:y().int().min(0).optional()}),T({kind:j(`continue`)}),T({kind:j(`next-record`)})]).optional().describe(`Post-submit behavior`),aria:Qz.optional().describe(`ARIA accessibility attributes for the form view`)}));J(()=>T({list:WB.optional(),form:qB.optional(),listViews:k(v(),WB).optional().describe(`Additional named list views`),formViews:k(v(),qB).optional().describe(`Additional named form views`),protection:Kz.optional().describe(`Package author protection block — lock policy for this view.`),...Gz}));var JB=v().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>`."),YB=A([`package`,`shared`,`personal`]).describe(`View identity layer: package | shared | personal.`);A([`list`,`form`]).describe("Whether `config` is a ListView (list family) or a FormView.");function XB(){return{name:JB,object:v().describe(`Bound object name — the foreign key used to aggregate views.`),label:Zz.optional().describe(`Display label (supports i18n).`),isDefault:b().optional().describe(`Whether this is the object's default view in the switcher.`),order:y().int().optional().describe(`Sort order within the object's view switcher / left rail.`),scope:YB.optional().describe("Identity layer (defaults to `package` for source-loaded views)."),owner:v().optional().describe("Owner user id — set when `scope` is `personal`."),hidden:b().optional().describe(`Hidden from the switcher (per-user / per-org declutter).`),protection:Kz.optional().describe(`Package author protection block — lock policy for this view.`),...Gz}}J(()=>D(`viewKind`,[T({viewKind:j(`list`),config:WB.describe(`List-family view configuration.`),...XB()}),T({viewKind:j(`form`),config:qB.describe(`Form view configuration.`),...XB()})]));function ZB(e){let{schemaId:t,...n}=e;return qB.parse({...n,data:{provider:`schema`,schemaId:t}})}ZB({schemaId:`role`,type:`simple`,sections:[{label:`Role`,description:`Roles compose a hierarchy used for record sharing (sales VP → sales mgr → sales rep). Permissions themselves live on Permission Sets and Profiles.`,columns:2,fields:[{field:`name`,required:!0,helpText:`snake_case`},{field:`label`,required:!0},{field:`parent`,helpText:`Parent role machine name (Reports To)`,colSpan:2},{field:`description`,colSpan:2}]}]}),J(()=>T({id:v().describe(`Unique organization identifier`),name:v().describe(`Organization display name`),slug:v().regex(/^[a-z0-9_-]+$/).describe(`Unique URL-friendly slug (lowercase alphanumeric, hyphens, underscores)`),logo:v().url().optional().describe(`Organization logo URL`),metadata:k(v(),S()).optional().describe(`Custom metadata`),createdAt:v().datetime().describe(`Organization creation timestamp`),updatedAt:v().datetime().describe(`Last update timestamp`)})),J(()=>T({id:v().describe(`Unique member identifier`),organizationId:v().describe(`Organization ID`),userId:v().describe(`User ID`),role:v().describe(`Member role (e.g., owner, admin, member, guest)`),createdAt:v().datetime().describe(`Member creation timestamp`),updatedAt:v().datetime().describe(`Last update timestamp`)}));var QB=A([`pending`,`accepted`,`rejected`,`expired`]);J(()=>T({id:v().describe(`Unique invitation identifier`),organizationId:v().describe(`Organization ID`),email:v().email().describe(`Invitee email address`),role:v().describe(`Role to assign upon acceptance`),status:QB.default(`pending`).describe(`Invitation status`),expiresAt:v().datetime().describe(`Invitation expiry timestamp`),inviterId:v().describe(`User ID of the inviter`),createdAt:v().datetime().describe(`Invitation creation timestamp`),updatedAt:v().datetime().describe(`Last update timestamp`)}));var $B={USER:`urn:ietf:params:scim:schemas:core:2.0:User`,GROUP:`urn:ietf:params:scim:schemas:core:2.0:Group`,ENTERPRISE_USER:`urn:ietf:params:scim:schemas:extension:enterprise:2.0:User`,RESOURCE_TYPE:`urn:ietf:params:scim:schemas:core:2.0:ResourceType`,SERVICE_PROVIDER_CONFIG:`urn:ietf:params:scim:schemas:core:2.0:ServiceProviderConfig`,SCHEMA:`urn:ietf:params:scim:schemas:core:2.0:Schema`,LIST_RESPONSE:`urn:ietf:params:scim:api:messages:2.0:ListResponse`,PATCH_OP:`urn:ietf:params:scim:api:messages:2.0:PatchOp`,BULK_REQUEST:`urn:ietf:params:scim:api:messages:2.0:BulkRequest`,BULK_RESPONSE:`urn:ietf:params:scim:api:messages:2.0:BulkResponse`,ERROR:`urn:ietf:params:scim:api:messages:2.0:Error`},eV=J(()=>T({resourceType:v().optional().describe(`Resource type`),created:v().datetime().optional().describe(`Creation timestamp`),lastModified:v().datetime().optional().describe(`Last modification timestamp`),location:v().url().optional().describe(`Resource location URI`),version:v().optional().describe(`Entity tag (ETag) for concurrency control`)})),tV=J(()=>T({formatted:v().optional().describe(`Formatted full name`),familyName:v().optional().describe(`Family name (last name)`),givenName:v().optional().describe(`Given name (first name)`),middleName:v().optional().describe(`Middle name`),honorificPrefix:v().optional().describe(`Honorific prefix (Mr., Ms., Dr.)`),honorificSuffix:v().optional().describe(`Honorific suffix (Jr., Sr.)`)})),nV=J(()=>T({value:v().email().describe(`Email address`),type:A([`work`,`home`,`other`]).optional().describe(`Email type`),display:v().optional().describe(`Display label`),primary:b().optional().default(!1).describe(`Primary email indicator`)})),rV=J(()=>T({value:v().describe(`Phone number`),type:A([`work`,`home`,`mobile`,`fax`,`pager`,`other`]).optional().describe(`Phone number type`),display:v().optional().describe(`Display label`),primary:b().optional().default(!1).describe(`Primary phone indicator`)})),iV=J(()=>T({formatted:v().optional().describe(`Formatted address`),streetAddress:v().optional().describe(`Street address`),locality:v().optional().describe(`City/Locality`),region:v().optional().describe(`State/Region`),postalCode:v().optional().describe(`Postal code`),country:v().optional().describe(`Country`),type:A([`work`,`home`,`other`]).optional().describe(`Address type`),primary:b().optional().default(!1).describe(`Primary address indicator`)})),aV=J(()=>T({value:v().describe(`Group ID`),$ref:v().url().optional().describe(`URI reference to the group`),display:v().optional().describe(`Group display name`),type:A([`direct`,`indirect`]).optional().describe(`Membership type`)})),oV=J(()=>T({employeeNumber:v().optional().describe(`Employee number`),costCenter:v().optional().describe(`Cost center`),organization:v().optional().describe(`Organization`),division:v().optional().describe(`Division`),department:v().optional().describe(`Department`),manager:T({value:v().describe(`Manager ID`),$ref:v().url().optional().describe(`Manager URI`),displayName:v().optional().describe(`Manager name`)}).optional().describe(`Manager reference`)})),sV=J(()=>T({schemas:w(v()).min(1).refine(e=>e.includes($B.USER),`Must include core User schema URI`).default([$B.USER]).describe(`SCIM schema URIs (must include User schema)`),id:v().optional().describe(`Unique resource identifier`),externalId:v().optional().describe(`External identifier from client system`),userName:v().describe(`Unique username (REQUIRED)`),name:tV.optional().describe(`Structured name components`),displayName:v().optional().describe(`Display name for UI`),nickName:v().optional().describe(`Nickname`),profileUrl:v().url().optional().describe(`Profile page URL`),title:v().optional().describe(`Job title`),userType:v().optional().describe(`User type (employee, contractor)`),preferredLanguage:v().optional().describe(`Preferred language (ISO 639-1)`),locale:v().optional().describe(`Locale (e.g., en-US)`),timezone:v().optional().describe(`Timezone`),active:b().optional().default(!0).describe(`Account active status`),password:v().optional().describe(`Password (write-only)`),emails:w(nV).optional().describe(`Email addresses`),phoneNumbers:w(rV).optional().describe(`Phone numbers`),ims:w(T({value:v(),type:v().optional(),primary:b().optional()})).optional().describe(`IM addresses`),photos:w(T({value:v().url(),type:A([`photo`,`thumbnail`]).optional(),primary:b().optional()})).optional().describe(`Photo URLs`),addresses:w(iV).optional().describe(`Physical addresses`),groups:w(aV).optional().describe(`Group memberships`),entitlements:w(T({value:v(),type:v().optional(),primary:b().optional()})).optional().describe(`Entitlements`),roles:w(T({value:v(),type:v().optional(),primary:b().optional()})).optional().describe(`Roles`),x509Certificates:w(T({value:v(),type:v().optional(),primary:b().optional()})).optional().describe(`X509 certificates`),meta:eV.optional().describe(`Resource metadata`),[$B.ENTERPRISE_USER]:oV.optional().describe(`Enterprise user attributes`)}).superRefine((e,t)=>{e[$B.ENTERPRISE_USER]!=null&&((e.schemas||[]).includes($B.ENTERPRISE_USER)||t.addIssue({code:ru.custom,path:[`schemas`],message:`schemas must include "${$B.ENTERPRISE_USER}" when enterprise user extension attributes are present`}))})),cV=J(()=>T({value:v().describe(`Member ID`),$ref:v().url().optional().describe(`URI reference to the member`),type:A([`User`,`Group`]).optional().describe(`Member type`),display:v().optional().describe(`Member display name`)})),lV=J(()=>T({schemas:w(v()).min(1).refine(e=>e.includes($B.GROUP),`Must include core Group schema URI`).default([$B.GROUP]).describe(`SCIM schema URIs (must include Group schema)`),id:v().optional().describe(`Unique resource identifier`),externalId:v().optional().describe(`External identifier from client system`),displayName:v().describe(`Group display name (REQUIRED)`),members:w(cV).optional().describe(`Group members`),meta:eV.optional().describe(`Resource metadata`)}));J(()=>T({schemas:w(v()).min(1).refine(e=>e.includes($B.LIST_RESPONSE),{message:`schemas must include ${$B.LIST_RESPONSE}`}).default([$B.LIST_RESPONSE]).describe(`SCIM schema URIs`),totalResults:y().int().min(0).describe(`Total results count`),Resources:w(E([sV,lV,k(v(),S())])).describe(`Resources array (Users, Groups, or custom resources)`),startIndex:y().int().min(1).optional().describe(`Start index (1-based)`),itemsPerPage:y().int().min(0).optional().describe(`Items per page`)})),J(()=>T({schemas:w(v()).min(1).refine(e=>e.includes($B.ERROR),{message:`schemas must include ${$B.ERROR}`}).default([$B.ERROR]).describe(`SCIM schema URIs`),status:y().int().min(400).max(599).describe(`HTTP status code`),scimType:A([`invalidFilter`,`tooMany`,`uniqueness`,`mutability`,`invalidSyntax`,`invalidPath`,`noTarget`,`invalidValue`,`invalidVers`,`sensitive`]).optional().describe(`SCIM error type`),detail:v().optional().describe(`Error detail message`)}));var uV=J(()=>T({op:A([`add`,`remove`,`replace`]).describe(`Operation type`),path:v().optional().describe(`Attribute path (optional for add)`),value:S().optional().describe(`Value to set`)}));J(()=>T({schemas:w(v()).min(1).refine(e=>e.includes($B.PATCH_OP),{message:`SCIM PATCH requests must include the PatchOp schema URI`}).default([$B.PATCH_OP]).describe(`SCIM schema URIs`),Operations:w(uV).min(1).describe(`Patch operations`)}));var dV=J(()=>T({method:A([`POST`,`PUT`,`PATCH`,`DELETE`]).describe(`HTTP method for the bulk operation`),path:v().describe(`Resource endpoint path (e.g. /Users, /Groups/{id})`),bulkId:v().optional().describe(`Client-assigned ID for cross-referencing between operations`),data:k(v(),S()).optional().describe(`Request body for POST/PUT/PATCH operations`),version:v().optional().describe(`ETag for optimistic concurrency control`)}));J(()=>T({schemas:w(j($B.BULK_REQUEST)).default([$B.BULK_REQUEST]).describe(`SCIM schema URIs (BulkRequest)`),operations:w(dV).min(1).describe(`Bulk operations to execute (minimum 1)`),failOnErrors:y().int().optional().describe(`Stop processing after this many errors`)}));var fV=J(()=>T({method:A([`POST`,`PUT`,`PATCH`,`DELETE`]).describe(`HTTP method that was executed`),bulkId:v().optional().describe(`Client-assigned bulk operation ID`),location:v().optional().describe(`URL of the created or modified resource`),status:v().describe(`HTTP status code as string (e.g. "201", "400")`),response:S().optional().describe(`Response body (typically present for errors)`)}));J(()=>T({schemas:w(j($B.BULK_RESPONSE)).default([$B.BULK_RESPONSE]).describe(`SCIM schema URIs (BulkResponse)`),operations:w(fV).describe(`Results for each bulk operation`)})),J(()=>T({id:v().describe(`User ID`),name:v().optional().describe(`Display name`),email:v().optional().describe(`Email address`),roles:w(v()).default([]).describe(`Canonical role names assigned to the user (scope-resolved)`),isPlatformAdmin:b().optional().describe(`DERIVED alias of 'platform_admin' in roles. Deprecated.`),organizationId:v().nullable().optional().describe(`Active organization ID (null = platform/unscoped)`)}));var pV=t({AuditPolicySchema:()=>HH,CriteriaSharingRuleSchema:()=>IH,FieldPermissionSchema:()=>xV,NetworkPolicySchema:()=>BH,ObjectAccessScopeSchema:()=>yV,ObjectPermissionSchema:()=>bV,OwnerSharingRuleSchema:()=>LH,PasswordPolicySchema:()=>zH,PermissionSetSchema:()=>SV,PolicySchema:()=>UH,RLSAuditConfigSchema:()=>vV,RLSOperation:()=>gV,RowLevelSecurityPolicySchema:()=>_V,SessionPolicySchema:()=>VH,ShareRecipientType:()=>PH,SharingLevel:()=>NH,TerritoryType:()=>RH});function Y(e){if(typeof process<`u`&&{}.OS_EAGER_SCHEMAS===`1`)return e();let t,n=()=>(t===void 0&&(t=e()),t);return new Proxy(function(){},{get(e,t){let r=n(),i=r[t];return typeof i==`function`?i.bind(r):i},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())}})}var mV=Y(()=>v().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)`)),hV=Y(()=>v().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)`));Y(()=>v().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 gV=A([`select`,`insert`,`update`,`delete`,`all`]),_V=Y(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Policy unique identifier (snake_case)`),label:v().optional().describe(`Human-readable policy label`),description:v().optional().describe(`Policy description and business justification`),object:v().describe(`Target object name`),operation:gV.describe(`Database operation this policy applies to`),using:v().optional().describe("Filter condition for SELECT/UPDATE/DELETE. One of the four compiler-supported forms: `field = current_user.<prop>`, `field = 'literal'`, `field IN (current_user.<array>)`, or `1 = 1`. Optional for INSERT-only policies."),check:v().optional().describe(`Validation condition for INSERT/UPDATE (defaults to USING clause if not specified - enforced at application level)`),roles:w(v()).optional().describe(`Roles this policy applies to (omit for all roles)`),enabled:b().default(!0).describe(`Whether this policy is active`),priority:y().int().default(0).describe(`Policy evaluation priority (higher = evaluated first)`),tags:w(v()).optional().describe(`Policy categorization tags`)}).superRefine((e,t)=>{!e.using&&!e.check&&t.addIssue({code:ru.custom,message:`At least one of "using" or "check" must be specified. For SELECT/UPDATE/DELETE operations, provide "using". For INSERT operations, provide "check".`})}));Y(()=>T({timestamp:v().describe(`ISO 8601 timestamp of the evaluation`),userId:v().describe(`User ID whose access was evaluated`),operation:A([`select`,`insert`,`update`,`delete`]).describe(`Database operation being performed`),object:v().describe(`Target object name`),policyName:v().describe(`Name of the RLS policy evaluated`),granted:b().describe(`Whether access was granted`),evaluationDurationMs:y().describe(`Policy evaluation duration in milliseconds`),matchedCondition:v().optional().describe(`Which USING/CHECK clause matched`),rowCount:y().optional().describe(`Number of rows affected`),metadata:k(v(),S()).optional().describe(`Additional audit event metadata`)}));var vV=Y(()=>T({enabled:b().describe(`Enable RLS audit logging`),logLevel:A([`all`,`denied_only`,`granted_only`,`none`]).describe(`Which evaluations to log`),destination:A([`system_log`,`audit_trail`,`external`]).describe(`Audit log destination`),sampleRate:y().min(0).max(1).describe(`Sampling rate (0-1) for high-traffic environments`),retentionDays:y().int().default(90).describe(`Audit log retention period in days`),includeRowData:b().default(!1).describe(`Include row data in audit logs (security-sensitive)`),alertOnDenied:b().default(!0).describe(`Send alerts when access is denied`)}));Y(()=>T({enabled:b().default(!0).describe(`Enable RLS enforcement globally`),defaultPolicy:A([`deny`,`allow`]).default(`deny`).describe(`Default action when no policies match`),allowSuperuserBypass:b().default(!0).describe(`Allow superusers to bypass RLS`),bypassRoles:w(v()).optional().describe(`Roles that bypass RLS (see all data)`),logEvaluations:b().default(!1).describe(`Log RLS policy evaluations for debugging`),cacheResults:b().default(!0).describe(`Cache RLS evaluation results`),cacheTtlSeconds:y().int().positive().default(300).describe(`Cache TTL in seconds`),prefetchUserContext:b().default(!0).describe(`Pre-fetch user context for performance`),audit:vV.optional().describe(`RLS audit logging configuration`)})),Y(()=>T({id:v().describe(`User ID`),email:v().email().optional().describe(`User email`),tenantId:v().optional().describe(`Tenant/Organization ID`),role:E([v(),w(v())]).optional().describe(`User role(s)`),department:v().optional().describe(`User department`),attributes:k(v(),S()).optional().describe(`Additional custom user attributes`)})),Y(()=>T({policyName:v().describe(`Policy name`),granted:b().describe(`Whether access was granted`),durationMs:y().optional().describe(`Evaluation duration in milliseconds`),error:v().optional().describe(`Error message if evaluation failed`),usingResult:b().optional().describe(`USING clause evaluation result`),checkResult:b().optional().describe(`CHECK clause evaluation result`)}));var yV=A([`own`,`own_and_reports`,`unit`,`unit_and_below`,`org`]),bV=Y(()=>T({allowCreate:b().default(!1).describe(`Create permission`),allowRead:b().default(!1).describe(`Read permission`),allowEdit:b().default(!1).describe(`Edit permission`),allowDelete:b().default(!1).describe(`Delete permission`),allowTransfer:b().default(!1).describe(`[EXPERIMENTAL — not enforced] Change record ownership`),allowRestore:b().default(!1).describe(`[EXPERIMENTAL — not enforced] Restore from trash (Undelete)`),allowPurge:b().default(!1).describe(`[EXPERIMENTAL — not enforced] Permanently delete (Hard Delete/GDPR)`),viewAllRecords:b().default(!1).describe(`View All Data (Bypass Sharing)`),modifyAllRecords:b().default(!1).describe(`Modify All Data (Bypass Sharing)`),readScope:yV.optional().describe(`[ADR-0057 D1] Read depth: own|unit|unit_and_below|org`),writeScope:yV.optional().describe(`[ADR-0057 D1] Write depth: own|unit|unit_and_below|org`)})),xV=Y(()=>T({readable:b().default(!0).describe(`Field read access`),editable:b().default(!1).describe(`Field edit access`)})),SV=Y(()=>T({name:hV.describe(`Permission set unique name (lowercase snake_case)`),label:v().optional().describe(`Display label`),isProfile:b().default(!1).describe(`Whether this is a user profile`),isDefault:b().default(!1).describe(`[ADR-0056 D7] When true, this profile is the FALLBACK assigned to authenticated users who have no explicit grants — an app declares its default access posture here instead of relying on the built-in member_default. Foundation for SSO/JIT provisioning.`),objects:k(v(),bV).describe(`Entity permissions`),fields:k(v(),xV).optional().describe(`Field level security`),systemPermissions:w(v()).optional().describe(`System level capabilities`),tabPermissions:k(v(),A([`visible`,`hidden`,`default_on`,`default_off`])).optional().describe(`App/tab visibility: visible, hidden, default_on (shown by default), default_off (available but hidden initially)`),rowLevelSecurity:w(_V).optional().describe(`Row-level security policies (see rls.zod.ts for full spec)`),contextVariables:k(v(),S()).optional().describe(`Context variables for RLS evaluation`)})),CV=A([`none`,`no-overlay`,`no-delete`,`full`]),wV=A([`artifact`,`package`,`env-forced`]),TV=A([`package`,`org`,`env-forced`]),EV={_lock:CV.optional().describe(`Item-level lock — controls overlay & delete (ADR-0010).`),_lockReason:v().max(500).optional().describe(`Human-readable reason shown when a write is refused by _lock.`),_lockSource:wV.optional().describe(`Layer that set _lock (artifact | package | env-forced).`),_provenance:TV.optional().describe(`Origin of the item (package | org | env-forced).`),_packageId:v().optional().describe(`Owning package machine id.`),_packageVersion:v().optional().describe(`Owning package version.`),_lockDocsUrl:v().optional().describe(`Optional documentation link surfaced next to _lockReason.`)},DV=T({lock:CV.describe(`Lock policy — none | no-overlay | no-delete | full.`),reason:v().min(1).max(500).describe(`User-visible reason shown when the lock blocks an action.`),docsUrl:v().url().optional().describe(`Optional URL the Studio banner links to for more context.`)}).strict(),OV=A([`cel`,`js`,`cron`,`template`]),kV=T({rationale:v().optional(),generatedBy:v().optional()}),AV=T({dialect:OV,source:v().min(1).optional(),ast:S().optional(),meta:kV.optional()}).refine(e=>e.source!==void 0||e.ast!==void 0,{message:"Expression requires at least one of `source` or `ast`"}),jV=E([v().min(1).transform(e=>({dialect:`cel`,source:e})),AV]);E([v().min(1).transform(e=>({dialect:`cron`,source:e})),AV]),E([v().min(1).transform(e=>({dialect:`template`,source:e})),AV]),Y(()=>T({key:v().describe(`Translation key (e.g., "views.task_list.label")`),defaultValue:v().optional().describe(`Fallback value when translation key is not found`),params:k(v(),E([v(),y(),b()])).optional().describe(`Interpolation parameters (e.g., { count: 5 })`)}));var MV=Y(()=>v().describe(`Display label (plain string; i18n keys are auto-generated by the framework)`)),NV=Y(()=>T({ariaLabel:MV.optional().describe(`Accessible label for screen readers (WAI-ARIA aria-label)`),ariaDescribedBy:v().optional().describe(`ID of element providing additional description (WAI-ARIA aria-describedby)`),role:v().optional().describe(`WAI-ARIA role attribute (e.g., "dialog", "navigation", "alert")`)}).describe(`ARIA accessibility attributes`));Y(()=>T({key:v().describe(`Translation key`),zero:v().optional().describe(`Zero form (e.g., "No items")`),one:v().optional().describe(`Singular form (e.g., "{count} item")`),two:v().optional().describe(`Dual form (e.g., "{count} items" for exactly 2)`),few:v().optional().describe(`Few form (e.g., for 2-4 in some languages)`),many:v().optional().describe(`Many form (e.g., for 5+ in some languages)`),other:v().describe(`Default plural form (e.g., "{count} items")`)}).describe(`ICU plural rules for a translation key`));var PV=Y(()=>T({style:A([`decimal`,`currency`,`percent`,`unit`]).default(`decimal`).describe(`Number formatting style`),currency:v().optional().describe(`ISO 4217 currency code (e.g., "USD", "EUR")`),unit:v().optional().describe(`Unit for unit formatting (e.g., "kilometer", "liter")`),minimumFractionDigits:y().optional().describe(`Minimum number of fraction digits`),maximumFractionDigits:y().optional().describe(`Maximum number of fraction digits`),useGrouping:b().optional().describe(`Whether to use grouping separators (e.g., 1,000)`)}).describe(`Number formatting rules`)),FV=Y(()=>T({dateStyle:A([`full`,`long`,`medium`,`short`]).optional().describe(`Date display style`),timeStyle:A([`full`,`long`,`medium`,`short`]).optional().describe(`Time display style`),timeZone:v().optional().describe(`IANA time zone (e.g., "America/New_York")`),hour12:b().optional().describe(`Use 12-hour format`)}).describe(`Date/time formatting rules`));Y(()=>T({code:v().describe(`BCP 47 language code (e.g., "en-US", "zh-CN")`),fallbackChain:w(v()).optional().describe(`Fallback language codes in priority order (e.g., ["zh-TW", "en"])`),direction:A([`ltr`,`rtl`]).default(`ltr`).describe(`Text direction: left-to-right or right-to-left`),numberFormat:PV.optional().describe(`Default number formatting rules`),dateFormat:FV.optional().describe(`Default date/time formatting rules`)}).describe(`Locale configuration`));var IV=Y(()=>T({enabled:b().default(!1).describe(`Enable public sharing`),publicLink:v().optional().describe(`Generated public share URL`),password:v().optional().describe(`Password required to access shared link`),allowedDomains:w(v()).optional().describe(`Restrict access to specific email domains (e.g. ["example.com"])`),expiresAt:v().optional().describe(`Expiration date/time in ISO 8601 format`),allowAnonymous:b().optional().default(!1).describe(`Allow access without authentication`)}));Y(()=>T({enabled:b().default(!1).describe(`Enable iframe embedding`),allowedOrigins:w(v()).optional().describe(`Allowed iframe parent origins (e.g. ["https://example.com"])`),width:v().optional().default(`100%`).describe(`Embed width (CSS value)`),height:v().optional().default(`600px`).describe(`Embed height (CSS value)`),showHeader:b().optional().default(!0).describe(`Show interface header in embed`),showNavigation:b().optional().default(!1).describe(`Show navigation in embed`),responsive:b().optional().default(!0).describe(`Enable responsive resizing`)}));var LV=A([`xs`,`sm`,`md`,`lg`,`xl`,`2xl`]),RV=Y(()=>T({xs:y().min(1).max(12).optional(),sm:y().min(1).max(12).optional(),md:y().min(1).max(12).optional(),lg:y().min(1).max(12).optional(),xl:y().min(1).max(12).optional(),"2xl":y().min(1).max(12).optional()}).describe(`Grid columns per breakpoint (1-12)`)),zV=Y(()=>T({xs:y().optional(),sm:y().optional(),md:y().optional(),lg:y().optional(),xl:y().optional(),"2xl":y().optional()}).describe(`Display order per breakpoint`)),BV=Y(()=>T({breakpoint:LV.optional().describe(`Minimum breakpoint for visibility`),hiddenOn:w(LV).optional().describe(`Hide on these breakpoints`),columns:RV.optional().describe(`Grid columns per breakpoint`),order:zV.optional().describe(`Display order per breakpoint`)}).describe(`Responsive layout configuration`)),VV=Y(()=>k(v(),E([v(),y()])).describe(`CSS property → value map (camelCase keys; design tokens encouraged)`));Y(()=>T({large:VV.optional().describe(`Unconditional base (desktop-first)`),medium:VV.optional().describe(`Applied at ≤ medium breakpoint`),small:VV.optional().describe(`Applied at ≤ small breakpoint`),xsmall:VV.optional().describe(`Applied at ≤ xsmall breakpoint`)}).describe(`Per-breakpoint scoped style maps (ADR-0065)`));var HV=Y(()=>T({lazyLoad:b().optional().describe(`Enable lazy loading (defer rendering until visible)`),virtualScroll:T({enabled:b().default(!1).describe(`Enable virtual scrolling`),itemHeight:y().optional().describe(`Fixed item height in pixels (for estimation)`),overscan:y().optional().describe(`Number of extra items to render outside viewport`)}).optional().describe(`Virtual scrolling configuration`),cacheStrategy:A([`none`,`cache-first`,`network-first`,`stale-while-revalidate`]).optional().describe(`Client-side data caching strategy`),prefetch:b().optional().describe(`Prefetch data before component is visible`),pageSize:y().optional().describe(`Number of items per page for pagination`),debounceMs:y().optional().describe(`Debounce interval for user interactions in milliseconds`)}).describe(`Performance optimization configuration`)),UV=A(`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(`.`)),WV=Y(()=>T({label:v().describe(`Display label (human-readable, any case allowed)`),value:mV.describe(`Stored value (lowercase machine identifier)`),color:v().optional().describe(`Color code for badges/charts`),default:b().optional().describe(`Is default option`)}));Y(()=>T({latitude:y().min(-90).max(90).describe(`Latitude coordinate`),longitude:y().min(-180).max(180).describe(`Longitude coordinate`),altitude:y().optional().describe(`Altitude in meters`),accuracy:y().optional().describe(`Accuracy in meters`)}));var GV=Y(()=>T({precision:y().int().min(0).max(10).default(2).describe(`Decimal precision (default: 2)`),currencyMode:A([`dynamic`,`fixed`]).default(`dynamic`).describe(`Currency mode: dynamic (user selectable) or fixed (single currency)`),defaultCurrency:v().length(3).default(`CNY`).describe(`Default or fixed currency code (ISO 4217, e.g., USD, CNY, EUR)`)}));Y(()=>T({value:y().describe(`Monetary amount`),currency:v().length(3).describe(`Currency code (ISO 4217)`)})),Y(()=>T({street:v().optional().describe(`Street address`),city:v().optional().describe(`City name`),state:v().optional().describe(`State/Province`),postalCode:v().optional().describe(`Postal/ZIP code`),country:v().optional().describe(`Country name or code`),countryCode:v().optional().describe(`ISO country code (e.g., US, GB)`),formatted:v().optional().describe(`Formatted address string`)}));var KV=Y(()=>T({dimensions:y().int().min(1).max(1e4).describe(`Vector dimensionality (e.g., 1536 for OpenAI embeddings)`),distanceMetric:A([`cosine`,`euclidean`,`dotProduct`,`manhattan`]).default(`cosine`).describe(`Distance/similarity metric for vector search`),normalized:b().default(!1).describe(`Whether vectors are normalized (unit length)`),indexed:b().default(!0).describe(`Whether to create a vector index for fast similarity search`),indexType:A([`hnsw`,`ivfflat`,`flat`]).optional().describe(`Vector index algorithm (HNSW for high accuracy, IVFFlat for large datasets)`)})),qV=Y(()=>T({minSize:y().min(0).optional().describe(`Minimum file size in bytes`),maxSize:y().min(1).optional().describe(`Maximum file size in bytes (e.g., 10485760 = 10MB)`),allowedTypes:w(v()).optional().describe(`Allowed file extensions (e.g., [".pdf", ".docx", ".jpg"])`),blockedTypes:w(v()).optional().describe(`Blocked file extensions (e.g., [".exe", ".bat", ".sh"])`),allowedMimeTypes:w(v()).optional().describe(`Allowed MIME types (e.g., ["image/jpeg", "application/pdf"])`),blockedMimeTypes:w(v()).optional().describe(`Blocked MIME types`),virusScan:b().default(!1).describe(`Enable virus scanning for uploaded files`),virusScanProvider:A([`clamav`,`virustotal`,`metadefender`,`custom`]).optional().describe(`Virus scanning service provider`),virusScanOnUpload:b().default(!0).describe(`Scan files immediately on upload`),quarantineOnThreat:b().default(!0).describe(`Quarantine files if threat detected`),storageProvider:v().optional().describe(`Object storage provider name (references ObjectStorageConfig)`),storageBucket:v().optional().describe(`Target bucket name`),storagePrefix:v().optional().describe(`Storage path prefix (e.g., "uploads/documents/")`),imageValidation:T({minWidth:y().min(1).optional().describe(`Minimum image width in pixels`),maxWidth:y().min(1).optional().describe(`Maximum image width in pixels`),minHeight:y().min(1).optional().describe(`Minimum image height in pixels`),maxHeight:y().min(1).optional().describe(`Maximum image height in pixels`),aspectRatio:v().optional().describe(`Required aspect ratio (e.g., "16:9", "1:1")`),generateThumbnails:b().default(!1).describe(`Auto-generate thumbnails`),thumbnailSizes:w(T({name:v().describe(`Thumbnail variant name (e.g., "small", "medium", "large")`),width:y().min(1).describe(`Thumbnail width in pixels`),height:y().min(1).describe(`Thumbnail height in pixels`),crop:b().default(!1).describe(`Crop to exact dimensions`)})).optional().describe(`Thumbnail size configurations`),preserveMetadata:b().default(!1).describe(`Preserve EXIF metadata`),autoRotate:b().default(!0).describe(`Auto-rotate based on EXIF orientation`)}).optional().describe(`Image-specific validation rules`),allowMultiple:b().default(!1).describe(`Allow multiple file uploads (overrides field.multiple)`),allowReplace:b().default(!0).describe(`Allow replacing existing files`),allowDelete:b().default(!0).describe(`Allow deleting uploaded files`),requireUpload:b().default(!1).describe(`Require at least one file when field is required`),extractMetadata:b().default(!0).describe(`Extract file metadata (name, size, type, etc.)`),extractText:b().default(!1).describe(`Extract text content from documents (OCR/parsing)`),versioningEnabled:b().default(!1).describe(`Keep previous versions of replaced files`),maxVersions:y().min(1).optional().describe(`Maximum number of versions to retain`),publicRead:b().default(!1).describe(`Allow public read access to uploaded files`),presignedUrlExpiry:y().min(60).max(604800).default(3600).describe(`Presigned URL expiration in seconds (default: 1 hour)`)}).refine(e=>!(e.minSize!==void 0&&e.maxSize!==void 0&&e.minSize>e.maxSize),{message:`minSize must be less than or equal to maxSize`}).refine(e=>!(e.virusScanProvider!==void 0&&e.virusScan!==!0),{message:`virusScanProvider requires virusScan to be enabled`}));Y(()=>T({uniqueness:b().default(!1).describe(`Enforce unique values across all records`),completeness:y().min(0).max(1).default(0).describe(`Minimum ratio of non-null values (0-1, default: 0 = no requirement)`),accuracy:T({source:v().describe(`Reference data source for validation (e.g., "api.verify.com", "master_data")`),threshold:y().min(0).max(1).describe(`Minimum accuracy threshold (0-1, e.g., 0.95 = 95% match required)`)}).optional().describe(`Accuracy validation configuration`)})),Y(()=>T({enabled:b().describe(`Enable caching for computed field results`),ttl:y().min(0).describe(`Cache TTL in seconds (0 = no expiration)`),invalidateOn:w(v()).describe(`Field paths that invalidate cache (e.g., ["inventory.quantity", "pricing.base_price"])`)})),Y(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Machine name (snake_case)`).optional(),label:v().optional().describe(`Human readable label`),type:UV.describe(`Field Data Type`),description:v().optional().describe(`Tooltip/Help text`),format:v().optional().describe(`Format string (e.g. email, phone)`),columnName:v().optional().describe(`Physical column name in the target datasource. Defaults to the field key when not set.`),required:b().default(!1).describe(`Is required`),searchable:b().default(!1).describe(`Is searchable`),multiple:b().default(!1).describe(`Allow multiple values (Stores as Array/JSON). Applicable for select, lookup, file, image.`),unique:b().default(!1).describe(`Is unique constraint`),defaultValue:S().optional().describe(`Default value`),maxLength:y().optional().describe(`Max character length`),minLength:y().optional().describe(`Min character length`),precision:y().optional().describe(`Total digits`),scale:y().optional().describe(`Decimal places`),min:y().optional().describe(`Minimum value`),max:y().optional().describe(`Maximum value`),options:w(WV).optional().describe(`Static options for select/multiselect`),reference:v().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.`),referenceFilters:w(v()).optional().describe(`Filters applied to lookup dialogs (e.g. "active = true")`),deleteBehavior:A([`set_null`,`cascade`,`restrict`]).optional().default(`set_null`).describe(`What happens if referenced record is deleted`),inlineEdit:E([b(),A([`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:v().optional().describe(`Title for the inline master-detail grid`),inlineColumns:w(x()).optional().describe(`Explicit columns for the inline grid (derived from the child object when omitted)`),inlineAmountField:v().optional().describe(`Numeric child field summed for the inline grid total`),relatedList:b().optional().describe(`Show this child collection as a related list on the parent's detail page (read-side mirror of inlineEdit). Defaults to shown for master_detail/lookup; set false to suppress.`),relatedListTitle:v().optional().describe(`Title for the detail-page related list`),relatedListColumns:w(x()).optional().describe(`Explicit columns for the detail-page related list (derived from the child object when omitted)`),displayField:v().optional().describe(`Field shown as each candidate's label in the picker/popover (defaults to the referenced object's name/title).`),descriptionField:v().optional().describe(`Secondary field shown under the label in the quick-select popover.`),lookupColumns:w(E([v(),T({field:v(),label:v().optional(),width:v().optional(),type:v().optional()})])).optional().describe(`Explicit columns for the record-picker table; auto-derived from the referenced object when omitted.`),lookupPageSize:y().int().positive().optional().describe(`Rows per page in the record-picker dialog (default 10).`),lookupFilters:w(T({field:v(),operator:A([`eq`,`ne`,`gt`,`lt`,`gte`,`lte`,`contains`,`in`,`notIn`]),value:x()})).optional().describe(`Base filters restricting which records are selectable (e.g. only active). Structured, picker-honoured form of referenceFilters.`),dependsOn:w(E([v(),T({field:v(),param:v().optional()})])).optional().describe(`Dependent lookup: restrict candidates by the value of other field(s) on the same record. String = same local/remote key; {field,param} when the remote filter key differs.`),allowCreate:b().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:jV.optional().describe("Formula expression (CEL). e.g. F`record.amount * 0.1`"),returnType:A([`number`,`text`,`boolean`,`date`]).optional().describe(`Inferred value type of a formula field (number/text/boolean/date)`),summaryOperations:T({object:v().describe(`Source child object name for roll-up`),field:v().describe(`Field on child object to aggregate (ignored for count)`),function:A([`count`,`sum`,`min`,`max`,`avg`]).describe(`Aggregation function to apply`),relationshipField:v().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.`)}).optional().describe(`Roll-up summary definition. The engine recomputes the value when child records are inserted/updated/deleted.`),language:v().optional().describe(`Programming language for syntax highlighting (e.g., javascript, python, sql)`),maxRating:y().optional().describe(`Maximum rating value (default: 5)`),step:y().optional().describe(`Step increment for slider (default: 1)`),currencyConfig:GV.optional().describe(`Configuration for currency field type`),dimensions:y().int().min(1).max(1e4).optional().describe(`Vector dimensionality (e.g., 1536 for OpenAI embeddings)`),vectorConfig:KV.optional().describe(`Configuration for vector field type (AI/ML embeddings)`),fileAttachmentConfig:qV.optional().describe(`Configuration for file and attachment field types`),trackHistory:b().optional().describe(`Render this field's value changes as human-readable entries on the record activity timeline (ADR-0052 §5b). Opt-in per field.`),dependencies:w(v()).optional().describe(`Array of field names that this field depends on (for formulas, visibility rules, etc.)`),group:v().optional().describe(`Field group name for organizing fields in forms and layouts (e.g., "contact_info", "billing", "system")`),visibleWhen:jV.optional().describe("Predicate (CEL) — field is shown only when TRUE (else hidden). e.g. P`record.type == 'invoice'`"),readonlyWhen:jV.optional().describe("Predicate (CEL) — field is read-only when TRUE. e.g. P`record.status == 'paid'`"),requiredWhen:jV.optional().describe("Predicate (CEL) — field is required when TRUE. Canonical name for `conditionalRequired`."),conditionalRequired:jV.optional().describe("Predicate (CEL) — field is required when TRUE. Alias of `requiredWhen`."),hidden:b().default(!1).describe(`Hidden from default UI`),readonly:b().default(!1).describe(`Read-only in UI`),requiredPermissions:w(v()).optional().describe(`[ADR-0066 D3] Capabilities required to read/edit this field (mask on read, deny on write; AND-gate).`),system:b().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:b().optional().default(!0).describe(`Whether field is sortable in list views`),inlineHelpText:v().optional().describe(`Help text displayed below the field in forms`),caseSensitive:b().optional().describe(`Whether text comparisons are case-sensitive`),autonumberFormat:v().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).`),index:b().default(!1).describe(`Create standard database index`),externalId:b().default(!1).describe(`Is external ID for upsert operations`)}));var JV=A([`GET`,`POST`,`PUT`,`DELETE`,`PATCH`,`HEAD`,`OPTIONS`]),YV=Y(()=>A([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`])),XV=Y(()=>T({url:v().describe(`API endpoint URL`),method:YV.optional().default(`GET`).describe(`HTTP method`),headers:k(v(),v()).optional().describe(`Custom HTTP headers`),params:k(v(),S()).optional().describe(`Query parameters`),body:S().optional().describe(`Request body for POST/PUT/PATCH`)}));Y(()=>T({enabled:b().default(!0).describe(`Enable CORS`),origins:E([v(),w(v())]).default(`*`).describe(`Allowed origins (* for all)`),methods:w(JV).optional().describe(`Allowed HTTP methods`),credentials:b().default(!1).describe(`Allow credentials (cookies, authorization headers)`),maxAge:y().int().optional().describe(`Preflight cache duration in seconds`)})),Y(()=>T({enabled:b().default(!1).describe(`Enable rate limiting`),windowMs:y().int().default(6e4).describe(`Time window in milliseconds`),maxRequests:y().int().default(100).describe(`Max requests per window`)})),Y(()=>T({path:v().describe(`URL path to serve from`),directory:v().describe(`Physical directory to serve`),cacheControl:v().optional().describe(`Cache-Control header value`)}));var ZV=Y(()=>D(`provider`,[T({provider:j(`object`),object:v().describe(`Target object name`)}),T({provider:j(`api`),read:XV.optional().describe(`Configuration for fetching data`),write:XV.optional().describe(`Configuration for submitting data (for forms/editable tables)`)}),T({provider:j(`value`),items:w(S()).describe(`Static data array`)}),T({provider:j(`schema`),schemaId:v().describe(`Schema identifier — typically the metadata type name`),schema:k(v(),S()).optional().describe(`Inline JSON Schema (Draft 2020-12). Optional when schemaId is resolvable.`)})])),QV=Y(()=>T({field:v().describe(`Field name to filter on`),operator:v().describe(`Filter operator (e.g. equals, not_equals, contains, this_quarter)`),value:E([v(),y(),b(),ul(),w(E([v(),y()]))]).optional().describe(`Filter value`)}).describe(`View filter rule`)),$V=Y(()=>A([`none`,`count`,`count_empty`,`count_filled`,`count_unique`,`percent_empty`,`percent_filled`,`sum`,`avg`,`min`,`max`]).describe(`Aggregation function for column footer summary`)),eH=Y(()=>T({field:v().describe(`Field name (snake_case)`),label:MV.optional().describe(`Display label override`),width:y().positive().optional().describe(`Column width in pixels`),align:A([`left`,`center`,`right`]).optional().describe(`Text alignment`),hidden:b().optional().describe(`Hide column by default`),sortable:b().optional().describe(`Allow sorting by this column`),resizable:b().optional().describe(`Allow resizing this column`),wrap:b().optional().describe(`Allow text wrapping`),type:v().optional().describe(`Renderer type override (e.g., "currency", "date")`),pinned:A([`left`,`right`]).optional().describe(`Pin/freeze column to left or right side`),summary:$V.optional().describe(`Footer aggregation function for this column`),link:b().optional().describe(`Functions as the primary navigation link (triggers View navigation)`),action:v().optional().describe(`Registered Action ID to execute when clicked`)})),tH=Y(()=>T({type:A([`none`,`single`,`multiple`]).default(`none`).describe(`Selection mode`)})),nH=Y(()=>T({pageSize:y().int().positive().default(25).describe(`Number of records per page`),pageSizeOptions:w(y().int().positive()).optional().describe(`Available page size options`)})),rH=Y(()=>A([`compact`,`short`,`medium`,`tall`,`extra_tall`]).describe(`Row height / density setting for list view`)),iH=Y(()=>T({field:v().describe(`Field name to group by`),order:A([`asc`,`desc`]).default(`asc`).describe(`Group sort order`),collapsed:b().default(!1).describe(`Collapse groups by default`)})),aH=Y(()=>T({fields:w(iH).min(1).describe(`Fields to group by (supports up to 3 levels)`)}).describe(`Record grouping configuration`)),oH=Y(()=>T({coverField:v().optional().describe(`Attachment/image field to display as card cover`),coverFit:A([`cover`,`contain`]).default(`cover`).describe(`Image fit mode for card cover`),cardSize:A([`small`,`medium`,`large`]).default(`medium`).describe(`Card size in gallery view`),titleField:v().optional().describe(`Field to display as card title`),visibleFields:w(v()).optional().describe(`Fields to display on card body`)}).describe(`Gallery/card view configuration`)),sH=Y(()=>T({startDateField:v().describe(`Field for timeline item start date`),endDateField:v().optional().describe(`Field for timeline item end date`),titleField:v().describe(`Field to display as timeline item title`),groupByField:v().optional().describe(`Field to group timeline rows`),colorField:v().optional().describe(`Field to determine item color`),scale:A([`hour`,`day`,`week`,`month`,`quarter`,`year`]).default(`week`).describe(`Default timeline scale`)}).describe(`Timeline view configuration`)),cH=Y(()=>T({type:A([`personal`,`collaborative`]).default(`collaborative`).describe(`View ownership type`),lockedBy:v().optional().describe(`User who locked the view configuration`)}).describe(`View sharing and access configuration`)),lH=Y(()=>T({field:v().describe(`Field to derive color from (typically a select/status field)`),colors:k(v(),v()).optional().describe(`Map of field value to color (hex/token)`)}).describe(`Row color configuration based on field values`)),uH=Y(()=>A([`grid`,`kanban`,`gallery`,`calendar`,`timeline`,`gantt`,`map`,`chart`,`tree`]).describe(`Visualization type that users can switch to`)),dH=Y(()=>T({sort:b().default(!0).describe(`Allow users to sort records`),search:b().default(!0).describe(`Allow users to search records`),filter:b().default(!0).describe(`Allow users to filter records`),rowHeight:b().default(!0).describe(`Allow users to toggle row height/density`),addRecordForm:b().default(!1).describe(`Add records through a form instead of inline`),buttons:w(v()).optional().describe(`Custom action button IDs to show in the toolbar`)}).describe(`User action toggles for the view toolbar`)),fH=Y(()=>T({showDescription:b().default(!0).describe(`Show the view description text`),allowedVisualizations:w(uH).optional().describe(`Whitelist of visualization types users can switch between (e.g. ["grid", "gallery", "kanban"])`)}).describe(`Appearance and visualization configuration`)),pH=Y(()=>T({name:hV.describe(`Tab identifier (snake_case)`),label:MV.optional().describe(`Display label`),icon:v().optional().describe(`Tab icon name`),view:v().optional().describe(`Referenced list view name from listViews`),filter:w(QV).optional().describe(`Tab-specific filter criteria`),order:y().int().min(0).optional().describe(`Tab display order`),pinned:b().default(!1).describe(`Pin tab (cannot be removed by users)`),isDefault:b().default(!1).describe(`Set as the default active tab`),visible:b().default(!0).describe(`Tab visibility`)}).describe(`Tab configuration for multi-tab view interface`)),mH=Y(()=>T({field:v().describe(`Field name on the source object (must exist — checked by reference diagnostics)`),label:MV.optional().describe(`Display label override (defaults to the field label)`),type:A([`select`,`multi-select`,`boolean`,`date-range`,`text`]).optional().describe(`Filter control type. Omit to infer from the field definition`),options:w(T({value:E([v(),y(),b()]).describe(`Option value`),label:MV.describe(`Option label`),color:v().optional().describe(`Option color token/hex`)})).optional().describe(`Static options. Omit to derive from the field definition (select options / lookup records)`),showCount:b().optional().describe(`Show per-option record counts`),defaultValues:w(E([v(),y(),b()])).optional().describe(`Pre-selected values when the view loads`)}).describe(`Quick-filter field configuration`)),hH=Y(()=>T({element:A([`dropdown`,`tabs`,`toggle`]).default(`dropdown`).describe(`Filter control style: "dropdown" (per-field value selectors) or "tabs" (named presets). "toggle" is deprecated.`),fields:w(mH).optional().describe(`Fields exposed as quick filters (dropdown/toggle elements)`),tabs:w(pH).optional().describe(`Named filter presets rendered as tabs (tabs element). Reuses ViewTabSchema`),showAllRecords:b().optional().describe(`Show an "All records" tab before the presets (tabs element)`)}).describe(`End-user quick-filter configuration (Airtable "User filters" parity)`)),gH=Y(()=>T({enabled:b().default(!0).describe(`Show the add record entry point`),position:A([`top`,`bottom`,`both`]).default(`bottom`).describe(`Position of the add record button`),mode:A([`inline`,`form`,`modal`]).default(`inline`).describe(`How to add a new record`),formView:v().optional().describe(`Named form view to use when mode is "form" or "modal"`)}).describe(`Add record entry point configuration`)),_H=Y(()=>T({groupByField:v().describe(`Field to group columns by (usually status/select)`),summarizeField:v().optional().describe(`Field to sum at top of column (e.g. amount)`),columns:w(v()).describe(`Fields to show on cards`)})),vH=Y(()=>T({chartType:A([`bar`,`line`,`pie`,`area`,`scatter`]).default(`bar`).describe(`Chart visualisation type`),dataset:hV.describe(`Dataset name to bind (ADR-0021)`),dimensions:w(v()).optional().describe(`Dimension names — X/group/split`),values:w(v()).min(1).describe(`Measure names — Y (at least one)`)}).describe(`List chart view configuration`)),yH=Y(()=>T({startDateField:v(),endDateField:v().optional(),titleField:v(),colorField:v().optional()})),bH=Y(()=>T({field:v().describe(`Record field / dot-path the dimension filters on`),label:v().optional().describe(`Trigger label (falls back to the field label)`),options:w(E([v(),T({value:E([v(),y()]),label:v().optional()})])).optional().describe(`Explicit option override for fixed enums`)})),xH=Y(()=>T({startDateField:v(),endDateField:v(),titleField:v(),progressField:v().optional(),dependenciesField:v().optional(),colorField:v().optional().describe(`Field that drives the bar color`),parentField:v().optional().describe(`Field holding the parent task id (builds the summary → step tree)`),typeField:v().optional().describe(`Field whose value maps to task/summary/milestone`),baselineStartField:v().optional().describe(`Baseline (planned) start field`),baselineEndField:v().optional().describe(`Baseline (planned) end field`),groupByField:v().optional().describe(`Field to group leaf tasks by (synthesized summary rows)`),resourceView:b().optional().describe(`Render a per-resource workload histogram instead of the timeline`),assigneeField:v().optional().describe(`Resource field to bucket load by (resource view)`),effortField:v().optional().describe(`Per-task load units (resource view; default 1)`),capacity:y().optional().describe(`Per-resource capacity ceiling; loads above this flag overload`),tooltipFields:w(E([v(),T({field:v(),label:v().optional()})])).optional().describe(`Fields to surface in the hover tooltip, in display order`),quickFilters:w(bH).optional().describe(`Multi-select filter dropdowns rendered above the chart`),autoZoomToFilter:b().optional().describe(`When true (default), filtering zooms the range to the filtered tasks`)}).passthrough()),SH=Y(()=>T({parentField:v().optional().describe(`Single-parent pointer field (auto-detected from the object schema when omitted)`),labelField:v().optional().describe(`Field rendered indented in the first column (defaults to "name")`),fields:w(v()).optional().describe(`Additional fields rendered as flat columns alongside the label`),defaultExpandedDepth:y().int().min(0).optional().describe(`Initial expansion depth (0 = roots only; omit = expand all)`)}).passthrough()),CH=Y(()=>A([`page`,`drawer`,`modal`,`split`,`popover`,`new_window`,`none`])),wH=Y(()=>T({mode:CH.default(`page`),view:v().optional().describe(`Name of the form view to use for details (e.g. "summary_view", "edit_form")`),preventNavigation:b().default(!1).describe(`Disable standard navigation entirely`),openNewTab:b().default(!1).describe(`Force open in new tab (applies to page mode)`),width:E([v(),y()]).optional().describe(`Width of the drawer/modal (e.g. "600px", "50%")`)})),TH=Y(()=>T({name:hV.optional().describe(`Internal view name (lowercase snake_case)`),label:MV.optional(),type:A([`grid`,`kanban`,`gallery`,`calendar`,`timeline`,`gantt`,`map`,`chart`,`tree`]).default(`grid`),data:ZV.optional().describe(`Data source configuration (defaults to "object" provider)`),columns:E([w(v()),w(eH)]).describe(`Fields to display as columns`),filter:w(QV).optional().describe(`Filter criteria (JSON Rules)`),sort:E([v(),w(T({field:v(),order:A([`asc`,`desc`])}))]).optional(),searchableFields:w(v()).optional().describe(`Fields enabled for search`),filterableFields:w(v()).optional().describe(`Legacy shorthand for userFilters.fields — bare field names enabled for end-user filtering. Prefer userFilters`),userFilters:hH.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:b().optional().describe(`Enable column resizing`),striped:b().optional().describe(`Striped row styling`),bordered:b().optional().describe(`Show borders`),compactToolbar:b().optional().describe(`Collapse Group/Color/Density/Hide-fields into a single View settings popover`),selection:tH.optional().describe(`Row selection configuration`),navigation:wH.optional().describe(`Configuration for item click navigation (page, drawer, modal, etc.)`),pagination:nH.optional().describe(`Pagination configuration`),kanban:_H.optional(),calendar:yH.optional(),gantt:xH.optional(),gallery:oH.optional(),timeline:sH.optional(),chart:vH.optional(),tree:SH.optional(),description:MV.optional().describe(`View description for documentation/tooltips`),sharing:cH.optional().describe(`View sharing and access configuration`),rowHeight:rH.optional().describe(`Row height / density setting`),grouping:aH.optional().describe(`Group records by one or more fields`),rowColor:lH.optional().describe(`Color rows based on field value`),hiddenFields:w(v()).optional().describe(`Fields to hide in this specific view`),fieldOrder:w(v()).optional().describe(`Explicit field display order for this view`),rowActions:w(v()).optional().describe(`Actions available for individual row items`),bulkActions:w(v()).optional().describe(`Actions available when multiple rows are selected`),bulkActionDefs:w(k(v(),x())).optional().describe(`Rich bulk action definitions (schema-driven, executed via BulkActionDialog)`),virtualScroll:b().optional().describe(`Enable virtual scrolling for large datasets`),conditionalFormatting:w(T({condition:jV.describe(`Predicate (CEL) to evaluate.`),style:k(v(),v()).describe(`CSS styles to apply when condition is true`)})).optional().describe(`Conditional formatting rules for list rows`),inlineEdit:b().optional().describe(`Allow inline editing of records directly in the list view`),exportOptions:w(A([`csv`,`xlsx`,`pdf`,`json`])).optional().describe(`Available export format options`),userActions:dH.optional().describe(`User action toggles for the view toolbar`),appearance:fH.optional().describe(`Appearance and visualization configuration`),tabs:w(pH).optional().describe(`Tab definitions for multi-tab view interface`),addRecord:gH.optional().describe(`Add record entry point configuration`),showRecordCount:b().optional().describe(`Show record count at the bottom of the list`),allowPrinting:b().optional().describe(`Allow users to print the view`),emptyState:T({title:MV.optional(),message:MV.optional(),icon:v().optional()}).optional().describe(`Empty state configuration when no records found`),aria:NV.optional().describe(`ARIA accessibility attributes for the list view`),responsive:BV.optional().describe(`Responsive layout configuration`),performance:HV.optional().describe(`Performance optimization settings`)})),EH=Y(()=>T({field:v().describe(`Field name (snake_case)`),type:UV.optional().describe(`Field type (auto-infers widget if omitted)`),options:w(WV).optional().describe(`Options for select/multiselect/radio/checkboxes fields`),reference:v().optional().describe(`Target object name for lookup/master_detail fields`),maxLength:y().optional().describe(`Maximum character length (for text/textarea/email/url/phone)`),minLength:y().optional().describe(`Minimum character length`),min:y().optional().describe(`Minimum value (for number/currency/percent/slider)`),max:y().optional().describe(`Maximum value`),precision:y().optional().describe(`Total digits (for number/currency)`),scale:y().optional().describe(`Decimal places`),multiple:b().optional().describe(`Allow multiple values (for select/lookup/file/image)`),label:MV.optional().describe(`Display label override`),placeholder:MV.optional().describe(`Placeholder text`),helpText:MV.optional().describe(`Help/hint text`),readonly:b().optional().describe(`Read-only override`),immutable:b().optional().describe(`Editable on create, locked once the record exists (e.g. machine names).`),required:b().optional().describe(`Required override`),hidden:b().optional().describe(`Hidden override`),colSpan:y().int().min(1).max(4).optional().describe(`Column span in grid layout (1-4)`),widget:v().optional().describe(`Custom widget/component name (overrides type-based inference)`),language:v().optional().describe(`Code editor language (for type=code)`),fields:w(M(()=>EH)).optional().describe(`Sub-fields for composite/repeater/record types`),keyField:T({field:v().default(`name`).describe(`Property name that holds the key inside each item (defaults to "name")`),label:MV.optional().describe(`Display label for the key column`),placeholder:MV.optional().describe(`Placeholder when entering a new key`),helpText:MV.optional().describe(`Help text under the key input`),regex:v().optional().describe(`JS regex source string the key must match (no flags)`),immutable:b().default(!0).describe(`If true, the key is read-only after creation`)}).optional().describe(`Key column config for record-typed fields`),dependsOn:v().optional().describe(`Parent field name for cascading`),visibleOn:jV.optional().describe(`Visibility predicate (CEL).`),disclosure:A([`inline`,`popover`]).optional().describe(`Composite rendering: inline bordered box (default) or a summary line + gear popover (progressive disclosure).`)})),DH=Y(()=>T({name:v().optional().describe(`Stable section identifier for i18n lookup (snake_case)`),label:MV.optional(),description:v().optional().describe(`Optional description rendered under the section header.`),collapsible:b().default(!1),collapsed:b().default(!1),visibleOn:jV.optional().describe(`Visibility predicate (CEL). Hides the whole section when false.`),columns:E([A([`1`,`2`,`3`,`4`]),j(1),j(2),j(3),j(4)]).default(1).transform(e=>typeof e==`string`?parseInt(e):e),fields:w(E([v(),EH]))})),OH=Y(()=>T({type:A([`simple`,`tabbed`,`wizard`,`split`,`drawer`,`modal`]).default(`simple`),data:ZV.optional().describe(`Data source configuration (defaults to "object" provider)`),sections:w(DH).optional(),groups:w(DH).optional(),subforms:w(T({childObject:v().describe(`Child object whose records are entered inline`),relationshipField:v().optional().describe(`FK on the child pointing back to the parent (auto-detected when omitted)`),columns:w(x()).optional().describe(`Editable grid columns (derived from the child object when omitted)`),amountField:v().optional().describe(`Numeric child column summed for the running total`),totalField:v().optional().describe(`Parent field to receive the rolled-up sum`),title:v().optional().describe(`Section title`),addLabel:v().optional().describe(`Add-row button label`),minRows:y().optional(),maxRows:y().optional()})).optional().describe(`Inline master-detail child collections`),defaultSort:w(T({field:v().describe(`Field name to sort by`),order:A([`asc`,`desc`]).default(`desc`).describe(`Sort direction`)})).optional().describe(`Default sort order for related list views within this form`),sharing:IV.optional().describe(`Public sharing configuration for this form`),submitBehavior:E([T({kind:j(`thank-you`),title:v().optional(),message:v().optional()}),T({kind:j(`redirect`),url:v(),delayMs:y().int().min(0).optional()}),T({kind:j(`continue`)}),T({kind:j(`next-record`)})]).optional().describe(`Post-submit behavior`),aria:NV.optional().describe(`ARIA accessibility attributes for the form view`)}));Y(()=>T({list:TH.optional(),form:OH.optional(),listViews:k(v(),TH).optional().describe(`Additional named list views`),formViews:k(v(),OH).optional().describe(`Additional named form views`),protection:DV.optional().describe(`Package author protection block — lock policy for this view.`),...EV}));var kH=v().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>`."),AH=A([`package`,`shared`,`personal`]).describe(`View identity layer: package | shared | personal.`);A([`list`,`form`]).describe("Whether `config` is a ListView (list family) or a FormView.");function jH(){return{name:kH,object:v().describe(`Bound object name — the foreign key used to aggregate views.`),label:MV.optional().describe(`Display label (supports i18n).`),isDefault:b().optional().describe(`Whether this is the object's default view in the switcher.`),order:y().int().optional().describe(`Sort order within the object's view switcher / left rail.`),scope:AH.optional().describe("Identity layer (defaults to `package` for source-loaded views)."),owner:v().optional().describe("Owner user id — set when `scope` is `personal`."),hidden:b().optional().describe(`Hidden from the switcher (per-user / per-org declutter).`),protection:DV.optional().describe(`Package author protection block — lock policy for this view.`),...EV}}Y(()=>D(`viewKind`,[T({viewKind:j(`list`),config:TH.describe(`List-family view configuration.`),...jH()}),T({viewKind:j(`form`),config:OH.describe(`Form view configuration.`),...jH()})]));function MH(e){let{schemaId:t,...n}=e;return OH.parse({...n,data:{provider:`schema`,schemaId:t}})}MH({schemaId:`permission`,type:`simple`,sections:[{label:`Identity`,description:`Permission Sets stack on top of a Profile to grant additional access. Profiles are the base set assigned 1:1 to each user.`,columns:2,fields:[{field:`name`,required:!0,colSpan:1,helpText:`Machine name (snake_case)`},{field:`label`,colSpan:1,helpText:`Display label for admins`},{field:`isProfile`,type:`toggle`,colSpan:2,helpText:`Profile = base set assigned to users. Permission Set = additive grant.`}]},{label:`System Permissions`,description:`High-level capabilities not tied to a specific object — e.g. manage_users, view_audit_logs.`,columns:1,fields:[{field:`systemPermissions`,type:`tags`,helpText:`List of system capability keys`}]},{label:`Object & Field Permissions`,description:`Per-object CRUD + per-field FLS. Edit via the matrix editor or paste JSON here.`,columns:1,fields:[{field:`objects`,widget:`json`,helpText:`{ "account": { allowRead: true, allowEdit: true, ... } }`},{field:`fields`,widget:`json`,helpText:`{ "account.amount": { readable: true, editable: false } }`}]},{label:`Tab & Row-Level Security`,description:`Tab visibility, RLS policies, and custom context variables for predicate evaluation.`,columns:1,fields:[{field:`tabPermissions`,widget:`json`,helpText:`{ "app_crm": "visible", "app_admin": "hidden" }`},{field:`rowLevelSecurity`,widget:`json`,helpText:`Array of RLS policies (see rls.zod.ts)`},{field:`contextVariables`,widget:`json`,helpText:`Custom variables referenced in RLS predicates`}]}]}),A([`private`,`public_read`,`public_read_write`,`controlled_by_parent`]),A([`owner`,`criteria`]);var NH=A([`read`,`edit`,`full`]),PH=A([`user`,`group`,`role`,`role_and_subordinates`,`guest`]),FH=T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Unique rule name (snake_case)`),label:v().optional().describe(`Human-readable label`),description:v().optional().describe(`Administrative notes`),object:v().describe(`Target Object Name`),active:b().default(!0),accessLevel:NH.default(`read`),sharedWith:T({type:PH,value:v().describe(`ID or Code of the User/Group/Role`)}).describe(`The recipient of the shared access`)}),IH=Y(()=>FH.extend({type:j(`criteria`),condition:jV.describe('Predicate (CEL). e.g. P`record.department == "Sales"`')})),LH=Y(()=>FH.extend({type:j(`owner`),ownedBy:T({type:PH,value:v()}).describe(`Source group/role whose records are being shared`)}));Y(()=>D(`type`,[IH,LH]));var RH=A([`geography`,`industry`,`named_account`,`product_line`]);Y(()=>T({name:v().describe(`Model Name (e.g. FY24 Planning)`),state:A([`planning`,`active`,`archived`]).default(`planning`),startDate:v().optional(),endDate:v().optional()})),Y(()=>T({name:hV.describe(`Territory unique name (lowercase snake_case)`),label:v().describe(`Territory Label (e.g. "West Coast")`),modelId:v().describe(`Belongs to which Territory Model`),parent:v().optional().describe(`Parent Territory`),type:RH.default(`geography`),assignmentRule:v().optional().describe(`Criteria based assignment rule`),assignedUsers:w(v()).optional(),accountAccess:A([`read`,`edit`]).default(`read`),opportunityAccess:A([`read`,`edit`]).default(`read`),caseAccess:A([`read`,`edit`]).default(`read`)}));var zH=Y(()=>T({minLength:y().default(8).describe(`[EXPERIMENTAL — not enforced] Minimum password length`),requireUppercase:b().default(!0).describe(`[EXPERIMENTAL — not enforced] Require an uppercase letter`),requireLowercase:b().default(!0).describe(`[EXPERIMENTAL — not enforced] Require a lowercase letter`),requireNumbers:b().default(!0).describe(`[EXPERIMENTAL — not enforced] Require a number`),requireSymbols:b().default(!1).describe(`[EXPERIMENTAL — not enforced] Require a symbol`),expirationDays:y().optional().describe(`[EXPERIMENTAL — not enforced] Force password change every X days`),historyCount:y().default(3).describe(`[EXPERIMENTAL — not enforced] Prevent reusing last X passwords`)})),BH=Y(()=>T({trustedRanges:w(v()).describe(`[EXPERIMENTAL — not enforced] CIDR ranges allowed to access (e.g. 10.0.0.0/8)`),blockUnknown:b().default(!1).describe(`[EXPERIMENTAL — not enforced] Block all IPs not in trusted ranges`),vpnRequired:b().default(!1).describe(`[EXPERIMENTAL — not enforced] Require VPN to access`)})),VH=Y(()=>T({idleTimeout:y().default(30).describe(`[EXPERIMENTAL — not enforced] Minutes before idle session logout`),absoluteTimeout:y().default(480).describe(`[EXPERIMENTAL — not enforced] Max session duration (minutes)`),forceMfa:b().default(!1).describe(`[EXPERIMENTAL — not enforced] Require 2FA for all users`)})),HH=Y(()=>T({logRetentionDays:y().default(180).describe(`[EXPERIMENTAL — not enforced] Days to retain audit logs`),sensitiveFields:w(v()).describe(`[EXPERIMENTAL — not enforced] Fields to redact in logs (e.g. password, ssn)`),captureRead:b().default(!1).describe(`[EXPERIMENTAL — not enforced] Log read access (High volume!)`)})),UH=Y(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`[EXPERIMENTAL — not enforced] Policy Name`),password:zH.optional(),network:BH.optional(),session:VH.optional(),audit:HH.optional(),isDefault:b().default(!1).describe(`[EXPERIMENTAL — not enforced] Apply to all users by default`),assignedProfiles:w(v()).optional().describe(`[EXPERIMENTAL — not enforced] Apply to specific profiles`)})),WH=t({AccessControlConfigSchema:()=>SU,AddFieldOperation:()=>jK,AdvancedAuthConfigSchema:()=>JK,AnalyzerConfigSchema:()=>kU,AuditEventActorSchema:()=>WU,AuditEventChangeSchema:()=>KU,AuditEventSeverity:()=>UU,AuditEventTargetSchema:()=>GU,AuditEventType:()=>HU,AuditFindingSchema:()=>V$,AuditFindingSeveritySchema:()=>z$,AuditFindingStatusSchema:()=>B$,AuditLogConfigSchema:()=>R$,AuditRetentionPolicySchema:()=>qU,AuditScheduleSchema:()=>H$,AuditStorageConfigSchema:()=>YU,AuthPluginConfigSchema:()=>VK,AuthProviderConfigSchema:()=>BK,AwarenessUserStateSchema:()=>s0,BackupConfigSchema:()=>oU,BackupRetentionSchema:()=>aU,BackupStrategySchema:()=>iU,BatchTaskSchema:()=>D1,BookAudienceSchema:()=>QK,BookGroupSchema:()=>ZK,BookIncludeSchema:()=>XK,BookNodeSchema:()=>YK,BucketConfigSchema:()=>TU,CRDTStateSchema:()=>t0,CacheAvalanchePreventionSchema:()=>nU,CacheConfigSchema:()=>eU,CacheConsistencySchema:()=>tU,CacheInvalidationSchema:()=>$H,CacheStrategySchema:()=>ZH,CacheTierSchema:()=>QH,CacheWarmupSchema:()=>rU,ChangeImpactSchema:()=>WW,ChangePrioritySchema:()=>HW,ChangeStatusSchema:()=>UW,ChangeTypeSchema:()=>VW,CollaborationMode:()=>c0,CollaborationSessionConfigSchema:()=>l0,CollaborativeCursorSchema:()=>a0,ComplianceAuditRequirementSchema:()=>IW,ComplianceEncryptionRequirementSchema:()=>LW,ComplianceFrameworkSchema:()=>FW,ConsoleDestinationConfigSchema:()=>tW,ConsumerConfigSchema:()=>pU,CoreServiceName:()=>v0,CoverageBreakdownEntrySchema:()=>W1,CreateObjectOperation:()=>PK,CronScheduleSchema:()=>h1,CursorColorPreset:()=>n0,CursorSelectionSchema:()=>i0,CursorStyleSchema:()=>r0,DataClassificationPolicySchema:()=>BW,DataClassificationSchema:()=>PW,DatabaseLevelIsolationStrategySchema:()=>T0,DatabaseProviderSchema:()=>b0,DeadLetterQueueSchema:()=>mU,DeleteObjectOperation:()=>IK,DeployManifestSchema:()=>I0,DeployValidationIssueSchema:()=>F0,ENVIRONMENT_ARTIFACT_SCHEMA_VERSION:()=>`0.1`,EmailAddressConfigSchema:()=>eq,EmailAndPasswordConfigSchema:()=>KK,EmailProviderSchema:()=>$K,EmailTemplateDefinitionCategorySchema:()=>tq,EmailTemplateDefinitionVariableSchema:()=>nq,EmailTemplateSchema:()=>k1,EmailVerificationConfigSchema:()=>qK,EncryptionAlgorithmSchema:()=>U$,EncryptionConfigSchema:()=>K$,EnvironmentArtifactChecksumSchema:()=>R0,EnvironmentArtifactFunctionLanguageEnum:()=>z0,EnvironmentArtifactFunctionSchema:()=>B0,EnvironmentArtifactHashAlgorithmEnum:()=>L0,EnvironmentArtifactManifestSchema:()=>H0,EnvironmentArtifactMetadataSchema:()=>U0,EnvironmentArtifactPayloadRefSchema:()=>W0,EnvironmentArtifactRequirementSchema:()=>V0,ExecuteSqlOperation:()=>LK,ExtendedLogLevel:()=>$U,ExternalServiceDestinationConfigSchema:()=>iW,FacetConfigSchema:()=>jU,FailoverConfigSchema:()=>cU,FailoverModeSchema:()=>sU,FieldTranslationSchema:()=>F1,FileDestinationConfigSchema:()=>nW,GCounterSchema:()=>Y1,GDPRConfigSchema:()=>F$,HIPAAConfigSchema:()=>I$,HistogramBucketConfigSchema:()=>uW,HttpDestinationConfigSchema:()=>rW,HttpServerConfigSchema:()=>RU,InAppNotificationSchema:()=>M1,IncidentCategorySchema:()=>X$,IncidentNotificationMatrixSchema:()=>e1,IncidentNotificationRuleSchema:()=>$$,IncidentResponsePhaseSchema:()=>Q$,IncidentSeveritySchema:()=>Y$,IncidentStatusSchema:()=>Z$,IntervalScheduleSchema:()=>g1,JobExecutionStatus:()=>x1,JobSchema:()=>b1,KeyManagementProviderSchema:()=>W$,KeyRotationPolicySchema:()=>G$,LWWRegisterSchema:()=>J1,LicenseMetricType:()=>E0,LifecycleActionSchema:()=>bU,LifecyclePolicyConfigSchema:()=>wU,LifecyclePolicyRuleSchema:()=>CU,LocaleSchema:()=>P1,LogDestinationSchema:()=>aW,LogDestinationType:()=>eW,LogEnrichmentConfigSchema:()=>oW,LogFormat:()=>ZU,LogLevel:()=>XU,LoggerConfigSchema:()=>QU,MaskingRuleSchema:()=>J$,MaskingStrategySchema:()=>q$,MaskingVisibilityRuleSchema:()=>RW,MessageFormatSchema:()=>z1,MessageQueueProviderSchema:()=>dU,MetadataFallbackStrategySchema:()=>f0,MetadataFormatSchema:()=>h0,MetadataHistoryRecordSchema:()=>_0,MetadataScopeSchema:()=>p0,MetadataStateSchema:()=>m0,MetadataStatsSchema:()=>g0,MetricAggregationConfigSchema:()=>mW,MetricAggregationType:()=>lW,MetricDefinitionSchema:()=>fW,MetricExportConfigSchema:()=>_W,MetricLabelsSchema:()=>dW,MetricType:()=>sW,MetricUnit:()=>cW,MiddlewareConfigSchema:()=>BU,MiddlewareType:()=>zU,MigrationDependencySchema:()=>zK,MigrationOperationSchema:()=>RK,MigrationStatementSchema:()=>P0,ModifyFieldOperation:()=>MK,MultipartUploadConfigSchema:()=>xU,MutualTLSConfigSchema:()=>HK,NotificationChannelSchema:()=>N1,ORSetElementSchema:()=>Z1,ORSetSchema:()=>Q1,OTComponentSchema:()=>G1,OTOperationSchema:()=>K1,ObjectStorageConfigSchema:()=>DU,ObjectTranslationDataSchema:()=>I1,ObjectTranslationNodeSchema:()=>V1,OidcProviderConfigSchema:()=>WK,OidcProvidersConfigSchema:()=>GK,OnceScheduleSchema:()=>_1,OpenTelemetryCompatibilitySchema:()=>NW,OtelExporterType:()=>MW,PCIDSSConfigSchema:()=>L$,PNCounterSchema:()=>X1,ProvisioningStepSchema:()=>M0,PushNotificationSchema:()=>j1,QueueConfigSchema:()=>E1,RPOSchema:()=>lU,RTOSchema:()=>uU,RegistrySyncPolicySchema:()=>D0,RegistryUpstreamSchema:()=>O0,RemoveFieldOperation:()=>NK,RenameObjectOperation:()=>FK,ResolvedSettingValueSchema:()=>m1,RetryPolicySchema:()=>y1,RollbackPlanSchema:()=>GW,RowLevelIsolationStrategySchema:()=>C0,SETTINGS_CHANGE_EVENT:()=>SETTINGS_CHANGE_EVENT,SMSTemplateSchema:()=>A1,SamplingDecision:()=>DW,SamplingStrategyType:()=>OW,ScheduleSchema:()=>v1,SchemaChangeSchema:()=>N0,SchemaLevelIsolationStrategySchema:()=>w0,SearchIndexConfigSchema:()=>AU,SearchProviderSchema:()=>OU,SecurityEventCorrelationSchema:()=>zW,ServerEventType:()=>VU,ServiceLevelIndicatorSchema:()=>hW,ServiceLevelObjectiveSchema:()=>gW,SettingsManifestSchema:()=>p1,SocialProviderConfigSchema:()=>UK,SpanAttributeValueSchema:()=>CW,SpanAttributesSchema:()=>wW,SpanEventSchema:()=>TW,SpanKind:()=>xW,SpanLinkSchema:()=>EW,SpanStatus:()=>SW,SpecifierHandlerSchema:()=>u1,SpecifierOptionSchema:()=>l1,SpecifierSchema:()=>f1,SpecifierScopeSchema:()=>d1,SpecifierType:()=>s1,StorageAclSchema:()=>vU,StorageClassSchema:()=>yU,StorageConnectionSchema:()=>EU,StorageProviderSchema:()=>_U,StorageScopeSchema:()=>gU,SupplierAssessmentStatusSchema:()=>n1,SupplierRiskLevelSchema:()=>t1,SupplierSecurityRequirementSchema:()=>r1,SuspiciousActivityRuleSchema:()=>JU,TRANSLATE_PLACEHOLDER:()=>TRANSLATE_PLACEHOLDER,TaskPriority:()=>S1,TaskRetryPolicySchema:()=>w1,TaskSchema:()=>T1,TaskStatus:()=>C1,TenantConnectionConfigSchema:()=>x0,TenantIsolationLevel:()=>y0,TenantPlanSchema:()=>A0,TenantProvisioningStatusEnum:()=>k0,TenantQuotaSchema:()=>S0,TenantRegionSchema:()=>j0,TextCRDTOperationSchema:()=>$1,TextCRDTStateSchema:()=>e0,TimeSeriesDataPointSchema:()=>pW,TopicConfigSchema:()=>fU,TraceContextPropagationSchema:()=>jW,TraceContextSchema:()=>bW,TraceFlagsSchema:()=>yW,TracePropagationFormat:()=>AW,TraceSamplingConfigSchema:()=>kW,TraceStateSchema:()=>vW,TrainingCategorySchema:()=>i1,TrainingCompletionStatusSchema:()=>a1,TrainingCourseSchema:()=>o1,TranslationDataSchema:()=>L1,TranslationDiffItemSchema:()=>U1,TranslationDiffStatusSchema:()=>H1,TranslationFileOrganizationSchema:()=>R1,UserActivityStatus:()=>o0,VectorClockSchema:()=>q1,WorkerConfigSchema:()=>O1,emailTemplateForm:()=>iq}),GH=A([`cel`,`js`,`cron`,`template`]),KH=T({rationale:v().optional(),generatedBy:v().optional()}),qH=T({dialect:GH,source:v().min(1).optional(),ast:S().optional(),meta:KH.optional()}).refine(e=>e.source!==void 0||e.ast!==void 0,{message:"Expression requires at least one of `source` or `ast`"}),JH=E([v().min(1).transform(e=>({dialect:`cel`,source:e})),qH]),YH=E([v().min(1).transform(e=>({dialect:`cron`,source:e})),qH]),XH=E([v().min(1).transform(e=>({dialect:`template`,source:e})),qH]);function X(e){if(typeof process<`u`&&{}.OS_EAGER_SCHEMAS===`1`)return e();let t,n=()=>(t===void 0&&(t=e()),t);return new Proxy(function(){},{get(e,t){let r=n(),i=r[t];return typeof i==`function`?i.bind(r):i},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())}})}var ZH=X(()=>A([`lru`,`lfu`,`fifo`,`ttl`,`adaptive`]).describe(`Cache eviction strategy`)),QH=X(()=>T({name:v().describe(`Unique cache tier name`),type:A([`memory`,`redis`,`memcached`,`cdn`]).describe(`Cache backend type`),maxSize:y().optional().describe(`Max size in MB`),ttl:y().default(300).describe(`Default TTL in seconds`),strategy:ZH.default(`lru`).describe(`Eviction strategy`),warmup:b().default(!1).describe(`Pre-populate cache on startup`)}).describe(`Configuration for a single cache tier in the hierarchy`)),$H=X(()=>T({trigger:A([`create`,`update`,`delete`,`manual`]).describe(`Event that triggers invalidation`),scope:A([`key`,`pattern`,`tag`,`all`]).describe(`Invalidation scope`),pattern:v().optional().describe(`Key pattern for pattern-based invalidation`),tags:w(v()).optional().describe(`Cache tags to invalidate`)}).describe(`Rule defining when and how cached entries are invalidated`)),eU=X(()=>T({enabled:b().default(!1).describe(`Enable application-level caching`),tiers:w(QH).describe(`Ordered cache tier hierarchy`),invalidation:w($H).describe(`Cache invalidation rules`),prefetch:b().default(!1).describe(`Enable cache prefetching`),compression:b().default(!1).describe(`Enable data compression in cache`),encryption:b().default(!1).describe(`Enable encryption for cached data`)}).describe(`Top-level application cache configuration`)),tU=X(()=>A([`write_through`,`write_behind`,`write_around`,`refresh_ahead`]).describe(`Distributed cache write consistency strategy`)),nU=X(()=>T({jitterTtl:T({enabled:b().default(!1).describe(`Add random jitter to TTL values`),maxJitterSeconds:y().default(60).describe(`Maximum jitter added to TTL in seconds`)}).optional().describe(`TTL jitter to prevent simultaneous expiration`),circuitBreaker:T({enabled:b().default(!1).describe(`Enable circuit breaker for backend protection`),failureThreshold:y().default(5).describe(`Failures before circuit opens`),resetTimeout:y().default(30).describe(`Seconds before half-open state`)}).optional().describe(`Circuit breaker for backend protection`),lockout:T({enabled:b().default(!1).describe(`Enable cache locking for key regeneration`),lockTimeoutMs:y().default(5e3).describe(`Maximum lock wait time in milliseconds`)}).optional().describe(`Lock-based stampede prevention`)}).describe(`Cache avalanche/stampede prevention configuration`)),rU=X(()=>T({enabled:b().default(!1).describe(`Enable cache warmup`),strategy:A([`eager`,`lazy`,`scheduled`]).default(`lazy`).describe(`Warmup strategy: eager (at startup), lazy (on first access), scheduled (cron)`),schedule:YH.optional().describe(`Cron expression for scheduled warmup`),patterns:w(v()).optional().describe(`Key patterns to warm up (e.g., "user:*", "config:*")`),concurrency:y().default(10).describe(`Maximum concurrent warmup operations`)}).describe(`Cache warmup strategy`));X(()=>eU.extend({consistency:tU.optional().describe(`Distributed cache consistency strategy`),avalanchePrevention:nU.optional().describe(`Cache avalanche and stampede prevention`),warmup:rU.optional().describe(`Cache warmup strategy`)}).describe(`Distributed cache configuration with consistency and avalanche prevention`));var iU=X(()=>A([`full`,`incremental`,`differential`]).describe(`Backup strategy type`)),aU=X(()=>T({days:y().min(1).describe(`Retention period in days`),minCopies:y().min(1).default(3).describe(`Minimum backup copies to retain`),maxCopies:y().optional().describe(`Maximum backup copies to store`)}).describe(`Backup retention policy`)),oU=X(()=>T({strategy:iU.default(`incremental`).describe(`Backup strategy`),schedule:YH.optional().describe("Cron expression for backup schedule — cron`0 2 * * *`"),retention:aU.describe(`Backup retention policy`),destination:T({type:A([`s3`,`gcs`,`azure_blob`,`local`]).describe(`Storage backend type`),bucket:v().optional().describe(`Cloud storage bucket/container name`),path:v().optional().describe(`Storage path prefix`),region:v().optional().describe(`Cloud storage region`)}).describe(`Backup storage destination`),encryption:T({enabled:b().default(!0).describe(`Enable backup encryption`),algorithm:A([`AES-256-GCM`,`AES-256-CBC`,`ChaCha20-Poly1305`]).default(`AES-256-GCM`).describe(`Encryption algorithm`),keyId:v().optional().describe(`KMS key ID for encryption`)}).optional().describe(`Backup encryption settings`),compression:T({enabled:b().default(!0).describe(`Enable backup compression`),algorithm:A([`gzip`,`zstd`,`lz4`,`snappy`]).default(`zstd`).describe(`Compression algorithm`)}).optional().describe(`Backup compression settings`),verifyAfterBackup:b().default(!0).describe(`Verify backup integrity after creation`)}).describe(`Backup configuration`)),sU=X(()=>A([`active_passive`,`active_active`,`pilot_light`,`warm_standby`]).describe(`Failover mode`)),cU=X(()=>T({mode:sU.default(`active_passive`).describe(`Failover mode`),autoFailover:b().default(!0).describe(`Enable automatic failover`),healthCheckInterval:y().default(30).describe(`Health check interval in seconds`),failureThreshold:y().default(3).describe(`Consecutive failures before failover`),regions:w(T({name:v().describe(`Region identifier (e.g., "us-east-1", "eu-west-1")`),role:A([`primary`,`secondary`,`witness`]).describe(`Region role`),endpoint:v().optional().describe(`Region endpoint URL`),priority:y().optional().describe(`Failover priority (lower = higher priority)`)})).min(2).describe(`Multi-region configuration (minimum 2 regions)`),dns:T({ttl:y().default(60).describe(`DNS TTL in seconds for failover`),provider:A([`route53`,`cloudflare`,`azure_dns`,`custom`]).optional().describe(`DNS provider for automatic failover`)}).optional().describe(`DNS failover settings`)}).describe(`Failover configuration`)),lU=X(()=>T({value:y().min(0).describe(`RPO value`),unit:A([`seconds`,`minutes`,`hours`]).default(`minutes`).describe(`RPO time unit`)}).describe(`Recovery Point Objective (maximum acceptable data loss)`)),uU=X(()=>T({value:y().min(0).describe(`RTO value`),unit:A([`seconds`,`minutes`,`hours`]).default(`minutes`).describe(`RTO time unit`)}).describe(`Recovery Time Objective (maximum acceptable downtime)`));X(()=>T({enabled:b().default(!1).describe(`Enable disaster recovery plan`),rpo:lU.describe(`Recovery Point Objective`),rto:uU.describe(`Recovery Time Objective`),backup:oU.describe(`Backup configuration`),failover:cU.optional().describe(`Multi-region failover configuration`),replication:T({mode:A([`synchronous`,`asynchronous`,`semi_synchronous`]).default(`asynchronous`).describe(`Data replication mode`),maxLagSeconds:y().optional().describe(`Maximum acceptable replication lag in seconds`),includeObjects:w(v()).optional().describe(`Objects to replicate (empty = all)`),excludeObjects:w(v()).optional().describe(`Objects to exclude from replication`)}).optional().describe(`Data replication settings`),testing:T({enabled:b().default(!1).describe(`Enable automated DR testing`),schedule:YH.optional().describe(`Cron expression for DR test schedule`),notificationChannel:v().optional().describe(`Notification channel for DR test results`)}).optional().describe(`Automated disaster recovery testing`),runbookUrl:v().optional().describe(`URL to disaster recovery runbook/playbook`),contacts:w(T({name:v().describe(`Contact name`),role:v().describe(`Contact role (e.g., "DBA", "SRE Lead")`),email:v().optional().describe(`Contact email`),phone:v().optional().describe(`Contact phone`)})).optional().describe(`Emergency contact list for DR incidents`)}).describe(`Complete disaster recovery plan configuration`));var dU=X(()=>A([`kafka`,`rabbitmq`,`aws-sqs`,`redis-pubsub`,`google-pubsub`,`azure-service-bus`]).describe(`Supported message queue backend provider`)),fU=X(()=>T({name:v().describe(`Topic name identifier`),partitions:y().default(1).describe(`Number of partitions for parallel consumption`),replicationFactor:y().default(1).describe(`Number of replicas for fault tolerance`),retentionMs:y().optional().describe(`Message retention period in milliseconds`),compressionType:A([`none`,`gzip`,`snappy`,`lz4`]).default(`none`).describe(`Message compression algorithm`)}).describe(`Configuration for a message queue topic`)),pU=X(()=>T({groupId:v().describe(`Consumer group identifier`),autoOffsetReset:A([`earliest`,`latest`]).default(`latest`).describe(`Where to start reading when no offset exists`),enableAutoCommit:b().default(!0).describe(`Automatically commit consumed offsets`),maxPollRecords:y().default(500).describe(`Maximum records returned per poll`)}).describe(`Consumer group configuration for topic consumption`)),mU=X(()=>T({enabled:b().default(!1).describe(`Enable dead letter queue for failed messages`),maxRetries:y().default(3).describe(`Maximum delivery attempts before sending to DLQ`),queueName:v().describe(`Name of the dead letter queue`)}).describe(`Dead letter queue configuration for unprocessable messages`));X(()=>T({provider:dU.describe(`Message queue backend provider`),topics:w(fU).describe(`List of topic configurations`),consumers:w(pU).optional().describe(`Consumer group configurations`),deadLetterQueue:mU.optional().describe(`Dead letter queue for failed messages`),ssl:b().default(!1).describe(`Enable SSL/TLS for broker connections`),sasl:T({mechanism:A([`plain`,`scram-sha-256`,`scram-sha-512`]).describe(`SASL authentication mechanism`),username:v().describe(`SASL username`),password:v().describe(`SASL password`)}).optional().describe(`SASL authentication configuration`)}).describe(`Top-level message queue configuration`));var hU=X(()=>v().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)`)),Z=X(()=>v().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)`));X(()=>v().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 gU=X(()=>A([`global`,`tenant`,`user`,`session`,`temp`,`cache`,`data`,`logs`,`config`,`public`]).describe(`Storage scope classification`));X(()=>T({path:v().describe(`File path`),name:v().describe(`File name`),size:y().int().describe(`File size in bytes`),mimeType:v().describe(`MIME type`),lastModified:v().datetime().describe(`Last modified timestamp`),created:v().datetime().describe(`Creation timestamp`),etag:v().optional().describe(`Entity tag`)}));var _U=X(()=>A([`s3`,`azure_blob`,`gcs`,`minio`,`r2`,`spaces`,`wasabi`,`backblaze`,`local`]).describe(`Storage provider type`)),vU=X(()=>A([`private`,`public_read`,`public_read_write`,`authenticated_read`,`bucket_owner_read`,`bucket_owner_full_control`]).describe(`Storage access control level`)),yU=X(()=>A([`standard`,`intelligent`,`infrequent_access`,`glacier`,`deep_archive`]).describe(`Storage class/tier for cost optimization`)),bU=X(()=>A([`transition`,`delete`,`abort`]).describe(`Lifecycle policy action type`));X(()=>T({contentType:v().describe(`MIME type (e.g., image/jpeg, application/pdf)`),contentLength:y().min(0).describe(`File size in bytes`),contentEncoding:v().optional().describe(`Content encoding (e.g., gzip)`),contentDisposition:v().optional().describe(`Content disposition header`),contentLanguage:v().optional().describe(`Content language`),cacheControl:v().optional().describe(`Cache control directives`),etag:v().optional().describe(`Entity tag for versioning/caching`),lastModified:v().datetime().optional().describe(`Last modification timestamp`),versionId:v().optional().describe(`Object version identifier`),storageClass:yU.optional().describe(`Storage class/tier`),encryption:T({algorithm:v().describe(`Encryption algorithm (e.g., AES256, aws:kms)`),keyId:v().optional().describe(`KMS key ID if using managed encryption`)}).optional().describe(`Server-side encryption configuration`),custom:k(v(),v()).optional().describe(`Custom user-defined metadata`)})),X(()=>T({operation:A([`get`,`put`,`delete`,`head`]).describe(`Allowed operation`),expiresIn:y().min(1).max(604800).describe(`Expiration time in seconds (max 7 days)`),contentType:v().optional().describe(`Required content type for PUT operations`),maxSize:y().min(0).optional().describe(`Maximum file size in bytes for PUT operations`),responseContentType:v().optional().describe(`Override content-type for GET operations`),responseContentDisposition:v().optional().describe(`Override content-disposition for GET operations`)}));var xU=X(()=>T({enabled:b().default(!0).describe(`Enable multipart uploads`),partSize:y().min(5*1024*1024).max(5*1024*1024*1024).default(10*1024*1024).describe(`Part size in bytes (min 5MB, max 5GB)`),maxParts:y().min(1).max(1e4).default(1e4).describe(`Maximum number of parts (max 10,000)`),threshold:y().min(0).default(100*1024*1024).describe(`File size threshold to trigger multipart upload (bytes)`),maxConcurrent:y().min(1).max(100).default(4).describe(`Maximum concurrent part uploads`),abortIncompleteAfterDays:y().min(1).optional().describe(`Auto-abort incomplete uploads after N days`)})),SU=X(()=>T({acl:vU.default(`private`).describe(`Default access control level`),allowedOrigins:w(v()).optional().describe(`CORS allowed origins`),allowedMethods:w(A([`GET`,`PUT`,`POST`,`DELETE`,`HEAD`])).optional().describe(`CORS allowed HTTP methods`),allowedHeaders:w(v()).optional().describe(`CORS allowed headers`),exposeHeaders:w(v()).optional().describe(`CORS exposed headers`),maxAge:y().min(0).optional().describe(`CORS preflight cache duration in seconds`),corsEnabled:b().default(!1).describe(`Enable CORS configuration`),publicAccess:T({allowPublicRead:b().default(!1).describe(`Allow public read access`),allowPublicWrite:b().default(!1).describe(`Allow public write access`),allowPublicList:b().default(!1).describe(`Allow public bucket listing`)}).optional().describe(`Public access control`),allowedIps:w(v()).optional().describe(`Allowed IP addresses/CIDR blocks`),blockedIps:w(v()).optional().describe(`Blocked IP addresses/CIDR blocks`)})),CU=X(()=>T({id:hU.describe(`Rule identifier`),enabled:b().default(!0).describe(`Enable this rule`),action:bU.describe(`Action to perform`),prefix:v().optional().describe(`Object key prefix filter (e.g., "uploads/")`),tags:k(v(),v()).optional().describe(`Object tag filters`),daysAfterCreation:y().min(0).optional().describe(`Days after object creation`),daysAfterModification:y().min(0).optional().describe(`Days after last modification`),targetStorageClass:yU.optional().describe(`Target storage class for transition action`)}).refine(e=>!(e.action===`transition`&&!e.targetStorageClass),{message:`targetStorageClass is required when action is "transition"`})),wU=X(()=>T({enabled:b().default(!1).describe(`Enable lifecycle policies`),rules:w(CU).default([]).describe(`Lifecycle rules`)})),TU=X(()=>T({name:hU.describe(`Bucket identifier in ObjectStack (snake_case)`),label:v().describe(`Display label`),bucketName:v().describe(`Actual bucket/container name in storage provider`),region:v().optional().describe(`Storage region (e.g., us-east-1, westus)`),provider:_U.describe(`Storage provider`),endpoint:v().optional().describe(`Custom endpoint URL (for S3-compatible providers)`),pathStyle:b().default(!1).describe(`Use path-style URLs (for S3-compatible providers)`),versioning:b().default(!1).describe(`Enable object versioning`),encryption:T({enabled:b().default(!1).describe(`Enable server-side encryption`),algorithm:A([`AES256`,`aws:kms`,`azure:kms`,`gcp:kms`]).default(`AES256`).describe(`Encryption algorithm`),kmsKeyId:v().optional().describe(`KMS key ID for managed encryption`)}).optional().describe(`Server-side encryption configuration`),accessControl:SU.optional().describe(`Access control configuration`),lifecyclePolicy:wU.optional().describe(`Lifecycle policy configuration`),multipartConfig:xU.optional().describe(`Multipart upload configuration`),tags:k(v(),v()).optional().describe(`Bucket tags for organization`),description:v().optional().describe(`Bucket description`),enabled:b().default(!0).describe(`Enable this bucket`)})),EU=X(()=>T({accessKeyId:v().optional().describe(`AWS access key ID or MinIO access key`),secretAccessKey:v().optional().describe(`AWS secret access key or MinIO secret key`),sessionToken:v().optional().describe(`AWS session token for temporary credentials`),accountName:v().optional().describe(`Azure storage account name`),accountKey:v().optional().describe(`Azure storage account key`),sasToken:v().optional().describe(`Azure SAS token`),environmentId:v().optional().describe(`GCP project ID`),credentials:v().optional().describe(`GCP service account credentials JSON`),endpoint:v().optional().describe(`Custom endpoint URL`),region:v().optional().describe(`Default region`),useSSL:b().default(!0).describe(`Use SSL/TLS for connections`),timeout:y().min(0).optional().describe(`Connection timeout in milliseconds`)})),DU=X(()=>T({name:hU.describe(`Storage configuration identifier`),label:v().describe(`Display label`),provider:_U.describe(`Primary storage provider`),scope:gU.optional().default(`global`).describe(`Storage scope`),connection:EU.describe(`Connection credentials`),buckets:w(TU).default([]).describe(`Configured buckets`),defaultBucket:v().optional().describe(`Default bucket name for operations`),location:v().optional().describe(`Root path (local) or base location`),quota:y().int().positive().optional().describe(`Max size in bytes`),options:k(v(),S()).optional().describe(`Provider-specific configuration options`),enabled:b().default(!0).describe(`Enable this storage configuration`),description:v().optional().describe(`Configuration description`)}));DU.parse({name:`aws_s3_storage`,label:`AWS S3 Production Storage`,provider:`s3`,connection:{accessKeyId:"${AWS_ACCESS_KEY_ID}",secretAccessKey:"${AWS_SECRET_ACCESS_KEY}",region:`us-east-1`},buckets:[{name:`user_uploads`,label:`User Uploads`,bucketName:`my-app-user-uploads`,region:`us-east-1`,provider:`s3`,versioning:!0,encryption:{enabled:!0,algorithm:`aws:kms`,kmsKeyId:"${AWS_KMS_KEY_ID}"},accessControl:{acl:`private`,corsEnabled:!0,allowedOrigins:[`https://app.example.com`],allowedMethods:[`GET`,`PUT`,`POST`]},lifecyclePolicy:{enabled:!0,rules:[{id:`archive_old_uploads`,enabled:!0,action:`transition`,daysAfterCreation:90,targetStorageClass:`glacier`}]},multipartConfig:{enabled:!0,partSize:10*1024*1024,threshold:100*1024*1024,maxConcurrent:4}}],defaultBucket:`user_uploads`,enabled:!0}),DU.parse({name:`minio_local`,label:`MinIO Local Storage`,provider:`minio`,connection:{accessKeyId:`minioadmin`,secretAccessKey:`minioadmin`,endpoint:`http://localhost:9000`,useSSL:!1},buckets:[{name:`development_files`,label:`Development Files`,bucketName:`dev-files`,provider:`minio`,endpoint:`http://localhost:9000`,pathStyle:!0,accessControl:{acl:`private`}}],defaultBucket:`development_files`,enabled:!0}),DU.parse({name:`azure_blob_storage`,label:`Azure Blob Storage`,provider:`azure_blob`,connection:{accountName:`mystorageaccount`,accountKey:"${AZURE_STORAGE_KEY}",endpoint:`https://mystorageaccount.blob.core.windows.net`},buckets:[{name:`media_files`,label:`Media Files`,bucketName:`media`,provider:`azure_blob`,region:`eastus`,accessControl:{acl:`public_read`,publicAccess:{allowPublicRead:!0,allowPublicWrite:!1,allowPublicList:!1}}}],defaultBucket:`media_files`,enabled:!0}),DU.parse({name:`gcs_storage`,label:`Google Cloud Storage`,provider:`gcs`,connection:{environmentId:`my-gcp-project`,credentials:"${GCP_SERVICE_ACCOUNT_JSON}"},buckets:[{name:`backup_storage`,label:`Backup Storage`,bucketName:`my-app-backups`,region:`us-central1`,provider:`gcs`,lifecyclePolicy:{enabled:!0,rules:[{id:`delete_old_backups`,enabled:!0,action:`delete`,daysAfterCreation:30}]}}],defaultBucket:`backup_storage`,enabled:!0});var OU=X(()=>A([`elasticsearch`,`algolia`,`meilisearch`,`typesense`,`opensearch`]).describe(`Supported full-text search engine provider`)),kU=X(()=>T({type:A([`standard`,`simple`,`whitespace`,`keyword`,`pattern`,`language`]).describe(`Text analyzer type`),language:v().optional().describe(`Language for language-specific analysis`),stopwords:w(v()).optional().describe(`Custom stopwords to filter during analysis`),customFilters:w(v()).optional().describe(`Additional token filter names to apply`)}).describe(`Text analyzer configuration for index tokenization and normalization`)),AU=X(()=>T({indexName:v().describe(`Name of the search index`),objectName:v().describe(`Source ObjectQL object`),fields:w(T({name:v().describe(`Field name to index`),type:A([`text`,`keyword`,`number`,`date`,`boolean`,`geo`]).describe(`Index field data type`),analyzer:v().optional().describe(`Named analyzer to use for this field`),searchable:b().default(!0).describe(`Include field in full-text search`),filterable:b().default(!1).describe(`Allow filtering on this field`),sortable:b().default(!1).describe(`Allow sorting by this field`),boost:y().default(1).describe(`Relevance boost factor for this field`)})).describe(`Fields to include in the search index`),replicas:y().default(1).describe(`Number of index replicas for availability`),shards:y().default(1).describe(`Number of index shards for distribution`)}).describe(`Search index definition mapping an ObjectQL object to a search engine index`)),jU=X(()=>T({field:v().describe(`Field name to generate facets from`),maxValues:y().default(10).describe(`Maximum number of facet values to return`),sort:A([`count`,`alpha`]).default(`count`).describe(`Facet value sort order`)}).describe(`Faceted search configuration for a single field`));X(()=>T({provider:OU.describe(`Search engine backend provider`),indexes:w(AU).describe(`Search index definitions`),analyzers:k(v(),kU).optional().describe(`Named text analyzer configurations`),facets:w(jU).optional().describe(`Faceted search configurations`),typoTolerance:b().default(!0).describe(`Enable typo-tolerant search`),synonyms:k(v(),w(v())).optional().describe(`Synonym mappings for search expansion`),ranking:w(A([`typo`,`geo`,`words`,`filters`,`proximity`,`attribute`,`exact`,`custom`])).optional().describe(`Custom ranking rule order`)}).describe(`Top-level full-text search engine configuration`));var MU=A([`GET`,`POST`,`PUT`,`DELETE`,`PATCH`,`HEAD`,`OPTIONS`]),NU=X(()=>A([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`])),PU=X(()=>T({url:v().describe(`API endpoint URL`),method:NU.optional().default(`GET`).describe(`HTTP method`),headers:k(v(),v()).optional().describe(`Custom HTTP headers`),params:k(v(),S()).optional().describe(`Query parameters`),body:S().optional().describe(`Request body for POST/PUT/PATCH`)})),FU=X(()=>T({enabled:b().default(!0).describe(`Enable CORS`),origins:E([v(),w(v())]).default(`*`).describe(`Allowed origins (* for all)`),methods:w(MU).optional().describe(`Allowed HTTP methods`),credentials:b().default(!1).describe(`Allow credentials (cookies, authorization headers)`),maxAge:y().int().optional().describe(`Preflight cache duration in seconds`)})),IU=X(()=>T({enabled:b().default(!1).describe(`Enable rate limiting`),windowMs:y().int().default(6e4).describe(`Time window in milliseconds`),maxRequests:y().int().default(100).describe(`Max requests per window`)})),LU=X(()=>T({path:v().describe(`URL path to serve from`),directory:v().describe(`Physical directory to serve`),cacheControl:v().optional().describe(`Cache-Control header value`)})),RU=X(()=>T({port:y().int().min(1).max(65535).default(3e3).describe(`Port number to listen on`),host:v().default(`0.0.0.0`).describe(`Host address to bind to`),cors:FU.optional().describe(`CORS configuration`),requestTimeout:y().int().default(3e4).describe(`Request timeout in milliseconds`),bodyLimit:v().default(`10mb`).describe(`Maximum request body size`),compression:b().default(!0).describe(`Enable response compression`),security:T({helmet:b().default(!0).describe(`Enable security headers via helmet`),rateLimit:IU.optional().describe(`Global rate limiting configuration`)}).optional().describe(`Security configuration`),static:w(LU).optional().describe(`Static file serving configuration`),trustProxy:b().default(!1).describe(`Trust X-Forwarded-* headers`)}));X(()=>T({method:MU.describe(`HTTP method`),path:v().describe(`URL path pattern`),handler:v().describe(`Handler identifier or name`),metadata:T({summary:v().optional().describe(`Route summary for documentation`),description:v().optional().describe(`Route description`),tags:w(v()).optional().describe(`Tags for grouping`),operationId:v().optional().describe(`Unique operation identifier`)}).optional(),security:T({authRequired:b().default(!0).describe(`Require authentication`),permissions:w(v()).optional().describe(`Required permissions`),rateLimit:v().optional().describe(`Rate limit policy override`)}).optional()}));var zU=A([`authentication`,`authorization`,`logging`,`validation`,`transformation`,`error`,`custom`]),BU=X(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Middleware name (snake_case)`),type:zU.describe(`Middleware type`),enabled:b().default(!0).describe(`Whether middleware is enabled`),order:y().int().default(100).describe(`Execution order priority`),config:k(v(),S()).optional().describe(`Middleware configuration object`),paths:T({include:w(v()).optional().describe(`Include path patterns (glob)`),exclude:w(v()).optional().describe(`Exclude path patterns (glob)`)}).optional().describe(`Path filtering`)})),VU=A([`starting`,`started`,`stopping`,`stopped`,`request`,`response`,`error`]);X(()=>T({type:VU.describe(`Event type`),timestamp:v().datetime().describe(`Event timestamp (ISO 8601)`),data:k(v(),S()).optional().describe(`Event-specific data`)})),X(()=>T({httpVersions:w(A([`1.0`,`1.1`,`2.0`,`3.0`])).default([`1.1`]).describe(`Supported HTTP versions`),websocket:b().default(!1).describe(`WebSocket support`),sse:b().default(!1).describe(`Server-Sent Events support`),serverPush:b().default(!1).describe(`HTTP/2 Server Push support`),streaming:b().default(!0).describe(`Response streaming support`),middleware:b().default(!0).describe(`Middleware chain support`),routeParams:b().default(!0).describe(`URL parameter support (/users/:id)`),compression:b().default(!0).describe(`Built-in compression support`)})),X(()=>T({state:A([`stopped`,`starting`,`running`,`stopping`,`error`]).describe(`Current server state`),uptime:y().int().optional().describe(`Server uptime in milliseconds`),server:T({port:y().int().describe(`Listening port`),host:v().describe(`Bound host`),url:v().optional().describe(`Full server URL`)}).optional(),connections:T({active:y().int().describe(`Active connections`),total:y().int().describe(`Total connections handled`)}).optional(),requests:T({total:y().int().describe(`Total requests processed`),success:y().int().describe(`Successful requests`),errors:y().int().describe(`Failed requests`)}).optional()})),Object.assign(RU,{create:e=>e}),Object.assign(BU,{create:e=>e});var HU=A(`data.create,data.read,data.update,data.delete,data.export,data.import,data.bulk_update,data.bulk_delete,auth.login,auth.login_failed,auth.logout,auth.session_created,auth.session_expired,auth.password_reset,auth.password_changed,auth.email_verified,auth.mfa_enabled,auth.mfa_disabled,auth.account_locked,auth.account_unlocked,authz.permission_granted,authz.permission_revoked,authz.role_assigned,authz.role_removed,authz.role_created,authz.role_updated,authz.role_deleted,authz.policy_created,authz.policy_updated,authz.policy_deleted,system.config_changed,system.plugin_installed,system.plugin_uninstalled,system.backup_created,system.backup_restored,system.integration_added,system.integration_removed,security.access_denied,security.suspicious_activity,security.data_breach,security.api_key_created,security.api_key_revoked`.split(`,`)),UU=A([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),WU=X(()=>T({type:A([`user`,`system`,`service`,`api_client`,`integration`]).describe(`Actor type`),id:v().describe(`Actor identifier`),name:v().optional().describe(`Actor display name`),email:v().email().optional().describe(`Actor email address`),ipAddress:v().optional().describe(`Actor IP address`),userAgent:v().optional().describe(`User agent string`)})),GU=X(()=>T({type:v().describe(`Target type`),id:v().describe(`Target identifier`),name:v().optional().describe(`Target display name`),metadata:k(v(),S()).optional().describe(`Target metadata`)})),KU=X(()=>T({field:v().describe(`Changed field name`),oldValue:S().optional().describe(`Previous value`),newValue:S().optional().describe(`New value`)}));X(()=>T({id:v().describe(`Audit event ID`),eventType:HU.describe(`Event type`),severity:UU.default(`info`).describe(`Event severity`),timestamp:v().datetime().describe(`Event timestamp`),actor:WU.describe(`Event actor`),target:GU.optional().describe(`Event target`),description:v().describe(`Event description`),changes:w(KU).optional().describe(`List of changes`),result:A([`success`,`failure`,`partial`]).default(`success`).describe(`Action result`),errorMessage:v().optional().describe(`Error message`),tenantId:v().optional().describe(`Tenant identifier`),requestId:v().optional().describe(`Request ID for tracing`),metadata:k(v(),S()).optional().describe(`Additional metadata`),location:T({country:v().optional(),region:v().optional(),city:v().optional()}).optional().describe(`Geographic location`)}));var qU=X(()=>T({retentionDays:y().int().min(1).default(180).describe(`Retention period in days`),archiveAfterRetention:b().default(!0).describe(`Archive logs after retention period`),archiveStorage:T({type:A([`s3`,`gcs`,`azure_blob`,`filesystem`]).describe(`Archive storage type`),endpoint:v().optional().describe(`Storage endpoint URL`),bucket:v().optional().describe(`Storage bucket/container name`),path:v().optional().describe(`Storage path prefix`),credentials:k(v(),S()).optional().describe(`Storage credentials`)}).optional().describe(`Archive storage configuration`),customRetention:k(v(),y().int().positive()).optional().describe(`Custom retention by event type`),minimumRetentionDays:y().int().positive().optional().describe(`Minimum retention for compliance`)})),JU=X(()=>T({id:v().describe(`Rule identifier`),name:v().describe(`Rule name`),description:v().optional().describe(`Rule description`),enabled:b().default(!0).describe(`Rule enabled status`),eventTypes:w(HU).describe(`Event types to monitor`),condition:E([T({threshold:y().int().positive().describe(`Event threshold`),windowSeconds:y().int().positive().describe(`Time window in seconds`),groupBy:w(v()).optional().describe(`Grouping criteria`),filters:k(v(),S()).optional().describe(`Additional filters`)}),JH]).describe(`Detection condition — structured threshold or CEL predicate`),actions:w(A([`alert`,`lock_account`,`block_ip`,`require_mfa`,`log_critical`,`webhook`])).describe(`Actions to take`),alertSeverity:UU.default(`warning`).describe(`Alert severity`),notifications:T({email:w(v().email()).optional().describe(`Email recipients`),slack:v().url().optional().describe(`Slack webhook URL`),webhook:v().url().optional().describe(`Custom webhook URL`)}).optional().describe(`Notification configuration`)})),YU=X(()=>T({type:A([`database`,`elasticsearch`,`mongodb`,`clickhouse`,`s3`,`gcs`,`azure_blob`,`custom`]).describe(`Storage backend type`),connectionString:v().optional().describe(`Connection string`),config:k(v(),S()).optional().describe(`Storage-specific configuration`),bufferEnabled:b().default(!0).describe(`Enable buffering`),bufferSize:y().int().positive().default(100).describe(`Buffer size`),flushIntervalSeconds:y().int().positive().default(5).describe(`Flush interval in seconds`),compression:b().default(!0).describe(`Enable compression`)}));X(()=>T({eventTypes:w(HU).optional().describe(`Event types to include`),severities:w(UU).optional().describe(`Severity levels to include`),actorId:v().optional().describe(`Actor identifier`),tenantId:v().optional().describe(`Tenant identifier`),timeRange:T({from:v().datetime().describe(`Start time`),to:v().datetime().describe(`End time`)}).optional().describe(`Time range filter`),result:A([`success`,`failure`,`partial`]).optional().describe(`Result status`),searchQuery:v().optional().describe(`Search query`),customFilters:k(v(),S()).optional().describe(`Custom filters`)})),X(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).max(64).describe(`Configuration name (snake_case, max 64 chars)`),label:v().describe(`Display label`),enabled:b().default(!0).describe(`Enable audit logging`),eventTypes:w(HU).optional().describe(`Event types to audit`),excludeEventTypes:w(HU).optional().describe(`Event types to exclude`),minimumSeverity:UU.default(`info`).describe(`Minimum severity level`),storage:YU.describe(`Storage configuration`),retentionPolicy:qU.optional().describe(`Retention policy`),suspiciousActivityRules:w(JU).default([]).describe(`Suspicious activity rules`),includeSensitiveData:b().default(!1).describe(`Include sensitive data`),redactFields:w(v()).default([`password`,`passwordHash`,`token`,`apiKey`,`secret`,`creditCard`,`ssn`]).describe(`Fields to redact`),logReads:b().default(!1).describe(`Log read operations`),readSamplingRate:y().min(0).max(1).default(.1).describe(`Read sampling rate`),logSystemEvents:b().default(!0).describe(`Log system events`),customHandlers:w(T({eventType:HU.describe(`Event type to handle`),handlerId:v().describe(`Unique identifier for the handler`)})).optional().describe(`Custom event handler references`),compliance:T({standards:w(A([`sox`,`hipaa`,`gdpr`,`pci_dss`,`iso_27001`,`fedramp`])).optional().describe(`Compliance standards`),immutableLogs:b().default(!0).describe(`Enforce immutable logs`),requireSigning:b().default(!1).describe(`Require log signing`),signingKey:v().optional().describe(`Signing key`)}).optional().describe(`Compliance configuration`)}));var XU=A([`debug`,`info`,`warn`,`error`,`fatal`,`silent`]).describe(`Log severity level`),ZU=A([`json`,`text`,`pretty`]).describe(`Log output format`),QU=X(()=>T({name:v().optional().describe(`Logger name identifier`),level:XU.optional().default(`info`),format:ZU.optional().default(`json`),redact:w(v()).optional().default([`password`,`token`,`secret`,`key`]).describe(`Keys to redact from log context`),sourceLocation:b().optional().default(!1).describe(`Include file and line number`),file:v().optional().describe(`Path to log file`),rotation:T({maxSize:v().optional().default(`10m`),maxFiles:y().optional().default(5)}).optional()}));X(()=>T({timestamp:v().datetime().describe(`ISO 8601 timestamp`),level:XU,message:v().describe(`Log message`),context:k(v(),S()).optional().describe(`Structured context data`),error:k(v(),S()).optional().describe(`Error object if present`),traceId:v().optional().describe(`Distributed trace ID`),spanId:v().optional().describe(`Span ID`),service:v().optional().describe(`Service name`),component:v().optional().describe(`Component name (e.g. plugin id)`)}));var $U=A([`trace`,`debug`,`info`,`warn`,`error`,`fatal`]).describe(`Extended log severity level`),eW=A([`console`,`file`,`syslog`,`elasticsearch`,`cloudwatch`,`stackdriver`,`azure_monitor`,`datadog`,`splunk`,`loki`,`http`,`kafka`,`redis`,`custom`]).describe(`Log destination type`),tW=X(()=>T({stream:A([`stdout`,`stderr`]).optional().default(`stdout`),colors:b().optional().default(!0),prettyPrint:b().optional().default(!1)}).describe(`Console destination configuration`)),nW=X(()=>T({path:v().describe(`Log file path`),rotation:T({maxSize:v().optional().default(`10m`),maxFiles:y().int().positive().optional().default(5),compress:b().optional().default(!0),interval:A([`hourly`,`daily`,`weekly`,`monthly`]).optional()}).optional(),encoding:v().optional().default(`utf8`),append:b().optional().default(!0)}).describe(`File destination configuration`)),rW=X(()=>T({url:v().url().describe(`HTTP endpoint URL`),method:A([`POST`,`PUT`]).optional().default(`POST`),headers:k(v(),v()).optional(),auth:T({type:A([`basic`,`bearer`,`api_key`]).describe(`Auth type`),username:v().optional(),password:v().optional(),token:v().optional(),apiKey:v().optional(),apiKeyHeader:v().optional().default(`X-API-Key`)}).optional(),batch:T({maxSize:y().int().positive().optional().default(100),flushInterval:y().int().positive().optional().default(5e3)}).optional(),retry:T({maxAttempts:y().int().positive().optional().default(3),initialDelay:y().int().positive().optional().default(1e3),backoffMultiplier:y().positive().optional().default(2)}).optional(),timeout:y().int().positive().optional().default(3e4)}).describe(`HTTP destination configuration`)),iW=X(()=>T({endpoint:v().url().optional(),region:v().optional(),credentials:T({accessKeyId:v().optional(),secretAccessKey:v().optional(),apiKey:v().optional(),environmentId:v().optional()}).optional(),logGroup:v().optional(),logStream:v().optional(),index:v().optional(),config:k(v(),S()).optional()}).describe(`External service destination configuration`)),aW=X(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Destination name (snake_case)`),type:eW.describe(`Destination type`),level:$U.optional().default(`info`),enabled:b().optional().default(!0),console:tW.optional(),file:nW.optional(),http:rW.optional(),externalService:iW.optional(),format:A([`json`,`text`,`pretty`]).optional().default(`json`),filterId:v().optional().describe(`Filter function identifier`)}).describe(`Log destination configuration`)),oW=X(()=>T({staticFields:k(v(),S()).optional().describe(`Static fields added to every log`),dynamicEnrichers:w(v()).optional().describe(`Dynamic enricher function IDs`),addHostname:b().optional().default(!0),addProcessId:b().optional().default(!0),addEnvironment:b().optional().default(!0),addTimestampFormats:T({unix:b().optional().default(!1),iso:b().optional().default(!0)}).optional(),addCaller:b().optional().default(!1),addCorrelationIds:b().optional().default(!0)}).describe(`Log enrichment configuration`));X(()=>T({timestamp:v().datetime().describe(`ISO 8601 timestamp`),level:$U.describe(`Log severity level`),message:v().describe(`Log message`),context:k(v(),S()).optional().describe(`Structured context`),error:T({name:v().optional(),message:v().optional(),stack:v().optional(),code:v().optional(),details:k(v(),S()).optional()}).optional().describe(`Error details`),trace:T({traceId:v().describe(`Trace ID`),spanId:v().describe(`Span ID`),parentSpanId:v().optional().describe(`Parent span ID`),traceFlags:y().int().optional().describe(`Trace flags`)}).optional().describe(`Distributed tracing context`),source:T({service:v().optional().describe(`Service name`),component:v().optional().describe(`Component name`),file:v().optional().describe(`Source file`),line:y().int().optional().describe(`Line number`),function:v().optional().describe(`Function name`)}).optional().describe(`Source information`),host:T({hostname:v().optional(),pid:y().int().optional(),ip:v().optional()}).optional().describe(`Host information`),environment:v().optional().describe(`Environment (e.g., production, staging)`),user:T({id:v().optional(),username:v().optional(),email:v().optional()}).optional().describe(`User context`),request:T({id:v().optional(),method:v().optional(),path:v().optional(),userAgent:v().optional(),ip:v().optional()}).optional().describe(`Request context`),labels:k(v(),v()).optional().describe(`Custom labels`),metadata:k(v(),S()).optional().describe(`Additional metadata`)}).describe(`Structured log entry`)),X(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).max(64).describe(`Configuration name (snake_case, max 64 chars)`),label:v().describe(`Display label`),enabled:b().optional().default(!0),level:$U.optional().default(`info`),default:QU.optional().describe(`Default logger configuration`),loggers:k(v(),QU).optional().describe(`Named logger configurations`),destinations:w(aW).describe(`Log destinations`),enrichment:oW.optional(),redact:w(v()).optional().default([`password`,`passwordHash`,`token`,`apiKey`,`secret`,`creditCard`,`ssn`,`authorization`]).describe(`Fields to redact`),sampling:T({enabled:b().optional().default(!1),rate:y().min(0).max(1).optional().default(1),rateByLevel:k(v(),y().min(0).max(1)).optional()}).optional(),buffer:T({enabled:b().optional().default(!0),size:y().int().positive().optional().default(1e3),flushInterval:y().int().positive().optional().default(1e3),flushOnShutdown:b().optional().default(!0)}).optional(),performance:T({async:b().optional().default(!0),workers:y().int().positive().optional().default(1)}).optional()}).describe(`Logging configuration`));var sW=A([`counter`,`gauge`,`histogram`,`summary`]).describe(`Metric type`),cW=A([`nanoseconds`,`microseconds`,`milliseconds`,`seconds`,`minutes`,`hours`,`days`,`bytes`,`kilobytes`,`megabytes`,`gigabytes`,`terabytes`,`requests_per_second`,`events_per_second`,`bytes_per_second`,`percent`,`ratio`,`count`,`operations`,`custom`]).describe(`Metric unit`),lW=A([`sum`,`avg`,`min`,`max`,`count`,`p50`,`p75`,`p90`,`p95`,`p99`,`p999`,`rate`,`stddev`]).describe(`Metric aggregation type`),uW=X(()=>T({type:A([`linear`,`exponential`,`explicit`]).describe(`Bucket type`),linear:T({start:y().describe(`Start value`),width:y().positive().describe(`Bucket width`),count:y().int().positive().describe(`Number of buckets`)}).optional(),exponential:T({start:y().positive().describe(`Start value`),factor:y().positive().describe(`Growth factor`),count:y().int().positive().describe(`Number of buckets`)}).optional(),explicit:T({boundaries:w(y()).describe(`Bucket boundaries`)}).optional()}).describe(`Histogram bucket configuration`)),dW=X(()=>k(v(),v()).describe(`Metric labels`)),fW=X(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Metric name (snake_case)`),label:v().optional().describe(`Display label`),type:sW.describe(`Metric type`),unit:cW.optional().describe(`Metric unit`),description:v().optional().describe(`Metric description`),labelNames:w(v()).optional().default([]).describe(`Label names`),histogram:uW.optional(),summary:T({quantiles:w(y().min(0).max(1)).optional().default([.5,.9,.99]),maxAge:y().int().positive().optional().default(600),ageBuckets:y().int().positive().optional().default(5)}).optional(),enabled:b().optional().default(!0)}).describe(`Metric definition`));X(()=>T({name:v().describe(`Metric name`),type:sW.describe(`Metric type`),timestamp:v().datetime().describe(`Observation timestamp`),value:y().optional().describe(`Metric value`),labels:dW.optional().describe(`Metric labels`),histogram:T({count:y().int().nonnegative().describe(`Total count`),sum:y().describe(`Sum of all values`),buckets:w(T({upperBound:y().describe(`Upper bound of bucket`),count:y().int().nonnegative().describe(`Count in bucket`)})).describe(`Histogram buckets`)}).optional(),summary:T({count:y().int().nonnegative().describe(`Total count`),sum:y().describe(`Sum of all values`),quantiles:w(T({quantile:y().min(0).max(1).describe(`Quantile (0-1)`),value:y().describe(`Quantile value`)})).describe(`Summary quantiles`)}).optional()}).describe(`Metric data point`));var pW=X(()=>T({timestamp:v().datetime().describe(`Timestamp`),value:y().describe(`Value`),labels:k(v(),v()).optional().describe(`Labels`)}).describe(`Time series data point`));X(()=>T({name:v().describe(`Series name`),labels:k(v(),v()).optional().describe(`Series labels`),dataPoints:w(pW).describe(`Data points`),startTime:v().datetime().optional().describe(`Start time`),endTime:v().datetime().optional().describe(`End time`)}).describe(`Time series`));var mW=X(()=>T({type:lW.describe(`Aggregation type`),window:T({size:y().int().positive().describe(`Window size in seconds`),sliding:b().optional().default(!1),slideInterval:y().int().positive().optional()}).optional(),groupBy:w(v()).optional().describe(`Group by label names`),filters:k(v(),S()).optional().describe(`Filter criteria`)}).describe(`Metric aggregation configuration`)),hW=X(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`SLI name (snake_case)`),label:v().describe(`Display label`),description:v().optional().describe(`SLI description`),metric:v().describe(`Base metric name`),type:A([`availability`,`latency`,`throughput`,`error_rate`,`saturation`,`custom`]).describe(`SLI type`),successCriteria:E([T({threshold:y().describe(`Threshold value`),operator:A([`lt`,`lte`,`gt`,`gte`,`eq`]).describe(`Comparison operator`),percentile:y().min(0).max(1).optional().describe(`Percentile (0-1)`)}),JH]).describe(`Success criteria — structured or CEL predicate`),window:T({size:y().int().positive().describe(`Window size in seconds`),rolling:b().optional().default(!0)}).describe(`Measurement window`),enabled:b().optional().default(!0)}).describe(`Service Level Indicator`)),gW=X(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`SLO name (snake_case)`),label:v().describe(`Display label`),description:v().optional().describe(`SLO description`),sli:v().describe(`SLI name`),target:y().min(0).max(100).describe(`Target percentage`),period:T({type:A([`rolling`,`calendar`]).describe(`Period type`),duration:y().int().positive().optional().describe(`Duration in seconds`),calendar:A([`daily`,`weekly`,`monthly`,`quarterly`,`yearly`]).optional()}).describe(`Time period`),errorBudget:T({enabled:b().optional().default(!0),alertThreshold:y().min(0).max(100).optional().default(80),burnRateWindows:w(T({window:y().int().positive().describe(`Window size`),threshold:y().positive().describe(`Burn rate threshold`)})).optional()}).optional(),alerts:w(T({name:v().describe(`Alert name`),severity:A([`info`,`warning`,`critical`]).describe(`Alert severity`),condition:T({type:A([`slo_breach`,`error_budget`,`burn_rate`]).describe(`Condition type`),threshold:y().optional().describe(`Threshold value`)}).describe(`Alert condition`)})).optional().default([]),enabled:b().optional().default(!0)}).describe(`Service Level Objective`)),_W=X(()=>T({type:A([`prometheus`,`openmetrics`,`graphite`,`statsd`,`influxdb`,`datadog`,`cloudwatch`,`stackdriver`,`azure_monitor`,`http`,`custom`]).describe(`Export type`),endpoint:v().optional().describe(`Export endpoint`),interval:y().int().positive().optional().default(60),batch:T({enabled:b().optional().default(!0),size:y().int().positive().optional().default(1e3)}).optional(),auth:T({type:A([`none`,`basic`,`bearer`,`api_key`]).describe(`Auth type`),username:v().optional(),password:v().optional(),token:v().optional(),apiKey:v().optional()}).optional(),config:k(v(),S()).optional().describe(`Additional configuration`)}).describe(`Metric export configuration`));X(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).max(64).describe(`Configuration name (snake_case, max 64 chars)`),label:v().describe(`Display label`),enabled:b().optional().default(!0),metrics:w(fW).optional().default([]),defaultLabels:dW.optional().default({}),aggregations:w(mW).optional().default([]),slis:w(hW).optional().default([]),slos:w(gW).optional().default([]),exports:w(_W).optional().default([]),collectionInterval:y().int().positive().optional().default(15),retention:T({period:y().int().positive().optional().default(604800),downsampling:w(T({afterSeconds:y().int().positive().describe(`Downsample after seconds`),resolution:y().int().positive().describe(`Downsampled resolution`)})).optional()}).optional(),cardinalityLimits:T({maxLabelCombinations:y().int().positive().optional().default(1e4),onLimitExceeded:A([`drop`,`sample`,`alert`]).optional().default(`alert`)}).optional()}).describe(`Metrics configuration`));var vW=X(()=>T({entries:k(v(),v()).describe(`Trace state entries`)}).describe(`Trace state`)),yW=X(()=>y().int().min(0).max(255).describe(`Trace flags bitmap`)),bW=X(()=>T({traceId:v().regex(/^[0-9a-f]{32}$/).describe(`Trace ID (32 hex chars)`),spanId:v().regex(/^[0-9a-f]{16}$/).describe(`Span ID (16 hex chars)`),traceFlags:yW.optional().default(1),traceState:vW.optional(),parentSpanId:v().regex(/^[0-9a-f]{16}$/).optional().describe(`Parent span ID (16 hex chars)`),sampled:b().optional().default(!0),remote:b().optional().default(!1)}).describe(`Trace context (W3C Trace Context)`)),xW=A([`internal`,`server`,`client`,`producer`,`consumer`]).describe(`Span kind`),SW=A([`unset`,`ok`,`error`]).describe(`Span status`),CW=X(()=>E([v(),y(),b(),w(v()),w(y()),w(b())]).describe(`Span attribute value`)),wW=X(()=>k(v(),CW).describe(`Span attributes`)),TW=X(()=>T({name:v().describe(`Event name`),timestamp:v().datetime().describe(`Event timestamp`),attributes:wW.optional().describe(`Event attributes`)}).describe(`Span event`)),EW=X(()=>T({context:bW.describe(`Linked trace context`),attributes:wW.optional().describe(`Link attributes`)}).describe(`Span link`));X(()=>T({context:bW.describe(`Trace context`),name:v().describe(`Span name`),kind:xW.optional().default(`internal`),startTime:v().datetime().describe(`Span start time`),endTime:v().datetime().optional().describe(`Span end time`),duration:y().nonnegative().optional().describe(`Duration in milliseconds`),status:T({code:SW.describe(`Status code`),message:v().optional().describe(`Status message`)}).optional(),attributes:wW.optional().default({}),events:w(TW).optional().default([]),links:w(EW).optional().default([]),resource:wW.optional().describe(`Resource attributes`),instrumentationLibrary:T({name:v().describe(`Library name`),version:v().optional().describe(`Library version`)}).optional()}).describe(`OpenTelemetry span`));var DW=A([`drop`,`record_only`,`record_and_sample`]).describe(`Sampling decision`),OW=A([`always_on`,`always_off`,`trace_id_ratio`,`rate_limiting`,`parent_based`,`probability`,`composite`,`custom`]).describe(`Sampling strategy type`),kW=X(()=>T({type:OW.describe(`Sampling strategy`),ratio:y().min(0).max(1).optional().describe(`Sample ratio (0-1)`),rateLimit:y().positive().optional().describe(`Traces per second`),parentBased:T({whenParentSampled:OW.optional().default(`always_on`),whenParentNotSampled:OW.optional().default(`always_off`),root:OW.optional().default(`trace_id_ratio`),rootRatio:y().min(0).max(1).optional().default(.1)}).optional(),composite:w(T({strategy:OW.describe(`Strategy type`),ratio:y().min(0).max(1).optional(),condition:E([k(v(),S()),JH]).optional().describe(`Condition for this strategy — structured filter or CEL predicate`)})).optional(),rules:w(T({name:v().describe(`Rule name`),match:T({service:v().optional(),spanName:v().optional(),attributes:k(v(),S()).optional()}).optional(),decision:DW.describe(`Sampling decision`),rate:y().min(0).max(1).optional()})).optional().default([]),customSamplerId:v().optional().describe(`Custom sampler identifier`)}).describe(`Trace sampling configuration`)),AW=A([`w3c`,`b3`,`b3_multi`,`jaeger`,`xray`,`ottrace`,`custom`]).describe(`Trace propagation format`),jW=X(()=>T({formats:w(AW).optional().default([`w3c`]),extract:b().optional().default(!0),inject:b().optional().default(!0),headers:T({traceId:v().optional(),spanId:v().optional(),traceFlags:v().optional(),traceState:v().optional()}).optional(),baggage:T({enabled:b().optional().default(!0),maxSize:y().int().positive().optional().default(8192),allowedKeys:w(v()).optional()}).optional()}).describe(`Trace context propagation`)),MW=A([`otlp_http`,`otlp_grpc`,`jaeger`,`zipkin`,`console`,`datadog`,`honeycomb`,`lightstep`,`newrelic`,`custom`]).describe(`OpenTelemetry exporter type`),NW=X(()=>T({sdkVersion:v().optional().describe(`OTel SDK version`),exporter:T({type:MW.describe(`Exporter type`),endpoint:v().url().optional().describe(`Exporter endpoint`),protocol:v().optional().describe(`Protocol version`),headers:k(v(),v()).optional().describe(`HTTP headers`),timeout:y().int().positive().optional().default(1e4),compression:A([`none`,`gzip`]).optional().default(`none`),batch:T({maxBatchSize:y().int().positive().optional().default(512),maxQueueSize:y().int().positive().optional().default(2048),exportTimeout:y().int().positive().optional().default(3e4),scheduledDelay:y().int().positive().optional().default(5e3)}).optional()}).describe(`Exporter configuration`),resource:T({serviceName:v().describe(`Service name`),serviceVersion:v().optional().describe(`Service version`),serviceInstanceId:v().optional().describe(`Service instance ID`),serviceNamespace:v().optional().describe(`Service namespace`),deploymentEnvironment:v().optional().describe(`Deployment environment`),attributes:wW.optional().describe(`Additional resource attributes`)}).describe(`Resource attributes`),instrumentation:T({autoInstrumentation:b().optional().default(!0),libraries:w(v()).optional().describe(`Enabled libraries`),disabledLibraries:w(v()).optional().describe(`Disabled libraries`)}).optional(),semanticConventionsVersion:v().optional().describe(`Semantic conventions version`)}).describe(`OpenTelemetry compatibility configuration`));X(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).max(64).describe(`Configuration name (snake_case, max 64 chars)`),label:v().describe(`Display label`),enabled:b().optional().default(!0),sampling:kW.optional().default({type:`always_on`,rules:[]}),propagation:jW.optional().default({formats:[`w3c`],extract:!0,inject:!0}),openTelemetry:NW.optional(),spanLimits:T({maxAttributes:y().int().positive().optional().default(128),maxEvents:y().int().positive().optional().default(128),maxLinks:y().int().positive().optional().default(128),maxAttributeValueLength:y().int().positive().optional().default(4096)}).optional(),traceIdGenerator:A([`random`,`uuid`,`custom`]).optional().default(`random`),customTraceIdGeneratorId:v().optional().describe(`Custom generator identifier`),performance:T({asyncExport:b().optional().default(!0),exportInterval:y().int().positive().optional().default(5e3)}).optional()}).describe(`Tracing configuration`));var PW=X(()=>A([`pii`,`phi`,`pci`,`financial`,`confidential`,`internal`,`public`]).describe(`Data classification level`)),FW=X(()=>A([`gdpr`,`hipaa`,`sox`,`pci_dss`,`ccpa`,`iso27001`]).describe(`Compliance framework identifier`)),IW=X(()=>T({framework:FW.describe(`Compliance framework identifier`),requiredEvents:w(v()).describe(`Audit event types required by this framework (e.g., "data.delete", "auth.login")`),retentionDays:y().min(1).describe(`Minimum audit log retention period required by this framework (in days)`),alertOnMissing:b().default(!0).describe(`Raise alert if a required audit event is not being captured`)}).describe(`Compliance framework audit event requirements`)),LW=X(()=>T({framework:FW.describe(`Compliance framework identifier`),dataClassifications:w(PW).describe(`Data classifications that must be encrypted under this framework`),minimumAlgorithm:A([`aes-256-gcm`,`aes-256-cbc`,`chacha20-poly1305`]).default(`aes-256-gcm`).describe(`Minimum encryption algorithm strength required`),keyRotationMaxDays:y().min(1).default(90).describe(`Maximum key rotation interval required (in days)`)}).describe(`Compliance framework encryption requirements`)),RW=X(()=>T({dataClassification:PW.describe(`Data classification this rule applies to`),defaultMasked:b().default(!0).describe(`Whether data is masked by default`),unmaskRoles:w(v()).optional().describe(`Roles allowed to view unmasked data`),auditUnmask:b().default(!0).describe(`Log an audit event when data is unmasked`),requireApproval:b().default(!1).describe(`Require explicit approval before unmasking`),approvalRoles:w(v()).optional().describe(`Roles that can approve unmasking requests`)}).describe(`Masking visibility and audit rule per data classification`)),zW=X(()=>T({enabled:b().default(!0).describe(`Enable cross-subsystem security event correlation`),correlationId:b().default(!0).describe(`Inject a shared correlation ID into audit, encryption, and masking events`),linkAuthToAudit:b().default(!0).describe(`Link authentication events to subsequent data operation audit trails`),linkEncryptionToAudit:b().default(!0).describe(`Log encryption/decryption operations in the audit trail`),linkMaskingToAudit:b().default(!0).describe(`Log masking/unmasking operations in the audit trail`)}).describe(`Cross-subsystem security event correlation configuration`)),BW=X(()=>T({classification:PW.describe(`Data classification level`),requireEncryption:b().default(!1).describe(`Encryption required for this classification`),requireMasking:b().default(!1).describe(`Masking required for this classification`),requireAudit:b().default(!1).describe(`Audit trail required for access to this classification`),retentionDays:y().optional().describe(`Data retention limit in days (for compliance)`)}).describe(`Security policy for a specific data classification level`));X(()=>T({enabled:b().default(!0).describe(`Enable unified security context governance`),complianceAuditRequirements:w(IW).optional().describe(`Compliance-driven audit event requirements`),complianceEncryptionRequirements:w(LW).optional().describe(`Compliance-driven encryption requirements by data classification`),maskingVisibility:w(RW).optional().describe(`Masking visibility rules per data classification`),dataClassifications:w(BW).optional().describe(`Data classification policies for unified security enforcement`),eventCorrelation:zW.optional().describe(`Cross-subsystem security event correlation settings`),enforceOnWrite:b().default(!0).describe(`Enforce encryption and masking requirements on data write operations`),enforceOnRead:b().default(!0).describe(`Enforce masking and audit requirements on data read operations`),failOpen:b().default(!1).describe(`When false (default), deny access if security context cannot be evaluated`)}).describe(`Unified security context governance configuration`));var VW=X(()=>A([`standard`,`normal`,`emergency`,`major`])),HW=X(()=>A([`critical`,`high`,`medium`,`low`])),UW=X(()=>A([`draft`,`submitted`,`in-review`,`approved`,`scheduled`,`in-progress`,`completed`,`failed`,`rolled-back`,`cancelled`])),WW=X(()=>T({level:A([`low`,`medium`,`high`,`critical`]).describe(`Impact level`),affectedSystems:w(v()).describe(`Affected systems`),affectedUsers:y().optional().describe(`Affected user count`),downtime:T({required:b().describe(`Downtime required`),durationMinutes:y().optional().describe(`Downtime duration`)}).optional().describe(`Downtime information`)})),GW=X(()=>T({description:v().describe(`Rollback description`),steps:w(T({order:y().describe(`Step order`),description:v().describe(`Step description`),estimatedMinutes:y().describe(`Estimated duration`)})).describe(`Rollback steps`),testProcedure:v().optional().describe(`Test procedure`)}));X(()=>T({id:v().describe(`Change request ID`),title:v().describe(`Change title`),description:v().describe(`Change description`),type:VW.describe(`Change type`),priority:HW.describe(`Change priority`),status:UW.describe(`Change status`),requestedBy:v().describe(`Requester user ID`),requestedAt:y().describe(`Request timestamp`),impact:WW.describe(`Impact assessment`),implementation:T({description:v().describe(`Implementation description`),steps:w(T({order:y().describe(`Step order`),description:v().describe(`Step description`),estimatedMinutes:y().describe(`Estimated duration`)})).describe(`Implementation steps`),testing:v().optional().describe(`Testing procedure`)}).describe(`Implementation plan`),rollbackPlan:GW.describe(`Rollback plan`),schedule:T({plannedStart:y().describe(`Planned start time`),plannedEnd:y().describe(`Planned end time`),actualStart:y().optional().describe(`Actual start time`),actualEnd:y().optional().describe(`Actual end time`)}).optional().describe(`Schedule`),securityImpact:T({assessed:b().describe(`Whether security impact has been assessed`),riskLevel:A([`none`,`low`,`medium`,`high`,`critical`]).optional().describe(`Security risk level`),affectedDataClassifications:w(PW).optional().describe(`Affected data classifications`),requiresSecurityApproval:b().default(!1).describe(`Whether security team approval is required`),reviewedBy:v().optional().describe(`Security reviewer user ID`),reviewedAt:y().optional().describe(`Security review timestamp`),reviewNotes:v().optional().describe(`Security review notes or conditions`)}).optional().describe(`Security impact assessment per ISO 27001:2022 A.8.32`),approval:T({required:b().describe(`Approval required`),approvers:w(T({userId:v().describe(`Approver user ID`),approvedAt:y().optional().describe(`Approval timestamp`),comments:v().optional().describe(`Approver comments`)})).describe(`Approvers`)}).optional().describe(`Approval workflow`),attachments:w(T({name:v().describe(`Attachment name`),url:v().url().describe(`Attachment URL`)})).optional().describe(`Attachments`),metadata:k(v(),S()).optional().describe(`Custom metadata key-value pairs for extensibility`)}));var KW=A(`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(`.`)),qW=X(()=>T({label:v().describe(`Display label (human-readable, any case allowed)`),value:hU.describe(`Stored value (lowercase machine identifier)`),color:v().optional().describe(`Color code for badges/charts`),default:b().optional().describe(`Is default option`)}));X(()=>T({latitude:y().min(-90).max(90).describe(`Latitude coordinate`),longitude:y().min(-180).max(180).describe(`Longitude coordinate`),altitude:y().optional().describe(`Altitude in meters`),accuracy:y().optional().describe(`Accuracy in meters`)}));var JW=X(()=>T({precision:y().int().min(0).max(10).default(2).describe(`Decimal precision (default: 2)`),currencyMode:A([`dynamic`,`fixed`]).default(`dynamic`).describe(`Currency mode: dynamic (user selectable) or fixed (single currency)`),defaultCurrency:v().length(3).default(`CNY`).describe(`Default or fixed currency code (ISO 4217, e.g., USD, CNY, EUR)`)}));X(()=>T({value:y().describe(`Monetary amount`),currency:v().length(3).describe(`Currency code (ISO 4217)`)})),X(()=>T({street:v().optional().describe(`Street address`),city:v().optional().describe(`City name`),state:v().optional().describe(`State/Province`),postalCode:v().optional().describe(`Postal/ZIP code`),country:v().optional().describe(`Country name or code`),countryCode:v().optional().describe(`ISO country code (e.g., US, GB)`),formatted:v().optional().describe(`Formatted address string`)}));var YW=X(()=>T({dimensions:y().int().min(1).max(1e4).describe(`Vector dimensionality (e.g., 1536 for OpenAI embeddings)`),distanceMetric:A([`cosine`,`euclidean`,`dotProduct`,`manhattan`]).default(`cosine`).describe(`Distance/similarity metric for vector search`),normalized:b().default(!1).describe(`Whether vectors are normalized (unit length)`),indexed:b().default(!0).describe(`Whether to create a vector index for fast similarity search`),indexType:A([`hnsw`,`ivfflat`,`flat`]).optional().describe(`Vector index algorithm (HNSW for high accuracy, IVFFlat for large datasets)`)})),XW=X(()=>T({minSize:y().min(0).optional().describe(`Minimum file size in bytes`),maxSize:y().min(1).optional().describe(`Maximum file size in bytes (e.g., 10485760 = 10MB)`),allowedTypes:w(v()).optional().describe(`Allowed file extensions (e.g., [".pdf", ".docx", ".jpg"])`),blockedTypes:w(v()).optional().describe(`Blocked file extensions (e.g., [".exe", ".bat", ".sh"])`),allowedMimeTypes:w(v()).optional().describe(`Allowed MIME types (e.g., ["image/jpeg", "application/pdf"])`),blockedMimeTypes:w(v()).optional().describe(`Blocked MIME types`),virusScan:b().default(!1).describe(`Enable virus scanning for uploaded files`),virusScanProvider:A([`clamav`,`virustotal`,`metadefender`,`custom`]).optional().describe(`Virus scanning service provider`),virusScanOnUpload:b().default(!0).describe(`Scan files immediately on upload`),quarantineOnThreat:b().default(!0).describe(`Quarantine files if threat detected`),storageProvider:v().optional().describe(`Object storage provider name (references ObjectStorageConfig)`),storageBucket:v().optional().describe(`Target bucket name`),storagePrefix:v().optional().describe(`Storage path prefix (e.g., "uploads/documents/")`),imageValidation:T({minWidth:y().min(1).optional().describe(`Minimum image width in pixels`),maxWidth:y().min(1).optional().describe(`Maximum image width in pixels`),minHeight:y().min(1).optional().describe(`Minimum image height in pixels`),maxHeight:y().min(1).optional().describe(`Maximum image height in pixels`),aspectRatio:v().optional().describe(`Required aspect ratio (e.g., "16:9", "1:1")`),generateThumbnails:b().default(!1).describe(`Auto-generate thumbnails`),thumbnailSizes:w(T({name:v().describe(`Thumbnail variant name (e.g., "small", "medium", "large")`),width:y().min(1).describe(`Thumbnail width in pixels`),height:y().min(1).describe(`Thumbnail height in pixels`),crop:b().default(!1).describe(`Crop to exact dimensions`)})).optional().describe(`Thumbnail size configurations`),preserveMetadata:b().default(!1).describe(`Preserve EXIF metadata`),autoRotate:b().default(!0).describe(`Auto-rotate based on EXIF orientation`)}).optional().describe(`Image-specific validation rules`),allowMultiple:b().default(!1).describe(`Allow multiple file uploads (overrides field.multiple)`),allowReplace:b().default(!0).describe(`Allow replacing existing files`),allowDelete:b().default(!0).describe(`Allow deleting uploaded files`),requireUpload:b().default(!1).describe(`Require at least one file when field is required`),extractMetadata:b().default(!0).describe(`Extract file metadata (name, size, type, etc.)`),extractText:b().default(!1).describe(`Extract text content from documents (OCR/parsing)`),versioningEnabled:b().default(!1).describe(`Keep previous versions of replaced files`),maxVersions:y().min(1).optional().describe(`Maximum number of versions to retain`),publicRead:b().default(!1).describe(`Allow public read access to uploaded files`),presignedUrlExpiry:y().min(60).max(604800).default(3600).describe(`Presigned URL expiration in seconds (default: 1 hour)`)}).refine(e=>!(e.minSize!==void 0&&e.maxSize!==void 0&&e.minSize>e.maxSize),{message:`minSize must be less than or equal to maxSize`}).refine(e=>!(e.virusScanProvider!==void 0&&e.virusScan!==!0),{message:`virusScanProvider requires virusScan to be enabled`}));X(()=>T({uniqueness:b().default(!1).describe(`Enforce unique values across all records`),completeness:y().min(0).max(1).default(0).describe(`Minimum ratio of non-null values (0-1, default: 0 = no requirement)`),accuracy:T({source:v().describe(`Reference data source for validation (e.g., "api.verify.com", "master_data")`),threshold:y().min(0).max(1).describe(`Minimum accuracy threshold (0-1, e.g., 0.95 = 95% match required)`)}).optional().describe(`Accuracy validation configuration`)})),X(()=>T({enabled:b().describe(`Enable caching for computed field results`),ttl:y().min(0).describe(`Cache TTL in seconds (0 = no expiration)`),invalidateOn:w(v()).describe(`Field paths that invalidate cache (e.g., ["inventory.quantity", "pricing.base_price"])`)}));var ZW=X(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Machine name (snake_case)`).optional(),label:v().optional().describe(`Human readable label`),type:KW.describe(`Field Data Type`),description:v().optional().describe(`Tooltip/Help text`),format:v().optional().describe(`Format string (e.g. email, phone)`),columnName:v().optional().describe(`Physical column name in the target datasource. Defaults to the field key when not set.`),required:b().default(!1).describe(`Is required`),searchable:b().default(!1).describe(`Is searchable`),multiple:b().default(!1).describe(`Allow multiple values (Stores as Array/JSON). Applicable for select, lookup, file, image.`),unique:b().default(!1).describe(`Is unique constraint`),defaultValue:S().optional().describe(`Default value`),maxLength:y().optional().describe(`Max character length`),minLength:y().optional().describe(`Min character length`),precision:y().optional().describe(`Total digits`),scale:y().optional().describe(`Decimal places`),min:y().optional().describe(`Minimum value`),max:y().optional().describe(`Maximum value`),options:w(qW).optional().describe(`Static options for select/multiselect`),reference:v().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.`),referenceFilters:w(v()).optional().describe(`Filters applied to lookup dialogs (e.g. "active = true")`),deleteBehavior:A([`set_null`,`cascade`,`restrict`]).optional().default(`set_null`).describe(`What happens if referenced record is deleted`),inlineEdit:E([b(),A([`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:v().optional().describe(`Title for the inline master-detail grid`),inlineColumns:w(x()).optional().describe(`Explicit columns for the inline grid (derived from the child object when omitted)`),inlineAmountField:v().optional().describe(`Numeric child field summed for the inline grid total`),relatedList:b().optional().describe(`Show this child collection as a related list on the parent's detail page (read-side mirror of inlineEdit). Defaults to shown for master_detail/lookup; set false to suppress.`),relatedListTitle:v().optional().describe(`Title for the detail-page related list`),relatedListColumns:w(x()).optional().describe(`Explicit columns for the detail-page related list (derived from the child object when omitted)`),displayField:v().optional().describe(`Field shown as each candidate's label in the picker/popover (defaults to the referenced object's name/title).`),descriptionField:v().optional().describe(`Secondary field shown under the label in the quick-select popover.`),lookupColumns:w(E([v(),T({field:v(),label:v().optional(),width:v().optional(),type:v().optional()})])).optional().describe(`Explicit columns for the record-picker table; auto-derived from the referenced object when omitted.`),lookupPageSize:y().int().positive().optional().describe(`Rows per page in the record-picker dialog (default 10).`),lookupFilters:w(T({field:v(),operator:A([`eq`,`ne`,`gt`,`lt`,`gte`,`lte`,`contains`,`in`,`notIn`]),value:x()})).optional().describe(`Base filters restricting which records are selectable (e.g. only active). Structured, picker-honoured form of referenceFilters.`),dependsOn:w(E([v(),T({field:v(),param:v().optional()})])).optional().describe(`Dependent lookup: restrict candidates by the value of other field(s) on the same record. String = same local/remote key; {field,param} when the remote filter key differs.`),allowCreate:b().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:JH.optional().describe("Formula expression (CEL). e.g. F`record.amount * 0.1`"),returnType:A([`number`,`text`,`boolean`,`date`]).optional().describe(`Inferred value type of a formula field (number/text/boolean/date)`),summaryOperations:T({object:v().describe(`Source child object name for roll-up`),field:v().describe(`Field on child object to aggregate (ignored for count)`),function:A([`count`,`sum`,`min`,`max`,`avg`]).describe(`Aggregation function to apply`),relationshipField:v().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.`)}).optional().describe(`Roll-up summary definition. The engine recomputes the value when child records are inserted/updated/deleted.`),language:v().optional().describe(`Programming language for syntax highlighting (e.g., javascript, python, sql)`),maxRating:y().optional().describe(`Maximum rating value (default: 5)`),step:y().optional().describe(`Step increment for slider (default: 1)`),currencyConfig:JW.optional().describe(`Configuration for currency field type`),dimensions:y().int().min(1).max(1e4).optional().describe(`Vector dimensionality (e.g., 1536 for OpenAI embeddings)`),vectorConfig:YW.optional().describe(`Configuration for vector field type (AI/ML embeddings)`),fileAttachmentConfig:XW.optional().describe(`Configuration for file and attachment field types`),trackHistory:b().optional().describe(`Render this field's value changes as human-readable entries on the record activity timeline (ADR-0052 §5b). Opt-in per field.`),dependencies:w(v()).optional().describe(`Array of field names that this field depends on (for formulas, visibility rules, etc.)`),group:v().optional().describe(`Field group name for organizing fields in forms and layouts (e.g., "contact_info", "billing", "system")`),visibleWhen:JH.optional().describe("Predicate (CEL) — field is shown only when TRUE (else hidden). e.g. P`record.type == 'invoice'`"),readonlyWhen:JH.optional().describe("Predicate (CEL) — field is read-only when TRUE. e.g. P`record.status == 'paid'`"),requiredWhen:JH.optional().describe("Predicate (CEL) — field is required when TRUE. Canonical name for `conditionalRequired`."),conditionalRequired:JH.optional().describe("Predicate (CEL) — field is required when TRUE. Alias of `requiredWhen`."),hidden:b().default(!1).describe(`Hidden from default UI`),readonly:b().default(!1).describe(`Read-only in UI`),requiredPermissions:w(v()).optional().describe(`[ADR-0066 D3] Capabilities required to read/edit this field (mask on read, deny on write; AND-gate).`),system:b().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:b().optional().default(!0).describe(`Whether field is sortable in list views`),inlineHelpText:v().optional().describe(`Help text displayed below the field in forms`),caseSensitive:b().optional().describe(`Whether text comparisons are case-sensitive`),autonumberFormat:v().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).`),index:b().default(!1).describe(`Create standard database index`),externalId:b().default(!1).describe(`Is external ID for upsert operations`)})),QW=T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Unique rule name (snake_case)`),label:v().optional().describe(`Human-readable label for the rule listing`),description:v().optional().describe(`Administrative notes explaining the business reason`),active:b().default(!0),events:w(A([`insert`,`update`,`delete`])).default([`insert`,`update`]).describe(`Validation contexts`),priority:y().int().min(0).max(9999).default(100).describe(`Execution priority (lower runs first, default: 100)`),tags:w(v()).optional().describe(`Categorization tags (e.g., "compliance", "billing")`),severity:A([`error`,`warning`,`info`]).default(`error`),message:v().describe(`Error message to display to the user`)}),$W=X(()=>QW.extend({type:j(`script`),condition:JH.describe("Predicate (CEL). If TRUE, validation fails. e.g. P`record.amount < 0`")})),eG=X(()=>QW.extend({type:j(`state_machine`),field:v().describe(`State field (e.g. status)`),transitions:k(v(),w(v())).describe(`Map of { OldState: [AllowedNewStates] }`)})),tG=X(()=>QW.extend({type:j(`format`),field:v(),regex:v().optional(),format:A([`email`,`url`,`phone`,`json`]).optional()})),nG=X(()=>QW.extend({type:j(`cross_field`),condition:JH.describe("Predicate (CEL) comparing fields. e.g. P`record.end_date > record.start_date`"),fields:w(v()).describe(`Fields involved in the validation`)})),rG=X(()=>QW.extend({type:j(`json_schema`),field:v().describe(`JSON field to validate`),schema:k(v(),S()).describe(`JSON Schema object definition`)})),iG=M(()=>D(`type`,[$W,eG,tG,nG,rG,aG])),aG=X(()=>QW.extend({type:j(`conditional`),when:JH.describe("Predicate (CEL). e.g. P`record.type == 'enterprise'`"),then:iG.describe(`Validation rule to apply when condition is true`),otherwise:iG.optional().describe(`Validation rule to apply when condition is false`)}));X(()=>T({key:v().describe(`Translation key (e.g., "views.task_list.label")`),defaultValue:v().optional().describe(`Fallback value when translation key is not found`),params:k(v(),E([v(),y(),b()])).optional().describe(`Interpolation parameters (e.g., { count: 5 })`)}));var Q=X(()=>v().describe(`Display label (plain string; i18n keys are auto-generated by the framework)`)),$=X(()=>T({ariaLabel:Q.optional().describe(`Accessible label for screen readers (WAI-ARIA aria-label)`),ariaDescribedBy:v().optional().describe(`ID of element providing additional description (WAI-ARIA aria-describedby)`),role:v().optional().describe(`WAI-ARIA role attribute (e.g., "dialog", "navigation", "alert")`)}).describe(`ARIA accessibility attributes`));X(()=>T({key:v().describe(`Translation key`),zero:v().optional().describe(`Zero form (e.g., "No items")`),one:v().optional().describe(`Singular form (e.g., "{count} item")`),two:v().optional().describe(`Dual form (e.g., "{count} items" for exactly 2)`),few:v().optional().describe(`Few form (e.g., for 2-4 in some languages)`),many:v().optional().describe(`Many form (e.g., for 5+ in some languages)`),other:v().describe(`Default plural form (e.g., "{count} items")`)}).describe(`ICU plural rules for a translation key`));var oG=X(()=>T({style:A([`decimal`,`currency`,`percent`,`unit`]).default(`decimal`).describe(`Number formatting style`),currency:v().optional().describe(`ISO 4217 currency code (e.g., "USD", "EUR")`),unit:v().optional().describe(`Unit for unit formatting (e.g., "kilometer", "liter")`),minimumFractionDigits:y().optional().describe(`Minimum number of fraction digits`),maximumFractionDigits:y().optional().describe(`Maximum number of fraction digits`),useGrouping:b().optional().describe(`Whether to use grouping separators (e.g., 1,000)`)}).describe(`Number formatting rules`)),sG=X(()=>T({dateStyle:A([`full`,`long`,`medium`,`short`]).optional().describe(`Date display style`),timeStyle:A([`full`,`long`,`medium`,`short`]).optional().describe(`Time display style`),timeZone:v().optional().describe(`IANA time zone (e.g., "America/New_York")`),hour12:b().optional().describe(`Use 12-hour format`)}).describe(`Date/time formatting rules`));X(()=>T({code:v().describe(`BCP 47 language code (e.g., "en-US", "zh-CN")`),fallbackChain:w(v()).optional().describe(`Fallback language codes in priority order (e.g., ["zh-TW", "en"])`),direction:A([`ltr`,`rtl`]).default(`ltr`).describe(`Text direction: left-to-right or right-to-left`),numberFormat:oG.optional().describe(`Default number formatting rules`),dateFormat:sG.optional().describe(`Default date/time formatting rules`)}).describe(`Locale configuration`));var cG=A([`api.read`,`api.write`,`api.transaction`,`crypto.uuid`,`crypto.hash`,`log`]),lG=D(`language`,[T({language:j(`expression`),source:v().min(1).describe(`Formula expression source`)}).describe(`L1 expression body — pure formula, no IO`),T({language:j(`js`),source:v().min(1).describe(`Function body source`),capabilities:w(cG).default([]).describe(`Granted capability tokens`),timeoutMs:y().int().positive().max(3e4).optional().describe(`Per-invocation timeout (ms)`),memoryMb:y().int().positive().max(256).optional().describe(`Per-invocation memory cap (MB)`)}).describe(`L2 sandboxed JS body — runs inside an isolated VM with declared capabilities`)]).describe(`Hook/Action body — expression (L1) or sandboxed JS (L2)`),uG=X(()=>T({name:v().optional(),field:Z.optional(),objectOverride:Z.optional(),label:Q.optional(),type:KW.optional(),required:b().optional().default(!1),options:w(T({label:Q,value:v()})).optional(),placeholder:v().optional(),helpText:v().optional(),defaultValue:S().optional(),defaultFromRow:b().optional()}).refine(e=>!!e.name||!!e.field,{message:`ActionParam requires either "name" or "field"`})),dG=A([`script`,`url`,`modal`,`flow`,`api`,`form`]),fG=new Set(dG.options.filter(e=>e!==`script`)),pG=A([`list_toolbar`,`list_item`,`record_header`,`record_more`,`record_related`,`record_section`,`global_nav`]),mG=A([`data`,`action`,`flow`,`integration`,`vector_search`,`analytics`,`utility`]),hG=T({exposed:b().default(!1).describe("Expose this action to AI agents. Requires `description` when true."),description:v().min(40).optional().describe(`LLM-facing description (≥40 chars). Required when exposed.`),category:mG.optional().describe(`Tool category override (defaults to "action").`),paramHints:k(v(),T({description:v().optional(),enum:w(E([v(),y()])).optional(),examples:w(S()).optional()})).optional().describe(`Per-parameter AI hints keyed by param name.`),outputSchema:k(v(),S()).optional().describe(`JSON Schema for the action return value.`),requiresConfirmation:b().optional().describe(`Override HITL confirmation for AI invocations.`)}),gG=X(()=>T({name:Z.describe(`Machine name (lowercase snake_case)`),label:Q.describe(`Display label`),objectName:v().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:v().optional().describe(`Icon name`),locations:w(pG).optional().describe(`Locations where this action is visible`),component:A([`action:button`,`action:icon`,`action:menu`,`action:group`]).optional().describe(`Visual component override`),type:dG.default(`script`).describe(`Action functionality type`),target:v().optional().describe("URL, Script Name, Flow ID, or API Endpoint. Supports ${param.X} and ${ctx.X} interpolation."),body:lG.optional().describe("Action body — expression (L1) or sandboxed JS (L2). Only used when type is `script`."),execute:v().optional().describe(`@deprecated — Use target instead. Auto-migrated to target during parsing.`),params:w(uG).optional().describe(`Input parameters required from user`),variant:A([`primary`,`secondary`,`danger`,`ghost`,`link`]).optional().describe(`Button visual variant for styling (primary = highlighted, danger = destructive, ghost = transparent)`),confirmText:Q.optional().describe(`Confirmation message before execution`),successMessage:Q.optional().describe(`Success message to show after execution`),errorMessage:Q.optional().describe(`Error message to show when the action fails (overrides the raw error).`),refreshAfter:b().default(!1).describe(`Refresh view after execution`),undoable:b().optional().describe(`Offer an Undo affordance after this single-record update action succeeds.`),resultDialog:T({title:Q.optional(),description:Q.optional(),acknowledge:Q.optional().describe(`Acknowledge button label, e.g. "I have saved this"`),format:A([`qrcode`,`code-list`,`secret`,`text`,`json`]).optional().describe(`Default format for fields without their own format. Defaults to json when omitted.`),fields:w(T({path:v().describe(`Dot path into result.data (e.g. "totpURI", "client.client_secret").`),label:Q.optional(),format:A([`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:JH.optional().describe(`Visibility predicate (CEL).`),disabled:E([b(),JH]).optional().describe(`Boolean or predicate (CEL) — action is disabled when TRUE.`),requiredPermissions:w(v()).optional().describe(`[ADR-0066 D4] Capabilities required to invoke this action (server-enforced 403 + UI hide/disable).`),shortcut:v().optional().describe(`Keyboard shortcut to trigger this action (e.g., "Ctrl+S")`),bulkEnabled:b().optional().describe(`Whether this action can be applied to multiple selected records`),ai:hG.optional().describe(`AI exposure (opt-in). Set ai.exposed=true + ai.description to make this callable by agents.`),recordIdParam:v().optional().describe(`Body key to inject the row id into when running from a list_item context.`),recordIdField:v().optional().describe(`Row field whose value seeds recordIdParam. Defaults to "id".`),bodyShape:E([j(`flat`),T({wrap:v()})]).optional().describe(`Body wrapping: flat (default) or { wrap: key } to nest user-collected params under a key.`),method:A([`POST`,`PATCH`,`PUT`,`DELETE`]).optional().describe(`HTTP method for type:"api" actions. Defaults to POST.`),bodyExtra:k(v(),S()).optional().describe(`Constant body fields merged into the API request (applied last; overrides user params).`),mode:A([`create`,`edit`,`delete`,`custom`]).optional().describe(`Semantic mode of the action.`),opensInNewTab:b().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:v().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.`),timeout:y().optional().describe(`Maximum execution time in milliseconds for the action`),aria:$.optional().describe(`ARIA accessibility attributes`)}).transform(e=>e.execute&&!e.target?{...e,target:e.execute}:e).refine(e=>!(fG.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.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`]})),_G=A([`none`,`no-overlay`,`no-delete`,`full`]),vG=A([`artifact`,`package`,`env-forced`]),yG=A([`package`,`org`,`env-forced`]),bG={_lock:_G.optional().describe(`Item-level lock — controls overlay & delete (ADR-0010).`),_lockReason:v().max(500).optional().describe(`Human-readable reason shown when a write is refused by _lock.`),_lockSource:vG.optional().describe(`Layer that set _lock (artifact | package | env-forced).`),_provenance:yG.optional().describe(`Origin of the item (package | org | env-forced).`),_packageId:v().optional().describe(`Owning package machine id.`),_packageVersion:v().optional().describe(`Owning package version.`),_lockDocsUrl:v().optional().describe(`Optional documentation link surfaced next to _lockReason.`)},xG=T({lock:_G.describe(`Lock policy — none | no-overlay | no-delete | full.`),reason:v().min(1).max(500).describe(`User-visible reason shown when the lock blocks an action.`),docsUrl:v().url().optional().describe(`Optional URL the Studio banner links to for more context.`)}).strict(),SG=X(()=>T({enabled:b().default(!1).describe(`Enable public sharing`),publicLink:v().optional().describe(`Generated public share URL`),password:v().optional().describe(`Password required to access shared link`),allowedDomains:w(v()).optional().describe(`Restrict access to specific email domains (e.g. ["example.com"])`),expiresAt:v().optional().describe(`Expiration date/time in ISO 8601 format`),allowAnonymous:b().optional().default(!1).describe(`Allow access without authentication`)})),CG=X(()=>T({enabled:b().default(!1).describe(`Enable iframe embedding`),allowedOrigins:w(v()).optional().describe(`Allowed iframe parent origins (e.g. ["https://example.com"])`),width:v().optional().default(`100%`).describe(`Embed width (CSS value)`),height:v().optional().default(`600px`).describe(`Embed height (CSS value)`),showHeader:b().optional().default(!0).describe(`Show interface header in embed`),showNavigation:b().optional().default(!1).describe(`Show navigation in embed`),responsive:b().optional().default(!0).describe(`Enable responsive resizing`)})),wG=A([`xs`,`sm`,`md`,`lg`,`xl`,`2xl`]),TG=X(()=>T({xs:y().min(1).max(12).optional(),sm:y().min(1).max(12).optional(),md:y().min(1).max(12).optional(),lg:y().min(1).max(12).optional(),xl:y().min(1).max(12).optional(),"2xl":y().min(1).max(12).optional()}).describe(`Grid columns per breakpoint (1-12)`)),EG=X(()=>T({xs:y().optional(),sm:y().optional(),md:y().optional(),lg:y().optional(),xl:y().optional(),"2xl":y().optional()}).describe(`Display order per breakpoint`)),DG=X(()=>T({breakpoint:wG.optional().describe(`Minimum breakpoint for visibility`),hiddenOn:w(wG).optional().describe(`Hide on these breakpoints`),columns:TG.optional().describe(`Grid columns per breakpoint`),order:EG.optional().describe(`Display order per breakpoint`)}).describe(`Responsive layout configuration`)),OG=X(()=>k(v(),E([v(),y()])).describe(`CSS property → value map (camelCase keys; design tokens encouraged)`)),kG=X(()=>T({large:OG.optional().describe(`Unconditional base (desktop-first)`),medium:OG.optional().describe(`Applied at ≤ medium breakpoint`),small:OG.optional().describe(`Applied at ≤ small breakpoint`),xsmall:OG.optional().describe(`Applied at ≤ xsmall breakpoint`)}).describe(`Per-breakpoint scoped style maps (ADR-0065)`)),AG=X(()=>T({lazyLoad:b().optional().describe(`Enable lazy loading (defer rendering until visible)`),virtualScroll:T({enabled:b().default(!1).describe(`Enable virtual scrolling`),itemHeight:y().optional().describe(`Fixed item height in pixels (for estimation)`),overscan:y().optional().describe(`Number of extra items to render outside viewport`)}).optional().describe(`Virtual scrolling configuration`),cacheStrategy:A([`none`,`cache-first`,`network-first`,`stale-while-revalidate`]).optional().describe(`Client-side data caching strategy`),prefetch:b().optional().describe(`Prefetch data before component is visible`),pageSize:y().optional().describe(`Number of items per page for pagination`),debounceMs:y().optional().describe(`Debounce interval for user interactions in milliseconds`)}).describe(`Performance optimization configuration`)),jG=X(()=>D(`provider`,[T({provider:j(`object`),object:v().describe(`Target object name`)}),T({provider:j(`api`),read:PU.optional().describe(`Configuration for fetching data`),write:PU.optional().describe(`Configuration for submitting data (for forms/editable tables)`)}),T({provider:j(`value`),items:w(S()).describe(`Static data array`)}),T({provider:j(`schema`),schemaId:v().describe(`Schema identifier — typically the metadata type name`),schema:k(v(),S()).optional().describe(`Inline JSON Schema (Draft 2020-12). Optional when schemaId is resolvable.`)})])),MG=X(()=>T({field:v().describe(`Field name to filter on`),operator:v().describe(`Filter operator (e.g. equals, not_equals, contains, this_quarter)`),value:E([v(),y(),b(),ul(),w(E([v(),y()]))]).optional().describe(`Filter value`)}).describe(`View filter rule`)),NG=X(()=>A([`none`,`count`,`count_empty`,`count_filled`,`count_unique`,`percent_empty`,`percent_filled`,`sum`,`avg`,`min`,`max`]).describe(`Aggregation function for column footer summary`)),PG=X(()=>T({field:v().describe(`Field name (snake_case)`),label:Q.optional().describe(`Display label override`),width:y().positive().optional().describe(`Column width in pixels`),align:A([`left`,`center`,`right`]).optional().describe(`Text alignment`),hidden:b().optional().describe(`Hide column by default`),sortable:b().optional().describe(`Allow sorting by this column`),resizable:b().optional().describe(`Allow resizing this column`),wrap:b().optional().describe(`Allow text wrapping`),type:v().optional().describe(`Renderer type override (e.g., "currency", "date")`),pinned:A([`left`,`right`]).optional().describe(`Pin/freeze column to left or right side`),summary:NG.optional().describe(`Footer aggregation function for this column`),link:b().optional().describe(`Functions as the primary navigation link (triggers View navigation)`),action:v().optional().describe(`Registered Action ID to execute when clicked`)})),FG=X(()=>T({type:A([`none`,`single`,`multiple`]).default(`none`).describe(`Selection mode`)})),IG=X(()=>T({pageSize:y().int().positive().default(25).describe(`Number of records per page`),pageSizeOptions:w(y().int().positive()).optional().describe(`Available page size options`)})),LG=X(()=>A([`compact`,`short`,`medium`,`tall`,`extra_tall`]).describe(`Row height / density setting for list view`)),RG=X(()=>T({field:v().describe(`Field name to group by`),order:A([`asc`,`desc`]).default(`asc`).describe(`Group sort order`),collapsed:b().default(!1).describe(`Collapse groups by default`)})),zG=X(()=>T({fields:w(RG).min(1).describe(`Fields to group by (supports up to 3 levels)`)}).describe(`Record grouping configuration`)),BG=X(()=>T({coverField:v().optional().describe(`Attachment/image field to display as card cover`),coverFit:A([`cover`,`contain`]).default(`cover`).describe(`Image fit mode for card cover`),cardSize:A([`small`,`medium`,`large`]).default(`medium`).describe(`Card size in gallery view`),titleField:v().optional().describe(`Field to display as card title`),visibleFields:w(v()).optional().describe(`Fields to display on card body`)}).describe(`Gallery/card view configuration`)),VG=X(()=>T({startDateField:v().describe(`Field for timeline item start date`),endDateField:v().optional().describe(`Field for timeline item end date`),titleField:v().describe(`Field to display as timeline item title`),groupByField:v().optional().describe(`Field to group timeline rows`),colorField:v().optional().describe(`Field to determine item color`),scale:A([`hour`,`day`,`week`,`month`,`quarter`,`year`]).default(`week`).describe(`Default timeline scale`)}).describe(`Timeline view configuration`)),HG=X(()=>T({type:A([`personal`,`collaborative`]).default(`collaborative`).describe(`View ownership type`),lockedBy:v().optional().describe(`User who locked the view configuration`)}).describe(`View sharing and access configuration`)),UG=X(()=>T({field:v().describe(`Field to derive color from (typically a select/status field)`),colors:k(v(),v()).optional().describe(`Map of field value to color (hex/token)`)}).describe(`Row color configuration based on field values`)),WG=X(()=>A([`grid`,`kanban`,`gallery`,`calendar`,`timeline`,`gantt`,`map`,`chart`,`tree`]).describe(`Visualization type that users can switch to`)),GG=X(()=>T({sort:b().default(!0).describe(`Allow users to sort records`),search:b().default(!0).describe(`Allow users to search records`),filter:b().default(!0).describe(`Allow users to filter records`),rowHeight:b().default(!0).describe(`Allow users to toggle row height/density`),addRecordForm:b().default(!1).describe(`Add records through a form instead of inline`),buttons:w(v()).optional().describe(`Custom action button IDs to show in the toolbar`)}).describe(`User action toggles for the view toolbar`)),KG=X(()=>T({showDescription:b().default(!0).describe(`Show the view description text`),allowedVisualizations:w(WG).optional().describe(`Whitelist of visualization types users can switch between (e.g. ["grid", "gallery", "kanban"])`)}).describe(`Appearance and visualization configuration`)),qG=X(()=>T({name:Z.describe(`Tab identifier (snake_case)`),label:Q.optional().describe(`Display label`),icon:v().optional().describe(`Tab icon name`),view:v().optional().describe(`Referenced list view name from listViews`),filter:w(MG).optional().describe(`Tab-specific filter criteria`),order:y().int().min(0).optional().describe(`Tab display order`),pinned:b().default(!1).describe(`Pin tab (cannot be removed by users)`),isDefault:b().default(!1).describe(`Set as the default active tab`),visible:b().default(!0).describe(`Tab visibility`)}).describe(`Tab configuration for multi-tab view interface`)),JG=X(()=>T({field:v().describe(`Field name on the source object (must exist — checked by reference diagnostics)`),label:Q.optional().describe(`Display label override (defaults to the field label)`),type:A([`select`,`multi-select`,`boolean`,`date-range`,`text`]).optional().describe(`Filter control type. Omit to infer from the field definition`),options:w(T({value:E([v(),y(),b()]).describe(`Option value`),label:Q.describe(`Option label`),color:v().optional().describe(`Option color token/hex`)})).optional().describe(`Static options. Omit to derive from the field definition (select options / lookup records)`),showCount:b().optional().describe(`Show per-option record counts`),defaultValues:w(E([v(),y(),b()])).optional().describe(`Pre-selected values when the view loads`)}).describe(`Quick-filter field configuration`)),YG=X(()=>T({element:A([`dropdown`,`tabs`,`toggle`]).default(`dropdown`).describe(`Filter control style: "dropdown" (per-field value selectors) or "tabs" (named presets). "toggle" is deprecated.`),fields:w(JG).optional().describe(`Fields exposed as quick filters (dropdown/toggle elements)`),tabs:w(qG).optional().describe(`Named filter presets rendered as tabs (tabs element). Reuses ViewTabSchema`),showAllRecords:b().optional().describe(`Show an "All records" tab before the presets (tabs element)`)}).describe(`End-user quick-filter configuration (Airtable "User filters" parity)`)),XG=X(()=>T({enabled:b().default(!0).describe(`Show the add record entry point`),position:A([`top`,`bottom`,`both`]).default(`bottom`).describe(`Position of the add record button`),mode:A([`inline`,`form`,`modal`]).default(`inline`).describe(`How to add a new record`),formView:v().optional().describe(`Named form view to use when mode is "form" or "modal"`)}).describe(`Add record entry point configuration`)),ZG=X(()=>T({groupByField:v().describe(`Field to group columns by (usually status/select)`),summarizeField:v().optional().describe(`Field to sum at top of column (e.g. amount)`),columns:w(v()).describe(`Fields to show on cards`)})),QG=X(()=>T({chartType:A([`bar`,`line`,`pie`,`area`,`scatter`]).default(`bar`).describe(`Chart visualisation type`),dataset:Z.describe(`Dataset name to bind (ADR-0021)`),dimensions:w(v()).optional().describe(`Dimension names — X/group/split`),values:w(v()).min(1).describe(`Measure names — Y (at least one)`)}).describe(`List chart view configuration`)),$G=X(()=>T({startDateField:v(),endDateField:v().optional(),titleField:v(),colorField:v().optional()})),eK=X(()=>T({field:v().describe(`Record field / dot-path the dimension filters on`),label:v().optional().describe(`Trigger label (falls back to the field label)`),options:w(E([v(),T({value:E([v(),y()]),label:v().optional()})])).optional().describe(`Explicit option override for fixed enums`)})),tK=X(()=>T({startDateField:v(),endDateField:v(),titleField:v(),progressField:v().optional(),dependenciesField:v().optional(),colorField:v().optional().describe(`Field that drives the bar color`),parentField:v().optional().describe(`Field holding the parent task id (builds the summary → step tree)`),typeField:v().optional().describe(`Field whose value maps to task/summary/milestone`),baselineStartField:v().optional().describe(`Baseline (planned) start field`),baselineEndField:v().optional().describe(`Baseline (planned) end field`),groupByField:v().optional().describe(`Field to group leaf tasks by (synthesized summary rows)`),resourceView:b().optional().describe(`Render a per-resource workload histogram instead of the timeline`),assigneeField:v().optional().describe(`Resource field to bucket load by (resource view)`),effortField:v().optional().describe(`Per-task load units (resource view; default 1)`),capacity:y().optional().describe(`Per-resource capacity ceiling; loads above this flag overload`),tooltipFields:w(E([v(),T({field:v(),label:v().optional()})])).optional().describe(`Fields to surface in the hover tooltip, in display order`),quickFilters:w(eK).optional().describe(`Multi-select filter dropdowns rendered above the chart`),autoZoomToFilter:b().optional().describe(`When true (default), filtering zooms the range to the filtered tasks`)}).passthrough()),nK=X(()=>T({parentField:v().optional().describe(`Single-parent pointer field (auto-detected from the object schema when omitted)`),labelField:v().optional().describe(`Field rendered indented in the first column (defaults to "name")`),fields:w(v()).optional().describe(`Additional fields rendered as flat columns alongside the label`),defaultExpandedDepth:y().int().min(0).optional().describe(`Initial expansion depth (0 = roots only; omit = expand all)`)}).passthrough()),rK=X(()=>A([`page`,`drawer`,`modal`,`split`,`popover`,`new_window`,`none`])),iK=X(()=>T({mode:rK.default(`page`),view:v().optional().describe(`Name of the form view to use for details (e.g. "summary_view", "edit_form")`),preventNavigation:b().default(!1).describe(`Disable standard navigation entirely`),openNewTab:b().default(!1).describe(`Force open in new tab (applies to page mode)`),width:E([v(),y()]).optional().describe(`Width of the drawer/modal (e.g. "600px", "50%")`)})),aK=X(()=>T({name:Z.optional().describe(`Internal view name (lowercase snake_case)`),label:Q.optional(),type:A([`grid`,`kanban`,`gallery`,`calendar`,`timeline`,`gantt`,`map`,`chart`,`tree`]).default(`grid`),data:jG.optional().describe(`Data source configuration (defaults to "object" provider)`),columns:E([w(v()),w(PG)]).describe(`Fields to display as columns`),filter:w(MG).optional().describe(`Filter criteria (JSON Rules)`),sort:E([v(),w(T({field:v(),order:A([`asc`,`desc`])}))]).optional(),searchableFields:w(v()).optional().describe(`Fields enabled for search`),filterableFields:w(v()).optional().describe(`Legacy shorthand for userFilters.fields — bare field names enabled for end-user filtering. Prefer userFilters`),userFilters:YG.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:b().optional().describe(`Enable column resizing`),striped:b().optional().describe(`Striped row styling`),bordered:b().optional().describe(`Show borders`),compactToolbar:b().optional().describe(`Collapse Group/Color/Density/Hide-fields into a single View settings popover`),selection:FG.optional().describe(`Row selection configuration`),navigation:iK.optional().describe(`Configuration for item click navigation (page, drawer, modal, etc.)`),pagination:IG.optional().describe(`Pagination configuration`),kanban:ZG.optional(),calendar:$G.optional(),gantt:tK.optional(),gallery:BG.optional(),timeline:VG.optional(),chart:QG.optional(),tree:nK.optional(),description:Q.optional().describe(`View description for documentation/tooltips`),sharing:HG.optional().describe(`View sharing and access configuration`),rowHeight:LG.optional().describe(`Row height / density setting`),grouping:zG.optional().describe(`Group records by one or more fields`),rowColor:UG.optional().describe(`Color rows based on field value`),hiddenFields:w(v()).optional().describe(`Fields to hide in this specific view`),fieldOrder:w(v()).optional().describe(`Explicit field display order for this view`),rowActions:w(v()).optional().describe(`Actions available for individual row items`),bulkActions:w(v()).optional().describe(`Actions available when multiple rows are selected`),bulkActionDefs:w(k(v(),x())).optional().describe(`Rich bulk action definitions (schema-driven, executed via BulkActionDialog)`),virtualScroll:b().optional().describe(`Enable virtual scrolling for large datasets`),conditionalFormatting:w(T({condition:JH.describe(`Predicate (CEL) to evaluate.`),style:k(v(),v()).describe(`CSS styles to apply when condition is true`)})).optional().describe(`Conditional formatting rules for list rows`),inlineEdit:b().optional().describe(`Allow inline editing of records directly in the list view`),exportOptions:w(A([`csv`,`xlsx`,`pdf`,`json`])).optional().describe(`Available export format options`),userActions:GG.optional().describe(`User action toggles for the view toolbar`),appearance:KG.optional().describe(`Appearance and visualization configuration`),tabs:w(qG).optional().describe(`Tab definitions for multi-tab view interface`),addRecord:XG.optional().describe(`Add record entry point configuration`),showRecordCount:b().optional().describe(`Show record count at the bottom of the list`),allowPrinting:b().optional().describe(`Allow users to print the view`),emptyState:T({title:Q.optional(),message:Q.optional(),icon:v().optional()}).optional().describe(`Empty state configuration when no records found`),aria:$.optional().describe(`ARIA accessibility attributes for the list view`),responsive:DG.optional().describe(`Responsive layout configuration`),performance:AG.optional().describe(`Performance optimization settings`)})),oK=X(()=>T({field:v().describe(`Field name (snake_case)`),type:KW.optional().describe(`Field type (auto-infers widget if omitted)`),options:w(qW).optional().describe(`Options for select/multiselect/radio/checkboxes fields`),reference:v().optional().describe(`Target object name for lookup/master_detail fields`),maxLength:y().optional().describe(`Maximum character length (for text/textarea/email/url/phone)`),minLength:y().optional().describe(`Minimum character length`),min:y().optional().describe(`Minimum value (for number/currency/percent/slider)`),max:y().optional().describe(`Maximum value`),precision:y().optional().describe(`Total digits (for number/currency)`),scale:y().optional().describe(`Decimal places`),multiple:b().optional().describe(`Allow multiple values (for select/lookup/file/image)`),label:Q.optional().describe(`Display label override`),placeholder:Q.optional().describe(`Placeholder text`),helpText:Q.optional().describe(`Help/hint text`),readonly:b().optional().describe(`Read-only override`),immutable:b().optional().describe(`Editable on create, locked once the record exists (e.g. machine names).`),required:b().optional().describe(`Required override`),hidden:b().optional().describe(`Hidden override`),colSpan:y().int().min(1).max(4).optional().describe(`Column span in grid layout (1-4)`),widget:v().optional().describe(`Custom widget/component name (overrides type-based inference)`),language:v().optional().describe(`Code editor language (for type=code)`),fields:w(M(()=>oK)).optional().describe(`Sub-fields for composite/repeater/record types`),keyField:T({field:v().default(`name`).describe(`Property name that holds the key inside each item (defaults to "name")`),label:Q.optional().describe(`Display label for the key column`),placeholder:Q.optional().describe(`Placeholder when entering a new key`),helpText:Q.optional().describe(`Help text under the key input`),regex:v().optional().describe(`JS regex source string the key must match (no flags)`),immutable:b().default(!0).describe(`If true, the key is read-only after creation`)}).optional().describe(`Key column config for record-typed fields`),dependsOn:v().optional().describe(`Parent field name for cascading`),visibleOn:JH.optional().describe(`Visibility predicate (CEL).`),disclosure:A([`inline`,`popover`]).optional().describe(`Composite rendering: inline bordered box (default) or a summary line + gear popover (progressive disclosure).`)})),sK=X(()=>T({name:v().optional().describe(`Stable section identifier for i18n lookup (snake_case)`),label:Q.optional(),description:v().optional().describe(`Optional description rendered under the section header.`),collapsible:b().default(!1),collapsed:b().default(!1),visibleOn:JH.optional().describe(`Visibility predicate (CEL). Hides the whole section when false.`),columns:E([A([`1`,`2`,`3`,`4`]),j(1),j(2),j(3),j(4)]).default(1).transform(e=>typeof e==`string`?parseInt(e):e),fields:w(E([v(),oK]))})),cK=X(()=>T({type:A([`simple`,`tabbed`,`wizard`,`split`,`drawer`,`modal`]).default(`simple`),data:jG.optional().describe(`Data source configuration (defaults to "object" provider)`),sections:w(sK).optional(),groups:w(sK).optional(),subforms:w(T({childObject:v().describe(`Child object whose records are entered inline`),relationshipField:v().optional().describe(`FK on the child pointing back to the parent (auto-detected when omitted)`),columns:w(x()).optional().describe(`Editable grid columns (derived from the child object when omitted)`),amountField:v().optional().describe(`Numeric child column summed for the running total`),totalField:v().optional().describe(`Parent field to receive the rolled-up sum`),title:v().optional().describe(`Section title`),addLabel:v().optional().describe(`Add-row button label`),minRows:y().optional(),maxRows:y().optional()})).optional().describe(`Inline master-detail child collections`),defaultSort:w(T({field:v().describe(`Field name to sort by`),order:A([`asc`,`desc`]).default(`desc`).describe(`Sort direction`)})).optional().describe(`Default sort order for related list views within this form`),sharing:SG.optional().describe(`Public sharing configuration for this form`),submitBehavior:E([T({kind:j(`thank-you`),title:v().optional(),message:v().optional()}),T({kind:j(`redirect`),url:v(),delayMs:y().int().min(0).optional()}),T({kind:j(`continue`)}),T({kind:j(`next-record`)})]).optional().describe(`Post-submit behavior`),aria:$.optional().describe(`ARIA accessibility attributes for the form view`)}));X(()=>T({list:aK.optional(),form:cK.optional(),listViews:k(v(),aK).optional().describe(`Additional named list views`),formViews:k(v(),cK).optional().describe(`Additional named form views`),protection:xG.optional().describe(`Package author protection block — lock policy for this view.`),...bG}));var lK=v().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>`."),uK=A([`package`,`shared`,`personal`]).describe(`View identity layer: package | shared | personal.`);A([`list`,`form`]).describe("Whether `config` is a ListView (list family) or a FormView.");function dK(){return{name:lK,object:v().describe(`Bound object name — the foreign key used to aggregate views.`),label:Q.optional().describe(`Display label (supports i18n).`),isDefault:b().optional().describe(`Whether this is the object's default view in the switcher.`),order:y().int().optional().describe(`Sort order within the object's view switcher / left rail.`),scope:uK.optional().describe("Identity layer (defaults to `package` for source-loaded views)."),owner:v().optional().describe("Owner user id — set when `scope` is `personal`."),hidden:b().optional().describe(`Hidden from the switcher (per-user / per-org declutter).`),protection:xG.optional().describe(`Package author protection block — lock policy for this view.`),...bG}}X(()=>D(`viewKind`,[T({viewKind:j(`list`),config:aK.describe(`List-family view configuration.`),...dK()}),T({viewKind:j(`form`),config:cK.describe(`Form view configuration.`),...dK()})]));function fK(e){let{schemaId:t,...n}=e;return cK.parse({...n,data:{provider:`schema`,schemaId:t}})}var pK=A([`get`,`list`,`create`,`update`,`delete`,`upsert`,`bulk`,`aggregate`,`history`,`search`,`restore`,`purge`,`import`,`export`]),mK=T({trackHistory:b().default(!1).describe(`Enable field history tracking for audit compliance`),searchable:b().default(!0).describe(`Index records for global search`),apiEnabled:b().default(!0).describe(`Expose object via automatic APIs`),apiMethods:w(pK).optional().describe(`Whitelist of allowed API operations`),files:b().default(!1).describe(`Enable file attachments and document management`),feeds:b().default(!1).describe(`Enable social feed, comments, and mentions (Chatter-like)`),activities:b().default(!1).describe(`Enable standard tasks and events tracking`),trash:b().default(!0).describe(`Enable soft-delete with restore capability`),mru:b().default(!0).describe(`Track Most Recently Used (MRU) list for users`),clone:b().default(!0).describe(`Allow record deep cloning`)}),hK=X(()=>T({name:v().optional().describe(`Index name (auto-generated if not provided)`),fields:w(v()).describe(`Fields included in the index`),type:A([`btree`,`hash`,`gin`,`gist`,`fulltext`]).optional().default(`btree`).describe(`Index algorithm type`),unique:b().optional().default(!1).describe(`Whether the index enforces uniqueness`),partial:v().optional().describe(`Partial index condition (SQL WHERE clause for conditional indexes)`)})),gK=X(()=>T({fields:w(v()).describe(`Fields to index for full-text search weighting`),displayFields:w(v()).optional().describe(`Fields to display in search result cards`),filters:w(v()).optional().describe(`Default filters for search results`)})),_K=X(()=>T({enabled:b().describe(`Enable multi-tenancy for this object`),strategy:A([`shared`,`isolated`,`hybrid`]).describe(`Tenant isolation strategy: shared (single DB, row-level), isolated (separate DB per tenant), hybrid (mix)`),tenantField:v().default(`tenant_id`).describe(`Field name for tenant identifier`),crossTenantAccess:b().default(!1).describe(`Allow cross-tenant data access (with explicit permission)`)})),vK=X(()=>T({default:A([`public`,`private`]).default(`public`).describe(`Default exposure posture: public (covered by wildcard grants) | private (needs explicit grant; exempt from wildcard RLS).`)})),yK=X(()=>T({enabled:b().describe(`Enable soft delete (trash/recycle bin)`),field:v().default(`deleted_at`).describe(`Field name for soft delete timestamp`),cascadeDelete:b().default(!1).describe(`Cascade soft delete to related records`)})),bK=X(()=>T({enabled:b().describe(`Enable record versioning`),strategy:A([`snapshot`,`delta`,`event-sourcing`]).describe(`Versioning strategy: snapshot (full copy), delta (changes only), event-sourcing (event log)`),retentionDays:y().min(1).optional().describe(`Number of days to retain old versions (undefined = infinite)`),versionField:v().default(`version`).describe(`Field name for version number/timestamp`)})),xK=X(()=>T({enabled:b().describe(`Enable table partitioning`),strategy:A([`range`,`hash`,`list`]).describe(`Partitioning strategy: range (date ranges), hash (consistent hashing), list (predefined values)`),key:v().describe(`Field name to partition by`),interval:v().optional().describe(`Partition interval for range strategy (e.g., "1 month", "1 year")`)}).refine(e=>!(e.strategy===`range`&&!e.interval),{message:`interval is required when strategy is "range"`})),SK=X(()=>T({key:v().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:v().describe(`Group display label`),icon:v().optional().describe(`Icon name (Lucide/Material) for the group header`),description:v().optional().describe(`Optional description shown under the group header`),defaultExpanded:b().optional().default(!0).describe(`Whether the group is expanded by default`),visibleOn:JH.optional().describe(`Visibility predicate (CEL); group is hidden when FALSE.`)})),CK=T({remoteName:v().optional().describe(`Remote table/view name. Defaults to object.name.`),remoteSchema:v().optional().describe(`Remote schema/database qualifier.`),writable:b().default(!1).describe(`Per-object write opt-in (also requires datasource.external.allowWrites).`),columnMap:k(v(),v()).optional().describe(`Remote column name → local field name.`),introspectedAt:v().datetime().optional().describe("Set by `os datasource introspect`; informational."),ignoreColumns:w(v()).optional().describe(`Remote columns to skip during validation (dev convenience).`)}).describe(`External datasource binding (ADR-0015)`),wK=T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Machine unique key (snake_case). Immutable.`),label:v().optional().describe(`Human readable singular label (e.g. "Account")`),pluralLabel:v().optional().describe(`Human readable plural label (e.g. "Accounts")`),description:v().optional().describe(`Developer documentation / description`),icon:v().optional().describe(`Icon name (Lucide/Material) for UI representation`),tags:w(v()).optional().describe(`Categorization tags (e.g. "sales", "system", "reference")`),active:b().optional().default(!0).describe(`Is the object active and usable`),isSystem:b().optional().default(!1).describe(`Is system object (protected from deletion)`),abstract:b().optional().default(!1).describe(`Is abstract base object (cannot be instantiated)`),managedBy:A([`platform`,`config`,`system`,`append-only`,`better-auth`]).optional().describe(`Lifecycle bucket — platform (user CRUD) | config (admin authored) | system (engine-managed) | append-only (audit) | better-auth (identity). UI clients honour the resolved affordance matrix.`),userActions:T({create:b().optional().describe(`Show generic "New" button.`),import:b().optional().describe(`Show CSV import wizard entry.`),edit:b().optional().describe(`Allow inline / form edit of existing rows.`),delete:b().optional().describe(`Show row-level delete + bulk delete.`),exportCsv:b().optional().describe(`Show CSV export entry.`)}).optional().describe(`Per-object override of the resolved CRUD affordance matrix.`),systemFields:E([j(!1),T({tenant:b().optional().describe(`Inject organization_id (multi-tenant only). Default true.`),owner:b().optional().describe(`Reserved for future owner_id auto-injection.`),audit:b().optional().describe(`Reserved for future created_by/updated_by auto-injection.`)})]).optional().describe(`Opt out of, or selectively disable, registry-level system-field auto-injection.`),datasource:v().optional().default(`default`).describe(`Target Datasource ID. "default" is the primary DB.`),external:CK.optional().describe(`Remote table binding for federated (external) objects.`),fields:k(v().regex(/^[a-z_][a-z0-9_]*$/,{message:`Field names must be lowercase snake_case (e.g., "first_name", "company", "annual_revenue")`}),ZW).describe(`Field definitions map. Keys must be snake_case identifiers.`),indexes:w(hK).optional().describe(`Database performance indexes`),fieldGroups:w(SK).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:_K.optional().describe(`Multi-tenancy configuration for SaaS applications`),access:vK.optional().describe(`[ADR-0066 D2] Object exposure posture (public-by-default vs private secure-by-default).`),requiredPermissions:w(v()).optional().describe(`[ADR-0066 D3] Capabilities required to access this object (AND-gate, checked alongside CRUD grants).`),softDelete:yK.optional().describe(`Soft delete (trash/recycle bin) configuration`),versioning:bK.optional().describe(`Record versioning and history tracking configuration`),partitioning:xK.optional().describe(`Table partitioning configuration for performance`),validations:w(iG).optional().describe(`Object-level validation rules`),activityMilestones:w(T({field:v().describe(`Field to watch (typically a status/stage select).`),value:v().describe(`The value the field must transition INTO to fire the milestone.`),summary:v().describe(`Activity summary template; {field} tokens interpolate the record value. e.g. "Deal won: {name}".`),type:v().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).`),displayNameField:v().optional().describe(`Field to use as the record display name (e.g., "name", "title"). Defaults to "name" if present.`),recordName:T({type:A([`text`,`autonumber`]).describe(`Record name type: text (user-entered) or autonumber (system-generated)`),displayFormat:v().optional().describe(`Auto-number format pattern (e.g., "CASE-{0000}", "INV-{YYYY}-{0000}")`),startNumber:y().int().min(0).optional().describe(`Starting number for autonumber (default: 1)`)}).optional().describe(`Record name generation configuration (Salesforce pattern)`),titleFormat:XH.optional().describe(`Title template — supports {{record.field}} interpolation. Overrides displayNameField.`),compactLayout:w(v()).optional().describe(`Primary fields for hover/cards/lookups`),listViews:k(v(),aK).optional().describe(`Built-in named list views (segmented tabs) shipped with the object schema`),defaultDetailForm:v().optional().describe(`Name of the default FormView for record detail / edit screens`),searchableFields:w(v()).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."),search:gK.optional().describe(`Search engine configuration`),enable:mK.optional().describe(`Enabled system features modules`),sharingModel:A([`private`,`public_read`,`public_read_write`,`controlled_by_parent`,`read`,`read_write`,`full`]).optional().describe(`Org-Wide Default record visibility (OWD). Canonical: private (owner-only) | public_read (everyone reads, owner writes) | public_read_write (everyone reads+writes) | controlled_by_parent (derived from the master record). Legacy aliases: read=public_read, read_write/full=public_read_write. ADR-0056 D1.`),publicSharing:T({enabled:b().default(!1).describe(`Allow records of this object to be published via share link`),allowedAudiences:w(A([`public`,`link_only`,`signed_in`,`email`])).optional().describe(`Audiences callers may select when creating a link`),allowedPermissions:w(A([`view`,`comment`,`edit`])).optional().describe(`Permission levels selectable on the share dialog`),maxExpiryDays:y().int().positive().optional().describe(`Reject links with expiry beyond this many days`),redactFields:w(v()).optional().describe(`Field names removed from records served via a share token`),eligibility:v().optional().describe(`CEL expression that must evaluate to true on the target record`)}).optional().describe(`Public share-link policy (Notion/Figma-style link sharing)`),keyPrefix:v().max(5).optional().describe(`Short prefix for record IDs (e.g., "001" for Account)`),detail:T({renderViaSchema:b().optional().describe(`Opt this object out of the schema-driven detail renderer`),hideReferenceRail:b().optional().describe(`Suppress the right-hand reference-rail on the detail page`),hideRelatedTab:b().optional().describe(`Suppress the Related tab on the detail page`)}).passthrough().optional().describe(`Detail-page UI hints consumed by @object-ui/plugin-detail synth`),actions:w(gG).optional().describe(`Actions associated with this object (auto-populated from top-level actions via objectName)`),protection:xG.optional().describe(`Package author protection block — lock policy for this object.`),...bG});function TK(e){return e.split(`_`).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `)}var EK={workflows:"`workflows` is not an ObjectSchema field. Object-level, record-triggered automation is authored as a lifecycle hook (`src/objects/<name>.hook.ts`, registered via `defineHook()`) 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, registered via `defineHook()`.",triggers:"`triggers` is not an ObjectSchema field. Use a lifecycle hook (`src/objects/<name>.hook.ts`) or a top-level `record_change` flow."};function DK(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 OK(e,t){let n,r=1/0;for(let i of t){let t=DK(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 kK(e,t,n){let r=typeof e==`string`&&e.length>0?e:`<unnamed>`,i=t.map(e=>{let t=EK[e];if(t)return` \u2022 ${t}`;let r=OK(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(`, `)}.
|
|
91
|
+
These keys would previously have been stripped silently at build, shipping dead metadata with no diagnostic (ADR-0032 "no silent failure", issue #1535).
|
|
92
|
+
|
|
93
|
+
${i.join(`
|
|
94
|
+
`)}
|
|
95
|
+
|
|
96
|
+
Remove the unknown key(s), fix the typo, or move the logic to a supported mechanism.`)}var AK=X(()=>Object.assign(wK,{create:e=>{let t=e,n=Object.keys(wK.shape),r=Object.keys(t).filter(e=>!n.includes(e));if(r.length>0)throw kK(t.name,r,n);let i={...t,label:t.label??TK(t.name)};return wK.parse(i)}}));A([`own`,`extend`]),X(()=>T({extend:v().describe(`Target object name (FQN) to extend`),fields:k(v(),ZW).optional().describe(`Fields to add/override`),label:v().optional().describe(`Override label for the extended object`),pluralLabel:v().optional().describe(`Override plural label for the extended object`),description:v().optional().describe(`Override description for the extended object`),validations:w(iG).optional().describe(`Additional validation rules to merge into the target object`),indexes:w(hK).optional().describe(`Additional indexes to merge into the target object`),priority:y().int().min(0).max(999).default(200).describe(`Merge priority (higher = applied later)`)}));var jK=T({type:j(`add_field`),objectName:v().describe(`Target object name`),fieldName:v().describe(`Name of the field to add`),field:ZW.describe(`Full field definition to add`)}).describe(`Add a new field to an existing object`),MK=T({type:j(`modify_field`),objectName:v().describe(`Target object name`),fieldName:v().describe(`Name of the field to modify`),changes:k(v(),S()).describe(`Partial field definition updates`)}).describe(`Modify properties of an existing field`),NK=T({type:j(`remove_field`),objectName:v().describe(`Target object name`),fieldName:v().describe(`Name of the field to remove`)}).describe(`Remove a field from an existing object`),PK=T({type:j(`create_object`),object:AK.describe(`Full object definition to create`)}).describe(`Create a new object`),FK=T({type:j(`rename_object`),oldName:v().describe(`Current object name`),newName:v().describe(`New object name`)}).describe(`Rename an existing object`),IK=T({type:j(`delete_object`),objectName:v().describe(`Name of the object to delete`)}).describe(`Delete an existing object`),LK=T({type:j(`execute_sql`),sql:v().describe(`Raw SQL statement to execute`),description:v().optional().describe(`Human-readable description of the SQL`)}).describe(`Execute a raw SQL statement`),RK=X(()=>D(`type`,[jK,MK,NK,PK,FK,IK,LK])),zK=X(()=>T({migrationId:v().describe(`ID of the migration this depends on`),package:v().optional().describe(`Package that owns the dependency migration`)}).describe(`Dependency reference to another migration that must run first`));X(()=>T({id:v().uuid().describe(`Unique identifier for this change set`),name:v().describe(`Human readable name for the migration`),description:v().optional().describe(`Detailed description of what this migration does`),author:v().optional().describe(`Author who created this migration`),createdAt:v().datetime().optional().describe(`ISO 8601 timestamp when the migration was created`),dependencies:w(zK).optional().describe(`Migrations that must run before this one`),operations:w(RK).describe(`Ordered list of atomic migration operations`),rollback:w(RK).optional().describe(`Operations to reverse this migration`)}).describe(`A versioned set of atomic schema migration operations`));var BK=X(()=>T({id:v().describe(`Provider ID (github, google)`),clientId:v().describe(`OAuth Client ID`),clientSecret:v().describe(`OAuth Client Secret`),scope:w(v()).optional().describe(`Requested permissions`)})),VK=X(()=>T({organization:b().default(!0).describe(`Enable Organization/Teams support (frontend AuthProvider expects this enabled)`),twoFactor:b().default(!1).describe(`Enable 2FA`),passkeys:b().default(!1).describe(`Enable Passkey support`),passwordRejectBreached:b().default(!1).describe(`Reject passwords found in the Have I Been Pwned breach corpus (enables better-auth's haveibeenpwned plugin)`),magicLink:b().default(!1).describe(`Enable Magic Link login`),oidcProvider:b().default(!1).describe(`Enable the OpenID Connect provider plugin (acts as an OIDC IdP)`),deviceAuthorization:b().default(!1).describe(`Enable RFC 8628 Device Authorization Grant (CLI / TV-style login)`),admin:b().default(!1).describe(`Enable platform admin operations (ban/unban, set-password, impersonate, set-role)`)})),HK=X(()=>T({enabled:b().default(!1).describe(`Enable mutual TLS authentication`),clientCertRequired:b().default(!1).describe(`Require client certificates for all connections`),trustedCAs:w(v()).describe(`PEM-encoded CA certificates or file paths`),crlUrl:v().optional().describe(`Certificate Revocation List (CRL) URL`),ocspUrl:v().optional().describe(`Online Certificate Status Protocol (OCSP) URL`),certificateValidation:A([`strict`,`relaxed`,`none`]).describe(`Certificate validation strictness level`),allowedCNs:w(v()).optional().describe(`Allowed Common Names (CN) on client certificates`),allowedOUs:w(v()).optional().describe(`Allowed Organizational Units (OU) on client certificates`),pinning:T({enabled:b().describe(`Enable certificate pinning`),pins:w(v()).describe(`Pinned certificate hashes`)}).optional().describe(`Certificate pinning configuration`)})),UK=X(()=>k(v(),T({clientId:v().describe(`OAuth Client ID`),clientSecret:v().describe(`OAuth Client Secret`),enabled:b().default(!0).describe(`Enable this provider (default: true)`),scope:w(v()).optional().describe(`Additional OAuth scopes`)}).catchall(S())).optional().describe(`Social/OAuth provider map forwarded to better-auth socialProviders. Keys are provider ids (google, github, apple, …).`)),WK=X(()=>T({providerId:v().describe(`Unique identifier for this provider (e.g., okta, azure-ad)`),name:v().optional().describe(`Display name shown in the UI (defaults to providerId)`),discoveryUrl:v().optional().describe(`OIDC discovery URL (.well-known/openid-configuration). When provided, authorizationUrl/tokenUrl/userInfoUrl are fetched automatically.`),issuer:v().optional().describe(`Expected issuer identifier for token validation`),authorizationUrl:v().optional().describe(`OAuth2 authorization endpoint (optional if discoveryUrl is set)`),tokenUrl:v().optional().describe(`OAuth2 token endpoint (optional if discoveryUrl is set)`),userInfoUrl:v().optional().describe(`OAuth2 userinfo endpoint (optional if discoveryUrl is set)`),clientId:v().describe(`OAuth2 client ID`),clientSecret:v().describe(`OAuth2 client secret`),scopes:w(v()).optional().describe(`Requested scopes (default: openid email profile)`),pkce:b().optional().describe(`Enable PKCE (recommended for public clients)`)}).describe(`OIDC / Generic OAuth2 provider configuration for enterprise SSO`)),GK=X(()=>w(WK).optional().describe(`List of OIDC/OAuth2 providers for enterprise SSO. Product or enterprise packages can pass this directly or contribute it through auth:configure.`)),KK=X(()=>T({enabled:b().default(!0).describe(`Enable email/password auth`),disableSignUp:b().optional().describe(`Disable new user registration via email/password`),requireEmailVerification:b().optional().describe(`Require email verification before creating a session`),minPasswordLength:y().optional().describe(`Minimum password length (default 8)`),maxPasswordLength:y().optional().describe(`Maximum password length (default 128)`),resetPasswordTokenExpiresIn:y().optional().describe(`Reset-password token TTL in seconds (default 3600)`),autoSignIn:b().optional().describe(`Auto sign-in after sign-up (default true)`),revokeSessionsOnPasswordReset:b().optional().describe(`Revoke all other sessions on password reset`)}).optional().describe(`Email and password authentication options forwarded to better-auth`)),qK=X(()=>T({sendOnSignUp:b().optional().describe(`Automatically send verification email after sign-up`),sendOnSignIn:b().optional().describe(`Send verification email on sign-in when not yet verified`),autoSignInAfterVerification:b().optional().describe(`Auto sign-in the user after email verification`),expiresIn:y().optional().describe(`Verification token TTL in seconds (default 3600)`)}).optional().describe(`Email verification options forwarded to better-auth`)),JK=X(()=>T({crossSubDomainCookies:T({enabled:b().describe(`Enable cross-subdomain cookies`),additionalCookies:w(v()).optional().describe(`Extra cookies shared across subdomains`),domain:v().optional().describe(`Cookie domain override — defaults to root domain derived from baseUrl`)}).optional().describe(`Share auth cookies across subdomains (critical for *.example.com multi-tenant)`),useSecureCookies:b().optional().describe(`Force Secure flag on cookies`),disableCSRFCheck:b().optional().describe(`⚠ Disable CSRF check — security risk, use with caution`),cookiePrefix:v().optional().describe(`Prefix for auth cookie names`)}).optional().describe(`Advanced / low-level Better-Auth options`));X(()=>T({secret:v().optional().describe(`Encryption secret`),baseUrl:v().optional().describe(`Base URL for auth routes`),uiBasePath:v().default(`/_console`).describe("Basename where the auth UI (Console) is mounted (default `/_console`)"),databaseUrl:v().optional().describe(`Database connection string`),providers:w(BK).optional(),plugins:VK.optional(),session:T({expiresIn:y().default(3600*24*7).describe(`Session duration in seconds`),updateAge:y().default(3600*24).describe(`Session update frequency`)}).optional(),trustedOrigins:w(v()).optional().describe(`Trusted origins for CSRF protection. Supports wildcards (e.g. "https://*.example.com"). The baseUrl origin is always trusted implicitly.`),socialProviders:UK,oidcProviders:GK,emailAndPassword:KK,emailVerification:qK,advanced:JK,ssoOnlyMode:b().optional().describe(`SSO-only login: hide the local password form + self-registration (the break-glass password endpoint stays enabled)`),mutualTls:HK.optional().describe(`Mutual TLS (mTLS) configuration`)}).catchall(S())),X(()=>T({name:v().regex(/^[a-z][a-z0-9_]*$/,`name must be lowercase snake_case`).describe(`Doc name (= filename stem, snake_case; namespace prefix recommended, not required)`),label:v().optional().describe("Display title; defaults to the first `#` heading, then the name"),description:v().optional().describe("One-line summary for listings; from frontmatter `description:`"),content:v().describe(`Raw Markdown content (CommonMark + GFM)`),order:y().optional().describe(`Sort key within a book group (ADR-0046 §6)`),group:v().optional().describe(`Explicit book-group key (ADR-0046 §6); rules usually suffice`),translations:k(v(),T({label:v().optional(),description:v().optional(),content:v()})).optional().describe(`Per-locale {label?,description?,content} variants; the base doc is the fallback`)}));var YK=X(()=>E([v(),T({doc:v().optional().describe(`Doc name to reference`),href:v().optional().describe("External link (use instead of `doc`)"),label:v().optional().describe(`Optional label override; title authority stays in the doc`),badge:v().optional().describe(`e.g. "beta" | "new"`),icon:v().optional()})])),XK=X(()=>E([v().describe(`Glob over doc names, e.g. "crm_guide_*"`),T({tag:v()}).describe(`Match by doc tag (§5 vocabulary)`)])),ZK=X(()=>T({key:v().regex(/^[a-z][a-z0-9_]*$/,`group key must be lowercase snake_case`).describe("Stable group key (used by overrides, deep links, explicit `doc.group`)"),label:v().describe(`Section title — first-class, i18n-homed`),translations:k(v(),T({label:v()})).optional().describe(`Per-locale label variants`),order:y().optional().describe(`Order of THIS group within the book`),include:XK.optional().describe(`Rule that derives membership (glob or tag)`),package:v().optional().describe(`Scope the rule to a package id (default: the book package; cross-package via ADR-0048)`),pages:w(YK).optional().describe("OPTIONAL explicit override — hand-pin a curated order; wins over `include`")})),QK=X(()=>E([j(`org`),j(`public`),T({profile:v()})]));X(()=>T({name:v().regex(/^[a-z][a-z0-9_]*$/,`name must be lowercase snake_case`).describe(`Book name (namespace prefix recommended, like every metadata name)`),label:v().optional().describe(`Display title`),description:v().optional(),translations:k(v(),T({label:v().optional(),description:v().optional()})).optional(),slug:v().optional().describe(`Portal URL segment; defaults to name sans prefix`),icon:v().optional(),order:y().optional().describe(`Orders books within the portal`),audience:QK.optional().describe(`Access audience; defaults to 'org' (inherits package grant)`),groups:w(ZK).describe(`The spine: ordered sections. Two levels total.`)}));var $K=X(()=>A([`log`,`resend`,`postmark`])),eq=X(()=>T({name:v().optional().describe(`Display name (e.g. "Acme CRM")`),address:v().email().describe(`RFC-5322 address`)}));X(()=>T({provider:$K.default(`log`),apiKey:v().optional().describe(`Provider API key (or OS_EMAIL_API_KEY env)`),defaultFrom:eq.optional(),retries:y().int().min(0).max(10).optional().describe(`Retry attempts on transport throw`),persist:b().optional().describe(`Persist to sys_email (default true)`),options:k(v(),S()).optional()}));var tq=X(()=>A([`auth`,`notification`,`workflow`,`marketing`,`custom`])),nq=X(()=>T({name:v().describe(`Variable name as referenced in placeholders (snake_case or dotted path)`),type:A([`string`,`number`,`boolean`,`date`,`url`,`user`,`record`]).default(`string`),required:b().default(!1),description:v().optional().describe(`Author hint shown in Studio`)}));X(()=>T({name:v().regex(/^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)*$/,`name must be dotted snake_case`).describe(`Template identifier (dotted snake_case)`),label:v().describe(`Display label`),category:tq.default(`custom`),locale:v().default(`en-US`).describe(`BCP-47 locale (e.g. en-US, zh-CN)`),subject:v().describe(`Subject template`),bodyHtml:v().describe(`HTML body template`),bodyText:v().optional().describe(`Plain-text body template (auto-derived from HTML when omitted)`),variables:w(nq).default([]),fromOverride:rq().optional(),replyTo:v().optional(),active:b().default(!0),isSystem:b().default(!1),description:v().optional(),protection:xG.optional().describe(`Package author protection block — lock policy for this email template.`),...bG}));function rq(){return T({name:v().optional(),address:v().email()})}var iq=fK({schemaId:`email_template`,type:`simple`,sections:[{label:`Identity`,description:`Template identifier resolved by IEmailService.sendTemplate({ template: name, locale, ... }).`,columns:2,fields:[{field:`name`,required:!0,colSpan:1,helpText:`Dotted snake_case (e.g. auth.password_reset, crm.welcome)`},{field:`label`,required:!0,colSpan:1},{field:`category`,type:`select`,colSpan:1,options:[{label:`Auth`,value:`auth`},{label:`Notification`,value:`notification`},{label:`Workflow`,value:`workflow`},{label:`Marketing`,value:`marketing`},{label:`Custom`,value:`custom`}]},{field:`locale`,colSpan:1,helpText:`BCP-47 tag — e.g. en-US, zh-CN`},{field:`description`,widget:`textarea`,colSpan:2}]},{label:`Subject`,description:`Subject line. Supports {{var.path}} interpolation.`,columns:1,fields:[{field:`subject`,required:!0,widget:`textarea`}]},{label:`HTML body`,description:`Rich HTML body. Most clients strip <head>, so use inline styles.`,columns:1,fields:[{field:`bodyHtml`,required:!0,type:`code`,language:`html`}]},{label:`Plain-text body`,description:`Optional plain-text alternative. When omitted, the service strips tags from the HTML body to derive one. Providing one improves spam scoring.`,columns:1,fields:[{field:`bodyText`,widget:`textarea`}]},{label:`Variables`,description:`Declared variables. Rendered as hints in Studio and validated by sendTemplate() when required.`,columns:1,fields:[{field:`variables`,widget:`json`,helpText:`[{ "name": "user.name", "type": "string", "required": true, "description": "..." }]`}]},{label:`Delivery overrides`,description:`Optional per-template overrides for From / Reply-To.`,columns:2,fields:[{field:`fromOverride`,widget:`json`,colSpan:2,helpText:`{ "name": "Acme Sales", "address": "sales@acme.com" }`},{field:`replyTo`,colSpan:2,helpText:`Reply-To email address`}]},{label:`Status`,columns:2,fields:[{field:`active`,type:`boolean`,colSpan:1,helpText:`When unchecked, sendTemplate() returns TEMPLATE_INACTIVE.`},{field:`isSystem`,type:`boolean`,colSpan:1,helpText:`Built-in template; tenants may override but should not delete.`}]}]}),aq=X(()=>T({$field:v().describe(`Field Reference/Column Name`)}));X(()=>T({$eq:x().optional(),$ne:x().optional()})),X(()=>T({$gt:E([y(),C(),aq]).optional(),$gte:E([y(),C(),aq]).optional(),$lt:E([y(),C(),aq]).optional(),$lte:E([y(),C(),aq]).optional()})),X(()=>T({$in:w(x()).optional(),$nin:w(x()).optional()})),X(()=>T({$between:O([E([y(),C(),aq]),E([y(),C(),aq])]).optional()})),X(()=>T({$contains:v().optional(),$notContains:v().optional(),$startsWith:v().optional(),$endsWith:v().optional()})),X(()=>T({$null:b().optional(),$exists:b().optional()}));var oq=X(()=>T({$eq:x().optional(),$ne:x().optional(),$gt:E([y(),C(),aq]).optional(),$gte:E([y(),C(),aq]).optional(),$lt:E([y(),C(),aq]).optional(),$lte:E([y(),C(),aq]).optional(),$in:w(x()).optional(),$nin:w(x()).optional(),$between:O([E([y(),C(),aq]),E([y(),C(),aq])]).optional(),$contains:v().optional(),$notContains:v().optional(),$startsWith:v().optional(),$endsWith:v().optional(),$null:b().optional(),$exists:b().optional()})),sq=M(()=>k(v(),S()).and(T({$and:w(sq).optional(),$or:w(sq).optional(),$not:sq.optional()})));X(()=>T({where:sq.optional()}));var cq=M(()=>T({$and:w(E([k(v(),oq),cq])).optional(),$or:w(E([k(v(),oq),cq])).optional(),$not:E([k(v(),oq),cq]).optional()})),lq=X(()=>T({field:v(),order:A([`asc`,`desc`]).default(`asc`)})),uq=A([`count`,`sum`,`avg`,`min`,`max`,`count_distinct`,`array_agg`,`string_agg`]),dq=A([`day`,`week`,`month`,`quarter`,`year`]),fq=X(()=>E([v(),T({field:v().describe(`Field to group by`),dateGranularity:dq.optional().describe(`Bucket date values into uniform periods (day/week/month/quarter/year)`),alias:v().optional().describe(`Alias for the projected group value`)})])),pq=X(()=>T({function:uq.describe(`Aggregation function`),field:v().optional().describe(`Field to aggregate (optional for COUNT(*))`),alias:v().describe(`Result column alias`),distinct:b().optional().describe(`Apply DISTINCT before aggregation`),filter:sq.optional().describe(`Filter/Condition to apply to the aggregation (FILTER WHERE clause)`)})),mq=A([`inner`,`left`,`right`,`full`]),hq=A([`auto`,`database`,`hash`,`loop`]),gq=M(()=>T({type:mq.describe(`Join type`),strategy:hq.optional().describe(`Execution strategy hint`),object:v().describe(`Object/table to join`),alias:v().optional().describe(`Table alias`),on:sq.describe(`Join condition`),subquery:M(()=>Cq).optional().describe(`Subquery instead of object`)})),_q=A([`row_number`,`rank`,`dense_rank`,`percent_rank`,`lag`,`lead`,`first_value`,`last_value`,`sum`,`avg`,`count`,`min`,`max`]),vq=X(()=>T({partitionBy:w(v()).optional().describe(`PARTITION BY fields`),orderBy:w(lq).optional().describe(`ORDER BY specification`),frame:T({type:A([`rows`,`range`]).optional(),start:v().optional().describe(`Frame start (e.g., "UNBOUNDED PRECEDING", "1 PRECEDING")`),end:v().optional().describe(`Frame end (e.g., "CURRENT ROW", "1 FOLLOWING")`)}).optional().describe(`Window frame specification`)})),yq=X(()=>T({function:_q.describe(`Window function name`),field:v().optional().describe(`Field to operate on (for aggregate window functions)`),alias:v().describe(`Result column alias`),over:vq.describe(`Window specification (OVER clause)`)})),bq=M(()=>E([v(),T({field:v(),fields:w(bq).optional(),alias:v().optional()})])),xq=X(()=>T({query:v().describe(`Search query text`),fields:w(v()).optional().describe(`Fields to search in (if not specified, searches all text fields)`),fuzzy:b().optional().default(!1).describe(`Enable fuzzy matching (tolerates typos)`),operator:A([`and`,`or`]).optional().default(`or`).describe(`Logical operator between terms`),boost:k(v(),y()).optional().describe(`Field-specific relevance boosting (field name -> boost factor)`),minScore:y().optional().describe(`Minimum relevance score threshold`),language:v().optional().describe(`Language for text analysis (e.g., "en", "zh", "es")`),highlight:b().optional().default(!1).describe(`Enable search result highlighting`)})),Sq=T({object:v().describe(`Object name (e.g. account)`),fields:w(bq).optional().describe(`Fields to retrieve`),where:sq.optional().describe(`Filtering criteria (WHERE)`),search:xq.optional().describe(`Full-text search configuration ($search parameter)`),orderBy:w(lq).optional().describe(`Sorting instructions (ORDER BY)`),limit:y().optional().describe(`Max records to return (LIMIT)`),offset:y().optional().describe(`Records to skip (OFFSET)`),top:y().optional().describe(`Alias for limit (OData compatibility)`),cursor:k(v(),S()).optional().describe(`Cursor for keyset pagination`),joins:w(gq).optional().describe(`Explicit Table Joins`),aggregations:w(pq).optional().describe(`Aggregation functions`),groupBy:w(fq).optional().describe("GROUP BY targets (strings or `{field, dateGranularity?}` objects for date bucketing)"),having:sq.optional().describe(`HAVING clause for aggregation filtering`),windowFunctions:w(yq).optional().describe(`Window functions with OVER clause`),distinct:b().optional().describe(`SELECT DISTINCT flag`)}),Cq=X(()=>Sq.extend({expand:M(()=>k(v(),Cq)).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.")})),wq=[`today`,`yesterday`,`tomorrow`,`now`],Tq=[`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`],Eq=[`week_start`,`week_end`,`month_start`,`month_end`,`quarter_start`,`quarter_end`,`year_start`,`year_end`],Dq=[...wq,...Tq,...Eq],Oq=/^(\d+)_(minutes?|hours?|days?|weeks?|months?|years?)_(ago|from_now)$/,kq=[`minute`,`hour`,`day`,`week`,`month`,`year`];function Aq(e){return Dq.includes(e)||Oq.test(e)}v().refine(Aq,{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: `+kq.join(`, `)});var jq=/^\$?\{([a-zA-Z0-9_]+)\}$/;v().refine(e=>{let t=e.match(jq);return!!t&&Aq(t[1])},{message:`Not a recognised {date-macro} placeholder`});var Mq=A([`beforeFind`,`afterFind`,`beforeFindOne`,`afterFindOne`,`beforeCount`,`afterCount`,`beforeAggregate`,`afterAggregate`,`beforeInsert`,`afterInsert`,`beforeUpdate`,`afterUpdate`,`beforeDelete`,`afterDelete`,`beforeUpdateMany`,`afterUpdateMany`,`beforeDeleteMany`,`afterDeleteMany`]);X(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Hook unique name (snake_case)`),label:v().optional().describe(`Description of what this hook does`),object:E([v(),w(v())]).describe(`Target object(s)`),events:w(Mq).describe(`Lifecycle events`),handler:E([v(),$l(e=>typeof e==`function`,{message:`Expected function`})]).optional().describe("Handler function name (string, post-build) or inline function (pre-build) — DEPRECATED, prefer `body`"),body:lG.optional().describe(`Hook body — expression (L1) or sandboxed JS (L2)`),priority:y().default(100).describe(`Execution priority`),async:b().default(!1).describe(`Run specifically as fire-and-forget`),condition:JH.optional().describe('Predicate (CEL); hook runs only when TRUE. e.g. P`record.status == "closed" && record.amount > 1000`'),description:v().optional().describe(`Human-readable description of what this hook does`),retryPolicy:T({maxRetries:y().default(3).describe(`Maximum retry attempts on failure`),backoffMs:y().default(1e3).describe(`Backoff delay between retries in milliseconds`)}).optional().describe(`Retry policy for failed hook executions`),timeout:y().optional().describe(`Maximum execution time in milliseconds before the hook is aborted`),onError:A([`abort`,`log`]).default(`abort`).describe(`Error handling strategy`)})),X(()=>T({id:v().optional().describe(`Unique execution ID for tracing`),object:v(),event:Mq,input:k(v(),S()).describe(`Mutable input parameters`),result:S().optional().describe(`Operation result (After hooks only)`),previous:k(v(),S()).optional().describe(`Record state before operation`),session:T({userId:v().optional(),tenantId:v().optional(),roles:w(v()).optional(),accessToken:v().optional(),isSystem:b().optional().describe(`True when the call was made with an elevated system context (engine self-writes)`)}).optional().describe(`Current session context`),transaction:S().optional().describe(`Database transaction handle`),ql:S().describe(`ObjectQL Engine Reference`),api:S().optional().describe(`Cross-object data access (ScopedContext)`),user:T({id:v().optional(),name:v().optional(),email:v().optional()}).optional().describe(`Current user info shortcut`)}));var Nq=A([`none`,`constant`,`lookup`,`split`,`join`,`javascript`,`map`]),Pq=X(()=>T({source:E([v(),w(v())]).describe(`Source column header(s)`),target:E([v(),w(v())]).describe(`Target object field(s)`),transform:Nq.default(`none`),params:T({value:S().optional(),object:v().optional(),fromField:v().optional(),toField:v().optional(),autoCreate:b().optional(),valueMap:k(v(),S()).optional(),separator:v().optional()}).optional()}));X(()=>T({name:Z.describe(`Mapping unique name (lowercase snake_case)`),label:v().optional(),sourceFormat:A([`csv`,`json`,`xml`,`sql`]).default(`csv`),targetObject:v().describe(`Target Object Name`),fieldMapping:w(Pq),mode:A([`insert`,`update`,`upsert`]).default(`insert`),upsertKey:w(v()).optional().describe(`Fields to match for upsert (e.g. email)`),extractQuery:Cq.optional().describe(`Query to run for export only`),errorPolicy:A([`skip`,`abort`,`retry`]).default(`skip`),batchSize:y().default(1e3)}));var Fq=X(()=>T({userId:v().optional(),actor:v().optional(),email:v().optional(),tenantId:v().optional(),timezone:v().optional(),locale:v().optional(),currency:v().optional(),roles:w(v()).default([]),permissions:w(v()).default([]),systemPermissions:w(v()).optional(),tabPermissions:k(v(),A([`visible`,`hidden`,`default_on`,`default_off`])).optional(),org_user_ids:w(v()).optional(),rlsMembership:k(v(),w(v())).optional(),isSystem:b().default(!1),accessToken:v().optional(),transaction:S().optional(),traceId:v().optional()})),Iq=X(()=>E([k(v(),S()),sq]).describe(`Data Engine query filter conditions`)),Lq=X(()=>E([k(v(),A([`asc`,`desc`])),k(v(),E([j(1),j(-1)])),w(lq)]).describe(`Sort order definition`)),Rq=X(()=>T({context:Fq.optional()})),zq=X(()=>Rq.extend({where:E([k(v(),S()),sq]).optional(),fields:w(bq).optional(),orderBy:w(lq).optional(),limit:y().optional(),offset:y().optional(),top:y().optional(),cursor:k(v(),S()).optional(),search:xq.optional(),expand:M(()=>k(v(),Cq)).optional(),distinct:b().optional()}).describe(`QueryAST-aligned query options for IDataEngine.find() operations`));X(()=>Rq.extend({filter:Iq.optional(),select:w(v()).optional(),sort:Lq.optional(),limit:y().int().min(1).optional(),skip:y().int().min(0).optional(),top:y().int().min(1).optional(),populate:w(v()).optional()}).describe(`Query options for IDataEngine.find() operations`));var Bq=X(()=>Rq.extend({returning:b().default(!0).optional()}).describe(`Options for DataEngine.insert operations`)),Vq=X(()=>Rq.extend({where:E([k(v(),S()),sq]).optional(),upsert:b().default(!1).optional(),multi:b().default(!1).optional(),returning:b().default(!1).optional()}).describe(`QueryAST-aligned options for DataEngine.update operations`));X(()=>Rq.extend({filter:Iq.optional(),upsert:b().default(!1).optional(),multi:b().default(!1).optional(),returning:b().default(!1).optional()}).describe(`Options for DataEngine.update operations`));var Hq=X(()=>Rq.extend({where:E([k(v(),S()),sq]).optional(),multi:b().default(!1).optional()}).describe(`QueryAST-aligned options for DataEngine.delete operations`));X(()=>Rq.extend({filter:Iq.optional(),multi:b().default(!1).optional()}).describe(`Options for DataEngine.delete operations`));var Uq=X(()=>Rq.extend({where:E([k(v(),S()),sq]).optional(),groupBy:w(v()).optional(),aggregations:w(pq).optional(),timezone:v().optional()}).describe(`QueryAST-aligned options for DataEngine.aggregate operations`));X(()=>Rq.extend({filter:Iq.optional(),groupBy:w(v()).optional(),aggregations:w(T({field:v(),method:A([`count`,`sum`,`avg`,`min`,`max`,`count_distinct`]),alias:v().optional()})).optional()}).describe(`Options for DataEngine.aggregate operations`));var Wq=X(()=>Rq.extend({where:E([k(v(),S()),sq]).optional()}).describe(`QueryAST-aligned options for DataEngine.count operations`));X(()=>Rq.extend({filter:Iq.optional()}).describe(`Options for DataEngine.count operations`)),X(()=>T({find:P().input(O([v(),zq.optional()])).output(N(w(S()))),findOne:P().input(O([v(),zq.optional()])).output(N(S())),insert:P().input(O([v(),E([k(v(),S()),w(k(v(),S()))]),Bq.optional()])).output(N(S())),update:P().input(O([v(),k(v(),S()),Vq.optional()])).output(N(S())),delete:P().input(O([v(),Hq.optional()])).output(N(S())),count:P().input(O([v(),Wq.optional()])).output(N(y())),aggregate:P().input(O([v(),Uq])).output(N(w(S())))}).describe(`Standard Data Engine Contract`));var Gq={filter:Iq.optional()},Kq=zq.extend({...Gq,select:w(v()).optional(),sort:Lq.optional(),skip:y().int().min(0).optional(),populate:w(v()).optional()}),qq=X(()=>T({method:j(`find`),object:v(),query:Kq.optional()})),Jq=X(()=>T({method:j(`findOne`),object:v(),query:Kq.optional()})),Yq=X(()=>T({method:j(`insert`),object:v(),data:E([k(v(),S()),w(k(v(),S()))]),options:Bq.optional()})),Xq=X(()=>T({method:j(`update`),object:v(),data:k(v(),S()),id:E([v(),y()]).optional().describe(`ID for single update, or use where in options`),options:Vq.extend(Gq).optional()})),Zq=X(()=>T({method:j(`delete`),object:v(),id:E([v(),y()]).optional().describe(`ID for single delete, or use where in options`),options:Hq.extend(Gq).optional()})),Qq=X(()=>T({method:j(`count`),object:v(),query:Wq.extend(Gq).optional()})),$q=X(()=>T({method:j(`aggregate`),object:v(),query:Uq.extend(Gq)})),eJ=X(()=>T({method:j(`execute`),command:S(),options:k(v(),S()).optional()})),tJ=X(()=>T({method:j(`vectorFind`),object:v(),vector:w(y()),where:E([k(v(),S()),sq]).optional(),fields:w(v()).optional(),limit:y().int().default(5).optional(),threshold:y().optional()})),nJ=X(()=>T({method:j(`batch`),requests:w(D(`method`,[qq,Jq,Yq,Xq,Zq,Qq,$q,eJ,tJ])),transaction:b().default(!0).optional()}));X(()=>D(`method`,[qq,Jq,Yq,Xq,Zq,Qq,$q,nJ,eJ,tJ]).describe(`Virtual ObjectQL Request Protocol`)),A([`count`,`sum`,`avg`,`min`,`max`,`count_distinct`,`percentile`,`median`,`stddev`,`variance`]).describe(`Standard aggregation functions`);var rJ=A([`asc`,`desc`]).describe(`Sort order direction`),iJ=X(()=>T({field:v().describe(`Field name to sort by`),order:rJ.describe(`Sort direction`)}).describe(`Sort field and direction pair`));A([`insert`,`update`,`delete`,`upsert`]).describe(`Data mutation event types`);var aJ=A([`read_uncommitted`,`read_committed`,`repeatable_read`,`serializable`,`snapshot`]).describe(`Transaction isolation levels (snake_case standard)`);A([`lru`,`lfu`,`ttl`,`fifo`]).describe(`Cache eviction strategy`);var oJ=X(()=>T({transaction:S().optional().describe(`Transaction handle`),timeout:y().optional().describe(`Timeout in ms`),skipCache:b().optional().describe(`Bypass cache`),traceContext:k(v(),v()).optional().describe(`OpenTelemetry context or request ID`),tenantId:v().optional().describe(`Tenant Isolation identifier`),timezone:v().optional().describe(`Business reference timezone (IANA) for date-dependent generation, e.g. autonumber date tokens`)})),sJ=X(()=>T({create:b().default(!0).describe(`Supports CREATE operations`),read:b().default(!0).describe(`Supports READ operations`),update:b().default(!0).describe(`Supports UPDATE operations`),delete:b().default(!0).describe(`Supports DELETE operations`),bulkCreate:b().default(!1).describe(`Supports bulk CREATE operations`),bulkUpdate:b().default(!1).describe(`Supports bulk UPDATE operations`),bulkDelete:b().default(!1).describe(`Supports bulk DELETE operations`),transactions:b().default(!1).describe(`Supports ACID transactions`),savepoints:b().default(!1).describe(`Supports transaction savepoints`),isolationLevels:w(aJ).optional().describe(`Supported isolation levels`),queryFilters:b().default(!0).describe(`Supports WHERE clause filtering`),queryAggregations:b().default(!1).describe(`Supports GROUP BY and aggregation functions`),queryDateGranularity:k(dq,b()).optional().describe(`Per-granularity native date bucketing (day/week/month/quarter/year). Missing keys fall back to in-memory bucketing.`),querySorting:b().default(!0).describe(`Supports ORDER BY sorting`),queryPagination:b().default(!0).describe(`Supports LIMIT/OFFSET pagination`),queryWindowFunctions:b().default(!1).describe(`Supports window functions with OVER clause`),querySubqueries:b().default(!1).describe(`Supports subqueries`),queryCTE:b().default(!1).describe(`Supports Common Table Expressions (WITH clause)`),joins:b().default(!1).describe(`Supports SQL joins`),fullTextSearch:b().default(!1).describe(`Supports full-text search`),jsonQuery:b().default(!1).describe(`Supports JSON field querying`),geospatialQuery:b().default(!1).describe(`Supports geospatial queries`),streaming:b().default(!1).describe(`Supports result streaming (cursors/iterators)`),jsonFields:b().default(!1).describe(`Supports JSON field types`),arrayFields:b().default(!1).describe(`Supports array field types`),vectorSearch:b().default(!1).describe(`Supports vector embeddings and similarity search`),autonumber:b().optional().describe(`Driver natively generates persistent autonumber/sequence values`),schemaSync:b().default(!1).describe(`Supports automatic schema synchronization`),batchSchemaSync:b().default(!1).describe(`Supports batched schema sync to reduce schema DDL round-trips`),migrations:b().default(!1).describe(`Supports database migrations`),indexes:b().default(!1).describe(`Supports index creation and management`),connectionPooling:b().default(!1).describe(`Supports connection pooling`),preparedStatements:b().default(!1).describe(`Supports prepared statements (SQL injection prevention)`),queryCache:b().default(!1).describe(`Supports query result caching`)}));X(()=>T({name:v().describe(`Driver unique name`),version:v().describe(`Driver version`),supports:sJ,connect:P().input(O([])).output(N(gl())).describe(`Establish connection`),disconnect:P().input(O([])).output(N(gl())).describe(`Close connection`),checkHealth:P().input(O([])).output(N(b())).describe(`Health check`),getPoolStats:P().input(O([])).output(T({total:y(),idle:y(),active:y(),waiting:y()}).optional()).optional().describe(`Get connection pool statistics`),execute:P().input(O([S(),w(S()).optional(),oJ.optional()])).output(N(S())).describe(`Execute raw command`),find:P().input(O([v(),Cq,oJ.optional()])).output(N(w(k(v(),S())))).describe(`Find records`),findStream:P().input(O([v(),Cq,oJ.optional()])).output(S()).describe(`Stream records (AsyncIterable)`),findOne:P().input(O([v(),Cq,oJ.optional()])).output(N(k(v(),S()).nullable())).describe(`Find one record`),create:P().input(O([v(),k(v(),S()),oJ.optional()])).output(N(k(v(),S()))).describe(`Create record`),update:P().input(O([v(),v().or(y()),k(v(),S()),oJ.optional()])).output(N(k(v(),S()))).describe(`Update record`),upsert:P().input(O([v(),k(v(),S()),w(v()).optional(),oJ.optional()])).output(N(k(v(),S()))).describe(`Upsert record`),delete:P().input(O([v(),v().or(y()),oJ.optional()])).output(N(b())).describe(`Delete record`),count:P().input(O([v(),Cq.optional(),oJ.optional()])).output(N(y())).describe(`Count records`),bulkCreate:P().input(O([v(),w(k(v(),S())),oJ.optional()])).output(N(w(k(v(),S())))),bulkUpdate:P().input(O([v(),w(T({id:v().or(y()),data:k(v(),S())})),oJ.optional()])).output(N(w(k(v(),S())))),bulkDelete:P().input(O([v(),w(v().or(y())),oJ.optional()])).output(N(gl())),updateMany:P().input(O([v(),Cq,k(v(),S()),oJ.optional()])).output(N(y())).optional(),deleteMany:P().input(O([v(),Cq,oJ.optional()])).output(N(y())).optional(),beginTransaction:P().input(O([T({isolationLevel:aJ.optional()}).optional()])).output(N(S())).describe(`Start transaction`),commit:P().input(O([S()])).output(N(gl())).describe(`Commit transaction`),rollback:P().input(O([S()])).output(N(gl())).describe(`Rollback transaction`),syncSchema:P().input(O([v(),S(),oJ.optional()])).output(N(gl())).describe(`Sync object schema to DB`),syncSchemasBatch:P().input(O([w(T({object:v(),schema:S()})),oJ.optional()])).output(N(gl())).optional().describe(`Batch sync multiple schemas in one round-trip`),dropTable:P().input(O([v(),oJ.optional()])).output(N(gl())),explain:P().input(O([v(),Cq,oJ.optional()])).output(N(S())).optional()}));var cJ=X(()=>T({min:y().min(0).default(2).describe(`Minimum number of connections in pool`),max:y().min(1).default(10).describe(`Maximum number of connections in pool`),idleTimeoutMillis:y().min(0).default(3e4).describe(`Time in ms before idle connection is closed`),connectionTimeoutMillis:y().min(0).default(5e3).describe(`Time in ms to wait for available connection`)})),lJ=X(()=>T({name:v().describe(`Driver instance name`),type:A([`sql`,`nosql`,`cache`,`search`,`graph`,`timeseries`]).describe(`Driver type category`),capabilities:sJ.describe(`Driver capability flags`),connectionString:v().optional().describe(`Database connection string (driver-specific format)`),poolConfig:cJ.optional().describe(`Connection pool configuration`)})),uJ=X(()=>A([`postgresql`,`mysql`,`sqlite`,`mssql`,`oracle`,`mariadb`])),dJ=X(()=>T({text:v().describe(`SQL type for text fields (e.g., VARCHAR, TEXT)`),number:v().describe(`SQL type for number fields (e.g., NUMERIC, DECIMAL, INT)`),boolean:v().describe(`SQL type for boolean fields (e.g., BOOLEAN, BIT)`),date:v().describe(`SQL type for date fields (e.g., DATE)`),datetime:v().describe(`SQL type for datetime fields (e.g., TIMESTAMP, DATETIME)`),json:v().optional().describe(`SQL type for JSON fields (e.g., JSON, JSONB)`),uuid:v().optional().describe(`SQL type for UUID fields (e.g., UUID, CHAR(36))`),binary:v().optional().describe(`SQL type for binary fields (e.g., BLOB, BYTEA)`)})),fJ=X(()=>T({rejectUnauthorized:b().default(!0).describe(`Reject connections with invalid certificates`),ca:v().optional().describe(`CA certificate file path or content`),cert:v().optional().describe(`Client certificate file path or content`),key:v().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`}));X(()=>lJ.extend({type:j(`sql`).describe(`Driver type must be "sql"`),dialect:uJ.describe(`SQL database dialect`),dataTypeMapping:dJ.describe(`SQL data type mapping configuration`),ssl:b().default(!1).describe(`Enable SSL/TLS connection`),sslConfig:fJ.optional().describe(`SSL/TLS configuration (required when ssl is true)`)}).refine(e=>!(e.ssl&&!e.sslConfig),{message:`sslConfig is required when ssl is true`}));var pJ=X(()=>A([`mongodb`,`couchdb`,`dynamodb`,`cassandra`,`redis`,`elasticsearch`,`neo4j`,`orientdb`]));X(()=>A([`find`,`findOne`,`insert`,`update`,`delete`,`aggregate`,`mapReduce`,`count`,`distinct`,`createIndex`,`dropIndex`]));var mJ=X(()=>A([`all`,`quorum`,`one`,`local_quorum`,`each_quorum`,`eventual`])),hJ=X(()=>A([`single`,`compound`,`unique`,`text`,`geospatial`,`hashed`,`ttl`,`sparse`])),gJ=X(()=>T({enabled:b().default(!1).describe(`Enable sharding`),shardKey:v().optional().describe(`Field to use as shard key`),shardingStrategy:A([`hash`,`range`,`zone`]).optional().describe(`Sharding strategy`),numShards:y().int().positive().optional().describe(`Number of shards`)})),_J=X(()=>T({enabled:b().default(!1).describe(`Enable replication`),replicaSetName:v().optional().describe(`Replica set name`),replicas:y().int().positive().optional().describe(`Number of replicas`),readPreference:A([`primary`,`primaryPreferred`,`secondary`,`secondaryPreferred`,`nearest`]).optional().describe(`Read preference for replica set`),writeConcern:A([`majority`,`acknowledged`,`unacknowledged`]).optional().describe(`Write concern level`)})),vJ=X(()=>T({enabled:b().default(!1).describe(`Enable schema validation`),validationLevel:A([`strict`,`moderate`,`off`]).optional().describe(`Validation strictness`),validationAction:A([`error`,`warn`]).optional().describe(`Action on validation failure`),jsonSchema:k(v(),S()).optional().describe(`JSON Schema for validation`)})),yJ=X(()=>T({text:v().describe(`NoSQL type for text fields`),number:v().describe(`NoSQL type for number fields`),boolean:v().describe(`NoSQL type for boolean fields`),date:v().describe(`NoSQL type for date fields`),datetime:v().describe(`NoSQL type for datetime fields`),json:v().optional().describe(`NoSQL type for JSON/object fields`),uuid:v().optional().describe(`NoSQL type for UUID fields`),binary:v().optional().describe(`NoSQL type for binary fields`),array:v().optional().describe(`NoSQL type for array fields`),objectId:v().optional().describe(`NoSQL type for ObjectID fields (MongoDB)`),geopoint:v().optional().describe(`NoSQL type for geospatial point fields`)}));X(()=>lJ.extend({type:j(`nosql`).describe(`Driver type must be "nosql"`),databaseType:pJ.describe(`Specific NoSQL database type`),dataTypeMapping:yJ.describe(`NoSQL data type mapping configuration`),consistency:mJ.optional().describe(`Consistency level for operations`),replication:_J.optional().describe(`Replication configuration`),sharding:gJ.optional().describe(`Sharding configuration`),schemaValidation:vJ.optional().describe(`Document schema validation`),region:v().optional().describe(`AWS region (for managed NoSQL services)`),accessKeyId:v().optional().describe(`AWS access key ID`),secretAccessKey:v().optional().describe(`AWS secret access key`),ttlField:v().optional().describe(`Field name for TTL (auto-deletion)`),maxDocumentSize:y().int().positive().optional().describe(`Maximum document size in bytes`),collectionPrefix:v().optional().describe(`Prefix for collection/table names`)}));var bJ=X(()=>T({consistency:mJ.optional().describe(`Consistency level override`),readFromSecondary:b().optional().describe(`Allow reading from secondary replicas`),projection:k(v(),E([j(0),j(1)])).optional().describe(`Field projection`),timeout:y().int().positive().optional().describe(`Query timeout (ms)`),useCursor:b().optional().describe(`Use cursor instead of loading all results`),batchSize:y().int().positive().optional().describe(`Cursor batch size`),profile:b().optional().describe(`Enable query profiling`),hint:v().optional().describe(`Index hint for query optimization`)})),xJ=X(()=>T({operator:v().describe(`Aggregation operator (e.g., $match, $group, $sort)`),options:k(v(),S()).describe(`Stage-specific options`)}));X(()=>T({collection:v().describe(`Collection/table name`),stages:w(xJ).describe(`Aggregation pipeline stages`),options:bJ.optional().describe(`Query options`)})),X(()=>T({name:v().describe(`Index name`),type:hJ.describe(`Index type`),fields:w(T({field:v().describe(`Field name`),order:A([`asc`,`desc`,`text`,`2dsphere`]).optional().describe(`Index order or type`)})).describe(`Fields to index`),unique:b().default(!1).describe(`Enforce uniqueness`),sparse:b().default(!1).describe(`Sparse index`),expireAfterSeconds:y().int().positive().optional().describe(`TTL in seconds`),partialFilterExpression:k(v(),S()).optional().describe(`Partial index filter`),background:b().default(!1).describe(`Create index in background`)})),X(()=>T({readConcern:A([`local`,`majority`,`linearizable`,`snapshot`]).optional().describe(`Read concern level`),writeConcern:A([`majority`,`acknowledged`,`unacknowledged`]).optional().describe(`Write concern level`),readPreference:A([`primary`,`primaryPreferred`,`secondary`,`secondaryPreferred`,`nearest`]).optional().describe(`Read preference`),maxCommitTimeMS:y().int().positive().optional().describe(`Transaction commit timeout (ms)`)}));var SJ=A([`insert`,`update`,`upsert`,`replace`,`ignore`]),CJ=X(()=>T({object:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Target Object Name`),externalId:v().default(`name`).describe(`Field match for uniqueness check`),mode:SJ.default(`upsert`).describe(`Conflict resolution strategy`),env:w(A([`prod`,`dev`,`test`])).default([`prod`,`dev`,`test`]).describe(`Applicable environments`),records:w(k(v(),S())).describe(`Data records`)})),wJ=fK({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:`tags`,type:`tags`,colSpan:2,helpText:`Categorization tags (e.g. "sales", "system")`},{field:`active`,type:`boolean`,colSpan:1,helpText:`Is the object active and usable`},{field:`isSystem`,type:`boolean`,colSpan:1,helpText:`System object (protected from deletion)`},{field:`abstract`,type:`boolean`,colSpan:1,helpText:`Abstract base (cannot be instantiated)`}]},{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:`indexed`,type:`boolean`,helpText:`Create a database index for faster querying`},{field:`readonly`,type:`boolean`,helpText:`Visible but never user-editable`},{field:`immutable`,type:`boolean`,helpText:`Editable on create, locked thereafter`},{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:`filterable`,type:`boolean`,helpText:`Allow filtering on this column`},{field:`defaultValue`,type:`text`,helpText:`Default value for new records (JSON literal)`},{field:`placeholder`,type:`text`,helpText:`Placeholder hint`},{field:`maxLength`,type:`number`,helpText:`Max characters`,visibleOn:`type in ['text','textarea','email','url','phone','password','markdown','html','richtext']`},{field:`minLength`,type:`number`,helpText:`Min characters`,visibleOn:`type in ['text','textarea','email','url','phone','password','markdown','html','richtext']`},{field:`min`,type:`number`,helpText:`Minimum value`,visibleOn:`type in ['number','currency','percent','rating','slider','progress']`},{field:`max`,type:`number`,helpText:`Maximum value`,visibleOn:`type in ['number','currency','percent','rating','slider','progress']`},{field:`precision`,type:`number`,helpText:`Total digits`,visibleOn:`type in ['number','currency','percent']`},{field:`scale`,type:`number`,helpText:`Decimal places`,visibleOn:`type in ['number','currency','percent']`},{field:`options`,type:`repeater`,helpText:`Available choices`,visibleOn:`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`,visibleOn:`type in ['lookup','master_detail','tree']`},{field:`referenceFilter`,type:`code`,language:`expression`,helpText:`CEL filter applied to the picker`,visibleOn:`type in ['lookup','master_detail']`},{field:`cascadeDelete`,type:`boolean`,helpText:`Delete children when parent is deleted`,visibleOn:`type == 'master_detail'`},{field:`multiple`,type:`boolean`,helpText:`Allow selecting multiple records`,visibleOn:`type in ['lookup']`},{field:`formula`,type:`code`,language:`expression`,helpText:`CEL formula expression`,visibleOn:`type == 'formula'`},{field:`returnType`,type:`select`,helpText:`Result type for formulas`,visibleOn:`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:`summaryType`,type:`select`,helpText:`Aggregation`,visibleOn:`type == 'summary'`,options:[{label:`Count`,value:`count`},{label:`Sum`,value:`sum`},{label:`Avg`,value:`avg`},{label:`Min`,value:`min`},{label:`Max`,value:`max`}]},{field:`summaryField`,type:`text`,helpText:`Field on child object to aggregate`,visibleOn:`type == 'summary'`},{field:`displayFormat`,type:`text`,helpText:`e.g. "INV-{0000}"`,visibleOn:`type == 'autonumber'`},{field:`startingNumber`,type:`number`,helpText:`Starting sequence value`,visibleOn:`type == 'autonumber'`},{field:`language`,type:`text`,helpText:`Editor language (e.g. sql, javascript)`,visibleOn:`type == 'code'`},{field:`validation`,type:`code`,language:`expression`,helpText:`CEL predicate — must evaluate true`},{field:`errorMessage`,type:`text`,helpText:`Shown when validation fails`},{field:`audit`,type:`boolean`,helpText:`Audit changes to this field`},{field:`trackHistory`,type:`boolean`,helpText:`Keep change history`},{field:`pii`,type:`boolean`,helpText:`Personally identifiable information`},{field:`encrypted`,type:`boolean`,helpText:`Encrypt at rest`}]}]},{name:`capabilities`,label:`Capabilities`,description:`System features and API exposure.`,collapsible:!0,collapsed:!0,fields:[{field:`capabilities`,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:`trash`,type:`boolean`},{field:`mru`,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")`}]}]}),TJ=fK({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`,visibleOn:`data.type == 'text' || data.type == 'textarea' || data.type == 'email'`,helpText:`Minimum character length`},{field:`maxLength`,visibleOn:`data.type == 'text' || data.type == 'textarea' || data.type == 'email'`,helpText:`Maximum character length`},{field:`min`,visibleOn:`data.type == 'number' || data.type == 'currency'`,helpText:`Minimum value`},{field:`max`,visibleOn:`data.type == 'number' || data.type == 'currency'`,helpText:`Maximum value`},{field:`precision`,visibleOn:`data.type == 'currency' || data.type == 'number'`,helpText:`Decimal places (e.g., 2 for $10.50)`},{field:`scale`,visibleOn:`data.type == 'number'`,helpText:`Number of decimal digits`},{field:`options`,type:`repeater`,visibleOn:`data.type == 'select' || data.type == 'multiselect'`,helpText:`Available options (label/value pairs)`},{field:`reference`,widget:`ref:object`,visibleOn:`data.type == 'lookup' || data.type == 'master_detail'`,helpText:`Referenced object name`},{field:`referenceFilters`,widget:`string-tags`,visibleOn:`data.type == 'lookup' || data.type == 'master_detail'`,helpText:`Filter expressions (e.g., "active = true")`},{field:`deleteBehavior`,visibleOn:`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`,helpText:`Roll-up summary configuration (for parent-child relationships)`}]},{name:`advanced`,label:`Advanced`,description:`Database, UI, audit, and security settings.`,collapsible:!0,collapsed:!0,columns:2,fields:[{field:`columnName`,colSpan:2,helpText:`Physical column name in database (defaults to field name)`},{field:`index`,colSpan:1,helpText:`Create database index for faster queries`},{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`}]}]}),EJ=fK({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)`}]}]},{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)`}]}]}]}),DJ=X(()=>T({field:v().describe(`Source field name containing the reference value`),targetObject:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Target object name (snake_case)`),targetField:v().default(`name`).describe(`Field on target object used for matching`),fieldType:A([`lookup`,`master_detail`,`user`]).describe(`Relationship field type`)}).describe(`Describes how a field reference is resolved during seed loading`)),OJ=X(()=>T({object:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Object name (snake_case)`),dependsOn:w(v()).describe(`Objects this object depends on`),references:w(DJ).describe(`Field-level reference details`)}).describe(`Object node in the seed data dependency graph`)),kJ=X(()=>T({nodes:w(OJ).describe(`All objects in the dependency graph`),insertOrder:w(v()).describe(`Topologically sorted insert order`),circularDependencies:w(w(v())).default([]).describe(`Circular dependency chains (e.g., [["a", "b", "a"]])`)}).describe(`Complete object dependency graph for seed data loading`)),AJ=X(()=>T({sourceObject:v().describe(`Object with the broken reference`),field:v().describe(`Field name with unresolved reference`),targetObject:v().describe(`Target object searched for the reference`),targetField:v().describe(`ExternalId field used for matching`),attemptedValue:S().describe(`Value that failed to resolve`),recordIndex:y().int().min(0).describe(`Index of the record in the dataset`),message:v().describe(`Human-readable error description`)}).describe(`Actionable error for a failed reference resolution`)),jJ=T({user:T({id:v().min(1),role:v().optional(),email:v().optional()}).optional().describe(`Subject bound to os.user in seed CEL expressions`),org:T({id:v().min(1),tier:v().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`),MJ=X(()=>T({dryRun:b().default(!1).describe(`Validate references without writing data`),haltOnError:b().default(!1).describe(`Stop on first reference resolution error`),multiPass:b().default(!0).describe(`Enable multi-pass loading for circular dependencies`),defaultMode:SJ.default(`upsert`).describe(`Default conflict resolution strategy`),batchSize:y().int().min(1).default(1e3).describe(`Maximum records per batch insert/upsert`),transaction:b().default(!1).describe(`Wrap entire load in a transaction (all-or-nothing)`),env:A([`prod`,`dev`,`test`]).optional().describe(`Only load datasets matching this environment`),organizationId:v().min(1).optional().describe(`Target organization id for per-tenant seed replay`),identity:jJ.optional().describe(`Identity bound to os.user / os.org when resolving CEL seed values`)}).describe(`Seed data loader configuration`)),NJ=X(()=>T({object:v().describe(`Object that was loaded`),mode:SJ.describe(`Import mode used`),inserted:y().int().min(0).describe(`Records inserted`),updated:y().int().min(0).describe(`Records updated`),skipped:y().int().min(0).describe(`Records skipped`),errored:y().int().min(0).describe(`Records with errors`),total:y().int().min(0).describe(`Total records in dataset`),referencesResolved:y().int().min(0).describe(`References resolved via externalId`),referencesDeferred:y().int().min(0).describe(`References deferred to second pass`),errors:w(AJ).default([]).describe(`Reference resolution errors`)}).describe(`Result of loading a single dataset`));X(()=>T({success:b().describe(`Overall success status`),dryRun:b().describe(`Whether this was a dry-run`),dependencyGraph:kJ.describe(`Object dependency graph`),results:w(NJ).describe(`Per-object load results`),errors:w(AJ).describe(`All reference resolution errors`),summary:T({objectsProcessed:y().int().min(0).describe(`Total objects processed`),totalRecords:y().int().min(0).describe(`Total records across all objects`),totalInserted:y().int().min(0).describe(`Total records inserted`),totalUpdated:y().int().min(0).describe(`Total records updated`),totalSkipped:y().int().min(0).describe(`Total records skipped`),totalErrored:y().int().min(0).describe(`Total records with errors`),totalReferencesResolved:y().int().min(0).describe(`Total references resolved`),totalReferencesDeferred:y().int().min(0).describe(`Total references deferred`),circularDependencyCount:y().int().min(0).describe(`Circular dependency chains detected`),durationMs:y().min(0).describe(`Load duration in milliseconds`)}).describe(`Summary statistics`)}).describe(`Complete seed loader result`)),X(()=>T({seeds:w(CJ).min(1).describe(`Seeds to load`),config:MJ.default(()=>MJ.parse({})).describe(`Loader configuration`)}).describe(`Seed loader request with datasets and configuration`));var PJ=X(()=>T({versionNumber:y().describe(`Version number`),createdAt:y().describe(`Creation timestamp`),createdBy:v().describe(`Creator user ID`),size:y().describe(`File size in bytes`),checksum:v().describe(`File checksum`),downloadUrl:v().url().describe(`Download URL`),isLatest:b().optional().default(!1).describe(`Is latest version`)})),FJ=X(()=>T({id:v().describe(`Template ID`),name:v().describe(`Template name`),description:v().optional().describe(`Template description`),fileUrl:v().url().describe(`Template file URL`),fileType:v().describe(`File MIME type`),placeholders:w(T({key:v().describe(`Placeholder key`),label:v().describe(`Placeholder label`),type:A([`text`,`number`,`date`,`image`]).describe(`Placeholder type`),required:b().optional().default(!1).describe(`Is required`)})).describe(`Template placeholders`)})),IJ=X(()=>T({provider:A([`docusign`,`adobe-sign`,`hellosign`,`custom`]).describe(`E-signature provider`),enabled:b().optional().default(!1).describe(`E-signature enabled`),signers:w(T({email:v().email().describe(`Signer email`),name:v().describe(`Signer name`),role:v().describe(`Signer role`),order:y().describe(`Signing order`)})).describe(`Document signers`),expirationDays:y().optional().default(30).describe(`Expiration days`),reminderDays:y().optional().default(7).describe(`Reminder interval days`)}));X(()=>T({id:v().describe(`Document ID`),name:v().describe(`Document name`),description:v().optional().describe(`Document description`),fileType:v().describe(`File MIME type`),fileSize:y().describe(`File size in bytes`),category:v().optional().describe(`Document category`),tags:w(v()).optional().describe(`Document tags`),versioning:T({enabled:b().describe(`Versioning enabled`),versions:w(PJ).describe(`Version history`),majorVersion:y().describe(`Major version`),minorVersion:y().describe(`Minor version`)}).optional().describe(`Version control`),template:FJ.optional().describe(`Document template`),eSignature:IJ.optional().describe(`E-signature config`),access:T({isPublic:b().optional().default(!1).describe(`Public access`),sharedWith:w(v()).optional().describe(`Shared with`),expiresAt:y().optional().describe(`Access expiration`)}).optional().describe(`Access control`),metadata:k(v(),S()).optional().describe(`Custom metadata`)}));var LJ=X(()=>D(`type`,[T({type:j(`constant`),value:S().describe(`Constant value to use`)}).describe(`Set a constant value`),T({type:j(`cast`),targetType:A([`string`,`number`,`boolean`,`date`]).describe(`Target data type`)}).describe(`Cast to a specific data type`),T({type:j(`lookup`),table:v().describe(`Lookup table name`),keyField:v().describe(`Field to match on`),valueField:v().describe(`Field to retrieve`)}).describe(`Lookup value from another table`),T({type:j(`javascript`),expression:JH.describe(`JS expression (dialect="js" recommended). e.g. value.toUpperCase()`)}).describe(`Custom JavaScript transformation`),T({type:j(`map`),mappings:k(v(),S()).describe(`Value mappings (e.g., {"Active": "active"})`)}).describe(`Map values using a dictionary`)])),RJ=X(()=>T({source:v().describe(`Source field name`),target:v().describe(`Target field name`),transform:LJ.optional().describe(`Transformation to apply`),defaultValue:S().optional().describe(`Default if source is null/undefined`)})),zJ=X(()=>T({id:v().describe(`Data source ID`),name:v().describe(`Data source name`),type:A([`odata`,`rest-api`,`graphql`,`custom`]).describe(`Protocol type`),endpoint:v().url().describe(`API endpoint URL`),authentication:T({type:A([`oauth2`,`api-key`,`basic`,`none`]).describe(`Auth type`),config:k(v(),S()).describe(`Auth configuration`)}).describe(`Authentication`)})),BJ=X(()=>RJ.extend({type:v().optional().describe(`Field type`),readonly:b().optional().default(!0).describe(`Read-only field`)}));X(()=>T({fieldName:v().describe(`Field name`),dataSource:zJ.describe(`External data source`),query:T({endpoint:v().describe(`Query endpoint path`),method:A([`GET`,`POST`]).optional().default(`GET`).describe(`HTTP method`),parameters:k(v(),S()).optional().describe(`Query parameters`)}).describe(`Query configuration`),fieldMappings:w(BJ).describe(`Field mappings`),caching:T({enabled:b().optional().default(!0).describe(`Cache enabled`),ttl:y().optional().default(300).describe(`Cache TTL (seconds)`),strategy:A([`lru`,`lfu`,`ttl`]).optional().default(`ttl`).describe(`Cache strategy`)}).optional().describe(`Caching configuration`),fallback:T({enabled:b().optional().default(!0).describe(`Fallback enabled`),defaultValue:S().optional().describe(`Default fallback value`),showError:b().optional().default(!0).describe(`Show error to user`)}).optional().describe(`Fallback configuration`),rateLimit:T({requestsPerSecond:y().describe(`Requests per second limit`),burstSize:y().optional().describe(`Burst size`)}).optional().describe(`Rate limiting`),retry:T({maxRetries:y().min(0).default(3).describe(`Maximum retry attempts`),initialDelayMs:y().default(1e3).describe(`Initial retry delay in milliseconds`),maxDelayMs:y().default(3e4).describe(`Maximum retry delay in milliseconds`),backoffMultiplier:y().default(2).describe(`Exponential backoff multiplier`),retryableStatusCodes:w(y()).default([429,500,502,503,504]).describe(`HTTP status codes that are retryable`)}).optional().describe(`Retry configuration with exponential backoff`),transform:T({request:T({headers:k(v(),v()).optional().describe(`Additional request headers`),queryParams:k(v(),v()).optional().describe(`Additional query parameters`)}).optional().describe(`Request transformation`),response:T({dataPath:v().optional().describe(`JSONPath to extract data (e.g., "$.data.results")`),totalPath:v().optional().describe(`JSONPath to extract total count (e.g., "$.meta.total")`)}).optional().describe(`Response transformation`)}).optional().describe(`Request/response transformation pipeline`),pagination:T({type:A([`offset`,`cursor`,`page`]).default(`offset`).describe(`Pagination type`),pageSize:y().default(100).describe(`Items per page`),maxPages:y().optional().describe(`Maximum number of pages to fetch`)}).optional().describe(`Pagination configuration for external data`)}));var VJ=v().describe(`Underlying driver identifier`);X(()=>T({id:v().describe(`Unique driver identifier (e.g. "postgres")`),label:v().describe(`Display label (e.g. "PostgreSQL")`),description:v().optional(),icon:v().optional(),configSchema:k(v(),S()).describe(`JSON Schema for connection configuration`),capabilities:M(()=>HJ).optional()}));var HJ=T({transactions:b().default(!1),queryFilters:b().default(!1),queryAggregations:b().default(!1),querySorting:b().default(!1),queryPagination:b().default(!1),queryWindowFunctions:b().default(!1),querySubqueries:b().default(!1),joins:b().default(!1),fullTextSearch:b().default(!1),readOnly:b().default(!1),dynamicSchema:b().default(!1)}),UJ=A([`managed`,`external`,`validate-only`]).describe(`Schema ownership mode`),WJ=T({label:v().optional().describe(`Display label, e.g. "Snowflake — ANALYTICS / PROD"`),allowedSchemas:w(v()).optional().describe(`Whitelist of remote schemas/databases that may be exposed.`),allowWrites:b().default(!1).describe(`Global write gate. Individual objects must also opt in via object.external.writable.`),validation:T({onMismatch:A([`fail`,`warn`,`ignore`]).default(`fail`).describe(`What to do when a federated object diverges from the remote table.`),checkOnBoot:b().default(!0).describe(`Validate federated objects against the remote schema at boot.`),checkIntervalMs:y().optional().describe(`Optional background drift-check interval in milliseconds.`)}).default({onMismatch:`fail`,checkOnBoot:!0}).describe(`Boot/drift validation policy`),credentialsRef:v().optional().describe(`Reference into the secrets store; never inline credentials.`),queryTimeoutMs:y().default(3e4).describe(`Hard cap on per-query execution time.`),requirePermission:v().optional().describe(`Optional convenience: gate the entire datasource behind a single role.`)}).describe(`External datasource federation settings (schemaMode != "managed")`);X(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Unique datasource identifier`),label:v().optional().describe(`Display label`),driver:VJ.describe(`Underlying driver type`),config:k(v(),S()).describe(`Driver specific configuration`),pool:T({min:y().default(0).describe(`Minimum connections`),max:y().default(10).describe(`Maximum connections`),idleTimeoutMillis:y().default(3e4).describe(`Idle timeout`),connectionTimeoutMillis:y().default(3e3).describe(`Connection establishment timeout`)}).optional().describe(`Connection pool settings`),readReplicas:w(k(v(),S())).optional().describe(`Read-only replica configurations`),capabilities:HJ.optional().describe(`Capability overrides`),healthCheck:T({enabled:b().default(!0).describe(`Enable health check endpoint`),intervalMs:y().default(3e4).describe(`Health check interval in milliseconds`),timeoutMs:y().default(5e3).describe(`Health check timeout in milliseconds`)}).optional().describe(`Datasource health check configuration`),ssl:T({enabled:b().default(!1).describe(`Enable SSL/TLS for database connection`),rejectUnauthorized:b().default(!0).describe(`Reject connections with invalid/self-signed certificates`),ca:v().optional().describe(`CA certificate (PEM format or path to file)`),cert:v().optional().describe(`Client certificate (PEM format or path to file)`),key:v().optional().describe(`Client private key (PEM format or path to file)`)}).optional().describe(`SSL/TLS configuration for secure database connections`),retryPolicy:T({maxRetries:y().default(3).describe(`Maximum number of retry attempts`),baseDelayMs:y().default(1e3).describe(`Base delay between retries in milliseconds`),maxDelayMs:y().default(3e4).describe(`Maximum delay between retries in milliseconds`),backoffMultiplier:y().default(2).describe(`Exponential backoff multiplier`)}).optional().describe(`Connection retry policy for transient failures`),description:v().optional().describe(`Internal description`),active:b().default(!0).describe(`Is datasource enabled`),autoConnect:b().default(!1).describe(`Force a live driver connection at boot even when managed + unrouted (ADR-0062 D2).`),schemaMode:UJ.default(`managed`),external:WJ.optional(),origin:A([`code`,`runtime`]).default(`code`).describe(`Datasource provenance (server-managed, read-only)`)}).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'.`})}));var GJ=T({name:v().describe(`Remote column name`),sqlType:v().describe(`Raw remote SQL type (e.g. "numeric(10,2)")`),nullable:b().describe(`Whether the remote column is nullable`),primaryKey:b().default(!1).describe(`Part of the remote primary key`),suggestedFieldType:v().optional().describe(`ObjectStack field type suggested by the type-compat matrix`)}),KJ=T({remoteSchema:v().optional().describe(`Remote schema/database qualifier`),remoteName:v().describe(`Remote table/view name`),columns:w(GJ).describe(`Remote columns`),indexes:w(T({name:v(),columns:w(v()),unique:b()})).optional().describe(`Remote indexes, when introspectable`),rowCountEstimate:y().optional().describe(`Approximate row count`)});X(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe("Catalog id, conventionally `<datasource>_catalog`."),datasource:v().describe(`Datasource.name this catalog snapshots.`),snapshotAt:v().datetime().describe(`When the snapshot was taken (ISO 8601).`),dialect:v().optional().describe(`Remote SQL dialect, when known.`),tables:w(KJ).describe(`Snapshotted remote tables.`)}));var qJ=A([`count`,`sum`,`avg`,`min`,`max`,`count_distinct`,`number`,`string`,`boolean`]),JJ=A([`string`,`number`,`boolean`,`time`,`geo`]),YJ=A([`second`,`minute`,`hour`,`day`,`week`,`month`,`quarter`,`year`]),XJ=X(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Unique metric ID`),label:v().describe(`Human readable label`),description:v().optional(),type:qJ,sql:v().describe(`SQL expression or field reference`),filters:w(T({sql:v()})).optional(),format:v().optional()})),ZJ=X(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Unique dimension ID`),label:v().describe(`Human readable label`),description:v().optional(),type:JJ,sql:v().describe(`SQL expression or column reference`),granularities:w(YJ).optional()})),QJ=X(()=>T({name:v().describe(`Target cube name`),relationship:A([`one_to_one`,`one_to_many`,`many_to_one`]).default(`many_to_one`),sql:v().describe(`Join condition (ON clause)`)}));X(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Cube name (snake_case)`),title:v().optional(),description:v().optional(),sql:v().describe(`Base SQL statement or Table Name`),measures:k(v(),XJ).describe(`Quantitative metrics`),dimensions:k(v(),ZJ).describe(`Qualitative attributes`),joins:k(v(),QJ).optional(),refreshKey:T({every:v().optional(),sql:v().optional()}).optional(),public:b().default(!1)})),X(()=>T({cube:v().optional().describe(`Target cube name (optional when provided externally, e.g. in API request wrapper)`),measures:w(v()).describe(`List of metrics to calculate`),dimensions:w(v()).optional().describe(`List of dimensions to group by`),where:sq.optional().describe(`Filtering criteria (canonical Query DSL FilterCondition)`),timeDimensions:w(T({dimension:v(),granularity:YJ.optional(),dateRange:E([v(),w(v())]).optional()})).optional(),order:k(v(),A([`asc`,`desc`])).optional(),limit:y().optional(),offset:y().optional(),timezone:v().optional().default(`UTC`)}));var $J=A([`comment`,`field_change`,`task`,`event`,`email`,`call`,`note`,`file`,`record_create`,`record_delete`,`approval`,`sharing`,`system`]),eY=X(()=>T({type:A([`user`,`team`,`record`]).describe(`Mention target type`),id:v().describe(`Target ID`),name:v().describe(`Display name for rendering`),offset:y().int().min(0).describe(`Character offset in body text`),length:y().int().min(1).describe(`Length of mention token in body text`)})),tY=X(()=>T({field:v().describe(`Field machine name`),fieldLabel:v().optional().describe(`Field display label`),oldValue:S().optional().describe(`Previous value`),newValue:S().optional().describe(`New value`),oldDisplayValue:v().optional().describe(`Human-readable old value`),newDisplayValue:v().optional().describe(`Human-readable new value`)})),nY=X(()=>T({emoji:v().describe(`Emoji character or shortcode (e.g., "👍", ":thumbsup:")`),userIds:w(v()).describe(`Users who reacted`),count:y().int().min(1).describe(`Total reaction count`)})),rY=X(()=>T({type:A([`user`,`system`,`service`,`automation`]).describe(`Actor type`),id:v().describe(`Actor ID`),name:v().optional().describe(`Actor display name`),avatarUrl:v().url().optional().describe(`Actor avatar URL`),source:v().optional().describe(`Source application (e.g., "Omni", "API", "Studio")`)})),iY=A([`public`,`internal`,`private`]);X(()=>T({id:v().describe(`Feed item ID`),type:$J.describe(`Activity type`),object:v().describe(`Object name (e.g., "account")`),recordId:v().describe(`Record ID this feed item belongs to`),actor:rY.describe(`Who performed this action`),body:v().optional().describe(`Rich text body (Markdown supported)`),mentions:w(eY).optional().describe(`Mentioned users/teams/records`),changes:w(tY).optional().describe(`Field-level changes`),reactions:w(nY).optional().describe(`Emoji reactions on this item`),parentId:v().optional().describe(`Parent feed item ID for threaded replies`),replyCount:y().int().min(0).default(0).describe(`Number of replies`),pinned:b().default(!1).describe(`Whether the feed item is pinned to the top of the timeline`),pinnedAt:v().datetime().optional().describe(`Timestamp when the item was pinned`),pinnedBy:v().optional().describe(`User ID who pinned the item`),starred:b().default(!1).describe(`Whether the feed item is starred/bookmarked by the current user`),starredAt:v().datetime().optional().describe(`Timestamp when the item was starred`),visibility:iY.default(`public`).describe(`Visibility: public (all users), internal (team only), private (author + mentioned)`),createdAt:v().datetime().describe(`Creation timestamp`),updatedAt:v().datetime().optional().describe(`Last update timestamp`),editedAt:v().datetime().optional().describe(`When comment was last edited`),isEdited:b().default(!1).describe(`Whether comment has been edited`)}));var aY=A([`all`,`comments_only`,`changes_only`,`tasks_only`]),oY=A([`comment`,`mention`,`field_change`,`task`,`approval`,`all`]),sY=A([`in_app`,`email`,`push`,`slack`]);X(()=>T({object:v().describe(`Object name`),recordId:v().describe(`Record ID`),userId:v().describe(`Subscribing user ID`),events:w(oY).default([`all`]).describe(`Event types to receive notifications for`),channels:w(sY).default([`in_app`]).describe(`Notification delivery channels`),active:b().default(!0).describe(`Whether the subscription is active`),createdAt:v().datetime().describe(`Subscription creation timestamp`)}));var cY=X(()=>A([`bar`,`horizontal-bar`,`column`,`line`,`area`,`pie`,`donut`,`funnel`,`scatter`,`treemap`,`sankey`,`gauge`,`solid-gauge`,`metric`,`kpi`,`bullet`,`radar`,`table`,`pivot`])),lY=X(()=>T({field:v().describe(`Data field key`),title:Q.optional().describe(`Axis display title`),format:v().optional().describe(`Value format string (e.g., "$0,0.00")`),min:y().optional().describe(`Minimum value`),max:y().optional().describe(`Maximum value`),stepSize:y().optional().describe(`Step size for ticks`),showGridLines:b().default(!0),position:A([`left`,`right`,`top`,`bottom`]).optional().describe(`Axis position`),logarithmic:b().default(!1)})),uY=X(()=>T({name:v().describe(`Field name or series identifier`),label:Q.optional().describe(`Series display label`),type:cY.optional().describe(`Override chart type for this series`),color:v().optional().describe(`Series color (hex/rgb/token)`),stack:v().optional().describe(`Stack identifier to group series`),yAxis:A([`left`,`right`]).default(`left`).describe(`Bind to specific Y-Axis`),variant:A([`primary`,`comparison`]).default(`primary`).optional().describe(`Series visual role`),dashArray:v().optional().describe(`SVG stroke-dasharray override`),opacity:y().min(0).max(1).optional().describe(`Series opacity override`)})),dY=X(()=>T({type:A([`line`,`region`]).default(`line`),axis:A([`x`,`y`]).default(`y`),value:E([y(),v()]).describe(`Start value`),endValue:E([y(),v()]).optional().describe(`End value for regions`),color:v().optional(),label:Q.optional(),style:A([`solid`,`dashed`,`dotted`]).default(`dashed`)})),fY=X(()=>T({tooltips:b().default(!0),zoom:b().default(!1),brush:b().default(!1),clickAction:v().optional().describe(`Action ID to trigger on click`)})),pY=X(()=>T({type:cY,title:Q.optional().describe(`Chart title`),subtitle:Q.optional().describe(`Chart subtitle`),description:Q.optional().describe(`Accessibility description`),xAxis:lY.optional().describe(`X-Axis configuration`),yAxis:w(lY).optional().describe(`Y-Axis configuration (support dual axis)`),series:w(uY).optional().describe(`Defined series configuration`),colors:E([w(v()),k(v(),v())]).optional().describe(`Color palette (string[]) or value→color map ({ value: color })`),height:y().optional().describe(`Fixed height in pixels`),showLegend:b().default(!0).describe(`Display legend`),showDataLabels:b().default(!1).describe(`Display data labels`),annotations:w(dY).optional(),interaction:fY.optional(),aria:$.optional().describe(`ARIA accessibility attributes`)})),mY=T({id:Z.describe(`Unique identifier for this navigation item (lowercase snake_case)`),label:Q.describe(`Display proper label`),icon:v().optional().describe(`Icon name`),order:y().optional().describe(`Sort order within the same level (lower = first)`),badge:E([v(),y()]).optional().describe(`Badge text or count displayed on the item`),visible:JH.optional().describe("Visibility predicate (CEL). e.g. P`'org_admin' in current_user.roles`"),requiredPermissions:w(v()).optional().describe(`Permissions required to access this item`),requiresObject:v().optional().describe(`Hide/disable this entry unless the named object is registered in the runtime`),requiresService:v().optional().describe(`Hide/disable this entry unless the named kernel service is registered`)}),hY=X(()=>mY.extend({type:j(`object`),objectName:v().describe(`Target object name`),viewName:v().optional().describe('Default list view to open. Defaults to "all". Ignored when `recordId` is set.'),recordId:v().optional().describe(`Navigate directly to this record id instead of the list view. Supports template vars: {current_user_id}, {current_org_id}.`),recordMode:A([`view`,`edit`]).optional().describe("Open the record in view (default) or edit mode. Only meaningful when `recordId` is set.")})),gY=X(()=>mY.extend({type:j(`dashboard`),dashboardName:v().describe(`Target dashboard name`)})),_Y=X(()=>mY.extend({type:j(`page`),pageName:v().describe(`Target custom page component name`),params:k(v(),S()).optional().describe(`Parameters passed to the page context`)})),vY=X(()=>mY.extend({type:j(`url`),url:v().describe(`Target external URL`),target:A([`_self`,`_blank`]).default(`_self`).describe(`Link target window`)})),yY=X(()=>mY.extend({type:j(`report`),reportName:v().describe(`Target report name`)})),bY=X(()=>mY.extend({type:j(`action`),actionDef:T({actionName:v().describe(`Action machine name to execute`),params:k(v(),S()).optional().describe(`Parameters passed to the action`)}).describe(`Action definition to execute when clicked`)})),xY=X(()=>mY.extend({type:j(`component`),componentRef:v().describe(`Component registry key (e.g. "metadata:directory")`),params:k(v(),S()).optional().describe(`Props passed to the component`)})),SY=X(()=>mY.extend({type:j(`group`),expanded:b().default(!1).describe(`Default expansion state in sidebar`)})),CY=M(()=>E([hY.extend({children:w(CY).optional().describe(`Child navigation items (e.g. specific views)`)}),gY,_Y,vY,yY,bY,xY,SY.extend({children:w(CY).describe(`Child navigation items`)})]));X(()=>T({app:Z.describe(`Target app name to contribute navigation into (e.g. "setup")`),group:Z.optional().describe(`Target group nav-item id to append into (e.g. "group_integrations"); omit to append at the app top level`),priority:y().int().min(0).default(200).describe(`Merge priority within the target group — lower applied first (matches object extender priority)`),items:w(CY).describe(`Navigation items contributed into the target app/group`)}).describe(`A navigation contribution: a package injecting nav items into an app it does not own (ADR-0029 D7)`));var wY=X(()=>T({primaryColor:v().optional().describe(`Primary theme color hex code`),logo:v().optional().describe(`Custom logo URL for this app`),favicon:v().optional().describe(`Custom favicon URL for this app`)})),TY=X(()=>T({id:Z.describe(`Unique area identifier (lowercase snake_case)`),label:Q.describe(`Area display label`),icon:v().optional().describe(`Area icon name`),order:y().optional().describe(`Sort order among areas (lower = first)`),description:Q.optional().describe(`Area description`),visible:JH.optional().describe(`Visibility predicate (CEL) for this area.`),requiredPermissions:w(v()).optional().describe(`Permissions required to access this area`),navigation:w(CY).describe(`Navigation items within this area`)})),EY=X(()=>T({id:Z.describe(`Selector id; selected value is exposed as the nav template var {<id>}`),label:Q.describe(`Dropdown label`),icon:v().optional().describe(`Icon name`),optionsSource:T({endpoint:v().describe(`REST endpoint returning the option rows (e.g. /api/v1/packages)`),valueKey:v().default(`id`).describe(`Row property used as the option value (dotted path allowed, e.g. "manifest.id")`),labelKey:v().default(`name`).describe(`Row property used as the option label (dotted path allowed, e.g. "manifest.name")`),filter:w(T({key:v().describe(`Dotted path on each row to compare (e.g. "manifest.scope")`),op:A([`eq`,`ne`,`in`,`nin`]).default(`eq`).describe(`Comparison operator: eq | ne | in | nin`),value:E([v(),w(v())]).describe(`Comparison value (string for eq/ne, string[] for in/nin)`)})).optional().describe(`Predicates (AND) each option row must satisfy`)}).describe(`Option data source`),includeAll:b().default(!0).describe(`Prepend an "All" option that clears the scope`),allValue:v().default(``).describe(`Template value when "All" is selected (empty = no filter)`),persist:A([`query`,`session`,`none`]).default(`query`).describe(`Persist selection via URL query, sessionStorage, or not at all`),placement:A([`sidebar_header`,`topbar`]).default(`sidebar_header`).describe(`Render location in the app chrome`)}));X(()=>T({name:Z.describe(`App unique machine name (lowercase snake_case)`),label:Q.describe(`App display label`),version:v().optional().describe(`App version`),description:Q.optional().describe(`App description`),icon:v().optional().describe(`App icon used in the App Launcher`),branding:wY.optional().describe(`App-specific branding`),active:b().optional().default(!0).describe(`Whether the app is enabled`),isDefault:b().optional().default(!1).describe(`Is default app`),hidden:b().optional().describe(`Hide from the App Switcher; the shell surfaces hidden apps via the avatar menu instead`),navigation:w(CY).optional().describe(`Full navigation tree for the app sidebar`),areas:w(TY).optional().describe(`Navigation areas for partitioning navigation by business domain`),contextSelectors:w(EY).optional().describe(`App-level scope dropdowns whose value is injected into nav items as {<id>} template vars`),homePageId:v().optional().describe(`ID of the navigation item to serve as landing page`),requiredPermissions:w(v()).optional().describe(`Permissions required to access this app`),objects:w(S()).optional().describe(`Objects belonging to this app`),apis:w(S()).optional().describe(`Custom APIs belonging to this app`),sharing:SG.optional().describe(`Public sharing configuration`),embed:CG.optional().describe(`Iframe embedding configuration`),mobileNavigation:T({mode:A([`drawer`,`bottom_nav`,`hamburger`]).default(`drawer`).describe(`Mobile navigation mode: drawer sidebar, bottom navigation bar, or hamburger menu`),bottomNavItems:w(v()).optional().describe(`Navigation item IDs to show in bottom nav (max 5)`)}).optional().describe(`Mobile-specific navigation configuration`),defaultAgent:Z.optional().describe(`Name of the default AI agent for this app (used by the ambient chat endpoint)`),aria:$.optional().describe(`ARIA accessibility attributes for the application`),protection:xG.optional().describe(`Package author protection block — lock policy for this app.`),...bG}));var DY=X(()=>A([`default`,`blue`,`teal`,`orange`,`purple`,`success`,`warning`,`danger`]).describe(`Widget color variant`)),OY=X(()=>A([`script`,`url`,`modal`,`flow`,`api`]).describe(`Widget action type`)),kY=X(()=>T({label:Q.describe(`Action button label`),actionUrl:v().describe(`URL or target for the action`),actionType:OY.optional().describe(`Type of action`),icon:v().optional().describe(`Icon identifier for the action button`)}).describe(`Dashboard header action`)),AY=X(()=>T({showTitle:b().default(!0).describe(`Show dashboard title in header`),showDescription:b().default(!0).describe(`Show dashboard description in header`),actions:w(kY).optional().describe(`Header action buttons`)}).describe(`Dashboard header configuration`)),jY=X(()=>T({id:Z.describe(`Unique widget identifier (snake_case)`),title:Q.optional().describe(`Widget title`),description:Q.optional().describe(`Widget description text below the header`),type:cY.default(`metric`).describe(`Visualization type`),chartConfig:pY.optional().describe(`Chart visualization configuration`),colorVariant:DY.optional().describe(`Widget color variant for theming`),requiresObject:v().optional().describe(`Hide the widget unless the named object is registered`),requiresService:v().optional().describe(`Hide the widget unless the named kernel service is registered`),actionUrl:v().optional().describe(`URL or target for the widget action button`),actionType:OY.optional().describe(`Type of action for the widget action button`),actionIcon:v().optional().describe(`Icon identifier for the widget action button`),filter:sq.optional().describe(`Presentation-scope filter (runtimeFilter)`),compareTo:E([j(`previousPeriod`),j(`previousYear`),T({offset:v().regex(/^\d+[dwMy]$/,`Offset must match <N>(d|w|M|y), e.g. "7d", "1M", "1y"`)})]).optional().describe(`Period-over-period comparison window`),dataset:Z.describe(`Dataset name to bind (ADR-0021)`),dimensions:w(v()).optional().describe(`Dimension names — X/group/split`),values:w(v()).min(1).describe(`Measure names — Y (at least one)`),layout:T({x:y(),y:y(),w:y(),h:y()}).optional().describe(`Grid layout position (auto-flowed when omitted)`),options:S().optional().describe(`Widget specific configuration`),suppressWarnings:w(v()).optional().describe(`Build diagnostic rule ids suppressed on this widget`),responsive:DG.optional().describe(`Responsive layout configuration`),aria:$.optional().describe(`ARIA accessibility attributes`)})),MY=X(()=>T({object:v().describe(`Source object name`),valueField:v().describe(`Field to use as option value`),labelField:v().describe(`Field to use as option label`),filter:sq.optional().describe(`Filter to apply to source object`)}).describe(`Dynamic filter options from object`)),NY=X(()=>T({field:v().describe(`Field name to filter on`),label:Q.optional().describe(`Display label for the filter`),type:A([`text`,`select`,`date`,`number`,`lookup`]).optional().describe(`Filter input type`),options:w(T({value:E([v(),y(),b()]).describe(`Option value`),label:Q})).optional().describe(`Static filter options`),optionsFrom:MY.optional().describe(`Dynamic filter options from object`),defaultValue:E([v(),y(),b()]).optional().describe(`Default filter value`),scope:A([`dashboard`,`widget`]).default(`dashboard`).describe(`Filter application scope`),targetWidgets:w(v()).optional().describe(`Widget IDs to apply this filter to`)}));X(()=>T({name:Z.describe(`Dashboard unique name`),label:Q.describe(`Dashboard label`),description:Q.optional().describe(`Dashboard description`),header:AY.optional().describe(`Dashboard header configuration`),widgets:w(jY).describe(`Widgets to display`),columns:y().int().min(1).max(24).optional().describe(`Number of grid columns (default 12)`),gap:y().int().min(0).optional().describe(`Grid gap in Tailwind spacing units`),refreshInterval:y().optional().describe(`Auto-refresh interval in seconds`),dateRange:T({field:v().optional().describe(`Default date field name for time-based filtering`),defaultRange:A([`today`,`yesterday`,`this_week`,`last_week`,`this_month`,`last_month`,`this_quarter`,`last_quarter`,`this_year`,`last_year`,`last_7_days`,`last_30_days`,`last_90_days`,`custom`]).default(`this_month`).describe(`Default date range preset`),allowCustomRange:b().default(!0).describe(`Allow users to pick a custom date range`)}).optional().describe(`Global dashboard date range filter configuration`),globalFilters:w(NY).optional().describe(`Global filters that apply to all widgets in the dashboard`),aria:$.optional().describe(`ARIA accessibility attributes`),performance:AG.optional().describe(`Performance optimization settings`),protection:xG.optional().describe(`Package author protection block — lock policy for this dashboard.`),...bG}));var PY=A([`tabular`,`summary`,`matrix`,`joined`]);X(()=>T({field:v().describe(`Field name`),label:Q.optional().describe(`Override label`),aggregate:A([`sum`,`avg`,`max`,`min`,`count`,`unique`]).optional().describe(`Aggregation function`),responsive:DG.optional().describe(`Responsive visibility for this column`)})),X(()=>T({field:v().describe(`Field to group by`),sortOrder:A([`asc`,`desc`]).default(`asc`),dateGranularity:A([`day`,`week`,`month`,`quarter`,`year`]).optional().describe(`For date fields`)}));var FY=X(()=>pY.extend({xAxis:v().describe(`Grouping field for X-Axis`),yAxis:v().describe(`Summary field for Y-Axis`),groupBy:v().optional().describe(`Additional grouping field`)})),IY=X(()=>T({name:Z,label:Q.optional(),description:Q.optional(),type:A([`tabular`,`summary`,`matrix`]).default(`tabular`),chart:FY.optional(),dataset:Z.optional().describe(`Dataset name to bind (ADR-0021)`),rows:w(v()).optional().describe(`Dimension names down (dataset-bound)`),columns:w(v()).optional().describe(`Dimension names across (matrix, dataset-bound)`),values:w(v()).optional().describe(`Measure names to show (dataset-bound)`),runtimeFilter:sq.optional().describe(`Render-time scope filter (dataset-bound)`)}));X(()=>T({name:Z.describe(`Report unique name`),label:Q.describe(`Report label`),description:Q.optional(),type:PY.default(`tabular`).describe(`Report format type`),dataset:Z.optional().describe(`Dataset name to bind (ADR-0021)`),rows:w(v()).optional().describe(`Dimension names down`),columns:w(v()).optional().describe(`Dimension names across (matrix)`),values:w(v()).optional().describe(`Measure names to show`),runtimeFilter:sq.optional().describe(`Render-time scope filter`),drilldown:b().default(!0).describe(`Click-through to underlying records`),chart:FY.optional().describe(`Embedded chart configuration`),aria:$.optional().describe(`ARIA accessibility attributes`),performance:AG.optional().describe(`Performance optimization settings`),blocks:w(IY).optional().describe(`Sub-reports for type=joined`),protection:xG.optional().describe(`Package author protection block — lock policy for this report.`),...bG}).superRefine((e,t)=>{e.type===`joined`?(!e.blocks||e.blocks.length===0)&&t.addIssue({code:`custom`,message:"a `joined` report needs `blocks`.",path:[`blocks`]}):(!e.dataset||!e.values||e.values.length===0)&&t.addIssue({code:`custom`,message:"a report needs `dataset` + `values` (measure names).",path:[`dataset`]})}));var LY=X(()=>T({name:Z.describe(`Dimension name — referenced by presentations`),label:Q.optional(),field:v().describe("Base field, or `relationship[.relationship].field` path"),type:A([`string`,`number`,`date`,`boolean`,`lookup`]).optional(),dateGranularity:dq.optional()})),RY=A([`ratio`,`sum`,`difference`,`product`]),zY=X(()=>T({name:Z.describe(`Measure name — e.g. "revenue"; defined once`),label:Q.optional(),aggregate:uq.optional().describe("Aggregation (sum/avg/count/...); omit when `derived` is set"),field:v().optional().describe(`Aggregated field; optional for count(*)`),filter:sq.optional(),format:v().optional(),currency:v().length(3).optional().describe(`Display currency code (ISO 4217)`),certified:b().default(!1).describe(`Blessed metric (governance checkpoint)`),derived:T({op:RY,of:w(Z).min(1)}).optional()}));X(()=>T({name:Z.describe(`Dataset unique name`),label:Q.describe(`Dataset label`),description:Q.optional(),object:v().describe(`Base object name`),include:w(v().refine(e=>e.split(`.`).length<=3,{message:`include path exceeds the 3-hop limit (ADR-0071)`})).optional().describe(`Relationship names/paths to join (derived from object graph; max 3 hops)`),filter:sq.optional().describe(`Intrinsic dataset scope filter`),dimensions:w(LY).describe(`Groupable axes`),measures:w(zY).describe(`Aggregatable values`),protection:xG.optional().describe(`Package author protection block — lock policy for this dataset.`),...bG}).superRefine((e,t)=>{let n=new Set;for(let r of e.measures)n.has(r.name)&&t.addIssue({code:`custom`,message:`duplicate measure name "${r.name}"`,path:[`measures`]}),n.add(r.name);let r=new Set;for(let n of e.dimensions)r.has(n.name)&&t.addIssue({code:`custom`,message:`duplicate dimension name "${n.name}"`,path:[`dimensions`]}),r.add(n.name);for(let r of e.measures){if(!r.derived){r.aggregate?!r.field&&r.aggregate!==`count`&&t.addIssue({code:`custom`,message:`measure "${r.name}" requires \`field\` (only \`count\` may omit it)`,path:[`measures`]}):t.addIssue({code:`custom`,message:`measure "${r.name}" requires \`aggregate\` (or a \`derived\` spec)`,path:[`measures`]});continue}for(let e of r.derived.of)e===r.name?t.addIssue({code:`custom`,message:`derived measure "${r.name}" cannot reference itself`,path:[`measures`]}):n.has(e)||t.addIssue({code:`custom`,message:`derived measure "${r.name}" references unknown measure "${e}"`,path:[`measures`]})}}));var BY=fK({schemaId:`report`,type:`simple`,sections:[{label:`Basics`,description:`Identity and report type.`,columns:2,fields:[{field:`name`,type:`text`,colSpan:1,required:!0,helpText:`snake_case unique identifier`},{field:`label`,type:`text`,colSpan:1,required:!0},{field:`description`,type:`textarea`,colSpan:2},{field:`type`,colSpan:2,helpText:`Report type: tabular/summary/matrix/joined`}]},{label:`Dataset binding`,description:`The semantic-layer dataset this report renders. Values are the dataset’s measures; rows are its dimensions.`,visibleOn:`data.type != 'joined'`,fields:[{field:`dataset`,widget:`ref:dataset`,helpText:`Dataset to bind (measures/dimensions come from its semantic layer)`},{field:`values`,widget:`string-tags`,helpText:`Measure names (from the dataset) to display`},{field:`rows`,widget:`string-tags`,helpText:`Dimension names (from the dataset) to group rows by`},{field:`columns`,widget:`string-tags`,visibleOn:`data.type == 'matrix'`,helpText:`Dimension names across (matrix only)`},{field:`drilldown`,helpText:`Click an aggregated row/cell to open the underlying records`}]},{label:`Joined blocks`,description:`Additional dataset-bound blocks stacked into a single report (joined reports only).`,visibleOn:`data.type == 'joined'`,fields:[{field:`blocks`,type:`repeater`,helpText:`Dataset-bound sub-reports (joined report only)`}]},{label:`Filter & chart`,description:`Render-time scope filter and chart presentation.`,collapsible:!0,collapsed:!0,fields:[{field:`runtimeFilter`,widget:`json`,helpText:`Render-time scope filter, ANDed at query time`},{field:`chart`,type:`composite`,helpText:`Chart config (type, legend, colors)`}]},{label:`Advanced`,description:`Accessibility and performance tuning.`,collapsible:!0,collapsed:!0,fields:[{field:`aria`,type:`composite`,helpText:`Accessibility labels`},{field:`performance`,type:`composite`,helpText:`Caching and optimization`}]}]}),VY=fK({schemaId:`view`,type:`simple`,sections:[{name:`basics`,label:`Basics`,description:`Identity and primary surface.`,columns:2,fields:[{field:`name`,type:`text`,required:!0,colSpan:1,helpText:`snake_case, unique per environment`},{field:`label`,type:`text`,required:!0,colSpan:1},{field:`description`,type:`textarea`,colSpan:2},{field:`type`,required:!0,colSpan:1,helpText:`Primary view surface`},{field:`data`,widget:`json`,colSpan:2,helpText:`Data source — e.g. {"provider":"object","object":"task"}`}]},{name:`columns_filters`,label:`Columns & filters`,description:`What rows show and how users filter them.`,fields:[{field:`columns`,type:`repeater`,required:!0,helpText:`Columns to display (field names from selected object)`},{field:`filter`,type:`repeater`,helpText:`Filter conditions`},{field:`sort`,type:`repeater`,helpText:`Default sort order`},{field:`searchableFields`,widget:`string-tags`,helpText:`Field names available for quick search`},{field:`filterableFields`,widget:`string-tags`,helpText:`Field names available for filtering`}]},{name:`table_options`,label:`Table options`,description:`Grid-only display options.`,visibleOn:`data.type == 'grid' || data.type == null`,collapsible:!0,collapsed:!0,columns:2,fields:[{field:`resizable`,colSpan:1},{field:`striped`,colSpan:1},{field:`bordered`,colSpan:1},{field:`compactToolbar`,colSpan:1},{field:`rowHeight`,colSpan:1},{field:`selection`,type:`composite`,colSpan:2},{field:`pagination`,type:`composite`,colSpan:2}]},{name:`kanban`,label:`Kanban`,description:`Kanban-specific board configuration.`,visibleOn:`data.type == 'kanban'`,fields:[{field:`kanban`,type:`composite`}]},{name:`calendar`,label:`Calendar`,description:`Calendar-specific configuration.`,visibleOn:`data.type == 'calendar'`,fields:[{field:`calendar`,type:`composite`}]},{name:`gantt`,label:`Gantt`,description:`Gantt-specific configuration.`,visibleOn:`data.type == 'gantt'`,fields:[{field:`gantt`,type:`composite`}]},{name:`gallery`,label:`Gallery`,description:`Gallery-specific configuration.`,visibleOn:`data.type == 'gallery'`,fields:[{field:`gallery`,type:`composite`}]},{name:`timeline`,label:`Timeline`,description:`Timeline-specific configuration.`,visibleOn:`data.type == 'timeline'`,fields:[{field:`timeline`,type:`composite`}]},{name:`chart`,label:`Chart`,description:`Chart-specific configuration.`,visibleOn:`data.type == 'chart'`,fields:[{field:`chart`,type:`composite`}]},{name:`end_user_controls`,label:`End-user controls`,description:`What end users can do on this view — quick filters, filter tabs, visualization switching (ADR-0047, Airtable Interface parity).`,collapsible:!0,collapsed:!0,fields:[{field:`userFilters`,type:`composite`,helpText:`Quick-filter bar: element style (dropdown / tabs / toggle) + exposed fields or tab presets`},{field:`tabs`,type:`repeater`,helpText:`In-view filter tabs — each tab applies its own filter rules`},{field:`appearance`,type:`composite`,helpText:`allowedVisualizations: which renderers users may switch between`},{field:`userActions`,type:`composite`,helpText:`Toolbar toggles: sort / search / filter / row height`},{field:`addRecord`,type:`composite`},{field:`showRecordCount`}]},{name:`navigation_sharing`,label:`Navigation & sharing`,description:`Where this view appears and who can see it.`,collapsible:!0,collapsed:!0,fields:[{field:`navigation`,type:`composite`},{field:`sharing`,type:`composite`}]}]}),HY=fK({schemaId:`app`,type:`simple`,sections:[{label:`Basics`,description:`App identity and activation.`,columns:2,fields:[{field:`name`,type:`text`,required:!0,colSpan:1,helpText:`snake_case, unique`},{field:`label`,type:`text`,required:!0,colSpan:1},{field:`description`,type:`textarea`,colSpan:2},{field:`version`,type:`text`,colSpan:1},{field:`icon`,type:`text`,colSpan:1,helpText:`Lucide icon name (e.g. "users", "briefcase")`},{field:`active`,type:`boolean`,colSpan:1},{field:`isDefault`,type:`boolean`,colSpan:1,helpText:`Make this the default app for new users`}]},{label:`Navigation`,description:`Sidebar items and area grouping.`,fields:[{field:`navigation`,type:`composite`,helpText:`Nav tree — recursive structure`},{field:`areas`,type:`repeater`,helpText:`Group items into collapsible areas`},{field:`homePageId`,type:`text`,helpText:`Landing page when app opens`},{field:`mobileNavigation`,type:`composite`,helpText:`Bottom tab bar config for mobile`}]},{label:`Content`,description:`Objects and APIs this app uses.`,fields:[{field:`objects`,widget:`object-selector`,multiple:!0,helpText:`Object names this app exposes`},{field:`apis`,type:`composite`,helpText:`API endpoint definitions`},{field:`defaultAgent`,type:`text`,helpText:`AI agent for the ambient assistant button`}]},{label:`Branding`,description:`Theme colors and logo.`,collapsible:!0,collapsed:!0,fields:[{field:`branding`,type:`composite`,helpText:`Primary/secondary colors, logo, theme`}]},{label:`Access & sharing`,description:`Who can access this app and how it can be embedded.`,collapsible:!0,collapsed:!0,fields:[{field:`requiredPermissions`,widget:`string-tags`,helpText:`Permissions needed to access this app`},{field:`sharing`,type:`composite`,helpText:`Public/internal/restricted access control`},{field:`embed`,type:`composite`,helpText:`iFrame embed configuration`},{field:`aria`,type:`composite`,helpText:`Accessibility labels`}]}]}),UY=fK({schemaId:`dashboard`,type:`simple`,sections:[{label:`Basics`,description:`Dashboard identity and description.`,columns:2,fields:[{field:`name`,type:`text`,required:!0,colSpan:1,helpText:`snake_case unique identifier`},{field:`label`,type:`text`,required:!0,colSpan:1,helpText:`Display name`},{field:`description`,type:`textarea`,colSpan:2}]},{label:`Layout`,description:`Grid sizing and refresh cadence.`,columns:3,fields:[{field:`columns`,type:`number`,colSpan:1,helpText:`Grid columns (default 12)`},{field:`gap`,type:`number`,colSpan:1,helpText:`Grid gap (Tailwind units)`},{field:`refreshInterval`,type:`number`,colSpan:1,helpText:`Auto-refresh (seconds)`},{field:`header`,type:`composite`,colSpan:3,helpText:`Dashboard header config (title, subtitle, actions)`}]},{label:`Widgets`,description:`Cards and charts placed on the grid.`,fields:[{field:`widgets`,type:`repeater`,required:!0,helpText:`Dashboard widgets with position and sizing`}]},{label:`Filters`,description:`Default and global filters applied across widgets.`,collapsible:!0,collapsed:!0,fields:[{field:`dateRange`,type:`composite`,helpText:`Default date range selector`},{field:`globalFilters`,type:`repeater`,helpText:`Filters applied to all widgets`}]},{label:`Advanced`,description:`Accessibility and performance tuning.`,collapsible:!0,collapsed:!0,fields:[{field:`aria`,type:`composite`,helpText:`Accessibility labels`},{field:`performance`,type:`composite`,helpText:`Caching and optimization config`}]}]}),WY=fK({schemaId:`dataset`,type:`simple`,sections:[{name:`basics`,label:`Basics`,description:`Dataset identity.`,columns:2,fields:[{field:`name`,type:`text`,colSpan:1,required:!0,immutable:!0,helpText:`snake_case unique identifier`},{field:`label`,type:`text`,colSpan:1,required:!0,helpText:`Display name`},{field:`description`,type:`textarea`,colSpan:2,helpText:`What this dataset measures`}]},{name:`source`,label:`Source`,description:`The base object, the relationships to join, and the dataset’s intrinsic scope. Joins are derived from the object graph — pick relationship (lookup / master_detail) names, never write an ON clause.`,fields:[{field:`object`,widget:`ref:object`,required:!0,helpText:`Base object — the FROM`},{field:`include`,widget:`string-tags`,helpText:'Relationship (lookup / master_detail) field names to join — enables `relationship.field` dimensions/measures (e.g. include "account" → group by account.region)'},{field:`filter`,widget:`filter-builder`,dependsOn:`object`,helpText:`Intrinsic scope filter (e.g. exclude soft-deleted records), ANDed into every query`}]},{name:`dimensions`,label:`Dimensions`,description:"Groupable axes. Use a base field, or `relationship.field` (e.g. account.region) for a relationship included above.",fields:[{field:`dimensions`,type:`repeater`,required:!0,helpText:`Each: name (referenced by presentations), field, type, and — for dates — a default bucketing granularity`}]},{name:`measures`,label:`Measures`,description:`Aggregatable values defined once and referenced by name. A measure is sum/avg/count/… of a field; a derived measure combines other measures (ratio/sum/difference/product). Measure-scoped filters and derived ops are edited per-row in the dataset designer.`,fields:[{field:`measures`,type:`repeater`,required:!0,helpText:`Each: name, aggregate, field (optional for count), display format/currency, and a “certified” governance flag`}]}]}),GY=fK({schemaId:`action`,type:`simple`,sections:[{label:`Basics`,description:`Action identity and presentation.`,columns:2,fields:[{field:`name`,required:!0,colSpan:1,helpText:`Unique identifier (snake_case)`},{field:`label`,required:!0,colSpan:1,helpText:`Button text shown to users`},{field:`objectName`,widget:`ref:object`,colSpan:1,helpText:`Object this action belongs to (optional)`},{field:`icon`,colSpan:1,helpText:`Lucide icon name (e.g., "check", "x-circle")`},{field:`type`,required:!0,colSpan:1,helpText:`What happens when clicked`},{field:`variant`,colSpan:1,helpText:`Button style (primary=blue, danger=red, ghost=transparent)`}]},{label:`Behavior`,description:`Configure what happens when the action is triggered.`,fields:[{field:`target`,visibleOn:`data.type != 'script'`,helpText:`URL, flow name, or API endpoint to call`},{field:`method`,visibleOn:`data.type == 'api'`,helpText:`HTTP method (GET, POST, PUT, DELETE)`},{field:`body`,type:`composite`,visibleOn:`data.type == 'script'`,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:`params`,type:`repeater`,helpText:`User input parameters (show form before executing)`},{field:`confirmText`,helpText:`Confirmation message (e.g., "Are you sure?")`},{field:`successMessage`,helpText:`Success message after completion`},{field:`refreshAfter`,helpText:`Refresh the list/page after action completes`}]},{label:`Placement`,description:`Where and when the action button appears.`,collapsible:!0,collapsed:!0,fields:[{field:`locations`,type:`repeater`,helpText:`Where to show this action (toolbar, row menu, etc.)`},{field:`component`,helpText:`How to render (button, icon, menu item)`},{field:`visible`,widget:`textarea`,helpText:`CEL expression: show only when condition is true`},{field:`disabled`,widget:`textarea`,helpText:`CEL expression: disable when condition is true`},{field:`shortcut`,helpText:`Keyboard shortcut (e.g., "Ctrl+S", "Cmd+Enter")`}]},{label:`Advanced`,description:`Bulk operations, AI exposure, and API request shape.`,collapsible:!0,collapsed:!0,columns:2,fields:[{field:`bulkEnabled`,colSpan:1,helpText:`Allow applying to multiple selected records`},{field:`ai`,colSpan:2,helpText:`AI exposure (opt-in): set ai.exposed=true and write ai.description (≥40 chars) to make this callable by agents.`},{field:`recordIdParam`,visibleOn:`data.type == 'api'`,colSpan:1,helpText:`Body parameter name for record ID`},{field:`recordIdField`,visibleOn:`data.type == 'api' && data.recordIdParam`,colSpan:1,helpText:`Field to use as record ID (default: "id")`},{field:`bodyShape`,visibleOn:`data.type == 'api'`,colSpan:2,helpText:`Request body structure (flat or nested)`}]}]}),KY=fK({schemaId:`page`,type:`simple`,sections:[{label:`Basics`,description:`Page identity and template.`,columns:2,fields:[{field:`name`,required:!0,colSpan:1,helpText:`Unique identifier (snake_case)`},{field:`label`,required:!0,colSpan:1,helpText:`Page title shown to users`},{field:`icon`,widget:`icon`,colSpan:1,helpText:`Icon for navigation menu`},{field:`type`,colSpan:1,options:[{label:`List / Interface page`,value:`list`},{label:`Record page`,value:`record`},{label:`Home page`,value:`home`},{label:`App page`,value:`app`},{label:`Utility panel`,value:`utility`}],helpText:`Page kind. "List / Interface" binds a source view into a curated surface — how it looks (grid / kanban / calendar / …) is a visualization set under Interface, not a page type.`},{field:`template`,colSpan:2,visibleOn:`data.type != 'list'`,helpText:`Layout template (e.g., "header-sidebar-main")`},{field:`description`,widget:`textarea`,colSpan:2,helpText:`Page description for navigation`}]},{label:`Data Context`,description:`Record binding and page-local state.`,visibleOn:`data.type != 'list'`,fields:[{field:`object`,widget:`ref:object`,helpText:`Bound object (for Record pages)`},{field:`variables`,type:`repeater`,helpText:`Local page state variables`}]},{label:`Layout`,description:`Page regions and components placed within them.`,visibleOn:`data.type != 'list'`,fields:[{field:`regions`,type:`repeater`,helpText:`Layout regions (header, main, sidebar, footer) with components`}]},{name:`interface`,label:`Interface (list pages)`,description:`Interface mode (Airtable parity): the page defines its own data surface directly — columns, filters, visualizations and toolbar — no inheriting from a separate view.`,collapsible:!0,collapsed:!1,visibleOn:`data.type == 'list'`,fields:[{field:`interfaceConfig`,type:`composite`,helpText:`The page IS the view: source picks the object, columns/filterBy are defined directly here; appearance.allowedVisualizations whitelists renderers (one entry = locked); userActions toggles the toolbar.`,fields:[{field:`source`,widget:`ref:object`,helpText:`Object this page reads from`},{field:`columns`,widget:`field-multi`,dependsOn:`source`,helpText:`Columns to show — defined directly on the page (blank = all object fields)`},{field:`filterBy`,widget:`filter-builder`,dependsOn:`source`,helpText:`Always-on base filter for the page — same visual builder as the list toolbar.`},{field:`levels`,helpText:`Hierarchy levels to display (tree-like sources)`},{field:`appearance`,type:`composite`,disclosure:`popover`,helpText:`Allowed visualizations (Grid / Kanban / Calendar / …) and description visibility`},{field:`userFilters`,widget:`filter-mode`,helpText:`End-user filter bar: None (no bar) / Tabs (named presets) / Dropdown (per-field). None removes the config.`},{field:`userActions`,type:`composite`,disclosure:`popover`,helpText:`Toolbar toggles (search, sort, filter, row height)`},{field:`addRecord`,type:`composite`,disclosure:`popover`,helpText:`Add-record entry point`},{field:`buttons`,widget:`action-multi`,dependsOn:`source`,helpText:`Toolbar buttons — pick from this object's actions`},{field:`recordAction`,options:[{label:`Drawer (right-side peek)`,value:`drawer`},{label:`Full page`,value:`page`},{label:`Modal`,value:`modal`},{label:`Not clickable`,value:`none`}],helpText:`How clicking a record opens its detail`},{field:`showRecordCount`,helpText:`Show the record count bar`},{field:`allowPrinting`,helpText:`Allow users to print this page`}]}]},{label:`Advanced`,description:`Activation, audience, and accessibility.`,collapsible:!0,collapsed:!0,fields:[{field:`isDefault`,helpText:`Set as default page for this page type`},{field:`kind`,helpText:`Page override mode: full or slotted (for record pages)`},{field:`assignedProfiles`,widget:`string-tags`,helpText:`Profiles that can access this page`},{field:`aria`,type:`composite`,helpText:`Accessibility attributes (ARIA labels, roles)`}]}]}),qY=X(()=>T({name:v().describe(`Region name (e.g. "sidebar", "main", "header")`),width:A([`small`,`medium`,`large`,`full`]).optional(),components:w(M(()=>XY)).describe(`Components in this region`)})),JY=A(`page:header.page:footer.page:sidebar.page:tabs.page:accordion.page:card.page:section.record:details.record:highlights.record:related_list.record:activity.record:chatter.record:path.record:alert.record:quick_actions.record:reference_rail.record:history.app:launcher.nav:menu.nav:breadcrumb.global:search.global:notifications.user:profile.ai:chat_window.ai:suggestion.element:text.element:number.element:image.element:divider.element:button.element:filter.element:form.element:record_picker.element:text_input`.split(`.`)),YY=X(()=>T({object:v().describe(`Object to query`),view:v().optional().describe(`Named view to apply`),filter:sq.optional().describe(`Additional filter criteria`),sort:w(iJ).optional().describe(`Sort order`),limit:y().int().positive().optional().describe(`Max records to display`)})),XY=X(()=>T({type:E([JY,v()]).describe(`Component Type (Standard enum or custom string)`),id:v().optional().describe(`Unique instance ID`),label:Q.optional(),properties:k(v(),S()).optional().default({}).describe(`Component props passed to the widget. See component.zod.ts for schemas.`),events:k(v(),v()).optional().describe(`Event handlers map`),style:k(v(),v()).optional().describe(`Inline styles or utility classes`),className:v().optional().describe(`CSS class names`),responsiveStyles:kG.optional().describe(`Per-breakpoint scoped style maps (ADR-0065)`),visibility:JH.optional().describe(`Visibility predicate (CEL).`),dataSource:YY.optional().describe(`Per-element data binding for multi-object pages`),responsive:DG.optional().describe(`Responsive layout configuration`),aria:$.optional().describe(`ARIA accessibility attributes`)})),ZY=X(()=>T({name:v().describe("Variable name. Exposed to expressions as `page.<name>`."),type:A([`string`,`number`,`boolean`,`object`,`array`,`record_id`]).default(`string`),defaultValue:S().optional().describe(`Initial value. Defaults to a type-appropriate empty value when omitted.`),source:v().optional().describe("Component id that writes this variable (e.g. an element:record_picker whose `id` matches).")})),QY=X(()=>A([`record`,`home`,`app`,`utility`,`list`]).describe(`Page type — the page KIND. Only types with a dedicated renderer are authorizable; visualizations of a list page live in interfaceConfig, not here.`)),$Y=X(()=>T({source:v().optional().describe(`Source object name for the page`),columns:E([w(v()),w(PG)]).optional().describe(`Columns shown by the page. Blank = all object fields. Defined directly on the page (no view inheritance).`),sort:w(iJ).optional().describe(`Default sort order for the page, defined directly on the page.`),filterBy:w(MG).optional().describe(`Always-on page filter (base filter).`),levels:y().int().min(1).optional().describe(`Number of hierarchy levels to display`),sourceView:v().optional().describe(`@deprecated Legacy named-view inheritance. Define columns/sort/filterBy on the page instead.`),appearance:KG.optional().describe(`Appearance and visualization configuration`),userFilters:YG.optional().describe(`End-user quick-filter bar for this page (overrides the source view's userFilters)`),userActions:GG.optional().describe(`User action toggles`),addRecord:XG.optional().describe(`Add record entry point configuration`),buttons:w(v()).optional().describe(`Toolbar buttons — names of the source object's actions to surface in the page toolbar`),recordAction:A([`drawer`,`page`,`modal`,`none`]).optional().describe(`How clicking a record opens its detail (drawer | page | modal | none). Default: drawer`),showRecordCount:b().optional().describe(`Show record count at page bottom`),allowPrinting:b().optional().describe(`Allow users to print the page`)}).describe(`Interface-level page configuration (Airtable parity)`));X(()=>T({name:Z.describe(`Page unique name (lowercase snake_case)`),label:Q,description:Q.optional(),icon:v().optional().describe(`Page icon name`),type:QY.default(`record`).describe(`Page type`),variables:w(ZY).optional().describe("Local page state, exposed to expressions as `page.<name>` and writable by interactive elements via `source` (master/detail, filtered dashboards)."),object:v().optional().describe(`Bound object (for Record pages)`),template:v().default(`default`).describe(`Layout template name (e.g. "header-sidebar-main")`),regions:w(qY).optional().default([]).describe(`Layout regions (header, main, sidebar, footer) with their components. Optional — list pages use interfaceConfig, slotted pages use slots, and an empty full page falls back to the synthesized default layout.`),isDefault:b().default(!1),assignedProfiles:w(v()).optional(),interfaceConfig:$Y.optional().describe(`Interface-level page configuration (for Airtable-style interface pages)`),aria:$.optional().describe(`ARIA accessibility attributes`),kind:A([`full`,`slotted`]).default(`full`).describe(`Page override mode: full (default) or slotted (partial overrides)`),slots:T({header:E([XY,w(XY)]).optional(),actions:E([XY,w(XY)]).optional(),alerts:E([XY,w(XY)]).optional(),highlights:E([XY,w(XY)]).optional(),details:E([XY,w(XY)]).optional(),tabs:E([XY,w(XY)]).optional(),discussion:E([XY,w(XY)]).optional()}).optional().describe(`Slot override map for slotted pages`)}));var eX=X(()=>T({onMount:v().optional().describe(`Initialization code when widget mounts`),onUpdate:v().optional().describe(`Code to run when props change`),onUnmount:v().optional().describe(`Cleanup code when widget unmounts`),onValidate:v().optional().describe(`Custom validation logic`),onFocus:v().optional().describe(`Code to run on focus`),onBlur:v().optional().describe(`Code to run on blur`),onError:v().optional().describe(`Error handling code`)})),tX=X(()=>T({name:v().describe(`Event name`),label:Q.optional().describe(`Human-readable event label`),description:Q.optional().describe(`Event description and usage`),bubbles:b().default(!1).describe(`Whether event bubbles`),cancelable:b().default(!1).describe(`Whether event is cancelable`),payload:k(v(),S()).optional().describe(`Event payload schema`)})),nX=X(()=>T({name:v().describe(`Property name (camelCase)`),label:Q.optional().describe(`Human-readable label`),type:A([`string`,`number`,`boolean`,`array`,`object`,`function`,`any`]).describe(`TypeScript type`),required:b().default(!1).describe(`Whether property is required`),default:S().optional().describe(`Default value`),description:Q.optional().describe(`Property description`),validation:k(v(),S()).optional().describe(`Validation rules`),category:v().optional().describe(`Property category`)})),rX=X(()=>D(`type`,[T({type:j(`npm`),packageName:v().describe(`NPM package name`),version:v().default(`latest`),exportName:v().optional().describe(`Named export (default: default)`)}),T({type:j(`remote`),url:v().url().describe(`Remote entry URL (.js)`),moduleName:v().describe(`Exposed module name`),scope:v().describe(`Remote scope name`)}),T({type:j(`inline`),code:v().describe(`JavaScript code body`)})]));X(()=>T({name:Z.describe(`Widget identifier (snake_case)`),label:Q.describe(`Widget display name`),description:Q.optional().describe(`Widget description`),version:v().optional().describe(`Widget version (semver)`),author:v().optional().describe(`Widget author`),icon:v().optional().describe(`Widget icon`),fieldTypes:w(v()).optional().describe(`Supported field types`),category:A([`input`,`display`,`picker`,`editor`,`custom`]).default(`custom`).describe(`Widget category`),lifecycle:eX.optional().describe(`Lifecycle hooks`),events:w(tX).optional().describe(`Custom events`),properties:w(nX).optional().describe(`Configuration properties`),implementation:rX.optional().describe(`Widget implementation source`),dependencies:w(T({name:v(),version:v().optional(),url:v().url().optional()})).optional().describe(`Widget dependencies`),screenshots:w(v().url()).optional().describe(`Screenshot URLs`),documentation:v().url().optional().describe(`Documentation URL`),license:v().optional().describe(`License (SPDX identifier)`),tags:w(v()).optional().describe(`Tags for categorization`),aria:$.optional().describe(`ARIA accessibility attributes`),performance:AG.optional().describe(`Performance optimization settings`)})),X(()=>T({value:S().describe(`Current field value`),onChange:P().input(O([S()])).output(gl()).describe(`Callback to update field value`),readonly:b().default(!1).describe(`Read-only mode flag`),required:b().default(!1).describe(`Required field flag`),error:v().optional().describe(`Validation error message`),field:ZW.describe(`Field schema definition`),record:k(v(),S()).optional().describe(`Complete record data`),options:k(v(),S()).optional().describe(`Custom widget options`)})),T({}),T({title:Q.describe(`Page title`),subtitle:Q.optional().describe(`Page subtitle`),icon:v().optional().describe(`Icon name`),breadcrumb:b().default(!0).describe(`Show breadcrumb`),actions:w(v()).optional().describe(`Action IDs to show in header`),aria:$.optional().describe(`ARIA accessibility attributes`)}),T({type:A([`line`,`card`,`pill`]).default(`line`),position:A([`top`,`left`]).default(`top`),items:w(T({label:Q,icon:v().optional(),children:w(S()).describe(`Child components`)})),aria:$.optional().describe(`ARIA accessibility attributes`)}),T({title:Q.optional(),bordered:b().default(!0),actions:w(v()).optional(),body:w(S()).optional().describe(`Card content components (slot)`),footer:w(S()).optional().describe(`Card footer components (slot)`),aria:$.optional().describe(`ARIA accessibility attributes`)}),T({columns:A([`1`,`2`,`3`,`4`]).default(`2`).describe(`Number of columns for field layout (1-4)`),layout:A([`auto`,`custom`]).default(`auto`).describe(`Layout mode: auto uses object compactLayout, custom uses explicit sections`),sections:w(v()).optional().describe(`Section IDs to show (required when layout is "custom")`),fields:w(v()).optional().describe(`Explicit field list to display (optional, overrides compactLayout)`),aria:$.optional().describe(`ARIA accessibility attributes`)}),T({objectName:v().describe(`Related object name (e.g., "task", "opportunity")`),relationshipField:v().describe(`Field on related object that points to this record (e.g., "account_id")`),columns:w(v()).describe(`Fields to display in the related list`),sort:E([v(),w(T({field:v(),order:A([`asc`,`desc`])}))]).optional().describe(`Sort order for related records`),limit:y().int().positive().default(5).describe(`Number of records to display initially`),filter:w(MG).optional().describe(`Additional filter criteria for related records`),title:Q.optional().describe(`Custom title for the related list`),showViewAll:b().default(!0).describe(`Show "View All" link to see all related records`),actions:w(v()).optional().describe(`Action IDs available for related records`),add:T({picker:T({object:v().describe(`Object to pick records from (the far side of an m2m, or the child object for a 1:m re-parent).`),valueField:v().default(`id`).describe("Field on the picked record used as the link value (default `id`)."),labelField:v().optional().describe(`Field shown in the picker rows (defaults to the object title field).`),filter:w(MG).optional().describe(`Restrict which records the picker offers.`)}).describe(`Where the Add affordance sources records from.`),linkField:v().optional().describe("Field on `objectName` that stores the picked record id (junction case). Omit for a 1:m re-parent."),label:Q.optional().describe(`Label for the Add button (default "Add").`)}).optional().describe(`Add-existing-via-picker config (generic m2m/junction assignment).`),aria:$.optional().describe(`ARIA accessibility attributes`)}),T({fields:w(E([v(),T({name:v().describe(`Field name on the record`),label:v().optional().describe(`Display label (overrides schema label)`),icon:v().optional().describe(`Icon name (lucide icon key)`),type:v().optional().describe(`Override cell renderer type (rare)`)})]).describe(`Highlight field: bare name, or {name,label?,icon?,type?}`)).min(1).max(7).describe(`Key fields to highlight (1-7 fields max, typically displayed as prominent cards). Each item may be a bare field name or {name, label?, icon?, type?} for inline overrides.`),layout:A([`horizontal`,`vertical`]).default(`horizontal`).describe(`Layout orientation for highlight fields`),aria:$.optional().describe(`ARIA accessibility attributes`)});var iX=T({types:w($J).optional().describe(`Feed item types to show (default: all)`),filterMode:aY.default(`all`).describe(`Default activity filter`),showFilterToggle:b().default(!0).describe(`Show filter dropdown in panel header`),limit:y().int().positive().default(20).describe(`Number of items to load per page`),showCompleted:b().default(!1).describe(`Include completed activities`),unifiedTimeline:b().default(!0).describe(`Mix field changes and comments in one timeline (Airtable style)`),showCommentInput:b().default(!0).describe(`Show "Leave a comment" input at the bottom`),enableMentions:b().default(!0).describe(`Enable @mentions in comments`),enableReactions:b().default(!1).describe(`Enable emoji reactions on feed items`),enableThreading:b().default(!1).describe(`Enable threaded replies on comments`),showSubscriptionToggle:b().default(!0).describe(`Show bell icon for record-level notification subscription`),aria:$.optional().describe(`ARIA accessibility attributes`)});T({position:A([`sidebar`,`inline`,`drawer`]).default(`sidebar`).describe(`Where to render the chatter panel`),width:E([v(),y()]).optional().describe(`Panel width (e.g., "350px", "30%")`),collapsible:b().default(!0).describe(`Whether the panel can be collapsed`),defaultCollapsed:b().default(!1).describe(`Whether the panel starts collapsed`),feed:iX.optional().describe(`Embedded activity feed configuration`),aria:$.optional().describe(`ARIA accessibility attributes`)}),T({statusField:v().describe(`Field name representing the current status/stage`),stages:w(T({value:v(),label:Q})).optional().describe(`Explicit stage definitions (if not using field metadata)`),aria:$.optional().describe(`ARIA accessibility attributes`)}),T({items:w(T({label:Q,icon:v().optional(),collapsed:b().default(!1),children:w(S()).describe(`Child components`)})),allowMultiple:b().default(!1).describe(`Allow multiple panels to be expanded simultaneously`),aria:$.optional().describe(`ARIA accessibility attributes`)}),T({mode:A([`float`,`sidebar`,`inline`]).default(`float`).describe(`Display mode for the chat window`),agentId:v().optional().describe(`Specific AI agent to use`),context:k(v(),S()).optional().describe(`Contextual data to pass to the AI`),aria:$.optional().describe(`ARIA accessibility attributes`)}),X(()=>T({content:v().describe(`Text or Markdown content`),variant:A([`heading`,`subheading`,`body`,`caption`]).optional().default(`body`).describe(`Text style variant`),align:A([`left`,`center`,`right`]).optional().default(`left`).describe(`Text alignment`),aria:$.optional().describe(`ARIA accessibility attributes`)})),X(()=>T({object:v().describe(`Source object`),field:v().optional().describe(`Field to aggregate`),aggregate:A([`count`,`sum`,`avg`,`min`,`max`]).describe(`Aggregation function`),filter:sq.optional().describe(`Filter criteria`),format:A([`number`,`currency`,`percent`]).optional().describe(`Number display format`),prefix:v().optional().describe(`Prefix text (e.g. "$")`),suffix:v().optional().describe(`Suffix text (e.g. "%")`),aria:$.optional().describe(`ARIA accessibility attributes`)})),X(()=>T({src:v().describe(`Image URL or attachment field`),alt:v().optional().describe(`Alt text for accessibility`),fit:A([`cover`,`contain`,`fill`]).optional().default(`cover`).describe(`Image object-fit mode`),height:y().optional().describe(`Fixed height in pixels`),aria:$.optional().describe(`ARIA accessibility attributes`)})),X(()=>T({type:A([`state_machine`,`flow`,`permission`]).describe(`Metadata view kind (ADR-0051): state_machine | flow | permission`),name:v().describe(`Target metadata item name; resolved package-scoped (ADR-0048), then dependencies (ADR-0046 §3.3)`),object:v().optional().describe(`Owning object — required for object-scoped kinds: state_machine is a rule ON an object (ADR-0020), permission renders a matrix FOR one; omit for top-level flow`),mode:A([`diagram`,`matrix`,`summary`]).optional().describe(`Render form; defaults per type (diagram for flow/state_machine, matrix for permission)`),detail:A([`business`,`technical`]).optional().default(`business`).describe(`Authoring altitude (ADR-0051 §3.4): business collapses technical flow nodes to business steps + approvals. NOT access (cf. book.audience); permission projection is automatic and render-time, never set here`),aria:$.optional().describe(`ARIA accessibility attributes`)})),X(()=>T({label:Q.describe(`Button display label`),variant:A([`primary`,`secondary`,`danger`,`ghost`,`link`]).optional().default(`primary`).describe(`Button visual variant`),size:A([`small`,`medium`,`large`]).optional().default(`medium`).describe(`Button size`),icon:v().optional().describe(`Icon name (Lucide icon)`),iconPosition:A([`left`,`right`]).optional().default(`left`).describe(`Icon position relative to label`),disabled:b().optional().default(!1).describe(`Disable the button`),aria:$.optional().describe(`ARIA accessibility attributes`)})),X(()=>T({object:v().describe(`Object to filter`),fields:w(v()).describe(`Filterable field names`),targetVariable:v().optional().describe(`Page variable to store filter state`),layout:A([`inline`,`dropdown`,`sidebar`]).optional().default(`inline`).describe(`Filter display layout`),showSearch:b().optional().default(!0).describe(`Show search input`),aria:$.optional().describe(`ARIA accessibility attributes`)})),X(()=>T({object:v().describe(`Object for the form`),fields:w(v()).optional().describe(`Fields to display (defaults to all editable fields)`),mode:A([`create`,`edit`]).optional().default(`create`).describe(`Form mode`),submitLabel:Q.optional().describe(`Submit button label`),onSubmit:JH.optional().describe(`Action expression on form submit (CEL)`),aria:$.optional().describe(`ARIA accessibility attributes`)})),X(()=>T({object:v().describe(`Object to pick records from`),displayField:v().describe(`Field to display as the record label`),searchFields:w(v()).optional().describe(`Fields to search against`),filter:sq.optional().describe(`Filter criteria for available records`),multiple:b().optional().default(!1).describe(`Allow multiple record selection`),targetVariable:v().optional().describe(`Page variable to bind selected record ID(s)`),placeholder:Q.optional().describe(`Placeholder text`),aria:$.optional().describe(`ARIA accessibility attributes`)})),X(()=>T({inputType:A([`text`,`email`,`number`,`tel`,`url`,`password`]).optional().default(`text`).describe(`Native input type — drives keyboard/validation affordance and how the bound value is coerced (number → numeric).`),label:Q.optional().describe(`Field label shown above the input`),placeholder:Q.optional().describe(`Placeholder text shown when empty`),defaultValue:E([v(),y()]).optional().describe(`Initial value; seeds the bound page variable on mount`),required:b().optional().default(!1).describe(`Mark the field as required`),disabled:b().optional().default(!1).describe(`Disable the input`),description:Q.optional().describe(`Helper text shown below the input`),targetVariable:v().optional().describe("Page variable this input writes to. Declarative hint; the live binding resolves via the variable whose `source` equals this component id (see PageVariableSchema)."),aria:$.optional().describe(`ARIA accessibility attributes`)})),T({context:v().optional()});var aX=X(()=>T({minWidth:y().default(44).describe(`Minimum touch target width in pixels (WCAG 2.5.5: 44px)`),minHeight:y().default(44).describe(`Minimum touch target height in pixels (WCAG 2.5.5: 44px)`),padding:y().optional().describe(`Additional padding around touch target in pixels`),hitSlop:T({top:y().optional().describe(`Extra hit area above the element`),right:y().optional().describe(`Extra hit area to the right of the element`),bottom:y().optional().describe(`Extra hit area below the element`),left:y().optional().describe(`Extra hit area to the left of the element`)}).optional().describe(`Invisible hit area extension beyond the visible bounds`)}).describe(`Touch target sizing configuration (WCAG accessible)`)),oX=X(()=>A([`swipe`,`pinch`,`long_press`,`double_tap`,`drag`,`rotate`,`pan`]).describe(`Touch gesture type`)),sX=X(()=>A([`up`,`down`,`left`,`right`])),cX=X(()=>T({direction:w(sX).describe(`Allowed swipe directions`),threshold:y().optional().describe(`Minimum distance in pixels to recognize swipe`),velocity:y().optional().describe(`Minimum velocity (px/ms) to trigger swipe`)}).describe(`Swipe gesture recognition settings`)),lX=X(()=>T({minScale:y().optional().describe(`Minimum scale factor (e.g., 0.5 for 50%)`),maxScale:y().optional().describe(`Maximum scale factor (e.g., 3.0 for 300%)`)}).describe(`Pinch/zoom gesture recognition settings`)),uX=X(()=>T({duration:y().default(500).describe(`Hold duration in milliseconds to trigger long press`),moveTolerance:y().optional().describe(`Max movement in pixels allowed during press`)}).describe(`Long press gesture recognition settings`)),dX=X(()=>T({type:oX.describe(`Gesture type to configure`),label:Q.optional().describe(`Descriptive label for the gesture action`),enabled:b().default(!0).describe(`Whether this gesture is active`),swipe:cX.optional().describe(`Swipe gesture settings (when type is swipe)`),pinch:lX.optional().describe(`Pinch gesture settings (when type is pinch)`),longPress:uX.optional().describe(`Long press settings (when type is long_press)`)}).describe(`Per-gesture configuration`));X(()=>T({gestures:w(dX).optional().describe(`Configured gesture recognizers`),touchTarget:aX.optional().describe(`Touch target sizing and hit area`),hapticFeedback:b().optional().describe(`Enable haptic feedback on touch interactions`)}).merge($.partial()).describe(`Touch and gesture interaction configuration`));var fX=X(()=>T({enabled:b().default(!1).describe(`Enable focus trapping within this container`),initialFocus:v().optional().describe(`CSS selector for the element to focus on activation`),returnFocus:b().default(!0).describe(`Return focus to trigger element on deactivation`),escapeDeactivates:b().default(!0).describe(`Allow Escape key to deactivate the focus trap`)}).describe(`Focus trap configuration for modal-like containers`)),pX=X(()=>T({key:v().describe(`Key combination (e.g., "Ctrl+S", "Alt+N", "Escape")`),action:v().describe(`Action identifier to invoke when shortcut is triggered`),description:Q.optional().describe(`Human-readable description of what the shortcut does`),scope:A([`global`,`view`,`form`,`modal`,`list`]).default(`global`).describe(`Scope in which this shortcut is active`)}).describe(`Keyboard shortcut binding`)),mX=X(()=>T({tabOrder:A([`auto`,`manual`]).default(`auto`).describe(`Tab order strategy: auto (DOM order) or manual (explicit tabIndex)`),skipLinks:b().default(!1).describe(`Provide skip-to-content navigation links`),focusVisible:b().default(!0).describe(`Show visible focus indicators for keyboard users`),focusTrap:fX.optional().describe(`Focus trap settings`),arrowNavigation:b().default(!1).describe(`Enable arrow key navigation between focusable items`)}).describe(`Focus and tab navigation management`));X(()=>T({shortcuts:w(pX).optional().describe(`Registered keyboard shortcuts`),focusManagement:mX.optional().describe(`Focus and tab order management`),rovingTabindex:b().default(!1).describe(`Enable roving tabindex pattern for composite widgets`)}).merge($.partial()).describe(`Keyboard navigation and shortcut configuration`));var hX=X(()=>T({primary:v().describe(`Primary brand color (hex, rgb, or hsl)`),secondary:v().optional().describe(`Secondary brand color`),accent:v().optional().describe(`Accent color for highlights`),success:v().optional().describe(`Success state color (default: green)`),warning:v().optional().describe(`Warning state color (default: yellow)`),error:v().optional().describe(`Error state color (default: red)`),info:v().optional().describe(`Info state color (default: blue)`),background:v().optional().describe(`Background color`),surface:v().optional().describe(`Surface/card background color`),text:v().optional().describe(`Primary text color`),textSecondary:v().optional().describe(`Secondary text color`),border:v().optional().describe(`Border color`),disabled:v().optional().describe(`Disabled state color`),primaryLight:v().optional().describe(`Lighter shade of primary`),primaryDark:v().optional().describe(`Darker shade of primary`),secondaryLight:v().optional().describe(`Lighter shade of secondary`),secondaryDark:v().optional().describe(`Darker shade of secondary`)})),gX=X(()=>T({fontFamily:T({base:v().optional().describe(`Base font family (default: system fonts)`),heading:v().optional().describe(`Heading font family`),mono:v().optional().describe(`Monospace font family for code`)}).optional(),fontSize:T({xs:v().optional().describe(`Extra small font size (e.g., 0.75rem)`),sm:v().optional().describe(`Small font size (e.g., 0.875rem)`),base:v().optional().describe(`Base font size (e.g., 1rem)`),lg:v().optional().describe(`Large font size (e.g., 1.125rem)`),xl:v().optional().describe(`Extra large font size (e.g., 1.25rem)`),"2xl":v().optional().describe(`2X large font size (e.g., 1.5rem)`),"3xl":v().optional().describe(`3X large font size (e.g., 1.875rem)`),"4xl":v().optional().describe(`4X large font size (e.g., 2.25rem)`)}).optional(),fontWeight:T({light:y().optional().describe(`Light weight (default: 300)`),normal:y().optional().describe(`Normal weight (default: 400)`),medium:y().optional().describe(`Medium weight (default: 500)`),semibold:y().optional().describe(`Semibold weight (default: 600)`),bold:y().optional().describe(`Bold weight (default: 700)`)}).optional(),lineHeight:T({tight:v().optional().describe(`Tight line height (e.g., 1.25)`),normal:v().optional().describe(`Normal line height (e.g., 1.5)`),relaxed:v().optional().describe(`Relaxed line height (e.g., 1.75)`),loose:v().optional().describe(`Loose line height (e.g., 2)`)}).optional(),letterSpacing:T({tighter:v().optional().describe(`Tighter letter spacing (e.g., -0.05em)`),tight:v().optional().describe(`Tight letter spacing (e.g., -0.025em)`),normal:v().optional().describe(`Normal letter spacing (e.g., 0)`),wide:v().optional().describe(`Wide letter spacing (e.g., 0.025em)`),wider:v().optional().describe(`Wider letter spacing (e.g., 0.05em)`)}).optional()})),_X=X(()=>T({0:v().optional().describe(`0 spacing (0)`),1:v().optional().describe(`Spacing unit 1 (e.g., 0.25rem)`),2:v().optional().describe(`Spacing unit 2 (e.g., 0.5rem)`),3:v().optional().describe(`Spacing unit 3 (e.g., 0.75rem)`),4:v().optional().describe(`Spacing unit 4 (e.g., 1rem)`),5:v().optional().describe(`Spacing unit 5 (e.g., 1.25rem)`),6:v().optional().describe(`Spacing unit 6 (e.g., 1.5rem)`),8:v().optional().describe(`Spacing unit 8 (e.g., 2rem)`),10:v().optional().describe(`Spacing unit 10 (e.g., 2.5rem)`),12:v().optional().describe(`Spacing unit 12 (e.g., 3rem)`),16:v().optional().describe(`Spacing unit 16 (e.g., 4rem)`),20:v().optional().describe(`Spacing unit 20 (e.g., 5rem)`),24:v().optional().describe(`Spacing unit 24 (e.g., 6rem)`)})),vX=X(()=>T({none:v().optional().describe(`No border radius (0)`),sm:v().optional().describe(`Small border radius (e.g., 0.125rem)`),base:v().optional().describe(`Base border radius (e.g., 0.25rem)`),md:v().optional().describe(`Medium border radius (e.g., 0.375rem)`),lg:v().optional().describe(`Large border radius (e.g., 0.5rem)`),xl:v().optional().describe(`Extra large border radius (e.g., 0.75rem)`),"2xl":v().optional().describe(`2X large border radius (e.g., 1rem)`),full:v().optional().describe(`Full border radius (50%)`)})),yX=X(()=>T({none:v().optional().describe(`No shadow`),sm:v().optional().describe(`Small shadow`),base:v().optional().describe(`Base shadow`),md:v().optional().describe(`Medium shadow`),lg:v().optional().describe(`Large shadow`),xl:v().optional().describe(`Extra large shadow`),"2xl":v().optional().describe(`2X large shadow`),inner:v().optional().describe(`Inner shadow (inset)`)})),bX=X(()=>T({xs:v().optional().describe(`Extra small breakpoint (e.g., 480px)`),sm:v().optional().describe(`Small breakpoint (e.g., 640px)`),md:v().optional().describe(`Medium breakpoint (e.g., 768px)`),lg:v().optional().describe(`Large breakpoint (e.g., 1024px)`),xl:v().optional().describe(`Extra large breakpoint (e.g., 1280px)`),"2xl":v().optional().describe(`2X large breakpoint (e.g., 1536px)`)})),xX=X(()=>T({duration:T({fast:v().optional().describe(`Fast animation (e.g., 150ms)`),base:v().optional().describe(`Base animation (e.g., 300ms)`),slow:v().optional().describe(`Slow animation (e.g., 500ms)`)}).optional(),timing:T({linear:v().optional().describe(`Linear timing function`),ease:v().optional().describe(`Ease timing function`),ease_in:v().optional().describe(`Ease-in timing function`),ease_out:v().optional().describe(`Ease-out timing function`),ease_in_out:v().optional().describe(`Ease-in-out timing function`)}).optional()})),SX=X(()=>T({base:y().optional().describe(`Base z-index (e.g., 0)`),dropdown:y().optional().describe(`Dropdown z-index (e.g., 1000)`),sticky:y().optional().describe(`Sticky z-index (e.g., 1020)`),fixed:y().optional().describe(`Fixed z-index (e.g., 1030)`),modalBackdrop:y().optional().describe(`Modal backdrop z-index (e.g., 1040)`),modal:y().optional().describe(`Modal z-index (e.g., 1050)`),popover:y().optional().describe(`Popover z-index (e.g., 1060)`),tooltip:y().optional().describe(`Tooltip z-index (e.g., 1070)`)})),CX=X(()=>A([`light`,`dark`,`auto`])),wX=X(()=>A([`compact`,`regular`,`spacious`])),TX=X(()=>A([`AA`,`AAA`]));X(()=>T({name:Z.describe(`Unique theme identifier (snake_case)`),label:v().describe(`Human-readable theme name`),description:v().optional().describe(`Theme description`),mode:CX.default(`light`).describe(`Theme mode (light, dark, or auto)`),colors:hX.describe(`Color palette configuration`),typography:gX.optional().describe(`Typography settings`),spacing:_X.optional().describe(`Spacing scale`),borderRadius:vX.optional().describe(`Border radius scale`),shadows:yX.optional().describe(`Box shadow effects`),breakpoints:bX.optional().describe(`Responsive breakpoints`),animation:xX.optional().describe(`Animation settings`),zIndex:SX.optional().describe(`Z-index scale for layering`),customVars:k(v(),v()).optional().describe(`Custom CSS variables (key-value pairs)`),logo:T({light:v().optional().describe(`Logo URL for light mode`),dark:v().optional().describe(`Logo URL for dark mode`),favicon:v().optional().describe(`Favicon URL`)}).optional().describe(`Logo assets`),extends:v().optional().describe(`Base theme to extend from`),density:wX.optional().describe(`Display density: compact, regular, or spacious`),wcagContrast:TX.optional().describe(`WCAG color contrast level (AA or AAA)`),rtl:b().optional().describe(`Enable right-to-left layout direction`),touchTarget:aX.optional().describe(`Touch target sizing defaults`),keyboardNavigation:mX.optional().describe(`Keyboard focus management settings`)}));var EX=X(()=>A([`cache_first`,`network_first`,`stale_while_revalidate`,`network_only`,`cache_only`]).describe(`Data fetching strategy for offline/online transitions`)),DX=X(()=>A([`client_wins`,`server_wins`,`manual`,`last_write_wins`]).describe(`How to resolve conflicts when syncing offline changes`)),OX=X(()=>T({strategy:EX.default(`network_first`).describe(`Sync fetch strategy`),conflictResolution:DX.default(`last_write_wins`).describe(`Conflict resolution policy`),retryInterval:y().optional().describe(`Retry interval in milliseconds between sync attempts`),maxRetries:y().optional().describe(`Maximum number of sync retry attempts`),batchSize:y().optional().describe(`Number of mutations to sync per batch`)}).describe(`Offline-to-online synchronization configuration`)),kX=X(()=>A([`indexeddb`,`localstorage`,`sqlite`]).describe(`Client-side storage backend for offline cache`)),AX=X(()=>A([`lru`,`lfu`,`fifo`]).describe(`Cache eviction policy`)),jX=X(()=>T({maxSize:y().optional().describe(`Maximum cache size in bytes`),ttl:y().optional().describe(`Time-to-live for cached entries in milliseconds`),persistStorage:kX.default(`indexeddb`).describe(`Storage backend`),evictionPolicy:AX.default(`lru`).describe(`Cache eviction policy when full`)}).describe(`Client-side offline cache configuration`));X(()=>T({enabled:b().default(!1).describe(`Enable offline support`),strategy:EX.default(`network_first`).describe(`Default offline fetch strategy`),cache:jX.optional().describe(`Cache settings for offline data`),sync:OX.optional().describe(`Sync settings for offline mutations`),offlineIndicator:b().default(!0).describe(`Show a visual indicator when offline`),offlineMessage:Q.optional().describe(`Customizable offline status message shown to users`),queueMaxSize:y().optional().describe(`Maximum number of queued offline mutations`)}).describe(`Offline support configuration`));var MX=X(()=>A([`fade`,`slide_up`,`slide_down`,`slide_left`,`slide_right`,`scale`,`rotate`,`flip`,`none`]).describe(`Transition preset type`)),NX=X(()=>A([`linear`,`ease`,`ease_in`,`ease_out`,`ease_in_out`,`spring`]).describe(`Animation easing function`)),PX=X(()=>T({preset:MX.optional().describe(`Transition preset to apply`),duration:y().optional().describe(`Transition duration in milliseconds`),easing:NX.optional().describe(`Easing function for the transition`),delay:y().optional().describe(`Delay before transition starts in milliseconds`),customKeyframes:v().optional().describe(`CSS @keyframes name for custom animations`),themeToken:v().optional().describe(`Reference to a theme animation token (e.g. "animation.duration.fast")`)}).describe(`Animation transition configuration`)),FX=X(()=>A([`on_mount`,`on_unmount`,`on_hover`,`on_focus`,`on_click`,`on_scroll`,`on_visible`]).describe(`Event that triggers the animation`)),IX=X(()=>T({label:Q.optional().describe(`Descriptive label for this animation configuration`),enter:PX.optional().describe(`Enter/mount animation`),exit:PX.optional().describe(`Exit/unmount animation`),hover:PX.optional().describe(`Hover state animation`),trigger:FX.optional().describe(`When to trigger the animation`),reducedMotion:A([`respect`,`disable`,`alternative`]).default(`respect`).describe(`Accessibility: how to handle prefers-reduced-motion`)}).merge($.partial()).describe(`Component-level animation configuration`)),LX=X(()=>T({type:MX.default(`fade`).describe(`Page transition type`),duration:y().default(300).describe(`Transition duration in milliseconds`),easing:NX.default(`ease_in_out`).describe(`Easing function for the transition`),crossFade:b().default(!1).describe(`Whether to cross-fade between pages`)}).describe(`Page-level transition configuration`));X(()=>T({label:Q.optional().describe(`Descriptive label for the motion configuration`),defaultTransition:PX.optional().describe(`Default transition applied to all animations`),pageTransitions:LX.optional().describe(`Page navigation transition settings`),componentAnimations:k(v(),IX).optional().describe(`Component name to animation configuration mapping`),reducedMotion:b().default(!1).describe(`When true, respect prefers-reduced-motion and suppress animations globally`),enabled:b().default(!0).describe(`Enable or disable all animations globally`)}).describe(`Top-level motion and animation design configuration`));var RX=X(()=>A([`toast`,`snackbar`,`banner`,`alert`,`inline`]).describe(`Notification presentation style`)),zX=X(()=>A([`info`,`success`,`warning`,`error`]).describe(`Notification severity level`)),BX=X(()=>A([`top_left`,`top_center`,`top_right`,`bottom_left`,`bottom_center`,`bottom_right`]).describe(`Screen position for notification placement`)),VX=X(()=>T({label:Q.describe(`Action button label`),action:v().describe(`Action identifier to execute`),variant:A([`primary`,`secondary`,`link`]).default(`primary`).describe(`Button variant style`)}).describe(`Notification action button`));X(()=>T({type:RX.default(`toast`).describe(`Notification presentation style`),severity:zX.default(`info`).describe(`Notification severity level`),title:Q.optional().describe(`Notification title`),message:Q.describe(`Notification message body`),icon:v().optional().describe(`Icon name override`),duration:y().optional().describe(`Auto-dismiss duration in ms, omit for persistent`),dismissible:b().default(!0).describe(`Allow user to dismiss the notification`),actions:w(VX).optional().describe(`Action buttons`),position:BX.optional().describe(`Override default position`)}).merge($.partial()).describe(`Notification instance definition`)),X(()=>T({defaultPosition:BX.default(`top_right`).describe(`Default screen position for notifications`),defaultDuration:y().default(5e3).describe(`Default auto-dismiss duration in ms`),maxVisible:y().default(5).describe(`Maximum number of notifications visible at once`),stackDirection:A([`up`,`down`]).default(`down`).describe(`Stack direction for multiple notifications`),pauseOnHover:b().default(!0).describe(`Pause auto-dismiss timer on hover`)}).describe(`Global notification system configuration`));var HX=X(()=>A([`element`,`handle`,`grip_icon`]).describe(`Drag initiation method`)),UX=X(()=>A([`move`,`copy`,`link`,`none`]).describe(`Drop operation effect`)),WX=X(()=>T({axis:A([`x`,`y`,`both`]).default(`both`).describe(`Constrain drag axis`),bounds:A([`parent`,`viewport`,`none`]).default(`none`).describe(`Constrain within bounds`),grid:O([y(),y()]).optional().describe(`Snap to grid [x, y] in pixels`)}).describe(`Drag movement constraints`)),GX=X(()=>T({label:Q.optional().describe(`Accessible label for the drop zone`),accept:w(v()).describe(`Accepted drag item types`),maxItems:y().optional().describe(`Maximum items allowed in drop zone`),highlightOnDragOver:b().default(!0).describe(`Highlight drop zone when dragging over`),dropEffect:UX.default(`move`).describe(`Visual effect on drop`)}).merge($.partial()).describe(`Drop zone configuration`)),KX=X(()=>T({type:v().describe(`Drag item type identifier for matching with drop zones`),label:Q.optional().describe(`Accessible label describing the draggable item`),handle:HX.default(`element`).describe(`How to initiate drag`),constraint:WX.optional().describe(`Drag movement constraints`),preview:A([`element`,`custom`,`none`]).default(`element`).describe(`Drag preview type`),disabled:b().default(!1).describe(`Disable dragging`)}).merge($.partial()).describe(`Draggable item configuration`));X(()=>T({enabled:b().default(!1).describe(`Enable drag and drop`),dragItem:KX.optional().describe(`Configuration for draggable item`),dropZone:GX.optional().describe(`Configuration for drop target`),sortable:b().default(!1).describe(`Enable sortable list behavior`),autoScroll:b().default(!0).describe(`Auto-scroll during drag near edges`),touchDelay:y().default(200).describe(`Delay in ms before drag starts on touch devices`)}).describe(`Drag and drop interaction configuration`));var qX=X(()=>T({primaryColor:v().optional().describe(`Primary brand color (hex, rgb, hsl). Mapped to --portal-primary.`),accentColor:v().optional().describe(`Accent color used for highlights and CTAs.`),backgroundColor:v().optional().describe(`Page background color.`),surfaceColor:v().optional().describe(`Card / surface background color.`),textColor:v().optional().describe(`Primary text color.`),logoUrl:v().optional().describe(`Absolute or relative URL to the portal header logo (SVG or PNG).`),faviconUrl:v().optional().describe(`Absolute or relative URL to the portal favicon.`),fontFamily:v().optional().describe(`CSS font-family stack for the portal.`),customCss:v().optional().describe(`OPTIONAL escape hatch: raw CSS appended last. Discouraged; prefer tokens.`)})),JX=T({id:Z.describe(`Unique identifier for this portal nav item (lowercase snake_case).`),label:Q.describe(`Display label.`),icon:v().optional().describe(`Icon name (Lucide).`),order:y().optional().describe(`Sort order; lower appears first.`),badge:E([v(),y()]).optional().describe(`Optional badge (e.g. unread count).`)}),YX=D(`type`,[JX.extend({type:j(`view`),viewRef:v().describe(`Reference to an existing view, e.g. "helpdesk_ticket.list.my_tickets".`)}),JX.extend({type:j(`action`),actionRef:v().describe(`Reference to an existing action, e.g. "helpdesk_ticket.create".`)}),JX.extend({type:j(`dashboard`),dashboardName:Z.describe(`Existing dashboard id.`)}),JX.extend({type:j(`url`),url:v().describe(`Absolute or root-relative URL.`),target:A([`_self`,`_blank`]).optional().default(`_self`)})]),XX=X(()=>T({rule:v().describe(`Rate-limit rule string, e.g. "5/hour/ip", "100/day/tenant".`),scope:A([`ip`,`tenant`,`route`]).default(`ip`).describe(`Counter scope. "ip" buckets per requester; "tenant" per portal owner; "route" global per route.`)})),ZX=X(()=>T({path:v().describe(`Path within the portal, e.g. "/submit" or "/kb".`),viewRef:v().optional().describe(`Reference to a public view (read-only).`),actionRef:v().optional().describe(`Reference to an action to perform anonymously (mutation).`),rateLimit:XX.optional().describe(`Rate-limit for anonymous traffic on this route.`),captcha:b().optional().default(!1).describe(`Require CAPTCHA / proof-of-work challenge before invoking.`),bindIdentityFromField:v().optional().describe(`Field name on the action input to use for magic-link identity binding (e.g. "customer_email").`)})),QX=X(()=>T({routes:w(ZX).describe(`List of anonymous-accessible routes.`),defaultRateLimit:XX.optional()})),$X=X(()=>T({title:v().optional().describe(`Default <title>.`),description:v().optional().describe(`Default <meta name="description">.`),openGraphImage:v().optional().describe(`Default og:image URL.`),robots:A([`index`,`noindex`]).optional().default(`index`)})),eZ=X(()=>E([j(`authenticated`),j(`magic-link`),j(`anonymous`),v().regex(/^sso:[a-z][a-z0-9_-]*(?::[a-z0-9_-]+)?$/i,`SSO mode must be "sso:<provider>" or "sso:<protocol>:<idp-id>"`)])),tZ=X(()=>E([j(`console`),j(`minimal`),j(`embedded`),v().regex(/^custom:[a-z][a-z0-9_-]*(?:\/[a-z0-9_-]+)?$/i,`Custom layout must be "custom:<plugin-id>" or "custom:<plugin-id>/<layout-id>"`)]));X(()=>T({kind:j(`portal`).describe(`Metadata kind discriminator.`),id:Z.describe(`Portal unique machine name (lowercase snake_case).`),label:Q.describe(`Portal display label.`),description:Q.optional(),routePrefix:v().regex(/^\/[a-z0-9/_-]*$/i,`routePrefix must start with "/" and be url-safe`).describe(`Root URL path for the portal (must start with "/").`),domain:v().optional().describe(`Optional vanity domain (e.g. "support.acme.com").`),layout:tZ.default(`minimal`).describe(`Shell layout for the portal.`),theme:qX.optional().describe(`Theme tokens.`),locale:E([j(`auto`),v()]).optional().default(`auto`).describe(`Locale resolution strategy.`),seo:$X.optional(),authMode:eZ.default(`authenticated`).describe(`Authentication mode for the portal.`),profiles:w(Z).min(1,`A portal must admit at least one profile (use a dedicated profile for "anonymous-only" portals).`).describe(`Profiles admitted to the portal.`),anonymousEntry:QX.optional(),navigation:w(YX).describe(`Flat list of portal entry points (references to existing metadata).`),defaultRoute:T({viewRef:v().optional(),actionRef:v().optional(),dashboardName:Z.optional()}).optional().describe(`Landing surface when the user hits the portal root.`),embeddable:b().optional().default(!1),allowedEmbedOrigins:w(v()).optional(),active:b().optional().default(!0)})),X(()=>T({id:v().describe(`Unique user identifier`),email:v().email().describe(`User email address`),emailVerified:b().default(!1).describe(`Whether email is verified`),name:v().optional().describe(`User display name`),image:v().url().optional().describe(`Profile image URL`),createdAt:v().datetime().describe(`Account creation timestamp`),updatedAt:v().datetime().describe(`Last update timestamp`)})),X(()=>T({id:v().describe(`Unique account identifier`),userId:v().describe(`Associated user ID`),type:A([`oauth`,`oidc`,`email`,`credentials`,`saml`,`ldap`]).describe(`Account type`),provider:v().describe(`Provider name`),providerAccountId:v().describe(`Provider account ID`),refreshToken:v().optional().describe(`OAuth refresh token`),accessToken:v().optional().describe(`OAuth access token`),expiresAt:y().optional().describe(`Token expiry timestamp (Unix)`),tokenType:v().optional().describe(`OAuth token type`),scope:v().optional().describe(`OAuth scope`),idToken:v().optional().describe(`OAuth ID token`),sessionState:v().optional().describe(`Session state`),createdAt:v().datetime().describe(`Account creation timestamp`),updatedAt:v().datetime().describe(`Last update timestamp`)})),X(()=>T({id:v().describe(`Unique session identifier`),sessionToken:v().describe(`Session token`),userId:v().describe(`Associated user ID`),activeOrganizationId:v().optional().describe(`Active organization ID for context switching`),expires:v().datetime().describe(`Session expiry timestamp`),createdAt:v().datetime().describe(`Session creation timestamp`),updatedAt:v().datetime().describe(`Last update timestamp`),ipAddress:v().optional().describe(`IP address`),userAgent:v().optional().describe(`User agent string`),fingerprint:v().optional().describe(`Device fingerprint`)})),X(()=>T({identifier:v().describe(`Token identifier (email or phone)`),token:v().describe(`Verification token`),expires:v().datetime().describe(`Token expiry timestamp`),createdAt:v().datetime().describe(`Token creation timestamp`)})),X(()=>T({id:v().describe(`API key identifier`),name:v().describe(`API key display name`),start:v().optional().describe(`Key prefix for identification`),prefix:v().optional().describe(`Custom key prefix`),userId:v().describe(`Owner user ID`),organizationId:v().optional().describe(`Scoped organization ID`),expiresAt:v().datetime().optional().describe(`Expiration timestamp`),createdAt:v().datetime().describe(`Creation timestamp`),updatedAt:v().datetime().describe(`Last update timestamp`),lastUsedAt:v().datetime().optional().describe(`Last used timestamp`),lastRefetchAt:v().datetime().optional().describe(`Last refetch timestamp`),enabled:b().default(!0).describe(`Whether the key is active`),rateLimitEnabled:b().optional().describe(`Whether rate limiting is enabled`),rateLimitTimeWindow:y().int().min(0).optional().describe(`Rate limit window (ms)`),rateLimitMax:y().int().min(0).optional().describe(`Max requests per window`),remaining:y().int().min(0).optional().describe(`Remaining requests`),permissions:k(v(),b()).optional().describe(`Granular permission flags`),scopes:w(v()).optional().describe(`High-level access scopes`),metadata:k(v(),S()).optional().describe(`Custom metadata`)})),X(()=>T({name:Z.describe(`Unique role name (lowercase snake_case)`),label:v().describe(`Display label (e.g. VP of Sales)`),parent:v().optional().describe(`Parent Role ID (Reports To)`),description:v().optional()}));var nZ=fK({schemaId:`role`,type:`simple`,sections:[{label:`Role`,description:`Roles compose a hierarchy used for record sharing (sales VP → sales mgr → sales rep). Permissions themselves live on Permission Sets and Profiles.`,columns:2,fields:[{field:`name`,required:!0,helpText:`snake_case`},{field:`label`,required:!0},{field:`parent`,helpText:`Parent role machine name (Reports To)`,colSpan:2},{field:`description`,colSpan:2}]}]});X(()=>T({id:v().describe(`Unique organization identifier`),name:v().describe(`Organization display name`),slug:v().regex(/^[a-z0-9_-]+$/).describe(`Unique URL-friendly slug (lowercase alphanumeric, hyphens, underscores)`),logo:v().url().optional().describe(`Organization logo URL`),metadata:k(v(),S()).optional().describe(`Custom metadata`),createdAt:v().datetime().describe(`Organization creation timestamp`),updatedAt:v().datetime().describe(`Last update timestamp`)})),X(()=>T({id:v().describe(`Unique member identifier`),organizationId:v().describe(`Organization ID`),userId:v().describe(`User ID`),role:v().describe(`Member role (e.g., owner, admin, member, guest)`),createdAt:v().datetime().describe(`Member creation timestamp`),updatedAt:v().datetime().describe(`Last update timestamp`)}));var rZ=A([`pending`,`accepted`,`rejected`,`expired`]);X(()=>T({id:v().describe(`Unique invitation identifier`),organizationId:v().describe(`Organization ID`),email:v().email().describe(`Invitee email address`),role:v().describe(`Role to assign upon acceptance`),status:rZ.default(`pending`).describe(`Invitation status`),expiresAt:v().datetime().describe(`Invitation expiry timestamp`),inviterId:v().describe(`User ID of the inviter`),createdAt:v().datetime().describe(`Invitation creation timestamp`),updatedAt:v().datetime().describe(`Last update timestamp`)}));var iZ={USER:`urn:ietf:params:scim:schemas:core:2.0:User`,GROUP:`urn:ietf:params:scim:schemas:core:2.0:Group`,ENTERPRISE_USER:`urn:ietf:params:scim:schemas:extension:enterprise:2.0:User`,LIST_RESPONSE:`urn:ietf:params:scim:api:messages:2.0:ListResponse`,PATCH_OP:`urn:ietf:params:scim:api:messages:2.0:PatchOp`,BULK_REQUEST:`urn:ietf:params:scim:api:messages:2.0:BulkRequest`,BULK_RESPONSE:`urn:ietf:params:scim:api:messages:2.0:BulkResponse`,ERROR:`urn:ietf:params:scim:api:messages:2.0:Error`},aZ=X(()=>T({resourceType:v().optional().describe(`Resource type`),created:v().datetime().optional().describe(`Creation timestamp`),lastModified:v().datetime().optional().describe(`Last modification timestamp`),location:v().url().optional().describe(`Resource location URI`),version:v().optional().describe(`Entity tag (ETag) for concurrency control`)})),oZ=X(()=>T({formatted:v().optional().describe(`Formatted full name`),familyName:v().optional().describe(`Family name (last name)`),givenName:v().optional().describe(`Given name (first name)`),middleName:v().optional().describe(`Middle name`),honorificPrefix:v().optional().describe(`Honorific prefix (Mr., Ms., Dr.)`),honorificSuffix:v().optional().describe(`Honorific suffix (Jr., Sr.)`)})),sZ=X(()=>T({value:v().email().describe(`Email address`),type:A([`work`,`home`,`other`]).optional().describe(`Email type`),display:v().optional().describe(`Display label`),primary:b().optional().default(!1).describe(`Primary email indicator`)})),cZ=X(()=>T({value:v().describe(`Phone number`),type:A([`work`,`home`,`mobile`,`fax`,`pager`,`other`]).optional().describe(`Phone number type`),display:v().optional().describe(`Display label`),primary:b().optional().default(!1).describe(`Primary phone indicator`)})),lZ=X(()=>T({formatted:v().optional().describe(`Formatted address`),streetAddress:v().optional().describe(`Street address`),locality:v().optional().describe(`City/Locality`),region:v().optional().describe(`State/Region`),postalCode:v().optional().describe(`Postal code`),country:v().optional().describe(`Country`),type:A([`work`,`home`,`other`]).optional().describe(`Address type`),primary:b().optional().default(!1).describe(`Primary address indicator`)})),uZ=X(()=>T({value:v().describe(`Group ID`),$ref:v().url().optional().describe(`URI reference to the group`),display:v().optional().describe(`Group display name`),type:A([`direct`,`indirect`]).optional().describe(`Membership type`)})),dZ=X(()=>T({employeeNumber:v().optional().describe(`Employee number`),costCenter:v().optional().describe(`Cost center`),organization:v().optional().describe(`Organization`),division:v().optional().describe(`Division`),department:v().optional().describe(`Department`),manager:T({value:v().describe(`Manager ID`),$ref:v().url().optional().describe(`Manager URI`),displayName:v().optional().describe(`Manager name`)}).optional().describe(`Manager reference`)})),fZ=X(()=>T({schemas:w(v()).min(1).refine(e=>e.includes(iZ.USER),`Must include core User schema URI`).default([iZ.USER]).describe(`SCIM schema URIs (must include User schema)`),id:v().optional().describe(`Unique resource identifier`),externalId:v().optional().describe(`External identifier from client system`),userName:v().describe(`Unique username (REQUIRED)`),name:oZ.optional().describe(`Structured name components`),displayName:v().optional().describe(`Display name for UI`),nickName:v().optional().describe(`Nickname`),profileUrl:v().url().optional().describe(`Profile page URL`),title:v().optional().describe(`Job title`),userType:v().optional().describe(`User type (employee, contractor)`),preferredLanguage:v().optional().describe(`Preferred language (ISO 639-1)`),locale:v().optional().describe(`Locale (e.g., en-US)`),timezone:v().optional().describe(`Timezone`),active:b().optional().default(!0).describe(`Account active status`),password:v().optional().describe(`Password (write-only)`),emails:w(sZ).optional().describe(`Email addresses`),phoneNumbers:w(cZ).optional().describe(`Phone numbers`),ims:w(T({value:v(),type:v().optional(),primary:b().optional()})).optional().describe(`IM addresses`),photos:w(T({value:v().url(),type:A([`photo`,`thumbnail`]).optional(),primary:b().optional()})).optional().describe(`Photo URLs`),addresses:w(lZ).optional().describe(`Physical addresses`),groups:w(uZ).optional().describe(`Group memberships`),entitlements:w(T({value:v(),type:v().optional(),primary:b().optional()})).optional().describe(`Entitlements`),roles:w(T({value:v(),type:v().optional(),primary:b().optional()})).optional().describe(`Roles`),x509Certificates:w(T({value:v(),type:v().optional(),primary:b().optional()})).optional().describe(`X509 certificates`),meta:aZ.optional().describe(`Resource metadata`),[iZ.ENTERPRISE_USER]:dZ.optional().describe(`Enterprise user attributes`)}).superRefine((e,t)=>{e[iZ.ENTERPRISE_USER]!=null&&((e.schemas||[]).includes(iZ.ENTERPRISE_USER)||t.addIssue({code:ru.custom,path:[`schemas`],message:`schemas must include "${iZ.ENTERPRISE_USER}" when enterprise user extension attributes are present`}))})),pZ=X(()=>T({value:v().describe(`Member ID`),$ref:v().url().optional().describe(`URI reference to the member`),type:A([`User`,`Group`]).optional().describe(`Member type`),display:v().optional().describe(`Member display name`)})),mZ=X(()=>T({schemas:w(v()).min(1).refine(e=>e.includes(iZ.GROUP),`Must include core Group schema URI`).default([iZ.GROUP]).describe(`SCIM schema URIs (must include Group schema)`),id:v().optional().describe(`Unique resource identifier`),externalId:v().optional().describe(`External identifier from client system`),displayName:v().describe(`Group display name (REQUIRED)`),members:w(pZ).optional().describe(`Group members`),meta:aZ.optional().describe(`Resource metadata`)}));X(()=>T({schemas:w(v()).min(1).refine(e=>e.includes(iZ.LIST_RESPONSE),{message:`schemas must include ${iZ.LIST_RESPONSE}`}).default([iZ.LIST_RESPONSE]).describe(`SCIM schema URIs`),totalResults:y().int().min(0).describe(`Total results count`),Resources:w(E([fZ,mZ,k(v(),S())])).describe(`Resources array (Users, Groups, or custom resources)`),startIndex:y().int().min(1).optional().describe(`Start index (1-based)`),itemsPerPage:y().int().min(0).optional().describe(`Items per page`)})),X(()=>T({schemas:w(v()).min(1).refine(e=>e.includes(iZ.ERROR),{message:`schemas must include ${iZ.ERROR}`}).default([iZ.ERROR]).describe(`SCIM schema URIs`),status:y().int().min(400).max(599).describe(`HTTP status code`),scimType:A([`invalidFilter`,`tooMany`,`uniqueness`,`mutability`,`invalidSyntax`,`invalidPath`,`noTarget`,`invalidValue`,`invalidVers`,`sensitive`]).optional().describe(`SCIM error type`),detail:v().optional().describe(`Error detail message`)}));var hZ=X(()=>T({op:A([`add`,`remove`,`replace`]).describe(`Operation type`),path:v().optional().describe(`Attribute path (optional for add)`),value:S().optional().describe(`Value to set`)}));X(()=>T({schemas:w(v()).min(1).refine(e=>e.includes(iZ.PATCH_OP),{message:`SCIM PATCH requests must include the PatchOp schema URI`}).default([iZ.PATCH_OP]).describe(`SCIM schema URIs`),Operations:w(hZ).min(1).describe(`Patch operations`)}));var gZ=X(()=>T({method:A([`POST`,`PUT`,`PATCH`,`DELETE`]).describe(`HTTP method for the bulk operation`),path:v().describe(`Resource endpoint path (e.g. /Users, /Groups/{id})`),bulkId:v().optional().describe(`Client-assigned ID for cross-referencing between operations`),data:k(v(),S()).optional().describe(`Request body for POST/PUT/PATCH operations`),version:v().optional().describe(`ETag for optimistic concurrency control`)}));X(()=>T({schemas:w(j(iZ.BULK_REQUEST)).default([iZ.BULK_REQUEST]).describe(`SCIM schema URIs (BulkRequest)`),operations:w(gZ).min(1).describe(`Bulk operations to execute (minimum 1)`),failOnErrors:y().int().optional().describe(`Stop processing after this many errors`)}));var _Z=X(()=>T({method:A([`POST`,`PUT`,`PATCH`,`DELETE`]).describe(`HTTP method that was executed`),bulkId:v().optional().describe(`Client-assigned bulk operation ID`),location:v().optional().describe(`URL of the created or modified resource`),status:v().describe(`HTTP status code as string (e.g. "201", "400")`),response:S().optional().describe(`Response body (typically present for errors)`)}));X(()=>T({schemas:w(j(iZ.BULK_RESPONSE)).default([iZ.BULK_RESPONSE]).describe(`SCIM schema URIs (BulkResponse)`),operations:w(_Z).describe(`Results for each bulk operation`)})),X(()=>T({id:v().describe(`User ID`),name:v().optional().describe(`Display name`),email:v().optional().describe(`Email address`),roles:w(v()).default([]).describe(`Canonical role names assigned to the user (scope-resolved)`),isPlatformAdmin:b().optional().describe(`DERIVED alias of 'platform_admin' in roles. Deprecated.`),organizationId:v().nullable().optional().describe(`Active organization ID (null = platform/unscoped)`)}));var vZ=A([`select`,`insert`,`update`,`delete`,`all`]),yZ=X(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Policy unique identifier (snake_case)`),label:v().optional().describe(`Human-readable policy label`),description:v().optional().describe(`Policy description and business justification`),object:v().describe(`Target object name`),operation:vZ.describe(`Database operation this policy applies to`),using:v().optional().describe("Filter condition for SELECT/UPDATE/DELETE. One of the four compiler-supported forms: `field = current_user.<prop>`, `field = 'literal'`, `field IN (current_user.<array>)`, or `1 = 1`. Optional for INSERT-only policies."),check:v().optional().describe(`Validation condition for INSERT/UPDATE (defaults to USING clause if not specified - enforced at application level)`),roles:w(v()).optional().describe(`Roles this policy applies to (omit for all roles)`),enabled:b().default(!0).describe(`Whether this policy is active`),priority:y().int().default(0).describe(`Policy evaluation priority (higher = evaluated first)`),tags:w(v()).optional().describe(`Policy categorization tags`)}).superRefine((e,t)=>{!e.using&&!e.check&&t.addIssue({code:ru.custom,message:`At least one of "using" or "check" must be specified. For SELECT/UPDATE/DELETE operations, provide "using". For INSERT operations, provide "check".`})}));X(()=>T({timestamp:v().describe(`ISO 8601 timestamp of the evaluation`),userId:v().describe(`User ID whose access was evaluated`),operation:A([`select`,`insert`,`update`,`delete`]).describe(`Database operation being performed`),object:v().describe(`Target object name`),policyName:v().describe(`Name of the RLS policy evaluated`),granted:b().describe(`Whether access was granted`),evaluationDurationMs:y().describe(`Policy evaluation duration in milliseconds`),matchedCondition:v().optional().describe(`Which USING/CHECK clause matched`),rowCount:y().optional().describe(`Number of rows affected`),metadata:k(v(),S()).optional().describe(`Additional audit event metadata`)}));var bZ=X(()=>T({enabled:b().describe(`Enable RLS audit logging`),logLevel:A([`all`,`denied_only`,`granted_only`,`none`]).describe(`Which evaluations to log`),destination:A([`system_log`,`audit_trail`,`external`]).describe(`Audit log destination`),sampleRate:y().min(0).max(1).describe(`Sampling rate (0-1) for high-traffic environments`),retentionDays:y().int().default(90).describe(`Audit log retention period in days`),includeRowData:b().default(!1).describe(`Include row data in audit logs (security-sensitive)`),alertOnDenied:b().default(!0).describe(`Send alerts when access is denied`)}));X(()=>T({enabled:b().default(!0).describe(`Enable RLS enforcement globally`),defaultPolicy:A([`deny`,`allow`]).default(`deny`).describe(`Default action when no policies match`),allowSuperuserBypass:b().default(!0).describe(`Allow superusers to bypass RLS`),bypassRoles:w(v()).optional().describe(`Roles that bypass RLS (see all data)`),logEvaluations:b().default(!1).describe(`Log RLS policy evaluations for debugging`),cacheResults:b().default(!0).describe(`Cache RLS evaluation results`),cacheTtlSeconds:y().int().positive().default(300).describe(`Cache TTL in seconds`),prefetchUserContext:b().default(!0).describe(`Pre-fetch user context for performance`),audit:bZ.optional().describe(`RLS audit logging configuration`)})),X(()=>T({id:v().describe(`User ID`),email:v().email().optional().describe(`User email`),tenantId:v().optional().describe(`Tenant/Organization ID`),role:E([v(),w(v())]).optional().describe(`User role(s)`),department:v().optional().describe(`User department`),attributes:k(v(),S()).optional().describe(`Additional custom user attributes`)})),X(()=>T({policyName:v().describe(`Policy name`),granted:b().describe(`Whether access was granted`),durationMs:y().optional().describe(`Evaluation duration in milliseconds`),error:v().optional().describe(`Error message if evaluation failed`),usingResult:b().optional().describe(`USING clause evaluation result`),checkResult:b().optional().describe(`CHECK clause evaluation result`)}));var xZ=A([`own`,`own_and_reports`,`unit`,`unit_and_below`,`org`]),SZ=X(()=>T({allowCreate:b().default(!1).describe(`Create permission`),allowRead:b().default(!1).describe(`Read permission`),allowEdit:b().default(!1).describe(`Edit permission`),allowDelete:b().default(!1).describe(`Delete permission`),allowTransfer:b().default(!1).describe(`[EXPERIMENTAL — not enforced] Change record ownership`),allowRestore:b().default(!1).describe(`[EXPERIMENTAL — not enforced] Restore from trash (Undelete)`),allowPurge:b().default(!1).describe(`[EXPERIMENTAL — not enforced] Permanently delete (Hard Delete/GDPR)`),viewAllRecords:b().default(!1).describe(`View All Data (Bypass Sharing)`),modifyAllRecords:b().default(!1).describe(`Modify All Data (Bypass Sharing)`),readScope:xZ.optional().describe(`[ADR-0057 D1] Read depth: own|unit|unit_and_below|org`),writeScope:xZ.optional().describe(`[ADR-0057 D1] Write depth: own|unit|unit_and_below|org`)})),CZ=X(()=>T({readable:b().default(!0).describe(`Field read access`),editable:b().default(!1).describe(`Field edit access`)}));X(()=>T({name:Z.describe(`Permission set unique name (lowercase snake_case)`),label:v().optional().describe(`Display label`),isProfile:b().default(!1).describe(`Whether this is a user profile`),isDefault:b().default(!1).describe(`[ADR-0056 D7] When true, this profile is the FALLBACK assigned to authenticated users who have no explicit grants — an app declares its default access posture here instead of relying on the built-in member_default. Foundation for SSO/JIT provisioning.`),objects:k(v(),SZ).describe(`Entity permissions`),fields:k(v(),CZ).optional().describe(`Field level security`),systemPermissions:w(v()).optional().describe(`System level capabilities`),tabPermissions:k(v(),A([`visible`,`hidden`,`default_on`,`default_off`])).optional().describe(`App/tab visibility: visible, hidden, default_on (shown by default), default_off (available but hidden initially)`),rowLevelSecurity:w(yZ).optional().describe(`Row-level security policies (see rls.zod.ts for full spec)`),contextVariables:k(v(),S()).optional().describe(`Context variables for RLS evaluation`)}));var wZ=fK({schemaId:`permission`,type:`simple`,sections:[{label:`Identity`,description:`Permission Sets stack on top of a Profile to grant additional access. Profiles are the base set assigned 1:1 to each user.`,columns:2,fields:[{field:`name`,required:!0,colSpan:1,helpText:`Machine name (snake_case)`},{field:`label`,colSpan:1,helpText:`Display label for admins`},{field:`isProfile`,type:`toggle`,colSpan:2,helpText:`Profile = base set assigned to users. Permission Set = additive grant.`}]},{label:`System Permissions`,description:`High-level capabilities not tied to a specific object — e.g. manage_users, view_audit_logs.`,columns:1,fields:[{field:`systemPermissions`,type:`tags`,helpText:`List of system capability keys`}]},{label:`Object & Field Permissions`,description:`Per-object CRUD + per-field FLS. Edit via the matrix editor or paste JSON here.`,columns:1,fields:[{field:`objects`,widget:`json`,helpText:`{ "account": { allowRead: true, allowEdit: true, ... } }`},{field:`fields`,widget:`json`,helpText:`{ "account.amount": { readable: true, editable: false } }`}]},{label:`Tab & Row-Level Security`,description:`Tab visibility, RLS policies, and custom context variables for predicate evaluation.`,columns:1,fields:[{field:`tabPermissions`,widget:`json`,helpText:`{ "app_crm": "visible", "app_admin": "hidden" }`},{field:`rowLevelSecurity`,widget:`json`,helpText:`Array of RLS policies (see rls.zod.ts)`},{field:`contextVariables`,widget:`json`,helpText:`Custom variables referenced in RLS predicates`}]}]});A([`private`,`public_read`,`public_read_write`,`controlled_by_parent`]),A([`owner`,`criteria`]);var TZ=A([`read`,`edit`,`full`]),EZ=A([`user`,`group`,`role`,`role_and_subordinates`,`guest`]),DZ=T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Unique rule name (snake_case)`),label:v().optional().describe(`Human-readable label`),description:v().optional().describe(`Administrative notes`),object:v().describe(`Target Object Name`),active:b().default(!0),accessLevel:TZ.default(`read`),sharedWith:T({type:EZ,value:v().describe(`ID or Code of the User/Group/Role`)}).describe(`The recipient of the shared access`)}),OZ=X(()=>DZ.extend({type:j(`criteria`),condition:JH.describe('Predicate (CEL). e.g. P`record.department == "Sales"`')})),kZ=X(()=>DZ.extend({type:j(`owner`),ownedBy:T({type:EZ,value:v()}).describe(`Source group/role whose records are being shared`)}));X(()=>D(`type`,[OZ,kZ]));var AZ=A([`geography`,`industry`,`named_account`,`product_line`]);X(()=>T({name:v().describe(`Model Name (e.g. FY24 Planning)`),state:A([`planning`,`active`,`archived`]).default(`planning`),startDate:v().optional(),endDate:v().optional()})),X(()=>T({name:Z.describe(`Territory unique name (lowercase snake_case)`),label:v().describe(`Territory Label (e.g. "West Coast")`),modelId:v().describe(`Belongs to which Territory Model`),parent:v().optional().describe(`Parent Territory`),type:AZ.default(`geography`),assignmentRule:v().optional().describe(`Criteria based assignment rule`),assignedUsers:w(v()).optional(),accountAccess:A([`read`,`edit`]).default(`read`),opportunityAccess:A([`read`,`edit`]).default(`read`),caseAccess:A([`read`,`edit`]).default(`read`)}));var jZ=X(()=>T({minLength:y().default(8).describe(`[EXPERIMENTAL — not enforced] Minimum password length`),requireUppercase:b().default(!0).describe(`[EXPERIMENTAL — not enforced] Require an uppercase letter`),requireLowercase:b().default(!0).describe(`[EXPERIMENTAL — not enforced] Require a lowercase letter`),requireNumbers:b().default(!0).describe(`[EXPERIMENTAL — not enforced] Require a number`),requireSymbols:b().default(!1).describe(`[EXPERIMENTAL — not enforced] Require a symbol`),expirationDays:y().optional().describe(`[EXPERIMENTAL — not enforced] Force password change every X days`),historyCount:y().default(3).describe(`[EXPERIMENTAL — not enforced] Prevent reusing last X passwords`)})),MZ=X(()=>T({trustedRanges:w(v()).describe(`[EXPERIMENTAL — not enforced] CIDR ranges allowed to access (e.g. 10.0.0.0/8)`),blockUnknown:b().default(!1).describe(`[EXPERIMENTAL — not enforced] Block all IPs not in trusted ranges`),vpnRequired:b().default(!1).describe(`[EXPERIMENTAL — not enforced] Require VPN to access`)})),NZ=X(()=>T({idleTimeout:y().default(30).describe(`[EXPERIMENTAL — not enforced] Minutes before idle session logout`),absoluteTimeout:y().default(480).describe(`[EXPERIMENTAL — not enforced] Max session duration (minutes)`),forceMfa:b().default(!1).describe(`[EXPERIMENTAL — not enforced] Require 2FA for all users`)})),PZ=X(()=>T({logRetentionDays:y().default(180).describe(`[EXPERIMENTAL — not enforced] Days to retain audit logs`),sensitiveFields:w(v()).describe(`[EXPERIMENTAL — not enforced] Fields to redact in logs (e.g. password, ssn)`),captureRead:b().default(!1).describe(`[EXPERIMENTAL — not enforced] Log read access (High volume!)`)}));X(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`[EXPERIMENTAL — not enforced] Policy Name`),password:jZ.optional(),network:MZ.optional(),session:NZ.optional(),audit:PZ.optional(),isDefault:b().default(!1).describe(`[EXPERIMENTAL — not enforced] Apply to all users by default`),assignedProfiles:w(v()).optional().describe(`[EXPERIMENTAL — not enforced] Apply to specific profiles`)}));var FZ=X(()=>E([v().describe(`Action Name`),T({type:v(),params:k(v(),S()).optional()})])),IZ=X(()=>E([v().describe(`Guard Name (e.g., "isManager", "amountGT1000")`),T({type:v(),params:k(v(),S()).optional()})])),LZ=X(()=>T({target:v().optional().describe(`Target State ID`),cond:IZ.optional().describe(`Condition (Guard) required to take this path`),actions:w(FZ).optional().describe(`Actions to execute during transition`),description:v().optional().describe(`Human readable description of this rule`)}));X(()=>T({type:v().describe(`Event Type (e.g. "APPROVE", "REJECT", "Submit")`),schema:k(v(),S()).optional().describe(`Expected event payload structure`)}));var RZ=M(()=>T({type:A([`atomic`,`compound`,`parallel`,`final`,`history`]).default(`atomic`),entry:w(FZ).optional().describe(`Actions to run when entering this state`),exit:w(FZ).optional().describe(`Actions to run when leaving this state`),on:k(v(),E([v(),LZ,w(LZ)])).optional().describe(`Map of Event Type -> Transition Definition`),always:w(LZ).optional(),initial:v().optional().describe(`Initial child state (if compound)`),states:k(v(),RZ).optional(),meta:T({label:v().optional(),description:v().optional(),color:v().optional(),aiInstructions:v().optional().describe(`Specific instructions for AI when in this state`)}).optional()})),zZ=X(()=>T({id:Z.describe(`Unique Machine ID`),description:v().optional(),contextSchema:k(v(),S()).optional().describe(`Zod Schema for the machine context/memory`),initial:v().describe(`Initial State ID`),states:k(v(),RZ).describe(`State Nodes`),on:k(v(),E([v(),LZ,w(LZ)])).optional()})),BZ=X(()=>T({provider:A([`openai`,`azure_openai`,`anthropic`,`local`]).default(`openai`),model:v().describe(`Model name (e.g. gpt-4, claude-3-opus)`),temperature:y().min(0).max(2).default(.7),maxTokens:y().optional(),topP:y().optional()})),VZ=X(()=>T({type:A([`action`,`flow`,`query`,`vector_search`]),name:v().describe(`Reference name (Action Name, Flow Name)`),description:v().optional().describe(`Override description for the LLM`)})),HZ=X(()=>T({topics:w(v()).describe(`Topics/Tags to recruit knowledge from`),indexes:w(v()).describe(`Vector Store Indexes`)})),UZ=X(()=>A([`json_object`,`json_schema`,`regex`,`grammar`,`xml`]).describe(`Output format for structured agent responses`)),WZ=X(()=>A([`trim`,`parse_json`,`validate`,`coerce_types`]).describe(`Post-processing step for structured output`)),GZ=X(()=>T({format:UZ.describe(`Expected output format`),schema:k(v(),S()).optional().describe(`JSON Schema definition for output`),strict:b().default(!1).describe(`Enforce exact schema compliance`),retryOnValidationFailure:b().default(!0).describe(`Retry generation when output fails validation`),maxRetries:y().int().min(0).default(3).describe(`Maximum retries on validation failure`),fallbackFormat:UZ.optional().describe(`Fallback format if primary format fails`),transformPipeline:w(WZ).optional().describe(`Post-processing steps applied to output`)}).describe(`Structured output configuration for agent responses`));X(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Agent unique identifier`),label:v().describe(`Agent display name`),avatar:v().optional(),role:v().describe(`The persona/role (e.g. "Senior Support Engineer")`),instructions:v().describe(`System Prompt / Prime Directives`),model:BZ.optional(),lifecycle:zZ.optional().describe(`State machine defining the agent conversation follow and constraints`),surface:A([`ask`,`build`]).default(`ask`).describe(`Product surface this agent binds ('ask' | 'build') — ADR-0063 §1`),skills:w(v().regex(/^[a-z_][a-z0-9_]*$/)).optional().describe(`Skill names to attach (Agent→Skill→Tool architecture)`),tools:w(VZ).optional().describe(`Direct tool references (legacy fallback)`),knowledge:HZ.optional().describe(`RAG access`),active:b().default(!0),access:w(v()).optional().describe(`Who can chat with this agent`),permissions:w(v()).optional().describe(`Required permissions or roles`),tenantId:v().optional().describe(`Tenant/Organization ID`),visibility:A([`global`,`organization`,`private`]).default(`organization`),planning:T({strategy:A([`react`,`plan_and_execute`,`reflexion`,`tree_of_thought`]).default(`react`).describe(`Autonomous reasoning strategy`),maxIterations:y().int().min(1).max(100).default(10).describe(`Maximum planning loop iterations`),allowReplan:b().default(!0).describe(`Allow dynamic re-planning based on intermediate results`)}).optional().describe(`Autonomous reasoning and planning configuration`),memory:T({longTerm:T({enabled:b().default(!1).describe(`Enable long-term memory persistence`),store:A([`vector`,`database`,`redis`]).default(`vector`).describe(`Long-term memory storage backend`),maxEntries:y().int().min(1).optional().describe(`Max entries in long-term memory`)}).optional().describe(`Long-term / persistent memory`),reflectionInterval:y().int().min(1).optional().describe(`Reflect every N interactions to improve behavior`)}).optional().describe(`Agent memory management`),guardrails:T({maxTokensPerInvocation:y().int().min(1).optional().describe(`Token budget per single invocation`),maxExecutionTimeSec:y().int().min(1).optional().describe(`Max execution time in seconds`),blockedTopics:w(v()).optional().describe(`Forbidden topics or action names`)}).optional().describe(`Safety guardrails for the agent`),structuredOutput:GZ.optional().describe(`Structured output format and validation configuration`),protection:xG.optional().describe(`Package author protection block — lock policy for this agent.`),...bG}));var KZ=fK({schemaId:`agent`,type:`simple`,sections:[{name:`identity`,label:`Identity`,description:`How users see and reference this agent.`,columns:2,fields:[{field:`name`,required:!0,colSpan:1,helpText:`Unique identifier (snake_case)`},{field:`label`,required:!0,colSpan:1,helpText:`Display name (e.g., "Sales Assistant")`},{field:`role`,required:!0,colSpan:2,helpText:`Agent persona (e.g., "Customer Support Specialist")`},{field:`avatar`,colSpan:1,helpText:`Avatar image URL`},{field:`active`,colSpan:1,helpText:`Enable/disable this agent`}]},{name:`ai_configuration`,label:`AI Configuration`,description:`Model selection, instructions, planning, and memory.`,fields:[{field:`instructions`,required:!0,widget:`textarea`,helpText:`System prompt — tell the agent how to behave and what it can do`},{field:`model`,type:`composite`,helpText:`AI model configuration (provider, model name, temperature, etc.)`},{field:`planning`,type:`composite`,helpText:`Autonomous reasoning configuration (strategy, max iterations, replan)`},{field:`memory`,type:`composite`,helpText:`Memory management (short-term, long-term, reflection)`},{field:`lifecycle`,type:`composite`,helpText:`State machine defining conversation flow`}]},{name:`capabilities`,label:`Capabilities`,description:`Skills, tools, and knowledge sources the agent can use.`,fields:[{field:`skills`,widget:`string-tags`,helpText:`Skill names (Agent→Skill→Tool architecture)`},{field:`tools`,type:`repeater`,helpText:`Direct tool references (legacy mode)`},{field:`knowledge`,type:`composite`,helpText:`RAG knowledge access configuration`}]},{name:`access`,label:`Access & Security`,description:`Who can use this agent and what safeguards apply.`,collapsible:!0,collapsed:!0,fields:[{field:`visibility`,helpText:`Scope: global, organization, or private`},{field:`access`,widget:`string-tags`,helpText:`User IDs or role names who can chat with this agent`},{field:`permissions`,widget:`string-tags`,helpText:`Required permissions to use this agent`},{field:`tenantId`,helpText:`Restrict to specific organization ID`},{field:`guardrails`,type:`composite`,helpText:`Safety rules and content policies`}]}]}),qZ=X(()=>A([`data`,`action`,`flow`,`integration`,`vector_search`,`analytics`,`utility`]).describe(`Tool operational category`));X(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Tool unique identifier (snake_case)`),label:v().describe(`Tool display name`),description:v().describe(`Tool description for LLM function calling`),category:qZ.optional().describe(`Tool category for grouping and filtering`),parameters:k(v(),S()).describe(`JSON Schema for tool parameters`),outputSchema:k(v(),S()).optional().describe(`JSON Schema for tool output`),objectName:v().regex(/^[a-z_][a-z0-9_]*$/).optional().describe(`Target object name (snake_case)`),requiresConfirmation:b().default(!1).describe(`Require user confirmation before execution`),permissions:w(v()).optional().describe(`Required permissions or roles`),active:b().default(!0).describe(`Whether the tool is enabled`),builtIn:b().default(!1).describe(`Platform built-in tool flag`),protection:xG.optional().describe(`Package author protection block — lock policy for this tool.`),...bG}));var JZ=fK({schemaId:`tool`,type:`simple`,sections:[{label:`Basics`,description:`Tool identity and AI-facing description.`,columns:2,fields:[{field:`name`,required:!0,colSpan:1,helpText:`Unique identifier (snake_case)`},{field:`label`,required:!0,colSpan:1,helpText:`Display name for Studio UI`},{field:`description`,required:!0,widget:`textarea`,colSpan:2,helpText:`Tell AI when to use this tool — be specific!`},{field:`category`,colSpan:1,helpText:`Tool category (data, action, flow, integration, etc.)`},{field:`objectName`,widget:`ref:object`,colSpan:1,helpText:`Related object (if this tool operates on a specific object)`},{field:`active`,colSpan:1,helpText:`Enable/disable this tool`},{field:`builtIn`,colSpan:1,helpText:`Platform built-in tool (vs user-defined)`}]},{label:`Schemas`,description:`Inputs the tool accepts and the shape of its output.`,fields:[{field:`parameters`,type:`composite`,required:!0,helpText:`Input parameters — define properties like: {name: {type: "string", description: "..."}}`},{field:`outputSchema`,type:`composite`,helpText:`Output schema for validation (optional)`}]},{label:`Access & safety`,description:`Permissions and confirmation requirements.`,collapsible:!0,collapsed:!0,fields:[{field:`requiresConfirmation`,helpText:`Ask user to approve before executing (for destructive actions)`},{field:`permissions`,widget:`string-tags`,helpText:`Required permissions to use this tool`}]}]}),YZ=X(()=>T({field:v().describe(`Context field to evaluate`),operator:A([`eq`,`neq`,`in`,`not_in`,`contains`]).describe(`Comparison operator`),value:E([v(),w(v())]).describe(`Expected value or values`)}));X(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Skill unique identifier (snake_case)`),label:v().describe(`Skill display name`),description:v().optional().describe(`Skill description`),surface:A([`ask`,`build`,`both`]).default(`ask`).describe(`Agent surface this skill binds to ('ask' | 'build' | 'both') — ADR-0063 §3`),instructions:v().optional().describe(`LLM instructions when skill is active`),tools:w(v().regex(/^[a-z_][a-z0-9_]*\*?$/)).describe("Tool names belonging to this skill (supports trailing wildcard, e.g. `action_*`)"),triggerPhrases:w(v()).optional().describe(`Phrases that activate this skill`),triggerConditions:w(YZ).optional().describe(`Programmatic activation conditions`),permissions:w(v()).optional().describe(`Required permissions or roles`),active:b().default(!0).describe(`Whether the skill is enabled`),protection:xG.optional().describe(`Package author protection block — lock policy for this skill.`),...bG}));var XZ=fK({schemaId:`skill`,type:`simple`,sections:[{label:`Basics`,description:`Skill identity and human-readable description.`,columns:2,fields:[{field:`name`,required:!0,colSpan:1,helpText:`Unique identifier (snake_case)`},{field:`label`,required:!0,colSpan:1,helpText:`Display name (e.g., "Case Management")`},{field:`description`,widget:`textarea`,colSpan:2,helpText:`What this skill does`},{field:`active`,colSpan:1,helpText:`Enable/disable this skill`}]},{label:`AI Instructions`,description:`How the agent should reason with this skill.`,fields:[{field:`instructions`,widget:`textarea`,helpText:`Instructions for AI — tell it how to use these tools together`},{field:`tools`,widget:`string-tags`,required:!0,helpText:`Tool names (supports wildcard: action_*)`}]},{label:`Triggers`,description:`When this skill should activate.`,collapsible:!0,collapsed:!0,fields:[{field:`triggerPhrases`,widget:`string-tags`,helpText:`Natural language phrases that activate this skill`},{field:`triggerConditions`,type:`repeater`,helpText:`Programmatic conditions (e.g., objectName == "case")`}]},{label:`Access`,description:`Required permissions to use this skill.`,collapsible:!0,collapsed:!0,fields:[{field:`permissions`,widget:`string-tags`,helpText:`Required permissions to use this skill`}]}]}),ZZ=X(()=>T({promptTokens:y().int().nonnegative().describe(`Tokens consumed by the prompt`),completionTokens:y().int().nonnegative().describe(`Tokens generated in the completion`),totalTokens:y().int().nonnegative().describe(`Total tokens (prompt + completion)`)}));X(()=>T({model:v(),usage:ZZ,costUsd:y().nonnegative().describe(`Computed cost in USD`),latencyMs:y().nonnegative().optional(),timestamp:v().datetime().optional()}));var QZ=X(()=>A([`system`,`user`,`assistant`,`function`,`tool`]));X(()=>A([`text`,`image`,`file`,`code`,`structured`]));var $Z=X(()=>T({type:j(`text`),text:v().describe(`Text content`),metadata:k(v(),S()).optional()})),eQ=X(()=>T({type:j(`image`),imageUrl:v().url().describe(`Image URL`),detail:A([`low`,`high`,`auto`]).optional().default(`auto`),metadata:k(v(),S()).optional()})),tQ=X(()=>T({type:j(`file`),fileUrl:v().url().describe(`File attachment URL`),mimeType:v().describe(`MIME type`),fileName:v().optional(),metadata:k(v(),S()).optional()})),nQ=X(()=>T({type:j(`code`),text:v().describe(`Code snippet`),language:v().optional().default(`text`),metadata:k(v(),S()).optional()})),rQ=X(()=>E([$Z,eQ,tQ,nQ])),iQ=X(()=>T({name:v().describe(`Function name`),arguments:v().describe(`JSON string of function arguments`),result:v().optional().describe(`Function execution result`)})),aQ=X(()=>T({id:v().describe(`Tool call ID`),type:A([`function`]).default(`function`),function:iQ})),oQ=X(()=>T({id:v().describe(`Unique message ID`),timestamp:v().datetime().describe(`ISO 8601 timestamp`),role:QZ,content:w(rQ).describe(`Message content (multimodal array)`),functionCall:iQ.optional().describe(`Legacy function call`),toolCalls:w(aQ).optional().describe(`Tool calls`),toolCallId:v().optional().describe(`Tool call ID this message responds to`),name:v().optional().describe(`Name of the function/user`),tokens:ZZ.optional().describe(`Token usage for this message`),cost:y().nonnegative().optional().describe(`Cost for this message in USD`),pinned:b().optional().default(!1).describe(`Prevent removal during pruning`),importance:y().min(0).max(1).optional().describe(`Importance score for pruning`),embedding:w(y()).optional().describe(`Vector embedding for semantic search`),metadata:k(v(),S()).optional()})),sQ=X(()=>A([`fifo`,`importance`,`semantic`,`sliding_window`,`summary`])),cQ=X(()=>T({maxTokens:y().int().positive().describe(`Maximum total tokens`),maxPromptTokens:y().int().positive().optional().describe(`Max tokens for prompt`),maxCompletionTokens:y().int().positive().optional().describe(`Max tokens for completion`),reserveTokens:y().int().nonnegative().default(500).describe(`Reserve tokens for system messages`),bufferPercentage:y().min(0).max(1).default(.1).describe(`Buffer percentage (0.1 = 10%)`),strategy:sQ.default(`sliding_window`),slidingWindowSize:y().int().positive().optional().describe(`Number of recent messages to keep`),minImportanceScore:y().min(0).max(1).optional().describe(`Minimum importance to keep`),semanticThreshold:y().min(0).max(1).optional().describe(`Semantic similarity threshold`),enableSummarization:b().default(!1).describe(`Enable context summarization`),summarizationThreshold:y().int().positive().optional().describe(`Trigger summarization at N tokens`),summaryModel:v().optional().describe(`Model ID for summarization`),warnThreshold:y().min(0).max(1).default(.8).describe(`Warn at % of budget (0.8 = 80%)`)})),lQ=X(()=>T({promptTokens:y().int().nonnegative().default(0),completionTokens:y().int().nonnegative().default(0),totalTokens:y().int().nonnegative().default(0),budgetLimit:y().int().positive(),budgetUsed:y().int().nonnegative().default(0),budgetRemaining:y().int().nonnegative(),budgetPercentage:y().min(0).max(1).describe(`Usage as percentage of budget`),messageCount:y().int().nonnegative().default(0),prunedMessageCount:y().int().nonnegative().default(0),summarizedMessageCount:y().int().nonnegative().default(0)})),uQ=X(()=>T({sessionId:v().describe(`Conversation session ID`),userId:v().optional().describe(`User identifier`),agentId:v().optional().describe(`AI agent identifier`),object:v().optional().describe(`Related object (e.g., "case", "project")`),recordId:v().optional().describe(`Related record ID`),scope:k(v(),S()).optional().describe(`Additional context scope`),systemMessage:v().optional().describe(`System prompt/instructions`),metadata:k(v(),S()).optional()}));X(()=>T({id:v().describe(`Unique session ID`),name:v().optional().describe(`Session name/title`),context:uQ,modelId:v().optional().describe(`AI model ID`),tokenBudget:cQ,messages:w(oQ).default([]),tokens:lQ.optional(),totalTokens:ZZ.optional().describe(`Total tokens across all messages`),totalCost:y().nonnegative().optional().describe(`Total cost for this session in USD`),status:A([`active`,`paused`,`completed`,`archived`]).default(`active`),createdAt:v().datetime().describe(`ISO 8601 timestamp`),updatedAt:v().datetime().describe(`ISO 8601 timestamp`),expiresAt:v().datetime().optional().describe(`ISO 8601 timestamp`),metadata:k(v(),S()).optional()})),X(()=>T({summary:v().describe(`Conversation summary`),keyPoints:w(v()).optional().describe(`Key discussion points`),originalTokens:y().int().nonnegative().describe(`Original token count`),summaryTokens:y().int().nonnegative().describe(`Summary token count`),tokensSaved:y().int().nonnegative().describe(`Tokens saved`),messageRange:T({startIndex:y().int().nonnegative(),endIndex:y().int().nonnegative()}).describe(`Range of messages summarized`),generatedAt:v().datetime().describe(`ISO 8601 timestamp`),modelId:v().optional().describe(`Model used for summarization`)})),X(()=>T({timestamp:v().datetime().describe(`Event timestamp`),prunedMessages:w(T({messageId:v(),role:QZ,tokens:y().int().nonnegative(),importance:y().min(0).max(1).optional()})),tokensFreed:y().int().nonnegative(),messagesRemoved:y().int().nonnegative(),remainingTokens:y().int().nonnegative(),remainingMessages:y().int().nonnegative()})),X(()=>T({sessionId:v(),totalMessages:y().int().nonnegative(),userMessages:y().int().nonnegative(),assistantMessages:y().int().nonnegative(),systemMessages:y().int().nonnegative(),totalTokens:y().int().nonnegative(),averageTokensPerMessage:y().nonnegative(),peakTokenUsage:y().int().nonnegative(),pruningEvents:y().int().nonnegative().default(0),summarizationEvents:y().int().nonnegative().default(0),tokensSavedByPruning:y().int().nonnegative().default(0),tokensSavedBySummarization:y().int().nonnegative().default(0),duration:y().nonnegative().optional().describe(`Session duration in seconds`),firstMessageAt:v().datetime().optional().describe(`ISO 8601 timestamp`),lastMessageAt:v().datetime().optional().describe(`ISO 8601 timestamp`)}));var dQ=X(()=>A([`openai`,`azure_openai`,`anthropic`,`google`,`cohere`,`huggingface`,`local`,`custom`])),fQ=X(()=>T({textGeneration:b().optional().default(!0).describe(`Supports text generation`),textEmbedding:b().optional().default(!1).describe(`Supports text embedding`),imageGeneration:b().optional().default(!1).describe(`Supports image generation`),imageUnderstanding:b().optional().default(!1).describe(`Supports image understanding`),functionCalling:b().optional().default(!1).describe(`Supports function calling`),codeGeneration:b().optional().default(!1).describe(`Supports code generation`),reasoning:b().optional().default(!1).describe(`Supports advanced reasoning`)})),pQ=X(()=>T({maxTokens:y().int().positive().describe(`Maximum tokens per request`),contextWindow:y().int().positive().describe(`Context window size`),maxOutputTokens:y().int().positive().optional().describe(`Maximum output tokens`),rateLimit:T({requestsPerMinute:y().int().positive().optional(),tokensPerMinute:y().int().positive().optional()}).optional()})),mQ=X(()=>T({currency:v().optional().default(`USD`),inputCostPer1kTokens:y().optional().describe(`Cost per 1K input tokens`),outputCostPer1kTokens:y().optional().describe(`Cost per 1K output tokens`),embeddingCostPer1kTokens:y().optional().describe(`Cost per 1K embedding tokens`)})),hQ=X(()=>T({id:v().describe(`Unique model identifier`),name:v().describe(`Model display name`),version:v().describe(`Model version (e.g., "gpt-4-turbo-2024-04-09")`),provider:dQ,capabilities:fQ,limits:pQ,pricing:mQ.optional(),endpoint:v().url().optional().describe(`Custom API endpoint`),apiKey:v().optional().describe(`API key (Warning: Prefer secretRef)`),secretRef:v().optional().describe(`Reference to stored secret (e.g. system:openai_api_key)`),region:v().optional().describe(`Deployment region (e.g., "us-east-1")`),description:v().optional(),tags:w(v()).optional().describe(`Tags for categorization`),deprecated:b().optional().default(!1),recommendedFor:w(v()).optional().describe(`Use case recommendations`)})),gQ=X(()=>T({name:v().describe(`Variable name (e.g., "user_name", "context")`),type:A([`string`,`number`,`boolean`,`object`,`array`]).default(`string`),required:b().default(!1),defaultValue:S().optional(),description:v().optional(),validation:T({minLength:y().optional(),maxLength:y().optional(),pattern:v().optional(),enum:w(S()).optional()}).optional()})),_Q=X(()=>T({id:v().describe(`Unique template identifier`),name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Template name (snake_case)`),label:v().describe(`Display name`),system:XH.optional().describe(`System prompt — supports {{var}} interpolation`),user:XH.describe(`User prompt template — supports {{var}} interpolation`),assistant:v().optional().describe(`Assistant message prefix`),variables:w(gQ).optional().describe(`Template variables`),modelId:v().optional().describe(`Recommended model ID`),temperature:y().min(0).max(2).optional(),maxTokens:y().optional(),topP:y().optional(),frequencyPenalty:y().optional(),presencePenalty:y().optional(),stopSequences:w(v()).optional(),version:v().optional().default(`1.0.0`),description:v().optional(),category:v().optional().describe(`Template category (e.g., "code_generation", "support")`),tags:w(v()).optional(),examples:w(T({input:k(v(),S()).describe(`Example variable values`),output:v().describe(`Expected output`)})).optional()})),vQ=X(()=>T({model:hQ,status:A([`active`,`deprecated`,`experimental`,`disabled`]).default(`active`),priority:y().int().default(0).describe(`Priority for model selection`),fallbackModels:w(v()).optional().describe(`Fallback model IDs`),healthCheck:T({enabled:b().default(!0),intervalSeconds:y().int().default(300),lastChecked:v().optional().describe(`ISO timestamp`),status:A([`healthy`,`unhealthy`,`unknown`]).default(`unknown`)}).optional()}));X(()=>T({name:v().describe(`Registry name`),models:k(v(),vQ).describe(`Model entries by ID`),promptTemplates:k(v(),_Q).optional().describe(`Prompt templates by name`),defaultModel:v().optional().describe(`Default model ID`),enableAutoFallback:b().default(!0).describe(`Auto-fallback on errors`)})),X(()=>T({capabilities:w(v()).optional().describe(`Required capabilities`),maxCostPer1kTokens:y().optional().describe(`Maximum acceptable cost`),minContextWindow:y().optional().describe(`Minimum context window size`),provider:dQ.optional(),tags:w(v()).optional(),excludeDeprecated:b().default(!0)}));var yQ=X(()=>A([`pgvector`,`chroma`,`qdrant`,`pinecone`,`weaviate`,`milvus`,`redis`,`opensearch`,`elasticsearch`,`custom`])),bQ=X(()=>T({provider:A([`openai`,`cohere`,`azure_openai`,`huggingface`,`local`,`custom`]),model:v().describe(`Provider-specific model identifier`),dimensions:y().int().positive().describe(`Embedding vector dimensions`),endpoint:v().url().optional().describe(`Custom endpoint URL`),secretRef:v().optional().describe(`Reference to stored API key secret`)})),xQ=X(()=>T({provider:yQ,collection:v().describe(`Collection / index / namespace name`),endpoint:v().optional().describe(`Connection string or endpoint URL`),secretRef:v().optional().describe(`Reference to stored credential secret`),dimensions:y().int().positive().optional()})),SQ=X(()=>A([`stdio`,`http`,`websocket`]));X(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Machine name (snake_case)`),label:v().describe(`Display label`),transport:SQ,endpoint:v().describe(`Command (stdio) or URL (http/websocket)`),secretRef:v().optional(),active:b().default(!0)}));var CQ=X(()=>A([`always`,`never`,`first_call`]));X(()=>T({server:v(),toolName:v(),aliasAs:v().optional(),approval:CQ.default(`never`)}));var wQ=X(()=>T({onRecordChange:b().default(!0).optional(),cron:v().optional()})),TQ=X(()=>T({kind:j(`object`),object:v().describe(`Short object name to index`),contentFields:w(v()).min(1).describe(`Fields contributing to document content`),metadataFields:w(v()).default([]).optional(),where:k(v(),S()).optional()})),EQ=X(()=>T({kind:j(`file`),prefix:v().describe(`Storage prefix`),mimeTypes:w(v()).default([]).optional()})),DQ=X(()=>T({kind:j(`http`),urls:w(v().url()).min(1),userAgent:v().optional()})),OQ=X(()=>D(`kind`,[TQ,EQ,DQ]));X(()=>T({id:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Snake_case source id`),label:v(),description:v().optional(),adapter:v().describe(`Adapter id`),adapterConfig:k(v(),S()).default({}).optional(),source:OQ,embedding:bQ.optional(),vectorStore:xQ.optional(),refresh:wQ.default({}).optional(),aiExposed:b().default(!0).optional()})),X(()=>T({id:v().describe(`Document id`),sourceId:v().describe(`Owning KnowledgeSource id`),sourceRecordId:v().optional(),content:v(),title:v().optional(),metadata:k(v(),S()).default({}).optional(),permissions:w(v()).optional()})),X(()=>T({id:v(),documentId:v(),index:y().int().nonnegative(),content:v(),metadata:k(v(),S()).optional()})),X(()=>T({chunkId:v(),documentId:v(),sourceId:v(),sourceRecordId:v().optional(),score:y(),snippet:v(),title:v().optional(),metadata:k(v(),S()).default({}).optional()}));var kQ=/^[a-z_][a-z0-9_]*$/,AQ=X(()=>T({name:v().regex(kQ).describe(`Field machine name (snake_case)`),label:v().optional().describe(`Human-readable field label`),type:KW.describe(`Field data type`),required:b().optional().describe(`Whether the field is required`),reference:v().regex(kQ).optional().describe(`Target object name for lookup / master_detail relationship fields`),options:w(T({label:v(),value:v().regex(kQ)})).optional().describe(`Choices for select / multiselect / radio fields`)})),jQ=X(()=>T({name:v().regex(kQ).describe(`Object machine name (snake_case)`),label:v().optional().describe(`Human-readable singular label`),description:v().optional().describe(`What this object represents`),fields:w(AQ).describe(`Fields to create on the object`)})),MQ=X(()=>T({object:v().regex(kQ).describe(`Object this view displays (snake_case)`),name:v().regex(kQ).describe(`View machine name (snake_case)`),label:v().optional().describe(`Human-readable view label`),type:A([`list`,`form`,`kanban`,`calendar`]).default(`list`).describe(`View kind`),columns:w(v().regex(kQ)).optional().describe(`Field names shown as columns (in order)`),groupBy:v().regex(kQ).optional().describe(`REQUIRED for kanban views: the select/status field whose options become the board columns (e.g. "stage", "status"). Without it a kanban renders as a plain list.`)})),NQ=X(()=>T({name:v().regex(kQ).describe(`Dashboard machine name (snake_case)`),label:v().optional().describe(`Human-readable dashboard label`),widgets:w(T({id:v().regex(kQ).describe(`Widget id (snake_case)`),title:v().optional().describe(`Widget title`),object:v().regex(kQ).optional().describe(`Source object for the widget`),chart:A([`metric`,`bar`,`line`,`pie`,`table`]).optional().describe(`Widget visualization`),measure:v().regex(kQ).optional().describe(`The field this widget aggregates (e.g. "amount", "probability"), or "count" to count records. The aggregation is chosen automatically from the field type — a money field SUMs, a percentage/rate AVERAGEs — so name the FIELD, not "total_amount". A "total revenue" widget sets measure:"amount"; an "average win rate" widget sets measure:"win_rate"; a "number of deals" widget sets measure:"count". Omit to let the builder infer from the title.`),groupBy:v().regex(kQ).optional().describe(`The field to break the widget down by — the category or time axis (e.g. "stage", "created_at"). A "by status" chart MUST set this to the status field; the title and this field MUST name the SAME field. Omit for a single-number metric.`)})).optional().describe(`Widgets to place on the dashboard`)})),PQ=X(()=>T({type:A([`object`,`dashboard`]).default(`object`).describe(`What this nav entry opens`),target:v().regex(kQ).describe(`Object or dashboard machine name to surface (snake_case)`),label:v().optional().describe(`Nav entry label (defaults to the target label/name)`),icon:v().optional().describe(`Lucide icon name for the nav entry`)})),FQ=X(()=>T({name:v().regex(kQ).describe(`App machine name (snake_case)`),label:v().optional().describe(`App display label`),icon:v().optional().describe(`Lucide icon for the App Launcher`),nav:w(PQ).optional().describe(`Navigation entries; omit to auto-surface every created object and dashboard`)})),IQ=X(()=>T({object:v().regex(kQ).describe(`Target object name (snake_case)`),records:w(k(v(),S())).describe(`Rows to seed`)}));X(()=>T({summary:v().describe(`One-line description of the proposed solution`),assumptions:w(v()).default([]).describe(`Design assumptions made from the underspecified goal`),questions:w(v()).max(2).optional().describe(`At most 1-2 structure-deciding questions to confirm before building`),objects:w(jQ).describe(`Objects (tables) to create`),views:w(MQ).optional().describe(`Views to create`),dashboards:w(NQ).optional().describe(`Dashboards to create`),app:FQ.optional().describe(`The navigation shell (app) that surfaces the created objects/dashboards to end users`),seedData:w(IQ).optional().describe(`Suggested seed data (reported, not auto-applied in Phase C)`)}));var LQ=T({name:v().describe(`Field machine name (snake_case)`),label:v().nullable().describe(`Human-readable field label, or null`),type:KW.describe(`Field data type`),required:b().nullable().describe(`Whether the field is required, or null`),reference:v().nullable().describe(`Target object for lookup/master_detail, or null`),options:w(T({label:v(),value:v()})).nullable().describe(`Choices for select-family fields, or null`)}),RQ=T({name:v().describe(`Object machine name (snake_case)`),label:v().nullable().describe(`Human-readable singular label, or null`),description:v().nullable().describe(`What this object represents, or null`),fields:w(LQ).describe(`Fields to create on the object`)}),zQ=T({object:v().describe(`Object this view displays (snake_case)`),name:v().describe(`View machine name (snake_case)`),label:v().nullable().describe(`Human-readable view label, or null`),type:A([`list`,`form`,`kanban`,`calendar`]).nullable().describe(`View kind, or null for list`),columns:w(v()).nullable().describe(`Field names shown as columns, or null`),groupBy:v().nullable().describe(`REQUIRED for kanban: the select/status field whose options become the board columns (e.g. "stage"). Null for non-kanban views.`)}),BQ=T({name:v().describe(`Dashboard machine name (snake_case)`),label:v().nullable().describe(`Human-readable dashboard label, or null`),widgets:w(T({id:v().describe(`Widget id (snake_case)`),title:v().nullable().describe(`Widget title, or null`),object:v().nullable().describe(`Source object, or null`),chart:A([`metric`,`bar`,`line`,`pie`,`table`]).nullable().describe(`Visualization, or null`),measure:v().nullable().describe(`The field this widget aggregates (e.g. "amount", "probability"), or "count" to count records, or null to infer from the title. The aggregation (sum vs average) is chosen automatically from the field type — name the FIELD, not "total_amount". "total revenue" → "amount"; "average win rate" → "win_rate"; "number of deals" → "count".`),groupBy:v().nullable().describe(`The field to break the widget down by — the category or time axis (e.g. "stage", "created_at"), or null for a single-number metric. A "by status" chart MUST set this to the status field; the title and this field MUST name the SAME field.`)})).nullable().describe(`Widgets to place on the dashboard, or null`)}),VQ=T({type:A([`object`,`dashboard`]).describe(`What this nav entry opens`),target:v().describe(`Object or dashboard machine name to surface (snake_case)`),label:v().nullable().describe(`Nav entry label, or null`),icon:v().nullable().describe(`Lucide icon name, or null`)}),HQ=T({name:v().describe(`App machine name (snake_case)`),label:v().nullable().describe(`App display label, or null`),icon:v().nullable().describe(`Lucide icon for the App Launcher, or null`),nav:w(VQ).nullable().describe(`Navigation entries; null to auto-surface every created object and dashboard`)});T({summary:v().describe(`One-line description of the proposed solution`),assumptions:w(v()).describe(`Design assumptions made from the underspecified goal`),questions:w(v()).nullable().describe(`At most 1-2 structure-deciding questions to confirm before building, or null`),objects:w(RQ).describe(`Objects (tables) to create`),views:w(zQ).nullable().describe(`Views to create, or null`),dashboards:w(BQ).nullable().describe(`Dashboards to create, or null`),app:HQ.nullable().describe(`The navigation shell (app) that surfaces the created objects/dashboards, or null`)}),A([`start`,`end`,`decision`,`assignment`,`loop`,`create_record`,`update_record`,`delete_record`,`get_record`,`http`,`notify`,`script`,`screen`,`wait`,`subflow`,`map`,`connector_action`,`parallel_gateway`,`join_gateway`,`boundary_event`]).options;var UQ=X(()=>T({name:v().describe(`Variable name`),type:v().describe(`Data type (text, number, boolean, object, list)`),isInput:b().default(!1).describe(`Is input parameter`),isOutput:b().default(!1).describe(`Is output parameter`)})),WQ=X(()=>T({id:v().describe(`Node unique ID`),type:v().min(1).describe(`Action type — a built-in FlowNodeAction id or a plugin-registered node type. Validated against the live action registry at registerFlow() (ADR-0018), not by a closed enum.`),label:v().describe(`Node label`),config:k(v(),S()).optional().describe(`Node configuration`),connectorConfig:T({connectorId:v(),actionId:v(),input:k(v(),S()).describe(`Mapped inputs for the action`)}).optional(),position:T({x:y(),y:y()}).optional(),timeoutMs:y().int().min(0).optional().describe(`Maximum execution time for this node in milliseconds`),inputSchema:k(v(),T({type:A([`string`,`number`,`boolean`,`object`,`array`]).describe(`Parameter type`),required:b().default(!1).describe(`Whether the parameter is required`),description:v().optional().describe(`Parameter description`)})).optional().describe(`Input parameter schema for this node`),outputSchema:k(v(),T({type:A([`string`,`number`,`boolean`,`object`,`array`]).describe(`Output type`),description:v().optional().describe(`Output description`)})).optional().describe(`Output schema declaration for this node`),waitEventConfig:T({eventType:A([`timer`,`signal`,`webhook`,`manual`,`condition`]).describe(`What kind of event resumes the execution`),timerDuration:v().optional().describe(`ISO 8601 duration (e.g., "PT1H") or wait time for timer events`),signalName:v().optional().describe(`Named signal or webhook event to wait for`),timeoutMs:y().int().min(0).optional().describe(`Maximum wait time before timeout (ms)`),onTimeout:A([`fail`,`continue`]).default(`fail`).describe(`Behavior when the wait times out`)}).optional().describe(`Configuration for wait node event resumption`),boundaryConfig:T({attachedToNodeId:v().describe(`Host node ID this boundary event monitors`),eventType:A([`error`,`timer`,`signal`,`cancel`]).describe(`Boundary event trigger type`),interrupting:b().default(!0).describe(`If true, the host activity is cancelled when this event fires`),errorCode:v().optional().describe(`Specific error code to catch (empty = catch all errors)`),timerDuration:v().optional().describe(`ISO 8601 duration for timer boundary events`),signalName:v().optional().describe(`Named signal to catch`)}).optional().describe(`Configuration for boundary events attached to host nodes`)})),GQ=X(()=>T({id:v().describe(`Edge unique ID`),source:v().describe(`Source Node ID`),target:v().describe(`Target Node ID`),condition:JH.optional().describe(`Predicate (CEL) returning boolean used for branching.`),type:A([`default`,`fault`,`conditional`,`back`]).default(`default`).describe(`Connection type: default (normal flow), fault (error path), conditional (expression-guarded), or back (ADR-0044 declared back-edge — traversed normally at run time, but excluded from DAG cycle validation so a revise/rework loop can re-enter an earlier node)`),label:v().optional().describe(`Label on the connector`),isDefault:b().default(!1).describe(`Marks this edge as the default path when no other conditions match`)})),KQ=X(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Machine name`),label:v().describe(`Flow label`),description:v().optional(),successMessage:v().optional().describe(`Toast shown when a screen flow completes (defaults to a generic "Done").`),errorMessage:v().optional().describe(`Toast shown when a screen flow fails (defaults to the raw error).`),version:y().int().default(1).describe(`Version number`),status:A([`draft`,`active`,`obsolete`,`invalid`]).default(`draft`).describe(`Deployment status`),template:b().default(!1).describe(`Is logic template (Subflow)`),type:A([`autolaunched`,`record_change`,`schedule`,`screen`,`api`]).describe(`Flow type`),variables:w(UQ).optional().describe(`Flow variables`),nodes:w(WQ).describe(`Flow nodes`),edges:w(GQ).describe(`Flow connections`),active:b().default(!1).describe(`Is active (Deprecated: use status)`),runAs:A([`system`,`user`]).default(`user`).describe(`Execution identity for the run: system = elevated (bypasses RLS), user = the triggering user (RLS-respecting). A schedule-triggered run has no trigger user, so under user it runs UNSCOPED (elevated) — declare system to make that explicit.`),errorHandling:T({strategy:A([`fail`,`retry`,`continue`]).default(`fail`).describe(`How to handle node execution errors`),maxRetries:y().int().min(0).max(10).default(0).describe(`Number of retry attempts (only for retry strategy)`),retryDelayMs:y().int().min(0).default(1e3).describe(`Delay between retries in milliseconds`),backoffMultiplier:y().min(1).default(1).describe(`Multiplier for exponential backoff between retries`),maxRetryDelayMs:y().int().min(0).default(3e4).describe(`Maximum delay between retries in milliseconds`),jitter:b().default(!1).describe(`Add random jitter to retry delay to avoid thundering herd`),fallbackNodeId:v().optional().describe(`Node ID to jump to on unrecoverable error`)}).optional().describe(`Flow-level error handling configuration`),protection:xG.optional().describe(`Package author protection block — lock policy for this flow.`),...bG}));X(()=>T({flowName:v().describe(`Flow machine name`),version:y().int().min(1).describe(`Version number`),definition:KQ.describe(`Complete flow definition snapshot`),createdAt:v().datetime().describe(`When this version was created`),createdBy:v().optional().describe(`User who created this version`),changeNote:v().optional().describe(`Description of what changed in this version`)}));var qQ=1e5,JQ=X(()=>T({nodes:w(WQ).min(1).describe(`Region body nodes (single-entry/single-exit sub-graph)`),edges:w(GQ).default([]).describe(`Region body edges`)}));X(()=>T({collection:v().min(1).describe(`Template/variable resolving to the array to iterate`),iteratorVariable:v().min(1).default(`item`).describe(`Loop variable holding the current item`),indexVariable:v().optional().describe(`Optional loop variable holding the current index`),maxIterations:y().int().min(1).max(qQ).optional().describe(`Hard cap on iterations (clamped to the engine ceiling)`),body:JQ.optional().describe(`Loop body region (omit for legacy flat-graph loops)`)}));var YQ=X(()=>T({name:v().optional().describe(`Branch label`),nodes:w(WQ).min(1).describe(`Branch body nodes`),edges:w(GQ).default([]).describe(`Branch body edges`)}));X(()=>T({branches:w(YQ).min(2).describe(`Branch regions executed concurrently; implicit join at block end`)}));var XQ=X(()=>T({maxRetries:y().int().min(0).max(10).default(0).describe(`Retry attempts before giving up`),retryDelayMs:y().int().min(0).default(1e3).describe(`Base delay between retries (ms)`),backoffMultiplier:y().min(1).default(1).describe(`Exponential backoff multiplier`),maxRetryDelayMs:y().int().min(0).default(3e4).describe(`Maximum delay between retries (ms)`),jitter:b().default(!1).describe(`Add random jitter to retry delay`)}));X(()=>T({try:JQ.describe(`Protected region`),catch:JQ.optional().describe(`Handler region run when the try region fails`),errorVariable:v().default(`$error`).describe(`Variable holding the caught error in the catch region`),retry:XQ.optional().describe(`Optional retry policy for the try region`)}));var ZQ=fK({schemaId:`flow`,type:`simple`,sections:[{name:`basics`,label:`Basics`,description:`Flow identity and how it starts.`,columns:2,fields:[{field:`name`,required:!0,colSpan:1,helpText:`Unique identifier (snake_case)`},{field:`label`,required:!0,colSpan:1,helpText:`Display name for users`},{field:`type`,required:!0,colSpan:1,helpText:`How the flow starts (autolaunched, record_change, schedule, screen, api)`},{field:`template`,colSpan:1,helpText:`Is this a reusable subflow (can be called from other flows)`},{field:`description`,widget:`textarea`,colSpan:2,helpText:`What this flow does`}]},{name:`canvas`,label:`Canvas`,description:`Nodes, edges, and flow variables — consider the visual designer for complex flows.`,fields:[{field:`nodes`,type:`repeater`,required:!0,helpText:`⚠️ Consider using Flow Designer visual editor instead of JSON`},{field:`edges`,type:`repeater`,required:!0,helpText:`Connections between nodes — use Flow Designer for easier editing`},{field:`variables`,type:`repeater`,helpText:`Flow variables (inputs/outputs)`}]},{name:`execution`,label:`Execution`,description:`Deployment status, identity, and error handling.`,collapsible:!0,collapsed:!0,columns:2,fields:[{field:`status`,required:!0,colSpan:1,helpText:`Deployment status: draft → active → obsolete`},{field:`version`,colSpan:1,helpText:`Version number (auto-incremented)`},{field:`runAs`,colSpan:1,helpText:`Execute as system (admin) or user (current user permissions)`},{field:`errorHandling`,type:`composite`,colSpan:2,helpText:`What to do when a node fails (fail, retry, continue)`}]}]}),QQ=A([`pending`,`running`,`paused`,`completed`,`failed`,`cancelled`,`timed_out`,`retrying`]),$Q=X(()=>T({nodeId:v().describe(`Node ID that was executed`),nodeType:v().describe(`Node action type (e.g., "decision", "http")`),nodeLabel:v().optional().describe(`Human-readable node label`),status:A([`success`,`failure`,`skipped`]).describe(`Step execution result`),startedAt:v().datetime().describe(`When the step started`),completedAt:v().datetime().optional().describe(`When the step completed`),durationMs:y().int().min(0).optional().describe(`Step execution duration in milliseconds`),input:k(v(),S()).optional().describe(`Input data passed to the node`),output:k(v(),S()).optional().describe(`Output data produced by the node`),error:T({code:v().describe(`Error code`),message:v().describe(`Error message`),stack:v().optional().describe(`Stack trace`)}).optional().describe(`Error details if step failed`),retryAttempt:y().int().min(0).optional().describe(`Retry attempt number (0 = first try)`),parentNodeId:v().optional().describe(`Enclosing structured-region container node ID (loop/parallel/try_catch)`),iteration:y().int().min(0).optional().describe(`Zero-based loop iteration or parallel branch index of the enclosing region`),regionKind:v().optional().describe(`Region kind the step ran in: loop-body | parallel-branch | try | catch`)}));X(()=>T({id:v().describe(`Execution instance ID`),flowName:v().describe(`Machine name of the executed flow`),flowVersion:y().int().optional().describe(`Version of the flow that was executed`),status:QQ.describe(`Current execution status`),trigger:T({type:v().describe(`Trigger type (e.g., "record_change", "schedule", "api", "manual")`),recordId:v().optional().describe(`Triggering record ID`),object:v().optional().describe(`Triggering object name`),userId:v().optional().describe(`User who triggered the execution`),metadata:k(v(),S()).optional().describe(`Additional trigger context`)}).describe(`What triggered this execution`),steps:w($Q).describe(`Ordered list of executed steps`),variables:k(v(),S()).optional().describe(`Final state of flow variables`),startedAt:v().datetime().describe(`Execution start timestamp`),completedAt:v().datetime().optional().describe(`Execution completion timestamp`),durationMs:y().int().min(0).optional().describe(`Total execution duration in milliseconds`),runAs:A([`system`,`user`]).optional().describe(`Execution context identity`),tenantId:v().optional().describe(`Tenant ID for multi-tenant isolation`)}));var e$=A([`warning`,`error`,`critical`]);X(()=>T({id:v().describe(`Error record ID`),executionId:v().describe(`Parent execution ID`),nodeId:v().optional().describe(`Node where the error occurred`),severity:e$.describe(`Error severity level`),code:v().describe(`Machine-readable error code`),message:v().describe(`Human-readable error message`),stack:v().optional().describe(`Stack trace for debugging`),context:k(v(),S()).optional().describe(`Additional diagnostic context (input data, config snapshot)`),timestamp:v().datetime().describe(`When the error occurred`),retryable:b().default(!1).describe(`Whether this error can be retried`),resolvedAt:v().datetime().optional().describe(`When the error was resolved (e.g., after successful retry)`)})),X(()=>T({id:v().describe(`Checkpoint ID`),executionId:v().describe(`Parent execution ID`),flowName:v().describe(`Flow machine name`),currentNodeId:v().describe(`Node ID where execution is paused`),variables:k(v(),S()).describe(`Flow variable state at checkpoint`),completedNodeIds:w(v()).describe(`List of node IDs already executed`),createdAt:v().datetime().describe(`Checkpoint creation timestamp`),expiresAt:v().datetime().optional().describe(`Checkpoint expiration (auto-cleanup)`),reason:A([`wait`,`screen_input`,`approval`,`error`,`manual_pause`,`parallel_join`,`boundary_event`]).describe(`Why the execution was checkpointed`)})),X(()=>T({maxConcurrent:y().int().min(1).default(1).describe(`Maximum number of concurrent executions allowed`),onConflict:A([`queue`,`reject`,`cancel_existing`]).default(`queue`).describe(`queue = enqueue for later, reject = fail immediately, cancel_existing = stop running instance`),lockScope:A([`global`,`per_record`,`per_user`]).default(`global`).describe(`Scope of the concurrency lock`),queueTimeoutMs:y().int().min(0).optional().describe(`Maximum time to wait in queue before timing out (ms)`)})),X(()=>T({id:v().describe(`Schedule instance ID`),flowName:v().describe(`Flow machine name`),cronExpression:YH.describe("Cron expression — cron`0 9 * * MON-FRI`"),timezone:v().default(`UTC`).describe(`IANA timezone for cron evaluation`),status:A([`active`,`paused`,`disabled`,`expired`]).default(`active`).describe(`Current schedule status`),nextRunAt:v().datetime().optional().describe(`Next scheduled execution timestamp`),lastRunAt:v().datetime().optional().describe(`Last execution timestamp`),lastExecutionId:v().optional().describe(`Execution ID of the last run`),lastRunStatus:QQ.optional().describe(`Status of the last run`),totalRuns:y().int().min(0).default(0).describe(`Total number of executions`),consecutiveFailures:y().int().min(0).default(0).describe(`Consecutive failed executions`),startDate:v().datetime().optional().describe(`Schedule effective start date`),endDate:v().datetime().optional().describe(`Schedule expiration date`),maxRuns:y().int().min(1).optional().describe(`Maximum total executions before auto-disable`),createdAt:v().datetime().describe(`Schedule creation timestamp`),updatedAt:v().datetime().optional().describe(`Last update timestamp`),createdBy:v().optional().describe(`User who created the schedule`)}));var t$=A([`create`,`update`,`delete`,`undelete`,`api`]);X(()=>T({name:Z.describe(`Webhook unique name (lowercase snake_case)`),label:v().optional().describe(`Human-readable webhook label`),object:v().optional().describe(`Object to listen to (optional for manual webhooks)`),triggers:w(t$).optional().describe(`Events that trigger execution`),url:v().url().describe(`External webhook endpoint URL`),method:A([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`]).default(`POST`).describe(`HTTP method`),headers:k(v(),v()).optional().describe(`Custom HTTP headers`),body:S().optional().describe(`Request body payload (if not using default record data)`),payloadFields:w(v()).optional().describe(`Fields to include. Empty = All`),includeSession:b().default(!1).describe(`Include user session info`),authentication:T({type:A([`none`,`bearer`,`basic`,`api-key`]).describe(`Authentication type`),credentials:k(v(),v()).optional().describe(`Authentication credentials`)}).optional().describe(`Authentication configuration`),retryPolicy:T({maxRetries:y().int().min(0).max(10).default(3).describe(`Maximum retry attempts`),backoffStrategy:A([`exponential`,`linear`,`fixed`]).default(`exponential`).describe(`Backoff strategy`),initialDelayMs:y().int().min(100).default(1e3).describe(`Initial retry delay in milliseconds`),maxDelayMs:y().int().min(1e3).default(6e4).describe(`Maximum retry delay in milliseconds`)}).optional().describe(`Retry policy configuration`),timeoutMs:y().int().min(1e3).max(3e5).default(3e4).describe(`Request timeout in milliseconds`),secret:v().optional().describe(`Signing secret for HMAC signature verification`),isActive:b().default(!0).describe(`Whether webhook is active`),description:v().optional().describe(`Webhook description`),tags:w(v()).optional().describe(`Tags for organization`)})),X(()=>T({name:Z.describe(`Webhook receiver unique name (lowercase snake_case)`),path:v().describe(`URL Path (e.g. /webhooks/stripe)`),verificationType:A([`none`,`header_token`,`hmac`,`ip_whitelist`]).default(`none`),verificationParams:T({header:v().optional(),secret:v().optional(),ips:w(v()).optional()}).optional(),action:A([`trigger_flow`,`script`,`upsert_record`]).default(`trigger_flow`),target:v().describe(`Flow ID or Script name`)}));var n$=A([`user`,`role`,`team`,`department`,`manager`,`field`,`queue`]);A([`approve`,`reject`]);var r$=X(()=>T({type:n$,value:v().optional().meta({description:"User id / role / team / department / field / queue — per `type`",xRef:{kindFrom:`type`,objectSource:`$trigger`,map:{user:`user`,role:`role`,team:`team`,department:`department`,field:`object-field`,queue:`queue`}}})})),i$=X(()=>T({enabled:b().default(!1).describe(`Enable SLA-based escalation for this node`),timeoutHours:y().min(1).describe(`Hours before escalation triggers`),action:A([`reassign`,`auto_approve`,`auto_reject`,`notify`]).default(`notify`).describe(`Action on escalation timeout`),escalateTo:v().optional().meta({description:`User id, role, or manager level to escalate to`,xRef:{kind:`role`}}),notifySubmitter:b().default(!0).describe(`Notify the original submitter on escalation`)}));X(()=>T({approvers:w(r$).min(1).describe(`Allowed approvers for this node`),behavior:A([`first_response`,`unanimous`]).default(`first_response`).describe(`How to combine multiple approvers`),lockRecord:b().default(!0).describe(`Lock the record from editing while pending`),approvalStatusField:v().optional().meta({description:`Business-object field to mirror request status onto`,xRef:{kind:`object-field`,objectSource:`$trigger`}}),escalation:i$.optional().describe(`Per-node SLA escalation`),maxRevisions:y().int().min(0).default(3).describe(`Max send-backs for revision before auto-reject (0 = send-back disabled)`)}));var a$=X(()=>A([`database`,`api`,`file`,`stream`,`object`,`warehouse`,`storage`,`spreadsheet`])),o$=X(()=>T({type:a$.describe(`Source type`),connector:v().optional().describe(`Connector ID`),config:k(v(),S()).describe(`Source configuration`),incremental:T({enabled:b().default(!1),cursorField:v().describe(`Field to track progress (e.g., updated_at)`),cursorValue:S().optional().describe(`Last processed value`)}).optional().describe(`Incremental extraction config`)})),s$=X(()=>T({type:a$.describe(`Destination type`),connector:v().optional().describe(`Connector ID`),config:k(v(),S()).describe(`Destination configuration`),writeMode:A([`append`,`overwrite`,`upsert`,`merge`]).default(`append`).describe(`How to write data`),primaryKey:w(v()).optional().describe(`Primary key fields`)})),c$=X(()=>A([`map`,`filter`,`aggregate`,`join`,`script`,`lookup`,`split`,`merge`,`normalize`,`deduplicate`])),l$=X(()=>T({name:v().optional().describe(`Transformation name`),type:c$.describe(`Transformation type`),config:k(v(),S()).describe(`Transformation config`),continueOnError:b().default(!1).describe(`Continue on error`)})),u$=X(()=>A([`full`,`incremental`,`cdc`]));X(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Pipeline identifier (snake_case)`),label:v().optional().describe(`Pipeline display name`),description:v().optional().describe(`Pipeline description`),source:o$.describe(`Data source`),destination:s$.describe(`Data destination`),transformations:w(l$).optional().describe(`Transformation pipeline`),syncMode:u$.default(`full`).describe(`Sync mode`),schedule:YH.optional().describe(`Cron schedule expression`),enabled:b().default(!0).describe(`Pipeline enabled status`),retry:T({maxAttempts:y().int().min(0).default(3).describe(`Max retry attempts`),backoffMs:y().int().min(0).default(6e4).describe(`Backoff in milliseconds`)}).optional().describe(`Retry configuration`),notifications:T({onSuccess:w(v()).optional().describe(`Email addresses for success notifications`),onFailure:w(v()).optional().describe(`Email addresses for failure notifications`)}).optional().describe(`Notification settings`),tags:w(v()).optional().describe(`Pipeline tags`),metadata:k(v(),S()).optional().describe(`Custom metadata`)}));var d$=X(()=>A([`pending`,`running`,`succeeded`,`failed`,`cancelled`,`timeout`]));X(()=>T({id:v().describe(`Run identifier`),pipelineName:v().describe(`Pipeline name`),status:d$.describe(`Run status`),startedAt:v().datetime().describe(`Start time`),completedAt:v().datetime().optional().describe(`Completion time`),durationMs:y().optional().describe(`Duration in ms`),stats:T({recordsRead:y().int().default(0).describe(`Records extracted`),recordsWritten:y().int().default(0).describe(`Records loaded`),recordsErrored:y().int().default(0).describe(`Records with errors`),bytesProcessed:y().int().default(0).describe(`Bytes processed`)}).optional().describe(`Run statistics`),error:T({message:v().describe(`Error message`),code:v().optional().describe(`Error code`),details:S().optional().describe(`Error details`)}).optional().describe(`Error information`),logs:w(v()).optional().describe(`Execution logs`)}));var f$=X(()=>A([`crm`,`payment`,`communication`,`storage`,`analytics`,`database`,`marketing`,`accounting`,`hr`,`productivity`,`ecommerce`,`support`,`devtools`,`social`,`other`])),p$=X(()=>A([`none`,`apiKey`,`basic`,`bearer`,`oauth1`,`oauth2`,`custom`])),m$=X(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Field name (snake_case)`),label:v().describe(`Field label`),type:A([`text`,`password`,`url`,`select`]).default(`text`).describe(`Field type`),description:v().optional().describe(`Field description`),required:b().default(!0).describe(`Required field`),default:v().optional().describe(`Default value`),options:w(T({label:v(),value:v()})).optional().describe(`Select field options`),placeholder:v().optional().describe(`Placeholder text`)})),h$=X(()=>T({authorizationUrl:v().url().describe(`Authorization endpoint URL`),tokenUrl:v().url().describe(`Token endpoint URL`),scopes:w(v()).optional().describe(`OAuth scopes`),clientIdField:v().default(`client_id`).describe(`Client ID field name`),clientSecretField:v().default(`client_secret`).describe(`Client secret field name`)})),g$=X(()=>T({type:p$.describe(`Authentication type`),fields:w(m$).optional().describe(`Authentication fields`),oauth2:h$.optional().describe(`OAuth 2.0 configuration`),test:T({url:v().optional().describe(`Test endpoint URL`),method:A([`GET`,`POST`,`PUT`,`DELETE`]).default(`GET`).describe(`HTTP method`)}).optional().describe(`Authentication test configuration`)})),_$=X(()=>A([`read`,`write`,`delete`,`search`,`trigger`,`action`])),v$=X(()=>T({name:v().describe(`Parameter name`),label:v().describe(`Parameter label`),description:v().optional().describe(`Parameter description`),type:A([`string`,`number`,`boolean`,`array`,`object`,`date`,`file`]).describe(`Parameter type`),required:b().default(!1).describe(`Required parameter`),default:S().optional().describe(`Default value`),validation:k(v(),S()).optional().describe(`Validation rules`),dynamicOptions:v().optional().describe(`Function to load dynamic options`)})),y$=X(()=>T({id:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Operation ID (snake_case)`),name:v().describe(`Operation name`),description:v().optional().describe(`Operation description`),type:_$.describe(`Operation type`),inputSchema:w(v$).optional().describe(`Input parameters`),outputSchema:k(v(),S()).optional().describe(`Output schema`),sampleOutput:S().optional().describe(`Sample output`),supportsPagination:b().default(!1).describe(`Supports pagination`),supportsFiltering:b().default(!1).describe(`Supports filtering`)})),b$=X(()=>T({id:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Trigger ID (snake_case)`),name:v().describe(`Trigger name`),description:v().optional().describe(`Trigger description`),type:A([`webhook`,`polling`,`stream`]).describe(`Trigger mechanism`),config:k(v(),S()).optional().describe(`Trigger configuration`),outputSchema:k(v(),S()).optional().describe(`Event payload schema`),pollingIntervalMs:y().int().min(1e3).optional().describe(`Polling interval in ms`)}));X(()=>T({id:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Connector ID (snake_case)`),name:v().describe(`Connector name`),description:v().optional().describe(`Connector description`),version:v().optional().describe(`Connector version`),icon:v().optional().describe(`Connector icon`),category:f$.describe(`Connector category`),baseUrl:v().url().optional().describe(`API base URL`),authentication:g$.describe(`Authentication config`),operations:w(y$).optional().describe(`Connector operations`),triggers:w(b$).optional().describe(`Connector triggers`),rateLimit:T({requestsPerSecond:y().optional().describe(`Max requests per second`),requestsPerMinute:y().optional().describe(`Max requests per minute`),requestsPerHour:y().optional().describe(`Max requests per hour`)}).optional().describe(`Rate limiting`),author:v().optional().describe(`Connector author`),documentation:v().url().optional().describe(`Documentation URL`),homepage:v().url().optional().describe(`Homepage URL`),license:v().optional().describe(`License (SPDX identifier)`),tags:w(v()).optional().describe(`Connector tags`),verified:b().default(!1).describe(`Verified connector`),metadata:k(v(),S()).optional().describe(`Custom metadata`)})),X(()=>T({id:v().describe(`Instance ID`),connectorId:v().describe(`Connector ID`),name:v().describe(`Instance name`),description:v().optional().describe(`Instance description`),credentials:k(v(),S()).describe(`Encrypted credentials`),config:k(v(),S()).optional().describe(`Additional config`),active:b().default(!0).describe(`Instance active status`),createdAt:v().datetime().optional().describe(`Creation time`),lastTestedAt:v().datetime().optional().describe(`Last test time`),testStatus:A([`unknown`,`success`,`failed`]).default(`unknown`).describe(`Connection test status`)}));var x$=X(()=>A([`push`,`pull`,`bidirectional`])),S$=X(()=>A([`full`,`incremental`,`realtime`])),C$=X(()=>A([`source_wins`,`destination_wins`,`latest_wins`,`manual`,`merge`])),w$=X(()=>T({object:v().optional().describe(`ObjectStack object name`),filters:S().optional().describe(`Filter conditions`),fields:w(v()).optional().describe(`Fields to sync`),connectorInstanceId:v().optional().describe(`Connector instance ID`),externalResource:v().optional().describe(`External resource ID`)})),T$=X(()=>T({object:v().optional().describe(`ObjectStack object name`),connectorInstanceId:v().optional().describe(`Connector instance ID`),operation:A([`insert`,`update`,`upsert`,`delete`,`sync`]).describe(`Sync operation`),mapping:E([k(v(),v()),w(RJ)]).optional().describe(`Field mappings`),externalResource:v().optional().describe(`External resource ID`),matchKey:w(v()).optional().describe(`Match key fields`)}));X(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Sync configuration name (snake_case)`),label:v().optional().describe(`Sync display name`),description:v().optional().describe(`Sync description`),source:w$.describe(`Data source`),destination:T$.describe(`Data destination`),direction:x$.default(`push`).describe(`Sync direction`),syncMode:S$.default(`incremental`).describe(`Sync mode`),conflictResolution:C$.default(`latest_wins`).describe(`Conflict resolution`),schedule:YH.optional().describe(`Cron schedule`),enabled:b().default(!0).describe(`Sync enabled`),changeTrackingField:v().optional().describe(`Field for change tracking`),batchSize:y().int().min(1).max(1e4).default(100).describe(`Batch size for processing`),retry:T({maxAttempts:y().int().min(0).default(3).describe(`Max retries`),backoffMs:y().int().min(0).default(3e4).describe(`Backoff duration`)}).optional().describe(`Retry configuration`),validation:T({required:w(v()).optional().describe(`Required fields`),unique:w(v()).optional().describe(`Unique constraint fields`),custom:w(T({name:v(),condition:JH.describe(`Validation predicate (CEL).`),message:v().describe(`Error message`)})).optional().describe(`Custom validation rules`)}).optional().describe(`Validation rules`),errorHandling:T({onValidationError:A([`skip`,`fail`,`log`]).default(`skip`),onSyncError:A([`skip`,`fail`,`retry`]).default(`retry`),notifyOnError:w(v()).optional().describe(`Email notifications`)}).optional().describe(`Error handling`),optimization:T({parallelBatches:b().default(!1).describe(`Process batches in parallel`),cacheEnabled:b().default(!0).describe(`Enable caching`),compressionEnabled:b().default(!1).describe(`Enable compression`)}).optional().describe(`Performance optimization`),audit:T({logLevel:A([`none`,`error`,`warn`,`info`,`debug`]).default(`info`),retainLogsForDays:y().int().min(1).default(30),trackChanges:b().default(!0).describe(`Track all changes`)}).optional().describe(`Audit configuration`),tags:w(v()).optional().describe(`Sync tags`),metadata:k(v(),S()).optional().describe(`Custom metadata`)}));var E$=X(()=>A([`pending`,`running`,`completed`,`partial`,`failed`,`cancelled`]));X(()=>T({id:v().describe(`Execution ID`),syncName:v().describe(`Sync name`),status:E$.describe(`Execution status`),startedAt:v().datetime().describe(`Start time`),completedAt:v().datetime().optional().describe(`Completion time`),durationMs:y().optional().describe(`Duration in ms`),stats:T({recordsProcessed:y().int().default(0).describe(`Total records processed`),recordsInserted:y().int().default(0).describe(`Records inserted`),recordsUpdated:y().int().default(0).describe(`Records updated`),recordsDeleted:y().int().default(0).describe(`Records deleted`),recordsSkipped:y().int().default(0).describe(`Records skipped`),recordsErrored:y().int().default(0).describe(`Records with errors`),conflictsDetected:y().int().default(0).describe(`Conflicts detected`),conflictsResolved:y().int().default(0).describe(`Conflicts resolved`)}).optional().describe(`Execution statistics`),errors:w(T({recordId:v().optional().describe(`Record ID`),field:v().optional().describe(`Field name`),message:v().describe(`Error message`),code:v().optional().describe(`Error code`)})).optional().describe(`Errors`),logs:w(v()).optional().describe(`Execution logs`)}));var D$=X(()=>A([`timer`,`signal`,`webhook`,`manual`,`condition`]).describe(`Wait event type determining how a paused flow is resumed`));X(()=>T({executionId:v().describe(`Execution ID of the paused flow`),checkpointId:v().describe(`Checkpoint ID to resume from`),nodeId:v().describe(`Wait node ID being resumed`),eventType:D$.describe(`Event type that triggered resume`),signalName:v().optional().describe(`Signal name (when eventType is signal)`),webhookPayload:k(v(),S()).optional().describe(`Webhook request payload (when eventType is webhook)`),resumedBy:v().optional().describe(`User ID or system identifier that triggered resume`),resumedAt:v().datetime().describe(`ISO 8601 timestamp of the resume event`),variables:k(v(),S()).optional().describe(`Variables to merge into flow context upon resume`)}).describe(`Payload for resuming a paused wait node`));var O$=X(()=>A([`fail`,`continue`,`fallback`]).describe(`Behavior when a wait node exceeds its timeout`));X(()=>T({defaultTimeoutMs:y().int().min(0).default(864e5).describe(`Default timeout in ms (default: 24 hours)`),defaultTimeoutBehavior:O$.default(`fail`).describe(`Default behavior when wait timeout is exceeded`),conditionPollIntervalMs:y().int().min(1e3).default(3e4).describe(`Polling interval for condition waits in ms (default: 30s)`),conditionMaxPolls:y().int().min(0).default(0).describe(`Max polling attempts for condition waits (0 = unlimited)`),webhookUrlPattern:v().default(`/api/v1/automation/resume/{executionId}/{nodeId}`).describe(`URL pattern for webhook resume endpoints`),persistCheckpoints:b().default(!0).describe(`Persist wait checkpoints to durable storage`),maxPausedExecutions:y().int().min(0).default(0).describe(`Max concurrent paused executions (0 = unlimited)`)}).describe(`Wait node executor plugin configuration`)),X(()=>T({id:v().describe(`Unique executor plugin identifier`),name:v().describe(`Display name`),nodeTypes:w(v()).min(1).describe(`FlowNodeAction types this executor handles`),version:v().describe(`Plugin version (semver)`),description:v().optional().describe(`Executor description`),supportsPause:b().default(!1).describe(`Whether the executor supports async pause/resume`),supportsCancellation:b().default(!1).describe(`Whether the executor supports mid-execution cancellation`),supportsRetry:b().default(!0).describe(`Whether the executor supports retry on failure`),configSchemaRef:v().optional().describe(`JSON Schema $ref for executor-specific config`)}).describe(`Node executor plugin descriptor`));var k$=X(()=>A([`logic`,`data`,`io`,`human`,`control`,`custom`]).describe(`Action palette category`)),A$=X(()=>A([`flow`,`approval`]).describe(`Authoring paradigm that may offer this action`));X(()=>T({type:v().min(1).describe(`Registry action/node type (matches the executor type)`),version:v().describe(`Executor version (semver)`),name:v().describe(`Display label (or i18n key)`),description:v().optional().describe(`Action description`),icon:v().optional().describe(`Icon id resolved by the designer`),category:k$.default(`custom`).describe(`Palette category`),paradigms:w(A$).default([`flow`]).describe(`Authoring surfaces that may offer this action`),configSchema:S().optional().describe(`JSON Schema for the node config (drives form + parse validation)`),supportsPause:b().default(!1).describe(`Supports async pause/resume`),supportsCancellation:b().default(!1).describe(`Supports cancellation`),supportsRetry:b().default(!0).describe(`Supports retry on failure`),needsOutbox:b().default(!1).describe(`Dispatch via service-messaging outbox (retry/idempotency/dead-letter)`),isAsync:b().default(!1).describe(`Suspends the flow awaiting an external reply`),maturity:A([`ga`,`beta`,`reserved`]).default(`ga`).describe(`Runtime maturity: ga (shipped), beta, or reserved (contract only — designers grey this out)`),source:A([`builtin`,`plugin`]).default(`plugin`).describe(`builtin = platform baseline; plugin = third-party contributed`),deprecated:b().default(!1).describe(`Deprecated alias kept for back-compat`),aliasOf:v().optional().describe(`Canonical type this alias forwards to`)}).describe(`Canonical cross-paradigm action/node descriptor (ADR-0018)`));var j$=X(()=>T({bpmnType:v().describe(`BPMN XML element type (e.g., "bpmn:parallelGateway")`),flowNodeAction:v().describe(`ObjectStack FlowNodeAction value`),bidirectional:b().default(!0).describe(`Whether the mapping supports both import and export`),notes:v().optional().describe(`Notes about mapping limitations`)}).describe(`Mapping between BPMN XML element and ObjectStack FlowNodeAction`)),M$=X(()=>A([`skip`,`warn`,`error`,`comment`]).describe(`Strategy for unmapped BPMN elements during import`));X(()=>T({unmappedStrategy:M$.default(`warn`).describe(`How to handle unmapped BPMN elements`),customMappings:w(j$).optional().describe(`Custom element mappings to override or extend defaults`),importLayout:b().default(!0).describe(`Import BPMN DI layout positions into canvas node coordinates`),importDocumentation:b().default(!0).describe(`Import BPMN documentation elements as node descriptions`),flowName:v().optional().describe(`Override flow name (defaults to BPMN process name)`),validateAfterImport:b().default(!0).describe(`Validate imported flow against FlowSchema after import`)}).describe(`Options for importing BPMN 2.0 XML into an ObjectStack flow`));var N$=X(()=>A([`2.0`,`2.0.2`]).describe(`BPMN specification version for export`));X(()=>T({version:N$.default(`2.0`).describe(`Target BPMN specification version`),includeLayout:b().default(!0).describe(`Include BPMN DI layout data from canvas positions`),includeExtensions:b().default(!1).describe(`Include ObjectStack extensions in BPMN extensionElements`),customMappings:w(j$).optional().describe(`Custom element mappings for export`),prettyPrint:b().default(!0).describe(`Pretty-print XML output with indentation`),namespacePrefix:v().default(`bpmn`).describe(`XML namespace prefix for BPMN elements`)}).describe(`Options for exporting an ObjectStack flow as BPMN 2.0 XML`));var P$=X(()=>T({severity:A([`info`,`warning`,`error`]).describe(`Diagnostic severity`),message:v().describe(`Diagnostic message`),bpmnElementId:v().optional().describe(`BPMN element ID related to this diagnostic`),nodeId:v().optional().describe(`ObjectStack node ID related to this diagnostic`)}).describe(`Diagnostic message from BPMN import/export`));X(()=>T({success:b().describe(`Whether the operation completed successfully`),diagnostics:w(P$).default([]).describe(`Diagnostic messages from the operation`),mappedCount:y().int().min(0).default(0).describe(`Number of elements successfully mapped`),unmappedCount:y().int().min(0).default(0).describe(`Number of elements that could not be mapped`)}).describe(`Result of a BPMN import/export operation`)),Object.freeze({object:wJ,field:TJ,hook:EJ,report:BY,dataset:WY,view:VY,app:HY,dashboard:UY,role:nZ,action:GY,page:KY,agent:KZ,tool:JZ,skill:XZ,flow:ZQ,permission:wZ,profile:wZ,email_template:iq});var F$=X(()=>T({enabled:b().describe(`Enable GDPR compliance controls`),dataSubjectRights:T({rightToAccess:b().default(!0).describe(`Allow data subjects to access their data`),rightToRectification:b().default(!0).describe(`Allow data subjects to correct their data`),rightToErasure:b().default(!0).describe(`Allow data subjects to request deletion`),rightToRestriction:b().default(!0).describe(`Allow data subjects to restrict processing`),rightToPortability:b().default(!0).describe(`Allow data subjects to export their data`),rightToObjection:b().default(!0).describe(`Allow data subjects to object to processing`)}).describe(`Data subject rights configuration per GDPR Articles 15-21`),legalBasis:A([`consent`,`contract`,`legal-obligation`,`vital-interests`,`public-task`,`legitimate-interests`]).describe(`Legal basis for data processing under GDPR Article 6`),consentTracking:b().default(!0).describe(`Track and record user consent`),dataRetentionDays:y().optional().describe(`Maximum data retention period in days`),dataProcessingAgreement:v().optional().describe(`URL or reference to the data processing agreement`)}).describe(`GDPR (General Data Protection Regulation) compliance configuration`)),I$=X(()=>T({enabled:b().describe(`Enable HIPAA compliance controls`),phi:T({encryption:b().default(!0).describe(`Encrypt Protected Health Information at rest`),accessControl:b().default(!0).describe(`Enforce role-based access to PHI`),auditTrail:b().default(!0).describe(`Log all PHI access events`),backupAndRecovery:b().default(!0).describe(`Enable PHI backup and disaster recovery`)}).describe(`Protected Health Information safeguards`),businessAssociateAgreement:b().default(!1).describe(`BAA is in place with third-party processors`)}).describe(`HIPAA (Health Insurance Portability and Accountability Act) compliance configuration`)),L$=X(()=>T({enabled:b().describe(`Enable PCI-DSS compliance controls`),level:A([`1`,`2`,`3`,`4`]).describe(`PCI-DSS compliance level (1 = highest)`),cardDataFields:w(v()).describe(`Field names containing cardholder data`),tokenization:b().default(!0).describe(`Replace card data with secure tokens`),encryptionInTransit:b().default(!0).describe(`Encrypt cardholder data during transmission`),encryptionAtRest:b().default(!0).describe(`Encrypt stored cardholder data`)}).describe(`PCI-DSS (Payment Card Industry Data Security Standard) compliance configuration`)),R$=X(()=>T({enabled:b().default(!0).describe(`Enable audit logging`),retentionDays:y().default(365).describe(`Number of days to retain audit logs`),immutable:b().default(!0).describe(`Prevent modification or deletion of audit logs`),signLogs:b().default(!1).describe(`Cryptographically sign log entries for tamper detection`),events:w(A([`create`,`read`,`update`,`delete`,`export`,`permission-change`,`login`,`logout`,`failed-login`])).describe(`Event types to capture in the audit log`)}).describe(`Audit log configuration for compliance and security monitoring`)),z$=X(()=>A([`critical`,`major`,`minor`,`observation`])),B$=X(()=>A([`open`,`in_remediation`,`remediated`,`verified`,`accepted_risk`,`closed`])),V$=X(()=>T({id:v().describe(`Unique finding identifier`),title:v().describe(`Finding title`),description:v().describe(`Finding description`),severity:z$.describe(`Finding severity`),status:B$.describe(`Finding status`),controlReference:v().optional().describe(`ISO 27001 control reference`),framework:FW.optional().describe(`Related compliance framework`),identifiedAt:y().describe(`Identification timestamp`),identifiedBy:v().describe(`Identifier (auditor name or system)`),remediationPlan:v().optional().describe(`Remediation plan`),remediationDeadline:y().optional().describe(`Remediation deadline timestamp`),verifiedAt:y().optional().describe(`Verification timestamp`),verifiedBy:v().optional().describe(`Verifier name or role`),notes:v().optional().describe(`Additional notes`)}).describe(`Audit finding with remediation tracking per ISO 27001:2022 A.5.35`)),H$=X(()=>T({id:v().describe(`Unique audit schedule identifier`),title:v().describe(`Audit title`),scope:w(v()).describe(`Audit scope areas`),framework:FW.describe(`Target compliance framework`),scheduledAt:y().describe(`Scheduled audit timestamp`),completedAt:y().optional().describe(`Completion timestamp`),assessor:v().describe(`Assessor or audit team`),isExternal:b().default(!1).describe(`Whether this is an external audit`),recurrenceMonths:y().default(0).describe(`Recurrence interval in months (0 = one-time)`),findings:w(V$).optional().describe(`Audit findings`)}).describe(`Audit schedule for independent security reviews per ISO 27001:2022 A.5.35`));X(()=>T({gdpr:F$.optional().describe(`GDPR compliance settings`),hipaa:I$.optional().describe(`HIPAA compliance settings`),pciDss:L$.optional().describe(`PCI-DSS compliance settings`),auditLog:R$.describe(`Audit log configuration`),auditSchedules:w(H$).optional().describe(`Scheduled compliance audits (A.5.35)`)}).describe(`Unified compliance configuration spanning GDPR, HIPAA, PCI-DSS, and audit governance`));var U$=X(()=>A([`aes-256-gcm`,`aes-256-cbc`,`chacha20-poly1305`]).describe(`Supported encryption algorithm`)),W$=X(()=>A([`local`,`aws-kms`,`azure-key-vault`,`gcp-kms`,`hashicorp-vault`]).describe(`Key management service provider`)),G$=X(()=>T({enabled:b().default(!1).describe(`Enable automatic key rotation`),frequencyDays:y().min(1).default(90).describe(`Rotation frequency in days`),retainOldVersions:y().default(3).describe(`Number of old key versions to retain`),autoRotate:b().default(!0).describe(`Automatically rotate without manual approval`)}).describe(`Policy for automatic encryption key rotation`)),K$=X(()=>T({enabled:b().default(!1).describe(`Enable field-level encryption`),algorithm:U$.default(`aes-256-gcm`).describe(`Encryption algorithm`),keyManagement:T({provider:W$.describe(`Key management service provider`),keyId:v().optional().describe(`Key identifier in the provider`),rotationPolicy:G$.optional().describe(`Key rotation policy`)}).describe(`Key management configuration`),scope:A([`field`,`record`,`table`,`database`]).describe(`Encryption scope level`),deterministicEncryption:b().default(!1).describe(`Allows equality queries on encrypted data`),searchableEncryption:b().default(!1).describe(`Allows search on encrypted data`)}).describe(`Field-level encryption configuration`));X(()=>T({fieldName:v().describe(`Name of the field to encrypt`),encryptionConfig:K$.describe(`Encryption settings for this field`),indexable:b().default(!1).describe(`Allow indexing on encrypted field`)}).describe(`Per-field encryption assignment`));var q$=X(()=>A([`redact`,`partial`,`hash`,`tokenize`,`randomize`,`nullify`,`substitute`]).describe(`Data masking strategy for PII protection`)),J$=X(()=>T({field:v().describe(`Field name to apply masking to`),strategy:q$.describe(`Masking strategy to use`),pattern:v().optional().describe(`Regex pattern for partial masking`),preserveFormat:b().default(!0).describe(`Keep the original data format after masking`),preserveLength:b().default(!0).describe(`Keep the original data length after masking`),roles:w(v()).optional().describe(`Roles that see masked data`),exemptRoles:w(v()).optional().describe(`Roles that see unmasked data`)}).describe(`Masking rule for a single field`));X(()=>T({enabled:b().default(!1).describe(`Enable data masking`),rules:w(J$).describe(`List of field-level masking rules`),auditUnmasking:b().default(!0).describe(`Log when masked data is accessed unmasked`)}).describe(`Top-level data masking configuration for PII protection`));var Y$=X(()=>A([`critical`,`high`,`medium`,`low`])),X$=X(()=>A([`data_breach`,`malware`,`unauthorized_access`,`denial_of_service`,`social_engineering`,`insider_threat`,`physical_security`,`configuration_error`,`vulnerability_exploit`,`policy_violation`,`other`])),Z$=X(()=>A([`reported`,`triaged`,`investigating`,`containing`,`eradicating`,`recovering`,`resolved`,`closed`])),Q$=X(()=>T({phase:A([`identification`,`containment`,`eradication`,`recovery`,`lessons_learned`]).describe(`Response phase name`),description:v().describe(`Phase description and objectives`),assignedTo:v().describe(`Responsible team or role`),targetHours:y().min(0).describe(`Target completion time in hours`),completedAt:y().optional().describe(`Actual completion timestamp`),notes:v().optional().describe(`Phase notes and findings`)}).describe(`Incident response phase with timing and assignment`)),$$=X(()=>T({severity:Y$.describe(`Minimum severity to trigger notification`),channels:w(A([`email`,`sms`,`slack`,`pagerduty`,`webhook`])).describe(`Notification channels`),recipients:w(v()).describe(`Roles or teams to notify`),withinMinutes:y().min(1).describe(`Notification deadline in minutes from detection`),notifyRegulators:b().default(!1).describe(`Whether to notify regulatory authorities`),regulatorDeadlineHours:y().optional().describe(`Regulatory notification deadline in hours`)}).describe(`Incident notification rule per severity level`)),e1=X(()=>T({rules:w($$).describe(`Notification rules by severity level`),escalationTimeoutMinutes:y().default(30).describe(`Auto-escalation timeout in minutes`),escalationChain:w(v()).default([]).describe(`Ordered escalation chain of roles`)}).describe(`Incident notification matrix with escalation policies`));X(()=>T({id:v().describe(`Unique incident identifier`),title:v().describe(`Incident title`),description:v().describe(`Detailed incident description`),severity:Y$.describe(`Incident severity level`),category:X$.describe(`Incident category`),status:Z$.describe(`Current incident status`),reportedBy:v().describe(`Reporter user ID or system name`),reportedAt:y().describe(`Report timestamp`),detectedAt:y().optional().describe(`Detection timestamp`),resolvedAt:y().optional().describe(`Resolution timestamp`),affectedSystems:w(v()).describe(`Affected systems`),affectedDataClassifications:w(PW).optional().describe(`Affected data classifications`),responsePhases:w(Q$).optional().describe(`Incident response phases`),rootCause:v().optional().describe(`Root cause analysis`),correctiveActions:w(v()).optional().describe(`Corrective actions taken or planned`),lessonsLearned:v().optional().describe(`Lessons learned from the incident`),relatedChangeRequestIds:w(v()).optional().describe(`Related change request IDs`),metadata:k(v(),S()).optional().describe(`Custom metadata key-value pairs`)}).describe(`Security incident record per ISO 27001:2022 A.5.24–A.5.28`)),X(()=>T({enabled:b().default(!0).describe(`Enable incident response management`),notificationMatrix:e1.describe(`Notification and escalation matrix`),defaultResponseTeam:v().describe(`Default incident response team or role`),triageDeadlineHours:y().default(1).describe(`Maximum hours to begin triage after detection`),requirePostIncidentReview:b().default(!0).describe(`Require post-incident review for all incidents`),regulatoryNotificationThreshold:Y$.default(`high`).describe(`Minimum severity requiring regulatory notification`),retentionDays:y().default(2555).describe(`Incident record retention period in days (default ~7 years)`)}).describe(`Organization-level incident response policy per ISO 27001:2022`));var t1=X(()=>A([`critical`,`high`,`medium`,`low`])),n1=X(()=>A([`pending`,`in_progress`,`completed`,`expired`,`failed`])),r1=X(()=>T({id:v().describe(`Requirement identifier`),description:v().describe(`Requirement description`),controlReference:v().optional().describe(`ISO 27001 control reference`),mandatory:b().default(!0).describe(`Whether this requirement is mandatory`),compliant:b().optional().describe(`Whether the supplier meets this requirement`),evidence:v().optional().describe(`Compliance evidence or assessment notes`)}).describe(`Individual supplier security requirement`));X(()=>T({supplierId:v().describe(`Unique supplier identifier`),supplierName:v().describe(`Supplier display name`),riskLevel:t1.describe(`Supplier risk classification`),status:n1.describe(`Assessment status`),assessedBy:v().describe(`Assessor user ID or team`),assessedAt:y().describe(`Assessment timestamp`),validUntil:y().describe(`Assessment validity expiry timestamp`),requirements:w(r1).describe(`Security requirements and their compliance status`),overallCompliant:b().describe(`Whether supplier meets all mandatory requirements`),dataClassificationsShared:w(PW).optional().describe(`Data classifications shared with supplier`),servicesProvided:w(v()).optional().describe(`Services provided by this supplier`),certifications:w(v()).optional().describe(`Supplier certifications (e.g., ISO 27001, SOC 2)`),remediationItems:w(T({requirementId:v().describe(`Non-compliant requirement ID`),action:v().describe(`Required remediation action`),deadline:y().describe(`Remediation deadline timestamp`),status:A([`pending`,`in_progress`,`completed`]).default(`pending`).describe(`Remediation status`)})).optional().describe(`Remediation items for non-compliant requirements`),metadata:k(v(),S()).optional().describe(`Custom metadata key-value pairs`)}).describe(`Supplier security assessment record per ISO 27001:2022 A.5.19–A.5.21`)),X(()=>T({enabled:b().default(!0).describe(`Enable supplier security management`),reassessmentIntervalDays:y().default(365).describe(`Supplier reassessment interval in days`),requirePreOnboardingAssessment:b().default(!0).describe(`Require security assessment before supplier onboarding`),formalAssessmentThreshold:t1.default(`medium`).describe(`Minimum risk level requiring formal assessment`),monitorChanges:b().default(!0).describe(`Monitor supplier security posture changes`),requiredCertifications:w(v()).default([]).describe(`Required certifications for critical-risk suppliers`)}).describe(`Organization-level supplier security management policy per ISO 27001:2022`));var i1=X(()=>A([`security_awareness`,`data_protection`,`incident_response`,`access_control`,`phishing_awareness`,`compliance`,`secure_development`,`physical_security`,`business_continuity`,`other`])),a1=X(()=>A([`not_started`,`in_progress`,`completed`,`failed`,`expired`])),o1=X(()=>T({id:v().describe(`Unique course identifier`),title:v().describe(`Course title`),description:v().describe(`Course description and learning objectives`),category:i1.describe(`Training category`),durationMinutes:y().min(1).describe(`Estimated course duration in minutes`),mandatory:b().default(!1).describe(`Whether training is mandatory`),targetRoles:w(v()).describe(`Target roles or groups`),validityDays:y().optional().describe(`Certification validity period in days`),passingScore:y().min(0).max(100).optional().describe(`Minimum passing score percentage`),version:v().optional().describe(`Course content version`)}).describe(`Security training course definition`));X(()=>T({courseId:v().describe(`Training course identifier`),userId:v().describe(`User identifier`),status:a1.describe(`Training completion status`),assignedAt:y().describe(`Assignment timestamp`),completedAt:y().optional().describe(`Completion timestamp`),score:y().min(0).max(100).optional().describe(`Assessment score percentage`),expiresAt:y().optional().describe(`Certification expiry timestamp`),notes:v().optional().describe(`Training notes or comments`)}).describe(`Individual training completion record`)),X(()=>T({enabled:b().default(!0).describe(`Enable training management`),courses:w(o1).describe(`Training courses`),recertificationIntervalDays:y().default(365).describe(`Default recertification interval in days`),trackCompletion:b().default(!0).describe(`Track training completion for compliance`),gracePeriodDays:y().default(30).describe(`Grace period in days after certification expiry`),sendReminders:b().default(!0).describe(`Send reminders for upcoming training deadlines`),reminderDaysBefore:y().default(14).describe(`Days before deadline to send first reminder`)}).describe(`Organizational training plan per ISO 27001:2022 A.6.3`));var s1=A([`group`,`child_pane`,`info_banner`,`title_value`,`text`,`textarea`,`password`,`email`,`url`,`phone`,`number`,`toggle`,`select`,`radio`,`multiselect`,`slider`,`color`,`json`,`action_button`]),c1=new Set([`text`,`textarea`,`password`,`email`,`url`,`phone`,`number`,`toggle`,`select`,`radio`,`multiselect`,`slider`,`color`,`json`]),l1=X(()=>T({value:E([v(),y(),b()]).describe(`Stored value`),label:Q.describe(`Display label`),description:v().optional().describe(`Optional helper text`),icon:v().optional().describe(`Optional Lucide icon name`)})),u1=X(()=>D(`kind`,[T({kind:j(`http`),method:A([`GET`,`POST`,`PUT`,`DELETE`,`PATCH`]).default(`POST`),url:v().describe("Endpoint URL; supports ${...} interpolation"),body:k(v(),S()).optional().describe("Optional JSON body; supports ${...} interpolation"),confirmText:Q.optional().describe(`Confirm dialog text before invoking (omit = no confirm)`)}),T({kind:j(`action`),name:v().describe(`Registered action machine name`),params:k(v(),S()).optional(),confirmText:Q.optional()}),T({kind:j(`navigate`),url:v().describe(`Target URL or in-app route`),target:A([`_self`,`_blank`]).default(`_self`)})])),d1=A([`global`,`tenant`,`user`]),f1=X(()=>T({type:s1.describe(`Specifier variant`),id:Z.optional().describe(`Stable identifier (snake_case)`),key:Z.optional().describe(`Storage key (snake_case)`),label:Q.describe(`Display label`),description:v().optional().describe(`Help text`),icon:v().optional().describe(`Icon name (Lucide)`),default:S().optional().describe(`Default value`),visible:JH.optional().describe(`Visibility expression`),required:b().default(!1).describe(`Required field`),encrypted:b().optional().describe(`Encrypt value at rest (forced true for password)`),scope:d1.optional().describe(`Override manifest scope for this key`),availableScopes:w(d1).optional().describe(`Scopes allowed to override this specifier`),lockable:b().optional().describe(`Allow upper-scope locking of this specifier`),readPermission:v().optional().describe(`Permission required to read this specifier`),writePermission:v().optional().describe(`Permission required to write this specifier`),deprecated:b().optional().describe(`Mark deprecated`),replacedBy:v().optional().describe(`Replacement key (used when deprecated=true)`),options:w(l1).optional().describe(`Options for select/radio/multiselect`),min:y().optional(),max:y().optional(),step:y().optional(),minLength:y().int().min(0).optional(),maxLength:y().int().min(1).optional(),pattern:v().optional().describe(`Regex pattern (text only)`),rows:y().int().min(1).optional(),handler:u1.optional().describe(`Action handler (action_button)`),childNamespace:Z.optional().describe(`Sub-namespace (child_pane)`),bannerText:v().optional().describe(`Markdown body (info_banner)`),bannerSeverity:A([`info`,`success`,`warning`,`error`]).optional()}).superRefine((e,t)=>{c1.has(e.type)&&!e.key&&t.addIssue({code:ru.custom,path:[`key`],message:`Specifier of type '${e.type}' requires a 'key'.`}),!c1.has(e.type)&&e.key&&t.addIssue({code:ru.custom,path:[`key`],message:`Specifier of type '${e.type}' must not declare a 'key'.`}),[`select`,`radio`,`multiselect`].includes(e.type)&&(!e.options||e.options.length===0)&&t.addIssue({code:ru.custom,path:[`options`],message:`Specifier of type '${e.type}' requires non-empty 'options'.`}),e.type===`action_button`&&!e.handler&&t.addIssue({code:ru.custom,path:[`handler`],message:`Specifier of type 'action_button' requires a 'handler'.`}),e.type===`child_pane`&&!e.childNamespace&&t.addIssue({code:ru.custom,path:[`childNamespace`],message:`Specifier of type 'child_pane' requires a 'childNamespace'.`}),e.type===`info_banner`&&!e.bannerText&&t.addIssue({code:ru.custom,path:[`bannerText`],message:`Specifier of type 'info_banner' requires 'bannerText'.`}),typeof e.min==`number`&&typeof e.max==`number`&&e.min>e.max&&t.addIssue({code:ru.custom,path:[`min`],message:`'min' must be ≤ 'max'.`}),typeof e.minLength==`number`&&typeof e.maxLength==`number`&&e.minLength>e.maxLength&&t.addIssue({code:ru.custom,path:[`minLength`],message:`'minLength' must be ≤ 'maxLength'.`}),e.deprecated&&!e.replacedBy&&t.addIssue({code:ru.custom,path:[`replacedBy`],message:`Deprecated specifiers should declare 'replacedBy'.`})})),p1=X(()=>T({namespace:Z.describe(`Namespace (snake_case, globally unique)`),version:y().int().min(1).default(1).describe(`Manifest schema version`),label:Q.describe(`Display label`),icon:v().optional().describe(`Icon (Lucide)`),description:v().optional().describe(`Short description`),helpText:v().optional().describe(`Markdown help text shown above specifiers`),scope:d1.default(`tenant`).describe(`Default scope for specifiers`),readPermission:v().default(`setup.access`).describe(`Permission required to read`),writePermission:v().default(`setup.write`).describe(`Permission required to write`),category:v().optional().describe(`Settings hub category`),order:y().optional().describe(`Display order`),specifiers:w(f1).min(1).describe(`Page contents (ordered)`),visible:JH.optional().describe(`Whole-manifest visibility`),featureFlag:v().optional().describe(`Gate manifest visibility on a feature flag`),beta:b().optional().describe(`Show a Beta chip on the page`)}).superRefine((e,t)=>{let n=new Set;e.specifiers.forEach((r,i)=>{r.key&&(n.has(r.key)?t.addIssue({code:ru.custom,path:[`specifiers`,i,`key`],message:`Duplicate specifier key '${r.key}' in manifest '${e.namespace}'.`}):n.add(r.key))});let r=new Set;e.specifiers.forEach((n,i)=>{n.id&&(r.has(n.id)?t.addIssue({code:ru.custom,path:[`specifiers`,i,`id`],message:`Duplicate specifier id '${n.id}' in manifest '${e.namespace}'.`}):r.add(n.id))}),e.specifiers.forEach((n,r)=>{n.type===`child_pane`&&n.childNamespace===e.namespace&&t.addIssue({code:ru.custom,path:[`specifiers`,r,`childNamespace`],message:`child_pane cannot reference its own namespace ('${e.namespace}').`})})})),m1=X(()=>T({value:S().describe(`Effective value (post-resolution)`),source:A([`env`,`global`,`tenant`,`user`,`default`]).describe(`Resolution source`),locked:b().describe(`Cannot be overridden from UI`),lockedReason:v().optional().describe(`Reason for the lock (UI tooltip)`),cascadeChain:w(T({scope:A([`env`,`global`,`tenant`,`user`,`default`]),value:S(),locked:b().optional(),lockedReason:v().optional(),effective:b().optional()})).optional().describe(`Full cascade trace (env → global → tenant → user → default)`)}));X(()=>T({manifest:p1,values:k(v(),m1).describe(`Effective values keyed by specifier.key`)})),X(()=>T({ok:b().describe(`Success flag`),message:v().optional().describe(`Toast message`),severity:A([`info`,`success`,`warning`,`error`]).optional(),details:S().optional().describe(`Optional structured detail (renderer-defined)`)})),X(()=>T({namespace:v().min(1).describe(`Settings namespace, e.g. "mail"`),key:v().min(1).describe(`Specifier key, e.g. "smtp_host"`),scope:d1.describe(`Scope of the mutated row`),action:A([`set`,`reset`]).describe(`Mutation kind`),at:v().describe(`ISO 8601 mutation timestamp`)}));var h1=X(()=>T({type:j(`cron`),expression:YH.describe('Cron expression — cron`0 0 * * *` for daily at midnight. Build emits {dialect:"cron",source} envelope.'),timezone:v().optional().default(`UTC`).describe(`Timezone for cron execution (e.g., "America/New_York")`)})),g1=X(()=>T({type:j(`interval`),intervalMs:y().int().positive().describe(`Interval in milliseconds`)})),_1=X(()=>T({type:j(`once`),at:v().datetime().describe(`ISO 8601 datetime when to execute`)})),v1=X(()=>D(`type`,[h1,g1,_1])),y1=X(()=>T({maxRetries:y().int().min(0).default(3).describe(`Maximum number of retry attempts`),backoffMs:y().int().positive().default(1e3).describe(`Initial backoff delay in milliseconds`),backoffMultiplier:y().positive().default(2).describe(`Multiplier for exponential backoff`)})),b1=X(()=>T({id:v().optional().describe("Unique job identifier (defaults to `name` when omitted)"),name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Job name (snake_case)`),label:v().optional().describe(`Human-readable label`),description:v().optional().describe(`Job description / purpose`),schedule:v1.describe(`Job schedule configuration`),handler:v().describe("Handler function name (must match a key in `defineStack({ functions })`)"),retryPolicy:y1.optional().describe(`Retry policy configuration`),timeout:y().int().positive().optional().describe(`Timeout in milliseconds`),enabled:b().default(!0).describe(`Whether the job is enabled`)})),x1=A([`running`,`success`,`failed`,`timeout`]);X(()=>T({jobId:v().describe(`Job identifier`),startedAt:v().datetime().describe(`ISO 8601 datetime when execution started`),completedAt:v().datetime().optional().describe(`ISO 8601 datetime when execution completed`),status:x1.describe(`Execution status`),error:v().optional().describe(`Error message if failed`),duration:y().int().optional().describe(`Execution duration in milliseconds`)}));var S1=A([`critical`,`high`,`normal`,`low`,`background`]),C1=A([`pending`,`queued`,`processing`,`completed`,`failed`,`cancelled`,`timeout`,`dead`]),w1=X(()=>T({maxRetries:y().int().min(0).default(3).describe(`Maximum retry attempts`),backoffStrategy:A([`fixed`,`linear`,`exponential`]).default(`exponential`).describe(`Backoff strategy between retries`),initialDelayMs:y().int().positive().default(1e3).describe(`Initial retry delay in milliseconds`),maxDelayMs:y().int().positive().default(6e4).describe(`Maximum retry delay in milliseconds`),backoffMultiplier:y().positive().default(2).describe(`Multiplier for exponential backoff`)})),T1=X(()=>T({id:v().describe(`Unique task identifier`),type:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Task type (snake_case)`),payload:S().describe(`Task payload data`),queue:v().default(`default`).describe(`Queue name`),priority:S1.default(`normal`).describe(`Task priority level`),retryPolicy:w1.optional().describe(`Retry policy configuration`),timeoutMs:y().int().positive().optional().describe(`Task timeout in milliseconds`),scheduledAt:v().datetime().optional().describe(`ISO 8601 datetime to execute task`),attempts:y().int().min(0).default(0).describe(`Number of execution attempts`),status:C1.default(`pending`).describe(`Current task status`),metadata:T({createdAt:v().datetime().optional().describe(`When task was created`),updatedAt:v().datetime().optional().describe(`Last update time`),createdBy:v().optional().describe(`User who created task`),tags:w(v()).optional().describe(`Task tags for filtering`)}).optional().describe(`Task metadata`)}));X(()=>T({taskId:v().describe(`Task identifier`),status:C1.describe(`Execution status`),result:S().optional().describe(`Execution result data`),error:T({message:v().describe(`Error message`),stack:v().optional().describe(`Error stack trace`),code:v().optional().describe(`Error code`)}).optional().describe(`Error details if failed`),durationMs:y().int().optional().describe(`Execution duration in milliseconds`),startedAt:v().datetime().describe(`When execution started`),completedAt:v().datetime().optional().describe(`When execution completed`),attempt:y().int().min(1).describe(`Attempt number (1-indexed)`),willRetry:b().describe(`Whether task will be retried`)}));var E1=X(()=>T({name:v().describe(`Queue name (snake_case)`),concurrency:y().int().min(1).default(5).describe(`Max concurrent task executions`),rateLimit:T({max:y().int().positive().describe(`Maximum tasks per duration`),duration:y().int().positive().describe(`Duration in milliseconds`)}).optional().describe(`Rate limit configuration`),defaultRetryPolicy:w1.optional().describe(`Default retry policy for tasks`),deadLetterQueue:v().optional().describe(`Dead letter queue name`),priority:y().int().min(0).default(0).describe(`Queue priority (lower = higher priority)`),autoScale:T({enabled:b().default(!1).describe(`Enable auto-scaling`),minWorkers:y().int().min(1).default(1).describe(`Minimum workers`),maxWorkers:y().int().min(1).default(10).describe(`Maximum workers`),scaleUpThreshold:y().int().positive().default(100).describe(`Queue size to scale up`),scaleDownThreshold:y().int().min(0).default(10).describe(`Queue size to scale down`)}).optional().describe(`Auto-scaling configuration`)})),D1=X(()=>T({id:v().describe(`Unique batch job identifier`),type:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Task type (snake_case)`),items:w(S()).describe(`Array of items to process`),batchSize:y().int().min(1).default(100).describe(`Number of items per batch`),queue:v().default(`batch`).describe(`Queue for batch tasks`),priority:S1.default(`normal`).describe(`Batch task priority`),parallel:b().default(!0).describe(`Process batches in parallel`),stopOnError:b().default(!1).describe(`Stop batch if any item fails`),onProgress:P().input(O([T({processed:y(),total:y(),failed:y()})])).output(gl()).optional().describe(`Progress callback function (called after each batch)`)}));X(()=>T({batchId:v().describe(`Batch job identifier`),total:y().int().min(0).describe(`Total number of items`),processed:y().int().min(0).default(0).describe(`Items processed`),succeeded:y().int().min(0).default(0).describe(`Items succeeded`),failed:y().int().min(0).default(0).describe(`Items failed`),percentage:y().min(0).max(100).describe(`Progress percentage`),status:A([`pending`,`running`,`completed`,`failed`,`cancelled`]).describe(`Batch status`),startedAt:v().datetime().optional().describe(`When batch started`),completedAt:v().datetime().optional().describe(`When batch completed`)}));var O1=X(()=>T({name:v().describe(`Worker name`),queues:w(v()).min(1).describe(`Queue names to process`),queueConfigs:w(E1).optional().describe(`Queue configurations`),pollIntervalMs:y().int().positive().default(1e3).describe(`Queue polling interval in milliseconds`),visibilityTimeoutMs:y().int().positive().default(3e4).describe(`How long a task is invisible after being claimed`),defaultTimeoutMs:y().int().positive().default(3e5).describe(`Default task timeout in milliseconds`),shutdownTimeoutMs:y().int().positive().default(3e4).describe(`Graceful shutdown timeout in milliseconds`),handlers:k(v(),P()).optional().describe(`Task type handlers`)}));X(()=>T({workerName:v().describe(`Worker name`),totalProcessed:y().int().min(0).describe(`Total tasks processed`),succeeded:y().int().min(0).describe(`Successful tasks`),failed:y().int().min(0).describe(`Failed tasks`),active:y().int().min(0).describe(`Currently active tasks`),avgExecutionMs:y().min(0).optional().describe(`Average execution time in milliseconds`),uptimeMs:y().int().min(0).describe(`Worker uptime in milliseconds`),queues:k(v(),T({pending:y().int().min(0).describe(`Pending tasks`),active:y().int().min(0).describe(`Active tasks`),completed:y().int().min(0).describe(`Completed tasks`),failed:y().int().min(0).describe(`Failed tasks`)})).optional().describe(`Per-queue statistics`)})),Object.assign(T1,{create:e=>e}),Object.assign(E1,{create:e=>e}),Object.assign(O1,{create:e=>e}),Object.assign(D1,{create:e=>e});var k1=X(()=>T({id:v().describe(`Template identifier`),subject:XH.describe(`Email subject — supports {{var}} interpolation`),body:XH.describe(`Email body content — supports {{var}} interpolation`),bodyType:A([`text`,`html`,`markdown`]).optional().default(`html`).describe(`Body content type`),variables:w(v()).optional().describe(`Template variables`),attachments:w(T({name:v().describe(`Attachment filename`),url:v().url().describe(`Attachment URL`)})).optional().describe(`Email attachments`)})),A1=X(()=>T({id:v().describe(`Template identifier`),message:XH.describe(`SMS message content — supports {{var}} interpolation`),maxLength:y().optional().default(160).describe(`Maximum message length`),variables:w(v()).optional().describe(`Template variables`)})),j1=X(()=>T({title:v().describe(`Notification title`),body:XH.describe(`Notification body — supports {{var}} interpolation`),icon:v().url().optional().describe(`Notification icon URL`),badge:y().optional().describe(`Badge count`),data:k(v(),S()).optional().describe(`Custom data`),actions:w(T({action:v().describe(`Action identifier`),title:v().describe(`Action button title`)})).optional().describe(`Notification actions`)})),M1=X(()=>T({title:v().describe(`Notification title`),message:XH.describe(`Notification message — supports {{var}} interpolation`),type:A([`info`,`success`,`warning`,`error`]).describe(`Notification type`),actionUrl:v().optional().describe(`Action URL`),dismissible:b().optional().default(!0).describe(`User dismissible`),expiresAt:y().optional().describe(`Expiration timestamp`)})),N1=X(()=>A([`email`,`sms`,`push`,`in-app`,`slack`,`teams`,`webhook`]));X(()=>T({id:v().describe(`Notification ID`),name:v().describe(`Notification name`),channel:N1.describe(`Notification channel`),template:E([k1,A1,j1,M1]).describe(`Notification template`),recipients:T({to:w(v()).describe(`Primary recipients`),cc:w(v()).optional().describe(`CC recipients`),bcc:w(v()).optional().describe(`BCC recipients`)}).describe(`Recipients`),schedule:T({type:A([`immediate`,`delayed`,`scheduled`]).describe(`Schedule type`),delay:y().optional().describe(`Delay in milliseconds`),scheduledAt:y().optional().describe(`Scheduled timestamp`)}).optional().describe(`Scheduling`),retryPolicy:T({enabled:b().optional().default(!0).describe(`Enable retries`),maxRetries:y().optional().default(3).describe(`Max retry attempts`),backoffStrategy:A([`exponential`,`linear`,`fixed`]).describe(`Backoff strategy`)}).optional().describe(`Retry policy`),tracking:T({trackOpens:b().optional().default(!1).describe(`Track opens`),trackClicks:b().optional().default(!1).describe(`Track clicks`),trackDelivery:b().optional().default(!0).describe(`Track delivery`)}).optional().describe(`Tracking configuration`)}));var P1=X(()=>v().describe(`BCP-47 Language Tag (e.g. en-US, zh-CN)`)),F1=X(()=>T({label:v().optional().describe(`Translated field label`),help:v().optional().describe(`Translated help text`),placeholder:v().optional().describe(`Translated placeholder text for form inputs`),options:k(v(),v()).optional().describe(`Option value to translated label map`)}).describe(`Translation data for a single field`)),I1=X(()=>T({label:v().describe(`Translated singular label`),pluralLabel:v().optional().describe(`Translated plural label`),description:v().optional().describe(`Translated object description`),fields:k(v(),F1).optional().describe(`Field-level translations`),_views:k(v(),T({label:v().optional().describe(`Translated view label`),description:v().optional().describe(`Translated view description`)})).optional().describe(`View translations keyed by view name`),_actions:k(v(),T({label:v().optional().describe(`Translated action label`),confirmText:v().optional().describe(`Translated confirmation prompt`),successMessage:v().optional().describe(`Translated success toast/message`),params:k(v(),T({label:v().optional().describe(`Translated action parameter label`),helpText:v().optional().describe(`Translated action parameter help/hint text`),placeholder:v().optional().describe(`Translated action parameter placeholder`),options:k(v(),v()).optional().describe(`Param select option value to translated label`)})).optional().describe(`Action parameter translations keyed by parameter name`)})).optional().describe(`Action translations keyed by action name`),_sections:k(v(),T({label:v().optional().describe(`Translated section label`),description:v().optional().describe(`Translated section description`)})).optional().describe(`Section translations keyed by section name`)}).describe(`Translation data for a single object`)),L1=X(()=>T({objects:k(v(),I1).optional().describe(`Object translations keyed by object name`),apps:k(v(),T({label:v().describe(`Translated app label`),description:v().optional().describe(`Translated app description`),navigation:k(v(),T({label:v().describe(`Translated navigation group label`)})).optional().describe(`Navigation group translations keyed by group ID`)})).optional().describe(`App translations keyed by app name`),messages:k(v(),v()).optional().describe(`UI message translations keyed by message ID`),validationMessages:k(v(),v()).optional().describe(`Translatable validation error messages keyed by rule name (e.g., {"discount_limit": "折扣不能超过40%"})`),globalActions:k(v(),T({label:v().optional().describe(`Translated action label`),confirmText:v().optional().describe(`Translated confirmation prompt`),successMessage:v().optional().describe(`Translated success toast/message`),params:k(v(),T({label:v().optional().describe(`Translated action parameter label`),helpText:v().optional().describe(`Translated action parameter help/hint text`),placeholder:v().optional().describe(`Translated action parameter placeholder`),options:k(v(),v()).optional().describe(`Param select option value to translated label`)})).optional().describe(`Action parameter translations keyed by parameter name`)})).optional().describe(`Global action translations keyed by action name`),dashboards:k(v(),T({label:v().optional().describe(`Translated dashboard title`),description:v().optional().describe(`Translated dashboard description`),actions:k(v(),T({label:v().optional().describe(`Translated header action label`)})).optional().describe(`Header action label translations keyed by action url/key`),widgets:k(v(),T({title:v().optional().describe(`Translated widget title`),description:v().optional().describe(`Translated widget description`)})).optional().describe(`Widget translations keyed by widget id`)})).optional().describe(`Dashboard translations keyed by dashboard name`),settings:k(v(),T({title:v().optional().describe(`Translated settings manifest title`),description:v().optional().describe(`Translated settings manifest description`),groups:k(v(),T({title:v().optional().describe(`Translated group title`),description:v().optional().describe(`Translated group description`)})).optional().describe(`Group translations keyed by group key`),keys:k(v(),T({label:v().optional().describe(`Translated setting label`),help:v().optional().describe(`Translated setting help text`),placeholder:v().optional().describe(`Translated input placeholder`),options:k(v(),v()).optional().describe(`Enum option value → translated label`)})).optional().describe(`Per-setting field translations keyed by setting key`),actions:k(v(),T({label:v().optional().describe(`Translated action label`),confirmText:v().optional().describe(`Translated confirmation prompt`),successMessage:v().optional().describe(`Translated success toast/message`)})).optional().describe(`Action button translations keyed by action id`)})).optional().describe(`Settings manifest translations keyed by namespace`),metadataForms:k(v(),T({label:v().optional().describe(`Translated metadata-type display label (overrides registry label)`),description:v().optional().describe(`Translated metadata-type description`),sections:k(v(),T({label:v().optional().describe(`Translated section label`),description:v().optional().describe(`Translated section description`)})).optional().describe(`Section translations keyed by section.name`),fields:k(v(),T({label:v().optional().describe(`Translated field label`),helpText:v().optional().describe(`Translated field help/hint text`),placeholder:v().optional().describe(`Translated field placeholder text`)})).optional().describe(`Field translations keyed by field path (dot-notation for nested fields)`)})).optional().describe(`Translations for metadata-type configuration forms keyed by metadata type`),settingsCommon:T({sourceLabels:T({env:v().optional(),global:v().optional(),tenant:v().optional(),user:v().optional(),default:v().optional()}).optional().describe(`Source badge labels by resolution layer`)}).optional().describe(`Cross-namespace Settings UI strings`)}).describe(`Translation data for objects, apps, and UI messages`));X(()=>k(P1,L1).describe(`Map of locale codes to translation data`));var R1=X(()=>A([`bundled`,`per_locale`,`per_namespace`]).describe(`Translation file organization strategy`)),z1=X(()=>A([`icu`,`simple`]).describe(`Message interpolation format: ICU MessageFormat or simple {variable} replacement`));X(()=>T({defaultLocale:P1.describe(`Default locale (e.g., "en")`),supportedLocales:w(P1).describe(`Supported BCP-47 locale codes`),fallbackLocale:P1.optional().describe(`Fallback locale code`),fileOrganization:R1.default(`per_locale`).describe(`File organization strategy`),messageFormat:z1.default(`simple`).describe(`Message interpolation format (ICU MessageFormat or simple)`),lazyLoad:b().default(!1).describe(`Load translations on demand`),cache:b().default(!0).describe(`Cache loaded translations`)}).describe(`Internationalization configuration`));var B1=k(v(),v()).describe(`Option value to translated label map`),V1=X(()=>T({label:v().describe(`Translated singular label`),pluralLabel:v().optional().describe(`Translated plural label`),description:v().optional().describe(`Translated object description`),helpText:v().optional().describe(`Translated help text for the object`),fields:k(v(),F1).optional().describe(`Field translations keyed by field name`),_options:k(v(),B1).optional().describe(`Object-scoped picklist option translations keyed by field name`),_views:k(v(),T({label:v().optional().describe(`Translated view label`),description:v().optional().describe(`Translated view description`)})).optional().describe(`View translations keyed by view name`),_sections:k(v(),T({label:v().optional().describe(`Translated section label`)})).optional().describe(`Section translations keyed by section name`),_actions:k(v(),T({label:v().optional().describe(`Translated action label`),confirmMessage:v().optional().describe(`Translated confirmation message`),params:k(v(),T({label:v().optional().describe(`Translated action parameter label`),helpText:v().optional().describe(`Translated action parameter help/hint text`),placeholder:v().optional().describe(`Translated action parameter placeholder`),options:k(v(),v()).optional().describe(`Param select option value to translated label`)})).optional().describe(`Action parameter translations keyed by parameter name`)})).optional().describe(`Action translations keyed by action name`),_notifications:k(v(),T({title:v().optional().describe(`Translated notification title`),body:v().optional().describe(`Translated notification body (supports ICU MessageFormat when enabled)`)})).optional().describe(`Notification translations keyed by notification name`),_errors:k(v(),v()).optional().describe(`Error message translations keyed by error code`)}).describe(`Object-first aggregated translation node`));X(()=>T({_meta:T({locale:v().optional().describe(`BCP-47 locale code for this bundle`),direction:A([`ltr`,`rtl`]).optional().describe(`Text direction: left-to-right or right-to-left`)}).optional().describe(`Bundle-level metadata (locale, bidi direction)`),namespace:v().optional().describe(`Namespace for plugin isolation to avoid translation key collisions`),o:k(v(),V1).optional().describe(`Object-first translations keyed by object name`),_globalOptions:k(v(),B1).optional().describe(`Global picklist option translations keyed by option set name`),app:k(v(),T({label:v().describe(`Translated app label`),description:v().optional().describe(`Translated app description`)})).optional().describe(`App translations keyed by app name`),nav:k(v(),v()).optional().describe(`Navigation item translations keyed by nav item name`),dashboard:k(v(),T({label:v().optional().describe(`Translated dashboard label`),description:v().optional().describe(`Translated dashboard description`)})).optional().describe(`Dashboard translations keyed by dashboard name`),reports:k(v(),T({label:v().optional().describe(`Translated report label`),description:v().optional().describe(`Translated report description`)})).optional().describe(`Report translations keyed by report name`),pages:k(v(),T({title:v().optional().describe(`Translated page title`),description:v().optional().describe(`Translated page description`)})).optional().describe(`Page translations keyed by page name`),messages:k(v(),v()).optional().describe(`UI message translations keyed by message ID (supports ICU MessageFormat)`),validationMessages:k(v(),v()).optional().describe(`Validation error message translations keyed by rule name (supports ICU MessageFormat)`),notifications:k(v(),T({title:v().optional().describe(`Translated notification title`),body:v().optional().describe(`Translated notification body (supports ICU MessageFormat when enabled)`)})).optional().describe(`Global notification translations keyed by notification name`),errors:k(v(),v()).optional().describe(`Global error message translations keyed by error code`)}).describe(`Object-first application translation bundle for a single locale`));var H1=X(()=>A([`missing`,`redundant`,`stale`]).describe(`Translation diff status: missing from bundle, redundant (no matching metadata), or stale (metadata changed)`)),U1=X(()=>T({key:v().describe(`Dot-path translation key`),status:H1.describe(`Diff status of this translation key`),objectName:v().optional().describe(`Associated object name (snake_case)`),locale:v().describe(`BCP-47 locale code`),sourceHash:v().optional().describe(`Hash of source metadata for precise stale detection`),aiSuggested:v().optional().describe(`AI-suggested translation for this key`),aiConfidence:y().min(0).max(1).optional().describe(`AI suggestion confidence score (0–1)`)}).describe(`A single translation diff item`)),W1=X(()=>T({group:v().describe(`Translation group category`),totalKeys:y().int().nonnegative().describe(`Total keys in this group`),translatedKeys:y().int().nonnegative().describe(`Translated keys in this group`),coveragePercent:y().min(0).max(100).describe(`Coverage percentage for this group`)}).describe(`Coverage breakdown for a single translation group`));X(()=>T({locale:v().describe(`BCP-47 locale code`),objectName:v().optional().describe(`Object name scope (omit for full bundle)`),totalKeys:y().int().nonnegative().describe(`Total translatable keys from metadata`),translatedKeys:y().int().nonnegative().describe(`Number of translated keys`),missingKeys:y().int().nonnegative().describe(`Number of missing translations`),redundantKeys:y().int().nonnegative().describe(`Number of redundant translations`),staleKeys:y().int().nonnegative().describe(`Number of stale translations`),coveragePercent:y().min(0).max(100).describe(`Translation coverage percentage`),items:w(U1).describe(`Detailed diff items`),breakdown:w(W1).optional().describe(`Per-group coverage breakdown`)}).describe(`Aggregated translation coverage result`)),A([`insert`,`delete`,`retain`]);var G1=X(()=>D(`type`,[T({type:j(`insert`),text:v().describe(`Text to insert`),attributes:k(v(),S()).optional().describe(`Text formatting attributes (e.g., bold, italic)`)}),T({type:j(`delete`),count:y().int().positive().describe(`Number of characters to delete`)}),T({type:j(`retain`),count:y().int().positive().describe(`Number of characters to retain`),attributes:k(v(),S()).optional().describe(`Attribute changes to apply`)})])),K1=X(()=>T({operationId:v().uuid().describe(`Unique operation identifier`),documentId:v().describe(`Document identifier`),userId:v().describe(`User who created the operation`),sessionId:v().uuid().describe(`Session identifier`),components:w(G1).describe(`Operation components`),baseVersion:y().int().nonnegative().describe(`Document version this operation is based on`),timestamp:v().datetime().describe(`ISO 8601 datetime when operation was created`),metadata:k(v(),S()).optional().describe(`Additional operation metadata`)}));X(()=>T({operation:K1.describe(`Transformed operation`),transformed:b().describe(`Whether transformation was applied`),conflicts:w(v()).optional().describe(`Conflict descriptions if any`)})),A([`lww-register`,`g-counter`,`pn-counter`,`g-set`,`or-set`,`lww-map`,`text`,`tree`,`json`]);var q1=X(()=>T({clock:k(v(),y().int().nonnegative()).describe(`Map of replica ID to logical timestamp`)})),J1=X(()=>T({type:j(`lww-register`),value:S().describe(`Current register value`),timestamp:v().datetime().describe(`ISO 8601 datetime of last write`),replicaId:v().describe(`ID of replica that performed last write`),vectorClock:q1.optional().describe(`Optional vector clock for causality tracking`)}));X(()=>T({replicaId:v().describe(`Replica identifier`),delta:y().int().describe(`Change amount (positive for increment, negative for decrement)`),timestamp:v().datetime().describe(`ISO 8601 datetime of operation`)}));var Y1=X(()=>T({type:j(`g-counter`),counts:k(v(),y().int().nonnegative()).describe(`Map of replica ID to count`)})),X1=X(()=>T({type:j(`pn-counter`),positive:k(v(),y().int().nonnegative()).describe(`Positive increments per replica`),negative:k(v(),y().int().nonnegative()).describe(`Negative increments per replica`)})),Z1=X(()=>T({value:S().describe(`Element value`),timestamp:v().datetime().describe(`Addition timestamp`),replicaId:v().describe(`Replica that added the element`),uid:v().uuid().describe(`Unique identifier for this addition`),removed:b().optional().default(!1).describe(`Whether element has been removed`)})),Q1=X(()=>T({type:j(`or-set`),elements:w(Z1).describe(`Set elements with metadata`)})),$1=X(()=>T({operationId:v().uuid().describe(`Unique operation identifier`),replicaId:v().describe(`Replica identifier`),position:y().int().nonnegative().describe(`Position in document`),insert:v().optional().describe(`Text to insert`),delete:y().int().positive().optional().describe(`Number of characters to delete`),timestamp:v().datetime().describe(`ISO 8601 datetime of operation`),lamportTimestamp:y().int().nonnegative().describe(`Lamport timestamp for ordering`)})),e0=X(()=>T({type:j(`text`),documentId:v().describe(`Document identifier`),content:v().describe(`Current text content`),operations:w($1).describe(`History of operations`),lamportClock:y().int().nonnegative().describe(`Current Lamport clock value`),vectorClock:q1.describe(`Vector clock for causality`)})),t0=X(()=>D(`type`,[J1,Y1,X1,Q1,e0]));X(()=>T({state:t0.describe(`Merged CRDT state`),conflicts:w(T({type:v().describe(`Conflict type`),description:v().describe(`Conflict description`),resolved:b().describe(`Whether conflict was automatically resolved`)})).optional().describe(`Conflicts encountered during merge`)}));var n0=A([`blue`,`green`,`red`,`yellow`,`purple`,`orange`,`pink`,`teal`,`indigo`,`cyan`]),r0=X(()=>T({color:E([n0,v()]).describe(`Cursor color (preset or custom hex)`),opacity:y().min(0).max(1).optional().default(1).describe(`Cursor opacity (0-1)`),label:v().optional().describe(`Label to display with cursor (usually username)`),showLabel:b().optional().default(!0).describe(`Whether to show label`),pulseOnUpdate:b().optional().default(!0).describe(`Whether to pulse when cursor moves`)})),i0=X(()=>T({anchor:T({line:y().int().nonnegative().describe(`Anchor line number`),column:y().int().nonnegative().describe(`Anchor column number`)}).describe(`Selection anchor (start point)`),focus:T({line:y().int().nonnegative().describe(`Focus line number`),column:y().int().nonnegative().describe(`Focus column number`)}).describe(`Selection focus (end point)`),direction:A([`forward`,`backward`]).optional().describe(`Selection direction`)})),a0=X(()=>T({userId:v().describe(`User identifier`),sessionId:v().uuid().describe(`Session identifier`),documentId:v().describe(`Document identifier`),userName:v().describe(`Display name of user`),position:T({line:y().int().nonnegative().describe(`Cursor line number (0-indexed)`),column:y().int().nonnegative().describe(`Cursor column number (0-indexed)`)}).describe(`Current cursor position`),selection:i0.optional().describe(`Current text selection`),style:r0.describe(`Visual style for this cursor`),isTyping:b().optional().default(!1).describe(`Whether user is currently typing`),lastUpdate:v().datetime().describe(`ISO 8601 datetime of last cursor update`),metadata:k(v(),S()).optional().describe(`Additional cursor metadata`)}));X(()=>T({position:T({line:y().int().nonnegative(),column:y().int().nonnegative()}).optional().describe(`Updated cursor position`),selection:i0.optional().describe(`Updated selection`),isTyping:b().optional().describe(`Updated typing state`),metadata:k(v(),S()).optional().describe(`Updated metadata`)}));var o0=A([`active`,`idle`,`viewing`,`disconnected`]),s0=X(()=>T({userId:v().describe(`User identifier`),sessionId:v().uuid().describe(`Session identifier`),userName:v().describe(`Display name`),userAvatar:v().optional().describe(`User avatar URL`),status:o0.describe(`Current activity status`),currentDocument:v().optional().describe(`Document ID user is currently editing`),currentView:v().optional().describe(`Current view/page user is on`),lastActivity:v().datetime().describe(`ISO 8601 datetime of last activity`),joinedAt:v().datetime().describe(`ISO 8601 datetime when user joined session`),permissions:w(v()).optional().describe(`User permissions in this session`),metadata:k(v(),S()).optional().describe(`Additional user state metadata`)}));X(()=>T({sessionId:v().uuid().describe(`Session identifier`),documentId:v().optional().describe(`Document ID this session is for`),users:w(s0).describe(`Active users in session`),startedAt:v().datetime().describe(`ISO 8601 datetime when session started`),lastUpdate:v().datetime().describe(`ISO 8601 datetime of last update`),metadata:k(v(),S()).optional().describe(`Session metadata`)})),X(()=>T({status:o0.optional().describe(`Updated status`),currentDocument:v().optional().describe(`Updated current document`),currentView:v().optional().describe(`Updated current view`),metadata:k(v(),S()).optional().describe(`Updated metadata`)})),X(()=>T({eventId:v().uuid().describe(`Event identifier`),sessionId:v().uuid().describe(`Session identifier`),eventType:A([`user.joined`,`user.left`,`user.updated`,`session.created`,`session.ended`]).describe(`Type of awareness event`),userId:v().optional().describe(`User involved in event`),timestamp:v().datetime().describe(`ISO 8601 datetime of event`),payload:S().describe(`Event payload`)}));var c0=A([`ot`,`crdt`,`lock`,`hybrid`]),l0=X(()=>T({mode:c0.describe(`Collaboration mode to use`),enableCursorSharing:b().optional().default(!0).describe(`Enable cursor sharing`),enablePresence:b().optional().default(!0).describe(`Enable presence tracking`),enableAwareness:b().optional().default(!0).describe(`Enable awareness state`),maxUsers:y().int().positive().optional().describe(`Maximum concurrent users`),idleTimeout:y().int().positive().optional().default(3e5).describe(`Idle timeout in milliseconds`),conflictResolution:A([`ot`,`crdt`,`manual`]).optional().default(`ot`).describe(`Conflict resolution strategy`),persistence:b().optional().default(!0).describe(`Enable operation persistence`),snapshot:T({enabled:b().describe(`Enable periodic snapshots`),interval:y().int().positive().describe(`Snapshot interval in milliseconds`)}).optional().describe(`Snapshot configuration`)}));X(()=>T({sessionId:v().uuid().describe(`Session identifier`),documentId:v().describe(`Document identifier`),config:l0.describe(`Session configuration`),users:w(s0).describe(`Active users`),cursors:w(a0).describe(`Active cursors`),version:y().int().nonnegative().describe(`Current document version`),operations:w(E([K1,$1])).optional().describe(`Recent operations`),createdAt:v().datetime().describe(`ISO 8601 datetime when session was created`),lastActivity:v().datetime().describe(`ISO 8601 datetime of last activity`),status:A([`active`,`idle`,`ended`]).describe(`Session status`)}));var u0=X(()=>A([`json`,`yaml`,`typescript`,`javascript`])),d0=X(()=>T({size:y().int().min(0).describe(`File size in bytes`),modifiedAt:v().datetime().describe(`Last modified date`),etag:v().describe(`Entity tag for cache validation`),format:u0.describe(`Serialization format`),path:v().optional().describe(`File system path`),metadata:k(v(),S()).optional().describe(`Provider-specific metadata`)}));X(()=>T({patterns:w(v()).optional().describe(`File glob patterns`),ifNoneMatch:v().optional().describe(`ETag for conditional request`),ifModifiedSince:v().datetime().optional().describe(`Only load if modified after this date`),validate:b().default(!0).describe(`Validate against schema`),useCache:b().default(!0).describe(`Enable caching`),filter:JH.optional().describe(`Filter predicate (CEL)`),limit:y().int().min(1).optional().describe(`Maximum items to load`),recursive:b().default(!0).describe(`Search subdirectories`)})),X(()=>T({format:u0.default(`typescript`).describe(`Output format`),prettify:b().default(!0).describe(`Format with indentation`),indent:y().int().min(0).max(8).default(2).describe(`Indentation spaces`),sortKeys:b().default(!1).describe(`Sort object keys`),includeDefaults:b().default(!1).describe(`Include default values`),backup:b().default(!1).describe(`Create backup file`),overwrite:b().default(!0).describe(`Overwrite existing file`),atomic:b().default(!0).describe(`Use atomic write operation`),path:v().optional().describe(`Custom output path`)})),X(()=>T({output:v().describe(`Output file path`),format:u0.default(`json`).describe(`Export format`),filter:JH.optional().describe(`Filter items to export (CEL)`),includeStats:b().default(!1).describe(`Include metadata statistics`),compress:b().default(!1).describe(`Compress output (gzip)`),prettify:b().default(!0).describe(`Pretty print output`)})),X(()=>T({conflictResolution:A([`skip`,`overwrite`,`merge`,`fail`]).default(`merge`).describe(`How to handle existing items`),validate:b().default(!0).describe(`Validate before import`),dryRun:b().default(!1).describe(`Simulate import without saving`),continueOnError:b().default(!1).describe(`Continue if validation fails`),transform:v().optional().describe(`Transform items before import`)})),X(()=>T({data:S().nullable().describe(`Loaded metadata`),fromCache:b().default(!1).describe(`Loaded from cache`),notModified:b().default(!1).describe(`Not modified since last request`),etag:v().optional().describe(`Entity tag`),stats:d0.optional().describe(`Metadata statistics`),loadTime:y().min(0).optional().describe(`Load duration in ms`)})),X(()=>T({success:b().describe(`Save successful`),path:v().describe(`Output path`),etag:v().optional().describe(`Generated entity tag`),size:y().int().min(0).optional().describe(`File size`),saveTime:y().min(0).optional().describe(`Save duration in ms`),backupPath:v().optional().describe(`Backup file path`)})),X(()=>T({type:A([`added`,`changed`,`deleted`]).describe(`Event type`),metadataType:v().describe(`Type of metadata`),name:v().describe(`Item identifier`),path:v().describe(`File path`),data:S().optional().describe(`Item data`),timestamp:v().datetime().describe(`Event timestamp`)})),X(()=>T({type:v().describe(`Collection type`),count:y().int().min(0).describe(`Number of items`),formats:w(u0).describe(`Formats in collection`),totalSize:y().int().min(0).optional().describe(`Total size in bytes`),lastModified:v().datetime().optional().describe(`Last modification date`),location:v().optional().describe(`Collection location`)})),X(()=>T({name:v().describe(`Loader identifier`),protocol:A([`file:`,`http:`,`s3:`,`datasource:`,`memory:`]).describe(`Protocol identifier`),capabilities:T({read:b().default(!0),write:b().default(!1),watch:b().default(!1),list:b().default(!0)}).describe(`Loader capabilities`),supportedFormats:w(u0).describe(`Supported formats`),supportsWatch:b().default(!1).describe(`Supports file watching`),supportsWrite:b().default(!0).describe(`Supports write operations`),supportsCache:b().default(!0).describe(`Supports caching`)}));var f0=X(()=>A([`filesystem`,`memory`,`none`]));X(()=>T({datasource:v().optional().describe(`Datasource name reference for database persistence`),tableName:v().default(`sys_metadata`).describe(`Database table name for metadata storage`),fallback:f0.default(`none`).describe(`Fallback strategy when datasource is unavailable`),rootDir:v().optional().describe(`Root directory path`),formats:w(u0).default([`typescript`,`json`,`yaml`]).describe(`Enabled formats`),cache:T({enabled:b().default(!0).describe(`Enable caching`),ttl:y().int().min(0).default(3600).describe(`Cache TTL in seconds`),maxSize:y().int().min(0).optional().describe(`Max cache size in bytes`),databaseLoader:T({enabled:b().default(!0).describe(`Enable DatabaseLoader cache`),maxSize:y().int().min(0).default(500).describe(`Max cached entries`),ttl:y().int().min(0).default(6e4).describe(`Cache TTL in milliseconds`)}).optional().describe(`DatabaseLoader read-through cache`)}).optional().describe(`Cache settings`),watch:b().default(!1).describe(`Enable file watching`),watchOptions:T({ignored:w(v()).optional().describe(`Patterns to ignore`),persistent:b().default(!0).describe(`Keep process running`),ignoreInitial:b().default(!0).describe(`Ignore initial add events`)}).optional().describe(`File watcher options`),validation:T({strict:b().default(!0).describe(`Strict validation`),throwOnError:b().default(!0).describe(`Throw on validation error`)}).optional().describe(`Validation settings`),loaderOptions:k(v(),S()).optional().describe(`Loader-specific configuration`),persistence:T({writable:b().default(!0).describe(`Allow base metadata writes via register()`),overlayWritable:b().default(!0).describe(`Allow overlay writes via saveOverlay()`)}).optional().describe(`Persistence write gates`)}));var p0=X(()=>A([`system`,`platform`,`user`])),m0=X(()=>A([`draft`,`active`,`archived`,`deprecated`]));X(()=>T({id:v(),name:v(),type:v(),namespace:v().default(`default`),packageId:v().optional().describe(`Package ID that owns/delivered this metadata`),managedBy:A([`package`,`platform`,`user`]).optional().describe(`Who manages this metadata record lifecycle`),scope:p0.default(`platform`),metadata:k(v(),S()),extends:v().optional().describe(`Name of the parent metadata to extend/override`),strategy:A([`merge`,`replace`]).default(`merge`),owner:v().optional(),state:m0.default(`active`),organizationId:v().optional().describe(`Organization identifier for multi-tenant isolation`),tenantId:v().optional().describe(`Tenant identifier for multi-tenant isolation`),environmentId:v().optional().describe(`Deprecated (ADR-0006 v4): legacy environment_id column. New code must use organization_id only.`),version:y().default(1).describe(`Record version for optimistic concurrency control`),checksum:v().optional().describe(`Content checksum for change detection`),source:A([`filesystem`,`database`,`api`,`migration`]).optional().describe(`Origin of this metadata record`),tags:w(v()).optional().describe(`Classification tags for filtering and grouping`),publishedDefinition:S().optional().describe(`Snapshot of the last published definition`),publishedAt:v().datetime().optional().describe(`When this metadata was last published`),publishedBy:v().optional().describe(`Who published this version`),createdBy:v().optional(),createdAt:v().datetime().optional().describe(`Creation timestamp`),updatedBy:v().optional(),updatedAt:v().datetime().optional().describe(`Last update timestamp`)})),X(()=>T({success:b().describe(`Whether the publish succeeded`),packageId:v().describe(`The package ID that was published`),version:y().int().describe(`New version number after publish`),publishedAt:v().datetime().describe(`Publish timestamp`),itemsPublished:y().int().describe(`Total metadata items published`),validationErrors:w(T({type:v().describe(`Metadata type that failed validation`),name:v().describe(`Item name that failed validation`),message:v().describe(`Validation error message`)})).optional().describe(`Validation errors if publish failed`)}));var h0=X(()=>A([`json`,`yaml`,`yml`,`ts`,`js`,`typescript`,`javascript`])),g0=X(()=>T({path:v().optional(),size:y().optional(),mtime:v().datetime().optional(),hash:v().optional(),etag:v().optional(),modifiedAt:v().datetime().optional(),format:h0.optional()}));X(()=>T({name:v(),protocol:A([`file:`,`http:`,`s3:`,`datasource:`,`memory:`]).describe(`Loader protocol identifier`),description:v().optional(),supportedFormats:w(v()).optional(),supportsWatch:b().optional(),supportsWrite:b().optional(),supportsCache:b().optional(),capabilities:T({read:b().default(!0),write:b().default(!1),watch:b().default(!1),list:b().default(!0)})})),X(()=>T({scope:p0.optional(),namespace:v().optional(),raw:b().optional().describe(`Return raw file content instead of parsed JSON`),cache:b().optional(),useCache:b().optional(),validate:b().optional(),ifNoneMatch:v().optional(),recursive:b().optional(),limit:y().optional(),patterns:w(v()).optional(),loader:v().optional().describe(`Specific loader to use (e.g. filesystem, database)`)})),X(()=>T({data:S(),stats:g0.optional(),format:h0.optional(),source:v().optional(),fromCache:b().optional(),etag:v().optional(),notModified:b().optional(),loadTime:y().optional()})),X(()=>T({format:h0.optional(),create:b().default(!0),overwrite:b().default(!0),path:v().optional(),prettify:b().optional(),indent:y().optional(),sortKeys:b().optional(),backup:b().optional(),atomic:b().optional(),loader:v().optional().describe(`Specific loader to use (e.g. filesystem, database)`)})),X(()=>T({success:b(),path:v().optional(),stats:g0.optional(),etag:v().optional(),size:y().optional(),saveTime:y().optional(),backupPath:v().optional()})),X(()=>T({type:A([`add`,`change`,`unlink`,`added`,`changed`,`deleted`]),path:v(),name:v().optional(),stats:g0.optional(),metadataType:v().optional(),data:S().optional(),timestamp:v().datetime().optional()})),X(()=>T({type:v(),count:y(),namespaces:w(v())})),X(()=>T({types:w(v()).optional(),namespaces:w(v()).optional(),output:v().describe(`Output directory or file`),format:h0.default(`json`)})),X(()=>T({source:v().describe(`Input directory or file`),strategy:A([`merge`,`replace`,`skip`]).default(`merge`),validate:b().default(!0)})),X(()=>A([`filesystem`,`database`,`api`,`migration`]));var _0=X(()=>T({id:v(),name:v(),type:v(),version:y().describe(`Version number at this snapshot`),operationType:A([`create`,`update`,`publish`,`revert`,`delete`]).describe(`Type of operation that created this history entry`),metadata:E([v(),k(v(),S())]).nullable().optional().describe(`Snapshot of metadata definition at this version (raw JSON string or parsed object)`),checksum:v().describe(`SHA-256 checksum of metadata content`),previousChecksum:v().optional().describe(`Checksum of the previous version`),changeNote:v().optional().describe(`Description of changes made in this version`),organizationId:v().optional().describe(`Organization identifier for multi-tenant isolation`),environmentId:v().optional().describe(`Deprecated (ADR-0006 v4): legacy environment_id column. New writes leave unset.`),recordedBy:v().optional().describe(`User who made this change`),recordedAt:v().datetime().describe(`Timestamp when this version was recorded`)}));X(()=>T({limit:y().int().positive().optional().describe(`Maximum number of history records to return`),offset:y().int().nonnegative().optional().describe(`Number of records to skip`),since:v().datetime().optional().describe(`Only return history after this timestamp`),until:v().datetime().optional().describe(`Only return history before this timestamp`),operationType:A([`create`,`update`,`publish`,`revert`,`delete`]).optional().describe(`Filter by operation type`),includeMetadata:b().optional().default(!0).describe(`Include full metadata payload`)})),X(()=>T({records:w(_0),total:y().int().nonnegative(),hasMore:b()})),X(()=>T({type:v(),name:v(),version1:y(),version2:y(),checksum1:v(),checksum2:v(),identical:b(),patch:w(S()).optional().describe(`JSON patch operations`),summary:v().optional().describe(`Human-readable summary of changes`)})),X(()=>T({maxVersions:y().int().positive().optional().describe(`Maximum number of versions to retain`),maxAgeDays:y().int().positive().optional().describe(`Maximum age of history records in days`),autoCleanup:b().default(!1).describe(`Enable automatic cleanup of old history`),cleanupIntervalHours:y().int().positive().default(24).describe(`How often to run cleanup (in hours)`)}));var v0=A([`metadata`,`data`,`auth`,`file-storage`,`search`,`cache`,`queue`,`automation`,`graphql`,`analytics`,`realtime`,`job`,`notification`,`ai`,`i18n`,`ui`,`workflow`]);X(()=>A([`required`,`core`,`optional`])),X(()=>T({name:v0,enabled:b(),status:A([`running`,`stopped`,`degraded`,`initializing`]),version:v().optional(),provider:v().optional().describe(`Implementation provider (e.g. "s3" for storage)`),features:w(v()).optional().describe(`List of supported sub-features`)})),X(()=>k(v0,S().describe(`Service Instance implementing the protocol interface`))),X(()=>T({id:v(),name:v0,options:k(v(),S()).optional()}));var y0=A([`shared_schema`,`isolated_schema`,`isolated_db`]),b0=X(()=>A([`turso`,`postgres`,`memory`]).describe(`Database provider for tenant data`)),x0=X(()=>T({url:v().min(1).describe(`Database connection URL`),authToken:v().optional().describe(`Database auth token (encrypted at rest)`),group:v().optional().describe(`Turso database group name`)}).describe(`Tenant database connection configuration`)),S0=X(()=>T({maxUsers:y().int().positive().optional().describe(`Maximum number of users`),maxStorage:y().int().positive().optional().describe(`Maximum storage in bytes`),apiRateLimit:y().int().positive().optional().describe(`API requests per minute`),maxObjects:y().int().positive().optional().describe(`Maximum number of custom objects`),maxRecordsPerObject:y().int().positive().optional().describe(`Maximum records per object`),maxDeploymentsPerDay:y().int().positive().optional().describe(`Maximum deployments per day`),maxStorageBytes:y().int().positive().optional().describe(`Maximum storage in bytes`)}));X(()=>T({currentObjectCount:y().int().min(0).default(0).describe(`Current number of custom objects`),currentRecordCount:y().int().min(0).default(0).describe(`Total records across all objects`),currentStorageBytes:y().int().min(0).default(0).describe(`Current storage usage in bytes`),deploymentsToday:y().int().min(0).default(0).describe(`Deployments executed today`),currentUsers:y().int().min(0).default(0).describe(`Current number of active users`),apiRequestsThisMinute:y().int().min(0).default(0).describe(`API requests in the current minute`),lastUpdatedAt:v().datetime().optional().describe(`Last usage update time`)}).describe(`Current tenant resource usage`)),X(()=>T({allowed:b().describe(`Whether the operation is within quota`),exceededQuota:v().optional().describe(`Name of the exceeded quota`),currentUsage:y().optional().describe(`Current usage value`),limit:y().optional().describe(`Quota limit`),message:v().optional().describe(`Human-readable quota message`)}).describe(`Quota enforcement check result`)),X(()=>T({id:v().describe(`Unique tenant identifier`),name:v().describe(`Tenant display name`),isolationLevel:y0,databaseProvider:b0.optional().describe(`Database provider`),connectionConfig:x0.optional().describe(`Database connection config`),provisioningStatus:A([`provisioning`,`active`,`suspended`,`failed`,`destroying`]).optional().describe(`Current provisioning lifecycle status`),plan:A([`free`,`pro`,`enterprise`]).optional().describe(`Subscription plan`),customizations:k(v(),S()).optional().describe(`Custom configuration values`),quotas:S0.optional()}));var C0=X(()=>T({strategy:j(`shared_schema`).describe(`Row-level isolation strategy`),database:T({enableRLS:b().default(!0).describe(`Enable PostgreSQL Row-Level Security`),contextMethod:A([`session_variable`,`search_path`,`application_name`]).default(`session_variable`).describe(`How to set tenant context`),contextVariable:v().default(`app.current_tenant`).describe(`Session variable name`),applicationValidation:b().default(!0).describe(`Application-level tenant validation`)}).optional().describe(`Database configuration`),performance:T({usePartialIndexes:b().default(!0).describe(`Use partial indexes per tenant`),usePartitioning:b().default(!1).describe(`Use table partitioning by tenant_id`),poolSizePerTenant:y().int().positive().optional().describe(`Connection pool size per tenant`)}).optional().describe(`Performance settings`)})),w0=X(()=>T({strategy:j(`isolated_schema`).describe(`Schema-level isolation strategy`),schema:T({namingPattern:v().default(`tenant_{tenant_id}`).describe(`Schema naming pattern`),includePublicSchema:b().default(!0).describe(`Include public schema`),sharedSchema:v().default(`public`).describe(`Schema for shared resources`),autoCreateSchema:b().default(!0).describe(`Auto-create schema`)}).optional().describe(`Schema configuration`),migrations:T({strategy:A([`parallel`,`sequential`,`on_demand`]).default(`parallel`).describe(`Migration strategy`),maxConcurrent:y().int().positive().default(10).describe(`Max concurrent migrations`),rollbackOnError:b().default(!0).describe(`Rollback on error`)}).optional().describe(`Migration configuration`),performance:T({poolPerSchema:b().default(!1).describe(`Separate pool per schema`),schemaCacheTTL:y().int().positive().default(3600).describe(`Schema cache TTL`)}).optional().describe(`Performance settings`)})),T0=X(()=>T({strategy:j(`isolated_db`).describe(`Database-level isolation strategy`),database:T({namingPattern:v().default(`tenant_{tenant_id}`).describe(`Database naming pattern`),serverStrategy:A([`shared`,`sharded`,`dedicated`]).default(`shared`).describe(`Server assignment strategy`),separateCredentials:b().default(!0).describe(`Separate credentials per tenant`),autoCreateDatabase:b().default(!0).describe(`Auto-create database`)}).optional().describe(`Database configuration`),connectionPool:T({poolSize:y().int().positive().default(10).describe(`Connection pool size`),maxActivePools:y().int().positive().default(100).describe(`Max active pools`),idleTimeout:y().int().positive().default(300).describe(`Idle pool timeout`),usePooler:b().default(!0).describe(`Use connection pooler`)}).optional().describe(`Connection pool configuration`),backup:T({strategy:A([`individual`,`consolidated`,`on_demand`]).default(`individual`).describe(`Backup strategy`),frequencyHours:y().int().positive().default(24).describe(`Backup frequency`),retentionDays:y().int().positive().default(30).describe(`Backup retention days`)}).optional().describe(`Backup configuration`),encryption:T({perTenantKeys:b().default(!1).describe(`Per-tenant encryption keys`),algorithm:v().default(`AES-256-GCM`).describe(`Encryption algorithm`),keyManagement:A([`aws_kms`,`azure_key_vault`,`gcp_kms`,`hashicorp_vault`,`custom`]).optional().describe(`Key management service`)}).optional().describe(`Encryption configuration`)}));X(()=>D(`strategy`,[C0,w0,T0])),X(()=>T({encryption:T({atRest:b().default(!0).describe(`Require encryption at rest`),inTransit:b().default(!0).describe(`Require encryption in transit`),fieldLevel:b().default(!1).describe(`Require field-level encryption`)}).optional().describe(`Encryption requirements`),accessControl:T({requireMFA:b().default(!1).describe(`Require MFA`),requireSSO:b().default(!1).describe(`Require SSO`),ipWhitelist:w(v()).optional().describe(`Allowed IP addresses`),sessionTimeout:y().int().positive().default(3600).describe(`Session timeout`)}).optional().describe(`Access control requirements`),compliance:T({standards:w(A([`sox`,`hipaa`,`gdpr`,`pci_dss`,`iso_27001`,`fedramp`])).optional().describe(`Compliance standards`),requireAuditLog:b().default(!0).describe(`Require audit logging`),auditRetentionDays:y().int().positive().default(365).describe(`Audit retention days`),dataResidency:T({region:v().optional().describe(`Required region (e.g., US, EU, APAC)`),excludeRegions:w(v()).optional().describe(`Prohibited regions`)}).optional().describe(`Data residency requirements`)}).optional().describe(`Compliance requirements`)}));var E0=A([`boolean`,`counter`,`gauge`]).describe(`License metric type`);X(()=>T({code:v().regex(/^[a-z_][a-z0-9_.]*$/).describe(`Feature code (e.g. core.api_access)`),label:v(),description:v().optional(),type:E0.default(`boolean`),unit:A([`count`,`bytes`,`seconds`,`percent`]).optional(),requires:w(v()).optional()})),X(()=>T({code:v().describe(`Plan code (e.g. pro_v1)`),label:v(),active:b().default(!0),features:w(v()).describe(`List of enabled boolean features`),limits:k(v(),y()).describe(`Map of metric codes to limit values (e.g. { storage_gb: 10 })`),currency:v().default(`USD`).optional(),priceMonthly:y().optional(),priceYearly:y().optional()})),X(()=>T({spaceId:v().describe(`Target Space ID`),planCode:v(),issuedAt:v().datetime(),expiresAt:v().datetime().optional(),status:A([`active`,`expired`,`suspended`,`trial`]),customFeatures:w(v()).optional(),customLimits:k(v(),y()).optional(),plugins:w(v()).optional().describe(`List of enabled plugin package IDs`),signature:v().optional().describe(`Cryptographic signature of the license`)}));var D0=X(()=>A([`manual`,`auto`,`proxy`]).describe(`Registry synchronization strategy`)),O0=X(()=>T({url:v().url().describe(`Upstream registry endpoint`),syncPolicy:D0.default(`auto`),syncInterval:y().int().min(60).optional().describe(`Auto-sync interval in seconds`),auth:T({type:A([`none`,`basic`,`bearer`,`api-key`,`oauth2`]).default(`none`),username:v().optional(),password:v().optional(),token:v().optional(),apiKey:v().optional()}).optional(),tls:T({enabled:b().default(!0),verifyCertificate:b().default(!0),certificate:v().optional(),privateKey:v().optional()}).optional(),timeout:y().int().min(1e3).default(3e4).describe(`Request timeout in milliseconds`),retry:T({maxAttempts:y().int().min(0).default(3),backoff:A([`fixed`,`linear`,`exponential`]).default(`exponential`)}).optional()}));X(()=>T({type:A([`public`,`private`,`hybrid`]).describe(`Registry deployment type`),upstream:w(O0).optional().describe(`Upstream registries to sync from or proxy to`),scope:w(v()).optional().describe(`npm-style scopes managed by this registry (e.g., @my-corp, @enterprise)`),defaultScope:v().optional().describe(`Default scope prefix for new plugins`),storage:T({backend:A([`local`,`s3`,`gcs`,`azure-blob`,`oss`]).default(`local`),path:v().optional(),credentials:k(v(),S()).optional()}).optional(),visibility:A([`public`,`private`,`internal`]).default(`private`).describe(`Who can access this registry`),accessControl:T({requireAuthForRead:b().default(!1),requireAuthForWrite:b().default(!0),allowedPrincipals:w(v()).optional()}).optional(),cache:T({enabled:b().default(!0),ttl:y().int().min(0).default(3600).describe(`Cache TTL in seconds`),maxSize:y().int().optional().describe(`Maximum cache size in bytes`)}).optional(),mirrors:w(T({url:v().url(),priority:y().int().min(1).default(1)})).optional().describe(`Mirror registries for redundancy`)}));var k0=A([`provisioning`,`active`,`suspended`,`failed`,`destroying`]).describe(`Tenant provisioning lifecycle status`),A0=X(()=>A([`free`,`pro`,`enterprise`]).describe(`Tenant subscription plan`)),j0=X(()=>A([`us-east`,`us-west`,`eu-west`,`eu-central`,`ap-southeast`,`ap-northeast`]).describe(`Available deployment region`)),M0=X(()=>T({name:v().min(1).describe(`Step name (e.g., create_database, sync_schema)`),status:A([`pending`,`running`,`completed`,`failed`,`skipped`]).describe(`Step status`),startedAt:v().datetime().optional().describe(`Step start time`),completedAt:v().datetime().optional().describe(`Step completion time`),durationMs:y().int().min(0).optional().describe(`Step duration in ms`),error:v().optional().describe(`Error message on failure`)}).describe(`Individual provisioning step status`));X(()=>T({orgId:v().min(1).describe(`Organization ID`),plan:A0.default(`free`),region:j0.default(`us-east`),displayName:v().optional().describe(`Tenant display name`),adminEmail:v().email().optional().describe(`Initial admin user email`),metadata:k(v(),S()).optional().describe(`Additional metadata`)}).describe(`Tenant provisioning request`)),X(()=>T({tenantId:v().min(1).describe(`Provisioned tenant ID`),connectionUrl:v().min(1).describe(`Database connection URL`),status:k0,region:j0,plan:A0,steps:w(M0).default([]).describe(`Pipeline step statuses`),totalDurationMs:y().int().min(0).optional().describe(`Total provisioning duration`),provisionedAt:v().datetime().optional().describe(`Provisioning completion time`),error:v().optional().describe(`Error message on failure`)}).describe(`Tenant provisioning result`)),A([`validating`,`diffing`,`migrating`,`registering`,`ready`,`failed`,`rolling_back`]).describe(`Deployment lifecycle status`);var N0=X(()=>T({entityType:A([`object`,`field`,`index`,`view`,`flow`,`permission`]).describe(`Entity type`),entityName:v().min(1).describe(`Entity name`),parentEntity:v().optional().describe(`Parent entity name`),changeType:A([`added`,`modified`,`removed`]).describe(`Change type`),oldValue:S().optional().describe(`Previous value`),newValue:S().optional().describe(`New value`)}).describe(`Individual schema change`));X(()=>T({changes:w(N0).default([]).describe(`List of schema changes`),summary:T({added:y().int().min(0).default(0).describe(`Number of added entities`),modified:y().int().min(0).default(0).describe(`Number of modified entities`),removed:y().int().min(0).default(0).describe(`Number of removed entities`)}).describe(`Change summary counts`),hasBreakingChanges:b().default(!1).describe(`Whether diff contains breaking changes`)}).describe(`Schema diff between current and desired state`));var P0=X(()=>T({sql:v().min(1).describe(`SQL DDL statement`),reversible:b().default(!0).describe(`Whether the statement can be reversed`),rollbackSql:v().optional().describe(`Reverse SQL for rollback`),order:y().int().min(0).describe(`Execution order`)}).describe(`Single DDL migration statement`));X(()=>T({statements:w(P0).default([]).describe(`Ordered DDL statements`),dialect:v().min(1).describe(`Target SQL dialect`),reversible:b().default(!0).describe(`Whether the plan can be fully rolled back`),estimatedDurationMs:y().int().min(0).optional().describe(`Estimated execution time`)}).describe(`Ordered migration plan`));var F0=X(()=>T({severity:A([`error`,`warning`,`info`]).describe(`Issue severity`),path:v().describe(`Entity path (e.g., objects.project_task.fields.name)`),message:v().describe(`Issue description`),code:v().optional().describe(`Validation error code`)}).describe(`Validation issue`));X(()=>T({valid:b().describe(`Whether the bundle is valid`),issues:w(F0).default([]).describe(`Validation issues`),errorCount:y().int().min(0).default(0).describe(`Number of errors`),warningCount:y().int().min(0).default(0).describe(`Number of warnings`)}).describe(`Bundle validation result`));var I0=X(()=>T({version:v().min(1).describe(`Deployment version`),checksum:v().optional().describe(`SHA256 checksum`),objects:w(v()).default([]).describe(`Object names included`),views:w(v()).default([]).describe(`View names included`),flows:w(v()).default([]).describe(`Flow names included`),permissions:w(v()).default([]).describe(`Permission names included`),createdAt:v().datetime().optional().describe(`Bundle creation time`)}).describe(`Deployment manifest`));X(()=>T({manifest:I0,objects:w(k(v(),S())).default([]).describe(`Object definitions`),views:w(k(v(),S())).default([]).describe(`View definitions`),flows:w(k(v(),S())).default([]).describe(`Flow definitions`),permissions:w(k(v(),S())).default([]).describe(`Permission definitions`),seedData:w(k(v(),S())).default([]).describe(`Seed data records`)}).describe(`Deploy bundle containing all metadata for deployment`)),X(()=>T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`App identifier (snake_case)`),label:v().min(1).describe(`App display label`),version:v().min(1).describe(`App version (semver)`),description:v().optional().describe(`App description`),minKernelVersion:v().optional().describe(`Minimum required kernel version`),objects:w(v()).default([]).describe(`Object names provided`),views:w(v()).default([]).describe(`View names provided`),flows:w(v()).default([]).describe(`Flow names provided`),hasSeedData:b().default(!1).describe(`Whether app includes seed data`),seedData:w(k(v(),S())).default([]).describe(`Seed data records`),dependencies:w(v()).default([]).describe(`Required app dependencies`)}).describe(`App manifest for marketplace installation`)),X(()=>T({compatible:b().describe(`Whether the app is compatible`),issues:w(T({severity:A([`error`,`warning`]).describe(`Issue severity`),message:v().describe(`Issue description`),category:A([`kernel_version`,`object_conflict`,`dependency_missing`,`quota_exceeded`]).describe(`Issue category`)})).default([]).describe(`Compatibility issues`)}).describe(`App compatibility check result`)),X(()=>T({tenantId:v().min(1).describe(`Target tenant ID`),appId:v().min(1).describe(`App identifier`),configOverrides:k(v(),S()).optional().describe(`Configuration overrides`),skipSeedData:b().default(!1).describe(`Skip seed data population`)}).describe(`App install request`)),X(()=>T({success:b().describe(`Whether installation succeeded`),appId:v().describe(`Installed app identifier`),version:v().describe(`Installed app version`),installedObjects:w(v()).default([]).describe(`Objects created/updated`),createdTables:w(v()).default([]).describe(`Database tables created`),seededRecords:y().int().min(0).default(0).describe(`Seed records inserted`),durationMs:y().int().min(0).optional().describe(`Installation duration`),error:v().optional().describe(`Error message on failure`)}).describe(`App install result`));var L0=A([`sha256`,`sha384`,`sha512`]).describe(`Hash algorithm used for the artifact checksum`),R0=T({algorithm:L0.default(`sha256`),value:v().regex(/^[a-f0-9]+$/,`Checksum value must be lowercase hexadecimal`).describe(`Hex-encoded digest of the artifact body`)}).describe(`Artifact integrity checksum`),z0=A([`javascript`,`typescript`]).describe(`Source language of the function code`),B0=T({name:v().regex(/^[a-z_][a-z0-9_]*$/).describe(`Function machine name (snake_case)`),language:z0.default(`javascript`),code:v().describe(`Inlined function source`),source:T({path:v().optional().describe(`Source file path (relative to project root)`),exportName:v().optional().describe(`Exported symbol name`)}).optional().describe(`Source-map metadata for the function`),hash:v().regex(/^[a-f0-9]+$/).optional().describe(`Hex SHA-256 of the inlined code`)}).describe(`A single inlined function`),V0=T({id:v().describe(`Plugin/driver package id`),version:v().optional().describe(`SemVer range required by the environment`)}).describe(`A plugin or driver dependency declaration`),H0=T({plugins:w(V0).optional(),drivers:w(V0).optional(),engine:T({objectstack:v().regex(/^[><=~^]*\d+\.\d+\.\d+/).describe(`ObjectStack platform version requirement (SemVer range)`)}).optional()}).describe(`Plugin/driver requirements baked into the artifact`),U0=T({objects:w(S()).optional(),fields:w(S()).optional(),views:w(S()).optional(),apps:w(S()).optional(),pages:w(S()).optional(),dashboards:w(S()).optional(),reports:w(S()).optional(),flows:w(S()).optional(),workflows:w(S()).optional(),triggers:w(S()).optional(),agents:w(S()).optional(),tools:w(S()).optional(),skills:w(S()).optional(),permissions:w(S()).optional(),permissionSets:w(S()).optional(),roles:w(S()).optional(),profiles:w(S()).optional(),translations:w(S()).optional(),datasources:w(S()).optional(),datasets:w(S()).optional(),actions:w(S()).optional(),apis:w(S()).optional()}).passthrough().describe(`Compiled environment metadata grouped by category`),W0=T({url:v().url().describe(`Signed URL pointing at the artifact payload`),expiresAt:v().datetime().optional().describe(`ISO-8601 expiry timestamp`),checksum:R0.describe(`Checksum of the referenced payload`)}).describe(`Out-of-band payload reference (reserved for future use)`);T({schemaVersion:j(`0.1`).describe(`Environment artifact envelope schema version`),environmentId:v().min(1).describe(`Environment identifier (control-plane scoped)`),commitId:v().min(1).describe(`Content-addressable revision id`),checksum:R0,builtAt:v().datetime().optional().describe(`ISO-8601 timestamp of when the artifact was built`),builtWith:v().optional().describe(`Build tool identifier`),metadata:U0,functions:w(B0).default([]).describe(`Inlined function code packaged with the artifact`),manifest:H0,payloadRef:W0.optional()}).describe(`ObjectStack Environment Artifact envelope (v0)`);export{T as A,b as C,j as D,M as E,E as F,S as I,wc as L,bl as M,v as N,ml as O,O as P,dc as R,w as S,D as T,ab as _,VO as a,nu as b,sS as c,Wv as d,zy as f,W_ as g,ib as h,TL as i,k as j,y as k,Fy as l,ob as m,pV as n,yE as o,yy as p,Rz as r,_E as s,WH as t,dy as u,U_ as v,$l as w,ul as x,A as y};
|