openxiangda-contracts 2.43.0 → 2.63.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/dist/browser.d.ts +8 -0
  2. package/dist/browser.d.ts.map +1 -1
  3. package/dist/browser.js +8 -0
  4. package/dist/browser.js.map +1 -1
  5. package/dist/concurrency.d.ts +2 -2
  6. package/dist/concurrency.d.ts.map +1 -1
  7. package/dist/data-field-validation.d.ts.map +1 -1
  8. package/dist/data-field-validation.js +13 -2
  9. package/dist/data-field-validation.js.map +1 -1
  10. package/dist/field-value-schemas.d.ts +1 -1
  11. package/dist/field-value-schemas.d.ts.map +1 -1
  12. package/dist/field-value-schemas.js +2 -1
  13. package/dist/field-value-schemas.js.map +1 -1
  14. package/dist/index.d.ts +8 -0
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +8 -0
  17. package/dist/index.js.map +1 -1
  18. package/dist/native-compiler/compiler.d.ts +1 -1
  19. package/dist/native-compiler/compiler.d.ts.map +1 -1
  20. package/dist/native-compiler/compiler.js +266 -22
  21. package/dist/native-compiler/compiler.js.map +1 -1
  22. package/dist/native-compiler/data-business-command.d.ts +42 -0
  23. package/dist/native-compiler/data-business-command.d.ts.map +1 -0
  24. package/dist/native-compiler/data-business-command.js +88 -0
  25. package/dist/native-compiler/data-business-command.js.map +1 -0
  26. package/dist/native-compiler/data-capacity.d.ts +8 -0
  27. package/dist/native-compiler/data-capacity.d.ts.map +1 -0
  28. package/dist/native-compiler/data-capacity.js +15 -0
  29. package/dist/native-compiler/data-capacity.js.map +1 -0
  30. package/dist/native-compiler/data-field.d.ts +2 -0
  31. package/dist/native-compiler/data-field.d.ts.map +1 -1
  32. package/dist/native-compiler/data-field.js +7 -2
  33. package/dist/native-compiler/data-field.js.map +1 -1
  34. package/dist/native-compiler/data-surface.d.ts +1 -1
  35. package/dist/native-compiler/data-surface.d.ts.map +1 -1
  36. package/dist/native-compiler/data-surface.js +2 -0
  37. package/dist/native-compiler/data-surface.js.map +1 -1
  38. package/dist/native-compiler/index.cjs +5 -5
  39. package/dist/native-compiler/index.d.ts +10 -0
  40. package/dist/native-compiler/index.d.ts.map +1 -1
  41. package/dist/native-compiler/index.js +5 -5
  42. package/dist/native-compiler/managed-concurrency.js +2 -2
  43. package/dist/native-compiler/managed-concurrency.js.map +1 -1
  44. package/dist/native-compiler/resource-view.d.ts +4 -0
  45. package/dist/native-compiler/resource-view.d.ts.map +1 -0
  46. package/dist/native-compiler/resource-view.js +20 -0
  47. package/dist/native-compiler/resource-view.js.map +1 -0
  48. package/dist/native-compiler/unique-keys.d.ts +21 -0
  49. package/dist/native-compiler/unique-keys.d.ts.map +1 -1
  50. package/dist/native-compiler/unique-keys.js +17 -3
  51. package/dist/native-compiler/unique-keys.js.map +1 -1
  52. package/dist/native-compiler/user-candidates.d.ts +72 -0
  53. package/dist/native-compiler/user-candidates.d.ts.map +1 -0
  54. package/dist/native-compiler/user-candidates.js +184 -0
  55. package/dist/native-compiler/user-candidates.js.map +1 -0
  56. package/dist/native-compiler/workflow-approval-empty.d.ts +28 -0
  57. package/dist/native-compiler/workflow-approval-empty.d.ts.map +1 -0
  58. package/dist/native-compiler/workflow-approval-empty.js +34 -0
  59. package/dist/native-compiler/workflow-approval-empty.js.map +1 -0
  60. package/dist/native-compiler/workflow-business-command.d.ts +108 -0
  61. package/dist/native-compiler/workflow-business-command.d.ts.map +1 -0
  62. package/dist/native-compiler/workflow-business-command.js +58 -0
  63. package/dist/native-compiler/workflow-business-command.js.map +1 -0
  64. package/dist/native-compiler/workflow-graph.d.ts +8 -0
  65. package/dist/native-compiler/workflow-graph.d.ts.map +1 -1
  66. package/dist/native-compiler/workflow-graph.js +1 -0
  67. package/dist/native-compiler/workflow-graph.js.map +1 -1
  68. package/dist/native-compiler/workflow-initiator-approval.d.ts +28 -0
  69. package/dist/native-compiler/workflow-initiator-approval.d.ts.map +1 -0
  70. package/dist/native-compiler/workflow-initiator-approval.js +30 -0
  71. package/dist/native-compiler/workflow-initiator-approval.js.map +1 -0
  72. package/dist/native-compiler/workflow-instance-policy.d.ts +2 -0
  73. package/dist/native-compiler/workflow-instance-policy.d.ts.map +1 -1
  74. package/dist/native-compiler/workflow-instance-policy.js +9 -4
  75. package/dist/native-compiler/workflow-instance-policy.js.map +1 -1
  76. package/dist/native-compiler/workflow-launch-preflight.d.ts +22 -0
  77. package/dist/native-compiler/workflow-launch-preflight.d.ts.map +1 -0
  78. package/dist/native-compiler/workflow-launch-preflight.js +30 -0
  79. package/dist/native-compiler/workflow-launch-preflight.js.map +1 -0
  80. package/dist/native-compiler/workflow-node-administration.d.ts +6 -0
  81. package/dist/native-compiler/workflow-node-administration.d.ts.map +1 -1
  82. package/dist/native-compiler/workflow-node-administration.js +9 -2
  83. package/dist/native-compiler/workflow-node-administration.js.map +1 -1
  84. package/dist/native-compiler/workflow-rejection-notification.d.ts +31 -0
  85. package/dist/native-compiler/workflow-rejection-notification.d.ts.map +1 -0
  86. package/dist/native-compiler/workflow-rejection-notification.js +47 -0
  87. package/dist/native-compiler/workflow-rejection-notification.js.map +1 -0
  88. package/dist/native-compiler/workflow-task-page.d.ts +44 -3
  89. package/dist/native-compiler/workflow-task-page.d.ts.map +1 -1
  90. package/dist/native-compiler/workflow-task-page.js +108 -9
  91. package/dist/native-compiler/workflow-task-page.js.map +1 -1
  92. package/dist/native-version.d.ts +19 -1
  93. package/dist/native-version.d.ts.map +1 -1
  94. package/dist/native-version.js +19 -1
  95. package/dist/native-version.js.map +1 -1
  96. package/dist/native.d.ts +15 -2
  97. package/dist/native.d.ts.map +1 -1
  98. package/dist/native.js.map +1 -1
  99. package/dist/schemas.d.ts +3048 -212
  100. package/dist/schemas.d.ts.map +1 -1
  101. package/dist/schemas.js +253 -9
  102. package/dist/schemas.js.map +1 -1
  103. package/dist/surface.d.ts +3 -2
  104. package/dist/surface.d.ts.map +1 -1
  105. package/dist/surface.js +1 -19
  106. package/dist/surface.js.map +1 -1
  107. package/dist/types.d.ts +286 -8
  108. package/dist/types.d.ts.map +1 -1
  109. package/dist/types.js +4 -0
  110. package/dist/types.js.map +1 -1
  111. package/dist/validation.d.ts.map +1 -1
  112. package/dist/validation.js +42 -5
  113. package/dist/validation.js.map +1 -1
  114. package/package.json +1 -1
@@ -1,9 +1,9 @@
1
- import{createHash as Bi}from"node:crypto";function Ki(e){if(!e||typeof e!="object")return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function zt(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)=>zt(n,`${t}[${i}]`)).join(",")}]`;if(Ki(e))return`{${Object.keys(e).filter(i=>e[i]!==void 0).sort((i,s)=>i===s?0:i<s?-1:1).map(i=>`${JSON.stringify(i)}:${zt(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 ee(e){return zt(e,"$")}function X(e){return Bi("sha256").update(ee(e)).digest("hex")}var to=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,Xt=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,Gi=["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"],qi=new Set(Gi),no=new Set(["option.multiple","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","file","image","subtable"]),Qn=new Set(["option.single","option.multiple","cascade.single","cascade.multiple"]),Zn=new Set(["resource-ref.single","resource-ref.multiple"]),Qt=[{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}],oo=new Map(Qt.map(e=>[e.code,e])),Ee=class extends Error{constructor(o,n){super(o);this.code=o;this.pointer=n;this.name="NativeDataFieldContractV2Error"}code;pointer};function It(e){return no.has(e)}function Nt(e,t={}){return e.type!=="serial-number"&&t.system!==!0&&e.nullable===!1&&(!It(e.type)||t.requiredHint===!0)}function Zt(e,t,o=500){Array.isArray(e)||w("NATIVE_ARRAY_REQUIRED",t),e.length===0&&w("NATIVE_DATA_FIELDS_REQUIRED",t),e.length>o&&w("NATIVE_ARRAY_LIMIT_EXCEEDED",t);let n=new Set;return e.map((i,s)=>{let c=`${t}/${s}`,r=le(i,c);pe(r,["code","type","nullable","indexed","options","source","maxLength","precision","scale","exactDecimal","min","max","rangeBoundary","timePrecision","file","serial","subtable"],c);let a=me(r.code,`${c}/code`,63);to.test(a)||w("NATIVE_FIELD_CODE_INVALID",`${c}/code`),n.has(a)&&w("NATIVE_DATA_FIELD_DUPLICATE",`${c}/code`),n.add(a);let d=me(r.type,`${c}/type`,32);qi.has(d)||w("NATIVE_DATA_FIELD_TYPE_INVALID",`${c}/type`);let u=d,l=Ht(r.nullable,`${c}/nullable`),f=Ht(r.indexed,`${c}/indexed`);l===!0&&no.has(u)&&w("NATIVE_DATA_MULTI_FIELD_NULLABLE_INVALID",`${c}/nullable`);let A=Yi(r.options,u,c),N=Hi(r.source,u,c),I=Qi(r,u,c),m=Ht(r.exactDecimal,`${c}/exactDecimal`);m!==void 0&&u!=="number.decimal"&&w("NATIVE_DATA_FIELD_EXACT_DECIMAL_TYPE_INVALID",`${c}/exactDecimal`);let E=Ji(r.rangeBoundary,u,c),p=Zi(r.file,u,c),g=es(r.serial,u,c),O=ts(r.subtable,u,c);return{code:a,type:u,...l===void 0?{}:{nullable:l},...f===void 0?{}:{indexed:f},...A?{options:A}:{},...N?{source:N}:{},...I,...m===void 0?{}:{exactDecimal:m},...E?{rangeBoundary:E}:{},...p?{file:p}:{},...g?{serial:g}:{},...O?{subtable:O}:{}}})}function Ji(e,t,o){let n=`${o}/rangeBoundary`;if(!(t==="date-range"||t==="datetime-range")){e!==void 0&&w("NATIVE_DATA_FIELD_RANGE_BOUNDARY_TYPE_INVALID",n);return}return e!=="closed"&&e!=="half-open"&&w("NATIVE_DATA_FIELD_RANGE_BOUNDARY_REQUIRED",n),e}function io(e,t){Array.isArray(e)||w("NATIVE_ARRAY_REQUIRED",t);let o=new Map;e.forEach((n,i)=>{let s=`${t}/${i}`,c=le(n,s),r=me(c.code,`${s}/code`,64);(!Xt.test(r)||o.has(r))&&w("NATIVE_RESOURCE_CODE_INVALID",`${s}/code`);let a=le(c.schema,`${s}/schema`);o.set(r,{pointer:s,fields:Zt(a.fields,`${s}/schema/fields`)})});for(let[n,i]of o){let s=new Map(i.fields.map(r=>[r.code,r]));i.fields.filter(r=>r.type==="subtable").reduce((r,a)=>r+(a.subtable?.maxRows??20),0)>49&&w("NATIVE_DATA_FIELD_SUBTABLE_AGGREGATE_MAX_ROWS_EXCEEDED",`${i.pointer}/schema/fields`),i.fields.forEach((r,a)=>{let d=`${i.pointer}/schema/fields/${a}`;if(r.source&&zi(r.source,s,o,`${d}/source`),r.subtable){let u=o.get(r.subtable.resourceCode);(!u||r.subtable.resourceCode===n)&&w("NATIVE_DATA_FIELD_SUBTABLE_TARGET_MISSING",`${d}/subtable/resourceCode`);let l=u.fields.find(A=>A.code===r.subtable?.foreignKey);(!l||l.type!=="uuid"||l.nullable!==!1)&&w("NATIVE_DATA_FIELD_SUBTABLE_FOREIGN_KEY_INVALID",`${d}/subtable/foreignKey`);let f=u.fields.find(A=>A.code===r.subtable?.orderField);(!f||f.type!=="number.integer"||f.nullable!==!1)&&w("NATIVE_DATA_FIELD_SUBTABLE_ORDER_FIELD_INVALID",`${d}/subtable/orderField`)}})}}function so(e,t,o){if(e===void 0)return[];(!Array.isArray(e)||e.length>20)&&w("NATIVE_DATA_RESOURCE_INVARIANTS_INVALID",o);let n=new Map(t.map(s=>[s.code,s])),i=new Set;return e.map((s,c)=>{let r=`${o}/${c}`,a=le(s,r);pe(a,["code","message","expression"],r);let d=me(a.code,`${r}/code`,128);(!/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/.test(d)||i.has(d))&&w("NATIVE_DATA_RESOURCE_INVARIANT_CODE_INVALID",`${r}/code`),i.add(d);let u=Et(a.message,`${r}/message`,500);u!==void 0&&u.length===0&&w("NATIVE_DATA_RESOURCE_INVARIANT_MESSAGE_INVALID",`${r}/message`);let l=le(a.expression,`${r}/expression`);if(l.kind==="nonBlankTextWhenOption"){pe(l,["kind","optionField","optionValue","textField"],`${r}/expression`);let p=Ae(l.optionField,`${r}/expression/optionField`),g=Ae(l.textField,`${r}/expression/textField`),O=me(l.optionValue,`${r}/expression/optionValue`,128),y=n.get(p),T=n.get(g);return(!y||!T)&&w("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_UNKNOWN",`${r}/expression`),(y.type!=="option.single"||!["text.short","text.long"].includes(T.type)||!y.options?.some(h=>h.value===O))&&w("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_TYPES_INVALID",`${r}/expression`),{code:d,...u===void 0?{}:{message:u},expression:{kind:"nonBlankTextWhenOption",optionField:p,optionValue:O,textField:g}}}pe(l,["leftField","operator","rightField"],`${r}/expression`);let f=Ae(l.leftField,`${r}/expression/leftField`),A=Ae(l.rightField,`${r}/expression/rightField`),N=n.get(f),I=n.get(A);(!N||!I)&&w("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_UNKNOWN",`${r}/expression`),N.type===I.type||["number.integer","number.decimal"].includes(N.type)&&["number.integer","number.decimal"].includes(I.type)||w("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_TYPES_INVALID",`${r}/expression`);let E=String(l.operator);return["eq","neq","gt","gte","lt","lte"].includes(E)||w("NATIVE_DATA_RESOURCE_INVARIANT_OPERATOR_INVALID",`${r}/expression/operator`),!["eq","neq"].includes(E)&&!["number.integer","number.decimal","date","time","datetime","text.short","text.long","text.rich","serial-number","uuid"].includes(N.type)&&w("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_TYPES_INVALID",`${r}/expression`),{code:d,...u===void 0?{}:{message:u},expression:{leftField:f,operator:E,rightField:A}}})}function zi(e,t,o,n){let i=o.get(e.resourceCode);i||w("NATIVE_DATA_FIELD_SOURCE_TARGET_MISSING",`${n}/resourceCode`);let s=new Map(i.fields.map(r=>[r.code,r])),c=s.get(e.labelField);(!c||!["text.short","text.long"].includes(c.type))&&w("NATIVE_DATA_FIELD_SOURCE_LABEL_INVALID",`${n}/labelField`);for(let r of["searchFields","descriptionFields","snapshotFields"])for(let a of e[r]||[])s.has(a)||w("NATIVE_DATA_FIELD_SOURCE_FIELD_MISSING",`${n}/${r}`);for(let[r,a]of(e.filters||[]).entries())s.has(a.field)||w("NATIVE_DATA_FIELD_SOURCE_FILTER_FIELD_MISSING",`${n}/filters/${r}/field`),"binding"in a&&!t.has(a.binding.field)&&w("NATIVE_DATA_FIELD_SOURCE_BINDING_FIELD_MISSING",`${n}/filters/${r}/binding/field`)}function Yi(e,t,o){let n=`${o}/options`;if(e===void 0){Qn.has(t)&&w("NATIVE_DATA_FIELD_OPTIONS_REQUIRED",n);return}(!Qn.has(t)||!Array.isArray(e))&&w("NATIVE_DATA_FIELD_OPTIONS_TYPE_INVALID",n),(e.length<1||e.length>100)&&w("NATIVE_DATA_FIELD_OPTIONS_INVALID",n);let i=0,s=(c,r,a)=>{a>5&&w("NATIVE_DATA_FIELD_OPTIONS_DEPTH_EXCEEDED",r);let d=new Set;return c.map((u,l)=>{i+=1,i>1e3&&w("NATIVE_DATA_FIELD_OPTIONS_COUNT_EXCEEDED",n);let f=`${r}/${l}`,A=le(u,f);pe(A,["label","value","description","color","children"],f);let N=me(A.label,`${f}/label`,500),I=me(A.value,`${f}/value`,500);d.has(I)&&w("NATIVE_DATA_FIELD_OPTION_VALUE_DUPLICATE",`${f}/value`),d.add(I);let m=Et(A.description,`${f}/description`,2e3),E=Et(A.color,`${f}/color`,64),p;return A.children!==void 0&&((!t.startsWith("cascade.")||!Array.isArray(A.children))&&w("NATIVE_DATA_FIELD_OPTION_CHILDREN_INVALID",`${f}/children`),(A.children.length<1||A.children.length>100)&&w("NATIVE_DATA_FIELD_OPTION_CHILDREN_INVALID",`${f}/children`),p=s(A.children,`${f}/children`,a+1)),{label:N,value:I,...m===void 0?{}:{description:m},...E===void 0?{}:{color:E},...p?{children:p}:{}}})};return s(e,n,1)}function Hi(e,t,o){let n=`${o}/source`;if(e===void 0){Zn.has(t)&&w("NATIVE_DATA_FIELD_SOURCE_REQUIRED",n);return}Zn.has(t)||w("NATIVE_DATA_FIELD_SOURCE_TYPE_INVALID",n);let i=le(e,n);pe(i,["kind","resourceCode","labelField","searchFields","descriptionFields","snapshotFields","filters","pageSize","loadMode"],n),i.kind!=="resource"&&w("NATIVE_DATA_FIELD_SOURCE_KIND_INVALID",`${n}/kind`);let s=me(i.resourceCode,`${n}/resourceCode`,64);Xt.test(s)||w("NATIVE_RESOURCE_CODE_INVALID",`${n}/resourceCode`);let c=Ae(i.labelField,`${n}/labelField`),r=Yt(i.searchFields,`${n}/searchFields`,10),a=Yt(i.descriptionFields,`${n}/descriptionFields`,10),d=Yt(i.snapshotFields,`${n}/snapshotFields`,50),u=Be(i.pageSize,`${n}/pageSize`,1,100),l;i.loadMode!==void 0&&(["search","all"].includes(String(i.loadMode))||w("NATIVE_DATA_FIELD_SOURCE_LOAD_MODE_INVALID",`${n}/loadMode`),l=i.loadMode);let f=Xi(i.filters,`${n}/filters`);return{kind:"resource",resourceCode:s,labelField:c,...r?{searchFields:r}:{},...a?{descriptionFields:a}:{},...d?{snapshotFields:d}:{},...f?{filters:f}:{},...u===void 0?{}:{pageSize:u},...l?{loadMode:l}:{}}}function Xi(e,t){if(e!==void 0)return(!Array.isArray(e)||e.length>20)&&w("NATIVE_DATA_FIELD_SOURCE_FILTERS_INVALID",t),e.map((o,n)=>{let i=`${t}/${n}`,s=le(o,i),c=Object.prototype.hasOwnProperty.call(s,"value"),r=Object.prototype.hasOwnProperty.call(s,"binding");pe(s,c?["field","operator","value"]:["field","operator","binding"],i),c===r&&w("NATIVE_DATA_FIELD_SOURCE_FILTER_VALUE_INVALID",i);let a=Ae(s.field,`${i}/field`);["eq","in"].includes(String(s.operator))||w("NATIVE_DATA_FIELD_SOURCE_FILTER_OPERATOR_INVALID",`${i}/operator`);let d=s.operator;if(c)return{field:a,operator:d,value:s.value};let u=le(s.binding,`${i}/binding`);return pe(u,["kind","field"],`${i}/binding`),u.kind!=="field"&&w("NATIVE_DATA_FIELD_SOURCE_BINDING_KIND_INVALID",`${i}/binding/kind`),{field:a,operator:d,binding:{kind:"field",field:Ae(u.field,`${i}/binding/field`)}}})}function Qi(e,t,o){let n={};if(e.maxLength!==void 0&&(["text.short","text.long","text.rich"].includes(t)||w("NATIVE_DATA_FIELD_MAX_LENGTH_TYPE_INVALID",`${o}/maxLength`),n.maxLength=At(e.maxLength,`${o}/maxLength`,1,1e6)),(e.precision!==void 0||e.scale!==void 0)&&((t!=="number.decimal"||e.precision===void 0)&&w("NATIVE_DATA_FIELD_DECIMAL_CONFIG_INVALID",o),n.precision=At(e.precision,`${o}/precision`,1,1e3),n.scale=e.scale===void 0?0:At(e.scale,`${o}/scale`,0,n.precision)),e.min!==void 0||e.max!==void 0){["number.integer","number.decimal"].includes(t)||w("NATIVE_DATA_FIELD_NUMERIC_BOUNDS_TYPE_INVALID",o);let i=eo(e.min,`${o}/min`),s=eo(e.max,`${o}/max`);t==="number.integer"&&[i,s].some(c=>c!==void 0&&!Number.isSafeInteger(c))&&w("NATIVE_DATA_FIELD_NUMERIC_BOUNDS_INVALID",o),i!==void 0&&s!==void 0&&i>s&&w("NATIVE_DATA_FIELD_NUMERIC_BOUNDS_INVALID",o),i!==void 0&&(n.min=i),s!==void 0&&(n.max=s)}return e.timePrecision!==void 0&&((t!=="time"||!["minute","second"].includes(e.timePrecision))&&w("NATIVE_DATA_FIELD_TIME_PRECISION_INVALID",`${o}/timePrecision`),n.timePrecision=e.timePrecision),n}function Zi(e,t,o){if(e===void 0)return;let n=`${o}/file`;["file","image","signature"].includes(t)||w("NATIVE_DATA_FIELD_FILE_TYPE_INVALID",n);let i=le(e,n);pe(i,["maxCount","maxSizeMb","accept"],n);let s=Be(i.maxCount,`${n}/maxCount`,1,100);t==="signature"&&s!==void 0&&s!==1&&w("NATIVE_DATA_FIELD_SIGNATURE_COUNT_INVALID",`${n}/maxCount`);let c=Be(i.maxSizeMb,`${n}/maxSizeMb`,1,1024),r;return i.accept!==void 0&&((!Array.isArray(i.accept)||i.accept.length>50)&&w("NATIVE_DATA_FIELD_FILE_ACCEPT_INVALID",`${n}/accept`),r=i.accept.map((a,d)=>me(a,`${n}/accept/${d}`,255)),new Set(r).size!==r.length&&w("NATIVE_DATA_FIELD_FILE_ACCEPT_INVALID",`${n}/accept`)),{...s===void 0?{}:{maxCount:s},...c===void 0?{}:{maxSizeMb:c},...r===void 0?{}:{accept:r}}}function es(e,t,o){let n=`${o}/serial`;if(e===void 0){t==="serial-number"&&w("NATIVE_DATA_FIELD_SERIAL_REQUIRED",n);return}t!=="serial-number"&&w("NATIVE_DATA_FIELD_SERIAL_TYPE_INVALID",n);let i=le(e,n);pe(i,["prefix","digits","start"],n);let s=Et(i.prefix,`${n}/prefix`,64),c=Be(i.digits,`${n}/digits`,1,32),r=Be(i.start,`${n}/start`,0,Number.MAX_SAFE_INTEGER);return{...s===void 0?{}:{prefix:s},...c===void 0?{}:{digits:c},...r===void 0?{}:{start:r}}}function ts(e,t,o){let n=`${o}/subtable`;if(e===void 0){t==="subtable"&&w("NATIVE_DATA_FIELD_SUBTABLE_REQUIRED",n);return}t!=="subtable"&&w("NATIVE_DATA_FIELD_SUBTABLE_TYPE_INVALID",n);let i=le(e,n);pe(i,["resourceCode","foreignKey","orderField","maxRows"],n);let s=me(i.resourceCode,`${n}/resourceCode`,64);Xt.test(s)||w("NATIVE_RESOURCE_CODE_INVALID",`${n}/resourceCode`);let c=Ae(i.foreignKey,`${n}/foreignKey`),r=Ae(i.orderField,`${n}/orderField`);r===c&&w("NATIVE_DATA_FIELD_SUBTABLE_ORDER_FIELD_INVALID",`${n}/orderField`);let a=Be(i.maxRows,`${n}/maxRows`,1,49);return{resourceCode:s,foreignKey:c,orderField:r,...a===void 0?{}:{maxRows:a}}}function Yt(e,t,o){if(e===void 0)return;(!Array.isArray(e)||e.length>o)&&w("NATIVE_DATA_FIELD_SOURCE_FIELDS_INVALID",t);let n=e.map((i,s)=>Ae(i,`${t}/${s}`));return new Set(n).size!==n.length&&w("NATIVE_DATA_FIELD_SOURCE_FIELDS_INVALID",t),n}function Ae(e,t){let o=me(e,t,63);return to.test(o)||w("NATIVE_FIELD_CODE_INVALID",t),o}function le(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&w("NATIVE_OBJECT_REQUIRED",t),e}function pe(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 me(e,t,o){return(typeof e!="string"||e.length===0||e.length>o)&&w("NATIVE_STRING_INVALID",t),e}function Et(e,t,o){if(e!==void 0)return(typeof e!="string"||e.length>o)&&w("NATIVE_STRING_INVALID",t),e}function Ht(e,t){if(e!==void 0)return typeof e!="boolean"&&w("NATIVE_BOOLEAN_REQUIRED",t),e}function Be(e,t,o,n){if(e!==void 0)return At(e,t,o,n)}function eo(e,t){if(e!==void 0)return(typeof e!="number"||!Number.isFinite(e))&&w("NATIVE_NUMBER_REQUIRED",t),e}function At(e,t,o,n){return(!Number.isSafeInteger(e)||Number(e)<o||Number(e)>n)&&w("NATIVE_INTEGER_OUT_OF_RANGE",t),Number(e)}function w(e,t){throw new Ee(e,t)}var ro=["created_by","updated_by","created_at","updated_at"];function Ze(e){return ro.includes(e)}function ao(e){return ro.some(t=>Object.prototype.hasOwnProperty.call(e.fieldPolicies||{},t))}var ns=Qt.map(e=>e.code);function co(e){return ns.includes(e)}var os=["eq","neq","gt","gte","lt","lte","contains","startsWith","endsWith","in","between","has","hasAny","hasAll","overlaps","containedBy","jsonContains","isEmpty","isNotEmpty"],is=new Set(os);function Oa(e){return is.has(String(e))}var en=["eq","neq","contains","startsWith","endsWith","in","isEmpty","isNotEmpty"],et=["eq","neq","gt","gte","lt","lte","between","in","isEmpty"],ss=["eq","neq","in","isEmpty"],yt=["eq","neq","in","isEmpty","isNotEmpty"],Ke=["has","hasAny","hasAll","isEmpty","isNotEmpty"],lo=["overlaps","contains","containedBy","isEmpty"],tn=["jsonContains","isEmpty","isNotEmpty"],nn=["isEmpty","isNotEmpty"],rs={"text.short":en,"text.long":en,"text.rich":en,"number.integer":et,"number.decimal":et,boolean:ss,date:et,time:et,datetime:et,"date-range":lo,"datetime-range":lo,"option.single":yt,"option.multiple":Ke,"cascade.single":Ke,"cascade.multiple":Ke,"user.single":yt,"user.multiple":Ke,"department.single":yt,"department.multiple":Ke,"resource-ref.single":yt,"resource-ref.multiple":Ke,file:nn,image:nn,signature:nn,address:tn,location:tn,uuid:["eq","neq","in","isEmpty"],json:tn,"serial-number":["eq","neq","in","contains","startsWith"],subtable:[]},as=new Set(["text.short","text.long","text.rich","option.single","user.single","department.single","resource-ref.single","serial-number"]),cs=new Set(["option.multiple","cascade.single","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","file","image","signature","address","location","json","subtable"]);function fo(e){return rs[e]}function ha(e,t){return fo(e).includes(t)}function on(e){return as.has(e)}function tt(e){return!cs.has(e)}function po(e){return fo(e).length>0}var uo=new Set(["number.integer","number.decimal"]),mo=new Set(["text.short","text.long","number.integer","number.decimal","date","time","datetime","serial-number"]),ds=new Set([...mo,"boolean","uuid"]),ls=new Set(["option.single","user.single","department.single","resource-ref.single"]);function Ra(e,t){return t==="sum"||t==="avg"?uo.has(e)?{valueExpression:"column",numericResult:!0}:null:t==="min"||t==="max"?mo.has(e)?{valueExpression:"column",numericResult:uo.has(e)}:null:ls.has(e)?{valueExpression:"snapshot-value",numericResult:!0}:ds.has(e)?{valueExpression:"column",numericResult:!0}:null}var rn=["version","maxBytes","fields"];function go(e,t){if(e===void 0)return;let o=sn(e,t);_o(o,rn,t);let n=bt(o.version,`${t}/version`,1,1e6),i=bt(o.maxBytes,`${t}/maxBytes`,2,196608);(!n||!i)&&se("NATIVE_DATA_DRAFT_STATE_SCHEMA_INVALID",t);let s=sn(o.fields,`${t}/fields`),c=Object.entries(s);(!c.length||c.length>50)&&se("NATIVE_DATA_DRAFT_STATE_FIELDS_INVALID",`${t}/fields`);for(let[r,a]of c){let d=`${t}/fields/${r}`;/^[A-Za-z][A-Za-z0-9_]{0,62}$/.test(r)||se("NATIVE_DATA_DRAFT_STATE_FIELD_CODE_INVALID",d);let u=sn(a,d),l=Ao(u.type,`${d}/type`,32),f=l==="string"?["type","required","maxLength","enum"]:l==="json.object"?["type","required","maxBytes"]:["type","required"];if(["string","number","integer","boolean","json.object"].includes(l)||se("NATIVE_DATA_DRAFT_STATE_FIELD_TYPE_INVALID",`${d}/type`),_o(u,f,d),fs(u.required,`${d}/required`),l==="string"){let A=bt(u.maxLength,`${d}/maxLength`,1,196608);A||se("NATIVE_DATA_DRAFT_STATE_FIELD_INVALID",d),u.enum!==void 0&&us(u.enum,`${d}/enum`,100,!1).some(I=>I.length>A)&&se("NATIVE_DATA_DRAFT_STATE_FIELD_INVALID",`${d}/enum`)}else if(l==="json.object"){let A=bt(u.maxBytes,`${d}/maxBytes`,2,65536);(!A||A>i)&&se("NATIVE_DATA_DRAFT_STATE_FIELD_INVALID",d)}}}function us(e,t,o,n){(!Array.isArray(e)||!n&&e.length===0||e.length>o)&&se("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t);let i=e.map((s,c)=>Ao(s,`${t}/${c}`,255));return new Set(i).size!==i.length&&se("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t),i}function sn(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&se("NATIVE_OBJECT_REQUIRED",t),e}function _o(e,t,o){let n=new Set(t);for(let i of Object.keys(e))n.has(i)||se("NATIVE_PROPERTY_UNKNOWN",`${o}/${i}`)}function Ao(e,t,o){return(typeof e!="string"||e.length===0||e.length>o)&&se("NATIVE_STRING_INVALID",t),e}function fs(e,t){e!==void 0&&typeof e!="boolean"&&se("NATIVE_BOOLEAN_REQUIRED",t)}function bt(e,t,o,n){return(!Number.isSafeInteger(e)||Number(e)<o||Number(e)>n)&&se("NATIVE_INTEGER_INVALID",t),Number(e)}function se(e,t){throw new Ee(e,t)}var ps=500,Ce={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","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:rn,mobile:["enabled"]},ms={"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 dn(e,t,o){if(e===void 0)return;let n=ne(e,o);Ie(n,Ce.surface,o);let i=n.mutationOwner===void 0?"native":Oe(n.mutationOwner,`${o}/mutationOwner`,16);["native","action","readonly","workflow","queued-command"].includes(i)||L("NATIVE_DATA_SURFACE_MUTATION_OWNER_INVALID",`${o}/mutationOwner`);let s=n.generated===void 0?{}:ne(n.generated,`${o}/generated`);Ie(s,Ce.generated,`${o}/generated`);for(let a of Ce.generated)cn(s[a],`${o}/generated/${a}`);if(i!=="native")for(let a of["create","update","delete"])s[a]===!0&&L("NATIVE_DATA_SURFACE_MUTATION_OWNER_CONFLICT",`${o}/generated/${a}`);let c=new Map(t.map(a=>[a.code,a])),r=ne(n.fields,`${o}/fields`);for(let a of Object.keys(r))c.has(a)||L("NATIVE_DATA_SURFACE_FIELD_MISSING",`${o}/fields/${a}`);for(let a of t)Object.prototype.hasOwnProperty.call(r,a.code)||L("NATIVE_DATA_SURFACE_FIELD_REQUIRED",`${o}/fields/${a.code}`),gs(r[a.code],a,`${o}/fields/${a.code}`);for(let a of["create","update"]){let d=s[a]??i==="native",u=t.some(l=>{let f=ne(r[l.code],`${o}/fields/${l.code}`);return Io(l,f,a)});d&&!u&&L("NATIVE_DATA_SURFACE_WRITABLE_FIELDS_REQUIRED",`${o}/generated/${a}`)}if(As(n.list,c,`${o}/list`),Eo(n.form,c,`${o}/form`,"form"),Eo(n.detail,c,`${o}/detail`,"detail"),n.mobile!==void 0){let a=ne(n.mobile,`${o}/mobile`);Ie(a,Ce.mobile,`${o}/mobile`),cn(a.enabled,`${o}/mobile/enabled`)}_s(n,t,o)}function ln(e,t){let o=e.views?.find(i=>i.code===t);o||L("NATIVE_DATA_VIEW_NOT_FOUND",`/surface/views/${t}`);let n=new Map((o.sections||[]).flatMap(i=>i.fields.map(s=>[s,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,s])=>{let c={...s};delete c.section;let r=n.get(i);return[i,{...c,...r?{section:r}:{},list:o.list.fieldOrder.includes(i)}]}))}}function _s(e,t,o){if(e.views===void 0)return;(!Array.isArray(e.views)||e.views.length>20)&&L("NATIVE_DATA_VIEWS_LIMIT_INVALID",`${o}/views`);let n=new Set;e.views.forEach((i,s)=>{let c=`${o}/views/${s}`,r=ne(i,c);Ie(r,["code","name","generated","list","form","detail","mobile","sections"],c);let a=Oe(r.code,`${c}/code`,64);(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(a)||n.has(a))&&L("NATIVE_DATA_VIEW_CODE_INVALID",`${c}/code`),n.add(a),Oe(r.name,`${c}/name`,255),ne(r.generated,`${c}/generated`),ne(r.mobile,`${c}/mobile`);for(let u of["list","detail","create","update","delete"])typeof r.generated[u]!="boolean"&&L("NATIVE_DATA_VIEW_OPERATION_INVALID",`${c}/generated/${u}`);typeof r.mobile.enabled!="boolean"&&L("NATIVE_DATA_VIEW_MOBILE_INVALID",`${c}/mobile/enabled`);for(let u of["list","form","detail"]){let l=ne(r[u],`${c}/${u}`),f=Ge(l.fieldOrder,`${c}/${u}/fieldOrder`,500,!0);for(let A of f){let N=e.fields[A];(!N||(N.hidden??N.system)===!0)&&L("NATIVE_DATA_VIEW_FIELD_INVALID",`${c}/${u}/fieldOrder`)}}if(r.sections!==void 0){(!Array.isArray(r.sections)||r.sections.length>100)&&L("NATIVE_DATA_VIEW_SECTIONS_INVALID",`${c}/sections`);let u=new Set;r.sections.forEach((l,f)=>{let A=`${c}/sections/${f}`,N=ne(l,A);Ie(N,["title","fields"],A),Oe(N.title,`${A}/title`,255);for(let I of Ge(N.fields,`${A}/fields`,100,!0)){let m=e.fields[I];(!m||(m.hidden??m.system)===!0||u.has(I))&&L("NATIVE_DATA_VIEW_FIELD_INVALID",`${A}/fields`),u.add(I)}})}let d=ln(e,a);if(dn(d,t,c),r.generated.create!==!1&&(e.mutationOwner||"native")==="native")for(let u of t)Nt(u,e.fields[u.code])&&Io(u,e.fields[u.code],"create")&&!r.form.fieldOrder.includes(u.code)&&L("NATIVE_DATA_VIEW_CREATE_REQUIRED_FIELD_MISSING",`${c}/form/fieldOrder`)})}function Io(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 gs(e,t,o){let n=ne(e,o);Ie(n,Ce.field,o),Oe(n.label,`${o}/label`,500),n.type!==t.type&&L("NATIVE_DATA_SURFACE_FIELD_TYPE_MISMATCH",`${o}/type`);let i=Oe(n.widget,`${o}/widget`,64);ms[t.type].includes(i)||L("NATIVE_DATA_SURFACE_WIDGET_INCOMPATIBLE",`${o}/widget`),Ns(n.section,`${o}/section`,255);for(let s of["requiredHint","system","hidden","list","searchable","sortable"])cn(n[s],`${o}/${s}`);n.searchable===!0&&!on(t.type)&&L("NATIVE_DATA_SURFACE_SEARCH_UNSUPPORTED",`${o}/searchable`),n.sortable===!0&&!tt(t.type)&&L("NATIVE_DATA_SURFACE_SORT_UNSUPPORTED",`${o}/sortable`);for(let s of["readCapabilities","createCapabilities","updateCapabilities"])Ge(n[s],`${o}/${s}`,100,!0);if(n.maxCount!==void 0&&(!Number.isSafeInteger(n.maxCount)||Number(n.maxCount)<1||Number(n.maxCount)>100)&&L("NATIVE_DATA_SURFACE_MAX_COUNT_INVALID",`${o}/maxCount`),n.maxSizeMb!==void 0&&(!Number.isSafeInteger(n.maxSizeMb)||Number(n.maxSizeMb)<1||Number(n.maxSizeMb)>1024)&&L("NATIVE_DATA_SURFACE_MAX_SIZE_INVALID",`${o}/maxSizeMb`),n.accept!==void 0){let s=Array.isArray(n.accept)?n.accept:[n.accept];Ge(s,`${o}/accept`,50,!1)}for(let s of["maxLength","precision","scale","exactDecimal","min","max","rangeBoundary","options","source","timePrecision","serial","subtable"])Es(n,t,s,o);Is(n,t,o)}function As(e,t,o){if(e===void 0)return;let n=ne(e,o);if(Ie(n,Ce.list,o),n.actions!==void 0){let i=ne(n.actions,`${o}/actions`);Ie(i,["import","export"],`${o}/actions`);for(let s of["import","export"])i[s]!==void 0&&typeof i[s]!="boolean"&&L("NATIVE_DATA_SURFACE_LIST_ACTION_INVALID",`${o}/actions/${s}`)}if(n.fieldOrder!==void 0)for(let i of Ge(n.fieldOrder,`${o}/fieldOrder`,500,!0))t.has(i)||L("NATIVE_DATA_SURFACE_LIST_FIELD_INVALID",`${o}/fieldOrder`);n.defaultPageSize!==void 0&&(!Number.isSafeInteger(n.defaultPageSize)||Number(n.defaultPageSize)<1||Number(n.defaultPageSize)>200)&&L("NATIVE_DATA_SURFACE_PAGE_SIZE_INVALID",`${o}/defaultPageSize`);for(let[i,s]of[["searchableFields",on],["filterFields",po]]){if(n[i]===void 0)continue;let c=Ge(n[i],`${o}/${i}`,100,!0);for(let r of c){let a=t.get(r);(!a||!s(a.type))&&L("NATIVE_DATA_SURFACE_LIST_FIELD_INVALID",`${o}/${i}`)}}if(n.defaultSort!==void 0){let i=ne(n.defaultSort,`${o}/defaultSort`);Ie(i,Ce.defaultSort,`${o}/defaultSort`);let s=Oe(i.field,`${o}/defaultSort/field`,63),c=t.get(s);!co(s)&&(!c||!tt(c.type))&&L("NATIVE_DATA_SURFACE_SORT_UNSUPPORTED",`${o}/defaultSort/field`),i.order!==void 0&&!["asc","desc"].includes(i.order)&&L("NATIVE_DATA_SURFACE_SORT_ORDER_INVALID",`${o}/defaultSort/order`)}}function Eo(e,t,o,n){if(e===void 0)return;let i=ne(e,o);if(Ie(i,Ce[n],o),i.layout!==void 0&&!["flat","sections"].includes(i.layout)&&L("NATIVE_DATA_SURFACE_LAYOUT_INVALID",`${o}/layout`),i.fieldOrder!==void 0){let s=`${o}/fieldOrder`;(!Array.isArray(i.fieldOrder)||i.fieldOrder.length>t.size||i.fieldOrder.length>ps)&&L("NATIVE_DATA_SURFACE_FIELD_ORDER_INVALID",s);let c=i.fieldOrder.map((r,a)=>Oe(r,`${s}/${a}`,63));new Set(c).size!==c.length&&L("NATIVE_DATA_SURFACE_FIELD_ORDER_INVALID",s),c.forEach((r,a)=>{t.has(r)||L("NATIVE_DATA_SURFACE_FIELD_ORDER_FIELD_MISSING",`${s}/${a}`)})}n==="form"&&go(i.draftState,`${o}/draftState`)}function Es(e,t,o,n){e[o]===void 0&&t[o]===void 0||((e[o]===void 0||t[o]===void 0)&&L("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${n}/${o}`),ee(e[o])!==ee(t[o])&&L("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${n}/${o}`))}function Is(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:an(e.accept)}};for(let s of["maxCount","maxSizeMb","accept"]){if(i[s]===void 0&&n[s]===void 0)continue;(i[s]===void 0||n[s]===void 0)&&L("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${o}/${s}`);let c=s==="accept"?an(i[s]):i[s],r=s==="accept"?an(n[s]):n[s];ee(c)!==ee(r)&&L("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${o}/${s}`)}}function an(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 Ge(e,t,o,n){(!Array.isArray(e)||!n&&e.length===0||e.length>o)&&L("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t);let i=e.map((s,c)=>Oe(s,`${t}/${c}`,255));return new Set(i).size!==i.length&&L("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t),i}function ne(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&L("NATIVE_OBJECT_REQUIRED",t),e}function Ie(e,t,o){let n=new Set(t);for(let i of Object.keys(e))n.has(i)||L("NATIVE_PROPERTY_UNKNOWN",`${o}/${i}`)}function Oe(e,t,o){return(typeof e!="string"||e.length===0||e.length>o)&&L("NATIVE_STRING_INVALID",t),e}function Ns(e,t,o){e!==void 0&&(typeof e!="string"||e.length>o)&&L("NATIVE_STRING_INVALID",t)}function cn(e,t){e!==void 0&&typeof e!="boolean"&&L("NATIVE_BOOLEAN_REQUIRED",t)}function L(e,t){throw new Ee(e,t)}var nt=class extends Error{constructor(o,n){super(`${o}: ${n}`);this.pointer=o;this.reason=n}pointer;reason;code="NATIVE_MANAGED_CONCURRENCY_INVALID"};function No(e,t,o){if(e===void 0)return;let n=(p,g)=>{throw new nt(p,g)},i=(p,g,O)=>((!p||typeof p!="object"||Array.isArray(p)||Object.keys(p).some(y=>!O.includes(y)))&&n(g,"object contains unsupported properties"),p),s=(p,g,O,y)=>{(!Number.isSafeInteger(p)||p<g||p>O)&&n(y,`expected integer ${g}..${O}`)},c=(p,g)=>{(typeof p!="string"||!/^[a-z][a-z0-9_-]{0,63}$/.test(p))&&n(g,"invalid code")},r=(p,g,O)=>((!Array.isArray(p)||p.length>g)&&n(O,"array exceeds bound"),p),a=(p,g)=>{let O=t.find(y=>y.code===p);return O||n(g,"unknown resource"),O},d=(p,g,O)=>{let y=p.schema.fields.find(T=>T.code===g);return!y&&g!=="id"&&n(O,"unknown field"),y},u=(p,g,O=!1)=>{i(p,g,Object.keys(p||{})),Object.keys(p).length>8&&n(g,"at most eight parameters");for(let[y,T]of Object.entries(p))if(c(y,g),i(T,g,["type","values","minimum","maximum","minLength","maxLength"]),T.type==="uuid")Object.keys(T).length!==1&&n(g,"uuid has no options");else if(O&&T.type==="boolean")i(T,g,["type"]);else if(O&&T.type==="string"&&T.values===void 0)i(T,g,["type","minLength","maxLength"]),s(T.maxLength,1,256,g),T.minLength!==void 0&&s(T.minLength,0,T.maxLength,g);else if(T.type==="string"){i(T,g,["type","values"]);let h=r(T.values,100,g);(!h.length||h.some(D=>typeof D!="string"||D.length>128)||new Set(h).size!==h.length)&&n(g,"finite string values required")}else T.type==="integer"?(i(T,g,["type","minimum","maximum"]),s(T.minimum,0,1e6,g),s(T.maximum,T.minimum,T.minimum+1e3,g)):n(g,"unsupported parameter type")},l=(p,g,O,y=!1)=>{i(p,O,["from","key","value"]),!(p.from==="input"&&Object.keys(p).length===2&&Object.hasOwn(g,p.key))&&((p.from==="actor"||y&&p.from==="allocation")&&Object.keys(p).length===1||p.from==="literal"&&Object.keys(p).length===2&&Object.hasOwn(p,"value")&&(p.value===null||["string","boolean"].includes(typeof p.value)||typeof p.value=="number"&&Number.isFinite(p.value))&&JSON.stringify(p.value).length<=512||n(O,"invalid binding"))},f=(p,g,O)=>{l(p,g,O),!(p.from==="input"&&g[p.key].type==="uuid")&&(p.from==="literal"&&typeof p.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(p.value)||n(O,"record and allocation identifiers require a UUID binding"))},A=(p,g,O)=>{l(p,g,O),!(p.from==="input"&&g[p.key].type==="integer"&&g[p.key].minimum>=1)&&(p.from==="literal"&&Number.isSafeInteger(p.value)&&p.value>=1||n(O,"expectedRevision requires a positive integer binding"))},N="/data/concurrency";JSON.stringify(e).length>131072&&n(N,"declaration exceeds 128 KiB");let I=i(e,N,["version","admission","reads","quotas","commands"]);I.version!==1&&n(N,"unsupported version"),i(I.admission,N,["perSecond","burst","maxInFlight"]),s(I.admission.perSecond,1,1e3,N),s(I.admission.burst,1,1e3,N),s(I.admission.maxInFlight,1,1e3,N);let m=(p,g)=>{let O=new Set;for(let y of p)c(y?.code,g),O.has(y.code)&&n(g,"duplicate code"),O.add(y.code)};m(r(I.reads,32,N),N),m(r(I.quotas,16,N),N),m(r(I.commands,32,N),N);for(let p of I.reads){let g=`${N}/reads/${p.code}`;i(p,g,["code","resourceCode","parameters","select","where","limit","scope","freshSeconds","staleSeconds","maxKeys","sourcePerSecond","dependencies"]);let O=a(p.resourceCode,g);u(p.parameters,g),["subject","application"].includes(p.scope)||n(g,"invalid cache scope"),p.scope==="application"&&O.dataPolicyCode&&n(g,"shared cache cannot bypass a row policy");let y=r(p.select,32,g);y.length||n(g,"select required"),y.forEach(h=>d(O,h,g));let T=r(p.dependencies,64,g);T.forEach(h=>d(O,h,g));for(let h of r(p.where||[],8,g))i(h,g,["field","value"]),d(O,h.field,g),l(h.value,p.parameters,g),p.scope==="application"&&h.value.from==="actor"&&n(g,"actor requires subject cache"),T.includes(h.field)||n(g,"filter dependency missing");y.some(h=>!T.includes(h))&&n(g,"selected field dependency missing"),s(p.limit,1,100,g),s(p.freshSeconds,1,300,g),s(p.staleSeconds,0,300,g),s(p.maxKeys,1,1e4,g),s(p.sourcePerSecond,1,20,g)}for(let p of I.quotas){let g=`${N}/quotas/${p.code}`;i(p,g,["code","sourceResource","capacityField","allocationResource","allocationField","reservationSeconds"]);let O=a(p.sourceResource,g),y=a(p.allocationResource,g);d(O,p.capacityField,g)?.type!=="number.integer"&&n(g,"capacity must be an integer"),(d(y,p.allocationField,g)?.type!=="uuid"||d(y,p.allocationField,g)?.nullable!==!1)&&n(g,"allocation reference must be a uuid"),y.surface?.mutationOwner!=="queued-command"&&n(g,"allocation model must be command owned"),p.reservationSeconds!==void 0&&s(p.reservationSeconds,10,86400,g)}new Set(I.quotas.map(p=>p.allocationResource)).size!==I.quotas.length&&n(N,"an allocation model has exactly one pool owner");for(let p of I.commands){let g=`${N}/commands/${p.code}`;i(p,g,["code","mode","intake","execution","capability","parameters","resourceKey","admission","deadlineSeconds","guards","operations","quota"]),p.mode!==void 0&&!["permit","durable"].includes(p.mode)&&n(g,"unsupported mode");let O=p.mode==="durable";if(u(p.parameters,g,O),l(p.resourceKey,p.parameters,g),o.some(y=>y.code===p.capability)||n(g,"command capability must be declared"),i(p.admission,g,["perSecond","burst","maxInFlight","maxQueue","maxWaitSeconds","permitSeconds"]),s(p.admission.perSecond,1,I.admission.perSecond,g),s(p.admission.burst,1,I.admission.burst,g),s(p.admission.maxInFlight,1,I.admission.maxInFlight,g),s(p.admission.maxQueue,1,1e4,g),s(p.admission.maxWaitSeconds,1,3600,g),(!O||p.admission.permitSeconds!==void 0)&&s(p.admission.permitSeconds,5,60,g),s(p.deadlineSeconds,10,3600,g),O){(p.operations!==void 0||p.guards!==void 0||p.quota!==void 0)&&n(g,"backend-plan does not accept static operations, guards or quota"),i(p.intake,g,["perSecond","burst","maxInFlight"]);for(let h of["perSecond","burst","maxInFlight"])s(p.intake[h],1,1e3,g);let y=i(p.execution,g,["kind","handlerCode","timeoutMs","resources","directory"]);y.kind!=="backend-plan"&&n(g,"durable requires backend-plan"),c(y.handlerCode,g),s(y.timeoutMs,100,3e4,g);let T=r(y.resources,32,g);T.length||n(g,"execution resources required"),new Set(T.map(h=>h.resourceCode)).size!==T.length&&n(g,"duplicate execution resource");for(let h of T){i(h,g,["resourceCode","readFields","writeOperations","writeFields"]);let D=a(h.resourceCode,g);for(let k of["readFields","writeFields"]){let U=r(h[k],64,g);new Set(U).size!==U.length&&n(g,"duplicate field"),U.forEach(j=>{k==="readFields"&&oo.has(j)||d(D,j,g)})}let F=r(h.writeOperations,3,g);(new Set(F).size!==F.length||F.some(k=>!["create","update","increment"].includes(k)))&&n(g,"unsupported execution operation"),h.writeFields.some(k=>["id","revision","created_by","updated_by","created_at","updated_at"].includes(k))&&n(g,"record metadata is platform owned"),!F.length&&h.writeFields.length&&n(g,"write fields require an operation"),F.length&&!h.writeFields.length&&n(g,"write operations require fields"),I.quotas.some(k=>k.allocationResource===h.resourceCode)&&F.length&&n(g,"allocation references remain owned by their pool command")}if(y.directory!==void 0){i(y.directory,g,["mode","fields"]),y.directory.mode!=="current-initiator"&&n(g,"only current initiator allowed");let h=r(y.directory.fields,4,g);(!h.length||new Set(h).size!==h.length||h.some(D=>!["displayName","employeeNumber","primaryDepartment","departments"].includes(D)))&&n(g,"unsupported directory fields")}continue}(p.execution!==void 0||p.intake!==void 0)&&n(g,"execution and intake require durable mode");for(let y of r(p.guards||[],8,g)){i(y,g,["resourceCode","id","conditions"]);let T=a(y.resourceCode,g);f(y.id,p.parameters,g);for(let h of r(y.conditions,16,g)){i(h,g,["kind","field","operator","value"]);let D=d(T,h.field,g);["eq","neq","lt","lte","gt","gte"].includes(h.operator)||n(g,"unsupported guard"),h.kind==="database-now"?(D?.type!=="datetime"||!["lt","lte","gt","gte"].includes(h.operator)||h.value!==void 0)&&n(g,"database-now requires datetime and an ordering operator"):(h.kind!==void 0&&h.kind!=="value"&&n(g,"unsupported condition kind"),l(h.value,p.parameters,g))}}for(let y of r(p.operations,8,g)){i(y,g,["operation","resourceCode","id","expectedRevision","data"]);let T=a(y.resourceCode,g);T.surface?.mutationOwner!=="queued-command"&&n(g,"command mutations require command owned models");let h=I.quotas.find(D=>D.allocationResource===y.resourceCode);h&&(y.operation==="create"?p.quota?.action!=="allocate"||p.quota.pool!==h.code:Object.hasOwn(y.data||{},h.allocationField))&&n(g,"allocation references are owned by their pool command"),["create","update"].includes(y.operation)||n(g,"unsupported operation"),y.operation==="update"?(f(y.id,p.parameters,g),A(y.expectedRevision,p.parameters,g)):(y.id!==void 0||y.expectedRevision!==void 0)&&n(g,"create has no caller supplied id/revision"),i(y.data,g,Object.keys(y.data||{})),Object.keys(y.data).length>32&&n(g,"too many fields");for(let[D,F]of Object.entries(y.data))D==="id"&&n(g,"record identifiers are platform owned"),d(T,D,g),l(F,p.parameters,g,p.quota?.action==="allocate")}if(p.quota){let y=i(p.quota,g,["pool","action","units","mode","allocation"]),T=I.quotas.find(h=>h.code===y.pool);T||n(g,"unknown quota pool"),f(p.resourceKey,p.parameters,g),y.action==="allocate"?(i(y,g,["pool","action","units","mode"]),s(y.units,1,1e3,g),(!["committed","reserved"].includes(y.mode)||y.mode==="reserved"&&!T.reservationSeconds)&&n(g,"invalid allocation mode"),(p.operations.length!==1||p.operations[0].operation!=="create"||p.operations[0].resourceCode!==T.allocationResource||p.operations[0].data[T.allocationField]?.from!=="allocation")&&n(g,"allocation must atomically create its bound business record")):["confirm","release"].includes(y.action)?(i(y,g,["pool","action","allocation"]),f(y.allocation,p.parameters,g),p.operations.length&&n(g,"lifecycle owns allocation state; business reference remains immutable")):n(g,"invalid quota action")}else p.operations.length||n(g,"operations required")}let E=I.commands.filter(p=>p.mode==="durable").map(p=>p.execution.handlerCode);return new Set(E).size!==E.length&&n(N,"handler code must be unique"),JSON.parse(JSON.stringify(I))}var qe=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"},pn=["parentTransitions","childTransitions","fulfilledChildStatuses","lockedParentStatuses"],yo=["amountFieldCode","currencyFieldCode","relationFieldCode","parentFieldCode","rootFieldCode","statusFieldCode","parentRelationValue","childRelationValue"],Ot=e=>!!(e&&typeof e=="object"&&!Array.isArray(e)),Tt=e=>Array.isArray(e)?e.filter(Ot):[],Ne=(e,t)=>{throw new qe(e,t)},un=e=>typeof e=="string"&&/^[A-Za-z0-9._:-]{1,128}$/.test(e),fn=(e,t)=>e<t?-1:e>t?1:0;function mn(e,t="/decimalReservationLifecycle"){if(e===void 0)return;if(!Ot(e)||Object.keys(e).some(i=>!pn.includes(i))||pn.some(i=>!Object.prototype.hasOwnProperty.call(e,i)))return Ne(t,"\u5FC5\u987B\u5B8C\u6574\u58F0\u660E\u56DB\u9879\u89C4\u5219\uFF0C\u4E0D\u80FD\u5305\u542B\u672A\u77E5\u5C5E\u6027");let o=i=>{let s=e[i];if(!Array.isArray(s)||s.length>64)return Ne(`${t}/${i}`,"\u72B6\u6001\u8FB9\u6700\u591A 64 \u6761");let c=new Set;return s.map((r,a)=>{let d=`${t}/${i}/${a}`;if(!Ot(r)||Object.keys(r).some(l=>l!=="from"&&l!=="to")||!un(r.from)||!un(r.to)||r.from===r.to)return Ne(d,"\u72B6\u6001\u8FB9\u5FC5\u987B\u5305\u542B\u4E0D\u540C\u7684\u6709\u6548 from/to");let u=JSON.stringify([r.from,r.to]);return c.has(u)?Ne(d,"\u72B6\u6001\u8FB9\u4E0D\u80FD\u91CD\u590D"):(c.add(u),{from:r.from,to:r.to})}).sort((r,a)=>fn(r.from,a.from)||fn(r.to,a.to))},n=i=>{let s=e[i];return!Array.isArray(s)||s.length<1||s.length>16||s.some(c=>!un(c))||new Set(s).size!==s.length?Ne(`${t}/${i}`,"\u72B6\u6001\u96C6\u5408\u5FC5\u987B\u5305\u542B 1 \u5230 16 \u4E2A\u4E0D\u91CD\u590D\u7684\u6709\u6548\u72B6\u6001"):[...s].sort(fn)};return{parentTransitions:o("parentTransitions"),childTransitions:o("childTransitions"),fulfilledChildStatuses:n("fulfilledChildStatuses"),lockedParentStatuses:n("lockedParentStatuses")}}function bo(e,t,o="/config/data/resources"){Tt(e).forEach((n,i)=>{let s=`${o}/${i}/decimalReservationLifecycle`,c=mn(n.decimalReservationLifecycle,s);if(!c)return;let r=Tt(t).map(l=>l.platformAccess?.decimalReservation).filter(l=>Ot(l)&&l.resourceCode===n.code),a=r.find(l=>l.mode==="reserve");if(!a)return Ne(s,"\u9700\u8981\u540C\u8D44\u6E90\u5DF2\u58F0\u660E\u7684 reserve \u52A8\u4F5C\u6620\u5C04");if(yo.some(l=>typeof a[l]!="string")||r.some(l=>yo.some(f=>l[f]!==a[f])))return Ne(s,"\u540C\u8D44\u6E90\u989D\u5EA6\u52A8\u4F5C\u7684\u5B57\u6BB5\u6620\u5C04\u5FC5\u987B\u4E00\u81F4");let d=Tt(n.schema?.fields).find(l=>l.code===a.statusFieldCode);if(d?.type!=="option.single")return Ne(s,"\u989D\u5EA6\u72B6\u6001\u5B57\u6BB5\u5FC5\u987B\u4E3A option.single");let u=new Set(Tt(d.options).map(l=>l.value));for(let l of pn)if((l==="parentTransitions"||l==="childTransitions"?c[l].flatMap(A=>[A.from,A.to]):c[l]).some(A=>!u.has(A)))return Ne(`${s}/${l}`,"\u72B6\u6001\u5FC5\u987B\u6765\u81EA\u989D\u5EA6\u72B6\u6001\u5B57\u6BB5\u7684\u9009\u9879");if(r.some(l=>l.mode==="reserve"&&Array.isArray(l.eligibleParentStatuses)&&l.eligibleParentStatuses.some(f=>c.lockedParentStatuses.includes(String(f)))))return Ne(`${s}/lockedParentStatuses`,"\u9501\u5B9A\u7236\u72B6\u6001\u4E0D\u80FD\u5141\u8BB8\u65B0\u9884\u7559")})}import{createHash as ys}from"crypto";var _n=new Set(["option.single","user.single","department.single","resource-ref.single"]),bs=new Set(["option.multiple","cascade.single","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","address","location","json"]),Oo=new Set(["option.multiple","cascade.single","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","file","image"]),Ts=new Set(["option.single","user.single","department.single","resource-ref.single","signature","address","location"]),Os=new Set([..._n,...Oo,"signature","address","location","json"]);function Ga(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=>hs(n,o.has(n.code))).sort((n,i)=>n.code.localeCompare(i.code))}function hs(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:Ss(e),index:Cs(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 qa(e,t){if(t.type==="subtable")return null;let o=re(t.code),n=ho(e,t),i=[n?` DEFAULT ${n}`:"",ws(o,t),Rs(o,t)].join("");return`${o} ${t.storage}${i}`}function Ja(e,t){return ho(e,t)}function Rs(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 za(e){return e.type==="serial-number"||It(e.type)&&e.type!=="subtable"}function Ya(e,t){return t.filter(o=>o.type==="serial-number").map(o=>{let n=Rt(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 Ha(e,t){let o=ht(e);return t.filter(n=>n.type==="serial-number").map(n=>`ALTER SEQUENCE ${Rt(e,n.code)} OWNED BY ${o}.${re(n.code)}`)}function Xa(e,t){return t.filter(o=>o.type==="serial-number").map(o=>`GRANT USAGE, SELECT ON SEQUENCE ${Rt(e,o.code)} TO "openxiangda_data_api"`)}function Qa(e,t){let o=ht(e),n=[];for(let i of t){if(i.type==="subtable")continue;let s=re(i.code),c=re(Se("idx",e,i.code,i.index));switch(i.index){case"btree":n.push(`CREATE INDEX IF NOT EXISTS ${c} ON ${o} (${s})`);break;case"btree-snapshot-expressions":{let r=re(Se("idx",e,i.code,"snapshot-value")),a=re(Se("idx",e,i.code,"snapshot-label"));n.push(`CREATE INDEX IF NOT EXISTS ${r} ON ${o} ((${s} ->> 'value'))`,`CREATE INDEX IF NOT EXISTS ${a} ON ${o} ((${s} ->> 'label'))`);break}case"gin-jsonb-path":n.push(`CREATE INDEX IF NOT EXISTS ${c} ON ${o} USING GIN (${s} jsonb_path_ops)`);break;case"gist-range":n.push(`CREATE INDEX IF NOT EXISTS ${c} ON ${o} USING GIST (${s})`);break;case"gin-trigram":{let r=_n.has(i.type)?`((${s} ->> 'label')) gin_trgm_ops`:`${s} gin_trgm_ops`;n.push(`CREATE INDEX IF NOT EXISTS ${c} ON ${o} USING GIN (${r})`);break}case"none":break}if(i.type==="serial-number"){let r=re(Se("uidx",e,i.code,"serial"));n.push(`CREATE UNIQUE INDEX IF NOT EXISTS ${r} ON ${o} (${s})`)}}return n}function Za(e,t,o,n){let i=ht(e),s=ht(t),c=re(Se("uidx",e,"environment_id","subtable-parent")),r=re(Se("idx",t,o,n,"subtable-child")),a=re(Se("fk",t,o,e)),d=re(o),u=re(n);return[`CREATE UNIQUE INDEX IF NOT EXISTS ${c} ON ${i} ("tenant_id", "app_code", "environment_key", "id")`,`CREATE INDEX IF NOT EXISTS ${r} ON ${s} ("tenant_id", "app_code", "environment_key", ${d}, ${u}, "id")`,`DO $native_subtable$ BEGIN
1
+ import{createHash as As}from"node:crypto";function Es(e){if(!e||typeof e!="object")return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function an(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)=>an(n,`${t}[${i}]`)).join(",")}]`;if(Es(e))return`{${Object.keys(e).filter(i=>e[i]!==void 0).sort((i,s)=>i===s?0:i<s?-1:1).map(i=>`${JSON.stringify(i)}:${an(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 ne(e){return an(e,"$")}function Q(e){return As("sha256").update(ne(e)).digest("hex")}var ac=200,Is=["text.short","uuid","option.single"],cn=/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/,mo=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,_o=new Set(["__proto__","prototype","constructor"]),dn=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&[Object.prototype,null].includes(Object.getPrototypeOf(e)),po=(e,t)=>Object.keys(e).every(o=>t.includes(o)),qe=(e,t)=>typeof e=="string"&&e.length>0&&e.trim()===e&&e.length<=t,Le=class extends Error{constructor(o,n){super(`${o}: ${n}`);this.code=o;this.pointer=n}code;pointer};function oe(e,t){throw new Le(e,t)}function ht(e,t,o){if(e===void 0)return;["user.single","user.multiple"].includes(t)||oe("DATA_USER_CANDIDATES_FIELD_TYPE_INVALID",o),(!dn(e)||!po(e,["kind","roleCode","scope","pageSize"])||e.kind!=="app-role"||!qe(e.roleCode,128)||!cn.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 i=e.scope;(!dn(i)||!po(i,["dimensionCode","operation","field","value"])||!qe(i.dimensionCode,128)||!cn.test(String(i.dimensionCode))||!qe(i.operation,64)||!cn.test(String(i.operation))||Object.hasOwn(i,"field")===Object.hasOwn(i,"value"))&&oe("DATA_USER_CANDIDATES_SCOPE_INVALID",`${o}/scope`),Object.hasOwn(i,"field")?((!qe(i.field,63)||!mo.test(String(i.field))||_o.has(String(i.field)))&&oe("DATA_USER_CANDIDATES_SCOPE_FIELD_INVALID",`${o}/scope/field`),n={dimensionCode:String(i.dimensionCode),operation:String(i.operation),field:String(i.field)}):(qe(i.value,255)||oe("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 go(e,t,o,n){for(let[i,s]of e.entries()){let a=`${n}/${i}/userCandidates`,r=ht(s.userCandidates,s.type,a);if(r&&(t.has(r.roleCode)||oe("DATA_USER_CANDIDATES_ROLE_UNDECLARED",`${a}/roleCode`),r.scope&&!o.has(r.scope.dimensionCode)&&oe("DATA_USER_CANDIDATES_DIMENSION_UNDECLARED",`${a}/scope/dimensionCode`),r.scope?.field)){let c=e.find(l=>l.code===r.scope.field);(!c||!Is.some(l=>l===c.type))&&oe("DATA_USER_CANDIDATES_SCOPE_FIELD_INVALID",`${a}/scope/field`)}}}function ys(e,t,o,n){let i=e.subject.factProjection,s=typeof t.inputPath=="string"&&Object.entries(i).some(([l,p])=>(t.inputPath===l||t.inputPath.startsWith(`${l}.`))&&o.get(p)?.userCandidates!==void 0);if(t.candidateField===void 0&&!s)return;(t.provider!=="form_field_users"||!t.candidateField||!mo.test(t.candidateField)||_o.has(t.candidateField)||!t.inputPath||i[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),r=a&&ht(a.userCandidates,a.type,`${n}/candidateField`);r||oe("WORKFLOW_USER_CANDIDATES_FIELD_UNDECLARED",`${n}/candidateField`);let c;if(r.scope?.field){let l=Object.entries(i).filter(([,p])=>p===r.scope.field).map(([p])=>p);l.length!==1&&oe("WORKFLOW_USER_CANDIDATES_SCOPE_PROJECTION_REQUIRED",n),c=l[0]}return{fieldCode:a.code,inputPath:t.inputPath,source:r,...c?{scopeInputPath:c}:{}}}function Ao(e,t,o,n,i=new Map){for(let[s,a]of Object.entries(t.bindings))ys(e,a,o,`${n}/${s}`);for(let[s,a]of Object.entries(e.taskPages||{})){let r=new Set(a.fields.filter(c=>c.readonly!==!0).map(c=>c.code));for(let c of a.fields){let l=o.get(c.code)?.userCandidates?.scope;if(r.has(c.code)&&l?.field&&r.has(l.field)&&oe("WORKFLOW_USER_CANDIDATES_SCOPE_WRITE_FORBIDDEN",`${n}/taskPages/${s}/${c.code}`),!r.has(c.code)||!c.subtable)continue;let p=o.get(c.code)?.subtable?.resourceCode,d=p?i.get(p):void 0;c.subtable.fields.some(u=>u.readonly!==!0&&d?.get(u.code)?.userCandidates)&&oe("WORKFLOW_USER_CANDIDATES_OWNED_FIELD_UNSUPPORTED",`${n}/taskPages/${s}/${c.code}`)}}}function cc(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 qe(n,255)||oe("DATA_USER_CANDIDATES_SCOPE_VALUE_REQUIRED",e.scope.field||"scope"),String(n)}var Rt=100,Ct=400,lc=1e3,uc=2097152,fc=2097152;function pc(e){try{return new TextEncoder().encode(JSON.stringify(e)).byteLength}catch{return 1/0}}var bo=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,fn=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,bs=["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"],Ns=new Set(bs),No=new Set(["option.multiple","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","file","image","subtable"]),Eo=new Set(["option.single","option.multiple","cascade.single","cascade.multiple"]),Io=new Set(["resource-ref.single","resource-ref.multiple"]),pn=[{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}],Oo=new Map(pn.map(e=>[e.code,e])),ye=class extends Error{constructor(o,n){super(o);this.code=o;this.pointer=n;this.name="NativeDataFieldContractV2Error"}code;pointer};function Dt(e){return No.has(e)}function $t(e,t={}){return e.type!=="serial-number"&&t.system!==!0&&e.nullable===!1&&(!Dt(e.type)||t.requiredHint===!0)}function mn(e,t,o=500){Array.isArray(e)||D("NATIVE_ARRAY_REQUIRED",t),e.length===0&&D("NATIVE_DATA_FIELDS_REQUIRED",t),e.length>o&&D("NATIVE_ARRAY_LIMIT_EXCEEDED",t);let n=new Set;return e.map((i,s)=>{let a=`${t}/${s}`,r=pe(i,a);ge(r,["code","type","nullable","indexed","options","source","userCandidates","maxLength","precision","scale","exactDecimal","min","max","rangeBoundary","timePrecision","file","serial","subtable"],a);let c=Ae(r.code,`${a}/code`,63);bo.test(c)||D("NATIVE_FIELD_CODE_INVALID",`${a}/code`),n.has(c)&&D("NATIVE_DATA_FIELD_DUPLICATE",`${a}/code`),n.add(c);let l=Ae(r.type,`${a}/type`,32);Ns.has(l)||D("NATIVE_DATA_FIELD_TYPE_INVALID",`${a}/type`);let p=l,d=un(r.nullable,`${a}/nullable`),u=un(r.indexed,`${a}/indexed`);d===!0&&No.has(p)&&D("NATIVE_DATA_MULTI_FIELD_NULLABLE_INVALID",`${a}/nullable`);let g=hs(r.options,p,a),I=Rs(r.source,p,a),E=ht(r.userCandidates,p,`${a}/userCandidates`),N=Ss(r,p,a),y=un(r.exactDecimal,`${a}/exactDecimal`);y!==void 0&&p!=="number.decimal"&&D("NATIVE_DATA_FIELD_EXACT_DECIMAL_TYPE_INVALID",`${a}/exactDecimal`);let _=Os(r.rangeBoundary,p,a),A=ws(r.file,p,a),T=Ds(r.serial,p,a),f=$s(r.subtable,p,a);return{code:c,type:p,...d===void 0?{}:{nullable:d},...u===void 0?{}:{indexed:u},...g?{options:g}:{},...I?{source:I}:{},...E?{userCandidates:E}:{},...N,...y===void 0?{}:{exactDecimal:y},..._?{rangeBoundary:_}:{},...A?{file:A}:{},...T?{serial:T}:{},...f?{subtable:f}:{}}})}function Os(e,t,o){let n=`${o}/rangeBoundary`;if(!(t==="date-range"||t==="datetime-range")){e!==void 0&&D("NATIVE_DATA_FIELD_RANGE_BOUNDARY_TYPE_INVALID",n);return}return e!=="closed"&&e!=="half-open"&&D("NATIVE_DATA_FIELD_RANGE_BOUNDARY_REQUIRED",n),e}function To(e,t){Array.isArray(e)||D("NATIVE_ARRAY_REQUIRED",t);let o=new Map;e.forEach((n,i)=>{let s=`${t}/${i}`,a=pe(n,s),r=Ae(a.code,`${s}/code`,64);(!fn.test(r)||o.has(r))&&D("NATIVE_RESOURCE_CODE_INVALID",`${s}/code`);let c=pe(a.schema,`${s}/schema`);o.set(r,{pointer:s,fields:mn(c.fields,`${s}/schema/fields`)})});for(let[n,i]of o){let s=new Map(i.fields.map(r=>[r.code,r]));i.fields.filter(r=>r.type==="subtable").reduce((r,c)=>r+(c.subtable?.maxRows??20),0)>400&&D("NATIVE_DATA_FIELD_SUBTABLE_AGGREGATE_MAX_ROWS_EXCEEDED",`${i.pointer}/schema/fields`),i.fields.forEach((r,c)=>{let l=`${i.pointer}/schema/fields/${c}`;if(r.source&&Ts(r.source,s,o,`${l}/source`),r.subtable){let p=o.get(r.subtable.resourceCode);(!p||r.subtable.resourceCode===n)&&D("NATIVE_DATA_FIELD_SUBTABLE_TARGET_MISSING",`${l}/subtable/resourceCode`);let d=p.fields.find(g=>g.code===r.subtable?.foreignKey);(!d||d.type!=="uuid"||d.nullable!==!1)&&D("NATIVE_DATA_FIELD_SUBTABLE_FOREIGN_KEY_INVALID",`${l}/subtable/foreignKey`);let u=p.fields.find(g=>g.code===r.subtable?.orderField);(!u||u.type!=="number.integer"||u.nullable!==!1)&&D("NATIVE_DATA_FIELD_SUBTABLE_ORDER_FIELD_INVALID",`${l}/subtable/orderField`)}})}}function ho(e,t,o){if(e===void 0)return[];(!Array.isArray(e)||e.length>20)&&D("NATIVE_DATA_RESOURCE_INVARIANTS_INVALID",o);let n=new Map(t.map(s=>[s.code,s])),i=new Set;return e.map((s,a)=>{let r=`${o}/${a}`,c=pe(s,r);ge(c,["code","message","expression"],r);let l=Ae(c.code,`${r}/code`,128);(!/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/.test(l)||i.has(l))&&D("NATIVE_DATA_RESOURCE_INVARIANT_CODE_INVALID",`${r}/code`),i.add(l);let p=wt(c.message,`${r}/message`,500);p!==void 0&&p.length===0&&D("NATIVE_DATA_RESOURCE_INVARIANT_MESSAGE_INVALID",`${r}/message`);let d=pe(c.expression,`${r}/expression`);if(d.kind==="nonBlankTextWhenOption"){ge(d,["kind","optionField","optionValue","textField"],`${r}/expression`);let _=Ie(d.optionField,`${r}/expression/optionField`),A=Ie(d.textField,`${r}/expression/textField`),T=Ae(d.optionValue,`${r}/expression/optionValue`,128),f=n.get(_),b=n.get(A);return(!f||!b)&&D("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_UNKNOWN",`${r}/expression`),(f.type!=="option.single"||!["text.short","text.long"].includes(b.type)||!f.options?.some(h=>h.value===T))&&D("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_TYPES_INVALID",`${r}/expression`),{code:l,...p===void 0?{}:{message:p},expression:{kind:"nonBlankTextWhenOption",optionField:_,optionValue:T,textField:A}}}ge(d,["leftField","operator","rightField"],`${r}/expression`);let u=Ie(d.leftField,`${r}/expression/leftField`),g=Ie(d.rightField,`${r}/expression/rightField`),I=n.get(u),E=n.get(g);(!I||!E)&&D("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_UNKNOWN",`${r}/expression`),I.type===E.type||["number.integer","number.decimal"].includes(I.type)&&["number.integer","number.decimal"].includes(E.type)||D("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_TYPES_INVALID",`${r}/expression`);let y=String(d.operator);return["eq","neq","gt","gte","lt","lte"].includes(y)||D("NATIVE_DATA_RESOURCE_INVARIANT_OPERATOR_INVALID",`${r}/expression/operator`),!["eq","neq"].includes(y)&&!["number.integer","number.decimal","date","time","datetime","text.short","text.long","text.rich","serial-number","uuid"].includes(I.type)&&D("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_TYPES_INVALID",`${r}/expression`),{code:l,...p===void 0?{}:{message:p},expression:{leftField:u,operator:y,rightField:g}}})}function Ts(e,t,o,n){let i=o.get(e.resourceCode);i||D("NATIVE_DATA_FIELD_SOURCE_TARGET_MISSING",`${n}/resourceCode`);let s=new Map(i.fields.map(r=>[r.code,r])),a=s.get(e.labelField);(!a||!["text.short","text.long"].includes(a.type))&&D("NATIVE_DATA_FIELD_SOURCE_LABEL_INVALID",`${n}/labelField`);for(let r of["searchFields","descriptionFields","snapshotFields"])for(let c of e[r]||[])s.has(c)||D("NATIVE_DATA_FIELD_SOURCE_FIELD_MISSING",`${n}/${r}`);for(let[r,c]of(e.filters||[]).entries())s.has(c.field)||D("NATIVE_DATA_FIELD_SOURCE_FILTER_FIELD_MISSING",`${n}/filters/${r}/field`),"binding"in c&&!t.has(c.binding.field)&&D("NATIVE_DATA_FIELD_SOURCE_BINDING_FIELD_MISSING",`${n}/filters/${r}/binding/field`)}function hs(e,t,o){let n=`${o}/options`;if(e===void 0){Eo.has(t)&&D("NATIVE_DATA_FIELD_OPTIONS_REQUIRED",n);return}(!Eo.has(t)||!Array.isArray(e))&&D("NATIVE_DATA_FIELD_OPTIONS_TYPE_INVALID",n),(e.length<1||e.length>100)&&D("NATIVE_DATA_FIELD_OPTIONS_INVALID",n);let i=0,s=(a,r,c)=>{c>5&&D("NATIVE_DATA_FIELD_OPTIONS_DEPTH_EXCEEDED",r);let l=new Set;return a.map((p,d)=>{i+=1,i>1e3&&D("NATIVE_DATA_FIELD_OPTIONS_COUNT_EXCEEDED",n);let u=`${r}/${d}`,g=pe(p,u);ge(g,["label","value","description","color","children"],u);let I=Ae(g.label,`${u}/label`,500),E=Ae(g.value,`${u}/value`,500);l.has(E)&&D("NATIVE_DATA_FIELD_OPTION_VALUE_DUPLICATE",`${u}/value`),l.add(E);let N=wt(g.description,`${u}/description`,2e3),y=wt(g.color,`${u}/color`,64),_;return g.children!==void 0&&((!t.startsWith("cascade.")||!Array.isArray(g.children))&&D("NATIVE_DATA_FIELD_OPTION_CHILDREN_INVALID",`${u}/children`),(g.children.length<1||g.children.length>100)&&D("NATIVE_DATA_FIELD_OPTION_CHILDREN_INVALID",`${u}/children`),_=s(g.children,`${u}/children`,c+1)),{label:I,value:E,...N===void 0?{}:{description:N},...y===void 0?{}:{color:y},..._?{children:_}:{}}})};return s(e,n,1)}function Rs(e,t,o){let n=`${o}/source`;if(e===void 0){Io.has(t)&&D("NATIVE_DATA_FIELD_SOURCE_REQUIRED",n);return}Io.has(t)||D("NATIVE_DATA_FIELD_SOURCE_TYPE_INVALID",n);let i=pe(e,n);ge(i,["kind","resourceCode","labelField","searchFields","descriptionFields","snapshotFields","filters","pageSize","loadMode"],n),i.kind!=="resource"&&D("NATIVE_DATA_FIELD_SOURCE_KIND_INVALID",`${n}/kind`);let s=Ae(i.resourceCode,`${n}/resourceCode`,64);fn.test(s)||D("NATIVE_RESOURCE_CODE_INVALID",`${n}/resourceCode`);let a=Ie(i.labelField,`${n}/labelField`),r=ln(i.searchFields,`${n}/searchFields`,10),c=ln(i.descriptionFields,`${n}/descriptionFields`,10),l=ln(i.snapshotFields,`${n}/snapshotFields`,50),p=Je(i.pageSize,`${n}/pageSize`,1,100),d;i.loadMode!==void 0&&(["search","all"].includes(String(i.loadMode))||D("NATIVE_DATA_FIELD_SOURCE_LOAD_MODE_INVALID",`${n}/loadMode`),d=i.loadMode);let u=Cs(i.filters,`${n}/filters`);return{kind:"resource",resourceCode:s,labelField:a,...r?{searchFields:r}:{},...c?{descriptionFields:c}:{},...l?{snapshotFields:l}:{},...u?{filters:u}:{},...p===void 0?{}:{pageSize:p},...d?{loadMode:d}:{}}}function Cs(e,t){if(e!==void 0)return(!Array.isArray(e)||e.length>20)&&D("NATIVE_DATA_FIELD_SOURCE_FILTERS_INVALID",t),e.map((o,n)=>{let i=`${t}/${n}`,s=pe(o,i),a=Object.prototype.hasOwnProperty.call(s,"value"),r=Object.prototype.hasOwnProperty.call(s,"binding");ge(s,a?["field","operator","value"]:["field","operator","binding"],i),a===r&&D("NATIVE_DATA_FIELD_SOURCE_FILTER_VALUE_INVALID",i);let c=Ie(s.field,`${i}/field`);["eq","in"].includes(String(s.operator))||D("NATIVE_DATA_FIELD_SOURCE_FILTER_OPERATOR_INVALID",`${i}/operator`);let l=s.operator;if(a)return{field:c,operator:l,value:s.value};let p=pe(s.binding,`${i}/binding`);return ge(p,["kind","field"],`${i}/binding`),p.kind!=="field"&&D("NATIVE_DATA_FIELD_SOURCE_BINDING_KIND_INVALID",`${i}/binding/kind`),{field:c,operator:l,binding:{kind:"field",field:Ie(p.field,`${i}/binding/field`)}}})}function Ss(e,t,o){let n={};if(e.maxLength!==void 0&&(["text.short","text.long","text.rich"].includes(t)||D("NATIVE_DATA_FIELD_MAX_LENGTH_TYPE_INVALID",`${o}/maxLength`),n.maxLength=St(e.maxLength,`${o}/maxLength`,1,1e6)),(e.precision!==void 0||e.scale!==void 0)&&((t!=="number.decimal"||e.precision===void 0)&&D("NATIVE_DATA_FIELD_DECIMAL_CONFIG_INVALID",o),n.precision=St(e.precision,`${o}/precision`,1,1e3),n.scale=e.scale===void 0?0:St(e.scale,`${o}/scale`,0,n.precision)),e.min!==void 0||e.max!==void 0){["number.integer","number.decimal"].includes(t)||D("NATIVE_DATA_FIELD_NUMERIC_BOUNDS_TYPE_INVALID",o);let i=yo(e.min,`${o}/min`),s=yo(e.max,`${o}/max`);t==="number.integer"&&[i,s].some(a=>a!==void 0&&!Number.isSafeInteger(a))&&D("NATIVE_DATA_FIELD_NUMERIC_BOUNDS_INVALID",o),i!==void 0&&s!==void 0&&i>s&&D("NATIVE_DATA_FIELD_NUMERIC_BOUNDS_INVALID",o),i!==void 0&&(n.min=i),s!==void 0&&(n.max=s)}return e.timePrecision!==void 0&&((t!=="time"||!["minute","second"].includes(e.timePrecision))&&D("NATIVE_DATA_FIELD_TIME_PRECISION_INVALID",`${o}/timePrecision`),n.timePrecision=e.timePrecision),n}function ws(e,t,o){if(e===void 0)return;let n=`${o}/file`;["file","image","signature"].includes(t)||D("NATIVE_DATA_FIELD_FILE_TYPE_INVALID",n);let i=pe(e,n);ge(i,["maxCount","maxSizeMb","accept"],n);let s=Je(i.maxCount,`${n}/maxCount`,1,100);t==="signature"&&s!==void 0&&s!==1&&D("NATIVE_DATA_FIELD_SIGNATURE_COUNT_INVALID",`${n}/maxCount`);let a=Je(i.maxSizeMb,`${n}/maxSizeMb`,1,1024),r;return i.accept!==void 0&&((!Array.isArray(i.accept)||i.accept.length>50)&&D("NATIVE_DATA_FIELD_FILE_ACCEPT_INVALID",`${n}/accept`),r=i.accept.map((c,l)=>Ae(c,`${n}/accept/${l}`,255)),new Set(r).size!==r.length&&D("NATIVE_DATA_FIELD_FILE_ACCEPT_INVALID",`${n}/accept`)),{...s===void 0?{}:{maxCount:s},...a===void 0?{}:{maxSizeMb:a},...r===void 0?{}:{accept:r}}}function Ds(e,t,o){let n=`${o}/serial`;if(e===void 0){t==="serial-number"&&D("NATIVE_DATA_FIELD_SERIAL_REQUIRED",n);return}t!=="serial-number"&&D("NATIVE_DATA_FIELD_SERIAL_TYPE_INVALID",n);let i=pe(e,n);ge(i,["prefix","digits","start"],n);let s=wt(i.prefix,`${n}/prefix`,64),a=Je(i.digits,`${n}/digits`,1,32),r=Je(i.start,`${n}/start`,0,Number.MAX_SAFE_INTEGER);return{...s===void 0?{}:{prefix:s},...a===void 0?{}:{digits:a},...r===void 0?{}:{start:r}}}function $s(e,t,o){let n=`${o}/subtable`;if(e===void 0){t==="subtable"&&D("NATIVE_DATA_FIELD_SUBTABLE_REQUIRED",n);return}t!=="subtable"&&D("NATIVE_DATA_FIELD_SUBTABLE_TYPE_INVALID",n);let i=pe(e,n);ge(i,["resourceCode","foreignKey","orderField","maxRows"],n);let s=Ae(i.resourceCode,`${n}/resourceCode`,64);fn.test(s)||D("NATIVE_RESOURCE_CODE_INVALID",`${n}/resourceCode`);let a=Ie(i.foreignKey,`${n}/foreignKey`),r=Ie(i.orderField,`${n}/orderField`);r===a&&D("NATIVE_DATA_FIELD_SUBTABLE_ORDER_FIELD_INVALID",`${n}/orderField`);let c=Je(i.maxRows,`${n}/maxRows`,1,100);return{resourceCode:s,foreignKey:a,orderField:r,...c===void 0?{}:{maxRows:c}}}function ln(e,t,o){if(e===void 0)return;(!Array.isArray(e)||e.length>o)&&D("NATIVE_DATA_FIELD_SOURCE_FIELDS_INVALID",t);let n=e.map((i,s)=>Ie(i,`${t}/${s}`));return new Set(n).size!==n.length&&D("NATIVE_DATA_FIELD_SOURCE_FIELDS_INVALID",t),n}function Ie(e,t){let o=Ae(e,t,63);return bo.test(o)||D("NATIVE_FIELD_CODE_INVALID",t),o}function pe(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&D("NATIVE_OBJECT_REQUIRED",t),e}function ge(e,t,o){let n=new Set(t);for(let i of Object.keys(e))n.has(i)||D("NATIVE_PROPERTY_UNKNOWN",`${o}/${i}`)}function Ae(e,t,o){return(typeof e!="string"||e.length===0||e.length>o)&&D("NATIVE_STRING_INVALID",t),e}function wt(e,t,o){if(e!==void 0)return(typeof e!="string"||e.length>o)&&D("NATIVE_STRING_INVALID",t),e}function un(e,t){if(e!==void 0)return typeof e!="boolean"&&D("NATIVE_BOOLEAN_REQUIRED",t),e}function Je(e,t,o,n){if(e!==void 0)return St(e,t,o,n)}function yo(e,t){if(e!==void 0)return(typeof e!="number"||!Number.isFinite(e))&&D("NATIVE_NUMBER_REQUIRED",t),e}function St(e,t,o,n){return(!Number.isSafeInteger(e)||Number(e)<o||Number(e)>n)&&D("NATIVE_INTEGER_OUT_OF_RANGE",t),Number(e)}function D(e,t){throw new ye(e,t)}var Ro=["created_by","updated_by","created_at","updated_at"];function ot(e){return Ro.includes(e)}function Co(e){return Ro.some(t=>Object.prototype.hasOwnProperty.call(e.fieldPolicies||{},t))}var ks=pn.map(e=>e.code);function So(e){return ks.includes(e)}var Vs=["eq","neq","gt","gte","lt","lte","contains","startsWith","endsWith","in","between","has","hasAny","hasAll","overlaps","containedBy","jsonContains","isEmpty","isNotEmpty"],Ps=new Set(Vs);function yc(e){return Ps.has(String(e))}var _n=["eq","neq","contains","startsWith","endsWith","in","isEmpty","isNotEmpty"],it=["eq","neq","gt","gte","lt","lte","between","in","isEmpty"],Fs=["eq","neq","in","isEmpty"],kt=["eq","neq","in","isEmpty","isNotEmpty"],Ge=["has","hasAny","hasAll","isEmpty","isNotEmpty"],wo=["overlaps","contains","containedBy","isEmpty"],gn=["jsonContains","isEmpty","isNotEmpty"],An=["isEmpty","isNotEmpty"],vs={"text.short":_n,"text.long":_n,"text.rich":_n,"number.integer":it,"number.decimal":it,boolean:Fs,date:it,time:it,datetime:it,"date-range":wo,"datetime-range":wo,"option.single":kt,"option.multiple":Ge,"cascade.single":Ge,"cascade.multiple":Ge,"user.single":kt,"user.multiple":Ge,"department.single":kt,"department.multiple":Ge,"resource-ref.single":kt,"resource-ref.multiple":Ge,file:An,image:An,signature:An,address:gn,location:gn,uuid:["eq","neq","in","isEmpty"],json:gn,"serial-number":["eq","neq","in","contains","startsWith"],subtable:[]},Ls=new Set(["text.short","text.long","text.rich","option.single","user.single","department.single","resource-ref.single","serial-number"]),xs=new Set(["option.multiple","cascade.single","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","file","image","signature","address","location","json","subtable"]);function $o(e){return vs[e]}function bc(e,t){return $o(e).includes(t)}function En(e){return Ls.has(e)}function st(e){return!xs.has(e)}function ko(e){return $o(e).length>0}var Do=new Set(["number.integer","number.decimal"]),Vo=new Set(["text.short","text.long","number.integer","number.decimal","date","time","datetime","serial-number"]),js=new Set([...Vo,"boolean","uuid"]),Ws=new Set(["option.single","user.single","department.single","resource-ref.single"]);function Nc(e,t){return t==="sum"||t==="avg"?Do.has(e)?{valueExpression:"column",numericResult:!0}:null:t==="min"||t==="max"?Vo.has(e)?{valueExpression:"column",numericResult:Do.has(e)}:null:Ws.has(e)?{valueExpression:"snapshot-value",numericResult:!0}:js.has(e)?{valueExpression:"column",numericResult:!0}:null}var yn=["version","maxBytes","fields"];function Fo(e,t){if(e===void 0)return;let o=In(e,t);Po(o,yn,t);let n=Vt(o.version,`${t}/version`,1,1e6),i=Vt(o.maxBytes,`${t}/maxBytes`,2,196608);(!n||!i)&&ce("NATIVE_DATA_DRAFT_STATE_SCHEMA_INVALID",t);let s=In(o.fields,`${t}/fields`),a=Object.entries(s);(!a.length||a.length>50)&&ce("NATIVE_DATA_DRAFT_STATE_FIELDS_INVALID",`${t}/fields`);for(let[r,c]of a){let l=`${t}/fields/${r}`;/^[A-Za-z][A-Za-z0-9_]{0,62}$/.test(r)||ce("NATIVE_DATA_DRAFT_STATE_FIELD_CODE_INVALID",l);let p=In(c,l),d=vo(p.type,`${l}/type`,32),u=d==="string"?["type","required","maxLength","enum"]:d==="json.object"?["type","required","maxBytes"]:["type","required"];if(["string","number","integer","boolean","json.object"].includes(d)||ce("NATIVE_DATA_DRAFT_STATE_FIELD_TYPE_INVALID",`${l}/type`),Po(p,u,l),Ms(p.required,`${l}/required`),d==="string"){let g=Vt(p.maxLength,`${l}/maxLength`,1,196608);g||ce("NATIVE_DATA_DRAFT_STATE_FIELD_INVALID",l),p.enum!==void 0&&Us(p.enum,`${l}/enum`,100,!1).some(E=>E.length>g)&&ce("NATIVE_DATA_DRAFT_STATE_FIELD_INVALID",`${l}/enum`)}else if(d==="json.object"){let g=Vt(p.maxBytes,`${l}/maxBytes`,2,65536);(!g||g>i)&&ce("NATIVE_DATA_DRAFT_STATE_FIELD_INVALID",l)}}}function Us(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((s,a)=>vo(s,`${t}/${a}`,255));return new Set(i).size!==i.length&&ce("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t),i}function In(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&ce("NATIVE_OBJECT_REQUIRED",t),e}function Po(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 vo(e,t,o){return(typeof e!="string"||e.length===0||e.length>o)&&ce("NATIVE_STRING_INVALID",t),e}function Ms(e,t){e!==void 0&&typeof e!="boolean"&&ce("NATIVE_BOOLEAN_REQUIRED",t)}function Vt(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 ye(e,t)}var Bs=500,De={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:yn,mobile:["enabled"]},Ks={"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 On(e,t,o){if(e===void 0)return;let n=re(e,o);be(n,De.surface,o);let i=n.mutationOwner===void 0?"native":Ce(n.mutationOwner,`${o}/mutationOwner`,16);["native","action","readonly","workflow","queued-command"].includes(i)||j("NATIVE_DATA_SURFACE_MUTATION_OWNER_INVALID",`${o}/mutationOwner`);let s=n.generated===void 0?{}:re(n.generated,`${o}/generated`);be(s,De.generated,`${o}/generated`);for(let c of De.generated)Nn(s[c],`${o}/generated/${c}`);if(i!=="native")for(let c of["create","update","delete"])s[c]===!0&&j("NATIVE_DATA_SURFACE_MUTATION_OWNER_CONFLICT",`${o}/generated/${c}`);let a=new Map(t.map(c=>[c.code,c])),r=re(n.fields,`${o}/fields`);for(let c of Object.keys(r))a.has(c)||j("NATIVE_DATA_SURFACE_FIELD_MISSING",`${o}/fields/${c}`);for(let c of t)Object.prototype.hasOwnProperty.call(r,c.code)||j("NATIVE_DATA_SURFACE_FIELD_REQUIRED",`${o}/fields/${c.code}`),Js(r[c.code],c,`${o}/fields/${c.code}`);for(let c of["create","update"]){let l=s[c]??i==="native",p=t.some(d=>{let u=re(r[d.code],`${o}/fields/${d.code}`);return xo(d,u,c)});l&&!p&&j("NATIVE_DATA_SURFACE_WRITABLE_FIELDS_REQUIRED",`${o}/generated/${c}`)}if(Gs(n.list,a,`${o}/list`),Lo(n.form,a,`${o}/form`,"form"),Lo(n.detail,a,`${o}/detail`,"detail"),n.mobile!==void 0){let c=re(n.mobile,`${o}/mobile`);be(c,De.mobile,`${o}/mobile`),Nn(c.enabled,`${o}/mobile/enabled`)}qs(n,t,o)}function Tn(e,t){let o=e.views?.find(i=>i.code===t);o||j("NATIVE_DATA_VIEW_NOT_FOUND",`/surface/views/${t}`);let n=new Map((o.sections||[]).flatMap(i=>i.fields.map(s=>[s,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,s])=>{let a={...s};delete a.section;let r=n.get(i);return[i,{...a,...r?{section:r}:{},list:o.list.fieldOrder.includes(i)}]}))}}function qs(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((i,s)=>{let a=`${o}/views/${s}`,r=re(i,a);be(r,["code","name","generated","list","form","detail","mobile","sections"],a);let c=Ce(r.code,`${a}/code`,64);(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(c)||n.has(c))&&j("NATIVE_DATA_VIEW_CODE_INVALID",`${a}/code`),n.add(c),Ce(r.name,`${a}/name`,255),re(r.generated,`${a}/generated`),re(r.mobile,`${a}/mobile`);for(let p of["list","detail","create","update","delete"])typeof r.generated[p]!="boolean"&&j("NATIVE_DATA_VIEW_OPERATION_INVALID",`${a}/generated/${p}`);typeof r.mobile.enabled!="boolean"&&j("NATIVE_DATA_VIEW_MOBILE_INVALID",`${a}/mobile/enabled`);for(let p of["list","form","detail"]){let d=re(r[p],`${a}/${p}`),u=ze(d.fieldOrder,`${a}/${p}/fieldOrder`,500,!0);for(let g of u){let I=e.fields[g];(!I||(I.hidden??I.system)===!0)&&j("NATIVE_DATA_VIEW_FIELD_INVALID",`${a}/${p}/fieldOrder`)}}if(r.sections!==void 0){(!Array.isArray(r.sections)||r.sections.length>100)&&j("NATIVE_DATA_VIEW_SECTIONS_INVALID",`${a}/sections`);let p=new Set;r.sections.forEach((d,u)=>{let g=`${a}/sections/${u}`,I=re(d,g);be(I,["title","fields"],g),Ce(I.title,`${g}/title`,255);for(let E of ze(I.fields,`${g}/fields`,100,!0)){let N=e.fields[E];(!N||(N.hidden??N.system)===!0||p.has(E))&&j("NATIVE_DATA_VIEW_FIELD_INVALID",`${g}/fields`),p.add(E)}})}let l=Tn(e,c);if(On(l,t,a),r.generated.create!==!1&&(e.mutationOwner||"native")==="native")for(let p of t)$t(p,e.fields[p.code])&&xo(p,e.fields[p.code],"create")&&!r.form.fieldOrder.includes(p.code)&&j("NATIVE_DATA_VIEW_CREATE_REQUIRED_FIELD_MISSING",`${a}/form/fieldOrder`)})}function xo(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 Js(e,t,o){let n=re(e,o);be(n,De.field,o),Ce(n.label,`${o}/label`,500),n.type!==t.type&&j("NATIVE_DATA_SURFACE_FIELD_TYPE_MISMATCH",`${o}/type`);let i=Ce(n.widget,`${o}/widget`,64);Ks[t.type].includes(i)||j("NATIVE_DATA_SURFACE_WIDGET_INCOMPATIBLE",`${o}/widget`),Ys(n.section,`${o}/section`,255);for(let s of["requiredHint","system","hidden","list","searchable","sortable"])Nn(n[s],`${o}/${s}`);n.searchable===!0&&!En(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 s of["readCapabilities","createCapabilities","updateCapabilities"])ze(n[s],`${o}/${s}`,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 s=Array.isArray(n.accept)?n.accept:[n.accept];ze(s,`${o}/accept`,50,!1)}for(let s of["maxLength","precision","scale","exactDecimal","min","max","rangeBoundary","options","source","userCandidates","timePrecision","serial","subtable"])zs(n,t,s,o);Hs(n,t,o)}function Gs(e,t,o){if(e===void 0)return;let n=re(e,o);if(be(n,De.list,o),n.actions!==void 0){let i=re(n.actions,`${o}/actions`);be(i,["import","export"],`${o}/actions`);for(let s of["import","export"])i[s]!==void 0&&typeof i[s]!="boolean"&&j("NATIVE_DATA_SURFACE_LIST_ACTION_INVALID",`${o}/actions/${s}`)}if(n.fieldOrder!==void 0)for(let i of ze(n.fieldOrder,`${o}/fieldOrder`,500,!0))t.has(i)||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[i,s]of[["searchableFields",En],["filterFields",ko]]){if(n[i]===void 0)continue;let a=ze(n[i],`${o}/${i}`,100,!0);for(let r of a){let c=t.get(r);(!c||!s(c.type))&&j("NATIVE_DATA_SURFACE_LIST_FIELD_INVALID",`${o}/${i}`)}}if(n.defaultSort!==void 0){let i=re(n.defaultSort,`${o}/defaultSort`);be(i,De.defaultSort,`${o}/defaultSort`);let s=Ce(i.field,`${o}/defaultSort/field`,63),a=t.get(s);!So(s)&&(!a||!st(a.type))&&j("NATIVE_DATA_SURFACE_SORT_UNSUPPORTED",`${o}/defaultSort/field`),i.order!==void 0&&!["asc","desc"].includes(i.order)&&j("NATIVE_DATA_SURFACE_SORT_ORDER_INVALID",`${o}/defaultSort/order`)}}function Lo(e,t,o,n){if(e===void 0)return;let i=re(e,o);if(be(i,De[n],o),i.layout!==void 0&&!["flat","sections"].includes(i.layout)&&j("NATIVE_DATA_SURFACE_LAYOUT_INVALID",`${o}/layout`),i.fieldOrder!==void 0){let s=`${o}/fieldOrder`;(!Array.isArray(i.fieldOrder)||i.fieldOrder.length>t.size||i.fieldOrder.length>Bs)&&j("NATIVE_DATA_SURFACE_FIELD_ORDER_INVALID",s);let a=i.fieldOrder.map((r,c)=>Ce(r,`${s}/${c}`,63));new Set(a).size!==a.length&&j("NATIVE_DATA_SURFACE_FIELD_ORDER_INVALID",s),a.forEach((r,c)=>{t.has(r)||j("NATIVE_DATA_SURFACE_FIELD_ORDER_FIELD_MISSING",`${s}/${c}`)})}n==="form"&&Fo(i.draftState,`${o}/draftState`)}function zs(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}`),ne(e[o])!==ne(t[o])&&j("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${n}/${o}`))}function Hs(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:bn(e.accept)}};for(let s of["maxCount","maxSizeMb","accept"]){if(i[s]===void 0&&n[s]===void 0)continue;(i[s]===void 0||n[s]===void 0)&&j("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${o}/${s}`);let a=s==="accept"?bn(i[s]):i[s],r=s==="accept"?bn(n[s]):n[s];ne(a)!==ne(r)&&j("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${o}/${s}`)}}function bn(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 ze(e,t,o,n){(!Array.isArray(e)||!n&&e.length===0||e.length>o)&&j("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t);let i=e.map((s,a)=>Ce(s,`${t}/${a}`,255));return new Set(i).size!==i.length&&j("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t),i}function re(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&j("NATIVE_OBJECT_REQUIRED",t),e}function be(e,t,o){let n=new Set(t);for(let i of Object.keys(e))n.has(i)||j("NATIVE_PROPERTY_UNKNOWN",`${o}/${i}`)}function Ce(e,t,o){return(typeof e!="string"||e.length===0||e.length>o)&&j("NATIVE_STRING_INVALID",t),e}function Ys(e,t,o){e!==void 0&&(typeof e!="string"||e.length>o)&&j("NATIVE_STRING_INVALID",t)}function Nn(e,t){e!==void 0&&typeof e!="boolean"&&j("NATIVE_BOOLEAN_REQUIRED",t)}function j(e,t){throw new ye(e,t)}var rt=class extends Error{constructor(o,n){super(`${o}: ${n}`);this.pointer=o;this.reason=n}pointer;reason;code="NATIVE_MANAGED_CONCURRENCY_INVALID"};function jo(e,t,o){if(e===void 0)return;let n=(_,A)=>{throw new rt(_,A)},i=(_,A,T)=>((!_||typeof _!="object"||Array.isArray(_)||Object.keys(_).some(f=>!T.includes(f)))&&n(A,"object contains unsupported properties"),_),s=(_,A,T,f)=>{(!Number.isSafeInteger(_)||_<A||_>T)&&n(f,`expected integer ${A}..${T}`)},a=(_,A)=>{(typeof _!="string"||!/^[a-z][a-z0-9_-]{0,63}$/.test(_))&&n(A,"invalid code")},r=(_,A,T)=>((!Array.isArray(_)||_.length>A)&&n(T,"array exceeds bound"),_),c=(_,A)=>{let T=t.find(f=>f.code===_);return T||n(A,"unknown resource"),T},l=(_,A,T)=>{let f=_.schema.fields.find(b=>b.code===A);return!f&&A!=="id"&&n(T,"unknown field"),f},p=(_,A,T=!1)=>{i(_,A,Object.keys(_||{})),Object.keys(_).length>8&&n(A,"at most eight parameters");for(let[f,b]of Object.entries(_))if(a(f,A),i(b,A,["type","values","minimum","maximum","minLength","maxLength"]),b.type==="uuid")Object.keys(b).length!==1&&n(A,"uuid has no options");else if(T&&b.type==="boolean")i(b,A,["type"]);else if(T&&b.type==="string"&&b.values===void 0)i(b,A,["type","minLength","maxLength"]),s(b.maxLength,1,256,A),b.minLength!==void 0&&s(b.minLength,0,b.maxLength,A);else if(b.type==="string"){i(b,A,["type","values"]);let h=r(b.values,100,A);(!h.length||h.some(C=>typeof C!="string"||C.length>128)||new Set(h).size!==h.length)&&n(A,"finite string values required")}else b.type==="integer"?(i(b,A,["type","minimum","maximum"]),s(b.minimum,0,1e6,A),s(b.maximum,b.minimum,b.minimum+1e3,A)):n(A,"unsupported parameter type")},d=(_,A,T,f=!1)=>{i(_,T,["from","key","value"]),!(_.from==="input"&&Object.keys(_).length===2&&Object.hasOwn(A,_.key))&&((_.from==="actor"||f&&_.from==="allocation")&&Object.keys(_).length===1||_.from==="literal"&&Object.keys(_).length===2&&Object.hasOwn(_,"value")&&(_.value===null||["string","boolean"].includes(typeof _.value)||typeof _.value=="number"&&Number.isFinite(_.value))&&JSON.stringify(_.value).length<=512||n(T,"invalid binding"))},u=(_,A,T)=>{d(_,A,T),!(_.from==="input"&&A[_.key].type==="uuid")&&(_.from==="literal"&&typeof _.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(_.value)||n(T,"record and allocation identifiers require a UUID binding"))},g=(_,A,T)=>{d(_,A,T),!(_.from==="input"&&A[_.key].type==="integer"&&A[_.key].minimum>=1)&&(_.from==="literal"&&Number.isSafeInteger(_.value)&&_.value>=1||n(T,"expectedRevision requires a positive integer binding"))},I="/data/concurrency";JSON.stringify(e).length>131072&&n(I,"declaration exceeds 128 KiB");let E=i(e,I,["version","admission","reads","quotas","commands"]);E.version!==1&&n(I,"unsupported version"),i(E.admission,I,["perSecond","burst","maxInFlight"]),s(E.admission.perSecond,1,1e3,I),s(E.admission.burst,1,1e3,I),s(E.admission.maxInFlight,1,1e3,I);let N=(_,A)=>{let T=new Set;for(let f of _)a(f?.code,A),T.has(f.code)&&n(A,"duplicate code"),T.add(f.code)};N(r(E.reads,32,I),I),N(r(E.quotas,16,I),I),N(r(E.commands,32,I),I);for(let _ of E.reads){let A=`${I}/reads/${_.code}`;i(_,A,["code","resourceCode","parameters","select","where","limit","scope","freshSeconds","staleSeconds","maxKeys","sourcePerSecond","dependencies"]);let T=c(_.resourceCode,A);p(_.parameters,A),["subject","application"].includes(_.scope)||n(A,"invalid cache scope"),_.scope==="application"&&T.dataPolicyCode&&n(A,"shared cache cannot bypass a row policy");let f=r(_.select,32,A);f.length||n(A,"select required"),f.forEach(h=>l(T,h,A));let b=r(_.dependencies,64,A);b.forEach(h=>l(T,h,A));for(let h of r(_.where||[],8,A))i(h,A,["field","value"]),l(T,h.field,A),d(h.value,_.parameters,A),_.scope==="application"&&h.value.from==="actor"&&n(A,"actor requires subject cache"),b.includes(h.field)||n(A,"filter dependency missing");f.some(h=>!b.includes(h))&&n(A,"selected field dependency missing"),s(_.limit,1,100,A),s(_.freshSeconds,1,300,A),s(_.staleSeconds,0,300,A),s(_.maxKeys,1,1e4,A),s(_.sourcePerSecond,1,20,A)}for(let _ of E.quotas){let A=`${I}/quotas/${_.code}`;i(_,A,["code","sourceResource","capacityField","allocationResource","allocationField","reservationSeconds"]);let T=c(_.sourceResource,A),f=c(_.allocationResource,A);l(T,_.capacityField,A)?.type!=="number.integer"&&n(A,"capacity must be an integer"),(l(f,_.allocationField,A)?.type!=="uuid"||l(f,_.allocationField,A)?.nullable!==!1)&&n(A,"allocation reference must be a uuid"),f.surface?.mutationOwner!=="queued-command"&&n(A,"allocation model must be command owned"),_.reservationSeconds!==void 0&&s(_.reservationSeconds,10,86400,A)}new Set(E.quotas.map(_=>_.allocationResource)).size!==E.quotas.length&&n(I,"an allocation model has exactly one pool owner");for(let _ of E.commands){let A=`${I}/commands/${_.code}`;i(_,A,["code","mode","intake","execution","capability","parameters","resourceKey","admission","deadlineSeconds","guards","operations","quota"]),_.mode!==void 0&&!["permit","durable"].includes(_.mode)&&n(A,"unsupported mode");let T=_.mode==="durable";if(p(_.parameters,A,T),d(_.resourceKey,_.parameters,A),o.some(f=>f.code===_.capability)||n(A,"command capability must be declared"),i(_.admission,A,["perSecond","burst","maxInFlight","maxQueue","maxWaitSeconds","permitSeconds"]),s(_.admission.perSecond,1,E.admission.perSecond,A),s(_.admission.burst,1,E.admission.burst,A),s(_.admission.maxInFlight,1,E.admission.maxInFlight,A),s(_.admission.maxQueue,1,1e4,A),s(_.admission.maxWaitSeconds,1,3600,A),(!T||_.admission.permitSeconds!==void 0)&&s(_.admission.permitSeconds,5,60,A),s(_.deadlineSeconds,10,3600,A),T){(_.operations!==void 0||_.guards!==void 0||_.quota!==void 0)&&n(A,"backend-plan does not accept static operations, guards or quota"),i(_.intake,A,["perSecond","burst","maxInFlight"]);for(let h of["perSecond","burst","maxInFlight"])s(_.intake[h],1,1e3,A);let f=i(_.execution,A,["kind","handlerCode","timeoutMs","resources","directory"]);f.kind!=="backend-plan"&&n(A,"durable requires backend-plan"),a(f.handlerCode,A),s(f.timeoutMs,100,3e4,A);let b=r(f.resources,32,A);b.length||n(A,"execution resources required"),new Set(b.map(h=>h.resourceCode)).size!==b.length&&n(A,"duplicate execution resource");for(let h of b){i(h,A,["resourceCode","readFields","writeOperations","writeFields"]);let C=c(h.resourceCode,A);for(let k of["readFields","writeFields"]){let W=r(h[k],64,A);new Set(W).size!==W.length&&n(A,"duplicate field"),W.forEach(v=>{k==="readFields"&&Oo.has(v)||l(C,v,A)})}let $=r(h.writeOperations,3,A);(new Set($).size!==$.length||$.some(k=>!["create","update","increment"].includes(k)))&&n(A,"unsupported execution operation"),h.writeFields.some(k=>["id","revision","created_by","updated_by","created_at","updated_at"].includes(k))&&n(A,"record metadata is platform owned"),!$.length&&h.writeFields.length&&n(A,"write fields require an operation"),$.length&&!h.writeFields.length&&n(A,"write operations require fields"),E.quotas.some(k=>k.allocationResource===h.resourceCode)&&$.length&&n(A,"allocation references remain owned by their pool command")}if(f.directory!==void 0){i(f.directory,A,["mode","fields"]),f.directory.mode!=="current-initiator"&&n(A,"only current initiator allowed");let h=r(f.directory.fields,5,A);(!h.length||new Set(h).size!==h.length||h.some(C=>!["displayName","employeeNumber","primaryDepartment","departments","phone"].includes(C)))&&n(A,"unsupported directory fields")}continue}(_.execution!==void 0||_.intake!==void 0)&&n(A,"execution and intake require durable mode");for(let f of r(_.guards||[],8,A)){i(f,A,["resourceCode","id","conditions"]);let b=c(f.resourceCode,A);u(f.id,_.parameters,A);for(let h of r(f.conditions,16,A)){i(h,A,["kind","field","operator","value"]);let C=l(b,h.field,A);["eq","neq","lt","lte","gt","gte"].includes(h.operator)||n(A,"unsupported guard"),h.kind==="database-now"?(C?.type!=="datetime"||!["lt","lte","gt","gte"].includes(h.operator)||h.value!==void 0)&&n(A,"database-now requires datetime and an ordering operator"):(h.kind!==void 0&&h.kind!=="value"&&n(A,"unsupported condition kind"),d(h.value,_.parameters,A))}}for(let f of r(_.operations,8,A)){i(f,A,["operation","resourceCode","id","expectedRevision","data"]);let b=c(f.resourceCode,A);b.surface?.mutationOwner!=="queued-command"&&n(A,"command mutations require command owned models");let h=E.quotas.find(C=>C.allocationResource===f.resourceCode);h&&(f.operation==="create"?_.quota?.action!=="allocate"||_.quota.pool!==h.code:Object.hasOwn(f.data||{},h.allocationField))&&n(A,"allocation references are owned by their pool command"),["create","update"].includes(f.operation)||n(A,"unsupported operation"),f.operation==="update"?(u(f.id,_.parameters,A),g(f.expectedRevision,_.parameters,A)):(f.id!==void 0||f.expectedRevision!==void 0)&&n(A,"create has no caller supplied id/revision"),i(f.data,A,Object.keys(f.data||{})),Object.keys(f.data).length>32&&n(A,"too many fields");for(let[C,$]of Object.entries(f.data))C==="id"&&n(A,"record identifiers are platform owned"),l(b,C,A),d($,_.parameters,A,_.quota?.action==="allocate")}if(_.quota){let f=i(_.quota,A,["pool","action","units","mode","allocation"]),b=E.quotas.find(h=>h.code===f.pool);b||n(A,"unknown quota pool"),u(_.resourceKey,_.parameters,A),f.action==="allocate"?(i(f,A,["pool","action","units","mode"]),s(f.units,1,1e3,A),(!["committed","reserved"].includes(f.mode)||f.mode==="reserved"&&!b.reservationSeconds)&&n(A,"invalid allocation mode"),(_.operations.length!==1||_.operations[0].operation!=="create"||_.operations[0].resourceCode!==b.allocationResource||_.operations[0].data[b.allocationField]?.from!=="allocation")&&n(A,"allocation must atomically create its bound business record")):["confirm","release"].includes(f.action)?(i(f,A,["pool","action","allocation"]),u(f.allocation,_.parameters,A),_.operations.length&&n(A,"lifecycle owns allocation state; business reference remains immutable")):n(A,"invalid quota action")}else _.operations.length||n(A,"operations required")}let y=E.commands.filter(_=>_.mode==="durable").map(_=>_.execution.handlerCode);return new Set(y).size!==y.length&&n(I,"handler code must be unique"),JSON.parse(JSON.stringify(E))}var He=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"},Cn=["parentTransitions","childTransitions","fulfilledChildStatuses","lockedParentStatuses"],Wo=["amountFieldCode","currencyFieldCode","relationFieldCode","parentFieldCode","rootFieldCode","statusFieldCode","parentRelationValue","childRelationValue"],Ft=e=>!!(e&&typeof e=="object"&&!Array.isArray(e)),Pt=e=>Array.isArray(e)?e.filter(Ft):[],Ne=(e,t)=>{throw new He(e,t)},hn=e=>typeof e=="string"&&/^[A-Za-z0-9._:-]{1,128}$/.test(e),Rn=(e,t)=>e<t?-1:e>t?1:0;function Sn(e,t="/decimalReservationLifecycle"){if(e===void 0)return;if(!Ft(e)||Object.keys(e).some(i=>!Cn.includes(i))||Cn.some(i=>!Object.prototype.hasOwnProperty.call(e,i)))return Ne(t,"\u5FC5\u987B\u5B8C\u6574\u58F0\u660E\u56DB\u9879\u89C4\u5219\uFF0C\u4E0D\u80FD\u5305\u542B\u672A\u77E5\u5C5E\u6027");let o=i=>{let s=e[i];if(!Array.isArray(s)||s.length>64)return Ne(`${t}/${i}`,"\u72B6\u6001\u8FB9\u6700\u591A 64 \u6761");let a=new Set;return s.map((r,c)=>{let l=`${t}/${i}/${c}`;if(!Ft(r)||Object.keys(r).some(d=>d!=="from"&&d!=="to")||!hn(r.from)||!hn(r.to)||r.from===r.to)return Ne(l,"\u72B6\u6001\u8FB9\u5FC5\u987B\u5305\u542B\u4E0D\u540C\u7684\u6709\u6548 from/to");let p=JSON.stringify([r.from,r.to]);return a.has(p)?Ne(l,"\u72B6\u6001\u8FB9\u4E0D\u80FD\u91CD\u590D"):(a.add(p),{from:r.from,to:r.to})}).sort((r,c)=>Rn(r.from,c.from)||Rn(r.to,c.to))},n=i=>{let s=e[i];return!Array.isArray(s)||s.length<1||s.length>16||s.some(a=>!hn(a))||new Set(s).size!==s.length?Ne(`${t}/${i}`,"\u72B6\u6001\u96C6\u5408\u5FC5\u987B\u5305\u542B 1 \u5230 16 \u4E2A\u4E0D\u91CD\u590D\u7684\u6709\u6548\u72B6\u6001"):[...s].sort(Rn)};return{parentTransitions:o("parentTransitions"),childTransitions:o("childTransitions"),fulfilledChildStatuses:n("fulfilledChildStatuses"),lockedParentStatuses:n("lockedParentStatuses")}}function Uo(e,t,o="/config/data/resources"){Pt(e).forEach((n,i)=>{let s=`${o}/${i}/decimalReservationLifecycle`,a=Sn(n.decimalReservationLifecycle,s);if(!a)return;let r=Pt(t).map(d=>d.platformAccess?.decimalReservation).filter(d=>Ft(d)&&d.resourceCode===n.code),c=r.find(d=>d.mode==="reserve");if(!c)return Ne(s,"\u9700\u8981\u540C\u8D44\u6E90\u5DF2\u58F0\u660E\u7684 reserve \u52A8\u4F5C\u6620\u5C04");if(Wo.some(d=>typeof c[d]!="string")||r.some(d=>Wo.some(u=>d[u]!==c[u])))return Ne(s,"\u540C\u8D44\u6E90\u989D\u5EA6\u52A8\u4F5C\u7684\u5B57\u6BB5\u6620\u5C04\u5FC5\u987B\u4E00\u81F4");let l=Pt(n.schema?.fields).find(d=>d.code===c.statusFieldCode);if(l?.type!=="option.single")return Ne(s,"\u989D\u5EA6\u72B6\u6001\u5B57\u6BB5\u5FC5\u987B\u4E3A option.single");let p=new Set(Pt(l.options).map(d=>d.value));for(let d of Cn)if((d==="parentTransitions"||d==="childTransitions"?a[d].flatMap(g=>[g.from,g.to]):a[d]).some(g=>!p.has(g)))return Ne(`${s}/${d}`,"\u72B6\u6001\u5FC5\u987B\u6765\u81EA\u989D\u5EA6\u72B6\u6001\u5B57\u6BB5\u7684\u9009\u9879");if(r.some(d=>d.mode==="reserve"&&Array.isArray(d.eligibleParentStatuses)&&d.eligibleParentStatuses.some(u=>a.lockedParentStatuses.includes(String(u)))))return Ne(`${s}/lockedParentStatuses`,"\u9501\u5B9A\u7236\u72B6\u6001\u4E0D\u80FD\u5141\u8BB8\u65B0\u9884\u7559")})}import{createHash as Xs}from"crypto";var wn=new Set(["option.single","user.single","department.single","resource-ref.single"]),Qs=new Set(["option.multiple","cascade.single","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","address","location","json"]),Bo=new Set(["option.multiple","cascade.single","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","file","image"]),Zs=new Set(["option.single","user.single","department.single","resource-ref.single","signature","address","location"]),er=new Set([...wn,...Bo,"signature","address","location","json"]);function Uc(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=>tr(n,o.has(n.code))).sort((n,i)=>n.code.localeCompare(i.code))}function tr(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:ir(e),index:or(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 Mc(e,t){if(t.type==="subtable")return null;let o=de(t.code),n=Ko(e,t),i=[n?` DEFAULT ${n}`:"",sr(o,t),nr(o,t)].join("");return`${o} ${t.storage}${i}`}function Bc(e,t){return Ko(e,t)}function nr(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 Kc(e){return e.type==="serial-number"||Dt(e.type)&&e.type!=="subtable"}function qc(e,t){return t.filter(o=>o.type==="serial-number").map(o=>{let n=Lt(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 Jc(e,t){let o=vt(e);return t.filter(n=>n.type==="serial-number").map(n=>`ALTER SEQUENCE ${Lt(e,n.code)} OWNED BY ${o}.${de(n.code)}`)}function Gc(e,t){return t.filter(o=>o.type==="serial-number").map(o=>`GRANT USAGE, SELECT ON SEQUENCE ${Lt(e,o.code)} TO "openxiangda_data_api"`)}function zc(e,t){let o=vt(e),n=[];for(let i of t){if(i.type==="subtable")continue;let s=de(i.code),a=de($e("idx",e,i.code,i.index));switch(i.index){case"btree":n.push(`CREATE INDEX IF NOT EXISTS ${a} ON ${o} (${s})`);break;case"btree-snapshot-expressions":{let r=de($e("idx",e,i.code,"snapshot-value")),c=de($e("idx",e,i.code,"snapshot-label"));n.push(`CREATE INDEX IF NOT EXISTS ${r} ON ${o} ((${s} ->> 'value'))`,`CREATE INDEX IF NOT EXISTS ${c} ON ${o} ((${s} ->> 'label'))`);break}case"gin-jsonb-path":n.push(`CREATE INDEX IF NOT EXISTS ${a} ON ${o} USING GIN (${s} jsonb_path_ops)`);break;case"gist-range":n.push(`CREATE INDEX IF NOT EXISTS ${a} ON ${o} USING GIST (${s})`);break;case"gin-trigram":{let r=wn.has(i.type)?`((${s} ->> 'label')) gin_trgm_ops`:`${s} gin_trgm_ops`;n.push(`CREATE INDEX IF NOT EXISTS ${a} ON ${o} USING GIN (${r})`);break}case"none":break}if(i.type==="serial-number"){let r=de($e("uidx",e,i.code,"serial"));n.push(`CREATE UNIQUE INDEX IF NOT EXISTS ${r} ON ${o} (${s})`)}}return n}function Hc(e,t,o,n){let i=vt(e),s=vt(t),a=de($e("uidx",e,"environment_id","subtable-parent")),r=de($e("idx",t,o,n,"subtable-child")),c=de($e("fk",t,o,e)),l=de(o),p=de(n);return[`CREATE UNIQUE INDEX IF NOT EXISTS ${a} ON ${i} ("tenant_id", "app_code", "environment_key", "id")`,`CREATE INDEX IF NOT EXISTS ${r} ON ${s} ("tenant_id", "app_code", "environment_key", ${l}, ${p}, "id")`,`DO $native_subtable$ BEGIN
2
2
  ALTER TABLE ${s}
3
- ADD CONSTRAINT ${a}
4
- FOREIGN KEY ("tenant_id", "app_code", "environment_key", ${d})
3
+ ADD CONSTRAINT ${c}
4
+ FOREIGN KEY ("tenant_id", "app_code", "environment_key", ${l})
5
5
  REFERENCES ${i} ("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 Se(e,...t){return`${e}_${ys("sha256").update(t.join(":")).digest("hex").slice(0,32)}`}function re(e){if(!/^[A-Za-z_][A-Za-z0-9_]{0,62}$/.test(e))throw new Error("OPENXIANGDA_NATIVE_IDENTIFIER_INVALID");return`"${e}"`}function Cs(e,t){return e.type==="subtable"?"none":t?"gin-trigram":e.indexed?["date-range","datetime-range"].includes(e.type)?"gist-range":_n.has(e.type)?"btree-snapshot-expressions":bs.has(e.type)?"gin-jsonb-path":"btree":"none"}function Ss(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 Os.has(e.type),"jsonb"}}function ho(e,t){if(It(t.type)&&t.type!=="subtable")return"'[]'::jsonb";if(t.type!=="serial-number")return"";let o=To(t.serial?.prefix||""),n=t.serial?.digits??6;return`(${o} || lpad(nextval(${To(Rt(e,t.code))})::text, ${n}, '0'))`}function ws(e,t){return Oo.has(t.type)?` CHECK (${e} IS NULL OR jsonb_typeof(${e}) = 'array')`:Ts.has(t.type)?` CHECK (${e} IS NULL OR jsonb_typeof(${e}) = 'object')`:""}function ht(e){return`"app_data".${re(e)}`}function Rt(e,t){let o=Se("seq",e,t);return`"app_data".${re(o)}`}function To(e){return`'${e.replace(/'/g,"''")}'`}var Ro=new Set(["option.single","option.multiple","user.single","user.multiple","department.single","department.multiple","resource-ref.single","resource-ref.multiple"]),Ds=new Set([...Ro,"cascade.single","cascade.multiple","file","image","signature","address","location","json"]),Co=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,$s=new Set(["__proto__","prototype","constructor"]),gn=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 ot(e,t){let o=wo(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 An(e){return!!(e&&e.field.type==="user.single"&&e.valuePath==="value")}function So(e,t,o){if(!e||!t||!Vs(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 s=i.slice(9),r=o.get(n.source?.resourceCode||"")?.get(s)?.type;return t.valueType==="uuid"?r==="uuid":["text.short","text.long","serial-number"].includes(r||"")}function tc(e,t){let o=wo(t);if(!o)throw new gn(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 Vs(e){let{field:t,valuePath:o}=e;if(!o)return!Ds.has(t.type);if(o==="value")return Ro.has(t.type);if(!o.startsWith("snapshot."))return!1;let n=o.slice(9);return Co.test(n)&&t.type.startsWith("resource-ref.")&&!!t.source?.snapshotFields?.includes(n)}function wo(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=>!Co.test(o)||$s.has(o))||t.length===2&&t[1]!=="value"||t.length===3&&t[1]!=="snapshot"?null:t}var ks=new Set(["option.single","user.single","department.single","resource-ref.single"]),Fs=new Set(["text.short","text.long","text.rich","number.integer","number.decimal","boolean","date","time","datetime","uuid","serial-number"]),vs=new Set(["value","label","description","color"]),Ps=new Set(["avatarUrl","employeeNo","title","mobile","email"]),Ls=new Set(["fullPath","parent.value","parent.label"]),xs=new Set(["country.value","country.label","province.value","province.label","city.value","city.label","district.value","district.label","street.value","street.label","detail","fullAddress"]),js=new Set(["longitude","latitude","accuracy"]),Ms=new Set(["address","name","province","city","district","source"]);function oc(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=Ws(n,t);if(!Object.keys(i).length)return n;let s={...n};return Object.defineProperty(s,"queryPathTypes",{configurable:!1,enumerable:!1,writable:!1,value:Object.freeze(i)}),s})}}))}function ic(e,t){if(ks.has(e.type)&&vs.has(t)||e.type==="user.single"&&Ps.has(t)||e.type==="department.single"&&Ls.has(t))return it(t);if(e.type==="resource-ref.single"){let o=e.queryPathTypes?.[t];return o?{parts:t.split("."),type:o}:null}if(e.type==="address"&&xs.has(t))return it(t);if(e.type==="location"){if(js.has(t))return{parts:[t],type:"number.decimal"};if(Ms.has(t))return it(t);if(t==="capturedAt")return{parts:[t],type:"datetime"}}return null}function Ws(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}`,Fs.has(i.type)?i.type:"json"]]:[]})):{}}function it(e){return{parts:e.split("."),type:"text.short"}}var Do=["exact-v1","nfkc-space-v1","nfkc-upper-ascii-v1"],rc=256,st=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"},En=e=>!!(e&&typeof e=="object"&&!Array.isArray(e)),oe=(e,t)=>{throw new st(e,t)},Ct=(e,t)=>e<t?-1:e>t?1:0,St=(e,t,o)=>{Object.keys(e).some(n=>!t.includes(n))&&oe(o,"\u4E0D\u652F\u6301\u672A\u77E5\u5C5E\u6027")};function $o(e,t,o="/uniqueKeys"){if(e===void 0)return;if(!Array.isArray(e)||e.length>8)return oe(o,"\u6BCF\u8D44\u6E90\u6700\u591A 8 \u6761\u89C4\u5219");let n=new Map(t.map(s=>[s.code,s])),i=new Set;return e.map((s,c)=>{let r=`${o}/${c}`;if(!En(s))return oe(r,"\u89C4\u5219\u5FC5\u987B\u662F\u5BF9\u8C61");if(St(s,["code","fields","when"],r),typeof s.code!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(s.code)||s.code.length>20||i.has(s.code))return oe(`${r}/code`,"\u9700\u8981\u4E0D\u91CD\u590D\u4E14\u4E0D\u8D85\u8FC7 20 \u5B57\u7B26\u7684 lower-kebab-case \u6807\u8BC6");if(i.add(s.code),!Array.isArray(s.fields)||s.fields.length<1||s.fields.length>4)return oe(`${r}/fields`,"\u5FC5\u987B\u9009\u62E9 1 \u5230 4 \u4E2A\u5B57\u6BB5");let a=new Set,d=s.fields.map((A,N)=>{let I=`${r}/fields/${N}`;if(!En(A))return oe(I,"\u5B57\u6BB5\u5FC5\u987B\u662F\u5BF9\u8C61");St(A,["fieldCode","normalizer"],I);let m=n.get(A.fieldCode);if(!m||!["text.short","uuid","option.single","resource-ref.single"].includes(m.type)||a.has(A.fieldCode))return oe(`${I}/fieldCode`,"\u9700\u8981\u4E0D\u91CD\u590D\u7684\u77ED\u6587\u672C\u3001UUID\u3001\u5355\u9009\u6216\u5355\u8BB0\u5F55\u5F15\u7528\u5B57\u6BB5");a.add(A.fieldCode);let E=A.normalizer===void 0?"exact-v1":A.normalizer;return!Do.includes(E)||m.type!=="text.short"&&E!=="exact-v1"?oe(`${I}/normalizer`,"\u5F52\u4E00\u5316\u65B9\u5F0F\u4E0D\u652F\u6301\u6216\u4E0E\u5B57\u6BB5\u7C7B\u578B\u4E0D\u7B26"):{fieldCode:m.code,normalizer:E}}).sort((A,N)=>Ct(A.fieldCode,N.fieldCode)),u=s.when===void 0?[]:s.when;if(!Array.isArray(u)||u.length>4)return oe(`${r}/when`,"\u6700\u591A 4 \u4E2A\u5408\u53D6\u6761\u4EF6");let l=new Set,f=u.map((A,N)=>{let I=`${r}/when/${N}`;if(!En(A))return oe(I,"\u6761\u4EF6\u5FC5\u987B\u662F\u5BF9\u8C61");let m=n.get(A.fieldCode);if(!m)return oe(`${I}/fieldCode`,"\u5B57\u6BB5\u4E0D\u5B58\u5728");let E;if(A.operator==="empty"||A.operator==="nonempty"){if(St(A,["fieldCode","operator"],I),m.type!=="text.short")return oe(I,"\u7A7A\u503C\u6761\u4EF6\u4EC5\u652F\u6301\u77ED\u6587\u672C");E={fieldCode:m.code,operator:A.operator}}else if(A.operator==="in"||A.operator==="notIn"){St(A,["fieldCode","operator","values"],I);let g=new Set((m.options??[]).map(O=>O.value));if(m.type!=="option.single"||!Array.isArray(A.values)||A.values.length<1||A.values.length>16||A.values.some(O=>typeof O!="string"||O.length<1||O.length>128||!g.has(O))||new Set(A.values).size!==A.values.length)return oe(I,"\u96C6\u5408\u6761\u4EF6\u9700\u8981 1 \u5230 16 \u4E2A\u4E0D\u91CD\u590D\u7684\u5DF2\u58F0\u660E\u5355\u9009\u503C");E={fieldCode:m.code,operator:A.operator,values:[...A.values].sort(Ct)}}else return oe(`${I}/operator`,"\u53EA\u652F\u6301 empty\u3001nonempty\u3001in \u548C notIn");let p=JSON.stringify(E);return l.has(p)?oe(I,"\u6761\u4EF6\u4E0D\u80FD\u91CD\u590D"):(l.add(p),E)}).sort((A,N)=>Ct(JSON.stringify(A),JSON.stringify(N)));return{code:s.code,fields:d,when:f}}).sort((s,c)=>Ct(s.code,c.code))}var In={type:"string",pattern:"^[A-Za-z_][A-Za-z0-9_]{0,62}$"},ac={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:In,normalizer:{enum:[...Do]}}}},when:{type:"array",maxItems:4,uniqueItems:!0,items:{oneOf:[{type:"object",additionalProperties:!1,required:["fieldCode","operator"],properties:{fieldCode:In,operator:{enum:["empty","nonempty"]}}},{type:"object",additionalProperties:!1,required:["fieldCode","operator","values"],properties:{fieldCode:In,operator:{enum:["in","notIn"]},values:{type:"array",minItems:1,maxItems:16,uniqueItems:!0,items:{type:"string",minLength:1,maxLength:128}}}}]}}}}};var Vo={"openxiangda.workflow.instance.completed.v2":"commit","openxiangda.workflow.instance.rejected.v2":"release","openxiangda.workflow.instance.withdrawn.v2":"release"};function ko(e,t){let o=()=>{throw new Error("NATIVE_EVENT_DECIMAL_RESERVATION_INVALID")},n=f=>!f||typeof f!="object"||Array.isArray(f)?o():f,i=n(e);if(Object.keys(i).some(f=>!["resourceCode","workflowCode","outcomes"].includes(f))||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 s=t.resources.find(f=>f.code===i.resourceCode),c=t.reservations.find(f=>f.mode==="reserve"&&f.resourceCode===i.resourceCode),r=t.workflows.find(f=>f.code===i.workflowCode);if(!s||!c||!r||r.resourceCode!==s.code)return o();let a=s.fields.find(f=>f.code===c.statusFieldCode);if(a?.type!=="option.single")return o();let d=new Set(a.options?.map(f=>f.value)),u=new Set,l=i.outcomes.map(f=>{let A=n(f),N=A.eventType;return Object.keys(A).some(I=>!["eventType","mode","eligibleChildStatuses"].includes(I))||typeof N!="string"||!Object.prototype.hasOwnProperty.call(Vo,N)||!t.eventTypes.includes(N)||u.has(N)||A.mode!==Vo[N]||!Array.isArray(A.eligibleChildStatuses)||!A.eligibleChildStatuses.length||A.eligibleChildStatuses.length>16||new Set(A.eligibleChildStatuses).size!==A.eligibleChildStatuses.length||A.eligibleChildStatuses.some(I=>typeof I!="string"||!/^[A-Za-z0-9._:-]{1,128}$/.test(I)||!d.has(I))?o():(u.add(N),{eventType:N,mode:A.mode,eligibleChildStatuses:[...A.eligibleChildStatuses].sort()})}).sort((f,A)=>f.eventType.localeCompare(A.eventType));return{resourceCode:i.resourceCode,workflowCode:i.workflowCode,outcomes:l}}function Fo(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(s=>({value:s.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 Nn=class extends Error{constructor(o,n){super(n);this.pointer=o}pointer;code="NATIVE_EVENT_ACTION_INVALID"};function vo(e,t,o="/events/subscriptions"){if(e.execution===void 0)return;let n=(I,m)=>{throw new Nn(`${o}${I}`,m)},i=(I,m,E)=>((!I||typeof I!="object"||Array.isArray(I)||Object.keys(I).some(p=>!E.includes(p)))&&n(m,"Invalid action object or unsupported property"),I),s=i(e.execution,"/execution",["kind","version","operations"]);(s.kind!=="native-data"||s.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(I=>!/^openxiangda\.data\.record\.(created|updated|deleted)\.v2$/.test(I)))&&n("/eventTypes","Native data actions require declared data events");let c=e.filter?.resourceCodes;(!Array.isArray(c)||!c.length||c.length>20)&&n("/filter/resourceCodes","Native actions require explicit source resources");let r=new Map(t.map(I=>[I.code,I])),a=c.map(I=>{let m=r.get(I);return m||n("/filter/resourceCodes","Unknown source resource"),new Set((m.schema?.fields||[]).map(E=>E.code))}),d=new Set(e.payload?.fields||[]),u=e.payload?.includeChanges===!0,l=(I,m)=>{let E=i(I,m,["source","path","value"]);if(E.source==="literal"){(!Object.hasOwn(E,"value")||Object.hasOwn(E,"path"))&&n(m,"Literal binding requires only value");let y;try{y=JSON.stringify(E.value)}catch{n(m,"Literal must be JSON")}return(y===void 0||Buffer.byteLength(y)>65536)&&n(m,"Literal is too large or not JSON"),{source:"literal",value:JSON.parse(y)}}(E.source!=="event"||typeof E.path!="string"||Object.hasOwn(E,"value"))&&n(m,"Expected a literal or event binding");let p=E.path.split(".");(p.length>8||p.some(y=>!/^[A-Za-z0-9_-]+$/.test(y)||["__proto__","prototype","constructor"].includes(y)))&&n(m,"Invalid event path");let g=/^data\.projection\.([A-Za-z][A-Za-z0-9_]{0,62})$/.exec(E.path),O=/^data\.changes\.([A-Za-z][A-Za-z0-9_]{0,62})\.(before|after)$/.exec(E.path);if(g||O){let y=(g||O)[1];a.some(T=>!T.has(y))&&n(m,"Source field must exist on every filtered resource"),d.add(y),O&&(u=!0)}else["id","time","type","subject","data.recordId","data.revision","data.operation","data.resourceCode"].includes(E.path)||n(m,"Event path is not part of the data event contract");return{source:"event",path:E.path}};(!Array.isArray(s.operations)||s.operations.length<1||s.operations.length>16)&&n("/execution/operations","Expected 1 to 16 operations");let f={},A=s.operations.map((I,m)=>{let E=`/execution/operations/${m}`,p=i(I,E,["operation","resourceCode","data","id","expectedRevision"]);["create","update","delete"].includes(p.operation)||n(E,"Unsupported Native operation");let g=r.get(p.resourceCode);g||n(E,"Unknown action target resource");let O=new Map((g.schema?.fields||[]).map(T=>[T.code,T])),y=p.data===void 0?{}:i(p.data,`${E}/data`,[...O.keys()]);return Object.keys(y).length>32&&n(E,"Maximum 32 mapped fields per operation"),p.operation==="create"&&(p.id!==void 0||p.expectedRevision!==void 0)&&n(E,"Create does not accept id or expectedRevision"),p.operation==="delete"&&p.data!==void 0&&n(E,"Delete does not accept data"),Object.keys(y).some(T=>O.get(T)?.type==="serial-number")&&n(E,"Generated fields cannot be assigned"),f[p.resourceCode]=X(g),{operation:p.operation,resourceCode:p.resourceCode,...p.operation==="create"?{}:{id:l(p.id,`${E}/id`),expectedRevision:l(p.expectedRevision,`${E}/expectedRevision`)},...p.operation==="delete"?{}:{data:Object.fromEntries(Object.entries(y).map(([T,h])=>[T,l(h,`${E}/data/${T}`)]))}}});(d.size>32||[...d].some(I=>a.some(m=>!m.has(I))))&&n("/payload/fields","Payload must contain at most 32 declared source fields");let N={kind:"native-data",version:1,operations:A,resourceDigests:f};return Buffer.byteLength(JSON.stringify(N))>65536&&n("/execution","Action plan exceeds 64 KiB"),{execution:{...N,digest:X(N)},payload:{includeChanges:u,fields:[...d].sort()}}}function we(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function Lo(e,t){if(e?.instanceCommands===void 0)return[];let o=we(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,s]of Object.entries(o)){let c=we(s),r=i==="withdraw"?["beforeFact"]:["beforeFact","capability"];if(!c||Object.keys(c).some(a=>!r.includes(a))){n.push(`WORKFLOW_INSTANCE_COMMAND_POLICY_INVALID:${i}`);continue}if(i==="terminate"){let a=c.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(i==="withdraw"||c.beforeFact!==void 0){let a=c.beforeFact,d=we(e.inputSchema),u=we(we(d?.properties)?.[a]),l=we(we(e.subject)?.factProjection)?.[a],f=t?.fields.get(l);(typeof a!="string"||!/^[A-Za-z][A-Za-z0-9_]{0,62}$/.test(a)||!Array.isArray(d?.required)||!d.required.includes(a)||u?.type!=="string"||u?.format!=="date-time"||typeof l!="string"||t&&(f?.type!=="datetime"||f.nullable===!0))&&n.push(`WORKFLOW_INSTANCE_COMMAND_DEADLINE_FACT_INVALID:${i}`)}}return n}function fc(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 Po(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,s,c,r]=t,a=t[8],d=new Date(Date.UTC(Number(o),Number(n),0)).getUTCDate();if(Number(n)<1||Number(n)>12||Number(i)<1||Number(i)>d||Number(s)>23||Number(c)>59||Number(r)>59||a!=="Z"&&(Number(a.slice(1,3))>23||Number(a.slice(4))>59))return null;let u=Date.parse(e);return Number.isFinite(u)?u:null}function pc(e,t,o,n){let i=e?.[t];if(!i||t==="terminate"&&i.beforeFact===void 0)return null;let s=i.beforeFact,c=we(o),r=s&&c&&Object.hasOwn(c,s)?Po(c[s]):null,a=n instanceof Date?n.getTime():Po(n);return r===null||a===null||!Number.isFinite(a)?"WORKFLOW_V2_CANCELLATION_DEADLINE_INVALID":a<r?null:"WORKFLOW_V2_CANCELLATION_DEADLINE_PASSED"}var rt="openxiangda.workflow.step.requested.v2",Mo=[rt,"openxiangda.workflow.step.result_received.v2","openxiangda.workflow.step.completed.v2","openxiangda.workflow.step.continuation_failed.v2"],Tn=16384,Us=2048,_c="steps",On=/^[A-Za-z][A-Za-z0-9_-]{0,127}$/,Wo=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,ke=new Set(["__proto__","prototype","constructor"]),B=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&[Object.prototype,null].includes(Object.getPrototypeOf(e)),Uo=e=>{try{let t=JSON.stringify(e);return t===void 0?1/0:new TextEncoder().encode(t).length}catch{return 1/0}},Je=(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((s,c)=>Je(s,t[c],o+1));if(!B(e)||!B(t))return!1;let n=Object.keys(e).filter(s=>e[s]!==void 0),i=Object.keys(t).filter(s=>t[s]!==void 0);return n.length===i.length&&n.every(s=>Object.hasOwn(t,s)&&Je(e[s],t[s],o+1))};function yn(e,t){let o=0,n=(i,s)=>++o>1e4||s>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(c=>n(c,s+1)):B(i)&&Object.keys(i).length<=32&&Object.keys(i).every(c=>!ke.has(c))&&Object.values(i).every(c=>n(c,s+1));return Uo(e)<=t&&n(e,0)}function Bs(e){return!B(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&&B(e.output)&&yn(e.output,Tn)&&(e.receipt===void 0||B(e.receipt)&&yn(e.receipt,Us))}function gc(e){return B(e)&&Object.keys(e).every(t=>["executionId","nodeId","handlerCode","handlerVersion","mode","input","inputDigest","expectedFactRevision"].includes(t))&&typeof e.nodeId=="string"&&On.test(e.nodeId)&&!ke.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)&&Bs({executionId:e.executionId,handlerVersion:e.handlerVersion,inputDigest:e.inputDigest,expectedFactRevision:e.expectedFactRevision,output:e.input})}function wt(e,t,o=Tn){if(!yn(t,o))return!1;let n=1e4,i=(s,c,r)=>{if(--n<0||r>8||!B(s))return!1;let a=c===null?"null":Array.isArray(c)?"array":typeof c=="number"&&Number.isSafeInteger(c)?"integer":typeof c,d=Array.isArray(s.type)?s.type:[s.type];if(!d.includes(a)&&!(a==="integer"&&d.includes("number"))||s.enum!==void 0&&(!Array.isArray(s.enum)||!s.enum.some(u=>Je(u,c)))||Object.hasOwn(s,"const")&&!Je(s.const,c))return!1;if(typeof c=="number")return Number.isFinite(c)&&(s.minimum===void 0||c>=s.minimum)&&(s.maximum===void 0||c<=s.maximum);if(typeof c=="string"){let u=Array.from(c).length;return(s.minLength===void 0||u>=s.minLength)&&(s.maxLength===void 0||u<=s.maxLength)}return Array.isArray(c)?c.length<=s.maxItems&&(s.minItems===void 0||c.length>=s.minItems)&&c.every(u=>i(s.items,u,r+1)):B(c)?!B(s.properties)||Object.keys(c).some(u=>ke.has(u)||!Object.hasOwn(s.properties,u))||(Array.isArray(s.required)?s.required:[]).some(u=>!Object.hasOwn(c,u))||s.minProperties!==void 0&&Object.keys(c).length<s.minProperties||s.maxProperties!==void 0&&Object.keys(c).length>s.maxProperties?!1:Object.entries(c).every(([u,l])=>i(s.properties[u],l,r+1)):c===null||typeof c=="boolean"};return i(e,t,0)}function Ks(e){return typeof e=="string"&&e.length<=256&&e.split(".").length<=8&&e.split(".").every(t=>On.test(t)&&!ke.has(t))}function Dt(e){let t=0,o=(n,i)=>{if(!B(n)||i>6||++t>256||Object.keys(n).some(r=>!["type","title","description","properties","required","additionalProperties","items","maxItems","minItems","maxLength","minLength","minimum","maximum","enum","const","maxProperties","minProperties"].includes(r)))return!1;let s=Array.isArray(n.type)?n.type:[n.type];if(!s.length||s.length>2||s.some(r=>!["object","array","string","integer","number","boolean","null"].includes(r))||s.length>1&&(!s.includes("null")||new Set(s).size!==s.length))return!1;for(let r of["title","description"])if(n[r]!==void 0&&(typeof n[r]!="string"||n[r].length>2e3))return!1;for(let r of["minimum","maximum"])if(n[r]!==void 0&&(typeof n[r]!="number"||!Number.isFinite(n[r])))return!1;for(let[r,a]of[["maxItems",200],["minItems",200],["maxLength",16384],["minLength",16384],["maxProperties",32],["minProperties",32]])if(n[r]!==void 0&&(!Number.isSafeInteger(n[r])||n[r]<0||n[r]>a))return!1;for(let[r,a]of[["minimum","maximum"],["minItems","maxItems"],["minLength","maxLength"],["minProperties","maxProperties"]])if(n[r]!==void 0&&n[a]!==void 0&&n[r]>n[a])return!1;if(["properties","required","additionalProperties","maxProperties","minProperties"].some(r=>n[r]!==void 0)&&!s.includes("object")||["items","maxItems","minItems"].some(r=>n[r]!==void 0)&&!s.includes("array")||["maxLength","minLength"].some(r=>n[r]!==void 0)&&!s.includes("string")||["minimum","maximum"].some(r=>n[r]!==void 0)&&!s.some(r=>r==="integer"||r==="number")||n.enum!==void 0&&(!Array.isArray(n.enum)||!n.enum.length||n.enum.length>100)||s.includes("object")&&(!B(n.properties)||n.additionalProperties!==!1||Object.keys(n.properties).length>32||Object.keys(n.properties).some(r=>!Wo.test(r)||ke.has(r))||n.required!==void 0&&(!Array.isArray(n.required)||new Set(n.required).size!==n.required.length||n.required.some(r=>typeof r!="string"||!Object.hasOwn(n.properties,r)))||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(r=>o(r,i+1)))||s.includes("array")&&(!Number.isSafeInteger(n.maxItems)||!o(n.items,i+1)))return!1;let c={...n};return delete c.enum,delete c.const,!(n.enum!==void 0&&(!n.enum.every(r=>wt(c,r))||n.enum.some((r,a)=>n.enum.slice(0,a).some(d=>Je(r,d))))||Object.hasOwn(n,"const")&&!wt(c,n.const))};return B(e)&&e.type==="object"&&Uo(e)<=Tn&&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 Bo(e,t){let o=e;for(let n of t.split(".")){if(!B(o?.properties)||!Object.hasOwn(o.properties,n))return;o=o.properties[n]}return B(o)?o:void 0}var xo=(e,t)=>!!Bo(e,t);function Ac(e){return B(e)&&Object.keys(e).every(t=>["version","mode","inputSchema","outputSchema"].includes(t))&&Number.isSafeInteger(e.version)&&e.version>=1&&e.version<=1e6&&["pure","reconciled-effect"].includes(e.mode)&&Dt(e.inputSchema)&&Dt(e.outputSchema)}function jo(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 bn(e,t=0){return!B(e)||t>16?[]:e.op==="path"?typeof e.path=="string"?[e.path]:[]:["left","right","value"].flatMap(o=>bn(e[o],t+1)).concat(Array.isArray(e.values)?e.values.flatMap(o=>bn(o,t+1)):[])}function Vt(e,t){if(!B(e)||!B(e.nodes))return["WORKFLOW_STEP_DEFINITION_INVALID"];let o=e.nodes,n=Object.entries(o).filter(([,r])=>r?.kind==="action");if(!n.length)return[];let i=[];Object.hasOwn(e.inputSchema?.properties||{},"steps")&&i.push("WORKFLOW_STEP_FACT_NAMESPACE_RESERVED");let s=$t(e);for(let[r,a]of n){(Object.keys(a).some(l=>!["id","kind","title","next","handler","inputSchema","outputSchema","inputs"].includes(l))||a.id!==r||!On.test(r)||ke.has(r)||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:${r}`);let d=a.handler;(!B(d)||Object.keys(d).some(l=>!["code","version","mode"].includes(l))||!Number.isSafeInteger(d.version)||d.version<1||d.version>1e6||!/^[a-z][a-z0-9-]{0,100}$/.test(d.code||"")||!String(d.code).endsWith(`-v${d.version}`)||!["pure","reconciled-effect"].includes(d.mode))&&i.push(`WORKFLOW_STEP_HANDLER_INVALID:${r}`);let u=Dt(a.inputSchema);if((!u||!Dt(a.outputSchema))&&i.push(`WORKFLOW_STEP_SCHEMA_INVALID:${r}`),!B(a.inputs)||Object.keys(a.inputs).length>32){i.push(`WORKFLOW_STEP_INPUTS_INVALID:${r}`);continue}for(let l of Array.isArray(a.inputSchema?.required)?a.inputSchema.required:[])Object.hasOwn(a.inputs,l)||i.push(`WORKFLOW_STEP_INPUT_REQUIRED:${r}:${l}`);for(let[l,f]of Object.entries(a.inputs)){if(!Wo.test(l)||ke.has(l)||!Object.hasOwn(a.inputSchema?.properties||{},l)||!B(f)){i.push(`WORKFLOW_STEP_INPUT_INVALID:${r}:${l}`);continue}if(f.source==="literal")(!u||Object.keys(f).some(A=>!["source","value"].includes(A))||!Object.hasOwn(f,"value")||!wt(a.inputSchema.properties[l],f.value))&&i.push(`WORKFLOW_STEP_LITERAL_INVALID:${r}:${l}`);else if(f.source!=="fact"||Object.keys(f).some(A=>!["source","path"].includes(A))||!Ks(f.path)||!xo(s,f.path))i.push(`WORKFLOW_STEP_FACT_PATH_INVALID:${r}:${l}`);else if(u){let A=Bo(s,f.path),N=a.inputSchema.properties[l],I=Array.isArray(A.type)?A.type:[A.type],m=Array.isArray(N.type)?N.type:[N.type];I.some(E=>!m.includes(E)&&!(E==="integer"&&m.includes("number")))&&i.push(`WORKFLOW_STEP_FACT_TYPE_MISMATCH:${r}:${l}`)}}}let c=(r,a)=>{let d=new Set,u=[e.startAt||""];for(;u.length&&d.size<=200;){let l=u.shift();if(!(l===a||d.has(l)||!o[l])){if(l===r)return!0;d.add(l),u.push(...jo(o[l]))}}return!1};for(let[r,a]of Object.entries(o)){if(!B(a))continue;let d=a.kind==="action"?Object.values(a.inputs||{}).flatMap(l=>l?.source==="fact"?[l.path]:[]):(Array.isArray(a.branches)?a.branches:[]).flatMap(l=>bn(l?.when)),u=t?.bindings?.[a.binding];u&&d.push(...[u.inputPath,u.departmentIdFrom,u.resourceIdFrom,u.scope?.valueFrom].filter(l=>typeof l=="string"));for(let l of d.filter(f=>typeof f=="string"&&f.startsWith("steps."))){let f=l.split(".")[1];(o[f]?.kind!=="action"||f===r||!xo(s,l)||c(r,f))&&i.push(`WORKFLOW_STEP_OUTPUT_NOT_AVAILABLE:${r}:${l}`)}}if(t)for(let[,r]of n){let a=new Set,d=[r.next];for(;d.length&&a.size<=200;){let u=d.shift();if(a.has(u)||!B(o[u]))continue;a.add(u);let l=o[u];if(!(l.kind==="action"||l.kind==="end")){if(l.kind==="approval"){let f=t.bindings?.[l.binding];f&&["application_provider","initiator_select"].includes(f.provider)&&i.push(`WORKFLOW_STEP_NEXT_PROVIDER_REQUIRES_PREPARED_RESULT:${u}`);continue}d.push(...jo(l))}}}return[...new Set(i)]}function Ec(e,t){let o={};for(let[n,i]of Object.entries(e.inputs)){let s=i.source==="literal"?i.value:i.path.split(".").reduce((c,r)=>B(c)&&Object.hasOwn(c,r)?c[r]:void 0,t);s!==void 0&&(o[n]=s)}if(!wt(e.inputSchema,o))throw new Error("WORKFLOW_STEP_INPUT_SCHEMA_INVALID");return o}function Ko(e,t,o){let n=hn(e),i=[];Object.keys(n).length&&!o&&i.push("WORKFLOW_STEP_BACKEND_REQUIRED");for(let s of Object.keys(n)){let c=t.find(r=>r.code===s);(!c||c.execution||c.action||!Array.isArray(c.eventTypes)||c.eventTypes.length!==1||c.eventTypes[0]!==rt||!B(c.filter)||Object.keys(c.filter).length!==1||!B(c.filter.workflowStep)||Object.keys(c.filter.workflowStep).length!==1||c.filter.workflowStep.handlerCode!==s||!B(c.payload)||c.payload.includeChanges!==!1||!Array.isArray(c.payload.fields)||c.payload.fields.length)&&i.push(`WORKFLOW_STEP_SUBSCRIPTION_INVALID:${s}`)}for(let s of t)(s.eventTypes?.includes(rt)&&!n[s.code]||s.filter?.workflowStep&&!n[s.code])&&i.push(`WORKFLOW_STEP_HANDLER_NOT_DECLARED:${s.code}`);return i}function hn(e){let t={};for(let o of e){let n=Vt(o);if(n.length)throw new Error(n.join("; "));for(let i of Object.values(o.nodes||{})){if(i.kind!=="action")continue;let s={version:i.handler.version,mode:i.handler.mode,inputSchema:i.inputSchema,outputSchema:i.outputSchema},c=t[i.handler.code];if(c&&!Je(c,s))throw new Error(`WORKFLOW_STEP_HANDLER_CONTRACT_CONFLICT:${i.handler.code}`);t[i.handler.code]=s}}return t}var ce=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},Fe=(e,t)=>typeof e=="string"&&!!e.trim()&&e.length<=t,Gs=/^[A-Za-z][A-Za-z0-9_-]*(?:\.[A-Za-z][A-Za-z0-9_-]*){0,15}$/,Rn=e=>typeof e=="string"&&e.length<=256&&Gs.test(e)&&!e.split(".").some(t=>["__proto__","prototype","constructor"].includes(t));function Ft(e,t){let o=ce(e),n=!0;for(let i of t.split(".")){n&&=Array.isArray(o.required)&&o.required.includes(i);let s=ce(o.properties)[i];if(!s||typeof s!="object")return null;o=ce(s)}return{schema:o,required:n}}function Go(e){let t=new Set,o=[],n=2048,i=(s,c)=>{if(--n<0||c>20){o.push("WORKFLOW_EXPRESSION_BUDGET_EXCEEDED");return}let r=ce(s);if(r.op==="path")Rn(r.path)?t.add(r.path):o.push("WORKFLOW_EXPRESSION_PATH_INVALID");else{if(r.op==="literal")return;if(r.op==="and"||r.op==="or")if(!Array.isArray(r.values)||!r.values.length||r.values.length>128)o.push("WORKFLOW_EXPRESSION_GROUP_INVALID");else for(let a of r.values){if(n<0)break;i(a,c+1)}else r.op==="not"||r.op==="exists"?i(r.value,c+1):["eq","neq","gt","gte","lt","lte","in","contains"].includes(String(r.op))?(i(r.left,c+1),i(r.right,c+1)):o.push("WORKFLOW_EXPRESSION_OPERATOR_INVALID")}};return i(e,0),{paths:[...t],errors:[...new Set(o)]}}function qo(e){if(e?.readability===void 0)return[];let t=[],o=$t(e),n=ce(e.readability);(Object.keys(n).some(r=>!["variables","logic"].includes(r))||!Object.keys(n).length)&&t.push("WORKFLOW_READABILITY_INVALID");let i=ce(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[r,a]of Object.entries(i)){let d=ce(a);(!Rn(r)||!Ft(o,r))&&t.push(`WORKFLOW_VARIABLE_SOURCE_UNKNOWN:${r}`),(!Fe(d.label,160)||Object.keys(d).some(u=>!["label","unit","description"].includes(u))||d.unit!==void 0&&!Fe(d.unit,32)||d.description!==void 0&&!Fe(d.description,2e3))&&t.push(`WORKFLOW_VARIABLE_METADATA_INVALID:${r}`)}let s=n.logic===void 0?[]:n.logic;(!Array.isArray(s)||s.length>32)&&t.push("WORKFLOW_LOGIC_LIMIT_INVALID");let c=new Set;for(let r of Array.isArray(s)?s.slice(0,32):[]){let a=ce(r),d=String(a.code||"");(!/^[a-z][a-z0-9-]{2,63}$/.test(d)||c.has(d)||!Fe(a.title,160)||!Fe(a.description,4e3)||Object.keys(a).some(u=>!["code","title","description","phase","nodeId","inputPaths","outputPaths","source"].includes(u)))&&t.push(`WORKFLOW_LOGIC_METADATA_INVALID:${d}`),c.add(d),(!["submission","node_input","completion"].includes(String(a.phase))||a.phase==="node_input"&&!ce(e.nodes)[String(a.nodeId)]||a.phase!=="node_input"&&a.nodeId!==void 0)&&t.push(`WORKFLOW_LOGIC_ANCHOR_INVALID:${d}`);for(let u of["inputPaths","outputPaths"]){let l=a[u];if(!(u==="outputPaths"&&l===void 0))if(!Array.isArray(l)||l.length>32||new Set(l).size!==l.length)t.push(`WORKFLOW_LOGIC_PATHS_INVALID:${d}:${u}`);else for(let f of l)(!Rn(f)||!Ft(o,f))&&t.push(`WORKFLOW_LOGIC_SOURCE_UNKNOWN:${d}:${String(f)}`)}if(a.source!==void 0){let u=ce(a.source);(!Fe(u.path,256)||String(u.path).startsWith("/")||String(u.path).includes("..")||String(u.path).includes("://")||!/^sha256:[a-f0-9]{64}$/.test(String(u.digest))||u.symbol!==void 0&&!Fe(u.symbol,160)||Object.keys(u).some(l=>!["path","symbol","digest"].includes(l)))&&t.push(`WORKFLOW_LOGIC_SOURCE_REFERENCE_INVALID:${d}`)}}for(let r of Object.values(ce(e.nodes))){let a=ce(r),d=Array.isArray(a.branches)?a.branches:[];for(let u of d){let l=Go(u.when);t.push(...l.errors.map(f=>`${f}:${a.id}`));for(let f of l.paths)Ft(o,f)||t.push(`WORKFLOW_VARIABLE_SOURCE_UNKNOWN:${a.id}:${f}`)}}return[...new Set(t)]}function yc(e,t){let o=$t(e),n=[],i=new Map,s=[];for(let a of Object.values(e.nodes)){if(a.kind==="approval")for(let[d,u,l]of[["approve",a.onApprove,"\u540C\u610F"],["reject",a.onReject,"\u62D2\u7EDD"]])u&&n.push({id:`${a.id}:${d}`,from:a.id,to:u,kind:d,label:l,variablePaths:[]});if(a.kind==="cc"&&a.next&&n.push({id:`${a.id}:next`,from:a.id,to:a.next,kind:"next",label:"\u6284\u9001\u540E\u7EE7\u7EED",variablePaths:[]}),a.kind==="action"&&a.next){let d=Object.values(a.inputs||{}).flatMap(u=>u.source==="fact"?[u.path]:[]);for(let u of d)i.has(u)||i.set(u,new Set),i.get(u).add(a.id);n.push({id:`${a.id}:next`,from:a.id,to:a.next,kind:"next",label:"\u6210\u529F\u56DE\u6267\u540E\u7EE7\u7EED",variablePaths:d})}if(a.kind==="condition"){for(let[d,u]of(a.branches||[]).entries()){let l=Go(u.when);for(let f of l.paths)i.has(f)||i.set(f,new Set),i.get(f).add(a.id);n.push({id:`${a.id}:branch:${d}`,from:a.id,to:u.target,kind:"branch",label:u.label||`\u6761\u4EF6 ${d+1}`,priority:d+1,expression:u.when,variablePaths:l.paths}),s.push(...l.errors.map(f=>({code:f,path:a.id})))}a.otherwise&&n.push({id:`${a.id}:default`,from:a.id,to:a.otherwise,kind:"default",label:"\u5747\u4E0D\u6EE1\u8DB3\u65F6",variablePaths:[]})}}let r=[...new Set([...i.keys(),...Object.keys(e.readability?.variables||{}),...(e.readability?.logic||[]).flatMap(a=>[...a.inputPaths,...a.outputPaths||[]])])].slice(0,128).map(a=>{let d=Ft(o,a),u=e.readability?.variables?.[a],l=a.split("."),f=e.subject?.factProjection[l[0]],A=l[0]==="steps"?e.nodes[l[1]]:void 0;return d||s.push({code:"WORKFLOW_VARIABLE_SOURCE_UNKNOWN",path:a}),{path:a,label:u?.label||String(d?.schema.title||a),type:String(d?.schema.type||"unknown"),...u,required:d?.required||!1,usedBy:[...i.get(a)||[]],source:d&&A?.handler?{kind:"step_output",nodeId:A.id,handlerCode:A.handler.code,handlerVersion:A.handler.version}:d&&f&&e.subject?{kind:"subject_field",resourceCode:e.subject.resourceCode,fieldPath:[f,...l.slice(1)].join(".")}:{kind:d?"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(a=>({id:a.id,kind:a.kind,title:a.title||a.id,...a.binding?{binding:a.binding}:{},...a.mode?{mode:a.mode}:{},...a.outcome?{outcome:a.outcome}:{},...a.kind==="cc"?{emptyPolicy:a.emptyPolicy,notify:a.notify!==!1}:{},...a.kind==="action"&&a.handler?{businessStep:{handler:a.handler,inputs:a.inputs||{},outputPaths:Object.keys(ce(a.outputSchema).properties||{}).map(d=>`steps.${a.id}.${d}`)}}:{}})),edges:n,variables:r,logic:e.readability?.logic||[],diagnostics:s}}function kt(e,t=[],o=0){if(!e||o>20)return"\u65E0\u6CD5\u8BC6\u522B\u7684\u6761\u4EF6";if(e.op==="path")return t.find(c=>c.path===e.path)?.label||e.path;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(c=>`\uFF08${kt(c,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${kt(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,s=i&&e.right.op==="literal"&&typeof e.right.value=="number"?t.find(c=>c.path===i)?.unit:void 0;return`${kt(e.left,t,o+1)} ${n[e.op]} ${kt(e.right,t,o+1)}${s?` ${s}`:""}`}var Cn=["approve","reject","return","transfer","delegate","add_assignee"],Sn=["fixed_users","app_role","app_role_in_scope"],qs=["single","any","all","sequence"],De=e=>!!e&&typeof e=="object"&&!Array.isArray(e),ze=(e,t)=>Object.keys(e).every(o=>t.includes(o)),vt=(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 at(e){return e.allowedOperations||[...Cn]}function Jo(e,t,o={},n=!1){return!(!De(e)||!Object.keys(e).length||!ze(e,n?["enabled","label","commentRequired"]:["label","commentRequired"])||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)||(t==="reject"||o.commentRequired)&&!e.commentRequired))}function wn(e,t){let o=[];for(let[n,i]of Object.entries(e?.nodes||{})){if(!De(i))continue;let s=i.administration,c=i.operationPolicy;if(i.kind==="cc"){(c!==void 0||s!==void 0&&(!De(s)||!ze(s,["assigneeProviders"])))&&o.push(`WORKFLOW_NODE_ADMINISTRATION_INVALID:${n}`),s?.assigneeProviders!==void 0&&!vt(s.assigneeProviders,Sn,3)&&o.push(`WORKFLOW_NODE_ADMINISTRATION_PROVIDERS_INVALID:${n}`),s?.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"){(s!==void 0||c!==void 0)&&o.push(`WORKFLOW_NODE_ADMINISTRATION_APPROVAL_REQUIRED:${n}`);continue}if(c!==void 0&&(!De(c)||Object.keys(c).length>8||Object.entries(c).some(([a,d])=>!Cn.includes(a)||!at(i).includes(a)||!Jo(d,a)))&&o.push(`WORKFLOW_NODE_OPERATION_POLICY_INVALID:${n}`),s===void 0)continue;if(!De(s)||!ze(s,["modes","assigneeProviders","operations"])){o.push(`WORKFLOW_NODE_ADMINISTRATION_INVALID:${n}`);continue}s.modes!==void 0&&(!vt(s.modes,qs,4)||!s.modes.includes(i.mode))&&o.push(`WORKFLOW_NODE_ADMINISTRATION_MODES_INVALID:${n}`),s.assigneeProviders!==void 0&&!vt(s.assigneeProviders,Sn,3)&&o.push(`WORKFLOW_NODE_ADMINISTRATION_PROVIDERS_INVALID:${n}`);let r=t?.bindings[i.binding||""];r&&Array.isArray(s.assigneeProviders)&&s.assigneeProviders.includes("app_role_in_scope")&&!r.scope&&o.push(`WORKFLOW_NODE_ADMINISTRATION_SCOPE_REQUIRED:${n}`),s.operations!==void 0&&(!vt(s.operations,Cn,8)||s.operations.some(a=>!at(i).includes(a)))&&o.push(`WORKFLOW_NODE_ADMINISTRATION_OPERATIONS_INVALID:${n}`)}return o}function Tc(e,t,o){let n=[];if(!e||!De(o)||!Object.keys(o).length||!ze(o,["title","description","assignee","mode","operations"]))return["WORKFLOW_V2_NODE_CONFIGURATION_PATCH_INVALID"];let i=o;for(let c of["title","description"])i[c]!==void 0&&(typeof i[c]!="string"||i[c].length>(c==="title"?255:1e3)||c==="title"&&!i[c].trim())&&n.push("WORKFLOW_V2_NODE_CONFIGURATION_PATCH_INVALID");let s=e.administration;if(i.mode!==void 0&&(e.kind!=="approval"||!s?.modes?.includes(i.mode))&&n.push("WORKFLOW_V2_NODE_CONFIGURATION_MODE_READONLY"),i.operations!==void 0&&(e.kind!=="approval"||!De(i.operations)||!Object.keys(i.operations).length||Object.keys(i.operations).length>8||Object.entries(i.operations).some(([c,r])=>!s?.operations?.includes(c)||!at(e).includes(c)||!Jo(r,c,e.operationPolicy?.[c],!0)))&&n.push("WORKFLOW_V2_NODE_CONFIGURATION_OPERATION_INVALID"),i.assignee!==void 0){let c=i.assignee,r=s?.assigneeProviders||(e.kind==="approval"&&t&&Sn.includes(t.provider)?[t.provider]:[]);!De(c)||!["approval","cc"].includes(e.kind)||!r.includes(c.provider)||c.provider==="app_role_in_scope"&&!t?.scope?n.push("WORKFLOW_V2_NODE_CONFIGURATION_PROVIDER_READONLY"):c.provider==="fixed_users"?(!ze(c,["provider","users"])||!Array.isArray(c.users)||c.users.length<1||c.users.length>(e.kind==="cc"?20:200)||new Set(c.users).size!==c.users.length||c.users.some(a=>typeof a!="string"||!a.trim()||a.length>255))&&n.push("WORKFLOW_V2_NODE_CONFIGURATION_USERS_INVALID"):(!ze(c,["provider","roleCode"])||typeof c.roleCode!="string"||!/^[a-z][a-z0-9_-]{0,127}$/.test(c.roleCode))&&n.push("WORKFLOW_V2_NODE_CONFIGURATION_ROLE_INVALID")}return n}function Oc(e,t){let o=Object.fromEntries(at(e).flatMap(n=>{let i=n,s=t?.operations?.[i],c={...e.operationPolicy?.[i],...s?.label!==void 0?{label:s.label}:{},...s?.commentRequired!==void 0?{commentRequired:s.commentRequired}:{}};return Object.keys(c).length?[[i,c]]:[]}));return{mode:t?.mode||e.mode,allowedOperations:at(e).filter(n=>t?.operations?.[n]?.enabled!==!1),operationPolicy:o,fieldPolicy:{default:e.fieldPolicy?.default||"readonly",fields:{...e.fieldPolicy?.fields}}}}var Rc=20,Js=["fixed_users","initiator","input_users","form_field_users","app_role","app_role_in_scope","previous_node_actor"];function Dn(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 s=t.bindings?.[i.binding];if(!s){o.push(`WORKFLOW_CC_BINDING_NOT_FOUND:${n}`);continue}Js.includes(s.provider)||o.push(`WORKFLOW_CC_PROVIDER_INVALID:${n}`);let c=s.min??1,r=s.max??20;(!Number.isSafeInteger(c)||!Number.isSafeInteger(r)||c<1||r<c||r>20||s.provider==="fixed_users"&&(!Array.isArray(s.users)||!s.users.length||s.users.length>r))&&o.push(`WORKFLOW_CC_RECIPIENT_LIMIT_INVALID:${n}`)}return[...new Set(o)]}var Sc=64,wc=65536,xe=new Set(["__proto__","prototype","constructor"]),zo=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,Vn=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,de=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&[null,Object.prototype].includes(Object.getPrototypeOf(e)),ve=(e,t)=>de(e)&&Object.keys(e).every(o=>t.includes(o)&&!xe.has(o)),kn=e=>{try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return 1/0}},Yo=e=>e==null||typeof e=="string"&&!e.trim()||Array.isArray(e)&&e.length===0;function Pe(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((n,i)=>Pe(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)&&Pe(e[n],t[n]))}function $n(e,t){let o=t.split(".");if(!(o.some(n=>!zo.test(n)||xe.has(n))||o.length>12))return o.reduce((n,i)=>de(n)&&Object.hasOwn(n,i)?n[i]:void 0,e)}function $e(e,t){switch(e.op){case"literal":return e.value;case"path":return $n({values:t},e.path);case"and":return e.values.every(o=>!!$e(o,t));case"or":return e.values.some(o=>!!$e(o,t));case"not":return!$e(e.value,t);case"exists":return!Yo($e(e.value,t));default:{let o=$e(e.left,t),n=$e(e.right,t);return e.op==="eq"?Pe(o,n):e.op==="neq"?!Pe(o,n):e.op==="in"?Array.isArray(n)&&n.some(i=>Pe(i,o)):e.op==="contains"?Array.isArray(o)?o.some(i=>Pe(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 ct(e,t,o=0,n={nodes:0}){if(o>8||++n.nodes>64||!de(e))return!1;if(e.op==="literal")return ve(e,["op","value"])&&Object.hasOwn(e,"value")&&kn(e.value)<=4096&&Pt(e.value);if(e.op==="path"){if(!ve(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(s=>Vn.test(s)&&!xe.has(s))}return["not","exists"].includes(e.op)?ve(e,["op","value"])&&ct(e.value,t,o+1,n):["and","or"].includes(e.op)?ve(e,["op","values"])&&Array.isArray(e.values)&&e.values.length>0&&e.values.length<=16&&e.values.every(i=>ct(i,t,o+1,n)):["eq","neq","gt","gte","lt","lte","in","contains"].includes(e.op)&&ve(e,["op","left","right"])&&ct(e.left,t,o+1,n)&&ct(e.right,t,o+1,n)}function Fn(e,t){let o=[],n=e.taskPages;if(n!==void 0&&(!de(n)||Object.keys(n).length===0||Object.keys(n).length>16||kn(n)>65536))return["WORKFLOW_TASK_PAGES_INVALID"];for(let[i,s]of Object.entries(n||{})){let c=`taskPages.${i}`;if(!zo.test(i)||xe.has(i)||!ve(s,["title","fields"])||typeof s.title!="string"||!s.title.trim()||s.title.length>160||!Array.isArray(s.fields)||!s.fields.length||s.fields.length>64){o.push(`WORKFLOW_TASK_PAGE_INVALID:${c}`);continue}let r=new Set(s.fields.map(a=>a?.code));r.size!==s.fields.length&&o.push(`WORKFLOW_TASK_PAGE_DUPLICATE_FIELD:${c}`);for(let a of s.fields){if(!ve(a,["code","readonly","required","visibleWhen","requiredWhen"])||!Vn.test(a.code)||xe.has(a.code)||["readonly","required"].some(d=>a[d]!==void 0&&typeof a[d]!="boolean")||a.readonly&&(a.required||a.requiredWhen)){o.push(`WORKFLOW_TASK_PAGE_FIELD_INVALID:${c}`);continue}for(let d of["visibleWhen","requiredWhen"])a[d]!==void 0&&!ct(a[d],r)&&o.push(`WORKFLOW_TASK_PAGE_EXPRESSION_INVALID:${c}.${a.code}.${d}`);if(t){let d=t.get(a.code);(!d||d.system||d.hidden||d.type==="serial-number"||!a.readonly&&(d.widget==="readonly"||["subtable","signature","text.rich"].includes(d.type)))&&o.push(`WORKFLOW_TASK_PAGE_RESOURCE_FIELD_INVALID:${c}.${a.code}`)}}}for(let[i,s]of Object.entries(e.nodes||{}))de(s)&&s.taskPageCode!==void 0&&(s.kind!=="approval"||typeof s.taskPageCode!="string"||!de(n)||!Object.hasOwn(n,s.taskPageCode)?o.push(`WORKFLOW_TASK_PAGE_NOT_FOUND:${i}`):Array.isArray(n[s.taskPageCode]?.fields)&&n[s.taskPageCode].fields.some(c=>c&&(s.fieldPolicy?.fields?.[c.code]||s.fieldPolicy?.default)==="hidden")&&o.push(`WORKFLOW_TASK_PAGE_FIELD_HIDDEN:${i}`));return o}function zs(e,t){return e.fields.map(o=>({code:o.code,visible:o.visibleWhen===void 0||!!$e(o.visibleWhen,t),readonly:o.readonly===!0,required:o.required===!0||o.requiredWhen!==void 0&&!!$e(o.requiredWhen,t)}))}var Le=class extends Error{constructor(o,n){super(o);this.code=o;this.field=n}code;field};function Pt(e,t={members:0},o=0){return++t.members>5e3||o>12?!1:e===null||typeof e=="boolean"?!0:typeof e=="string"?e.length<=65536:typeof e=="number"?Number.isFinite(e):Array.isArray(e)?e.length<=1e3&&e.every(n=>Pt(n,t,o+1)):de(e)&&Object.entries(e).every(([n,i])=>!xe.has(n)&&Pt(i,t,o+1))}function Dc(e,t,o,n){if(!de(o)||kn(o)>65536||!Pt(o))throw new Le("WORKFLOW_TASK_FORM_VALUES_INVALID");let i={...t,...o},s=new Map(zs(e,i).map(c=>[c.code,c]));for(let c of Object.keys(o)){let r=s.get(c);if(!r||r.readonly||!r.visible)throw new Le("WORKFLOW_TASK_FORM_FIELD_NOT_EDITABLE",c)}if(n){for(let c of s.values())if(c.visible&&!c.readonly&&c.required&&Yo(i[c.code]))throw new Le("WORKFLOW_TASK_FORM_REQUIRED",c.code)}return i}function $c(e,t,o){let n=JSON.parse(JSON.stringify(t));for(let[c,r]of Object.entries(e.subject?.factProjection||{})){let a=c.split(".");if(!a.length||a.length>12||c.length>128||a[0]==="steps"||a.some(u=>!Vn.test(u)||xe.has(u)))throw new Le("WORKFLOW_TASK_FORM_FACT_PROJECTION_INVALID");if(!Object.hasOwn(o,r))throw new Le("WORKFLOW_TASK_FORM_FACT_FIELD_MISSING",r);let d=n;for(let u of a.slice(0,-1))d=d[u]=de(d[u])?d[u]:{};d[a.at(-1)]=o[r]===void 0?void 0:JSON.parse(JSON.stringify(o[r]))}let i=new Set,s=Object.values(e.nodes||{}).filter(c=>c.kind==="action");for(let c=0;c<=s.length;c++){let r=!1;for(let a of s)de(n.steps)&&Object.hasOwn(n.steps,a.id)&&Object.values(a.inputs||{}).some(d=>d.source==="fact"&&!Pe($n(t,d.path),$n(n,d.path)))&&(delete n.steps[a.id],i.add(a.id),r=!0);if(!r)break}return{facts:n,invalidatedNodeIds:[...i].sort()}}function Vc(e,t,o){let n=e.nodes||{};for(let i of o){let s=new Set,c=new Map,r=a=>{if(a===i)return!0;if(c.has(a))return c.get(a);if(s.has(a)||s.size>200)return!1;let d=n[a];if(!de(d)||d.kind==="end")return!1;s.add(a);let u=d.kind==="approval"?[d.onApprove]:d.kind==="condition"?[...(d.branches||[]).map(f=>f.target),d.otherwise]:[d.next],l=u.length>0&&u.every(f=>typeof f=="string"&&r(f));return s.delete(a),c.set(a,l),l};if(!r(t))return!1}return!0}var Fc=256,vc=64,Pc=262144,Ys=/^[a-z][a-z0-9_-]{0,127}$/,Hs=/^[A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z][A-Za-z0-9_]*)*$/,Xo=new Set(["__proto__","prototype","constructor"]),ye=e=>!!e&&typeof e=="object"&&!Array.isArray(e),lt=(e,t)=>Object.keys(e).every(o=>t.includes(o)),je=(e,t)=>typeof e=="string"&&e.trim().length>0&&e.length<=t&&!/[\u0000-\u001f\u007f]/.test(e),he=e=>typeof e=="string"&&Ys.test(e)&&!Xo.has(e),Qo=e=>typeof e=="string"&&e.length<=255&&Hs.test(e)&&!e.split(".").some(t=>Xo.has(t)),Xs=e=>ye(e)&&lt(e,["dimension","valueFrom","value"])&&he(e.dimension)&&(je(e.value,255)&&e.valueFrom===void 0||Qo(e.valueFrom)&&e.value===void 0),Ho=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)),dt={type:"string",pattern:"^[a-z][a-z0-9_-]{0,127}$"},vn={type:"string",minLength:1,maxLength:128},Lc={type:"object",additionalProperties:!1,required:["policyCode","title","strategy","dimensions","sources"],properties:{policyCode:dt,title:vn,strategy:{enum:["replace_then_append","replace_only"]},dimensions:{type:"object",maxProperties:8,propertyNames:dt,additionalProperties:{type:"object",additionalProperties:!1,required:["title","valueFrom"],properties:{title:vn,valueFrom:{type:"string",minLength:1,maxLength:255}}}},sources:{type:"object",minProperties:1,maxProperties:16,propertyNames:dt,additionalProperties:{type:"object",additionalProperties:!1,required:["title","provider","roleCode"],properties:{title:vn,provider:{enum:["app_role","app_role_in_scope"]},roleCode:dt,scope:{type:"object",additionalProperties:!1,required:["dimension"],properties:{dimension:dt,value:{type:"string",minLength:1,maxLength:255},valueFrom:{type:"string",minLength:1,maxLength:255}}}}}}}};function Lt(e){if(!ye(e)||!lt(e,["policyCode","title","strategy","dimensions","sources"])||!he(e.policyCode)||!je(e.title,128)||!["replace_then_append","replace_only"].includes(e.strategy))return["WORKFLOW_V2_ROUTING_POLICY_INVALID"];let t=[];return(!ye(e.dimensions)||Object.keys(e.dimensions).length>8||Object.entries(e.dimensions).some(([o,n])=>!he(o)||!ye(n)||!lt(n,["title","valueFrom"])||!je(n.title,128)||!Qo(n.valueFrom)))&&t.push("WORKFLOW_V2_ROUTING_DIMENSIONS_INVALID"),(!ye(e.sources)||Object.keys(e.sources).length<1||Object.keys(e.sources).length>16||Object.entries(e.sources).some(([o,n])=>!he(o)||!ye(n)||!lt(n,["title","provider","roleCode","scope"])||!je(n.title,128)||!he(n.roleCode)||!["app_role","app_role_in_scope"].includes(n.provider)||(n.provider==="app_role_in_scope"?!Xs(n.scope):n.scope!==void 0)))&&t.push("WORKFLOW_V2_ROUTING_SOURCES_INVALID"),t}function xc(e,t){if(Lt(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(!ye(i)||!lt(i,["ruleCode","title","enabled","workflowCode","nodeId","matches","sourceCode","effect","priority","validFrom","validTo"])||!he(i.ruleCode)||!je(i.title,128)||typeof i.enabled!="boolean"||!he(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&&!he(i.workflowCode)||i.nodeId!==void 0&&(!he(i.nodeId)||i.workflowCode===void 0)||i.validFrom!==void 0&&!Ho(i.validFrom)||i.validTo!==void 0&&!Ho(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),(!ye(i.matches)||Object.entries(i.matches).some(([s,c])=>!Object.hasOwn(e.dimensions,s)||!Array.isArray(c)||c.length<1||c.length>64||new Set(c).size!==c.length||c.some(r=>!je(r,255))))&&o.push(`WORKFLOW_V2_ROUTING_MATCH_INVALID:${i.ruleCode}`)}return[...new Set(o)]}function Qs(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 Zo(e){let t=[],o=new Map;for(let n of e)for(let[i,s]of Object.entries(n.bindings||{})){if(!ye(s)||s.routing===void 0)continue;let c=Lt(s.routing);if(c.length){t.push(...c.map(d=>`${d}:${i}`));continue}let r=Qs(s.routing),a=o.get(s.routing.policyCode);a&&a!==r&&t.push(`WORKFLOW_V2_ROUTING_POLICY_CONFLICT:${s.routing.policyCode}`),o.set(s.routing.policyCode,r)}return[...new Set(t)]}function jc(e,t){let o={};for(let[n,i]of Object.entries(e.dimensions)){let s=t;for(let c of i.valueFrom.split("."))s=ye(s)&&Object.hasOwn(s,c)?s[c]:void 0;if(!(typeof s=="string"&&je(s,255)||typeof s=="number"&&Number.isFinite(s)||typeof s=="boolean"))throw new Error(`WORKFLOW_V2_ROUTING_FACT_REQUIRED:${n}`);o[n]=String(s)}return o}function Mc(e,t,o){let n=t.filter(d=>d.enabled&&(!d.validFrom||Date.parse(d.validFrom)<=o.at)&&(!d.validTo||Date.parse(d.validTo)>o.at)&&(!d.workflowCode||d.workflowCode===o.workflowCode)&&(!d.nodeId||d.nodeId===o.nodeId)&&Object.entries(d.matches).every(([u,l])=>l.includes(o.facts[u])));if(n.length>64)throw new Error("WORKFLOW_V2_ROUTING_MATCH_LIMIT_EXCEEDED");let i=(d,u)=>u.priority-d.priority||+!!d.workflowCode-+!!u.workflowCode||+!!d.nodeId-+!!u.nodeId||(d.ruleCode<u.ruleCode?-1:d.ruleCode>u.ruleCode?1:0),s=n.filter(d=>d.effect==="replace").sort(i);if(s.length>1&&s[0].priority===s[1].priority)throw new Error("WORKFLOW_V2_ROUTING_REPLACE_CONFLICT");let c=s[0],r=c&&e.strategy==="replace_only"?[]:n.filter(d=>d.effect==="append").sort(i),a=[...c?[c]:[],...r];return{matched:n.sort(i),replacement:c,applied:a,ignored:n.filter(d=>!a.includes(d))}}import*as Ut from"crypto";var ei="native-4",ti={"application-native-2":"1.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-api-v2":"1.1.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.0.0","data.managed-concurrency":"1.0.0","data.managed-concurrency.durable":"1.0.0","workflow.named-input-sources":"1.0.0","directory-v2":"1.0.0","directory.selected-user":"1.0.0","events-v2":"1.0.0","events.durable-receipts":"1.0.0","events.capture-policy":"1.0.0","events.native-data-actions":"1.0.0","workflow-kernel-v2":"1.0.0","workflow.instance-cancellation-policy":"1.0.0","workflow.node-administration":"1.0.0","workflow.assignment-routing":"1.0.0","workflow.role-references":"1.0.0","workflow.delegation-management":"1.0.0","workflow.automatic-cc":"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.durable-business-step":"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 Bc=5,Kc=20,Gc=50,qc=50,Jc=100,ft=class extends Error{constructor(o,n){super(o);this.code=o;this.pointer=n;this.name="NativeDataPolicyExpressionV2Error"}code;pointer};function xt(e,t){let o=[],n=(i,s,c)=>{c>5&&ut("NATIVE_DATA_POLICY_EXPRESSION_DEPTH_EXCEEDED",s);let r=oi(i,s),a=["allOf","anyOf"].filter(l=>l in r);if(a.length===0){o.push({rule:r,pointer:s}),o.length>50&&ut("NATIVE_DATA_POLICY_EXPRESSION_LEAVES_EXCEEDED",s);return}let d=a[0],u=r[d];(a.length!==1||Object.keys(r).length!==1||!Array.isArray(u)||u.length<1||u.length>20)&&ut("NATIVE_DATA_POLICY_EXPRESSION_GROUP_INVALID",s),u.forEach((l,f)=>n(l,`${s}/${d}/${f}`,c+1))};return n(e,t,1),o}function ni(e,t){xt(e,t);let o=(n,i)=>{let s=oi(n,i);if(Array.isArray(s.allOf))return Pn(s.allOf.flatMap((c,r)=>o(c,`${i}/allOf/${r}`)),i);if(Array.isArray(s.anyOf)){let c=[[]];return s.anyOf.forEach((r,a)=>{let d=o(r,`${i}/anyOf/${a}`);c=Pn(c.flatMap(u=>d.map(l=>[...u,...l])),i)}),c}return[[s]]};return Pn(o(e,t),t)}function Pn(e,t){let o=e.reduce((n,i)=>n+i.length,0);return(e.length>50||o>100)&&ut("NATIVE_DATA_POLICY_EXPRESSION_EXPANSION_EXCEEDED",t),e}function oi(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&ut("NATIVE_DATA_POLICY_EXPRESSION_NODE_INVALID",t),e}function ut(e,t){throw new ft(e,t)}var Zs="openxiangda.config-bundle/v3",yi="openxiangda.contract-bundle/v3",ii="openxiangda.native-configuration-projection/v1",mt=ei,er=/^[a-f0-9]{64}$/,tr=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,nr=/^app:[a-z][a-z0-9]*(?:-[a-z0-9]+)*:[A-Za-z0-9:._*-]+$/,or=/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/,ir=/^[a-z][a-z0-9]*(?:[-.][a-z0-9]+)*$/,sr=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,rr=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,si=/^[A-Za-z][A-Za-z0-9_]{0,127}$/,ar=/^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*$/,cr=/^[A-Z][A-Z0-9_]*$/,dr=/^[a-z][a-z0-9-]{2,63}$/,lr=/^[A-Za-z][A-Za-z0-9_-]{0,127}$/,ur=/^[A-Za-z][A-Za-z0-9_.]{0,127}$/,fr=16,pr=2*1024,mr=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"]),_r=new Set(["overview","database","operations","workflow","members","calendar","document","folder","settings"]),gr=new Set(["approve","reject","return","transfer","delegate","add_assignee","resubmit","withdraw","terminate","admin_reassign","admin_override","retry_resolution"]),Ar=4*1024*1024,Er=8*1024*1024,Ir=40,Nr=1e5,xn=1024*1024,yr="openxiangda.event-handler-manifest/v2",bi="openxiangda.application-route-manifest/v3",ri=64,Ti=new Set(["id","revision","created_by","updated_by","created_at","updated_at"]),Y=Object.freeze({perspectives:100,resources:100,subjectReadSurfaces:50,capabilities:2e3,operations:500,eventConsumers:100,eventProducers:1e3,eventSchemas:100,eventTypes:500,workflows:100,routes:500,adminPages:500,adminNavigationGroups:100,adminNavigationItems:500}),jn=["openxiangda.data.record.created.v2","openxiangda.data.record.updated.v2","openxiangda.data.record.deleted.v2"],Mn=[rt,"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"],br=new Set(Mn),Wn=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,s])=>[i,String(s).slice(0,128)]))}};function Ed(e){let t=C(e.appCode,"/appCode",128);tr.test(t)||_("NATIVE_CONFIG_APP_CODE_INVALID","/appCode");let o=Bn(e.expectedConfigDigest,"/expectedConfigDigest"),n=Bn(e.expectedContractDigest,"/expectedContractDigest"),i=Ei(e.configBytes,Ar,"/configBytes","NATIVE_CONFIG_ARTIFACT_TOO_LARGE"),s=Ei(e.contractBytes,Er,"/contractBytes","NATIVE_CONTRACT_ARTIFACT_TOO_LARGE");Ii(i,o,"/configBytes","NATIVE_CONFIG_DIGEST_MISMATCH"),Ii(s,n,"/contractBytes","NATIVE_CONTRACT_DIGEST_MISMATCH");let c=gi(i,"/configBytes","NATIVE_CONFIG_JSON_INVALID","NATIVE_CONFIG_NOT_CANONICAL"),r=gi(s,"/contractBytes","NATIVE_CONTRACT_JSON_INVALID","NATIVE_CONTRACT_NOT_CANONICAL");Ai(c,"/config"),Ai(r,"/contracts");let a=c,d=r;Rr(a,t),Cr(d,t,o);let u=Sr(a,o,d.generatorVersion);ma(u,d,a),ee(u)!==ee(d)&&_("NATIVE_CONTRACT_CLOSURE_MISMATCH",Kn(u,d,"/contracts"));let l={authz:{appCode:t,...a.authz,perspectives:a.perspectives,capabilityCatalog:u.capabilities},data:{appCode:t,resources:a.data.resources,resourceContracts:u.resources,...u.concurrency?{concurrency:u.concurrency}:{},...u.subjectReadSurfaces?{subjectReadSurfaces:u.subjectReadSurfaces}:{}},events:{appCode:t,...a.events,consumers:u.eventConsumers,producers:u.eventProducers,handlerManifest:u.eventHandlerManifest,eventTypes:u.eventTypes,capturePlans:Or({resources:a.data.resources,dataPolicies:a.authz.dataPolicies,subscriptions:u.eventConsumers,capturePolicies:a.events.capturePolicies})},workflows:{appCode:t,...a.workflows,contracts:u.workflows},runtime:{appCode:t,requirements:a.runtime,backend:a.backend,frontend:a.frontend},contracts:u},f={authz:Ye(l.authz),data:Ye(l.data),events:Ye(l.events),workflows:Ye(l.workflows),runtime:Ye(l.runtime),contracts:Ye(l.contracts)},A={configDigest:o,contractDigest:n,generatorVersion:d.generatorVersion},N=Tr(a),I={schemaVersion:ii,compilerContractVersion:mt,appCode:t,source:A,projections:f,requiredPlatformCapabilities:N,aggregateDigest:X({schemaVersion:ii,compilerContractVersion:mt,appCode:t,source:A,requiredPlatformCapabilities:N,projectionDigests:Object.fromEntries(Object.entries(f).map(([m,E])=>[m,E.digest]))})};return vi(I)}function Tr(e){let t=e.authz.roles,o=e.data.resources,n=e.backend.operations,i=t.some(m=>m.capabilities.some(E=>E.endsWith(":directory:read")))||o.some(m=>m.schema.fields.some(E=>["user.single","user.multiple","department.single","department.multiple"].includes(E.type)))||n.some(m=>m.platformAccess?.directory),s=!!(e.events.subscriptions.length||e.events.timers.length||e.events.dateTriggers.length||e.events.schemas.length),c=n.some(m=>m.platformAccess?.managedFiles||m.platformAccess?.managedFileCopies)||e.events.subscriptions.some(m=>m.platformAccess?.managedFileCopies),r=n.some(m=>m.platformAccess?.notification)||e.events.subscriptions.some(m=>m.platformAccess?.notification),a=e.workflows.definitions.filter(m=>{let E=o.find(p=>p.code===m.definition.subject?.resourceCode)?.schema.fields||[];return Object.values(m.definition.taskPages||{}).some(p=>p.fields.some(g=>!g.readonly&&E.some(O=>O.code===g.code&&["file","image"].includes(O.type))))}),d=e.workflows.definitions.filter(m=>m.launch.mode==="standalone"||m.launch.mode==="hidden-handoff"),u=n.some(m=>m.platformAccess?.workflow)||d.length>0,l=d.filter(m=>{let E=m.launch.submission;if(!E)return!1;let p=o.find(g=>g.code===m.definition.subject.resourceCode);return[E.create,E.existing].some(g=>g&&Object.values(g.inputs).some(O=>O.source==="field"&&p?.schema.fields.some(y=>y.code===O.fieldCode&&y.type.startsWith("resource-ref.")&&y.source)))}),f={resources:o},A={perspectives:e.perspectives,authz:e.authz},N={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(m=>({code:m.code,method:m.method,path:m.path,capability:m.capability,platformAccess:m.platformAccess||null,...m.browser?{browser:m.browser}:{},ai:m.ai||null}))}};return[...o.some(m=>m.uniqueKeys?.length)?[{code:"data.unique-keys",declaration:o.filter(m=>m.uniqueKeys?.length).map(m=>({code:m.code,uniqueKeys:m.uniqueKeys}))}]:[],...e.data.concurrency?[{code:"data.managed-concurrency",declaration:e.data.concurrency}]:[],...e.data.concurrency?.commands.some(m=>m.mode==="durable")?[{code:"data.managed-concurrency.durable",declaration:e.data.concurrency}]:[],...o.some(m=>m.decimalReservationLifecycle)?[{code:"data.decimal-reservation-lifecycle",declaration:o.filter(m=>m.decimalReservationLifecycle).map(m=>({code:m.code,decimalReservationLifecycle:m.decimalReservationLifecycle}))}]:[],...n.some(m=>m.platformAccess?.decimalReservation)||e.events.subscriptions.some(m=>m.platformAccess?.decimalReservation)?[{code:"data.decimal-reservations",declaration:[...n.filter(m=>m.platformAccess?.decimalReservation).map(m=>({code:m.code,decimalReservation:m.platformAccess.decimalReservation})),...e.events.subscriptions.filter(m=>m.platformAccess?.decimalReservation).map(m=>({subscriptionCode:m.code,decimalReservation:m.platformAccess.decimalReservation}))]}]:[],{code:"application-native-2",declaration:N},{code:"authz.native-batch-explain",declaration:A},{code:"authz.native-management",declaration:A},{code:"deployment.durable-runs",declaration:N.backend},{code:"deployment.platform-executor",declaration:N.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:f},{code:"data.native-golden-crud",declaration:f}]:[],...o.some(ao)?[{code:"data.audit-read-access",declaration:f}]:[],...i?[{code:"directory-v2",declaration:{roles:t.map(m=>({code:m.code,capabilities:m.capabilities.filter(E=>E.endsWith(":directory:read"))})),resources:o.map(m=>({code:m.code,fields:m.schema.fields.filter(E=>["user.single","user.multiple","department.single","department.multiple"].includes(E.type))})),operations:n.filter(m=>m.platformAccess?.directory).map(m=>({code:m.code,directory:m.platformAccess.directory}))}}]:[],...n.some(m=>m.platformAccess?.directory?.mode==="selected-user")?[{code:"directory.selected-user",declaration:n.filter(m=>m.platformAccess?.directory?.mode==="selected-user").map(m=>({code:m.code,directory:m.platformAccess.directory}))}]:[],...c?[{code:"data.managed-files",declaration:{operations:n.filter(m=>m.platformAccess?.managedFiles||m.platformAccess?.managedFileCopies).map(m=>({code:m.code,...m.platformAccess?.managedFiles?{managedFiles:m.platformAccess.managedFiles}:{},...m.platformAccess?.managedFileCopies?{managedFileCopies:m.platformAccess.managedFileCopies}:{}})),subscriptions:e.events.subscriptions.filter(m=>m.platformAccess?.managedFileCopies).map(m=>({code:m.code,managedFileCopies:m.platformAccess.managedFileCopies}))}}]:[],...e.events.subscriptions.some(m=>m.execution)?[{code:"events.native-data-actions",declaration:e.events.subscriptions.filter(m=>m.execution)}]:[],...e.events.capturePolicies?.length?[{code:"events.capture-policy",declaration:e.events.capturePolicies}]:[],...s?[{code:"events-v2",declaration:e.events},{code:"events.durable-receipts",declaration:e.events}]:[],...e.workflows.activations.length?[{code:"workflow-kernel-v2",declaration:e.workflows},{code:"workflow.fresh-command-token",declaration:e.workflows}]:[],...e.workflows.definitions.some(m=>m.definition.instanceCommands!==void 0)?[{code:"workflow.instance-cancellation-policy",declaration:e.workflows.definitions.filter(m=>m.definition.instanceCommands!==void 0)}]:[],...l.length?[{code:"workflow.named-input-sources",declaration:l}]:[],...e.workflows.definitions.some(m=>Object.values(m.definition.nodes).some(E=>E.administration!==void 0||E.operationPolicy!==void 0))?[{code:"workflow.node-administration",declaration:e.workflows.definitions.filter(m=>Object.values(m.definition.nodes).some(E=>E.administration!==void 0||E.operationPolicy!==void 0))}]:[],...e.workflows.definitions.some(m=>Object.values(m.definition.nodes).some(E=>E.kind==="cc"))?[{code:"workflow.automatic-cc",declaration:e.workflows.definitions.filter(m=>Object.values(m.definition.nodes).some(E=>E.kind==="cc"))}]:[],...e.workflows.definitions.some(m=>m.definition.taskPages!==void 0)?["workflow.task-page-submit","workflow.task-private-drafts"].map(m=>({code:m,declaration:e.workflows.definitions.filter(E=>E.definition.taskPages!==void 0)})):[],...a.length?[{code:"workflow.task-managed-files",declaration:a}]:[],...e.workflows.definitions.some(m=>Object.values(m.definition.nodes).some(E=>E.kind==="action"))?[{code:"workflow.durable-business-step",declaration:e.workflows.definitions.filter(m=>Object.values(m.definition.nodes).some(E=>E.kind==="action"))}]:[],...e.workflows.bindings.some(m=>Object.values(m.binding.bindings).some(E=>E.routing!==void 0))?[{code:"workflow.assignment-routing",declaration:e.workflows.bindings.filter(m=>Object.values(m.binding.bindings).some(E=>E.routing!==void 0))}]:[],...u?[{code:"business-process.durable-command",declaration:{operations:n.filter(m=>m.platformAccess?.workflow).map(m=>({code:m.code,workflow:m.platformAccess.workflow})),definitions:d,activations:e.workflows.activations.filter(m=>d.some(E=>E.definition.code===m.workflowCode))}}]:[],...r?[{code:"notification-hub-v2",declaration:{operations:n.filter(m=>m.platformAccess?.notification).map(m=>({code:m.code,notification:m.platformAccess.notification})),subscriptions:e.events.subscriptions.filter(m=>m.platformAccess?.notification).map(m=>({code:m.code,notification:m.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:m,declaration:E})=>({code:m,contractVersion:ti[m],usageDigest:`sha256:${X(E)}`})).sort((m,E)=>m.code===E.code?0:m.code<E.code?-1:1)}function Or(e){let t=new Map,o=new Set(e.resources.map(s=>String(s.code)));for(let[s,c]of S(e.capturePolicies===void 0?[]:e.capturePolicies,"/capturePlan/capturePolicies",100).entries()){let r=`/capturePlan/capturePolicies/${s}`,a=b(c,r);R(a,["resourceCode","mode"],r);let d=J(a.resourceCode,`${r}/resourceCode`);o.has(d)||_("NATIVE_EVENT_CAPTURE_RESOURCE_NOT_FOUND",r,{resourceCode:d}),t.has(d)&&_("NATIVE_EVENT_CAPTURE_POLICY_DUPLICATE",r,{resourceCode:d}),a.mode!=="all"&&a.mode!=="subscribed"&&_("NATIVE_EVENT_CAPTURE_MODE_INVALID",`${r}/mode`),t.set(d,a.mode)}let n=new Map(e.dataPolicies.map((s,c)=>{let r=b(s,`/capturePlan/dataPolicies/${c}`);return[String(r.code),r]})),i=e.subscriptions.map((s,c)=>b(s,`/capturePlan/subscriptions/${c}`));return e.resources.map((s,c)=>{let r=`/capturePlan/resources/${c}`,a=b(s,r),d=J(a.code,`${r}/code`),u=a.schema?b(a.schema,`${r}/schema`):a,l=new Set(S(u.fields||[],`${r}/schema/fields`,500).map((T,h)=>K(b(T,`${r}/schema/fields/${h}`).code,`${r}/schema/fields/${h}/code`))),f=a.dataPolicyCode?V(a.dataPolicyCode,`${r}/dataPolicyCode`):null,A=f?n.get(f):void 0;f&&!A&&_("NATIVE_EVENT_CAPTURE_AUTHZ_POLICY_NOT_FOUND",r,{resourceCode:d,dataPolicyCode:f});let N=new Set;for(let T of A?.rules||[])N.add(String(T.field));if(A?.readExpression)for(let T of xt(A.readExpression,`${r}/readExpression`))N.add(String(T.rule.field));let I=new Set,m=new Set,E=new Set;for(let[T,h]of i.entries()){let D=S(h.eventTypes,`/capturePlan/subscriptions/${T}/eventTypes`,20).map(String);if(!D.some(j=>j.startsWith("openxiangda.data.")))continue;let F=b(h.filter||{},`/capturePlan/subscriptions/${T}/filter`),k=Array.isArray(F.resourceCodes)?F.resourceCodes.map(String):[];if(k.length&&!k.includes(d))continue;for(let j of D)jn.includes(j)&&E.add(j);for(let j of hr(F,`/capturePlan/subscriptions/${T}/filter`))I.add(j);let U=b(h.payload||{},`/capturePlan/subscriptions/${T}/payload`);for(let j of S(U.fields||[],`/capturePlan/subscriptions/${T}/payload/fields`,32))m.add(K(j,`/capturePlan/subscriptions/${T}/payload/fields`))}let p=new Set([...I,...m]),g=new Set([...p,...N]);g.size>ri&&_("NATIVE_EVENT_CAPTURE_FIELDS_LIMIT",r,{resourceCode:d,maximum:ri});for(let T of g)!l.has(T)&&!(N.has(T)&&Ti.has(T))&&_("NATIVE_EVENT_CAPTURE_FIELD_NOT_FOUND",r,{resourceCode:d,field:T});let O=b(a.fieldPolicies||{},`${r}/fieldPolicies`);for(let T of p)O[T]?.mask==="omit"&&_("NATIVE_EVENT_CAPTURE_FIELD_SENSITIVE",r,{resourceCode:d,field:T});let y={resourceCode:d,...t.get(d)==="subscribed"?{capturedEventTypes:[...E].sort()}:{},filterFields:[...I].sort(),projectionFields:[...m].sort(),authorizationFields:[...N].sort(),captureFields:[...g].sort()};return{...y,digest:X(y)}}).sort((s,c)=>s.resourceCode.localeCompare(c.resourceCode))}function hr(e,t){let o=new Set;for(let[c,r]of S(e.changes||[],`${t}/changes`,16).entries()){let a=b(r,`${t}/changes/${c}`);o.add(K(a.field,`${t}/changes/${c}/field`))}let n=b(e.changedFields||{},`${t}/changedFields`);for(let c of["anyOf","allOf","noneOf"])for(let[r,a]of S(n[c]||[],`${t}/changedFields/${c}`,32).entries())o.add(K(a,`${t}/changedFields/${c}/${r}`));let i=0,s=(c,r,a)=>{a>3&&_("NATIVE_EVENT_FILTER_DEPTH_LIMIT",r);let d=b(c,r);if(d.change){let l=b(d.change,`${r}/change`);o.add(K(l.field,`${r}/change/field`)),i+=1;return}if(d.not){s(d.not,`${r}/not`,a+1);return}let u=d.all?"all":d.any?"any":null;u||_("NATIVE_EVENT_FILTER_CONDITION_INVALID",r);for(let[l,f]of S(d[u],`${r}/${u}`,16).entries())s(f,`${r}/${u}/${l}`,a+1)};return e.where&&s(e.where,`${t}/where`,1),i+=Array.isArray(e.changes)?e.changes.length:0,i>16&&_("NATIVE_EVENT_FILTER_ATOM_LIMIT",t),[...o].sort()}function Rr(e,t){R(e,["schemaVersion","compilerContractVersion","appCode","perspectives","authz","backend","data","events","workflows","frontend","runtime"],"/config"),x(e.schemaVersion,Zs,"/config/schemaVersion"),x(e.compilerContractVersion,mt,"/config/compilerContractVersion"),x(e.appCode,t,"/config/appCode"),S(e.perspectives,"/config/perspectives",100);let o=b(e.authz,"/config/authz");R(o,["capabilities","roles","scopeDimensions","scopeSources","roleMembershipSources","relationshipGrantSources","dataPolicies","authorizationTransitions"],"/config/authz",["authenticatedUserRoleCode"]),S(o.capabilities,"/config/authz/capabilities",2e3),S(o.roles,"/config/authz/roles",100),S(o.scopeDimensions,"/config/authz/scopeDimensions",100),S(o.scopeSources,"/config/authz/scopeSources",100),S(o.roleMembershipSources,"/config/authz/roleMembershipSources",100),S(o.relationshipGrantSources,"/config/authz/relationshipGrantSources",100),S(o.dataPolicies,"/config/authz/dataPolicies",100),S(o.authorizationTransitions,"/config/authz/authorizationTransitions",100);let n=b(e.backend,"/config/backend");R(n,["secrets","operations"],"/config/backend"),S(n.secrets,"/config/backend/secrets",100),S(n.operations,"/config/backend/operations",500),ca(n.secrets);let i=b(e.data,"/config/data");R(i,["resources"],"/config/data",["resourceDetailRoutes","subjectReadSurfaces","concurrency"]),S(i.resources,"/config/data/resources",100),i.subjectReadSurfaces!==void 0&&S(i.subjectReadSurfaces,"/config/data/subjectReadSurfaces",Y.subjectReadSurfaces),i.resourceDetailRoutes!==void 0&&S(i.resourceDetailRoutes,"/config/data/resourceDetailRoutes",100);let s=b(e.events,"/config/events");R(s,["schemas","subscriptions","timers","dateTriggers"],"/config/events",["capturePolicies"]),S(s.schemas,"/config/events/schemas",100),S(s.subscriptions,"/config/events/subscriptions",100),S(s.timers,"/config/events/timers",100),S(s.dateTriggers,"/config/events/dateTriggers",100);let c=b(e.workflows,"/config/workflows");R(c,["definitions","bindings","activations","providers","editableParameters"],"/config/workflows"),S(c.definitions,"/config/workflows/definitions",100),S(c.bindings,"/config/workflows/bindings",100),S(c.activations,"/config/workflows/activations",100),S(c.providers,"/config/workflows/providers",100),S(c.editableParameters,"/config/workflows/editableParameters",100);let r=b(e.frontend,"/config/frontend");R(r,["routes","user","admin","devicePolicy"],"/config/frontend",["authentication","publicAccess"]),S(r.routes,"/config/frontend/routes",500);let a=b(r.user,"/config/frontend/user");R(a,["applicationTodoCenter"],"/config/frontend/user"),Xe(a.applicationTodoCenter,"/config/frontend/user/applicationTodoCenter"),Gn(r.devicePolicy,"/config/frontend/devicePolicy"),Object.prototype.hasOwnProperty.call(r,"authentication")&&hi(r.authentication,r.routes,e,"/config/frontend/authentication"),Object.prototype.hasOwnProperty.call(r,"publicAccess")&&Br(r.publicAccess,e,"/config/frontend/publicAccess");let d=b(r.admin,"/config/frontend/admin");R(d,["navigation"],"/config/frontend/admin",["access"]),d.access!==void 0&&Kt(d.access,"/config/frontend/admin/access",e.appCode),Jr(d.navigation,"/config/frontend/admin/navigation");let u=b(e.runtime,"/config/runtime");R(u,["protocolCapabilities","health"],"/config/runtime"),v(u.protocolCapabilities,"/config/runtime/protocolCapabilities",100),R(b(u.health,"/config/runtime/health"),["livePath","readyPath","versionPath"],"/config/runtime/health"),x(u.health.livePath,"/__platform/health","/config/runtime/health/livePath"),x(u.health.readyPath,"/__platform/ready","/config/runtime/health/readyPath"),x(u.health.versionPath,"/__platform/version","/config/runtime/health/versionPath")}function Cr(e,t,o){R(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"]),x(e.schemaVersion,yi,"/contracts/schemaVersion"),x(e.compilerContractVersion,mt,"/contracts/compilerContractVersion"),C(e.generatorVersion,"/contracts/generatorVersion",128),x(e.appCode,t,"/contracts/appCode"),x(e.configDigest,o,"/contracts/configDigest"),S(e.perspectives,"/contracts/perspectives",Y.perspectives),S(e.resources,"/contracts/resources",Y.resources),e.subjectReadSurfaces!==void 0&&S(e.subjectReadSurfaces,"/contracts/subjectReadSurfaces",Y.subjectReadSurfaces),S(e.capabilities,"/contracts/capabilities",Y.capabilities),S(e.operations,"/contracts/operations",Y.operations),S(e.eventConsumers,"/contracts/eventConsumers",Y.eventConsumers),S(e.eventProducers,"/contracts/eventProducers",Y.eventProducers),S(e.eventSchemas,"/contracts/eventSchemas",Y.eventSchemas),b(e.eventHandlerManifest,"/contracts/eventHandlerManifest"),v(e.eventTypes,"/contracts/eventTypes",Y.eventTypes),S(e.workflows,"/contracts/workflows",Y.workflows),S(e.routes,"/contracts/routes",Y.routes),Object.prototype.hasOwnProperty.call(e,"authentication")&&Mr(e.authentication,"/contracts/authentication"),Object.prototype.hasOwnProperty.call(e,"publicAccess")&&Kr(e.publicAccess,"/contracts/publicAccess"),Object.prototype.hasOwnProperty.call(e,"adminAccess")&&Kt(e.adminAccess,"/contracts/adminAccess",t),Zr(e.routeManifest,"/contracts/routeManifest",t),Hr(e.adminPages,"/contracts/adminPages"),Xr(e.adminNavigation,"/contracts/adminNavigation")}function Sr(e,t,o){let n=$r(e);ia(e,n),ra(e),sa(e),da(e);let i=e.events.schemas.map((p,g)=>{let O=`/config/events/schemas/${g}`,y=b(p,O),T=C(y.eventType,`${O}/eventType`,255);return T.startsWith("openxiangda.")&&_("NATIVE_EVENT_SCHEMA_RESERVED",`${O}/eventType`,{eventType:T}),x(y.schemaDigest,X(b(y.jsonSchema,`${O}/jsonSchema`)),`${O}/schemaDigest`),y}),s=new Set([...jn,...Mn,...i.map(p=>String(p.eventType))]),c=new Map(e.data.resources.map(p=>[String(p.code),new Map(p.schema.fields.map(g=>[String(g.code),String(g.type)]))])),r=Z(e.events.subscriptions.map((p,g)=>{let O=`/config/events/subscriptions/${g}`,y=b(p,O),T=v(y.eventTypes,`${O}/eventTypes`,20);T.forEach((k,U)=>{s.has(k)||_("NATIVE_EVENT_TYPE_NOT_REGISTERED",`${O}/eventTypes/${U}`,{eventType:k})});let h=vo(y,e.data.resources,O),D=Dr(y.delivery,T,`${O}/delivery`),F=wr(y.platformAccess,`${O}/platformAccess`,c,e,y);return{code:V(y.code,`${O}/code`),endpointPath:_e(y.endpointPath,`${O}/endpointPath`),eventTypes:T,filter:b(y.filter,`${O}/filter`),payload:h?.payload||b(y.payload,`${O}/payload`),...h?{execution:h.execution}:{},...F?{platformAccess:F}:{},delivery:D}}),p=>p.code),a=new Map(i.map(p=>[String(p.eventType),String(p.dataSchemaVersion)])),d=Z([...e.data.resources.flatMap(p=>jn.map(g=>({code:`data:${p.code}:${g}`,source:"data",eventType:g,dataSchemaVersion:"2.0.0",resourceCode:p.code}))),...i.map(p=>({code:`app:${p.eventType}`,source:"app",eventType:p.eventType,dataSchemaVersion:p.dataSchemaVersion})),...e.events.timers.map(p=>({code:p.code,source:"timer",eventType:p.eventType,dataSchemaVersion:a.get(String(p.eventType))||"2.0.0"})),...e.events.dateTriggers.map(p=>({code:p.code,source:"date",eventType:p.eventType,dataSchemaVersion:a.get(String(p.eventType))||"2.0.0",resourceCode:p.resourceCode,field:p.field})),...e.workflows.activations.length?Mn.filter(p=>!Mo.includes(p)||e.workflows.definitions.some(g=>Object.values(g.definition.nodes).some(O=>O.kind==="action"))).map(p=>({code:`workflow:${p}`,source:"workflow",eventType:p,dataSchemaVersion:"2.0.0"})):[]],p=>`${p.source}:${p.code}:${p.eventType}`),u=W([...r.flatMap(p=>p.eventTypes),...d.map(p=>String(p.eventType))]);Yr(e);let l=Si(e),f;try{f=No(e.data.concurrency,e.data.resources,n)}catch(p){throw p instanceof nt&&_(p.code,p.pointer,{reason:p.reason}),p}f?.commands.some(p=>p.mode==="durable")&&e.backend?.enabled===!1&&_("NATIVE_MANAGED_CONCURRENCY_INVALID","/data/concurrency",{reason:"durable commands require backend runtime"});let A=kr(e,n),N=Oi(e),I=e.workflows.definitions.map(p=>p.definition),m=hn(I),E=Ko(I,r,!0);E.length&&_(E[0],"/config/events/subscriptions");try{bo(e.data.resources,N)}catch(p){throw p instanceof qe&&_(p.code,p.pointer,{reason:p.reason}),p}return{schemaVersion:yi,compilerContractVersion:mt,generatorVersion:o,appCode:e.appCode,configDigest:t,perspectives:e.perspectives,resources:Vr(e),...A.length?{subjectReadSurfaces:A}:{},...f?{concurrency:f}:{},capabilities:Z(n,p=>p.code),operations:N,eventConsumers:r,eventProducers:d,eventSchemas:i,eventHandlerManifest:{schemaVersion:yr,appCode:e.appCode,handlers:r.filter(p=>!p.execution).map(p=>({code:p.code,endpointPath:p.endpointPath,eventTypes:p.eventTypes,dataSchemaVersions:W(p.eventTypes.map(g=>g.startsWith("openxiangda.")?"2.0.0":a.get(g)||"2.0.0")),maxBodyBytes:65536,receiptProtocolVersion:2,...m[p.code]?{workflowStep:m[p.code]}:{}}))},eventTypes:u,workflows:$i(e),routes:Bt(e),...Object.prototype.hasOwnProperty.call(e.frontend,"authentication")?{authentication:Wr(e)}:{},...Object.prototype.hasOwnProperty.call(e.frontend,"publicAccess")?{publicAccess:Gr(e)}:{},...e.frontend.admin.access?{adminAccess:e.frontend.admin.access}:{},routeManifest:na(e),adminPages:l,adminNavigation:qr(e)}}function wr(e,t,o,n,i){if(e===void 0)return;let s=b(e,t);R(s,["notification","managedFileCopies","decimalReservation"],t,!0);let c={};if(s.decimalReservation!==void 0)try{c.decimalReservation=ko(s.decimalReservation,Fo(n,i))}catch{_("NATIVE_EVENT_DECIMAL_RESERVATION_INVALID",`${t}/decimalReservation`)}if(s.notification!==void 0){let r=b(s.notification,`${t}/notification`);R(r,["mode"],`${t}/notification`),x(r.mode,"business-standard",`${t}/notification/mode`),c.notification={mode:"business-standard"}}if(s.managedFileCopies!==void 0){let r=S(s.managedFileCopies,`${t}/managedFileCopies`,16);r.length||_("NATIVE_EVENT_MANAGED_FILE_COPIES_REQUIRED",`${t}/managedFileCopies`);let a=new Set;c.managedFileCopies=Z(r.map((d,u)=>{let l=`${t}/managedFileCopies/${u}`,f=b(d,l);R(f,["mode","sourceResourceCode","sourceFieldCodes","targetResourceCode","targetFieldCodes"],l),x(f.mode,"copy",`${l}/mode`);let A=J(f.sourceResourceCode,`${l}/sourceResourceCode`),N=J(f.targetResourceCode,`${l}/targetResourceCode`),I=o.get(A),m=o.get(N);(!I||!m)&&_("NATIVE_EVENT_MANAGED_FILE_COPY_RESOURCE_INVALID",l);let E=v(f.sourceFieldCodes,`${l}/sourceFieldCodes`,16),p=v(f.targetFieldCodes,`${l}/targetFieldCodes`,16);(!E.length||E.length!==p.length)&&_("NATIVE_EVENT_MANAGED_FILE_COPY_FIELDS_INVALID",l),E.forEach((O,y)=>{let T=I.get(O),h=m.get(p[y]);(!["file","image"].includes(String(T))||T!==h)&&_("NATIVE_EVENT_MANAGED_FILE_COPY_FIELD_INVALID",`${l}/sourceFieldCodes/${y}`)});let g=`${A}:${E.join(",")}=>${N}:${p.join(",")}`;return a.has(g)&&_("NATIVE_EVENT_MANAGED_FILE_COPY_DUPLICATE",l),a.add(g),{mode:"copy",sourceResourceCode:A,sourceFieldCodes:W(E),targetResourceCode:N,targetFieldCodes:W(p)}}),d=>`${d.sourceResourceCode}:${d.sourceFieldCodes.join(",")}=>${d.targetResourceCode}:${d.targetFieldCodes.join(",")}`)}return Object.keys(c).length||_("NATIVE_EVENT_PLATFORM_ACCESS_EMPTY",t),c}function Dr(e,t,o){let n=b(e,o);R(n,["timeoutMs","maxAttempts","initialBackoffMs","maxBackoffMs","ordering","concurrency"],o),te(n.timeoutMs,`${o}/timeoutMs`,1e3,3e4),te(n.maxAttempts,`${o}/maxAttempts`,1,12);let i=te(n.initialBackoffMs,`${o}/initialBackoffMs`,1e3,3e5);te(n.maxBackoffMs,`${o}/maxBackoffMs`,i,18e5),te(n.concurrency,`${o}/concurrency`,1,50);let s=C(n.ordering,`${o}/ordering`,32);return["none","record","workflow-instance"].includes(s)||_("NATIVE_EVENT_DELIVERY_ORDERING_INVALID",`${o}/ordering`),s==="workflow-instance"&&t.some(c=>!br.has(c))&&_("NATIVE_EVENT_WORKFLOW_ORDERING_REQUIRES_WORKFLOW_FACTS",`${o}/ordering`),n}function $r(e){let t=new Map;for(let o of Fi(e.appCode))t.set(o.code,o);for(let[o,n]of e.authz.capabilities.entries()){let i=`/config/authz/capabilities/${o}`,s=b(n,i);R(s,["code","kind","name","description"],i,!0);let c=Re(s.code,`${i}/code`,e.appCode);t.has(c)&&_("NATIVE_CAPABILITY_DUPLICATE",`${i}/code`),["backend","ui"].includes(s.kind)||_("NATIVE_CAPABILITY_KIND_INVALID",`${i}/kind`);let r={code:c,kind:s.kind,name:C(s.name,`${i}/name`,255),source:"explicit",...s.description===void 0?{}:{description:Jn(s.description,`${i}/description`,2e3)}};t.set(c,r)}for(let[o,n]of e.data.resources.entries()){let i=`/config/data/resources/${o}`,s=Me(n,i,e.appCode),c={read:`\u8BFB\u53D6${s.name}`,create:`\u65B0\u5EFA${s.name}`,update:`\u66F4\u65B0${s.name}`,delete:`\u5220\u9664${s.name}`};for(let r of["read","create","update","delete"]){let a=Re(s.capabilities[r],`${i}/capabilities/${r}`,e.appCode);t.has(a)&&_("NATIVE_CAPABILITY_DUPLICATE",`${i}/capabilities/${r}`),t.set(a,{code:a,kind:"data",name:c[r],source:"data"})}for(let[r,a]of Object.entries(s.fieldPolicies)){if(Ze(r))continue;let d=b(a,`${i}/fieldPolicies/${r}`);for(let u of["read","create","update"])if(Array.isArray(d[u]))for(let l of v(d[u],`${i}/fieldPolicies/${r}/${u}`,2e3))Re(l,`${i}/fieldPolicies/${r}/${u}`,e.appCode),!t.has(l)&&t.set(l,{code:l,kind:"data",name:`${s.name}.${r}.${u}`,source:"data"})}}return[...t.values()]}function Vr(e){let t=Fr(e);return Z(e.data.resources.map((o,n)=>{let i=Me(o,`/config/data/resources/${n}`,e.appCode),s=t.get(i.code);return{code:i.code,schemaDigest:X(i.schema),fields:Z(i.schema.fields.map(c=>({code:c.code,type:c.type})),c=>c.code),...s?{detailRouteCode:s}:{}}}),o=>o.code)}function kr(e,t){if(e.data.subjectReadSurfaces===void 0)return[];let o=S(e.data.subjectReadSurfaces,"/config/data/subjectReadSurfaces",Y.subjectReadSurfaces),n=new Set(t.map(c=>String(c.code))),i=new Map(e.data.resources.map((c,r)=>{let a=`/config/data/resources/${r}`,d=Me(c,a,e.appCode);return[String(d.code),{resource:d,fields:new Map(S(b(d.schema,`${a}/schema`).fields,`${a}/schema/fields`,500).map(u=>{let l=b(u,`${a}/schema/fields`);return[String(l.code),l]}))}]})),s=new Set;return Z(o.map((c,r)=>{let a=`/config/data/subjectReadSurfaces/${r}`,d=b(c,a);R(d,["code","name","capability","subject","relations"],a);let u=V(d.code,`${a}/code`);s.has(u)&&_("NATIVE_SUBJECT_READ_SURFACE_CODE_DUPLICATE",`${a}/code`),s.add(u);let l=Re(d.capability,`${a}/capability`,e.appCode);n.has(l)||_("NATIVE_SUBJECT_READ_SURFACE_CAPABILITY_NOT_DECLARED",`${a}/capability`);let f=b(d.subject,`${a}/subject`);R(f,["resourceCode","fields"],`${a}/subject`);let A=J(f.resourceCode,`${a}/subject/resourceCode`),N=i.get(A);N||_("NATIVE_SUBJECT_READ_SURFACE_RESOURCE_NOT_DECLARED",`${a}/subject/resourceCode`);let I=v(f.fields,`${a}/subject/fields`,100).map((O,y)=>K(O,`${a}/subject/fields/${y}`));I.length||_("NATIVE_SUBJECT_READ_SURFACE_FIELDS_REQUIRED",`${a}/subject/fields`);for(let[O,y]of I.entries()){let T=N.fields.get(y);(!T||T.type==="subtable")&&_("NATIVE_SUBJECT_READ_SURFACE_FIELD_INVALID",`${a}/subject/fields/${O}`)}let m=S(d.relations,`${a}/relations`,8);m.length||_("NATIVE_SUBJECT_READ_SURFACE_RELATIONS_REQUIRED",`${a}/relations`);let E=new Set,p=0,g=Z(m.map((O,y)=>{let T=`${a}/relations/${y}`,h=b(O,T);R(h,["code","resourceCode","foreignKeyField","fields","limit"],T,["order"]);let D=V(h.code,`${T}/code`);E.has(D)&&_("NATIVE_SUBJECT_READ_SURFACE_RELATION_CODE_DUPLICATE",`${T}/code`),E.add(D);let F=J(h.resourceCode,`${T}/resourceCode`),k=i.get(F);k||_("NATIVE_SUBJECT_READ_SURFACE_RESOURCE_NOT_DECLARED",`${T}/resourceCode`);let U=K(h.foreignKeyField,`${T}/foreignKeyField`),j=k.fields.get(U),ie=b(j?.source||{},`${T}/foreignKeyField/source`);(!j||!["uuid","resource-ref.single"].includes(String(j.type))||j.type==="resource-ref.single"&&(ie.kind!=="resource"||ie.resourceCode!==A))&&_("NATIVE_SUBJECT_READ_SURFACE_RELATION_INVALID",`${T}/foreignKeyField`);let ge=v(h.fields,`${T}/fields`,100).map((ae,$)=>K(ae,`${T}/fields/${$}`));ge.length||_("NATIVE_SUBJECT_READ_SURFACE_FIELDS_REQUIRED",`${T}/fields`);for(let[ae,$]of ge.entries()){let M=k.fields.get($);(!M||M.type==="subtable")&&_("NATIVE_SUBJECT_READ_SURFACE_FIELD_INVALID",`${T}/fields/${ae}`)}let H=S(h.order||[],`${T}/order`,10).map((ae,$)=>{let M=`${T}/order/${$}`,P=b(ae,M);R(P,["field","direction"],M);let G=K(P.field,`${M}/field`),q=k.fields.get(G);return(!Ti.has(G)&&!q||q?.type==="subtable"||q&&!tt(q.type))&&_("NATIVE_SUBJECT_READ_SURFACE_ORDER_FIELD_INVALID",`${M}/field`),["asc","desc"].includes(String(P.direction))||_("NATIVE_SUBJECT_READ_SURFACE_ORDER_DIRECTION_INVALID",`${M}/direction`),{field:G,direction:P.direction}}),be=te(h.limit,`${T}/limit`,1,100);return p+=be,{code:D,resourceCode:F,foreignKeyField:U,fields:W(ge),...H.length?{order:H}:{},limit:be}}),O=>O.code);return p>400&&_("NATIVE_SUBJECT_READ_SURFACE_ROW_LIMIT_EXCEEDED",`${a}/relations`),{code:u,name:C(d.name,`${a}/name`,255),capability:l,subject:{resourceCode:A,fields:W(I)},relations:g}}),c=>c.code)}function Fr(e){let t=e.data.resourceDetailRoutes===void 0?[]:S(e.data.resourceDetailRoutes,"/config/data/resourceDetailRoutes",100),o=new Map(e.data.resources.map((s,c)=>{let r=`/config/data/resources/${c}`,a=Me(s,r,e.appCode);return[a.code,a]})),n=new Map(Bt(e).map(s=>[String(s.code),s])),i=new Map;for(let[s,c]of t.entries()){let r=`/config/data/resourceDetailRoutes/${s}`,a=b(c,r);R(a,["resourceCode","desktop","mobile"],r);let d=J(a.resourceCode,`${r}/resourceCode`);i.has(d)&&_("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_DUPLICATE",`${r}/resourceCode`);let u=o.get(d);u||_("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_RESOURCE_MISSING",`${r}/resourceCode`);let l=V(a.desktop,`${r}/desktop`),f=V(a.mobile,`${r}/mobile`);l===f&&_("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_INVALID",r);let A=String(u.capabilities.read);for(let[N,I]of[["desktop",l],["mobile",f]]){let m=`${r}/${N}`,E=n.get(I);E||_("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_REFERENCE_MISSING",m),E.surface!=="user"&&_("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_SURFACE_INVALID",m);let p=_e(E.path,`${m}/path`),g=[...p.matchAll(/:([A-Za-z][A-Za-z0-9_]*)/g)],O=N==="mobile"?!p.startsWith("/m/"):p==="/m"||p.startsWith("/m/");(p.includes("*")||p.includes("?")||p.includes("#")||p.split("/").includes("..")||g.length!==1||O)&&_("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_PATH_INVALID",m);let y=Array.isArray(E.access?.allOf)?E.access.allOf:[];E.capability!==A&&!y.includes(A)&&_("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_CAPABILITY_INVALID",m)}i.set(d,{desktop:l,mobile:f})}return i}function Oi(e){let t=new Map(e.data.resources.map((c,r)=>{let a=`/config/data/resources/${r}`,d=Me(c,a,e.appCode);return[d.code,new Map(d.schema.fields.map(u=>[String(u.code),u]))]})),o=new Map(e.data.resources.map((c,r)=>{let a=`/config/data/resources/${r}`,d=Me(c,a,e.appCode);return[d.code,new Map(d.schema.fields.map(u=>[String(u.code),String(u.type)]))]})),n=new Set(o.keys()),i=new Set(e.workflows.activations.map((c,r)=>Gt(b(c,`/config/workflows/activations/${r}`).workflowCode,`/config/workflows/activations/${r}/workflowCode`))),s=new Map;return Z(e.backend.operations.map((c,r)=>{let a=`/config/backend/operations/${r}`,d=b(c,a);R(d,["code","method","path","capability","requestSchema","responseSchema","description","platformAccess","browser","ai"],a,!0);let u=C(d.method,`${a}/method`,16);["GET","POST","PUT","PATCH","DELETE"].includes(u)||_("NATIVE_OPERATION_METHOD_INVALID",`${a}/method`);let l=V(d.code,`${a}/code`);xr(d.ai,a,l,u,n);let f=Lr(d.platformAccess,`${a}/platformAccess`,o,t,i,new Set(e.authz.roles.map(N=>String(N.code))));if(f?.decimalReservation){let N=f.decimalReservation,I=String(N.resourceCode),m=JSON.stringify([N.amountFieldCode,N.currencyFieldCode,N.relationFieldCode,N.parentFieldCode,N.rootFieldCode,N.statusFieldCode,N.parentRelationValue,N.childRelationValue]),E=s.get(I);E&&E!==m&&_("NATIVE_DECIMAL_RESERVATION_MAPPING_CONFLICT",`${a}/platformAccess/decimalReservation`),s.set(I,m)}let A=vr(d.browser,`${a}/browser`,u,d.requestSchema,d.responseSchema,o,t,e.data.subjectReadSurfaces||[]);return{code:l,method:u,path:_e(d.path,`${a}/path`),requiredCapability:Re(d.capability,`${a}/capability`,e.appCode),requestSchemaDigest:X(b(d.requestSchema,`${a}/requestSchema`)),responseSchemaDigest:X(b(d.responseSchema,`${a}/responseSchema`)),...d.description===void 0?{}:{description:Jn(d.description,`${a}/description`,2e3)},...f?{platformAccess:f}:{},...A?{browser:A}:{}}}),c=>c.code)}function vr(e,t,o,n,i,s,c,r){if(e===void 0)return null;let a=b(e,t);R(a,["exposure","behavior","idempotency","subject"],t,["refreshTargets","fileIntent"]),x(a.exposure,"authenticated",`${t}/exposure`);let d=C(a.behavior,`${t}/behavior`,32);["read","controlled"].includes(d)||_("NATIVE_OPERATION_BROWSER_BEHAVIOR_INVALID",`${t}/behavior`);let u=C(a.idempotency,`${t}/idempotency`,32);(!["none","required"].includes(u)||d==="controlled"&&u!=="required"||d==="read"&&u!=="none")&&_("NATIVE_OPERATION_BROWSER_IDEMPOTENCY_INVALID",`${t}/idempotency`);let l=b(a.subject,`${t}/subject`);R(l,["resourceCode","inputField"],`${t}/subject`);let f=J(l.resourceCode,`${t}/subject/resourceCode`);s.has(f)||_("NATIVE_OPERATION_BROWSER_SUBJECT_RESOURCE_NOT_DECLARED",`${t}/subject/resourceCode`);let A=K(l.inputField,`${t}/subject/inputField`),N=b(n,`${t}/requestSchema`),I=b(i,`${t}/responseSchema`);(N.type!=="object"||N.additionalProperties!==!1||I.type!=="object"||I.additionalProperties!==!1)&&_("NATIVE_OPERATION_BROWSER_SCHEMA_ROOT_INVALID",`${t}/requestSchema`);let m=b(N.properties,`${t}/requestSchema/properties`),E=new Set(N.required===void 0?[]:v(N.required,`${t}/requestSchema/required`,200));(!(A in m)||!E.has(A))&&_("NATIVE_OPERATION_BROWSER_SUBJECT_INPUT_INVALID",`${t}/subject/inputField`);let p=b(m[A],`${t}/requestSchema/properties/${A}`);(p.type!=="string"||p.format!=="uuid")&&_("NATIVE_OPERATION_BROWSER_SUBJECT_INPUT_INVALID",`${t}/subject/inputField`);let g=new Map((Array.isArray(r)?r:[]).map((D,F)=>{let k=b(D,`/config/data/subjectReadSurfaces/${F}`);return[String(k.code),String(b(k.subject,`/config/data/subjectReadSurfaces/${F}/subject`).resourceCode)]})),O=a.refreshTargets===void 0?[]:S(a.refreshTargets,`${t}/refreshTargets`,16),y=new Set,T=Z(O.map((D,F)=>{let k=`${t}/refreshTargets/${F}`,U=b(D,k);R(U,["kind","code"],k),x(U.kind,"subject-surface",`${k}/kind`);let j=V(U.code,`${k}/code`);return(y.has(j)||!g.has(j)||g.get(j)!==f)&&_("NATIVE_OPERATION_BROWSER_REFRESH_TARGET_INVALID",`${k}/code`),y.add(j),{kind:"subject-surface",code:j}}),D=>`${D.kind}:${D.code}`),h=Pr(a.fileIntent,`${t}/fileIntent`,o,d,u,f,m,E,c);return{exposure:"authenticated",behavior:d,idempotency:u,subject:{resourceCode:f,inputField:A},...T.length?{refreshTargets:T}:{},...h?{fileIntent:h}:{}}}function Pr(e,t,o,n,i,s,c,r,a){if(e===void 0)return null;let d=b(e,t);R(d,["recordResourceCode","recordIdInputField","relationField","fileNameField","contentTypeField","sizeField","purposes","maxTtlSeconds","maxBytes"],t),(o!=="GET"||n!=="read"||i!=="none")&&_("NATIVE_OPERATION_FILE_INTENT_BEHAVIOR_INVALID",t);let u=J(d.recordResourceCode,`${t}/recordResourceCode`),l=a.get(u);l||_("NATIVE_OPERATION_FILE_INTENT_RESOURCE_NOT_DECLARED",`${t}/recordResourceCode`);let f=K(d.recordIdInputField,`${t}/recordIdInputField`),A=b(c[f],`${t}/recordIdInputField`);(!r.has(f)||A.type!=="string"||A.format!=="uuid")&&_("NATIVE_OPERATION_FILE_INTENT_RECORD_INPUT_INVALID",`${t}/recordIdInputField`);let N=K(d.relationField,`${t}/relationField`),I=l.get(N);(!I||!["uuid","resource-ref.single"].includes(String(I.type))||String(I.type)==="resource-ref.single"&&(String(b(I.source,`${t}/relationField`).kind||"")!=="resource"||String(b(I.source,`${t}/relationField`).resourceCode||"")!==s))&&_("NATIVE_OPERATION_FILE_INTENT_RELATION_INVALID",`${t}/relationField`);let m=[["fileNameField",["text.short","text.long"]],["contentTypeField",["text.short","text.long"]],["sizeField",["number.integer"]]],E={};for(let[y,T]of m){let h=K(d[y],`${t}/${y}`);T.includes(String(l.get(h)?.type))||_("NATIVE_OPERATION_FILE_INTENT_METADATA_INVALID",`${t}/${y}`),E[y]=h}let p=Z(v(d.purposes,`${t}/purposes`,2),y=>y);(!p.length||p.some(y=>!["preview","download"].includes(y)))&&_("NATIVE_OPERATION_FILE_INTENT_PURPOSE_INVALID",`${t}/purposes`);let g=Number(d.maxTtlSeconds);(!Number.isSafeInteger(g)||g<1||g>300)&&_("NATIVE_OPERATION_FILE_INTENT_TTL_INVALID",`${t}/maxTtlSeconds`);let O=Number(d.maxBytes);return(!Number.isSafeInteger(O)||O<1||O>104857600)&&_("NATIVE_OPERATION_FILE_INTENT_SIZE_INVALID",`${t}/maxBytes`),{recordResourceCode:u,recordIdInputField:f,relationField:N,fileNameField:E.fileNameField,contentTypeField:E.contentTypeField,sizeField:E.sizeField,purposes:p,maxTtlSeconds:g,maxBytes:O}}function Lr(e,t,o,n,i,s){if(e===void 0)return null;let c=b(e,t);R(c,["directory","managedFiles","managedFileCopies","notification","workflow","roleAssertions","decimalReservation"],t,!0),Object.keys(c).length===0&&_("NATIVE_OPERATION_PLATFORM_ACCESS_EMPTY",t);let r={};if(c.roleAssertions!==void 0){let a=b(c.roleAssertions,`${t}/roleAssertions`);R(a,["roleCodes"],`${t}/roleAssertions`);let d=v(a.roleCodes,`${t}/roleAssertions/roleCodes`,20);d.length||_("NATIVE_OPERATION_ROLE_ASSERTIONS_REQUIRED",`${t}/roleAssertions/roleCodes`),d.forEach((u,l)=>{s.has(u)||_("NATIVE_ROLE_REFERENCE_MISSING",`${t}/roleAssertions/roleCodes/${l}`)}),r.roleAssertions={roleCodes:W(d)}}if(c.directory!==void 0){let a=b(c.directory,`${t}/directory`);R(a,["mode","fields"],`${t}/directory`),["current-initiator","selected-user"].includes(String(a.mode))||_("NATIVE_OPERATION_DIRECTORY_MODE_INVALID",`${t}/directory/mode`);let d=new Set(["displayName","employeeNumber","primaryDepartment","departments"]),u=v(a.fields,`${t}/directory/fields`,4);(!u.length||u.some(l=>!d.has(l)))&&_("NATIVE_OPERATION_DIRECTORY_FIELDS_INVALID",`${t}/directory/fields`),r.directory={mode:String(a.mode),fields:W(u)}}if(c.managedFiles!==void 0){let a=S(c.managedFiles,`${t}/managedFiles`,16);a.length||_("NATIVE_OPERATION_MANAGED_FILES_REQUIRED",`${t}/managedFiles`);let d=new Set;r.managedFiles=Z(a.map((u,l)=>{let f=`${t}/managedFiles/${l}`,A=b(u,f);R(A,["resourceCode","fieldCodes","intents"],f);let N=J(A.resourceCode,`${f}/resourceCode`);(d.has(N)||!o.has(N))&&_("NATIVE_OPERATION_MANAGED_FILE_RESOURCE_INVALID",`${f}/resourceCode`),d.add(N);let I=v(A.fieldCodes,`${f}/fieldCodes`,16);(!I.length||I.some(E=>!["file","image","signature","text.rich"].includes(String(o.get(N)?.get(E)||""))))&&_("NATIVE_OPERATION_MANAGED_FILE_FIELD_INVALID",`${f}/fieldCodes`);let m=v(A.intents,`${f}/intents`,2);return(!m.length||m.some(E=>!["create","update"].includes(E)))&&_("NATIVE_OPERATION_MANAGED_FILE_INTENT_INVALID",`${f}/intents`),{resourceCode:N,fieldCodes:W(I),intents:W(m)}}),u=>u.resourceCode)}if(c.managedFileCopies!==void 0){let a=S(c.managedFileCopies,`${t}/managedFileCopies`,16);a.length||_("NATIVE_OPERATION_MANAGED_FILE_COPIES_REQUIRED",`${t}/managedFileCopies`);let d=new Set;r.managedFileCopies=Z(a.map((u,l)=>{let f=`${t}/managedFileCopies/${l}`,A=b(u,f);R(A,["mode","sourceResourceCode","sourceFieldCodes","targetResourceCode","targetFieldCodes"],f),x(A.mode,"copy",`${f}/mode`);let N=J(A.sourceResourceCode,`${f}/sourceResourceCode`),I=J(A.targetResourceCode,`${f}/targetResourceCode`),m=o.get(N),E=o.get(I);(!m||!E)&&_("NATIVE_OPERATION_MANAGED_FILE_COPY_RESOURCE_INVALID",f);let p=v(A.sourceFieldCodes,`${f}/sourceFieldCodes`,16),g=v(A.targetFieldCodes,`${f}/targetFieldCodes`,16);(!p.length||p.length!==g.length)&&_("NATIVE_OPERATION_MANAGED_FILE_COPY_FIELDS_INVALID",f),p.forEach((y,T)=>{let h=m.get(y),D=E.get(g[T]);(!["file","image"].includes(String(h))||h!==D)&&_("NATIVE_OPERATION_MANAGED_FILE_COPY_FIELD_INVALID",`${f}/sourceFieldCodes/${T}`)});let O=`${N}:${p.join(",")}=>${I}:${g.join(",")}`;return d.has(O)&&_("NATIVE_OPERATION_MANAGED_FILE_COPY_DUPLICATE",f),d.add(O),{mode:"copy",sourceResourceCode:N,sourceFieldCodes:W(p),targetResourceCode:I,targetFieldCodes:W(g)}}),u=>`${u.sourceResourceCode}:${u.sourceFieldCodes.join(",")}=>${u.targetResourceCode}:${u.targetFieldCodes.join(",")}`)}if(c.notification!==void 0){let a=b(c.notification,`${t}/notification`);R(a,["mode"],`${t}/notification`),a.mode!=="business-standard"&&_("NATIVE_OPERATION_NOTIFICATION_MODE_INVALID",`${t}/notification/mode`),r.notification={mode:"business-standard"}}if(c.workflow!==void 0){let a=b(c.workflow,`${t}/workflow`);R(a,["codes"],`${t}/workflow`);let d=v(a.codes,`${t}/workflow/codes`,16);(!d.length||d.some(u=>!i.has(u)))&&_("NATIVE_OPERATION_WORKFLOW_CODE_INVALID",`${t}/workflow/codes`),r.workflow={codes:W(d)}}if(c.decimalReservation!==void 0){let a=`${t}/decimalReservation`,d=b(c.decimalReservation,a);R(d,["mode","resourceCode","amountFieldCode","currencyFieldCode","relationFieldCode","parentFieldCode","rootFieldCode","statusFieldCode","parentRelationValue","childRelationValue","eligibleParentStatuses","eligibleChildStatuses"],a);let u=C(d.mode,`${a}/mode`,16);["reserve","commit","release"].includes(u)||_("NATIVE_DECIMAL_RESERVATION_MODE_INVALID",`${a}/mode`);let l=J(d.resourceCode,`${a}/resourceCode`),f=n.get(l);f||_("NATIVE_DECIMAL_RESERVATION_RESOURCE_MISSING",`${a}/resourceCode`);let N=Object.fromEntries(["amountFieldCode","currencyFieldCode","relationFieldCode","parentFieldCode","rootFieldCode","statusFieldCode"].map(y=>[y,K(d[y],`${a}/${y}`)])),I=y=>f.get(N[y]),m=y=>new Set((I(y)?.options||[]).map(T=>String(T.value))),E=V(d.parentRelationValue,`${a}/parentRelationValue`),p=V(d.childRelationValue,`${a}/childRelationValue`),g=v(d.eligibleParentStatuses,`${a}/eligibleParentStatuses`,16),O=v(d.eligibleChildStatuses,`${a}/eligibleChildStatuses`,16);(I("amountFieldCode")?.type!=="number.decimal"||I("amountFieldCode")?.exactDecimal!==!0||I("amountFieldCode")?.precision!==18||I("amountFieldCode")?.scale!==2||I("currencyFieldCode")?.type!=="option.single"||I("relationFieldCode")?.type!=="option.single"||I("parentFieldCode")?.type!=="resource-ref.single"||I("parentFieldCode")?.source?.resourceCode!==l||I("rootFieldCode")?.type!=="uuid"||I("statusFieldCode")?.type!=="option.single"||E===p||!m("relationFieldCode").has(E)||!m("relationFieldCode").has(p)||!g.length||!O.length||g.some(y=>!m("statusFieldCode").has(y))||O.some(y=>!m("statusFieldCode").has(y)))&&_("NATIVE_DECIMAL_RESERVATION_FIELD_INVALID",a),r.decimalReservation={mode:u,resourceCode:l,...N,parentRelationValue:E,childRelationValue:p,eligibleParentStatuses:W(g),eligibleChildStatuses:W(O)}}return r}function xr(e,t,o,n,i){if(e===void 0)return;let s=`${t}/ai`,c=b(e,s);ir.test(o)||_("NATIVE_OPERATION_AI_CODE_INVALID",`${t}/code`),R(c,["name","description","risk","resources","sideEffects","concurrency","timeoutMs"],s,!0),C(c.name,`${s}/name`,xn),C(c.description,`${s}/description`,xn);let r=C(c.risk,`${s}/risk`,16);["read","write","destructive","external"].includes(r)||_("NATIVE_OPERATION_AI_RISK_INVALID",`${s}/risk`),r==="read"!=(n==="GET")&&_("NATIVE_OPERATION_AI_METHOD_RISK_MISMATCH",`${s}/risk`),n==="DELETE"&&!["destructive","external"].includes(r)&&_("NATIVE_OPERATION_AI_METHOD_RISK_MISMATCH",`${s}/risk`);let a=v(c.resources,`${s}/resources`,16);a.length===0&&_("NATIVE_OPERATION_AI_RESOURCE_REQUIRED",`${s}/resources`),a.forEach((u,l)=>{let f=J(u,`${s}/resources/${l}`);i.has(f)||_("NATIVE_OPERATION_AI_RESOURCE_MISSING",`${s}/resources/${l}`)});let d=v(c.sideEffects,`${s}/sideEffects`,20);(r==="read"&&d.length!==0||r!=="read"&&d.length===0)&&_("NATIVE_OPERATION_AI_SIDE_EFFECT_INVALID",`${s}/sideEffects`),c.concurrency!==void 0&&!["none","revision"].includes(C(c.concurrency,`${s}/concurrency`,16))&&_("NATIVE_OPERATION_AI_CONCURRENCY_INVALID",`${s}/concurrency`),c.timeoutMs!==void 0&&te(c.timeoutMs,`${s}/timeoutMs`,100,3e4)}function jt(e){return(e.replace(/\/{2,}/g,"/").replace(/\/$/,"")||"/").split("/").map(o=>o.startsWith(":")?":":o.includes("*")?"*":o).join("/")}function jr(e,t){let o=b(e,t),n=C(o.type,`${t}/type`,32),i=["code","type","label","presentation","required"],s=n==="sso"?[...i,"provider"]:n==="dingtalk"?[...i,"flow"]:i;R(o,s,t);let c=V(o.code,`${t}/code`),r=C(o.label,`${t}/label`,255),a=C(o.presentation,`${t}/presentation`,16);["primary","secondary"].includes(a)||_("NATIVE_APPLICATION_AUTH_METHOD_PRESENTATION_INVALID",`${t}/presentation`);let d=Xe(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(C(o.flow,`${t}/flow`,16))&&_("NATIVE_APPLICATION_AUTH_DINGTALK_FLOW_INVALID",`${t}/flow`),{code:c,type:n,label:r,presentation:a,required:d,...n==="sso"?{provider:"tenant-default"}:{},...n==="dingtalk"?{flow:o.flow}:{}}}function ai(e,t,o){let n=b(e,o);R(n,["routeCode","path","defaultRouteCode"],o);let i=V(n.routeCode,`${o}/routeCode`),s=_e(n.path,`${o}/path`),c=t==="desktop"?"/login":"/m/login";return(s!==c||/[:*?#\\]/.test(s))&&_("NATIVE_APPLICATION_AUTH_SURFACE_PATH_INVALID",`${o}/path`,{device:t,expectedPath:c}),{routeCode:i,path:s,defaultRouteCode:V(n.defaultRouteCode,`${o}/defaultRouteCode`)}}function hi(e,t,o,n){if(e===null)return;let i=b(e,n);R(i,["accountMode","registration","methods","surfaces"],n),x(i.accountMode,"existing-platform-users-only",`${n}/accountMode`);let s=b(i.registration,`${n}/registration`);R(s,["mode"],`${n}/registration`),x(s.mode,"reject",`${n}/registration/mode`);let c=S(i.methods,`${n}/methods`,8);c.length===0&&_("NATIVE_APPLICATION_AUTH_METHOD_REQUIRED",`${n}/methods`);let r=c.map((E,p)=>jr(E,`${n}/methods/${p}`)),a=new Set,d=new Set;for(let[E,p]of r.entries())a.has(p.code)&&_("NATIVE_APPLICATION_AUTH_METHOD_CODE_DUPLICATE",`${n}/methods/${E}/code`),d.has(p.type)&&_("NATIVE_APPLICATION_AUTH_METHOD_TYPE_DUPLICATE",`${n}/methods/${E}/type`),a.add(p.code),d.add(p.type);r.filter(E=>E.presentation==="primary").length!==1&&_("NATIVE_APPLICATION_AUTH_PRIMARY_METHOD_INVALID",`${n}/methods`);let u=b(i.surfaces,`${n}/surfaces`);R(u,["desktop","mobile"],`${n}/surfaces`);let l=ai(u.desktop,"desktop",`${n}/surfaces/desktop`),f=ai(u.mobile,"mobile",`${n}/surfaces/mobile`);l.routeCode===f.routeCode&&_("NATIVE_APPLICATION_AUTH_SURFACE_CODE_DUPLICATE",`${n}/surfaces/mobile/routeCode`);let A=S(t,"/config/frontend/routes",500),N=new Map;for(let[E,p]of A.entries()){let g=b(p,`/config/frontend/routes/${E}`);N.set(String(g.code||""),g)}let I=new Set((Array.isArray(o.data?.resources)?o.data.resources:[]).map(E=>String(E.code||"")).filter(E=>/^[a-z][a-z0-9-]{0,62}$/.test(E)));for(let[E,p]of[["desktop",l],["mobile",f]]){N.has(p.routeCode)&&_("NATIVE_APPLICATION_AUTH_SURFACE_CODE_CONFLICT",`${n}/surfaces/${E}/routeCode`);let g=/^user\.([a-z][a-z0-9-]{0,62})\.(records|submit)$/.exec(String(p.defaultRouteCode||"")),O=N.get(p.defaultRouteCode),y=String(O?.path||"");if(g&&I.has(g[1])){let h=g[2]==="records"?`/my/${g[1]}`:`/my/${g[1]}/submit`;O={surface:"user",path:E==="mobile"?`/m${h}`:h},y=String(O.path)}let T=E==="desktop"?y==="/m"||y.startsWith("/m/"):!(y==="/m"||y.startsWith("/m/"));(!O||O.surface!=="user"||/[:*]/.test(y)||T)&&_("NATIVE_APPLICATION_AUTH_DEFAULT_ROUTE_INVALID",`${n}/surfaces/${E}/defaultRouteCode`)}let m=Ri(o).filter(E=>!E.owner.startsWith("authentication:"));for(let[E,p]of[["desktop",l],["mobile",f]]){let g=m.find(O=>jt(O.path)===jt(p.path));g&&_("NATIVE_APPLICATION_AUTH_SURFACE_PATH_CONFLICT",`${n}/surfaces/${E}/path`,{owner:g.owner})}}function Mr(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=b(e,t),i=b(n.surfaces,`${t}/surfaces`),s={...n,surfaces:{...i,desktop:{...b(i.desktop,`${t}/surfaces/desktop`),defaultRouteCode:"auth-desktop-default"},mobile:{...b(i.mobile,`${t}/surfaces/mobile`),defaultRouteCode:"auth-mobile-default"}}};hi(s,o.frontend.routes,{...o,frontend:{...o.frontend,authentication:s}},t)}function Wr(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 Ur=new Set(["draft.read","draft.update","validate","create","own.list","own.read","public.list","public.read"]);function Br(e,t,o){let n=b(e,o);R(n,["policies"],o);let i=S(n.policies,`${o}/policies`,16);i.length<1&&_("NATIVE_PUBLIC_POLICY_REQUIRED",o);let s=new Map(t.frontend.routes.map(d=>[d.code,d])),c=new Map(t.data.resources.map(d=>[d.code,d])),r=new Set,a=new Set(i.map(d=>String(d?.code||"")));i.forEach((d,u)=>{let l=`${o}/policies/${u}`,f=b(d,l);R(f,["code","routeCode","mode","resourceCode","operations","fields"],l,["requiredFields","ownRecordFields","publicRecordFields","publicFilters","serverGeneratedFields","schedule","publicSubtableFields","draft","validations"]);let A=V(f.code,`${l}/code`);r.has(A)&&_("NATIVE_PUBLIC_POLICY_DUPLICATE",`${l}/code`);let N=V(f.routeCode,`${l}/routeCode`),I=s.get(N);(!I||I.surface!=="user"||I.capability!==void 0||I.access!==void 0||/[:*]/.test(String(I.path)))&&_("NATIVE_PUBLIC_ROUTE_INVALID",`${l}/routeCode`),x(f.mode,"anonymous",`${l}/mode`);let m=J(f.resourceCode,`${l}/resourceCode`),E=c.get(m);E||_("NATIVE_PUBLIC_RESOURCE_MISSING",`${l}/resourceCode`);let p=new Map(E.schema.fields.map($=>[String($.code),String($.type)])),g=v(f.operations,`${l}/operations`,8);(g.length<1||g.some($=>!Ur.has($)))&&_("NATIVE_PUBLIC_OPERATION_INVALID",`${l}/operations`),g.includes("draft.read")!==g.includes("draft.update")&&_("NATIVE_PUBLIC_DRAFT_OPERATION_INCOMPLETE",`${l}/operations`);let O=v(f.fields,`${l}/fields`,64);(O.length<1||O.some($=>!p.has($)))&&_("NATIVE_PUBLIC_FIELD_INVALID",`${l}/fields`);for(let $ of["requiredFields","ownRecordFields","publicRecordFields"]){if(!Object.prototype.hasOwnProperty.call(f,$))continue;v(f[$],`${l}/${$}`,64).some(P=>!O.includes(P))&&_("NATIVE_PUBLIC_FIELD_SCOPE_INVALID",`${l}/${$}`)}let y=Object.prototype.hasOwnProperty.call(f,"serverGeneratedFields")?S(f.serverGeneratedFields,`${l}/serverGeneratedFields`,16):[],T=new Set;y.forEach(($,M)=>{let P=`${l}/serverGeneratedFields/${M}`,G=b($,P);R(G,["field","kind"],P);let q=K(G.field,`${P}/field`);(T.has(q)||!p.has(q)||O.includes(q)||p.get(q)!=="text.short"&&p.get(q)!=="text.long")&&_("NATIVE_PUBLIC_SERVER_GENERATED_FIELD_INVALID",`${P}/field`),x(G.kind,"random-token",`${P}/kind`),T.add(q)});let h=Object.prototype.hasOwnProperty.call(f,"schedule")?b(f.schedule,`${l}/schedule`):null;if(h){let $=["campusPolicyCode","rulePolicyCode","campusField","ruleCampusField","ruleWeekdaysField","ruleOpenAtField","ruleCloseAtField","ruleSlotMinutesField","ruleAdvanceHoursField","ruleAdvanceDaysField","campusEnabledField","ruleEnabledField","dateField","timeField"];R(h,$,`${l}/schedule`);for(let M of["campusPolicyCode","rulePolicyCode"])V(h[M],`${l}/schedule/${M}`);for(let M of $.filter(P=>!["campusPolicyCode","rulePolicyCode"].includes(P)))K(h[M],`${l}/schedule/${M}`);for(let M of[h.campusField,h.dateField,h.timeField])O.includes(String(M))||_("NATIVE_PUBLIC_SCHEDULE_FIELD_INVALID",`${l}/schedule`);(!a.has(String(h.campusPolicyCode))||!a.has(String(h.rulePolicyCode)))&&_("NATIVE_PUBLIC_SCHEDULE_POLICY_INVALID",`${l}/schedule`)}let D=Object.prototype.hasOwnProperty.call(f,"publicFilters")?S(f.publicFilters,`${l}/publicFilters`,16):[],F=new Set;D.forEach(($,M)=>{let P=`${l}/publicFilters/${M}`,G=b($,P);R(G,["field","operator","value"],P);let q=K(G.field,`${P}/field`);F.has(q)&&_("NATIVE_PUBLIC_FILTER_DUPLICATE",`${P}/field`),O.includes(q)||_("NATIVE_PUBLIC_FILTER_FIELD_INVALID",`${P}/field`),x(G.operator,"eq",`${P}/operator`),["boolean","text.short","text.long","number.integer","number.decimal","date","time"].includes(p.get(q)||"")||_("NATIVE_PUBLIC_FILTER_FIELD_INVALID",`${P}/field`),G.value!==null&&typeof G.value!="string"&&typeof G.value!="number"&&typeof G.value!="boolean"&&_("NATIVE_PUBLIC_FILTER_VALUE_INVALID",`${P}/value`),F.add(q)});let k=Object.prototype.hasOwnProperty.call(f,"publicSubtableFields")?b(f.publicSubtableFields,`${l}/publicSubtableFields`):null;if(k){Object.keys(k).length>64&&_("NATIVE_PUBLIC_SUBTABLE_FIELDS_INVALID",`${l}/publicSubtableFields`);for(let[$,M]of Object.entries(k)){let P=E.schema.fields.find(Q=>String(Q.code)===$),G=String(P?.subtable?.resourceCode||""),q=c.get(G),Te=new Map((q?.schema?.fields||[]).map(Q=>[String(Q.code),String(Q.type)])),z=v(M,`${l}/publicSubtableFields/${$}`,64);(!O.includes($)||p.get($)!=="subtable"||!q||z.length<1||z.some(Q=>!Te.has(Q))||z.some(Q=>Te.get(Q)==="subtable")||z.some(Q=>Te.get(Q)==="signature"))&&_("NATIVE_PUBLIC_SUBTABLE_FIELDS_INVALID",`${l}/publicSubtableFields/${$}`)}}if(g.some($=>$.startsWith("public."))){Object.prototype.hasOwnProperty.call(f,"publicRecordFields")||_("NATIVE_PUBLIC_RECORD_FIELDS_REQUIRED",`${l}/publicRecordFields`);let $=v(f.publicRecordFields,`${l}/publicRecordFields`,64);($.length<1||$.some(M=>!O.includes(M))||$.some(M=>p.get(M)==="signature"||p.get(M)==="subtable"&&!k?.[M]))&&_("NATIVE_PUBLIC_RECORD_FIELDS_INVALID",`${l}/publicRecordFields`)}let U=Object.prototype.hasOwnProperty.call(f,"requiredFields")?v(f.requiredFields,`${l}/requiredFields`,64):[],j=E.surface||{},ie=j.fields||{},ge=String(j.mutationOwner||"native")==="native"&&j.generated?.create!==!1,H=E.schema.fields.filter($=>Nt($,ie[$.code])).map($=>String($.code));if(g.includes("create")&&!ge&&_("NATIVE_PUBLIC_CREATE_FIELDS_INCOMPLETE",`${l}/fields`),g.includes("create")&&!Object.prototype.hasOwnProperty.call(f,"draft")&&_("NATIVE_PUBLIC_DRAFT_REQUIRED",`${l}/draft`),g.includes("create"))for(let $ of H){let M=O.includes($)?U.includes($)?null:"requiredFields":"fields";M&&_("NATIVE_PUBLIC_CREATE_FIELDS_INCOMPLETE",`${l}/${M}`,{resourceCode:J,fieldCode:$})}if(Object.prototype.hasOwnProperty.call(f,"draft")){let $=b(f.draft,`${l}/draft`);R($,["enabled","inactivityTtlSeconds","maxBytes"],`${l}/draft`),x($.enabled,!0,`${l}/draft/enabled`),te($.inactivityTtlSeconds,`${l}/draft/inactivityTtlSeconds`,3600,7776e3),te($.maxBytes,`${l}/draft/maxBytes`,4096,262144)}else g.includes("draft.read")&&_("NATIVE_PUBLIC_DRAFT_REQUIRED",`${l}/draft`);let be=Object.prototype.hasOwnProperty.call(f,"validations")?S(f.validations,`${l}/validations`,16):[],ae=new Set;be.forEach(($,M)=>{let P=`${l}/validations/${M}`,G=b($,P);R(G,["code","kind","fields","result"],P);let q=V(G.code,`${P}/code`);ae.has(q)&&_("NATIVE_PUBLIC_VALIDATION_DUPLICATE",`${P}/code`),x(G.kind,"duplicate",`${P}/kind`),x(G.result,"availability",`${P}/result`);let Te=v(G.fields,`${P}/fields`,8);(Te.length<1||Te.some(z=>!O.includes(z))||Te.some(z=>["file","subtable"].includes(p.get(z)||"")))&&_("NATIVE_PUBLIC_VALIDATION_FIELD_INVALID",`${P}/fields`),ae.add(q)}),r.add(A)})}function Kr(e,t){let o=b(e,t);R(o,["policies"],t),S(o.policies,`${t}/policies`,16).length<1&&_("NATIVE_PUBLIC_POLICY_REQUIRED",t)}function Gr(e){return{policies:Z(e.frontend.publicAccess.policies.map(t=>({code:t.code,routeCode:t.routeCode,mode:t.mode,resourceCode:t.resourceCode,operations:W(t.operations),fields:W(t.fields),...t.requiredFields?{requiredFields:W(t.requiredFields)}:{},...t.ownRecordFields?{ownRecordFields:W(t.ownRecordFields)}:{},...t.publicRecordFields?{publicRecordFields:W(t.publicRecordFields)}:{},...t.publicFilters?{publicFilters:t.publicFilters.map(o=>({field:o.field,operator:o.operator,value:o.value})).sort((o,n)=>ue(o.field,n.field))}:{},...t.publicSubtableFields?{publicSubtableFields:Object.fromEntries(Object.entries(t.publicSubtableFields).sort(([o],[n])=>o.localeCompare(n)).map(([o,n])=>[o,W(Array.isArray(n)?n.map(String):[])]))}:{},...t.serverGeneratedFields?{serverGeneratedFields:t.serverGeneratedFields.map(o=>({field:o.field,kind:o.kind})).sort((o,n)=>ue(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:Z(t.validations.map(o=>({code:o.code,kind:o.kind,fields:W(o.fields),result:o.result})),o=>o.code)}:{}})),t=>t.code)}}function Ri(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=Ci(o),i=`/admin/resources/${o.code}`,s=[["list",i],["detail",`${i}/:id`],["create",`${i}/new`],["update",`${i}/:id/edit`]];for(let[c,r]of s)n[c]&&t.push({owner:`resource:${o.code}:${c}`,path:r},{owner:`resource:${o.code}:${c}:mobile`,path:`/m${r}`})}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 Bt(e){let t=new Map(Ri(e).map(o=>[jt(o.path),o]));return Z(e.frontend.routes.map((o,n)=>{let i=`/config/frontend/routes/${n}`,s=b(o,i);R(s,["code","path","label","surface","parentCode","capability","access","pinned","tabPersistence","keepAlive"],i,!0),["admin","user"].includes(s.surface)||_("NATIVE_ROUTE_SURFACE_INVALID",`${i}/surface`);let c=_e(s.path,`${i}/path`);s.surface==="admin"&&c!=="/admin"&&!c.startsWith("/admin/")&&_("NATIVE_ADMIN_ROUTE_PATH_INVALID",`${i}/path`),s.surface==="user"&&(c==="/admin"||c.startsWith("/admin/"))&&_("NATIVE_USER_ROUTE_PATH_RESERVED",`${i}/path`);let r=jt(c),a=t.get(r);a&&_("NATIVE_ROUTE_PATH_CONFLICT",`${i}/path`,{path:c,owner:a.owner}),t.set(r,{owner:`frontend:${String(s.code||n)}`,path:c});let d=/[:*]/.test(c),u=qn(s,i,e.appCode),l=s.pinned===void 0?void 0:Xe(s.pinned,`${i}/pinned`),f=s.tabPersistence===void 0?d?"none":"session":C(s.tabPersistence,`${i}/tabPersistence`,16),A=s.keepAlive===void 0?"none":C(s.keepAlive,`${i}/keepAlive`,16);return["session","none"].includes(f)||_("NATIVE_ROUTE_TAB_PERSISTENCE_INVALID",`${i}/tabPersistence`),["none","memory"].includes(A)||_("NATIVE_ROUTE_KEEP_ALIVE_INVALID",`${i}/keepAlive`),d&&l===!0&&_("NATIVE_DYNAMIC_ROUTE_PINNED_FORBIDDEN",`${i}/pinned`),d&&f==="session"&&_("NATIVE_DYNAMIC_ROUTE_TAB_PERSISTENCE_FORBIDDEN",`${i}/tabPersistence`),d&&A==="memory"&&_("NATIVE_DYNAMIC_ROUTE_KEEP_ALIVE_FORBIDDEN",`${i}/keepAlive`),{code:V(s.code,`${i}/code`),path:c,label:C(s.label,`${i}/label`,255),surface:s.surface,...s.parentCode===void 0?{}:{parentCode:V(s.parentCode,`${i}/parentCode`)},...u,...l===void 0?{}:{pinned:l},tabPersistence:f,keepAlive:A}}),o=>o.code)}function Ci(e){let t=e.surface===void 0?{}:b(e.surface,"/surface"),o=t.mutationOwner||"native",n=t.generated===void 0?{}:b(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 Si(e){let t=[];for(let o of Z(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:ln(n.surface,i.code)}}))])){let{resource:n,viewCode:i}=o,s=`/admin/resources/${n.code}${i?`/views/${i}`:""}`,c=Ci(n),r=[{operation:"list",kind:"resource-list",path:`${s}`,label:n.name,capability:n.capabilities.read,navigationEligible:!0},{operation:"detail",kind:"resource-detail",path:`${s}/:id`,label:`${n.name}\u8BE6\u60C5`,capability:n.capabilities.read,navigationEligible:!1},{operation:"create",kind:"resource-create",path:`${s}/new`,label:`\u65B0\u589E${n.name}`,capability:n.capabilities.create,navigationEligible:!1},{operation:"update",kind:"resource-update",path:`${s}/:id/edit`,label:`\u7F16\u8F91${n.name}`,capability:n.capabilities.update,navigationEligible:!1}];for(let a of r)c[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 Bt(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)=>ue(o.code,n.code))}function wi(e){return e.kind==="resource"?`resource:${e.resourceCode}${e.viewCode?`:view:${e.viewCode}`:""}:list`:`operation:${e.routeCode}`}function qr(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:wi(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||ue(n.pageCode,i.pageCode))})).sort((t,o)=>t.order-o.order||ue(t.code,o.code))}function Jr(e,t){let o=S(e,t,Y.adminNavigationGroups),n=0;o.forEach((i,s)=>{let c=`${t}/${s}`,r=b(i,c);R(r,["code","label","icon","order","items"],c,!0),V(r.code,`${c}/code`),C(r.label,`${c}/label`,255),Mt(r.icon,`${c}/icon`),fi(r.order,`${c}/order`);let a=S(r.items,`${c}/items`,500);a.length===0&&_("NATIVE_ADMIN_GROUP_ORPHANED",`${c}/items`),n+=a.length,n>Y.adminNavigationItems&&_("NATIVE_ARRAY_LIMIT_EXCEEDED",t),a.forEach((d,u)=>{let l=`${c}/items/${u}`,f=b(d,l);R(f,["page","label","icon","order"],l,!0),zr(f.page,`${l}/page`),f.label!==void 0&&C(f.label,`${l}/label`,255),Mt(f.icon,`${l}/icon`),fi(f.order,`${l}/order`)})})}function zr(e,t){let o=b(e,t),n=C(o.kind,`${t}/kind`,64);if(n==="resource"){R(o,["kind","resourceCode"],t,["viewCode"]),o.viewCode!==void 0&&V(o.viewCode,`${t}/viewCode`),J(o.resourceCode,`${t}/resourceCode`);return}if(n==="operation"){R(o,["kind","routeCode"],t),V(o.routeCode,`${t}/routeCode`);return}_("NATIVE_ADMIN_PAGE_REFERENCE_KIND_INVALID",`${t}/kind`)}function Yr(e){let t=new Map(Si(e).map(i=>[String(i.code),i])),o=new Set,n=new Set;e.frontend.admin.navigation.forEach((i,s)=>{let c=`/config/frontend/admin/navigation/${s}`;o.has(i.code)&&_("NATIVE_ADMIN_GROUP_DUPLICATE",`${c}/code`),o.add(i.code),i.label===i.code&&_("NATIVE_ADMIN_USER_LABEL_REQUIRED",`${c}/label`),i.items.forEach((r,a)=>{let d=`${c}/items/${a}`,u=wi(r.page),l=t.get(u);(!l||l.navigationEligible!==!0)&&_("NATIVE_ADMIN_PAGE_NOT_FOUND",`${d}/page`),n.has(u)&&_("NATIVE_ADMIN_PAGE_DUPLICATE",`${d}/page`),n.add(u);let f=r.page.resourceCode||r.page.routeCode||r.page.workflowCode||u,A=r.label||l.label;(!A||A===f||A===u)&&_("NATIVE_ADMIN_USER_LABEL_REQUIRED",`${d}/label`)})})}function Hr(e,t){let o=S(e,t,Y.adminPages),n=new Set;o.forEach((i,s)=>{let c=`${t}/${s}`,r=b(i,c);R(r,["code","kind","path","label","navigationEligible","capability","access","resourceCode","viewCode","routeCode"],c,!0);let a=C(r.code,`${c}/code`,255);n.has(a)&&_("NATIVE_ADMIN_PAGE_DUPLICATE",`${c}/code`),n.add(a);let d=C(r.kind,`${c}/kind`,64);if(["resource-list","resource-detail","resource-create","resource-update","operation"].includes(d)||_("NATIVE_ADMIN_PAGE_KIND_INVALID",`${c}/kind`),_e(r.path,`${c}/path`),C(r.label,`${c}/label`,255),Xe(r.navigationEligible,`${c}/navigationEligible`),r.capability!==void 0&&r.access!==void 0&&_("NATIVE_ROUTE_ACCESS_CONFLICT",`${c}/access`),r.capability!==void 0&&C(r.capability,`${c}/capability`,255),r.access!==void 0){let u=b(r.access,`${c}/access`);R(u,["allOf","anyOf"],`${c}/access`,!0);for(let l of["allOf","anyOf"])u[l]!==void 0&&v(u[l],`${c}/access/${l}`,50)}for(let u of["resourceCode","viewCode","routeCode"])r[u]!==void 0&&V(r[u],`${c}/${u}`)})}function Xr(e,t){let o=S(e,t,Y.adminNavigationGroups),n=0;o.forEach((i,s)=>{let c=`${t}/${s}`,r=b(i,c);R(r,["code","label","icon","order","items"],c,!0),V(r.code,`${c}/code`),C(r.label,`${c}/label`,255),Mt(r.icon,`${c}/icon`),te(r.order,`${c}/order`,-1e4,1e4);let a=S(r.items,`${c}/items`,500);a.length===0&&_("NATIVE_ADMIN_GROUP_ORPHANED",`${c}/items`),n+=a.length,n>Y.adminNavigationItems&&_("NATIVE_ARRAY_LIMIT_EXCEEDED",t),a.forEach((d,u)=>{let l=`${c}/items/${u}`,f=b(d,l);R(f,["pageCode","label","icon","order"],l,!0),C(f.pageCode,`${l}/pageCode`,255),f.label!==void 0&&C(f.label,`${l}/label`,255),Mt(f.icon,`${l}/icon`),te(f.order,`${l}/order`,-1e4,1e4)})})}var Qr=new Set(["application-todo-center","workflow-work-center","workflow-launch","workflow-task","workflow-instance","resource-records","resource-submit"]);function Zr(e,t,o){let n=b(e,t);R(n,["schemaVersion","appCode","devicePolicy","rootEntry","authentication","routes","digest"],t),x(n.schemaVersion,bi,`${t}/schemaVersion`),x(n.appCode,o,`${t}/appCode`),Gn(n.devicePolicy,`${t}/devicePolicy`),ea(n.rootEntry,`${t}/rootEntry`),ta(n.authentication,`${t}/authentication`),Bn(n.digest,`${t}/digest`);let i=S(n.routes,`${t}/routes`,Y.routes),s=new Set;i.forEach((c,r)=>{let a=`${t}/routes/${r}`,d=b(c,a),u=d.kind==="resource-records"||d.kind==="resource-submit";R(d,["code","kind","desktop","mobile"],a,["workflowCode",...u?["resourceCode"]:[]]);let l=C(d.code,`${a}/code`,255);s.has(l)&&_("NATIVE_ROUTE_MANIFEST_DUPLICATE",`${a}/code`),s.add(l);let f=C(d.kind,`${a}/kind`,64);if(Qr.has(f)||_("NATIVE_ROUTE_MANIFEST_KIND_INVALID",`${a}/kind`),d.workflowCode!==void 0&&V(d.workflowCode,`${a}/workflowCode`),u){let I=J(d.resourceCode,`${a}/resourceCode`);x(l,`user.${I}.${d.kind==="resource-records"?"records":"submit"}`,`${a}/code`)}else d.resourceCode!==void 0&&_("NATIVE_PROPERTY_UNKNOWN",`${a}/resourceCode`);let A=di(d.desktop,`${a}/desktop`,o),N=di(d.mobile,`${a}/mobile`,o);A.surface!=="user"&&_("NATIVE_ROUTE_MANIFEST_DESKTOP_SURFACE_INVALID",`${a}/desktop/surface`),N.surface!=="user"&&_("NATIVE_ROUTE_MANIFEST_MOBILE_SURFACE_INVALID",`${a}/mobile/surface`),A.routeCode===N.routeCode&&_("NATIVE_ROUTE_MANIFEST_PAIR_DUPLICATE",a)}),x(n.digest,X({schemaVersion:n.schemaVersion,appCode:n.appCode,devicePolicy:n.devicePolicy,rootEntry:n.rootEntry,authentication:n.authentication,routes:n.routes}),`${t}/digest`)}function Gn(e,t){let o=b(e,t);R(o,["kind","mobileMaxWidthPx","desktopMinWidthPx"],t),x(o.kind,"viewport-family",`${t}/kind`);let n=te(o.mobileMaxWidthPx,`${t}/mobileMaxWidthPx`,320,1600),i=te(o.desktopMinWidthPx,`${t}/desktopMinWidthPx`,320,1600);return i!==n+1&&_("NATIVE_FRONTEND_DEVICE_POLICY_INVALID",t),{kind:"viewport-family",mobileMaxWidthPx:n,desktopMinWidthPx:i}}function ea(e,t){let o=b(e,t);R(o,["code","desktop","mobile"],t);let n=V(o.code,`${t}/code`),i=Un(o.desktop,`${t}/desktop`),s=Un(o.mobile,`${t}/mobile`);return(i===s||s==="/"||!s.startsWith("/m/"))&&_("NATIVE_ROUTE_MANIFEST_ROOT_ENTRY_INVALID",t),i.startsWith("/m/")&&_("NATIVE_ROUTE_MANIFEST_ROOT_ENTRY_INVALID",`${t}/desktop`),{code:n,desktop:i,mobile:s}}function ta(e,t){let o=b(e,t);R(o,["desktop","mobile"],t);let n=ci(o.desktop,`${t}/desktop`,!1),i=ci(o.mobile,`${t}/mobile`,!0);return(n.routeCode===i.routeCode||n.path===i.path)&&_("NATIVE_ROUTE_MANIFEST_AUTHENTICATION_DUPLICATE",t),{desktop:n,mobile:i}}function ci(e,t,o){let n=b(e,t);R(n,["routeCode","path"],t);let i=V(n.routeCode,`${t}/routeCode`),s=Un(n.path,`${t}/path`);return(o?!s.startsWith("/m/"):s.startsWith("/m/"))&&_("NATIVE_ROUTE_MANIFEST_AUTHENTICATION_PATH_INVALID",`${t}/path`),{routeCode:i,path:s}}function Un(e,t){let o=_e(e,t);return/[:*?#\\\\]/.test(o)&&_("NATIVE_ROUTE_MANIFEST_STATIC_PATH_INVALID",t),o}function di(e,t,o){let n=b(e,t);R(n,["routeCode","path","surface","pathParams","requiresAuthentication"],t,["capability","access"]),V(n.routeCode,`${t}/routeCode`);let i=_e(n.path,`${t}/path`),s=C(n.surface,`${t}/surface`,16);["admin","user"].includes(s)||_("NATIVE_ROUTE_SURFACE_INVALID",`${t}/surface`);let c=v(n.pathParams,`${t}/pathParams`,8);return c.forEach((r,a)=>{(!/^[A-Za-z][A-Za-z0-9_]*$/.test(r)||r.length>64)&&_("NATIVE_ROUTE_PATH_PARAM_INVALID",`${t}/pathParams/${a}`)}),ee(c)!==ee(Di(i))&&_("NATIVE_ROUTE_PATH_PARAMS_MISMATCH",`${t}/pathParams`),qn(n,t,o),n.requiresAuthentication!==!0&&_("NATIVE_ROUTE_AUTHENTICATION_REQUIRED",`${t}/requiresAuthentication`),n}function Di(e){return W([...e.matchAll(/:([A-Za-z][A-Za-z0-9_]*)/g)].map(t=>t[1]))}function li(e,t,o,n){return{routeCode:e,path:t,surface:o,pathParams:Di(t),...n?.capability?{capability:n.capability}:{},...n?.access?{access:n.access}:{},requiresAuthentication:!0}}function ui(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 na(e){let t=e.appCode,o=[],n=(A,N,I,m,E,p,g)=>{o.push({code:A,kind:N,...E?{workflowCode:E}:{},...g?{resourceCode:g}:{},desktop:li(ui(N,"desktop",E,g),I,"user",p),mobile:li(ui(N,"mobile",E,g),m,"user",p)})};e.frontend.user.applicationTodoCenter===!0&&n("application:todo-center","application-todo-center","/todos","/m/todos");let i=$i(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 A of i){if(!["standalone","hidden-handoff"].includes(A.launch.mode))continue;let N=W([A.launch.submission?.create?.requiredCapability,A.launch.submission?.existing?.requiredCapability].filter(I=>!!I));n(`workflow:${A.code}:launch`,"workflow-launch","/workflows/:workflowCode/start","/m/workflows/:workflowCode/start",A.code,N.length===1?{capability:N[0]}:N.length>1?{access:{anyOf:N}}:void 0)}let s=o.sort((A,N)=>ue(String(A.code),String(N.code))),c=Bt(e),r=A=>{let N=A==="mobile"?"/m/":"/",I=c.filter(E=>E.surface==="user"&&!/[:*?#\\\\]/.test(E.path)&&E.path===N).sort((E,p)=>ue(E.code,p.code))[0];if(I)return{code:I.code,path:I.path};let m=c.filter(E=>E.surface==="user"&&!/[:*?#\\\\]/.test(E.path)&&(A==="mobile"?E.path.startsWith("/m/"):!E.path.startsWith("/m/"))).sort((E,p)=>ue(E.code,p.code))[0];return m?{code:m.code,path:m.path}:{code:A==="mobile"?"application-root-mobile":"application-root",path:N}},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"}},d=Gn(e.frontend.devicePolicy,"/config/frontend/devicePolicy"),u=r("desktop"),l=r("mobile"),f={schemaVersion:bi,appCode:t,devicePolicy:d,rootEntry:{code:u.code,desktop:u.path,mobile:l.path},authentication:a,routes:s};return{...f,digest:X(f)}}function Mt(e,t){if(e===void 0)return;let o=C(e,t,32);_r.has(o)||_("NATIVE_ADMIN_ICON_INVALID",t)}function fi(e,t){e!==void 0&&te(e,t,-1e4,1e4)}function qn(e,t,o){return e.capability!==void 0&&e.access!==void 0&&_("NATIVE_ROUTE_ACCESS_CONFLICT",`${t}/access`),e.capability!==void 0?{capability:Re(e.capability,`${t}/capability`,o)}:e.access===void 0?{}:{access:Kt(e.access,`${t}/access`,o)}}function Kt(e,t,o){let n=b(e,t);R(n,["allOf","anyOf"],t,!0);let i=n.allOf===void 0?void 0:W(v(n.allOf,`${t}/allOf`,50).map((c,r)=>Re(c,`${t}/allOf/${r}`,o))),s=n.anyOf===void 0?void 0:W(v(n.anyOf,`${t}/anyOf`,50).map((c,r)=>Re(c,`${t}/anyOf/${r}`,o)));return(i?.length||0)+(s?.length||0)===0&&_("NATIVE_ROUTE_ACCESS_EMPTY",t),{...i===void 0?{}:{allOf:i},...s===void 0?{}:{anyOf:s}}}function $i(e){let t=new Map(Oi(e).map(i=>[String(i.code),i])),o=e.workflows.definitions.map((i,s)=>{let c=`/config/workflows/definitions/${s}`,r=b(i,c);R(r,["version","definition","launch"],c,["detailRouteCode"]);let a=b(r.definition,`${c}/definition`),d=r.detailRouteCode===void 0?void 0:ki(r.detailRouteCode,`${c}/detailRouteCode`);return{code:V(a.code,`${c}/definition/code`),title:C(a.title,`${c}/definition/title`,255),version:He(r.version,`${c}/version`),launch:oa(e,a,r.launch,`${c}/launch`,t),...d?{detailRouteCode:d}:{},definition:a}});return W(o.map(i=>i.code)).map(i=>{let s=o.filter(d=>d.code===i),c=e.workflows.activations.find(d=>d.workflowCode===i)?.definitionVersion,r=s.find(d=>d.version===c)||[...s].sort((d,u)=>u.version-d.version)[0],a=new Set;for(let d of s){let u=b(d.definition.nodes,"/config/workflows/definitions/nodes");for(let l of Object.values(u)){let f=b(l,"/config/workflows/definitions/nodes/*");if(f.kind==="approval")for(let A of v(f.allowedOperations||[],"/config/workflows/definitions/nodes/*/allowedOperations",20))a.add(A)}}return{code:i,title:r.title,acceptedCommandDeactivationPolicy:r.definition.acceptedCommandDeactivationPolicy,subject:r.definition.subject,launch:r.launch,...["standalone","hidden-handoff"].includes(r.launch.mode)&&!r.launch.submission?{processOperationCode:`openxiangda.workflow.${i}.submit`}:{},...r.detailRouteCode?{detailRouteCode:r.detailRouteCode}:{},definitionVersions:Ni(s.map(d=>d.version)),bindingVersions:Ni(e.workflows.bindings.map((d,u)=>{let l=`/config/workflows/bindings/${u}`,f=b(d,l),A=b(f.binding,`${l}/binding`);return{code:V(A.workflowCode,`${l}/binding/workflowCode`),version:He(f.version,`${l}/version`)}}).filter(d=>d.code===i).map(d=>d.version)),providerCodes:W(e.workflows.providers.map((d,u)=>V(b(d,`/config/workflows/providers/${u}`).code,`/config/workflows/providers/${u}/code`))),allowedOperations:[...a].sort(ue),editableParameterCodes:W(e.workflows.editableParameters.map((d,u)=>{let l=`/config/workflows/editableParameters/${u}`,f=b(d,l);return{code:V(f.code,`${l}/code`),workflowCode:V(f.workflowCode,`${l}/workflowCode`)}}).filter(d=>d.workflowCode===i).map(d=>d.code))}})}function Vi(e,t){let o=b(e,t);R(o,["mode"],t,["submission"]);let n=C(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:b(o.submission,`${t}/submission`)}}}function oa(e,t,o,n,i){let s=Vi(o,n);if(!s.submission)return{mode:s.mode};["standalone","hidden-handoff"].includes(s.mode)||_("NATIVE_WORKFLOW_NAMED_OPERATION_SUBMISSION_INVALID",`${n}/submission`);let c=b(s.submission,`${n}/submission`);R(c,["kind"],`${n}/submission`,["create","existing","context"]),x(c.kind,"named-operation",`${n}/submission/kind`);let r=n.endsWith("/launch")?n.slice(0,-7):n,a=b(t.subject,`${r}/definition/subject`),d=J(a.resourceCode,`${r}/definition/subject/resourceCode`),u=e.data.resources.findIndex(T=>T.code===d),l=e.data.resources[u];(u<0||!l)&&_("NATIVE_WORKFLOW_SUBJECT_RESOURCE_MISSING",`${r}/definition/subject/resourceCode`);let f=new Set(b(l.schema,`/config/data/resources/${u}/schema`).fields.map(T=>String(T.code))),A=new Map(e.backend.operations.map(T=>[String(T.code),T])),N=(T,h)=>{let D=`${n}/submission/${h}`,F=b(T,D);R(F,["operationCode","inputs","output"],D);let k=V(F.operationCode,`${D}/operationCode`),U=A.get(k),j=i.get(k),ie=j?.platformAccess?.workflow?.codes;(!U||!j||j.method!=="POST"||!Array.isArray(ie)||!ie.includes(t.code))&&_("NATIVE_WORKFLOW_NAMED_OPERATION_INVALID",D);let ge=b(U.requestSchema,`${D}/operation/requestSchema`),H=b(ge.properties,`${D}/operation/requestSchema/properties`),be=new Set(ge.required===void 0?[]:v(ge.required,`${D}/operation/requestSchema/required`,64)),ae=b(F.inputs,`${D}/inputs`),$=Object.entries(ae);(!$.length||$.length>64)&&_("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${D}/inputs`);let M=new Set,P=new Map,G={};for(let[z,Q]of $){(!si.test(z)||!Object.prototype.hasOwnProperty.call(H,z))&&_("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${D}/inputs/${z}`);let Ue=`${D}/inputs/${z}`,Jt=b(Q,Ue),Ve=C(Jt.source,`${Ue}/source`,32);if(["field","idempotency-key","current-user-reference","subject-id","subject-revision","requested-at"].includes(Ve)||_("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",Ue),R(Jt,["source"],Ue,Ve==="field"?["fieldCode"]:!1),P.set(Ve,(P.get(Ve)||0)+1),Ve==="field"){let gt=K(Jt.fieldCode,`${Ue}/fieldCode`);(M.has(gt)||!f.has(gt))&&_("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${Ue}/fieldCode`),M.add(gt),G[z]={source:Ve,fieldCode:gt}}else G[z]={source:Ve}}([...be].some(z=>!(z in ae))||(P.get("idempotency-key")||0)!==1||!$.some(([z,Q])=>b(Q,`${D}/inputs/${z}`).source==="idempotency-key"&&be.has(z))||h==="create"&&((P.get("subject-id")||0)>0||(P.get("subject-revision")||0)>0)||h==="existing"&&((P.get("subject-id")||0)!==1||(P.get("subject-revision")||0)!==1))&&_("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${D}/inputs`);let q=b(F.output,`${D}/output`);R(q,["subjectId"],`${D}/output`,["subjectRevision","processCommand"]);let Te=b(b(U.responseSchema,`${D}/operation/responseSchema`).properties,`${D}/operation/responseSchema/properties`);for(let z of["subjectId","subjectRevision","processCommand"]){if(q[z]===void 0)continue;let Q=C(q[z],`${D}/output/${z}`,128);(!si.test(Q)||!Object.prototype.hasOwnProperty.call(Te,Q))&&_("NATIVE_WORKFLOW_NAMED_OPERATION_OUTPUT_INVALID",`${D}/output/${z}`)}return{operationCode:k,method:"POST",path:j.path,requiredCapability:j.requiredCapability,requestSchemaDigest:j.requestSchemaDigest,responseSchemaDigest:j.responseSchemaDigest,inputs:G,output:{...q},fieldCodes:M}},I=c.create===void 0?void 0:N(c.create,"create"),m=c.existing===void 0?void 0:N(c.existing,"existing");!I&&!m&&_("NATIVE_WORKFLOW_NAMED_OPERATION_SUBMISSION_INVALID",`${n}/submission`);let E=new Set([...I?.fieldCodes||[],...m?.fieldCodes||[]]),p=c.context===void 0?[]:S(c.context,`${n}/submission/context`,16),g=new Set,O=p.map((T,h)=>{let D=`${n}/submission/context/${h}`,F=b(T,D);R(F,["queryParameter","fieldCode"],D);let k=C(F.queryParameter,`${D}/queryParameter`,64),U=K(F.fieldCode,`${D}/fieldCode`);return(!/^[A-Za-z][A-Za-z0-9]{0,63}$/.test(k)||g.has(k)||!E.has(U))&&_("NATIVE_WORKFLOW_LAUNCH_CONTEXT_INVALID",D),g.add(k),{queryParameter:k,fieldCode:U}}),y=T=>{let{fieldCodes:h,...D}=T;return D};return{mode:s.mode,submission:{kind:"named-operation",...I?{create:y(I)}:{},...m?{existing:y(m)}:{},context:O}}}function ki(e,t){let o=b(e,t);R(o,["desktop","mobile"],t);let n=V(o.desktop,`${t}/desktop`),i=V(o.mobile,`${t}/mobile`);return n===i&&_("NATIVE_WORKFLOW_DETAIL_ROUTE_DUPLICATE",t),{desktop:n,mobile:i}}function ia(e,t){let o=new Set(t.map(u=>u.code)),n=new Map;e.data.resources.forEach((u,l)=>{let f=`/config/data/resources/${l}`,A=b(u,f);for(let[m,E]of Object.entries(A.fieldPolicies||{})){if(!Ze(m))continue;let p=`${f}/fieldPolicies/${m}/read`,g=b(E,`${f}/fieldPolicies/${m}`);for(let O of v(g.read||[],p,2e3))o.has(O)||_("NATIVE_CAPABILITY_REFERENCE_MISSING",p)}let N=A.surface===void 0?{}:b(A.surface,`${f}/surface`);if(["native","queued-command"].includes(N.mutationOwner||"native"))return;let I=b(A.capabilities,`${f}/capabilities`);for(let m of["create","update","delete"])n.set(String(I[m]),m)});let i=new Set;for(let[u,l]of e.authz.roles.entries()){let f=`/config/authz/roles/${u}`,A=b(l,f);R(A,["code","name","description","capabilities"],f,!0);let N=V(A.code,`${f}/code`);i.has(N)&&_("NATIVE_ROLE_DUPLICATE",`${f}/code`),i.add(N),C(A.name,`${f}/name`,255);let I=v(A.capabilities,`${f}/capabilities`,2e3);for(let[m,E]of I.entries())n.has(E)&&_("NATIVE_DATA_SURFACE_MUTATION_GRANT_FORBIDDEN",`${f}/capabilities/${m}`,{operation:n.get(E)}),o.has(E)||_("NATIVE_CAPABILITY_REFERENCE_MISSING",`${f}/capabilities`)}let s=e.authz.authenticatedUserRoleCode===void 0?"":V(e.authz.authenticatedUserRoleCode,"/config/authz/authenticatedUserRoleCode");s&&!i.has(s)&&_("NATIVE_AUTHENTICATED_USER_ROLE_REFERENCE_MISSING","/config/authz/authenticatedUserRoleCode");let c=new Set,r=0;for(let[u,l]of e.perspectives.entries()){let f=`/config/perspectives/${u}`,A=b(l,f);R(A,["code","name","description","roleCodes","capabilityCodes","default"],f,!0);let N=V(A.code,`${f}/code`);c.has(N)&&_("NATIVE_PERSPECTIVE_DUPLICATE",`${f}/code`),c.add(N),C(A.name,`${f}/name`,255);let I=v(A.roleCodes,`${f}/roleCodes`,20);I.length<1&&_("NATIVE_PERSPECTIVE_ROLE_REQUIRED",`${f}/roleCodes`),I.forEach((p,g)=>{i.has(p)||_("NATIVE_PERSPECTIVE_ROLE_MISSING",`${f}/roleCodes/${g}`)});let m=W(e.authz.roles.filter(p=>I.includes(p.code)).flatMap(p=>p.capabilities)),E=v(A.capabilityCodes,`${f}/capabilityCodes`,2e3);ee(m)!==ee(E)&&_("NATIVE_PERSPECTIVE_CAPABILITY_PROJECTION_MISMATCH",`${f}/capabilityCodes`),A.default===!0?r+=1:A.default!==void 0&&_("NATIVE_PERSPECTIVE_DEFAULT_INVALID",`${f}/default`)}r>1&&_("NATIVE_PERSPECTIVE_DEFAULT_DUPLICATE","/config/perspectives");for(let[u,l]of e.backend.operations.entries()){let f=b(l,`/config/backend/operations/${u}`);o.has(f.capability)||_("NATIVE_CAPABILITY_REFERENCE_MISSING",`/config/backend/operations/${u}/capability`)}let a=new Set,d=new Set;for(let[u,l]of e.frontend.routes.entries()){let f=`/config/frontend/routes/${u}`,A=b(l,f),N=V(A.code,`${f}/code`);a.has(N)&&_("NATIVE_ROUTE_DUPLICATE",`${f}/code`),a.add(N);let I=_e(A.path,`${f}/path`);d.has(I)&&_("NATIVE_ROUTE_PATH_DUPLICATE",`${f}/path`),d.add(I);let m=qn(A,f,e.appCode);m.capability&&!o.has(m.capability)&&_("NATIVE_CAPABILITY_REFERENCE_MISSING",`${f}/capability`);let E=A.access===void 0?void 0:b(A.access,`${f}/access`);for(let p of["allOf","anyOf"]){let g=E?.[p]===void 0?[]:S(E[p],`${f}/access/${p}`,50);for(let[O,y]of g.entries()){let T=Re(y,`${f}/access/${p}/${O}`,e.appCode);o.has(T)||_("NATIVE_CAPABILITY_REFERENCE_MISSING",`${f}/access/${p}/${O}`)}}}if(e.frontend.admin.access!==void 0){let u=Kt(e.frontend.admin.access,"/config/frontend/admin/access",e.appCode);for(let l of["allOf","anyOf"])for(let[f,A]of(u[l]||[]).entries())o.has(A)||_("NATIVE_CAPABILITY_REFERENCE_MISSING",`/config/frontend/admin/access/${l}/${f}`)}for(let[u,l]of e.frontend.routes.entries()){let f=b(l,`/config/frontend/routes/${u}`);f.parentCode&&!a.has(f.parentCode)&&_("NATIVE_ROUTE_PARENT_MISSING",`/config/frontend/routes/${u}/parentCode`)}}function sa(e){let t=new Set(e.authz.roles.map(d=>String(d.code))),o=e.authz.authenticatedUserRoleCode===void 0?"":V(e.authz.authenticatedUserRoleCode,"/config/authz/authenticatedUserRoleCode"),n=new Map(e.authz.scopeDimensions.map(d=>[String(d.code),{valueType:d.valueType==="uuid"?"uuid":"string",...d.valueSource?.resourceCode?{valueSourceResourceCode:String(d.valueSource.resourceCode)}:{}}])),i=new Set(n.keys()),s=new Map(e.data.resources.map((d,u)=>{let l=Me(d,`/config/data/resources/${u}`,e.appCode);return[l.code,new Map(l.schema.fields.map(f=>[String(f.code),f]))]}));for(let[d,u]of e.authz.scopeDimensions.entries()){let l=`/config/authz/scopeDimensions/${d}`,f=b(u,l);if(R(f,["code","name","resourceCode","valueType","hierarchyMode","valueSource"],l,!0),f.valueSource===void 0)continue;let A=b(f.valueSource,`${l}/valueSource`);R(A,["kind","resourceCode","labelField","enabledField"],`${l}/valueSource`,!0),A.kind!=="native_resource"&&_("NATIVE_SCOPE_VALUE_SOURCE_KIND_INVALID",`${l}/valueSource/kind`),f.valueType!=="uuid"&&_("NATIVE_SCOPE_VALUE_SOURCE_TYPE_INVALID",`${l}/valueType`);let N=J(A.resourceCode,`${l}/valueSource/resourceCode`),I=s.get(N);I||_("NATIVE_SCOPE_VALUE_SOURCE_RESOURCE_MISSING",`${l}/valueSource/resourceCode`);let m=K(A.labelField,`${l}/valueSource/labelField`);if(["text.short","text.long"].includes(String(I.get(m)?.type||""))||_("NATIVE_SCOPE_VALUE_SOURCE_LABEL_FIELD_INVALID",`${l}/valueSource/labelField`),A.enabledField!==void 0){let E=K(A.enabledField,`${l}/valueSource/enabledField`);I.get(E)?.type!=="boolean"&&_("NATIVE_SCOPE_VALUE_SOURCE_ENABLED_FIELD_INVALID",`${l}/valueSource/enabledField`)}}let c=new Set,r=new Set;for(let[d,u]of e.authz.scopeSources.entries()){let l=`/config/authz/scopeSources/${d}`,f=b(u,l);R(f,["code","name","resourceCode","subject","grants","operationField","enabledField","effectiveFromField","effectiveToField","failureMode"],l,!0);let A=V(f.code,`${l}/code`);c.has(A)&&_("NATIVE_SCOPE_SOURCE_DUPLICATE",`${l}/code`),c.add(A),C(f.name,`${l}/name`,255);let N=J(f.resourceCode,`${l}/resourceCode`),I=s.get(N);I||_("NATIVE_SCOPE_SOURCE_RESOURCE_MISSING",`${l}/resourceCode`);let m=b(f.subject,`${l}/subject`),E=C(m.type,`${l}/subject/type`,32);R(m,E==="role_membership"?["type","userIdField","roleCode"]:["type","userIdField"],`${l}/subject`),["user","role_membership"].includes(E)||_("NATIVE_SCOPE_SOURCE_SUBJECT_INVALID",`${l}/subject/type`);let p=ot(m.userIdField,I);An(p)||_("NATIVE_SCOPE_SOURCE_SUBJECT_PATH_INVALID",`${l}/subject/userIdField`),E==="role_membership"&&!t.has(String(m.roleCode))&&_("NATIVE_ROLE_REFERENCE_MISSING",`${l}/subject/roleCode`);let g=new Set;for(let[O,y]of S(f.grants,`${l}/grants`,100).entries()){let T=`${l}/grants/${O}`,h=b(y,T);R(h,["dimensionCode","valueField","parentValueField"],T,!0);let D=V(h.dimensionCode,`${T}/dimensionCode`);(!i.has(D)||g.has(D))&&_("NATIVE_SCOPE_SOURCE_DIMENSION_INVALID",`${T}/dimensionCode`),g.add(D),f.failureMode==="last_known_good"&&r.add(D);for(let F of["valueField","parentValueField"]){if(h[F]===void 0)continue;let k=ot(h[F],I);So(k,n.get(D),s)||_("NATIVE_SCOPE_SOURCE_GRANT_PATH_INVALID",`${T}/${F}`)}}g.size===0&&_("NATIVE_SCOPE_SOURCE_GRANT_REQUIRED",`${l}/grants`),["strict","last_known_good"].includes(f.failureMode)||_("NATIVE_SCOPE_SOURCE_FAILURE_MODE_INVALID",`${l}/failureMode`);for(let O of["operationField","enabledField","effectiveFromField","effectiveToField"]){if(f[O]===void 0)continue;let y=K(f[O],`${l}/${O}`);I.has(y)||_("NATIVE_SCOPE_SOURCE_FIELD_MISSING",`${l}/${O}`)}}aa(e,t,s,o);let a=new Set;for(let[d,u]of e.authz.dataPolicies.entries()){let l=`/config/authz/dataPolicies/${d}`,f=b(u,l);R(f,["code","name","resourceCode","unrestrictedRoleCodes","operations","matchMode","rules","readExpression","writeBoundary"],l,!0);let A=V(f.code,`${l}/code`);a.has(A)&&_("NATIVE_DATA_POLICY_DUPLICATE",`${l}/code`),a.add(A);let N=f.readExpression!==void 0,I=v(f.operations||[],`${l}/operations`,4);f.operations!==void 0&&(I.length===0||I.some(y=>!["read","create","update","delete"].includes(y)))&&_("NATIVE_DATA_POLICY_OPERATIONS_INVALID",`${l}/operations`),["AND","OR"].includes(f.matchMode)||_("NATIVE_DATA_POLICY_MATCH_MODE_INVALID",`${l}/matchMode`),N&&f.operations!==void 0&&_("NATIVE_DATA_POLICY_READ_EXPRESSION_OPERATIONS_FORBIDDEN",`${l}/operations`);let m=e.data.resources.find(y=>y.dataPolicyCode===A),E=f.resourceCode||m?.code,p=E?s.get(J(E,`${l}/resourceCode`)):void 0;N&&!p&&_("NATIVE_DATA_POLICY_RESOURCE_MISSING",`${l}/resourceCode`);let g=v(f.unrestrictedRoleCodes||[],`${l}/unrestrictedRoleCodes`,100);f.unrestrictedRoleCodes!==void 0&&g.length===0&&_("NATIVE_DATA_POLICY_UNRESTRICTED_ROLES_INVALID",`${l}/unrestrictedRoleCodes`);for(let y of g)t.has(y)||_("NATIVE_ROLE_REFERENCE_MISSING",`${l}/unrestrictedRoleCodes`);let O;try{let y=S(f.rules,`${l}/rules`,100).map((T,h)=>({rule:b(T,`${l}/rules/${h}`),pointer:`${l}/rules/${h}`}));y.length===0?(!N||f.matchMode!=="AND"||f.writeBoundary!=="capability_only")&&_("NATIVE_DATA_POLICY_WRITE_BOUNDARY_REQUIRED",l):f.writeBoundary!==void 0&&_("NATIVE_DATA_POLICY_WRITE_BOUNDARY_INVALID",`${l}/writeBoundary`),O=[...y],N&&(O.push(...xt(f.readExpression,`${l}/readExpression`)),ni(f.readExpression,`${l}/readExpression`))}catch(y){throw y instanceof ft&&_(y.code,y.pointer),y}for(let{rule:y,pointer:T}of O){R(y,["subject","dimensionCode","relationCode","resourceCode","field","roleCodes","operation","valuePath","emptyMatchesAll","operator","value","operand"],T,!0);let h=K(y.field,`${T}/field`),D=p?.get(h);N&&!D&&_("NATIVE_DATA_POLICY_FIELD_MISSING",`${T}/field`);for(let H of v(y.roleCodes||[],`${T}/roleCodes`,100))t.has(H)||_("NATIVE_ROLE_REFERENCE_MISSING",`${T}/roleCodes`);let F=String(y.operator||""),k=y.operand==="db_now",U=["is_null","is_not_null"].includes(F),j=["eq","not_eq","in","not_in"].includes(F),ie=!k&&(y.operator!==void 0||y.value!==void 0);if([y.subject==="current_user"?"current_user":"",typeof y.dimensionCode=="string"?"dimension":"",typeof y.relationCode=="string"?"relationship":"",ie?"constant":"",k?"db_now":""].filter(Boolean).length!==1&&_("NATIVE_DATA_POLICY_RULE_SOURCE_INVALID",T),y.subject!==void 0&&y.subject!=="current_user"&&_("NATIVE_DATA_POLICY_SUBJECT_INVALID",`${T}/subject`),ie){if(!j&&!U&&_("NATIVE_DATA_POLICY_OPERATOR_INVALID",`${T}/operator`),["in","not_in"].includes(F)){let H=S(y.value,`${T}/value`,100).map((be,ae)=>C(be,`${T}/value/${ae}`,2048));(H.length===0||new Set(H).size!==H.length)&&_("NATIVE_DATA_POLICY_VALUE_INVALID",`${T}/value`)}else["eq","not_eq"].includes(F)?C(y.value,`${T}/value`,2048):(y.value!==void 0||y.operand!==void 0)&&_("NATIVE_DATA_POLICY_VALUE_INVALID",`${T}/value`);for(let H of["operation","valuePath","emptyMatchesAll","resourceCode","operand"])y[H]!==void 0&&_("NATIVE_DATA_POLICY_CONSTANT_RULE_INVALID",`${T}/${H}`)}if(k){(!["lt","lte","gt","gte"].includes(F)||y.value!==void 0||D?.type!=="datetime")&&_("NATIVE_DATA_POLICY_DB_NOW_INVALID",T);for(let H of["operation","valuePath","emptyMatchesAll","resourceCode","value"])y[H]!==void 0&&_("NATIVE_DATA_POLICY_DB_NOW_INVALID",`${T}/${H}`)}y.dimensionCode&&!i.has(y.dimensionCode)&&_("NATIVE_SCOPE_DIMENSION_MISSING",`${T}/dimensionCode`),r.has(String(y.dimensionCode||""))&&y.operation!=="read"&&_("NATIVE_SCOPE_SOURCE_LAST_KNOWN_GOOD_UNSAFE",`${T}/operation`)}}for(let[d,u]of e.data.resources.entries()){let l=b(u,`/config/data/resources/${d}`);l.dataPolicyCode&&!a.has(l.dataPolicyCode)&&_("NATIVE_DATA_POLICY_REFERENCE_MISSING",`/config/data/resources/${d}/dataPolicyCode`)}}function ra(e){try{io(e.data.resources,"/config/data/resources")}catch(t){throw t instanceof Ee&&_(t.code,t.pointer),t}}function aa(e,t,o,n){let i=new Set;for(let[s,c]of e.authz.roleMembershipSources.entries()){let r=`/config/authz/roleMembershipSources/${s}`,a=b(c,r);R(a,["code","name","resourceCode","userIdField","roleCode","enabledField","effectiveFromField","effectiveToField","failureMode"],r,!0);let d=V(a.code,`${r}/code`);d.length>100&&_("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_CODE_INVALID",`${r}/code`),i.has(d)&&_("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_DUPLICATE",`${r}/code`),i.add(d),C(a.name,`${r}/name`,255);let u=pi(a.resourceCode,`${r}/resourceCode`,o);mi(a.userIdField,`${r}/userIdField`,u),t.has(String(a.roleCode||""))||_("NATIVE_ROLE_REFERENCE_MISSING",`${r}/roleCode`),n&&a.roleCode===n&&_("NATIVE_AUTHENTICATED_USER_ROLE_SOURCE_CONFLICT",`${r}/roleCode`),_i(a,r,u)}for(let[s,c]of e.authz.relationshipGrantSources.entries()){let r=`/config/authz/relationshipGrantSources/${s}`,a=b(c,r);R(a,["code","name","resourceCode","subject","relationCode","targetResourceCode","resourceIdField","operations","enabledField","effectiveFromField","effectiveToField","failureMode"],r,!0);let d=V(a.code,`${r}/code`);d.length>100&&_("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_CODE_INVALID",`${r}/code`),i.has(d)&&_("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_DUPLICATE",`${r}/code`),i.add(d),C(a.name,`${r}/name`,255);let u=pi(a.resourceCode,`${r}/resourceCode`,o),l=b(a.subject,`${r}/subject`),f=C(l.type,`${r}/subject/type`,32);R(l,f==="role_membership"?["type","userIdField","roleCode"]:["type","userIdField"],`${r}/subject`),["user","role_membership"].includes(f)||_("NATIVE_AUTHORIZATION_PROJECTION_SUBJECT_INVALID",`${r}/subject/type`),mi(l.userIdField,`${r}/subject/userIdField`,u),f==="role_membership"&&!t.has(String(l.roleCode||""))&&_("NATIVE_ROLE_REFERENCE_MISSING",`${r}/subject/roleCode`),V(a.relationCode,`${r}/relationCode`);let A=J(a.targetResourceCode,`${r}/targetResourceCode`);o.has(A)||_("NATIVE_AUTHORIZATION_PROJECTION_TARGET_RESOURCE_MISSING",`${r}/targetResourceCode`);let N=ot(a.resourceIdField,u),I=N?.field.type==="resource-ref.single"&&N.valuePath==="value"&&N.field.source?.resourceCode===A;(a.resourceIdField==="id"?A!==String(a.resourceCode):!I)&&_("NATIVE_AUTHORIZATION_PROJECTION_RESOURCE_ID_FIELD_INVALID",`${r}/resourceIdField`);let m=v(a.operations,`${r}/operations`,20);(m.length===0||m.some(E=>E.length>64||!/^[A-Za-z0-9][A-Za-z0-9:._*-]{0,63}$/.test(E)))&&_("NATIVE_AUTHORIZATION_PROJECTION_OPERATIONS_INVALID",`${r}/operations`),_i(a,r,u)}}function pi(e,t,o){let n=J(e,t),i=o.get(n);return i||_("NATIVE_AUTHORIZATION_PROJECTION_RESOURCE_MISSING",t),i}function mi(e,t,o){let n=ot(e,o);An(n)||_("NATIVE_AUTHORIZATION_PROJECTION_USER_FIELD_INVALID",t)}function _i(e,t,o){if(e.failureMode!=="strict"&&_("NATIVE_AUTHORIZATION_PROJECTION_FAILURE_MODE_INVALID",`${t}/failureMode`),e.enabledField!==void 0){let n=K(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 i=K(e[n],`${t}/${n}`);["date","datetime"].includes(String(o.get(i)?.type))||_("NATIVE_AUTHORIZATION_PROJECTION_EFFECTIVE_FIELD_INVALID",`${t}/${n}`)}}function ca(e){let t=new Set,o=new Set;e.forEach((n,i)=>{let s=`/config/backend/secrets/${i}`,c=b(n,s);R(c,["name","env","description","required","exposure"],s,!0);let r=C(c.name,`${s}/name`,128),a=C(c.env,`${s}/env`,128);ar.test(r)||_("NATIVE_SECRET_NAME_INVALID",`${s}/name`),(!cr.test(a)||a.startsWith("OPENXIANGDA_")||["NODE_ENV","PORT"].includes(a))&&_("NATIVE_SECRET_ENV_INVALID",`${s}/env`),t.has(r)&&_("NATIVE_SECRET_NAME_DUPLICATE",`${s}/name`),o.has(a)&&_("NATIVE_SECRET_ENV_DUPLICATE",`${s}/env`),t.add(r),o.add(a),x(c.exposure,"active_only",`${s}/exposure`),c.required!==void 0&&Xe(c.required,`${s}/required`),c.description!==void 0&&Jn(c.description,`${s}/description`,2e3)})}function da(e){let t=new Set,o=new Map,n=new Map(e.data.resources.map(A=>[String(A.code),A])),i=new Map(e.frontend.routes.map((A,N)=>{let I=b(A,`/config/frontend/routes/${N}`);return[V(I.code,`/config/frontend/routes/${N}/code`),I]}));for(let[A,N]of e.workflows.definitions.entries()){let I=`/config/workflows/definitions/${A}`,m=b(N,I);if(R(m,["version","definition","launch"],I,["detailRouteCode"]),Vi(m.launch,`${I}/launch`),m.detailRouteCode!==void 0){let y=ki(m.detailRouteCode,`${I}/detailRouteCode`);for(let[T,h,D]of[["desktop",y.desktop,["admin","user"]],["mobile",y.mobile,["user"]]]){let F=`${I}/detailRouteCode/${T}`,k=i.get(h);k||_("NATIVE_WORKFLOW_DETAIL_ROUTE_MISSING",F),D.some(ie=>ie===k.surface)||_("NATIVE_WORKFLOW_DETAIL_ROUTE_SURFACE_INVALID",F);let U=_e(k.path,F),j=[...U.matchAll(/:([A-Za-z][A-Za-z0-9_]*)/g)].map(ie=>ie[1]);(U.includes("*")||j.length!==1||j[0]!=="instanceId")&&_("NATIVE_WORKFLOW_DETAIL_ROUTE_PATH_INVALID",F)}}let E=b(m.definition,`${I}/definition`),p=`${E.code}:${He(m.version,`${I}/version`)}`;t.has(p)&&_("NATIVE_WORKFLOW_DEFINITION_DUPLICATE",I),t.add(p),ua(E,`${I}/definition`),la(E.subject,n,`${I}/definition/subject`);let g=Fn(E,new Map((n.get(E.subject.resourceCode)?.schema.fields||[]).map(y=>[y.code,{...n.get(E.subject.resourceCode)?.surface?.fields?.[y.code],...y,system:["id","revision","createdAt","updatedAt","createdBy","updatedBy"].includes(y.code)}])));g.length&&_(g[0],`${I}/definition/taskPages`);let O=Lo(E,{appCode:e.appCode,capabilities:e.authz.capabilities.map(y=>y.code),fields:new Map((n.get(E.subject.resourceCode)?.schema.fields||[]).map(y=>[y.code,y]))});O.length&&_("NATIVE_WORKFLOW_INSTANCE_COMMAND_POLICY_INVALID",`${I}/definition/instanceCommands`,{errors:O}),E.title===E.code&&_("NATIVE_WORKFLOW_USER_TITLE_REQUIRED",`${I}/definition/title`),o.set(p,E)}let s=new Set,c=new Map;for(let[A,N]of e.workflows.bindings.entries()){let I=b(N,`/config/workflows/bindings/${A}`),m=b(I.binding,`/config/workflows/bindings/${A}/binding`),E=`${m.workflowCode}:${He(I.version,`/config/workflows/bindings/${A}/version`)}`;s.has(E)&&_("NATIVE_WORKFLOW_BINDING_DUPLICATE",`/config/workflows/bindings/${A}`),s.add(E),fa(m,`/config/workflows/bindings/${A}/binding`),c.set(E,m)}let r=new Set,a=new Map;for(let[A,N]of e.workflows.activations.entries()){let I=`/config/workflows/activations/${A}`,m=b(N,I);R(m,["workflowCode","definitionVersion","bindingVersion","acceptedCommandDeactivationPolicy"],I,["environmentKey"]);let E=V(m.workflowCode,`${I}/workflowCode`);r.has(E)&&_("NATIVE_WORKFLOW_ACTIVATION_DUPLICATE",I),r.add(E);let p=`${E}:${He(m.definitionVersion,`${I}/definitionVersion`)}`,g=`${E}:${He(m.bindingVersion,`${I}/bindingVersion`)}`;t.has(p)||_("NATIVE_WORKFLOW_DEFINITION_REFERENCE_MISSING",`${I}/definitionVersion`),s.has(g)||_("NATIVE_WORKFLOW_BINDING_REFERENCE_MISSING",`${I}/bindingVersion`);let O=o.get(p),y=c.get(g),T=wn(O,y);T.length&&_(T[0],I),(!["finish-pinned","cancel-on-deactivate"].includes(m.acceptedCommandDeactivationPolicy)||m.acceptedCommandDeactivationPolicy!==O.acceptedCommandDeactivationPolicy)&&_("NATIVE_WORKFLOW_COMMAND_DEACTIVATION_POLICY_MISMATCH",`${I}/acceptedCommandDeactivationPolicy`),pa(O,y,`/config/workflows/activations/${A}`),a.set(E,y)}let d=Zo([...a.values()]);d.length&&_(d[0],"/config/workflows/activations");let u=new Set;e.workflows.providers.forEach((A,N)=>{let I=`/config/workflows/providers/${N}`,m=b(A,I);R(m,["code","endpointPath","timeoutMs"],I,!0);let E=V(m.code,`${I}/code`);u.has(E)&&_("NATIVE_WORKFLOW_PROVIDER_DUPLICATE",`${I}/code`),u.add(E),_e(m.endpointPath,`${I}/endpointPath`),m.timeoutMs!==void 0&&te(m.timeoutMs,`${I}/timeoutMs`,100,1e4)});for(let[A,N]of a.entries())for(let[I,m]of Object.entries(b(N.bindings,"/config/workflows/bindings/*/binding/bindings"))){let E=b(m,`/config/workflows/${A}/bindings/${I}`);E.provider==="application_provider"&&!u.has(E.providerCode)&&_("NATIVE_WORKFLOW_PROVIDER_REFERENCE_MISSING",`/config/workflows/${A}/bindings/${I}/providerCode`)}let l=new Set(e.authz.roles.map(A=>A.code)),f=new Set;e.workflows.editableParameters.forEach((A,N)=>{let I=`/config/workflows/editableParameters/${N}`,m=b(A,I);R(m,["code","workflowCode","bindingKey","label","valueType","required","allowedRoleCodes","allowedProviderCodes","maxItems"],I,!0);let E=V(m.code,`${I}/code`);f.has(E)&&_("NATIVE_WORKFLOW_EDITABLE_PARAMETER_DUPLICATE",`${I}/code`),f.add(E);let p=Gt(m.workflowCode,`${I}/workflowCode`),g=Wt(m.bindingKey,`${I}/bindingKey`),O=a.get(p);(!O||!b(O.bindings,`${I}/bindingKey`)[g])&&_("NATIVE_WORKFLOW_EDITABLE_BINDING_MISSING",`${I}/bindingKey`),C(m.label,`${I}/label`,255),["role_code","user_ids","provider_code"].includes(m.valueType)||_("NATIVE_WORKFLOW_EDITABLE_VALUE_TYPE_INVALID",`${I}/valueType`);for(let y of v(m.allowedRoleCodes||[],`${I}/allowedRoleCodes`,100))l.has(y)||_("NATIVE_ROLE_REFERENCE_MISSING",`${I}/allowedRoleCodes`);for(let y of v(m.allowedProviderCodes||[],`${I}/allowedProviderCodes`,100))u.has(y)||_("NATIVE_WORKFLOW_PROVIDER_REFERENCE_MISSING",`${I}/allowedProviderCodes`);m.required!==void 0&&Xe(m.required,`${I}/required`),m.maxItems!==void 0&&te(m.maxItems,`${I}/maxItems`,1,200)})}function la(e,t,o){let n=b(e,o);R(n,["resourceCode","factProjection"],o,["summaryFields"]);let i=J(n.resourceCode,`${o}/resourceCode`),s=t.get(i);s||_("NATIVE_WORKFLOW_SUBJECT_RESOURCE_MISSING",`${o}/resourceCode`);let c=new Set(S(b(s.schema,`${o}/resourceCode`).fields,`${o}/resourceCode`,500).map((d,u)=>K(b(d,`${o}/resourceCode/${u}`).code,`${o}/resourceCode/${u}`))),r=b(n.factProjection,`${o}/factProjection`),a=Object.entries(r);(a.length<1||a.length>64)&&_("NATIVE_WORKFLOW_SUBJECT_FACT_PROJECTION_INVALID",`${o}/factProjection`);for(let[d,u]of a){ur.test(d)||_("NATIVE_WORKFLOW_SUBJECT_FACT_KEY_INVALID",`${o}/factProjection/${d}`);let l=K(u,`${o}/factProjection/${d}`);c.has(l)||_("NATIVE_WORKFLOW_SUBJECT_FIELD_MISSING",`${o}/factProjection/${d}`)}if(n.summaryFields!==void 0){let d=v(n.summaryFields,`${o}/summaryFields`,fr).map((N,I)=>K(N,`${o}/summaryFields/${I}`)),u=t.get(i),l=u.surface&&typeof u.surface=="object"&&!Array.isArray(u.surface)?u.surface:{},f=l.fields&&typeof l.fields=="object"&&!Array.isArray(l.fields)?l.fields:{},A=new Map(S(b(u.schema,`${o}/resourceCode`).fields,`${o}/resourceCode`,500).map((N,I)=>{let m=b(N,`${o}/resourceCode/${I}`);return[String(m.code),m]}));for(let[N,I]of d.entries()){let m=A.get(I),E=f[I],p=String(m?.type||""),g=m?.maxLength;(!m||m.system===!0||E&&typeof E=="object"&&!Array.isArray(E)&&E.system===!0||["id","revision","created_by","updated_by","created_at","updated_at"].includes(I)||!mr.has(p)||p==="text.long"&&typeof g=="number"&&Number.isFinite(g)&&g>pr)&&_("NATIVE_WORKFLOW_SUBJECT_SUMMARY_FIELDS_INVALID",`${o}/summaryFields/${N}`)}}}function ua(e,t){R(e,["schemaVersion","code","title","subject","acceptedCommandDeactivationPolicy","startAt","inputSchema","nodes"],t,["organizationContext","instanceCommands","readability","taskPages"]),x(e.schemaVersion,"openxiangda.workflow-definition/v2",`${t}/schemaVersion`),Gt(e.code,`${t}/code`),C(e.title,`${t}/title`,255),["finish-pinned","cancel-on-deactivate"].includes(e.acceptedCommandDeactivationPolicy)||_("NATIVE_WORKFLOW_COMMAND_DEACTIVATION_POLICY_REQUIRED",`${t}/acceptedCommandDeactivationPolicy`);let o=b(e.nodes,`${t}/nodes`),n=Object.keys(o);(n.length===0||n.length>200)&&_("NATIVE_WORKFLOW_NODE_COUNT_INVALID",`${t}/nodes`);let i=C(e.startAt,`${t}/startAt`,128),s=qo(e);s.length&&_(s[0],`${t}/readability`);let c=wn(e);c.length&&_(c[0],`${t}/nodes`);let r=Dn(e);r.length&&_(r[0],`${t}/nodes`);let a=Fn(e);a.length&&_(a[0],`${t}/taskPages`);let d=Vt(e);d.length&&_(d[0],`${t}/nodes`),o[i]||_("NATIVE_WORKFLOW_START_NODE_MISSING",`${t}/startAt`);let u=new Map;for(let[N,I]of Object.entries(o)){let m=`${t}/nodes/${N}`,E=b(I,m);x(E.id,N,`${m}/id`),["approval","condition","end","cc","action"].includes(E.kind)||_("NATIVE_WORKFLOW_NODE_KIND_INVALID",`${m}/kind`);let p=[];if(E.kind==="approval"){C(E.title,`${m}/title`,255),Wt(E.binding,`${m}/binding`),["single","any","all","sequence"].includes(E.mode)||_("NATIVE_WORKFLOW_APPROVAL_MODE_INVALID",`${m}/mode`),p.push(C(E.onApprove,`${m}/onApprove`,128),C(E.onReject,`${m}/onReject`,128));for(let g of v(E.returnTargets||[],`${m}/returnTargets`,200))o[g]||_("NATIVE_WORKFLOW_TARGET_MISSING",`${m}/returnTargets`);for(let g of v(E.allowedOperations||[],`${m}/allowedOperations`,20))gr.has(g)||_("NATIVE_WORKFLOW_OPERATION_INVALID",`${m}/allowedOperations`)}else if(E.kind==="action")p.push(C(E.next,`${m}/next`,128));else if(E.kind==="cc")C(E.title,`${m}/title`,255),Wt(E.binding,`${m}/binding`),p.push(C(E.next,`${m}/next`,128));else if(E.kind==="condition"){let g=S(E.branches,`${m}/branches`,100);g.length===0&&_("NATIVE_WORKFLOW_BRANCH_REQUIRED",`${m}/branches`),g.forEach((O,y)=>{let T=b(O,`${m}/branches/${y}`);pt(T.when,`${m}/branches/${y}/when`,0),p.push(C(T.target,`${m}/branches/${y}/target`,128))}),p.push(C(E.otherwise,`${m}/otherwise`,128))}else C(E.title,`${m}/title`,255),C(E.outcome,`${m}/outcome`,128);for(let g of p)o[g]||_("NATIVE_WORKFLOW_TARGET_MISSING",m);u.set(N,p)}let l=new Set,f=new Set,A=N=>{if(f.has(N)&&_("NATIVE_WORKFLOW_CYCLE_FORBIDDEN",`${t}/nodes/${N}`),!l.has(N)){l.add(N),f.add(N);for(let I of u.get(N)||[])A(I);f.delete(N)}};A(i),l.size!==n.length&&_("NATIVE_WORKFLOW_NODE_UNREACHABLE",`${t}/nodes`)}function pt(e,t,o){o>20&&_("NATIVE_WORKFLOW_EXPRESSION_DEPTH_EXCEEDED",t);let n=b(e,t),i=C(n.op,`${t}/op`,16);if(i!=="literal"){if(i==="path"){let s=C(n.path,`${t}/path`,255);(!/^[A-Za-z][A-Za-z0-9_.-]{0,254}$/.test(s)||s.split(".").some(c=>["__proto__","constructor","prototype"].includes(c)))&&_("NATIVE_WORKFLOW_EXPRESSION_PATH_INVALID",`${t}/path`);return}if(["eq","neq","gt","gte","lt","lte","in","contains"].includes(i)){pt(n.left,`${t}/left`,o+1),pt(n.right,`${t}/right`,o+1);return}if(["and","or"].includes(i)){let s=S(n.values,`${t}/values`,100);s.length===0&&_("NATIVE_WORKFLOW_EXPRESSION_EMPTY",`${t}/values`),s.forEach((c,r)=>pt(c,`${t}/values/${r}`,o+1));return}if(["not","exists"].includes(i)){pt(n.value,`${t}/value`,o+1);return}_("NATIVE_WORKFLOW_EXPRESSION_OPERATOR_INVALID",`${t}/op`)}}function fa(e,t){x(e.schemaVersion,"openxiangda.workflow-binding/v2",`${t}/schemaVersion`),Gt(e.workflowCode,`${t}/workflowCode`);let o=b(e.bindings,`${t}/bindings`);Object.keys(o).length>200&&_("NATIVE_WORKFLOW_BINDING_LIMIT_EXCEEDED",`${t}/bindings`);for(let[n,i]of Object.entries(o)){Wt(n,`${t}/bindings/${n}`);let s=b(i,`${t}/bindings/${n}`),c=C(s.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(c)||_("NATIVE_WORKFLOW_BINDING_PROVIDER_INVALID",`${t}/bindings/${n}/provider`),c==="fixed_users"&&S(s.users,`${t}/bindings/${n}/users`,200).length===0&&_("NATIVE_WORKFLOW_BINDING_USERS_REQUIRED",`${t}/bindings/${n}/users`),["input_users","form_field_users"].includes(c)&&C(s.inputPath,`${t}/bindings/${n}/inputPath`,255),["app_role","app_role_in_scope","initiator_select"].includes(c)&&V(s.roleCode,`${t}/bindings/${n}/roleCode`),c==="department_supervisor"&&C(s.departmentIdFrom,`${t}/bindings/${n}/departmentIdFrom`,255),c==="application_provider"&&V(s.providerCode,`${t}/bindings/${n}/providerCode`),s.routing!==void 0){let r=Lt(s.routing);r.length&&_(r[0],`${t}/bindings/${n}/routing`)}}}function pa(e,t,o){x(t.workflowCode,e.code,`${o}/workflowCode`);let n=b(t.bindings,`${o}/bindings`),i=Dn(e,t);i.length&&_(i[0],o);let s=Vt(e,t);s.length&&_(s[0],o);for(let[c,r]of Object.entries(b(e.nodes,`${o}/nodes`))){let a=b(r,`${o}/nodes/${c}`);["approval","cc"].includes(a.kind)&&!n[a.binding]&&_("NATIVE_WORKFLOW_BINDING_REFERENCE_MISSING",`${o}/nodes/${c}/binding`)}}function ma(e,t,o){let n=b(t.routeManifest,"/contracts/routeManifest"),i=b(e.routeManifest,"/contracts/routeManifest"),s=new Map;for(let u of S(o.data?.resources,"/config/data/resources",100)){let l=b(u,"/config/data/resources");s.set(String(l.code||""),l)}let c=new Set(S(i.routes,"/contracts/routeManifest/routes",1e3).map(u=>String(b(u,"/contracts/routeManifest/routes").code||""))),r=[];for(let u of S(n.routes,"/contracts/routeManifest/routes",1e3)){let l=b(u,"/contracts/routeManifest/routes"),f=String(l.kind||"");if(f!=="resource-records"&&f!=="resource-submit")continue;let A=String(l.resourceCode||""),N=s.get(A);N||_("NATIVE_ROUTE_MANIFEST_RESOURCE_UNKNOWN","/contracts/routeManifest/routes");let m=`user.${A}.${f==="resource-records"?"records":"submit"}`;x(String(l.code||""),m,"/contracts/routeManifest/routes/code");let E=f==="resource-records"?"read":"create",p=String(b(N.capabilities,"/config/data/resources/capabilities")[E]||"");for(let g of["desktop","mobile"]){let O=b(l[g],`/contracts/routeManifest/routes/${g}`),y=g==="mobile"?"/m/my/":"/my/",T=f==="resource-records"?`${y}${A}`:`${y}${A}/submit`;x(String(O.path||""),T,`/contracts/routeManifest/routes/${g}/path`),x(String(O.capability||""),p,`/contracts/routeManifest/routes/${g}/capability`),x(String(O.routeCode||""),`${m}.${g}`,`/contracts/routeManifest/routes/${g}/routeCode`)}(c.has(m)||r.some(g=>String(g.code)===m))&&_("NATIVE_ROUTE_MANIFEST_DUPLICATE","/contracts/routeManifest/routes/code"),r.push(l)}if(!r.length)return;i.routes=S([...i.routes,...r],"/contracts/routeManifest/routes",1e3).sort((u,l)=>ue(String(b(u,"x").code||""),String(b(l,"x").code||"")));let a=String(b(n.rootEntry,"x").code||"");if(r.find(u=>String(u.code)===a&&u.kind==="resource-records")){let u=b(n.rootEntry,"x");i.rootEntry={code:a,desktop:String(u.desktop||""),mobile:String(u.mobile||"")}}i.digest=X({schemaVersion:i.schemaVersion,appCode:i.appCode,devicePolicy:i.devicePolicy,rootEntry:i.rootEntry,authentication:i.authentication,routes:i.routes})}function Me(e,t,o){let n=b(e,t);R(n,["schemaVersion","appCode","code","name","schema","surface","invariants","decimalReservationLifecycle","uniqueKeys","capabilities","dataPolicyCode","fieldPolicies"],t,!0),x(n.schemaVersion,"openxiangda.data-resource/v2",`${t}/schemaVersion`),x(n.appCode,o,`${t}/appCode`);let i=J(n.code,`${t}/code`),s=C(n.name,`${t}/name`,255),c=b(n.schema,`${t}/schema`);R(c,["fields"],`${t}/schema`);let r,a,d,u;try{d=mn(n.decimalReservationLifecycle,`${t}/decimalReservationLifecycle`),r=Zt(c.fields,`${t}/schema/fields`),u=$o(n.uniqueKeys,r,`${t}/uniqueKeys`),a=so(n.invariants,r,`${t}/invariants`),dn(n.surface,r,`${t}/surface`)}catch(N){throw(N instanceof Ee||N instanceof qe||N instanceof st)&&_(N.code,N.pointer),N}let l=new Set(r.map(N=>N.code)),f=b(n.capabilities,`${t}/capabilities`);R(f,["read","create","update","delete"],`${t}/capabilities`);let A=b(n.fieldPolicies,`${t}/fieldPolicies`);for(let[N,I]of Object.entries(A)){!l.has(N)&&!Ze(N)&&_("NATIVE_DATA_FIELD_POLICY_FIELD_MISSING",`${t}/fieldPolicies/${N}`);let m=`${t}/fieldPolicies/${N}`,E=b(I,m);Ze(N)&&(R(E,["read"],m,!0),(!Array.isArray(E.read)||E.read.length>20||E.read.some(p=>typeof p!="string"||!p.trim())||new Set(E.read).size!==E.read.length)&&_("NATIVE_DATA_AUDIT_READ_POLICY_INVALID",`${m}/read`)),R(E,["read","create","update","mask"],m,!0),E.mask!==void 0&&!["omit","null"].includes(E.mask)&&_("NATIVE_DATA_FIELD_POLICY_MASK_INVALID",`${m}/mask`)}return{...n,code:i,name:s,schema:{fields:r},...n.invariants===void 0?{}:{invariants:a},...d?{decimalReservationLifecycle:d}:{},...u!==void 0?{uniqueKeys:u}:{},capabilities:f,fieldPolicies:A}}function Fi(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 gi(e,t,o,n){let i=e.toString("utf8"),s;try{s=JSON.parse(i)}catch{_(o,t)}let c=b(s,t);return ee(c)!==i&&_(n,t),c}function Ai(e,t){let o=0,n=(i,s,c)=>{if(o+=1,o>Nr&&_("NATIVE_ARTIFACT_NODE_LIMIT_EXCEEDED",s),c>Ir&&_("NATIVE_ARTIFACT_DEPTH_LIMIT_EXCEEDED",s),typeof i=="string"){Buffer.byteLength(i)>xn&&_("NATIVE_ARTIFACT_STRING_LIMIT_EXCEEDED",s);return}if(Array.isArray(i)){i.forEach((r,a)=>n(r,`${s}/${a}`,c+1));return}if(!(!i||typeof i!="object"))for(let[r,a]of Object.entries(i))["__proto__","prototype","constructor"].includes(r)&&_("NATIVE_ARTIFACT_DANGEROUS_KEY",`${s}/${r}`),_a(r)&&_("NATIVE_ARTIFACT_RUNTIME_FIELD_FORBIDDEN",`${s}/${r}`),n(a,`${s}/${r}`,c+1)};n(e,t,0)}function _a(e){return["environmentKey","environmentId","secretValue","ciphertext","oauthClient","oauthClientId","oauthClientSecret","signingSecret","kubernetesNamespace","nodePort","productionUrl"].includes(e)}function Ye(e){return{value:e,digest:X(e)}}function Ei(e,t,o,n){typeof e!="string"&&!Buffer.isBuffer(e)&&!(e instanceof Uint8Array)&&_("NATIVE_ARTIFACT_BYTES_REQUIRED",o);let i=Buffer.isBuffer(e)?e:Buffer.from(e);return i.byteLength===0&&_("NATIVE_ARTIFACT_EMPTY",o),i.byteLength>t&&_(n,o),i}function Ii(e,t,o,n){let i=Ut.createHash("sha256").update(e).digest("hex");Ut.timingSafeEqual(Buffer.from(i),Buffer.from(t))||_(n,o)}function b(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&_("NATIVE_OBJECT_REQUIRED",t),e}function S(e,t,o){return Array.isArray(e)||_("NATIVE_ARRAY_REQUIRED",t),e.length>o&&_("NATIVE_ARRAY_LIMIT_EXCEEDED",t),e}function v(e,t,o){let n=S(e,t,o).map((i,s)=>C(i,`${t}/${s}`,255));return new Set(n).size!==n.length&&_("NATIVE_ARRAY_DUPLICATE",t),n}function C(e,t,o){return(typeof e!="string"||e.length===0||e.length>o)&&_("NATIVE_STRING_INVALID",t),e}function Jn(e,t,o){return(typeof e!="string"||e.length>o)&&_("NATIVE_STRING_INVALID",t),e}function V(e,t){let o=C(e,t,128);return or.test(o)||_("NATIVE_CODE_INVALID",t),o}function J(e,t){let o=C(e,t,64);return sr.test(o)||_("NATIVE_RESOURCE_CODE_INVALID",t),o}function K(e,t){let o=C(e,t,63);return rr.test(o)||_("NATIVE_FIELD_CODE_INVALID",t),o}function Gt(e,t){let o=C(e,t,128);return dr.test(o)||_("NATIVE_WORKFLOW_CODE_INVALID",t),o}function Wt(e,t){let o=C(e,t,128);return lr.test(o)||_("NATIVE_WORKFLOW_BINDING_CODE_INVALID",t),o}function Re(e,t,o){let n=C(e,t,255);return nr.test(n)||_("NATIVE_CAPABILITY_CODE_INVALID",t),!n.startsWith(`app:${o}:`)&&!Fi(o).some(i=>i.code===n)&&_("NATIVE_CAPABILITY_APP_MISMATCH",t),n}function _e(e,t){let o=C(e,t,2048);return(!o.startsWith("/")||o.startsWith("//")||o.includes("..")||o.includes("?")||o.includes("#"))&&_("NATIVE_ABSOLUTE_PATH_INVALID",t),o}function He(e,t){return(!Number.isInteger(e)||Number(e)<1)&&_("NATIVE_POSITIVE_INTEGER_REQUIRED",t),Number(e)}function te(e,t,o,n){return(!Number.isInteger(e)||Number(e)<o||Number(e)>n)&&_("NATIVE_INTEGER_OUT_OF_RANGE",t),Number(e)}function Xe(e,t){return typeof e!="boolean"&&_("NATIVE_BOOLEAN_REQUIRED",t),e}function Bn(e,t){let o=C(e,t,64).toLowerCase();return er.test(o)||_("NATIVE_DIGEST_INVALID",t),o}function x(e,t,o){e!==t&&_("NATIVE_VALUE_MISMATCH",o)}function R(e,t,o,n=!1){let i=new Set([...t,...Array.isArray(n)?n:[]]);for(let s of Object.keys(e))i.has(s)||_("NATIVE_PROPERTY_UNKNOWN",`${o}/${s}`);if(n!==!0)for(let s of t)Object.prototype.hasOwnProperty.call(e,s)||_("NATIVE_PROPERTY_REQUIRED",`${o}/${s}`)}function Z(e,t){return[...e].sort((o,n)=>ue(t(o),t(n)))}function W(e){return[...new Set(e)].sort(ue)}function Ni(e){return[...new Set(e)].sort((t,o)=>t-o)}function ue(e,t){return e===t?0:e<t?-1:1}function vi(e){return!e||typeof e!="object"||Object.isFrozen(e)||(Object.freeze(e),Object.values(e).forEach(t=>vi(t))),e}function Kn(e,t,o){if(Ln(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(!Ln(e[i],t[i]))return Kn(e[i],t[i],`${o}/${i}`)}if(e&&t&&typeof e=="object"&&typeof t=="object"&&!Array.isArray(e)&&!Array.isArray(t)){let n=W([...Object.keys(e),...Object.keys(t)]);for(let i of n){let s=e[i],c=t[i];if(!Ln(s,c))return Kn(s,c,`${o}/${i}`)}}return o}function Ln(e,t){return e===void 0||t===void 0?e===t:ee(e)===ee(t)}function _(e,t,o={}){throw new Wn(e,t,o)}var Nd=50,yd=131072,zn=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 bd(e){let t=l=>{throw new zn(l)},o=(l,f)=>((!l||typeof l!="object"||Array.isArray(l))&&t(f),l),n=(l,f,A)=>{for(let N of Object.keys(l))f.includes(N)||t(`${A}/${N}`)},i=(l,f,A)=>((typeof l!="string"||!l.trim()||l.length>f)&&t(A),l),s=(l,f)=>{let A=i(l,36,f);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(A)||t(f),A.toLowerCase()},c=o(e,""),r;try{r=new TextEncoder().encode(JSON.stringify(c)).byteLength}catch{t("")}r>131072&&t(""),n(c,["schemaVersion","environmentKey","items"],""),c.schemaVersion!=="openxiangda.native-role-membership-batch-request/v2"&&t("/schemaVersion"),c.environmentKey!==void 0&&!["preproduction","production"].includes(String(c.environmentKey))&&t("/environmentKey"),(!Array.isArray(c.items)||c.items.length<1||c.items.length>50)&&t("/items");let a=new Set,d=new Set,u;for(let[l,f]of c.items.entries()){let A=`/items/${l}`,N=o(f,A);["create","update","revoke"].includes(String(N.operation))||t(`${A}/operation`),u??=N.operation,u!==N.operation&&t(`${A}/operation`),n(N,["operation","operationId","reason",...u==="create"?["userId","roleCode"]:["membershipId","expectedRevision"],...u!=="revoke"?["scopeGrants","validFrom","validTo"]:[]],A);let I=s(N.operationId,`${A}/operationId`);a.has(I)&&t(`${A}/operationId`),a.add(I),i(N.reason,1e3,`${A}/reason`);let m;if(u==="create"){let E=i(N.userId,255,`${A}/userId`),p=i(N.roleCode,128,`${A}/roleCode`);/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/.test(p)||t(`${A}/roleCode`),m=JSON.stringify([E,p])}else m=s(N.membershipId,`${A}/membershipId`),(!Number.isSafeInteger(N.expectedRevision)||Number(N.expectedRevision)<1)&&t(`${A}/expectedRevision`);d.has(m)&&t(A),d.add(m),N.scopeGrants!==void 0&&(!Array.isArray(N.scopeGrants)||N.scopeGrants.length>100)&&t(`${A}/scopeGrants`);for(let E of["validFrom","validTo"])N[E]!==void 0&&N[E]!==null&&i(N[E],64,`${A}/${E}`)}}var ji="openxiangda.workflow-delegation-administration/v2",Mi="openxiangda.workflow-delegation-mutation/v2",Pi="openxiangda.workflow-delegation-preview/v2";var _t={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}$"},fe={type:"string",minLength:1,maxLength:255},We={type:"string",format:"date-time"},Qe={type:"integer",minimum:1},ga={anyOf:[We,{type:"null"}]},Yn={anyOf:[fe,{type:"null"}]},qt={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}$"},Wi={const:"future-assignments-only"},Hn={schemaVersion:{const:ji},id:_t,appCode:fe,environmentKey:fe,workflowCode:Yn,delegatorUserId:fe,delegateUserId:fe,delegatorRoleSubjectKey:qt,delegateRoleSubjectKey:qt,validFrom:We,validTo:We,status:{enum:["active","revoked","expired"]},reason:{type:"string",minLength:1,maxLength:4e3},createdBy:fe,createdAt:We,revokedAt:ga,revision:Qe,roleCode:fe,roleName:fe,delegatorDisplayName:fe,delegateDisplayName:fe,delegatorRoleSubjectRevision:Qe,delegateRoleSubjectRevision:Qe,effectiveState:{enum:["active","scheduled","expired","revoked","ineligible"]},evaluatedAt:We,issues:{type:"array",maxItems:20,uniqueItems:!0,items:fe},canRevoke:{type:"boolean"},revokedBy:Yn,revokeReason:{type:["string","null"],maxLength:4e3},taskPolicy:Wi},Xn={type:"object",additionalProperties:!1,required:Object.keys(Hn),properties:Hn},Od={$id:ji,...Xn},Ui={schemaVersion:{const:Mi},operationId:_t,environmentKey:{enum:["preproduction","production"]},reason:{type:"string",minLength:1,maxLength:2e3,pattern:"\\S"}},Li={...Ui,operation:{const:"create"},workflowCode:Yn,delegatorRoleSubjectKey:qt,expectedDelegatorRevision:Qe,delegateUserId:fe,delegateRoleSubjectKey:qt,expectedDelegateRevision:Qe,validFrom:We,validTo:We},xi={...Ui,operation:{const:"revoke"},delegationId:_t,expectedRevision:Qe},Aa={$id:Mi,type:"object",oneOf:[{type:"object",additionalProperties:!1,required:Object.keys(Li),properties:Li},{type:"object",additionalProperties:!1,required:Object.keys(xi),properties:xi}]},Ea={type:"string",pattern:"^[0-9a-f]{64}$"},hd={$id:Pi,type:"object",additionalProperties:!1,required:["schemaVersion","operationId","operation","requestDigest","before","after","taskPolicy"],properties:{schemaVersion:{const:Pi},operationId:_t,operation:{enum:["create","revoke"]},requestDigest:Ea,before:{anyOf:[Xn,{type:"null"}]},after:{...Xn,properties:{...Hn,id:{anyOf:[_t,{type:"null"}]}}},taskPolicy:Wi}};function Sd(e){return e===void 0?"":`
9
- ${X(e)}`}function wd(e,t){let o=e.handlers.find(n=>n.code===t);return X(o?.workflowStep?o:e)}var $d="c7768a3f65626330bcaf93664c3ab890eda13cbdd76ea4cfaf74b8ad2032ac99";export{ro as DATA_AUDIT_METADATA_FIELDS,jn as DATA_EVENT_TYPES_V2,ns as DATA_SYSTEM_SORT_FIELD_CODES,nt as ManagedConcurrencyContractError,$d as NATIVE_CONFIGURATION_VALIDATOR_DIGEST,Y as NATIVE_CONTRACT_CAPACITY_V2,qc as NATIVE_DATA_POLICY_EXPRESSION_MAX_CLAUSES,Bc as NATIVE_DATA_POLICY_EXPRESSION_MAX_DEPTH,Kc as NATIVE_DATA_POLICY_EXPRESSION_MAX_GROUP_ITEMS,Gc as NATIVE_DATA_POLICY_EXPRESSION_MAX_LEAVES,Jc as NATIVE_DATA_POLICY_EXPRESSION_MAX_OCCURRENCES,os as NATIVE_DATA_QUERY_OPERATORS_V2,yd as NATIVE_ROLE_MEMBERSHIP_BATCH_MAX_BYTES,Nd as NATIVE_ROLE_MEMBERSHIP_BATCH_MAX_ITEMS,rc as NATIVE_UNIQUE_KEY_MAX_BYTES,Do as NATIVE_UNIQUE_KEY_NORMALIZERS,Wn as NativeConfigurationCompilerError,Ee as NativeDataFieldContractV2Error,ft as NativeDataPolicyExpressionV2Error,qe as NativeDecimalLifecycleContractError,Nn as NativeEventActionContractError,zn as NativeRoleMembershipBatchInputError,gn as NativeScopeSourceFieldPathV2Error,st as NativeUniqueKeyContractError,Gi as OPENXIANGDA_NATIVE_DATA_FIELD_TYPES_V2,Ce as OPENXIANGDA_NATIVE_DATA_SURFACE_KEYS_V2,rn as OPENXIANGDA_NATIVE_DRAFT_STATE_KEYS_V2,Qt as OPENXIANGDA_NATIVE_SYSTEM_FIELDS_V2,oo as OPENXIANGDA_NATIVE_SYSTEM_FIELD_MAP_V2,Rc as WORKFLOW_AUTOMATIC_CC_MAX_RECIPIENTS,Js as WORKFLOW_AUTOMATIC_CC_PROVIDERS,rt as WORKFLOW_BUSINESS_STEP_EVENT,Mo as WORKFLOW_BUSINESS_STEP_EVENTS,_c as WORKFLOW_BUSINESS_STEP_FACTS_KEY,Tn as WORKFLOW_BUSINESS_STEP_MAX_BYTES,Us as WORKFLOW_BUSINESS_STEP_MAX_RECEIPT_BYTES,Cn as WORKFLOW_CONFIGURABLE_OPERATIONS,Sn as WORKFLOW_CONFIGURABLE_PROVIDERS,Mn as WORKFLOW_EVENT_TYPES_V2,Pc as WORKFLOW_ROUTING_MAX_BYTES,vc as WORKFLOW_ROUTING_MAX_MATCHED_RULES,Fc as WORKFLOW_ROUTING_MAX_RULES,wc as WORKFLOW_TASK_PAGE_MAX_BYTES,Sc as WORKFLOW_TASK_PAGE_MAX_FIELDS,Le as WorkflowTaskPageError,Dc as applyWorkflowTaskPageValues,bd as assertNativeRoleMembershipBatchInput,Ed as compileNativeApplicationConfiguration,vo as compileNativeEventAction,Or as compileNativeEventCapturePlansV2,Tr as compileRequiredPlatformCapabilitiesV3,hn as compileWorkflowBusinessStepHandlers,$e as evaluateWorkflowTaskPageExpression,kt as formatWorkflowExpression,ao as hasDataAuditReadPolicy,Ze as isDataAuditMetadataField,co as isDataSystemSortField,Oa as isNativeDataQueryOperatorV2,It as isNativeMultiValueFieldV2,oc as materializeNativeDataQueryPathTypesV2,xt as nativeDataPolicyExpressionLeavesV2,ni as nativeDataPolicyExpressionToCnfV2,ic as nativeDataQueryPathPlanV2,Ra as nativeFieldAggregatePlanV2,qa as nativeFieldColumnDefinitionV2,Ja as nativeFieldDefaultSqlV2,za as nativeFieldHasDefaultV2,Qa as nativeFieldIndexStatementsV2,Nt as nativeFieldRequiresCreateInputV2,Xa as nativeFieldSequenceGrantStatementsV2,Ha as nativeFieldSequenceOwnershipStatementsV2,Ya as nativeFieldSequenceStatementsV2,po as nativeFieldSupportsFilterV2,ha as nativeFieldSupportsOperatorV2,on as nativeFieldSupportsSearchV2,tt as nativeFieldSupportsSortV2,fo as nativeOperatorsForFieldV2,hs as nativePhysicalFieldV2,Ga as nativePhysicalFieldsV2,Se as nativePhysicalObjectNameV2,tc as nativeScopeSourceFieldValueV2,So as nativeScopeSourceGrantPathSupportedV2,An as nativeScopeSourceSubjectPathSupportedV2,Za as nativeSubtableConstraintStatementsV2,ac as nativeUniqueKeysJsonSchema,mn as parseDecimalReservationLifecycle,Zt as parseNativeDataFieldsV2,so as parseNativeDataResourceInvariantsV2,$o as parseNativeUniqueKeys,ln as projectNativeDataResourceViewV2,yc as projectWorkflowGraph,Oc as projectWorkflowNodePolicy,re as quoteNativeIdentifierV2,$c as refreshWorkflowTaskPageFacts,ot as resolveNativeScopeSourceFieldPathV2,Mc as selectWorkflowAssignmentRoutingRules,bo as validateDecimalReservationLifecycles,No as validateManagedConcurrency,go as validateNativeDataDraftStateV2,io as validateNativeDataResourceReferencesV2,dn as validateNativeDataResourceSurfaceV2,wn as validateWorkflowAdministration,Zo as validateWorkflowAssignmentRoutingBindings,Lt as validateWorkflowAssignmentRoutingPolicy,xc as validateWorkflowAssignmentRoutingRules,Dn as validateWorkflowAutomaticCc,Ac as validateWorkflowBusinessStepHandlerContract,gc as validateWorkflowBusinessStepRequest,Bs as validateWorkflowBusinessStepResult,Dt as validateWorkflowBusinessStepSchema,Ko as validateWorkflowBusinessStepSubscriptions,Vt as validateWorkflowBusinessSteps,Lo as validateWorkflowInstanceCommandPolicies,Tc as validateWorkflowNodeConfigurationPatch,qo as validateWorkflowReadability,Fn as validateWorkflowTaskPages,jc as workflowAssignmentRoutingFacts,Lc as workflowAssignmentRoutingPolicySchema,Qs as workflowAssignmentRoutingSemantic,$t as workflowBusinessStepFactSchema,wd as workflowBusinessStepHandlerDigest,Ec as workflowBusinessStepInput,Ks as workflowBusinessStepPath,Sd as workflowBusinessStepReceiptSignatureSuffix,wt as workflowBusinessStepValueMatches,Aa as workflowDelegationMutationRequestSchema,Go as workflowExpressionPaths,pc as workflowInstanceCommandDeadlineError,fc as workflowInstanceTerminateCapabilityAllowed,at as workflowNodeAllowedOperations,Po as workflowPolicyTimestamp,zs as workflowTaskPageFieldState,Vc as workflowTaskPageReplayCoversInvalidation};
8
+ END $native_subtable$`]}function $e(e,...t){return`${e}_${Xs("sha256").update(t.join(":")).digest("hex").slice(0,32)}`}function de(e){if(!/^[A-Za-z_][A-Za-z0-9_]{0,62}$/.test(e))throw new Error("OPENXIANGDA_NATIVE_IDENTIFIER_INVALID");return`"${e}"`}function or(e,t){return e.type==="subtable"?"none":t?"gin-trigram":e.indexed?["date-range","datetime-range"].includes(e.type)?"gist-range":wn.has(e.type)?"btree-snapshot-expressions":Qs.has(e.type)?"gin-jsonb-path":"btree":"none"}function ir(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 er.has(e.type),"jsonb"}}function Ko(e,t){if(Dt(t.type)&&t.type!=="subtable")return"'[]'::jsonb";if(t.type!=="serial-number")return"";let o=Mo(t.serial?.prefix||""),n=t.serial?.digits??6;return`(${o} || lpad(nextval(${Mo(Lt(e,t.code))})::text, ${n}, '0'))`}function sr(e,t){return Bo.has(t.type)?` CHECK (${e} IS NULL OR jsonb_typeof(${e}) = 'array')`:Zs.has(t.type)?` CHECK (${e} IS NULL OR jsonb_typeof(${e}) = 'object')`:""}function vt(e){return`"app_data".${de(e)}`}function Lt(e,t){let o=$e("seq",e,t);return`"app_data".${de(o)}`}function Mo(e){return`'${e.replace(/'/g,"''")}'`}var qo=new Set(["option.single","option.multiple","user.single","user.multiple","department.single","department.multiple","resource-ref.single","resource-ref.multiple"]),rr=new Set([...qo,"cascade.single","cascade.multiple","file","image","signature","address","location","json"]),Jo=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,ar=new Set(["__proto__","prototype","constructor"]),Dn=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 at(e,t){let o=zo(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 $n(e){return!!(e&&e.field.type==="user.single"&&e.valuePath==="value")}function Go(e,t,o){if(!e||!t||!cr(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 s=i.slice(9),r=o.get(n.source?.resourceCode||"")?.get(s)?.type;return t.valueType==="uuid"?r==="uuid":["text.short","text.long","serial-number"].includes(r||"")}function Xc(e,t){let o=zo(t);if(!o)throw new Dn(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 cr(e){let{field:t,valuePath:o}=e;if(!o)return!rr.has(t.type);if(o==="value")return qo.has(t.type);if(!o.startsWith("snapshot."))return!1;let n=o.slice(9);return Jo.test(n)&&t.type.startsWith("resource-ref.")&&!!t.source?.snapshotFields?.includes(n)}function zo(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=>!Jo.test(o)||ar.has(o))||t.length===2&&t[1]!=="value"||t.length===3&&t[1]!=="snapshot"?null:t}var dr=new Set(["option.single","user.single","department.single","resource-ref.single"]),lr=new Set(["text.short","text.long","text.rich","number.integer","number.decimal","boolean","date","time","datetime","uuid","serial-number"]),ur=new Set(["value","label","description","color"]),fr=new Set(["avatarUrl","employeeNo","title","mobile","email"]),pr=new Set(["fullPath","parent.value","parent.label"]),mr=new Set(["country.value","country.label","province.value","province.label","city.value","city.label","district.value","district.label","street.value","street.label","detail","fullAddress"]),_r=new Set(["longitude","latitude","accuracy"]),gr=new Set(["address","name","province","city","district","source"]);function Zc(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=Ar(n,t);if(!Object.keys(i).length)return n;let s={...n};return Object.defineProperty(s,"queryPathTypes",{configurable:!1,enumerable:!1,writable:!1,value:Object.freeze(i)}),s})}}))}function ed(e,t){if(dr.has(e.type)&&ur.has(t)||e.type==="user.single"&&fr.has(t)||e.type==="department.single"&&pr.has(t))return ct(t);if(e.type==="resource-ref.single"){let o=e.queryPathTypes?.[t];return o?{parts:t.split("."),type:o}:null}if(e.type==="address"&&mr.has(t))return ct(t);if(e.type==="location"){if(_r.has(t))return{parts:[t],type:"number.decimal"};if(gr.has(t))return ct(t);if(t==="capturedAt")return{parts:[t],type:"datetime"}}return null}function Ar(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}`,lr.has(i.type)?i.type:"json"]]:[]})):{}}function ct(e){return{parts:e.split("."),type:"text.short"}}var Ho=["exact-v1","nfkc-space-v1","nfkc-upper-ascii-v1"],nd=256,lt=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"},kn=e=>!!(e&&typeof e=="object"&&!Array.isArray(e)),ie=(e,t)=>{throw new lt(e,t)},xt=(e,t)=>e<t?-1:e>t?1:0,dt=(e,t,o)=>{Object.keys(e).some(n=>!t.includes(n))&&ie(o,"\u4E0D\u652F\u6301\u672A\u77E5\u5C5E\u6027")};function Yo(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(s=>[s.code,s])),i=new Set;return e.map((s,a)=>{let r=`${o}/${a}`;if(!kn(s))return ie(r,"\u89C4\u5219\u5FC5\u987B\u662F\u5BF9\u8C61");if(dt(s,["code","fields","when"],r),typeof s.code!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(s.code)||s.code.length>20||i.has(s.code))return ie(`${r}/code`,"\u9700\u8981\u4E0D\u91CD\u590D\u4E14\u4E0D\u8D85\u8FC7 20 \u5B57\u7B26\u7684 lower-kebab-case \u6807\u8BC6");if(i.add(s.code),!Array.isArray(s.fields)||s.fields.length<1||s.fields.length>4)return ie(`${r}/fields`,"\u5FC5\u987B\u9009\u62E9 1 \u5230 4 \u4E2A\u5B57\u6BB5");let c=new Set,l=s.fields.map((g,I)=>{let E=`${r}/fields/${I}`;if(!kn(g))return ie(E,"\u5B57\u6BB5\u5FC5\u987B\u662F\u5BF9\u8C61");dt(g,["fieldCode","normalizer"],E);let N=n.get(g.fieldCode);if(!N||!["text.short","uuid","option.single","resource-ref.single","user.single"].includes(N.type)||c.has(g.fieldCode))return ie(`${E}/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");c.add(g.fieldCode);let y=g.normalizer===void 0?"exact-v1":g.normalizer;return!Ho.includes(y)||N.type!=="text.short"&&y!=="exact-v1"?ie(`${E}/normalizer`,"\u5F52\u4E00\u5316\u65B9\u5F0F\u4E0D\u652F\u6301\u6216\u4E0E\u5B57\u6BB5\u7C7B\u578B\u4E0D\u7B26"):{fieldCode:N.code,normalizer:y}}).sort((g,I)=>xt(g.fieldCode,I.fieldCode)),p=s.when===void 0?[]:s.when;if(!Array.isArray(p)||p.length>4)return ie(`${r}/when`,"\u6700\u591A 4 \u4E2A\u5408\u53D6\u6761\u4EF6");let d=new Set,u=p.map((g,I)=>{let E=`${r}/when/${I}`;if(!kn(g))return ie(E,"\u6761\u4EF6\u5FC5\u987B\u662F\u5BF9\u8C61");let N=n.get(g.fieldCode);if(!N)return ie(`${E}/fieldCode`,"\u5B57\u6BB5\u4E0D\u5B58\u5728");let y;if(g.operator==="empty"||g.operator==="nonempty"){if(dt(g,["fieldCode","operator"],E),N.type!=="text.short")return ie(E,"\u7A7A\u503C\u6761\u4EF6\u4EC5\u652F\u6301\u77ED\u6587\u672C");y={fieldCode:N.code,operator:g.operator}}else if(g.operator==="in"||g.operator==="notIn"){dt(g,["fieldCode","operator","values"],E);let A=new Set((N.options??[]).map(T=>T.value));if(N.type!=="option.single"||!Array.isArray(g.values)||g.values.length<1||g.values.length>16||g.values.some(T=>typeof T!="string"||T.length<1||T.length>128||!A.has(T))||new Set(g.values).size!==g.values.length)return ie(E,"\u96C6\u5408\u6761\u4EF6\u9700\u8981 1 \u5230 16 \u4E2A\u4E0D\u91CD\u590D\u7684\u5DF2\u58F0\u660E\u5355\u9009\u503C");y={fieldCode:N.code,operator:g.operator,values:[...g.values].sort(xt)}}else if(g.operator==="eq"||g.operator==="ne"){if(dt(g,["fieldCode","operator","value"],E),N.type!=="boolean"||typeof g.value!="boolean")return ie(E,"\u7B49\u503C\u6761\u4EF6\u4EC5\u652F\u6301\u5E03\u5C14\u5B57\u6BB5\u548C\u5E03\u5C14\u503C");y={fieldCode:N.code,operator:g.operator,value:g.value}}else return ie(`${E}/operator`,"\u53EA\u652F\u6301 empty\u3001nonempty\u3001in\u3001notIn \u548C\u5E03\u5C14 eq\u3001ne");let _=JSON.stringify(y);return d.has(_)?ie(E,"\u6761\u4EF6\u4E0D\u80FD\u91CD\u590D"):(d.add(_),y)}).sort((g,I)=>xt(JSON.stringify(g),JSON.stringify(I)));return{code:s.code,fields:l,when:u}}).sort((s,a)=>xt(s.code,a.code))}function Xo(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 jt={type:"string",pattern:"^[A-Za-z_][A-Za-z0-9_]{0,62}$"},od={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:jt,normalizer:{enum:[...Ho]}}}},when:{type:"array",maxItems:4,uniqueItems:!0,items:{oneOf:[{type:"object",additionalProperties:!1,required:["fieldCode","operator"],properties:{fieldCode:jt,operator:{enum:["empty","nonempty"]}}},{type:"object",additionalProperties:!1,required:["fieldCode","operator","values"],properties:{fieldCode:jt,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:jt,operator:{enum:["eq","ne"]},value:{type:"boolean"}}}]}}}}};var Qo={"openxiangda.workflow.instance.completed.v2":"commit","openxiangda.workflow.instance.rejected.v2":"release","openxiangda.workflow.instance.withdrawn.v2":"release"};function Zo(e,t){let o=()=>{throw new Error("NATIVE_EVENT_DECIMAL_RESERVATION_INVALID")},n=u=>!u||typeof u!="object"||Array.isArray(u)?o():u,i=n(e);if(Object.keys(i).some(u=>!["resourceCode","workflowCode","outcomes"].includes(u))||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 s=t.resources.find(u=>u.code===i.resourceCode),a=t.reservations.find(u=>u.mode==="reserve"&&u.resourceCode===i.resourceCode),r=t.workflows.find(u=>u.code===i.workflowCode);if(!s||!a||!r||r.resourceCode!==s.code)return o();let c=s.fields.find(u=>u.code===a.statusFieldCode);if(c?.type!=="option.single")return o();let l=new Set(c.options?.map(u=>u.value)),p=new Set,d=i.outcomes.map(u=>{let g=n(u),I=g.eventType;return Object.keys(g).some(E=>!["eventType","mode","eligibleChildStatuses"].includes(E))||typeof I!="string"||!Object.prototype.hasOwnProperty.call(Qo,I)||!t.eventTypes.includes(I)||p.has(I)||g.mode!==Qo[I]||!Array.isArray(g.eligibleChildStatuses)||!g.eligibleChildStatuses.length||g.eligibleChildStatuses.length>16||new Set(g.eligibleChildStatuses).size!==g.eligibleChildStatuses.length||g.eligibleChildStatuses.some(E=>typeof E!="string"||!/^[A-Za-z0-9._:-]{1,128}$/.test(E)||!l.has(E))?o():(p.add(I),{eventType:I,mode:g.mode,eligibleChildStatuses:[...g.eligibleChildStatuses].sort()})}).sort((u,g)=>u.eventType.localeCompare(g.eventType));return{resourceCode:i.resourceCode,workflowCode:i.workflowCode,outcomes:d}}function ei(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(s=>({value:s.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 Vn=class extends Error{constructor(o,n){super(n);this.pointer=o}pointer;code="NATIVE_EVENT_ACTION_INVALID"};function ti(e,t,o="/events/subscriptions"){if(e.execution===void 0)return;let n=(E,N)=>{throw new Vn(`${o}${E}`,N)},i=(E,N,y)=>((!E||typeof E!="object"||Array.isArray(E)||Object.keys(E).some(_=>!y.includes(_)))&&n(N,"Invalid action object or unsupported property"),E),s=i(e.execution,"/execution",["kind","version","operations"]);(s.kind!=="native-data"||s.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(E=>!/^openxiangda\.data\.record\.(created|updated|deleted)\.v2$/.test(E)))&&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 r=new Map(t.map(E=>[E.code,E])),c=a.map(E=>{let N=r.get(E);return N||n("/filter/resourceCodes","Unknown source resource"),new Set((N.schema?.fields||[]).map(y=>y.code))}),l=new Set(e.payload?.fields||[]),p=e.payload?.includeChanges===!0,d=(E,N)=>{let y=i(E,N,["source","path","value"]);if(y.source==="literal"){(!Object.hasOwn(y,"value")||Object.hasOwn(y,"path"))&&n(N,"Literal binding requires only value");let f;try{f=JSON.stringify(y.value)}catch{n(N,"Literal must be JSON")}return(f===void 0||Buffer.byteLength(f)>65536)&&n(N,"Literal is too large or not JSON"),{source:"literal",value:JSON.parse(f)}}(y.source!=="event"||typeof y.path!="string"||Object.hasOwn(y,"value"))&&n(N,"Expected a literal or event binding");let _=y.path.split(".");(_.length>8||_.some(f=>!/^[A-Za-z0-9_-]+$/.test(f)||["__proto__","prototype","constructor"].includes(f)))&&n(N,"Invalid event path");let A=/^data\.projection\.([A-Za-z][A-Za-z0-9_]{0,62})$/.exec(y.path),T=/^data\.changes\.([A-Za-z][A-Za-z0-9_]{0,62})\.(before|after)$/.exec(y.path);if(A||T){let f=(A||T)[1];c.some(b=>!b.has(f))&&n(N,"Source field must exist on every filtered resource"),l.add(f),T&&(p=!0)}else["id","time","type","subject","data.recordId","data.revision","data.operation","data.resourceCode"].includes(y.path)||n(N,"Event path is not part of the data event contract");return{source:"event",path:y.path}};(!Array.isArray(s.operations)||s.operations.length<1||s.operations.length>16)&&n("/execution/operations","Expected 1 to 16 operations");let u={},g=s.operations.map((E,N)=>{let y=`/execution/operations/${N}`,_=i(E,y,["operation","resourceCode","data","id","expectedRevision"]);["create","update","delete"].includes(_.operation)||n(y,"Unsupported Native operation");let A=r.get(_.resourceCode);A||n(y,"Unknown action target resource");let T=new Map((A.schema?.fields||[]).map(b=>[b.code,b])),f=_.data===void 0?{}:i(_.data,`${y}/data`,[...T.keys()]);return Object.keys(f).length>32&&n(y,"Maximum 32 mapped fields per operation"),_.operation==="create"&&(_.id!==void 0||_.expectedRevision!==void 0)&&n(y,"Create does not accept id or expectedRevision"),_.operation==="delete"&&_.data!==void 0&&n(y,"Delete does not accept data"),Object.keys(f).some(b=>T.get(b)?.type==="serial-number")&&n(y,"Generated fields cannot be assigned"),u[_.resourceCode]=Q(A),{operation:_.operation,resourceCode:_.resourceCode,..._.operation==="create"?{}:{id:d(_.id,`${y}/id`),expectedRevision:d(_.expectedRevision,`${y}/expectedRevision`)},..._.operation==="delete"?{}:{data:Object.fromEntries(Object.entries(f).map(([b,h])=>[b,d(h,`${y}/data/${b}`)]))}}});(l.size>32||[...l].some(E=>c.some(N=>!N.has(E))))&&n("/payload/fields","Payload must contain at most 32 declared source fields");let I={kind:"native-data",version:1,operations:g,resourceDigests:u};return Buffer.byteLength(JSON.stringify(I))>65536&&n("/execution","Action plan exceeds 64 KiB"),{execution:{...I,digest:Q(I)},payload:{includeChanges:p,fields:[...l].sort()}}}function ke(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function oi(e,t){if(e?.instanceCommands===void 0)return[];let o=ke(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,s]of Object.entries(o)){let a=ke(s),r=i==="withdraw"?["beforeFact","reasonRequired"]:["beforeFact","capability"];if(!a||!Object.keys(a).length||Object.keys(a).some(c=>!r.includes(c))||Object.hasOwn(a,"reasonRequired")&&typeof a.reasonRequired!="boolean"){n.push(`WORKFLOW_INSTANCE_COMMAND_POLICY_INVALID:${i}`);continue}if(i==="terminate"){let c=a.capability;(typeof c!="string"||c.length>255||!/^app:[a-z][a-z0-9]*(?:-[a-z0-9]+)*:[A-Za-z0-9:._-]+$/.test(c)||t&&(!c.startsWith(`app:${t.appCode}:`)||!t.capabilities.includes(c)))&&n.push("WORKFLOW_INSTANCE_TERMINATE_CAPABILITY_INVALID")}if(Object.hasOwn(a,"beforeFact")){let c=a.beforeFact,l=ke(e.inputSchema),p=ke(ke(l?.properties)?.[c]),d=ke(ke(e.subject)?.factProjection)?.[c],u=t?.fields.get(d);(typeof c!="string"||!/^[A-Za-z][A-Za-z0-9_]{0,62}$/.test(c)||!Array.isArray(l?.required)||!l.required.includes(c)||p?.type!=="string"||p?.format!=="date-time"||typeof d!="string"||t&&(u?.type!=="datetime"||u.nullable===!0))&&n.push(`WORKFLOW_INSTANCE_COMMAND_DEADLINE_FACT_INVALID:${i}`)}}return n}function cd(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 dd(e){return e?.withdraw?.reasonRequired!==!1}function ni(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,s,a,r]=t,c=t[8],l=new Date(Date.UTC(Number(o),Number(n),0)).getUTCDate();if(Number(n)<1||Number(n)>12||Number(i)<1||Number(i)>l||Number(s)>23||Number(a)>59||Number(r)>59||c!=="Z"&&(Number(c.slice(1,3))>23||Number(c.slice(4))>59))return null;let p=Date.parse(e);return Number.isFinite(p)?p:null}function ld(e,t,o,n){let i=e?.[t];if(!i||i.beforeFact===void 0)return null;let s=i.beforeFact,a=ke(o),r=s&&a&&Object.hasOwn(a,s)?ni(a[s]):null,c=n instanceof Date?n.getTime():ni(n);return r===null||c===null||!Number.isFinite(c)?"WORKFLOW_V2_CANCELLATION_DEADLINE_INVALID":c<r?null:"WORKFLOW_V2_CANCELLATION_DEADLINE_PASSED"}var ut="openxiangda.workflow.step.requested.v2",ri=[ut,"openxiangda.workflow.step.result_received.v2","openxiangda.workflow.step.completed.v2","openxiangda.workflow.step.continuation_failed.v2"],vn=16384,Er=2048,fd="steps",Ln=/^[A-Za-z][A-Za-z0-9_-]{0,127}$/,ai=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,xe=new Set(["__proto__","prototype","constructor"]),B=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&[Object.prototype,null].includes(Object.getPrototypeOf(e)),ci=e=>{try{let t=JSON.stringify(e);return t===void 0?1/0:new TextEncoder().encode(t).length}catch{return 1/0}},Ye=(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((s,a)=>Ye(s,t[a],o+1));if(!B(e)||!B(t))return!1;let n=Object.keys(e).filter(s=>e[s]!==void 0),i=Object.keys(t).filter(s=>t[s]!==void 0);return n.length===i.length&&n.every(s=>Object.hasOwn(t,s)&&Ye(e[s],t[s],o+1))};function Pn(e,t){let o=0,n=(i,s)=>++o>1e4||s>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(a=>n(a,s+1)):B(i)&&Object.keys(i).length<=32&&Object.keys(i).every(a=>!xe.has(a))&&Object.values(i).every(a=>n(a,s+1));return ci(e)<=t&&n(e,0)}function Ir(e){return!B(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&&B(e.output)&&Pn(e.output,vn)&&(e.receipt===void 0||B(e.receipt)&&Pn(e.receipt,Er))}function pd(e){return B(e)&&Object.keys(e).every(t=>["executionId","nodeId","handlerCode","handlerVersion","mode","input","inputDigest","expectedFactRevision"].includes(t))&&typeof e.nodeId=="string"&&Ln.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)&&Ir({executionId:e.executionId,handlerVersion:e.handlerVersion,inputDigest:e.inputDigest,expectedFactRevision:e.expectedFactRevision,output:e.input})}function Wt(e,t,o=vn){if(!Pn(t,o))return!1;let n=1e4,i=(s,a,r)=>{if(--n<0||r>8||!B(s))return!1;let c=a===null?"null":Array.isArray(a)?"array":typeof a=="number"&&Number.isSafeInteger(a)?"integer":typeof a,l=Array.isArray(s.type)?s.type:[s.type];if(!l.includes(c)&&!(c==="integer"&&l.includes("number"))||s.enum!==void 0&&(!Array.isArray(s.enum)||!s.enum.some(p=>Ye(p,a)))||Object.hasOwn(s,"const")&&!Ye(s.const,a))return!1;if(typeof a=="number")return Number.isFinite(a)&&(s.minimum===void 0||a>=s.minimum)&&(s.maximum===void 0||a<=s.maximum);if(typeof a=="string"){let p=Array.from(a).length;return(s.minLength===void 0||p>=s.minLength)&&(s.maxLength===void 0||p<=s.maxLength)}return Array.isArray(a)?a.length<=s.maxItems&&(s.minItems===void 0||a.length>=s.minItems)&&a.every(p=>i(s.items,p,r+1)):B(a)?!B(s.properties)||Object.keys(a).some(p=>xe.has(p)||!Object.hasOwn(s.properties,p))||(Array.isArray(s.required)?s.required:[]).some(p=>!Object.hasOwn(a,p))||s.minProperties!==void 0&&Object.keys(a).length<s.minProperties||s.maxProperties!==void 0&&Object.keys(a).length>s.maxProperties?!1:Object.entries(a).every(([p,d])=>i(s.properties[p],d,r+1)):a===null||typeof a=="boolean"};return i(e,t,0)}function yr(e){return typeof e=="string"&&e.length<=256&&e.split(".").length<=8&&e.split(".").every(t=>Ln.test(t)&&!xe.has(t))}function Ut(e){let t=0,o=(n,i)=>{if(!B(n)||i>6||++t>256||Object.keys(n).some(r=>!["type","title","description","properties","required","additionalProperties","items","maxItems","minItems","maxLength","minLength","minimum","maximum","enum","const","maxProperties","minProperties"].includes(r)))return!1;let s=Array.isArray(n.type)?n.type:[n.type];if(!s.length||s.length>2||s.some(r=>!["object","array","string","integer","number","boolean","null"].includes(r))||s.length>1&&(!s.includes("null")||new Set(s).size!==s.length))return!1;for(let r of["title","description"])if(n[r]!==void 0&&(typeof n[r]!="string"||n[r].length>2e3))return!1;for(let r of["minimum","maximum"])if(n[r]!==void 0&&(typeof n[r]!="number"||!Number.isFinite(n[r])))return!1;for(let[r,c]of[["maxItems",200],["minItems",200],["maxLength",16384],["minLength",16384],["maxProperties",32],["minProperties",32]])if(n[r]!==void 0&&(!Number.isSafeInteger(n[r])||n[r]<0||n[r]>c))return!1;for(let[r,c]of[["minimum","maximum"],["minItems","maxItems"],["minLength","maxLength"],["minProperties","maxProperties"]])if(n[r]!==void 0&&n[c]!==void 0&&n[r]>n[c])return!1;if(["properties","required","additionalProperties","maxProperties","minProperties"].some(r=>n[r]!==void 0)&&!s.includes("object")||["items","maxItems","minItems"].some(r=>n[r]!==void 0)&&!s.includes("array")||["maxLength","minLength"].some(r=>n[r]!==void 0)&&!s.includes("string")||["minimum","maximum"].some(r=>n[r]!==void 0)&&!s.some(r=>r==="integer"||r==="number")||n.enum!==void 0&&(!Array.isArray(n.enum)||!n.enum.length||n.enum.length>100)||s.includes("object")&&(!B(n.properties)||n.additionalProperties!==!1||Object.keys(n.properties).length>32||Object.keys(n.properties).some(r=>!ai.test(r)||xe.has(r))||n.required!==void 0&&(!Array.isArray(n.required)||new Set(n.required).size!==n.required.length||n.required.some(r=>typeof r!="string"||!Object.hasOwn(n.properties,r)))||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(r=>o(r,i+1)))||s.includes("array")&&(!Number.isSafeInteger(n.maxItems)||!o(n.items,i+1)))return!1;let a={...n};return delete a.enum,delete a.const,!(n.enum!==void 0&&(!n.enum.every(r=>Wt(a,r))||n.enum.some((r,c)=>n.enum.slice(0,c).some(l=>Ye(r,l))))||Object.hasOwn(n,"const")&&!Wt(a,n.const))};return B(e)&&e.type==="object"&&ci(e)<=vn&&o(e,0)}function Mt(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 di(e,t){let o=e;for(let n of t.split(".")){if(!B(o?.properties)||!Object.hasOwn(o.properties,n))return;o=o.properties[n]}return B(o)?o:void 0}var ii=(e,t)=>!!di(e,t);function md(e){return B(e)&&Object.keys(e).every(t=>["version","mode","inputSchema","outputSchema"].includes(t))&&Number.isSafeInteger(e.version)&&e.version>=1&&e.version<=1e6&&["pure","reconciled-effect"].includes(e.mode)&&Ut(e.inputSchema)&&Ut(e.outputSchema)}function si(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 Fn(e,t=0){return!B(e)||t>16?[]:e.op==="path"?typeof e.path=="string"?[e.path]:[]:["left","right","value"].flatMap(o=>Fn(e[o],t+1)).concat(Array.isArray(e.values)?e.values.flatMap(o=>Fn(o,t+1)):[])}function Bt(e,t){if(!B(e)||!B(e.nodes))return["WORKFLOW_STEP_DEFINITION_INVALID"];let o=e.nodes,n=Object.entries(o).filter(([,r])=>r?.kind==="action");if(!n.length)return[];let i=[];Object.hasOwn(e.inputSchema?.properties||{},"steps")&&i.push("WORKFLOW_STEP_FACT_NAMESPACE_RESERVED");let s=Mt(e);for(let[r,c]of n){(Object.keys(c).some(d=>!["id","kind","title","next","handler","inputSchema","outputSchema","inputs"].includes(d))||c.id!==r||!Ln.test(r)||xe.has(r)||typeof c.title!="string"||!c.title.trim()||c.title.length>255||typeof c.next!="string"||!Object.hasOwn(o,c.next))&&i.push(`WORKFLOW_STEP_NODE_INVALID:${r}`);let l=c.handler;(!B(l)||Object.keys(l).some(d=>!["code","version","mode"].includes(d))||!Number.isSafeInteger(l.version)||l.version<1||l.version>1e6||!/^[a-z][a-z0-9-]{0,100}$/.test(l.code||"")||!String(l.code).endsWith(`-v${l.version}`)||!["pure","reconciled-effect"].includes(l.mode))&&i.push(`WORKFLOW_STEP_HANDLER_INVALID:${r}`);let p=Ut(c.inputSchema);if((!p||!Ut(c.outputSchema))&&i.push(`WORKFLOW_STEP_SCHEMA_INVALID:${r}`),!B(c.inputs)||Object.keys(c.inputs).length>32){i.push(`WORKFLOW_STEP_INPUTS_INVALID:${r}`);continue}for(let d of Array.isArray(c.inputSchema?.required)?c.inputSchema.required:[])Object.hasOwn(c.inputs,d)||i.push(`WORKFLOW_STEP_INPUT_REQUIRED:${r}:${d}`);for(let[d,u]of Object.entries(c.inputs)){if(!ai.test(d)||xe.has(d)||!Object.hasOwn(c.inputSchema?.properties||{},d)||!B(u)){i.push(`WORKFLOW_STEP_INPUT_INVALID:${r}:${d}`);continue}if(u.source==="literal")(!p||Object.keys(u).some(g=>!["source","value"].includes(g))||!Object.hasOwn(u,"value")||!Wt(c.inputSchema.properties[d],u.value))&&i.push(`WORKFLOW_STEP_LITERAL_INVALID:${r}:${d}`);else if(u.source!=="fact"||Object.keys(u).some(g=>!["source","path"].includes(g))||!yr(u.path)||!ii(s,u.path))i.push(`WORKFLOW_STEP_FACT_PATH_INVALID:${r}:${d}`);else if(p){let g=di(s,u.path),I=c.inputSchema.properties[d],E=Array.isArray(g.type)?g.type:[g.type],N=Array.isArray(I.type)?I.type:[I.type];E.some(y=>!N.includes(y)&&!(y==="integer"&&N.includes("number")))&&i.push(`WORKFLOW_STEP_FACT_TYPE_MISMATCH:${r}:${d}`)}}}let a=(r,c)=>{let l=new Set,p=[e.startAt||""];for(;p.length&&l.size<=200;){let d=p.shift();if(!(d===c||l.has(d)||!o[d])){if(d===r)return!0;l.add(d),p.push(...si(o[d]))}}return!1};for(let[r,c]of Object.entries(o)){if(!B(c))continue;let l=c.kind==="action"?Object.values(c.inputs||{}).flatMap(d=>d?.source==="fact"?[d.path]:[]):(Array.isArray(c.branches)?c.branches:[]).flatMap(d=>Fn(d?.when)),p=t?.bindings?.[c.binding];p&&l.push(...[p.inputPath,p.departmentIdFrom,p.resourceIdFrom,p.scope?.valueFrom].filter(d=>typeof d=="string"));for(let d of l.filter(u=>typeof u=="string"&&u.startsWith("steps."))){let u=d.split(".")[1];(o[u]?.kind!=="action"||u===r||!ii(s,d)||a(r,u))&&i.push(`WORKFLOW_STEP_OUTPUT_NOT_AVAILABLE:${r}:${d}`)}}if(t)for(let[,r]of n){let c=new Set,l=[r.next];for(;l.length&&c.size<=200;){let p=l.shift();if(c.has(p)||!B(o[p]))continue;c.add(p);let d=o[p];if(!(d.kind==="action"||d.kind==="end")){if(d.kind==="approval"){let u=t.bindings?.[d.binding];u&&["application_provider","initiator_select"].includes(u.provider)&&i.push(`WORKFLOW_STEP_NEXT_PROVIDER_REQUIRES_PREPARED_RESULT:${p}`);continue}l.push(...si(d))}}}return[...new Set(i)]}function _d(e,t){let o={};for(let[n,i]of Object.entries(e.inputs)){let s=i.source==="literal"?i.value:i.path.split(".").reduce((a,r)=>B(a)&&Object.hasOwn(a,r)?a[r]:void 0,t);s!==void 0&&(o[n]=s)}if(!Wt(e.inputSchema,o))throw new Error("WORKFLOW_STEP_INPUT_SCHEMA_INVALID");return o}function li(e,t,o){let n=xn(e),i=[];Object.keys(n).length&&!o&&i.push("WORKFLOW_STEP_BACKEND_REQUIRED");for(let s of Object.keys(n)){let a=t.find(r=>r.code===s);(!a||a.execution||a.action||!Array.isArray(a.eventTypes)||a.eventTypes.length!==1||a.eventTypes[0]!==ut||!B(a.filter)||Object.keys(a.filter).length!==1||!B(a.filter.workflowStep)||Object.keys(a.filter.workflowStep).length!==1||a.filter.workflowStep.handlerCode!==s||!B(a.payload)||a.payload.includeChanges!==!1||!Array.isArray(a.payload.fields)||a.payload.fields.length)&&i.push(`WORKFLOW_STEP_SUBSCRIPTION_INVALID:${s}`)}for(let s of t)(s.eventTypes?.includes(ut)&&!n[s.code]||s.filter?.workflowStep&&!n[s.code])&&i.push(`WORKFLOW_STEP_HANDLER_NOT_DECLARED:${s.code}`);return i}function xn(e){let t={};for(let o of e){let n=Bt(o);if(n.length)throw new Error(n.join("; "));for(let i of Object.values(o.nodes||{})){if(i.kind!=="action")continue;let s={version:i.handler.version,mode:i.handler.mode,inputSchema:i.inputSchema,outputSchema:i.outputSchema},a=t[i.handler.code];if(a&&!Ye(a,s))throw new Error(`WORKFLOW_STEP_HANDLER_CONTRACT_CONFLICT:${i.handler.code}`);t[i.handler.code]=s}}return t}var ue=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},je=(e,t)=>typeof e=="string"&&!!e.trim()&&e.length<=t,br=/^[A-Za-z][A-Za-z0-9_-]*(?:\.[A-Za-z][A-Za-z0-9_-]*){0,15}$/,jn=e=>typeof e=="string"&&e.length<=256&&br.test(e)&&!e.split(".").some(t=>["__proto__","prototype","constructor"].includes(t));function qt(e,t){let o=ue(e),n=!0;for(let i of t.split(".")){n&&=Array.isArray(o.required)&&o.required.includes(i);let s=ue(o.properties)[i];if(!s||typeof s!="object")return null;o=ue(s)}return{schema:o,required:n}}function ui(e){let t=new Set,o=[],n=2048,i=(s,a)=>{if(--n<0||a>20){o.push("WORKFLOW_EXPRESSION_BUDGET_EXCEEDED");return}let r=ue(s);if(r.op==="path")jn(r.path)?t.add(r.path):o.push("WORKFLOW_EXPRESSION_PATH_INVALID");else{if(r.op==="literal")return;if(r.op==="and"||r.op==="or")if(!Array.isArray(r.values)||!r.values.length||r.values.length>128)o.push("WORKFLOW_EXPRESSION_GROUP_INVALID");else for(let c of r.values){if(n<0)break;i(c,a+1)}else r.op==="not"||r.op==="exists"?i(r.value,a+1):["eq","neq","gt","gte","lt","lte","in","contains"].includes(String(r.op))?(i(r.left,a+1),i(r.right,a+1)):o.push("WORKFLOW_EXPRESSION_OPERATOR_INVALID")}};return i(e,0),{paths:[...t],errors:[...new Set(o)]}}function fi(e){if(e?.readability===void 0)return[];let t=[],o=Mt(e),n=ue(e.readability);(Object.keys(n).some(r=>!["variables","logic"].includes(r))||!Object.keys(n).length)&&t.push("WORKFLOW_READABILITY_INVALID");let i=ue(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[r,c]of Object.entries(i)){let l=ue(c);(!jn(r)||!qt(o,r))&&t.push(`WORKFLOW_VARIABLE_SOURCE_UNKNOWN:${r}`),(!je(l.label,160)||Object.keys(l).some(p=>!["label","unit","description"].includes(p))||l.unit!==void 0&&!je(l.unit,32)||l.description!==void 0&&!je(l.description,2e3))&&t.push(`WORKFLOW_VARIABLE_METADATA_INVALID:${r}`)}let s=n.logic===void 0?[]:n.logic;(!Array.isArray(s)||s.length>32)&&t.push("WORKFLOW_LOGIC_LIMIT_INVALID");let a=new Set;for(let r of Array.isArray(s)?s.slice(0,32):[]){let c=ue(r),l=String(c.code||"");(!/^[a-z][a-z0-9-]{2,63}$/.test(l)||a.has(l)||!je(c.title,160)||!je(c.description,4e3)||Object.keys(c).some(p=>!["code","title","description","phase","nodeId","inputPaths","outputPaths","source"].includes(p)))&&t.push(`WORKFLOW_LOGIC_METADATA_INVALID:${l}`),a.add(l),(!["submission","node_input","completion"].includes(String(c.phase))||c.phase==="node_input"&&!ue(e.nodes)[String(c.nodeId)]||c.phase!=="node_input"&&c.nodeId!==void 0)&&t.push(`WORKFLOW_LOGIC_ANCHOR_INVALID:${l}`);for(let p of["inputPaths","outputPaths"]){let d=c[p];if(!(p==="outputPaths"&&d===void 0))if(!Array.isArray(d)||d.length>32||new Set(d).size!==d.length)t.push(`WORKFLOW_LOGIC_PATHS_INVALID:${l}:${p}`);else for(let u of d)(!jn(u)||!qt(o,u))&&t.push(`WORKFLOW_LOGIC_SOURCE_UNKNOWN:${l}:${String(u)}`)}if(c.source!==void 0){let p=ue(c.source);(!je(p.path,256)||String(p.path).startsWith("/")||String(p.path).includes("..")||String(p.path).includes("://")||!/^sha256:[a-f0-9]{64}$/.test(String(p.digest))||p.symbol!==void 0&&!je(p.symbol,160)||Object.keys(p).some(d=>!["path","symbol","digest"].includes(d)))&&t.push(`WORKFLOW_LOGIC_SOURCE_REFERENCE_INVALID:${l}`)}}for(let r of Object.values(ue(e.nodes))){let c=ue(r),l=Array.isArray(c.branches)?c.branches:[];for(let p of l){let d=ui(p.when);t.push(...d.errors.map(u=>`${u}:${c.id}`));for(let u of d.paths)qt(o,u)||t.push(`WORKFLOW_VARIABLE_SOURCE_UNKNOWN:${c.id}:${u}`)}}return[...new Set(t)]}function Ed(e,t){let o=Mt(e),n=[],i=new Map,s=[];for(let c of Object.values(e.nodes)){if(c.kind==="approval")for(let[l,p,d]of[["approve",c.onApprove,"\u540C\u610F"],["reject",c.onReject,"\u62D2\u7EDD"]])p&&n.push({id:`${c.id}:${l}`,from:c.id,to:p,kind:l,label:d,variablePaths:[]});if(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 l=Object.values(c.inputs||{}).flatMap(p=>p.source==="fact"?[p.path]:[]);for(let p of l)i.has(p)||i.set(p,new Set),i.get(p).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:l})}if(c.kind==="condition"){for(let[l,p]of(c.branches||[]).entries()){let d=ui(p.when);for(let u of d.paths)i.has(u)||i.set(u,new Set),i.get(u).add(c.id);n.push({id:`${c.id}:branch:${l}`,from:c.id,to:p.target,kind:"branch",label:p.label||`\u6761\u4EF6 ${l+1}`,priority:l+1,expression:p.when,variablePaths:d.paths}),s.push(...d.errors.map(u=>({code:u,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 r=[...new Set([...i.keys(),...Object.keys(e.readability?.variables||{}),...(e.readability?.logic||[]).flatMap(c=>[...c.inputPaths,...c.outputPaths||[]])])].slice(0,128).map(c=>{let l=qt(o,c),p=e.readability?.variables?.[c],d=c.split("."),u=e.subject?.factProjection[d[0]],g=d[0]==="steps"?e.nodes[d[1]]:void 0;return l||s.push({code:"WORKFLOW_VARIABLE_SOURCE_UNKNOWN",path:c}),{path:c,label:p?.label||String(l?.schema.title||c),type:String(l?.schema.type||"unknown"),...p,required:l?.required||!1,usedBy:[...i.get(c)||[]],source:l&&g?.handler?{kind:"step_output",nodeId:g.id,handlerCode:g.handler.code,handlerVersion:g.handler.version}:l&&u&&e.subject?{kind:"subject_field",resourceCode:e.subject.resourceCode,fieldPath:[u,...d.slice(1)].join(".")}:{kind:l?"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.kind==="action"&&c.handler?{businessStep:{handler:c.handler,inputs:c.inputs||{},outputPaths:Object.keys(ue(c.outputSchema).properties||{}).map(l=>`steps.${c.id}.${l}`)}}:{}})),edges:n,variables:r,logic:e.readability?.logic||[],diagnostics:s}}function Kt(e,t=[],o=0){if(!e||o>20)return"\u65E0\u6CD5\u8BC6\u522B\u7684\u6761\u4EF6";if(e.op==="path")return t.find(a=>a.path===e.path)?.label||e.path;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${Kt(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${Kt(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,s=i&&e.right.op==="literal"&&typeof e.right.value=="number"?t.find(a=>a.path===i)?.unit:void 0;return`${Kt(e.left,t,o+1)} ${n[e.op]} ${Kt(e.right,t,o+1)}${s?` ${s}`:""}`}function ft(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||[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 yd(e,t,o,n){return e.kind==="approval"&&e.initiatorApprovalPolicy==="auto_approve"&&ft({nodes:{node:e}}).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 Wn=["approve","reject","return","transfer","delegate","add_assignee"],Un=["fixed_users","app_role","app_role_in_scope"],Nr=["single","any","all","sequence"],Ve=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Xe=(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 pt(e){return e.allowedOperations||[...Wn]}function Or(e,t){return t?.commentRequired??e==="reject"}function pi(e,t,o={},n=!1){return!(!Ve(e)||!Object.keys(e).length||!Xe(e,n?["enabled","label","commentRequired"]:["label","commentRequired"])||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&&Or(t,o)&&!e.commentRequired))}function Mn(e,t){let o=[];for(let[n,i]of Object.entries(e?.nodes||{})){if(!Ve(i))continue;let s=i.administration,a=i.operationPolicy;if(i.kind==="cc"){(a!==void 0||s!==void 0&&(!Ve(s)||!Xe(s,["assigneeProviders"])))&&o.push(`WORKFLOW_NODE_ADMINISTRATION_INVALID:${n}`),s?.assigneeProviders!==void 0&&!Jt(s.assigneeProviders,Un,3)&&o.push(`WORKFLOW_NODE_ADMINISTRATION_PROVIDERS_INVALID:${n}`),s?.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"){(s!==void 0||a!==void 0)&&o.push(`WORKFLOW_NODE_ADMINISTRATION_APPROVAL_REQUIRED:${n}`);continue}if(a!==void 0&&(!Ve(a)||Object.keys(a).length>8||Object.entries(a).some(([c,l])=>!Wn.includes(c)||!pt(i).includes(c)||!pi(l,c)))&&o.push(`WORKFLOW_NODE_OPERATION_POLICY_INVALID:${n}`),s===void 0)continue;if(!Ve(s)||!Xe(s,["modes","assigneeProviders","operations"])){o.push(`WORKFLOW_NODE_ADMINISTRATION_INVALID:${n}`);continue}s.modes!==void 0&&(!Jt(s.modes,Nr,4)||!s.modes.includes(i.mode))&&o.push(`WORKFLOW_NODE_ADMINISTRATION_MODES_INVALID:${n}`),s.assigneeProviders!==void 0&&!Jt(s.assigneeProviders,Un,3)&&o.push(`WORKFLOW_NODE_ADMINISTRATION_PROVIDERS_INVALID:${n}`);let r=t?.bindings[i.binding||""];r&&Array.isArray(s.assigneeProviders)&&s.assigneeProviders.includes("app_role_in_scope")&&!r.scope&&o.push(`WORKFLOW_NODE_ADMINISTRATION_SCOPE_REQUIRED:${n}`),s.operations!==void 0&&(!Jt(s.operations,Wn,8)||s.operations.some(c=>!pt(i).includes(c)))&&o.push(`WORKFLOW_NODE_ADMINISTRATION_OPERATIONS_INVALID:${n}`)}return o}function Od(e,t,o){let n=[];if(!e||!Ve(o)||!Object.keys(o).length||!Xe(o,["title","description","assignee","mode","operations"]))return["WORKFLOW_V2_NODE_CONFIGURATION_PATCH_INVALID"];let i=o;for(let a of["title","description"])i[a]!==void 0&&(typeof i[a]!="string"||i[a].length>(a==="title"?255:1e3)||a==="title"&&!i[a].trim())&&n.push("WORKFLOW_V2_NODE_CONFIGURATION_PATCH_INVALID");let s=e.administration;if(i.mode!==void 0&&(e.kind!=="approval"||!s?.modes?.includes(i.mode))&&n.push("WORKFLOW_V2_NODE_CONFIGURATION_MODE_READONLY"),i.operations!==void 0&&(e.kind!=="approval"||!Ve(i.operations)||!Object.keys(i.operations).length||Object.keys(i.operations).length>8||Object.entries(i.operations).some(([a,r])=>!s?.operations?.includes(a)||!pt(e).includes(a)||!pi(r,a,e.operationPolicy?.[a],!0)))&&n.push("WORKFLOW_V2_NODE_CONFIGURATION_OPERATION_INVALID"),i.assignee!==void 0){let a=i.assignee,r=s?.assigneeProviders||(e.kind==="approval"&&t&&Un.includes(t.provider)?[t.provider]:[]);!Ve(a)||!["approval","cc"].includes(e.kind)||!r.includes(a.provider)||a.provider==="app_role_in_scope"&&!t?.scope?n.push("WORKFLOW_V2_NODE_CONFIGURATION_PROVIDER_READONLY"):a.provider==="fixed_users"?(!Xe(a,["provider","users"])||!Array.isArray(a.users)||a.users.length<1&&!(e.kind==="approval"&&e.emptyPolicy==="skip")||a.users.length>(e.kind==="cc"?20:200)||new Set(a.users).size!==a.users.length||a.users.some(c=>typeof c!="string"||!c.trim()||c.length>255))&&n.push("WORKFLOW_V2_NODE_CONFIGURATION_USERS_INVALID"):(!Xe(a,["provider","roleCode"])||typeof a.roleCode!="string"||!/^[a-z][a-z0-9_-]{0,127}$/.test(a.roleCode))&&n.push("WORKFLOW_V2_NODE_CONFIGURATION_ROLE_INVALID")}return n.push(...ft({nodes:{node:{...e,operationPolicy:Tr(e,i).operationPolicy}}})),n}function Tr(e,t){let o=Object.fromEntries(pt(e).flatMap(n=>{let i=n,s=t?.operations?.[i],a={...e.operationPolicy?.[i],...s?.label!==void 0?{label:s.label}:{},...s?.commentRequired!==void 0?{commentRequired:s.commentRequired}:{}};return Object.keys(a).length?[[i,a]]:[]}));return{mode:t?.mode||e.mode,initiatorApprovalPolicy:e.initiatorApprovalPolicy||"manual",allowedOperations:pt(e).filter(n=>t?.operations?.[n]?.enabled!==!1),operationPolicy:o,fieldPolicy:{default:e.fieldPolicy?.default||"readonly",fields:{...e.fieldPolicy?.fields}}}}var hd=20,hr=["fixed_users","initiator","input_users","form_field_users","app_role","app_role_in_scope","previous_node_actor"];function Bn(e,t){let o=[];for(let[n,i]of Object.entries(e?.nodes||{})){if(i?.kind!=="cc"||((Object.keys(i).some(c=>!["id","kind","title","binding","next","emptyPolicy","notify","administration"].includes(c))||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 s=t.bindings?.[i.binding];if(!s){o.push(`WORKFLOW_CC_BINDING_NOT_FOUND:${n}`);continue}hr.includes(s.provider)||o.push(`WORKFLOW_CC_PROVIDER_INVALID:${n}`);let a=s.min??1,r=s.max??20;(!Number.isSafeInteger(a)||!Number.isSafeInteger(r)||a<1||r<a||r>20||s.provider==="fixed_users"&&(!Array.isArray(s.users)||!s.users.length||s.users.length>r))&&o.push(`WORKFLOW_CC_RECIPIENT_LIMIT_INVALID:${n}`)}return[...new Set(o)]}var mi=["fixed_users","input_users","form_field_users","app_role","app_role_in_scope"];function Kn(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&&!mi.includes(t.bindings?.[i.binding||""]?.provider)&&o.push(`WORKFLOW_APPROVAL_EMPTY_PROVIDER_UNSUPPORTED:${n}`));return o}function Cd(e,t){return e.kind==="approval"&&e.emptyPolicy==="skip"&&t?.emptyResult==="no_candidates"&&mi.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 _i(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")}var Rr="openxiangda.workflow-rejection-notification/v1",wd=4096;function gi(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Qe(e,t){return typeof e=="string"&&e.trim().length>0&&e.length<=t}function qn(e,t){return Object.keys(e).sort().join(",")===t.sort().join(",")}function Ai(e){let t=e?.rejectionNotification;return t===void 0?[]:!gi(t)||!qn(t,["recipient","title","summary"])||t.recipient!=="record_last_modifier"||!Qe(t.title,160)||!Qe(t.summary,500)?["WORKFLOW_REJECTION_NOTIFICATION_INVALID"]:Qe(e.subject?.resourceCode,63)?[]:["WORKFLOW_REJECTION_NOTIFICATION_SUBJECT_REQUIRED"]}function Dd(e){if(!gi(e)||e.schemaVersion!==Rr||e.recipient!=="record_last_modifier"||!Qe(e.title,160)||!Qe(e.summary,500))return!1;let t=["schemaVersion","recipient","title","summary","status","sourceRevision"];if(e.status==="ready"){if(!qn(e,[...t,"userId"])||!Qe(e.userId,255)||!Number.isSafeInteger(e.sourceRevision)||Number(e.sourceRevision)<1)return!1}else if(e.status==="skipped"){if(!qn(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 Ei(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"].includes(i)))return["WORKFLOW_BUSINESS_COMMAND_HANDLERS_INVALID"];let n=[];for(let[i,s]of Object.entries(o)){if(!s||typeof s!="object"||Array.isArray(s)||Object.keys(s).join(",")!=="operationCode"||!/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/.test(s.operationCode||"")){n.push("WORKFLOW_BUSINESS_COMMAND_HANDLER_INVALID");continue}if(!t)continue;let a=t.find(r=>r.code===s.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(i))&&n.push("WORKFLOW_BUSINESS_COMMAND_OPERATION_INVALID")}return 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 kd={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"]}}},{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 Cr=["fixed_users","initiator","app_role","app_role_in_scope"],Sr=e=>!!e&&typeof e=="object"&&!Array.isArray(e);function Jn(e,t){let o=e?.launchPreflight;if(o===void 0)return[];if(!Sr(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 s=e.nodes?.[i];if(!s||s.kind!=="approval"){n.push(`WORKFLOW_LAUNCH_PREFLIGHT_NODE_INVALID:${i}`);continue}if(!t)continue;let a=t.bindings?.[s.binding||""];(!a||!Cr.includes(a.provider)||a.candidateField!==void 0)&&n.push(`WORKFLOW_LAUNCH_PREFLIGHT_PROVIDER_UNSUPPORTED:${i}`)}return n}var wr=64,zn=1024*1024,Dr=65536,yi=100,$r=400,We=new Set(["__proto__","prototype","constructor"]),bi=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,_t=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,Ii=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,ae=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&[null,Object.prototype].includes(Object.getPrototypeOf(e)),Se=(e,t)=>ae(e)&&Object.keys(e).every(o=>t.includes(o)&&!We.has(o)),Gt=e=>{try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return 1/0}},Ni=e=>e==null||typeof e=="string"&&!e.trim()||Array.isArray(e)&&e.length===0;function Fe(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((n,i)=>Fe(n,t[i]));if(!ae(e)||!ae(t))return!1;let o=Object.keys(e);return o.length===Object.keys(t).length&&o.every(n=>Object.hasOwn(t,n)&&Fe(e[n],t[n]))}function Gn(e,t){let o=t.split(".");if(!(o.some(n=>!bi.test(n)||We.has(n))||o.length>12))return o.reduce((n,i)=>ae(n)&&Object.hasOwn(n,i)?n[i]:void 0,e)}function Pe(e,t){switch(e.op){case"literal":return e.value;case"path":return Gn({values:t},e.path);case"and":return e.values.every(o=>!!Pe(o,t));case"or":return e.values.some(o=>!!Pe(o,t));case"not":return!Pe(e.value,t);case"exists":return!Ni(Pe(e.value,t));default:{let o=Pe(e.left,t),n=Pe(e.right,t);return e.op==="eq"?Fe(o,n):e.op==="neq"?!Fe(o,n):e.op==="in"?Array.isArray(n)&&n.some(i=>Fe(i,o)):e.op==="contains"?Array.isArray(o)?o.some(i=>Fe(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 mt(e,t,o=0,n={nodes:0}){if(o>8||++n.nodes>64||!ae(e))return!1;if(e.op==="literal")return Se(e,["op","value"])&&Object.hasOwn(e,"value")&&Gt(e.value)<=4096&&gt(e.value);if(e.op==="path"){if(!Se(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(s=>_t.test(s)&&!We.has(s))}return["not","exists"].includes(e.op)?Se(e,["op","value"])&&mt(e.value,t,o+1,n):["and","or"].includes(e.op)?Se(e,["op","values"])&&Array.isArray(e.values)&&e.values.length>0&&e.values.length<=16&&e.values.every(i=>mt(i,t,o+1,n)):["eq","neq","gt","gte","lt","lte","in","contains"].includes(e.op)&&Se(e,["op","left","right"])&&mt(e.left,t,o+1,n)&&mt(e.right,t,o+1,n)}function zt(e,t,o){let n=[],i=e.taskPages;if(i!==void 0&&(!ae(i)||Object.keys(i).length===0||Object.keys(i).length>16||Gt(i)>Dr))return["WORKFLOW_TASK_PAGES_INVALID"];for(let[s,a]of Object.entries(i||{})){let r=`taskPages.${s}`;if(!bi.test(s)||We.has(s)||!Se(a,["title","fields"])||typeof a.title!="string"||!a.title.trim()||a.title.length>160||!Array.isArray(a.fields)||!a.fields.length||a.fields.length>wr){n.push(`WORKFLOW_TASK_PAGE_INVALID:${r}`);continue}let c=new Set(a.fields.map(d=>d?.code));c.size!==a.fields.length&&n.push(`WORKFLOW_TASK_PAGE_DUPLICATE_FIELD:${r}`);let l=0,p=new Set;for(let d of a.fields){if(!Se(d,["code","readonly","required","visibleWhen","requiredWhen","subtable"])||!_t.test(d.code)||We.has(d.code)||["readonly","required"].some(u=>d[u]!==void 0&&typeof d[u]!="boolean")||d.readonly&&(d.required||d.requiredWhen)){n.push(`WORKFLOW_TASK_PAGE_FIELD_INVALID:${r}`);continue}for(let u of["visibleWhen","requiredWhen"])d[u]!==void 0&&!mt(d[u],c)&&n.push(`WORKFLOW_TASK_PAGE_EXPRESSION_INVALID:${r}.${d.code}.${u}`);if(t){let u=t.get(d.code);if((!u||u.system||u.hidden||u.type==="serial-number"||!d.readonly&&u.widget==="readonly"||!d.readonly&&u.type==="subtable"&&!d.subtable||d.subtable&&u.type!=="subtable")&&n.push(`WORKFLOW_TASK_PAGE_RESOURCE_FIELD_INVALID:${r}.${d.code}`),d.subtable&&u?.subtable){let g=u.subtable;l+=g.maxRows??20,(p.has(g.resourceCode)||!Number.isSafeInteger(g.maxRows??20)||(g.maxRows??20)<1||(g.maxRows??20)>yi||!_t.test(g.foreignKey)||!_t.test(g.orderField)||g.foreignKey===g.orderField)&&n.push(`WORKFLOW_TASK_SUBTABLE_RELATION_INVALID:${r}.${d.code}`),p.add(g.resourceCode);let I=o?.get(g.resourceCode);o&&(!I||!["uuid","resource-ref.single"].includes(I.get(g.foreignKey)?.type||"")||I.get(g.orderField)?.type!=="number.integer")&&n.push(`WORKFLOW_TASK_SUBTABLE_RELATION_INVALID:${r}.${d.code}`);for(let E of Array.isArray(d.subtable.fields)?d.subtable.fields:[]){if(!E||typeof E.code!="string")continue;let N=I?.get(E.code);(E.code===g.foreignKey||E.code===g.orderField||I&&(!N||N.system||N.hidden||N.type==="subtable"||!E.readonly&&(N.widget==="readonly"||N.type==="serial-number")))&&n.push(`WORKFLOW_TASK_SUBTABLE_FIELD_UNSUPPORTED:${r}.${d.code}.${E.code}`)}}else d.subtable&&t&&n.push(`WORKFLOW_TASK_SUBTABLE_RELATION_INVALID:${r}.${d.code}`)}d.subtable&&(d.readonly||!Se(d.subtable,["fields","create","delete","reorder"])||["create","delete","reorder"].some(u=>d.subtable?.[u]!==void 0&&typeof d.subtable[u]!="boolean")||!Array.isArray(d.subtable.fields)||d.subtable.fields.some(u=>u?.subtable)?n.push(`WORKFLOW_TASK_SUBTABLE_PAGE_INVALID:${r}.${d.code}`):n.push(...zt({taskPages:{child:{title:"\u5B50\u884C",fields:d.subtable.fields}}},o?.get(t?.get(d.code)?.subtable?.resourceCode||"")).map(u=>`${u}:${r}.${d.code}`)))}(l>$r||l<0||!Number.isSafeInteger(l))&&n.push(`WORKFLOW_TASK_SUBTABLE_BUDGET_EXCEEDED:${r}`)}for(let[s,a]of Object.entries(e.nodes||{}))ae(a)&&a.taskPageCode!==void 0&&(a.kind!=="approval"||typeof a.taskPageCode!="string"||!ae(i)||!Object.hasOwn(i,a.taskPageCode)?n.push(`WORKFLOW_TASK_PAGE_NOT_FOUND:${s}`):Array.isArray(i[a.taskPageCode]?.fields)&&i[a.taskPageCode].fields.some(r=>r&&(a.fieldPolicy?.fields?.[r.code]||a.fieldPolicy?.default)==="hidden")&&n.push(`WORKFLOW_TASK_PAGE_FIELD_HIDDEN:${s}`));return n}function Oi(e,t){return e.fields.map(o=>({code:o.code,visible:o.visibleWhen===void 0||!!Pe(o.visibleWhen,t),readonly:o.readonly===!0,required:o.required===!0||o.requiredWhen!==void 0&&!!Pe(o.requiredWhen,t)}))}var Oe=class extends Error{constructor(o,n){super(o);this.code=o;this.field=n}code;field;rowIndex;childField};function vd(e,t){return t.map(o=>({key:String(o.id),id:String(o.id),revision:Number(o.revision),state:"persisted",values:Object.fromEntries(Oi({title:"\u5B50\u884C",fields:e.fields},o).filter(n=>n.visible&&!n.readonly).map(n=>[n.code,o[n.code]??null]))}))}function Ld(e,t,o,n,i,s=!0){let a=e.subtable,r=u=>{throw new Oe(u,e.code)};if(!a||!Number.isSafeInteger(t)||t<1||t>yi||!Array.isArray(n)||n.length>2*t||Gt(n)>zn||!gt(n))return r("WORKFLOW_TASK_SUBTABLE_VALUES_INVALID");let c=new Map(o.map(u=>[String(u.id),u])),l=new Set,p=new Set,d=[];for(let u of n){if(!Se(u,["key","state","id","revision","values"])||typeof u.key!="string"||!Ii.test(u.key)||l.has(u.key)||!["created","persisted","deleted"].includes(u.state)||!ae(u.values))return r("WORKFLOW_TASK_SUBTABLE_ROW_INVALID");if(l.add(u.key),u.state==="created"){if(!a.create||u.id!==void 0||u.revision!==void 0||c.has(u.key))return r("WORKFLOW_TASK_SUBTABLE_CREATE_FORBIDDEN")}else{if(typeof u.id!="string"||u.id!==u.key||!Ii.test(u.id)||p.has(u.id)||!Number.isSafeInteger(u.revision)||u.revision<1||!c.has(u.id))return r("WORKFLOW_TASK_SUBTABLE_SCOPE_CONFLICT");if(p.add(u.id),s&&Number(c.get(u.id).revision)!==u.revision)return r("WORKFLOW_TASK_SUBTABLE_REVISION_CONFLICT")}if(u.state==="deleted"){if(!a.delete||Object.keys(u.values).length)return r("WORKFLOW_TASK_SUBTABLE_DELETE_FORBIDDEN");continue}try{kr({title:e.code,fields:a.fields},u.id?c.get(u.id):{},u.values,i)}catch(g){if(!(g instanceof Oe))throw g;let I=new Oe(g.code,e.code);throw I.rowIndex=d.length,g.field!==void 0&&(I.childField=g.field),I}d.push(u)}if(p.size!==c.size)return r("WORKFLOW_TASK_SUBTABLE_SCOPE_CONFLICT");if(d.length>t)return r("WORKFLOW_TASK_SUBTABLE_MAX_ROWS_EXCEEDED");if(!a.reorder){let u=o.filter(I=>d.some(E=>E.id===String(I.id))).map(I=>String(I.id)),g=d.filter(I=>I.state==="persisted").map(I=>I.id);if(!Fe(u,g)||d.some((I,E)=>I.state==="created"&&d.slice(E+1).some(N=>N.state==="persisted")))return r("WORKFLOW_TASK_SUBTABLE_REORDER_FORBIDDEN")}return n}function gt(e,t={members:0},o=0){return++t.members>5e4||o>12?!1:e===null||typeof e=="boolean"?!0:typeof e=="string"?e.length<=zn:typeof e=="number"?Number.isFinite(e):Array.isArray(e)?e.length<=1e3&&e.every(n=>gt(n,t,o+1)):ae(e)&&Object.entries(e).every(([n,i])=>!We.has(n)&&gt(i,t,o+1))}function kr(e,t,o,n){if(!ae(o)||Gt(o)>zn||!gt(o))throw new Oe("WORKFLOW_TASK_FORM_VALUES_INVALID");let i={...t,...o},s=new Map(Oi(e,i).map(a=>[a.code,a]));for(let a of Object.keys(o)){let r=s.get(a);if(!r||r.readonly||!r.visible)throw new Oe("WORKFLOW_TASK_FORM_FIELD_NOT_EDITABLE",a)}if(n)for(let a of s.values()){let r=i[a.code],c=e.fields.find(l=>l.code===a.code)?.subtable&&Array.isArray(r)?r.every(l=>ae(l)&&l.state==="deleted"):Ni(r);if(a.visible&&!a.readonly&&a.required&&c)throw new Oe("WORKFLOW_TASK_FORM_REQUIRED",a.code)}return i}function xd(e,t,o){let n=JSON.parse(JSON.stringify(t));for(let[a,r]of Object.entries(e.subject?.factProjection||{})){let c=a.split(".");if(!c.length||c.length>12||a.length>128||c[0]==="steps"||c.some(p=>!_t.test(p)||We.has(p)))throw new Oe("WORKFLOW_TASK_FORM_FACT_PROJECTION_INVALID");if(!Object.hasOwn(o,r))throw new Oe("WORKFLOW_TASK_FORM_FACT_FIELD_MISSING",r);let l=n;for(let p of c.slice(0,-1))l=l[p]=ae(l[p])?l[p]:{};l[c.at(-1)]=o[r]===void 0?void 0:JSON.parse(JSON.stringify(o[r]))}let i=new Set,s=Object.values(e.nodes||{}).filter(a=>a.kind==="action");for(let a=0;a<=s.length;a++){let r=!1;for(let c of s)ae(n.steps)&&Object.hasOwn(n.steps,c.id)&&Object.values(c.inputs||{}).some(l=>l.source==="fact"&&!Fe(Gn(t,l.path),Gn(n,l.path)))&&(delete n.steps[c.id],i.add(c.id),r=!0);if(!r)break}return{facts:n,invalidatedNodeIds:[...i].sort()}}function jd(e,t,o){let n=e.nodes||{};for(let i of o){let s=new Set,a=new Map,r=c=>{if(c===i)return!0;if(a.has(c))return a.get(c);if(s.has(c)||s.size>200)return!1;let l=n[c];if(!ae(l)||l.kind==="end")return!1;s.add(c);let p=l.kind==="approval"?[l.onApprove]:l.kind==="condition"?[...(l.branches||[]).map(u=>u.target),l.otherwise]:[l.next],d=p.length>0&&p.every(u=>typeof u=="string"&&r(u));return s.delete(c),a.set(c,d),d};if(!r(t))return!1}return!0}var Ud=256,Md=64,Bd=262144,Vr=/^[a-z][a-z0-9_-]{0,127}$/,Pr=/^[A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z][A-Za-z0-9_]*)*$/,hi=new Set(["__proto__","prototype","constructor"]),Te=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Et=(e,t)=>Object.keys(e).every(o=>t.includes(o)),Ue=(e,t)=>typeof e=="string"&&e.trim().length>0&&e.length<=t&&!/[\u0000-\u001f\u007f]/.test(e),we=e=>typeof e=="string"&&Vr.test(e)&&!hi.has(e),Ri=e=>typeof e=="string"&&e.length<=255&&Pr.test(e)&&!e.split(".").some(t=>hi.has(t)),Fr=e=>Te(e)&&Et(e,["dimension","valueFrom","value"])&&we(e.dimension)&&(Ue(e.value,255)&&e.valueFrom===void 0||Ri(e.valueFrom)&&e.value===void 0),Ti=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)),At={type:"string",pattern:"^[a-z][a-z0-9_-]{0,127}$"},Hn={type:"string",minLength:1,maxLength:128},Kd={type:"object",additionalProperties:!1,required:["policyCode","title","strategy","dimensions","sources"],properties:{policyCode:At,title:Hn,strategy:{enum:["replace_then_append","replace_only"]},dimensions:{type:"object",maxProperties:8,propertyNames:At,additionalProperties:{type:"object",additionalProperties:!1,required:["title","valueFrom"],properties:{title:Hn,valueFrom:{type:"string",minLength:1,maxLength:255}}}},sources:{type:"object",minProperties:1,maxProperties:16,propertyNames:At,additionalProperties:{type:"object",additionalProperties:!1,required:["title","provider","roleCode"],properties:{title:Hn,provider:{enum:["app_role","app_role_in_scope"]},roleCode:At,scope:{type:"object",additionalProperties:!1,required:["dimension"],properties:{dimension:At,value:{type:"string",minLength:1,maxLength:255},valueFrom:{type:"string",minLength:1,maxLength:255}}}}}}}};function Ht(e){if(!Te(e)||!Et(e,["policyCode","title","strategy","dimensions","sources"])||!we(e.policyCode)||!Ue(e.title,128)||!["replace_then_append","replace_only"].includes(e.strategy))return["WORKFLOW_V2_ROUTING_POLICY_INVALID"];let t=[];return(!Te(e.dimensions)||Object.keys(e.dimensions).length>8||Object.entries(e.dimensions).some(([o,n])=>!we(o)||!Te(n)||!Et(n,["title","valueFrom"])||!Ue(n.title,128)||!Ri(n.valueFrom)))&&t.push("WORKFLOW_V2_ROUTING_DIMENSIONS_INVALID"),(!Te(e.sources)||Object.keys(e.sources).length<1||Object.keys(e.sources).length>16||Object.entries(e.sources).some(([o,n])=>!we(o)||!Te(n)||!Et(n,["title","provider","roleCode","scope"])||!Ue(n.title,128)||!we(n.roleCode)||!["app_role","app_role_in_scope"].includes(n.provider)||(n.provider==="app_role_in_scope"?!Fr(n.scope):n.scope!==void 0)))&&t.push("WORKFLOW_V2_ROUTING_SOURCES_INVALID"),t}function qd(e,t){if(Ht(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(!Te(i)||!Et(i,["ruleCode","title","enabled","workflowCode","nodeId","matches","sourceCode","effect","priority","validFrom","validTo"])||!we(i.ruleCode)||!Ue(i.title,128)||typeof i.enabled!="boolean"||!we(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&&!we(i.workflowCode)||i.nodeId!==void 0&&(!we(i.nodeId)||i.workflowCode===void 0)||i.validFrom!==void 0&&!Ti(i.validFrom)||i.validTo!==void 0&&!Ti(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),(!Te(i.matches)||Object.entries(i.matches).some(([s,a])=>!Object.hasOwn(e.dimensions,s)||!Array.isArray(a)||a.length<1||a.length>64||new Set(a).size!==a.length||a.some(r=>!Ue(r,255))))&&o.push(`WORKFLOW_V2_ROUTING_MATCH_INVALID:${i.ruleCode}`)}return[...new Set(o)]}function vr(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 Ci(e){let t=[],o=new Map;for(let n of e)for(let[i,s]of Object.entries(n.bindings||{})){if(!Te(s)||s.routing===void 0)continue;let a=Ht(s.routing);if(a.length){t.push(...a.map(l=>`${l}:${i}`));continue}let r=vr(s.routing),c=o.get(s.routing.policyCode);c&&c!==r&&t.push(`WORKFLOW_V2_ROUTING_POLICY_CONFLICT:${s.routing.policyCode}`),o.set(s.routing.policyCode,r)}return[...new Set(t)]}function Jd(e,t){let o={};for(let[n,i]of Object.entries(e.dimensions)){let s=t;for(let a of i.valueFrom.split("."))s=Te(s)&&Object.hasOwn(s,a)?s[a]:void 0;if(!(typeof s=="string"&&Ue(s,255)||typeof s=="number"&&Number.isFinite(s)||typeof s=="boolean"))throw new Error(`WORKFLOW_V2_ROUTING_FACT_REQUIRED:${n}`);o[n]=String(s)}return o}function Gd(e,t,o){let n=t.filter(l=>l.enabled&&(!l.validFrom||Date.parse(l.validFrom)<=o.at)&&(!l.validTo||Date.parse(l.validTo)>o.at)&&(!l.workflowCode||l.workflowCode===o.workflowCode)&&(!l.nodeId||l.nodeId===o.nodeId)&&Object.entries(l.matches).every(([p,d])=>d.includes(o.facts[p])));if(n.length>64)throw new Error("WORKFLOW_V2_ROUTING_MATCH_LIMIT_EXCEEDED");let i=(l,p)=>p.priority-l.priority||+!!l.workflowCode-+!!p.workflowCode||+!!l.nodeId-+!!p.nodeId||(l.ruleCode<p.ruleCode?-1:l.ruleCode>p.ruleCode?1:0),s=n.filter(l=>l.effect==="replace").sort(i);if(s.length>1&&s[0].priority===s[1].priority)throw new Error("WORKFLOW_V2_ROUTING_REPLACE_CONFLICT");let a=s[0],r=a&&e.strategy==="replace_only"?[]:n.filter(l=>l.effect==="append").sort(i),c=[...a?[a]:[],...r];return{matched:n.sort(i),replacement:a,applied:c,ignored:n.filter(l=>!c.includes(l))}}import*as en from"crypto";var Si="native-4",wi={"application-native-2":"1.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-api-v2":"1.1.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.managed-concurrency":"1.0.0","data.managed-concurrency.durable":"1.0.0","workflow.named-input-sources":"1.0.0","directory-v2":"1.0.0","directory.selected-user":"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.native-data-actions":"1.0.0","workflow-kernel-v2":"1.0.0","workflow.business-data-command":"1.0.0","workflow.launch-preflight":"1.0.0","workflow.optional-rejection-comment":"1.0.0","workflow.optional-withdrawal-reason":"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-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.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","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 Yd=5,Xd=20,Qd=50,Zd=50,el=100,yt=class extends Error{constructor(o,n){super(o);this.code=o;this.pointer=n;this.name="NativeDataPolicyExpressionV2Error"}code;pointer};function Yt(e,t){let o=[],n=(i,s,a)=>{a>5&&It("NATIVE_DATA_POLICY_EXPRESSION_DEPTH_EXCEEDED",s);let r=$i(i,s),c=["allOf","anyOf"].filter(d=>d in r);if(c.length===0){o.push({rule:r,pointer:s}),o.length>50&&It("NATIVE_DATA_POLICY_EXPRESSION_LEAVES_EXCEEDED",s);return}let l=c[0],p=r[l];(c.length!==1||Object.keys(r).length!==1||!Array.isArray(p)||p.length<1||p.length>20)&&It("NATIVE_DATA_POLICY_EXPRESSION_GROUP_INVALID",s),p.forEach((d,u)=>n(d,`${s}/${l}/${u}`,a+1))};return n(e,t,1),o}function Di(e,t){Yt(e,t);let o=(n,i)=>{let s=$i(n,i);if(Array.isArray(s.allOf))return Yn(s.allOf.flatMap((a,r)=>o(a,`${i}/allOf/${r}`)),i);if(Array.isArray(s.anyOf)){let a=[[]];return s.anyOf.forEach((r,c)=>{let l=o(r,`${i}/anyOf/${c}`);a=Yn(a.flatMap(p=>l.map(d=>[...p,...d])),i)}),a}return[[s]]};return Yn(o(e,t),t)}function Yn(e,t){let o=e.reduce((n,i)=>n+i.length,0);return(e.length>50||o>100)&&It("NATIVE_DATA_POLICY_EXPRESSION_EXPANSION_EXCEEDED",t),e}function $i(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&It("NATIVE_DATA_POLICY_EXPRESSION_NODE_INVALID",t),e}function It(e,t){throw new yt(e,t)}var Lr="openxiangda.config-bundle/v3",Hi="openxiangda.contract-bundle/v3",ki="openxiangda.native-configuration-projection/v1",Nt=Si,xr=/^[a-f0-9]{64}$/,jr=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,Wr=/^app:[a-z][a-z0-9]*(?:-[a-z0-9]+)*:[A-Za-z0-9:._*-]+$/,Ur=/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/,Mr=/^[a-z][a-z0-9]*(?:[-.][a-z0-9]+)*$/,Br=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,Kr=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,Vi=/^[A-Za-z][A-Za-z0-9_]{0,127}$/,qr=/^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*$/,Jr=/^[A-Z][A-Z0-9_]*$/,Gr=/^[a-z][a-z0-9-]{2,63}$/,zr=/^[A-Za-z][A-Za-z0-9_-]{0,127}$/,Hr=/^[A-Za-z][A-Za-z0-9_.]{0,127}$/,Yr=16,Xr=2*1024,Qr=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"]),Zr=new Set(["overview","database","operations","workflow","members","calendar","document","folder","settings"]),ea=new Set(["approve","reject","return","transfer","delegate","add_assignee","resubmit","withdraw","terminate","admin_reassign","admin_override","retry_resolution"]),ta=4*1024*1024,na=8*1024*1024,oa=40,ia=1e5,Qn=1024*1024,sa="openxiangda.event-handler-manifest/v2",Yi="openxiangda.application-route-manifest/v3",Pi=64,Xi=new Set(["id","revision","created_by","updated_by","created_at","updated_at"]),X=Object.freeze({perspectives:100,resources:100,subjectReadSurfaces:50,capabilities:2e3,operations:500,eventConsumers:100,eventProducers:1e3,eventSchemas:100,eventTypes:500,workflows:100,routes:500,adminPages:500,adminNavigationGroups:100,adminNavigationItems:500}),Zn=["openxiangda.data.record.created.v2","openxiangda.data.record.updated.v2","openxiangda.data.record.deleted.v2"],eo=["openxiangda.workflow.node.skipped.v2",ut,"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"],ra=new Set(eo),to=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,s])=>[i,String(s).slice(0,128)]))}};function $l(e){let t=S(e.appCode,"/appCode",128);jr.test(t)||m("NATIVE_CONFIG_APP_CODE_INVALID","/appCode");let o=oo(e.expectedConfigDigest,"/expectedConfigDigest"),n=oo(e.expectedContractDigest,"/expectedContractDigest"),i=Ji(e.configBytes,ta,"/configBytes","NATIVE_CONFIG_ARTIFACT_TOO_LARGE"),s=Ji(e.contractBytes,na,"/contractBytes","NATIVE_CONTRACT_ARTIFACT_TOO_LARGE");Gi(i,o,"/configBytes","NATIVE_CONFIG_DIGEST_MISMATCH"),Gi(s,n,"/contractBytes","NATIVE_CONTRACT_DIGEST_MISMATCH");let a=Ki(i,"/configBytes","NATIVE_CONFIG_JSON_INVALID","NATIVE_CONFIG_NOT_CANONICAL"),r=Ki(s,"/contractBytes","NATIVE_CONTRACT_JSON_INVALID","NATIVE_CONTRACT_NOT_CANONICAL");qi(a,"/config"),qi(r,"/contracts");let c=a,l=r;la(c,t),ua(l,t,o);let p=fa(c,o,l.generatorVersion);Qa(p,l,c),ne(p)!==ne(l)&&m("NATIVE_CONTRACT_CLOSURE_MISMATCH",io(p,l,"/contracts"));let d={authz:{appCode:t,...c.authz,perspectives:c.perspectives,capabilityCatalog:p.capabilities},data:{appCode:t,resources:c.data.resources,resourceContracts:p.resources,...p.concurrency?{concurrency:p.concurrency}:{},...p.subjectReadSurfaces?{subjectReadSurfaces:p.subjectReadSurfaces}:{}},events:{appCode:t,...c.events,consumers:p.eventConsumers,producers:p.eventProducers,handlerManifest:p.eventHandlerManifest,eventTypes:p.eventTypes,capturePlans:ca({resources:c.data.resources,dataPolicies:c.authz.dataPolicies,subscriptions:p.eventConsumers,capturePolicies:c.events.capturePolicies})},workflows:{appCode:t,...c.workflows,contracts:p.workflows},runtime:{appCode:t,requirements:c.runtime,backend:c.backend,frontend:c.frontend},contracts:p},u={authz:Ze(d.authz),data:Ze(d.data),events:Ze(d.events),workflows:Ze(d.workflows),runtime:Ze(d.runtime),contracts:Ze(d.contracts)},g={configDigest:o,contractDigest:n,generatorVersion:l.generatorVersion},I=aa(c),E={schemaVersion:ki,compilerContractVersion:Nt,appCode:t,source:g,projections:u,requiredPlatformCapabilities:I,aggregateDigest:Q({schemaVersion:ki,compilerContractVersion:Nt,appCode:t,source:g,requiredPlatformCapabilities:I,projectionDigests:Object.fromEntries(Object.entries(u).map(([N,y])=>[N,y.digest]))})};return ds(E)}function aa(e){let t=e.authz.roles,o=e.data.resources,n=e.backend.operations,i=n.filter(f=>f.platformAccess?.directory?.mode==="current-initiator"&&f.platformAccess.directory.fields.includes("phone")),s=(e.data.concurrency?.commands||[]).filter(f=>f.execution?.directory?.mode==="current-initiator"&&f.execution.directory.fields.includes("phone")),a=t.some(f=>f.capabilities.some(b=>b.endsWith(":directory:read")))||o.some(f=>f.schema.fields.some(b=>["user.single","user.multiple","department.single","department.multiple"].includes(b.type)))||n.some(f=>f.platformAccess?.directory),r=!!(e.events.subscriptions.length||e.events.timers.length||e.events.dateTriggers.length||e.events.schemas.length),c=n.some(f=>f.platformAccess?.managedFiles||f.platformAccess?.managedFileCopies)||e.events.subscriptions.some(f=>f.platformAccess?.managedFileCopies),l=e.workflows.definitions.some(f=>f.definition.rejectionNotification!==void 0)||n.some(f=>f.platformAccess?.notification)||e.events.subscriptions.some(f=>f.platformAccess?.notification),p=(f,b,h=!1)=>{let C=o.find($=>$.code===f.definition.subject?.resourceCode)?.schema.fields||[];return Object.values(f.definition.taskPages||{}).some($=>$.fields.some(k=>{if(k.readonly)return!1;let W=C.find(Y=>Y.code===k.code);if(!h&&W&&b.includes(W.type))return!0;if(!k.subtable||!W?.subtable)return!1;let v=o.find(Y=>Y.code===W.subtable.resourceCode)?.schema.fields||[];return k.subtable.fields.some(Y=>!Y.readonly&&v.some(te=>te.code===Y.code&&b.includes(te.type)))}))},d=e.workflows.definitions.filter(f=>p(f,["file","image","signature","text.rich"])),u=e.workflows.definitions.filter(f=>p(f,["signature","text.rich"])),g=e.workflows.definitions.filter(f=>p(f,["file","image","signature","text.rich"],!0)),I=e.workflows.definitions.filter(f=>f.launch.mode==="standalone"||f.launch.mode==="hidden-handoff"),E=n.some(f=>f.platformAccess?.workflow)||I.length>0,N=I.filter(f=>{let b=f.launch.submission;if(!b)return!1;let h=o.find(C=>C.code===f.definition.subject.resourceCode);return[b.create,b.existing].some(C=>C&&Object.values(C.inputs).some($=>$.source==="field"&&h?.schema.fields.some(k=>k.code===$.fieldCode&&k.type.startsWith("resource-ref.")&&k.source)))}),y={resources:o},_={perspectives:e.perspectives,authz:e.authz},A={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(f=>({code:f.code,method:f.method,path:f.path,capability:f.capability,platformAccess:f.platformAccess||null,...f.browser?{browser:f.browser}:{},ai:f.ai||null}))}};return[...o.some(f=>f.uniqueKeys?.length)?[{code:"data.unique-keys",declaration:o.filter(f=>f.uniqueKeys?.length).map(f=>({code:f.code,uniqueKeys:f.uniqueKeys}))}]:[],...e.data.concurrency?[{code:"data.managed-concurrency",declaration:e.data.concurrency}]:[],...e.data.concurrency?.commands.some(f=>f.mode==="durable")?[{code:"data.managed-concurrency.durable",declaration:e.data.concurrency}]:[],...o.some(f=>f.decimalReservationLifecycle)?[{code:"data.decimal-reservation-lifecycle",declaration:o.filter(f=>f.decimalReservationLifecycle).map(f=>({code:f.code,decimalReservationLifecycle:f.decimalReservationLifecycle}))}]:[],...n.some(f=>f.platformAccess?.dataCommands)?[{code:"data.business-commands",declaration:n.filter(f=>f.platformAccess?.dataCommands)}]:[],...n.some(f=>f.platformAccess?.recordEdit)?[{code:"data.record-edit",declaration:n.filter(f=>f.platformAccess?.recordEdit)}]:[],...n.some(f=>f.platformAccess?.decimalReservation)||e.events.subscriptions.some(f=>f.platformAccess?.decimalReservation)?[{code:"data.decimal-reservations",declaration:[...n.filter(f=>f.platformAccess?.decimalReservation).map(f=>({code:f.code,decimalReservation:f.platformAccess.decimalReservation})),...e.events.subscriptions.filter(f=>f.platformAccess?.decimalReservation).map(f=>({subscriptionCode:f.code,decimalReservation:f.platformAccess.decimalReservation}))]}]:[],{code:"application-native-2",declaration:A},{code:"authz.native-batch-explain",declaration:_},{code:"authz.native-management",declaration:_},{code:"deployment.durable-runs",declaration:A.backend},{code:"deployment.platform-executor",declaration:A.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:y},{code:"data.native-golden-crud",declaration:y}]:[],...o.some(f=>f.recordComments!==void 0)?[{code:"data.record-comments",declaration:y}]:[],...o.some(f=>f.recordDeletion!==void 0)?[{code:"data.workflow-record-deletion",declaration:y}]:[],...o.some(f=>f.recordPrint!==void 0)?[{code:"data.record-print",declaration:y}]:[],...o.some(f=>f.workflowHistory!==void 0)?[{code:"workflow.record-history-read",declaration:y}]:[],...o.some(Co)?[{code:"data.audit-read-access",declaration:y}]:[],...a?[{code:"directory-v2",declaration:{roles:t.map(f=>({code:f.code,capabilities:f.capabilities.filter(b=>b.endsWith(":directory:read"))})),resources:o.map(f=>({code:f.code,fields:f.schema.fields.filter(b=>["user.single","user.multiple","department.single","department.multiple"].includes(b.type))})),operations:n.filter(f=>f.platformAccess?.directory).map(f=>({code:f.code,directory:f.platformAccess.directory}))}}]:[],...n.some(f=>f.platformAccess?.directory?.mode==="selected-user")?[{code:"directory.selected-user",declaration:n.filter(f=>f.platformAccess?.directory?.mode==="selected-user").map(f=>({code:f.code,directory:f.platformAccess.directory}))}]:[],...i.length||s.length?[{code:"directory.current-initiator-phone",declaration:{operations:i.map(f=>({code:f.code,directory:f.platformAccess.directory})),commands:s.map(f=>({code:f.code,directory:f.execution.directory}))}}]:[],...c?[{code:"data.managed-files",declaration:{operations:n.filter(f=>f.platformAccess?.managedFiles||f.platformAccess?.managedFileCopies).map(f=>({code:f.code,...f.platformAccess?.managedFiles?{managedFiles:f.platformAccess.managedFiles}:{},...f.platformAccess?.managedFileCopies?{managedFileCopies:f.platformAccess.managedFileCopies}:{}})),subscriptions:e.events.subscriptions.filter(f=>f.platformAccess?.managedFileCopies).map(f=>({code:f.code,managedFileCopies:f.platformAccess.managedFileCopies}))}}]:[],...e.events.subscriptions.some(f=>f.execution)?[{code:"events.native-data-actions",declaration:e.events.subscriptions.filter(f=>f.execution)}]:[],...e.events.capturePolicies?.length?[{code:"events.capture-policy",declaration:e.events.capturePolicies}]:[],...r?[{code:"events-v2",declaration:e.events},{code:"events.durable-receipts",declaration:e.events}]:[],...e.data.resources.some(f=>f.schema.fields.some(b=>b.userCandidates!==void 0))?[{code:"data.user-candidates",declaration:e.data.resources.filter(f=>f.schema.fields.some(b=>b.userCandidates!==void 0))}]:[],...e.workflows.activations.length?[{code:"workflow-kernel-v2",declaration:e.workflows},{code:"workflow.fresh-command-token",declaration:e.workflows}]:[],...e.workflows.definitions.some(f=>f.definition.instanceCommands!==void 0)?[{code:"workflow.instance-cancellation-policy",declaration:e.workflows.definitions.filter(f=>f.definition.instanceCommands!==void 0)}]:[],...e.workflows.definitions.some(f=>f.definition.instanceCommands?.withdraw?.reasonRequired===!1)?[{code:"workflow.optional-withdrawal-reason",declaration:e.workflows.definitions.filter(f=>f.definition.instanceCommands?.withdraw?.reasonRequired===!1)}]:[],...e.workflows.definitions.some(f=>f.definition.rejectionNotification!==void 0)?[{code:"workflow.rejection-notification",declaration:e.workflows.definitions.filter(f=>f.definition.rejectionNotification!==void 0)}]:[],...e.workflows.definitions.some(f=>f.definition.commandHandlers!==void 0)||n.some(f=>f.platformAccess?.workflow?.businessCommands)?[{code:"workflow.business-data-command",declaration:{definitions:e.workflows.definitions.filter(f=>f.definition.commandHandlers!==void 0),operations:n.filter(f=>f.platformAccess?.workflow?.businessCommands)}}]:[],...e.workflows.definitions.some(f=>f.definition.launchPreflight!==void 0)?[{code:"workflow.launch-preflight",declaration:e.workflows.definitions.filter(f=>f.definition.launchPreflight!==void 0)}]:[],...e.workflows.definitions.some(f=>Object.values(f.definition.nodes).some(b=>b.operationPolicy?.reject?.commentRequired===!1))?[{code:"workflow.optional-rejection-comment",declaration:e.workflows.definitions.filter(f=>Object.values(f.definition.nodes).some(b=>b.operationPolicy?.reject?.commentRequired===!1))}]:[],...N.length?[{code:"workflow.named-input-sources",declaration:N}]:[],...e.workflows.definitions.some(f=>Object.values(f.definition.nodes).some(b=>b.administration!==void 0||b.operationPolicy!==void 0))?[{code:"workflow.node-administration",declaration:e.workflows.definitions.filter(f=>Object.values(f.definition.nodes).some(b=>b.administration!==void 0||b.operationPolicy!==void 0))}]:[],...e.workflows.definitions.some(f=>Object.values(f.definition.nodes).some(b=>b.kind==="approval"&&b.emptyPolicy!==void 0))?[{code:"workflow.approval-empty-policy",declaration:e.workflows.definitions.filter(f=>Object.values(f.definition.nodes).some(b=>b.kind==="approval"&&b.emptyPolicy!==void 0))}]:[],...e.workflows.definitions.some(f=>Object.values(f.definition.nodes).some(b=>b.initiatorApprovalPolicy!==void 0))?[{code:"workflow.initiator-approval-policy",declaration:e.workflows.definitions.filter(f=>Object.values(f.definition.nodes).some(b=>b.initiatorApprovalPolicy!==void 0))}]:[],...e.workflows.definitions.some(f=>Object.values(f.definition.nodes).some(b=>b.kind==="cc"))?[{code:"workflow.automatic-cc",declaration:e.workflows.definitions.filter(f=>Object.values(f.definition.nodes).some(b=>b.kind==="cc"))}]:[],...e.workflows.definitions.some(f=>f.definition.taskPages!==void 0)?["workflow.task-page-submit","workflow.task-private-drafts"].map(f=>({code:f,declaration:e.workflows.definitions.filter(b=>b.definition.taskPages!==void 0)})):[],...d.length?[{code:"workflow.task-managed-files",declaration:d}]:[],...g.length?[{code:"workflow.task-owned-files",declaration:g}]:[],...u.length?[{code:"workflow.task-rich-fields",declaration:u}]:[],...e.workflows.definitions.some(f=>Object.values(f.definition.taskPages||{}).some(b=>b.fields.some(h=>h.subtable)))?[{code:"workflow.task-owned-subtables",declaration:e.workflows.definitions.filter(f=>Object.values(f.definition.taskPages||{}).some(b=>b.fields.some(h=>h.subtable)))}]:[],...e.workflows.definitions.some(f=>Object.values(f.definition.nodes).some(b=>b.kind==="action"))?[{code:"workflow.durable-business-step",declaration:e.workflows.definitions.filter(f=>Object.values(f.definition.nodes).some(b=>b.kind==="action"))}]:[],...e.workflows.bindings.some(f=>Object.values(f.binding.bindings).some(b=>b.routing!==void 0))?[{code:"workflow.assignment-routing",declaration:e.workflows.bindings.filter(f=>Object.values(f.binding.bindings).some(b=>b.routing!==void 0))}]:[],...E?[{code:"business-process.durable-command",declaration:{operations:n.filter(f=>f.platformAccess?.workflow).map(f=>({code:f.code,workflow:f.platformAccess.workflow})),definitions:I,activations:e.workflows.activations.filter(f=>I.some(b=>b.definition.code===f.workflowCode))}}]:[],...l?[{code:"notification-hub-v2",declaration:{...e.workflows.definitions.some(f=>f.definition.rejectionNotification!==void 0)?{rejectionNotifications:e.workflows.definitions.filter(f=>f.definition.rejectionNotification!==void 0)}:{},operations:n.filter(f=>f.platformAccess?.notification).map(f=>({code:f.code,notification:f.platformAccess.notification})),subscriptions:e.events.subscriptions.filter(f=>f.platformAccess?.notification).map(f=>({code:f.code,notification:f.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:f,declaration:b})=>({code:f,contractVersion:f==="data.unique-keys"?o.some(h=>Xo(h.schema.fields,h.uniqueKeys)==="1.1.0")?"1.1.0":"1.0.0":wi[f],usageDigest:`sha256:${Q(b)}`})).sort((f,b)=>f.code===b.code?0:f.code<b.code?-1:1)}function ca(e){let t=new Map,o=new Set(e.resources.map(s=>String(s.code)));for(let[s,a]of w(e.capturePolicies===void 0?[]:e.capturePolicies,"/capturePlan/capturePolicies",100).entries()){let r=`/capturePlan/capturePolicies/${s}`,c=O(a,r);R(c,["resourceCode","mode"],r);let l=G(c.resourceCode,`${r}/resourceCode`);o.has(l)||m("NATIVE_EVENT_CAPTURE_RESOURCE_NOT_FOUND",r,{resourceCode:l}),t.has(l)&&m("NATIVE_EVENT_CAPTURE_POLICY_DUPLICATE",r,{resourceCode:l}),c.mode!=="all"&&c.mode!=="subscribed"&&m("NATIVE_EVENT_CAPTURE_MODE_INVALID",`${r}/mode`),t.set(l,c.mode)}let n=new Map(e.dataPolicies.map((s,a)=>{let r=O(s,`/capturePlan/dataPolicies/${a}`);return[String(r.code),r]})),i=e.subscriptions.map((s,a)=>O(s,`/capturePlan/subscriptions/${a}`));return e.resources.map((s,a)=>{let r=`/capturePlan/resources/${a}`,c=O(s,r),l=G(c.code,`${r}/code`),p=c.schema?O(c.schema,`${r}/schema`):c,d=new Set(w(p.fields||[],`${r}/schema/fields`,500).map((b,h)=>K(O(b,`${r}/schema/fields/${h}`).code,`${r}/schema/fields/${h}/code`))),u=c.dataPolicyCode?P(c.dataPolicyCode,`${r}/dataPolicyCode`):null,g=u?n.get(u):void 0;u&&!g&&m("NATIVE_EVENT_CAPTURE_AUTHZ_POLICY_NOT_FOUND",r,{resourceCode:l,dataPolicyCode:u});let I=new Set;for(let b of g?.rules||[])I.add(String(b.field));if(g?.readExpression)for(let b of Yt(g.readExpression,`${r}/readExpression`))I.add(String(b.rule.field));let E=new Set,N=new Set,y=new Set;for(let[b,h]of i.entries()){let C=w(h.eventTypes,`/capturePlan/subscriptions/${b}/eventTypes`,20).map(String);if(!C.some(v=>v.startsWith("openxiangda.data.")))continue;let $=O(h.filter||{},`/capturePlan/subscriptions/${b}/filter`),k=Array.isArray($.resourceCodes)?$.resourceCodes.map(String):[];if(k.length&&!k.includes(l))continue;for(let v of C)Zn.includes(v)&&y.add(v);for(let v of da($,`/capturePlan/subscriptions/${b}/filter`))E.add(v);let W=O(h.payload||{},`/capturePlan/subscriptions/${b}/payload`);for(let v of w(W.fields||[],`/capturePlan/subscriptions/${b}/payload/fields`,32))N.add(K(v,`/capturePlan/subscriptions/${b}/payload/fields`))}let _=new Set([...E,...N]),A=new Set([..._,...I]);A.size>Pi&&m("NATIVE_EVENT_CAPTURE_FIELDS_LIMIT",r,{resourceCode:l,maximum:Pi});for(let b of A)!d.has(b)&&!(I.has(b)&&Xi.has(b))&&m("NATIVE_EVENT_CAPTURE_FIELD_NOT_FOUND",r,{resourceCode:l,field:b});let T=O(c.fieldPolicies||{},`${r}/fieldPolicies`);for(let b of _)T[b]?.mask==="omit"&&m("NATIVE_EVENT_CAPTURE_FIELD_SENSITIVE",r,{resourceCode:l,field:b});let f={resourceCode:l,...t.get(l)==="subscribed"?{capturedEventTypes:[...y].sort()}:{},filterFields:[...E].sort(),projectionFields:[...N].sort(),authorizationFields:[...I].sort(),captureFields:[...A].sort()};return{...f,digest:Q(f)}}).sort((s,a)=>s.resourceCode.localeCompare(a.resourceCode))}function da(e,t){let o=new Set;for(let[a,r]of w(e.changes||[],`${t}/changes`,16).entries()){let c=O(r,`${t}/changes/${a}`);o.add(K(c.field,`${t}/changes/${a}/field`))}let n=O(e.changedFields||{},`${t}/changedFields`);for(let a of["anyOf","allOf","noneOf"])for(let[r,c]of w(n[a]||[],`${t}/changedFields/${a}`,32).entries())o.add(K(c,`${t}/changedFields/${a}/${r}`));let i=0,s=(a,r,c)=>{c>3&&m("NATIVE_EVENT_FILTER_DEPTH_LIMIT",r);let l=O(a,r);if(l.change){let d=O(l.change,`${r}/change`);o.add(K(d.field,`${r}/change/field`)),i+=1;return}if(l.not){s(l.not,`${r}/not`,c+1);return}let p=l.all?"all":l.any?"any":null;p||m("NATIVE_EVENT_FILTER_CONDITION_INVALID",r);for(let[d,u]of w(l[p],`${r}/${p}`,16).entries())s(u,`${r}/${p}/${d}`,c+1)};return e.where&&s(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 la(e,t){R(e,["schemaVersion","compilerContractVersion","appCode","perspectives","authz","backend","data","events","workflows","frontend","runtime"],"/config"),x(e.schemaVersion,Lr,"/config/schemaVersion"),x(e.compilerContractVersion,Nt,"/config/compilerContractVersion"),x(e.appCode,t,"/config/appCode"),w(e.perspectives,"/config/perspectives",100);let o=O(e.authz,"/config/authz");R(o,["capabilities","roles","scopeDimensions","scopeSources","roleMembershipSources","relationshipGrantSources","dataPolicies","authorizationTransitions"],"/config/authz",["authenticatedUserRoleCode"]),w(o.capabilities,"/config/authz/capabilities",2e3),w(o.roles,"/config/authz/roles",100),w(o.scopeDimensions,"/config/authz/scopeDimensions",100),w(o.scopeSources,"/config/authz/scopeSources",100),w(o.roleMembershipSources,"/config/authz/roleMembershipSources",100),w(o.relationshipGrantSources,"/config/authz/relationshipGrantSources",100),w(o.dataPolicies,"/config/authz/dataPolicies",100),w(o.authorizationTransitions,"/config/authz/authorizationTransitions",100);let n=O(e.backend,"/config/backend");R(n,["secrets","operations"],"/config/backend"),w(n.secrets,"/config/backend/secrets",100),w(n.operations,"/config/backend/operations",500),Ja(n.secrets);let i=O(e.data,"/config/data");R(i,["resources"],"/config/data",["resourceDetailRoutes","subjectReadSurfaces","concurrency"]),w(i.resources,"/config/data/resources",100),i.subjectReadSurfaces!==void 0&&w(i.subjectReadSurfaces,"/config/data/subjectReadSurfaces",X.subjectReadSurfaces),i.resourceDetailRoutes!==void 0&&w(i.resourceDetailRoutes,"/config/data/resourceDetailRoutes",100);let s=O(e.events,"/config/events");R(s,["schemas","subscriptions","timers","dateTriggers"],"/config/events",["capturePolicies"]),w(s.schemas,"/config/events/schemas",100),w(s.subscriptions,"/config/events/subscriptions",100),w(s.timers,"/config/events/timers",100),w(s.dateTriggers,"/config/events/dateTriggers",100);let a=O(e.workflows,"/config/workflows");R(a,["definitions","bindings","activations","providers","editableParameters"],"/config/workflows"),w(a.definitions,"/config/workflows/definitions",100),w(a.bindings,"/config/workflows/bindings",100),w(a.activations,"/config/workflows/activations",100),w(a.providers,"/config/workflows/providers",100),w(a.editableParameters,"/config/workflows/editableParameters",100);let r=O(e.frontend,"/config/frontend");R(r,["routes","user","admin","devicePolicy"],"/config/frontend",["authentication","publicAccess"]),w(r.routes,"/config/frontend/routes",500);let c=O(r.user,"/config/frontend/user");R(c,["applicationTodoCenter"],"/config/frontend/user"),tt(c.applicationTodoCenter,"/config/frontend/user/applicationTodoCenter"),so(r.devicePolicy,"/config/frontend/devicePolicy"),Object.prototype.hasOwnProperty.call(r,"authentication")&&Zi(r.authentication,r.routes,e,"/config/frontend/authentication"),Object.prototype.hasOwnProperty.call(r,"publicAccess")&&Ca(r.publicAccess,e,"/config/frontend/publicAccess");let l=O(r.admin,"/config/frontend/admin");R(l,["navigation"],"/config/frontend/admin",["access"]),l.access!==void 0&&nn(l.access,"/config/frontend/admin/access",e.appCode),$a(l.navigation,"/config/frontend/admin/navigation");let p=O(e.runtime,"/config/runtime");R(p,["protocolCapabilities","health"],"/config/runtime"),F(p.protocolCapabilities,"/config/runtime/protocolCapabilities",100),R(O(p.health,"/config/runtime/health"),["livePath","readyPath","versionPath"],"/config/runtime/health"),x(p.health.livePath,"/__platform/health","/config/runtime/health/livePath"),x(p.health.readyPath,"/__platform/ready","/config/runtime/health/readyPath"),x(p.health.versionPath,"/__platform/version","/config/runtime/health/versionPath")}function ua(e,t,o){R(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"]),x(e.schemaVersion,Hi,"/contracts/schemaVersion"),x(e.compilerContractVersion,Nt,"/contracts/compilerContractVersion"),S(e.generatorVersion,"/contracts/generatorVersion",128),x(e.appCode,t,"/contracts/appCode"),x(e.configDigest,o,"/contracts/configDigest"),w(e.perspectives,"/contracts/perspectives",X.perspectives),w(e.resources,"/contracts/resources",X.resources),e.subjectReadSurfaces!==void 0&&w(e.subjectReadSurfaces,"/contracts/subjectReadSurfaces",X.subjectReadSurfaces),w(e.capabilities,"/contracts/capabilities",X.capabilities),w(e.operations,"/contracts/operations",X.operations),w(e.eventConsumers,"/contracts/eventConsumers",X.eventConsumers),w(e.eventProducers,"/contracts/eventProducers",X.eventProducers),w(e.eventSchemas,"/contracts/eventSchemas",X.eventSchemas),O(e.eventHandlerManifest,"/contracts/eventHandlerManifest"),F(e.eventTypes,"/contracts/eventTypes",X.eventTypes),w(e.workflows,"/contracts/workflows",X.workflows),w(e.routes,"/contracts/routes",X.routes),Object.prototype.hasOwnProperty.call(e,"authentication")&&Ta(e.authentication,"/contracts/authentication"),Object.prototype.hasOwnProperty.call(e,"publicAccess")&&Sa(e.publicAccess,"/contracts/publicAccess"),Object.prototype.hasOwnProperty.call(e,"adminAccess")&&nn(e.adminAccess,"/contracts/adminAccess",t),La(e.routeManifest,"/contracts/routeManifest",t),Pa(e.adminPages,"/contracts/adminPages"),Fa(e.adminNavigation,"/contracts/adminNavigation")}function fa(e,t,o){let n=_a(e);Ma(e,n),Ka(e),Ba(e),Ga(e);let i=e.events.schemas.map((_,A)=>{let T=`/config/events/schemas/${A}`,f=O(_,T),b=S(f.eventType,`${T}/eventType`,255);return b.startsWith("openxiangda.")&&m("NATIVE_EVENT_SCHEMA_RESERVED",`${T}/eventType`,{eventType:b}),x(f.schemaDigest,Q(O(f.jsonSchema,`${T}/jsonSchema`)),`${T}/schemaDigest`),f}),s=new Set([...Zn,...eo,...i.map(_=>String(_.eventType))]),a=new Map(e.data.resources.map(_=>[String(_.code),new Map(_.schema.fields.map(A=>[String(A.code),String(A.type)]))])),r=ee(e.events.subscriptions.map((_,A)=>{let T=`/config/events/subscriptions/${A}`,f=O(_,T),b=F(f.eventTypes,`${T}/eventTypes`,20);b.forEach((k,W)=>{s.has(k)||m("NATIVE_EVENT_TYPE_NOT_REGISTERED",`${T}/eventTypes/${W}`,{eventType:k})});let h=ti(f,e.data.resources,T),C=ma(f.delivery,b,`${T}/delivery`),$=pa(f.platformAccess,`${T}/platformAccess`,a,e,f);return{code:P(f.code,`${T}/code`),endpointPath:Ee(f.endpointPath,`${T}/endpointPath`),eventTypes:b,filter:O(f.filter,`${T}/filter`),payload:h?.payload||O(f.payload,`${T}/payload`),...h?{execution:h.execution}:{},...$?{platformAccess:$}:{},delivery:C}}),_=>_.code),c=new Map(i.map(_=>[String(_.eventType),String(_.dataSchemaVersion)])),l=ee([...e.data.resources.flatMap(_=>Zn.map(A=>({code:`data:${_.code}:${A}`,source:"data",eventType:A,dataSchemaVersion:"2.0.0",resourceCode:_.code}))),...i.map(_=>({code:`app:${_.eventType}`,source:"app",eventType:_.eventType,dataSchemaVersion:_.dataSchemaVersion})),...e.events.timers.map(_=>({code:_.code,source:"timer",eventType:_.eventType,dataSchemaVersion:c.get(String(_.eventType))||"2.0.0"})),...e.events.dateTriggers.map(_=>({code:_.code,source:"date",eventType:_.eventType,dataSchemaVersion:c.get(String(_.eventType))||"2.0.0",resourceCode:_.resourceCode,field:_.field})),...e.workflows.activations.length?eo.filter(_=>!ri.includes(_)||e.workflows.definitions.some(A=>Object.values(A.definition.nodes).some(T=>T.kind==="action"))).filter(_=>_!=="openxiangda.workflow.node.skipped.v2"||e.workflows.definitions.some(A=>Object.values(A.definition.nodes).some(T=>T.kind==="approval"&&T.emptyPolicy==="skip"))).map(_=>({code:`workflow:${_}`,source:"workflow",eventType:_,dataSchemaVersion:"2.0.0"})):[]],_=>`${_.source}:${_.code}:${_.eventType}`),p=M([...r.flatMap(_=>_.eventTypes),...l.map(_=>String(_.eventType))]);Va(e);let d=ns(e),u;try{u=jo(e.data.concurrency,e.data.resources,n)}catch(_){throw _ instanceof rt&&m(_.code,_.pointer,{reason:_.reason}),_}u?.commands.some(_=>_.mode==="durable")&&e.backend?.enabled===!1&&m("NATIVE_MANAGED_CONCURRENCY_INVALID","/data/concurrency",{reason:"durable commands require backend runtime"});let g=Aa(e,n),I=Qi(e),E=e.workflows.definitions.map(_=>_.definition),N=xn(E),y=li(E,r,!0);y.length&&m(y[0],"/config/events/subscriptions");try{Uo(e.data.resources,I)}catch(_){throw _ instanceof He&&m(_.code,_.pointer,{reason:_.reason}),_}return{schemaVersion:Hi,compilerContractVersion:Nt,generatorVersion:o,appCode:e.appCode,configDigest:t,perspectives:e.perspectives,resources:ga(e),...g.length?{subjectReadSurfaces:g}:{},...u?{concurrency:u}:{},capabilities:ee(n,_=>_.code),operations:I,eventConsumers:r,eventProducers:l,eventSchemas:i,eventHandlerManifest:{schemaVersion:sa,appCode:e.appCode,handlers:r.filter(_=>!_.execution).map(_=>({code:_.code,endpointPath:_.endpointPath,eventTypes:_.eventTypes,dataSchemaVersions:M(_.eventTypes.map(A=>A.startsWith("openxiangda.")?"2.0.0":c.get(A)||"2.0.0")),maxBodyBytes:65536,receiptProtocolVersion:2,...N[_.code]?{workflowStep:N[_.code]}:{}}))},eventTypes:p,workflows:ss(e),routes:tn(e),...Object.prototype.hasOwnProperty.call(e.frontend,"authentication")?{authentication:ha(e)}:{},...Object.prototype.hasOwnProperty.call(e.frontend,"publicAccess")?{publicAccess:wa(e)}:{},...e.frontend.admin.access?{adminAccess:e.frontend.admin.access}:{},routeManifest:Wa(e),adminPages:d,adminNavigation:Da(e)}}function pa(e,t,o,n,i){if(e===void 0)return;let s=O(e,t);R(s,["notification","managedFileCopies","decimalReservation"],t,!0);let a={};if(s.decimalReservation!==void 0)try{a.decimalReservation=Zo(s.decimalReservation,ei(n,i))}catch{m("NATIVE_EVENT_DECIMAL_RESERVATION_INVALID",`${t}/decimalReservation`)}if(s.notification!==void 0){let r=O(s.notification,`${t}/notification`);R(r,["mode"],`${t}/notification`),x(r.mode,"business-standard",`${t}/notification/mode`),a.notification={mode:"business-standard"}}if(s.managedFileCopies!==void 0){let r=w(s.managedFileCopies,`${t}/managedFileCopies`,16);r.length||m("NATIVE_EVENT_MANAGED_FILE_COPIES_REQUIRED",`${t}/managedFileCopies`);let c=new Set;a.managedFileCopies=ee(r.map((l,p)=>{let d=`${t}/managedFileCopies/${p}`,u=O(l,d);R(u,["mode","sourceResourceCode","sourceFieldCodes","targetResourceCode","targetFieldCodes"],d),x(u.mode,"copy",`${d}/mode`);let g=G(u.sourceResourceCode,`${d}/sourceResourceCode`),I=G(u.targetResourceCode,`${d}/targetResourceCode`),E=o.get(g),N=o.get(I);(!E||!N)&&m("NATIVE_EVENT_MANAGED_FILE_COPY_RESOURCE_INVALID",d);let y=F(u.sourceFieldCodes,`${d}/sourceFieldCodes`,16),_=F(u.targetFieldCodes,`${d}/targetFieldCodes`,16);(!y.length||y.length!==_.length)&&m("NATIVE_EVENT_MANAGED_FILE_COPY_FIELDS_INVALID",d),y.forEach((T,f)=>{let b=E.get(T),h=N.get(_[f]);(!["file","image"].includes(String(b))||b!==h)&&m("NATIVE_EVENT_MANAGED_FILE_COPY_FIELD_INVALID",`${d}/sourceFieldCodes/${f}`)});let A=`${g}:${y.join(",")}=>${I}:${_.join(",")}`;return c.has(A)&&m("NATIVE_EVENT_MANAGED_FILE_COPY_DUPLICATE",d),c.add(A),{mode:"copy",sourceResourceCode:g,sourceFieldCodes:M(y),targetResourceCode:I,targetFieldCodes:M(_)}}),l=>`${l.sourceResourceCode}:${l.sourceFieldCodes.join(",")}=>${l.targetResourceCode}:${l.targetFieldCodes.join(",")}`)}return Object.keys(a).length||m("NATIVE_EVENT_PLATFORM_ACCESS_EMPTY",t),a}function ma(e,t,o){let n=O(e,o);R(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 s=S(n.ordering,`${o}/ordering`,32);return["none","record","workflow-instance"].includes(s)||m("NATIVE_EVENT_DELIVERY_ORDERING_INVALID",`${o}/ordering`),s==="workflow-instance"&&t.some(a=>!ra.has(a))&&m("NATIVE_EVENT_WORKFLOW_ORDERING_REQUIRES_WORKFLOW_FACTS",`${o}/ordering`),n}function _a(e){let t=new Map;for(let s of cs(e.appCode))t.set(s.code,s);for(let[s,a]of e.authz.capabilities.entries()){let r=`/config/authz/capabilities/${s}`,c=O(a,r);R(c,["code","kind","name","description"],r,!0);let l=fe(c.code,`${r}/code`,e.appCode);t.has(l)&&m("NATIVE_CAPABILITY_DUPLICATE",`${r}/code`),["backend","ui"].includes(c.kind)||m("NATIVE_CAPABILITY_KIND_INVALID",`${r}/kind`);let p={code:l,kind:c.kind,name:S(c.name,`${r}/name`,255),source:"explicit",...c.description===void 0?{}:{description:ao(c.description,`${r}/description`,2e3)}};t.set(l,p)}let o=e.data.resources.map((s,a)=>({pointer:`/config/data/resources/${a}`,resource:Me(s,`/config/data/resources/${a}`,e.appCode)}));for(let{pointer:s,resource:a}of o){let r={read:`\u8BFB\u53D6${a.name}`,create:`\u65B0\u5EFA${a.name}`,update:`\u66F4\u65B0${a.name}`,delete:`\u5220\u9664${a.name}`};for(let c of["read","create","update","delete"]){let l=fe(a.capabilities[c],`${s}/capabilities/${c}`,e.appCode);t.has(l)&&m("NATIVE_CAPABILITY_DUPLICATE",`${s}/capabilities/${c}`),t.set(l,{code:l,kind:"data",name:r[c],source:"data"})}}let n=new Set(t.keys()),i=new Map;for(let{pointer:s,resource:a}of o)for(let[r,c]of Object.entries(a.fieldPolicies)){if(ot(r))continue;let l=O(c,`${s}/fieldPolicies/${r}`);for(let p of["read","create","update"])if(Array.isArray(l[p]))for(let d of F(l[p],`${s}/fieldPolicies/${r}/${p}`,2e3)){if(fe(d,`${s}/fieldPolicies/${r}/${p}`,e.appCode),n.has(d))continue;let u=i.get(d);u&&u!==a.code&&m("NATIVE_CAPABILITY_DUPLICATE",`${s}/fieldPolicies/${r}/${p}`),i.set(d,a.code),!t.has(d)&&t.set(d,{code:d,kind:"data",name:`${a.name}.${r}.${p}`,source:"data"})}}return[...t.values()]}function ga(e){let t=Ea(e);return ee(e.data.resources.map((o,n)=>{let i=Me(o,`/config/data/resources/${n}`,e.appCode),s=t.get(i.code);return{code:i.code,schemaDigest:Q(i.schema),fields:ee(i.schema.fields.map(a=>({code:a.code,type:a.type})),a=>a.code),...s?{detailRouteCode:s}:{}}}),o=>o.code)}function Aa(e,t){if(e.data.subjectReadSurfaces===void 0)return[];let o=w(e.data.subjectReadSurfaces,"/config/data/subjectReadSurfaces",X.subjectReadSurfaces),n=new Set(t.map(a=>String(a.code))),i=new Map(e.data.resources.map((a,r)=>{let c=`/config/data/resources/${r}`,l=Me(a,c,e.appCode);return[String(l.code),{resource:l,fields:new Map(w(O(l.schema,`${c}/schema`).fields,`${c}/schema/fields`,500).map(p=>{let d=O(p,`${c}/schema/fields`);return[String(d.code),d]}))}]})),s=new Set;return ee(o.map((a,r)=>{let c=`/config/data/subjectReadSurfaces/${r}`,l=O(a,c);R(l,["code","name","capability","subject","relations"],c);let p=P(l.code,`${c}/code`);s.has(p)&&m("NATIVE_SUBJECT_READ_SURFACE_CODE_DUPLICATE",`${c}/code`),s.add(p);let d=fe(l.capability,`${c}/capability`,e.appCode);n.has(d)||m("NATIVE_SUBJECT_READ_SURFACE_CAPABILITY_NOT_DECLARED",`${c}/capability`);let u=O(l.subject,`${c}/subject`);R(u,["resourceCode","fields"],`${c}/subject`);let g=G(u.resourceCode,`${c}/subject/resourceCode`),I=i.get(g);I||m("NATIVE_SUBJECT_READ_SURFACE_RESOURCE_NOT_DECLARED",`${c}/subject/resourceCode`);let E=F(u.fields,`${c}/subject/fields`,100).map((T,f)=>K(T,`${c}/subject/fields/${f}`));E.length||m("NATIVE_SUBJECT_READ_SURFACE_FIELDS_REQUIRED",`${c}/subject/fields`);for(let[T,f]of E.entries()){let b=I.fields.get(f);(!b||b.type==="subtable")&&m("NATIVE_SUBJECT_READ_SURFACE_FIELD_INVALID",`${c}/subject/fields/${T}`)}let N=w(l.relations,`${c}/relations`,8);N.length||m("NATIVE_SUBJECT_READ_SURFACE_RELATIONS_REQUIRED",`${c}/relations`);let y=new Set,_=0,A=ee(N.map((T,f)=>{let b=`${c}/relations/${f}`,h=O(T,b);R(h,["code","resourceCode","foreignKeyField","fields","limit"],b,["order"]);let C=P(h.code,`${b}/code`);y.has(C)&&m("NATIVE_SUBJECT_READ_SURFACE_RELATION_CODE_DUPLICATE",`${b}/code`),y.add(C);let $=G(h.resourceCode,`${b}/resourceCode`),k=i.get($);k||m("NATIVE_SUBJECT_READ_SURFACE_RESOURCE_NOT_DECLARED",`${b}/resourceCode`);let W=K(h.foreignKeyField,`${b}/foreignKeyField`),v=k.fields.get(W),Y=O(v?.source||{},`${b}/foreignKeyField/source`);(!v||!["uuid","resource-ref.single"].includes(String(v.type))||v.type==="resource-ref.single"&&(Y.kind!=="resource"||Y.resourceCode!==g))&&m("NATIVE_SUBJECT_READ_SURFACE_RELATION_INVALID",`${b}/foreignKeyField`);let te=F(h.fields,`${b}/fields`,100).map((le,V)=>K(le,`${b}/fields/${V}`));te.length||m("NATIVE_SUBJECT_READ_SURFACE_FIELDS_REQUIRED",`${b}/fields`);for(let[le,V]of te.entries()){let U=k.fields.get(V);(!U||U.type==="subtable")&&m("NATIVE_SUBJECT_READ_SURFACE_FIELD_INVALID",`${b}/fields/${le}`)}let H=w(h.order||[],`${b}/order`,10).map((le,V)=>{let U=`${b}/order/${V}`,L=O(le,U);R(L,["field","direction"],U);let q=K(L.field,`${U}/field`),J=k.fields.get(q);return(!Xi.has(q)&&!J||J?.type==="subtable"||J&&!st(J.type))&&m("NATIVE_SUBJECT_READ_SURFACE_ORDER_FIELD_INVALID",`${U}/field`),["asc","desc"].includes(String(L.direction))||m("NATIVE_SUBJECT_READ_SURFACE_ORDER_DIRECTION_INVALID",`${U}/direction`),{field:q,direction:L.direction}}),he=se(h.limit,`${b}/limit`,1,100);return _+=he,{code:C,resourceCode:$,foreignKeyField:W,fields:M(te),...H.length?{order:H}:{},limit:he}}),T=>T.code);return _>400&&m("NATIVE_SUBJECT_READ_SURFACE_ROW_LIMIT_EXCEEDED",`${c}/relations`),{code:p,name:S(l.name,`${c}/name`,255),capability:d,subject:{resourceCode:g,fields:M(E)},relations:A}}),a=>a.code)}function Ea(e){let t=e.data.resourceDetailRoutes===void 0?[]:w(e.data.resourceDetailRoutes,"/config/data/resourceDetailRoutes",100),o=new Map(e.data.resources.map((s,a)=>{let r=`/config/data/resources/${a}`,c=Me(s,r,e.appCode);return[c.code,c]})),n=new Map(tn(e).map(s=>[String(s.code),s])),i=new Map;for(let[s,a]of t.entries()){let r=`/config/data/resourceDetailRoutes/${s}`,c=O(a,r);R(c,["resourceCode","desktop","mobile"],r);let l=G(c.resourceCode,`${r}/resourceCode`);i.has(l)&&m("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_DUPLICATE",`${r}/resourceCode`);let p=o.get(l);p||m("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_RESOURCE_MISSING",`${r}/resourceCode`);let d=P(c.desktop,`${r}/desktop`),u=P(c.mobile,`${r}/mobile`);d===u&&m("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_INVALID",r);let g=String(p.capabilities.read);for(let[I,E]of[["desktop",d],["mobile",u]]){let N=`${r}/${I}`,y=n.get(E);y||m("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_REFERENCE_MISSING",N),y.surface!=="user"&&m("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_SURFACE_INVALID",N);let _=Ee(y.path,`${N}/path`),A=[..._.matchAll(/:([A-Za-z][A-Za-z0-9_]*)/g)],T=I==="mobile"?!_.startsWith("/m/"):_==="/m"||_.startsWith("/m/");(_.includes("*")||_.includes("?")||_.includes("#")||_.split("/").includes("..")||A.length!==1||T)&&m("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_PATH_INVALID",N);let f=Array.isArray(y.access?.allOf)?y.access.allOf:[];y.capability!==g&&!f.includes(g)&&m("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_CAPABILITY_INVALID",N)}i.set(l,{desktop:d,mobile:u})}return i}function Qi(e){let t=new Map(e.data.resources.map((a,r)=>{let c=`/config/data/resources/${r}`,l=Me(a,c,e.appCode);return[l.code,new Map(l.schema.fields.map(p=>[String(p.code),p]))]})),o=new Map(e.data.resources.map((a,r)=>{let c=`/config/data/resources/${r}`,l=Me(a,c,e.appCode);return[l.code,new Map(l.schema.fields.map(p=>[String(p.code),String(p.type)]))]})),n=new Set(o.keys()),i=new Set(e.workflows.activations.map((a,r)=>on(O(a,`/config/workflows/activations/${r}`).workflowCode,`/config/workflows/activations/${r}/workflowCode`))),s=new Map;return ee(e.backend.operations.map((a,r)=>{let c=`/config/backend/operations/${r}`,l=O(a,c);R(l,["code","method","path","capability","requestSchema","responseSchema","description","platformAccess","browser","ai"],c,!0);let p=S(l.method,`${c}/method`,16);["GET","POST","PUT","PATCH","DELETE"].includes(p)||m("NATIVE_OPERATION_METHOD_INVALID",`${c}/method`);let d=P(l.code,`${c}/code`);Na(l.ai,c,d,p,n);let u=ba(l.platformAccess,`${c}/platformAccess`,o,t,i,new Set(e.authz.roles.map(I=>String(I.code))));if(u?.recordEdit){let I=e.data.resources.find(E=>E.code===u.recordEdit.resourceCode);I?.surface?.mutationOwner!=="action"&&m("NATIVE_RECORD_EDIT_ACTION_OWNER_REQUIRED",`${c}/platformAccess/recordEdit`);for(let E of u.recordEdit.fieldCodes)(!I.fieldPolicies?.[E]?.update?.length||I.surface?.fields?.[E]?.system===!0)&&m("NATIVE_RECORD_EDIT_FIELD_INVALID",`${c}/platformAccess/recordEdit/fieldCodes`)}if(u?.decimalReservation){let I=u.decimalReservation,E=String(I.resourceCode),N=JSON.stringify([I.amountFieldCode,I.currencyFieldCode,I.relationFieldCode,I.parentFieldCode,I.rootFieldCode,I.statusFieldCode,I.parentRelationValue,I.childRelationValue]),y=s.get(E);y&&y!==N&&m("NATIVE_DECIMAL_RESERVATION_MAPPING_CONFLICT",`${c}/platformAccess/decimalReservation`),s.set(E,N)}let g=Ia(l.browser,`${c}/browser`,p,l.requestSchema,l.responseSchema,o,t,e.data.subjectReadSurfaces||[]);return{code:d,method:p,path:Ee(l.path,`${c}/path`),requiredCapability:fe(l.capability,`${c}/capability`,e.appCode),requestSchemaDigest:Q(O(l.requestSchema,`${c}/requestSchema`)),responseSchemaDigest:Q(O(l.responseSchema,`${c}/responseSchema`)),...l.description===void 0?{}:{description:ao(l.description,`${c}/description`,2e3)},...u?{platformAccess:u}:{},...g?{browser:g}:{}}}),a=>a.code)}function Ia(e,t,o,n,i,s,a,r){if(e===void 0)return null;let c=O(e,t);R(c,["exposure","behavior","idempotency","subject"],t,["refreshTargets","fileIntent"]),x(c.exposure,"authenticated",`${t}/exposure`);let l=S(c.behavior,`${t}/behavior`,32);["read","controlled"].includes(l)||m("NATIVE_OPERATION_BROWSER_BEHAVIOR_INVALID",`${t}/behavior`);let p=S(c.idempotency,`${t}/idempotency`,32);(!["none","required"].includes(p)||l==="controlled"&&p!=="required"||l==="read"&&p!=="none")&&m("NATIVE_OPERATION_BROWSER_IDEMPOTENCY_INVALID",`${t}/idempotency`);let d=O(c.subject,`${t}/subject`);R(d,["resourceCode","inputField"],`${t}/subject`);let u=G(d.resourceCode,`${t}/subject/resourceCode`);s.has(u)||m("NATIVE_OPERATION_BROWSER_SUBJECT_RESOURCE_NOT_DECLARED",`${t}/subject/resourceCode`);let g=K(d.inputField,`${t}/subject/inputField`),I=O(n,`${t}/requestSchema`),E=O(i,`${t}/responseSchema`);(I.type!=="object"||I.additionalProperties!==!1||E.type!=="object"||E.additionalProperties!==!1)&&m("NATIVE_OPERATION_BROWSER_SCHEMA_ROOT_INVALID",`${t}/requestSchema`);let N=O(I.properties,`${t}/requestSchema/properties`),y=new Set(I.required===void 0?[]:F(I.required,`${t}/requestSchema/required`,200));(!(g in N)||!y.has(g))&&m("NATIVE_OPERATION_BROWSER_SUBJECT_INPUT_INVALID",`${t}/subject/inputField`);let _=O(N[g],`${t}/requestSchema/properties/${g}`);(_.type!=="string"||_.format!=="uuid")&&m("NATIVE_OPERATION_BROWSER_SUBJECT_INPUT_INVALID",`${t}/subject/inputField`);let A=new Map((Array.isArray(r)?r:[]).map((C,$)=>{let k=O(C,`/config/data/subjectReadSurfaces/${$}`);return[String(k.code),String(O(k.subject,`/config/data/subjectReadSurfaces/${$}/subject`).resourceCode)]})),T=c.refreshTargets===void 0?[]:w(c.refreshTargets,`${t}/refreshTargets`,16),f=new Set,b=ee(T.map((C,$)=>{let k=`${t}/refreshTargets/${$}`,W=O(C,k);R(W,["kind","code"],k),x(W.kind,"subject-surface",`${k}/kind`);let v=P(W.code,`${k}/code`);return(f.has(v)||!A.has(v)||A.get(v)!==u)&&m("NATIVE_OPERATION_BROWSER_REFRESH_TARGET_INVALID",`${k}/code`),f.add(v),{kind:"subject-surface",code:v}}),C=>`${C.kind}:${C.code}`),h=ya(c.fileIntent,`${t}/fileIntent`,o,l,p,u,N,y,a);return{exposure:"authenticated",behavior:l,idempotency:p,subject:{resourceCode:u,inputField:g},...b.length?{refreshTargets:b}:{},...h?{fileIntent:h}:{}}}function ya(e,t,o,n,i,s,a,r,c){if(e===void 0)return null;let l=O(e,t);R(l,["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 p=G(l.recordResourceCode,`${t}/recordResourceCode`),d=c.get(p);d||m("NATIVE_OPERATION_FILE_INTENT_RESOURCE_NOT_DECLARED",`${t}/recordResourceCode`);let u=K(l.recordIdInputField,`${t}/recordIdInputField`),g=O(a[u],`${t}/recordIdInputField`);(!r.has(u)||g.type!=="string"||g.format!=="uuid")&&m("NATIVE_OPERATION_FILE_INTENT_RECORD_INPUT_INVALID",`${t}/recordIdInputField`);let I=K(l.relationField,`${t}/relationField`),E=d.get(I);(!E||!["uuid","resource-ref.single"].includes(String(E.type))||String(E.type)==="resource-ref.single"&&(String(O(E.source,`${t}/relationField`).kind||"")!=="resource"||String(O(E.source,`${t}/relationField`).resourceCode||"")!==s))&&m("NATIVE_OPERATION_FILE_INTENT_RELATION_INVALID",`${t}/relationField`);let N=[["fileNameField",["text.short","text.long"]],["contentTypeField",["text.short","text.long"]],["sizeField",["number.integer"]]],y={};for(let[f,b]of N){let h=K(l[f],`${t}/${f}`);b.includes(String(d.get(h)?.type))||m("NATIVE_OPERATION_FILE_INTENT_METADATA_INVALID",`${t}/${f}`),y[f]=h}let _=ee(F(l.purposes,`${t}/purposes`,2),f=>f);(!_.length||_.some(f=>!["preview","download"].includes(f)))&&m("NATIVE_OPERATION_FILE_INTENT_PURPOSE_INVALID",`${t}/purposes`);let A=Number(l.maxTtlSeconds);(!Number.isSafeInteger(A)||A<1||A>300)&&m("NATIVE_OPERATION_FILE_INTENT_TTL_INVALID",`${t}/maxTtlSeconds`);let T=Number(l.maxBytes);return(!Number.isSafeInteger(T)||T<1||T>104857600)&&m("NATIVE_OPERATION_FILE_INTENT_SIZE_INVALID",`${t}/maxBytes`),{recordResourceCode:p,recordIdInputField:u,relationField:I,fileNameField:y.fileNameField,contentTypeField:y.contentTypeField,sizeField:y.sizeField,purposes:_,maxTtlSeconds:A,maxBytes:T}}function ba(e,t,o,n,i,s){if(e===void 0)return null;let a=O(e,t);R(a,["directory","managedFiles","managedFileCopies","notification","workflow","roleAssertions","decimalReservation","dataCommands","recordEdit"],t,!0),Object.keys(a).length===0&&m("NATIVE_OPERATION_PLATFORM_ACCESS_EMPTY",t);let r={};if(a.dataCommands!==void 0){let c=O(a.dataCommands,`${t}/dataCommands`);R(c,["mode"],`${t}/dataCommands`),x(c.mode,"recoverable-native",`${t}/dataCommands/mode`),r.dataCommands={mode:"recoverable-native"}}if(a.recordEdit!==void 0){let c=`${t}/recordEdit`,l=O(a.recordEdit,c);R(l,["resourceCode","fieldCodes"],c);let p=G(l.resourceCode,`${c}/resourceCode`),d=n.get(p),u=F(l.fieldCodes,`${c}/fieldCodes`,200);(!d||!u.length||!r.dataCommands)&&m("NATIVE_RECORD_EDIT_DECLARATION_INVALID",c);for(let g of u){let I=d.get(g);(!I||I.type==="serial-number"||I.type==="subtable")&&m("NATIVE_RECORD_EDIT_FIELD_INVALID",`${c}/fieldCodes`)}r.recordEdit={resourceCode:p,fieldCodes:M(u)}}if(a.roleAssertions!==void 0){let c=O(a.roleAssertions,`${t}/roleAssertions`);R(c,["roleCodes"],`${t}/roleAssertions`);let l=F(c.roleCodes,`${t}/roleAssertions/roleCodes`,20);l.length||m("NATIVE_OPERATION_ROLE_ASSERTIONS_REQUIRED",`${t}/roleAssertions/roleCodes`),l.forEach((p,d)=>{s.has(p)||m("NATIVE_ROLE_REFERENCE_MISSING",`${t}/roleAssertions/roleCodes/${d}`)}),r.roleAssertions={roleCodes:M(l)}}if(a.directory!==void 0){let c=O(a.directory,`${t}/directory`);R(c,["mode","fields"],`${t}/directory`),["current-initiator","selected-user"].includes(String(c.mode))||m("NATIVE_OPERATION_DIRECTORY_MODE_INVALID",`${t}/directory/mode`);let l=new Set(["displayName","employeeNumber","primaryDepartment","departments",...c.mode==="current-initiator"?["phone"]:[]]),p=F(c.fields,`${t}/directory/fields`,l.size);(!p.length||p.some(d=>!l.has(d)))&&m("NATIVE_OPERATION_DIRECTORY_FIELDS_INVALID",`${t}/directory/fields`),r.directory={mode:String(c.mode),fields:M(p)}}if(a.managedFiles!==void 0){let c=w(a.managedFiles,`${t}/managedFiles`,16);c.length||m("NATIVE_OPERATION_MANAGED_FILES_REQUIRED",`${t}/managedFiles`);let l=new Set;r.managedFiles=ee(c.map((p,d)=>{let u=`${t}/managedFiles/${d}`,g=O(p,u);R(g,["resourceCode","fieldCodes","intents"],u);let I=G(g.resourceCode,`${u}/resourceCode`);(l.has(I)||!o.has(I))&&m("NATIVE_OPERATION_MANAGED_FILE_RESOURCE_INVALID",`${u}/resourceCode`),l.add(I);let E=F(g.fieldCodes,`${u}/fieldCodes`,16);(!E.length||E.some(y=>!["file","image","signature","text.rich"].includes(String(o.get(I)?.get(y)||""))))&&m("NATIVE_OPERATION_MANAGED_FILE_FIELD_INVALID",`${u}/fieldCodes`);let N=F(g.intents,`${u}/intents`,2);return(!N.length||N.some(y=>!["create","update"].includes(y)))&&m("NATIVE_OPERATION_MANAGED_FILE_INTENT_INVALID",`${u}/intents`),{resourceCode:I,fieldCodes:M(E),intents:M(N)}}),p=>p.resourceCode)}if(a.managedFileCopies!==void 0){let c=w(a.managedFileCopies,`${t}/managedFileCopies`,16);c.length||m("NATIVE_OPERATION_MANAGED_FILE_COPIES_REQUIRED",`${t}/managedFileCopies`);let l=new Set;r.managedFileCopies=ee(c.map((p,d)=>{let u=`${t}/managedFileCopies/${d}`,g=O(p,u);R(g,["mode","sourceResourceCode","sourceFieldCodes","targetResourceCode","targetFieldCodes"],u),x(g.mode,"copy",`${u}/mode`);let I=G(g.sourceResourceCode,`${u}/sourceResourceCode`),E=G(g.targetResourceCode,`${u}/targetResourceCode`),N=o.get(I),y=o.get(E);(!N||!y)&&m("NATIVE_OPERATION_MANAGED_FILE_COPY_RESOURCE_INVALID",u);let _=F(g.sourceFieldCodes,`${u}/sourceFieldCodes`,16),A=F(g.targetFieldCodes,`${u}/targetFieldCodes`,16);(!_.length||_.length!==A.length)&&m("NATIVE_OPERATION_MANAGED_FILE_COPY_FIELDS_INVALID",u),_.forEach((f,b)=>{let h=N.get(f),C=y.get(A[b]);(!["file","image"].includes(String(h))||h!==C)&&m("NATIVE_OPERATION_MANAGED_FILE_COPY_FIELD_INVALID",`${u}/sourceFieldCodes/${b}`)});let T=`${I}:${_.join(",")}=>${E}:${A.join(",")}`;return l.has(T)&&m("NATIVE_OPERATION_MANAGED_FILE_COPY_DUPLICATE",u),l.add(T),{mode:"copy",sourceResourceCode:I,sourceFieldCodes:M(_),targetResourceCode:E,targetFieldCodes:M(A)}}),p=>`${p.sourceResourceCode}:${p.sourceFieldCodes.join(",")}=>${p.targetResourceCode}:${p.targetFieldCodes.join(",")}`)}if(a.notification!==void 0){let c=O(a.notification,`${t}/notification`);R(c,["mode"],`${t}/notification`),c.mode!=="business-standard"&&m("NATIVE_OPERATION_NOTIFICATION_MODE_INVALID",`${t}/notification/mode`),r.notification={mode:"business-standard"}}if(a.workflow!==void 0){let c=O(a.workflow,`${t}/workflow`);R(c,["codes"],`${t}/workflow`,["businessCommands"]);let l=F(c.codes,`${t}/workflow/codes`,16);(!l.length||l.some(d=>!i.has(d)))&&m("NATIVE_OPERATION_WORKFLOW_CODE_INVALID",`${t}/workflow/codes`);let p=c.businessCommands===void 0?void 0:F(c.businessCommands,`${t}/workflow/businessCommands`,3);p&&(!p.length||p.some(d=>!["approve","reject","withdraw"].includes(d)))&&m("NATIVE_OPERATION_WORKFLOW_BUSINESS_COMMAND_INVALID",`${t}/workflow/businessCommands`),r.workflow={codes:M(l),...p?{businessCommands:M(p)}:{}}}if(a.decimalReservation!==void 0){let c=`${t}/decimalReservation`,l=O(a.decimalReservation,c);R(l,["mode","resourceCode","amountFieldCode","currencyFieldCode","relationFieldCode","parentFieldCode","rootFieldCode","statusFieldCode","parentRelationValue","childRelationValue","eligibleParentStatuses","eligibleChildStatuses"],c);let p=S(l.mode,`${c}/mode`,16);["reserve","commit","release"].includes(p)||m("NATIVE_DECIMAL_RESERVATION_MODE_INVALID",`${c}/mode`);let d=G(l.resourceCode,`${c}/resourceCode`),u=n.get(d);u||m("NATIVE_DECIMAL_RESERVATION_RESOURCE_MISSING",`${c}/resourceCode`);let I=Object.fromEntries(["amountFieldCode","currencyFieldCode","relationFieldCode","parentFieldCode","rootFieldCode","statusFieldCode"].map(f=>[f,K(l[f],`${c}/${f}`)])),E=f=>u.get(I[f]),N=f=>new Set((E(f)?.options||[]).map(b=>String(b.value))),y=P(l.parentRelationValue,`${c}/parentRelationValue`),_=P(l.childRelationValue,`${c}/childRelationValue`),A=F(l.eligibleParentStatuses,`${c}/eligibleParentStatuses`,16),T=F(l.eligibleChildStatuses,`${c}/eligibleChildStatuses`,16);(E("amountFieldCode")?.type!=="number.decimal"||E("amountFieldCode")?.exactDecimal!==!0||E("amountFieldCode")?.precision!==18||E("amountFieldCode")?.scale!==2||E("currencyFieldCode")?.type!=="option.single"||E("relationFieldCode")?.type!=="option.single"||E("parentFieldCode")?.type!=="resource-ref.single"||E("parentFieldCode")?.source?.resourceCode!==d||E("rootFieldCode")?.type!=="uuid"||E("statusFieldCode")?.type!=="option.single"||y===_||!N("relationFieldCode").has(y)||!N("relationFieldCode").has(_)||!A.length||!T.length||A.some(f=>!N("statusFieldCode").has(f))||T.some(f=>!N("statusFieldCode").has(f)))&&m("NATIVE_DECIMAL_RESERVATION_FIELD_INVALID",c),r.decimalReservation={mode:p,resourceCode:d,...I,parentRelationValue:y,childRelationValue:_,eligibleParentStatuses:M(A),eligibleChildStatuses:M(T)}}return r}function Na(e,t,o,n,i){if(e===void 0)return;let s=`${t}/ai`,a=O(e,s);Mr.test(o)||m("NATIVE_OPERATION_AI_CODE_INVALID",`${t}/code`),R(a,["name","description","risk","resources","sideEffects","concurrency","timeoutMs"],s,!0),S(a.name,`${s}/name`,Qn),S(a.description,`${s}/description`,Qn);let r=S(a.risk,`${s}/risk`,16);["read","write","destructive","external"].includes(r)||m("NATIVE_OPERATION_AI_RISK_INVALID",`${s}/risk`),r==="read"!=(n==="GET")&&m("NATIVE_OPERATION_AI_METHOD_RISK_MISMATCH",`${s}/risk`),n==="DELETE"&&!["destructive","external"].includes(r)&&m("NATIVE_OPERATION_AI_METHOD_RISK_MISMATCH",`${s}/risk`);let c=F(a.resources,`${s}/resources`,16);c.length===0&&m("NATIVE_OPERATION_AI_RESOURCE_REQUIRED",`${s}/resources`),c.forEach((p,d)=>{let u=G(p,`${s}/resources/${d}`);i.has(u)||m("NATIVE_OPERATION_AI_RESOURCE_MISSING",`${s}/resources/${d}`)});let l=F(a.sideEffects,`${s}/sideEffects`,20);(r==="read"&&l.length!==0||r!=="read"&&l.length===0)&&m("NATIVE_OPERATION_AI_SIDE_EFFECT_INVALID",`${s}/sideEffects`),a.concurrency!==void 0&&!["none","revision"].includes(S(a.concurrency,`${s}/concurrency`,16))&&m("NATIVE_OPERATION_AI_CONCURRENCY_INVALID",`${s}/concurrency`),a.timeoutMs!==void 0&&se(a.timeoutMs,`${s}/timeoutMs`,100,3e4)}function Xt(e){return(e.replace(/\/{2,}/g,"/").replace(/\/$/,"")||"/").split("/").map(o=>o.startsWith(":")?":":o.includes("*")?"*":o).join("/")}function Oa(e,t){let o=O(e,t),n=S(o.type,`${t}/type`,32),i=["code","type","label","presentation","required"],s=n==="sso"?[...i,"provider"]:n==="dingtalk"?[...i,"flow"]:i;R(o,s,t);let a=P(o.code,`${t}/code`),r=S(o.label,`${t}/label`,255),c=S(o.presentation,`${t}/presentation`,16);["primary","secondary"].includes(c)||m("NATIVE_APPLICATION_AUTH_METHOD_PRESENTATION_INVALID",`${t}/presentation`);let l=tt(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:a,type:n,label:r,presentation:c,required:l,...n==="sso"?{provider:"tenant-default"}:{},...n==="dingtalk"?{flow:o.flow}:{}}}function Fi(e,t,o){let n=O(e,o);R(n,["routeCode","path","defaultRouteCode"],o);let i=P(n.routeCode,`${o}/routeCode`),s=Ee(n.path,`${o}/path`),a=t==="desktop"?"/login":"/m/login";return(s!==a||/[:*?#\\]/.test(s))&&m("NATIVE_APPLICATION_AUTH_SURFACE_PATH_INVALID",`${o}/path`,{device:t,expectedPath:a}),{routeCode:i,path:s,defaultRouteCode:P(n.defaultRouteCode,`${o}/defaultRouteCode`)}}function Zi(e,t,o,n){if(e===null)return;let i=O(e,n);R(i,["accountMode","registration","methods","surfaces"],n),x(i.accountMode,"existing-platform-users-only",`${n}/accountMode`);let s=O(i.registration,`${n}/registration`);R(s,["mode"],`${n}/registration`),x(s.mode,"reject",`${n}/registration/mode`);let a=w(i.methods,`${n}/methods`,8);a.length===0&&m("NATIVE_APPLICATION_AUTH_METHOD_REQUIRED",`${n}/methods`);let r=a.map((y,_)=>Oa(y,`${n}/methods/${_}`)),c=new Set,l=new Set;for(let[y,_]of r.entries())c.has(_.code)&&m("NATIVE_APPLICATION_AUTH_METHOD_CODE_DUPLICATE",`${n}/methods/${y}/code`),l.has(_.type)&&m("NATIVE_APPLICATION_AUTH_METHOD_TYPE_DUPLICATE",`${n}/methods/${y}/type`),c.add(_.code),l.add(_.type);r.filter(y=>y.presentation==="primary").length!==1&&m("NATIVE_APPLICATION_AUTH_PRIMARY_METHOD_INVALID",`${n}/methods`);let p=O(i.surfaces,`${n}/surfaces`);R(p,["desktop","mobile"],`${n}/surfaces`);let d=Fi(p.desktop,"desktop",`${n}/surfaces/desktop`),u=Fi(p.mobile,"mobile",`${n}/surfaces/mobile`);d.routeCode===u.routeCode&&m("NATIVE_APPLICATION_AUTH_SURFACE_CODE_DUPLICATE",`${n}/surfaces/mobile/routeCode`);let g=w(t,"/config/frontend/routes",500),I=new Map;for(let[y,_]of g.entries()){let A=O(_,`/config/frontend/routes/${y}`);I.set(String(A.code||""),A)}let E=new Set((Array.isArray(o.data?.resources)?o.data.resources:[]).map(y=>String(y.code||"")).filter(y=>/^[a-z][a-z0-9-]{0,62}$/.test(y)));for(let[y,_]of[["desktop",d],["mobile",u]]){I.has(_.routeCode)&&m("NATIVE_APPLICATION_AUTH_SURFACE_CODE_CONFLICT",`${n}/surfaces/${y}/routeCode`);let A=/^user\.([a-z][a-z0-9-]{0,62})\.(records|submit)$/.exec(String(_.defaultRouteCode||"")),T=I.get(_.defaultRouteCode),f=String(T?.path||"");if(A&&E.has(A[1])){let h=A[2]==="records"?`/my/${A[1]}`:`/my/${A[1]}/submit`;T={surface:"user",path:y==="mobile"?`/m${h}`:h},f=String(T.path)}let b=y==="desktop"?f==="/m"||f.startsWith("/m/"):!(f==="/m"||f.startsWith("/m/"));(!T||T.surface!=="user"||/[:*]/.test(f)||b)&&m("NATIVE_APPLICATION_AUTH_DEFAULT_ROUTE_INVALID",`${n}/surfaces/${y}/defaultRouteCode`)}let N=es(o).filter(y=>!y.owner.startsWith("authentication:"));for(let[y,_]of[["desktop",d],["mobile",u]]){let A=N.find(T=>Xt(T.path)===Xt(_.path));A&&m("NATIVE_APPLICATION_AUTH_SURFACE_PATH_CONFLICT",`${n}/surfaces/${y}/path`,{owner:A.owner})}}function Ta(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=O(e,t),i=O(n.surfaces,`${t}/surfaces`),s={...n,surfaces:{...i,desktop:{...O(i.desktop,`${t}/surfaces/desktop`),defaultRouteCode:"auth-desktop-default"},mobile:{...O(i.mobile,`${t}/surfaces/mobile`),defaultRouteCode:"auth-mobile-default"}}};Zi(s,o.frontend.routes,{...o,frontend:{...o.frontend,authentication:s}},t)}function ha(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 Ra=new Set(["draft.read","draft.update","validate","create","own.list","own.read","public.list","public.read"]);function Ca(e,t,o){let n=O(e,o);R(n,["policies"],o);let i=w(n.policies,`${o}/policies`,16);i.length<1&&m("NATIVE_PUBLIC_POLICY_REQUIRED",o);let s=new Map(t.frontend.routes.map(l=>[l.code,l])),a=new Map(t.data.resources.map(l=>[l.code,l])),r=new Set,c=new Set(i.map(l=>String(l?.code||"")));i.forEach((l,p)=>{let d=`${o}/policies/${p}`,u=O(l,d);R(u,["code","routeCode","mode","resourceCode","operations","fields"],d,["requiredFields","ownRecordFields","publicRecordFields","publicFilters","serverGeneratedFields","schedule","publicSubtableFields","draft","validations"]);let g=P(u.code,`${d}/code`);r.has(g)&&m("NATIVE_PUBLIC_POLICY_DUPLICATE",`${d}/code`);let I=P(u.routeCode,`${d}/routeCode`),E=s.get(I);(!E||E.surface!=="user"||E.capability!==void 0||E.access!==void 0||/[:*]/.test(String(E.path)))&&m("NATIVE_PUBLIC_ROUTE_INVALID",`${d}/routeCode`),x(u.mode,"anonymous",`${d}/mode`);let N=G(u.resourceCode,`${d}/resourceCode`),y=a.get(N);y||m("NATIVE_PUBLIC_RESOURCE_MISSING",`${d}/resourceCode`);let _=new Map(y.schema.fields.map(V=>[String(V.code),String(V.type)])),A=F(u.operations,`${d}/operations`,8);(A.length<1||A.some(V=>!Ra.has(V)))&&m("NATIVE_PUBLIC_OPERATION_INVALID",`${d}/operations`),A.includes("draft.read")!==A.includes("draft.update")&&m("NATIVE_PUBLIC_DRAFT_OPERATION_INCOMPLETE",`${d}/operations`);let T=F(u.fields,`${d}/fields`,64);(T.length<1||T.some(V=>!_.has(V)))&&m("NATIVE_PUBLIC_FIELD_INVALID",`${d}/fields`);for(let V of["requiredFields","ownRecordFields","publicRecordFields"]){if(!Object.prototype.hasOwnProperty.call(u,V))continue;F(u[V],`${d}/${V}`,64).some(L=>!T.includes(L))&&m("NATIVE_PUBLIC_FIELD_SCOPE_INVALID",`${d}/${V}`)}let f=Object.prototype.hasOwnProperty.call(u,"serverGeneratedFields")?w(u.serverGeneratedFields,`${d}/serverGeneratedFields`,16):[],b=new Set;f.forEach((V,U)=>{let L=`${d}/serverGeneratedFields/${U}`,q=O(V,L);R(q,["field","kind"],L);let J=K(q.field,`${L}/field`);(b.has(J)||!_.has(J)||T.includes(J)||_.get(J)!=="text.short"&&_.get(J)!=="text.long")&&m("NATIVE_PUBLIC_SERVER_GENERATED_FIELD_INVALID",`${L}/field`),x(q.kind,"random-token",`${L}/kind`),b.add(J)});let h=Object.prototype.hasOwnProperty.call(u,"schedule")?O(u.schedule,`${d}/schedule`):null;if(h){let V=["campusPolicyCode","rulePolicyCode","campusField","ruleCampusField","ruleWeekdaysField","ruleOpenAtField","ruleCloseAtField","ruleSlotMinutesField","ruleAdvanceHoursField","ruleAdvanceDaysField","campusEnabledField","ruleEnabledField","dateField","timeField"];R(h,V,`${d}/schedule`);for(let U of["campusPolicyCode","rulePolicyCode"])P(h[U],`${d}/schedule/${U}`);for(let U of V.filter(L=>!["campusPolicyCode","rulePolicyCode"].includes(L)))K(h[U],`${d}/schedule/${U}`);for(let U of[h.campusField,h.dateField,h.timeField])T.includes(String(U))||m("NATIVE_PUBLIC_SCHEDULE_FIELD_INVALID",`${d}/schedule`);(!c.has(String(h.campusPolicyCode))||!c.has(String(h.rulePolicyCode)))&&m("NATIVE_PUBLIC_SCHEDULE_POLICY_INVALID",`${d}/schedule`)}let C=Object.prototype.hasOwnProperty.call(u,"publicFilters")?w(u.publicFilters,`${d}/publicFilters`,16):[],$=new Set;C.forEach((V,U)=>{let L=`${d}/publicFilters/${U}`,q=O(V,L);R(q,["field","operator","value"],L);let J=K(q.field,`${L}/field`);$.has(J)&&m("NATIVE_PUBLIC_FILTER_DUPLICATE",`${L}/field`),T.includes(J)||m("NATIVE_PUBLIC_FILTER_FIELD_INVALID",`${L}/field`),x(q.operator,"eq",`${L}/operator`),["boolean","text.short","text.long","number.integer","number.decimal","date","time"].includes(_.get(J)||"")||m("NATIVE_PUBLIC_FILTER_FIELD_INVALID",`${L}/field`),q.value!==null&&typeof q.value!="string"&&typeof q.value!="number"&&typeof q.value!="boolean"&&m("NATIVE_PUBLIC_FILTER_VALUE_INVALID",`${L}/value`),$.add(J)});let k=Object.prototype.hasOwnProperty.call(u,"publicSubtableFields")?O(u.publicSubtableFields,`${d}/publicSubtableFields`):null;if(k){Object.keys(k).length>64&&m("NATIVE_PUBLIC_SUBTABLE_FIELDS_INVALID",`${d}/publicSubtableFields`);for(let[V,U]of Object.entries(k)){let L=y.schema.fields.find(Z=>String(Z.code)===V),q=String(L?.subtable?.resourceCode||""),J=a.get(q),Re=new Map((J?.schema?.fields||[]).map(Z=>[String(Z.code),String(Z.type)])),z=F(U,`${d}/publicSubtableFields/${V}`,64);(!T.includes(V)||_.get(V)!=="subtable"||!J||z.length<1||z.some(Z=>!Re.has(Z))||z.some(Z=>Re.get(Z)==="subtable")||z.some(Z=>Re.get(Z)==="signature"))&&m("NATIVE_PUBLIC_SUBTABLE_FIELDS_INVALID",`${d}/publicSubtableFields/${V}`)}}if(A.some(V=>V.startsWith("public."))){Object.prototype.hasOwnProperty.call(u,"publicRecordFields")||m("NATIVE_PUBLIC_RECORD_FIELDS_REQUIRED",`${d}/publicRecordFields`);let V=F(u.publicRecordFields,`${d}/publicRecordFields`,64);(V.length<1||V.some(U=>!T.includes(U))||V.some(U=>_.get(U)==="signature"||_.get(U)==="subtable"&&!k?.[U]))&&m("NATIVE_PUBLIC_RECORD_FIELDS_INVALID",`${d}/publicRecordFields`)}let W=Object.prototype.hasOwnProperty.call(u,"requiredFields")?F(u.requiredFields,`${d}/requiredFields`,64):[],v=y.surface||{},Y=v.fields||{},te=String(v.mutationOwner||"native")==="native"&&v.generated?.create!==!1,H=y.schema.fields.filter(V=>$t(V,Y[V.code])).map(V=>String(V.code));if(A.includes("create")&&!te&&m("NATIVE_PUBLIC_CREATE_FIELDS_INCOMPLETE",`${d}/fields`),A.includes("create")&&!Object.prototype.hasOwnProperty.call(u,"draft")&&m("NATIVE_PUBLIC_DRAFT_REQUIRED",`${d}/draft`),A.includes("create"))for(let V of H){let U=T.includes(V)?W.includes(V)?null:"requiredFields":"fields";U&&m("NATIVE_PUBLIC_CREATE_FIELDS_INCOMPLETE",`${d}/${U}`,{resourceCode:G,fieldCode:V})}if(Object.prototype.hasOwnProperty.call(u,"draft")){let V=O(u.draft,`${d}/draft`);R(V,["enabled","inactivityTtlSeconds","maxBytes"],`${d}/draft`),x(V.enabled,!0,`${d}/draft/enabled`),se(V.inactivityTtlSeconds,`${d}/draft/inactivityTtlSeconds`,3600,7776e3),se(V.maxBytes,`${d}/draft/maxBytes`,4096,262144)}else A.includes("draft.read")&&m("NATIVE_PUBLIC_DRAFT_REQUIRED",`${d}/draft`);let he=Object.prototype.hasOwnProperty.call(u,"validations")?w(u.validations,`${d}/validations`,16):[],le=new Set;he.forEach((V,U)=>{let L=`${d}/validations/${U}`,q=O(V,L);R(q,["code","kind","fields","result"],L);let J=P(q.code,`${L}/code`);le.has(J)&&m("NATIVE_PUBLIC_VALIDATION_DUPLICATE",`${L}/code`),x(q.kind,"duplicate",`${L}/kind`),x(q.result,"availability",`${L}/result`);let Re=F(q.fields,`${L}/fields`,8);(Re.length<1||Re.some(z=>!T.includes(z))||Re.some(z=>["file","subtable"].includes(_.get(z)||"")))&&m("NATIVE_PUBLIC_VALIDATION_FIELD_INVALID",`${L}/fields`),le.add(J)}),r.add(g)})}function Sa(e,t){let o=O(e,t);R(o,["policies"],t),w(o.policies,`${t}/policies`,16).length<1&&m("NATIVE_PUBLIC_POLICY_REQUIRED",t)}function wa(e){return{policies:ee(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)=>me(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)=>me(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:ee(t.validations.map(o=>({code:o.code,kind:o.kind,fields:M(o.fields),result:o.result})),o=>o.code)}:{}})),t=>t.code)}}function es(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=ts(o),i=`/admin/resources/${o.code}`,s=[["list",i],["detail",`${i}/:id`],["create",`${i}/new`],["update",`${i}/:id/edit`]];for(let[a,r]of s)n[a]&&t.push({owner:`resource:${o.code}:${a}`,path:r},{owner:`resource:${o.code}:${a}:mobile`,path:`/m${r}`})}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 tn(e){let t=new Map(es(e).map(o=>[Xt(o.path),o]));return ee(e.frontend.routes.map((o,n)=>{let i=`/config/frontend/routes/${n}`,s=O(o,i);R(s,["code","path","label","surface","parentCode","capability","access","pinned","tabPersistence","keepAlive"],i,!0),["admin","user"].includes(s.surface)||m("NATIVE_ROUTE_SURFACE_INVALID",`${i}/surface`);let a=Ee(s.path,`${i}/path`);s.surface==="admin"&&a!=="/admin"&&!a.startsWith("/admin/")&&m("NATIVE_ADMIN_ROUTE_PATH_INVALID",`${i}/path`),s.surface==="user"&&(a==="/admin"||a.startsWith("/admin/"))&&m("NATIVE_USER_ROUTE_PATH_RESERVED",`${i}/path`);let r=Xt(a),c=t.get(r);c&&m("NATIVE_ROUTE_PATH_CONFLICT",`${i}/path`,{path:a,owner:c.owner}),t.set(r,{owner:`frontend:${String(s.code||n)}`,path:a});let l=/[:*]/.test(a),p=ro(s,i,e.appCode),d=s.pinned===void 0?void 0:tt(s.pinned,`${i}/pinned`),u=s.tabPersistence===void 0?l?"none":"session":S(s.tabPersistence,`${i}/tabPersistence`,16),g=s.keepAlive===void 0?"none":S(s.keepAlive,`${i}/keepAlive`,16);return["session","none"].includes(u)||m("NATIVE_ROUTE_TAB_PERSISTENCE_INVALID",`${i}/tabPersistence`),["none","memory"].includes(g)||m("NATIVE_ROUTE_KEEP_ALIVE_INVALID",`${i}/keepAlive`),l&&d===!0&&m("NATIVE_DYNAMIC_ROUTE_PINNED_FORBIDDEN",`${i}/pinned`),l&&u==="session"&&m("NATIVE_DYNAMIC_ROUTE_TAB_PERSISTENCE_FORBIDDEN",`${i}/tabPersistence`),l&&g==="memory"&&m("NATIVE_DYNAMIC_ROUTE_KEEP_ALIVE_FORBIDDEN",`${i}/keepAlive`),{code:P(s.code,`${i}/code`),path:a,label:S(s.label,`${i}/label`,255),surface:s.surface,...s.parentCode===void 0?{}:{parentCode:P(s.parentCode,`${i}/parentCode`)},...p,...d===void 0?{}:{pinned:d},tabPersistence:u,keepAlive:g}}),o=>o.code)}function ts(e){let t=e.surface===void 0?{}:O(e.surface,"/surface"),o=t.mutationOwner||"native",n=t.generated===void 0?{}:O(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 ns(e){let t=[];for(let o of ee(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:Tn(n.surface,i.code)}}))])){let{resource:n,viewCode:i}=o,s=`/admin/resources/${n.code}${i?`/views/${i}`:""}`,a=ts(n),r=[{operation:"list",kind:"resource-list",path:`${s}`,label:n.name,capability:n.capabilities.read,navigationEligible:!0},{operation:"detail",kind:"resource-detail",path:`${s}/:id`,label:`${n.name}\u8BE6\u60C5`,capability:n.capabilities.read,navigationEligible:!1},{operation:"create",kind:"resource-create",path:`${s}/new`,label:`\u65B0\u589E${n.name}`,capability:n.capabilities.create,navigationEligible:!1},{operation:"update",kind:"resource-update",path:`${s}/:id/edit`,label:`\u7F16\u8F91${n.name}`,capability:n.capabilities.update,navigationEligible:!1}];for(let c of r)a[c.operation]&&t.push({code:`resource:${n.code}${i?`:view:${i}`:""}:${c.operation}`,kind:c.kind,path:c.path,label:c.label,navigationEligible:c.navigationEligible,capability:c.capability,resourceCode:n.code,...i?{viewCode:i}:{}})}for(let o of tn(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)=>me(o.code,n.code))}function os(e){return e.kind==="resource"?`resource:${e.resourceCode}${e.viewCode?`:view:${e.viewCode}`:""}:list`:`operation:${e.routeCode}`}function Da(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:os(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||me(n.pageCode,i.pageCode))})).sort((t,o)=>t.order-o.order||me(t.code,o.code))}function $a(e,t){let o=w(e,t,X.adminNavigationGroups),n=0;o.forEach((i,s)=>{let a=`${t}/${s}`,r=O(i,a);R(r,["code","label","icon","order","items"],a,!0),P(r.code,`${a}/code`),S(r.label,`${a}/label`,255),Qt(r.icon,`${a}/icon`),Wi(r.order,`${a}/order`);let c=w(r.items,`${a}/items`,500);c.length===0&&m("NATIVE_ADMIN_GROUP_ORPHANED",`${a}/items`),n+=c.length,n>X.adminNavigationItems&&m("NATIVE_ARRAY_LIMIT_EXCEEDED",t),c.forEach((l,p)=>{let d=`${a}/items/${p}`,u=O(l,d);R(u,["page","label","icon","order"],d,!0),ka(u.page,`${d}/page`),u.label!==void 0&&S(u.label,`${d}/label`,255),Qt(u.icon,`${d}/icon`),Wi(u.order,`${d}/order`)})})}function ka(e,t){let o=O(e,t),n=S(o.kind,`${t}/kind`,64);if(n==="resource"){R(o,["kind","resourceCode"],t,["viewCode"]),o.viewCode!==void 0&&P(o.viewCode,`${t}/viewCode`),G(o.resourceCode,`${t}/resourceCode`);return}if(n==="operation"){R(o,["kind","routeCode"],t),P(o.routeCode,`${t}/routeCode`);return}m("NATIVE_ADMIN_PAGE_REFERENCE_KIND_INVALID",`${t}/kind`)}function Va(e){let t=new Map(ns(e).map(i=>[String(i.code),i])),o=new Set,n=new Set;e.frontend.admin.navigation.forEach((i,s)=>{let a=`/config/frontend/admin/navigation/${s}`;o.has(i.code)&&m("NATIVE_ADMIN_GROUP_DUPLICATE",`${a}/code`),o.add(i.code),i.label===i.code&&m("NATIVE_ADMIN_USER_LABEL_REQUIRED",`${a}/label`),i.items.forEach((r,c)=>{let l=`${a}/items/${c}`,p=os(r.page),d=t.get(p);(!d||d.navigationEligible!==!0)&&m("NATIVE_ADMIN_PAGE_NOT_FOUND",`${l}/page`),n.has(p)&&m("NATIVE_ADMIN_PAGE_DUPLICATE",`${l}/page`),n.add(p);let u=r.page.resourceCode||r.page.routeCode||r.page.workflowCode||p,g=r.label||d.label;(!g||g===u||g===p)&&m("NATIVE_ADMIN_USER_LABEL_REQUIRED",`${l}/label`)})})}function Pa(e,t){let o=w(e,t,X.adminPages),n=new Set;o.forEach((i,s)=>{let a=`${t}/${s}`,r=O(i,a);R(r,["code","kind","path","label","navigationEligible","capability","access","resourceCode","viewCode","routeCode"],a,!0);let c=S(r.code,`${a}/code`,255);n.has(c)&&m("NATIVE_ADMIN_PAGE_DUPLICATE",`${a}/code`),n.add(c);let l=S(r.kind,`${a}/kind`,64);if(["resource-list","resource-detail","resource-create","resource-update","operation"].includes(l)||m("NATIVE_ADMIN_PAGE_KIND_INVALID",`${a}/kind`),Ee(r.path,`${a}/path`),S(r.label,`${a}/label`,255),tt(r.navigationEligible,`${a}/navigationEligible`),r.capability!==void 0&&r.access!==void 0&&m("NATIVE_ROUTE_ACCESS_CONFLICT",`${a}/access`),r.capability!==void 0&&S(r.capability,`${a}/capability`,255),r.access!==void 0){let p=O(r.access,`${a}/access`);R(p,["allOf","anyOf"],`${a}/access`,!0);for(let d of["allOf","anyOf"])p[d]!==void 0&&F(p[d],`${a}/access/${d}`,50)}for(let p of["resourceCode","viewCode","routeCode"])r[p]!==void 0&&P(r[p],`${a}/${p}`)})}function Fa(e,t){let o=w(e,t,X.adminNavigationGroups),n=0;o.forEach((i,s)=>{let a=`${t}/${s}`,r=O(i,a);R(r,["code","label","icon","order","items"],a,!0),P(r.code,`${a}/code`),S(r.label,`${a}/label`,255),Qt(r.icon,`${a}/icon`),se(r.order,`${a}/order`,-1e4,1e4);let c=w(r.items,`${a}/items`,500);c.length===0&&m("NATIVE_ADMIN_GROUP_ORPHANED",`${a}/items`),n+=c.length,n>X.adminNavigationItems&&m("NATIVE_ARRAY_LIMIT_EXCEEDED",t),c.forEach((l,p)=>{let d=`${a}/items/${p}`,u=O(l,d);R(u,["pageCode","label","icon","order"],d,!0),S(u.pageCode,`${d}/pageCode`,255),u.label!==void 0&&S(u.label,`${d}/label`,255),Qt(u.icon,`${d}/icon`),se(u.order,`${d}/order`,-1e4,1e4)})})}var va=new Set(["application-todo-center","workflow-work-center","workflow-launch","workflow-task","workflow-instance","resource-records","resource-submit"]);function La(e,t,o){let n=O(e,t);R(n,["schemaVersion","appCode","devicePolicy","rootEntry","authentication","routes","digest"],t),x(n.schemaVersion,Yi,`${t}/schemaVersion`),x(n.appCode,o,`${t}/appCode`),so(n.devicePolicy,`${t}/devicePolicy`),xa(n.rootEntry,`${t}/rootEntry`),ja(n.authentication,`${t}/authentication`),oo(n.digest,`${t}/digest`);let i=w(n.routes,`${t}/routes`,X.routes),s=new Set;i.forEach((a,r)=>{let c=`${t}/routes/${r}`,l=O(a,c),p=l.kind==="resource-records"||l.kind==="resource-submit";R(l,["code","kind","desktop","mobile"],c,["workflowCode",...p?["resourceCode"]:[]]);let d=S(l.code,`${c}/code`,255);s.has(d)&&m("NATIVE_ROUTE_MANIFEST_DUPLICATE",`${c}/code`),s.add(d);let u=S(l.kind,`${c}/kind`,64);if(va.has(u)||m("NATIVE_ROUTE_MANIFEST_KIND_INVALID",`${c}/kind`),l.workflowCode!==void 0&&P(l.workflowCode,`${c}/workflowCode`),p){let E=G(l.resourceCode,`${c}/resourceCode`);x(d,`user.${E}.${l.kind==="resource-records"?"records":"submit"}`,`${c}/code`)}else l.resourceCode!==void 0&&m("NATIVE_PROPERTY_UNKNOWN",`${c}/resourceCode`);let g=Li(l.desktop,`${c}/desktop`,o),I=Li(l.mobile,`${c}/mobile`,o);g.surface!=="user"&&m("NATIVE_ROUTE_MANIFEST_DESKTOP_SURFACE_INVALID",`${c}/desktop/surface`),I.surface!=="user"&&m("NATIVE_ROUTE_MANIFEST_MOBILE_SURFACE_INVALID",`${c}/mobile/surface`),g.routeCode===I.routeCode&&m("NATIVE_ROUTE_MANIFEST_PAIR_DUPLICATE",c)}),x(n.digest,Q({schemaVersion:n.schemaVersion,appCode:n.appCode,devicePolicy:n.devicePolicy,rootEntry:n.rootEntry,authentication:n.authentication,routes:n.routes}),`${t}/digest`)}function so(e,t){let o=O(e,t);R(o,["kind","mobileMaxWidthPx","desktopMinWidthPx"],t),x(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 xa(e,t){let o=O(e,t);R(o,["code","desktop","mobile"],t);let n=P(o.code,`${t}/code`),i=no(o.desktop,`${t}/desktop`),s=no(o.mobile,`${t}/mobile`);return(i===s||s==="/"||!s.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:s}}function ja(e,t){let o=O(e,t);R(o,["desktop","mobile"],t);let n=vi(o.desktop,`${t}/desktop`,!1),i=vi(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 vi(e,t,o){let n=O(e,t);R(n,["routeCode","path"],t);let i=P(n.routeCode,`${t}/routeCode`),s=no(n.path,`${t}/path`);return(o?!s.startsWith("/m/"):s.startsWith("/m/"))&&m("NATIVE_ROUTE_MANIFEST_AUTHENTICATION_PATH_INVALID",`${t}/path`),{routeCode:i,path:s}}function no(e,t){let o=Ee(e,t);return/[:*?#\\\\]/.test(o)&&m("NATIVE_ROUTE_MANIFEST_STATIC_PATH_INVALID",t),o}function Li(e,t,o){let n=O(e,t);R(n,["routeCode","path","surface","pathParams","requiresAuthentication"],t,["capability","access"]),P(n.routeCode,`${t}/routeCode`);let i=Ee(n.path,`${t}/path`),s=S(n.surface,`${t}/surface`,16);["admin","user"].includes(s)||m("NATIVE_ROUTE_SURFACE_INVALID",`${t}/surface`);let a=F(n.pathParams,`${t}/pathParams`,8);return a.forEach((r,c)=>{(!/^[A-Za-z][A-Za-z0-9_]*$/.test(r)||r.length>64)&&m("NATIVE_ROUTE_PATH_PARAM_INVALID",`${t}/pathParams/${c}`)}),ne(a)!==ne(is(i))&&m("NATIVE_ROUTE_PATH_PARAMS_MISMATCH",`${t}/pathParams`),ro(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 xi(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 ji(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 Wa(e){let t=e.appCode,o=[],n=(g,I,E,N,y,_,A)=>{o.push({code:g,kind:I,...y?{workflowCode:y}:{},...A?{resourceCode:A}:{},desktop:xi(ji(I,"desktop",y,A),E,"user",_),mobile:xi(ji(I,"mobile",y,A),N,"user",_)})};e.frontend.user.applicationTodoCenter===!0&&n("application:todo-center","application-todo-center","/todos","/m/todos");let i=ss(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 g of i){if(!["standalone","hidden-handoff"].includes(g.launch.mode))continue;let I=M([g.launch.submission?.create?.requiredCapability,g.launch.submission?.existing?.requiredCapability].filter(E=>!!E));n(`workflow:${g.code}:launch`,"workflow-launch","/workflows/:workflowCode/start","/m/workflows/:workflowCode/start",g.code,I.length===1?{capability:I[0]}:I.length>1?{access:{anyOf:I}}:void 0)}let s=o.sort((g,I)=>me(String(g.code),String(I.code))),a=tn(e),r=g=>{let I=g==="mobile"?"/m/":"/",E=a.filter(y=>y.surface==="user"&&!/[:*?#\\\\]/.test(y.path)&&y.path===I).sort((y,_)=>me(y.code,_.code))[0];if(E)return{code:E.code,path:E.path};let N=a.filter(y=>y.surface==="user"&&!/[:*?#\\\\]/.test(y.path)&&(g==="mobile"?y.path.startsWith("/m/"):!y.path.startsWith("/m/"))).sort((y,_)=>me(y.code,_.code))[0];return N?{code:N.code,path:N.path}:{code:g==="mobile"?"application-root-mobile":"application-root",path:I}},c=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"}},l=so(e.frontend.devicePolicy,"/config/frontend/devicePolicy"),p=r("desktop"),d=r("mobile"),u={schemaVersion:Yi,appCode:t,devicePolicy:l,rootEntry:{code:p.code,desktop:p.path,mobile:d.path},authentication:c,routes:s};return{...u,digest:Q(u)}}function Qt(e,t){if(e===void 0)return;let o=S(e,t,32);Zr.has(o)||m("NATIVE_ADMIN_ICON_INVALID",t)}function Wi(e,t){e!==void 0&&se(e,t,-1e4,1e4)}function ro(e,t,o){return e.capability!==void 0&&e.access!==void 0&&m("NATIVE_ROUTE_ACCESS_CONFLICT",`${t}/access`),e.capability!==void 0?{capability:fe(e.capability,`${t}/capability`,o)}:e.access===void 0?{}:{access:nn(e.access,`${t}/access`,o)}}function nn(e,t,o){let n=O(e,t);R(n,["allOf","anyOf"],t,!0);let i=n.allOf===void 0?void 0:M(F(n.allOf,`${t}/allOf`,50).map((a,r)=>fe(a,`${t}/allOf/${r}`,o))),s=n.anyOf===void 0?void 0:M(F(n.anyOf,`${t}/anyOf`,50).map((a,r)=>fe(a,`${t}/anyOf/${r}`,o)));return(i?.length||0)+(s?.length||0)===0&&m("NATIVE_ROUTE_ACCESS_EMPTY",t),{...i===void 0?{}:{allOf:i},...s===void 0?{}:{anyOf:s}}}function ss(e){let t=new Map(Qi(e).map(i=>[String(i.code),i])),o=e.workflows.definitions.map((i,s)=>{let a=`/config/workflows/definitions/${s}`,r=O(i,a);R(r,["version","definition","launch"],a,["detailRouteCode"]);let c=O(r.definition,`${a}/definition`),l=r.detailRouteCode===void 0?void 0:as(r.detailRouteCode,`${a}/detailRouteCode`);return{code:P(c.code,`${a}/definition/code`),title:S(c.title,`${a}/definition/title`,255),version:et(r.version,`${a}/version`),launch:Ua(e,c,r.launch,`${a}/launch`,t),...l?{detailRouteCode:l}:{},definition:c}});return M(o.map(i=>i.code)).map(i=>{let s=o.filter(l=>l.code===i),a=e.workflows.activations.find(l=>l.workflowCode===i)?.definitionVersion,r=s.find(l=>l.version===a)||[...s].sort((l,p)=>p.version-l.version)[0],c=new Set;for(let l of s){let p=O(l.definition.nodes,"/config/workflows/definitions/nodes");for(let d of Object.values(p)){let u=O(d,"/config/workflows/definitions/nodes/*");if(u.kind==="approval")for(let g of F(u.allowedOperations||[],"/config/workflows/definitions/nodes/*/allowedOperations",20))c.add(g)}}return{code:i,title:r.title,acceptedCommandDeactivationPolicy:r.definition.acceptedCommandDeactivationPolicy,subject:r.definition.subject,launch:r.launch,...["standalone","hidden-handoff"].includes(r.launch.mode)&&!r.launch.submission?{processOperationCode:`openxiangda.workflow.${i}.submit`}:{},...r.detailRouteCode?{detailRouteCode:r.detailRouteCode}:{},definitionVersions:zi(s.map(l=>l.version)),bindingVersions:zi(e.workflows.bindings.map((l,p)=>{let d=`/config/workflows/bindings/${p}`,u=O(l,d),g=O(u.binding,`${d}/binding`);return{code:P(g.workflowCode,`${d}/binding/workflowCode`),version:et(u.version,`${d}/version`)}}).filter(l=>l.code===i).map(l=>l.version)),providerCodes:M(e.workflows.providers.map((l,p)=>P(O(l,`/config/workflows/providers/${p}`).code,`/config/workflows/providers/${p}/code`))),allowedOperations:[...c].sort(me),editableParameterCodes:M(e.workflows.editableParameters.map((l,p)=>{let d=`/config/workflows/editableParameters/${p}`,u=O(l,d);return{code:P(u.code,`${d}/code`),workflowCode:P(u.workflowCode,`${d}/workflowCode`)}}).filter(l=>l.workflowCode===i).map(l=>l.code))}})}function rs(e,t){let o=O(e,t);R(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:O(o.submission,`${t}/submission`)}}}function Ua(e,t,o,n,i){let s=rs(o,n);if(!s.submission)return{mode:s.mode};["standalone","hidden-handoff"].includes(s.mode)||m("NATIVE_WORKFLOW_NAMED_OPERATION_SUBMISSION_INVALID",`${n}/submission`);let a=O(s.submission,`${n}/submission`);R(a,["kind"],`${n}/submission`,["create","existing","context"]),x(a.kind,"named-operation",`${n}/submission/kind`);let r=n.endsWith("/launch")?n.slice(0,-7):n,c=O(t.subject,`${r}/definition/subject`),l=G(c.resourceCode,`${r}/definition/subject/resourceCode`),p=e.data.resources.findIndex(b=>b.code===l),d=e.data.resources[p];(p<0||!d)&&m("NATIVE_WORKFLOW_SUBJECT_RESOURCE_MISSING",`${r}/definition/subject/resourceCode`);let u=new Set(O(d.schema,`/config/data/resources/${p}/schema`).fields.map(b=>String(b.code))),g=new Map(e.backend.operations.map(b=>[String(b.code),b])),I=(b,h)=>{let C=`${n}/submission/${h}`,$=O(b,C);R($,["operationCode","inputs","output"],C);let k=P($.operationCode,`${C}/operationCode`),W=g.get(k),v=i.get(k),Y=v?.platformAccess?.workflow?.codes;(!W||!v||v.method!=="POST"||!Array.isArray(Y)||!Y.includes(t.code))&&m("NATIVE_WORKFLOW_NAMED_OPERATION_INVALID",C);let te=O(W.requestSchema,`${C}/operation/requestSchema`),H=O(te.properties,`${C}/operation/requestSchema/properties`),he=new Set(te.required===void 0?[]:F(te.required,`${C}/operation/requestSchema/required`,64)),le=O($.inputs,`${C}/inputs`),V=Object.entries(le);(!V.length||V.length>64)&&m("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${C}/inputs`);let U=new Set,L=new Map,q={};for(let[z,Z]of V){(!Vi.test(z)||!Object.prototype.hasOwnProperty.call(H,z))&&m("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${C}/inputs/${z}`);let Ke=`${C}/inputs/${z}`,rn=O(Z,Ke),ve=S(rn.source,`${Ke}/source`,32);if(["field","idempotency-key","current-user-reference","subject-id","subject-revision","requested-at"].includes(ve)||m("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",Ke),R(rn,["source"],Ke,ve==="field"?["fieldCode"]:!1),L.set(ve,(L.get(ve)||0)+1),ve==="field"){let Tt=K(rn.fieldCode,`${Ke}/fieldCode`);(U.has(Tt)||!u.has(Tt))&&m("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${Ke}/fieldCode`),U.add(Tt),q[z]={source:ve,fieldCode:Tt}}else q[z]={source:ve}}([...he].some(z=>!(z in le))||(L.get("idempotency-key")||0)!==1||!V.some(([z,Z])=>O(Z,`${C}/inputs/${z}`).source==="idempotency-key"&&he.has(z))||h==="create"&&((L.get("subject-id")||0)>0||(L.get("subject-revision")||0)>0)||h==="existing"&&((L.get("subject-id")||0)!==1||(L.get("subject-revision")||0)!==1))&&m("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${C}/inputs`);let J=O($.output,`${C}/output`);R(J,["subjectId"],`${C}/output`,["subjectRevision","processCommand"]);let Re=O(O(W.responseSchema,`${C}/operation/responseSchema`).properties,`${C}/operation/responseSchema/properties`);for(let z of["subjectId","subjectRevision","processCommand"]){if(J[z]===void 0)continue;let Z=S(J[z],`${C}/output/${z}`,128);(!Vi.test(Z)||!Object.prototype.hasOwnProperty.call(Re,Z))&&m("NATIVE_WORKFLOW_NAMED_OPERATION_OUTPUT_INVALID",`${C}/output/${z}`)}return{operationCode:k,method:"POST",path:v.path,requiredCapability:v.requiredCapability,requestSchemaDigest:v.requestSchemaDigest,responseSchemaDigest:v.responseSchemaDigest,inputs:q,output:{...J},fieldCodes:U}},E=a.create===void 0?void 0:I(a.create,"create"),N=a.existing===void 0?void 0:I(a.existing,"existing");!E&&!N&&m("NATIVE_WORKFLOW_NAMED_OPERATION_SUBMISSION_INVALID",`${n}/submission`);let y=new Set([...E?.fieldCodes||[],...N?.fieldCodes||[]]),_=a.context===void 0?[]:w(a.context,`${n}/submission/context`,16),A=new Set,T=_.map((b,h)=>{let C=`${n}/submission/context/${h}`,$=O(b,C);R($,["queryParameter","fieldCode"],C);let k=S($.queryParameter,`${C}/queryParameter`,64),W=K($.fieldCode,`${C}/fieldCode`);return(!/^[A-Za-z][A-Za-z0-9]{0,63}$/.test(k)||A.has(k)||!y.has(W))&&m("NATIVE_WORKFLOW_LAUNCH_CONTEXT_INVALID",C),A.add(k),{queryParameter:k,fieldCode:W}}),f=b=>{let{fieldCodes:h,...C}=b;return C};return{mode:s.mode,submission:{kind:"named-operation",...E?{create:f(E)}:{},...N?{existing:f(N)}:{},context:T}}}function as(e,t){let o=O(e,t);R(o,["desktop","mobile"],t);let n=P(o.desktop,`${t}/desktop`),i=P(o.mobile,`${t}/mobile`);return n===i&&m("NATIVE_WORKFLOW_DETAIL_ROUTE_DUPLICATE",t),{desktop:n,mobile:i}}function Ma(e,t){let o=new Set(t.map(p=>p.code)),n=new Map;e.data.resources.forEach((p,d)=>{let u=`/config/data/resources/${d}`,g=O(p,u);if(g.recordDeletion!==void 0){let N=`${u}/recordDeletion/delete`;for(let y of g.recordDeletion.delete)fe(y,N,e.appCode),o.has(y)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",N)}if(g.recordComments!==void 0)for(let N of["read","create"]){let y=`${u}/recordComments/${N}`;for(let _ of g.recordComments[N])fe(_,y,e.appCode),o.has(_)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",y)}if(g.recordPrint!==void 0){let N=`${u}/recordPrint/read`;for(let y of g.recordPrint.read)fe(y,N,e.appCode),o.has(y)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",N)}if(g.workflowHistory!==void 0){let N=`${u}/workflowHistory/read`;for(let y of g.workflowHistory.read)fe(y,N,e.appCode),o.has(y)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",N)}for(let[N,y]of Object.entries(g.fieldPolicies||{})){if(!ot(N))continue;let _=`${u}/fieldPolicies/${N}/read`,A=O(y,`${u}/fieldPolicies/${N}`);for(let T of F(A.read||[],_,2e3))o.has(T)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",_)}let I=g.surface===void 0?{}:O(g.surface,`${u}/surface`);if(["native","queued-command"].includes(I.mutationOwner||"native"))return;let E=O(g.capabilities,`${u}/capabilities`);for(let N of["create","update","delete"])N==="delete"&&Array.isArray(g.recordDeletion?.delete)&&g.recordDeletion.delete.length>0||n.set(String(E[N]),N)});let i=new Set;for(let[p,d]of e.authz.roles.entries()){let u=`/config/authz/roles/${p}`,g=O(d,u);R(g,["code","name","description","capabilities"],u,!0);let I=P(g.code,`${u}/code`);i.has(I)&&m("NATIVE_ROLE_DUPLICATE",`${u}/code`),i.add(I),S(g.name,`${u}/name`,255);let E=F(g.capabilities,`${u}/capabilities`,2e3);for(let[N,y]of E.entries())n.has(y)&&m("NATIVE_DATA_SURFACE_MUTATION_GRANT_FORBIDDEN",`${u}/capabilities/${N}`,{operation:n.get(y)}),o.has(y)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",`${u}/capabilities`)}let s=e.authz.authenticatedUserRoleCode===void 0?"":P(e.authz.authenticatedUserRoleCode,"/config/authz/authenticatedUserRoleCode");s&&!i.has(s)&&m("NATIVE_AUTHENTICATED_USER_ROLE_REFERENCE_MISSING","/config/authz/authenticatedUserRoleCode");let a=new Set,r=0;for(let[p,d]of e.perspectives.entries()){let u=`/config/perspectives/${p}`,g=O(d,u);R(g,["code","name","description","roleCodes","capabilityCodes","default"],u,!0);let I=P(g.code,`${u}/code`);a.has(I)&&m("NATIVE_PERSPECTIVE_DUPLICATE",`${u}/code`),a.add(I),S(g.name,`${u}/name`,255);let E=F(g.roleCodes,`${u}/roleCodes`,20);E.length<1&&m("NATIVE_PERSPECTIVE_ROLE_REQUIRED",`${u}/roleCodes`),E.forEach((_,A)=>{i.has(_)||m("NATIVE_PERSPECTIVE_ROLE_MISSING",`${u}/roleCodes/${A}`)});let N=M(e.authz.roles.filter(_=>E.includes(_.code)).flatMap(_=>_.capabilities)),y=F(g.capabilityCodes,`${u}/capabilityCodes`,2e3);ne(N)!==ne(y)&&m("NATIVE_PERSPECTIVE_CAPABILITY_PROJECTION_MISMATCH",`${u}/capabilityCodes`),g.default===!0?r+=1:g.default!==void 0&&m("NATIVE_PERSPECTIVE_DEFAULT_INVALID",`${u}/default`)}r>1&&m("NATIVE_PERSPECTIVE_DEFAULT_DUPLICATE","/config/perspectives");for(let[p,d]of e.backend.operations.entries()){let u=O(d,`/config/backend/operations/${p}`);o.has(u.capability)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",`/config/backend/operations/${p}/capability`)}let c=new Set,l=new Set;for(let[p,d]of e.frontend.routes.entries()){let u=`/config/frontend/routes/${p}`,g=O(d,u),I=P(g.code,`${u}/code`);c.has(I)&&m("NATIVE_ROUTE_DUPLICATE",`${u}/code`),c.add(I);let E=Ee(g.path,`${u}/path`);l.has(E)&&m("NATIVE_ROUTE_PATH_DUPLICATE",`${u}/path`),l.add(E);let N=ro(g,u,e.appCode);N.capability&&!o.has(N.capability)&&m("NATIVE_CAPABILITY_REFERENCE_MISSING",`${u}/capability`);let y=g.access===void 0?void 0:O(g.access,`${u}/access`);for(let _ of["allOf","anyOf"]){let A=y?.[_]===void 0?[]:w(y[_],`${u}/access/${_}`,50);for(let[T,f]of A.entries()){let b=fe(f,`${u}/access/${_}/${T}`,e.appCode);o.has(b)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",`${u}/access/${_}/${T}`)}}}if(e.frontend.admin.access!==void 0){let p=nn(e.frontend.admin.access,"/config/frontend/admin/access",e.appCode);for(let d of["allOf","anyOf"])for(let[u,g]of(p[d]||[]).entries())o.has(g)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",`/config/frontend/admin/access/${d}/${u}`)}for(let[p,d]of e.frontend.routes.entries()){let u=O(d,`/config/frontend/routes/${p}`);u.parentCode&&!c.has(u.parentCode)&&m("NATIVE_ROUTE_PARENT_MISSING",`/config/frontend/routes/${p}/parentCode`)}}function Ba(e){let t=new Set(e.authz.roles.map(l=>String(l.code))),o=e.authz.authenticatedUserRoleCode===void 0?"":P(e.authz.authenticatedUserRoleCode,"/config/authz/authenticatedUserRoleCode"),n=new Map(e.authz.scopeDimensions.map(l=>[String(l.code),{valueType:l.valueType==="uuid"?"uuid":"string",...l.valueSource?.resourceCode?{valueSourceResourceCode:String(l.valueSource.resourceCode)}:{}}])),i=new Set(n.keys()),s=new Map(e.data.resources.map((l,p)=>{let d=Me(l,`/config/data/resources/${p}`,e.appCode);return[d.code,new Map(d.schema.fields.map(u=>[String(u.code),u]))]}));for(let[l,p]of e.authz.scopeDimensions.entries()){let d=`/config/authz/scopeDimensions/${l}`,u=O(p,d);if(R(u,["code","name","resourceCode","valueType","hierarchyMode","valueSource"],d,!0),u.valueSource===void 0)continue;let g=O(u.valueSource,`${d}/valueSource`);R(g,["kind","resourceCode","labelField","enabledField"],`${d}/valueSource`,!0),g.kind!=="native_resource"&&m("NATIVE_SCOPE_VALUE_SOURCE_KIND_INVALID",`${d}/valueSource/kind`),u.valueType!=="uuid"&&m("NATIVE_SCOPE_VALUE_SOURCE_TYPE_INVALID",`${d}/valueType`);let I=G(g.resourceCode,`${d}/valueSource/resourceCode`),E=s.get(I);E||m("NATIVE_SCOPE_VALUE_SOURCE_RESOURCE_MISSING",`${d}/valueSource/resourceCode`);let N=K(g.labelField,`${d}/valueSource/labelField`);if(["text.short","text.long"].includes(String(E.get(N)?.type||""))||m("NATIVE_SCOPE_VALUE_SOURCE_LABEL_FIELD_INVALID",`${d}/valueSource/labelField`),g.enabledField!==void 0){let y=K(g.enabledField,`${d}/valueSource/enabledField`);E.get(y)?.type!=="boolean"&&m("NATIVE_SCOPE_VALUE_SOURCE_ENABLED_FIELD_INVALID",`${d}/valueSource/enabledField`)}}let a=new Set,r=new Set;for(let[l,p]of e.authz.scopeSources.entries()){let d=`/config/authz/scopeSources/${l}`,u=O(p,d);R(u,["code","name","resourceCode","subject","grants","operationField","enabledField","effectiveFromField","effectiveToField","failureMode"],d,!0);let g=P(u.code,`${d}/code`);a.has(g)&&m("NATIVE_SCOPE_SOURCE_DUPLICATE",`${d}/code`),a.add(g),S(u.name,`${d}/name`,255);let I=G(u.resourceCode,`${d}/resourceCode`),E=s.get(I);E||m("NATIVE_SCOPE_SOURCE_RESOURCE_MISSING",`${d}/resourceCode`);let N=O(u.subject,`${d}/subject`),y=S(N.type,`${d}/subject/type`,32);R(N,y==="role_membership"?["type","userIdField","roleCode"]:["type","userIdField"],`${d}/subject`),["user","role_membership"].includes(y)||m("NATIVE_SCOPE_SOURCE_SUBJECT_INVALID",`${d}/subject/type`);let _=at(N.userIdField,E);$n(_)||m("NATIVE_SCOPE_SOURCE_SUBJECT_PATH_INVALID",`${d}/subject/userIdField`),y==="role_membership"&&!t.has(String(N.roleCode))&&m("NATIVE_ROLE_REFERENCE_MISSING",`${d}/subject/roleCode`);let A=new Set;for(let[T,f]of w(u.grants,`${d}/grants`,100).entries()){let b=`${d}/grants/${T}`,h=O(f,b);R(h,["dimensionCode","valueField","parentValueField"],b,!0);let C=P(h.dimensionCode,`${b}/dimensionCode`);(!i.has(C)||A.has(C))&&m("NATIVE_SCOPE_SOURCE_DIMENSION_INVALID",`${b}/dimensionCode`),A.add(C),u.failureMode==="last_known_good"&&r.add(C);for(let $ of["valueField","parentValueField"]){if(h[$]===void 0)continue;let k=at(h[$],E);Go(k,n.get(C),s)||m("NATIVE_SCOPE_SOURCE_GRANT_PATH_INVALID",`${b}/${$}`)}}A.size===0&&m("NATIVE_SCOPE_SOURCE_GRANT_REQUIRED",`${d}/grants`),["strict","last_known_good"].includes(u.failureMode)||m("NATIVE_SCOPE_SOURCE_FAILURE_MODE_INVALID",`${d}/failureMode`);for(let T of["operationField","enabledField","effectiveFromField","effectiveToField"]){if(u[T]===void 0)continue;let f=K(u[T],`${d}/${T}`);E.has(f)||m("NATIVE_SCOPE_SOURCE_FIELD_MISSING",`${d}/${T}`)}}qa(e,t,s,o);let c=new Set;for(let[l,p]of e.authz.dataPolicies.entries()){let d=`/config/authz/dataPolicies/${l}`,u=O(p,d);R(u,["code","name","resourceCode","unrestrictedRoleCodes","operations","matchMode","rules","readExpression","writeBoundary"],d,!0);let g=P(u.code,`${d}/code`);c.has(g)&&m("NATIVE_DATA_POLICY_DUPLICATE",`${d}/code`),c.add(g);let I=u.readExpression!==void 0,E=F(u.operations||[],`${d}/operations`,4);u.operations!==void 0&&(E.length===0||E.some(f=>!["read","create","update","delete"].includes(f)))&&m("NATIVE_DATA_POLICY_OPERATIONS_INVALID",`${d}/operations`),["AND","OR"].includes(u.matchMode)||m("NATIVE_DATA_POLICY_MATCH_MODE_INVALID",`${d}/matchMode`),I&&u.operations!==void 0&&m("NATIVE_DATA_POLICY_READ_EXPRESSION_OPERATIONS_FORBIDDEN",`${d}/operations`);let N=e.data.resources.find(f=>f.dataPolicyCode===g),y=u.resourceCode||N?.code,_=y?s.get(G(y,`${d}/resourceCode`)):void 0;I&&!_&&m("NATIVE_DATA_POLICY_RESOURCE_MISSING",`${d}/resourceCode`);let A=F(u.unrestrictedRoleCodes||[],`${d}/unrestrictedRoleCodes`,100);u.unrestrictedRoleCodes!==void 0&&A.length===0&&m("NATIVE_DATA_POLICY_UNRESTRICTED_ROLES_INVALID",`${d}/unrestrictedRoleCodes`);for(let f of A)t.has(f)||m("NATIVE_ROLE_REFERENCE_MISSING",`${d}/unrestrictedRoleCodes`);let T;try{let f=w(u.rules,`${d}/rules`,100).map((b,h)=>({rule:O(b,`${d}/rules/${h}`),pointer:`${d}/rules/${h}`}));f.length===0?(!I||u.matchMode!=="AND"||u.writeBoundary!=="capability_only")&&m("NATIVE_DATA_POLICY_WRITE_BOUNDARY_REQUIRED",d):u.writeBoundary!==void 0&&m("NATIVE_DATA_POLICY_WRITE_BOUNDARY_INVALID",`${d}/writeBoundary`),T=[...f],I&&(T.push(...Yt(u.readExpression,`${d}/readExpression`)),Di(u.readExpression,`${d}/readExpression`))}catch(f){throw f instanceof yt&&m(f.code,f.pointer),f}for(let{rule:f,pointer:b}of T){R(f,["subject","dimensionCode","relationCode","resourceCode","field","roleCodes","operation","valuePath","emptyMatchesAll","operator","value","operand"],b,!0);let h=K(f.field,`${b}/field`),C=_?.get(h);I&&!C&&m("NATIVE_DATA_POLICY_FIELD_MISSING",`${b}/field`);for(let H of F(f.roleCodes||[],`${b}/roleCodes`,100))t.has(H)||m("NATIVE_ROLE_REFERENCE_MISSING",`${b}/roleCodes`);let $=String(f.operator||""),k=f.operand==="db_now",W=["is_null","is_not_null"].includes($),v=["eq","not_eq","in","not_in"].includes($),Y=!k&&(f.operator!==void 0||f.value!==void 0);if([f.subject==="current_user"?"current_user":"",typeof f.dimensionCode=="string"?"dimension":"",typeof f.relationCode=="string"?"relationship":"",Y?"constant":"",k?"db_now":""].filter(Boolean).length!==1&&m("NATIVE_DATA_POLICY_RULE_SOURCE_INVALID",b),f.subject!==void 0&&f.subject!=="current_user"&&m("NATIVE_DATA_POLICY_SUBJECT_INVALID",`${b}/subject`),Y){if(!v&&!W&&m("NATIVE_DATA_POLICY_OPERATOR_INVALID",`${b}/operator`),["in","not_in"].includes($)){let H=w(f.value,`${b}/value`,100).map((he,le)=>S(he,`${b}/value/${le}`,2048));(H.length===0||new Set(H).size!==H.length)&&m("NATIVE_DATA_POLICY_VALUE_INVALID",`${b}/value`)}else["eq","not_eq"].includes($)?S(f.value,`${b}/value`,2048):(f.value!==void 0||f.operand!==void 0)&&m("NATIVE_DATA_POLICY_VALUE_INVALID",`${b}/value`);for(let H of["operation","valuePath","emptyMatchesAll","resourceCode","operand"])f[H]!==void 0&&m("NATIVE_DATA_POLICY_CONSTANT_RULE_INVALID",`${b}/${H}`)}if(k){(!["lt","lte","gt","gte"].includes($)||f.value!==void 0||C?.type!=="datetime")&&m("NATIVE_DATA_POLICY_DB_NOW_INVALID",b);for(let H of["operation","valuePath","emptyMatchesAll","resourceCode","value"])f[H]!==void 0&&m("NATIVE_DATA_POLICY_DB_NOW_INVALID",`${b}/${H}`)}f.dimensionCode&&!i.has(f.dimensionCode)&&m("NATIVE_SCOPE_DIMENSION_MISSING",`${b}/dimensionCode`),r.has(String(f.dimensionCode||""))&&f.operation!=="read"&&m("NATIVE_SCOPE_SOURCE_LAST_KNOWN_GOOD_UNSAFE",`${b}/operation`)}}for(let[l,p]of e.data.resources.entries()){let d=O(p,`/config/data/resources/${l}`);d.dataPolicyCode&&!c.has(d.dataPolicyCode)&&m("NATIVE_DATA_POLICY_REFERENCE_MISSING",`/config/data/resources/${l}/dataPolicyCode`)}}function Ka(e){try{To(e.data.resources,"/config/data/resources"),e.data.resources.forEach((t,o)=>go(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 ye||t instanceof Le)&&m(t.code,t.pointer),t}}function qa(e,t,o,n){let i=new Set;for(let[s,a]of e.authz.roleMembershipSources.entries()){let r=`/config/authz/roleMembershipSources/${s}`,c=O(a,r);R(c,["code","name","resourceCode","userIdField","roleCode","enabledField","effectiveFromField","effectiveToField","failureMode"],r,!0);let l=P(c.code,`${r}/code`);l.length>100&&m("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_CODE_INVALID",`${r}/code`),i.has(l)&&m("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_DUPLICATE",`${r}/code`),i.add(l),S(c.name,`${r}/name`,255);let p=Ui(c.resourceCode,`${r}/resourceCode`,o);Mi(c.userIdField,`${r}/userIdField`,p),t.has(String(c.roleCode||""))||m("NATIVE_ROLE_REFERENCE_MISSING",`${r}/roleCode`),n&&c.roleCode===n&&m("NATIVE_AUTHENTICATED_USER_ROLE_SOURCE_CONFLICT",`${r}/roleCode`),Bi(c,r,p)}for(let[s,a]of e.authz.relationshipGrantSources.entries()){let r=`/config/authz/relationshipGrantSources/${s}`,c=O(a,r);R(c,["code","name","resourceCode","subject","relationCode","targetResourceCode","resourceIdField","operations","enabledField","effectiveFromField","effectiveToField","failureMode"],r,!0);let l=P(c.code,`${r}/code`);l.length>100&&m("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_CODE_INVALID",`${r}/code`),i.has(l)&&m("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_DUPLICATE",`${r}/code`),i.add(l),S(c.name,`${r}/name`,255);let p=Ui(c.resourceCode,`${r}/resourceCode`,o),d=O(c.subject,`${r}/subject`),u=S(d.type,`${r}/subject/type`,32);R(d,u==="role_membership"?["type","userIdField","roleCode"]:["type","userIdField"],`${r}/subject`),["user","role_membership"].includes(u)||m("NATIVE_AUTHORIZATION_PROJECTION_SUBJECT_INVALID",`${r}/subject/type`),Mi(d.userIdField,`${r}/subject/userIdField`,p),u==="role_membership"&&!t.has(String(d.roleCode||""))&&m("NATIVE_ROLE_REFERENCE_MISSING",`${r}/subject/roleCode`),P(c.relationCode,`${r}/relationCode`);let g=G(c.targetResourceCode,`${r}/targetResourceCode`);o.has(g)||m("NATIVE_AUTHORIZATION_PROJECTION_TARGET_RESOURCE_MISSING",`${r}/targetResourceCode`);let I=at(c.resourceIdField,p),E=I?.field.type==="resource-ref.single"&&I.valuePath==="value"&&I.field.source?.resourceCode===g;(c.resourceIdField==="id"?g!==String(c.resourceCode):!E)&&m("NATIVE_AUTHORIZATION_PROJECTION_RESOURCE_ID_FIELD_INVALID",`${r}/resourceIdField`);let N=F(c.operations,`${r}/operations`,20);(N.length===0||N.some(y=>y.length>64||!/^[A-Za-z0-9][A-Za-z0-9:._*-]{0,63}$/.test(y)))&&m("NATIVE_AUTHORIZATION_PROJECTION_OPERATIONS_INVALID",`${r}/operations`),Bi(c,r,p)}}function Ui(e,t,o){let n=G(e,t),i=o.get(n);return i||m("NATIVE_AUTHORIZATION_PROJECTION_RESOURCE_MISSING",t),i}function Mi(e,t,o){let n=at(e,o);$n(n)||m("NATIVE_AUTHORIZATION_PROJECTION_USER_FIELD_INVALID",t)}function Bi(e,t,o){if(e.failureMode!=="strict"&&m("NATIVE_AUTHORIZATION_PROJECTION_FAILURE_MODE_INVALID",`${t}/failureMode`),e.enabledField!==void 0){let n=K(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=K(e[n],`${t}/${n}`);["date","datetime"].includes(String(o.get(i)?.type))||m("NATIVE_AUTHORIZATION_PROJECTION_EFFECTIVE_FIELD_INVALID",`${t}/${n}`)}}function Ja(e){let t=new Set,o=new Set;e.forEach((n,i)=>{let s=`/config/backend/secrets/${i}`,a=O(n,s);R(a,["name","env","description","required","exposure"],s,!0);let r=S(a.name,`${s}/name`,128),c=S(a.env,`${s}/env`,128);qr.test(r)||m("NATIVE_SECRET_NAME_INVALID",`${s}/name`),(!Jr.test(c)||c.startsWith("OPENXIANGDA_")||["NODE_ENV","PORT"].includes(c))&&m("NATIVE_SECRET_ENV_INVALID",`${s}/env`),t.has(r)&&m("NATIVE_SECRET_NAME_DUPLICATE",`${s}/name`),o.has(c)&&m("NATIVE_SECRET_ENV_DUPLICATE",`${s}/env`),t.add(r),o.add(c),x(a.exposure,"active_only",`${s}/exposure`),a.required!==void 0&&tt(a.required,`${s}/required`),a.description!==void 0&&ao(a.description,`${s}/description`,2e3)})}function Ga(e){let t=new Set,o=new Map,n=new Map(e.data.resources.map(g=>[String(g.code),g])),i=new Map(e.frontend.routes.map((g,I)=>{let E=O(g,`/config/frontend/routes/${I}`);return[P(E.code,`/config/frontend/routes/${I}/code`),E]}));for(let[g,I]of e.workflows.definitions.entries()){let E=`/config/workflows/definitions/${g}`,N=O(I,E);if(R(N,["version","definition","launch"],E,["detailRouteCode"]),rs(N.launch,`${E}/launch`),N.detailRouteCode!==void 0){let h=as(N.detailRouteCode,`${E}/detailRouteCode`);for(let[C,$,k]of[["desktop",h.desktop,["admin","user"]],["mobile",h.mobile,["user"]]]){let W=`${E}/detailRouteCode/${C}`,v=i.get($);v||m("NATIVE_WORKFLOW_DETAIL_ROUTE_MISSING",W),k.some(H=>H===v.surface)||m("NATIVE_WORKFLOW_DETAIL_ROUTE_SURFACE_INVALID",W);let Y=Ee(v.path,W),te=[...Y.matchAll(/:([A-Za-z][A-Za-z0-9_]*)/g)].map(H=>H[1]);(Y.includes("*")||te.length!==1||te[0]!=="instanceId")&&m("NATIVE_WORKFLOW_DETAIL_ROUTE_PATH_INVALID",W)}}let y=O(N.definition,`${E}/definition`),_=`${y.code}:${et(N.version,`${E}/version`)}`;t.has(_)&&m("NATIVE_WORKFLOW_DEFINITION_DUPLICATE",E),t.add(_),Ha(y,`${E}/definition`);let A=Jn(y);A.length&&m(A[0],`${E}/definition/launchPreflight`);let T=Ei(y,e.backend.operations);T.length&&m(T[0],`${E}/definition/commandHandlers`),za(y.subject,n,`${E}/definition/subject`);let f=zt(y,new Map((n.get(y.subject.resourceCode)?.schema.fields||[]).map(h=>[h.code,{...n.get(y.subject.resourceCode)?.surface?.fields?.[h.code],...h,system:["id","revision","createdAt","updatedAt","createdBy","updatedBy"].includes(h.code)}])),new Map([...n].map(([h,C])=>[h,new Map(C.schema.fields.map($=>[$.code,{...C.surface?.fields?.[$.code],...$,system:["id","revision","createdAt","updatedAt","createdBy","updatedBy"].includes($.code)}]))])));f.length&&m(f[0],`${E}/definition/taskPages`);let b=oi(y,{appCode:e.appCode,capabilities:e.authz.capabilities.map(h=>h.code),fields:new Map((n.get(y.subject.resourceCode)?.schema.fields||[]).map(h=>[h.code,h]))});b.length&&m("NATIVE_WORKFLOW_INSTANCE_COMMAND_POLICY_INVALID",`${E}/definition/instanceCommands`,{errors:b}),y.title===y.code&&m("NATIVE_WORKFLOW_USER_TITLE_REQUIRED",`${E}/definition/title`),o.set(_,y)}let s=new Set,a=new Map;for(let[g,I]of e.workflows.bindings.entries()){let E=O(I,`/config/workflows/bindings/${g}`),N=O(E.binding,`/config/workflows/bindings/${g}/binding`),y=`${N.workflowCode}:${et(E.version,`/config/workflows/bindings/${g}/version`)}`;s.has(y)&&m("NATIVE_WORKFLOW_BINDING_DUPLICATE",`/config/workflows/bindings/${g}`),s.add(y),Ya(N,`/config/workflows/bindings/${g}/binding`),a.set(y,N)}let r=new Set,c=new Map;for(let[g,I]of e.workflows.activations.entries()){let E=`/config/workflows/activations/${g}`,N=O(I,E);R(N,["workflowCode","definitionVersion","bindingVersion","acceptedCommandDeactivationPolicy"],E,["environmentKey"]);let y=P(N.workflowCode,`${E}/workflowCode`);r.has(y)&&m("NATIVE_WORKFLOW_ACTIVATION_DUPLICATE",E),r.add(y);let _=`${y}:${et(N.definitionVersion,`${E}/definitionVersion`)}`,A=`${y}:${et(N.bindingVersion,`${E}/bindingVersion`)}`;t.has(_)||m("NATIVE_WORKFLOW_DEFINITION_REFERENCE_MISSING",`${E}/definitionVersion`),s.has(A)||m("NATIVE_WORKFLOW_BINDING_REFERENCE_MISSING",`${E}/bindingVersion`);let T=o.get(_),f=a.get(A),b=Jn(T,f);b.length&&m(b[0],E);let h=Mn(T,f);h.length&&m(h[0],E),(!["finish-pinned","cancel-on-deactivate"].includes(N.acceptedCommandDeactivationPolicy)||N.acceptedCommandDeactivationPolicy!==T.acceptedCommandDeactivationPolicy)&&m("NATIVE_WORKFLOW_COMMAND_DEACTIVATION_POLICY_MISMATCH",`${E}/acceptedCommandDeactivationPolicy`),Xa(T,f,`/config/workflows/activations/${g}`);try{let C=n.get(T.subject.resourceCode)?.schema.fields||[];Ao(T,f,new Map(C.map($=>[$.code,$])),`${E}/bindings`,new Map([...n].map(([$,k])=>[$,new Map(k.schema.fields.map(W=>[W.code,W]))])))}catch(C){throw C instanceof Le&&m(C.code,C.pointer),C}c.set(y,f)}let l=Ci([...c.values()]);l.length&&m(l[0],"/config/workflows/activations");let p=new Set;e.workflows.providers.forEach((g,I)=>{let E=`/config/workflows/providers/${I}`,N=O(g,E);R(N,["code","endpointPath","timeoutMs"],E,!0);let y=P(N.code,`${E}/code`);p.has(y)&&m("NATIVE_WORKFLOW_PROVIDER_DUPLICATE",`${E}/code`),p.add(y),Ee(N.endpointPath,`${E}/endpointPath`),N.timeoutMs!==void 0&&se(N.timeoutMs,`${E}/timeoutMs`,100,1e4)});for(let[g,I]of c.entries())for(let[E,N]of Object.entries(O(I.bindings,"/config/workflows/bindings/*/binding/bindings"))){let y=O(N,`/config/workflows/${g}/bindings/${E}`);y.provider==="application_provider"&&!p.has(y.providerCode)&&m("NATIVE_WORKFLOW_PROVIDER_REFERENCE_MISSING",`/config/workflows/${g}/bindings/${E}/providerCode`)}let d=new Set(e.authz.roles.map(g=>g.code)),u=new Set;e.workflows.editableParameters.forEach((g,I)=>{let E=`/config/workflows/editableParameters/${I}`,N=O(g,E);R(N,["code","workflowCode","bindingKey","label","valueType","required","allowedRoleCodes","allowedProviderCodes","maxItems"],E,!0);let y=P(N.code,`${E}/code`);u.has(y)&&m("NATIVE_WORKFLOW_EDITABLE_PARAMETER_DUPLICATE",`${E}/code`),u.add(y);let _=on(N.workflowCode,`${E}/workflowCode`),A=Zt(N.bindingKey,`${E}/bindingKey`),T=c.get(_);(!T||!O(T.bindings,`${E}/bindingKey`)[A])&&m("NATIVE_WORKFLOW_EDITABLE_BINDING_MISSING",`${E}/bindingKey`),S(N.label,`${E}/label`,255),["role_code","user_ids","provider_code"].includes(N.valueType)||m("NATIVE_WORKFLOW_EDITABLE_VALUE_TYPE_INVALID",`${E}/valueType`);for(let f of F(N.allowedRoleCodes||[],`${E}/allowedRoleCodes`,100))d.has(f)||m("NATIVE_ROLE_REFERENCE_MISSING",`${E}/allowedRoleCodes`);for(let f of F(N.allowedProviderCodes||[],`${E}/allowedProviderCodes`,100))p.has(f)||m("NATIVE_WORKFLOW_PROVIDER_REFERENCE_MISSING",`${E}/allowedProviderCodes`);N.required!==void 0&&tt(N.required,`${E}/required`),N.maxItems!==void 0&&se(N.maxItems,`${E}/maxItems`,1,200)})}function za(e,t,o){let n=O(e,o);R(n,["resourceCode","factProjection"],o,["summaryFields"]);let i=G(n.resourceCode,`${o}/resourceCode`),s=t.get(i);s||m("NATIVE_WORKFLOW_SUBJECT_RESOURCE_MISSING",`${o}/resourceCode`);let a=new Set(w(O(s.schema,`${o}/resourceCode`).fields,`${o}/resourceCode`,500).map((l,p)=>K(O(l,`${o}/resourceCode/${p}`).code,`${o}/resourceCode/${p}`))),r=O(n.factProjection,`${o}/factProjection`),c=Object.entries(r);(c.length<1||c.length>64)&&m("NATIVE_WORKFLOW_SUBJECT_FACT_PROJECTION_INVALID",`${o}/factProjection`);for(let[l,p]of c){Hr.test(l)||m("NATIVE_WORKFLOW_SUBJECT_FACT_KEY_INVALID",`${o}/factProjection/${l}`);let d=K(p,`${o}/factProjection/${l}`);a.has(d)||m("NATIVE_WORKFLOW_SUBJECT_FIELD_MISSING",`${o}/factProjection/${l}`)}if(n.summaryFields!==void 0){let l=F(n.summaryFields,`${o}/summaryFields`,Yr).map((I,E)=>K(I,`${o}/summaryFields/${E}`)),p=t.get(i),d=p.surface&&typeof p.surface=="object"&&!Array.isArray(p.surface)?p.surface:{},u=d.fields&&typeof d.fields=="object"&&!Array.isArray(d.fields)?d.fields:{},g=new Map(w(O(p.schema,`${o}/resourceCode`).fields,`${o}/resourceCode`,500).map((I,E)=>{let N=O(I,`${o}/resourceCode/${E}`);return[String(N.code),N]}));for(let[I,E]of l.entries()){let N=g.get(E),y=u[E],_=String(N?.type||""),A=N?.maxLength;(!N||N.system===!0||y&&typeof y=="object"&&!Array.isArray(y)&&y.system===!0||["id","revision","created_by","updated_by","created_at","updated_at"].includes(E)||!Qr.has(_)||_==="text.long"&&typeof A=="number"&&Number.isFinite(A)&&A>Xr)&&m("NATIVE_WORKFLOW_SUBJECT_SUMMARY_FIELDS_INVALID",`${o}/summaryFields/${I}`)}}}function Ha(e,t){R(e,["schemaVersion","code","title","subject","acceptedCommandDeactivationPolicy","startAt","inputSchema","nodes"],t,["organizationContext","instanceCommands","readability","taskPages","rejectionNotification","commandHandlers","launchPreflight"]),x(e.schemaVersion,"openxiangda.workflow-definition/v2",`${t}/schemaVersion`),on(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=O(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),s=fi(e);s.length&&m(s[0],`${t}/readability`);let a=Mn(e);a.length&&m(a[0],`${t}/nodes`);let r=Kn(e);r.length&&m(r[0],`${t}/nodes`);let c=ft(e);c.length&&m(c[0],`${t}/nodes`);let l=Ai(e);l.length&&m(l[0],`${t}/rejectionNotification`);let p=Bn(e);p.length&&m(p[0],`${t}/nodes`);let d=zt(e);d.length&&m(d[0],`${t}/taskPages`);let u=Bt(e);u.length&&m(u[0],`${t}/nodes`),o[i]||m("NATIVE_WORKFLOW_START_NODE_MISSING",`${t}/startAt`);let g=new Map;for(let[y,_]of Object.entries(o)){let A=`${t}/nodes/${y}`,T=O(_,A);x(T.id,y,`${A}/id`),["approval","condition","end","cc","action"].includes(T.kind)||m("NATIVE_WORKFLOW_NODE_KIND_INVALID",`${A}/kind`);let f=[];if(T.kind==="approval"){S(T.title,`${A}/title`,255),Zt(T.binding,`${A}/binding`),["single","any","all","sequence"].includes(T.mode)||m("NATIVE_WORKFLOW_APPROVAL_MODE_INVALID",`${A}/mode`),f.push(S(T.onApprove,`${A}/onApprove`,128),S(T.onReject,`${A}/onReject`,128));for(let b of F(T.returnTargets||[],`${A}/returnTargets`,200))o[b]||m("NATIVE_WORKFLOW_TARGET_MISSING",`${A}/returnTargets`);for(let b of F(T.allowedOperations||[],`${A}/allowedOperations`,20))ea.has(b)||m("NATIVE_WORKFLOW_OPERATION_INVALID",`${A}/allowedOperations`)}else if(T.kind==="action")f.push(S(T.next,`${A}/next`,128));else if(T.kind==="cc")S(T.title,`${A}/title`,255),Zt(T.binding,`${A}/binding`),f.push(S(T.next,`${A}/next`,128));else if(T.kind==="condition"){let b=w(T.branches,`${A}/branches`,100);b.length===0&&m("NATIVE_WORKFLOW_BRANCH_REQUIRED",`${A}/branches`),b.forEach((h,C)=>{let $=O(h,`${A}/branches/${C}`);bt($.when,`${A}/branches/${C}/when`,0),f.push(S($.target,`${A}/branches/${C}/target`,128))}),f.push(S(T.otherwise,`${A}/otherwise`,128))}else S(T.title,`${A}/title`,255),S(T.outcome,`${A}/outcome`,128);for(let b of f)o[b]||m("NATIVE_WORKFLOW_TARGET_MISSING",A);g.set(y,f)}let I=new Set,E=new Set,N=y=>{if(E.has(y)&&m("NATIVE_WORKFLOW_CYCLE_FORBIDDEN",`${t}/nodes/${y}`),!I.has(y)){I.add(y),E.add(y);for(let _ of g.get(y)||[])N(_);E.delete(y)}};N(i),I.size!==n.length&&m("NATIVE_WORKFLOW_NODE_UNREACHABLE",`${t}/nodes`)}function bt(e,t,o){o>20&&m("NATIVE_WORKFLOW_EXPRESSION_DEPTH_EXCEEDED",t);let n=O(e,t),i=S(n.op,`${t}/op`,16);if(i!=="literal"){if(i==="path"){let s=S(n.path,`${t}/path`,255);(!/^[A-Za-z][A-Za-z0-9_.-]{0,254}$/.test(s)||s.split(".").some(a=>["__proto__","constructor","prototype"].includes(a)))&&m("NATIVE_WORKFLOW_EXPRESSION_PATH_INVALID",`${t}/path`);return}if(["eq","neq","gt","gte","lt","lte","in","contains"].includes(i)){bt(n.left,`${t}/left`,o+1),bt(n.right,`${t}/right`,o+1);return}if(["and","or"].includes(i)){let s=w(n.values,`${t}/values`,100);s.length===0&&m("NATIVE_WORKFLOW_EXPRESSION_EMPTY",`${t}/values`),s.forEach((a,r)=>bt(a,`${t}/values/${r}`,o+1));return}if(["not","exists"].includes(i)){bt(n.value,`${t}/value`,o+1);return}m("NATIVE_WORKFLOW_EXPRESSION_OPERATOR_INVALID",`${t}/op`)}}function Ya(e,t){x(e.schemaVersion,"openxiangda.workflow-binding/v2",`${t}/schemaVersion`),on(e.workflowCode,`${t}/workflowCode`);let o=O(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)){Zt(n,`${t}/bindings/${n}`);let s=O(i,`${t}/bindings/${n}`),a=S(s.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(s.users)||m("NATIVE_WORKFLOW_BINDING_USERS_REQUIRED",`${t}/bindings/${n}/users`),w(s.users,`${t}/bindings/${n}/users`,200)),["input_users","form_field_users"].includes(a)&&S(s.inputPath,`${t}/bindings/${n}/inputPath`,255),["app_role","app_role_in_scope","initiator_select"].includes(a)&&P(s.roleCode,`${t}/bindings/${n}/roleCode`),a==="department_supervisor"&&S(s.departmentIdFrom,`${t}/bindings/${n}/departmentIdFrom`,255),a==="application_provider"&&P(s.providerCode,`${t}/bindings/${n}/providerCode`),s.routing!==void 0){let r=Ht(s.routing);r.length&&m(r[0],`${t}/bindings/${n}/routing`)}}}function Xa(e,t,o){x(t.workflowCode,e.code,`${o}/workflowCode`);let n=O(t.bindings,`${o}/bindings`);for(let[r,c]of Object.entries(n))c.provider==="fixed_users"&&!c.users.length&&!_i(e,r)&&m("NATIVE_WORKFLOW_BINDING_USERS_REQUIRED",`${o}/bindings/${r}/users`);let i=Kn(e,t);i.length&&m(i[0],o);let s=Bn(e,t);s.length&&m(s[0],o);let a=Bt(e,t);a.length&&m(a[0],o);for(let[r,c]of Object.entries(O(e.nodes,`${o}/nodes`))){let l=O(c,`${o}/nodes/${r}`);["approval","cc"].includes(l.kind)&&!n[l.binding]&&m("NATIVE_WORKFLOW_BINDING_REFERENCE_MISSING",`${o}/nodes/${r}/binding`)}}function Qa(e,t,o){let n=O(t.routeManifest,"/contracts/routeManifest"),i=O(e.routeManifest,"/contracts/routeManifest"),s=new Map;for(let p of w(o.data?.resources,"/config/data/resources",100)){let d=O(p,"/config/data/resources");s.set(String(d.code||""),d)}let a=new Set(w(i.routes,"/contracts/routeManifest/routes",1e3).map(p=>String(O(p,"/contracts/routeManifest/routes").code||""))),r=[];for(let p of w(n.routes,"/contracts/routeManifest/routes",1e3)){let d=O(p,"/contracts/routeManifest/routes"),u=String(d.kind||"");if(u!=="resource-records"&&u!=="resource-submit")continue;let g=String(d.resourceCode||""),I=s.get(g);I||m("NATIVE_ROUTE_MANIFEST_RESOURCE_UNKNOWN","/contracts/routeManifest/routes");let N=`user.${g}.${u==="resource-records"?"records":"submit"}`;x(String(d.code||""),N,"/contracts/routeManifest/routes/code");let y=u==="resource-records"?"read":"create",_=String(O(I.capabilities,"/config/data/resources/capabilities")[y]||"");for(let A of["desktop","mobile"]){let T=O(d[A],`/contracts/routeManifest/routes/${A}`),f=A==="mobile"?"/m/my/":"/my/",b=u==="resource-records"?`${f}${g}`:`${f}${g}/submit`;x(String(T.path||""),b,`/contracts/routeManifest/routes/${A}/path`),x(String(T.capability||""),_,`/contracts/routeManifest/routes/${A}/capability`),x(String(T.routeCode||""),`${N}.${A}`,`/contracts/routeManifest/routes/${A}/routeCode`)}(a.has(N)||r.some(A=>String(A.code)===N))&&m("NATIVE_ROUTE_MANIFEST_DUPLICATE","/contracts/routeManifest/routes/code"),r.push(d)}if(!r.length)return;i.routes=w([...i.routes,...r],"/contracts/routeManifest/routes",1e3).sort((p,d)=>me(String(O(p,"x").code||""),String(O(d,"x").code||"")));let c=String(O(n.rootEntry,"x").code||"");if(r.find(p=>String(p.code)===c&&p.kind==="resource-records")){let p=O(n.rootEntry,"x");i.rootEntry={code:c,desktop:String(p.desktop||""),mobile:String(p.mobile||"")}}i.digest=Q({schemaVersion:i.schemaVersion,appCode:i.appCode,devicePolicy:i.devicePolicy,rootEntry:i.rootEntry,authentication:i.authentication,routes:i.routes})}function Me(e,t,o){let n=O(e,t);R(n,["schemaVersion","appCode","code","name","schema","surface","invariants","decimalReservationLifecycle","uniqueKeys","workflowHistory","recordPrint","recordComments","recordDeletion","capabilities","dataPolicyCode","fieldPolicies"],t,!0),x(n.schemaVersion,"openxiangda.data-resource/v2",`${t}/schemaVersion`),x(n.appCode,o,`${t}/appCode`);let i=G(n.code,`${t}/code`),s=S(n.name,`${t}/name`,255),a=O(n.schema,`${t}/schema`);R(a,["fields"],`${t}/schema`);let r,c,l,p;try{l=Sn(n.decimalReservationLifecycle,`${t}/decimalReservationLifecycle`),r=mn(a.fields,`${t}/schema/fields`),p=Yo(n.uniqueKeys,r,`${t}/uniqueKeys`),c=ho(n.invariants,r,`${t}/invariants`),On(n.surface,r,`${t}/surface`)}catch(I){throw(I instanceof ye||I instanceof Le||I instanceof He||I instanceof lt)&&m(I.code,I.pointer),I}if(n.recordComments!==void 0){let I=O(n.recordComments,`${t}/recordComments`);R(I,["read","create"],`${t}/recordComments`);for(let E of["read","create"]){let N=I[E];(!Array.isArray(N)||N.length>20||N.some(y=>typeof y!="string"||!y.trim())||new Set(N).size!==N.length)&&m("NATIVE_RECORD_COMMENTS_POLICY_INVALID",`${t}/recordComments/${E}`)}}if(n.recordDeletion!==void 0){let I=O(n.recordDeletion,`${t}/recordDeletion`);R(I,["delete"],`${t}/recordDeletion`);let E=I.delete;(!Array.isArray(E)||E.length>20||E.some(N=>typeof N!="string"||!N.trim())||new Set(E).size!==E.length)&&m("NATIVE_RECORD_DELETION_DELETE_INVALID",`${t}/recordDeletion/delete`)}if(n.recordPrint!==void 0){let I=O(n.recordPrint,`${t}/recordPrint`);R(I,["read"],`${t}/recordPrint`);let E=I.read;(!Array.isArray(E)||E.length>20||E.some(N=>typeof N!="string"||!N.trim())||new Set(E).size!==E.length)&&m("NATIVE_RECORD_PRINT_READ_INVALID",`${t}/recordPrint/read`)}if(n.workflowHistory!==void 0){let I=O(n.workflowHistory,`${t}/workflowHistory`);R(I,["read"],`${t}/workflowHistory`);let E=I.read;(!Array.isArray(E)||E.length>20||E.some(N=>typeof N!="string"||!N.trim())||new Set(E).size!==E.length)&&m("NATIVE_WORKFLOW_HISTORY_READ_INVALID",`${t}/workflowHistory/read`)}let d=new Set(r.map(I=>I.code)),u=O(n.capabilities,`${t}/capabilities`);R(u,["read","create","update","delete"],`${t}/capabilities`);let g=O(n.fieldPolicies,`${t}/fieldPolicies`);for(let[I,E]of Object.entries(g)){!d.has(I)&&!ot(I)&&m("NATIVE_DATA_FIELD_POLICY_FIELD_MISSING",`${t}/fieldPolicies/${I}`);let N=`${t}/fieldPolicies/${I}`,y=O(E,N);ot(I)&&(R(y,["read"],N,!0),(!Array.isArray(y.read)||y.read.length>20||y.read.some(_=>typeof _!="string"||!_.trim())||new Set(y.read).size!==y.read.length)&&m("NATIVE_DATA_AUDIT_READ_POLICY_INVALID",`${N}/read`)),R(y,["read","create","update","mask"],N,!0),y.mask!==void 0&&!["omit","null"].includes(y.mask)&&m("NATIVE_DATA_FIELD_POLICY_MASK_INVALID",`${N}/mask`)}return{...n,code:i,name:s,schema:{fields:r},...n.invariants===void 0?{}:{invariants:c},...l?{decimalReservationLifecycle:l}:{},...p!==void 0?{uniqueKeys:p}:{},capabilities:u,fieldPolicies:g}}function cs(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 Ki(e,t,o,n){let i=e.toString("utf8"),s;try{s=JSON.parse(i)}catch{m(o,t)}let a=O(s,t);return ne(a)!==i&&m(n,t),a}function qi(e,t){let o=0,n=(i,s,a)=>{if(o+=1,o>ia&&m("NATIVE_ARTIFACT_NODE_LIMIT_EXCEEDED",s),a>oa&&m("NATIVE_ARTIFACT_DEPTH_LIMIT_EXCEEDED",s),typeof i=="string"){Buffer.byteLength(i)>Qn&&m("NATIVE_ARTIFACT_STRING_LIMIT_EXCEEDED",s);return}if(Array.isArray(i)){i.forEach((r,c)=>n(r,`${s}/${c}`,a+1));return}if(!(!i||typeof i!="object"))for(let[r,c]of Object.entries(i))["__proto__","prototype","constructor"].includes(r)&&m("NATIVE_ARTIFACT_DANGEROUS_KEY",`${s}/${r}`),Za(r)&&m("NATIVE_ARTIFACT_RUNTIME_FIELD_FORBIDDEN",`${s}/${r}`),n(c,`${s}/${r}`,a+1)};n(e,t,0)}function Za(e){return["environmentKey","environmentId","secretValue","ciphertext","oauthClient","oauthClientId","oauthClientSecret","signingSecret","kubernetesNamespace","nodePort","productionUrl"].includes(e)}function Ze(e){return{value:e,digest:Q(e)}}function Ji(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 Gi(e,t,o,n){let i=en.createHash("sha256").update(e).digest("hex");en.timingSafeEqual(Buffer.from(i),Buffer.from(t))||m(n,o)}function O(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&m("NATIVE_OBJECT_REQUIRED",t),e}function w(e,t,o){return Array.isArray(e)||m("NATIVE_ARRAY_REQUIRED",t),e.length>o&&m("NATIVE_ARRAY_LIMIT_EXCEEDED",t),e}function F(e,t,o){let n=w(e,t,o).map((i,s)=>S(i,`${t}/${s}`,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 ao(e,t,o){return(typeof e!="string"||e.length>o)&&m("NATIVE_STRING_INVALID",t),e}function P(e,t){let o=S(e,t,128);return Ur.test(o)||m("NATIVE_CODE_INVALID",t),o}function G(e,t){let o=S(e,t,64);return Br.test(o)||m("NATIVE_RESOURCE_CODE_INVALID",t),o}function K(e,t){let o=S(e,t,63);return Kr.test(o)||m("NATIVE_FIELD_CODE_INVALID",t),o}function on(e,t){let o=S(e,t,128);return Gr.test(o)||m("NATIVE_WORKFLOW_CODE_INVALID",t),o}function Zt(e,t){let o=S(e,t,128);return zr.test(o)||m("NATIVE_WORKFLOW_BINDING_CODE_INVALID",t),o}function fe(e,t,o){let n=S(e,t,255);return Wr.test(n)||m("NATIVE_CAPABILITY_CODE_INVALID",t),!n.startsWith(`app:${o}:`)&&!cs(o).some(i=>i.code===n)&&m("NATIVE_CAPABILITY_APP_MISMATCH",t),n}function Ee(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 et(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 tt(e,t){return typeof e!="boolean"&&m("NATIVE_BOOLEAN_REQUIRED",t),e}function oo(e,t){let o=S(e,t,64).toLowerCase();return xr.test(o)||m("NATIVE_DIGEST_INVALID",t),o}function x(e,t,o){e!==t&&m("NATIVE_VALUE_MISMATCH",o)}function R(e,t,o,n=!1){let i=new Set([...t,...Array.isArray(n)?n:[]]);for(let s of Object.keys(e))i.has(s)||m("NATIVE_PROPERTY_UNKNOWN",`${o}/${s}`);if(n!==!0)for(let s of t)Object.prototype.hasOwnProperty.call(e,s)||m("NATIVE_PROPERTY_REQUIRED",`${o}/${s}`)}function ee(e,t){return[...e].sort((o,n)=>me(t(o),t(n)))}function M(e){return[...new Set(e)].sort(me)}function zi(e){return[...new Set(e)].sort((t,o)=>t-o)}function me(e,t){return e===t?0:e<t?-1:1}function ds(e){return!e||typeof e!="object"||Object.isFrozen(e)||(Object.freeze(e),Object.values(e).forEach(t=>ds(t))),e}function io(e,t,o){if(Xn(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(!Xn(e[i],t[i]))return io(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 s=e[i],a=t[i];if(!Xn(s,a))return io(s,a,`${o}/${i}`)}}return o}function Xn(e,t){return e===void 0||t===void 0?e===t:ne(e)===ne(t)}function m(e,t,o={}){throw new to(e,t,o)}var Vl=50,Pl=131072,co=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 Fl(e){let t=d=>{throw new co(d)},o=(d,u)=>((!d||typeof d!="object"||Array.isArray(d))&&t(u),d),n=(d,u,g)=>{for(let I of Object.keys(d))u.includes(I)||t(`${g}/${I}`)},i=(d,u,g)=>((typeof d!="string"||!d.trim()||d.length>u)&&t(g),d),s=(d,u)=>{let g=i(d,36,u);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(g)||t(u),g.toLowerCase()},a=o(e,""),r;try{r=new TextEncoder().encode(JSON.stringify(a)).byteLength}catch{t("")}r>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 c=new Set,l=new Set,p;for(let[d,u]of a.items.entries()){let g=`/items/${d}`,I=o(u,g);["create","update","revoke"].includes(String(I.operation))||t(`${g}/operation`),p??=I.operation,p!==I.operation&&t(`${g}/operation`),n(I,["operation","operationId","reason",...p==="create"?["userId","roleCode"]:["membershipId","expectedRevision"],...p!=="revoke"?["scopeGrants","validFrom","validTo"]:[]],g);let E=s(I.operationId,`${g}/operationId`);c.has(E)&&t(`${g}/operationId`),c.add(E),i(I.reason,1e3,`${g}/reason`);let N;if(p==="create"){let y=i(I.userId,255,`${g}/userId`),_=i(I.roleCode,128,`${g}/roleCode`);/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/.test(_)||t(`${g}/roleCode`),N=JSON.stringify([y,_])}else N=s(I.membershipId,`${g}/membershipId`),(!Number.isSafeInteger(I.expectedRevision)||Number(I.expectedRevision)<1)&&t(`${g}/expectedRevision`);l.has(N)&&t(g),l.add(N),I.scopeGrants!==void 0&&(!Array.isArray(I.scopeGrants)||I.scopeGrants.length>100)&&t(`${g}/scopeGrants`);for(let y of["validFrom","validTo"])I[y]!==void 0&&I[y]!==null&&i(I[y],64,`${g}/${y}`)}}var ps="openxiangda.workflow-delegation-administration/v2",ms="openxiangda.workflow-delegation-mutation/v2",ls="openxiangda.workflow-delegation-preview/v2";var Ot={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},Be={type:"string",format:"date-time"},nt={type:"integer",minimum:1},ec={anyOf:[Be,{type:"null"}]},lo={anyOf:[_e,{type:"null"}]},sn={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}$"},_s={const:"future-assignments-only"},uo={schemaVersion:{const:ps},id:Ot,appCode:_e,environmentKey:_e,workflowCode:lo,delegatorUserId:_e,delegateUserId:_e,delegatorRoleSubjectKey:sn,delegateRoleSubjectKey:sn,validFrom:Be,validTo:Be,status:{enum:["active","revoked","expired"]},reason:{type:"string",minLength:1,maxLength:4e3},createdBy:_e,createdAt:Be,revokedAt:ec,revision:nt,roleCode:_e,roleName:_e,delegatorDisplayName:_e,delegateDisplayName:_e,delegatorRoleSubjectRevision:nt,delegateRoleSubjectRevision:nt,effectiveState:{enum:["active","scheduled","expired","revoked","ineligible"]},evaluatedAt:Be,issues:{type:"array",maxItems:20,uniqueItems:!0,items:_e},canRevoke:{type:"boolean"},revokedBy:lo,revokeReason:{type:["string","null"],maxLength:4e3},taskPolicy:_s},fo={type:"object",additionalProperties:!1,required:Object.keys(uo),properties:uo},Ll={$id:ps,...fo},gs={schemaVersion:{const:ms},operationId:Ot,environmentKey:{enum:["preproduction","production"]},reason:{type:"string",minLength:1,maxLength:2e3,pattern:"\\S"}},us={...gs,operation:{const:"create"},workflowCode:lo,delegatorRoleSubjectKey:sn,expectedDelegatorRevision:nt,delegateUserId:_e,delegateRoleSubjectKey:sn,expectedDelegateRevision:nt,validFrom:Be,validTo:Be},fs={...gs,operation:{const:"revoke"},delegationId:Ot,expectedRevision:nt},tc={$id:ms,type:"object",oneOf:[{type:"object",additionalProperties:!1,required:Object.keys(us),properties:us},{type:"object",additionalProperties:!1,required:Object.keys(fs),properties:fs}]},nc={type:"string",pattern:"^[0-9a-f]{64}$"},xl={$id:ls,type:"object",additionalProperties:!1,required:["schemaVersion","operationId","operation","requestDigest","before","after","taskPolicy"],properties:{schemaVersion:{const:ls},operationId:Ot,operation:{enum:["create","revoke"]},requestDigest:nc,before:{anyOf:[fo,{type:"null"}]},after:{...fo,properties:{...uo,id:{anyOf:[Ot,{type:"null"}]}}},taskPolicy:_s}};function Ul(e){return e===void 0?"":`
9
+ ${Q(e)}`}function Ml(e,t){let o=e.handlers.find(n=>n.code===t);return Q(o?.workflowStep?o:e)}var Kl="openxiangda.data-business-command/v1",oc="openxiangda.data-business-command-resolution/v1",ql=65536;function Jl(e){let t=0,o=0,n=new Set,i=new TextEncoder,s=()=>{throw new Error("OPENXIANGDA_DATA_COMMAND_INTENT_INVALID")},a=c=>(o+=i.encode(c).byteLength,o>65536&&s(),c),r=(c,l)=>{if(++t>1e4||l>32)return s();if(c===null||typeof c=="string"||typeof c=="boolean")return a(JSON.stringify(c));if(typeof c=="number")return Number.isFinite(c)?a(JSON.stringify(c)):s();if(!c||typeof c!="object"||n.has(c)||Object.getOwnPropertySymbols(c).length)return s();n.add(c);let p;if(Array.isArray(c))return Object.keys(c).length!==c.length?s():(p=a("[")+c.map((u,g)=>(g?a(","):"")+r(u,l+1)).join("")+a("]"),n.delete(c),p);let d=Object.getPrototypeOf(c);return d!==Object.prototype&&d!==null?s():(p=a("{")+Object.keys(c).sort().map((u,g)=>(g?a(","):"")+a(JSON.stringify(u))+a(":")+r(c[u],l+1)).join("")+a("}"),n.delete(c),p)};return!e||typeof e!="object"||Array.isArray(e)?s():r(e,0)}function Gl(e,t,o=!1){let n=e,i=()=>{throw new Error("OPENXIANGDA_DATA_COMMAND_RESPONSE_INVALID")};if(!n||typeof n!="object"||n.schemaVersion!==oc)return i();for(let c of["appCode","environmentKey","operationCode","idempotencyKey","intentDigest"])if(n[c]!==t[c])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 s=n.receipt,a=c=>typeof c=="string"&&/^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(c);if(!a(s.id)||!a(s.appVersionId)||!Number.isSafeInteger(s.environmentHeadRevision)||s.environmentHeadRevision<1||typeof s.completedAt!="string"||!Number.isFinite(Date.parse(s.completedAt)))return i();let r=s.transaction;if(!r||r.schemaVersion!=="openxiangda.data-transaction-result/v2"||r.idempotencyKey!==t.idempotencyKey||typeof r.replayed!="boolean"||!Array.isArray(r.items)||!r.items.length||r.items.length>1e3)return i();for(let[c,l]of r.items.entries()){if(!l||l.index!==c)return i();if(l.operation==="emitEvent"){if(!a(l.eventId)||typeof l.eventType!="string"||!l.eventType)return i()}else if(!["create","update","delete","increment"].includes(l.operation)||!a(l.id)||typeof l.resourceCode!="string"||!l.resourceCode||!Number.isSafeInteger(l.revision)||l.revision<1)return i()}return n}function ic(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(r=>[r,a.title]))),{views:i,...s}=e;return{...s,generated:o.generated,list:o.list,form:o.form,detail:o.detail,mobile:o.mobile,fields:Object.fromEntries(Object.entries(e.fields).map(([a,r])=>{let{section:c,...l}=r,p=n.get(a);return[a,{...l,...p?{section:p}:{},list:o.list.fieldOrder?.includes(a)??!1}]}))}}var Yl="4ac94b73641338f07a5a6c7ff5009ba37f9f7a005031a24c0ae740d0b54bfa59";export{Ro as DATA_AUDIT_METADATA_FIELDS,ql as DATA_BUSINESS_COMMAND_INTENT_MAX_BYTES,oc as DATA_BUSINESS_COMMAND_RESOLUTION_SCHEMA,Kl as DATA_BUSINESS_COMMAND_SCHEMA,Zn as DATA_EVENT_TYPES_V2,fc as DATA_FORM_DRAFT_MAX_BYTES,Rt as DATA_SUBTABLE_MAX_ROWS,Ct as DATA_SUBTABLE_MAX_TOTAL_ROWS,ks as DATA_SYSTEM_SORT_FIELD_CODES,uc as DATA_TRANSACTION_MAX_BYTES,lc as DATA_TRANSACTION_MAX_OPERATIONS,rt as ManagedConcurrencyContractError,Yl as NATIVE_CONFIGURATION_VALIDATOR_DIGEST,X as NATIVE_CONTRACT_CAPACITY_V2,Zd as NATIVE_DATA_POLICY_EXPRESSION_MAX_CLAUSES,Yd as NATIVE_DATA_POLICY_EXPRESSION_MAX_DEPTH,Xd as NATIVE_DATA_POLICY_EXPRESSION_MAX_GROUP_ITEMS,Qd as NATIVE_DATA_POLICY_EXPRESSION_MAX_LEAVES,el as NATIVE_DATA_POLICY_EXPRESSION_MAX_OCCURRENCES,Vs as NATIVE_DATA_QUERY_OPERATORS_V2,Pl as NATIVE_ROLE_MEMBERSHIP_BATCH_MAX_BYTES,Vl as NATIVE_ROLE_MEMBERSHIP_BATCH_MAX_ITEMS,nd as NATIVE_UNIQUE_KEY_MAX_BYTES,Ho as NATIVE_UNIQUE_KEY_NORMALIZERS,to as NativeConfigurationCompilerError,ye as NativeDataFieldContractV2Error,yt as NativeDataPolicyExpressionV2Error,He as NativeDecimalLifecycleContractError,Vn as NativeEventActionContractError,co as NativeRoleMembershipBatchInputError,Dn as NativeScopeSourceFieldPathV2Error,lt as NativeUniqueKeyContractError,bs as OPENXIANGDA_NATIVE_DATA_FIELD_TYPES_V2,De as OPENXIANGDA_NATIVE_DATA_SURFACE_KEYS_V2,yn as OPENXIANGDA_NATIVE_DRAFT_STATE_KEYS_V2,pn as OPENXIANGDA_NATIVE_SYSTEM_FIELDS_V2,Oo as OPENXIANGDA_NATIVE_SYSTEM_FIELD_MAP_V2,ac as USER_CANDIDATE_MAX_SELECTIONS,Is as USER_CANDIDATE_SCOPE_FIELD_TYPES,Le as UserCandidateContractError,mi as WORKFLOW_APPROVAL_EMPTY_PROVIDERS,hd as WORKFLOW_AUTOMATIC_CC_MAX_RECIPIENTS,hr as WORKFLOW_AUTOMATIC_CC_PROVIDERS,ut as WORKFLOW_BUSINESS_STEP_EVENT,ri as WORKFLOW_BUSINESS_STEP_EVENTS,fd as WORKFLOW_BUSINESS_STEP_FACTS_KEY,vn as WORKFLOW_BUSINESS_STEP_MAX_BYTES,Er as WORKFLOW_BUSINESS_STEP_MAX_RECEIPT_BYTES,Wn as WORKFLOW_CONFIGURABLE_OPERATIONS,Un as WORKFLOW_CONFIGURABLE_PROVIDERS,eo as WORKFLOW_EVENT_TYPES_V2,Cr as WORKFLOW_LAUNCH_PREFLIGHT_PROVIDERS,wd as WORKFLOW_REJECTION_NOTIFICATION_MAX_BYTES,Rr as WORKFLOW_REJECTION_NOTIFICATION_SCHEMA,Bd as WORKFLOW_ROUTING_MAX_BYTES,Md as WORKFLOW_ROUTING_MAX_MATCHED_RULES,Ud as WORKFLOW_ROUTING_MAX_RULES,Dr as WORKFLOW_TASK_PAGE_DEFINITION_MAX_BYTES,zn as WORKFLOW_TASK_PAGE_MAX_BYTES,wr as WORKFLOW_TASK_PAGE_MAX_FIELDS,yi as WORKFLOW_TASK_SUBTABLE_MAX_ROWS,$r as WORKFLOW_TASK_SUBTABLE_MAX_TOTAL_ROWS,Oe as WorkflowTaskPageError,kr as applyWorkflowTaskPageValues,Ld as applyWorkflowTaskSubtableRows,Fl as assertNativeRoleMembershipBatchInput,Jl as canonicalDataBusinessIntent,$l as compileNativeApplicationConfiguration,ti as compileNativeEventAction,ca as compileNativeEventCapturePlansV2,aa as compileRequiredPlatformCapabilitiesV3,xn as compileWorkflowBusinessStepHandlers,Pe as evaluateWorkflowTaskPageExpression,Kt as formatWorkflowExpression,Co as hasDataAuditReadPolicy,ot as isDataAuditMetadataField,So as isDataSystemSortField,yc as isNativeDataQueryOperatorV2,Dt as isNativeMultiValueFieldV2,Dd as isWorkflowRejectionNotificationSnapshot,Zc as materializeNativeDataQueryPathTypesV2,Yt as nativeDataPolicyExpressionLeavesV2,Di as nativeDataPolicyExpressionToCnfV2,ed as nativeDataQueryPathPlanV2,Nc as nativeFieldAggregatePlanV2,Mc as nativeFieldColumnDefinitionV2,Bc as nativeFieldDefaultSqlV2,Kc as nativeFieldHasDefaultV2,zc as nativeFieldIndexStatementsV2,$t as nativeFieldRequiresCreateInputV2,Gc as nativeFieldSequenceGrantStatementsV2,Jc as nativeFieldSequenceOwnershipStatementsV2,qc as nativeFieldSequenceStatementsV2,ko as nativeFieldSupportsFilterV2,bc as nativeFieldSupportsOperatorV2,En as nativeFieldSupportsSearchV2,st as nativeFieldSupportsSortV2,$o as nativeOperatorsForFieldV2,tr as nativePhysicalFieldV2,Uc as nativePhysicalFieldsV2,$e as nativePhysicalObjectNameV2,Xc as nativeScopeSourceFieldValueV2,Go as nativeScopeSourceGrantPathSupportedV2,$n as nativeScopeSourceSubjectPathSupportedV2,Hc as nativeSubtableConstraintStatementsV2,Xo as nativeUniqueKeysContractVersion,od as nativeUniqueKeysJsonSchema,Gl as parseDataBusinessCommandResolution,ht as parseDataFieldUserCandidates,Sn as parseDecimalReservationLifecycle,mn as parseNativeDataFieldsV2,ho as parseNativeDataResourceInvariantsV2,Yo as parseNativeUniqueKeys,ic as projectDataResourceView,Tn as projectNativeDataResourceViewV2,Ed as projectWorkflowGraph,Tr as projectWorkflowNodePolicy,de as quoteNativeIdentifierV2,xd as refreshWorkflowTaskPageFacts,at as resolveNativeScopeSourceFieldPathV2,ys as resolveWorkflowUserCandidates,Gd as selectWorkflowAssignmentRoutingRules,pc as serializedDataBytes,cc as userCandidateScopeValue,Uo as validateDecimalReservationLifecycles,jo as validateManagedConcurrency,Fo as validateNativeDataDraftStateV2,To as validateNativeDataResourceReferencesV2,On as validateNativeDataResourceSurfaceV2,go as validateUserCandidateReferences,Mn as validateWorkflowAdministration,Kn as validateWorkflowApprovalEmptyPolicy,Ci as validateWorkflowAssignmentRoutingBindings,Ht as validateWorkflowAssignmentRoutingPolicy,qd as validateWorkflowAssignmentRoutingRules,Bn as validateWorkflowAutomaticCc,md as validateWorkflowBusinessStepHandlerContract,pd as validateWorkflowBusinessStepRequest,Ir as validateWorkflowBusinessStepResult,Ut as validateWorkflowBusinessStepSchema,li as validateWorkflowBusinessStepSubscriptions,Bt as validateWorkflowBusinessSteps,Ei as validateWorkflowCommandHandlers,ft as validateWorkflowInitiatorApprovalPolicy,oi as validateWorkflowInstanceCommandPolicies,Jn as validateWorkflowLaunchPreflight,Od as validateWorkflowNodeConfigurationPatch,fi as validateWorkflowReadability,Ai as validateWorkflowRejectionNotification,zt as validateWorkflowTaskPages,Ao as validateWorkflowUserCandidateBindings,Cd as workflowApprovalCanSkip,Jd as workflowAssignmentRoutingFacts,Kd as workflowAssignmentRoutingPolicySchema,vr as workflowAssignmentRoutingSemantic,_i as workflowBindingAllowsEmptyUsers,kd as workflowBusinessCommandInvocationSchema,Mt as workflowBusinessStepFactSchema,Ml as workflowBusinessStepHandlerDigest,_d as workflowBusinessStepInput,yr as workflowBusinessStepPath,Ul as workflowBusinessStepReceiptSignatureSuffix,Wt as workflowBusinessStepValueMatches,tc as workflowDelegationMutationRequestSchema,ui as workflowExpressionPaths,yd as workflowInitiatorApprovalCanComplete,ld as workflowInstanceCommandDeadlineError,cd as workflowInstanceTerminateCapabilityAllowed,dd as workflowInstanceWithdrawalReasonRequired,pt as workflowNodeAllowedOperations,Or as workflowOperationCommentRequired,ni as workflowPolicyTimestamp,Oi as workflowTaskPageFieldState,jd as workflowTaskPageReplayCoversInvalidation,vd as workflowTaskSubtableRows};