openxiangda-contracts 2.77.0 → 2.79.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. package/dist/ai.d.ts +31 -0
  2. package/dist/ai.d.ts.map +1 -1
  3. package/dist/ai.js +14 -0
  4. package/dist/ai.js.map +1 -1
  5. package/dist/browser.d.ts +11 -0
  6. package/dist/browser.d.ts.map +1 -1
  7. package/dist/browser.js +10 -0
  8. package/dist/browser.js.map +1 -1
  9. package/dist/cli.d.ts +5 -0
  10. package/dist/cli.d.ts.map +1 -1
  11. package/dist/data-field-validation.js +26 -23
  12. package/dist/data-field-validation.js.map +1 -1
  13. package/dist/index.d.ts +13 -0
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +13 -0
  16. package/dist/index.js.map +1 -1
  17. package/dist/native-compiler/address-value.d.ts +13 -0
  18. package/dist/native-compiler/address-value.d.ts.map +1 -0
  19. package/dist/native-compiler/address-value.js +70 -0
  20. package/dist/native-compiler/address-value.js.map +1 -0
  21. package/dist/native-compiler/cascade-value.d.ts +6 -0
  22. package/dist/native-compiler/cascade-value.d.ts.map +1 -0
  23. package/dist/native-compiler/cascade-value.js +47 -0
  24. package/dist/native-compiler/cascade-value.js.map +1 -0
  25. package/dist/native-compiler/compiler.d.ts +1 -1
  26. package/dist/native-compiler/compiler.d.ts.map +1 -1
  27. package/dist/native-compiler/compiler.js +99 -54
  28. package/dist/native-compiler/compiler.js.map +1 -1
  29. package/dist/native-compiler/data-field.d.ts +3 -0
  30. package/dist/native-compiler/data-field.d.ts.map +1 -1
  31. package/dist/native-compiler/data-field.js +10 -2
  32. package/dist/native-compiler/data-field.js.map +1 -1
  33. package/dist/native-compiler/index.cjs +6 -6
  34. package/dist/native-compiler/index.d.ts +12 -0
  35. package/dist/native-compiler/index.d.ts.map +1 -1
  36. package/dist/native-compiler/index.js +6 -6
  37. package/dist/native-compiler/resource-query.d.ts +21 -0
  38. package/dist/native-compiler/resource-query.d.ts.map +1 -0
  39. package/dist/native-compiler/resource-query.js +154 -0
  40. package/dist/native-compiler/resource-query.js.map +1 -0
  41. package/dist/native-compiler/service-mutations.d.ts +13 -0
  42. package/dist/native-compiler/service-mutations.d.ts.map +1 -0
  43. package/dist/native-compiler/service-mutations.js +25 -0
  44. package/dist/native-compiler/service-mutations.js.map +1 -0
  45. package/dist/native-compiler/workflow-approval-empty.d.ts +1 -1
  46. package/dist/native-compiler/workflow-approval-empty.d.ts.map +1 -1
  47. package/dist/native-compiler/workflow-approval-empty.js +1 -1
  48. package/dist/native-compiler/workflow-approval-empty.js.map +1 -1
  49. package/dist/native-compiler/workflow-business-command.d.ts +10 -0
  50. package/dist/native-compiler/workflow-business-command.d.ts.map +1 -1
  51. package/dist/native-compiler/workflow-business-command.js +6 -0
  52. package/dist/native-compiler/workflow-business-command.js.map +1 -1
  53. package/dist/native-compiler/workflow-business-step.d.ts +8 -2
  54. package/dist/native-compiler/workflow-business-step.d.ts.map +1 -1
  55. package/dist/native-compiler/workflow-business-step.js +10 -5
  56. package/dist/native-compiler/workflow-business-step.js.map +1 -1
  57. package/dist/native-compiler/workflow-completion-deadline.d.ts +1 -0
  58. package/dist/native-compiler/workflow-completion-deadline.d.ts.map +1 -1
  59. package/dist/native-compiler/workflow-completion-deadline.js +1 -1
  60. package/dist/native-compiler/workflow-completion-deadline.js.map +1 -1
  61. package/dist/native-compiler/workflow-correction.d.ts +1 -0
  62. package/dist/native-compiler/workflow-correction.d.ts.map +1 -1
  63. package/dist/native-compiler/workflow-correction.js +5 -4
  64. package/dist/native-compiler/workflow-correction.js.map +1 -1
  65. package/dist/native-compiler/workflow-designer.d.ts +127 -0
  66. package/dist/native-compiler/workflow-designer.d.ts.map +1 -0
  67. package/dist/native-compiler/workflow-designer.js +397 -0
  68. package/dist/native-compiler/workflow-designer.js.map +1 -0
  69. package/dist/native-compiler/workflow-events.d.ts +8 -0
  70. package/dist/native-compiler/workflow-events.d.ts.map +1 -0
  71. package/dist/native-compiler/workflow-events.js +53 -0
  72. package/dist/native-compiler/workflow-events.js.map +1 -0
  73. package/dist/native-compiler/workflow-graph.d.ts +16 -1
  74. package/dist/native-compiler/workflow-graph.d.ts.map +1 -1
  75. package/dist/native-compiler/workflow-graph.js +27 -5
  76. package/dist/native-compiler/workflow-graph.js.map +1 -1
  77. package/dist/native-compiler/workflow-handle.d.ts +4 -0
  78. package/dist/native-compiler/workflow-handle.d.ts.map +1 -0
  79. package/dist/native-compiler/workflow-handle.js +20 -0
  80. package/dist/native-compiler/workflow-handle.js.map +1 -0
  81. package/dist/native-compiler/workflow-initiator-approval.d.ts +1 -0
  82. package/dist/native-compiler/workflow-initiator-approval.d.ts.map +1 -1
  83. package/dist/native-compiler/workflow-initiator-approval.js +1 -1
  84. package/dist/native-compiler/workflow-initiator-approval.js.map +1 -1
  85. package/dist/native-compiler/workflow-node-administration.d.ts +12 -1
  86. package/dist/native-compiler/workflow-node-administration.d.ts.map +1 -1
  87. package/dist/native-compiler/workflow-node-administration.js +66 -14
  88. package/dist/native-compiler/workflow-node-administration.js.map +1 -1
  89. package/dist/native-compiler/workflow-parallel.d.ts +69 -0
  90. package/dist/native-compiler/workflow-parallel.d.ts.map +1 -0
  91. package/dist/native-compiler/workflow-parallel.js +178 -0
  92. package/dist/native-compiler/workflow-parallel.js.map +1 -0
  93. package/dist/native-compiler/workflow-platform-notify.d.ts +41 -0
  94. package/dist/native-compiler/workflow-platform-notify.d.ts.map +1 -0
  95. package/dist/native-compiler/workflow-platform-notify.js +49 -0
  96. package/dist/native-compiler/workflow-platform-notify.js.map +1 -0
  97. package/dist/native-compiler/workflow-reminders.d.ts +11 -0
  98. package/dist/native-compiler/workflow-reminders.d.ts.map +1 -0
  99. package/dist/native-compiler/workflow-reminders.js +12 -0
  100. package/dist/native-compiler/workflow-reminders.js.map +1 -0
  101. package/dist/native-compiler/workflow-return-policy.d.ts +20 -0
  102. package/dist/native-compiler/workflow-return-policy.d.ts.map +1 -0
  103. package/dist/native-compiler/workflow-return-policy.js +37 -0
  104. package/dist/native-compiler/workflow-return-policy.js.map +1 -0
  105. package/dist/native-compiler/workflow-role-union.d.ts +5 -1
  106. package/dist/native-compiler/workflow-role-union.d.ts.map +1 -1
  107. package/dist/native-compiler/workflow-role-union.js +1 -1
  108. package/dist/native-compiler/workflow-role-union.js.map +1 -1
  109. package/dist/native-compiler/workflow-source-sync.d.ts +109 -0
  110. package/dist/native-compiler/workflow-source-sync.d.ts.map +1 -0
  111. package/dist/native-compiler/workflow-source-sync.js +120 -0
  112. package/dist/native-compiler/workflow-source-sync.js.map +1 -0
  113. package/dist/native-compiler/workflow-supervisor-chain.d.ts +16 -0
  114. package/dist/native-compiler/workflow-supervisor-chain.d.ts.map +1 -0
  115. package/dist/native-compiler/workflow-supervisor-chain.js +44 -0
  116. package/dist/native-compiler/workflow-supervisor-chain.js.map +1 -0
  117. package/dist/native-compiler/workflow-task-page.js +1 -1
  118. package/dist/native-compiler/workflow-task-page.js.map +1 -1
  119. package/dist/native-version.d.ts +7 -0
  120. package/dist/native-version.d.ts.map +1 -1
  121. package/dist/native-version.js +7 -0
  122. package/dist/native-version.js.map +1 -1
  123. package/dist/native.d.ts +12 -0
  124. package/dist/native.d.ts.map +1 -1
  125. package/dist/native.js.map +1 -1
  126. package/dist/references.d.ts +4 -0
  127. package/dist/references.d.ts.map +1 -1
  128. package/dist/schemas.d.ts +1266 -10
  129. package/dist/schemas.d.ts.map +1 -1
  130. package/dist/schemas.js +83 -8
  131. package/dist/schemas.js.map +1 -1
  132. package/dist/types.d.ts +54 -12
  133. package/dist/types.d.ts.map +1 -1
  134. package/dist/types.js +1 -40
  135. package/dist/types.js.map +1 -1
  136. package/package.json +1 -1
@@ -1,9 +1,9 @@
1
- import{createHash as Vs}from"node:crypto";function Ls(e){if(!e||typeof e!="object")return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function wn(e,t){if(e===null)return"null";if(typeof e=="string"||typeof e=="boolean")return JSON.stringify(e);if(typeof e=="number"){if(!Number.isFinite(e))throw new TypeError(`JSON number must be finite: ${t}`);return JSON.stringify(e)}if(Array.isArray(e))return`[${e.map((n,i)=>wn(n,`${t}[${i}]`)).join(",")}]`;if(Ls(e))return`{${Object.keys(e).filter(i=>e[i]!==void 0).sort((i,r)=>i===r?0:i<r?-1:1).map(i=>`${JSON.stringify(i)}:${wn(e[i],`${t}.${i}`)}`).join(",")}}`;let o=e instanceof Date?"Date":e?.constructor?.name||typeof e;throw new TypeError(`Value is not JSON serializable: ${t} (${o})`)}function X(e){return wn(e,"$")}function Z(e){return Vs("sha256").update(X(e)).digest("hex")}var jc=200,Fs=["text.short","uuid","option.single","resource-ref.single"],Sn=/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/,ei=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,ti=new Set(["__proto__","prototype","constructor"]),Dn=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&[Object.prototype,null].includes(Object.getPrototypeOf(e)),Qo=(e,t)=>Object.keys(e).every(o=>t.includes(o)),et=(e,t)=>typeof e=="string"&&e.length>0&&e.trim()===e&&e.length<=t,Me=class extends Error{constructor(o,n){super(`${o}: ${n}`);this.code=o;this.pointer=n}code;pointer};function ne(e,t){throw new Me(e,t)}function xt(e,t,o){if(e===void 0)return;["user.single","user.multiple"].includes(t)||ne("DATA_USER_CANDIDATES_FIELD_TYPE_INVALID",o),(!Dn(e)||!Qo(e,["kind","roleCode","scope","pageSize"])||e.kind!=="app-role"||!et(e.roleCode,128)||!Sn.test(String(e.roleCode)))&&ne("DATA_USER_CANDIDATES_SOURCE_INVALID",o),e.pageSize!==void 0&&(!Number.isSafeInteger(e.pageSize)||Number(e.pageSize)<1||Number(e.pageSize)>50)&&ne("DATA_USER_CANDIDATES_PAGE_SIZE_INVALID",`${o}/pageSize`);let n;if(e.scope!==void 0){let i=e.scope;(!Dn(i)||!Qo(i,["dimensionCode","operation","field","value","creation"])||!et(i.dimensionCode,128)||!Sn.test(String(i.dimensionCode))||!et(i.operation,64)||!Sn.test(String(i.operation))||Object.hasOwn(i,"field")===Object.hasOwn(i,"value"))&&ne("DATA_USER_CANDIDATES_SCOPE_INVALID",`${o}/scope`),i.creation!==void 0&&(i.creation!=="prospective"||!Object.hasOwn(i,"field"))&&ne("DATA_USER_CANDIDATES_SCOPE_INVALID",`${o}/scope/creation`),Object.hasOwn(i,"field")?((!et(i.field,63)||!ei.test(String(i.field))||ti.has(String(i.field)))&&ne("DATA_USER_CANDIDATES_SCOPE_FIELD_INVALID",`${o}/scope/field`),n={dimensionCode:String(i.dimensionCode),operation:String(i.operation),field:String(i.field),...i.creation==="prospective"?{creation:"prospective"}:{}}):(et(i.value,255)||ne("DATA_USER_CANDIDATES_SCOPE_VALUE_INVALID",`${o}/scope/value`),n={dimensionCode:String(i.dimensionCode),operation:String(i.operation),value:String(i.value)})}return{kind:"app-role",roleCode:String(e.roleCode),...n?{scope:n}:{},...e.pageSize===void 0?{}:{pageSize:Number(e.pageSize)}}}function kn(e){return e.some(t=>t.schema.fields.some(o=>{let n=o.userCandidates?.scope;return n?.creation==="prospective"||!!(n?.field&&t.schema.fields.find(i=>i.code===n.field)?.type==="resource-ref.single")}))}function ni(e,t,o,n){for(let[i,r]of e.entries()){let d=`${n}/${i}/userCandidates`,s=xt(r.userCandidates,r.type,d);if(s&&(t.has(s.roleCode)||ne("DATA_USER_CANDIDATES_ROLE_UNDECLARED",`${d}/roleCode`),s.scope&&!o.has(s.scope.dimensionCode)&&ne("DATA_USER_CANDIDATES_DIMENSION_UNDECLARED",`${d}/scope/dimensionCode`),s.scope?.field)){let a=e.find(c=>c.code===s.scope.field);(!a||!Fs.some(c=>c===a.type))&&ne("DATA_USER_CANDIDATES_SCOPE_FIELD_INVALID",`${d}/scope/field`)}}}function xs(e,t,o,n){let i=e.subject.factProjection,r=typeof t.inputPath=="string"&&Object.entries(i).some(([c,f])=>(t.inputPath===c||t.inputPath.startsWith(`${c}.`))&&o.get(f)?.userCandidates!==void 0);if(t.candidateField===void 0&&!r)return;(t.provider!=="form_field_users"||!t.candidateField||!ei.test(t.candidateField)||ti.has(t.candidateField)||!t.inputPath||i[t.inputPath]!==t.candidateField)&&ne("WORKFLOW_USER_CANDIDATES_FIELD_BINDING_REQUIRED",n),(t.roleCode!==void 0||t.scope!==void 0||t.routing!==void 0)&&ne("WORKFLOW_USER_CANDIDATES_SOURCE_OVERRIDE_FORBIDDEN",n);let d=o.get(t.candidateField),s=d&&xt(d.userCandidates,d.type,`${n}/candidateField`);s||ne("WORKFLOW_USER_CANDIDATES_FIELD_UNDECLARED",`${n}/candidateField`);let a;if(s.scope?.field){let c=Object.entries(i).filter(([,f])=>f===s.scope.field).map(([f])=>f);c.length!==1&&ne("WORKFLOW_USER_CANDIDATES_SCOPE_PROJECTION_REQUIRED",n),a=c[0]}return{fieldCode:d.code,inputPath:t.inputPath,source:s,...a?{scopeInputPath:a}:{}}}function oi(e,t,o,n,i=new Map){for(let[r,d]of Object.entries(t.bindings))xs(e,d,o,`${n}/${r}`);for(let[r,d]of Object.entries(e.taskPages||{})){let s=new Set(d.fields.filter(a=>a.readonly!==!0).map(a=>a.code));for(let a of d.fields){let c=o.get(a.code)?.userCandidates?.scope;if(s.has(a.code)&&c?.field&&s.has(c.field)&&ne("WORKFLOW_USER_CANDIDATES_SCOPE_WRITE_FORBIDDEN",`${n}/taskPages/${r}/${a.code}`),!s.has(a.code)||!a.subtable)continue;let f=o.get(a.code)?.subtable?.resourceCode,u=f?i.get(f):void 0;a.subtable.fields.some(p=>p.readonly!==!0&&u?.get(p.code)?.userCandidates)&&ne("WORKFLOW_USER_CANDIDATES_OWNED_FIELD_UNSUPPORTED",`${n}/taskPages/${r}/${a.code}`)}}}function Wc(e,t){if(!e.scope)return;let o=e.scope.field?t[e.scope.field]:e.scope.value,n=Dn(o)?o.value:o;return et(n,255)||ne("DATA_USER_CANDIDATES_SCOPE_VALUE_REQUIRED",e.scope.field||"scope"),String(n)}var ii=200,Pn=205;function vn(e,t=[]){return e.some(o=>o.schema.fields.length>100)||t.some(o=>Object.values(o.definition.taskPages||{}).some(n=>(n.fields?.length??0)>64)||[o.launch?.submission?.create,o.launch?.submission?.existing].some(n=>Object.keys(n?.inputs||{}).length>64))}var Be=500,$n=500,tt=1e3,ri=2*tt+16,Mc=2*1024*1024,Bc=2*1024*1024;function mt(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=1&&e<=tt}function jt(e){if(e.ownedRowLimit===void 0)return $n;if(!mt(e.ownedRowLimit))throw new Error("NATIVE_DATA_OWNED_ROW_LIMIT_INVALID");return e.ownedRowLimit}function Vn(e){return e.some(t=>(t.schema.ownedRowLimit??$n)>$n)}function Ln(e){return e.some(t=>{let o=t.schema.fields.filter(n=>n.type==="subtable").map(n=>n.subtable?.maxRows??20);return o.some(n=>n>100)||o.reduce((n,i)=>n+i,0)>400})}function Kc(e){try{return new TextEncoder().encode(JSON.stringify(e)).byteLength}catch{return 1/0}}var ci=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,jn=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,js=["text.short","text.long","text.rich","number.integer","number.decimal","boolean","date","time","datetime","date-range","datetime-range","option.single","option.multiple","cascade.single","cascade.multiple","user.single","user.multiple","department.single","department.multiple","resource-ref.single","resource-ref.multiple","image","signature","address","location","uuid","json","file","serial-number","subtable"];function Wn(e){return e.some(t=>t.schema.fields.some(o=>(o.type==="datetime"||o.type==="datetime-range")&&o.timePrecision==="minute"))}function Un(e){return e.some(t=>t.schema.fields.some(o=>o.type==="subtable"&&(o.subtable?.minRows??0)>0))}var Ws=new Set(js),li=new Set(["option.multiple","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","file","image","subtable"]),si=new Set(["option.single","option.multiple","cascade.single","cascade.multiple"]),ai=new Set(["resource-ref.single","resource-ref.multiple"]),Mn=[{code:"id",type:"uuid",nullable:!1},{code:"revision",type:"number.integer",nullable:!1},{code:"created_by",type:"text.short",nullable:!1},{code:"updated_by",type:"text.short",nullable:!1},{code:"created_at",type:"datetime",nullable:!1},{code:"updated_at",type:"datetime",nullable:!1}],nt=new Map(Mn.map(e=>[e.code,e])),Re=class extends Error{constructor(o,n){super(o);this.code=o;this.pointer=n;this.name="NativeDataFieldContractV2Error"}code;pointer};function Mt(e){return li.has(e)}function Bt(e,t={}){return e.type!=="serial-number"&&t.system!==!0&&e.nullable===!1&&(!Mt(e.type)||t.requiredHint===!0)}function Bn(e,t,o=500){Array.isArray(e)||k("NATIVE_ARRAY_REQUIRED",t),e.length===0&&k("NATIVE_DATA_FIELDS_REQUIRED",t),e.length>o&&k("NATIVE_ARRAY_LIMIT_EXCEEDED",t);let n=new Set;return e.map((i,r)=>{let d=`${t}/${r}`,s=Ee(i,d);ye(s,["code","type","nullable","indexed","options","source","userCandidates","maxLength","precision","scale","exactDecimal","min","max","rangeBoundary","timePrecision","file","serial","subtable"],d);let a=be(s.code,`${d}/code`,63);ci.test(a)||k("NATIVE_FIELD_CODE_INVALID",`${d}/code`),n.has(a)&&k("NATIVE_DATA_FIELD_DUPLICATE",`${d}/code`),n.add(a);let c=be(s.type,`${d}/type`,32);Ws.has(c)||k("NATIVE_DATA_FIELD_TYPE_INVALID",`${d}/type`);let f=c,u=xn(s.nullable,`${d}/nullable`),p=xn(s.indexed,`${d}/indexed`);u===!0&&li.has(f)&&k("NATIVE_DATA_MULTI_FIELD_NULLABLE_INVALID",`${d}/nullable`);let _=Bs(s.options,f,d),E=Ks(s.source,f,d),A=xt(s.userCandidates,f,`${d}/userCandidates`),O=qs(s,f,d),b=xn(s.exactDecimal,`${d}/exactDecimal`);b!==void 0&&f!=="number.decimal"&&k("NATIVE_DATA_FIELD_EXACT_DECIMAL_TYPE_INVALID",`${d}/exactDecimal`);let g=Us(s.rangeBoundary,f,d),I=zs(s.file,f,d),T=Js(s.serial,f,d),l=Hs(s.subtable,f,d);return{code:a,type:f,...u===void 0?{}:{nullable:u},...p===void 0?{}:{indexed:p},..._?{options:_}:{},...E?{source:E}:{},...A?{userCandidates:A}:{},...O,...b===void 0?{}:{exactDecimal:b},...g?{rangeBoundary:g}:{},...I?{file:I}:{},...T?{serial:T}:{},...l?{subtable:l}:{}}})}function Us(e,t,o){let n=`${o}/rangeBoundary`;if(!(t==="date-range"||t==="datetime-range")){e!==void 0&&k("NATIVE_DATA_FIELD_RANGE_BOUNDARY_TYPE_INVALID",n);return}return e!=="closed"&&e!=="half-open"&&k("NATIVE_DATA_FIELD_RANGE_BOUNDARY_REQUIRED",n),e}function ui(e,t){Array.isArray(e)||k("NATIVE_ARRAY_REQUIRED",t);let o=new Map;e.forEach((n,i)=>{let r=`${t}/${i}`,d=Ee(n,r),s=be(d.code,`${r}/code`,64);(!jn.test(s)||o.has(s))&&k("NATIVE_RESOURCE_CODE_INVALID",`${r}/code`);let a=Ee(d.schema,`${r}/schema`);a.ownedRowLimit!==void 0&&!mt(a.ownedRowLimit)&&k("NATIVE_DATA_OWNED_ROW_LIMIT_INVALID",`${r}/schema/ownedRowLimit`),o.set(s,{pointer:r,ownedRowLimit:jt(a),fields:Bn(a.fields,`${r}/schema/fields`)})});for(let[n,i]of o){let r=new Map(i.fields.map(s=>[s.code,s]));i.fields.filter(s=>s.type==="subtable").reduce((s,a)=>s+(a.subtable?.maxRows??20),0)>i.ownedRowLimit&&k("NATIVE_DATA_FIELD_SUBTABLE_AGGREGATE_MAX_ROWS_EXCEEDED",`${i.pointer}/schema/fields`),i.fields.forEach((s,a)=>{let c=`${i.pointer}/schema/fields/${a}`;if(s.source&&Ms(s.source,r,o,`${c}/source`),s.subtable){let f=o.get(s.subtable.resourceCode);(!f||s.subtable.resourceCode===n)&&k("NATIVE_DATA_FIELD_SUBTABLE_TARGET_MISSING",`${c}/subtable/resourceCode`);let u=f.fields.find(_=>_.code===s.subtable?.foreignKey);(!u||u.type!=="uuid"||u.nullable!==!1)&&k("NATIVE_DATA_FIELD_SUBTABLE_FOREIGN_KEY_INVALID",`${c}/subtable/foreignKey`);let p=f.fields.find(_=>_.code===s.subtable?.orderField);(!p||p.type!=="number.integer"||p.nullable!==!1)&&k("NATIVE_DATA_FIELD_SUBTABLE_ORDER_FIELD_INVALID",`${c}/subtable/orderField`)}})}}function fi(e,t,o){if(e===void 0)return[];(!Array.isArray(e)||e.length>20)&&k("NATIVE_DATA_RESOURCE_INVARIANTS_INVALID",o);let n=new Map(t.map(r=>[r.code,r])),i=new Set;return e.map((r,d)=>{let s=`${o}/${d}`,a=Ee(r,s);ye(a,["code","message","expression"],s);let c=be(a.code,`${s}/code`,128);(!/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/.test(c)||i.has(c))&&k("NATIVE_DATA_RESOURCE_INVARIANT_CODE_INVALID",`${s}/code`),i.add(c);let f=Ut(a.message,`${s}/message`,500);f!==void 0&&f.length===0&&k("NATIVE_DATA_RESOURCE_INVARIANT_MESSAGE_INVALID",`${s}/message`);let u=Ee(a.expression,`${s}/expression`);if(u.kind==="nonBlankTextWhenOption"){ye(u,["kind","optionField","optionValue","textField"],`${s}/expression`);let g=Te(u.optionField,`${s}/expression/optionField`),I=Te(u.textField,`${s}/expression/textField`),T=be(u.optionValue,`${s}/expression/optionValue`,128),l=n.get(g),y=n.get(I);return(!l||!y)&&k("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_UNKNOWN",`${s}/expression`),(l.type!=="option.single"||!["text.short","text.long"].includes(y.type)||!l.options?.some(R=>R.value===T))&&k("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_TYPES_INVALID",`${s}/expression`),{code:c,...f===void 0?{}:{message:f},expression:{kind:"nonBlankTextWhenOption",optionField:g,optionValue:T,textField:I}}}ye(u,["leftField","operator","rightField"],`${s}/expression`);let p=Te(u.leftField,`${s}/expression/leftField`),_=Te(u.rightField,`${s}/expression/rightField`),E=n.get(p),A=n.get(_);(!E||!A)&&k("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_UNKNOWN",`${s}/expression`),E.type===A.type||["number.integer","number.decimal"].includes(E.type)&&["number.integer","number.decimal"].includes(A.type)||k("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_TYPES_INVALID",`${s}/expression`);let b=String(u.operator);return["eq","neq","gt","gte","lt","lte"].includes(b)||k("NATIVE_DATA_RESOURCE_INVARIANT_OPERATOR_INVALID",`${s}/expression/operator`),!["eq","neq"].includes(b)&&!["number.integer","number.decimal","date","time","datetime","text.short","text.long","text.rich","serial-number","uuid"].includes(E.type)&&k("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_TYPES_INVALID",`${s}/expression`),{code:c,...f===void 0?{}:{message:f},expression:{leftField:p,operator:b,rightField:_}}})}function Ms(e,t,o,n){let i=o.get(e.resourceCode);i||k("NATIVE_DATA_FIELD_SOURCE_TARGET_MISSING",`${n}/resourceCode`);let r=new Map(i.fields.map(s=>[s.code,s])),d=r.get(e.labelField);(!d||!["text.short","text.long"].includes(d.type))&&k("NATIVE_DATA_FIELD_SOURCE_LABEL_INVALID",`${n}/labelField`);for(let s of["searchFields","descriptionFields","snapshotFields"])for(let a of e[s]||[])r.has(a)||k("NATIVE_DATA_FIELD_SOURCE_FIELD_MISSING",`${n}/${s}`);for(let[s,a]of(e.filters||[]).entries())r.has(a.field)||k("NATIVE_DATA_FIELD_SOURCE_FILTER_FIELD_MISSING",`${n}/filters/${s}/field`),"binding"in a&&!t.has(a.binding.field)&&k("NATIVE_DATA_FIELD_SOURCE_BINDING_FIELD_MISSING",`${n}/filters/${s}/binding/field`)}function Bs(e,t,o){let n=`${o}/options`;if(e===void 0){si.has(t)&&k("NATIVE_DATA_FIELD_OPTIONS_REQUIRED",n);return}(!si.has(t)||!Array.isArray(e))&&k("NATIVE_DATA_FIELD_OPTIONS_TYPE_INVALID",n),(e.length<1||e.length>100)&&k("NATIVE_DATA_FIELD_OPTIONS_INVALID",n);let i=0,r=(d,s,a)=>{a>5&&k("NATIVE_DATA_FIELD_OPTIONS_DEPTH_EXCEEDED",s);let c=new Set;return d.map((f,u)=>{i+=1,i>1e3&&k("NATIVE_DATA_FIELD_OPTIONS_COUNT_EXCEEDED",n);let p=`${s}/${u}`,_=Ee(f,p);ye(_,["label","value","description","color","children"],p);let E=be(_.label,`${p}/label`,500),A=be(_.value,`${p}/value`,500);c.has(A)&&k("NATIVE_DATA_FIELD_OPTION_VALUE_DUPLICATE",`${p}/value`),c.add(A);let O=Ut(_.description,`${p}/description`,2e3),b=Ut(_.color,`${p}/color`,64),g;return _.children!==void 0&&((!t.startsWith("cascade.")||!Array.isArray(_.children))&&k("NATIVE_DATA_FIELD_OPTION_CHILDREN_INVALID",`${p}/children`),(_.children.length<1||_.children.length>100)&&k("NATIVE_DATA_FIELD_OPTION_CHILDREN_INVALID",`${p}/children`),g=r(_.children,`${p}/children`,a+1)),{label:E,value:A,...O===void 0?{}:{description:O},...b===void 0?{}:{color:b},...g?{children:g}:{}}})};return r(e,n,1)}function Ks(e,t,o){let n=`${o}/source`;if(e===void 0){ai.has(t)&&k("NATIVE_DATA_FIELD_SOURCE_REQUIRED",n);return}ai.has(t)||k("NATIVE_DATA_FIELD_SOURCE_TYPE_INVALID",n);let i=Ee(e,n);ye(i,["kind","resourceCode","labelField","searchFields","descriptionFields","snapshotFields","filters","pageSize","loadMode","clearOnBindingChange"],n),i.kind!=="resource"&&k("NATIVE_DATA_FIELD_SOURCE_KIND_INVALID",`${n}/kind`);let r=be(i.resourceCode,`${n}/resourceCode`,64);jn.test(r)||k("NATIVE_RESOURCE_CODE_INVALID",`${n}/resourceCode`);let d=Te(i.labelField,`${n}/labelField`),s=Fn(i.searchFields,`${n}/searchFields`,10),a=Fn(i.descriptionFields,`${n}/descriptionFields`,10),c=Fn(i.snapshotFields,`${n}/snapshotFields`,50),f=Ke(i.pageSize,`${n}/pageSize`,1,100),u;i.loadMode!==void 0&&(["search","all"].includes(String(i.loadMode))||k("NATIVE_DATA_FIELD_SOURCE_LOAD_MODE_INVALID",`${n}/loadMode`),u=i.loadMode);let p=Gs(i.filters,`${n}/filters`);return i.clearOnBindingChange!==void 0&&typeof i.clearOnBindingChange!="boolean"&&k("NATIVE_DATA_FIELD_SOURCE_BINDING_RESET_INVALID",`${n}/clearOnBindingChange`),{kind:"resource",resourceCode:r,labelField:d,...s?{searchFields:s}:{},...a?{descriptionFields:a}:{},...c?{snapshotFields:c}:{},...p?{filters:p}:{},...f===void 0?{}:{pageSize:f},...u?{loadMode:u}:{},...i.clearOnBindingChange===void 0?{}:{clearOnBindingChange:i.clearOnBindingChange}}}function Gs(e,t){if(e!==void 0)return(!Array.isArray(e)||e.length>20)&&k("NATIVE_DATA_FIELD_SOURCE_FILTERS_INVALID",t),e.map((o,n)=>{let i=`${t}/${n}`,r=Ee(o,i),d=Object.prototype.hasOwnProperty.call(r,"value"),s=Object.prototype.hasOwnProperty.call(r,"binding");ye(r,d?["field","operator","value"]:["field","operator","binding"],i),d===s&&k("NATIVE_DATA_FIELD_SOURCE_FILTER_VALUE_INVALID",i);let a=Te(r.field,`${i}/field`);["eq","in"].includes(String(r.operator))||k("NATIVE_DATA_FIELD_SOURCE_FILTER_OPERATOR_INVALID",`${i}/operator`);let c=r.operator;if(d)return{field:a,operator:c,value:r.value};let f=Ee(r.binding,`${i}/binding`);return ye(f,["kind","field"],`${i}/binding`),f.kind!=="field"&&k("NATIVE_DATA_FIELD_SOURCE_BINDING_KIND_INVALID",`${i}/binding/kind`),{field:a,operator:c,binding:{kind:"field",field:Te(f.field,`${i}/binding/field`)}}})}function qs(e,t,o){let n={};if(e.maxLength!==void 0&&(["text.short","text.long","text.rich"].includes(t)||k("NATIVE_DATA_FIELD_MAX_LENGTH_TYPE_INVALID",`${o}/maxLength`),n.maxLength=Wt(e.maxLength,`${o}/maxLength`,1,1e6)),(e.precision!==void 0||e.scale!==void 0)&&((t!=="number.decimal"||e.precision===void 0)&&k("NATIVE_DATA_FIELD_DECIMAL_CONFIG_INVALID",o),n.precision=Wt(e.precision,`${o}/precision`,1,1e3),n.scale=e.scale===void 0?0:Wt(e.scale,`${o}/scale`,0,n.precision)),e.min!==void 0||e.max!==void 0){["number.integer","number.decimal"].includes(t)||k("NATIVE_DATA_FIELD_NUMERIC_BOUNDS_TYPE_INVALID",o);let i=di(e.min,`${o}/min`),r=di(e.max,`${o}/max`);t==="number.integer"&&[i,r].some(d=>d!==void 0&&!Number.isSafeInteger(d))&&k("NATIVE_DATA_FIELD_NUMERIC_BOUNDS_INVALID",o),i!==void 0&&r!==void 0&&i>r&&k("NATIVE_DATA_FIELD_NUMERIC_BOUNDS_INVALID",o),i!==void 0&&(n.min=i),r!==void 0&&(n.max=r)}return e.timePrecision!==void 0&&((!["time","datetime","datetime-range"].includes(t)||!["minute","second"].includes(e.timePrecision))&&k("NATIVE_DATA_FIELD_TIME_PRECISION_INVALID",`${o}/timePrecision`),n.timePrecision=e.timePrecision),n}function zs(e,t,o){if(e===void 0)return;let n=`${o}/file`;["file","image","signature"].includes(t)||k("NATIVE_DATA_FIELD_FILE_TYPE_INVALID",n);let i=Ee(e,n);ye(i,["maxCount","maxSizeMb","accept"],n);let r=Ke(i.maxCount,`${n}/maxCount`,1,100);t==="signature"&&r!==void 0&&r!==1&&k("NATIVE_DATA_FIELD_SIGNATURE_COUNT_INVALID",`${n}/maxCount`);let d=Ke(i.maxSizeMb,`${n}/maxSizeMb`,1,1024),s;return i.accept!==void 0&&((!Array.isArray(i.accept)||i.accept.length>50)&&k("NATIVE_DATA_FIELD_FILE_ACCEPT_INVALID",`${n}/accept`),s=i.accept.map((a,c)=>be(a,`${n}/accept/${c}`,255)),new Set(s).size!==s.length&&k("NATIVE_DATA_FIELD_FILE_ACCEPT_INVALID",`${n}/accept`)),{...r===void 0?{}:{maxCount:r},...d===void 0?{}:{maxSizeMb:d},...s===void 0?{}:{accept:s}}}function Js(e,t,o){let n=`${o}/serial`;if(e===void 0){t==="serial-number"&&k("NATIVE_DATA_FIELD_SERIAL_REQUIRED",n);return}t!=="serial-number"&&k("NATIVE_DATA_FIELD_SERIAL_TYPE_INVALID",n);let i=Ee(e,n);ye(i,["prefix","digits","start"],n);let r=Ut(i.prefix,`${n}/prefix`,64),d=Ke(i.digits,`${n}/digits`,1,32),s=Ke(i.start,`${n}/start`,0,Number.MAX_SAFE_INTEGER);return{...r===void 0?{}:{prefix:r},...d===void 0?{}:{digits:d},...s===void 0?{}:{start:s}}}function Hs(e,t,o){let n=`${o}/subtable`;if(e===void 0){t==="subtable"&&k("NATIVE_DATA_FIELD_SUBTABLE_REQUIRED",n);return}t!=="subtable"&&k("NATIVE_DATA_FIELD_SUBTABLE_TYPE_INVALID",n);let i=Ee(e,n);ye(i,["resourceCode","foreignKey","orderField","minRows","maxRows"],n);let r=be(i.resourceCode,`${n}/resourceCode`,64);jn.test(r)||k("NATIVE_RESOURCE_CODE_INVALID",`${n}/resourceCode`);let d=Te(i.foreignKey,`${n}/foreignKey`),s=Te(i.orderField,`${n}/orderField`);s===d&&k("NATIVE_DATA_FIELD_SUBTABLE_ORDER_FIELD_INVALID",`${n}/orderField`);let a=Ke(i.maxRows,`${n}/maxRows`,1,Be),c=Ke(i.minRows,`${n}/minRows`,0,Be);return(c??0)>(a??20)&&k("NATIVE_DATA_FIELD_SUBTABLE_MIN_ROWS_INVALID",`${n}/minRows`),{resourceCode:r,foreignKey:d,orderField:s,...c===void 0?{}:{minRows:c},...a===void 0?{}:{maxRows:a}}}function Fn(e,t,o){if(e===void 0)return;(!Array.isArray(e)||e.length>o)&&k("NATIVE_DATA_FIELD_SOURCE_FIELDS_INVALID",t);let n=e.map((i,r)=>Te(i,`${t}/${r}`));return new Set(n).size!==n.length&&k("NATIVE_DATA_FIELD_SOURCE_FIELDS_INVALID",t),n}function Te(e,t){let o=be(e,t,63);return ci.test(o)||k("NATIVE_FIELD_CODE_INVALID",t),o}function Ee(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&k("NATIVE_OBJECT_REQUIRED",t),e}function ye(e,t,o){let n=new Set(t);for(let i of Object.keys(e))n.has(i)||k("NATIVE_PROPERTY_UNKNOWN",`${o}/${i}`)}function be(e,t,o){return(typeof e!="string"||e.length===0||e.length>o)&&k("NATIVE_STRING_INVALID",t),e}function Ut(e,t,o){if(e!==void 0)return(typeof e!="string"||e.length>o)&&k("NATIVE_STRING_INVALID",t),e}function xn(e,t){if(e!==void 0)return typeof e!="boolean"&&k("NATIVE_BOOLEAN_REQUIRED",t),e}function Ke(e,t,o,n){if(e!==void 0)return Wt(e,t,o,n)}function di(e,t){if(e!==void 0)return(typeof e!="number"||!Number.isFinite(e))&&k("NATIVE_NUMBER_REQUIRED",t),e}function Wt(e,t,o,n){return(!Number.isSafeInteger(e)||Number(e)<o||Number(e)>n)&&k("NATIVE_INTEGER_OUT_OF_RANGE",t),Number(e)}function k(e,t){throw new Re(e,t)}var Kt=["created_by","updated_by","created_at","updated_at"];function _t(e){return Kt.includes(e)}function pi(e){return Kt.some(t=>Object.prototype.hasOwnProperty.call(e.fieldPolicies||{},t))}var Ys=Mn.map(e=>e.code);function mi(e){return Ys.includes(e)}var Xs=["eq","neq","gt","gte","lt","lte","contains","startsWith","endsWith","in","between","has","hasAny","hasAll","overlaps","containedBy","jsonContains","isEmpty","isNotEmpty"],Zs=new Set(Xs);function Xc(e){return Zs.has(String(e))}var Kn=["eq","neq","contains","startsWith","endsWith","in","isEmpty","isNotEmpty"],gt=["eq","neq","gt","gte","lt","lte","between","in","isEmpty"],Qs=["eq","neq","in","isEmpty"],Gt=["eq","neq","in","isEmpty","isNotEmpty"],ot=["has","hasAny","hasAll","isEmpty","isNotEmpty"],_i=["overlaps","contains","containedBy","isEmpty"],Gn=["jsonContains","isEmpty","isNotEmpty"],qn=["isEmpty","isNotEmpty"],ea={"text.short":Kn,"text.long":Kn,"text.rich":Kn,"number.integer":gt,"number.decimal":gt,boolean:Qs,date:gt,time:gt,datetime:gt,"date-range":_i,"datetime-range":_i,"option.single":Gt,"option.multiple":ot,"cascade.single":ot,"cascade.multiple":ot,"user.single":Gt,"user.multiple":ot,"department.single":Gt,"department.multiple":ot,"resource-ref.single":Gt,"resource-ref.multiple":ot,file:qn,image:qn,signature:qn,address:Gn,location:Gn,uuid:["eq","neq","in","isEmpty"],json:Gn,"serial-number":["eq","neq","in","contains","startsWith"],subtable:[]},ta=new Set(["text.short","text.long","text.rich","option.single","user.single","department.single","resource-ref.single","serial-number"]),na=new Set(["option.multiple","cascade.single","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","file","image","signature","address","location","json","subtable"]);function Ai(e){return ea[e]}function Zc(e,t){return Ai(e).includes(t)}function zn(e){return ta.has(e)}function At(e){return!na.has(e)}function Ei(e){return Ai(e).length>0}var gi=new Set(["number.integer","number.decimal"]),Ii=new Set(["text.short","text.long","number.integer","number.decimal","date","time","datetime","serial-number"]),oa=new Set([...Ii,"boolean","uuid"]),ia=new Set(["option.single","user.single","department.single","resource-ref.single"]);function Qc(e,t){return t==="sum"||t==="avg"?gi.has(e)?{valueExpression:"column",numericResult:!0}:null:t==="min"||t==="max"?Ii.has(e)?{valueExpression:"column",numericResult:gi.has(e)}:null:ia.has(e)?{valueExpression:"snapshot-value",numericResult:!0}:oa.has(e)?{valueExpression:"column",numericResult:!0}:null}var Hn=["version","maxBytes","fields"];function bi(e,t){if(e===void 0)return;let o=Jn(e,t);yi(o,Hn,t);let n=qt(o.version,`${t}/version`,1,1e6),i=qt(o.maxBytes,`${t}/maxBytes`,2,196608);(!n||!i)&&ce("NATIVE_DATA_DRAFT_STATE_SCHEMA_INVALID",t);let r=Jn(o.fields,`${t}/fields`),d=Object.entries(r);(!d.length||d.length>50)&&ce("NATIVE_DATA_DRAFT_STATE_FIELDS_INVALID",`${t}/fields`);for(let[s,a]of d){let c=`${t}/fields/${s}`;/^[A-Za-z][A-Za-z0-9_]{0,62}$/.test(s)||ce("NATIVE_DATA_DRAFT_STATE_FIELD_CODE_INVALID",c);let f=Jn(a,c),u=Oi(f.type,`${c}/type`,32),p=u==="string"?["type","required","maxLength","enum"]:u==="json.object"?["type","required","maxBytes"]:["type","required"];if(["string","number","integer","boolean","json.object"].includes(u)||ce("NATIVE_DATA_DRAFT_STATE_FIELD_TYPE_INVALID",`${c}/type`),yi(f,p,c),sa(f.required,`${c}/required`),u==="string"){let _=qt(f.maxLength,`${c}/maxLength`,1,196608);_||ce("NATIVE_DATA_DRAFT_STATE_FIELD_INVALID",c),f.enum!==void 0&&ra(f.enum,`${c}/enum`,100,!1).some(A=>A.length>_)&&ce("NATIVE_DATA_DRAFT_STATE_FIELD_INVALID",`${c}/enum`)}else if(u==="json.object"){let _=qt(f.maxBytes,`${c}/maxBytes`,2,65536);(!_||_>i)&&ce("NATIVE_DATA_DRAFT_STATE_FIELD_INVALID",c)}}}function ra(e,t,o,n){(!Array.isArray(e)||!n&&e.length===0||e.length>o)&&ce("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t);let i=e.map((r,d)=>Oi(r,`${t}/${d}`,255));return new Set(i).size!==i.length&&ce("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t),i}function Jn(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&ce("NATIVE_OBJECT_REQUIRED",t),e}function yi(e,t,o){let n=new Set(t);for(let i of Object.keys(e))n.has(i)||ce("NATIVE_PROPERTY_UNKNOWN",`${o}/${i}`)}function Oi(e,t,o){return(typeof e!="string"||e.length===0||e.length>o)&&ce("NATIVE_STRING_INVALID",t),e}function sa(e,t){e!==void 0&&typeof e!="boolean"&&ce("NATIVE_BOOLEAN_REQUIRED",t)}function qt(e,t,o,n){return(!Number.isSafeInteger(e)||Number(e)<o||Number(e)>n)&&ce("NATIVE_INTEGER_INVALID",t),Number(e)}function ce(e,t){throw new Re(e,t)}var aa=500,Pe={surface:["mutationOwner","generated","fields","list","form","detail","mobile","views"],generated:["list","detail","create","update","delete"],field:["label","type","widget","section","requiredHint","system","hidden","readCapabilities","createCapabilities","updateCapabilities","maxLength","precision","scale","exactDecimal","min","max","rangeBoundary","maxCount","maxSizeMb","accept","options","list","searchable","sortable","source","userCandidates","timePrecision","serial","subtable"],list:["actions","fieldOrder","defaultPageSize","searchableFields","filterFields","defaultSort"],defaultSort:["field","order"],form:["layout","fieldOrder","draftState"],detail:["layout","fieldOrder"],layout:["layout","fieldOrder","draftState"],draftState:Hn,mobile:["enabled"]},da={"text.short":["text","email","phone"],"text.long":["textarea"],"text.rich":["rich-text"],"number.integer":["number","rating"],"number.decimal":["number","money","percent"],boolean:["switch"],date:["date"],time:["time"],datetime:["datetime"],"date-range":["date-range"],"datetime-range":["datetime-range"],"option.single":["select","radio"],"option.multiple":["multi-select","checkbox"],"cascade.single":["cascade"],"cascade.multiple":["cascade"],"user.single":["directory-user"],"user.multiple":["directory-user"],"department.single":["directory-department","scope"],"department.multiple":["directory-department","scope"],"resource-ref.single":["select","radio","resource"],"resource-ref.multiple":["multi-select","checkbox","resource"],file:["attachment"],image:["image"],signature:["signature"],address:["address"],location:["location"],uuid:["readonly"],json:["json"],"serial-number":["readonly"],subtable:["subtable"]};function Zn(e,t,o){if(e===void 0)return;let n=ae(e,o);Ce(n,Pe.surface,o);let i=n.mutationOwner===void 0?"native":De(n.mutationOwner,`${o}/mutationOwner`,16);["native","action","readonly","workflow","queued-command"].includes(i)||W("NATIVE_DATA_SURFACE_MUTATION_OWNER_INVALID",`${o}/mutationOwner`);let r=n.generated===void 0?{}:ae(n.generated,`${o}/generated`);Ce(r,Pe.generated,`${o}/generated`);for(let a of Pe.generated)Xn(r[a],`${o}/generated/${a}`);if(i!=="native")for(let a of["create","update","delete"])r[a]===!0&&W("NATIVE_DATA_SURFACE_MUTATION_OWNER_CONFLICT",`${o}/generated/${a}`);let d=new Map(t.map(a=>[a.code,a])),s=ae(n.fields,`${o}/fields`);for(let a of Object.keys(s))d.has(a)||W("NATIVE_DATA_SURFACE_FIELD_MISSING",`${o}/fields/${a}`);for(let a of t)Object.prototype.hasOwnProperty.call(s,a.code)||W("NATIVE_DATA_SURFACE_FIELD_REQUIRED",`${o}/fields/${a.code}`),la(s[a.code],a,`${o}/fields/${a.code}`);for(let a of["create","update"]){let c=r[a]??i==="native",f=t.some(u=>{let p=ae(s[u.code],`${o}/fields/${u.code}`);return Ti(u,p,a)});c&&!f&&W("NATIVE_DATA_SURFACE_WRITABLE_FIELDS_REQUIRED",`${o}/generated/${a}`)}if(ua(n.list,d,`${o}/list`),Ni(n.form,d,`${o}/form`,"form"),Ni(n.detail,d,`${o}/detail`,"detail"),n.mobile!==void 0){let a=ae(n.mobile,`${o}/mobile`);Ce(a,Pe.mobile,`${o}/mobile`),Xn(a.enabled,`${o}/mobile/enabled`)}ca(n,t,o)}function Qn(e,t){let o=e.views?.find(i=>i.code===t);o||W("NATIVE_DATA_VIEW_NOT_FOUND",`/surface/views/${t}`);let n=new Map((o.sections||[]).flatMap(i=>i.fields.map(r=>[r,i.title])));return{mutationOwner:e.mutationOwner||"native",generated:o.generated,list:o.list,form:o.form,detail:o.detail,mobile:o.mobile,fields:Object.fromEntries(Object.entries(e.fields).map(([i,r])=>{let d={...r};delete d.section;let s=n.get(i);return[i,{...d,...s?{section:s}:{},list:o.list.fieldOrder.includes(i)}]}))}}function ca(e,t,o){if(e.views===void 0)return;(!Array.isArray(e.views)||e.views.length>20)&&W("NATIVE_DATA_VIEWS_LIMIT_INVALID",`${o}/views`);let n=new Set;e.views.forEach((i,r)=>{let d=`${o}/views/${r}`,s=ae(i,d);Ce(s,["code","name","generated","list","form","detail","mobile","sections"],d);let a=De(s.code,`${d}/code`,64);(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(a)||n.has(a))&&W("NATIVE_DATA_VIEW_CODE_INVALID",`${d}/code`),n.add(a),De(s.name,`${d}/name`,255),ae(s.generated,`${d}/generated`),ae(s.mobile,`${d}/mobile`);for(let f of["list","detail","create","update","delete"])typeof s.generated[f]!="boolean"&&W("NATIVE_DATA_VIEW_OPERATION_INVALID",`${d}/generated/${f}`);typeof s.mobile.enabled!="boolean"&&W("NATIVE_DATA_VIEW_MOBILE_INVALID",`${d}/mobile/enabled`);for(let f of["list","form","detail"]){let u=ae(s[f],`${d}/${f}`),p=it(u.fieldOrder,`${d}/${f}/fieldOrder`,500,!0);for(let _ of p){let E=e.fields[_];(!E||(E.hidden??E.system)===!0)&&W("NATIVE_DATA_VIEW_FIELD_INVALID",`${d}/${f}/fieldOrder`)}}if(s.sections!==void 0){(!Array.isArray(s.sections)||s.sections.length>100)&&W("NATIVE_DATA_VIEW_SECTIONS_INVALID",`${d}/sections`);let f=new Set;s.sections.forEach((u,p)=>{let _=`${d}/sections/${p}`,E=ae(u,_);Ce(E,["title","fields"],_),De(E.title,`${_}/title`,255);for(let A of it(E.fields,`${_}/fields`,100,!0)){let O=e.fields[A];(!O||(O.hidden??O.system)===!0||f.has(A))&&W("NATIVE_DATA_VIEW_FIELD_INVALID",`${_}/fields`),f.add(A)}})}let c=Qn(e,a);if(Zn(c,t,d),s.generated.create!==!1&&(e.mutationOwner||"native")==="native")for(let f of t)Bt(f,e.fields[f.code])&&Ti(f,e.fields[f.code],"create")&&!s.form.fieldOrder.includes(f.code)&&W("NATIVE_DATA_VIEW_CREATE_REQUIRED_FIELD_MISSING",`${d}/form/fieldOrder`)})}function Ti(e,t,o){if(e.type==="serial-number"||t.system===!0)return!1;let n=t[`${o}Capabilities`];return Array.isArray(n)&&n.length>0}function la(e,t,o){let n=ae(e,o);Ce(n,Pe.field,o),De(n.label,`${o}/label`,500),n.type!==t.type&&W("NATIVE_DATA_SURFACE_FIELD_TYPE_MISMATCH",`${o}/type`);let i=De(n.widget,`${o}/widget`,64);da[t.type].includes(i)||W("NATIVE_DATA_SURFACE_WIDGET_INCOMPATIBLE",`${o}/widget`),ma(n.section,`${o}/section`,255);for(let r of["requiredHint","system","hidden","list","searchable","sortable"])Xn(n[r],`${o}/${r}`);n.searchable===!0&&!zn(t.type)&&W("NATIVE_DATA_SURFACE_SEARCH_UNSUPPORTED",`${o}/searchable`),n.sortable===!0&&!At(t.type)&&W("NATIVE_DATA_SURFACE_SORT_UNSUPPORTED",`${o}/sortable`);for(let r of["readCapabilities","createCapabilities","updateCapabilities"])it(n[r],`${o}/${r}`,100,!0);if(n.maxCount!==void 0&&(!Number.isSafeInteger(n.maxCount)||Number(n.maxCount)<1||Number(n.maxCount)>100)&&W("NATIVE_DATA_SURFACE_MAX_COUNT_INVALID",`${o}/maxCount`),n.maxSizeMb!==void 0&&(!Number.isSafeInteger(n.maxSizeMb)||Number(n.maxSizeMb)<1||Number(n.maxSizeMb)>1024)&&W("NATIVE_DATA_SURFACE_MAX_SIZE_INVALID",`${o}/maxSizeMb`),n.accept!==void 0){let r=Array.isArray(n.accept)?n.accept:[n.accept];it(r,`${o}/accept`,50,!1)}for(let r of["maxLength","precision","scale","exactDecimal","min","max","rangeBoundary","options","source","userCandidates","timePrecision","serial","subtable"])fa(n,t,r,o);pa(n,t,o)}function ua(e,t,o){if(e===void 0)return;let n=ae(e,o);if(Ce(n,Pe.list,o),n.actions!==void 0){let i=ae(n.actions,`${o}/actions`);Ce(i,["import","export"],`${o}/actions`);for(let r of["import","export"])i[r]!==void 0&&typeof i[r]!="boolean"&&W("NATIVE_DATA_SURFACE_LIST_ACTION_INVALID",`${o}/actions/${r}`)}if(n.fieldOrder!==void 0)for(let i of it(n.fieldOrder,`${o}/fieldOrder`,500,!0))t.has(i)||W("NATIVE_DATA_SURFACE_LIST_FIELD_INVALID",`${o}/fieldOrder`);n.defaultPageSize!==void 0&&(!Number.isSafeInteger(n.defaultPageSize)||Number(n.defaultPageSize)<1||Number(n.defaultPageSize)>200)&&W("NATIVE_DATA_SURFACE_PAGE_SIZE_INVALID",`${o}/defaultPageSize`);for(let[i,r]of[["searchableFields",zn],["filterFields",Ei]]){if(n[i]===void 0)continue;let d=it(n[i],`${o}/${i}`,100,!0);for(let s of d){let a=t.get(s);(!a||!r(a.type))&&W("NATIVE_DATA_SURFACE_LIST_FIELD_INVALID",`${o}/${i}`)}}if(n.defaultSort!==void 0){let i=ae(n.defaultSort,`${o}/defaultSort`);Ce(i,Pe.defaultSort,`${o}/defaultSort`);let r=De(i.field,`${o}/defaultSort/field`,63),d=t.get(r);!mi(r)&&(!d||!At(d.type))&&W("NATIVE_DATA_SURFACE_SORT_UNSUPPORTED",`${o}/defaultSort/field`),i.order!==void 0&&!["asc","desc"].includes(i.order)&&W("NATIVE_DATA_SURFACE_SORT_ORDER_INVALID",`${o}/defaultSort/order`)}}function Ni(e,t,o,n){if(e===void 0)return;let i=ae(e,o);if(Ce(i,Pe[n],o),i.layout!==void 0&&!["flat","sections"].includes(i.layout)&&W("NATIVE_DATA_SURFACE_LAYOUT_INVALID",`${o}/layout`),i.fieldOrder!==void 0){let r=`${o}/fieldOrder`;(!Array.isArray(i.fieldOrder)||i.fieldOrder.length>t.size||i.fieldOrder.length>aa)&&W("NATIVE_DATA_SURFACE_FIELD_ORDER_INVALID",r);let d=i.fieldOrder.map((s,a)=>De(s,`${r}/${a}`,63));new Set(d).size!==d.length&&W("NATIVE_DATA_SURFACE_FIELD_ORDER_INVALID",r),d.forEach((s,a)=>{t.has(s)||W("NATIVE_DATA_SURFACE_FIELD_ORDER_FIELD_MISSING",`${r}/${a}`)})}n==="form"&&bi(i.draftState,`${o}/draftState`)}function fa(e,t,o,n){e[o]===void 0&&t[o]===void 0||((e[o]===void 0||t[o]===void 0)&&W("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${n}/${o}`),X(e[o])!==X(t[o])&&W("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${n}/${o}`))}function pa(e,t,o){let n=t.file||{},i={...e.maxCount===void 0?{}:{maxCount:e.maxCount},...e.maxSizeMb===void 0?{}:{maxSizeMb:e.maxSizeMb},...e.accept===void 0?{}:{accept:Yn(e.accept)}};for(let r of["maxCount","maxSizeMb","accept"]){if(i[r]===void 0&&n[r]===void 0)continue;(i[r]===void 0||n[r]===void 0)&&W("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${o}/${r}`);let d=r==="accept"?Yn(i[r]):i[r],s=r==="accept"?Yn(n[r]):n[r];X(d)!==X(s)&&W("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${o}/${r}`)}}function Yn(e){return(Array.isArray(e)?[...e]:[e]).sort((t,o)=>{let n=String(t),i=String(o);return n===i?0:n<i?-1:1})}function it(e,t,o,n){(!Array.isArray(e)||!n&&e.length===0||e.length>o)&&W("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t);let i=e.map((r,d)=>De(r,`${t}/${d}`,255));return new Set(i).size!==i.length&&W("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t),i}function ae(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&W("NATIVE_OBJECT_REQUIRED",t),e}function Ce(e,t,o){let n=new Set(t);for(let i of Object.keys(e))n.has(i)||W("NATIVE_PROPERTY_UNKNOWN",`${o}/${i}`)}function De(e,t,o){return(typeof e!="string"||e.length===0||e.length>o)&&W("NATIVE_STRING_INVALID",t),e}function ma(e,t,o){e!==void 0&&(typeof e!="string"||e.length>o)&&W("NATIVE_STRING_INVALID",t)}function Xn(e,t){e!==void 0&&typeof e!="boolean"&&W("NATIVE_BOOLEAN_REQUIRED",t)}function W(e,t){throw new Re(e,t)}var Et=class extends Error{constructor(o,n){super(`${o}: ${n}`);this.pointer=o;this.reason=n}pointer;reason;code="NATIVE_MANAGED_CONCURRENCY_INVALID"};function Ri(e,t,o){if(e===void 0)return;let n=(g,I)=>{throw new Et(g,I)},i=(g,I,T)=>((!g||typeof g!="object"||Array.isArray(g)||Object.keys(g).some(l=>!T.includes(l)))&&n(I,"object contains unsupported properties"),g),r=(g,I,T,l)=>{(!Number.isSafeInteger(g)||g<I||g>T)&&n(l,`expected integer ${I}..${T}`)},d=(g,I)=>{(typeof g!="string"||!/^[a-z][a-z0-9_-]{0,63}$/.test(g))&&n(I,"invalid code")},s=(g,I,T)=>((!Array.isArray(g)||g.length>I)&&n(T,"array exceeds bound"),g),a=(g,I)=>{let T=t.find(l=>l.code===g);return T||n(I,"unknown resource"),T},c=(g,I,T)=>{let l=g.schema.fields.find(y=>y.code===I);return!l&&I!=="id"&&n(T,"unknown field"),l},f=(g,I,T=!1)=>{i(g,I,Object.keys(g||{})),Object.keys(g).length>8&&n(I,"at most eight parameters");for(let[l,y]of Object.entries(g))if(d(l,I),i(y,I,["type","values","minimum","maximum","minLength","maxLength"]),y.type==="uuid")Object.keys(y).length!==1&&n(I,"uuid has no options");else if(T&&y.type==="boolean")i(y,I,["type"]);else if(T&&y.type==="string"&&y.values===void 0)i(y,I,["type","minLength","maxLength"]),r(y.maxLength,1,256,I),y.minLength!==void 0&&r(y.minLength,0,y.maxLength,I);else if(y.type==="string"){i(y,I,["type","values"]);let R=s(y.values,100,I);(!R.length||R.some(h=>typeof h!="string"||h.length>128)||new Set(R).size!==R.length)&&n(I,"finite string values required")}else y.type==="integer"?(i(y,I,["type","minimum","maximum"]),r(y.minimum,0,1e6,I),r(y.maximum,y.minimum,y.minimum+1e3,I)):n(I,"unsupported parameter type")},u=(g,I,T,l=!1)=>{i(g,T,["from","key","value"]),!(g.from==="input"&&Object.keys(g).length===2&&Object.hasOwn(I,g.key))&&((g.from==="actor"||l&&g.from==="allocation")&&Object.keys(g).length===1||g.from==="literal"&&Object.keys(g).length===2&&Object.hasOwn(g,"value")&&(g.value===null||["string","boolean"].includes(typeof g.value)||typeof g.value=="number"&&Number.isFinite(g.value))&&JSON.stringify(g.value).length<=512||n(T,"invalid binding"))},p=(g,I,T)=>{u(g,I,T),!(g.from==="input"&&I[g.key].type==="uuid")&&(g.from==="literal"&&typeof g.value=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(g.value)||n(T,"record and allocation identifiers require a UUID binding"))},_=(g,I,T)=>{u(g,I,T),!(g.from==="input"&&I[g.key].type==="integer"&&I[g.key].minimum>=1)&&(g.from==="literal"&&Number.isSafeInteger(g.value)&&g.value>=1||n(T,"expectedRevision requires a positive integer binding"))},E="/data/concurrency";JSON.stringify(e).length>131072&&n(E,"declaration exceeds 128 KiB");let A=i(e,E,["version","admission","reads","quotas","commands"]);A.version!==1&&n(E,"unsupported version"),i(A.admission,E,["perSecond","burst","maxInFlight"]),r(A.admission.perSecond,1,1e3,E),r(A.admission.burst,1,1e3,E),r(A.admission.maxInFlight,1,1e3,E);let O=(g,I)=>{let T=new Set;for(let l of g)d(l?.code,I),T.has(l.code)&&n(I,"duplicate code"),T.add(l.code)};O(s(A.reads,32,E),E),O(s(A.quotas,16,E),E),O(s(A.commands,32,E),E);for(let g of A.reads){let I=`${E}/reads/${g.code}`;i(g,I,["code","resourceCode","parameters","select","where","limit","scope","freshSeconds","staleSeconds","maxKeys","sourcePerSecond","dependencies"]);let T=a(g.resourceCode,I);f(g.parameters,I),["subject","application"].includes(g.scope)||n(I,"invalid cache scope"),g.scope==="application"&&T.dataPolicyCode&&n(I,"shared cache cannot bypass a row policy");let l=s(g.select,32,I);l.length||n(I,"select required"),l.forEach(R=>c(T,R,I));let y=s(g.dependencies,64,I);y.forEach(R=>c(T,R,I));for(let R of s(g.where||[],8,I))i(R,I,["field","value"]),c(T,R.field,I),u(R.value,g.parameters,I),g.scope==="application"&&R.value.from==="actor"&&n(I,"actor requires subject cache"),y.includes(R.field)||n(I,"filter dependency missing");l.some(R=>!y.includes(R))&&n(I,"selected field dependency missing"),r(g.limit,1,100,I),r(g.freshSeconds,1,300,I),r(g.staleSeconds,0,300,I),r(g.maxKeys,1,1e4,I),r(g.sourcePerSecond,1,20,I)}for(let g of A.quotas){let I=`${E}/quotas/${g.code}`;i(g,I,["code","sourceResource","capacityField","allocationResource","allocationField","reservationSeconds"]);let T=a(g.sourceResource,I),l=a(g.allocationResource,I);c(T,g.capacityField,I)?.type!=="number.integer"&&n(I,"capacity must be an integer"),(c(l,g.allocationField,I)?.type!=="uuid"||c(l,g.allocationField,I)?.nullable!==!1)&&n(I,"allocation reference must be a uuid"),l.surface?.mutationOwner!=="queued-command"&&n(I,"allocation model must be command owned"),g.reservationSeconds!==void 0&&r(g.reservationSeconds,10,86400,I)}new Set(A.quotas.map(g=>g.allocationResource)).size!==A.quotas.length&&n(E,"an allocation model has exactly one pool owner");for(let g of A.commands){let I=`${E}/commands/${g.code}`;i(g,I,["code","mode","intake","execution","capability","parameters","resourceKey","admission","deadlineSeconds","guards","operations","quota"]),g.mode!==void 0&&!["permit","durable"].includes(g.mode)&&n(I,"unsupported mode");let T=g.mode==="durable";if(f(g.parameters,I,T),u(g.resourceKey,g.parameters,I),o.some(l=>l.code===g.capability)||n(I,"command capability must be declared"),i(g.admission,I,["perSecond","burst","maxInFlight","maxQueue","maxWaitSeconds","permitSeconds"]),r(g.admission.perSecond,1,A.admission.perSecond,I),r(g.admission.burst,1,A.admission.burst,I),r(g.admission.maxInFlight,1,A.admission.maxInFlight,I),r(g.admission.maxQueue,1,1e4,I),r(g.admission.maxWaitSeconds,1,3600,I),(!T||g.admission.permitSeconds!==void 0)&&r(g.admission.permitSeconds,5,60,I),r(g.deadlineSeconds,10,3600,I),T){(g.operations!==void 0||g.guards!==void 0||g.quota!==void 0)&&n(I,"backend-plan does not accept static operations, guards or quota"),i(g.intake,I,["perSecond","burst","maxInFlight"]);for(let R of["perSecond","burst","maxInFlight"])r(g.intake[R],1,1e3,I);let l=i(g.execution,I,["kind","handlerCode","timeoutMs","resources","directory"]);l.kind!=="backend-plan"&&n(I,"durable requires backend-plan"),d(l.handlerCode,I),r(l.timeoutMs,100,3e4,I);let y=s(l.resources,32,I);y.length||n(I,"execution resources required"),new Set(y.map(R=>R.resourceCode)).size!==y.length&&n(I,"duplicate execution resource");for(let R of y){i(R,I,["resourceCode","readFields","writeOperations","writeFields"]);let h=a(R.resourceCode,I);for(let w of["readFields","writeFields"]){let j=s(R[w],64,I);new Set(j).size!==j.length&&n(I,"duplicate field"),j.forEach(L=>{w==="readFields"&&nt.has(L)||c(h,L,I)})}let $=s(R.writeOperations,3,I);(new Set($).size!==$.length||$.some(w=>!["create","update","increment"].includes(w)))&&n(I,"unsupported execution operation"),R.writeFields.some(w=>["id","revision","created_by","updated_by","created_at","updated_at"].includes(w))&&n(I,"record metadata is platform owned"),!$.length&&R.writeFields.length&&n(I,"write fields require an operation"),$.length&&!R.writeFields.length&&n(I,"write operations require fields"),A.quotas.some(w=>w.allocationResource===R.resourceCode)&&$.length&&n(I,"allocation references remain owned by their pool command")}if(l.directory!==void 0){i(l.directory,I,["mode","fields"]),l.directory.mode!=="current-initiator"&&n(I,"only current initiator allowed");let R=s(l.directory.fields,5,I);(!R.length||new Set(R).size!==R.length||R.some(h=>!["displayName","employeeNumber","primaryDepartment","departments","phone"].includes(h)))&&n(I,"unsupported directory fields")}continue}(g.execution!==void 0||g.intake!==void 0)&&n(I,"execution and intake require durable mode");for(let l of s(g.guards||[],8,I)){i(l,I,["resourceCode","id","conditions"]);let y=a(l.resourceCode,I);p(l.id,g.parameters,I);for(let R of s(l.conditions,16,I)){i(R,I,["kind","field","operator","value"]);let h=c(y,R.field,I);["eq","neq","lt","lte","gt","gte"].includes(R.operator)||n(I,"unsupported guard"),R.kind==="database-now"?(h?.type!=="datetime"||!["lt","lte","gt","gte"].includes(R.operator)||R.value!==void 0)&&n(I,"database-now requires datetime and an ordering operator"):(R.kind!==void 0&&R.kind!=="value"&&n(I,"unsupported condition kind"),u(R.value,g.parameters,I))}}for(let l of s(g.operations,8,I)){i(l,I,["operation","resourceCode","id","expectedRevision","data"]);let y=a(l.resourceCode,I);y.surface?.mutationOwner!=="queued-command"&&n(I,"command mutations require command owned models");let R=A.quotas.find(h=>h.allocationResource===l.resourceCode);R&&(l.operation==="create"?g.quota?.action!=="allocate"||g.quota.pool!==R.code:Object.hasOwn(l.data||{},R.allocationField))&&n(I,"allocation references are owned by their pool command"),["create","update"].includes(l.operation)||n(I,"unsupported operation"),l.operation==="update"?(p(l.id,g.parameters,I),_(l.expectedRevision,g.parameters,I)):(l.id!==void 0||l.expectedRevision!==void 0)&&n(I,"create has no caller supplied id/revision"),i(l.data,I,Object.keys(l.data||{})),Object.keys(l.data).length>32&&n(I,"too many fields");for(let[h,$]of Object.entries(l.data))h==="id"&&n(I,"record identifiers are platform owned"),c(y,h,I),u($,g.parameters,I,g.quota?.action==="allocate")}if(g.quota){let l=i(g.quota,I,["pool","action","units","mode","allocation"]),y=A.quotas.find(R=>R.code===l.pool);y||n(I,"unknown quota pool"),p(g.resourceKey,g.parameters,I),l.action==="allocate"?(i(l,I,["pool","action","units","mode"]),r(l.units,1,1e3,I),(!["committed","reserved"].includes(l.mode)||l.mode==="reserved"&&!y.reservationSeconds)&&n(I,"invalid allocation mode"),(g.operations.length!==1||g.operations[0].operation!=="create"||g.operations[0].resourceCode!==y.allocationResource||g.operations[0].data[y.allocationField]?.from!=="allocation")&&n(I,"allocation must atomically create its bound business record")):["confirm","release"].includes(l.action)?(i(l,I,["pool","action","allocation"]),p(l.allocation,g.parameters,I),g.operations.length&&n(I,"lifecycle owns allocation state; business reference remains immutable")):n(I,"invalid quota action")}else g.operations.length||n(I,"operations required")}let b=A.commands.filter(g=>g.mode==="durable").map(g=>g.execution.handlerCode);return new Set(b).size!==b.length&&n(E,"handler code must be unique"),JSON.parse(JSON.stringify(A))}var rt=class extends Error{constructor(o,n){super(`\u91D1\u989D\u751F\u547D\u5468\u671F\u58F0\u660E\u65E0\u6548\uFF1A${n}\uFF08${o}\uFF09`);this.pointer=o;this.reason=n}pointer;reason;code="NATIVE_DECIMAL_LIFECYCLE_INVALID"},no=["parentTransitions","childTransitions","fulfilledChildStatuses","lockedParentStatuses"],Ci=["amountFieldCode","currencyFieldCode","relationFieldCode","parentFieldCode","rootFieldCode","statusFieldCode","parentRelationValue","childRelationValue"],Jt=e=>!!(e&&typeof e=="object"&&!Array.isArray(e)),zt=e=>Array.isArray(e)?e.filter(Jt):[],he=(e,t)=>{throw new rt(e,t)},eo=e=>typeof e=="string"&&/^[A-Za-z0-9._:-]{1,128}$/.test(e),to=(e,t)=>e<t?-1:e>t?1:0;function oo(e,t="/decimalReservationLifecycle"){if(e===void 0)return;if(!Jt(e)||Object.keys(e).some(i=>!no.includes(i))||no.some(i=>!Object.prototype.hasOwnProperty.call(e,i)))return he(t,"\u5FC5\u987B\u5B8C\u6574\u58F0\u660E\u56DB\u9879\u89C4\u5219\uFF0C\u4E0D\u80FD\u5305\u542B\u672A\u77E5\u5C5E\u6027");let o=i=>{let r=e[i];if(!Array.isArray(r)||r.length>64)return he(`${t}/${i}`,"\u72B6\u6001\u8FB9\u6700\u591A 64 \u6761");let d=new Set;return r.map((s,a)=>{let c=`${t}/${i}/${a}`;if(!Jt(s)||Object.keys(s).some(u=>u!=="from"&&u!=="to")||!eo(s.from)||!eo(s.to)||s.from===s.to)return he(c,"\u72B6\u6001\u8FB9\u5FC5\u987B\u5305\u542B\u4E0D\u540C\u7684\u6709\u6548 from/to");let f=JSON.stringify([s.from,s.to]);return d.has(f)?he(c,"\u72B6\u6001\u8FB9\u4E0D\u80FD\u91CD\u590D"):(d.add(f),{from:s.from,to:s.to})}).sort((s,a)=>to(s.from,a.from)||to(s.to,a.to))},n=i=>{let r=e[i];return!Array.isArray(r)||r.length<1||r.length>16||r.some(d=>!eo(d))||new Set(r).size!==r.length?he(`${t}/${i}`,"\u72B6\u6001\u96C6\u5408\u5FC5\u987B\u5305\u542B 1 \u5230 16 \u4E2A\u4E0D\u91CD\u590D\u7684\u6709\u6548\u72B6\u6001"):[...r].sort(to)};return{parentTransitions:o("parentTransitions"),childTransitions:o("childTransitions"),fulfilledChildStatuses:n("fulfilledChildStatuses"),lockedParentStatuses:n("lockedParentStatuses")}}function hi(e,t,o="/config/data/resources"){zt(e).forEach((n,i)=>{let r=`${o}/${i}/decimalReservationLifecycle`,d=oo(n.decimalReservationLifecycle,r);if(!d)return;let s=zt(t).map(u=>u.platformAccess?.decimalReservation).filter(u=>Jt(u)&&u.resourceCode===n.code),a=s.find(u=>u.mode==="reserve");if(!a)return he(r,"\u9700\u8981\u540C\u8D44\u6E90\u5DF2\u58F0\u660E\u7684 reserve \u52A8\u4F5C\u6620\u5C04");if(Ci.some(u=>typeof a[u]!="string")||s.some(u=>Ci.some(p=>u[p]!==a[p])))return he(r,"\u540C\u8D44\u6E90\u989D\u5EA6\u52A8\u4F5C\u7684\u5B57\u6BB5\u6620\u5C04\u5FC5\u987B\u4E00\u81F4");let c=zt(n.schema?.fields).find(u=>u.code===a.statusFieldCode);if(c?.type!=="option.single")return he(r,"\u989D\u5EA6\u72B6\u6001\u5B57\u6BB5\u5FC5\u987B\u4E3A option.single");let f=new Set(zt(c.options).map(u=>u.value));for(let u of no)if((u==="parentTransitions"||u==="childTransitions"?d[u].flatMap(_=>[_.from,_.to]):d[u]).some(_=>!f.has(_)))return he(`${r}/${u}`,"\u72B6\u6001\u5FC5\u987B\u6765\u81EA\u989D\u5EA6\u72B6\u6001\u5B57\u6BB5\u7684\u9009\u9879");if(s.some(u=>u.mode==="reserve"&&Array.isArray(u.eligibleParentStatuses)&&u.eligibleParentStatuses.some(p=>d.lockedParentStatuses.includes(String(p)))))return he(`${r}/lockedParentStatuses`,"\u9501\u5B9A\u7236\u72B6\u6001\u4E0D\u80FD\u5141\u8BB8\u65B0\u9884\u7559")})}import{createHash as _a}from"crypto";var io=new Set(["option.single","user.single","department.single","resource-ref.single"]),ga=new Set(["option.multiple","cascade.single","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","address","location","json"]),Si=new Set(["option.multiple","cascade.single","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","file","image"]),Aa=new Set(["option.single","user.single","department.single","resource-ref.single","signature","address","location"]),Ea=new Set([...io,...Si,"signature","address","location","json"]);function El(e,t){let o=new Set([...Array.isArray(t?.list?.searchableFields)?t.list.searchableFields:[],...Object.entries(t?.fields||{}).filter(([,n])=>n?.searchable===!0).map(([n])=>n)]);return e.map(n=>Ia(n,o.has(n.code))).sort((n,i)=>n.code.localeCompare(i.code))}function Ia(e,t=!1){let o=e.type==="date-range"||e.type==="datetime-range";if(o&&e.rangeBoundary!=="closed"&&e.rangeBoundary!=="half-open")throw new Error("OPENXIANGDA_NATIVE_DATA_RANGE_BOUNDARY_INVALID");return{code:e.code,type:e.type,nullable:!0,indexed:e.indexed===!0,storage:Oa(e),index:ba(e,t),...o?{rangeBoundary:e.rangeBoundary}:{},...e.type==="serial-number"?{serial:{prefix:e.serial?.prefix||"",digits:e.serial?.digits??6,start:e.serial?.start??1}}:{},...e.type==="subtable"&&e.subtable?{subtable:{resourceCode:e.subtable.resourceCode,foreignKey:e.subtable.foreignKey,orderField:e.subtable.orderField,maxRows:e.subtable.maxRows??20}}:{}}}function Il(e,t){if(t.type==="subtable")return null;let o=le(t.code),n=Di(e,t),i=[n?` DEFAULT ${n}`:"",Na(o,t),ya(o,t)].join("");return`${o} ${t.storage}${i}`}function yl(e,t){return Di(e,t)}function ya(e,t){if(t.type!=="date-range"&&t.type!=="datetime-range")return"";if(t.rangeBoundary!=="closed"&&t.rangeBoundary!=="half-open")throw new Error("OPENXIANGDA_NATIVE_DATA_RANGE_BOUNDARY_INVALID");let o=t.type==="datetime-range"&&t.rangeBoundary==="closed";return` CHECK (${e} IS NULL OR (NOT isempty(${e}) AND lower(${e}) IS NOT NULL AND upper(${e}) IS NOT NULL AND lower_inc(${e}) AND ${o?"":"NOT "}upper_inc(${e})))`}function bl(e){return e.type==="serial-number"||Mt(e.type)&&e.type!=="subtable"}function Ol(e,t){return t.filter(o=>o.type==="serial-number").map(o=>{let n=Yt(e,o.code),i=o.serial?.start??1;return`CREATE SEQUENCE IF NOT EXISTS ${n} AS bigint MINVALUE ${i} START WITH ${i} CACHE 1`})}function Nl(e,t){let o=Ht(e);return t.filter(n=>n.type==="serial-number").map(n=>`ALTER SEQUENCE ${Yt(e,n.code)} OWNED BY ${o}.${le(n.code)}`)}function Tl(e,t){return t.filter(o=>o.type==="serial-number").map(o=>`GRANT USAGE, SELECT ON SEQUENCE ${Yt(e,o.code)} TO "openxiangda_data_api"`)}function Rl(e,t){let o=Ht(e),n=[];for(let i of t){if(i.type==="subtable")continue;let r=le(i.code),d=le(ve("idx",e,i.code,i.index));switch(i.index){case"btree":n.push(`CREATE INDEX IF NOT EXISTS ${d} ON ${o} (${r})`);break;case"btree-snapshot-expressions":{let s=le(ve("idx",e,i.code,"snapshot-value")),a=le(ve("idx",e,i.code,"snapshot-label"));n.push(`CREATE INDEX IF NOT EXISTS ${s} ON ${o} ((${r} ->> 'value'))`,`CREATE INDEX IF NOT EXISTS ${a} ON ${o} ((${r} ->> 'label'))`);break}case"gin-jsonb-path":n.push(`CREATE INDEX IF NOT EXISTS ${d} ON ${o} USING GIN (${r} jsonb_path_ops)`);break;case"gist-range":n.push(`CREATE INDEX IF NOT EXISTS ${d} ON ${o} USING GIST (${r})`);break;case"gin-trigram":{let s=io.has(i.type)?`((${r} ->> 'label')) gin_trgm_ops`:`${r} gin_trgm_ops`;n.push(`CREATE INDEX IF NOT EXISTS ${d} ON ${o} USING GIN (${s})`);break}case"none":break}if(i.type==="serial-number"){let s=le(ve("uidx",e,i.code,"serial"));n.push(`CREATE UNIQUE INDEX IF NOT EXISTS ${s} ON ${o} (${r})`)}}return n}function Cl(e,t,o,n){let i=Ht(e),r=Ht(t),d=le(ve("uidx",e,"environment_id","subtable-parent")),s=le(ve("idx",t,o,n,"subtable-child")),a=le(ve("fk",t,o,e)),c=le(o),f=le(n);return[`CREATE UNIQUE INDEX IF NOT EXISTS ${d} ON ${i} ("tenant_id", "app_code", "environment_key", "id")`,`CREATE INDEX IF NOT EXISTS ${s} ON ${r} ("tenant_id", "app_code", "environment_key", ${c}, ${f}, "id")`,`DO $native_subtable$ BEGIN
2
- ALTER TABLE ${r}
3
- ADD CONSTRAINT ${a}
1
+ import{createHash as ha}from"node:crypto";function Ra(e){if(!e||typeof e!="object")return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function to(e,t){if(e===null)return"null";if(typeof e=="string"||typeof e=="boolean")return JSON.stringify(e);if(typeof e=="number"){if(!Number.isFinite(e))throw new TypeError(`JSON number must be finite: ${t}`);return JSON.stringify(e)}if(Array.isArray(e))return`[${e.map((n,r)=>to(n,`${t}[${r}]`)).join(",")}]`;if(Ra(e))return`{${Object.keys(e).filter(r=>e[r]!==void 0).sort((r,i)=>r===i?0:r<i?-1:1).map(r=>`${JSON.stringify(r)}:${to(e[r],`${t}.${r}`)}`).join(",")}}`;let o=e instanceof Date?"Date":e?.constructor?.name||typeof e;throw new TypeError(`Value is not JSON serializable: ${t} (${o})`)}function Q(e){return to(e,"$")}function ee(e){return ha("sha256").update(Q(e)).digest("hex")}var Ml=200,wa=["text.short","uuid","option.single","resource-ref.single"],no=/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/,vr=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,Vr=new Set(["__proto__","prototype","constructor"]),oo=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&[Object.prototype,null].includes(Object.getPrototypeOf(e)),Pr=(e,t)=>Object.keys(e).every(o=>t.includes(o)),dt=(e,t)=>typeof e=="string"&&e.length>0&&e.trim()===e&&e.length<=t,Je=class extends Error{constructor(o,n){super(`${o}: ${n}`);this.code=o;this.pointer=n}code;pointer};function oe(e,t){throw new Je(e,t)}function Xt(e,t,o){if(e===void 0)return;["user.single","user.multiple"].includes(t)||oe("DATA_USER_CANDIDATES_FIELD_TYPE_INVALID",o),(!oo(e)||!Pr(e,["kind","roleCode","scope","pageSize"])||e.kind!=="app-role"||!dt(e.roleCode,128)||!no.test(String(e.roleCode)))&&oe("DATA_USER_CANDIDATES_SOURCE_INVALID",o),e.pageSize!==void 0&&(!Number.isSafeInteger(e.pageSize)||Number(e.pageSize)<1||Number(e.pageSize)>50)&&oe("DATA_USER_CANDIDATES_PAGE_SIZE_INVALID",`${o}/pageSize`);let n;if(e.scope!==void 0){let r=e.scope;(!oo(r)||!Pr(r,["dimensionCode","operation","field","value","creation"])||!dt(r.dimensionCode,128)||!no.test(String(r.dimensionCode))||!dt(r.operation,64)||!no.test(String(r.operation))||Object.hasOwn(r,"field")===Object.hasOwn(r,"value"))&&oe("DATA_USER_CANDIDATES_SCOPE_INVALID",`${o}/scope`),r.creation!==void 0&&(r.creation!=="prospective"||!Object.hasOwn(r,"field"))&&oe("DATA_USER_CANDIDATES_SCOPE_INVALID",`${o}/scope/creation`),Object.hasOwn(r,"field")?((!dt(r.field,63)||!vr.test(String(r.field))||Vr.has(String(r.field)))&&oe("DATA_USER_CANDIDATES_SCOPE_FIELD_INVALID",`${o}/scope/field`),n={dimensionCode:String(r.dimensionCode),operation:String(r.operation),field:String(r.field),...r.creation==="prospective"?{creation:"prospective"}:{}}):(dt(r.value,255)||oe("DATA_USER_CANDIDATES_SCOPE_VALUE_INVALID",`${o}/scope/value`),n={dimensionCode:String(r.dimensionCode),operation:String(r.operation),value:String(r.value)})}return{kind:"app-role",roleCode:String(e.roleCode),...n?{scope:n}:{},...e.pageSize===void 0?{}:{pageSize:Number(e.pageSize)}}}function ro(e){return e.some(t=>t.schema.fields.some(o=>{let n=o.userCandidates?.scope;return n?.creation==="prospective"||!!(n?.field&&t.schema.fields.find(r=>r.code===n.field)?.type==="resource-ref.single")}))}function Fr(e,t,o,n){for(let[r,i]of e.entries()){let a=`${n}/${r}/userCandidates`,s=Xt(i.userCandidates,i.type,a);if(s&&(t.has(s.roleCode)||oe("DATA_USER_CANDIDATES_ROLE_UNDECLARED",`${a}/roleCode`),s.scope&&!o.has(s.scope.dimensionCode)&&oe("DATA_USER_CANDIDATES_DIMENSION_UNDECLARED",`${a}/scope/dimensionCode`),s.scope?.field)){let d=e.find(c=>c.code===s.scope.field);(!d||!wa.some(c=>c===d.type))&&oe("DATA_USER_CANDIDATES_SCOPE_FIELD_INVALID",`${a}/scope/field`)}}}function Ta(e,t,o,n){let r=e.subject.factProjection,i=typeof t.inputPath=="string"&&Object.entries(r).some(([c,l])=>(t.inputPath===c||t.inputPath.startsWith(`${c}.`))&&o.get(l)?.userCandidates!==void 0);if(t.candidateField===void 0&&!i)return;(t.provider!=="form_field_users"||!t.candidateField||!vr.test(t.candidateField)||Vr.has(t.candidateField)||!t.inputPath||r[t.inputPath]!==t.candidateField)&&oe("WORKFLOW_USER_CANDIDATES_FIELD_BINDING_REQUIRED",n),(t.roleCode!==void 0||t.scope!==void 0||t.routing!==void 0)&&oe("WORKFLOW_USER_CANDIDATES_SOURCE_OVERRIDE_FORBIDDEN",n);let a=o.get(t.candidateField),s=a&&Xt(a.userCandidates,a.type,`${n}/candidateField`);s||oe("WORKFLOW_USER_CANDIDATES_FIELD_UNDECLARED",`${n}/candidateField`);let d;if(s.scope?.field){let c=Object.entries(r).filter(([,l])=>l===s.scope.field).map(([l])=>l);c.length!==1&&oe("WORKFLOW_USER_CANDIDATES_SCOPE_PROJECTION_REQUIRED",n),d=c[0]}return{fieldCode:a.code,inputPath:t.inputPath,source:s,...d?{scopeInputPath:d}:{}}}function Wr(e,t,o,n,r=new Map){for(let[i,a]of Object.entries(t.bindings))Ta(e,a,o,`${n}/${i}`);for(let[i,a]of Object.entries(e.taskPages||{})){let s=new Set(a.fields.filter(d=>d.readonly!==!0).map(d=>d.code));for(let d of a.fields){let c=o.get(d.code)?.userCandidates?.scope;if(s.has(d.code)&&c?.field&&s.has(c.field)&&oe("WORKFLOW_USER_CANDIDATES_SCOPE_WRITE_FORBIDDEN",`${n}/taskPages/${i}/${d.code}`),!s.has(d.code)||!d.subtable)continue;let l=o.get(d.code)?.subtable?.resourceCode,f=l?r.get(l):void 0;d.subtable.fields.some(p=>p.readonly!==!0&&f?.get(p.code)?.userCandidates)&&oe("WORKFLOW_USER_CANDIDATES_OWNED_FIELD_UNSUPPORTED",`${n}/taskPages/${i}/${d.code}`)}}}function Ul(e,t){if(!e.scope)return;let o=e.scope.field?t[e.scope.field]:e.scope.value,n=oo(o)?o.value:o;return dt(n,255)||oe("DATA_USER_CANDIDATES_SCOPE_VALUE_REQUIRED",e.scope.field||"scope"),String(n)}var xr=200,so=205;function ao(e,t=[]){return e.some(o=>o.schema.fields.length>100)||t.some(o=>Object.values(o.definition.taskPages||{}).some(n=>(n.fields?.length??0)>64)||[o.launch?.submission?.create,o.launch?.submission?.existing].some(n=>Object.keys(n?.inputs||{}).length>64))}var He=500,io=500,ct=1e3,jr=2*ct+16,Kl=2*1024*1024,Gl=2*1024*1024;function wt(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=1&&e<=ct}function Zt(e){if(e.ownedRowLimit===void 0)return io;if(!wt(e.ownedRowLimit))throw new Error("NATIVE_DATA_OWNED_ROW_LIMIT_INVALID");return e.ownedRowLimit}function co(e){return e.some(t=>(t.schema.ownedRowLimit??io)>io)}function lo(e){return e.some(t=>{let o=t.schema.fields.filter(n=>n.type==="subtable").map(n=>n.subtable?.maxRows??20);return o.some(n=>n>100)||o.reduce((n,r)=>n+r,0)>400})}function ql(e){try{return new TextEncoder().encode(JSON.stringify(e)).byteLength}catch{return 1/0}}var Gr=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,po=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,Ca=["text.short","text.long","text.rich","number.integer","number.decimal","boolean","date","time","datetime","date-range","datetime-range","option.single","option.multiple","cascade.single","cascade.multiple","user.single","user.multiple","department.single","department.multiple","resource-ref.single","resource-ref.multiple","image","signature","address","location","uuid","json","file","serial-number","subtable"];function mo(e){return e.some(t=>t.schema.fields.some(o=>(o.type==="datetime"||o.type==="datetime-range")&&o.timePrecision==="minute"))}function _o(e){return e.some(t=>t.schema.fields.some(o=>o.type==="subtable"&&(o.subtable?.minRows??0)>0))}var Sa=new Set(Ca),qr=new Set(["option.multiple","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","file","image","subtable"]),Mr=new Set(["option.single","option.multiple","cascade.single","cascade.multiple"]),Ur=new Set(["resource-ref.single","resource-ref.multiple"]),go=[{code:"id",type:"uuid",nullable:!1},{code:"revision",type:"number.integer",nullable:!1},{code:"created_by",type:"text.short",nullable:!1},{code:"updated_by",type:"text.short",nullable:!1},{code:"created_at",type:"datetime",nullable:!1},{code:"updated_at",type:"datetime",nullable:!1}],lt=new Map(go.map(e=>[e.code,e])),Ce=class extends Error{constructor(o,n){super(o);this.code=o;this.pointer=n;this.name="NativeDataFieldContractV2Error"}code;pointer};function tn(e){return qr.has(e)}function nn(e,t={}){return e.type!=="serial-number"&&t.system!==!0&&e.nullable===!1&&(!tn(e.type)||t.requiredHint===!0)}function Ao(e,t,o=500){Array.isArray(e)||L("NATIVE_ARRAY_REQUIRED",t),e.length===0&&L("NATIVE_DATA_FIELDS_REQUIRED",t),e.length>o&&L("NATIVE_ARRAY_LIMIT_EXCEEDED",t);let n=new Set;return e.map((r,i)=>{let a=`${t}/${i}`,s=Oe(r,a);Ne(s,["code","type","nullable","indexed","options","source","userCandidates","maxLength","precision","scale","exactDecimal","min","max","rangeBoundary","timePrecision","file","serial","subtable"],a);let d=he(s.code,`${a}/code`,63);Gr.test(d)||L("NATIVE_FIELD_CODE_INVALID",`${a}/code`),n.has(d)&&L("NATIVE_DATA_FIELD_DUPLICATE",`${a}/code`),n.add(d);let c=he(s.type,`${a}/type`,32);Sa.has(c)||L("NATIVE_DATA_FIELD_TYPE_INVALID",`${a}/type`);let l=c,f=fo(s.nullable,`${a}/nullable`),p=fo(s.indexed,`${a}/indexed`);f===!0&&qr.has(l)&&L("NATIVE_DATA_MULTI_FIELD_NULLABLE_INVALID",`${a}/nullable`);let m=La(s.options,l,a),E=$a(s.source,l,a),A=Xt(s.userCandidates,l,`${a}/userCandidates`),b=Pa(s,l,a),O=fo(s.exactDecimal,`${a}/exactDecimal`);O!==void 0&&l!=="number.decimal"&&L("NATIVE_DATA_FIELD_EXACT_DECIMAL_TYPE_INVALID",`${a}/exactDecimal`);let g=Da(s.rangeBoundary,l,a),y=va(s.file,l,a),h=Va(s.serial,l,a),u=Fa(s.subtable,l,a);return{code:d,type:l,...f===void 0?{}:{nullable:f},...p===void 0?{}:{indexed:p},...m?{options:m}:{},...E?{source:E}:{},...A?{userCandidates:A}:{},...b,...O===void 0?{}:{exactDecimal:O},...g?{rangeBoundary:g}:{},...y?{file:y}:{},...h?{serial:h}:{},...u?{subtable:u}:{}}})}function Da(e,t,o){let n=`${o}/rangeBoundary`;if(!(t==="date-range"||t==="datetime-range")){e!==void 0&&L("NATIVE_DATA_FIELD_RANGE_BOUNDARY_TYPE_INVALID",n);return}return e!=="closed"&&e!=="half-open"&&L("NATIVE_DATA_FIELD_RANGE_BOUNDARY_REQUIRED",n),e}function zr(e,t){Array.isArray(e)||L("NATIVE_ARRAY_REQUIRED",t);let o=new Map;e.forEach((n,r)=>{let i=`${t}/${r}`,a=Oe(n,i),s=he(a.code,`${i}/code`,64);(!po.test(s)||o.has(s))&&L("NATIVE_RESOURCE_CODE_INVALID",`${i}/code`);let d=Oe(a.schema,`${i}/schema`);d.ownedRowLimit!==void 0&&!wt(d.ownedRowLimit)&&L("NATIVE_DATA_OWNED_ROW_LIMIT_INVALID",`${i}/schema/ownedRowLimit`),o.set(s,{pointer:i,ownedRowLimit:Zt(d),fields:Ao(d.fields,`${i}/schema/fields`)})});for(let[n,r]of o){let i=new Map(r.fields.map(s=>[s.code,s]));r.fields.filter(s=>s.type==="subtable").reduce((s,d)=>s+(d.subtable?.maxRows??20),0)>r.ownedRowLimit&&L("NATIVE_DATA_FIELD_SUBTABLE_AGGREGATE_MAX_ROWS_EXCEEDED",`${r.pointer}/schema/fields`),r.fields.forEach((s,d)=>{let c=`${r.pointer}/schema/fields/${d}`;if(s.source&&ka(s.source,i,o,`${c}/source`),s.subtable){let l=o.get(s.subtable.resourceCode);(!l||s.subtable.resourceCode===n)&&L("NATIVE_DATA_FIELD_SUBTABLE_TARGET_MISSING",`${c}/subtable/resourceCode`);let f=l.fields.find(m=>m.code===s.subtable?.foreignKey);(!f||f.type!=="uuid"||f.nullable!==!1)&&L("NATIVE_DATA_FIELD_SUBTABLE_FOREIGN_KEY_INVALID",`${c}/subtable/foreignKey`);let p=l.fields.find(m=>m.code===s.subtable?.orderField);(!p||p.type!=="number.integer"||p.nullable!==!1)&&L("NATIVE_DATA_FIELD_SUBTABLE_ORDER_FIELD_INVALID",`${c}/subtable/orderField`)}})}}function Jr(e,t,o){if(e===void 0)return[];(!Array.isArray(e)||e.length>20)&&L("NATIVE_DATA_RESOURCE_INVARIANTS_INVALID",o);let n=new Map(t.map(i=>[i.code,i])),r=new Set;return e.map((i,a)=>{let s=`${o}/${a}`,d=Oe(i,s);Ne(d,["code","message","expression"],s);let c=he(d.code,`${s}/code`,128);(!/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/.test(c)||r.has(c))&&L("NATIVE_DATA_RESOURCE_INVARIANT_CODE_INVALID",`${s}/code`),r.add(c);let l=en(d.message,`${s}/message`,500);l!==void 0&&l.length===0&&L("NATIVE_DATA_RESOURCE_INVARIANT_MESSAGE_INVALID",`${s}/message`);let f=Oe(d.expression,`${s}/expression`);if(f.kind==="nonBlankTextWhenOption"){Ne(f,["kind","optionField","optionValue","textField"],`${s}/expression`);let g=Te(f.optionField,`${s}/expression/optionField`),y=Te(f.textField,`${s}/expression/textField`),h=he(f.optionValue,`${s}/expression/optionValue`,128),u=n.get(g),I=n.get(y);return(!u||!I)&&L("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_UNKNOWN",`${s}/expression`),(u.type!=="option.single"||!["text.short","text.long"].includes(I.type)||!u.options?.some(R=>R.value===h))&&L("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_TYPES_INVALID",`${s}/expression`),{code:c,...l===void 0?{}:{message:l},expression:{kind:"nonBlankTextWhenOption",optionField:g,optionValue:h,textField:y}}}Ne(f,["leftField","operator","rightField"],`${s}/expression`);let p=Te(f.leftField,`${s}/expression/leftField`),m=Te(f.rightField,`${s}/expression/rightField`),E=n.get(p),A=n.get(m);(!E||!A)&&L("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_UNKNOWN",`${s}/expression`),E.type===A.type||["number.integer","number.decimal"].includes(E.type)&&["number.integer","number.decimal"].includes(A.type)||L("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_TYPES_INVALID",`${s}/expression`);let O=String(f.operator);return["eq","neq","gt","gte","lt","lte"].includes(O)||L("NATIVE_DATA_RESOURCE_INVARIANT_OPERATOR_INVALID",`${s}/expression/operator`),!["eq","neq"].includes(O)&&!["number.integer","number.decimal","date","time","datetime","text.short","text.long","text.rich","serial-number","uuid"].includes(E.type)&&L("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_TYPES_INVALID",`${s}/expression`),{code:c,...l===void 0?{}:{message:l},expression:{leftField:p,operator:O,rightField:m}}})}function ka(e,t,o,n){let r=o.get(e.resourceCode);r||L("NATIVE_DATA_FIELD_SOURCE_TARGET_MISSING",`${n}/resourceCode`);let i=new Map(r.fields.map(s=>[s.code,s])),a=i.get(e.labelField);(!a||!["text.short","text.long"].includes(a.type))&&L("NATIVE_DATA_FIELD_SOURCE_LABEL_INVALID",`${n}/labelField`);for(let s of["searchFields","descriptionFields","snapshotFields"])for(let d of e[s]||[])i.has(d)||L("NATIVE_DATA_FIELD_SOURCE_FIELD_MISSING",`${n}/${s}`);for(let[s,d]of(e.filterWhere||[]).entries())i.has(d.field)||L("NATIVE_DATA_FIELD_SOURCE_FILTER_FIELD_MISSING",`${n}/filterWhere/${s}/field`);for(let[s,d]of(e.filters||[]).entries())i.has(d.field)||L("NATIVE_DATA_FIELD_SOURCE_FILTER_FIELD_MISSING",`${n}/filters/${s}/field`),"binding"in d&&!t.has(d.binding.field)&&L("NATIVE_DATA_FIELD_SOURCE_BINDING_FIELD_MISSING",`${n}/filters/${s}/binding/field`)}function La(e,t,o){let n=`${o}/options`;if(e===void 0){Mr.has(t)&&L("NATIVE_DATA_FIELD_OPTIONS_REQUIRED",n);return}(!Mr.has(t)||!Array.isArray(e))&&L("NATIVE_DATA_FIELD_OPTIONS_TYPE_INVALID",n),(e.length<1||e.length>100)&&L("NATIVE_DATA_FIELD_OPTIONS_INVALID",n);let r=0,i=(a,s,d)=>{d>5&&L("NATIVE_DATA_FIELD_OPTIONS_DEPTH_EXCEEDED",s);let c=new Set;return a.map((l,f)=>{r+=1,r>1e3&&L("NATIVE_DATA_FIELD_OPTIONS_COUNT_EXCEEDED",n);let p=`${s}/${f}`,m=Oe(l,p);Ne(m,["label","value","description","color","children"],p);let E=he(m.label,`${p}/label`,500),A=he(m.value,`${p}/value`,500);c.has(A)&&L("NATIVE_DATA_FIELD_OPTION_VALUE_DUPLICATE",`${p}/value`),c.add(A);let b=en(m.description,`${p}/description`,2e3),O=en(m.color,`${p}/color`,64),g;return m.children!==void 0&&((!t.startsWith("cascade.")||!Array.isArray(m.children))&&L("NATIVE_DATA_FIELD_OPTION_CHILDREN_INVALID",`${p}/children`),(m.children.length<1||m.children.length>100)&&L("NATIVE_DATA_FIELD_OPTION_CHILDREN_INVALID",`${p}/children`),g=i(m.children,`${p}/children`,d+1)),{label:E,value:A,...b===void 0?{}:{description:b},...O===void 0?{}:{color:O},...g?{children:g}:{}}})};return i(e,n,1)}function $a(e,t,o){let n=`${o}/source`;if(e===void 0){Ur.has(t)&&L("NATIVE_DATA_FIELD_SOURCE_REQUIRED",n);return}Ur.has(t)||L("NATIVE_DATA_FIELD_SOURCE_TYPE_INVALID",n);let r=Oe(e,n);Ne(r,["kind","resourceCode","labelField","searchFields","descriptionFields","snapshotFields","filters","filterWhere","pageSize","loadMode","clearOnBindingChange"],n),r.kind!=="resource"&&L("NATIVE_DATA_FIELD_SOURCE_KIND_INVALID",`${n}/kind`);let i=he(r.resourceCode,`${n}/resourceCode`,64);po.test(i)||L("NATIVE_RESOURCE_CODE_INVALID",`${n}/resourceCode`);let a=Te(r.labelField,`${n}/labelField`),s=uo(r.searchFields,`${n}/searchFields`,10),d=uo(r.descriptionFields,`${n}/descriptionFields`,10),c=uo(r.snapshotFields,`${n}/snapshotFields`,50),l=Ye(r.pageSize,`${n}/pageSize`,1,100),f;r.loadMode!==void 0&&(["search","all"].includes(String(r.loadMode))||L("NATIVE_DATA_FIELD_SOURCE_LOAD_MODE_INVALID",`${n}/loadMode`),f=r.loadMode);let p=Br(r.filters,`${n}/filters`),m=Br(r.filterWhere,`${n}/filterWhere`,!1);return r.clearOnBindingChange!==void 0&&typeof r.clearOnBindingChange!="boolean"&&L("NATIVE_DATA_FIELD_SOURCE_BINDING_RESET_INVALID",`${n}/clearOnBindingChange`),{kind:"resource",resourceCode:i,labelField:a,...s?{searchFields:s}:{},...d?{descriptionFields:d}:{},...c?{snapshotFields:c}:{},...p?{filters:p}:{},...m?{filterWhere:m}:{},...l===void 0?{}:{pageSize:l},...f?{loadMode:f}:{},...r.clearOnBindingChange===void 0?{}:{clearOnBindingChange:r.clearOnBindingChange}}}function Br(e,t,o=!0){if(e!==void 0)return(!Array.isArray(e)||e.length>20)&&L("NATIVE_DATA_FIELD_SOURCE_FILTERS_INVALID",t),e.map((n,r)=>{let i=`${t}/${r}`,a=Oe(n,i),s=Object.prototype.hasOwnProperty.call(a,"value"),d=Object.prototype.hasOwnProperty.call(a,"binding");Ne(a,s?["field","operator","value"]:["field","operator","binding"],i),(s===d||d&&!o)&&L("NATIVE_DATA_FIELD_SOURCE_FILTER_VALUE_INVALID",i);let c=Te(a.field,`${i}/field`);["eq","in"].includes(String(a.operator))||L("NATIVE_DATA_FIELD_SOURCE_FILTER_OPERATOR_INVALID",`${i}/operator`);let l=a.operator;if(s)return{field:c,operator:l,value:a.value};let f=Oe(a.binding,`${i}/binding`);return Ne(f,["kind","field"],`${i}/binding`),f.kind!=="field"&&L("NATIVE_DATA_FIELD_SOURCE_BINDING_KIND_INVALID",`${i}/binding/kind`),{field:c,operator:l,binding:{kind:"field",field:Te(f.field,`${i}/binding/field`)}}})}function Pa(e,t,o){let n={};if(e.maxLength!==void 0&&(["text.short","text.long","text.rich"].includes(t)||L("NATIVE_DATA_FIELD_MAX_LENGTH_TYPE_INVALID",`${o}/maxLength`),n.maxLength=Qt(e.maxLength,`${o}/maxLength`,1,1e6)),(e.precision!==void 0||e.scale!==void 0)&&((t!=="number.decimal"||e.precision===void 0)&&L("NATIVE_DATA_FIELD_DECIMAL_CONFIG_INVALID",o),n.precision=Qt(e.precision,`${o}/precision`,1,1e3),n.scale=e.scale===void 0?0:Qt(e.scale,`${o}/scale`,0,n.precision)),e.min!==void 0||e.max!==void 0){["number.integer","number.decimal"].includes(t)||L("NATIVE_DATA_FIELD_NUMERIC_BOUNDS_TYPE_INVALID",o);let r=Kr(e.min,`${o}/min`),i=Kr(e.max,`${o}/max`);t==="number.integer"&&[r,i].some(a=>a!==void 0&&!Number.isSafeInteger(a))&&L("NATIVE_DATA_FIELD_NUMERIC_BOUNDS_INVALID",o),r!==void 0&&i!==void 0&&r>i&&L("NATIVE_DATA_FIELD_NUMERIC_BOUNDS_INVALID",o),r!==void 0&&(n.min=r),i!==void 0&&(n.max=i)}return e.timePrecision!==void 0&&((!["time","datetime","datetime-range"].includes(t)||!["minute","second"].includes(e.timePrecision))&&L("NATIVE_DATA_FIELD_TIME_PRECISION_INVALID",`${o}/timePrecision`),n.timePrecision=e.timePrecision),n}function va(e,t,o){if(e===void 0)return;let n=`${o}/file`;["file","image","signature"].includes(t)||L("NATIVE_DATA_FIELD_FILE_TYPE_INVALID",n);let r=Oe(e,n);Ne(r,["maxCount","maxSizeMb","accept"],n);let i=Ye(r.maxCount,`${n}/maxCount`,1,100);t==="signature"&&i!==void 0&&i!==1&&L("NATIVE_DATA_FIELD_SIGNATURE_COUNT_INVALID",`${n}/maxCount`);let a=Ye(r.maxSizeMb,`${n}/maxSizeMb`,1,1024),s;return r.accept!==void 0&&((!Array.isArray(r.accept)||r.accept.length>50)&&L("NATIVE_DATA_FIELD_FILE_ACCEPT_INVALID",`${n}/accept`),s=r.accept.map((d,c)=>he(d,`${n}/accept/${c}`,255)),new Set(s).size!==s.length&&L("NATIVE_DATA_FIELD_FILE_ACCEPT_INVALID",`${n}/accept`)),{...i===void 0?{}:{maxCount:i},...a===void 0?{}:{maxSizeMb:a},...s===void 0?{}:{accept:s}}}function Va(e,t,o){let n=`${o}/serial`;if(e===void 0){t==="serial-number"&&L("NATIVE_DATA_FIELD_SERIAL_REQUIRED",n);return}t!=="serial-number"&&L("NATIVE_DATA_FIELD_SERIAL_TYPE_INVALID",n);let r=Oe(e,n);Ne(r,["prefix","digits","start"],n);let i=en(r.prefix,`${n}/prefix`,64),a=Ye(r.digits,`${n}/digits`,1,32),s=Ye(r.start,`${n}/start`,0,Number.MAX_SAFE_INTEGER);return{...i===void 0?{}:{prefix:i},...a===void 0?{}:{digits:a},...s===void 0?{}:{start:s}}}function Fa(e,t,o){let n=`${o}/subtable`;if(e===void 0){t==="subtable"&&L("NATIVE_DATA_FIELD_SUBTABLE_REQUIRED",n);return}t!=="subtable"&&L("NATIVE_DATA_FIELD_SUBTABLE_TYPE_INVALID",n);let r=Oe(e,n);Ne(r,["resourceCode","foreignKey","orderField","minRows","maxRows"],n);let i=he(r.resourceCode,`${n}/resourceCode`,64);po.test(i)||L("NATIVE_RESOURCE_CODE_INVALID",`${n}/resourceCode`);let a=Te(r.foreignKey,`${n}/foreignKey`),s=Te(r.orderField,`${n}/orderField`);s===a&&L("NATIVE_DATA_FIELD_SUBTABLE_ORDER_FIELD_INVALID",`${n}/orderField`);let d=Ye(r.maxRows,`${n}/maxRows`,1,He),c=Ye(r.minRows,`${n}/minRows`,0,He);return(c??0)>(d??20)&&L("NATIVE_DATA_FIELD_SUBTABLE_MIN_ROWS_INVALID",`${n}/minRows`),{resourceCode:i,foreignKey:a,orderField:s,...c===void 0?{}:{minRows:c},...d===void 0?{}:{maxRows:d}}}function uo(e,t,o){if(e===void 0)return;(!Array.isArray(e)||e.length>o)&&L("NATIVE_DATA_FIELD_SOURCE_FIELDS_INVALID",t);let n=e.map((r,i)=>Te(r,`${t}/${i}`));return new Set(n).size!==n.length&&L("NATIVE_DATA_FIELD_SOURCE_FIELDS_INVALID",t),n}function Te(e,t){let o=he(e,t,63);return Gr.test(o)||L("NATIVE_FIELD_CODE_INVALID",t),o}function Oe(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&L("NATIVE_OBJECT_REQUIRED",t),e}function Ne(e,t,o){let n=new Set(t);for(let r of Object.keys(e))n.has(r)||L("NATIVE_PROPERTY_UNKNOWN",`${o}/${r}`)}function he(e,t,o){return(typeof e!="string"||e.length===0||e.length>o)&&L("NATIVE_STRING_INVALID",t),e}function en(e,t,o){if(e!==void 0)return(typeof e!="string"||e.length>o)&&L("NATIVE_STRING_INVALID",t),e}function fo(e,t){if(e!==void 0)return typeof e!="boolean"&&L("NATIVE_BOOLEAN_REQUIRED",t),e}function Ye(e,t,o,n){if(e!==void 0)return Qt(e,t,o,n)}function Kr(e,t){if(e!==void 0)return(typeof e!="number"||!Number.isFinite(e))&&L("NATIVE_NUMBER_REQUIRED",t),e}function Qt(e,t,o,n){return(!Number.isSafeInteger(e)||Number(e)<o||Number(e)>n)&&L("NATIVE_INTEGER_OUT_OF_RANGE",t),Number(e)}function L(e,t){throw new Ce(e,t)}var on=["created_by","updated_by","created_at","updated_at"];function Tt(e){return on.includes(e)}function Hr(e){return on.some(t=>Object.prototype.hasOwnProperty.call(e.fieldPolicies||{},t))}var Wa=go.map(e=>e.code);function Yr(e){return Wa.includes(e)}var xa=["eq","neq","gt","gte","lt","lte","contains","startsWith","endsWith","in","between","has","hasAny","hasAll","overlaps","containedBy","jsonContains","isEmpty","isNotEmpty"],ja=new Set(xa);function Ql(e){return ja.has(String(e))}var Eo=["eq","neq","contains","startsWith","endsWith","in","isEmpty","isNotEmpty"],Ct=["eq","neq","gt","gte","lt","lte","between","in","isEmpty"],Ma=["eq","neq","in","isEmpty"],rn=["eq","neq","in","isEmpty","isNotEmpty"],ut=["has","hasAny","hasAll","isEmpty","isNotEmpty"],Xr=["overlaps","contains","containedBy","isEmpty"],Io=["jsonContains","isEmpty","isNotEmpty"],yo=["isEmpty","isNotEmpty"],Ua={"text.short":Eo,"text.long":Eo,"text.rich":Eo,"number.integer":Ct,"number.decimal":Ct,boolean:Ma,date:Ct,time:Ct,datetime:Ct,"date-range":Xr,"datetime-range":Xr,"option.single":rn,"option.multiple":ut,"cascade.single":ut,"cascade.multiple":ut,"user.single":rn,"user.multiple":ut,"department.single":rn,"department.multiple":ut,"resource-ref.single":rn,"resource-ref.multiple":ut,file:yo,image:yo,signature:yo,address:Io,location:Io,uuid:["eq","neq","in","isEmpty"],json:Io,"serial-number":["eq","neq","in","contains","startsWith"],subtable:[]},Ba=new Set(["text.short","text.long","text.rich","option.single","user.single","department.single","resource-ref.single","serial-number"]),Ka=new Set(["option.multiple","cascade.single","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","file","image","signature","address","location","json","subtable"]);function Qr(e){return Ua[e]}function eu(e,t){return Qr(e).includes(t)}function Oo(e){return Ba.has(e)}function St(e){return!Ka.has(e)}function ei(e){return Qr(e).length>0}var Zr=new Set(["number.integer","number.decimal"]),ti=new Set(["text.short","text.long","number.integer","number.decimal","date","time","datetime","serial-number"]),Ga=new Set([...ti,"boolean","uuid"]),qa=new Set(["option.single","user.single","department.single","resource-ref.single"]);function tu(e,t){return t==="sum"||t==="avg"?Zr.has(e)?{valueExpression:"column",numericResult:!0}:null:t==="min"||t==="max"?ti.has(e)?{valueExpression:"column",numericResult:Zr.has(e)}:null:qa.has(e)?{valueExpression:"snapshot-value",numericResult:!0}:Ga.has(e)?{valueExpression:"column",numericResult:!0}:null}var No=["version","maxBytes","fields"];function oi(e,t){if(e===void 0)return;let o=bo(e,t);ni(o,No,t);let n=sn(o.version,`${t}/version`,1,1e6),r=sn(o.maxBytes,`${t}/maxBytes`,2,196608);(!n||!r)&&ue("NATIVE_DATA_DRAFT_STATE_SCHEMA_INVALID",t);let i=bo(o.fields,`${t}/fields`),a=Object.entries(i);(!a.length||a.length>50)&&ue("NATIVE_DATA_DRAFT_STATE_FIELDS_INVALID",`${t}/fields`);for(let[s,d]of a){let c=`${t}/fields/${s}`;/^[A-Za-z][A-Za-z0-9_]{0,62}$/.test(s)||ue("NATIVE_DATA_DRAFT_STATE_FIELD_CODE_INVALID",c);let l=bo(d,c),f=ri(l.type,`${c}/type`,32),p=f==="string"?["type","required","maxLength","enum"]:f==="json.object"?["type","required","maxBytes"]:["type","required"];if(["string","number","integer","boolean","json.object"].includes(f)||ue("NATIVE_DATA_DRAFT_STATE_FIELD_TYPE_INVALID",`${c}/type`),ni(l,p,c),Ja(l.required,`${c}/required`),f==="string"){let m=sn(l.maxLength,`${c}/maxLength`,1,196608);m||ue("NATIVE_DATA_DRAFT_STATE_FIELD_INVALID",c),l.enum!==void 0&&za(l.enum,`${c}/enum`,100,!1).some(A=>A.length>m)&&ue("NATIVE_DATA_DRAFT_STATE_FIELD_INVALID",`${c}/enum`)}else if(f==="json.object"){let m=sn(l.maxBytes,`${c}/maxBytes`,2,65536);(!m||m>r)&&ue("NATIVE_DATA_DRAFT_STATE_FIELD_INVALID",c)}}}function za(e,t,o,n){(!Array.isArray(e)||!n&&e.length===0||e.length>o)&&ue("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t);let r=e.map((i,a)=>ri(i,`${t}/${a}`,255));return new Set(r).size!==r.length&&ue("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t),r}function bo(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&ue("NATIVE_OBJECT_REQUIRED",t),e}function ni(e,t,o){let n=new Set(t);for(let r of Object.keys(e))n.has(r)||ue("NATIVE_PROPERTY_UNKNOWN",`${o}/${r}`)}function ri(e,t,o){return(typeof e!="string"||e.length===0||e.length>o)&&ue("NATIVE_STRING_INVALID",t),e}function Ja(e,t){e!==void 0&&typeof e!="boolean"&&ue("NATIVE_BOOLEAN_REQUIRED",t)}function sn(e,t,o,n){return(!Number.isSafeInteger(e)||Number(e)<o||Number(e)>n)&&ue("NATIVE_INTEGER_INVALID",t),Number(e)}function ue(e,t){throw new Ce(e,t)}var Ha=500,Fe={surface:["mutationOwner","generated","fields","list","form","detail","mobile","views"],generated:["list","detail","create","update","delete"],field:["label","type","widget","section","requiredHint","system","hidden","readCapabilities","createCapabilities","updateCapabilities","maxLength","precision","scale","exactDecimal","min","max","rangeBoundary","maxCount","maxSizeMb","accept","options","list","searchable","sortable","source","userCandidates","timePrecision","serial","subtable"],list:["actions","fieldOrder","defaultPageSize","searchableFields","filterFields","defaultSort"],defaultSort:["field","order"],form:["layout","fieldOrder","draftState"],detail:["layout","fieldOrder"],layout:["layout","fieldOrder","draftState"],draftState:No,mobile:["enabled"]},Ya={"text.short":["text","email","phone"],"text.long":["textarea"],"text.rich":["rich-text"],"number.integer":["number","rating"],"number.decimal":["number","money","percent"],boolean:["switch"],date:["date"],time:["time"],datetime:["datetime"],"date-range":["date-range"],"datetime-range":["datetime-range"],"option.single":["select","radio"],"option.multiple":["multi-select","checkbox"],"cascade.single":["cascade"],"cascade.multiple":["cascade"],"user.single":["directory-user"],"user.multiple":["directory-user"],"department.single":["directory-department","scope"],"department.multiple":["directory-department","scope"],"resource-ref.single":["select","radio","resource"],"resource-ref.multiple":["multi-select","checkbox","resource"],file:["attachment"],image:["image"],signature:["signature"],address:["address"],location:["location"],uuid:["readonly"],json:["json"],"serial-number":["readonly"],subtable:["subtable"]};function wo(e,t,o){if(e===void 0)return;let n=de(e,o);Se(n,Fe.surface,o);let r=n.mutationOwner===void 0?"native":$e(n.mutationOwner,`${o}/mutationOwner`,16);["native","action","readonly","workflow","queued-command"].includes(r)||j("NATIVE_DATA_SURFACE_MUTATION_OWNER_INVALID",`${o}/mutationOwner`);let i=n.generated===void 0?{}:de(n.generated,`${o}/generated`);Se(i,Fe.generated,`${o}/generated`);for(let d of Fe.generated)Ro(i[d],`${o}/generated/${d}`);if(r!=="native")for(let d of["create","update","delete"])i[d]===!0&&j("NATIVE_DATA_SURFACE_MUTATION_OWNER_CONFLICT",`${o}/generated/${d}`);let a=new Map(t.map(d=>[d.code,d])),s=de(n.fields,`${o}/fields`);for(let d of Object.keys(s))a.has(d)||j("NATIVE_DATA_SURFACE_FIELD_MISSING",`${o}/fields/${d}`);for(let d of t)Object.prototype.hasOwnProperty.call(s,d.code)||j("NATIVE_DATA_SURFACE_FIELD_REQUIRED",`${o}/fields/${d.code}`),Za(s[d.code],d,`${o}/fields/${d.code}`);for(let d of["create","update"]){let c=i[d]??r==="native",l=t.some(f=>{let p=de(s[f.code],`${o}/fields/${f.code}`);return si(f,p,d)});c&&!l&&j("NATIVE_DATA_SURFACE_WRITABLE_FIELDS_REQUIRED",`${o}/generated/${d}`)}if(Qa(n.list,a,`${o}/list`),ii(n.form,a,`${o}/form`,"form"),ii(n.detail,a,`${o}/detail`,"detail"),n.mobile!==void 0){let d=de(n.mobile,`${o}/mobile`);Se(d,Fe.mobile,`${o}/mobile`),Ro(d.enabled,`${o}/mobile/enabled`)}Xa(n,t,o)}function To(e,t){let o=e.views?.find(r=>r.code===t);o||j("NATIVE_DATA_VIEW_NOT_FOUND",`/surface/views/${t}`);let n=new Map((o.sections||[]).flatMap(r=>r.fields.map(i=>[i,r.title])));return{mutationOwner:e.mutationOwner||"native",generated:o.generated,list:o.list,form:o.form,detail:o.detail,mobile:o.mobile,fields:Object.fromEntries(Object.entries(e.fields).map(([r,i])=>{let a={...i};delete a.section;let s=n.get(r);return[r,{...a,...s?{section:s}:{},list:o.list.fieldOrder.includes(r)}]}))}}function Xa(e,t,o){if(e.views===void 0)return;(!Array.isArray(e.views)||e.views.length>20)&&j("NATIVE_DATA_VIEWS_LIMIT_INVALID",`${o}/views`);let n=new Set;e.views.forEach((r,i)=>{let a=`${o}/views/${i}`,s=de(r,a);Se(s,["code","name","generated","list","form","detail","mobile","sections"],a);let d=$e(s.code,`${a}/code`,64);(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(d)||n.has(d))&&j("NATIVE_DATA_VIEW_CODE_INVALID",`${a}/code`),n.add(d),$e(s.name,`${a}/name`,255),de(s.generated,`${a}/generated`),de(s.mobile,`${a}/mobile`);for(let l of["list","detail","create","update","delete"])typeof s.generated[l]!="boolean"&&j("NATIVE_DATA_VIEW_OPERATION_INVALID",`${a}/generated/${l}`);typeof s.mobile.enabled!="boolean"&&j("NATIVE_DATA_VIEW_MOBILE_INVALID",`${a}/mobile/enabled`);for(let l of["list","form","detail"]){let f=de(s[l],`${a}/${l}`),p=ft(f.fieldOrder,`${a}/${l}/fieldOrder`,500,!0);for(let m of p){let E=e.fields[m];(!E||(E.hidden??E.system)===!0)&&j("NATIVE_DATA_VIEW_FIELD_INVALID",`${a}/${l}/fieldOrder`)}}if(s.sections!==void 0){(!Array.isArray(s.sections)||s.sections.length>100)&&j("NATIVE_DATA_VIEW_SECTIONS_INVALID",`${a}/sections`);let l=new Set;s.sections.forEach((f,p)=>{let m=`${a}/sections/${p}`,E=de(f,m);Se(E,["title","fields"],m),$e(E.title,`${m}/title`,255);for(let A of ft(E.fields,`${m}/fields`,100,!0)){let b=e.fields[A];(!b||(b.hidden??b.system)===!0||l.has(A))&&j("NATIVE_DATA_VIEW_FIELD_INVALID",`${m}/fields`),l.add(A)}})}let c=To(e,d);if(wo(c,t,a),s.generated.create!==!1&&(e.mutationOwner||"native")==="native")for(let l of t)nn(l,e.fields[l.code])&&si(l,e.fields[l.code],"create")&&!s.form.fieldOrder.includes(l.code)&&j("NATIVE_DATA_VIEW_CREATE_REQUIRED_FIELD_MISSING",`${a}/form/fieldOrder`)})}function si(e,t,o){if(e.type==="serial-number"||t.system===!0)return!1;let n=t[`${o}Capabilities`];return Array.isArray(n)&&n.length>0}function Za(e,t,o){let n=de(e,o);Se(n,Fe.field,o),$e(n.label,`${o}/label`,500),n.type!==t.type&&j("NATIVE_DATA_SURFACE_FIELD_TYPE_MISMATCH",`${o}/type`);let r=$e(n.widget,`${o}/widget`,64);Ya[t.type].includes(r)||j("NATIVE_DATA_SURFACE_WIDGET_INCOMPATIBLE",`${o}/widget`),nd(n.section,`${o}/section`,255);for(let i of["requiredHint","system","hidden","list","searchable","sortable"])Ro(n[i],`${o}/${i}`);n.searchable===!0&&!Oo(t.type)&&j("NATIVE_DATA_SURFACE_SEARCH_UNSUPPORTED",`${o}/searchable`),n.sortable===!0&&!St(t.type)&&j("NATIVE_DATA_SURFACE_SORT_UNSUPPORTED",`${o}/sortable`);for(let i of["readCapabilities","createCapabilities","updateCapabilities"])ft(n[i],`${o}/${i}`,100,!0);if(n.maxCount!==void 0&&(!Number.isSafeInteger(n.maxCount)||Number(n.maxCount)<1||Number(n.maxCount)>100)&&j("NATIVE_DATA_SURFACE_MAX_COUNT_INVALID",`${o}/maxCount`),n.maxSizeMb!==void 0&&(!Number.isSafeInteger(n.maxSizeMb)||Number(n.maxSizeMb)<1||Number(n.maxSizeMb)>1024)&&j("NATIVE_DATA_SURFACE_MAX_SIZE_INVALID",`${o}/maxSizeMb`),n.accept!==void 0){let i=Array.isArray(n.accept)?n.accept:[n.accept];ft(i,`${o}/accept`,50,!1)}for(let i of["maxLength","precision","scale","exactDecimal","min","max","rangeBoundary","options","source","userCandidates","timePrecision","serial","subtable"])ed(n,t,i,o);td(n,t,o)}function Qa(e,t,o){if(e===void 0)return;let n=de(e,o);if(Se(n,Fe.list,o),n.actions!==void 0){let r=de(n.actions,`${o}/actions`);Se(r,["import","export"],`${o}/actions`);for(let i of["import","export"])r[i]!==void 0&&typeof r[i]!="boolean"&&j("NATIVE_DATA_SURFACE_LIST_ACTION_INVALID",`${o}/actions/${i}`)}if(n.fieldOrder!==void 0)for(let r of ft(n.fieldOrder,`${o}/fieldOrder`,500,!0))t.has(r)||j("NATIVE_DATA_SURFACE_LIST_FIELD_INVALID",`${o}/fieldOrder`);n.defaultPageSize!==void 0&&(!Number.isSafeInteger(n.defaultPageSize)||Number(n.defaultPageSize)<1||Number(n.defaultPageSize)>200)&&j("NATIVE_DATA_SURFACE_PAGE_SIZE_INVALID",`${o}/defaultPageSize`);for(let[r,i]of[["searchableFields",Oo],["filterFields",ei]]){if(n[r]===void 0)continue;let a=ft(n[r],`${o}/${r}`,100,!0);for(let s of a){let d=t.get(s);(!d||!i(d.type))&&j("NATIVE_DATA_SURFACE_LIST_FIELD_INVALID",`${o}/${r}`)}}if(n.defaultSort!==void 0){let r=de(n.defaultSort,`${o}/defaultSort`);Se(r,Fe.defaultSort,`${o}/defaultSort`);let i=$e(r.field,`${o}/defaultSort/field`,63),a=t.get(i);!Yr(i)&&(!a||!St(a.type))&&j("NATIVE_DATA_SURFACE_SORT_UNSUPPORTED",`${o}/defaultSort/field`),r.order!==void 0&&!["asc","desc"].includes(r.order)&&j("NATIVE_DATA_SURFACE_SORT_ORDER_INVALID",`${o}/defaultSort/order`)}}function ii(e,t,o,n){if(e===void 0)return;let r=de(e,o);if(Se(r,Fe[n],o),r.layout!==void 0&&!["flat","sections"].includes(r.layout)&&j("NATIVE_DATA_SURFACE_LAYOUT_INVALID",`${o}/layout`),r.fieldOrder!==void 0){let i=`${o}/fieldOrder`;(!Array.isArray(r.fieldOrder)||r.fieldOrder.length>t.size||r.fieldOrder.length>Ha)&&j("NATIVE_DATA_SURFACE_FIELD_ORDER_INVALID",i);let a=r.fieldOrder.map((s,d)=>$e(s,`${i}/${d}`,63));new Set(a).size!==a.length&&j("NATIVE_DATA_SURFACE_FIELD_ORDER_INVALID",i),a.forEach((s,d)=>{t.has(s)||j("NATIVE_DATA_SURFACE_FIELD_ORDER_FIELD_MISSING",`${i}/${d}`)})}n==="form"&&oi(r.draftState,`${o}/draftState`)}function ed(e,t,o,n){e[o]===void 0&&t[o]===void 0||((e[o]===void 0||t[o]===void 0)&&j("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${n}/${o}`),Q(e[o])!==Q(t[o])&&j("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${n}/${o}`))}function td(e,t,o){let n=t.file||{},r={...e.maxCount===void 0?{}:{maxCount:e.maxCount},...e.maxSizeMb===void 0?{}:{maxSizeMb:e.maxSizeMb},...e.accept===void 0?{}:{accept:ho(e.accept)}};for(let i of["maxCount","maxSizeMb","accept"]){if(r[i]===void 0&&n[i]===void 0)continue;(r[i]===void 0||n[i]===void 0)&&j("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${o}/${i}`);let a=i==="accept"?ho(r[i]):r[i],s=i==="accept"?ho(n[i]):n[i];Q(a)!==Q(s)&&j("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${o}/${i}`)}}function ho(e){return(Array.isArray(e)?[...e]:[e]).sort((t,o)=>{let n=String(t),r=String(o);return n===r?0:n<r?-1:1})}function ft(e,t,o,n){(!Array.isArray(e)||!n&&e.length===0||e.length>o)&&j("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t);let r=e.map((i,a)=>$e(i,`${t}/${a}`,255));return new Set(r).size!==r.length&&j("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t),r}function de(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&j("NATIVE_OBJECT_REQUIRED",t),e}function Se(e,t,o){let n=new Set(t);for(let r of Object.keys(e))n.has(r)||j("NATIVE_PROPERTY_UNKNOWN",`${o}/${r}`)}function $e(e,t,o){return(typeof e!="string"||e.length===0||e.length>o)&&j("NATIVE_STRING_INVALID",t),e}function nd(e,t,o){e!==void 0&&(typeof e!="string"||e.length>o)&&j("NATIVE_STRING_INVALID",t)}function Ro(e,t){e!==void 0&&typeof e!="boolean"&&j("NATIVE_BOOLEAN_REQUIRED",t)}function j(e,t){throw new Ce(e,t)}var Dt=class extends Error{constructor(o,n){super(`${o}: ${n}`);this.pointer=o;this.reason=n}pointer;reason;code="NATIVE_MANAGED_CONCURRENCY_INVALID"};function ai(e,t,o){if(e===void 0)return;let n=(g,y)=>{throw new Dt(g,y)},r=(g,y,h)=>((!g||typeof g!="object"||Array.isArray(g)||Object.keys(g).some(u=>!h.includes(u)))&&n(y,"object contains unsupported properties"),g),i=(g,y,h,u)=>{(!Number.isSafeInteger(g)||g<y||g>h)&&n(u,`expected integer ${y}..${h}`)},a=(g,y)=>{(typeof g!="string"||!/^[a-z][a-z0-9_-]{0,63}$/.test(g))&&n(y,"invalid code")},s=(g,y,h)=>((!Array.isArray(g)||g.length>y)&&n(h,"array exceeds bound"),g),d=(g,y)=>{let h=t.find(u=>u.code===g);return h||n(y,"unknown resource"),h},c=(g,y,h)=>{let u=g.schema.fields.find(I=>I.code===y);return!u&&y!=="id"&&n(h,"unknown field"),u},l=(g,y,h=!1)=>{r(g,y,Object.keys(g||{})),Object.keys(g).length>8&&n(y,"at most eight parameters");for(let[u,I]of Object.entries(g))if(a(u,y),r(I,y,["type","values","minimum","maximum","minLength","maxLength"]),I.type==="uuid")Object.keys(I).length!==1&&n(y,"uuid has no options");else if(h&&I.type==="boolean")r(I,y,["type"]);else if(h&&I.type==="string"&&I.values===void 0)r(I,y,["type","minLength","maxLength"]),i(I.maxLength,1,256,y),I.minLength!==void 0&&i(I.minLength,0,I.maxLength,y);else if(I.type==="string"){r(I,y,["type","values"]);let R=s(I.values,100,y);(!R.length||R.some(w=>typeof w!="string"||w.length>128)||new Set(R).size!==R.length)&&n(y,"finite string values required")}else I.type==="integer"?(r(I,y,["type","minimum","maximum"]),i(I.minimum,0,1e6,y),i(I.maximum,I.minimum,I.minimum+1e3,y)):n(y,"unsupported parameter type")},f=(g,y,h,u=!1)=>{r(g,h,["from","key","value"]),!(g.from==="input"&&Object.keys(g).length===2&&Object.hasOwn(y,g.key))&&((g.from==="actor"||u&&g.from==="allocation")&&Object.keys(g).length===1||g.from==="literal"&&Object.keys(g).length===2&&Object.hasOwn(g,"value")&&(g.value===null||["string","boolean"].includes(typeof g.value)||typeof g.value=="number"&&Number.isFinite(g.value))&&JSON.stringify(g.value).length<=512||n(h,"invalid binding"))},p=(g,y,h)=>{f(g,y,h),!(g.from==="input"&&y[g.key].type==="uuid")&&(g.from==="literal"&&typeof g.value=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(g.value)||n(h,"record and allocation identifiers require a UUID binding"))},m=(g,y,h)=>{f(g,y,h),!(g.from==="input"&&y[g.key].type==="integer"&&y[g.key].minimum>=1)&&(g.from==="literal"&&Number.isSafeInteger(g.value)&&g.value>=1||n(h,"expectedRevision requires a positive integer binding"))},E="/data/concurrency";JSON.stringify(e).length>131072&&n(E,"declaration exceeds 128 KiB");let A=r(e,E,["version","admission","reads","quotas","commands"]);A.version!==1&&n(E,"unsupported version"),r(A.admission,E,["perSecond","burst","maxInFlight"]),i(A.admission.perSecond,1,1e3,E),i(A.admission.burst,1,1e3,E),i(A.admission.maxInFlight,1,1e3,E);let b=(g,y)=>{let h=new Set;for(let u of g)a(u?.code,y),h.has(u.code)&&n(y,"duplicate code"),h.add(u.code)};b(s(A.reads,32,E),E),b(s(A.quotas,16,E),E),b(s(A.commands,32,E),E);for(let g of A.reads){let y=`${E}/reads/${g.code}`;r(g,y,["code","resourceCode","parameters","select","where","limit","scope","freshSeconds","staleSeconds","maxKeys","sourcePerSecond","dependencies"]);let h=d(g.resourceCode,y);l(g.parameters,y),["subject","application"].includes(g.scope)||n(y,"invalid cache scope"),g.scope==="application"&&h.dataPolicyCode&&n(y,"shared cache cannot bypass a row policy");let u=s(g.select,32,y);u.length||n(y,"select required"),u.forEach(R=>c(h,R,y));let I=s(g.dependencies,64,y);I.forEach(R=>c(h,R,y));for(let R of s(g.where||[],8,y))r(R,y,["field","value"]),c(h,R.field,y),f(R.value,g.parameters,y),g.scope==="application"&&R.value.from==="actor"&&n(y,"actor requires subject cache"),I.includes(R.field)||n(y,"filter dependency missing");u.some(R=>!I.includes(R))&&n(y,"selected field dependency missing"),i(g.limit,1,100,y),i(g.freshSeconds,1,300,y),i(g.staleSeconds,0,300,y),i(g.maxKeys,1,1e4,y),i(g.sourcePerSecond,1,20,y)}for(let g of A.quotas){let y=`${E}/quotas/${g.code}`;r(g,y,["code","sourceResource","capacityField","allocationResource","allocationField","reservationSeconds"]);let h=d(g.sourceResource,y),u=d(g.allocationResource,y);c(h,g.capacityField,y)?.type!=="number.integer"&&n(y,"capacity must be an integer"),(c(u,g.allocationField,y)?.type!=="uuid"||c(u,g.allocationField,y)?.nullable!==!1)&&n(y,"allocation reference must be a uuid"),u.surface?.mutationOwner!=="queued-command"&&n(y,"allocation model must be command owned"),g.reservationSeconds!==void 0&&i(g.reservationSeconds,10,86400,y)}new Set(A.quotas.map(g=>g.allocationResource)).size!==A.quotas.length&&n(E,"an allocation model has exactly one pool owner");for(let g of A.commands){let y=`${E}/commands/${g.code}`;r(g,y,["code","mode","intake","execution","capability","parameters","resourceKey","admission","deadlineSeconds","guards","operations","quota"]),g.mode!==void 0&&!["permit","durable"].includes(g.mode)&&n(y,"unsupported mode");let h=g.mode==="durable";if(l(g.parameters,y,h),f(g.resourceKey,g.parameters,y),o.some(u=>u.code===g.capability)||n(y,"command capability must be declared"),r(g.admission,y,["perSecond","burst","maxInFlight","maxQueue","maxWaitSeconds","permitSeconds"]),i(g.admission.perSecond,1,A.admission.perSecond,y),i(g.admission.burst,1,A.admission.burst,y),i(g.admission.maxInFlight,1,A.admission.maxInFlight,y),i(g.admission.maxQueue,1,1e4,y),i(g.admission.maxWaitSeconds,1,3600,y),(!h||g.admission.permitSeconds!==void 0)&&i(g.admission.permitSeconds,5,60,y),i(g.deadlineSeconds,10,3600,y),h){(g.operations!==void 0||g.guards!==void 0||g.quota!==void 0)&&n(y,"backend-plan does not accept static operations, guards or quota"),r(g.intake,y,["perSecond","burst","maxInFlight"]);for(let R of["perSecond","burst","maxInFlight"])i(g.intake[R],1,1e3,y);let u=r(g.execution,y,["kind","handlerCode","timeoutMs","resources","directory"]);u.kind!=="backend-plan"&&n(y,"durable requires backend-plan"),a(u.handlerCode,y),i(u.timeoutMs,100,3e4,y);let I=s(u.resources,32,y);I.length||n(y,"execution resources required"),new Set(I.map(R=>R.resourceCode)).size!==I.length&&n(y,"duplicate execution resource");for(let R of I){r(R,y,["resourceCode","readFields","writeOperations","writeFields"]);let w=d(R.resourceCode,y);for(let S of["readFields","writeFields"]){let P=s(R[S],64,y);new Set(P).size!==P.length&&n(y,"duplicate field"),P.forEach(V=>{S==="readFields"&&lt.has(V)||c(w,V,y)})}let C=s(R.writeOperations,3,y);(new Set(C).size!==C.length||C.some(S=>!["create","update","increment"].includes(S)))&&n(y,"unsupported execution operation"),R.writeFields.some(S=>["id","revision","created_by","updated_by","created_at","updated_at"].includes(S))&&n(y,"record metadata is platform owned"),!C.length&&R.writeFields.length&&n(y,"write fields require an operation"),C.length&&!R.writeFields.length&&n(y,"write operations require fields"),A.quotas.some(S=>S.allocationResource===R.resourceCode)&&C.length&&n(y,"allocation references remain owned by their pool command")}if(u.directory!==void 0){r(u.directory,y,["mode","fields"]),u.directory.mode!=="current-initiator"&&n(y,"only current initiator allowed");let R=s(u.directory.fields,5,y);(!R.length||new Set(R).size!==R.length||R.some(w=>!["displayName","employeeNumber","primaryDepartment","departments","phone"].includes(w)))&&n(y,"unsupported directory fields")}continue}(g.execution!==void 0||g.intake!==void 0)&&n(y,"execution and intake require durable mode");for(let u of s(g.guards||[],8,y)){r(u,y,["resourceCode","id","conditions"]);let I=d(u.resourceCode,y);p(u.id,g.parameters,y);for(let R of s(u.conditions,16,y)){r(R,y,["kind","field","operator","value"]);let w=c(I,R.field,y);["eq","neq","lt","lte","gt","gte"].includes(R.operator)||n(y,"unsupported guard"),R.kind==="database-now"?(w?.type!=="datetime"||!["lt","lte","gt","gte"].includes(R.operator)||R.value!==void 0)&&n(y,"database-now requires datetime and an ordering operator"):(R.kind!==void 0&&R.kind!=="value"&&n(y,"unsupported condition kind"),f(R.value,g.parameters,y))}}for(let u of s(g.operations,8,y)){r(u,y,["operation","resourceCode","id","expectedRevision","data"]);let I=d(u.resourceCode,y);I.surface?.mutationOwner!=="queued-command"&&n(y,"command mutations require command owned models");let R=A.quotas.find(w=>w.allocationResource===u.resourceCode);R&&(u.operation==="create"?g.quota?.action!=="allocate"||g.quota.pool!==R.code:Object.hasOwn(u.data||{},R.allocationField))&&n(y,"allocation references are owned by their pool command"),["create","update"].includes(u.operation)||n(y,"unsupported operation"),u.operation==="update"?(p(u.id,g.parameters,y),m(u.expectedRevision,g.parameters,y)):(u.id!==void 0||u.expectedRevision!==void 0)&&n(y,"create has no caller supplied id/revision"),r(u.data,y,Object.keys(u.data||{})),Object.keys(u.data).length>32&&n(y,"too many fields");for(let[w,C]of Object.entries(u.data))w==="id"&&n(y,"record identifiers are platform owned"),c(I,w,y),f(C,g.parameters,y,g.quota?.action==="allocate")}if(g.quota){let u=r(g.quota,y,["pool","action","units","mode","allocation"]),I=A.quotas.find(R=>R.code===u.pool);I||n(y,"unknown quota pool"),p(g.resourceKey,g.parameters,y),u.action==="allocate"?(r(u,y,["pool","action","units","mode"]),i(u.units,1,1e3,y),(!["committed","reserved"].includes(u.mode)||u.mode==="reserved"&&!I.reservationSeconds)&&n(y,"invalid allocation mode"),(g.operations.length!==1||g.operations[0].operation!=="create"||g.operations[0].resourceCode!==I.allocationResource||g.operations[0].data[I.allocationField]?.from!=="allocation")&&n(y,"allocation must atomically create its bound business record")):["confirm","release"].includes(u.action)?(r(u,y,["pool","action","allocation"]),p(u.allocation,g.parameters,y),g.operations.length&&n(y,"lifecycle owns allocation state; business reference remains immutable")):n(y,"invalid quota action")}else g.operations.length||n(y,"operations required")}let O=A.commands.filter(g=>g.mode==="durable").map(g=>g.execution.handlerCode);return new Set(O).size!==O.length&&n(E,"handler code must be unique"),JSON.parse(JSON.stringify(A))}var pt=class extends Error{constructor(o,n){super(`\u91D1\u989D\u751F\u547D\u5468\u671F\u58F0\u660E\u65E0\u6548\uFF1A${n}\uFF08${o}\uFF09`);this.pointer=o;this.reason=n}pointer;reason;code="NATIVE_DECIMAL_LIFECYCLE_INVALID"},Do=["parentTransitions","childTransitions","fulfilledChildStatuses","lockedParentStatuses"],di=["amountFieldCode","currencyFieldCode","relationFieldCode","parentFieldCode","rootFieldCode","statusFieldCode","parentRelationValue","childRelationValue"],dn=e=>!!(e&&typeof e=="object"&&!Array.isArray(e)),an=e=>Array.isArray(e)?e.filter(dn):[],De=(e,t)=>{throw new pt(e,t)},Co=e=>typeof e=="string"&&/^[A-Za-z0-9._:-]{1,128}$/.test(e),So=(e,t)=>e<t?-1:e>t?1:0;function ko(e,t="/decimalReservationLifecycle"){if(e===void 0)return;if(!dn(e)||Object.keys(e).some(r=>!Do.includes(r))||Do.some(r=>!Object.prototype.hasOwnProperty.call(e,r)))return De(t,"\u5FC5\u987B\u5B8C\u6574\u58F0\u660E\u56DB\u9879\u89C4\u5219\uFF0C\u4E0D\u80FD\u5305\u542B\u672A\u77E5\u5C5E\u6027");let o=r=>{let i=e[r];if(!Array.isArray(i)||i.length>64)return De(`${t}/${r}`,"\u72B6\u6001\u8FB9\u6700\u591A 64 \u6761");let a=new Set;return i.map((s,d)=>{let c=`${t}/${r}/${d}`;if(!dn(s)||Object.keys(s).some(f=>f!=="from"&&f!=="to")||!Co(s.from)||!Co(s.to)||s.from===s.to)return De(c,"\u72B6\u6001\u8FB9\u5FC5\u987B\u5305\u542B\u4E0D\u540C\u7684\u6709\u6548 from/to");let l=JSON.stringify([s.from,s.to]);return a.has(l)?De(c,"\u72B6\u6001\u8FB9\u4E0D\u80FD\u91CD\u590D"):(a.add(l),{from:s.from,to:s.to})}).sort((s,d)=>So(s.from,d.from)||So(s.to,d.to))},n=r=>{let i=e[r];return!Array.isArray(i)||i.length<1||i.length>16||i.some(a=>!Co(a))||new Set(i).size!==i.length?De(`${t}/${r}`,"\u72B6\u6001\u96C6\u5408\u5FC5\u987B\u5305\u542B 1 \u5230 16 \u4E2A\u4E0D\u91CD\u590D\u7684\u6709\u6548\u72B6\u6001"):[...i].sort(So)};return{parentTransitions:o("parentTransitions"),childTransitions:o("childTransitions"),fulfilledChildStatuses:n("fulfilledChildStatuses"),lockedParentStatuses:n("lockedParentStatuses")}}function ci(e,t,o="/config/data/resources"){an(e).forEach((n,r)=>{let i=`${o}/${r}/decimalReservationLifecycle`,a=ko(n.decimalReservationLifecycle,i);if(!a)return;let s=an(t).map(f=>f.platformAccess?.decimalReservation).filter(f=>dn(f)&&f.resourceCode===n.code),d=s.find(f=>f.mode==="reserve");if(!d)return De(i,"\u9700\u8981\u540C\u8D44\u6E90\u5DF2\u58F0\u660E\u7684 reserve \u52A8\u4F5C\u6620\u5C04");if(di.some(f=>typeof d[f]!="string")||s.some(f=>di.some(p=>f[p]!==d[p])))return De(i,"\u540C\u8D44\u6E90\u989D\u5EA6\u52A8\u4F5C\u7684\u5B57\u6BB5\u6620\u5C04\u5FC5\u987B\u4E00\u81F4");let c=an(n.schema?.fields).find(f=>f.code===d.statusFieldCode);if(c?.type!=="option.single")return De(i,"\u989D\u5EA6\u72B6\u6001\u5B57\u6BB5\u5FC5\u987B\u4E3A option.single");let l=new Set(an(c.options).map(f=>f.value));for(let f of Do)if((f==="parentTransitions"||f==="childTransitions"?a[f].flatMap(m=>[m.from,m.to]):a[f]).some(m=>!l.has(m)))return De(`${i}/${f}`,"\u72B6\u6001\u5FC5\u987B\u6765\u81EA\u989D\u5EA6\u72B6\u6001\u5B57\u6BB5\u7684\u9009\u9879");if(s.some(f=>f.mode==="reserve"&&Array.isArray(f.eligibleParentStatuses)&&f.eligibleParentStatuses.some(p=>a.lockedParentStatuses.includes(String(p)))))return De(`${i}/lockedParentStatuses`,"\u9501\u5B9A\u7236\u72B6\u6001\u4E0D\u80FD\u5141\u8BB8\u65B0\u9884\u7559")})}import{createHash as od}from"crypto";var Lo=new Set(["option.single","user.single","department.single","resource-ref.single"]),rd=new Set(["option.multiple","cascade.single","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","address","location","json"]),ui=new Set(["option.multiple","cascade.single","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","file","image"]),id=new Set(["option.single","user.single","department.single","resource-ref.single","signature","address","location"]),sd=new Set([...Lo,...ui,"signature","address","location","json"]);function yu(e,t){let o=new Set([...Array.isArray(t?.list?.searchableFields)?t.list.searchableFields:[],...Object.entries(t?.fields||{}).filter(([,n])=>n?.searchable===!0).map(([n])=>n)]);return e.map(n=>ad(n,o.has(n.code))).sort((n,r)=>n.code.localeCompare(r.code))}function ad(e,t=!1){let o=e.type==="date-range"||e.type==="datetime-range";if(o&&e.rangeBoundary!=="closed"&&e.rangeBoundary!=="half-open")throw new Error("OPENXIANGDA_NATIVE_DATA_RANGE_BOUNDARY_INVALID");return{code:e.code,type:e.type,nullable:!0,indexed:e.indexed===!0,storage:ld(e),index:cd(e,t),...o?{rangeBoundary:e.rangeBoundary}:{},...e.type==="serial-number"?{serial:{prefix:e.serial?.prefix||"",digits:e.serial?.digits??6,start:e.serial?.start??1}}:{},...e.type==="subtable"&&e.subtable?{subtable:{resourceCode:e.subtable.resourceCode,foreignKey:e.subtable.foreignKey,orderField:e.subtable.orderField,maxRows:e.subtable.maxRows??20}}:{}}}function Ou(e,t){if(t.type==="subtable")return null;let o=fe(t.code),n=fi(e,t),r=[n?` DEFAULT ${n}`:"",ud(o,t),dd(o,t)].join("");return`${o} ${t.storage}${r}`}function bu(e,t){return fi(e,t)}function dd(e,t){if(t.type!=="date-range"&&t.type!=="datetime-range")return"";if(t.rangeBoundary!=="closed"&&t.rangeBoundary!=="half-open")throw new Error("OPENXIANGDA_NATIVE_DATA_RANGE_BOUNDARY_INVALID");let o=t.type==="datetime-range"&&t.rangeBoundary==="closed";return` CHECK (${e} IS NULL OR (NOT isempty(${e}) AND lower(${e}) IS NOT NULL AND upper(${e}) IS NOT NULL AND lower_inc(${e}) AND ${o?"":"NOT "}upper_inc(${e})))`}function Nu(e){return e.type==="serial-number"||tn(e.type)&&e.type!=="subtable"}function hu(e,t){return t.filter(o=>o.type==="serial-number").map(o=>{let n=ln(e,o.code),r=o.serial?.start??1;return`CREATE SEQUENCE IF NOT EXISTS ${n} AS bigint MINVALUE ${r} START WITH ${r} CACHE 1`})}function Ru(e,t){let o=cn(e);return t.filter(n=>n.type==="serial-number").map(n=>`ALTER SEQUENCE ${ln(e,n.code)} OWNED BY ${o}.${fe(n.code)}`)}function wu(e,t){return t.filter(o=>o.type==="serial-number").map(o=>`GRANT USAGE, SELECT ON SEQUENCE ${ln(e,o.code)} TO "openxiangda_data_api"`)}function Tu(e,t){let o=cn(e),n=[];for(let r of t){if(r.type==="subtable")continue;let i=fe(r.code),a=fe(We("idx",e,r.code,r.index));switch(r.index){case"btree":n.push(`CREATE INDEX IF NOT EXISTS ${a} ON ${o} (${i})`);break;case"btree-snapshot-expressions":{let s=fe(We("idx",e,r.code,"snapshot-value")),d=fe(We("idx",e,r.code,"snapshot-label"));n.push(`CREATE INDEX IF NOT EXISTS ${s} ON ${o} ((${i} ->> 'value'))`,`CREATE INDEX IF NOT EXISTS ${d} ON ${o} ((${i} ->> 'label'))`);break}case"gin-jsonb-path":n.push(`CREATE INDEX IF NOT EXISTS ${a} ON ${o} USING GIN (${i} jsonb_path_ops)`);break;case"gist-range":n.push(`CREATE INDEX IF NOT EXISTS ${a} ON ${o} USING GIST (${i})`);break;case"gin-trigram":{let s=Lo.has(r.type)?`((${i} ->> 'label')) gin_trgm_ops`:`${i} gin_trgm_ops`;n.push(`CREATE INDEX IF NOT EXISTS ${a} ON ${o} USING GIN (${s})`);break}case"none":break}if(r.type==="serial-number"){let s=fe(We("uidx",e,r.code,"serial"));n.push(`CREATE UNIQUE INDEX IF NOT EXISTS ${s} ON ${o} (${i})`)}}return n}function Cu(e,t,o,n){let r=cn(e),i=cn(t),a=fe(We("uidx",e,"environment_id","subtable-parent")),s=fe(We("idx",t,o,n,"subtable-child")),d=fe(We("fk",t,o,e)),c=fe(o),l=fe(n);return[`CREATE UNIQUE INDEX IF NOT EXISTS ${a} ON ${r} ("tenant_id", "app_code", "environment_key", "id")`,`CREATE INDEX IF NOT EXISTS ${s} ON ${i} ("tenant_id", "app_code", "environment_key", ${c}, ${l}, "id")`,`DO $native_subtable$ BEGIN
2
+ ALTER TABLE ${i}
3
+ ADD CONSTRAINT ${d}
4
4
  FOREIGN KEY ("tenant_id", "app_code", "environment_key", ${c})
5
- REFERENCES ${i} ("tenant_id", "app_code", "environment_key", "id")
5
+ REFERENCES ${r} ("tenant_id", "app_code", "environment_key", "id")
6
6
  ON DELETE CASCADE;
7
7
  EXCEPTION WHEN duplicate_object THEN NULL;
8
- END $native_subtable$`]}function ve(e,...t){return`${e}_${_a("sha256").update(t.join(":")).digest("hex").slice(0,32)}`}function le(e){if(!/^[A-Za-z_][A-Za-z0-9_]{0,62}$/.test(e))throw new Error("OPENXIANGDA_NATIVE_IDENTIFIER_INVALID");return`"${e}"`}function ba(e,t){return e.type==="subtable"?"none":t?"gin-trigram":e.indexed?["date-range","datetime-range"].includes(e.type)?"gist-range":io.has(e.type)?"btree-snapshot-expressions":ga.has(e.type)?"gin-jsonb-path":"btree":"none"}function Oa(e){switch(e.type){case"text.short":return`varchar(${e.maxLength??255})`;case"text.long":case"text.rich":return"text";case"number.integer":return"bigint";case"number.decimal":return`numeric(${e.precision??38},${e.scale??10})`;case"boolean":return"boolean";case"date":return"date";case"time":return"time(0)";case"datetime":return"timestamptz";case"date-range":return"daterange";case"datetime-range":return"tstzrange";case"uuid":return"uuid";case"serial-number":return"varchar(255)";case"subtable":return"child-resource";default:return Ea.has(e.type),"jsonb"}}function Di(e,t){if(Mt(t.type)&&t.type!=="subtable")return"'[]'::jsonb";if(t.type!=="serial-number")return"";let o=wi(t.serial?.prefix||""),n=t.serial?.digits??6;return`(${o} || lpad(nextval(${wi(Yt(e,t.code))})::text, ${n}, '0'))`}function Na(e,t){return Si.has(t.type)?` CHECK (${e} IS NULL OR jsonb_typeof(${e}) = 'array')`:Aa.has(t.type)?` CHECK (${e} IS NULL OR jsonb_typeof(${e}) = 'object')`:""}function Ht(e){return`"app_data".${le(e)}`}function Yt(e,t){let o=ve("seq",e,t);return`"app_data".${le(o)}`}function wi(e){return`'${e.replace(/'/g,"''")}'`}var ki=new Set(["option.single","option.multiple","user.single","user.multiple","department.single","department.multiple","resource-ref.single","resource-ref.multiple"]),Ta=new Set([...ki,"cascade.single","cascade.multiple","file","image","signature","address","location","json"]),$i=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,Ra=new Set(["__proto__","prototype","constructor"]),ro=class extends Error{constructor(o){super("OPENXIANGDA_SCOPE_PROJECTION_FIELD_PATH_INVALID");this.path=o;this.name="NativeScopeSourceFieldPathV2Error"}path;code="OPENXIANGDA_SCOPE_PROJECTION_FIELD_PATH_INVALID"};function It(e,t){let o=vi(e);if(!o)return null;let n=t.get(o[0]);if(!n)return null;let i=o.slice(1).join(".")||void 0;return{field:n,...i?{valuePath:i}:{}}}function so(e){return!!(e&&e.field.type==="user.single"&&e.valuePath==="value")}function Pi(e,t,o){if(!e||!t||!Ca(e))return!1;let{field:n,valuePath:i}=e;if(!i)return t.valueType==="uuid"?n.type==="uuid":["text.short","text.long","serial-number"].includes(n.type);if(i==="value")return!(t.valueSourceResourceCode&&n.type.startsWith("resource-ref.")&&n.source?.resourceCode!==t.valueSourceResourceCode);let r=i.slice(9),s=o.get(n.source?.resourceCode||"")?.get(r)?.type;return t.valueType==="uuid"?s==="uuid":["text.short","text.long","serial-number"].includes(s||"")}function wl(e,t){let o=vi(t);if(!o)throw new ro(String(t||""));let n=e;for(let i of o){if(!n||typeof n!="object"||!Object.prototype.hasOwnProperty.call(n,i))return;n=n[i]}return n}function Ca(e){let{field:t,valuePath:o}=e;if(!o)return!Ta.has(t.type);if(o==="value")return ki.has(t.type);if(!o.startsWith("snapshot."))return!1;let n=o.slice(9);return $i.test(n)&&t.type.startsWith("resource-ref.")&&!!t.source?.snapshotFields?.includes(n)}function vi(e){if(typeof e!="string"||e.length===0||e.length>192)return null;let t=e.split(".");return![1,2,3].includes(t.length)||t.some(o=>!$i.test(o)||Ra.has(o))||t.length===2&&t[1]!=="value"||t.length===3&&t[1]!=="snapshot"?null:t}var ha=new Set(["option.single","user.single","department.single","resource-ref.single"]),wa=new Set(["text.short","text.long","text.rich","number.integer","number.decimal","boolean","date","time","datetime","uuid","serial-number"]),Sa=new Set(["value","label","description","color"]),Da=new Set(["avatarUrl","employeeNo","title","mobile","email"]),ka=new Set(["fullPath","parent.value","parent.label"]),$a=new Set(["country.value","country.label","province.value","province.label","city.value","city.label","district.value","district.label","street.value","street.label","detail","fullAddress"]),Pa=new Set(["longitude","latitude","accuracy"]),va=new Set(["address","name","province","city","district","source"]);function Dl(e){let t=new Map(e.map(o=>[o.code,new Map(o.schema.fields.map(n=>[n.code,n]))]));return e.map(o=>({...o,schema:{...o.schema,fields:o.schema.fields.map(n=>{let i=Va(n,t);if(!Object.keys(i).length)return n;let r={...n};return Object.defineProperty(r,"queryPathTypes",{configurable:!1,enumerable:!1,writable:!1,value:Object.freeze(i)}),r})}}))}function kl(e,t){if(ha.has(e.type)&&Sa.has(t)||e.type==="user.single"&&Da.has(t)||e.type==="department.single"&&ka.has(t))return yt(t);if(e.type==="resource-ref.single"){let o=e.queryPathTypes?.[t];return o?{parts:t.split("."),type:o}:null}if(e.type==="address"&&$a.has(t))return yt(t);if(e.type==="location"){if(Pa.has(t))return{parts:[t],type:"number.decimal"};if(va.has(t))return yt(t);if(t==="capturedAt")return{parts:[t],type:"datetime"}}return null}function Va(e,t){if(e.type!=="resource-ref.single"||!e.source)return{};let o=t.get(e.source.resourceCode);return o?Object.fromEntries((e.source.snapshotFields||[]).flatMap(n=>{let i=o.get(n);return i?[[`snapshot.${n}`,wa.has(i.type)?i.type:"json"]]:[]})):{}}function yt(e){return{parts:e.split("."),type:"text.short"}}var Pl=5,vl=20,Vl=50,Ll=50,Fl=100,Ot=class extends Error{constructor(o,n){super(o);this.code=o;this.pointer=n;this.name="NativeDataPolicyExpressionV2Error"}code;pointer};function st(e,t){let o=[],n=(i,r,d)=>{d>5&&bt("NATIVE_DATA_POLICY_EXPRESSION_DEPTH_EXCEEDED",r);let s=Li(i,r),a=["allOf","anyOf"].filter(u=>u in s);if(a.length===0){o.push({rule:s,pointer:r}),o.length>50&&bt("NATIVE_DATA_POLICY_EXPRESSION_LEAVES_EXCEEDED",r);return}let c=a[0],f=s[c];(a.length!==1||Object.keys(s).length!==1||!Array.isArray(f)||f.length<1||f.length>20)&&bt("NATIVE_DATA_POLICY_EXPRESSION_GROUP_INVALID",r),f.forEach((u,p)=>n(u,`${r}/${c}/${p}`,d+1))};return n(e,t,1),o}function Vi(e,t){st(e,t);let o=(n,i)=>{let r=Li(n,i);if(Array.isArray(r.allOf))return ao(r.allOf.flatMap((d,s)=>o(d,`${i}/allOf/${s}`)),i);if(Array.isArray(r.anyOf)){let d=[[]];return r.anyOf.forEach((s,a)=>{let c=o(s,`${i}/anyOf/${a}`);d=ao(d.flatMap(f=>c.map(u=>[...f,...u])),i)}),d}return[[r]]};return ao(o(e,t),t)}function ao(e,t){let o=e.reduce((n,i)=>n+i.length,0);return(e.length>50||o>100)&&bt("NATIVE_DATA_POLICY_EXPRESSION_EXPANSION_EXCEEDED",t),e}function Li(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&bt("NATIVE_DATA_POLICY_EXPRESSION_NODE_INVALID",t),e}function bt(e,t){throw new Ot(e,t)}var ue=class extends Error{constructor(o,n){super(`${o}: ${n}`);this.code=o;this.pointer=n}code;pointer},La=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,Fi=/^[A-Za-z_][A-Za-z0-9_]{0,127}$/;function Fa(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new ue("NATIVE_PARENT_READ_INVALID",t);let o=e;if(Object.keys(o).some(n=>!["resourceCode","subtableFieldCode"].includes(n))||typeof o.resourceCode!="string"||o.resourceCode.length>64||!La.test(o.resourceCode)||typeof o.subtableFieldCode!="string"||!Fi.test(o.subtableFieldCode))throw new ue("NATIVE_PARENT_READ_INVALID",t);return{resourceCode:o.resourceCode,subtableFieldCode:o.subtableFieldCode}}function xi(e,t){return[...(Array.isArray(e.rules)?e.rules:[]).map((o,n)=>({rule:o,pointer:`${t}/rules/${n}`,base:!0})),...e.readExpression===void 0?[]:st(e.readExpression,`${t}/readExpression`).map(o=>({...o,base:!1}))]}function Xt(e,t,o,n){let i=Fa(o,n),r=e.find(_=>_.code===i.resourceCode),d=e.find(_=>_.code===t),a=(Array.isArray(r?.schema?.fields)?r.schema.fields:[]).find(_=>_.code===i.subtableFieldCode);if(!r||!d||r.code===d.code||a?.type!=="subtable"||a.subtable?.resourceCode!==t)throw new ue("NATIVE_PARENT_READ_BINDING_INVALID",n);if(e.flatMap(_=>(Array.isArray(_.schema?.fields)?_.schema.fields:[]).filter(E=>E.type==="subtable"&&E.subtable?.resourceCode===t).map(E=>({resource:_,field:E}))).length!==1)throw new ue("NATIVE_PARENT_READ_PARENT_AMBIGUOUS",n);let f=a.subtable.foreignKey,p=(Array.isArray(d.schema?.fields)?d.schema.fields:[]).find(_=>_.code===f);if(typeof f!="string"||!Fi.test(f)||p?.type!=="uuid")throw new ue("NATIVE_PARENT_READ_FOREIGN_KEY_INVALID",n);return{...i,childResourceCode:t,foreignKey:f,...a.subtable.orderField?{orderField:a.subtable.orderField}:{}}}function ji(e,t,o="/config/authz/dataPolicies"){let n=new Map;for(let[i,r]of t.entries())for(let d of xi(r,`${o}/${i}`)){if(d.rule.parentRead===void 0)continue;if(Object.keys(d.rule).some(f=>!["parentRead","roleCodes"].includes(f)))throw new ue("NATIVE_PARENT_READ_RULE_KEYS_INVALID",d.pointer);if(d.base&&(r.operations?.length!==1||r.operations[0]!=="read"))throw new ue("NATIVE_PARENT_READ_READ_ONLY",d.pointer);if(e.find(f=>f.code===r.resourceCode)?.dataPolicyCode!==r.code)throw new ue("NATIVE_PARENT_READ_POLICY_BINDING_INVALID",d.pointer);let a=Xt(e,r.resourceCode,d.rule.parentRead,`${d.pointer}/parentRead`),c=n.get(r.resourceCode);if(c&&c!==a.resourceCode)throw new ue("NATIVE_PARENT_READ_PARENT_AMBIGUOUS",d.pointer);n.set(r.resourceCode,a.resourceCode)}for(let[i,r]of n)if(n.has(r))throw new ue("NATIVE_PARENT_READ_MULTI_HOP_FORBIDDEN",`${o}/${t.findIndex(d=>d.resourceCode===i)}`)}function co(e){return xi(e,"/dataPolicy").some(t=>t.rule.parentRead!==void 0)}var Mi=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Bi=(e,t)=>Object.keys(e).length===t.length&&Object.keys(e).every(o=>t.includes(o)),Wi=e=>typeof e=="string"&&/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/.test(e)&&e.length<=100,Ui=e=>typeof e=="string"&&/^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(e);function lo(e){throw new Error(`OPENXIANGDA_WORKFLOW_STAGE_${e}`)}function Ki(e){(!Mi(e)||!Bi(e,["workflowCode","resourceCode","actor","runningNodeIds","allowedStatuses"])||!Wi(e.workflowCode)||!Wi(e.resourceCode)||!["initiator","reader"].includes(String(e.actor))||!Array.isArray(e.runningNodeIds)||e.runningNodeIds.length>32||new Set(e.runningNodeIds).size!==e.runningNodeIds.length||e.runningNodeIds.some(t=>typeof t!="string"||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(t))||!Array.isArray(e.allowedStatuses)||e.allowedStatuses.length>5||new Set(e.allowedStatuses).size!==e.allowedStatuses.length||e.allowedStatuses.some(t=>!["approved","rejected","cancelled","terminated","returned"].includes(t))||e.runningNodeIds.length+e.allowedStatuses.length===0)&&lo("POLICY_INVALID")}function Ul(e){(!Mi(e)||!Bi(e,["instanceId","subjectRecordId","expectedInstanceSequence"])||!Ui(e.instanceId)||!Ui(e.subjectRecordId)||!Number.isSafeInteger(e.expectedInstanceSequence)||e.expectedInstanceSequence<0)&&lo("GUARD_INVALID")}function Ml(e,t,o){o?.some(n=>(n.kind==="record-match"||n.kind==="record-assert")&&n.resourceCode===e.resourceCode&&n.id.toLowerCase()===t.subjectRecordId.toLowerCase()&&n.assertions.some(i=>i.kind==="value"&&i.field==="revision"&&i.operator==="eq"&&Number.isSafeInteger(i.value)&&Number(i.value)>0))||lo("SOURCE_GUARD_REQUIRED")}var Bl={type:"object",additionalProperties:!1,required:["workflowCode","resourceCode","actor","runningNodeIds","allowedStatuses"],properties:{workflowCode:{type:"string",pattern:"^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$",maxLength:100},resourceCode:{type:"string",pattern:"^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$",maxLength:100},actor:{enum:["initiator","reader"]},runningNodeIds:{type:"array",maxItems:32,uniqueItems:!0,items:{type:"string",pattern:"^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$"}},allowedStatuses:{type:"array",maxItems:5,uniqueItems:!0,items:{enum:["approved","rejected","cancelled","terminated","returned"]}}},anyOf:[{properties:{runningNodeIds:{minItems:1}}},{properties:{allowedStatuses:{minItems:1}}}]};var Nt=class extends Error{constructor(o,n){super(o);this.code=o;this.pointer=n}code;pointer},fe=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},Gi=(e,t)=>e===t||e==="*"||e.endsWith(":*")&&t.startsWith(e.slice(0,-1));function qi(e){let{policy:t,resource:o,baselineRoleCode:n,baselineCapabilities:i,pointer:r}=e,d=A=>A===void 0||A===!0||Array.isArray(A)&&A.length>0&&A.every(O=>typeof O=="string"&&O.length>0&&!e.baselineDeniedCapabilities?.some(b=>Gi(b,O))&&i.some(b=>Gi(b,O))),s=(A,O="")=>{throw new Nt(A,`${r}/publicRead${O}`)},a=fe(t.publicRead);(!t.publicRead||Object.keys(a).length!==1||!Object.hasOwn(a,"fields")||!Array.isArray(a.fields)||a.fields.length<1||a.fields.length>1e3||a.fields.some(A=>typeof A!="string"||!/^[A-Za-z][A-Za-z0-9_]{0,62}$/.test(A))||new Set(a.fields).size!==a.fields.length)&&s("AUTHENTICATED_PUBLIC_READ_FIELDS_INVALID","/fields"),(!Array.isArray(t.operations)||t.operations.length!==1||t.operations[0]!=="read"||t.readExpression!==void 0||t.writeBoundary!==void 0)&&s("AUTHENTICATED_PUBLIC_READ_POLICY_NOT_READ_ONLY"),(!n||!o||o.code!==t.resourceCode||o.dataPolicyCode!==t.code||!d([fe(o.capabilities).read]))&&s("AUTHENTICATED_PUBLIC_READ_BASELINE_OR_RESOURCE_INVALID");let c=fe(o),f=fe(c.schema).fields;(!Array.isArray(f)||!f.length)&&s("AUTHENTICATED_PUBLIC_READ_RESOURCE_FIELDS_MISSING");let u=new Map(f.map(A=>[String(fe(A).code),fe(A)])),p=new Set(a.fields),_=fe(c.fieldPolicies);for(let A of p){let O=fe(u.get(A));(!u.has(A)||O.system===!0||fe(fe(c.surface).fields)[A]?.system===!0||nt.has(A))&&s("AUTHENTICATED_PUBLIC_READ_FIELD_NOT_DECLARED",`/fields/${A}`),(O.type==="subtable"||O.subtable!==void 0)&&s("AUTHENTICATED_PUBLIC_READ_SUBTABLE_UNSUPPORTED",`/fields/${A}`),d(fe(_[A]).read)||s("AUTHENTICATED_PUBLIC_READ_FIELD_NOT_BASELINE_READABLE",`/fields/${A}`)}let E=[...u.keys()].filter(A=>!p.has(A));for(let A of E)d(fe(_[A]).read)&&s("AUTHENTICATED_PUBLIC_READ_PRIVATE_FIELD_ACCESSIBLE",`/fields/${A}`);E.length&&Kt.some(A=>d(fe(_[A]).read))&&s("AUTHENTICATED_PUBLIC_READ_PRIVATE_HISTORY_ACCESSIBLE")}var zi=["exact-v1","nfkc-space-v1","nfkc-upper-ascii-v1"],Jl=256,Rt=class extends Error{constructor(o,n){super(`\u6761\u4EF6\u552F\u4E00\u952E\u58F0\u660E\u65E0\u6548\uFF1A${n}\uFF08${o}\uFF09`);this.pointer=o;this.reason=n}pointer;reason;code="NATIVE_UNIQUE_KEY_INVALID"},uo=e=>!!(e&&typeof e=="object"&&!Array.isArray(e)),ie=(e,t)=>{throw new Rt(e,t)},Zt=(e,t)=>e<t?-1:e>t?1:0,Tt=(e,t,o)=>{Object.keys(e).some(n=>!t.includes(n))&&ie(o,"\u4E0D\u652F\u6301\u672A\u77E5\u5C5E\u6027")};function Ji(e,t,o="/uniqueKeys"){if(e===void 0)return;if(!Array.isArray(e)||e.length>8)return ie(o,"\u6BCF\u8D44\u6E90\u6700\u591A 8 \u6761\u89C4\u5219");let n=new Map(t.map(r=>[r.code,r])),i=new Set;return e.map((r,d)=>{let s=`${o}/${d}`;if(!uo(r))return ie(s,"\u89C4\u5219\u5FC5\u987B\u662F\u5BF9\u8C61");if(Tt(r,["code","fields","when"],s),typeof r.code!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(r.code)||r.code.length>20||i.has(r.code))return ie(`${s}/code`,"\u9700\u8981\u4E0D\u91CD\u590D\u4E14\u4E0D\u8D85\u8FC7 20 \u5B57\u7B26\u7684 lower-kebab-case \u6807\u8BC6");if(i.add(r.code),!Array.isArray(r.fields)||r.fields.length<1||r.fields.length>4)return ie(`${s}/fields`,"\u5FC5\u987B\u9009\u62E9 1 \u5230 4 \u4E2A\u5B57\u6BB5");let a=new Set,c=r.fields.map((_,E)=>{let A=`${s}/fields/${E}`;if(!uo(_))return ie(A,"\u5B57\u6BB5\u5FC5\u987B\u662F\u5BF9\u8C61");Tt(_,["fieldCode","normalizer"],A);let O=n.get(_.fieldCode);if(!O||!["text.short","uuid","option.single","resource-ref.single","user.single"].includes(O.type)||a.has(_.fieldCode))return ie(`${A}/fieldCode`,"\u9700\u8981\u4E0D\u91CD\u590D\u7684\u77ED\u6587\u672C\u3001UUID\u3001\u5355\u9009\u3001\u5355\u8BB0\u5F55\u5F15\u7528\u6216\u5355\u4EBA\u5B57\u6BB5");a.add(_.fieldCode);let b=_.normalizer===void 0?"exact-v1":_.normalizer;return!zi.includes(b)||O.type!=="text.short"&&b!=="exact-v1"?ie(`${A}/normalizer`,"\u5F52\u4E00\u5316\u65B9\u5F0F\u4E0D\u652F\u6301\u6216\u4E0E\u5B57\u6BB5\u7C7B\u578B\u4E0D\u7B26"):{fieldCode:O.code,normalizer:b}}).sort((_,E)=>Zt(_.fieldCode,E.fieldCode)),f=r.when===void 0?[]:r.when;if(!Array.isArray(f)||f.length>4)return ie(`${s}/when`,"\u6700\u591A 4 \u4E2A\u5408\u53D6\u6761\u4EF6");let u=new Set,p=f.map((_,E)=>{let A=`${s}/when/${E}`;if(!uo(_))return ie(A,"\u6761\u4EF6\u5FC5\u987B\u662F\u5BF9\u8C61");let O=n.get(_.fieldCode);if(!O)return ie(`${A}/fieldCode`,"\u5B57\u6BB5\u4E0D\u5B58\u5728");let b;if(_.operator==="empty"||_.operator==="nonempty"){if(Tt(_,["fieldCode","operator"],A),O.type!=="text.short")return ie(A,"\u7A7A\u503C\u6761\u4EF6\u4EC5\u652F\u6301\u77ED\u6587\u672C");b={fieldCode:O.code,operator:_.operator}}else if(_.operator==="in"||_.operator==="notIn"){Tt(_,["fieldCode","operator","values"],A);let I=new Set((O.options??[]).map(T=>T.value));if(O.type!=="option.single"||!Array.isArray(_.values)||_.values.length<1||_.values.length>16||_.values.some(T=>typeof T!="string"||T.length<1||T.length>128||!I.has(T))||new Set(_.values).size!==_.values.length)return ie(A,"\u96C6\u5408\u6761\u4EF6\u9700\u8981 1 \u5230 16 \u4E2A\u4E0D\u91CD\u590D\u7684\u5DF2\u58F0\u660E\u5355\u9009\u503C");b={fieldCode:O.code,operator:_.operator,values:[..._.values].sort(Zt)}}else if(_.operator==="eq"||_.operator==="ne"){if(Tt(_,["fieldCode","operator","value"],A),O.type!=="boolean"||typeof _.value!="boolean")return ie(A,"\u7B49\u503C\u6761\u4EF6\u4EC5\u652F\u6301\u5E03\u5C14\u5B57\u6BB5\u548C\u5E03\u5C14\u503C");b={fieldCode:O.code,operator:_.operator,value:_.value}}else return ie(`${A}/operator`,"\u53EA\u652F\u6301 empty\u3001nonempty\u3001in\u3001notIn \u548C\u5E03\u5C14 eq\u3001ne");let g=JSON.stringify(b);return u.has(g)?ie(A,"\u6761\u4EF6\u4E0D\u80FD\u91CD\u590D"):(u.add(g),b)}).sort((_,E)=>Zt(JSON.stringify(_),JSON.stringify(E)));return{code:r.code,fields:c,when:p}}).sort((r,d)=>Zt(r.code,d.code))}function Hi(e,t){let o=new Set(e.filter(n=>n.type==="user.single").map(n=>n.code));return t?.some(n=>n.fields.some(i=>o.has(i.fieldCode))||n.when?.some(i=>i.operator==="eq"||i.operator==="ne"))?"1.1.0":"1.0.0"}var Qt={type:"string",pattern:"^[A-Za-z_][A-Za-z0-9_]{0,62}$"},Hl={type:"array",maxItems:8,items:{type:"object",additionalProperties:!1,required:["code","fields"],properties:{code:{type:"string",maxLength:20,pattern:"^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$"},fields:{type:"array",minItems:1,maxItems:4,uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["fieldCode"],properties:{fieldCode:Qt,normalizer:{enum:[...zi]}}}},when:{type:"array",maxItems:4,uniqueItems:!0,items:{oneOf:[{type:"object",additionalProperties:!1,required:["fieldCode","operator"],properties:{fieldCode:Qt,operator:{enum:["empty","nonempty"]}}},{type:"object",additionalProperties:!1,required:["fieldCode","operator","values"],properties:{fieldCode:Qt,operator:{enum:["in","notIn"]},values:{type:"array",minItems:1,maxItems:16,uniqueItems:!0,items:{type:"string",minLength:1,maxLength:128}}}},{type:"object",additionalProperties:!1,required:["fieldCode","operator","value"],properties:{fieldCode:Qt,operator:{enum:["eq","ne"]},value:{type:"boolean"}}}]}}}}};var Yi={"openxiangda.workflow.instance.completed.v2":"commit","openxiangda.workflow.instance.rejected.v2":"release","openxiangda.workflow.instance.withdrawn.v2":"release"};function Xi(e,t){let o=()=>{throw new Error("NATIVE_EVENT_DECIMAL_RESERVATION_INVALID")},n=p=>!p||typeof p!="object"||Array.isArray(p)?o():p,i=n(e);if(Object.keys(i).some(p=>!["resourceCode","workflowCode","outcomes"].includes(p))||typeof i.resourceCode!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(i.resourceCode)||typeof i.workflowCode!="string"||!/^[A-Za-z0-9._:-]{1,128}$/.test(i.workflowCode)||t.execution!==void 0||!Array.isArray(i.outcomes)||!i.outcomes.length||i.outcomes.length>3)return o();let r=t.resources.find(p=>p.code===i.resourceCode),d=t.reservations.find(p=>p.mode==="reserve"&&p.resourceCode===i.resourceCode),s=t.workflows.find(p=>p.code===i.workflowCode);if(!r||!d||!s||s.resourceCode!==r.code)return o();let a=r.fields.find(p=>p.code===d.statusFieldCode);if(a?.type!=="option.single")return o();let c=new Set(a.options?.map(p=>p.value)),f=new Set,u=i.outcomes.map(p=>{let _=n(p),E=_.eventType;return Object.keys(_).some(A=>!["eventType","mode","eligibleChildStatuses"].includes(A))||typeof E!="string"||!Object.prototype.hasOwnProperty.call(Yi,E)||!t.eventTypes.includes(E)||f.has(E)||_.mode!==Yi[E]||!Array.isArray(_.eligibleChildStatuses)||!_.eligibleChildStatuses.length||_.eligibleChildStatuses.length>16||new Set(_.eligibleChildStatuses).size!==_.eligibleChildStatuses.length||_.eligibleChildStatuses.some(A=>typeof A!="string"||!/^[A-Za-z0-9._:-]{1,128}$/.test(A)||!c.has(A))?o():(f.add(E),{eventType:E,mode:_.mode,eligibleChildStatuses:[..._.eligibleChildStatuses].sort()})}).sort((p,_)=>p.eventType.localeCompare(_.eventType));return{resourceCode:i.resourceCode,workflowCode:i.workflowCode,outcomes:u}}function Zi(e,t){let o=n=>Array.isArray(n)?n.filter(i=>i&&typeof i=="object"&&!Array.isArray(i)):[];return{eventTypes:Array.isArray(t.eventTypes)?t.eventTypes:[],execution:t.execution,resources:o(e.data?.resources).map(n=>({code:n.code,fields:o(n.schema?.fields).map(i=>({code:i.code,type:i.type,options:o(i.options).map(r=>({value:r.value}))}))})),reservations:o(e.backend?.operations).flatMap(n=>n.platformAccess?.decimalReservation?[n.platformAccess.decimalReservation]:[]),workflows:o(e.workflows?.definitions).map(n=>({code:n.definition?.code,resourceCode:n.definition?.subject?.resourceCode}))}}var fo=class extends Error{constructor(o,n){super(n);this.pointer=o}pointer;code="NATIVE_EVENT_ACTION_INVALID"};function Qi(e,t,o="/events/subscriptions"){if(e.execution===void 0)return;let n=(A,O)=>{throw new fo(`${o}${A}`,O)},i=(A,O,b)=>((!A||typeof A!="object"||Array.isArray(A)||Object.keys(A).some(g=>!b.includes(g)))&&n(O,"Invalid action object or unsupported property"),A),r=i(e.execution,"/execution",["kind","version","operations"]);(r.kind!=="native-data"||r.version!==1)&&n("/execution","Expected native-data version 1"),e.platformAccess&&n("/platformAccess","Native actions do not use application runtime capabilities"),(!Array.isArray(e.eventTypes)||!e.eventTypes.length||e.eventTypes.some(A=>!/^openxiangda\.data\.record\.(created|updated|deleted)\.v2$/.test(A)))&&n("/eventTypes","Native data actions require declared data events");let d=e.filter?.resourceCodes;(!Array.isArray(d)||!d.length||d.length>20)&&n("/filter/resourceCodes","Native actions require explicit source resources");let s=new Map(t.map(A=>[A.code,A])),a=d.map(A=>{let O=s.get(A);return O||n("/filter/resourceCodes","Unknown source resource"),new Set((O.schema?.fields||[]).map(b=>b.code))}),c=new Set(e.payload?.fields||[]),f=e.payload?.includeChanges===!0,u=(A,O)=>{let b=i(A,O,["source","path","value"]);if(b.source==="literal"){(!Object.hasOwn(b,"value")||Object.hasOwn(b,"path"))&&n(O,"Literal binding requires only value");let l;try{l=JSON.stringify(b.value)}catch{n(O,"Literal must be JSON")}return(l===void 0||Buffer.byteLength(l)>65536)&&n(O,"Literal is too large or not JSON"),{source:"literal",value:JSON.parse(l)}}(b.source!=="event"||typeof b.path!="string"||Object.hasOwn(b,"value"))&&n(O,"Expected a literal or event binding");let g=b.path.split(".");(g.length>8||g.some(l=>!/^[A-Za-z0-9_-]+$/.test(l)||["__proto__","prototype","constructor"].includes(l)))&&n(O,"Invalid event path");let I=/^data\.projection\.([A-Za-z][A-Za-z0-9_]{0,62})$/.exec(b.path),T=/^data\.changes\.([A-Za-z][A-Za-z0-9_]{0,62})\.(before|after)$/.exec(b.path);if(I||T){let l=(I||T)[1];a.some(y=>!y.has(l))&&n(O,"Source field must exist on every filtered resource"),c.add(l),T&&(f=!0)}else["id","time","type","subject","data.recordId","data.revision","data.operation","data.resourceCode"].includes(b.path)||n(O,"Event path is not part of the data event contract");return{source:"event",path:b.path}};(!Array.isArray(r.operations)||r.operations.length<1||r.operations.length>16)&&n("/execution/operations","Expected 1 to 16 operations");let p={},_=r.operations.map((A,O)=>{let b=`/execution/operations/${O}`,g=i(A,b,["operation","resourceCode","data","id","expectedRevision"]);["create","update","delete"].includes(g.operation)||n(b,"Unsupported Native operation");let I=s.get(g.resourceCode);I||n(b,"Unknown action target resource");let T=new Map((I.schema?.fields||[]).map(y=>[y.code,y])),l=g.data===void 0?{}:i(g.data,`${b}/data`,[...T.keys()]);return Object.keys(l).length>32&&n(b,"Maximum 32 mapped fields per operation"),g.operation==="create"&&(g.id!==void 0||g.expectedRevision!==void 0)&&n(b,"Create does not accept id or expectedRevision"),g.operation==="delete"&&g.data!==void 0&&n(b,"Delete does not accept data"),Object.keys(l).some(y=>T.get(y)?.type==="serial-number")&&n(b,"Generated fields cannot be assigned"),p[g.resourceCode]=Z(I),{operation:g.operation,resourceCode:g.resourceCode,...g.operation==="create"?{}:{id:u(g.id,`${b}/id`),expectedRevision:u(g.expectedRevision,`${b}/expectedRevision`)},...g.operation==="delete"?{}:{data:Object.fromEntries(Object.entries(l).map(([y,R])=>[y,u(R,`${b}/data/${y}`)]))}}});(c.size>32||[...c].some(A=>a.some(O=>!O.has(A))))&&n("/payload/fields","Payload must contain at most 32 declared source fields");let E={kind:"native-data",version:1,operations:_,resourceDigests:p};return Buffer.byteLength(JSON.stringify(E))>65536&&n("/execution","Action plan exceeds 64 KiB"),{execution:{...E,digest:Z(E)},payload:{includeChanges:f,fields:[...c].sort()}}}function Ve(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function tr(e,t){if(e?.instanceCommands===void 0)return[];let o=Ve(e.instanceCommands);if(!o||!Object.keys(o).length||Object.keys(o).some(i=>!["withdraw","terminate"].includes(i)))return["WORKFLOW_INSTANCE_COMMAND_POLICIES_INVALID"];let n=[];for(let[i,r]of Object.entries(o)){let d=Ve(r),s=i==="withdraw"?["beforeFact","reasonRequired"]:["beforeFact","capability"];if(!d||!Object.keys(d).length||Object.keys(d).some(a=>!s.includes(a))||Object.hasOwn(d,"reasonRequired")&&typeof d.reasonRequired!="boolean"){n.push(`WORKFLOW_INSTANCE_COMMAND_POLICY_INVALID:${i}`);continue}if(i==="terminate"){let a=d.capability;(typeof a!="string"||a.length>255||!/^app:[a-z][a-z0-9]*(?:-[a-z0-9]+)*:[A-Za-z0-9:._-]+$/.test(a)||t&&(!a.startsWith(`app:${t.appCode}:`)||!t.capabilities.includes(a)))&&n.push("WORKFLOW_INSTANCE_TERMINATE_CAPABILITY_INVALID")}if(Object.hasOwn(d,"beforeFact")){let a=d.beforeFact,c=Ve(e.inputSchema),f=Ve(Ve(c?.properties)?.[a]),u=Ve(Ve(e.subject)?.factProjection)?.[a],p=t?.fields.get(u);(typeof a!="string"||!/^[A-Za-z][A-Za-z0-9_]{0,62}$/.test(a)||!Array.isArray(c?.required)||!c.required.includes(a)||f?.type!=="string"||f?.format!=="date-time"||typeof u!="string"||t&&(p?.type!=="datetime"||p.nullable===!0))&&n.push(`WORKFLOW_INSTANCE_COMMAND_DEADLINE_FACT_INVALID:${i}`)}}return n}function eu(e,t){let o=e?.terminate?.capability;return typeof o=="string"&&/^app:[a-z][a-z0-9]*(?:-[a-z0-9]+)*:[A-Za-z0-9:._-]+$/.test(o)&&t.includes(o)}function tu(e){return e?.withdraw?.reasonRequired!==!1}function er(e){if(typeof e!="string")return null;let t=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,3}))?(Z|[+-]\d{2}:\d{2})$/.exec(e);if(!t)return null;let[,o,n,i,r,d,s]=t,a=t[8],c=new Date(Date.UTC(Number(o),Number(n),0)).getUTCDate();if(Number(n)<1||Number(n)>12||Number(i)<1||Number(i)>c||Number(r)>23||Number(d)>59||Number(s)>59||a!=="Z"&&(Number(a.slice(1,3))>23||Number(a.slice(4))>59))return null;let f=Date.parse(e);return Number.isFinite(f)?f:null}function nu(e,t,o,n){let i=e?.[t];if(!i||i.beforeFact===void 0)return null;let r=i.beforeFact,d=Ve(o),s=r&&d&&Object.hasOwn(d,r)?er(d[r]):null,a=n instanceof Date?n.getTime():er(n);return s===null||a===null||!Number.isFinite(a)?"WORKFLOW_V2_CANCELLATION_DEADLINE_INVALID":a<s?null:"WORKFLOW_V2_CANCELLATION_DEADLINE_PASSED"}var Ct="openxiangda.workflow.step.requested.v2",ir=[Ct,"openxiangda.workflow.step.result_received.v2","openxiangda.workflow.step.completed.v2","openxiangda.workflow.step.continuation_failed.v2"],_o=16384,xa=2048,iu="steps",go=/^[A-Za-z][A-Za-z0-9_-]{0,127}$/,rr=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,Ge=new Set(["__proto__","prototype","constructor"]),K=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&[Object.prototype,null].includes(Object.getPrototypeOf(e)),sr=e=>{try{let t=JSON.stringify(e);return t===void 0?1/0:new TextEncoder().encode(t).length}catch{return 1/0}},at=(e,t,o=0)=>{if(o>32)return!1;if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((r,d)=>at(r,t[d],o+1));if(!K(e)||!K(t))return!1;let n=Object.keys(e).filter(r=>e[r]!==void 0),i=Object.keys(t).filter(r=>t[r]!==void 0);return n.length===i.length&&n.every(r=>Object.hasOwn(t,r)&&at(e[r],t[r],o+1))};function po(e,t){let o=0,n=(i,r)=>++o>1e4||r>8?!1:i===null||typeof i=="boolean"||typeof i=="string"?!0:typeof i=="number"?Number.isFinite(i):Array.isArray(i)?i.length<=200&&i.every(d=>n(d,r+1)):K(i)&&Object.keys(i).length<=32&&Object.keys(i).every(d=>!Ge.has(d))&&Object.values(i).every(d=>n(d,r+1));return sr(e)<=t&&n(e,0)}function ja(e){return!K(e)||Object.keys(e).some(t=>!["executionId","handlerVersion","inputDigest","expectedFactRevision","output","receipt"].includes(t))?!1:/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/i.test(e.executionId||"")&&Number.isSafeInteger(e.handlerVersion)&&e.handlerVersion>=1&&e.handlerVersion<=1e6&&/^[a-f0-9]{64}$/.test(e.inputDigest||"")&&Number.isSafeInteger(e.expectedFactRevision)&&e.expectedFactRevision>=0&&K(e.output)&&po(e.output,_o)&&(e.receipt===void 0||K(e.receipt)&&po(e.receipt,xa))}function ru(e){return K(e)&&Object.keys(e).every(t=>["executionId","nodeId","handlerCode","handlerVersion","mode","dataTransaction","input","inputDigest","expectedFactRevision"].includes(t))&&typeof e.nodeId=="string"&&go.test(e.nodeId)&&!Ge.has(e.nodeId)&&typeof e.handlerCode=="string"&&/^[a-z][a-z0-9-]{0,100}$/.test(e.handlerCode)&&e.handlerCode.endsWith(`-v${e.handlerVersion}`)&&["pure","reconciled-effect"].includes(e.mode)&&(e.dataTransaction===void 0||e.dataTransaction===!0&&e.mode==="reconciled-effect")&&ja({executionId:e.executionId,handlerVersion:e.handlerVersion,inputDigest:e.inputDigest,expectedFactRevision:e.expectedFactRevision,output:e.input})}function en(e,t,o=_o){if(!po(t,o))return!1;let n=1e4,i=(r,d,s)=>{if(--n<0||s>8||!K(r))return!1;let a=d===null?"null":Array.isArray(d)?"array":typeof d=="number"&&Number.isSafeInteger(d)?"integer":typeof d,c=Array.isArray(r.type)?r.type:[r.type];if(!c.includes(a)&&!(a==="integer"&&c.includes("number"))||r.enum!==void 0&&(!Array.isArray(r.enum)||!r.enum.some(f=>at(f,d)))||Object.hasOwn(r,"const")&&!at(r.const,d))return!1;if(typeof d=="number")return Number.isFinite(d)&&(r.minimum===void 0||d>=r.minimum)&&(r.maximum===void 0||d<=r.maximum);if(typeof d=="string"){let f=Array.from(d).length;return(r.minLength===void 0||f>=r.minLength)&&(r.maxLength===void 0||f<=r.maxLength)}return Array.isArray(d)?d.length<=r.maxItems&&(r.minItems===void 0||d.length>=r.minItems)&&d.every(f=>i(r.items,f,s+1)):K(d)?!K(r.properties)||Object.keys(d).some(f=>Ge.has(f)||!Object.hasOwn(r.properties,f))||(Array.isArray(r.required)?r.required:[]).some(f=>!Object.hasOwn(d,f))||r.minProperties!==void 0&&Object.keys(d).length<r.minProperties||r.maxProperties!==void 0&&Object.keys(d).length>r.maxProperties?!1:Object.entries(d).every(([f,u])=>i(r.properties[f],u,s+1)):d===null||typeof d=="boolean"};return i(e,t,0)}function Wa(e){return typeof e=="string"&&e.length<=256&&e.split(".").length<=8&&e.split(".").every(t=>go.test(t)&&!Ge.has(t))}function tn(e){let t=0,o=(n,i)=>{if(!K(n)||i>6||++t>256||Object.keys(n).some(s=>!["type","title","description","properties","required","additionalProperties","items","maxItems","minItems","maxLength","minLength","minimum","maximum","enum","const","maxProperties","minProperties"].includes(s)))return!1;let r=Array.isArray(n.type)?n.type:[n.type];if(!r.length||r.length>2||r.some(s=>!["object","array","string","integer","number","boolean","null"].includes(s))||r.length>1&&(!r.includes("null")||new Set(r).size!==r.length))return!1;for(let s of["title","description"])if(n[s]!==void 0&&(typeof n[s]!="string"||n[s].length>2e3))return!1;for(let s of["minimum","maximum"])if(n[s]!==void 0&&(typeof n[s]!="number"||!Number.isFinite(n[s])))return!1;for(let[s,a]of[["maxItems",200],["minItems",200],["maxLength",16384],["minLength",16384],["maxProperties",32],["minProperties",32]])if(n[s]!==void 0&&(!Number.isSafeInteger(n[s])||n[s]<0||n[s]>a))return!1;for(let[s,a]of[["minimum","maximum"],["minItems","maxItems"],["minLength","maxLength"],["minProperties","maxProperties"]])if(n[s]!==void 0&&n[a]!==void 0&&n[s]>n[a])return!1;if(["properties","required","additionalProperties","maxProperties","minProperties"].some(s=>n[s]!==void 0)&&!r.includes("object")||["items","maxItems","minItems"].some(s=>n[s]!==void 0)&&!r.includes("array")||["maxLength","minLength"].some(s=>n[s]!==void 0)&&!r.includes("string")||["minimum","maximum"].some(s=>n[s]!==void 0)&&!r.some(s=>s==="integer"||s==="number")||n.enum!==void 0&&(!Array.isArray(n.enum)||!n.enum.length||n.enum.length>100)||r.includes("object")&&(!K(n.properties)||n.additionalProperties!==!1||Object.keys(n.properties).length>32||Object.keys(n.properties).some(s=>!rr.test(s)||Ge.has(s))||n.required!==void 0&&(!Array.isArray(n.required)||new Set(n.required).size!==n.required.length||n.required.some(s=>typeof s!="string"||!Object.hasOwn(n.properties,s)))||n.minProperties!==void 0&&n.minProperties>Object.keys(n.properties).length||n.maxProperties!==void 0&&n.maxProperties<(n.required?.length||0)||!Object.values(n.properties).every(s=>o(s,i+1)))||r.includes("array")&&(!Number.isSafeInteger(n.maxItems)||!o(n.items,i+1)))return!1;let d={...n};return delete d.enum,delete d.const,!(n.enum!==void 0&&(!n.enum.every(s=>en(d,s))||n.enum.some((s,a)=>n.enum.slice(0,a).some(c=>at(s,c))))||Object.hasOwn(n,"const")&&!en(d,n.const))};return K(e)&&e.type==="object"&&sr(e)<=_o&&o(e,0)}function nn(e){let t=Object.fromEntries(Object.values(e.nodes||{}).filter(o=>o?.kind==="action").map(o=>[o.id,o.outputSchema]));return Object.keys(t).length?{...e.inputSchema,properties:{...e.inputSchema?.properties,steps:{type:"object",additionalProperties:!1,properties:t}}}:e.inputSchema||{}}function ar(e,t){let o=e;for(let n of t.split(".")){if(!K(o?.properties)||!Object.hasOwn(o.properties,n))return;o=o.properties[n]}return K(o)?o:void 0}var nr=(e,t)=>!!ar(e,t);function su(e){return K(e)&&Object.keys(e).every(t=>["version","mode","dataTransaction","inputSchema","outputSchema"].includes(t))&&Number.isSafeInteger(e.version)&&e.version>=1&&e.version<=1e6&&["pure","reconciled-effect"].includes(e.mode)&&(e.dataTransaction===void 0||e.dataTransaction===!0&&e.mode==="reconciled-effect")&&tn(e.inputSchema)&&tn(e.outputSchema)}function or(e){return e.kind==="approval"?[e.onApprove,e.onReject]:e.kind==="condition"?[...Array.isArray(e.branches)?e.branches.map(t=>t.target):[],e.otherwise]:e.kind==="cc"||e.kind==="action"?[e.next]:[]}function mo(e,t=0){return!K(e)||t>16?[]:e.op==="path"?typeof e.path=="string"?[e.path]:[]:["left","right","value"].flatMap(o=>mo(e[o],t+1)).concat(Array.isArray(e.values)?e.values.flatMap(o=>mo(o,t+1)):[])}function on(e,t){if(!K(e)||!K(e.nodes))return["WORKFLOW_STEP_DEFINITION_INVALID"];let o=e.nodes,n=Object.entries(o).filter(([,s])=>s?.kind==="action");if(!n.length)return[];let i=[];Object.hasOwn(e.inputSchema?.properties||{},"steps")&&i.push("WORKFLOW_STEP_FACT_NAMESPACE_RESERVED");let r=nn(e);for(let[s,a]of n){(Object.keys(a).some(u=>!["id","kind","title","next","handler","inputSchema","outputSchema","inputs"].includes(u))||a.id!==s||!go.test(s)||Ge.has(s)||typeof a.title!="string"||!a.title.trim()||a.title.length>255||typeof a.next!="string"||!Object.hasOwn(o,a.next))&&i.push(`WORKFLOW_STEP_NODE_INVALID:${s}`);let c=a.handler;(!K(c)||Object.keys(c).some(u=>!["code","version","mode","dataTransaction"].includes(u))||!Number.isSafeInteger(c.version)||c.version<1||c.version>1e6||!/^[a-z][a-z0-9-]{0,100}$/.test(c.code||"")||!String(c.code).endsWith(`-v${c.version}`)||!["pure","reconciled-effect"].includes(c.mode)||c.dataTransaction!==void 0&&(c.dataTransaction!==!0||c.mode!=="reconciled-effect"))&&i.push(`WORKFLOW_STEP_HANDLER_INVALID:${s}`);let f=tn(a.inputSchema);if((!f||!tn(a.outputSchema))&&i.push(`WORKFLOW_STEP_SCHEMA_INVALID:${s}`),!K(a.inputs)||Object.keys(a.inputs).length>32){i.push(`WORKFLOW_STEP_INPUTS_INVALID:${s}`);continue}for(let u of Array.isArray(a.inputSchema?.required)?a.inputSchema.required:[])Object.hasOwn(a.inputs,u)||i.push(`WORKFLOW_STEP_INPUT_REQUIRED:${s}:${u}`);for(let[u,p]of Object.entries(a.inputs)){if(!rr.test(u)||Ge.has(u)||!Object.hasOwn(a.inputSchema?.properties||{},u)||!K(p)){i.push(`WORKFLOW_STEP_INPUT_INVALID:${s}:${u}`);continue}if(p.source==="literal")(!f||Object.keys(p).some(_=>!["source","value"].includes(_))||!Object.hasOwn(p,"value")||!en(a.inputSchema.properties[u],p.value))&&i.push(`WORKFLOW_STEP_LITERAL_INVALID:${s}:${u}`);else if(p.source!=="fact"||Object.keys(p).some(_=>!["source","path"].includes(_))||!Wa(p.path)||!nr(r,p.path))i.push(`WORKFLOW_STEP_FACT_PATH_INVALID:${s}:${u}`);else if(f){let _=ar(r,p.path),E=a.inputSchema.properties[u],A=Array.isArray(_.type)?_.type:[_.type],O=Array.isArray(E.type)?E.type:[E.type];A.some(b=>!O.includes(b)&&!(b==="integer"&&O.includes("number")))&&i.push(`WORKFLOW_STEP_FACT_TYPE_MISMATCH:${s}:${u}`)}}}let d=(s,a)=>{let c=new Set,f=[e.startAt||""];for(;f.length&&c.size<=200;){let u=f.shift();if(!(u===a||c.has(u)||!o[u])){if(u===s)return!0;c.add(u),f.push(...or(o[u]))}}return!1};for(let[s,a]of Object.entries(o)){if(!K(a))continue;let c=a.kind==="action"?Object.values(a.inputs||{}).flatMap(u=>u?.source==="fact"?[u.path]:[]):(Array.isArray(a.branches)?a.branches:[]).flatMap(u=>mo(u?.when)),f=t?.bindings?.[a.binding];f&&c.push(...[f.inputPath,f.departmentIdFrom,f.resourceIdFrom,f.scope?.valueFrom].filter(u=>typeof u=="string"));for(let u of c.filter(p=>typeof p=="string"&&p.startsWith("steps."))){let p=u.split(".")[1];(o[p]?.kind!=="action"||p===s||!nr(r,u)||d(s,p))&&i.push(`WORKFLOW_STEP_OUTPUT_NOT_AVAILABLE:${s}:${u}`)}}if(t)for(let[,s]of n){let a=new Set,c=[s.next];for(;c.length&&a.size<=200;){let f=c.shift();if(a.has(f)||!K(o[f]))continue;a.add(f);let u=o[f];if(!(u.kind==="action"||u.kind==="end")){if(u.kind==="approval"){let p=t.bindings?.[u.binding];p&&["application_provider","initiator_select"].includes(p.provider)&&i.push(`WORKFLOW_STEP_NEXT_PROVIDER_REQUIRES_PREPARED_RESULT:${f}`);continue}c.push(...or(u))}}}return[...new Set(i)]}function au(e,t){let o={};for(let[n,i]of Object.entries(e.inputs)){let r=i.source==="literal"?i.value:i.path.split(".").reduce((d,s)=>K(d)&&Object.hasOwn(d,s)?d[s]:void 0,t);r!==void 0&&(o[n]=r)}if(!en(e.inputSchema,o))throw new Error("WORKFLOW_STEP_INPUT_SCHEMA_INVALID");return o}function dr(e,t,o){let n=Ao(e),i=[];Object.keys(n).length&&!o&&i.push("WORKFLOW_STEP_BACKEND_REQUIRED");for(let r of Object.keys(n)){let d=t.find(s=>s.code===r);(!d||d.execution||d.action||!Array.isArray(d.eventTypes)||d.eventTypes.length!==1||d.eventTypes[0]!==Ct||!K(d.filter)||Object.keys(d.filter).length!==1||!K(d.filter.workflowStep)||Object.keys(d.filter.workflowStep).length!==1||d.filter.workflowStep.handlerCode!==r||!K(d.payload)||d.payload.includeChanges!==!1||!Array.isArray(d.payload.fields)||d.payload.fields.length)&&i.push(`WORKFLOW_STEP_SUBSCRIPTION_INVALID:${r}`)}for(let r of t)(r.eventTypes?.includes(Ct)&&!n[r.code]||r.filter?.workflowStep&&!n[r.code])&&i.push(`WORKFLOW_STEP_HANDLER_NOT_DECLARED:${r.code}`);return i}function Ao(e){let t={};for(let o of e){let n=on(o);if(n.length)throw new Error(n.join("; "));for(let i of Object.values(o.nodes||{})){if(i.kind!=="action")continue;let r={version:i.handler.version,mode:i.handler.mode,...i.handler.dataTransaction?{dataTransaction:!0}:{},inputSchema:i.inputSchema,outputSchema:i.outputSchema},d=t[i.handler.code];if(d&&!at(d,r))throw new Error(`WORKFLOW_STEP_HANDLER_CONTRACT_CONFLICT:${i.handler.code}`);t[i.handler.code]=r}}return t}var pe=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},qe=(e,t)=>typeof e=="string"&&!!e.trim()&&e.length<=t,Ua=/^[A-Za-z][A-Za-z0-9_-]*(?:\.[A-Za-z][A-Za-z0-9_-]*){0,15}$/,Eo=e=>typeof e=="string"&&e.length<=256&&Ua.test(e)&&!e.split(".").some(t=>["__proto__","prototype","constructor"].includes(t));function sn(e,t){let o=pe(e),n=!0;for(let i of t.split(".")){n&&=Array.isArray(o.required)&&o.required.includes(i);let r=pe(o.properties)[i];if(!r||typeof r!="object")return null;o=pe(r)}return{schema:o,required:n}}function cr(e){let t=new Set,o=[],n=2048,i=(r,d)=>{if(--n<0||d>20){o.push("WORKFLOW_EXPRESSION_BUDGET_EXCEEDED");return}let s=pe(r);if(s.op==="path")Eo(s.path)?t.add(s.path):o.push("WORKFLOW_EXPRESSION_PATH_INVALID");else{if(s.op==="literal")return;if(s.op==="and"||s.op==="or")if(!Array.isArray(s.values)||!s.values.length||s.values.length>128)o.push("WORKFLOW_EXPRESSION_GROUP_INVALID");else for(let a of s.values){if(n<0)break;i(a,d+1)}else s.op==="not"||s.op==="exists"?i(s.value,d+1):["eq","neq","gt","gte","lt","lte","in","contains"].includes(String(s.op))?(i(s.left,d+1),i(s.right,d+1)):o.push("WORKFLOW_EXPRESSION_OPERATOR_INVALID")}};return i(e,0),{paths:[...t],errors:[...new Set(o)]}}function lr(e){if(e?.readability===void 0)return[];let t=[],o=nn(e),n=pe(e.readability);(Object.keys(n).some(s=>!["variables","logic"].includes(s))||!Object.keys(n).length)&&t.push("WORKFLOW_READABILITY_INVALID");let i=pe(n.variables);n.variables!==void 0&&(typeof n.variables!="object"||Array.isArray(n.variables)||n.variables===null)&&t.push("WORKFLOW_VARIABLES_INVALID"),Object.keys(i).length>128&&t.push("WORKFLOW_VARIABLE_LIMIT_EXCEEDED");for(let[s,a]of Object.entries(i)){let c=pe(a);(!Eo(s)||!sn(o,s))&&t.push(`WORKFLOW_VARIABLE_SOURCE_UNKNOWN:${s}`),(!qe(c.label,160)||Object.keys(c).some(f=>!["label","unit","description"].includes(f))||c.unit!==void 0&&!qe(c.unit,32)||c.description!==void 0&&!qe(c.description,2e3))&&t.push(`WORKFLOW_VARIABLE_METADATA_INVALID:${s}`)}let r=n.logic===void 0?[]:n.logic;(!Array.isArray(r)||r.length>32)&&t.push("WORKFLOW_LOGIC_LIMIT_INVALID");let d=new Set;for(let s of Array.isArray(r)?r.slice(0,32):[]){let a=pe(s),c=String(a.code||"");e.approvedDelegation&&c==="kernel-approved-delegation"&&t.push("WORKFLOW_LOGIC_PLATFORM_CODE_RESERVED"),(!/^[a-z][a-z0-9-]{2,63}$/.test(c)||d.has(c)||!qe(a.title,160)||!qe(a.description,4e3)||Object.keys(a).some(f=>!["code","title","description","phase","nodeId","inputPaths","outputPaths","source"].includes(f)))&&t.push(`WORKFLOW_LOGIC_METADATA_INVALID:${c}`),d.add(c),(!["submission","node_input","completion"].includes(String(a.phase))||a.phase==="node_input"&&!pe(e.nodes)[String(a.nodeId)]||a.phase!=="node_input"&&a.nodeId!==void 0)&&t.push(`WORKFLOW_LOGIC_ANCHOR_INVALID:${c}`);for(let f of["inputPaths","outputPaths"]){let u=a[f];if(!(f==="outputPaths"&&u===void 0))if(!Array.isArray(u)||u.length>32||new Set(u).size!==u.length)t.push(`WORKFLOW_LOGIC_PATHS_INVALID:${c}:${f}`);else for(let p of u)(!Eo(p)||!sn(o,p))&&t.push(`WORKFLOW_LOGIC_SOURCE_UNKNOWN:${c}:${String(p)}`)}if(a.source!==void 0){let f=pe(a.source);(!qe(f.path,256)||String(f.path).startsWith("/")||String(f.path).includes("..")||String(f.path).includes("://")||!/^sha256:[a-f0-9]{64}$/.test(String(f.digest))||f.symbol!==void 0&&!qe(f.symbol,160)||Object.keys(f).some(u=>!["path","symbol","digest"].includes(u)))&&t.push(`WORKFLOW_LOGIC_SOURCE_REFERENCE_INVALID:${c}`)}}for(let s of Object.values(pe(e.nodes))){let a=pe(s),c=Array.isArray(a.branches)?a.branches:[];for(let f of c){let u=cr(f.when);t.push(...u.errors.map(p=>`${p}:${a.id}`));for(let p of u.paths)sn(o,p)||t.push(`WORKFLOW_VARIABLE_SOURCE_UNKNOWN:${a.id}:${p}`)}}return[...new Set(t)]}function lu(e,t){let o=nn(e),n=[],i=new Map,r=[];for(let c of Object.values(e.nodes)){if(c.kind==="approval")for(let[f,u,p]of[["approve",c.onApprove,"\u540C\u610F"],["reject",c.onReject,"\u62D2\u7EDD"]])u&&n.push({id:`${c.id}:${f}`,from:c.id,to:u,kind:f,label:p,variablePaths:[]});if(c.kind==="approval")for(let f of new Set(c.returnTargets||[]))e.nodes[f]?.kind==="correction"&&n.push({id:`${c.id}:return:${f}`,from:c.id,to:f,kind:"return",label:"\u9000\u56DE\u53D1\u8D77\u4EBA\u8865\u6B63",variablePaths:[]});if(c.kind==="correction"&&c.next&&n.push({id:`${c.id}:resubmit`,from:c.id,to:c.next,kind:"resubmit",label:"\u91CD\u65B0\u63D0\u4EA4\uFF0C\u4ECE\u8D77\u70B9\u91CD\u7B97",variablePaths:[]}),c.kind==="cc"&&c.next&&n.push({id:`${c.id}:next`,from:c.id,to:c.next,kind:"next",label:"\u6284\u9001\u540E\u7EE7\u7EED",variablePaths:[]}),c.kind==="action"&&c.next){let f=Object.values(c.inputs||{}).flatMap(u=>u.source==="fact"?[u.path]:[]);for(let u of f)i.has(u)||i.set(u,new Set),i.get(u).add(c.id);n.push({id:`${c.id}:next`,from:c.id,to:c.next,kind:"next",label:"\u6210\u529F\u56DE\u6267\u540E\u7EE7\u7EED",variablePaths:f})}if(c.kind==="condition"){for(let[f,u]of(c.branches||[]).entries()){let p=cr(u.when);for(let _ of p.paths)i.has(_)||i.set(_,new Set),i.get(_).add(c.id);n.push({id:`${c.id}:branch:${f}`,from:c.id,to:u.target,kind:"branch",label:u.label||`\u6761\u4EF6 ${f+1}`,priority:f+1,expression:u.when,variablePaths:p.paths}),r.push(...p.errors.map(_=>({code:_,path:c.id})))}c.otherwise&&n.push({id:`${c.id}:default`,from:c.id,to:c.otherwise,kind:"default",label:"\u5747\u4E0D\u6EE1\u8DB3\u65F6",variablePaths:[]})}}let d=[...e.readability?.logic||[]];if(e.approvedDelegation){let c=e.approvedDelegation,f=c.confirmer==="initiator"?"\u7533\u8BF7\u4EBA\u672C\u4EBA":"\u6240\u9009\u4EE3\u7406\u4EBA";d.push({code:"kernel-approved-delegation",title:"\u6279\u51C6\u540E\u6574\u6279\u6388\u6743\u4EE3\u7406",phase:"completion",inputPaths:[c.requestsField],description:`\u6279\u51C6\u65F6\u6838\u9A8C${f}\u5728\u5F53\u524D\u9000\u56DE\u5468\u671F\u5B8C\u6210\u201C${e.nodes[c.confirmationNodeId]?.title||c.confirmationNodeId}\u201D\u7684\u4EBA\u5DE5\u786E\u8BA4\uFF1B\u968F\u540E\u91CD\u65B0\u6838\u9A8C\u53CC\u65B9\u5F53\u524D\u8D26\u53F7\u3001\u804C\u8D23\u3001\u4FEE\u8BA2\u3001\u8303\u56F4\u4E0E\u5B8C\u6574\u6709\u6548\u671F\uFF0C\u6574\u6279\u6388\u6743\uFF08\u6700\u591A${c.maxRequests}\u884C\uFF09\u3002\u4EFB\u4E00\u884C\u5931\u8D25\uFF0C\u6279\u51C6\u4E0E\u5168\u90E8\u6388\u6743\u4E00\u8D77\u56DE\u6EDA\uFF1B\u539F\u547D\u4EE4\u6062\u590D\u4E0D\u91CD\u65B0\u6FC0\u6D3B\u5DF2\u64A4\u9500\u6388\u6743\u3002`})}let a=[...new Set([...i.keys(),...Object.keys(e.readability?.variables||{}),...d.flatMap(c=>[...c.inputPaths,...c.outputPaths||[]])])].slice(0,128).map(c=>{let f=sn(o,c),u=e.readability?.variables?.[c],p=c.split("."),_=e.subject?.factProjection[p[0]],E=p[0]==="steps"?e.nodes[p[1]]:void 0;return f||r.push({code:"WORKFLOW_VARIABLE_SOURCE_UNKNOWN",path:c}),{path:c,label:u?.label||String(f?.schema.title||c),type:String(f?.schema.type||"unknown"),...u,required:f?.required||!1,usedBy:[...i.get(c)||[]],source:f&&E?.handler?{kind:"step_output",nodeId:E.id,handlerCode:E.handler.code,handlerVersion:E.handler.version}:f&&_&&e.subject?{kind:"subject_field",resourceCode:e.subject.resourceCode,fieldPath:[_,...p.slice(1)].join(".")}:{kind:f?"input":"unknown"}}});return{schemaVersion:"openxiangda.workflow-graph/v2",workflowCode:e.code,definitionDigest:t,startAt:e.startAt,fixedTopology:!0,branchStrategy:"first_match",nodes:Object.values(e.nodes).map(c=>({id:c.id,kind:c.kind,title:c.title||c.id,...c.binding?{binding:c.binding}:{},...c.mode?{mode:c.mode}:{},...c.outcome?{outcome:c.outcome}:{},...c.kind==="cc"?{emptyPolicy:c.emptyPolicy,notify:c.notify!==!1}:{},...c.kind==="approval"?{emptyPolicy:c.emptyPolicy||"block",initiatorApprovalPolicy:c.initiatorApprovalPolicy||"manual",...c.completionDeadline?{completionDeadline:{...c.completionDeadline}}:{}}:{},...c.kind==="action"&&c.handler?{businessStep:{handler:c.handler,inputs:c.inputs||{},outputPaths:Object.keys(pe(c.outputSchema).properties||{}).map(f=>`steps.${c.id}.${f}`)}}:{}})),edges:n,variables:a,logic:d,diagnostics:r}}function Ma(e,t=[]){let o=i=>{let r=t.find(d=>d.path===i)?.label;return r&&r!==i?r:void 0},n=o(e);if(n)return n;for(let i=e.lastIndexOf(".");i>0;i=e.lastIndexOf(".",i-1)){let r=o(e.slice(0,i));if(!r)continue;let d=e.slice(i+1);return d==="value"?`${r}\uFF08\u503C\uFF09`:d==="label"?`${r}\uFF08\u663E\u793A\u540D\u79F0\uFF09`:`${r}.${d}`}return e}function rn(e,t=[],o=0){if(!e||o>20)return"\u65E0\u6CD5\u8BC6\u522B\u7684\u6761\u4EF6";if(e.op==="path")return Ma(e.path,t);if(e.op==="literal")return JSON.stringify(e.value)??"\u7F3A\u503C";if(e.op==="and"||e.op==="or")return e.values.slice(0,128).map(d=>`\uFF08${rn(d,t,o+1)}\uFF09`).join(e.op==="and"?" \u4E14 ":" \u6216 ");if(e.op==="not"||e.op==="exists")return`${e.op==="not"?"\u4E0D\u6EE1\u8DB3":"\u5B58\u5728"}\uFF08${rn(e.value,t,o+1)}\uFF09`;if(!("left"in e))return"\u65E0\u6CD5\u8BC6\u522B\u7684\u6761\u4EF6";let n={eq:"=",neq:"\u2260",gt:">",gte:"\u2265",lt:"<",lte:"\u2264",in:"\u5C5E\u4E8E",contains:"\u5305\u542B"},i=e.left.op==="path"?e.left.path:void 0,r=i&&e.right.op==="literal"&&typeof e.right.value=="number"?t.find(d=>d.path===i)?.unit:void 0;return`${rn(e.left,t,o+1)} ${n[e.op]} ${rn(e.right,t,o+1)}${r?` ${r}`:""}`}function ur(e,t=0){return!Array.isArray(e)||e.length>64||t>1?!1:e.every(o=>{if(!o||typeof o!="object"||Array.isArray(o)||o.readonlyWhen!==void 0)return!1;if(o.subtable!==void 0){let n=o.subtable;return n&&n.create===!1&&n.delete===!1&&n.reorder===!1&&ur(n.fields,t+1)}return o.readonly===!0})}function ht(e){let t=[];for(let[o,n]of Object.entries(e?.nodes||{}))if(n.initiatorApprovalPolicy!==void 0){if(n.kind!=="approval"||!["manual","auto_approve"].includes(n.initiatorApprovalPolicy)){t.push(`WORKFLOW_INITIATOR_APPROVAL_POLICY_INVALID:${o}`);continue}n.initiatorApprovalPolicy==="auto_approve"&&((n.taskPageCode!==void 0&&(typeof n.taskPageCode!="string"||!ur(e.taskPages?.[n.taskPageCode]?.fields))||[n.fieldPolicy?.default,...Object.values(n.fieldPolicy?.fields||{})].some(i=>i==="edit"||i==="edit_required"))&&t.push(`WORKFLOW_INITIATOR_APPROVAL_INPUT_REQUIRED:${o}`),n.operationPolicy?.approve?.commentRequired===!0&&t.push(`WORKFLOW_INITIATOR_APPROVAL_COMMENT_REQUIRED:${o}`))}return t}function fu(e,t,o,n,i){return e.kind==="approval"&&e.initiatorApprovalPolicy==="auto_approve"&&ht({nodes:{node:e},...i?{taskPages:i}:{}}).length===0&&t!=="return_review"&&!!o&&n.user_id===o&&n.status==="active"&&n.participant_kind==="primary"&&["resolution","resolution_retry"].includes(n.source||"")&&!n.source_participant_id&&!n.delegate_authorization_id}var mu=8,_u={type:"array",minItems:2,maxItems:8,uniqueItems:!0,items:{type:"string",maxLength:128,pattern:"^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$"}};function an(e){if(e.roleCodes===void 0)return[];let t=e.roleCodes;if(!["app_role","app_role_in_scope"].includes(e.provider||"")||e.roleCode!==void 0||e.candidateField!==void 0||!Array.isArray(t)||t.length<2||t.length>8||new Set(t).size!==t.length||t.some(o=>typeof o!="string"||o.length>128||!/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/.test(o)))return["WORKFLOW_V2_BINDING_ROLE_UNION_INVALID"];if(e.provider==="app_role_in_scope"){let o=e.scope,n=typeof o?.value=="string"&&o.value.length>0&&o.value.length<=255&&o.valueFrom===void 0,i=typeof o?.valueFrom=="string"&&o.valueFrom.length<=255&&/^[A-Za-z][A-Za-z0-9_-]*(?:\.[A-Za-z][A-Za-z0-9_-]*)*$/.test(o.valueFrom)&&!o.valueFrom.split(".").some(r=>["__proto__","prototype","constructor"].includes(r))&&o.value===void 0;if(!o||typeof o!="object"||Array.isArray(o)||Object.keys(o).some(r=>!["dimension","value","valueFrom"].includes(r))||typeof o.dimension!="string"||!/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/.test(o.dimension)||!n&&!i)return["WORKFLOW_V2_BINDING_ROLE_UNION_SCOPE_INVALID"]}else if(e.scope!==void 0)return["WORKFLOW_V2_BINDING_ROLE_UNION_SCOPE_INVALID"];return[]}function gu(e){return e.roleCodes?[...e.roleCodes]:e.roleCode?[e.roleCode]:[]}function fr(e){return e.some(t=>Object.values(t.binding.bindings).some(o=>o.roleCodes!==void 0))}function pr(e){if(e.selectedInputPath===void 0)return[];let t=e.selectedInputPath;return!["app_role","app_role_in_scope"].includes(e.provider||"")||e.candidateField!==void 0||e.inputPath!==void 0||e.routing!==void 0||e.roleCode===void 0&&e.roleCodes===void 0||typeof t!="string"||t.length>255||!/^[A-Za-z][A-Za-z0-9_-]*(?:\.[A-Za-z][A-Za-z0-9_-]*)*$/.test(t)||t.split(".").some(o=>["__proto__","constructor","prototype"].includes(o))?["WORKFLOW_V2_ROLE_INPUT_SELECTION_INVALID"]:[]}function mr(e){return e.some(t=>Object.values(t.binding.bindings).some(o=>o.selectedInputPath!==void 0))}var _r=20,gr=200,Ba=["fixed_users","initiator","input_users","form_field_users","app_role","app_role_in_scope","previous_node_actor"];function Io(e,t){let o=[];for(let[n,i]of Object.entries(e?.nodes||{})){if(i?.kind!=="cc"||((Object.keys(i).some(a=>!["id","kind","title","binding","next","emptyPolicy","notify","administration"].includes(a))||typeof i.title!="string"||!i.title.trim()||i.title.length>255||typeof i.binding!="string"||!i.binding.trim()||i.binding.length>255||typeof i.next!="string"||!i.next.trim()||!e.nodes?.[i.next]||!["block","skip"].includes(i.emptyPolicy)||i.notify!==void 0&&typeof i.notify!="boolean")&&o.push(`WORKFLOW_CC_NODE_INVALID:${n}`),!t))continue;let r=t.bindings?.[i.binding];if(!r){o.push(`WORKFLOW_CC_BINDING_NOT_FOUND:${n}`);continue}Ba.includes(r.provider)||o.push(`WORKFLOW_CC_PROVIDER_INVALID:${n}`);let d=r.min??1,s=r.max??20;(!Number.isSafeInteger(d)||!Number.isSafeInteger(s)||d<1||s<d||s>200||r.provider==="fixed_users"&&(!Array.isArray(r.users)||!r.users.length||r.users.length>s))&&o.push(`WORKFLOW_CC_RECIPIENT_LIMIT_INVALID:${n}`)}return[...new Set(o)]}var yo=["approve","reject","return","transfer","delegate","add_assignee"],bo=["fixed_users","app_role","app_role_in_scope"],Ka=["single","any","all","sequence"],Le=e=>!!e&&typeof e=="object"&&!Array.isArray(e),ze=(e,t)=>Object.keys(e).every(o=>t.includes(o)),dn=(e,t,o)=>Array.isArray(e)&&e.length>0&&e.length<=o&&new Set(e).size===e.length&&e.every(n=>typeof n=="string"&&t.includes(n));function wt(e){return e.allowedOperations||[...yo]}function Ga(e,t){return t?.commentRequired??e==="reject"}function qa(e,t){return!["transfer","delegate","add_assignee","return"].includes(e)||t?.reasonRequired!==!1}function Er(e,t,o={},n=!1){return!(!Le(e)||!Object.keys(e).length||!ze(e,n?["enabled","label","commentRequired","reasonRequired"]:["label","commentRequired","reasonRequired"])||e.label!==void 0&&(typeof e.label!="string"||!e.label.trim()||e.label.length>40||/[\u0000-\u001f\u007f]/.test(e.label))||e.enabled!==void 0&&(typeof e.enabled!="boolean"||["approve","reject"].includes(t)&&!e.enabled)||e.commentRequired!==void 0&&(typeof e.commentRequired!="boolean"||!["approve","reject"].includes(t)||n&&Ga(t,o)&&!e.commentRequired)||e.reasonRequired!==void 0&&(typeof e.reasonRequired!="boolean"||!["transfer","delegate","add_assignee","return"].includes(t)||n&&qa(t,o)&&!e.reasonRequired))}function Oo(e,t){let o=[];for(let[n,i]of Object.entries(e?.nodes||{})){if(!Le(i))continue;let r=i.administration,d=i.operationPolicy;if(i.kind==="cc"){(d!==void 0||r!==void 0&&(!Le(r)||!ze(r,["assigneeProviders"])))&&o.push(`WORKFLOW_NODE_ADMINISTRATION_INVALID:${n}`),r?.assigneeProviders!==void 0&&!dn(r.assigneeProviders,bo,3)&&o.push(`WORKFLOW_NODE_ADMINISTRATION_PROVIDERS_INVALID:${n}`),r?.assigneeProviders?.includes("app_role_in_scope")&&t&&!t.bindings[i.binding||""]?.scope&&o.push(`WORKFLOW_NODE_ADMINISTRATION_SCOPE_REQUIRED:${n}`);continue}if(i.kind!=="approval"){(r!==void 0||d!==void 0)&&o.push(`WORKFLOW_NODE_ADMINISTRATION_APPROVAL_REQUIRED:${n}`);continue}if(d!==void 0&&(!Le(d)||Object.keys(d).length>8||Object.entries(d).some(([a,c])=>!yo.includes(a)||!wt(i).includes(a)||!Er(c,a)))&&o.push(`WORKFLOW_NODE_OPERATION_POLICY_INVALID:${n}`),r===void 0)continue;if(!Le(r)||!ze(r,["modes","assigneeProviders","operations"])){o.push(`WORKFLOW_NODE_ADMINISTRATION_INVALID:${n}`);continue}r.modes!==void 0&&(!dn(r.modes,Ka,4)||!r.modes.includes(i.mode))&&o.push(`WORKFLOW_NODE_ADMINISTRATION_MODES_INVALID:${n}`),r.assigneeProviders!==void 0&&!dn(r.assigneeProviders,bo,3)&&o.push(`WORKFLOW_NODE_ADMINISTRATION_PROVIDERS_INVALID:${n}`);let s=t?.bindings[i.binding||""];s&&Array.isArray(r.assigneeProviders)&&r.assigneeProviders.includes("app_role_in_scope")&&!s.scope&&o.push(`WORKFLOW_NODE_ADMINISTRATION_SCOPE_REQUIRED:${n}`),r.operations!==void 0&&(!dn(r.operations,yo,8)||r.operations.some(a=>!wt(i).includes(a)))&&o.push(`WORKFLOW_NODE_ADMINISTRATION_OPERATIONS_INVALID:${n}`)}return o}function Ou(e,t,o,n){let i=[];if(!e||!Le(o)||!Object.keys(o).length||!ze(o,["title","description","assignee","mode","operations"]))return["WORKFLOW_V2_NODE_CONFIGURATION_PATCH_INVALID"];let r=o;for(let s of["title","description"])r[s]!==void 0&&(typeof r[s]!="string"||r[s].length>(s==="title"?255:1e3)||s==="title"&&!r[s].trim())&&i.push("WORKFLOW_V2_NODE_CONFIGURATION_PATCH_INVALID");let d=e.administration;if(r.mode!==void 0&&(e.kind!=="approval"||!d?.modes?.includes(r.mode))&&i.push("WORKFLOW_V2_NODE_CONFIGURATION_MODE_READONLY"),r.operations!==void 0&&(e.kind!=="approval"||!Le(r.operations)||!Object.keys(r.operations).length||Object.keys(r.operations).length>8||Object.entries(r.operations).some(([s,a])=>!d?.operations?.includes(s)||!wt(e).includes(s)||!Er(a,s,e.operationPolicy?.[s],!0)))&&i.push("WORKFLOW_V2_NODE_CONFIGURATION_OPERATION_INVALID"),r.assignee!==void 0){let s=r.assignee,a=d?.assigneeProviders||(e.kind==="approval"&&t&&bo.includes(t.provider)?[t.provider]:[]);if(t?.selectedInputPath&&!["app_role","app_role_in_scope"].includes(s?.provider||"")&&i.push("WORKFLOW_V2_NODE_CONFIGURATION_PROVIDER_READONLY"),!Le(s)||!["approval","cc"].includes(e.kind)||!a.includes(s.provider)||s.provider==="app_role_in_scope"&&!t?.scope)i.push("WORKFLOW_V2_NODE_CONFIGURATION_PROVIDER_READONLY");else if(s.provider==="fixed_users"){let c=e.kind==="cc"?t?.min??1:e.emptyPolicy==="skip"?0:1,f=e.kind==="cc"?Math.min(t?.max??20,200):200;(!ze(s,["provider","users"])||!Array.isArray(s.users)||s.users.length<c||s.users.length>f||new Set(s.users).size!==s.users.length||s.users.some(u=>typeof u!="string"||!u.trim()||u.length>255))&&i.push("WORKFLOW_V2_NODE_CONFIGURATION_USERS_INVALID")}else s.roleCodes!==void 0?(!ze(s,["provider","roleCodes"])||an({...s,...s.provider==="app_role_in_scope"?{scope:t?.scope}:{}}).length)&&i.push("WORKFLOW_V2_NODE_CONFIGURATION_ROLE_INVALID"):(!ze(s,["provider","roleCode"])||typeof s.roleCode!="string"||!/^[a-z][a-z0-9_-]{0,127}$/.test(s.roleCode))&&i.push("WORKFLOW_V2_NODE_CONFIGURATION_ROLE_INVALID")}return i.push(...ht({nodes:{node:{...e,operationPolicy:Ar(e,r).operationPolicy}},...n?{taskPages:n}:{}})),e.completionDeadline&&Ar(e,r).operationPolicy.approve?.commentRequired===!0&&i.push("WORKFLOW_COMPLETION_DEADLINE_INPUT_REQUIRED:node"),i}function Ar(e,t){let o=Object.fromEntries(wt(e).flatMap(n=>{let i=n,r=t?.operations?.[i],d={...e.operationPolicy?.[i],...r?.label!==void 0?{label:r.label}:{},...r?.commentRequired!==void 0?{commentRequired:r.commentRequired}:{},...r?.reasonRequired!==void 0?{reasonRequired:r.reasonRequired}:{}};return Object.keys(d).length?[[i,d]]:[]}));return{mode:t?.mode||e.mode,initiatorApprovalPolicy:e.initiatorApprovalPolicy||"manual",allowedOperations:wt(e).filter(n=>t?.operations?.[n]?.enabled!==!1),operationPolicy:o,fieldPolicy:{default:e.fieldPolicy?.default||"readonly",fields:{...e.fieldPolicy?.fields}}}}var Ir=["fixed_users","input_users","form_field_users","app_role","app_role_in_scope"];function No(e,t){let o=[];for(let[n,i]of Object.entries(e?.nodes||{}))i.kind==="cc"||i.emptyPolicy===void 0||(i.kind!=="approval"||!["block","skip"].includes(i.emptyPolicy)?o.push(`WORKFLOW_APPROVAL_EMPTY_POLICY_INVALID:${n}`):i.emptyPolicy==="skip"&&t&&!Ir.includes(t.bindings?.[i.binding||""]?.provider)&&o.push(`WORKFLOW_APPROVAL_EMPTY_PROVIDER_UNSUPPORTED:${n}`));return o}function Tu(e,t){return e.kind==="approval"&&e.emptyPolicy==="skip"&&t?.emptyResult==="no_candidates"&&Ir.includes(t.provider)&&Array.isArray(t.candidates)&&t.candidates.length===0&&Array.isArray(t.selected)&&t.selected.length===0&&Array.isArray(t.warnings)&&t.warnings.length===0}function yr(e,t){let o=Object.values(e.nodes||{}).filter(n=>n.binding===t);return o.length>0&&o.every(n=>n.kind==="approval"&&n.emptyPolicy==="skip")}function br(e,t=0){return!Array.isArray(e)||e.length>64||t>1?!0:e.some(o=>!o||typeof o!="object"||Array.isArray(o)||o.required===!0||o.requiredWhen!==void 0||o.subtable!==void 0&&(!o.subtable||br(o.subtable.fields,t+1)))}function Cu(e){let t=e.afterSeconds;return`\u8FDB\u5165\u540E ${t%86400===0?`${t/86400} \u5929`:t%3600===0?`${t/3600} \u5C0F\u65F6`:t%60===0?`${t/60} \u5206\u949F`:`${t} \u79D2`}\u672A\u5B8C\u6210\uFF0C\u81EA\u52A8\u540C\u610F`}function Or(e){let t=[];for(let[o,n]of Object.entries(e?.nodes||{})){if(!n||typeof n!="object"||n.completionDeadline===void 0)continue;let i=n.completionDeadline;if(n.kind!=="approval"||!i||typeof i!="object"||Array.isArray(i)||Object.keys(i).length!==2||Object.keys(i).some(d=>!["afterSeconds","action"].includes(d))||i.action!=="approve"||!Number.isInteger(i.afterSeconds)||i.afterSeconds<1||i.afterSeconds>2592e3){t.push(`WORKFLOW_COMPLETION_DEADLINE_INVALID:${o}`);continue}n.allowedOperations&&!n.allowedOperations.includes("approve")&&t.push(`WORKFLOW_COMPLETION_DEADLINE_APPROVE_UNAVAILABLE:${o}`);let r=n.taskPageCode?e.taskPages?.[n.taskPageCode]:void 0;(n.taskPageCode&&(!r||br(r.fields))||[n.fieldPolicy?.default,...Object.values(n.fieldPolicy?.fields||{})].includes("edit_required")||n.operationPolicy?.approve?.commentRequired===!0||e.commandHandlers?.approve!==void 0)&&t.push(`WORKFLOW_COMPLETION_DEADLINE_INPUT_REQUIRED:${o}`)}return t}var za="openxiangda.workflow-rejection-notification/v1",wu=4096;function Nr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function dt(e,t){return typeof e=="string"&&e.trim().length>0&&e.length<=t}function To(e,t){return Object.keys(e).sort().join(",")===t.sort().join(",")}function Tr(e){let t=e?.rejectionNotification;return t===void 0?[]:!Nr(t)||!To(t,["recipient","title","summary"])||t.recipient!=="record_last_modifier"||!dt(t.title,160)||!dt(t.summary,500)?["WORKFLOW_REJECTION_NOTIFICATION_INVALID"]:dt(e.subject?.resourceCode,63)?[]:["WORKFLOW_REJECTION_NOTIFICATION_SUBJECT_REQUIRED"]}function Su(e){if(!Nr(e)||e.schemaVersion!==za||e.recipient!=="record_last_modifier"||!dt(e.title,160)||!dt(e.summary,500))return!1;let t=["schemaVersion","recipient","title","summary","status","sourceRevision"];if(e.status==="ready"){if(!To(e,[...t,"userId"])||!dt(e.userId,255)||!Number.isSafeInteger(e.sourceRevision)||Number(e.sourceRevision)<1)return!1}else if(e.status==="skipped"){if(!To(e,[...t,"reason"])||!["record_missing","modifier_missing","modifier_ineligible"].includes(String(e.reason))||(e.reason==="record_missing"?e.sourceRevision!==null:!Number.isSafeInteger(e.sourceRevision)||Number(e.sourceRevision)<1))return!1}else return!1;return new TextEncoder().encode(JSON.stringify(e)).byteLength<=4096}function Rr(e,t){let o=e.commandHandlers;if(o===void 0)return[];if(!o||typeof o!="object"||Array.isArray(o)||!Object.keys(o).length||Object.keys(o).some(i=>!["approve","reject","withdraw","resubmit"].includes(i)))return["WORKFLOW_BUSINESS_COMMAND_HANDLERS_INVALID"];let n=[];o.resubmit&&!Object.values(e.nodes||{}).some(i=>i.kind==="correction")&&n.push("WORKFLOW_BUSINESS_CORRECTION_REQUIRED");for(let[i,r]of Object.entries(o)){if(!r||typeof r!="object"||Array.isArray(r)||Object.keys(r).some(s=>!["operationCode","transitionPolicy","derivedSubjectFields"].includes(s))||r.transitionPolicy!==void 0&&(i!=="approve"||r.transitionPolicy!=="workflow")||!/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/.test(r.operationCode||"")){n.push("WORKFLOW_BUSINESS_COMMAND_HANDLER_INVALID");continue}if(r.derivedSubjectFields!==void 0){let s=r.derivedSubjectFields,a=new Set(Object.values(e.subject?.factProjection||{}));(i!=="resubmit"||!Array.isArray(s)||s.length<1||s.length>32||new Set(s).size!==s.length||s.some(c=>typeof c!="string"||!/^[A-Za-z][A-Za-z0-9_]{0,62}$/.test(c)||!a.has(c)||nt.has(c)||["createdBy","updatedBy","createdAt","updatedAt"].includes(c)||Object.values(e.taskPages||{}).some(f=>f.fields?.some(u=>u.code===c&&u.readonly!==!0))))&&n.push("WORKFLOW_CORRECTION_DERIVED_SUBJECT_FIELDS_INVALID")}if(!t)continue;let d=t.find(s=>s.code===r.operationCode);if(!d){n.push("WORKFLOW_BUSINESS_COMMAND_OPERATION_MISSING");continue}(d.method!=="POST"||d.browser?.exposure!=="authenticated"||d.browser.behavior!=="controlled"||d.browser.idempotency!=="required"||d.browser.fileIntent||d.browser.subject?.resourceCode!==e.subject?.resourceCode||d.browser.subject?.inputField!=="recordId"||!d.platformAccess?.workflow?.codes?.includes(e.code)||!d.platformAccess.workflow.businessCommands?.includes(i))&&n.push("WORKFLOW_BUSINESS_COMMAND_OPERATION_INVALID")}return["approve","reject","withdraw"].some(i=>Object.hasOwn(o,i))&&Object.values(e.nodes||{}).some(i=>i.kind==="approval"&&(i.emptyPolicy==="skip"||i.initiatorApprovalPolicy==="auto_approve"))&&n.push("WORKFLOW_BUSINESS_COMMAND_AUTOMATIC_DECISION_FORBIDDEN"),[...new Set(n)]}var $u={type:"object",additionalProperties:!1,required:["workflowCode","target","recordId","expectedRevision","commandToken","idempotencyKey","input"],properties:{workflowCode:{type:"string",pattern:"^[A-Za-z][A-Za-z0-9_-]{0,127}$"},target:{oneOf:[{type:"object",additionalProperties:!1,required:["kind","id","command"],properties:{kind:{const:"task"},id:{type:"string",format:"uuid"},command:{enum:["approve","reject","resubmit"]}}},{type:"object",additionalProperties:!1,required:["kind","id","command"],properties:{kind:{const:"instance"},id:{type:"string",format:"uuid"},command:{const:"withdraw"}}}]},recordId:{type:"string",format:"uuid"},expectedRevision:{type:"integer",minimum:1},commandToken:{type:"string",pattern:"^[A-Za-z0-9_-]{43}$"},idempotencyKey:{type:"string",minLength:1,maxLength:128},input:{type:"object",maxProperties:64}}};var Ja=["fixed_users","initiator","app_role","app_role_in_scope"],Ha=e=>!!e&&typeof e=="object"&&!Array.isArray(e);function Ro(e,t){let o=e?.launchPreflight;if(o===void 0)return[];if(!Ha(o)||Object.keys(o).join(",")!=="requiredApprovalNodes"||!Array.isArray(o.requiredApprovalNodes)||o.requiredApprovalNodes.length<1||o.requiredApprovalNodes.length>20||new Set(o.requiredApprovalNodes).size!==o.requiredApprovalNodes.length||o.requiredApprovalNodes.some(i=>typeof i!="string"||!/^[A-Za-z][A-Za-z0-9_-]{0,127}$/.test(i)))return["WORKFLOW_LAUNCH_PREFLIGHT_INVALID"];let n=[];for(let i of o.requiredApprovalNodes){let r=e.nodes?.[i];if(!r||r.kind!=="approval"){n.push(`WORKFLOW_LAUNCH_PREFLIGHT_NODE_INVALID:${i}`);continue}if(!t)continue;let d=t.bindings?.[r.binding||""];(!d||!Ja.includes(d.provider)||d.candidateField!==void 0)&&n.push(`WORKFLOW_LAUNCH_PREFLIGHT_PROVIDER_UNSUPPORTED:${i}`)}return n}var Co=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Ya=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,hr=/^[A-Za-z][A-Za-z0-9_-]{0,127}$/,Cr=/^membership:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Vu=500,Lu=262144;function wr(e){if(e?.approvedDelegation===void 0)return[];let t=e.approvedDelegation;if(!Co(t)||Object.keys(t).some(a=>!["confirmationNodeId","confirmer","requestsField","maxRequests"].includes(a))||!hr.test(t.confirmationNodeId||"")||!["initiator","delegate"].includes(t.confirmer)||!Ya.test(t.requestsField||"")||!Number.isSafeInteger(t.maxRequests)||t.maxRequests<1||t.maxRequests>500)return["WORKFLOW_APPROVED_DELEGATION_POLICY_INVALID"];let o=[],n=e.nodes?.[t.confirmationNodeId];(!n||n.kind!=="approval"||n.mode!=="single"||n.emptyPolicy==="skip"||n.initiatorApprovalPolicy==="auto_approve"||n.completionDeadline||n.administration?.assigneeProviders?.length||n.administration?.modes?.some(a=>a!=="single")||n.allowedOperations?.some(a=>["transfer","delegate","add_assignee","admin_override"].includes(a)))&&o.push("WORKFLOW_APPROVED_DELEGATION_CONFIRMATION_INVALID");let i=e.inputSchema?.properties?.[t.requestsField];(!i||i.type!=="array"||!Number.isSafeInteger(i.maxItems)||i.maxItems<1||i.maxItems>t.maxRequests||!i.items||i.items.type!=="object"||i.items.additionalProperties!==!1||!e.subject?.factProjection?.[t.requestsField])&&o.push("WORKFLOW_APPROVED_DELEGATION_REQUEST_SCHEMA_INVALID"),Object.values(e.nodes||{}).some(a=>a.kind==="end"&&a.outcome==="approved")||o.push("WORKFLOW_APPROVED_DELEGATION_APPROVED_END_REQUIRED");let d=[e.startAt],s=new Set;for(;d.length;){let a=d.pop();if(a===t.confirmationNodeId||s.has(a))continue;s.add(a);let c=e.nodes?.[a];c&&(c.kind==="end"&&c.outcome==="approved"&&o.push("WORKFLOW_APPROVED_DELEGATION_CONFIRMATION_BYPASS"),c.kind==="approval"&&d.push(c.onApprove,c.onReject),c.kind==="condition"&&d.push(c.otherwise,...(c.branches||[]).map(f=>f.target)),(c.kind==="cc"||c.kind==="action")&&d.push(c.next))}return[...new Set(o)]}function Fu(e,t){let o=t?.data?.[e.requestsField],n=()=>{throw new Error("WORKFLOW_APPROVED_DELEGATION_REQUEST_INVALID")};(!Array.isArray(o)||!o.length||o.length>e.maxRequests||o.length>500||new TextEncoder().encode(JSON.stringify(o)).byteLength>262144)&&n();let i=["key","delegatorRoleSubjectKey","delegatorRoleSubjectRevision","delegate","delegateRoleSubjectKey","expectedDelegateRevision","workflowCode","nodeId","validFrom","validTo","reason"],r=(a,c)=>typeof a=="string"&&a.trim().length>0&&a.length<=c,d=a=>{if(typeof a!="string")return!1;let c=/^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)(?:\.\d{1,3})?(?:Z|[+-](\d\d):(\d\d))$/.exec(a);if(!c)return!1;let[,f,u,p,_,E,A,O,b]=c,g=Number(f),I=Number(u),T=Number(p),y=[31,g%4===0&&(g%100!==0||g%400===0)?29:28,31,30,31,30,31,31,30,31,30,31];return I>=1&&I<=12&&T>=1&&T<=y[I-1]&&Number(_)<=23&&Number(E)<=59&&Number(A)<=59&&(O===void 0||Number(O)<=23&&Number(b)<=59)&&Number.isFinite(Date.parse(a))},s=o.map(a=>Co(a)?((Object.keys(a).some(c=>!i.includes(c))||!r(a.delegatorRoleSubjectKey,255)||!Cr.test(a.delegatorRoleSubjectKey)||!r(a.delegateRoleSubjectKey,255)||!Cr.test(a.delegateRoleSubjectKey)||!Number.isSafeInteger(a.delegatorRoleSubjectRevision)||a.delegatorRoleSubjectRevision<1||!Number.isSafeInteger(a.expectedDelegateRevision)||a.expectedDelegateRevision<1||!Co(a.delegate)||Object.keys(a.delegate).some(c=>!["value","label"].includes(c))||!r(a.delegate.value,255)||!r(a.delegate.label,200)||!(a.workflowCode===null||r(a.workflowCode,128)&&hr.test(a.workflowCode))||!(a.nodeId===null||r(a.nodeId,128)&&/^[A-Za-z0-9._:-]{1,128}$/.test(a.nodeId)&&a.workflowCode)||!d(a.validFrom)||!d(a.validTo)||Date.parse(a.validFrom)>=Date.parse(a.validTo)||!r(a.reason,4e3)||a.key!==void 0&&!r(a.key,128))&&n(),{...a,delegate:{value:a.delegate.value,label:a.delegate.label},validFrom:new Date(a.validFrom).toISOString(),validTo:new Date(a.validTo).toISOString()}):n());return e.confirmer==="delegate"&&new Set(s.map(a=>a.delegate.value)).size!==1&&n(),s}var Xa=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&[null,Object.prototype].includes(Object.getPrototypeOf(e));function Sr(e){let t=e?.nodes||{},o=Object.values(t).filter(s=>s?.kind==="correction");if(!o.length)return[];let n=[],i=s=>s?.kind==="approval"?[s.onApprove,s.onReject]:s?.kind==="condition"?[...(Array.isArray(s.branches)?s.branches:[]).map(a=>a.target),s.otherwise]:s?.kind==="action"||s?.kind==="cc"?[s.next]:[],r=new Set,d=[e.startAt];for(;d.length;){let s=d.pop();r.has(s)||(r.add(s),d.push(...i(t[s])))}for(let s of o){(!Xa(s)||Object.keys(s).some(c=>!["id","kind","title","taskPageCode","next"].includes(c))||typeof s.id!="string"||!/^[A-Za-z][A-Za-z0-9_-]{0,127}$/.test(s.id)||["__proto__","prototype","constructor"].includes(s.id)||t[s.id]!==s||typeof s.title!="string"||!s.title.trim()||s.title.length>255||typeof s.taskPageCode!="string"||!/^[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(s.taskPageCode))&&n.push("WORKFLOW_CORRECTION_NODE_INVALID"),(s.next!==e.startAt||t[s.next]?.kind==="correction")&&n.push("WORKFLOW_CORRECTION_REPLAY_TARGET_INVALID"),(r.has(s.id)||Object.values(t).some(c=>i(c).includes(s.id)))&&n.push("WORKFLOW_CORRECTION_FORWARD_ENTRY_FORBIDDEN"),Object.values(t).some(c=>c?.kind==="approval"&&r.has(c.id)&&Array.isArray(c.returnTargets)&&c.returnTargets.includes(s.id))||n.push("WORKFLOW_CORRECTION_RETURN_SOURCE_REQUIRED");let a=e.taskPages?.[s.taskPageCode];!a||!Array.isArray(a.fields)?n.push("WORKFLOW_CORRECTION_PAGE_REQUIRED"):a.fields.some(c=>c?.subtable&&Object.values(e.subject?.factProjection||{}).some(f=>f===c.code||f.startsWith(`${c.code}.`)))&&n.push("WORKFLOW_CORRECTION_OWNED_FACTS_UNSUPPORTED")}return[...new Set(n)]}var cn=class extends Error{constructor(o){super(o);this.code=o}code},Wu=["projection","triggerCode","resourceCode","recordId","recordRevision","field","dueAt"];function Dr(e,t,o){let n=r=>{throw new cn(r)};t.length>100&&n("DATE_TRIGGER_PROJECTION_LIMIT");let i=new Set;for(let r of t){let d=r.filter?.resourceCodes||[];if(Array.isArray(d)||n("DATE_TRIGGER_PROJECTION_INVALID"),d.length&&!d.includes(e))continue;let s=r.payload?.fields||[];(!Array.isArray(s)||s.length>32)&&n("DATE_TRIGGER_PROJECTION_LIMIT");for(let a of s)(typeof a!="string"||!/^[A-Za-z_][A-Za-z0-9_]{0,62}$/.test(a)||["__proto__","constructor","prototype"].includes(a))&&n("DATE_TRIGGER_PROJECTION_FIELD_INVALID"),i.add(a)}if(i.size>64&&n("DATE_TRIGGER_PROJECTION_LIMIT"),o!==void 0){let r=o?.schema?.fields??o?.fields;Array.isArray(r)||n("DATE_TRIGGER_PROJECTION_RESOURCE_INVALID");let d=new Map(r.map(s=>[s.code,s]));for(let s of i){let a=d.get(s);a||n("DATE_TRIGGER_PROJECTION_FIELD_UNKNOWN"),a.type==="subtable"&&n("DATE_TRIGGER_PROJECTION_SUBTABLE_FORBIDDEN"),o.fieldPolicies?.[s]?.mask==="omit"&&n("DATE_TRIGGER_PROJECTION_FIELD_SENSITIVE")}}return[...i].sort()}function Uu(e,t){if(!t.length)return e;let o=e?.properties?.projection;if(o?.type!=="object"||!o.properties||typeof o.properties!="object"||Array.isArray(o.properties)||o.additionalProperties!==!1||o.required!==void 0&&!Array.isArray(o.required)||t.some(n=>!Object.hasOwn(o.properties,n))||(o.required||[]).some(n=>!t.includes(n)))throw new cn("DATE_TRIGGER_PROJECTION_SCHEMA_INVALID");return{...e,properties:{...e.properties,projection:{}}}}var Za=200,wo=1024*1024,Qa=65536,Pr=Be,kr=tt,Je=new Set(["__proto__","prototype","constructor"]),vr=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,Dt=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,$r=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,de=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&[null,Object.prototype].includes(Object.getPrototypeOf(e)),ke=(e,t)=>de(e)&&Object.keys(e).every(o=>t.includes(o)&&!Je.has(o)),ln=e=>{try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return 1/0}},Vr=e=>e==null||typeof e=="string"&&!e.trim()||Array.isArray(e)&&e.length===0;function xe(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((n,i)=>xe(n,t[i]));if(!de(e)||!de(t))return!1;let o=Object.keys(e);return o.length===Object.keys(t).length&&o.every(n=>Object.hasOwn(t,n)&&xe(e[n],t[n]))}function ho(e,t){let o=t.split(".");if(!(o.some(n=>!vr.test(n)||Je.has(n))||o.length>12))return o.reduce((n,i)=>de(n)&&Object.hasOwn(n,i)?n[i]:void 0,e)}function Fe(e,t){switch(e.op){case"literal":return e.value;case"path":return ho({values:t},e.path);case"and":return e.values.every(o=>!!Fe(o,t));case"or":return e.values.some(o=>!!Fe(o,t));case"not":return!Fe(e.value,t);case"exists":return!Vr(Fe(e.value,t));default:{let o=Fe(e.left,t),n=Fe(e.right,t);return e.op==="eq"?xe(o,n):e.op==="neq"?!xe(o,n):e.op==="in"?Array.isArray(n)&&n.some(i=>xe(i,o)):e.op==="contains"?Array.isArray(o)?o.some(i=>xe(i,n)):typeof o=="string"&&typeof n=="string"&&o.includes(n):typeof o!="number"||typeof n!="number"||!Number.isFinite(o)||!Number.isFinite(n)?!1:e.op==="gt"?o>n:e.op==="gte"?o>=n:e.op==="lt"?o<n:o<=n}}}function St(e,t,o=0,n={nodes:0}){if(o>8||++n.nodes>64||!de(e))return!1;if(e.op==="literal")return ke(e,["op","value"])&&Object.hasOwn(e,"value")&&ln(e.value)<=4096&&kt(e.value);if(e.op==="path"){if(!ke(e,["op","path"])||typeof e.path!="string")return!1;let i=e.path.split(".");return i[0]==="values"&&i.length>=2&&i.length<=8&&t.has(i[1])&&i.every(r=>Dt.test(r)&&!Je.has(r))}return["not","exists"].includes(e.op)?ke(e,["op","value"])&&St(e.value,t,o+1,n):["and","or"].includes(e.op)?ke(e,["op","values"])&&Array.isArray(e.values)&&e.values.length>0&&e.values.length<=16&&e.values.every(i=>St(i,t,o+1,n)):["eq","neq","gt","gte","lt","lte","in","contains"].includes(e.op)&&ke(e,["op","left","right"])&&St(e.left,t,o+1,n)&&St(e.right,t,o+1,n)}function un(e,t,o,n=kr){let i=[],r=e.taskPages;if(r!==void 0&&(!de(r)||Object.keys(r).length===0||Object.keys(r).length>16||ln(r)>Qa))return["WORKFLOW_TASK_PAGES_INVALID"];for(let[d,s]of Object.entries(r||{})){let a=`taskPages.${d}`;if(!vr.test(d)||Je.has(d)||!ke(s,["title","fields"])||typeof s.title!="string"||!s.title.trim()||s.title.length>160||!Array.isArray(s.fields)||!s.fields.length||s.fields.length>Za){i.push(`WORKFLOW_TASK_PAGE_INVALID:${a}`);continue}let c=new Set(s.fields.map(p=>p?.code));c.size!==s.fields.length&&i.push(`WORKFLOW_TASK_PAGE_DUPLICATE_FIELD:${a}`);let f=0,u=new Set;for(let p of s.fields){if(!ke(p,["code","readonly","required","visibleWhen","requiredWhen","subtable"])||!Dt.test(p.code)||Je.has(p.code)||["readonly","required"].some(_=>p[_]!==void 0&&typeof p[_]!="boolean")||p.readonly&&(p.required||p.requiredWhen)){i.push(`WORKFLOW_TASK_PAGE_FIELD_INVALID:${a}`);continue}for(let _ of["visibleWhen","requiredWhen"])p[_]!==void 0&&!St(p[_],c)&&i.push(`WORKFLOW_TASK_PAGE_EXPRESSION_INVALID:${a}.${p.code}.${_}`);if(t){let _=t.get(p.code);if((!_||_.system||_.hidden||_.type==="serial-number"||!p.readonly&&_.widget==="readonly"||!p.readonly&&_.type==="subtable"&&!p.subtable||p.subtable&&_.type!=="subtable")&&i.push(`WORKFLOW_TASK_PAGE_RESOURCE_FIELD_INVALID:${a}.${p.code}`),p.subtable&&_?.subtable){let E=_.subtable;f+=E.maxRows??20,(u.has(E.resourceCode)||!Number.isSafeInteger(E.maxRows??20)||(E.maxRows??20)<1||(E.maxRows??20)>Pr||!Dt.test(E.foreignKey)||!Dt.test(E.orderField)||E.foreignKey===E.orderField)&&i.push(`WORKFLOW_TASK_SUBTABLE_RELATION_INVALID:${a}.${p.code}`),u.add(E.resourceCode);let A=o?.get(E.resourceCode);o&&(!A||!["uuid","resource-ref.single"].includes(A.get(E.foreignKey)?.type||"")||A.get(E.orderField)?.type!=="number.integer")&&i.push(`WORKFLOW_TASK_SUBTABLE_RELATION_INVALID:${a}.${p.code}`);for(let O of Array.isArray(p.subtable.fields)?p.subtable.fields:[]){if(!O||typeof O.code!="string")continue;let b=A?.get(O.code);(O.code===E.foreignKey||O.code===E.orderField||A&&(!b||b.system||b.hidden||b.type==="subtable"||!O.readonly&&(b.widget==="readonly"||b.type==="serial-number")))&&i.push(`WORKFLOW_TASK_SUBTABLE_FIELD_UNSUPPORTED:${a}.${p.code}.${O.code}`)}}else p.subtable&&t&&i.push(`WORKFLOW_TASK_SUBTABLE_RELATION_INVALID:${a}.${p.code}`)}p.subtable&&(p.readonly||!ke(p.subtable,["fields","create","delete","reorder"])||["create","delete","reorder"].some(_=>p.subtable?.[_]!==void 0&&typeof p.subtable[_]!="boolean")||!Array.isArray(p.subtable.fields)||p.subtable.fields.some(_=>_?.subtable)?i.push(`WORKFLOW_TASK_SUBTABLE_PAGE_INVALID:${a}.${p.code}`):i.push(...un({taskPages:{child:{title:"\u5B50\u884C",fields:p.subtable.fields}}},o?.get(t?.get(p.code)?.subtable?.resourceCode||"")).map(_=>`${_}:${a}.${p.code}`)))}(f>Math.min(n,kr)||f<0||!Number.isSafeInteger(f)||!Number.isSafeInteger(n)||n<1)&&i.push(`WORKFLOW_TASK_SUBTABLE_BUDGET_EXCEEDED:${a}`)}for(let[d,s]of Object.entries(e.nodes||{}))de(s)&&s.taskPageCode!==void 0&&(!["approval","correction"].includes(s.kind)||typeof s.taskPageCode!="string"||!de(r)||!Object.hasOwn(r,s.taskPageCode)?i.push(`WORKFLOW_TASK_PAGE_NOT_FOUND:${d}`):Array.isArray(r[s.taskPageCode]?.fields)&&r[s.taskPageCode].fields.some(a=>a&&(s.fieldPolicy?.fields?.[a.code]||s.fieldPolicy?.default)==="hidden")&&i.push(`WORKFLOW_TASK_PAGE_FIELD_HIDDEN:${d}`));return i}function Lr(e,t){return e.fields.map(o=>({code:o.code,visible:o.visibleWhen===void 0||!!Fe(o.visibleWhen,t),readonly:o.readonly===!0,required:o.required===!0||o.requiredWhen!==void 0&&!!Fe(o.requiredWhen,t)}))}var we=class extends Error{constructor(o,n){super(o);this.code=o;this.field=n}code;field;rowIndex;childField};function Ku(e,t){return t.map(o=>({key:String(o.id),id:String(o.id),revision:Number(o.revision),state:"persisted",values:Object.fromEntries(Lr({title:"\u5B50\u884C",fields:e.fields},o).filter(n=>n.visible&&!n.readonly).map(n=>[n.code,o[n.code]??null]))}))}function Gu(e,t,o,n,i,r=!0,d=0){let s=e.subtable,a=_=>{throw new we(_,e.code)};if(!s||!Number.isSafeInteger(t)||t<1||t>Pr||!Number.isSafeInteger(d)||d<0||d>t||!Array.isArray(n)||n.length>2*t||ln(n)>wo||!kt(n))return a("WORKFLOW_TASK_SUBTABLE_VALUES_INVALID");let c=new Map(o.map(_=>[String(_.id),_])),f=new Set,u=new Set,p=[];for(let _ of n){if(!ke(_,["key","state","id","revision","values"])||typeof _.key!="string"||!$r.test(_.key)||f.has(_.key)||!["created","persisted","deleted"].includes(_.state)||!de(_.values))return a("WORKFLOW_TASK_SUBTABLE_ROW_INVALID");if(f.add(_.key),_.state==="created"){if(!s.create||_.id!==void 0||_.revision!==void 0||c.has(_.key))return a("WORKFLOW_TASK_SUBTABLE_CREATE_FORBIDDEN")}else{if(typeof _.id!="string"||_.id!==_.key||!$r.test(_.id)||u.has(_.id)||!Number.isSafeInteger(_.revision)||_.revision<1||!c.has(_.id))return a("WORKFLOW_TASK_SUBTABLE_SCOPE_CONFLICT");if(u.add(_.id),r&&Number(c.get(_.id).revision)!==_.revision)return a("WORKFLOW_TASK_SUBTABLE_REVISION_CONFLICT")}if(_.state==="deleted"){if(!s.delete||Object.keys(_.values).length)return a("WORKFLOW_TASK_SUBTABLE_DELETE_FORBIDDEN");continue}try{ed({title:e.code,fields:s.fields},_.id?c.get(_.id):{},_.values,i)}catch(E){if(!(E instanceof we))throw E;let A=new we(E.code,e.code);throw A.rowIndex=p.length,E.field!==void 0&&(A.childField=E.field),A}p.push(_)}if(u.size!==c.size)return a("WORKFLOW_TASK_SUBTABLE_SCOPE_CONFLICT");if(p.length>t)return a("WORKFLOW_TASK_SUBTABLE_MAX_ROWS_EXCEEDED");if(i&&p.length<d)return a("WORKFLOW_TASK_SUBTABLE_MIN_ROWS_NOT_MET");if(!s.reorder){let _=o.filter(A=>p.some(O=>O.id===String(A.id))).map(A=>String(A.id)),E=p.filter(A=>A.state==="persisted").map(A=>A.id);if(!xe(_,E)||p.some((A,O)=>A.state==="created"&&p.slice(O+1).some(b=>b.state==="persisted")))return a("WORKFLOW_TASK_SUBTABLE_REORDER_FORBIDDEN")}return n}function kt(e,t={members:0},o=0){return++t.members>5e4||o>12?!1:e===null||typeof e=="boolean"?!0:typeof e=="string"?e.length<=wo:typeof e=="number"?Number.isFinite(e):Array.isArray(e)?e.length<=1e3&&e.every(n=>kt(n,t,o+1)):de(e)&&Object.entries(e).every(([n,i])=>!Je.has(n)&&kt(i,t,o+1))}function ed(e,t,o,n){if(!de(o)||ln(o)>wo||!kt(o))throw new we("WORKFLOW_TASK_FORM_VALUES_INVALID");let i={...t,...o},r=new Map(Lr(e,i).map(d=>[d.code,d]));for(let d of Object.keys(o)){let s=r.get(d);if(!s||s.readonly||!s.visible)throw new we("WORKFLOW_TASK_FORM_FIELD_NOT_EDITABLE",d)}if(n)for(let d of r.values()){let s=i[d.code],a=e.fields.find(c=>c.code===d.code)?.subtable&&Array.isArray(s)?s.every(c=>de(c)&&c.state==="deleted"):Vr(s);if(d.visible&&!d.readonly&&d.required&&a)throw new we("WORKFLOW_TASK_FORM_REQUIRED",d.code)}return i}function qu(e,t,o){let n=JSON.parse(JSON.stringify(t));for(let[d,s]of Object.entries(e.subject?.factProjection||{})){let a=d.split(".");if(!a.length||a.length>12||d.length>128||a[0]==="steps"||a.some(f=>!Dt.test(f)||Je.has(f)))throw new we("WORKFLOW_TASK_FORM_FACT_PROJECTION_INVALID");if(!Object.hasOwn(o,s))throw new we("WORKFLOW_TASK_FORM_FACT_FIELD_MISSING",s);let c=n;for(let f of a.slice(0,-1))c=c[f]=de(c[f])?c[f]:{};c[a.at(-1)]=o[s]===void 0?void 0:JSON.parse(JSON.stringify(o[s]))}let i=new Set,r=Object.values(e.nodes||{}).filter(d=>d.kind==="action");for(let d=0;d<=r.length;d++){let s=!1;for(let a of r)de(n.steps)&&Object.hasOwn(n.steps,a.id)&&Object.values(a.inputs||{}).some(c=>c.source==="fact"&&!xe(ho(t,c.path),ho(n,c.path)))&&(delete n.steps[a.id],i.add(a.id),s=!0);if(!s)break}return{facts:n,invalidatedNodeIds:[...i].sort()}}function zu(e,t,o){let n=e.nodes||{};for(let i of o){let r=new Set,d=new Map,s=a=>{if(a===i)return!0;if(d.has(a))return d.get(a);if(r.has(a)||r.size>200)return!1;let c=n[a];if(!de(c)||c.kind==="end")return!1;r.add(a);let f=c.kind==="approval"?[c.onApprove]:c.kind==="condition"?[...(c.branches||[]).map(p=>p.target),c.otherwise]:[c.next],u=f.length>0&&f.every(p=>typeof p=="string"&&s(p));return r.delete(a),d.set(a,u),u};if(!s(t))return!1}return!0}var Hu=256,Yu=64,Xu=262144,td=/^[a-z][a-z0-9_-]{0,127}$/,nd=/^[A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z][A-Za-z0-9_]*)*$/,xr=new Set(["__proto__","prototype","constructor"]),Se=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Pt=(e,t)=>Object.keys(e).every(o=>t.includes(o)),He=(e,t)=>typeof e=="string"&&e.trim().length>0&&e.length<=t&&!/[\u0000-\u001f\u007f]/.test(e),$e=e=>typeof e=="string"&&td.test(e)&&!xr.has(e),jr=e=>typeof e=="string"&&e.length<=255&&nd.test(e)&&!e.split(".").some(t=>xr.has(t)),od=e=>Se(e)&&Pt(e,["dimension","valueFrom","value"])&&$e(e.dimension)&&(He(e.value,255)&&e.valueFrom===void 0||jr(e.valueFrom)&&e.value===void 0),Fr=e=>typeof e=="string"&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?(?:Z|[+-]\d{2}:\d{2})$/.test(e)&&Number.isFinite(Date.parse(e)),$t={type:"string",pattern:"^[a-z][a-z0-9_-]{0,127}$"},So={type:"string",minLength:1,maxLength:128},Zu={type:"object",additionalProperties:!1,required:["policyCode","title","strategy","dimensions","sources"],properties:{policyCode:$t,title:So,strategy:{enum:["replace_then_append","replace_only"]},dimensions:{type:"object",maxProperties:8,propertyNames:$t,additionalProperties:{type:"object",additionalProperties:!1,required:["title","valueFrom"],properties:{title:So,valueFrom:{type:"string",minLength:1,maxLength:255}}}},sources:{type:"object",minProperties:1,maxProperties:16,propertyNames:$t,additionalProperties:{type:"object",additionalProperties:!1,required:["title","provider","roleCode"],properties:{title:So,provider:{enum:["app_role","app_role_in_scope"]},roleCode:$t,scope:{type:"object",additionalProperties:!1,required:["dimension"],properties:{dimension:$t,value:{type:"string",minLength:1,maxLength:255},valueFrom:{type:"string",minLength:1,maxLength:255}}}}}}}};function fn(e){if(!Se(e)||!Pt(e,["policyCode","title","strategy","dimensions","sources"])||!$e(e.policyCode)||!He(e.title,128)||!["replace_then_append","replace_only"].includes(e.strategy))return["WORKFLOW_V2_ROUTING_POLICY_INVALID"];let t=[];return(!Se(e.dimensions)||Object.keys(e.dimensions).length>8||Object.entries(e.dimensions).some(([o,n])=>!$e(o)||!Se(n)||!Pt(n,["title","valueFrom"])||!He(n.title,128)||!jr(n.valueFrom)))&&t.push("WORKFLOW_V2_ROUTING_DIMENSIONS_INVALID"),(!Se(e.sources)||Object.keys(e.sources).length<1||Object.keys(e.sources).length>16||Object.entries(e.sources).some(([o,n])=>!$e(o)||!Se(n)||!Pt(n,["title","provider","roleCode","scope"])||!He(n.title,128)||!$e(n.roleCode)||!["app_role","app_role_in_scope"].includes(n.provider)||(n.provider==="app_role_in_scope"?!od(n.scope):n.scope!==void 0)))&&t.push("WORKFLOW_V2_ROUTING_SOURCES_INVALID"),t}function Qu(e,t){if(fn(e).length)return["WORKFLOW_V2_ROUTING_POLICY_INVALID"];if(!Array.isArray(t)||t.length>256||new TextEncoder().encode(JSON.stringify(t)).length>262144)return["WORKFLOW_V2_ROUTING_RULE_LIMIT_EXCEEDED"];let o=[],n=new Set;for(let i of t){if(!Se(i)||!Pt(i,["ruleCode","title","enabled","workflowCode","nodeId","matches","sourceCode","effect","priority","validFrom","validTo"])||!$e(i.ruleCode)||!He(i.title,128)||typeof i.enabled!="boolean"||!$e(i.sourceCode)||!Object.hasOwn(e.sources,i.sourceCode)||!["append","replace"].includes(i.effect)||!Number.isSafeInteger(i.priority)||i.priority<-1e3||i.priority>1e3||i.workflowCode!==void 0&&!$e(i.workflowCode)||i.nodeId!==void 0&&(!$e(i.nodeId)||i.workflowCode===void 0)||i.validFrom!==void 0&&!Fr(i.validFrom)||i.validTo!==void 0&&!Fr(i.validTo)||i.validFrom&&i.validTo&&Date.parse(i.validFrom)>=Date.parse(i.validTo)){o.push("WORKFLOW_V2_ROUTING_RULE_INVALID");continue}n.has(i.ruleCode)&&o.push(`WORKFLOW_V2_ROUTING_RULE_DUPLICATE:${i.ruleCode}`),n.add(i.ruleCode),(!Se(i.matches)||Object.entries(i.matches).some(([r,d])=>!Object.hasOwn(e.dimensions,r)||!Array.isArray(d)||d.length<1||d.length>64||new Set(d).size!==d.length||d.some(s=>!He(s,255))))&&o.push(`WORKFLOW_V2_ROUTING_MATCH_INVALID:${i.ruleCode}`)}return[...new Set(o)]}function id(e){return JSON.stringify({policyCode:e.policyCode,strategy:e.strategy,dimensions:Object.entries(e.dimensions).sort(([t],[o])=>t<o?-1:t>o?1:0).map(([t,o])=>[t,o.valueFrom]),sources:Object.entries(e.sources).sort(([t],[o])=>t<o?-1:t>o?1:0).map(([t,o])=>[t,o.provider,o.roleCode,o.scope?.dimension??null,o.scope?.valueFrom??null,o.scope?.value??null])})}function Wr(e){let t=[],o=new Map;for(let n of e)for(let[i,r]of Object.entries(n.bindings||{})){if(!Se(r)||r.routing===void 0)continue;let d=fn(r.routing);if(d.length){t.push(...d.map(c=>`${c}:${i}`));continue}let s=id(r.routing),a=o.get(r.routing.policyCode);a&&a!==s&&t.push(`WORKFLOW_V2_ROUTING_POLICY_CONFLICT:${r.routing.policyCode}`),o.set(r.routing.policyCode,s)}return[...new Set(t)]}function ef(e,t){let o={};for(let[n,i]of Object.entries(e.dimensions)){let r=t;for(let d of i.valueFrom.split("."))r=Se(r)&&Object.hasOwn(r,d)?r[d]:void 0;if(!(typeof r=="string"&&He(r,255)||typeof r=="number"&&Number.isFinite(r)||typeof r=="boolean"))throw new Error(`WORKFLOW_V2_ROUTING_FACT_REQUIRED:${n}`);o[n]=String(r)}return o}function tf(e,t,o){let n=t.filter(c=>c.enabled&&(!c.validFrom||Date.parse(c.validFrom)<=o.at)&&(!c.validTo||Date.parse(c.validTo)>o.at)&&(!c.workflowCode||c.workflowCode===o.workflowCode)&&(!c.nodeId||c.nodeId===o.nodeId)&&Object.entries(c.matches).every(([f,u])=>u.includes(o.facts[f])));if(n.length>64)throw new Error("WORKFLOW_V2_ROUTING_MATCH_LIMIT_EXCEEDED");let i=(c,f)=>f.priority-c.priority||+!!c.workflowCode-+!!f.workflowCode||+!!c.nodeId-+!!f.nodeId||(c.ruleCode<f.ruleCode?-1:c.ruleCode>f.ruleCode?1:0),r=n.filter(c=>c.effect==="replace").sort(i);if(r.length>1&&r[0].priority===r[1].priority)throw new Error("WORKFLOW_V2_ROUTING_REPLACE_CONFLICT");let d=r[0],s=d&&e.strategy==="replace_only"?[]:n.filter(c=>c.effect==="append").sort(i),a=[...d?[d]:[],...s];return{matched:n.sort(i),replacement:d,applied:a,ignored:n.filter(c=>!a.includes(c))}}var Do="^[A-Za-z][A-Za-z0-9_]{0,62}$",Ur="^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$",rf={type:"object",additionalProperties:!1,required:["mode","resourceCode","subtables"],properties:{mode:{const:"create"},resourceCode:{type:"string",maxLength:64,pattern:Ur},subtables:{type:"array",minItems:1,maxItems:16,items:{type:"object",additionalProperties:!1,required:["fieldCode","fieldCodes"],properties:{fieldCode:{type:"string",pattern:Do},fieldCodes:{type:"array",minItems:1,maxItems:200,uniqueItems:!0,items:{type:"string",pattern:Do}}}}}}};function pn(e){let t=n=>!!(n&&typeof n=="object"&&!Array.isArray(n)),o=n=>typeof n=="string"&&new RegExp(Do).test(n)&&!["__proto__","prototype","constructor"].includes(n);if(!t(e)||Object.keys(e).some(n=>!["mode","resourceCode","subtables"].includes(n))||e.mode!=="create"||typeof e.resourceCode!="string"||e.resourceCode.length>64||!new RegExp(Ur).test(e.resourceCode)||!Array.isArray(e.subtables)||e.subtables.length<1||e.subtables.length>16||e.subtables.some(n=>!t(n)||Object.keys(n).some(i=>!["fieldCode","fieldCodes"].includes(i))||!o(n.fieldCode)||!Array.isArray(n.fieldCodes)||n.fieldCodes.length<1||n.fieldCodes.length>200||new Set(n.fieldCodes).size!==n.fieldCodes.length||n.fieldCodes.some(i=>!o(i)))||new Set(e.subtables.map(n=>n.fieldCode)).size!==e.subtables.length)throw new Error("WORKFLOW_OWNED_SUBJECT_CREATE_INVALID")}function sf(e){return pn(e),{mode:"create",resourceCode:e.resourceCode,subtables:e.subtables.map(t=>({fieldCode:t.fieldCode,fieldCodes:[...t.fieldCodes].sort()})).sort((t,o)=>t.fieldCode.localeCompare(o.fieldCode))}}function Mr(e,t,o){pn(e);let n=s=>{throw new Error(`WORKFLOW_OWNED_SUBJECT_${s}`)},i=t.get(e.resourceCode);i||n("RESOURCE_MISSING");let r=new Set,d=0;for(let s of e.subtables){let a=i.get(s.fieldCode),c=a?.subtable,f=t.get(c?.resourceCode);(a?.type!=="subtable"||!f||c.resourceCode===e.resourceCode||r.has(c.resourceCode))&&n("RELATION_INVALID"),r.add(c.resourceCode);let u=c.maxRows??20;(!Number.isSafeInteger(u)||u<1||u>Be)&&n("BUDGET_EXCEEDED"),d+=u;for(let p of s.fieldCodes){let _=f.get(p);(!_||["serial-number","subtable"].includes(_.type)||[c.foreignKey,c.orderField].includes(p))&&n("FIELD_INVALID"),["file","image","signature","text.rich"].includes(_.type)&&!o.some(E=>E.resourceCode===c.resourceCode&&E.fieldCodes.includes(p)&&E.intents.includes("create"))&&n("FILE_ACCESS_REQUIRED")}}d>tt&&n("BUDGET_EXCEEDED")}import*as yn from"crypto";var Br="native-4",ko="2.0.0-alpha.5",Kr={"application-native-2":"1.0.0","application.extended-declaration-capacity":"1.0.0","application.extended-role-capacity":"1.0.0","application.extended-artifact-capacity":"1.0.0","application.high-density-artifact-capacity":"1.0.0","application.extended-configuration-bytes":"1.0.0","application.development-configuration":"2.0.0","authz.native-batch-explain":"1.0.0","authz.native-management":"1.0.0","authz.native-membership-batch":"1.0.0","deployment.durable-runs":"1.0.0","deployment.platform-executor":"1.0.0","environment.on-demand-production":"1.0.0","environment.runtime-lifecycle":"1.0.0","data.rich-text":"1.0.0","data-api-v2":"1.1.0","data.extended-owned-subtable-capacity":"1.0.0","data.aggregate-owned-subtable-capacity":"1.0.0","data.extended-field-capacity":"1.0.0","data.business-commands":"1.0.0","data.record-edit":"1.0.0","data.native-golden-crud":"1.0.0","data.audit-read-access":"1.0.0","data.managed-files":"1.1.0","data.decimal-reservations":"1.1.0","data.decimal-reservation-lifecycle":"1.0.0","data.unique-keys":"1.1.0","data.user-candidates":"1.0.0","data.user-candidate-launch-scope":"1.0.0","data.datetime-minute-precision":"1.0.0","data.subtable-minimum-rows":"1.0.0","data.managed-concurrency":"1.0.0","data.managed-concurrency.durable":"1.0.0","workflow.named-input-sources":"1.0.0","workflow.approved-delegation":"1.0.0","directory-v2":"1.0.0","directory.selected-user":"1.0.0","directory.selected-departments":"1.0.0","directory.current-initiator-phone":"1.0.0","events-v2":"1.0.0","events.durable-receipts":"1.0.0","events.capture-policy":"1.0.0","events.date-source-projection":"1.0.0","events.native-data-actions":"1.0.0","workflow-kernel-v2":"1.0.0","workflow.business-data-command":"1.0.0","workflow.approval-business-command":"1.0.0","workflow.native-stage-guard":"1.0.0","workflow.launch-preflight":"1.0.0","workflow.optional-rejection-comment":"1.0.0","workflow.optional-operation-reason":"1.0.0","workflow.optional-withdrawal-reason":"1.0.0","data.transaction-actor-authority":"1.0.0","data.authenticated-public-projection":"1.0.0","data.parent-read-policy":"1.0.0","data.record-print":"1.0.0","data.workflow-record-deletion":"1.0.0","data.record-comments":"1.0.0","workflow.record-history-read":"1.0.0","workflow.rejection-notification":"1.0.0","workflow.instance-cancellation-policy":"1.0.0","workflow.node-administration":"1.0.0","workflow.assignment-routing":"1.0.0","workflow.role-union":"1.0.0","workflow.role-input-selection":"1.0.0","workflow.named-owned-create":"1.0.0","workflow.owned-initial-facts":"1.0.0","workflow.initiator-correction":"1.0.0","workflow.correction-business-command":"1.0.0","workflow.correction-derived-subject-facts":"1.0.0","workflow.role-references":"1.0.0","workflow.delegation-management":"1.0.0","workflow.automatic-cc":"1.0.0","workflow.approval-empty-policy":"1.0.0","workflow.initiator-approval-policy":"1.0.0","workflow.completion-deadline":"1.0.0","workflow.task-page-submit":"1.0.0","workflow.task-private-drafts":"1.0.0","workflow.task-managed-files":"1.0.0","workflow.task-rich-fields":"1.0.0","workflow.task-owned-subtables":"1.0.0","workflow.task-owned-files":"1.0.0","workflow.durable-business-step":"1.0.0","workflow.step-data-transaction":"1.0.0","business-process.durable-command":"1.1.0","workflow.fresh-command-token":"1.0.0","notification-hub-v2":"1.0.0","authentication.application-login-surface":"1.0.0","public-access.anonymous-owner-records":"1.0.0"};var B=Object.freeze({perspectives:100,resources:512,dataPolicies:512,roles:512,subjectReadSurfaces:50,capabilities:4096,operations:500,eventConsumers:100,eventProducers:1e3,eventSchemas:100,eventTypes:500,workflows:512,routes:2048,adminPages:2048,adminNavigationGroups:100,adminNavigationItems:1024});function Gr(e){let t=(e.surface?.mutationOwner||"native")==="native";return["query","get","create","update","delete"].filter(o=>{let n=e.surface?.generated;return o==="query"?n?.list??!0:o==="get"?n?.detail??!0:n?.[o]??t})}function $o(e){return(e.authz?.roles?.length||0)>256}function Po(e){let t=(e.data?.resources||[]).filter(o=>o.status!=="retired").reduce((o,n)=>o+Gr(n).length,0)+(e.backend?.operations||[]).filter(o=>o.ai).length;return(e.data?.resources?.length||0)>100||(e.authz?.dataPolicies?.length||0)>100||(e.authz?.roles?.length||0)>100||(e.authz?.capabilities?.length||0)>2e3||[e.workflows?.definitions,e.workflows?.bindings,e.workflows?.activations].some(o=>(o?.length||0)>100)||(e.frontend?.routes?.length||0)>500||t>500||(e.frontend?.admin?.navigation||[]).reduce((o,n)=>o+n.items.length,0)>500}var re=Object.freeze({legacyConfigBytes:4194304,configBytes:8388608,contractBytes:8388608,depth:40,stringBytes:1048576,legacyNodes:1e5,extendedNodes:25e4}),ct=Object.freeze({nodes:5e5});function vo(e){return Buffer.byteLength(X(e),"utf8")>re.legacyConfigBytes}function qr(e,t){let o=0,n=[[e][Symbol.iterator]()];for(;n.length;){let i=n[n.length-1].next();if(i.done){n.pop();continue}if(++o>t)return!0;if(Array.isArray(i.value))n.push(i.value.values());else if(i.value&&typeof i.value=="object"){let r=i.value;n.push((function*(){for(let d of Object.keys(r))r[d]!==void 0&&(yield r[d])})())}}return!1}function mn(e){return qr(e,re.legacyNodes)}function _n(e){return qr(e,re.extendedNodes)}var rd="openxiangda.config-bundle/v3",ls="openxiangda.contract-bundle/v3",zr="openxiangda.native-configuration-projection/v1",Vt=Br,sd=/^[a-f0-9]{64}$/,ad=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,dd=/^app:[a-z][a-z0-9]*(?:-[a-z0-9]+)*:[A-Za-z0-9:._*-]+$/,cd=/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/,ld=/^[a-z][a-z0-9]*(?:[-.][a-z0-9]+)*$/,ud=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,fd=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,Jr=/^[A-Za-z][A-Za-z0-9_]{0,127}$/,pd=/^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*$/,md=/^[A-Z][A-Z0-9_]*$/,_d=/^[a-z][a-z0-9-]{2,63}$/,gd=/^[A-Za-z][A-Za-z0-9_-]{0,127}$/,Ad=/^[A-Za-z][A-Za-z0-9_.]{0,127}$/,Ed=16,Id=2*1024,yd=new Set(["text.short","text.long","number.integer","number.decimal","boolean","date","time","datetime","option.single","option.multiple","cascade.single","cascade.multiple","user.single","user.multiple","department.single","department.multiple","resource-ref.single","resource-ref.multiple","uuid","serial-number"]),bd=new Set(["overview","database","operations","workflow","members","calendar","document","folder","settings"]),Od=new Set(["approve","reject","return","transfer","delegate","add_assignee","resubmit","withdraw","terminate","admin_reassign","admin_override","retry_resolution"]),Nd=re.configBytes,Td=re.contractBytes,Rd=re.depth,Lo=re.stringBytes,Cd="openxiangda.event-handler-manifest/v2",us="openxiangda.application-route-manifest/v3",Hr=64,fs=new Set(["id","revision","created_by","updated_by","created_at","updated_at"]),Fo=["openxiangda.data.record.created.v2","openxiangda.data.record.updated.v2","openxiangda.data.record.deleted.v2"],xo=["openxiangda.workflow.node.skipped.v2",Ct,"openxiangda.workflow.step.result_received.v2","openxiangda.workflow.step.completed.v2","openxiangda.workflow.step.continuation_failed.v2","openxiangda.workflow.instance.started.v2","openxiangda.workflow.instance.cc_added.v2","openxiangda.workflow.instance.completed.v2","openxiangda.workflow.instance.rejected.v2","openxiangda.workflow.instance.returned.v2","openxiangda.workflow.instance.resumed.v2","openxiangda.workflow.instance.withdrawn.v2","openxiangda.workflow.instance.terminated.v2","openxiangda.workflow.task.created.v2","openxiangda.workflow.task.assigned.v2","openxiangda.workflow.task.assignment_pending.v2","openxiangda.workflow.task.assignment_resolution_failed.v2","openxiangda.workflow.task.approved.v2","openxiangda.workflow.task.completed.v2","openxiangda.workflow.task.rejected.v2","openxiangda.workflow.task.returned.v2","openxiangda.workflow.task.resubmitted.v2","openxiangda.workflow.task.transferred.v2","openxiangda.workflow.task.reassigned.v2","openxiangda.workflow.task.delegated.v2","openxiangda.workflow.task.assignee_added.v2","openxiangda.workflow.task.cancelled.v2","openxiangda.workflow.participant.activated.v2","openxiangda.workflow.participant.completed.v2","openxiangda.workflow.participant.rejected.v2","openxiangda.workflow.participant.returned.v2","openxiangda.workflow.participant.transferred.v2","openxiangda.workflow.participant.reassigned.v2","openxiangda.workflow.participant.delegated.v2","openxiangda.workflow.participant.added.v2","openxiangda.workflow.participant.suspended.v2","openxiangda.workflow.participant.resumed.v2","openxiangda.workflow.participant.cancelled.v2"],hd=new Set(xo),jo=class extends Error{code;pointer;identifiers;constructor(t,o,n={}){super(t),this.name="NativeConfigurationCompilerError",this.code=t,this.pointer=o,this.identifiers=Object.fromEntries(Object.entries(n).slice(0,8).map(([i,r])=>[i,String(r).slice(0,128)]))}};function op(e){let t=S(e.appCode,"/appCode",128);ad.test(t)||m("NATIVE_CONFIG_APP_CODE_INVALID","/appCode");let o=Uo(e.expectedConfigDigest,"/expectedConfigDigest"),n=Uo(e.expectedContractDigest,"/expectedContractDigest"),i=as(e.configBytes,Nd,"/configBytes","NATIVE_CONFIG_ARTIFACT_TOO_LARGE"),r=as(e.contractBytes,Td,"/contractBytes","NATIVE_CONTRACT_ARTIFACT_TOO_LARGE");ds(i,o,"/configBytes","NATIVE_CONFIG_DIGEST_MISMATCH"),ds(r,n,"/contractBytes","NATIVE_CONTRACT_DIGEST_MISMATCH");let d=ss(i,"/configBytes","NATIVE_CONFIG_JSON_INVALID","NATIVE_CONFIG_NOT_CANONICAL"),s=ss(r,"/contractBytes","NATIVE_CONTRACT_JSON_INVALID","NATIVE_CONTRACT_NOT_CANONICAL");gn(d,"/config",ct.nodes),gn(s,"/contracts",ct.nodes),_n(d)||gn(s,"/contracts",re.extendedNodes),mn(d)||gn(s,"/contracts",re.legacyNodes);let a=d,c=s;kd(a,t),$d(c,t,o);let f=Pd(a,o,c.generatorVersion);Ic(f,c,a),X(f)!==X(c)&&m("NATIVE_CONTRACT_CLOSURE_MISMATCH",Mo(f,c,"/contracts"));let u={authz:{appCode:t,...a.authz,perspectives:a.perspectives,capabilityCatalog:f.capabilities},data:{appCode:t,resources:a.data.resources,resourceContracts:f.resources,...f.concurrency?{concurrency:f.concurrency}:{},...f.subjectReadSurfaces?{subjectReadSurfaces:f.subjectReadSurfaces}:{}},events:{appCode:t,...a.events,consumers:f.eventConsumers,producers:f.eventProducers,handlerManifest:f.eventHandlerManifest,eventTypes:f.eventTypes,capturePlans:Sd({resources:a.data.resources,dataPolicies:a.authz.dataPolicies,subscriptions:f.eventConsumers,capturePolicies:a.events.capturePolicies})},workflows:{appCode:t,...a.workflows,contracts:f.workflows},runtime:{appCode:t,requirements:a.runtime,backend:a.backend,frontend:a.frontend},contracts:f},p={authz:lt(u.authz),data:lt(u.data),events:lt(u.events),workflows:lt(u.workflows),runtime:lt(u.runtime),contracts:lt(u.contracts)},_={configDigest:o,contractDigest:n,generatorVersion:c.generatorVersion},E=wd(a),A={schemaVersion:zr,compilerContractVersion:Vt,appCode:t,source:_,projections:p,requiredPlatformCapabilities:E,aggregateDigest:Z({schemaVersion:zr,compilerContractVersion:Vt,appCode:t,source:_,requiredPlatformCapabilities:E,projectionDigests:Object.fromEntries(Object.entries(p).map(([O,b])=>[O,b.digest]))})};return Ts(A)}function Yr(e,t){let o=e.subject,n=t.find(r=>r.code===o?.resourceCode),i=new Set(Object.values(o?.factProjection||{}));return!!n?.schema?.fields?.some(r=>r.type==="subtable"&&i.has(r.code))}function wd(e){let t=e.authz.roles,o=e.data.resources,n=e.backend.operations,i=n.filter(l=>l.platformAccess?.directory?.mode==="current-initiator"&&l.platformAccess.directory.fields.includes("phone")),r=(e.data.concurrency?.commands||[]).filter(l=>l.execution?.directory?.mode==="current-initiator"&&l.execution.directory.fields.includes("phone")),d=t.some(l=>l.capabilities.some(y=>y.endsWith(":directory:read")))||o.some(l=>l.schema.fields.some(y=>["user.single","user.multiple","department.single","department.multiple"].includes(y.type)))||n.some(l=>l.platformAccess?.directory||l.platformAccess?.selectedDepartments),s=!!(e.events.subscriptions.length||e.events.timers.length||e.events.dateTriggers.length||e.events.schemas.length),a=n.some(l=>l.platformAccess?.managedFiles||l.platformAccess?.managedFileCopies)||e.events.subscriptions.some(l=>l.platformAccess?.managedFileCopies),c=e.workflows.definitions.some(l=>l.definition.rejectionNotification!==void 0)||n.some(l=>l.platformAccess?.notification)||e.events.subscriptions.some(l=>l.platformAccess?.notification),f=(l,y,R=!1)=>{let h=o.find($=>$.code===l.definition.subject?.resourceCode)?.schema.fields||[];return Object.values(l.definition.taskPages||{}).some($=>$.fields.some(w=>{if(w.readonly)return!1;let j=h.find(Q=>Q.code===w.code);if(!R&&j&&y.includes(j.type))return!0;if(!w.subtable||!j?.subtable)return!1;let L=o.find(Q=>Q.code===j.subtable.resourceCode)?.schema.fields||[];return w.subtable.fields.some(Q=>!Q.readonly&&L.some(ee=>ee.code===Q.code&&y.includes(ee.type)))}))},u=e.workflows.definitions.filter(l=>f(l,["file","image","signature","text.rich"])),p=e.workflows.definitions.filter(l=>f(l,["signature","text.rich"])),_=e.workflows.definitions.filter(l=>f(l,["file","image","signature","text.rich"],!0)),E=e.workflows.definitions.filter(l=>l.launch.mode==="standalone"||l.launch.mode==="hidden-handoff"),A=n.some(l=>l.platformAccess?.workflow)||E.length>0,O=E.filter(l=>{let y=l.launch.submission;if(!y)return!1;let R=o.find(h=>h.code===l.definition.subject.resourceCode);return[y.create,y.existing].some(h=>h&&Object.values(h.inputs).some($=>$.source==="field"&&R?.schema.fields.some(w=>w.code===$.fieldCode&&w.type.startsWith("resource-ref.")&&w.source)))}),b={resources:o},g={perspectives:e.perspectives,authz:e.authz},I={schemaVersion:e.schemaVersion,appCode:e.appCode,frontend:{routes:e.frontend.routes,user:e.frontend.user,admin:e.frontend.admin,devicePolicy:e.frontend.devicePolicy},backend:{operations:n.map(l=>({code:l.code,method:l.method,path:l.path,capability:l.capability,platformAccess:l.platformAccess||null,...l.browser?{browser:l.browser}:{},ai:l.ai||null}))}};return[...$o(e)?[{code:"application.extended-role-capacity",declaration:{roles:e.authz.roles.length,maximum:B.roles}}]:[],...vo(e)?[{code:"application.extended-configuration-bytes",declaration:{legacyConfigBytes:re.legacyConfigBytes,configBytes:re.configBytes}}]:[],...mn(e)?[{code:"application.extended-artifact-capacity",declaration:re}]:[],..._n(e)?[{code:"application.high-density-artifact-capacity",declaration:ct}]:[],...Po(e)?[{code:"application.extended-declaration-capacity",declaration:{resources:e.data.resources.length,policies:e.authz.dataPolicies.length,roles:e.authz.roles.length,capabilities:e.authz.capabilities.length,definitions:e.workflows.definitions.length,bindings:e.workflows.bindings.length,activations:e.workflows.activations.length,routes:e.frontend.routes.length,navigationItems:e.frontend.admin.navigation.reduce((l,y)=>l+y.items.length,0)}}]:[],...o.some(l=>l.uniqueKeys?.length)?[{code:"data.unique-keys",declaration:o.filter(l=>l.uniqueKeys?.length).map(l=>({code:l.code,uniqueKeys:l.uniqueKeys}))}]:[],...e.data.concurrency?[{code:"data.managed-concurrency",declaration:e.data.concurrency}]:[],...e.data.concurrency?.commands.some(l=>l.mode==="durable")?[{code:"data.managed-concurrency.durable",declaration:e.data.concurrency}]:[],...o.some(l=>l.decimalReservationLifecycle)?[{code:"data.decimal-reservation-lifecycle",declaration:o.filter(l=>l.decimalReservationLifecycle).map(l=>({code:l.code,decimalReservationLifecycle:l.decimalReservationLifecycle}))}]:[],...n.some(l=>l.platformAccess?.dataCommands)?[{code:"data.business-commands",declaration:n.filter(l=>l.platformAccess?.dataCommands)}]:[],...e.authz.dataPolicies.some(co)?[{code:"data.parent-read-policy",declaration:e.authz.dataPolicies.filter(co)}]:[],...e.authz.dataPolicies.some(l=>l.publicRead)?[{code:"data.authenticated-public-projection",declaration:e.authz.dataPolicies.filter(l=>l.publicRead)}]:[],...n.some(l=>l.platformAccess?.roleAssertions?.actorAuthority)?[{code:"data.transaction-actor-authority",declaration:n.filter(l=>l.platformAccess?.roleAssertions?.actorAuthority)}]:[],...n.some(l=>l.platformAccess?.workflowStage)?[{code:"workflow.native-stage-guard",declaration:n.filter(l=>l.platformAccess?.workflowStage)}]:[],...n.some(l=>l.platformAccess?.recordEdit)?[{code:"data.record-edit",declaration:n.filter(l=>l.platformAccess?.recordEdit)}]:[],...n.some(l=>l.platformAccess?.decimalReservation)||e.events.subscriptions.some(l=>l.platformAccess?.decimalReservation)?[{code:"data.decimal-reservations",declaration:[...n.filter(l=>l.platformAccess?.decimalReservation).map(l=>({code:l.code,decimalReservation:l.platformAccess.decimalReservation})),...e.events.subscriptions.filter(l=>l.platformAccess?.decimalReservation).map(l=>({subscriptionCode:l.code,decimalReservation:l.platformAccess.decimalReservation}))]}]:[],{code:"application-native-2",declaration:I},{code:"authz.native-batch-explain",declaration:g},{code:"authz.native-management",declaration:g},{code:"deployment.durable-runs",declaration:I.backend},{code:"deployment.platform-executor",declaration:I.backend},{code:"environment.on-demand-production",declaration:{environments:["preproduction","production"]}},{code:"environment.runtime-lifecycle",declaration:{environments:["preproduction","production"]}},...o.length?[{code:"data-api-v2",declaration:b},{code:"data.native-golden-crud",declaration:b}]:[],...o.some(l=>l.recordComments!==void 0)?[{code:"data.record-comments",declaration:b}]:[],...o.some(l=>l.recordDeletion!==void 0)?[{code:"data.workflow-record-deletion",declaration:b}]:[],...o.some(l=>l.recordPrint!==void 0)?[{code:"data.record-print",declaration:b}]:[],...o.some(l=>l.workflowHistory!==void 0)?[{code:"workflow.record-history-read",declaration:b}]:[],...o.some(pi)?[{code:"data.audit-read-access",declaration:b}]:[],...d?[{code:"directory-v2",declaration:{roles:t.map(l=>({code:l.code,capabilities:l.capabilities.filter(y=>y.endsWith(":directory:read"))})),resources:o.map(l=>({code:l.code,fields:l.schema.fields.filter(y=>["user.single","user.multiple","department.single","department.multiple"].includes(y.type))})),operations:n.filter(l=>l.platformAccess?.directory).map(l=>({code:l.code,directory:l.platformAccess.directory}))}}]:[],...n.some(l=>l.platformAccess?.selectedDepartments)?[{code:"directory.selected-departments",declaration:n.filter(l=>l.platformAccess?.selectedDepartments).map(l=>({code:l.code,selectedDepartments:l.platformAccess.selectedDepartments}))}]:[],...n.some(l=>l.platformAccess?.directory?.mode==="selected-user")?[{code:"directory.selected-user",declaration:n.filter(l=>l.platformAccess?.directory?.mode==="selected-user").map(l=>({code:l.code,directory:l.platformAccess.directory}))}]:[],...i.length||r.length?[{code:"directory.current-initiator-phone",declaration:{operations:i.map(l=>({code:l.code,directory:l.platformAccess.directory})),commands:r.map(l=>({code:l.code,directory:l.execution.directory}))}}]:[],...e.data.resources.some(l=>l.schema.fields.some(y=>y.type==="text.rich"))?[{code:"data.rich-text",declaration:{policyVersion:"rich-text-html/1"}}]:[],...a?[{code:"data.managed-files",declaration:{operations:n.filter(l=>l.platformAccess?.managedFiles||l.platformAccess?.managedFileCopies).map(l=>({code:l.code,...l.platformAccess?.managedFiles?{managedFiles:l.platformAccess.managedFiles}:{},...l.platformAccess?.managedFileCopies?{managedFileCopies:l.platformAccess.managedFileCopies}:{}})),subscriptions:e.events.subscriptions.filter(l=>l.platformAccess?.managedFileCopies).map(l=>({code:l.code,managedFileCopies:l.platformAccess.managedFileCopies}))}}]:[],...e.events.subscriptions.some(l=>l.execution)?[{code:"events.native-data-actions",declaration:e.events.subscriptions.filter(l=>l.execution)}]:[],...e.events.capturePolicies?.length?[{code:"events.capture-policy",declaration:e.events.capturePolicies}]:[],...e.events.dateTriggers.some(l=>Dr(l.resourceCode,e.events.subscriptions.filter(y=>y.eventTypes.includes(l.eventType)),e.data.resources.find(y=>y.code===l.resourceCode)).length>0)?[{code:"events.date-source-projection",declaration:{triggers:e.events.dateTriggers,subscriptions:e.events.subscriptions}}]:[],...s?[{code:"events-v2",declaration:e.events},{code:"events.durable-receipts",declaration:e.events}]:[],...Ln(e.data.resources)?[{code:"data.extended-owned-subtable-capacity",declaration:e.data.resources.filter(l=>Ln([l]))}]:[],...vn(e.data.resources,e.workflows?.definitions||[])?[{code:"data.extended-field-capacity",declaration:{resources:e.data.resources.filter(l=>l.schema.fields.length>100),workflows:(e.workflows?.definitions||[]).filter(l=>vn([],[l]))}}]:[],...Vn(e.data.resources)?[{code:"data.aggregate-owned-subtable-capacity",declaration:e.data.resources.filter(l=>Vn([l]))}]:[],...e.data.resources.some(l=>l.schema.fields.some(y=>y.userCandidates!==void 0))?[{code:"data.user-candidates",declaration:e.data.resources.filter(l=>l.schema.fields.some(y=>y.userCandidates!==void 0))}]:[],...mr(e.workflows.bindings)?[{code:"workflow.role-input-selection",declaration:e.workflows.bindings.filter(l=>Object.values(l.binding.bindings).some(y=>y.selectedInputPath!==void 0))}]:[],...fr(e.workflows.bindings)?[{code:"workflow.role-union",declaration:e.workflows.bindings.filter(l=>Object.values(l.binding.bindings).some(y=>y.roleCodes!==void 0))}]:[],...e.backend.operations.some(l=>l.platformAccess?.ownedSubject)?[{code:"workflow.named-owned-create",declaration:e.backend.operations.filter(l=>l.platformAccess?.ownedSubject)}]:[],...kn(e.data.resources)?[{code:"data.user-candidate-launch-scope",declaration:e.data.resources.filter(l=>kn([l]))}]:[],...Un(e.data.resources)?[{code:"data.subtable-minimum-rows",declaration:e.data.resources.filter(l=>Un([l]))}]:[],...Wn(e.data.resources)?[{code:"data.datetime-minute-precision",declaration:e.data.resources.filter(l=>Wn([l]))}]:[],...e.workflows.activations.length?[{code:"workflow-kernel-v2",declaration:e.workflows},{code:"workflow.fresh-command-token",declaration:e.workflows}]:[],...e.workflows.definitions.some(l=>l.definition.instanceCommands!==void 0)?[{code:"workflow.instance-cancellation-policy",declaration:e.workflows.definitions.filter(l=>l.definition.instanceCommands!==void 0)}]:[],...e.workflows.definitions.some(l=>l.definition.instanceCommands?.withdraw?.reasonRequired===!1)?[{code:"workflow.optional-withdrawal-reason",declaration:e.workflows.definitions.filter(l=>l.definition.instanceCommands?.withdraw?.reasonRequired===!1)}]:[],...e.workflows.definitions.some(l=>l.definition.rejectionNotification!==void 0)?[{code:"workflow.rejection-notification",declaration:e.workflows.definitions.filter(l=>l.definition.rejectionNotification!==void 0)}]:[],...e.workflows.definitions.some(l=>l.definition.commandHandlers!==void 0)||n.some(l=>l.platformAccess?.workflow?.businessCommands)?[{code:"workflow.business-data-command",declaration:{definitions:e.workflows.definitions.filter(l=>l.definition.commandHandlers!==void 0),operations:n.filter(l=>l.platformAccess?.workflow?.businessCommands)}}]:[],...e.workflows.definitions.some(l=>l.definition.commandHandlers?.approve?.transitionPolicy==="workflow")?[{code:"workflow.approval-business-command",declaration:e.workflows.definitions.filter(l=>l.definition.commandHandlers?.approve?.transitionPolicy==="workflow")}]:[],...e.workflows.definitions.some(l=>l.definition.commandHandlers?.resubmit)||n.some(l=>l.platformAccess?.workflow?.businessCommands?.includes("resubmit"))?[{code:"workflow.correction-business-command",declaration:{definitions:e.workflows.definitions.filter(l=>l.definition.commandHandlers?.resubmit),operations:n.filter(l=>l.platformAccess?.workflow?.businessCommands?.includes("resubmit"))}}]:[],...e.workflows.definitions.some(l=>l.definition.launchPreflight!==void 0)?[{code:"workflow.launch-preflight",declaration:e.workflows.definitions.filter(l=>l.definition.launchPreflight!==void 0)}]:[],...e.workflows.definitions.some(l=>l.definition.commandHandlers?.resubmit?.derivedSubjectFields!==void 0)?[{code:"workflow.correction-derived-subject-facts",declaration:e.workflows.definitions.filter(l=>l.definition.commandHandlers?.resubmit?.derivedSubjectFields!==void 0)}]:[],...e.workflows.definitions.some(l=>l.definition.approvedDelegation!==void 0)?[{code:"workflow.approved-delegation",declaration:e.workflows.definitions.filter(l=>l.definition.approvedDelegation!==void 0)}]:[],...e.workflows.definitions.some(l=>Yr(l.definition,e.data.resources))?[{code:"workflow.owned-initial-facts",declaration:e.workflows.definitions.filter(l=>Yr(l.definition,e.data.resources))}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.nodes).some(y=>y.kind==="correction"))?[{code:"workflow.initiator-correction",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.nodes).some(y=>y.kind==="correction"))}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.nodes).some(y=>y.operationPolicy?.reject?.commentRequired===!1))?[{code:"workflow.optional-rejection-comment",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.nodes).some(y=>y.operationPolicy?.reject?.commentRequired===!1))}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.nodes).some(y=>Object.values(y.operationPolicy||{}).some(R=>R.reasonRequired===!1)))?[{code:"workflow.optional-operation-reason",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.nodes).some(y=>Object.values(y.operationPolicy||{}).some(R=>R.reasonRequired===!1)))}]:[],...O.length?[{code:"workflow.named-input-sources",declaration:O}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.nodes).some(y=>y.administration!==void 0||y.operationPolicy!==void 0))?[{code:"workflow.node-administration",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.nodes).some(y=>y.administration!==void 0||y.operationPolicy!==void 0))}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.nodes).some(y=>y.kind==="approval"&&y.emptyPolicy!==void 0))?[{code:"workflow.approval-empty-policy",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.nodes).some(y=>y.kind==="approval"&&y.emptyPolicy!==void 0))}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.nodes).some(y=>y.completionDeadline!==void 0))?[{code:"workflow.completion-deadline",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.nodes).some(y=>y.completionDeadline!==void 0))}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.nodes).some(y=>y.initiatorApprovalPolicy!==void 0))?[{code:"workflow.initiator-approval-policy",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.nodes).some(y=>y.initiatorApprovalPolicy!==void 0))}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.nodes).some(y=>y.kind==="cc"))?[{code:"workflow.automatic-cc",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.nodes).some(y=>y.kind==="cc"))}]:[],...e.workflows.definitions.some(l=>l.definition.taskPages!==void 0)?["workflow.task-page-submit","workflow.task-private-drafts"].map(l=>({code:l,declaration:e.workflows.definitions.filter(y=>y.definition.taskPages!==void 0)})):[],...u.length?[{code:"workflow.task-managed-files",declaration:u}]:[],..._.length?[{code:"workflow.task-owned-files",declaration:_}]:[],...p.length?[{code:"workflow.task-rich-fields",declaration:p}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.taskPages||{}).some(y=>y.fields.some(R=>R.subtable)))?[{code:"workflow.task-owned-subtables",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.taskPages||{}).some(y=>y.fields.some(R=>R.subtable)))}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.nodes).some(y=>y.kind==="action"))?[{code:"workflow.durable-business-step",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.nodes).some(y=>y.kind==="action"))}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.nodes).some(y=>y.kind==="action"&&y.handler.dataTransaction))?[{code:"workflow.step-data-transaction",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.nodes).some(y=>y.kind==="action"&&y.handler.dataTransaction))}]:[],...e.workflows.bindings.some(l=>Object.values(l.binding.bindings).some(y=>y.routing!==void 0))?[{code:"workflow.assignment-routing",declaration:e.workflows.bindings.filter(l=>Object.values(l.binding.bindings).some(y=>y.routing!==void 0))}]:[],...A?[{code:"business-process.durable-command",declaration:{operations:n.filter(l=>l.platformAccess?.workflow).map(l=>({code:l.code,workflow:l.platformAccess.workflow})),definitions:E,activations:e.workflows.activations.filter(l=>E.some(y=>y.definition.code===l.workflowCode))}}]:[],...c?[{code:"notification-hub-v2",declaration:{...e.workflows.definitions.some(l=>l.definition.rejectionNotification!==void 0)?{rejectionNotifications:e.workflows.definitions.filter(l=>l.definition.rejectionNotification!==void 0)}:{},operations:n.filter(l=>l.platformAccess?.notification).map(l=>({code:l.code,notification:l.platformAccess.notification})),subscriptions:e.events.subscriptions.filter(l=>l.platformAccess?.notification).map(l=>({code:l.code,notification:l.platformAccess.notification}))}}]:[],...e.frontend.authentication?[{code:"authentication.application-login-surface",declaration:e.frontend.authentication}]:[],...e.frontend.publicAccess?[{code:"public-access.anonymous-owner-records",declaration:e.frontend.publicAccess}]:[]].map(({code:l,declaration:y})=>({code:l,contractVersion:l==="data.unique-keys"?o.some(R=>Hi(R.schema.fields,R.uniqueKeys)==="1.1.0")?"1.1.0":"1.0.0":Kr[l],usageDigest:`sha256:${Z(y)}`})).sort((l,y)=>l.code===y.code?0:l.code<y.code?-1:1)}function Sd(e){let t=new Map,o=new Set(e.resources.map(r=>String(r.code)));for(let[r,d]of D(e.capturePolicies===void 0?[]:e.capturePolicies,"/capturePlan/capturePolicies",100).entries()){let s=`/capturePlan/capturePolicies/${r}`,a=N(d,s);C(a,["resourceCode","mode"],s);let c=H(a.resourceCode,`${s}/resourceCode`);o.has(c)||m("NATIVE_EVENT_CAPTURE_RESOURCE_NOT_FOUND",s,{resourceCode:c}),t.has(c)&&m("NATIVE_EVENT_CAPTURE_POLICY_DUPLICATE",s,{resourceCode:c}),a.mode!=="all"&&a.mode!=="subscribed"&&m("NATIVE_EVENT_CAPTURE_MODE_INVALID",`${s}/mode`),t.set(c,a.mode)}let n=new Map(e.dataPolicies.map((r,d)=>{let s=N(r,`/capturePlan/dataPolicies/${d}`);return[String(s.code),s]})),i=e.subscriptions.map((r,d)=>N(r,`/capturePlan/subscriptions/${d}`));return e.resources.map((r,d)=>{let s=`/capturePlan/resources/${d}`,a=N(r,s),c=H(a.code,`${s}/code`),f=a.schema?N(a.schema,`${s}/schema`):a,u=new Set(D(f.fields||[],`${s}/schema/fields`,500).map((y,R)=>G(N(y,`${s}/schema/fields/${R}`).code,`${s}/schema/fields/${R}/code`))),p=a.dataPolicyCode?v(a.dataPolicyCode,`${s}/dataPolicyCode`):null,_=p?n.get(p):void 0;p&&!_&&m("NATIVE_EVENT_CAPTURE_AUTHZ_POLICY_NOT_FOUND",s,{resourceCode:c,dataPolicyCode:p});let E=new Set;for(let y of _?.rules||[])E.add(y.parentRead?Xt(e.resources,c,y.parentRead,`${s}/parentRead`).foreignKey:String(y.field));if(_?.readExpression)for(let y of st(_.readExpression,`${s}/readExpression`))E.add(y.rule.parentRead?Xt(e.resources,c,y.rule.parentRead,`${s}/parentRead`).foreignKey:String(y.rule.field));let A=new Set,O=new Set,b=new Set;for(let[y,R]of i.entries()){let h=D(R.eventTypes,`/capturePlan/subscriptions/${y}/eventTypes`,20).map(String);if(!h.some(L=>L.startsWith("openxiangda.data.")))continue;let $=N(R.filter||{},`/capturePlan/subscriptions/${y}/filter`),w=Array.isArray($.resourceCodes)?$.resourceCodes.map(String):[];if(w.length&&!w.includes(c))continue;for(let L of h)Fo.includes(L)&&b.add(L);for(let L of Dd($,`/capturePlan/subscriptions/${y}/filter`))A.add(L);let j=N(R.payload||{},`/capturePlan/subscriptions/${y}/payload`);for(let L of D(j.fields||[],`/capturePlan/subscriptions/${y}/payload/fields`,32))O.add(G(L,`/capturePlan/subscriptions/${y}/payload/fields`))}let g=new Set([...A,...O]),I=new Set([...g,...E]);I.size>Hr&&m("NATIVE_EVENT_CAPTURE_FIELDS_LIMIT",s,{resourceCode:c,maximum:Hr});for(let y of I)!u.has(y)&&!(E.has(y)&&fs.has(y))&&m("NATIVE_EVENT_CAPTURE_FIELD_NOT_FOUND",s,{resourceCode:c,field:y});let T=N(a.fieldPolicies||{},`${s}/fieldPolicies`);for(let y of g)T[y]?.mask==="omit"&&m("NATIVE_EVENT_CAPTURE_FIELD_SENSITIVE",s,{resourceCode:c,field:y});let l={resourceCode:c,...t.get(c)==="subscribed"?{capturedEventTypes:[...b].sort()}:{},filterFields:[...A].sort(),projectionFields:[...O].sort(),authorizationFields:[...E].sort(),captureFields:[...I].sort()};return{...l,digest:Z(l)}}).sort((r,d)=>r.resourceCode.localeCompare(d.resourceCode))}function Dd(e,t){let o=new Set;for(let[d,s]of D(e.changes||[],`${t}/changes`,16).entries()){let a=N(s,`${t}/changes/${d}`);o.add(G(a.field,`${t}/changes/${d}/field`))}let n=N(e.changedFields||{},`${t}/changedFields`);for(let d of["anyOf","allOf","noneOf"])for(let[s,a]of D(n[d]||[],`${t}/changedFields/${d}`,32).entries())o.add(G(a,`${t}/changedFields/${d}/${s}`));let i=0,r=(d,s,a)=>{a>3&&m("NATIVE_EVENT_FILTER_DEPTH_LIMIT",s);let c=N(d,s);if(c.change){let u=N(c.change,`${s}/change`);o.add(G(u.field,`${s}/change/field`)),i+=1;return}if(c.not){r(c.not,`${s}/not`,a+1);return}let f=c.all?"all":c.any?"any":null;f||m("NATIVE_EVENT_FILTER_CONDITION_INVALID",s);for(let[u,p]of D(c[f],`${s}/${f}`,16).entries())r(p,`${s}/${f}/${u}`,a+1)};return e.where&&r(e.where,`${t}/where`,1),i+=Array.isArray(e.changes)?e.changes.length:0,i>16&&m("NATIVE_EVENT_FILTER_ATOM_LIMIT",t),[...o].sort()}function kd(e,t){C(e,["schemaVersion","compilerContractVersion","appCode","perspectives","authz","backend","data","events","workflows","frontend","runtime"],"/config"),F(e.schemaVersion,rd,"/config/schemaVersion"),F(e.compilerContractVersion,Vt,"/config/compilerContractVersion"),F(e.appCode,t,"/config/appCode"),D(e.perspectives,"/config/perspectives",100);let o=N(e.authz,"/config/authz");C(o,["capabilities","roles","scopeDimensions","scopeSources","roleMembershipSources","relationshipGrantSources","dataPolicies","authorizationTransitions"],"/config/authz",["authenticatedUserRoleCode"]),D(o.capabilities,"/config/authz/capabilities",B.capabilities),D(o.roles,"/config/authz/roles",B.roles),D(o.scopeDimensions,"/config/authz/scopeDimensions",100),D(o.scopeSources,"/config/authz/scopeSources",100),D(o.roleMembershipSources,"/config/authz/roleMembershipSources",100),D(o.relationshipGrantSources,"/config/authz/relationshipGrantSources",100),D(o.dataPolicies,"/config/authz/dataPolicies",B.dataPolicies),D(o.authorizationTransitions,"/config/authz/authorizationTransitions",100);let n=N(e.backend,"/config/backend");C(n,["secrets","operations"],"/config/backend"),D(n.secrets,"/config/backend/secrets",100),D(n.operations,"/config/backend/operations",500),pc(n.secrets);let i=N(e.data,"/config/data");C(i,["resources"],"/config/data",["resourceDetailRoutes","subjectReadSurfaces","concurrency"]),D(i.resources,"/config/data/resources",B.resources),i.subjectReadSurfaces!==void 0&&D(i.subjectReadSurfaces,"/config/data/subjectReadSurfaces",B.subjectReadSurfaces),i.resourceDetailRoutes!==void 0&&D(i.resourceDetailRoutes,"/config/data/resourceDetailRoutes",100);let r=N(e.events,"/config/events");C(r,["schemas","subscriptions","timers","dateTriggers"],"/config/events",["capturePolicies"]),D(r.schemas,"/config/events/schemas",100),D(r.subscriptions,"/config/events/subscriptions",100),D(r.timers,"/config/events/timers",100),D(r.dateTriggers,"/config/events/dateTriggers",100);let d=N(e.workflows,"/config/workflows");C(d,["definitions","bindings","activations","providers","editableParameters"],"/config/workflows"),D(d.definitions,"/config/workflows/definitions",B.workflows),D(d.bindings,"/config/workflows/bindings",B.workflows),D(d.activations,"/config/workflows/activations",B.workflows),D(d.providers,"/config/workflows/providers",100),D(d.editableParameters,"/config/workflows/editableParameters",100);let s=N(e.frontend,"/config/frontend");C(s,["routes","user","admin","devicePolicy"],"/config/frontend",["authentication","publicAccess"]),D(s.routes,"/config/frontend/routes",B.routes);let a=N(s.user,"/config/frontend/user");C(a,["applicationTodoCenter"],"/config/frontend/user"),ft(a.applicationTodoCenter,"/config/frontend/user/applicationTodoCenter"),Bo(s.devicePolicy,"/config/frontend/devicePolicy"),Object.prototype.hasOwnProperty.call(s,"authentication")&&ms(s.authentication,s.routes,e,"/config/frontend/authentication"),Object.prototype.hasOwnProperty.call(s,"publicAccess")&&Jd(s.publicAccess,e,"/config/frontend/publicAccess");let c=N(s.admin,"/config/frontend/admin");C(c,["navigation"],"/config/frontend/admin",["access"]),c.access!==void 0&&On(c.access,"/config/frontend/admin/access",e.appCode),Zd(c.navigation,"/config/frontend/admin/navigation");let f=N(e.runtime,"/config/runtime");C(f,["protocolCapabilities","health"],"/config/runtime"),V(f.protocolCapabilities,"/config/runtime/protocolCapabilities",100),C(N(f.health,"/config/runtime/health"),["livePath","readyPath","versionPath"],"/config/runtime/health"),F(f.health.livePath,"/__platform/health","/config/runtime/health/livePath"),F(f.health.readyPath,"/__platform/ready","/config/runtime/health/readyPath"),F(f.health.versionPath,"/__platform/version","/config/runtime/health/versionPath")}function $d(e,t,o){C(e,["schemaVersion","compilerContractVersion","generatorVersion","appCode","configDigest","perspectives","resources","capabilities","operations","eventConsumers","eventProducers","eventSchemas","eventHandlerManifest","eventTypes","workflows","routes","routeManifest","adminPages","adminNavigation"],"/contracts",["authentication","publicAccess","adminAccess","subjectReadSurfaces","concurrency"]),F(e.schemaVersion,ls,"/contracts/schemaVersion"),F(e.compilerContractVersion,Vt,"/contracts/compilerContractVersion"),S(e.generatorVersion,"/contracts/generatorVersion",128),F(e.appCode,t,"/contracts/appCode"),F(e.configDigest,o,"/contracts/configDigest"),D(e.perspectives,"/contracts/perspectives",B.perspectives),D(e.resources,"/contracts/resources",B.resources),e.subjectReadSurfaces!==void 0&&D(e.subjectReadSurfaces,"/contracts/subjectReadSurfaces",B.subjectReadSurfaces),D(e.capabilities,"/contracts/capabilities",B.capabilities),D(e.operations,"/contracts/operations",B.operations),D(e.eventConsumers,"/contracts/eventConsumers",B.eventConsumers),D(e.eventProducers,"/contracts/eventProducers",B.eventProducers),D(e.eventSchemas,"/contracts/eventSchemas",B.eventSchemas),N(e.eventHandlerManifest,"/contracts/eventHandlerManifest"),V(e.eventTypes,"/contracts/eventTypes",B.eventTypes),D(e.workflows,"/contracts/workflows",B.workflows),D(e.routes,"/contracts/routes",B.routes),Object.prototype.hasOwnProperty.call(e,"authentication")&&Gd(e.authentication,"/contracts/authentication"),Object.prototype.hasOwnProperty.call(e,"publicAccess")&&Hd(e.publicAccess,"/contracts/publicAccess"),Object.prototype.hasOwnProperty.call(e,"adminAccess")&&On(e.adminAccess,"/contracts/adminAccess",t),ic(e.routeManifest,"/contracts/routeManifest",t),tc(e.adminPages,"/contracts/adminPages"),nc(e.adminNavigation,"/contracts/adminNavigation")}function Pd(e,t,o){let n=Ld(e);cc(e,n),uc(e),lc(e),mc(e);let i=e.events.schemas.map((g,I)=>{let T=`/config/events/schemas/${I}`,l=N(g,T),y=S(l.eventType,`${T}/eventType`,255);return y.startsWith("openxiangda.")&&m("NATIVE_EVENT_SCHEMA_RESERVED",`${T}/eventType`,{eventType:y}),F(l.schemaDigest,Z(N(l.jsonSchema,`${T}/jsonSchema`)),`${T}/schemaDigest`),l}),r=new Set([...Fo,...xo,...i.map(g=>String(g.eventType))]),d=new Map(e.data.resources.map(g=>[String(g.code),new Map(g.schema.fields.map(I=>[String(I.code),String(I.type)]))])),s=te(e.events.subscriptions.map((g,I)=>{let T=`/config/events/subscriptions/${I}`,l=N(g,T),y=V(l.eventTypes,`${T}/eventTypes`,20);y.forEach((w,j)=>{r.has(w)||m("NATIVE_EVENT_TYPE_NOT_REGISTERED",`${T}/eventTypes/${j}`,{eventType:w})});let R=Qi(l,e.data.resources,T),h=Vd(l.delivery,y,`${T}/delivery`),$=vd(l.platformAccess,`${T}/platformAccess`,d,e,l);return{code:v(l.code,`${T}/code`),endpointPath:Oe(l.endpointPath,`${T}/endpointPath`),eventTypes:y,filter:N(l.filter,`${T}/filter`),payload:R?.payload||N(l.payload,`${T}/payload`),...R?{execution:R.execution}:{},...$?{platformAccess:$}:{},delivery:h}}),g=>g.code),a=new Map(i.map(g=>[String(g.eventType),String(g.dataSchemaVersion)])),c=te([...e.data.resources.flatMap(g=>Fo.map(I=>({code:`data:${g.code}:${I}`,source:"data",eventType:I,dataSchemaVersion:"2.0.0",resourceCode:g.code}))),...i.map(g=>({code:`app:${g.eventType}`,source:"app",eventType:g.eventType,dataSchemaVersion:g.dataSchemaVersion})),...e.events.timers.map(g=>({code:g.code,source:"timer",eventType:g.eventType,dataSchemaVersion:a.get(String(g.eventType))||"2.0.0"})),...e.events.dateTriggers.map(g=>({code:g.code,source:"date",eventType:g.eventType,dataSchemaVersion:a.get(String(g.eventType))||"2.0.0",resourceCode:g.resourceCode,field:g.field})),...e.workflows.activations.length?xo.filter(g=>!ir.includes(g)||e.workflows.definitions.some(I=>Object.values(I.definition.nodes).some(T=>T.kind==="action"))).filter(g=>g!=="openxiangda.workflow.node.skipped.v2"||e.workflows.definitions.some(I=>Object.values(I.definition.nodes).some(T=>T.kind==="approval"&&T.emptyPolicy==="skip"))).map(g=>({code:`workflow:${g}`,source:"workflow",eventType:g,dataSchemaVersion:"2.0.0"})):[]],g=>`${g.source}:${g.code}:${g.eventType}`),f=M([...s.flatMap(g=>g.eventTypes),...c.map(g=>String(g.eventType))]);ec(e);let u=As(e),p;try{p=Ri(e.data.concurrency,e.data.resources,n)}catch(g){throw g instanceof Et&&m(g.code,g.pointer,{reason:g.reason}),g}p?.commands.some(g=>g.mode==="durable")&&e.backend?.enabled===!1&&m("NATIVE_MANAGED_CONCURRENCY_INVALID","/data/concurrency",{reason:"durable commands require backend runtime"});let _=xd(e,n),E=ps(e),A=e.workflows.definitions.map(g=>g.definition),O=Ao(A),b=dr(A,s,!0);b.length&&m(b[0],"/config/events/subscriptions");try{hi(e.data.resources,E)}catch(g){throw g instanceof rt&&m(g.code,g.pointer,{reason:g.reason}),g}return{schemaVersion:ls,compilerContractVersion:Vt,generatorVersion:o,appCode:e.appCode,configDigest:t,perspectives:e.perspectives,resources:Fd(e),..._.length?{subjectReadSurfaces:_}:{},...p?{concurrency:p}:{},capabilities:te(n,g=>g.code),operations:E,eventConsumers:s,eventProducers:c,eventSchemas:i,eventHandlerManifest:{schemaVersion:Cd,appCode:e.appCode,handlers:s.filter(g=>!g.execution).map(g=>({code:g.code,endpointPath:g.endpointPath,eventTypes:g.eventTypes,dataSchemaVersions:M(g.eventTypes.map(I=>I.startsWith("openxiangda.")?"2.0.0":a.get(I)||"2.0.0")),maxBodyBytes:65536,receiptProtocolVersion:2,...O[g.code]?{workflowStep:O[g.code]}:{}}))},eventTypes:f,workflows:ys(e),routes:bn(e),...Object.prototype.hasOwnProperty.call(e.frontend,"authentication")?{authentication:qd(e)}:{},...Object.prototype.hasOwnProperty.call(e.frontend,"publicAccess")?{publicAccess:Yd(e)}:{},...e.frontend.admin.access?{adminAccess:e.frontend.admin.access}:{},routeManifest:ac(e),adminPages:u,adminNavigation:Xd(e)}}function vd(e,t,o,n,i){if(e===void 0)return;let r=N(e,t);C(r,["notification","managedFileCopies","decimalReservation"],t,!0);let d={};if(r.decimalReservation!==void 0)try{d.decimalReservation=Xi(r.decimalReservation,Zi(n,i))}catch{m("NATIVE_EVENT_DECIMAL_RESERVATION_INVALID",`${t}/decimalReservation`)}if(r.notification!==void 0){let s=N(r.notification,`${t}/notification`);C(s,["mode"],`${t}/notification`),F(s.mode,"business-standard",`${t}/notification/mode`),d.notification={mode:"business-standard"}}if(r.managedFileCopies!==void 0){let s=D(r.managedFileCopies,`${t}/managedFileCopies`,16);s.length||m("NATIVE_EVENT_MANAGED_FILE_COPIES_REQUIRED",`${t}/managedFileCopies`);let a=new Set;d.managedFileCopies=te(s.map((c,f)=>{let u=`${t}/managedFileCopies/${f}`,p=N(c,u);C(p,["mode","sourceResourceCode","sourceFieldCodes","targetResourceCode","targetFieldCodes"],u),F(p.mode,"copy",`${u}/mode`);let _=H(p.sourceResourceCode,`${u}/sourceResourceCode`),E=H(p.targetResourceCode,`${u}/targetResourceCode`),A=o.get(_),O=o.get(E);(!A||!O)&&m("NATIVE_EVENT_MANAGED_FILE_COPY_RESOURCE_INVALID",u);let b=V(p.sourceFieldCodes,`${u}/sourceFieldCodes`,16),g=V(p.targetFieldCodes,`${u}/targetFieldCodes`,16);(!b.length||b.length!==g.length)&&m("NATIVE_EVENT_MANAGED_FILE_COPY_FIELDS_INVALID",u),b.forEach((T,l)=>{let y=A.get(T),R=O.get(g[l]);(!["file","image","text.rich"].includes(String(y))||y!==R)&&m("NATIVE_EVENT_MANAGED_FILE_COPY_FIELD_INVALID",`${u}/sourceFieldCodes/${l}`)});let I=`${_}:${b.join(",")}=>${E}:${g.join(",")}`;return a.has(I)&&m("NATIVE_EVENT_MANAGED_FILE_COPY_DUPLICATE",u),a.add(I),{mode:"copy",sourceResourceCode:_,sourceFieldCodes:M(b),targetResourceCode:E,targetFieldCodes:M(g)}}),c=>`${c.sourceResourceCode}:${c.sourceFieldCodes.join(",")}=>${c.targetResourceCode}:${c.targetFieldCodes.join(",")}`)}return Object.keys(d).length||m("NATIVE_EVENT_PLATFORM_ACCESS_EMPTY",t),d}function Vd(e,t,o){let n=N(e,o);C(n,["timeoutMs","maxAttempts","initialBackoffMs","maxBackoffMs","ordering","concurrency"],o),se(n.timeoutMs,`${o}/timeoutMs`,1e3,3e4),se(n.maxAttempts,`${o}/maxAttempts`,1,12);let i=se(n.initialBackoffMs,`${o}/initialBackoffMs`,1e3,3e5);se(n.maxBackoffMs,`${o}/maxBackoffMs`,i,18e5),se(n.concurrency,`${o}/concurrency`,1,50);let r=S(n.ordering,`${o}/ordering`,32);return["none","record","workflow-instance"].includes(r)||m("NATIVE_EVENT_DELIVERY_ORDERING_INVALID",`${o}/ordering`),r==="workflow-instance"&&t.some(d=>!hd.has(d))&&m("NATIVE_EVENT_WORKFLOW_ORDERING_REQUIRES_WORKFLOW_FACTS",`${o}/ordering`),n}function Ld(e){let t=new Map;for(let r of Ns(e.appCode))t.set(r.code,r);for(let[r,d]of e.authz.capabilities.entries()){let s=`/config/authz/capabilities/${r}`,a=N(d,s);C(a,["code","kind","name","description"],s,!0);let c=me(a.code,`${s}/code`,e.appCode);t.has(c)&&m("NATIVE_CAPABILITY_DUPLICATE",`${s}/code`),["backend","ui"].includes(a.kind)||m("NATIVE_CAPABILITY_KIND_INVALID",`${s}/kind`);let f={code:c,kind:a.kind,name:S(a.name,`${s}/name`,255),source:"explicit",...a.description===void 0?{}:{description:Go(a.description,`${s}/description`,2e3)}};t.set(c,f)}let o=e.data.resources.map((r,d)=>({pointer:`/config/data/resources/${d}`,resource:Ye(r,`/config/data/resources/${d}`,e.appCode)}));for(let{pointer:r,resource:d}of o){let s={read:`\u8BFB\u53D6${d.name}`,create:`\u65B0\u5EFA${d.name}`,update:`\u66F4\u65B0${d.name}`,delete:`\u5220\u9664${d.name}`};for(let a of["read","create","update","delete"]){let c=me(d.capabilities[a],`${r}/capabilities/${a}`,e.appCode);t.has(c)&&m("NATIVE_CAPABILITY_DUPLICATE",`${r}/capabilities/${a}`),t.set(c,{code:c,kind:"data",name:s[a],source:"data"})}}let n=new Set(t.keys()),i=new Map;for(let{pointer:r,resource:d}of o)for(let[s,a]of Object.entries(d.fieldPolicies)){if(_t(s))continue;let c=N(a,`${r}/fieldPolicies/${s}`);for(let f of["read","create","update"])if(Array.isArray(c[f]))for(let u of V(c[f],`${r}/fieldPolicies/${s}/${f}`,2e3)){if(me(u,`${r}/fieldPolicies/${s}/${f}`,e.appCode),n.has(u))continue;let p=i.get(u);p&&p!==d.code&&m("NATIVE_CAPABILITY_DUPLICATE",`${r}/fieldPolicies/${s}/${f}`),i.set(u,d.code),!t.has(u)&&t.set(u,{code:u,kind:"data",name:`${d.name}.${s}.${f}`,source:"data"})}}return[...t.values()]}function Fd(e){let t=jd(e);return te(e.data.resources.map((o,n)=>{let i=Ye(o,`/config/data/resources/${n}`,e.appCode),r=t.get(i.code);return{code:i.code,schemaDigest:Z(i.schema),fields:te(i.schema.fields.map(d=>({code:d.code,type:d.type})),d=>d.code),...r?{detailRouteCode:r}:{}}}),o=>o.code)}function xd(e,t){if(e.data.subjectReadSurfaces===void 0)return[];let o=D(e.data.subjectReadSurfaces,"/config/data/subjectReadSurfaces",B.subjectReadSurfaces),n=new Set(t.map(d=>String(d.code))),i=new Map(e.data.resources.map((d,s)=>{let a=`/config/data/resources/${s}`,c=Ye(d,a,e.appCode);return[String(c.code),{resource:c,fields:new Map(D(N(c.schema,`${a}/schema`).fields,`${a}/schema/fields`,500).map(f=>{let u=N(f,`${a}/schema/fields`);return[String(u.code),u]}))}]})),r=new Set;return te(o.map((d,s)=>{let a=`/config/data/subjectReadSurfaces/${s}`,c=N(d,a);C(c,["code","name","capability","subject","relations"],a);let f=v(c.code,`${a}/code`);r.has(f)&&m("NATIVE_SUBJECT_READ_SURFACE_CODE_DUPLICATE",`${a}/code`),r.add(f);let u=me(c.capability,`${a}/capability`,e.appCode);n.has(u)||m("NATIVE_SUBJECT_READ_SURFACE_CAPABILITY_NOT_DECLARED",`${a}/capability`);let p=N(c.subject,`${a}/subject`);C(p,["resourceCode","fields"],`${a}/subject`);let _=H(p.resourceCode,`${a}/subject/resourceCode`),E=i.get(_);E||m("NATIVE_SUBJECT_READ_SURFACE_RESOURCE_NOT_DECLARED",`${a}/subject/resourceCode`);let A=V(p.fields,`${a}/subject/fields`,100).map((T,l)=>G(T,`${a}/subject/fields/${l}`));A.length||m("NATIVE_SUBJECT_READ_SURFACE_FIELDS_REQUIRED",`${a}/subject/fields`);for(let[T,l]of A.entries()){let y=E.fields.get(l);(!y||y.type==="subtable")&&m("NATIVE_SUBJECT_READ_SURFACE_FIELD_INVALID",`${a}/subject/fields/${T}`)}let O=D(c.relations,`${a}/relations`,8);O.length||m("NATIVE_SUBJECT_READ_SURFACE_RELATIONS_REQUIRED",`${a}/relations`);let b=new Set,g=0,I=te(O.map((T,l)=>{let y=`${a}/relations/${l}`,R=N(T,y);C(R,["code","resourceCode","foreignKeyField","fields","limit"],y,["order"]);let h=v(R.code,`${y}/code`);b.has(h)&&m("NATIVE_SUBJECT_READ_SURFACE_RELATION_CODE_DUPLICATE",`${y}/code`),b.add(h);let $=H(R.resourceCode,`${y}/resourceCode`),w=i.get($);w||m("NATIVE_SUBJECT_READ_SURFACE_RESOURCE_NOT_DECLARED",`${y}/resourceCode`);let j=G(R.foreignKeyField,`${y}/foreignKeyField`),L=w.fields.get(j),Q=N(L?.source||{},`${y}/foreignKeyField/source`);(!L||!["uuid","resource-ref.single"].includes(String(L.type))||L.type==="resource-ref.single"&&(Q.kind!=="resource"||Q.resourceCode!==_))&&m("NATIVE_SUBJECT_READ_SURFACE_RELATION_INVALID",`${y}/foreignKeyField`);let ee=V(R.fields,`${y}/fields`,100).map((oe,P)=>G(oe,`${y}/fields/${P}`));ee.length||m("NATIVE_SUBJECT_READ_SURFACE_FIELDS_REQUIRED",`${y}/fields`);for(let[oe,P]of ee.entries()){let U=w.fields.get(P);(!U||U.type==="subtable")&&m("NATIVE_SUBJECT_READ_SURFACE_FIELD_INVALID",`${y}/fields/${oe}`)}let Y=D(R.order||[],`${y}/order`,10).map((oe,P)=>{let U=`${y}/order/${P}`,x=N(oe,U);C(x,["field","direction"],U);let q=G(x.field,`${U}/field`),z=w.fields.get(q);return(!fs.has(q)&&!z||z?.type==="subtable"||z&&!At(z.type))&&m("NATIVE_SUBJECT_READ_SURFACE_ORDER_FIELD_INVALID",`${U}/field`),["asc","desc"].includes(String(x.direction))||m("NATIVE_SUBJECT_READ_SURFACE_ORDER_DIRECTION_INVALID",`${U}/direction`),{field:q,direction:x.direction}}),ge=se(R.limit,`${y}/limit`,1,100);return g+=ge,{code:h,resourceCode:$,foreignKeyField:j,fields:M(ee),...Y.length?{order:Y}:{},limit:ge}}),T=>T.code);return g>400&&m("NATIVE_SUBJECT_READ_SURFACE_ROW_LIMIT_EXCEEDED",`${a}/relations`),{code:f,name:S(c.name,`${a}/name`,255),capability:u,subject:{resourceCode:_,fields:M(A)},relations:I}}),d=>d.code)}function jd(e){let t=e.data.resourceDetailRoutes===void 0?[]:D(e.data.resourceDetailRoutes,"/config/data/resourceDetailRoutes",100),o=new Map(e.data.resources.map((r,d)=>{let s=`/config/data/resources/${d}`,a=Ye(r,s,e.appCode);return[a.code,a]})),n=new Map(bn(e).map(r=>[String(r.code),r])),i=new Map;for(let[r,d]of t.entries()){let s=`/config/data/resourceDetailRoutes/${r}`,a=N(d,s);C(a,["resourceCode","desktop","mobile"],s);let c=H(a.resourceCode,`${s}/resourceCode`);i.has(c)&&m("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_DUPLICATE",`${s}/resourceCode`);let f=o.get(c);f||m("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_RESOURCE_MISSING",`${s}/resourceCode`);let u=v(a.desktop,`${s}/desktop`),p=v(a.mobile,`${s}/mobile`);u===p&&m("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_INVALID",s);let _=String(f.capabilities.read);for(let[E,A]of[["desktop",u],["mobile",p]]){let O=`${s}/${E}`,b=n.get(A);b||m("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_REFERENCE_MISSING",O),b.surface!=="user"&&m("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_SURFACE_INVALID",O);let g=Oe(b.path,`${O}/path`),I=[...g.matchAll(/:([A-Za-z][A-Za-z0-9_]*)/g)],T=E==="mobile"?!g.startsWith("/m/"):g==="/m"||g.startsWith("/m/");(g.includes("*")||g.includes("?")||g.includes("#")||g.split("/").includes("..")||I.length!==1||T)&&m("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_PATH_INVALID",O);let l=Array.isArray(b.access?.allOf)?b.access.allOf:[];b.capability!==_&&!l.includes(_)&&m("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_CAPABILITY_INVALID",O)}i.set(c,{desktop:u,mobile:p})}return i}function ps(e){let t=new Map(e.data.resources.map((d,s)=>{let a=`/config/data/resources/${s}`,c=Ye(d,a,e.appCode);return[c.code,new Map(c.schema.fields.map(f=>[String(f.code),f]))]})),o=new Map(e.data.resources.map((d,s)=>{let a=`/config/data/resources/${s}`,c=Ye(d,a,e.appCode);return[c.code,new Map(c.schema.fields.map(f=>[String(f.code),String(f.type)]))]})),n=new Set(o.keys()),i=new Set(e.workflows.activations.map((d,s)=>Nn(N(d,`/config/workflows/activations/${s}`).workflowCode,`/config/workflows/activations/${s}/workflowCode`))),r=new Map;return te(e.backend.operations.map((d,s)=>{let a=`/config/backend/operations/${s}`,c=N(d,a);C(c,["code","method","path","capability","requestSchema","responseSchema","description","platformAccess","browser","ai"],a,!0);let f=S(c.method,`${a}/method`,16);["GET","POST","PUT","PATCH","DELETE"].includes(f)||m("NATIVE_OPERATION_METHOD_INVALID",`${a}/method`);let u=v(c.code,`${a}/code`);Bd(c.ai,a,u,f,n);let p=Md(c.platformAccess,`${a}/platformAccess`,o,t,i,new Set(e.authz.roles.map(E=>String(E.code))));if(p?.workflowStage){let E=p.workflowStage,A=e.workflows.definitions.find(O=>O.definition.code===E.workflowCode);(!A||A.definition.subject?.resourceCode!==E.resourceCode||E.runningNodeIds.some(O=>!A.definition.nodes[O]))&&m("NATIVE_WORKFLOW_STAGE_NODE_INVALID",`${a}/platformAccess/workflowStage/runningNodeIds`)}if(p?.recordEdit){let E=e.data.resources.find(A=>A.code===p.recordEdit.resourceCode);E?.surface?.mutationOwner!=="action"&&m("NATIVE_RECORD_EDIT_ACTION_OWNER_REQUIRED",`${a}/platformAccess/recordEdit`);for(let A of p.recordEdit.fieldCodes)(!E.fieldPolicies?.[A]?.update?.length||E.surface?.fields?.[A]?.system===!0)&&m("NATIVE_RECORD_EDIT_FIELD_INVALID",`${a}/platformAccess/recordEdit/fieldCodes`)}if(p?.decimalReservation){let E=p.decimalReservation,A=String(E.resourceCode),O=JSON.stringify([E.amountFieldCode,E.currencyFieldCode,E.relationFieldCode,E.parentFieldCode,E.rootFieldCode,E.statusFieldCode,E.parentRelationValue,E.childRelationValue]),b=r.get(A);b&&b!==O&&m("NATIVE_DECIMAL_RESERVATION_MAPPING_CONFLICT",`${a}/platformAccess/decimalReservation`),r.set(A,O)}let _=Wd(c.browser,`${a}/browser`,f,c.requestSchema,c.responseSchema,o,t,e.data.subjectReadSurfaces||[]);return{code:u,method:f,path:Oe(c.path,`${a}/path`),requiredCapability:me(c.capability,`${a}/capability`,e.appCode),requestSchemaDigest:Z(N(c.requestSchema,`${a}/requestSchema`)),responseSchemaDigest:Z(N(c.responseSchema,`${a}/responseSchema`)),...c.description===void 0?{}:{description:Go(c.description,`${a}/description`,2e3)},...p?{platformAccess:p}:{},..._?{browser:_}:{}}}),d=>d.code)}function Wd(e,t,o,n,i,r,d,s){if(e===void 0)return null;let a=N(e,t);C(a,["exposure","behavior","idempotency","subject"],t,["refreshTargets","fileIntent"]),F(a.exposure,"authenticated",`${t}/exposure`);let c=S(a.behavior,`${t}/behavior`,32);["read","controlled"].includes(c)||m("NATIVE_OPERATION_BROWSER_BEHAVIOR_INVALID",`${t}/behavior`);let f=S(a.idempotency,`${t}/idempotency`,32);(!["none","required"].includes(f)||c==="controlled"&&f!=="required"||c==="read"&&f!=="none")&&m("NATIVE_OPERATION_BROWSER_IDEMPOTENCY_INVALID",`${t}/idempotency`);let u=N(a.subject,`${t}/subject`);C(u,["resourceCode","inputField"],`${t}/subject`);let p=H(u.resourceCode,`${t}/subject/resourceCode`);r.has(p)||m("NATIVE_OPERATION_BROWSER_SUBJECT_RESOURCE_NOT_DECLARED",`${t}/subject/resourceCode`);let _=G(u.inputField,`${t}/subject/inputField`),E=N(n,`${t}/requestSchema`),A=N(i,`${t}/responseSchema`);(E.type!=="object"||E.additionalProperties!==!1||A.type!=="object"||A.additionalProperties!==!1)&&m("NATIVE_OPERATION_BROWSER_SCHEMA_ROOT_INVALID",`${t}/requestSchema`);let O=N(E.properties,`${t}/requestSchema/properties`),b=new Set(E.required===void 0?[]:V(E.required,`${t}/requestSchema/required`,200));(!(_ in O)||!b.has(_))&&m("NATIVE_OPERATION_BROWSER_SUBJECT_INPUT_INVALID",`${t}/subject/inputField`);let g=N(O[_],`${t}/requestSchema/properties/${_}`);(g.type!=="string"||g.format!=="uuid")&&m("NATIVE_OPERATION_BROWSER_SUBJECT_INPUT_INVALID",`${t}/subject/inputField`);let I=new Map((Array.isArray(s)?s:[]).map((h,$)=>{let w=N(h,`/config/data/subjectReadSurfaces/${$}`);return[String(w.code),String(N(w.subject,`/config/data/subjectReadSurfaces/${$}/subject`).resourceCode)]})),T=a.refreshTargets===void 0?[]:D(a.refreshTargets,`${t}/refreshTargets`,16),l=new Set,y=te(T.map((h,$)=>{let w=`${t}/refreshTargets/${$}`,j=N(h,w);C(j,["kind","code"],w),F(j.kind,"subject-surface",`${w}/kind`);let L=v(j.code,`${w}/code`);return(l.has(L)||!I.has(L)||I.get(L)!==p)&&m("NATIVE_OPERATION_BROWSER_REFRESH_TARGET_INVALID",`${w}/code`),l.add(L),{kind:"subject-surface",code:L}}),h=>`${h.kind}:${h.code}`),R=Ud(a.fileIntent,`${t}/fileIntent`,o,c,f,p,O,b,d);return{exposure:"authenticated",behavior:c,idempotency:f,subject:{resourceCode:p,inputField:_},...y.length?{refreshTargets:y}:{},...R?{fileIntent:R}:{}}}function Ud(e,t,o,n,i,r,d,s,a){if(e===void 0)return null;let c=N(e,t);C(c,["recordResourceCode","recordIdInputField","relationField","fileNameField","contentTypeField","sizeField","purposes","maxTtlSeconds","maxBytes"],t),(o!=="GET"||n!=="read"||i!=="none")&&m("NATIVE_OPERATION_FILE_INTENT_BEHAVIOR_INVALID",t);let f=H(c.recordResourceCode,`${t}/recordResourceCode`),u=a.get(f);u||m("NATIVE_OPERATION_FILE_INTENT_RESOURCE_NOT_DECLARED",`${t}/recordResourceCode`);let p=G(c.recordIdInputField,`${t}/recordIdInputField`),_=N(d[p],`${t}/recordIdInputField`);(!s.has(p)||_.type!=="string"||_.format!=="uuid")&&m("NATIVE_OPERATION_FILE_INTENT_RECORD_INPUT_INVALID",`${t}/recordIdInputField`);let E=G(c.relationField,`${t}/relationField`),A=u.get(E);(!A||!["uuid","resource-ref.single"].includes(String(A.type))||String(A.type)==="resource-ref.single"&&(String(N(A.source,`${t}/relationField`).kind||"")!=="resource"||String(N(A.source,`${t}/relationField`).resourceCode||"")!==r))&&m("NATIVE_OPERATION_FILE_INTENT_RELATION_INVALID",`${t}/relationField`);let O=[["fileNameField",["text.short","text.long"]],["contentTypeField",["text.short","text.long"]],["sizeField",["number.integer"]]],b={};for(let[l,y]of O){let R=G(c[l],`${t}/${l}`);y.includes(String(u.get(R)?.type))||m("NATIVE_OPERATION_FILE_INTENT_METADATA_INVALID",`${t}/${l}`),b[l]=R}let g=te(V(c.purposes,`${t}/purposes`,2),l=>l);(!g.length||g.some(l=>!["preview","download"].includes(l)))&&m("NATIVE_OPERATION_FILE_INTENT_PURPOSE_INVALID",`${t}/purposes`);let I=Number(c.maxTtlSeconds);(!Number.isSafeInteger(I)||I<1||I>300)&&m("NATIVE_OPERATION_FILE_INTENT_TTL_INVALID",`${t}/maxTtlSeconds`);let T=Number(c.maxBytes);return(!Number.isSafeInteger(T)||T<1||T>104857600)&&m("NATIVE_OPERATION_FILE_INTENT_SIZE_INVALID",`${t}/maxBytes`),{recordResourceCode:f,recordIdInputField:p,relationField:E,fileNameField:b.fileNameField,contentTypeField:b.contentTypeField,sizeField:b.sizeField,purposes:g,maxTtlSeconds:I,maxBytes:T}}function Md(e,t,o,n,i,r){if(e===void 0)return null;let d=N(e,t);C(d,["directory","selectedDepartments","managedFiles","managedFileCopies","notification","workflow","roleAssertions","decimalReservation","dataCommands","recordEdit","ownedSubject","workflowStage"],t,!0),Object.keys(d).length===0&&m("NATIVE_OPERATION_PLATFORM_ACCESS_EMPTY",t);let s={};if(d.dataCommands!==void 0){let a=N(d.dataCommands,`${t}/dataCommands`);C(a,["mode"],`${t}/dataCommands`),F(a.mode,"recoverable-native",`${t}/dataCommands/mode`),s.dataCommands={mode:"recoverable-native"}}if(d.workflowStage!==void 0){try{Ki(d.workflowStage)}catch{m("NATIVE_WORKFLOW_STAGE_DECLARATION_INVALID",`${t}/workflowStage`)}let a=d.workflowStage;(!s.dataCommands||d.decimalReservation!==void 0||!o.has(a.resourceCode)||!i.has(a.workflowCode)||!d.workflow?.codes?.includes(a.workflowCode))&&m("NATIVE_WORKFLOW_STAGE_DECLARATION_INVALID",`${t}/workflowStage`),s.workflowStage={...a,runningNodeIds:M([...a.runningNodeIds]),allowedStatuses:M([...a.allowedStatuses])}}if(d.recordEdit!==void 0){let a=`${t}/recordEdit`,c=N(d.recordEdit,a);C(c,["resourceCode","fieldCodes"],a);let f=H(c.resourceCode,`${a}/resourceCode`),u=n.get(f),p=V(c.fieldCodes,`${a}/fieldCodes`,200);(!u||!p.length||!s.dataCommands)&&m("NATIVE_RECORD_EDIT_DECLARATION_INVALID",a);for(let _ of p){let E=u.get(_);(!E||E.type==="serial-number"||E.type==="subtable")&&m("NATIVE_RECORD_EDIT_FIELD_INVALID",`${a}/fieldCodes`)}s.recordEdit={resourceCode:f,fieldCodes:M(p)}}if(d.roleAssertions!==void 0){let a=N(d.roleAssertions,`${t}/roleAssertions`);C(a,["roleCodes","actorAuthority"],`${t}/roleAssertions`,!0),a.actorAuthority!==void 0&&F(a.actorAuthority,!0,`${t}/roleAssertions/actorAuthority`);let c=V(a.roleCodes,`${t}/roleAssertions/roleCodes`,20);c.length||m("NATIVE_OPERATION_ROLE_ASSERTIONS_REQUIRED",`${t}/roleAssertions/roleCodes`),c.forEach((f,u)=>{r.has(f)||m("NATIVE_ROLE_REFERENCE_MISSING",`${t}/roleAssertions/roleCodes/${u}`)}),s.roleAssertions={roleCodes:M(c),...a.actorAuthority===!0?{actorAuthority:!0}:{}}}if(d.directory!==void 0){let a=N(d.directory,`${t}/directory`);C(a,["mode","fields"],`${t}/directory`),["current-initiator","selected-user"].includes(String(a.mode))||m("NATIVE_OPERATION_DIRECTORY_MODE_INVALID",`${t}/directory/mode`);let c=new Set(["displayName","employeeNumber","primaryDepartment","departments",...a.mode==="current-initiator"?["phone"]:[]]),f=V(a.fields,`${t}/directory/fields`,c.size);(!f.length||f.some(u=>!c.has(u)))&&m("NATIVE_OPERATION_DIRECTORY_FIELDS_INVALID",`${t}/directory/fields`),s.directory={mode:String(a.mode),fields:M(f)}}if(d.selectedDepartments!==void 0){let a=`${t}/selectedDepartments`,c=N(d.selectedDepartments,a);C(c,["fields","maxIds"],a);let f=V(c.fields,`${a}/fields`,4);(!f.includes("name")||f.some(u=>!["name","path","parent","fullPath"].includes(u))||!Number.isSafeInteger(c.maxIds)||c.maxIds<1||c.maxIds>50)&&m("NATIVE_OPERATION_SELECTED_DEPARTMENTS_INVALID",a),s.selectedDepartments={fields:M(f),maxIds:c.maxIds}}if(d.managedFiles!==void 0){let a=D(d.managedFiles,`${t}/managedFiles`,16);a.length||m("NATIVE_OPERATION_MANAGED_FILES_REQUIRED",`${t}/managedFiles`);let c=new Set;s.managedFiles=te(a.map((f,u)=>{let p=`${t}/managedFiles/${u}`,_=N(f,p);C(_,["resourceCode","fieldCodes","intents"],p);let E=H(_.resourceCode,`${p}/resourceCode`);(c.has(E)||!o.has(E))&&m("NATIVE_OPERATION_MANAGED_FILE_RESOURCE_INVALID",`${p}/resourceCode`),c.add(E);let A=V(_.fieldCodes,`${p}/fieldCodes`,16);(!A.length||A.some(b=>!["file","image","signature","text.rich"].includes(String(o.get(E)?.get(b)||""))))&&m("NATIVE_OPERATION_MANAGED_FILE_FIELD_INVALID",`${p}/fieldCodes`);let O=V(_.intents,`${p}/intents`,2);return(!O.length||O.some(b=>!["create","update"].includes(b)))&&m("NATIVE_OPERATION_MANAGED_FILE_INTENT_INVALID",`${p}/intents`),{resourceCode:E,fieldCodes:M(A),intents:M(O)}}),f=>f.resourceCode)}if(d.managedFileCopies!==void 0){let a=D(d.managedFileCopies,`${t}/managedFileCopies`,16);a.length||m("NATIVE_OPERATION_MANAGED_FILE_COPIES_REQUIRED",`${t}/managedFileCopies`);let c=new Set;s.managedFileCopies=te(a.map((f,u)=>{let p=`${t}/managedFileCopies/${u}`,_=N(f,p);C(_,["mode","sourceResourceCode","sourceFieldCodes","targetResourceCode","targetFieldCodes"],p),F(_.mode,"copy",`${p}/mode`);let E=H(_.sourceResourceCode,`${p}/sourceResourceCode`),A=H(_.targetResourceCode,`${p}/targetResourceCode`),O=o.get(E),b=o.get(A);(!O||!b)&&m("NATIVE_OPERATION_MANAGED_FILE_COPY_RESOURCE_INVALID",p);let g=V(_.sourceFieldCodes,`${p}/sourceFieldCodes`,16),I=V(_.targetFieldCodes,`${p}/targetFieldCodes`,16);(!g.length||g.length!==I.length)&&m("NATIVE_OPERATION_MANAGED_FILE_COPY_FIELDS_INVALID",p),g.forEach((l,y)=>{let R=O.get(l),h=b.get(I[y]);(!["file","image","text.rich"].includes(String(R))||R!==h)&&m("NATIVE_OPERATION_MANAGED_FILE_COPY_FIELD_INVALID",`${p}/sourceFieldCodes/${y}`)});let T=`${E}:${g.join(",")}=>${A}:${I.join(",")}`;return c.has(T)&&m("NATIVE_OPERATION_MANAGED_FILE_COPY_DUPLICATE",p),c.add(T),{mode:"copy",sourceResourceCode:E,sourceFieldCodes:M(g),targetResourceCode:A,targetFieldCodes:M(I)}}),f=>`${f.sourceResourceCode}:${f.sourceFieldCodes.join(",")}=>${f.targetResourceCode}:${f.targetFieldCodes.join(",")}`)}if(d.notification!==void 0){let a=N(d.notification,`${t}/notification`);C(a,["mode"],`${t}/notification`),a.mode!=="business-standard"&&m("NATIVE_OPERATION_NOTIFICATION_MODE_INVALID",`${t}/notification/mode`),s.notification={mode:"business-standard"}}if(d.workflow!==void 0){let a=N(d.workflow,`${t}/workflow`);C(a,["codes"],`${t}/workflow`,["businessCommands"]);let c=V(a.codes,`${t}/workflow/codes`,16);(!c.length||c.some(u=>!i.has(u)))&&m("NATIVE_OPERATION_WORKFLOW_CODE_INVALID",`${t}/workflow/codes`);let f=a.businessCommands===void 0?void 0:V(a.businessCommands,`${t}/workflow/businessCommands`,4);f&&(!f.length||f.some(u=>!["approve","reject","withdraw","resubmit"].includes(u)))&&m("NATIVE_OPERATION_WORKFLOW_BUSINESS_COMMAND_INVALID",`${t}/workflow/businessCommands`),s.workflow={codes:M(c),...f?{businessCommands:M(f)}:{}}}if(d.ownedSubject!==void 0){let a=`${t}/ownedSubject`,c=d.ownedSubject;try{pn(c)}catch{m("NATIVE_WORKFLOW_OWNED_SUBJECT_INVALID",a)}(!s.workflow||d.decimalReservation!==void 0)&&m("NATIVE_WORKFLOW_OWNED_SUBJECT_INVALID",a);try{Mr(c,n,s.managedFiles||[])}catch(f){m(`NATIVE_${f.message}`,a)}s.ownedSubject={mode:"create",resourceCode:c.resourceCode,subtables:te(c.subtables.map(f=>({fieldCode:f.fieldCode,fieldCodes:M([...f.fieldCodes])})),f=>f.fieldCode)}}if(d.decimalReservation!==void 0){let a=`${t}/decimalReservation`,c=N(d.decimalReservation,a);C(c,["mode","resourceCode","amountFieldCode","currencyFieldCode","relationFieldCode","parentFieldCode","rootFieldCode","statusFieldCode","parentRelationValue","childRelationValue","eligibleParentStatuses","eligibleChildStatuses"],a);let f=S(c.mode,`${a}/mode`,16);["reserve","commit","release"].includes(f)||m("NATIVE_DECIMAL_RESERVATION_MODE_INVALID",`${a}/mode`);let u=H(c.resourceCode,`${a}/resourceCode`),p=n.get(u);p||m("NATIVE_DECIMAL_RESERVATION_RESOURCE_MISSING",`${a}/resourceCode`);let E=Object.fromEntries(["amountFieldCode","currencyFieldCode","relationFieldCode","parentFieldCode","rootFieldCode","statusFieldCode"].map(l=>[l,G(c[l],`${a}/${l}`)])),A=l=>p.get(E[l]),O=l=>new Set((A(l)?.options||[]).map(y=>String(y.value))),b=v(c.parentRelationValue,`${a}/parentRelationValue`),g=v(c.childRelationValue,`${a}/childRelationValue`),I=V(c.eligibleParentStatuses,`${a}/eligibleParentStatuses`,16),T=V(c.eligibleChildStatuses,`${a}/eligibleChildStatuses`,16);(A("amountFieldCode")?.type!=="number.decimal"||A("amountFieldCode")?.exactDecimal!==!0||A("amountFieldCode")?.precision!==18||A("amountFieldCode")?.scale!==2||A("currencyFieldCode")?.type!=="option.single"||A("relationFieldCode")?.type!=="option.single"||A("parentFieldCode")?.type!=="resource-ref.single"||A("parentFieldCode")?.source?.resourceCode!==u||A("rootFieldCode")?.type!=="uuid"||A("statusFieldCode")?.type!=="option.single"||b===g||!O("relationFieldCode").has(b)||!O("relationFieldCode").has(g)||!I.length||!T.length||I.some(l=>!O("statusFieldCode").has(l))||T.some(l=>!O("statusFieldCode").has(l)))&&m("NATIVE_DECIMAL_RESERVATION_FIELD_INVALID",a),s.decimalReservation={mode:f,resourceCode:u,...E,parentRelationValue:b,childRelationValue:g,eligibleParentStatuses:M(I),eligibleChildStatuses:M(T)}}return s}function Bd(e,t,o,n,i){if(e===void 0)return;let r=`${t}/ai`,d=N(e,r);ld.test(o)||m("NATIVE_OPERATION_AI_CODE_INVALID",`${t}/code`),C(d,["name","description","risk","resources","sideEffects","concurrency","timeoutMs"],r,!0),S(d.name,`${r}/name`,Lo),S(d.description,`${r}/description`,Lo);let s=S(d.risk,`${r}/risk`,16);["read","write","destructive","external"].includes(s)||m("NATIVE_OPERATION_AI_RISK_INVALID",`${r}/risk`),s==="read"!=(n==="GET")&&m("NATIVE_OPERATION_AI_METHOD_RISK_MISMATCH",`${r}/risk`),n==="DELETE"&&!["destructive","external"].includes(s)&&m("NATIVE_OPERATION_AI_METHOD_RISK_MISMATCH",`${r}/risk`);let a=V(d.resources,`${r}/resources`,16);a.length===0&&m("NATIVE_OPERATION_AI_RESOURCE_REQUIRED",`${r}/resources`),a.forEach((f,u)=>{let p=H(f,`${r}/resources/${u}`);i.has(p)||m("NATIVE_OPERATION_AI_RESOURCE_MISSING",`${r}/resources/${u}`)});let c=V(d.sideEffects,`${r}/sideEffects`,20);(s==="read"&&c.length!==0||s!=="read"&&c.length===0)&&m("NATIVE_OPERATION_AI_SIDE_EFFECT_INVALID",`${r}/sideEffects`),d.concurrency!==void 0&&!["none","revision"].includes(S(d.concurrency,`${r}/concurrency`,16))&&m("NATIVE_OPERATION_AI_CONCURRENCY_INVALID",`${r}/concurrency`),d.timeoutMs!==void 0&&se(d.timeoutMs,`${r}/timeoutMs`,100,3e4)}function An(e){return(e.replace(/\/{2,}/g,"/").replace(/\/$/,"")||"/").split("/").map(o=>o.startsWith(":")?":":o.includes("*")?"*":o).join("/")}function Kd(e,t){let o=N(e,t),n=S(o.type,`${t}/type`,32),i=["code","type","label","presentation","required"],r=n==="sso"?[...i,"provider"]:n==="dingtalk"?[...i,"flow"]:i;C(o,r,t);let d=v(o.code,`${t}/code`),s=S(o.label,`${t}/label`,255),a=S(o.presentation,`${t}/presentation`,16);["primary","secondary"].includes(a)||m("NATIVE_APPLICATION_AUTH_METHOD_PRESENTATION_INVALID",`${t}/presentation`);let c=ft(o.required,`${t}/required`);return["sso","password","dingtalk"].includes(n)||m("NATIVE_APPLICATION_AUTH_METHOD_TYPE_INVALID",`${t}/type`),n==="sso"&&o.provider!=="tenant-default"&&m("NATIVE_APPLICATION_AUTH_SSO_PROVIDER_INVALID",`${t}/provider`),n==="dingtalk"&&!["auto","jsapi","oauth"].includes(S(o.flow,`${t}/flow`,16))&&m("NATIVE_APPLICATION_AUTH_DINGTALK_FLOW_INVALID",`${t}/flow`),{code:d,type:n,label:s,presentation:a,required:c,...n==="sso"?{provider:"tenant-default"}:{},...n==="dingtalk"?{flow:o.flow}:{}}}function Xr(e,t,o){let n=N(e,o);C(n,["routeCode","path","defaultRouteCode"],o);let i=v(n.routeCode,`${o}/routeCode`),r=Oe(n.path,`${o}/path`),d=t==="desktop"?"/login":"/m/login";return(r!==d||/[:*?#\\]/.test(r))&&m("NATIVE_APPLICATION_AUTH_SURFACE_PATH_INVALID",`${o}/path`,{device:t,expectedPath:d}),{routeCode:i,path:r,defaultRouteCode:v(n.defaultRouteCode,`${o}/defaultRouteCode`)}}function ms(e,t,o,n){if(e===null)return;let i=N(e,n);C(i,["accountMode","registration","methods","surfaces"],n),F(i.accountMode,"existing-platform-users-only",`${n}/accountMode`);let r=N(i.registration,`${n}/registration`);C(r,["mode"],`${n}/registration`),F(r.mode,"reject",`${n}/registration/mode`);let d=D(i.methods,`${n}/methods`,8);d.length===0&&m("NATIVE_APPLICATION_AUTH_METHOD_REQUIRED",`${n}/methods`);let s=d.map((b,g)=>Kd(b,`${n}/methods/${g}`)),a=new Set,c=new Set;for(let[b,g]of s.entries())a.has(g.code)&&m("NATIVE_APPLICATION_AUTH_METHOD_CODE_DUPLICATE",`${n}/methods/${b}/code`),c.has(g.type)&&m("NATIVE_APPLICATION_AUTH_METHOD_TYPE_DUPLICATE",`${n}/methods/${b}/type`),a.add(g.code),c.add(g.type);s.filter(b=>b.presentation==="primary").length!==1&&m("NATIVE_APPLICATION_AUTH_PRIMARY_METHOD_INVALID",`${n}/methods`);let f=N(i.surfaces,`${n}/surfaces`);C(f,["desktop","mobile"],`${n}/surfaces`);let u=Xr(f.desktop,"desktop",`${n}/surfaces/desktop`),p=Xr(f.mobile,"mobile",`${n}/surfaces/mobile`);u.routeCode===p.routeCode&&m("NATIVE_APPLICATION_AUTH_SURFACE_CODE_DUPLICATE",`${n}/surfaces/mobile/routeCode`);let _=D(t,"/config/frontend/routes",B.routes),E=new Map;for(let[b,g]of _.entries()){let I=N(g,`/config/frontend/routes/${b}`);E.set(String(I.code||""),I)}let A=new Set((Array.isArray(o.data?.resources)?o.data.resources:[]).map(b=>String(b.code||"")).filter(b=>/^[a-z][a-z0-9-]{0,62}$/.test(b)));for(let[b,g]of[["desktop",u],["mobile",p]]){E.has(g.routeCode)&&m("NATIVE_APPLICATION_AUTH_SURFACE_CODE_CONFLICT",`${n}/surfaces/${b}/routeCode`);let I=/^user\.([a-z][a-z0-9-]{0,62})\.(records|submit)$/.exec(String(g.defaultRouteCode||"")),T=E.get(g.defaultRouteCode),l=String(T?.path||"");if(I&&A.has(I[1])){let R=I[2]==="records"?`/my/${I[1]}`:`/my/${I[1]}/submit`;T={surface:"user",path:b==="mobile"?`/m${R}`:R},l=String(T.path)}let y=b==="desktop"?l==="/m"||l.startsWith("/m/"):!(l==="/m"||l.startsWith("/m/"));(!T||T.surface!=="user"||/[:*]/.test(l)||y)&&m("NATIVE_APPLICATION_AUTH_DEFAULT_ROUTE_INVALID",`${n}/surfaces/${b}/defaultRouteCode`)}let O=_s(o).filter(b=>!b.owner.startsWith("authentication:"));for(let[b,g]of[["desktop",u],["mobile",p]]){let I=O.find(T=>An(T.path)===An(g.path));I&&m("NATIVE_APPLICATION_AUTH_SURFACE_PATH_CONFLICT",`${n}/surfaces/${b}/path`,{owner:I.owner})}}function Gd(e,t){if(e===null)return;let o={data:{resources:[]},workflows:{definitions:[]},frontend:{routes:[{code:"auth-desktop-default",path:"/auth-desktop-default",surface:"user"},{code:"auth-mobile-default",path:"/m/auth-mobile-default",surface:"user"}],user:{applicationTodoCenter:!1},admin:{navigation:[]},authentication:e}},n=N(e,t),i=N(n.surfaces,`${t}/surfaces`),r={...n,surfaces:{...i,desktop:{...N(i.desktop,`${t}/surfaces/desktop`),defaultRouteCode:"auth-desktop-default"},mobile:{...N(i.mobile,`${t}/surfaces/mobile`),defaultRouteCode:"auth-mobile-default"}}};ms(r,o.frontend.routes,{...o,frontend:{...o.frontend,authentication:r}},t)}function qd(e){let t=e.frontend.authentication;return t===null?null:{accountMode:t.accountMode,registration:{mode:t.registration.mode},methods:t.methods.map(o=>({...o})),surfaces:{desktop:{...t.surfaces.desktop},mobile:{...t.surfaces.mobile}}}}var zd=new Set(["draft.read","draft.update","validate","create","own.list","own.read","public.list","public.read"]);function Jd(e,t,o){let n=N(e,o);C(n,["policies"],o);let i=D(n.policies,`${o}/policies`,16);i.length<1&&m("NATIVE_PUBLIC_POLICY_REQUIRED",o);let r=new Map(t.frontend.routes.map(c=>[c.code,c])),d=new Map(t.data.resources.map(c=>[c.code,c])),s=new Set,a=new Set(i.map(c=>String(c?.code||"")));i.forEach((c,f)=>{let u=`${o}/policies/${f}`,p=N(c,u);C(p,["code","routeCode","mode","resourceCode","operations","fields"],u,["requiredFields","ownRecordFields","publicRecordFields","publicFilters","serverGeneratedFields","schedule","publicSubtableFields","draft","validations"]);let _=v(p.code,`${u}/code`);s.has(_)&&m("NATIVE_PUBLIC_POLICY_DUPLICATE",`${u}/code`);let E=v(p.routeCode,`${u}/routeCode`),A=r.get(E);(!A||A.surface!=="user"||A.capability!==void 0||A.access!==void 0||/[:*]/.test(String(A.path)))&&m("NATIVE_PUBLIC_ROUTE_INVALID",`${u}/routeCode`),F(p.mode,"anonymous",`${u}/mode`);let O=H(p.resourceCode,`${u}/resourceCode`),b=d.get(O);b||m("NATIVE_PUBLIC_RESOURCE_MISSING",`${u}/resourceCode`);let g=new Map(b.schema.fields.map(P=>[String(P.code),String(P.type)])),I=V(p.operations,`${u}/operations`,8);(I.length<1||I.some(P=>!zd.has(P)))&&m("NATIVE_PUBLIC_OPERATION_INVALID",`${u}/operations`),I.includes("draft.read")!==I.includes("draft.update")&&m("NATIVE_PUBLIC_DRAFT_OPERATION_INCOMPLETE",`${u}/operations`);let T=V(p.fields,`${u}/fields`,64);(T.length<1||T.some(P=>!g.has(P)))&&m("NATIVE_PUBLIC_FIELD_INVALID",`${u}/fields`);for(let P of["requiredFields","ownRecordFields","publicRecordFields"]){if(!Object.prototype.hasOwnProperty.call(p,P))continue;V(p[P],`${u}/${P}`,64).some(x=>!T.includes(x))&&m("NATIVE_PUBLIC_FIELD_SCOPE_INVALID",`${u}/${P}`)}let l=Object.prototype.hasOwnProperty.call(p,"serverGeneratedFields")?D(p.serverGeneratedFields,`${u}/serverGeneratedFields`,16):[],y=new Set;l.forEach((P,U)=>{let x=`${u}/serverGeneratedFields/${U}`,q=N(P,x);C(q,["field","kind"],x);let z=G(q.field,`${x}/field`);(y.has(z)||!g.has(z)||T.includes(z)||g.get(z)!=="text.short"&&g.get(z)!=="text.long")&&m("NATIVE_PUBLIC_SERVER_GENERATED_FIELD_INVALID",`${x}/field`),F(q.kind,"random-token",`${x}/kind`),y.add(z)});let R=Object.prototype.hasOwnProperty.call(p,"schedule")?N(p.schedule,`${u}/schedule`):null;if(R){let P=["campusPolicyCode","rulePolicyCode","campusField","ruleCampusField","ruleWeekdaysField","ruleOpenAtField","ruleCloseAtField","ruleSlotMinutesField","ruleAdvanceHoursField","ruleAdvanceDaysField","campusEnabledField","ruleEnabledField","dateField","timeField"];C(R,P,`${u}/schedule`);for(let U of["campusPolicyCode","rulePolicyCode"])v(R[U],`${u}/schedule/${U}`);for(let U of P.filter(x=>!["campusPolicyCode","rulePolicyCode"].includes(x)))G(R[U],`${u}/schedule/${U}`);for(let U of[R.campusField,R.dateField,R.timeField])T.includes(String(U))||m("NATIVE_PUBLIC_SCHEDULE_FIELD_INVALID",`${u}/schedule`);(!a.has(String(R.campusPolicyCode))||!a.has(String(R.rulePolicyCode)))&&m("NATIVE_PUBLIC_SCHEDULE_POLICY_INVALID",`${u}/schedule`)}let h=Object.prototype.hasOwnProperty.call(p,"publicFilters")?D(p.publicFilters,`${u}/publicFilters`,16):[],$=new Set;h.forEach((P,U)=>{let x=`${u}/publicFilters/${U}`,q=N(P,x);C(q,["field","operator","value"],x);let z=G(q.field,`${x}/field`);$.has(z)&&m("NATIVE_PUBLIC_FILTER_DUPLICATE",`${x}/field`),T.includes(z)||m("NATIVE_PUBLIC_FILTER_FIELD_INVALID",`${x}/field`),F(q.operator,"eq",`${x}/operator`),["boolean","text.short","text.long","number.integer","number.decimal","date","time"].includes(g.get(z)||"")||m("NATIVE_PUBLIC_FILTER_FIELD_INVALID",`${x}/field`),q.value!==null&&typeof q.value!="string"&&typeof q.value!="number"&&typeof q.value!="boolean"&&m("NATIVE_PUBLIC_FILTER_VALUE_INVALID",`${x}/value`),$.add(z)});let w=Object.prototype.hasOwnProperty.call(p,"publicSubtableFields")?N(p.publicSubtableFields,`${u}/publicSubtableFields`):null;if(w){Object.keys(w).length>64&&m("NATIVE_PUBLIC_SUBTABLE_FIELDS_INVALID",`${u}/publicSubtableFields`);for(let[P,U]of Object.entries(w)){let x=b.schema.fields.find(J=>String(J.code)===P),q=String(x?.subtable?.resourceCode||""),z=d.get(q),Ae=new Map((z?.schema?.fields||[]).map(J=>[String(J.code),String(J.type)])),Ne=V(U,`${u}/publicSubtableFields/${P}`,64);(!T.includes(P)||g.get(P)!=="subtable"||!z||Ne.length<1||Ne.some(J=>!Ae.has(J))||Ne.some(J=>Ae.get(J)==="subtable")||Ne.some(J=>Ae.get(J)==="signature"))&&m("NATIVE_PUBLIC_SUBTABLE_FIELDS_INVALID",`${u}/publicSubtableFields/${P}`)}}if(I.some(P=>P.startsWith("public."))){Object.prototype.hasOwnProperty.call(p,"publicRecordFields")||m("NATIVE_PUBLIC_RECORD_FIELDS_REQUIRED",`${u}/publicRecordFields`);let P=V(p.publicRecordFields,`${u}/publicRecordFields`,64);(P.length<1||P.some(U=>!T.includes(U))||P.some(U=>g.get(U)==="signature"||g.get(U)==="subtable"&&!w?.[U]))&&m("NATIVE_PUBLIC_RECORD_FIELDS_INVALID",`${u}/publicRecordFields`)}let j=Object.prototype.hasOwnProperty.call(p,"requiredFields")?V(p.requiredFields,`${u}/requiredFields`,64):[],L=b.surface||{},Q=L.fields||{},ee=String(L.mutationOwner||"native")==="native"&&L.generated?.create!==!1,Y=b.schema.fields.filter(P=>Bt(P,Q[P.code])).map(P=>String(P.code));if(I.includes("create")&&!ee&&m("NATIVE_PUBLIC_CREATE_FIELDS_INCOMPLETE",`${u}/fields`),I.includes("create")&&!Object.prototype.hasOwnProperty.call(p,"draft")&&m("NATIVE_PUBLIC_DRAFT_REQUIRED",`${u}/draft`),I.includes("create"))for(let P of Y){let U=T.includes(P)?j.includes(P)?null:"requiredFields":"fields";U&&m("NATIVE_PUBLIC_CREATE_FIELDS_INCOMPLETE",`${u}/${U}`,{resourceCode:H,fieldCode:P})}if(Object.prototype.hasOwnProperty.call(p,"draft")){let P=N(p.draft,`${u}/draft`);C(P,["enabled","inactivityTtlSeconds","maxBytes"],`${u}/draft`),F(P.enabled,!0,`${u}/draft/enabled`),se(P.inactivityTtlSeconds,`${u}/draft/inactivityTtlSeconds`,3600,7776e3),se(P.maxBytes,`${u}/draft/maxBytes`,4096,262144)}else I.includes("draft.read")&&m("NATIVE_PUBLIC_DRAFT_REQUIRED",`${u}/draft`);let ge=Object.prototype.hasOwnProperty.call(p,"validations")?D(p.validations,`${u}/validations`,16):[],oe=new Set;ge.forEach((P,U)=>{let x=`${u}/validations/${U}`,q=N(P,x);C(q,["code","kind","fields","result"],x);let z=v(q.code,`${x}/code`);oe.has(z)&&m("NATIVE_PUBLIC_VALIDATION_DUPLICATE",`${x}/code`),F(q.kind,"duplicate",`${x}/kind`),F(q.result,"availability",`${x}/result`);let Ae=V(q.fields,`${x}/fields`,8);(Ae.length<1||Ae.some(Ne=>!T.includes(Ne))||Ae.some(Ne=>["file","subtable"].includes(g.get(Ne)||"")))&&m("NATIVE_PUBLIC_VALIDATION_FIELD_INVALID",`${x}/fields`),oe.add(z)}),s.add(_)})}function Hd(e,t){let o=N(e,t);C(o,["policies"],t),D(o.policies,`${t}/policies`,16).length<1&&m("NATIVE_PUBLIC_POLICY_REQUIRED",t)}function Yd(e){return{policies:te(e.frontend.publicAccess.policies.map(t=>({code:t.code,routeCode:t.routeCode,mode:t.mode,resourceCode:t.resourceCode,operations:M(t.operations),fields:M(t.fields),...t.requiredFields?{requiredFields:M(t.requiredFields)}:{},...t.ownRecordFields?{ownRecordFields:M(t.ownRecordFields)}:{},...t.publicRecordFields?{publicRecordFields:M(t.publicRecordFields)}:{},...t.publicFilters?{publicFilters:t.publicFilters.map(o=>({field:o.field,operator:o.operator,value:o.value})).sort((o,n)=>Ie(o.field,n.field))}:{},...t.publicSubtableFields?{publicSubtableFields:Object.fromEntries(Object.entries(t.publicSubtableFields).sort(([o],[n])=>o.localeCompare(n)).map(([o,n])=>[o,M(Array.isArray(n)?n.map(String):[])]))}:{},...t.serverGeneratedFields?{serverGeneratedFields:t.serverGeneratedFields.map(o=>({field:o.field,kind:o.kind})).sort((o,n)=>Ie(o.field,n.field))}:{},...t.schedule?{schedule:{campusPolicyCode:t.schedule.campusPolicyCode,rulePolicyCode:t.schedule.rulePolicyCode,campusField:t.schedule.campusField,ruleCampusField:t.schedule.ruleCampusField,ruleWeekdaysField:t.schedule.ruleWeekdaysField,ruleOpenAtField:t.schedule.ruleOpenAtField,ruleCloseAtField:t.schedule.ruleCloseAtField,ruleSlotMinutesField:t.schedule.ruleSlotMinutesField,ruleAdvanceHoursField:t.schedule.ruleAdvanceHoursField,ruleAdvanceDaysField:t.schedule.ruleAdvanceDaysField,campusEnabledField:t.schedule.campusEnabledField,ruleEnabledField:t.schedule.ruleEnabledField,dateField:t.schedule.dateField,timeField:t.schedule.timeField}}:{},...t.draft?{draft:{...t.draft}}:{},...t.validations?{validations:te(t.validations.map(o=>({code:o.code,kind:o.kind,fields:M(o.fields),result:o.result})),o=>o.code)}:{}})),t=>t.code)}}function _s(e){let t=[{owner:"platform:admin-entry",path:"/"},{owner:"platform:admin-entry",path:"/admin"},{owner:"platform:file-preview",path:"/files/:resourceCode/:fileId/preview"}];e.frontend.authentication&&t.push({owner:"authentication:desktop",path:e.frontend.authentication.surfaces.desktop.path},{owner:"authentication:mobile",path:e.frontend.authentication.surfaces.mobile.path});for(let o of e.data.resources){let n=gs(o),i=`/admin/resources/${o.code}`,r=[["list",i],["detail",`${i}/:id`],["create",`${i}/new`],["update",`${i}/:id/edit`]];for(let[d,s]of r)n[d]&&t.push({owner:`resource:${o.code}:${d}`,path:s},{owner:`resource:${o.code}:${d}:mobile`,path:`/m${s}`})}if(e.frontend.user.applicationTodoCenter===!0&&t.push({owner:"application:todo-center",path:"/todos"},{owner:"application:todo-center:mobile",path:"/m/todos"}),e.workflows.definitions.length>0){t.push({owner:"workflow:work-center",path:"/work-center"},{owner:"workflow:work-center:mobile",path:"/m/work-center"},{owner:"workflow:task",path:"/tasks/:taskId"},{owner:"workflow:task:mobile",path:"/m/tasks/:taskId"},{owner:"workflow:instance",path:"/workflows/:instanceId"},{owner:"workflow:instance:mobile",path:"/m/workflows/:instanceId"});let o=!1;for(let n of e.workflows.definitions)["standalone","hidden-handoff"].includes(n.launch.mode)&&(o=!0);o&&t.push({owner:"workflow:launch",path:"/workflows/:workflowCode/start"},{owner:"workflow:launch:mobile",path:"/m/workflows/:workflowCode/start"})}return t}function bn(e){let t=new Map(_s(e).map(o=>[An(o.path),o]));return te(e.frontend.routes.map((o,n)=>{let i=`/config/frontend/routes/${n}`,r=N(o,i);C(r,["code","path","label","surface","parentCode","capability","access","pinned","tabPersistence","keepAlive"],i,!0),["admin","user"].includes(r.surface)||m("NATIVE_ROUTE_SURFACE_INVALID",`${i}/surface`);let d=Oe(r.path,`${i}/path`);r.surface==="admin"&&d!=="/admin"&&!d.startsWith("/admin/")&&m("NATIVE_ADMIN_ROUTE_PATH_INVALID",`${i}/path`),r.surface==="user"&&(d==="/admin"||d.startsWith("/admin/"))&&m("NATIVE_USER_ROUTE_PATH_RESERVED",`${i}/path`);let s=An(d),a=t.get(s);a&&m("NATIVE_ROUTE_PATH_CONFLICT",`${i}/path`,{path:d,owner:a.owner}),t.set(s,{owner:`frontend:${String(r.code||n)}`,path:d});let c=/[:*]/.test(d),f=Ko(r,i,e.appCode),u=r.pinned===void 0?void 0:ft(r.pinned,`${i}/pinned`),p=r.tabPersistence===void 0?c?"none":"session":S(r.tabPersistence,`${i}/tabPersistence`,16),_=r.keepAlive===void 0?"none":S(r.keepAlive,`${i}/keepAlive`,16);return["session","none"].includes(p)||m("NATIVE_ROUTE_TAB_PERSISTENCE_INVALID",`${i}/tabPersistence`),["none","memory"].includes(_)||m("NATIVE_ROUTE_KEEP_ALIVE_INVALID",`${i}/keepAlive`),c&&u===!0&&m("NATIVE_DYNAMIC_ROUTE_PINNED_FORBIDDEN",`${i}/pinned`),c&&p==="session"&&m("NATIVE_DYNAMIC_ROUTE_TAB_PERSISTENCE_FORBIDDEN",`${i}/tabPersistence`),c&&_==="memory"&&m("NATIVE_DYNAMIC_ROUTE_KEEP_ALIVE_FORBIDDEN",`${i}/keepAlive`),{code:v(r.code,`${i}/code`),path:d,label:S(r.label,`${i}/label`,255),surface:r.surface,...r.parentCode===void 0?{}:{parentCode:v(r.parentCode,`${i}/parentCode`)},...f,...u===void 0?{}:{pinned:u},tabPersistence:p,keepAlive:_}}),o=>o.code)}function gs(e){let t=e.surface===void 0?{}:N(e.surface,"/surface"),o=t.mutationOwner||"native",n=t.generated===void 0?{}:N(t.generated,"/surface/generated"),i=o==="native";return{list:n.list??!0,detail:n.detail??!0,create:n.create??i,update:n.update??i,delete:n.delete??i}}function As(e){let t=[];for(let o of te(e.data.resources,n=>n.code).flatMap(n=>[{resource:n,viewCode:void 0},...(n.surface?.views||[]).map(i=>({viewCode:i.code,resource:{...n,name:i.name,surface:Qn(n.surface,i.code)}}))])){let{resource:n,viewCode:i}=o,r=`/admin/resources/${n.code}${i?`/views/${i}`:""}`,d=gs(n),s=[{operation:"list",kind:"resource-list",path:`${r}`,label:n.name,capability:n.capabilities.read,navigationEligible:!0},{operation:"detail",kind:"resource-detail",path:`${r}/:id`,label:`${n.name}\u8BE6\u60C5`,capability:n.capabilities.read,navigationEligible:!1},{operation:"create",kind:"resource-create",path:`${r}/new`,label:`\u65B0\u589E${n.name}`,capability:n.capabilities.create,navigationEligible:!1},{operation:"update",kind:"resource-update",path:`${r}/:id/edit`,label:`\u7F16\u8F91${n.name}`,capability:n.capabilities.update,navigationEligible:!1}];for(let a of s)d[a.operation]&&t.push({code:`resource:${n.code}${i?`:view:${i}`:""}:${a.operation}`,kind:a.kind,path:a.path,label:a.label,navigationEligible:a.navigationEligible,capability:a.capability,resourceCode:n.code,...i?{viewCode:i}:{}})}for(let o of bn(e))o.surface==="admin"&&t.push({code:`operation:${o.code}`,kind:"operation",path:o.path,label:o.label,navigationEligible:!/[:*]/.test(o.path),routeCode:o.code});return t.sort((o,n)=>Ie(o.code,n.code))}function Es(e){return e.kind==="resource"?`resource:${e.resourceCode}${e.viewCode?`:view:${e.viewCode}`:""}:list`:`operation:${e.routeCode}`}function Xd(e){return e.frontend.admin.navigation.map((t,o)=>({code:t.code,label:t.label,...t.icon===void 0?{}:{icon:t.icon},order:t.order??o,items:t.items.map((n,i)=>({pageCode:Es(n.page),...n.label===void 0?{}:{label:n.label},...n.icon===void 0?{}:{icon:n.icon},order:n.order??i})).sort((n,i)=>n.order-i.order||Ie(n.pageCode,i.pageCode))})).sort((t,o)=>t.order-o.order||Ie(t.code,o.code))}function Zd(e,t){let o=D(e,t,B.adminNavigationGroups);o.reduce((i,r)=>i+(Array.isArray(r?.items)?r.items.length:0),0)>B.adminNavigationItems&&m("NATIVE_ARRAY_LIMIT_EXCEEDED",t);let n=0;o.forEach((i,r)=>{let d=`${t}/${r}`,s=N(i,d);C(s,["code","label","icon","order","items"],d,!0),v(s.code,`${d}/code`),S(s.label,`${d}/label`,255),En(s.icon,`${d}/icon`),ns(s.order,`${d}/order`);let a=D(s.items,`${d}/items`,500);a.length===0&&m("NATIVE_ADMIN_GROUP_ORPHANED",`${d}/items`),n+=a.length,n>B.adminNavigationItems&&m("NATIVE_ARRAY_LIMIT_EXCEEDED",t),a.forEach((c,f)=>{let u=`${d}/items/${f}`,p=N(c,u);C(p,["page","label","icon","order"],u,!0),Qd(p.page,`${u}/page`),p.label!==void 0&&S(p.label,`${u}/label`,255),En(p.icon,`${u}/icon`),ns(p.order,`${u}/order`)})})}function Qd(e,t){let o=N(e,t),n=S(o.kind,`${t}/kind`,64);if(n==="resource"){C(o,["kind","resourceCode"],t,["viewCode"]),o.viewCode!==void 0&&v(o.viewCode,`${t}/viewCode`),H(o.resourceCode,`${t}/resourceCode`);return}if(n==="operation"){C(o,["kind","routeCode"],t),v(o.routeCode,`${t}/routeCode`);return}m("NATIVE_ADMIN_PAGE_REFERENCE_KIND_INVALID",`${t}/kind`)}function ec(e){let t=new Map(As(e).map(i=>[String(i.code),i])),o=new Set,n=new Set;e.frontend.admin.navigation.forEach((i,r)=>{let d=`/config/frontend/admin/navigation/${r}`;o.has(i.code)&&m("NATIVE_ADMIN_GROUP_DUPLICATE",`${d}/code`),o.add(i.code),i.label===i.code&&m("NATIVE_ADMIN_USER_LABEL_REQUIRED",`${d}/label`),i.items.forEach((s,a)=>{let c=`${d}/items/${a}`,f=Es(s.page),u=t.get(f);(!u||u.navigationEligible!==!0)&&m("NATIVE_ADMIN_PAGE_NOT_FOUND",`${c}/page`),n.has(f)&&m("NATIVE_ADMIN_PAGE_DUPLICATE",`${c}/page`),n.add(f);let p=s.page.resourceCode||s.page.routeCode||s.page.workflowCode||f,_=s.label||u.label;(!_||_===p||_===f)&&m("NATIVE_ADMIN_USER_LABEL_REQUIRED",`${c}/label`)})})}function tc(e,t){let o=D(e,t,B.adminPages),n=new Set;o.forEach((i,r)=>{let d=`${t}/${r}`,s=N(i,d);C(s,["code","kind","path","label","navigationEligible","capability","access","resourceCode","viewCode","routeCode"],d,!0);let a=S(s.code,`${d}/code`,255);n.has(a)&&m("NATIVE_ADMIN_PAGE_DUPLICATE",`${d}/code`),n.add(a);let c=S(s.kind,`${d}/kind`,64);if(["resource-list","resource-detail","resource-create","resource-update","operation"].includes(c)||m("NATIVE_ADMIN_PAGE_KIND_INVALID",`${d}/kind`),Oe(s.path,`${d}/path`),S(s.label,`${d}/label`,255),ft(s.navigationEligible,`${d}/navigationEligible`),s.capability!==void 0&&s.access!==void 0&&m("NATIVE_ROUTE_ACCESS_CONFLICT",`${d}/access`),s.capability!==void 0&&S(s.capability,`${d}/capability`,255),s.access!==void 0){let f=N(s.access,`${d}/access`);C(f,["allOf","anyOf"],`${d}/access`,!0);for(let u of["allOf","anyOf"])f[u]!==void 0&&V(f[u],`${d}/access/${u}`,50)}for(let f of["resourceCode","viewCode","routeCode"])s[f]!==void 0&&v(s[f],`${d}/${f}`)})}function nc(e,t){let o=D(e,t,B.adminNavigationGroups);o.reduce((i,r)=>i+(Array.isArray(r?.items)?r.items.length:0),0)>B.adminNavigationItems&&m("NATIVE_ARRAY_LIMIT_EXCEEDED",t);let n=0;o.forEach((i,r)=>{let d=`${t}/${r}`,s=N(i,d);C(s,["code","label","icon","order","items"],d,!0),v(s.code,`${d}/code`),S(s.label,`${d}/label`,255),En(s.icon,`${d}/icon`),se(s.order,`${d}/order`,-1e4,1e4);let a=D(s.items,`${d}/items`,500);a.length===0&&m("NATIVE_ADMIN_GROUP_ORPHANED",`${d}/items`),n+=a.length,n>B.adminNavigationItems&&m("NATIVE_ARRAY_LIMIT_EXCEEDED",t),a.forEach((c,f)=>{let u=`${d}/items/${f}`,p=N(c,u);C(p,["pageCode","label","icon","order"],u,!0),S(p.pageCode,`${u}/pageCode`,255),p.label!==void 0&&S(p.label,`${u}/label`,255),En(p.icon,`${u}/icon`),se(p.order,`${u}/order`,-1e4,1e4)})})}var oc=new Set(["application-todo-center","workflow-work-center","workflow-launch","workflow-task","workflow-instance","resource-records","resource-submit"]);function ic(e,t,o){let n=N(e,t);C(n,["schemaVersion","appCode","devicePolicy","rootEntry","authentication","routes","digest"],t),F(n.schemaVersion,us,`${t}/schemaVersion`),F(n.appCode,o,`${t}/appCode`),Bo(n.devicePolicy,`${t}/devicePolicy`),rc(n.rootEntry,`${t}/rootEntry`),sc(n.authentication,`${t}/authentication`),Uo(n.digest,`${t}/digest`);let i=D(n.routes,`${t}/routes`,B.routes),r=new Set;i.forEach((d,s)=>{let a=`${t}/routes/${s}`,c=N(d,a),f=c.kind==="resource-records"||c.kind==="resource-submit";C(c,["code","kind","desktop","mobile"],a,["workflowCode",...f?["resourceCode"]:[]]);let u=S(c.code,`${a}/code`,255);r.has(u)&&m("NATIVE_ROUTE_MANIFEST_DUPLICATE",`${a}/code`),r.add(u);let p=S(c.kind,`${a}/kind`,64);if(oc.has(p)||m("NATIVE_ROUTE_MANIFEST_KIND_INVALID",`${a}/kind`),c.workflowCode!==void 0&&v(c.workflowCode,`${a}/workflowCode`),f){let A=H(c.resourceCode,`${a}/resourceCode`);F(u,`user.${A}.${c.kind==="resource-records"?"records":"submit"}`,`${a}/code`)}else c.resourceCode!==void 0&&m("NATIVE_PROPERTY_UNKNOWN",`${a}/resourceCode`);let _=Qr(c.desktop,`${a}/desktop`,o),E=Qr(c.mobile,`${a}/mobile`,o);_.surface!=="user"&&m("NATIVE_ROUTE_MANIFEST_DESKTOP_SURFACE_INVALID",`${a}/desktop/surface`),E.surface!=="user"&&m("NATIVE_ROUTE_MANIFEST_MOBILE_SURFACE_INVALID",`${a}/mobile/surface`),_.routeCode===E.routeCode&&m("NATIVE_ROUTE_MANIFEST_PAIR_DUPLICATE",a)}),F(n.digest,Z({schemaVersion:n.schemaVersion,appCode:n.appCode,devicePolicy:n.devicePolicy,rootEntry:n.rootEntry,authentication:n.authentication,routes:n.routes}),`${t}/digest`)}function Bo(e,t){let o=N(e,t);C(o,["kind","mobileMaxWidthPx","desktopMinWidthPx"],t),F(o.kind,"viewport-family",`${t}/kind`);let n=se(o.mobileMaxWidthPx,`${t}/mobileMaxWidthPx`,320,1600),i=se(o.desktopMinWidthPx,`${t}/desktopMinWidthPx`,320,1600);return i!==n+1&&m("NATIVE_FRONTEND_DEVICE_POLICY_INVALID",t),{kind:"viewport-family",mobileMaxWidthPx:n,desktopMinWidthPx:i}}function rc(e,t){let o=N(e,t);C(o,["code","desktop","mobile"],t);let n=v(o.code,`${t}/code`),i=Wo(o.desktop,`${t}/desktop`),r=Wo(o.mobile,`${t}/mobile`);return(i===r||r==="/"||!r.startsWith("/m/"))&&m("NATIVE_ROUTE_MANIFEST_ROOT_ENTRY_INVALID",t),i.startsWith("/m/")&&m("NATIVE_ROUTE_MANIFEST_ROOT_ENTRY_INVALID",`${t}/desktop`),{code:n,desktop:i,mobile:r}}function sc(e,t){let o=N(e,t);C(o,["desktop","mobile"],t);let n=Zr(o.desktop,`${t}/desktop`,!1),i=Zr(o.mobile,`${t}/mobile`,!0);return(n.routeCode===i.routeCode||n.path===i.path)&&m("NATIVE_ROUTE_MANIFEST_AUTHENTICATION_DUPLICATE",t),{desktop:n,mobile:i}}function Zr(e,t,o){let n=N(e,t);C(n,["routeCode","path"],t);let i=v(n.routeCode,`${t}/routeCode`),r=Wo(n.path,`${t}/path`);return(o?!r.startsWith("/m/"):r.startsWith("/m/"))&&m("NATIVE_ROUTE_MANIFEST_AUTHENTICATION_PATH_INVALID",`${t}/path`),{routeCode:i,path:r}}function Wo(e,t){let o=Oe(e,t);return/[:*?#\\\\]/.test(o)&&m("NATIVE_ROUTE_MANIFEST_STATIC_PATH_INVALID",t),o}function Qr(e,t,o){let n=N(e,t);C(n,["routeCode","path","surface","pathParams","requiresAuthentication"],t,["capability","access"]),v(n.routeCode,`${t}/routeCode`);let i=Oe(n.path,`${t}/path`),r=S(n.surface,`${t}/surface`,16);["admin","user"].includes(r)||m("NATIVE_ROUTE_SURFACE_INVALID",`${t}/surface`);let d=V(n.pathParams,`${t}/pathParams`,8);return d.forEach((s,a)=>{(!/^[A-Za-z][A-Za-z0-9_]*$/.test(s)||s.length>64)&&m("NATIVE_ROUTE_PATH_PARAM_INVALID",`${t}/pathParams/${a}`)}),X(d)!==X(Is(i))&&m("NATIVE_ROUTE_PATH_PARAMS_MISMATCH",`${t}/pathParams`),Ko(n,t,o),n.requiresAuthentication!==!0&&m("NATIVE_ROUTE_AUTHENTICATION_REQUIRED",`${t}/requiresAuthentication`),n}function Is(e){return M([...e.matchAll(/:([A-Za-z][A-Za-z0-9_]*)/g)].map(t=>t[1]))}function es(e,t,o,n){return{routeCode:e,path:t,surface:o,pathParams:Is(t),...n?.capability?{capability:n.capability}:{},...n?.access?{access:n.access}:{},requiresAuthentication:!0}}function ts(e,t,o,n){return e==="workflow-launch"?`workflow.${o}.launch.${t}`:e==="application-todo-center"?`application.todo-center.${t}`:e==="resource-records"?`user.${n}.records.${t}`:e==="resource-submit"?`user.${n}.submit.${t}`:`${e.replace(/-/g,".")}.${t}`}function ac(e){let t=e.appCode,o=[],n=(_,E,A,O,b,g,I)=>{o.push({code:_,kind:E,...b?{workflowCode:b}:{},...I?{resourceCode:I}:{},desktop:es(ts(E,"desktop",b,I),A,"user",g),mobile:es(ts(E,"mobile",b,I),O,"user",g)})};e.frontend.user.applicationTodoCenter===!0&&n("application:todo-center","application-todo-center","/todos","/m/todos");let i=ys(e);i.length>0&&(n("workflow:work-center","workflow-work-center","/work-center","/m/work-center"),n("workflow:task","workflow-task","/tasks/:taskId","/m/tasks/:taskId"),n("workflow:instance","workflow-instance","/workflows/:instanceId","/m/workflows/:instanceId"));for(let _ of i){if(!["standalone","hidden-handoff"].includes(_.launch.mode))continue;let E=M([_.launch.submission?.create?.requiredCapability,_.launch.submission?.existing?.requiredCapability].filter(A=>!!A));n(`workflow:${_.code}:launch`,"workflow-launch","/workflows/:workflowCode/start","/m/workflows/:workflowCode/start",_.code,E.length===1?{capability:E[0]}:E.length>1?{access:{anyOf:E}}:void 0)}let r=o.sort((_,E)=>Ie(String(_.code),String(E.code))),d=bn(e),s=_=>{let E=_==="mobile"?"/m/":"/",A=d.filter(b=>b.surface==="user"&&!/[:*?#\\\\]/.test(b.path)&&b.path===E).sort((b,g)=>Ie(b.code,g.code))[0];if(A)return{code:A.code,path:A.path};let O=d.filter(b=>b.surface==="user"&&!/[:*?#\\\\]/.test(b.path)&&(_==="mobile"?b.path.startsWith("/m/"):!b.path.startsWith("/m/"))).sort((b,g)=>Ie(b.code,g.code))[0];return O?{code:O.code,path:O.path}:{code:_==="mobile"?"application-root-mobile":"application-root",path:E}},a=e.frontend.authentication?{desktop:{routeCode:e.frontend.authentication.surfaces.desktop.routeCode,path:e.frontend.authentication.surfaces.desktop.path},mobile:{routeCode:e.frontend.authentication.surfaces.mobile.routeCode,path:e.frontend.authentication.surfaces.mobile.path}}:{desktop:{routeCode:"application-login",path:"/login"},mobile:{routeCode:"application-login-mobile",path:"/m/login"}},c=Bo(e.frontend.devicePolicy,"/config/frontend/devicePolicy"),f=s("desktop"),u=s("mobile"),p={schemaVersion:us,appCode:t,devicePolicy:c,rootEntry:{code:f.code,desktop:f.path,mobile:u.path},authentication:a,routes:r};return{...p,digest:Z(p)}}function En(e,t){if(e===void 0)return;let o=S(e,t,32);bd.has(o)||m("NATIVE_ADMIN_ICON_INVALID",t)}function ns(e,t){e!==void 0&&se(e,t,-1e4,1e4)}function Ko(e,t,o){return e.capability!==void 0&&e.access!==void 0&&m("NATIVE_ROUTE_ACCESS_CONFLICT",`${t}/access`),e.capability!==void 0?{capability:me(e.capability,`${t}/capability`,o)}:e.access===void 0?{}:{access:On(e.access,`${t}/access`,o)}}function On(e,t,o){let n=N(e,t);C(n,["allOf","anyOf"],t,!0);let i=n.allOf===void 0?void 0:M(V(n.allOf,`${t}/allOf`,50).map((d,s)=>me(d,`${t}/allOf/${s}`,o))),r=n.anyOf===void 0?void 0:M(V(n.anyOf,`${t}/anyOf`,50).map((d,s)=>me(d,`${t}/anyOf/${s}`,o)));return(i?.length||0)+(r?.length||0)===0&&m("NATIVE_ROUTE_ACCESS_EMPTY",t),{...i===void 0?{}:{allOf:i},...r===void 0?{}:{anyOf:r}}}function ys(e){let t=new Map(ps(e).map(i=>[String(i.code),i])),o=e.workflows.definitions.map((i,r)=>{let d=`/config/workflows/definitions/${r}`,s=N(i,d);C(s,["version","definition","launch"],d,["detailRouteCode"]);let a=N(s.definition,`${d}/definition`),c=s.detailRouteCode===void 0?void 0:Os(s.detailRouteCode,`${d}/detailRouteCode`);return{code:v(a.code,`${d}/definition/code`),title:S(a.title,`${d}/definition/title`,255),version:ut(s.version,`${d}/version`),launch:dc(e,a,s.launch,`${d}/launch`,t),...c?{detailRouteCode:c}:{},definition:a}});return M(o.map(i=>i.code)).map(i=>{let r=o.filter(c=>c.code===i),d=e.workflows.activations.find(c=>c.workflowCode===i)?.definitionVersion,s=r.find(c=>c.version===d)||[...r].sort((c,f)=>f.version-c.version)[0],a=new Set;for(let c of r){let f=N(c.definition.nodes,"/config/workflows/definitions/nodes");for(let u of Object.values(f)){let p=N(u,"/config/workflows/definitions/nodes/*");if(p.kind==="approval")for(let _ of V(p.allowedOperations||[],"/config/workflows/definitions/nodes/*/allowedOperations",20))a.add(_)}}return{code:i,title:s.title,acceptedCommandDeactivationPolicy:s.definition.acceptedCommandDeactivationPolicy,subject:s.definition.subject,launch:s.launch,...["standalone","hidden-handoff"].includes(s.launch.mode)&&!s.launch.submission?{processOperationCode:`openxiangda.workflow.${i}.submit`}:{},...s.detailRouteCode?{detailRouteCode:s.detailRouteCode}:{},definitionVersions:cs(r.map(c=>c.version)),bindingVersions:cs(e.workflows.bindings.map((c,f)=>{let u=`/config/workflows/bindings/${f}`,p=N(c,u),_=N(p.binding,`${u}/binding`);return{code:v(_.workflowCode,`${u}/binding/workflowCode`),version:ut(p.version,`${u}/version`)}}).filter(c=>c.code===i).map(c=>c.version)),providerCodes:M(e.workflows.providers.map((c,f)=>v(N(c,`/config/workflows/providers/${f}`).code,`/config/workflows/providers/${f}/code`))),allowedOperations:[...a].sort(Ie),editableParameterCodes:M(e.workflows.editableParameters.map((c,f)=>{let u=`/config/workflows/editableParameters/${f}`,p=N(c,u);return{code:v(p.code,`${u}/code`),workflowCode:v(p.workflowCode,`${u}/workflowCode`)}}).filter(c=>c.workflowCode===i).map(c=>c.code))}})}function bs(e,t){let o=N(e,t);C(o,["mode"],t,["submission"]);let n=S(o.mode,`${t}/mode`,32);return["standalone","custom-page","hidden-handoff","work-center-only"].includes(n)||m("NATIVE_WORKFLOW_LAUNCH_MODE_INVALID",`${t}/mode`),{mode:n,...o.submission===void 0?{}:{submission:N(o.submission,`${t}/submission`)}}}function dc(e,t,o,n,i){let r=bs(o,n);if(!r.submission)return{mode:r.mode};["standalone","hidden-handoff"].includes(r.mode)||m("NATIVE_WORKFLOW_NAMED_OPERATION_SUBMISSION_INVALID",`${n}/submission`);let d=N(r.submission,`${n}/submission`);C(d,["kind"],`${n}/submission`,["create","existing","context"]),F(d.kind,"named-operation",`${n}/submission/kind`);let s=n.endsWith("/launch")?n.slice(0,-7):n,a=N(t.subject,`${s}/definition/subject`),c=H(a.resourceCode,`${s}/definition/subject/resourceCode`),f=e.data.resources.findIndex(y=>y.code===c),u=e.data.resources[f];(f<0||!u)&&m("NATIVE_WORKFLOW_SUBJECT_RESOURCE_MISSING",`${s}/definition/subject/resourceCode`);let p=new Set(N(u.schema,`/config/data/resources/${f}/schema`).fields.map(y=>String(y.code))),_=new Map(e.backend.operations.map(y=>[String(y.code),y])),E=(y,R)=>{let h=`${n}/submission/${R}`,$=N(y,h);C($,["operationCode","inputs","output"],h);let w=v($.operationCode,`${h}/operationCode`),j=_.get(w),L=i.get(w),Q=L?.platformAccess?.workflow?.codes;(!j||!L||L.method!=="POST"||!Array.isArray(Q)||!Q.includes(t.code))&&m("NATIVE_WORKFLOW_NAMED_OPERATION_INVALID",h);let ee=N(j.requestSchema,`${h}/operation/requestSchema`),Y=N(ee.properties,`${h}/operation/requestSchema/properties`),ge=new Set(ee.required===void 0?[]:V(ee.required,`${h}/operation/requestSchema/required`,205)),oe=N($.inputs,`${h}/inputs`),P=Object.entries(oe);(!P.length||P.length>205)&&m("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${h}/inputs`);let U=new Set,x=new Map,q={},z=L.platformAccess?.ownedSubject;z&&(R!=="create"||z.resourceCode!==c)&&m("NATIVE_WORKFLOW_OWNED_SUBJECT_LAUNCH_MISMATCH",h);for(let[J,Ze]of P){(!Jr.test(J)||!Object.prototype.hasOwnProperty.call(Y,J))&&m("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${h}/inputs/${J}`);let We=`${h}/inputs/${J}`,Cn=N(Ze,We),Ue=S(Cn.source,`${We}/source`,32);if(["field","idempotency-key","current-user-reference","subject-id","subject-revision","requested-at"].includes(Ue)||m("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",We),C(Cn,["source"],We,Ue==="field"?["fieldCode"]:!1),x.set(Ue,(x.get(Ue)||0)+1),Ue==="field"){let Qe=G(Cn.fieldCode,`${We}/fieldCode`);(U.has(Qe)||!p.has(Qe))&&m("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${We}/fieldCode`),U.add(Qe),u.schema.fields.find(hn=>hn.code===Qe)?.type==="subtable"&&(!z||!z.subtables.some(hn=>hn.fieldCode===Qe))&&m("NATIVE_WORKFLOW_OWNED_SUBJECT_LAUNCH_REQUIRED",We),q[J]={source:Ue,fieldCode:Qe}}else q[J]={source:Ue}}([...ge].some(J=>!(J in oe))||(x.get("idempotency-key")||0)!==1||!P.some(([J,Ze])=>N(Ze,`${h}/inputs/${J}`).source==="idempotency-key"&&ge.has(J))||R==="create"&&((x.get("subject-id")||0)>0||(x.get("subject-revision")||0)>0)||R==="existing"&&((x.get("subject-id")||0)!==1||(x.get("subject-revision")||0)!==1))&&m("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${h}/inputs`);let Ae=N($.output,`${h}/output`);C(Ae,["subjectId"],`${h}/output`,["subjectRevision","processCommand"]);let Ne=N(N(j.responseSchema,`${h}/operation/responseSchema`).properties,`${h}/operation/responseSchema/properties`);for(let J of["subjectId","subjectRevision","processCommand"]){if(Ae[J]===void 0)continue;let Ze=S(Ae[J],`${h}/output/${J}`,128);(!Jr.test(Ze)||!Object.prototype.hasOwnProperty.call(Ne,Ze))&&m("NATIVE_WORKFLOW_NAMED_OPERATION_OUTPUT_INVALID",`${h}/output/${J}`)}return{operationCode:w,method:"POST",path:L.path,requiredCapability:L.requiredCapability,requestSchemaDigest:L.requestSchemaDigest,responseSchemaDigest:L.responseSchemaDigest,inputs:q,output:{...Ae},fieldCodes:U}},A=d.create===void 0?void 0:E(d.create,"create"),O=d.existing===void 0?void 0:E(d.existing,"existing");!A&&!O&&m("NATIVE_WORKFLOW_NAMED_OPERATION_SUBMISSION_INVALID",`${n}/submission`);let b=new Set([...A?.fieldCodes||[],...O?.fieldCodes||[]]),g=d.context===void 0?[]:D(d.context,`${n}/submission/context`,16),I=new Set,T=g.map((y,R)=>{let h=`${n}/submission/context/${R}`,$=N(y,h);C($,["queryParameter","fieldCode"],h);let w=S($.queryParameter,`${h}/queryParameter`,64),j=G($.fieldCode,`${h}/fieldCode`);return(!/^[A-Za-z][A-Za-z0-9]{0,63}$/.test(w)||I.has(w)||!b.has(j))&&m("NATIVE_WORKFLOW_LAUNCH_CONTEXT_INVALID",h),I.add(w),{queryParameter:w,fieldCode:j}}),l=y=>{let{fieldCodes:R,...h}=y;return h};return{mode:r.mode,submission:{kind:"named-operation",...A?{create:l(A)}:{},...O?{existing:l(O)}:{},context:T}}}function Os(e,t){let o=N(e,t);C(o,["desktop","mobile"],t);let n=v(o.desktop,`${t}/desktop`),i=v(o.mobile,`${t}/mobile`);return n===i&&m("NATIVE_WORKFLOW_DETAIL_ROUTE_DUPLICATE",t),{desktop:n,mobile:i}}function cc(e,t){let o=new Set(t.map(f=>f.code)),n=new Map;e.data.resources.forEach((f,u)=>{let p=`/config/data/resources/${u}`,_=N(f,p);if(_.recordDeletion!==void 0){let O=`${p}/recordDeletion/delete`;for(let b of _.recordDeletion.delete)me(b,O,e.appCode),o.has(b)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",O)}if(_.recordComments!==void 0)for(let O of["read","create"]){let b=`${p}/recordComments/${O}`;for(let g of _.recordComments[O])me(g,b,e.appCode),o.has(g)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",b)}if(_.recordPrint!==void 0){let O=`${p}/recordPrint/read`;for(let b of _.recordPrint.read)me(b,O,e.appCode),o.has(b)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",O)}if(_.workflowHistory!==void 0){let O=`${p}/workflowHistory/read`;for(let b of _.workflowHistory.read)me(b,O,e.appCode),o.has(b)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",O)}for(let[O,b]of Object.entries(_.fieldPolicies||{})){if(!_t(O))continue;let g=`${p}/fieldPolicies/${O}/read`,I=N(b,`${p}/fieldPolicies/${O}`);for(let T of V(I.read||[],g,2e3))o.has(T)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",g)}let E=_.surface===void 0?{}:N(_.surface,`${p}/surface`);if(["native","queued-command"].includes(E.mutationOwner||"native"))return;let A=N(_.capabilities,`${p}/capabilities`);for(let O of["create","update","delete"])O==="delete"&&Array.isArray(_.recordDeletion?.delete)&&_.recordDeletion.delete.length>0||n.set(String(A[O]),O)});let i=new Set;for(let[f,u]of e.authz.roles.entries()){let p=`/config/authz/roles/${f}`,_=N(u,p);C(_,["code","name","description","capabilities"],p,!0);let E=v(_.code,`${p}/code`);i.has(E)&&m("NATIVE_ROLE_DUPLICATE",`${p}/code`),i.add(E),S(_.name,`${p}/name`,255);let A=V(_.capabilities,`${p}/capabilities`,2e3);for(let[O,b]of A.entries())n.has(b)&&m("NATIVE_DATA_SURFACE_MUTATION_GRANT_FORBIDDEN",`${p}/capabilities/${O}`,{operation:n.get(b)}),o.has(b)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",`${p}/capabilities`)}let r=e.authz.authenticatedUserRoleCode===void 0?"":v(e.authz.authenticatedUserRoleCode,"/config/authz/authenticatedUserRoleCode");r&&!i.has(r)&&m("NATIVE_AUTHENTICATED_USER_ROLE_REFERENCE_MISSING","/config/authz/authenticatedUserRoleCode");let d=new Set,s=0;for(let[f,u]of e.perspectives.entries()){let p=`/config/perspectives/${f}`,_=N(u,p);C(_,["code","name","description","roleCodes","capabilityCodes","default"],p,!0);let E=v(_.code,`${p}/code`);d.has(E)&&m("NATIVE_PERSPECTIVE_DUPLICATE",`${p}/code`),d.add(E),S(_.name,`${p}/name`,255);let A=V(_.roleCodes,`${p}/roleCodes`,20);A.length<1&&m("NATIVE_PERSPECTIVE_ROLE_REQUIRED",`${p}/roleCodes`),A.forEach((g,I)=>{i.has(g)||m("NATIVE_PERSPECTIVE_ROLE_MISSING",`${p}/roleCodes/${I}`)});let O=M(e.authz.roles.filter(g=>A.includes(g.code)).flatMap(g=>g.capabilities)),b=V(_.capabilityCodes,`${p}/capabilityCodes`,2e3);X(O)!==X(b)&&m("NATIVE_PERSPECTIVE_CAPABILITY_PROJECTION_MISMATCH",`${p}/capabilityCodes`),_.default===!0?s+=1:_.default!==void 0&&m("NATIVE_PERSPECTIVE_DEFAULT_INVALID",`${p}/default`)}s>1&&m("NATIVE_PERSPECTIVE_DEFAULT_DUPLICATE","/config/perspectives");for(let[f,u]of e.backend.operations.entries()){let p=N(u,`/config/backend/operations/${f}`);o.has(p.capability)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",`/config/backend/operations/${f}/capability`)}let a=new Set,c=new Set;for(let[f,u]of e.frontend.routes.entries()){let p=`/config/frontend/routes/${f}`,_=N(u,p),E=v(_.code,`${p}/code`);a.has(E)&&m("NATIVE_ROUTE_DUPLICATE",`${p}/code`),a.add(E);let A=Oe(_.path,`${p}/path`);c.has(A)&&m("NATIVE_ROUTE_PATH_DUPLICATE",`${p}/path`),c.add(A);let O=Ko(_,p,e.appCode);O.capability&&!o.has(O.capability)&&m("NATIVE_CAPABILITY_REFERENCE_MISSING",`${p}/capability`);let b=_.access===void 0?void 0:N(_.access,`${p}/access`);for(let g of["allOf","anyOf"]){let I=b?.[g]===void 0?[]:D(b[g],`${p}/access/${g}`,50);for(let[T,l]of I.entries()){let y=me(l,`${p}/access/${g}/${T}`,e.appCode);o.has(y)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",`${p}/access/${g}/${T}`)}}}if(e.frontend.admin.access!==void 0){let f=On(e.frontend.admin.access,"/config/frontend/admin/access",e.appCode);for(let u of["allOf","anyOf"])for(let[p,_]of(f[u]||[]).entries())o.has(_)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",`/config/frontend/admin/access/${u}/${p}`)}for(let[f,u]of e.frontend.routes.entries()){let p=N(u,`/config/frontend/routes/${f}`);p.parentCode&&!a.has(p.parentCode)&&m("NATIVE_ROUTE_PARENT_MISSING",`/config/frontend/routes/${f}/parentCode`)}}function lc(e){let t=new Set(e.authz.roles.map(c=>String(c.code))),o=e.authz.authenticatedUserRoleCode===void 0?"":v(e.authz.authenticatedUserRoleCode,"/config/authz/authenticatedUserRoleCode"),n=new Map(e.authz.scopeDimensions.map(c=>[String(c.code),{valueType:c.valueType==="uuid"?"uuid":"string",...c.valueSource?.resourceCode?{valueSourceResourceCode:String(c.valueSource.resourceCode)}:{}}])),i=new Set(n.keys()),r=new Map(e.data.resources.map((c,f)=>{let u=Ye(c,`/config/data/resources/${f}`,e.appCode);return[u.code,new Map(u.schema.fields.map(p=>[String(p.code),p]))]}));for(let[c,f]of e.authz.scopeDimensions.entries()){let u=`/config/authz/scopeDimensions/${c}`,p=N(f,u);if(C(p,["code","name","resourceCode","valueType","hierarchyMode","valueSource"],u,!0),p.valueSource===void 0)continue;let _=N(p.valueSource,`${u}/valueSource`);C(_,["kind","resourceCode","labelField","enabledField"],`${u}/valueSource`,!0),_.kind!=="native_resource"&&m("NATIVE_SCOPE_VALUE_SOURCE_KIND_INVALID",`${u}/valueSource/kind`),p.valueType!=="uuid"&&m("NATIVE_SCOPE_VALUE_SOURCE_TYPE_INVALID",`${u}/valueType`);let E=H(_.resourceCode,`${u}/valueSource/resourceCode`),A=r.get(E);A||m("NATIVE_SCOPE_VALUE_SOURCE_RESOURCE_MISSING",`${u}/valueSource/resourceCode`);let O=G(_.labelField,`${u}/valueSource/labelField`);if(["text.short","text.long"].includes(String(A.get(O)?.type||""))||m("NATIVE_SCOPE_VALUE_SOURCE_LABEL_FIELD_INVALID",`${u}/valueSource/labelField`),_.enabledField!==void 0){let b=G(_.enabledField,`${u}/valueSource/enabledField`);A.get(b)?.type!=="boolean"&&m("NATIVE_SCOPE_VALUE_SOURCE_ENABLED_FIELD_INVALID",`${u}/valueSource/enabledField`)}}let d=new Set,s=new Set;for(let[c,f]of e.authz.scopeSources.entries()){let u=`/config/authz/scopeSources/${c}`,p=N(f,u);C(p,["code","name","resourceCode","subject","grants","operationField","enabledField","effectiveFromField","effectiveToField","failureMode"],u,!0);let _=v(p.code,`${u}/code`);d.has(_)&&m("NATIVE_SCOPE_SOURCE_DUPLICATE",`${u}/code`),d.add(_),S(p.name,`${u}/name`,255);let E=H(p.resourceCode,`${u}/resourceCode`),A=r.get(E);A||m("NATIVE_SCOPE_SOURCE_RESOURCE_MISSING",`${u}/resourceCode`);let O=N(p.subject,`${u}/subject`),b=S(O.type,`${u}/subject/type`,32);C(O,b==="role_membership"?["type","userIdField","roleCode"]:["type","userIdField"],`${u}/subject`),["user","role_membership"].includes(b)||m("NATIVE_SCOPE_SOURCE_SUBJECT_INVALID",`${u}/subject/type`);let g=It(O.userIdField,A);so(g)||m("NATIVE_SCOPE_SOURCE_SUBJECT_PATH_INVALID",`${u}/subject/userIdField`),b==="role_membership"&&!t.has(String(O.roleCode))&&m("NATIVE_ROLE_REFERENCE_MISSING",`${u}/subject/roleCode`);let I=new Set;for(let[T,l]of D(p.grants,`${u}/grants`,100).entries()){let y=`${u}/grants/${T}`,R=N(l,y);C(R,["dimensionCode","valueField","parentValueField"],y,!0);let h=v(R.dimensionCode,`${y}/dimensionCode`);(!i.has(h)||I.has(h))&&m("NATIVE_SCOPE_SOURCE_DIMENSION_INVALID",`${y}/dimensionCode`),I.add(h),p.failureMode==="last_known_good"&&s.add(h);for(let $ of["valueField","parentValueField"]){if(R[$]===void 0)continue;let w=It(R[$],A);Pi(w,n.get(h),r)||m("NATIVE_SCOPE_SOURCE_GRANT_PATH_INVALID",`${y}/${$}`)}}I.size===0&&m("NATIVE_SCOPE_SOURCE_GRANT_REQUIRED",`${u}/grants`),["strict","last_known_good"].includes(p.failureMode)||m("NATIVE_SCOPE_SOURCE_FAILURE_MODE_INVALID",`${u}/failureMode`);for(let T of["operationField","enabledField","effectiveFromField","effectiveToField"]){if(p[T]===void 0)continue;let l=G(p[T],`${u}/${T}`);A.has(l)||m("NATIVE_SCOPE_SOURCE_FIELD_MISSING",`${u}/${T}`)}}fc(e,t,r,o);let a=new Set;for(let[c,f]of e.authz.dataPolicies.entries()){let u=`/config/authz/dataPolicies/${c}`,p=N(f,u);C(p,["code","name","resourceCode","unrestrictedRoleCodes","publicRead","operations","matchMode","rules","readExpression","writeBoundary"],u,!0);let _=v(p.code,`${u}/code`);a.has(_)&&m("NATIVE_DATA_POLICY_DUPLICATE",`${u}/code`),a.add(_);let E=p.readExpression!==void 0,A=V(p.operations||[],`${u}/operations`,4);p.operations!==void 0&&(A.length===0||A.some(l=>!["read","create","update","delete"].includes(l)))&&m("NATIVE_DATA_POLICY_OPERATIONS_INVALID",`${u}/operations`),["AND","OR"].includes(p.matchMode)||m("NATIVE_DATA_POLICY_MATCH_MODE_INVALID",`${u}/matchMode`),E&&p.operations!==void 0&&m("NATIVE_DATA_POLICY_READ_EXPRESSION_OPERATIONS_FORBIDDEN",`${u}/operations`);let O=e.data.resources.find(l=>l.dataPolicyCode===_),b=p.resourceCode||O?.code,g=b?r.get(H(b,`${u}/resourceCode`)):void 0;if(E&&!g&&m("NATIVE_DATA_POLICY_RESOURCE_MISSING",`${u}/resourceCode`),p.publicRead!==void 0){try{let l=e.authz.roles.find(y=>y.code===o);qi({policy:p,resource:e.data.resources.find(y=>y.code===b),baselineRoleCode:o,baselineCapabilities:l?.capabilities||[],baselineDeniedCapabilities:l?.deniedCapabilities||[],pointer:u})}catch(l){if(!(l instanceof Nt))throw l;m(l.code,l.pointer)}(p.unrestrictedRoleCodes||[]).includes(o)||m("AUTHENTICATED_PUBLIC_READ_CANONICAL_BASELINE_MISSING",`${u}/unrestrictedRoleCodes`)}else o&&(p.unrestrictedRoleCodes||[]).includes(o)&&m("NATIVE_DATA_POLICY_BASELINE_UNRESTRICTED",`${u}/unrestrictedRoleCodes`);let I=V(p.unrestrictedRoleCodes||[],`${u}/unrestrictedRoleCodes`,100);p.unrestrictedRoleCodes!==void 0&&I.length===0&&m("NATIVE_DATA_POLICY_UNRESTRICTED_ROLES_INVALID",`${u}/unrestrictedRoleCodes`);for(let l of I)t.has(l)||m("NATIVE_ROLE_REFERENCE_MISSING",`${u}/unrestrictedRoleCodes`);let T;try{let l=D(p.rules,`${u}/rules`,100).map((y,R)=>({rule:N(y,`${u}/rules/${R}`),pointer:`${u}/rules/${R}`}));l.length===0?(!E||p.matchMode!=="AND"||p.writeBoundary!=="capability_only")&&m("NATIVE_DATA_POLICY_WRITE_BOUNDARY_REQUIRED",u):p.writeBoundary!==void 0&&m("NATIVE_DATA_POLICY_WRITE_BOUNDARY_INVALID",`${u}/writeBoundary`),T=[...l],E&&(T.push(...st(p.readExpression,`${u}/readExpression`)),Vi(p.readExpression,`${u}/readExpression`))}catch(l){throw l instanceof Ot&&m(l.code,l.pointer),l}for(let{rule:l,pointer:y}of T){if(C(l,["parentRead","subject","dimensionCode","relationCode","resourceCode","field","roleCodes","operation","valuePath","emptyMatchesAll","operator","value","operand"],y,!0),l.parentRead!==void 0){for(let Y of V(l.roleCodes||[],`${y}/roleCodes`,100))t.has(Y)||m("NATIVE_ROLE_REFERENCE_MISSING",`${y}/roleCodes`);continue}let R=G(l.field,`${y}/field`),h=g?.get(R);E&&!h&&m("NATIVE_DATA_POLICY_FIELD_MISSING",`${y}/field`);for(let Y of V(l.roleCodes||[],`${y}/roleCodes`,100))t.has(Y)||m("NATIVE_ROLE_REFERENCE_MISSING",`${y}/roleCodes`);let $=String(l.operator||""),w=l.operand==="db_now",j=["is_null","is_not_null"].includes($),L=["eq","not_eq","in","not_in"].includes($),Q=!w&&(l.operator!==void 0||l.value!==void 0);if([l.subject==="current_user"?"current_user":"",typeof l.dimensionCode=="string"?"dimension":"",typeof l.relationCode=="string"?"relationship":"",Q?"constant":"",w?"db_now":""].filter(Boolean).length!==1&&m("NATIVE_DATA_POLICY_RULE_SOURCE_INVALID",y),l.subject!==void 0&&l.subject!=="current_user"&&m("NATIVE_DATA_POLICY_SUBJECT_INVALID",`${y}/subject`),Q){if(!L&&!j&&m("NATIVE_DATA_POLICY_OPERATOR_INVALID",`${y}/operator`),["in","not_in"].includes($)){let Y=D(l.value,`${y}/value`,100).map((ge,oe)=>S(ge,`${y}/value/${oe}`,2048));(Y.length===0||new Set(Y).size!==Y.length)&&m("NATIVE_DATA_POLICY_VALUE_INVALID",`${y}/value`)}else["eq","not_eq"].includes($)?S(l.value,`${y}/value`,2048):(l.value!==void 0||l.operand!==void 0)&&m("NATIVE_DATA_POLICY_VALUE_INVALID",`${y}/value`);for(let Y of["operation","valuePath","emptyMatchesAll","resourceCode","operand"])l[Y]!==void 0&&m("NATIVE_DATA_POLICY_CONSTANT_RULE_INVALID",`${y}/${Y}`)}if(w){(!["lt","lte","gt","gte"].includes($)||l.value!==void 0||h?.type!=="datetime")&&m("NATIVE_DATA_POLICY_DB_NOW_INVALID",y);for(let Y of["operation","valuePath","emptyMatchesAll","resourceCode","value"])l[Y]!==void 0&&m("NATIVE_DATA_POLICY_DB_NOW_INVALID",`${y}/${Y}`)}l.dimensionCode&&!i.has(l.dimensionCode)&&m("NATIVE_SCOPE_DIMENSION_MISSING",`${y}/dimensionCode`),s.has(String(l.dimensionCode||""))&&l.operation!=="read"&&m("NATIVE_SCOPE_SOURCE_LAST_KNOWN_GOOD_UNSAFE",`${y}/operation`)}}try{ji(e.data.resources,e.authz.dataPolicies)}catch(c){throw c instanceof ue&&m(c.code,c.pointer),c}for(let[c,f]of e.data.resources.entries()){let u=N(f,`/config/data/resources/${c}`);u.dataPolicyCode&&!a.has(u.dataPolicyCode)&&m("NATIVE_DATA_POLICY_REFERENCE_MISSING",`/config/data/resources/${c}/dataPolicyCode`)}}function uc(e){try{ui(e.data.resources,"/config/data/resources"),e.data.resources.forEach((t,o)=>ni(t.schema.fields,new Set(e.authz.roles.map(n=>n.code)),new Set(e.authz.scopeDimensions.map(n=>n.code)),`/config/data/resources/${o}/schema/fields`))}catch(t){throw(t instanceof Re||t instanceof Me)&&m(t.code,t.pointer),t}}function fc(e,t,o,n){let i=new Set;for(let[r,d]of e.authz.roleMembershipSources.entries()){let s=`/config/authz/roleMembershipSources/${r}`,a=N(d,s);C(a,["code","name","resourceCode","userIdField","roleCode","enabledField","effectiveFromField","effectiveToField","failureMode"],s,!0);let c=v(a.code,`${s}/code`);c.length>100&&m("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_CODE_INVALID",`${s}/code`),i.has(c)&&m("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_DUPLICATE",`${s}/code`),i.add(c),S(a.name,`${s}/name`,255);let f=os(a.resourceCode,`${s}/resourceCode`,o);is(a.userIdField,`${s}/userIdField`,f),t.has(String(a.roleCode||""))||m("NATIVE_ROLE_REFERENCE_MISSING",`${s}/roleCode`),n&&a.roleCode===n&&m("NATIVE_AUTHENTICATED_USER_ROLE_SOURCE_CONFLICT",`${s}/roleCode`),rs(a,s,f)}for(let[r,d]of e.authz.relationshipGrantSources.entries()){let s=`/config/authz/relationshipGrantSources/${r}`,a=N(d,s);C(a,["code","name","resourceCode","subject","relationCode","targetResourceCode","resourceIdField","operations","enabledField","effectiveFromField","effectiveToField","failureMode"],s,!0);let c=v(a.code,`${s}/code`);c.length>100&&m("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_CODE_INVALID",`${s}/code`),i.has(c)&&m("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_DUPLICATE",`${s}/code`),i.add(c),S(a.name,`${s}/name`,255);let f=os(a.resourceCode,`${s}/resourceCode`,o),u=N(a.subject,`${s}/subject`),p=S(u.type,`${s}/subject/type`,32);C(u,p==="role_membership"?["type","userIdField","roleCode"]:["type","userIdField"],`${s}/subject`),["user","role_membership"].includes(p)||m("NATIVE_AUTHORIZATION_PROJECTION_SUBJECT_INVALID",`${s}/subject/type`),is(u.userIdField,`${s}/subject/userIdField`,f),p==="role_membership"&&!t.has(String(u.roleCode||""))&&m("NATIVE_ROLE_REFERENCE_MISSING",`${s}/subject/roleCode`),v(a.relationCode,`${s}/relationCode`);let _=H(a.targetResourceCode,`${s}/targetResourceCode`);o.has(_)||m("NATIVE_AUTHORIZATION_PROJECTION_TARGET_RESOURCE_MISSING",`${s}/targetResourceCode`);let E=It(a.resourceIdField,f),A=E?.field.type==="resource-ref.single"&&E.valuePath==="value"&&E.field.source?.resourceCode===_;(a.resourceIdField==="id"?_!==String(a.resourceCode):!A)&&m("NATIVE_AUTHORIZATION_PROJECTION_RESOURCE_ID_FIELD_INVALID",`${s}/resourceIdField`);let O=V(a.operations,`${s}/operations`,20);(O.length===0||O.some(b=>b.length>64||!/^[A-Za-z0-9][A-Za-z0-9:._*-]{0,63}$/.test(b)))&&m("NATIVE_AUTHORIZATION_PROJECTION_OPERATIONS_INVALID",`${s}/operations`),rs(a,s,f)}}function os(e,t,o){let n=H(e,t),i=o.get(n);return i||m("NATIVE_AUTHORIZATION_PROJECTION_RESOURCE_MISSING",t),i}function is(e,t,o){let n=It(e,o);so(n)||m("NATIVE_AUTHORIZATION_PROJECTION_USER_FIELD_INVALID",t)}function rs(e,t,o){if(e.failureMode!=="strict"&&m("NATIVE_AUTHORIZATION_PROJECTION_FAILURE_MODE_INVALID",`${t}/failureMode`),e.enabledField!==void 0){let n=G(e.enabledField,`${t}/enabledField`);o.get(n)?.type!=="boolean"&&m("NATIVE_AUTHORIZATION_PROJECTION_ENABLED_FIELD_INVALID",`${t}/enabledField`)}for(let n of["effectiveFromField","effectiveToField"]){if(e[n]===void 0)continue;let i=G(e[n],`${t}/${n}`);["date","datetime"].includes(String(o.get(i)?.type))||m("NATIVE_AUTHORIZATION_PROJECTION_EFFECTIVE_FIELD_INVALID",`${t}/${n}`)}}function pc(e){let t=new Set,o=new Set;e.forEach((n,i)=>{let r=`/config/backend/secrets/${i}`,d=N(n,r);C(d,["name","env","description","required","exposure"],r,!0);let s=S(d.name,`${r}/name`,128),a=S(d.env,`${r}/env`,128);pd.test(s)||m("NATIVE_SECRET_NAME_INVALID",`${r}/name`),(!md.test(a)||a.startsWith("OPENXIANGDA_")||["NODE_ENV","PORT"].includes(a))&&m("NATIVE_SECRET_ENV_INVALID",`${r}/env`),t.has(s)&&m("NATIVE_SECRET_NAME_DUPLICATE",`${r}/name`),o.has(a)&&m("NATIVE_SECRET_ENV_DUPLICATE",`${r}/env`),t.add(s),o.add(a),F(d.exposure,"active_only",`${r}/exposure`),d.required!==void 0&&ft(d.required,`${r}/required`),d.description!==void 0&&Go(d.description,`${r}/description`,2e3)})}function mc(e){let t=new Set,o=new Map,n=new Map(e.data.resources.map(_=>[String(_.code),_])),i=new Map(e.frontend.routes.map((_,E)=>{let A=N(_,`/config/frontend/routes/${E}`);return[v(A.code,`/config/frontend/routes/${E}/code`),A]}));for(let[_,E]of e.workflows.definitions.entries()){let A=`/config/workflows/definitions/${_}`,O=N(E,A);if(C(O,["version","definition","launch"],A,["detailRouteCode"]),bs(O.launch,`${A}/launch`),O.detailRouteCode!==void 0){let w=Os(O.detailRouteCode,`${A}/detailRouteCode`);for(let[j,L,Q]of[["desktop",w.desktop,["admin","user"]],["mobile",w.mobile,["user"]]]){let ee=`${A}/detailRouteCode/${j}`,Y=i.get(L);Y||m("NATIVE_WORKFLOW_DETAIL_ROUTE_MISSING",ee),Q.some(P=>P===Y.surface)||m("NATIVE_WORKFLOW_DETAIL_ROUTE_SURFACE_INVALID",ee);let ge=Oe(Y.path,ee),oe=[...ge.matchAll(/:([A-Za-z][A-Za-z0-9_]*)/g)].map(P=>P[1]);(ge.includes("*")||oe.length!==1||oe[0]!=="instanceId")&&m("NATIVE_WORKFLOW_DETAIL_ROUTE_PATH_INVALID",ee)}}let b=N(O.definition,`${A}/definition`),g=`${b.code}:${ut(O.version,`${A}/version`)}`;t.has(g)&&m("NATIVE_WORKFLOW_DEFINITION_DUPLICATE",A),t.add(g),gc(b,`${A}/definition`);let I=Ro(b);I.length&&m(I[0],`${A}/definition/launchPreflight`);let T=wr(b);T.length&&m(T[0],`${A}/definition/approvedDelegation`);let l=Rr(b,e.backend.operations);l.length&&m(l[0],`${A}/definition/commandHandlers`),_c(b.subject,n,`${A}/definition/subject`);let y=b.commandHandlers?.resubmit?.derivedSubjectFields||[],R=n.get(b.subject.resourceCode);for(let w of y){let j=R?.schema.fields.find(L=>L.code===w);(!j||j.system===!0||R?.surface?.fields?.[w]?.system===!0)&&m("WORKFLOW_CORRECTION_DERIVED_SUBJECT_FIELDS_INVALID",`${A}/definition/commandHandlers/resubmit/derivedSubjectFields`)}let h=un(b,new Map((n.get(b.subject.resourceCode)?.schema.fields||[]).map(w=>[w.code,{...n.get(b.subject.resourceCode)?.surface?.fields?.[w.code],...w,system:["id","revision","createdAt","updatedAt","createdBy","updatedBy"].includes(w.code)}])),new Map([...n].map(([w,j])=>[w,new Map(j.schema.fields.map(L=>[L.code,{...j.surface?.fields?.[L.code],...L,system:["id","revision","createdAt","updatedAt","createdBy","updatedBy"].includes(L.code)}]))])),jt(n.get(b.subject.resourceCode)?.schema||{}));h.length&&m(h[0],`${A}/definition/taskPages`);let $=tr(b,{appCode:e.appCode,capabilities:e.authz.capabilities.map(w=>w.code),fields:new Map((n.get(b.subject.resourceCode)?.schema.fields||[]).map(w=>[w.code,w]))});$.length&&m("NATIVE_WORKFLOW_INSTANCE_COMMAND_POLICY_INVALID",`${A}/definition/instanceCommands`,{errors:$}),b.title===b.code&&m("NATIVE_WORKFLOW_USER_TITLE_REQUIRED",`${A}/definition/title`),o.set(g,b)}let r=new Set,d=new Map;for(let[_,E]of e.workflows.bindings.entries()){let A=N(E,`/config/workflows/bindings/${_}`),O=N(A.binding,`/config/workflows/bindings/${_}/binding`),b=`${O.workflowCode}:${ut(A.version,`/config/workflows/bindings/${_}/version`)}`;r.has(b)&&m("NATIVE_WORKFLOW_BINDING_DUPLICATE",`/config/workflows/bindings/${_}`),r.add(b),Ac(O,`/config/workflows/bindings/${_}/binding`),d.set(b,O)}let s=new Set,a=new Map;for(let[_,E]of e.workflows.activations.entries()){let A=`/config/workflows/activations/${_}`,O=N(E,A);C(O,["workflowCode","definitionVersion","bindingVersion","acceptedCommandDeactivationPolicy"],A,["environmentKey"]);let b=v(O.workflowCode,`${A}/workflowCode`);s.has(b)&&m("NATIVE_WORKFLOW_ACTIVATION_DUPLICATE",A),s.add(b);let g=`${b}:${ut(O.definitionVersion,`${A}/definitionVersion`)}`,I=`${b}:${ut(O.bindingVersion,`${A}/bindingVersion`)}`;t.has(g)||m("NATIVE_WORKFLOW_DEFINITION_REFERENCE_MISSING",`${A}/definitionVersion`),r.has(I)||m("NATIVE_WORKFLOW_BINDING_REFERENCE_MISSING",`${A}/bindingVersion`);let T=o.get(g),l=d.get(I),y=Ro(T,l);y.length&&m(y[0],A);let R=Oo(T,l);R.length&&m(R[0],A),(!["finish-pinned","cancel-on-deactivate"].includes(O.acceptedCommandDeactivationPolicy)||O.acceptedCommandDeactivationPolicy!==T.acceptedCommandDeactivationPolicy)&&m("NATIVE_WORKFLOW_COMMAND_DEACTIVATION_POLICY_MISMATCH",`${A}/acceptedCommandDeactivationPolicy`),Ec(T,l,`/config/workflows/activations/${_}`);try{let h=n.get(T.subject.resourceCode)?.schema.fields||[];oi(T,l,new Map(h.map($=>[$.code,$])),`${A}/bindings`,new Map([...n].map(([$,w])=>[$,new Map(w.schema.fields.map(j=>[j.code,j]))])))}catch(h){throw h instanceof Me&&m(h.code,h.pointer),h}a.set(b,l)}let c=Wr([...a.values()]);c.length&&m(c[0],"/config/workflows/activations");let f=new Set;e.workflows.providers.forEach((_,E)=>{let A=`/config/workflows/providers/${E}`,O=N(_,A);C(O,["code","endpointPath","timeoutMs"],A,!0);let b=v(O.code,`${A}/code`);f.has(b)&&m("NATIVE_WORKFLOW_PROVIDER_DUPLICATE",`${A}/code`),f.add(b),Oe(O.endpointPath,`${A}/endpointPath`),O.timeoutMs!==void 0&&se(O.timeoutMs,`${A}/timeoutMs`,100,1e4)});for(let[_,E]of a.entries())for(let[A,O]of Object.entries(N(E.bindings,"/config/workflows/bindings/*/binding/bindings"))){let b=N(O,`/config/workflows/${_}/bindings/${A}`);b.provider==="application_provider"&&!f.has(b.providerCode)&&m("NATIVE_WORKFLOW_PROVIDER_REFERENCE_MISSING",`/config/workflows/${_}/bindings/${A}/providerCode`)}let u=new Set(e.authz.roles.map(_=>_.code)),p=new Set;e.workflows.editableParameters.forEach((_,E)=>{let A=`/config/workflows/editableParameters/${E}`,O=N(_,A);C(O,["code","workflowCode","bindingKey","label","valueType","required","allowedRoleCodes","allowedProviderCodes","maxItems"],A,!0);let b=v(O.code,`${A}/code`);p.has(b)&&m("NATIVE_WORKFLOW_EDITABLE_PARAMETER_DUPLICATE",`${A}/code`),p.add(b);let g=Nn(O.workflowCode,`${A}/workflowCode`),I=In(O.bindingKey,`${A}/bindingKey`),T=a.get(g);(!T||!N(T.bindings,`${A}/bindingKey`)[I])&&m("NATIVE_WORKFLOW_EDITABLE_BINDING_MISSING",`${A}/bindingKey`),S(O.label,`${A}/label`,255),["role_code","user_ids","provider_code"].includes(O.valueType)||m("NATIVE_WORKFLOW_EDITABLE_VALUE_TYPE_INVALID",`${A}/valueType`);for(let l of V(O.allowedRoleCodes||[],`${A}/allowedRoleCodes`,100))u.has(l)||m("NATIVE_ROLE_REFERENCE_MISSING",`${A}/allowedRoleCodes`);for(let l of V(O.allowedProviderCodes||[],`${A}/allowedProviderCodes`,100))f.has(l)||m("NATIVE_WORKFLOW_PROVIDER_REFERENCE_MISSING",`${A}/allowedProviderCodes`);O.required!==void 0&&ft(O.required,`${A}/required`),O.maxItems!==void 0&&se(O.maxItems,`${A}/maxItems`,1,200)})}function _c(e,t,o){let n=N(e,o);C(n,["resourceCode","factProjection"],o,["summaryFields"]);let i=H(n.resourceCode,`${o}/resourceCode`),r=t.get(i);r||m("NATIVE_WORKFLOW_SUBJECT_RESOURCE_MISSING",`${o}/resourceCode`);let d=new Set(D(N(r.schema,`${o}/resourceCode`).fields,`${o}/resourceCode`,500).map((c,f)=>G(N(c,`${o}/resourceCode/${f}`).code,`${o}/resourceCode/${f}`))),s=N(n.factProjection,`${o}/factProjection`),a=Object.entries(s);(a.length<1||a.length>64)&&m("NATIVE_WORKFLOW_SUBJECT_FACT_PROJECTION_INVALID",`${o}/factProjection`);for(let[c,f]of a){Ad.test(c)||m("NATIVE_WORKFLOW_SUBJECT_FACT_KEY_INVALID",`${o}/factProjection/${c}`);let u=G(f,`${o}/factProjection/${c}`);d.has(u)||m("NATIVE_WORKFLOW_SUBJECT_FIELD_MISSING",`${o}/factProjection/${c}`)}if(n.summaryFields!==void 0){let c=V(n.summaryFields,`${o}/summaryFields`,Ed).map((E,A)=>G(E,`${o}/summaryFields/${A}`)),f=t.get(i),u=f.surface&&typeof f.surface=="object"&&!Array.isArray(f.surface)?f.surface:{},p=u.fields&&typeof u.fields=="object"&&!Array.isArray(u.fields)?u.fields:{},_=new Map(D(N(f.schema,`${o}/resourceCode`).fields,`${o}/resourceCode`,500).map((E,A)=>{let O=N(E,`${o}/resourceCode/${A}`);return[String(O.code),O]}));for(let[E,A]of c.entries()){let O=_.get(A),b=p[A],g=String(O?.type||""),I=O?.maxLength;(!O||O.system===!0||b&&typeof b=="object"&&!Array.isArray(b)&&b.system===!0||["id","revision","created_by","updated_by","created_at","updated_at"].includes(A)||!yd.has(g)||g==="text.long"&&typeof I=="number"&&Number.isFinite(I)&&I>Id)&&m("NATIVE_WORKFLOW_SUBJECT_SUMMARY_FIELDS_INVALID",`${o}/summaryFields/${E}`)}}}function gc(e,t){C(e,["schemaVersion","code","title","subject","acceptedCommandDeactivationPolicy","startAt","inputSchema","nodes"],t,["organizationContext","instanceCommands","readability","taskPages","rejectionNotification","commandHandlers","launchPreflight","approvedDelegation"]),F(e.schemaVersion,"openxiangda.workflow-definition/v2",`${t}/schemaVersion`),Nn(e.code,`${t}/code`),S(e.title,`${t}/title`,255),["finish-pinned","cancel-on-deactivate"].includes(e.acceptedCommandDeactivationPolicy)||m("NATIVE_WORKFLOW_COMMAND_DEACTIVATION_POLICY_REQUIRED",`${t}/acceptedCommandDeactivationPolicy`);let o=N(e.nodes,`${t}/nodes`),n=Object.keys(o);(n.length===0||n.length>200)&&m("NATIVE_WORKFLOW_NODE_COUNT_INVALID",`${t}/nodes`);let i=S(e.startAt,`${t}/startAt`,128),r=lr(e);r.length&&m(r[0],`${t}/readability`);let d=Oo(e);d.length&&m(d[0],`${t}/nodes`);let s=No(e);s.length&&m(s[0],`${t}/nodes`);let a=ht(e);a.length&&m(a[0],`${t}/nodes`);let c=Or(e);c.length&&m(c[0],`${t}/nodes`);let f=Tr(e);f.length&&m(f[0],`${t}/rejectionNotification`);let u=Io(e);u.length&&m(u[0],`${t}/nodes`);let p=un(e);p.length&&m(p[0],`${t}/taskPages`);let _=on(e);_.length&&m(_[0],`${t}/nodes`),o[i]||m("NATIVE_WORKFLOW_START_NODE_MISSING",`${t}/startAt`);let E=new Map;for(let[g,I]of Object.entries(o)){let T=`${t}/nodes/${g}`,l=N(I,T);F(l.id,g,`${T}/id`),["approval","condition","end","cc","action","correction"].includes(l.kind)||m("NATIVE_WORKFLOW_NODE_KIND_INVALID",`${T}/kind`);let y=[];if(l.kind==="approval"){S(l.title,`${T}/title`,255),In(l.binding,`${T}/binding`),["single","any","all","sequence"].includes(l.mode)||m("NATIVE_WORKFLOW_APPROVAL_MODE_INVALID",`${T}/mode`),y.push(S(l.onApprove,`${T}/onApprove`,128),S(l.onReject,`${T}/onReject`,128));for(let R of V(l.returnTargets||[],`${T}/returnTargets`,200))o[R]||m("NATIVE_WORKFLOW_TARGET_MISSING",`${T}/returnTargets`);for(let R of V(l.allowedOperations||[],`${T}/allowedOperations`,20))Od.has(R)||m("NATIVE_WORKFLOW_OPERATION_INVALID",`${T}/allowedOperations`)}else if(l.kind==="correction"){let R=Sr(e);R.length&&m(R[0],T)}else if(l.kind==="action")y.push(S(l.next,`${T}/next`,128));else if(l.kind==="cc")S(l.title,`${T}/title`,255),In(l.binding,`${T}/binding`),y.push(S(l.next,`${T}/next`,128));else if(l.kind==="condition"){let R=D(l.branches,`${T}/branches`,100);R.length===0&&m("NATIVE_WORKFLOW_BRANCH_REQUIRED",`${T}/branches`),R.forEach((h,$)=>{let w=N(h,`${T}/branches/${$}`);vt(w.when,`${T}/branches/${$}/when`,0),y.push(S(w.target,`${T}/branches/${$}/target`,128))}),y.push(S(l.otherwise,`${T}/otherwise`,128))}else S(l.title,`${T}/title`,255),S(l.outcome,`${T}/outcome`,128);for(let R of y)o[R]||m("NATIVE_WORKFLOW_TARGET_MISSING",T);E.set(g,y)}let A=new Set,O=new Set,b=g=>{if(O.has(g)&&m("NATIVE_WORKFLOW_CYCLE_FORBIDDEN",`${t}/nodes/${g}`),!A.has(g)){A.add(g),O.add(g);for(let I of E.get(g)||[])b(I);O.delete(g)}};b(i);for(let g of[...A]){let I=o[g];if(I?.kind==="approval")for(let T of I.returnTargets||[])o[T]?.kind==="correction"&&A.add(T)}A.size!==n.length&&m("NATIVE_WORKFLOW_NODE_UNREACHABLE",`${t}/nodes`)}function vt(e,t,o){o>20&&m("NATIVE_WORKFLOW_EXPRESSION_DEPTH_EXCEEDED",t);let n=N(e,t),i=S(n.op,`${t}/op`,16);if(i!=="literal"){if(i==="path"){let r=S(n.path,`${t}/path`,255);(!/^[A-Za-z][A-Za-z0-9_.-]{0,254}$/.test(r)||r.split(".").some(d=>["__proto__","constructor","prototype"].includes(d)))&&m("NATIVE_WORKFLOW_EXPRESSION_PATH_INVALID",`${t}/path`);return}if(["eq","neq","gt","gte","lt","lte","in","contains"].includes(i)){vt(n.left,`${t}/left`,o+1),vt(n.right,`${t}/right`,o+1);return}if(["and","or"].includes(i)){let r=D(n.values,`${t}/values`,100);r.length===0&&m("NATIVE_WORKFLOW_EXPRESSION_EMPTY",`${t}/values`),r.forEach((d,s)=>vt(d,`${t}/values/${s}`,o+1));return}if(["not","exists"].includes(i)){vt(n.value,`${t}/value`,o+1);return}m("NATIVE_WORKFLOW_EXPRESSION_OPERATOR_INVALID",`${t}/op`)}}function Ac(e,t){F(e.schemaVersion,"openxiangda.workflow-binding/v2",`${t}/schemaVersion`),Nn(e.workflowCode,`${t}/workflowCode`);let o=N(e.bindings,`${t}/bindings`);Object.keys(o).length>200&&m("NATIVE_WORKFLOW_BINDING_LIMIT_EXCEEDED",`${t}/bindings`);for(let[n,i]of Object.entries(o)){In(n,`${t}/bindings/${n}`);let r=N(i,`${t}/bindings/${n}`),d=pr(r);d.length&&m(d[0],`${t}/bindings/${n}/selectedInputPath`);let s=an(r);s.length&&m(s[0],`${t}/bindings/${n}/roleCodes`);let a=S(r.provider,`${t}/bindings/${n}/provider`,64);if(["fixed_users","initiator","input_users","form_field_users","department_supervisor","app_role","app_role_in_scope","business_relation","previous_node_actor","initiator_select","application_provider"].includes(a)||m("NATIVE_WORKFLOW_BINDING_PROVIDER_INVALID",`${t}/bindings/${n}/provider`),a==="fixed_users"&&(Array.isArray(r.users)||m("NATIVE_WORKFLOW_BINDING_USERS_REQUIRED",`${t}/bindings/${n}/users`),D(r.users,`${t}/bindings/${n}/users`,200)),["input_users","form_field_users"].includes(a)&&S(r.inputPath,`${t}/bindings/${n}/inputPath`,255),["app_role","app_role_in_scope","initiator_select"].includes(a)&&r.roleCodes===void 0&&v(r.roleCode,`${t}/bindings/${n}/roleCode`),a==="department_supervisor"&&S(r.departmentIdFrom,`${t}/bindings/${n}/departmentIdFrom`,255),a==="application_provider"&&v(r.providerCode,`${t}/bindings/${n}/providerCode`),r.routing!==void 0){let c=fn(r.routing);c.length&&m(c[0],`${t}/bindings/${n}/routing`)}}}function Ec(e,t,o){F(t.workflowCode,e.code,`${o}/workflowCode`);let n=N(t.bindings,`${o}/bindings`);for(let[s,a]of Object.entries(n))a.provider==="fixed_users"&&!a.users.length&&!yr(e,s)&&m("NATIVE_WORKFLOW_BINDING_USERS_REQUIRED",`${o}/bindings/${s}/users`);let i=No(e,t);i.length&&m(i[0],o);let r=Io(e,t);r.length&&m(r[0],o);let d=on(e,t);d.length&&m(d[0],o);for(let[s,a]of Object.entries(N(e.nodes,`${o}/nodes`))){let c=N(a,`${o}/nodes/${s}`);["approval","cc"].includes(c.kind)&&!n[c.binding]&&m("NATIVE_WORKFLOW_BINDING_REFERENCE_MISSING",`${o}/nodes/${s}/binding`)}}function Ic(e,t,o){let n=N(t.routeManifest,"/contracts/routeManifest"),i=N(e.routeManifest,"/contracts/routeManifest"),r=new Map;for(let f of D(o.data?.resources,"/config/data/resources",B.resources)){let u=N(f,"/config/data/resources");r.set(String(u.code||""),u)}let d=new Set(D(i.routes,"/contracts/routeManifest/routes",B.routes).map(f=>String(N(f,"/contracts/routeManifest/routes").code||""))),s=[];for(let f of D(n.routes,"/contracts/routeManifest/routes",B.routes)){let u=N(f,"/contracts/routeManifest/routes"),p=String(u.kind||"");if(p!=="resource-records"&&p!=="resource-submit")continue;let _=String(u.resourceCode||""),E=r.get(_);E||m("NATIVE_ROUTE_MANIFEST_RESOURCE_UNKNOWN","/contracts/routeManifest/routes");let O=`user.${_}.${p==="resource-records"?"records":"submit"}`;F(String(u.code||""),O,"/contracts/routeManifest/routes/code");let b=p==="resource-records"?"read":"create",g=String(N(E.capabilities,"/config/data/resources/capabilities")[b]||"");for(let I of["desktop","mobile"]){let T=N(u[I],`/contracts/routeManifest/routes/${I}`),l=I==="mobile"?"/m/my/":"/my/",y=p==="resource-records"?`${l}${_}`:`${l}${_}/submit`;F(String(T.path||""),y,`/contracts/routeManifest/routes/${I}/path`),F(String(T.capability||""),g,`/contracts/routeManifest/routes/${I}/capability`),F(String(T.routeCode||""),`${O}.${I}`,`/contracts/routeManifest/routes/${I}/routeCode`)}(d.has(O)||s.some(I=>String(I.code)===O))&&m("NATIVE_ROUTE_MANIFEST_DUPLICATE","/contracts/routeManifest/routes/code"),s.push(u)}if(!s.length)return;i.routes=D([...i.routes,...s],"/contracts/routeManifest/routes",1e3).sort((f,u)=>Ie(String(N(f,"x").code||""),String(N(u,"x").code||"")));let a=String(N(n.rootEntry,"x").code||"");if(s.find(f=>String(f.code)===a&&f.kind==="resource-records")){let f=N(n.rootEntry,"x");i.rootEntry={code:a,desktop:String(f.desktop||""),mobile:String(f.mobile||"")}}i.digest=Z({schemaVersion:i.schemaVersion,appCode:i.appCode,devicePolicy:i.devicePolicy,rootEntry:i.rootEntry,authentication:i.authentication,routes:i.routes})}function Ye(e,t,o){let n=N(e,t);C(n,["schemaVersion","appCode","code","name","schema","surface","invariants","decimalReservationLifecycle","uniqueKeys","workflowHistory","recordPrint","recordComments","recordDeletion","capabilities","dataPolicyCode","fieldPolicies"],t,!0),F(n.schemaVersion,"openxiangda.data-resource/v2",`${t}/schemaVersion`),F(n.appCode,o,`${t}/appCode`);let i=H(n.code,`${t}/code`),r=S(n.name,`${t}/name`,255),d=N(n.schema,`${t}/schema`);C(d,["fields","ownedRowLimit"],`${t}/schema`,!0),d.ownedRowLimit!==void 0&&!mt(d.ownedRowLimit)&&m("NATIVE_DATA_OWNED_ROW_LIMIT_INVALID",`${t}/schema/ownedRowLimit`);let s,a,c,f;try{c=oo(n.decimalReservationLifecycle,`${t}/decimalReservationLifecycle`),s=Bn(d.fields,`${t}/schema/fields`),f=Ji(n.uniqueKeys,s,`${t}/uniqueKeys`),a=fi(n.invariants,s,`${t}/invariants`),Zn(n.surface,s,`${t}/surface`)}catch(E){throw(E instanceof Re||E instanceof Me||E instanceof rt||E instanceof Rt)&&m(E.code,E.pointer),E}if(n.recordComments!==void 0){let E=N(n.recordComments,`${t}/recordComments`);C(E,["read","create"],`${t}/recordComments`);for(let A of["read","create"]){let O=E[A];(!Array.isArray(O)||O.length>20||O.some(b=>typeof b!="string"||!b.trim())||new Set(O).size!==O.length)&&m("NATIVE_RECORD_COMMENTS_POLICY_INVALID",`${t}/recordComments/${A}`)}}if(n.recordDeletion!==void 0){let E=N(n.recordDeletion,`${t}/recordDeletion`);C(E,["delete"],`${t}/recordDeletion`);let A=E.delete;(!Array.isArray(A)||A.length>20||A.some(O=>typeof O!="string"||!O.trim())||new Set(A).size!==A.length)&&m("NATIVE_RECORD_DELETION_DELETE_INVALID",`${t}/recordDeletion/delete`)}if(n.recordPrint!==void 0){let E=N(n.recordPrint,`${t}/recordPrint`);C(E,["read"],`${t}/recordPrint`);let A=E.read;(!Array.isArray(A)||A.length>20||A.some(O=>typeof O!="string"||!O.trim())||new Set(A).size!==A.length)&&m("NATIVE_RECORD_PRINT_READ_INVALID",`${t}/recordPrint/read`)}if(n.workflowHistory!==void 0){let E=N(n.workflowHistory,`${t}/workflowHistory`);C(E,["read"],`${t}/workflowHistory`);let A=E.read;(!Array.isArray(A)||A.length>20||A.some(O=>typeof O!="string"||!O.trim())||new Set(A).size!==A.length)&&m("NATIVE_WORKFLOW_HISTORY_READ_INVALID",`${t}/workflowHistory/read`)}let u=new Set(s.map(E=>E.code)),p=N(n.capabilities,`${t}/capabilities`);C(p,["read","create","update","delete"],`${t}/capabilities`);let _=N(n.fieldPolicies,`${t}/fieldPolicies`);for(let[E,A]of Object.entries(_)){!u.has(E)&&!_t(E)&&m("NATIVE_DATA_FIELD_POLICY_FIELD_MISSING",`${t}/fieldPolicies/${E}`);let O=`${t}/fieldPolicies/${E}`,b=N(A,O);_t(E)&&(C(b,["read"],O,!0),(!Array.isArray(b.read)||b.read.length>20||b.read.some(g=>typeof g!="string"||!g.trim())||new Set(b.read).size!==b.read.length)&&m("NATIVE_DATA_AUDIT_READ_POLICY_INVALID",`${O}/read`)),C(b,["read","create","update","mask"],O,!0),b.mask!==void 0&&!["omit","null"].includes(b.mask)&&m("NATIVE_DATA_FIELD_POLICY_MASK_INVALID",`${O}/mask`)}return{...n,code:i,name:r,schema:{fields:s,...d.ownedRowLimit!==void 0?{ownedRowLimit:d.ownedRowLimit}:{}},...n.invariants===void 0?{}:{invariants:a},...c?{decimalReservationLifecycle:c}:{},...f!==void 0?{uniqueKeys:f}:{},capabilities:p,fieldPolicies:_}}function Ns(e){return[{code:`app:${e}:directory:read`,kind:"platform",name:"\u8BFB\u53D6\u53D7\u9650\u7EC4\u7EC7\u76EE\u5F55",source:"platform"},...[["app:role:read","\u67E5\u770B\u89D2\u8272\u4E0E\u6388\u6743"],["app:role:define","\u5B9A\u4E49\u624B\u5DE5\u89D2\u8272"],["app:role:assign","\u5206\u914D\u89D2\u8272\u6210\u5458"],["app:role:grant-capability","\u6388\u4E88\u89D2\u8272\u80FD\u529B"],["app:scope-grant:manage","\u7BA1\u7406\u6570\u636E\u8303\u56F4"],["app:super-admin:manage","\u7BA1\u7406\u5E94\u7528\u6700\u9AD8\u7BA1\u7406\u5458"]].map(([t,o])=>({code:t,kind:"platform",name:o,source:"platform"}))]}function ss(e,t,o,n){let i=e.toString("utf8"),r;try{r=JSON.parse(i)}catch{m(o,t)}let d=N(r,t);return X(d)!==i&&m(n,t),d}function gn(e,t,o){let n=0,i=(r,d,s)=>{if(n+=1,n>o&&m("NATIVE_ARTIFACT_NODE_LIMIT_EXCEEDED",d),s>Rd&&m("NATIVE_ARTIFACT_DEPTH_LIMIT_EXCEEDED",d),typeof r=="string"){Buffer.byteLength(r)>Lo&&m("NATIVE_ARTIFACT_STRING_LIMIT_EXCEEDED",d);return}if(Array.isArray(r)){r.forEach((a,c)=>i(a,`${d}/${c}`,s+1));return}if(!(!r||typeof r!="object"))for(let[a,c]of Object.entries(r))["__proto__","prototype","constructor"].includes(a)&&m("NATIVE_ARTIFACT_DANGEROUS_KEY",`${d}/${a}`),yc(a)&&m("NATIVE_ARTIFACT_RUNTIME_FIELD_FORBIDDEN",`${d}/${a}`),i(c,`${d}/${a}`,s+1)};i(e,t,0)}function yc(e){return["environmentKey","environmentId","secretValue","ciphertext","oauthClient","oauthClientId","oauthClientSecret","signingSecret","kubernetesNamespace","nodePort","productionUrl"].includes(e)}function lt(e){return{value:e,digest:Z(e)}}function as(e,t,o,n){typeof e!="string"&&!Buffer.isBuffer(e)&&!(e instanceof Uint8Array)&&m("NATIVE_ARTIFACT_BYTES_REQUIRED",o);let i=Buffer.isBuffer(e)?e:Buffer.from(e);return i.byteLength===0&&m("NATIVE_ARTIFACT_EMPTY",o),i.byteLength>t&&m(n,o),i}function ds(e,t,o,n){let i=yn.createHash("sha256").update(e).digest("hex");yn.timingSafeEqual(Buffer.from(i),Buffer.from(t))||m(n,o)}function N(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&m("NATIVE_OBJECT_REQUIRED",t),e}function D(e,t,o){return Array.isArray(e)||m("NATIVE_ARRAY_REQUIRED",t),e.length>o&&m("NATIVE_ARRAY_LIMIT_EXCEEDED",t),e}function V(e,t,o){let n=D(e,t,o).map((i,r)=>S(i,`${t}/${r}`,255));return new Set(n).size!==n.length&&m("NATIVE_ARRAY_DUPLICATE",t),n}function S(e,t,o){return(typeof e!="string"||e.length===0||e.length>o)&&m("NATIVE_STRING_INVALID",t),e}function Go(e,t,o){return(typeof e!="string"||e.length>o)&&m("NATIVE_STRING_INVALID",t),e}function v(e,t){let o=S(e,t,128);return cd.test(o)||m("NATIVE_CODE_INVALID",t),o}function H(e,t){let o=S(e,t,64);return ud.test(o)||m("NATIVE_RESOURCE_CODE_INVALID",t),o}function G(e,t){let o=S(e,t,63);return fd.test(o)||m("NATIVE_FIELD_CODE_INVALID",t),o}function Nn(e,t){let o=S(e,t,128);return _d.test(o)||m("NATIVE_WORKFLOW_CODE_INVALID",t),o}function In(e,t){let o=S(e,t,128);return gd.test(o)||m("NATIVE_WORKFLOW_BINDING_CODE_INVALID",t),o}function me(e,t,o){let n=S(e,t,255);return dd.test(n)||m("NATIVE_CAPABILITY_CODE_INVALID",t),!n.startsWith(`app:${o}:`)&&!Ns(o).some(i=>i.code===n)&&m("NATIVE_CAPABILITY_APP_MISMATCH",t),n}function Oe(e,t){let o=S(e,t,2048);return(!o.startsWith("/")||o.startsWith("//")||o.includes("..")||o.includes("?")||o.includes("#"))&&m("NATIVE_ABSOLUTE_PATH_INVALID",t),o}function ut(e,t){return(!Number.isInteger(e)||Number(e)<1)&&m("NATIVE_POSITIVE_INTEGER_REQUIRED",t),Number(e)}function se(e,t,o,n){return(!Number.isInteger(e)||Number(e)<o||Number(e)>n)&&m("NATIVE_INTEGER_OUT_OF_RANGE",t),Number(e)}function ft(e,t){return typeof e!="boolean"&&m("NATIVE_BOOLEAN_REQUIRED",t),e}function Uo(e,t){let o=S(e,t,64).toLowerCase();return sd.test(o)||m("NATIVE_DIGEST_INVALID",t),o}function F(e,t,o){e!==t&&m("NATIVE_VALUE_MISMATCH",o)}function C(e,t,o,n=!1){let i=new Set([...t,...Array.isArray(n)?n:[]]);for(let r of Object.keys(e))i.has(r)||m("NATIVE_PROPERTY_UNKNOWN",`${o}/${r}`);if(n!==!0)for(let r of t)Object.prototype.hasOwnProperty.call(e,r)||m("NATIVE_PROPERTY_REQUIRED",`${o}/${r}`)}function te(e,t){return[...e].sort((o,n)=>Ie(t(o),t(n)))}function M(e){return[...new Set(e)].sort(Ie)}function cs(e){return[...new Set(e)].sort((t,o)=>t-o)}function Ie(e,t){return e===t?0:e<t?-1:1}function Ts(e){return!e||typeof e!="object"||Object.isFrozen(e)||(Object.freeze(e),Object.values(e).forEach(t=>Ts(t))),e}function Mo(e,t,o){if(Vo(e,t))return o;if(Array.isArray(e)&&Array.isArray(t)){let n=Math.max(e.length,t.length);for(let i=0;i<n;i+=1)if(!Vo(e[i],t[i]))return Mo(e[i],t[i],`${o}/${i}`)}if(e&&t&&typeof e=="object"&&typeof t=="object"&&!Array.isArray(e)&&!Array.isArray(t)){let n=M([...Object.keys(e),...Object.keys(t)]);for(let i of n){let r=e[i],d=t[i];if(!Vo(r,d))return Mo(r,d,`${o}/${i}`)}}return o}function Vo(e,t){return e===void 0||t===void 0?e===t:X(e)===X(t)}function m(e,t,o={}){throw new jo(e,t,o)}var dp="openxiangda.workflow-step-data-command/v1",bc="openxiangda.workflow-step-data-resolution/v1";function cp(e,t,o=!1){let n=s=>!!s&&typeof s=="object"&&!Array.isArray(s),i=s=>typeof s=="string"&&/^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(s),r=()=>{throw new Error("WORKFLOW_STEP_DATA_RESPONSE_INVALID")};if(!n(e)||e.schemaVersion!==bc||e.executionId!==t||Object.keys(e).some(s=>!["schemaVersion","executionId","outcome","transaction"].includes(s)))return r();if(e.outcome==="not_observed"&&!Object.hasOwn(e,"transaction")&&!o)return e;let d=e.transaction;if(e.outcome!=="committed"||!n(d)||d.schemaVersion!=="openxiangda.data-transaction-result/v2"||d.idempotencyKey!==`workflow-step:${t}`||typeof d.replayed!="boolean"||!Array.isArray(d.items)||d.items.length<1||d.items.length>ri||d.evaluatedAt!==void 0&&(typeof d.evaluatedAt!="string"||!Number.isFinite(Date.parse(d.evaluatedAt))))return r();for(let[s,a]of d.items.entries()){if(!n(a)||a.index!==s)return r();if(a.operation==="emitEvent"){if(typeof a.eventType!="string"||!a.eventType||!i(a.eventId))return r()}else if(!["create","update","delete","increment"].includes(a.operation)||typeof a.resourceCode!="string"||!a.resourceCode||!i(a.id)||!Number.isSafeInteger(a.revision)||a.revision<1)return r()}return e}var up=50,fp=131072,qo=class extends Error{constructor(o){super("OPENXIANGDA_NATIVE_AUTHZ_BATCH_INPUT_INVALID");this.pointer=o}pointer;code="OPENXIANGDA_NATIVE_AUTHZ_BATCH_INPUT_INVALID";status=400};function pp(e){let t=u=>{throw new qo(u)},o=(u,p)=>((!u||typeof u!="object"||Array.isArray(u))&&t(p),u),n=(u,p,_)=>{for(let E of Object.keys(u))p.includes(E)||t(`${_}/${E}`)},i=(u,p,_)=>((typeof u!="string"||!u.trim()||u.length>p)&&t(_),u),r=(u,p)=>{let _=i(u,36,p);return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(_)||t(p),_.toLowerCase()},d=o(e,""),s;try{s=new TextEncoder().encode(JSON.stringify(d)).byteLength}catch{t("")}s>131072&&t(""),n(d,["schemaVersion","environmentKey","items"],""),d.schemaVersion!=="openxiangda.native-role-membership-batch-request/v2"&&t("/schemaVersion"),d.environmentKey!==void 0&&!["preproduction","production"].includes(String(d.environmentKey))&&t("/environmentKey"),(!Array.isArray(d.items)||d.items.length<1||d.items.length>50)&&t("/items");let a=new Set,c=new Set,f;for(let[u,p]of d.items.entries()){let _=`/items/${u}`,E=o(p,_);["create","update","revoke"].includes(String(E.operation))||t(`${_}/operation`),f??=E.operation,f!==E.operation&&t(`${_}/operation`),n(E,["operation","operationId","reason",...f==="create"?["userId","roleCode"]:["membershipId","expectedRevision"],...f!=="revoke"?["scopeGrants","validFrom","validTo"]:[]],_);let A=r(E.operationId,`${_}/operationId`);a.has(A)&&t(`${_}/operationId`),a.add(A),i(E.reason,1e3,`${_}/reason`);let O;if(f==="create"){let b=i(E.userId,255,`${_}/userId`),g=i(E.roleCode,128,`${_}/roleCode`);/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/.test(g)||t(`${_}/roleCode`),O=JSON.stringify([b,g])}else O=r(E.membershipId,`${_}/membershipId`),(!Number.isSafeInteger(E.expectedRevision)||Number(E.expectedRevision)<1)&&t(`${_}/expectedRevision`);c.has(O)&&t(_),c.add(O),E.scopeGrants!==void 0&&(!Array.isArray(E.scopeGrants)||E.scopeGrants.length>100)&&t(`${_}/scopeGrants`);for(let b of["validFrom","validTo"])E[b]!==void 0&&E[b]!==null&&i(E[b],64,`${_}/${b}`)}}var ws="openxiangda.workflow-delegation-administration/v2",Ss="openxiangda.workflow-delegation-mutation/v2",Rs="openxiangda.workflow-delegation-preview/v2";var Lt={type:"string",format:"uuid",pattern:"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$"},_e={type:"string",minLength:1,maxLength:255},Xe={type:"string",format:"date-time"},pt={type:"integer",minimum:1},Oc={anyOf:[Xe,{type:"null"}]},zo={anyOf:[_e,{type:"null"}]},Ds={anyOf:[{type:"string",pattern:"^[A-Za-z0-9._:-]{1,128}$"},{type:"null"}]},Tn={type:"string",pattern:"^membership:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},ks={const:"future-assignments-only"},Jo={schemaVersion:{const:ws},id:Lt,appCode:_e,environmentKey:_e,workflowCode:zo,nodeId:Ds,delegatorUserId:_e,delegateUserId:_e,delegatorRoleSubjectKey:Tn,delegateRoleSubjectKey:Tn,validFrom:Xe,validTo:Xe,status:{enum:["active","revoked","expired"]},reason:{type:"string",minLength:1,maxLength:4e3},createdBy:_e,createdAt:Xe,revokedAt:Oc,revision:pt,roleCode:_e,roleName:_e,delegatorDisplayName:_e,delegateDisplayName:_e,delegatorRoleSubjectRevision:pt,delegateRoleSubjectRevision:pt,effectiveState:{enum:["active","scheduled","expired","revoked","ineligible"]},evaluatedAt:Xe,issues:{type:"array",maxItems:20,uniqueItems:!0,items:_e},canRevoke:{type:"boolean"},revokedBy:zo,revokeReason:{type:["string","null"],maxLength:4e3},taskPolicy:ks},Ho={type:"object",additionalProperties:!1,required:Object.keys(Jo).filter(e=>e!=="nodeId"),properties:Jo},_p={$id:ws,...Ho},$s={schemaVersion:{const:Ss},operationId:Lt,environmentKey:{enum:["preproduction","production"]},reason:{type:"string",minLength:1,maxLength:2e3,pattern:"\\S"}},Cs={...$s,operation:{const:"create"},workflowCode:zo,nodeId:Ds,delegatorRoleSubjectKey:Tn,expectedDelegatorRevision:pt,delegateUserId:_e,delegateRoleSubjectKey:Tn,expectedDelegateRevision:pt,validFrom:Xe,validTo:Xe},hs={...$s,operation:{const:"revoke"},delegationId:Lt,expectedRevision:pt},Nc={$id:Ss,type:"object",oneOf:[{type:"object",additionalProperties:!1,required:Object.keys(Cs).filter(e=>e!=="nodeId"),properties:Cs,if:{required:["nodeId"],properties:{nodeId:{type:"string"}}},then:{properties:{workflowCode:_e}}},{type:"object",additionalProperties:!1,required:Object.keys(hs),properties:hs}]},Tc={type:"string",pattern:"^[0-9a-f]{64}$"},gp={$id:Rs,type:"object",additionalProperties:!1,required:["schemaVersion","operationId","operation","requestDigest","before","after","taskPolicy"],properties:{schemaVersion:{const:Rs},operationId:Lt,operation:{enum:["create","revoke"]},requestDigest:Tc,before:{anyOf:[Ho,{type:"null"}]},after:{...Ho,properties:{...Jo,id:{anyOf:[Lt,{type:"null"}]}}},taskPolicy:ks}};function Ip(e){return e===void 0?"":`
9
- ${Z(e)}`}function yp(e,t){let o=e.handlers.find(n=>n.code===t);return Z(o?.workflowStep?o:e)}var Op="openxiangda.data-business-command/v1",Rc="openxiangda.data-business-command-resolution/v1",Np=65536;function Tp(e){let t=0,o=0,n=new Set,i=new TextEncoder,r=()=>{throw new Error("OPENXIANGDA_DATA_COMMAND_INTENT_INVALID")},d=a=>(o+=i.encode(a).byteLength,o>65536&&r(),a),s=(a,c)=>{if(++t>1e4||c>32)return r();if(a===null||typeof a=="string"||typeof a=="boolean")return d(JSON.stringify(a));if(typeof a=="number")return Number.isFinite(a)?d(JSON.stringify(a)):r();if(!a||typeof a!="object"||n.has(a)||Object.getOwnPropertySymbols(a).length)return r();n.add(a);let f;if(Array.isArray(a))return Object.keys(a).length!==a.length?r():(f=d("[")+a.map((p,_)=>(_?d(","):"")+s(p,c+1)).join("")+d("]"),n.delete(a),f);let u=Object.getPrototypeOf(a);return u!==Object.prototype&&u!==null?r():(f=d("{")+Object.keys(a).sort().map((p,_)=>(_?d(","):"")+d(JSON.stringify(p))+d(":")+s(a[p],c+1)).join("")+d("}"),n.delete(a),f)};return!e||typeof e!="object"||Array.isArray(e)?r():s(e,0)}function Rp(e,t,o=!1){let n=e,i=()=>{throw new Error("OPENXIANGDA_DATA_COMMAND_RESPONSE_INVALID")};if(!n||typeof n!="object"||n.schemaVersion!==Rc)return i();for(let a of["appCode","environmentKey","operationCode","idempotencyKey","intentDigest"])if(n[a]!==t[a])return i();if(typeof n.observedAt!="string"||!Number.isFinite(Date.parse(n.observedAt)))return i();if(n.outcome==="not_observed"&&n.receipt===null&&!o)return n;if(n.outcome!=="committed"||!n.receipt)return i();let r=n.receipt,d=a=>typeof a=="string"&&/^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(a);if(!d(r.id)||!d(r.appVersionId)||!Number.isSafeInteger(r.environmentHeadRevision)||r.environmentHeadRevision<1||typeof r.completedAt!="string"||!Number.isFinite(Date.parse(r.completedAt)))return i();let s=r.transaction;if(!s||s.schemaVersion!=="openxiangda.data-transaction-result/v2"||s.idempotencyKey!==t.idempotencyKey||typeof s.replayed!="boolean"||!Array.isArray(s.items)||!s.items.length||s.items.length>1e3)return i();for(let[a,c]of s.items.entries()){if(!c||c.index!==a)return i();if(c.operation==="emitEvent"){if(!d(c.eventId)||typeof c.eventType!="string"||!c.eventType)return i()}else if(!["create","update","delete","increment"].includes(c.operation)||!d(c.id)||typeof c.resourceCode!="string"||!c.resourceCode||!Number.isSafeInteger(c.revision)||c.revision<1)return i()}return n}var Ps=/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/,Rn=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Ft=(e,t)=>typeof e=="string"&&e.length<=t&&e.trim().length>0&&e===e.trim(),Yo=(e,t,o=[])=>t.every(n=>Object.hasOwn(e,n))&&Object.keys(e).every(n=>[...t,...o].includes(n));function hp(e){if(!Rn(e)||!Yo(e,["kind","errorCode","anyOf"],["allowAppSuperAdmin"])||e.kind!=="actor-authority"||!Ft(e.errorCode,110)||!/^OPENXIANGDA_[A-Z0-9_]{1,96}$/.test(e.errorCode)||Object.hasOwn(e,"allowAppSuperAdmin")&&typeof e.allowAppSuperAdmin!="boolean"||!Array.isArray(e.anyOf)||e.anyOf.length<1||e.anyOf.length>20)return!1;let t=new Set;return e.anyOf.every(o=>{if(!Rn(o)||!Yo(o,["roleCode"],["scope"])||!Ft(o.roleCode,100)||!Ps.test(o.roleCode))return!1;if(Object.hasOwn(o,"scope")){let r=o.scope;if(!Rn(r)||!Yo(r,["dimensionCode","value","operation"])||!Ft(r.dimensionCode,100)||!Ps.test(r.dimensionCode)||!Ft(r.value,255)||!Ft(r.operation,64)||!/^[A-Za-z0-9*][A-Za-z0-9*._:-]*$/.test(r.operation))return!1}let n=o.scope,i=JSON.stringify([o.roleCode,n?.dimensionCode,n?.value,n?.operation]);return t.has(i)?!1:(t.add(i),!0)})}function wp(e,t,o){if(t.roleSource!=="package"||t.roleCode!==e.roleCode||!o||!t.capabilityCodes.includes(o))return!1;if(!e.scope)return!0;let n;try{n=JSON.parse(t.scopeGrantsJson)}catch{return!1}if(!Array.isArray(n))return!1;let i=e.scope;return n.some(r=>Rn(r)&&r.dimensionCode===i.dimensionCode&&Array.isArray(r.values)&&r.values.includes(i.value)&&(r.operations===void 0||r.operations===null||Array.isArray(r.operations)&&(!r.operations.length||r.operations.includes("*")||r.operations.includes(i.operation))))}var Dp=500,Cc=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Xo=e=>!!e&&typeof e=="object"&&!Array.isArray(e);function kp(e){if(!Xo(e)||e.kind!=="record-set-match"||Object.keys(e).some(o=>!["kind","resourceCode","errorCode","records","where"].includes(o))||typeof e.resourceCode!="string"||e.resourceCode.length>64||!/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/.test(e.resourceCode)||typeof e.errorCode!="string"||!/^OPENXIANGDA_[A-Z0-9_]{1,96}$/.test(e.errorCode)||!Array.isArray(e.records)||!e.records.length||e.records.length>500||Object.hasOwn(e,"where")&&!Xo(e.where))return!1;let t=new Set;return e.records.every(o=>{if(!Xo(o)||Object.keys(o).length!==2||typeof o.id!="string"||!Cc.test(o.id)||!Number.isSafeInteger(o.expectedRevision)||Number(o.expectedRevision)<1)return!1;let n=o.id.toLowerCase();return t.has(n)?!1:(t.add(n),!0)})}function hc(e,t){if(t===void 0)return e;let o=e.views?.find(d=>d.code===t);if(!o)throw new Error(`DATA_RESOURCE_VIEW_NOT_FOUND: ${t}`);let n=new Map(o.sections?.flatMap(d=>d.fields.map(s=>[s,d.title]))),{views:i,...r}=e;return{...r,generated:o.generated,list:o.list,form:o.form,detail:o.detail,mobile:o.mobile,fields:Object.fromEntries(Object.entries(e.fields).map(([d,s])=>{let{section:a,...c}=s,f=n.get(d);return[d,{...c,...f?{section:f}:{},list:o.list.fieldOrder?.includes(d)??!1}]}))}}var wc="openxiangda.development-configuration/v2",vs="openxiangda.development-configuration-manifest/v1",Lp="application.development-configuration",Fp="/openxiangda-api/v2/applications/{appCode}/dev-sessions/configuration",Zo=class extends Error{constructor(o,n){super(o);this.code=o;this.pointer=n;this.data={pointer:n}}code;pointer;status=400;data};function je(e){throw new Zo("OPENXIANGDA_CONNECTED_DEV_CONFIGURATION_INVALID",e)}function Sc(e){(!e||typeof e!="object"||Array.isArray(e))&&je("/packageManifest");let t=e,o=["schemaVersion","appCode","version","configDigest","contractDigest","source","toolchain","artifacts"];(Object.keys(t).some(i=>!o.includes(i))||t.schemaVersion!==vs||typeof t.appCode!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(t.appCode)||!/^[a-f0-9]{64}$/.test(t.configDigest)||!/^[a-f0-9]{64}$/.test(t.contractDigest)||t.version!==`development-${t.configDigest}`)&&je("/packageManifest"),(!t.source||typeof t.source!="object"||Array.isArray(t.source)||Object.keys(t.source).some(i=>!["repository","commit","dirty"].includes(i))||![null,"string"].includes(t.source.repository===null?null:typeof t.source.repository)||t.source.repository!==null&&(t.source.repository.length>1024||/[\r\n\0]/.test(t.source.repository))||t.source.commit!==null&&(typeof t.source.commit!="string"||!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(t.source.commit))||typeof t.source.dirty!="boolean")&&je("/packageManifest/source"),(!t.toolchain||Object.keys(t.toolchain).some(i=>!["version","contractVersion"].includes(i))||typeof t.toolchain.version!="string"||!/^[A-Za-z0-9][A-Za-z0-9.+_-]{0,127}$/.test(t.toolchain.version)||t.toolchain.contractVersion!==ko)&&je("/packageManifest/toolchain");let n=[{kind:"config",digest:t.configDigest,mediaType:"application/json"},{kind:"contracts",digest:t.contractDigest,mediaType:"application/json"}];return X(t.artifacts)!==X(n)&&je("/packageManifest/artifacts"),t}function xp(e,t){return Sc({schemaVersion:vs,appCode:e,version:`development-${t.configDigest}`,configDigest:t.configDigest,contractDigest:t.contractDigest,source:{...t.source},toolchain:{version:t.toolchainVersion,contractVersion:ko},artifacts:[{kind:"config",digest:t.configDigest,mediaType:"application/json"},{kind:"contracts",digest:t.contractDigest,mediaType:"application/json"}]})}function jp(e,t,o){return(!Number.isSafeInteger(t)||t<1)&&je("/expectedHeadRevision"),`development:${Z({manifest:e,expectedHeadRevision:t,...o?{actorUserId:o}:{}})}`}function Wp(e,t,o){(!e||typeof e!="object"||Array.isArray(e))&&je("/result");let n=e,i=["schemaVersion","appCode","environmentKey","environmentId","appVersionId","configurationRunId","headRevision","publishedAppVersionId","selection","configDigest","contractDigest","reused","runtimeArtifactsDeployed","backendEventsAvailable"],r=/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/i;return(Object.keys(n).some(d=>!i.includes(d))||n.schemaVersion!==wc||n.appCode!==t||n.environmentKey!=="preproduction"||n.configDigest!==o.configDigest||n.contractDigest!==o.contractDigest||!r.test(n.environmentId)||!r.test(n.appVersionId)||!r.test(n.publishedAppVersionId)||n.appVersionId===n.publishedAppVersionId||n.selection!=="session"||!r.test(n.configurationRunId)||typeof n.reused!="boolean"||!Number.isSafeInteger(n.headRevision)||n.headRevision<1||n.headRevision!==o.expectedHeadRevision||n.runtimeArtifactsDeployed!==!1||n.backendEventsAvailable!==!1)&&je("/result"),n}var Mp="application.development-backend-events",Bp="openxiangda.development-backend/v1",Kp="application.development-backend-invocations",Dc="openxiangda.development-backend-invocation/v1",Gp=262144,qp=1048576,zp=131072,Jp=131072,Hp=8,Yp=45,Xp=/^\/__platform\/events\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;function Zp(e){return(e.backend?.operations?.length||0)>0||(e.workflows?.providers?.length||0)>0||(e.events?.subscriptions||[]).some(t=>t.execution?.kind!=="native-data")}function Qp(e){return`connected-development:${e}`}function kc(e){if(typeof e!="string"||e.length%4!==0||!/^[A-Za-z0-9+/]*={0,2}$/.test(e))return null;let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=e.endsWith("==")?2:e.endsWith("=")?1:0;return o&&t.indexOf(e[e.length-o-1])%(o===2?16:4)!==0?null:e.length/4*3-o}function $c(e,t,o){if(!["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(e)||o.method!==e||typeof t!="string"||t.length>2048||!t.startsWith("/")||t.startsWith("//")||t.startsWith("/__platform")||/[\\?#\s\u0000-\u001f\u007f]/.test(t))return!1;let n=t.split("/"),i=String(o.path||"").split("/");return n.length!==i.length?!1:n.every((r,d)=>{if(d===0)return i[d]==="";let s;try{s=decodeURIComponent(r)}catch{return!1}return!s||[".",".."].includes(s)||/[\/\\\s\u0000-\u001f\u007f]/.test(s)?!1:/^:[A-Za-z][A-Za-z0-9_]*$/.test(i[d]||"")||r===i[d]})}var Pc=/^(?:authorization|content-type|content-length|accept|if-match|idempotency-key|x-request-id|x-openxiangda-(?:gateway-assertion|forwarded-by|perspective|csrf-token|mcp-bus-token|dev-selection))$/i,vc=/^(?:content-type|content-disposition|cache-control|etag|last-modified|retry-after)$/i;function Vc(e,t=!1){if(!e||typeof e!="object"||Array.isArray(e))return!1;let o=Object.entries(e),n=o.map(([i])=>i.toLowerCase());return o.length<=24&&new Set(n).size===n.length&&o.every(([i,r])=>(t?vc:Pc).test(i)&&typeof r=="string"&&r.length<=8192&&!/[\r\n\u0000]/.test(r))}function em(e){let t=kc(e.body);return e.schemaVersion===Dc&&!!e.operation&&typeof e.operation.code=="string"&&e.operation.code.length<=128&&e.operation.code.length>0&&$c(e.method,e.endpointPath,e.operation)&&typeof e.canonicalQuery=="string"&&e.canonicalQuery.length<=8192&&!/[\s#\u0000-\u001f\u007f]/.test(e.canonicalQuery)&&t!==null&&t<=262144&&Vc(e.headers)&&Object.entries(e.headers).some(([o,n])=>o.toLowerCase()==="authorization"&&/^Bearer \S+$/.test(n))&&Object.entries(e.headers).some(([o,n])=>o.toLowerCase()==="x-openxiangda-gateway-assertion"&&!!n)}var nm=Object.freeze({version:"rich-text-html/1",maxBytes:1048576,maxNodes:25e3,maxDepth:128,maxImages:20,imageMaxBytes:10485760,maxVideos:4,videoMaxBytes:104857600,imageTypes:["image/png","image/jpeg","image/webp","image/gif"],videoTypes:["video/mp4","video/webm"],fonts:["Arial","Verdana","Tahoma","Times New Roman","Courier New","\u5B8B\u4F53","\u5FAE\u8F6F\u96C5\u9ED1","SimSun","Microsoft YaHei","sans-serif","serif","monospace"]});var im="4c4c20b850e5c473401b3a8767f68374e662b74bf636984bfcc20b5c5f8262c9";export{Nt as AuthenticatedPublicReadContractError,Kt as DATA_AUDIT_METADATA_FIELDS,Np as DATA_BUSINESS_COMMAND_INTENT_MAX_BYTES,Rc as DATA_BUSINESS_COMMAND_RESOLUTION_SCHEMA,Op as DATA_BUSINESS_COMMAND_SCHEMA,Fo as DATA_EVENT_TYPES_V2,Bc as DATA_FORM_DRAFT_MAX_BYTES,ii as DATA_RESOURCE_MAX_FIELDS,$n as DATA_SUBTABLE_DEFAULT_TOTAL_ROWS,Be as DATA_SUBTABLE_MAX_ROWS,tt as DATA_SUBTABLE_MAX_TOTAL_ROWS,Ys as DATA_SYSTEM_SORT_FIELD_CODES,Mc as DATA_TRANSACTION_MAX_BYTES,ri as DATA_TRANSACTION_MAX_OPERATIONS,Dp as DATA_TRANSACTION_RECORD_SET_MAX_RECORDS,Wu as DATE_EVENT_RESERVED_DATA_FIELDS_V2,Yp as DEVELOPMENT_BACKEND_CONNECTION_TTL_SECONDS,Xp as DEVELOPMENT_BACKEND_ENDPOINT_PATTERN,Mp as DEVELOPMENT_BACKEND_FEATURE,Kp as DEVELOPMENT_BACKEND_INVOCATION_FEATURE,Gp as DEVELOPMENT_BACKEND_INVOCATION_MAX_REQUEST_BYTES,qp as DEVELOPMENT_BACKEND_INVOCATION_MAX_RESPONSE_BYTES,Dc as DEVELOPMENT_BACKEND_INVOCATION_SCHEMA,Hp as DEVELOPMENT_BACKEND_MAX_INFLIGHT,Jp as DEVELOPMENT_BACKEND_MAX_REQUEST_BYTES,zp as DEVELOPMENT_BACKEND_MAX_RESPONSE_BYTES,Bp as DEVELOPMENT_BACKEND_SCHEMA,Fp as DEVELOPMENT_CONFIGURATION_ENDPOINT,Lp as DEVELOPMENT_CONFIGURATION_FEATURE,vs as DEVELOPMENT_CONFIGURATION_MANIFEST_SCHEMA,wc as DEVELOPMENT_CONFIGURATION_SCHEMA,cn as DateEventProjectionV2Error,Zo as DevelopmentConfigurationContractError,Et as ManagedConcurrencyContractError,re as NATIVE_ARTIFACT_CAPACITY_V2,im as NATIVE_CONFIGURATION_VALIDATOR_DIGEST,B as NATIVE_CONTRACT_CAPACITY_V2,Ll as NATIVE_DATA_POLICY_EXPRESSION_MAX_CLAUSES,Pl as NATIVE_DATA_POLICY_EXPRESSION_MAX_DEPTH,vl as NATIVE_DATA_POLICY_EXPRESSION_MAX_GROUP_ITEMS,Vl as NATIVE_DATA_POLICY_EXPRESSION_MAX_LEAVES,Fl as NATIVE_DATA_POLICY_EXPRESSION_MAX_OCCURRENCES,Xs as NATIVE_DATA_QUERY_OPERATORS_V2,ct as NATIVE_HIGH_DENSITY_ARTIFACT_CAPACITY_V2,fp as NATIVE_ROLE_MEMBERSHIP_BATCH_MAX_BYTES,up as NATIVE_ROLE_MEMBERSHIP_BATCH_MAX_ITEMS,Jl as NATIVE_UNIQUE_KEY_MAX_BYTES,zi as NATIVE_UNIQUE_KEY_NORMALIZERS,jo as NativeConfigurationCompilerError,Re as NativeDataFieldContractV2Error,Ot as NativeDataPolicyExpressionV2Error,rt as NativeDecimalLifecycleContractError,fo as NativeEventActionContractError,ue as NativeParentReadPolicyError,qo as NativeRoleMembershipBatchInputError,ro as NativeScopeSourceFieldPathV2Error,Rt as NativeUniqueKeyContractError,js as OPENXIANGDA_NATIVE_DATA_FIELD_TYPES_V2,Pe as OPENXIANGDA_NATIVE_DATA_SURFACE_KEYS_V2,Hn as OPENXIANGDA_NATIVE_DRAFT_STATE_KEYS_V2,Mn as OPENXIANGDA_NATIVE_SYSTEM_FIELDS_V2,nt as OPENXIANGDA_NATIVE_SYSTEM_FIELD_MAP_V2,nm as RICH_TEXT_POLICY_V2,jc as USER_CANDIDATE_MAX_SELECTIONS,Fs as USER_CANDIDATE_SCOPE_FIELD_TYPES,Me as UserCandidateContractError,Ir as WORKFLOW_APPROVAL_EMPTY_PROVIDERS,Lu as WORKFLOW_APPROVED_DELEGATION_MAX_BYTES,Vu as WORKFLOW_APPROVED_DELEGATION_MAX_REQUESTS,_r as WORKFLOW_AUTOMATIC_CC_DEFAULT_RECIPIENTS,gr as WORKFLOW_AUTOMATIC_CC_MAX_RECIPIENTS,Ba as WORKFLOW_AUTOMATIC_CC_PROVIDERS,Ct as WORKFLOW_BUSINESS_STEP_EVENT,ir as WORKFLOW_BUSINESS_STEP_EVENTS,iu as WORKFLOW_BUSINESS_STEP_FACTS_KEY,_o as WORKFLOW_BUSINESS_STEP_MAX_BYTES,xa as WORKFLOW_BUSINESS_STEP_MAX_RECEIPT_BYTES,yo as WORKFLOW_CONFIGURABLE_OPERATIONS,bo as WORKFLOW_CONFIGURABLE_PROVIDERS,xo as WORKFLOW_EVENT_TYPES_V2,Pn as WORKFLOW_LAUNCH_MAX_INPUTS,Ja as WORKFLOW_LAUNCH_PREFLIGHT_PROVIDERS,wu as WORKFLOW_REJECTION_NOTIFICATION_MAX_BYTES,za as WORKFLOW_REJECTION_NOTIFICATION_SCHEMA,mu as WORKFLOW_ROLE_UNION_MAX_ROLES,Xu as WORKFLOW_ROUTING_MAX_BYTES,Yu as WORKFLOW_ROUTING_MAX_MATCHED_RULES,Hu as WORKFLOW_ROUTING_MAX_RULES,dp as WORKFLOW_STEP_DATA_COMMAND_SCHEMA,bc as WORKFLOW_STEP_DATA_RESOLUTION_SCHEMA,Qa as WORKFLOW_TASK_PAGE_DEFINITION_MAX_BYTES,wo as WORKFLOW_TASK_PAGE_MAX_BYTES,Za as WORKFLOW_TASK_PAGE_MAX_FIELDS,Pr as WORKFLOW_TASK_SUBTABLE_MAX_ROWS,kr as WORKFLOW_TASK_SUBTABLE_MAX_TOTAL_ROWS,we as WorkflowTaskPageError,ed as applyWorkflowTaskPageValues,Gu as applyWorkflowTaskSubtableRows,Sc as assertDevelopmentConfigurationManifest,Wp as assertDevelopmentConfigurationResult,pp as assertNativeRoleMembershipBatchInput,Ul as assertWorkflowNativeStageGuard,Ki as assertWorkflowNativeStagePolicy,Ml as assertWorkflowNativeStageSourceGuard,pn as assertWorkflowOwnedSubjectCreate,Mr as assertWorkflowOwnedSubjectCreateResources,Tp as canonicalDataBusinessIntent,op as compileNativeApplicationConfiguration,Qi as compileNativeEventAction,Sd as compileNativeEventCapturePlansV2,wd as compileRequiredPlatformCapabilitiesV3,Ao as compileWorkflowBusinessStepHandlers,xp as createDevelopmentConfigurationManifest,jt as dataOwnedRowLimit,Uu as dateEventProjectionEnvelopeSchemaV2,Dr as dateEventProjectionFieldsV2,kc as developmentBackendBase64Bytes,Vc as developmentBackendInvocationHeadersValid,em as developmentBackendInvocationRequestValid,Qp as developmentBackendInvocationRevision,$c as developmentBackendOperationMatches,jp as developmentConfigurationKey,Fe as evaluateWorkflowTaskPageExpression,Cu as formatWorkflowCompletionDeadline,rn as formatWorkflowExpression,Gr as generatedCrudCapabilityOperations,pi as hasDataAuditReadPolicy,co as hasNativeParentReadPolicy,_t as isDataAuditMetadataField,mt as isDataOwnedRowLimit,mi as isDataSystemSortField,hp as isDataTransactionActorAuthorityGuard,kp as isDataTransactionRecordSetMatchGuard,Xc as isNativeDataQueryOperatorV2,Mt as isNativeMultiValueFieldV2,Su as isWorkflowRejectionNotificationSnapshot,wp as matchesDataActorAuthorityMembership,Dl as materializeNativeDataQueryPathTypesV2,st as nativeDataPolicyExpressionLeavesV2,Vi as nativeDataPolicyExpressionToCnfV2,kl as nativeDataQueryPathPlanV2,Qc as nativeFieldAggregatePlanV2,Il as nativeFieldColumnDefinitionV2,yl as nativeFieldDefaultSqlV2,bl as nativeFieldHasDefaultV2,Rl as nativeFieldIndexStatementsV2,Bt as nativeFieldRequiresCreateInputV2,Tl as nativeFieldSequenceGrantStatementsV2,Nl as nativeFieldSequenceOwnershipStatementsV2,Ol as nativeFieldSequenceStatementsV2,Ei as nativeFieldSupportsFilterV2,Zc as nativeFieldSupportsOperatorV2,zn as nativeFieldSupportsSearchV2,At as nativeFieldSupportsSortV2,Ai as nativeOperatorsForFieldV2,Ia as nativePhysicalFieldV2,El as nativePhysicalFieldsV2,ve as nativePhysicalObjectNameV2,wl as nativeScopeSourceFieldValueV2,Pi as nativeScopeSourceGrantPathSupportedV2,so as nativeScopeSourceSubjectPathSupportedV2,Cl as nativeSubtableConstraintStatementsV2,Hi as nativeUniqueKeysContractVersion,Hl as nativeUniqueKeysJsonSchema,sf as normalizeWorkflowOwnedSubjectCreate,Rp as parseDataBusinessCommandResolution,xt as parseDataFieldUserCandidates,oo as parseDecimalReservationLifecycle,Bn as parseNativeDataFieldsV2,fi as parseNativeDataResourceInvariantsV2,Fa as parseNativeParentReadPolicy,Ji as parseNativeUniqueKeys,cp as parseWorkflowStepDataResolution,hc as projectDataResourceView,Qn as projectNativeDataResourceViewV2,lu as projectWorkflowGraph,Ar as projectWorkflowNodePolicy,le as quoteNativeIdentifierV2,qu as refreshWorkflowTaskPageFacts,Vn as requiresAggregateOwnedSubtableCapacity,Wn as requiresDateTimeMinutePrecision,Zp as requiresDevelopmentBackendCredential,mn as requiresExtendedArtifactCapacity,vo as requiresExtendedConfigurationBytes,Po as requiresExtendedDeclarationCapacity,vn as requiresExtendedFieldCapacity,Ln as requiresExtendedOwnedSubtableCapacity,$o as requiresExtendedRoleCapacity,_n as requiresHighDensityArtifactCapacity,Un as requiresOwnedSubtableMinimumRows,kn as requiresUserCandidateLaunchScope,mr as requiresWorkflowRoleInputSelection,fr as requiresWorkflowRoleUnion,Xt as resolveNativeParentReadBinding,It as resolveNativeScopeSourceFieldPathV2,xs as resolveWorkflowUserCandidates,tf as selectWorkflowAssignmentRoutingRules,Kc as serializedDataBytes,Wc as userCandidateScopeValue,qi as validateAuthenticatedPublicRead,hi as validateDecimalReservationLifecycles,Ri as validateManagedConcurrency,bi as validateNativeDataDraftStateV2,ui as validateNativeDataResourceReferencesV2,Zn as validateNativeDataResourceSurfaceV2,ji as validateNativeParentReadPolicies,ni as validateUserCandidateReferences,Oo as validateWorkflowAdministration,No as validateWorkflowApprovalEmptyPolicy,wr as validateWorkflowApprovedDelegation,Wr as validateWorkflowAssignmentRoutingBindings,fn as validateWorkflowAssignmentRoutingPolicy,Qu as validateWorkflowAssignmentRoutingRules,Io as validateWorkflowAutomaticCc,su as validateWorkflowBusinessStepHandlerContract,ru as validateWorkflowBusinessStepRequest,ja as validateWorkflowBusinessStepResult,tn as validateWorkflowBusinessStepSchema,dr as validateWorkflowBusinessStepSubscriptions,on as validateWorkflowBusinessSteps,Rr as validateWorkflowCommandHandlers,Or as validateWorkflowCompletionDeadlines,Sr as validateWorkflowCorrections,ht as validateWorkflowInitiatorApprovalPolicy,tr as validateWorkflowInstanceCommandPolicies,Ro as validateWorkflowLaunchPreflight,Ou as validateWorkflowNodeConfigurationPatch,lr as validateWorkflowReadability,Tr as validateWorkflowRejectionNotification,pr as validateWorkflowRoleInputSelection,an as validateWorkflowRoleUnion,un as validateWorkflowTaskPages,oi as validateWorkflowUserCandidateBindings,Tu as workflowApprovalCanSkip,Fu as workflowApprovedDelegationRequests,ef as workflowAssignmentRoutingFacts,Zu as workflowAssignmentRoutingPolicySchema,id as workflowAssignmentRoutingSemantic,yr as workflowBindingAllowsEmptyUsers,gu as workflowBindingRoleCodes,$u as workflowBusinessCommandInvocationSchema,nn as workflowBusinessStepFactSchema,yp as workflowBusinessStepHandlerDigest,au as workflowBusinessStepInput,Wa as workflowBusinessStepPath,Ip as workflowBusinessStepReceiptSignatureSuffix,en as workflowBusinessStepValueMatches,Nc as workflowDelegationMutationRequestSchema,cr as workflowExpressionPaths,fu as workflowInitiatorApprovalCanComplete,nu as workflowInstanceCommandDeadlineError,eu as workflowInstanceTerminateCapabilityAllowed,tu as workflowInstanceWithdrawalReasonRequired,Bl as workflowNativeStagePolicySchema,wt as workflowNodeAllowedOperations,Ga as workflowOperationCommentRequired,qa as workflowOperationReasonRequired,rf as workflowOwnedSubjectCreateSchema,er as workflowPolicyTimestamp,_u as workflowRoleCodesSchema,Lr as workflowTaskPageFieldState,zu as workflowTaskPageReplayCoversInvalidation,Ku as workflowTaskSubtableRows,Ma as workflowVariableLabel};
8
+ END $native_subtable$`]}function We(e,...t){return`${e}_${od("sha256").update(t.join(":")).digest("hex").slice(0,32)}`}function fe(e){if(!/^[A-Za-z_][A-Za-z0-9_]{0,62}$/.test(e))throw new Error("OPENXIANGDA_NATIVE_IDENTIFIER_INVALID");return`"${e}"`}function cd(e,t){return e.type==="subtable"?"none":t?"gin-trigram":e.indexed?["date-range","datetime-range"].includes(e.type)?"gist-range":Lo.has(e.type)?"btree-snapshot-expressions":rd.has(e.type)?"gin-jsonb-path":"btree":"none"}function ld(e){switch(e.type){case"text.short":return`varchar(${e.maxLength??255})`;case"text.long":case"text.rich":return"text";case"number.integer":return"bigint";case"number.decimal":return`numeric(${e.precision??38},${e.scale??10})`;case"boolean":return"boolean";case"date":return"date";case"time":return"time(0)";case"datetime":return"timestamptz";case"date-range":return"daterange";case"datetime-range":return"tstzrange";case"uuid":return"uuid";case"serial-number":return"varchar(255)";case"subtable":return"child-resource";default:return sd.has(e.type),"jsonb"}}function fi(e,t){if(tn(t.type)&&t.type!=="subtable")return"'[]'::jsonb";if(t.type!=="serial-number")return"";let o=li(t.serial?.prefix||""),n=t.serial?.digits??6;return`(${o} || lpad(nextval(${li(ln(e,t.code))})::text, ${n}, '0'))`}function ud(e,t){return ui.has(t.type)?` CHECK (${e} IS NULL OR jsonb_typeof(${e}) = 'array')`:id.has(t.type)?` CHECK (${e} IS NULL OR jsonb_typeof(${e}) = 'object')`:""}function cn(e){return`"app_data".${fe(e)}`}function ln(e,t){let o=We("seq",e,t);return`"app_data".${fe(o)}`}function li(e){return`'${e.replace(/'/g,"''")}'`}var pi=new Set(["option.single","option.multiple","user.single","user.multiple","department.single","department.multiple","resource-ref.single","resource-ref.multiple"]),fd=new Set([...pi,"cascade.single","cascade.multiple","file","image","signature","address","location","json"]),mi=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,pd=new Set(["__proto__","prototype","constructor"]),$o=class extends Error{constructor(o){super("OPENXIANGDA_SCOPE_PROJECTION_FIELD_PATH_INVALID");this.path=o;this.name="NativeScopeSourceFieldPathV2Error"}path;code="OPENXIANGDA_SCOPE_PROJECTION_FIELD_PATH_INVALID"};function kt(e,t){let o=gi(e);if(!o)return null;let n=t.get(o[0]);if(!n)return null;let r=o.slice(1).join(".")||void 0;return{field:n,...r?{valuePath:r}:{}}}function Po(e){return!!(e&&e.field.type==="user.single"&&e.valuePath==="value")}function _i(e,t,o){if(!e||!t||!md(e))return!1;let{field:n,valuePath:r}=e;if(!r)return t.valueType==="uuid"?n.type==="uuid":["text.short","text.long","serial-number"].includes(n.type);if(r==="value")return!(t.valueSourceResourceCode&&n.type.startsWith("resource-ref.")&&n.source?.resourceCode!==t.valueSourceResourceCode);let i=r.slice(9),s=o.get(n.source?.resourceCode||"")?.get(i)?.type;return t.valueType==="uuid"?s==="uuid":["text.short","text.long","serial-number"].includes(s||"")}function Du(e,t){let o=gi(t);if(!o)throw new $o(String(t||""));let n=e;for(let r of o){if(!n||typeof n!="object"||!Object.prototype.hasOwnProperty.call(n,r))return;n=n[r]}return n}function md(e){let{field:t,valuePath:o}=e;if(!o)return!fd.has(t.type);if(o==="value")return pi.has(t.type);if(!o.startsWith("snapshot."))return!1;let n=o.slice(9);return mi.test(n)&&t.type.startsWith("resource-ref.")&&!!t.source?.snapshotFields?.includes(n)}function gi(e){if(typeof e!="string"||e.length===0||e.length>192)return null;let t=e.split(".");return![1,2,3].includes(t.length)||t.some(o=>!mi.test(o)||pd.has(o))||t.length===2&&t[1]!=="value"||t.length===3&&t[1]!=="snapshot"?null:t}var _d=new Set(["option.single","user.single","department.single","resource-ref.single"]),gd=new Set(["text.short","text.long","text.rich","number.integer","number.decimal","boolean","date","time","datetime","uuid","serial-number"]),Ad=new Set(["value","label","description","color"]),Ed=new Set(["avatarUrl","employeeNo","title","mobile","email"]),Id=new Set(["fullPath","parent.value","parent.label"]),yd=new Set(["country.value","country.label","province.value","province.label","city.value","city.label","district.value","district.label","street.value","street.label","detail","fullAddress"]),Od=new Set(["longitude","latitude","accuracy"]),bd=new Set(["address","name","province","city","district","source"]);function Lu(e){let t=new Map(e.map(o=>[o.code,new Map(o.schema.fields.map(n=>[n.code,n]))]));return e.map(o=>({...o,schema:{...o.schema,fields:o.schema.fields.map(n=>{let r=Nd(n,t);if(!Object.keys(r).length)return n;let i={...n};return Object.defineProperty(i,"queryPathTypes",{configurable:!1,enumerable:!1,writable:!1,value:Object.freeze(r)}),i})}}))}function $u(e,t){if(_d.has(e.type)&&Ad.has(t)||e.type==="user.single"&&Ed.has(t)||e.type==="department.single"&&Id.has(t))return Lt(t);if(e.type==="resource-ref.single"){let o=e.queryPathTypes?.[t];return o?{parts:t.split("."),type:o}:null}if(e.type==="address"&&yd.has(t))return Lt(t);if(e.type==="location"){if(Od.has(t))return{parts:[t],type:"number.decimal"};if(bd.has(t))return Lt(t);if(t==="capturedAt")return{parts:[t],type:"datetime"}}return null}function Nd(e,t){if(e.type!=="resource-ref.single"||!e.source)return{};let o=t.get(e.source.resourceCode);return o?Object.fromEntries((e.source.snapshotFields||[]).flatMap(n=>{let r=o.get(n);return r?[[`snapshot.${n}`,gd.has(r.type)?r.type:"json"]]:[]})):{}}function Lt(e){return{parts:e.split("."),type:"text.short"}}var hd="platform-notify-v1",vu="platform.notify",Rd={type:"object",additionalProperties:!1,properties:{text:{type:"string",minLength:1,maxLength:2048}},required:["text"]},wd={type:"object",additionalProperties:!1,properties:{}},vo=e=>!!e&&typeof e=="object"&&!Array.isArray(e),un=e=>JSON.stringify(e,(t,o)=>vo(o)?Object.fromEntries(Object.keys(o).sort().map(n=>[n,o[n]])):o);function te(e){return e?.kind==="action"&&e.handler?.code===hd&&e.notification!==void 0}function Vu(e){return{...e.notification.recipients,min:1,max:50,delegatable:!1}}function fn(e){let t=[];for(let[o,n]of Object.entries(e?.nodes||{})){if(n?.notification===void 0)continue;(!te(n)||n.handler.version!==1||n.handler.mode!=="reconciled-effect"||n.handler.dataTransaction!==void 0||un(n.inputSchema)!==un(Rd)||un(n.outputSchema)!==un(wd))&&t.push(`WORKFLOW_NOTIFY_PRESET_INVALID:${o}`),n.inputs?.text?.source==="literal"&&(typeof n.inputs.text.value!="string"||!n.inputs.text.value.trim())&&t.push(`WORKFLOW_NOTIFY_TEXT_INVALID:${o}`);let r=n.notification,i=r?.recipients;if(!vo(r)||Object.keys(r).some(s=>!["template","recipients"].includes(s))||r.template!=="workflow_message"||!vo(i)){t.push(`WORKFLOW_NOTIFY_RECIPIENT_INVALID:${o}`);continue}let a=Object.keys(i);i.provider==="initiator"?a.length!==1&&t.push(`WORKFLOW_NOTIFY_RECIPIENT_INVALID:${o}`):i.provider==="fixed_users"?(a.some(s=>!["provider","users"].includes(s))||!Array.isArray(i.users)||i.users.length<1||i.users.length>50||new Set(i.users).size!==i.users.length||i.users.some(s=>typeof s!="string"||!s.trim()||s.length>255))&&t.push(`WORKFLOW_NOTIFY_RECIPIENT_INVALID:${o}`):i.provider==="app_role"?(a.some(s=>!["provider","roleCode"].includes(s))||typeof i.roleCode!="string"||!/^[A-Za-z][A-Za-z0-9_.-]{0,127}$/.test(i.roleCode))&&t.push(`WORKFLOW_NOTIFY_RECIPIENT_INVALID:${o}`):i.provider==="form_field_users"?(a.some(s=>!["provider","inputPath"].includes(s))||typeof i.inputPath!="string"||!/^[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z][A-Za-z0-9_]*)*$/.test(i.inputPath)||i.inputPath.length>256||i.inputPath.split(".").length>8||i.inputPath.split(".").some(s=>["prototype","constructor","__proto__"].includes(s)))&&t.push(`WORKFLOW_NOTIFY_RECIPIENT_INVALID:${o}`):t.push(`WORKFLOW_NOTIFY_RECIPIENT_INVALID:${o}`)}return t}var Vo="openxiangda.workflow.step.requested.v2",xu=[Vo,"openxiangda.workflow.step.result_received.v2","openxiangda.workflow.step.completed.v2","openxiangda.workflow.step.continuation_failed.v2"],xo=16384,Td=2048,ju="steps",jo=/^[A-Za-z][A-Za-z0-9_-]{0,127}$/,Ii=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,Xe=new Set(["__proto__","prototype","constructor"]),K=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&[Object.prototype,null].includes(Object.getPrototypeOf(e)),yi=e=>{try{let t=JSON.stringify(e);return t===void 0?1/0:new TextEncoder().encode(t).length}catch{return 1/0}},mt=(e,t,o=0)=>{if(o>32)return!1;if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((i,a)=>mt(i,t[a],o+1));if(!K(e)||!K(t))return!1;let n=Object.keys(e).filter(i=>e[i]!==void 0),r=Object.keys(t).filter(i=>t[i]!==void 0);return n.length===r.length&&n.every(i=>Object.hasOwn(t,i)&&mt(e[i],t[i],o+1))};function Fo(e,t){let o=0,n=(r,i)=>++o>1e4||i>8?!1:r===null||typeof r=="boolean"||typeof r=="string"?!0:typeof r=="number"?Number.isFinite(r):Array.isArray(r)?r.length<=200&&r.every(a=>n(a,i+1)):K(r)&&Object.keys(r).length<=32&&Object.keys(r).every(a=>!Xe.has(a))&&Object.values(r).every(a=>n(a,i+1));return yi(e)<=t&&n(e,0)}function Cd(e){return!K(e)||Object.keys(e).some(t=>!["executionId","handlerVersion","inputDigest","expectedFactRevision","output","receipt"].includes(t))?!1:/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/i.test(e.executionId||"")&&Number.isSafeInteger(e.handlerVersion)&&e.handlerVersion>=1&&e.handlerVersion<=1e6&&/^[a-f0-9]{64}$/.test(e.inputDigest||"")&&Number.isSafeInteger(e.expectedFactRevision)&&e.expectedFactRevision>=0&&K(e.output)&&Fo(e.output,xo)&&(e.receipt===void 0||K(e.receipt)&&Fo(e.receipt,Td))}function Mu(e){return K(e)&&Object.keys(e).every(t=>["executionId","nodeId","handlerCode","handlerVersion","mode","dataTransaction","input","inputDigest","expectedFactRevision"].includes(t))&&typeof e.nodeId=="string"&&jo.test(e.nodeId)&&!Xe.has(e.nodeId)&&typeof e.handlerCode=="string"&&/^[a-z][a-z0-9-]{0,100}$/.test(e.handlerCode)&&e.handlerCode.endsWith(`-v${e.handlerVersion}`)&&["pure","reconciled-effect"].includes(e.mode)&&(e.dataTransaction===void 0||e.dataTransaction===!0&&e.mode==="reconciled-effect")&&Cd({executionId:e.executionId,handlerVersion:e.handlerVersion,inputDigest:e.inputDigest,expectedFactRevision:e.expectedFactRevision,output:e.input})}function pn(e,t,o=xo){if(!Fo(t,o))return!1;let n=1e4,r=(i,a,s)=>{if(--n<0||s>8||!K(i))return!1;let d=a===null?"null":Array.isArray(a)?"array":typeof a=="number"&&Number.isSafeInteger(a)?"integer":typeof a,c=Array.isArray(i.type)?i.type:[i.type];if(!c.includes(d)&&!(d==="integer"&&c.includes("number"))||i.enum!==void 0&&(!Array.isArray(i.enum)||!i.enum.some(l=>mt(l,a)))||Object.hasOwn(i,"const")&&!mt(i.const,a))return!1;if(typeof a=="number")return Number.isFinite(a)&&(i.minimum===void 0||a>=i.minimum)&&(i.maximum===void 0||a<=i.maximum);if(typeof a=="string"){let l=Array.from(a).length;return(i.minLength===void 0||l>=i.minLength)&&(i.maxLength===void 0||l<=i.maxLength)}return Array.isArray(a)?a.length<=i.maxItems&&(i.minItems===void 0||a.length>=i.minItems)&&a.every(l=>r(i.items,l,s+1)):K(a)?!K(i.properties)||Object.keys(a).some(l=>Xe.has(l)||!Object.hasOwn(i.properties,l))||(Array.isArray(i.required)?i.required:[]).some(l=>!Object.hasOwn(a,l))||i.minProperties!==void 0&&Object.keys(a).length<i.minProperties||i.maxProperties!==void 0&&Object.keys(a).length>i.maxProperties?!1:Object.entries(a).every(([l,f])=>r(i.properties[l],f,s+1)):a===null||typeof a=="boolean"};return r(e,t,0)}function Sd(e){return typeof e=="string"&&e.length<=256&&e.split(".").length<=8&&e.split(".").every(t=>jo.test(t)&&!Xe.has(t))}function mn(e){let t=0,o=(n,r)=>{if(!K(n)||r>6||++t>256||Object.keys(n).some(s=>!["type","title","description","properties","required","additionalProperties","items","maxItems","minItems","maxLength","minLength","minimum","maximum","enum","const","maxProperties","minProperties"].includes(s)))return!1;let i=Array.isArray(n.type)?n.type:[n.type];if(!i.length||i.length>2||i.some(s=>!["object","array","string","integer","number","boolean","null"].includes(s))||i.length>1&&(!i.includes("null")||new Set(i).size!==i.length))return!1;for(let s of["title","description"])if(n[s]!==void 0&&(typeof n[s]!="string"||n[s].length>2e3))return!1;for(let s of["minimum","maximum"])if(n[s]!==void 0&&(typeof n[s]!="number"||!Number.isFinite(n[s])))return!1;for(let[s,d]of[["maxItems",200],["minItems",200],["maxLength",16384],["minLength",16384],["maxProperties",32],["minProperties",32]])if(n[s]!==void 0&&(!Number.isSafeInteger(n[s])||n[s]<0||n[s]>d))return!1;for(let[s,d]of[["minimum","maximum"],["minItems","maxItems"],["minLength","maxLength"],["minProperties","maxProperties"]])if(n[s]!==void 0&&n[d]!==void 0&&n[s]>n[d])return!1;if(["properties","required","additionalProperties","maxProperties","minProperties"].some(s=>n[s]!==void 0)&&!i.includes("object")||["items","maxItems","minItems"].some(s=>n[s]!==void 0)&&!i.includes("array")||["maxLength","minLength"].some(s=>n[s]!==void 0)&&!i.includes("string")||["minimum","maximum"].some(s=>n[s]!==void 0)&&!i.some(s=>s==="integer"||s==="number")||n.enum!==void 0&&(!Array.isArray(n.enum)||!n.enum.length||n.enum.length>100)||i.includes("object")&&(!K(n.properties)||n.additionalProperties!==!1||Object.keys(n.properties).length>32||Object.keys(n.properties).some(s=>!Ii.test(s)||Xe.has(s))||n.required!==void 0&&(!Array.isArray(n.required)||new Set(n.required).size!==n.required.length||n.required.some(s=>typeof s!="string"||!Object.hasOwn(n.properties,s)))||n.minProperties!==void 0&&n.minProperties>Object.keys(n.properties).length||n.maxProperties!==void 0&&n.maxProperties<(n.required?.length||0)||!Object.values(n.properties).every(s=>o(s,r+1)))||i.includes("array")&&(!Number.isSafeInteger(n.maxItems)||!o(n.items,r+1)))return!1;let a={...n};return delete a.enum,delete a.const,!(n.enum!==void 0&&(!n.enum.every(s=>pn(a,s))||n.enum.some((s,d)=>n.enum.slice(0,d).some(c=>mt(s,c))))||Object.hasOwn(n,"const")&&!pn(a,n.const))};return K(e)&&e.type==="object"&&yi(e)<=xo&&o(e,0)}function _t(e){let t=Object.fromEntries(Object.values(e.nodes||{}).filter(o=>o?.kind==="action").map(o=>[o.id,o.outputSchema]));return Object.keys(t).length?{...e.inputSchema,properties:{...e.inputSchema?.properties,steps:{type:"object",additionalProperties:!1,properties:t}}}:e.inputSchema||{}}function Oi(e,t){let o=e;for(let n of t.split(".")){if(!K(o?.properties)||!Object.hasOwn(o.properties,n))return;o=o.properties[n]}return K(o)?o:void 0}var Ai=(e,t)=>!!Oi(e,t);function Uu(e){return K(e)&&Object.keys(e).every(t=>["version","mode","dataTransaction","inputSchema","outputSchema"].includes(t))&&Number.isSafeInteger(e.version)&&e.version>=1&&e.version<=1e6&&["pure","reconciled-effect"].includes(e.mode)&&(e.dataTransaction===void 0||e.dataTransaction===!0&&e.mode==="reconciled-effect")&&mn(e.inputSchema)&&mn(e.outputSchema)}function Ei(e){return e.kind==="approval"?[e.onApprove,e.onReject]:e.kind==="parallel"?[...Array.isArray(e.branches)?e.branches.map(t=>t.target):[],e.join]:e.kind==="join"?[e.next]:e.kind==="condition"?[...Array.isArray(e.branches)?e.branches.map(t=>t.target):[],e.otherwise]:e.kind==="cc"||e.kind==="action"||e.kind==="handle"?[e.next]:[]}function Wo(e,t=0){return!K(e)||t>16?[]:e.op==="path"?typeof e.path=="string"?[e.path]:[]:["left","right","value"].flatMap(o=>Wo(e[o],t+1)).concat(Array.isArray(e.values)?e.values.flatMap(o=>Wo(o,t+1)):[])}function _n(e,t){if(!K(e)||!K(e.nodes))return["WORKFLOW_STEP_DEFINITION_INVALID"];let o=e.nodes,n=Object.entries(o).filter(([,s])=>s?.kind==="action");if(!n.length)return[];let r=[...fn(e)];Object.hasOwn(e.inputSchema?.properties||{},"steps")&&r.push("WORKFLOW_STEP_FACT_NAMESPACE_RESERVED");let i=_t(e);for(let[s,d]of n){(Object.keys(d).some(f=>!["id","kind","title","next","handler","inputSchema","outputSchema","inputs",...te(d)?["notification"]:[]].includes(f))||d.id!==s||!jo.test(s)||Xe.has(s)||typeof d.title!="string"||!d.title.trim()||d.title.length>255||typeof d.next!="string"||!Object.hasOwn(o,d.next))&&r.push(`WORKFLOW_STEP_NODE_INVALID:${s}`);let c=d.handler;(!K(c)||Object.keys(c).some(f=>!["code","version","mode","dataTransaction"].includes(f))||!Number.isSafeInteger(c.version)||c.version<1||c.version>1e6||!/^[a-z][a-z0-9-]{0,100}$/.test(c.code||"")||!String(c.code).endsWith(`-v${c.version}`)||!["pure","reconciled-effect"].includes(c.mode)||c.dataTransaction!==void 0&&(c.dataTransaction!==!0||c.mode!=="reconciled-effect"))&&r.push(`WORKFLOW_STEP_HANDLER_INVALID:${s}`);let l=mn(d.inputSchema);if((!l||!mn(d.outputSchema))&&r.push(`WORKFLOW_STEP_SCHEMA_INVALID:${s}`),!K(d.inputs)||Object.keys(d.inputs).length>32){r.push(`WORKFLOW_STEP_INPUTS_INVALID:${s}`);continue}for(let f of Array.isArray(d.inputSchema?.required)?d.inputSchema.required:[])Object.hasOwn(d.inputs,f)||r.push(`WORKFLOW_STEP_INPUT_REQUIRED:${s}:${f}`);for(let[f,p]of Object.entries(d.inputs)){if(!Ii.test(f)||Xe.has(f)||!Object.hasOwn(d.inputSchema?.properties||{},f)||!K(p)){r.push(`WORKFLOW_STEP_INPUT_INVALID:${s}:${f}`);continue}if(p.source==="literal")(!l||Object.keys(p).some(m=>!["source","value"].includes(m))||!Object.hasOwn(p,"value")||!pn(d.inputSchema.properties[f],p.value))&&r.push(`WORKFLOW_STEP_LITERAL_INVALID:${s}:${f}`);else if(p.source!=="fact"||Object.keys(p).some(m=>!["source","path"].includes(m))||!Sd(p.path)||!Ai(i,p.path))r.push(`WORKFLOW_STEP_FACT_PATH_INVALID:${s}:${f}`);else if(l){let m=Oi(i,p.path),E=d.inputSchema.properties[f],A=Array.isArray(m.type)?m.type:[m.type],b=Array.isArray(E.type)?E.type:[E.type];A.some(O=>!b.includes(O)&&!(O==="integer"&&b.includes("number")))&&r.push(`WORKFLOW_STEP_FACT_TYPE_MISMATCH:${s}:${f}`)}}}let a=(s,d)=>{let c=new Set,l=[e.startAt||""];for(;l.length&&c.size<=200;){let f=l.shift();if(!(f===d||c.has(f)||!o[f])){if(f===s)return!0;c.add(f),l.push(...Ei(o[f]))}}return!1};for(let[s,d]of Object.entries(o)){if(!K(d))continue;let c=d.kind==="action"?Object.values(d.inputs||{}).flatMap(f=>f?.source==="fact"?[f.path]:[]):(Array.isArray(d.branches)?d.branches:[]).flatMap(f=>Wo(f?.when)),l=t?.bindings?.[d.binding];l&&c.push(...[l.inputPath,l.departmentIdFrom,l.resourceIdFrom,l.scope?.valueFrom].filter(f=>typeof f=="string"));for(let f of c.filter(p=>typeof p=="string"&&p.startsWith("steps."))){let p=f.split(".")[1];(o[p]?.kind!=="action"||p===s||!Ai(i,f)||a(s,p))&&r.push(`WORKFLOW_STEP_OUTPUT_NOT_AVAILABLE:${s}:${f}`)}}if(t)for(let[,s]of n.filter(([,d])=>!te(d))){let d=new Set,c=[s.next];for(;c.length&&d.size<=200;){let l=c.shift();if(d.has(l)||!K(o[l]))continue;d.add(l);let f=o[l];if(!(f.kind==="action"||f.kind==="end")){if(f.kind==="approval"){let p=t.bindings?.[f.binding];p&&["application_provider","initiator_select"].includes(p.provider)&&r.push(`WORKFLOW_STEP_NEXT_PROVIDER_REQUIRES_PREPARED_RESULT:${l}`);continue}c.push(...Ei(f))}}}return[...new Set(r)]}function Bu(e,t){let o={};for(let[n,r]of Object.entries(e.inputs)){let i=r.source==="literal"?r.value:r.path.split(".").reduce((a,s)=>K(a)&&Object.hasOwn(a,s)?a[s]:void 0,t);i!==void 0&&(o[n]=i)}if(!pn(e.inputSchema,o))throw new Error("WORKFLOW_STEP_INPUT_SCHEMA_INVALID");return o}function bi(e,t,o){let n=Mo(e),r=[];Object.keys(n).length&&!o&&r.push("WORKFLOW_STEP_BACKEND_REQUIRED");for(let i of Object.keys(n)){let a=t.find(s=>s.code===i);(!a||a.execution||a.action||!Array.isArray(a.eventTypes)||a.eventTypes.length!==1||a.eventTypes[0]!==Vo||!K(a.filter)||Object.keys(a.filter).length!==1||!K(a.filter.workflowStep)||Object.keys(a.filter.workflowStep).length!==1||a.filter.workflowStep.handlerCode!==i||!K(a.payload)||a.payload.includeChanges!==!1||!Array.isArray(a.payload.fields)||a.payload.fields.length)&&r.push(`WORKFLOW_STEP_SUBSCRIPTION_INVALID:${i}`)}for(let i of t)(i.eventTypes?.includes(Vo)&&!n[i.code]||i.filter?.workflowStep&&!n[i.code])&&r.push(`WORKFLOW_STEP_HANDLER_NOT_DECLARED:${i.code}`);return r}function Mo(e){let t={};for(let o of e){let n=_n(o);if(n.length)throw new Error(n.join("; "));for(let r of Object.values(o.nodes||{})){if(r.kind!=="action"||te(r))continue;let i={version:r.handler.version,mode:r.handler.mode,...r.handler.dataTransaction?{dataTransaction:!0}:{},inputSchema:r.inputSchema,outputSchema:r.outputSchema},a=t[r.handler.code];if(a&&!mt(a,i))throw new Error(`WORKFLOW_STEP_HANDLER_CONTRACT_CONFLICT:${r.handler.code}`);t[r.handler.code]=i}}return t}var Uo=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Dd=e=>typeof e=="string"&&e.length<=255&&e.split(".").length<=8&&/^[A-Za-z][A-Za-z0-9_-]*(\.[A-Za-z][A-Za-z0-9_-]*)*$/.test(e)&&!e.split(".").some(t=>["__proto__","prototype","constructor"].includes(t));function gn(e){if(e?.provider!=="supervisor_chain")return e&&["from","until","continuous","missing"].some(n=>e[n]!==void 0)?["WORKFLOW_SUPERVISOR_CHAIN_PROVIDER_INVALID"]:[];let t=e.from,o=e.until;return!Uo(e)||Object.keys(e).some(n=>!["provider","from","until","continuous","missing","min","max","delegatable"].includes(n))||!(t==="initiator"||Uo(t)&&Object.keys(t).length===1&&Dd(t.field))||!(o==="top"||Uo(o)&&Object.keys(o).length===1&&(Number.isInteger(o.level)&&o.level>=1&&o.level<=20||typeof o.roleCode=="string"&&/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/.test(o.roleCode)&&o.roleCode.length<=128))||e.continuous!==void 0&&typeof e.continuous!="boolean"||e.missing!==void 0&&!["skip_level","block"].includes(e.missing)?["WORKFLOW_SUPERVISOR_CHAIN_BINDING_INVALID"]:[]}function An(e,t){let o=[];for(let[n,r]of Object.entries(t?.bindings||{}))o.push(...gn(r).map(i=>`${i}:${n}`));for(let[n,r]of Object.entries(e?.nodes||{})){let i=t?.bindings?.[r?.binding];if(!(i?.provider!=="supervisor_chain"||gn(i).length))if(["approval","handle"].includes(r.kind)||o.push(`WORKFLOW_SUPERVISOR_CHAIN_HUMAN_REQUIRED:${n}`),i.continuous!==!1&&r.mode!=="sequence"&&o.push(`WORKFLOW_SUPERVISOR_CHAIN_SEQUENCE_REQUIRED:${n}`),i.from==="initiator")(!e.organizationContext?.department||e.organizationContext.department.source==="none")&&o.push(`WORKFLOW_SUPERVISOR_CHAIN_DEPARTMENT_CONTEXT_REQUIRED:${n}`);else{let a=_t(e);for(let d of i.from.field.split("."))a=a?.properties?.[d];let s=Array.isArray(a?.type)?a.type.filter(d=>d!=="null")[0]:a?.type;(!a||!["string","array","object"].includes(s))&&o.push(`WORKFLOW_SUPERVISOR_CHAIN_USER_FACT_REQUIRED:${n}`)}}return o}function qu(e){let t=e.from==="initiator"?"\u7533\u8BF7\u4EBA":`\u6210\u5458\u53D8\u91CF ${e.from.field}`,o=e.until==="top"?"\u6700\u4E0A\u7EA7":"level"in e.until?`\u7B2C ${e.until.level} \u7EA7`:`\u89D2\u8272 ${e.until.roleCode}`;return`${t}\u7684\u4E3B\u7BA1\u94FE \xB7 \u81F3${o} \xB7 ${e.continuous!==!1?"\u9010\u7EA7\u529E\u7406":"\u4EC5\u7EC8\u70B9\u529E\u7406"}`}function En(e){let t=[];for(let[o,n]of Object.entries(e?.nodes||{})){if(n?.reminders===void 0)continue;let r=n.reminders;(!["approval","handle","correction"].includes(n.kind)||!r||typeof r!="object"||Array.isArray(r)||Object.keys(r).length!==4||Object.keys(r).some(i=>!["afterSeconds","everySeconds","max","to"].includes(i))||!Number.isInteger(r.afterSeconds)||r.afterSeconds<1||r.afterSeconds>2592e3||!Number.isInteger(r.everySeconds)||r.everySeconds<1||r.everySeconds>2592e3||!Number.isInteger(r.max)||r.max<1||r.max>10||!Array.isArray(r.to)||r.to.length!==1||r.to[0]!=="handlers")&&t.push(`WORKFLOW_REMINDERS_INVALID:${o}`)}return t}function xe(e){return e.returnPolicy?Array.isArray(e.returnPolicy.targets)?e.returnPolicy.targets.filter(t=>typeof t?.nodeId=="string").map(t=>t.nodeId):[]:Array.isArray(e.returnTargets)?[...e.returnTargets]:[]}function Hu(e,t,o){if(t.returnPolicy)return Array.isArray(t.returnPolicy.targets)?t.returnPolicy.targets.find(n=>n.nodeId===o):void 0;if(t.returnTargets?.includes(o))return{nodeId:o,routes:e.nodes[o]?.kind==="correction"?["replay"]:["replay","resume"],defaultRoute:"replay"}}function In(e){let t=[];for(let[o,n]of Object.entries(e?.nodes||{})){let r=n?.returnPolicy;if(r===void 0)continue;if(!["approval","handle"].includes(n.kind)||!r||typeof r!="object"||Array.isArray(r)||Object.keys(r).some(a=>a!=="targets")||!Array.isArray(r.targets)||r.targets.length>20){t.push(`WORKFLOW_RETURN_POLICY_INVALID:${o}`);continue}let i=new Set;for(let a of r.targets)(!a||typeof a!="object"||Object.keys(a).some(s=>!["nodeId","routes","defaultRoute"].includes(s))||typeof a.nodeId!="string"||a.nodeId===o||i.has(a.nodeId)||!["approval","handle","correction"].includes(e.nodes?.[a.nodeId]?.kind))&&t.push(`WORKFLOW_RETURN_TARGET_INVALID:${o}`),a?.nodeId&&i.add(a.nodeId),(!Array.isArray(a?.routes)||a.routes.length<1||a.routes.length>2||new Set(a.routes).size!==a.routes.length||a.routes.some(s=>!["replay","resume"].includes(s))||!a.routes.includes(a.defaultRoute))&&t.push(`WORKFLOW_RETURN_ROUTES_INVALID:${o}`);n.returnTargets&&(n.returnTargets.length!==i.size||n.returnTargets.some(a=>!i.has(a)))&&t.push(`WORKFLOW_RETURN_TARGETS_CONFLICT:${o}`)}return t}var kd=2,Ld=8,Bo=e=>!!e&&typeof e=="object"&&!Array.isArray(e),$d=e=>typeof e=="string"&&/^[A-Za-z][A-Za-z0-9_-]{0,127}$/.test(e),Ni=(e,t)=>e===t||e.startsWith(`${t}.`)||t.startsWith(`${e}.`);function hi(e){return e.kind==="approval"?[e.onApprove,e.onReject]:e.kind==="condition"?[...(Array.isArray(e.branches)?e.branches:[]).map(t=>t?.target),e.otherwise]:e.kind==="parallel"?[...(Array.isArray(e.branches)?e.branches:[]).map(t=>t?.target),e.join]:"next"in e?[e.next]:[]}function je(e){let t=[],o=[];if(!Bo(e?.nodes))return{regions:o,errors:["WORKFLOW_PARALLEL_DOCUMENT_INVALID"]};let n=e.nodes;if(!Object.values(n).some(a=>a?.kind==="parallel"||a?.kind==="join"))return{regions:o,errors:t};if(Object.keys(n).length>200)return{regions:o,errors:["WORKFLOW_PARALLEL_NODE_LIMIT"]};let r=new Map,i=new Set;for(let a of Object.values(n)){if(a?.kind!=="parallel")continue;let s=n[a.join];if(s?.kind!=="join"||s.parallel!==a.id||i.has(a.join)){t.push(`WORKFLOW_PARALLEL_PAIR_INVALID:${a.id}`);continue}if(i.add(s.id),n[s.next]||t.push(`WORKFLOW_PARALLEL_TARGET_MISSING:${s.id}`),!Array.isArray(a.branches)||a.branches.length<kd||a.branches.length>Ld){t.push(`WORKFLOW_PARALLEL_BRANCH_LIMIT:${a.id}`);continue}let d={parallelNodeId:a.id,joinNodeId:s.id,branches:[]},c=new Set,l=new Set;for(let f of a.branches){if(!Bo(f)||!$d(f.id)||typeof f.title!="string"||!f.title.trim()||f.title.length>255||c.has(f.id)){t.push(`WORKFLOW_PARALLEL_BRANCH_INVALID:${a.id}`);continue}c.add(f.id);let p=new Set,m=new Set,E=new Set,A=O=>{if(O===s.id)return;let g=n[O];if(!g){t.push(`WORKFLOW_PARALLEL_TARGET_MISSING:${a.id}:${O}`);return}if(g.kind==="end"){g.outcome!=="rejected"?t.push(`WORKFLOW_PARALLEL_BRANCH_END_INVALID:${a.id}:${f.id}:${O}`):l.add(O);return}if(g.kind==="parallel"||g.kind==="join"){t.push(`WORKFLOW_PARALLEL_NESTING_FORBIDDEN:${a.id}:${O}`);return}if(m.has(O)){t.push(`WORKFLOW_PARALLEL_CYCLE:${a.id}:${O}`);return}if(E.has(O))return;p.add(O),m.add(O);let y=hi(g);y.length||t.push(`WORKFLOW_PARALLEL_BRANCH_DANGLING:${a.id}:${O}`);for(let h of y)A(h);m.delete(O),E.add(O)};A(f.target);let b=new Set;for(let O of p){r.get(O)?t.push(`WORKFLOW_PARALLEL_BODY_OVERLAP:${a.id}:${f.id}:${O}`):r.set(O,{parallel:a.id,branch:f.id});let y=n[O];if(y.kind==="approval"||y.kind==="handle")for(let h of e.taskPages?.[y.taskPageCode||""]?.fields||[]){let u=y.fieldPolicy?.fields?.[h.code]||y.fieldPolicy?.default||"readonly";h.readonly!==!0&&(u==="edit"||u==="edit_required")&&b.add(h.code)}}d.branches.push({id:f.id,target:f.target,nodeIds:[...p].sort(),writableFields:[...b].sort()})}l.size>1&&t.push(`WORKFLOW_PARALLEL_REJECT_END_NOT_SHARED:${a.id}`),o.push(d)}for(let a of Object.values(n))a?.kind==="join"&&!i.has(a.id)&&t.push(`WORKFLOW_PARALLEL_JOIN_ORPHAN:${a.id}`);r.has(e.startAt)&&t.push(`WORKFLOW_PARALLEL_EXTERNAL_ENTRY:${e.startAt}`);for(let[a,s]of Object.entries(n))if(Bo(s)){for(let d of hi(s)){let c=r.get(d),l=r.get(a),f=c&&n[c.parallel],p=f?.kind==="parallel"&&a===f.id&&f.branches.some(m=>m.id===c.branch&&m.target===d);if(c&&!p&&(!l||l.parallel!==c.parallel||l.branch!==c.branch)&&t.push(`WORKFLOW_PARALLEL_EXTERNAL_ENTRY:${a}:${d}`),n[d]?.kind==="join"&&s.kind!=="parallel"){let m=n[d];(!l||l.parallel!==m.parallel)&&t.push(`WORKFLOW_PARALLEL_EXTERNAL_JOIN:${a}:${d}`)}}if(s.kind==="approval"||s.kind==="handle"){let d=r.get(a);for(let c of xe(s)){let l=r.get(c);d&&(!l||l.parallel!==d.parallel||l.branch!==d.branch)&&t.push(`WORKFLOW_PARALLEL_RETURN_CROSSES_BRANCH:${a}:${c}`),!d&&l&&t.push(`WORKFLOW_PARALLEL_RETURN_ENTERS_BRANCH:${a}:${c}`)}}}for(let a of o)for(let s of a.branches){let d=a.branches.filter(l=>l.id!==s.id);for(let l of s.writableFields)d.some(f=>f.writableFields.includes(l))&&t.push(`WORKFLOW_PARALLEL_SHARED_WRITABLE_FIELD:${a.parallelNodeId}:${l}`);let c=d.flatMap(l=>[...Object.entries(e.subject?.factProjection||{}).filter(([,f])=>l.writableFields.some(p=>Ni(p,f))).map(([f])=>f),...l.nodeIds.filter(f=>n[f]?.kind==="action").map(f=>`steps.${f}`)]);for(let l of s.nodeIds){let f=n[l];if(f.kind==="action")for(let p of Object.values(f.inputs||{}))p.source==="fact"&&c.some(m=>Ni(m,p.path))&&t.push(`WORKFLOW_PARALLEL_SIBLING_INPUT:${l}:${p.path}`)}}return{regions:o,errors:[...new Set(t)]}}function yn(e){return je(e).errors}function Zu(e){if(!["running","returned"].includes(e.status))return!1;if(!e.forkVisitId&&!e.branchId)return e.currentNodeId===e.nodeId;let t=e.fork;return!!t&&e.forkVisitId===t.forkVisitId&&e.branchId===t.branchId&&t.status==="active"&&e.currentNodeId===t.parallelNodeId&&t.activation.includes(e.branchId)&&!t.arrived.includes(e.branchId)&&e.activeToken}function On(e){let t=[];for(let[o,n]of Object.entries(e?.nodes||{})){if(n?.kind!=="handle"){n?.allowedOperations?.includes("complete")&&t.push(`WORKFLOW_HANDLE_COMMAND_ONLY:${o}`);continue}(!n.next||!e.nodes?.[n.next])&&t.push(`WORKFLOW_HANDLE_TARGET_MISSING:${o}`),(["onApprove","onReject","initiatorApprovalPolicy","completionDeadline"].some(r=>r in n)||n.emptyPolicy==="skip")&&t.push(`WORKFLOW_HANDLE_APPROVAL_POLICY_FORBIDDEN:${o}`),(!Array.isArray(n.allowedOperations)||!n.allowedOperations.includes("complete")||n.allowedOperations.some(r=>!["complete","save_form","transfer","delegate","return"].includes(r)))&&t.push(`WORKFLOW_HANDLE_OPERATIONS_INVALID:${o}`),(!Array.isArray(n.requiredOperations)||!n.requiredOperations.includes("complete"))&&t.push(`WORKFLOW_HANDLE_COMPLETE_REQUIRED:${o}`)}return t}function Ko(e,t){let o=()=>{throw Object.assign(new Error("DATA_MUTATION_GRANT_INVALID"),{code:"DATA_MUTATION_GRANT_INVALID"})};if(!Array.isArray(e)||e.length<1||e.length>32)return o();let n=new Set;return e.map(i=>!i||typeof i!="object"||Array.isArray(i)||Object.keys(i).some(a=>!["resourceCode","operations","fieldCodes","maxOperations","allowRuntimeWorker"].includes(a))||typeof i.resourceCode!="string"||!/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/.test(i.resourceCode)||i.allowRuntimeWorker!==void 0&&i.allowRuntimeWorker!==!0||n.has(i.resourceCode)||t&&!t.has(i.resourceCode)||!Array.isArray(i.operations)||i.operations.length<1||i.operations.length>4||new Set(i.operations).size!==i.operations.length||i.operations.some(a=>!["create","update","delete","increment"].includes(a))||!Array.isArray(i.fieldCodes)||i.fieldCodes.length>128||new Set(i.fieldCodes).size!==i.fieldCodes.length||i.operations.some(a=>a!=="delete")&&!i.fieldCodes.length||i.fieldCodes.some(a=>typeof a!="string"||!/^[A-Za-z][A-Za-z0-9_]{0,62}$/.test(a)||t&&!t.get(i.resourceCode)?.has(a))||!Number.isSafeInteger(i.maxOperations)||i.maxOperations<1||i.maxOperations>1e3?o():(n.add(i.resourceCode),{resourceCode:i.resourceCode,operations:[...i.operations].sort(),fieldCodes:[...i.fieldCodes].sort(),maxOperations:i.maxOperations,...i.allowRuntimeWorker?{allowRuntimeWorker:!0}:{}})).sort((i,a)=>i.resourceCode.localeCompare(a.resourceCode))}var nf=5,of=20,rf=50,sf=50,af=100,Pt=class extends Error{constructor(o,n){super(o);this.code=o;this.pointer=n;this.name="NativeDataPolicyExpressionV2Error"}code;pointer};function gt(e,t){let o=[],n=(r,i,a)=>{a>5&&$t("NATIVE_DATA_POLICY_EXPRESSION_DEPTH_EXCEEDED",i);let s=wi(r,i),d=["allOf","anyOf"].filter(f=>f in s);if(d.length===0){o.push({rule:s,pointer:i}),o.length>50&&$t("NATIVE_DATA_POLICY_EXPRESSION_LEAVES_EXCEEDED",i);return}let c=d[0],l=s[c];(d.length!==1||Object.keys(s).length!==1||!Array.isArray(l)||l.length<1||l.length>20)&&$t("NATIVE_DATA_POLICY_EXPRESSION_GROUP_INVALID",i),l.forEach((f,p)=>n(f,`${i}/${c}/${p}`,a+1))};return n(e,t,1),o}function Ri(e,t){gt(e,t);let o=(n,r)=>{let i=wi(n,r);if(Array.isArray(i.allOf))return Go(i.allOf.flatMap((a,s)=>o(a,`${r}/allOf/${s}`)),r);if(Array.isArray(i.anyOf)){let a=[[]];return i.anyOf.forEach((s,d)=>{let c=o(s,`${r}/anyOf/${d}`);a=Go(a.flatMap(l=>c.map(f=>[...l,...f])),r)}),a}return[[i]]};return Go(o(e,t),t)}function Go(e,t){let o=e.reduce((n,r)=>n+r.length,0);return(e.length>50||o>100)&&$t("NATIVE_DATA_POLICY_EXPRESSION_EXPANSION_EXCEEDED",t),e}function wi(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&$t("NATIVE_DATA_POLICY_EXPRESSION_NODE_INVALID",t),e}function $t(e,t){throw new Pt(e,t)}var pe=class extends Error{constructor(o,n){super(`${o}: ${n}`);this.code=o;this.pointer=n}code;pointer},Pd=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,Ti=/^[A-Za-z_][A-Za-z0-9_]{0,127}$/;function vd(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new pe("NATIVE_PARENT_READ_INVALID",t);let o=e;if(Object.keys(o).some(n=>!["resourceCode","subtableFieldCode"].includes(n))||typeof o.resourceCode!="string"||o.resourceCode.length>64||!Pd.test(o.resourceCode)||typeof o.subtableFieldCode!="string"||!Ti.test(o.subtableFieldCode))throw new pe("NATIVE_PARENT_READ_INVALID",t);return{resourceCode:o.resourceCode,subtableFieldCode:o.subtableFieldCode}}function Ci(e,t){return[...(Array.isArray(e.rules)?e.rules:[]).map((o,n)=>({rule:o,pointer:`${t}/rules/${n}`,base:!0})),...e.readExpression===void 0?[]:gt(e.readExpression,`${t}/readExpression`).map(o=>({...o,base:!1}))]}function bn(e,t,o,n){let r=vd(o,n),i=e.find(m=>m.code===r.resourceCode),a=e.find(m=>m.code===t),d=(Array.isArray(i?.schema?.fields)?i.schema.fields:[]).find(m=>m.code===r.subtableFieldCode);if(!i||!a||i.code===a.code||d?.type!=="subtable"||d.subtable?.resourceCode!==t)throw new pe("NATIVE_PARENT_READ_BINDING_INVALID",n);if(e.flatMap(m=>(Array.isArray(m.schema?.fields)?m.schema.fields:[]).filter(E=>E.type==="subtable"&&E.subtable?.resourceCode===t).map(E=>({resource:m,field:E}))).length!==1)throw new pe("NATIVE_PARENT_READ_PARENT_AMBIGUOUS",n);let l=d.subtable.foreignKey,p=(Array.isArray(a.schema?.fields)?a.schema.fields:[]).find(m=>m.code===l);if(typeof l!="string"||!Ti.test(l)||p?.type!=="uuid")throw new pe("NATIVE_PARENT_READ_FOREIGN_KEY_INVALID",n);return{...r,childResourceCode:t,foreignKey:l,...d.subtable.orderField?{orderField:d.subtable.orderField}:{}}}function Si(e,t,o="/config/authz/dataPolicies"){let n=new Map;for(let[r,i]of t.entries())for(let a of Ci(i,`${o}/${r}`)){if(a.rule.parentRead===void 0)continue;if(Object.keys(a.rule).some(l=>!["parentRead","roleCodes"].includes(l)))throw new pe("NATIVE_PARENT_READ_RULE_KEYS_INVALID",a.pointer);if(a.base&&(i.operations?.length!==1||i.operations[0]!=="read"))throw new pe("NATIVE_PARENT_READ_READ_ONLY",a.pointer);if(e.find(l=>l.code===i.resourceCode)?.dataPolicyCode!==i.code)throw new pe("NATIVE_PARENT_READ_POLICY_BINDING_INVALID",a.pointer);let d=bn(e,i.resourceCode,a.rule.parentRead,`${a.pointer}/parentRead`),c=n.get(i.resourceCode);if(c&&c!==d.resourceCode)throw new pe("NATIVE_PARENT_READ_PARENT_AMBIGUOUS",a.pointer);n.set(i.resourceCode,d.resourceCode)}for(let[r,i]of n)if(n.has(i))throw new pe("NATIVE_PARENT_READ_MULTI_HOP_FORBIDDEN",`${o}/${t.findIndex(a=>a.resourceCode===r)}`)}function qo(e){return Ci(e,"/dataPolicy").some(t=>t.rule.parentRead!==void 0)}var Li=e=>!!e&&typeof e=="object"&&!Array.isArray(e),$i=(e,t)=>Object.keys(e).length===t.length&&Object.keys(e).every(o=>t.includes(o)),Di=e=>typeof e=="string"&&/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/.test(e)&&e.length<=100,ki=e=>typeof e=="string"&&/^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(e);function zo(e){throw new Error(`OPENXIANGDA_WORKFLOW_STAGE_${e}`)}function Pi(e){(!Li(e)||!$i(e,["workflowCode","resourceCode","actor","runningNodeIds","allowedStatuses"])||!Di(e.workflowCode)||!Di(e.resourceCode)||!["initiator","reader"].includes(String(e.actor))||!Array.isArray(e.runningNodeIds)||e.runningNodeIds.length>32||new Set(e.runningNodeIds).size!==e.runningNodeIds.length||e.runningNodeIds.some(t=>typeof t!="string"||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(t))||!Array.isArray(e.allowedStatuses)||e.allowedStatuses.length>5||new Set(e.allowedStatuses).size!==e.allowedStatuses.length||e.allowedStatuses.some(t=>!["approved","rejected","cancelled","terminated","returned"].includes(t))||e.runningNodeIds.length+e.allowedStatuses.length===0)&&zo("POLICY_INVALID")}function uf(e){(!Li(e)||!$i(e,["instanceId","subjectRecordId","expectedInstanceSequence"])||!ki(e.instanceId)||!ki(e.subjectRecordId)||!Number.isSafeInteger(e.expectedInstanceSequence)||e.expectedInstanceSequence<0)&&zo("GUARD_INVALID")}function ff(e,t,o){o?.some(n=>(n.kind==="record-match"||n.kind==="record-assert")&&n.resourceCode===e.resourceCode&&n.id.toLowerCase()===t.subjectRecordId.toLowerCase()&&n.assertions.some(r=>r.kind==="value"&&r.field==="revision"&&r.operator==="eq"&&Number.isSafeInteger(r.value)&&Number(r.value)>0))||zo("SOURCE_GUARD_REQUIRED")}var pf={type:"object",additionalProperties:!1,required:["workflowCode","resourceCode","actor","runningNodeIds","allowedStatuses"],properties:{workflowCode:{type:"string",pattern:"^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$",maxLength:100},resourceCode:{type:"string",pattern:"^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$",maxLength:100},actor:{enum:["initiator","reader"]},runningNodeIds:{type:"array",maxItems:32,uniqueItems:!0,items:{type:"string",pattern:"^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$"}},allowedStatuses:{type:"array",maxItems:5,uniqueItems:!0,items:{enum:["approved","rejected","cancelled","terminated","returned"]}}},anyOf:[{properties:{runningNodeIds:{minItems:1}}},{properties:{allowedStatuses:{minItems:1}}}]};var vt=class extends Error{constructor(o,n){super(o);this.code=o;this.pointer=n}code;pointer},me=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},vi=(e,t)=>e===t||e==="*"||e.endsWith(":*")&&t.startsWith(e.slice(0,-1));function Vi(e){let{policy:t,resource:o,baselineRoleCode:n,baselineCapabilities:r,pointer:i}=e,a=A=>A===void 0||A===!0||Array.isArray(A)&&A.length>0&&A.every(b=>typeof b=="string"&&b.length>0&&!e.baselineDeniedCapabilities?.some(O=>vi(O,b))&&r.some(O=>vi(O,b))),s=(A,b="")=>{throw new vt(A,`${i}/publicRead${b}`)},d=me(t.publicRead);(!t.publicRead||Object.keys(d).length!==1||!Object.hasOwn(d,"fields")||!Array.isArray(d.fields)||d.fields.length<1||d.fields.length>1e3||d.fields.some(A=>typeof A!="string"||!/^[A-Za-z][A-Za-z0-9_]{0,62}$/.test(A))||new Set(d.fields).size!==d.fields.length)&&s("AUTHENTICATED_PUBLIC_READ_FIELDS_INVALID","/fields"),(!Array.isArray(t.operations)||t.operations.length!==1||t.operations[0]!=="read"||t.readExpression!==void 0||t.writeBoundary!==void 0)&&s("AUTHENTICATED_PUBLIC_READ_POLICY_NOT_READ_ONLY"),(!n||!o||o.code!==t.resourceCode||o.dataPolicyCode!==t.code||!a([me(o.capabilities).read]))&&s("AUTHENTICATED_PUBLIC_READ_BASELINE_OR_RESOURCE_INVALID");let c=me(o),l=me(c.schema).fields;(!Array.isArray(l)||!l.length)&&s("AUTHENTICATED_PUBLIC_READ_RESOURCE_FIELDS_MISSING");let f=new Map(l.map(A=>[String(me(A).code),me(A)])),p=new Set(d.fields),m=me(c.fieldPolicies);for(let A of p){let b=me(f.get(A));(!f.has(A)||b.system===!0||me(me(c.surface).fields)[A]?.system===!0||lt.has(A))&&s("AUTHENTICATED_PUBLIC_READ_FIELD_NOT_DECLARED",`/fields/${A}`),(b.type==="subtable"||b.subtable!==void 0)&&s("AUTHENTICATED_PUBLIC_READ_SUBTABLE_UNSUPPORTED",`/fields/${A}`),a(me(m[A]).read)||s("AUTHENTICATED_PUBLIC_READ_FIELD_NOT_BASELINE_READABLE",`/fields/${A}`)}let E=[...f.keys()].filter(A=>!p.has(A));for(let A of E)a(me(m[A]).read)&&s("AUTHENTICATED_PUBLIC_READ_PRIVATE_FIELD_ACCESSIBLE",`/fields/${A}`);E.length&&on.some(A=>a(me(m[A]).read))&&s("AUTHENTICATED_PUBLIC_READ_PRIVATE_HISTORY_ACCESSIBLE")}var Fi=["exact-v1","nfkc-space-v1","nfkc-upper-ascii-v1"],Ef=256,Ft=class extends Error{constructor(o,n){super(`\u6761\u4EF6\u552F\u4E00\u952E\u58F0\u660E\u65E0\u6548\uFF1A${n}\uFF08${o}\uFF09`);this.pointer=o;this.reason=n}pointer;reason;code="NATIVE_UNIQUE_KEY_INVALID"},Jo=e=>!!(e&&typeof e=="object"&&!Array.isArray(e)),ie=(e,t)=>{throw new Ft(e,t)},Nn=(e,t)=>e<t?-1:e>t?1:0,Vt=(e,t,o)=>{Object.keys(e).some(n=>!t.includes(n))&&ie(o,"\u4E0D\u652F\u6301\u672A\u77E5\u5C5E\u6027")};function Wi(e,t,o="/uniqueKeys"){if(e===void 0)return;if(!Array.isArray(e)||e.length>8)return ie(o,"\u6BCF\u8D44\u6E90\u6700\u591A 8 \u6761\u89C4\u5219");let n=new Map(t.map(i=>[i.code,i])),r=new Set;return e.map((i,a)=>{let s=`${o}/${a}`;if(!Jo(i))return ie(s,"\u89C4\u5219\u5FC5\u987B\u662F\u5BF9\u8C61");if(Vt(i,["code","fields","when"],s),typeof i.code!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(i.code)||i.code.length>20||r.has(i.code))return ie(`${s}/code`,"\u9700\u8981\u4E0D\u91CD\u590D\u4E14\u4E0D\u8D85\u8FC7 20 \u5B57\u7B26\u7684 lower-kebab-case \u6807\u8BC6");if(r.add(i.code),!Array.isArray(i.fields)||i.fields.length<1||i.fields.length>4)return ie(`${s}/fields`,"\u5FC5\u987B\u9009\u62E9 1 \u5230 4 \u4E2A\u5B57\u6BB5");let d=new Set,c=i.fields.map((m,E)=>{let A=`${s}/fields/${E}`;if(!Jo(m))return ie(A,"\u5B57\u6BB5\u5FC5\u987B\u662F\u5BF9\u8C61");Vt(m,["fieldCode","normalizer"],A);let b=n.get(m.fieldCode);if(!b||!["text.short","uuid","option.single","resource-ref.single","user.single"].includes(b.type)||d.has(m.fieldCode))return ie(`${A}/fieldCode`,"\u9700\u8981\u4E0D\u91CD\u590D\u7684\u77ED\u6587\u672C\u3001UUID\u3001\u5355\u9009\u3001\u5355\u8BB0\u5F55\u5F15\u7528\u6216\u5355\u4EBA\u5B57\u6BB5");d.add(m.fieldCode);let O=m.normalizer===void 0?"exact-v1":m.normalizer;return!Fi.includes(O)||b.type!=="text.short"&&O!=="exact-v1"?ie(`${A}/normalizer`,"\u5F52\u4E00\u5316\u65B9\u5F0F\u4E0D\u652F\u6301\u6216\u4E0E\u5B57\u6BB5\u7C7B\u578B\u4E0D\u7B26"):{fieldCode:b.code,normalizer:O}}).sort((m,E)=>Nn(m.fieldCode,E.fieldCode)),l=i.when===void 0?[]:i.when;if(!Array.isArray(l)||l.length>4)return ie(`${s}/when`,"\u6700\u591A 4 \u4E2A\u5408\u53D6\u6761\u4EF6");let f=new Set,p=l.map((m,E)=>{let A=`${s}/when/${E}`;if(!Jo(m))return ie(A,"\u6761\u4EF6\u5FC5\u987B\u662F\u5BF9\u8C61");let b=n.get(m.fieldCode);if(!b)return ie(`${A}/fieldCode`,"\u5B57\u6BB5\u4E0D\u5B58\u5728");let O;if(m.operator==="empty"||m.operator==="nonempty"){if(Vt(m,["fieldCode","operator"],A),b.type!=="text.short")return ie(A,"\u7A7A\u503C\u6761\u4EF6\u4EC5\u652F\u6301\u77ED\u6587\u672C");O={fieldCode:b.code,operator:m.operator}}else if(m.operator==="in"||m.operator==="notIn"){Vt(m,["fieldCode","operator","values"],A);let y=new Set((b.options??[]).map(h=>h.value));if(b.type!=="option.single"||!Array.isArray(m.values)||m.values.length<1||m.values.length>16||m.values.some(h=>typeof h!="string"||h.length<1||h.length>128||!y.has(h))||new Set(m.values).size!==m.values.length)return ie(A,"\u96C6\u5408\u6761\u4EF6\u9700\u8981 1 \u5230 16 \u4E2A\u4E0D\u91CD\u590D\u7684\u5DF2\u58F0\u660E\u5355\u9009\u503C");O={fieldCode:b.code,operator:m.operator,values:[...m.values].sort(Nn)}}else if(m.operator==="eq"||m.operator==="ne"){if(Vt(m,["fieldCode","operator","value"],A),b.type!=="boolean"||typeof m.value!="boolean")return ie(A,"\u7B49\u503C\u6761\u4EF6\u4EC5\u652F\u6301\u5E03\u5C14\u5B57\u6BB5\u548C\u5E03\u5C14\u503C");O={fieldCode:b.code,operator:m.operator,value:m.value}}else return ie(`${A}/operator`,"\u53EA\u652F\u6301 empty\u3001nonempty\u3001in\u3001notIn \u548C\u5E03\u5C14 eq\u3001ne");let g=JSON.stringify(O);return f.has(g)?ie(A,"\u6761\u4EF6\u4E0D\u80FD\u91CD\u590D"):(f.add(g),O)}).sort((m,E)=>Nn(JSON.stringify(m),JSON.stringify(E)));return{code:i.code,fields:c,when:p}}).sort((i,a)=>Nn(i.code,a.code))}function xi(e,t){let o=new Set(e.filter(n=>n.type==="user.single").map(n=>n.code));return t?.some(n=>n.fields.some(r=>o.has(r.fieldCode))||n.when?.some(r=>r.operator==="eq"||r.operator==="ne"))?"1.1.0":"1.0.0"}var hn={type:"string",pattern:"^[A-Za-z_][A-Za-z0-9_]{0,62}$"},If={type:"array",maxItems:8,items:{type:"object",additionalProperties:!1,required:["code","fields"],properties:{code:{type:"string",maxLength:20,pattern:"^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$"},fields:{type:"array",minItems:1,maxItems:4,uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["fieldCode"],properties:{fieldCode:hn,normalizer:{enum:[...Fi]}}}},when:{type:"array",maxItems:4,uniqueItems:!0,items:{oneOf:[{type:"object",additionalProperties:!1,required:["fieldCode","operator"],properties:{fieldCode:hn,operator:{enum:["empty","nonempty"]}}},{type:"object",additionalProperties:!1,required:["fieldCode","operator","values"],properties:{fieldCode:hn,operator:{enum:["in","notIn"]},values:{type:"array",minItems:1,maxItems:16,uniqueItems:!0,items:{type:"string",minLength:1,maxLength:128}}}},{type:"object",additionalProperties:!1,required:["fieldCode","operator","value"],properties:{fieldCode:hn,operator:{enum:["eq","ne"]},value:{type:"boolean"}}}]}}}}};var ji={"openxiangda.workflow.instance.completed.v2":"commit","openxiangda.workflow.instance.rejected.v2":"release","openxiangda.workflow.instance.withdrawn.v2":"release"};function Mi(e,t){let o=()=>{throw new Error("NATIVE_EVENT_DECIMAL_RESERVATION_INVALID")},n=p=>!p||typeof p!="object"||Array.isArray(p)?o():p,r=n(e);if(Object.keys(r).some(p=>!["resourceCode","workflowCode","outcomes"].includes(p))||typeof r.resourceCode!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(r.resourceCode)||typeof r.workflowCode!="string"||!/^[A-Za-z0-9._:-]{1,128}$/.test(r.workflowCode)||t.execution!==void 0||!Array.isArray(r.outcomes)||!r.outcomes.length||r.outcomes.length>3)return o();let i=t.resources.find(p=>p.code===r.resourceCode),a=t.reservations.find(p=>p.mode==="reserve"&&p.resourceCode===r.resourceCode),s=t.workflows.find(p=>p.code===r.workflowCode);if(!i||!a||!s||s.resourceCode!==i.code)return o();let d=i.fields.find(p=>p.code===a.statusFieldCode);if(d?.type!=="option.single")return o();let c=new Set(d.options?.map(p=>p.value)),l=new Set,f=r.outcomes.map(p=>{let m=n(p),E=m.eventType;return Object.keys(m).some(A=>!["eventType","mode","eligibleChildStatuses"].includes(A))||typeof E!="string"||!Object.prototype.hasOwnProperty.call(ji,E)||!t.eventTypes.includes(E)||l.has(E)||m.mode!==ji[E]||!Array.isArray(m.eligibleChildStatuses)||!m.eligibleChildStatuses.length||m.eligibleChildStatuses.length>16||new Set(m.eligibleChildStatuses).size!==m.eligibleChildStatuses.length||m.eligibleChildStatuses.some(A=>typeof A!="string"||!/^[A-Za-z0-9._:-]{1,128}$/.test(A)||!c.has(A))?o():(l.add(E),{eventType:E,mode:m.mode,eligibleChildStatuses:[...m.eligibleChildStatuses].sort()})}).sort((p,m)=>p.eventType.localeCompare(m.eventType));return{resourceCode:r.resourceCode,workflowCode:r.workflowCode,outcomes:f}}function Ui(e,t){let o=n=>Array.isArray(n)?n.filter(r=>r&&typeof r=="object"&&!Array.isArray(r)):[];return{eventTypes:Array.isArray(t.eventTypes)?t.eventTypes:[],execution:t.execution,resources:o(e.data?.resources).map(n=>({code:n.code,fields:o(n.schema?.fields).map(r=>({code:r.code,type:r.type,options:o(r.options).map(i=>({value:i.value}))}))})),reservations:o(e.backend?.operations).flatMap(n=>n.platformAccess?.decimalReservation?[n.platformAccess.decimalReservation]:[]),workflows:o(e.workflows?.definitions).map(n=>({code:n.definition?.code,resourceCode:n.definition?.subject?.resourceCode}))}}var Ho=class extends Error{constructor(o,n){super(n);this.pointer=o}pointer;code="NATIVE_EVENT_ACTION_INVALID"};function Bi(e,t,o="/events/subscriptions"){if(e.execution===void 0)return;let n=(A,b)=>{throw new Ho(`${o}${A}`,b)},r=(A,b,O)=>((!A||typeof A!="object"||Array.isArray(A)||Object.keys(A).some(g=>!O.includes(g)))&&n(b,"Invalid action object or unsupported property"),A),i=r(e.execution,"/execution",["kind","version","operations"]);(i.kind!=="native-data"||i.version!==1)&&n("/execution","Expected native-data version 1"),e.platformAccess&&n("/platformAccess","Native actions do not use application runtime capabilities"),(!Array.isArray(e.eventTypes)||!e.eventTypes.length||e.eventTypes.some(A=>!/^openxiangda\.data\.record\.(created|updated|deleted)\.v2$/.test(A)))&&n("/eventTypes","Native data actions require declared data events");let a=e.filter?.resourceCodes;(!Array.isArray(a)||!a.length||a.length>20)&&n("/filter/resourceCodes","Native actions require explicit source resources");let s=new Map(t.map(A=>[A.code,A])),d=a.map(A=>{let b=s.get(A);return b||n("/filter/resourceCodes","Unknown source resource"),new Set((b.schema?.fields||[]).map(O=>O.code))}),c=new Set(e.payload?.fields||[]),l=e.payload?.includeChanges===!0,f=(A,b)=>{let O=r(A,b,["source","path","value"]);if(O.source==="literal"){(!Object.hasOwn(O,"value")||Object.hasOwn(O,"path"))&&n(b,"Literal binding requires only value");let u;try{u=JSON.stringify(O.value)}catch{n(b,"Literal must be JSON")}return(u===void 0||Buffer.byteLength(u)>65536)&&n(b,"Literal is too large or not JSON"),{source:"literal",value:JSON.parse(u)}}(O.source!=="event"||typeof O.path!="string"||Object.hasOwn(O,"value"))&&n(b,"Expected a literal or event binding");let g=O.path.split(".");(g.length>8||g.some(u=>!/^[A-Za-z0-9_-]+$/.test(u)||["__proto__","prototype","constructor"].includes(u)))&&n(b,"Invalid event path");let y=/^data\.projection\.([A-Za-z][A-Za-z0-9_]{0,62})$/.exec(O.path),h=/^data\.changes\.([A-Za-z][A-Za-z0-9_]{0,62})\.(before|after)$/.exec(O.path);if(y||h){let u=(y||h)[1];d.some(I=>!I.has(u))&&n(b,"Source field must exist on every filtered resource"),c.add(u),h&&(l=!0)}else["id","time","type","subject","data.recordId","data.revision","data.operation","data.resourceCode"].includes(O.path)||n(b,"Event path is not part of the data event contract");return{source:"event",path:O.path}};(!Array.isArray(i.operations)||i.operations.length<1||i.operations.length>16)&&n("/execution/operations","Expected 1 to 16 operations");let p={},m=i.operations.map((A,b)=>{let O=`/execution/operations/${b}`,g=r(A,O,["operation","resourceCode","data","id","expectedRevision"]);["create","update","delete"].includes(g.operation)||n(O,"Unsupported Native operation");let y=s.get(g.resourceCode);y||n(O,"Unknown action target resource");let h=new Map((y.schema?.fields||[]).map(I=>[I.code,I])),u=g.data===void 0?{}:r(g.data,`${O}/data`,[...h.keys()]);return Object.keys(u).length>32&&n(O,"Maximum 32 mapped fields per operation"),g.operation==="create"&&(g.id!==void 0||g.expectedRevision!==void 0)&&n(O,"Create does not accept id or expectedRevision"),g.operation==="delete"&&g.data!==void 0&&n(O,"Delete does not accept data"),Object.keys(u).some(I=>h.get(I)?.type==="serial-number")&&n(O,"Generated fields cannot be assigned"),p[g.resourceCode]=ee(y),{operation:g.operation,resourceCode:g.resourceCode,...g.operation==="create"?{}:{id:f(g.id,`${O}/id`),expectedRevision:f(g.expectedRevision,`${O}/expectedRevision`)},...g.operation==="delete"?{}:{data:Object.fromEntries(Object.entries(u).map(([I,R])=>[I,f(R,`${O}/data/${I}`)]))}}});(c.size>32||[...c].some(A=>d.some(b=>!b.has(A))))&&n("/payload/fields","Payload must contain at most 32 declared source fields");let E={kind:"native-data",version:1,operations:m,resourceDigests:p};return Buffer.byteLength(JSON.stringify(E))>65536&&n("/execution","Action plan exceeds 64 KiB"),{execution:{...E,digest:ee(E)},payload:{includeChanges:l,fields:[...c].sort()}}}function Me(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function Gi(e,t){if(e?.instanceCommands===void 0)return[];let o=Me(e.instanceCommands);if(!o||!Object.keys(o).length||Object.keys(o).some(r=>!["withdraw","terminate"].includes(r)))return["WORKFLOW_INSTANCE_COMMAND_POLICIES_INVALID"];let n=[];for(let[r,i]of Object.entries(o)){let a=Me(i),s=r==="withdraw"?["beforeFact","reasonRequired"]:["beforeFact","capability"];if(!a||!Object.keys(a).length||Object.keys(a).some(d=>!s.includes(d))||Object.hasOwn(a,"reasonRequired")&&typeof a.reasonRequired!="boolean"){n.push(`WORKFLOW_INSTANCE_COMMAND_POLICY_INVALID:${r}`);continue}if(r==="terminate"){let d=a.capability;(typeof d!="string"||d.length>255||!/^app:[a-z][a-z0-9]*(?:-[a-z0-9]+)*:[A-Za-z0-9:._-]+$/.test(d)||t&&(!d.startsWith(`app:${t.appCode}:`)||!t.capabilities.includes(d)))&&n.push("WORKFLOW_INSTANCE_TERMINATE_CAPABILITY_INVALID")}if(Object.hasOwn(a,"beforeFact")){let d=a.beforeFact,c=Me(e.inputSchema),l=Me(Me(c?.properties)?.[d]),f=Me(Me(e.subject)?.factProjection)?.[d],p=t?.fields.get(f);(typeof d!="string"||!/^[A-Za-z][A-Za-z0-9_]{0,62}$/.test(d)||!Array.isArray(c?.required)||!c.required.includes(d)||l?.type!=="string"||l?.format!=="date-time"||typeof f!="string"||t&&(p?.type!=="datetime"||p.nullable===!0))&&n.push(`WORKFLOW_INSTANCE_COMMAND_DEADLINE_FACT_INVALID:${r}`)}}return n}function hf(e,t){let o=e?.terminate?.capability;return typeof o=="string"&&/^app:[a-z][a-z0-9]*(?:-[a-z0-9]+)*:[A-Za-z0-9:._-]+$/.test(o)&&t.includes(o)}function Rf(e){return e?.withdraw?.reasonRequired!==!1}function Ki(e){if(typeof e!="string")return null;let t=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,3}))?(Z|[+-]\d{2}:\d{2})$/.exec(e);if(!t)return null;let[,o,n,r,i,a,s]=t,d=t[8],c=new Date(Date.UTC(Number(o),Number(n),0)).getUTCDate();if(Number(n)<1||Number(n)>12||Number(r)<1||Number(r)>c||Number(i)>23||Number(a)>59||Number(s)>59||d!=="Z"&&(Number(d.slice(1,3))>23||Number(d.slice(4))>59))return null;let l=Date.parse(e);return Number.isFinite(l)?l:null}function wf(e,t,o,n){let r=e?.[t];if(!r||r.beforeFact===void 0)return null;let i=r.beforeFact,a=Me(o),s=i&&a&&Object.hasOwn(a,i)?Ki(a[i]):null,d=n instanceof Date?n.getTime():Ki(n);return s===null||d===null||!Number.isFinite(d)?"WORKFLOW_V2_CANCELLATION_DEADLINE_INVALID":d<s?null:"WORKFLOW_V2_CANCELLATION_DEADLINE_PASSED"}var _e=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},Ze=(e,t)=>typeof e=="string"&&!!e.trim()&&e.length<=t,Vd=/^[A-Za-z][A-Za-z0-9_-]*(?:\.[A-Za-z][A-Za-z0-9_-]*){0,15}$/,Yo=e=>typeof e=="string"&&e.length<=256&&Vd.test(e)&&!e.split(".").some(t=>["__proto__","prototype","constructor"].includes(t));function wn(e,t){let o=_e(e),n=!0;for(let r of t.split(".")){n&&=Array.isArray(o.required)&&o.required.includes(r);let i=_e(o.properties)[r];if(!i||typeof i!="object")return null;o=_e(i)}return{schema:o,required:n}}function Wt(e){let t=new Set,o=[],n=2048,r=(i,a)=>{if(--n<0||a>20){o.push("WORKFLOW_EXPRESSION_BUDGET_EXCEEDED");return}let s=_e(i);if(s.op==="path")Yo(s.path)?t.add(s.path):o.push("WORKFLOW_EXPRESSION_PATH_INVALID");else{if(s.op==="literal")return;if(s.op==="and"||s.op==="or")if(!Array.isArray(s.values)||!s.values.length||s.values.length>128)o.push("WORKFLOW_EXPRESSION_GROUP_INVALID");else for(let d of s.values){if(n<0)break;r(d,a+1)}else s.op==="not"||s.op==="exists"?r(s.value,a+1):["eq","neq","gt","gte","lt","lte","in","contains"].includes(String(s.op))?(r(s.left,a+1),r(s.right,a+1)):o.push("WORKFLOW_EXPRESSION_OPERATOR_INVALID")}};return r(e,0),{paths:[...t],errors:[...new Set(o)]}}function qi(e){if(e?.readability===void 0)return[];let t=[],o=_t(e),n=_e(e.readability);(Object.keys(n).some(s=>!["variables","logic"].includes(s))||!Object.keys(n).length)&&t.push("WORKFLOW_READABILITY_INVALID");let r=_e(n.variables);n.variables!==void 0&&(typeof n.variables!="object"||Array.isArray(n.variables)||n.variables===null)&&t.push("WORKFLOW_VARIABLES_INVALID"),Object.keys(r).length>128&&t.push("WORKFLOW_VARIABLE_LIMIT_EXCEEDED");for(let[s,d]of Object.entries(r)){let c=_e(d);(!Yo(s)||!wn(o,s))&&t.push(`WORKFLOW_VARIABLE_SOURCE_UNKNOWN:${s}`),(!Ze(c.label,160)||Object.keys(c).some(l=>!["label","unit","description"].includes(l))||c.unit!==void 0&&!Ze(c.unit,32)||c.description!==void 0&&!Ze(c.description,2e3))&&t.push(`WORKFLOW_VARIABLE_METADATA_INVALID:${s}`)}let i=n.logic===void 0?[]:n.logic;(!Array.isArray(i)||i.length>32)&&t.push("WORKFLOW_LOGIC_LIMIT_INVALID");let a=new Set;for(let s of Array.isArray(i)?i.slice(0,32):[]){let d=_e(s),c=String(d.code||"");e.approvedDelegation&&c==="kernel-approved-delegation"&&t.push("WORKFLOW_LOGIC_PLATFORM_CODE_RESERVED"),(!/^[a-z][a-z0-9-]{2,63}$/.test(c)||a.has(c)||!Ze(d.title,160)||!Ze(d.description,4e3)||Object.keys(d).some(l=>!["code","title","description","phase","nodeId","inputPaths","outputPaths","source"].includes(l)))&&t.push(`WORKFLOW_LOGIC_METADATA_INVALID:${c}`),a.add(c),(!["submission","node_input","completion"].includes(String(d.phase))||d.phase==="node_input"&&!_e(e.nodes)[String(d.nodeId)]||d.phase!=="node_input"&&d.nodeId!==void 0)&&t.push(`WORKFLOW_LOGIC_ANCHOR_INVALID:${c}`);for(let l of["inputPaths","outputPaths"]){let f=d[l];if(!(l==="outputPaths"&&f===void 0))if(!Array.isArray(f)||f.length>32||new Set(f).size!==f.length)t.push(`WORKFLOW_LOGIC_PATHS_INVALID:${c}:${l}`);else for(let p of f)(!Yo(p)||!wn(o,p))&&t.push(`WORKFLOW_LOGIC_SOURCE_UNKNOWN:${c}:${String(p)}`)}if(d.source!==void 0){let l=_e(d.source);(!Ze(l.path,256)||String(l.path).startsWith("/")||String(l.path).includes("..")||String(l.path).includes("://")||!/^sha256:[a-f0-9]{64}$/.test(String(l.digest))||l.symbol!==void 0&&!Ze(l.symbol,160)||Object.keys(l).some(f=>!["path","symbol","digest"].includes(f)))&&t.push(`WORKFLOW_LOGIC_SOURCE_REFERENCE_INVALID:${c}`)}}for(let s of Object.values(_e(e.nodes))){let d=_e(s),c=Array.isArray(d.branches)?d.branches:[];for(let l of c){if(!l.when)continue;let f=Wt(l.when);t.push(...f.errors.map(p=>`${p}:${d.id}`));for(let p of f.paths)wn(o,p)||t.push(`WORKFLOW_VARIABLE_SOURCE_UNKNOWN:${d.id}:${p}`)}}return[...new Set(t)]}function Tn(e,t){let o=_t(e),n=je(e).regions,r=[],i=new Map,a=[];for(let l of Object.values(e.nodes)){if(l.kind==="approval")for(let[f,p,m]of[["approve",l.onApprove,"\u540C\u610F"],["reject",l.onReject,"\u62D2\u7EDD"]])p&&r.push({id:`${l.id}:${f}`,from:l.id,to:p,kind:f,label:m,variablePaths:[]});if(l.kind==="approval"||l.kind==="handle")for(let f of new Set(xe(l)))e.nodes[f]?.kind==="correction"&&r.push({id:`${l.id}:return:${f}`,from:l.id,to:f,kind:"return",label:"\u9000\u56DE\u53D1\u8D77\u4EBA\u8865\u6B63",variablePaths:[]});if(l.kind==="parallel")for(let[f,p]of(l.branches||[]).entries()){let m=p.when?Wt(p.when):{paths:[],errors:[]};for(let E of m.paths)i.has(E)||i.set(E,new Set),i.get(E).add(l.id);r.push({id:`${l.id}:parallel:${p.id}`,from:l.id,to:p.target,kind:"branch",parallelBranch:!0,label:p.title||`\u5206\u652F ${f+1}`,priority:f+1,...p.when?{expression:p.when}:{},variablePaths:m.paths})}if(l.kind==="join"&&l.next&&r.push({id:`${l.id}:next`,from:l.id,to:l.next,kind:"next",label:"\u5168\u90E8\u5206\u652F\u5B8C\u6210\u540E\u7EE7\u7EED",variablePaths:[]}),l.kind==="handle"&&l.next&&r.push({id:`${l.id}:next`,from:l.id,to:l.next,kind:"next",label:"\u529E\u7406\u5B8C\u6210",variablePaths:[]}),l.kind==="correction"&&l.next&&r.push({id:`${l.id}:resubmit`,from:l.id,to:l.next,kind:"resubmit",label:"\u91CD\u65B0\u63D0\u4EA4\uFF0C\u6309\u9000\u56DE\u8BBE\u7F6E\u7EE7\u7EED",variablePaths:[]}),l.kind==="cc"&&l.next&&r.push({id:`${l.id}:next`,from:l.id,to:l.next,kind:"next",label:"\u6284\u9001\u540E\u7EE7\u7EED",variablePaths:[]}),l.kind==="action"&&l.next){let f=Object.values(l.inputs||{}).flatMap(p=>p.source==="fact"?[p.path]:[]);for(let p of f)i.has(p)||i.set(p,new Set),i.get(p).add(l.id);r.push({id:`${l.id}:next`,from:l.id,to:l.next,kind:"next",label:te(l)?"\u53D1\u9001\u540E\u7EE7\u7EED":"\u6210\u529F\u56DE\u6267\u540E\u7EE7\u7EED",variablePaths:f})}if(l.kind==="condition"){for(let[f,p]of(l.branches||[]).entries()){let m=Wt(p.when);for(let E of m.paths)i.has(E)||i.set(E,new Set),i.get(E).add(l.id);r.push({id:`${l.id}:branch:${f}`,from:l.id,to:p.target,kind:"branch",label:p.label||`\u6761\u4EF6 ${f+1}`,priority:f+1,expression:p.when,variablePaths:m.paths}),a.push(...m.errors.map(E=>({code:E,path:l.id})))}l.otherwise&&r.push({id:`${l.id}:default`,from:l.id,to:l.otherwise,kind:"default",label:"\u5747\u4E0D\u6EE1\u8DB3\u65F6",variablePaths:[]})}}let s=[...e.readability?.logic||[]];if(e.approvedDelegation){let l=e.approvedDelegation,f=l.confirmer==="initiator"?"\u7533\u8BF7\u4EBA\u672C\u4EBA":"\u6240\u9009\u4EE3\u7406\u4EBA";s.push({code:"kernel-approved-delegation",title:"\u6279\u51C6\u540E\u6574\u6279\u6388\u6743\u4EE3\u7406",phase:"completion",inputPaths:[l.requestsField],description:`\u6279\u51C6\u65F6\u6838\u9A8C${f}\u5728\u5F53\u524D\u9000\u56DE\u5468\u671F\u5B8C\u6210\u201C${e.nodes[l.confirmationNodeId]?.title||l.confirmationNodeId}\u201D\u7684\u4EBA\u5DE5\u786E\u8BA4\uFF1B\u968F\u540E\u91CD\u65B0\u6838\u9A8C\u53CC\u65B9\u5F53\u524D\u8D26\u53F7\u3001\u804C\u8D23\u3001\u4FEE\u8BA2\u3001\u8303\u56F4\u4E0E\u5B8C\u6574\u6709\u6548\u671F\uFF0C\u6574\u6279\u6388\u6743\uFF08\u6700\u591A${l.maxRequests}\u884C\uFF09\u3002\u4EFB\u4E00\u884C\u5931\u8D25\uFF0C\u6279\u51C6\u4E0E\u5168\u90E8\u6388\u6743\u4E00\u8D77\u56DE\u6EDA\uFF1B\u539F\u547D\u4EE4\u6062\u590D\u4E0D\u91CD\u65B0\u6FC0\u6D3B\u5DF2\u64A4\u9500\u6388\u6743\u3002`})}let c=[...new Set([...i.keys(),...Object.keys(e.readability?.variables||{}),...s.flatMap(l=>[...l.inputPaths,...l.outputPaths||[]])])].slice(0,128).map(l=>{let f=wn(o,l),p=e.readability?.variables?.[l],m=l.split("."),E=e.subject?.factProjection[m[0]],A=m[0]==="steps"?e.nodes[m[1]]:void 0;return f||a.push({code:"WORKFLOW_VARIABLE_SOURCE_UNKNOWN",path:l}),{path:l,label:p?.label||String(f?.schema.title||l),type:String(f?.schema.type||"unknown"),...p,required:f?.required||!1,usedBy:[...i.get(l)||[]],source:f&&A?.handler?{kind:"step_output",nodeId:A.id,handlerCode:A.handler.code,handlerVersion:A.handler.version}:f&&E&&e.subject?{kind:"subject_field",resourceCode:e.subject.resourceCode,fieldPath:[E,...m.slice(1)].join(".")}:{kind:f?"input":"unknown"}}});return{schemaVersion:"openxiangda.workflow-graph/v2",workflowCode:e.code,definitionDigest:t,startAt:e.startAt,fixedTopology:!0,branchStrategy:"first_match",nodes:Object.values(e.nodes).map(l=>({id:l.id,kind:l.kind,title:l.title||l.id,...l.kind==="parallel"?{parallel:{joinNodeId:l.join,branchNodeIds:n.find(f=>f.parallelNodeId===l.id)?.branches.flatMap(f=>f.nodeIds)||[],branchCount:l.branches?.length||0}}:{},...l.binding?{binding:l.binding}:{},...l.mode?{mode:l.mode}:{},...l.outcome?{outcome:l.outcome}:{},...l.kind==="cc"?{emptyPolicy:l.emptyPolicy,notify:l.notify!==!1}:{},...l.kind==="approval"?{emptyPolicy:l.emptyPolicy||"block",initiatorApprovalPolicy:l.initiatorApprovalPolicy||"manual",...l.completionDeadline?{completionDeadline:{...l.completionDeadline}}:{}}:{},...te(l)?{presentation:"notification"}:{},...l.kind==="action"&&l.handler&&!te(l)?{businessStep:{handler:l.handler,inputs:l.inputs||{},outputPaths:Object.keys(_e(l.outputSchema).properties||{}).map(f=>`steps.${l.id}.${f}`)}}:{}})),edges:r,variables:c,logic:s,diagnostics:a}}function Fd(e,t=[]){let o=r=>{let i=t.find(a=>a.path===r)?.label;return i&&i!==r?i:void 0},n=o(e);if(n)return n;for(let r=e.lastIndexOf(".");r>0;r=e.lastIndexOf(".",r-1)){let i=o(e.slice(0,r));if(!i)continue;let a=e.slice(r+1);return a==="value"?`${i}\uFF08\u503C\uFF09`:a==="label"?`${i}\uFF08\u663E\u793A\u540D\u79F0\uFF09`:`${i}.${a}`}return e}function Rn(e,t=[],o=0){if(!e||o>20)return"\u65E0\u6CD5\u8BC6\u522B\u7684\u6761\u4EF6";if(e.op==="path")return Fd(e.path,t);if(e.op==="literal")return JSON.stringify(e.value)??"\u7F3A\u503C";if(e.op==="and"||e.op==="or")return e.values.slice(0,128).map(a=>`\uFF08${Rn(a,t,o+1)}\uFF09`).join(e.op==="and"?" \u4E14 ":" \u6216 ");if(e.op==="not"||e.op==="exists")return`${e.op==="not"?"\u4E0D\u6EE1\u8DB3":"\u5B58\u5728"}\uFF08${Rn(e.value,t,o+1)}\uFF09`;if(!("left"in e))return"\u65E0\u6CD5\u8BC6\u522B\u7684\u6761\u4EF6";let n={eq:"=",neq:"\u2260",gt:">",gte:"\u2265",lt:"<",lte:"\u2264",in:"\u5C5E\u4E8E",contains:"\u5305\u542B"},r=e.left.op==="path"?e.left.path:void 0,i=r&&e.right.op==="literal"&&typeof e.right.value=="number"?t.find(a=>a.path===r)?.unit:void 0;return`${Rn(e.left,t,o+1)} ${n[e.op]} ${Rn(e.right,t,o+1)}${i?` ${i}`:""}`}function zi(e,t=0){return!Array.isArray(e)||e.length>64||t>1?!1:e.every(o=>{if(!o||typeof o!="object"||Array.isArray(o)||o.readonlyWhen!==void 0)return!1;if(o.subtable!==void 0){let n=o.subtable;return n&&n.create===!1&&n.delete===!1&&n.reorder===!1&&zi(n.fields,t+1)}return o.readonly===!0})}function xt(e){let t=[];for(let[o,n]of Object.entries(e?.nodes||{}))if(n.initiatorApprovalPolicy!==void 0){if(n.kind!=="approval"||!["manual","auto_approve"].includes(n.initiatorApprovalPolicy)){t.push(`WORKFLOW_INITIATOR_APPROVAL_POLICY_INVALID:${o}`);continue}n.initiatorApprovalPolicy==="auto_approve"&&((n.taskPageCode!==void 0&&(typeof n.taskPageCode!="string"||!zi(e.taskPages?.[n.taskPageCode]?.fields))||[n.fieldPolicy?.default,...Object.values(n.fieldPolicy?.fields||{})].some(r=>r==="edit"||r==="edit_required"))&&t.push(`WORKFLOW_INITIATOR_APPROVAL_INPUT_REQUIRED:${o}`),(n.operationPolicy?.approve?.opinion==="required"||n.operationPolicy?.approve?.commentRequired===!0)&&t.push(`WORKFLOW_INITIATOR_APPROVAL_COMMENT_REQUIRED:${o}`))}return t}function $f(e,t,o,n,r){return e.kind==="approval"&&e.initiatorApprovalPolicy==="auto_approve"&&xt({nodes:{node:e},...r?{taskPages:r}:{}}).length===0&&t!=="return_review"&&!!o&&n.user_id===o&&n.status==="active"&&n.participant_kind==="primary"&&["resolution","resolution_retry"].includes(n.source||"")&&!n.source_participant_id&&!n.delegate_authorization_id}var vf=8,Vf={type:"array",minItems:2,maxItems:8,uniqueItems:!0,items:{type:"string",maxLength:128,pattern:"^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$"}};function Cn(e){if(e.roleCodes===void 0)return[];let t=e.roleCodes;if(!["app_role","app_role_in_scope"].includes(e.provider||"")||e.roleCode!==void 0||e.candidateField!==void 0||!Array.isArray(t)||t.length<2||t.length>8||new Set(t).size!==t.length||t.some(o=>typeof o!="string"||o.length>128||!/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/.test(o)))return["WORKFLOW_V2_BINDING_ROLE_UNION_INVALID"];if(e.provider==="app_role_in_scope"){let o=e.scope,n=typeof o?.value=="string"&&o.value.length>0&&o.value.length<=255&&o.valueFrom===void 0,r=typeof o?.valueFrom=="string"&&o.valueFrom.length<=255&&/^[A-Za-z][A-Za-z0-9_-]*(?:\.[A-Za-z][A-Za-z0-9_-]*)*$/.test(o.valueFrom)&&!o.valueFrom.split(".").some(i=>["__proto__","prototype","constructor"].includes(i))&&o.value===void 0;if(!o||typeof o!="object"||Array.isArray(o)||Object.keys(o).some(i=>!["dimension","value","valueFrom"].includes(i))||typeof o.dimension!="string"||!/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/.test(o.dimension)||!n&&!r)return["WORKFLOW_V2_BINDING_ROLE_UNION_SCOPE_INVALID"]}else if(e.scope!==void 0)return["WORKFLOW_V2_BINDING_ROLE_UNION_SCOPE_INVALID"];return[]}function Ff(e){return e.roleCodes?[...e.roleCodes]:e.roleCode?[e.roleCode]:typeof e.until=="object"&&e.until.roleCode?[e.until.roleCode]:[]}function Ji(e){return e.some(t=>Object.values(t.binding.bindings).some(o=>o.roleCodes!==void 0))}function Hi(e){if(e.selectedInputPath===void 0)return[];let t=e.selectedInputPath;return!["app_role","app_role_in_scope"].includes(e.provider||"")||e.candidateField!==void 0||e.inputPath!==void 0||e.routing!==void 0||e.roleCode===void 0&&e.roleCodes===void 0||typeof t!="string"||t.length>255||!/^[A-Za-z][A-Za-z0-9_-]*(?:\.[A-Za-z][A-Za-z0-9_-]*)*$/.test(t)||t.split(".").some(o=>["__proto__","constructor","prototype"].includes(o))?["WORKFLOW_V2_ROLE_INPUT_SELECTION_INVALID"]:[]}function Yi(e){return e.some(t=>Object.values(t.binding.bindings).some(o=>o.selectedInputPath!==void 0))}var Xi=20,Zi=200,Wd=["fixed_users","initiator","input_users","form_field_users","app_role","app_role_in_scope","previous_node_actor"];function Xo(e,t){let o=[];for(let[n,r]of Object.entries(e?.nodes||{})){if(r?.kind!=="cc"||((Object.keys(r).some(d=>!["id","kind","title","binding","next","emptyPolicy","notify","administration"].includes(d))||typeof r.title!="string"||!r.title.trim()||r.title.length>255||typeof r.binding!="string"||!r.binding.trim()||r.binding.length>255||typeof r.next!="string"||!r.next.trim()||!e.nodes?.[r.next]||!["block","skip"].includes(r.emptyPolicy)||r.notify!==void 0&&typeof r.notify!="boolean")&&o.push(`WORKFLOW_CC_NODE_INVALID:${n}`),!t))continue;let i=t.bindings?.[r.binding];if(!i){o.push(`WORKFLOW_CC_BINDING_NOT_FOUND:${n}`);continue}Wd.includes(i.provider)||o.push(`WORKFLOW_CC_PROVIDER_INVALID:${n}`);let a=i.min??1,s=i.max??20;(!Number.isSafeInteger(a)||!Number.isSafeInteger(s)||a<1||s<a||s>200||i.provider==="fixed_users"&&(!Array.isArray(i.users)||!i.users.length||i.users.length>s))&&o.push(`WORKFLOW_CC_RECIPIENT_LIMIT_INVALID:${n}`)}return[...new Set(o)]}var Sn=["complete","approve","reject","save_form","return","transfer","delegate","add_assignee"],Zo=["fixed_users","app_role","app_role_in_scope"],xd=["single","any","all","sequence"],Ue=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Qe=(e,t)=>Object.keys(e).every(o=>t.includes(o)),jt=(e,t,o)=>Array.isArray(e)&&e.length>0&&e.length<=o&&new Set(e).size===e.length&&e.every(n=>typeof n=="string"&&t.includes(n));function Et(e){return e.allowedOperations||(e.kind==="handle"?["complete","save_form","return","transfer","delegate"]:Sn.filter(t=>t!=="complete")).filter(t=>t!=="save_form"||!!e.taskPageCode)}function jd(e,t){return t?.opinion!==void 0?t.opinion==="required":t?.commentRequired??e==="reject"}function Md(e,t){return["transfer","delegate","add_assignee","return"].includes(e)?t?.opinion!==void 0?t.opinion==="required":t?.reasonRequired!==!1:!0}var At=["none","optional","required"];function Mt(e,t){return e==="save_form"?"none":t?.opinion?t.opinion:(["complete","approve","reject"].includes(e)?jd(e,t):Md(e,t))?"required":"optional"}function Dn(e,t){return t?.minimumOpinion??(Mt(e,t)==="required"?"required":"none")}function Bf(e){return e.hasTaskPage&&(e.operationModel==null||e.operationModel==="configured-v1"&&e.allowedOperations?.includes("save_form")===!0)}function es(e,t,o={},n=!1){let r=["label","commentRequired","reasonRequired","opinion"];if(!Ue(e)||!Object.keys(e).length||!Qe(e,n?[...r,"enabled"]:[...r,"minimumOpinion"])||e.label!==void 0&&(typeof e.label!="string"||!e.label.trim()||e.label.length>40||/[\u0000-\u001f\u007f]/.test(e.label))||e.enabled!==void 0&&(typeof e.enabled!="boolean"||t==="approve"&&!e.enabled)||e.opinion!==void 0&&(!At.includes(e.opinion)||t==="save_form")||e.minimumOpinion!==void 0&&(!At.includes(e.minimumOpinion)||t==="save_form")||e.commentRequired!==void 0&&(typeof e.commentRequired!="boolean"||!["complete","approve","reject"].includes(t))||e.reasonRequired!==void 0&&(typeof e.reasonRequired!="boolean"||!["transfer","delegate","add_assignee","return"].includes(t))||e.opinion!==void 0&&[e.commentRequired,e.reasonRequired].some(i=>i!==void 0&&i!==(e.opinion==="required")))return!1;if(n&&(e.opinion!==void 0||e.commentRequired!==void 0||e.reasonRequired!==void 0)){let i=e.opinion??(e.commentRequired??e.reasonRequired?"required":"optional");if(At.indexOf(i)<At.indexOf(Dn(t,o)))return!1}return!(!n&&e.minimumOpinion!==void 0&&At.indexOf(Mt(t,e))<At.indexOf(e.minimumOpinion))}function Qo(e,t){let o=[];for(let[n,r]of Object.entries(e?.nodes||{})){if(!Ue(r))continue;let i=r.administration,a=r.operationPolicy;if(r.kind==="approval"||r.kind==="handle"){let d=Et(r);d.includes(r.kind==="handle"?"complete":"approve")||o.push(`WORKFLOW_NODE_FORWARD_OPERATION_REQUIRED:${n}`),d.includes("save_form")&&!r.taskPageCode&&o.push(`WORKFLOW_NODE_SAVE_PAGE_REQUIRED:${n}`),r.requiredOperations!==void 0&&(!jt(r.requiredOperations,Sn,8)||r.requiredOperations.some(c=>!d.includes(c)))&&o.push(`WORKFLOW_NODE_REQUIRED_OPERATIONS_INVALID:${n}`)}if(r.kind==="cc"){(a!==void 0||i!==void 0&&(!Ue(i)||!Qe(i,["assigneeProviders"])))&&o.push(`WORKFLOW_NODE_ADMINISTRATION_INVALID:${n}`),i?.assigneeProviders!==void 0&&!jt(i.assigneeProviders,Zo,3)&&o.push(`WORKFLOW_NODE_ADMINISTRATION_PROVIDERS_INVALID:${n}`),i?.assigneeProviders?.includes("app_role_in_scope")&&t&&!t.bindings[r.binding||""]?.scope&&o.push(`WORKFLOW_NODE_ADMINISTRATION_SCOPE_REQUIRED:${n}`);continue}if(!["approval","handle"].includes(r.kind)){(i!==void 0||a!==void 0)&&o.push(`WORKFLOW_NODE_ADMINISTRATION_APPROVAL_REQUIRED:${n}`);continue}if(a!==void 0&&(!Ue(a)||Object.keys(a).length>8||Object.entries(a).some(([d,c])=>!Sn.includes(d)||!Et(r).includes(d)||!es(c,d)))&&o.push(`WORKFLOW_NODE_OPERATION_POLICY_INVALID:${n}`),i===void 0)continue;if(!Ue(i)||!Qe(i,["modes","assigneeProviders","operations"])){o.push(`WORKFLOW_NODE_ADMINISTRATION_INVALID:${n}`);continue}i.modes!==void 0&&(!jt(i.modes,xd,4)||!i.modes.includes(r.mode))&&o.push(`WORKFLOW_NODE_ADMINISTRATION_MODES_INVALID:${n}`),i.assigneeProviders!==void 0&&!jt(i.assigneeProviders,Zo,3)&&o.push(`WORKFLOW_NODE_ADMINISTRATION_PROVIDERS_INVALID:${n}`);let s=t?.bindings[r.binding||""];s&&Array.isArray(i.assigneeProviders)&&i.assigneeProviders.includes("app_role_in_scope")&&!s.scope&&o.push(`WORKFLOW_NODE_ADMINISTRATION_SCOPE_REQUIRED:${n}`),i.operations!==void 0&&(!jt(i.operations,Sn,8)||i.operations.some(d=>!Et(r).includes(d)))&&o.push(`WORKFLOW_NODE_ADMINISTRATION_OPERATIONS_INVALID:${n}`)}return o}function Kf(e,t,o,n){let r=[];if(!e||!Ue(o)||!Object.keys(o).length||!Qe(o,["title","description","assignee","mode","operations"]))return["WORKFLOW_V2_NODE_CONFIGURATION_PATCH_INVALID"];let i=o;!i.assignee&&t?.provider==="supervisor_chain"&&t.continuous!==!1&&(i.mode||e.mode)!=="sequence"&&r.push("WORKFLOW_SUPERVISOR_CHAIN_SEQUENCE_REQUIRED"),Object.entries(i.operations||{}).some(([s,d])=>d?.enabled===!1&&e.requiredOperations?.includes(s))&&r.push("WORKFLOW_V2_NODE_CONFIGURATION_REQUIRED_OPERATION");for(let s of["title","description"])i[s]!==void 0&&(typeof i[s]!="string"||i[s].length>(s==="title"?255:1e3)||s==="title"&&!i[s].trim())&&r.push("WORKFLOW_V2_NODE_CONFIGURATION_PATCH_INVALID");let a=e.administration;if(i.mode!==void 0&&(!["approval","handle"].includes(e.kind)||!a?.modes?.includes(i.mode))&&r.push("WORKFLOW_V2_NODE_CONFIGURATION_MODE_READONLY"),i.operations!==void 0&&(!["approval","handle"].includes(e.kind)||!Ue(i.operations)||!Object.keys(i.operations).length||Object.keys(i.operations).length>8||Object.entries(i.operations).some(([s,d])=>!a?.operations?.includes(s)||!Et(e).includes(s)||!es(d,s,e.operationPolicy?.[s],!0)))&&r.push("WORKFLOW_V2_NODE_CONFIGURATION_OPERATION_INVALID"),i.assignee!==void 0){let s=i.assignee,d=a?.assigneeProviders||((e.kind==="approval"||e.kind==="handle")&&t&&Zo.includes(t.provider)?[t.provider]:[]);if(t?.selectedInputPath&&!["app_role","app_role_in_scope"].includes(s?.provider||"")&&r.push("WORKFLOW_V2_NODE_CONFIGURATION_PROVIDER_READONLY"),!Ue(s)||!["approval","handle","cc"].includes(e.kind)||!d.includes(s.provider)||s.provider==="app_role_in_scope"&&!t?.scope)r.push("WORKFLOW_V2_NODE_CONFIGURATION_PROVIDER_READONLY");else if(s.provider==="fixed_users"){let c=e.kind==="cc"?t?.min??1:e.emptyPolicy==="skip"?0:1,l=e.kind==="cc"?Math.min(t?.max??20,200):200;(!Qe(s,["provider","users"])||!Array.isArray(s.users)||s.users.length<c||s.users.length>l||new Set(s.users).size!==s.users.length||s.users.some(f=>typeof f!="string"||!f.trim()||f.length>255))&&r.push("WORKFLOW_V2_NODE_CONFIGURATION_USERS_INVALID")}else s.roleCodes!==void 0?(!Qe(s,["provider","roleCodes"])||Cn({...s,...s.provider==="app_role_in_scope"?{scope:t?.scope}:{}}).length)&&r.push("WORKFLOW_V2_NODE_CONFIGURATION_ROLE_INVALID"):(!Qe(s,["provider","roleCode"])||typeof s.roleCode!="string"||!/^[a-z][a-z0-9_-]{0,127}$/.test(s.roleCode))&&r.push("WORKFLOW_V2_NODE_CONFIGURATION_ROLE_INVALID")}return r.push(...xt({nodes:{node:{...e,operationPolicy:Qi(e,i).operationPolicy}},...n?{taskPages:n}:{}})),e.completionDeadline&&Qi(e,i).operationPolicy.approve?.commentRequired===!0&&r.push("WORKFLOW_COMPLETION_DEADLINE_INPUT_REQUIRED:node"),r}function Qi(e,t){let o=Object.fromEntries(Et(e).flatMap(n=>{let r=n,i=t?.operations?.[r],a={...e.operationPolicy?.[r],...i?.label!==void 0?{label:i.label}:{},...i?.commentRequired!==void 0?{commentRequired:i.commentRequired}:{},...i?.reasonRequired!==void 0?{reasonRequired:i.reasonRequired}:{},...i?.opinion!==void 0?{opinion:i.opinion}:{}};return i?.opinion===void 0&&(i?.commentRequired!==void 0||i?.reasonRequired!==void 0)&&a.opinion!==void 0&&(a.opinion=i.commentRequired??i.reasonRequired?"required":"optional"),a.opinion!==void 0&&(["complete","approve","reject"].includes(r)&&(a.commentRequired=a.opinion==="required"),["transfer","delegate","add_assignee","return"].includes(r)&&(a.reasonRequired=a.opinion==="required")),Object.keys(a).length?[[r,a]]:[]}));return{mode:t?.mode||e.mode,initiatorApprovalPolicy:e.initiatorApprovalPolicy||"manual",allowedOperations:Et(e).filter(n=>t?.operations?.[n]?.enabled!==!1),operationPolicy:o,fieldPolicy:{default:e.fieldPolicy?.default||"readonly",fields:{...e.fieldPolicy?.fields}}}}var ts=["supervisor_chain","fixed_users","input_users","form_field_users","app_role","app_role_in_scope"];function er(e,t){let o=[];for(let[n,r]of Object.entries(e?.nodes||{}))r.kind==="cc"||r.emptyPolicy===void 0||(r.kind!=="approval"||!["block","skip"].includes(r.emptyPolicy)?o.push(`WORKFLOW_APPROVAL_EMPTY_POLICY_INVALID:${n}`):r.emptyPolicy==="skip"&&t&&!ts.includes(t.bindings?.[r.binding||""]?.provider)&&o.push(`WORKFLOW_APPROVAL_EMPTY_PROVIDER_UNSUPPORTED:${n}`));return o}function qf(e,t){return e.kind==="approval"&&e.emptyPolicy==="skip"&&t?.emptyResult==="no_candidates"&&ts.includes(t.provider)&&Array.isArray(t.candidates)&&t.candidates.length===0&&Array.isArray(t.selected)&&t.selected.length===0&&Array.isArray(t.warnings)&&t.warnings.length===0}function ns(e,t){let o=Object.values(e.nodes||{}).filter(n=>n.binding===t);return o.length>0&&o.every(n=>n.kind==="approval"&&n.emptyPolicy==="skip")}function os(e,t=0){return!Array.isArray(e)||e.length>64||t>1?!0:e.some(o=>!o||typeof o!="object"||Array.isArray(o)||o.required===!0||o.requiredWhen!==void 0||o.subtable!==void 0&&(!o.subtable||os(o.subtable.fields,t+1)))}function Jf(e){let t=e.afterSeconds;return`\u8FDB\u5165\u540E ${t%86400===0?`${t/86400} \u5929`:t%3600===0?`${t/3600} \u5C0F\u65F6`:t%60===0?`${t/60} \u5206\u949F`:`${t} \u79D2`}\u672A\u5B8C\u6210\uFF0C\u81EA\u52A8\u540C\u610F`}function rs(e){let t=[];for(let[o,n]of Object.entries(e?.nodes||{})){if(!n||typeof n!="object"||n.completionDeadline===void 0)continue;let r=n.completionDeadline;if(n.kind!=="approval"||!r||typeof r!="object"||Array.isArray(r)||Object.keys(r).length!==2||Object.keys(r).some(a=>!["afterSeconds","action"].includes(a))||r.action!=="approve"||!Number.isInteger(r.afterSeconds)||r.afterSeconds<1||r.afterSeconds>2592e3){t.push(`WORKFLOW_COMPLETION_DEADLINE_INVALID:${o}`);continue}n.allowedOperations&&!n.allowedOperations.includes("approve")&&t.push(`WORKFLOW_COMPLETION_DEADLINE_APPROVE_UNAVAILABLE:${o}`);let i=n.taskPageCode?e.taskPages?.[n.taskPageCode]:void 0;(n.taskPageCode&&(!i||os(i.fields))||[n.fieldPolicy?.default,...Object.values(n.fieldPolicy?.fields||{})].includes("edit_required")||n.operationPolicy?.approve?.opinion==="required"||n.operationPolicy?.approve?.commentRequired===!0||e.commandHandlers?.approve!==void 0)&&t.push(`WORKFLOW_COMPLETION_DEADLINE_INPUT_REQUIRED:${o}`)}return t}var Ud="openxiangda.workflow-rejection-notification/v1",Yf=4096;function is(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function It(e,t){return typeof e=="string"&&e.trim().length>0&&e.length<=t}function tr(e,t){return Object.keys(e).sort().join(",")===t.sort().join(",")}function ss(e){let t=e?.rejectionNotification;return t===void 0?[]:!is(t)||!tr(t,["recipient","title","summary"])||t.recipient!=="record_last_modifier"||!It(t.title,160)||!It(t.summary,500)?["WORKFLOW_REJECTION_NOTIFICATION_INVALID"]:It(e.subject?.resourceCode,63)?[]:["WORKFLOW_REJECTION_NOTIFICATION_SUBJECT_REQUIRED"]}function Xf(e){if(!is(e)||e.schemaVersion!==Ud||e.recipient!=="record_last_modifier"||!It(e.title,160)||!It(e.summary,500))return!1;let t=["schemaVersion","recipient","title","summary","status","sourceRevision"];if(e.status==="ready"){if(!tr(e,[...t,"userId"])||!It(e.userId,255)||!Number.isSafeInteger(e.sourceRevision)||Number(e.sourceRevision)<1)return!1}else if(e.status==="skipped"){if(!tr(e,[...t,"reason"])||!["record_missing","modifier_missing","modifier_ineligible"].includes(String(e.reason))||(e.reason==="record_missing"?e.sourceRevision!==null:!Number.isSafeInteger(e.sourceRevision)||Number(e.sourceRevision)<1))return!1}else return!1;return new TextEncoder().encode(JSON.stringify(e)).byteLength<=4096}function as(e,t){let o=e.commandHandlers;if(o===void 0)return[];if(!o||typeof o!="object"||Array.isArray(o)||!Object.keys(o).length||Object.keys(o).some(r=>!["approve","reject","withdraw","resubmit"].includes(r)))return["WORKFLOW_BUSINESS_COMMAND_HANDLERS_INVALID"];let n=[];o.resubmit&&!Object.values(e.nodes||{}).some(r=>r.kind==="correction")&&n.push("WORKFLOW_BUSINESS_CORRECTION_REQUIRED");for(let[r,i]of Object.entries(o)){if(!i||typeof i!="object"||Array.isArray(i)||Object.keys(i).some(s=>!["operationCode","transitionPolicy","derivedSubjectFields"].includes(s))||i.transitionPolicy!==void 0&&(r!=="approve"||i.transitionPolicy!=="workflow")||!/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/.test(i.operationCode||"")){n.push("WORKFLOW_BUSINESS_COMMAND_HANDLER_INVALID");continue}if(i.derivedSubjectFields!==void 0){let s=i.derivedSubjectFields,d=new Set(Object.values(e.subject?.factProjection||{}));(r!=="resubmit"||!Array.isArray(s)||s.length<1||s.length>32||new Set(s).size!==s.length||s.some(c=>typeof c!="string"||!/^[A-Za-z][A-Za-z0-9_]{0,62}$/.test(c)||!d.has(c)||lt.has(c)||["createdBy","updatedBy","createdAt","updatedAt"].includes(c)||Object.values(e.taskPages||{}).some(l=>l.fields?.some(f=>f.code===c&&f.readonly!==!0))))&&n.push("WORKFLOW_CORRECTION_DERIVED_SUBJECT_FIELDS_INVALID")}if(!t)continue;let a=t.find(s=>s.code===i.operationCode);if(!a){n.push("WORKFLOW_BUSINESS_COMMAND_OPERATION_MISSING");continue}(a.method!=="POST"||a.browser?.exposure!=="authenticated"||a.browser.behavior!=="controlled"||a.browser.idempotency!=="required"||a.browser.fileIntent||a.browser.subject?.resourceCode!==e.subject?.resourceCode||a.browser.subject?.inputField!=="recordId"||!a.platformAccess?.workflow?.codes?.includes(e.code)||!a.platformAccess.workflow.businessCommands?.includes(r))&&n.push("WORKFLOW_BUSINESS_COMMAND_OPERATION_INVALID")}return["approve","reject","withdraw"].some(r=>Object.hasOwn(o,r))&&Object.values(e.nodes||{}).some(r=>r.kind==="approval"&&(r.emptyPolicy==="skip"||r.initiatorApprovalPolicy==="auto_approve"))&&n.push("WORKFLOW_BUSINESS_COMMAND_AUTOMATIC_DECISION_FORBIDDEN"),[...new Set(n)]}var ep={type:"object",additionalProperties:!1,required:["workflowCode","target","recordId","expectedRevision","commandToken","idempotencyKey","input"],properties:{workflowCode:{type:"string",pattern:"^[A-Za-z][A-Za-z0-9_-]{0,127}$"},target:{oneOf:[{type:"object",additionalProperties:!1,required:["kind","id","command"],properties:{kind:{const:"task"},id:{type:"string",format:"uuid"},command:{enum:["approve","reject","resubmit"]}}},{type:"object",additionalProperties:!1,required:["kind","id","command"],properties:{kind:{const:"instance"},id:{type:"string",format:"uuid"},command:{const:"withdraw"}}}]},recordId:{type:"string",format:"uuid"},expectedRevision:{type:"integer",minimum:1},commandToken:{type:"string",pattern:"^[A-Za-z0-9_-]{43}$"},idempotencyKey:{type:"string",minLength:1,maxLength:128},input:{type:"object",maxProperties:64}}};function tp(e,t,o){if(!(t==="resubmit"&&o===!1))return e.commandHandlers?.[t]}var Bd=["fixed_users","initiator","app_role","app_role_in_scope"],Kd=e=>!!e&&typeof e=="object"&&!Array.isArray(e);function nr(e,t){let o=e?.launchPreflight;if(o===void 0)return[];if(!Kd(o)||Object.keys(o).join(",")!=="requiredApprovalNodes"||!Array.isArray(o.requiredApprovalNodes)||o.requiredApprovalNodes.length<1||o.requiredApprovalNodes.length>20||new Set(o.requiredApprovalNodes).size!==o.requiredApprovalNodes.length||o.requiredApprovalNodes.some(r=>typeof r!="string"||!/^[A-Za-z][A-Za-z0-9_-]{0,127}$/.test(r)))return["WORKFLOW_LAUNCH_PREFLIGHT_INVALID"];let n=[];for(let r of o.requiredApprovalNodes){let i=e.nodes?.[r];if(!i||i.kind!=="approval"){n.push(`WORKFLOW_LAUNCH_PREFLIGHT_NODE_INVALID:${r}`);continue}if(!t)continue;let a=t.bindings?.[i.binding||""];(!a||!Bd.includes(a.provider)||a.candidateField!==void 0)&&n.push(`WORKFLOW_LAUNCH_PREFLIGHT_PROVIDER_UNSUPPORTED:${r}`)}return n}var or=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Gd=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,cs=/^[A-Za-z][A-Za-z0-9_-]{0,127}$/,ds=/^membership:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,rp=500,ip=262144;function ls(e){if(e?.approvedDelegation===void 0)return[];let t=e.approvedDelegation;if(!or(t)||Object.keys(t).some(d=>!["confirmationNodeId","confirmer","requestsField","maxRequests"].includes(d))||!cs.test(t.confirmationNodeId||"")||!["initiator","delegate"].includes(t.confirmer)||!Gd.test(t.requestsField||"")||!Number.isSafeInteger(t.maxRequests)||t.maxRequests<1||t.maxRequests>500)return["WORKFLOW_APPROVED_DELEGATION_POLICY_INVALID"];let o=[],n=e.nodes?.[t.confirmationNodeId];(!n||n.kind!=="approval"||n.mode!=="single"||n.emptyPolicy==="skip"||n.initiatorApprovalPolicy==="auto_approve"||n.completionDeadline||n.administration?.assigneeProviders?.length||n.administration?.modes?.some(d=>d!=="single")||n.allowedOperations?.some(d=>["transfer","delegate","add_assignee","admin_override"].includes(d)))&&o.push("WORKFLOW_APPROVED_DELEGATION_CONFIRMATION_INVALID");let r=e.inputSchema?.properties?.[t.requestsField];(!r||r.type!=="array"||!Number.isSafeInteger(r.maxItems)||r.maxItems<1||r.maxItems>t.maxRequests||!r.items||r.items.type!=="object"||r.items.additionalProperties!==!1||!e.subject?.factProjection?.[t.requestsField])&&o.push("WORKFLOW_APPROVED_DELEGATION_REQUEST_SCHEMA_INVALID"),Object.values(e.nodes||{}).some(d=>d.kind==="end"&&d.outcome==="approved")||o.push("WORKFLOW_APPROVED_DELEGATION_APPROVED_END_REQUIRED");let a=[e.startAt],s=new Set;for(;a.length;){let d=a.pop();if(d===t.confirmationNodeId||s.has(d))continue;s.add(d);let c=e.nodes?.[d];c&&(c.kind==="end"&&c.outcome==="approved"&&o.push("WORKFLOW_APPROVED_DELEGATION_CONFIRMATION_BYPASS"),c.kind==="approval"&&a.push(c.onApprove,c.onReject),c.kind==="condition"&&a.push(c.otherwise,...(c.branches||[]).map(l=>l.target)),(c.kind==="cc"||c.kind==="action")&&a.push(c.next))}return[...new Set(o)]}function sp(e,t){let o=t?.data?.[e.requestsField],n=()=>{throw new Error("WORKFLOW_APPROVED_DELEGATION_REQUEST_INVALID")};(!Array.isArray(o)||!o.length||o.length>e.maxRequests||o.length>500||new TextEncoder().encode(JSON.stringify(o)).byteLength>262144)&&n();let r=["key","delegatorRoleSubjectKey","delegatorRoleSubjectRevision","delegate","delegateRoleSubjectKey","expectedDelegateRevision","workflowCode","nodeId","validFrom","validTo","reason"],i=(d,c)=>typeof d=="string"&&d.trim().length>0&&d.length<=c,a=d=>{if(typeof d!="string")return!1;let c=/^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)(?:\.\d{1,3})?(?:Z|[+-](\d\d):(\d\d))$/.exec(d);if(!c)return!1;let[,l,f,p,m,E,A,b,O]=c,g=Number(l),y=Number(f),h=Number(p),I=[31,g%4===0&&(g%100!==0||g%400===0)?29:28,31,30,31,30,31,31,30,31,30,31];return y>=1&&y<=12&&h>=1&&h<=I[y-1]&&Number(m)<=23&&Number(E)<=59&&Number(A)<=59&&(b===void 0||Number(b)<=23&&Number(O)<=59)&&Number.isFinite(Date.parse(d))},s=o.map(d=>or(d)?((Object.keys(d).some(c=>!r.includes(c))||!i(d.delegatorRoleSubjectKey,255)||!ds.test(d.delegatorRoleSubjectKey)||!i(d.delegateRoleSubjectKey,255)||!ds.test(d.delegateRoleSubjectKey)||!Number.isSafeInteger(d.delegatorRoleSubjectRevision)||d.delegatorRoleSubjectRevision<1||!Number.isSafeInteger(d.expectedDelegateRevision)||d.expectedDelegateRevision<1||!or(d.delegate)||Object.keys(d.delegate).some(c=>!["value","label"].includes(c))||!i(d.delegate.value,255)||!i(d.delegate.label,200)||!(d.workflowCode===null||i(d.workflowCode,128)&&cs.test(d.workflowCode))||!(d.nodeId===null||i(d.nodeId,128)&&/^[A-Za-z0-9._:-]{1,128}$/.test(d.nodeId)&&d.workflowCode)||!a(d.validFrom)||!a(d.validTo)||Date.parse(d.validFrom)>=Date.parse(d.validTo)||!i(d.reason,4e3)||d.key!==void 0&&!i(d.key,128))&&n(),{...d,delegate:{value:d.delegate.value,label:d.delegate.label},validFrom:new Date(d.validFrom).toISOString(),validTo:new Date(d.validTo).toISOString()}):n());return e.confirmer==="delegate"&&new Set(s.map(d=>d.delegate.value)).size!==1&&n(),s}var qd=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&[null,Object.prototype].includes(Object.getPrototypeOf(e));function us(e){let t=e?.nodes||{},o=Object.values(t).filter(s=>s?.kind==="correction");if(!o.length)return[];let n=[],r=s=>s?.kind==="approval"?[s.onApprove,s.onReject]:s?.kind==="condition"?[...(Array.isArray(s.branches)?s.branches:[]).map(d=>d.target),s.otherwise]:s?.kind==="action"||s?.kind==="cc"||s?.kind==="handle"?[s.next]:[],i=new Set,a=[e.startAt];for(;a.length;){let s=a.pop();i.has(s)||(i.add(s),a.push(...r(t[s])))}for(let s of o){(!qd(s)||Object.keys(s).some(c=>!["id","kind","title","taskPageCode","next","reminders"].includes(c))||typeof s.id!="string"||!/^[A-Za-z][A-Za-z0-9_-]{0,127}$/.test(s.id)||["__proto__","prototype","constructor"].includes(s.id)||t[s.id]!==s||typeof s.title!="string"||!s.title.trim()||s.title.length>255||typeof s.taskPageCode!="string"||!/^[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(s.taskPageCode))&&n.push("WORKFLOW_CORRECTION_NODE_INVALID"),(s.next!==e.startAt||t[s.next]?.kind==="correction")&&n.push("WORKFLOW_CORRECTION_REPLAY_TARGET_INVALID"),(i.has(s.id)||Object.values(t).some(c=>r(c).includes(s.id)))&&n.push("WORKFLOW_CORRECTION_FORWARD_ENTRY_FORBIDDEN"),Object.values(t).some(c=>(c?.kind==="approval"||c?.kind==="handle")&&i.has(c.id)&&xe(c).includes(s.id))||n.push("WORKFLOW_CORRECTION_RETURN_SOURCE_REQUIRED");let d=e.taskPages?.[s.taskPageCode];!d||!Array.isArray(d.fields)?n.push("WORKFLOW_CORRECTION_PAGE_REQUIRED"):d.fields.some(c=>c?.subtable&&Object.values(e.subject?.factProjection||{}).some(l=>l===c.code||l.startsWith(`${c.code}.`)))&&n.push("WORKFLOW_CORRECTION_OWNED_FACTS_UNSUPPORTED")}return[...new Set(n)]}var kn=class extends Error{constructor(o){super(o);this.code=o}code},lp=["projection","triggerCode","resourceCode","recordId","recordRevision","field","dueAt"];function fs(e,t,o){let n=i=>{throw new kn(i)};t.length>100&&n("DATE_TRIGGER_PROJECTION_LIMIT");let r=new Set;for(let i of t){let a=i.filter?.resourceCodes||[];if(Array.isArray(a)||n("DATE_TRIGGER_PROJECTION_INVALID"),a.length&&!a.includes(e))continue;let s=i.payload?.fields||[];(!Array.isArray(s)||s.length>32)&&n("DATE_TRIGGER_PROJECTION_LIMIT");for(let d of s)(typeof d!="string"||!/^[A-Za-z_][A-Za-z0-9_]{0,62}$/.test(d)||["__proto__","constructor","prototype"].includes(d))&&n("DATE_TRIGGER_PROJECTION_FIELD_INVALID"),r.add(d)}if(r.size>64&&n("DATE_TRIGGER_PROJECTION_LIMIT"),o!==void 0){let i=o?.schema?.fields??o?.fields;Array.isArray(i)||n("DATE_TRIGGER_PROJECTION_RESOURCE_INVALID");let a=new Map(i.map(s=>[s.code,s]));for(let s of r){let d=a.get(s);d||n("DATE_TRIGGER_PROJECTION_FIELD_UNKNOWN"),d.type==="subtable"&&n("DATE_TRIGGER_PROJECTION_SUBTABLE_FORBIDDEN"),o.fieldPolicies?.[s]?.mask==="omit"&&n("DATE_TRIGGER_PROJECTION_FIELD_SENSITIVE")}}return[...r].sort()}function up(e,t){if(!t.length)return e;let o=e?.properties?.projection;if(o?.type!=="object"||!o.properties||typeof o.properties!="object"||Array.isArray(o.properties)||o.additionalProperties!==!1||o.required!==void 0&&!Array.isArray(o.required)||t.some(n=>!Object.hasOwn(o.properties,n))||(o.required||[]).some(n=>!t.includes(n)))throw new kn("DATE_TRIGGER_PROJECTION_SCHEMA_INVALID");return{...e,properties:{...e.properties,projection:{}}}}var zd=200,ir=1024*1024,Jd=65536,_s=He,ps=ct,et=new Set(["__proto__","prototype","constructor"]),gs=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,Bt=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,ms=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,ce=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&[null,Object.prototype].includes(Object.getPrototypeOf(e)),Pe=(e,t)=>ce(e)&&Object.keys(e).every(o=>t.includes(o)&&!et.has(o)),Ln=e=>{try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return 1/0}},As=e=>e==null||typeof e=="string"&&!e.trim()||Array.isArray(e)&&e.length===0;function Ke(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((n,r)=>Ke(n,t[r]));if(!ce(e)||!ce(t))return!1;let o=Object.keys(e);return o.length===Object.keys(t).length&&o.every(n=>Object.hasOwn(t,n)&&Ke(e[n],t[n]))}function rr(e,t){let o=t.split(".");if(!(o.some(n=>!gs.test(n)||et.has(n))||o.length>12))return o.reduce((n,r)=>ce(n)&&Object.hasOwn(n,r)?n[r]:void 0,e)}function Be(e,t){switch(e.op){case"literal":return e.value;case"path":return rr({values:t},e.path);case"and":return e.values.every(o=>!!Be(o,t));case"or":return e.values.some(o=>!!Be(o,t));case"not":return!Be(e.value,t);case"exists":return!As(Be(e.value,t));default:{let o=Be(e.left,t),n=Be(e.right,t);return e.op==="eq"?Ke(o,n):e.op==="neq"?!Ke(o,n):e.op==="in"?Array.isArray(n)&&n.some(r=>Ke(r,o)):e.op==="contains"?Array.isArray(o)?o.some(r=>Ke(r,n)):typeof o=="string"&&typeof n=="string"&&o.includes(n):typeof o!="number"||typeof n!="number"||!Number.isFinite(o)||!Number.isFinite(n)?!1:e.op==="gt"?o>n:e.op==="gte"?o>=n:e.op==="lt"?o<n:o<=n}}}function Ut(e,t,o=0,n={nodes:0}){if(o>8||++n.nodes>64||!ce(e))return!1;if(e.op==="literal")return Pe(e,["op","value"])&&Object.hasOwn(e,"value")&&Ln(e.value)<=4096&&Kt(e.value);if(e.op==="path"){if(!Pe(e,["op","path"])||typeof e.path!="string")return!1;let r=e.path.split(".");return r[0]==="values"&&r.length>=2&&r.length<=8&&t.has(r[1])&&r.every(i=>Bt.test(i)&&!et.has(i))}return["not","exists"].includes(e.op)?Pe(e,["op","value"])&&Ut(e.value,t,o+1,n):["and","or"].includes(e.op)?Pe(e,["op","values"])&&Array.isArray(e.values)&&e.values.length>0&&e.values.length<=16&&e.values.every(r=>Ut(r,t,o+1,n)):["eq","neq","gt","gte","lt","lte","in","contains"].includes(e.op)&&Pe(e,["op","left","right"])&&Ut(e.left,t,o+1,n)&&Ut(e.right,t,o+1,n)}function $n(e,t,o,n=ps){let r=[],i=e.taskPages;if(i!==void 0&&(!ce(i)||Object.keys(i).length===0||Object.keys(i).length>16||Ln(i)>Jd))return["WORKFLOW_TASK_PAGES_INVALID"];for(let[a,s]of Object.entries(i||{})){let d=`taskPages.${a}`;if(!gs.test(a)||et.has(a)||!Pe(s,["title","fields"])||typeof s.title!="string"||!s.title.trim()||s.title.length>160||!Array.isArray(s.fields)||!s.fields.length||s.fields.length>zd){r.push(`WORKFLOW_TASK_PAGE_INVALID:${d}`);continue}let c=new Set(s.fields.map(p=>p?.code));c.size!==s.fields.length&&r.push(`WORKFLOW_TASK_PAGE_DUPLICATE_FIELD:${d}`);let l=0,f=new Set;for(let p of s.fields){if(!Pe(p,["code","readonly","required","visibleWhen","requiredWhen","subtable"])||!Bt.test(p.code)||et.has(p.code)||["readonly","required"].some(m=>p[m]!==void 0&&typeof p[m]!="boolean")||p.readonly&&(p.required||p.requiredWhen)){r.push(`WORKFLOW_TASK_PAGE_FIELD_INVALID:${d}`);continue}for(let m of["visibleWhen","requiredWhen"])p[m]!==void 0&&!Ut(p[m],c)&&r.push(`WORKFLOW_TASK_PAGE_EXPRESSION_INVALID:${d}.${p.code}.${m}`);if(t){let m=t.get(p.code);if((!m||m.system||m.hidden||m.type==="serial-number"||!p.readonly&&m.widget==="readonly"||!p.readonly&&m.type==="subtable"&&!p.subtable||p.subtable&&m.type!=="subtable")&&r.push(`WORKFLOW_TASK_PAGE_RESOURCE_FIELD_INVALID:${d}.${p.code}`),p.subtable&&m?.subtable){let E=m.subtable;l+=E.maxRows??20,(f.has(E.resourceCode)||!Number.isSafeInteger(E.maxRows??20)||(E.maxRows??20)<1||(E.maxRows??20)>_s||!Bt.test(E.foreignKey)||!Bt.test(E.orderField)||E.foreignKey===E.orderField)&&r.push(`WORKFLOW_TASK_SUBTABLE_RELATION_INVALID:${d}.${p.code}`),f.add(E.resourceCode);let A=o?.get(E.resourceCode);o&&(!A||!["uuid","resource-ref.single"].includes(A.get(E.foreignKey)?.type||"")||A.get(E.orderField)?.type!=="number.integer")&&r.push(`WORKFLOW_TASK_SUBTABLE_RELATION_INVALID:${d}.${p.code}`);for(let b of Array.isArray(p.subtable.fields)?p.subtable.fields:[]){if(!b||typeof b.code!="string")continue;let O=A?.get(b.code);(b.code===E.foreignKey||b.code===E.orderField||A&&(!O||O.system||O.hidden||O.type==="subtable"||!b.readonly&&(O.widget==="readonly"||O.type==="serial-number")))&&r.push(`WORKFLOW_TASK_SUBTABLE_FIELD_UNSUPPORTED:${d}.${p.code}.${b.code}`)}}else p.subtable&&t&&r.push(`WORKFLOW_TASK_SUBTABLE_RELATION_INVALID:${d}.${p.code}`)}p.subtable&&(p.readonly||!Pe(p.subtable,["fields","create","delete","reorder"])||["create","delete","reorder"].some(m=>p.subtable?.[m]!==void 0&&typeof p.subtable[m]!="boolean")||!Array.isArray(p.subtable.fields)||p.subtable.fields.some(m=>m?.subtable)?r.push(`WORKFLOW_TASK_SUBTABLE_PAGE_INVALID:${d}.${p.code}`):r.push(...$n({taskPages:{child:{title:"\u5B50\u884C",fields:p.subtable.fields}}},o?.get(t?.get(p.code)?.subtable?.resourceCode||"")).map(m=>`${m}:${d}.${p.code}`)))}(l>Math.min(n,ps)||l<0||!Number.isSafeInteger(l)||!Number.isSafeInteger(n)||n<1)&&r.push(`WORKFLOW_TASK_SUBTABLE_BUDGET_EXCEEDED:${d}`)}for(let[a,s]of Object.entries(e.nodes||{}))ce(s)&&s.taskPageCode!==void 0&&(!["approval","handle","correction"].includes(s.kind)||typeof s.taskPageCode!="string"||!ce(i)||!Object.hasOwn(i,s.taskPageCode)?r.push(`WORKFLOW_TASK_PAGE_NOT_FOUND:${a}`):Array.isArray(i[s.taskPageCode]?.fields)&&i[s.taskPageCode].fields.some(d=>d&&(s.fieldPolicy?.fields?.[d.code]||s.fieldPolicy?.default)==="hidden")&&r.push(`WORKFLOW_TASK_PAGE_FIELD_HIDDEN:${a}`));return r}function Es(e,t){return e.fields.map(o=>({code:o.code,visible:o.visibleWhen===void 0||!!Be(o.visibleWhen,t),readonly:o.readonly===!0,required:o.required===!0||o.requiredWhen!==void 0&&!!Be(o.requiredWhen,t)}))}var ke=class extends Error{constructor(o,n){super(o);this.code=o;this.field=n}code;field;rowIndex;childField};function mp(e,t){return t.map(o=>({key:String(o.id),id:String(o.id),revision:Number(o.revision),state:"persisted",values:Object.fromEntries(Es({title:"\u5B50\u884C",fields:e.fields},o).filter(n=>n.visible&&!n.readonly).map(n=>[n.code,o[n.code]??null]))}))}function _p(e,t,o,n,r,i=!0,a=0){let s=e.subtable,d=m=>{throw new ke(m,e.code)};if(!s||!Number.isSafeInteger(t)||t<1||t>_s||!Number.isSafeInteger(a)||a<0||a>t||!Array.isArray(n)||n.length>2*t||Ln(n)>ir||!Kt(n))return d("WORKFLOW_TASK_SUBTABLE_VALUES_INVALID");let c=new Map(o.map(m=>[String(m.id),m])),l=new Set,f=new Set,p=[];for(let m of n){if(!Pe(m,["key","state","id","revision","values"])||typeof m.key!="string"||!ms.test(m.key)||l.has(m.key)||!["created","persisted","deleted"].includes(m.state)||!ce(m.values))return d("WORKFLOW_TASK_SUBTABLE_ROW_INVALID");if(l.add(m.key),m.state==="created"){if(!s.create||m.id!==void 0||m.revision!==void 0||c.has(m.key))return d("WORKFLOW_TASK_SUBTABLE_CREATE_FORBIDDEN")}else{if(typeof m.id!="string"||m.id!==m.key||!ms.test(m.id)||f.has(m.id)||!Number.isSafeInteger(m.revision)||m.revision<1||!c.has(m.id))return d("WORKFLOW_TASK_SUBTABLE_SCOPE_CONFLICT");if(f.add(m.id),i&&Number(c.get(m.id).revision)!==m.revision)return d("WORKFLOW_TASK_SUBTABLE_REVISION_CONFLICT")}if(m.state==="deleted"){if(!s.delete||Object.keys(m.values).length)return d("WORKFLOW_TASK_SUBTABLE_DELETE_FORBIDDEN");continue}try{Hd({title:e.code,fields:s.fields},m.id?c.get(m.id):{},m.values,r)}catch(E){if(!(E instanceof ke))throw E;let A=new ke(E.code,e.code);throw A.rowIndex=p.length,E.field!==void 0&&(A.childField=E.field),A}p.push(m)}if(f.size!==c.size)return d("WORKFLOW_TASK_SUBTABLE_SCOPE_CONFLICT");if(p.length>t)return d("WORKFLOW_TASK_SUBTABLE_MAX_ROWS_EXCEEDED");if(r&&p.length<a)return d("WORKFLOW_TASK_SUBTABLE_MIN_ROWS_NOT_MET");if(!s.reorder){let m=o.filter(A=>p.some(b=>b.id===String(A.id))).map(A=>String(A.id)),E=p.filter(A=>A.state==="persisted").map(A=>A.id);if(!Ke(m,E)||p.some((A,b)=>A.state==="created"&&p.slice(b+1).some(O=>O.state==="persisted")))return d("WORKFLOW_TASK_SUBTABLE_REORDER_FORBIDDEN")}return n}function Kt(e,t={members:0},o=0){return++t.members>5e4||o>12?!1:e===null||typeof e=="boolean"?!0:typeof e=="string"?e.length<=ir:typeof e=="number"?Number.isFinite(e):Array.isArray(e)?e.length<=1e3&&e.every(n=>Kt(n,t,o+1)):ce(e)&&Object.entries(e).every(([n,r])=>!et.has(n)&&Kt(r,t,o+1))}function Hd(e,t,o,n){if(!ce(o)||Ln(o)>ir||!Kt(o))throw new ke("WORKFLOW_TASK_FORM_VALUES_INVALID");let r={...t,...o},i=new Map(Es(e,r).map(a=>[a.code,a]));for(let a of Object.keys(o)){let s=i.get(a);if(!s||s.readonly||!s.visible)throw new ke("WORKFLOW_TASK_FORM_FIELD_NOT_EDITABLE",a)}if(n)for(let a of i.values()){let s=r[a.code],d=e.fields.find(c=>c.code===a.code)?.subtable&&Array.isArray(s)?s.every(c=>ce(c)&&c.state==="deleted"):As(s);if(a.visible&&!a.readonly&&a.required&&d)throw new ke("WORKFLOW_TASK_FORM_REQUIRED",a.code)}return r}function gp(e,t,o){let n=JSON.parse(JSON.stringify(t));for(let[a,s]of Object.entries(e.subject?.factProjection||{})){let d=a.split(".");if(!d.length||d.length>12||a.length>128||d[0]==="steps"||d.some(l=>!Bt.test(l)||et.has(l)))throw new ke("WORKFLOW_TASK_FORM_FACT_PROJECTION_INVALID");if(!Object.hasOwn(o,s))throw new ke("WORKFLOW_TASK_FORM_FACT_FIELD_MISSING",s);let c=n;for(let l of d.slice(0,-1))c=c[l]=ce(c[l])?c[l]:{};c[d.at(-1)]=o[s]===void 0?void 0:JSON.parse(JSON.stringify(o[s]))}let r=new Set,i=Object.values(e.nodes||{}).filter(a=>a.kind==="action");for(let a=0;a<=i.length;a++){let s=!1;for(let d of i)ce(n.steps)&&Object.hasOwn(n.steps,d.id)&&Object.values(d.inputs||{}).some(c=>c.source==="fact"&&!Ke(rr(t,c.path),rr(n,c.path)))&&(delete n.steps[d.id],r.add(d.id),s=!0);if(!s)break}return{facts:n,invalidatedNodeIds:[...r].sort()}}function Ap(e,t,o){let n=e.nodes||{};for(let r of o){let i=new Set,a=new Map,s=d=>{if(d===r)return!0;if(a.has(d))return a.get(d);if(i.has(d)||i.size>200)return!1;let c=n[d];if(!ce(c)||c.kind==="end")return!1;i.add(d);let l=c.kind==="approval"?[c.onApprove]:c.kind==="condition"?[...(c.branches||[]).map(p=>p.target),c.otherwise]:[c.next],f=l.length>0&&l.every(p=>typeof p=="string"&&s(p));return i.delete(d),a.set(d,f),f};if(!s(t))return!1}return!0}var Ip=256,yp=64,Op=262144,Yd=/^[a-z][a-z0-9_-]{0,127}$/,Xd=/^[A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z][A-Za-z0-9_]*)*$/,ys=new Set(["__proto__","prototype","constructor"]),Le=e=>!!e&&typeof e=="object"&&!Array.isArray(e),qt=(e,t)=>Object.keys(e).every(o=>t.includes(o)),tt=(e,t)=>typeof e=="string"&&e.trim().length>0&&e.length<=t&&!/[\u0000-\u001f\u007f]/.test(e),ve=e=>typeof e=="string"&&Yd.test(e)&&!ys.has(e),Os=e=>typeof e=="string"&&e.length<=255&&Xd.test(e)&&!e.split(".").some(t=>ys.has(t)),Zd=e=>Le(e)&&qt(e,["dimension","valueFrom","value"])&&ve(e.dimension)&&(tt(e.value,255)&&e.valueFrom===void 0||Os(e.valueFrom)&&e.value===void 0),Is=e=>typeof e=="string"&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?(?:Z|[+-]\d{2}:\d{2})$/.test(e)&&Number.isFinite(Date.parse(e)),Gt={type:"string",pattern:"^[a-z][a-z0-9_-]{0,127}$"},sr={type:"string",minLength:1,maxLength:128},bp={type:"object",additionalProperties:!1,required:["policyCode","title","strategy","dimensions","sources"],properties:{policyCode:Gt,title:sr,strategy:{enum:["replace_then_append","replace_only"]},dimensions:{type:"object",maxProperties:8,propertyNames:Gt,additionalProperties:{type:"object",additionalProperties:!1,required:["title","valueFrom"],properties:{title:sr,valueFrom:{type:"string",minLength:1,maxLength:255}}}},sources:{type:"object",minProperties:1,maxProperties:16,propertyNames:Gt,additionalProperties:{type:"object",additionalProperties:!1,required:["title","provider","roleCode"],properties:{title:sr,provider:{enum:["app_role","app_role_in_scope"]},roleCode:Gt,scope:{type:"object",additionalProperties:!1,required:["dimension"],properties:{dimension:Gt,value:{type:"string",minLength:1,maxLength:255},valueFrom:{type:"string",minLength:1,maxLength:255}}}}}}}};function Pn(e){if(!Le(e)||!qt(e,["policyCode","title","strategy","dimensions","sources"])||!ve(e.policyCode)||!tt(e.title,128)||!["replace_then_append","replace_only"].includes(e.strategy))return["WORKFLOW_V2_ROUTING_POLICY_INVALID"];let t=[];return(!Le(e.dimensions)||Object.keys(e.dimensions).length>8||Object.entries(e.dimensions).some(([o,n])=>!ve(o)||!Le(n)||!qt(n,["title","valueFrom"])||!tt(n.title,128)||!Os(n.valueFrom)))&&t.push("WORKFLOW_V2_ROUTING_DIMENSIONS_INVALID"),(!Le(e.sources)||Object.keys(e.sources).length<1||Object.keys(e.sources).length>16||Object.entries(e.sources).some(([o,n])=>!ve(o)||!Le(n)||!qt(n,["title","provider","roleCode","scope"])||!tt(n.title,128)||!ve(n.roleCode)||!["app_role","app_role_in_scope"].includes(n.provider)||(n.provider==="app_role_in_scope"?!Zd(n.scope):n.scope!==void 0)))&&t.push("WORKFLOW_V2_ROUTING_SOURCES_INVALID"),t}function Np(e,t){if(Pn(e).length)return["WORKFLOW_V2_ROUTING_POLICY_INVALID"];if(!Array.isArray(t)||t.length>256||new TextEncoder().encode(JSON.stringify(t)).length>262144)return["WORKFLOW_V2_ROUTING_RULE_LIMIT_EXCEEDED"];let o=[],n=new Set;for(let r of t){if(!Le(r)||!qt(r,["ruleCode","title","enabled","workflowCode","nodeId","matches","sourceCode","effect","priority","validFrom","validTo"])||!ve(r.ruleCode)||!tt(r.title,128)||typeof r.enabled!="boolean"||!ve(r.sourceCode)||!Object.hasOwn(e.sources,r.sourceCode)||!["append","replace"].includes(r.effect)||!Number.isSafeInteger(r.priority)||r.priority<-1e3||r.priority>1e3||r.workflowCode!==void 0&&!ve(r.workflowCode)||r.nodeId!==void 0&&(!ve(r.nodeId)||r.workflowCode===void 0)||r.validFrom!==void 0&&!Is(r.validFrom)||r.validTo!==void 0&&!Is(r.validTo)||r.validFrom&&r.validTo&&Date.parse(r.validFrom)>=Date.parse(r.validTo)){o.push("WORKFLOW_V2_ROUTING_RULE_INVALID");continue}n.has(r.ruleCode)&&o.push(`WORKFLOW_V2_ROUTING_RULE_DUPLICATE:${r.ruleCode}`),n.add(r.ruleCode),(!Le(r.matches)||Object.entries(r.matches).some(([i,a])=>!Object.hasOwn(e.dimensions,i)||!Array.isArray(a)||a.length<1||a.length>64||new Set(a).size!==a.length||a.some(s=>!tt(s,255))))&&o.push(`WORKFLOW_V2_ROUTING_MATCH_INVALID:${r.ruleCode}`)}return[...new Set(o)]}function Qd(e){return JSON.stringify({policyCode:e.policyCode,strategy:e.strategy,dimensions:Object.entries(e.dimensions).sort(([t],[o])=>t<o?-1:t>o?1:0).map(([t,o])=>[t,o.valueFrom]),sources:Object.entries(e.sources).sort(([t],[o])=>t<o?-1:t>o?1:0).map(([t,o])=>[t,o.provider,o.roleCode,o.scope?.dimension??null,o.scope?.valueFrom??null,o.scope?.value??null])})}function bs(e){let t=[],o=new Map;for(let n of e)for(let[r,i]of Object.entries(n.bindings||{})){if(!Le(i)||i.routing===void 0)continue;let a=Pn(i.routing);if(a.length){t.push(...a.map(c=>`${c}:${r}`));continue}let s=Qd(i.routing),d=o.get(i.routing.policyCode);d&&d!==s&&t.push(`WORKFLOW_V2_ROUTING_POLICY_CONFLICT:${i.routing.policyCode}`),o.set(i.routing.policyCode,s)}return[...new Set(t)]}function hp(e,t){let o={};for(let[n,r]of Object.entries(e.dimensions)){let i=t;for(let a of r.valueFrom.split("."))i=Le(i)&&Object.hasOwn(i,a)?i[a]:void 0;if(!(typeof i=="string"&&tt(i,255)||typeof i=="number"&&Number.isFinite(i)||typeof i=="boolean"))throw new Error(`WORKFLOW_V2_ROUTING_FACT_REQUIRED:${n}`);o[n]=String(i)}return o}function Rp(e,t,o){let n=t.filter(c=>c.enabled&&(!c.validFrom||Date.parse(c.validFrom)<=o.at)&&(!c.validTo||Date.parse(c.validTo)>o.at)&&(!c.workflowCode||c.workflowCode===o.workflowCode)&&(!c.nodeId||c.nodeId===o.nodeId)&&Object.entries(c.matches).every(([l,f])=>f.includes(o.facts[l])));if(n.length>64)throw new Error("WORKFLOW_V2_ROUTING_MATCH_LIMIT_EXCEEDED");let r=(c,l)=>l.priority-c.priority||+!!c.workflowCode-+!!l.workflowCode||+!!c.nodeId-+!!l.nodeId||(c.ruleCode<l.ruleCode?-1:c.ruleCode>l.ruleCode?1:0),i=n.filter(c=>c.effect==="replace").sort(r);if(i.length>1&&i[0].priority===i[1].priority)throw new Error("WORKFLOW_V2_ROUTING_REPLACE_CONFLICT");let a=i[0],s=a&&e.strategy==="replace_only"?[]:n.filter(c=>c.effect==="append").sort(r),d=[...a?[a]:[],...s];return{matched:n.sort(r),replacement:a,applied:d,ignored:n.filter(c=>!d.includes(c))}}var ar="^[A-Za-z][A-Za-z0-9_]{0,62}$",Ns="^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$",Cp={type:"object",additionalProperties:!1,required:["mode","resourceCode","subtables"],properties:{mode:{const:"create"},resourceCode:{type:"string",maxLength:64,pattern:Ns},subtables:{type:"array",minItems:1,maxItems:16,items:{type:"object",additionalProperties:!1,required:["fieldCode","fieldCodes"],properties:{fieldCode:{type:"string",pattern:ar},fieldCodes:{type:"array",minItems:1,maxItems:200,uniqueItems:!0,items:{type:"string",pattern:ar}}}}}}};function vn(e){let t=n=>!!(n&&typeof n=="object"&&!Array.isArray(n)),o=n=>typeof n=="string"&&new RegExp(ar).test(n)&&!["__proto__","prototype","constructor"].includes(n);if(!t(e)||Object.keys(e).some(n=>!["mode","resourceCode","subtables"].includes(n))||e.mode!=="create"||typeof e.resourceCode!="string"||e.resourceCode.length>64||!new RegExp(Ns).test(e.resourceCode)||!Array.isArray(e.subtables)||e.subtables.length<1||e.subtables.length>16||e.subtables.some(n=>!t(n)||Object.keys(n).some(r=>!["fieldCode","fieldCodes"].includes(r))||!o(n.fieldCode)||!Array.isArray(n.fieldCodes)||n.fieldCodes.length<1||n.fieldCodes.length>200||new Set(n.fieldCodes).size!==n.fieldCodes.length||n.fieldCodes.some(r=>!o(r)))||new Set(e.subtables.map(n=>n.fieldCode)).size!==e.subtables.length)throw new Error("WORKFLOW_OWNED_SUBJECT_CREATE_INVALID")}function Sp(e){return vn(e),{mode:"create",resourceCode:e.resourceCode,subtables:e.subtables.map(t=>({fieldCode:t.fieldCode,fieldCodes:[...t.fieldCodes].sort()})).sort((t,o)=>t.fieldCode.localeCompare(o.fieldCode))}}function hs(e,t,o){vn(e);let n=s=>{throw new Error(`WORKFLOW_OWNED_SUBJECT_${s}`)},r=t.get(e.resourceCode);r||n("RESOURCE_MISSING");let i=new Set,a=0;for(let s of e.subtables){let d=r.get(s.fieldCode),c=d?.subtable,l=t.get(c?.resourceCode);(d?.type!=="subtable"||!l||c.resourceCode===e.resourceCode||i.has(c.resourceCode))&&n("RELATION_INVALID"),i.add(c.resourceCode);let f=c.maxRows??20;(!Number.isSafeInteger(f)||f<1||f>He)&&n("BUDGET_EXCEEDED"),a+=f;for(let p of s.fieldCodes){let m=l.get(p);(!m||["serial-number","subtable"].includes(m.type)||[c.foreignKey,c.orderField].includes(p))&&n("FIELD_INVALID"),["file","image","signature","text.rich"].includes(m.type)&&!o.some(E=>E.resourceCode===c.resourceCode&&E.fieldCodes.includes(p)&&E.intents.includes("create"))&&n("FILE_ACCESS_REQUIRED")}}a>ct&&n("BUDGET_EXCEEDED")}import*as Un from"crypto";var Rs="native-4",dr="2.0.0-alpha.5",ws={"application-native-2":"1.0.0","application.extended-declaration-capacity":"1.0.0","application.extended-role-capacity":"1.0.0","application.extended-artifact-capacity":"1.0.0","application.high-density-artifact-capacity":"1.0.0","application.extended-configuration-bytes":"1.0.0","application.development-configuration":"2.0.0","authz.native-batch-explain":"1.0.0","authz.native-management":"1.0.0","authz.native-membership-batch":"1.0.0","deployment.durable-runs":"1.0.0","deployment.platform-executor":"1.0.0","environment.on-demand-production":"1.0.0","environment.runtime-lifecycle":"1.0.0","data.rich-text":"1.0.0","data-api-v2":"1.1.0","data.service-mutations":"1.0.0","data.extended-owned-subtable-capacity":"1.0.0","data.aggregate-owned-subtable-capacity":"1.0.0","data.extended-field-capacity":"1.0.0","data.business-commands":"1.0.0","data.record-edit":"1.0.0","data.native-golden-crud":"1.0.0","data.audit-read-access":"1.0.0","data.managed-files":"1.1.0","data.decimal-reservations":"1.1.0","data.decimal-reservation-lifecycle":"1.0.0","data.unique-keys":"1.1.0","data.user-candidates":"1.0.0","data.field-source-contexts":"1.0.0","data.user-candidate-launch-scope":"1.0.0","data.datetime-minute-precision":"1.0.0","data.subtable-minimum-rows":"1.0.0","data.managed-concurrency":"1.0.0","data.managed-concurrency.durable":"1.0.0","workflow.named-input-sources":"1.0.0","workflow.approved-delegation":"1.0.0","directory-v2":"1.0.0","directory.selected-user":"1.0.0","directory.selected-departments":"1.0.0","directory.current-initiator-phone":"1.0.0","events-v2":"1.0.0","events.durable-receipts":"1.0.0","events.capture-policy":"1.0.0","events.date-source-projection":"1.0.0","events.native-data-actions":"1.0.0","workflow-kernel-v2":"1.0.0","workflow.business-data-command":"1.0.0","workflow.approval-business-command":"1.0.0","workflow.native-stage-guard":"1.0.0","workflow.launch-preflight":"1.0.0","workflow.optional-rejection-comment":"1.0.0","workflow.optional-operation-reason":"1.0.0","workflow.optional-withdrawal-reason":"1.0.0","data.transaction-actor-authority":"1.0.0","data.authenticated-public-projection":"1.0.0","data.parent-read-policy":"1.0.0","data.record-print":"1.0.0","data.workflow-record-deletion":"1.0.0","data.record-comments":"1.0.0","workflow.record-history-read":"1.0.0","workflow.rejection-notification":"1.0.0","workflow.instance-cancellation-policy":"1.0.0","workflow.node-administration":"1.0.0","workflow.assignment-routing":"1.0.0","workflow.role-union":"1.0.0","workflow.role-input-selection":"1.0.0","workflow.named-owned-create":"1.0.0","workflow.owned-initial-facts":"1.0.0","workflow.initiator-correction":"1.0.0","workflow.correction-business-command":"1.0.0","workflow.correction-derived-subject-facts":"1.0.0","workflow.role-references":"1.0.0","workflow.delegation-management":"1.0.0","workflow.automatic-cc":"1.0.0","workflow.approval-empty-policy":"1.0.0","workflow.initiator-approval-policy":"1.0.0","workflow.platform-notify":"1.0.0","workflow.reminders":"1.0.0","workflow.supervisor-chain":"1.0.0","workflow.return-policy":"1.0.0","workflow.handling-nodes":"1.0.0","workflow.completion-deadline":"1.0.0","workflow.task-page-submit":"1.0.0","workflow.task-private-drafts":"1.0.0","workflow.task-managed-files":"1.0.0","workflow.task-rich-fields":"1.0.0","workflow.task-owned-subtables":"1.0.0","workflow.task-owned-files":"1.0.0","workflow.durable-business-step":"1.0.0","workflow.step-data-transaction":"1.0.0","business-process.durable-command":"1.1.0","workflow.fresh-command-token":"1.0.0","notification-hub-v2":"1.0.0","authentication.application-login-surface":"1.0.0","public-access.anonymous-owner-records":"1.0.0"};var B=Object.freeze({perspectives:100,resources:512,dataPolicies:512,roles:512,subjectReadSurfaces:50,capabilities:4096,operations:500,eventConsumers:100,eventProducers:1e3,eventSchemas:100,eventTypes:500,workflows:512,routes:2048,adminPages:2048,adminNavigationGroups:100,adminNavigationItems:1024});function Ts(e){let t=(e.surface?.mutationOwner||"native")==="native";return["query","get","create","update","delete"].filter(o=>{let n=e.surface?.generated;return o==="query"?n?.list??!0:o==="get"?n?.detail??!0:n?.[o]??t})}function cr(e){return(e.authz?.roles?.length||0)>256}function lr(e){let t=(e.data?.resources||[]).filter(o=>o.status!=="retired").reduce((o,n)=>o+Ts(n).length,0)+(e.backend?.operations||[]).filter(o=>o.ai).length;return(e.data?.resources?.length||0)>100||(e.authz?.dataPolicies?.length||0)>100||(e.authz?.roles?.length||0)>100||(e.authz?.capabilities?.length||0)>2e3||[e.workflows?.definitions,e.workflows?.bindings,e.workflows?.activations].some(o=>(o?.length||0)>100)||(e.frontend?.routes?.length||0)>500||t>500||(e.frontend?.admin?.navigation||[]).reduce((o,n)=>o+n.items.length,0)>500}var se=Object.freeze({legacyConfigBytes:4194304,configBytes:8388608,contractBytes:8388608,depth:40,stringBytes:1048576,legacyNodes:1e5,extendedNodes:25e4}),yt=Object.freeze({nodes:5e5});function ur(e){return Buffer.byteLength(Q(e),"utf8")>se.legacyConfigBytes}function Cs(e,t){let o=0,n=[[e][Symbol.iterator]()];for(;n.length;){let r=n[n.length-1].next();if(r.done){n.pop();continue}if(++o>t)return!0;if(Array.isArray(r.value))n.push(r.value.values());else if(r.value&&typeof r.value=="object"){let i=r.value;n.push((function*(){for(let a of Object.keys(i))i[a]!==void 0&&(yield i[a])})())}}return!1}function Vn(e){return Cs(e,se.legacyNodes)}function Fn(e){return Cs(e,se.extendedNodes)}var zt=["openxiangda.workflow.task.reminded.v2","openxiangda.workflow.node.notified.v2","openxiangda.workflow.node.skipped.v2","openxiangda.workflow.step.requested.v2","openxiangda.workflow.step.result_received.v2","openxiangda.workflow.step.completed.v2","openxiangda.workflow.step.continuation_failed.v2","openxiangda.workflow.instance.started.v2","openxiangda.workflow.instance.cc_added.v2","openxiangda.workflow.instance.completed.v2","openxiangda.workflow.instance.rejected.v2","openxiangda.workflow.instance.returned.v2","openxiangda.workflow.instance.resumed.v2","openxiangda.workflow.instance.withdrawn.v2","openxiangda.workflow.instance.terminated.v2","openxiangda.workflow.task.created.v2","openxiangda.workflow.task.assigned.v2","openxiangda.workflow.task.assignment_pending.v2","openxiangda.workflow.task.assignment_resolution_failed.v2","openxiangda.workflow.task.approved.v2","openxiangda.workflow.task.completed.v2","openxiangda.workflow.task.rejected.v2","openxiangda.workflow.task.returned.v2","openxiangda.workflow.task.resubmitted.v2","openxiangda.workflow.task.transferred.v2","openxiangda.workflow.task.reassigned.v2","openxiangda.workflow.task.delegated.v2","openxiangda.workflow.task.assignee_added.v2","openxiangda.workflow.task.cancelled.v2","openxiangda.workflow.participant.activated.v2","openxiangda.workflow.participant.completed.v2","openxiangda.workflow.participant.rejected.v2","openxiangda.workflow.participant.returned.v2","openxiangda.workflow.participant.transferred.v2","openxiangda.workflow.participant.reassigned.v2","openxiangda.workflow.participant.delegated.v2","openxiangda.workflow.participant.added.v2","openxiangda.workflow.participant.suspended.v2","openxiangda.workflow.participant.resumed.v2","openxiangda.workflow.participant.cancelled.v2"];function fr(e){let t=e.flatMap(n=>Object.values(n.definition.nodes)),o=t.some(n=>n.kind==="action"&&!te(n));return zt.filter(n=>n==="openxiangda.workflow.task.reminded.v2"?t.some(r=>r.reminders):n==="openxiangda.workflow.node.notified.v2"?t.some(te):n==="openxiangda.workflow.node.skipped.v2"?t.some(r=>r.kind==="approval"&&r.emptyPolicy==="skip"):n.startsWith("openxiangda.workflow.step.")?o:!0)}var ec="openxiangda.config-bundle/v3",qs="openxiangda.contract-bundle/v3",Ss="openxiangda.native-configuration-projection/v1",Jt=Rs,tc=/^[a-f0-9]{64}$/,nc=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,oc=/^app:[a-z][a-z0-9]*(?:-[a-z0-9]+)*:[A-Za-z0-9:._*-]+$/,rc=/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/,ic=/^[a-z][a-z0-9]*(?:[-.][a-z0-9]+)*$/,sc=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,ac=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,Ds=/^[A-Za-z][A-Za-z0-9_]{0,127}$/,dc=/^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*$/,cc=/^[A-Z][A-Z0-9_]*$/,lc=/^[a-z][a-z0-9-]{2,63}$/,uc=/^[A-Za-z][A-Za-z0-9_-]{0,127}$/,fc=/^[A-Za-z][A-Za-z0-9_.]{0,127}$/,pc=16,mc=2*1024,_c=new Set(["text.short","text.long","number.integer","number.decimal","boolean","date","time","datetime","option.single","option.multiple","cascade.single","cascade.multiple","user.single","user.multiple","department.single","department.multiple","resource-ref.single","resource-ref.multiple","uuid","serial-number"]),gc=new Set(["overview","database","operations","workflow","members","calendar","document","folder","settings"]),Ac=new Set(["complete","save_form","approve","reject","return","transfer","delegate","add_assignee","resubmit","withdraw","terminate","admin_reassign","admin_override","retry_resolution"]),Ec=se.configBytes,Ic=se.contractBytes,yc=se.depth,mr=se.stringBytes,Oc="openxiangda.event-handler-manifest/v2",zs="openxiangda.application-route-manifest/v3",ks=64,Js=new Set(["id","revision","created_by","updated_by","created_at","updated_at"]),_r=["openxiangda.data.record.created.v2","openxiangda.data.record.updated.v2","openxiangda.data.record.deleted.v2"],bc=new Set(zt),gr=class extends Error{code;pointer;identifiers;constructor(t,o,n={}){super(t),this.name="NativeConfigurationCompilerError",this.code=t,this.pointer=o,this.identifiers=Object.fromEntries(Object.entries(n).slice(0,8).map(([r,i])=>[r,String(i).slice(0,128)]))}};function Wm(e){let t=D(e.appCode,"/appCode",128);nc.test(t)||_("NATIVE_CONFIG_APP_CODE_INVALID","/appCode");let o=Er(e.expectedConfigDigest,"/expectedConfigDigest"),n=Er(e.expectedContractDigest,"/expectedContractDigest"),r=Bs(e.configBytes,Ec,"/configBytes","NATIVE_CONFIG_ARTIFACT_TOO_LARGE"),i=Bs(e.contractBytes,Ic,"/contractBytes","NATIVE_CONTRACT_ARTIFACT_TOO_LARGE");Ks(r,o,"/configBytes","NATIVE_CONFIG_DIGEST_MISMATCH"),Ks(i,n,"/contractBytes","NATIVE_CONTRACT_DIGEST_MISMATCH");let a=Us(r,"/configBytes","NATIVE_CONFIG_JSON_INVALID","NATIVE_CONFIG_NOT_CANONICAL"),s=Us(i,"/contractBytes","NATIVE_CONTRACT_JSON_INVALID","NATIVE_CONTRACT_NOT_CANONICAL");Wn(a,"/config",yt.nodes),Wn(s,"/contracts",yt.nodes),Fn(a)||Wn(s,"/contracts",se.extendedNodes),Vn(a)||Wn(s,"/contracts",se.legacyNodes);let d=a,c=s;wc(d,t),Tc(c,t,o);let l=Cc(d,o,c.generatorVersion);ml(l,c,d),Q(l)!==Q(c)&&_("NATIVE_CONTRACT_CLOSURE_MISMATCH",Ir(l,c,"/contracts"));let f={authz:{appCode:t,...d.authz,perspectives:d.perspectives,capabilityCatalog:l.capabilities},data:{appCode:t,resources:d.data.resources,resourceContracts:l.resources,...l.concurrency?{concurrency:l.concurrency}:{},...l.subjectReadSurfaces?{subjectReadSurfaces:l.subjectReadSurfaces}:{}},events:{appCode:t,...d.events,consumers:l.eventConsumers,producers:l.eventProducers,handlerManifest:l.eventHandlerManifest,eventTypes:l.eventTypes,capturePlans:hc({resources:d.data.resources,dataPolicies:d.authz.dataPolicies,subscriptions:l.eventConsumers,capturePolicies:d.events.capturePolicies})},workflows:{appCode:t,...d.workflows,contracts:l.workflows},runtime:{appCode:t,requirements:d.runtime,backend:d.backend,frontend:d.frontend},contracts:l},p={authz:Ot(f.authz),data:Ot(f.data),events:Ot(f.events),workflows:Ot(f.workflows),runtime:Ot(f.runtime),contracts:Ot(f.contracts)},m={configDigest:o,contractDigest:n,generatorVersion:c.generatorVersion},E=Nc(d),A={schemaVersion:Ss,compilerContractVersion:Jt,appCode:t,source:m,projections:p,requiredPlatformCapabilities:E,aggregateDigest:ee({schemaVersion:Ss,compilerContractVersion:Jt,appCode:t,source:m,requiredPlatformCapabilities:E,projectionDigests:Object.fromEntries(Object.entries(p).map(([b,O])=>[b,O.digest]))})};return sa(A)}function Ls(e,t){let o=e.subject,n=t.find(i=>i.code===o?.resourceCode),r=new Set(Object.values(o?.factProjection||{}));return!!n?.schema?.fields?.some(i=>i.type==="subtable"&&r.has(i.code))}function Nc(e){let t=e.authz.roles,o=e.data.resources,n=e.backend.operations,r=n.filter(u=>u.platformAccess?.directory?.mode==="current-initiator"&&u.platformAccess.directory.fields.includes("phone")),i=(e.data.concurrency?.commands||[]).filter(u=>u.execution?.directory?.mode==="current-initiator"&&u.execution.directory.fields.includes("phone")),a=t.some(u=>u.capabilities.some(I=>I.endsWith(":directory:read")))||o.some(u=>u.schema.fields.some(I=>["user.single","user.multiple","department.single","department.multiple"].includes(I.type)))||n.some(u=>u.platformAccess?.directory||u.platformAccess?.selectedDepartments),s=!!(e.events.subscriptions.length||e.events.timers.length||e.events.dateTriggers.length||e.events.schemas.length),d=n.some(u=>u.platformAccess?.managedFiles||u.platformAccess?.managedFileCopies)||e.events.subscriptions.some(u=>u.platformAccess?.managedFileCopies),c=e.workflows.definitions.some(u=>u.definition.rejectionNotification!==void 0)||n.some(u=>u.platformAccess?.notification)||e.events.subscriptions.some(u=>u.platformAccess?.notification),l=(u,I,R=!1)=>{let w=o.find(C=>C.code===u.definition.subject?.resourceCode)?.schema.fields||[];return Object.values(u.definition.taskPages||{}).some(C=>C.fields.some(S=>{if(S.readonly)return!1;let P=w.find(q=>q.code===S.code);if(!R&&P&&I.includes(P.type))return!0;if(!S.subtable||!P?.subtable)return!1;let V=o.find(q=>q.code===P.subtable.resourceCode)?.schema.fields||[];return S.subtable.fields.some(q=>!q.readonly&&V.some(Z=>Z.code===q.code&&I.includes(Z.type)))}))},f=e.workflows.definitions.filter(u=>l(u,["file","image","signature","text.rich"])),p=e.workflows.definitions.filter(u=>l(u,["signature","text.rich"])),m=e.workflows.definitions.filter(u=>l(u,["file","image","signature","text.rich"],!0)),E=e.workflows.definitions.filter(u=>u.launch.mode==="standalone"||u.launch.mode==="hidden-handoff"),A=n.some(u=>u.platformAccess?.workflow)||E.length>0,b=E.filter(u=>{let I=u.launch.submission;if(!I)return!1;let R=o.find(w=>w.code===u.definition.subject.resourceCode);return[I.create,I.existing].some(w=>w&&Object.values(w.inputs).some(C=>C.source==="field"&&R?.schema.fields.some(S=>S.code===C.fieldCode&&S.type.startsWith("resource-ref.")&&S.source)))}),O={resources:o},g={perspectives:e.perspectives,authz:e.authz},y={schemaVersion:e.schemaVersion,appCode:e.appCode,frontend:{routes:e.frontend.routes,user:e.frontend.user,admin:e.frontend.admin,devicePolicy:e.frontend.devicePolicy},backend:{operations:n.map(u=>({code:u.code,method:u.method,path:u.path,capability:u.capability,platformAccess:u.platformAccess||null,...u.browser?{browser:u.browser}:{},ai:u.ai||null}))}};return[...cr(e)?[{code:"application.extended-role-capacity",declaration:{roles:e.authz.roles.length,maximum:B.roles}}]:[],...ur(e)?[{code:"application.extended-configuration-bytes",declaration:{legacyConfigBytes:se.legacyConfigBytes,configBytes:se.configBytes}}]:[],...Vn(e)?[{code:"application.extended-artifact-capacity",declaration:se}]:[],...Fn(e)?[{code:"application.high-density-artifact-capacity",declaration:yt}]:[],...lr(e)?[{code:"application.extended-declaration-capacity",declaration:{resources:e.data.resources.length,policies:e.authz.dataPolicies.length,roles:e.authz.roles.length,capabilities:e.authz.capabilities.length,definitions:e.workflows.definitions.length,bindings:e.workflows.bindings.length,activations:e.workflows.activations.length,routes:e.frontend.routes.length,navigationItems:e.frontend.admin.navigation.reduce((u,I)=>u+I.items.length,0)}}]:[],...o.some(u=>u.uniqueKeys?.length)?[{code:"data.unique-keys",declaration:o.filter(u=>u.uniqueKeys?.length).map(u=>({code:u.code,uniqueKeys:u.uniqueKeys}))}]:[],...e.data.concurrency?[{code:"data.managed-concurrency",declaration:e.data.concurrency}]:[],...e.data.concurrency?.commands.some(u=>u.mode==="durable")?[{code:"data.managed-concurrency.durable",declaration:e.data.concurrency}]:[],...o.some(u=>u.decimalReservationLifecycle)?[{code:"data.decimal-reservation-lifecycle",declaration:o.filter(u=>u.decimalReservationLifecycle).map(u=>({code:u.code,decimalReservationLifecycle:u.decimalReservationLifecycle}))}]:[],...n.some(u=>u.platformAccess?.dataCommands)?[{code:"data.business-commands",declaration:n.filter(u=>u.platformAccess?.dataCommands)}]:[],...e.authz.dataPolicies.some(qo)?[{code:"data.parent-read-policy",declaration:e.authz.dataPolicies.filter(qo)}]:[],...e.authz.dataPolicies.some(u=>u.publicRead)?[{code:"data.authenticated-public-projection",declaration:e.authz.dataPolicies.filter(u=>u.publicRead)}]:[],...n.some(u=>u.platformAccess?.roleAssertions?.actorAuthority)?[{code:"data.transaction-actor-authority",declaration:n.filter(u=>u.platformAccess?.roleAssertions?.actorAuthority)}]:[],...n.some(u=>u.platformAccess?.workflowStage)?[{code:"workflow.native-stage-guard",declaration:n.filter(u=>u.platformAccess?.workflowStage)}]:[],...n.some(u=>u.platformAccess?.recordEdit)?[{code:"data.record-edit",declaration:n.filter(u=>u.platformAccess?.recordEdit)}]:[],...n.some(u=>u.platformAccess?.decimalReservation)||e.events.subscriptions.some(u=>u.platformAccess?.decimalReservation)?[{code:"data.decimal-reservations",declaration:[...n.filter(u=>u.platformAccess?.decimalReservation).map(u=>({code:u.code,decimalReservation:u.platformAccess.decimalReservation})),...e.events.subscriptions.filter(u=>u.platformAccess?.decimalReservation).map(u=>({subscriptionCode:u.code,decimalReservation:u.platformAccess.decimalReservation}))]}]:[],{code:"application-native-2",declaration:y},{code:"authz.native-batch-explain",declaration:g},{code:"authz.native-management",declaration:g},{code:"deployment.durable-runs",declaration:y.backend},{code:"deployment.platform-executor",declaration:y.backend},{code:"environment.on-demand-production",declaration:{environments:["preproduction","production"]}},{code:"environment.runtime-lifecycle",declaration:{environments:["preproduction","production"]}},...o.length?[{code:"data-api-v2",declaration:O},{code:"data.native-golden-crud",declaration:O}]:[],...o.some(u=>u.recordComments!==void 0)?[{code:"data.record-comments",declaration:O}]:[],...o.some(u=>u.recordDeletion!==void 0)?[{code:"data.workflow-record-deletion",declaration:O}]:[],...o.some(u=>u.recordPrint!==void 0)?[{code:"data.record-print",declaration:O}]:[],...o.some(u=>u.workflowHistory!==void 0)?[{code:"workflow.record-history-read",declaration:O}]:[],...o.some(Hr)?[{code:"data.audit-read-access",declaration:O}]:[],...o.some(u=>u.schema.fields.some(I=>/^(resource-ref|user|department)\.(single|multiple)$/.test(I.type)))||e.authz.scopeDimensions.some(u=>u.valueSource)?[{code:"data.field-source-contexts",declaration:{resources:o.map(u=>({code:u.code,fields:u.schema.fields.filter(I=>/^(resource-ref|user|department)\.(single|multiple)$/.test(I.type))})),dimensions:e.authz.scopeDimensions.filter(u=>u.valueSource)}}]:[],...a?[{code:"directory-v2",declaration:{roles:t.map(u=>({code:u.code,capabilities:u.capabilities.filter(I=>I.endsWith(":directory:read"))})),resources:o.map(u=>({code:u.code,fields:u.schema.fields.filter(I=>["user.single","user.multiple","department.single","department.multiple"].includes(I.type))})),operations:n.filter(u=>u.platformAccess?.directory).map(u=>({code:u.code,directory:u.platformAccess.directory}))}}]:[],...n.some(u=>u.platformAccess?.selectedDepartments)?[{code:"directory.selected-departments",declaration:n.filter(u=>u.platformAccess?.selectedDepartments).map(u=>({code:u.code,selectedDepartments:u.platformAccess.selectedDepartments}))}]:[],...n.some(u=>u.platformAccess?.directory?.mode==="selected-user")?[{code:"directory.selected-user",declaration:n.filter(u=>u.platformAccess?.directory?.mode==="selected-user").map(u=>({code:u.code,directory:u.platformAccess.directory}))}]:[],...r.length||i.length?[{code:"directory.current-initiator-phone",declaration:{operations:r.map(u=>({code:u.code,directory:u.platformAccess.directory})),commands:i.map(u=>({code:u.code,directory:u.execution.directory}))}}]:[],...e.data.resources.some(u=>u.schema.fields.some(I=>I.type==="text.rich"))?[{code:"data.rich-text",declaration:{policyVersion:"rich-text-html/1"}}]:[],...d?[{code:"data.managed-files",declaration:{operations:n.filter(u=>u.platformAccess?.managedFiles||u.platformAccess?.managedFileCopies).map(u=>({code:u.code,...u.platformAccess?.managedFiles?{managedFiles:u.platformAccess.managedFiles}:{},...u.platformAccess?.managedFileCopies?{managedFileCopies:u.platformAccess.managedFileCopies}:{}})),subscriptions:e.events.subscriptions.filter(u=>u.platformAccess?.managedFileCopies).map(u=>({code:u.code,managedFileCopies:u.platformAccess.managedFileCopies}))}}]:[],...e.events.subscriptions.some(u=>u.execution)?[{code:"events.native-data-actions",declaration:e.events.subscriptions.filter(u=>u.execution)}]:[],...e.events.capturePolicies?.length?[{code:"events.capture-policy",declaration:e.events.capturePolicies}]:[],...e.events.dateTriggers.some(u=>fs(u.resourceCode,e.events.subscriptions.filter(I=>I.eventTypes.includes(u.eventType)),e.data.resources.find(I=>I.code===u.resourceCode)).length>0)?[{code:"events.date-source-projection",declaration:{triggers:e.events.dateTriggers,subscriptions:e.events.subscriptions}}]:[],...s?[{code:"events-v2",declaration:e.events},{code:"events.durable-receipts",declaration:e.events}]:[],...lo(e.data.resources)?[{code:"data.extended-owned-subtable-capacity",declaration:e.data.resources.filter(u=>lo([u]))}]:[],...ao(e.data.resources,e.workflows?.definitions||[])?[{code:"data.extended-field-capacity",declaration:{resources:e.data.resources.filter(u=>u.schema.fields.length>100),workflows:(e.workflows?.definitions||[]).filter(u=>ao([],[u]))}}]:[],...co(e.data.resources)?[{code:"data.aggregate-owned-subtable-capacity",declaration:e.data.resources.filter(u=>co([u]))}]:[],...e.data.resources.some(u=>u.schema.fields.some(I=>I.userCandidates!==void 0))?[{code:"data.user-candidates",declaration:e.data.resources.filter(u=>u.schema.fields.some(I=>I.userCandidates!==void 0))}]:[],...Yi(e.workflows.bindings)?[{code:"workflow.role-input-selection",declaration:e.workflows.bindings.filter(u=>Object.values(u.binding.bindings).some(I=>I.selectedInputPath!==void 0))}]:[],...Ji(e.workflows.bindings)?[{code:"workflow.role-union",declaration:e.workflows.bindings.filter(u=>Object.values(u.binding.bindings).some(I=>I.roleCodes!==void 0))}]:[],...e.backend.operations.some(u=>u.platformAccess?.ownedSubject)?[{code:"workflow.named-owned-create",declaration:e.backend.operations.filter(u=>u.platformAccess?.ownedSubject)}]:[],...ro(e.data.resources)?[{code:"data.user-candidate-launch-scope",declaration:e.data.resources.filter(u=>ro([u]))}]:[],..._o(e.data.resources)?[{code:"data.subtable-minimum-rows",declaration:e.data.resources.filter(u=>_o([u]))}]:[],...mo(e.data.resources)?[{code:"data.datetime-minute-precision",declaration:e.data.resources.filter(u=>mo([u]))}]:[],...e.workflows.activations.length?[{code:"workflow-kernel-v2",declaration:e.workflows},{code:"workflow.fresh-command-token",declaration:e.workflows}]:[],...e.workflows.definitions.some(u=>u.definition.instanceCommands!==void 0)?[{code:"workflow.instance-cancellation-policy",declaration:e.workflows.definitions.filter(u=>u.definition.instanceCommands!==void 0)}]:[],...e.workflows.definitions.some(u=>u.definition.instanceCommands?.withdraw?.reasonRequired===!1)?[{code:"workflow.optional-withdrawal-reason",declaration:e.workflows.definitions.filter(u=>u.definition.instanceCommands?.withdraw?.reasonRequired===!1)}]:[],...e.workflows.definitions.some(u=>u.definition.rejectionNotification!==void 0)?[{code:"workflow.rejection-notification",declaration:e.workflows.definitions.filter(u=>u.definition.rejectionNotification!==void 0)}]:[],...e.workflows.definitions.some(u=>u.definition.commandHandlers!==void 0)||n.some(u=>u.platformAccess?.workflow?.businessCommands)?[{code:"workflow.business-data-command",declaration:{definitions:e.workflows.definitions.filter(u=>u.definition.commandHandlers!==void 0),operations:n.filter(u=>u.platformAccess?.workflow?.businessCommands)}}]:[],...e.workflows.definitions.some(u=>u.definition.commandHandlers?.approve?.transitionPolicy==="workflow")?[{code:"workflow.approval-business-command",declaration:e.workflows.definitions.filter(u=>u.definition.commandHandlers?.approve?.transitionPolicy==="workflow")}]:[],...e.workflows.definitions.some(u=>u.definition.commandHandlers?.resubmit)||n.some(u=>u.platformAccess?.workflow?.businessCommands?.includes("resubmit"))?[{code:"workflow.correction-business-command",declaration:{definitions:e.workflows.definitions.filter(u=>u.definition.commandHandlers?.resubmit),operations:n.filter(u=>u.platformAccess?.workflow?.businessCommands?.includes("resubmit"))}}]:[],...e.workflows.definitions.some(u=>u.definition.launchPreflight!==void 0)?[{code:"workflow.launch-preflight",declaration:e.workflows.definitions.filter(u=>u.definition.launchPreflight!==void 0)}]:[],...e.workflows.definitions.some(u=>u.definition.commandHandlers?.resubmit?.derivedSubjectFields!==void 0)?[{code:"workflow.correction-derived-subject-facts",declaration:e.workflows.definitions.filter(u=>u.definition.commandHandlers?.resubmit?.derivedSubjectFields!==void 0)}]:[],...e.workflows.definitions.some(u=>u.definition.approvedDelegation!==void 0)?[{code:"workflow.approved-delegation",declaration:e.workflows.definitions.filter(u=>u.definition.approvedDelegation!==void 0)}]:[],...e.workflows.definitions.some(u=>Ls(u.definition,e.data.resources))?[{code:"workflow.owned-initial-facts",declaration:e.workflows.definitions.filter(u=>Ls(u.definition,e.data.resources))}]:[],...e.workflows.definitions.some(u=>Object.values(u.definition.nodes).some(I=>I.kind==="correction"))?[{code:"workflow.initiator-correction",declaration:e.workflows.definitions.filter(u=>Object.values(u.definition.nodes).some(I=>I.kind==="correction"))}]:[],...e.workflows.definitions.some(u=>Object.values(u.definition.nodes).some(I=>I.operationPolicy?.reject?.commentRequired===!1))?[{code:"workflow.optional-rejection-comment",declaration:e.workflows.definitions.filter(u=>Object.values(u.definition.nodes).some(I=>I.operationPolicy?.reject?.commentRequired===!1))}]:[],...e.workflows.definitions.some(u=>Object.values(u.definition.nodes).some(I=>Object.values(I.operationPolicy||{}).some(R=>R.reasonRequired===!1)))?[{code:"workflow.optional-operation-reason",declaration:e.workflows.definitions.filter(u=>Object.values(u.definition.nodes).some(I=>Object.values(I.operationPolicy||{}).some(R=>R.reasonRequired===!1)))}]:[],...b.length?[{code:"workflow.named-input-sources",declaration:b}]:[],...e.workflows.definitions.some(u=>Object.values(u.definition.nodes).some(I=>I.administration!==void 0||I.operationPolicy!==void 0))?[{code:"workflow.node-administration",declaration:e.workflows.definitions.filter(u=>Object.values(u.definition.nodes).some(I=>I.administration!==void 0||I.operationPolicy!==void 0))}]:[],...e.workflows.definitions.some(u=>Object.values(u.definition.nodes).some(I=>I.kind==="approval"&&I.emptyPolicy!==void 0))?[{code:"workflow.approval-empty-policy",declaration:e.workflows.definitions.filter(u=>Object.values(u.definition.nodes).some(I=>I.kind==="approval"&&I.emptyPolicy!==void 0))}]:[],...e.workflows.bindings.some(u=>Object.values(u.binding.bindings).some(I=>I.provider==="supervisor_chain"))?[{code:"workflow.supervisor-chain",declaration:e.workflows.bindings.filter(u=>Object.values(u.binding.bindings).some(I=>I.provider==="supervisor_chain"))}]:[],...e.workflows.definitions.some(u=>Object.values(u.definition.nodes).some(I=>I.reminders))?[{code:"workflow.reminders",declaration:e.workflows.definitions.filter(u=>Object.values(u.definition.nodes).some(I=>I.reminders))}]:[],...e.workflows.definitions.some(u=>Object.values(u.definition.nodes).some(I=>te(I)))?[{code:"workflow.platform-notify",declaration:e.workflows.definitions.filter(u=>Object.values(u.definition.nodes).some(I=>te(I)))}]:[],...e.workflows.definitions.some(u=>Object.values(u.definition.nodes).some(I=>I.returnPolicy!==void 0))?[{code:"workflow.return-policy",declaration:e.workflows.definitions.filter(u=>Object.values(u.definition.nodes).some(I=>I.returnPolicy!==void 0))}]:[],...e.workflows.definitions.some(u=>Object.values(u.definition.nodes).some(I=>I.kind==="handle"))?[{code:"workflow.handling-nodes",declaration:e.workflows.definitions.filter(u=>Object.values(u.definition.nodes).some(I=>I.kind==="handle"))}]:[],...e.workflows.definitions.some(u=>Object.values(u.definition.nodes).some(I=>I.completionDeadline!==void 0))?[{code:"workflow.completion-deadline",declaration:e.workflows.definitions.filter(u=>Object.values(u.definition.nodes).some(I=>I.completionDeadline!==void 0))}]:[],...e.workflows.definitions.some(u=>Object.values(u.definition.nodes).some(I=>I.initiatorApprovalPolicy!==void 0))?[{code:"workflow.initiator-approval-policy",declaration:e.workflows.definitions.filter(u=>Object.values(u.definition.nodes).some(I=>I.initiatorApprovalPolicy!==void 0))}]:[],...e.workflows.definitions.some(u=>Object.values(u.definition.nodes).some(I=>I.kind==="cc"))?[{code:"workflow.automatic-cc",declaration:e.workflows.definitions.filter(u=>Object.values(u.definition.nodes).some(I=>I.kind==="cc"))}]:[],...e.workflows.definitions.some(u=>u.definition.taskPages!==void 0)?["workflow.task-page-submit","workflow.task-private-drafts"].map(u=>({code:u,declaration:e.workflows.definitions.filter(I=>I.definition.taskPages!==void 0)})):[],...f.length?[{code:"workflow.task-managed-files",declaration:f}]:[],...m.length?[{code:"workflow.task-owned-files",declaration:m}]:[],...p.length?[{code:"workflow.task-rich-fields",declaration:p}]:[],...e.workflows.definitions.some(u=>Object.values(u.definition.taskPages||{}).some(I=>I.fields.some(R=>R.subtable)))?[{code:"workflow.task-owned-subtables",declaration:e.workflows.definitions.filter(u=>Object.values(u.definition.taskPages||{}).some(I=>I.fields.some(R=>R.subtable)))}]:[],...e.workflows.definitions.some(u=>Object.values(u.definition.nodes).some(I=>I.kind==="action"&&!te(I)))?[{code:"workflow.durable-business-step",declaration:e.workflows.definitions.filter(u=>Object.values(u.definition.nodes).some(I=>I.kind==="action"&&!te(I)))}]:[],...e.workflows.definitions.some(u=>Object.values(u.definition.nodes).some(I=>I.kind==="action"&&I.handler.dataTransaction))?[{code:"workflow.step-data-transaction",declaration:e.workflows.definitions.filter(u=>Object.values(u.definition.nodes).some(I=>I.kind==="action"&&I.handler.dataTransaction))}]:[],...e.workflows.bindings.some(u=>Object.values(u.binding.bindings).some(I=>I.routing!==void 0))?[{code:"workflow.assignment-routing",declaration:e.workflows.bindings.filter(u=>Object.values(u.binding.bindings).some(I=>I.routing!==void 0))}]:[],...A?[{code:"business-process.durable-command",declaration:{operations:n.filter(u=>u.platformAccess?.workflow).map(u=>({code:u.code,workflow:u.platformAccess.workflow})),definitions:E,activations:e.workflows.activations.filter(u=>E.some(I=>I.definition.code===u.workflowCode))}}]:[],...n.some(u=>u.platformAccess?.dataMutations)||e.events.subscriptions.some(u=>u.platformAccess?.dataMutations)?[{code:"data.service-mutations",declaration:{operations:n.filter(u=>u.platformAccess?.dataMutations).map(u=>({code:u.code,grants:u.platformAccess.dataMutations})),subscriptions:e.events.subscriptions.filter(u=>u.platformAccess?.dataMutations).map(u=>({code:u.code,grants:u.platformAccess.dataMutations}))}}]:[],...c?[{code:"notification-hub-v2",declaration:{...e.workflows.definitions.some(u=>u.definition.rejectionNotification!==void 0)?{rejectionNotifications:e.workflows.definitions.filter(u=>u.definition.rejectionNotification!==void 0)}:{},operations:n.filter(u=>u.platformAccess?.notification).map(u=>({code:u.code,notification:u.platformAccess.notification})),subscriptions:e.events.subscriptions.filter(u=>u.platformAccess?.notification).map(u=>({code:u.code,notification:u.platformAccess.notification}))}}]:[],...e.frontend.authentication?[{code:"authentication.application-login-surface",declaration:e.frontend.authentication}]:[],...e.frontend.publicAccess?[{code:"public-access.anonymous-owner-records",declaration:e.frontend.publicAccess}]:[]].map(({code:u,declaration:I})=>({code:u,contractVersion:u==="data.unique-keys"?o.some(R=>xi(R.schema.fields,R.uniqueKeys)==="1.1.0")?"1.1.0":"1.0.0":ws[u],usageDigest:`sha256:${ee(I)}`})).sort((u,I)=>u.code===I.code?0:u.code<I.code?-1:1)}function hc(e){let t=new Map,o=new Set(e.resources.map(i=>String(i.code)));for(let[i,a]of k(e.capturePolicies===void 0?[]:e.capturePolicies,"/capturePlan/capturePolicies",100).entries()){let s=`/capturePlan/capturePolicies/${i}`,d=N(a,s);T(d,["resourceCode","mode"],s);let c=Y(d.resourceCode,`${s}/resourceCode`);o.has(c)||_("NATIVE_EVENT_CAPTURE_RESOURCE_NOT_FOUND",s,{resourceCode:c}),t.has(c)&&_("NATIVE_EVENT_CAPTURE_POLICY_DUPLICATE",s,{resourceCode:c}),d.mode!=="all"&&d.mode!=="subscribed"&&_("NATIVE_EVENT_CAPTURE_MODE_INVALID",`${s}/mode`),t.set(c,d.mode)}let n=new Map(e.dataPolicies.map((i,a)=>{let s=N(i,`/capturePlan/dataPolicies/${a}`);return[String(s.code),s]})),r=e.subscriptions.map((i,a)=>N(i,`/capturePlan/subscriptions/${a}`));return e.resources.map((i,a)=>{let s=`/capturePlan/resources/${a}`,d=N(i,s),c=Y(d.code,`${s}/code`),l=d.schema?N(d.schema,`${s}/schema`):d,f=new Set(k(l.fields||[],`${s}/schema/fields`,500).map((I,R)=>G(N(I,`${s}/schema/fields/${R}`).code,`${s}/schema/fields/${R}/code`))),p=d.dataPolicyCode?v(d.dataPolicyCode,`${s}/dataPolicyCode`):null,m=p?n.get(p):void 0;p&&!m&&_("NATIVE_EVENT_CAPTURE_AUTHZ_POLICY_NOT_FOUND",s,{resourceCode:c,dataPolicyCode:p});let E=new Set;for(let I of m?.rules||[])E.add(I.parentRead?bn(e.resources,c,I.parentRead,`${s}/parentRead`).foreignKey:String(I.field));if(m?.readExpression)for(let I of gt(m.readExpression,`${s}/readExpression`))E.add(I.rule.parentRead?bn(e.resources,c,I.rule.parentRead,`${s}/parentRead`).foreignKey:String(I.rule.field));let A=new Set,b=new Set,O=new Set;for(let[I,R]of r.entries()){let w=k(R.eventTypes,`/capturePlan/subscriptions/${I}/eventTypes`,20).map(String);if(!w.some(V=>V.startsWith("openxiangda.data.")))continue;let C=N(R.filter||{},`/capturePlan/subscriptions/${I}/filter`),S=Array.isArray(C.resourceCodes)?C.resourceCodes.map(String):[];if(S.length&&!S.includes(c))continue;for(let V of w)_r.includes(V)&&O.add(V);for(let V of Rc(C,`/capturePlan/subscriptions/${I}/filter`))A.add(V);let P=N(R.payload||{},`/capturePlan/subscriptions/${I}/payload`);for(let V of k(P.fields||[],`/capturePlan/subscriptions/${I}/payload/fields`,32))b.add(G(V,`/capturePlan/subscriptions/${I}/payload/fields`))}let g=new Set([...A,...b]),y=new Set([...g,...E]);y.size>ks&&_("NATIVE_EVENT_CAPTURE_FIELDS_LIMIT",s,{resourceCode:c,maximum:ks});for(let I of y)!f.has(I)&&!(E.has(I)&&Js.has(I))&&_("NATIVE_EVENT_CAPTURE_FIELD_NOT_FOUND",s,{resourceCode:c,field:I});let h=N(d.fieldPolicies||{},`${s}/fieldPolicies`);for(let I of g)h[I]?.mask==="omit"&&_("NATIVE_EVENT_CAPTURE_FIELD_SENSITIVE",s,{resourceCode:c,field:I});let u={resourceCode:c,...t.get(c)==="subscribed"?{capturedEventTypes:[...O].sort()}:{},filterFields:[...A].sort(),projectionFields:[...b].sort(),authorizationFields:[...E].sort(),captureFields:[...y].sort()};return{...u,digest:ee(u)}}).sort((i,a)=>i.resourceCode.localeCompare(a.resourceCode))}function Rc(e,t){let o=new Set;for(let[a,s]of k(e.changes||[],`${t}/changes`,16).entries()){let d=N(s,`${t}/changes/${a}`);o.add(G(d.field,`${t}/changes/${a}/field`))}let n=N(e.changedFields||{},`${t}/changedFields`);for(let a of["anyOf","allOf","noneOf"])for(let[s,d]of k(n[a]||[],`${t}/changedFields/${a}`,32).entries())o.add(G(d,`${t}/changedFields/${a}/${s}`));let r=0,i=(a,s,d)=>{d>3&&_("NATIVE_EVENT_FILTER_DEPTH_LIMIT",s);let c=N(a,s);if(c.change){let f=N(c.change,`${s}/change`);o.add(G(f.field,`${s}/change/field`)),r+=1;return}if(c.not){i(c.not,`${s}/not`,d+1);return}let l=c.all?"all":c.any?"any":null;l||_("NATIVE_EVENT_FILTER_CONDITION_INVALID",s);for(let[f,p]of k(c[l],`${s}/${l}`,16).entries())i(p,`${s}/${l}/${f}`,d+1)};return e.where&&i(e.where,`${t}/where`,1),r+=Array.isArray(e.changes)?e.changes.length:0,r>16&&_("NATIVE_EVENT_FILTER_ATOM_LIMIT",t),[...o].sort()}function wc(e,t){T(e,["schemaVersion","compilerContractVersion","appCode","perspectives","authz","backend","data","events","workflows","frontend","runtime"],"/config"),W(e.schemaVersion,ec,"/config/schemaVersion"),W(e.compilerContractVersion,Jt,"/config/compilerContractVersion"),W(e.appCode,t,"/config/appCode"),k(e.perspectives,"/config/perspectives",100);let o=N(e.authz,"/config/authz");T(o,["capabilities","roles","scopeDimensions","scopeSources","roleMembershipSources","relationshipGrantSources","dataPolicies","authorizationTransitions"],"/config/authz",["authenticatedUserRoleCode"]),k(o.capabilities,"/config/authz/capabilities",B.capabilities),k(o.roles,"/config/authz/roles",B.roles),k(o.scopeDimensions,"/config/authz/scopeDimensions",100),k(o.scopeSources,"/config/authz/scopeSources",100),k(o.roleMembershipSources,"/config/authz/roleMembershipSources",100),k(o.relationshipGrantSources,"/config/authz/relationshipGrantSources",100),k(o.dataPolicies,"/config/authz/dataPolicies",B.dataPolicies),k(o.authorizationTransitions,"/config/authz/authorizationTransitions",100);let n=N(e.backend,"/config/backend");T(n,["secrets","operations"],"/config/backend"),k(n.secrets,"/config/backend/secrets",100),k(n.operations,"/config/backend/operations",500),dl(n.secrets);let r=N(e.data,"/config/data");T(r,["resources"],"/config/data",["resourceDetailRoutes","subjectReadSurfaces","concurrency"]),k(r.resources,"/config/data/resources",B.resources),r.subjectReadSurfaces!==void 0&&k(r.subjectReadSurfaces,"/config/data/subjectReadSurfaces",B.subjectReadSurfaces),r.resourceDetailRoutes!==void 0&&k(r.resourceDetailRoutes,"/config/data/resourceDetailRoutes",100);let i=N(e.events,"/config/events");T(i,["schemas","subscriptions","timers","dateTriggers"],"/config/events",["capturePolicies"]),k(i.schemas,"/config/events/schemas",100),k(i.subscriptions,"/config/events/subscriptions",100),k(i.timers,"/config/events/timers",100),k(i.dateTriggers,"/config/events/dateTriggers",100);let a=N(e.workflows,"/config/workflows");T(a,["definitions","bindings","activations","providers","editableParameters"],"/config/workflows"),k(a.definitions,"/config/workflows/definitions",B.workflows),k(a.bindings,"/config/workflows/bindings",B.workflows),k(a.activations,"/config/workflows/activations",B.workflows),k(a.providers,"/config/workflows/providers",100),k(a.editableParameters,"/config/workflows/editableParameters",100);let s=N(e.frontend,"/config/frontend");T(s,["routes","user","admin","devicePolicy"],"/config/frontend",["authentication","publicAccess"]),k(s.routes,"/config/frontend/routes",B.routes);let d=N(s.user,"/config/frontend/user");T(d,["applicationTodoCenter"],"/config/frontend/user"),ht(d.applicationTodoCenter,"/config/frontend/user/applicationTodoCenter"),yr(s.devicePolicy,"/config/frontend/devicePolicy"),Object.prototype.hasOwnProperty.call(s,"authentication")&&Ys(s.authentication,s.routes,e,"/config/frontend/authentication"),Object.prototype.hasOwnProperty.call(s,"publicAccess")&&Bc(s.publicAccess,e,"/config/frontend/publicAccess");let c=N(s.admin,"/config/frontend/admin");T(c,["navigation"],"/config/frontend/admin",["access"]),c.access!==void 0&&Kn(c.access,"/config/frontend/admin/access",e.appCode),zc(c.navigation,"/config/frontend/admin/navigation");let l=N(e.runtime,"/config/runtime");T(l,["protocolCapabilities","health"],"/config/runtime"),F(l.protocolCapabilities,"/config/runtime/protocolCapabilities",100),T(N(l.health,"/config/runtime/health"),["livePath","readyPath","versionPath"],"/config/runtime/health"),W(l.health.livePath,"/__platform/health","/config/runtime/health/livePath"),W(l.health.readyPath,"/__platform/ready","/config/runtime/health/readyPath"),W(l.health.versionPath,"/__platform/version","/config/runtime/health/versionPath")}function Tc(e,t,o){T(e,["schemaVersion","compilerContractVersion","generatorVersion","appCode","configDigest","perspectives","resources","capabilities","operations","eventConsumers","eventProducers","eventSchemas","eventHandlerManifest","eventTypes","workflows","routes","routeManifest","adminPages","adminNavigation"],"/contracts",["authentication","publicAccess","adminAccess","subjectReadSurfaces","concurrency"]),W(e.schemaVersion,qs,"/contracts/schemaVersion"),W(e.compilerContractVersion,Jt,"/contracts/compilerContractVersion"),D(e.generatorVersion,"/contracts/generatorVersion",128),W(e.appCode,t,"/contracts/appCode"),W(e.configDigest,o,"/contracts/configDigest"),k(e.perspectives,"/contracts/perspectives",B.perspectives),k(e.resources,"/contracts/resources",B.resources),e.subjectReadSurfaces!==void 0&&k(e.subjectReadSurfaces,"/contracts/subjectReadSurfaces",B.subjectReadSurfaces),k(e.capabilities,"/contracts/capabilities",B.capabilities),k(e.operations,"/contracts/operations",B.operations),k(e.eventConsumers,"/contracts/eventConsumers",B.eventConsumers),k(e.eventProducers,"/contracts/eventProducers",B.eventProducers),k(e.eventSchemas,"/contracts/eventSchemas",B.eventSchemas),N(e.eventHandlerManifest,"/contracts/eventHandlerManifest"),F(e.eventTypes,"/contracts/eventTypes",B.eventTypes),k(e.workflows,"/contracts/workflows",B.workflows),k(e.routes,"/contracts/routes",B.routes),Object.prototype.hasOwnProperty.call(e,"authentication")&&jc(e.authentication,"/contracts/authentication"),Object.prototype.hasOwnProperty.call(e,"publicAccess")&&Kc(e.publicAccess,"/contracts/publicAccess"),Object.prototype.hasOwnProperty.call(e,"adminAccess")&&Kn(e.adminAccess,"/contracts/adminAccess",t),Qc(e.routeManifest,"/contracts/routeManifest",t),Yc(e.adminPages,"/contracts/adminPages"),Xc(e.adminNavigation,"/contracts/adminNavigation")}function Cc(e,t,o){let n=kc(e);rl(e,n),sl(e),il(e),cl(e);let r=e.events.schemas.map((g,y)=>{let h=`/config/events/schemas/${y}`,u=N(g,h),I=D(u.eventType,`${h}/eventType`,255);return I.startsWith("openxiangda.")&&_("NATIVE_EVENT_SCHEMA_RESERVED",`${h}/eventType`,{eventType:I}),W(u.schemaDigest,ee(N(u.jsonSchema,`${h}/jsonSchema`)),`${h}/schemaDigest`),u}),i=new Set([..._r,...zt,...r.map(g=>String(g.eventType))]),a=new Map(e.data.resources.map(g=>[String(g.code),new Map(g.schema.fields.map(y=>[String(y.code),String(y.type)]))])),s=ne(e.events.subscriptions.map((g,y)=>{let h=`/config/events/subscriptions/${y}`,u=N(g,h),I=F(u.eventTypes,`${h}/eventTypes`,20);I.forEach((S,P)=>{i.has(S)||_("NATIVE_EVENT_TYPE_NOT_REGISTERED",`${h}/eventTypes/${P}`,{eventType:S})});let R=Bi(u,e.data.resources,h),w=Dc(u.delivery,I,`${h}/delivery`),C=Sc(u.platformAccess,`${h}/platformAccess`,a,e,u);return{code:v(u.code,`${h}/code`),endpointPath:Re(u.endpointPath,`${h}/endpointPath`),eventTypes:I,filter:N(u.filter,`${h}/filter`),payload:R?.payload||N(u.payload,`${h}/payload`),...R?{execution:R.execution}:{},...C?{platformAccess:C}:{},delivery:w}}),g=>g.code),d=new Map(r.map(g=>[String(g.eventType),String(g.dataSchemaVersion)])),c=ne([...e.data.resources.flatMap(g=>_r.map(y=>({code:`data:${g.code}:${y}`,source:"data",eventType:y,dataSchemaVersion:"2.0.0",resourceCode:g.code}))),...r.map(g=>({code:`app:${g.eventType}`,source:"app",eventType:g.eventType,dataSchemaVersion:g.dataSchemaVersion})),...e.events.timers.map(g=>({code:g.code,source:"timer",eventType:g.eventType,dataSchemaVersion:d.get(String(g.eventType))||"2.0.0"})),...e.events.dateTriggers.map(g=>({code:g.code,source:"date",eventType:g.eventType,dataSchemaVersion:d.get(String(g.eventType))||"2.0.0",resourceCode:g.resourceCode,field:g.field})),...e.workflows.activations.length?fr(e.workflows.definitions).map(g=>({code:`workflow:${g}`,source:"workflow",eventType:g,dataSchemaVersion:"2.0.0"})):[]],g=>`${g.source}:${g.code}:${g.eventType}`),l=U([...s.flatMap(g=>g.eventTypes),...c.map(g=>String(g.eventType))]);Hc(e);let f=Qs(e),p;try{p=ai(e.data.concurrency,e.data.resources,n)}catch(g){throw g instanceof Dt&&_(g.code,g.pointer,{reason:g.reason}),g}p?.commands.some(g=>g.mode==="durable")&&e.backend?.enabled===!1&&_("NATIVE_MANAGED_CONCURRENCY_INVALID","/data/concurrency",{reason:"durable commands require backend runtime"});let m=$c(e,n),E=Hs(e),A=e.workflows.definitions.map(g=>g.definition),b=Mo(A),O=bi(A,s,!0);O.length&&_(O[0],"/config/events/subscriptions");try{ci(e.data.resources,E)}catch(g){throw g instanceof pt&&_(g.code,g.pointer,{reason:g.reason}),g}return{schemaVersion:qs,compilerContractVersion:Jt,generatorVersion:o,appCode:e.appCode,configDigest:t,perspectives:e.perspectives,resources:Lc(e),...m.length?{subjectReadSurfaces:m}:{},...p?{concurrency:p}:{},capabilities:ne(n,g=>g.code),operations:E,eventConsumers:s,eventProducers:c,eventSchemas:r,eventHandlerManifest:{schemaVersion:Oc,appCode:e.appCode,handlers:s.filter(g=>!g.execution).map(g=>({code:g.code,endpointPath:g.endpointPath,eventTypes:g.eventTypes,dataSchemaVersions:U(g.eventTypes.map(y=>y.startsWith("openxiangda.")?"2.0.0":d.get(y)||"2.0.0")),maxBodyBytes:65536,receiptProtocolVersion:2,...b[g.code]?{workflowStep:b[g.code]}:{}}))},eventTypes:l,workflows:na(e),routes:Bn(e),...Object.prototype.hasOwnProperty.call(e.frontend,"authentication")?{authentication:Mc(e)}:{},...Object.prototype.hasOwnProperty.call(e.frontend,"publicAccess")?{publicAccess:Gc(e)}:{},...e.frontend.admin.access?{adminAccess:e.frontend.admin.access}:{},routeManifest:nl(e),adminPages:f,adminNavigation:qc(e)}}function Sc(e,t,o,n,r){if(e===void 0)return;let i=N(e,t);T(i,["notification","managedFileCopies","decimalReservation","dataMutations"],t,!0);let a={};if(i.dataMutations!==void 0)try{a.dataMutations=Ko(i.dataMutations,o)}catch{_("NATIVE_EVENT_DATA_MUTATIONS_INVALID",`${t}/dataMutations`)}if(i.decimalReservation!==void 0)try{a.decimalReservation=Mi(i.decimalReservation,Ui(n,r))}catch{_("NATIVE_EVENT_DECIMAL_RESERVATION_INVALID",`${t}/decimalReservation`)}if(i.notification!==void 0){let s=N(i.notification,`${t}/notification`);T(s,["mode"],`${t}/notification`),W(s.mode,"business-standard",`${t}/notification/mode`),a.notification={mode:"business-standard"}}if(i.managedFileCopies!==void 0){let s=k(i.managedFileCopies,`${t}/managedFileCopies`,16);s.length||_("NATIVE_EVENT_MANAGED_FILE_COPIES_REQUIRED",`${t}/managedFileCopies`);let d=new Set;a.managedFileCopies=ne(s.map((c,l)=>{let f=`${t}/managedFileCopies/${l}`,p=N(c,f);T(p,["mode","sourceResourceCode","sourceFieldCodes","targetResourceCode","targetFieldCodes"],f),W(p.mode,"copy",`${f}/mode`);let m=Y(p.sourceResourceCode,`${f}/sourceResourceCode`),E=Y(p.targetResourceCode,`${f}/targetResourceCode`),A=o.get(m),b=o.get(E);(!A||!b)&&_("NATIVE_EVENT_MANAGED_FILE_COPY_RESOURCE_INVALID",f);let O=F(p.sourceFieldCodes,`${f}/sourceFieldCodes`,16),g=F(p.targetFieldCodes,`${f}/targetFieldCodes`,16);(!O.length||O.length!==g.length)&&_("NATIVE_EVENT_MANAGED_FILE_COPY_FIELDS_INVALID",f),O.forEach((h,u)=>{let I=A.get(h),R=b.get(g[u]);(!["file","image","text.rich"].includes(String(I))||I!==R)&&_("NATIVE_EVENT_MANAGED_FILE_COPY_FIELD_INVALID",`${f}/sourceFieldCodes/${u}`)});let y=`${m}:${O.join(",")}=>${E}:${g.join(",")}`;return d.has(y)&&_("NATIVE_EVENT_MANAGED_FILE_COPY_DUPLICATE",f),d.add(y),{mode:"copy",sourceResourceCode:m,sourceFieldCodes:U(O),targetResourceCode:E,targetFieldCodes:U(g)}}),c=>`${c.sourceResourceCode}:${c.sourceFieldCodes.join(",")}=>${c.targetResourceCode}:${c.targetFieldCodes.join(",")}`)}return Object.keys(a).length||_("NATIVE_EVENT_PLATFORM_ACCESS_EMPTY",t),a}function Dc(e,t,o){let n=N(e,o);T(n,["timeoutMs","maxAttempts","initialBackoffMs","maxBackoffMs","ordering","concurrency"],o),ae(n.timeoutMs,`${o}/timeoutMs`,1e3,3e4),ae(n.maxAttempts,`${o}/maxAttempts`,1,12);let r=ae(n.initialBackoffMs,`${o}/initialBackoffMs`,1e3,3e5);ae(n.maxBackoffMs,`${o}/maxBackoffMs`,r,18e5),ae(n.concurrency,`${o}/concurrency`,1,50);let i=D(n.ordering,`${o}/ordering`,32);return["none","record","workflow-instance"].includes(i)||_("NATIVE_EVENT_DELIVERY_ORDERING_INVALID",`${o}/ordering`),i==="workflow-instance"&&t.some(a=>!bc.has(a))&&_("NATIVE_EVENT_WORKFLOW_ORDERING_REQUIRES_WORKFLOW_FACTS",`${o}/ordering`),n}function kc(e){let t=new Map;for(let i of ia(e.appCode))t.set(i.code,i);for(let[i,a]of e.authz.capabilities.entries()){let s=`/config/authz/capabilities/${i}`,d=N(a,s);T(d,["code","kind","name","description"],s,!0);let c=ge(d.code,`${s}/code`,e.appCode);t.has(c)&&_("NATIVE_CAPABILITY_DUPLICATE",`${s}/code`),["backend","ui"].includes(d.kind)||_("NATIVE_CAPABILITY_KIND_INVALID",`${s}/kind`);let l={code:c,kind:d.kind,name:D(d.name,`${s}/name`,255),source:"explicit",...d.description===void 0?{}:{description:br(d.description,`${s}/description`,2e3)}};t.set(c,l)}let o=e.data.resources.map((i,a)=>({pointer:`/config/data/resources/${a}`,resource:nt(i,`/config/data/resources/${a}`,e.appCode)}));for(let{pointer:i,resource:a}of o){let s={read:`\u8BFB\u53D6${a.name}`,create:`\u65B0\u5EFA${a.name}`,update:`\u66F4\u65B0${a.name}`,delete:`\u5220\u9664${a.name}`};for(let d of["read","create","update","delete"]){let c=ge(a.capabilities[d],`${i}/capabilities/${d}`,e.appCode);t.has(c)&&_("NATIVE_CAPABILITY_DUPLICATE",`${i}/capabilities/${d}`),t.set(c,{code:c,kind:"data",name:s[d],source:"data"})}}let n=new Set(t.keys()),r=new Map;for(let{pointer:i,resource:a}of o)for(let[s,d]of Object.entries(a.fieldPolicies)){if(Tt(s))continue;let c=N(d,`${i}/fieldPolicies/${s}`);for(let l of["read","create","update"])if(Array.isArray(c[l]))for(let f of F(c[l],`${i}/fieldPolicies/${s}/${l}`,2e3)){if(ge(f,`${i}/fieldPolicies/${s}/${l}`,e.appCode),n.has(f))continue;let p=r.get(f);p&&p!==a.code&&_("NATIVE_CAPABILITY_DUPLICATE",`${i}/fieldPolicies/${s}/${l}`),r.set(f,a.code),!t.has(f)&&t.set(f,{code:f,kind:"data",name:`${a.name}.${s}.${l}`,source:"data"})}}return[...t.values()]}function Lc(e){let t=Pc(e);return ne(e.data.resources.map((o,n)=>{let r=nt(o,`/config/data/resources/${n}`,e.appCode),i=t.get(r.code);return{code:r.code,schemaDigest:ee(r.schema),fields:ne(r.schema.fields.map(a=>({code:a.code,type:a.type})),a=>a.code),...i?{detailRouteCode:i}:{}}}),o=>o.code)}function $c(e,t){if(e.data.subjectReadSurfaces===void 0)return[];let o=k(e.data.subjectReadSurfaces,"/config/data/subjectReadSurfaces",B.subjectReadSurfaces),n=new Set(t.map(a=>String(a.code))),r=new Map(e.data.resources.map((a,s)=>{let d=`/config/data/resources/${s}`,c=nt(a,d,e.appCode);return[String(c.code),{resource:c,fields:new Map(k(N(c.schema,`${d}/schema`).fields,`${d}/schema/fields`,500).map(l=>{let f=N(l,`${d}/schema/fields`);return[String(f.code),f]}))}]})),i=new Set;return ne(o.map((a,s)=>{let d=`/config/data/subjectReadSurfaces/${s}`,c=N(a,d);T(c,["code","name","capability","subject","relations"],d);let l=v(c.code,`${d}/code`);i.has(l)&&_("NATIVE_SUBJECT_READ_SURFACE_CODE_DUPLICATE",`${d}/code`),i.add(l);let f=ge(c.capability,`${d}/capability`,e.appCode);n.has(f)||_("NATIVE_SUBJECT_READ_SURFACE_CAPABILITY_NOT_DECLARED",`${d}/capability`);let p=N(c.subject,`${d}/subject`);T(p,["resourceCode","fields"],`${d}/subject`);let m=Y(p.resourceCode,`${d}/subject/resourceCode`),E=r.get(m);E||_("NATIVE_SUBJECT_READ_SURFACE_RESOURCE_NOT_DECLARED",`${d}/subject/resourceCode`);let A=F(p.fields,`${d}/subject/fields`,100).map((h,u)=>G(h,`${d}/subject/fields/${u}`));A.length||_("NATIVE_SUBJECT_READ_SURFACE_FIELDS_REQUIRED",`${d}/subject/fields`);for(let[h,u]of A.entries()){let I=E.fields.get(u);(!I||I.type==="subtable")&&_("NATIVE_SUBJECT_READ_SURFACE_FIELD_INVALID",`${d}/subject/fields/${h}`)}let b=k(c.relations,`${d}/relations`,8);b.length||_("NATIVE_SUBJECT_READ_SURFACE_RELATIONS_REQUIRED",`${d}/relations`);let O=new Set,g=0,y=ne(b.map((h,u)=>{let I=`${d}/relations/${u}`,R=N(h,I);T(R,["code","resourceCode","foreignKeyField","fields","limit"],I,["order"]);let w=v(R.code,`${I}/code`);O.has(w)&&_("NATIVE_SUBJECT_READ_SURFACE_RELATION_CODE_DUPLICATE",`${I}/code`),O.add(w);let C=Y(R.resourceCode,`${I}/resourceCode`),S=r.get(C);S||_("NATIVE_SUBJECT_READ_SURFACE_RESOURCE_NOT_DECLARED",`${I}/resourceCode`);let P=G(R.foreignKeyField,`${I}/foreignKeyField`),V=S.fields.get(P),q=N(V?.source||{},`${I}/foreignKeyField/source`);(!V||!["uuid","resource-ref.single"].includes(String(V.type))||V.type==="resource-ref.single"&&(q.kind!=="resource"||q.resourceCode!==m))&&_("NATIVE_SUBJECT_READ_SURFACE_RELATION_INVALID",`${I}/foreignKeyField`);let Z=F(R.fields,`${I}/fields`,100).map((re,$)=>G(re,`${I}/fields/${$}`));Z.length||_("NATIVE_SUBJECT_READ_SURFACE_FIELDS_REQUIRED",`${I}/fields`);for(let[re,$]of Z.entries()){let M=S.fields.get($);(!M||M.type==="subtable")&&_("NATIVE_SUBJECT_READ_SURFACE_FIELD_INVALID",`${I}/fields/${re}`)}let X=k(R.order||[],`${I}/order`,10).map((re,$)=>{let M=`${I}/order/${$}`,x=N(re,M);T(x,["field","direction"],M);let z=G(x.field,`${M}/field`),J=S.fields.get(z);return(!Js.has(z)&&!J||J?.type==="subtable"||J&&!St(J.type))&&_("NATIVE_SUBJECT_READ_SURFACE_ORDER_FIELD_INVALID",`${M}/field`),["asc","desc"].includes(String(x.direction))||_("NATIVE_SUBJECT_READ_SURFACE_ORDER_DIRECTION_INVALID",`${M}/direction`),{field:z,direction:x.direction}}),Ie=ae(R.limit,`${I}/limit`,1,100);return g+=Ie,{code:w,resourceCode:C,foreignKeyField:P,fields:U(Z),...X.length?{order:X}:{},limit:Ie}}),h=>h.code);return g>400&&_("NATIVE_SUBJECT_READ_SURFACE_ROW_LIMIT_EXCEEDED",`${d}/relations`),{code:l,name:D(c.name,`${d}/name`,255),capability:f,subject:{resourceCode:m,fields:U(A)},relations:y}}),a=>a.code)}function Pc(e){let t=e.data.resourceDetailRoutes===void 0?[]:k(e.data.resourceDetailRoutes,"/config/data/resourceDetailRoutes",100),o=new Map(e.data.resources.map((i,a)=>{let s=`/config/data/resources/${a}`,d=nt(i,s,e.appCode);return[d.code,d]})),n=new Map(Bn(e).map(i=>[String(i.code),i])),r=new Map;for(let[i,a]of t.entries()){let s=`/config/data/resourceDetailRoutes/${i}`,d=N(a,s);T(d,["resourceCode","desktop","mobile"],s);let c=Y(d.resourceCode,`${s}/resourceCode`);r.has(c)&&_("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_DUPLICATE",`${s}/resourceCode`);let l=o.get(c);l||_("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_RESOURCE_MISSING",`${s}/resourceCode`);let f=v(d.desktop,`${s}/desktop`),p=v(d.mobile,`${s}/mobile`);f===p&&_("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_INVALID",s);let m=String(l.capabilities.read);for(let[E,A]of[["desktop",f],["mobile",p]]){let b=`${s}/${E}`,O=n.get(A);O||_("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_REFERENCE_MISSING",b),O.surface!=="user"&&_("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_SURFACE_INVALID",b);let g=Re(O.path,`${b}/path`),y=[...g.matchAll(/:([A-Za-z][A-Za-z0-9_]*)/g)],h=E==="mobile"?!g.startsWith("/m/"):g==="/m"||g.startsWith("/m/");(g.includes("*")||g.includes("?")||g.includes("#")||g.split("/").includes("..")||y.length!==1||h)&&_("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_PATH_INVALID",b);let u=Array.isArray(O.access?.allOf)?O.access.allOf:[];O.capability!==m&&!u.includes(m)&&_("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_CAPABILITY_INVALID",b)}r.set(c,{desktop:f,mobile:p})}return r}function Hs(e){let t=new Map(e.data.resources.map((a,s)=>{let d=`/config/data/resources/${s}`,c=nt(a,d,e.appCode);return[c.code,new Map(c.schema.fields.map(l=>[String(l.code),l]))]})),o=new Map(e.data.resources.map((a,s)=>{let d=`/config/data/resources/${s}`,c=nt(a,d,e.appCode);return[c.code,new Map(c.schema.fields.map(l=>[String(l.code),String(l.type)]))]})),n=new Set(o.keys()),r=new Set(e.workflows.activations.map((a,s)=>Gn(N(a,`/config/workflows/activations/${s}`).workflowCode,`/config/workflows/activations/${s}/workflowCode`))),i=new Map;return ne(e.backend.operations.map((a,s)=>{let d=`/config/backend/operations/${s}`,c=N(a,d);T(c,["code","method","path","capability","requestSchema","responseSchema","description","platformAccess","browser","ai"],d,!0);let l=D(c.method,`${d}/method`,16);["GET","POST","PUT","PATCH","DELETE"].includes(l)||_("NATIVE_OPERATION_METHOD_INVALID",`${d}/method`);let f=v(c.code,`${d}/code`);Wc(c.ai,d,f,l,n);let p=Fc(c.platformAccess,`${d}/platformAccess`,o,t,r,new Set(e.authz.roles.map(E=>String(E.code))));if(p?.workflowStage){let E=p.workflowStage,A=e.workflows.definitions.find(b=>b.definition.code===E.workflowCode);(!A||A.definition.subject?.resourceCode!==E.resourceCode||E.runningNodeIds.some(b=>!A.definition.nodes[b]))&&_("NATIVE_WORKFLOW_STAGE_NODE_INVALID",`${d}/platformAccess/workflowStage/runningNodeIds`)}if(p?.recordEdit){let E=e.data.resources.find(A=>A.code===p.recordEdit.resourceCode);E?.surface?.mutationOwner!=="action"&&_("NATIVE_RECORD_EDIT_ACTION_OWNER_REQUIRED",`${d}/platformAccess/recordEdit`);for(let A of p.recordEdit.fieldCodes)(!E.fieldPolicies?.[A]?.update?.length||E.surface?.fields?.[A]?.system===!0)&&_("NATIVE_RECORD_EDIT_FIELD_INVALID",`${d}/platformAccess/recordEdit/fieldCodes`)}if(p?.decimalReservation){let E=p.decimalReservation,A=String(E.resourceCode),b=JSON.stringify([E.amountFieldCode,E.currencyFieldCode,E.relationFieldCode,E.parentFieldCode,E.rootFieldCode,E.statusFieldCode,E.parentRelationValue,E.childRelationValue]),O=i.get(A);O&&O!==b&&_("NATIVE_DECIMAL_RESERVATION_MAPPING_CONFLICT",`${d}/platformAccess/decimalReservation`),i.set(A,b)}let m=vc(c.browser,`${d}/browser`,l,c.requestSchema,c.responseSchema,o,t,e.data.subjectReadSurfaces||[]);return{code:f,method:l,path:Re(c.path,`${d}/path`),requiredCapability:ge(c.capability,`${d}/capability`,e.appCode),requestSchemaDigest:ee(N(c.requestSchema,`${d}/requestSchema`)),responseSchemaDigest:ee(N(c.responseSchema,`${d}/responseSchema`)),...c.description===void 0?{}:{description:br(c.description,`${d}/description`,2e3)},...p?{platformAccess:p}:{},...m?{browser:m}:{}}}),a=>a.code)}function vc(e,t,o,n,r,i,a,s){if(e===void 0)return null;let d=N(e,t);T(d,["exposure","behavior","idempotency","subject"],t,["refreshTargets","fileIntent"]),W(d.exposure,"authenticated",`${t}/exposure`);let c=D(d.behavior,`${t}/behavior`,32);["read","controlled"].includes(c)||_("NATIVE_OPERATION_BROWSER_BEHAVIOR_INVALID",`${t}/behavior`);let l=D(d.idempotency,`${t}/idempotency`,32);(!["none","required"].includes(l)||c==="controlled"&&l!=="required"||c==="read"&&l!=="none")&&_("NATIVE_OPERATION_BROWSER_IDEMPOTENCY_INVALID",`${t}/idempotency`);let f=N(d.subject,`${t}/subject`);T(f,["resourceCode","inputField"],`${t}/subject`);let p=Y(f.resourceCode,`${t}/subject/resourceCode`);i.has(p)||_("NATIVE_OPERATION_BROWSER_SUBJECT_RESOURCE_NOT_DECLARED",`${t}/subject/resourceCode`);let m=G(f.inputField,`${t}/subject/inputField`),E=N(n,`${t}/requestSchema`),A=N(r,`${t}/responseSchema`);(E.type!=="object"||E.additionalProperties!==!1||A.type!=="object"||A.additionalProperties!==!1)&&_("NATIVE_OPERATION_BROWSER_SCHEMA_ROOT_INVALID",`${t}/requestSchema`);let b=N(E.properties,`${t}/requestSchema/properties`),O=new Set(E.required===void 0?[]:F(E.required,`${t}/requestSchema/required`,200));(!(m in b)||!O.has(m))&&_("NATIVE_OPERATION_BROWSER_SUBJECT_INPUT_INVALID",`${t}/subject/inputField`);let g=N(b[m],`${t}/requestSchema/properties/${m}`);(g.type!=="string"||g.format!=="uuid")&&_("NATIVE_OPERATION_BROWSER_SUBJECT_INPUT_INVALID",`${t}/subject/inputField`);let y=new Map((Array.isArray(s)?s:[]).map((w,C)=>{let S=N(w,`/config/data/subjectReadSurfaces/${C}`);return[String(S.code),String(N(S.subject,`/config/data/subjectReadSurfaces/${C}/subject`).resourceCode)]})),h=d.refreshTargets===void 0?[]:k(d.refreshTargets,`${t}/refreshTargets`,16),u=new Set,I=ne(h.map((w,C)=>{let S=`${t}/refreshTargets/${C}`,P=N(w,S);T(P,["kind","code"],S),W(P.kind,"subject-surface",`${S}/kind`);let V=v(P.code,`${S}/code`);return(u.has(V)||!y.has(V)||y.get(V)!==p)&&_("NATIVE_OPERATION_BROWSER_REFRESH_TARGET_INVALID",`${S}/code`),u.add(V),{kind:"subject-surface",code:V}}),w=>`${w.kind}:${w.code}`),R=Vc(d.fileIntent,`${t}/fileIntent`,o,c,l,p,b,O,a);return{exposure:"authenticated",behavior:c,idempotency:l,subject:{resourceCode:p,inputField:m},...I.length?{refreshTargets:I}:{},...R?{fileIntent:R}:{}}}function Vc(e,t,o,n,r,i,a,s,d){if(e===void 0)return null;let c=N(e,t);T(c,["recordResourceCode","recordIdInputField","relationField","fileNameField","contentTypeField","sizeField","purposes","maxTtlSeconds","maxBytes"],t),(o!=="GET"||n!=="read"||r!=="none")&&_("NATIVE_OPERATION_FILE_INTENT_BEHAVIOR_INVALID",t);let l=Y(c.recordResourceCode,`${t}/recordResourceCode`),f=d.get(l);f||_("NATIVE_OPERATION_FILE_INTENT_RESOURCE_NOT_DECLARED",`${t}/recordResourceCode`);let p=G(c.recordIdInputField,`${t}/recordIdInputField`),m=N(a[p],`${t}/recordIdInputField`);(!s.has(p)||m.type!=="string"||m.format!=="uuid")&&_("NATIVE_OPERATION_FILE_INTENT_RECORD_INPUT_INVALID",`${t}/recordIdInputField`);let E=G(c.relationField,`${t}/relationField`),A=f.get(E);(!A||!["uuid","resource-ref.single"].includes(String(A.type))||String(A.type)==="resource-ref.single"&&(String(N(A.source,`${t}/relationField`).kind||"")!=="resource"||String(N(A.source,`${t}/relationField`).resourceCode||"")!==i))&&_("NATIVE_OPERATION_FILE_INTENT_RELATION_INVALID",`${t}/relationField`);let b=[["fileNameField",["text.short","text.long"]],["contentTypeField",["text.short","text.long"]],["sizeField",["number.integer"]]],O={};for(let[u,I]of b){let R=G(c[u],`${t}/${u}`);I.includes(String(f.get(R)?.type))||_("NATIVE_OPERATION_FILE_INTENT_METADATA_INVALID",`${t}/${u}`),O[u]=R}let g=ne(F(c.purposes,`${t}/purposes`,2),u=>u);(!g.length||g.some(u=>!["preview","download"].includes(u)))&&_("NATIVE_OPERATION_FILE_INTENT_PURPOSE_INVALID",`${t}/purposes`);let y=Number(c.maxTtlSeconds);(!Number.isSafeInteger(y)||y<1||y>300)&&_("NATIVE_OPERATION_FILE_INTENT_TTL_INVALID",`${t}/maxTtlSeconds`);let h=Number(c.maxBytes);return(!Number.isSafeInteger(h)||h<1||h>104857600)&&_("NATIVE_OPERATION_FILE_INTENT_SIZE_INVALID",`${t}/maxBytes`),{recordResourceCode:l,recordIdInputField:p,relationField:E,fileNameField:O.fileNameField,contentTypeField:O.contentTypeField,sizeField:O.sizeField,purposes:g,maxTtlSeconds:y,maxBytes:h}}function Fc(e,t,o,n,r,i){if(e===void 0)return null;let a=N(e,t);T(a,["directory","selectedDepartments","managedFiles","managedFileCopies","notification","workflow","roleAssertions","decimalReservation","dataCommands","recordEdit","ownedSubject","workflowStage","dataMutations"],t,!0),Object.keys(a).length===0&&_("NATIVE_OPERATION_PLATFORM_ACCESS_EMPTY",t);let s={};if(a.dataMutations!==void 0)try{s.dataMutations=Ko(a.dataMutations,n)}catch{_("NATIVE_OPERATION_DATA_MUTATIONS_INVALID",`${t}/dataMutations`)}if(a.dataCommands!==void 0){let d=N(a.dataCommands,`${t}/dataCommands`);T(d,["mode"],`${t}/dataCommands`),W(d.mode,"recoverable-native",`${t}/dataCommands/mode`),s.dataCommands={mode:"recoverable-native"}}if(a.workflowStage!==void 0){try{Pi(a.workflowStage)}catch{_("NATIVE_WORKFLOW_STAGE_DECLARATION_INVALID",`${t}/workflowStage`)}let d=a.workflowStage;(!s.dataCommands||a.decimalReservation!==void 0||!o.has(d.resourceCode)||!r.has(d.workflowCode)||!a.workflow?.codes?.includes(d.workflowCode))&&_("NATIVE_WORKFLOW_STAGE_DECLARATION_INVALID",`${t}/workflowStage`),s.workflowStage={...d,runningNodeIds:U([...d.runningNodeIds]),allowedStatuses:U([...d.allowedStatuses])}}if(a.recordEdit!==void 0){let d=`${t}/recordEdit`,c=N(a.recordEdit,d);T(c,["resourceCode","fieldCodes"],d);let l=Y(c.resourceCode,`${d}/resourceCode`),f=n.get(l),p=F(c.fieldCodes,`${d}/fieldCodes`,200);(!f||!p.length||!s.dataCommands)&&_("NATIVE_RECORD_EDIT_DECLARATION_INVALID",d);for(let m of p){let E=f.get(m);(!E||E.type==="serial-number"||E.type==="subtable")&&_("NATIVE_RECORD_EDIT_FIELD_INVALID",`${d}/fieldCodes`)}s.recordEdit={resourceCode:l,fieldCodes:U(p)}}if(a.roleAssertions!==void 0){let d=N(a.roleAssertions,`${t}/roleAssertions`);T(d,["roleCodes","actorAuthority"],`${t}/roleAssertions`,!0),d.actorAuthority!==void 0&&W(d.actorAuthority,!0,`${t}/roleAssertions/actorAuthority`);let c=F(d.roleCodes,`${t}/roleAssertions/roleCodes`,20);c.length||_("NATIVE_OPERATION_ROLE_ASSERTIONS_REQUIRED",`${t}/roleAssertions/roleCodes`),c.forEach((l,f)=>{i.has(l)||_("NATIVE_ROLE_REFERENCE_MISSING",`${t}/roleAssertions/roleCodes/${f}`)}),s.roleAssertions={roleCodes:U(c),...d.actorAuthority===!0?{actorAuthority:!0}:{}}}if(a.directory!==void 0){let d=N(a.directory,`${t}/directory`);T(d,["mode","fields"],`${t}/directory`),["current-initiator","selected-user"].includes(String(d.mode))||_("NATIVE_OPERATION_DIRECTORY_MODE_INVALID",`${t}/directory/mode`);let c=new Set(["displayName","employeeNumber","primaryDepartment","departments",...d.mode==="current-initiator"?["phone"]:[]]),l=F(d.fields,`${t}/directory/fields`,c.size);(!l.length||l.some(f=>!c.has(f)))&&_("NATIVE_OPERATION_DIRECTORY_FIELDS_INVALID",`${t}/directory/fields`),s.directory={mode:String(d.mode),fields:U(l)}}if(a.selectedDepartments!==void 0){let d=`${t}/selectedDepartments`,c=N(a.selectedDepartments,d);T(c,["fields","maxIds"],d);let l=F(c.fields,`${d}/fields`,4);(!l.includes("name")||l.some(f=>!["name","path","parent","fullPath"].includes(f))||!Number.isSafeInteger(c.maxIds)||c.maxIds<1||c.maxIds>50)&&_("NATIVE_OPERATION_SELECTED_DEPARTMENTS_INVALID",d),s.selectedDepartments={fields:U(l),maxIds:c.maxIds}}if(a.managedFiles!==void 0){let d=k(a.managedFiles,`${t}/managedFiles`,16);d.length||_("NATIVE_OPERATION_MANAGED_FILES_REQUIRED",`${t}/managedFiles`);let c=new Set;s.managedFiles=ne(d.map((l,f)=>{let p=`${t}/managedFiles/${f}`,m=N(l,p);T(m,["resourceCode","fieldCodes","intents"],p);let E=Y(m.resourceCode,`${p}/resourceCode`);(c.has(E)||!o.has(E))&&_("NATIVE_OPERATION_MANAGED_FILE_RESOURCE_INVALID",`${p}/resourceCode`),c.add(E);let A=F(m.fieldCodes,`${p}/fieldCodes`,16);(!A.length||A.some(O=>!["file","image","signature","text.rich"].includes(String(o.get(E)?.get(O)||""))))&&_("NATIVE_OPERATION_MANAGED_FILE_FIELD_INVALID",`${p}/fieldCodes`);let b=F(m.intents,`${p}/intents`,2);return(!b.length||b.some(O=>!["create","update"].includes(O)))&&_("NATIVE_OPERATION_MANAGED_FILE_INTENT_INVALID",`${p}/intents`),{resourceCode:E,fieldCodes:U(A),intents:U(b)}}),l=>l.resourceCode)}if(a.managedFileCopies!==void 0){let d=k(a.managedFileCopies,`${t}/managedFileCopies`,16);d.length||_("NATIVE_OPERATION_MANAGED_FILE_COPIES_REQUIRED",`${t}/managedFileCopies`);let c=new Set;s.managedFileCopies=ne(d.map((l,f)=>{let p=`${t}/managedFileCopies/${f}`,m=N(l,p);T(m,["mode","sourceResourceCode","sourceFieldCodes","targetResourceCode","targetFieldCodes"],p),W(m.mode,"copy",`${p}/mode`);let E=Y(m.sourceResourceCode,`${p}/sourceResourceCode`),A=Y(m.targetResourceCode,`${p}/targetResourceCode`),b=o.get(E),O=o.get(A);(!b||!O)&&_("NATIVE_OPERATION_MANAGED_FILE_COPY_RESOURCE_INVALID",p);let g=F(m.sourceFieldCodes,`${p}/sourceFieldCodes`,16),y=F(m.targetFieldCodes,`${p}/targetFieldCodes`,16);(!g.length||g.length!==y.length)&&_("NATIVE_OPERATION_MANAGED_FILE_COPY_FIELDS_INVALID",p),g.forEach((u,I)=>{let R=b.get(u),w=O.get(y[I]);(!["file","image","text.rich"].includes(String(R))||R!==w)&&_("NATIVE_OPERATION_MANAGED_FILE_COPY_FIELD_INVALID",`${p}/sourceFieldCodes/${I}`)});let h=`${E}:${g.join(",")}=>${A}:${y.join(",")}`;return c.has(h)&&_("NATIVE_OPERATION_MANAGED_FILE_COPY_DUPLICATE",p),c.add(h),{mode:"copy",sourceResourceCode:E,sourceFieldCodes:U(g),targetResourceCode:A,targetFieldCodes:U(y)}}),l=>`${l.sourceResourceCode}:${l.sourceFieldCodes.join(",")}=>${l.targetResourceCode}:${l.targetFieldCodes.join(",")}`)}if(a.notification!==void 0){let d=N(a.notification,`${t}/notification`);T(d,["mode"],`${t}/notification`),d.mode!=="business-standard"&&_("NATIVE_OPERATION_NOTIFICATION_MODE_INVALID",`${t}/notification/mode`),s.notification={mode:"business-standard"}}if(a.workflow!==void 0){let d=N(a.workflow,`${t}/workflow`);T(d,["codes"],`${t}/workflow`,["businessCommands"]);let c=F(d.codes,`${t}/workflow/codes`,16);(!c.length||c.some(f=>!r.has(f)))&&_("NATIVE_OPERATION_WORKFLOW_CODE_INVALID",`${t}/workflow/codes`);let l=d.businessCommands===void 0?void 0:F(d.businessCommands,`${t}/workflow/businessCommands`,4);l&&(!l.length||l.some(f=>!["approve","reject","withdraw","resubmit"].includes(f)))&&_("NATIVE_OPERATION_WORKFLOW_BUSINESS_COMMAND_INVALID",`${t}/workflow/businessCommands`),s.workflow={codes:U(c),...l?{businessCommands:U(l)}:{}}}if(a.ownedSubject!==void 0){let d=`${t}/ownedSubject`,c=a.ownedSubject;try{vn(c)}catch{_("NATIVE_WORKFLOW_OWNED_SUBJECT_INVALID",d)}(!s.workflow||a.decimalReservation!==void 0)&&_("NATIVE_WORKFLOW_OWNED_SUBJECT_INVALID",d);try{hs(c,n,s.managedFiles||[])}catch(l){_(`NATIVE_${l.message}`,d)}s.ownedSubject={mode:"create",resourceCode:c.resourceCode,subtables:ne(c.subtables.map(l=>({fieldCode:l.fieldCode,fieldCodes:U([...l.fieldCodes])})),l=>l.fieldCode)}}if(a.decimalReservation!==void 0){let d=`${t}/decimalReservation`,c=N(a.decimalReservation,d);T(c,["mode","resourceCode","amountFieldCode","currencyFieldCode","relationFieldCode","parentFieldCode","rootFieldCode","statusFieldCode","parentRelationValue","childRelationValue","eligibleParentStatuses","eligibleChildStatuses"],d);let l=D(c.mode,`${d}/mode`,16);["reserve","commit","release"].includes(l)||_("NATIVE_DECIMAL_RESERVATION_MODE_INVALID",`${d}/mode`);let f=Y(c.resourceCode,`${d}/resourceCode`),p=n.get(f);p||_("NATIVE_DECIMAL_RESERVATION_RESOURCE_MISSING",`${d}/resourceCode`);let E=Object.fromEntries(["amountFieldCode","currencyFieldCode","relationFieldCode","parentFieldCode","rootFieldCode","statusFieldCode"].map(u=>[u,G(c[u],`${d}/${u}`)])),A=u=>p.get(E[u]),b=u=>new Set((A(u)?.options||[]).map(I=>String(I.value))),O=v(c.parentRelationValue,`${d}/parentRelationValue`),g=v(c.childRelationValue,`${d}/childRelationValue`),y=F(c.eligibleParentStatuses,`${d}/eligibleParentStatuses`,16),h=F(c.eligibleChildStatuses,`${d}/eligibleChildStatuses`,16);(A("amountFieldCode")?.type!=="number.decimal"||A("amountFieldCode")?.exactDecimal!==!0||A("amountFieldCode")?.precision!==18||A("amountFieldCode")?.scale!==2||A("currencyFieldCode")?.type!=="option.single"||A("relationFieldCode")?.type!=="option.single"||A("parentFieldCode")?.type!=="resource-ref.single"||A("parentFieldCode")?.source?.resourceCode!==f||A("rootFieldCode")?.type!=="uuid"||A("statusFieldCode")?.type!=="option.single"||O===g||!b("relationFieldCode").has(O)||!b("relationFieldCode").has(g)||!y.length||!h.length||y.some(u=>!b("statusFieldCode").has(u))||h.some(u=>!b("statusFieldCode").has(u)))&&_("NATIVE_DECIMAL_RESERVATION_FIELD_INVALID",d),s.decimalReservation={mode:l,resourceCode:f,...E,parentRelationValue:O,childRelationValue:g,eligibleParentStatuses:U(y),eligibleChildStatuses:U(h)}}return s}function Wc(e,t,o,n,r){if(e===void 0)return;let i=`${t}/ai`,a=N(e,i);ic.test(o)||_("NATIVE_OPERATION_AI_CODE_INVALID",`${t}/code`),T(a,["name","description","risk","resources","sideEffects","concurrency","timeoutMs"],i,!0),D(a.name,`${i}/name`,mr),D(a.description,`${i}/description`,mr);let s=D(a.risk,`${i}/risk`,16);["read","write","destructive","external"].includes(s)||_("NATIVE_OPERATION_AI_RISK_INVALID",`${i}/risk`),s==="read"!=(n==="GET")&&_("NATIVE_OPERATION_AI_METHOD_RISK_MISMATCH",`${i}/risk`),n==="DELETE"&&!["destructive","external"].includes(s)&&_("NATIVE_OPERATION_AI_METHOD_RISK_MISMATCH",`${i}/risk`);let d=F(a.resources,`${i}/resources`,16);d.length===0&&_("NATIVE_OPERATION_AI_RESOURCE_REQUIRED",`${i}/resources`),d.forEach((l,f)=>{let p=Y(l,`${i}/resources/${f}`);r.has(p)||_("NATIVE_OPERATION_AI_RESOURCE_MISSING",`${i}/resources/${f}`)});let c=F(a.sideEffects,`${i}/sideEffects`,20);(s==="read"&&c.length!==0||s!=="read"&&c.length===0)&&_("NATIVE_OPERATION_AI_SIDE_EFFECT_INVALID",`${i}/sideEffects`),a.concurrency!==void 0&&!["none","revision"].includes(D(a.concurrency,`${i}/concurrency`,16))&&_("NATIVE_OPERATION_AI_CONCURRENCY_INVALID",`${i}/concurrency`),a.timeoutMs!==void 0&&ae(a.timeoutMs,`${i}/timeoutMs`,100,3e4)}function xn(e){return(e.replace(/\/{2,}/g,"/").replace(/\/$/,"")||"/").split("/").map(o=>o.startsWith(":")?":":o.includes("*")?"*":o).join("/")}function xc(e,t){let o=N(e,t),n=D(o.type,`${t}/type`,32),r=["code","type","label","presentation","required"],i=n==="sso"?[...r,"provider"]:n==="dingtalk"?[...r,"flow"]:r;T(o,i,t);let a=v(o.code,`${t}/code`),s=D(o.label,`${t}/label`,255),d=D(o.presentation,`${t}/presentation`,16);["primary","secondary"].includes(d)||_("NATIVE_APPLICATION_AUTH_METHOD_PRESENTATION_INVALID",`${t}/presentation`);let c=ht(o.required,`${t}/required`);return["sso","password","dingtalk"].includes(n)||_("NATIVE_APPLICATION_AUTH_METHOD_TYPE_INVALID",`${t}/type`),n==="sso"&&o.provider!=="tenant-default"&&_("NATIVE_APPLICATION_AUTH_SSO_PROVIDER_INVALID",`${t}/provider`),n==="dingtalk"&&!["auto","jsapi","oauth"].includes(D(o.flow,`${t}/flow`,16))&&_("NATIVE_APPLICATION_AUTH_DINGTALK_FLOW_INVALID",`${t}/flow`),{code:a,type:n,label:s,presentation:d,required:c,...n==="sso"?{provider:"tenant-default"}:{},...n==="dingtalk"?{flow:o.flow}:{}}}function $s(e,t,o){let n=N(e,o);T(n,["routeCode","path","defaultRouteCode"],o);let r=v(n.routeCode,`${o}/routeCode`),i=Re(n.path,`${o}/path`),a=t==="desktop"?"/login":"/m/login";return(i!==a||/[:*?#\\]/.test(i))&&_("NATIVE_APPLICATION_AUTH_SURFACE_PATH_INVALID",`${o}/path`,{device:t,expectedPath:a}),{routeCode:r,path:i,defaultRouteCode:v(n.defaultRouteCode,`${o}/defaultRouteCode`)}}function Ys(e,t,o,n){if(e===null)return;let r=N(e,n);T(r,["accountMode","registration","methods","surfaces"],n),W(r.accountMode,"existing-platform-users-only",`${n}/accountMode`);let i=N(r.registration,`${n}/registration`);T(i,["mode"],`${n}/registration`),W(i.mode,"reject",`${n}/registration/mode`);let a=k(r.methods,`${n}/methods`,8);a.length===0&&_("NATIVE_APPLICATION_AUTH_METHOD_REQUIRED",`${n}/methods`);let s=a.map((O,g)=>xc(O,`${n}/methods/${g}`)),d=new Set,c=new Set;for(let[O,g]of s.entries())d.has(g.code)&&_("NATIVE_APPLICATION_AUTH_METHOD_CODE_DUPLICATE",`${n}/methods/${O}/code`),c.has(g.type)&&_("NATIVE_APPLICATION_AUTH_METHOD_TYPE_DUPLICATE",`${n}/methods/${O}/type`),d.add(g.code),c.add(g.type);s.filter(O=>O.presentation==="primary").length!==1&&_("NATIVE_APPLICATION_AUTH_PRIMARY_METHOD_INVALID",`${n}/methods`);let l=N(r.surfaces,`${n}/surfaces`);T(l,["desktop","mobile"],`${n}/surfaces`);let f=$s(l.desktop,"desktop",`${n}/surfaces/desktop`),p=$s(l.mobile,"mobile",`${n}/surfaces/mobile`);f.routeCode===p.routeCode&&_("NATIVE_APPLICATION_AUTH_SURFACE_CODE_DUPLICATE",`${n}/surfaces/mobile/routeCode`);let m=k(t,"/config/frontend/routes",B.routes),E=new Map;for(let[O,g]of m.entries()){let y=N(g,`/config/frontend/routes/${O}`);E.set(String(y.code||""),y)}let A=new Set((Array.isArray(o.data?.resources)?o.data.resources:[]).map(O=>String(O.code||"")).filter(O=>/^[a-z][a-z0-9-]{0,62}$/.test(O)));for(let[O,g]of[["desktop",f],["mobile",p]]){E.has(g.routeCode)&&_("NATIVE_APPLICATION_AUTH_SURFACE_CODE_CONFLICT",`${n}/surfaces/${O}/routeCode`);let y=/^user\.([a-z][a-z0-9-]{0,62})\.(records|submit)$/.exec(String(g.defaultRouteCode||"")),h=E.get(g.defaultRouteCode),u=String(h?.path||"");if(y&&A.has(y[1])){let R=y[2]==="records"?`/my/${y[1]}`:`/my/${y[1]}/submit`;h={surface:"user",path:O==="mobile"?`/m${R}`:R},u=String(h.path)}let I=O==="desktop"?u==="/m"||u.startsWith("/m/"):!(u==="/m"||u.startsWith("/m/"));(!h||h.surface!=="user"||/[:*]/.test(u)||I)&&_("NATIVE_APPLICATION_AUTH_DEFAULT_ROUTE_INVALID",`${n}/surfaces/${O}/defaultRouteCode`)}let b=Xs(o).filter(O=>!O.owner.startsWith("authentication:"));for(let[O,g]of[["desktop",f],["mobile",p]]){let y=b.find(h=>xn(h.path)===xn(g.path));y&&_("NATIVE_APPLICATION_AUTH_SURFACE_PATH_CONFLICT",`${n}/surfaces/${O}/path`,{owner:y.owner})}}function jc(e,t){if(e===null)return;let o={data:{resources:[]},workflows:{definitions:[]},frontend:{routes:[{code:"auth-desktop-default",path:"/auth-desktop-default",surface:"user"},{code:"auth-mobile-default",path:"/m/auth-mobile-default",surface:"user"}],user:{applicationTodoCenter:!1},admin:{navigation:[]},authentication:e}},n=N(e,t),r=N(n.surfaces,`${t}/surfaces`),i={...n,surfaces:{...r,desktop:{...N(r.desktop,`${t}/surfaces/desktop`),defaultRouteCode:"auth-desktop-default"},mobile:{...N(r.mobile,`${t}/surfaces/mobile`),defaultRouteCode:"auth-mobile-default"}}};Ys(i,o.frontend.routes,{...o,frontend:{...o.frontend,authentication:i}},t)}function Mc(e){let t=e.frontend.authentication;return t===null?null:{accountMode:t.accountMode,registration:{mode:t.registration.mode},methods:t.methods.map(o=>({...o})),surfaces:{desktop:{...t.surfaces.desktop},mobile:{...t.surfaces.mobile}}}}var Uc=new Set(["draft.read","draft.update","validate","create","own.list","own.read","public.list","public.read"]);function Bc(e,t,o){let n=N(e,o);T(n,["policies"],o);let r=k(n.policies,`${o}/policies`,16);r.length<1&&_("NATIVE_PUBLIC_POLICY_REQUIRED",o);let i=new Map(t.frontend.routes.map(c=>[c.code,c])),a=new Map(t.data.resources.map(c=>[c.code,c])),s=new Set,d=new Set(r.map(c=>String(c?.code||"")));r.forEach((c,l)=>{let f=`${o}/policies/${l}`,p=N(c,f);T(p,["code","routeCode","mode","resourceCode","operations","fields"],f,["requiredFields","ownRecordFields","publicRecordFields","publicFilters","serverGeneratedFields","schedule","publicSubtableFields","draft","validations"]);let m=v(p.code,`${f}/code`);s.has(m)&&_("NATIVE_PUBLIC_POLICY_DUPLICATE",`${f}/code`);let E=v(p.routeCode,`${f}/routeCode`),A=i.get(E);(!A||A.surface!=="user"||A.capability!==void 0||A.access!==void 0||/[:*]/.test(String(A.path)))&&_("NATIVE_PUBLIC_ROUTE_INVALID",`${f}/routeCode`),W(p.mode,"anonymous",`${f}/mode`);let b=Y(p.resourceCode,`${f}/resourceCode`),O=a.get(b);O||_("NATIVE_PUBLIC_RESOURCE_MISSING",`${f}/resourceCode`);let g=new Map(O.schema.fields.map($=>[String($.code),String($.type)])),y=F(p.operations,`${f}/operations`,8);(y.length<1||y.some($=>!Uc.has($)))&&_("NATIVE_PUBLIC_OPERATION_INVALID",`${f}/operations`),y.includes("draft.read")!==y.includes("draft.update")&&_("NATIVE_PUBLIC_DRAFT_OPERATION_INCOMPLETE",`${f}/operations`);let h=F(p.fields,`${f}/fields`,64);(h.length<1||h.some($=>!g.has($)))&&_("NATIVE_PUBLIC_FIELD_INVALID",`${f}/fields`);for(let $ of["requiredFields","ownRecordFields","publicRecordFields"]){if(!Object.prototype.hasOwnProperty.call(p,$))continue;F(p[$],`${f}/${$}`,64).some(x=>!h.includes(x))&&_("NATIVE_PUBLIC_FIELD_SCOPE_INVALID",`${f}/${$}`)}let u=Object.prototype.hasOwnProperty.call(p,"serverGeneratedFields")?k(p.serverGeneratedFields,`${f}/serverGeneratedFields`,16):[],I=new Set;u.forEach(($,M)=>{let x=`${f}/serverGeneratedFields/${M}`,z=N($,x);T(z,["field","kind"],x);let J=G(z.field,`${x}/field`);(I.has(J)||!g.has(J)||h.includes(J)||g.get(J)!=="text.short"&&g.get(J)!=="text.long")&&_("NATIVE_PUBLIC_SERVER_GENERATED_FIELD_INVALID",`${x}/field`),W(z.kind,"random-token",`${x}/kind`),I.add(J)});let R=Object.prototype.hasOwnProperty.call(p,"schedule")?N(p.schedule,`${f}/schedule`):null;if(R){let $=["campusPolicyCode","rulePolicyCode","campusField","ruleCampusField","ruleWeekdaysField","ruleOpenAtField","ruleCloseAtField","ruleSlotMinutesField","ruleAdvanceHoursField","ruleAdvanceDaysField","campusEnabledField","ruleEnabledField","dateField","timeField"];T(R,$,`${f}/schedule`);for(let M of["campusPolicyCode","rulePolicyCode"])v(R[M],`${f}/schedule/${M}`);for(let M of $.filter(x=>!["campusPolicyCode","rulePolicyCode"].includes(x)))G(R[M],`${f}/schedule/${M}`);for(let M of[R.campusField,R.dateField,R.timeField])h.includes(String(M))||_("NATIVE_PUBLIC_SCHEDULE_FIELD_INVALID",`${f}/schedule`);(!d.has(String(R.campusPolicyCode))||!d.has(String(R.rulePolicyCode)))&&_("NATIVE_PUBLIC_SCHEDULE_POLICY_INVALID",`${f}/schedule`)}let w=Object.prototype.hasOwnProperty.call(p,"publicFilters")?k(p.publicFilters,`${f}/publicFilters`,16):[],C=new Set;w.forEach(($,M)=>{let x=`${f}/publicFilters/${M}`,z=N($,x);T(z,["field","operator","value"],x);let J=G(z.field,`${x}/field`);C.has(J)&&_("NATIVE_PUBLIC_FILTER_DUPLICATE",`${x}/field`),h.includes(J)||_("NATIVE_PUBLIC_FILTER_FIELD_INVALID",`${x}/field`),W(z.operator,"eq",`${x}/operator`),["boolean","text.short","text.long","number.integer","number.decimal","date","time"].includes(g.get(J)||"")||_("NATIVE_PUBLIC_FILTER_FIELD_INVALID",`${x}/field`),z.value!==null&&typeof z.value!="string"&&typeof z.value!="number"&&typeof z.value!="boolean"&&_("NATIVE_PUBLIC_FILTER_VALUE_INVALID",`${x}/value`),C.add(J)});let S=Object.prototype.hasOwnProperty.call(p,"publicSubtableFields")?N(p.publicSubtableFields,`${f}/publicSubtableFields`):null;if(S){Object.keys(S).length>64&&_("NATIVE_PUBLIC_SUBTABLE_FIELDS_INVALID",`${f}/publicSubtableFields`);for(let[$,M]of Object.entries(S)){let x=O.schema.fields.find(H=>String(H.code)===$),z=String(x?.subtable?.resourceCode||""),J=a.get(z),ye=new Map((J?.schema?.fields||[]).map(H=>[String(H.code),String(H.type)])),we=F(M,`${f}/publicSubtableFields/${$}`,64);(!h.includes($)||g.get($)!=="subtable"||!J||we.length<1||we.some(H=>!ye.has(H))||we.some(H=>ye.get(H)==="subtable")||we.some(H=>ye.get(H)==="signature"))&&_("NATIVE_PUBLIC_SUBTABLE_FIELDS_INVALID",`${f}/publicSubtableFields/${$}`)}}if(y.some($=>$.startsWith("public."))){Object.prototype.hasOwnProperty.call(p,"publicRecordFields")||_("NATIVE_PUBLIC_RECORD_FIELDS_REQUIRED",`${f}/publicRecordFields`);let $=F(p.publicRecordFields,`${f}/publicRecordFields`,64);($.length<1||$.some(M=>!h.includes(M))||$.some(M=>g.get(M)==="signature"||g.get(M)==="subtable"&&!S?.[M]))&&_("NATIVE_PUBLIC_RECORD_FIELDS_INVALID",`${f}/publicRecordFields`)}let P=Object.prototype.hasOwnProperty.call(p,"requiredFields")?F(p.requiredFields,`${f}/requiredFields`,64):[],V=O.surface||{},q=V.fields||{},Z=String(V.mutationOwner||"native")==="native"&&V.generated?.create!==!1,X=O.schema.fields.filter($=>nn($,q[$.code])).map($=>String($.code));if(y.includes("create")&&!Z&&_("NATIVE_PUBLIC_CREATE_FIELDS_INCOMPLETE",`${f}/fields`),y.includes("create")&&!Object.prototype.hasOwnProperty.call(p,"draft")&&_("NATIVE_PUBLIC_DRAFT_REQUIRED",`${f}/draft`),y.includes("create"))for(let $ of X){let M=h.includes($)?P.includes($)?null:"requiredFields":"fields";M&&_("NATIVE_PUBLIC_CREATE_FIELDS_INCOMPLETE",`${f}/${M}`,{resourceCode:Y,fieldCode:$})}if(Object.prototype.hasOwnProperty.call(p,"draft")){let $=N(p.draft,`${f}/draft`);T($,["enabled","inactivityTtlSeconds","maxBytes"],`${f}/draft`),W($.enabled,!0,`${f}/draft/enabled`),ae($.inactivityTtlSeconds,`${f}/draft/inactivityTtlSeconds`,3600,7776e3),ae($.maxBytes,`${f}/draft/maxBytes`,4096,262144)}else y.includes("draft.read")&&_("NATIVE_PUBLIC_DRAFT_REQUIRED",`${f}/draft`);let Ie=Object.prototype.hasOwnProperty.call(p,"validations")?k(p.validations,`${f}/validations`,16):[],re=new Set;Ie.forEach(($,M)=>{let x=`${f}/validations/${M}`,z=N($,x);T(z,["code","kind","fields","result"],x);let J=v(z.code,`${x}/code`);re.has(J)&&_("NATIVE_PUBLIC_VALIDATION_DUPLICATE",`${x}/code`),W(z.kind,"duplicate",`${x}/kind`),W(z.result,"availability",`${x}/result`);let ye=F(z.fields,`${x}/fields`,8);(ye.length<1||ye.some(we=>!h.includes(we))||ye.some(we=>["file","subtable"].includes(g.get(we)||"")))&&_("NATIVE_PUBLIC_VALIDATION_FIELD_INVALID",`${x}/fields`),re.add(J)}),s.add(m)})}function Kc(e,t){let o=N(e,t);T(o,["policies"],t),k(o.policies,`${t}/policies`,16).length<1&&_("NATIVE_PUBLIC_POLICY_REQUIRED",t)}function Gc(e){return{policies:ne(e.frontend.publicAccess.policies.map(t=>({code:t.code,routeCode:t.routeCode,mode:t.mode,resourceCode:t.resourceCode,operations:U(t.operations),fields:U(t.fields),...t.requiredFields?{requiredFields:U(t.requiredFields)}:{},...t.ownRecordFields?{ownRecordFields:U(t.ownRecordFields)}:{},...t.publicRecordFields?{publicRecordFields:U(t.publicRecordFields)}:{},...t.publicFilters?{publicFilters:t.publicFilters.map(o=>({field:o.field,operator:o.operator,value:o.value})).sort((o,n)=>be(o.field,n.field))}:{},...t.publicSubtableFields?{publicSubtableFields:Object.fromEntries(Object.entries(t.publicSubtableFields).sort(([o],[n])=>o.localeCompare(n)).map(([o,n])=>[o,U(Array.isArray(n)?n.map(String):[])]))}:{},...t.serverGeneratedFields?{serverGeneratedFields:t.serverGeneratedFields.map(o=>({field:o.field,kind:o.kind})).sort((o,n)=>be(o.field,n.field))}:{},...t.schedule?{schedule:{campusPolicyCode:t.schedule.campusPolicyCode,rulePolicyCode:t.schedule.rulePolicyCode,campusField:t.schedule.campusField,ruleCampusField:t.schedule.ruleCampusField,ruleWeekdaysField:t.schedule.ruleWeekdaysField,ruleOpenAtField:t.schedule.ruleOpenAtField,ruleCloseAtField:t.schedule.ruleCloseAtField,ruleSlotMinutesField:t.schedule.ruleSlotMinutesField,ruleAdvanceHoursField:t.schedule.ruleAdvanceHoursField,ruleAdvanceDaysField:t.schedule.ruleAdvanceDaysField,campusEnabledField:t.schedule.campusEnabledField,ruleEnabledField:t.schedule.ruleEnabledField,dateField:t.schedule.dateField,timeField:t.schedule.timeField}}:{},...t.draft?{draft:{...t.draft}}:{},...t.validations?{validations:ne(t.validations.map(o=>({code:o.code,kind:o.kind,fields:U(o.fields),result:o.result})),o=>o.code)}:{}})),t=>t.code)}}function Xs(e){let t=[{owner:"platform:admin-entry",path:"/"},{owner:"platform:admin-entry",path:"/admin"},{owner:"platform:file-preview",path:"/files/:resourceCode/:fileId/preview"}];e.frontend.authentication&&t.push({owner:"authentication:desktop",path:e.frontend.authentication.surfaces.desktop.path},{owner:"authentication:mobile",path:e.frontend.authentication.surfaces.mobile.path});for(let o of e.data.resources){let n=Zs(o),r=`/admin/resources/${o.code}`,i=[["list",r],["detail",`${r}/:id`],["create",`${r}/new`],["update",`${r}/:id/edit`]];for(let[a,s]of i)n[a]&&t.push({owner:`resource:${o.code}:${a}`,path:s},{owner:`resource:${o.code}:${a}:mobile`,path:`/m${s}`})}if(e.frontend.user.applicationTodoCenter===!0&&t.push({owner:"application:todo-center",path:"/todos"},{owner:"application:todo-center:mobile",path:"/m/todos"}),e.workflows.definitions.length>0){t.push({owner:"workflow:work-center",path:"/work-center"},{owner:"workflow:work-center:mobile",path:"/m/work-center"},{owner:"workflow:task",path:"/tasks/:taskId"},{owner:"workflow:task:mobile",path:"/m/tasks/:taskId"},{owner:"workflow:instance",path:"/workflows/:instanceId"},{owner:"workflow:instance:mobile",path:"/m/workflows/:instanceId"});let o=!1;for(let n of e.workflows.definitions)["standalone","hidden-handoff"].includes(n.launch.mode)&&(o=!0);o&&t.push({owner:"workflow:launch",path:"/workflows/:workflowCode/start"},{owner:"workflow:launch:mobile",path:"/m/workflows/:workflowCode/start"})}return t}function Bn(e){let t=new Map(Xs(e).map(o=>[xn(o.path),o]));return ne(e.frontend.routes.map((o,n)=>{let r=`/config/frontend/routes/${n}`,i=N(o,r);T(i,["code","path","label","surface","parentCode","capability","access","pinned","tabPersistence","keepAlive"],r,!0),["admin","user"].includes(i.surface)||_("NATIVE_ROUTE_SURFACE_INVALID",`${r}/surface`);let a=Re(i.path,`${r}/path`);i.surface==="admin"&&a!=="/admin"&&!a.startsWith("/admin/")&&_("NATIVE_ADMIN_ROUTE_PATH_INVALID",`${r}/path`),i.surface==="user"&&(a==="/admin"||a.startsWith("/admin/"))&&_("NATIVE_USER_ROUTE_PATH_RESERVED",`${r}/path`);let s=xn(a),d=t.get(s);d&&_("NATIVE_ROUTE_PATH_CONFLICT",`${r}/path`,{path:a,owner:d.owner}),t.set(s,{owner:`frontend:${String(i.code||n)}`,path:a});let c=/[:*]/.test(a),l=Or(i,r,e.appCode),f=i.pinned===void 0?void 0:ht(i.pinned,`${r}/pinned`),p=i.tabPersistence===void 0?c?"none":"session":D(i.tabPersistence,`${r}/tabPersistence`,16),m=i.keepAlive===void 0?"none":D(i.keepAlive,`${r}/keepAlive`,16);return["session","none"].includes(p)||_("NATIVE_ROUTE_TAB_PERSISTENCE_INVALID",`${r}/tabPersistence`),["none","memory"].includes(m)||_("NATIVE_ROUTE_KEEP_ALIVE_INVALID",`${r}/keepAlive`),c&&f===!0&&_("NATIVE_DYNAMIC_ROUTE_PINNED_FORBIDDEN",`${r}/pinned`),c&&p==="session"&&_("NATIVE_DYNAMIC_ROUTE_TAB_PERSISTENCE_FORBIDDEN",`${r}/tabPersistence`),c&&m==="memory"&&_("NATIVE_DYNAMIC_ROUTE_KEEP_ALIVE_FORBIDDEN",`${r}/keepAlive`),{code:v(i.code,`${r}/code`),path:a,label:D(i.label,`${r}/label`,255),surface:i.surface,...i.parentCode===void 0?{}:{parentCode:v(i.parentCode,`${r}/parentCode`)},...l,...f===void 0?{}:{pinned:f},tabPersistence:p,keepAlive:m}}),o=>o.code)}function Zs(e){let t=e.surface===void 0?{}:N(e.surface,"/surface"),o=t.mutationOwner||"native",n=t.generated===void 0?{}:N(t.generated,"/surface/generated"),r=o==="native";return{list:n.list??!0,detail:n.detail??!0,create:n.create??r,update:n.update??r,delete:n.delete??r}}function Qs(e){let t=[];for(let o of ne(e.data.resources,n=>n.code).flatMap(n=>[{resource:n,viewCode:void 0},...(n.surface?.views||[]).map(r=>({viewCode:r.code,resource:{...n,name:r.name,surface:To(n.surface,r.code)}}))])){let{resource:n,viewCode:r}=o,i=`/admin/resources/${n.code}${r?`/views/${r}`:""}`,a=Zs(n),s=[{operation:"list",kind:"resource-list",path:`${i}`,label:n.name,capability:n.capabilities.read,navigationEligible:!0},{operation:"detail",kind:"resource-detail",path:`${i}/:id`,label:`${n.name}\u8BE6\u60C5`,capability:n.capabilities.read,navigationEligible:!1},{operation:"create",kind:"resource-create",path:`${i}/new`,label:`\u65B0\u589E${n.name}`,capability:n.capabilities.create,navigationEligible:!1},{operation:"update",kind:"resource-update",path:`${i}/:id/edit`,label:`\u7F16\u8F91${n.name}`,capability:n.capabilities.update,navigationEligible:!1}];for(let d of s)a[d.operation]&&t.push({code:`resource:${n.code}${r?`:view:${r}`:""}:${d.operation}`,kind:d.kind,path:d.path,label:d.label,navigationEligible:d.navigationEligible,capability:d.capability,resourceCode:n.code,...r?{viewCode:r}:{}})}for(let o of Bn(e))o.surface==="admin"&&t.push({code:`operation:${o.code}`,kind:"operation",path:o.path,label:o.label,navigationEligible:!/[:*]/.test(o.path),routeCode:o.code});return t.sort((o,n)=>be(o.code,n.code))}function ea(e){return e.kind==="resource"?`resource:${e.resourceCode}${e.viewCode?`:view:${e.viewCode}`:""}:list`:`operation:${e.routeCode}`}function qc(e){return e.frontend.admin.navigation.map((t,o)=>({code:t.code,label:t.label,...t.icon===void 0?{}:{icon:t.icon},order:t.order??o,items:t.items.map((n,r)=>({pageCode:ea(n.page),...n.label===void 0?{}:{label:n.label},...n.icon===void 0?{}:{icon:n.icon},order:n.order??r})).sort((n,r)=>n.order-r.order||be(n.pageCode,r.pageCode))})).sort((t,o)=>t.order-o.order||be(t.code,o.code))}function zc(e,t){let o=k(e,t,B.adminNavigationGroups);o.reduce((r,i)=>r+(Array.isArray(i?.items)?i.items.length:0),0)>B.adminNavigationItems&&_("NATIVE_ARRAY_LIMIT_EXCEEDED",t);let n=0;o.forEach((r,i)=>{let a=`${t}/${i}`,s=N(r,a);T(s,["code","label","icon","order","items"],a,!0),v(s.code,`${a}/code`),D(s.label,`${a}/label`,255),jn(s.icon,`${a}/icon`),Ws(s.order,`${a}/order`);let d=k(s.items,`${a}/items`,500);d.length===0&&_("NATIVE_ADMIN_GROUP_ORPHANED",`${a}/items`),n+=d.length,n>B.adminNavigationItems&&_("NATIVE_ARRAY_LIMIT_EXCEEDED",t),d.forEach((c,l)=>{let f=`${a}/items/${l}`,p=N(c,f);T(p,["page","label","icon","order"],f,!0),Jc(p.page,`${f}/page`),p.label!==void 0&&D(p.label,`${f}/label`,255),jn(p.icon,`${f}/icon`),Ws(p.order,`${f}/order`)})})}function Jc(e,t){let o=N(e,t),n=D(o.kind,`${t}/kind`,64);if(n==="resource"){T(o,["kind","resourceCode"],t,["viewCode"]),o.viewCode!==void 0&&v(o.viewCode,`${t}/viewCode`),Y(o.resourceCode,`${t}/resourceCode`);return}if(n==="operation"){T(o,["kind","routeCode"],t),v(o.routeCode,`${t}/routeCode`);return}_("NATIVE_ADMIN_PAGE_REFERENCE_KIND_INVALID",`${t}/kind`)}function Hc(e){let t=new Map(Qs(e).map(r=>[String(r.code),r])),o=new Set,n=new Set;e.frontend.admin.navigation.forEach((r,i)=>{let a=`/config/frontend/admin/navigation/${i}`;o.has(r.code)&&_("NATIVE_ADMIN_GROUP_DUPLICATE",`${a}/code`),o.add(r.code),r.label===r.code&&_("NATIVE_ADMIN_USER_LABEL_REQUIRED",`${a}/label`),r.items.forEach((s,d)=>{let c=`${a}/items/${d}`,l=ea(s.page),f=t.get(l);(!f||f.navigationEligible!==!0)&&_("NATIVE_ADMIN_PAGE_NOT_FOUND",`${c}/page`),n.has(l)&&_("NATIVE_ADMIN_PAGE_DUPLICATE",`${c}/page`),n.add(l);let p=s.page.resourceCode||s.page.routeCode||s.page.workflowCode||l,m=s.label||f.label;(!m||m===p||m===l)&&_("NATIVE_ADMIN_USER_LABEL_REQUIRED",`${c}/label`)})})}function Yc(e,t){let o=k(e,t,B.adminPages),n=new Set;o.forEach((r,i)=>{let a=`${t}/${i}`,s=N(r,a);T(s,["code","kind","path","label","navigationEligible","capability","access","resourceCode","viewCode","routeCode"],a,!0);let d=D(s.code,`${a}/code`,255);n.has(d)&&_("NATIVE_ADMIN_PAGE_DUPLICATE",`${a}/code`),n.add(d);let c=D(s.kind,`${a}/kind`,64);if(["resource-list","resource-detail","resource-create","resource-update","operation"].includes(c)||_("NATIVE_ADMIN_PAGE_KIND_INVALID",`${a}/kind`),Re(s.path,`${a}/path`),D(s.label,`${a}/label`,255),ht(s.navigationEligible,`${a}/navigationEligible`),s.capability!==void 0&&s.access!==void 0&&_("NATIVE_ROUTE_ACCESS_CONFLICT",`${a}/access`),s.capability!==void 0&&D(s.capability,`${a}/capability`,255),s.access!==void 0){let l=N(s.access,`${a}/access`);T(l,["allOf","anyOf"],`${a}/access`,!0);for(let f of["allOf","anyOf"])l[f]!==void 0&&F(l[f],`${a}/access/${f}`,50)}for(let l of["resourceCode","viewCode","routeCode"])s[l]!==void 0&&v(s[l],`${a}/${l}`)})}function Xc(e,t){let o=k(e,t,B.adminNavigationGroups);o.reduce((r,i)=>r+(Array.isArray(i?.items)?i.items.length:0),0)>B.adminNavigationItems&&_("NATIVE_ARRAY_LIMIT_EXCEEDED",t);let n=0;o.forEach((r,i)=>{let a=`${t}/${i}`,s=N(r,a);T(s,["code","label","icon","order","items"],a,!0),v(s.code,`${a}/code`),D(s.label,`${a}/label`,255),jn(s.icon,`${a}/icon`),ae(s.order,`${a}/order`,-1e4,1e4);let d=k(s.items,`${a}/items`,500);d.length===0&&_("NATIVE_ADMIN_GROUP_ORPHANED",`${a}/items`),n+=d.length,n>B.adminNavigationItems&&_("NATIVE_ARRAY_LIMIT_EXCEEDED",t),d.forEach((c,l)=>{let f=`${a}/items/${l}`,p=N(c,f);T(p,["pageCode","label","icon","order"],f,!0),D(p.pageCode,`${f}/pageCode`,255),p.label!==void 0&&D(p.label,`${f}/label`,255),jn(p.icon,`${f}/icon`),ae(p.order,`${f}/order`,-1e4,1e4)})})}var Zc=new Set(["application-todo-center","workflow-work-center","workflow-launch","workflow-task","workflow-instance","resource-records","resource-submit"]);function Qc(e,t,o){let n=N(e,t);T(n,["schemaVersion","appCode","devicePolicy","rootEntry","authentication","routes","digest"],t),W(n.schemaVersion,zs,`${t}/schemaVersion`),W(n.appCode,o,`${t}/appCode`),yr(n.devicePolicy,`${t}/devicePolicy`),el(n.rootEntry,`${t}/rootEntry`),tl(n.authentication,`${t}/authentication`),Er(n.digest,`${t}/digest`);let r=k(n.routes,`${t}/routes`,B.routes),i=new Set;r.forEach((a,s)=>{let d=`${t}/routes/${s}`,c=N(a,d),l=c.kind==="resource-records"||c.kind==="resource-submit";T(c,["code","kind","desktop","mobile"],d,["workflowCode",...l?["resourceCode"]:[]]);let f=D(c.code,`${d}/code`,255);i.has(f)&&_("NATIVE_ROUTE_MANIFEST_DUPLICATE",`${d}/code`),i.add(f);let p=D(c.kind,`${d}/kind`,64);if(Zc.has(p)||_("NATIVE_ROUTE_MANIFEST_KIND_INVALID",`${d}/kind`),c.workflowCode!==void 0&&v(c.workflowCode,`${d}/workflowCode`),l){let A=Y(c.resourceCode,`${d}/resourceCode`);W(f,`user.${A}.${c.kind==="resource-records"?"records":"submit"}`,`${d}/code`)}else c.resourceCode!==void 0&&_("NATIVE_PROPERTY_UNKNOWN",`${d}/resourceCode`);let m=vs(c.desktop,`${d}/desktop`,o),E=vs(c.mobile,`${d}/mobile`,o);m.surface!=="user"&&_("NATIVE_ROUTE_MANIFEST_DESKTOP_SURFACE_INVALID",`${d}/desktop/surface`),E.surface!=="user"&&_("NATIVE_ROUTE_MANIFEST_MOBILE_SURFACE_INVALID",`${d}/mobile/surface`),m.routeCode===E.routeCode&&_("NATIVE_ROUTE_MANIFEST_PAIR_DUPLICATE",d)}),W(n.digest,ee({schemaVersion:n.schemaVersion,appCode:n.appCode,devicePolicy:n.devicePolicy,rootEntry:n.rootEntry,authentication:n.authentication,routes:n.routes}),`${t}/digest`)}function yr(e,t){let o=N(e,t);T(o,["kind","mobileMaxWidthPx","desktopMinWidthPx"],t),W(o.kind,"viewport-family",`${t}/kind`);let n=ae(o.mobileMaxWidthPx,`${t}/mobileMaxWidthPx`,320,1600),r=ae(o.desktopMinWidthPx,`${t}/desktopMinWidthPx`,320,1600);return r!==n+1&&_("NATIVE_FRONTEND_DEVICE_POLICY_INVALID",t),{kind:"viewport-family",mobileMaxWidthPx:n,desktopMinWidthPx:r}}function el(e,t){let o=N(e,t);T(o,["code","desktop","mobile"],t);let n=v(o.code,`${t}/code`),r=Ar(o.desktop,`${t}/desktop`),i=Ar(o.mobile,`${t}/mobile`);return(r===i||i==="/"||!i.startsWith("/m/"))&&_("NATIVE_ROUTE_MANIFEST_ROOT_ENTRY_INVALID",t),r.startsWith("/m/")&&_("NATIVE_ROUTE_MANIFEST_ROOT_ENTRY_INVALID",`${t}/desktop`),{code:n,desktop:r,mobile:i}}function tl(e,t){let o=N(e,t);T(o,["desktop","mobile"],t);let n=Ps(o.desktop,`${t}/desktop`,!1),r=Ps(o.mobile,`${t}/mobile`,!0);return(n.routeCode===r.routeCode||n.path===r.path)&&_("NATIVE_ROUTE_MANIFEST_AUTHENTICATION_DUPLICATE",t),{desktop:n,mobile:r}}function Ps(e,t,o){let n=N(e,t);T(n,["routeCode","path"],t);let r=v(n.routeCode,`${t}/routeCode`),i=Ar(n.path,`${t}/path`);return(o?!i.startsWith("/m/"):i.startsWith("/m/"))&&_("NATIVE_ROUTE_MANIFEST_AUTHENTICATION_PATH_INVALID",`${t}/path`),{routeCode:r,path:i}}function Ar(e,t){let o=Re(e,t);return/[:*?#\\\\]/.test(o)&&_("NATIVE_ROUTE_MANIFEST_STATIC_PATH_INVALID",t),o}function vs(e,t,o){let n=N(e,t);T(n,["routeCode","path","surface","pathParams","requiresAuthentication"],t,["capability","access"]),v(n.routeCode,`${t}/routeCode`);let r=Re(n.path,`${t}/path`),i=D(n.surface,`${t}/surface`,16);["admin","user"].includes(i)||_("NATIVE_ROUTE_SURFACE_INVALID",`${t}/surface`);let a=F(n.pathParams,`${t}/pathParams`,8);return a.forEach((s,d)=>{(!/^[A-Za-z][A-Za-z0-9_]*$/.test(s)||s.length>64)&&_("NATIVE_ROUTE_PATH_PARAM_INVALID",`${t}/pathParams/${d}`)}),Q(a)!==Q(ta(r))&&_("NATIVE_ROUTE_PATH_PARAMS_MISMATCH",`${t}/pathParams`),Or(n,t,o),n.requiresAuthentication!==!0&&_("NATIVE_ROUTE_AUTHENTICATION_REQUIRED",`${t}/requiresAuthentication`),n}function ta(e){return U([...e.matchAll(/:([A-Za-z][A-Za-z0-9_]*)/g)].map(t=>t[1]))}function Vs(e,t,o,n){return{routeCode:e,path:t,surface:o,pathParams:ta(t),...n?.capability?{capability:n.capability}:{},...n?.access?{access:n.access}:{},requiresAuthentication:!0}}function Fs(e,t,o,n){return e==="workflow-launch"?`workflow.${o}.launch.${t}`:e==="application-todo-center"?`application.todo-center.${t}`:e==="resource-records"?`user.${n}.records.${t}`:e==="resource-submit"?`user.${n}.submit.${t}`:`${e.replace(/-/g,".")}.${t}`}function nl(e){let t=e.appCode,o=[],n=(m,E,A,b,O,g,y)=>{o.push({code:m,kind:E,...O?{workflowCode:O}:{},...y?{resourceCode:y}:{},desktop:Vs(Fs(E,"desktop",O,y),A,"user",g),mobile:Vs(Fs(E,"mobile",O,y),b,"user",g)})};e.frontend.user.applicationTodoCenter===!0&&n("application:todo-center","application-todo-center","/todos","/m/todos");let r=na(e);r.length>0&&(n("workflow:work-center","workflow-work-center","/work-center","/m/work-center"),n("workflow:task","workflow-task","/tasks/:taskId","/m/tasks/:taskId"),n("workflow:instance","workflow-instance","/workflows/:instanceId","/m/workflows/:instanceId"));for(let m of r){if(!["standalone","hidden-handoff"].includes(m.launch.mode))continue;let E=U([m.launch.submission?.create?.requiredCapability,m.launch.submission?.existing?.requiredCapability].filter(A=>!!A));n(`workflow:${m.code}:launch`,"workflow-launch","/workflows/:workflowCode/start","/m/workflows/:workflowCode/start",m.code,E.length===1?{capability:E[0]}:E.length>1?{access:{anyOf:E}}:void 0)}let i=o.sort((m,E)=>be(String(m.code),String(E.code))),a=Bn(e),s=m=>{let E=m==="mobile"?"/m/":"/",A=a.filter(O=>O.surface==="user"&&!/[:*?#\\\\]/.test(O.path)&&O.path===E).sort((O,g)=>be(O.code,g.code))[0];if(A)return{code:A.code,path:A.path};let b=a.filter(O=>O.surface==="user"&&!/[:*?#\\\\]/.test(O.path)&&(m==="mobile"?O.path.startsWith("/m/"):!O.path.startsWith("/m/"))).sort((O,g)=>be(O.code,g.code))[0];return b?{code:b.code,path:b.path}:{code:m==="mobile"?"application-root-mobile":"application-root",path:E}},d=e.frontend.authentication?{desktop:{routeCode:e.frontend.authentication.surfaces.desktop.routeCode,path:e.frontend.authentication.surfaces.desktop.path},mobile:{routeCode:e.frontend.authentication.surfaces.mobile.routeCode,path:e.frontend.authentication.surfaces.mobile.path}}:{desktop:{routeCode:"application-login",path:"/login"},mobile:{routeCode:"application-login-mobile",path:"/m/login"}},c=yr(e.frontend.devicePolicy,"/config/frontend/devicePolicy"),l=s("desktop"),f=s("mobile"),p={schemaVersion:zs,appCode:t,devicePolicy:c,rootEntry:{code:l.code,desktop:l.path,mobile:f.path},authentication:d,routes:i};return{...p,digest:ee(p)}}function jn(e,t){if(e===void 0)return;let o=D(e,t,32);gc.has(o)||_("NATIVE_ADMIN_ICON_INVALID",t)}function Ws(e,t){e!==void 0&&ae(e,t,-1e4,1e4)}function Or(e,t,o){return e.capability!==void 0&&e.access!==void 0&&_("NATIVE_ROUTE_ACCESS_CONFLICT",`${t}/access`),e.capability!==void 0?{capability:ge(e.capability,`${t}/capability`,o)}:e.access===void 0?{}:{access:Kn(e.access,`${t}/access`,o)}}function Kn(e,t,o){let n=N(e,t);T(n,["allOf","anyOf"],t,!0);let r=n.allOf===void 0?void 0:U(F(n.allOf,`${t}/allOf`,50).map((a,s)=>ge(a,`${t}/allOf/${s}`,o))),i=n.anyOf===void 0?void 0:U(F(n.anyOf,`${t}/anyOf`,50).map((a,s)=>ge(a,`${t}/anyOf/${s}`,o)));return(r?.length||0)+(i?.length||0)===0&&_("NATIVE_ROUTE_ACCESS_EMPTY",t),{...r===void 0?{}:{allOf:r},...i===void 0?{}:{anyOf:i}}}function na(e){let t=new Map(Hs(e).map(r=>[String(r.code),r])),o=e.workflows.definitions.map((r,i)=>{let a=`/config/workflows/definitions/${i}`,s=N(r,a);T(s,["version","definition","launch"],a,["detailRouteCode"]);let d=N(s.definition,`${a}/definition`),c=s.detailRouteCode===void 0?void 0:ra(s.detailRouteCode,`${a}/detailRouteCode`);return{code:v(d.code,`${a}/definition/code`),title:D(d.title,`${a}/definition/title`,255),version:Nt(s.version,`${a}/version`),launch:ol(e,d,s.launch,`${a}/launch`,t),...c?{detailRouteCode:c}:{},definition:d}});return U(o.map(r=>r.code)).map(r=>{let i=o.filter(c=>c.code===r),a=e.workflows.activations.find(c=>c.workflowCode===r)?.definitionVersion,s=i.find(c=>c.version===a)||[...i].sort((c,l)=>l.version-c.version)[0],d=new Set;for(let c of i){let l=N(c.definition.nodes,"/config/workflows/definitions/nodes");for(let f of Object.values(l)){let p=N(f,"/config/workflows/definitions/nodes/*");if(!(p.kind!=="approval"&&p.kind!=="handle"))for(let m of F(p.allowedOperations||[],"/config/workflows/definitions/nodes/*/allowedOperations",20))d.add(m)}}return{code:r,title:s.title,acceptedCommandDeactivationPolicy:s.definition.acceptedCommandDeactivationPolicy,subject:s.definition.subject,launch:s.launch,...["standalone","hidden-handoff"].includes(s.launch.mode)&&!s.launch.submission?{processOperationCode:`openxiangda.workflow.${r}.submit`}:{},...s.detailRouteCode?{detailRouteCode:s.detailRouteCode}:{},definitionVersions:Gs(i.map(c=>c.version)),bindingVersions:Gs(e.workflows.bindings.map((c,l)=>{let f=`/config/workflows/bindings/${l}`,p=N(c,f),m=N(p.binding,`${f}/binding`);return{code:v(m.workflowCode,`${f}/binding/workflowCode`),version:Nt(p.version,`${f}/version`)}}).filter(c=>c.code===r).map(c=>c.version)),providerCodes:U(e.workflows.providers.map((c,l)=>v(N(c,`/config/workflows/providers/${l}`).code,`/config/workflows/providers/${l}/code`))),allowedOperations:[...d].sort(be),editableParameterCodes:U(e.workflows.editableParameters.map((c,l)=>{let f=`/config/workflows/editableParameters/${l}`,p=N(c,f);return{code:v(p.code,`${f}/code`),workflowCode:v(p.workflowCode,`${f}/workflowCode`)}}).filter(c=>c.workflowCode===r).map(c=>c.code))}})}function oa(e,t){let o=N(e,t);T(o,["mode"],t,["submission"]);let n=D(o.mode,`${t}/mode`,32);return["standalone","custom-page","hidden-handoff","work-center-only"].includes(n)||_("NATIVE_WORKFLOW_LAUNCH_MODE_INVALID",`${t}/mode`),{mode:n,...o.submission===void 0?{}:{submission:N(o.submission,`${t}/submission`)}}}function ol(e,t,o,n,r){let i=oa(o,n);if(!i.submission)return{mode:i.mode};["standalone","hidden-handoff"].includes(i.mode)||_("NATIVE_WORKFLOW_NAMED_OPERATION_SUBMISSION_INVALID",`${n}/submission`);let a=N(i.submission,`${n}/submission`);T(a,["kind"],`${n}/submission`,["create","existing","context"]),W(a.kind,"named-operation",`${n}/submission/kind`);let s=n.endsWith("/launch")?n.slice(0,-7):n,d=N(t.subject,`${s}/definition/subject`),c=Y(d.resourceCode,`${s}/definition/subject/resourceCode`),l=e.data.resources.findIndex(I=>I.code===c),f=e.data.resources[l];(l<0||!f)&&_("NATIVE_WORKFLOW_SUBJECT_RESOURCE_MISSING",`${s}/definition/subject/resourceCode`);let p=new Set(N(f.schema,`/config/data/resources/${l}/schema`).fields.map(I=>String(I.code))),m=new Map(e.backend.operations.map(I=>[String(I.code),I])),E=(I,R)=>{let w=`${n}/submission/${R}`,C=N(I,w);T(C,["operationCode","inputs","output"],w);let S=v(C.operationCode,`${w}/operationCode`),P=m.get(S),V=r.get(S),q=V?.platformAccess?.workflow?.codes;(!P||!V||V.method!=="POST"||!Array.isArray(q)||!q.includes(t.code))&&_("NATIVE_WORKFLOW_NAMED_OPERATION_INVALID",w);let Z=N(P.requestSchema,`${w}/operation/requestSchema`),X=N(Z.properties,`${w}/operation/requestSchema/properties`),Ie=new Set(Z.required===void 0?[]:F(Z.required,`${w}/operation/requestSchema/required`,205)),re=N(C.inputs,`${w}/inputs`),$=Object.entries(re);(!$.length||$.length>205)&&_("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${w}/inputs`);let M=new Set,x=new Map,z={},J=V.platformAccess?.ownedSubject;J&&(R!=="create"||J.resourceCode!==c)&&_("NATIVE_WORKFLOW_OWNED_SUBJECT_LAUNCH_MISMATCH",w);for(let[H,st]of $){(!Ds.test(H)||!Object.prototype.hasOwnProperty.call(X,H))&&_("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${w}/inputs/${H}`);let qe=`${w}/inputs/${H}`,Qn=N(st,qe),ze=D(Qn.source,`${qe}/source`,32);if(["field","idempotency-key","current-user-reference","subject-id","subject-revision","requested-at"].includes(ze)||_("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",qe),T(Qn,["source"],qe,ze==="field"?["fieldCode"]:!1),x.set(ze,(x.get(ze)||0)+1),ze==="field"){let at=G(Qn.fieldCode,`${qe}/fieldCode`);(M.has(at)||!p.has(at))&&_("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${qe}/fieldCode`),M.add(at),f.schema.fields.find(eo=>eo.code===at)?.type==="subtable"&&(!J||!J.subtables.some(eo=>eo.fieldCode===at))&&_("NATIVE_WORKFLOW_OWNED_SUBJECT_LAUNCH_REQUIRED",qe),z[H]={source:ze,fieldCode:at}}else z[H]={source:ze}}([...Ie].some(H=>!(H in re))||(x.get("idempotency-key")||0)!==1||!$.some(([H,st])=>N(st,`${w}/inputs/${H}`).source==="idempotency-key"&&Ie.has(H))||R==="create"&&((x.get("subject-id")||0)>0||(x.get("subject-revision")||0)>0)||R==="existing"&&((x.get("subject-id")||0)!==1||(x.get("subject-revision")||0)!==1))&&_("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${w}/inputs`);let ye=N(C.output,`${w}/output`);T(ye,["subjectId"],`${w}/output`,["subjectRevision","processCommand"]);let we=N(N(P.responseSchema,`${w}/operation/responseSchema`).properties,`${w}/operation/responseSchema/properties`);for(let H of["subjectId","subjectRevision","processCommand"]){if(ye[H]===void 0)continue;let st=D(ye[H],`${w}/output/${H}`,128);(!Ds.test(st)||!Object.prototype.hasOwnProperty.call(we,st))&&_("NATIVE_WORKFLOW_NAMED_OPERATION_OUTPUT_INVALID",`${w}/output/${H}`)}return{operationCode:S,method:"POST",path:V.path,requiredCapability:V.requiredCapability,requestSchemaDigest:V.requestSchemaDigest,responseSchemaDigest:V.responseSchemaDigest,inputs:z,output:{...ye},fieldCodes:M}},A=a.create===void 0?void 0:E(a.create,"create"),b=a.existing===void 0?void 0:E(a.existing,"existing");!A&&!b&&_("NATIVE_WORKFLOW_NAMED_OPERATION_SUBMISSION_INVALID",`${n}/submission`);let O=new Set([...A?.fieldCodes||[],...b?.fieldCodes||[]]),g=a.context===void 0?[]:k(a.context,`${n}/submission/context`,16),y=new Set,h=g.map((I,R)=>{let w=`${n}/submission/context/${R}`,C=N(I,w);T(C,["queryParameter","fieldCode"],w);let S=D(C.queryParameter,`${w}/queryParameter`,64),P=G(C.fieldCode,`${w}/fieldCode`);return(!/^[A-Za-z][A-Za-z0-9]{0,63}$/.test(S)||y.has(S)||!O.has(P))&&_("NATIVE_WORKFLOW_LAUNCH_CONTEXT_INVALID",w),y.add(S),{queryParameter:S,fieldCode:P}}),u=I=>{let{fieldCodes:R,...w}=I;return w};return{mode:i.mode,submission:{kind:"named-operation",...A?{create:u(A)}:{},...b?{existing:u(b)}:{},context:h}}}function ra(e,t){let o=N(e,t);T(o,["desktop","mobile"],t);let n=v(o.desktop,`${t}/desktop`),r=v(o.mobile,`${t}/mobile`);return n===r&&_("NATIVE_WORKFLOW_DETAIL_ROUTE_DUPLICATE",t),{desktop:n,mobile:r}}function rl(e,t){let o=new Set(t.map(l=>l.code)),n=new Map;e.data.resources.forEach((l,f)=>{let p=`/config/data/resources/${f}`,m=N(l,p);if(m.recordDeletion!==void 0){let b=`${p}/recordDeletion/delete`;for(let O of m.recordDeletion.delete)ge(O,b,e.appCode),o.has(O)||_("NATIVE_CAPABILITY_REFERENCE_MISSING",b)}if(m.recordComments!==void 0)for(let b of["read","create"]){let O=`${p}/recordComments/${b}`;for(let g of m.recordComments[b])ge(g,O,e.appCode),o.has(g)||_("NATIVE_CAPABILITY_REFERENCE_MISSING",O)}if(m.recordPrint!==void 0){let b=`${p}/recordPrint/read`;for(let O of m.recordPrint.read)ge(O,b,e.appCode),o.has(O)||_("NATIVE_CAPABILITY_REFERENCE_MISSING",b)}if(m.workflowHistory!==void 0){let b=`${p}/workflowHistory/read`;for(let O of m.workflowHistory.read)ge(O,b,e.appCode),o.has(O)||_("NATIVE_CAPABILITY_REFERENCE_MISSING",b)}for(let[b,O]of Object.entries(m.fieldPolicies||{})){if(!Tt(b))continue;let g=`${p}/fieldPolicies/${b}/read`,y=N(O,`${p}/fieldPolicies/${b}`);for(let h of F(y.read||[],g,2e3))o.has(h)||_("NATIVE_CAPABILITY_REFERENCE_MISSING",g)}let E=m.surface===void 0?{}:N(m.surface,`${p}/surface`);if(["native","queued-command"].includes(E.mutationOwner||"native"))return;let A=N(m.capabilities,`${p}/capabilities`);for(let b of["create","update","delete"])b==="delete"&&Array.isArray(m.recordDeletion?.delete)&&m.recordDeletion.delete.length>0||n.set(String(A[b]),b)});let r=new Set;for(let[l,f]of e.authz.roles.entries()){let p=`/config/authz/roles/${l}`,m=N(f,p);T(m,["code","name","description","capabilities"],p,!0);let E=v(m.code,`${p}/code`);r.has(E)&&_("NATIVE_ROLE_DUPLICATE",`${p}/code`),r.add(E),D(m.name,`${p}/name`,255);let A=F(m.capabilities,`${p}/capabilities`,2e3);for(let[b,O]of A.entries())n.has(O)&&_("NATIVE_DATA_SURFACE_MUTATION_GRANT_FORBIDDEN",`${p}/capabilities/${b}`,{operation:n.get(O)}),o.has(O)||_("NATIVE_CAPABILITY_REFERENCE_MISSING",`${p}/capabilities`)}let i=e.authz.authenticatedUserRoleCode===void 0?"":v(e.authz.authenticatedUserRoleCode,"/config/authz/authenticatedUserRoleCode");i&&!r.has(i)&&_("NATIVE_AUTHENTICATED_USER_ROLE_REFERENCE_MISSING","/config/authz/authenticatedUserRoleCode");let a=new Set,s=0;for(let[l,f]of e.perspectives.entries()){let p=`/config/perspectives/${l}`,m=N(f,p);T(m,["code","name","description","roleCodes","capabilityCodes","default"],p,!0);let E=v(m.code,`${p}/code`);a.has(E)&&_("NATIVE_PERSPECTIVE_DUPLICATE",`${p}/code`),a.add(E),D(m.name,`${p}/name`,255);let A=F(m.roleCodes,`${p}/roleCodes`,20);A.length<1&&_("NATIVE_PERSPECTIVE_ROLE_REQUIRED",`${p}/roleCodes`),A.forEach((g,y)=>{r.has(g)||_("NATIVE_PERSPECTIVE_ROLE_MISSING",`${p}/roleCodes/${y}`)});let b=U(e.authz.roles.filter(g=>A.includes(g.code)).flatMap(g=>g.capabilities)),O=F(m.capabilityCodes,`${p}/capabilityCodes`,2e3);Q(b)!==Q(O)&&_("NATIVE_PERSPECTIVE_CAPABILITY_PROJECTION_MISMATCH",`${p}/capabilityCodes`),m.default===!0?s+=1:m.default!==void 0&&_("NATIVE_PERSPECTIVE_DEFAULT_INVALID",`${p}/default`)}s>1&&_("NATIVE_PERSPECTIVE_DEFAULT_DUPLICATE","/config/perspectives");for(let[l,f]of e.backend.operations.entries()){let p=N(f,`/config/backend/operations/${l}`);o.has(p.capability)||_("NATIVE_CAPABILITY_REFERENCE_MISSING",`/config/backend/operations/${l}/capability`)}let d=new Set,c=new Set;for(let[l,f]of e.frontend.routes.entries()){let p=`/config/frontend/routes/${l}`,m=N(f,p),E=v(m.code,`${p}/code`);d.has(E)&&_("NATIVE_ROUTE_DUPLICATE",`${p}/code`),d.add(E);let A=Re(m.path,`${p}/path`);c.has(A)&&_("NATIVE_ROUTE_PATH_DUPLICATE",`${p}/path`),c.add(A);let b=Or(m,p,e.appCode);b.capability&&!o.has(b.capability)&&_("NATIVE_CAPABILITY_REFERENCE_MISSING",`${p}/capability`);let O=m.access===void 0?void 0:N(m.access,`${p}/access`);for(let g of["allOf","anyOf"]){let y=O?.[g]===void 0?[]:k(O[g],`${p}/access/${g}`,50);for(let[h,u]of y.entries()){let I=ge(u,`${p}/access/${g}/${h}`,e.appCode);o.has(I)||_("NATIVE_CAPABILITY_REFERENCE_MISSING",`${p}/access/${g}/${h}`)}}}if(e.frontend.admin.access!==void 0){let l=Kn(e.frontend.admin.access,"/config/frontend/admin/access",e.appCode);for(let f of["allOf","anyOf"])for(let[p,m]of(l[f]||[]).entries())o.has(m)||_("NATIVE_CAPABILITY_REFERENCE_MISSING",`/config/frontend/admin/access/${f}/${p}`)}for(let[l,f]of e.frontend.routes.entries()){let p=N(f,`/config/frontend/routes/${l}`);p.parentCode&&!d.has(p.parentCode)&&_("NATIVE_ROUTE_PARENT_MISSING",`/config/frontend/routes/${l}/parentCode`)}}function il(e){let t=new Set(e.authz.roles.map(c=>String(c.code))),o=e.authz.authenticatedUserRoleCode===void 0?"":v(e.authz.authenticatedUserRoleCode,"/config/authz/authenticatedUserRoleCode"),n=new Map(e.authz.scopeDimensions.map(c=>[String(c.code),{valueType:c.valueType==="uuid"?"uuid":"string",...c.valueSource?.resourceCode?{valueSourceResourceCode:String(c.valueSource.resourceCode)}:{}}])),r=new Set(n.keys()),i=new Map(e.data.resources.map((c,l)=>{let f=nt(c,`/config/data/resources/${l}`,e.appCode);return[f.code,new Map(f.schema.fields.map(p=>[String(p.code),p]))]}));for(let[c,l]of e.authz.scopeDimensions.entries()){let f=`/config/authz/scopeDimensions/${c}`,p=N(l,f);if(T(p,["code","name","resourceCode","valueType","hierarchyMode","valueSource"],f,!0),p.valueSource===void 0)continue;let m=N(p.valueSource,`${f}/valueSource`);T(m,["kind","resourceCode","labelField","enabledField"],`${f}/valueSource`,!0),m.kind!=="native_resource"&&_("NATIVE_SCOPE_VALUE_SOURCE_KIND_INVALID",`${f}/valueSource/kind`),p.valueType!=="uuid"&&_("NATIVE_SCOPE_VALUE_SOURCE_TYPE_INVALID",`${f}/valueType`);let E=Y(m.resourceCode,`${f}/valueSource/resourceCode`),A=i.get(E);A||_("NATIVE_SCOPE_VALUE_SOURCE_RESOURCE_MISSING",`${f}/valueSource/resourceCode`);let b=G(m.labelField,`${f}/valueSource/labelField`);if(["text.short","text.long"].includes(String(A.get(b)?.type||""))||_("NATIVE_SCOPE_VALUE_SOURCE_LABEL_FIELD_INVALID",`${f}/valueSource/labelField`),m.enabledField!==void 0){let O=G(m.enabledField,`${f}/valueSource/enabledField`);A.get(O)?.type!=="boolean"&&_("NATIVE_SCOPE_VALUE_SOURCE_ENABLED_FIELD_INVALID",`${f}/valueSource/enabledField`)}}let a=new Set,s=new Set;for(let[c,l]of e.authz.scopeSources.entries()){let f=`/config/authz/scopeSources/${c}`,p=N(l,f);T(p,["code","name","resourceCode","subject","grants","operationField","enabledField","effectiveFromField","effectiveToField","failureMode"],f,!0);let m=v(p.code,`${f}/code`);a.has(m)&&_("NATIVE_SCOPE_SOURCE_DUPLICATE",`${f}/code`),a.add(m),D(p.name,`${f}/name`,255);let E=Y(p.resourceCode,`${f}/resourceCode`),A=i.get(E);A||_("NATIVE_SCOPE_SOURCE_RESOURCE_MISSING",`${f}/resourceCode`);let b=N(p.subject,`${f}/subject`),O=D(b.type,`${f}/subject/type`,32);T(b,O==="role_membership"?["type","userIdField","roleCode"]:["type","userIdField"],`${f}/subject`),["user","role_membership"].includes(O)||_("NATIVE_SCOPE_SOURCE_SUBJECT_INVALID",`${f}/subject/type`);let g=kt(b.userIdField,A);Po(g)||_("NATIVE_SCOPE_SOURCE_SUBJECT_PATH_INVALID",`${f}/subject/userIdField`),O==="role_membership"&&!t.has(String(b.roleCode))&&_("NATIVE_ROLE_REFERENCE_MISSING",`${f}/subject/roleCode`);let y=new Set;for(let[h,u]of k(p.grants,`${f}/grants`,100).entries()){let I=`${f}/grants/${h}`,R=N(u,I);T(R,["dimensionCode","valueField","parentValueField"],I,!0);let w=v(R.dimensionCode,`${I}/dimensionCode`);(!r.has(w)||y.has(w))&&_("NATIVE_SCOPE_SOURCE_DIMENSION_INVALID",`${I}/dimensionCode`),y.add(w),p.failureMode==="last_known_good"&&s.add(w);for(let C of["valueField","parentValueField"]){if(R[C]===void 0)continue;let S=kt(R[C],A);_i(S,n.get(w),i)||_("NATIVE_SCOPE_SOURCE_GRANT_PATH_INVALID",`${I}/${C}`)}}y.size===0&&_("NATIVE_SCOPE_SOURCE_GRANT_REQUIRED",`${f}/grants`),["strict","last_known_good"].includes(p.failureMode)||_("NATIVE_SCOPE_SOURCE_FAILURE_MODE_INVALID",`${f}/failureMode`);for(let h of["operationField","enabledField","effectiveFromField","effectiveToField"]){if(p[h]===void 0)continue;let u=G(p[h],`${f}/${h}`);A.has(u)||_("NATIVE_SCOPE_SOURCE_FIELD_MISSING",`${f}/${h}`)}}al(e,t,i,o);let d=new Set;for(let[c,l]of e.authz.dataPolicies.entries()){let f=`/config/authz/dataPolicies/${c}`,p=N(l,f);T(p,["code","name","resourceCode","unrestrictedRoleCodes","publicRead","operations","matchMode","rules","readExpression","writeBoundary"],f,!0);let m=v(p.code,`${f}/code`);d.has(m)&&_("NATIVE_DATA_POLICY_DUPLICATE",`${f}/code`),d.add(m);let E=p.readExpression!==void 0,A=F(p.operations||[],`${f}/operations`,4);p.operations!==void 0&&(A.length===0||A.some(u=>!["read","create","update","delete"].includes(u)))&&_("NATIVE_DATA_POLICY_OPERATIONS_INVALID",`${f}/operations`),["AND","OR"].includes(p.matchMode)||_("NATIVE_DATA_POLICY_MATCH_MODE_INVALID",`${f}/matchMode`),E&&p.operations!==void 0&&_("NATIVE_DATA_POLICY_READ_EXPRESSION_OPERATIONS_FORBIDDEN",`${f}/operations`);let b=e.data.resources.find(u=>u.dataPolicyCode===m),O=p.resourceCode||b?.code,g=O?i.get(Y(O,`${f}/resourceCode`)):void 0;if(E&&!g&&_("NATIVE_DATA_POLICY_RESOURCE_MISSING",`${f}/resourceCode`),p.publicRead!==void 0){try{let u=e.authz.roles.find(I=>I.code===o);Vi({policy:p,resource:e.data.resources.find(I=>I.code===O),baselineRoleCode:o,baselineCapabilities:u?.capabilities||[],baselineDeniedCapabilities:u?.deniedCapabilities||[],pointer:f})}catch(u){if(!(u instanceof vt))throw u;_(u.code,u.pointer)}(p.unrestrictedRoleCodes||[]).includes(o)||_("AUTHENTICATED_PUBLIC_READ_CANONICAL_BASELINE_MISSING",`${f}/unrestrictedRoleCodes`)}else o&&(p.unrestrictedRoleCodes||[]).includes(o)&&_("NATIVE_DATA_POLICY_BASELINE_UNRESTRICTED",`${f}/unrestrictedRoleCodes`);let y=F(p.unrestrictedRoleCodes||[],`${f}/unrestrictedRoleCodes`,100);p.unrestrictedRoleCodes!==void 0&&y.length===0&&_("NATIVE_DATA_POLICY_UNRESTRICTED_ROLES_INVALID",`${f}/unrestrictedRoleCodes`);for(let u of y)t.has(u)||_("NATIVE_ROLE_REFERENCE_MISSING",`${f}/unrestrictedRoleCodes`);let h;try{let u=k(p.rules,`${f}/rules`,100).map((I,R)=>({rule:N(I,`${f}/rules/${R}`),pointer:`${f}/rules/${R}`}));u.length===0?(!E||p.matchMode!=="AND"||p.writeBoundary!=="capability_only")&&_("NATIVE_DATA_POLICY_WRITE_BOUNDARY_REQUIRED",f):p.writeBoundary!==void 0&&_("NATIVE_DATA_POLICY_WRITE_BOUNDARY_INVALID",`${f}/writeBoundary`),h=[...u],E&&(h.push(...gt(p.readExpression,`${f}/readExpression`)),Ri(p.readExpression,`${f}/readExpression`))}catch(u){throw u instanceof Pt&&_(u.code,u.pointer),u}for(let{rule:u,pointer:I}of h){if(T(u,["parentRead","subject","dimensionCode","relationCode","resourceCode","field","roleCodes","operation","valuePath","emptyMatchesAll","operator","value","operand"],I,!0),u.parentRead!==void 0){for(let X of F(u.roleCodes||[],`${I}/roleCodes`,100))t.has(X)||_("NATIVE_ROLE_REFERENCE_MISSING",`${I}/roleCodes`);continue}let R=G(u.field,`${I}/field`),w=g?.get(R);E&&!w&&_("NATIVE_DATA_POLICY_FIELD_MISSING",`${I}/field`);for(let X of F(u.roleCodes||[],`${I}/roleCodes`,100))t.has(X)||_("NATIVE_ROLE_REFERENCE_MISSING",`${I}/roleCodes`);let C=String(u.operator||""),S=u.operand==="db_now",P=["is_null","is_not_null"].includes(C),V=["eq","not_eq","in","not_in"].includes(C),q=!S&&(u.operator!==void 0||u.value!==void 0);if([u.subject==="current_user"?"current_user":"",typeof u.dimensionCode=="string"?"dimension":"",typeof u.relationCode=="string"?"relationship":"",q?"constant":"",S?"db_now":""].filter(Boolean).length!==1&&_("NATIVE_DATA_POLICY_RULE_SOURCE_INVALID",I),u.subject!==void 0&&u.subject!=="current_user"&&_("NATIVE_DATA_POLICY_SUBJECT_INVALID",`${I}/subject`),q){if(!V&&!P&&_("NATIVE_DATA_POLICY_OPERATOR_INVALID",`${I}/operator`),["in","not_in"].includes(C)){let X=k(u.value,`${I}/value`,100).map((Ie,re)=>D(Ie,`${I}/value/${re}`,2048));(X.length===0||new Set(X).size!==X.length)&&_("NATIVE_DATA_POLICY_VALUE_INVALID",`${I}/value`)}else["eq","not_eq"].includes(C)?D(u.value,`${I}/value`,2048):(u.value!==void 0||u.operand!==void 0)&&_("NATIVE_DATA_POLICY_VALUE_INVALID",`${I}/value`);for(let X of["operation","valuePath","emptyMatchesAll","resourceCode","operand"])u[X]!==void 0&&_("NATIVE_DATA_POLICY_CONSTANT_RULE_INVALID",`${I}/${X}`)}if(S){(!["lt","lte","gt","gte"].includes(C)||u.value!==void 0||w?.type!=="datetime")&&_("NATIVE_DATA_POLICY_DB_NOW_INVALID",I);for(let X of["operation","valuePath","emptyMatchesAll","resourceCode","value"])u[X]!==void 0&&_("NATIVE_DATA_POLICY_DB_NOW_INVALID",`${I}/${X}`)}u.dimensionCode&&!r.has(u.dimensionCode)&&_("NATIVE_SCOPE_DIMENSION_MISSING",`${I}/dimensionCode`),s.has(String(u.dimensionCode||""))&&u.operation!=="read"&&_("NATIVE_SCOPE_SOURCE_LAST_KNOWN_GOOD_UNSAFE",`${I}/operation`)}}try{Si(e.data.resources,e.authz.dataPolicies)}catch(c){throw c instanceof pe&&_(c.code,c.pointer),c}for(let[c,l]of e.data.resources.entries()){let f=N(l,`/config/data/resources/${c}`);f.dataPolicyCode&&!d.has(f.dataPolicyCode)&&_("NATIVE_DATA_POLICY_REFERENCE_MISSING",`/config/data/resources/${c}/dataPolicyCode`)}}function sl(e){try{zr(e.data.resources,"/config/data/resources"),e.data.resources.forEach((t,o)=>Fr(t.schema.fields,new Set(e.authz.roles.map(n=>n.code)),new Set(e.authz.scopeDimensions.map(n=>n.code)),`/config/data/resources/${o}/schema/fields`))}catch(t){throw(t instanceof Ce||t instanceof Je)&&_(t.code,t.pointer),t}}function al(e,t,o,n){let r=new Set;for(let[i,a]of e.authz.roleMembershipSources.entries()){let s=`/config/authz/roleMembershipSources/${i}`,d=N(a,s);T(d,["code","name","resourceCode","userIdField","roleCode","enabledField","effectiveFromField","effectiveToField","failureMode"],s,!0);let c=v(d.code,`${s}/code`);c.length>100&&_("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_CODE_INVALID",`${s}/code`),r.has(c)&&_("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_DUPLICATE",`${s}/code`),r.add(c),D(d.name,`${s}/name`,255);let l=xs(d.resourceCode,`${s}/resourceCode`,o);js(d.userIdField,`${s}/userIdField`,l),t.has(String(d.roleCode||""))||_("NATIVE_ROLE_REFERENCE_MISSING",`${s}/roleCode`),n&&d.roleCode===n&&_("NATIVE_AUTHENTICATED_USER_ROLE_SOURCE_CONFLICT",`${s}/roleCode`),Ms(d,s,l)}for(let[i,a]of e.authz.relationshipGrantSources.entries()){let s=`/config/authz/relationshipGrantSources/${i}`,d=N(a,s);T(d,["code","name","resourceCode","subject","relationCode","targetResourceCode","resourceIdField","operations","enabledField","effectiveFromField","effectiveToField","failureMode"],s,!0);let c=v(d.code,`${s}/code`);c.length>100&&_("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_CODE_INVALID",`${s}/code`),r.has(c)&&_("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_DUPLICATE",`${s}/code`),r.add(c),D(d.name,`${s}/name`,255);let l=xs(d.resourceCode,`${s}/resourceCode`,o),f=N(d.subject,`${s}/subject`),p=D(f.type,`${s}/subject/type`,32);T(f,p==="role_membership"?["type","userIdField","roleCode"]:["type","userIdField"],`${s}/subject`),["user","role_membership"].includes(p)||_("NATIVE_AUTHORIZATION_PROJECTION_SUBJECT_INVALID",`${s}/subject/type`),js(f.userIdField,`${s}/subject/userIdField`,l),p==="role_membership"&&!t.has(String(f.roleCode||""))&&_("NATIVE_ROLE_REFERENCE_MISSING",`${s}/subject/roleCode`),v(d.relationCode,`${s}/relationCode`);let m=Y(d.targetResourceCode,`${s}/targetResourceCode`);o.has(m)||_("NATIVE_AUTHORIZATION_PROJECTION_TARGET_RESOURCE_MISSING",`${s}/targetResourceCode`);let E=kt(d.resourceIdField,l),A=E?.field.type==="resource-ref.single"&&E.valuePath==="value"&&E.field.source?.resourceCode===m;(d.resourceIdField==="id"?m!==String(d.resourceCode):!A)&&_("NATIVE_AUTHORIZATION_PROJECTION_RESOURCE_ID_FIELD_INVALID",`${s}/resourceIdField`);let b=F(d.operations,`${s}/operations`,20);(b.length===0||b.some(O=>O.length>64||!/^[A-Za-z0-9][A-Za-z0-9:._*-]{0,63}$/.test(O)))&&_("NATIVE_AUTHORIZATION_PROJECTION_OPERATIONS_INVALID",`${s}/operations`),Ms(d,s,l)}}function xs(e,t,o){let n=Y(e,t),r=o.get(n);return r||_("NATIVE_AUTHORIZATION_PROJECTION_RESOURCE_MISSING",t),r}function js(e,t,o){let n=kt(e,o);Po(n)||_("NATIVE_AUTHORIZATION_PROJECTION_USER_FIELD_INVALID",t)}function Ms(e,t,o){if(e.failureMode!=="strict"&&_("NATIVE_AUTHORIZATION_PROJECTION_FAILURE_MODE_INVALID",`${t}/failureMode`),e.enabledField!==void 0){let n=G(e.enabledField,`${t}/enabledField`);o.get(n)?.type!=="boolean"&&_("NATIVE_AUTHORIZATION_PROJECTION_ENABLED_FIELD_INVALID",`${t}/enabledField`)}for(let n of["effectiveFromField","effectiveToField"]){if(e[n]===void 0)continue;let r=G(e[n],`${t}/${n}`);["date","datetime"].includes(String(o.get(r)?.type))||_("NATIVE_AUTHORIZATION_PROJECTION_EFFECTIVE_FIELD_INVALID",`${t}/${n}`)}}function dl(e){let t=new Set,o=new Set;e.forEach((n,r)=>{let i=`/config/backend/secrets/${r}`,a=N(n,i);T(a,["name","env","description","required","exposure"],i,!0);let s=D(a.name,`${i}/name`,128),d=D(a.env,`${i}/env`,128);dc.test(s)||_("NATIVE_SECRET_NAME_INVALID",`${i}/name`),(!cc.test(d)||d.startsWith("OPENXIANGDA_")||["NODE_ENV","PORT"].includes(d))&&_("NATIVE_SECRET_ENV_INVALID",`${i}/env`),t.has(s)&&_("NATIVE_SECRET_NAME_DUPLICATE",`${i}/name`),o.has(d)&&_("NATIVE_SECRET_ENV_DUPLICATE",`${i}/env`),t.add(s),o.add(d),W(a.exposure,"active_only",`${i}/exposure`),a.required!==void 0&&ht(a.required,`${i}/required`),a.description!==void 0&&br(a.description,`${i}/description`,2e3)})}function cl(e){let t=new Set,o=new Map,n=new Map(e.data.resources.map(m=>[String(m.code),m])),r=new Map(e.frontend.routes.map((m,E)=>{let A=N(m,`/config/frontend/routes/${E}`);return[v(A.code,`/config/frontend/routes/${E}/code`),A]}));for(let[m,E]of e.workflows.definitions.entries()){let A=`/config/workflows/definitions/${m}`,b=N(E,A);if(T(b,["version","definition","launch"],A,["detailRouteCode"]),oa(b.launch,`${A}/launch`),b.detailRouteCode!==void 0){let S=ra(b.detailRouteCode,`${A}/detailRouteCode`);for(let[P,V,q]of[["desktop",S.desktop,["admin","user"]],["mobile",S.mobile,["user"]]]){let Z=`${A}/detailRouteCode/${P}`,X=r.get(V);X||_("NATIVE_WORKFLOW_DETAIL_ROUTE_MISSING",Z),q.some($=>$===X.surface)||_("NATIVE_WORKFLOW_DETAIL_ROUTE_SURFACE_INVALID",Z);let Ie=Re(X.path,Z),re=[...Ie.matchAll(/:([A-Za-z][A-Za-z0-9_]*)/g)].map($=>$[1]);(Ie.includes("*")||re.length!==1||re[0]!=="instanceId")&&_("NATIVE_WORKFLOW_DETAIL_ROUTE_PATH_INVALID",Z)}}let O=N(b.definition,`${A}/definition`),g=`${O.code}:${Nt(b.version,`${A}/version`)}`;t.has(g)&&_("NATIVE_WORKFLOW_DEFINITION_DUPLICATE",A),t.add(g),ul(O,`${A}/definition`);let y=nr(O);y.length&&_(y[0],`${A}/definition/launchPreflight`);let h=ls(O);h.length&&_(h[0],`${A}/definition/approvedDelegation`);let u=as(O,e.backend.operations);u.length&&_(u[0],`${A}/definition/commandHandlers`),ll(O.subject,n,`${A}/definition/subject`);let I=O.commandHandlers?.resubmit?.derivedSubjectFields||[],R=n.get(O.subject.resourceCode);for(let S of I){let P=R?.schema.fields.find(V=>V.code===S);(!P||P.system===!0||R?.surface?.fields?.[S]?.system===!0)&&_("WORKFLOW_CORRECTION_DERIVED_SUBJECT_FIELDS_INVALID",`${A}/definition/commandHandlers/resubmit/derivedSubjectFields`)}let w=$n(O,new Map((n.get(O.subject.resourceCode)?.schema.fields||[]).map(S=>[S.code,{...n.get(O.subject.resourceCode)?.surface?.fields?.[S.code],...S,system:["id","revision","createdAt","updatedAt","createdBy","updatedBy"].includes(S.code)}])),new Map([...n].map(([S,P])=>[S,new Map(P.schema.fields.map(V=>[V.code,{...P.surface?.fields?.[V.code],...V,system:["id","revision","createdAt","updatedAt","createdBy","updatedBy"].includes(V.code)}]))])),Zt(n.get(O.subject.resourceCode)?.schema||{}));w.length&&_(w[0],`${A}/definition/taskPages`);let C=Gi(O,{appCode:e.appCode,capabilities:e.authz.capabilities.map(S=>S.code),fields:new Map((n.get(O.subject.resourceCode)?.schema.fields||[]).map(S=>[S.code,S]))});C.length&&_("NATIVE_WORKFLOW_INSTANCE_COMMAND_POLICY_INVALID",`${A}/definition/instanceCommands`,{errors:C}),O.title===O.code&&_("NATIVE_WORKFLOW_USER_TITLE_REQUIRED",`${A}/definition/title`),o.set(g,O)}let i=new Set,a=new Map;for(let[m,E]of e.workflows.bindings.entries()){let A=N(E,`/config/workflows/bindings/${m}`),b=N(A.binding,`/config/workflows/bindings/${m}/binding`),O=`${b.workflowCode}:${Nt(A.version,`/config/workflows/bindings/${m}/version`)}`;i.has(O)&&_("NATIVE_WORKFLOW_BINDING_DUPLICATE",`/config/workflows/bindings/${m}`),i.add(O),fl(b,`/config/workflows/bindings/${m}/binding`),a.set(O,b)}let s=new Set,d=new Map;for(let[m,E]of e.workflows.activations.entries()){let A=`/config/workflows/activations/${m}`,b=N(E,A);T(b,["workflowCode","definitionVersion","bindingVersion","acceptedCommandDeactivationPolicy"],A,["environmentKey","sourceBase"]);let O=v(b.workflowCode,`${A}/workflowCode`);if(s.has(O)&&_("NATIVE_WORKFLOW_ACTIVATION_DUPLICATE",A),s.add(O),b.sourceBase!==void 0){let w=N(b.sourceBase,`${A}/sourceBase`);T(w,["definitionDigest","bindingDigest"],`${A}/sourceBase`);for(let C of["definitionDigest","bindingDigest"])/^(sha256:)?[a-f0-9]{64}$/.test(String(w[C]||""))||_("NATIVE_WORKFLOW_SOURCE_BASE_INVALID",`${A}/sourceBase/${C}`)}let g=`${O}:${Nt(b.definitionVersion,`${A}/definitionVersion`)}`,y=`${O}:${Nt(b.bindingVersion,`${A}/bindingVersion`)}`;t.has(g)||_("NATIVE_WORKFLOW_DEFINITION_REFERENCE_MISSING",`${A}/definitionVersion`),i.has(y)||_("NATIVE_WORKFLOW_BINDING_REFERENCE_MISSING",`${A}/bindingVersion`);let h=o.get(g),u=a.get(y),I=nr(h,u);I.length&&_(I[0],A);let R=Qo(h,u);R.length&&_(R[0],A),(!["finish-pinned","cancel-on-deactivate"].includes(b.acceptedCommandDeactivationPolicy)||b.acceptedCommandDeactivationPolicy!==h.acceptedCommandDeactivationPolicy)&&_("NATIVE_WORKFLOW_COMMAND_DEACTIVATION_POLICY_MISMATCH",`${A}/acceptedCommandDeactivationPolicy`),pl(h,u,`/config/workflows/activations/${m}`);try{let w=n.get(h.subject.resourceCode)?.schema.fields||[];Wr(h,u,new Map(w.map(C=>[C.code,C])),`${A}/bindings`,new Map([...n].map(([C,S])=>[C,new Map(S.schema.fields.map(P=>[P.code,P]))])))}catch(w){throw w instanceof Je&&_(w.code,w.pointer),w}d.set(O,u)}let c=bs([...d.values()]);c.length&&_(c[0],"/config/workflows/activations");let l=new Set;e.workflows.providers.forEach((m,E)=>{let A=`/config/workflows/providers/${E}`,b=N(m,A);T(b,["code","endpointPath","timeoutMs"],A,!0);let O=v(b.code,`${A}/code`);l.has(O)&&_("NATIVE_WORKFLOW_PROVIDER_DUPLICATE",`${A}/code`),l.add(O),Re(b.endpointPath,`${A}/endpointPath`),b.timeoutMs!==void 0&&ae(b.timeoutMs,`${A}/timeoutMs`,100,1e4)});for(let[m,E]of d.entries())for(let[A,b]of Object.entries(N(E.bindings,"/config/workflows/bindings/*/binding/bindings"))){let O=N(b,`/config/workflows/${m}/bindings/${A}`);O.provider==="application_provider"&&!l.has(O.providerCode)&&_("NATIVE_WORKFLOW_PROVIDER_REFERENCE_MISSING",`/config/workflows/${m}/bindings/${A}/providerCode`)}let f=new Set(e.authz.roles.map(m=>m.code)),p=new Set;e.workflows.editableParameters.forEach((m,E)=>{let A=`/config/workflows/editableParameters/${E}`,b=N(m,A);T(b,["code","workflowCode","bindingKey","label","valueType","required","allowedRoleCodes","allowedProviderCodes","maxItems"],A,!0);let O=v(b.code,`${A}/code`);p.has(O)&&_("NATIVE_WORKFLOW_EDITABLE_PARAMETER_DUPLICATE",`${A}/code`),p.add(O);let g=Gn(b.workflowCode,`${A}/workflowCode`),y=Mn(b.bindingKey,`${A}/bindingKey`),h=d.get(g);(!h||!N(h.bindings,`${A}/bindingKey`)[y])&&_("NATIVE_WORKFLOW_EDITABLE_BINDING_MISSING",`${A}/bindingKey`),D(b.label,`${A}/label`,255),["role_code","user_ids","provider_code"].includes(b.valueType)||_("NATIVE_WORKFLOW_EDITABLE_VALUE_TYPE_INVALID",`${A}/valueType`);for(let u of F(b.allowedRoleCodes||[],`${A}/allowedRoleCodes`,100))f.has(u)||_("NATIVE_ROLE_REFERENCE_MISSING",`${A}/allowedRoleCodes`);for(let u of F(b.allowedProviderCodes||[],`${A}/allowedProviderCodes`,100))l.has(u)||_("NATIVE_WORKFLOW_PROVIDER_REFERENCE_MISSING",`${A}/allowedProviderCodes`);b.required!==void 0&&ht(b.required,`${A}/required`),b.maxItems!==void 0&&ae(b.maxItems,`${A}/maxItems`,1,200)})}function ll(e,t,o){let n=N(e,o);T(n,["resourceCode","factProjection"],o,["summaryFields"]);let r=Y(n.resourceCode,`${o}/resourceCode`),i=t.get(r);i||_("NATIVE_WORKFLOW_SUBJECT_RESOURCE_MISSING",`${o}/resourceCode`);let a=new Set(k(N(i.schema,`${o}/resourceCode`).fields,`${o}/resourceCode`,500).map((c,l)=>G(N(c,`${o}/resourceCode/${l}`).code,`${o}/resourceCode/${l}`))),s=N(n.factProjection,`${o}/factProjection`),d=Object.entries(s);(d.length<1||d.length>64)&&_("NATIVE_WORKFLOW_SUBJECT_FACT_PROJECTION_INVALID",`${o}/factProjection`);for(let[c,l]of d){fc.test(c)||_("NATIVE_WORKFLOW_SUBJECT_FACT_KEY_INVALID",`${o}/factProjection/${c}`);let f=G(l,`${o}/factProjection/${c}`);a.has(f)||_("NATIVE_WORKFLOW_SUBJECT_FIELD_MISSING",`${o}/factProjection/${c}`)}if(n.summaryFields!==void 0){let c=F(n.summaryFields,`${o}/summaryFields`,pc).map((E,A)=>G(E,`${o}/summaryFields/${A}`)),l=t.get(r),f=l.surface&&typeof l.surface=="object"&&!Array.isArray(l.surface)?l.surface:{},p=f.fields&&typeof f.fields=="object"&&!Array.isArray(f.fields)?f.fields:{},m=new Map(k(N(l.schema,`${o}/resourceCode`).fields,`${o}/resourceCode`,500).map((E,A)=>{let b=N(E,`${o}/resourceCode/${A}`);return[String(b.code),b]}));for(let[E,A]of c.entries()){let b=m.get(A),O=p[A],g=String(b?.type||""),y=b?.maxLength;(!b||b.system===!0||O&&typeof O=="object"&&!Array.isArray(O)&&O.system===!0||["id","revision","created_by","updated_by","created_at","updated_at"].includes(A)||!_c.has(g)||g==="text.long"&&typeof y=="number"&&Number.isFinite(y)&&y>mc)&&_("NATIVE_WORKFLOW_SUBJECT_SUMMARY_FIELDS_INVALID",`${o}/summaryFields/${E}`)}}}function ul(e,t){T(e,["schemaVersion","code","title","subject","acceptedCommandDeactivationPolicy","startAt","inputSchema","nodes"],t,["organizationContext","instanceCommands","readability","taskPages","rejectionNotification","commandHandlers","launchPreflight","approvedDelegation"]),W(e.schemaVersion,"openxiangda.workflow-definition/v2",`${t}/schemaVersion`),Gn(e.code,`${t}/code`),D(e.title,`${t}/title`,255),["finish-pinned","cancel-on-deactivate"].includes(e.acceptedCommandDeactivationPolicy)||_("NATIVE_WORKFLOW_COMMAND_DEACTIVATION_POLICY_REQUIRED",`${t}/acceptedCommandDeactivationPolicy`);let o=N(e.nodes,`${t}/nodes`),n=Object.keys(o);(n.length===0||n.length>200)&&_("NATIVE_WORKFLOW_NODE_COUNT_INVALID",`${t}/nodes`);let r=D(e.startAt,`${t}/startAt`,128),i=qi(e);i.length&&_(i[0],`${t}/readability`);let a=Qo(e);a.length&&_(a[0],`${t}/nodes`);let s=er(e);s.length&&_(s[0],`${t}/nodes`);let d=xt(e);d.length&&_(d[0],`${t}/nodes`);let c=rs(e);c.length&&_(c[0],`${t}/nodes`);let l=ss(e);l.length&&_(l[0],`${t}/rejectionNotification`);let f=Xo(e);f.length&&_(f[0],`${t}/nodes`);let p=$n(e);p.length&&_(p[0],`${t}/taskPages`);let m=In(e);m.length&&_(m[0],`${t}/nodes`);let E=En(e);E.length&&_(E[0],`${t}/nodes`);let A=On(e);A.length&&_(A[0],`${t}/nodes`);let b=yn(e);b.length&&_(b[0],`${t}/nodes`);let O=_n(e);O.length&&_(O[0],`${t}/nodes`),o[r]||_("NATIVE_WORKFLOW_START_NODE_MISSING",`${t}/startAt`);let g=new Map;for(let[I,R]of Object.entries(o)){let w=`${t}/nodes/${I}`,C=N(R,w);W(C.id,I,`${w}/id`),["approval","handle","condition","end","cc","action","correction","parallel","join"].includes(C.kind)||_("NATIVE_WORKFLOW_NODE_KIND_INVALID",`${w}/kind`);let S=[];if(C.kind==="approval"||C.kind==="handle"){D(C.title,`${w}/title`,255),Mn(C.binding,`${w}/binding`),["single","any","all","sequence"].includes(C.mode)||_("NATIVE_WORKFLOW_APPROVAL_MODE_INVALID",`${w}/mode`),C.kind==="handle"?S.push(D(C.next,`${w}/next`,128)):S.push(D(C.onApprove,`${w}/onApprove`,128),D(C.onReject,`${w}/onReject`,128));for(let P of F(C.returnTargets||[],`${w}/returnTargets`,200))o[P]||_("NATIVE_WORKFLOW_TARGET_MISSING",`${w}/returnTargets`);for(let P of F(C.allowedOperations||[],`${w}/allowedOperations`,20))Ac.has(P)||_("NATIVE_WORKFLOW_OPERATION_INVALID",`${w}/allowedOperations`)}else if(C.kind==="correction"){let P=us(e);P.length&&_(P[0],w)}else if(C.kind==="action")S.push(D(C.next,`${w}/next`,128));else if(C.kind==="cc")D(C.title,`${w}/title`,255),Mn(C.binding,`${w}/binding`),S.push(D(C.next,`${w}/next`,128));else if(C.kind==="parallel"){D(C.title,`${w}/title`,255),S.push(D(C.join,`${w}/join`,128));for(let[P,V]of k(C.branches,`${w}/branches`,8).entries()){let q=N(V,`${w}/branches/${P}`);q.when!==void 0&&bt(q.when,`${w}/branches/${P}/when`,0),S.push(D(q.target,`${w}/branches/${P}/target`,128))}}else if(C.kind==="join")D(C.title,`${w}/title`,255),S.push(D(C.next,`${w}/next`,128));else if(C.kind==="condition"){let P=k(C.branches,`${w}/branches`,100);P.length===0&&_("NATIVE_WORKFLOW_BRANCH_REQUIRED",`${w}/branches`),P.forEach((V,q)=>{let Z=N(V,`${w}/branches/${q}`);bt(Z.when,`${w}/branches/${q}/when`,0),S.push(D(Z.target,`${w}/branches/${q}/target`,128))}),S.push(D(C.otherwise,`${w}/otherwise`,128))}else D(C.title,`${w}/title`,255),D(C.outcome,`${w}/outcome`,128);for(let P of S)o[P]||_("NATIVE_WORKFLOW_TARGET_MISSING",w);g.set(I,S)}let y=new Set,h=new Set,u=I=>{if(h.has(I)&&_("NATIVE_WORKFLOW_CYCLE_FORBIDDEN",`${t}/nodes/${I}`),!y.has(I)){y.add(I),h.add(I);for(let R of g.get(I)||[])u(R);h.delete(I)}};u(r);for(let I of[...y]){let R=o[I];if(R?.kind==="approval"||R?.kind==="handle")for(let w of xe(R))o[w]?.kind==="correction"&&y.add(w)}y.size!==n.length&&_("NATIVE_WORKFLOW_NODE_UNREACHABLE",`${t}/nodes`)}function bt(e,t,o){o>20&&_("NATIVE_WORKFLOW_EXPRESSION_DEPTH_EXCEEDED",t);let n=N(e,t),r=D(n.op,`${t}/op`,16);if(r!=="literal"){if(r==="path"){let i=D(n.path,`${t}/path`,255);(!/^[A-Za-z][A-Za-z0-9_.-]{0,254}$/.test(i)||i.split(".").some(a=>["__proto__","constructor","prototype"].includes(a)))&&_("NATIVE_WORKFLOW_EXPRESSION_PATH_INVALID",`${t}/path`);return}if(["eq","neq","gt","gte","lt","lte","in","contains"].includes(r)){bt(n.left,`${t}/left`,o+1),bt(n.right,`${t}/right`,o+1);return}if(["and","or"].includes(r)){let i=k(n.values,`${t}/values`,100);i.length===0&&_("NATIVE_WORKFLOW_EXPRESSION_EMPTY",`${t}/values`),i.forEach((a,s)=>bt(a,`${t}/values/${s}`,o+1));return}if(["not","exists"].includes(r)){bt(n.value,`${t}/value`,o+1);return}_("NATIVE_WORKFLOW_EXPRESSION_OPERATOR_INVALID",`${t}/op`)}}function fl(e,t){W(e.schemaVersion,"openxiangda.workflow-binding/v2",`${t}/schemaVersion`),Gn(e.workflowCode,`${t}/workflowCode`);let o=N(e.bindings,`${t}/bindings`);Object.keys(o).length>200&&_("NATIVE_WORKFLOW_BINDING_LIMIT_EXCEEDED",`${t}/bindings`);for(let[n,r]of Object.entries(o)){Mn(n,`${t}/bindings/${n}`);let i=N(r,`${t}/bindings/${n}`),a=gn(i);a.length&&_(a[0],`${t}/bindings/${n}`);let s=Hi(i);s.length&&_(s[0],`${t}/bindings/${n}/selectedInputPath`);let d=Cn(i);d.length&&_(d[0],`${t}/bindings/${n}/roleCodes`);let c=D(i.provider,`${t}/bindings/${n}/provider`,64);if(["fixed_users","initiator","input_users","form_field_users","department_supervisor","supervisor_chain","app_role","app_role_in_scope","business_relation","previous_node_actor","initiator_select","application_provider"].includes(c)||_("NATIVE_WORKFLOW_BINDING_PROVIDER_INVALID",`${t}/bindings/${n}/provider`),c==="fixed_users"&&(Array.isArray(i.users)||_("NATIVE_WORKFLOW_BINDING_USERS_REQUIRED",`${t}/bindings/${n}/users`),k(i.users,`${t}/bindings/${n}/users`,200)),["input_users","form_field_users"].includes(c)&&D(i.inputPath,`${t}/bindings/${n}/inputPath`,255),["app_role","app_role_in_scope","initiator_select"].includes(c)&&i.roleCodes===void 0&&v(i.roleCode,`${t}/bindings/${n}/roleCode`),c==="department_supervisor"&&D(i.departmentIdFrom,`${t}/bindings/${n}/departmentIdFrom`,255),c==="application_provider"&&v(i.providerCode,`${t}/bindings/${n}/providerCode`),i.routing!==void 0){let l=Pn(i.routing);l.length&&_(l[0],`${t}/bindings/${n}/routing`)}}}function pl(e,t,o){let n=An(e,t);n.length&&_(n[0],o),W(t.workflowCode,e.code,`${o}/workflowCode`);let r=N(t.bindings,`${o}/bindings`);for(let[d,c]of Object.entries(r))c.provider==="fixed_users"&&!c.users.length&&!ns(e,d)&&_("NATIVE_WORKFLOW_BINDING_USERS_REQUIRED",`${o}/bindings/${d}/users`);let i=er(e,t);i.length&&_(i[0],o);let a=Xo(e,t);a.length&&_(a[0],o);let s=_n(e,t);s.length&&_(s[0],o);for(let[d,c]of Object.entries(N(e.nodes,`${o}/nodes`))){let l=N(c,`${o}/nodes/${d}`);["approval","handle","cc"].includes(l.kind)&&!r[l.binding]&&_("NATIVE_WORKFLOW_BINDING_REFERENCE_MISSING",`${o}/nodes/${d}/binding`)}}function ml(e,t,o){let n=N(t.routeManifest,"/contracts/routeManifest"),r=N(e.routeManifest,"/contracts/routeManifest"),i=new Map;for(let l of k(o.data?.resources,"/config/data/resources",B.resources)){let f=N(l,"/config/data/resources");i.set(String(f.code||""),f)}let a=new Set(k(r.routes,"/contracts/routeManifest/routes",B.routes).map(l=>String(N(l,"/contracts/routeManifest/routes").code||""))),s=[];for(let l of k(n.routes,"/contracts/routeManifest/routes",B.routes)){let f=N(l,"/contracts/routeManifest/routes"),p=String(f.kind||"");if(p!=="resource-records"&&p!=="resource-submit")continue;let m=String(f.resourceCode||""),E=i.get(m);E||_("NATIVE_ROUTE_MANIFEST_RESOURCE_UNKNOWN","/contracts/routeManifest/routes");let b=`user.${m}.${p==="resource-records"?"records":"submit"}`;W(String(f.code||""),b,"/contracts/routeManifest/routes/code");let O=p==="resource-records"?"read":"create",g=String(N(E.capabilities,"/config/data/resources/capabilities")[O]||"");for(let y of["desktop","mobile"]){let h=N(f[y],`/contracts/routeManifest/routes/${y}`),u=y==="mobile"?"/m/my/":"/my/",I=p==="resource-records"?`${u}${m}`:`${u}${m}/submit`;W(String(h.path||""),I,`/contracts/routeManifest/routes/${y}/path`),W(String(h.capability||""),g,`/contracts/routeManifest/routes/${y}/capability`),W(String(h.routeCode||""),`${b}.${y}`,`/contracts/routeManifest/routes/${y}/routeCode`)}(a.has(b)||s.some(y=>String(y.code)===b))&&_("NATIVE_ROUTE_MANIFEST_DUPLICATE","/contracts/routeManifest/routes/code"),s.push(f)}if(!s.length)return;r.routes=k([...r.routes,...s],"/contracts/routeManifest/routes",1e3).sort((l,f)=>be(String(N(l,"x").code||""),String(N(f,"x").code||"")));let d=String(N(n.rootEntry,"x").code||"");if(s.find(l=>String(l.code)===d&&l.kind==="resource-records")){let l=N(n.rootEntry,"x");r.rootEntry={code:d,desktop:String(l.desktop||""),mobile:String(l.mobile||"")}}r.digest=ee({schemaVersion:r.schemaVersion,appCode:r.appCode,devicePolicy:r.devicePolicy,rootEntry:r.rootEntry,authentication:r.authentication,routes:r.routes})}function nt(e,t,o){let n=N(e,t);T(n,["schemaVersion","appCode","code","name","schema","surface","invariants","decimalReservationLifecycle","uniqueKeys","workflowHistory","recordPrint","recordComments","recordDeletion","capabilities","dataPolicyCode","fieldPolicies"],t,!0),W(n.schemaVersion,"openxiangda.data-resource/v2",`${t}/schemaVersion`),W(n.appCode,o,`${t}/appCode`);let r=Y(n.code,`${t}/code`),i=D(n.name,`${t}/name`,255),a=N(n.schema,`${t}/schema`);T(a,["fields","ownedRowLimit"],`${t}/schema`,!0),a.ownedRowLimit!==void 0&&!wt(a.ownedRowLimit)&&_("NATIVE_DATA_OWNED_ROW_LIMIT_INVALID",`${t}/schema/ownedRowLimit`);let s,d,c,l;try{c=ko(n.decimalReservationLifecycle,`${t}/decimalReservationLifecycle`),s=Ao(a.fields,`${t}/schema/fields`),l=Wi(n.uniqueKeys,s,`${t}/uniqueKeys`),d=Jr(n.invariants,s,`${t}/invariants`),wo(n.surface,s,`${t}/surface`)}catch(E){throw(E instanceof Ce||E instanceof Je||E instanceof pt||E instanceof Ft)&&_(E.code,E.pointer),E}if(n.recordComments!==void 0){let E=N(n.recordComments,`${t}/recordComments`);T(E,["read","create"],`${t}/recordComments`);for(let A of["read","create"]){let b=E[A];(!Array.isArray(b)||b.length>20||b.some(O=>typeof O!="string"||!O.trim())||new Set(b).size!==b.length)&&_("NATIVE_RECORD_COMMENTS_POLICY_INVALID",`${t}/recordComments/${A}`)}}if(n.recordDeletion!==void 0){let E=N(n.recordDeletion,`${t}/recordDeletion`);T(E,["delete"],`${t}/recordDeletion`);let A=E.delete;(!Array.isArray(A)||A.length>20||A.some(b=>typeof b!="string"||!b.trim())||new Set(A).size!==A.length)&&_("NATIVE_RECORD_DELETION_DELETE_INVALID",`${t}/recordDeletion/delete`)}if(n.recordPrint!==void 0){let E=N(n.recordPrint,`${t}/recordPrint`);T(E,["read"],`${t}/recordPrint`);let A=E.read;(!Array.isArray(A)||A.length>20||A.some(b=>typeof b!="string"||!b.trim())||new Set(A).size!==A.length)&&_("NATIVE_RECORD_PRINT_READ_INVALID",`${t}/recordPrint/read`)}if(n.workflowHistory!==void 0){let E=N(n.workflowHistory,`${t}/workflowHistory`);T(E,["read"],`${t}/workflowHistory`);let A=E.read;(!Array.isArray(A)||A.length>20||A.some(b=>typeof b!="string"||!b.trim())||new Set(A).size!==A.length)&&_("NATIVE_WORKFLOW_HISTORY_READ_INVALID",`${t}/workflowHistory/read`)}let f=new Set(s.map(E=>E.code)),p=N(n.capabilities,`${t}/capabilities`);T(p,["read","create","update","delete"],`${t}/capabilities`);let m=N(n.fieldPolicies,`${t}/fieldPolicies`);for(let[E,A]of Object.entries(m)){!f.has(E)&&!Tt(E)&&_("NATIVE_DATA_FIELD_POLICY_FIELD_MISSING",`${t}/fieldPolicies/${E}`);let b=`${t}/fieldPolicies/${E}`,O=N(A,b);Tt(E)&&(T(O,["read"],b,!0),(!Array.isArray(O.read)||O.read.length>20||O.read.some(g=>typeof g!="string"||!g.trim())||new Set(O.read).size!==O.read.length)&&_("NATIVE_DATA_AUDIT_READ_POLICY_INVALID",`${b}/read`)),T(O,["read","create","update","mask"],b,!0),O.mask!==void 0&&!["omit","null"].includes(O.mask)&&_("NATIVE_DATA_FIELD_POLICY_MASK_INVALID",`${b}/mask`)}return{...n,code:r,name:i,schema:{fields:s,...a.ownedRowLimit!==void 0?{ownedRowLimit:a.ownedRowLimit}:{}},...n.invariants===void 0?{}:{invariants:d},...c?{decimalReservationLifecycle:c}:{},...l!==void 0?{uniqueKeys:l}:{},capabilities:p,fieldPolicies:m}}function ia(e){return[{code:`app:${e}:directory:read`,kind:"platform",name:"\u8BFB\u53D6\u53D7\u9650\u7EC4\u7EC7\u76EE\u5F55",source:"platform"},...[["app:role:read","\u67E5\u770B\u89D2\u8272\u4E0E\u6388\u6743"],["app:role:define","\u5B9A\u4E49\u624B\u5DE5\u89D2\u8272"],["app:role:assign","\u5206\u914D\u89D2\u8272\u6210\u5458"],["app:role:grant-capability","\u6388\u4E88\u89D2\u8272\u80FD\u529B"],["app:scope-grant:manage","\u7BA1\u7406\u6570\u636E\u8303\u56F4"],["app:super-admin:manage","\u7BA1\u7406\u5E94\u7528\u6700\u9AD8\u7BA1\u7406\u5458"]].map(([t,o])=>({code:t,kind:"platform",name:o,source:"platform"}))]}function Us(e,t,o,n){let r=e.toString("utf8"),i;try{i=JSON.parse(r)}catch{_(o,t)}let a=N(i,t);return Q(a)!==r&&_(n,t),a}function Wn(e,t,o){let n=0,r=(i,a,s)=>{if(n+=1,n>o&&_("NATIVE_ARTIFACT_NODE_LIMIT_EXCEEDED",a),s>yc&&_("NATIVE_ARTIFACT_DEPTH_LIMIT_EXCEEDED",a),typeof i=="string"){Buffer.byteLength(i)>mr&&_("NATIVE_ARTIFACT_STRING_LIMIT_EXCEEDED",a);return}if(Array.isArray(i)){i.forEach((d,c)=>r(d,`${a}/${c}`,s+1));return}if(!(!i||typeof i!="object"))for(let[d,c]of Object.entries(i))["__proto__","prototype","constructor"].includes(d)&&_("NATIVE_ARTIFACT_DANGEROUS_KEY",`${a}/${d}`),_l(d)&&_("NATIVE_ARTIFACT_RUNTIME_FIELD_FORBIDDEN",`${a}/${d}`),r(c,`${a}/${d}`,s+1)};r(e,t,0)}function _l(e){return["environmentKey","environmentId","secretValue","ciphertext","oauthClient","oauthClientId","oauthClientSecret","signingSecret","kubernetesNamespace","nodePort","productionUrl"].includes(e)}function Ot(e){return{value:e,digest:ee(e)}}function Bs(e,t,o,n){typeof e!="string"&&!Buffer.isBuffer(e)&&!(e instanceof Uint8Array)&&_("NATIVE_ARTIFACT_BYTES_REQUIRED",o);let r=Buffer.isBuffer(e)?e:Buffer.from(e);return r.byteLength===0&&_("NATIVE_ARTIFACT_EMPTY",o),r.byteLength>t&&_(n,o),r}function Ks(e,t,o,n){let r=Un.createHash("sha256").update(e).digest("hex");Un.timingSafeEqual(Buffer.from(r),Buffer.from(t))||_(n,o)}function N(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&_("NATIVE_OBJECT_REQUIRED",t),e}function k(e,t,o){return Array.isArray(e)||_("NATIVE_ARRAY_REQUIRED",t),e.length>o&&_("NATIVE_ARRAY_LIMIT_EXCEEDED",t),e}function F(e,t,o){let n=k(e,t,o).map((r,i)=>D(r,`${t}/${i}`,255));return new Set(n).size!==n.length&&_("NATIVE_ARRAY_DUPLICATE",t),n}function D(e,t,o){return(typeof e!="string"||e.length===0||e.length>o)&&_("NATIVE_STRING_INVALID",t),e}function br(e,t,o){return(typeof e!="string"||e.length>o)&&_("NATIVE_STRING_INVALID",t),e}function v(e,t){let o=D(e,t,128);return rc.test(o)||_("NATIVE_CODE_INVALID",t),o}function Y(e,t){let o=D(e,t,64);return sc.test(o)||_("NATIVE_RESOURCE_CODE_INVALID",t),o}function G(e,t){let o=D(e,t,63);return ac.test(o)||_("NATIVE_FIELD_CODE_INVALID",t),o}function Gn(e,t){let o=D(e,t,128);return lc.test(o)||_("NATIVE_WORKFLOW_CODE_INVALID",t),o}function Mn(e,t){let o=D(e,t,128);return uc.test(o)||_("NATIVE_WORKFLOW_BINDING_CODE_INVALID",t),o}function ge(e,t,o){let n=D(e,t,255);return oc.test(n)||_("NATIVE_CAPABILITY_CODE_INVALID",t),!n.startsWith(`app:${o}:`)&&!ia(o).some(r=>r.code===n)&&_("NATIVE_CAPABILITY_APP_MISMATCH",t),n}function Re(e,t){let o=D(e,t,2048);return(!o.startsWith("/")||o.startsWith("//")||o.includes("..")||o.includes("?")||o.includes("#"))&&_("NATIVE_ABSOLUTE_PATH_INVALID",t),o}function Nt(e,t){return(!Number.isInteger(e)||Number(e)<1)&&_("NATIVE_POSITIVE_INTEGER_REQUIRED",t),Number(e)}function ae(e,t,o,n){return(!Number.isInteger(e)||Number(e)<o||Number(e)>n)&&_("NATIVE_INTEGER_OUT_OF_RANGE",t),Number(e)}function ht(e,t){return typeof e!="boolean"&&_("NATIVE_BOOLEAN_REQUIRED",t),e}function Er(e,t){let o=D(e,t,64).toLowerCase();return tc.test(o)||_("NATIVE_DIGEST_INVALID",t),o}function W(e,t,o){e!==t&&_("NATIVE_VALUE_MISMATCH",o)}function T(e,t,o,n=!1){let r=new Set([...t,...Array.isArray(n)?n:[]]);for(let i of Object.keys(e))r.has(i)||_("NATIVE_PROPERTY_UNKNOWN",`${o}/${i}`);if(n!==!0)for(let i of t)Object.prototype.hasOwnProperty.call(e,i)||_("NATIVE_PROPERTY_REQUIRED",`${o}/${i}`)}function ne(e,t){return[...e].sort((o,n)=>be(t(o),t(n)))}function U(e){return[...new Set(e)].sort(be)}function Gs(e){return[...new Set(e)].sort((t,o)=>t-o)}function be(e,t){return e===t?0:e<t?-1:1}function sa(e){return!e||typeof e!="object"||Object.isFrozen(e)||(Object.freeze(e),Object.values(e).forEach(t=>sa(t))),e}function Ir(e,t,o){if(pr(e,t))return o;if(Array.isArray(e)&&Array.isArray(t)){let n=Math.max(e.length,t.length);for(let r=0;r<n;r+=1)if(!pr(e[r],t[r]))return Ir(e[r],t[r],`${o}/${r}`)}if(e&&t&&typeof e=="object"&&typeof t=="object"&&!Array.isArray(e)&&!Array.isArray(t)){let n=U([...Object.keys(e),...Object.keys(t)]);for(let r of n){let i=e[r],a=t[r];if(!pr(i,a))return Ir(i,a,`${o}/${r}`)}}return o}function pr(e,t){return e===void 0||t===void 0?e===t:Q(e)===Q(t)}function _(e,t,o={}){throw new gr(e,t,o)}var Km="openxiangda.workflow-step-data-command/v1",gl="openxiangda.workflow-step-data-resolution/v1";function Gm(e,t,o=!1){let n=s=>!!s&&typeof s=="object"&&!Array.isArray(s),r=s=>typeof s=="string"&&/^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(s),i=()=>{throw new Error("WORKFLOW_STEP_DATA_RESPONSE_INVALID")};if(!n(e)||e.schemaVersion!==gl||e.executionId!==t||Object.keys(e).some(s=>!["schemaVersion","executionId","outcome","transaction"].includes(s)))return i();if(e.outcome==="not_observed"&&!Object.hasOwn(e,"transaction")&&!o)return e;let a=e.transaction;if(e.outcome!=="committed"||!n(a)||a.schemaVersion!=="openxiangda.data-transaction-result/v2"||a.idempotencyKey!==`workflow-step:${t}`||typeof a.replayed!="boolean"||!Array.isArray(a.items)||a.items.length<1||a.items.length>jr||a.evaluatedAt!==void 0&&(typeof a.evaluatedAt!="string"||!Number.isFinite(Date.parse(a.evaluatedAt))))return i();for(let[s,d]of a.items.entries()){if(!n(d)||d.index!==s)return i();if(d.operation==="emitEvent"){if(typeof d.eventType!="string"||!d.eventType||!r(d.eventId))return i()}else if(!["create","update","delete","increment"].includes(d.operation)||typeof d.resourceCode!="string"||!d.resourceCode||!r(d.id)||!Number.isSafeInteger(d.revision)||d.revision<1)return i()}return e}var zm=50,Jm=131072,Nr=class extends Error{constructor(o){super("OPENXIANGDA_NATIVE_AUTHZ_BATCH_INPUT_INVALID");this.pointer=o}pointer;code="OPENXIANGDA_NATIVE_AUTHZ_BATCH_INPUT_INVALID";status=400};function Hm(e){let t=f=>{throw new Nr(f)},o=(f,p)=>((!f||typeof f!="object"||Array.isArray(f))&&t(p),f),n=(f,p,m)=>{for(let E of Object.keys(f))p.includes(E)||t(`${m}/${E}`)},r=(f,p,m)=>((typeof f!="string"||!f.trim()||f.length>p)&&t(m),f),i=(f,p)=>{let m=r(f,36,p);return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(m)||t(p),m.toLowerCase()},a=o(e,""),s;try{s=new TextEncoder().encode(JSON.stringify(a)).byteLength}catch{t("")}s>131072&&t(""),n(a,["schemaVersion","environmentKey","items"],""),a.schemaVersion!=="openxiangda.native-role-membership-batch-request/v2"&&t("/schemaVersion"),a.environmentKey!==void 0&&!["preproduction","production"].includes(String(a.environmentKey))&&t("/environmentKey"),(!Array.isArray(a.items)||a.items.length<1||a.items.length>50)&&t("/items");let d=new Set,c=new Set,l;for(let[f,p]of a.items.entries()){let m=`/items/${f}`,E=o(p,m);["create","update","revoke"].includes(String(E.operation))||t(`${m}/operation`),l??=E.operation,l!==E.operation&&t(`${m}/operation`),n(E,["operation","operationId","reason",...l==="create"?["userId","roleCode"]:["membershipId","expectedRevision"],...l!=="revoke"?["scopeGrants","validFrom","validTo"]:[]],m);let A=i(E.operationId,`${m}/operationId`);d.has(A)&&t(`${m}/operationId`),d.add(A),r(E.reason,1e3,`${m}/reason`);let b;if(l==="create"){let O=r(E.userId,255,`${m}/userId`),g=r(E.roleCode,128,`${m}/roleCode`);/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/.test(g)||t(`${m}/roleCode`),b=JSON.stringify([O,g])}else b=i(E.membershipId,`${m}/membershipId`),(!Number.isSafeInteger(E.expectedRevision)||Number(E.expectedRevision)<1)&&t(`${m}/expectedRevision`);c.has(b)&&t(m),c.add(b),E.scopeGrants!==void 0&&(!Array.isArray(E.scopeGrants)||E.scopeGrants.length>100)&&t(`${m}/scopeGrants`);for(let O of["validFrom","validTo"])E[O]!==void 0&&E[O]!==null&&r(E[O],64,`${m}/${O}`)}}var la="openxiangda.workflow-delegation-administration/v2",ua="openxiangda.workflow-delegation-mutation/v2",aa="openxiangda.workflow-delegation-preview/v2";var Ht={type:"string",format:"uuid",pattern:"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$"},Ae={type:"string",minLength:1,maxLength:255},ot={type:"string",format:"date-time"},Rt={type:"integer",minimum:1},Al={anyOf:[ot,{type:"null"}]},hr={anyOf:[Ae,{type:"null"}]},fa={anyOf:[{type:"string",pattern:"^[A-Za-z0-9._:-]{1,128}$"},{type:"null"}]},qn={type:"string",pattern:"^membership:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},pa={const:"future-assignments-only"},Rr={schemaVersion:{const:la},id:Ht,appCode:Ae,environmentKey:Ae,workflowCode:hr,nodeId:fa,delegatorUserId:Ae,delegateUserId:Ae,delegatorRoleSubjectKey:qn,delegateRoleSubjectKey:qn,validFrom:ot,validTo:ot,status:{enum:["active","revoked","expired"]},reason:{type:"string",minLength:1,maxLength:4e3},createdBy:Ae,createdAt:ot,revokedAt:Al,revision:Rt,roleCode:Ae,roleName:Ae,delegatorDisplayName:Ae,delegateDisplayName:Ae,delegatorRoleSubjectRevision:Rt,delegateRoleSubjectRevision:Rt,effectiveState:{enum:["active","scheduled","expired","revoked","ineligible"]},evaluatedAt:ot,issues:{type:"array",maxItems:20,uniqueItems:!0,items:Ae},canRevoke:{type:"boolean"},revokedBy:hr,revokeReason:{type:["string","null"],maxLength:4e3},taskPolicy:pa},wr={type:"object",additionalProperties:!1,required:Object.keys(Rr).filter(e=>e!=="nodeId"),properties:Rr},Xm={$id:la,...wr},ma={schemaVersion:{const:ua},operationId:Ht,environmentKey:{enum:["preproduction","production"]},reason:{type:"string",minLength:1,maxLength:2e3,pattern:"\\S"}},da={...ma,operation:{const:"create"},workflowCode:hr,nodeId:fa,delegatorRoleSubjectKey:qn,expectedDelegatorRevision:Rt,delegateUserId:Ae,delegateRoleSubjectKey:qn,expectedDelegateRevision:Rt,validFrom:ot,validTo:ot},ca={...ma,operation:{const:"revoke"},delegationId:Ht,expectedRevision:Rt},El={$id:ua,type:"object",oneOf:[{type:"object",additionalProperties:!1,required:Object.keys(da).filter(e=>e!=="nodeId"),properties:da,if:{required:["nodeId"],properties:{nodeId:{type:"string"}}},then:{properties:{workflowCode:Ae}}},{type:"object",additionalProperties:!1,required:Object.keys(ca),properties:ca}]},Il={type:"string",pattern:"^[0-9a-f]{64}$"},Zm={$id:aa,type:"object",additionalProperties:!1,required:["schemaVersion","operationId","operation","requestDigest","before","after","taskPolicy"],properties:{schemaVersion:{const:aa},operationId:Ht,operation:{enum:["create","revoke"]},requestDigest:Il,before:{anyOf:[wr,{type:"null"}]},after:{...wr,properties:{...Rr,id:{anyOf:[Ht,{type:"null"}]}}},taskPolicy:pa}};function t_(e){return e===void 0?"":`
9
+ ${ee(e)}`}function n_(e,t){let o=e.handlers.find(n=>n.code===t);return ee(o?.workflowStep?o:e)}var r_="openxiangda.data-business-command/v1",yl="openxiangda.data-business-command-resolution/v1",i_=65536;function s_(e){let t=0,o=0,n=new Set,r=new TextEncoder,i=()=>{throw new Error("OPENXIANGDA_DATA_COMMAND_INTENT_INVALID")},a=d=>(o+=r.encode(d).byteLength,o>65536&&i(),d),s=(d,c)=>{if(++t>1e4||c>32)return i();if(d===null||typeof d=="string"||typeof d=="boolean")return a(JSON.stringify(d));if(typeof d=="number")return Number.isFinite(d)?a(JSON.stringify(d)):i();if(!d||typeof d!="object"||n.has(d)||Object.getOwnPropertySymbols(d).length)return i();n.add(d);let l;if(Array.isArray(d))return Object.keys(d).length!==d.length?i():(l=a("[")+d.map((p,m)=>(m?a(","):"")+s(p,c+1)).join("")+a("]"),n.delete(d),l);let f=Object.getPrototypeOf(d);return f!==Object.prototype&&f!==null?i():(l=a("{")+Object.keys(d).sort().map((p,m)=>(m?a(","):"")+a(JSON.stringify(p))+a(":")+s(d[p],c+1)).join("")+a("}"),n.delete(d),l)};return!e||typeof e!="object"||Array.isArray(e)?i():s(e,0)}function a_(e,t,o=!1){let n=e,r=()=>{throw new Error("OPENXIANGDA_DATA_COMMAND_RESPONSE_INVALID")};if(!n||typeof n!="object"||n.schemaVersion!==yl)return r();for(let d of["appCode","environmentKey","operationCode","idempotencyKey","intentDigest"])if(n[d]!==t[d])return r();if(typeof n.observedAt!="string"||!Number.isFinite(Date.parse(n.observedAt)))return r();if(n.outcome==="not_observed"&&n.receipt===null&&!o)return n;if(n.outcome!=="committed"||!n.receipt)return r();let i=n.receipt,a=d=>typeof d=="string"&&/^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(d);if(!a(i.id)||!a(i.appVersionId)||!Number.isSafeInteger(i.environmentHeadRevision)||i.environmentHeadRevision<1||typeof i.completedAt!="string"||!Number.isFinite(Date.parse(i.completedAt)))return r();let s=i.transaction;if(!s||s.schemaVersion!=="openxiangda.data-transaction-result/v2"||s.idempotencyKey!==t.idempotencyKey||typeof s.replayed!="boolean"||!Array.isArray(s.items)||!s.items.length||s.items.length>1e3)return r();for(let[d,c]of s.items.entries()){if(!c||c.index!==d)return r();if(c.operation==="emitEvent"){if(!a(c.eventId)||typeof c.eventType!="string"||!c.eventType)return r()}else if(!["create","update","delete","increment"].includes(c.operation)||!a(c.id)||typeof c.resourceCode!="string"||!c.resourceCode||!Number.isSafeInteger(c.revision)||c.revision<1)return r()}return n}var _a=/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/,zn=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Yt=(e,t)=>typeof e=="string"&&e.length<=t&&e.trim().length>0&&e===e.trim(),Tr=(e,t,o=[])=>t.every(n=>Object.hasOwn(e,n))&&Object.keys(e).every(n=>[...t,...o].includes(n));function c_(e){if(!zn(e)||!Tr(e,["kind","errorCode","anyOf"],["allowAppSuperAdmin"])||e.kind!=="actor-authority"||!Yt(e.errorCode,110)||!/^OPENXIANGDA_[A-Z0-9_]{1,96}$/.test(e.errorCode)||Object.hasOwn(e,"allowAppSuperAdmin")&&typeof e.allowAppSuperAdmin!="boolean"||!Array.isArray(e.anyOf)||e.anyOf.length<1||e.anyOf.length>20)return!1;let t=new Set;return e.anyOf.every(o=>{if(!zn(o)||!Tr(o,["roleCode"],["scope"])||!Yt(o.roleCode,100)||!_a.test(o.roleCode))return!1;if(Object.hasOwn(o,"scope")){let i=o.scope;if(!zn(i)||!Tr(i,["dimensionCode","value","operation"])||!Yt(i.dimensionCode,100)||!_a.test(i.dimensionCode)||!Yt(i.value,255)||!Yt(i.operation,64)||!/^[A-Za-z0-9*][A-Za-z0-9*._:-]*$/.test(i.operation))return!1}let n=o.scope,r=JSON.stringify([o.roleCode,n?.dimensionCode,n?.value,n?.operation]);return t.has(r)?!1:(t.add(r),!0)})}function l_(e,t,o){if(t.roleSource!=="package"||t.roleCode!==e.roleCode||!o||!t.capabilityCodes.includes(o))return!1;if(!e.scope)return!0;let n;try{n=JSON.parse(t.scopeGrantsJson)}catch{return!1}if(!Array.isArray(n))return!1;let r=e.scope;return n.some(i=>zn(i)&&i.dimensionCode===r.dimensionCode&&Array.isArray(i.values)&&i.values.includes(r.value)&&(i.operations===void 0||i.operations===null||Array.isArray(i.operations)&&(!i.operations.length||i.operations.includes("*")||i.operations.includes(r.operation))))}var f_=500,Ol=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Cr=e=>!!e&&typeof e=="object"&&!Array.isArray(e);function p_(e){if(!Cr(e)||e.kind!=="record-set-match"||Object.keys(e).some(o=>!["kind","resourceCode","errorCode","records","where"].includes(o))||typeof e.resourceCode!="string"||e.resourceCode.length>64||!/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/.test(e.resourceCode)||typeof e.errorCode!="string"||!/^OPENXIANGDA_[A-Z0-9_]{1,96}$/.test(e.errorCode)||!Array.isArray(e.records)||!e.records.length||e.records.length>500||Object.hasOwn(e,"where")&&!Cr(e.where))return!1;let t=new Set;return e.records.every(o=>{if(!Cr(o)||Object.keys(o).length!==2||typeof o.id!="string"||!Ol.test(o.id)||!Number.isSafeInteger(o.expectedRevision)||Number(o.expectedRevision)<1)return!1;let n=o.id.toLowerCase();return t.has(n)?!1:(t.add(n),!0)})}function bl(e,t){if(t===void 0)return e;let o=e.views?.find(a=>a.code===t);if(!o)throw new Error(`DATA_RESOURCE_VIEW_NOT_FOUND: ${t}`);let n=new Map(o.sections?.flatMap(a=>a.fields.map(s=>[s,a.title]))),{views:r,...i}=e;return{...i,generated:o.generated,list:o.list,form:o.form,detail:o.detail,mobile:o.mobile,fields:Object.fromEntries(Object.entries(e.fields).map(([a,s])=>{let{section:d,...c}=s,l=n.get(a);return[a,{...c,...l?{section:l}:{},list:o.list.fieldOrder?.includes(a)??!1}]}))}}var Nl="openxiangda.development-configuration/v2",ga="openxiangda.development-configuration-manifest/v1",E_="application.development-configuration",I_="/openxiangda-api/v2/applications/{appCode}/dev-sessions/configuration",Sr=class extends Error{constructor(o,n){super(o);this.code=o;this.pointer=n;this.data={pointer:n}}code;pointer;status=400;data};function Ge(e){throw new Sr("OPENXIANGDA_CONNECTED_DEV_CONFIGURATION_INVALID",e)}function hl(e){(!e||typeof e!="object"||Array.isArray(e))&&Ge("/packageManifest");let t=e,o=["schemaVersion","appCode","version","configDigest","contractDigest","source","toolchain","artifacts"];(Object.keys(t).some(r=>!o.includes(r))||t.schemaVersion!==ga||typeof t.appCode!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(t.appCode)||!/^[a-f0-9]{64}$/.test(t.configDigest)||!/^[a-f0-9]{64}$/.test(t.contractDigest)||t.version!==`development-${t.configDigest}`)&&Ge("/packageManifest"),(!t.source||typeof t.source!="object"||Array.isArray(t.source)||Object.keys(t.source).some(r=>!["repository","commit","dirty"].includes(r))||![null,"string"].includes(t.source.repository===null?null:typeof t.source.repository)||t.source.repository!==null&&(t.source.repository.length>1024||/[\r\n\0]/.test(t.source.repository))||t.source.commit!==null&&(typeof t.source.commit!="string"||!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(t.source.commit))||typeof t.source.dirty!="boolean")&&Ge("/packageManifest/source"),(!t.toolchain||Object.keys(t.toolchain).some(r=>!["version","contractVersion"].includes(r))||typeof t.toolchain.version!="string"||!/^[A-Za-z0-9][A-Za-z0-9.+_-]{0,127}$/.test(t.toolchain.version)||t.toolchain.contractVersion!==dr)&&Ge("/packageManifest/toolchain");let n=[{kind:"config",digest:t.configDigest,mediaType:"application/json"},{kind:"contracts",digest:t.contractDigest,mediaType:"application/json"}];return Q(t.artifacts)!==Q(n)&&Ge("/packageManifest/artifacts"),t}function y_(e,t){return hl({schemaVersion:ga,appCode:e,version:`development-${t.configDigest}`,configDigest:t.configDigest,contractDigest:t.contractDigest,source:{...t.source},toolchain:{version:t.toolchainVersion,contractVersion:dr},artifacts:[{kind:"config",digest:t.configDigest,mediaType:"application/json"},{kind:"contracts",digest:t.contractDigest,mediaType:"application/json"}]})}function O_(e,t,o){return(!Number.isSafeInteger(t)||t<1)&&Ge("/expectedHeadRevision"),`development:${ee({manifest:e,expectedHeadRevision:t,...o?{actorUserId:o}:{}})}`}function b_(e,t,o){(!e||typeof e!="object"||Array.isArray(e))&&Ge("/result");let n=e,r=["schemaVersion","appCode","environmentKey","environmentId","appVersionId","configurationRunId","headRevision","publishedAppVersionId","selection","configDigest","contractDigest","reused","runtimeArtifactsDeployed","backendEventsAvailable"],i=/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/i;return(Object.keys(n).some(a=>!r.includes(a))||n.schemaVersion!==Nl||n.appCode!==t||n.environmentKey!=="preproduction"||n.configDigest!==o.configDigest||n.contractDigest!==o.contractDigest||!i.test(n.environmentId)||!i.test(n.appVersionId)||!i.test(n.publishedAppVersionId)||n.appVersionId===n.publishedAppVersionId||n.selection!=="session"||!i.test(n.configurationRunId)||typeof n.reused!="boolean"||!Number.isSafeInteger(n.headRevision)||n.headRevision<1||n.headRevision!==o.expectedHeadRevision||n.runtimeArtifactsDeployed!==!1||n.backendEventsAvailable!==!1)&&Ge("/result"),n}var h_="application.development-backend-events",R_="openxiangda.development-backend/v1",w_="application.development-backend-invocations",Rl="openxiangda.development-backend-invocation/v1",T_=262144,C_=1048576,S_=131072,D_=131072,k_=8,L_=45,$_=/^\/__platform\/events\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;function P_(e){return(e.backend?.operations?.length||0)>0||(e.workflows?.providers?.length||0)>0||(e.events?.subscriptions||[]).some(t=>t.execution?.kind!=="native-data")}function v_(e){return`connected-development:${e}`}function wl(e){if(typeof e!="string"||e.length%4!==0||!/^[A-Za-z0-9+/]*={0,2}$/.test(e))return null;let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=e.endsWith("==")?2:e.endsWith("=")?1:0;return o&&t.indexOf(e[e.length-o-1])%(o===2?16:4)!==0?null:e.length/4*3-o}function Tl(e,t,o){if(!["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(e)||o.method!==e||typeof t!="string"||t.length>2048||!t.startsWith("/")||t.startsWith("//")||t.startsWith("/__platform")||/[\\?#\s\u0000-\u001f\u007f]/.test(t))return!1;let n=t.split("/"),r=String(o.path||"").split("/");return n.length!==r.length?!1:n.every((i,a)=>{if(a===0)return r[a]==="";let s;try{s=decodeURIComponent(i)}catch{return!1}return!s||[".",".."].includes(s)||/[\/\\\s\u0000-\u001f\u007f]/.test(s)?!1:/^:[A-Za-z][A-Za-z0-9_]*$/.test(r[a]||"")||i===r[a]})}var Cl=/^(?:authorization|content-type|content-length|accept|if-match|idempotency-key|x-request-id|x-openxiangda-(?:gateway-assertion|forwarded-by|perspective|csrf-token|mcp-bus-token|dev-selection))$/i,Sl=/^(?:content-type|content-disposition|cache-control|etag|last-modified|retry-after)$/i;function Dl(e,t=!1){if(!e||typeof e!="object"||Array.isArray(e))return!1;let o=Object.entries(e),n=o.map(([r])=>r.toLowerCase());return o.length<=24&&new Set(n).size===n.length&&o.every(([r,i])=>(t?Sl:Cl).test(r)&&typeof i=="string"&&i.length<=8192&&!/[\r\n\u0000]/.test(i))}function V_(e){let t=wl(e.body);return e.schemaVersion===Rl&&!!e.operation&&typeof e.operation.code=="string"&&e.operation.code.length<=128&&e.operation.code.length>0&&Tl(e.method,e.endpointPath,e.operation)&&typeof e.canonicalQuery=="string"&&e.canonicalQuery.length<=8192&&!/[\s#\u0000-\u001f\u007f]/.test(e.canonicalQuery)&&t!==null&&t<=262144&&Dl(e.headers)&&Object.entries(e.headers).some(([o,n])=>o.toLowerCase()==="authorization"&&/^Bearer \S+$/.test(n))&&Object.entries(e.headers).some(([o,n])=>o.toLowerCase()==="x-openxiangda-gateway-assertion"&&!!n)}var W_=Object.freeze({version:"rich-text-html/1",maxBytes:1048576,maxNodes:25e3,maxDepth:128,maxImages:20,imageMaxBytes:10485760,maxVideos:4,videoMaxBytes:104857600,imageTypes:["image/png","image/jpeg","image/webp","image/gif"],videoTypes:["video/mp4","video/webm"],fonts:["Arial","Verdana","Tahoma","Times New Roman","Courier New","\u5B8B\u4F53","\u5FAE\u8F6F\u96C5\u9ED1","SimSun","Microsoft YaHei","sans-serif","serif","monospace"]});var le=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Jn=e=>Array.isArray(e)?e.map(Jn):le(e)?Object.fromEntries(Object.keys(e).sort().map(t=>[t,Jn(e[t])])):e,Ee=(e,t)=>JSON.stringify(Jn(e))===JSON.stringify(Jn(t));function Hn(e){return e.kind==="approval"?[e.onApprove,e.onReject]:e.kind==="parallel"?[...(e.branches||[]).map(t=>t.target),e.join]:e.kind==="condition"?[...(e.branches||[]).map(t=>t.target),e.otherwise]:"next"in e?[e.next]:[]}function Ea(e,t,o,n){let r=[...En(t),...An(t,n)];if(!le(t)||!le(t.nodes)||!le(n?.bindings))return["WORKFLOW_DESIGNER_DOCUMENT_INVALID"];let i=new Set(["title","startAt","nodes","readability"]);for(let s of new Set([...Object.keys(e),...Object.keys(t)]))!i.has(s)&&!Ee(e[s],t[s])&&r.push(`WORKFLOW_DESIGNER_CODE_OWNED:${s}`);(o.workflowCode!==n.workflowCode||o.schemaVersion!==n.schemaVersion)&&r.push("WORKFLOW_DESIGNER_BINDING_IDENTITY");let a=Object.values(e.nodes).filter(s=>s.kind==="action");for(let[s,d]of Object.entries(t.nodes)){if(!le(d)||d.id!==s||!["approval","handle","condition","cc","action","correction","end","parallel","join"].includes(d.kind)){r.push(`WORKFLOW_DESIGNER_NODE_INVALID:${s}`);continue}"taskPageCode"in d&&d.taskPageCode&&!e.taskPages?.[d.taskPageCode]&&r.push(`WORKFLOW_DESIGNER_PAGE_UNRELEASED:${s}`),d.kind==="action"&&!te(d)&&!a.some(l=>l.kind==="action"&&Ee(l.handler,d.handler)&&Ee(l.inputs,d.inputs)&&Ee(l.outputSchema,d.outputSchema))&&r.push(`WORKFLOW_DESIGNER_STEP_UNRELEASED:${s}`),["approval","handle"].includes(d.kind)&&"allowedOperations"in d&&d.allowedOperations&&(!Array.isArray(d.allowedOperations)||!d.allowedOperations.includes(d.kind==="handle"?"complete":"approve"))&&r.push(`WORKFLOW_DESIGNER_REQUIRED_ACTION:${s}.approve`);let c=e.nodes[s]||(d.kind==="approval"||d.kind==="handle"?Object.values(e.nodes).find(l=>{if(l.kind!==d.kind||!["approval","handle"].includes(l.kind)||!["fieldPolicy","administration","requiredOperations","taskPageCode"].every(m=>Ee(l[m],d[m])))return!1;let f=l;if(d.mode!==f.mode&&!f.administration?.modes?.includes(d.mode))return!1;let p=["none","optional","required"];return Object.entries(f.operationPolicy||{}).every(([m,E])=>{let A=d.operationPolicy?.[m];return Ee(E?.minimumOpinion,A?.minimumOpinion)&&p.indexOf(Mt(m,A))>=p.indexOf(Dn(m,E))})}):void 0);if(!c&&(d.kind==="approval"||d.kind==="handle")&&r.push(`WORKFLOW_DESIGNER_APPROVAL_TEMPLATE_REQUIRED:${s}`),(c?.kind==="approval"||c?.kind==="handle")&&(d.kind==="approval"||d.kind==="handle")){d.mode!==c.mode&&!c.administration?.modes?.includes(d.mode)&&r.push(`WORKFLOW_DESIGNER_MODE_NOT_ALLOWED:${s}`);for(let l of["requiredOperations","fieldPolicy","administration"])Ee(c[l],d[l])||r.push(`WORKFLOW_DESIGNER_CODE_OWNED:${s}.${l}`);for(let l of c.requiredOperations||[])d.allowedOperations&&!d.allowedOperations.includes(l)&&r.push(`WORKFLOW_DESIGNER_REQUIRED_ACTION:${s}.${l}`);for(let[l,f]of Object.entries(c.operationPolicy||{})){let p=d.operationPolicy?.[l],m=["none","optional","required"];(!Ee(f?.minimumOpinion,p?.minimumOpinion)||m.indexOf(Mt(l,p))<m.indexOf(Dn(l,f)))&&r.push(`WORKFLOW_DESIGNER_CODE_OWNED:${s}.${l}.minimumOpinion`)}}"binding"in d&&!n.bindings[d.binding]&&r.push(`WORKFLOW_DESIGNER_BINDING_MISSING:${s}`)}Ee(e.readability?.logic,t.readability?.logic)||r.push("WORKFLOW_DESIGNER_CODE_OWNED:readability.logic");for(let[s,d]of Object.entries(n.bindings)){let c=o.bindings[s];!c&&!Object.values(o.bindings).some(l=>Ee(l,d))&&r.push(`WORKFLOW_DESIGNER_BINDING_UNRELEASED:${s}`),c&&!Ee(c,d)&&r.push(`WORKFLOW_DESIGNER_BINDING_CODE_OWNED:${s}`)}return r.push(...Dr(t)),[...new Set(r)]}function kl(e,t){if(t.type==="insert_parallel"){if(e.nodes[t.joinId]||t.joinId===t.id||t.branches.length<2||t.branches.length>8)throw new Error("WORKFLOW_DESIGNER_PARALLEL_INSERT_INVALID");let r=kl(e,{type:"insert",from:t.from,target:t.target,node:{id:t.id,kind:"parallel",title:t.title,join:t.joinId,branches:t.branches.map(i=>({...i,target:t.joinId}))},...t.edge===void 0?{}:{edge:t.edge}});return r.nodes[t.joinId]={id:t.joinId,kind:"join",title:"\u5168\u90E8\u5B8C\u6210\u540E\u7EE7\u7EED",parallel:t.id,next:t.target},r}let o=structuredClone(e),n=(r,i,a)=>{if(r.kind==="approval")r.onApprove===i&&(r.onApprove=a),r.onReject===i&&(r.onReject=a);else if(r.kind==="condition"){for(let s of r.branches)s.target===i&&(s.target=a);r.otherwise===i&&(r.otherwise=a)}else if(r.kind==="parallel")for(let s of r.branches)s.target===i&&(s.target=a);else"next"in r&&r.next===i&&(r.next=a)};if(t.type==="insert"){let r=o.nodes[t.from];if(!r||o.nodes[t.node.id]||!Hn(r).includes(t.target)||!o.nodes[t.target])throw new Error("WORKFLOW_DESIGNER_INSERT_INVALID");if(o.nodes[t.node.id]=structuredClone(t.node),r.kind==="approval"){let i=t.edge==="reject"?"onReject":"onApprove";if(r[i]!==t.target)throw new Error("WORKFLOW_DESIGNER_INSERT_EDGE_INVALID");r[i]=t.node.id}else if(r.kind==="parallel"){if(typeof t.edge!="number"||r.branches[t.edge]?.target!==t.target)throw new Error("WORKFLOW_DESIGNER_INSERT_EDGE_INVALID");r.branches[t.edge].target=t.node.id}else if(r.kind==="condition")if(typeof t.edge=="number"&&r.branches[t.edge]?.target===t.target)r.branches[t.edge].target=t.node.id;else if(t.edge==="default"&&r.otherwise===t.target)r.otherwise=t.node.id;else throw new Error("WORKFLOW_DESIGNER_INSERT_EDGE_INVALID");else if("next"in r)r.next=t.node.id;else throw new Error("WORKFLOW_DESIGNER_INSERT_EDGE_INVALID")}else if(t.type==="remove_parallel_branch"){let r=o.nodes[t.nodeId];if(r?.kind!=="parallel"||r.branches.length<=2)throw new Error("WORKFLOW_PARALLEL_BRANCH_LIMIT");let a=je(o).regions.find(s=>s.parallelNodeId===r.id)?.branches.find(s=>s.id===t.branchId);if(!a)throw new Error("WORKFLOW_DESIGNER_PARALLEL_BRANCH_MISSING");r.branches=r.branches.filter(s=>s.id!==t.branchId);for(let s of a.nodeIds)delete o.nodes[s]}else if(t.type==="remove"){let r=o.nodes[t.nodeId];if(r?.kind==="parallel"){let a=o.nodes[r.join],s=je(o).regions.find(c=>c.parallelNodeId===r.id);if(a?.kind!=="join"||!s)throw new Error("WORKFLOW_DESIGNER_PARALLEL_PAIR_INVALID");let d=new Set([r.id,a.id,...s.branches.flatMap(c=>c.nodeIds)]);for(let c of Object.values(o.nodes))if(!d.has(c.id))for(let l of d)n(c,l,a.next);for(let c of d)delete o.nodes[c];return o.startAt===r.id&&(o.startAt=a.next),o}let i=t.reconnectTo||(r?.kind==="approval"?r.onApprove:r&&"next"in r?r.next:void 0);if(!r||!i||i===r.id||!o.nodes[i]||r.kind==="end"||r.kind==="correction"||r.kind==="join")throw new Error("WORKFLOW_DESIGNER_REMOVE_INVALID");for(let a of Object.values(o.nodes))n(a,r.id,i),(a.kind==="approval"||a.kind==="handle")&&a.returnTargets&&(a.returnTargets=a.returnTargets.filter(s=>s!==r.id)),(a.kind==="approval"||a.kind==="handle")&&a.returnPolicy&&(a.returnPolicy.targets=a.returnPolicy.targets.filter(s=>s.nodeId!==r.id));o.startAt===r.id&&(o.startAt=i),delete o.nodes[r.id]}else{let r=o.nodes[t.nodeId];if(!r)throw new Error("WORKFLOW_DESIGNER_NODE_MISSING");if(t.type==="node"){if("id"in t.patch||"kind"in t.patch)throw new Error("WORKFLOW_DESIGNER_NODE_ID_IMMUTABLE");Object.assign(r,t.patch)}else{if(r.kind!=="condition"||t.index<0||t.index>r.branches.length)throw new Error("WORKFLOW_DESIGNER_BRANCH_INVALID");r.branches[t.index]={when:structuredClone(t.when),target:t.target,...t.label?{label:t.label}:{}}}}return o}var Aa=(e,t)=>t.split(".").reduce((o,n)=>le(o)&&Object.hasOwn(o,n)?o[n]:void 0,e),Ia=(e,t)=>t.includes(",")?t.split(",").some(o=>Ia(e,o)):t==="unknown"?!0:t==="null"?e===null:t==="number"||t==="integer"?typeof e=="number"&&Number.isFinite(e)&&(t!=="integer"||Number.isInteger(e)):t==="array"?Array.isArray(e):t==="object"?le(e):typeof e===t;function J_(e,t,o){if(o.held)return{outcome:"held",reason:"\u5DF2\u6307\u5B9A\u4FDD\u7559\u5728\u539F\u7248\u672C"};let n=o.activeNodeIds?.length?o.activeNodeIds:o.currentNodeId?[o.currentNodeId]:[];if(!n.length)return{outcome:"excepted",reason:"\u5F53\u524D\u8FD0\u884C\u4F4D\u7F6E\u65E0\u6CD5\u786E\u5B9A"};if(n.some(s=>!t.nodes[s]))return{outcome:"excepted",reason:"\u5F53\u524D\u8282\u70B9\u5DF2\u88AB\u5220\u9664"};if(n.some(s=>e.nodes[s]?.kind!==t.nodes[s]?.kind))return{outcome:"excepted",reason:"\u5F53\u524D\u8282\u70B9\u7C7B\u578B\u5DF2\u6539\u53D8"};if((o.returnTargetNodeIds||[]).some(s=>!t.nodes[s]))return{outcome:"excepted",reason:"\u6B63\u5728\u9000\u56DE\u7684\u76EE\u6807\u8282\u70B9\u5DF2\u88AB\u5220\u9664"};if(!Ee(e.subject,t.subject)||!Ee(e.inputSchema,t.inputSchema))return{outcome:"excepted",reason:"\u7533\u8BF7\u6570\u636E\u6216\u53D8\u91CF\u5B9A\u4E49\u5DF2\u6539\u53D8\uFF0C\u9700\u8981\u660E\u786E\u7684\u6570\u636E\u8F6C\u6362"};if(o.forkNodeId){let s=e.nodes[o.forkNodeId],d=t.nodes[o.forkNodeId];if(s?.kind!=="parallel"||d?.kind!=="parallel"||s.join!==d.join)return{outcome:"excepted",reason:"\u6B63\u5728\u8FD0\u884C\u7684\u5E76\u884C\u5206\u652F\u6216\u6C47\u5408\u70B9\u5DF2\u6539\u53D8"};let c=je(e).regions.find(f=>f.parallelNodeId===s.id),l=je(t).regions.find(f=>f.parallelNodeId===d.id);for(let f of o.unarrivedBranchIds||[]){let p=l?.branches.find(m=>m.id===f);if(!p||n.some(m=>c?.branches.find(E=>E.id===f)?.nodeIds.includes(m)&&!p.nodeIds.includes(m)))return{outcome:"excepted",reason:"\u5C1A\u672A\u5B8C\u6210\u7684\u5E76\u884C\u5206\u652F\u6216\u5176\u5F53\u524D\u8282\u70B9\u5DF2\u6539\u53D8"}}}if(o.businessStepPending)return{outcome:"deferred",reason:"\u4E1A\u52A1\u6B65\u9AA4\u6267\u884C\u4E2D\uFF0C\u5B8C\u6210\u540E\u81EA\u52A8\u66F4\u65B0"};let r=new Set,i=[...n];for(;i.length;){let s=i.pop();r.has(s)||(r.add(s),i.push(...Hn(t.nodes[s]||{}).filter(d=>!!t.nodes[d])))}let a=Tn(t,"preview");for(let s of Object.values(t.nodes)){if(!r.has(s.id))continue;let d=s.kind==="condition"?s.branches.map(c=>c.when):s.kind==="action"?Object.values(s.inputs).filter(c=>c.source==="fact").map(c=>({op:"path",path:c.path})):[];for(let c of d)for(let l of Wt(c).paths){let f=a.variables.find(m=>m.path===l),p=Aa(o.facts,l);if(p===void 0&&f?.source.kind==="step_output"&&r.has(f.source.nodeId)&&!n.includes(f.source.nodeId)){let m=new Set,E=[...n];for(;E.length;){let A=E.pop();A===f.source.nodeId||m.has(A)||(m.add(A),E.push(...Hn(t.nodes[A]||{}).filter(b=>!!t.nodes[b])))}if(!m.has(s.id))continue}if(!(p===void 0&&f&&!f.required&&(f.source.kind!=="step_output"||le(Aa(o.facts,`steps.${f.source.nodeId}`))))&&(p===void 0||f&&!Ia(p,f.type)))return{outcome:"excepted",reason:`\u540E\u7EED\u6761\u4EF6\u9700\u8981\u7684\u6570\u636E\u5728\u8BE5\u7533\u8BF7\u4E2D\u4E0D\u5B58\u5728\u6216\u7C7B\u578B\u4E0D\u517C\u5BB9\uFF1A${f?.label||l}`}}}return{outcome:"eligible"}}function Dr(e){if(!le(e?.nodes))return["WORKFLOW_DESIGNER_DOCUMENT_INVALID"];let t=[];t.push(...yn(e),...On(e),...In(e),...fn(e));let o=Object.values(e.nodes);if(o.length>200||!o.length)return["WORKFLOW_DESIGNER_NODE_LIMIT"];for(let c of o)!le(c)||!["approval","handle","condition","cc","action","correction","end","parallel","join"].includes(c.kind)?t.push("WORKFLOW_DESIGNER_NODE_INVALID"):c.kind==="condition"&&(!Array.isArray(c.branches)||!c.branches.length||c.branches.length>32||c.branches.some(l=>!le(l)||!le(l.when)||typeof l.target!="string"))&&t.push(`WORKFLOW_DESIGNER_BRANCH_INVALID:${c.id}`);if(t.length)return[...new Set(t)];let n=Tn(e,"draft").variables,r=0,i=(c,l,f=0)=>{if(!le(c)||f>16||++r>4096)return t.push(`WORKFLOW_DESIGNER_EXPRESSION_LIMIT:${l}`),"invalid";if(c.op==="literal"){let p=c.value;return p===null?"null":Array.isArray(p)?"array":typeof p=="object"?"object":typeof p}if(c.op==="path"){let p=n.find(E=>E.path===c.path);(!p||p.type==="unknown")&&t.push(`WORKFLOW_DESIGNER_VARIABLE_UNKNOWN:${l}:${c.path}`);let m=p?.type.split(",").find(E=>E!=="null")||p?.type||"unknown";return m==="integer"?"number":m}if(c.op==="and"||c.op==="or"){if(!Array.isArray(c.values)||c.values.length<1||c.values.length>32)return t.push(`WORKFLOW_DESIGNER_CONDITION_GROUP:${l}`),"invalid";for(let p of c.values)i(p,l,f+1)!=="boolean"&&t.push(`WORKFLOW_DESIGNER_CONDITION_BOOLEAN:${l}`)}else if(c.op==="not"||c.op==="exists"){let p=i(c.value,l,f+1);c.op==="not"&&p!=="boolean"&&t.push(`WORKFLOW_DESIGNER_CONDITION_BOOLEAN:${l}`)}else if(["eq","neq","gt","gte","lt","lte","in","contains"].includes(c.op)&&"left"in c){let p=i(c.left,l,f+1),m=i(c.right,l,f+1);(c.op==="in"?m==="array":c.op==="contains"?p==="array"||p==="string"&&m==="string":["gt","gte","lt","lte"].includes(c.op)?p===m&&["number","string"].includes(p):p===m||p==="null"||m==="null")||t.push(`WORKFLOW_DESIGNER_CONDITION_TYPE:${l}`)}else t.push(`WORKFLOW_DESIGNER_CONDITION_OPERATOR:${l}`);return"boolean"},a=new Set,s=new Set,d=c=>{if(s.has(c)){t.push(`WORKFLOW_DESIGNER_CYCLE:${c}`);return}if(a.has(c))return;let l=e.nodes[c];if(!l){t.push(`WORKFLOW_DESIGNER_TARGET_MISSING:${c}`);return}s.add(c);for(let f of Hn(l))d(f);s.delete(c),a.add(c)};for(let c of o){if((!/^[a-z][a-z0-9_-]{0,127}$/.test(c.id)||e.nodes[c.id]!==c)&&t.push(`WORKFLOW_DESIGNER_NODE_ID:${c.id}`),c.kind==="parallel")for(let l of c.branches)l.when&&i(l.when,c.id)!=="boolean"&&t.push(`WORKFLOW_DESIGNER_CONDITION_BOOLEAN:${c.id}`);if(c.kind==="condition"){(!c.branches.length||c.branches.length>32)&&t.push(`WORKFLOW_DESIGNER_BRANCH_LIMIT:${c.id}`);for(let l of c.branches)i(l.when,c.id)!=="boolean"&&t.push(`WORKFLOW_DESIGNER_CONDITION_BOOLEAN:${c.id}`)}}d(e.startAt);for(let c of o)!a.has(c.id)&&c.kind!=="correction"&&t.push(`WORKFLOW_DESIGNER_UNREACHABLE:${c.id}`);return[...new Set(t)]}function H_(e){let t={...e.readability?.variables},o=(n,r="",i=0)=>{if(!(i>8||!le(n)))if(n.type==="object"&&le(n.properties))for(let[a,s]of Object.entries(n.properties))o(s,r?`${r}.${a}`:a,i+1);else r&&(t[r]||={label:String(n.title||r)})};o(e.inputSchema);for(let n of Object.values(e.nodes))n.kind==="action"&&o(n.outputSchema,`steps.${n.id}`);return Tn({...e,readability:{...e.readability,variables:t}},"draft").variables.filter(n=>n.type!=="unknown")}function Yn(e,t){return(t?(Array.isArray(e)?e:[]).filter(Array.isArray):[Array.isArray(e)?e.filter(n=>!Array.isArray(n)):[]]).map(n=>n[n.length-1]?.value).filter(n=>!!n)}var ya=["province","city","district","street"];function Oa(e){for(let t=ya.length-1;t>=0;t-=1){let o=ya[t],n=o?e?.[o]:void 0;if(o&&n?.value)return{path:`${o}.value`,value:n.value}}}function kr(e){return!!(e&&typeof e=="object"&&!Array.isArray(e)&&"value"in e)}function Lr(e){return kr(e)?String(e.value):e}function ba(e){return(Array.isArray(e)?e:[e]).map(Lr)}function Ll(e,t,o){let n=new Set(Object.keys(t.fields)),r=a=>{if(!n.has(a))throw new Error(`OPENXIANGDA_RESOURCE_QUERY_FIELD_NOT_DECLARED:${e}:${a}`);return a},i=o.where?[Xn(e,t,o.where)]:[];if(o.createdBy!==void 0&&o.createdBy!==""&&i.push({field:"created_by",operator:"eq",value:o.createdBy}),o.keyword?.trim()){let a=(t.list?.searchableFields||[]).filter(s=>n.has(s));a.length&&i.push({or:a.map(s=>({field:r(s),operator:"contains",value:o.keyword.trim()}))})}for(let[a,s]of Object.entries(o.filters||{})){if(s==null||s===""||Array.isArray(s)&&s.length===0||!n.has(a))continue;let d=t.fields[a];if(d)if(d.type==="json")i.push({field:a,operator:"jsonContains",value:s});else if(d.type==="address"){let c=Oa(s);c&&i.push({field:a,operator:"jsonContains",path:c.path,value:c.value})}else if(d.type==="cascade.single"||d.type==="cascade.multiple"){let c=Yn(s,d.type==="cascade.multiple");c.length&&i.push({field:a,operator:d.type==="cascade.multiple"?"hasAny":"has",value:d.type==="cascade.multiple"?c:c[0]})}else if((d.type==="date-range"||d.type==="datetime-range")&&s!==null&&typeof s=="object"&&!Array.isArray(s)){let c=s;c.start!==void 0&&c.end!==void 0&&i.push({field:a,operator:"overlaps",value:{start:c.start,end:c.end}})}else if(Array.isArray(s)&&s.length===2&&["date","datetime","number","money","percent"].includes(d.widget))s[0]!==void 0&&s[0]!==null&&s[0]!==""&&i.push({field:a,operator:"gte",value:s[0]}),s[1]!==void 0&&s[1]!==null&&s[1]!==""&&i.push({field:a,operator:"lte",value:s[1]});else if(d.type==="option.multiple"||d.type==="user.multiple"||d.type==="department.multiple"||d.type==="resource-ref.multiple")i.push({field:a,operator:"hasAny",value:ba(s)});else{let[c]=ba(s);i.push({field:a,operator:"eq",value:c})}}return i.length?{and:i}:void 0}function Xn(e,t,o){if("and"in o)return{and:o.and.map(a=>Xn(e,t,a))};if("or"in o)return{or:o.or.map(a=>Xn(e,t,a))};if("not"in o)return{not:Xn(e,t,o.not)};if(o.path!==void 0)return o;if(o.operator==="isEmpty"||o.operator==="isNotEmpty")return{field:o.field,operator:o.operator};let n=t.fields[o.field];if(o.operator==="has"){let a=n?.type==="cascade.single"&&Array.isArray(o.value)&&o.value.length>0&&o.value.every(kr);return{...o,value:a?Yn(o.value,!1)[0]:Lr(o.value)}}if(["in","between","hasAny","hasAll"].includes(o.operator)){if(!Array.isArray(o.value))return o;let a=n?.type==="cascade.multiple"&&["hasAny","hasAll"].includes(o.operator)&&o.value.length>0&&o.value.every(s=>Array.isArray(s)&&s.length>0&&s.every(kr));return{...o,value:a?Yn(o.value,!0):o.value.map(Lr)}}let r=Ll(e,t,{page:1,pageSize:20,filters:{[o.field]:o.value}}),i=r&&"and"in r?r.and[0]:void 0;return i&&"field"in i?{...i,operator:o.operator}:o}var $l="openxiangda.workflow-source-bundle/v1",Pl=3*1024*1024,Ve=(e,t)=>e.replace(/^sha256:/,"")===t.replace(/^sha256:/,""),it=(e,t)=>Ve(e.definitionDigest,t.definitionDigest)&&Ve(e.bindingDigest,t.bindingDigest),Zn=e=>!!e&&typeof e=="object"&&!Array.isArray(e),rt=(e,t)=>Zn(e)&&Object.keys(e).every(o=>t.includes(o)&&!["__proto__","constructor","prototype"].includes(o)),$r=e=>typeof e=="string"&&/^[A-Za-z][A-Za-z0-9_-]{0,127}$/.test(e),vl=e=>typeof e=="string"&&/^(sha256:)?[a-f0-9]{64}$/.test(e);function Na(e,t,o){let n=new Set(Object.values(e.nodes).flatMap(i=>"taskPageCode"in i&&i.taskPageCode?[i.taskPageCode]:[])),r=new Map;for(let i of Object.values(e.nodes))i.kind==="action"&&r.set(`${i.handler.code}@${i.handler.version}`,{code:i.handler.code,version:i.handler.version,digest:o({handler:i.handler,inputSchema:i.inputSchema,outputSchema:i.outputSchema})});return{taskPages:[...n].sort().map(i=>({code:i,digest:o(e.taskPages?.[i])})),steps:[...r.values()].sort((i,a)=>i.code.localeCompare(a.code)||i.version-a.version),bindingKeys:Object.keys(t.bindings).sort(),roles:[...new Set(Object.values(t.bindings).flatMap(i=>[...i.roleCode?[i.roleCode]:[],...i.roleCodes||[]]))].sort()}}function Vl(e,t){try{return Fl(e,t)}catch{return["WORKFLOW_BUNDLE_CORRUPT"]}}function Fl(e,t){let o=[];if(!rt(e,["schemaVersion","appCode","workflowCode","origin","definition","binding","references","handling"])||e.schemaVersion!==$l||!$r(e.appCode)||!$r(e.workflowCode))return["WORKFLOW_BUNDLE_CORRUPT"];if(new TextEncoder().encode(JSON.stringify(e)).length>Pl)return["WORKFLOW_BUNDLE_TOO_LARGE"];let n=e,r=n.origin;if(!rt(r,["environmentKey","headRevision","definitionVersion","bindingVersion","definitionDigest","bindingDigest","handlingDigest","catalogDigest"])||!["preproduction","production"].includes(r.environmentKey)||![r.headRevision,r.definitionVersion,r.bindingVersion].every(i=>Number.isSafeInteger(i)&&i>=1)||![r.definitionDigest,r.bindingDigest,r.handlingDigest,r.catalogDigest].every(vl))return["WORKFLOW_BUNDLE_CORRUPT"];if(!Zn(n.definition?.nodes)||!Zn(n.binding?.bindings)||n.definition.code!==n.workflowCode||n.binding.workflowCode!==n.workflowCode)return["WORKFLOW_BUNDLE_CORRUPT"];if(Dr(n.definition).length&&o.push("WORKFLOW_BUNDLE_DEFINITION_INVALID"),(!Ve(t(n.definition),r.definitionDigest)||!Ve(t(n.binding),r.bindingDigest)||!Ve(t(n.handling),r.handlingDigest)||!Ve(t(n.references),r.catalogDigest))&&o.push("WORKFLOW_BUNDLE_CORRUPT"),Ve(t(Na(n.definition,n.binding,t)),t(n.references))||o.push("WORKFLOW_BUNDLE_CATALOG_CORRUPT"),!Zn(n.handling)||Object.keys(n.handling).length>200)o.push("WORKFLOW_BUNDLE_HANDLING_INVALID");else for(let[i,a]of Object.entries(n.handling)){if(!n.definition.nodes[i]||!rt(a,["mode","operations","assignee"])){o.push("WORKFLOW_BUNDLE_HANDLING_INVALID");continue}if(a.mode!==void 0&&!["single","any","all","sequence"].includes(a.mode)&&o.push("WORKFLOW_BUNDLE_HANDLING_INVALID"),a.operations!==void 0){let d=["complete","approve","reject","save_form","return","transfer","delegate","add_assignee"];if(!rt(a.operations,d))o.push("WORKFLOW_BUNDLE_HANDLING_INVALID");else for(let c of Object.values(a.operations))(!rt(c,["enabled","label","opinion","commentRequired","reasonRequired"])||c.enabled!==void 0&&typeof c.enabled!="boolean"||c.commentRequired!==void 0&&typeof c.commentRequired!="boolean"||c.reasonRequired!==void 0&&typeof c.reasonRequired!="boolean"||c.label!==void 0&&(typeof c.label!="string"||!c.label.trim()||c.label.length>255)||c.opinion!==void 0&&!["none","optional","required"].includes(c.opinion))&&o.push("WORKFLOW_BUNDLE_HANDLING_INVALID")}let s=a.assignee;s&&(s.kind==="named_people"?!rt(s,["kind","count"])||!Number.isSafeInteger(s.count)||s.count<0||s.count>200:s.kind!=="roles"||!rt(s,["kind","roleCodes"])||!Array.isArray(s.roleCodes)||s.roleCodes.length>200||!s.roleCodes.every($r))&&o.push("WORKFLOW_BUNDLE_HANDLING_INVALID")}return[...new Set(o)]}function og(e){if(!e.head)return"not_active";if(it(e.declared,e.head))return"in_sync";let t=e.base||e.activeDeclaration;return t&&it(t,e.head)?"ahead":!t||it(e.declared,t)?"behind":"diverged"}function rg(e){return e.head?it(e.declared,e.head)?"reuse":e.activeDeclaration&&it(e.declared,e.activeDeclaration)?"preserve":e.base&&it(e.base,e.head)||e.activeDeclaration&&it(e.activeDeclaration,e.head)?"advance":"diverged":"advance"}function ig(e,t,o,n){let r=Vl(o,n);if(r.length)return r;r.push(...Ea(e,o.definition,t,o.binding).map(a=>`WORKFLOW_IMPORT_CODE_OWNED_DRIFT:${a}`));let i;try{i=Na(e,t,n)}catch{return[...new Set([...r,"WORKFLOW_IMPORT_CODE_OWNED_DRIFT:catalog"])]}for(let a of o.references.taskPages)(!e.taskPages?.[a.code]||!Ve(n(e.taskPages[a.code]),a.digest))&&r.push(`WORKFLOW_IMPORT_CODE_OWNED_DRIFT:taskPage:${a.code}`);for(let a of o.references.steps)i.steps.some(s=>s.code===a.code&&s.version===a.version&&Ve(s.digest,a.digest))||r.push(`WORKFLOW_IMPORT_CODE_OWNED_DRIFT:step:${a.code}@${a.version}`);return[...new Set(r)]}var ag="8a8dcb9adf5e1eb450b61f19e374c790750df822eea5acc6499766c2c3e4f3f3";export{vt as AuthenticatedPublicReadContractError,on as DATA_AUDIT_METADATA_FIELDS,i_ as DATA_BUSINESS_COMMAND_INTENT_MAX_BYTES,yl as DATA_BUSINESS_COMMAND_RESOLUTION_SCHEMA,r_ as DATA_BUSINESS_COMMAND_SCHEMA,_r as DATA_EVENT_TYPES_V2,Gl as DATA_FORM_DRAFT_MAX_BYTES,xr as DATA_RESOURCE_MAX_FIELDS,io as DATA_SUBTABLE_DEFAULT_TOTAL_ROWS,He as DATA_SUBTABLE_MAX_ROWS,ct as DATA_SUBTABLE_MAX_TOTAL_ROWS,Wa as DATA_SYSTEM_SORT_FIELD_CODES,Kl as DATA_TRANSACTION_MAX_BYTES,jr as DATA_TRANSACTION_MAX_OPERATIONS,f_ as DATA_TRANSACTION_RECORD_SET_MAX_RECORDS,lp as DATE_EVENT_RESERVED_DATA_FIELDS_V2,L_ as DEVELOPMENT_BACKEND_CONNECTION_TTL_SECONDS,$_ as DEVELOPMENT_BACKEND_ENDPOINT_PATTERN,h_ as DEVELOPMENT_BACKEND_FEATURE,w_ as DEVELOPMENT_BACKEND_INVOCATION_FEATURE,T_ as DEVELOPMENT_BACKEND_INVOCATION_MAX_REQUEST_BYTES,C_ as DEVELOPMENT_BACKEND_INVOCATION_MAX_RESPONSE_BYTES,Rl as DEVELOPMENT_BACKEND_INVOCATION_SCHEMA,k_ as DEVELOPMENT_BACKEND_MAX_INFLIGHT,D_ as DEVELOPMENT_BACKEND_MAX_REQUEST_BYTES,S_ as DEVELOPMENT_BACKEND_MAX_RESPONSE_BYTES,R_ as DEVELOPMENT_BACKEND_SCHEMA,I_ as DEVELOPMENT_CONFIGURATION_ENDPOINT,E_ as DEVELOPMENT_CONFIGURATION_FEATURE,ga as DEVELOPMENT_CONFIGURATION_MANIFEST_SCHEMA,Nl as DEVELOPMENT_CONFIGURATION_SCHEMA,kn as DateEventProjectionV2Error,Sr as DevelopmentConfigurationContractError,Dt as ManagedConcurrencyContractError,se as NATIVE_ARTIFACT_CAPACITY_V2,ag as NATIVE_CONFIGURATION_VALIDATOR_DIGEST,B as NATIVE_CONTRACT_CAPACITY_V2,sf as NATIVE_DATA_POLICY_EXPRESSION_MAX_CLAUSES,nf as NATIVE_DATA_POLICY_EXPRESSION_MAX_DEPTH,of as NATIVE_DATA_POLICY_EXPRESSION_MAX_GROUP_ITEMS,rf as NATIVE_DATA_POLICY_EXPRESSION_MAX_LEAVES,af as NATIVE_DATA_POLICY_EXPRESSION_MAX_OCCURRENCES,xa as NATIVE_DATA_QUERY_OPERATORS_V2,yt as NATIVE_HIGH_DENSITY_ARTIFACT_CAPACITY_V2,Jm as NATIVE_ROLE_MEMBERSHIP_BATCH_MAX_BYTES,zm as NATIVE_ROLE_MEMBERSHIP_BATCH_MAX_ITEMS,Ef as NATIVE_UNIQUE_KEY_MAX_BYTES,Fi as NATIVE_UNIQUE_KEY_NORMALIZERS,gr as NativeConfigurationCompilerError,Ce as NativeDataFieldContractV2Error,Pt as NativeDataPolicyExpressionV2Error,pt as NativeDecimalLifecycleContractError,Ho as NativeEventActionContractError,pe as NativeParentReadPolicyError,Nr as NativeRoleMembershipBatchInputError,$o as NativeScopeSourceFieldPathV2Error,Ft as NativeUniqueKeyContractError,Ca as OPENXIANGDA_NATIVE_DATA_FIELD_TYPES_V2,Fe as OPENXIANGDA_NATIVE_DATA_SURFACE_KEYS_V2,No as OPENXIANGDA_NATIVE_DRAFT_STATE_KEYS_V2,go as OPENXIANGDA_NATIVE_SYSTEM_FIELDS_V2,lt as OPENXIANGDA_NATIVE_SYSTEM_FIELD_MAP_V2,W_ as RICH_TEXT_POLICY_V2,Ml as USER_CANDIDATE_MAX_SELECTIONS,wa as USER_CANDIDATE_SCOPE_FIELD_TYPES,Je as UserCandidateContractError,ts as WORKFLOW_APPROVAL_EMPTY_PROVIDERS,ip as WORKFLOW_APPROVED_DELEGATION_MAX_BYTES,rp as WORKFLOW_APPROVED_DELEGATION_MAX_REQUESTS,Xi as WORKFLOW_AUTOMATIC_CC_DEFAULT_RECIPIENTS,Zi as WORKFLOW_AUTOMATIC_CC_MAX_RECIPIENTS,Wd as WORKFLOW_AUTOMATIC_CC_PROVIDERS,Vo as WORKFLOW_BUSINESS_STEP_EVENT,xu as WORKFLOW_BUSINESS_STEP_EVENTS,ju as WORKFLOW_BUSINESS_STEP_FACTS_KEY,xo as WORKFLOW_BUSINESS_STEP_MAX_BYTES,Td as WORKFLOW_BUSINESS_STEP_MAX_RECEIPT_BYTES,Sn as WORKFLOW_CONFIGURABLE_OPERATIONS,Zo as WORKFLOW_CONFIGURABLE_PROVIDERS,zt as WORKFLOW_EVENT_TYPES_V2,so as WORKFLOW_LAUNCH_MAX_INPUTS,Bd as WORKFLOW_LAUNCH_PREFLIGHT_PROVIDERS,Ld as WORKFLOW_PARALLEL_MAX_BRANCHES,kd as WORKFLOW_PARALLEL_MIN_BRANCHES,vu as WORKFLOW_PLATFORM_NOTIFY_CAPABILITY,hd as WORKFLOW_PLATFORM_NOTIFY_HANDLER,Rd as WORKFLOW_PLATFORM_NOTIFY_INPUT_SCHEMA,wd as WORKFLOW_PLATFORM_NOTIFY_OUTPUT_SCHEMA,Yf as WORKFLOW_REJECTION_NOTIFICATION_MAX_BYTES,Ud as WORKFLOW_REJECTION_NOTIFICATION_SCHEMA,vf as WORKFLOW_ROLE_UNION_MAX_ROLES,Op as WORKFLOW_ROUTING_MAX_BYTES,yp as WORKFLOW_ROUTING_MAX_MATCHED_RULES,Ip as WORKFLOW_ROUTING_MAX_RULES,Pl as WORKFLOW_SOURCE_BUNDLE_MAX_BYTES,$l as WORKFLOW_SOURCE_BUNDLE_SCHEMA,Km as WORKFLOW_STEP_DATA_COMMAND_SCHEMA,gl as WORKFLOW_STEP_DATA_RESOLUTION_SCHEMA,Jd as WORKFLOW_TASK_PAGE_DEFINITION_MAX_BYTES,ir as WORKFLOW_TASK_PAGE_MAX_BYTES,zd as WORKFLOW_TASK_PAGE_MAX_FIELDS,_s as WORKFLOW_TASK_SUBTABLE_MAX_ROWS,ps as WORKFLOW_TASK_SUBTABLE_MAX_TOTAL_ROWS,ke as WorkflowTaskPageError,Hd as applyWorkflowTaskPageValues,_p as applyWorkflowTaskSubtableRows,hl as assertDevelopmentConfigurationManifest,b_ as assertDevelopmentConfigurationResult,Hm as assertNativeRoleMembershipBatchInput,uf as assertWorkflowNativeStageGuard,Pi as assertWorkflowNativeStagePolicy,ff as assertWorkflowNativeStageSourceGuard,vn as assertWorkflowOwnedSubjectCreate,hs as assertWorkflowOwnedSubjectCreateResources,Ll as buildResourceWhere,s_ as canonicalDataBusinessIntent,J_ as classifyWorkflowAdoption,rg as classifyWorkflowSourceDeployment,Xn as compileAdvancedWhere,Wm as compileNativeApplicationConfiguration,Bi as compileNativeEventAction,hc as compileNativeEventCapturePlansV2,Nc as compileRequiredPlatformCapabilitiesV3,Mo as compileWorkflowBusinessStepHandlers,y_ as createDevelopmentConfigurationManifest,Zt as dataOwnedRowLimit,up as dateEventProjectionEnvelopeSchemaV2,fs as dateEventProjectionFieldsV2,wl as developmentBackendBase64Bytes,Dl as developmentBackendInvocationHeadersValid,V_ as developmentBackendInvocationRequestValid,v_ as developmentBackendInvocationRevision,Tl as developmentBackendOperationMatches,O_ as developmentConfigurationKey,kl as editWorkflowDesignerDefinition,Be as evaluateWorkflowTaskPageExpression,Jf as formatWorkflowCompletionDeadline,Rn as formatWorkflowExpression,qu as formatWorkflowSupervisorChain,Ts as generatedCrudCapabilityOperations,Hr as hasDataAuditReadPolicy,qo as hasNativeParentReadPolicy,je as inspectWorkflowParallel,Tt as isDataAuditMetadataField,wt as isDataOwnedRowLimit,Yr as isDataSystemSortField,c_ as isDataTransactionActorAuthorityGuard,p_ as isDataTransactionRecordSetMatchGuard,Ql as isNativeDataQueryOperatorV2,tn as isNativeMultiValueFieldV2,te as isWorkflowPlatformNotify,Xf as isWorkflowRejectionNotificationSnapshot,l_ as matchesDataActorAuthorityMembership,Lu as materializeNativeDataQueryPathTypesV2,gt as nativeDataPolicyExpressionLeavesV2,Ri as nativeDataPolicyExpressionToCnfV2,$u as nativeDataQueryPathPlanV2,tu as nativeFieldAggregatePlanV2,Ou as nativeFieldColumnDefinitionV2,bu as nativeFieldDefaultSqlV2,Nu as nativeFieldHasDefaultV2,Tu as nativeFieldIndexStatementsV2,nn as nativeFieldRequiresCreateInputV2,wu as nativeFieldSequenceGrantStatementsV2,Ru as nativeFieldSequenceOwnershipStatementsV2,hu as nativeFieldSequenceStatementsV2,ei as nativeFieldSupportsFilterV2,eu as nativeFieldSupportsOperatorV2,Oo as nativeFieldSupportsSearchV2,St as nativeFieldSupportsSortV2,Qr as nativeOperatorsForFieldV2,ad as nativePhysicalFieldV2,yu as nativePhysicalFieldsV2,We as nativePhysicalObjectNameV2,Du as nativeScopeSourceFieldValueV2,_i as nativeScopeSourceGrantPathSupportedV2,Po as nativeScopeSourceSubjectPathSupportedV2,Cu as nativeSubtableConstraintStatementsV2,xi as nativeUniqueKeysContractVersion,If as nativeUniqueKeysJsonSchema,Ko as normalizeDataMutationGrants,Sp as normalizeWorkflowOwnedSubjectCreate,a_ as parseDataBusinessCommandResolution,Xt as parseDataFieldUserCandidates,ko as parseDecimalReservationLifecycle,Ao as parseNativeDataFieldsV2,Jr as parseNativeDataResourceInvariantsV2,vd as parseNativeParentReadPolicy,Wi as parseNativeUniqueKeys,Gm as parseWorkflowStepDataResolution,bl as projectDataResourceView,To as projectNativeDataResourceViewV2,Tn as projectWorkflowGraph,Qi as projectWorkflowNodePolicy,fe as quoteNativeIdentifierV2,gp as refreshWorkflowTaskPageFacts,co as requiresAggregateOwnedSubtableCapacity,mo as requiresDateTimeMinutePrecision,P_ as requiresDevelopmentBackendCredential,Vn as requiresExtendedArtifactCapacity,ur as requiresExtendedConfigurationBytes,lr as requiresExtendedDeclarationCapacity,ao as requiresExtendedFieldCapacity,lo as requiresExtendedOwnedSubtableCapacity,cr as requiresExtendedRoleCapacity,Fn as requiresHighDensityArtifactCapacity,_o as requiresOwnedSubtableMinimumRows,ro as requiresUserCandidateLaunchScope,Yi as requiresWorkflowRoleInputSelection,Ji as requiresWorkflowRoleUnion,bn as resolveNativeParentReadBinding,kt as resolveNativeScopeSourceFieldPathV2,tp as resolveWorkflowCommandHandler,Ta as resolveWorkflowUserCandidates,Rp as selectWorkflowAssignmentRoutingRules,ql as serializedDataBytes,Ul as userCandidateScopeValue,Vi as validateAuthenticatedPublicRead,ci as validateDecimalReservationLifecycles,ai as validateManagedConcurrency,oi as validateNativeDataDraftStateV2,zr as validateNativeDataResourceReferencesV2,wo as validateNativeDataResourceSurfaceV2,Si as validateNativeParentReadPolicies,Fr as validateUserCandidateReferences,Qo as validateWorkflowAdministration,er as validateWorkflowApprovalEmptyPolicy,ls as validateWorkflowApprovedDelegation,bs as validateWorkflowAssignmentRoutingBindings,Pn as validateWorkflowAssignmentRoutingPolicy,Np as validateWorkflowAssignmentRoutingRules,Xo as validateWorkflowAutomaticCc,Uu as validateWorkflowBusinessStepHandlerContract,Mu as validateWorkflowBusinessStepRequest,Cd as validateWorkflowBusinessStepResult,mn as validateWorkflowBusinessStepSchema,bi as validateWorkflowBusinessStepSubscriptions,_n as validateWorkflowBusinessSteps,as as validateWorkflowCommandHandlers,rs as validateWorkflowCompletionDeadlines,us as validateWorkflowCorrections,Ea as validateWorkflowDesignerCapabilities,Dr as validateWorkflowDesignerDocument,On as validateWorkflowHandlingNodes,xt as validateWorkflowInitiatorApprovalPolicy,Gi as validateWorkflowInstanceCommandPolicies,nr as validateWorkflowLaunchPreflight,Kf as validateWorkflowNodeConfigurationPatch,yn as validateWorkflowParallel,fn as validateWorkflowPlatformNotify,qi as validateWorkflowReadability,ss as validateWorkflowRejectionNotification,En as validateWorkflowReminders,In as validateWorkflowReturnPolicies,Hi as validateWorkflowRoleInputSelection,Cn as validateWorkflowRoleUnion,Vl as validateWorkflowSourceBundle,gn as validateWorkflowSupervisorChainBinding,An as validateWorkflowSupervisorChains,$n as validateWorkflowTaskPages,Wr as validateWorkflowUserCandidateBindings,qf as workflowApprovalCanSkip,sp as workflowApprovedDelegationRequests,hp as workflowAssignmentRoutingFacts,bp as workflowAssignmentRoutingPolicySchema,Qd as workflowAssignmentRoutingSemantic,ns as workflowBindingAllowsEmptyUsers,Ff as workflowBindingRoleCodes,ep as workflowBusinessCommandInvocationSchema,_t as workflowBusinessStepFactSchema,n_ as workflowBusinessStepHandlerDigest,Bu as workflowBusinessStepInput,Sd as workflowBusinessStepPath,t_ as workflowBusinessStepReceiptSignatureSuffix,pn as workflowBusinessStepValueMatches,El as workflowDelegationMutationRequestSchema,Hn as workflowDesignerTargets,H_ as workflowDesignerVariables,Wt as workflowExpressionPaths,hi as workflowForwardTargets,$f as workflowInitiatorApprovalCanComplete,wf as workflowInstanceCommandDeadlineError,hf as workflowInstanceTerminateCapabilityAllowed,Rf as workflowInstanceWithdrawalReasonRequired,pf as workflowNativeStagePolicySchema,Et as workflowNodeAllowedOperations,Vu as workflowNotificationBinding,jd as workflowOperationCommentRequired,Dn as workflowOperationMinimumOpinion,Mt as workflowOperationOpinion,Md as workflowOperationReasonRequired,Cp as workflowOwnedSubjectCreateSchema,Ki as workflowPolicyTimestamp,Zu as workflowPositionActive,fr as workflowProducedEventTypes,Hu as workflowReturnTargetPolicy,xe as workflowReturnTargets,Vf as workflowRoleCodesSchema,Ve as workflowSourceDigestEqual,ig as workflowSourceImportDrift,Na as workflowSourceReferences,og as workflowSourceStatus,Es as workflowTaskPageFieldState,Ap as workflowTaskPageReplayCoversInvalidation,Bf as workflowTaskSaveEnabled,mp as workflowTaskSubtableRows,Fd as workflowVariableLabel};