openxiangda-contracts 2.77.0 → 2.78.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.
@@ -1,9 +1,9 @@
1
- import{createHash as Vs}from"node:crypto";function Ls(e){if(!e||typeof e!="object")return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function wn(e,t){if(e===null)return"null";if(typeof e=="string"||typeof e=="boolean")return JSON.stringify(e);if(typeof e=="number"){if(!Number.isFinite(e))throw new TypeError(`JSON number must be finite: ${t}`);return JSON.stringify(e)}if(Array.isArray(e))return`[${e.map((n,i)=>wn(n,`${t}[${i}]`)).join(",")}]`;if(Ls(e))return`{${Object.keys(e).filter(i=>e[i]!==void 0).sort((i,r)=>i===r?0:i<r?-1:1).map(i=>`${JSON.stringify(i)}:${wn(e[i],`${t}.${i}`)}`).join(",")}}`;let o=e instanceof Date?"Date":e?.constructor?.name||typeof e;throw new TypeError(`Value is not JSON serializable: ${t} (${o})`)}function X(e){return wn(e,"$")}function Z(e){return Vs("sha256").update(X(e)).digest("hex")}var jc=200,Fs=["text.short","uuid","option.single","resource-ref.single"],Sn=/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/,ei=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,ti=new Set(["__proto__","prototype","constructor"]),Dn=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&[Object.prototype,null].includes(Object.getPrototypeOf(e)),Qo=(e,t)=>Object.keys(e).every(o=>t.includes(o)),et=(e,t)=>typeof e=="string"&&e.length>0&&e.trim()===e&&e.length<=t,Me=class extends Error{constructor(o,n){super(`${o}: ${n}`);this.code=o;this.pointer=n}code;pointer};function ne(e,t){throw new Me(e,t)}function xt(e,t,o){if(e===void 0)return;["user.single","user.multiple"].includes(t)||ne("DATA_USER_CANDIDATES_FIELD_TYPE_INVALID",o),(!Dn(e)||!Qo(e,["kind","roleCode","scope","pageSize"])||e.kind!=="app-role"||!et(e.roleCode,128)||!Sn.test(String(e.roleCode)))&&ne("DATA_USER_CANDIDATES_SOURCE_INVALID",o),e.pageSize!==void 0&&(!Number.isSafeInteger(e.pageSize)||Number(e.pageSize)<1||Number(e.pageSize)>50)&&ne("DATA_USER_CANDIDATES_PAGE_SIZE_INVALID",`${o}/pageSize`);let n;if(e.scope!==void 0){let i=e.scope;(!Dn(i)||!Qo(i,["dimensionCode","operation","field","value","creation"])||!et(i.dimensionCode,128)||!Sn.test(String(i.dimensionCode))||!et(i.operation,64)||!Sn.test(String(i.operation))||Object.hasOwn(i,"field")===Object.hasOwn(i,"value"))&&ne("DATA_USER_CANDIDATES_SCOPE_INVALID",`${o}/scope`),i.creation!==void 0&&(i.creation!=="prospective"||!Object.hasOwn(i,"field"))&&ne("DATA_USER_CANDIDATES_SCOPE_INVALID",`${o}/scope/creation`),Object.hasOwn(i,"field")?((!et(i.field,63)||!ei.test(String(i.field))||ti.has(String(i.field)))&&ne("DATA_USER_CANDIDATES_SCOPE_FIELD_INVALID",`${o}/scope/field`),n={dimensionCode:String(i.dimensionCode),operation:String(i.operation),field:String(i.field),...i.creation==="prospective"?{creation:"prospective"}:{}}):(et(i.value,255)||ne("DATA_USER_CANDIDATES_SCOPE_VALUE_INVALID",`${o}/scope/value`),n={dimensionCode:String(i.dimensionCode),operation:String(i.operation),value:String(i.value)})}return{kind:"app-role",roleCode:String(e.roleCode),...n?{scope:n}:{},...e.pageSize===void 0?{}:{pageSize:Number(e.pageSize)}}}function kn(e){return e.some(t=>t.schema.fields.some(o=>{let n=o.userCandidates?.scope;return n?.creation==="prospective"||!!(n?.field&&t.schema.fields.find(i=>i.code===n.field)?.type==="resource-ref.single")}))}function ni(e,t,o,n){for(let[i,r]of e.entries()){let d=`${n}/${i}/userCandidates`,s=xt(r.userCandidates,r.type,d);if(s&&(t.has(s.roleCode)||ne("DATA_USER_CANDIDATES_ROLE_UNDECLARED",`${d}/roleCode`),s.scope&&!o.has(s.scope.dimensionCode)&&ne("DATA_USER_CANDIDATES_DIMENSION_UNDECLARED",`${d}/scope/dimensionCode`),s.scope?.field)){let a=e.find(c=>c.code===s.scope.field);(!a||!Fs.some(c=>c===a.type))&&ne("DATA_USER_CANDIDATES_SCOPE_FIELD_INVALID",`${d}/scope/field`)}}}function xs(e,t,o,n){let i=e.subject.factProjection,r=typeof t.inputPath=="string"&&Object.entries(i).some(([c,f])=>(t.inputPath===c||t.inputPath.startsWith(`${c}.`))&&o.get(f)?.userCandidates!==void 0);if(t.candidateField===void 0&&!r)return;(t.provider!=="form_field_users"||!t.candidateField||!ei.test(t.candidateField)||ti.has(t.candidateField)||!t.inputPath||i[t.inputPath]!==t.candidateField)&&ne("WORKFLOW_USER_CANDIDATES_FIELD_BINDING_REQUIRED",n),(t.roleCode!==void 0||t.scope!==void 0||t.routing!==void 0)&&ne("WORKFLOW_USER_CANDIDATES_SOURCE_OVERRIDE_FORBIDDEN",n);let d=o.get(t.candidateField),s=d&&xt(d.userCandidates,d.type,`${n}/candidateField`);s||ne("WORKFLOW_USER_CANDIDATES_FIELD_UNDECLARED",`${n}/candidateField`);let a;if(s.scope?.field){let c=Object.entries(i).filter(([,f])=>f===s.scope.field).map(([f])=>f);c.length!==1&&ne("WORKFLOW_USER_CANDIDATES_SCOPE_PROJECTION_REQUIRED",n),a=c[0]}return{fieldCode:d.code,inputPath:t.inputPath,source:s,...a?{scopeInputPath:a}:{}}}function oi(e,t,o,n,i=new Map){for(let[r,d]of Object.entries(t.bindings))xs(e,d,o,`${n}/${r}`);for(let[r,d]of Object.entries(e.taskPages||{})){let s=new Set(d.fields.filter(a=>a.readonly!==!0).map(a=>a.code));for(let a of d.fields){let c=o.get(a.code)?.userCandidates?.scope;if(s.has(a.code)&&c?.field&&s.has(c.field)&&ne("WORKFLOW_USER_CANDIDATES_SCOPE_WRITE_FORBIDDEN",`${n}/taskPages/${r}/${a.code}`),!s.has(a.code)||!a.subtable)continue;let f=o.get(a.code)?.subtable?.resourceCode,u=f?i.get(f):void 0;a.subtable.fields.some(p=>p.readonly!==!0&&u?.get(p.code)?.userCandidates)&&ne("WORKFLOW_USER_CANDIDATES_OWNED_FIELD_UNSUPPORTED",`${n}/taskPages/${r}/${a.code}`)}}}function Wc(e,t){if(!e.scope)return;let o=e.scope.field?t[e.scope.field]:e.scope.value,n=Dn(o)?o.value:o;return et(n,255)||ne("DATA_USER_CANDIDATES_SCOPE_VALUE_REQUIRED",e.scope.field||"scope"),String(n)}var ii=200,Pn=205;function vn(e,t=[]){return e.some(o=>o.schema.fields.length>100)||t.some(o=>Object.values(o.definition.taskPages||{}).some(n=>(n.fields?.length??0)>64)||[o.launch?.submission?.create,o.launch?.submission?.existing].some(n=>Object.keys(n?.inputs||{}).length>64))}var Be=500,$n=500,tt=1e3,ri=2*tt+16,Mc=2*1024*1024,Bc=2*1024*1024;function mt(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=1&&e<=tt}function jt(e){if(e.ownedRowLimit===void 0)return $n;if(!mt(e.ownedRowLimit))throw new Error("NATIVE_DATA_OWNED_ROW_LIMIT_INVALID");return e.ownedRowLimit}function Vn(e){return e.some(t=>(t.schema.ownedRowLimit??$n)>$n)}function Ln(e){return e.some(t=>{let o=t.schema.fields.filter(n=>n.type==="subtable").map(n=>n.subtable?.maxRows??20);return o.some(n=>n>100)||o.reduce((n,i)=>n+i,0)>400})}function Kc(e){try{return new TextEncoder().encode(JSON.stringify(e)).byteLength}catch{return 1/0}}var ci=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,jn=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,js=["text.short","text.long","text.rich","number.integer","number.decimal","boolean","date","time","datetime","date-range","datetime-range","option.single","option.multiple","cascade.single","cascade.multiple","user.single","user.multiple","department.single","department.multiple","resource-ref.single","resource-ref.multiple","image","signature","address","location","uuid","json","file","serial-number","subtable"];function Wn(e){return e.some(t=>t.schema.fields.some(o=>(o.type==="datetime"||o.type==="datetime-range")&&o.timePrecision==="minute"))}function Un(e){return e.some(t=>t.schema.fields.some(o=>o.type==="subtable"&&(o.subtable?.minRows??0)>0))}var Ws=new Set(js),li=new Set(["option.multiple","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","file","image","subtable"]),si=new Set(["option.single","option.multiple","cascade.single","cascade.multiple"]),ai=new Set(["resource-ref.single","resource-ref.multiple"]),Mn=[{code:"id",type:"uuid",nullable:!1},{code:"revision",type:"number.integer",nullable:!1},{code:"created_by",type:"text.short",nullable:!1},{code:"updated_by",type:"text.short",nullable:!1},{code:"created_at",type:"datetime",nullable:!1},{code:"updated_at",type:"datetime",nullable:!1}],nt=new Map(Mn.map(e=>[e.code,e])),Re=class extends Error{constructor(o,n){super(o);this.code=o;this.pointer=n;this.name="NativeDataFieldContractV2Error"}code;pointer};function Mt(e){return li.has(e)}function Bt(e,t={}){return e.type!=="serial-number"&&t.system!==!0&&e.nullable===!1&&(!Mt(e.type)||t.requiredHint===!0)}function Bn(e,t,o=500){Array.isArray(e)||k("NATIVE_ARRAY_REQUIRED",t),e.length===0&&k("NATIVE_DATA_FIELDS_REQUIRED",t),e.length>o&&k("NATIVE_ARRAY_LIMIT_EXCEEDED",t);let n=new Set;return e.map((i,r)=>{let d=`${t}/${r}`,s=Ee(i,d);ye(s,["code","type","nullable","indexed","options","source","userCandidates","maxLength","precision","scale","exactDecimal","min","max","rangeBoundary","timePrecision","file","serial","subtable"],d);let a=be(s.code,`${d}/code`,63);ci.test(a)||k("NATIVE_FIELD_CODE_INVALID",`${d}/code`),n.has(a)&&k("NATIVE_DATA_FIELD_DUPLICATE",`${d}/code`),n.add(a);let c=be(s.type,`${d}/type`,32);Ws.has(c)||k("NATIVE_DATA_FIELD_TYPE_INVALID",`${d}/type`);let f=c,u=xn(s.nullable,`${d}/nullable`),p=xn(s.indexed,`${d}/indexed`);u===!0&&li.has(f)&&k("NATIVE_DATA_MULTI_FIELD_NULLABLE_INVALID",`${d}/nullable`);let _=Bs(s.options,f,d),E=Ks(s.source,f,d),A=xt(s.userCandidates,f,`${d}/userCandidates`),O=qs(s,f,d),b=xn(s.exactDecimal,`${d}/exactDecimal`);b!==void 0&&f!=="number.decimal"&&k("NATIVE_DATA_FIELD_EXACT_DECIMAL_TYPE_INVALID",`${d}/exactDecimal`);let g=Us(s.rangeBoundary,f,d),I=zs(s.file,f,d),T=Js(s.serial,f,d),l=Hs(s.subtable,f,d);return{code:a,type:f,...u===void 0?{}:{nullable:u},...p===void 0?{}:{indexed:p},..._?{options:_}:{},...E?{source:E}:{},...A?{userCandidates:A}:{},...O,...b===void 0?{}:{exactDecimal:b},...g?{rangeBoundary:g}:{},...I?{file:I}:{},...T?{serial:T}:{},...l?{subtable:l}:{}}})}function Us(e,t,o){let n=`${o}/rangeBoundary`;if(!(t==="date-range"||t==="datetime-range")){e!==void 0&&k("NATIVE_DATA_FIELD_RANGE_BOUNDARY_TYPE_INVALID",n);return}return e!=="closed"&&e!=="half-open"&&k("NATIVE_DATA_FIELD_RANGE_BOUNDARY_REQUIRED",n),e}function ui(e,t){Array.isArray(e)||k("NATIVE_ARRAY_REQUIRED",t);let o=new Map;e.forEach((n,i)=>{let r=`${t}/${i}`,d=Ee(n,r),s=be(d.code,`${r}/code`,64);(!jn.test(s)||o.has(s))&&k("NATIVE_RESOURCE_CODE_INVALID",`${r}/code`);let a=Ee(d.schema,`${r}/schema`);a.ownedRowLimit!==void 0&&!mt(a.ownedRowLimit)&&k("NATIVE_DATA_OWNED_ROW_LIMIT_INVALID",`${r}/schema/ownedRowLimit`),o.set(s,{pointer:r,ownedRowLimit:jt(a),fields:Bn(a.fields,`${r}/schema/fields`)})});for(let[n,i]of o){let r=new Map(i.fields.map(s=>[s.code,s]));i.fields.filter(s=>s.type==="subtable").reduce((s,a)=>s+(a.subtable?.maxRows??20),0)>i.ownedRowLimit&&k("NATIVE_DATA_FIELD_SUBTABLE_AGGREGATE_MAX_ROWS_EXCEEDED",`${i.pointer}/schema/fields`),i.fields.forEach((s,a)=>{let c=`${i.pointer}/schema/fields/${a}`;if(s.source&&Ms(s.source,r,o,`${c}/source`),s.subtable){let f=o.get(s.subtable.resourceCode);(!f||s.subtable.resourceCode===n)&&k("NATIVE_DATA_FIELD_SUBTABLE_TARGET_MISSING",`${c}/subtable/resourceCode`);let u=f.fields.find(_=>_.code===s.subtable?.foreignKey);(!u||u.type!=="uuid"||u.nullable!==!1)&&k("NATIVE_DATA_FIELD_SUBTABLE_FOREIGN_KEY_INVALID",`${c}/subtable/foreignKey`);let p=f.fields.find(_=>_.code===s.subtable?.orderField);(!p||p.type!=="number.integer"||p.nullable!==!1)&&k("NATIVE_DATA_FIELD_SUBTABLE_ORDER_FIELD_INVALID",`${c}/subtable/orderField`)}})}}function fi(e,t,o){if(e===void 0)return[];(!Array.isArray(e)||e.length>20)&&k("NATIVE_DATA_RESOURCE_INVARIANTS_INVALID",o);let n=new Map(t.map(r=>[r.code,r])),i=new Set;return e.map((r,d)=>{let s=`${o}/${d}`,a=Ee(r,s);ye(a,["code","message","expression"],s);let c=be(a.code,`${s}/code`,128);(!/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/.test(c)||i.has(c))&&k("NATIVE_DATA_RESOURCE_INVARIANT_CODE_INVALID",`${s}/code`),i.add(c);let f=Ut(a.message,`${s}/message`,500);f!==void 0&&f.length===0&&k("NATIVE_DATA_RESOURCE_INVARIANT_MESSAGE_INVALID",`${s}/message`);let u=Ee(a.expression,`${s}/expression`);if(u.kind==="nonBlankTextWhenOption"){ye(u,["kind","optionField","optionValue","textField"],`${s}/expression`);let g=Te(u.optionField,`${s}/expression/optionField`),I=Te(u.textField,`${s}/expression/textField`),T=be(u.optionValue,`${s}/expression/optionValue`,128),l=n.get(g),y=n.get(I);return(!l||!y)&&k("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_UNKNOWN",`${s}/expression`),(l.type!=="option.single"||!["text.short","text.long"].includes(y.type)||!l.options?.some(R=>R.value===T))&&k("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_TYPES_INVALID",`${s}/expression`),{code:c,...f===void 0?{}:{message:f},expression:{kind:"nonBlankTextWhenOption",optionField:g,optionValue:T,textField:I}}}ye(u,["leftField","operator","rightField"],`${s}/expression`);let p=Te(u.leftField,`${s}/expression/leftField`),_=Te(u.rightField,`${s}/expression/rightField`),E=n.get(p),A=n.get(_);(!E||!A)&&k("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_UNKNOWN",`${s}/expression`),E.type===A.type||["number.integer","number.decimal"].includes(E.type)&&["number.integer","number.decimal"].includes(A.type)||k("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_TYPES_INVALID",`${s}/expression`);let b=String(u.operator);return["eq","neq","gt","gte","lt","lte"].includes(b)||k("NATIVE_DATA_RESOURCE_INVARIANT_OPERATOR_INVALID",`${s}/expression/operator`),!["eq","neq"].includes(b)&&!["number.integer","number.decimal","date","time","datetime","text.short","text.long","text.rich","serial-number","uuid"].includes(E.type)&&k("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_TYPES_INVALID",`${s}/expression`),{code:c,...f===void 0?{}:{message:f},expression:{leftField:p,operator:b,rightField:_}}})}function Ms(e,t,o,n){let i=o.get(e.resourceCode);i||k("NATIVE_DATA_FIELD_SOURCE_TARGET_MISSING",`${n}/resourceCode`);let r=new Map(i.fields.map(s=>[s.code,s])),d=r.get(e.labelField);(!d||!["text.short","text.long"].includes(d.type))&&k("NATIVE_DATA_FIELD_SOURCE_LABEL_INVALID",`${n}/labelField`);for(let s of["searchFields","descriptionFields","snapshotFields"])for(let a of e[s]||[])r.has(a)||k("NATIVE_DATA_FIELD_SOURCE_FIELD_MISSING",`${n}/${s}`);for(let[s,a]of(e.filters||[]).entries())r.has(a.field)||k("NATIVE_DATA_FIELD_SOURCE_FILTER_FIELD_MISSING",`${n}/filters/${s}/field`),"binding"in a&&!t.has(a.binding.field)&&k("NATIVE_DATA_FIELD_SOURCE_BINDING_FIELD_MISSING",`${n}/filters/${s}/binding/field`)}function Bs(e,t,o){let n=`${o}/options`;if(e===void 0){si.has(t)&&k("NATIVE_DATA_FIELD_OPTIONS_REQUIRED",n);return}(!si.has(t)||!Array.isArray(e))&&k("NATIVE_DATA_FIELD_OPTIONS_TYPE_INVALID",n),(e.length<1||e.length>100)&&k("NATIVE_DATA_FIELD_OPTIONS_INVALID",n);let i=0,r=(d,s,a)=>{a>5&&k("NATIVE_DATA_FIELD_OPTIONS_DEPTH_EXCEEDED",s);let c=new Set;return d.map((f,u)=>{i+=1,i>1e3&&k("NATIVE_DATA_FIELD_OPTIONS_COUNT_EXCEEDED",n);let p=`${s}/${u}`,_=Ee(f,p);ye(_,["label","value","description","color","children"],p);let E=be(_.label,`${p}/label`,500),A=be(_.value,`${p}/value`,500);c.has(A)&&k("NATIVE_DATA_FIELD_OPTION_VALUE_DUPLICATE",`${p}/value`),c.add(A);let O=Ut(_.description,`${p}/description`,2e3),b=Ut(_.color,`${p}/color`,64),g;return _.children!==void 0&&((!t.startsWith("cascade.")||!Array.isArray(_.children))&&k("NATIVE_DATA_FIELD_OPTION_CHILDREN_INVALID",`${p}/children`),(_.children.length<1||_.children.length>100)&&k("NATIVE_DATA_FIELD_OPTION_CHILDREN_INVALID",`${p}/children`),g=r(_.children,`${p}/children`,a+1)),{label:E,value:A,...O===void 0?{}:{description:O},...b===void 0?{}:{color:b},...g?{children:g}:{}}})};return r(e,n,1)}function Ks(e,t,o){let n=`${o}/source`;if(e===void 0){ai.has(t)&&k("NATIVE_DATA_FIELD_SOURCE_REQUIRED",n);return}ai.has(t)||k("NATIVE_DATA_FIELD_SOURCE_TYPE_INVALID",n);let i=Ee(e,n);ye(i,["kind","resourceCode","labelField","searchFields","descriptionFields","snapshotFields","filters","pageSize","loadMode","clearOnBindingChange"],n),i.kind!=="resource"&&k("NATIVE_DATA_FIELD_SOURCE_KIND_INVALID",`${n}/kind`);let r=be(i.resourceCode,`${n}/resourceCode`,64);jn.test(r)||k("NATIVE_RESOURCE_CODE_INVALID",`${n}/resourceCode`);let d=Te(i.labelField,`${n}/labelField`),s=Fn(i.searchFields,`${n}/searchFields`,10),a=Fn(i.descriptionFields,`${n}/descriptionFields`,10),c=Fn(i.snapshotFields,`${n}/snapshotFields`,50),f=Ke(i.pageSize,`${n}/pageSize`,1,100),u;i.loadMode!==void 0&&(["search","all"].includes(String(i.loadMode))||k("NATIVE_DATA_FIELD_SOURCE_LOAD_MODE_INVALID",`${n}/loadMode`),u=i.loadMode);let p=Gs(i.filters,`${n}/filters`);return i.clearOnBindingChange!==void 0&&typeof i.clearOnBindingChange!="boolean"&&k("NATIVE_DATA_FIELD_SOURCE_BINDING_RESET_INVALID",`${n}/clearOnBindingChange`),{kind:"resource",resourceCode:r,labelField:d,...s?{searchFields:s}:{},...a?{descriptionFields:a}:{},...c?{snapshotFields:c}:{},...p?{filters:p}:{},...f===void 0?{}:{pageSize:f},...u?{loadMode:u}:{},...i.clearOnBindingChange===void 0?{}:{clearOnBindingChange:i.clearOnBindingChange}}}function Gs(e,t){if(e!==void 0)return(!Array.isArray(e)||e.length>20)&&k("NATIVE_DATA_FIELD_SOURCE_FILTERS_INVALID",t),e.map((o,n)=>{let i=`${t}/${n}`,r=Ee(o,i),d=Object.prototype.hasOwnProperty.call(r,"value"),s=Object.prototype.hasOwnProperty.call(r,"binding");ye(r,d?["field","operator","value"]:["field","operator","binding"],i),d===s&&k("NATIVE_DATA_FIELD_SOURCE_FILTER_VALUE_INVALID",i);let a=Te(r.field,`${i}/field`);["eq","in"].includes(String(r.operator))||k("NATIVE_DATA_FIELD_SOURCE_FILTER_OPERATOR_INVALID",`${i}/operator`);let c=r.operator;if(d)return{field:a,operator:c,value:r.value};let f=Ee(r.binding,`${i}/binding`);return ye(f,["kind","field"],`${i}/binding`),f.kind!=="field"&&k("NATIVE_DATA_FIELD_SOURCE_BINDING_KIND_INVALID",`${i}/binding/kind`),{field:a,operator:c,binding:{kind:"field",field:Te(f.field,`${i}/binding/field`)}}})}function qs(e,t,o){let n={};if(e.maxLength!==void 0&&(["text.short","text.long","text.rich"].includes(t)||k("NATIVE_DATA_FIELD_MAX_LENGTH_TYPE_INVALID",`${o}/maxLength`),n.maxLength=Wt(e.maxLength,`${o}/maxLength`,1,1e6)),(e.precision!==void 0||e.scale!==void 0)&&((t!=="number.decimal"||e.precision===void 0)&&k("NATIVE_DATA_FIELD_DECIMAL_CONFIG_INVALID",o),n.precision=Wt(e.precision,`${o}/precision`,1,1e3),n.scale=e.scale===void 0?0:Wt(e.scale,`${o}/scale`,0,n.precision)),e.min!==void 0||e.max!==void 0){["number.integer","number.decimal"].includes(t)||k("NATIVE_DATA_FIELD_NUMERIC_BOUNDS_TYPE_INVALID",o);let i=di(e.min,`${o}/min`),r=di(e.max,`${o}/max`);t==="number.integer"&&[i,r].some(d=>d!==void 0&&!Number.isSafeInteger(d))&&k("NATIVE_DATA_FIELD_NUMERIC_BOUNDS_INVALID",o),i!==void 0&&r!==void 0&&i>r&&k("NATIVE_DATA_FIELD_NUMERIC_BOUNDS_INVALID",o),i!==void 0&&(n.min=i),r!==void 0&&(n.max=r)}return e.timePrecision!==void 0&&((!["time","datetime","datetime-range"].includes(t)||!["minute","second"].includes(e.timePrecision))&&k("NATIVE_DATA_FIELD_TIME_PRECISION_INVALID",`${o}/timePrecision`),n.timePrecision=e.timePrecision),n}function zs(e,t,o){if(e===void 0)return;let n=`${o}/file`;["file","image","signature"].includes(t)||k("NATIVE_DATA_FIELD_FILE_TYPE_INVALID",n);let i=Ee(e,n);ye(i,["maxCount","maxSizeMb","accept"],n);let r=Ke(i.maxCount,`${n}/maxCount`,1,100);t==="signature"&&r!==void 0&&r!==1&&k("NATIVE_DATA_FIELD_SIGNATURE_COUNT_INVALID",`${n}/maxCount`);let d=Ke(i.maxSizeMb,`${n}/maxSizeMb`,1,1024),s;return i.accept!==void 0&&((!Array.isArray(i.accept)||i.accept.length>50)&&k("NATIVE_DATA_FIELD_FILE_ACCEPT_INVALID",`${n}/accept`),s=i.accept.map((a,c)=>be(a,`${n}/accept/${c}`,255)),new Set(s).size!==s.length&&k("NATIVE_DATA_FIELD_FILE_ACCEPT_INVALID",`${n}/accept`)),{...r===void 0?{}:{maxCount:r},...d===void 0?{}:{maxSizeMb:d},...s===void 0?{}:{accept:s}}}function Js(e,t,o){let n=`${o}/serial`;if(e===void 0){t==="serial-number"&&k("NATIVE_DATA_FIELD_SERIAL_REQUIRED",n);return}t!=="serial-number"&&k("NATIVE_DATA_FIELD_SERIAL_TYPE_INVALID",n);let i=Ee(e,n);ye(i,["prefix","digits","start"],n);let r=Ut(i.prefix,`${n}/prefix`,64),d=Ke(i.digits,`${n}/digits`,1,32),s=Ke(i.start,`${n}/start`,0,Number.MAX_SAFE_INTEGER);return{...r===void 0?{}:{prefix:r},...d===void 0?{}:{digits:d},...s===void 0?{}:{start:s}}}function Hs(e,t,o){let n=`${o}/subtable`;if(e===void 0){t==="subtable"&&k("NATIVE_DATA_FIELD_SUBTABLE_REQUIRED",n);return}t!=="subtable"&&k("NATIVE_DATA_FIELD_SUBTABLE_TYPE_INVALID",n);let i=Ee(e,n);ye(i,["resourceCode","foreignKey","orderField","minRows","maxRows"],n);let r=be(i.resourceCode,`${n}/resourceCode`,64);jn.test(r)||k("NATIVE_RESOURCE_CODE_INVALID",`${n}/resourceCode`);let d=Te(i.foreignKey,`${n}/foreignKey`),s=Te(i.orderField,`${n}/orderField`);s===d&&k("NATIVE_DATA_FIELD_SUBTABLE_ORDER_FIELD_INVALID",`${n}/orderField`);let a=Ke(i.maxRows,`${n}/maxRows`,1,Be),c=Ke(i.minRows,`${n}/minRows`,0,Be);return(c??0)>(a??20)&&k("NATIVE_DATA_FIELD_SUBTABLE_MIN_ROWS_INVALID",`${n}/minRows`),{resourceCode:r,foreignKey:d,orderField:s,...c===void 0?{}:{minRows:c},...a===void 0?{}:{maxRows:a}}}function Fn(e,t,o){if(e===void 0)return;(!Array.isArray(e)||e.length>o)&&k("NATIVE_DATA_FIELD_SOURCE_FIELDS_INVALID",t);let n=e.map((i,r)=>Te(i,`${t}/${r}`));return new Set(n).size!==n.length&&k("NATIVE_DATA_FIELD_SOURCE_FIELDS_INVALID",t),n}function Te(e,t){let o=be(e,t,63);return ci.test(o)||k("NATIVE_FIELD_CODE_INVALID",t),o}function Ee(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&k("NATIVE_OBJECT_REQUIRED",t),e}function ye(e,t,o){let n=new Set(t);for(let i of Object.keys(e))n.has(i)||k("NATIVE_PROPERTY_UNKNOWN",`${o}/${i}`)}function be(e,t,o){return(typeof e!="string"||e.length===0||e.length>o)&&k("NATIVE_STRING_INVALID",t),e}function Ut(e,t,o){if(e!==void 0)return(typeof e!="string"||e.length>o)&&k("NATIVE_STRING_INVALID",t),e}function xn(e,t){if(e!==void 0)return typeof e!="boolean"&&k("NATIVE_BOOLEAN_REQUIRED",t),e}function Ke(e,t,o,n){if(e!==void 0)return Wt(e,t,o,n)}function di(e,t){if(e!==void 0)return(typeof e!="number"||!Number.isFinite(e))&&k("NATIVE_NUMBER_REQUIRED",t),e}function Wt(e,t,o,n){return(!Number.isSafeInteger(e)||Number(e)<o||Number(e)>n)&&k("NATIVE_INTEGER_OUT_OF_RANGE",t),Number(e)}function k(e,t){throw new Re(e,t)}var Kt=["created_by","updated_by","created_at","updated_at"];function _t(e){return Kt.includes(e)}function pi(e){return Kt.some(t=>Object.prototype.hasOwnProperty.call(e.fieldPolicies||{},t))}var Ys=Mn.map(e=>e.code);function mi(e){return Ys.includes(e)}var Xs=["eq","neq","gt","gte","lt","lte","contains","startsWith","endsWith","in","between","has","hasAny","hasAll","overlaps","containedBy","jsonContains","isEmpty","isNotEmpty"],Zs=new Set(Xs);function Xc(e){return Zs.has(String(e))}var Kn=["eq","neq","contains","startsWith","endsWith","in","isEmpty","isNotEmpty"],gt=["eq","neq","gt","gte","lt","lte","between","in","isEmpty"],Qs=["eq","neq","in","isEmpty"],Gt=["eq","neq","in","isEmpty","isNotEmpty"],ot=["has","hasAny","hasAll","isEmpty","isNotEmpty"],_i=["overlaps","contains","containedBy","isEmpty"],Gn=["jsonContains","isEmpty","isNotEmpty"],qn=["isEmpty","isNotEmpty"],ea={"text.short":Kn,"text.long":Kn,"text.rich":Kn,"number.integer":gt,"number.decimal":gt,boolean:Qs,date:gt,time:gt,datetime:gt,"date-range":_i,"datetime-range":_i,"option.single":Gt,"option.multiple":ot,"cascade.single":ot,"cascade.multiple":ot,"user.single":Gt,"user.multiple":ot,"department.single":Gt,"department.multiple":ot,"resource-ref.single":Gt,"resource-ref.multiple":ot,file:qn,image:qn,signature:qn,address:Gn,location:Gn,uuid:["eq","neq","in","isEmpty"],json:Gn,"serial-number":["eq","neq","in","contains","startsWith"],subtable:[]},ta=new Set(["text.short","text.long","text.rich","option.single","user.single","department.single","resource-ref.single","serial-number"]),na=new Set(["option.multiple","cascade.single","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","file","image","signature","address","location","json","subtable"]);function Ai(e){return ea[e]}function Zc(e,t){return Ai(e).includes(t)}function zn(e){return ta.has(e)}function At(e){return!na.has(e)}function Ei(e){return Ai(e).length>0}var gi=new Set(["number.integer","number.decimal"]),Ii=new Set(["text.short","text.long","number.integer","number.decimal","date","time","datetime","serial-number"]),oa=new Set([...Ii,"boolean","uuid"]),ia=new Set(["option.single","user.single","department.single","resource-ref.single"]);function Qc(e,t){return t==="sum"||t==="avg"?gi.has(e)?{valueExpression:"column",numericResult:!0}:null:t==="min"||t==="max"?Ii.has(e)?{valueExpression:"column",numericResult:gi.has(e)}:null:ia.has(e)?{valueExpression:"snapshot-value",numericResult:!0}:oa.has(e)?{valueExpression:"column",numericResult:!0}:null}var Hn=["version","maxBytes","fields"];function bi(e,t){if(e===void 0)return;let o=Jn(e,t);yi(o,Hn,t);let n=qt(o.version,`${t}/version`,1,1e6),i=qt(o.maxBytes,`${t}/maxBytes`,2,196608);(!n||!i)&&ce("NATIVE_DATA_DRAFT_STATE_SCHEMA_INVALID",t);let r=Jn(o.fields,`${t}/fields`),d=Object.entries(r);(!d.length||d.length>50)&&ce("NATIVE_DATA_DRAFT_STATE_FIELDS_INVALID",`${t}/fields`);for(let[s,a]of d){let c=`${t}/fields/${s}`;/^[A-Za-z][A-Za-z0-9_]{0,62}$/.test(s)||ce("NATIVE_DATA_DRAFT_STATE_FIELD_CODE_INVALID",c);let f=Jn(a,c),u=Oi(f.type,`${c}/type`,32),p=u==="string"?["type","required","maxLength","enum"]:u==="json.object"?["type","required","maxBytes"]:["type","required"];if(["string","number","integer","boolean","json.object"].includes(u)||ce("NATIVE_DATA_DRAFT_STATE_FIELD_TYPE_INVALID",`${c}/type`),yi(f,p,c),sa(f.required,`${c}/required`),u==="string"){let _=qt(f.maxLength,`${c}/maxLength`,1,196608);_||ce("NATIVE_DATA_DRAFT_STATE_FIELD_INVALID",c),f.enum!==void 0&&ra(f.enum,`${c}/enum`,100,!1).some(A=>A.length>_)&&ce("NATIVE_DATA_DRAFT_STATE_FIELD_INVALID",`${c}/enum`)}else if(u==="json.object"){let _=qt(f.maxBytes,`${c}/maxBytes`,2,65536);(!_||_>i)&&ce("NATIVE_DATA_DRAFT_STATE_FIELD_INVALID",c)}}}function ra(e,t,o,n){(!Array.isArray(e)||!n&&e.length===0||e.length>o)&&ce("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t);let i=e.map((r,d)=>Oi(r,`${t}/${d}`,255));return new Set(i).size!==i.length&&ce("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t),i}function Jn(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&ce("NATIVE_OBJECT_REQUIRED",t),e}function yi(e,t,o){let n=new Set(t);for(let i of Object.keys(e))n.has(i)||ce("NATIVE_PROPERTY_UNKNOWN",`${o}/${i}`)}function Oi(e,t,o){return(typeof e!="string"||e.length===0||e.length>o)&&ce("NATIVE_STRING_INVALID",t),e}function sa(e,t){e!==void 0&&typeof e!="boolean"&&ce("NATIVE_BOOLEAN_REQUIRED",t)}function qt(e,t,o,n){return(!Number.isSafeInteger(e)||Number(e)<o||Number(e)>n)&&ce("NATIVE_INTEGER_INVALID",t),Number(e)}function ce(e,t){throw new Re(e,t)}var aa=500,Pe={surface:["mutationOwner","generated","fields","list","form","detail","mobile","views"],generated:["list","detail","create","update","delete"],field:["label","type","widget","section","requiredHint","system","hidden","readCapabilities","createCapabilities","updateCapabilities","maxLength","precision","scale","exactDecimal","min","max","rangeBoundary","maxCount","maxSizeMb","accept","options","list","searchable","sortable","source","userCandidates","timePrecision","serial","subtable"],list:["actions","fieldOrder","defaultPageSize","searchableFields","filterFields","defaultSort"],defaultSort:["field","order"],form:["layout","fieldOrder","draftState"],detail:["layout","fieldOrder"],layout:["layout","fieldOrder","draftState"],draftState:Hn,mobile:["enabled"]},da={"text.short":["text","email","phone"],"text.long":["textarea"],"text.rich":["rich-text"],"number.integer":["number","rating"],"number.decimal":["number","money","percent"],boolean:["switch"],date:["date"],time:["time"],datetime:["datetime"],"date-range":["date-range"],"datetime-range":["datetime-range"],"option.single":["select","radio"],"option.multiple":["multi-select","checkbox"],"cascade.single":["cascade"],"cascade.multiple":["cascade"],"user.single":["directory-user"],"user.multiple":["directory-user"],"department.single":["directory-department","scope"],"department.multiple":["directory-department","scope"],"resource-ref.single":["select","radio","resource"],"resource-ref.multiple":["multi-select","checkbox","resource"],file:["attachment"],image:["image"],signature:["signature"],address:["address"],location:["location"],uuid:["readonly"],json:["json"],"serial-number":["readonly"],subtable:["subtable"]};function Zn(e,t,o){if(e===void 0)return;let n=ae(e,o);Ce(n,Pe.surface,o);let i=n.mutationOwner===void 0?"native":De(n.mutationOwner,`${o}/mutationOwner`,16);["native","action","readonly","workflow","queued-command"].includes(i)||W("NATIVE_DATA_SURFACE_MUTATION_OWNER_INVALID",`${o}/mutationOwner`);let r=n.generated===void 0?{}:ae(n.generated,`${o}/generated`);Ce(r,Pe.generated,`${o}/generated`);for(let a of Pe.generated)Xn(r[a],`${o}/generated/${a}`);if(i!=="native")for(let a of["create","update","delete"])r[a]===!0&&W("NATIVE_DATA_SURFACE_MUTATION_OWNER_CONFLICT",`${o}/generated/${a}`);let d=new Map(t.map(a=>[a.code,a])),s=ae(n.fields,`${o}/fields`);for(let a of Object.keys(s))d.has(a)||W("NATIVE_DATA_SURFACE_FIELD_MISSING",`${o}/fields/${a}`);for(let a of t)Object.prototype.hasOwnProperty.call(s,a.code)||W("NATIVE_DATA_SURFACE_FIELD_REQUIRED",`${o}/fields/${a.code}`),la(s[a.code],a,`${o}/fields/${a.code}`);for(let a of["create","update"]){let c=r[a]??i==="native",f=t.some(u=>{let p=ae(s[u.code],`${o}/fields/${u.code}`);return Ti(u,p,a)});c&&!f&&W("NATIVE_DATA_SURFACE_WRITABLE_FIELDS_REQUIRED",`${o}/generated/${a}`)}if(ua(n.list,d,`${o}/list`),Ni(n.form,d,`${o}/form`,"form"),Ni(n.detail,d,`${o}/detail`,"detail"),n.mobile!==void 0){let a=ae(n.mobile,`${o}/mobile`);Ce(a,Pe.mobile,`${o}/mobile`),Xn(a.enabled,`${o}/mobile/enabled`)}ca(n,t,o)}function Qn(e,t){let o=e.views?.find(i=>i.code===t);o||W("NATIVE_DATA_VIEW_NOT_FOUND",`/surface/views/${t}`);let n=new Map((o.sections||[]).flatMap(i=>i.fields.map(r=>[r,i.title])));return{mutationOwner:e.mutationOwner||"native",generated:o.generated,list:o.list,form:o.form,detail:o.detail,mobile:o.mobile,fields:Object.fromEntries(Object.entries(e.fields).map(([i,r])=>{let d={...r};delete d.section;let s=n.get(i);return[i,{...d,...s?{section:s}:{},list:o.list.fieldOrder.includes(i)}]}))}}function ca(e,t,o){if(e.views===void 0)return;(!Array.isArray(e.views)||e.views.length>20)&&W("NATIVE_DATA_VIEWS_LIMIT_INVALID",`${o}/views`);let n=new Set;e.views.forEach((i,r)=>{let d=`${o}/views/${r}`,s=ae(i,d);Ce(s,["code","name","generated","list","form","detail","mobile","sections"],d);let a=De(s.code,`${d}/code`,64);(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(a)||n.has(a))&&W("NATIVE_DATA_VIEW_CODE_INVALID",`${d}/code`),n.add(a),De(s.name,`${d}/name`,255),ae(s.generated,`${d}/generated`),ae(s.mobile,`${d}/mobile`);for(let f of["list","detail","create","update","delete"])typeof s.generated[f]!="boolean"&&W("NATIVE_DATA_VIEW_OPERATION_INVALID",`${d}/generated/${f}`);typeof s.mobile.enabled!="boolean"&&W("NATIVE_DATA_VIEW_MOBILE_INVALID",`${d}/mobile/enabled`);for(let f of["list","form","detail"]){let u=ae(s[f],`${d}/${f}`),p=it(u.fieldOrder,`${d}/${f}/fieldOrder`,500,!0);for(let _ of p){let E=e.fields[_];(!E||(E.hidden??E.system)===!0)&&W("NATIVE_DATA_VIEW_FIELD_INVALID",`${d}/${f}/fieldOrder`)}}if(s.sections!==void 0){(!Array.isArray(s.sections)||s.sections.length>100)&&W("NATIVE_DATA_VIEW_SECTIONS_INVALID",`${d}/sections`);let f=new Set;s.sections.forEach((u,p)=>{let _=`${d}/sections/${p}`,E=ae(u,_);Ce(E,["title","fields"],_),De(E.title,`${_}/title`,255);for(let A of it(E.fields,`${_}/fields`,100,!0)){let O=e.fields[A];(!O||(O.hidden??O.system)===!0||f.has(A))&&W("NATIVE_DATA_VIEW_FIELD_INVALID",`${_}/fields`),f.add(A)}})}let c=Qn(e,a);if(Zn(c,t,d),s.generated.create!==!1&&(e.mutationOwner||"native")==="native")for(let f of t)Bt(f,e.fields[f.code])&&Ti(f,e.fields[f.code],"create")&&!s.form.fieldOrder.includes(f.code)&&W("NATIVE_DATA_VIEW_CREATE_REQUIRED_FIELD_MISSING",`${d}/form/fieldOrder`)})}function Ti(e,t,o){if(e.type==="serial-number"||t.system===!0)return!1;let n=t[`${o}Capabilities`];return Array.isArray(n)&&n.length>0}function la(e,t,o){let n=ae(e,o);Ce(n,Pe.field,o),De(n.label,`${o}/label`,500),n.type!==t.type&&W("NATIVE_DATA_SURFACE_FIELD_TYPE_MISMATCH",`${o}/type`);let i=De(n.widget,`${o}/widget`,64);da[t.type].includes(i)||W("NATIVE_DATA_SURFACE_WIDGET_INCOMPATIBLE",`${o}/widget`),ma(n.section,`${o}/section`,255);for(let r of["requiredHint","system","hidden","list","searchable","sortable"])Xn(n[r],`${o}/${r}`);n.searchable===!0&&!zn(t.type)&&W("NATIVE_DATA_SURFACE_SEARCH_UNSUPPORTED",`${o}/searchable`),n.sortable===!0&&!At(t.type)&&W("NATIVE_DATA_SURFACE_SORT_UNSUPPORTED",`${o}/sortable`);for(let r of["readCapabilities","createCapabilities","updateCapabilities"])it(n[r],`${o}/${r}`,100,!0);if(n.maxCount!==void 0&&(!Number.isSafeInteger(n.maxCount)||Number(n.maxCount)<1||Number(n.maxCount)>100)&&W("NATIVE_DATA_SURFACE_MAX_COUNT_INVALID",`${o}/maxCount`),n.maxSizeMb!==void 0&&(!Number.isSafeInteger(n.maxSizeMb)||Number(n.maxSizeMb)<1||Number(n.maxSizeMb)>1024)&&W("NATIVE_DATA_SURFACE_MAX_SIZE_INVALID",`${o}/maxSizeMb`),n.accept!==void 0){let r=Array.isArray(n.accept)?n.accept:[n.accept];it(r,`${o}/accept`,50,!1)}for(let r of["maxLength","precision","scale","exactDecimal","min","max","rangeBoundary","options","source","userCandidates","timePrecision","serial","subtable"])fa(n,t,r,o);pa(n,t,o)}function ua(e,t,o){if(e===void 0)return;let n=ae(e,o);if(Ce(n,Pe.list,o),n.actions!==void 0){let i=ae(n.actions,`${o}/actions`);Ce(i,["import","export"],`${o}/actions`);for(let r of["import","export"])i[r]!==void 0&&typeof i[r]!="boolean"&&W("NATIVE_DATA_SURFACE_LIST_ACTION_INVALID",`${o}/actions/${r}`)}if(n.fieldOrder!==void 0)for(let i of it(n.fieldOrder,`${o}/fieldOrder`,500,!0))t.has(i)||W("NATIVE_DATA_SURFACE_LIST_FIELD_INVALID",`${o}/fieldOrder`);n.defaultPageSize!==void 0&&(!Number.isSafeInteger(n.defaultPageSize)||Number(n.defaultPageSize)<1||Number(n.defaultPageSize)>200)&&W("NATIVE_DATA_SURFACE_PAGE_SIZE_INVALID",`${o}/defaultPageSize`);for(let[i,r]of[["searchableFields",zn],["filterFields",Ei]]){if(n[i]===void 0)continue;let d=it(n[i],`${o}/${i}`,100,!0);for(let s of d){let a=t.get(s);(!a||!r(a.type))&&W("NATIVE_DATA_SURFACE_LIST_FIELD_INVALID",`${o}/${i}`)}}if(n.defaultSort!==void 0){let i=ae(n.defaultSort,`${o}/defaultSort`);Ce(i,Pe.defaultSort,`${o}/defaultSort`);let r=De(i.field,`${o}/defaultSort/field`,63),d=t.get(r);!mi(r)&&(!d||!At(d.type))&&W("NATIVE_DATA_SURFACE_SORT_UNSUPPORTED",`${o}/defaultSort/field`),i.order!==void 0&&!["asc","desc"].includes(i.order)&&W("NATIVE_DATA_SURFACE_SORT_ORDER_INVALID",`${o}/defaultSort/order`)}}function Ni(e,t,o,n){if(e===void 0)return;let i=ae(e,o);if(Ce(i,Pe[n],o),i.layout!==void 0&&!["flat","sections"].includes(i.layout)&&W("NATIVE_DATA_SURFACE_LAYOUT_INVALID",`${o}/layout`),i.fieldOrder!==void 0){let r=`${o}/fieldOrder`;(!Array.isArray(i.fieldOrder)||i.fieldOrder.length>t.size||i.fieldOrder.length>aa)&&W("NATIVE_DATA_SURFACE_FIELD_ORDER_INVALID",r);let d=i.fieldOrder.map((s,a)=>De(s,`${r}/${a}`,63));new Set(d).size!==d.length&&W("NATIVE_DATA_SURFACE_FIELD_ORDER_INVALID",r),d.forEach((s,a)=>{t.has(s)||W("NATIVE_DATA_SURFACE_FIELD_ORDER_FIELD_MISSING",`${r}/${a}`)})}n==="form"&&bi(i.draftState,`${o}/draftState`)}function fa(e,t,o,n){e[o]===void 0&&t[o]===void 0||((e[o]===void 0||t[o]===void 0)&&W("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${n}/${o}`),X(e[o])!==X(t[o])&&W("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${n}/${o}`))}function pa(e,t,o){let n=t.file||{},i={...e.maxCount===void 0?{}:{maxCount:e.maxCount},...e.maxSizeMb===void 0?{}:{maxSizeMb:e.maxSizeMb},...e.accept===void 0?{}:{accept:Yn(e.accept)}};for(let r of["maxCount","maxSizeMb","accept"]){if(i[r]===void 0&&n[r]===void 0)continue;(i[r]===void 0||n[r]===void 0)&&W("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${o}/${r}`);let d=r==="accept"?Yn(i[r]):i[r],s=r==="accept"?Yn(n[r]):n[r];X(d)!==X(s)&&W("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${o}/${r}`)}}function Yn(e){return(Array.isArray(e)?[...e]:[e]).sort((t,o)=>{let n=String(t),i=String(o);return n===i?0:n<i?-1:1})}function it(e,t,o,n){(!Array.isArray(e)||!n&&e.length===0||e.length>o)&&W("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t);let i=e.map((r,d)=>De(r,`${t}/${d}`,255));return new Set(i).size!==i.length&&W("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t),i}function ae(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&W("NATIVE_OBJECT_REQUIRED",t),e}function Ce(e,t,o){let n=new Set(t);for(let i of Object.keys(e))n.has(i)||W("NATIVE_PROPERTY_UNKNOWN",`${o}/${i}`)}function De(e,t,o){return(typeof e!="string"||e.length===0||e.length>o)&&W("NATIVE_STRING_INVALID",t),e}function ma(e,t,o){e!==void 0&&(typeof e!="string"||e.length>o)&&W("NATIVE_STRING_INVALID",t)}function Xn(e,t){e!==void 0&&typeof e!="boolean"&&W("NATIVE_BOOLEAN_REQUIRED",t)}function W(e,t){throw new Re(e,t)}var Et=class extends Error{constructor(o,n){super(`${o}: ${n}`);this.pointer=o;this.reason=n}pointer;reason;code="NATIVE_MANAGED_CONCURRENCY_INVALID"};function Ri(e,t,o){if(e===void 0)return;let n=(g,I)=>{throw new Et(g,I)},i=(g,I,T)=>((!g||typeof g!="object"||Array.isArray(g)||Object.keys(g).some(l=>!T.includes(l)))&&n(I,"object contains unsupported properties"),g),r=(g,I,T,l)=>{(!Number.isSafeInteger(g)||g<I||g>T)&&n(l,`expected integer ${I}..${T}`)},d=(g,I)=>{(typeof g!="string"||!/^[a-z][a-z0-9_-]{0,63}$/.test(g))&&n(I,"invalid code")},s=(g,I,T)=>((!Array.isArray(g)||g.length>I)&&n(T,"array exceeds bound"),g),a=(g,I)=>{let T=t.find(l=>l.code===g);return T||n(I,"unknown resource"),T},c=(g,I,T)=>{let l=g.schema.fields.find(y=>y.code===I);return!l&&I!=="id"&&n(T,"unknown field"),l},f=(g,I,T=!1)=>{i(g,I,Object.keys(g||{})),Object.keys(g).length>8&&n(I,"at most eight parameters");for(let[l,y]of Object.entries(g))if(d(l,I),i(y,I,["type","values","minimum","maximum","minLength","maxLength"]),y.type==="uuid")Object.keys(y).length!==1&&n(I,"uuid has no options");else if(T&&y.type==="boolean")i(y,I,["type"]);else if(T&&y.type==="string"&&y.values===void 0)i(y,I,["type","minLength","maxLength"]),r(y.maxLength,1,256,I),y.minLength!==void 0&&r(y.minLength,0,y.maxLength,I);else if(y.type==="string"){i(y,I,["type","values"]);let R=s(y.values,100,I);(!R.length||R.some(h=>typeof h!="string"||h.length>128)||new Set(R).size!==R.length)&&n(I,"finite string values required")}else y.type==="integer"?(i(y,I,["type","minimum","maximum"]),r(y.minimum,0,1e6,I),r(y.maximum,y.minimum,y.minimum+1e3,I)):n(I,"unsupported parameter type")},u=(g,I,T,l=!1)=>{i(g,T,["from","key","value"]),!(g.from==="input"&&Object.keys(g).length===2&&Object.hasOwn(I,g.key))&&((g.from==="actor"||l&&g.from==="allocation")&&Object.keys(g).length===1||g.from==="literal"&&Object.keys(g).length===2&&Object.hasOwn(g,"value")&&(g.value===null||["string","boolean"].includes(typeof g.value)||typeof g.value=="number"&&Number.isFinite(g.value))&&JSON.stringify(g.value).length<=512||n(T,"invalid binding"))},p=(g,I,T)=>{u(g,I,T),!(g.from==="input"&&I[g.key].type==="uuid")&&(g.from==="literal"&&typeof g.value=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(g.value)||n(T,"record and allocation identifiers require a UUID binding"))},_=(g,I,T)=>{u(g,I,T),!(g.from==="input"&&I[g.key].type==="integer"&&I[g.key].minimum>=1)&&(g.from==="literal"&&Number.isSafeInteger(g.value)&&g.value>=1||n(T,"expectedRevision requires a positive integer binding"))},E="/data/concurrency";JSON.stringify(e).length>131072&&n(E,"declaration exceeds 128 KiB");let A=i(e,E,["version","admission","reads","quotas","commands"]);A.version!==1&&n(E,"unsupported version"),i(A.admission,E,["perSecond","burst","maxInFlight"]),r(A.admission.perSecond,1,1e3,E),r(A.admission.burst,1,1e3,E),r(A.admission.maxInFlight,1,1e3,E);let O=(g,I)=>{let T=new Set;for(let l of g)d(l?.code,I),T.has(l.code)&&n(I,"duplicate code"),T.add(l.code)};O(s(A.reads,32,E),E),O(s(A.quotas,16,E),E),O(s(A.commands,32,E),E);for(let g of A.reads){let I=`${E}/reads/${g.code}`;i(g,I,["code","resourceCode","parameters","select","where","limit","scope","freshSeconds","staleSeconds","maxKeys","sourcePerSecond","dependencies"]);let T=a(g.resourceCode,I);f(g.parameters,I),["subject","application"].includes(g.scope)||n(I,"invalid cache scope"),g.scope==="application"&&T.dataPolicyCode&&n(I,"shared cache cannot bypass a row policy");let l=s(g.select,32,I);l.length||n(I,"select required"),l.forEach(R=>c(T,R,I));let y=s(g.dependencies,64,I);y.forEach(R=>c(T,R,I));for(let R of s(g.where||[],8,I))i(R,I,["field","value"]),c(T,R.field,I),u(R.value,g.parameters,I),g.scope==="application"&&R.value.from==="actor"&&n(I,"actor requires subject cache"),y.includes(R.field)||n(I,"filter dependency missing");l.some(R=>!y.includes(R))&&n(I,"selected field dependency missing"),r(g.limit,1,100,I),r(g.freshSeconds,1,300,I),r(g.staleSeconds,0,300,I),r(g.maxKeys,1,1e4,I),r(g.sourcePerSecond,1,20,I)}for(let g of A.quotas){let I=`${E}/quotas/${g.code}`;i(g,I,["code","sourceResource","capacityField","allocationResource","allocationField","reservationSeconds"]);let T=a(g.sourceResource,I),l=a(g.allocationResource,I);c(T,g.capacityField,I)?.type!=="number.integer"&&n(I,"capacity must be an integer"),(c(l,g.allocationField,I)?.type!=="uuid"||c(l,g.allocationField,I)?.nullable!==!1)&&n(I,"allocation reference must be a uuid"),l.surface?.mutationOwner!=="queued-command"&&n(I,"allocation model must be command owned"),g.reservationSeconds!==void 0&&r(g.reservationSeconds,10,86400,I)}new Set(A.quotas.map(g=>g.allocationResource)).size!==A.quotas.length&&n(E,"an allocation model has exactly one pool owner");for(let g of A.commands){let I=`${E}/commands/${g.code}`;i(g,I,["code","mode","intake","execution","capability","parameters","resourceKey","admission","deadlineSeconds","guards","operations","quota"]),g.mode!==void 0&&!["permit","durable"].includes(g.mode)&&n(I,"unsupported mode");let T=g.mode==="durable";if(f(g.parameters,I,T),u(g.resourceKey,g.parameters,I),o.some(l=>l.code===g.capability)||n(I,"command capability must be declared"),i(g.admission,I,["perSecond","burst","maxInFlight","maxQueue","maxWaitSeconds","permitSeconds"]),r(g.admission.perSecond,1,A.admission.perSecond,I),r(g.admission.burst,1,A.admission.burst,I),r(g.admission.maxInFlight,1,A.admission.maxInFlight,I),r(g.admission.maxQueue,1,1e4,I),r(g.admission.maxWaitSeconds,1,3600,I),(!T||g.admission.permitSeconds!==void 0)&&r(g.admission.permitSeconds,5,60,I),r(g.deadlineSeconds,10,3600,I),T){(g.operations!==void 0||g.guards!==void 0||g.quota!==void 0)&&n(I,"backend-plan does not accept static operations, guards or quota"),i(g.intake,I,["perSecond","burst","maxInFlight"]);for(let R of["perSecond","burst","maxInFlight"])r(g.intake[R],1,1e3,I);let l=i(g.execution,I,["kind","handlerCode","timeoutMs","resources","directory"]);l.kind!=="backend-plan"&&n(I,"durable requires backend-plan"),d(l.handlerCode,I),r(l.timeoutMs,100,3e4,I);let y=s(l.resources,32,I);y.length||n(I,"execution resources required"),new Set(y.map(R=>R.resourceCode)).size!==y.length&&n(I,"duplicate execution resource");for(let R of y){i(R,I,["resourceCode","readFields","writeOperations","writeFields"]);let h=a(R.resourceCode,I);for(let w of["readFields","writeFields"]){let j=s(R[w],64,I);new Set(j).size!==j.length&&n(I,"duplicate field"),j.forEach(L=>{w==="readFields"&&nt.has(L)||c(h,L,I)})}let $=s(R.writeOperations,3,I);(new Set($).size!==$.length||$.some(w=>!["create","update","increment"].includes(w)))&&n(I,"unsupported execution operation"),R.writeFields.some(w=>["id","revision","created_by","updated_by","created_at","updated_at"].includes(w))&&n(I,"record metadata is platform owned"),!$.length&&R.writeFields.length&&n(I,"write fields require an operation"),$.length&&!R.writeFields.length&&n(I,"write operations require fields"),A.quotas.some(w=>w.allocationResource===R.resourceCode)&&$.length&&n(I,"allocation references remain owned by their pool command")}if(l.directory!==void 0){i(l.directory,I,["mode","fields"]),l.directory.mode!=="current-initiator"&&n(I,"only current initiator allowed");let R=s(l.directory.fields,5,I);(!R.length||new Set(R).size!==R.length||R.some(h=>!["displayName","employeeNumber","primaryDepartment","departments","phone"].includes(h)))&&n(I,"unsupported directory fields")}continue}(g.execution!==void 0||g.intake!==void 0)&&n(I,"execution and intake require durable mode");for(let l of s(g.guards||[],8,I)){i(l,I,["resourceCode","id","conditions"]);let y=a(l.resourceCode,I);p(l.id,g.parameters,I);for(let R of s(l.conditions,16,I)){i(R,I,["kind","field","operator","value"]);let h=c(y,R.field,I);["eq","neq","lt","lte","gt","gte"].includes(R.operator)||n(I,"unsupported guard"),R.kind==="database-now"?(h?.type!=="datetime"||!["lt","lte","gt","gte"].includes(R.operator)||R.value!==void 0)&&n(I,"database-now requires datetime and an ordering operator"):(R.kind!==void 0&&R.kind!=="value"&&n(I,"unsupported condition kind"),u(R.value,g.parameters,I))}}for(let l of s(g.operations,8,I)){i(l,I,["operation","resourceCode","id","expectedRevision","data"]);let y=a(l.resourceCode,I);y.surface?.mutationOwner!=="queued-command"&&n(I,"command mutations require command owned models");let R=A.quotas.find(h=>h.allocationResource===l.resourceCode);R&&(l.operation==="create"?g.quota?.action!=="allocate"||g.quota.pool!==R.code:Object.hasOwn(l.data||{},R.allocationField))&&n(I,"allocation references are owned by their pool command"),["create","update"].includes(l.operation)||n(I,"unsupported operation"),l.operation==="update"?(p(l.id,g.parameters,I),_(l.expectedRevision,g.parameters,I)):(l.id!==void 0||l.expectedRevision!==void 0)&&n(I,"create has no caller supplied id/revision"),i(l.data,I,Object.keys(l.data||{})),Object.keys(l.data).length>32&&n(I,"too many fields");for(let[h,$]of Object.entries(l.data))h==="id"&&n(I,"record identifiers are platform owned"),c(y,h,I),u($,g.parameters,I,g.quota?.action==="allocate")}if(g.quota){let l=i(g.quota,I,["pool","action","units","mode","allocation"]),y=A.quotas.find(R=>R.code===l.pool);y||n(I,"unknown quota pool"),p(g.resourceKey,g.parameters,I),l.action==="allocate"?(i(l,I,["pool","action","units","mode"]),r(l.units,1,1e3,I),(!["committed","reserved"].includes(l.mode)||l.mode==="reserved"&&!y.reservationSeconds)&&n(I,"invalid allocation mode"),(g.operations.length!==1||g.operations[0].operation!=="create"||g.operations[0].resourceCode!==y.allocationResource||g.operations[0].data[y.allocationField]?.from!=="allocation")&&n(I,"allocation must atomically create its bound business record")):["confirm","release"].includes(l.action)?(i(l,I,["pool","action","allocation"]),p(l.allocation,g.parameters,I),g.operations.length&&n(I,"lifecycle owns allocation state; business reference remains immutable")):n(I,"invalid quota action")}else g.operations.length||n(I,"operations required")}let b=A.commands.filter(g=>g.mode==="durable").map(g=>g.execution.handlerCode);return new Set(b).size!==b.length&&n(E,"handler code must be unique"),JSON.parse(JSON.stringify(A))}var rt=class extends Error{constructor(o,n){super(`\u91D1\u989D\u751F\u547D\u5468\u671F\u58F0\u660E\u65E0\u6548\uFF1A${n}\uFF08${o}\uFF09`);this.pointer=o;this.reason=n}pointer;reason;code="NATIVE_DECIMAL_LIFECYCLE_INVALID"},no=["parentTransitions","childTransitions","fulfilledChildStatuses","lockedParentStatuses"],Ci=["amountFieldCode","currencyFieldCode","relationFieldCode","parentFieldCode","rootFieldCode","statusFieldCode","parentRelationValue","childRelationValue"],Jt=e=>!!(e&&typeof e=="object"&&!Array.isArray(e)),zt=e=>Array.isArray(e)?e.filter(Jt):[],he=(e,t)=>{throw new rt(e,t)},eo=e=>typeof e=="string"&&/^[A-Za-z0-9._:-]{1,128}$/.test(e),to=(e,t)=>e<t?-1:e>t?1:0;function oo(e,t="/decimalReservationLifecycle"){if(e===void 0)return;if(!Jt(e)||Object.keys(e).some(i=>!no.includes(i))||no.some(i=>!Object.prototype.hasOwnProperty.call(e,i)))return he(t,"\u5FC5\u987B\u5B8C\u6574\u58F0\u660E\u56DB\u9879\u89C4\u5219\uFF0C\u4E0D\u80FD\u5305\u542B\u672A\u77E5\u5C5E\u6027");let o=i=>{let r=e[i];if(!Array.isArray(r)||r.length>64)return he(`${t}/${i}`,"\u72B6\u6001\u8FB9\u6700\u591A 64 \u6761");let d=new Set;return r.map((s,a)=>{let c=`${t}/${i}/${a}`;if(!Jt(s)||Object.keys(s).some(u=>u!=="from"&&u!=="to")||!eo(s.from)||!eo(s.to)||s.from===s.to)return he(c,"\u72B6\u6001\u8FB9\u5FC5\u987B\u5305\u542B\u4E0D\u540C\u7684\u6709\u6548 from/to");let f=JSON.stringify([s.from,s.to]);return d.has(f)?he(c,"\u72B6\u6001\u8FB9\u4E0D\u80FD\u91CD\u590D"):(d.add(f),{from:s.from,to:s.to})}).sort((s,a)=>to(s.from,a.from)||to(s.to,a.to))},n=i=>{let r=e[i];return!Array.isArray(r)||r.length<1||r.length>16||r.some(d=>!eo(d))||new Set(r).size!==r.length?he(`${t}/${i}`,"\u72B6\u6001\u96C6\u5408\u5FC5\u987B\u5305\u542B 1 \u5230 16 \u4E2A\u4E0D\u91CD\u590D\u7684\u6709\u6548\u72B6\u6001"):[...r].sort(to)};return{parentTransitions:o("parentTransitions"),childTransitions:o("childTransitions"),fulfilledChildStatuses:n("fulfilledChildStatuses"),lockedParentStatuses:n("lockedParentStatuses")}}function hi(e,t,o="/config/data/resources"){zt(e).forEach((n,i)=>{let r=`${o}/${i}/decimalReservationLifecycle`,d=oo(n.decimalReservationLifecycle,r);if(!d)return;let s=zt(t).map(u=>u.platformAccess?.decimalReservation).filter(u=>Jt(u)&&u.resourceCode===n.code),a=s.find(u=>u.mode==="reserve");if(!a)return he(r,"\u9700\u8981\u540C\u8D44\u6E90\u5DF2\u58F0\u660E\u7684 reserve \u52A8\u4F5C\u6620\u5C04");if(Ci.some(u=>typeof a[u]!="string")||s.some(u=>Ci.some(p=>u[p]!==a[p])))return he(r,"\u540C\u8D44\u6E90\u989D\u5EA6\u52A8\u4F5C\u7684\u5B57\u6BB5\u6620\u5C04\u5FC5\u987B\u4E00\u81F4");let c=zt(n.schema?.fields).find(u=>u.code===a.statusFieldCode);if(c?.type!=="option.single")return he(r,"\u989D\u5EA6\u72B6\u6001\u5B57\u6BB5\u5FC5\u987B\u4E3A option.single");let f=new Set(zt(c.options).map(u=>u.value));for(let u of no)if((u==="parentTransitions"||u==="childTransitions"?d[u].flatMap(_=>[_.from,_.to]):d[u]).some(_=>!f.has(_)))return he(`${r}/${u}`,"\u72B6\u6001\u5FC5\u987B\u6765\u81EA\u989D\u5EA6\u72B6\u6001\u5B57\u6BB5\u7684\u9009\u9879");if(s.some(u=>u.mode==="reserve"&&Array.isArray(u.eligibleParentStatuses)&&u.eligibleParentStatuses.some(p=>d.lockedParentStatuses.includes(String(p)))))return he(`${r}/lockedParentStatuses`,"\u9501\u5B9A\u7236\u72B6\u6001\u4E0D\u80FD\u5141\u8BB8\u65B0\u9884\u7559")})}import{createHash as _a}from"crypto";var io=new Set(["option.single","user.single","department.single","resource-ref.single"]),ga=new Set(["option.multiple","cascade.single","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","address","location","json"]),Si=new Set(["option.multiple","cascade.single","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","file","image"]),Aa=new Set(["option.single","user.single","department.single","resource-ref.single","signature","address","location"]),Ea=new Set([...io,...Si,"signature","address","location","json"]);function El(e,t){let o=new Set([...Array.isArray(t?.list?.searchableFields)?t.list.searchableFields:[],...Object.entries(t?.fields||{}).filter(([,n])=>n?.searchable===!0).map(([n])=>n)]);return e.map(n=>Ia(n,o.has(n.code))).sort((n,i)=>n.code.localeCompare(i.code))}function Ia(e,t=!1){let o=e.type==="date-range"||e.type==="datetime-range";if(o&&e.rangeBoundary!=="closed"&&e.rangeBoundary!=="half-open")throw new Error("OPENXIANGDA_NATIVE_DATA_RANGE_BOUNDARY_INVALID");return{code:e.code,type:e.type,nullable:!0,indexed:e.indexed===!0,storage:Oa(e),index:ba(e,t),...o?{rangeBoundary:e.rangeBoundary}:{},...e.type==="serial-number"?{serial:{prefix:e.serial?.prefix||"",digits:e.serial?.digits??6,start:e.serial?.start??1}}:{},...e.type==="subtable"&&e.subtable?{subtable:{resourceCode:e.subtable.resourceCode,foreignKey:e.subtable.foreignKey,orderField:e.subtable.orderField,maxRows:e.subtable.maxRows??20}}:{}}}function Il(e,t){if(t.type==="subtable")return null;let o=le(t.code),n=Di(e,t),i=[n?` DEFAULT ${n}`:"",Na(o,t),ya(o,t)].join("");return`${o} ${t.storage}${i}`}function yl(e,t){return Di(e,t)}function ya(e,t){if(t.type!=="date-range"&&t.type!=="datetime-range")return"";if(t.rangeBoundary!=="closed"&&t.rangeBoundary!=="half-open")throw new Error("OPENXIANGDA_NATIVE_DATA_RANGE_BOUNDARY_INVALID");let o=t.type==="datetime-range"&&t.rangeBoundary==="closed";return` CHECK (${e} IS NULL OR (NOT isempty(${e}) AND lower(${e}) IS NOT NULL AND upper(${e}) IS NOT NULL AND lower_inc(${e}) AND ${o?"":"NOT "}upper_inc(${e})))`}function bl(e){return e.type==="serial-number"||Mt(e.type)&&e.type!=="subtable"}function Ol(e,t){return t.filter(o=>o.type==="serial-number").map(o=>{let n=Yt(e,o.code),i=o.serial?.start??1;return`CREATE SEQUENCE IF NOT EXISTS ${n} AS bigint MINVALUE ${i} START WITH ${i} CACHE 1`})}function Nl(e,t){let o=Ht(e);return t.filter(n=>n.type==="serial-number").map(n=>`ALTER SEQUENCE ${Yt(e,n.code)} OWNED BY ${o}.${le(n.code)}`)}function Tl(e,t){return t.filter(o=>o.type==="serial-number").map(o=>`GRANT USAGE, SELECT ON SEQUENCE ${Yt(e,o.code)} TO "openxiangda_data_api"`)}function Rl(e,t){let o=Ht(e),n=[];for(let i of t){if(i.type==="subtable")continue;let r=le(i.code),d=le(ve("idx",e,i.code,i.index));switch(i.index){case"btree":n.push(`CREATE INDEX IF NOT EXISTS ${d} ON ${o} (${r})`);break;case"btree-snapshot-expressions":{let s=le(ve("idx",e,i.code,"snapshot-value")),a=le(ve("idx",e,i.code,"snapshot-label"));n.push(`CREATE INDEX IF NOT EXISTS ${s} ON ${o} ((${r} ->> 'value'))`,`CREATE INDEX IF NOT EXISTS ${a} ON ${o} ((${r} ->> 'label'))`);break}case"gin-jsonb-path":n.push(`CREATE INDEX IF NOT EXISTS ${d} ON ${o} USING GIN (${r} jsonb_path_ops)`);break;case"gist-range":n.push(`CREATE INDEX IF NOT EXISTS ${d} ON ${o} USING GIST (${r})`);break;case"gin-trigram":{let s=io.has(i.type)?`((${r} ->> 'label')) gin_trgm_ops`:`${r} gin_trgm_ops`;n.push(`CREATE INDEX IF NOT EXISTS ${d} ON ${o} USING GIN (${s})`);break}case"none":break}if(i.type==="serial-number"){let s=le(ve("uidx",e,i.code,"serial"));n.push(`CREATE UNIQUE INDEX IF NOT EXISTS ${s} ON ${o} (${r})`)}}return n}function Cl(e,t,o,n){let i=Ht(e),r=Ht(t),d=le(ve("uidx",e,"environment_id","subtable-parent")),s=le(ve("idx",t,o,n,"subtable-child")),a=le(ve("fk",t,o,e)),c=le(o),f=le(n);return[`CREATE UNIQUE INDEX IF NOT EXISTS ${d} ON ${i} ("tenant_id", "app_code", "environment_key", "id")`,`CREATE INDEX IF NOT EXISTS ${s} ON ${r} ("tenant_id", "app_code", "environment_key", ${c}, ${f}, "id")`,`DO $native_subtable$ BEGIN
2
- ALTER TABLE ${r}
1
+ import{createHash as Ls}from"node:crypto";function Fs(e){if(!e||typeof e!="object")return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function wn(e,t){if(e===null)return"null";if(typeof e=="string"||typeof e=="boolean")return JSON.stringify(e);if(typeof e=="number"){if(!Number.isFinite(e))throw new TypeError(`JSON number must be finite: ${t}`);return JSON.stringify(e)}if(Array.isArray(e))return`[${e.map((n,r)=>wn(n,`${t}[${r}]`)).join(",")}]`;if(Fs(e))return`{${Object.keys(e).filter(r=>e[r]!==void 0).sort((r,i)=>r===i?0:r<i?-1:1).map(r=>`${JSON.stringify(r)}:${wn(e[r],`${t}.${r}`)}`).join(",")}}`;let o=e instanceof Date?"Date":e?.constructor?.name||typeof e;throw new TypeError(`Value is not JSON serializable: ${t} (${o})`)}function X(e){return wn(e,"$")}function Z(e){return Ls("sha256").update(X(e)).digest("hex")}var Wc=200,xs=["text.short","uuid","option.single","resource-ref.single"],Sn=/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/,tr=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,nr=new Set(["__proto__","prototype","constructor"]),Dn=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&[Object.prototype,null].includes(Object.getPrototypeOf(e)),er=(e,t)=>Object.keys(e).every(o=>t.includes(o)),et=(e,t)=>typeof e=="string"&&e.length>0&&e.trim()===e&&e.length<=t,Ue=class extends Error{constructor(o,n){super(`${o}: ${n}`);this.code=o;this.pointer=n}code;pointer};function ne(e,t){throw new Ue(e,t)}function xt(e,t,o){if(e===void 0)return;["user.single","user.multiple"].includes(t)||ne("DATA_USER_CANDIDATES_FIELD_TYPE_INVALID",o),(!Dn(e)||!er(e,["kind","roleCode","scope","pageSize"])||e.kind!=="app-role"||!et(e.roleCode,128)||!Sn.test(String(e.roleCode)))&&ne("DATA_USER_CANDIDATES_SOURCE_INVALID",o),e.pageSize!==void 0&&(!Number.isSafeInteger(e.pageSize)||Number(e.pageSize)<1||Number(e.pageSize)>50)&&ne("DATA_USER_CANDIDATES_PAGE_SIZE_INVALID",`${o}/pageSize`);let n;if(e.scope!==void 0){let r=e.scope;(!Dn(r)||!er(r,["dimensionCode","operation","field","value","creation"])||!et(r.dimensionCode,128)||!Sn.test(String(r.dimensionCode))||!et(r.operation,64)||!Sn.test(String(r.operation))||Object.hasOwn(r,"field")===Object.hasOwn(r,"value"))&&ne("DATA_USER_CANDIDATES_SCOPE_INVALID",`${o}/scope`),r.creation!==void 0&&(r.creation!=="prospective"||!Object.hasOwn(r,"field"))&&ne("DATA_USER_CANDIDATES_SCOPE_INVALID",`${o}/scope/creation`),Object.hasOwn(r,"field")?((!et(r.field,63)||!tr.test(String(r.field))||nr.has(String(r.field)))&&ne("DATA_USER_CANDIDATES_SCOPE_FIELD_INVALID",`${o}/scope/field`),n={dimensionCode:String(r.dimensionCode),operation:String(r.operation),field:String(r.field),...r.creation==="prospective"?{creation:"prospective"}:{}}):(et(r.value,255)||ne("DATA_USER_CANDIDATES_SCOPE_VALUE_INVALID",`${o}/scope/value`),n={dimensionCode:String(r.dimensionCode),operation:String(r.operation),value:String(r.value)})}return{kind:"app-role",roleCode:String(e.roleCode),...n?{scope:n}:{},...e.pageSize===void 0?{}:{pageSize:Number(e.pageSize)}}}function kn(e){return e.some(t=>t.schema.fields.some(o=>{let n=o.userCandidates?.scope;return n?.creation==="prospective"||!!(n?.field&&t.schema.fields.find(r=>r.code===n.field)?.type==="resource-ref.single")}))}function or(e,t,o,n){for(let[r,i]of e.entries()){let d=`${n}/${r}/userCandidates`,s=xt(i.userCandidates,i.type,d);if(s&&(t.has(s.roleCode)||ne("DATA_USER_CANDIDATES_ROLE_UNDECLARED",`${d}/roleCode`),s.scope&&!o.has(s.scope.dimensionCode)&&ne("DATA_USER_CANDIDATES_DIMENSION_UNDECLARED",`${d}/scope/dimensionCode`),s.scope?.field)){let a=e.find(c=>c.code===s.scope.field);(!a||!xs.some(c=>c===a.type))&&ne("DATA_USER_CANDIDATES_SCOPE_FIELD_INVALID",`${d}/scope/field`)}}}function js(e,t,o,n){let r=e.subject.factProjection,i=typeof t.inputPath=="string"&&Object.entries(r).some(([c,f])=>(t.inputPath===c||t.inputPath.startsWith(`${c}.`))&&o.get(f)?.userCandidates!==void 0);if(t.candidateField===void 0&&!i)return;(t.provider!=="form_field_users"||!t.candidateField||!tr.test(t.candidateField)||nr.has(t.candidateField)||!t.inputPath||r[t.inputPath]!==t.candidateField)&&ne("WORKFLOW_USER_CANDIDATES_FIELD_BINDING_REQUIRED",n),(t.roleCode!==void 0||t.scope!==void 0||t.routing!==void 0)&&ne("WORKFLOW_USER_CANDIDATES_SOURCE_OVERRIDE_FORBIDDEN",n);let d=o.get(t.candidateField),s=d&&xt(d.userCandidates,d.type,`${n}/candidateField`);s||ne("WORKFLOW_USER_CANDIDATES_FIELD_UNDECLARED",`${n}/candidateField`);let a;if(s.scope?.field){let c=Object.entries(r).filter(([,f])=>f===s.scope.field).map(([f])=>f);c.length!==1&&ne("WORKFLOW_USER_CANDIDATES_SCOPE_PROJECTION_REQUIRED",n),a=c[0]}return{fieldCode:d.code,inputPath:t.inputPath,source:s,...a?{scopeInputPath:a}:{}}}function rr(e,t,o,n,r=new Map){for(let[i,d]of Object.entries(t.bindings))js(e,d,o,`${n}/${i}`);for(let[i,d]of Object.entries(e.taskPages||{})){let s=new Set(d.fields.filter(a=>a.readonly!==!0).map(a=>a.code));for(let a of d.fields){let c=o.get(a.code)?.userCandidates?.scope;if(s.has(a.code)&&c?.field&&s.has(c.field)&&ne("WORKFLOW_USER_CANDIDATES_SCOPE_WRITE_FORBIDDEN",`${n}/taskPages/${i}/${a.code}`),!s.has(a.code)||!a.subtable)continue;let f=o.get(a.code)?.subtable?.resourceCode,u=f?r.get(f):void 0;a.subtable.fields.some(p=>p.readonly!==!0&&u?.get(p.code)?.userCandidates)&&ne("WORKFLOW_USER_CANDIDATES_OWNED_FIELD_UNSUPPORTED",`${n}/taskPages/${i}/${a.code}`)}}}function Mc(e,t){if(!e.scope)return;let o=e.scope.field?t[e.scope.field]:e.scope.value,n=Dn(o)?o.value:o;return et(n,255)||ne("DATA_USER_CANDIDATES_SCOPE_VALUE_REQUIRED",e.scope.field||"scope"),String(n)}var ir=200,Pn=205;function vn(e,t=[]){return e.some(o=>o.schema.fields.length>100)||t.some(o=>Object.values(o.definition.taskPages||{}).some(n=>(n.fields?.length??0)>64)||[o.launch?.submission?.create,o.launch?.submission?.existing].some(n=>Object.keys(n?.inputs||{}).length>64))}var Be=500,$n=500,tt=1e3,sr=2*tt+16,Bc=2*1024*1024,Kc=2*1024*1024;function mt(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=1&&e<=tt}function jt(e){if(e.ownedRowLimit===void 0)return $n;if(!mt(e.ownedRowLimit))throw new Error("NATIVE_DATA_OWNED_ROW_LIMIT_INVALID");return e.ownedRowLimit}function Vn(e){return e.some(t=>(t.schema.ownedRowLimit??$n)>$n)}function Ln(e){return e.some(t=>{let o=t.schema.fields.filter(n=>n.type==="subtable").map(n=>n.subtable?.maxRows??20);return o.some(n=>n>100)||o.reduce((n,r)=>n+r,0)>400})}function Gc(e){try{return new TextEncoder().encode(JSON.stringify(e)).byteLength}catch{return 1/0}}var lr=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,jn=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,Ws=["text.short","text.long","text.rich","number.integer","number.decimal","boolean","date","time","datetime","date-range","datetime-range","option.single","option.multiple","cascade.single","cascade.multiple","user.single","user.multiple","department.single","department.multiple","resource-ref.single","resource-ref.multiple","image","signature","address","location","uuid","json","file","serial-number","subtable"];function Wn(e){return e.some(t=>t.schema.fields.some(o=>(o.type==="datetime"||o.type==="datetime-range")&&o.timePrecision==="minute"))}function Mn(e){return e.some(t=>t.schema.fields.some(o=>o.type==="subtable"&&(o.subtable?.minRows??0)>0))}var Ms=new Set(Ws),ur=new Set(["option.multiple","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","file","image","subtable"]),ar=new Set(["option.single","option.multiple","cascade.single","cascade.multiple"]),dr=new Set(["resource-ref.single","resource-ref.multiple"]),Un=[{code:"id",type:"uuid",nullable:!1},{code:"revision",type:"number.integer",nullable:!1},{code:"created_by",type:"text.short",nullable:!1},{code:"updated_by",type:"text.short",nullable:!1},{code:"created_at",type:"datetime",nullable:!1},{code:"updated_at",type:"datetime",nullable:!1}],nt=new Map(Un.map(e=>[e.code,e])),Re=class extends Error{constructor(o,n){super(o);this.code=o;this.pointer=n;this.name="NativeDataFieldContractV2Error"}code;pointer};function Ut(e){return ur.has(e)}function Bt(e,t={}){return e.type!=="serial-number"&&t.system!==!0&&e.nullable===!1&&(!Ut(e.type)||t.requiredHint===!0)}function Bn(e,t,o=500){Array.isArray(e)||k("NATIVE_ARRAY_REQUIRED",t),e.length===0&&k("NATIVE_DATA_FIELDS_REQUIRED",t),e.length>o&&k("NATIVE_ARRAY_LIMIT_EXCEEDED",t);let n=new Set;return e.map((r,i)=>{let d=`${t}/${i}`,s=Ee(r,d);ye(s,["code","type","nullable","indexed","options","source","userCandidates","maxLength","precision","scale","exactDecimal","min","max","rangeBoundary","timePrecision","file","serial","subtable"],d);let a=be(s.code,`${d}/code`,63);lr.test(a)||k("NATIVE_FIELD_CODE_INVALID",`${d}/code`),n.has(a)&&k("NATIVE_DATA_FIELD_DUPLICATE",`${d}/code`),n.add(a);let c=be(s.type,`${d}/type`,32);Ms.has(c)||k("NATIVE_DATA_FIELD_TYPE_INVALID",`${d}/type`);let f=c,u=xn(s.nullable,`${d}/nullable`),p=xn(s.indexed,`${d}/indexed`);u===!0&&ur.has(f)&&k("NATIVE_DATA_MULTI_FIELD_NULLABLE_INVALID",`${d}/nullable`);let _=Ks(s.options,f,d),E=Gs(s.source,f,d),A=xt(s.userCandidates,f,`${d}/userCandidates`),O=qs(s,f,d),b=xn(s.exactDecimal,`${d}/exactDecimal`);b!==void 0&&f!=="number.decimal"&&k("NATIVE_DATA_FIELD_EXACT_DECIMAL_TYPE_INVALID",`${d}/exactDecimal`);let g=Us(s.rangeBoundary,f,d),I=Js(s.file,f,d),T=Hs(s.serial,f,d),l=Ys(s.subtable,f,d);return{code:a,type:f,...u===void 0?{}:{nullable:u},...p===void 0?{}:{indexed:p},..._?{options:_}:{},...E?{source:E}:{},...A?{userCandidates:A}:{},...O,...b===void 0?{}:{exactDecimal:b},...g?{rangeBoundary:g}:{},...I?{file:I}:{},...T?{serial:T}:{},...l?{subtable:l}:{}}})}function Us(e,t,o){let n=`${o}/rangeBoundary`;if(!(t==="date-range"||t==="datetime-range")){e!==void 0&&k("NATIVE_DATA_FIELD_RANGE_BOUNDARY_TYPE_INVALID",n);return}return e!=="closed"&&e!=="half-open"&&k("NATIVE_DATA_FIELD_RANGE_BOUNDARY_REQUIRED",n),e}function fr(e,t){Array.isArray(e)||k("NATIVE_ARRAY_REQUIRED",t);let o=new Map;e.forEach((n,r)=>{let i=`${t}/${r}`,d=Ee(n,i),s=be(d.code,`${i}/code`,64);(!jn.test(s)||o.has(s))&&k("NATIVE_RESOURCE_CODE_INVALID",`${i}/code`);let a=Ee(d.schema,`${i}/schema`);a.ownedRowLimit!==void 0&&!mt(a.ownedRowLimit)&&k("NATIVE_DATA_OWNED_ROW_LIMIT_INVALID",`${i}/schema/ownedRowLimit`),o.set(s,{pointer:i,ownedRowLimit:jt(a),fields:Bn(a.fields,`${i}/schema/fields`)})});for(let[n,r]of o){let i=new Map(r.fields.map(s=>[s.code,s]));r.fields.filter(s=>s.type==="subtable").reduce((s,a)=>s+(a.subtable?.maxRows??20),0)>r.ownedRowLimit&&k("NATIVE_DATA_FIELD_SUBTABLE_AGGREGATE_MAX_ROWS_EXCEEDED",`${r.pointer}/schema/fields`),r.fields.forEach((s,a)=>{let c=`${r.pointer}/schema/fields/${a}`;if(s.source&&Bs(s.source,i,o,`${c}/source`),s.subtable){let f=o.get(s.subtable.resourceCode);(!f||s.subtable.resourceCode===n)&&k("NATIVE_DATA_FIELD_SUBTABLE_TARGET_MISSING",`${c}/subtable/resourceCode`);let u=f.fields.find(_=>_.code===s.subtable?.foreignKey);(!u||u.type!=="uuid"||u.nullable!==!1)&&k("NATIVE_DATA_FIELD_SUBTABLE_FOREIGN_KEY_INVALID",`${c}/subtable/foreignKey`);let p=f.fields.find(_=>_.code===s.subtable?.orderField);(!p||p.type!=="number.integer"||p.nullable!==!1)&&k("NATIVE_DATA_FIELD_SUBTABLE_ORDER_FIELD_INVALID",`${c}/subtable/orderField`)}})}}function pr(e,t,o){if(e===void 0)return[];(!Array.isArray(e)||e.length>20)&&k("NATIVE_DATA_RESOURCE_INVARIANTS_INVALID",o);let n=new Map(t.map(i=>[i.code,i])),r=new Set;return e.map((i,d)=>{let s=`${o}/${d}`,a=Ee(i,s);ye(a,["code","message","expression"],s);let c=be(a.code,`${s}/code`,128);(!/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/.test(c)||r.has(c))&&k("NATIVE_DATA_RESOURCE_INVARIANT_CODE_INVALID",`${s}/code`),r.add(c);let f=Mt(a.message,`${s}/message`,500);f!==void 0&&f.length===0&&k("NATIVE_DATA_RESOURCE_INVARIANT_MESSAGE_INVALID",`${s}/message`);let u=Ee(a.expression,`${s}/expression`);if(u.kind==="nonBlankTextWhenOption"){ye(u,["kind","optionField","optionValue","textField"],`${s}/expression`);let g=Te(u.optionField,`${s}/expression/optionField`),I=Te(u.textField,`${s}/expression/textField`),T=be(u.optionValue,`${s}/expression/optionValue`,128),l=n.get(g),y=n.get(I);return(!l||!y)&&k("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_UNKNOWN",`${s}/expression`),(l.type!=="option.single"||!["text.short","text.long"].includes(y.type)||!l.options?.some(R=>R.value===T))&&k("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_TYPES_INVALID",`${s}/expression`),{code:c,...f===void 0?{}:{message:f},expression:{kind:"nonBlankTextWhenOption",optionField:g,optionValue:T,textField:I}}}ye(u,["leftField","operator","rightField"],`${s}/expression`);let p=Te(u.leftField,`${s}/expression/leftField`),_=Te(u.rightField,`${s}/expression/rightField`),E=n.get(p),A=n.get(_);(!E||!A)&&k("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_UNKNOWN",`${s}/expression`),E.type===A.type||["number.integer","number.decimal"].includes(E.type)&&["number.integer","number.decimal"].includes(A.type)||k("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_TYPES_INVALID",`${s}/expression`);let b=String(u.operator);return["eq","neq","gt","gte","lt","lte"].includes(b)||k("NATIVE_DATA_RESOURCE_INVARIANT_OPERATOR_INVALID",`${s}/expression/operator`),!["eq","neq"].includes(b)&&!["number.integer","number.decimal","date","time","datetime","text.short","text.long","text.rich","serial-number","uuid"].includes(E.type)&&k("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_TYPES_INVALID",`${s}/expression`),{code:c,...f===void 0?{}:{message:f},expression:{leftField:p,operator:b,rightField:_}}})}function Bs(e,t,o,n){let r=o.get(e.resourceCode);r||k("NATIVE_DATA_FIELD_SOURCE_TARGET_MISSING",`${n}/resourceCode`);let i=new Map(r.fields.map(s=>[s.code,s])),d=i.get(e.labelField);(!d||!["text.short","text.long"].includes(d.type))&&k("NATIVE_DATA_FIELD_SOURCE_LABEL_INVALID",`${n}/labelField`);for(let s of["searchFields","descriptionFields","snapshotFields"])for(let a of e[s]||[])i.has(a)||k("NATIVE_DATA_FIELD_SOURCE_FIELD_MISSING",`${n}/${s}`);for(let[s,a]of(e.filters||[]).entries())i.has(a.field)||k("NATIVE_DATA_FIELD_SOURCE_FILTER_FIELD_MISSING",`${n}/filters/${s}/field`),"binding"in a&&!t.has(a.binding.field)&&k("NATIVE_DATA_FIELD_SOURCE_BINDING_FIELD_MISSING",`${n}/filters/${s}/binding/field`)}function Ks(e,t,o){let n=`${o}/options`;if(e===void 0){ar.has(t)&&k("NATIVE_DATA_FIELD_OPTIONS_REQUIRED",n);return}(!ar.has(t)||!Array.isArray(e))&&k("NATIVE_DATA_FIELD_OPTIONS_TYPE_INVALID",n),(e.length<1||e.length>100)&&k("NATIVE_DATA_FIELD_OPTIONS_INVALID",n);let r=0,i=(d,s,a)=>{a>5&&k("NATIVE_DATA_FIELD_OPTIONS_DEPTH_EXCEEDED",s);let c=new Set;return d.map((f,u)=>{r+=1,r>1e3&&k("NATIVE_DATA_FIELD_OPTIONS_COUNT_EXCEEDED",n);let p=`${s}/${u}`,_=Ee(f,p);ye(_,["label","value","description","color","children"],p);let E=be(_.label,`${p}/label`,500),A=be(_.value,`${p}/value`,500);c.has(A)&&k("NATIVE_DATA_FIELD_OPTION_VALUE_DUPLICATE",`${p}/value`),c.add(A);let O=Mt(_.description,`${p}/description`,2e3),b=Mt(_.color,`${p}/color`,64),g;return _.children!==void 0&&((!t.startsWith("cascade.")||!Array.isArray(_.children))&&k("NATIVE_DATA_FIELD_OPTION_CHILDREN_INVALID",`${p}/children`),(_.children.length<1||_.children.length>100)&&k("NATIVE_DATA_FIELD_OPTION_CHILDREN_INVALID",`${p}/children`),g=i(_.children,`${p}/children`,a+1)),{label:E,value:A,...O===void 0?{}:{description:O},...b===void 0?{}:{color:b},...g?{children:g}:{}}})};return i(e,n,1)}function Gs(e,t,o){let n=`${o}/source`;if(e===void 0){dr.has(t)&&k("NATIVE_DATA_FIELD_SOURCE_REQUIRED",n);return}dr.has(t)||k("NATIVE_DATA_FIELD_SOURCE_TYPE_INVALID",n);let r=Ee(e,n);ye(r,["kind","resourceCode","labelField","searchFields","descriptionFields","snapshotFields","filters","pageSize","loadMode","clearOnBindingChange"],n),r.kind!=="resource"&&k("NATIVE_DATA_FIELD_SOURCE_KIND_INVALID",`${n}/kind`);let i=be(r.resourceCode,`${n}/resourceCode`,64);jn.test(i)||k("NATIVE_RESOURCE_CODE_INVALID",`${n}/resourceCode`);let d=Te(r.labelField,`${n}/labelField`),s=Fn(r.searchFields,`${n}/searchFields`,10),a=Fn(r.descriptionFields,`${n}/descriptionFields`,10),c=Fn(r.snapshotFields,`${n}/snapshotFields`,50),f=Ke(r.pageSize,`${n}/pageSize`,1,100),u;r.loadMode!==void 0&&(["search","all"].includes(String(r.loadMode))||k("NATIVE_DATA_FIELD_SOURCE_LOAD_MODE_INVALID",`${n}/loadMode`),u=r.loadMode);let p=zs(r.filters,`${n}/filters`);return r.clearOnBindingChange!==void 0&&typeof r.clearOnBindingChange!="boolean"&&k("NATIVE_DATA_FIELD_SOURCE_BINDING_RESET_INVALID",`${n}/clearOnBindingChange`),{kind:"resource",resourceCode:i,labelField:d,...s?{searchFields:s}:{},...a?{descriptionFields:a}:{},...c?{snapshotFields:c}:{},...p?{filters:p}:{},...f===void 0?{}:{pageSize:f},...u?{loadMode:u}:{},...r.clearOnBindingChange===void 0?{}:{clearOnBindingChange:r.clearOnBindingChange}}}function zs(e,t){if(e!==void 0)return(!Array.isArray(e)||e.length>20)&&k("NATIVE_DATA_FIELD_SOURCE_FILTERS_INVALID",t),e.map((o,n)=>{let r=`${t}/${n}`,i=Ee(o,r),d=Object.prototype.hasOwnProperty.call(i,"value"),s=Object.prototype.hasOwnProperty.call(i,"binding");ye(i,d?["field","operator","value"]:["field","operator","binding"],r),d===s&&k("NATIVE_DATA_FIELD_SOURCE_FILTER_VALUE_INVALID",r);let a=Te(i.field,`${r}/field`);["eq","in"].includes(String(i.operator))||k("NATIVE_DATA_FIELD_SOURCE_FILTER_OPERATOR_INVALID",`${r}/operator`);let c=i.operator;if(d)return{field:a,operator:c,value:i.value};let f=Ee(i.binding,`${r}/binding`);return ye(f,["kind","field"],`${r}/binding`),f.kind!=="field"&&k("NATIVE_DATA_FIELD_SOURCE_BINDING_KIND_INVALID",`${r}/binding/kind`),{field:a,operator:c,binding:{kind:"field",field:Te(f.field,`${r}/binding/field`)}}})}function qs(e,t,o){let n={};if(e.maxLength!==void 0&&(["text.short","text.long","text.rich"].includes(t)||k("NATIVE_DATA_FIELD_MAX_LENGTH_TYPE_INVALID",`${o}/maxLength`),n.maxLength=Wt(e.maxLength,`${o}/maxLength`,1,1e6)),(e.precision!==void 0||e.scale!==void 0)&&((t!=="number.decimal"||e.precision===void 0)&&k("NATIVE_DATA_FIELD_DECIMAL_CONFIG_INVALID",o),n.precision=Wt(e.precision,`${o}/precision`,1,1e3),n.scale=e.scale===void 0?0:Wt(e.scale,`${o}/scale`,0,n.precision)),e.min!==void 0||e.max!==void 0){["number.integer","number.decimal"].includes(t)||k("NATIVE_DATA_FIELD_NUMERIC_BOUNDS_TYPE_INVALID",o);let r=cr(e.min,`${o}/min`),i=cr(e.max,`${o}/max`);t==="number.integer"&&[r,i].some(d=>d!==void 0&&!Number.isSafeInteger(d))&&k("NATIVE_DATA_FIELD_NUMERIC_BOUNDS_INVALID",o),r!==void 0&&i!==void 0&&r>i&&k("NATIVE_DATA_FIELD_NUMERIC_BOUNDS_INVALID",o),r!==void 0&&(n.min=r),i!==void 0&&(n.max=i)}return e.timePrecision!==void 0&&((!["time","datetime","datetime-range"].includes(t)||!["minute","second"].includes(e.timePrecision))&&k("NATIVE_DATA_FIELD_TIME_PRECISION_INVALID",`${o}/timePrecision`),n.timePrecision=e.timePrecision),n}function Js(e,t,o){if(e===void 0)return;let n=`${o}/file`;["file","image","signature"].includes(t)||k("NATIVE_DATA_FIELD_FILE_TYPE_INVALID",n);let r=Ee(e,n);ye(r,["maxCount","maxSizeMb","accept"],n);let i=Ke(r.maxCount,`${n}/maxCount`,1,100);t==="signature"&&i!==void 0&&i!==1&&k("NATIVE_DATA_FIELD_SIGNATURE_COUNT_INVALID",`${n}/maxCount`);let d=Ke(r.maxSizeMb,`${n}/maxSizeMb`,1,1024),s;return r.accept!==void 0&&((!Array.isArray(r.accept)||r.accept.length>50)&&k("NATIVE_DATA_FIELD_FILE_ACCEPT_INVALID",`${n}/accept`),s=r.accept.map((a,c)=>be(a,`${n}/accept/${c}`,255)),new Set(s).size!==s.length&&k("NATIVE_DATA_FIELD_FILE_ACCEPT_INVALID",`${n}/accept`)),{...i===void 0?{}:{maxCount:i},...d===void 0?{}:{maxSizeMb:d},...s===void 0?{}:{accept:s}}}function Hs(e,t,o){let n=`${o}/serial`;if(e===void 0){t==="serial-number"&&k("NATIVE_DATA_FIELD_SERIAL_REQUIRED",n);return}t!=="serial-number"&&k("NATIVE_DATA_FIELD_SERIAL_TYPE_INVALID",n);let r=Ee(e,n);ye(r,["prefix","digits","start"],n);let i=Mt(r.prefix,`${n}/prefix`,64),d=Ke(r.digits,`${n}/digits`,1,32),s=Ke(r.start,`${n}/start`,0,Number.MAX_SAFE_INTEGER);return{...i===void 0?{}:{prefix:i},...d===void 0?{}:{digits:d},...s===void 0?{}:{start:s}}}function Ys(e,t,o){let n=`${o}/subtable`;if(e===void 0){t==="subtable"&&k("NATIVE_DATA_FIELD_SUBTABLE_REQUIRED",n);return}t!=="subtable"&&k("NATIVE_DATA_FIELD_SUBTABLE_TYPE_INVALID",n);let r=Ee(e,n);ye(r,["resourceCode","foreignKey","orderField","minRows","maxRows"],n);let i=be(r.resourceCode,`${n}/resourceCode`,64);jn.test(i)||k("NATIVE_RESOURCE_CODE_INVALID",`${n}/resourceCode`);let d=Te(r.foreignKey,`${n}/foreignKey`),s=Te(r.orderField,`${n}/orderField`);s===d&&k("NATIVE_DATA_FIELD_SUBTABLE_ORDER_FIELD_INVALID",`${n}/orderField`);let a=Ke(r.maxRows,`${n}/maxRows`,1,Be),c=Ke(r.minRows,`${n}/minRows`,0,Be);return(c??0)>(a??20)&&k("NATIVE_DATA_FIELD_SUBTABLE_MIN_ROWS_INVALID",`${n}/minRows`),{resourceCode:i,foreignKey:d,orderField:s,...c===void 0?{}:{minRows:c},...a===void 0?{}:{maxRows:a}}}function Fn(e,t,o){if(e===void 0)return;(!Array.isArray(e)||e.length>o)&&k("NATIVE_DATA_FIELD_SOURCE_FIELDS_INVALID",t);let n=e.map((r,i)=>Te(r,`${t}/${i}`));return new Set(n).size!==n.length&&k("NATIVE_DATA_FIELD_SOURCE_FIELDS_INVALID",t),n}function Te(e,t){let o=be(e,t,63);return lr.test(o)||k("NATIVE_FIELD_CODE_INVALID",t),o}function Ee(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&k("NATIVE_OBJECT_REQUIRED",t),e}function ye(e,t,o){let n=new Set(t);for(let r of Object.keys(e))n.has(r)||k("NATIVE_PROPERTY_UNKNOWN",`${o}/${r}`)}function be(e,t,o){return(typeof e!="string"||e.length===0||e.length>o)&&k("NATIVE_STRING_INVALID",t),e}function Mt(e,t,o){if(e!==void 0)return(typeof e!="string"||e.length>o)&&k("NATIVE_STRING_INVALID",t),e}function xn(e,t){if(e!==void 0)return typeof e!="boolean"&&k("NATIVE_BOOLEAN_REQUIRED",t),e}function Ke(e,t,o,n){if(e!==void 0)return Wt(e,t,o,n)}function cr(e,t){if(e!==void 0)return(typeof e!="number"||!Number.isFinite(e))&&k("NATIVE_NUMBER_REQUIRED",t),e}function Wt(e,t,o,n){return(!Number.isSafeInteger(e)||Number(e)<o||Number(e)>n)&&k("NATIVE_INTEGER_OUT_OF_RANGE",t),Number(e)}function k(e,t){throw new Re(e,t)}var Kt=["created_by","updated_by","created_at","updated_at"];function _t(e){return Kt.includes(e)}function mr(e){return Kt.some(t=>Object.prototype.hasOwnProperty.call(e.fieldPolicies||{},t))}var Xs=Un.map(e=>e.code);function _r(e){return Xs.includes(e)}var Zs=["eq","neq","gt","gte","lt","lte","contains","startsWith","endsWith","in","between","has","hasAny","hasAll","overlaps","containedBy","jsonContains","isEmpty","isNotEmpty"],Qs=new Set(Zs);function Zc(e){return Qs.has(String(e))}var Kn=["eq","neq","contains","startsWith","endsWith","in","isEmpty","isNotEmpty"],gt=["eq","neq","gt","gte","lt","lte","between","in","isEmpty"],ea=["eq","neq","in","isEmpty"],Gt=["eq","neq","in","isEmpty","isNotEmpty"],ot=["has","hasAny","hasAll","isEmpty","isNotEmpty"],gr=["overlaps","contains","containedBy","isEmpty"],Gn=["jsonContains","isEmpty","isNotEmpty"],zn=["isEmpty","isNotEmpty"],ta={"text.short":Kn,"text.long":Kn,"text.rich":Kn,"number.integer":gt,"number.decimal":gt,boolean:ea,date:gt,time:gt,datetime:gt,"date-range":gr,"datetime-range":gr,"option.single":Gt,"option.multiple":ot,"cascade.single":ot,"cascade.multiple":ot,"user.single":Gt,"user.multiple":ot,"department.single":Gt,"department.multiple":ot,"resource-ref.single":Gt,"resource-ref.multiple":ot,file:zn,image:zn,signature:zn,address:Gn,location:Gn,uuid:["eq","neq","in","isEmpty"],json:Gn,"serial-number":["eq","neq","in","contains","startsWith"],subtable:[]},na=new Set(["text.short","text.long","text.rich","option.single","user.single","department.single","resource-ref.single","serial-number"]),oa=new Set(["option.multiple","cascade.single","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","file","image","signature","address","location","json","subtable"]);function Er(e){return ta[e]}function Qc(e,t){return Er(e).includes(t)}function qn(e){return na.has(e)}function At(e){return!oa.has(e)}function Ir(e){return Er(e).length>0}var Ar=new Set(["number.integer","number.decimal"]),yr=new Set(["text.short","text.long","number.integer","number.decimal","date","time","datetime","serial-number"]),ra=new Set([...yr,"boolean","uuid"]),ia=new Set(["option.single","user.single","department.single","resource-ref.single"]);function el(e,t){return t==="sum"||t==="avg"?Ar.has(e)?{valueExpression:"column",numericResult:!0}:null:t==="min"||t==="max"?yr.has(e)?{valueExpression:"column",numericResult:Ar.has(e)}:null:ia.has(e)?{valueExpression:"snapshot-value",numericResult:!0}:ra.has(e)?{valueExpression:"column",numericResult:!0}:null}var Hn=["version","maxBytes","fields"];function Or(e,t){if(e===void 0)return;let o=Jn(e,t);br(o,Hn,t);let n=zt(o.version,`${t}/version`,1,1e6),r=zt(o.maxBytes,`${t}/maxBytes`,2,196608);(!n||!r)&&ce("NATIVE_DATA_DRAFT_STATE_SCHEMA_INVALID",t);let i=Jn(o.fields,`${t}/fields`),d=Object.entries(i);(!d.length||d.length>50)&&ce("NATIVE_DATA_DRAFT_STATE_FIELDS_INVALID",`${t}/fields`);for(let[s,a]of d){let c=`${t}/fields/${s}`;/^[A-Za-z][A-Za-z0-9_]{0,62}$/.test(s)||ce("NATIVE_DATA_DRAFT_STATE_FIELD_CODE_INVALID",c);let f=Jn(a,c),u=Nr(f.type,`${c}/type`,32),p=u==="string"?["type","required","maxLength","enum"]:u==="json.object"?["type","required","maxBytes"]:["type","required"];if(["string","number","integer","boolean","json.object"].includes(u)||ce("NATIVE_DATA_DRAFT_STATE_FIELD_TYPE_INVALID",`${c}/type`),br(f,p,c),aa(f.required,`${c}/required`),u==="string"){let _=zt(f.maxLength,`${c}/maxLength`,1,196608);_||ce("NATIVE_DATA_DRAFT_STATE_FIELD_INVALID",c),f.enum!==void 0&&sa(f.enum,`${c}/enum`,100,!1).some(A=>A.length>_)&&ce("NATIVE_DATA_DRAFT_STATE_FIELD_INVALID",`${c}/enum`)}else if(u==="json.object"){let _=zt(f.maxBytes,`${c}/maxBytes`,2,65536);(!_||_>r)&&ce("NATIVE_DATA_DRAFT_STATE_FIELD_INVALID",c)}}}function sa(e,t,o,n){(!Array.isArray(e)||!n&&e.length===0||e.length>o)&&ce("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t);let r=e.map((i,d)=>Nr(i,`${t}/${d}`,255));return new Set(r).size!==r.length&&ce("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t),r}function Jn(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&ce("NATIVE_OBJECT_REQUIRED",t),e}function br(e,t,o){let n=new Set(t);for(let r of Object.keys(e))n.has(r)||ce("NATIVE_PROPERTY_UNKNOWN",`${o}/${r}`)}function Nr(e,t,o){return(typeof e!="string"||e.length===0||e.length>o)&&ce("NATIVE_STRING_INVALID",t),e}function aa(e,t){e!==void 0&&typeof e!="boolean"&&ce("NATIVE_BOOLEAN_REQUIRED",t)}function zt(e,t,o,n){return(!Number.isSafeInteger(e)||Number(e)<o||Number(e)>n)&&ce("NATIVE_INTEGER_INVALID",t),Number(e)}function ce(e,t){throw new Re(e,t)}var da=500,Pe={surface:["mutationOwner","generated","fields","list","form","detail","mobile","views"],generated:["list","detail","create","update","delete"],field:["label","type","widget","section","requiredHint","system","hidden","readCapabilities","createCapabilities","updateCapabilities","maxLength","precision","scale","exactDecimal","min","max","rangeBoundary","maxCount","maxSizeMb","accept","options","list","searchable","sortable","source","userCandidates","timePrecision","serial","subtable"],list:["actions","fieldOrder","defaultPageSize","searchableFields","filterFields","defaultSort"],defaultSort:["field","order"],form:["layout","fieldOrder","draftState"],detail:["layout","fieldOrder"],layout:["layout","fieldOrder","draftState"],draftState:Hn,mobile:["enabled"]},ca={"text.short":["text","email","phone"],"text.long":["textarea"],"text.rich":["rich-text"],"number.integer":["number","rating"],"number.decimal":["number","money","percent"],boolean:["switch"],date:["date"],time:["time"],datetime:["datetime"],"date-range":["date-range"],"datetime-range":["datetime-range"],"option.single":["select","radio"],"option.multiple":["multi-select","checkbox"],"cascade.single":["cascade"],"cascade.multiple":["cascade"],"user.single":["directory-user"],"user.multiple":["directory-user"],"department.single":["directory-department","scope"],"department.multiple":["directory-department","scope"],"resource-ref.single":["select","radio","resource"],"resource-ref.multiple":["multi-select","checkbox","resource"],file:["attachment"],image:["image"],signature:["signature"],address:["address"],location:["location"],uuid:["readonly"],json:["json"],"serial-number":["readonly"],subtable:["subtable"]};function Zn(e,t,o){if(e===void 0)return;let n=ae(e,o);Ce(n,Pe.surface,o);let r=n.mutationOwner===void 0?"native":De(n.mutationOwner,`${o}/mutationOwner`,16);["native","action","readonly","workflow","queued-command"].includes(r)||W("NATIVE_DATA_SURFACE_MUTATION_OWNER_INVALID",`${o}/mutationOwner`);let i=n.generated===void 0?{}:ae(n.generated,`${o}/generated`);Ce(i,Pe.generated,`${o}/generated`);for(let a of Pe.generated)Xn(i[a],`${o}/generated/${a}`);if(r!=="native")for(let a of["create","update","delete"])i[a]===!0&&W("NATIVE_DATA_SURFACE_MUTATION_OWNER_CONFLICT",`${o}/generated/${a}`);let d=new Map(t.map(a=>[a.code,a])),s=ae(n.fields,`${o}/fields`);for(let a of Object.keys(s))d.has(a)||W("NATIVE_DATA_SURFACE_FIELD_MISSING",`${o}/fields/${a}`);for(let a of t)Object.prototype.hasOwnProperty.call(s,a.code)||W("NATIVE_DATA_SURFACE_FIELD_REQUIRED",`${o}/fields/${a.code}`),ua(s[a.code],a,`${o}/fields/${a.code}`);for(let a of["create","update"]){let c=i[a]??r==="native",f=t.some(u=>{let p=ae(s[u.code],`${o}/fields/${u.code}`);return Rr(u,p,a)});c&&!f&&W("NATIVE_DATA_SURFACE_WRITABLE_FIELDS_REQUIRED",`${o}/generated/${a}`)}if(fa(n.list,d,`${o}/list`),Tr(n.form,d,`${o}/form`,"form"),Tr(n.detail,d,`${o}/detail`,"detail"),n.mobile!==void 0){let a=ae(n.mobile,`${o}/mobile`);Ce(a,Pe.mobile,`${o}/mobile`),Xn(a.enabled,`${o}/mobile/enabled`)}la(n,t,o)}function Qn(e,t){let o=e.views?.find(r=>r.code===t);o||W("NATIVE_DATA_VIEW_NOT_FOUND",`/surface/views/${t}`);let n=new Map((o.sections||[]).flatMap(r=>r.fields.map(i=>[i,r.title])));return{mutationOwner:e.mutationOwner||"native",generated:o.generated,list:o.list,form:o.form,detail:o.detail,mobile:o.mobile,fields:Object.fromEntries(Object.entries(e.fields).map(([r,i])=>{let d={...i};delete d.section;let s=n.get(r);return[r,{...d,...s?{section:s}:{},list:o.list.fieldOrder.includes(r)}]}))}}function la(e,t,o){if(e.views===void 0)return;(!Array.isArray(e.views)||e.views.length>20)&&W("NATIVE_DATA_VIEWS_LIMIT_INVALID",`${o}/views`);let n=new Set;e.views.forEach((r,i)=>{let d=`${o}/views/${i}`,s=ae(r,d);Ce(s,["code","name","generated","list","form","detail","mobile","sections"],d);let a=De(s.code,`${d}/code`,64);(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(a)||n.has(a))&&W("NATIVE_DATA_VIEW_CODE_INVALID",`${d}/code`),n.add(a),De(s.name,`${d}/name`,255),ae(s.generated,`${d}/generated`),ae(s.mobile,`${d}/mobile`);for(let f of["list","detail","create","update","delete"])typeof s.generated[f]!="boolean"&&W("NATIVE_DATA_VIEW_OPERATION_INVALID",`${d}/generated/${f}`);typeof s.mobile.enabled!="boolean"&&W("NATIVE_DATA_VIEW_MOBILE_INVALID",`${d}/mobile/enabled`);for(let f of["list","form","detail"]){let u=ae(s[f],`${d}/${f}`),p=rt(u.fieldOrder,`${d}/${f}/fieldOrder`,500,!0);for(let _ of p){let E=e.fields[_];(!E||(E.hidden??E.system)===!0)&&W("NATIVE_DATA_VIEW_FIELD_INVALID",`${d}/${f}/fieldOrder`)}}if(s.sections!==void 0){(!Array.isArray(s.sections)||s.sections.length>100)&&W("NATIVE_DATA_VIEW_SECTIONS_INVALID",`${d}/sections`);let f=new Set;s.sections.forEach((u,p)=>{let _=`${d}/sections/${p}`,E=ae(u,_);Ce(E,["title","fields"],_),De(E.title,`${_}/title`,255);for(let A of rt(E.fields,`${_}/fields`,100,!0)){let O=e.fields[A];(!O||(O.hidden??O.system)===!0||f.has(A))&&W("NATIVE_DATA_VIEW_FIELD_INVALID",`${_}/fields`),f.add(A)}})}let c=Qn(e,a);if(Zn(c,t,d),s.generated.create!==!1&&(e.mutationOwner||"native")==="native")for(let f of t)Bt(f,e.fields[f.code])&&Rr(f,e.fields[f.code],"create")&&!s.form.fieldOrder.includes(f.code)&&W("NATIVE_DATA_VIEW_CREATE_REQUIRED_FIELD_MISSING",`${d}/form/fieldOrder`)})}function Rr(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 ua(e,t,o){let n=ae(e,o);Ce(n,Pe.field,o),De(n.label,`${o}/label`,500),n.type!==t.type&&W("NATIVE_DATA_SURFACE_FIELD_TYPE_MISMATCH",`${o}/type`);let r=De(n.widget,`${o}/widget`,64);ca[t.type].includes(r)||W("NATIVE_DATA_SURFACE_WIDGET_INCOMPATIBLE",`${o}/widget`),_a(n.section,`${o}/section`,255);for(let i of["requiredHint","system","hidden","list","searchable","sortable"])Xn(n[i],`${o}/${i}`);n.searchable===!0&&!qn(t.type)&&W("NATIVE_DATA_SURFACE_SEARCH_UNSUPPORTED",`${o}/searchable`),n.sortable===!0&&!At(t.type)&&W("NATIVE_DATA_SURFACE_SORT_UNSUPPORTED",`${o}/sortable`);for(let i of["readCapabilities","createCapabilities","updateCapabilities"])rt(n[i],`${o}/${i}`,100,!0);if(n.maxCount!==void 0&&(!Number.isSafeInteger(n.maxCount)||Number(n.maxCount)<1||Number(n.maxCount)>100)&&W("NATIVE_DATA_SURFACE_MAX_COUNT_INVALID",`${o}/maxCount`),n.maxSizeMb!==void 0&&(!Number.isSafeInteger(n.maxSizeMb)||Number(n.maxSizeMb)<1||Number(n.maxSizeMb)>1024)&&W("NATIVE_DATA_SURFACE_MAX_SIZE_INVALID",`${o}/maxSizeMb`),n.accept!==void 0){let i=Array.isArray(n.accept)?n.accept:[n.accept];rt(i,`${o}/accept`,50,!1)}for(let i of["maxLength","precision","scale","exactDecimal","min","max","rangeBoundary","options","source","userCandidates","timePrecision","serial","subtable"])pa(n,t,i,o);ma(n,t,o)}function fa(e,t,o){if(e===void 0)return;let n=ae(e,o);if(Ce(n,Pe.list,o),n.actions!==void 0){let r=ae(n.actions,`${o}/actions`);Ce(r,["import","export"],`${o}/actions`);for(let i of["import","export"])r[i]!==void 0&&typeof r[i]!="boolean"&&W("NATIVE_DATA_SURFACE_LIST_ACTION_INVALID",`${o}/actions/${i}`)}if(n.fieldOrder!==void 0)for(let r of rt(n.fieldOrder,`${o}/fieldOrder`,500,!0))t.has(r)||W("NATIVE_DATA_SURFACE_LIST_FIELD_INVALID",`${o}/fieldOrder`);n.defaultPageSize!==void 0&&(!Number.isSafeInteger(n.defaultPageSize)||Number(n.defaultPageSize)<1||Number(n.defaultPageSize)>200)&&W("NATIVE_DATA_SURFACE_PAGE_SIZE_INVALID",`${o}/defaultPageSize`);for(let[r,i]of[["searchableFields",qn],["filterFields",Ir]]){if(n[r]===void 0)continue;let d=rt(n[r],`${o}/${r}`,100,!0);for(let s of d){let a=t.get(s);(!a||!i(a.type))&&W("NATIVE_DATA_SURFACE_LIST_FIELD_INVALID",`${o}/${r}`)}}if(n.defaultSort!==void 0){let r=ae(n.defaultSort,`${o}/defaultSort`);Ce(r,Pe.defaultSort,`${o}/defaultSort`);let i=De(r.field,`${o}/defaultSort/field`,63),d=t.get(i);!_r(i)&&(!d||!At(d.type))&&W("NATIVE_DATA_SURFACE_SORT_UNSUPPORTED",`${o}/defaultSort/field`),r.order!==void 0&&!["asc","desc"].includes(r.order)&&W("NATIVE_DATA_SURFACE_SORT_ORDER_INVALID",`${o}/defaultSort/order`)}}function Tr(e,t,o,n){if(e===void 0)return;let r=ae(e,o);if(Ce(r,Pe[n],o),r.layout!==void 0&&!["flat","sections"].includes(r.layout)&&W("NATIVE_DATA_SURFACE_LAYOUT_INVALID",`${o}/layout`),r.fieldOrder!==void 0){let i=`${o}/fieldOrder`;(!Array.isArray(r.fieldOrder)||r.fieldOrder.length>t.size||r.fieldOrder.length>da)&&W("NATIVE_DATA_SURFACE_FIELD_ORDER_INVALID",i);let d=r.fieldOrder.map((s,a)=>De(s,`${i}/${a}`,63));new Set(d).size!==d.length&&W("NATIVE_DATA_SURFACE_FIELD_ORDER_INVALID",i),d.forEach((s,a)=>{t.has(s)||W("NATIVE_DATA_SURFACE_FIELD_ORDER_FIELD_MISSING",`${i}/${a}`)})}n==="form"&&Or(r.draftState,`${o}/draftState`)}function pa(e,t,o,n){e[o]===void 0&&t[o]===void 0||((e[o]===void 0||t[o]===void 0)&&W("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${n}/${o}`),X(e[o])!==X(t[o])&&W("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${n}/${o}`))}function ma(e,t,o){let n=t.file||{},r={...e.maxCount===void 0?{}:{maxCount:e.maxCount},...e.maxSizeMb===void 0?{}:{maxSizeMb:e.maxSizeMb},...e.accept===void 0?{}:{accept:Yn(e.accept)}};for(let i of["maxCount","maxSizeMb","accept"]){if(r[i]===void 0&&n[i]===void 0)continue;(r[i]===void 0||n[i]===void 0)&&W("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${o}/${i}`);let d=i==="accept"?Yn(r[i]):r[i],s=i==="accept"?Yn(n[i]):n[i];X(d)!==X(s)&&W("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${o}/${i}`)}}function Yn(e){return(Array.isArray(e)?[...e]:[e]).sort((t,o)=>{let n=String(t),r=String(o);return n===r?0:n<r?-1:1})}function rt(e,t,o,n){(!Array.isArray(e)||!n&&e.length===0||e.length>o)&&W("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t);let r=e.map((i,d)=>De(i,`${t}/${d}`,255));return new Set(r).size!==r.length&&W("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t),r}function ae(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&W("NATIVE_OBJECT_REQUIRED",t),e}function Ce(e,t,o){let n=new Set(t);for(let r of Object.keys(e))n.has(r)||W("NATIVE_PROPERTY_UNKNOWN",`${o}/${r}`)}function De(e,t,o){return(typeof e!="string"||e.length===0||e.length>o)&&W("NATIVE_STRING_INVALID",t),e}function _a(e,t,o){e!==void 0&&(typeof e!="string"||e.length>o)&&W("NATIVE_STRING_INVALID",t)}function Xn(e,t){e!==void 0&&typeof e!="boolean"&&W("NATIVE_BOOLEAN_REQUIRED",t)}function W(e,t){throw new Re(e,t)}var Et=class extends Error{constructor(o,n){super(`${o}: ${n}`);this.pointer=o;this.reason=n}pointer;reason;code="NATIVE_MANAGED_CONCURRENCY_INVALID"};function Cr(e,t,o){if(e===void 0)return;let n=(g,I)=>{throw new Et(g,I)},r=(g,I,T)=>((!g||typeof g!="object"||Array.isArray(g)||Object.keys(g).some(l=>!T.includes(l)))&&n(I,"object contains unsupported properties"),g),i=(g,I,T,l)=>{(!Number.isSafeInteger(g)||g<I||g>T)&&n(l,`expected integer ${I}..${T}`)},d=(g,I)=>{(typeof g!="string"||!/^[a-z][a-z0-9_-]{0,63}$/.test(g))&&n(I,"invalid code")},s=(g,I,T)=>((!Array.isArray(g)||g.length>I)&&n(T,"array exceeds bound"),g),a=(g,I)=>{let T=t.find(l=>l.code===g);return T||n(I,"unknown resource"),T},c=(g,I,T)=>{let l=g.schema.fields.find(y=>y.code===I);return!l&&I!=="id"&&n(T,"unknown field"),l},f=(g,I,T=!1)=>{r(g,I,Object.keys(g||{})),Object.keys(g).length>8&&n(I,"at most eight parameters");for(let[l,y]of Object.entries(g))if(d(l,I),r(y,I,["type","values","minimum","maximum","minLength","maxLength"]),y.type==="uuid")Object.keys(y).length!==1&&n(I,"uuid has no options");else if(T&&y.type==="boolean")r(y,I,["type"]);else if(T&&y.type==="string"&&y.values===void 0)r(y,I,["type","minLength","maxLength"]),i(y.maxLength,1,256,I),y.minLength!==void 0&&i(y.minLength,0,y.maxLength,I);else if(y.type==="string"){r(y,I,["type","values"]);let R=s(y.values,100,I);(!R.length||R.some(h=>typeof h!="string"||h.length>128)||new Set(R).size!==R.length)&&n(I,"finite string values required")}else y.type==="integer"?(r(y,I,["type","minimum","maximum"]),i(y.minimum,0,1e6,I),i(y.maximum,y.minimum,y.minimum+1e3,I)):n(I,"unsupported parameter type")},u=(g,I,T,l=!1)=>{r(g,T,["from","key","value"]),!(g.from==="input"&&Object.keys(g).length===2&&Object.hasOwn(I,g.key))&&((g.from==="actor"||l&&g.from==="allocation")&&Object.keys(g).length===1||g.from==="literal"&&Object.keys(g).length===2&&Object.hasOwn(g,"value")&&(g.value===null||["string","boolean"].includes(typeof g.value)||typeof g.value=="number"&&Number.isFinite(g.value))&&JSON.stringify(g.value).length<=512||n(T,"invalid binding"))},p=(g,I,T)=>{u(g,I,T),!(g.from==="input"&&I[g.key].type==="uuid")&&(g.from==="literal"&&typeof g.value=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(g.value)||n(T,"record and allocation identifiers require a UUID binding"))},_=(g,I,T)=>{u(g,I,T),!(g.from==="input"&&I[g.key].type==="integer"&&I[g.key].minimum>=1)&&(g.from==="literal"&&Number.isSafeInteger(g.value)&&g.value>=1||n(T,"expectedRevision requires a positive integer binding"))},E="/data/concurrency";JSON.stringify(e).length>131072&&n(E,"declaration exceeds 128 KiB");let A=r(e,E,["version","admission","reads","quotas","commands"]);A.version!==1&&n(E,"unsupported version"),r(A.admission,E,["perSecond","burst","maxInFlight"]),i(A.admission.perSecond,1,1e3,E),i(A.admission.burst,1,1e3,E),i(A.admission.maxInFlight,1,1e3,E);let O=(g,I)=>{let T=new Set;for(let l of g)d(l?.code,I),T.has(l.code)&&n(I,"duplicate code"),T.add(l.code)};O(s(A.reads,32,E),E),O(s(A.quotas,16,E),E),O(s(A.commands,32,E),E);for(let g of A.reads){let I=`${E}/reads/${g.code}`;r(g,I,["code","resourceCode","parameters","select","where","limit","scope","freshSeconds","staleSeconds","maxKeys","sourcePerSecond","dependencies"]);let T=a(g.resourceCode,I);f(g.parameters,I),["subject","application"].includes(g.scope)||n(I,"invalid cache scope"),g.scope==="application"&&T.dataPolicyCode&&n(I,"shared cache cannot bypass a row policy");let l=s(g.select,32,I);l.length||n(I,"select required"),l.forEach(R=>c(T,R,I));let y=s(g.dependencies,64,I);y.forEach(R=>c(T,R,I));for(let R of s(g.where||[],8,I))r(R,I,["field","value"]),c(T,R.field,I),u(R.value,g.parameters,I),g.scope==="application"&&R.value.from==="actor"&&n(I,"actor requires subject cache"),y.includes(R.field)||n(I,"filter dependency missing");l.some(R=>!y.includes(R))&&n(I,"selected field dependency missing"),i(g.limit,1,100,I),i(g.freshSeconds,1,300,I),i(g.staleSeconds,0,300,I),i(g.maxKeys,1,1e4,I),i(g.sourcePerSecond,1,20,I)}for(let g of A.quotas){let I=`${E}/quotas/${g.code}`;r(g,I,["code","sourceResource","capacityField","allocationResource","allocationField","reservationSeconds"]);let T=a(g.sourceResource,I),l=a(g.allocationResource,I);c(T,g.capacityField,I)?.type!=="number.integer"&&n(I,"capacity must be an integer"),(c(l,g.allocationField,I)?.type!=="uuid"||c(l,g.allocationField,I)?.nullable!==!1)&&n(I,"allocation reference must be a uuid"),l.surface?.mutationOwner!=="queued-command"&&n(I,"allocation model must be command owned"),g.reservationSeconds!==void 0&&i(g.reservationSeconds,10,86400,I)}new Set(A.quotas.map(g=>g.allocationResource)).size!==A.quotas.length&&n(E,"an allocation model has exactly one pool owner");for(let g of A.commands){let I=`${E}/commands/${g.code}`;r(g,I,["code","mode","intake","execution","capability","parameters","resourceKey","admission","deadlineSeconds","guards","operations","quota"]),g.mode!==void 0&&!["permit","durable"].includes(g.mode)&&n(I,"unsupported mode");let T=g.mode==="durable";if(f(g.parameters,I,T),u(g.resourceKey,g.parameters,I),o.some(l=>l.code===g.capability)||n(I,"command capability must be declared"),r(g.admission,I,["perSecond","burst","maxInFlight","maxQueue","maxWaitSeconds","permitSeconds"]),i(g.admission.perSecond,1,A.admission.perSecond,I),i(g.admission.burst,1,A.admission.burst,I),i(g.admission.maxInFlight,1,A.admission.maxInFlight,I),i(g.admission.maxQueue,1,1e4,I),i(g.admission.maxWaitSeconds,1,3600,I),(!T||g.admission.permitSeconds!==void 0)&&i(g.admission.permitSeconds,5,60,I),i(g.deadlineSeconds,10,3600,I),T){(g.operations!==void 0||g.guards!==void 0||g.quota!==void 0)&&n(I,"backend-plan does not accept static operations, guards or quota"),r(g.intake,I,["perSecond","burst","maxInFlight"]);for(let R of["perSecond","burst","maxInFlight"])i(g.intake[R],1,1e3,I);let l=r(g.execution,I,["kind","handlerCode","timeoutMs","resources","directory"]);l.kind!=="backend-plan"&&n(I,"durable requires backend-plan"),d(l.handlerCode,I),i(l.timeoutMs,100,3e4,I);let y=s(l.resources,32,I);y.length||n(I,"execution resources required"),new Set(y.map(R=>R.resourceCode)).size!==y.length&&n(I,"duplicate execution resource");for(let R of y){r(R,I,["resourceCode","readFields","writeOperations","writeFields"]);let h=a(R.resourceCode,I);for(let w of["readFields","writeFields"]){let j=s(R[w],64,I);new Set(j).size!==j.length&&n(I,"duplicate field"),j.forEach(L=>{w==="readFields"&&nt.has(L)||c(h,L,I)})}let $=s(R.writeOperations,3,I);(new Set($).size!==$.length||$.some(w=>!["create","update","increment"].includes(w)))&&n(I,"unsupported execution operation"),R.writeFields.some(w=>["id","revision","created_by","updated_by","created_at","updated_at"].includes(w))&&n(I,"record metadata is platform owned"),!$.length&&R.writeFields.length&&n(I,"write fields require an operation"),$.length&&!R.writeFields.length&&n(I,"write operations require fields"),A.quotas.some(w=>w.allocationResource===R.resourceCode)&&$.length&&n(I,"allocation references remain owned by their pool command")}if(l.directory!==void 0){r(l.directory,I,["mode","fields"]),l.directory.mode!=="current-initiator"&&n(I,"only current initiator allowed");let R=s(l.directory.fields,5,I);(!R.length||new Set(R).size!==R.length||R.some(h=>!["displayName","employeeNumber","primaryDepartment","departments","phone"].includes(h)))&&n(I,"unsupported directory fields")}continue}(g.execution!==void 0||g.intake!==void 0)&&n(I,"execution and intake require durable mode");for(let l of s(g.guards||[],8,I)){r(l,I,["resourceCode","id","conditions"]);let y=a(l.resourceCode,I);p(l.id,g.parameters,I);for(let R of s(l.conditions,16,I)){r(R,I,["kind","field","operator","value"]);let h=c(y,R.field,I);["eq","neq","lt","lte","gt","gte"].includes(R.operator)||n(I,"unsupported guard"),R.kind==="database-now"?(h?.type!=="datetime"||!["lt","lte","gt","gte"].includes(R.operator)||R.value!==void 0)&&n(I,"database-now requires datetime and an ordering operator"):(R.kind!==void 0&&R.kind!=="value"&&n(I,"unsupported condition kind"),u(R.value,g.parameters,I))}}for(let l of s(g.operations,8,I)){r(l,I,["operation","resourceCode","id","expectedRevision","data"]);let y=a(l.resourceCode,I);y.surface?.mutationOwner!=="queued-command"&&n(I,"command mutations require command owned models");let R=A.quotas.find(h=>h.allocationResource===l.resourceCode);R&&(l.operation==="create"?g.quota?.action!=="allocate"||g.quota.pool!==R.code:Object.hasOwn(l.data||{},R.allocationField))&&n(I,"allocation references are owned by their pool command"),["create","update"].includes(l.operation)||n(I,"unsupported operation"),l.operation==="update"?(p(l.id,g.parameters,I),_(l.expectedRevision,g.parameters,I)):(l.id!==void 0||l.expectedRevision!==void 0)&&n(I,"create has no caller supplied id/revision"),r(l.data,I,Object.keys(l.data||{})),Object.keys(l.data).length>32&&n(I,"too many fields");for(let[h,$]of Object.entries(l.data))h==="id"&&n(I,"record identifiers are platform owned"),c(y,h,I),u($,g.parameters,I,g.quota?.action==="allocate")}if(g.quota){let l=r(g.quota,I,["pool","action","units","mode","allocation"]),y=A.quotas.find(R=>R.code===l.pool);y||n(I,"unknown quota pool"),p(g.resourceKey,g.parameters,I),l.action==="allocate"?(r(l,I,["pool","action","units","mode"]),i(l.units,1,1e3,I),(!["committed","reserved"].includes(l.mode)||l.mode==="reserved"&&!y.reservationSeconds)&&n(I,"invalid allocation mode"),(g.operations.length!==1||g.operations[0].operation!=="create"||g.operations[0].resourceCode!==y.allocationResource||g.operations[0].data[y.allocationField]?.from!=="allocation")&&n(I,"allocation must atomically create its bound business record")):["confirm","release"].includes(l.action)?(r(l,I,["pool","action","allocation"]),p(l.allocation,g.parameters,I),g.operations.length&&n(I,"lifecycle owns allocation state; business reference remains immutable")):n(I,"invalid quota action")}else g.operations.length||n(I,"operations required")}let b=A.commands.filter(g=>g.mode==="durable").map(g=>g.execution.handlerCode);return new Set(b).size!==b.length&&n(E,"handler code must be unique"),JSON.parse(JSON.stringify(A))}var it=class extends Error{constructor(o,n){super(`\u91D1\u989D\u751F\u547D\u5468\u671F\u58F0\u660E\u65E0\u6548\uFF1A${n}\uFF08${o}\uFF09`);this.pointer=o;this.reason=n}pointer;reason;code="NATIVE_DECIMAL_LIFECYCLE_INVALID"},no=["parentTransitions","childTransitions","fulfilledChildStatuses","lockedParentStatuses"],hr=["amountFieldCode","currencyFieldCode","relationFieldCode","parentFieldCode","rootFieldCode","statusFieldCode","parentRelationValue","childRelationValue"],Jt=e=>!!(e&&typeof e=="object"&&!Array.isArray(e)),qt=e=>Array.isArray(e)?e.filter(Jt):[],he=(e,t)=>{throw new it(e,t)},eo=e=>typeof e=="string"&&/^[A-Za-z0-9._:-]{1,128}$/.test(e),to=(e,t)=>e<t?-1:e>t?1:0;function oo(e,t="/decimalReservationLifecycle"){if(e===void 0)return;if(!Jt(e)||Object.keys(e).some(r=>!no.includes(r))||no.some(r=>!Object.prototype.hasOwnProperty.call(e,r)))return he(t,"\u5FC5\u987B\u5B8C\u6574\u58F0\u660E\u56DB\u9879\u89C4\u5219\uFF0C\u4E0D\u80FD\u5305\u542B\u672A\u77E5\u5C5E\u6027");let o=r=>{let i=e[r];if(!Array.isArray(i)||i.length>64)return he(`${t}/${r}`,"\u72B6\u6001\u8FB9\u6700\u591A 64 \u6761");let d=new Set;return i.map((s,a)=>{let c=`${t}/${r}/${a}`;if(!Jt(s)||Object.keys(s).some(u=>u!=="from"&&u!=="to")||!eo(s.from)||!eo(s.to)||s.from===s.to)return he(c,"\u72B6\u6001\u8FB9\u5FC5\u987B\u5305\u542B\u4E0D\u540C\u7684\u6709\u6548 from/to");let f=JSON.stringify([s.from,s.to]);return d.has(f)?he(c,"\u72B6\u6001\u8FB9\u4E0D\u80FD\u91CD\u590D"):(d.add(f),{from:s.from,to:s.to})}).sort((s,a)=>to(s.from,a.from)||to(s.to,a.to))},n=r=>{let i=e[r];return!Array.isArray(i)||i.length<1||i.length>16||i.some(d=>!eo(d))||new Set(i).size!==i.length?he(`${t}/${r}`,"\u72B6\u6001\u96C6\u5408\u5FC5\u987B\u5305\u542B 1 \u5230 16 \u4E2A\u4E0D\u91CD\u590D\u7684\u6709\u6548\u72B6\u6001"):[...i].sort(to)};return{parentTransitions:o("parentTransitions"),childTransitions:o("childTransitions"),fulfilledChildStatuses:n("fulfilledChildStatuses"),lockedParentStatuses:n("lockedParentStatuses")}}function wr(e,t,o="/config/data/resources"){qt(e).forEach((n,r)=>{let i=`${o}/${r}/decimalReservationLifecycle`,d=oo(n.decimalReservationLifecycle,i);if(!d)return;let s=qt(t).map(u=>u.platformAccess?.decimalReservation).filter(u=>Jt(u)&&u.resourceCode===n.code),a=s.find(u=>u.mode==="reserve");if(!a)return he(i,"\u9700\u8981\u540C\u8D44\u6E90\u5DF2\u58F0\u660E\u7684 reserve \u52A8\u4F5C\u6620\u5C04");if(hr.some(u=>typeof a[u]!="string")||s.some(u=>hr.some(p=>u[p]!==a[p])))return he(i,"\u540C\u8D44\u6E90\u989D\u5EA6\u52A8\u4F5C\u7684\u5B57\u6BB5\u6620\u5C04\u5FC5\u987B\u4E00\u81F4");let c=qt(n.schema?.fields).find(u=>u.code===a.statusFieldCode);if(c?.type!=="option.single")return he(i,"\u989D\u5EA6\u72B6\u6001\u5B57\u6BB5\u5FC5\u987B\u4E3A option.single");let f=new Set(qt(c.options).map(u=>u.value));for(let u of no)if((u==="parentTransitions"||u==="childTransitions"?d[u].flatMap(_=>[_.from,_.to]):d[u]).some(_=>!f.has(_)))return he(`${i}/${u}`,"\u72B6\u6001\u5FC5\u987B\u6765\u81EA\u989D\u5EA6\u72B6\u6001\u5B57\u6BB5\u7684\u9009\u9879");if(s.some(u=>u.mode==="reserve"&&Array.isArray(u.eligibleParentStatuses)&&u.eligibleParentStatuses.some(p=>d.lockedParentStatuses.includes(String(p)))))return he(`${i}/lockedParentStatuses`,"\u9501\u5B9A\u7236\u72B6\u6001\u4E0D\u80FD\u5141\u8BB8\u65B0\u9884\u7559")})}import{createHash as ga}from"crypto";var ro=new Set(["option.single","user.single","department.single","resource-ref.single"]),Aa=new Set(["option.multiple","cascade.single","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","address","location","json"]),Dr=new Set(["option.multiple","cascade.single","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","file","image"]),Ea=new Set(["option.single","user.single","department.single","resource-ref.single","signature","address","location"]),Ia=new Set([...ro,...Dr,"signature","address","location","json"]);function Il(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=>ya(n,o.has(n.code))).sort((n,r)=>n.code.localeCompare(r.code))}function ya(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:Na(e),index:Oa(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 yl(e,t){if(t.type==="subtable")return null;let o=le(t.code),n=kr(e,t),r=[n?` DEFAULT ${n}`:"",Ta(o,t),ba(o,t)].join("");return`${o} ${t.storage}${r}`}function bl(e,t){return kr(e,t)}function ba(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 Ol(e){return e.type==="serial-number"||Ut(e.type)&&e.type!=="subtable"}function Nl(e,t){return t.filter(o=>o.type==="serial-number").map(o=>{let n=Yt(e,o.code),r=o.serial?.start??1;return`CREATE SEQUENCE IF NOT EXISTS ${n} AS bigint MINVALUE ${r} START WITH ${r} CACHE 1`})}function Tl(e,t){let o=Ht(e);return t.filter(n=>n.type==="serial-number").map(n=>`ALTER SEQUENCE ${Yt(e,n.code)} OWNED BY ${o}.${le(n.code)}`)}function Rl(e,t){return t.filter(o=>o.type==="serial-number").map(o=>`GRANT USAGE, SELECT ON SEQUENCE ${Yt(e,o.code)} TO "openxiangda_data_api"`)}function Cl(e,t){let o=Ht(e),n=[];for(let r of t){if(r.type==="subtable")continue;let i=le(r.code),d=le(ve("idx",e,r.code,r.index));switch(r.index){case"btree":n.push(`CREATE INDEX IF NOT EXISTS ${d} ON ${o} (${i})`);break;case"btree-snapshot-expressions":{let s=le(ve("idx",e,r.code,"snapshot-value")),a=le(ve("idx",e,r.code,"snapshot-label"));n.push(`CREATE INDEX IF NOT EXISTS ${s} ON ${o} ((${i} ->> 'value'))`,`CREATE INDEX IF NOT EXISTS ${a} ON ${o} ((${i} ->> 'label'))`);break}case"gin-jsonb-path":n.push(`CREATE INDEX IF NOT EXISTS ${d} ON ${o} USING GIN (${i} jsonb_path_ops)`);break;case"gist-range":n.push(`CREATE INDEX IF NOT EXISTS ${d} ON ${o} USING GIST (${i})`);break;case"gin-trigram":{let s=ro.has(r.type)?`((${i} ->> 'label')) gin_trgm_ops`:`${i} gin_trgm_ops`;n.push(`CREATE INDEX IF NOT EXISTS ${d} ON ${o} USING GIN (${s})`);break}case"none":break}if(r.type==="serial-number"){let s=le(ve("uidx",e,r.code,"serial"));n.push(`CREATE UNIQUE INDEX IF NOT EXISTS ${s} ON ${o} (${i})`)}}return n}function hl(e,t,o,n){let r=Ht(e),i=Ht(t),d=le(ve("uidx",e,"environment_id","subtable-parent")),s=le(ve("idx",t,o,n,"subtable-child")),a=le(ve("fk",t,o,e)),c=le(o),f=le(n);return[`CREATE UNIQUE INDEX IF NOT EXISTS ${d} ON ${r} ("tenant_id", "app_code", "environment_key", "id")`,`CREATE INDEX IF NOT EXISTS ${s} ON ${i} ("tenant_id", "app_code", "environment_key", ${c}, ${f}, "id")`,`DO $native_subtable$ BEGIN
2
+ ALTER TABLE ${i}
3
3
  ADD CONSTRAINT ${a}
4
4
  FOREIGN KEY ("tenant_id", "app_code", "environment_key", ${c})
5
- REFERENCES ${i} ("tenant_id", "app_code", "environment_key", "id")
5
+ REFERENCES ${r} ("tenant_id", "app_code", "environment_key", "id")
6
6
  ON DELETE CASCADE;
7
7
  EXCEPTION WHEN duplicate_object THEN NULL;
8
- END $native_subtable$`]}function ve(e,...t){return`${e}_${_a("sha256").update(t.join(":")).digest("hex").slice(0,32)}`}function le(e){if(!/^[A-Za-z_][A-Za-z0-9_]{0,62}$/.test(e))throw new Error("OPENXIANGDA_NATIVE_IDENTIFIER_INVALID");return`"${e}"`}function ba(e,t){return e.type==="subtable"?"none":t?"gin-trigram":e.indexed?["date-range","datetime-range"].includes(e.type)?"gist-range":io.has(e.type)?"btree-snapshot-expressions":ga.has(e.type)?"gin-jsonb-path":"btree":"none"}function Oa(e){switch(e.type){case"text.short":return`varchar(${e.maxLength??255})`;case"text.long":case"text.rich":return"text";case"number.integer":return"bigint";case"number.decimal":return`numeric(${e.precision??38},${e.scale??10})`;case"boolean":return"boolean";case"date":return"date";case"time":return"time(0)";case"datetime":return"timestamptz";case"date-range":return"daterange";case"datetime-range":return"tstzrange";case"uuid":return"uuid";case"serial-number":return"varchar(255)";case"subtable":return"child-resource";default:return Ea.has(e.type),"jsonb"}}function Di(e,t){if(Mt(t.type)&&t.type!=="subtable")return"'[]'::jsonb";if(t.type!=="serial-number")return"";let o=wi(t.serial?.prefix||""),n=t.serial?.digits??6;return`(${o} || lpad(nextval(${wi(Yt(e,t.code))})::text, ${n}, '0'))`}function Na(e,t){return Si.has(t.type)?` CHECK (${e} IS NULL OR jsonb_typeof(${e}) = 'array')`:Aa.has(t.type)?` CHECK (${e} IS NULL OR jsonb_typeof(${e}) = 'object')`:""}function Ht(e){return`"app_data".${le(e)}`}function Yt(e,t){let o=ve("seq",e,t);return`"app_data".${le(o)}`}function wi(e){return`'${e.replace(/'/g,"''")}'`}var ki=new Set(["option.single","option.multiple","user.single","user.multiple","department.single","department.multiple","resource-ref.single","resource-ref.multiple"]),Ta=new Set([...ki,"cascade.single","cascade.multiple","file","image","signature","address","location","json"]),$i=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,Ra=new Set(["__proto__","prototype","constructor"]),ro=class extends Error{constructor(o){super("OPENXIANGDA_SCOPE_PROJECTION_FIELD_PATH_INVALID");this.path=o;this.name="NativeScopeSourceFieldPathV2Error"}path;code="OPENXIANGDA_SCOPE_PROJECTION_FIELD_PATH_INVALID"};function It(e,t){let o=vi(e);if(!o)return null;let n=t.get(o[0]);if(!n)return null;let i=o.slice(1).join(".")||void 0;return{field:n,...i?{valuePath:i}:{}}}function so(e){return!!(e&&e.field.type==="user.single"&&e.valuePath==="value")}function Pi(e,t,o){if(!e||!t||!Ca(e))return!1;let{field:n,valuePath:i}=e;if(!i)return t.valueType==="uuid"?n.type==="uuid":["text.short","text.long","serial-number"].includes(n.type);if(i==="value")return!(t.valueSourceResourceCode&&n.type.startsWith("resource-ref.")&&n.source?.resourceCode!==t.valueSourceResourceCode);let r=i.slice(9),s=o.get(n.source?.resourceCode||"")?.get(r)?.type;return t.valueType==="uuid"?s==="uuid":["text.short","text.long","serial-number"].includes(s||"")}function wl(e,t){let o=vi(t);if(!o)throw new ro(String(t||""));let n=e;for(let i of o){if(!n||typeof n!="object"||!Object.prototype.hasOwnProperty.call(n,i))return;n=n[i]}return n}function Ca(e){let{field:t,valuePath:o}=e;if(!o)return!Ta.has(t.type);if(o==="value")return ki.has(t.type);if(!o.startsWith("snapshot."))return!1;let n=o.slice(9);return $i.test(n)&&t.type.startsWith("resource-ref.")&&!!t.source?.snapshotFields?.includes(n)}function vi(e){if(typeof e!="string"||e.length===0||e.length>192)return null;let t=e.split(".");return![1,2,3].includes(t.length)||t.some(o=>!$i.test(o)||Ra.has(o))||t.length===2&&t[1]!=="value"||t.length===3&&t[1]!=="snapshot"?null:t}var ha=new Set(["option.single","user.single","department.single","resource-ref.single"]),wa=new Set(["text.short","text.long","text.rich","number.integer","number.decimal","boolean","date","time","datetime","uuid","serial-number"]),Sa=new Set(["value","label","description","color"]),Da=new Set(["avatarUrl","employeeNo","title","mobile","email"]),ka=new Set(["fullPath","parent.value","parent.label"]),$a=new Set(["country.value","country.label","province.value","province.label","city.value","city.label","district.value","district.label","street.value","street.label","detail","fullAddress"]),Pa=new Set(["longitude","latitude","accuracy"]),va=new Set(["address","name","province","city","district","source"]);function Dl(e){let t=new Map(e.map(o=>[o.code,new Map(o.schema.fields.map(n=>[n.code,n]))]));return e.map(o=>({...o,schema:{...o.schema,fields:o.schema.fields.map(n=>{let i=Va(n,t);if(!Object.keys(i).length)return n;let r={...n};return Object.defineProperty(r,"queryPathTypes",{configurable:!1,enumerable:!1,writable:!1,value:Object.freeze(i)}),r})}}))}function kl(e,t){if(ha.has(e.type)&&Sa.has(t)||e.type==="user.single"&&Da.has(t)||e.type==="department.single"&&ka.has(t))return yt(t);if(e.type==="resource-ref.single"){let o=e.queryPathTypes?.[t];return o?{parts:t.split("."),type:o}:null}if(e.type==="address"&&$a.has(t))return yt(t);if(e.type==="location"){if(Pa.has(t))return{parts:[t],type:"number.decimal"};if(va.has(t))return yt(t);if(t==="capturedAt")return{parts:[t],type:"datetime"}}return null}function Va(e,t){if(e.type!=="resource-ref.single"||!e.source)return{};let o=t.get(e.source.resourceCode);return o?Object.fromEntries((e.source.snapshotFields||[]).flatMap(n=>{let i=o.get(n);return i?[[`snapshot.${n}`,wa.has(i.type)?i.type:"json"]]:[]})):{}}function yt(e){return{parts:e.split("."),type:"text.short"}}var Pl=5,vl=20,Vl=50,Ll=50,Fl=100,Ot=class extends Error{constructor(o,n){super(o);this.code=o;this.pointer=n;this.name="NativeDataPolicyExpressionV2Error"}code;pointer};function st(e,t){let o=[],n=(i,r,d)=>{d>5&&bt("NATIVE_DATA_POLICY_EXPRESSION_DEPTH_EXCEEDED",r);let s=Li(i,r),a=["allOf","anyOf"].filter(u=>u in s);if(a.length===0){o.push({rule:s,pointer:r}),o.length>50&&bt("NATIVE_DATA_POLICY_EXPRESSION_LEAVES_EXCEEDED",r);return}let c=a[0],f=s[c];(a.length!==1||Object.keys(s).length!==1||!Array.isArray(f)||f.length<1||f.length>20)&&bt("NATIVE_DATA_POLICY_EXPRESSION_GROUP_INVALID",r),f.forEach((u,p)=>n(u,`${r}/${c}/${p}`,d+1))};return n(e,t,1),o}function Vi(e,t){st(e,t);let o=(n,i)=>{let r=Li(n,i);if(Array.isArray(r.allOf))return ao(r.allOf.flatMap((d,s)=>o(d,`${i}/allOf/${s}`)),i);if(Array.isArray(r.anyOf)){let d=[[]];return r.anyOf.forEach((s,a)=>{let c=o(s,`${i}/anyOf/${a}`);d=ao(d.flatMap(f=>c.map(u=>[...f,...u])),i)}),d}return[[r]]};return ao(o(e,t),t)}function ao(e,t){let o=e.reduce((n,i)=>n+i.length,0);return(e.length>50||o>100)&&bt("NATIVE_DATA_POLICY_EXPRESSION_EXPANSION_EXCEEDED",t),e}function Li(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&bt("NATIVE_DATA_POLICY_EXPRESSION_NODE_INVALID",t),e}function bt(e,t){throw new Ot(e,t)}var ue=class extends Error{constructor(o,n){super(`${o}: ${n}`);this.code=o;this.pointer=n}code;pointer},La=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,Fi=/^[A-Za-z_][A-Za-z0-9_]{0,127}$/;function Fa(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new ue("NATIVE_PARENT_READ_INVALID",t);let o=e;if(Object.keys(o).some(n=>!["resourceCode","subtableFieldCode"].includes(n))||typeof o.resourceCode!="string"||o.resourceCode.length>64||!La.test(o.resourceCode)||typeof o.subtableFieldCode!="string"||!Fi.test(o.subtableFieldCode))throw new ue("NATIVE_PARENT_READ_INVALID",t);return{resourceCode:o.resourceCode,subtableFieldCode:o.subtableFieldCode}}function xi(e,t){return[...(Array.isArray(e.rules)?e.rules:[]).map((o,n)=>({rule:o,pointer:`${t}/rules/${n}`,base:!0})),...e.readExpression===void 0?[]:st(e.readExpression,`${t}/readExpression`).map(o=>({...o,base:!1}))]}function Xt(e,t,o,n){let i=Fa(o,n),r=e.find(_=>_.code===i.resourceCode),d=e.find(_=>_.code===t),a=(Array.isArray(r?.schema?.fields)?r.schema.fields:[]).find(_=>_.code===i.subtableFieldCode);if(!r||!d||r.code===d.code||a?.type!=="subtable"||a.subtable?.resourceCode!==t)throw new ue("NATIVE_PARENT_READ_BINDING_INVALID",n);if(e.flatMap(_=>(Array.isArray(_.schema?.fields)?_.schema.fields:[]).filter(E=>E.type==="subtable"&&E.subtable?.resourceCode===t).map(E=>({resource:_,field:E}))).length!==1)throw new ue("NATIVE_PARENT_READ_PARENT_AMBIGUOUS",n);let f=a.subtable.foreignKey,p=(Array.isArray(d.schema?.fields)?d.schema.fields:[]).find(_=>_.code===f);if(typeof f!="string"||!Fi.test(f)||p?.type!=="uuid")throw new ue("NATIVE_PARENT_READ_FOREIGN_KEY_INVALID",n);return{...i,childResourceCode:t,foreignKey:f,...a.subtable.orderField?{orderField:a.subtable.orderField}:{}}}function ji(e,t,o="/config/authz/dataPolicies"){let n=new Map;for(let[i,r]of t.entries())for(let d of xi(r,`${o}/${i}`)){if(d.rule.parentRead===void 0)continue;if(Object.keys(d.rule).some(f=>!["parentRead","roleCodes"].includes(f)))throw new ue("NATIVE_PARENT_READ_RULE_KEYS_INVALID",d.pointer);if(d.base&&(r.operations?.length!==1||r.operations[0]!=="read"))throw new ue("NATIVE_PARENT_READ_READ_ONLY",d.pointer);if(e.find(f=>f.code===r.resourceCode)?.dataPolicyCode!==r.code)throw new ue("NATIVE_PARENT_READ_POLICY_BINDING_INVALID",d.pointer);let a=Xt(e,r.resourceCode,d.rule.parentRead,`${d.pointer}/parentRead`),c=n.get(r.resourceCode);if(c&&c!==a.resourceCode)throw new ue("NATIVE_PARENT_READ_PARENT_AMBIGUOUS",d.pointer);n.set(r.resourceCode,a.resourceCode)}for(let[i,r]of n)if(n.has(r))throw new ue("NATIVE_PARENT_READ_MULTI_HOP_FORBIDDEN",`${o}/${t.findIndex(d=>d.resourceCode===i)}`)}function co(e){return xi(e,"/dataPolicy").some(t=>t.rule.parentRead!==void 0)}var Mi=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Bi=(e,t)=>Object.keys(e).length===t.length&&Object.keys(e).every(o=>t.includes(o)),Wi=e=>typeof e=="string"&&/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/.test(e)&&e.length<=100,Ui=e=>typeof e=="string"&&/^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(e);function lo(e){throw new Error(`OPENXIANGDA_WORKFLOW_STAGE_${e}`)}function Ki(e){(!Mi(e)||!Bi(e,["workflowCode","resourceCode","actor","runningNodeIds","allowedStatuses"])||!Wi(e.workflowCode)||!Wi(e.resourceCode)||!["initiator","reader"].includes(String(e.actor))||!Array.isArray(e.runningNodeIds)||e.runningNodeIds.length>32||new Set(e.runningNodeIds).size!==e.runningNodeIds.length||e.runningNodeIds.some(t=>typeof t!="string"||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(t))||!Array.isArray(e.allowedStatuses)||e.allowedStatuses.length>5||new Set(e.allowedStatuses).size!==e.allowedStatuses.length||e.allowedStatuses.some(t=>!["approved","rejected","cancelled","terminated","returned"].includes(t))||e.runningNodeIds.length+e.allowedStatuses.length===0)&&lo("POLICY_INVALID")}function Ul(e){(!Mi(e)||!Bi(e,["instanceId","subjectRecordId","expectedInstanceSequence"])||!Ui(e.instanceId)||!Ui(e.subjectRecordId)||!Number.isSafeInteger(e.expectedInstanceSequence)||e.expectedInstanceSequence<0)&&lo("GUARD_INVALID")}function Ml(e,t,o){o?.some(n=>(n.kind==="record-match"||n.kind==="record-assert")&&n.resourceCode===e.resourceCode&&n.id.toLowerCase()===t.subjectRecordId.toLowerCase()&&n.assertions.some(i=>i.kind==="value"&&i.field==="revision"&&i.operator==="eq"&&Number.isSafeInteger(i.value)&&Number(i.value)>0))||lo("SOURCE_GUARD_REQUIRED")}var Bl={type:"object",additionalProperties:!1,required:["workflowCode","resourceCode","actor","runningNodeIds","allowedStatuses"],properties:{workflowCode:{type:"string",pattern:"^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$",maxLength:100},resourceCode:{type:"string",pattern:"^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$",maxLength:100},actor:{enum:["initiator","reader"]},runningNodeIds:{type:"array",maxItems:32,uniqueItems:!0,items:{type:"string",pattern:"^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$"}},allowedStatuses:{type:"array",maxItems:5,uniqueItems:!0,items:{enum:["approved","rejected","cancelled","terminated","returned"]}}},anyOf:[{properties:{runningNodeIds:{minItems:1}}},{properties:{allowedStatuses:{minItems:1}}}]};var Nt=class extends Error{constructor(o,n){super(o);this.code=o;this.pointer=n}code;pointer},fe=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},Gi=(e,t)=>e===t||e==="*"||e.endsWith(":*")&&t.startsWith(e.slice(0,-1));function qi(e){let{policy:t,resource:o,baselineRoleCode:n,baselineCapabilities:i,pointer:r}=e,d=A=>A===void 0||A===!0||Array.isArray(A)&&A.length>0&&A.every(O=>typeof O=="string"&&O.length>0&&!e.baselineDeniedCapabilities?.some(b=>Gi(b,O))&&i.some(b=>Gi(b,O))),s=(A,O="")=>{throw new Nt(A,`${r}/publicRead${O}`)},a=fe(t.publicRead);(!t.publicRead||Object.keys(a).length!==1||!Object.hasOwn(a,"fields")||!Array.isArray(a.fields)||a.fields.length<1||a.fields.length>1e3||a.fields.some(A=>typeof A!="string"||!/^[A-Za-z][A-Za-z0-9_]{0,62}$/.test(A))||new Set(a.fields).size!==a.fields.length)&&s("AUTHENTICATED_PUBLIC_READ_FIELDS_INVALID","/fields"),(!Array.isArray(t.operations)||t.operations.length!==1||t.operations[0]!=="read"||t.readExpression!==void 0||t.writeBoundary!==void 0)&&s("AUTHENTICATED_PUBLIC_READ_POLICY_NOT_READ_ONLY"),(!n||!o||o.code!==t.resourceCode||o.dataPolicyCode!==t.code||!d([fe(o.capabilities).read]))&&s("AUTHENTICATED_PUBLIC_READ_BASELINE_OR_RESOURCE_INVALID");let c=fe(o),f=fe(c.schema).fields;(!Array.isArray(f)||!f.length)&&s("AUTHENTICATED_PUBLIC_READ_RESOURCE_FIELDS_MISSING");let u=new Map(f.map(A=>[String(fe(A).code),fe(A)])),p=new Set(a.fields),_=fe(c.fieldPolicies);for(let A of p){let O=fe(u.get(A));(!u.has(A)||O.system===!0||fe(fe(c.surface).fields)[A]?.system===!0||nt.has(A))&&s("AUTHENTICATED_PUBLIC_READ_FIELD_NOT_DECLARED",`/fields/${A}`),(O.type==="subtable"||O.subtable!==void 0)&&s("AUTHENTICATED_PUBLIC_READ_SUBTABLE_UNSUPPORTED",`/fields/${A}`),d(fe(_[A]).read)||s("AUTHENTICATED_PUBLIC_READ_FIELD_NOT_BASELINE_READABLE",`/fields/${A}`)}let E=[...u.keys()].filter(A=>!p.has(A));for(let A of E)d(fe(_[A]).read)&&s("AUTHENTICATED_PUBLIC_READ_PRIVATE_FIELD_ACCESSIBLE",`/fields/${A}`);E.length&&Kt.some(A=>d(fe(_[A]).read))&&s("AUTHENTICATED_PUBLIC_READ_PRIVATE_HISTORY_ACCESSIBLE")}var zi=["exact-v1","nfkc-space-v1","nfkc-upper-ascii-v1"],Jl=256,Rt=class extends Error{constructor(o,n){super(`\u6761\u4EF6\u552F\u4E00\u952E\u58F0\u660E\u65E0\u6548\uFF1A${n}\uFF08${o}\uFF09`);this.pointer=o;this.reason=n}pointer;reason;code="NATIVE_UNIQUE_KEY_INVALID"},uo=e=>!!(e&&typeof e=="object"&&!Array.isArray(e)),ie=(e,t)=>{throw new Rt(e,t)},Zt=(e,t)=>e<t?-1:e>t?1:0,Tt=(e,t,o)=>{Object.keys(e).some(n=>!t.includes(n))&&ie(o,"\u4E0D\u652F\u6301\u672A\u77E5\u5C5E\u6027")};function Ji(e,t,o="/uniqueKeys"){if(e===void 0)return;if(!Array.isArray(e)||e.length>8)return ie(o,"\u6BCF\u8D44\u6E90\u6700\u591A 8 \u6761\u89C4\u5219");let n=new Map(t.map(r=>[r.code,r])),i=new Set;return e.map((r,d)=>{let s=`${o}/${d}`;if(!uo(r))return ie(s,"\u89C4\u5219\u5FC5\u987B\u662F\u5BF9\u8C61");if(Tt(r,["code","fields","when"],s),typeof r.code!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(r.code)||r.code.length>20||i.has(r.code))return ie(`${s}/code`,"\u9700\u8981\u4E0D\u91CD\u590D\u4E14\u4E0D\u8D85\u8FC7 20 \u5B57\u7B26\u7684 lower-kebab-case \u6807\u8BC6");if(i.add(r.code),!Array.isArray(r.fields)||r.fields.length<1||r.fields.length>4)return ie(`${s}/fields`,"\u5FC5\u987B\u9009\u62E9 1 \u5230 4 \u4E2A\u5B57\u6BB5");let a=new Set,c=r.fields.map((_,E)=>{let A=`${s}/fields/${E}`;if(!uo(_))return ie(A,"\u5B57\u6BB5\u5FC5\u987B\u662F\u5BF9\u8C61");Tt(_,["fieldCode","normalizer"],A);let O=n.get(_.fieldCode);if(!O||!["text.short","uuid","option.single","resource-ref.single","user.single"].includes(O.type)||a.has(_.fieldCode))return ie(`${A}/fieldCode`,"\u9700\u8981\u4E0D\u91CD\u590D\u7684\u77ED\u6587\u672C\u3001UUID\u3001\u5355\u9009\u3001\u5355\u8BB0\u5F55\u5F15\u7528\u6216\u5355\u4EBA\u5B57\u6BB5");a.add(_.fieldCode);let b=_.normalizer===void 0?"exact-v1":_.normalizer;return!zi.includes(b)||O.type!=="text.short"&&b!=="exact-v1"?ie(`${A}/normalizer`,"\u5F52\u4E00\u5316\u65B9\u5F0F\u4E0D\u652F\u6301\u6216\u4E0E\u5B57\u6BB5\u7C7B\u578B\u4E0D\u7B26"):{fieldCode:O.code,normalizer:b}}).sort((_,E)=>Zt(_.fieldCode,E.fieldCode)),f=r.when===void 0?[]:r.when;if(!Array.isArray(f)||f.length>4)return ie(`${s}/when`,"\u6700\u591A 4 \u4E2A\u5408\u53D6\u6761\u4EF6");let u=new Set,p=f.map((_,E)=>{let A=`${s}/when/${E}`;if(!uo(_))return ie(A,"\u6761\u4EF6\u5FC5\u987B\u662F\u5BF9\u8C61");let O=n.get(_.fieldCode);if(!O)return ie(`${A}/fieldCode`,"\u5B57\u6BB5\u4E0D\u5B58\u5728");let b;if(_.operator==="empty"||_.operator==="nonempty"){if(Tt(_,["fieldCode","operator"],A),O.type!=="text.short")return ie(A,"\u7A7A\u503C\u6761\u4EF6\u4EC5\u652F\u6301\u77ED\u6587\u672C");b={fieldCode:O.code,operator:_.operator}}else if(_.operator==="in"||_.operator==="notIn"){Tt(_,["fieldCode","operator","values"],A);let I=new Set((O.options??[]).map(T=>T.value));if(O.type!=="option.single"||!Array.isArray(_.values)||_.values.length<1||_.values.length>16||_.values.some(T=>typeof T!="string"||T.length<1||T.length>128||!I.has(T))||new Set(_.values).size!==_.values.length)return ie(A,"\u96C6\u5408\u6761\u4EF6\u9700\u8981 1 \u5230 16 \u4E2A\u4E0D\u91CD\u590D\u7684\u5DF2\u58F0\u660E\u5355\u9009\u503C");b={fieldCode:O.code,operator:_.operator,values:[..._.values].sort(Zt)}}else if(_.operator==="eq"||_.operator==="ne"){if(Tt(_,["fieldCode","operator","value"],A),O.type!=="boolean"||typeof _.value!="boolean")return ie(A,"\u7B49\u503C\u6761\u4EF6\u4EC5\u652F\u6301\u5E03\u5C14\u5B57\u6BB5\u548C\u5E03\u5C14\u503C");b={fieldCode:O.code,operator:_.operator,value:_.value}}else return ie(`${A}/operator`,"\u53EA\u652F\u6301 empty\u3001nonempty\u3001in\u3001notIn \u548C\u5E03\u5C14 eq\u3001ne");let g=JSON.stringify(b);return u.has(g)?ie(A,"\u6761\u4EF6\u4E0D\u80FD\u91CD\u590D"):(u.add(g),b)}).sort((_,E)=>Zt(JSON.stringify(_),JSON.stringify(E)));return{code:r.code,fields:c,when:p}}).sort((r,d)=>Zt(r.code,d.code))}function Hi(e,t){let o=new Set(e.filter(n=>n.type==="user.single").map(n=>n.code));return t?.some(n=>n.fields.some(i=>o.has(i.fieldCode))||n.when?.some(i=>i.operator==="eq"||i.operator==="ne"))?"1.1.0":"1.0.0"}var Qt={type:"string",pattern:"^[A-Za-z_][A-Za-z0-9_]{0,62}$"},Hl={type:"array",maxItems:8,items:{type:"object",additionalProperties:!1,required:["code","fields"],properties:{code:{type:"string",maxLength:20,pattern:"^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$"},fields:{type:"array",minItems:1,maxItems:4,uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["fieldCode"],properties:{fieldCode:Qt,normalizer:{enum:[...zi]}}}},when:{type:"array",maxItems:4,uniqueItems:!0,items:{oneOf:[{type:"object",additionalProperties:!1,required:["fieldCode","operator"],properties:{fieldCode:Qt,operator:{enum:["empty","nonempty"]}}},{type:"object",additionalProperties:!1,required:["fieldCode","operator","values"],properties:{fieldCode:Qt,operator:{enum:["in","notIn"]},values:{type:"array",minItems:1,maxItems:16,uniqueItems:!0,items:{type:"string",minLength:1,maxLength:128}}}},{type:"object",additionalProperties:!1,required:["fieldCode","operator","value"],properties:{fieldCode:Qt,operator:{enum:["eq","ne"]},value:{type:"boolean"}}}]}}}}};var Yi={"openxiangda.workflow.instance.completed.v2":"commit","openxiangda.workflow.instance.rejected.v2":"release","openxiangda.workflow.instance.withdrawn.v2":"release"};function Xi(e,t){let o=()=>{throw new Error("NATIVE_EVENT_DECIMAL_RESERVATION_INVALID")},n=p=>!p||typeof p!="object"||Array.isArray(p)?o():p,i=n(e);if(Object.keys(i).some(p=>!["resourceCode","workflowCode","outcomes"].includes(p))||typeof i.resourceCode!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(i.resourceCode)||typeof i.workflowCode!="string"||!/^[A-Za-z0-9._:-]{1,128}$/.test(i.workflowCode)||t.execution!==void 0||!Array.isArray(i.outcomes)||!i.outcomes.length||i.outcomes.length>3)return o();let r=t.resources.find(p=>p.code===i.resourceCode),d=t.reservations.find(p=>p.mode==="reserve"&&p.resourceCode===i.resourceCode),s=t.workflows.find(p=>p.code===i.workflowCode);if(!r||!d||!s||s.resourceCode!==r.code)return o();let a=r.fields.find(p=>p.code===d.statusFieldCode);if(a?.type!=="option.single")return o();let c=new Set(a.options?.map(p=>p.value)),f=new Set,u=i.outcomes.map(p=>{let _=n(p),E=_.eventType;return Object.keys(_).some(A=>!["eventType","mode","eligibleChildStatuses"].includes(A))||typeof E!="string"||!Object.prototype.hasOwnProperty.call(Yi,E)||!t.eventTypes.includes(E)||f.has(E)||_.mode!==Yi[E]||!Array.isArray(_.eligibleChildStatuses)||!_.eligibleChildStatuses.length||_.eligibleChildStatuses.length>16||new Set(_.eligibleChildStatuses).size!==_.eligibleChildStatuses.length||_.eligibleChildStatuses.some(A=>typeof A!="string"||!/^[A-Za-z0-9._:-]{1,128}$/.test(A)||!c.has(A))?o():(f.add(E),{eventType:E,mode:_.mode,eligibleChildStatuses:[..._.eligibleChildStatuses].sort()})}).sort((p,_)=>p.eventType.localeCompare(_.eventType));return{resourceCode:i.resourceCode,workflowCode:i.workflowCode,outcomes:u}}function Zi(e,t){let o=n=>Array.isArray(n)?n.filter(i=>i&&typeof i=="object"&&!Array.isArray(i)):[];return{eventTypes:Array.isArray(t.eventTypes)?t.eventTypes:[],execution:t.execution,resources:o(e.data?.resources).map(n=>({code:n.code,fields:o(n.schema?.fields).map(i=>({code:i.code,type:i.type,options:o(i.options).map(r=>({value:r.value}))}))})),reservations:o(e.backend?.operations).flatMap(n=>n.platformAccess?.decimalReservation?[n.platformAccess.decimalReservation]:[]),workflows:o(e.workflows?.definitions).map(n=>({code:n.definition?.code,resourceCode:n.definition?.subject?.resourceCode}))}}var fo=class extends Error{constructor(o,n){super(n);this.pointer=o}pointer;code="NATIVE_EVENT_ACTION_INVALID"};function Qi(e,t,o="/events/subscriptions"){if(e.execution===void 0)return;let n=(A,O)=>{throw new fo(`${o}${A}`,O)},i=(A,O,b)=>((!A||typeof A!="object"||Array.isArray(A)||Object.keys(A).some(g=>!b.includes(g)))&&n(O,"Invalid action object or unsupported property"),A),r=i(e.execution,"/execution",["kind","version","operations"]);(r.kind!=="native-data"||r.version!==1)&&n("/execution","Expected native-data version 1"),e.platformAccess&&n("/platformAccess","Native actions do not use application runtime capabilities"),(!Array.isArray(e.eventTypes)||!e.eventTypes.length||e.eventTypes.some(A=>!/^openxiangda\.data\.record\.(created|updated|deleted)\.v2$/.test(A)))&&n("/eventTypes","Native data actions require declared data events");let d=e.filter?.resourceCodes;(!Array.isArray(d)||!d.length||d.length>20)&&n("/filter/resourceCodes","Native actions require explicit source resources");let s=new Map(t.map(A=>[A.code,A])),a=d.map(A=>{let O=s.get(A);return O||n("/filter/resourceCodes","Unknown source resource"),new Set((O.schema?.fields||[]).map(b=>b.code))}),c=new Set(e.payload?.fields||[]),f=e.payload?.includeChanges===!0,u=(A,O)=>{let b=i(A,O,["source","path","value"]);if(b.source==="literal"){(!Object.hasOwn(b,"value")||Object.hasOwn(b,"path"))&&n(O,"Literal binding requires only value");let l;try{l=JSON.stringify(b.value)}catch{n(O,"Literal must be JSON")}return(l===void 0||Buffer.byteLength(l)>65536)&&n(O,"Literal is too large or not JSON"),{source:"literal",value:JSON.parse(l)}}(b.source!=="event"||typeof b.path!="string"||Object.hasOwn(b,"value"))&&n(O,"Expected a literal or event binding");let g=b.path.split(".");(g.length>8||g.some(l=>!/^[A-Za-z0-9_-]+$/.test(l)||["__proto__","prototype","constructor"].includes(l)))&&n(O,"Invalid event path");let I=/^data\.projection\.([A-Za-z][A-Za-z0-9_]{0,62})$/.exec(b.path),T=/^data\.changes\.([A-Za-z][A-Za-z0-9_]{0,62})\.(before|after)$/.exec(b.path);if(I||T){let l=(I||T)[1];a.some(y=>!y.has(l))&&n(O,"Source field must exist on every filtered resource"),c.add(l),T&&(f=!0)}else["id","time","type","subject","data.recordId","data.revision","data.operation","data.resourceCode"].includes(b.path)||n(O,"Event path is not part of the data event contract");return{source:"event",path:b.path}};(!Array.isArray(r.operations)||r.operations.length<1||r.operations.length>16)&&n("/execution/operations","Expected 1 to 16 operations");let p={},_=r.operations.map((A,O)=>{let b=`/execution/operations/${O}`,g=i(A,b,["operation","resourceCode","data","id","expectedRevision"]);["create","update","delete"].includes(g.operation)||n(b,"Unsupported Native operation");let I=s.get(g.resourceCode);I||n(b,"Unknown action target resource");let T=new Map((I.schema?.fields||[]).map(y=>[y.code,y])),l=g.data===void 0?{}:i(g.data,`${b}/data`,[...T.keys()]);return Object.keys(l).length>32&&n(b,"Maximum 32 mapped fields per operation"),g.operation==="create"&&(g.id!==void 0||g.expectedRevision!==void 0)&&n(b,"Create does not accept id or expectedRevision"),g.operation==="delete"&&g.data!==void 0&&n(b,"Delete does not accept data"),Object.keys(l).some(y=>T.get(y)?.type==="serial-number")&&n(b,"Generated fields cannot be assigned"),p[g.resourceCode]=Z(I),{operation:g.operation,resourceCode:g.resourceCode,...g.operation==="create"?{}:{id:u(g.id,`${b}/id`),expectedRevision:u(g.expectedRevision,`${b}/expectedRevision`)},...g.operation==="delete"?{}:{data:Object.fromEntries(Object.entries(l).map(([y,R])=>[y,u(R,`${b}/data/${y}`)]))}}});(c.size>32||[...c].some(A=>a.some(O=>!O.has(A))))&&n("/payload/fields","Payload must contain at most 32 declared source fields");let E={kind:"native-data",version:1,operations:_,resourceDigests:p};return Buffer.byteLength(JSON.stringify(E))>65536&&n("/execution","Action plan exceeds 64 KiB"),{execution:{...E,digest:Z(E)},payload:{includeChanges:f,fields:[...c].sort()}}}function Ve(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function tr(e,t){if(e?.instanceCommands===void 0)return[];let o=Ve(e.instanceCommands);if(!o||!Object.keys(o).length||Object.keys(o).some(i=>!["withdraw","terminate"].includes(i)))return["WORKFLOW_INSTANCE_COMMAND_POLICIES_INVALID"];let n=[];for(let[i,r]of Object.entries(o)){let d=Ve(r),s=i==="withdraw"?["beforeFact","reasonRequired"]:["beforeFact","capability"];if(!d||!Object.keys(d).length||Object.keys(d).some(a=>!s.includes(a))||Object.hasOwn(d,"reasonRequired")&&typeof d.reasonRequired!="boolean"){n.push(`WORKFLOW_INSTANCE_COMMAND_POLICY_INVALID:${i}`);continue}if(i==="terminate"){let a=d.capability;(typeof a!="string"||a.length>255||!/^app:[a-z][a-z0-9]*(?:-[a-z0-9]+)*:[A-Za-z0-9:._-]+$/.test(a)||t&&(!a.startsWith(`app:${t.appCode}:`)||!t.capabilities.includes(a)))&&n.push("WORKFLOW_INSTANCE_TERMINATE_CAPABILITY_INVALID")}if(Object.hasOwn(d,"beforeFact")){let a=d.beforeFact,c=Ve(e.inputSchema),f=Ve(Ve(c?.properties)?.[a]),u=Ve(Ve(e.subject)?.factProjection)?.[a],p=t?.fields.get(u);(typeof a!="string"||!/^[A-Za-z][A-Za-z0-9_]{0,62}$/.test(a)||!Array.isArray(c?.required)||!c.required.includes(a)||f?.type!=="string"||f?.format!=="date-time"||typeof u!="string"||t&&(p?.type!=="datetime"||p.nullable===!0))&&n.push(`WORKFLOW_INSTANCE_COMMAND_DEADLINE_FACT_INVALID:${i}`)}}return n}function eu(e,t){let o=e?.terminate?.capability;return typeof o=="string"&&/^app:[a-z][a-z0-9]*(?:-[a-z0-9]+)*:[A-Za-z0-9:._-]+$/.test(o)&&t.includes(o)}function tu(e){return e?.withdraw?.reasonRequired!==!1}function er(e){if(typeof e!="string")return null;let t=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,3}))?(Z|[+-]\d{2}:\d{2})$/.exec(e);if(!t)return null;let[,o,n,i,r,d,s]=t,a=t[8],c=new Date(Date.UTC(Number(o),Number(n),0)).getUTCDate();if(Number(n)<1||Number(n)>12||Number(i)<1||Number(i)>c||Number(r)>23||Number(d)>59||Number(s)>59||a!=="Z"&&(Number(a.slice(1,3))>23||Number(a.slice(4))>59))return null;let f=Date.parse(e);return Number.isFinite(f)?f:null}function nu(e,t,o,n){let i=e?.[t];if(!i||i.beforeFact===void 0)return null;let r=i.beforeFact,d=Ve(o),s=r&&d&&Object.hasOwn(d,r)?er(d[r]):null,a=n instanceof Date?n.getTime():er(n);return s===null||a===null||!Number.isFinite(a)?"WORKFLOW_V2_CANCELLATION_DEADLINE_INVALID":a<s?null:"WORKFLOW_V2_CANCELLATION_DEADLINE_PASSED"}var Ct="openxiangda.workflow.step.requested.v2",ir=[Ct,"openxiangda.workflow.step.result_received.v2","openxiangda.workflow.step.completed.v2","openxiangda.workflow.step.continuation_failed.v2"],_o=16384,xa=2048,iu="steps",go=/^[A-Za-z][A-Za-z0-9_-]{0,127}$/,rr=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,Ge=new Set(["__proto__","prototype","constructor"]),K=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&[Object.prototype,null].includes(Object.getPrototypeOf(e)),sr=e=>{try{let t=JSON.stringify(e);return t===void 0?1/0:new TextEncoder().encode(t).length}catch{return 1/0}},at=(e,t,o=0)=>{if(o>32)return!1;if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((r,d)=>at(r,t[d],o+1));if(!K(e)||!K(t))return!1;let n=Object.keys(e).filter(r=>e[r]!==void 0),i=Object.keys(t).filter(r=>t[r]!==void 0);return n.length===i.length&&n.every(r=>Object.hasOwn(t,r)&&at(e[r],t[r],o+1))};function po(e,t){let o=0,n=(i,r)=>++o>1e4||r>8?!1:i===null||typeof i=="boolean"||typeof i=="string"?!0:typeof i=="number"?Number.isFinite(i):Array.isArray(i)?i.length<=200&&i.every(d=>n(d,r+1)):K(i)&&Object.keys(i).length<=32&&Object.keys(i).every(d=>!Ge.has(d))&&Object.values(i).every(d=>n(d,r+1));return sr(e)<=t&&n(e,0)}function ja(e){return!K(e)||Object.keys(e).some(t=>!["executionId","handlerVersion","inputDigest","expectedFactRevision","output","receipt"].includes(t))?!1:/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/i.test(e.executionId||"")&&Number.isSafeInteger(e.handlerVersion)&&e.handlerVersion>=1&&e.handlerVersion<=1e6&&/^[a-f0-9]{64}$/.test(e.inputDigest||"")&&Number.isSafeInteger(e.expectedFactRevision)&&e.expectedFactRevision>=0&&K(e.output)&&po(e.output,_o)&&(e.receipt===void 0||K(e.receipt)&&po(e.receipt,xa))}function ru(e){return K(e)&&Object.keys(e).every(t=>["executionId","nodeId","handlerCode","handlerVersion","mode","dataTransaction","input","inputDigest","expectedFactRevision"].includes(t))&&typeof e.nodeId=="string"&&go.test(e.nodeId)&&!Ge.has(e.nodeId)&&typeof e.handlerCode=="string"&&/^[a-z][a-z0-9-]{0,100}$/.test(e.handlerCode)&&e.handlerCode.endsWith(`-v${e.handlerVersion}`)&&["pure","reconciled-effect"].includes(e.mode)&&(e.dataTransaction===void 0||e.dataTransaction===!0&&e.mode==="reconciled-effect")&&ja({executionId:e.executionId,handlerVersion:e.handlerVersion,inputDigest:e.inputDigest,expectedFactRevision:e.expectedFactRevision,output:e.input})}function en(e,t,o=_o){if(!po(t,o))return!1;let n=1e4,i=(r,d,s)=>{if(--n<0||s>8||!K(r))return!1;let a=d===null?"null":Array.isArray(d)?"array":typeof d=="number"&&Number.isSafeInteger(d)?"integer":typeof d,c=Array.isArray(r.type)?r.type:[r.type];if(!c.includes(a)&&!(a==="integer"&&c.includes("number"))||r.enum!==void 0&&(!Array.isArray(r.enum)||!r.enum.some(f=>at(f,d)))||Object.hasOwn(r,"const")&&!at(r.const,d))return!1;if(typeof d=="number")return Number.isFinite(d)&&(r.minimum===void 0||d>=r.minimum)&&(r.maximum===void 0||d<=r.maximum);if(typeof d=="string"){let f=Array.from(d).length;return(r.minLength===void 0||f>=r.minLength)&&(r.maxLength===void 0||f<=r.maxLength)}return Array.isArray(d)?d.length<=r.maxItems&&(r.minItems===void 0||d.length>=r.minItems)&&d.every(f=>i(r.items,f,s+1)):K(d)?!K(r.properties)||Object.keys(d).some(f=>Ge.has(f)||!Object.hasOwn(r.properties,f))||(Array.isArray(r.required)?r.required:[]).some(f=>!Object.hasOwn(d,f))||r.minProperties!==void 0&&Object.keys(d).length<r.minProperties||r.maxProperties!==void 0&&Object.keys(d).length>r.maxProperties?!1:Object.entries(d).every(([f,u])=>i(r.properties[f],u,s+1)):d===null||typeof d=="boolean"};return i(e,t,0)}function Wa(e){return typeof e=="string"&&e.length<=256&&e.split(".").length<=8&&e.split(".").every(t=>go.test(t)&&!Ge.has(t))}function tn(e){let t=0,o=(n,i)=>{if(!K(n)||i>6||++t>256||Object.keys(n).some(s=>!["type","title","description","properties","required","additionalProperties","items","maxItems","minItems","maxLength","minLength","minimum","maximum","enum","const","maxProperties","minProperties"].includes(s)))return!1;let r=Array.isArray(n.type)?n.type:[n.type];if(!r.length||r.length>2||r.some(s=>!["object","array","string","integer","number","boolean","null"].includes(s))||r.length>1&&(!r.includes("null")||new Set(r).size!==r.length))return!1;for(let s of["title","description"])if(n[s]!==void 0&&(typeof n[s]!="string"||n[s].length>2e3))return!1;for(let s of["minimum","maximum"])if(n[s]!==void 0&&(typeof n[s]!="number"||!Number.isFinite(n[s])))return!1;for(let[s,a]of[["maxItems",200],["minItems",200],["maxLength",16384],["minLength",16384],["maxProperties",32],["minProperties",32]])if(n[s]!==void 0&&(!Number.isSafeInteger(n[s])||n[s]<0||n[s]>a))return!1;for(let[s,a]of[["minimum","maximum"],["minItems","maxItems"],["minLength","maxLength"],["minProperties","maxProperties"]])if(n[s]!==void 0&&n[a]!==void 0&&n[s]>n[a])return!1;if(["properties","required","additionalProperties","maxProperties","minProperties"].some(s=>n[s]!==void 0)&&!r.includes("object")||["items","maxItems","minItems"].some(s=>n[s]!==void 0)&&!r.includes("array")||["maxLength","minLength"].some(s=>n[s]!==void 0)&&!r.includes("string")||["minimum","maximum"].some(s=>n[s]!==void 0)&&!r.some(s=>s==="integer"||s==="number")||n.enum!==void 0&&(!Array.isArray(n.enum)||!n.enum.length||n.enum.length>100)||r.includes("object")&&(!K(n.properties)||n.additionalProperties!==!1||Object.keys(n.properties).length>32||Object.keys(n.properties).some(s=>!rr.test(s)||Ge.has(s))||n.required!==void 0&&(!Array.isArray(n.required)||new Set(n.required).size!==n.required.length||n.required.some(s=>typeof s!="string"||!Object.hasOwn(n.properties,s)))||n.minProperties!==void 0&&n.minProperties>Object.keys(n.properties).length||n.maxProperties!==void 0&&n.maxProperties<(n.required?.length||0)||!Object.values(n.properties).every(s=>o(s,i+1)))||r.includes("array")&&(!Number.isSafeInteger(n.maxItems)||!o(n.items,i+1)))return!1;let d={...n};return delete d.enum,delete d.const,!(n.enum!==void 0&&(!n.enum.every(s=>en(d,s))||n.enum.some((s,a)=>n.enum.slice(0,a).some(c=>at(s,c))))||Object.hasOwn(n,"const")&&!en(d,n.const))};return K(e)&&e.type==="object"&&sr(e)<=_o&&o(e,0)}function nn(e){let t=Object.fromEntries(Object.values(e.nodes||{}).filter(o=>o?.kind==="action").map(o=>[o.id,o.outputSchema]));return Object.keys(t).length?{...e.inputSchema,properties:{...e.inputSchema?.properties,steps:{type:"object",additionalProperties:!1,properties:t}}}:e.inputSchema||{}}function ar(e,t){let o=e;for(let n of t.split(".")){if(!K(o?.properties)||!Object.hasOwn(o.properties,n))return;o=o.properties[n]}return K(o)?o:void 0}var nr=(e,t)=>!!ar(e,t);function su(e){return K(e)&&Object.keys(e).every(t=>["version","mode","dataTransaction","inputSchema","outputSchema"].includes(t))&&Number.isSafeInteger(e.version)&&e.version>=1&&e.version<=1e6&&["pure","reconciled-effect"].includes(e.mode)&&(e.dataTransaction===void 0||e.dataTransaction===!0&&e.mode==="reconciled-effect")&&tn(e.inputSchema)&&tn(e.outputSchema)}function or(e){return e.kind==="approval"?[e.onApprove,e.onReject]:e.kind==="condition"?[...Array.isArray(e.branches)?e.branches.map(t=>t.target):[],e.otherwise]:e.kind==="cc"||e.kind==="action"?[e.next]:[]}function mo(e,t=0){return!K(e)||t>16?[]:e.op==="path"?typeof e.path=="string"?[e.path]:[]:["left","right","value"].flatMap(o=>mo(e[o],t+1)).concat(Array.isArray(e.values)?e.values.flatMap(o=>mo(o,t+1)):[])}function on(e,t){if(!K(e)||!K(e.nodes))return["WORKFLOW_STEP_DEFINITION_INVALID"];let o=e.nodes,n=Object.entries(o).filter(([,s])=>s?.kind==="action");if(!n.length)return[];let i=[];Object.hasOwn(e.inputSchema?.properties||{},"steps")&&i.push("WORKFLOW_STEP_FACT_NAMESPACE_RESERVED");let r=nn(e);for(let[s,a]of n){(Object.keys(a).some(u=>!["id","kind","title","next","handler","inputSchema","outputSchema","inputs"].includes(u))||a.id!==s||!go.test(s)||Ge.has(s)||typeof a.title!="string"||!a.title.trim()||a.title.length>255||typeof a.next!="string"||!Object.hasOwn(o,a.next))&&i.push(`WORKFLOW_STEP_NODE_INVALID:${s}`);let c=a.handler;(!K(c)||Object.keys(c).some(u=>!["code","version","mode","dataTransaction"].includes(u))||!Number.isSafeInteger(c.version)||c.version<1||c.version>1e6||!/^[a-z][a-z0-9-]{0,100}$/.test(c.code||"")||!String(c.code).endsWith(`-v${c.version}`)||!["pure","reconciled-effect"].includes(c.mode)||c.dataTransaction!==void 0&&(c.dataTransaction!==!0||c.mode!=="reconciled-effect"))&&i.push(`WORKFLOW_STEP_HANDLER_INVALID:${s}`);let f=tn(a.inputSchema);if((!f||!tn(a.outputSchema))&&i.push(`WORKFLOW_STEP_SCHEMA_INVALID:${s}`),!K(a.inputs)||Object.keys(a.inputs).length>32){i.push(`WORKFLOW_STEP_INPUTS_INVALID:${s}`);continue}for(let u of Array.isArray(a.inputSchema?.required)?a.inputSchema.required:[])Object.hasOwn(a.inputs,u)||i.push(`WORKFLOW_STEP_INPUT_REQUIRED:${s}:${u}`);for(let[u,p]of Object.entries(a.inputs)){if(!rr.test(u)||Ge.has(u)||!Object.hasOwn(a.inputSchema?.properties||{},u)||!K(p)){i.push(`WORKFLOW_STEP_INPUT_INVALID:${s}:${u}`);continue}if(p.source==="literal")(!f||Object.keys(p).some(_=>!["source","value"].includes(_))||!Object.hasOwn(p,"value")||!en(a.inputSchema.properties[u],p.value))&&i.push(`WORKFLOW_STEP_LITERAL_INVALID:${s}:${u}`);else if(p.source!=="fact"||Object.keys(p).some(_=>!["source","path"].includes(_))||!Wa(p.path)||!nr(r,p.path))i.push(`WORKFLOW_STEP_FACT_PATH_INVALID:${s}:${u}`);else if(f){let _=ar(r,p.path),E=a.inputSchema.properties[u],A=Array.isArray(_.type)?_.type:[_.type],O=Array.isArray(E.type)?E.type:[E.type];A.some(b=>!O.includes(b)&&!(b==="integer"&&O.includes("number")))&&i.push(`WORKFLOW_STEP_FACT_TYPE_MISMATCH:${s}:${u}`)}}}let d=(s,a)=>{let c=new Set,f=[e.startAt||""];for(;f.length&&c.size<=200;){let u=f.shift();if(!(u===a||c.has(u)||!o[u])){if(u===s)return!0;c.add(u),f.push(...or(o[u]))}}return!1};for(let[s,a]of Object.entries(o)){if(!K(a))continue;let c=a.kind==="action"?Object.values(a.inputs||{}).flatMap(u=>u?.source==="fact"?[u.path]:[]):(Array.isArray(a.branches)?a.branches:[]).flatMap(u=>mo(u?.when)),f=t?.bindings?.[a.binding];f&&c.push(...[f.inputPath,f.departmentIdFrom,f.resourceIdFrom,f.scope?.valueFrom].filter(u=>typeof u=="string"));for(let u of c.filter(p=>typeof p=="string"&&p.startsWith("steps."))){let p=u.split(".")[1];(o[p]?.kind!=="action"||p===s||!nr(r,u)||d(s,p))&&i.push(`WORKFLOW_STEP_OUTPUT_NOT_AVAILABLE:${s}:${u}`)}}if(t)for(let[,s]of n){let a=new Set,c=[s.next];for(;c.length&&a.size<=200;){let f=c.shift();if(a.has(f)||!K(o[f]))continue;a.add(f);let u=o[f];if(!(u.kind==="action"||u.kind==="end")){if(u.kind==="approval"){let p=t.bindings?.[u.binding];p&&["application_provider","initiator_select"].includes(p.provider)&&i.push(`WORKFLOW_STEP_NEXT_PROVIDER_REQUIRES_PREPARED_RESULT:${f}`);continue}c.push(...or(u))}}}return[...new Set(i)]}function au(e,t){let o={};for(let[n,i]of Object.entries(e.inputs)){let r=i.source==="literal"?i.value:i.path.split(".").reduce((d,s)=>K(d)&&Object.hasOwn(d,s)?d[s]:void 0,t);r!==void 0&&(o[n]=r)}if(!en(e.inputSchema,o))throw new Error("WORKFLOW_STEP_INPUT_SCHEMA_INVALID");return o}function dr(e,t,o){let n=Ao(e),i=[];Object.keys(n).length&&!o&&i.push("WORKFLOW_STEP_BACKEND_REQUIRED");for(let r of Object.keys(n)){let d=t.find(s=>s.code===r);(!d||d.execution||d.action||!Array.isArray(d.eventTypes)||d.eventTypes.length!==1||d.eventTypes[0]!==Ct||!K(d.filter)||Object.keys(d.filter).length!==1||!K(d.filter.workflowStep)||Object.keys(d.filter.workflowStep).length!==1||d.filter.workflowStep.handlerCode!==r||!K(d.payload)||d.payload.includeChanges!==!1||!Array.isArray(d.payload.fields)||d.payload.fields.length)&&i.push(`WORKFLOW_STEP_SUBSCRIPTION_INVALID:${r}`)}for(let r of t)(r.eventTypes?.includes(Ct)&&!n[r.code]||r.filter?.workflowStep&&!n[r.code])&&i.push(`WORKFLOW_STEP_HANDLER_NOT_DECLARED:${r.code}`);return i}function Ao(e){let t={};for(let o of e){let n=on(o);if(n.length)throw new Error(n.join("; "));for(let i of Object.values(o.nodes||{})){if(i.kind!=="action")continue;let r={version:i.handler.version,mode:i.handler.mode,...i.handler.dataTransaction?{dataTransaction:!0}:{},inputSchema:i.inputSchema,outputSchema:i.outputSchema},d=t[i.handler.code];if(d&&!at(d,r))throw new Error(`WORKFLOW_STEP_HANDLER_CONTRACT_CONFLICT:${i.handler.code}`);t[i.handler.code]=r}}return t}var pe=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},qe=(e,t)=>typeof e=="string"&&!!e.trim()&&e.length<=t,Ua=/^[A-Za-z][A-Za-z0-9_-]*(?:\.[A-Za-z][A-Za-z0-9_-]*){0,15}$/,Eo=e=>typeof e=="string"&&e.length<=256&&Ua.test(e)&&!e.split(".").some(t=>["__proto__","prototype","constructor"].includes(t));function sn(e,t){let o=pe(e),n=!0;for(let i of t.split(".")){n&&=Array.isArray(o.required)&&o.required.includes(i);let r=pe(o.properties)[i];if(!r||typeof r!="object")return null;o=pe(r)}return{schema:o,required:n}}function cr(e){let t=new Set,o=[],n=2048,i=(r,d)=>{if(--n<0||d>20){o.push("WORKFLOW_EXPRESSION_BUDGET_EXCEEDED");return}let s=pe(r);if(s.op==="path")Eo(s.path)?t.add(s.path):o.push("WORKFLOW_EXPRESSION_PATH_INVALID");else{if(s.op==="literal")return;if(s.op==="and"||s.op==="or")if(!Array.isArray(s.values)||!s.values.length||s.values.length>128)o.push("WORKFLOW_EXPRESSION_GROUP_INVALID");else for(let a of s.values){if(n<0)break;i(a,d+1)}else s.op==="not"||s.op==="exists"?i(s.value,d+1):["eq","neq","gt","gte","lt","lte","in","contains"].includes(String(s.op))?(i(s.left,d+1),i(s.right,d+1)):o.push("WORKFLOW_EXPRESSION_OPERATOR_INVALID")}};return i(e,0),{paths:[...t],errors:[...new Set(o)]}}function lr(e){if(e?.readability===void 0)return[];let t=[],o=nn(e),n=pe(e.readability);(Object.keys(n).some(s=>!["variables","logic"].includes(s))||!Object.keys(n).length)&&t.push("WORKFLOW_READABILITY_INVALID");let i=pe(n.variables);n.variables!==void 0&&(typeof n.variables!="object"||Array.isArray(n.variables)||n.variables===null)&&t.push("WORKFLOW_VARIABLES_INVALID"),Object.keys(i).length>128&&t.push("WORKFLOW_VARIABLE_LIMIT_EXCEEDED");for(let[s,a]of Object.entries(i)){let c=pe(a);(!Eo(s)||!sn(o,s))&&t.push(`WORKFLOW_VARIABLE_SOURCE_UNKNOWN:${s}`),(!qe(c.label,160)||Object.keys(c).some(f=>!["label","unit","description"].includes(f))||c.unit!==void 0&&!qe(c.unit,32)||c.description!==void 0&&!qe(c.description,2e3))&&t.push(`WORKFLOW_VARIABLE_METADATA_INVALID:${s}`)}let r=n.logic===void 0?[]:n.logic;(!Array.isArray(r)||r.length>32)&&t.push("WORKFLOW_LOGIC_LIMIT_INVALID");let d=new Set;for(let s of Array.isArray(r)?r.slice(0,32):[]){let a=pe(s),c=String(a.code||"");e.approvedDelegation&&c==="kernel-approved-delegation"&&t.push("WORKFLOW_LOGIC_PLATFORM_CODE_RESERVED"),(!/^[a-z][a-z0-9-]{2,63}$/.test(c)||d.has(c)||!qe(a.title,160)||!qe(a.description,4e3)||Object.keys(a).some(f=>!["code","title","description","phase","nodeId","inputPaths","outputPaths","source"].includes(f)))&&t.push(`WORKFLOW_LOGIC_METADATA_INVALID:${c}`),d.add(c),(!["submission","node_input","completion"].includes(String(a.phase))||a.phase==="node_input"&&!pe(e.nodes)[String(a.nodeId)]||a.phase!=="node_input"&&a.nodeId!==void 0)&&t.push(`WORKFLOW_LOGIC_ANCHOR_INVALID:${c}`);for(let f of["inputPaths","outputPaths"]){let u=a[f];if(!(f==="outputPaths"&&u===void 0))if(!Array.isArray(u)||u.length>32||new Set(u).size!==u.length)t.push(`WORKFLOW_LOGIC_PATHS_INVALID:${c}:${f}`);else for(let p of u)(!Eo(p)||!sn(o,p))&&t.push(`WORKFLOW_LOGIC_SOURCE_UNKNOWN:${c}:${String(p)}`)}if(a.source!==void 0){let f=pe(a.source);(!qe(f.path,256)||String(f.path).startsWith("/")||String(f.path).includes("..")||String(f.path).includes("://")||!/^sha256:[a-f0-9]{64}$/.test(String(f.digest))||f.symbol!==void 0&&!qe(f.symbol,160)||Object.keys(f).some(u=>!["path","symbol","digest"].includes(u)))&&t.push(`WORKFLOW_LOGIC_SOURCE_REFERENCE_INVALID:${c}`)}}for(let s of Object.values(pe(e.nodes))){let a=pe(s),c=Array.isArray(a.branches)?a.branches:[];for(let f of c){let u=cr(f.when);t.push(...u.errors.map(p=>`${p}:${a.id}`));for(let p of u.paths)sn(o,p)||t.push(`WORKFLOW_VARIABLE_SOURCE_UNKNOWN:${a.id}:${p}`)}}return[...new Set(t)]}function lu(e,t){let o=nn(e),n=[],i=new Map,r=[];for(let c of Object.values(e.nodes)){if(c.kind==="approval")for(let[f,u,p]of[["approve",c.onApprove,"\u540C\u610F"],["reject",c.onReject,"\u62D2\u7EDD"]])u&&n.push({id:`${c.id}:${f}`,from:c.id,to:u,kind:f,label:p,variablePaths:[]});if(c.kind==="approval")for(let f of new Set(c.returnTargets||[]))e.nodes[f]?.kind==="correction"&&n.push({id:`${c.id}:return:${f}`,from:c.id,to:f,kind:"return",label:"\u9000\u56DE\u53D1\u8D77\u4EBA\u8865\u6B63",variablePaths:[]});if(c.kind==="correction"&&c.next&&n.push({id:`${c.id}:resubmit`,from:c.id,to:c.next,kind:"resubmit",label:"\u91CD\u65B0\u63D0\u4EA4\uFF0C\u4ECE\u8D77\u70B9\u91CD\u7B97",variablePaths:[]}),c.kind==="cc"&&c.next&&n.push({id:`${c.id}:next`,from:c.id,to:c.next,kind:"next",label:"\u6284\u9001\u540E\u7EE7\u7EED",variablePaths:[]}),c.kind==="action"&&c.next){let f=Object.values(c.inputs||{}).flatMap(u=>u.source==="fact"?[u.path]:[]);for(let u of f)i.has(u)||i.set(u,new Set),i.get(u).add(c.id);n.push({id:`${c.id}:next`,from:c.id,to:c.next,kind:"next",label:"\u6210\u529F\u56DE\u6267\u540E\u7EE7\u7EED",variablePaths:f})}if(c.kind==="condition"){for(let[f,u]of(c.branches||[]).entries()){let p=cr(u.when);for(let _ of p.paths)i.has(_)||i.set(_,new Set),i.get(_).add(c.id);n.push({id:`${c.id}:branch:${f}`,from:c.id,to:u.target,kind:"branch",label:u.label||`\u6761\u4EF6 ${f+1}`,priority:f+1,expression:u.when,variablePaths:p.paths}),r.push(...p.errors.map(_=>({code:_,path:c.id})))}c.otherwise&&n.push({id:`${c.id}:default`,from:c.id,to:c.otherwise,kind:"default",label:"\u5747\u4E0D\u6EE1\u8DB3\u65F6",variablePaths:[]})}}let d=[...e.readability?.logic||[]];if(e.approvedDelegation){let c=e.approvedDelegation,f=c.confirmer==="initiator"?"\u7533\u8BF7\u4EBA\u672C\u4EBA":"\u6240\u9009\u4EE3\u7406\u4EBA";d.push({code:"kernel-approved-delegation",title:"\u6279\u51C6\u540E\u6574\u6279\u6388\u6743\u4EE3\u7406",phase:"completion",inputPaths:[c.requestsField],description:`\u6279\u51C6\u65F6\u6838\u9A8C${f}\u5728\u5F53\u524D\u9000\u56DE\u5468\u671F\u5B8C\u6210\u201C${e.nodes[c.confirmationNodeId]?.title||c.confirmationNodeId}\u201D\u7684\u4EBA\u5DE5\u786E\u8BA4\uFF1B\u968F\u540E\u91CD\u65B0\u6838\u9A8C\u53CC\u65B9\u5F53\u524D\u8D26\u53F7\u3001\u804C\u8D23\u3001\u4FEE\u8BA2\u3001\u8303\u56F4\u4E0E\u5B8C\u6574\u6709\u6548\u671F\uFF0C\u6574\u6279\u6388\u6743\uFF08\u6700\u591A${c.maxRequests}\u884C\uFF09\u3002\u4EFB\u4E00\u884C\u5931\u8D25\uFF0C\u6279\u51C6\u4E0E\u5168\u90E8\u6388\u6743\u4E00\u8D77\u56DE\u6EDA\uFF1B\u539F\u547D\u4EE4\u6062\u590D\u4E0D\u91CD\u65B0\u6FC0\u6D3B\u5DF2\u64A4\u9500\u6388\u6743\u3002`})}let a=[...new Set([...i.keys(),...Object.keys(e.readability?.variables||{}),...d.flatMap(c=>[...c.inputPaths,...c.outputPaths||[]])])].slice(0,128).map(c=>{let f=sn(o,c),u=e.readability?.variables?.[c],p=c.split("."),_=e.subject?.factProjection[p[0]],E=p[0]==="steps"?e.nodes[p[1]]:void 0;return f||r.push({code:"WORKFLOW_VARIABLE_SOURCE_UNKNOWN",path:c}),{path:c,label:u?.label||String(f?.schema.title||c),type:String(f?.schema.type||"unknown"),...u,required:f?.required||!1,usedBy:[...i.get(c)||[]],source:f&&E?.handler?{kind:"step_output",nodeId:E.id,handlerCode:E.handler.code,handlerVersion:E.handler.version}:f&&_&&e.subject?{kind:"subject_field",resourceCode:e.subject.resourceCode,fieldPath:[_,...p.slice(1)].join(".")}:{kind:f?"input":"unknown"}}});return{schemaVersion:"openxiangda.workflow-graph/v2",workflowCode:e.code,definitionDigest:t,startAt:e.startAt,fixedTopology:!0,branchStrategy:"first_match",nodes:Object.values(e.nodes).map(c=>({id:c.id,kind:c.kind,title:c.title||c.id,...c.binding?{binding:c.binding}:{},...c.mode?{mode:c.mode}:{},...c.outcome?{outcome:c.outcome}:{},...c.kind==="cc"?{emptyPolicy:c.emptyPolicy,notify:c.notify!==!1}:{},...c.kind==="approval"?{emptyPolicy:c.emptyPolicy||"block",initiatorApprovalPolicy:c.initiatorApprovalPolicy||"manual",...c.completionDeadline?{completionDeadline:{...c.completionDeadline}}:{}}:{},...c.kind==="action"&&c.handler?{businessStep:{handler:c.handler,inputs:c.inputs||{},outputPaths:Object.keys(pe(c.outputSchema).properties||{}).map(f=>`steps.${c.id}.${f}`)}}:{}})),edges:n,variables:a,logic:d,diagnostics:r}}function Ma(e,t=[]){let o=i=>{let r=t.find(d=>d.path===i)?.label;return r&&r!==i?r:void 0},n=o(e);if(n)return n;for(let i=e.lastIndexOf(".");i>0;i=e.lastIndexOf(".",i-1)){let r=o(e.slice(0,i));if(!r)continue;let d=e.slice(i+1);return d==="value"?`${r}\uFF08\u503C\uFF09`:d==="label"?`${r}\uFF08\u663E\u793A\u540D\u79F0\uFF09`:`${r}.${d}`}return e}function rn(e,t=[],o=0){if(!e||o>20)return"\u65E0\u6CD5\u8BC6\u522B\u7684\u6761\u4EF6";if(e.op==="path")return Ma(e.path,t);if(e.op==="literal")return JSON.stringify(e.value)??"\u7F3A\u503C";if(e.op==="and"||e.op==="or")return e.values.slice(0,128).map(d=>`\uFF08${rn(d,t,o+1)}\uFF09`).join(e.op==="and"?" \u4E14 ":" \u6216 ");if(e.op==="not"||e.op==="exists")return`${e.op==="not"?"\u4E0D\u6EE1\u8DB3":"\u5B58\u5728"}\uFF08${rn(e.value,t,o+1)}\uFF09`;if(!("left"in e))return"\u65E0\u6CD5\u8BC6\u522B\u7684\u6761\u4EF6";let n={eq:"=",neq:"\u2260",gt:">",gte:"\u2265",lt:"<",lte:"\u2264",in:"\u5C5E\u4E8E",contains:"\u5305\u542B"},i=e.left.op==="path"?e.left.path:void 0,r=i&&e.right.op==="literal"&&typeof e.right.value=="number"?t.find(d=>d.path===i)?.unit:void 0;return`${rn(e.left,t,o+1)} ${n[e.op]} ${rn(e.right,t,o+1)}${r?` ${r}`:""}`}function ur(e,t=0){return!Array.isArray(e)||e.length>64||t>1?!1:e.every(o=>{if(!o||typeof o!="object"||Array.isArray(o)||o.readonlyWhen!==void 0)return!1;if(o.subtable!==void 0){let n=o.subtable;return n&&n.create===!1&&n.delete===!1&&n.reorder===!1&&ur(n.fields,t+1)}return o.readonly===!0})}function ht(e){let t=[];for(let[o,n]of Object.entries(e?.nodes||{}))if(n.initiatorApprovalPolicy!==void 0){if(n.kind!=="approval"||!["manual","auto_approve"].includes(n.initiatorApprovalPolicy)){t.push(`WORKFLOW_INITIATOR_APPROVAL_POLICY_INVALID:${o}`);continue}n.initiatorApprovalPolicy==="auto_approve"&&((n.taskPageCode!==void 0&&(typeof n.taskPageCode!="string"||!ur(e.taskPages?.[n.taskPageCode]?.fields))||[n.fieldPolicy?.default,...Object.values(n.fieldPolicy?.fields||{})].some(i=>i==="edit"||i==="edit_required"))&&t.push(`WORKFLOW_INITIATOR_APPROVAL_INPUT_REQUIRED:${o}`),n.operationPolicy?.approve?.commentRequired===!0&&t.push(`WORKFLOW_INITIATOR_APPROVAL_COMMENT_REQUIRED:${o}`))}return t}function fu(e,t,o,n,i){return e.kind==="approval"&&e.initiatorApprovalPolicy==="auto_approve"&&ht({nodes:{node:e},...i?{taskPages:i}:{}}).length===0&&t!=="return_review"&&!!o&&n.user_id===o&&n.status==="active"&&n.participant_kind==="primary"&&["resolution","resolution_retry"].includes(n.source||"")&&!n.source_participant_id&&!n.delegate_authorization_id}var mu=8,_u={type:"array",minItems:2,maxItems:8,uniqueItems:!0,items:{type:"string",maxLength:128,pattern:"^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$"}};function an(e){if(e.roleCodes===void 0)return[];let t=e.roleCodes;if(!["app_role","app_role_in_scope"].includes(e.provider||"")||e.roleCode!==void 0||e.candidateField!==void 0||!Array.isArray(t)||t.length<2||t.length>8||new Set(t).size!==t.length||t.some(o=>typeof o!="string"||o.length>128||!/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/.test(o)))return["WORKFLOW_V2_BINDING_ROLE_UNION_INVALID"];if(e.provider==="app_role_in_scope"){let o=e.scope,n=typeof o?.value=="string"&&o.value.length>0&&o.value.length<=255&&o.valueFrom===void 0,i=typeof o?.valueFrom=="string"&&o.valueFrom.length<=255&&/^[A-Za-z][A-Za-z0-9_-]*(?:\.[A-Za-z][A-Za-z0-9_-]*)*$/.test(o.valueFrom)&&!o.valueFrom.split(".").some(r=>["__proto__","prototype","constructor"].includes(r))&&o.value===void 0;if(!o||typeof o!="object"||Array.isArray(o)||Object.keys(o).some(r=>!["dimension","value","valueFrom"].includes(r))||typeof o.dimension!="string"||!/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/.test(o.dimension)||!n&&!i)return["WORKFLOW_V2_BINDING_ROLE_UNION_SCOPE_INVALID"]}else if(e.scope!==void 0)return["WORKFLOW_V2_BINDING_ROLE_UNION_SCOPE_INVALID"];return[]}function gu(e){return e.roleCodes?[...e.roleCodes]:e.roleCode?[e.roleCode]:[]}function fr(e){return e.some(t=>Object.values(t.binding.bindings).some(o=>o.roleCodes!==void 0))}function pr(e){if(e.selectedInputPath===void 0)return[];let t=e.selectedInputPath;return!["app_role","app_role_in_scope"].includes(e.provider||"")||e.candidateField!==void 0||e.inputPath!==void 0||e.routing!==void 0||e.roleCode===void 0&&e.roleCodes===void 0||typeof t!="string"||t.length>255||!/^[A-Za-z][A-Za-z0-9_-]*(?:\.[A-Za-z][A-Za-z0-9_-]*)*$/.test(t)||t.split(".").some(o=>["__proto__","constructor","prototype"].includes(o))?["WORKFLOW_V2_ROLE_INPUT_SELECTION_INVALID"]:[]}function mr(e){return e.some(t=>Object.values(t.binding.bindings).some(o=>o.selectedInputPath!==void 0))}var _r=20,gr=200,Ba=["fixed_users","initiator","input_users","form_field_users","app_role","app_role_in_scope","previous_node_actor"];function Io(e,t){let o=[];for(let[n,i]of Object.entries(e?.nodes||{})){if(i?.kind!=="cc"||((Object.keys(i).some(a=>!["id","kind","title","binding","next","emptyPolicy","notify","administration"].includes(a))||typeof i.title!="string"||!i.title.trim()||i.title.length>255||typeof i.binding!="string"||!i.binding.trim()||i.binding.length>255||typeof i.next!="string"||!i.next.trim()||!e.nodes?.[i.next]||!["block","skip"].includes(i.emptyPolicy)||i.notify!==void 0&&typeof i.notify!="boolean")&&o.push(`WORKFLOW_CC_NODE_INVALID:${n}`),!t))continue;let r=t.bindings?.[i.binding];if(!r){o.push(`WORKFLOW_CC_BINDING_NOT_FOUND:${n}`);continue}Ba.includes(r.provider)||o.push(`WORKFLOW_CC_PROVIDER_INVALID:${n}`);let d=r.min??1,s=r.max??20;(!Number.isSafeInteger(d)||!Number.isSafeInteger(s)||d<1||s<d||s>200||r.provider==="fixed_users"&&(!Array.isArray(r.users)||!r.users.length||r.users.length>s))&&o.push(`WORKFLOW_CC_RECIPIENT_LIMIT_INVALID:${n}`)}return[...new Set(o)]}var yo=["approve","reject","return","transfer","delegate","add_assignee"],bo=["fixed_users","app_role","app_role_in_scope"],Ka=["single","any","all","sequence"],Le=e=>!!e&&typeof e=="object"&&!Array.isArray(e),ze=(e,t)=>Object.keys(e).every(o=>t.includes(o)),dn=(e,t,o)=>Array.isArray(e)&&e.length>0&&e.length<=o&&new Set(e).size===e.length&&e.every(n=>typeof n=="string"&&t.includes(n));function wt(e){return e.allowedOperations||[...yo]}function Ga(e,t){return t?.commentRequired??e==="reject"}function qa(e,t){return!["transfer","delegate","add_assignee","return"].includes(e)||t?.reasonRequired!==!1}function Er(e,t,o={},n=!1){return!(!Le(e)||!Object.keys(e).length||!ze(e,n?["enabled","label","commentRequired","reasonRequired"]:["label","commentRequired","reasonRequired"])||e.label!==void 0&&(typeof e.label!="string"||!e.label.trim()||e.label.length>40||/[\u0000-\u001f\u007f]/.test(e.label))||e.enabled!==void 0&&(typeof e.enabled!="boolean"||["approve","reject"].includes(t)&&!e.enabled)||e.commentRequired!==void 0&&(typeof e.commentRequired!="boolean"||!["approve","reject"].includes(t)||n&&Ga(t,o)&&!e.commentRequired)||e.reasonRequired!==void 0&&(typeof e.reasonRequired!="boolean"||!["transfer","delegate","add_assignee","return"].includes(t)||n&&qa(t,o)&&!e.reasonRequired))}function Oo(e,t){let o=[];for(let[n,i]of Object.entries(e?.nodes||{})){if(!Le(i))continue;let r=i.administration,d=i.operationPolicy;if(i.kind==="cc"){(d!==void 0||r!==void 0&&(!Le(r)||!ze(r,["assigneeProviders"])))&&o.push(`WORKFLOW_NODE_ADMINISTRATION_INVALID:${n}`),r?.assigneeProviders!==void 0&&!dn(r.assigneeProviders,bo,3)&&o.push(`WORKFLOW_NODE_ADMINISTRATION_PROVIDERS_INVALID:${n}`),r?.assigneeProviders?.includes("app_role_in_scope")&&t&&!t.bindings[i.binding||""]?.scope&&o.push(`WORKFLOW_NODE_ADMINISTRATION_SCOPE_REQUIRED:${n}`);continue}if(i.kind!=="approval"){(r!==void 0||d!==void 0)&&o.push(`WORKFLOW_NODE_ADMINISTRATION_APPROVAL_REQUIRED:${n}`);continue}if(d!==void 0&&(!Le(d)||Object.keys(d).length>8||Object.entries(d).some(([a,c])=>!yo.includes(a)||!wt(i).includes(a)||!Er(c,a)))&&o.push(`WORKFLOW_NODE_OPERATION_POLICY_INVALID:${n}`),r===void 0)continue;if(!Le(r)||!ze(r,["modes","assigneeProviders","operations"])){o.push(`WORKFLOW_NODE_ADMINISTRATION_INVALID:${n}`);continue}r.modes!==void 0&&(!dn(r.modes,Ka,4)||!r.modes.includes(i.mode))&&o.push(`WORKFLOW_NODE_ADMINISTRATION_MODES_INVALID:${n}`),r.assigneeProviders!==void 0&&!dn(r.assigneeProviders,bo,3)&&o.push(`WORKFLOW_NODE_ADMINISTRATION_PROVIDERS_INVALID:${n}`);let s=t?.bindings[i.binding||""];s&&Array.isArray(r.assigneeProviders)&&r.assigneeProviders.includes("app_role_in_scope")&&!s.scope&&o.push(`WORKFLOW_NODE_ADMINISTRATION_SCOPE_REQUIRED:${n}`),r.operations!==void 0&&(!dn(r.operations,yo,8)||r.operations.some(a=>!wt(i).includes(a)))&&o.push(`WORKFLOW_NODE_ADMINISTRATION_OPERATIONS_INVALID:${n}`)}return o}function Ou(e,t,o,n){let i=[];if(!e||!Le(o)||!Object.keys(o).length||!ze(o,["title","description","assignee","mode","operations"]))return["WORKFLOW_V2_NODE_CONFIGURATION_PATCH_INVALID"];let r=o;for(let s of["title","description"])r[s]!==void 0&&(typeof r[s]!="string"||r[s].length>(s==="title"?255:1e3)||s==="title"&&!r[s].trim())&&i.push("WORKFLOW_V2_NODE_CONFIGURATION_PATCH_INVALID");let d=e.administration;if(r.mode!==void 0&&(e.kind!=="approval"||!d?.modes?.includes(r.mode))&&i.push("WORKFLOW_V2_NODE_CONFIGURATION_MODE_READONLY"),r.operations!==void 0&&(e.kind!=="approval"||!Le(r.operations)||!Object.keys(r.operations).length||Object.keys(r.operations).length>8||Object.entries(r.operations).some(([s,a])=>!d?.operations?.includes(s)||!wt(e).includes(s)||!Er(a,s,e.operationPolicy?.[s],!0)))&&i.push("WORKFLOW_V2_NODE_CONFIGURATION_OPERATION_INVALID"),r.assignee!==void 0){let s=r.assignee,a=d?.assigneeProviders||(e.kind==="approval"&&t&&bo.includes(t.provider)?[t.provider]:[]);if(t?.selectedInputPath&&!["app_role","app_role_in_scope"].includes(s?.provider||"")&&i.push("WORKFLOW_V2_NODE_CONFIGURATION_PROVIDER_READONLY"),!Le(s)||!["approval","cc"].includes(e.kind)||!a.includes(s.provider)||s.provider==="app_role_in_scope"&&!t?.scope)i.push("WORKFLOW_V2_NODE_CONFIGURATION_PROVIDER_READONLY");else if(s.provider==="fixed_users"){let c=e.kind==="cc"?t?.min??1:e.emptyPolicy==="skip"?0:1,f=e.kind==="cc"?Math.min(t?.max??20,200):200;(!ze(s,["provider","users"])||!Array.isArray(s.users)||s.users.length<c||s.users.length>f||new Set(s.users).size!==s.users.length||s.users.some(u=>typeof u!="string"||!u.trim()||u.length>255))&&i.push("WORKFLOW_V2_NODE_CONFIGURATION_USERS_INVALID")}else s.roleCodes!==void 0?(!ze(s,["provider","roleCodes"])||an({...s,...s.provider==="app_role_in_scope"?{scope:t?.scope}:{}}).length)&&i.push("WORKFLOW_V2_NODE_CONFIGURATION_ROLE_INVALID"):(!ze(s,["provider","roleCode"])||typeof s.roleCode!="string"||!/^[a-z][a-z0-9_-]{0,127}$/.test(s.roleCode))&&i.push("WORKFLOW_V2_NODE_CONFIGURATION_ROLE_INVALID")}return i.push(...ht({nodes:{node:{...e,operationPolicy:Ar(e,r).operationPolicy}},...n?{taskPages:n}:{}})),e.completionDeadline&&Ar(e,r).operationPolicy.approve?.commentRequired===!0&&i.push("WORKFLOW_COMPLETION_DEADLINE_INPUT_REQUIRED:node"),i}function Ar(e,t){let o=Object.fromEntries(wt(e).flatMap(n=>{let i=n,r=t?.operations?.[i],d={...e.operationPolicy?.[i],...r?.label!==void 0?{label:r.label}:{},...r?.commentRequired!==void 0?{commentRequired:r.commentRequired}:{},...r?.reasonRequired!==void 0?{reasonRequired:r.reasonRequired}:{}};return Object.keys(d).length?[[i,d]]:[]}));return{mode:t?.mode||e.mode,initiatorApprovalPolicy:e.initiatorApprovalPolicy||"manual",allowedOperations:wt(e).filter(n=>t?.operations?.[n]?.enabled!==!1),operationPolicy:o,fieldPolicy:{default:e.fieldPolicy?.default||"readonly",fields:{...e.fieldPolicy?.fields}}}}var Ir=["fixed_users","input_users","form_field_users","app_role","app_role_in_scope"];function No(e,t){let o=[];for(let[n,i]of Object.entries(e?.nodes||{}))i.kind==="cc"||i.emptyPolicy===void 0||(i.kind!=="approval"||!["block","skip"].includes(i.emptyPolicy)?o.push(`WORKFLOW_APPROVAL_EMPTY_POLICY_INVALID:${n}`):i.emptyPolicy==="skip"&&t&&!Ir.includes(t.bindings?.[i.binding||""]?.provider)&&o.push(`WORKFLOW_APPROVAL_EMPTY_PROVIDER_UNSUPPORTED:${n}`));return o}function Tu(e,t){return e.kind==="approval"&&e.emptyPolicy==="skip"&&t?.emptyResult==="no_candidates"&&Ir.includes(t.provider)&&Array.isArray(t.candidates)&&t.candidates.length===0&&Array.isArray(t.selected)&&t.selected.length===0&&Array.isArray(t.warnings)&&t.warnings.length===0}function yr(e,t){let o=Object.values(e.nodes||{}).filter(n=>n.binding===t);return o.length>0&&o.every(n=>n.kind==="approval"&&n.emptyPolicy==="skip")}function br(e,t=0){return!Array.isArray(e)||e.length>64||t>1?!0:e.some(o=>!o||typeof o!="object"||Array.isArray(o)||o.required===!0||o.requiredWhen!==void 0||o.subtable!==void 0&&(!o.subtable||br(o.subtable.fields,t+1)))}function Cu(e){let t=e.afterSeconds;return`\u8FDB\u5165\u540E ${t%86400===0?`${t/86400} \u5929`:t%3600===0?`${t/3600} \u5C0F\u65F6`:t%60===0?`${t/60} \u5206\u949F`:`${t} \u79D2`}\u672A\u5B8C\u6210\uFF0C\u81EA\u52A8\u540C\u610F`}function Or(e){let t=[];for(let[o,n]of Object.entries(e?.nodes||{})){if(!n||typeof n!="object"||n.completionDeadline===void 0)continue;let i=n.completionDeadline;if(n.kind!=="approval"||!i||typeof i!="object"||Array.isArray(i)||Object.keys(i).length!==2||Object.keys(i).some(d=>!["afterSeconds","action"].includes(d))||i.action!=="approve"||!Number.isInteger(i.afterSeconds)||i.afterSeconds<1||i.afterSeconds>2592e3){t.push(`WORKFLOW_COMPLETION_DEADLINE_INVALID:${o}`);continue}n.allowedOperations&&!n.allowedOperations.includes("approve")&&t.push(`WORKFLOW_COMPLETION_DEADLINE_APPROVE_UNAVAILABLE:${o}`);let r=n.taskPageCode?e.taskPages?.[n.taskPageCode]:void 0;(n.taskPageCode&&(!r||br(r.fields))||[n.fieldPolicy?.default,...Object.values(n.fieldPolicy?.fields||{})].includes("edit_required")||n.operationPolicy?.approve?.commentRequired===!0||e.commandHandlers?.approve!==void 0)&&t.push(`WORKFLOW_COMPLETION_DEADLINE_INPUT_REQUIRED:${o}`)}return t}var za="openxiangda.workflow-rejection-notification/v1",wu=4096;function Nr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function dt(e,t){return typeof e=="string"&&e.trim().length>0&&e.length<=t}function To(e,t){return Object.keys(e).sort().join(",")===t.sort().join(",")}function Tr(e){let t=e?.rejectionNotification;return t===void 0?[]:!Nr(t)||!To(t,["recipient","title","summary"])||t.recipient!=="record_last_modifier"||!dt(t.title,160)||!dt(t.summary,500)?["WORKFLOW_REJECTION_NOTIFICATION_INVALID"]:dt(e.subject?.resourceCode,63)?[]:["WORKFLOW_REJECTION_NOTIFICATION_SUBJECT_REQUIRED"]}function Su(e){if(!Nr(e)||e.schemaVersion!==za||e.recipient!=="record_last_modifier"||!dt(e.title,160)||!dt(e.summary,500))return!1;let t=["schemaVersion","recipient","title","summary","status","sourceRevision"];if(e.status==="ready"){if(!To(e,[...t,"userId"])||!dt(e.userId,255)||!Number.isSafeInteger(e.sourceRevision)||Number(e.sourceRevision)<1)return!1}else if(e.status==="skipped"){if(!To(e,[...t,"reason"])||!["record_missing","modifier_missing","modifier_ineligible"].includes(String(e.reason))||(e.reason==="record_missing"?e.sourceRevision!==null:!Number.isSafeInteger(e.sourceRevision)||Number(e.sourceRevision)<1))return!1}else return!1;return new TextEncoder().encode(JSON.stringify(e)).byteLength<=4096}function Rr(e,t){let o=e.commandHandlers;if(o===void 0)return[];if(!o||typeof o!="object"||Array.isArray(o)||!Object.keys(o).length||Object.keys(o).some(i=>!["approve","reject","withdraw","resubmit"].includes(i)))return["WORKFLOW_BUSINESS_COMMAND_HANDLERS_INVALID"];let n=[];o.resubmit&&!Object.values(e.nodes||{}).some(i=>i.kind==="correction")&&n.push("WORKFLOW_BUSINESS_CORRECTION_REQUIRED");for(let[i,r]of Object.entries(o)){if(!r||typeof r!="object"||Array.isArray(r)||Object.keys(r).some(s=>!["operationCode","transitionPolicy","derivedSubjectFields"].includes(s))||r.transitionPolicy!==void 0&&(i!=="approve"||r.transitionPolicy!=="workflow")||!/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/.test(r.operationCode||"")){n.push("WORKFLOW_BUSINESS_COMMAND_HANDLER_INVALID");continue}if(r.derivedSubjectFields!==void 0){let s=r.derivedSubjectFields,a=new Set(Object.values(e.subject?.factProjection||{}));(i!=="resubmit"||!Array.isArray(s)||s.length<1||s.length>32||new Set(s).size!==s.length||s.some(c=>typeof c!="string"||!/^[A-Za-z][A-Za-z0-9_]{0,62}$/.test(c)||!a.has(c)||nt.has(c)||["createdBy","updatedBy","createdAt","updatedAt"].includes(c)||Object.values(e.taskPages||{}).some(f=>f.fields?.some(u=>u.code===c&&u.readonly!==!0))))&&n.push("WORKFLOW_CORRECTION_DERIVED_SUBJECT_FIELDS_INVALID")}if(!t)continue;let d=t.find(s=>s.code===r.operationCode);if(!d){n.push("WORKFLOW_BUSINESS_COMMAND_OPERATION_MISSING");continue}(d.method!=="POST"||d.browser?.exposure!=="authenticated"||d.browser.behavior!=="controlled"||d.browser.idempotency!=="required"||d.browser.fileIntent||d.browser.subject?.resourceCode!==e.subject?.resourceCode||d.browser.subject?.inputField!=="recordId"||!d.platformAccess?.workflow?.codes?.includes(e.code)||!d.platformAccess.workflow.businessCommands?.includes(i))&&n.push("WORKFLOW_BUSINESS_COMMAND_OPERATION_INVALID")}return["approve","reject","withdraw"].some(i=>Object.hasOwn(o,i))&&Object.values(e.nodes||{}).some(i=>i.kind==="approval"&&(i.emptyPolicy==="skip"||i.initiatorApprovalPolicy==="auto_approve"))&&n.push("WORKFLOW_BUSINESS_COMMAND_AUTOMATIC_DECISION_FORBIDDEN"),[...new Set(n)]}var $u={type:"object",additionalProperties:!1,required:["workflowCode","target","recordId","expectedRevision","commandToken","idempotencyKey","input"],properties:{workflowCode:{type:"string",pattern:"^[A-Za-z][A-Za-z0-9_-]{0,127}$"},target:{oneOf:[{type:"object",additionalProperties:!1,required:["kind","id","command"],properties:{kind:{const:"task"},id:{type:"string",format:"uuid"},command:{enum:["approve","reject","resubmit"]}}},{type:"object",additionalProperties:!1,required:["kind","id","command"],properties:{kind:{const:"instance"},id:{type:"string",format:"uuid"},command:{const:"withdraw"}}}]},recordId:{type:"string",format:"uuid"},expectedRevision:{type:"integer",minimum:1},commandToken:{type:"string",pattern:"^[A-Za-z0-9_-]{43}$"},idempotencyKey:{type:"string",minLength:1,maxLength:128},input:{type:"object",maxProperties:64}}};var Ja=["fixed_users","initiator","app_role","app_role_in_scope"],Ha=e=>!!e&&typeof e=="object"&&!Array.isArray(e);function Ro(e,t){let o=e?.launchPreflight;if(o===void 0)return[];if(!Ha(o)||Object.keys(o).join(",")!=="requiredApprovalNodes"||!Array.isArray(o.requiredApprovalNodes)||o.requiredApprovalNodes.length<1||o.requiredApprovalNodes.length>20||new Set(o.requiredApprovalNodes).size!==o.requiredApprovalNodes.length||o.requiredApprovalNodes.some(i=>typeof i!="string"||!/^[A-Za-z][A-Za-z0-9_-]{0,127}$/.test(i)))return["WORKFLOW_LAUNCH_PREFLIGHT_INVALID"];let n=[];for(let i of o.requiredApprovalNodes){let r=e.nodes?.[i];if(!r||r.kind!=="approval"){n.push(`WORKFLOW_LAUNCH_PREFLIGHT_NODE_INVALID:${i}`);continue}if(!t)continue;let d=t.bindings?.[r.binding||""];(!d||!Ja.includes(d.provider)||d.candidateField!==void 0)&&n.push(`WORKFLOW_LAUNCH_PREFLIGHT_PROVIDER_UNSUPPORTED:${i}`)}return n}var Co=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Ya=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,hr=/^[A-Za-z][A-Za-z0-9_-]{0,127}$/,Cr=/^membership:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Vu=500,Lu=262144;function wr(e){if(e?.approvedDelegation===void 0)return[];let t=e.approvedDelegation;if(!Co(t)||Object.keys(t).some(a=>!["confirmationNodeId","confirmer","requestsField","maxRequests"].includes(a))||!hr.test(t.confirmationNodeId||"")||!["initiator","delegate"].includes(t.confirmer)||!Ya.test(t.requestsField||"")||!Number.isSafeInteger(t.maxRequests)||t.maxRequests<1||t.maxRequests>500)return["WORKFLOW_APPROVED_DELEGATION_POLICY_INVALID"];let o=[],n=e.nodes?.[t.confirmationNodeId];(!n||n.kind!=="approval"||n.mode!=="single"||n.emptyPolicy==="skip"||n.initiatorApprovalPolicy==="auto_approve"||n.completionDeadline||n.administration?.assigneeProviders?.length||n.administration?.modes?.some(a=>a!=="single")||n.allowedOperations?.some(a=>["transfer","delegate","add_assignee","admin_override"].includes(a)))&&o.push("WORKFLOW_APPROVED_DELEGATION_CONFIRMATION_INVALID");let i=e.inputSchema?.properties?.[t.requestsField];(!i||i.type!=="array"||!Number.isSafeInteger(i.maxItems)||i.maxItems<1||i.maxItems>t.maxRequests||!i.items||i.items.type!=="object"||i.items.additionalProperties!==!1||!e.subject?.factProjection?.[t.requestsField])&&o.push("WORKFLOW_APPROVED_DELEGATION_REQUEST_SCHEMA_INVALID"),Object.values(e.nodes||{}).some(a=>a.kind==="end"&&a.outcome==="approved")||o.push("WORKFLOW_APPROVED_DELEGATION_APPROVED_END_REQUIRED");let d=[e.startAt],s=new Set;for(;d.length;){let a=d.pop();if(a===t.confirmationNodeId||s.has(a))continue;s.add(a);let c=e.nodes?.[a];c&&(c.kind==="end"&&c.outcome==="approved"&&o.push("WORKFLOW_APPROVED_DELEGATION_CONFIRMATION_BYPASS"),c.kind==="approval"&&d.push(c.onApprove,c.onReject),c.kind==="condition"&&d.push(c.otherwise,...(c.branches||[]).map(f=>f.target)),(c.kind==="cc"||c.kind==="action")&&d.push(c.next))}return[...new Set(o)]}function Fu(e,t){let o=t?.data?.[e.requestsField],n=()=>{throw new Error("WORKFLOW_APPROVED_DELEGATION_REQUEST_INVALID")};(!Array.isArray(o)||!o.length||o.length>e.maxRequests||o.length>500||new TextEncoder().encode(JSON.stringify(o)).byteLength>262144)&&n();let i=["key","delegatorRoleSubjectKey","delegatorRoleSubjectRevision","delegate","delegateRoleSubjectKey","expectedDelegateRevision","workflowCode","nodeId","validFrom","validTo","reason"],r=(a,c)=>typeof a=="string"&&a.trim().length>0&&a.length<=c,d=a=>{if(typeof a!="string")return!1;let c=/^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)(?:\.\d{1,3})?(?:Z|[+-](\d\d):(\d\d))$/.exec(a);if(!c)return!1;let[,f,u,p,_,E,A,O,b]=c,g=Number(f),I=Number(u),T=Number(p),y=[31,g%4===0&&(g%100!==0||g%400===0)?29:28,31,30,31,30,31,31,30,31,30,31];return I>=1&&I<=12&&T>=1&&T<=y[I-1]&&Number(_)<=23&&Number(E)<=59&&Number(A)<=59&&(O===void 0||Number(O)<=23&&Number(b)<=59)&&Number.isFinite(Date.parse(a))},s=o.map(a=>Co(a)?((Object.keys(a).some(c=>!i.includes(c))||!r(a.delegatorRoleSubjectKey,255)||!Cr.test(a.delegatorRoleSubjectKey)||!r(a.delegateRoleSubjectKey,255)||!Cr.test(a.delegateRoleSubjectKey)||!Number.isSafeInteger(a.delegatorRoleSubjectRevision)||a.delegatorRoleSubjectRevision<1||!Number.isSafeInteger(a.expectedDelegateRevision)||a.expectedDelegateRevision<1||!Co(a.delegate)||Object.keys(a.delegate).some(c=>!["value","label"].includes(c))||!r(a.delegate.value,255)||!r(a.delegate.label,200)||!(a.workflowCode===null||r(a.workflowCode,128)&&hr.test(a.workflowCode))||!(a.nodeId===null||r(a.nodeId,128)&&/^[A-Za-z0-9._:-]{1,128}$/.test(a.nodeId)&&a.workflowCode)||!d(a.validFrom)||!d(a.validTo)||Date.parse(a.validFrom)>=Date.parse(a.validTo)||!r(a.reason,4e3)||a.key!==void 0&&!r(a.key,128))&&n(),{...a,delegate:{value:a.delegate.value,label:a.delegate.label},validFrom:new Date(a.validFrom).toISOString(),validTo:new Date(a.validTo).toISOString()}):n());return e.confirmer==="delegate"&&new Set(s.map(a=>a.delegate.value)).size!==1&&n(),s}var Xa=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&[null,Object.prototype].includes(Object.getPrototypeOf(e));function Sr(e){let t=e?.nodes||{},o=Object.values(t).filter(s=>s?.kind==="correction");if(!o.length)return[];let n=[],i=s=>s?.kind==="approval"?[s.onApprove,s.onReject]:s?.kind==="condition"?[...(Array.isArray(s.branches)?s.branches:[]).map(a=>a.target),s.otherwise]:s?.kind==="action"||s?.kind==="cc"?[s.next]:[],r=new Set,d=[e.startAt];for(;d.length;){let s=d.pop();r.has(s)||(r.add(s),d.push(...i(t[s])))}for(let s of o){(!Xa(s)||Object.keys(s).some(c=>!["id","kind","title","taskPageCode","next"].includes(c))||typeof s.id!="string"||!/^[A-Za-z][A-Za-z0-9_-]{0,127}$/.test(s.id)||["__proto__","prototype","constructor"].includes(s.id)||t[s.id]!==s||typeof s.title!="string"||!s.title.trim()||s.title.length>255||typeof s.taskPageCode!="string"||!/^[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(s.taskPageCode))&&n.push("WORKFLOW_CORRECTION_NODE_INVALID"),(s.next!==e.startAt||t[s.next]?.kind==="correction")&&n.push("WORKFLOW_CORRECTION_REPLAY_TARGET_INVALID"),(r.has(s.id)||Object.values(t).some(c=>i(c).includes(s.id)))&&n.push("WORKFLOW_CORRECTION_FORWARD_ENTRY_FORBIDDEN"),Object.values(t).some(c=>c?.kind==="approval"&&r.has(c.id)&&Array.isArray(c.returnTargets)&&c.returnTargets.includes(s.id))||n.push("WORKFLOW_CORRECTION_RETURN_SOURCE_REQUIRED");let a=e.taskPages?.[s.taskPageCode];!a||!Array.isArray(a.fields)?n.push("WORKFLOW_CORRECTION_PAGE_REQUIRED"):a.fields.some(c=>c?.subtable&&Object.values(e.subject?.factProjection||{}).some(f=>f===c.code||f.startsWith(`${c.code}.`)))&&n.push("WORKFLOW_CORRECTION_OWNED_FACTS_UNSUPPORTED")}return[...new Set(n)]}var cn=class extends Error{constructor(o){super(o);this.code=o}code},Wu=["projection","triggerCode","resourceCode","recordId","recordRevision","field","dueAt"];function Dr(e,t,o){let n=r=>{throw new cn(r)};t.length>100&&n("DATE_TRIGGER_PROJECTION_LIMIT");let i=new Set;for(let r of t){let d=r.filter?.resourceCodes||[];if(Array.isArray(d)||n("DATE_TRIGGER_PROJECTION_INVALID"),d.length&&!d.includes(e))continue;let s=r.payload?.fields||[];(!Array.isArray(s)||s.length>32)&&n("DATE_TRIGGER_PROJECTION_LIMIT");for(let a of s)(typeof a!="string"||!/^[A-Za-z_][A-Za-z0-9_]{0,62}$/.test(a)||["__proto__","constructor","prototype"].includes(a))&&n("DATE_TRIGGER_PROJECTION_FIELD_INVALID"),i.add(a)}if(i.size>64&&n("DATE_TRIGGER_PROJECTION_LIMIT"),o!==void 0){let r=o?.schema?.fields??o?.fields;Array.isArray(r)||n("DATE_TRIGGER_PROJECTION_RESOURCE_INVALID");let d=new Map(r.map(s=>[s.code,s]));for(let s of i){let a=d.get(s);a||n("DATE_TRIGGER_PROJECTION_FIELD_UNKNOWN"),a.type==="subtable"&&n("DATE_TRIGGER_PROJECTION_SUBTABLE_FORBIDDEN"),o.fieldPolicies?.[s]?.mask==="omit"&&n("DATE_TRIGGER_PROJECTION_FIELD_SENSITIVE")}}return[...i].sort()}function Uu(e,t){if(!t.length)return e;let o=e?.properties?.projection;if(o?.type!=="object"||!o.properties||typeof o.properties!="object"||Array.isArray(o.properties)||o.additionalProperties!==!1||o.required!==void 0&&!Array.isArray(o.required)||t.some(n=>!Object.hasOwn(o.properties,n))||(o.required||[]).some(n=>!t.includes(n)))throw new cn("DATE_TRIGGER_PROJECTION_SCHEMA_INVALID");return{...e,properties:{...e.properties,projection:{}}}}var Za=200,wo=1024*1024,Qa=65536,Pr=Be,kr=tt,Je=new Set(["__proto__","prototype","constructor"]),vr=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,Dt=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,$r=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,de=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&[null,Object.prototype].includes(Object.getPrototypeOf(e)),ke=(e,t)=>de(e)&&Object.keys(e).every(o=>t.includes(o)&&!Je.has(o)),ln=e=>{try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return 1/0}},Vr=e=>e==null||typeof e=="string"&&!e.trim()||Array.isArray(e)&&e.length===0;function xe(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((n,i)=>xe(n,t[i]));if(!de(e)||!de(t))return!1;let o=Object.keys(e);return o.length===Object.keys(t).length&&o.every(n=>Object.hasOwn(t,n)&&xe(e[n],t[n]))}function ho(e,t){let o=t.split(".");if(!(o.some(n=>!vr.test(n)||Je.has(n))||o.length>12))return o.reduce((n,i)=>de(n)&&Object.hasOwn(n,i)?n[i]:void 0,e)}function Fe(e,t){switch(e.op){case"literal":return e.value;case"path":return ho({values:t},e.path);case"and":return e.values.every(o=>!!Fe(o,t));case"or":return e.values.some(o=>!!Fe(o,t));case"not":return!Fe(e.value,t);case"exists":return!Vr(Fe(e.value,t));default:{let o=Fe(e.left,t),n=Fe(e.right,t);return e.op==="eq"?xe(o,n):e.op==="neq"?!xe(o,n):e.op==="in"?Array.isArray(n)&&n.some(i=>xe(i,o)):e.op==="contains"?Array.isArray(o)?o.some(i=>xe(i,n)):typeof o=="string"&&typeof n=="string"&&o.includes(n):typeof o!="number"||typeof n!="number"||!Number.isFinite(o)||!Number.isFinite(n)?!1:e.op==="gt"?o>n:e.op==="gte"?o>=n:e.op==="lt"?o<n:o<=n}}}function St(e,t,o=0,n={nodes:0}){if(o>8||++n.nodes>64||!de(e))return!1;if(e.op==="literal")return ke(e,["op","value"])&&Object.hasOwn(e,"value")&&ln(e.value)<=4096&&kt(e.value);if(e.op==="path"){if(!ke(e,["op","path"])||typeof e.path!="string")return!1;let i=e.path.split(".");return i[0]==="values"&&i.length>=2&&i.length<=8&&t.has(i[1])&&i.every(r=>Dt.test(r)&&!Je.has(r))}return["not","exists"].includes(e.op)?ke(e,["op","value"])&&St(e.value,t,o+1,n):["and","or"].includes(e.op)?ke(e,["op","values"])&&Array.isArray(e.values)&&e.values.length>0&&e.values.length<=16&&e.values.every(i=>St(i,t,o+1,n)):["eq","neq","gt","gte","lt","lte","in","contains"].includes(e.op)&&ke(e,["op","left","right"])&&St(e.left,t,o+1,n)&&St(e.right,t,o+1,n)}function un(e,t,o,n=kr){let i=[],r=e.taskPages;if(r!==void 0&&(!de(r)||Object.keys(r).length===0||Object.keys(r).length>16||ln(r)>Qa))return["WORKFLOW_TASK_PAGES_INVALID"];for(let[d,s]of Object.entries(r||{})){let a=`taskPages.${d}`;if(!vr.test(d)||Je.has(d)||!ke(s,["title","fields"])||typeof s.title!="string"||!s.title.trim()||s.title.length>160||!Array.isArray(s.fields)||!s.fields.length||s.fields.length>Za){i.push(`WORKFLOW_TASK_PAGE_INVALID:${a}`);continue}let c=new Set(s.fields.map(p=>p?.code));c.size!==s.fields.length&&i.push(`WORKFLOW_TASK_PAGE_DUPLICATE_FIELD:${a}`);let f=0,u=new Set;for(let p of s.fields){if(!ke(p,["code","readonly","required","visibleWhen","requiredWhen","subtable"])||!Dt.test(p.code)||Je.has(p.code)||["readonly","required"].some(_=>p[_]!==void 0&&typeof p[_]!="boolean")||p.readonly&&(p.required||p.requiredWhen)){i.push(`WORKFLOW_TASK_PAGE_FIELD_INVALID:${a}`);continue}for(let _ of["visibleWhen","requiredWhen"])p[_]!==void 0&&!St(p[_],c)&&i.push(`WORKFLOW_TASK_PAGE_EXPRESSION_INVALID:${a}.${p.code}.${_}`);if(t){let _=t.get(p.code);if((!_||_.system||_.hidden||_.type==="serial-number"||!p.readonly&&_.widget==="readonly"||!p.readonly&&_.type==="subtable"&&!p.subtable||p.subtable&&_.type!=="subtable")&&i.push(`WORKFLOW_TASK_PAGE_RESOURCE_FIELD_INVALID:${a}.${p.code}`),p.subtable&&_?.subtable){let E=_.subtable;f+=E.maxRows??20,(u.has(E.resourceCode)||!Number.isSafeInteger(E.maxRows??20)||(E.maxRows??20)<1||(E.maxRows??20)>Pr||!Dt.test(E.foreignKey)||!Dt.test(E.orderField)||E.foreignKey===E.orderField)&&i.push(`WORKFLOW_TASK_SUBTABLE_RELATION_INVALID:${a}.${p.code}`),u.add(E.resourceCode);let A=o?.get(E.resourceCode);o&&(!A||!["uuid","resource-ref.single"].includes(A.get(E.foreignKey)?.type||"")||A.get(E.orderField)?.type!=="number.integer")&&i.push(`WORKFLOW_TASK_SUBTABLE_RELATION_INVALID:${a}.${p.code}`);for(let O of Array.isArray(p.subtable.fields)?p.subtable.fields:[]){if(!O||typeof O.code!="string")continue;let b=A?.get(O.code);(O.code===E.foreignKey||O.code===E.orderField||A&&(!b||b.system||b.hidden||b.type==="subtable"||!O.readonly&&(b.widget==="readonly"||b.type==="serial-number")))&&i.push(`WORKFLOW_TASK_SUBTABLE_FIELD_UNSUPPORTED:${a}.${p.code}.${O.code}`)}}else p.subtable&&t&&i.push(`WORKFLOW_TASK_SUBTABLE_RELATION_INVALID:${a}.${p.code}`)}p.subtable&&(p.readonly||!ke(p.subtable,["fields","create","delete","reorder"])||["create","delete","reorder"].some(_=>p.subtable?.[_]!==void 0&&typeof p.subtable[_]!="boolean")||!Array.isArray(p.subtable.fields)||p.subtable.fields.some(_=>_?.subtable)?i.push(`WORKFLOW_TASK_SUBTABLE_PAGE_INVALID:${a}.${p.code}`):i.push(...un({taskPages:{child:{title:"\u5B50\u884C",fields:p.subtable.fields}}},o?.get(t?.get(p.code)?.subtable?.resourceCode||"")).map(_=>`${_}:${a}.${p.code}`)))}(f>Math.min(n,kr)||f<0||!Number.isSafeInteger(f)||!Number.isSafeInteger(n)||n<1)&&i.push(`WORKFLOW_TASK_SUBTABLE_BUDGET_EXCEEDED:${a}`)}for(let[d,s]of Object.entries(e.nodes||{}))de(s)&&s.taskPageCode!==void 0&&(!["approval","correction"].includes(s.kind)||typeof s.taskPageCode!="string"||!de(r)||!Object.hasOwn(r,s.taskPageCode)?i.push(`WORKFLOW_TASK_PAGE_NOT_FOUND:${d}`):Array.isArray(r[s.taskPageCode]?.fields)&&r[s.taskPageCode].fields.some(a=>a&&(s.fieldPolicy?.fields?.[a.code]||s.fieldPolicy?.default)==="hidden")&&i.push(`WORKFLOW_TASK_PAGE_FIELD_HIDDEN:${d}`));return i}function Lr(e,t){return e.fields.map(o=>({code:o.code,visible:o.visibleWhen===void 0||!!Fe(o.visibleWhen,t),readonly:o.readonly===!0,required:o.required===!0||o.requiredWhen!==void 0&&!!Fe(o.requiredWhen,t)}))}var we=class extends Error{constructor(o,n){super(o);this.code=o;this.field=n}code;field;rowIndex;childField};function Ku(e,t){return t.map(o=>({key:String(o.id),id:String(o.id),revision:Number(o.revision),state:"persisted",values:Object.fromEntries(Lr({title:"\u5B50\u884C",fields:e.fields},o).filter(n=>n.visible&&!n.readonly).map(n=>[n.code,o[n.code]??null]))}))}function Gu(e,t,o,n,i,r=!0,d=0){let s=e.subtable,a=_=>{throw new we(_,e.code)};if(!s||!Number.isSafeInteger(t)||t<1||t>Pr||!Number.isSafeInteger(d)||d<0||d>t||!Array.isArray(n)||n.length>2*t||ln(n)>wo||!kt(n))return a("WORKFLOW_TASK_SUBTABLE_VALUES_INVALID");let c=new Map(o.map(_=>[String(_.id),_])),f=new Set,u=new Set,p=[];for(let _ of n){if(!ke(_,["key","state","id","revision","values"])||typeof _.key!="string"||!$r.test(_.key)||f.has(_.key)||!["created","persisted","deleted"].includes(_.state)||!de(_.values))return a("WORKFLOW_TASK_SUBTABLE_ROW_INVALID");if(f.add(_.key),_.state==="created"){if(!s.create||_.id!==void 0||_.revision!==void 0||c.has(_.key))return a("WORKFLOW_TASK_SUBTABLE_CREATE_FORBIDDEN")}else{if(typeof _.id!="string"||_.id!==_.key||!$r.test(_.id)||u.has(_.id)||!Number.isSafeInteger(_.revision)||_.revision<1||!c.has(_.id))return a("WORKFLOW_TASK_SUBTABLE_SCOPE_CONFLICT");if(u.add(_.id),r&&Number(c.get(_.id).revision)!==_.revision)return a("WORKFLOW_TASK_SUBTABLE_REVISION_CONFLICT")}if(_.state==="deleted"){if(!s.delete||Object.keys(_.values).length)return a("WORKFLOW_TASK_SUBTABLE_DELETE_FORBIDDEN");continue}try{ed({title:e.code,fields:s.fields},_.id?c.get(_.id):{},_.values,i)}catch(E){if(!(E instanceof we))throw E;let A=new we(E.code,e.code);throw A.rowIndex=p.length,E.field!==void 0&&(A.childField=E.field),A}p.push(_)}if(u.size!==c.size)return a("WORKFLOW_TASK_SUBTABLE_SCOPE_CONFLICT");if(p.length>t)return a("WORKFLOW_TASK_SUBTABLE_MAX_ROWS_EXCEEDED");if(i&&p.length<d)return a("WORKFLOW_TASK_SUBTABLE_MIN_ROWS_NOT_MET");if(!s.reorder){let _=o.filter(A=>p.some(O=>O.id===String(A.id))).map(A=>String(A.id)),E=p.filter(A=>A.state==="persisted").map(A=>A.id);if(!xe(_,E)||p.some((A,O)=>A.state==="created"&&p.slice(O+1).some(b=>b.state==="persisted")))return a("WORKFLOW_TASK_SUBTABLE_REORDER_FORBIDDEN")}return n}function kt(e,t={members:0},o=0){return++t.members>5e4||o>12?!1:e===null||typeof e=="boolean"?!0:typeof e=="string"?e.length<=wo:typeof e=="number"?Number.isFinite(e):Array.isArray(e)?e.length<=1e3&&e.every(n=>kt(n,t,o+1)):de(e)&&Object.entries(e).every(([n,i])=>!Je.has(n)&&kt(i,t,o+1))}function ed(e,t,o,n){if(!de(o)||ln(o)>wo||!kt(o))throw new we("WORKFLOW_TASK_FORM_VALUES_INVALID");let i={...t,...o},r=new Map(Lr(e,i).map(d=>[d.code,d]));for(let d of Object.keys(o)){let s=r.get(d);if(!s||s.readonly||!s.visible)throw new we("WORKFLOW_TASK_FORM_FIELD_NOT_EDITABLE",d)}if(n)for(let d of r.values()){let s=i[d.code],a=e.fields.find(c=>c.code===d.code)?.subtable&&Array.isArray(s)?s.every(c=>de(c)&&c.state==="deleted"):Vr(s);if(d.visible&&!d.readonly&&d.required&&a)throw new we("WORKFLOW_TASK_FORM_REQUIRED",d.code)}return i}function qu(e,t,o){let n=JSON.parse(JSON.stringify(t));for(let[d,s]of Object.entries(e.subject?.factProjection||{})){let a=d.split(".");if(!a.length||a.length>12||d.length>128||a[0]==="steps"||a.some(f=>!Dt.test(f)||Je.has(f)))throw new we("WORKFLOW_TASK_FORM_FACT_PROJECTION_INVALID");if(!Object.hasOwn(o,s))throw new we("WORKFLOW_TASK_FORM_FACT_FIELD_MISSING",s);let c=n;for(let f of a.slice(0,-1))c=c[f]=de(c[f])?c[f]:{};c[a.at(-1)]=o[s]===void 0?void 0:JSON.parse(JSON.stringify(o[s]))}let i=new Set,r=Object.values(e.nodes||{}).filter(d=>d.kind==="action");for(let d=0;d<=r.length;d++){let s=!1;for(let a of r)de(n.steps)&&Object.hasOwn(n.steps,a.id)&&Object.values(a.inputs||{}).some(c=>c.source==="fact"&&!xe(ho(t,c.path),ho(n,c.path)))&&(delete n.steps[a.id],i.add(a.id),s=!0);if(!s)break}return{facts:n,invalidatedNodeIds:[...i].sort()}}function zu(e,t,o){let n=e.nodes||{};for(let i of o){let r=new Set,d=new Map,s=a=>{if(a===i)return!0;if(d.has(a))return d.get(a);if(r.has(a)||r.size>200)return!1;let c=n[a];if(!de(c)||c.kind==="end")return!1;r.add(a);let f=c.kind==="approval"?[c.onApprove]:c.kind==="condition"?[...(c.branches||[]).map(p=>p.target),c.otherwise]:[c.next],u=f.length>0&&f.every(p=>typeof p=="string"&&s(p));return r.delete(a),d.set(a,u),u};if(!s(t))return!1}return!0}var Hu=256,Yu=64,Xu=262144,td=/^[a-z][a-z0-9_-]{0,127}$/,nd=/^[A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z][A-Za-z0-9_]*)*$/,xr=new Set(["__proto__","prototype","constructor"]),Se=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Pt=(e,t)=>Object.keys(e).every(o=>t.includes(o)),He=(e,t)=>typeof e=="string"&&e.trim().length>0&&e.length<=t&&!/[\u0000-\u001f\u007f]/.test(e),$e=e=>typeof e=="string"&&td.test(e)&&!xr.has(e),jr=e=>typeof e=="string"&&e.length<=255&&nd.test(e)&&!e.split(".").some(t=>xr.has(t)),od=e=>Se(e)&&Pt(e,["dimension","valueFrom","value"])&&$e(e.dimension)&&(He(e.value,255)&&e.valueFrom===void 0||jr(e.valueFrom)&&e.value===void 0),Fr=e=>typeof e=="string"&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?(?:Z|[+-]\d{2}:\d{2})$/.test(e)&&Number.isFinite(Date.parse(e)),$t={type:"string",pattern:"^[a-z][a-z0-9_-]{0,127}$"},So={type:"string",minLength:1,maxLength:128},Zu={type:"object",additionalProperties:!1,required:["policyCode","title","strategy","dimensions","sources"],properties:{policyCode:$t,title:So,strategy:{enum:["replace_then_append","replace_only"]},dimensions:{type:"object",maxProperties:8,propertyNames:$t,additionalProperties:{type:"object",additionalProperties:!1,required:["title","valueFrom"],properties:{title:So,valueFrom:{type:"string",minLength:1,maxLength:255}}}},sources:{type:"object",minProperties:1,maxProperties:16,propertyNames:$t,additionalProperties:{type:"object",additionalProperties:!1,required:["title","provider","roleCode"],properties:{title:So,provider:{enum:["app_role","app_role_in_scope"]},roleCode:$t,scope:{type:"object",additionalProperties:!1,required:["dimension"],properties:{dimension:$t,value:{type:"string",minLength:1,maxLength:255},valueFrom:{type:"string",minLength:1,maxLength:255}}}}}}}};function fn(e){if(!Se(e)||!Pt(e,["policyCode","title","strategy","dimensions","sources"])||!$e(e.policyCode)||!He(e.title,128)||!["replace_then_append","replace_only"].includes(e.strategy))return["WORKFLOW_V2_ROUTING_POLICY_INVALID"];let t=[];return(!Se(e.dimensions)||Object.keys(e.dimensions).length>8||Object.entries(e.dimensions).some(([o,n])=>!$e(o)||!Se(n)||!Pt(n,["title","valueFrom"])||!He(n.title,128)||!jr(n.valueFrom)))&&t.push("WORKFLOW_V2_ROUTING_DIMENSIONS_INVALID"),(!Se(e.sources)||Object.keys(e.sources).length<1||Object.keys(e.sources).length>16||Object.entries(e.sources).some(([o,n])=>!$e(o)||!Se(n)||!Pt(n,["title","provider","roleCode","scope"])||!He(n.title,128)||!$e(n.roleCode)||!["app_role","app_role_in_scope"].includes(n.provider)||(n.provider==="app_role_in_scope"?!od(n.scope):n.scope!==void 0)))&&t.push("WORKFLOW_V2_ROUTING_SOURCES_INVALID"),t}function Qu(e,t){if(fn(e).length)return["WORKFLOW_V2_ROUTING_POLICY_INVALID"];if(!Array.isArray(t)||t.length>256||new TextEncoder().encode(JSON.stringify(t)).length>262144)return["WORKFLOW_V2_ROUTING_RULE_LIMIT_EXCEEDED"];let o=[],n=new Set;for(let i of t){if(!Se(i)||!Pt(i,["ruleCode","title","enabled","workflowCode","nodeId","matches","sourceCode","effect","priority","validFrom","validTo"])||!$e(i.ruleCode)||!He(i.title,128)||typeof i.enabled!="boolean"||!$e(i.sourceCode)||!Object.hasOwn(e.sources,i.sourceCode)||!["append","replace"].includes(i.effect)||!Number.isSafeInteger(i.priority)||i.priority<-1e3||i.priority>1e3||i.workflowCode!==void 0&&!$e(i.workflowCode)||i.nodeId!==void 0&&(!$e(i.nodeId)||i.workflowCode===void 0)||i.validFrom!==void 0&&!Fr(i.validFrom)||i.validTo!==void 0&&!Fr(i.validTo)||i.validFrom&&i.validTo&&Date.parse(i.validFrom)>=Date.parse(i.validTo)){o.push("WORKFLOW_V2_ROUTING_RULE_INVALID");continue}n.has(i.ruleCode)&&o.push(`WORKFLOW_V2_ROUTING_RULE_DUPLICATE:${i.ruleCode}`),n.add(i.ruleCode),(!Se(i.matches)||Object.entries(i.matches).some(([r,d])=>!Object.hasOwn(e.dimensions,r)||!Array.isArray(d)||d.length<1||d.length>64||new Set(d).size!==d.length||d.some(s=>!He(s,255))))&&o.push(`WORKFLOW_V2_ROUTING_MATCH_INVALID:${i.ruleCode}`)}return[...new Set(o)]}function id(e){return JSON.stringify({policyCode:e.policyCode,strategy:e.strategy,dimensions:Object.entries(e.dimensions).sort(([t],[o])=>t<o?-1:t>o?1:0).map(([t,o])=>[t,o.valueFrom]),sources:Object.entries(e.sources).sort(([t],[o])=>t<o?-1:t>o?1:0).map(([t,o])=>[t,o.provider,o.roleCode,o.scope?.dimension??null,o.scope?.valueFrom??null,o.scope?.value??null])})}function Wr(e){let t=[],o=new Map;for(let n of e)for(let[i,r]of Object.entries(n.bindings||{})){if(!Se(r)||r.routing===void 0)continue;let d=fn(r.routing);if(d.length){t.push(...d.map(c=>`${c}:${i}`));continue}let s=id(r.routing),a=o.get(r.routing.policyCode);a&&a!==s&&t.push(`WORKFLOW_V2_ROUTING_POLICY_CONFLICT:${r.routing.policyCode}`),o.set(r.routing.policyCode,s)}return[...new Set(t)]}function ef(e,t){let o={};for(let[n,i]of Object.entries(e.dimensions)){let r=t;for(let d of i.valueFrom.split("."))r=Se(r)&&Object.hasOwn(r,d)?r[d]:void 0;if(!(typeof r=="string"&&He(r,255)||typeof r=="number"&&Number.isFinite(r)||typeof r=="boolean"))throw new Error(`WORKFLOW_V2_ROUTING_FACT_REQUIRED:${n}`);o[n]=String(r)}return o}function tf(e,t,o){let n=t.filter(c=>c.enabled&&(!c.validFrom||Date.parse(c.validFrom)<=o.at)&&(!c.validTo||Date.parse(c.validTo)>o.at)&&(!c.workflowCode||c.workflowCode===o.workflowCode)&&(!c.nodeId||c.nodeId===o.nodeId)&&Object.entries(c.matches).every(([f,u])=>u.includes(o.facts[f])));if(n.length>64)throw new Error("WORKFLOW_V2_ROUTING_MATCH_LIMIT_EXCEEDED");let i=(c,f)=>f.priority-c.priority||+!!c.workflowCode-+!!f.workflowCode||+!!c.nodeId-+!!f.nodeId||(c.ruleCode<f.ruleCode?-1:c.ruleCode>f.ruleCode?1:0),r=n.filter(c=>c.effect==="replace").sort(i);if(r.length>1&&r[0].priority===r[1].priority)throw new Error("WORKFLOW_V2_ROUTING_REPLACE_CONFLICT");let d=r[0],s=d&&e.strategy==="replace_only"?[]:n.filter(c=>c.effect==="append").sort(i),a=[...d?[d]:[],...s];return{matched:n.sort(i),replacement:d,applied:a,ignored:n.filter(c=>!a.includes(c))}}var Do="^[A-Za-z][A-Za-z0-9_]{0,62}$",Ur="^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$",rf={type:"object",additionalProperties:!1,required:["mode","resourceCode","subtables"],properties:{mode:{const:"create"},resourceCode:{type:"string",maxLength:64,pattern:Ur},subtables:{type:"array",minItems:1,maxItems:16,items:{type:"object",additionalProperties:!1,required:["fieldCode","fieldCodes"],properties:{fieldCode:{type:"string",pattern:Do},fieldCodes:{type:"array",minItems:1,maxItems:200,uniqueItems:!0,items:{type:"string",pattern:Do}}}}}}};function pn(e){let t=n=>!!(n&&typeof n=="object"&&!Array.isArray(n)),o=n=>typeof n=="string"&&new RegExp(Do).test(n)&&!["__proto__","prototype","constructor"].includes(n);if(!t(e)||Object.keys(e).some(n=>!["mode","resourceCode","subtables"].includes(n))||e.mode!=="create"||typeof e.resourceCode!="string"||e.resourceCode.length>64||!new RegExp(Ur).test(e.resourceCode)||!Array.isArray(e.subtables)||e.subtables.length<1||e.subtables.length>16||e.subtables.some(n=>!t(n)||Object.keys(n).some(i=>!["fieldCode","fieldCodes"].includes(i))||!o(n.fieldCode)||!Array.isArray(n.fieldCodes)||n.fieldCodes.length<1||n.fieldCodes.length>200||new Set(n.fieldCodes).size!==n.fieldCodes.length||n.fieldCodes.some(i=>!o(i)))||new Set(e.subtables.map(n=>n.fieldCode)).size!==e.subtables.length)throw new Error("WORKFLOW_OWNED_SUBJECT_CREATE_INVALID")}function sf(e){return pn(e),{mode:"create",resourceCode:e.resourceCode,subtables:e.subtables.map(t=>({fieldCode:t.fieldCode,fieldCodes:[...t.fieldCodes].sort()})).sort((t,o)=>t.fieldCode.localeCompare(o.fieldCode))}}function Mr(e,t,o){pn(e);let n=s=>{throw new Error(`WORKFLOW_OWNED_SUBJECT_${s}`)},i=t.get(e.resourceCode);i||n("RESOURCE_MISSING");let r=new Set,d=0;for(let s of e.subtables){let a=i.get(s.fieldCode),c=a?.subtable,f=t.get(c?.resourceCode);(a?.type!=="subtable"||!f||c.resourceCode===e.resourceCode||r.has(c.resourceCode))&&n("RELATION_INVALID"),r.add(c.resourceCode);let u=c.maxRows??20;(!Number.isSafeInteger(u)||u<1||u>Be)&&n("BUDGET_EXCEEDED"),d+=u;for(let p of s.fieldCodes){let _=f.get(p);(!_||["serial-number","subtable"].includes(_.type)||[c.foreignKey,c.orderField].includes(p))&&n("FIELD_INVALID"),["file","image","signature","text.rich"].includes(_.type)&&!o.some(E=>E.resourceCode===c.resourceCode&&E.fieldCodes.includes(p)&&E.intents.includes("create"))&&n("FILE_ACCESS_REQUIRED")}}d>tt&&n("BUDGET_EXCEEDED")}import*as yn from"crypto";var Br="native-4",ko="2.0.0-alpha.5",Kr={"application-native-2":"1.0.0","application.extended-declaration-capacity":"1.0.0","application.extended-role-capacity":"1.0.0","application.extended-artifact-capacity":"1.0.0","application.high-density-artifact-capacity":"1.0.0","application.extended-configuration-bytes":"1.0.0","application.development-configuration":"2.0.0","authz.native-batch-explain":"1.0.0","authz.native-management":"1.0.0","authz.native-membership-batch":"1.0.0","deployment.durable-runs":"1.0.0","deployment.platform-executor":"1.0.0","environment.on-demand-production":"1.0.0","environment.runtime-lifecycle":"1.0.0","data.rich-text":"1.0.0","data-api-v2":"1.1.0","data.extended-owned-subtable-capacity":"1.0.0","data.aggregate-owned-subtable-capacity":"1.0.0","data.extended-field-capacity":"1.0.0","data.business-commands":"1.0.0","data.record-edit":"1.0.0","data.native-golden-crud":"1.0.0","data.audit-read-access":"1.0.0","data.managed-files":"1.1.0","data.decimal-reservations":"1.1.0","data.decimal-reservation-lifecycle":"1.0.0","data.unique-keys":"1.1.0","data.user-candidates":"1.0.0","data.user-candidate-launch-scope":"1.0.0","data.datetime-minute-precision":"1.0.0","data.subtable-minimum-rows":"1.0.0","data.managed-concurrency":"1.0.0","data.managed-concurrency.durable":"1.0.0","workflow.named-input-sources":"1.0.0","workflow.approved-delegation":"1.0.0","directory-v2":"1.0.0","directory.selected-user":"1.0.0","directory.selected-departments":"1.0.0","directory.current-initiator-phone":"1.0.0","events-v2":"1.0.0","events.durable-receipts":"1.0.0","events.capture-policy":"1.0.0","events.date-source-projection":"1.0.0","events.native-data-actions":"1.0.0","workflow-kernel-v2":"1.0.0","workflow.business-data-command":"1.0.0","workflow.approval-business-command":"1.0.0","workflow.native-stage-guard":"1.0.0","workflow.launch-preflight":"1.0.0","workflow.optional-rejection-comment":"1.0.0","workflow.optional-operation-reason":"1.0.0","workflow.optional-withdrawal-reason":"1.0.0","data.transaction-actor-authority":"1.0.0","data.authenticated-public-projection":"1.0.0","data.parent-read-policy":"1.0.0","data.record-print":"1.0.0","data.workflow-record-deletion":"1.0.0","data.record-comments":"1.0.0","workflow.record-history-read":"1.0.0","workflow.rejection-notification":"1.0.0","workflow.instance-cancellation-policy":"1.0.0","workflow.node-administration":"1.0.0","workflow.assignment-routing":"1.0.0","workflow.role-union":"1.0.0","workflow.role-input-selection":"1.0.0","workflow.named-owned-create":"1.0.0","workflow.owned-initial-facts":"1.0.0","workflow.initiator-correction":"1.0.0","workflow.correction-business-command":"1.0.0","workflow.correction-derived-subject-facts":"1.0.0","workflow.role-references":"1.0.0","workflow.delegation-management":"1.0.0","workflow.automatic-cc":"1.0.0","workflow.approval-empty-policy":"1.0.0","workflow.initiator-approval-policy":"1.0.0","workflow.completion-deadline":"1.0.0","workflow.task-page-submit":"1.0.0","workflow.task-private-drafts":"1.0.0","workflow.task-managed-files":"1.0.0","workflow.task-rich-fields":"1.0.0","workflow.task-owned-subtables":"1.0.0","workflow.task-owned-files":"1.0.0","workflow.durable-business-step":"1.0.0","workflow.step-data-transaction":"1.0.0","business-process.durable-command":"1.1.0","workflow.fresh-command-token":"1.0.0","notification-hub-v2":"1.0.0","authentication.application-login-surface":"1.0.0","public-access.anonymous-owner-records":"1.0.0"};var B=Object.freeze({perspectives:100,resources:512,dataPolicies:512,roles:512,subjectReadSurfaces:50,capabilities:4096,operations:500,eventConsumers:100,eventProducers:1e3,eventSchemas:100,eventTypes:500,workflows:512,routes:2048,adminPages:2048,adminNavigationGroups:100,adminNavigationItems:1024});function Gr(e){let t=(e.surface?.mutationOwner||"native")==="native";return["query","get","create","update","delete"].filter(o=>{let n=e.surface?.generated;return o==="query"?n?.list??!0:o==="get"?n?.detail??!0:n?.[o]??t})}function $o(e){return(e.authz?.roles?.length||0)>256}function Po(e){let t=(e.data?.resources||[]).filter(o=>o.status!=="retired").reduce((o,n)=>o+Gr(n).length,0)+(e.backend?.operations||[]).filter(o=>o.ai).length;return(e.data?.resources?.length||0)>100||(e.authz?.dataPolicies?.length||0)>100||(e.authz?.roles?.length||0)>100||(e.authz?.capabilities?.length||0)>2e3||[e.workflows?.definitions,e.workflows?.bindings,e.workflows?.activations].some(o=>(o?.length||0)>100)||(e.frontend?.routes?.length||0)>500||t>500||(e.frontend?.admin?.navigation||[]).reduce((o,n)=>o+n.items.length,0)>500}var re=Object.freeze({legacyConfigBytes:4194304,configBytes:8388608,contractBytes:8388608,depth:40,stringBytes:1048576,legacyNodes:1e5,extendedNodes:25e4}),ct=Object.freeze({nodes:5e5});function vo(e){return Buffer.byteLength(X(e),"utf8")>re.legacyConfigBytes}function qr(e,t){let o=0,n=[[e][Symbol.iterator]()];for(;n.length;){let i=n[n.length-1].next();if(i.done){n.pop();continue}if(++o>t)return!0;if(Array.isArray(i.value))n.push(i.value.values());else if(i.value&&typeof i.value=="object"){let r=i.value;n.push((function*(){for(let d of Object.keys(r))r[d]!==void 0&&(yield r[d])})())}}return!1}function mn(e){return qr(e,re.legacyNodes)}function _n(e){return qr(e,re.extendedNodes)}var rd="openxiangda.config-bundle/v3",ls="openxiangda.contract-bundle/v3",zr="openxiangda.native-configuration-projection/v1",Vt=Br,sd=/^[a-f0-9]{64}$/,ad=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,dd=/^app:[a-z][a-z0-9]*(?:-[a-z0-9]+)*:[A-Za-z0-9:._*-]+$/,cd=/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/,ld=/^[a-z][a-z0-9]*(?:[-.][a-z0-9]+)*$/,ud=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,fd=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,Jr=/^[A-Za-z][A-Za-z0-9_]{0,127}$/,pd=/^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*$/,md=/^[A-Z][A-Z0-9_]*$/,_d=/^[a-z][a-z0-9-]{2,63}$/,gd=/^[A-Za-z][A-Za-z0-9_-]{0,127}$/,Ad=/^[A-Za-z][A-Za-z0-9_.]{0,127}$/,Ed=16,Id=2*1024,yd=new Set(["text.short","text.long","number.integer","number.decimal","boolean","date","time","datetime","option.single","option.multiple","cascade.single","cascade.multiple","user.single","user.multiple","department.single","department.multiple","resource-ref.single","resource-ref.multiple","uuid","serial-number"]),bd=new Set(["overview","database","operations","workflow","members","calendar","document","folder","settings"]),Od=new Set(["approve","reject","return","transfer","delegate","add_assignee","resubmit","withdraw","terminate","admin_reassign","admin_override","retry_resolution"]),Nd=re.configBytes,Td=re.contractBytes,Rd=re.depth,Lo=re.stringBytes,Cd="openxiangda.event-handler-manifest/v2",us="openxiangda.application-route-manifest/v3",Hr=64,fs=new Set(["id","revision","created_by","updated_by","created_at","updated_at"]),Fo=["openxiangda.data.record.created.v2","openxiangda.data.record.updated.v2","openxiangda.data.record.deleted.v2"],xo=["openxiangda.workflow.node.skipped.v2",Ct,"openxiangda.workflow.step.result_received.v2","openxiangda.workflow.step.completed.v2","openxiangda.workflow.step.continuation_failed.v2","openxiangda.workflow.instance.started.v2","openxiangda.workflow.instance.cc_added.v2","openxiangda.workflow.instance.completed.v2","openxiangda.workflow.instance.rejected.v2","openxiangda.workflow.instance.returned.v2","openxiangda.workflow.instance.resumed.v2","openxiangda.workflow.instance.withdrawn.v2","openxiangda.workflow.instance.terminated.v2","openxiangda.workflow.task.created.v2","openxiangda.workflow.task.assigned.v2","openxiangda.workflow.task.assignment_pending.v2","openxiangda.workflow.task.assignment_resolution_failed.v2","openxiangda.workflow.task.approved.v2","openxiangda.workflow.task.completed.v2","openxiangda.workflow.task.rejected.v2","openxiangda.workflow.task.returned.v2","openxiangda.workflow.task.resubmitted.v2","openxiangda.workflow.task.transferred.v2","openxiangda.workflow.task.reassigned.v2","openxiangda.workflow.task.delegated.v2","openxiangda.workflow.task.assignee_added.v2","openxiangda.workflow.task.cancelled.v2","openxiangda.workflow.participant.activated.v2","openxiangda.workflow.participant.completed.v2","openxiangda.workflow.participant.rejected.v2","openxiangda.workflow.participant.returned.v2","openxiangda.workflow.participant.transferred.v2","openxiangda.workflow.participant.reassigned.v2","openxiangda.workflow.participant.delegated.v2","openxiangda.workflow.participant.added.v2","openxiangda.workflow.participant.suspended.v2","openxiangda.workflow.participant.resumed.v2","openxiangda.workflow.participant.cancelled.v2"],hd=new Set(xo),jo=class extends Error{code;pointer;identifiers;constructor(t,o,n={}){super(t),this.name="NativeConfigurationCompilerError",this.code=t,this.pointer=o,this.identifiers=Object.fromEntries(Object.entries(n).slice(0,8).map(([i,r])=>[i,String(r).slice(0,128)]))}};function op(e){let t=S(e.appCode,"/appCode",128);ad.test(t)||m("NATIVE_CONFIG_APP_CODE_INVALID","/appCode");let o=Uo(e.expectedConfigDigest,"/expectedConfigDigest"),n=Uo(e.expectedContractDigest,"/expectedContractDigest"),i=as(e.configBytes,Nd,"/configBytes","NATIVE_CONFIG_ARTIFACT_TOO_LARGE"),r=as(e.contractBytes,Td,"/contractBytes","NATIVE_CONTRACT_ARTIFACT_TOO_LARGE");ds(i,o,"/configBytes","NATIVE_CONFIG_DIGEST_MISMATCH"),ds(r,n,"/contractBytes","NATIVE_CONTRACT_DIGEST_MISMATCH");let d=ss(i,"/configBytes","NATIVE_CONFIG_JSON_INVALID","NATIVE_CONFIG_NOT_CANONICAL"),s=ss(r,"/contractBytes","NATIVE_CONTRACT_JSON_INVALID","NATIVE_CONTRACT_NOT_CANONICAL");gn(d,"/config",ct.nodes),gn(s,"/contracts",ct.nodes),_n(d)||gn(s,"/contracts",re.extendedNodes),mn(d)||gn(s,"/contracts",re.legacyNodes);let a=d,c=s;kd(a,t),$d(c,t,o);let f=Pd(a,o,c.generatorVersion);Ic(f,c,a),X(f)!==X(c)&&m("NATIVE_CONTRACT_CLOSURE_MISMATCH",Mo(f,c,"/contracts"));let u={authz:{appCode:t,...a.authz,perspectives:a.perspectives,capabilityCatalog:f.capabilities},data:{appCode:t,resources:a.data.resources,resourceContracts:f.resources,...f.concurrency?{concurrency:f.concurrency}:{},...f.subjectReadSurfaces?{subjectReadSurfaces:f.subjectReadSurfaces}:{}},events:{appCode:t,...a.events,consumers:f.eventConsumers,producers:f.eventProducers,handlerManifest:f.eventHandlerManifest,eventTypes:f.eventTypes,capturePlans:Sd({resources:a.data.resources,dataPolicies:a.authz.dataPolicies,subscriptions:f.eventConsumers,capturePolicies:a.events.capturePolicies})},workflows:{appCode:t,...a.workflows,contracts:f.workflows},runtime:{appCode:t,requirements:a.runtime,backend:a.backend,frontend:a.frontend},contracts:f},p={authz:lt(u.authz),data:lt(u.data),events:lt(u.events),workflows:lt(u.workflows),runtime:lt(u.runtime),contracts:lt(u.contracts)},_={configDigest:o,contractDigest:n,generatorVersion:c.generatorVersion},E=wd(a),A={schemaVersion:zr,compilerContractVersion:Vt,appCode:t,source:_,projections:p,requiredPlatformCapabilities:E,aggregateDigest:Z({schemaVersion:zr,compilerContractVersion:Vt,appCode:t,source:_,requiredPlatformCapabilities:E,projectionDigests:Object.fromEntries(Object.entries(p).map(([O,b])=>[O,b.digest]))})};return Ts(A)}function Yr(e,t){let o=e.subject,n=t.find(r=>r.code===o?.resourceCode),i=new Set(Object.values(o?.factProjection||{}));return!!n?.schema?.fields?.some(r=>r.type==="subtable"&&i.has(r.code))}function wd(e){let t=e.authz.roles,o=e.data.resources,n=e.backend.operations,i=n.filter(l=>l.platformAccess?.directory?.mode==="current-initiator"&&l.platformAccess.directory.fields.includes("phone")),r=(e.data.concurrency?.commands||[]).filter(l=>l.execution?.directory?.mode==="current-initiator"&&l.execution.directory.fields.includes("phone")),d=t.some(l=>l.capabilities.some(y=>y.endsWith(":directory:read")))||o.some(l=>l.schema.fields.some(y=>["user.single","user.multiple","department.single","department.multiple"].includes(y.type)))||n.some(l=>l.platformAccess?.directory||l.platformAccess?.selectedDepartments),s=!!(e.events.subscriptions.length||e.events.timers.length||e.events.dateTriggers.length||e.events.schemas.length),a=n.some(l=>l.platformAccess?.managedFiles||l.platformAccess?.managedFileCopies)||e.events.subscriptions.some(l=>l.platformAccess?.managedFileCopies),c=e.workflows.definitions.some(l=>l.definition.rejectionNotification!==void 0)||n.some(l=>l.platformAccess?.notification)||e.events.subscriptions.some(l=>l.platformAccess?.notification),f=(l,y,R=!1)=>{let h=o.find($=>$.code===l.definition.subject?.resourceCode)?.schema.fields||[];return Object.values(l.definition.taskPages||{}).some($=>$.fields.some(w=>{if(w.readonly)return!1;let j=h.find(Q=>Q.code===w.code);if(!R&&j&&y.includes(j.type))return!0;if(!w.subtable||!j?.subtable)return!1;let L=o.find(Q=>Q.code===j.subtable.resourceCode)?.schema.fields||[];return w.subtable.fields.some(Q=>!Q.readonly&&L.some(ee=>ee.code===Q.code&&y.includes(ee.type)))}))},u=e.workflows.definitions.filter(l=>f(l,["file","image","signature","text.rich"])),p=e.workflows.definitions.filter(l=>f(l,["signature","text.rich"])),_=e.workflows.definitions.filter(l=>f(l,["file","image","signature","text.rich"],!0)),E=e.workflows.definitions.filter(l=>l.launch.mode==="standalone"||l.launch.mode==="hidden-handoff"),A=n.some(l=>l.platformAccess?.workflow)||E.length>0,O=E.filter(l=>{let y=l.launch.submission;if(!y)return!1;let R=o.find(h=>h.code===l.definition.subject.resourceCode);return[y.create,y.existing].some(h=>h&&Object.values(h.inputs).some($=>$.source==="field"&&R?.schema.fields.some(w=>w.code===$.fieldCode&&w.type.startsWith("resource-ref.")&&w.source)))}),b={resources:o},g={perspectives:e.perspectives,authz:e.authz},I={schemaVersion:e.schemaVersion,appCode:e.appCode,frontend:{routes:e.frontend.routes,user:e.frontend.user,admin:e.frontend.admin,devicePolicy:e.frontend.devicePolicy},backend:{operations:n.map(l=>({code:l.code,method:l.method,path:l.path,capability:l.capability,platformAccess:l.platformAccess||null,...l.browser?{browser:l.browser}:{},ai:l.ai||null}))}};return[...$o(e)?[{code:"application.extended-role-capacity",declaration:{roles:e.authz.roles.length,maximum:B.roles}}]:[],...vo(e)?[{code:"application.extended-configuration-bytes",declaration:{legacyConfigBytes:re.legacyConfigBytes,configBytes:re.configBytes}}]:[],...mn(e)?[{code:"application.extended-artifact-capacity",declaration:re}]:[],..._n(e)?[{code:"application.high-density-artifact-capacity",declaration:ct}]:[],...Po(e)?[{code:"application.extended-declaration-capacity",declaration:{resources:e.data.resources.length,policies:e.authz.dataPolicies.length,roles:e.authz.roles.length,capabilities:e.authz.capabilities.length,definitions:e.workflows.definitions.length,bindings:e.workflows.bindings.length,activations:e.workflows.activations.length,routes:e.frontend.routes.length,navigationItems:e.frontend.admin.navigation.reduce((l,y)=>l+y.items.length,0)}}]:[],...o.some(l=>l.uniqueKeys?.length)?[{code:"data.unique-keys",declaration:o.filter(l=>l.uniqueKeys?.length).map(l=>({code:l.code,uniqueKeys:l.uniqueKeys}))}]:[],...e.data.concurrency?[{code:"data.managed-concurrency",declaration:e.data.concurrency}]:[],...e.data.concurrency?.commands.some(l=>l.mode==="durable")?[{code:"data.managed-concurrency.durable",declaration:e.data.concurrency}]:[],...o.some(l=>l.decimalReservationLifecycle)?[{code:"data.decimal-reservation-lifecycle",declaration:o.filter(l=>l.decimalReservationLifecycle).map(l=>({code:l.code,decimalReservationLifecycle:l.decimalReservationLifecycle}))}]:[],...n.some(l=>l.platformAccess?.dataCommands)?[{code:"data.business-commands",declaration:n.filter(l=>l.platformAccess?.dataCommands)}]:[],...e.authz.dataPolicies.some(co)?[{code:"data.parent-read-policy",declaration:e.authz.dataPolicies.filter(co)}]:[],...e.authz.dataPolicies.some(l=>l.publicRead)?[{code:"data.authenticated-public-projection",declaration:e.authz.dataPolicies.filter(l=>l.publicRead)}]:[],...n.some(l=>l.platformAccess?.roleAssertions?.actorAuthority)?[{code:"data.transaction-actor-authority",declaration:n.filter(l=>l.platformAccess?.roleAssertions?.actorAuthority)}]:[],...n.some(l=>l.platformAccess?.workflowStage)?[{code:"workflow.native-stage-guard",declaration:n.filter(l=>l.platformAccess?.workflowStage)}]:[],...n.some(l=>l.platformAccess?.recordEdit)?[{code:"data.record-edit",declaration:n.filter(l=>l.platformAccess?.recordEdit)}]:[],...n.some(l=>l.platformAccess?.decimalReservation)||e.events.subscriptions.some(l=>l.platformAccess?.decimalReservation)?[{code:"data.decimal-reservations",declaration:[...n.filter(l=>l.platformAccess?.decimalReservation).map(l=>({code:l.code,decimalReservation:l.platformAccess.decimalReservation})),...e.events.subscriptions.filter(l=>l.platformAccess?.decimalReservation).map(l=>({subscriptionCode:l.code,decimalReservation:l.platformAccess.decimalReservation}))]}]:[],{code:"application-native-2",declaration:I},{code:"authz.native-batch-explain",declaration:g},{code:"authz.native-management",declaration:g},{code:"deployment.durable-runs",declaration:I.backend},{code:"deployment.platform-executor",declaration:I.backend},{code:"environment.on-demand-production",declaration:{environments:["preproduction","production"]}},{code:"environment.runtime-lifecycle",declaration:{environments:["preproduction","production"]}},...o.length?[{code:"data-api-v2",declaration:b},{code:"data.native-golden-crud",declaration:b}]:[],...o.some(l=>l.recordComments!==void 0)?[{code:"data.record-comments",declaration:b}]:[],...o.some(l=>l.recordDeletion!==void 0)?[{code:"data.workflow-record-deletion",declaration:b}]:[],...o.some(l=>l.recordPrint!==void 0)?[{code:"data.record-print",declaration:b}]:[],...o.some(l=>l.workflowHistory!==void 0)?[{code:"workflow.record-history-read",declaration:b}]:[],...o.some(pi)?[{code:"data.audit-read-access",declaration:b}]:[],...d?[{code:"directory-v2",declaration:{roles:t.map(l=>({code:l.code,capabilities:l.capabilities.filter(y=>y.endsWith(":directory:read"))})),resources:o.map(l=>({code:l.code,fields:l.schema.fields.filter(y=>["user.single","user.multiple","department.single","department.multiple"].includes(y.type))})),operations:n.filter(l=>l.platformAccess?.directory).map(l=>({code:l.code,directory:l.platformAccess.directory}))}}]:[],...n.some(l=>l.platformAccess?.selectedDepartments)?[{code:"directory.selected-departments",declaration:n.filter(l=>l.platformAccess?.selectedDepartments).map(l=>({code:l.code,selectedDepartments:l.platformAccess.selectedDepartments}))}]:[],...n.some(l=>l.platformAccess?.directory?.mode==="selected-user")?[{code:"directory.selected-user",declaration:n.filter(l=>l.platformAccess?.directory?.mode==="selected-user").map(l=>({code:l.code,directory:l.platformAccess.directory}))}]:[],...i.length||r.length?[{code:"directory.current-initiator-phone",declaration:{operations:i.map(l=>({code:l.code,directory:l.platformAccess.directory})),commands:r.map(l=>({code:l.code,directory:l.execution.directory}))}}]:[],...e.data.resources.some(l=>l.schema.fields.some(y=>y.type==="text.rich"))?[{code:"data.rich-text",declaration:{policyVersion:"rich-text-html/1"}}]:[],...a?[{code:"data.managed-files",declaration:{operations:n.filter(l=>l.platformAccess?.managedFiles||l.platformAccess?.managedFileCopies).map(l=>({code:l.code,...l.platformAccess?.managedFiles?{managedFiles:l.platformAccess.managedFiles}:{},...l.platformAccess?.managedFileCopies?{managedFileCopies:l.platformAccess.managedFileCopies}:{}})),subscriptions:e.events.subscriptions.filter(l=>l.platformAccess?.managedFileCopies).map(l=>({code:l.code,managedFileCopies:l.platformAccess.managedFileCopies}))}}]:[],...e.events.subscriptions.some(l=>l.execution)?[{code:"events.native-data-actions",declaration:e.events.subscriptions.filter(l=>l.execution)}]:[],...e.events.capturePolicies?.length?[{code:"events.capture-policy",declaration:e.events.capturePolicies}]:[],...e.events.dateTriggers.some(l=>Dr(l.resourceCode,e.events.subscriptions.filter(y=>y.eventTypes.includes(l.eventType)),e.data.resources.find(y=>y.code===l.resourceCode)).length>0)?[{code:"events.date-source-projection",declaration:{triggers:e.events.dateTriggers,subscriptions:e.events.subscriptions}}]:[],...s?[{code:"events-v2",declaration:e.events},{code:"events.durable-receipts",declaration:e.events}]:[],...Ln(e.data.resources)?[{code:"data.extended-owned-subtable-capacity",declaration:e.data.resources.filter(l=>Ln([l]))}]:[],...vn(e.data.resources,e.workflows?.definitions||[])?[{code:"data.extended-field-capacity",declaration:{resources:e.data.resources.filter(l=>l.schema.fields.length>100),workflows:(e.workflows?.definitions||[]).filter(l=>vn([],[l]))}}]:[],...Vn(e.data.resources)?[{code:"data.aggregate-owned-subtable-capacity",declaration:e.data.resources.filter(l=>Vn([l]))}]:[],...e.data.resources.some(l=>l.schema.fields.some(y=>y.userCandidates!==void 0))?[{code:"data.user-candidates",declaration:e.data.resources.filter(l=>l.schema.fields.some(y=>y.userCandidates!==void 0))}]:[],...mr(e.workflows.bindings)?[{code:"workflow.role-input-selection",declaration:e.workflows.bindings.filter(l=>Object.values(l.binding.bindings).some(y=>y.selectedInputPath!==void 0))}]:[],...fr(e.workflows.bindings)?[{code:"workflow.role-union",declaration:e.workflows.bindings.filter(l=>Object.values(l.binding.bindings).some(y=>y.roleCodes!==void 0))}]:[],...e.backend.operations.some(l=>l.platformAccess?.ownedSubject)?[{code:"workflow.named-owned-create",declaration:e.backend.operations.filter(l=>l.platformAccess?.ownedSubject)}]:[],...kn(e.data.resources)?[{code:"data.user-candidate-launch-scope",declaration:e.data.resources.filter(l=>kn([l]))}]:[],...Un(e.data.resources)?[{code:"data.subtable-minimum-rows",declaration:e.data.resources.filter(l=>Un([l]))}]:[],...Wn(e.data.resources)?[{code:"data.datetime-minute-precision",declaration:e.data.resources.filter(l=>Wn([l]))}]:[],...e.workflows.activations.length?[{code:"workflow-kernel-v2",declaration:e.workflows},{code:"workflow.fresh-command-token",declaration:e.workflows}]:[],...e.workflows.definitions.some(l=>l.definition.instanceCommands!==void 0)?[{code:"workflow.instance-cancellation-policy",declaration:e.workflows.definitions.filter(l=>l.definition.instanceCommands!==void 0)}]:[],...e.workflows.definitions.some(l=>l.definition.instanceCommands?.withdraw?.reasonRequired===!1)?[{code:"workflow.optional-withdrawal-reason",declaration:e.workflows.definitions.filter(l=>l.definition.instanceCommands?.withdraw?.reasonRequired===!1)}]:[],...e.workflows.definitions.some(l=>l.definition.rejectionNotification!==void 0)?[{code:"workflow.rejection-notification",declaration:e.workflows.definitions.filter(l=>l.definition.rejectionNotification!==void 0)}]:[],...e.workflows.definitions.some(l=>l.definition.commandHandlers!==void 0)||n.some(l=>l.platformAccess?.workflow?.businessCommands)?[{code:"workflow.business-data-command",declaration:{definitions:e.workflows.definitions.filter(l=>l.definition.commandHandlers!==void 0),operations:n.filter(l=>l.platformAccess?.workflow?.businessCommands)}}]:[],...e.workflows.definitions.some(l=>l.definition.commandHandlers?.approve?.transitionPolicy==="workflow")?[{code:"workflow.approval-business-command",declaration:e.workflows.definitions.filter(l=>l.definition.commandHandlers?.approve?.transitionPolicy==="workflow")}]:[],...e.workflows.definitions.some(l=>l.definition.commandHandlers?.resubmit)||n.some(l=>l.platformAccess?.workflow?.businessCommands?.includes("resubmit"))?[{code:"workflow.correction-business-command",declaration:{definitions:e.workflows.definitions.filter(l=>l.definition.commandHandlers?.resubmit),operations:n.filter(l=>l.platformAccess?.workflow?.businessCommands?.includes("resubmit"))}}]:[],...e.workflows.definitions.some(l=>l.definition.launchPreflight!==void 0)?[{code:"workflow.launch-preflight",declaration:e.workflows.definitions.filter(l=>l.definition.launchPreflight!==void 0)}]:[],...e.workflows.definitions.some(l=>l.definition.commandHandlers?.resubmit?.derivedSubjectFields!==void 0)?[{code:"workflow.correction-derived-subject-facts",declaration:e.workflows.definitions.filter(l=>l.definition.commandHandlers?.resubmit?.derivedSubjectFields!==void 0)}]:[],...e.workflows.definitions.some(l=>l.definition.approvedDelegation!==void 0)?[{code:"workflow.approved-delegation",declaration:e.workflows.definitions.filter(l=>l.definition.approvedDelegation!==void 0)}]:[],...e.workflows.definitions.some(l=>Yr(l.definition,e.data.resources))?[{code:"workflow.owned-initial-facts",declaration:e.workflows.definitions.filter(l=>Yr(l.definition,e.data.resources))}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.nodes).some(y=>y.kind==="correction"))?[{code:"workflow.initiator-correction",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.nodes).some(y=>y.kind==="correction"))}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.nodes).some(y=>y.operationPolicy?.reject?.commentRequired===!1))?[{code:"workflow.optional-rejection-comment",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.nodes).some(y=>y.operationPolicy?.reject?.commentRequired===!1))}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.nodes).some(y=>Object.values(y.operationPolicy||{}).some(R=>R.reasonRequired===!1)))?[{code:"workflow.optional-operation-reason",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.nodes).some(y=>Object.values(y.operationPolicy||{}).some(R=>R.reasonRequired===!1)))}]:[],...O.length?[{code:"workflow.named-input-sources",declaration:O}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.nodes).some(y=>y.administration!==void 0||y.operationPolicy!==void 0))?[{code:"workflow.node-administration",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.nodes).some(y=>y.administration!==void 0||y.operationPolicy!==void 0))}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.nodes).some(y=>y.kind==="approval"&&y.emptyPolicy!==void 0))?[{code:"workflow.approval-empty-policy",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.nodes).some(y=>y.kind==="approval"&&y.emptyPolicy!==void 0))}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.nodes).some(y=>y.completionDeadline!==void 0))?[{code:"workflow.completion-deadline",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.nodes).some(y=>y.completionDeadline!==void 0))}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.nodes).some(y=>y.initiatorApprovalPolicy!==void 0))?[{code:"workflow.initiator-approval-policy",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.nodes).some(y=>y.initiatorApprovalPolicy!==void 0))}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.nodes).some(y=>y.kind==="cc"))?[{code:"workflow.automatic-cc",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.nodes).some(y=>y.kind==="cc"))}]:[],...e.workflows.definitions.some(l=>l.definition.taskPages!==void 0)?["workflow.task-page-submit","workflow.task-private-drafts"].map(l=>({code:l,declaration:e.workflows.definitions.filter(y=>y.definition.taskPages!==void 0)})):[],...u.length?[{code:"workflow.task-managed-files",declaration:u}]:[],..._.length?[{code:"workflow.task-owned-files",declaration:_}]:[],...p.length?[{code:"workflow.task-rich-fields",declaration:p}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.taskPages||{}).some(y=>y.fields.some(R=>R.subtable)))?[{code:"workflow.task-owned-subtables",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.taskPages||{}).some(y=>y.fields.some(R=>R.subtable)))}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.nodes).some(y=>y.kind==="action"))?[{code:"workflow.durable-business-step",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.nodes).some(y=>y.kind==="action"))}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.nodes).some(y=>y.kind==="action"&&y.handler.dataTransaction))?[{code:"workflow.step-data-transaction",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.nodes).some(y=>y.kind==="action"&&y.handler.dataTransaction))}]:[],...e.workflows.bindings.some(l=>Object.values(l.binding.bindings).some(y=>y.routing!==void 0))?[{code:"workflow.assignment-routing",declaration:e.workflows.bindings.filter(l=>Object.values(l.binding.bindings).some(y=>y.routing!==void 0))}]:[],...A?[{code:"business-process.durable-command",declaration:{operations:n.filter(l=>l.platformAccess?.workflow).map(l=>({code:l.code,workflow:l.platformAccess.workflow})),definitions:E,activations:e.workflows.activations.filter(l=>E.some(y=>y.definition.code===l.workflowCode))}}]:[],...c?[{code:"notification-hub-v2",declaration:{...e.workflows.definitions.some(l=>l.definition.rejectionNotification!==void 0)?{rejectionNotifications:e.workflows.definitions.filter(l=>l.definition.rejectionNotification!==void 0)}:{},operations:n.filter(l=>l.platformAccess?.notification).map(l=>({code:l.code,notification:l.platformAccess.notification})),subscriptions:e.events.subscriptions.filter(l=>l.platformAccess?.notification).map(l=>({code:l.code,notification:l.platformAccess.notification}))}}]:[],...e.frontend.authentication?[{code:"authentication.application-login-surface",declaration:e.frontend.authentication}]:[],...e.frontend.publicAccess?[{code:"public-access.anonymous-owner-records",declaration:e.frontend.publicAccess}]:[]].map(({code:l,declaration:y})=>({code:l,contractVersion:l==="data.unique-keys"?o.some(R=>Hi(R.schema.fields,R.uniqueKeys)==="1.1.0")?"1.1.0":"1.0.0":Kr[l],usageDigest:`sha256:${Z(y)}`})).sort((l,y)=>l.code===y.code?0:l.code<y.code?-1:1)}function Sd(e){let t=new Map,o=new Set(e.resources.map(r=>String(r.code)));for(let[r,d]of D(e.capturePolicies===void 0?[]:e.capturePolicies,"/capturePlan/capturePolicies",100).entries()){let s=`/capturePlan/capturePolicies/${r}`,a=N(d,s);C(a,["resourceCode","mode"],s);let c=H(a.resourceCode,`${s}/resourceCode`);o.has(c)||m("NATIVE_EVENT_CAPTURE_RESOURCE_NOT_FOUND",s,{resourceCode:c}),t.has(c)&&m("NATIVE_EVENT_CAPTURE_POLICY_DUPLICATE",s,{resourceCode:c}),a.mode!=="all"&&a.mode!=="subscribed"&&m("NATIVE_EVENT_CAPTURE_MODE_INVALID",`${s}/mode`),t.set(c,a.mode)}let n=new Map(e.dataPolicies.map((r,d)=>{let s=N(r,`/capturePlan/dataPolicies/${d}`);return[String(s.code),s]})),i=e.subscriptions.map((r,d)=>N(r,`/capturePlan/subscriptions/${d}`));return e.resources.map((r,d)=>{let s=`/capturePlan/resources/${d}`,a=N(r,s),c=H(a.code,`${s}/code`),f=a.schema?N(a.schema,`${s}/schema`):a,u=new Set(D(f.fields||[],`${s}/schema/fields`,500).map((y,R)=>G(N(y,`${s}/schema/fields/${R}`).code,`${s}/schema/fields/${R}/code`))),p=a.dataPolicyCode?v(a.dataPolicyCode,`${s}/dataPolicyCode`):null,_=p?n.get(p):void 0;p&&!_&&m("NATIVE_EVENT_CAPTURE_AUTHZ_POLICY_NOT_FOUND",s,{resourceCode:c,dataPolicyCode:p});let E=new Set;for(let y of _?.rules||[])E.add(y.parentRead?Xt(e.resources,c,y.parentRead,`${s}/parentRead`).foreignKey:String(y.field));if(_?.readExpression)for(let y of st(_.readExpression,`${s}/readExpression`))E.add(y.rule.parentRead?Xt(e.resources,c,y.rule.parentRead,`${s}/parentRead`).foreignKey:String(y.rule.field));let A=new Set,O=new Set,b=new Set;for(let[y,R]of i.entries()){let h=D(R.eventTypes,`/capturePlan/subscriptions/${y}/eventTypes`,20).map(String);if(!h.some(L=>L.startsWith("openxiangda.data.")))continue;let $=N(R.filter||{},`/capturePlan/subscriptions/${y}/filter`),w=Array.isArray($.resourceCodes)?$.resourceCodes.map(String):[];if(w.length&&!w.includes(c))continue;for(let L of h)Fo.includes(L)&&b.add(L);for(let L of Dd($,`/capturePlan/subscriptions/${y}/filter`))A.add(L);let j=N(R.payload||{},`/capturePlan/subscriptions/${y}/payload`);for(let L of D(j.fields||[],`/capturePlan/subscriptions/${y}/payload/fields`,32))O.add(G(L,`/capturePlan/subscriptions/${y}/payload/fields`))}let g=new Set([...A,...O]),I=new Set([...g,...E]);I.size>Hr&&m("NATIVE_EVENT_CAPTURE_FIELDS_LIMIT",s,{resourceCode:c,maximum:Hr});for(let y of I)!u.has(y)&&!(E.has(y)&&fs.has(y))&&m("NATIVE_EVENT_CAPTURE_FIELD_NOT_FOUND",s,{resourceCode:c,field:y});let T=N(a.fieldPolicies||{},`${s}/fieldPolicies`);for(let y of g)T[y]?.mask==="omit"&&m("NATIVE_EVENT_CAPTURE_FIELD_SENSITIVE",s,{resourceCode:c,field:y});let l={resourceCode:c,...t.get(c)==="subscribed"?{capturedEventTypes:[...b].sort()}:{},filterFields:[...A].sort(),projectionFields:[...O].sort(),authorizationFields:[...E].sort(),captureFields:[...I].sort()};return{...l,digest:Z(l)}}).sort((r,d)=>r.resourceCode.localeCompare(d.resourceCode))}function Dd(e,t){let o=new Set;for(let[d,s]of D(e.changes||[],`${t}/changes`,16).entries()){let a=N(s,`${t}/changes/${d}`);o.add(G(a.field,`${t}/changes/${d}/field`))}let n=N(e.changedFields||{},`${t}/changedFields`);for(let d of["anyOf","allOf","noneOf"])for(let[s,a]of D(n[d]||[],`${t}/changedFields/${d}`,32).entries())o.add(G(a,`${t}/changedFields/${d}/${s}`));let i=0,r=(d,s,a)=>{a>3&&m("NATIVE_EVENT_FILTER_DEPTH_LIMIT",s);let c=N(d,s);if(c.change){let u=N(c.change,`${s}/change`);o.add(G(u.field,`${s}/change/field`)),i+=1;return}if(c.not){r(c.not,`${s}/not`,a+1);return}let f=c.all?"all":c.any?"any":null;f||m("NATIVE_EVENT_FILTER_CONDITION_INVALID",s);for(let[u,p]of D(c[f],`${s}/${f}`,16).entries())r(p,`${s}/${f}/${u}`,a+1)};return e.where&&r(e.where,`${t}/where`,1),i+=Array.isArray(e.changes)?e.changes.length:0,i>16&&m("NATIVE_EVENT_FILTER_ATOM_LIMIT",t),[...o].sort()}function kd(e,t){C(e,["schemaVersion","compilerContractVersion","appCode","perspectives","authz","backend","data","events","workflows","frontend","runtime"],"/config"),F(e.schemaVersion,rd,"/config/schemaVersion"),F(e.compilerContractVersion,Vt,"/config/compilerContractVersion"),F(e.appCode,t,"/config/appCode"),D(e.perspectives,"/config/perspectives",100);let o=N(e.authz,"/config/authz");C(o,["capabilities","roles","scopeDimensions","scopeSources","roleMembershipSources","relationshipGrantSources","dataPolicies","authorizationTransitions"],"/config/authz",["authenticatedUserRoleCode"]),D(o.capabilities,"/config/authz/capabilities",B.capabilities),D(o.roles,"/config/authz/roles",B.roles),D(o.scopeDimensions,"/config/authz/scopeDimensions",100),D(o.scopeSources,"/config/authz/scopeSources",100),D(o.roleMembershipSources,"/config/authz/roleMembershipSources",100),D(o.relationshipGrantSources,"/config/authz/relationshipGrantSources",100),D(o.dataPolicies,"/config/authz/dataPolicies",B.dataPolicies),D(o.authorizationTransitions,"/config/authz/authorizationTransitions",100);let n=N(e.backend,"/config/backend");C(n,["secrets","operations"],"/config/backend"),D(n.secrets,"/config/backend/secrets",100),D(n.operations,"/config/backend/operations",500),pc(n.secrets);let i=N(e.data,"/config/data");C(i,["resources"],"/config/data",["resourceDetailRoutes","subjectReadSurfaces","concurrency"]),D(i.resources,"/config/data/resources",B.resources),i.subjectReadSurfaces!==void 0&&D(i.subjectReadSurfaces,"/config/data/subjectReadSurfaces",B.subjectReadSurfaces),i.resourceDetailRoutes!==void 0&&D(i.resourceDetailRoutes,"/config/data/resourceDetailRoutes",100);let r=N(e.events,"/config/events");C(r,["schemas","subscriptions","timers","dateTriggers"],"/config/events",["capturePolicies"]),D(r.schemas,"/config/events/schemas",100),D(r.subscriptions,"/config/events/subscriptions",100),D(r.timers,"/config/events/timers",100),D(r.dateTriggers,"/config/events/dateTriggers",100);let d=N(e.workflows,"/config/workflows");C(d,["definitions","bindings","activations","providers","editableParameters"],"/config/workflows"),D(d.definitions,"/config/workflows/definitions",B.workflows),D(d.bindings,"/config/workflows/bindings",B.workflows),D(d.activations,"/config/workflows/activations",B.workflows),D(d.providers,"/config/workflows/providers",100),D(d.editableParameters,"/config/workflows/editableParameters",100);let s=N(e.frontend,"/config/frontend");C(s,["routes","user","admin","devicePolicy"],"/config/frontend",["authentication","publicAccess"]),D(s.routes,"/config/frontend/routes",B.routes);let a=N(s.user,"/config/frontend/user");C(a,["applicationTodoCenter"],"/config/frontend/user"),ft(a.applicationTodoCenter,"/config/frontend/user/applicationTodoCenter"),Bo(s.devicePolicy,"/config/frontend/devicePolicy"),Object.prototype.hasOwnProperty.call(s,"authentication")&&ms(s.authentication,s.routes,e,"/config/frontend/authentication"),Object.prototype.hasOwnProperty.call(s,"publicAccess")&&Jd(s.publicAccess,e,"/config/frontend/publicAccess");let c=N(s.admin,"/config/frontend/admin");C(c,["navigation"],"/config/frontend/admin",["access"]),c.access!==void 0&&On(c.access,"/config/frontend/admin/access",e.appCode),Zd(c.navigation,"/config/frontend/admin/navigation");let f=N(e.runtime,"/config/runtime");C(f,["protocolCapabilities","health"],"/config/runtime"),V(f.protocolCapabilities,"/config/runtime/protocolCapabilities",100),C(N(f.health,"/config/runtime/health"),["livePath","readyPath","versionPath"],"/config/runtime/health"),F(f.health.livePath,"/__platform/health","/config/runtime/health/livePath"),F(f.health.readyPath,"/__platform/ready","/config/runtime/health/readyPath"),F(f.health.versionPath,"/__platform/version","/config/runtime/health/versionPath")}function $d(e,t,o){C(e,["schemaVersion","compilerContractVersion","generatorVersion","appCode","configDigest","perspectives","resources","capabilities","operations","eventConsumers","eventProducers","eventSchemas","eventHandlerManifest","eventTypes","workflows","routes","routeManifest","adminPages","adminNavigation"],"/contracts",["authentication","publicAccess","adminAccess","subjectReadSurfaces","concurrency"]),F(e.schemaVersion,ls,"/contracts/schemaVersion"),F(e.compilerContractVersion,Vt,"/contracts/compilerContractVersion"),S(e.generatorVersion,"/contracts/generatorVersion",128),F(e.appCode,t,"/contracts/appCode"),F(e.configDigest,o,"/contracts/configDigest"),D(e.perspectives,"/contracts/perspectives",B.perspectives),D(e.resources,"/contracts/resources",B.resources),e.subjectReadSurfaces!==void 0&&D(e.subjectReadSurfaces,"/contracts/subjectReadSurfaces",B.subjectReadSurfaces),D(e.capabilities,"/contracts/capabilities",B.capabilities),D(e.operations,"/contracts/operations",B.operations),D(e.eventConsumers,"/contracts/eventConsumers",B.eventConsumers),D(e.eventProducers,"/contracts/eventProducers",B.eventProducers),D(e.eventSchemas,"/contracts/eventSchemas",B.eventSchemas),N(e.eventHandlerManifest,"/contracts/eventHandlerManifest"),V(e.eventTypes,"/contracts/eventTypes",B.eventTypes),D(e.workflows,"/contracts/workflows",B.workflows),D(e.routes,"/contracts/routes",B.routes),Object.prototype.hasOwnProperty.call(e,"authentication")&&Gd(e.authentication,"/contracts/authentication"),Object.prototype.hasOwnProperty.call(e,"publicAccess")&&Hd(e.publicAccess,"/contracts/publicAccess"),Object.prototype.hasOwnProperty.call(e,"adminAccess")&&On(e.adminAccess,"/contracts/adminAccess",t),ic(e.routeManifest,"/contracts/routeManifest",t),tc(e.adminPages,"/contracts/adminPages"),nc(e.adminNavigation,"/contracts/adminNavigation")}function Pd(e,t,o){let n=Ld(e);cc(e,n),uc(e),lc(e),mc(e);let i=e.events.schemas.map((g,I)=>{let T=`/config/events/schemas/${I}`,l=N(g,T),y=S(l.eventType,`${T}/eventType`,255);return y.startsWith("openxiangda.")&&m("NATIVE_EVENT_SCHEMA_RESERVED",`${T}/eventType`,{eventType:y}),F(l.schemaDigest,Z(N(l.jsonSchema,`${T}/jsonSchema`)),`${T}/schemaDigest`),l}),r=new Set([...Fo,...xo,...i.map(g=>String(g.eventType))]),d=new Map(e.data.resources.map(g=>[String(g.code),new Map(g.schema.fields.map(I=>[String(I.code),String(I.type)]))])),s=te(e.events.subscriptions.map((g,I)=>{let T=`/config/events/subscriptions/${I}`,l=N(g,T),y=V(l.eventTypes,`${T}/eventTypes`,20);y.forEach((w,j)=>{r.has(w)||m("NATIVE_EVENT_TYPE_NOT_REGISTERED",`${T}/eventTypes/${j}`,{eventType:w})});let R=Qi(l,e.data.resources,T),h=Vd(l.delivery,y,`${T}/delivery`),$=vd(l.platformAccess,`${T}/platformAccess`,d,e,l);return{code:v(l.code,`${T}/code`),endpointPath:Oe(l.endpointPath,`${T}/endpointPath`),eventTypes:y,filter:N(l.filter,`${T}/filter`),payload:R?.payload||N(l.payload,`${T}/payload`),...R?{execution:R.execution}:{},...$?{platformAccess:$}:{},delivery:h}}),g=>g.code),a=new Map(i.map(g=>[String(g.eventType),String(g.dataSchemaVersion)])),c=te([...e.data.resources.flatMap(g=>Fo.map(I=>({code:`data:${g.code}:${I}`,source:"data",eventType:I,dataSchemaVersion:"2.0.0",resourceCode:g.code}))),...i.map(g=>({code:`app:${g.eventType}`,source:"app",eventType:g.eventType,dataSchemaVersion:g.dataSchemaVersion})),...e.events.timers.map(g=>({code:g.code,source:"timer",eventType:g.eventType,dataSchemaVersion:a.get(String(g.eventType))||"2.0.0"})),...e.events.dateTriggers.map(g=>({code:g.code,source:"date",eventType:g.eventType,dataSchemaVersion:a.get(String(g.eventType))||"2.0.0",resourceCode:g.resourceCode,field:g.field})),...e.workflows.activations.length?xo.filter(g=>!ir.includes(g)||e.workflows.definitions.some(I=>Object.values(I.definition.nodes).some(T=>T.kind==="action"))).filter(g=>g!=="openxiangda.workflow.node.skipped.v2"||e.workflows.definitions.some(I=>Object.values(I.definition.nodes).some(T=>T.kind==="approval"&&T.emptyPolicy==="skip"))).map(g=>({code:`workflow:${g}`,source:"workflow",eventType:g,dataSchemaVersion:"2.0.0"})):[]],g=>`${g.source}:${g.code}:${g.eventType}`),f=M([...s.flatMap(g=>g.eventTypes),...c.map(g=>String(g.eventType))]);ec(e);let u=As(e),p;try{p=Ri(e.data.concurrency,e.data.resources,n)}catch(g){throw g instanceof Et&&m(g.code,g.pointer,{reason:g.reason}),g}p?.commands.some(g=>g.mode==="durable")&&e.backend?.enabled===!1&&m("NATIVE_MANAGED_CONCURRENCY_INVALID","/data/concurrency",{reason:"durable commands require backend runtime"});let _=xd(e,n),E=ps(e),A=e.workflows.definitions.map(g=>g.definition),O=Ao(A),b=dr(A,s,!0);b.length&&m(b[0],"/config/events/subscriptions");try{hi(e.data.resources,E)}catch(g){throw g instanceof rt&&m(g.code,g.pointer,{reason:g.reason}),g}return{schemaVersion:ls,compilerContractVersion:Vt,generatorVersion:o,appCode:e.appCode,configDigest:t,perspectives:e.perspectives,resources:Fd(e),..._.length?{subjectReadSurfaces:_}:{},...p?{concurrency:p}:{},capabilities:te(n,g=>g.code),operations:E,eventConsumers:s,eventProducers:c,eventSchemas:i,eventHandlerManifest:{schemaVersion:Cd,appCode:e.appCode,handlers:s.filter(g=>!g.execution).map(g=>({code:g.code,endpointPath:g.endpointPath,eventTypes:g.eventTypes,dataSchemaVersions:M(g.eventTypes.map(I=>I.startsWith("openxiangda.")?"2.0.0":a.get(I)||"2.0.0")),maxBodyBytes:65536,receiptProtocolVersion:2,...O[g.code]?{workflowStep:O[g.code]}:{}}))},eventTypes:f,workflows:ys(e),routes:bn(e),...Object.prototype.hasOwnProperty.call(e.frontend,"authentication")?{authentication:qd(e)}:{},...Object.prototype.hasOwnProperty.call(e.frontend,"publicAccess")?{publicAccess:Yd(e)}:{},...e.frontend.admin.access?{adminAccess:e.frontend.admin.access}:{},routeManifest:ac(e),adminPages:u,adminNavigation:Xd(e)}}function vd(e,t,o,n,i){if(e===void 0)return;let r=N(e,t);C(r,["notification","managedFileCopies","decimalReservation"],t,!0);let d={};if(r.decimalReservation!==void 0)try{d.decimalReservation=Xi(r.decimalReservation,Zi(n,i))}catch{m("NATIVE_EVENT_DECIMAL_RESERVATION_INVALID",`${t}/decimalReservation`)}if(r.notification!==void 0){let s=N(r.notification,`${t}/notification`);C(s,["mode"],`${t}/notification`),F(s.mode,"business-standard",`${t}/notification/mode`),d.notification={mode:"business-standard"}}if(r.managedFileCopies!==void 0){let s=D(r.managedFileCopies,`${t}/managedFileCopies`,16);s.length||m("NATIVE_EVENT_MANAGED_FILE_COPIES_REQUIRED",`${t}/managedFileCopies`);let a=new Set;d.managedFileCopies=te(s.map((c,f)=>{let u=`${t}/managedFileCopies/${f}`,p=N(c,u);C(p,["mode","sourceResourceCode","sourceFieldCodes","targetResourceCode","targetFieldCodes"],u),F(p.mode,"copy",`${u}/mode`);let _=H(p.sourceResourceCode,`${u}/sourceResourceCode`),E=H(p.targetResourceCode,`${u}/targetResourceCode`),A=o.get(_),O=o.get(E);(!A||!O)&&m("NATIVE_EVENT_MANAGED_FILE_COPY_RESOURCE_INVALID",u);let b=V(p.sourceFieldCodes,`${u}/sourceFieldCodes`,16),g=V(p.targetFieldCodes,`${u}/targetFieldCodes`,16);(!b.length||b.length!==g.length)&&m("NATIVE_EVENT_MANAGED_FILE_COPY_FIELDS_INVALID",u),b.forEach((T,l)=>{let y=A.get(T),R=O.get(g[l]);(!["file","image","text.rich"].includes(String(y))||y!==R)&&m("NATIVE_EVENT_MANAGED_FILE_COPY_FIELD_INVALID",`${u}/sourceFieldCodes/${l}`)});let I=`${_}:${b.join(",")}=>${E}:${g.join(",")}`;return a.has(I)&&m("NATIVE_EVENT_MANAGED_FILE_COPY_DUPLICATE",u),a.add(I),{mode:"copy",sourceResourceCode:_,sourceFieldCodes:M(b),targetResourceCode:E,targetFieldCodes:M(g)}}),c=>`${c.sourceResourceCode}:${c.sourceFieldCodes.join(",")}=>${c.targetResourceCode}:${c.targetFieldCodes.join(",")}`)}return Object.keys(d).length||m("NATIVE_EVENT_PLATFORM_ACCESS_EMPTY",t),d}function Vd(e,t,o){let n=N(e,o);C(n,["timeoutMs","maxAttempts","initialBackoffMs","maxBackoffMs","ordering","concurrency"],o),se(n.timeoutMs,`${o}/timeoutMs`,1e3,3e4),se(n.maxAttempts,`${o}/maxAttempts`,1,12);let i=se(n.initialBackoffMs,`${o}/initialBackoffMs`,1e3,3e5);se(n.maxBackoffMs,`${o}/maxBackoffMs`,i,18e5),se(n.concurrency,`${o}/concurrency`,1,50);let r=S(n.ordering,`${o}/ordering`,32);return["none","record","workflow-instance"].includes(r)||m("NATIVE_EVENT_DELIVERY_ORDERING_INVALID",`${o}/ordering`),r==="workflow-instance"&&t.some(d=>!hd.has(d))&&m("NATIVE_EVENT_WORKFLOW_ORDERING_REQUIRES_WORKFLOW_FACTS",`${o}/ordering`),n}function Ld(e){let t=new Map;for(let r of Ns(e.appCode))t.set(r.code,r);for(let[r,d]of e.authz.capabilities.entries()){let s=`/config/authz/capabilities/${r}`,a=N(d,s);C(a,["code","kind","name","description"],s,!0);let c=me(a.code,`${s}/code`,e.appCode);t.has(c)&&m("NATIVE_CAPABILITY_DUPLICATE",`${s}/code`),["backend","ui"].includes(a.kind)||m("NATIVE_CAPABILITY_KIND_INVALID",`${s}/kind`);let f={code:c,kind:a.kind,name:S(a.name,`${s}/name`,255),source:"explicit",...a.description===void 0?{}:{description:Go(a.description,`${s}/description`,2e3)}};t.set(c,f)}let o=e.data.resources.map((r,d)=>({pointer:`/config/data/resources/${d}`,resource:Ye(r,`/config/data/resources/${d}`,e.appCode)}));for(let{pointer:r,resource:d}of o){let s={read:`\u8BFB\u53D6${d.name}`,create:`\u65B0\u5EFA${d.name}`,update:`\u66F4\u65B0${d.name}`,delete:`\u5220\u9664${d.name}`};for(let a of["read","create","update","delete"]){let c=me(d.capabilities[a],`${r}/capabilities/${a}`,e.appCode);t.has(c)&&m("NATIVE_CAPABILITY_DUPLICATE",`${r}/capabilities/${a}`),t.set(c,{code:c,kind:"data",name:s[a],source:"data"})}}let n=new Set(t.keys()),i=new Map;for(let{pointer:r,resource:d}of o)for(let[s,a]of Object.entries(d.fieldPolicies)){if(_t(s))continue;let c=N(a,`${r}/fieldPolicies/${s}`);for(let f of["read","create","update"])if(Array.isArray(c[f]))for(let u of V(c[f],`${r}/fieldPolicies/${s}/${f}`,2e3)){if(me(u,`${r}/fieldPolicies/${s}/${f}`,e.appCode),n.has(u))continue;let p=i.get(u);p&&p!==d.code&&m("NATIVE_CAPABILITY_DUPLICATE",`${r}/fieldPolicies/${s}/${f}`),i.set(u,d.code),!t.has(u)&&t.set(u,{code:u,kind:"data",name:`${d.name}.${s}.${f}`,source:"data"})}}return[...t.values()]}function Fd(e){let t=jd(e);return te(e.data.resources.map((o,n)=>{let i=Ye(o,`/config/data/resources/${n}`,e.appCode),r=t.get(i.code);return{code:i.code,schemaDigest:Z(i.schema),fields:te(i.schema.fields.map(d=>({code:d.code,type:d.type})),d=>d.code),...r?{detailRouteCode:r}:{}}}),o=>o.code)}function xd(e,t){if(e.data.subjectReadSurfaces===void 0)return[];let o=D(e.data.subjectReadSurfaces,"/config/data/subjectReadSurfaces",B.subjectReadSurfaces),n=new Set(t.map(d=>String(d.code))),i=new Map(e.data.resources.map((d,s)=>{let a=`/config/data/resources/${s}`,c=Ye(d,a,e.appCode);return[String(c.code),{resource:c,fields:new Map(D(N(c.schema,`${a}/schema`).fields,`${a}/schema/fields`,500).map(f=>{let u=N(f,`${a}/schema/fields`);return[String(u.code),u]}))}]})),r=new Set;return te(o.map((d,s)=>{let a=`/config/data/subjectReadSurfaces/${s}`,c=N(d,a);C(c,["code","name","capability","subject","relations"],a);let f=v(c.code,`${a}/code`);r.has(f)&&m("NATIVE_SUBJECT_READ_SURFACE_CODE_DUPLICATE",`${a}/code`),r.add(f);let u=me(c.capability,`${a}/capability`,e.appCode);n.has(u)||m("NATIVE_SUBJECT_READ_SURFACE_CAPABILITY_NOT_DECLARED",`${a}/capability`);let p=N(c.subject,`${a}/subject`);C(p,["resourceCode","fields"],`${a}/subject`);let _=H(p.resourceCode,`${a}/subject/resourceCode`),E=i.get(_);E||m("NATIVE_SUBJECT_READ_SURFACE_RESOURCE_NOT_DECLARED",`${a}/subject/resourceCode`);let A=V(p.fields,`${a}/subject/fields`,100).map((T,l)=>G(T,`${a}/subject/fields/${l}`));A.length||m("NATIVE_SUBJECT_READ_SURFACE_FIELDS_REQUIRED",`${a}/subject/fields`);for(let[T,l]of A.entries()){let y=E.fields.get(l);(!y||y.type==="subtable")&&m("NATIVE_SUBJECT_READ_SURFACE_FIELD_INVALID",`${a}/subject/fields/${T}`)}let O=D(c.relations,`${a}/relations`,8);O.length||m("NATIVE_SUBJECT_READ_SURFACE_RELATIONS_REQUIRED",`${a}/relations`);let b=new Set,g=0,I=te(O.map((T,l)=>{let y=`${a}/relations/${l}`,R=N(T,y);C(R,["code","resourceCode","foreignKeyField","fields","limit"],y,["order"]);let h=v(R.code,`${y}/code`);b.has(h)&&m("NATIVE_SUBJECT_READ_SURFACE_RELATION_CODE_DUPLICATE",`${y}/code`),b.add(h);let $=H(R.resourceCode,`${y}/resourceCode`),w=i.get($);w||m("NATIVE_SUBJECT_READ_SURFACE_RESOURCE_NOT_DECLARED",`${y}/resourceCode`);let j=G(R.foreignKeyField,`${y}/foreignKeyField`),L=w.fields.get(j),Q=N(L?.source||{},`${y}/foreignKeyField/source`);(!L||!["uuid","resource-ref.single"].includes(String(L.type))||L.type==="resource-ref.single"&&(Q.kind!=="resource"||Q.resourceCode!==_))&&m("NATIVE_SUBJECT_READ_SURFACE_RELATION_INVALID",`${y}/foreignKeyField`);let ee=V(R.fields,`${y}/fields`,100).map((oe,P)=>G(oe,`${y}/fields/${P}`));ee.length||m("NATIVE_SUBJECT_READ_SURFACE_FIELDS_REQUIRED",`${y}/fields`);for(let[oe,P]of ee.entries()){let U=w.fields.get(P);(!U||U.type==="subtable")&&m("NATIVE_SUBJECT_READ_SURFACE_FIELD_INVALID",`${y}/fields/${oe}`)}let Y=D(R.order||[],`${y}/order`,10).map((oe,P)=>{let U=`${y}/order/${P}`,x=N(oe,U);C(x,["field","direction"],U);let q=G(x.field,`${U}/field`),z=w.fields.get(q);return(!fs.has(q)&&!z||z?.type==="subtable"||z&&!At(z.type))&&m("NATIVE_SUBJECT_READ_SURFACE_ORDER_FIELD_INVALID",`${U}/field`),["asc","desc"].includes(String(x.direction))||m("NATIVE_SUBJECT_READ_SURFACE_ORDER_DIRECTION_INVALID",`${U}/direction`),{field:q,direction:x.direction}}),ge=se(R.limit,`${y}/limit`,1,100);return g+=ge,{code:h,resourceCode:$,foreignKeyField:j,fields:M(ee),...Y.length?{order:Y}:{},limit:ge}}),T=>T.code);return g>400&&m("NATIVE_SUBJECT_READ_SURFACE_ROW_LIMIT_EXCEEDED",`${a}/relations`),{code:f,name:S(c.name,`${a}/name`,255),capability:u,subject:{resourceCode:_,fields:M(A)},relations:I}}),d=>d.code)}function jd(e){let t=e.data.resourceDetailRoutes===void 0?[]:D(e.data.resourceDetailRoutes,"/config/data/resourceDetailRoutes",100),o=new Map(e.data.resources.map((r,d)=>{let s=`/config/data/resources/${d}`,a=Ye(r,s,e.appCode);return[a.code,a]})),n=new Map(bn(e).map(r=>[String(r.code),r])),i=new Map;for(let[r,d]of t.entries()){let s=`/config/data/resourceDetailRoutes/${r}`,a=N(d,s);C(a,["resourceCode","desktop","mobile"],s);let c=H(a.resourceCode,`${s}/resourceCode`);i.has(c)&&m("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_DUPLICATE",`${s}/resourceCode`);let f=o.get(c);f||m("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_RESOURCE_MISSING",`${s}/resourceCode`);let u=v(a.desktop,`${s}/desktop`),p=v(a.mobile,`${s}/mobile`);u===p&&m("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_INVALID",s);let _=String(f.capabilities.read);for(let[E,A]of[["desktop",u],["mobile",p]]){let O=`${s}/${E}`,b=n.get(A);b||m("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_REFERENCE_MISSING",O),b.surface!=="user"&&m("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_SURFACE_INVALID",O);let g=Oe(b.path,`${O}/path`),I=[...g.matchAll(/:([A-Za-z][A-Za-z0-9_]*)/g)],T=E==="mobile"?!g.startsWith("/m/"):g==="/m"||g.startsWith("/m/");(g.includes("*")||g.includes("?")||g.includes("#")||g.split("/").includes("..")||I.length!==1||T)&&m("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_PATH_INVALID",O);let l=Array.isArray(b.access?.allOf)?b.access.allOf:[];b.capability!==_&&!l.includes(_)&&m("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_CAPABILITY_INVALID",O)}i.set(c,{desktop:u,mobile:p})}return i}function ps(e){let t=new Map(e.data.resources.map((d,s)=>{let a=`/config/data/resources/${s}`,c=Ye(d,a,e.appCode);return[c.code,new Map(c.schema.fields.map(f=>[String(f.code),f]))]})),o=new Map(e.data.resources.map((d,s)=>{let a=`/config/data/resources/${s}`,c=Ye(d,a,e.appCode);return[c.code,new Map(c.schema.fields.map(f=>[String(f.code),String(f.type)]))]})),n=new Set(o.keys()),i=new Set(e.workflows.activations.map((d,s)=>Nn(N(d,`/config/workflows/activations/${s}`).workflowCode,`/config/workflows/activations/${s}/workflowCode`))),r=new Map;return te(e.backend.operations.map((d,s)=>{let a=`/config/backend/operations/${s}`,c=N(d,a);C(c,["code","method","path","capability","requestSchema","responseSchema","description","platformAccess","browser","ai"],a,!0);let f=S(c.method,`${a}/method`,16);["GET","POST","PUT","PATCH","DELETE"].includes(f)||m("NATIVE_OPERATION_METHOD_INVALID",`${a}/method`);let u=v(c.code,`${a}/code`);Bd(c.ai,a,u,f,n);let p=Md(c.platformAccess,`${a}/platformAccess`,o,t,i,new Set(e.authz.roles.map(E=>String(E.code))));if(p?.workflowStage){let E=p.workflowStage,A=e.workflows.definitions.find(O=>O.definition.code===E.workflowCode);(!A||A.definition.subject?.resourceCode!==E.resourceCode||E.runningNodeIds.some(O=>!A.definition.nodes[O]))&&m("NATIVE_WORKFLOW_STAGE_NODE_INVALID",`${a}/platformAccess/workflowStage/runningNodeIds`)}if(p?.recordEdit){let E=e.data.resources.find(A=>A.code===p.recordEdit.resourceCode);E?.surface?.mutationOwner!=="action"&&m("NATIVE_RECORD_EDIT_ACTION_OWNER_REQUIRED",`${a}/platformAccess/recordEdit`);for(let A of p.recordEdit.fieldCodes)(!E.fieldPolicies?.[A]?.update?.length||E.surface?.fields?.[A]?.system===!0)&&m("NATIVE_RECORD_EDIT_FIELD_INVALID",`${a}/platformAccess/recordEdit/fieldCodes`)}if(p?.decimalReservation){let E=p.decimalReservation,A=String(E.resourceCode),O=JSON.stringify([E.amountFieldCode,E.currencyFieldCode,E.relationFieldCode,E.parentFieldCode,E.rootFieldCode,E.statusFieldCode,E.parentRelationValue,E.childRelationValue]),b=r.get(A);b&&b!==O&&m("NATIVE_DECIMAL_RESERVATION_MAPPING_CONFLICT",`${a}/platformAccess/decimalReservation`),r.set(A,O)}let _=Wd(c.browser,`${a}/browser`,f,c.requestSchema,c.responseSchema,o,t,e.data.subjectReadSurfaces||[]);return{code:u,method:f,path:Oe(c.path,`${a}/path`),requiredCapability:me(c.capability,`${a}/capability`,e.appCode),requestSchemaDigest:Z(N(c.requestSchema,`${a}/requestSchema`)),responseSchemaDigest:Z(N(c.responseSchema,`${a}/responseSchema`)),...c.description===void 0?{}:{description:Go(c.description,`${a}/description`,2e3)},...p?{platformAccess:p}:{},..._?{browser:_}:{}}}),d=>d.code)}function Wd(e,t,o,n,i,r,d,s){if(e===void 0)return null;let a=N(e,t);C(a,["exposure","behavior","idempotency","subject"],t,["refreshTargets","fileIntent"]),F(a.exposure,"authenticated",`${t}/exposure`);let c=S(a.behavior,`${t}/behavior`,32);["read","controlled"].includes(c)||m("NATIVE_OPERATION_BROWSER_BEHAVIOR_INVALID",`${t}/behavior`);let f=S(a.idempotency,`${t}/idempotency`,32);(!["none","required"].includes(f)||c==="controlled"&&f!=="required"||c==="read"&&f!=="none")&&m("NATIVE_OPERATION_BROWSER_IDEMPOTENCY_INVALID",`${t}/idempotency`);let u=N(a.subject,`${t}/subject`);C(u,["resourceCode","inputField"],`${t}/subject`);let p=H(u.resourceCode,`${t}/subject/resourceCode`);r.has(p)||m("NATIVE_OPERATION_BROWSER_SUBJECT_RESOURCE_NOT_DECLARED",`${t}/subject/resourceCode`);let _=G(u.inputField,`${t}/subject/inputField`),E=N(n,`${t}/requestSchema`),A=N(i,`${t}/responseSchema`);(E.type!=="object"||E.additionalProperties!==!1||A.type!=="object"||A.additionalProperties!==!1)&&m("NATIVE_OPERATION_BROWSER_SCHEMA_ROOT_INVALID",`${t}/requestSchema`);let O=N(E.properties,`${t}/requestSchema/properties`),b=new Set(E.required===void 0?[]:V(E.required,`${t}/requestSchema/required`,200));(!(_ in O)||!b.has(_))&&m("NATIVE_OPERATION_BROWSER_SUBJECT_INPUT_INVALID",`${t}/subject/inputField`);let g=N(O[_],`${t}/requestSchema/properties/${_}`);(g.type!=="string"||g.format!=="uuid")&&m("NATIVE_OPERATION_BROWSER_SUBJECT_INPUT_INVALID",`${t}/subject/inputField`);let I=new Map((Array.isArray(s)?s:[]).map((h,$)=>{let w=N(h,`/config/data/subjectReadSurfaces/${$}`);return[String(w.code),String(N(w.subject,`/config/data/subjectReadSurfaces/${$}/subject`).resourceCode)]})),T=a.refreshTargets===void 0?[]:D(a.refreshTargets,`${t}/refreshTargets`,16),l=new Set,y=te(T.map((h,$)=>{let w=`${t}/refreshTargets/${$}`,j=N(h,w);C(j,["kind","code"],w),F(j.kind,"subject-surface",`${w}/kind`);let L=v(j.code,`${w}/code`);return(l.has(L)||!I.has(L)||I.get(L)!==p)&&m("NATIVE_OPERATION_BROWSER_REFRESH_TARGET_INVALID",`${w}/code`),l.add(L),{kind:"subject-surface",code:L}}),h=>`${h.kind}:${h.code}`),R=Ud(a.fileIntent,`${t}/fileIntent`,o,c,f,p,O,b,d);return{exposure:"authenticated",behavior:c,idempotency:f,subject:{resourceCode:p,inputField:_},...y.length?{refreshTargets:y}:{},...R?{fileIntent:R}:{}}}function Ud(e,t,o,n,i,r,d,s,a){if(e===void 0)return null;let c=N(e,t);C(c,["recordResourceCode","recordIdInputField","relationField","fileNameField","contentTypeField","sizeField","purposes","maxTtlSeconds","maxBytes"],t),(o!=="GET"||n!=="read"||i!=="none")&&m("NATIVE_OPERATION_FILE_INTENT_BEHAVIOR_INVALID",t);let f=H(c.recordResourceCode,`${t}/recordResourceCode`),u=a.get(f);u||m("NATIVE_OPERATION_FILE_INTENT_RESOURCE_NOT_DECLARED",`${t}/recordResourceCode`);let p=G(c.recordIdInputField,`${t}/recordIdInputField`),_=N(d[p],`${t}/recordIdInputField`);(!s.has(p)||_.type!=="string"||_.format!=="uuid")&&m("NATIVE_OPERATION_FILE_INTENT_RECORD_INPUT_INVALID",`${t}/recordIdInputField`);let E=G(c.relationField,`${t}/relationField`),A=u.get(E);(!A||!["uuid","resource-ref.single"].includes(String(A.type))||String(A.type)==="resource-ref.single"&&(String(N(A.source,`${t}/relationField`).kind||"")!=="resource"||String(N(A.source,`${t}/relationField`).resourceCode||"")!==r))&&m("NATIVE_OPERATION_FILE_INTENT_RELATION_INVALID",`${t}/relationField`);let O=[["fileNameField",["text.short","text.long"]],["contentTypeField",["text.short","text.long"]],["sizeField",["number.integer"]]],b={};for(let[l,y]of O){let R=G(c[l],`${t}/${l}`);y.includes(String(u.get(R)?.type))||m("NATIVE_OPERATION_FILE_INTENT_METADATA_INVALID",`${t}/${l}`),b[l]=R}let g=te(V(c.purposes,`${t}/purposes`,2),l=>l);(!g.length||g.some(l=>!["preview","download"].includes(l)))&&m("NATIVE_OPERATION_FILE_INTENT_PURPOSE_INVALID",`${t}/purposes`);let I=Number(c.maxTtlSeconds);(!Number.isSafeInteger(I)||I<1||I>300)&&m("NATIVE_OPERATION_FILE_INTENT_TTL_INVALID",`${t}/maxTtlSeconds`);let T=Number(c.maxBytes);return(!Number.isSafeInteger(T)||T<1||T>104857600)&&m("NATIVE_OPERATION_FILE_INTENT_SIZE_INVALID",`${t}/maxBytes`),{recordResourceCode:f,recordIdInputField:p,relationField:E,fileNameField:b.fileNameField,contentTypeField:b.contentTypeField,sizeField:b.sizeField,purposes:g,maxTtlSeconds:I,maxBytes:T}}function Md(e,t,o,n,i,r){if(e===void 0)return null;let d=N(e,t);C(d,["directory","selectedDepartments","managedFiles","managedFileCopies","notification","workflow","roleAssertions","decimalReservation","dataCommands","recordEdit","ownedSubject","workflowStage"],t,!0),Object.keys(d).length===0&&m("NATIVE_OPERATION_PLATFORM_ACCESS_EMPTY",t);let s={};if(d.dataCommands!==void 0){let a=N(d.dataCommands,`${t}/dataCommands`);C(a,["mode"],`${t}/dataCommands`),F(a.mode,"recoverable-native",`${t}/dataCommands/mode`),s.dataCommands={mode:"recoverable-native"}}if(d.workflowStage!==void 0){try{Ki(d.workflowStage)}catch{m("NATIVE_WORKFLOW_STAGE_DECLARATION_INVALID",`${t}/workflowStage`)}let a=d.workflowStage;(!s.dataCommands||d.decimalReservation!==void 0||!o.has(a.resourceCode)||!i.has(a.workflowCode)||!d.workflow?.codes?.includes(a.workflowCode))&&m("NATIVE_WORKFLOW_STAGE_DECLARATION_INVALID",`${t}/workflowStage`),s.workflowStage={...a,runningNodeIds:M([...a.runningNodeIds]),allowedStatuses:M([...a.allowedStatuses])}}if(d.recordEdit!==void 0){let a=`${t}/recordEdit`,c=N(d.recordEdit,a);C(c,["resourceCode","fieldCodes"],a);let f=H(c.resourceCode,`${a}/resourceCode`),u=n.get(f),p=V(c.fieldCodes,`${a}/fieldCodes`,200);(!u||!p.length||!s.dataCommands)&&m("NATIVE_RECORD_EDIT_DECLARATION_INVALID",a);for(let _ of p){let E=u.get(_);(!E||E.type==="serial-number"||E.type==="subtable")&&m("NATIVE_RECORD_EDIT_FIELD_INVALID",`${a}/fieldCodes`)}s.recordEdit={resourceCode:f,fieldCodes:M(p)}}if(d.roleAssertions!==void 0){let a=N(d.roleAssertions,`${t}/roleAssertions`);C(a,["roleCodes","actorAuthority"],`${t}/roleAssertions`,!0),a.actorAuthority!==void 0&&F(a.actorAuthority,!0,`${t}/roleAssertions/actorAuthority`);let c=V(a.roleCodes,`${t}/roleAssertions/roleCodes`,20);c.length||m("NATIVE_OPERATION_ROLE_ASSERTIONS_REQUIRED",`${t}/roleAssertions/roleCodes`),c.forEach((f,u)=>{r.has(f)||m("NATIVE_ROLE_REFERENCE_MISSING",`${t}/roleAssertions/roleCodes/${u}`)}),s.roleAssertions={roleCodes:M(c),...a.actorAuthority===!0?{actorAuthority:!0}:{}}}if(d.directory!==void 0){let a=N(d.directory,`${t}/directory`);C(a,["mode","fields"],`${t}/directory`),["current-initiator","selected-user"].includes(String(a.mode))||m("NATIVE_OPERATION_DIRECTORY_MODE_INVALID",`${t}/directory/mode`);let c=new Set(["displayName","employeeNumber","primaryDepartment","departments",...a.mode==="current-initiator"?["phone"]:[]]),f=V(a.fields,`${t}/directory/fields`,c.size);(!f.length||f.some(u=>!c.has(u)))&&m("NATIVE_OPERATION_DIRECTORY_FIELDS_INVALID",`${t}/directory/fields`),s.directory={mode:String(a.mode),fields:M(f)}}if(d.selectedDepartments!==void 0){let a=`${t}/selectedDepartments`,c=N(d.selectedDepartments,a);C(c,["fields","maxIds"],a);let f=V(c.fields,`${a}/fields`,4);(!f.includes("name")||f.some(u=>!["name","path","parent","fullPath"].includes(u))||!Number.isSafeInteger(c.maxIds)||c.maxIds<1||c.maxIds>50)&&m("NATIVE_OPERATION_SELECTED_DEPARTMENTS_INVALID",a),s.selectedDepartments={fields:M(f),maxIds:c.maxIds}}if(d.managedFiles!==void 0){let a=D(d.managedFiles,`${t}/managedFiles`,16);a.length||m("NATIVE_OPERATION_MANAGED_FILES_REQUIRED",`${t}/managedFiles`);let c=new Set;s.managedFiles=te(a.map((f,u)=>{let p=`${t}/managedFiles/${u}`,_=N(f,p);C(_,["resourceCode","fieldCodes","intents"],p);let E=H(_.resourceCode,`${p}/resourceCode`);(c.has(E)||!o.has(E))&&m("NATIVE_OPERATION_MANAGED_FILE_RESOURCE_INVALID",`${p}/resourceCode`),c.add(E);let A=V(_.fieldCodes,`${p}/fieldCodes`,16);(!A.length||A.some(b=>!["file","image","signature","text.rich"].includes(String(o.get(E)?.get(b)||""))))&&m("NATIVE_OPERATION_MANAGED_FILE_FIELD_INVALID",`${p}/fieldCodes`);let O=V(_.intents,`${p}/intents`,2);return(!O.length||O.some(b=>!["create","update"].includes(b)))&&m("NATIVE_OPERATION_MANAGED_FILE_INTENT_INVALID",`${p}/intents`),{resourceCode:E,fieldCodes:M(A),intents:M(O)}}),f=>f.resourceCode)}if(d.managedFileCopies!==void 0){let a=D(d.managedFileCopies,`${t}/managedFileCopies`,16);a.length||m("NATIVE_OPERATION_MANAGED_FILE_COPIES_REQUIRED",`${t}/managedFileCopies`);let c=new Set;s.managedFileCopies=te(a.map((f,u)=>{let p=`${t}/managedFileCopies/${u}`,_=N(f,p);C(_,["mode","sourceResourceCode","sourceFieldCodes","targetResourceCode","targetFieldCodes"],p),F(_.mode,"copy",`${p}/mode`);let E=H(_.sourceResourceCode,`${p}/sourceResourceCode`),A=H(_.targetResourceCode,`${p}/targetResourceCode`),O=o.get(E),b=o.get(A);(!O||!b)&&m("NATIVE_OPERATION_MANAGED_FILE_COPY_RESOURCE_INVALID",p);let g=V(_.sourceFieldCodes,`${p}/sourceFieldCodes`,16),I=V(_.targetFieldCodes,`${p}/targetFieldCodes`,16);(!g.length||g.length!==I.length)&&m("NATIVE_OPERATION_MANAGED_FILE_COPY_FIELDS_INVALID",p),g.forEach((l,y)=>{let R=O.get(l),h=b.get(I[y]);(!["file","image","text.rich"].includes(String(R))||R!==h)&&m("NATIVE_OPERATION_MANAGED_FILE_COPY_FIELD_INVALID",`${p}/sourceFieldCodes/${y}`)});let T=`${E}:${g.join(",")}=>${A}:${I.join(",")}`;return c.has(T)&&m("NATIVE_OPERATION_MANAGED_FILE_COPY_DUPLICATE",p),c.add(T),{mode:"copy",sourceResourceCode:E,sourceFieldCodes:M(g),targetResourceCode:A,targetFieldCodes:M(I)}}),f=>`${f.sourceResourceCode}:${f.sourceFieldCodes.join(",")}=>${f.targetResourceCode}:${f.targetFieldCodes.join(",")}`)}if(d.notification!==void 0){let a=N(d.notification,`${t}/notification`);C(a,["mode"],`${t}/notification`),a.mode!=="business-standard"&&m("NATIVE_OPERATION_NOTIFICATION_MODE_INVALID",`${t}/notification/mode`),s.notification={mode:"business-standard"}}if(d.workflow!==void 0){let a=N(d.workflow,`${t}/workflow`);C(a,["codes"],`${t}/workflow`,["businessCommands"]);let c=V(a.codes,`${t}/workflow/codes`,16);(!c.length||c.some(u=>!i.has(u)))&&m("NATIVE_OPERATION_WORKFLOW_CODE_INVALID",`${t}/workflow/codes`);let f=a.businessCommands===void 0?void 0:V(a.businessCommands,`${t}/workflow/businessCommands`,4);f&&(!f.length||f.some(u=>!["approve","reject","withdraw","resubmit"].includes(u)))&&m("NATIVE_OPERATION_WORKFLOW_BUSINESS_COMMAND_INVALID",`${t}/workflow/businessCommands`),s.workflow={codes:M(c),...f?{businessCommands:M(f)}:{}}}if(d.ownedSubject!==void 0){let a=`${t}/ownedSubject`,c=d.ownedSubject;try{pn(c)}catch{m("NATIVE_WORKFLOW_OWNED_SUBJECT_INVALID",a)}(!s.workflow||d.decimalReservation!==void 0)&&m("NATIVE_WORKFLOW_OWNED_SUBJECT_INVALID",a);try{Mr(c,n,s.managedFiles||[])}catch(f){m(`NATIVE_${f.message}`,a)}s.ownedSubject={mode:"create",resourceCode:c.resourceCode,subtables:te(c.subtables.map(f=>({fieldCode:f.fieldCode,fieldCodes:M([...f.fieldCodes])})),f=>f.fieldCode)}}if(d.decimalReservation!==void 0){let a=`${t}/decimalReservation`,c=N(d.decimalReservation,a);C(c,["mode","resourceCode","amountFieldCode","currencyFieldCode","relationFieldCode","parentFieldCode","rootFieldCode","statusFieldCode","parentRelationValue","childRelationValue","eligibleParentStatuses","eligibleChildStatuses"],a);let f=S(c.mode,`${a}/mode`,16);["reserve","commit","release"].includes(f)||m("NATIVE_DECIMAL_RESERVATION_MODE_INVALID",`${a}/mode`);let u=H(c.resourceCode,`${a}/resourceCode`),p=n.get(u);p||m("NATIVE_DECIMAL_RESERVATION_RESOURCE_MISSING",`${a}/resourceCode`);let E=Object.fromEntries(["amountFieldCode","currencyFieldCode","relationFieldCode","parentFieldCode","rootFieldCode","statusFieldCode"].map(l=>[l,G(c[l],`${a}/${l}`)])),A=l=>p.get(E[l]),O=l=>new Set((A(l)?.options||[]).map(y=>String(y.value))),b=v(c.parentRelationValue,`${a}/parentRelationValue`),g=v(c.childRelationValue,`${a}/childRelationValue`),I=V(c.eligibleParentStatuses,`${a}/eligibleParentStatuses`,16),T=V(c.eligibleChildStatuses,`${a}/eligibleChildStatuses`,16);(A("amountFieldCode")?.type!=="number.decimal"||A("amountFieldCode")?.exactDecimal!==!0||A("amountFieldCode")?.precision!==18||A("amountFieldCode")?.scale!==2||A("currencyFieldCode")?.type!=="option.single"||A("relationFieldCode")?.type!=="option.single"||A("parentFieldCode")?.type!=="resource-ref.single"||A("parentFieldCode")?.source?.resourceCode!==u||A("rootFieldCode")?.type!=="uuid"||A("statusFieldCode")?.type!=="option.single"||b===g||!O("relationFieldCode").has(b)||!O("relationFieldCode").has(g)||!I.length||!T.length||I.some(l=>!O("statusFieldCode").has(l))||T.some(l=>!O("statusFieldCode").has(l)))&&m("NATIVE_DECIMAL_RESERVATION_FIELD_INVALID",a),s.decimalReservation={mode:f,resourceCode:u,...E,parentRelationValue:b,childRelationValue:g,eligibleParentStatuses:M(I),eligibleChildStatuses:M(T)}}return s}function Bd(e,t,o,n,i){if(e===void 0)return;let r=`${t}/ai`,d=N(e,r);ld.test(o)||m("NATIVE_OPERATION_AI_CODE_INVALID",`${t}/code`),C(d,["name","description","risk","resources","sideEffects","concurrency","timeoutMs"],r,!0),S(d.name,`${r}/name`,Lo),S(d.description,`${r}/description`,Lo);let s=S(d.risk,`${r}/risk`,16);["read","write","destructive","external"].includes(s)||m("NATIVE_OPERATION_AI_RISK_INVALID",`${r}/risk`),s==="read"!=(n==="GET")&&m("NATIVE_OPERATION_AI_METHOD_RISK_MISMATCH",`${r}/risk`),n==="DELETE"&&!["destructive","external"].includes(s)&&m("NATIVE_OPERATION_AI_METHOD_RISK_MISMATCH",`${r}/risk`);let a=V(d.resources,`${r}/resources`,16);a.length===0&&m("NATIVE_OPERATION_AI_RESOURCE_REQUIRED",`${r}/resources`),a.forEach((f,u)=>{let p=H(f,`${r}/resources/${u}`);i.has(p)||m("NATIVE_OPERATION_AI_RESOURCE_MISSING",`${r}/resources/${u}`)});let c=V(d.sideEffects,`${r}/sideEffects`,20);(s==="read"&&c.length!==0||s!=="read"&&c.length===0)&&m("NATIVE_OPERATION_AI_SIDE_EFFECT_INVALID",`${r}/sideEffects`),d.concurrency!==void 0&&!["none","revision"].includes(S(d.concurrency,`${r}/concurrency`,16))&&m("NATIVE_OPERATION_AI_CONCURRENCY_INVALID",`${r}/concurrency`),d.timeoutMs!==void 0&&se(d.timeoutMs,`${r}/timeoutMs`,100,3e4)}function An(e){return(e.replace(/\/{2,}/g,"/").replace(/\/$/,"")||"/").split("/").map(o=>o.startsWith(":")?":":o.includes("*")?"*":o).join("/")}function Kd(e,t){let o=N(e,t),n=S(o.type,`${t}/type`,32),i=["code","type","label","presentation","required"],r=n==="sso"?[...i,"provider"]:n==="dingtalk"?[...i,"flow"]:i;C(o,r,t);let d=v(o.code,`${t}/code`),s=S(o.label,`${t}/label`,255),a=S(o.presentation,`${t}/presentation`,16);["primary","secondary"].includes(a)||m("NATIVE_APPLICATION_AUTH_METHOD_PRESENTATION_INVALID",`${t}/presentation`);let c=ft(o.required,`${t}/required`);return["sso","password","dingtalk"].includes(n)||m("NATIVE_APPLICATION_AUTH_METHOD_TYPE_INVALID",`${t}/type`),n==="sso"&&o.provider!=="tenant-default"&&m("NATIVE_APPLICATION_AUTH_SSO_PROVIDER_INVALID",`${t}/provider`),n==="dingtalk"&&!["auto","jsapi","oauth"].includes(S(o.flow,`${t}/flow`,16))&&m("NATIVE_APPLICATION_AUTH_DINGTALK_FLOW_INVALID",`${t}/flow`),{code:d,type:n,label:s,presentation:a,required:c,...n==="sso"?{provider:"tenant-default"}:{},...n==="dingtalk"?{flow:o.flow}:{}}}function Xr(e,t,o){let n=N(e,o);C(n,["routeCode","path","defaultRouteCode"],o);let i=v(n.routeCode,`${o}/routeCode`),r=Oe(n.path,`${o}/path`),d=t==="desktop"?"/login":"/m/login";return(r!==d||/[:*?#\\]/.test(r))&&m("NATIVE_APPLICATION_AUTH_SURFACE_PATH_INVALID",`${o}/path`,{device:t,expectedPath:d}),{routeCode:i,path:r,defaultRouteCode:v(n.defaultRouteCode,`${o}/defaultRouteCode`)}}function ms(e,t,o,n){if(e===null)return;let i=N(e,n);C(i,["accountMode","registration","methods","surfaces"],n),F(i.accountMode,"existing-platform-users-only",`${n}/accountMode`);let r=N(i.registration,`${n}/registration`);C(r,["mode"],`${n}/registration`),F(r.mode,"reject",`${n}/registration/mode`);let d=D(i.methods,`${n}/methods`,8);d.length===0&&m("NATIVE_APPLICATION_AUTH_METHOD_REQUIRED",`${n}/methods`);let s=d.map((b,g)=>Kd(b,`${n}/methods/${g}`)),a=new Set,c=new Set;for(let[b,g]of s.entries())a.has(g.code)&&m("NATIVE_APPLICATION_AUTH_METHOD_CODE_DUPLICATE",`${n}/methods/${b}/code`),c.has(g.type)&&m("NATIVE_APPLICATION_AUTH_METHOD_TYPE_DUPLICATE",`${n}/methods/${b}/type`),a.add(g.code),c.add(g.type);s.filter(b=>b.presentation==="primary").length!==1&&m("NATIVE_APPLICATION_AUTH_PRIMARY_METHOD_INVALID",`${n}/methods`);let f=N(i.surfaces,`${n}/surfaces`);C(f,["desktop","mobile"],`${n}/surfaces`);let u=Xr(f.desktop,"desktop",`${n}/surfaces/desktop`),p=Xr(f.mobile,"mobile",`${n}/surfaces/mobile`);u.routeCode===p.routeCode&&m("NATIVE_APPLICATION_AUTH_SURFACE_CODE_DUPLICATE",`${n}/surfaces/mobile/routeCode`);let _=D(t,"/config/frontend/routes",B.routes),E=new Map;for(let[b,g]of _.entries()){let I=N(g,`/config/frontend/routes/${b}`);E.set(String(I.code||""),I)}let A=new Set((Array.isArray(o.data?.resources)?o.data.resources:[]).map(b=>String(b.code||"")).filter(b=>/^[a-z][a-z0-9-]{0,62}$/.test(b)));for(let[b,g]of[["desktop",u],["mobile",p]]){E.has(g.routeCode)&&m("NATIVE_APPLICATION_AUTH_SURFACE_CODE_CONFLICT",`${n}/surfaces/${b}/routeCode`);let I=/^user\.([a-z][a-z0-9-]{0,62})\.(records|submit)$/.exec(String(g.defaultRouteCode||"")),T=E.get(g.defaultRouteCode),l=String(T?.path||"");if(I&&A.has(I[1])){let R=I[2]==="records"?`/my/${I[1]}`:`/my/${I[1]}/submit`;T={surface:"user",path:b==="mobile"?`/m${R}`:R},l=String(T.path)}let y=b==="desktop"?l==="/m"||l.startsWith("/m/"):!(l==="/m"||l.startsWith("/m/"));(!T||T.surface!=="user"||/[:*]/.test(l)||y)&&m("NATIVE_APPLICATION_AUTH_DEFAULT_ROUTE_INVALID",`${n}/surfaces/${b}/defaultRouteCode`)}let O=_s(o).filter(b=>!b.owner.startsWith("authentication:"));for(let[b,g]of[["desktop",u],["mobile",p]]){let I=O.find(T=>An(T.path)===An(g.path));I&&m("NATIVE_APPLICATION_AUTH_SURFACE_PATH_CONFLICT",`${n}/surfaces/${b}/path`,{owner:I.owner})}}function Gd(e,t){if(e===null)return;let o={data:{resources:[]},workflows:{definitions:[]},frontend:{routes:[{code:"auth-desktop-default",path:"/auth-desktop-default",surface:"user"},{code:"auth-mobile-default",path:"/m/auth-mobile-default",surface:"user"}],user:{applicationTodoCenter:!1},admin:{navigation:[]},authentication:e}},n=N(e,t),i=N(n.surfaces,`${t}/surfaces`),r={...n,surfaces:{...i,desktop:{...N(i.desktop,`${t}/surfaces/desktop`),defaultRouteCode:"auth-desktop-default"},mobile:{...N(i.mobile,`${t}/surfaces/mobile`),defaultRouteCode:"auth-mobile-default"}}};ms(r,o.frontend.routes,{...o,frontend:{...o.frontend,authentication:r}},t)}function qd(e){let t=e.frontend.authentication;return t===null?null:{accountMode:t.accountMode,registration:{mode:t.registration.mode},methods:t.methods.map(o=>({...o})),surfaces:{desktop:{...t.surfaces.desktop},mobile:{...t.surfaces.mobile}}}}var zd=new Set(["draft.read","draft.update","validate","create","own.list","own.read","public.list","public.read"]);function Jd(e,t,o){let n=N(e,o);C(n,["policies"],o);let i=D(n.policies,`${o}/policies`,16);i.length<1&&m("NATIVE_PUBLIC_POLICY_REQUIRED",o);let r=new Map(t.frontend.routes.map(c=>[c.code,c])),d=new Map(t.data.resources.map(c=>[c.code,c])),s=new Set,a=new Set(i.map(c=>String(c?.code||"")));i.forEach((c,f)=>{let u=`${o}/policies/${f}`,p=N(c,u);C(p,["code","routeCode","mode","resourceCode","operations","fields"],u,["requiredFields","ownRecordFields","publicRecordFields","publicFilters","serverGeneratedFields","schedule","publicSubtableFields","draft","validations"]);let _=v(p.code,`${u}/code`);s.has(_)&&m("NATIVE_PUBLIC_POLICY_DUPLICATE",`${u}/code`);let E=v(p.routeCode,`${u}/routeCode`),A=r.get(E);(!A||A.surface!=="user"||A.capability!==void 0||A.access!==void 0||/[:*]/.test(String(A.path)))&&m("NATIVE_PUBLIC_ROUTE_INVALID",`${u}/routeCode`),F(p.mode,"anonymous",`${u}/mode`);let O=H(p.resourceCode,`${u}/resourceCode`),b=d.get(O);b||m("NATIVE_PUBLIC_RESOURCE_MISSING",`${u}/resourceCode`);let g=new Map(b.schema.fields.map(P=>[String(P.code),String(P.type)])),I=V(p.operations,`${u}/operations`,8);(I.length<1||I.some(P=>!zd.has(P)))&&m("NATIVE_PUBLIC_OPERATION_INVALID",`${u}/operations`),I.includes("draft.read")!==I.includes("draft.update")&&m("NATIVE_PUBLIC_DRAFT_OPERATION_INCOMPLETE",`${u}/operations`);let T=V(p.fields,`${u}/fields`,64);(T.length<1||T.some(P=>!g.has(P)))&&m("NATIVE_PUBLIC_FIELD_INVALID",`${u}/fields`);for(let P of["requiredFields","ownRecordFields","publicRecordFields"]){if(!Object.prototype.hasOwnProperty.call(p,P))continue;V(p[P],`${u}/${P}`,64).some(x=>!T.includes(x))&&m("NATIVE_PUBLIC_FIELD_SCOPE_INVALID",`${u}/${P}`)}let l=Object.prototype.hasOwnProperty.call(p,"serverGeneratedFields")?D(p.serverGeneratedFields,`${u}/serverGeneratedFields`,16):[],y=new Set;l.forEach((P,U)=>{let x=`${u}/serverGeneratedFields/${U}`,q=N(P,x);C(q,["field","kind"],x);let z=G(q.field,`${x}/field`);(y.has(z)||!g.has(z)||T.includes(z)||g.get(z)!=="text.short"&&g.get(z)!=="text.long")&&m("NATIVE_PUBLIC_SERVER_GENERATED_FIELD_INVALID",`${x}/field`),F(q.kind,"random-token",`${x}/kind`),y.add(z)});let R=Object.prototype.hasOwnProperty.call(p,"schedule")?N(p.schedule,`${u}/schedule`):null;if(R){let P=["campusPolicyCode","rulePolicyCode","campusField","ruleCampusField","ruleWeekdaysField","ruleOpenAtField","ruleCloseAtField","ruleSlotMinutesField","ruleAdvanceHoursField","ruleAdvanceDaysField","campusEnabledField","ruleEnabledField","dateField","timeField"];C(R,P,`${u}/schedule`);for(let U of["campusPolicyCode","rulePolicyCode"])v(R[U],`${u}/schedule/${U}`);for(let U of P.filter(x=>!["campusPolicyCode","rulePolicyCode"].includes(x)))G(R[U],`${u}/schedule/${U}`);for(let U of[R.campusField,R.dateField,R.timeField])T.includes(String(U))||m("NATIVE_PUBLIC_SCHEDULE_FIELD_INVALID",`${u}/schedule`);(!a.has(String(R.campusPolicyCode))||!a.has(String(R.rulePolicyCode)))&&m("NATIVE_PUBLIC_SCHEDULE_POLICY_INVALID",`${u}/schedule`)}let h=Object.prototype.hasOwnProperty.call(p,"publicFilters")?D(p.publicFilters,`${u}/publicFilters`,16):[],$=new Set;h.forEach((P,U)=>{let x=`${u}/publicFilters/${U}`,q=N(P,x);C(q,["field","operator","value"],x);let z=G(q.field,`${x}/field`);$.has(z)&&m("NATIVE_PUBLIC_FILTER_DUPLICATE",`${x}/field`),T.includes(z)||m("NATIVE_PUBLIC_FILTER_FIELD_INVALID",`${x}/field`),F(q.operator,"eq",`${x}/operator`),["boolean","text.short","text.long","number.integer","number.decimal","date","time"].includes(g.get(z)||"")||m("NATIVE_PUBLIC_FILTER_FIELD_INVALID",`${x}/field`),q.value!==null&&typeof q.value!="string"&&typeof q.value!="number"&&typeof q.value!="boolean"&&m("NATIVE_PUBLIC_FILTER_VALUE_INVALID",`${x}/value`),$.add(z)});let w=Object.prototype.hasOwnProperty.call(p,"publicSubtableFields")?N(p.publicSubtableFields,`${u}/publicSubtableFields`):null;if(w){Object.keys(w).length>64&&m("NATIVE_PUBLIC_SUBTABLE_FIELDS_INVALID",`${u}/publicSubtableFields`);for(let[P,U]of Object.entries(w)){let x=b.schema.fields.find(J=>String(J.code)===P),q=String(x?.subtable?.resourceCode||""),z=d.get(q),Ae=new Map((z?.schema?.fields||[]).map(J=>[String(J.code),String(J.type)])),Ne=V(U,`${u}/publicSubtableFields/${P}`,64);(!T.includes(P)||g.get(P)!=="subtable"||!z||Ne.length<1||Ne.some(J=>!Ae.has(J))||Ne.some(J=>Ae.get(J)==="subtable")||Ne.some(J=>Ae.get(J)==="signature"))&&m("NATIVE_PUBLIC_SUBTABLE_FIELDS_INVALID",`${u}/publicSubtableFields/${P}`)}}if(I.some(P=>P.startsWith("public."))){Object.prototype.hasOwnProperty.call(p,"publicRecordFields")||m("NATIVE_PUBLIC_RECORD_FIELDS_REQUIRED",`${u}/publicRecordFields`);let P=V(p.publicRecordFields,`${u}/publicRecordFields`,64);(P.length<1||P.some(U=>!T.includes(U))||P.some(U=>g.get(U)==="signature"||g.get(U)==="subtable"&&!w?.[U]))&&m("NATIVE_PUBLIC_RECORD_FIELDS_INVALID",`${u}/publicRecordFields`)}let j=Object.prototype.hasOwnProperty.call(p,"requiredFields")?V(p.requiredFields,`${u}/requiredFields`,64):[],L=b.surface||{},Q=L.fields||{},ee=String(L.mutationOwner||"native")==="native"&&L.generated?.create!==!1,Y=b.schema.fields.filter(P=>Bt(P,Q[P.code])).map(P=>String(P.code));if(I.includes("create")&&!ee&&m("NATIVE_PUBLIC_CREATE_FIELDS_INCOMPLETE",`${u}/fields`),I.includes("create")&&!Object.prototype.hasOwnProperty.call(p,"draft")&&m("NATIVE_PUBLIC_DRAFT_REQUIRED",`${u}/draft`),I.includes("create"))for(let P of Y){let U=T.includes(P)?j.includes(P)?null:"requiredFields":"fields";U&&m("NATIVE_PUBLIC_CREATE_FIELDS_INCOMPLETE",`${u}/${U}`,{resourceCode:H,fieldCode:P})}if(Object.prototype.hasOwnProperty.call(p,"draft")){let P=N(p.draft,`${u}/draft`);C(P,["enabled","inactivityTtlSeconds","maxBytes"],`${u}/draft`),F(P.enabled,!0,`${u}/draft/enabled`),se(P.inactivityTtlSeconds,`${u}/draft/inactivityTtlSeconds`,3600,7776e3),se(P.maxBytes,`${u}/draft/maxBytes`,4096,262144)}else I.includes("draft.read")&&m("NATIVE_PUBLIC_DRAFT_REQUIRED",`${u}/draft`);let ge=Object.prototype.hasOwnProperty.call(p,"validations")?D(p.validations,`${u}/validations`,16):[],oe=new Set;ge.forEach((P,U)=>{let x=`${u}/validations/${U}`,q=N(P,x);C(q,["code","kind","fields","result"],x);let z=v(q.code,`${x}/code`);oe.has(z)&&m("NATIVE_PUBLIC_VALIDATION_DUPLICATE",`${x}/code`),F(q.kind,"duplicate",`${x}/kind`),F(q.result,"availability",`${x}/result`);let Ae=V(q.fields,`${x}/fields`,8);(Ae.length<1||Ae.some(Ne=>!T.includes(Ne))||Ae.some(Ne=>["file","subtable"].includes(g.get(Ne)||"")))&&m("NATIVE_PUBLIC_VALIDATION_FIELD_INVALID",`${x}/fields`),oe.add(z)}),s.add(_)})}function Hd(e,t){let o=N(e,t);C(o,["policies"],t),D(o.policies,`${t}/policies`,16).length<1&&m("NATIVE_PUBLIC_POLICY_REQUIRED",t)}function Yd(e){return{policies:te(e.frontend.publicAccess.policies.map(t=>({code:t.code,routeCode:t.routeCode,mode:t.mode,resourceCode:t.resourceCode,operations:M(t.operations),fields:M(t.fields),...t.requiredFields?{requiredFields:M(t.requiredFields)}:{},...t.ownRecordFields?{ownRecordFields:M(t.ownRecordFields)}:{},...t.publicRecordFields?{publicRecordFields:M(t.publicRecordFields)}:{},...t.publicFilters?{publicFilters:t.publicFilters.map(o=>({field:o.field,operator:o.operator,value:o.value})).sort((o,n)=>Ie(o.field,n.field))}:{},...t.publicSubtableFields?{publicSubtableFields:Object.fromEntries(Object.entries(t.publicSubtableFields).sort(([o],[n])=>o.localeCompare(n)).map(([o,n])=>[o,M(Array.isArray(n)?n.map(String):[])]))}:{},...t.serverGeneratedFields?{serverGeneratedFields:t.serverGeneratedFields.map(o=>({field:o.field,kind:o.kind})).sort((o,n)=>Ie(o.field,n.field))}:{},...t.schedule?{schedule:{campusPolicyCode:t.schedule.campusPolicyCode,rulePolicyCode:t.schedule.rulePolicyCode,campusField:t.schedule.campusField,ruleCampusField:t.schedule.ruleCampusField,ruleWeekdaysField:t.schedule.ruleWeekdaysField,ruleOpenAtField:t.schedule.ruleOpenAtField,ruleCloseAtField:t.schedule.ruleCloseAtField,ruleSlotMinutesField:t.schedule.ruleSlotMinutesField,ruleAdvanceHoursField:t.schedule.ruleAdvanceHoursField,ruleAdvanceDaysField:t.schedule.ruleAdvanceDaysField,campusEnabledField:t.schedule.campusEnabledField,ruleEnabledField:t.schedule.ruleEnabledField,dateField:t.schedule.dateField,timeField:t.schedule.timeField}}:{},...t.draft?{draft:{...t.draft}}:{},...t.validations?{validations:te(t.validations.map(o=>({code:o.code,kind:o.kind,fields:M(o.fields),result:o.result})),o=>o.code)}:{}})),t=>t.code)}}function _s(e){let t=[{owner:"platform:admin-entry",path:"/"},{owner:"platform:admin-entry",path:"/admin"},{owner:"platform:file-preview",path:"/files/:resourceCode/:fileId/preview"}];e.frontend.authentication&&t.push({owner:"authentication:desktop",path:e.frontend.authentication.surfaces.desktop.path},{owner:"authentication:mobile",path:e.frontend.authentication.surfaces.mobile.path});for(let o of e.data.resources){let n=gs(o),i=`/admin/resources/${o.code}`,r=[["list",i],["detail",`${i}/:id`],["create",`${i}/new`],["update",`${i}/:id/edit`]];for(let[d,s]of r)n[d]&&t.push({owner:`resource:${o.code}:${d}`,path:s},{owner:`resource:${o.code}:${d}:mobile`,path:`/m${s}`})}if(e.frontend.user.applicationTodoCenter===!0&&t.push({owner:"application:todo-center",path:"/todos"},{owner:"application:todo-center:mobile",path:"/m/todos"}),e.workflows.definitions.length>0){t.push({owner:"workflow:work-center",path:"/work-center"},{owner:"workflow:work-center:mobile",path:"/m/work-center"},{owner:"workflow:task",path:"/tasks/:taskId"},{owner:"workflow:task:mobile",path:"/m/tasks/:taskId"},{owner:"workflow:instance",path:"/workflows/:instanceId"},{owner:"workflow:instance:mobile",path:"/m/workflows/:instanceId"});let o=!1;for(let n of e.workflows.definitions)["standalone","hidden-handoff"].includes(n.launch.mode)&&(o=!0);o&&t.push({owner:"workflow:launch",path:"/workflows/:workflowCode/start"},{owner:"workflow:launch:mobile",path:"/m/workflows/:workflowCode/start"})}return t}function bn(e){let t=new Map(_s(e).map(o=>[An(o.path),o]));return te(e.frontend.routes.map((o,n)=>{let i=`/config/frontend/routes/${n}`,r=N(o,i);C(r,["code","path","label","surface","parentCode","capability","access","pinned","tabPersistence","keepAlive"],i,!0),["admin","user"].includes(r.surface)||m("NATIVE_ROUTE_SURFACE_INVALID",`${i}/surface`);let d=Oe(r.path,`${i}/path`);r.surface==="admin"&&d!=="/admin"&&!d.startsWith("/admin/")&&m("NATIVE_ADMIN_ROUTE_PATH_INVALID",`${i}/path`),r.surface==="user"&&(d==="/admin"||d.startsWith("/admin/"))&&m("NATIVE_USER_ROUTE_PATH_RESERVED",`${i}/path`);let s=An(d),a=t.get(s);a&&m("NATIVE_ROUTE_PATH_CONFLICT",`${i}/path`,{path:d,owner:a.owner}),t.set(s,{owner:`frontend:${String(r.code||n)}`,path:d});let c=/[:*]/.test(d),f=Ko(r,i,e.appCode),u=r.pinned===void 0?void 0:ft(r.pinned,`${i}/pinned`),p=r.tabPersistence===void 0?c?"none":"session":S(r.tabPersistence,`${i}/tabPersistence`,16),_=r.keepAlive===void 0?"none":S(r.keepAlive,`${i}/keepAlive`,16);return["session","none"].includes(p)||m("NATIVE_ROUTE_TAB_PERSISTENCE_INVALID",`${i}/tabPersistence`),["none","memory"].includes(_)||m("NATIVE_ROUTE_KEEP_ALIVE_INVALID",`${i}/keepAlive`),c&&u===!0&&m("NATIVE_DYNAMIC_ROUTE_PINNED_FORBIDDEN",`${i}/pinned`),c&&p==="session"&&m("NATIVE_DYNAMIC_ROUTE_TAB_PERSISTENCE_FORBIDDEN",`${i}/tabPersistence`),c&&_==="memory"&&m("NATIVE_DYNAMIC_ROUTE_KEEP_ALIVE_FORBIDDEN",`${i}/keepAlive`),{code:v(r.code,`${i}/code`),path:d,label:S(r.label,`${i}/label`,255),surface:r.surface,...r.parentCode===void 0?{}:{parentCode:v(r.parentCode,`${i}/parentCode`)},...f,...u===void 0?{}:{pinned:u},tabPersistence:p,keepAlive:_}}),o=>o.code)}function gs(e){let t=e.surface===void 0?{}:N(e.surface,"/surface"),o=t.mutationOwner||"native",n=t.generated===void 0?{}:N(t.generated,"/surface/generated"),i=o==="native";return{list:n.list??!0,detail:n.detail??!0,create:n.create??i,update:n.update??i,delete:n.delete??i}}function As(e){let t=[];for(let o of te(e.data.resources,n=>n.code).flatMap(n=>[{resource:n,viewCode:void 0},...(n.surface?.views||[]).map(i=>({viewCode:i.code,resource:{...n,name:i.name,surface:Qn(n.surface,i.code)}}))])){let{resource:n,viewCode:i}=o,r=`/admin/resources/${n.code}${i?`/views/${i}`:""}`,d=gs(n),s=[{operation:"list",kind:"resource-list",path:`${r}`,label:n.name,capability:n.capabilities.read,navigationEligible:!0},{operation:"detail",kind:"resource-detail",path:`${r}/:id`,label:`${n.name}\u8BE6\u60C5`,capability:n.capabilities.read,navigationEligible:!1},{operation:"create",kind:"resource-create",path:`${r}/new`,label:`\u65B0\u589E${n.name}`,capability:n.capabilities.create,navigationEligible:!1},{operation:"update",kind:"resource-update",path:`${r}/:id/edit`,label:`\u7F16\u8F91${n.name}`,capability:n.capabilities.update,navigationEligible:!1}];for(let a of s)d[a.operation]&&t.push({code:`resource:${n.code}${i?`:view:${i}`:""}:${a.operation}`,kind:a.kind,path:a.path,label:a.label,navigationEligible:a.navigationEligible,capability:a.capability,resourceCode:n.code,...i?{viewCode:i}:{}})}for(let o of bn(e))o.surface==="admin"&&t.push({code:`operation:${o.code}`,kind:"operation",path:o.path,label:o.label,navigationEligible:!/[:*]/.test(o.path),routeCode:o.code});return t.sort((o,n)=>Ie(o.code,n.code))}function Es(e){return e.kind==="resource"?`resource:${e.resourceCode}${e.viewCode?`:view:${e.viewCode}`:""}:list`:`operation:${e.routeCode}`}function Xd(e){return e.frontend.admin.navigation.map((t,o)=>({code:t.code,label:t.label,...t.icon===void 0?{}:{icon:t.icon},order:t.order??o,items:t.items.map((n,i)=>({pageCode:Es(n.page),...n.label===void 0?{}:{label:n.label},...n.icon===void 0?{}:{icon:n.icon},order:n.order??i})).sort((n,i)=>n.order-i.order||Ie(n.pageCode,i.pageCode))})).sort((t,o)=>t.order-o.order||Ie(t.code,o.code))}function Zd(e,t){let o=D(e,t,B.adminNavigationGroups);o.reduce((i,r)=>i+(Array.isArray(r?.items)?r.items.length:0),0)>B.adminNavigationItems&&m("NATIVE_ARRAY_LIMIT_EXCEEDED",t);let n=0;o.forEach((i,r)=>{let d=`${t}/${r}`,s=N(i,d);C(s,["code","label","icon","order","items"],d,!0),v(s.code,`${d}/code`),S(s.label,`${d}/label`,255),En(s.icon,`${d}/icon`),ns(s.order,`${d}/order`);let a=D(s.items,`${d}/items`,500);a.length===0&&m("NATIVE_ADMIN_GROUP_ORPHANED",`${d}/items`),n+=a.length,n>B.adminNavigationItems&&m("NATIVE_ARRAY_LIMIT_EXCEEDED",t),a.forEach((c,f)=>{let u=`${d}/items/${f}`,p=N(c,u);C(p,["page","label","icon","order"],u,!0),Qd(p.page,`${u}/page`),p.label!==void 0&&S(p.label,`${u}/label`,255),En(p.icon,`${u}/icon`),ns(p.order,`${u}/order`)})})}function Qd(e,t){let o=N(e,t),n=S(o.kind,`${t}/kind`,64);if(n==="resource"){C(o,["kind","resourceCode"],t,["viewCode"]),o.viewCode!==void 0&&v(o.viewCode,`${t}/viewCode`),H(o.resourceCode,`${t}/resourceCode`);return}if(n==="operation"){C(o,["kind","routeCode"],t),v(o.routeCode,`${t}/routeCode`);return}m("NATIVE_ADMIN_PAGE_REFERENCE_KIND_INVALID",`${t}/kind`)}function ec(e){let t=new Map(As(e).map(i=>[String(i.code),i])),o=new Set,n=new Set;e.frontend.admin.navigation.forEach((i,r)=>{let d=`/config/frontend/admin/navigation/${r}`;o.has(i.code)&&m("NATIVE_ADMIN_GROUP_DUPLICATE",`${d}/code`),o.add(i.code),i.label===i.code&&m("NATIVE_ADMIN_USER_LABEL_REQUIRED",`${d}/label`),i.items.forEach((s,a)=>{let c=`${d}/items/${a}`,f=Es(s.page),u=t.get(f);(!u||u.navigationEligible!==!0)&&m("NATIVE_ADMIN_PAGE_NOT_FOUND",`${c}/page`),n.has(f)&&m("NATIVE_ADMIN_PAGE_DUPLICATE",`${c}/page`),n.add(f);let p=s.page.resourceCode||s.page.routeCode||s.page.workflowCode||f,_=s.label||u.label;(!_||_===p||_===f)&&m("NATIVE_ADMIN_USER_LABEL_REQUIRED",`${c}/label`)})})}function tc(e,t){let o=D(e,t,B.adminPages),n=new Set;o.forEach((i,r)=>{let d=`${t}/${r}`,s=N(i,d);C(s,["code","kind","path","label","navigationEligible","capability","access","resourceCode","viewCode","routeCode"],d,!0);let a=S(s.code,`${d}/code`,255);n.has(a)&&m("NATIVE_ADMIN_PAGE_DUPLICATE",`${d}/code`),n.add(a);let c=S(s.kind,`${d}/kind`,64);if(["resource-list","resource-detail","resource-create","resource-update","operation"].includes(c)||m("NATIVE_ADMIN_PAGE_KIND_INVALID",`${d}/kind`),Oe(s.path,`${d}/path`),S(s.label,`${d}/label`,255),ft(s.navigationEligible,`${d}/navigationEligible`),s.capability!==void 0&&s.access!==void 0&&m("NATIVE_ROUTE_ACCESS_CONFLICT",`${d}/access`),s.capability!==void 0&&S(s.capability,`${d}/capability`,255),s.access!==void 0){let f=N(s.access,`${d}/access`);C(f,["allOf","anyOf"],`${d}/access`,!0);for(let u of["allOf","anyOf"])f[u]!==void 0&&V(f[u],`${d}/access/${u}`,50)}for(let f of["resourceCode","viewCode","routeCode"])s[f]!==void 0&&v(s[f],`${d}/${f}`)})}function nc(e,t){let o=D(e,t,B.adminNavigationGroups);o.reduce((i,r)=>i+(Array.isArray(r?.items)?r.items.length:0),0)>B.adminNavigationItems&&m("NATIVE_ARRAY_LIMIT_EXCEEDED",t);let n=0;o.forEach((i,r)=>{let d=`${t}/${r}`,s=N(i,d);C(s,["code","label","icon","order","items"],d,!0),v(s.code,`${d}/code`),S(s.label,`${d}/label`,255),En(s.icon,`${d}/icon`),se(s.order,`${d}/order`,-1e4,1e4);let a=D(s.items,`${d}/items`,500);a.length===0&&m("NATIVE_ADMIN_GROUP_ORPHANED",`${d}/items`),n+=a.length,n>B.adminNavigationItems&&m("NATIVE_ARRAY_LIMIT_EXCEEDED",t),a.forEach((c,f)=>{let u=`${d}/items/${f}`,p=N(c,u);C(p,["pageCode","label","icon","order"],u,!0),S(p.pageCode,`${u}/pageCode`,255),p.label!==void 0&&S(p.label,`${u}/label`,255),En(p.icon,`${u}/icon`),se(p.order,`${u}/order`,-1e4,1e4)})})}var oc=new Set(["application-todo-center","workflow-work-center","workflow-launch","workflow-task","workflow-instance","resource-records","resource-submit"]);function ic(e,t,o){let n=N(e,t);C(n,["schemaVersion","appCode","devicePolicy","rootEntry","authentication","routes","digest"],t),F(n.schemaVersion,us,`${t}/schemaVersion`),F(n.appCode,o,`${t}/appCode`),Bo(n.devicePolicy,`${t}/devicePolicy`),rc(n.rootEntry,`${t}/rootEntry`),sc(n.authentication,`${t}/authentication`),Uo(n.digest,`${t}/digest`);let i=D(n.routes,`${t}/routes`,B.routes),r=new Set;i.forEach((d,s)=>{let a=`${t}/routes/${s}`,c=N(d,a),f=c.kind==="resource-records"||c.kind==="resource-submit";C(c,["code","kind","desktop","mobile"],a,["workflowCode",...f?["resourceCode"]:[]]);let u=S(c.code,`${a}/code`,255);r.has(u)&&m("NATIVE_ROUTE_MANIFEST_DUPLICATE",`${a}/code`),r.add(u);let p=S(c.kind,`${a}/kind`,64);if(oc.has(p)||m("NATIVE_ROUTE_MANIFEST_KIND_INVALID",`${a}/kind`),c.workflowCode!==void 0&&v(c.workflowCode,`${a}/workflowCode`),f){let A=H(c.resourceCode,`${a}/resourceCode`);F(u,`user.${A}.${c.kind==="resource-records"?"records":"submit"}`,`${a}/code`)}else c.resourceCode!==void 0&&m("NATIVE_PROPERTY_UNKNOWN",`${a}/resourceCode`);let _=Qr(c.desktop,`${a}/desktop`,o),E=Qr(c.mobile,`${a}/mobile`,o);_.surface!=="user"&&m("NATIVE_ROUTE_MANIFEST_DESKTOP_SURFACE_INVALID",`${a}/desktop/surface`),E.surface!=="user"&&m("NATIVE_ROUTE_MANIFEST_MOBILE_SURFACE_INVALID",`${a}/mobile/surface`),_.routeCode===E.routeCode&&m("NATIVE_ROUTE_MANIFEST_PAIR_DUPLICATE",a)}),F(n.digest,Z({schemaVersion:n.schemaVersion,appCode:n.appCode,devicePolicy:n.devicePolicy,rootEntry:n.rootEntry,authentication:n.authentication,routes:n.routes}),`${t}/digest`)}function Bo(e,t){let o=N(e,t);C(o,["kind","mobileMaxWidthPx","desktopMinWidthPx"],t),F(o.kind,"viewport-family",`${t}/kind`);let n=se(o.mobileMaxWidthPx,`${t}/mobileMaxWidthPx`,320,1600),i=se(o.desktopMinWidthPx,`${t}/desktopMinWidthPx`,320,1600);return i!==n+1&&m("NATIVE_FRONTEND_DEVICE_POLICY_INVALID",t),{kind:"viewport-family",mobileMaxWidthPx:n,desktopMinWidthPx:i}}function rc(e,t){let o=N(e,t);C(o,["code","desktop","mobile"],t);let n=v(o.code,`${t}/code`),i=Wo(o.desktop,`${t}/desktop`),r=Wo(o.mobile,`${t}/mobile`);return(i===r||r==="/"||!r.startsWith("/m/"))&&m("NATIVE_ROUTE_MANIFEST_ROOT_ENTRY_INVALID",t),i.startsWith("/m/")&&m("NATIVE_ROUTE_MANIFEST_ROOT_ENTRY_INVALID",`${t}/desktop`),{code:n,desktop:i,mobile:r}}function sc(e,t){let o=N(e,t);C(o,["desktop","mobile"],t);let n=Zr(o.desktop,`${t}/desktop`,!1),i=Zr(o.mobile,`${t}/mobile`,!0);return(n.routeCode===i.routeCode||n.path===i.path)&&m("NATIVE_ROUTE_MANIFEST_AUTHENTICATION_DUPLICATE",t),{desktop:n,mobile:i}}function Zr(e,t,o){let n=N(e,t);C(n,["routeCode","path"],t);let i=v(n.routeCode,`${t}/routeCode`),r=Wo(n.path,`${t}/path`);return(o?!r.startsWith("/m/"):r.startsWith("/m/"))&&m("NATIVE_ROUTE_MANIFEST_AUTHENTICATION_PATH_INVALID",`${t}/path`),{routeCode:i,path:r}}function Wo(e,t){let o=Oe(e,t);return/[:*?#\\\\]/.test(o)&&m("NATIVE_ROUTE_MANIFEST_STATIC_PATH_INVALID",t),o}function Qr(e,t,o){let n=N(e,t);C(n,["routeCode","path","surface","pathParams","requiresAuthentication"],t,["capability","access"]),v(n.routeCode,`${t}/routeCode`);let i=Oe(n.path,`${t}/path`),r=S(n.surface,`${t}/surface`,16);["admin","user"].includes(r)||m("NATIVE_ROUTE_SURFACE_INVALID",`${t}/surface`);let d=V(n.pathParams,`${t}/pathParams`,8);return d.forEach((s,a)=>{(!/^[A-Za-z][A-Za-z0-9_]*$/.test(s)||s.length>64)&&m("NATIVE_ROUTE_PATH_PARAM_INVALID",`${t}/pathParams/${a}`)}),X(d)!==X(Is(i))&&m("NATIVE_ROUTE_PATH_PARAMS_MISMATCH",`${t}/pathParams`),Ko(n,t,o),n.requiresAuthentication!==!0&&m("NATIVE_ROUTE_AUTHENTICATION_REQUIRED",`${t}/requiresAuthentication`),n}function Is(e){return M([...e.matchAll(/:([A-Za-z][A-Za-z0-9_]*)/g)].map(t=>t[1]))}function es(e,t,o,n){return{routeCode:e,path:t,surface:o,pathParams:Is(t),...n?.capability?{capability:n.capability}:{},...n?.access?{access:n.access}:{},requiresAuthentication:!0}}function ts(e,t,o,n){return e==="workflow-launch"?`workflow.${o}.launch.${t}`:e==="application-todo-center"?`application.todo-center.${t}`:e==="resource-records"?`user.${n}.records.${t}`:e==="resource-submit"?`user.${n}.submit.${t}`:`${e.replace(/-/g,".")}.${t}`}function ac(e){let t=e.appCode,o=[],n=(_,E,A,O,b,g,I)=>{o.push({code:_,kind:E,...b?{workflowCode:b}:{},...I?{resourceCode:I}:{},desktop:es(ts(E,"desktop",b,I),A,"user",g),mobile:es(ts(E,"mobile",b,I),O,"user",g)})};e.frontend.user.applicationTodoCenter===!0&&n("application:todo-center","application-todo-center","/todos","/m/todos");let i=ys(e);i.length>0&&(n("workflow:work-center","workflow-work-center","/work-center","/m/work-center"),n("workflow:task","workflow-task","/tasks/:taskId","/m/tasks/:taskId"),n("workflow:instance","workflow-instance","/workflows/:instanceId","/m/workflows/:instanceId"));for(let _ of i){if(!["standalone","hidden-handoff"].includes(_.launch.mode))continue;let E=M([_.launch.submission?.create?.requiredCapability,_.launch.submission?.existing?.requiredCapability].filter(A=>!!A));n(`workflow:${_.code}:launch`,"workflow-launch","/workflows/:workflowCode/start","/m/workflows/:workflowCode/start",_.code,E.length===1?{capability:E[0]}:E.length>1?{access:{anyOf:E}}:void 0)}let r=o.sort((_,E)=>Ie(String(_.code),String(E.code))),d=bn(e),s=_=>{let E=_==="mobile"?"/m/":"/",A=d.filter(b=>b.surface==="user"&&!/[:*?#\\\\]/.test(b.path)&&b.path===E).sort((b,g)=>Ie(b.code,g.code))[0];if(A)return{code:A.code,path:A.path};let O=d.filter(b=>b.surface==="user"&&!/[:*?#\\\\]/.test(b.path)&&(_==="mobile"?b.path.startsWith("/m/"):!b.path.startsWith("/m/"))).sort((b,g)=>Ie(b.code,g.code))[0];return O?{code:O.code,path:O.path}:{code:_==="mobile"?"application-root-mobile":"application-root",path:E}},a=e.frontend.authentication?{desktop:{routeCode:e.frontend.authentication.surfaces.desktop.routeCode,path:e.frontend.authentication.surfaces.desktop.path},mobile:{routeCode:e.frontend.authentication.surfaces.mobile.routeCode,path:e.frontend.authentication.surfaces.mobile.path}}:{desktop:{routeCode:"application-login",path:"/login"},mobile:{routeCode:"application-login-mobile",path:"/m/login"}},c=Bo(e.frontend.devicePolicy,"/config/frontend/devicePolicy"),f=s("desktop"),u=s("mobile"),p={schemaVersion:us,appCode:t,devicePolicy:c,rootEntry:{code:f.code,desktop:f.path,mobile:u.path},authentication:a,routes:r};return{...p,digest:Z(p)}}function En(e,t){if(e===void 0)return;let o=S(e,t,32);bd.has(o)||m("NATIVE_ADMIN_ICON_INVALID",t)}function ns(e,t){e!==void 0&&se(e,t,-1e4,1e4)}function Ko(e,t,o){return e.capability!==void 0&&e.access!==void 0&&m("NATIVE_ROUTE_ACCESS_CONFLICT",`${t}/access`),e.capability!==void 0?{capability:me(e.capability,`${t}/capability`,o)}:e.access===void 0?{}:{access:On(e.access,`${t}/access`,o)}}function On(e,t,o){let n=N(e,t);C(n,["allOf","anyOf"],t,!0);let i=n.allOf===void 0?void 0:M(V(n.allOf,`${t}/allOf`,50).map((d,s)=>me(d,`${t}/allOf/${s}`,o))),r=n.anyOf===void 0?void 0:M(V(n.anyOf,`${t}/anyOf`,50).map((d,s)=>me(d,`${t}/anyOf/${s}`,o)));return(i?.length||0)+(r?.length||0)===0&&m("NATIVE_ROUTE_ACCESS_EMPTY",t),{...i===void 0?{}:{allOf:i},...r===void 0?{}:{anyOf:r}}}function ys(e){let t=new Map(ps(e).map(i=>[String(i.code),i])),o=e.workflows.definitions.map((i,r)=>{let d=`/config/workflows/definitions/${r}`,s=N(i,d);C(s,["version","definition","launch"],d,["detailRouteCode"]);let a=N(s.definition,`${d}/definition`),c=s.detailRouteCode===void 0?void 0:Os(s.detailRouteCode,`${d}/detailRouteCode`);return{code:v(a.code,`${d}/definition/code`),title:S(a.title,`${d}/definition/title`,255),version:ut(s.version,`${d}/version`),launch:dc(e,a,s.launch,`${d}/launch`,t),...c?{detailRouteCode:c}:{},definition:a}});return M(o.map(i=>i.code)).map(i=>{let r=o.filter(c=>c.code===i),d=e.workflows.activations.find(c=>c.workflowCode===i)?.definitionVersion,s=r.find(c=>c.version===d)||[...r].sort((c,f)=>f.version-c.version)[0],a=new Set;for(let c of r){let f=N(c.definition.nodes,"/config/workflows/definitions/nodes");for(let u of Object.values(f)){let p=N(u,"/config/workflows/definitions/nodes/*");if(p.kind==="approval")for(let _ of V(p.allowedOperations||[],"/config/workflows/definitions/nodes/*/allowedOperations",20))a.add(_)}}return{code:i,title:s.title,acceptedCommandDeactivationPolicy:s.definition.acceptedCommandDeactivationPolicy,subject:s.definition.subject,launch:s.launch,...["standalone","hidden-handoff"].includes(s.launch.mode)&&!s.launch.submission?{processOperationCode:`openxiangda.workflow.${i}.submit`}:{},...s.detailRouteCode?{detailRouteCode:s.detailRouteCode}:{},definitionVersions:cs(r.map(c=>c.version)),bindingVersions:cs(e.workflows.bindings.map((c,f)=>{let u=`/config/workflows/bindings/${f}`,p=N(c,u),_=N(p.binding,`${u}/binding`);return{code:v(_.workflowCode,`${u}/binding/workflowCode`),version:ut(p.version,`${u}/version`)}}).filter(c=>c.code===i).map(c=>c.version)),providerCodes:M(e.workflows.providers.map((c,f)=>v(N(c,`/config/workflows/providers/${f}`).code,`/config/workflows/providers/${f}/code`))),allowedOperations:[...a].sort(Ie),editableParameterCodes:M(e.workflows.editableParameters.map((c,f)=>{let u=`/config/workflows/editableParameters/${f}`,p=N(c,u);return{code:v(p.code,`${u}/code`),workflowCode:v(p.workflowCode,`${u}/workflowCode`)}}).filter(c=>c.workflowCode===i).map(c=>c.code))}})}function bs(e,t){let o=N(e,t);C(o,["mode"],t,["submission"]);let n=S(o.mode,`${t}/mode`,32);return["standalone","custom-page","hidden-handoff","work-center-only"].includes(n)||m("NATIVE_WORKFLOW_LAUNCH_MODE_INVALID",`${t}/mode`),{mode:n,...o.submission===void 0?{}:{submission:N(o.submission,`${t}/submission`)}}}function dc(e,t,o,n,i){let r=bs(o,n);if(!r.submission)return{mode:r.mode};["standalone","hidden-handoff"].includes(r.mode)||m("NATIVE_WORKFLOW_NAMED_OPERATION_SUBMISSION_INVALID",`${n}/submission`);let d=N(r.submission,`${n}/submission`);C(d,["kind"],`${n}/submission`,["create","existing","context"]),F(d.kind,"named-operation",`${n}/submission/kind`);let s=n.endsWith("/launch")?n.slice(0,-7):n,a=N(t.subject,`${s}/definition/subject`),c=H(a.resourceCode,`${s}/definition/subject/resourceCode`),f=e.data.resources.findIndex(y=>y.code===c),u=e.data.resources[f];(f<0||!u)&&m("NATIVE_WORKFLOW_SUBJECT_RESOURCE_MISSING",`${s}/definition/subject/resourceCode`);let p=new Set(N(u.schema,`/config/data/resources/${f}/schema`).fields.map(y=>String(y.code))),_=new Map(e.backend.operations.map(y=>[String(y.code),y])),E=(y,R)=>{let h=`${n}/submission/${R}`,$=N(y,h);C($,["operationCode","inputs","output"],h);let w=v($.operationCode,`${h}/operationCode`),j=_.get(w),L=i.get(w),Q=L?.platformAccess?.workflow?.codes;(!j||!L||L.method!=="POST"||!Array.isArray(Q)||!Q.includes(t.code))&&m("NATIVE_WORKFLOW_NAMED_OPERATION_INVALID",h);let ee=N(j.requestSchema,`${h}/operation/requestSchema`),Y=N(ee.properties,`${h}/operation/requestSchema/properties`),ge=new Set(ee.required===void 0?[]:V(ee.required,`${h}/operation/requestSchema/required`,205)),oe=N($.inputs,`${h}/inputs`),P=Object.entries(oe);(!P.length||P.length>205)&&m("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${h}/inputs`);let U=new Set,x=new Map,q={},z=L.platformAccess?.ownedSubject;z&&(R!=="create"||z.resourceCode!==c)&&m("NATIVE_WORKFLOW_OWNED_SUBJECT_LAUNCH_MISMATCH",h);for(let[J,Ze]of P){(!Jr.test(J)||!Object.prototype.hasOwnProperty.call(Y,J))&&m("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${h}/inputs/${J}`);let We=`${h}/inputs/${J}`,Cn=N(Ze,We),Ue=S(Cn.source,`${We}/source`,32);if(["field","idempotency-key","current-user-reference","subject-id","subject-revision","requested-at"].includes(Ue)||m("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",We),C(Cn,["source"],We,Ue==="field"?["fieldCode"]:!1),x.set(Ue,(x.get(Ue)||0)+1),Ue==="field"){let Qe=G(Cn.fieldCode,`${We}/fieldCode`);(U.has(Qe)||!p.has(Qe))&&m("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${We}/fieldCode`),U.add(Qe),u.schema.fields.find(hn=>hn.code===Qe)?.type==="subtable"&&(!z||!z.subtables.some(hn=>hn.fieldCode===Qe))&&m("NATIVE_WORKFLOW_OWNED_SUBJECT_LAUNCH_REQUIRED",We),q[J]={source:Ue,fieldCode:Qe}}else q[J]={source:Ue}}([...ge].some(J=>!(J in oe))||(x.get("idempotency-key")||0)!==1||!P.some(([J,Ze])=>N(Ze,`${h}/inputs/${J}`).source==="idempotency-key"&&ge.has(J))||R==="create"&&((x.get("subject-id")||0)>0||(x.get("subject-revision")||0)>0)||R==="existing"&&((x.get("subject-id")||0)!==1||(x.get("subject-revision")||0)!==1))&&m("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${h}/inputs`);let Ae=N($.output,`${h}/output`);C(Ae,["subjectId"],`${h}/output`,["subjectRevision","processCommand"]);let Ne=N(N(j.responseSchema,`${h}/operation/responseSchema`).properties,`${h}/operation/responseSchema/properties`);for(let J of["subjectId","subjectRevision","processCommand"]){if(Ae[J]===void 0)continue;let Ze=S(Ae[J],`${h}/output/${J}`,128);(!Jr.test(Ze)||!Object.prototype.hasOwnProperty.call(Ne,Ze))&&m("NATIVE_WORKFLOW_NAMED_OPERATION_OUTPUT_INVALID",`${h}/output/${J}`)}return{operationCode:w,method:"POST",path:L.path,requiredCapability:L.requiredCapability,requestSchemaDigest:L.requestSchemaDigest,responseSchemaDigest:L.responseSchemaDigest,inputs:q,output:{...Ae},fieldCodes:U}},A=d.create===void 0?void 0:E(d.create,"create"),O=d.existing===void 0?void 0:E(d.existing,"existing");!A&&!O&&m("NATIVE_WORKFLOW_NAMED_OPERATION_SUBMISSION_INVALID",`${n}/submission`);let b=new Set([...A?.fieldCodes||[],...O?.fieldCodes||[]]),g=d.context===void 0?[]:D(d.context,`${n}/submission/context`,16),I=new Set,T=g.map((y,R)=>{let h=`${n}/submission/context/${R}`,$=N(y,h);C($,["queryParameter","fieldCode"],h);let w=S($.queryParameter,`${h}/queryParameter`,64),j=G($.fieldCode,`${h}/fieldCode`);return(!/^[A-Za-z][A-Za-z0-9]{0,63}$/.test(w)||I.has(w)||!b.has(j))&&m("NATIVE_WORKFLOW_LAUNCH_CONTEXT_INVALID",h),I.add(w),{queryParameter:w,fieldCode:j}}),l=y=>{let{fieldCodes:R,...h}=y;return h};return{mode:r.mode,submission:{kind:"named-operation",...A?{create:l(A)}:{},...O?{existing:l(O)}:{},context:T}}}function Os(e,t){let o=N(e,t);C(o,["desktop","mobile"],t);let n=v(o.desktop,`${t}/desktop`),i=v(o.mobile,`${t}/mobile`);return n===i&&m("NATIVE_WORKFLOW_DETAIL_ROUTE_DUPLICATE",t),{desktop:n,mobile:i}}function cc(e,t){let o=new Set(t.map(f=>f.code)),n=new Map;e.data.resources.forEach((f,u)=>{let p=`/config/data/resources/${u}`,_=N(f,p);if(_.recordDeletion!==void 0){let O=`${p}/recordDeletion/delete`;for(let b of _.recordDeletion.delete)me(b,O,e.appCode),o.has(b)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",O)}if(_.recordComments!==void 0)for(let O of["read","create"]){let b=`${p}/recordComments/${O}`;for(let g of _.recordComments[O])me(g,b,e.appCode),o.has(g)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",b)}if(_.recordPrint!==void 0){let O=`${p}/recordPrint/read`;for(let b of _.recordPrint.read)me(b,O,e.appCode),o.has(b)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",O)}if(_.workflowHistory!==void 0){let O=`${p}/workflowHistory/read`;for(let b of _.workflowHistory.read)me(b,O,e.appCode),o.has(b)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",O)}for(let[O,b]of Object.entries(_.fieldPolicies||{})){if(!_t(O))continue;let g=`${p}/fieldPolicies/${O}/read`,I=N(b,`${p}/fieldPolicies/${O}`);for(let T of V(I.read||[],g,2e3))o.has(T)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",g)}let E=_.surface===void 0?{}:N(_.surface,`${p}/surface`);if(["native","queued-command"].includes(E.mutationOwner||"native"))return;let A=N(_.capabilities,`${p}/capabilities`);for(let O of["create","update","delete"])O==="delete"&&Array.isArray(_.recordDeletion?.delete)&&_.recordDeletion.delete.length>0||n.set(String(A[O]),O)});let i=new Set;for(let[f,u]of e.authz.roles.entries()){let p=`/config/authz/roles/${f}`,_=N(u,p);C(_,["code","name","description","capabilities"],p,!0);let E=v(_.code,`${p}/code`);i.has(E)&&m("NATIVE_ROLE_DUPLICATE",`${p}/code`),i.add(E),S(_.name,`${p}/name`,255);let A=V(_.capabilities,`${p}/capabilities`,2e3);for(let[O,b]of A.entries())n.has(b)&&m("NATIVE_DATA_SURFACE_MUTATION_GRANT_FORBIDDEN",`${p}/capabilities/${O}`,{operation:n.get(b)}),o.has(b)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",`${p}/capabilities`)}let r=e.authz.authenticatedUserRoleCode===void 0?"":v(e.authz.authenticatedUserRoleCode,"/config/authz/authenticatedUserRoleCode");r&&!i.has(r)&&m("NATIVE_AUTHENTICATED_USER_ROLE_REFERENCE_MISSING","/config/authz/authenticatedUserRoleCode");let d=new Set,s=0;for(let[f,u]of e.perspectives.entries()){let p=`/config/perspectives/${f}`,_=N(u,p);C(_,["code","name","description","roleCodes","capabilityCodes","default"],p,!0);let E=v(_.code,`${p}/code`);d.has(E)&&m("NATIVE_PERSPECTIVE_DUPLICATE",`${p}/code`),d.add(E),S(_.name,`${p}/name`,255);let A=V(_.roleCodes,`${p}/roleCodes`,20);A.length<1&&m("NATIVE_PERSPECTIVE_ROLE_REQUIRED",`${p}/roleCodes`),A.forEach((g,I)=>{i.has(g)||m("NATIVE_PERSPECTIVE_ROLE_MISSING",`${p}/roleCodes/${I}`)});let O=M(e.authz.roles.filter(g=>A.includes(g.code)).flatMap(g=>g.capabilities)),b=V(_.capabilityCodes,`${p}/capabilityCodes`,2e3);X(O)!==X(b)&&m("NATIVE_PERSPECTIVE_CAPABILITY_PROJECTION_MISMATCH",`${p}/capabilityCodes`),_.default===!0?s+=1:_.default!==void 0&&m("NATIVE_PERSPECTIVE_DEFAULT_INVALID",`${p}/default`)}s>1&&m("NATIVE_PERSPECTIVE_DEFAULT_DUPLICATE","/config/perspectives");for(let[f,u]of e.backend.operations.entries()){let p=N(u,`/config/backend/operations/${f}`);o.has(p.capability)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",`/config/backend/operations/${f}/capability`)}let a=new Set,c=new Set;for(let[f,u]of e.frontend.routes.entries()){let p=`/config/frontend/routes/${f}`,_=N(u,p),E=v(_.code,`${p}/code`);a.has(E)&&m("NATIVE_ROUTE_DUPLICATE",`${p}/code`),a.add(E);let A=Oe(_.path,`${p}/path`);c.has(A)&&m("NATIVE_ROUTE_PATH_DUPLICATE",`${p}/path`),c.add(A);let O=Ko(_,p,e.appCode);O.capability&&!o.has(O.capability)&&m("NATIVE_CAPABILITY_REFERENCE_MISSING",`${p}/capability`);let b=_.access===void 0?void 0:N(_.access,`${p}/access`);for(let g of["allOf","anyOf"]){let I=b?.[g]===void 0?[]:D(b[g],`${p}/access/${g}`,50);for(let[T,l]of I.entries()){let y=me(l,`${p}/access/${g}/${T}`,e.appCode);o.has(y)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",`${p}/access/${g}/${T}`)}}}if(e.frontend.admin.access!==void 0){let f=On(e.frontend.admin.access,"/config/frontend/admin/access",e.appCode);for(let u of["allOf","anyOf"])for(let[p,_]of(f[u]||[]).entries())o.has(_)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",`/config/frontend/admin/access/${u}/${p}`)}for(let[f,u]of e.frontend.routes.entries()){let p=N(u,`/config/frontend/routes/${f}`);p.parentCode&&!a.has(p.parentCode)&&m("NATIVE_ROUTE_PARENT_MISSING",`/config/frontend/routes/${f}/parentCode`)}}function lc(e){let t=new Set(e.authz.roles.map(c=>String(c.code))),o=e.authz.authenticatedUserRoleCode===void 0?"":v(e.authz.authenticatedUserRoleCode,"/config/authz/authenticatedUserRoleCode"),n=new Map(e.authz.scopeDimensions.map(c=>[String(c.code),{valueType:c.valueType==="uuid"?"uuid":"string",...c.valueSource?.resourceCode?{valueSourceResourceCode:String(c.valueSource.resourceCode)}:{}}])),i=new Set(n.keys()),r=new Map(e.data.resources.map((c,f)=>{let u=Ye(c,`/config/data/resources/${f}`,e.appCode);return[u.code,new Map(u.schema.fields.map(p=>[String(p.code),p]))]}));for(let[c,f]of e.authz.scopeDimensions.entries()){let u=`/config/authz/scopeDimensions/${c}`,p=N(f,u);if(C(p,["code","name","resourceCode","valueType","hierarchyMode","valueSource"],u,!0),p.valueSource===void 0)continue;let _=N(p.valueSource,`${u}/valueSource`);C(_,["kind","resourceCode","labelField","enabledField"],`${u}/valueSource`,!0),_.kind!=="native_resource"&&m("NATIVE_SCOPE_VALUE_SOURCE_KIND_INVALID",`${u}/valueSource/kind`),p.valueType!=="uuid"&&m("NATIVE_SCOPE_VALUE_SOURCE_TYPE_INVALID",`${u}/valueType`);let E=H(_.resourceCode,`${u}/valueSource/resourceCode`),A=r.get(E);A||m("NATIVE_SCOPE_VALUE_SOURCE_RESOURCE_MISSING",`${u}/valueSource/resourceCode`);let O=G(_.labelField,`${u}/valueSource/labelField`);if(["text.short","text.long"].includes(String(A.get(O)?.type||""))||m("NATIVE_SCOPE_VALUE_SOURCE_LABEL_FIELD_INVALID",`${u}/valueSource/labelField`),_.enabledField!==void 0){let b=G(_.enabledField,`${u}/valueSource/enabledField`);A.get(b)?.type!=="boolean"&&m("NATIVE_SCOPE_VALUE_SOURCE_ENABLED_FIELD_INVALID",`${u}/valueSource/enabledField`)}}let d=new Set,s=new Set;for(let[c,f]of e.authz.scopeSources.entries()){let u=`/config/authz/scopeSources/${c}`,p=N(f,u);C(p,["code","name","resourceCode","subject","grants","operationField","enabledField","effectiveFromField","effectiveToField","failureMode"],u,!0);let _=v(p.code,`${u}/code`);d.has(_)&&m("NATIVE_SCOPE_SOURCE_DUPLICATE",`${u}/code`),d.add(_),S(p.name,`${u}/name`,255);let E=H(p.resourceCode,`${u}/resourceCode`),A=r.get(E);A||m("NATIVE_SCOPE_SOURCE_RESOURCE_MISSING",`${u}/resourceCode`);let O=N(p.subject,`${u}/subject`),b=S(O.type,`${u}/subject/type`,32);C(O,b==="role_membership"?["type","userIdField","roleCode"]:["type","userIdField"],`${u}/subject`),["user","role_membership"].includes(b)||m("NATIVE_SCOPE_SOURCE_SUBJECT_INVALID",`${u}/subject/type`);let g=It(O.userIdField,A);so(g)||m("NATIVE_SCOPE_SOURCE_SUBJECT_PATH_INVALID",`${u}/subject/userIdField`),b==="role_membership"&&!t.has(String(O.roleCode))&&m("NATIVE_ROLE_REFERENCE_MISSING",`${u}/subject/roleCode`);let I=new Set;for(let[T,l]of D(p.grants,`${u}/grants`,100).entries()){let y=`${u}/grants/${T}`,R=N(l,y);C(R,["dimensionCode","valueField","parentValueField"],y,!0);let h=v(R.dimensionCode,`${y}/dimensionCode`);(!i.has(h)||I.has(h))&&m("NATIVE_SCOPE_SOURCE_DIMENSION_INVALID",`${y}/dimensionCode`),I.add(h),p.failureMode==="last_known_good"&&s.add(h);for(let $ of["valueField","parentValueField"]){if(R[$]===void 0)continue;let w=It(R[$],A);Pi(w,n.get(h),r)||m("NATIVE_SCOPE_SOURCE_GRANT_PATH_INVALID",`${y}/${$}`)}}I.size===0&&m("NATIVE_SCOPE_SOURCE_GRANT_REQUIRED",`${u}/grants`),["strict","last_known_good"].includes(p.failureMode)||m("NATIVE_SCOPE_SOURCE_FAILURE_MODE_INVALID",`${u}/failureMode`);for(let T of["operationField","enabledField","effectiveFromField","effectiveToField"]){if(p[T]===void 0)continue;let l=G(p[T],`${u}/${T}`);A.has(l)||m("NATIVE_SCOPE_SOURCE_FIELD_MISSING",`${u}/${T}`)}}fc(e,t,r,o);let a=new Set;for(let[c,f]of e.authz.dataPolicies.entries()){let u=`/config/authz/dataPolicies/${c}`,p=N(f,u);C(p,["code","name","resourceCode","unrestrictedRoleCodes","publicRead","operations","matchMode","rules","readExpression","writeBoundary"],u,!0);let _=v(p.code,`${u}/code`);a.has(_)&&m("NATIVE_DATA_POLICY_DUPLICATE",`${u}/code`),a.add(_);let E=p.readExpression!==void 0,A=V(p.operations||[],`${u}/operations`,4);p.operations!==void 0&&(A.length===0||A.some(l=>!["read","create","update","delete"].includes(l)))&&m("NATIVE_DATA_POLICY_OPERATIONS_INVALID",`${u}/operations`),["AND","OR"].includes(p.matchMode)||m("NATIVE_DATA_POLICY_MATCH_MODE_INVALID",`${u}/matchMode`),E&&p.operations!==void 0&&m("NATIVE_DATA_POLICY_READ_EXPRESSION_OPERATIONS_FORBIDDEN",`${u}/operations`);let O=e.data.resources.find(l=>l.dataPolicyCode===_),b=p.resourceCode||O?.code,g=b?r.get(H(b,`${u}/resourceCode`)):void 0;if(E&&!g&&m("NATIVE_DATA_POLICY_RESOURCE_MISSING",`${u}/resourceCode`),p.publicRead!==void 0){try{let l=e.authz.roles.find(y=>y.code===o);qi({policy:p,resource:e.data.resources.find(y=>y.code===b),baselineRoleCode:o,baselineCapabilities:l?.capabilities||[],baselineDeniedCapabilities:l?.deniedCapabilities||[],pointer:u})}catch(l){if(!(l instanceof Nt))throw l;m(l.code,l.pointer)}(p.unrestrictedRoleCodes||[]).includes(o)||m("AUTHENTICATED_PUBLIC_READ_CANONICAL_BASELINE_MISSING",`${u}/unrestrictedRoleCodes`)}else o&&(p.unrestrictedRoleCodes||[]).includes(o)&&m("NATIVE_DATA_POLICY_BASELINE_UNRESTRICTED",`${u}/unrestrictedRoleCodes`);let I=V(p.unrestrictedRoleCodes||[],`${u}/unrestrictedRoleCodes`,100);p.unrestrictedRoleCodes!==void 0&&I.length===0&&m("NATIVE_DATA_POLICY_UNRESTRICTED_ROLES_INVALID",`${u}/unrestrictedRoleCodes`);for(let l of I)t.has(l)||m("NATIVE_ROLE_REFERENCE_MISSING",`${u}/unrestrictedRoleCodes`);let T;try{let l=D(p.rules,`${u}/rules`,100).map((y,R)=>({rule:N(y,`${u}/rules/${R}`),pointer:`${u}/rules/${R}`}));l.length===0?(!E||p.matchMode!=="AND"||p.writeBoundary!=="capability_only")&&m("NATIVE_DATA_POLICY_WRITE_BOUNDARY_REQUIRED",u):p.writeBoundary!==void 0&&m("NATIVE_DATA_POLICY_WRITE_BOUNDARY_INVALID",`${u}/writeBoundary`),T=[...l],E&&(T.push(...st(p.readExpression,`${u}/readExpression`)),Vi(p.readExpression,`${u}/readExpression`))}catch(l){throw l instanceof Ot&&m(l.code,l.pointer),l}for(let{rule:l,pointer:y}of T){if(C(l,["parentRead","subject","dimensionCode","relationCode","resourceCode","field","roleCodes","operation","valuePath","emptyMatchesAll","operator","value","operand"],y,!0),l.parentRead!==void 0){for(let Y of V(l.roleCodes||[],`${y}/roleCodes`,100))t.has(Y)||m("NATIVE_ROLE_REFERENCE_MISSING",`${y}/roleCodes`);continue}let R=G(l.field,`${y}/field`),h=g?.get(R);E&&!h&&m("NATIVE_DATA_POLICY_FIELD_MISSING",`${y}/field`);for(let Y of V(l.roleCodes||[],`${y}/roleCodes`,100))t.has(Y)||m("NATIVE_ROLE_REFERENCE_MISSING",`${y}/roleCodes`);let $=String(l.operator||""),w=l.operand==="db_now",j=["is_null","is_not_null"].includes($),L=["eq","not_eq","in","not_in"].includes($),Q=!w&&(l.operator!==void 0||l.value!==void 0);if([l.subject==="current_user"?"current_user":"",typeof l.dimensionCode=="string"?"dimension":"",typeof l.relationCode=="string"?"relationship":"",Q?"constant":"",w?"db_now":""].filter(Boolean).length!==1&&m("NATIVE_DATA_POLICY_RULE_SOURCE_INVALID",y),l.subject!==void 0&&l.subject!=="current_user"&&m("NATIVE_DATA_POLICY_SUBJECT_INVALID",`${y}/subject`),Q){if(!L&&!j&&m("NATIVE_DATA_POLICY_OPERATOR_INVALID",`${y}/operator`),["in","not_in"].includes($)){let Y=D(l.value,`${y}/value`,100).map((ge,oe)=>S(ge,`${y}/value/${oe}`,2048));(Y.length===0||new Set(Y).size!==Y.length)&&m("NATIVE_DATA_POLICY_VALUE_INVALID",`${y}/value`)}else["eq","not_eq"].includes($)?S(l.value,`${y}/value`,2048):(l.value!==void 0||l.operand!==void 0)&&m("NATIVE_DATA_POLICY_VALUE_INVALID",`${y}/value`);for(let Y of["operation","valuePath","emptyMatchesAll","resourceCode","operand"])l[Y]!==void 0&&m("NATIVE_DATA_POLICY_CONSTANT_RULE_INVALID",`${y}/${Y}`)}if(w){(!["lt","lte","gt","gte"].includes($)||l.value!==void 0||h?.type!=="datetime")&&m("NATIVE_DATA_POLICY_DB_NOW_INVALID",y);for(let Y of["operation","valuePath","emptyMatchesAll","resourceCode","value"])l[Y]!==void 0&&m("NATIVE_DATA_POLICY_DB_NOW_INVALID",`${y}/${Y}`)}l.dimensionCode&&!i.has(l.dimensionCode)&&m("NATIVE_SCOPE_DIMENSION_MISSING",`${y}/dimensionCode`),s.has(String(l.dimensionCode||""))&&l.operation!=="read"&&m("NATIVE_SCOPE_SOURCE_LAST_KNOWN_GOOD_UNSAFE",`${y}/operation`)}}try{ji(e.data.resources,e.authz.dataPolicies)}catch(c){throw c instanceof ue&&m(c.code,c.pointer),c}for(let[c,f]of e.data.resources.entries()){let u=N(f,`/config/data/resources/${c}`);u.dataPolicyCode&&!a.has(u.dataPolicyCode)&&m("NATIVE_DATA_POLICY_REFERENCE_MISSING",`/config/data/resources/${c}/dataPolicyCode`)}}function uc(e){try{ui(e.data.resources,"/config/data/resources"),e.data.resources.forEach((t,o)=>ni(t.schema.fields,new Set(e.authz.roles.map(n=>n.code)),new Set(e.authz.scopeDimensions.map(n=>n.code)),`/config/data/resources/${o}/schema/fields`))}catch(t){throw(t instanceof Re||t instanceof Me)&&m(t.code,t.pointer),t}}function fc(e,t,o,n){let i=new Set;for(let[r,d]of e.authz.roleMembershipSources.entries()){let s=`/config/authz/roleMembershipSources/${r}`,a=N(d,s);C(a,["code","name","resourceCode","userIdField","roleCode","enabledField","effectiveFromField","effectiveToField","failureMode"],s,!0);let c=v(a.code,`${s}/code`);c.length>100&&m("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_CODE_INVALID",`${s}/code`),i.has(c)&&m("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_DUPLICATE",`${s}/code`),i.add(c),S(a.name,`${s}/name`,255);let f=os(a.resourceCode,`${s}/resourceCode`,o);is(a.userIdField,`${s}/userIdField`,f),t.has(String(a.roleCode||""))||m("NATIVE_ROLE_REFERENCE_MISSING",`${s}/roleCode`),n&&a.roleCode===n&&m("NATIVE_AUTHENTICATED_USER_ROLE_SOURCE_CONFLICT",`${s}/roleCode`),rs(a,s,f)}for(let[r,d]of e.authz.relationshipGrantSources.entries()){let s=`/config/authz/relationshipGrantSources/${r}`,a=N(d,s);C(a,["code","name","resourceCode","subject","relationCode","targetResourceCode","resourceIdField","operations","enabledField","effectiveFromField","effectiveToField","failureMode"],s,!0);let c=v(a.code,`${s}/code`);c.length>100&&m("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_CODE_INVALID",`${s}/code`),i.has(c)&&m("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_DUPLICATE",`${s}/code`),i.add(c),S(a.name,`${s}/name`,255);let f=os(a.resourceCode,`${s}/resourceCode`,o),u=N(a.subject,`${s}/subject`),p=S(u.type,`${s}/subject/type`,32);C(u,p==="role_membership"?["type","userIdField","roleCode"]:["type","userIdField"],`${s}/subject`),["user","role_membership"].includes(p)||m("NATIVE_AUTHORIZATION_PROJECTION_SUBJECT_INVALID",`${s}/subject/type`),is(u.userIdField,`${s}/subject/userIdField`,f),p==="role_membership"&&!t.has(String(u.roleCode||""))&&m("NATIVE_ROLE_REFERENCE_MISSING",`${s}/subject/roleCode`),v(a.relationCode,`${s}/relationCode`);let _=H(a.targetResourceCode,`${s}/targetResourceCode`);o.has(_)||m("NATIVE_AUTHORIZATION_PROJECTION_TARGET_RESOURCE_MISSING",`${s}/targetResourceCode`);let E=It(a.resourceIdField,f),A=E?.field.type==="resource-ref.single"&&E.valuePath==="value"&&E.field.source?.resourceCode===_;(a.resourceIdField==="id"?_!==String(a.resourceCode):!A)&&m("NATIVE_AUTHORIZATION_PROJECTION_RESOURCE_ID_FIELD_INVALID",`${s}/resourceIdField`);let O=V(a.operations,`${s}/operations`,20);(O.length===0||O.some(b=>b.length>64||!/^[A-Za-z0-9][A-Za-z0-9:._*-]{0,63}$/.test(b)))&&m("NATIVE_AUTHORIZATION_PROJECTION_OPERATIONS_INVALID",`${s}/operations`),rs(a,s,f)}}function os(e,t,o){let n=H(e,t),i=o.get(n);return i||m("NATIVE_AUTHORIZATION_PROJECTION_RESOURCE_MISSING",t),i}function is(e,t,o){let n=It(e,o);so(n)||m("NATIVE_AUTHORIZATION_PROJECTION_USER_FIELD_INVALID",t)}function rs(e,t,o){if(e.failureMode!=="strict"&&m("NATIVE_AUTHORIZATION_PROJECTION_FAILURE_MODE_INVALID",`${t}/failureMode`),e.enabledField!==void 0){let n=G(e.enabledField,`${t}/enabledField`);o.get(n)?.type!=="boolean"&&m("NATIVE_AUTHORIZATION_PROJECTION_ENABLED_FIELD_INVALID",`${t}/enabledField`)}for(let n of["effectiveFromField","effectiveToField"]){if(e[n]===void 0)continue;let i=G(e[n],`${t}/${n}`);["date","datetime"].includes(String(o.get(i)?.type))||m("NATIVE_AUTHORIZATION_PROJECTION_EFFECTIVE_FIELD_INVALID",`${t}/${n}`)}}function pc(e){let t=new Set,o=new Set;e.forEach((n,i)=>{let r=`/config/backend/secrets/${i}`,d=N(n,r);C(d,["name","env","description","required","exposure"],r,!0);let s=S(d.name,`${r}/name`,128),a=S(d.env,`${r}/env`,128);pd.test(s)||m("NATIVE_SECRET_NAME_INVALID",`${r}/name`),(!md.test(a)||a.startsWith("OPENXIANGDA_")||["NODE_ENV","PORT"].includes(a))&&m("NATIVE_SECRET_ENV_INVALID",`${r}/env`),t.has(s)&&m("NATIVE_SECRET_NAME_DUPLICATE",`${r}/name`),o.has(a)&&m("NATIVE_SECRET_ENV_DUPLICATE",`${r}/env`),t.add(s),o.add(a),F(d.exposure,"active_only",`${r}/exposure`),d.required!==void 0&&ft(d.required,`${r}/required`),d.description!==void 0&&Go(d.description,`${r}/description`,2e3)})}function mc(e){let t=new Set,o=new Map,n=new Map(e.data.resources.map(_=>[String(_.code),_])),i=new Map(e.frontend.routes.map((_,E)=>{let A=N(_,`/config/frontend/routes/${E}`);return[v(A.code,`/config/frontend/routes/${E}/code`),A]}));for(let[_,E]of e.workflows.definitions.entries()){let A=`/config/workflows/definitions/${_}`,O=N(E,A);if(C(O,["version","definition","launch"],A,["detailRouteCode"]),bs(O.launch,`${A}/launch`),O.detailRouteCode!==void 0){let w=Os(O.detailRouteCode,`${A}/detailRouteCode`);for(let[j,L,Q]of[["desktop",w.desktop,["admin","user"]],["mobile",w.mobile,["user"]]]){let ee=`${A}/detailRouteCode/${j}`,Y=i.get(L);Y||m("NATIVE_WORKFLOW_DETAIL_ROUTE_MISSING",ee),Q.some(P=>P===Y.surface)||m("NATIVE_WORKFLOW_DETAIL_ROUTE_SURFACE_INVALID",ee);let ge=Oe(Y.path,ee),oe=[...ge.matchAll(/:([A-Za-z][A-Za-z0-9_]*)/g)].map(P=>P[1]);(ge.includes("*")||oe.length!==1||oe[0]!=="instanceId")&&m("NATIVE_WORKFLOW_DETAIL_ROUTE_PATH_INVALID",ee)}}let b=N(O.definition,`${A}/definition`),g=`${b.code}:${ut(O.version,`${A}/version`)}`;t.has(g)&&m("NATIVE_WORKFLOW_DEFINITION_DUPLICATE",A),t.add(g),gc(b,`${A}/definition`);let I=Ro(b);I.length&&m(I[0],`${A}/definition/launchPreflight`);let T=wr(b);T.length&&m(T[0],`${A}/definition/approvedDelegation`);let l=Rr(b,e.backend.operations);l.length&&m(l[0],`${A}/definition/commandHandlers`),_c(b.subject,n,`${A}/definition/subject`);let y=b.commandHandlers?.resubmit?.derivedSubjectFields||[],R=n.get(b.subject.resourceCode);for(let w of y){let j=R?.schema.fields.find(L=>L.code===w);(!j||j.system===!0||R?.surface?.fields?.[w]?.system===!0)&&m("WORKFLOW_CORRECTION_DERIVED_SUBJECT_FIELDS_INVALID",`${A}/definition/commandHandlers/resubmit/derivedSubjectFields`)}let h=un(b,new Map((n.get(b.subject.resourceCode)?.schema.fields||[]).map(w=>[w.code,{...n.get(b.subject.resourceCode)?.surface?.fields?.[w.code],...w,system:["id","revision","createdAt","updatedAt","createdBy","updatedBy"].includes(w.code)}])),new Map([...n].map(([w,j])=>[w,new Map(j.schema.fields.map(L=>[L.code,{...j.surface?.fields?.[L.code],...L,system:["id","revision","createdAt","updatedAt","createdBy","updatedBy"].includes(L.code)}]))])),jt(n.get(b.subject.resourceCode)?.schema||{}));h.length&&m(h[0],`${A}/definition/taskPages`);let $=tr(b,{appCode:e.appCode,capabilities:e.authz.capabilities.map(w=>w.code),fields:new Map((n.get(b.subject.resourceCode)?.schema.fields||[]).map(w=>[w.code,w]))});$.length&&m("NATIVE_WORKFLOW_INSTANCE_COMMAND_POLICY_INVALID",`${A}/definition/instanceCommands`,{errors:$}),b.title===b.code&&m("NATIVE_WORKFLOW_USER_TITLE_REQUIRED",`${A}/definition/title`),o.set(g,b)}let r=new Set,d=new Map;for(let[_,E]of e.workflows.bindings.entries()){let A=N(E,`/config/workflows/bindings/${_}`),O=N(A.binding,`/config/workflows/bindings/${_}/binding`),b=`${O.workflowCode}:${ut(A.version,`/config/workflows/bindings/${_}/version`)}`;r.has(b)&&m("NATIVE_WORKFLOW_BINDING_DUPLICATE",`/config/workflows/bindings/${_}`),r.add(b),Ac(O,`/config/workflows/bindings/${_}/binding`),d.set(b,O)}let s=new Set,a=new Map;for(let[_,E]of e.workflows.activations.entries()){let A=`/config/workflows/activations/${_}`,O=N(E,A);C(O,["workflowCode","definitionVersion","bindingVersion","acceptedCommandDeactivationPolicy"],A,["environmentKey"]);let b=v(O.workflowCode,`${A}/workflowCode`);s.has(b)&&m("NATIVE_WORKFLOW_ACTIVATION_DUPLICATE",A),s.add(b);let g=`${b}:${ut(O.definitionVersion,`${A}/definitionVersion`)}`,I=`${b}:${ut(O.bindingVersion,`${A}/bindingVersion`)}`;t.has(g)||m("NATIVE_WORKFLOW_DEFINITION_REFERENCE_MISSING",`${A}/definitionVersion`),r.has(I)||m("NATIVE_WORKFLOW_BINDING_REFERENCE_MISSING",`${A}/bindingVersion`);let T=o.get(g),l=d.get(I),y=Ro(T,l);y.length&&m(y[0],A);let R=Oo(T,l);R.length&&m(R[0],A),(!["finish-pinned","cancel-on-deactivate"].includes(O.acceptedCommandDeactivationPolicy)||O.acceptedCommandDeactivationPolicy!==T.acceptedCommandDeactivationPolicy)&&m("NATIVE_WORKFLOW_COMMAND_DEACTIVATION_POLICY_MISMATCH",`${A}/acceptedCommandDeactivationPolicy`),Ec(T,l,`/config/workflows/activations/${_}`);try{let h=n.get(T.subject.resourceCode)?.schema.fields||[];oi(T,l,new Map(h.map($=>[$.code,$])),`${A}/bindings`,new Map([...n].map(([$,w])=>[$,new Map(w.schema.fields.map(j=>[j.code,j]))])))}catch(h){throw h instanceof Me&&m(h.code,h.pointer),h}a.set(b,l)}let c=Wr([...a.values()]);c.length&&m(c[0],"/config/workflows/activations");let f=new Set;e.workflows.providers.forEach((_,E)=>{let A=`/config/workflows/providers/${E}`,O=N(_,A);C(O,["code","endpointPath","timeoutMs"],A,!0);let b=v(O.code,`${A}/code`);f.has(b)&&m("NATIVE_WORKFLOW_PROVIDER_DUPLICATE",`${A}/code`),f.add(b),Oe(O.endpointPath,`${A}/endpointPath`),O.timeoutMs!==void 0&&se(O.timeoutMs,`${A}/timeoutMs`,100,1e4)});for(let[_,E]of a.entries())for(let[A,O]of Object.entries(N(E.bindings,"/config/workflows/bindings/*/binding/bindings"))){let b=N(O,`/config/workflows/${_}/bindings/${A}`);b.provider==="application_provider"&&!f.has(b.providerCode)&&m("NATIVE_WORKFLOW_PROVIDER_REFERENCE_MISSING",`/config/workflows/${_}/bindings/${A}/providerCode`)}let u=new Set(e.authz.roles.map(_=>_.code)),p=new Set;e.workflows.editableParameters.forEach((_,E)=>{let A=`/config/workflows/editableParameters/${E}`,O=N(_,A);C(O,["code","workflowCode","bindingKey","label","valueType","required","allowedRoleCodes","allowedProviderCodes","maxItems"],A,!0);let b=v(O.code,`${A}/code`);p.has(b)&&m("NATIVE_WORKFLOW_EDITABLE_PARAMETER_DUPLICATE",`${A}/code`),p.add(b);let g=Nn(O.workflowCode,`${A}/workflowCode`),I=In(O.bindingKey,`${A}/bindingKey`),T=a.get(g);(!T||!N(T.bindings,`${A}/bindingKey`)[I])&&m("NATIVE_WORKFLOW_EDITABLE_BINDING_MISSING",`${A}/bindingKey`),S(O.label,`${A}/label`,255),["role_code","user_ids","provider_code"].includes(O.valueType)||m("NATIVE_WORKFLOW_EDITABLE_VALUE_TYPE_INVALID",`${A}/valueType`);for(let l of V(O.allowedRoleCodes||[],`${A}/allowedRoleCodes`,100))u.has(l)||m("NATIVE_ROLE_REFERENCE_MISSING",`${A}/allowedRoleCodes`);for(let l of V(O.allowedProviderCodes||[],`${A}/allowedProviderCodes`,100))f.has(l)||m("NATIVE_WORKFLOW_PROVIDER_REFERENCE_MISSING",`${A}/allowedProviderCodes`);O.required!==void 0&&ft(O.required,`${A}/required`),O.maxItems!==void 0&&se(O.maxItems,`${A}/maxItems`,1,200)})}function _c(e,t,o){let n=N(e,o);C(n,["resourceCode","factProjection"],o,["summaryFields"]);let i=H(n.resourceCode,`${o}/resourceCode`),r=t.get(i);r||m("NATIVE_WORKFLOW_SUBJECT_RESOURCE_MISSING",`${o}/resourceCode`);let d=new Set(D(N(r.schema,`${o}/resourceCode`).fields,`${o}/resourceCode`,500).map((c,f)=>G(N(c,`${o}/resourceCode/${f}`).code,`${o}/resourceCode/${f}`))),s=N(n.factProjection,`${o}/factProjection`),a=Object.entries(s);(a.length<1||a.length>64)&&m("NATIVE_WORKFLOW_SUBJECT_FACT_PROJECTION_INVALID",`${o}/factProjection`);for(let[c,f]of a){Ad.test(c)||m("NATIVE_WORKFLOW_SUBJECT_FACT_KEY_INVALID",`${o}/factProjection/${c}`);let u=G(f,`${o}/factProjection/${c}`);d.has(u)||m("NATIVE_WORKFLOW_SUBJECT_FIELD_MISSING",`${o}/factProjection/${c}`)}if(n.summaryFields!==void 0){let c=V(n.summaryFields,`${o}/summaryFields`,Ed).map((E,A)=>G(E,`${o}/summaryFields/${A}`)),f=t.get(i),u=f.surface&&typeof f.surface=="object"&&!Array.isArray(f.surface)?f.surface:{},p=u.fields&&typeof u.fields=="object"&&!Array.isArray(u.fields)?u.fields:{},_=new Map(D(N(f.schema,`${o}/resourceCode`).fields,`${o}/resourceCode`,500).map((E,A)=>{let O=N(E,`${o}/resourceCode/${A}`);return[String(O.code),O]}));for(let[E,A]of c.entries()){let O=_.get(A),b=p[A],g=String(O?.type||""),I=O?.maxLength;(!O||O.system===!0||b&&typeof b=="object"&&!Array.isArray(b)&&b.system===!0||["id","revision","created_by","updated_by","created_at","updated_at"].includes(A)||!yd.has(g)||g==="text.long"&&typeof I=="number"&&Number.isFinite(I)&&I>Id)&&m("NATIVE_WORKFLOW_SUBJECT_SUMMARY_FIELDS_INVALID",`${o}/summaryFields/${E}`)}}}function gc(e,t){C(e,["schemaVersion","code","title","subject","acceptedCommandDeactivationPolicy","startAt","inputSchema","nodes"],t,["organizationContext","instanceCommands","readability","taskPages","rejectionNotification","commandHandlers","launchPreflight","approvedDelegation"]),F(e.schemaVersion,"openxiangda.workflow-definition/v2",`${t}/schemaVersion`),Nn(e.code,`${t}/code`),S(e.title,`${t}/title`,255),["finish-pinned","cancel-on-deactivate"].includes(e.acceptedCommandDeactivationPolicy)||m("NATIVE_WORKFLOW_COMMAND_DEACTIVATION_POLICY_REQUIRED",`${t}/acceptedCommandDeactivationPolicy`);let o=N(e.nodes,`${t}/nodes`),n=Object.keys(o);(n.length===0||n.length>200)&&m("NATIVE_WORKFLOW_NODE_COUNT_INVALID",`${t}/nodes`);let i=S(e.startAt,`${t}/startAt`,128),r=lr(e);r.length&&m(r[0],`${t}/readability`);let d=Oo(e);d.length&&m(d[0],`${t}/nodes`);let s=No(e);s.length&&m(s[0],`${t}/nodes`);let a=ht(e);a.length&&m(a[0],`${t}/nodes`);let c=Or(e);c.length&&m(c[0],`${t}/nodes`);let f=Tr(e);f.length&&m(f[0],`${t}/rejectionNotification`);let u=Io(e);u.length&&m(u[0],`${t}/nodes`);let p=un(e);p.length&&m(p[0],`${t}/taskPages`);let _=on(e);_.length&&m(_[0],`${t}/nodes`),o[i]||m("NATIVE_WORKFLOW_START_NODE_MISSING",`${t}/startAt`);let E=new Map;for(let[g,I]of Object.entries(o)){let T=`${t}/nodes/${g}`,l=N(I,T);F(l.id,g,`${T}/id`),["approval","condition","end","cc","action","correction"].includes(l.kind)||m("NATIVE_WORKFLOW_NODE_KIND_INVALID",`${T}/kind`);let y=[];if(l.kind==="approval"){S(l.title,`${T}/title`,255),In(l.binding,`${T}/binding`),["single","any","all","sequence"].includes(l.mode)||m("NATIVE_WORKFLOW_APPROVAL_MODE_INVALID",`${T}/mode`),y.push(S(l.onApprove,`${T}/onApprove`,128),S(l.onReject,`${T}/onReject`,128));for(let R of V(l.returnTargets||[],`${T}/returnTargets`,200))o[R]||m("NATIVE_WORKFLOW_TARGET_MISSING",`${T}/returnTargets`);for(let R of V(l.allowedOperations||[],`${T}/allowedOperations`,20))Od.has(R)||m("NATIVE_WORKFLOW_OPERATION_INVALID",`${T}/allowedOperations`)}else if(l.kind==="correction"){let R=Sr(e);R.length&&m(R[0],T)}else if(l.kind==="action")y.push(S(l.next,`${T}/next`,128));else if(l.kind==="cc")S(l.title,`${T}/title`,255),In(l.binding,`${T}/binding`),y.push(S(l.next,`${T}/next`,128));else if(l.kind==="condition"){let R=D(l.branches,`${T}/branches`,100);R.length===0&&m("NATIVE_WORKFLOW_BRANCH_REQUIRED",`${T}/branches`),R.forEach((h,$)=>{let w=N(h,`${T}/branches/${$}`);vt(w.when,`${T}/branches/${$}/when`,0),y.push(S(w.target,`${T}/branches/${$}/target`,128))}),y.push(S(l.otherwise,`${T}/otherwise`,128))}else S(l.title,`${T}/title`,255),S(l.outcome,`${T}/outcome`,128);for(let R of y)o[R]||m("NATIVE_WORKFLOW_TARGET_MISSING",T);E.set(g,y)}let A=new Set,O=new Set,b=g=>{if(O.has(g)&&m("NATIVE_WORKFLOW_CYCLE_FORBIDDEN",`${t}/nodes/${g}`),!A.has(g)){A.add(g),O.add(g);for(let I of E.get(g)||[])b(I);O.delete(g)}};b(i);for(let g of[...A]){let I=o[g];if(I?.kind==="approval")for(let T of I.returnTargets||[])o[T]?.kind==="correction"&&A.add(T)}A.size!==n.length&&m("NATIVE_WORKFLOW_NODE_UNREACHABLE",`${t}/nodes`)}function vt(e,t,o){o>20&&m("NATIVE_WORKFLOW_EXPRESSION_DEPTH_EXCEEDED",t);let n=N(e,t),i=S(n.op,`${t}/op`,16);if(i!=="literal"){if(i==="path"){let r=S(n.path,`${t}/path`,255);(!/^[A-Za-z][A-Za-z0-9_.-]{0,254}$/.test(r)||r.split(".").some(d=>["__proto__","constructor","prototype"].includes(d)))&&m("NATIVE_WORKFLOW_EXPRESSION_PATH_INVALID",`${t}/path`);return}if(["eq","neq","gt","gte","lt","lte","in","contains"].includes(i)){vt(n.left,`${t}/left`,o+1),vt(n.right,`${t}/right`,o+1);return}if(["and","or"].includes(i)){let r=D(n.values,`${t}/values`,100);r.length===0&&m("NATIVE_WORKFLOW_EXPRESSION_EMPTY",`${t}/values`),r.forEach((d,s)=>vt(d,`${t}/values/${s}`,o+1));return}if(["not","exists"].includes(i)){vt(n.value,`${t}/value`,o+1);return}m("NATIVE_WORKFLOW_EXPRESSION_OPERATOR_INVALID",`${t}/op`)}}function Ac(e,t){F(e.schemaVersion,"openxiangda.workflow-binding/v2",`${t}/schemaVersion`),Nn(e.workflowCode,`${t}/workflowCode`);let o=N(e.bindings,`${t}/bindings`);Object.keys(o).length>200&&m("NATIVE_WORKFLOW_BINDING_LIMIT_EXCEEDED",`${t}/bindings`);for(let[n,i]of Object.entries(o)){In(n,`${t}/bindings/${n}`);let r=N(i,`${t}/bindings/${n}`),d=pr(r);d.length&&m(d[0],`${t}/bindings/${n}/selectedInputPath`);let s=an(r);s.length&&m(s[0],`${t}/bindings/${n}/roleCodes`);let a=S(r.provider,`${t}/bindings/${n}/provider`,64);if(["fixed_users","initiator","input_users","form_field_users","department_supervisor","app_role","app_role_in_scope","business_relation","previous_node_actor","initiator_select","application_provider"].includes(a)||m("NATIVE_WORKFLOW_BINDING_PROVIDER_INVALID",`${t}/bindings/${n}/provider`),a==="fixed_users"&&(Array.isArray(r.users)||m("NATIVE_WORKFLOW_BINDING_USERS_REQUIRED",`${t}/bindings/${n}/users`),D(r.users,`${t}/bindings/${n}/users`,200)),["input_users","form_field_users"].includes(a)&&S(r.inputPath,`${t}/bindings/${n}/inputPath`,255),["app_role","app_role_in_scope","initiator_select"].includes(a)&&r.roleCodes===void 0&&v(r.roleCode,`${t}/bindings/${n}/roleCode`),a==="department_supervisor"&&S(r.departmentIdFrom,`${t}/bindings/${n}/departmentIdFrom`,255),a==="application_provider"&&v(r.providerCode,`${t}/bindings/${n}/providerCode`),r.routing!==void 0){let c=fn(r.routing);c.length&&m(c[0],`${t}/bindings/${n}/routing`)}}}function Ec(e,t,o){F(t.workflowCode,e.code,`${o}/workflowCode`);let n=N(t.bindings,`${o}/bindings`);for(let[s,a]of Object.entries(n))a.provider==="fixed_users"&&!a.users.length&&!yr(e,s)&&m("NATIVE_WORKFLOW_BINDING_USERS_REQUIRED",`${o}/bindings/${s}/users`);let i=No(e,t);i.length&&m(i[0],o);let r=Io(e,t);r.length&&m(r[0],o);let d=on(e,t);d.length&&m(d[0],o);for(let[s,a]of Object.entries(N(e.nodes,`${o}/nodes`))){let c=N(a,`${o}/nodes/${s}`);["approval","cc"].includes(c.kind)&&!n[c.binding]&&m("NATIVE_WORKFLOW_BINDING_REFERENCE_MISSING",`${o}/nodes/${s}/binding`)}}function Ic(e,t,o){let n=N(t.routeManifest,"/contracts/routeManifest"),i=N(e.routeManifest,"/contracts/routeManifest"),r=new Map;for(let f of D(o.data?.resources,"/config/data/resources",B.resources)){let u=N(f,"/config/data/resources");r.set(String(u.code||""),u)}let d=new Set(D(i.routes,"/contracts/routeManifest/routes",B.routes).map(f=>String(N(f,"/contracts/routeManifest/routes").code||""))),s=[];for(let f of D(n.routes,"/contracts/routeManifest/routes",B.routes)){let u=N(f,"/contracts/routeManifest/routes"),p=String(u.kind||"");if(p!=="resource-records"&&p!=="resource-submit")continue;let _=String(u.resourceCode||""),E=r.get(_);E||m("NATIVE_ROUTE_MANIFEST_RESOURCE_UNKNOWN","/contracts/routeManifest/routes");let O=`user.${_}.${p==="resource-records"?"records":"submit"}`;F(String(u.code||""),O,"/contracts/routeManifest/routes/code");let b=p==="resource-records"?"read":"create",g=String(N(E.capabilities,"/config/data/resources/capabilities")[b]||"");for(let I of["desktop","mobile"]){let T=N(u[I],`/contracts/routeManifest/routes/${I}`),l=I==="mobile"?"/m/my/":"/my/",y=p==="resource-records"?`${l}${_}`:`${l}${_}/submit`;F(String(T.path||""),y,`/contracts/routeManifest/routes/${I}/path`),F(String(T.capability||""),g,`/contracts/routeManifest/routes/${I}/capability`),F(String(T.routeCode||""),`${O}.${I}`,`/contracts/routeManifest/routes/${I}/routeCode`)}(d.has(O)||s.some(I=>String(I.code)===O))&&m("NATIVE_ROUTE_MANIFEST_DUPLICATE","/contracts/routeManifest/routes/code"),s.push(u)}if(!s.length)return;i.routes=D([...i.routes,...s],"/contracts/routeManifest/routes",1e3).sort((f,u)=>Ie(String(N(f,"x").code||""),String(N(u,"x").code||"")));let a=String(N(n.rootEntry,"x").code||"");if(s.find(f=>String(f.code)===a&&f.kind==="resource-records")){let f=N(n.rootEntry,"x");i.rootEntry={code:a,desktop:String(f.desktop||""),mobile:String(f.mobile||"")}}i.digest=Z({schemaVersion:i.schemaVersion,appCode:i.appCode,devicePolicy:i.devicePolicy,rootEntry:i.rootEntry,authentication:i.authentication,routes:i.routes})}function Ye(e,t,o){let n=N(e,t);C(n,["schemaVersion","appCode","code","name","schema","surface","invariants","decimalReservationLifecycle","uniqueKeys","workflowHistory","recordPrint","recordComments","recordDeletion","capabilities","dataPolicyCode","fieldPolicies"],t,!0),F(n.schemaVersion,"openxiangda.data-resource/v2",`${t}/schemaVersion`),F(n.appCode,o,`${t}/appCode`);let i=H(n.code,`${t}/code`),r=S(n.name,`${t}/name`,255),d=N(n.schema,`${t}/schema`);C(d,["fields","ownedRowLimit"],`${t}/schema`,!0),d.ownedRowLimit!==void 0&&!mt(d.ownedRowLimit)&&m("NATIVE_DATA_OWNED_ROW_LIMIT_INVALID",`${t}/schema/ownedRowLimit`);let s,a,c,f;try{c=oo(n.decimalReservationLifecycle,`${t}/decimalReservationLifecycle`),s=Bn(d.fields,`${t}/schema/fields`),f=Ji(n.uniqueKeys,s,`${t}/uniqueKeys`),a=fi(n.invariants,s,`${t}/invariants`),Zn(n.surface,s,`${t}/surface`)}catch(E){throw(E instanceof Re||E instanceof Me||E instanceof rt||E instanceof Rt)&&m(E.code,E.pointer),E}if(n.recordComments!==void 0){let E=N(n.recordComments,`${t}/recordComments`);C(E,["read","create"],`${t}/recordComments`);for(let A of["read","create"]){let O=E[A];(!Array.isArray(O)||O.length>20||O.some(b=>typeof b!="string"||!b.trim())||new Set(O).size!==O.length)&&m("NATIVE_RECORD_COMMENTS_POLICY_INVALID",`${t}/recordComments/${A}`)}}if(n.recordDeletion!==void 0){let E=N(n.recordDeletion,`${t}/recordDeletion`);C(E,["delete"],`${t}/recordDeletion`);let A=E.delete;(!Array.isArray(A)||A.length>20||A.some(O=>typeof O!="string"||!O.trim())||new Set(A).size!==A.length)&&m("NATIVE_RECORD_DELETION_DELETE_INVALID",`${t}/recordDeletion/delete`)}if(n.recordPrint!==void 0){let E=N(n.recordPrint,`${t}/recordPrint`);C(E,["read"],`${t}/recordPrint`);let A=E.read;(!Array.isArray(A)||A.length>20||A.some(O=>typeof O!="string"||!O.trim())||new Set(A).size!==A.length)&&m("NATIVE_RECORD_PRINT_READ_INVALID",`${t}/recordPrint/read`)}if(n.workflowHistory!==void 0){let E=N(n.workflowHistory,`${t}/workflowHistory`);C(E,["read"],`${t}/workflowHistory`);let A=E.read;(!Array.isArray(A)||A.length>20||A.some(O=>typeof O!="string"||!O.trim())||new Set(A).size!==A.length)&&m("NATIVE_WORKFLOW_HISTORY_READ_INVALID",`${t}/workflowHistory/read`)}let u=new Set(s.map(E=>E.code)),p=N(n.capabilities,`${t}/capabilities`);C(p,["read","create","update","delete"],`${t}/capabilities`);let _=N(n.fieldPolicies,`${t}/fieldPolicies`);for(let[E,A]of Object.entries(_)){!u.has(E)&&!_t(E)&&m("NATIVE_DATA_FIELD_POLICY_FIELD_MISSING",`${t}/fieldPolicies/${E}`);let O=`${t}/fieldPolicies/${E}`,b=N(A,O);_t(E)&&(C(b,["read"],O,!0),(!Array.isArray(b.read)||b.read.length>20||b.read.some(g=>typeof g!="string"||!g.trim())||new Set(b.read).size!==b.read.length)&&m("NATIVE_DATA_AUDIT_READ_POLICY_INVALID",`${O}/read`)),C(b,["read","create","update","mask"],O,!0),b.mask!==void 0&&!["omit","null"].includes(b.mask)&&m("NATIVE_DATA_FIELD_POLICY_MASK_INVALID",`${O}/mask`)}return{...n,code:i,name:r,schema:{fields:s,...d.ownedRowLimit!==void 0?{ownedRowLimit:d.ownedRowLimit}:{}},...n.invariants===void 0?{}:{invariants:a},...c?{decimalReservationLifecycle:c}:{},...f!==void 0?{uniqueKeys:f}:{},capabilities:p,fieldPolicies:_}}function Ns(e){return[{code:`app:${e}:directory:read`,kind:"platform",name:"\u8BFB\u53D6\u53D7\u9650\u7EC4\u7EC7\u76EE\u5F55",source:"platform"},...[["app:role:read","\u67E5\u770B\u89D2\u8272\u4E0E\u6388\u6743"],["app:role:define","\u5B9A\u4E49\u624B\u5DE5\u89D2\u8272"],["app:role:assign","\u5206\u914D\u89D2\u8272\u6210\u5458"],["app:role:grant-capability","\u6388\u4E88\u89D2\u8272\u80FD\u529B"],["app:scope-grant:manage","\u7BA1\u7406\u6570\u636E\u8303\u56F4"],["app:super-admin:manage","\u7BA1\u7406\u5E94\u7528\u6700\u9AD8\u7BA1\u7406\u5458"]].map(([t,o])=>({code:t,kind:"platform",name:o,source:"platform"}))]}function ss(e,t,o,n){let i=e.toString("utf8"),r;try{r=JSON.parse(i)}catch{m(o,t)}let d=N(r,t);return X(d)!==i&&m(n,t),d}function gn(e,t,o){let n=0,i=(r,d,s)=>{if(n+=1,n>o&&m("NATIVE_ARTIFACT_NODE_LIMIT_EXCEEDED",d),s>Rd&&m("NATIVE_ARTIFACT_DEPTH_LIMIT_EXCEEDED",d),typeof r=="string"){Buffer.byteLength(r)>Lo&&m("NATIVE_ARTIFACT_STRING_LIMIT_EXCEEDED",d);return}if(Array.isArray(r)){r.forEach((a,c)=>i(a,`${d}/${c}`,s+1));return}if(!(!r||typeof r!="object"))for(let[a,c]of Object.entries(r))["__proto__","prototype","constructor"].includes(a)&&m("NATIVE_ARTIFACT_DANGEROUS_KEY",`${d}/${a}`),yc(a)&&m("NATIVE_ARTIFACT_RUNTIME_FIELD_FORBIDDEN",`${d}/${a}`),i(c,`${d}/${a}`,s+1)};i(e,t,0)}function yc(e){return["environmentKey","environmentId","secretValue","ciphertext","oauthClient","oauthClientId","oauthClientSecret","signingSecret","kubernetesNamespace","nodePort","productionUrl"].includes(e)}function lt(e){return{value:e,digest:Z(e)}}function as(e,t,o,n){typeof e!="string"&&!Buffer.isBuffer(e)&&!(e instanceof Uint8Array)&&m("NATIVE_ARTIFACT_BYTES_REQUIRED",o);let i=Buffer.isBuffer(e)?e:Buffer.from(e);return i.byteLength===0&&m("NATIVE_ARTIFACT_EMPTY",o),i.byteLength>t&&m(n,o),i}function ds(e,t,o,n){let i=yn.createHash("sha256").update(e).digest("hex");yn.timingSafeEqual(Buffer.from(i),Buffer.from(t))||m(n,o)}function N(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&m("NATIVE_OBJECT_REQUIRED",t),e}function D(e,t,o){return Array.isArray(e)||m("NATIVE_ARRAY_REQUIRED",t),e.length>o&&m("NATIVE_ARRAY_LIMIT_EXCEEDED",t),e}function V(e,t,o){let n=D(e,t,o).map((i,r)=>S(i,`${t}/${r}`,255));return new Set(n).size!==n.length&&m("NATIVE_ARRAY_DUPLICATE",t),n}function S(e,t,o){return(typeof e!="string"||e.length===0||e.length>o)&&m("NATIVE_STRING_INVALID",t),e}function Go(e,t,o){return(typeof e!="string"||e.length>o)&&m("NATIVE_STRING_INVALID",t),e}function v(e,t){let o=S(e,t,128);return cd.test(o)||m("NATIVE_CODE_INVALID",t),o}function H(e,t){let o=S(e,t,64);return ud.test(o)||m("NATIVE_RESOURCE_CODE_INVALID",t),o}function G(e,t){let o=S(e,t,63);return fd.test(o)||m("NATIVE_FIELD_CODE_INVALID",t),o}function Nn(e,t){let o=S(e,t,128);return _d.test(o)||m("NATIVE_WORKFLOW_CODE_INVALID",t),o}function In(e,t){let o=S(e,t,128);return gd.test(o)||m("NATIVE_WORKFLOW_BINDING_CODE_INVALID",t),o}function me(e,t,o){let n=S(e,t,255);return dd.test(n)||m("NATIVE_CAPABILITY_CODE_INVALID",t),!n.startsWith(`app:${o}:`)&&!Ns(o).some(i=>i.code===n)&&m("NATIVE_CAPABILITY_APP_MISMATCH",t),n}function Oe(e,t){let o=S(e,t,2048);return(!o.startsWith("/")||o.startsWith("//")||o.includes("..")||o.includes("?")||o.includes("#"))&&m("NATIVE_ABSOLUTE_PATH_INVALID",t),o}function ut(e,t){return(!Number.isInteger(e)||Number(e)<1)&&m("NATIVE_POSITIVE_INTEGER_REQUIRED",t),Number(e)}function se(e,t,o,n){return(!Number.isInteger(e)||Number(e)<o||Number(e)>n)&&m("NATIVE_INTEGER_OUT_OF_RANGE",t),Number(e)}function ft(e,t){return typeof e!="boolean"&&m("NATIVE_BOOLEAN_REQUIRED",t),e}function Uo(e,t){let o=S(e,t,64).toLowerCase();return sd.test(o)||m("NATIVE_DIGEST_INVALID",t),o}function F(e,t,o){e!==t&&m("NATIVE_VALUE_MISMATCH",o)}function C(e,t,o,n=!1){let i=new Set([...t,...Array.isArray(n)?n:[]]);for(let r of Object.keys(e))i.has(r)||m("NATIVE_PROPERTY_UNKNOWN",`${o}/${r}`);if(n!==!0)for(let r of t)Object.prototype.hasOwnProperty.call(e,r)||m("NATIVE_PROPERTY_REQUIRED",`${o}/${r}`)}function te(e,t){return[...e].sort((o,n)=>Ie(t(o),t(n)))}function M(e){return[...new Set(e)].sort(Ie)}function cs(e){return[...new Set(e)].sort((t,o)=>t-o)}function Ie(e,t){return e===t?0:e<t?-1:1}function Ts(e){return!e||typeof e!="object"||Object.isFrozen(e)||(Object.freeze(e),Object.values(e).forEach(t=>Ts(t))),e}function Mo(e,t,o){if(Vo(e,t))return o;if(Array.isArray(e)&&Array.isArray(t)){let n=Math.max(e.length,t.length);for(let i=0;i<n;i+=1)if(!Vo(e[i],t[i]))return Mo(e[i],t[i],`${o}/${i}`)}if(e&&t&&typeof e=="object"&&typeof t=="object"&&!Array.isArray(e)&&!Array.isArray(t)){let n=M([...Object.keys(e),...Object.keys(t)]);for(let i of n){let r=e[i],d=t[i];if(!Vo(r,d))return Mo(r,d,`${o}/${i}`)}}return o}function Vo(e,t){return e===void 0||t===void 0?e===t:X(e)===X(t)}function m(e,t,o={}){throw new jo(e,t,o)}var dp="openxiangda.workflow-step-data-command/v1",bc="openxiangda.workflow-step-data-resolution/v1";function cp(e,t,o=!1){let n=s=>!!s&&typeof s=="object"&&!Array.isArray(s),i=s=>typeof s=="string"&&/^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(s),r=()=>{throw new Error("WORKFLOW_STEP_DATA_RESPONSE_INVALID")};if(!n(e)||e.schemaVersion!==bc||e.executionId!==t||Object.keys(e).some(s=>!["schemaVersion","executionId","outcome","transaction"].includes(s)))return r();if(e.outcome==="not_observed"&&!Object.hasOwn(e,"transaction")&&!o)return e;let d=e.transaction;if(e.outcome!=="committed"||!n(d)||d.schemaVersion!=="openxiangda.data-transaction-result/v2"||d.idempotencyKey!==`workflow-step:${t}`||typeof d.replayed!="boolean"||!Array.isArray(d.items)||d.items.length<1||d.items.length>ri||d.evaluatedAt!==void 0&&(typeof d.evaluatedAt!="string"||!Number.isFinite(Date.parse(d.evaluatedAt))))return r();for(let[s,a]of d.items.entries()){if(!n(a)||a.index!==s)return r();if(a.operation==="emitEvent"){if(typeof a.eventType!="string"||!a.eventType||!i(a.eventId))return r()}else if(!["create","update","delete","increment"].includes(a.operation)||typeof a.resourceCode!="string"||!a.resourceCode||!i(a.id)||!Number.isSafeInteger(a.revision)||a.revision<1)return r()}return e}var up=50,fp=131072,qo=class extends Error{constructor(o){super("OPENXIANGDA_NATIVE_AUTHZ_BATCH_INPUT_INVALID");this.pointer=o}pointer;code="OPENXIANGDA_NATIVE_AUTHZ_BATCH_INPUT_INVALID";status=400};function pp(e){let t=u=>{throw new qo(u)},o=(u,p)=>((!u||typeof u!="object"||Array.isArray(u))&&t(p),u),n=(u,p,_)=>{for(let E of Object.keys(u))p.includes(E)||t(`${_}/${E}`)},i=(u,p,_)=>((typeof u!="string"||!u.trim()||u.length>p)&&t(_),u),r=(u,p)=>{let _=i(u,36,p);return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(_)||t(p),_.toLowerCase()},d=o(e,""),s;try{s=new TextEncoder().encode(JSON.stringify(d)).byteLength}catch{t("")}s>131072&&t(""),n(d,["schemaVersion","environmentKey","items"],""),d.schemaVersion!=="openxiangda.native-role-membership-batch-request/v2"&&t("/schemaVersion"),d.environmentKey!==void 0&&!["preproduction","production"].includes(String(d.environmentKey))&&t("/environmentKey"),(!Array.isArray(d.items)||d.items.length<1||d.items.length>50)&&t("/items");let a=new Set,c=new Set,f;for(let[u,p]of d.items.entries()){let _=`/items/${u}`,E=o(p,_);["create","update","revoke"].includes(String(E.operation))||t(`${_}/operation`),f??=E.operation,f!==E.operation&&t(`${_}/operation`),n(E,["operation","operationId","reason",...f==="create"?["userId","roleCode"]:["membershipId","expectedRevision"],...f!=="revoke"?["scopeGrants","validFrom","validTo"]:[]],_);let A=r(E.operationId,`${_}/operationId`);a.has(A)&&t(`${_}/operationId`),a.add(A),i(E.reason,1e3,`${_}/reason`);let O;if(f==="create"){let b=i(E.userId,255,`${_}/userId`),g=i(E.roleCode,128,`${_}/roleCode`);/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/.test(g)||t(`${_}/roleCode`),O=JSON.stringify([b,g])}else O=r(E.membershipId,`${_}/membershipId`),(!Number.isSafeInteger(E.expectedRevision)||Number(E.expectedRevision)<1)&&t(`${_}/expectedRevision`);c.has(O)&&t(_),c.add(O),E.scopeGrants!==void 0&&(!Array.isArray(E.scopeGrants)||E.scopeGrants.length>100)&&t(`${_}/scopeGrants`);for(let b of["validFrom","validTo"])E[b]!==void 0&&E[b]!==null&&i(E[b],64,`${_}/${b}`)}}var ws="openxiangda.workflow-delegation-administration/v2",Ss="openxiangda.workflow-delegation-mutation/v2",Rs="openxiangda.workflow-delegation-preview/v2";var Lt={type:"string",format:"uuid",pattern:"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$"},_e={type:"string",minLength:1,maxLength:255},Xe={type:"string",format:"date-time"},pt={type:"integer",minimum:1},Oc={anyOf:[Xe,{type:"null"}]},zo={anyOf:[_e,{type:"null"}]},Ds={anyOf:[{type:"string",pattern:"^[A-Za-z0-9._:-]{1,128}$"},{type:"null"}]},Tn={type:"string",pattern:"^membership:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},ks={const:"future-assignments-only"},Jo={schemaVersion:{const:ws},id:Lt,appCode:_e,environmentKey:_e,workflowCode:zo,nodeId:Ds,delegatorUserId:_e,delegateUserId:_e,delegatorRoleSubjectKey:Tn,delegateRoleSubjectKey:Tn,validFrom:Xe,validTo:Xe,status:{enum:["active","revoked","expired"]},reason:{type:"string",minLength:1,maxLength:4e3},createdBy:_e,createdAt:Xe,revokedAt:Oc,revision:pt,roleCode:_e,roleName:_e,delegatorDisplayName:_e,delegateDisplayName:_e,delegatorRoleSubjectRevision:pt,delegateRoleSubjectRevision:pt,effectiveState:{enum:["active","scheduled","expired","revoked","ineligible"]},evaluatedAt:Xe,issues:{type:"array",maxItems:20,uniqueItems:!0,items:_e},canRevoke:{type:"boolean"},revokedBy:zo,revokeReason:{type:["string","null"],maxLength:4e3},taskPolicy:ks},Ho={type:"object",additionalProperties:!1,required:Object.keys(Jo).filter(e=>e!=="nodeId"),properties:Jo},_p={$id:ws,...Ho},$s={schemaVersion:{const:Ss},operationId:Lt,environmentKey:{enum:["preproduction","production"]},reason:{type:"string",minLength:1,maxLength:2e3,pattern:"\\S"}},Cs={...$s,operation:{const:"create"},workflowCode:zo,nodeId:Ds,delegatorRoleSubjectKey:Tn,expectedDelegatorRevision:pt,delegateUserId:_e,delegateRoleSubjectKey:Tn,expectedDelegateRevision:pt,validFrom:Xe,validTo:Xe},hs={...$s,operation:{const:"revoke"},delegationId:Lt,expectedRevision:pt},Nc={$id:Ss,type:"object",oneOf:[{type:"object",additionalProperties:!1,required:Object.keys(Cs).filter(e=>e!=="nodeId"),properties:Cs,if:{required:["nodeId"],properties:{nodeId:{type:"string"}}},then:{properties:{workflowCode:_e}}},{type:"object",additionalProperties:!1,required:Object.keys(hs),properties:hs}]},Tc={type:"string",pattern:"^[0-9a-f]{64}$"},gp={$id:Rs,type:"object",additionalProperties:!1,required:["schemaVersion","operationId","operation","requestDigest","before","after","taskPolicy"],properties:{schemaVersion:{const:Rs},operationId:Lt,operation:{enum:["create","revoke"]},requestDigest:Tc,before:{anyOf:[Ho,{type:"null"}]},after:{...Ho,properties:{...Jo,id:{anyOf:[Lt,{type:"null"}]}}},taskPolicy:ks}};function Ip(e){return e===void 0?"":`
9
- ${Z(e)}`}function yp(e,t){let o=e.handlers.find(n=>n.code===t);return Z(o?.workflowStep?o:e)}var Op="openxiangda.data-business-command/v1",Rc="openxiangda.data-business-command-resolution/v1",Np=65536;function Tp(e){let t=0,o=0,n=new Set,i=new TextEncoder,r=()=>{throw new Error("OPENXIANGDA_DATA_COMMAND_INTENT_INVALID")},d=a=>(o+=i.encode(a).byteLength,o>65536&&r(),a),s=(a,c)=>{if(++t>1e4||c>32)return r();if(a===null||typeof a=="string"||typeof a=="boolean")return d(JSON.stringify(a));if(typeof a=="number")return Number.isFinite(a)?d(JSON.stringify(a)):r();if(!a||typeof a!="object"||n.has(a)||Object.getOwnPropertySymbols(a).length)return r();n.add(a);let f;if(Array.isArray(a))return Object.keys(a).length!==a.length?r():(f=d("[")+a.map((p,_)=>(_?d(","):"")+s(p,c+1)).join("")+d("]"),n.delete(a),f);let u=Object.getPrototypeOf(a);return u!==Object.prototype&&u!==null?r():(f=d("{")+Object.keys(a).sort().map((p,_)=>(_?d(","):"")+d(JSON.stringify(p))+d(":")+s(a[p],c+1)).join("")+d("}"),n.delete(a),f)};return!e||typeof e!="object"||Array.isArray(e)?r():s(e,0)}function Rp(e,t,o=!1){let n=e,i=()=>{throw new Error("OPENXIANGDA_DATA_COMMAND_RESPONSE_INVALID")};if(!n||typeof n!="object"||n.schemaVersion!==Rc)return i();for(let a of["appCode","environmentKey","operationCode","idempotencyKey","intentDigest"])if(n[a]!==t[a])return i();if(typeof n.observedAt!="string"||!Number.isFinite(Date.parse(n.observedAt)))return i();if(n.outcome==="not_observed"&&n.receipt===null&&!o)return n;if(n.outcome!=="committed"||!n.receipt)return i();let r=n.receipt,d=a=>typeof a=="string"&&/^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(a);if(!d(r.id)||!d(r.appVersionId)||!Number.isSafeInteger(r.environmentHeadRevision)||r.environmentHeadRevision<1||typeof r.completedAt!="string"||!Number.isFinite(Date.parse(r.completedAt)))return i();let s=r.transaction;if(!s||s.schemaVersion!=="openxiangda.data-transaction-result/v2"||s.idempotencyKey!==t.idempotencyKey||typeof s.replayed!="boolean"||!Array.isArray(s.items)||!s.items.length||s.items.length>1e3)return i();for(let[a,c]of s.items.entries()){if(!c||c.index!==a)return i();if(c.operation==="emitEvent"){if(!d(c.eventId)||typeof c.eventType!="string"||!c.eventType)return i()}else if(!["create","update","delete","increment"].includes(c.operation)||!d(c.id)||typeof c.resourceCode!="string"||!c.resourceCode||!Number.isSafeInteger(c.revision)||c.revision<1)return i()}return n}var Ps=/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/,Rn=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Ft=(e,t)=>typeof e=="string"&&e.length<=t&&e.trim().length>0&&e===e.trim(),Yo=(e,t,o=[])=>t.every(n=>Object.hasOwn(e,n))&&Object.keys(e).every(n=>[...t,...o].includes(n));function hp(e){if(!Rn(e)||!Yo(e,["kind","errorCode","anyOf"],["allowAppSuperAdmin"])||e.kind!=="actor-authority"||!Ft(e.errorCode,110)||!/^OPENXIANGDA_[A-Z0-9_]{1,96}$/.test(e.errorCode)||Object.hasOwn(e,"allowAppSuperAdmin")&&typeof e.allowAppSuperAdmin!="boolean"||!Array.isArray(e.anyOf)||e.anyOf.length<1||e.anyOf.length>20)return!1;let t=new Set;return e.anyOf.every(o=>{if(!Rn(o)||!Yo(o,["roleCode"],["scope"])||!Ft(o.roleCode,100)||!Ps.test(o.roleCode))return!1;if(Object.hasOwn(o,"scope")){let r=o.scope;if(!Rn(r)||!Yo(r,["dimensionCode","value","operation"])||!Ft(r.dimensionCode,100)||!Ps.test(r.dimensionCode)||!Ft(r.value,255)||!Ft(r.operation,64)||!/^[A-Za-z0-9*][A-Za-z0-9*._:-]*$/.test(r.operation))return!1}let n=o.scope,i=JSON.stringify([o.roleCode,n?.dimensionCode,n?.value,n?.operation]);return t.has(i)?!1:(t.add(i),!0)})}function wp(e,t,o){if(t.roleSource!=="package"||t.roleCode!==e.roleCode||!o||!t.capabilityCodes.includes(o))return!1;if(!e.scope)return!0;let n;try{n=JSON.parse(t.scopeGrantsJson)}catch{return!1}if(!Array.isArray(n))return!1;let i=e.scope;return n.some(r=>Rn(r)&&r.dimensionCode===i.dimensionCode&&Array.isArray(r.values)&&r.values.includes(i.value)&&(r.operations===void 0||r.operations===null||Array.isArray(r.operations)&&(!r.operations.length||r.operations.includes("*")||r.operations.includes(i.operation))))}var Dp=500,Cc=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Xo=e=>!!e&&typeof e=="object"&&!Array.isArray(e);function kp(e){if(!Xo(e)||e.kind!=="record-set-match"||Object.keys(e).some(o=>!["kind","resourceCode","errorCode","records","where"].includes(o))||typeof e.resourceCode!="string"||e.resourceCode.length>64||!/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/.test(e.resourceCode)||typeof e.errorCode!="string"||!/^OPENXIANGDA_[A-Z0-9_]{1,96}$/.test(e.errorCode)||!Array.isArray(e.records)||!e.records.length||e.records.length>500||Object.hasOwn(e,"where")&&!Xo(e.where))return!1;let t=new Set;return e.records.every(o=>{if(!Xo(o)||Object.keys(o).length!==2||typeof o.id!="string"||!Cc.test(o.id)||!Number.isSafeInteger(o.expectedRevision)||Number(o.expectedRevision)<1)return!1;let n=o.id.toLowerCase();return t.has(n)?!1:(t.add(n),!0)})}function hc(e,t){if(t===void 0)return e;let o=e.views?.find(d=>d.code===t);if(!o)throw new Error(`DATA_RESOURCE_VIEW_NOT_FOUND: ${t}`);let n=new Map(o.sections?.flatMap(d=>d.fields.map(s=>[s,d.title]))),{views:i,...r}=e;return{...r,generated:o.generated,list:o.list,form:o.form,detail:o.detail,mobile:o.mobile,fields:Object.fromEntries(Object.entries(e.fields).map(([d,s])=>{let{section:a,...c}=s,f=n.get(d);return[d,{...c,...f?{section:f}:{},list:o.list.fieldOrder?.includes(d)??!1}]}))}}var wc="openxiangda.development-configuration/v2",vs="openxiangda.development-configuration-manifest/v1",Lp="application.development-configuration",Fp="/openxiangda-api/v2/applications/{appCode}/dev-sessions/configuration",Zo=class extends Error{constructor(o,n){super(o);this.code=o;this.pointer=n;this.data={pointer:n}}code;pointer;status=400;data};function je(e){throw new Zo("OPENXIANGDA_CONNECTED_DEV_CONFIGURATION_INVALID",e)}function Sc(e){(!e||typeof e!="object"||Array.isArray(e))&&je("/packageManifest");let t=e,o=["schemaVersion","appCode","version","configDigest","contractDigest","source","toolchain","artifacts"];(Object.keys(t).some(i=>!o.includes(i))||t.schemaVersion!==vs||typeof t.appCode!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(t.appCode)||!/^[a-f0-9]{64}$/.test(t.configDigest)||!/^[a-f0-9]{64}$/.test(t.contractDigest)||t.version!==`development-${t.configDigest}`)&&je("/packageManifest"),(!t.source||typeof t.source!="object"||Array.isArray(t.source)||Object.keys(t.source).some(i=>!["repository","commit","dirty"].includes(i))||![null,"string"].includes(t.source.repository===null?null:typeof t.source.repository)||t.source.repository!==null&&(t.source.repository.length>1024||/[\r\n\0]/.test(t.source.repository))||t.source.commit!==null&&(typeof t.source.commit!="string"||!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(t.source.commit))||typeof t.source.dirty!="boolean")&&je("/packageManifest/source"),(!t.toolchain||Object.keys(t.toolchain).some(i=>!["version","contractVersion"].includes(i))||typeof t.toolchain.version!="string"||!/^[A-Za-z0-9][A-Za-z0-9.+_-]{0,127}$/.test(t.toolchain.version)||t.toolchain.contractVersion!==ko)&&je("/packageManifest/toolchain");let n=[{kind:"config",digest:t.configDigest,mediaType:"application/json"},{kind:"contracts",digest:t.contractDigest,mediaType:"application/json"}];return X(t.artifacts)!==X(n)&&je("/packageManifest/artifacts"),t}function xp(e,t){return Sc({schemaVersion:vs,appCode:e,version:`development-${t.configDigest}`,configDigest:t.configDigest,contractDigest:t.contractDigest,source:{...t.source},toolchain:{version:t.toolchainVersion,contractVersion:ko},artifacts:[{kind:"config",digest:t.configDigest,mediaType:"application/json"},{kind:"contracts",digest:t.contractDigest,mediaType:"application/json"}]})}function jp(e,t,o){return(!Number.isSafeInteger(t)||t<1)&&je("/expectedHeadRevision"),`development:${Z({manifest:e,expectedHeadRevision:t,...o?{actorUserId:o}:{}})}`}function Wp(e,t,o){(!e||typeof e!="object"||Array.isArray(e))&&je("/result");let n=e,i=["schemaVersion","appCode","environmentKey","environmentId","appVersionId","configurationRunId","headRevision","publishedAppVersionId","selection","configDigest","contractDigest","reused","runtimeArtifactsDeployed","backendEventsAvailable"],r=/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/i;return(Object.keys(n).some(d=>!i.includes(d))||n.schemaVersion!==wc||n.appCode!==t||n.environmentKey!=="preproduction"||n.configDigest!==o.configDigest||n.contractDigest!==o.contractDigest||!r.test(n.environmentId)||!r.test(n.appVersionId)||!r.test(n.publishedAppVersionId)||n.appVersionId===n.publishedAppVersionId||n.selection!=="session"||!r.test(n.configurationRunId)||typeof n.reused!="boolean"||!Number.isSafeInteger(n.headRevision)||n.headRevision<1||n.headRevision!==o.expectedHeadRevision||n.runtimeArtifactsDeployed!==!1||n.backendEventsAvailable!==!1)&&je("/result"),n}var Mp="application.development-backend-events",Bp="openxiangda.development-backend/v1",Kp="application.development-backend-invocations",Dc="openxiangda.development-backend-invocation/v1",Gp=262144,qp=1048576,zp=131072,Jp=131072,Hp=8,Yp=45,Xp=/^\/__platform\/events\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;function Zp(e){return(e.backend?.operations?.length||0)>0||(e.workflows?.providers?.length||0)>0||(e.events?.subscriptions||[]).some(t=>t.execution?.kind!=="native-data")}function Qp(e){return`connected-development:${e}`}function kc(e){if(typeof e!="string"||e.length%4!==0||!/^[A-Za-z0-9+/]*={0,2}$/.test(e))return null;let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=e.endsWith("==")?2:e.endsWith("=")?1:0;return o&&t.indexOf(e[e.length-o-1])%(o===2?16:4)!==0?null:e.length/4*3-o}function $c(e,t,o){if(!["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(e)||o.method!==e||typeof t!="string"||t.length>2048||!t.startsWith("/")||t.startsWith("//")||t.startsWith("/__platform")||/[\\?#\s\u0000-\u001f\u007f]/.test(t))return!1;let n=t.split("/"),i=String(o.path||"").split("/");return n.length!==i.length?!1:n.every((r,d)=>{if(d===0)return i[d]==="";let s;try{s=decodeURIComponent(r)}catch{return!1}return!s||[".",".."].includes(s)||/[\/\\\s\u0000-\u001f\u007f]/.test(s)?!1:/^:[A-Za-z][A-Za-z0-9_]*$/.test(i[d]||"")||r===i[d]})}var Pc=/^(?:authorization|content-type|content-length|accept|if-match|idempotency-key|x-request-id|x-openxiangda-(?:gateway-assertion|forwarded-by|perspective|csrf-token|mcp-bus-token|dev-selection))$/i,vc=/^(?:content-type|content-disposition|cache-control|etag|last-modified|retry-after)$/i;function Vc(e,t=!1){if(!e||typeof e!="object"||Array.isArray(e))return!1;let o=Object.entries(e),n=o.map(([i])=>i.toLowerCase());return o.length<=24&&new Set(n).size===n.length&&o.every(([i,r])=>(t?vc:Pc).test(i)&&typeof r=="string"&&r.length<=8192&&!/[\r\n\u0000]/.test(r))}function em(e){let t=kc(e.body);return e.schemaVersion===Dc&&!!e.operation&&typeof e.operation.code=="string"&&e.operation.code.length<=128&&e.operation.code.length>0&&$c(e.method,e.endpointPath,e.operation)&&typeof e.canonicalQuery=="string"&&e.canonicalQuery.length<=8192&&!/[\s#\u0000-\u001f\u007f]/.test(e.canonicalQuery)&&t!==null&&t<=262144&&Vc(e.headers)&&Object.entries(e.headers).some(([o,n])=>o.toLowerCase()==="authorization"&&/^Bearer \S+$/.test(n))&&Object.entries(e.headers).some(([o,n])=>o.toLowerCase()==="x-openxiangda-gateway-assertion"&&!!n)}var nm=Object.freeze({version:"rich-text-html/1",maxBytes:1048576,maxNodes:25e3,maxDepth:128,maxImages:20,imageMaxBytes:10485760,maxVideos:4,videoMaxBytes:104857600,imageTypes:["image/png","image/jpeg","image/webp","image/gif"],videoTypes:["video/mp4","video/webm"],fonts:["Arial","Verdana","Tahoma","Times New Roman","Courier New","\u5B8B\u4F53","\u5FAE\u8F6F\u96C5\u9ED1","SimSun","Microsoft YaHei","sans-serif","serif","monospace"]});var im="4c4c20b850e5c473401b3a8767f68374e662b74bf636984bfcc20b5c5f8262c9";export{Nt as AuthenticatedPublicReadContractError,Kt as DATA_AUDIT_METADATA_FIELDS,Np as DATA_BUSINESS_COMMAND_INTENT_MAX_BYTES,Rc as DATA_BUSINESS_COMMAND_RESOLUTION_SCHEMA,Op as DATA_BUSINESS_COMMAND_SCHEMA,Fo as DATA_EVENT_TYPES_V2,Bc as DATA_FORM_DRAFT_MAX_BYTES,ii as DATA_RESOURCE_MAX_FIELDS,$n as DATA_SUBTABLE_DEFAULT_TOTAL_ROWS,Be as DATA_SUBTABLE_MAX_ROWS,tt as DATA_SUBTABLE_MAX_TOTAL_ROWS,Ys as DATA_SYSTEM_SORT_FIELD_CODES,Mc as DATA_TRANSACTION_MAX_BYTES,ri as DATA_TRANSACTION_MAX_OPERATIONS,Dp as DATA_TRANSACTION_RECORD_SET_MAX_RECORDS,Wu as DATE_EVENT_RESERVED_DATA_FIELDS_V2,Yp as DEVELOPMENT_BACKEND_CONNECTION_TTL_SECONDS,Xp as DEVELOPMENT_BACKEND_ENDPOINT_PATTERN,Mp as DEVELOPMENT_BACKEND_FEATURE,Kp as DEVELOPMENT_BACKEND_INVOCATION_FEATURE,Gp as DEVELOPMENT_BACKEND_INVOCATION_MAX_REQUEST_BYTES,qp as DEVELOPMENT_BACKEND_INVOCATION_MAX_RESPONSE_BYTES,Dc as DEVELOPMENT_BACKEND_INVOCATION_SCHEMA,Hp as DEVELOPMENT_BACKEND_MAX_INFLIGHT,Jp as DEVELOPMENT_BACKEND_MAX_REQUEST_BYTES,zp as DEVELOPMENT_BACKEND_MAX_RESPONSE_BYTES,Bp as DEVELOPMENT_BACKEND_SCHEMA,Fp as DEVELOPMENT_CONFIGURATION_ENDPOINT,Lp as DEVELOPMENT_CONFIGURATION_FEATURE,vs as DEVELOPMENT_CONFIGURATION_MANIFEST_SCHEMA,wc as DEVELOPMENT_CONFIGURATION_SCHEMA,cn as DateEventProjectionV2Error,Zo as DevelopmentConfigurationContractError,Et as ManagedConcurrencyContractError,re as NATIVE_ARTIFACT_CAPACITY_V2,im as NATIVE_CONFIGURATION_VALIDATOR_DIGEST,B as NATIVE_CONTRACT_CAPACITY_V2,Ll as NATIVE_DATA_POLICY_EXPRESSION_MAX_CLAUSES,Pl as NATIVE_DATA_POLICY_EXPRESSION_MAX_DEPTH,vl as NATIVE_DATA_POLICY_EXPRESSION_MAX_GROUP_ITEMS,Vl as NATIVE_DATA_POLICY_EXPRESSION_MAX_LEAVES,Fl as NATIVE_DATA_POLICY_EXPRESSION_MAX_OCCURRENCES,Xs as NATIVE_DATA_QUERY_OPERATORS_V2,ct as NATIVE_HIGH_DENSITY_ARTIFACT_CAPACITY_V2,fp as NATIVE_ROLE_MEMBERSHIP_BATCH_MAX_BYTES,up as NATIVE_ROLE_MEMBERSHIP_BATCH_MAX_ITEMS,Jl as NATIVE_UNIQUE_KEY_MAX_BYTES,zi as NATIVE_UNIQUE_KEY_NORMALIZERS,jo as NativeConfigurationCompilerError,Re as NativeDataFieldContractV2Error,Ot as NativeDataPolicyExpressionV2Error,rt as NativeDecimalLifecycleContractError,fo as NativeEventActionContractError,ue as NativeParentReadPolicyError,qo as NativeRoleMembershipBatchInputError,ro as NativeScopeSourceFieldPathV2Error,Rt as NativeUniqueKeyContractError,js as OPENXIANGDA_NATIVE_DATA_FIELD_TYPES_V2,Pe as OPENXIANGDA_NATIVE_DATA_SURFACE_KEYS_V2,Hn as OPENXIANGDA_NATIVE_DRAFT_STATE_KEYS_V2,Mn as OPENXIANGDA_NATIVE_SYSTEM_FIELDS_V2,nt as OPENXIANGDA_NATIVE_SYSTEM_FIELD_MAP_V2,nm as RICH_TEXT_POLICY_V2,jc as USER_CANDIDATE_MAX_SELECTIONS,Fs as USER_CANDIDATE_SCOPE_FIELD_TYPES,Me as UserCandidateContractError,Ir as WORKFLOW_APPROVAL_EMPTY_PROVIDERS,Lu as WORKFLOW_APPROVED_DELEGATION_MAX_BYTES,Vu as WORKFLOW_APPROVED_DELEGATION_MAX_REQUESTS,_r as WORKFLOW_AUTOMATIC_CC_DEFAULT_RECIPIENTS,gr as WORKFLOW_AUTOMATIC_CC_MAX_RECIPIENTS,Ba as WORKFLOW_AUTOMATIC_CC_PROVIDERS,Ct as WORKFLOW_BUSINESS_STEP_EVENT,ir as WORKFLOW_BUSINESS_STEP_EVENTS,iu as WORKFLOW_BUSINESS_STEP_FACTS_KEY,_o as WORKFLOW_BUSINESS_STEP_MAX_BYTES,xa as WORKFLOW_BUSINESS_STEP_MAX_RECEIPT_BYTES,yo as WORKFLOW_CONFIGURABLE_OPERATIONS,bo as WORKFLOW_CONFIGURABLE_PROVIDERS,xo as WORKFLOW_EVENT_TYPES_V2,Pn as WORKFLOW_LAUNCH_MAX_INPUTS,Ja as WORKFLOW_LAUNCH_PREFLIGHT_PROVIDERS,wu as WORKFLOW_REJECTION_NOTIFICATION_MAX_BYTES,za as WORKFLOW_REJECTION_NOTIFICATION_SCHEMA,mu as WORKFLOW_ROLE_UNION_MAX_ROLES,Xu as WORKFLOW_ROUTING_MAX_BYTES,Yu as WORKFLOW_ROUTING_MAX_MATCHED_RULES,Hu as WORKFLOW_ROUTING_MAX_RULES,dp as WORKFLOW_STEP_DATA_COMMAND_SCHEMA,bc as WORKFLOW_STEP_DATA_RESOLUTION_SCHEMA,Qa as WORKFLOW_TASK_PAGE_DEFINITION_MAX_BYTES,wo as WORKFLOW_TASK_PAGE_MAX_BYTES,Za as WORKFLOW_TASK_PAGE_MAX_FIELDS,Pr as WORKFLOW_TASK_SUBTABLE_MAX_ROWS,kr as WORKFLOW_TASK_SUBTABLE_MAX_TOTAL_ROWS,we as WorkflowTaskPageError,ed as applyWorkflowTaskPageValues,Gu as applyWorkflowTaskSubtableRows,Sc as assertDevelopmentConfigurationManifest,Wp as assertDevelopmentConfigurationResult,pp as assertNativeRoleMembershipBatchInput,Ul as assertWorkflowNativeStageGuard,Ki as assertWorkflowNativeStagePolicy,Ml as assertWorkflowNativeStageSourceGuard,pn as assertWorkflowOwnedSubjectCreate,Mr as assertWorkflowOwnedSubjectCreateResources,Tp as canonicalDataBusinessIntent,op as compileNativeApplicationConfiguration,Qi as compileNativeEventAction,Sd as compileNativeEventCapturePlansV2,wd as compileRequiredPlatformCapabilitiesV3,Ao as compileWorkflowBusinessStepHandlers,xp as createDevelopmentConfigurationManifest,jt as dataOwnedRowLimit,Uu as dateEventProjectionEnvelopeSchemaV2,Dr as dateEventProjectionFieldsV2,kc as developmentBackendBase64Bytes,Vc as developmentBackendInvocationHeadersValid,em as developmentBackendInvocationRequestValid,Qp as developmentBackendInvocationRevision,$c as developmentBackendOperationMatches,jp as developmentConfigurationKey,Fe as evaluateWorkflowTaskPageExpression,Cu as formatWorkflowCompletionDeadline,rn as formatWorkflowExpression,Gr as generatedCrudCapabilityOperations,pi as hasDataAuditReadPolicy,co as hasNativeParentReadPolicy,_t as isDataAuditMetadataField,mt as isDataOwnedRowLimit,mi as isDataSystemSortField,hp as isDataTransactionActorAuthorityGuard,kp as isDataTransactionRecordSetMatchGuard,Xc as isNativeDataQueryOperatorV2,Mt as isNativeMultiValueFieldV2,Su as isWorkflowRejectionNotificationSnapshot,wp as matchesDataActorAuthorityMembership,Dl as materializeNativeDataQueryPathTypesV2,st as nativeDataPolicyExpressionLeavesV2,Vi as nativeDataPolicyExpressionToCnfV2,kl as nativeDataQueryPathPlanV2,Qc as nativeFieldAggregatePlanV2,Il as nativeFieldColumnDefinitionV2,yl as nativeFieldDefaultSqlV2,bl as nativeFieldHasDefaultV2,Rl as nativeFieldIndexStatementsV2,Bt as nativeFieldRequiresCreateInputV2,Tl as nativeFieldSequenceGrantStatementsV2,Nl as nativeFieldSequenceOwnershipStatementsV2,Ol as nativeFieldSequenceStatementsV2,Ei as nativeFieldSupportsFilterV2,Zc as nativeFieldSupportsOperatorV2,zn as nativeFieldSupportsSearchV2,At as nativeFieldSupportsSortV2,Ai as nativeOperatorsForFieldV2,Ia as nativePhysicalFieldV2,El as nativePhysicalFieldsV2,ve as nativePhysicalObjectNameV2,wl as nativeScopeSourceFieldValueV2,Pi as nativeScopeSourceGrantPathSupportedV2,so as nativeScopeSourceSubjectPathSupportedV2,Cl as nativeSubtableConstraintStatementsV2,Hi as nativeUniqueKeysContractVersion,Hl as nativeUniqueKeysJsonSchema,sf as normalizeWorkflowOwnedSubjectCreate,Rp as parseDataBusinessCommandResolution,xt as parseDataFieldUserCandidates,oo as parseDecimalReservationLifecycle,Bn as parseNativeDataFieldsV2,fi as parseNativeDataResourceInvariantsV2,Fa as parseNativeParentReadPolicy,Ji as parseNativeUniqueKeys,cp as parseWorkflowStepDataResolution,hc as projectDataResourceView,Qn as projectNativeDataResourceViewV2,lu as projectWorkflowGraph,Ar as projectWorkflowNodePolicy,le as quoteNativeIdentifierV2,qu as refreshWorkflowTaskPageFacts,Vn as requiresAggregateOwnedSubtableCapacity,Wn as requiresDateTimeMinutePrecision,Zp as requiresDevelopmentBackendCredential,mn as requiresExtendedArtifactCapacity,vo as requiresExtendedConfigurationBytes,Po as requiresExtendedDeclarationCapacity,vn as requiresExtendedFieldCapacity,Ln as requiresExtendedOwnedSubtableCapacity,$o as requiresExtendedRoleCapacity,_n as requiresHighDensityArtifactCapacity,Un as requiresOwnedSubtableMinimumRows,kn as requiresUserCandidateLaunchScope,mr as requiresWorkflowRoleInputSelection,fr as requiresWorkflowRoleUnion,Xt as resolveNativeParentReadBinding,It as resolveNativeScopeSourceFieldPathV2,xs as resolveWorkflowUserCandidates,tf as selectWorkflowAssignmentRoutingRules,Kc as serializedDataBytes,Wc as userCandidateScopeValue,qi as validateAuthenticatedPublicRead,hi as validateDecimalReservationLifecycles,Ri as validateManagedConcurrency,bi as validateNativeDataDraftStateV2,ui as validateNativeDataResourceReferencesV2,Zn as validateNativeDataResourceSurfaceV2,ji as validateNativeParentReadPolicies,ni as validateUserCandidateReferences,Oo as validateWorkflowAdministration,No as validateWorkflowApprovalEmptyPolicy,wr as validateWorkflowApprovedDelegation,Wr as validateWorkflowAssignmentRoutingBindings,fn as validateWorkflowAssignmentRoutingPolicy,Qu as validateWorkflowAssignmentRoutingRules,Io as validateWorkflowAutomaticCc,su as validateWorkflowBusinessStepHandlerContract,ru as validateWorkflowBusinessStepRequest,ja as validateWorkflowBusinessStepResult,tn as validateWorkflowBusinessStepSchema,dr as validateWorkflowBusinessStepSubscriptions,on as validateWorkflowBusinessSteps,Rr as validateWorkflowCommandHandlers,Or as validateWorkflowCompletionDeadlines,Sr as validateWorkflowCorrections,ht as validateWorkflowInitiatorApprovalPolicy,tr as validateWorkflowInstanceCommandPolicies,Ro as validateWorkflowLaunchPreflight,Ou as validateWorkflowNodeConfigurationPatch,lr as validateWorkflowReadability,Tr as validateWorkflowRejectionNotification,pr as validateWorkflowRoleInputSelection,an as validateWorkflowRoleUnion,un as validateWorkflowTaskPages,oi as validateWorkflowUserCandidateBindings,Tu as workflowApprovalCanSkip,Fu as workflowApprovedDelegationRequests,ef as workflowAssignmentRoutingFacts,Zu as workflowAssignmentRoutingPolicySchema,id as workflowAssignmentRoutingSemantic,yr as workflowBindingAllowsEmptyUsers,gu as workflowBindingRoleCodes,$u as workflowBusinessCommandInvocationSchema,nn as workflowBusinessStepFactSchema,yp as workflowBusinessStepHandlerDigest,au as workflowBusinessStepInput,Wa as workflowBusinessStepPath,Ip as workflowBusinessStepReceiptSignatureSuffix,en as workflowBusinessStepValueMatches,Nc as workflowDelegationMutationRequestSchema,cr as workflowExpressionPaths,fu as workflowInitiatorApprovalCanComplete,nu as workflowInstanceCommandDeadlineError,eu as workflowInstanceTerminateCapabilityAllowed,tu as workflowInstanceWithdrawalReasonRequired,Bl as workflowNativeStagePolicySchema,wt as workflowNodeAllowedOperations,Ga as workflowOperationCommentRequired,qa as workflowOperationReasonRequired,rf as workflowOwnedSubjectCreateSchema,er as workflowPolicyTimestamp,_u as workflowRoleCodesSchema,Lr as workflowTaskPageFieldState,zu as workflowTaskPageReplayCoversInvalidation,Ku as workflowTaskSubtableRows,Ma as workflowVariableLabel};
8
+ END $native_subtable$`]}function ve(e,...t){return`${e}_${ga("sha256").update(t.join(":")).digest("hex").slice(0,32)}`}function le(e){if(!/^[A-Za-z_][A-Za-z0-9_]{0,62}$/.test(e))throw new Error("OPENXIANGDA_NATIVE_IDENTIFIER_INVALID");return`"${e}"`}function Oa(e,t){return e.type==="subtable"?"none":t?"gin-trigram":e.indexed?["date-range","datetime-range"].includes(e.type)?"gist-range":ro.has(e.type)?"btree-snapshot-expressions":Aa.has(e.type)?"gin-jsonb-path":"btree":"none"}function Na(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 Ia.has(e.type),"jsonb"}}function kr(e,t){if(Ut(t.type)&&t.type!=="subtable")return"'[]'::jsonb";if(t.type!=="serial-number")return"";let o=Sr(t.serial?.prefix||""),n=t.serial?.digits??6;return`(${o} || lpad(nextval(${Sr(Yt(e,t.code))})::text, ${n}, '0'))`}function Ta(e,t){return Dr.has(t.type)?` CHECK (${e} IS NULL OR jsonb_typeof(${e}) = 'array')`:Ea.has(t.type)?` CHECK (${e} IS NULL OR jsonb_typeof(${e}) = 'object')`:""}function Ht(e){return`"app_data".${le(e)}`}function Yt(e,t){let o=ve("seq",e,t);return`"app_data".${le(o)}`}function Sr(e){return`'${e.replace(/'/g,"''")}'`}var $r=new Set(["option.single","option.multiple","user.single","user.multiple","department.single","department.multiple","resource-ref.single","resource-ref.multiple"]),Ra=new Set([...$r,"cascade.single","cascade.multiple","file","image","signature","address","location","json"]),Pr=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,Ca=new Set(["__proto__","prototype","constructor"]),io=class extends Error{constructor(o){super("OPENXIANGDA_SCOPE_PROJECTION_FIELD_PATH_INVALID");this.path=o;this.name="NativeScopeSourceFieldPathV2Error"}path;code="OPENXIANGDA_SCOPE_PROJECTION_FIELD_PATH_INVALID"};function It(e,t){let o=Vr(e);if(!o)return null;let n=t.get(o[0]);if(!n)return null;let r=o.slice(1).join(".")||void 0;return{field:n,...r?{valuePath:r}:{}}}function so(e){return!!(e&&e.field.type==="user.single"&&e.valuePath==="value")}function vr(e,t,o){if(!e||!t||!ha(e))return!1;let{field:n,valuePath:r}=e;if(!r)return t.valueType==="uuid"?n.type==="uuid":["text.short","text.long","serial-number"].includes(n.type);if(r==="value")return!(t.valueSourceResourceCode&&n.type.startsWith("resource-ref.")&&n.source?.resourceCode!==t.valueSourceResourceCode);let i=r.slice(9),s=o.get(n.source?.resourceCode||"")?.get(i)?.type;return t.valueType==="uuid"?s==="uuid":["text.short","text.long","serial-number"].includes(s||"")}function Sl(e,t){let o=Vr(t);if(!o)throw new io(String(t||""));let n=e;for(let r of o){if(!n||typeof n!="object"||!Object.prototype.hasOwnProperty.call(n,r))return;n=n[r]}return n}function ha(e){let{field:t,valuePath:o}=e;if(!o)return!Ra.has(t.type);if(o==="value")return $r.has(t.type);if(!o.startsWith("snapshot."))return!1;let n=o.slice(9);return Pr.test(n)&&t.type.startsWith("resource-ref.")&&!!t.source?.snapshotFields?.includes(n)}function Vr(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=>!Pr.test(o)||Ca.has(o))||t.length===2&&t[1]!=="value"||t.length===3&&t[1]!=="snapshot"?null:t}var wa=new Set(["option.single","user.single","department.single","resource-ref.single"]),Sa=new Set(["text.short","text.long","text.rich","number.integer","number.decimal","boolean","date","time","datetime","uuid","serial-number"]),Da=new Set(["value","label","description","color"]),ka=new Set(["avatarUrl","employeeNo","title","mobile","email"]),$a=new Set(["fullPath","parent.value","parent.label"]),Pa=new Set(["country.value","country.label","province.value","province.label","city.value","city.label","district.value","district.label","street.value","street.label","detail","fullAddress"]),va=new Set(["longitude","latitude","accuracy"]),Va=new Set(["address","name","province","city","district","source"]);function kl(e){let t=new Map(e.map(o=>[o.code,new Map(o.schema.fields.map(n=>[n.code,n]))]));return e.map(o=>({...o,schema:{...o.schema,fields:o.schema.fields.map(n=>{let r=La(n,t);if(!Object.keys(r).length)return n;let i={...n};return Object.defineProperty(i,"queryPathTypes",{configurable:!1,enumerable:!1,writable:!1,value:Object.freeze(r)}),i})}}))}function $l(e,t){if(wa.has(e.type)&&Da.has(t)||e.type==="user.single"&&ka.has(t)||e.type==="department.single"&&$a.has(t))return yt(t);if(e.type==="resource-ref.single"){let o=e.queryPathTypes?.[t];return o?{parts:t.split("."),type:o}:null}if(e.type==="address"&&Pa.has(t))return yt(t);if(e.type==="location"){if(va.has(t))return{parts:[t],type:"number.decimal"};if(Va.has(t))return yt(t);if(t==="capturedAt")return{parts:[t],type:"datetime"}}return null}function La(e,t){if(e.type!=="resource-ref.single"||!e.source)return{};let o=t.get(e.source.resourceCode);return o?Object.fromEntries((e.source.snapshotFields||[]).flatMap(n=>{let r=o.get(n);return r?[[`snapshot.${n}`,Sa.has(r.type)?r.type:"json"]]:[]})):{}}function yt(e){return{parts:e.split("."),type:"text.short"}}function ao(e,t){let o=()=>{throw Object.assign(new Error("DATA_MUTATION_GRANT_INVALID"),{code:"DATA_MUTATION_GRANT_INVALID"})};if(!Array.isArray(e)||e.length<1||e.length>32)return o();let n=new Set;return e.map(i=>!i||typeof i!="object"||Array.isArray(i)||Object.keys(i).some(d=>!["resourceCode","operations","fieldCodes","maxOperations","allowRuntimeWorker"].includes(d))||typeof i.resourceCode!="string"||!/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/.test(i.resourceCode)||i.allowRuntimeWorker!==void 0&&i.allowRuntimeWorker!==!0||n.has(i.resourceCode)||t&&!t.has(i.resourceCode)||!Array.isArray(i.operations)||i.operations.length<1||i.operations.length>4||new Set(i.operations).size!==i.operations.length||i.operations.some(d=>!["create","update","delete","increment"].includes(d))||!Array.isArray(i.fieldCodes)||i.fieldCodes.length>128||new Set(i.fieldCodes).size!==i.fieldCodes.length||i.operations.some(d=>d!=="delete")&&!i.fieldCodes.length||i.fieldCodes.some(d=>typeof d!="string"||!/^[A-Za-z][A-Za-z0-9_]{0,62}$/.test(d)||t&&!t.get(i.resourceCode)?.has(d))||!Number.isSafeInteger(i.maxOperations)||i.maxOperations<1||i.maxOperations>1e3?o():(n.add(i.resourceCode),{resourceCode:i.resourceCode,operations:[...i.operations].sort(),fieldCodes:[...i.fieldCodes].sort(),maxOperations:i.maxOperations,...i.allowRuntimeWorker?{allowRuntimeWorker:!0}:{}})).sort((i,d)=>i.resourceCode.localeCompare(d.resourceCode))}var Vl=5,Ll=20,Fl=50,xl=50,jl=100,Ot=class extends Error{constructor(o,n){super(o);this.code=o;this.pointer=n;this.name="NativeDataPolicyExpressionV2Error"}code;pointer};function st(e,t){let o=[],n=(r,i,d)=>{d>5&&bt("NATIVE_DATA_POLICY_EXPRESSION_DEPTH_EXCEEDED",i);let s=Fr(r,i),a=["allOf","anyOf"].filter(u=>u in s);if(a.length===0){o.push({rule:s,pointer:i}),o.length>50&&bt("NATIVE_DATA_POLICY_EXPRESSION_LEAVES_EXCEEDED",i);return}let c=a[0],f=s[c];(a.length!==1||Object.keys(s).length!==1||!Array.isArray(f)||f.length<1||f.length>20)&&bt("NATIVE_DATA_POLICY_EXPRESSION_GROUP_INVALID",i),f.forEach((u,p)=>n(u,`${i}/${c}/${p}`,d+1))};return n(e,t,1),o}function Lr(e,t){st(e,t);let o=(n,r)=>{let i=Fr(n,r);if(Array.isArray(i.allOf))return co(i.allOf.flatMap((d,s)=>o(d,`${r}/allOf/${s}`)),r);if(Array.isArray(i.anyOf)){let d=[[]];return i.anyOf.forEach((s,a)=>{let c=o(s,`${r}/anyOf/${a}`);d=co(d.flatMap(f=>c.map(u=>[...f,...u])),r)}),d}return[[i]]};return co(o(e,t),t)}function co(e,t){let o=e.reduce((n,r)=>n+r.length,0);return(e.length>50||o>100)&&bt("NATIVE_DATA_POLICY_EXPRESSION_EXPANSION_EXCEEDED",t),e}function Fr(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&bt("NATIVE_DATA_POLICY_EXPRESSION_NODE_INVALID",t),e}function bt(e,t){throw new Ot(e,t)}var ue=class extends Error{constructor(o,n){super(`${o}: ${n}`);this.code=o;this.pointer=n}code;pointer},Fa=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,xr=/^[A-Za-z_][A-Za-z0-9_]{0,127}$/;function xa(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new ue("NATIVE_PARENT_READ_INVALID",t);let o=e;if(Object.keys(o).some(n=>!["resourceCode","subtableFieldCode"].includes(n))||typeof o.resourceCode!="string"||o.resourceCode.length>64||!Fa.test(o.resourceCode)||typeof o.subtableFieldCode!="string"||!xr.test(o.subtableFieldCode))throw new ue("NATIVE_PARENT_READ_INVALID",t);return{resourceCode:o.resourceCode,subtableFieldCode:o.subtableFieldCode}}function jr(e,t){return[...(Array.isArray(e.rules)?e.rules:[]).map((o,n)=>({rule:o,pointer:`${t}/rules/${n}`,base:!0})),...e.readExpression===void 0?[]:st(e.readExpression,`${t}/readExpression`).map(o=>({...o,base:!1}))]}function Xt(e,t,o,n){let r=xa(o,n),i=e.find(_=>_.code===r.resourceCode),d=e.find(_=>_.code===t),a=(Array.isArray(i?.schema?.fields)?i.schema.fields:[]).find(_=>_.code===r.subtableFieldCode);if(!i||!d||i.code===d.code||a?.type!=="subtable"||a.subtable?.resourceCode!==t)throw new ue("NATIVE_PARENT_READ_BINDING_INVALID",n);if(e.flatMap(_=>(Array.isArray(_.schema?.fields)?_.schema.fields:[]).filter(E=>E.type==="subtable"&&E.subtable?.resourceCode===t).map(E=>({resource:_,field:E}))).length!==1)throw new ue("NATIVE_PARENT_READ_PARENT_AMBIGUOUS",n);let f=a.subtable.foreignKey,p=(Array.isArray(d.schema?.fields)?d.schema.fields:[]).find(_=>_.code===f);if(typeof f!="string"||!xr.test(f)||p?.type!=="uuid")throw new ue("NATIVE_PARENT_READ_FOREIGN_KEY_INVALID",n);return{...r,childResourceCode:t,foreignKey:f,...a.subtable.orderField?{orderField:a.subtable.orderField}:{}}}function Wr(e,t,o="/config/authz/dataPolicies"){let n=new Map;for(let[r,i]of t.entries())for(let d of jr(i,`${o}/${r}`)){if(d.rule.parentRead===void 0)continue;if(Object.keys(d.rule).some(f=>!["parentRead","roleCodes"].includes(f)))throw new ue("NATIVE_PARENT_READ_RULE_KEYS_INVALID",d.pointer);if(d.base&&(i.operations?.length!==1||i.operations[0]!=="read"))throw new ue("NATIVE_PARENT_READ_READ_ONLY",d.pointer);if(e.find(f=>f.code===i.resourceCode)?.dataPolicyCode!==i.code)throw new ue("NATIVE_PARENT_READ_POLICY_BINDING_INVALID",d.pointer);let a=Xt(e,i.resourceCode,d.rule.parentRead,`${d.pointer}/parentRead`),c=n.get(i.resourceCode);if(c&&c!==a.resourceCode)throw new ue("NATIVE_PARENT_READ_PARENT_AMBIGUOUS",d.pointer);n.set(i.resourceCode,a.resourceCode)}for(let[r,i]of n)if(n.has(i))throw new ue("NATIVE_PARENT_READ_MULTI_HOP_FORBIDDEN",`${o}/${t.findIndex(d=>d.resourceCode===r)}`)}function lo(e){return jr(e,"/dataPolicy").some(t=>t.rule.parentRead!==void 0)}var Br=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Kr=(e,t)=>Object.keys(e).length===t.length&&Object.keys(e).every(o=>t.includes(o)),Mr=e=>typeof e=="string"&&/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/.test(e)&&e.length<=100,Ur=e=>typeof e=="string"&&/^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(e);function uo(e){throw new Error(`OPENXIANGDA_WORKFLOW_STAGE_${e}`)}function Gr(e){(!Br(e)||!Kr(e,["workflowCode","resourceCode","actor","runningNodeIds","allowedStatuses"])||!Mr(e.workflowCode)||!Mr(e.resourceCode)||!["initiator","reader"].includes(String(e.actor))||!Array.isArray(e.runningNodeIds)||e.runningNodeIds.length>32||new Set(e.runningNodeIds).size!==e.runningNodeIds.length||e.runningNodeIds.some(t=>typeof t!="string"||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(t))||!Array.isArray(e.allowedStatuses)||e.allowedStatuses.length>5||new Set(e.allowedStatuses).size!==e.allowedStatuses.length||e.allowedStatuses.some(t=>!["approved","rejected","cancelled","terminated","returned"].includes(t))||e.runningNodeIds.length+e.allowedStatuses.length===0)&&uo("POLICY_INVALID")}function Bl(e){(!Br(e)||!Kr(e,["instanceId","subjectRecordId","expectedInstanceSequence"])||!Ur(e.instanceId)||!Ur(e.subjectRecordId)||!Number.isSafeInteger(e.expectedInstanceSequence)||e.expectedInstanceSequence<0)&&uo("GUARD_INVALID")}function Kl(e,t,o){o?.some(n=>(n.kind==="record-match"||n.kind==="record-assert")&&n.resourceCode===e.resourceCode&&n.id.toLowerCase()===t.subjectRecordId.toLowerCase()&&n.assertions.some(r=>r.kind==="value"&&r.field==="revision"&&r.operator==="eq"&&Number.isSafeInteger(r.value)&&Number(r.value)>0))||uo("SOURCE_GUARD_REQUIRED")}var Gl={type:"object",additionalProperties:!1,required:["workflowCode","resourceCode","actor","runningNodeIds","allowedStatuses"],properties:{workflowCode:{type:"string",pattern:"^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$",maxLength:100},resourceCode:{type:"string",pattern:"^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$",maxLength:100},actor:{enum:["initiator","reader"]},runningNodeIds:{type:"array",maxItems:32,uniqueItems:!0,items:{type:"string",pattern:"^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$"}},allowedStatuses:{type:"array",maxItems:5,uniqueItems:!0,items:{enum:["approved","rejected","cancelled","terminated","returned"]}}},anyOf:[{properties:{runningNodeIds:{minItems:1}}},{properties:{allowedStatuses:{minItems:1}}}]};var Nt=class extends Error{constructor(o,n){super(o);this.code=o;this.pointer=n}code;pointer},fe=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},zr=(e,t)=>e===t||e==="*"||e.endsWith(":*")&&t.startsWith(e.slice(0,-1));function qr(e){let{policy:t,resource:o,baselineRoleCode:n,baselineCapabilities:r,pointer:i}=e,d=A=>A===void 0||A===!0||Array.isArray(A)&&A.length>0&&A.every(O=>typeof O=="string"&&O.length>0&&!e.baselineDeniedCapabilities?.some(b=>zr(b,O))&&r.some(b=>zr(b,O))),s=(A,O="")=>{throw new Nt(A,`${i}/publicRead${O}`)},a=fe(t.publicRead);(!t.publicRead||Object.keys(a).length!==1||!Object.hasOwn(a,"fields")||!Array.isArray(a.fields)||a.fields.length<1||a.fields.length>1e3||a.fields.some(A=>typeof A!="string"||!/^[A-Za-z][A-Za-z0-9_]{0,62}$/.test(A))||new Set(a.fields).size!==a.fields.length)&&s("AUTHENTICATED_PUBLIC_READ_FIELDS_INVALID","/fields"),(!Array.isArray(t.operations)||t.operations.length!==1||t.operations[0]!=="read"||t.readExpression!==void 0||t.writeBoundary!==void 0)&&s("AUTHENTICATED_PUBLIC_READ_POLICY_NOT_READ_ONLY"),(!n||!o||o.code!==t.resourceCode||o.dataPolicyCode!==t.code||!d([fe(o.capabilities).read]))&&s("AUTHENTICATED_PUBLIC_READ_BASELINE_OR_RESOURCE_INVALID");let c=fe(o),f=fe(c.schema).fields;(!Array.isArray(f)||!f.length)&&s("AUTHENTICATED_PUBLIC_READ_RESOURCE_FIELDS_MISSING");let u=new Map(f.map(A=>[String(fe(A).code),fe(A)])),p=new Set(a.fields),_=fe(c.fieldPolicies);for(let A of p){let O=fe(u.get(A));(!u.has(A)||O.system===!0||fe(fe(c.surface).fields)[A]?.system===!0||nt.has(A))&&s("AUTHENTICATED_PUBLIC_READ_FIELD_NOT_DECLARED",`/fields/${A}`),(O.type==="subtable"||O.subtable!==void 0)&&s("AUTHENTICATED_PUBLIC_READ_SUBTABLE_UNSUPPORTED",`/fields/${A}`),d(fe(_[A]).read)||s("AUTHENTICATED_PUBLIC_READ_FIELD_NOT_BASELINE_READABLE",`/fields/${A}`)}let E=[...u.keys()].filter(A=>!p.has(A));for(let A of E)d(fe(_[A]).read)&&s("AUTHENTICATED_PUBLIC_READ_PRIVATE_FIELD_ACCESSIBLE",`/fields/${A}`);E.length&&Kt.some(A=>d(fe(_[A]).read))&&s("AUTHENTICATED_PUBLIC_READ_PRIVATE_HISTORY_ACCESSIBLE")}var Jr=["exact-v1","nfkc-space-v1","nfkc-upper-ascii-v1"],Yl=256,Rt=class extends Error{constructor(o,n){super(`\u6761\u4EF6\u552F\u4E00\u952E\u58F0\u660E\u65E0\u6548\uFF1A${n}\uFF08${o}\uFF09`);this.pointer=o;this.reason=n}pointer;reason;code="NATIVE_UNIQUE_KEY_INVALID"},fo=e=>!!(e&&typeof e=="object"&&!Array.isArray(e)),re=(e,t)=>{throw new Rt(e,t)},Zt=(e,t)=>e<t?-1:e>t?1:0,Tt=(e,t,o)=>{Object.keys(e).some(n=>!t.includes(n))&&re(o,"\u4E0D\u652F\u6301\u672A\u77E5\u5C5E\u6027")};function Hr(e,t,o="/uniqueKeys"){if(e===void 0)return;if(!Array.isArray(e)||e.length>8)return re(o,"\u6BCF\u8D44\u6E90\u6700\u591A 8 \u6761\u89C4\u5219");let n=new Map(t.map(i=>[i.code,i])),r=new Set;return e.map((i,d)=>{let s=`${o}/${d}`;if(!fo(i))return re(s,"\u89C4\u5219\u5FC5\u987B\u662F\u5BF9\u8C61");if(Tt(i,["code","fields","when"],s),typeof i.code!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(i.code)||i.code.length>20||r.has(i.code))return re(`${s}/code`,"\u9700\u8981\u4E0D\u91CD\u590D\u4E14\u4E0D\u8D85\u8FC7 20 \u5B57\u7B26\u7684 lower-kebab-case \u6807\u8BC6");if(r.add(i.code),!Array.isArray(i.fields)||i.fields.length<1||i.fields.length>4)return re(`${s}/fields`,"\u5FC5\u987B\u9009\u62E9 1 \u5230 4 \u4E2A\u5B57\u6BB5");let a=new Set,c=i.fields.map((_,E)=>{let A=`${s}/fields/${E}`;if(!fo(_))return re(A,"\u5B57\u6BB5\u5FC5\u987B\u662F\u5BF9\u8C61");Tt(_,["fieldCode","normalizer"],A);let O=n.get(_.fieldCode);if(!O||!["text.short","uuid","option.single","resource-ref.single","user.single"].includes(O.type)||a.has(_.fieldCode))return re(`${A}/fieldCode`,"\u9700\u8981\u4E0D\u91CD\u590D\u7684\u77ED\u6587\u672C\u3001UUID\u3001\u5355\u9009\u3001\u5355\u8BB0\u5F55\u5F15\u7528\u6216\u5355\u4EBA\u5B57\u6BB5");a.add(_.fieldCode);let b=_.normalizer===void 0?"exact-v1":_.normalizer;return!Jr.includes(b)||O.type!=="text.short"&&b!=="exact-v1"?re(`${A}/normalizer`,"\u5F52\u4E00\u5316\u65B9\u5F0F\u4E0D\u652F\u6301\u6216\u4E0E\u5B57\u6BB5\u7C7B\u578B\u4E0D\u7B26"):{fieldCode:O.code,normalizer:b}}).sort((_,E)=>Zt(_.fieldCode,E.fieldCode)),f=i.when===void 0?[]:i.when;if(!Array.isArray(f)||f.length>4)return re(`${s}/when`,"\u6700\u591A 4 \u4E2A\u5408\u53D6\u6761\u4EF6");let u=new Set,p=f.map((_,E)=>{let A=`${s}/when/${E}`;if(!fo(_))return re(A,"\u6761\u4EF6\u5FC5\u987B\u662F\u5BF9\u8C61");let O=n.get(_.fieldCode);if(!O)return re(`${A}/fieldCode`,"\u5B57\u6BB5\u4E0D\u5B58\u5728");let b;if(_.operator==="empty"||_.operator==="nonempty"){if(Tt(_,["fieldCode","operator"],A),O.type!=="text.short")return re(A,"\u7A7A\u503C\u6761\u4EF6\u4EC5\u652F\u6301\u77ED\u6587\u672C");b={fieldCode:O.code,operator:_.operator}}else if(_.operator==="in"||_.operator==="notIn"){Tt(_,["fieldCode","operator","values"],A);let I=new Set((O.options??[]).map(T=>T.value));if(O.type!=="option.single"||!Array.isArray(_.values)||_.values.length<1||_.values.length>16||_.values.some(T=>typeof T!="string"||T.length<1||T.length>128||!I.has(T))||new Set(_.values).size!==_.values.length)return re(A,"\u96C6\u5408\u6761\u4EF6\u9700\u8981 1 \u5230 16 \u4E2A\u4E0D\u91CD\u590D\u7684\u5DF2\u58F0\u660E\u5355\u9009\u503C");b={fieldCode:O.code,operator:_.operator,values:[..._.values].sort(Zt)}}else if(_.operator==="eq"||_.operator==="ne"){if(Tt(_,["fieldCode","operator","value"],A),O.type!=="boolean"||typeof _.value!="boolean")return re(A,"\u7B49\u503C\u6761\u4EF6\u4EC5\u652F\u6301\u5E03\u5C14\u5B57\u6BB5\u548C\u5E03\u5C14\u503C");b={fieldCode:O.code,operator:_.operator,value:_.value}}else return re(`${A}/operator`,"\u53EA\u652F\u6301 empty\u3001nonempty\u3001in\u3001notIn \u548C\u5E03\u5C14 eq\u3001ne");let g=JSON.stringify(b);return u.has(g)?re(A,"\u6761\u4EF6\u4E0D\u80FD\u91CD\u590D"):(u.add(g),b)}).sort((_,E)=>Zt(JSON.stringify(_),JSON.stringify(E)));return{code:i.code,fields:c,when:p}}).sort((i,d)=>Zt(i.code,d.code))}function Yr(e,t){let o=new Set(e.filter(n=>n.type==="user.single").map(n=>n.code));return t?.some(n=>n.fields.some(r=>o.has(r.fieldCode))||n.when?.some(r=>r.operator==="eq"||r.operator==="ne"))?"1.1.0":"1.0.0"}var Qt={type:"string",pattern:"^[A-Za-z_][A-Za-z0-9_]{0,62}$"},Xl={type:"array",maxItems:8,items:{type:"object",additionalProperties:!1,required:["code","fields"],properties:{code:{type:"string",maxLength:20,pattern:"^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$"},fields:{type:"array",minItems:1,maxItems:4,uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["fieldCode"],properties:{fieldCode:Qt,normalizer:{enum:[...Jr]}}}},when:{type:"array",maxItems:4,uniqueItems:!0,items:{oneOf:[{type:"object",additionalProperties:!1,required:["fieldCode","operator"],properties:{fieldCode:Qt,operator:{enum:["empty","nonempty"]}}},{type:"object",additionalProperties:!1,required:["fieldCode","operator","values"],properties:{fieldCode:Qt,operator:{enum:["in","notIn"]},values:{type:"array",minItems:1,maxItems:16,uniqueItems:!0,items:{type:"string",minLength:1,maxLength:128}}}},{type:"object",additionalProperties:!1,required:["fieldCode","operator","value"],properties:{fieldCode:Qt,operator:{enum:["eq","ne"]},value:{type:"boolean"}}}]}}}}};var Xr={"openxiangda.workflow.instance.completed.v2":"commit","openxiangda.workflow.instance.rejected.v2":"release","openxiangda.workflow.instance.withdrawn.v2":"release"};function Zr(e,t){let o=()=>{throw new Error("NATIVE_EVENT_DECIMAL_RESERVATION_INVALID")},n=p=>!p||typeof p!="object"||Array.isArray(p)?o():p,r=n(e);if(Object.keys(r).some(p=>!["resourceCode","workflowCode","outcomes"].includes(p))||typeof r.resourceCode!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(r.resourceCode)||typeof r.workflowCode!="string"||!/^[A-Za-z0-9._:-]{1,128}$/.test(r.workflowCode)||t.execution!==void 0||!Array.isArray(r.outcomes)||!r.outcomes.length||r.outcomes.length>3)return o();let i=t.resources.find(p=>p.code===r.resourceCode),d=t.reservations.find(p=>p.mode==="reserve"&&p.resourceCode===r.resourceCode),s=t.workflows.find(p=>p.code===r.workflowCode);if(!i||!d||!s||s.resourceCode!==i.code)return o();let a=i.fields.find(p=>p.code===d.statusFieldCode);if(a?.type!=="option.single")return o();let c=new Set(a.options?.map(p=>p.value)),f=new Set,u=r.outcomes.map(p=>{let _=n(p),E=_.eventType;return Object.keys(_).some(A=>!["eventType","mode","eligibleChildStatuses"].includes(A))||typeof E!="string"||!Object.prototype.hasOwnProperty.call(Xr,E)||!t.eventTypes.includes(E)||f.has(E)||_.mode!==Xr[E]||!Array.isArray(_.eligibleChildStatuses)||!_.eligibleChildStatuses.length||_.eligibleChildStatuses.length>16||new Set(_.eligibleChildStatuses).size!==_.eligibleChildStatuses.length||_.eligibleChildStatuses.some(A=>typeof A!="string"||!/^[A-Za-z0-9._:-]{1,128}$/.test(A)||!c.has(A))?o():(f.add(E),{eventType:E,mode:_.mode,eligibleChildStatuses:[..._.eligibleChildStatuses].sort()})}).sort((p,_)=>p.eventType.localeCompare(_.eventType));return{resourceCode:r.resourceCode,workflowCode:r.workflowCode,outcomes:u}}function Qr(e,t){let o=n=>Array.isArray(n)?n.filter(r=>r&&typeof r=="object"&&!Array.isArray(r)):[];return{eventTypes:Array.isArray(t.eventTypes)?t.eventTypes:[],execution:t.execution,resources:o(e.data?.resources).map(n=>({code:n.code,fields:o(n.schema?.fields).map(r=>({code:r.code,type:r.type,options:o(r.options).map(i=>({value:i.value}))}))})),reservations:o(e.backend?.operations).flatMap(n=>n.platformAccess?.decimalReservation?[n.platformAccess.decimalReservation]:[]),workflows:o(e.workflows?.definitions).map(n=>({code:n.definition?.code,resourceCode:n.definition?.subject?.resourceCode}))}}var po=class extends Error{constructor(o,n){super(n);this.pointer=o}pointer;code="NATIVE_EVENT_ACTION_INVALID"};function ei(e,t,o="/events/subscriptions"){if(e.execution===void 0)return;let n=(A,O)=>{throw new po(`${o}${A}`,O)},r=(A,O,b)=>((!A||typeof A!="object"||Array.isArray(A)||Object.keys(A).some(g=>!b.includes(g)))&&n(O,"Invalid action object or unsupported property"),A),i=r(e.execution,"/execution",["kind","version","operations"]);(i.kind!=="native-data"||i.version!==1)&&n("/execution","Expected native-data version 1"),e.platformAccess&&n("/platformAccess","Native actions do not use application runtime capabilities"),(!Array.isArray(e.eventTypes)||!e.eventTypes.length||e.eventTypes.some(A=>!/^openxiangda\.data\.record\.(created|updated|deleted)\.v2$/.test(A)))&&n("/eventTypes","Native data actions require declared data events");let d=e.filter?.resourceCodes;(!Array.isArray(d)||!d.length||d.length>20)&&n("/filter/resourceCodes","Native actions require explicit source resources");let s=new Map(t.map(A=>[A.code,A])),a=d.map(A=>{let O=s.get(A);return O||n("/filter/resourceCodes","Unknown source resource"),new Set((O.schema?.fields||[]).map(b=>b.code))}),c=new Set(e.payload?.fields||[]),f=e.payload?.includeChanges===!0,u=(A,O)=>{let b=r(A,O,["source","path","value"]);if(b.source==="literal"){(!Object.hasOwn(b,"value")||Object.hasOwn(b,"path"))&&n(O,"Literal binding requires only value");let l;try{l=JSON.stringify(b.value)}catch{n(O,"Literal must be JSON")}return(l===void 0||Buffer.byteLength(l)>65536)&&n(O,"Literal is too large or not JSON"),{source:"literal",value:JSON.parse(l)}}(b.source!=="event"||typeof b.path!="string"||Object.hasOwn(b,"value"))&&n(O,"Expected a literal or event binding");let g=b.path.split(".");(g.length>8||g.some(l=>!/^[A-Za-z0-9_-]+$/.test(l)||["__proto__","prototype","constructor"].includes(l)))&&n(O,"Invalid event path");let I=/^data\.projection\.([A-Za-z][A-Za-z0-9_]{0,62})$/.exec(b.path),T=/^data\.changes\.([A-Za-z][A-Za-z0-9_]{0,62})\.(before|after)$/.exec(b.path);if(I||T){let l=(I||T)[1];a.some(y=>!y.has(l))&&n(O,"Source field must exist on every filtered resource"),c.add(l),T&&(f=!0)}else["id","time","type","subject","data.recordId","data.revision","data.operation","data.resourceCode"].includes(b.path)||n(O,"Event path is not part of the data event contract");return{source:"event",path:b.path}};(!Array.isArray(i.operations)||i.operations.length<1||i.operations.length>16)&&n("/execution/operations","Expected 1 to 16 operations");let p={},_=i.operations.map((A,O)=>{let b=`/execution/operations/${O}`,g=r(A,b,["operation","resourceCode","data","id","expectedRevision"]);["create","update","delete"].includes(g.operation)||n(b,"Unsupported Native operation");let I=s.get(g.resourceCode);I||n(b,"Unknown action target resource");let T=new Map((I.schema?.fields||[]).map(y=>[y.code,y])),l=g.data===void 0?{}:r(g.data,`${b}/data`,[...T.keys()]);return Object.keys(l).length>32&&n(b,"Maximum 32 mapped fields per operation"),g.operation==="create"&&(g.id!==void 0||g.expectedRevision!==void 0)&&n(b,"Create does not accept id or expectedRevision"),g.operation==="delete"&&g.data!==void 0&&n(b,"Delete does not accept data"),Object.keys(l).some(y=>T.get(y)?.type==="serial-number")&&n(b,"Generated fields cannot be assigned"),p[g.resourceCode]=Z(I),{operation:g.operation,resourceCode:g.resourceCode,...g.operation==="create"?{}:{id:u(g.id,`${b}/id`),expectedRevision:u(g.expectedRevision,`${b}/expectedRevision`)},...g.operation==="delete"?{}:{data:Object.fromEntries(Object.entries(l).map(([y,R])=>[y,u(R,`${b}/data/${y}`)]))}}});(c.size>32||[...c].some(A=>a.some(O=>!O.has(A))))&&n("/payload/fields","Payload must contain at most 32 declared source fields");let E={kind:"native-data",version:1,operations:_,resourceDigests:p};return Buffer.byteLength(JSON.stringify(E))>65536&&n("/execution","Action plan exceeds 64 KiB"),{execution:{...E,digest:Z(E)},payload:{includeChanges:f,fields:[...c].sort()}}}function Ve(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function ni(e,t){if(e?.instanceCommands===void 0)return[];let o=Ve(e.instanceCommands);if(!o||!Object.keys(o).length||Object.keys(o).some(r=>!["withdraw","terminate"].includes(r)))return["WORKFLOW_INSTANCE_COMMAND_POLICIES_INVALID"];let n=[];for(let[r,i]of Object.entries(o)){let d=Ve(i),s=r==="withdraw"?["beforeFact","reasonRequired"]:["beforeFact","capability"];if(!d||!Object.keys(d).length||Object.keys(d).some(a=>!s.includes(a))||Object.hasOwn(d,"reasonRequired")&&typeof d.reasonRequired!="boolean"){n.push(`WORKFLOW_INSTANCE_COMMAND_POLICY_INVALID:${r}`);continue}if(r==="terminate"){let a=d.capability;(typeof a!="string"||a.length>255||!/^app:[a-z][a-z0-9]*(?:-[a-z0-9]+)*:[A-Za-z0-9:._-]+$/.test(a)||t&&(!a.startsWith(`app:${t.appCode}:`)||!t.capabilities.includes(a)))&&n.push("WORKFLOW_INSTANCE_TERMINATE_CAPABILITY_INVALID")}if(Object.hasOwn(d,"beforeFact")){let a=d.beforeFact,c=Ve(e.inputSchema),f=Ve(Ve(c?.properties)?.[a]),u=Ve(Ve(e.subject)?.factProjection)?.[a],p=t?.fields.get(u);(typeof a!="string"||!/^[A-Za-z][A-Za-z0-9_]{0,62}$/.test(a)||!Array.isArray(c?.required)||!c.required.includes(a)||f?.type!=="string"||f?.format!=="date-time"||typeof u!="string"||t&&(p?.type!=="datetime"||p.nullable===!0))&&n.push(`WORKFLOW_INSTANCE_COMMAND_DEADLINE_FACT_INVALID:${r}`)}}return n}function nu(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 ou(e){return e?.withdraw?.reasonRequired!==!1}function ti(e){if(typeof e!="string")return null;let t=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,3}))?(Z|[+-]\d{2}:\d{2})$/.exec(e);if(!t)return null;let[,o,n,r,i,d,s]=t,a=t[8],c=new Date(Date.UTC(Number(o),Number(n),0)).getUTCDate();if(Number(n)<1||Number(n)>12||Number(r)<1||Number(r)>c||Number(i)>23||Number(d)>59||Number(s)>59||a!=="Z"&&(Number(a.slice(1,3))>23||Number(a.slice(4))>59))return null;let f=Date.parse(e);return Number.isFinite(f)?f:null}function ru(e,t,o,n){let r=e?.[t];if(!r||r.beforeFact===void 0)return null;let i=r.beforeFact,d=Ve(o),s=i&&d&&Object.hasOwn(d,i)?ti(d[i]):null,a=n instanceof Date?n.getTime():ti(n);return s===null||a===null||!Number.isFinite(a)?"WORKFLOW_V2_CANCELLATION_DEADLINE_INVALID":a<s?null:"WORKFLOW_V2_CANCELLATION_DEADLINE_PASSED"}var Ct="openxiangda.workflow.step.requested.v2",ii=[Ct,"openxiangda.workflow.step.result_received.v2","openxiangda.workflow.step.completed.v2","openxiangda.workflow.step.continuation_failed.v2"],go=16384,ja=2048,su="steps",Ao=/^[A-Za-z][A-Za-z0-9_-]{0,127}$/,si=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,Ge=new Set(["__proto__","prototype","constructor"]),K=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&[Object.prototype,null].includes(Object.getPrototypeOf(e)),ai=e=>{try{let t=JSON.stringify(e);return t===void 0?1/0:new TextEncoder().encode(t).length}catch{return 1/0}},at=(e,t,o=0)=>{if(o>32)return!1;if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((i,d)=>at(i,t[d],o+1));if(!K(e)||!K(t))return!1;let n=Object.keys(e).filter(i=>e[i]!==void 0),r=Object.keys(t).filter(i=>t[i]!==void 0);return n.length===r.length&&n.every(i=>Object.hasOwn(t,i)&&at(e[i],t[i],o+1))};function mo(e,t){let o=0,n=(r,i)=>++o>1e4||i>8?!1:r===null||typeof r=="boolean"||typeof r=="string"?!0:typeof r=="number"?Number.isFinite(r):Array.isArray(r)?r.length<=200&&r.every(d=>n(d,i+1)):K(r)&&Object.keys(r).length<=32&&Object.keys(r).every(d=>!Ge.has(d))&&Object.values(r).every(d=>n(d,i+1));return ai(e)<=t&&n(e,0)}function Wa(e){return!K(e)||Object.keys(e).some(t=>!["executionId","handlerVersion","inputDigest","expectedFactRevision","output","receipt"].includes(t))?!1:/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/i.test(e.executionId||"")&&Number.isSafeInteger(e.handlerVersion)&&e.handlerVersion>=1&&e.handlerVersion<=1e6&&/^[a-f0-9]{64}$/.test(e.inputDigest||"")&&Number.isSafeInteger(e.expectedFactRevision)&&e.expectedFactRevision>=0&&K(e.output)&&mo(e.output,go)&&(e.receipt===void 0||K(e.receipt)&&mo(e.receipt,ja))}function au(e){return K(e)&&Object.keys(e).every(t=>["executionId","nodeId","handlerCode","handlerVersion","mode","dataTransaction","input","inputDigest","expectedFactRevision"].includes(t))&&typeof e.nodeId=="string"&&Ao.test(e.nodeId)&&!Ge.has(e.nodeId)&&typeof e.handlerCode=="string"&&/^[a-z][a-z0-9-]{0,100}$/.test(e.handlerCode)&&e.handlerCode.endsWith(`-v${e.handlerVersion}`)&&["pure","reconciled-effect"].includes(e.mode)&&(e.dataTransaction===void 0||e.dataTransaction===!0&&e.mode==="reconciled-effect")&&Wa({executionId:e.executionId,handlerVersion:e.handlerVersion,inputDigest:e.inputDigest,expectedFactRevision:e.expectedFactRevision,output:e.input})}function en(e,t,o=go){if(!mo(t,o))return!1;let n=1e4,r=(i,d,s)=>{if(--n<0||s>8||!K(i))return!1;let a=d===null?"null":Array.isArray(d)?"array":typeof d=="number"&&Number.isSafeInteger(d)?"integer":typeof d,c=Array.isArray(i.type)?i.type:[i.type];if(!c.includes(a)&&!(a==="integer"&&c.includes("number"))||i.enum!==void 0&&(!Array.isArray(i.enum)||!i.enum.some(f=>at(f,d)))||Object.hasOwn(i,"const")&&!at(i.const,d))return!1;if(typeof d=="number")return Number.isFinite(d)&&(i.minimum===void 0||d>=i.minimum)&&(i.maximum===void 0||d<=i.maximum);if(typeof d=="string"){let f=Array.from(d).length;return(i.minLength===void 0||f>=i.minLength)&&(i.maxLength===void 0||f<=i.maxLength)}return Array.isArray(d)?d.length<=i.maxItems&&(i.minItems===void 0||d.length>=i.minItems)&&d.every(f=>r(i.items,f,s+1)):K(d)?!K(i.properties)||Object.keys(d).some(f=>Ge.has(f)||!Object.hasOwn(i.properties,f))||(Array.isArray(i.required)?i.required:[]).some(f=>!Object.hasOwn(d,f))||i.minProperties!==void 0&&Object.keys(d).length<i.minProperties||i.maxProperties!==void 0&&Object.keys(d).length>i.maxProperties?!1:Object.entries(d).every(([f,u])=>r(i.properties[f],u,s+1)):d===null||typeof d=="boolean"};return r(e,t,0)}function Ma(e){return typeof e=="string"&&e.length<=256&&e.split(".").length<=8&&e.split(".").every(t=>Ao.test(t)&&!Ge.has(t))}function tn(e){let t=0,o=(n,r)=>{if(!K(n)||r>6||++t>256||Object.keys(n).some(s=>!["type","title","description","properties","required","additionalProperties","items","maxItems","minItems","maxLength","minLength","minimum","maximum","enum","const","maxProperties","minProperties"].includes(s)))return!1;let i=Array.isArray(n.type)?n.type:[n.type];if(!i.length||i.length>2||i.some(s=>!["object","array","string","integer","number","boolean","null"].includes(s))||i.length>1&&(!i.includes("null")||new Set(i).size!==i.length))return!1;for(let s of["title","description"])if(n[s]!==void 0&&(typeof n[s]!="string"||n[s].length>2e3))return!1;for(let s of["minimum","maximum"])if(n[s]!==void 0&&(typeof n[s]!="number"||!Number.isFinite(n[s])))return!1;for(let[s,a]of[["maxItems",200],["minItems",200],["maxLength",16384],["minLength",16384],["maxProperties",32],["minProperties",32]])if(n[s]!==void 0&&(!Number.isSafeInteger(n[s])||n[s]<0||n[s]>a))return!1;for(let[s,a]of[["minimum","maximum"],["minItems","maxItems"],["minLength","maxLength"],["minProperties","maxProperties"]])if(n[s]!==void 0&&n[a]!==void 0&&n[s]>n[a])return!1;if(["properties","required","additionalProperties","maxProperties","minProperties"].some(s=>n[s]!==void 0)&&!i.includes("object")||["items","maxItems","minItems"].some(s=>n[s]!==void 0)&&!i.includes("array")||["maxLength","minLength"].some(s=>n[s]!==void 0)&&!i.includes("string")||["minimum","maximum"].some(s=>n[s]!==void 0)&&!i.some(s=>s==="integer"||s==="number")||n.enum!==void 0&&(!Array.isArray(n.enum)||!n.enum.length||n.enum.length>100)||i.includes("object")&&(!K(n.properties)||n.additionalProperties!==!1||Object.keys(n.properties).length>32||Object.keys(n.properties).some(s=>!si.test(s)||Ge.has(s))||n.required!==void 0&&(!Array.isArray(n.required)||new Set(n.required).size!==n.required.length||n.required.some(s=>typeof s!="string"||!Object.hasOwn(n.properties,s)))||n.minProperties!==void 0&&n.minProperties>Object.keys(n.properties).length||n.maxProperties!==void 0&&n.maxProperties<(n.required?.length||0)||!Object.values(n.properties).every(s=>o(s,r+1)))||i.includes("array")&&(!Number.isSafeInteger(n.maxItems)||!o(n.items,r+1)))return!1;let d={...n};return delete d.enum,delete d.const,!(n.enum!==void 0&&(!n.enum.every(s=>en(d,s))||n.enum.some((s,a)=>n.enum.slice(0,a).some(c=>at(s,c))))||Object.hasOwn(n,"const")&&!en(d,n.const))};return K(e)&&e.type==="object"&&ai(e)<=go&&o(e,0)}function nn(e){let t=Object.fromEntries(Object.values(e.nodes||{}).filter(o=>o?.kind==="action").map(o=>[o.id,o.outputSchema]));return Object.keys(t).length?{...e.inputSchema,properties:{...e.inputSchema?.properties,steps:{type:"object",additionalProperties:!1,properties:t}}}:e.inputSchema||{}}function di(e,t){let o=e;for(let n of t.split(".")){if(!K(o?.properties)||!Object.hasOwn(o.properties,n))return;o=o.properties[n]}return K(o)?o:void 0}var oi=(e,t)=>!!di(e,t);function du(e){return K(e)&&Object.keys(e).every(t=>["version","mode","dataTransaction","inputSchema","outputSchema"].includes(t))&&Number.isSafeInteger(e.version)&&e.version>=1&&e.version<=1e6&&["pure","reconciled-effect"].includes(e.mode)&&(e.dataTransaction===void 0||e.dataTransaction===!0&&e.mode==="reconciled-effect")&&tn(e.inputSchema)&&tn(e.outputSchema)}function ri(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 _o(e,t=0){return!K(e)||t>16?[]:e.op==="path"?typeof e.path=="string"?[e.path]:[]:["left","right","value"].flatMap(o=>_o(e[o],t+1)).concat(Array.isArray(e.values)?e.values.flatMap(o=>_o(o,t+1)):[])}function on(e,t){if(!K(e)||!K(e.nodes))return["WORKFLOW_STEP_DEFINITION_INVALID"];let o=e.nodes,n=Object.entries(o).filter(([,s])=>s?.kind==="action");if(!n.length)return[];let r=[];Object.hasOwn(e.inputSchema?.properties||{},"steps")&&r.push("WORKFLOW_STEP_FACT_NAMESPACE_RESERVED");let i=nn(e);for(let[s,a]of n){(Object.keys(a).some(u=>!["id","kind","title","next","handler","inputSchema","outputSchema","inputs"].includes(u))||a.id!==s||!Ao.test(s)||Ge.has(s)||typeof a.title!="string"||!a.title.trim()||a.title.length>255||typeof a.next!="string"||!Object.hasOwn(o,a.next))&&r.push(`WORKFLOW_STEP_NODE_INVALID:${s}`);let c=a.handler;(!K(c)||Object.keys(c).some(u=>!["code","version","mode","dataTransaction"].includes(u))||!Number.isSafeInteger(c.version)||c.version<1||c.version>1e6||!/^[a-z][a-z0-9-]{0,100}$/.test(c.code||"")||!String(c.code).endsWith(`-v${c.version}`)||!["pure","reconciled-effect"].includes(c.mode)||c.dataTransaction!==void 0&&(c.dataTransaction!==!0||c.mode!=="reconciled-effect"))&&r.push(`WORKFLOW_STEP_HANDLER_INVALID:${s}`);let f=tn(a.inputSchema);if((!f||!tn(a.outputSchema))&&r.push(`WORKFLOW_STEP_SCHEMA_INVALID:${s}`),!K(a.inputs)||Object.keys(a.inputs).length>32){r.push(`WORKFLOW_STEP_INPUTS_INVALID:${s}`);continue}for(let u of Array.isArray(a.inputSchema?.required)?a.inputSchema.required:[])Object.hasOwn(a.inputs,u)||r.push(`WORKFLOW_STEP_INPUT_REQUIRED:${s}:${u}`);for(let[u,p]of Object.entries(a.inputs)){if(!si.test(u)||Ge.has(u)||!Object.hasOwn(a.inputSchema?.properties||{},u)||!K(p)){r.push(`WORKFLOW_STEP_INPUT_INVALID:${s}:${u}`);continue}if(p.source==="literal")(!f||Object.keys(p).some(_=>!["source","value"].includes(_))||!Object.hasOwn(p,"value")||!en(a.inputSchema.properties[u],p.value))&&r.push(`WORKFLOW_STEP_LITERAL_INVALID:${s}:${u}`);else if(p.source!=="fact"||Object.keys(p).some(_=>!["source","path"].includes(_))||!Ma(p.path)||!oi(i,p.path))r.push(`WORKFLOW_STEP_FACT_PATH_INVALID:${s}:${u}`);else if(f){let _=di(i,p.path),E=a.inputSchema.properties[u],A=Array.isArray(_.type)?_.type:[_.type],O=Array.isArray(E.type)?E.type:[E.type];A.some(b=>!O.includes(b)&&!(b==="integer"&&O.includes("number")))&&r.push(`WORKFLOW_STEP_FACT_TYPE_MISMATCH:${s}:${u}`)}}}let d=(s,a)=>{let c=new Set,f=[e.startAt||""];for(;f.length&&c.size<=200;){let u=f.shift();if(!(u===a||c.has(u)||!o[u])){if(u===s)return!0;c.add(u),f.push(...ri(o[u]))}}return!1};for(let[s,a]of Object.entries(o)){if(!K(a))continue;let c=a.kind==="action"?Object.values(a.inputs||{}).flatMap(u=>u?.source==="fact"?[u.path]:[]):(Array.isArray(a.branches)?a.branches:[]).flatMap(u=>_o(u?.when)),f=t?.bindings?.[a.binding];f&&c.push(...[f.inputPath,f.departmentIdFrom,f.resourceIdFrom,f.scope?.valueFrom].filter(u=>typeof u=="string"));for(let u of c.filter(p=>typeof p=="string"&&p.startsWith("steps."))){let p=u.split(".")[1];(o[p]?.kind!=="action"||p===s||!oi(i,u)||d(s,p))&&r.push(`WORKFLOW_STEP_OUTPUT_NOT_AVAILABLE:${s}:${u}`)}}if(t)for(let[,s]of n){let a=new Set,c=[s.next];for(;c.length&&a.size<=200;){let f=c.shift();if(a.has(f)||!K(o[f]))continue;a.add(f);let u=o[f];if(!(u.kind==="action"||u.kind==="end")){if(u.kind==="approval"){let p=t.bindings?.[u.binding];p&&["application_provider","initiator_select"].includes(p.provider)&&r.push(`WORKFLOW_STEP_NEXT_PROVIDER_REQUIRES_PREPARED_RESULT:${f}`);continue}c.push(...ri(u))}}}return[...new Set(r)]}function cu(e,t){let o={};for(let[n,r]of Object.entries(e.inputs)){let i=r.source==="literal"?r.value:r.path.split(".").reduce((d,s)=>K(d)&&Object.hasOwn(d,s)?d[s]:void 0,t);i!==void 0&&(o[n]=i)}if(!en(e.inputSchema,o))throw new Error("WORKFLOW_STEP_INPUT_SCHEMA_INVALID");return o}function ci(e,t,o){let n=Eo(e),r=[];Object.keys(n).length&&!o&&r.push("WORKFLOW_STEP_BACKEND_REQUIRED");for(let i of Object.keys(n)){let d=t.find(s=>s.code===i);(!d||d.execution||d.action||!Array.isArray(d.eventTypes)||d.eventTypes.length!==1||d.eventTypes[0]!==Ct||!K(d.filter)||Object.keys(d.filter).length!==1||!K(d.filter.workflowStep)||Object.keys(d.filter.workflowStep).length!==1||d.filter.workflowStep.handlerCode!==i||!K(d.payload)||d.payload.includeChanges!==!1||!Array.isArray(d.payload.fields)||d.payload.fields.length)&&r.push(`WORKFLOW_STEP_SUBSCRIPTION_INVALID:${i}`)}for(let i of t)(i.eventTypes?.includes(Ct)&&!n[i.code]||i.filter?.workflowStep&&!n[i.code])&&r.push(`WORKFLOW_STEP_HANDLER_NOT_DECLARED:${i.code}`);return r}function Eo(e){let t={};for(let o of e){let n=on(o);if(n.length)throw new Error(n.join("; "));for(let r of Object.values(o.nodes||{})){if(r.kind!=="action")continue;let i={version:r.handler.version,mode:r.handler.mode,...r.handler.dataTransaction?{dataTransaction:!0}:{},inputSchema:r.inputSchema,outputSchema:r.outputSchema},d=t[r.handler.code];if(d&&!at(d,i))throw new Error(`WORKFLOW_STEP_HANDLER_CONTRACT_CONFLICT:${r.handler.code}`);t[r.handler.code]=i}}return t}var pe=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},ze=(e,t)=>typeof e=="string"&&!!e.trim()&&e.length<=t,Ua=/^[A-Za-z][A-Za-z0-9_-]*(?:\.[A-Za-z][A-Za-z0-9_-]*){0,15}$/,Io=e=>typeof e=="string"&&e.length<=256&&Ua.test(e)&&!e.split(".").some(t=>["__proto__","prototype","constructor"].includes(t));function sn(e,t){let o=pe(e),n=!0;for(let r of t.split(".")){n&&=Array.isArray(o.required)&&o.required.includes(r);let i=pe(o.properties)[r];if(!i||typeof i!="object")return null;o=pe(i)}return{schema:o,required:n}}function li(e){let t=new Set,o=[],n=2048,r=(i,d)=>{if(--n<0||d>20){o.push("WORKFLOW_EXPRESSION_BUDGET_EXCEEDED");return}let s=pe(i);if(s.op==="path")Io(s.path)?t.add(s.path):o.push("WORKFLOW_EXPRESSION_PATH_INVALID");else{if(s.op==="literal")return;if(s.op==="and"||s.op==="or")if(!Array.isArray(s.values)||!s.values.length||s.values.length>128)o.push("WORKFLOW_EXPRESSION_GROUP_INVALID");else for(let a of s.values){if(n<0)break;r(a,d+1)}else s.op==="not"||s.op==="exists"?r(s.value,d+1):["eq","neq","gt","gte","lt","lte","in","contains"].includes(String(s.op))?(r(s.left,d+1),r(s.right,d+1)):o.push("WORKFLOW_EXPRESSION_OPERATOR_INVALID")}};return r(e,0),{paths:[...t],errors:[...new Set(o)]}}function ui(e){if(e?.readability===void 0)return[];let t=[],o=nn(e),n=pe(e.readability);(Object.keys(n).some(s=>!["variables","logic"].includes(s))||!Object.keys(n).length)&&t.push("WORKFLOW_READABILITY_INVALID");let r=pe(n.variables);n.variables!==void 0&&(typeof n.variables!="object"||Array.isArray(n.variables)||n.variables===null)&&t.push("WORKFLOW_VARIABLES_INVALID"),Object.keys(r).length>128&&t.push("WORKFLOW_VARIABLE_LIMIT_EXCEEDED");for(let[s,a]of Object.entries(r)){let c=pe(a);(!Io(s)||!sn(o,s))&&t.push(`WORKFLOW_VARIABLE_SOURCE_UNKNOWN:${s}`),(!ze(c.label,160)||Object.keys(c).some(f=>!["label","unit","description"].includes(f))||c.unit!==void 0&&!ze(c.unit,32)||c.description!==void 0&&!ze(c.description,2e3))&&t.push(`WORKFLOW_VARIABLE_METADATA_INVALID:${s}`)}let i=n.logic===void 0?[]:n.logic;(!Array.isArray(i)||i.length>32)&&t.push("WORKFLOW_LOGIC_LIMIT_INVALID");let d=new Set;for(let s of Array.isArray(i)?i.slice(0,32):[]){let a=pe(s),c=String(a.code||"");e.approvedDelegation&&c==="kernel-approved-delegation"&&t.push("WORKFLOW_LOGIC_PLATFORM_CODE_RESERVED"),(!/^[a-z][a-z0-9-]{2,63}$/.test(c)||d.has(c)||!ze(a.title,160)||!ze(a.description,4e3)||Object.keys(a).some(f=>!["code","title","description","phase","nodeId","inputPaths","outputPaths","source"].includes(f)))&&t.push(`WORKFLOW_LOGIC_METADATA_INVALID:${c}`),d.add(c),(!["submission","node_input","completion"].includes(String(a.phase))||a.phase==="node_input"&&!pe(e.nodes)[String(a.nodeId)]||a.phase!=="node_input"&&a.nodeId!==void 0)&&t.push(`WORKFLOW_LOGIC_ANCHOR_INVALID:${c}`);for(let f of["inputPaths","outputPaths"]){let u=a[f];if(!(f==="outputPaths"&&u===void 0))if(!Array.isArray(u)||u.length>32||new Set(u).size!==u.length)t.push(`WORKFLOW_LOGIC_PATHS_INVALID:${c}:${f}`);else for(let p of u)(!Io(p)||!sn(o,p))&&t.push(`WORKFLOW_LOGIC_SOURCE_UNKNOWN:${c}:${String(p)}`)}if(a.source!==void 0){let f=pe(a.source);(!ze(f.path,256)||String(f.path).startsWith("/")||String(f.path).includes("..")||String(f.path).includes("://")||!/^sha256:[a-f0-9]{64}$/.test(String(f.digest))||f.symbol!==void 0&&!ze(f.symbol,160)||Object.keys(f).some(u=>!["path","symbol","digest"].includes(u)))&&t.push(`WORKFLOW_LOGIC_SOURCE_REFERENCE_INVALID:${c}`)}}for(let s of Object.values(pe(e.nodes))){let a=pe(s),c=Array.isArray(a.branches)?a.branches:[];for(let f of c){let u=li(f.when);t.push(...u.errors.map(p=>`${p}:${a.id}`));for(let p of u.paths)sn(o,p)||t.push(`WORKFLOW_VARIABLE_SOURCE_UNKNOWN:${a.id}:${p}`)}}return[...new Set(t)]}function fu(e,t){let o=nn(e),n=[],r=new Map,i=[];for(let c of Object.values(e.nodes)){if(c.kind==="approval")for(let[f,u,p]of[["approve",c.onApprove,"\u540C\u610F"],["reject",c.onReject,"\u62D2\u7EDD"]])u&&n.push({id:`${c.id}:${f}`,from:c.id,to:u,kind:f,label:p,variablePaths:[]});if(c.kind==="approval")for(let f of new Set(c.returnTargets||[]))e.nodes[f]?.kind==="correction"&&n.push({id:`${c.id}:return:${f}`,from:c.id,to:f,kind:"return",label:"\u9000\u56DE\u53D1\u8D77\u4EBA\u8865\u6B63",variablePaths:[]});if(c.kind==="correction"&&c.next&&n.push({id:`${c.id}:resubmit`,from:c.id,to:c.next,kind:"resubmit",label:"\u91CD\u65B0\u63D0\u4EA4\uFF0C\u4ECE\u8D77\u70B9\u91CD\u7B97",variablePaths:[]}),c.kind==="cc"&&c.next&&n.push({id:`${c.id}:next`,from:c.id,to:c.next,kind:"next",label:"\u6284\u9001\u540E\u7EE7\u7EED",variablePaths:[]}),c.kind==="action"&&c.next){let f=Object.values(c.inputs||{}).flatMap(u=>u.source==="fact"?[u.path]:[]);for(let u of f)r.has(u)||r.set(u,new Set),r.get(u).add(c.id);n.push({id:`${c.id}:next`,from:c.id,to:c.next,kind:"next",label:"\u6210\u529F\u56DE\u6267\u540E\u7EE7\u7EED",variablePaths:f})}if(c.kind==="condition"){for(let[f,u]of(c.branches||[]).entries()){let p=li(u.when);for(let _ of p.paths)r.has(_)||r.set(_,new Set),r.get(_).add(c.id);n.push({id:`${c.id}:branch:${f}`,from:c.id,to:u.target,kind:"branch",label:u.label||`\u6761\u4EF6 ${f+1}`,priority:f+1,expression:u.when,variablePaths:p.paths}),i.push(...p.errors.map(_=>({code:_,path:c.id})))}c.otherwise&&n.push({id:`${c.id}:default`,from:c.id,to:c.otherwise,kind:"default",label:"\u5747\u4E0D\u6EE1\u8DB3\u65F6",variablePaths:[]})}}let d=[...e.readability?.logic||[]];if(e.approvedDelegation){let c=e.approvedDelegation,f=c.confirmer==="initiator"?"\u7533\u8BF7\u4EBA\u672C\u4EBA":"\u6240\u9009\u4EE3\u7406\u4EBA";d.push({code:"kernel-approved-delegation",title:"\u6279\u51C6\u540E\u6574\u6279\u6388\u6743\u4EE3\u7406",phase:"completion",inputPaths:[c.requestsField],description:`\u6279\u51C6\u65F6\u6838\u9A8C${f}\u5728\u5F53\u524D\u9000\u56DE\u5468\u671F\u5B8C\u6210\u201C${e.nodes[c.confirmationNodeId]?.title||c.confirmationNodeId}\u201D\u7684\u4EBA\u5DE5\u786E\u8BA4\uFF1B\u968F\u540E\u91CD\u65B0\u6838\u9A8C\u53CC\u65B9\u5F53\u524D\u8D26\u53F7\u3001\u804C\u8D23\u3001\u4FEE\u8BA2\u3001\u8303\u56F4\u4E0E\u5B8C\u6574\u6709\u6548\u671F\uFF0C\u6574\u6279\u6388\u6743\uFF08\u6700\u591A${c.maxRequests}\u884C\uFF09\u3002\u4EFB\u4E00\u884C\u5931\u8D25\uFF0C\u6279\u51C6\u4E0E\u5168\u90E8\u6388\u6743\u4E00\u8D77\u56DE\u6EDA\uFF1B\u539F\u547D\u4EE4\u6062\u590D\u4E0D\u91CD\u65B0\u6FC0\u6D3B\u5DF2\u64A4\u9500\u6388\u6743\u3002`})}let a=[...new Set([...r.keys(),...Object.keys(e.readability?.variables||{}),...d.flatMap(c=>[...c.inputPaths,...c.outputPaths||[]])])].slice(0,128).map(c=>{let f=sn(o,c),u=e.readability?.variables?.[c],p=c.split("."),_=e.subject?.factProjection[p[0]],E=p[0]==="steps"?e.nodes[p[1]]:void 0;return f||i.push({code:"WORKFLOW_VARIABLE_SOURCE_UNKNOWN",path:c}),{path:c,label:u?.label||String(f?.schema.title||c),type:String(f?.schema.type||"unknown"),...u,required:f?.required||!1,usedBy:[...r.get(c)||[]],source:f&&E?.handler?{kind:"step_output",nodeId:E.id,handlerCode:E.handler.code,handlerVersion:E.handler.version}:f&&_&&e.subject?{kind:"subject_field",resourceCode:e.subject.resourceCode,fieldPath:[_,...p.slice(1)].join(".")}:{kind:f?"input":"unknown"}}});return{schemaVersion:"openxiangda.workflow-graph/v2",workflowCode:e.code,definitionDigest:t,startAt:e.startAt,fixedTopology:!0,branchStrategy:"first_match",nodes:Object.values(e.nodes).map(c=>({id:c.id,kind:c.kind,title:c.title||c.id,...c.binding?{binding:c.binding}:{},...c.mode?{mode:c.mode}:{},...c.outcome?{outcome:c.outcome}:{},...c.kind==="cc"?{emptyPolicy:c.emptyPolicy,notify:c.notify!==!1}:{},...c.kind==="approval"?{emptyPolicy:c.emptyPolicy||"block",initiatorApprovalPolicy:c.initiatorApprovalPolicy||"manual",...c.completionDeadline?{completionDeadline:{...c.completionDeadline}}:{}}:{},...c.kind==="action"&&c.handler?{businessStep:{handler:c.handler,inputs:c.inputs||{},outputPaths:Object.keys(pe(c.outputSchema).properties||{}).map(f=>`steps.${c.id}.${f}`)}}:{}})),edges:n,variables:a,logic:d,diagnostics:i}}function Ba(e,t=[]){let o=r=>{let i=t.find(d=>d.path===r)?.label;return i&&i!==r?i:void 0},n=o(e);if(n)return n;for(let r=e.lastIndexOf(".");r>0;r=e.lastIndexOf(".",r-1)){let i=o(e.slice(0,r));if(!i)continue;let d=e.slice(r+1);return d==="value"?`${i}\uFF08\u503C\uFF09`:d==="label"?`${i}\uFF08\u663E\u793A\u540D\u79F0\uFF09`:`${i}.${d}`}return e}function rn(e,t=[],o=0){if(!e||o>20)return"\u65E0\u6CD5\u8BC6\u522B\u7684\u6761\u4EF6";if(e.op==="path")return Ba(e.path,t);if(e.op==="literal")return JSON.stringify(e.value)??"\u7F3A\u503C";if(e.op==="and"||e.op==="or")return e.values.slice(0,128).map(d=>`\uFF08${rn(d,t,o+1)}\uFF09`).join(e.op==="and"?" \u4E14 ":" \u6216 ");if(e.op==="not"||e.op==="exists")return`${e.op==="not"?"\u4E0D\u6EE1\u8DB3":"\u5B58\u5728"}\uFF08${rn(e.value,t,o+1)}\uFF09`;if(!("left"in e))return"\u65E0\u6CD5\u8BC6\u522B\u7684\u6761\u4EF6";let n={eq:"=",neq:"\u2260",gt:">",gte:"\u2265",lt:"<",lte:"\u2264",in:"\u5C5E\u4E8E",contains:"\u5305\u542B"},r=e.left.op==="path"?e.left.path:void 0,i=r&&e.right.op==="literal"&&typeof e.right.value=="number"?t.find(d=>d.path===r)?.unit:void 0;return`${rn(e.left,t,o+1)} ${n[e.op]} ${rn(e.right,t,o+1)}${i?` ${i}`:""}`}function fi(e,t=0){return!Array.isArray(e)||e.length>64||t>1?!1:e.every(o=>{if(!o||typeof o!="object"||Array.isArray(o)||o.readonlyWhen!==void 0)return!1;if(o.subtable!==void 0){let n=o.subtable;return n&&n.create===!1&&n.delete===!1&&n.reorder===!1&&fi(n.fields,t+1)}return o.readonly===!0})}function ht(e){let t=[];for(let[o,n]of Object.entries(e?.nodes||{}))if(n.initiatorApprovalPolicy!==void 0){if(n.kind!=="approval"||!["manual","auto_approve"].includes(n.initiatorApprovalPolicy)){t.push(`WORKFLOW_INITIATOR_APPROVAL_POLICY_INVALID:${o}`);continue}n.initiatorApprovalPolicy==="auto_approve"&&((n.taskPageCode!==void 0&&(typeof n.taskPageCode!="string"||!fi(e.taskPages?.[n.taskPageCode]?.fields))||[n.fieldPolicy?.default,...Object.values(n.fieldPolicy?.fields||{})].some(r=>r==="edit"||r==="edit_required"))&&t.push(`WORKFLOW_INITIATOR_APPROVAL_INPUT_REQUIRED:${o}`),n.operationPolicy?.approve?.commentRequired===!0&&t.push(`WORKFLOW_INITIATOR_APPROVAL_COMMENT_REQUIRED:${o}`))}return t}function mu(e,t,o,n,r){return e.kind==="approval"&&e.initiatorApprovalPolicy==="auto_approve"&&ht({nodes:{node:e},...r?{taskPages:r}:{}}).length===0&&t!=="return_review"&&!!o&&n.user_id===o&&n.status==="active"&&n.participant_kind==="primary"&&["resolution","resolution_retry"].includes(n.source||"")&&!n.source_participant_id&&!n.delegate_authorization_id}var gu=8,Au={type:"array",minItems:2,maxItems:8,uniqueItems:!0,items:{type:"string",maxLength:128,pattern:"^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$"}};function an(e){if(e.roleCodes===void 0)return[];let t=e.roleCodes;if(!["app_role","app_role_in_scope"].includes(e.provider||"")||e.roleCode!==void 0||e.candidateField!==void 0||!Array.isArray(t)||t.length<2||t.length>8||new Set(t).size!==t.length||t.some(o=>typeof o!="string"||o.length>128||!/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/.test(o)))return["WORKFLOW_V2_BINDING_ROLE_UNION_INVALID"];if(e.provider==="app_role_in_scope"){let o=e.scope,n=typeof o?.value=="string"&&o.value.length>0&&o.value.length<=255&&o.valueFrom===void 0,r=typeof o?.valueFrom=="string"&&o.valueFrom.length<=255&&/^[A-Za-z][A-Za-z0-9_-]*(?:\.[A-Za-z][A-Za-z0-9_-]*)*$/.test(o.valueFrom)&&!o.valueFrom.split(".").some(i=>["__proto__","prototype","constructor"].includes(i))&&o.value===void 0;if(!o||typeof o!="object"||Array.isArray(o)||Object.keys(o).some(i=>!["dimension","value","valueFrom"].includes(i))||typeof o.dimension!="string"||!/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/.test(o.dimension)||!n&&!r)return["WORKFLOW_V2_BINDING_ROLE_UNION_SCOPE_INVALID"]}else if(e.scope!==void 0)return["WORKFLOW_V2_BINDING_ROLE_UNION_SCOPE_INVALID"];return[]}function Eu(e){return e.roleCodes?[...e.roleCodes]:e.roleCode?[e.roleCode]:[]}function pi(e){return e.some(t=>Object.values(t.binding.bindings).some(o=>o.roleCodes!==void 0))}function mi(e){if(e.selectedInputPath===void 0)return[];let t=e.selectedInputPath;return!["app_role","app_role_in_scope"].includes(e.provider||"")||e.candidateField!==void 0||e.inputPath!==void 0||e.routing!==void 0||e.roleCode===void 0&&e.roleCodes===void 0||typeof t!="string"||t.length>255||!/^[A-Za-z][A-Za-z0-9_-]*(?:\.[A-Za-z][A-Za-z0-9_-]*)*$/.test(t)||t.split(".").some(o=>["__proto__","constructor","prototype"].includes(o))?["WORKFLOW_V2_ROLE_INPUT_SELECTION_INVALID"]:[]}function _i(e){return e.some(t=>Object.values(t.binding.bindings).some(o=>o.selectedInputPath!==void 0))}var gi=20,Ai=200,Ka=["fixed_users","initiator","input_users","form_field_users","app_role","app_role_in_scope","previous_node_actor"];function yo(e,t){let o=[];for(let[n,r]of Object.entries(e?.nodes||{})){if(r?.kind!=="cc"||((Object.keys(r).some(a=>!["id","kind","title","binding","next","emptyPolicy","notify","administration"].includes(a))||typeof r.title!="string"||!r.title.trim()||r.title.length>255||typeof r.binding!="string"||!r.binding.trim()||r.binding.length>255||typeof r.next!="string"||!r.next.trim()||!e.nodes?.[r.next]||!["block","skip"].includes(r.emptyPolicy)||r.notify!==void 0&&typeof r.notify!="boolean")&&o.push(`WORKFLOW_CC_NODE_INVALID:${n}`),!t))continue;let i=t.bindings?.[r.binding];if(!i){o.push(`WORKFLOW_CC_BINDING_NOT_FOUND:${n}`);continue}Ka.includes(i.provider)||o.push(`WORKFLOW_CC_PROVIDER_INVALID:${n}`);let d=i.min??1,s=i.max??20;(!Number.isSafeInteger(d)||!Number.isSafeInteger(s)||d<1||s<d||s>200||i.provider==="fixed_users"&&(!Array.isArray(i.users)||!i.users.length||i.users.length>s))&&o.push(`WORKFLOW_CC_RECIPIENT_LIMIT_INVALID:${n}`)}return[...new Set(o)]}var bo=["approve","reject","return","transfer","delegate","add_assignee"],Oo=["fixed_users","app_role","app_role_in_scope"],Ga=["single","any","all","sequence"],Le=e=>!!e&&typeof e=="object"&&!Array.isArray(e),qe=(e,t)=>Object.keys(e).every(o=>t.includes(o)),dn=(e,t,o)=>Array.isArray(e)&&e.length>0&&e.length<=o&&new Set(e).size===e.length&&e.every(n=>typeof n=="string"&&t.includes(n));function wt(e){return e.allowedOperations||[...bo]}function za(e,t){return t?.commentRequired??e==="reject"}function qa(e,t){return!["transfer","delegate","add_assignee","return"].includes(e)||t?.reasonRequired!==!1}function Ii(e,t,o={},n=!1){return!(!Le(e)||!Object.keys(e).length||!qe(e,n?["enabled","label","commentRequired","reasonRequired"]:["label","commentRequired","reasonRequired"])||e.label!==void 0&&(typeof e.label!="string"||!e.label.trim()||e.label.length>40||/[\u0000-\u001f\u007f]/.test(e.label))||e.enabled!==void 0&&(typeof e.enabled!="boolean"||["approve","reject"].includes(t)&&!e.enabled)||e.commentRequired!==void 0&&(typeof e.commentRequired!="boolean"||!["approve","reject"].includes(t)||n&&za(t,o)&&!e.commentRequired)||e.reasonRequired!==void 0&&(typeof e.reasonRequired!="boolean"||!["transfer","delegate","add_assignee","return"].includes(t)||n&&qa(t,o)&&!e.reasonRequired))}function No(e,t){let o=[];for(let[n,r]of Object.entries(e?.nodes||{})){if(!Le(r))continue;let i=r.administration,d=r.operationPolicy;if(r.kind==="cc"){(d!==void 0||i!==void 0&&(!Le(i)||!qe(i,["assigneeProviders"])))&&o.push(`WORKFLOW_NODE_ADMINISTRATION_INVALID:${n}`),i?.assigneeProviders!==void 0&&!dn(i.assigneeProviders,Oo,3)&&o.push(`WORKFLOW_NODE_ADMINISTRATION_PROVIDERS_INVALID:${n}`),i?.assigneeProviders?.includes("app_role_in_scope")&&t&&!t.bindings[r.binding||""]?.scope&&o.push(`WORKFLOW_NODE_ADMINISTRATION_SCOPE_REQUIRED:${n}`);continue}if(r.kind!=="approval"){(i!==void 0||d!==void 0)&&o.push(`WORKFLOW_NODE_ADMINISTRATION_APPROVAL_REQUIRED:${n}`);continue}if(d!==void 0&&(!Le(d)||Object.keys(d).length>8||Object.entries(d).some(([a,c])=>!bo.includes(a)||!wt(r).includes(a)||!Ii(c,a)))&&o.push(`WORKFLOW_NODE_OPERATION_POLICY_INVALID:${n}`),i===void 0)continue;if(!Le(i)||!qe(i,["modes","assigneeProviders","operations"])){o.push(`WORKFLOW_NODE_ADMINISTRATION_INVALID:${n}`);continue}i.modes!==void 0&&(!dn(i.modes,Ga,4)||!i.modes.includes(r.mode))&&o.push(`WORKFLOW_NODE_ADMINISTRATION_MODES_INVALID:${n}`),i.assigneeProviders!==void 0&&!dn(i.assigneeProviders,Oo,3)&&o.push(`WORKFLOW_NODE_ADMINISTRATION_PROVIDERS_INVALID:${n}`);let s=t?.bindings[r.binding||""];s&&Array.isArray(i.assigneeProviders)&&i.assigneeProviders.includes("app_role_in_scope")&&!s.scope&&o.push(`WORKFLOW_NODE_ADMINISTRATION_SCOPE_REQUIRED:${n}`),i.operations!==void 0&&(!dn(i.operations,bo,8)||i.operations.some(a=>!wt(r).includes(a)))&&o.push(`WORKFLOW_NODE_ADMINISTRATION_OPERATIONS_INVALID:${n}`)}return o}function Tu(e,t,o,n){let r=[];if(!e||!Le(o)||!Object.keys(o).length||!qe(o,["title","description","assignee","mode","operations"]))return["WORKFLOW_V2_NODE_CONFIGURATION_PATCH_INVALID"];let i=o;for(let s of["title","description"])i[s]!==void 0&&(typeof i[s]!="string"||i[s].length>(s==="title"?255:1e3)||s==="title"&&!i[s].trim())&&r.push("WORKFLOW_V2_NODE_CONFIGURATION_PATCH_INVALID");let d=e.administration;if(i.mode!==void 0&&(e.kind!=="approval"||!d?.modes?.includes(i.mode))&&r.push("WORKFLOW_V2_NODE_CONFIGURATION_MODE_READONLY"),i.operations!==void 0&&(e.kind!=="approval"||!Le(i.operations)||!Object.keys(i.operations).length||Object.keys(i.operations).length>8||Object.entries(i.operations).some(([s,a])=>!d?.operations?.includes(s)||!wt(e).includes(s)||!Ii(a,s,e.operationPolicy?.[s],!0)))&&r.push("WORKFLOW_V2_NODE_CONFIGURATION_OPERATION_INVALID"),i.assignee!==void 0){let s=i.assignee,a=d?.assigneeProviders||(e.kind==="approval"&&t&&Oo.includes(t.provider)?[t.provider]:[]);if(t?.selectedInputPath&&!["app_role","app_role_in_scope"].includes(s?.provider||"")&&r.push("WORKFLOW_V2_NODE_CONFIGURATION_PROVIDER_READONLY"),!Le(s)||!["approval","cc"].includes(e.kind)||!a.includes(s.provider)||s.provider==="app_role_in_scope"&&!t?.scope)r.push("WORKFLOW_V2_NODE_CONFIGURATION_PROVIDER_READONLY");else if(s.provider==="fixed_users"){let c=e.kind==="cc"?t?.min??1:e.emptyPolicy==="skip"?0:1,f=e.kind==="cc"?Math.min(t?.max??20,200):200;(!qe(s,["provider","users"])||!Array.isArray(s.users)||s.users.length<c||s.users.length>f||new Set(s.users).size!==s.users.length||s.users.some(u=>typeof u!="string"||!u.trim()||u.length>255))&&r.push("WORKFLOW_V2_NODE_CONFIGURATION_USERS_INVALID")}else s.roleCodes!==void 0?(!qe(s,["provider","roleCodes"])||an({...s,...s.provider==="app_role_in_scope"?{scope:t?.scope}:{}}).length)&&r.push("WORKFLOW_V2_NODE_CONFIGURATION_ROLE_INVALID"):(!qe(s,["provider","roleCode"])||typeof s.roleCode!="string"||!/^[a-z][a-z0-9_-]{0,127}$/.test(s.roleCode))&&r.push("WORKFLOW_V2_NODE_CONFIGURATION_ROLE_INVALID")}return r.push(...ht({nodes:{node:{...e,operationPolicy:Ei(e,i).operationPolicy}},...n?{taskPages:n}:{}})),e.completionDeadline&&Ei(e,i).operationPolicy.approve?.commentRequired===!0&&r.push("WORKFLOW_COMPLETION_DEADLINE_INPUT_REQUIRED:node"),r}function Ei(e,t){let o=Object.fromEntries(wt(e).flatMap(n=>{let r=n,i=t?.operations?.[r],d={...e.operationPolicy?.[r],...i?.label!==void 0?{label:i.label}:{},...i?.commentRequired!==void 0?{commentRequired:i.commentRequired}:{},...i?.reasonRequired!==void 0?{reasonRequired:i.reasonRequired}:{}};return Object.keys(d).length?[[r,d]]:[]}));return{mode:t?.mode||e.mode,initiatorApprovalPolicy:e.initiatorApprovalPolicy||"manual",allowedOperations:wt(e).filter(n=>t?.operations?.[n]?.enabled!==!1),operationPolicy:o,fieldPolicy:{default:e.fieldPolicy?.default||"readonly",fields:{...e.fieldPolicy?.fields}}}}var yi=["fixed_users","input_users","form_field_users","app_role","app_role_in_scope"];function To(e,t){let o=[];for(let[n,r]of Object.entries(e?.nodes||{}))r.kind==="cc"||r.emptyPolicy===void 0||(r.kind!=="approval"||!["block","skip"].includes(r.emptyPolicy)?o.push(`WORKFLOW_APPROVAL_EMPTY_POLICY_INVALID:${n}`):r.emptyPolicy==="skip"&&t&&!yi.includes(t.bindings?.[r.binding||""]?.provider)&&o.push(`WORKFLOW_APPROVAL_EMPTY_PROVIDER_UNSUPPORTED:${n}`));return o}function Cu(e,t){return e.kind==="approval"&&e.emptyPolicy==="skip"&&t?.emptyResult==="no_candidates"&&yi.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 bi(e,t){let o=Object.values(e.nodes||{}).filter(n=>n.binding===t);return o.length>0&&o.every(n=>n.kind==="approval"&&n.emptyPolicy==="skip")}function Oi(e,t=0){return!Array.isArray(e)||e.length>64||t>1?!0:e.some(o=>!o||typeof o!="object"||Array.isArray(o)||o.required===!0||o.requiredWhen!==void 0||o.subtable!==void 0&&(!o.subtable||Oi(o.subtable.fields,t+1)))}function wu(e){let t=e.afterSeconds;return`\u8FDB\u5165\u540E ${t%86400===0?`${t/86400} \u5929`:t%3600===0?`${t/3600} \u5C0F\u65F6`:t%60===0?`${t/60} \u5206\u949F`:`${t} \u79D2`}\u672A\u5B8C\u6210\uFF0C\u81EA\u52A8\u540C\u610F`}function Ni(e){let t=[];for(let[o,n]of Object.entries(e?.nodes||{})){if(!n||typeof n!="object"||n.completionDeadline===void 0)continue;let r=n.completionDeadline;if(n.kind!=="approval"||!r||typeof r!="object"||Array.isArray(r)||Object.keys(r).length!==2||Object.keys(r).some(d=>!["afterSeconds","action"].includes(d))||r.action!=="approve"||!Number.isInteger(r.afterSeconds)||r.afterSeconds<1||r.afterSeconds>2592e3){t.push(`WORKFLOW_COMPLETION_DEADLINE_INVALID:${o}`);continue}n.allowedOperations&&!n.allowedOperations.includes("approve")&&t.push(`WORKFLOW_COMPLETION_DEADLINE_APPROVE_UNAVAILABLE:${o}`);let i=n.taskPageCode?e.taskPages?.[n.taskPageCode]:void 0;(n.taskPageCode&&(!i||Oi(i.fields))||[n.fieldPolicy?.default,...Object.values(n.fieldPolicy?.fields||{})].includes("edit_required")||n.operationPolicy?.approve?.commentRequired===!0||e.commandHandlers?.approve!==void 0)&&t.push(`WORKFLOW_COMPLETION_DEADLINE_INPUT_REQUIRED:${o}`)}return t}var Ja="openxiangda.workflow-rejection-notification/v1",Du=4096;function Ti(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function dt(e,t){return typeof e=="string"&&e.trim().length>0&&e.length<=t}function Ro(e,t){return Object.keys(e).sort().join(",")===t.sort().join(",")}function Ri(e){let t=e?.rejectionNotification;return t===void 0?[]:!Ti(t)||!Ro(t,["recipient","title","summary"])||t.recipient!=="record_last_modifier"||!dt(t.title,160)||!dt(t.summary,500)?["WORKFLOW_REJECTION_NOTIFICATION_INVALID"]:dt(e.subject?.resourceCode,63)?[]:["WORKFLOW_REJECTION_NOTIFICATION_SUBJECT_REQUIRED"]}function ku(e){if(!Ti(e)||e.schemaVersion!==Ja||e.recipient!=="record_last_modifier"||!dt(e.title,160)||!dt(e.summary,500))return!1;let t=["schemaVersion","recipient","title","summary","status","sourceRevision"];if(e.status==="ready"){if(!Ro(e,[...t,"userId"])||!dt(e.userId,255)||!Number.isSafeInteger(e.sourceRevision)||Number(e.sourceRevision)<1)return!1}else if(e.status==="skipped"){if(!Ro(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 Ci(e,t){let o=e.commandHandlers;if(o===void 0)return[];if(!o||typeof o!="object"||Array.isArray(o)||!Object.keys(o).length||Object.keys(o).some(r=>!["approve","reject","withdraw","resubmit"].includes(r)))return["WORKFLOW_BUSINESS_COMMAND_HANDLERS_INVALID"];let n=[];o.resubmit&&!Object.values(e.nodes||{}).some(r=>r.kind==="correction")&&n.push("WORKFLOW_BUSINESS_CORRECTION_REQUIRED");for(let[r,i]of Object.entries(o)){if(!i||typeof i!="object"||Array.isArray(i)||Object.keys(i).some(s=>!["operationCode","transitionPolicy","derivedSubjectFields"].includes(s))||i.transitionPolicy!==void 0&&(r!=="approve"||i.transitionPolicy!=="workflow")||!/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/.test(i.operationCode||"")){n.push("WORKFLOW_BUSINESS_COMMAND_HANDLER_INVALID");continue}if(i.derivedSubjectFields!==void 0){let s=i.derivedSubjectFields,a=new Set(Object.values(e.subject?.factProjection||{}));(r!=="resubmit"||!Array.isArray(s)||s.length<1||s.length>32||new Set(s).size!==s.length||s.some(c=>typeof c!="string"||!/^[A-Za-z][A-Za-z0-9_]{0,62}$/.test(c)||!a.has(c)||nt.has(c)||["createdBy","updatedBy","createdAt","updatedAt"].includes(c)||Object.values(e.taskPages||{}).some(f=>f.fields?.some(u=>u.code===c&&u.readonly!==!0))))&&n.push("WORKFLOW_CORRECTION_DERIVED_SUBJECT_FIELDS_INVALID")}if(!t)continue;let d=t.find(s=>s.code===i.operationCode);if(!d){n.push("WORKFLOW_BUSINESS_COMMAND_OPERATION_MISSING");continue}(d.method!=="POST"||d.browser?.exposure!=="authenticated"||d.browser.behavior!=="controlled"||d.browser.idempotency!=="required"||d.browser.fileIntent||d.browser.subject?.resourceCode!==e.subject?.resourceCode||d.browser.subject?.inputField!=="recordId"||!d.platformAccess?.workflow?.codes?.includes(e.code)||!d.platformAccess.workflow.businessCommands?.includes(r))&&n.push("WORKFLOW_BUSINESS_COMMAND_OPERATION_INVALID")}return["approve","reject","withdraw"].some(r=>Object.hasOwn(o,r))&&Object.values(e.nodes||{}).some(r=>r.kind==="approval"&&(r.emptyPolicy==="skip"||r.initiatorApprovalPolicy==="auto_approve"))&&n.push("WORKFLOW_BUSINESS_COMMAND_AUTOMATIC_DECISION_FORBIDDEN"),[...new Set(n)]}var vu={type:"object",additionalProperties:!1,required:["workflowCode","target","recordId","expectedRevision","commandToken","idempotencyKey","input"],properties:{workflowCode:{type:"string",pattern:"^[A-Za-z][A-Za-z0-9_-]{0,127}$"},target:{oneOf:[{type:"object",additionalProperties:!1,required:["kind","id","command"],properties:{kind:{const:"task"},id:{type:"string",format:"uuid"},command:{enum:["approve","reject","resubmit"]}}},{type:"object",additionalProperties:!1,required:["kind","id","command"],properties:{kind:{const:"instance"},id:{type:"string",format:"uuid"},command:{const:"withdraw"}}}]},recordId:{type:"string",format:"uuid"},expectedRevision:{type:"integer",minimum:1},commandToken:{type:"string",pattern:"^[A-Za-z0-9_-]{43}$"},idempotencyKey:{type:"string",minLength:1,maxLength:128},input:{type:"object",maxProperties:64}}};function Vu(e,t,o){if(!(t==="resubmit"&&o===!1))return e.commandHandlers?.[t]}var Ha=["fixed_users","initiator","app_role","app_role_in_scope"],Ya=e=>!!e&&typeof e=="object"&&!Array.isArray(e);function Co(e,t){let o=e?.launchPreflight;if(o===void 0)return[];if(!Ya(o)||Object.keys(o).join(",")!=="requiredApprovalNodes"||!Array.isArray(o.requiredApprovalNodes)||o.requiredApprovalNodes.length<1||o.requiredApprovalNodes.length>20||new Set(o.requiredApprovalNodes).size!==o.requiredApprovalNodes.length||o.requiredApprovalNodes.some(r=>typeof r!="string"||!/^[A-Za-z][A-Za-z0-9_-]{0,127}$/.test(r)))return["WORKFLOW_LAUNCH_PREFLIGHT_INVALID"];let n=[];for(let r of o.requiredApprovalNodes){let i=e.nodes?.[r];if(!i||i.kind!=="approval"){n.push(`WORKFLOW_LAUNCH_PREFLIGHT_NODE_INVALID:${r}`);continue}if(!t)continue;let d=t.bindings?.[i.binding||""];(!d||!Ha.includes(d.provider)||d.candidateField!==void 0)&&n.push(`WORKFLOW_LAUNCH_PREFLIGHT_PROVIDER_UNSUPPORTED:${r}`)}return n}var ho=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Xa=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,wi=/^[A-Za-z][A-Za-z0-9_-]{0,127}$/,hi=/^membership:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,xu=500,ju=262144;function Si(e){if(e?.approvedDelegation===void 0)return[];let t=e.approvedDelegation;if(!ho(t)||Object.keys(t).some(a=>!["confirmationNodeId","confirmer","requestsField","maxRequests"].includes(a))||!wi.test(t.confirmationNodeId||"")||!["initiator","delegate"].includes(t.confirmer)||!Xa.test(t.requestsField||"")||!Number.isSafeInteger(t.maxRequests)||t.maxRequests<1||t.maxRequests>500)return["WORKFLOW_APPROVED_DELEGATION_POLICY_INVALID"];let o=[],n=e.nodes?.[t.confirmationNodeId];(!n||n.kind!=="approval"||n.mode!=="single"||n.emptyPolicy==="skip"||n.initiatorApprovalPolicy==="auto_approve"||n.completionDeadline||n.administration?.assigneeProviders?.length||n.administration?.modes?.some(a=>a!=="single")||n.allowedOperations?.some(a=>["transfer","delegate","add_assignee","admin_override"].includes(a)))&&o.push("WORKFLOW_APPROVED_DELEGATION_CONFIRMATION_INVALID");let r=e.inputSchema?.properties?.[t.requestsField];(!r||r.type!=="array"||!Number.isSafeInteger(r.maxItems)||r.maxItems<1||r.maxItems>t.maxRequests||!r.items||r.items.type!=="object"||r.items.additionalProperties!==!1||!e.subject?.factProjection?.[t.requestsField])&&o.push("WORKFLOW_APPROVED_DELEGATION_REQUEST_SCHEMA_INVALID"),Object.values(e.nodes||{}).some(a=>a.kind==="end"&&a.outcome==="approved")||o.push("WORKFLOW_APPROVED_DELEGATION_APPROVED_END_REQUIRED");let d=[e.startAt],s=new Set;for(;d.length;){let a=d.pop();if(a===t.confirmationNodeId||s.has(a))continue;s.add(a);let c=e.nodes?.[a];c&&(c.kind==="end"&&c.outcome==="approved"&&o.push("WORKFLOW_APPROVED_DELEGATION_CONFIRMATION_BYPASS"),c.kind==="approval"&&d.push(c.onApprove,c.onReject),c.kind==="condition"&&d.push(c.otherwise,...(c.branches||[]).map(f=>f.target)),(c.kind==="cc"||c.kind==="action")&&d.push(c.next))}return[...new Set(o)]}function Wu(e,t){let o=t?.data?.[e.requestsField],n=()=>{throw new Error("WORKFLOW_APPROVED_DELEGATION_REQUEST_INVALID")};(!Array.isArray(o)||!o.length||o.length>e.maxRequests||o.length>500||new TextEncoder().encode(JSON.stringify(o)).byteLength>262144)&&n();let r=["key","delegatorRoleSubjectKey","delegatorRoleSubjectRevision","delegate","delegateRoleSubjectKey","expectedDelegateRevision","workflowCode","nodeId","validFrom","validTo","reason"],i=(a,c)=>typeof a=="string"&&a.trim().length>0&&a.length<=c,d=a=>{if(typeof a!="string")return!1;let c=/^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)(?:\.\d{1,3})?(?:Z|[+-](\d\d):(\d\d))$/.exec(a);if(!c)return!1;let[,f,u,p,_,E,A,O,b]=c,g=Number(f),I=Number(u),T=Number(p),y=[31,g%4===0&&(g%100!==0||g%400===0)?29:28,31,30,31,30,31,31,30,31,30,31];return I>=1&&I<=12&&T>=1&&T<=y[I-1]&&Number(_)<=23&&Number(E)<=59&&Number(A)<=59&&(O===void 0||Number(O)<=23&&Number(b)<=59)&&Number.isFinite(Date.parse(a))},s=o.map(a=>ho(a)?((Object.keys(a).some(c=>!r.includes(c))||!i(a.delegatorRoleSubjectKey,255)||!hi.test(a.delegatorRoleSubjectKey)||!i(a.delegateRoleSubjectKey,255)||!hi.test(a.delegateRoleSubjectKey)||!Number.isSafeInteger(a.delegatorRoleSubjectRevision)||a.delegatorRoleSubjectRevision<1||!Number.isSafeInteger(a.expectedDelegateRevision)||a.expectedDelegateRevision<1||!ho(a.delegate)||Object.keys(a.delegate).some(c=>!["value","label"].includes(c))||!i(a.delegate.value,255)||!i(a.delegate.label,200)||!(a.workflowCode===null||i(a.workflowCode,128)&&wi.test(a.workflowCode))||!(a.nodeId===null||i(a.nodeId,128)&&/^[A-Za-z0-9._:-]{1,128}$/.test(a.nodeId)&&a.workflowCode)||!d(a.validFrom)||!d(a.validTo)||Date.parse(a.validFrom)>=Date.parse(a.validTo)||!i(a.reason,4e3)||a.key!==void 0&&!i(a.key,128))&&n(),{...a,delegate:{value:a.delegate.value,label:a.delegate.label},validFrom:new Date(a.validFrom).toISOString(),validTo:new Date(a.validTo).toISOString()}):n());return e.confirmer==="delegate"&&new Set(s.map(a=>a.delegate.value)).size!==1&&n(),s}var Za=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&[null,Object.prototype].includes(Object.getPrototypeOf(e));function Di(e){let t=e?.nodes||{},o=Object.values(t).filter(s=>s?.kind==="correction");if(!o.length)return[];let n=[],r=s=>s?.kind==="approval"?[s.onApprove,s.onReject]:s?.kind==="condition"?[...(Array.isArray(s.branches)?s.branches:[]).map(a=>a.target),s.otherwise]:s?.kind==="action"||s?.kind==="cc"?[s.next]:[],i=new Set,d=[e.startAt];for(;d.length;){let s=d.pop();i.has(s)||(i.add(s),d.push(...r(t[s])))}for(let s of o){(!Za(s)||Object.keys(s).some(c=>!["id","kind","title","taskPageCode","next"].includes(c))||typeof s.id!="string"||!/^[A-Za-z][A-Za-z0-9_-]{0,127}$/.test(s.id)||["__proto__","prototype","constructor"].includes(s.id)||t[s.id]!==s||typeof s.title!="string"||!s.title.trim()||s.title.length>255||typeof s.taskPageCode!="string"||!/^[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(s.taskPageCode))&&n.push("WORKFLOW_CORRECTION_NODE_INVALID"),(s.next!==e.startAt||t[s.next]?.kind==="correction")&&n.push("WORKFLOW_CORRECTION_REPLAY_TARGET_INVALID"),(i.has(s.id)||Object.values(t).some(c=>r(c).includes(s.id)))&&n.push("WORKFLOW_CORRECTION_FORWARD_ENTRY_FORBIDDEN"),Object.values(t).some(c=>c?.kind==="approval"&&i.has(c.id)&&Array.isArray(c.returnTargets)&&c.returnTargets.includes(s.id))||n.push("WORKFLOW_CORRECTION_RETURN_SOURCE_REQUIRED");let a=e.taskPages?.[s.taskPageCode];!a||!Array.isArray(a.fields)?n.push("WORKFLOW_CORRECTION_PAGE_REQUIRED"):a.fields.some(c=>c?.subtable&&Object.values(e.subject?.factProjection||{}).some(f=>f===c.code||f.startsWith(`${c.code}.`)))&&n.push("WORKFLOW_CORRECTION_OWNED_FACTS_UNSUPPORTED")}return[...new Set(n)]}var cn=class extends Error{constructor(o){super(o);this.code=o}code},Bu=["projection","triggerCode","resourceCode","recordId","recordRevision","field","dueAt"];function ki(e,t,o){let n=i=>{throw new cn(i)};t.length>100&&n("DATE_TRIGGER_PROJECTION_LIMIT");let r=new Set;for(let i of t){let d=i.filter?.resourceCodes||[];if(Array.isArray(d)||n("DATE_TRIGGER_PROJECTION_INVALID"),d.length&&!d.includes(e))continue;let s=i.payload?.fields||[];(!Array.isArray(s)||s.length>32)&&n("DATE_TRIGGER_PROJECTION_LIMIT");for(let a of s)(typeof a!="string"||!/^[A-Za-z_][A-Za-z0-9_]{0,62}$/.test(a)||["__proto__","constructor","prototype"].includes(a))&&n("DATE_TRIGGER_PROJECTION_FIELD_INVALID"),r.add(a)}if(r.size>64&&n("DATE_TRIGGER_PROJECTION_LIMIT"),o!==void 0){let i=o?.schema?.fields??o?.fields;Array.isArray(i)||n("DATE_TRIGGER_PROJECTION_RESOURCE_INVALID");let d=new Map(i.map(s=>[s.code,s]));for(let s of r){let a=d.get(s);a||n("DATE_TRIGGER_PROJECTION_FIELD_UNKNOWN"),a.type==="subtable"&&n("DATE_TRIGGER_PROJECTION_SUBTABLE_FORBIDDEN"),o.fieldPolicies?.[s]?.mask==="omit"&&n("DATE_TRIGGER_PROJECTION_FIELD_SENSITIVE")}}return[...r].sort()}function Ku(e,t){if(!t.length)return e;let o=e?.properties?.projection;if(o?.type!=="object"||!o.properties||typeof o.properties!="object"||Array.isArray(o.properties)||o.additionalProperties!==!1||o.required!==void 0&&!Array.isArray(o.required)||t.some(n=>!Object.hasOwn(o.properties,n))||(o.required||[]).some(n=>!t.includes(n)))throw new cn("DATE_TRIGGER_PROJECTION_SCHEMA_INVALID");return{...e,properties:{...e.properties,projection:{}}}}var Qa=200,So=1024*1024,ed=65536,vi=Be,$i=tt,Je=new Set(["__proto__","prototype","constructor"]),Vi=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,Dt=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,Pi=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,de=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&[null,Object.prototype].includes(Object.getPrototypeOf(e)),ke=(e,t)=>de(e)&&Object.keys(e).every(o=>t.includes(o)&&!Je.has(o)),ln=e=>{try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return 1/0}},Li=e=>e==null||typeof e=="string"&&!e.trim()||Array.isArray(e)&&e.length===0;function xe(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((n,r)=>xe(n,t[r]));if(!de(e)||!de(t))return!1;let o=Object.keys(e);return o.length===Object.keys(t).length&&o.every(n=>Object.hasOwn(t,n)&&xe(e[n],t[n]))}function wo(e,t){let o=t.split(".");if(!(o.some(n=>!Vi.test(n)||Je.has(n))||o.length>12))return o.reduce((n,r)=>de(n)&&Object.hasOwn(n,r)?n[r]:void 0,e)}function Fe(e,t){switch(e.op){case"literal":return e.value;case"path":return wo({values:t},e.path);case"and":return e.values.every(o=>!!Fe(o,t));case"or":return e.values.some(o=>!!Fe(o,t));case"not":return!Fe(e.value,t);case"exists":return!Li(Fe(e.value,t));default:{let o=Fe(e.left,t),n=Fe(e.right,t);return e.op==="eq"?xe(o,n):e.op==="neq"?!xe(o,n):e.op==="in"?Array.isArray(n)&&n.some(r=>xe(r,o)):e.op==="contains"?Array.isArray(o)?o.some(r=>xe(r,n)):typeof o=="string"&&typeof n=="string"&&o.includes(n):typeof o!="number"||typeof n!="number"||!Number.isFinite(o)||!Number.isFinite(n)?!1:e.op==="gt"?o>n:e.op==="gte"?o>=n:e.op==="lt"?o<n:o<=n}}}function St(e,t,o=0,n={nodes:0}){if(o>8||++n.nodes>64||!de(e))return!1;if(e.op==="literal")return ke(e,["op","value"])&&Object.hasOwn(e,"value")&&ln(e.value)<=4096&&kt(e.value);if(e.op==="path"){if(!ke(e,["op","path"])||typeof e.path!="string")return!1;let r=e.path.split(".");return r[0]==="values"&&r.length>=2&&r.length<=8&&t.has(r[1])&&r.every(i=>Dt.test(i)&&!Je.has(i))}return["not","exists"].includes(e.op)?ke(e,["op","value"])&&St(e.value,t,o+1,n):["and","or"].includes(e.op)?ke(e,["op","values"])&&Array.isArray(e.values)&&e.values.length>0&&e.values.length<=16&&e.values.every(r=>St(r,t,o+1,n)):["eq","neq","gt","gte","lt","lte","in","contains"].includes(e.op)&&ke(e,["op","left","right"])&&St(e.left,t,o+1,n)&&St(e.right,t,o+1,n)}function un(e,t,o,n=$i){let r=[],i=e.taskPages;if(i!==void 0&&(!de(i)||Object.keys(i).length===0||Object.keys(i).length>16||ln(i)>ed))return["WORKFLOW_TASK_PAGES_INVALID"];for(let[d,s]of Object.entries(i||{})){let a=`taskPages.${d}`;if(!Vi.test(d)||Je.has(d)||!ke(s,["title","fields"])||typeof s.title!="string"||!s.title.trim()||s.title.length>160||!Array.isArray(s.fields)||!s.fields.length||s.fields.length>Qa){r.push(`WORKFLOW_TASK_PAGE_INVALID:${a}`);continue}let c=new Set(s.fields.map(p=>p?.code));c.size!==s.fields.length&&r.push(`WORKFLOW_TASK_PAGE_DUPLICATE_FIELD:${a}`);let f=0,u=new Set;for(let p of s.fields){if(!ke(p,["code","readonly","required","visibleWhen","requiredWhen","subtable"])||!Dt.test(p.code)||Je.has(p.code)||["readonly","required"].some(_=>p[_]!==void 0&&typeof p[_]!="boolean")||p.readonly&&(p.required||p.requiredWhen)){r.push(`WORKFLOW_TASK_PAGE_FIELD_INVALID:${a}`);continue}for(let _ of["visibleWhen","requiredWhen"])p[_]!==void 0&&!St(p[_],c)&&r.push(`WORKFLOW_TASK_PAGE_EXPRESSION_INVALID:${a}.${p.code}.${_}`);if(t){let _=t.get(p.code);if((!_||_.system||_.hidden||_.type==="serial-number"||!p.readonly&&_.widget==="readonly"||!p.readonly&&_.type==="subtable"&&!p.subtable||p.subtable&&_.type!=="subtable")&&r.push(`WORKFLOW_TASK_PAGE_RESOURCE_FIELD_INVALID:${a}.${p.code}`),p.subtable&&_?.subtable){let E=_.subtable;f+=E.maxRows??20,(u.has(E.resourceCode)||!Number.isSafeInteger(E.maxRows??20)||(E.maxRows??20)<1||(E.maxRows??20)>vi||!Dt.test(E.foreignKey)||!Dt.test(E.orderField)||E.foreignKey===E.orderField)&&r.push(`WORKFLOW_TASK_SUBTABLE_RELATION_INVALID:${a}.${p.code}`),u.add(E.resourceCode);let A=o?.get(E.resourceCode);o&&(!A||!["uuid","resource-ref.single"].includes(A.get(E.foreignKey)?.type||"")||A.get(E.orderField)?.type!=="number.integer")&&r.push(`WORKFLOW_TASK_SUBTABLE_RELATION_INVALID:${a}.${p.code}`);for(let O of Array.isArray(p.subtable.fields)?p.subtable.fields:[]){if(!O||typeof O.code!="string")continue;let b=A?.get(O.code);(O.code===E.foreignKey||O.code===E.orderField||A&&(!b||b.system||b.hidden||b.type==="subtable"||!O.readonly&&(b.widget==="readonly"||b.type==="serial-number")))&&r.push(`WORKFLOW_TASK_SUBTABLE_FIELD_UNSUPPORTED:${a}.${p.code}.${O.code}`)}}else p.subtable&&t&&r.push(`WORKFLOW_TASK_SUBTABLE_RELATION_INVALID:${a}.${p.code}`)}p.subtable&&(p.readonly||!ke(p.subtable,["fields","create","delete","reorder"])||["create","delete","reorder"].some(_=>p.subtable?.[_]!==void 0&&typeof p.subtable[_]!="boolean")||!Array.isArray(p.subtable.fields)||p.subtable.fields.some(_=>_?.subtable)?r.push(`WORKFLOW_TASK_SUBTABLE_PAGE_INVALID:${a}.${p.code}`):r.push(...un({taskPages:{child:{title:"\u5B50\u884C",fields:p.subtable.fields}}},o?.get(t?.get(p.code)?.subtable?.resourceCode||"")).map(_=>`${_}:${a}.${p.code}`)))}(f>Math.min(n,$i)||f<0||!Number.isSafeInteger(f)||!Number.isSafeInteger(n)||n<1)&&r.push(`WORKFLOW_TASK_SUBTABLE_BUDGET_EXCEEDED:${a}`)}for(let[d,s]of Object.entries(e.nodes||{}))de(s)&&s.taskPageCode!==void 0&&(!["approval","correction"].includes(s.kind)||typeof s.taskPageCode!="string"||!de(i)||!Object.hasOwn(i,s.taskPageCode)?r.push(`WORKFLOW_TASK_PAGE_NOT_FOUND:${d}`):Array.isArray(i[s.taskPageCode]?.fields)&&i[s.taskPageCode].fields.some(a=>a&&(s.fieldPolicy?.fields?.[a.code]||s.fieldPolicy?.default)==="hidden")&&r.push(`WORKFLOW_TASK_PAGE_FIELD_HIDDEN:${d}`));return r}function Fi(e,t){return e.fields.map(o=>({code:o.code,visible:o.visibleWhen===void 0||!!Fe(o.visibleWhen,t),readonly:o.readonly===!0,required:o.required===!0||o.requiredWhen!==void 0&&!!Fe(o.requiredWhen,t)}))}var we=class extends Error{constructor(o,n){super(o);this.code=o;this.field=n}code;field;rowIndex;childField};function qu(e,t){return t.map(o=>({key:String(o.id),id:String(o.id),revision:Number(o.revision),state:"persisted",values:Object.fromEntries(Fi({title:"\u5B50\u884C",fields:e.fields},o).filter(n=>n.visible&&!n.readonly).map(n=>[n.code,o[n.code]??null]))}))}function Ju(e,t,o,n,r,i=!0,d=0){let s=e.subtable,a=_=>{throw new we(_,e.code)};if(!s||!Number.isSafeInteger(t)||t<1||t>vi||!Number.isSafeInteger(d)||d<0||d>t||!Array.isArray(n)||n.length>2*t||ln(n)>So||!kt(n))return a("WORKFLOW_TASK_SUBTABLE_VALUES_INVALID");let c=new Map(o.map(_=>[String(_.id),_])),f=new Set,u=new Set,p=[];for(let _ of n){if(!ke(_,["key","state","id","revision","values"])||typeof _.key!="string"||!Pi.test(_.key)||f.has(_.key)||!["created","persisted","deleted"].includes(_.state)||!de(_.values))return a("WORKFLOW_TASK_SUBTABLE_ROW_INVALID");if(f.add(_.key),_.state==="created"){if(!s.create||_.id!==void 0||_.revision!==void 0||c.has(_.key))return a("WORKFLOW_TASK_SUBTABLE_CREATE_FORBIDDEN")}else{if(typeof _.id!="string"||_.id!==_.key||!Pi.test(_.id)||u.has(_.id)||!Number.isSafeInteger(_.revision)||_.revision<1||!c.has(_.id))return a("WORKFLOW_TASK_SUBTABLE_SCOPE_CONFLICT");if(u.add(_.id),i&&Number(c.get(_.id).revision)!==_.revision)return a("WORKFLOW_TASK_SUBTABLE_REVISION_CONFLICT")}if(_.state==="deleted"){if(!s.delete||Object.keys(_.values).length)return a("WORKFLOW_TASK_SUBTABLE_DELETE_FORBIDDEN");continue}try{td({title:e.code,fields:s.fields},_.id?c.get(_.id):{},_.values,r)}catch(E){if(!(E instanceof we))throw E;let A=new we(E.code,e.code);throw A.rowIndex=p.length,E.field!==void 0&&(A.childField=E.field),A}p.push(_)}if(u.size!==c.size)return a("WORKFLOW_TASK_SUBTABLE_SCOPE_CONFLICT");if(p.length>t)return a("WORKFLOW_TASK_SUBTABLE_MAX_ROWS_EXCEEDED");if(r&&p.length<d)return a("WORKFLOW_TASK_SUBTABLE_MIN_ROWS_NOT_MET");if(!s.reorder){let _=o.filter(A=>p.some(O=>O.id===String(A.id))).map(A=>String(A.id)),E=p.filter(A=>A.state==="persisted").map(A=>A.id);if(!xe(_,E)||p.some((A,O)=>A.state==="created"&&p.slice(O+1).some(b=>b.state==="persisted")))return a("WORKFLOW_TASK_SUBTABLE_REORDER_FORBIDDEN")}return n}function kt(e,t={members:0},o=0){return++t.members>5e4||o>12?!1:e===null||typeof e=="boolean"?!0:typeof e=="string"?e.length<=So:typeof e=="number"?Number.isFinite(e):Array.isArray(e)?e.length<=1e3&&e.every(n=>kt(n,t,o+1)):de(e)&&Object.entries(e).every(([n,r])=>!Je.has(n)&&kt(r,t,o+1))}function td(e,t,o,n){if(!de(o)||ln(o)>So||!kt(o))throw new we("WORKFLOW_TASK_FORM_VALUES_INVALID");let r={...t,...o},i=new Map(Fi(e,r).map(d=>[d.code,d]));for(let d of Object.keys(o)){let s=i.get(d);if(!s||s.readonly||!s.visible)throw new we("WORKFLOW_TASK_FORM_FIELD_NOT_EDITABLE",d)}if(n)for(let d of i.values()){let s=r[d.code],a=e.fields.find(c=>c.code===d.code)?.subtable&&Array.isArray(s)?s.every(c=>de(c)&&c.state==="deleted"):Li(s);if(d.visible&&!d.readonly&&d.required&&a)throw new we("WORKFLOW_TASK_FORM_REQUIRED",d.code)}return r}function Hu(e,t,o){let n=JSON.parse(JSON.stringify(t));for(let[d,s]of Object.entries(e.subject?.factProjection||{})){let a=d.split(".");if(!a.length||a.length>12||d.length>128||a[0]==="steps"||a.some(f=>!Dt.test(f)||Je.has(f)))throw new we("WORKFLOW_TASK_FORM_FACT_PROJECTION_INVALID");if(!Object.hasOwn(o,s))throw new we("WORKFLOW_TASK_FORM_FACT_FIELD_MISSING",s);let c=n;for(let f of a.slice(0,-1))c=c[f]=de(c[f])?c[f]:{};c[a.at(-1)]=o[s]===void 0?void 0:JSON.parse(JSON.stringify(o[s]))}let r=new Set,i=Object.values(e.nodes||{}).filter(d=>d.kind==="action");for(let d=0;d<=i.length;d++){let s=!1;for(let a of i)de(n.steps)&&Object.hasOwn(n.steps,a.id)&&Object.values(a.inputs||{}).some(c=>c.source==="fact"&&!xe(wo(t,c.path),wo(n,c.path)))&&(delete n.steps[a.id],r.add(a.id),s=!0);if(!s)break}return{facts:n,invalidatedNodeIds:[...r].sort()}}function Yu(e,t,o){let n=e.nodes||{};for(let r of o){let i=new Set,d=new Map,s=a=>{if(a===r)return!0;if(d.has(a))return d.get(a);if(i.has(a)||i.size>200)return!1;let c=n[a];if(!de(c)||c.kind==="end")return!1;i.add(a);let f=c.kind==="approval"?[c.onApprove]:c.kind==="condition"?[...(c.branches||[]).map(p=>p.target),c.otherwise]:[c.next],u=f.length>0&&f.every(p=>typeof p=="string"&&s(p));return i.delete(a),d.set(a,u),u};if(!s(t))return!1}return!0}var Zu=256,Qu=64,ef=262144,nd=/^[a-z][a-z0-9_-]{0,127}$/,od=/^[A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z][A-Za-z0-9_]*)*$/,ji=new Set(["__proto__","prototype","constructor"]),Se=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Pt=(e,t)=>Object.keys(e).every(o=>t.includes(o)),He=(e,t)=>typeof e=="string"&&e.trim().length>0&&e.length<=t&&!/[\u0000-\u001f\u007f]/.test(e),$e=e=>typeof e=="string"&&nd.test(e)&&!ji.has(e),Wi=e=>typeof e=="string"&&e.length<=255&&od.test(e)&&!e.split(".").some(t=>ji.has(t)),rd=e=>Se(e)&&Pt(e,["dimension","valueFrom","value"])&&$e(e.dimension)&&(He(e.value,255)&&e.valueFrom===void 0||Wi(e.valueFrom)&&e.value===void 0),xi=e=>typeof e=="string"&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?(?:Z|[+-]\d{2}:\d{2})$/.test(e)&&Number.isFinite(Date.parse(e)),$t={type:"string",pattern:"^[a-z][a-z0-9_-]{0,127}$"},Do={type:"string",minLength:1,maxLength:128},tf={type:"object",additionalProperties:!1,required:["policyCode","title","strategy","dimensions","sources"],properties:{policyCode:$t,title:Do,strategy:{enum:["replace_then_append","replace_only"]},dimensions:{type:"object",maxProperties:8,propertyNames:$t,additionalProperties:{type:"object",additionalProperties:!1,required:["title","valueFrom"],properties:{title:Do,valueFrom:{type:"string",minLength:1,maxLength:255}}}},sources:{type:"object",minProperties:1,maxProperties:16,propertyNames:$t,additionalProperties:{type:"object",additionalProperties:!1,required:["title","provider","roleCode"],properties:{title:Do,provider:{enum:["app_role","app_role_in_scope"]},roleCode:$t,scope:{type:"object",additionalProperties:!1,required:["dimension"],properties:{dimension:$t,value:{type:"string",minLength:1,maxLength:255},valueFrom:{type:"string",minLength:1,maxLength:255}}}}}}}};function fn(e){if(!Se(e)||!Pt(e,["policyCode","title","strategy","dimensions","sources"])||!$e(e.policyCode)||!He(e.title,128)||!["replace_then_append","replace_only"].includes(e.strategy))return["WORKFLOW_V2_ROUTING_POLICY_INVALID"];let t=[];return(!Se(e.dimensions)||Object.keys(e.dimensions).length>8||Object.entries(e.dimensions).some(([o,n])=>!$e(o)||!Se(n)||!Pt(n,["title","valueFrom"])||!He(n.title,128)||!Wi(n.valueFrom)))&&t.push("WORKFLOW_V2_ROUTING_DIMENSIONS_INVALID"),(!Se(e.sources)||Object.keys(e.sources).length<1||Object.keys(e.sources).length>16||Object.entries(e.sources).some(([o,n])=>!$e(o)||!Se(n)||!Pt(n,["title","provider","roleCode","scope"])||!He(n.title,128)||!$e(n.roleCode)||!["app_role","app_role_in_scope"].includes(n.provider)||(n.provider==="app_role_in_scope"?!rd(n.scope):n.scope!==void 0)))&&t.push("WORKFLOW_V2_ROUTING_SOURCES_INVALID"),t}function nf(e,t){if(fn(e).length)return["WORKFLOW_V2_ROUTING_POLICY_INVALID"];if(!Array.isArray(t)||t.length>256||new TextEncoder().encode(JSON.stringify(t)).length>262144)return["WORKFLOW_V2_ROUTING_RULE_LIMIT_EXCEEDED"];let o=[],n=new Set;for(let r of t){if(!Se(r)||!Pt(r,["ruleCode","title","enabled","workflowCode","nodeId","matches","sourceCode","effect","priority","validFrom","validTo"])||!$e(r.ruleCode)||!He(r.title,128)||typeof r.enabled!="boolean"||!$e(r.sourceCode)||!Object.hasOwn(e.sources,r.sourceCode)||!["append","replace"].includes(r.effect)||!Number.isSafeInteger(r.priority)||r.priority<-1e3||r.priority>1e3||r.workflowCode!==void 0&&!$e(r.workflowCode)||r.nodeId!==void 0&&(!$e(r.nodeId)||r.workflowCode===void 0)||r.validFrom!==void 0&&!xi(r.validFrom)||r.validTo!==void 0&&!xi(r.validTo)||r.validFrom&&r.validTo&&Date.parse(r.validFrom)>=Date.parse(r.validTo)){o.push("WORKFLOW_V2_ROUTING_RULE_INVALID");continue}n.has(r.ruleCode)&&o.push(`WORKFLOW_V2_ROUTING_RULE_DUPLICATE:${r.ruleCode}`),n.add(r.ruleCode),(!Se(r.matches)||Object.entries(r.matches).some(([i,d])=>!Object.hasOwn(e.dimensions,i)||!Array.isArray(d)||d.length<1||d.length>64||new Set(d).size!==d.length||d.some(s=>!He(s,255))))&&o.push(`WORKFLOW_V2_ROUTING_MATCH_INVALID:${r.ruleCode}`)}return[...new Set(o)]}function id(e){return JSON.stringify({policyCode:e.policyCode,strategy:e.strategy,dimensions:Object.entries(e.dimensions).sort(([t],[o])=>t<o?-1:t>o?1:0).map(([t,o])=>[t,o.valueFrom]),sources:Object.entries(e.sources).sort(([t],[o])=>t<o?-1:t>o?1:0).map(([t,o])=>[t,o.provider,o.roleCode,o.scope?.dimension??null,o.scope?.valueFrom??null,o.scope?.value??null])})}function Mi(e){let t=[],o=new Map;for(let n of e)for(let[r,i]of Object.entries(n.bindings||{})){if(!Se(i)||i.routing===void 0)continue;let d=fn(i.routing);if(d.length){t.push(...d.map(c=>`${c}:${r}`));continue}let s=id(i.routing),a=o.get(i.routing.policyCode);a&&a!==s&&t.push(`WORKFLOW_V2_ROUTING_POLICY_CONFLICT:${i.routing.policyCode}`),o.set(i.routing.policyCode,s)}return[...new Set(t)]}function of(e,t){let o={};for(let[n,r]of Object.entries(e.dimensions)){let i=t;for(let d of r.valueFrom.split("."))i=Se(i)&&Object.hasOwn(i,d)?i[d]:void 0;if(!(typeof i=="string"&&He(i,255)||typeof i=="number"&&Number.isFinite(i)||typeof i=="boolean"))throw new Error(`WORKFLOW_V2_ROUTING_FACT_REQUIRED:${n}`);o[n]=String(i)}return o}function rf(e,t,o){let n=t.filter(c=>c.enabled&&(!c.validFrom||Date.parse(c.validFrom)<=o.at)&&(!c.validTo||Date.parse(c.validTo)>o.at)&&(!c.workflowCode||c.workflowCode===o.workflowCode)&&(!c.nodeId||c.nodeId===o.nodeId)&&Object.entries(c.matches).every(([f,u])=>u.includes(o.facts[f])));if(n.length>64)throw new Error("WORKFLOW_V2_ROUTING_MATCH_LIMIT_EXCEEDED");let r=(c,f)=>f.priority-c.priority||+!!c.workflowCode-+!!f.workflowCode||+!!c.nodeId-+!!f.nodeId||(c.ruleCode<f.ruleCode?-1:c.ruleCode>f.ruleCode?1:0),i=n.filter(c=>c.effect==="replace").sort(r);if(i.length>1&&i[0].priority===i[1].priority)throw new Error("WORKFLOW_V2_ROUTING_REPLACE_CONFLICT");let d=i[0],s=d&&e.strategy==="replace_only"?[]:n.filter(c=>c.effect==="append").sort(r),a=[...d?[d]:[],...s];return{matched:n.sort(r),replacement:d,applied:a,ignored:n.filter(c=>!a.includes(c))}}var ko="^[A-Za-z][A-Za-z0-9_]{0,62}$",Ui="^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$",df={type:"object",additionalProperties:!1,required:["mode","resourceCode","subtables"],properties:{mode:{const:"create"},resourceCode:{type:"string",maxLength:64,pattern:Ui},subtables:{type:"array",minItems:1,maxItems:16,items:{type:"object",additionalProperties:!1,required:["fieldCode","fieldCodes"],properties:{fieldCode:{type:"string",pattern:ko},fieldCodes:{type:"array",minItems:1,maxItems:200,uniqueItems:!0,items:{type:"string",pattern:ko}}}}}}};function pn(e){let t=n=>!!(n&&typeof n=="object"&&!Array.isArray(n)),o=n=>typeof n=="string"&&new RegExp(ko).test(n)&&!["__proto__","prototype","constructor"].includes(n);if(!t(e)||Object.keys(e).some(n=>!["mode","resourceCode","subtables"].includes(n))||e.mode!=="create"||typeof e.resourceCode!="string"||e.resourceCode.length>64||!new RegExp(Ui).test(e.resourceCode)||!Array.isArray(e.subtables)||e.subtables.length<1||e.subtables.length>16||e.subtables.some(n=>!t(n)||Object.keys(n).some(r=>!["fieldCode","fieldCodes"].includes(r))||!o(n.fieldCode)||!Array.isArray(n.fieldCodes)||n.fieldCodes.length<1||n.fieldCodes.length>200||new Set(n.fieldCodes).size!==n.fieldCodes.length||n.fieldCodes.some(r=>!o(r)))||new Set(e.subtables.map(n=>n.fieldCode)).size!==e.subtables.length)throw new Error("WORKFLOW_OWNED_SUBJECT_CREATE_INVALID")}function cf(e){return pn(e),{mode:"create",resourceCode:e.resourceCode,subtables:e.subtables.map(t=>({fieldCode:t.fieldCode,fieldCodes:[...t.fieldCodes].sort()})).sort((t,o)=>t.fieldCode.localeCompare(o.fieldCode))}}function Bi(e,t,o){pn(e);let n=s=>{throw new Error(`WORKFLOW_OWNED_SUBJECT_${s}`)},r=t.get(e.resourceCode);r||n("RESOURCE_MISSING");let i=new Set,d=0;for(let s of e.subtables){let a=r.get(s.fieldCode),c=a?.subtable,f=t.get(c?.resourceCode);(a?.type!=="subtable"||!f||c.resourceCode===e.resourceCode||i.has(c.resourceCode))&&n("RELATION_INVALID"),i.add(c.resourceCode);let u=c.maxRows??20;(!Number.isSafeInteger(u)||u<1||u>Be)&&n("BUDGET_EXCEEDED"),d+=u;for(let p of s.fieldCodes){let _=f.get(p);(!_||["serial-number","subtable"].includes(_.type)||[c.foreignKey,c.orderField].includes(p))&&n("FIELD_INVALID"),["file","image","signature","text.rich"].includes(_.type)&&!o.some(E=>E.resourceCode===c.resourceCode&&E.fieldCodes.includes(p)&&E.intents.includes("create"))&&n("FILE_ACCESS_REQUIRED")}}d>tt&&n("BUDGET_EXCEEDED")}import*as yn from"crypto";var Ki="native-4",$o="2.0.0-alpha.5",Gi={"application-native-2":"1.0.0","application.extended-declaration-capacity":"1.0.0","application.extended-role-capacity":"1.0.0","application.extended-artifact-capacity":"1.0.0","application.high-density-artifact-capacity":"1.0.0","application.extended-configuration-bytes":"1.0.0","application.development-configuration":"2.0.0","authz.native-batch-explain":"1.0.0","authz.native-management":"1.0.0","authz.native-membership-batch":"1.0.0","deployment.durable-runs":"1.0.0","deployment.platform-executor":"1.0.0","environment.on-demand-production":"1.0.0","environment.runtime-lifecycle":"1.0.0","data.rich-text":"1.0.0","data-api-v2":"1.1.0","data.service-mutations":"1.0.0","data.extended-owned-subtable-capacity":"1.0.0","data.aggregate-owned-subtable-capacity":"1.0.0","data.extended-field-capacity":"1.0.0","data.business-commands":"1.0.0","data.record-edit":"1.0.0","data.native-golden-crud":"1.0.0","data.audit-read-access":"1.0.0","data.managed-files":"1.1.0","data.decimal-reservations":"1.1.0","data.decimal-reservation-lifecycle":"1.0.0","data.unique-keys":"1.1.0","data.user-candidates":"1.0.0","data.user-candidate-launch-scope":"1.0.0","data.datetime-minute-precision":"1.0.0","data.subtable-minimum-rows":"1.0.0","data.managed-concurrency":"1.0.0","data.managed-concurrency.durable":"1.0.0","workflow.named-input-sources":"1.0.0","workflow.approved-delegation":"1.0.0","directory-v2":"1.0.0","directory.selected-user":"1.0.0","directory.selected-departments":"1.0.0","directory.current-initiator-phone":"1.0.0","events-v2":"1.0.0","events.durable-receipts":"1.0.0","events.capture-policy":"1.0.0","events.date-source-projection":"1.0.0","events.native-data-actions":"1.0.0","workflow-kernel-v2":"1.0.0","workflow.business-data-command":"1.0.0","workflow.approval-business-command":"1.0.0","workflow.native-stage-guard":"1.0.0","workflow.launch-preflight":"1.0.0","workflow.optional-rejection-comment":"1.0.0","workflow.optional-operation-reason":"1.0.0","workflow.optional-withdrawal-reason":"1.0.0","data.transaction-actor-authority":"1.0.0","data.authenticated-public-projection":"1.0.0","data.parent-read-policy":"1.0.0","data.record-print":"1.0.0","data.workflow-record-deletion":"1.0.0","data.record-comments":"1.0.0","workflow.record-history-read":"1.0.0","workflow.rejection-notification":"1.0.0","workflow.instance-cancellation-policy":"1.0.0","workflow.node-administration":"1.0.0","workflow.assignment-routing":"1.0.0","workflow.role-union":"1.0.0","workflow.role-input-selection":"1.0.0","workflow.named-owned-create":"1.0.0","workflow.owned-initial-facts":"1.0.0","workflow.initiator-correction":"1.0.0","workflow.correction-business-command":"1.0.0","workflow.correction-derived-subject-facts":"1.0.0","workflow.role-references":"1.0.0","workflow.delegation-management":"1.0.0","workflow.automatic-cc":"1.0.0","workflow.approval-empty-policy":"1.0.0","workflow.initiator-approval-policy":"1.0.0","workflow.completion-deadline":"1.0.0","workflow.task-page-submit":"1.0.0","workflow.task-private-drafts":"1.0.0","workflow.task-managed-files":"1.0.0","workflow.task-rich-fields":"1.0.0","workflow.task-owned-subtables":"1.0.0","workflow.task-owned-files":"1.0.0","workflow.durable-business-step":"1.0.0","workflow.step-data-transaction":"1.0.0","business-process.durable-command":"1.1.0","workflow.fresh-command-token":"1.0.0","notification-hub-v2":"1.0.0","authentication.application-login-surface":"1.0.0","public-access.anonymous-owner-records":"1.0.0"};var B=Object.freeze({perspectives:100,resources:512,dataPolicies:512,roles:512,subjectReadSurfaces:50,capabilities:4096,operations:500,eventConsumers:100,eventProducers:1e3,eventSchemas:100,eventTypes:500,workflows:512,routes:2048,adminPages:2048,adminNavigationGroups:100,adminNavigationItems:1024});function zi(e){let t=(e.surface?.mutationOwner||"native")==="native";return["query","get","create","update","delete"].filter(o=>{let n=e.surface?.generated;return o==="query"?n?.list??!0:o==="get"?n?.detail??!0:n?.[o]??t})}function Po(e){return(e.authz?.roles?.length||0)>256}function vo(e){let t=(e.data?.resources||[]).filter(o=>o.status!=="retired").reduce((o,n)=>o+zi(n).length,0)+(e.backend?.operations||[]).filter(o=>o.ai).length;return(e.data?.resources?.length||0)>100||(e.authz?.dataPolicies?.length||0)>100||(e.authz?.roles?.length||0)>100||(e.authz?.capabilities?.length||0)>2e3||[e.workflows?.definitions,e.workflows?.bindings,e.workflows?.activations].some(o=>(o?.length||0)>100)||(e.frontend?.routes?.length||0)>500||t>500||(e.frontend?.admin?.navigation||[]).reduce((o,n)=>o+n.items.length,0)>500}var ie=Object.freeze({legacyConfigBytes:4194304,configBytes:8388608,contractBytes:8388608,depth:40,stringBytes:1048576,legacyNodes:1e5,extendedNodes:25e4}),ct=Object.freeze({nodes:5e5});function Vo(e){return Buffer.byteLength(X(e),"utf8")>ie.legacyConfigBytes}function qi(e,t){let o=0,n=[[e][Symbol.iterator]()];for(;n.length;){let r=n[n.length-1].next();if(r.done){n.pop();continue}if(++o>t)return!0;if(Array.isArray(r.value))n.push(r.value.values());else if(r.value&&typeof r.value=="object"){let i=r.value;n.push((function*(){for(let d of Object.keys(i))i[d]!==void 0&&(yield i[d])})())}}return!1}function mn(e){return qi(e,ie.legacyNodes)}function _n(e){return qi(e,ie.extendedNodes)}var sd="openxiangda.config-bundle/v3",us="openxiangda.contract-bundle/v3",Ji="openxiangda.native-configuration-projection/v1",Vt=Ki,ad=/^[a-f0-9]{64}$/,dd=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,cd=/^app:[a-z][a-z0-9]*(?:-[a-z0-9]+)*:[A-Za-z0-9:._*-]+$/,ld=/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/,ud=/^[a-z][a-z0-9]*(?:[-.][a-z0-9]+)*$/,fd=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,pd=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,Hi=/^[A-Za-z][A-Za-z0-9_]{0,127}$/,md=/^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*$/,_d=/^[A-Z][A-Z0-9_]*$/,gd=/^[a-z][a-z0-9-]{2,63}$/,Ad=/^[A-Za-z][A-Za-z0-9_-]{0,127}$/,Ed=/^[A-Za-z][A-Za-z0-9_.]{0,127}$/,Id=16,yd=2*1024,bd=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"]),Od=new Set(["overview","database","operations","workflow","members","calendar","document","folder","settings"]),Nd=new Set(["approve","reject","return","transfer","delegate","add_assignee","resubmit","withdraw","terminate","admin_reassign","admin_override","retry_resolution"]),Td=ie.configBytes,Rd=ie.contractBytes,Cd=ie.depth,Fo=ie.stringBytes,hd="openxiangda.event-handler-manifest/v2",fs="openxiangda.application-route-manifest/v3",Yi=64,ps=new Set(["id","revision","created_by","updated_by","created_at","updated_at"]),xo=["openxiangda.data.record.created.v2","openxiangda.data.record.updated.v2","openxiangda.data.record.deleted.v2"],jo=["openxiangda.workflow.node.skipped.v2",Ct,"openxiangda.workflow.step.result_received.v2","openxiangda.workflow.step.completed.v2","openxiangda.workflow.step.continuation_failed.v2","openxiangda.workflow.instance.started.v2","openxiangda.workflow.instance.cc_added.v2","openxiangda.workflow.instance.completed.v2","openxiangda.workflow.instance.rejected.v2","openxiangda.workflow.instance.returned.v2","openxiangda.workflow.instance.resumed.v2","openxiangda.workflow.instance.withdrawn.v2","openxiangda.workflow.instance.terminated.v2","openxiangda.workflow.task.created.v2","openxiangda.workflow.task.assigned.v2","openxiangda.workflow.task.assignment_pending.v2","openxiangda.workflow.task.assignment_resolution_failed.v2","openxiangda.workflow.task.approved.v2","openxiangda.workflow.task.completed.v2","openxiangda.workflow.task.rejected.v2","openxiangda.workflow.task.returned.v2","openxiangda.workflow.task.resubmitted.v2","openxiangda.workflow.task.transferred.v2","openxiangda.workflow.task.reassigned.v2","openxiangda.workflow.task.delegated.v2","openxiangda.workflow.task.assignee_added.v2","openxiangda.workflow.task.cancelled.v2","openxiangda.workflow.participant.activated.v2","openxiangda.workflow.participant.completed.v2","openxiangda.workflow.participant.rejected.v2","openxiangda.workflow.participant.returned.v2","openxiangda.workflow.participant.transferred.v2","openxiangda.workflow.participant.reassigned.v2","openxiangda.workflow.participant.delegated.v2","openxiangda.workflow.participant.added.v2","openxiangda.workflow.participant.suspended.v2","openxiangda.workflow.participant.resumed.v2","openxiangda.workflow.participant.cancelled.v2"],wd=new Set(jo),Wo=class extends Error{code;pointer;identifiers;constructor(t,o,n={}){super(t),this.name="NativeConfigurationCompilerError",this.code=t,this.pointer=o,this.identifiers=Object.fromEntries(Object.entries(n).slice(0,8).map(([r,i])=>[r,String(i).slice(0,128)]))}};function ap(e){let t=S(e.appCode,"/appCode",128);dd.test(t)||m("NATIVE_CONFIG_APP_CODE_INVALID","/appCode");let o=Uo(e.expectedConfigDigest,"/expectedConfigDigest"),n=Uo(e.expectedContractDigest,"/expectedContractDigest"),r=ds(e.configBytes,Td,"/configBytes","NATIVE_CONFIG_ARTIFACT_TOO_LARGE"),i=ds(e.contractBytes,Rd,"/contractBytes","NATIVE_CONTRACT_ARTIFACT_TOO_LARGE");cs(r,o,"/configBytes","NATIVE_CONFIG_DIGEST_MISMATCH"),cs(i,n,"/contractBytes","NATIVE_CONTRACT_DIGEST_MISMATCH");let d=as(r,"/configBytes","NATIVE_CONFIG_JSON_INVALID","NATIVE_CONFIG_NOT_CANONICAL"),s=as(i,"/contractBytes","NATIVE_CONTRACT_JSON_INVALID","NATIVE_CONTRACT_NOT_CANONICAL");gn(d,"/config",ct.nodes),gn(s,"/contracts",ct.nodes),_n(d)||gn(s,"/contracts",ie.extendedNodes),mn(d)||gn(s,"/contracts",ie.legacyNodes);let a=d,c=s;$d(a,t),Pd(c,t,o);let f=vd(a,o,c.generatorVersion);yc(f,c,a),X(f)!==X(c)&&m("NATIVE_CONTRACT_CLOSURE_MISMATCH",Bo(f,c,"/contracts"));let u={authz:{appCode:t,...a.authz,perspectives:a.perspectives,capabilityCatalog:f.capabilities},data:{appCode:t,resources:a.data.resources,resourceContracts:f.resources,...f.concurrency?{concurrency:f.concurrency}:{},...f.subjectReadSurfaces?{subjectReadSurfaces:f.subjectReadSurfaces}:{}},events:{appCode:t,...a.events,consumers:f.eventConsumers,producers:f.eventProducers,handlerManifest:f.eventHandlerManifest,eventTypes:f.eventTypes,capturePlans:Dd({resources:a.data.resources,dataPolicies:a.authz.dataPolicies,subscriptions:f.eventConsumers,capturePolicies:a.events.capturePolicies})},workflows:{appCode:t,...a.workflows,contracts:f.workflows},runtime:{appCode:t,requirements:a.runtime,backend:a.backend,frontend:a.frontend},contracts:f},p={authz:lt(u.authz),data:lt(u.data),events:lt(u.events),workflows:lt(u.workflows),runtime:lt(u.runtime),contracts:lt(u.contracts)},_={configDigest:o,contractDigest:n,generatorVersion:c.generatorVersion},E=Sd(a),A={schemaVersion:Ji,compilerContractVersion:Vt,appCode:t,source:_,projections:p,requiredPlatformCapabilities:E,aggregateDigest:Z({schemaVersion:Ji,compilerContractVersion:Vt,appCode:t,source:_,requiredPlatformCapabilities:E,projectionDigests:Object.fromEntries(Object.entries(p).map(([O,b])=>[O,b.digest]))})};return Rs(A)}function Xi(e,t){let o=e.subject,n=t.find(i=>i.code===o?.resourceCode),r=new Set(Object.values(o?.factProjection||{}));return!!n?.schema?.fields?.some(i=>i.type==="subtable"&&r.has(i.code))}function Sd(e){let t=e.authz.roles,o=e.data.resources,n=e.backend.operations,r=n.filter(l=>l.platformAccess?.directory?.mode==="current-initiator"&&l.platformAccess.directory.fields.includes("phone")),i=(e.data.concurrency?.commands||[]).filter(l=>l.execution?.directory?.mode==="current-initiator"&&l.execution.directory.fields.includes("phone")),d=t.some(l=>l.capabilities.some(y=>y.endsWith(":directory:read")))||o.some(l=>l.schema.fields.some(y=>["user.single","user.multiple","department.single","department.multiple"].includes(y.type)))||n.some(l=>l.platformAccess?.directory||l.platformAccess?.selectedDepartments),s=!!(e.events.subscriptions.length||e.events.timers.length||e.events.dateTriggers.length||e.events.schemas.length),a=n.some(l=>l.platformAccess?.managedFiles||l.platformAccess?.managedFileCopies)||e.events.subscriptions.some(l=>l.platformAccess?.managedFileCopies),c=e.workflows.definitions.some(l=>l.definition.rejectionNotification!==void 0)||n.some(l=>l.platformAccess?.notification)||e.events.subscriptions.some(l=>l.platformAccess?.notification),f=(l,y,R=!1)=>{let h=o.find($=>$.code===l.definition.subject?.resourceCode)?.schema.fields||[];return Object.values(l.definition.taskPages||{}).some($=>$.fields.some(w=>{if(w.readonly)return!1;let j=h.find(Q=>Q.code===w.code);if(!R&&j&&y.includes(j.type))return!0;if(!w.subtable||!j?.subtable)return!1;let L=o.find(Q=>Q.code===j.subtable.resourceCode)?.schema.fields||[];return w.subtable.fields.some(Q=>!Q.readonly&&L.some(ee=>ee.code===Q.code&&y.includes(ee.type)))}))},u=e.workflows.definitions.filter(l=>f(l,["file","image","signature","text.rich"])),p=e.workflows.definitions.filter(l=>f(l,["signature","text.rich"])),_=e.workflows.definitions.filter(l=>f(l,["file","image","signature","text.rich"],!0)),E=e.workflows.definitions.filter(l=>l.launch.mode==="standalone"||l.launch.mode==="hidden-handoff"),A=n.some(l=>l.platformAccess?.workflow)||E.length>0,O=E.filter(l=>{let y=l.launch.submission;if(!y)return!1;let R=o.find(h=>h.code===l.definition.subject.resourceCode);return[y.create,y.existing].some(h=>h&&Object.values(h.inputs).some($=>$.source==="field"&&R?.schema.fields.some(w=>w.code===$.fieldCode&&w.type.startsWith("resource-ref.")&&w.source)))}),b={resources:o},g={perspectives:e.perspectives,authz:e.authz},I={schemaVersion:e.schemaVersion,appCode:e.appCode,frontend:{routes:e.frontend.routes,user:e.frontend.user,admin:e.frontend.admin,devicePolicy:e.frontend.devicePolicy},backend:{operations:n.map(l=>({code:l.code,method:l.method,path:l.path,capability:l.capability,platformAccess:l.platformAccess||null,...l.browser?{browser:l.browser}:{},ai:l.ai||null}))}};return[...Po(e)?[{code:"application.extended-role-capacity",declaration:{roles:e.authz.roles.length,maximum:B.roles}}]:[],...Vo(e)?[{code:"application.extended-configuration-bytes",declaration:{legacyConfigBytes:ie.legacyConfigBytes,configBytes:ie.configBytes}}]:[],...mn(e)?[{code:"application.extended-artifact-capacity",declaration:ie}]:[],..._n(e)?[{code:"application.high-density-artifact-capacity",declaration:ct}]:[],...vo(e)?[{code:"application.extended-declaration-capacity",declaration:{resources:e.data.resources.length,policies:e.authz.dataPolicies.length,roles:e.authz.roles.length,capabilities:e.authz.capabilities.length,definitions:e.workflows.definitions.length,bindings:e.workflows.bindings.length,activations:e.workflows.activations.length,routes:e.frontend.routes.length,navigationItems:e.frontend.admin.navigation.reduce((l,y)=>l+y.items.length,0)}}]:[],...o.some(l=>l.uniqueKeys?.length)?[{code:"data.unique-keys",declaration:o.filter(l=>l.uniqueKeys?.length).map(l=>({code:l.code,uniqueKeys:l.uniqueKeys}))}]:[],...e.data.concurrency?[{code:"data.managed-concurrency",declaration:e.data.concurrency}]:[],...e.data.concurrency?.commands.some(l=>l.mode==="durable")?[{code:"data.managed-concurrency.durable",declaration:e.data.concurrency}]:[],...o.some(l=>l.decimalReservationLifecycle)?[{code:"data.decimal-reservation-lifecycle",declaration:o.filter(l=>l.decimalReservationLifecycle).map(l=>({code:l.code,decimalReservationLifecycle:l.decimalReservationLifecycle}))}]:[],...n.some(l=>l.platformAccess?.dataCommands)?[{code:"data.business-commands",declaration:n.filter(l=>l.platformAccess?.dataCommands)}]:[],...e.authz.dataPolicies.some(lo)?[{code:"data.parent-read-policy",declaration:e.authz.dataPolicies.filter(lo)}]:[],...e.authz.dataPolicies.some(l=>l.publicRead)?[{code:"data.authenticated-public-projection",declaration:e.authz.dataPolicies.filter(l=>l.publicRead)}]:[],...n.some(l=>l.platformAccess?.roleAssertions?.actorAuthority)?[{code:"data.transaction-actor-authority",declaration:n.filter(l=>l.platformAccess?.roleAssertions?.actorAuthority)}]:[],...n.some(l=>l.platformAccess?.workflowStage)?[{code:"workflow.native-stage-guard",declaration:n.filter(l=>l.platformAccess?.workflowStage)}]:[],...n.some(l=>l.platformAccess?.recordEdit)?[{code:"data.record-edit",declaration:n.filter(l=>l.platformAccess?.recordEdit)}]:[],...n.some(l=>l.platformAccess?.decimalReservation)||e.events.subscriptions.some(l=>l.platformAccess?.decimalReservation)?[{code:"data.decimal-reservations",declaration:[...n.filter(l=>l.platformAccess?.decimalReservation).map(l=>({code:l.code,decimalReservation:l.platformAccess.decimalReservation})),...e.events.subscriptions.filter(l=>l.platformAccess?.decimalReservation).map(l=>({subscriptionCode:l.code,decimalReservation:l.platformAccess.decimalReservation}))]}]:[],{code:"application-native-2",declaration:I},{code:"authz.native-batch-explain",declaration:g},{code:"authz.native-management",declaration:g},{code:"deployment.durable-runs",declaration:I.backend},{code:"deployment.platform-executor",declaration:I.backend},{code:"environment.on-demand-production",declaration:{environments:["preproduction","production"]}},{code:"environment.runtime-lifecycle",declaration:{environments:["preproduction","production"]}},...o.length?[{code:"data-api-v2",declaration:b},{code:"data.native-golden-crud",declaration:b}]:[],...o.some(l=>l.recordComments!==void 0)?[{code:"data.record-comments",declaration:b}]:[],...o.some(l=>l.recordDeletion!==void 0)?[{code:"data.workflow-record-deletion",declaration:b}]:[],...o.some(l=>l.recordPrint!==void 0)?[{code:"data.record-print",declaration:b}]:[],...o.some(l=>l.workflowHistory!==void 0)?[{code:"workflow.record-history-read",declaration:b}]:[],...o.some(mr)?[{code:"data.audit-read-access",declaration:b}]:[],...d?[{code:"directory-v2",declaration:{roles:t.map(l=>({code:l.code,capabilities:l.capabilities.filter(y=>y.endsWith(":directory:read"))})),resources:o.map(l=>({code:l.code,fields:l.schema.fields.filter(y=>["user.single","user.multiple","department.single","department.multiple"].includes(y.type))})),operations:n.filter(l=>l.platformAccess?.directory).map(l=>({code:l.code,directory:l.platformAccess.directory}))}}]:[],...n.some(l=>l.platformAccess?.selectedDepartments)?[{code:"directory.selected-departments",declaration:n.filter(l=>l.platformAccess?.selectedDepartments).map(l=>({code:l.code,selectedDepartments:l.platformAccess.selectedDepartments}))}]:[],...n.some(l=>l.platformAccess?.directory?.mode==="selected-user")?[{code:"directory.selected-user",declaration:n.filter(l=>l.platformAccess?.directory?.mode==="selected-user").map(l=>({code:l.code,directory:l.platformAccess.directory}))}]:[],...r.length||i.length?[{code:"directory.current-initiator-phone",declaration:{operations:r.map(l=>({code:l.code,directory:l.platformAccess.directory})),commands:i.map(l=>({code:l.code,directory:l.execution.directory}))}}]:[],...e.data.resources.some(l=>l.schema.fields.some(y=>y.type==="text.rich"))?[{code:"data.rich-text",declaration:{policyVersion:"rich-text-html/1"}}]:[],...a?[{code:"data.managed-files",declaration:{operations:n.filter(l=>l.platformAccess?.managedFiles||l.platformAccess?.managedFileCopies).map(l=>({code:l.code,...l.platformAccess?.managedFiles?{managedFiles:l.platformAccess.managedFiles}:{},...l.platformAccess?.managedFileCopies?{managedFileCopies:l.platformAccess.managedFileCopies}:{}})),subscriptions:e.events.subscriptions.filter(l=>l.platformAccess?.managedFileCopies).map(l=>({code:l.code,managedFileCopies:l.platformAccess.managedFileCopies}))}}]:[],...e.events.subscriptions.some(l=>l.execution)?[{code:"events.native-data-actions",declaration:e.events.subscriptions.filter(l=>l.execution)}]:[],...e.events.capturePolicies?.length?[{code:"events.capture-policy",declaration:e.events.capturePolicies}]:[],...e.events.dateTriggers.some(l=>ki(l.resourceCode,e.events.subscriptions.filter(y=>y.eventTypes.includes(l.eventType)),e.data.resources.find(y=>y.code===l.resourceCode)).length>0)?[{code:"events.date-source-projection",declaration:{triggers:e.events.dateTriggers,subscriptions:e.events.subscriptions}}]:[],...s?[{code:"events-v2",declaration:e.events},{code:"events.durable-receipts",declaration:e.events}]:[],...Ln(e.data.resources)?[{code:"data.extended-owned-subtable-capacity",declaration:e.data.resources.filter(l=>Ln([l]))}]:[],...vn(e.data.resources,e.workflows?.definitions||[])?[{code:"data.extended-field-capacity",declaration:{resources:e.data.resources.filter(l=>l.schema.fields.length>100),workflows:(e.workflows?.definitions||[]).filter(l=>vn([],[l]))}}]:[],...Vn(e.data.resources)?[{code:"data.aggregate-owned-subtable-capacity",declaration:e.data.resources.filter(l=>Vn([l]))}]:[],...e.data.resources.some(l=>l.schema.fields.some(y=>y.userCandidates!==void 0))?[{code:"data.user-candidates",declaration:e.data.resources.filter(l=>l.schema.fields.some(y=>y.userCandidates!==void 0))}]:[],..._i(e.workflows.bindings)?[{code:"workflow.role-input-selection",declaration:e.workflows.bindings.filter(l=>Object.values(l.binding.bindings).some(y=>y.selectedInputPath!==void 0))}]:[],...pi(e.workflows.bindings)?[{code:"workflow.role-union",declaration:e.workflows.bindings.filter(l=>Object.values(l.binding.bindings).some(y=>y.roleCodes!==void 0))}]:[],...e.backend.operations.some(l=>l.platformAccess?.ownedSubject)?[{code:"workflow.named-owned-create",declaration:e.backend.operations.filter(l=>l.platformAccess?.ownedSubject)}]:[],...kn(e.data.resources)?[{code:"data.user-candidate-launch-scope",declaration:e.data.resources.filter(l=>kn([l]))}]:[],...Mn(e.data.resources)?[{code:"data.subtable-minimum-rows",declaration:e.data.resources.filter(l=>Mn([l]))}]:[],...Wn(e.data.resources)?[{code:"data.datetime-minute-precision",declaration:e.data.resources.filter(l=>Wn([l]))}]:[],...e.workflows.activations.length?[{code:"workflow-kernel-v2",declaration:e.workflows},{code:"workflow.fresh-command-token",declaration:e.workflows}]:[],...e.workflows.definitions.some(l=>l.definition.instanceCommands!==void 0)?[{code:"workflow.instance-cancellation-policy",declaration:e.workflows.definitions.filter(l=>l.definition.instanceCommands!==void 0)}]:[],...e.workflows.definitions.some(l=>l.definition.instanceCommands?.withdraw?.reasonRequired===!1)?[{code:"workflow.optional-withdrawal-reason",declaration:e.workflows.definitions.filter(l=>l.definition.instanceCommands?.withdraw?.reasonRequired===!1)}]:[],...e.workflows.definitions.some(l=>l.definition.rejectionNotification!==void 0)?[{code:"workflow.rejection-notification",declaration:e.workflows.definitions.filter(l=>l.definition.rejectionNotification!==void 0)}]:[],...e.workflows.definitions.some(l=>l.definition.commandHandlers!==void 0)||n.some(l=>l.platformAccess?.workflow?.businessCommands)?[{code:"workflow.business-data-command",declaration:{definitions:e.workflows.definitions.filter(l=>l.definition.commandHandlers!==void 0),operations:n.filter(l=>l.platformAccess?.workflow?.businessCommands)}}]:[],...e.workflows.definitions.some(l=>l.definition.commandHandlers?.approve?.transitionPolicy==="workflow")?[{code:"workflow.approval-business-command",declaration:e.workflows.definitions.filter(l=>l.definition.commandHandlers?.approve?.transitionPolicy==="workflow")}]:[],...e.workflows.definitions.some(l=>l.definition.commandHandlers?.resubmit)||n.some(l=>l.platformAccess?.workflow?.businessCommands?.includes("resubmit"))?[{code:"workflow.correction-business-command",declaration:{definitions:e.workflows.definitions.filter(l=>l.definition.commandHandlers?.resubmit),operations:n.filter(l=>l.platformAccess?.workflow?.businessCommands?.includes("resubmit"))}}]:[],...e.workflows.definitions.some(l=>l.definition.launchPreflight!==void 0)?[{code:"workflow.launch-preflight",declaration:e.workflows.definitions.filter(l=>l.definition.launchPreflight!==void 0)}]:[],...e.workflows.definitions.some(l=>l.definition.commandHandlers?.resubmit?.derivedSubjectFields!==void 0)?[{code:"workflow.correction-derived-subject-facts",declaration:e.workflows.definitions.filter(l=>l.definition.commandHandlers?.resubmit?.derivedSubjectFields!==void 0)}]:[],...e.workflows.definitions.some(l=>l.definition.approvedDelegation!==void 0)?[{code:"workflow.approved-delegation",declaration:e.workflows.definitions.filter(l=>l.definition.approvedDelegation!==void 0)}]:[],...e.workflows.definitions.some(l=>Xi(l.definition,e.data.resources))?[{code:"workflow.owned-initial-facts",declaration:e.workflows.definitions.filter(l=>Xi(l.definition,e.data.resources))}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.nodes).some(y=>y.kind==="correction"))?[{code:"workflow.initiator-correction",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.nodes).some(y=>y.kind==="correction"))}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.nodes).some(y=>y.operationPolicy?.reject?.commentRequired===!1))?[{code:"workflow.optional-rejection-comment",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.nodes).some(y=>y.operationPolicy?.reject?.commentRequired===!1))}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.nodes).some(y=>Object.values(y.operationPolicy||{}).some(R=>R.reasonRequired===!1)))?[{code:"workflow.optional-operation-reason",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.nodes).some(y=>Object.values(y.operationPolicy||{}).some(R=>R.reasonRequired===!1)))}]:[],...O.length?[{code:"workflow.named-input-sources",declaration:O}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.nodes).some(y=>y.administration!==void 0||y.operationPolicy!==void 0))?[{code:"workflow.node-administration",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.nodes).some(y=>y.administration!==void 0||y.operationPolicy!==void 0))}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.nodes).some(y=>y.kind==="approval"&&y.emptyPolicy!==void 0))?[{code:"workflow.approval-empty-policy",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.nodes).some(y=>y.kind==="approval"&&y.emptyPolicy!==void 0))}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.nodes).some(y=>y.completionDeadline!==void 0))?[{code:"workflow.completion-deadline",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.nodes).some(y=>y.completionDeadline!==void 0))}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.nodes).some(y=>y.initiatorApprovalPolicy!==void 0))?[{code:"workflow.initiator-approval-policy",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.nodes).some(y=>y.initiatorApprovalPolicy!==void 0))}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.nodes).some(y=>y.kind==="cc"))?[{code:"workflow.automatic-cc",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.nodes).some(y=>y.kind==="cc"))}]:[],...e.workflows.definitions.some(l=>l.definition.taskPages!==void 0)?["workflow.task-page-submit","workflow.task-private-drafts"].map(l=>({code:l,declaration:e.workflows.definitions.filter(y=>y.definition.taskPages!==void 0)})):[],...u.length?[{code:"workflow.task-managed-files",declaration:u}]:[],..._.length?[{code:"workflow.task-owned-files",declaration:_}]:[],...p.length?[{code:"workflow.task-rich-fields",declaration:p}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.taskPages||{}).some(y=>y.fields.some(R=>R.subtable)))?[{code:"workflow.task-owned-subtables",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.taskPages||{}).some(y=>y.fields.some(R=>R.subtable)))}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.nodes).some(y=>y.kind==="action"))?[{code:"workflow.durable-business-step",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.nodes).some(y=>y.kind==="action"))}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.nodes).some(y=>y.kind==="action"&&y.handler.dataTransaction))?[{code:"workflow.step-data-transaction",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.nodes).some(y=>y.kind==="action"&&y.handler.dataTransaction))}]:[],...e.workflows.bindings.some(l=>Object.values(l.binding.bindings).some(y=>y.routing!==void 0))?[{code:"workflow.assignment-routing",declaration:e.workflows.bindings.filter(l=>Object.values(l.binding.bindings).some(y=>y.routing!==void 0))}]:[],...A?[{code:"business-process.durable-command",declaration:{operations:n.filter(l=>l.platformAccess?.workflow).map(l=>({code:l.code,workflow:l.platformAccess.workflow})),definitions:E,activations:e.workflows.activations.filter(l=>E.some(y=>y.definition.code===l.workflowCode))}}]:[],...n.some(l=>l.platformAccess?.dataMutations)||e.events.subscriptions.some(l=>l.platformAccess?.dataMutations)?[{code:"data.service-mutations",declaration:{operations:n.filter(l=>l.platformAccess?.dataMutations).map(l=>({code:l.code,grants:l.platformAccess.dataMutations})),subscriptions:e.events.subscriptions.filter(l=>l.platformAccess?.dataMutations).map(l=>({code:l.code,grants:l.platformAccess.dataMutations}))}}]:[],...c?[{code:"notification-hub-v2",declaration:{...e.workflows.definitions.some(l=>l.definition.rejectionNotification!==void 0)?{rejectionNotifications:e.workflows.definitions.filter(l=>l.definition.rejectionNotification!==void 0)}:{},operations:n.filter(l=>l.platformAccess?.notification).map(l=>({code:l.code,notification:l.platformAccess.notification})),subscriptions:e.events.subscriptions.filter(l=>l.platformAccess?.notification).map(l=>({code:l.code,notification:l.platformAccess.notification}))}}]:[],...e.frontend.authentication?[{code:"authentication.application-login-surface",declaration:e.frontend.authentication}]:[],...e.frontend.publicAccess?[{code:"public-access.anonymous-owner-records",declaration:e.frontend.publicAccess}]:[]].map(({code:l,declaration:y})=>({code:l,contractVersion:l==="data.unique-keys"?o.some(R=>Yr(R.schema.fields,R.uniqueKeys)==="1.1.0")?"1.1.0":"1.0.0":Gi[l],usageDigest:`sha256:${Z(y)}`})).sort((l,y)=>l.code===y.code?0:l.code<y.code?-1:1)}function Dd(e){let t=new Map,o=new Set(e.resources.map(i=>String(i.code)));for(let[i,d]of D(e.capturePolicies===void 0?[]:e.capturePolicies,"/capturePlan/capturePolicies",100).entries()){let s=`/capturePlan/capturePolicies/${i}`,a=N(d,s);C(a,["resourceCode","mode"],s);let c=H(a.resourceCode,`${s}/resourceCode`);o.has(c)||m("NATIVE_EVENT_CAPTURE_RESOURCE_NOT_FOUND",s,{resourceCode:c}),t.has(c)&&m("NATIVE_EVENT_CAPTURE_POLICY_DUPLICATE",s,{resourceCode:c}),a.mode!=="all"&&a.mode!=="subscribed"&&m("NATIVE_EVENT_CAPTURE_MODE_INVALID",`${s}/mode`),t.set(c,a.mode)}let n=new Map(e.dataPolicies.map((i,d)=>{let s=N(i,`/capturePlan/dataPolicies/${d}`);return[String(s.code),s]})),r=e.subscriptions.map((i,d)=>N(i,`/capturePlan/subscriptions/${d}`));return e.resources.map((i,d)=>{let s=`/capturePlan/resources/${d}`,a=N(i,s),c=H(a.code,`${s}/code`),f=a.schema?N(a.schema,`${s}/schema`):a,u=new Set(D(f.fields||[],`${s}/schema/fields`,500).map((y,R)=>G(N(y,`${s}/schema/fields/${R}`).code,`${s}/schema/fields/${R}/code`))),p=a.dataPolicyCode?v(a.dataPolicyCode,`${s}/dataPolicyCode`):null,_=p?n.get(p):void 0;p&&!_&&m("NATIVE_EVENT_CAPTURE_AUTHZ_POLICY_NOT_FOUND",s,{resourceCode:c,dataPolicyCode:p});let E=new Set;for(let y of _?.rules||[])E.add(y.parentRead?Xt(e.resources,c,y.parentRead,`${s}/parentRead`).foreignKey:String(y.field));if(_?.readExpression)for(let y of st(_.readExpression,`${s}/readExpression`))E.add(y.rule.parentRead?Xt(e.resources,c,y.rule.parentRead,`${s}/parentRead`).foreignKey:String(y.rule.field));let A=new Set,O=new Set,b=new Set;for(let[y,R]of r.entries()){let h=D(R.eventTypes,`/capturePlan/subscriptions/${y}/eventTypes`,20).map(String);if(!h.some(L=>L.startsWith("openxiangda.data.")))continue;let $=N(R.filter||{},`/capturePlan/subscriptions/${y}/filter`),w=Array.isArray($.resourceCodes)?$.resourceCodes.map(String):[];if(w.length&&!w.includes(c))continue;for(let L of h)xo.includes(L)&&b.add(L);for(let L of kd($,`/capturePlan/subscriptions/${y}/filter`))A.add(L);let j=N(R.payload||{},`/capturePlan/subscriptions/${y}/payload`);for(let L of D(j.fields||[],`/capturePlan/subscriptions/${y}/payload/fields`,32))O.add(G(L,`/capturePlan/subscriptions/${y}/payload/fields`))}let g=new Set([...A,...O]),I=new Set([...g,...E]);I.size>Yi&&m("NATIVE_EVENT_CAPTURE_FIELDS_LIMIT",s,{resourceCode:c,maximum:Yi});for(let y of I)!u.has(y)&&!(E.has(y)&&ps.has(y))&&m("NATIVE_EVENT_CAPTURE_FIELD_NOT_FOUND",s,{resourceCode:c,field:y});let T=N(a.fieldPolicies||{},`${s}/fieldPolicies`);for(let y of g)T[y]?.mask==="omit"&&m("NATIVE_EVENT_CAPTURE_FIELD_SENSITIVE",s,{resourceCode:c,field:y});let l={resourceCode:c,...t.get(c)==="subscribed"?{capturedEventTypes:[...b].sort()}:{},filterFields:[...A].sort(),projectionFields:[...O].sort(),authorizationFields:[...E].sort(),captureFields:[...I].sort()};return{...l,digest:Z(l)}}).sort((i,d)=>i.resourceCode.localeCompare(d.resourceCode))}function kd(e,t){let o=new Set;for(let[d,s]of D(e.changes||[],`${t}/changes`,16).entries()){let a=N(s,`${t}/changes/${d}`);o.add(G(a.field,`${t}/changes/${d}/field`))}let n=N(e.changedFields||{},`${t}/changedFields`);for(let d of["anyOf","allOf","noneOf"])for(let[s,a]of D(n[d]||[],`${t}/changedFields/${d}`,32).entries())o.add(G(a,`${t}/changedFields/${d}/${s}`));let r=0,i=(d,s,a)=>{a>3&&m("NATIVE_EVENT_FILTER_DEPTH_LIMIT",s);let c=N(d,s);if(c.change){let u=N(c.change,`${s}/change`);o.add(G(u.field,`${s}/change/field`)),r+=1;return}if(c.not){i(c.not,`${s}/not`,a+1);return}let f=c.all?"all":c.any?"any":null;f||m("NATIVE_EVENT_FILTER_CONDITION_INVALID",s);for(let[u,p]of D(c[f],`${s}/${f}`,16).entries())i(p,`${s}/${f}/${u}`,a+1)};return e.where&&i(e.where,`${t}/where`,1),r+=Array.isArray(e.changes)?e.changes.length:0,r>16&&m("NATIVE_EVENT_FILTER_ATOM_LIMIT",t),[...o].sort()}function $d(e,t){C(e,["schemaVersion","compilerContractVersion","appCode","perspectives","authz","backend","data","events","workflows","frontend","runtime"],"/config"),F(e.schemaVersion,sd,"/config/schemaVersion"),F(e.compilerContractVersion,Vt,"/config/compilerContractVersion"),F(e.appCode,t,"/config/appCode"),D(e.perspectives,"/config/perspectives",100);let o=N(e.authz,"/config/authz");C(o,["capabilities","roles","scopeDimensions","scopeSources","roleMembershipSources","relationshipGrantSources","dataPolicies","authorizationTransitions"],"/config/authz",["authenticatedUserRoleCode"]),D(o.capabilities,"/config/authz/capabilities",B.capabilities),D(o.roles,"/config/authz/roles",B.roles),D(o.scopeDimensions,"/config/authz/scopeDimensions",100),D(o.scopeSources,"/config/authz/scopeSources",100),D(o.roleMembershipSources,"/config/authz/roleMembershipSources",100),D(o.relationshipGrantSources,"/config/authz/relationshipGrantSources",100),D(o.dataPolicies,"/config/authz/dataPolicies",B.dataPolicies),D(o.authorizationTransitions,"/config/authz/authorizationTransitions",100);let n=N(e.backend,"/config/backend");C(n,["secrets","operations"],"/config/backend"),D(n.secrets,"/config/backend/secrets",100),D(n.operations,"/config/backend/operations",500),mc(n.secrets);let r=N(e.data,"/config/data");C(r,["resources"],"/config/data",["resourceDetailRoutes","subjectReadSurfaces","concurrency"]),D(r.resources,"/config/data/resources",B.resources),r.subjectReadSurfaces!==void 0&&D(r.subjectReadSurfaces,"/config/data/subjectReadSurfaces",B.subjectReadSurfaces),r.resourceDetailRoutes!==void 0&&D(r.resourceDetailRoutes,"/config/data/resourceDetailRoutes",100);let i=N(e.events,"/config/events");C(i,["schemas","subscriptions","timers","dateTriggers"],"/config/events",["capturePolicies"]),D(i.schemas,"/config/events/schemas",100),D(i.subscriptions,"/config/events/subscriptions",100),D(i.timers,"/config/events/timers",100),D(i.dateTriggers,"/config/events/dateTriggers",100);let d=N(e.workflows,"/config/workflows");C(d,["definitions","bindings","activations","providers","editableParameters"],"/config/workflows"),D(d.definitions,"/config/workflows/definitions",B.workflows),D(d.bindings,"/config/workflows/bindings",B.workflows),D(d.activations,"/config/workflows/activations",B.workflows),D(d.providers,"/config/workflows/providers",100),D(d.editableParameters,"/config/workflows/editableParameters",100);let s=N(e.frontend,"/config/frontend");C(s,["routes","user","admin","devicePolicy"],"/config/frontend",["authentication","publicAccess"]),D(s.routes,"/config/frontend/routes",B.routes);let a=N(s.user,"/config/frontend/user");C(a,["applicationTodoCenter"],"/config/frontend/user"),ft(a.applicationTodoCenter,"/config/frontend/user/applicationTodoCenter"),Ko(s.devicePolicy,"/config/frontend/devicePolicy"),Object.prototype.hasOwnProperty.call(s,"authentication")&&_s(s.authentication,s.routes,e,"/config/frontend/authentication"),Object.prototype.hasOwnProperty.call(s,"publicAccess")&&Hd(s.publicAccess,e,"/config/frontend/publicAccess");let c=N(s.admin,"/config/frontend/admin");C(c,["navigation"],"/config/frontend/admin",["access"]),c.access!==void 0&&On(c.access,"/config/frontend/admin/access",e.appCode),Qd(c.navigation,"/config/frontend/admin/navigation");let f=N(e.runtime,"/config/runtime");C(f,["protocolCapabilities","health"],"/config/runtime"),V(f.protocolCapabilities,"/config/runtime/protocolCapabilities",100),C(N(f.health,"/config/runtime/health"),["livePath","readyPath","versionPath"],"/config/runtime/health"),F(f.health.livePath,"/__platform/health","/config/runtime/health/livePath"),F(f.health.readyPath,"/__platform/ready","/config/runtime/health/readyPath"),F(f.health.versionPath,"/__platform/version","/config/runtime/health/versionPath")}function Pd(e,t,o){C(e,["schemaVersion","compilerContractVersion","generatorVersion","appCode","configDigest","perspectives","resources","capabilities","operations","eventConsumers","eventProducers","eventSchemas","eventHandlerManifest","eventTypes","workflows","routes","routeManifest","adminPages","adminNavigation"],"/contracts",["authentication","publicAccess","adminAccess","subjectReadSurfaces","concurrency"]),F(e.schemaVersion,us,"/contracts/schemaVersion"),F(e.compilerContractVersion,Vt,"/contracts/compilerContractVersion"),S(e.generatorVersion,"/contracts/generatorVersion",128),F(e.appCode,t,"/contracts/appCode"),F(e.configDigest,o,"/contracts/configDigest"),D(e.perspectives,"/contracts/perspectives",B.perspectives),D(e.resources,"/contracts/resources",B.resources),e.subjectReadSurfaces!==void 0&&D(e.subjectReadSurfaces,"/contracts/subjectReadSurfaces",B.subjectReadSurfaces),D(e.capabilities,"/contracts/capabilities",B.capabilities),D(e.operations,"/contracts/operations",B.operations),D(e.eventConsumers,"/contracts/eventConsumers",B.eventConsumers),D(e.eventProducers,"/contracts/eventProducers",B.eventProducers),D(e.eventSchemas,"/contracts/eventSchemas",B.eventSchemas),N(e.eventHandlerManifest,"/contracts/eventHandlerManifest"),V(e.eventTypes,"/contracts/eventTypes",B.eventTypes),D(e.workflows,"/contracts/workflows",B.workflows),D(e.routes,"/contracts/routes",B.routes),Object.prototype.hasOwnProperty.call(e,"authentication")&&zd(e.authentication,"/contracts/authentication"),Object.prototype.hasOwnProperty.call(e,"publicAccess")&&Yd(e.publicAccess,"/contracts/publicAccess"),Object.prototype.hasOwnProperty.call(e,"adminAccess")&&On(e.adminAccess,"/contracts/adminAccess",t),ic(e.routeManifest,"/contracts/routeManifest",t),nc(e.adminPages,"/contracts/adminPages"),oc(e.adminNavigation,"/contracts/adminNavigation")}function vd(e,t,o){let n=Fd(e);lc(e,n),fc(e),uc(e),_c(e);let r=e.events.schemas.map((g,I)=>{let T=`/config/events/schemas/${I}`,l=N(g,T),y=S(l.eventType,`${T}/eventType`,255);return y.startsWith("openxiangda.")&&m("NATIVE_EVENT_SCHEMA_RESERVED",`${T}/eventType`,{eventType:y}),F(l.schemaDigest,Z(N(l.jsonSchema,`${T}/jsonSchema`)),`${T}/schemaDigest`),l}),i=new Set([...xo,...jo,...r.map(g=>String(g.eventType))]),d=new Map(e.data.resources.map(g=>[String(g.code),new Map(g.schema.fields.map(I=>[String(I.code),String(I.type)]))])),s=te(e.events.subscriptions.map((g,I)=>{let T=`/config/events/subscriptions/${I}`,l=N(g,T),y=V(l.eventTypes,`${T}/eventTypes`,20);y.forEach((w,j)=>{i.has(w)||m("NATIVE_EVENT_TYPE_NOT_REGISTERED",`${T}/eventTypes/${j}`,{eventType:w})});let R=ei(l,e.data.resources,T),h=Ld(l.delivery,y,`${T}/delivery`),$=Vd(l.platformAccess,`${T}/platformAccess`,d,e,l);return{code:v(l.code,`${T}/code`),endpointPath:Oe(l.endpointPath,`${T}/endpointPath`),eventTypes:y,filter:N(l.filter,`${T}/filter`),payload:R?.payload||N(l.payload,`${T}/payload`),...R?{execution:R.execution}:{},...$?{platformAccess:$}:{},delivery:h}}),g=>g.code),a=new Map(r.map(g=>[String(g.eventType),String(g.dataSchemaVersion)])),c=te([...e.data.resources.flatMap(g=>xo.map(I=>({code:`data:${g.code}:${I}`,source:"data",eventType:I,dataSchemaVersion:"2.0.0",resourceCode:g.code}))),...r.map(g=>({code:`app:${g.eventType}`,source:"app",eventType:g.eventType,dataSchemaVersion:g.dataSchemaVersion})),...e.events.timers.map(g=>({code:g.code,source:"timer",eventType:g.eventType,dataSchemaVersion:a.get(String(g.eventType))||"2.0.0"})),...e.events.dateTriggers.map(g=>({code:g.code,source:"date",eventType:g.eventType,dataSchemaVersion:a.get(String(g.eventType))||"2.0.0",resourceCode:g.resourceCode,field:g.field})),...e.workflows.activations.length?jo.filter(g=>!ii.includes(g)||e.workflows.definitions.some(I=>Object.values(I.definition.nodes).some(T=>T.kind==="action"))).filter(g=>g!=="openxiangda.workflow.node.skipped.v2"||e.workflows.definitions.some(I=>Object.values(I.definition.nodes).some(T=>T.kind==="approval"&&T.emptyPolicy==="skip"))).map(g=>({code:`workflow:${g}`,source:"workflow",eventType:g,dataSchemaVersion:"2.0.0"})):[]],g=>`${g.source}:${g.code}:${g.eventType}`),f=U([...s.flatMap(g=>g.eventTypes),...c.map(g=>String(g.eventType))]);tc(e);let u=Es(e),p;try{p=Cr(e.data.concurrency,e.data.resources,n)}catch(g){throw g instanceof Et&&m(g.code,g.pointer,{reason:g.reason}),g}p?.commands.some(g=>g.mode==="durable")&&e.backend?.enabled===!1&&m("NATIVE_MANAGED_CONCURRENCY_INVALID","/data/concurrency",{reason:"durable commands require backend runtime"});let _=jd(e,n),E=ms(e),A=e.workflows.definitions.map(g=>g.definition),O=Eo(A),b=ci(A,s,!0);b.length&&m(b[0],"/config/events/subscriptions");try{wr(e.data.resources,E)}catch(g){throw g instanceof it&&m(g.code,g.pointer,{reason:g.reason}),g}return{schemaVersion:us,compilerContractVersion:Vt,generatorVersion:o,appCode:e.appCode,configDigest:t,perspectives:e.perspectives,resources:xd(e),..._.length?{subjectReadSurfaces:_}:{},...p?{concurrency:p}:{},capabilities:te(n,g=>g.code),operations:E,eventConsumers:s,eventProducers:c,eventSchemas:r,eventHandlerManifest:{schemaVersion:hd,appCode:e.appCode,handlers:s.filter(g=>!g.execution).map(g=>({code:g.code,endpointPath:g.endpointPath,eventTypes:g.eventTypes,dataSchemaVersions:U(g.eventTypes.map(I=>I.startsWith("openxiangda.")?"2.0.0":a.get(I)||"2.0.0")),maxBodyBytes:65536,receiptProtocolVersion:2,...O[g.code]?{workflowStep:O[g.code]}:{}}))},eventTypes:f,workflows:bs(e),routes:bn(e),...Object.prototype.hasOwnProperty.call(e.frontend,"authentication")?{authentication:qd(e)}:{},...Object.prototype.hasOwnProperty.call(e.frontend,"publicAccess")?{publicAccess:Xd(e)}:{},...e.frontend.admin.access?{adminAccess:e.frontend.admin.access}:{},routeManifest:dc(e),adminPages:u,adminNavigation:Zd(e)}}function Vd(e,t,o,n,r){if(e===void 0)return;let i=N(e,t);C(i,["notification","managedFileCopies","decimalReservation","dataMutations"],t,!0);let d={};if(i.dataMutations!==void 0)try{d.dataMutations=ao(i.dataMutations,o)}catch{m("NATIVE_EVENT_DATA_MUTATIONS_INVALID",`${t}/dataMutations`)}if(i.decimalReservation!==void 0)try{d.decimalReservation=Zr(i.decimalReservation,Qr(n,r))}catch{m("NATIVE_EVENT_DECIMAL_RESERVATION_INVALID",`${t}/decimalReservation`)}if(i.notification!==void 0){let s=N(i.notification,`${t}/notification`);C(s,["mode"],`${t}/notification`),F(s.mode,"business-standard",`${t}/notification/mode`),d.notification={mode:"business-standard"}}if(i.managedFileCopies!==void 0){let s=D(i.managedFileCopies,`${t}/managedFileCopies`,16);s.length||m("NATIVE_EVENT_MANAGED_FILE_COPIES_REQUIRED",`${t}/managedFileCopies`);let a=new Set;d.managedFileCopies=te(s.map((c,f)=>{let u=`${t}/managedFileCopies/${f}`,p=N(c,u);C(p,["mode","sourceResourceCode","sourceFieldCodes","targetResourceCode","targetFieldCodes"],u),F(p.mode,"copy",`${u}/mode`);let _=H(p.sourceResourceCode,`${u}/sourceResourceCode`),E=H(p.targetResourceCode,`${u}/targetResourceCode`),A=o.get(_),O=o.get(E);(!A||!O)&&m("NATIVE_EVENT_MANAGED_FILE_COPY_RESOURCE_INVALID",u);let b=V(p.sourceFieldCodes,`${u}/sourceFieldCodes`,16),g=V(p.targetFieldCodes,`${u}/targetFieldCodes`,16);(!b.length||b.length!==g.length)&&m("NATIVE_EVENT_MANAGED_FILE_COPY_FIELDS_INVALID",u),b.forEach((T,l)=>{let y=A.get(T),R=O.get(g[l]);(!["file","image","text.rich"].includes(String(y))||y!==R)&&m("NATIVE_EVENT_MANAGED_FILE_COPY_FIELD_INVALID",`${u}/sourceFieldCodes/${l}`)});let I=`${_}:${b.join(",")}=>${E}:${g.join(",")}`;return a.has(I)&&m("NATIVE_EVENT_MANAGED_FILE_COPY_DUPLICATE",u),a.add(I),{mode:"copy",sourceResourceCode:_,sourceFieldCodes:U(b),targetResourceCode:E,targetFieldCodes:U(g)}}),c=>`${c.sourceResourceCode}:${c.sourceFieldCodes.join(",")}=>${c.targetResourceCode}:${c.targetFieldCodes.join(",")}`)}return Object.keys(d).length||m("NATIVE_EVENT_PLATFORM_ACCESS_EMPTY",t),d}function Ld(e,t,o){let n=N(e,o);C(n,["timeoutMs","maxAttempts","initialBackoffMs","maxBackoffMs","ordering","concurrency"],o),se(n.timeoutMs,`${o}/timeoutMs`,1e3,3e4),se(n.maxAttempts,`${o}/maxAttempts`,1,12);let r=se(n.initialBackoffMs,`${o}/initialBackoffMs`,1e3,3e5);se(n.maxBackoffMs,`${o}/maxBackoffMs`,r,18e5),se(n.concurrency,`${o}/concurrency`,1,50);let i=S(n.ordering,`${o}/ordering`,32);return["none","record","workflow-instance"].includes(i)||m("NATIVE_EVENT_DELIVERY_ORDERING_INVALID",`${o}/ordering`),i==="workflow-instance"&&t.some(d=>!wd.has(d))&&m("NATIVE_EVENT_WORKFLOW_ORDERING_REQUIRES_WORKFLOW_FACTS",`${o}/ordering`),n}function Fd(e){let t=new Map;for(let i of Ts(e.appCode))t.set(i.code,i);for(let[i,d]of e.authz.capabilities.entries()){let s=`/config/authz/capabilities/${i}`,a=N(d,s);C(a,["code","kind","name","description"],s,!0);let c=me(a.code,`${s}/code`,e.appCode);t.has(c)&&m("NATIVE_CAPABILITY_DUPLICATE",`${s}/code`),["backend","ui"].includes(a.kind)||m("NATIVE_CAPABILITY_KIND_INVALID",`${s}/kind`);let f={code:c,kind:a.kind,name:S(a.name,`${s}/name`,255),source:"explicit",...a.description===void 0?{}:{description:zo(a.description,`${s}/description`,2e3)}};t.set(c,f)}let o=e.data.resources.map((i,d)=>({pointer:`/config/data/resources/${d}`,resource:Ye(i,`/config/data/resources/${d}`,e.appCode)}));for(let{pointer:i,resource:d}of o){let s={read:`\u8BFB\u53D6${d.name}`,create:`\u65B0\u5EFA${d.name}`,update:`\u66F4\u65B0${d.name}`,delete:`\u5220\u9664${d.name}`};for(let a of["read","create","update","delete"]){let c=me(d.capabilities[a],`${i}/capabilities/${a}`,e.appCode);t.has(c)&&m("NATIVE_CAPABILITY_DUPLICATE",`${i}/capabilities/${a}`),t.set(c,{code:c,kind:"data",name:s[a],source:"data"})}}let n=new Set(t.keys()),r=new Map;for(let{pointer:i,resource:d}of o)for(let[s,a]of Object.entries(d.fieldPolicies)){if(_t(s))continue;let c=N(a,`${i}/fieldPolicies/${s}`);for(let f of["read","create","update"])if(Array.isArray(c[f]))for(let u of V(c[f],`${i}/fieldPolicies/${s}/${f}`,2e3)){if(me(u,`${i}/fieldPolicies/${s}/${f}`,e.appCode),n.has(u))continue;let p=r.get(u);p&&p!==d.code&&m("NATIVE_CAPABILITY_DUPLICATE",`${i}/fieldPolicies/${s}/${f}`),r.set(u,d.code),!t.has(u)&&t.set(u,{code:u,kind:"data",name:`${d.name}.${s}.${f}`,source:"data"})}}return[...t.values()]}function xd(e){let t=Wd(e);return te(e.data.resources.map((o,n)=>{let r=Ye(o,`/config/data/resources/${n}`,e.appCode),i=t.get(r.code);return{code:r.code,schemaDigest:Z(r.schema),fields:te(r.schema.fields.map(d=>({code:d.code,type:d.type})),d=>d.code),...i?{detailRouteCode:i}:{}}}),o=>o.code)}function jd(e,t){if(e.data.subjectReadSurfaces===void 0)return[];let o=D(e.data.subjectReadSurfaces,"/config/data/subjectReadSurfaces",B.subjectReadSurfaces),n=new Set(t.map(d=>String(d.code))),r=new Map(e.data.resources.map((d,s)=>{let a=`/config/data/resources/${s}`,c=Ye(d,a,e.appCode);return[String(c.code),{resource:c,fields:new Map(D(N(c.schema,`${a}/schema`).fields,`${a}/schema/fields`,500).map(f=>{let u=N(f,`${a}/schema/fields`);return[String(u.code),u]}))}]})),i=new Set;return te(o.map((d,s)=>{let a=`/config/data/subjectReadSurfaces/${s}`,c=N(d,a);C(c,["code","name","capability","subject","relations"],a);let f=v(c.code,`${a}/code`);i.has(f)&&m("NATIVE_SUBJECT_READ_SURFACE_CODE_DUPLICATE",`${a}/code`),i.add(f);let u=me(c.capability,`${a}/capability`,e.appCode);n.has(u)||m("NATIVE_SUBJECT_READ_SURFACE_CAPABILITY_NOT_DECLARED",`${a}/capability`);let p=N(c.subject,`${a}/subject`);C(p,["resourceCode","fields"],`${a}/subject`);let _=H(p.resourceCode,`${a}/subject/resourceCode`),E=r.get(_);E||m("NATIVE_SUBJECT_READ_SURFACE_RESOURCE_NOT_DECLARED",`${a}/subject/resourceCode`);let A=V(p.fields,`${a}/subject/fields`,100).map((T,l)=>G(T,`${a}/subject/fields/${l}`));A.length||m("NATIVE_SUBJECT_READ_SURFACE_FIELDS_REQUIRED",`${a}/subject/fields`);for(let[T,l]of A.entries()){let y=E.fields.get(l);(!y||y.type==="subtable")&&m("NATIVE_SUBJECT_READ_SURFACE_FIELD_INVALID",`${a}/subject/fields/${T}`)}let O=D(c.relations,`${a}/relations`,8);O.length||m("NATIVE_SUBJECT_READ_SURFACE_RELATIONS_REQUIRED",`${a}/relations`);let b=new Set,g=0,I=te(O.map((T,l)=>{let y=`${a}/relations/${l}`,R=N(T,y);C(R,["code","resourceCode","foreignKeyField","fields","limit"],y,["order"]);let h=v(R.code,`${y}/code`);b.has(h)&&m("NATIVE_SUBJECT_READ_SURFACE_RELATION_CODE_DUPLICATE",`${y}/code`),b.add(h);let $=H(R.resourceCode,`${y}/resourceCode`),w=r.get($);w||m("NATIVE_SUBJECT_READ_SURFACE_RESOURCE_NOT_DECLARED",`${y}/resourceCode`);let j=G(R.foreignKeyField,`${y}/foreignKeyField`),L=w.fields.get(j),Q=N(L?.source||{},`${y}/foreignKeyField/source`);(!L||!["uuid","resource-ref.single"].includes(String(L.type))||L.type==="resource-ref.single"&&(Q.kind!=="resource"||Q.resourceCode!==_))&&m("NATIVE_SUBJECT_READ_SURFACE_RELATION_INVALID",`${y}/foreignKeyField`);let ee=V(R.fields,`${y}/fields`,100).map((oe,P)=>G(oe,`${y}/fields/${P}`));ee.length||m("NATIVE_SUBJECT_READ_SURFACE_FIELDS_REQUIRED",`${y}/fields`);for(let[oe,P]of ee.entries()){let M=w.fields.get(P);(!M||M.type==="subtable")&&m("NATIVE_SUBJECT_READ_SURFACE_FIELD_INVALID",`${y}/fields/${oe}`)}let Y=D(R.order||[],`${y}/order`,10).map((oe,P)=>{let M=`${y}/order/${P}`,x=N(oe,M);C(x,["field","direction"],M);let z=G(x.field,`${M}/field`),q=w.fields.get(z);return(!ps.has(z)&&!q||q?.type==="subtable"||q&&!At(q.type))&&m("NATIVE_SUBJECT_READ_SURFACE_ORDER_FIELD_INVALID",`${M}/field`),["asc","desc"].includes(String(x.direction))||m("NATIVE_SUBJECT_READ_SURFACE_ORDER_DIRECTION_INVALID",`${M}/direction`),{field:z,direction:x.direction}}),ge=se(R.limit,`${y}/limit`,1,100);return g+=ge,{code:h,resourceCode:$,foreignKeyField:j,fields:U(ee),...Y.length?{order:Y}:{},limit:ge}}),T=>T.code);return g>400&&m("NATIVE_SUBJECT_READ_SURFACE_ROW_LIMIT_EXCEEDED",`${a}/relations`),{code:f,name:S(c.name,`${a}/name`,255),capability:u,subject:{resourceCode:_,fields:U(A)},relations:I}}),d=>d.code)}function Wd(e){let t=e.data.resourceDetailRoutes===void 0?[]:D(e.data.resourceDetailRoutes,"/config/data/resourceDetailRoutes",100),o=new Map(e.data.resources.map((i,d)=>{let s=`/config/data/resources/${d}`,a=Ye(i,s,e.appCode);return[a.code,a]})),n=new Map(bn(e).map(i=>[String(i.code),i])),r=new Map;for(let[i,d]of t.entries()){let s=`/config/data/resourceDetailRoutes/${i}`,a=N(d,s);C(a,["resourceCode","desktop","mobile"],s);let c=H(a.resourceCode,`${s}/resourceCode`);r.has(c)&&m("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_DUPLICATE",`${s}/resourceCode`);let f=o.get(c);f||m("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_RESOURCE_MISSING",`${s}/resourceCode`);let u=v(a.desktop,`${s}/desktop`),p=v(a.mobile,`${s}/mobile`);u===p&&m("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_INVALID",s);let _=String(f.capabilities.read);for(let[E,A]of[["desktop",u],["mobile",p]]){let O=`${s}/${E}`,b=n.get(A);b||m("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_REFERENCE_MISSING",O),b.surface!=="user"&&m("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_SURFACE_INVALID",O);let g=Oe(b.path,`${O}/path`),I=[...g.matchAll(/:([A-Za-z][A-Za-z0-9_]*)/g)],T=E==="mobile"?!g.startsWith("/m/"):g==="/m"||g.startsWith("/m/");(g.includes("*")||g.includes("?")||g.includes("#")||g.split("/").includes("..")||I.length!==1||T)&&m("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_PATH_INVALID",O);let l=Array.isArray(b.access?.allOf)?b.access.allOf:[];b.capability!==_&&!l.includes(_)&&m("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_CAPABILITY_INVALID",O)}r.set(c,{desktop:u,mobile:p})}return r}function ms(e){let t=new Map(e.data.resources.map((d,s)=>{let a=`/config/data/resources/${s}`,c=Ye(d,a,e.appCode);return[c.code,new Map(c.schema.fields.map(f=>[String(f.code),f]))]})),o=new Map(e.data.resources.map((d,s)=>{let a=`/config/data/resources/${s}`,c=Ye(d,a,e.appCode);return[c.code,new Map(c.schema.fields.map(f=>[String(f.code),String(f.type)]))]})),n=new Set(o.keys()),r=new Set(e.workflows.activations.map((d,s)=>Nn(N(d,`/config/workflows/activations/${s}`).workflowCode,`/config/workflows/activations/${s}/workflowCode`))),i=new Map;return te(e.backend.operations.map((d,s)=>{let a=`/config/backend/operations/${s}`,c=N(d,a);C(c,["code","method","path","capability","requestSchema","responseSchema","description","platformAccess","browser","ai"],a,!0);let f=S(c.method,`${a}/method`,16);["GET","POST","PUT","PATCH","DELETE"].includes(f)||m("NATIVE_OPERATION_METHOD_INVALID",`${a}/method`);let u=v(c.code,`${a}/code`);Kd(c.ai,a,u,f,n);let p=Bd(c.platformAccess,`${a}/platformAccess`,o,t,r,new Set(e.authz.roles.map(E=>String(E.code))));if(p?.workflowStage){let E=p.workflowStage,A=e.workflows.definitions.find(O=>O.definition.code===E.workflowCode);(!A||A.definition.subject?.resourceCode!==E.resourceCode||E.runningNodeIds.some(O=>!A.definition.nodes[O]))&&m("NATIVE_WORKFLOW_STAGE_NODE_INVALID",`${a}/platformAccess/workflowStage/runningNodeIds`)}if(p?.recordEdit){let E=e.data.resources.find(A=>A.code===p.recordEdit.resourceCode);E?.surface?.mutationOwner!=="action"&&m("NATIVE_RECORD_EDIT_ACTION_OWNER_REQUIRED",`${a}/platformAccess/recordEdit`);for(let A of p.recordEdit.fieldCodes)(!E.fieldPolicies?.[A]?.update?.length||E.surface?.fields?.[A]?.system===!0)&&m("NATIVE_RECORD_EDIT_FIELD_INVALID",`${a}/platformAccess/recordEdit/fieldCodes`)}if(p?.decimalReservation){let E=p.decimalReservation,A=String(E.resourceCode),O=JSON.stringify([E.amountFieldCode,E.currencyFieldCode,E.relationFieldCode,E.parentFieldCode,E.rootFieldCode,E.statusFieldCode,E.parentRelationValue,E.childRelationValue]),b=i.get(A);b&&b!==O&&m("NATIVE_DECIMAL_RESERVATION_MAPPING_CONFLICT",`${a}/platformAccess/decimalReservation`),i.set(A,O)}let _=Md(c.browser,`${a}/browser`,f,c.requestSchema,c.responseSchema,o,t,e.data.subjectReadSurfaces||[]);return{code:u,method:f,path:Oe(c.path,`${a}/path`),requiredCapability:me(c.capability,`${a}/capability`,e.appCode),requestSchemaDigest:Z(N(c.requestSchema,`${a}/requestSchema`)),responseSchemaDigest:Z(N(c.responseSchema,`${a}/responseSchema`)),...c.description===void 0?{}:{description:zo(c.description,`${a}/description`,2e3)},...p?{platformAccess:p}:{},..._?{browser:_}:{}}}),d=>d.code)}function Md(e,t,o,n,r,i,d,s){if(e===void 0)return null;let a=N(e,t);C(a,["exposure","behavior","idempotency","subject"],t,["refreshTargets","fileIntent"]),F(a.exposure,"authenticated",`${t}/exposure`);let c=S(a.behavior,`${t}/behavior`,32);["read","controlled"].includes(c)||m("NATIVE_OPERATION_BROWSER_BEHAVIOR_INVALID",`${t}/behavior`);let f=S(a.idempotency,`${t}/idempotency`,32);(!["none","required"].includes(f)||c==="controlled"&&f!=="required"||c==="read"&&f!=="none")&&m("NATIVE_OPERATION_BROWSER_IDEMPOTENCY_INVALID",`${t}/idempotency`);let u=N(a.subject,`${t}/subject`);C(u,["resourceCode","inputField"],`${t}/subject`);let p=H(u.resourceCode,`${t}/subject/resourceCode`);i.has(p)||m("NATIVE_OPERATION_BROWSER_SUBJECT_RESOURCE_NOT_DECLARED",`${t}/subject/resourceCode`);let _=G(u.inputField,`${t}/subject/inputField`),E=N(n,`${t}/requestSchema`),A=N(r,`${t}/responseSchema`);(E.type!=="object"||E.additionalProperties!==!1||A.type!=="object"||A.additionalProperties!==!1)&&m("NATIVE_OPERATION_BROWSER_SCHEMA_ROOT_INVALID",`${t}/requestSchema`);let O=N(E.properties,`${t}/requestSchema/properties`),b=new Set(E.required===void 0?[]:V(E.required,`${t}/requestSchema/required`,200));(!(_ in O)||!b.has(_))&&m("NATIVE_OPERATION_BROWSER_SUBJECT_INPUT_INVALID",`${t}/subject/inputField`);let g=N(O[_],`${t}/requestSchema/properties/${_}`);(g.type!=="string"||g.format!=="uuid")&&m("NATIVE_OPERATION_BROWSER_SUBJECT_INPUT_INVALID",`${t}/subject/inputField`);let I=new Map((Array.isArray(s)?s:[]).map((h,$)=>{let w=N(h,`/config/data/subjectReadSurfaces/${$}`);return[String(w.code),String(N(w.subject,`/config/data/subjectReadSurfaces/${$}/subject`).resourceCode)]})),T=a.refreshTargets===void 0?[]:D(a.refreshTargets,`${t}/refreshTargets`,16),l=new Set,y=te(T.map((h,$)=>{let w=`${t}/refreshTargets/${$}`,j=N(h,w);C(j,["kind","code"],w),F(j.kind,"subject-surface",`${w}/kind`);let L=v(j.code,`${w}/code`);return(l.has(L)||!I.has(L)||I.get(L)!==p)&&m("NATIVE_OPERATION_BROWSER_REFRESH_TARGET_INVALID",`${w}/code`),l.add(L),{kind:"subject-surface",code:L}}),h=>`${h.kind}:${h.code}`),R=Ud(a.fileIntent,`${t}/fileIntent`,o,c,f,p,O,b,d);return{exposure:"authenticated",behavior:c,idempotency:f,subject:{resourceCode:p,inputField:_},...y.length?{refreshTargets:y}:{},...R?{fileIntent:R}:{}}}function Ud(e,t,o,n,r,i,d,s,a){if(e===void 0)return null;let c=N(e,t);C(c,["recordResourceCode","recordIdInputField","relationField","fileNameField","contentTypeField","sizeField","purposes","maxTtlSeconds","maxBytes"],t),(o!=="GET"||n!=="read"||r!=="none")&&m("NATIVE_OPERATION_FILE_INTENT_BEHAVIOR_INVALID",t);let f=H(c.recordResourceCode,`${t}/recordResourceCode`),u=a.get(f);u||m("NATIVE_OPERATION_FILE_INTENT_RESOURCE_NOT_DECLARED",`${t}/recordResourceCode`);let p=G(c.recordIdInputField,`${t}/recordIdInputField`),_=N(d[p],`${t}/recordIdInputField`);(!s.has(p)||_.type!=="string"||_.format!=="uuid")&&m("NATIVE_OPERATION_FILE_INTENT_RECORD_INPUT_INVALID",`${t}/recordIdInputField`);let E=G(c.relationField,`${t}/relationField`),A=u.get(E);(!A||!["uuid","resource-ref.single"].includes(String(A.type))||String(A.type)==="resource-ref.single"&&(String(N(A.source,`${t}/relationField`).kind||"")!=="resource"||String(N(A.source,`${t}/relationField`).resourceCode||"")!==i))&&m("NATIVE_OPERATION_FILE_INTENT_RELATION_INVALID",`${t}/relationField`);let O=[["fileNameField",["text.short","text.long"]],["contentTypeField",["text.short","text.long"]],["sizeField",["number.integer"]]],b={};for(let[l,y]of O){let R=G(c[l],`${t}/${l}`);y.includes(String(u.get(R)?.type))||m("NATIVE_OPERATION_FILE_INTENT_METADATA_INVALID",`${t}/${l}`),b[l]=R}let g=te(V(c.purposes,`${t}/purposes`,2),l=>l);(!g.length||g.some(l=>!["preview","download"].includes(l)))&&m("NATIVE_OPERATION_FILE_INTENT_PURPOSE_INVALID",`${t}/purposes`);let I=Number(c.maxTtlSeconds);(!Number.isSafeInteger(I)||I<1||I>300)&&m("NATIVE_OPERATION_FILE_INTENT_TTL_INVALID",`${t}/maxTtlSeconds`);let T=Number(c.maxBytes);return(!Number.isSafeInteger(T)||T<1||T>104857600)&&m("NATIVE_OPERATION_FILE_INTENT_SIZE_INVALID",`${t}/maxBytes`),{recordResourceCode:f,recordIdInputField:p,relationField:E,fileNameField:b.fileNameField,contentTypeField:b.contentTypeField,sizeField:b.sizeField,purposes:g,maxTtlSeconds:I,maxBytes:T}}function Bd(e,t,o,n,r,i){if(e===void 0)return null;let d=N(e,t);C(d,["directory","selectedDepartments","managedFiles","managedFileCopies","notification","workflow","roleAssertions","decimalReservation","dataCommands","recordEdit","ownedSubject","workflowStage","dataMutations"],t,!0),Object.keys(d).length===0&&m("NATIVE_OPERATION_PLATFORM_ACCESS_EMPTY",t);let s={};if(d.dataMutations!==void 0)try{s.dataMutations=ao(d.dataMutations,n)}catch{m("NATIVE_OPERATION_DATA_MUTATIONS_INVALID",`${t}/dataMutations`)}if(d.dataCommands!==void 0){let a=N(d.dataCommands,`${t}/dataCommands`);C(a,["mode"],`${t}/dataCommands`),F(a.mode,"recoverable-native",`${t}/dataCommands/mode`),s.dataCommands={mode:"recoverable-native"}}if(d.workflowStage!==void 0){try{Gr(d.workflowStage)}catch{m("NATIVE_WORKFLOW_STAGE_DECLARATION_INVALID",`${t}/workflowStage`)}let a=d.workflowStage;(!s.dataCommands||d.decimalReservation!==void 0||!o.has(a.resourceCode)||!r.has(a.workflowCode)||!d.workflow?.codes?.includes(a.workflowCode))&&m("NATIVE_WORKFLOW_STAGE_DECLARATION_INVALID",`${t}/workflowStage`),s.workflowStage={...a,runningNodeIds:U([...a.runningNodeIds]),allowedStatuses:U([...a.allowedStatuses])}}if(d.recordEdit!==void 0){let a=`${t}/recordEdit`,c=N(d.recordEdit,a);C(c,["resourceCode","fieldCodes"],a);let f=H(c.resourceCode,`${a}/resourceCode`),u=n.get(f),p=V(c.fieldCodes,`${a}/fieldCodes`,200);(!u||!p.length||!s.dataCommands)&&m("NATIVE_RECORD_EDIT_DECLARATION_INVALID",a);for(let _ of p){let E=u.get(_);(!E||E.type==="serial-number"||E.type==="subtable")&&m("NATIVE_RECORD_EDIT_FIELD_INVALID",`${a}/fieldCodes`)}s.recordEdit={resourceCode:f,fieldCodes:U(p)}}if(d.roleAssertions!==void 0){let a=N(d.roleAssertions,`${t}/roleAssertions`);C(a,["roleCodes","actorAuthority"],`${t}/roleAssertions`,!0),a.actorAuthority!==void 0&&F(a.actorAuthority,!0,`${t}/roleAssertions/actorAuthority`);let c=V(a.roleCodes,`${t}/roleAssertions/roleCodes`,20);c.length||m("NATIVE_OPERATION_ROLE_ASSERTIONS_REQUIRED",`${t}/roleAssertions/roleCodes`),c.forEach((f,u)=>{i.has(f)||m("NATIVE_ROLE_REFERENCE_MISSING",`${t}/roleAssertions/roleCodes/${u}`)}),s.roleAssertions={roleCodes:U(c),...a.actorAuthority===!0?{actorAuthority:!0}:{}}}if(d.directory!==void 0){let a=N(d.directory,`${t}/directory`);C(a,["mode","fields"],`${t}/directory`),["current-initiator","selected-user"].includes(String(a.mode))||m("NATIVE_OPERATION_DIRECTORY_MODE_INVALID",`${t}/directory/mode`);let c=new Set(["displayName","employeeNumber","primaryDepartment","departments",...a.mode==="current-initiator"?["phone"]:[]]),f=V(a.fields,`${t}/directory/fields`,c.size);(!f.length||f.some(u=>!c.has(u)))&&m("NATIVE_OPERATION_DIRECTORY_FIELDS_INVALID",`${t}/directory/fields`),s.directory={mode:String(a.mode),fields:U(f)}}if(d.selectedDepartments!==void 0){let a=`${t}/selectedDepartments`,c=N(d.selectedDepartments,a);C(c,["fields","maxIds"],a);let f=V(c.fields,`${a}/fields`,4);(!f.includes("name")||f.some(u=>!["name","path","parent","fullPath"].includes(u))||!Number.isSafeInteger(c.maxIds)||c.maxIds<1||c.maxIds>50)&&m("NATIVE_OPERATION_SELECTED_DEPARTMENTS_INVALID",a),s.selectedDepartments={fields:U(f),maxIds:c.maxIds}}if(d.managedFiles!==void 0){let a=D(d.managedFiles,`${t}/managedFiles`,16);a.length||m("NATIVE_OPERATION_MANAGED_FILES_REQUIRED",`${t}/managedFiles`);let c=new Set;s.managedFiles=te(a.map((f,u)=>{let p=`${t}/managedFiles/${u}`,_=N(f,p);C(_,["resourceCode","fieldCodes","intents"],p);let E=H(_.resourceCode,`${p}/resourceCode`);(c.has(E)||!o.has(E))&&m("NATIVE_OPERATION_MANAGED_FILE_RESOURCE_INVALID",`${p}/resourceCode`),c.add(E);let A=V(_.fieldCodes,`${p}/fieldCodes`,16);(!A.length||A.some(b=>!["file","image","signature","text.rich"].includes(String(o.get(E)?.get(b)||""))))&&m("NATIVE_OPERATION_MANAGED_FILE_FIELD_INVALID",`${p}/fieldCodes`);let O=V(_.intents,`${p}/intents`,2);return(!O.length||O.some(b=>!["create","update"].includes(b)))&&m("NATIVE_OPERATION_MANAGED_FILE_INTENT_INVALID",`${p}/intents`),{resourceCode:E,fieldCodes:U(A),intents:U(O)}}),f=>f.resourceCode)}if(d.managedFileCopies!==void 0){let a=D(d.managedFileCopies,`${t}/managedFileCopies`,16);a.length||m("NATIVE_OPERATION_MANAGED_FILE_COPIES_REQUIRED",`${t}/managedFileCopies`);let c=new Set;s.managedFileCopies=te(a.map((f,u)=>{let p=`${t}/managedFileCopies/${u}`,_=N(f,p);C(_,["mode","sourceResourceCode","sourceFieldCodes","targetResourceCode","targetFieldCodes"],p),F(_.mode,"copy",`${p}/mode`);let E=H(_.sourceResourceCode,`${p}/sourceResourceCode`),A=H(_.targetResourceCode,`${p}/targetResourceCode`),O=o.get(E),b=o.get(A);(!O||!b)&&m("NATIVE_OPERATION_MANAGED_FILE_COPY_RESOURCE_INVALID",p);let g=V(_.sourceFieldCodes,`${p}/sourceFieldCodes`,16),I=V(_.targetFieldCodes,`${p}/targetFieldCodes`,16);(!g.length||g.length!==I.length)&&m("NATIVE_OPERATION_MANAGED_FILE_COPY_FIELDS_INVALID",p),g.forEach((l,y)=>{let R=O.get(l),h=b.get(I[y]);(!["file","image","text.rich"].includes(String(R))||R!==h)&&m("NATIVE_OPERATION_MANAGED_FILE_COPY_FIELD_INVALID",`${p}/sourceFieldCodes/${y}`)});let T=`${E}:${g.join(",")}=>${A}:${I.join(",")}`;return c.has(T)&&m("NATIVE_OPERATION_MANAGED_FILE_COPY_DUPLICATE",p),c.add(T),{mode:"copy",sourceResourceCode:E,sourceFieldCodes:U(g),targetResourceCode:A,targetFieldCodes:U(I)}}),f=>`${f.sourceResourceCode}:${f.sourceFieldCodes.join(",")}=>${f.targetResourceCode}:${f.targetFieldCodes.join(",")}`)}if(d.notification!==void 0){let a=N(d.notification,`${t}/notification`);C(a,["mode"],`${t}/notification`),a.mode!=="business-standard"&&m("NATIVE_OPERATION_NOTIFICATION_MODE_INVALID",`${t}/notification/mode`),s.notification={mode:"business-standard"}}if(d.workflow!==void 0){let a=N(d.workflow,`${t}/workflow`);C(a,["codes"],`${t}/workflow`,["businessCommands"]);let c=V(a.codes,`${t}/workflow/codes`,16);(!c.length||c.some(u=>!r.has(u)))&&m("NATIVE_OPERATION_WORKFLOW_CODE_INVALID",`${t}/workflow/codes`);let f=a.businessCommands===void 0?void 0:V(a.businessCommands,`${t}/workflow/businessCommands`,4);f&&(!f.length||f.some(u=>!["approve","reject","withdraw","resubmit"].includes(u)))&&m("NATIVE_OPERATION_WORKFLOW_BUSINESS_COMMAND_INVALID",`${t}/workflow/businessCommands`),s.workflow={codes:U(c),...f?{businessCommands:U(f)}:{}}}if(d.ownedSubject!==void 0){let a=`${t}/ownedSubject`,c=d.ownedSubject;try{pn(c)}catch{m("NATIVE_WORKFLOW_OWNED_SUBJECT_INVALID",a)}(!s.workflow||d.decimalReservation!==void 0)&&m("NATIVE_WORKFLOW_OWNED_SUBJECT_INVALID",a);try{Bi(c,n,s.managedFiles||[])}catch(f){m(`NATIVE_${f.message}`,a)}s.ownedSubject={mode:"create",resourceCode:c.resourceCode,subtables:te(c.subtables.map(f=>({fieldCode:f.fieldCode,fieldCodes:U([...f.fieldCodes])})),f=>f.fieldCode)}}if(d.decimalReservation!==void 0){let a=`${t}/decimalReservation`,c=N(d.decimalReservation,a);C(c,["mode","resourceCode","amountFieldCode","currencyFieldCode","relationFieldCode","parentFieldCode","rootFieldCode","statusFieldCode","parentRelationValue","childRelationValue","eligibleParentStatuses","eligibleChildStatuses"],a);let f=S(c.mode,`${a}/mode`,16);["reserve","commit","release"].includes(f)||m("NATIVE_DECIMAL_RESERVATION_MODE_INVALID",`${a}/mode`);let u=H(c.resourceCode,`${a}/resourceCode`),p=n.get(u);p||m("NATIVE_DECIMAL_RESERVATION_RESOURCE_MISSING",`${a}/resourceCode`);let E=Object.fromEntries(["amountFieldCode","currencyFieldCode","relationFieldCode","parentFieldCode","rootFieldCode","statusFieldCode"].map(l=>[l,G(c[l],`${a}/${l}`)])),A=l=>p.get(E[l]),O=l=>new Set((A(l)?.options||[]).map(y=>String(y.value))),b=v(c.parentRelationValue,`${a}/parentRelationValue`),g=v(c.childRelationValue,`${a}/childRelationValue`),I=V(c.eligibleParentStatuses,`${a}/eligibleParentStatuses`,16),T=V(c.eligibleChildStatuses,`${a}/eligibleChildStatuses`,16);(A("amountFieldCode")?.type!=="number.decimal"||A("amountFieldCode")?.exactDecimal!==!0||A("amountFieldCode")?.precision!==18||A("amountFieldCode")?.scale!==2||A("currencyFieldCode")?.type!=="option.single"||A("relationFieldCode")?.type!=="option.single"||A("parentFieldCode")?.type!=="resource-ref.single"||A("parentFieldCode")?.source?.resourceCode!==u||A("rootFieldCode")?.type!=="uuid"||A("statusFieldCode")?.type!=="option.single"||b===g||!O("relationFieldCode").has(b)||!O("relationFieldCode").has(g)||!I.length||!T.length||I.some(l=>!O("statusFieldCode").has(l))||T.some(l=>!O("statusFieldCode").has(l)))&&m("NATIVE_DECIMAL_RESERVATION_FIELD_INVALID",a),s.decimalReservation={mode:f,resourceCode:u,...E,parentRelationValue:b,childRelationValue:g,eligibleParentStatuses:U(I),eligibleChildStatuses:U(T)}}return s}function Kd(e,t,o,n,r){if(e===void 0)return;let i=`${t}/ai`,d=N(e,i);ud.test(o)||m("NATIVE_OPERATION_AI_CODE_INVALID",`${t}/code`),C(d,["name","description","risk","resources","sideEffects","concurrency","timeoutMs"],i,!0),S(d.name,`${i}/name`,Fo),S(d.description,`${i}/description`,Fo);let s=S(d.risk,`${i}/risk`,16);["read","write","destructive","external"].includes(s)||m("NATIVE_OPERATION_AI_RISK_INVALID",`${i}/risk`),s==="read"!=(n==="GET")&&m("NATIVE_OPERATION_AI_METHOD_RISK_MISMATCH",`${i}/risk`),n==="DELETE"&&!["destructive","external"].includes(s)&&m("NATIVE_OPERATION_AI_METHOD_RISK_MISMATCH",`${i}/risk`);let a=V(d.resources,`${i}/resources`,16);a.length===0&&m("NATIVE_OPERATION_AI_RESOURCE_REQUIRED",`${i}/resources`),a.forEach((f,u)=>{let p=H(f,`${i}/resources/${u}`);r.has(p)||m("NATIVE_OPERATION_AI_RESOURCE_MISSING",`${i}/resources/${u}`)});let c=V(d.sideEffects,`${i}/sideEffects`,20);(s==="read"&&c.length!==0||s!=="read"&&c.length===0)&&m("NATIVE_OPERATION_AI_SIDE_EFFECT_INVALID",`${i}/sideEffects`),d.concurrency!==void 0&&!["none","revision"].includes(S(d.concurrency,`${i}/concurrency`,16))&&m("NATIVE_OPERATION_AI_CONCURRENCY_INVALID",`${i}/concurrency`),d.timeoutMs!==void 0&&se(d.timeoutMs,`${i}/timeoutMs`,100,3e4)}function An(e){return(e.replace(/\/{2,}/g,"/").replace(/\/$/,"")||"/").split("/").map(o=>o.startsWith(":")?":":o.includes("*")?"*":o).join("/")}function Gd(e,t){let o=N(e,t),n=S(o.type,`${t}/type`,32),r=["code","type","label","presentation","required"],i=n==="sso"?[...r,"provider"]:n==="dingtalk"?[...r,"flow"]:r;C(o,i,t);let d=v(o.code,`${t}/code`),s=S(o.label,`${t}/label`,255),a=S(o.presentation,`${t}/presentation`,16);["primary","secondary"].includes(a)||m("NATIVE_APPLICATION_AUTH_METHOD_PRESENTATION_INVALID",`${t}/presentation`);let c=ft(o.required,`${t}/required`);return["sso","password","dingtalk"].includes(n)||m("NATIVE_APPLICATION_AUTH_METHOD_TYPE_INVALID",`${t}/type`),n==="sso"&&o.provider!=="tenant-default"&&m("NATIVE_APPLICATION_AUTH_SSO_PROVIDER_INVALID",`${t}/provider`),n==="dingtalk"&&!["auto","jsapi","oauth"].includes(S(o.flow,`${t}/flow`,16))&&m("NATIVE_APPLICATION_AUTH_DINGTALK_FLOW_INVALID",`${t}/flow`),{code:d,type:n,label:s,presentation:a,required:c,...n==="sso"?{provider:"tenant-default"}:{},...n==="dingtalk"?{flow:o.flow}:{}}}function Zi(e,t,o){let n=N(e,o);C(n,["routeCode","path","defaultRouteCode"],o);let r=v(n.routeCode,`${o}/routeCode`),i=Oe(n.path,`${o}/path`),d=t==="desktop"?"/login":"/m/login";return(i!==d||/[:*?#\\]/.test(i))&&m("NATIVE_APPLICATION_AUTH_SURFACE_PATH_INVALID",`${o}/path`,{device:t,expectedPath:d}),{routeCode:r,path:i,defaultRouteCode:v(n.defaultRouteCode,`${o}/defaultRouteCode`)}}function _s(e,t,o,n){if(e===null)return;let r=N(e,n);C(r,["accountMode","registration","methods","surfaces"],n),F(r.accountMode,"existing-platform-users-only",`${n}/accountMode`);let i=N(r.registration,`${n}/registration`);C(i,["mode"],`${n}/registration`),F(i.mode,"reject",`${n}/registration/mode`);let d=D(r.methods,`${n}/methods`,8);d.length===0&&m("NATIVE_APPLICATION_AUTH_METHOD_REQUIRED",`${n}/methods`);let s=d.map((b,g)=>Gd(b,`${n}/methods/${g}`)),a=new Set,c=new Set;for(let[b,g]of s.entries())a.has(g.code)&&m("NATIVE_APPLICATION_AUTH_METHOD_CODE_DUPLICATE",`${n}/methods/${b}/code`),c.has(g.type)&&m("NATIVE_APPLICATION_AUTH_METHOD_TYPE_DUPLICATE",`${n}/methods/${b}/type`),a.add(g.code),c.add(g.type);s.filter(b=>b.presentation==="primary").length!==1&&m("NATIVE_APPLICATION_AUTH_PRIMARY_METHOD_INVALID",`${n}/methods`);let f=N(r.surfaces,`${n}/surfaces`);C(f,["desktop","mobile"],`${n}/surfaces`);let u=Zi(f.desktop,"desktop",`${n}/surfaces/desktop`),p=Zi(f.mobile,"mobile",`${n}/surfaces/mobile`);u.routeCode===p.routeCode&&m("NATIVE_APPLICATION_AUTH_SURFACE_CODE_DUPLICATE",`${n}/surfaces/mobile/routeCode`);let _=D(t,"/config/frontend/routes",B.routes),E=new Map;for(let[b,g]of _.entries()){let I=N(g,`/config/frontend/routes/${b}`);E.set(String(I.code||""),I)}let A=new Set((Array.isArray(o.data?.resources)?o.data.resources:[]).map(b=>String(b.code||"")).filter(b=>/^[a-z][a-z0-9-]{0,62}$/.test(b)));for(let[b,g]of[["desktop",u],["mobile",p]]){E.has(g.routeCode)&&m("NATIVE_APPLICATION_AUTH_SURFACE_CODE_CONFLICT",`${n}/surfaces/${b}/routeCode`);let I=/^user\.([a-z][a-z0-9-]{0,62})\.(records|submit)$/.exec(String(g.defaultRouteCode||"")),T=E.get(g.defaultRouteCode),l=String(T?.path||"");if(I&&A.has(I[1])){let R=I[2]==="records"?`/my/${I[1]}`:`/my/${I[1]}/submit`;T={surface:"user",path:b==="mobile"?`/m${R}`:R},l=String(T.path)}let y=b==="desktop"?l==="/m"||l.startsWith("/m/"):!(l==="/m"||l.startsWith("/m/"));(!T||T.surface!=="user"||/[:*]/.test(l)||y)&&m("NATIVE_APPLICATION_AUTH_DEFAULT_ROUTE_INVALID",`${n}/surfaces/${b}/defaultRouteCode`)}let O=gs(o).filter(b=>!b.owner.startsWith("authentication:"));for(let[b,g]of[["desktop",u],["mobile",p]]){let I=O.find(T=>An(T.path)===An(g.path));I&&m("NATIVE_APPLICATION_AUTH_SURFACE_PATH_CONFLICT",`${n}/surfaces/${b}/path`,{owner:I.owner})}}function zd(e,t){if(e===null)return;let o={data:{resources:[]},workflows:{definitions:[]},frontend:{routes:[{code:"auth-desktop-default",path:"/auth-desktop-default",surface:"user"},{code:"auth-mobile-default",path:"/m/auth-mobile-default",surface:"user"}],user:{applicationTodoCenter:!1},admin:{navigation:[]},authentication:e}},n=N(e,t),r=N(n.surfaces,`${t}/surfaces`),i={...n,surfaces:{...r,desktop:{...N(r.desktop,`${t}/surfaces/desktop`),defaultRouteCode:"auth-desktop-default"},mobile:{...N(r.mobile,`${t}/surfaces/mobile`),defaultRouteCode:"auth-mobile-default"}}};_s(i,o.frontend.routes,{...o,frontend:{...o.frontend,authentication:i}},t)}function qd(e){let t=e.frontend.authentication;return t===null?null:{accountMode:t.accountMode,registration:{mode:t.registration.mode},methods:t.methods.map(o=>({...o})),surfaces:{desktop:{...t.surfaces.desktop},mobile:{...t.surfaces.mobile}}}}var Jd=new Set(["draft.read","draft.update","validate","create","own.list","own.read","public.list","public.read"]);function Hd(e,t,o){let n=N(e,o);C(n,["policies"],o);let r=D(n.policies,`${o}/policies`,16);r.length<1&&m("NATIVE_PUBLIC_POLICY_REQUIRED",o);let i=new Map(t.frontend.routes.map(c=>[c.code,c])),d=new Map(t.data.resources.map(c=>[c.code,c])),s=new Set,a=new Set(r.map(c=>String(c?.code||"")));r.forEach((c,f)=>{let u=`${o}/policies/${f}`,p=N(c,u);C(p,["code","routeCode","mode","resourceCode","operations","fields"],u,["requiredFields","ownRecordFields","publicRecordFields","publicFilters","serverGeneratedFields","schedule","publicSubtableFields","draft","validations"]);let _=v(p.code,`${u}/code`);s.has(_)&&m("NATIVE_PUBLIC_POLICY_DUPLICATE",`${u}/code`);let E=v(p.routeCode,`${u}/routeCode`),A=i.get(E);(!A||A.surface!=="user"||A.capability!==void 0||A.access!==void 0||/[:*]/.test(String(A.path)))&&m("NATIVE_PUBLIC_ROUTE_INVALID",`${u}/routeCode`),F(p.mode,"anonymous",`${u}/mode`);let O=H(p.resourceCode,`${u}/resourceCode`),b=d.get(O);b||m("NATIVE_PUBLIC_RESOURCE_MISSING",`${u}/resourceCode`);let g=new Map(b.schema.fields.map(P=>[String(P.code),String(P.type)])),I=V(p.operations,`${u}/operations`,8);(I.length<1||I.some(P=>!Jd.has(P)))&&m("NATIVE_PUBLIC_OPERATION_INVALID",`${u}/operations`),I.includes("draft.read")!==I.includes("draft.update")&&m("NATIVE_PUBLIC_DRAFT_OPERATION_INCOMPLETE",`${u}/operations`);let T=V(p.fields,`${u}/fields`,64);(T.length<1||T.some(P=>!g.has(P)))&&m("NATIVE_PUBLIC_FIELD_INVALID",`${u}/fields`);for(let P of["requiredFields","ownRecordFields","publicRecordFields"]){if(!Object.prototype.hasOwnProperty.call(p,P))continue;V(p[P],`${u}/${P}`,64).some(x=>!T.includes(x))&&m("NATIVE_PUBLIC_FIELD_SCOPE_INVALID",`${u}/${P}`)}let l=Object.prototype.hasOwnProperty.call(p,"serverGeneratedFields")?D(p.serverGeneratedFields,`${u}/serverGeneratedFields`,16):[],y=new Set;l.forEach((P,M)=>{let x=`${u}/serverGeneratedFields/${M}`,z=N(P,x);C(z,["field","kind"],x);let q=G(z.field,`${x}/field`);(y.has(q)||!g.has(q)||T.includes(q)||g.get(q)!=="text.short"&&g.get(q)!=="text.long")&&m("NATIVE_PUBLIC_SERVER_GENERATED_FIELD_INVALID",`${x}/field`),F(z.kind,"random-token",`${x}/kind`),y.add(q)});let R=Object.prototype.hasOwnProperty.call(p,"schedule")?N(p.schedule,`${u}/schedule`):null;if(R){let P=["campusPolicyCode","rulePolicyCode","campusField","ruleCampusField","ruleWeekdaysField","ruleOpenAtField","ruleCloseAtField","ruleSlotMinutesField","ruleAdvanceHoursField","ruleAdvanceDaysField","campusEnabledField","ruleEnabledField","dateField","timeField"];C(R,P,`${u}/schedule`);for(let M of["campusPolicyCode","rulePolicyCode"])v(R[M],`${u}/schedule/${M}`);for(let M of P.filter(x=>!["campusPolicyCode","rulePolicyCode"].includes(x)))G(R[M],`${u}/schedule/${M}`);for(let M of[R.campusField,R.dateField,R.timeField])T.includes(String(M))||m("NATIVE_PUBLIC_SCHEDULE_FIELD_INVALID",`${u}/schedule`);(!a.has(String(R.campusPolicyCode))||!a.has(String(R.rulePolicyCode)))&&m("NATIVE_PUBLIC_SCHEDULE_POLICY_INVALID",`${u}/schedule`)}let h=Object.prototype.hasOwnProperty.call(p,"publicFilters")?D(p.publicFilters,`${u}/publicFilters`,16):[],$=new Set;h.forEach((P,M)=>{let x=`${u}/publicFilters/${M}`,z=N(P,x);C(z,["field","operator","value"],x);let q=G(z.field,`${x}/field`);$.has(q)&&m("NATIVE_PUBLIC_FILTER_DUPLICATE",`${x}/field`),T.includes(q)||m("NATIVE_PUBLIC_FILTER_FIELD_INVALID",`${x}/field`),F(z.operator,"eq",`${x}/operator`),["boolean","text.short","text.long","number.integer","number.decimal","date","time"].includes(g.get(q)||"")||m("NATIVE_PUBLIC_FILTER_FIELD_INVALID",`${x}/field`),z.value!==null&&typeof z.value!="string"&&typeof z.value!="number"&&typeof z.value!="boolean"&&m("NATIVE_PUBLIC_FILTER_VALUE_INVALID",`${x}/value`),$.add(q)});let w=Object.prototype.hasOwnProperty.call(p,"publicSubtableFields")?N(p.publicSubtableFields,`${u}/publicSubtableFields`):null;if(w){Object.keys(w).length>64&&m("NATIVE_PUBLIC_SUBTABLE_FIELDS_INVALID",`${u}/publicSubtableFields`);for(let[P,M]of Object.entries(w)){let x=b.schema.fields.find(J=>String(J.code)===P),z=String(x?.subtable?.resourceCode||""),q=d.get(z),Ae=new Map((q?.schema?.fields||[]).map(J=>[String(J.code),String(J.type)])),Ne=V(M,`${u}/publicSubtableFields/${P}`,64);(!T.includes(P)||g.get(P)!=="subtable"||!q||Ne.length<1||Ne.some(J=>!Ae.has(J))||Ne.some(J=>Ae.get(J)==="subtable")||Ne.some(J=>Ae.get(J)==="signature"))&&m("NATIVE_PUBLIC_SUBTABLE_FIELDS_INVALID",`${u}/publicSubtableFields/${P}`)}}if(I.some(P=>P.startsWith("public."))){Object.prototype.hasOwnProperty.call(p,"publicRecordFields")||m("NATIVE_PUBLIC_RECORD_FIELDS_REQUIRED",`${u}/publicRecordFields`);let P=V(p.publicRecordFields,`${u}/publicRecordFields`,64);(P.length<1||P.some(M=>!T.includes(M))||P.some(M=>g.get(M)==="signature"||g.get(M)==="subtable"&&!w?.[M]))&&m("NATIVE_PUBLIC_RECORD_FIELDS_INVALID",`${u}/publicRecordFields`)}let j=Object.prototype.hasOwnProperty.call(p,"requiredFields")?V(p.requiredFields,`${u}/requiredFields`,64):[],L=b.surface||{},Q=L.fields||{},ee=String(L.mutationOwner||"native")==="native"&&L.generated?.create!==!1,Y=b.schema.fields.filter(P=>Bt(P,Q[P.code])).map(P=>String(P.code));if(I.includes("create")&&!ee&&m("NATIVE_PUBLIC_CREATE_FIELDS_INCOMPLETE",`${u}/fields`),I.includes("create")&&!Object.prototype.hasOwnProperty.call(p,"draft")&&m("NATIVE_PUBLIC_DRAFT_REQUIRED",`${u}/draft`),I.includes("create"))for(let P of Y){let M=T.includes(P)?j.includes(P)?null:"requiredFields":"fields";M&&m("NATIVE_PUBLIC_CREATE_FIELDS_INCOMPLETE",`${u}/${M}`,{resourceCode:H,fieldCode:P})}if(Object.prototype.hasOwnProperty.call(p,"draft")){let P=N(p.draft,`${u}/draft`);C(P,["enabled","inactivityTtlSeconds","maxBytes"],`${u}/draft`),F(P.enabled,!0,`${u}/draft/enabled`),se(P.inactivityTtlSeconds,`${u}/draft/inactivityTtlSeconds`,3600,7776e3),se(P.maxBytes,`${u}/draft/maxBytes`,4096,262144)}else I.includes("draft.read")&&m("NATIVE_PUBLIC_DRAFT_REQUIRED",`${u}/draft`);let ge=Object.prototype.hasOwnProperty.call(p,"validations")?D(p.validations,`${u}/validations`,16):[],oe=new Set;ge.forEach((P,M)=>{let x=`${u}/validations/${M}`,z=N(P,x);C(z,["code","kind","fields","result"],x);let q=v(z.code,`${x}/code`);oe.has(q)&&m("NATIVE_PUBLIC_VALIDATION_DUPLICATE",`${x}/code`),F(z.kind,"duplicate",`${x}/kind`),F(z.result,"availability",`${x}/result`);let Ae=V(z.fields,`${x}/fields`,8);(Ae.length<1||Ae.some(Ne=>!T.includes(Ne))||Ae.some(Ne=>["file","subtable"].includes(g.get(Ne)||"")))&&m("NATIVE_PUBLIC_VALIDATION_FIELD_INVALID",`${x}/fields`),oe.add(q)}),s.add(_)})}function Yd(e,t){let o=N(e,t);C(o,["policies"],t),D(o.policies,`${t}/policies`,16).length<1&&m("NATIVE_PUBLIC_POLICY_REQUIRED",t)}function Xd(e){return{policies:te(e.frontend.publicAccess.policies.map(t=>({code:t.code,routeCode:t.routeCode,mode:t.mode,resourceCode:t.resourceCode,operations:U(t.operations),fields:U(t.fields),...t.requiredFields?{requiredFields:U(t.requiredFields)}:{},...t.ownRecordFields?{ownRecordFields:U(t.ownRecordFields)}:{},...t.publicRecordFields?{publicRecordFields:U(t.publicRecordFields)}:{},...t.publicFilters?{publicFilters:t.publicFilters.map(o=>({field:o.field,operator:o.operator,value:o.value})).sort((o,n)=>Ie(o.field,n.field))}:{},...t.publicSubtableFields?{publicSubtableFields:Object.fromEntries(Object.entries(t.publicSubtableFields).sort(([o],[n])=>o.localeCompare(n)).map(([o,n])=>[o,U(Array.isArray(n)?n.map(String):[])]))}:{},...t.serverGeneratedFields?{serverGeneratedFields:t.serverGeneratedFields.map(o=>({field:o.field,kind:o.kind})).sort((o,n)=>Ie(o.field,n.field))}:{},...t.schedule?{schedule:{campusPolicyCode:t.schedule.campusPolicyCode,rulePolicyCode:t.schedule.rulePolicyCode,campusField:t.schedule.campusField,ruleCampusField:t.schedule.ruleCampusField,ruleWeekdaysField:t.schedule.ruleWeekdaysField,ruleOpenAtField:t.schedule.ruleOpenAtField,ruleCloseAtField:t.schedule.ruleCloseAtField,ruleSlotMinutesField:t.schedule.ruleSlotMinutesField,ruleAdvanceHoursField:t.schedule.ruleAdvanceHoursField,ruleAdvanceDaysField:t.schedule.ruleAdvanceDaysField,campusEnabledField:t.schedule.campusEnabledField,ruleEnabledField:t.schedule.ruleEnabledField,dateField:t.schedule.dateField,timeField:t.schedule.timeField}}:{},...t.draft?{draft:{...t.draft}}:{},...t.validations?{validations:te(t.validations.map(o=>({code:o.code,kind:o.kind,fields:U(o.fields),result:o.result})),o=>o.code)}:{}})),t=>t.code)}}function gs(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=As(o),r=`/admin/resources/${o.code}`,i=[["list",r],["detail",`${r}/:id`],["create",`${r}/new`],["update",`${r}/:id/edit`]];for(let[d,s]of i)n[d]&&t.push({owner:`resource:${o.code}:${d}`,path:s},{owner:`resource:${o.code}:${d}:mobile`,path:`/m${s}`})}if(e.frontend.user.applicationTodoCenter===!0&&t.push({owner:"application:todo-center",path:"/todos"},{owner:"application:todo-center:mobile",path:"/m/todos"}),e.workflows.definitions.length>0){t.push({owner:"workflow:work-center",path:"/work-center"},{owner:"workflow:work-center:mobile",path:"/m/work-center"},{owner:"workflow:task",path:"/tasks/:taskId"},{owner:"workflow:task:mobile",path:"/m/tasks/:taskId"},{owner:"workflow:instance",path:"/workflows/:instanceId"},{owner:"workflow:instance:mobile",path:"/m/workflows/:instanceId"});let o=!1;for(let n of e.workflows.definitions)["standalone","hidden-handoff"].includes(n.launch.mode)&&(o=!0);o&&t.push({owner:"workflow:launch",path:"/workflows/:workflowCode/start"},{owner:"workflow:launch:mobile",path:"/m/workflows/:workflowCode/start"})}return t}function bn(e){let t=new Map(gs(e).map(o=>[An(o.path),o]));return te(e.frontend.routes.map((o,n)=>{let r=`/config/frontend/routes/${n}`,i=N(o,r);C(i,["code","path","label","surface","parentCode","capability","access","pinned","tabPersistence","keepAlive"],r,!0),["admin","user"].includes(i.surface)||m("NATIVE_ROUTE_SURFACE_INVALID",`${r}/surface`);let d=Oe(i.path,`${r}/path`);i.surface==="admin"&&d!=="/admin"&&!d.startsWith("/admin/")&&m("NATIVE_ADMIN_ROUTE_PATH_INVALID",`${r}/path`),i.surface==="user"&&(d==="/admin"||d.startsWith("/admin/"))&&m("NATIVE_USER_ROUTE_PATH_RESERVED",`${r}/path`);let s=An(d),a=t.get(s);a&&m("NATIVE_ROUTE_PATH_CONFLICT",`${r}/path`,{path:d,owner:a.owner}),t.set(s,{owner:`frontend:${String(i.code||n)}`,path:d});let c=/[:*]/.test(d),f=Go(i,r,e.appCode),u=i.pinned===void 0?void 0:ft(i.pinned,`${r}/pinned`),p=i.tabPersistence===void 0?c?"none":"session":S(i.tabPersistence,`${r}/tabPersistence`,16),_=i.keepAlive===void 0?"none":S(i.keepAlive,`${r}/keepAlive`,16);return["session","none"].includes(p)||m("NATIVE_ROUTE_TAB_PERSISTENCE_INVALID",`${r}/tabPersistence`),["none","memory"].includes(_)||m("NATIVE_ROUTE_KEEP_ALIVE_INVALID",`${r}/keepAlive`),c&&u===!0&&m("NATIVE_DYNAMIC_ROUTE_PINNED_FORBIDDEN",`${r}/pinned`),c&&p==="session"&&m("NATIVE_DYNAMIC_ROUTE_TAB_PERSISTENCE_FORBIDDEN",`${r}/tabPersistence`),c&&_==="memory"&&m("NATIVE_DYNAMIC_ROUTE_KEEP_ALIVE_FORBIDDEN",`${r}/keepAlive`),{code:v(i.code,`${r}/code`),path:d,label:S(i.label,`${r}/label`,255),surface:i.surface,...i.parentCode===void 0?{}:{parentCode:v(i.parentCode,`${r}/parentCode`)},...f,...u===void 0?{}:{pinned:u},tabPersistence:p,keepAlive:_}}),o=>o.code)}function As(e){let t=e.surface===void 0?{}:N(e.surface,"/surface"),o=t.mutationOwner||"native",n=t.generated===void 0?{}:N(t.generated,"/surface/generated"),r=o==="native";return{list:n.list??!0,detail:n.detail??!0,create:n.create??r,update:n.update??r,delete:n.delete??r}}function Es(e){let t=[];for(let o of te(e.data.resources,n=>n.code).flatMap(n=>[{resource:n,viewCode:void 0},...(n.surface?.views||[]).map(r=>({viewCode:r.code,resource:{...n,name:r.name,surface:Qn(n.surface,r.code)}}))])){let{resource:n,viewCode:r}=o,i=`/admin/resources/${n.code}${r?`/views/${r}`:""}`,d=As(n),s=[{operation:"list",kind:"resource-list",path:`${i}`,label:n.name,capability:n.capabilities.read,navigationEligible:!0},{operation:"detail",kind:"resource-detail",path:`${i}/:id`,label:`${n.name}\u8BE6\u60C5`,capability:n.capabilities.read,navigationEligible:!1},{operation:"create",kind:"resource-create",path:`${i}/new`,label:`\u65B0\u589E${n.name}`,capability:n.capabilities.create,navigationEligible:!1},{operation:"update",kind:"resource-update",path:`${i}/:id/edit`,label:`\u7F16\u8F91${n.name}`,capability:n.capabilities.update,navigationEligible:!1}];for(let a of s)d[a.operation]&&t.push({code:`resource:${n.code}${r?`:view:${r}`:""}:${a.operation}`,kind:a.kind,path:a.path,label:a.label,navigationEligible:a.navigationEligible,capability:a.capability,resourceCode:n.code,...r?{viewCode:r}:{}})}for(let o of bn(e))o.surface==="admin"&&t.push({code:`operation:${o.code}`,kind:"operation",path:o.path,label:o.label,navigationEligible:!/[:*]/.test(o.path),routeCode:o.code});return t.sort((o,n)=>Ie(o.code,n.code))}function Is(e){return e.kind==="resource"?`resource:${e.resourceCode}${e.viewCode?`:view:${e.viewCode}`:""}:list`:`operation:${e.routeCode}`}function Zd(e){return e.frontend.admin.navigation.map((t,o)=>({code:t.code,label:t.label,...t.icon===void 0?{}:{icon:t.icon},order:t.order??o,items:t.items.map((n,r)=>({pageCode:Is(n.page),...n.label===void 0?{}:{label:n.label},...n.icon===void 0?{}:{icon:n.icon},order:n.order??r})).sort((n,r)=>n.order-r.order||Ie(n.pageCode,r.pageCode))})).sort((t,o)=>t.order-o.order||Ie(t.code,o.code))}function Qd(e,t){let o=D(e,t,B.adminNavigationGroups);o.reduce((r,i)=>r+(Array.isArray(i?.items)?i.items.length:0),0)>B.adminNavigationItems&&m("NATIVE_ARRAY_LIMIT_EXCEEDED",t);let n=0;o.forEach((r,i)=>{let d=`${t}/${i}`,s=N(r,d);C(s,["code","label","icon","order","items"],d,!0),v(s.code,`${d}/code`),S(s.label,`${d}/label`,255),En(s.icon,`${d}/icon`),os(s.order,`${d}/order`);let a=D(s.items,`${d}/items`,500);a.length===0&&m("NATIVE_ADMIN_GROUP_ORPHANED",`${d}/items`),n+=a.length,n>B.adminNavigationItems&&m("NATIVE_ARRAY_LIMIT_EXCEEDED",t),a.forEach((c,f)=>{let u=`${d}/items/${f}`,p=N(c,u);C(p,["page","label","icon","order"],u,!0),ec(p.page,`${u}/page`),p.label!==void 0&&S(p.label,`${u}/label`,255),En(p.icon,`${u}/icon`),os(p.order,`${u}/order`)})})}function ec(e,t){let o=N(e,t),n=S(o.kind,`${t}/kind`,64);if(n==="resource"){C(o,["kind","resourceCode"],t,["viewCode"]),o.viewCode!==void 0&&v(o.viewCode,`${t}/viewCode`),H(o.resourceCode,`${t}/resourceCode`);return}if(n==="operation"){C(o,["kind","routeCode"],t),v(o.routeCode,`${t}/routeCode`);return}m("NATIVE_ADMIN_PAGE_REFERENCE_KIND_INVALID",`${t}/kind`)}function tc(e){let t=new Map(Es(e).map(r=>[String(r.code),r])),o=new Set,n=new Set;e.frontend.admin.navigation.forEach((r,i)=>{let d=`/config/frontend/admin/navigation/${i}`;o.has(r.code)&&m("NATIVE_ADMIN_GROUP_DUPLICATE",`${d}/code`),o.add(r.code),r.label===r.code&&m("NATIVE_ADMIN_USER_LABEL_REQUIRED",`${d}/label`),r.items.forEach((s,a)=>{let c=`${d}/items/${a}`,f=Is(s.page),u=t.get(f);(!u||u.navigationEligible!==!0)&&m("NATIVE_ADMIN_PAGE_NOT_FOUND",`${c}/page`),n.has(f)&&m("NATIVE_ADMIN_PAGE_DUPLICATE",`${c}/page`),n.add(f);let p=s.page.resourceCode||s.page.routeCode||s.page.workflowCode||f,_=s.label||u.label;(!_||_===p||_===f)&&m("NATIVE_ADMIN_USER_LABEL_REQUIRED",`${c}/label`)})})}function nc(e,t){let o=D(e,t,B.adminPages),n=new Set;o.forEach((r,i)=>{let d=`${t}/${i}`,s=N(r,d);C(s,["code","kind","path","label","navigationEligible","capability","access","resourceCode","viewCode","routeCode"],d,!0);let a=S(s.code,`${d}/code`,255);n.has(a)&&m("NATIVE_ADMIN_PAGE_DUPLICATE",`${d}/code`),n.add(a);let c=S(s.kind,`${d}/kind`,64);if(["resource-list","resource-detail","resource-create","resource-update","operation"].includes(c)||m("NATIVE_ADMIN_PAGE_KIND_INVALID",`${d}/kind`),Oe(s.path,`${d}/path`),S(s.label,`${d}/label`,255),ft(s.navigationEligible,`${d}/navigationEligible`),s.capability!==void 0&&s.access!==void 0&&m("NATIVE_ROUTE_ACCESS_CONFLICT",`${d}/access`),s.capability!==void 0&&S(s.capability,`${d}/capability`,255),s.access!==void 0){let f=N(s.access,`${d}/access`);C(f,["allOf","anyOf"],`${d}/access`,!0);for(let u of["allOf","anyOf"])f[u]!==void 0&&V(f[u],`${d}/access/${u}`,50)}for(let f of["resourceCode","viewCode","routeCode"])s[f]!==void 0&&v(s[f],`${d}/${f}`)})}function oc(e,t){let o=D(e,t,B.adminNavigationGroups);o.reduce((r,i)=>r+(Array.isArray(i?.items)?i.items.length:0),0)>B.adminNavigationItems&&m("NATIVE_ARRAY_LIMIT_EXCEEDED",t);let n=0;o.forEach((r,i)=>{let d=`${t}/${i}`,s=N(r,d);C(s,["code","label","icon","order","items"],d,!0),v(s.code,`${d}/code`),S(s.label,`${d}/label`,255),En(s.icon,`${d}/icon`),se(s.order,`${d}/order`,-1e4,1e4);let a=D(s.items,`${d}/items`,500);a.length===0&&m("NATIVE_ADMIN_GROUP_ORPHANED",`${d}/items`),n+=a.length,n>B.adminNavigationItems&&m("NATIVE_ARRAY_LIMIT_EXCEEDED",t),a.forEach((c,f)=>{let u=`${d}/items/${f}`,p=N(c,u);C(p,["pageCode","label","icon","order"],u,!0),S(p.pageCode,`${u}/pageCode`,255),p.label!==void 0&&S(p.label,`${u}/label`,255),En(p.icon,`${u}/icon`),se(p.order,`${u}/order`,-1e4,1e4)})})}var rc=new Set(["application-todo-center","workflow-work-center","workflow-launch","workflow-task","workflow-instance","resource-records","resource-submit"]);function ic(e,t,o){let n=N(e,t);C(n,["schemaVersion","appCode","devicePolicy","rootEntry","authentication","routes","digest"],t),F(n.schemaVersion,fs,`${t}/schemaVersion`),F(n.appCode,o,`${t}/appCode`),Ko(n.devicePolicy,`${t}/devicePolicy`),sc(n.rootEntry,`${t}/rootEntry`),ac(n.authentication,`${t}/authentication`),Uo(n.digest,`${t}/digest`);let r=D(n.routes,`${t}/routes`,B.routes),i=new Set;r.forEach((d,s)=>{let a=`${t}/routes/${s}`,c=N(d,a),f=c.kind==="resource-records"||c.kind==="resource-submit";C(c,["code","kind","desktop","mobile"],a,["workflowCode",...f?["resourceCode"]:[]]);let u=S(c.code,`${a}/code`,255);i.has(u)&&m("NATIVE_ROUTE_MANIFEST_DUPLICATE",`${a}/code`),i.add(u);let p=S(c.kind,`${a}/kind`,64);if(rc.has(p)||m("NATIVE_ROUTE_MANIFEST_KIND_INVALID",`${a}/kind`),c.workflowCode!==void 0&&v(c.workflowCode,`${a}/workflowCode`),f){let A=H(c.resourceCode,`${a}/resourceCode`);F(u,`user.${A}.${c.kind==="resource-records"?"records":"submit"}`,`${a}/code`)}else c.resourceCode!==void 0&&m("NATIVE_PROPERTY_UNKNOWN",`${a}/resourceCode`);let _=es(c.desktop,`${a}/desktop`,o),E=es(c.mobile,`${a}/mobile`,o);_.surface!=="user"&&m("NATIVE_ROUTE_MANIFEST_DESKTOP_SURFACE_INVALID",`${a}/desktop/surface`),E.surface!=="user"&&m("NATIVE_ROUTE_MANIFEST_MOBILE_SURFACE_INVALID",`${a}/mobile/surface`),_.routeCode===E.routeCode&&m("NATIVE_ROUTE_MANIFEST_PAIR_DUPLICATE",a)}),F(n.digest,Z({schemaVersion:n.schemaVersion,appCode:n.appCode,devicePolicy:n.devicePolicy,rootEntry:n.rootEntry,authentication:n.authentication,routes:n.routes}),`${t}/digest`)}function Ko(e,t){let o=N(e,t);C(o,["kind","mobileMaxWidthPx","desktopMinWidthPx"],t),F(o.kind,"viewport-family",`${t}/kind`);let n=se(o.mobileMaxWidthPx,`${t}/mobileMaxWidthPx`,320,1600),r=se(o.desktopMinWidthPx,`${t}/desktopMinWidthPx`,320,1600);return r!==n+1&&m("NATIVE_FRONTEND_DEVICE_POLICY_INVALID",t),{kind:"viewport-family",mobileMaxWidthPx:n,desktopMinWidthPx:r}}function sc(e,t){let o=N(e,t);C(o,["code","desktop","mobile"],t);let n=v(o.code,`${t}/code`),r=Mo(o.desktop,`${t}/desktop`),i=Mo(o.mobile,`${t}/mobile`);return(r===i||i==="/"||!i.startsWith("/m/"))&&m("NATIVE_ROUTE_MANIFEST_ROOT_ENTRY_INVALID",t),r.startsWith("/m/")&&m("NATIVE_ROUTE_MANIFEST_ROOT_ENTRY_INVALID",`${t}/desktop`),{code:n,desktop:r,mobile:i}}function ac(e,t){let o=N(e,t);C(o,["desktop","mobile"],t);let n=Qi(o.desktop,`${t}/desktop`,!1),r=Qi(o.mobile,`${t}/mobile`,!0);return(n.routeCode===r.routeCode||n.path===r.path)&&m("NATIVE_ROUTE_MANIFEST_AUTHENTICATION_DUPLICATE",t),{desktop:n,mobile:r}}function Qi(e,t,o){let n=N(e,t);C(n,["routeCode","path"],t);let r=v(n.routeCode,`${t}/routeCode`),i=Mo(n.path,`${t}/path`);return(o?!i.startsWith("/m/"):i.startsWith("/m/"))&&m("NATIVE_ROUTE_MANIFEST_AUTHENTICATION_PATH_INVALID",`${t}/path`),{routeCode:r,path:i}}function Mo(e,t){let o=Oe(e,t);return/[:*?#\\\\]/.test(o)&&m("NATIVE_ROUTE_MANIFEST_STATIC_PATH_INVALID",t),o}function es(e,t,o){let n=N(e,t);C(n,["routeCode","path","surface","pathParams","requiresAuthentication"],t,["capability","access"]),v(n.routeCode,`${t}/routeCode`);let r=Oe(n.path,`${t}/path`),i=S(n.surface,`${t}/surface`,16);["admin","user"].includes(i)||m("NATIVE_ROUTE_SURFACE_INVALID",`${t}/surface`);let d=V(n.pathParams,`${t}/pathParams`,8);return d.forEach((s,a)=>{(!/^[A-Za-z][A-Za-z0-9_]*$/.test(s)||s.length>64)&&m("NATIVE_ROUTE_PATH_PARAM_INVALID",`${t}/pathParams/${a}`)}),X(d)!==X(ys(r))&&m("NATIVE_ROUTE_PATH_PARAMS_MISMATCH",`${t}/pathParams`),Go(n,t,o),n.requiresAuthentication!==!0&&m("NATIVE_ROUTE_AUTHENTICATION_REQUIRED",`${t}/requiresAuthentication`),n}function ys(e){return U([...e.matchAll(/:([A-Za-z][A-Za-z0-9_]*)/g)].map(t=>t[1]))}function ts(e,t,o,n){return{routeCode:e,path:t,surface:o,pathParams:ys(t),...n?.capability?{capability:n.capability}:{},...n?.access?{access:n.access}:{},requiresAuthentication:!0}}function ns(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 dc(e){let t=e.appCode,o=[],n=(_,E,A,O,b,g,I)=>{o.push({code:_,kind:E,...b?{workflowCode:b}:{},...I?{resourceCode:I}:{},desktop:ts(ns(E,"desktop",b,I),A,"user",g),mobile:ts(ns(E,"mobile",b,I),O,"user",g)})};e.frontend.user.applicationTodoCenter===!0&&n("application:todo-center","application-todo-center","/todos","/m/todos");let r=bs(e);r.length>0&&(n("workflow:work-center","workflow-work-center","/work-center","/m/work-center"),n("workflow:task","workflow-task","/tasks/:taskId","/m/tasks/:taskId"),n("workflow:instance","workflow-instance","/workflows/:instanceId","/m/workflows/:instanceId"));for(let _ of r){if(!["standalone","hidden-handoff"].includes(_.launch.mode))continue;let E=U([_.launch.submission?.create?.requiredCapability,_.launch.submission?.existing?.requiredCapability].filter(A=>!!A));n(`workflow:${_.code}:launch`,"workflow-launch","/workflows/:workflowCode/start","/m/workflows/:workflowCode/start",_.code,E.length===1?{capability:E[0]}:E.length>1?{access:{anyOf:E}}:void 0)}let i=o.sort((_,E)=>Ie(String(_.code),String(E.code))),d=bn(e),s=_=>{let E=_==="mobile"?"/m/":"/",A=d.filter(b=>b.surface==="user"&&!/[:*?#\\\\]/.test(b.path)&&b.path===E).sort((b,g)=>Ie(b.code,g.code))[0];if(A)return{code:A.code,path:A.path};let O=d.filter(b=>b.surface==="user"&&!/[:*?#\\\\]/.test(b.path)&&(_==="mobile"?b.path.startsWith("/m/"):!b.path.startsWith("/m/"))).sort((b,g)=>Ie(b.code,g.code))[0];return O?{code:O.code,path:O.path}:{code:_==="mobile"?"application-root-mobile":"application-root",path:E}},a=e.frontend.authentication?{desktop:{routeCode:e.frontend.authentication.surfaces.desktop.routeCode,path:e.frontend.authentication.surfaces.desktop.path},mobile:{routeCode:e.frontend.authentication.surfaces.mobile.routeCode,path:e.frontend.authentication.surfaces.mobile.path}}:{desktop:{routeCode:"application-login",path:"/login"},mobile:{routeCode:"application-login-mobile",path:"/m/login"}},c=Ko(e.frontend.devicePolicy,"/config/frontend/devicePolicy"),f=s("desktop"),u=s("mobile"),p={schemaVersion:fs,appCode:t,devicePolicy:c,rootEntry:{code:f.code,desktop:f.path,mobile:u.path},authentication:a,routes:i};return{...p,digest:Z(p)}}function En(e,t){if(e===void 0)return;let o=S(e,t,32);Od.has(o)||m("NATIVE_ADMIN_ICON_INVALID",t)}function os(e,t){e!==void 0&&se(e,t,-1e4,1e4)}function Go(e,t,o){return e.capability!==void 0&&e.access!==void 0&&m("NATIVE_ROUTE_ACCESS_CONFLICT",`${t}/access`),e.capability!==void 0?{capability:me(e.capability,`${t}/capability`,o)}:e.access===void 0?{}:{access:On(e.access,`${t}/access`,o)}}function On(e,t,o){let n=N(e,t);C(n,["allOf","anyOf"],t,!0);let r=n.allOf===void 0?void 0:U(V(n.allOf,`${t}/allOf`,50).map((d,s)=>me(d,`${t}/allOf/${s}`,o))),i=n.anyOf===void 0?void 0:U(V(n.anyOf,`${t}/anyOf`,50).map((d,s)=>me(d,`${t}/anyOf/${s}`,o)));return(r?.length||0)+(i?.length||0)===0&&m("NATIVE_ROUTE_ACCESS_EMPTY",t),{...r===void 0?{}:{allOf:r},...i===void 0?{}:{anyOf:i}}}function bs(e){let t=new Map(ms(e).map(r=>[String(r.code),r])),o=e.workflows.definitions.map((r,i)=>{let d=`/config/workflows/definitions/${i}`,s=N(r,d);C(s,["version","definition","launch"],d,["detailRouteCode"]);let a=N(s.definition,`${d}/definition`),c=s.detailRouteCode===void 0?void 0:Ns(s.detailRouteCode,`${d}/detailRouteCode`);return{code:v(a.code,`${d}/definition/code`),title:S(a.title,`${d}/definition/title`,255),version:ut(s.version,`${d}/version`),launch:cc(e,a,s.launch,`${d}/launch`,t),...c?{detailRouteCode:c}:{},definition:a}});return U(o.map(r=>r.code)).map(r=>{let i=o.filter(c=>c.code===r),d=e.workflows.activations.find(c=>c.workflowCode===r)?.definitionVersion,s=i.find(c=>c.version===d)||[...i].sort((c,f)=>f.version-c.version)[0],a=new Set;for(let c of i){let f=N(c.definition.nodes,"/config/workflows/definitions/nodes");for(let u of Object.values(f)){let p=N(u,"/config/workflows/definitions/nodes/*");if(p.kind==="approval")for(let _ of V(p.allowedOperations||[],"/config/workflows/definitions/nodes/*/allowedOperations",20))a.add(_)}}return{code:r,title:s.title,acceptedCommandDeactivationPolicy:s.definition.acceptedCommandDeactivationPolicy,subject:s.definition.subject,launch:s.launch,...["standalone","hidden-handoff"].includes(s.launch.mode)&&!s.launch.submission?{processOperationCode:`openxiangda.workflow.${r}.submit`}:{},...s.detailRouteCode?{detailRouteCode:s.detailRouteCode}:{},definitionVersions:ls(i.map(c=>c.version)),bindingVersions:ls(e.workflows.bindings.map((c,f)=>{let u=`/config/workflows/bindings/${f}`,p=N(c,u),_=N(p.binding,`${u}/binding`);return{code:v(_.workflowCode,`${u}/binding/workflowCode`),version:ut(p.version,`${u}/version`)}}).filter(c=>c.code===r).map(c=>c.version)),providerCodes:U(e.workflows.providers.map((c,f)=>v(N(c,`/config/workflows/providers/${f}`).code,`/config/workflows/providers/${f}/code`))),allowedOperations:[...a].sort(Ie),editableParameterCodes:U(e.workflows.editableParameters.map((c,f)=>{let u=`/config/workflows/editableParameters/${f}`,p=N(c,u);return{code:v(p.code,`${u}/code`),workflowCode:v(p.workflowCode,`${u}/workflowCode`)}}).filter(c=>c.workflowCode===r).map(c=>c.code))}})}function Os(e,t){let o=N(e,t);C(o,["mode"],t,["submission"]);let n=S(o.mode,`${t}/mode`,32);return["standalone","custom-page","hidden-handoff","work-center-only"].includes(n)||m("NATIVE_WORKFLOW_LAUNCH_MODE_INVALID",`${t}/mode`),{mode:n,...o.submission===void 0?{}:{submission:N(o.submission,`${t}/submission`)}}}function cc(e,t,o,n,r){let i=Os(o,n);if(!i.submission)return{mode:i.mode};["standalone","hidden-handoff"].includes(i.mode)||m("NATIVE_WORKFLOW_NAMED_OPERATION_SUBMISSION_INVALID",`${n}/submission`);let d=N(i.submission,`${n}/submission`);C(d,["kind"],`${n}/submission`,["create","existing","context"]),F(d.kind,"named-operation",`${n}/submission/kind`);let s=n.endsWith("/launch")?n.slice(0,-7):n,a=N(t.subject,`${s}/definition/subject`),c=H(a.resourceCode,`${s}/definition/subject/resourceCode`),f=e.data.resources.findIndex(y=>y.code===c),u=e.data.resources[f];(f<0||!u)&&m("NATIVE_WORKFLOW_SUBJECT_RESOURCE_MISSING",`${s}/definition/subject/resourceCode`);let p=new Set(N(u.schema,`/config/data/resources/${f}/schema`).fields.map(y=>String(y.code))),_=new Map(e.backend.operations.map(y=>[String(y.code),y])),E=(y,R)=>{let h=`${n}/submission/${R}`,$=N(y,h);C($,["operationCode","inputs","output"],h);let w=v($.operationCode,`${h}/operationCode`),j=_.get(w),L=r.get(w),Q=L?.platformAccess?.workflow?.codes;(!j||!L||L.method!=="POST"||!Array.isArray(Q)||!Q.includes(t.code))&&m("NATIVE_WORKFLOW_NAMED_OPERATION_INVALID",h);let ee=N(j.requestSchema,`${h}/operation/requestSchema`),Y=N(ee.properties,`${h}/operation/requestSchema/properties`),ge=new Set(ee.required===void 0?[]:V(ee.required,`${h}/operation/requestSchema/required`,205)),oe=N($.inputs,`${h}/inputs`),P=Object.entries(oe);(!P.length||P.length>205)&&m("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${h}/inputs`);let M=new Set,x=new Map,z={},q=L.platformAccess?.ownedSubject;q&&(R!=="create"||q.resourceCode!==c)&&m("NATIVE_WORKFLOW_OWNED_SUBJECT_LAUNCH_MISMATCH",h);for(let[J,Ze]of P){(!Hi.test(J)||!Object.prototype.hasOwnProperty.call(Y,J))&&m("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${h}/inputs/${J}`);let We=`${h}/inputs/${J}`,Cn=N(Ze,We),Me=S(Cn.source,`${We}/source`,32);if(["field","idempotency-key","current-user-reference","subject-id","subject-revision","requested-at"].includes(Me)||m("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",We),C(Cn,["source"],We,Me==="field"?["fieldCode"]:!1),x.set(Me,(x.get(Me)||0)+1),Me==="field"){let Qe=G(Cn.fieldCode,`${We}/fieldCode`);(M.has(Qe)||!p.has(Qe))&&m("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${We}/fieldCode`),M.add(Qe),u.schema.fields.find(hn=>hn.code===Qe)?.type==="subtable"&&(!q||!q.subtables.some(hn=>hn.fieldCode===Qe))&&m("NATIVE_WORKFLOW_OWNED_SUBJECT_LAUNCH_REQUIRED",We),z[J]={source:Me,fieldCode:Qe}}else z[J]={source:Me}}([...ge].some(J=>!(J in oe))||(x.get("idempotency-key")||0)!==1||!P.some(([J,Ze])=>N(Ze,`${h}/inputs/${J}`).source==="idempotency-key"&&ge.has(J))||R==="create"&&((x.get("subject-id")||0)>0||(x.get("subject-revision")||0)>0)||R==="existing"&&((x.get("subject-id")||0)!==1||(x.get("subject-revision")||0)!==1))&&m("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${h}/inputs`);let Ae=N($.output,`${h}/output`);C(Ae,["subjectId"],`${h}/output`,["subjectRevision","processCommand"]);let Ne=N(N(j.responseSchema,`${h}/operation/responseSchema`).properties,`${h}/operation/responseSchema/properties`);for(let J of["subjectId","subjectRevision","processCommand"]){if(Ae[J]===void 0)continue;let Ze=S(Ae[J],`${h}/output/${J}`,128);(!Hi.test(Ze)||!Object.prototype.hasOwnProperty.call(Ne,Ze))&&m("NATIVE_WORKFLOW_NAMED_OPERATION_OUTPUT_INVALID",`${h}/output/${J}`)}return{operationCode:w,method:"POST",path:L.path,requiredCapability:L.requiredCapability,requestSchemaDigest:L.requestSchemaDigest,responseSchemaDigest:L.responseSchemaDigest,inputs:z,output:{...Ae},fieldCodes:M}},A=d.create===void 0?void 0:E(d.create,"create"),O=d.existing===void 0?void 0:E(d.existing,"existing");!A&&!O&&m("NATIVE_WORKFLOW_NAMED_OPERATION_SUBMISSION_INVALID",`${n}/submission`);let b=new Set([...A?.fieldCodes||[],...O?.fieldCodes||[]]),g=d.context===void 0?[]:D(d.context,`${n}/submission/context`,16),I=new Set,T=g.map((y,R)=>{let h=`${n}/submission/context/${R}`,$=N(y,h);C($,["queryParameter","fieldCode"],h);let w=S($.queryParameter,`${h}/queryParameter`,64),j=G($.fieldCode,`${h}/fieldCode`);return(!/^[A-Za-z][A-Za-z0-9]{0,63}$/.test(w)||I.has(w)||!b.has(j))&&m("NATIVE_WORKFLOW_LAUNCH_CONTEXT_INVALID",h),I.add(w),{queryParameter:w,fieldCode:j}}),l=y=>{let{fieldCodes:R,...h}=y;return h};return{mode:i.mode,submission:{kind:"named-operation",...A?{create:l(A)}:{},...O?{existing:l(O)}:{},context:T}}}function Ns(e,t){let o=N(e,t);C(o,["desktop","mobile"],t);let n=v(o.desktop,`${t}/desktop`),r=v(o.mobile,`${t}/mobile`);return n===r&&m("NATIVE_WORKFLOW_DETAIL_ROUTE_DUPLICATE",t),{desktop:n,mobile:r}}function lc(e,t){let o=new Set(t.map(f=>f.code)),n=new Map;e.data.resources.forEach((f,u)=>{let p=`/config/data/resources/${u}`,_=N(f,p);if(_.recordDeletion!==void 0){let O=`${p}/recordDeletion/delete`;for(let b of _.recordDeletion.delete)me(b,O,e.appCode),o.has(b)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",O)}if(_.recordComments!==void 0)for(let O of["read","create"]){let b=`${p}/recordComments/${O}`;for(let g of _.recordComments[O])me(g,b,e.appCode),o.has(g)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",b)}if(_.recordPrint!==void 0){let O=`${p}/recordPrint/read`;for(let b of _.recordPrint.read)me(b,O,e.appCode),o.has(b)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",O)}if(_.workflowHistory!==void 0){let O=`${p}/workflowHistory/read`;for(let b of _.workflowHistory.read)me(b,O,e.appCode),o.has(b)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",O)}for(let[O,b]of Object.entries(_.fieldPolicies||{})){if(!_t(O))continue;let g=`${p}/fieldPolicies/${O}/read`,I=N(b,`${p}/fieldPolicies/${O}`);for(let T of V(I.read||[],g,2e3))o.has(T)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",g)}let E=_.surface===void 0?{}:N(_.surface,`${p}/surface`);if(["native","queued-command"].includes(E.mutationOwner||"native"))return;let A=N(_.capabilities,`${p}/capabilities`);for(let O of["create","update","delete"])O==="delete"&&Array.isArray(_.recordDeletion?.delete)&&_.recordDeletion.delete.length>0||n.set(String(A[O]),O)});let r=new Set;for(let[f,u]of e.authz.roles.entries()){let p=`/config/authz/roles/${f}`,_=N(u,p);C(_,["code","name","description","capabilities"],p,!0);let E=v(_.code,`${p}/code`);r.has(E)&&m("NATIVE_ROLE_DUPLICATE",`${p}/code`),r.add(E),S(_.name,`${p}/name`,255);let A=V(_.capabilities,`${p}/capabilities`,2e3);for(let[O,b]of A.entries())n.has(b)&&m("NATIVE_DATA_SURFACE_MUTATION_GRANT_FORBIDDEN",`${p}/capabilities/${O}`,{operation:n.get(b)}),o.has(b)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",`${p}/capabilities`)}let i=e.authz.authenticatedUserRoleCode===void 0?"":v(e.authz.authenticatedUserRoleCode,"/config/authz/authenticatedUserRoleCode");i&&!r.has(i)&&m("NATIVE_AUTHENTICATED_USER_ROLE_REFERENCE_MISSING","/config/authz/authenticatedUserRoleCode");let d=new Set,s=0;for(let[f,u]of e.perspectives.entries()){let p=`/config/perspectives/${f}`,_=N(u,p);C(_,["code","name","description","roleCodes","capabilityCodes","default"],p,!0);let E=v(_.code,`${p}/code`);d.has(E)&&m("NATIVE_PERSPECTIVE_DUPLICATE",`${p}/code`),d.add(E),S(_.name,`${p}/name`,255);let A=V(_.roleCodes,`${p}/roleCodes`,20);A.length<1&&m("NATIVE_PERSPECTIVE_ROLE_REQUIRED",`${p}/roleCodes`),A.forEach((g,I)=>{r.has(g)||m("NATIVE_PERSPECTIVE_ROLE_MISSING",`${p}/roleCodes/${I}`)});let O=U(e.authz.roles.filter(g=>A.includes(g.code)).flatMap(g=>g.capabilities)),b=V(_.capabilityCodes,`${p}/capabilityCodes`,2e3);X(O)!==X(b)&&m("NATIVE_PERSPECTIVE_CAPABILITY_PROJECTION_MISMATCH",`${p}/capabilityCodes`),_.default===!0?s+=1:_.default!==void 0&&m("NATIVE_PERSPECTIVE_DEFAULT_INVALID",`${p}/default`)}s>1&&m("NATIVE_PERSPECTIVE_DEFAULT_DUPLICATE","/config/perspectives");for(let[f,u]of e.backend.operations.entries()){let p=N(u,`/config/backend/operations/${f}`);o.has(p.capability)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",`/config/backend/operations/${f}/capability`)}let a=new Set,c=new Set;for(let[f,u]of e.frontend.routes.entries()){let p=`/config/frontend/routes/${f}`,_=N(u,p),E=v(_.code,`${p}/code`);a.has(E)&&m("NATIVE_ROUTE_DUPLICATE",`${p}/code`),a.add(E);let A=Oe(_.path,`${p}/path`);c.has(A)&&m("NATIVE_ROUTE_PATH_DUPLICATE",`${p}/path`),c.add(A);let O=Go(_,p,e.appCode);O.capability&&!o.has(O.capability)&&m("NATIVE_CAPABILITY_REFERENCE_MISSING",`${p}/capability`);let b=_.access===void 0?void 0:N(_.access,`${p}/access`);for(let g of["allOf","anyOf"]){let I=b?.[g]===void 0?[]:D(b[g],`${p}/access/${g}`,50);for(let[T,l]of I.entries()){let y=me(l,`${p}/access/${g}/${T}`,e.appCode);o.has(y)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",`${p}/access/${g}/${T}`)}}}if(e.frontend.admin.access!==void 0){let f=On(e.frontend.admin.access,"/config/frontend/admin/access",e.appCode);for(let u of["allOf","anyOf"])for(let[p,_]of(f[u]||[]).entries())o.has(_)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",`/config/frontend/admin/access/${u}/${p}`)}for(let[f,u]of e.frontend.routes.entries()){let p=N(u,`/config/frontend/routes/${f}`);p.parentCode&&!a.has(p.parentCode)&&m("NATIVE_ROUTE_PARENT_MISSING",`/config/frontend/routes/${f}/parentCode`)}}function uc(e){let t=new Set(e.authz.roles.map(c=>String(c.code))),o=e.authz.authenticatedUserRoleCode===void 0?"":v(e.authz.authenticatedUserRoleCode,"/config/authz/authenticatedUserRoleCode"),n=new Map(e.authz.scopeDimensions.map(c=>[String(c.code),{valueType:c.valueType==="uuid"?"uuid":"string",...c.valueSource?.resourceCode?{valueSourceResourceCode:String(c.valueSource.resourceCode)}:{}}])),r=new Set(n.keys()),i=new Map(e.data.resources.map((c,f)=>{let u=Ye(c,`/config/data/resources/${f}`,e.appCode);return[u.code,new Map(u.schema.fields.map(p=>[String(p.code),p]))]}));for(let[c,f]of e.authz.scopeDimensions.entries()){let u=`/config/authz/scopeDimensions/${c}`,p=N(f,u);if(C(p,["code","name","resourceCode","valueType","hierarchyMode","valueSource"],u,!0),p.valueSource===void 0)continue;let _=N(p.valueSource,`${u}/valueSource`);C(_,["kind","resourceCode","labelField","enabledField"],`${u}/valueSource`,!0),_.kind!=="native_resource"&&m("NATIVE_SCOPE_VALUE_SOURCE_KIND_INVALID",`${u}/valueSource/kind`),p.valueType!=="uuid"&&m("NATIVE_SCOPE_VALUE_SOURCE_TYPE_INVALID",`${u}/valueType`);let E=H(_.resourceCode,`${u}/valueSource/resourceCode`),A=i.get(E);A||m("NATIVE_SCOPE_VALUE_SOURCE_RESOURCE_MISSING",`${u}/valueSource/resourceCode`);let O=G(_.labelField,`${u}/valueSource/labelField`);if(["text.short","text.long"].includes(String(A.get(O)?.type||""))||m("NATIVE_SCOPE_VALUE_SOURCE_LABEL_FIELD_INVALID",`${u}/valueSource/labelField`),_.enabledField!==void 0){let b=G(_.enabledField,`${u}/valueSource/enabledField`);A.get(b)?.type!=="boolean"&&m("NATIVE_SCOPE_VALUE_SOURCE_ENABLED_FIELD_INVALID",`${u}/valueSource/enabledField`)}}let d=new Set,s=new Set;for(let[c,f]of e.authz.scopeSources.entries()){let u=`/config/authz/scopeSources/${c}`,p=N(f,u);C(p,["code","name","resourceCode","subject","grants","operationField","enabledField","effectiveFromField","effectiveToField","failureMode"],u,!0);let _=v(p.code,`${u}/code`);d.has(_)&&m("NATIVE_SCOPE_SOURCE_DUPLICATE",`${u}/code`),d.add(_),S(p.name,`${u}/name`,255);let E=H(p.resourceCode,`${u}/resourceCode`),A=i.get(E);A||m("NATIVE_SCOPE_SOURCE_RESOURCE_MISSING",`${u}/resourceCode`);let O=N(p.subject,`${u}/subject`),b=S(O.type,`${u}/subject/type`,32);C(O,b==="role_membership"?["type","userIdField","roleCode"]:["type","userIdField"],`${u}/subject`),["user","role_membership"].includes(b)||m("NATIVE_SCOPE_SOURCE_SUBJECT_INVALID",`${u}/subject/type`);let g=It(O.userIdField,A);so(g)||m("NATIVE_SCOPE_SOURCE_SUBJECT_PATH_INVALID",`${u}/subject/userIdField`),b==="role_membership"&&!t.has(String(O.roleCode))&&m("NATIVE_ROLE_REFERENCE_MISSING",`${u}/subject/roleCode`);let I=new Set;for(let[T,l]of D(p.grants,`${u}/grants`,100).entries()){let y=`${u}/grants/${T}`,R=N(l,y);C(R,["dimensionCode","valueField","parentValueField"],y,!0);let h=v(R.dimensionCode,`${y}/dimensionCode`);(!r.has(h)||I.has(h))&&m("NATIVE_SCOPE_SOURCE_DIMENSION_INVALID",`${y}/dimensionCode`),I.add(h),p.failureMode==="last_known_good"&&s.add(h);for(let $ of["valueField","parentValueField"]){if(R[$]===void 0)continue;let w=It(R[$],A);vr(w,n.get(h),i)||m("NATIVE_SCOPE_SOURCE_GRANT_PATH_INVALID",`${y}/${$}`)}}I.size===0&&m("NATIVE_SCOPE_SOURCE_GRANT_REQUIRED",`${u}/grants`),["strict","last_known_good"].includes(p.failureMode)||m("NATIVE_SCOPE_SOURCE_FAILURE_MODE_INVALID",`${u}/failureMode`);for(let T of["operationField","enabledField","effectiveFromField","effectiveToField"]){if(p[T]===void 0)continue;let l=G(p[T],`${u}/${T}`);A.has(l)||m("NATIVE_SCOPE_SOURCE_FIELD_MISSING",`${u}/${T}`)}}pc(e,t,i,o);let a=new Set;for(let[c,f]of e.authz.dataPolicies.entries()){let u=`/config/authz/dataPolicies/${c}`,p=N(f,u);C(p,["code","name","resourceCode","unrestrictedRoleCodes","publicRead","operations","matchMode","rules","readExpression","writeBoundary"],u,!0);let _=v(p.code,`${u}/code`);a.has(_)&&m("NATIVE_DATA_POLICY_DUPLICATE",`${u}/code`),a.add(_);let E=p.readExpression!==void 0,A=V(p.operations||[],`${u}/operations`,4);p.operations!==void 0&&(A.length===0||A.some(l=>!["read","create","update","delete"].includes(l)))&&m("NATIVE_DATA_POLICY_OPERATIONS_INVALID",`${u}/operations`),["AND","OR"].includes(p.matchMode)||m("NATIVE_DATA_POLICY_MATCH_MODE_INVALID",`${u}/matchMode`),E&&p.operations!==void 0&&m("NATIVE_DATA_POLICY_READ_EXPRESSION_OPERATIONS_FORBIDDEN",`${u}/operations`);let O=e.data.resources.find(l=>l.dataPolicyCode===_),b=p.resourceCode||O?.code,g=b?i.get(H(b,`${u}/resourceCode`)):void 0;if(E&&!g&&m("NATIVE_DATA_POLICY_RESOURCE_MISSING",`${u}/resourceCode`),p.publicRead!==void 0){try{let l=e.authz.roles.find(y=>y.code===o);qr({policy:p,resource:e.data.resources.find(y=>y.code===b),baselineRoleCode:o,baselineCapabilities:l?.capabilities||[],baselineDeniedCapabilities:l?.deniedCapabilities||[],pointer:u})}catch(l){if(!(l instanceof Nt))throw l;m(l.code,l.pointer)}(p.unrestrictedRoleCodes||[]).includes(o)||m("AUTHENTICATED_PUBLIC_READ_CANONICAL_BASELINE_MISSING",`${u}/unrestrictedRoleCodes`)}else o&&(p.unrestrictedRoleCodes||[]).includes(o)&&m("NATIVE_DATA_POLICY_BASELINE_UNRESTRICTED",`${u}/unrestrictedRoleCodes`);let I=V(p.unrestrictedRoleCodes||[],`${u}/unrestrictedRoleCodes`,100);p.unrestrictedRoleCodes!==void 0&&I.length===0&&m("NATIVE_DATA_POLICY_UNRESTRICTED_ROLES_INVALID",`${u}/unrestrictedRoleCodes`);for(let l of I)t.has(l)||m("NATIVE_ROLE_REFERENCE_MISSING",`${u}/unrestrictedRoleCodes`);let T;try{let l=D(p.rules,`${u}/rules`,100).map((y,R)=>({rule:N(y,`${u}/rules/${R}`),pointer:`${u}/rules/${R}`}));l.length===0?(!E||p.matchMode!=="AND"||p.writeBoundary!=="capability_only")&&m("NATIVE_DATA_POLICY_WRITE_BOUNDARY_REQUIRED",u):p.writeBoundary!==void 0&&m("NATIVE_DATA_POLICY_WRITE_BOUNDARY_INVALID",`${u}/writeBoundary`),T=[...l],E&&(T.push(...st(p.readExpression,`${u}/readExpression`)),Lr(p.readExpression,`${u}/readExpression`))}catch(l){throw l instanceof Ot&&m(l.code,l.pointer),l}for(let{rule:l,pointer:y}of T){if(C(l,["parentRead","subject","dimensionCode","relationCode","resourceCode","field","roleCodes","operation","valuePath","emptyMatchesAll","operator","value","operand"],y,!0),l.parentRead!==void 0){for(let Y of V(l.roleCodes||[],`${y}/roleCodes`,100))t.has(Y)||m("NATIVE_ROLE_REFERENCE_MISSING",`${y}/roleCodes`);continue}let R=G(l.field,`${y}/field`),h=g?.get(R);E&&!h&&m("NATIVE_DATA_POLICY_FIELD_MISSING",`${y}/field`);for(let Y of V(l.roleCodes||[],`${y}/roleCodes`,100))t.has(Y)||m("NATIVE_ROLE_REFERENCE_MISSING",`${y}/roleCodes`);let $=String(l.operator||""),w=l.operand==="db_now",j=["is_null","is_not_null"].includes($),L=["eq","not_eq","in","not_in"].includes($),Q=!w&&(l.operator!==void 0||l.value!==void 0);if([l.subject==="current_user"?"current_user":"",typeof l.dimensionCode=="string"?"dimension":"",typeof l.relationCode=="string"?"relationship":"",Q?"constant":"",w?"db_now":""].filter(Boolean).length!==1&&m("NATIVE_DATA_POLICY_RULE_SOURCE_INVALID",y),l.subject!==void 0&&l.subject!=="current_user"&&m("NATIVE_DATA_POLICY_SUBJECT_INVALID",`${y}/subject`),Q){if(!L&&!j&&m("NATIVE_DATA_POLICY_OPERATOR_INVALID",`${y}/operator`),["in","not_in"].includes($)){let Y=D(l.value,`${y}/value`,100).map((ge,oe)=>S(ge,`${y}/value/${oe}`,2048));(Y.length===0||new Set(Y).size!==Y.length)&&m("NATIVE_DATA_POLICY_VALUE_INVALID",`${y}/value`)}else["eq","not_eq"].includes($)?S(l.value,`${y}/value`,2048):(l.value!==void 0||l.operand!==void 0)&&m("NATIVE_DATA_POLICY_VALUE_INVALID",`${y}/value`);for(let Y of["operation","valuePath","emptyMatchesAll","resourceCode","operand"])l[Y]!==void 0&&m("NATIVE_DATA_POLICY_CONSTANT_RULE_INVALID",`${y}/${Y}`)}if(w){(!["lt","lte","gt","gte"].includes($)||l.value!==void 0||h?.type!=="datetime")&&m("NATIVE_DATA_POLICY_DB_NOW_INVALID",y);for(let Y of["operation","valuePath","emptyMatchesAll","resourceCode","value"])l[Y]!==void 0&&m("NATIVE_DATA_POLICY_DB_NOW_INVALID",`${y}/${Y}`)}l.dimensionCode&&!r.has(l.dimensionCode)&&m("NATIVE_SCOPE_DIMENSION_MISSING",`${y}/dimensionCode`),s.has(String(l.dimensionCode||""))&&l.operation!=="read"&&m("NATIVE_SCOPE_SOURCE_LAST_KNOWN_GOOD_UNSAFE",`${y}/operation`)}}try{Wr(e.data.resources,e.authz.dataPolicies)}catch(c){throw c instanceof ue&&m(c.code,c.pointer),c}for(let[c,f]of e.data.resources.entries()){let u=N(f,`/config/data/resources/${c}`);u.dataPolicyCode&&!a.has(u.dataPolicyCode)&&m("NATIVE_DATA_POLICY_REFERENCE_MISSING",`/config/data/resources/${c}/dataPolicyCode`)}}function fc(e){try{fr(e.data.resources,"/config/data/resources"),e.data.resources.forEach((t,o)=>or(t.schema.fields,new Set(e.authz.roles.map(n=>n.code)),new Set(e.authz.scopeDimensions.map(n=>n.code)),`/config/data/resources/${o}/schema/fields`))}catch(t){throw(t instanceof Re||t instanceof Ue)&&m(t.code,t.pointer),t}}function pc(e,t,o,n){let r=new Set;for(let[i,d]of e.authz.roleMembershipSources.entries()){let s=`/config/authz/roleMembershipSources/${i}`,a=N(d,s);C(a,["code","name","resourceCode","userIdField","roleCode","enabledField","effectiveFromField","effectiveToField","failureMode"],s,!0);let c=v(a.code,`${s}/code`);c.length>100&&m("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_CODE_INVALID",`${s}/code`),r.has(c)&&m("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_DUPLICATE",`${s}/code`),r.add(c),S(a.name,`${s}/name`,255);let f=rs(a.resourceCode,`${s}/resourceCode`,o);is(a.userIdField,`${s}/userIdField`,f),t.has(String(a.roleCode||""))||m("NATIVE_ROLE_REFERENCE_MISSING",`${s}/roleCode`),n&&a.roleCode===n&&m("NATIVE_AUTHENTICATED_USER_ROLE_SOURCE_CONFLICT",`${s}/roleCode`),ss(a,s,f)}for(let[i,d]of e.authz.relationshipGrantSources.entries()){let s=`/config/authz/relationshipGrantSources/${i}`,a=N(d,s);C(a,["code","name","resourceCode","subject","relationCode","targetResourceCode","resourceIdField","operations","enabledField","effectiveFromField","effectiveToField","failureMode"],s,!0);let c=v(a.code,`${s}/code`);c.length>100&&m("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_CODE_INVALID",`${s}/code`),r.has(c)&&m("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_DUPLICATE",`${s}/code`),r.add(c),S(a.name,`${s}/name`,255);let f=rs(a.resourceCode,`${s}/resourceCode`,o),u=N(a.subject,`${s}/subject`),p=S(u.type,`${s}/subject/type`,32);C(u,p==="role_membership"?["type","userIdField","roleCode"]:["type","userIdField"],`${s}/subject`),["user","role_membership"].includes(p)||m("NATIVE_AUTHORIZATION_PROJECTION_SUBJECT_INVALID",`${s}/subject/type`),is(u.userIdField,`${s}/subject/userIdField`,f),p==="role_membership"&&!t.has(String(u.roleCode||""))&&m("NATIVE_ROLE_REFERENCE_MISSING",`${s}/subject/roleCode`),v(a.relationCode,`${s}/relationCode`);let _=H(a.targetResourceCode,`${s}/targetResourceCode`);o.has(_)||m("NATIVE_AUTHORIZATION_PROJECTION_TARGET_RESOURCE_MISSING",`${s}/targetResourceCode`);let E=It(a.resourceIdField,f),A=E?.field.type==="resource-ref.single"&&E.valuePath==="value"&&E.field.source?.resourceCode===_;(a.resourceIdField==="id"?_!==String(a.resourceCode):!A)&&m("NATIVE_AUTHORIZATION_PROJECTION_RESOURCE_ID_FIELD_INVALID",`${s}/resourceIdField`);let O=V(a.operations,`${s}/operations`,20);(O.length===0||O.some(b=>b.length>64||!/^[A-Za-z0-9][A-Za-z0-9:._*-]{0,63}$/.test(b)))&&m("NATIVE_AUTHORIZATION_PROJECTION_OPERATIONS_INVALID",`${s}/operations`),ss(a,s,f)}}function rs(e,t,o){let n=H(e,t),r=o.get(n);return r||m("NATIVE_AUTHORIZATION_PROJECTION_RESOURCE_MISSING",t),r}function is(e,t,o){let n=It(e,o);so(n)||m("NATIVE_AUTHORIZATION_PROJECTION_USER_FIELD_INVALID",t)}function ss(e,t,o){if(e.failureMode!=="strict"&&m("NATIVE_AUTHORIZATION_PROJECTION_FAILURE_MODE_INVALID",`${t}/failureMode`),e.enabledField!==void 0){let n=G(e.enabledField,`${t}/enabledField`);o.get(n)?.type!=="boolean"&&m("NATIVE_AUTHORIZATION_PROJECTION_ENABLED_FIELD_INVALID",`${t}/enabledField`)}for(let n of["effectiveFromField","effectiveToField"]){if(e[n]===void 0)continue;let r=G(e[n],`${t}/${n}`);["date","datetime"].includes(String(o.get(r)?.type))||m("NATIVE_AUTHORIZATION_PROJECTION_EFFECTIVE_FIELD_INVALID",`${t}/${n}`)}}function mc(e){let t=new Set,o=new Set;e.forEach((n,r)=>{let i=`/config/backend/secrets/${r}`,d=N(n,i);C(d,["name","env","description","required","exposure"],i,!0);let s=S(d.name,`${i}/name`,128),a=S(d.env,`${i}/env`,128);md.test(s)||m("NATIVE_SECRET_NAME_INVALID",`${i}/name`),(!_d.test(a)||a.startsWith("OPENXIANGDA_")||["NODE_ENV","PORT"].includes(a))&&m("NATIVE_SECRET_ENV_INVALID",`${i}/env`),t.has(s)&&m("NATIVE_SECRET_NAME_DUPLICATE",`${i}/name`),o.has(a)&&m("NATIVE_SECRET_ENV_DUPLICATE",`${i}/env`),t.add(s),o.add(a),F(d.exposure,"active_only",`${i}/exposure`),d.required!==void 0&&ft(d.required,`${i}/required`),d.description!==void 0&&zo(d.description,`${i}/description`,2e3)})}function _c(e){let t=new Set,o=new Map,n=new Map(e.data.resources.map(_=>[String(_.code),_])),r=new Map(e.frontend.routes.map((_,E)=>{let A=N(_,`/config/frontend/routes/${E}`);return[v(A.code,`/config/frontend/routes/${E}/code`),A]}));for(let[_,E]of e.workflows.definitions.entries()){let A=`/config/workflows/definitions/${_}`,O=N(E,A);if(C(O,["version","definition","launch"],A,["detailRouteCode"]),Os(O.launch,`${A}/launch`),O.detailRouteCode!==void 0){let w=Ns(O.detailRouteCode,`${A}/detailRouteCode`);for(let[j,L,Q]of[["desktop",w.desktop,["admin","user"]],["mobile",w.mobile,["user"]]]){let ee=`${A}/detailRouteCode/${j}`,Y=r.get(L);Y||m("NATIVE_WORKFLOW_DETAIL_ROUTE_MISSING",ee),Q.some(P=>P===Y.surface)||m("NATIVE_WORKFLOW_DETAIL_ROUTE_SURFACE_INVALID",ee);let ge=Oe(Y.path,ee),oe=[...ge.matchAll(/:([A-Za-z][A-Za-z0-9_]*)/g)].map(P=>P[1]);(ge.includes("*")||oe.length!==1||oe[0]!=="instanceId")&&m("NATIVE_WORKFLOW_DETAIL_ROUTE_PATH_INVALID",ee)}}let b=N(O.definition,`${A}/definition`),g=`${b.code}:${ut(O.version,`${A}/version`)}`;t.has(g)&&m("NATIVE_WORKFLOW_DEFINITION_DUPLICATE",A),t.add(g),Ac(b,`${A}/definition`);let I=Co(b);I.length&&m(I[0],`${A}/definition/launchPreflight`);let T=Si(b);T.length&&m(T[0],`${A}/definition/approvedDelegation`);let l=Ci(b,e.backend.operations);l.length&&m(l[0],`${A}/definition/commandHandlers`),gc(b.subject,n,`${A}/definition/subject`);let y=b.commandHandlers?.resubmit?.derivedSubjectFields||[],R=n.get(b.subject.resourceCode);for(let w of y){let j=R?.schema.fields.find(L=>L.code===w);(!j||j.system===!0||R?.surface?.fields?.[w]?.system===!0)&&m("WORKFLOW_CORRECTION_DERIVED_SUBJECT_FIELDS_INVALID",`${A}/definition/commandHandlers/resubmit/derivedSubjectFields`)}let h=un(b,new Map((n.get(b.subject.resourceCode)?.schema.fields||[]).map(w=>[w.code,{...n.get(b.subject.resourceCode)?.surface?.fields?.[w.code],...w,system:["id","revision","createdAt","updatedAt","createdBy","updatedBy"].includes(w.code)}])),new Map([...n].map(([w,j])=>[w,new Map(j.schema.fields.map(L=>[L.code,{...j.surface?.fields?.[L.code],...L,system:["id","revision","createdAt","updatedAt","createdBy","updatedBy"].includes(L.code)}]))])),jt(n.get(b.subject.resourceCode)?.schema||{}));h.length&&m(h[0],`${A}/definition/taskPages`);let $=ni(b,{appCode:e.appCode,capabilities:e.authz.capabilities.map(w=>w.code),fields:new Map((n.get(b.subject.resourceCode)?.schema.fields||[]).map(w=>[w.code,w]))});$.length&&m("NATIVE_WORKFLOW_INSTANCE_COMMAND_POLICY_INVALID",`${A}/definition/instanceCommands`,{errors:$}),b.title===b.code&&m("NATIVE_WORKFLOW_USER_TITLE_REQUIRED",`${A}/definition/title`),o.set(g,b)}let i=new Set,d=new Map;for(let[_,E]of e.workflows.bindings.entries()){let A=N(E,`/config/workflows/bindings/${_}`),O=N(A.binding,`/config/workflows/bindings/${_}/binding`),b=`${O.workflowCode}:${ut(A.version,`/config/workflows/bindings/${_}/version`)}`;i.has(b)&&m("NATIVE_WORKFLOW_BINDING_DUPLICATE",`/config/workflows/bindings/${_}`),i.add(b),Ec(O,`/config/workflows/bindings/${_}/binding`),d.set(b,O)}let s=new Set,a=new Map;for(let[_,E]of e.workflows.activations.entries()){let A=`/config/workflows/activations/${_}`,O=N(E,A);C(O,["workflowCode","definitionVersion","bindingVersion","acceptedCommandDeactivationPolicy"],A,["environmentKey"]);let b=v(O.workflowCode,`${A}/workflowCode`);s.has(b)&&m("NATIVE_WORKFLOW_ACTIVATION_DUPLICATE",A),s.add(b);let g=`${b}:${ut(O.definitionVersion,`${A}/definitionVersion`)}`,I=`${b}:${ut(O.bindingVersion,`${A}/bindingVersion`)}`;t.has(g)||m("NATIVE_WORKFLOW_DEFINITION_REFERENCE_MISSING",`${A}/definitionVersion`),i.has(I)||m("NATIVE_WORKFLOW_BINDING_REFERENCE_MISSING",`${A}/bindingVersion`);let T=o.get(g),l=d.get(I),y=Co(T,l);y.length&&m(y[0],A);let R=No(T,l);R.length&&m(R[0],A),(!["finish-pinned","cancel-on-deactivate"].includes(O.acceptedCommandDeactivationPolicy)||O.acceptedCommandDeactivationPolicy!==T.acceptedCommandDeactivationPolicy)&&m("NATIVE_WORKFLOW_COMMAND_DEACTIVATION_POLICY_MISMATCH",`${A}/acceptedCommandDeactivationPolicy`),Ic(T,l,`/config/workflows/activations/${_}`);try{let h=n.get(T.subject.resourceCode)?.schema.fields||[];rr(T,l,new Map(h.map($=>[$.code,$])),`${A}/bindings`,new Map([...n].map(([$,w])=>[$,new Map(w.schema.fields.map(j=>[j.code,j]))])))}catch(h){throw h instanceof Ue&&m(h.code,h.pointer),h}a.set(b,l)}let c=Mi([...a.values()]);c.length&&m(c[0],"/config/workflows/activations");let f=new Set;e.workflows.providers.forEach((_,E)=>{let A=`/config/workflows/providers/${E}`,O=N(_,A);C(O,["code","endpointPath","timeoutMs"],A,!0);let b=v(O.code,`${A}/code`);f.has(b)&&m("NATIVE_WORKFLOW_PROVIDER_DUPLICATE",`${A}/code`),f.add(b),Oe(O.endpointPath,`${A}/endpointPath`),O.timeoutMs!==void 0&&se(O.timeoutMs,`${A}/timeoutMs`,100,1e4)});for(let[_,E]of a.entries())for(let[A,O]of Object.entries(N(E.bindings,"/config/workflows/bindings/*/binding/bindings"))){let b=N(O,`/config/workflows/${_}/bindings/${A}`);b.provider==="application_provider"&&!f.has(b.providerCode)&&m("NATIVE_WORKFLOW_PROVIDER_REFERENCE_MISSING",`/config/workflows/${_}/bindings/${A}/providerCode`)}let u=new Set(e.authz.roles.map(_=>_.code)),p=new Set;e.workflows.editableParameters.forEach((_,E)=>{let A=`/config/workflows/editableParameters/${E}`,O=N(_,A);C(O,["code","workflowCode","bindingKey","label","valueType","required","allowedRoleCodes","allowedProviderCodes","maxItems"],A,!0);let b=v(O.code,`${A}/code`);p.has(b)&&m("NATIVE_WORKFLOW_EDITABLE_PARAMETER_DUPLICATE",`${A}/code`),p.add(b);let g=Nn(O.workflowCode,`${A}/workflowCode`),I=In(O.bindingKey,`${A}/bindingKey`),T=a.get(g);(!T||!N(T.bindings,`${A}/bindingKey`)[I])&&m("NATIVE_WORKFLOW_EDITABLE_BINDING_MISSING",`${A}/bindingKey`),S(O.label,`${A}/label`,255),["role_code","user_ids","provider_code"].includes(O.valueType)||m("NATIVE_WORKFLOW_EDITABLE_VALUE_TYPE_INVALID",`${A}/valueType`);for(let l of V(O.allowedRoleCodes||[],`${A}/allowedRoleCodes`,100))u.has(l)||m("NATIVE_ROLE_REFERENCE_MISSING",`${A}/allowedRoleCodes`);for(let l of V(O.allowedProviderCodes||[],`${A}/allowedProviderCodes`,100))f.has(l)||m("NATIVE_WORKFLOW_PROVIDER_REFERENCE_MISSING",`${A}/allowedProviderCodes`);O.required!==void 0&&ft(O.required,`${A}/required`),O.maxItems!==void 0&&se(O.maxItems,`${A}/maxItems`,1,200)})}function gc(e,t,o){let n=N(e,o);C(n,["resourceCode","factProjection"],o,["summaryFields"]);let r=H(n.resourceCode,`${o}/resourceCode`),i=t.get(r);i||m("NATIVE_WORKFLOW_SUBJECT_RESOURCE_MISSING",`${o}/resourceCode`);let d=new Set(D(N(i.schema,`${o}/resourceCode`).fields,`${o}/resourceCode`,500).map((c,f)=>G(N(c,`${o}/resourceCode/${f}`).code,`${o}/resourceCode/${f}`))),s=N(n.factProjection,`${o}/factProjection`),a=Object.entries(s);(a.length<1||a.length>64)&&m("NATIVE_WORKFLOW_SUBJECT_FACT_PROJECTION_INVALID",`${o}/factProjection`);for(let[c,f]of a){Ed.test(c)||m("NATIVE_WORKFLOW_SUBJECT_FACT_KEY_INVALID",`${o}/factProjection/${c}`);let u=G(f,`${o}/factProjection/${c}`);d.has(u)||m("NATIVE_WORKFLOW_SUBJECT_FIELD_MISSING",`${o}/factProjection/${c}`)}if(n.summaryFields!==void 0){let c=V(n.summaryFields,`${o}/summaryFields`,Id).map((E,A)=>G(E,`${o}/summaryFields/${A}`)),f=t.get(r),u=f.surface&&typeof f.surface=="object"&&!Array.isArray(f.surface)?f.surface:{},p=u.fields&&typeof u.fields=="object"&&!Array.isArray(u.fields)?u.fields:{},_=new Map(D(N(f.schema,`${o}/resourceCode`).fields,`${o}/resourceCode`,500).map((E,A)=>{let O=N(E,`${o}/resourceCode/${A}`);return[String(O.code),O]}));for(let[E,A]of c.entries()){let O=_.get(A),b=p[A],g=String(O?.type||""),I=O?.maxLength;(!O||O.system===!0||b&&typeof b=="object"&&!Array.isArray(b)&&b.system===!0||["id","revision","created_by","updated_by","created_at","updated_at"].includes(A)||!bd.has(g)||g==="text.long"&&typeof I=="number"&&Number.isFinite(I)&&I>yd)&&m("NATIVE_WORKFLOW_SUBJECT_SUMMARY_FIELDS_INVALID",`${o}/summaryFields/${E}`)}}}function Ac(e,t){C(e,["schemaVersion","code","title","subject","acceptedCommandDeactivationPolicy","startAt","inputSchema","nodes"],t,["organizationContext","instanceCommands","readability","taskPages","rejectionNotification","commandHandlers","launchPreflight","approvedDelegation"]),F(e.schemaVersion,"openxiangda.workflow-definition/v2",`${t}/schemaVersion`),Nn(e.code,`${t}/code`),S(e.title,`${t}/title`,255),["finish-pinned","cancel-on-deactivate"].includes(e.acceptedCommandDeactivationPolicy)||m("NATIVE_WORKFLOW_COMMAND_DEACTIVATION_POLICY_REQUIRED",`${t}/acceptedCommandDeactivationPolicy`);let o=N(e.nodes,`${t}/nodes`),n=Object.keys(o);(n.length===0||n.length>200)&&m("NATIVE_WORKFLOW_NODE_COUNT_INVALID",`${t}/nodes`);let r=S(e.startAt,`${t}/startAt`,128),i=ui(e);i.length&&m(i[0],`${t}/readability`);let d=No(e);d.length&&m(d[0],`${t}/nodes`);let s=To(e);s.length&&m(s[0],`${t}/nodes`);let a=ht(e);a.length&&m(a[0],`${t}/nodes`);let c=Ni(e);c.length&&m(c[0],`${t}/nodes`);let f=Ri(e);f.length&&m(f[0],`${t}/rejectionNotification`);let u=yo(e);u.length&&m(u[0],`${t}/nodes`);let p=un(e);p.length&&m(p[0],`${t}/taskPages`);let _=on(e);_.length&&m(_[0],`${t}/nodes`),o[r]||m("NATIVE_WORKFLOW_START_NODE_MISSING",`${t}/startAt`);let E=new Map;for(let[g,I]of Object.entries(o)){let T=`${t}/nodes/${g}`,l=N(I,T);F(l.id,g,`${T}/id`),["approval","condition","end","cc","action","correction"].includes(l.kind)||m("NATIVE_WORKFLOW_NODE_KIND_INVALID",`${T}/kind`);let y=[];if(l.kind==="approval"){S(l.title,`${T}/title`,255),In(l.binding,`${T}/binding`),["single","any","all","sequence"].includes(l.mode)||m("NATIVE_WORKFLOW_APPROVAL_MODE_INVALID",`${T}/mode`),y.push(S(l.onApprove,`${T}/onApprove`,128),S(l.onReject,`${T}/onReject`,128));for(let R of V(l.returnTargets||[],`${T}/returnTargets`,200))o[R]||m("NATIVE_WORKFLOW_TARGET_MISSING",`${T}/returnTargets`);for(let R of V(l.allowedOperations||[],`${T}/allowedOperations`,20))Nd.has(R)||m("NATIVE_WORKFLOW_OPERATION_INVALID",`${T}/allowedOperations`)}else if(l.kind==="correction"){let R=Di(e);R.length&&m(R[0],T)}else if(l.kind==="action")y.push(S(l.next,`${T}/next`,128));else if(l.kind==="cc")S(l.title,`${T}/title`,255),In(l.binding,`${T}/binding`),y.push(S(l.next,`${T}/next`,128));else if(l.kind==="condition"){let R=D(l.branches,`${T}/branches`,100);R.length===0&&m("NATIVE_WORKFLOW_BRANCH_REQUIRED",`${T}/branches`),R.forEach((h,$)=>{let w=N(h,`${T}/branches/${$}`);vt(w.when,`${T}/branches/${$}/when`,0),y.push(S(w.target,`${T}/branches/${$}/target`,128))}),y.push(S(l.otherwise,`${T}/otherwise`,128))}else S(l.title,`${T}/title`,255),S(l.outcome,`${T}/outcome`,128);for(let R of y)o[R]||m("NATIVE_WORKFLOW_TARGET_MISSING",T);E.set(g,y)}let A=new Set,O=new Set,b=g=>{if(O.has(g)&&m("NATIVE_WORKFLOW_CYCLE_FORBIDDEN",`${t}/nodes/${g}`),!A.has(g)){A.add(g),O.add(g);for(let I of E.get(g)||[])b(I);O.delete(g)}};b(r);for(let g of[...A]){let I=o[g];if(I?.kind==="approval")for(let T of I.returnTargets||[])o[T]?.kind==="correction"&&A.add(T)}A.size!==n.length&&m("NATIVE_WORKFLOW_NODE_UNREACHABLE",`${t}/nodes`)}function vt(e,t,o){o>20&&m("NATIVE_WORKFLOW_EXPRESSION_DEPTH_EXCEEDED",t);let n=N(e,t),r=S(n.op,`${t}/op`,16);if(r!=="literal"){if(r==="path"){let i=S(n.path,`${t}/path`,255);(!/^[A-Za-z][A-Za-z0-9_.-]{0,254}$/.test(i)||i.split(".").some(d=>["__proto__","constructor","prototype"].includes(d)))&&m("NATIVE_WORKFLOW_EXPRESSION_PATH_INVALID",`${t}/path`);return}if(["eq","neq","gt","gte","lt","lte","in","contains"].includes(r)){vt(n.left,`${t}/left`,o+1),vt(n.right,`${t}/right`,o+1);return}if(["and","or"].includes(r)){let i=D(n.values,`${t}/values`,100);i.length===0&&m("NATIVE_WORKFLOW_EXPRESSION_EMPTY",`${t}/values`),i.forEach((d,s)=>vt(d,`${t}/values/${s}`,o+1));return}if(["not","exists"].includes(r)){vt(n.value,`${t}/value`,o+1);return}m("NATIVE_WORKFLOW_EXPRESSION_OPERATOR_INVALID",`${t}/op`)}}function Ec(e,t){F(e.schemaVersion,"openxiangda.workflow-binding/v2",`${t}/schemaVersion`),Nn(e.workflowCode,`${t}/workflowCode`);let o=N(e.bindings,`${t}/bindings`);Object.keys(o).length>200&&m("NATIVE_WORKFLOW_BINDING_LIMIT_EXCEEDED",`${t}/bindings`);for(let[n,r]of Object.entries(o)){In(n,`${t}/bindings/${n}`);let i=N(r,`${t}/bindings/${n}`),d=mi(i);d.length&&m(d[0],`${t}/bindings/${n}/selectedInputPath`);let s=an(i);s.length&&m(s[0],`${t}/bindings/${n}/roleCodes`);let a=S(i.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(i.users)||m("NATIVE_WORKFLOW_BINDING_USERS_REQUIRED",`${t}/bindings/${n}/users`),D(i.users,`${t}/bindings/${n}/users`,200)),["input_users","form_field_users"].includes(a)&&S(i.inputPath,`${t}/bindings/${n}/inputPath`,255),["app_role","app_role_in_scope","initiator_select"].includes(a)&&i.roleCodes===void 0&&v(i.roleCode,`${t}/bindings/${n}/roleCode`),a==="department_supervisor"&&S(i.departmentIdFrom,`${t}/bindings/${n}/departmentIdFrom`,255),a==="application_provider"&&v(i.providerCode,`${t}/bindings/${n}/providerCode`),i.routing!==void 0){let c=fn(i.routing);c.length&&m(c[0],`${t}/bindings/${n}/routing`)}}}function Ic(e,t,o){F(t.workflowCode,e.code,`${o}/workflowCode`);let n=N(t.bindings,`${o}/bindings`);for(let[s,a]of Object.entries(n))a.provider==="fixed_users"&&!a.users.length&&!bi(e,s)&&m("NATIVE_WORKFLOW_BINDING_USERS_REQUIRED",`${o}/bindings/${s}/users`);let r=To(e,t);r.length&&m(r[0],o);let i=yo(e,t);i.length&&m(i[0],o);let d=on(e,t);d.length&&m(d[0],o);for(let[s,a]of Object.entries(N(e.nodes,`${o}/nodes`))){let c=N(a,`${o}/nodes/${s}`);["approval","cc"].includes(c.kind)&&!n[c.binding]&&m("NATIVE_WORKFLOW_BINDING_REFERENCE_MISSING",`${o}/nodes/${s}/binding`)}}function yc(e,t,o){let n=N(t.routeManifest,"/contracts/routeManifest"),r=N(e.routeManifest,"/contracts/routeManifest"),i=new Map;for(let f of D(o.data?.resources,"/config/data/resources",B.resources)){let u=N(f,"/config/data/resources");i.set(String(u.code||""),u)}let d=new Set(D(r.routes,"/contracts/routeManifest/routes",B.routes).map(f=>String(N(f,"/contracts/routeManifest/routes").code||""))),s=[];for(let f of D(n.routes,"/contracts/routeManifest/routes",B.routes)){let u=N(f,"/contracts/routeManifest/routes"),p=String(u.kind||"");if(p!=="resource-records"&&p!=="resource-submit")continue;let _=String(u.resourceCode||""),E=i.get(_);E||m("NATIVE_ROUTE_MANIFEST_RESOURCE_UNKNOWN","/contracts/routeManifest/routes");let O=`user.${_}.${p==="resource-records"?"records":"submit"}`;F(String(u.code||""),O,"/contracts/routeManifest/routes/code");let b=p==="resource-records"?"read":"create",g=String(N(E.capabilities,"/config/data/resources/capabilities")[b]||"");for(let I of["desktop","mobile"]){let T=N(u[I],`/contracts/routeManifest/routes/${I}`),l=I==="mobile"?"/m/my/":"/my/",y=p==="resource-records"?`${l}${_}`:`${l}${_}/submit`;F(String(T.path||""),y,`/contracts/routeManifest/routes/${I}/path`),F(String(T.capability||""),g,`/contracts/routeManifest/routes/${I}/capability`),F(String(T.routeCode||""),`${O}.${I}`,`/contracts/routeManifest/routes/${I}/routeCode`)}(d.has(O)||s.some(I=>String(I.code)===O))&&m("NATIVE_ROUTE_MANIFEST_DUPLICATE","/contracts/routeManifest/routes/code"),s.push(u)}if(!s.length)return;r.routes=D([...r.routes,...s],"/contracts/routeManifest/routes",1e3).sort((f,u)=>Ie(String(N(f,"x").code||""),String(N(u,"x").code||"")));let a=String(N(n.rootEntry,"x").code||"");if(s.find(f=>String(f.code)===a&&f.kind==="resource-records")){let f=N(n.rootEntry,"x");r.rootEntry={code:a,desktop:String(f.desktop||""),mobile:String(f.mobile||"")}}r.digest=Z({schemaVersion:r.schemaVersion,appCode:r.appCode,devicePolicy:r.devicePolicy,rootEntry:r.rootEntry,authentication:r.authentication,routes:r.routes})}function Ye(e,t,o){let n=N(e,t);C(n,["schemaVersion","appCode","code","name","schema","surface","invariants","decimalReservationLifecycle","uniqueKeys","workflowHistory","recordPrint","recordComments","recordDeletion","capabilities","dataPolicyCode","fieldPolicies"],t,!0),F(n.schemaVersion,"openxiangda.data-resource/v2",`${t}/schemaVersion`),F(n.appCode,o,`${t}/appCode`);let r=H(n.code,`${t}/code`),i=S(n.name,`${t}/name`,255),d=N(n.schema,`${t}/schema`);C(d,["fields","ownedRowLimit"],`${t}/schema`,!0),d.ownedRowLimit!==void 0&&!mt(d.ownedRowLimit)&&m("NATIVE_DATA_OWNED_ROW_LIMIT_INVALID",`${t}/schema/ownedRowLimit`);let s,a,c,f;try{c=oo(n.decimalReservationLifecycle,`${t}/decimalReservationLifecycle`),s=Bn(d.fields,`${t}/schema/fields`),f=Hr(n.uniqueKeys,s,`${t}/uniqueKeys`),a=pr(n.invariants,s,`${t}/invariants`),Zn(n.surface,s,`${t}/surface`)}catch(E){throw(E instanceof Re||E instanceof Ue||E instanceof it||E instanceof Rt)&&m(E.code,E.pointer),E}if(n.recordComments!==void 0){let E=N(n.recordComments,`${t}/recordComments`);C(E,["read","create"],`${t}/recordComments`);for(let A of["read","create"]){let O=E[A];(!Array.isArray(O)||O.length>20||O.some(b=>typeof b!="string"||!b.trim())||new Set(O).size!==O.length)&&m("NATIVE_RECORD_COMMENTS_POLICY_INVALID",`${t}/recordComments/${A}`)}}if(n.recordDeletion!==void 0){let E=N(n.recordDeletion,`${t}/recordDeletion`);C(E,["delete"],`${t}/recordDeletion`);let A=E.delete;(!Array.isArray(A)||A.length>20||A.some(O=>typeof O!="string"||!O.trim())||new Set(A).size!==A.length)&&m("NATIVE_RECORD_DELETION_DELETE_INVALID",`${t}/recordDeletion/delete`)}if(n.recordPrint!==void 0){let E=N(n.recordPrint,`${t}/recordPrint`);C(E,["read"],`${t}/recordPrint`);let A=E.read;(!Array.isArray(A)||A.length>20||A.some(O=>typeof O!="string"||!O.trim())||new Set(A).size!==A.length)&&m("NATIVE_RECORD_PRINT_READ_INVALID",`${t}/recordPrint/read`)}if(n.workflowHistory!==void 0){let E=N(n.workflowHistory,`${t}/workflowHistory`);C(E,["read"],`${t}/workflowHistory`);let A=E.read;(!Array.isArray(A)||A.length>20||A.some(O=>typeof O!="string"||!O.trim())||new Set(A).size!==A.length)&&m("NATIVE_WORKFLOW_HISTORY_READ_INVALID",`${t}/workflowHistory/read`)}let u=new Set(s.map(E=>E.code)),p=N(n.capabilities,`${t}/capabilities`);C(p,["read","create","update","delete"],`${t}/capabilities`);let _=N(n.fieldPolicies,`${t}/fieldPolicies`);for(let[E,A]of Object.entries(_)){!u.has(E)&&!_t(E)&&m("NATIVE_DATA_FIELD_POLICY_FIELD_MISSING",`${t}/fieldPolicies/${E}`);let O=`${t}/fieldPolicies/${E}`,b=N(A,O);_t(E)&&(C(b,["read"],O,!0),(!Array.isArray(b.read)||b.read.length>20||b.read.some(g=>typeof g!="string"||!g.trim())||new Set(b.read).size!==b.read.length)&&m("NATIVE_DATA_AUDIT_READ_POLICY_INVALID",`${O}/read`)),C(b,["read","create","update","mask"],O,!0),b.mask!==void 0&&!["omit","null"].includes(b.mask)&&m("NATIVE_DATA_FIELD_POLICY_MASK_INVALID",`${O}/mask`)}return{...n,code:r,name:i,schema:{fields:s,...d.ownedRowLimit!==void 0?{ownedRowLimit:d.ownedRowLimit}:{}},...n.invariants===void 0?{}:{invariants:a},...c?{decimalReservationLifecycle:c}:{},...f!==void 0?{uniqueKeys:f}:{},capabilities:p,fieldPolicies:_}}function Ts(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 as(e,t,o,n){let r=e.toString("utf8"),i;try{i=JSON.parse(r)}catch{m(o,t)}let d=N(i,t);return X(d)!==r&&m(n,t),d}function gn(e,t,o){let n=0,r=(i,d,s)=>{if(n+=1,n>o&&m("NATIVE_ARTIFACT_NODE_LIMIT_EXCEEDED",d),s>Cd&&m("NATIVE_ARTIFACT_DEPTH_LIMIT_EXCEEDED",d),typeof i=="string"){Buffer.byteLength(i)>Fo&&m("NATIVE_ARTIFACT_STRING_LIMIT_EXCEEDED",d);return}if(Array.isArray(i)){i.forEach((a,c)=>r(a,`${d}/${c}`,s+1));return}if(!(!i||typeof i!="object"))for(let[a,c]of Object.entries(i))["__proto__","prototype","constructor"].includes(a)&&m("NATIVE_ARTIFACT_DANGEROUS_KEY",`${d}/${a}`),bc(a)&&m("NATIVE_ARTIFACT_RUNTIME_FIELD_FORBIDDEN",`${d}/${a}`),r(c,`${d}/${a}`,s+1)};r(e,t,0)}function bc(e){return["environmentKey","environmentId","secretValue","ciphertext","oauthClient","oauthClientId","oauthClientSecret","signingSecret","kubernetesNamespace","nodePort","productionUrl"].includes(e)}function lt(e){return{value:e,digest:Z(e)}}function ds(e,t,o,n){typeof e!="string"&&!Buffer.isBuffer(e)&&!(e instanceof Uint8Array)&&m("NATIVE_ARTIFACT_BYTES_REQUIRED",o);let r=Buffer.isBuffer(e)?e:Buffer.from(e);return r.byteLength===0&&m("NATIVE_ARTIFACT_EMPTY",o),r.byteLength>t&&m(n,o),r}function cs(e,t,o,n){let r=yn.createHash("sha256").update(e).digest("hex");yn.timingSafeEqual(Buffer.from(r),Buffer.from(t))||m(n,o)}function N(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&m("NATIVE_OBJECT_REQUIRED",t),e}function D(e,t,o){return Array.isArray(e)||m("NATIVE_ARRAY_REQUIRED",t),e.length>o&&m("NATIVE_ARRAY_LIMIT_EXCEEDED",t),e}function V(e,t,o){let n=D(e,t,o).map((r,i)=>S(r,`${t}/${i}`,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 zo(e,t,o){return(typeof e!="string"||e.length>o)&&m("NATIVE_STRING_INVALID",t),e}function v(e,t){let o=S(e,t,128);return ld.test(o)||m("NATIVE_CODE_INVALID",t),o}function H(e,t){let o=S(e,t,64);return fd.test(o)||m("NATIVE_RESOURCE_CODE_INVALID",t),o}function G(e,t){let o=S(e,t,63);return pd.test(o)||m("NATIVE_FIELD_CODE_INVALID",t),o}function Nn(e,t){let o=S(e,t,128);return gd.test(o)||m("NATIVE_WORKFLOW_CODE_INVALID",t),o}function In(e,t){let o=S(e,t,128);return Ad.test(o)||m("NATIVE_WORKFLOW_BINDING_CODE_INVALID",t),o}function me(e,t,o){let n=S(e,t,255);return cd.test(n)||m("NATIVE_CAPABILITY_CODE_INVALID",t),!n.startsWith(`app:${o}:`)&&!Ts(o).some(r=>r.code===n)&&m("NATIVE_CAPABILITY_APP_MISMATCH",t),n}function Oe(e,t){let o=S(e,t,2048);return(!o.startsWith("/")||o.startsWith("//")||o.includes("..")||o.includes("?")||o.includes("#"))&&m("NATIVE_ABSOLUTE_PATH_INVALID",t),o}function ut(e,t){return(!Number.isInteger(e)||Number(e)<1)&&m("NATIVE_POSITIVE_INTEGER_REQUIRED",t),Number(e)}function se(e,t,o,n){return(!Number.isInteger(e)||Number(e)<o||Number(e)>n)&&m("NATIVE_INTEGER_OUT_OF_RANGE",t),Number(e)}function ft(e,t){return typeof e!="boolean"&&m("NATIVE_BOOLEAN_REQUIRED",t),e}function Uo(e,t){let o=S(e,t,64).toLowerCase();return ad.test(o)||m("NATIVE_DIGEST_INVALID",t),o}function F(e,t,o){e!==t&&m("NATIVE_VALUE_MISMATCH",o)}function C(e,t,o,n=!1){let r=new Set([...t,...Array.isArray(n)?n:[]]);for(let i of Object.keys(e))r.has(i)||m("NATIVE_PROPERTY_UNKNOWN",`${o}/${i}`);if(n!==!0)for(let i of t)Object.prototype.hasOwnProperty.call(e,i)||m("NATIVE_PROPERTY_REQUIRED",`${o}/${i}`)}function te(e,t){return[...e].sort((o,n)=>Ie(t(o),t(n)))}function U(e){return[...new Set(e)].sort(Ie)}function ls(e){return[...new Set(e)].sort((t,o)=>t-o)}function Ie(e,t){return e===t?0:e<t?-1:1}function Rs(e){return!e||typeof e!="object"||Object.isFrozen(e)||(Object.freeze(e),Object.values(e).forEach(t=>Rs(t))),e}function Bo(e,t,o){if(Lo(e,t))return o;if(Array.isArray(e)&&Array.isArray(t)){let n=Math.max(e.length,t.length);for(let r=0;r<n;r+=1)if(!Lo(e[r],t[r]))return Bo(e[r],t[r],`${o}/${r}`)}if(e&&t&&typeof e=="object"&&typeof t=="object"&&!Array.isArray(e)&&!Array.isArray(t)){let n=U([...Object.keys(e),...Object.keys(t)]);for(let r of n){let i=e[r],d=t[r];if(!Lo(i,d))return Bo(i,d,`${o}/${r}`)}}return o}function Lo(e,t){return e===void 0||t===void 0?e===t:X(e)===X(t)}function m(e,t,o={}){throw new Wo(e,t,o)}var fp="openxiangda.workflow-step-data-command/v1",Oc="openxiangda.workflow-step-data-resolution/v1";function pp(e,t,o=!1){let n=s=>!!s&&typeof s=="object"&&!Array.isArray(s),r=s=>typeof s=="string"&&/^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(s),i=()=>{throw new Error("WORKFLOW_STEP_DATA_RESPONSE_INVALID")};if(!n(e)||e.schemaVersion!==Oc||e.executionId!==t||Object.keys(e).some(s=>!["schemaVersion","executionId","outcome","transaction"].includes(s)))return i();if(e.outcome==="not_observed"&&!Object.hasOwn(e,"transaction")&&!o)return e;let d=e.transaction;if(e.outcome!=="committed"||!n(d)||d.schemaVersion!=="openxiangda.data-transaction-result/v2"||d.idempotencyKey!==`workflow-step:${t}`||typeof d.replayed!="boolean"||!Array.isArray(d.items)||d.items.length<1||d.items.length>sr||d.evaluatedAt!==void 0&&(typeof d.evaluatedAt!="string"||!Number.isFinite(Date.parse(d.evaluatedAt))))return i();for(let[s,a]of d.items.entries()){if(!n(a)||a.index!==s)return i();if(a.operation==="emitEvent"){if(typeof a.eventType!="string"||!a.eventType||!r(a.eventId))return i()}else if(!["create","update","delete","increment"].includes(a.operation)||typeof a.resourceCode!="string"||!a.resourceCode||!r(a.id)||!Number.isSafeInteger(a.revision)||a.revision<1)return i()}return e}var _p=50,gp=131072,qo=class extends Error{constructor(o){super("OPENXIANGDA_NATIVE_AUTHZ_BATCH_INPUT_INVALID");this.pointer=o}pointer;code="OPENXIANGDA_NATIVE_AUTHZ_BATCH_INPUT_INVALID";status=400};function Ap(e){let t=u=>{throw new qo(u)},o=(u,p)=>((!u||typeof u!="object"||Array.isArray(u))&&t(p),u),n=(u,p,_)=>{for(let E of Object.keys(u))p.includes(E)||t(`${_}/${E}`)},r=(u,p,_)=>((typeof u!="string"||!u.trim()||u.length>p)&&t(_),u),i=(u,p)=>{let _=r(u,36,p);return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(_)||t(p),_.toLowerCase()},d=o(e,""),s;try{s=new TextEncoder().encode(JSON.stringify(d)).byteLength}catch{t("")}s>131072&&t(""),n(d,["schemaVersion","environmentKey","items"],""),d.schemaVersion!=="openxiangda.native-role-membership-batch-request/v2"&&t("/schemaVersion"),d.environmentKey!==void 0&&!["preproduction","production"].includes(String(d.environmentKey))&&t("/environmentKey"),(!Array.isArray(d.items)||d.items.length<1||d.items.length>50)&&t("/items");let a=new Set,c=new Set,f;for(let[u,p]of d.items.entries()){let _=`/items/${u}`,E=o(p,_);["create","update","revoke"].includes(String(E.operation))||t(`${_}/operation`),f??=E.operation,f!==E.operation&&t(`${_}/operation`),n(E,["operation","operationId","reason",...f==="create"?["userId","roleCode"]:["membershipId","expectedRevision"],...f!=="revoke"?["scopeGrants","validFrom","validTo"]:[]],_);let A=i(E.operationId,`${_}/operationId`);a.has(A)&&t(`${_}/operationId`),a.add(A),r(E.reason,1e3,`${_}/reason`);let O;if(f==="create"){let b=r(E.userId,255,`${_}/userId`),g=r(E.roleCode,128,`${_}/roleCode`);/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/.test(g)||t(`${_}/roleCode`),O=JSON.stringify([b,g])}else O=i(E.membershipId,`${_}/membershipId`),(!Number.isSafeInteger(E.expectedRevision)||Number(E.expectedRevision)<1)&&t(`${_}/expectedRevision`);c.has(O)&&t(_),c.add(O),E.scopeGrants!==void 0&&(!Array.isArray(E.scopeGrants)||E.scopeGrants.length>100)&&t(`${_}/scopeGrants`);for(let b of["validFrom","validTo"])E[b]!==void 0&&E[b]!==null&&r(E[b],64,`${_}/${b}`)}}var Ss="openxiangda.workflow-delegation-administration/v2",Ds="openxiangda.workflow-delegation-mutation/v2",Cs="openxiangda.workflow-delegation-preview/v2";var Lt={type:"string",format:"uuid",pattern:"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$"},_e={type:"string",minLength:1,maxLength:255},Xe={type:"string",format:"date-time"},pt={type:"integer",minimum:1},Nc={anyOf:[Xe,{type:"null"}]},Jo={anyOf:[_e,{type:"null"}]},ks={anyOf:[{type:"string",pattern:"^[A-Za-z0-9._:-]{1,128}$"},{type:"null"}]},Tn={type:"string",pattern:"^membership:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},$s={const:"future-assignments-only"},Ho={schemaVersion:{const:Ss},id:Lt,appCode:_e,environmentKey:_e,workflowCode:Jo,nodeId:ks,delegatorUserId:_e,delegateUserId:_e,delegatorRoleSubjectKey:Tn,delegateRoleSubjectKey:Tn,validFrom:Xe,validTo:Xe,status:{enum:["active","revoked","expired"]},reason:{type:"string",minLength:1,maxLength:4e3},createdBy:_e,createdAt:Xe,revokedAt:Nc,revision:pt,roleCode:_e,roleName:_e,delegatorDisplayName:_e,delegateDisplayName:_e,delegatorRoleSubjectRevision:pt,delegateRoleSubjectRevision:pt,effectiveState:{enum:["active","scheduled","expired","revoked","ineligible"]},evaluatedAt:Xe,issues:{type:"array",maxItems:20,uniqueItems:!0,items:_e},canRevoke:{type:"boolean"},revokedBy:Jo,revokeReason:{type:["string","null"],maxLength:4e3},taskPolicy:$s},Yo={type:"object",additionalProperties:!1,required:Object.keys(Ho).filter(e=>e!=="nodeId"),properties:Ho},Ip={$id:Ss,...Yo},Ps={schemaVersion:{const:Ds},operationId:Lt,environmentKey:{enum:["preproduction","production"]},reason:{type:"string",minLength:1,maxLength:2e3,pattern:"\\S"}},hs={...Ps,operation:{const:"create"},workflowCode:Jo,nodeId:ks,delegatorRoleSubjectKey:Tn,expectedDelegatorRevision:pt,delegateUserId:_e,delegateRoleSubjectKey:Tn,expectedDelegateRevision:pt,validFrom:Xe,validTo:Xe},ws={...Ps,operation:{const:"revoke"},delegationId:Lt,expectedRevision:pt},Tc={$id:Ds,type:"object",oneOf:[{type:"object",additionalProperties:!1,required:Object.keys(hs).filter(e=>e!=="nodeId"),properties:hs,if:{required:["nodeId"],properties:{nodeId:{type:"string"}}},then:{properties:{workflowCode:_e}}},{type:"object",additionalProperties:!1,required:Object.keys(ws),properties:ws}]},Rc={type:"string",pattern:"^[0-9a-f]{64}$"},yp={$id:Cs,type:"object",additionalProperties:!1,required:["schemaVersion","operationId","operation","requestDigest","before","after","taskPolicy"],properties:{schemaVersion:{const:Cs},operationId:Lt,operation:{enum:["create","revoke"]},requestDigest:Rc,before:{anyOf:[Yo,{type:"null"}]},after:{...Yo,properties:{...Ho,id:{anyOf:[Lt,{type:"null"}]}}},taskPolicy:$s}};function Np(e){return e===void 0?"":`
9
+ ${Z(e)}`}function Tp(e,t){let o=e.handlers.find(n=>n.code===t);return Z(o?.workflowStep?o:e)}var Cp="openxiangda.data-business-command/v1",Cc="openxiangda.data-business-command-resolution/v1",hp=65536;function wp(e){let t=0,o=0,n=new Set,r=new TextEncoder,i=()=>{throw new Error("OPENXIANGDA_DATA_COMMAND_INTENT_INVALID")},d=a=>(o+=r.encode(a).byteLength,o>65536&&i(),a),s=(a,c)=>{if(++t>1e4||c>32)return i();if(a===null||typeof a=="string"||typeof a=="boolean")return d(JSON.stringify(a));if(typeof a=="number")return Number.isFinite(a)?d(JSON.stringify(a)):i();if(!a||typeof a!="object"||n.has(a)||Object.getOwnPropertySymbols(a).length)return i();n.add(a);let f;if(Array.isArray(a))return Object.keys(a).length!==a.length?i():(f=d("[")+a.map((p,_)=>(_?d(","):"")+s(p,c+1)).join("")+d("]"),n.delete(a),f);let u=Object.getPrototypeOf(a);return u!==Object.prototype&&u!==null?i():(f=d("{")+Object.keys(a).sort().map((p,_)=>(_?d(","):"")+d(JSON.stringify(p))+d(":")+s(a[p],c+1)).join("")+d("}"),n.delete(a),f)};return!e||typeof e!="object"||Array.isArray(e)?i():s(e,0)}function Sp(e,t,o=!1){let n=e,r=()=>{throw new Error("OPENXIANGDA_DATA_COMMAND_RESPONSE_INVALID")};if(!n||typeof n!="object"||n.schemaVersion!==Cc)return r();for(let a of["appCode","environmentKey","operationCode","idempotencyKey","intentDigest"])if(n[a]!==t[a])return r();if(typeof n.observedAt!="string"||!Number.isFinite(Date.parse(n.observedAt)))return r();if(n.outcome==="not_observed"&&n.receipt===null&&!o)return n;if(n.outcome!=="committed"||!n.receipt)return r();let i=n.receipt,d=a=>typeof a=="string"&&/^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(a);if(!d(i.id)||!d(i.appVersionId)||!Number.isSafeInteger(i.environmentHeadRevision)||i.environmentHeadRevision<1||typeof i.completedAt!="string"||!Number.isFinite(Date.parse(i.completedAt)))return r();let s=i.transaction;if(!s||s.schemaVersion!=="openxiangda.data-transaction-result/v2"||s.idempotencyKey!==t.idempotencyKey||typeof s.replayed!="boolean"||!Array.isArray(s.items)||!s.items.length||s.items.length>1e3)return r();for(let[a,c]of s.items.entries()){if(!c||c.index!==a)return r();if(c.operation==="emitEvent"){if(!d(c.eventId)||typeof c.eventType!="string"||!c.eventType)return r()}else if(!["create","update","delete","increment"].includes(c.operation)||!d(c.id)||typeof c.resourceCode!="string"||!c.resourceCode||!Number.isSafeInteger(c.revision)||c.revision<1)return r()}return n}var vs=/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/,Rn=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Ft=(e,t)=>typeof e=="string"&&e.length<=t&&e.trim().length>0&&e===e.trim(),Xo=(e,t,o=[])=>t.every(n=>Object.hasOwn(e,n))&&Object.keys(e).every(n=>[...t,...o].includes(n));function kp(e){if(!Rn(e)||!Xo(e,["kind","errorCode","anyOf"],["allowAppSuperAdmin"])||e.kind!=="actor-authority"||!Ft(e.errorCode,110)||!/^OPENXIANGDA_[A-Z0-9_]{1,96}$/.test(e.errorCode)||Object.hasOwn(e,"allowAppSuperAdmin")&&typeof e.allowAppSuperAdmin!="boolean"||!Array.isArray(e.anyOf)||e.anyOf.length<1||e.anyOf.length>20)return!1;let t=new Set;return e.anyOf.every(o=>{if(!Rn(o)||!Xo(o,["roleCode"],["scope"])||!Ft(o.roleCode,100)||!vs.test(o.roleCode))return!1;if(Object.hasOwn(o,"scope")){let i=o.scope;if(!Rn(i)||!Xo(i,["dimensionCode","value","operation"])||!Ft(i.dimensionCode,100)||!vs.test(i.dimensionCode)||!Ft(i.value,255)||!Ft(i.operation,64)||!/^[A-Za-z0-9*][A-Za-z0-9*._:-]*$/.test(i.operation))return!1}let n=o.scope,r=JSON.stringify([o.roleCode,n?.dimensionCode,n?.value,n?.operation]);return t.has(r)?!1:(t.add(r),!0)})}function $p(e,t,o){if(t.roleSource!=="package"||t.roleCode!==e.roleCode||!o||!t.capabilityCodes.includes(o))return!1;if(!e.scope)return!0;let n;try{n=JSON.parse(t.scopeGrantsJson)}catch{return!1}if(!Array.isArray(n))return!1;let r=e.scope;return n.some(i=>Rn(i)&&i.dimensionCode===r.dimensionCode&&Array.isArray(i.values)&&i.values.includes(r.value)&&(i.operations===void 0||i.operations===null||Array.isArray(i.operations)&&(!i.operations.length||i.operations.includes("*")||i.operations.includes(r.operation))))}var vp=500,hc=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Zo=e=>!!e&&typeof e=="object"&&!Array.isArray(e);function Vp(e){if(!Zo(e)||e.kind!=="record-set-match"||Object.keys(e).some(o=>!["kind","resourceCode","errorCode","records","where"].includes(o))||typeof e.resourceCode!="string"||e.resourceCode.length>64||!/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/.test(e.resourceCode)||typeof e.errorCode!="string"||!/^OPENXIANGDA_[A-Z0-9_]{1,96}$/.test(e.errorCode)||!Array.isArray(e.records)||!e.records.length||e.records.length>500||Object.hasOwn(e,"where")&&!Zo(e.where))return!1;let t=new Set;return e.records.every(o=>{if(!Zo(o)||Object.keys(o).length!==2||typeof o.id!="string"||!hc.test(o.id)||!Number.isSafeInteger(o.expectedRevision)||Number(o.expectedRevision)<1)return!1;let n=o.id.toLowerCase();return t.has(n)?!1:(t.add(n),!0)})}function wc(e,t){if(t===void 0)return e;let o=e.views?.find(d=>d.code===t);if(!o)throw new Error(`DATA_RESOURCE_VIEW_NOT_FOUND: ${t}`);let n=new Map(o.sections?.flatMap(d=>d.fields.map(s=>[s,d.title]))),{views:r,...i}=e;return{...i,generated:o.generated,list:o.list,form:o.form,detail:o.detail,mobile:o.mobile,fields:Object.fromEntries(Object.entries(e.fields).map(([d,s])=>{let{section:a,...c}=s,f=n.get(d);return[d,{...c,...f?{section:f}:{},list:o.list.fieldOrder?.includes(d)??!1}]}))}}var Sc="openxiangda.development-configuration/v2",Vs="openxiangda.development-configuration-manifest/v1",Wp="application.development-configuration",Mp="/openxiangda-api/v2/applications/{appCode}/dev-sessions/configuration",Qo=class extends Error{constructor(o,n){super(o);this.code=o;this.pointer=n;this.data={pointer:n}}code;pointer;status=400;data};function je(e){throw new Qo("OPENXIANGDA_CONNECTED_DEV_CONFIGURATION_INVALID",e)}function Dc(e){(!e||typeof e!="object"||Array.isArray(e))&&je("/packageManifest");let t=e,o=["schemaVersion","appCode","version","configDigest","contractDigest","source","toolchain","artifacts"];(Object.keys(t).some(r=>!o.includes(r))||t.schemaVersion!==Vs||typeof t.appCode!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(t.appCode)||!/^[a-f0-9]{64}$/.test(t.configDigest)||!/^[a-f0-9]{64}$/.test(t.contractDigest)||t.version!==`development-${t.configDigest}`)&&je("/packageManifest"),(!t.source||typeof t.source!="object"||Array.isArray(t.source)||Object.keys(t.source).some(r=>!["repository","commit","dirty"].includes(r))||![null,"string"].includes(t.source.repository===null?null:typeof t.source.repository)||t.source.repository!==null&&(t.source.repository.length>1024||/[\r\n\0]/.test(t.source.repository))||t.source.commit!==null&&(typeof t.source.commit!="string"||!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(t.source.commit))||typeof t.source.dirty!="boolean")&&je("/packageManifest/source"),(!t.toolchain||Object.keys(t.toolchain).some(r=>!["version","contractVersion"].includes(r))||typeof t.toolchain.version!="string"||!/^[A-Za-z0-9][A-Za-z0-9.+_-]{0,127}$/.test(t.toolchain.version)||t.toolchain.contractVersion!==$o)&&je("/packageManifest/toolchain");let n=[{kind:"config",digest:t.configDigest,mediaType:"application/json"},{kind:"contracts",digest:t.contractDigest,mediaType:"application/json"}];return X(t.artifacts)!==X(n)&&je("/packageManifest/artifacts"),t}function Up(e,t){return Dc({schemaVersion:Vs,appCode:e,version:`development-${t.configDigest}`,configDigest:t.configDigest,contractDigest:t.contractDigest,source:{...t.source},toolchain:{version:t.toolchainVersion,contractVersion:$o},artifacts:[{kind:"config",digest:t.configDigest,mediaType:"application/json"},{kind:"contracts",digest:t.contractDigest,mediaType:"application/json"}]})}function Bp(e,t,o){return(!Number.isSafeInteger(t)||t<1)&&je("/expectedHeadRevision"),`development:${Z({manifest:e,expectedHeadRevision:t,...o?{actorUserId:o}:{}})}`}function Kp(e,t,o){(!e||typeof e!="object"||Array.isArray(e))&&je("/result");let n=e,r=["schemaVersion","appCode","environmentKey","environmentId","appVersionId","configurationRunId","headRevision","publishedAppVersionId","selection","configDigest","contractDigest","reused","runtimeArtifactsDeployed","backendEventsAvailable"],i=/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/i;return(Object.keys(n).some(d=>!r.includes(d))||n.schemaVersion!==Sc||n.appCode!==t||n.environmentKey!=="preproduction"||n.configDigest!==o.configDigest||n.contractDigest!==o.contractDigest||!i.test(n.environmentId)||!i.test(n.appVersionId)||!i.test(n.publishedAppVersionId)||n.appVersionId===n.publishedAppVersionId||n.selection!=="session"||!i.test(n.configurationRunId)||typeof n.reused!="boolean"||!Number.isSafeInteger(n.headRevision)||n.headRevision<1||n.headRevision!==o.expectedHeadRevision||n.runtimeArtifactsDeployed!==!1||n.backendEventsAvailable!==!1)&&je("/result"),n}var zp="application.development-backend-events",qp="openxiangda.development-backend/v1",Jp="application.development-backend-invocations",kc="openxiangda.development-backend-invocation/v1",Hp=262144,Yp=1048576,Xp=131072,Zp=131072,Qp=8,em=45,tm=/^\/__platform\/events\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;function nm(e){return(e.backend?.operations?.length||0)>0||(e.workflows?.providers?.length||0)>0||(e.events?.subscriptions||[]).some(t=>t.execution?.kind!=="native-data")}function om(e){return`connected-development:${e}`}function $c(e){if(typeof e!="string"||e.length%4!==0||!/^[A-Za-z0-9+/]*={0,2}$/.test(e))return null;let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=e.endsWith("==")?2:e.endsWith("=")?1:0;return o&&t.indexOf(e[e.length-o-1])%(o===2?16:4)!==0?null:e.length/4*3-o}function Pc(e,t,o){if(!["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(e)||o.method!==e||typeof t!="string"||t.length>2048||!t.startsWith("/")||t.startsWith("//")||t.startsWith("/__platform")||/[\\?#\s\u0000-\u001f\u007f]/.test(t))return!1;let n=t.split("/"),r=String(o.path||"").split("/");return n.length!==r.length?!1:n.every((i,d)=>{if(d===0)return r[d]==="";let s;try{s=decodeURIComponent(i)}catch{return!1}return!s||[".",".."].includes(s)||/[\/\\\s\u0000-\u001f\u007f]/.test(s)?!1:/^:[A-Za-z][A-Za-z0-9_]*$/.test(r[d]||"")||i===r[d]})}var vc=/^(?:authorization|content-type|content-length|accept|if-match|idempotency-key|x-request-id|x-openxiangda-(?:gateway-assertion|forwarded-by|perspective|csrf-token|mcp-bus-token|dev-selection))$/i,Vc=/^(?:content-type|content-disposition|cache-control|etag|last-modified|retry-after)$/i;function Lc(e,t=!1){if(!e||typeof e!="object"||Array.isArray(e))return!1;let o=Object.entries(e),n=o.map(([r])=>r.toLowerCase());return o.length<=24&&new Set(n).size===n.length&&o.every(([r,i])=>(t?Vc:vc).test(r)&&typeof i=="string"&&i.length<=8192&&!/[\r\n\u0000]/.test(i))}function rm(e){let t=$c(e.body);return e.schemaVersion===kc&&!!e.operation&&typeof e.operation.code=="string"&&e.operation.code.length<=128&&e.operation.code.length>0&&Pc(e.method,e.endpointPath,e.operation)&&typeof e.canonicalQuery=="string"&&e.canonicalQuery.length<=8192&&!/[\s#\u0000-\u001f\u007f]/.test(e.canonicalQuery)&&t!==null&&t<=262144&&Lc(e.headers)&&Object.entries(e.headers).some(([o,n])=>o.toLowerCase()==="authorization"&&/^Bearer \S+$/.test(n))&&Object.entries(e.headers).some(([o,n])=>o.toLowerCase()==="x-openxiangda-gateway-assertion"&&!!n)}var sm=Object.freeze({version:"rich-text-html/1",maxBytes:1048576,maxNodes:25e3,maxDepth:128,maxImages:20,imageMaxBytes:10485760,maxVideos:4,videoMaxBytes:104857600,imageTypes:["image/png","image/jpeg","image/webp","image/gif"],videoTypes:["video/mp4","video/webm"],fonts:["Arial","Verdana","Tahoma","Times New Roman","Courier New","\u5B8B\u4F53","\u5FAE\u8F6F\u96C5\u9ED1","SimSun","Microsoft YaHei","sans-serif","serif","monospace"]});var dm="2884482bb1c398e21f3b3f8fad18ecca4f890b33a2894c7999f7ff4f00a35527";export{Nt as AuthenticatedPublicReadContractError,Kt as DATA_AUDIT_METADATA_FIELDS,hp as DATA_BUSINESS_COMMAND_INTENT_MAX_BYTES,Cc as DATA_BUSINESS_COMMAND_RESOLUTION_SCHEMA,Cp as DATA_BUSINESS_COMMAND_SCHEMA,xo as DATA_EVENT_TYPES_V2,Kc as DATA_FORM_DRAFT_MAX_BYTES,ir as DATA_RESOURCE_MAX_FIELDS,$n as DATA_SUBTABLE_DEFAULT_TOTAL_ROWS,Be as DATA_SUBTABLE_MAX_ROWS,tt as DATA_SUBTABLE_MAX_TOTAL_ROWS,Xs as DATA_SYSTEM_SORT_FIELD_CODES,Bc as DATA_TRANSACTION_MAX_BYTES,sr as DATA_TRANSACTION_MAX_OPERATIONS,vp as DATA_TRANSACTION_RECORD_SET_MAX_RECORDS,Bu as DATE_EVENT_RESERVED_DATA_FIELDS_V2,em as DEVELOPMENT_BACKEND_CONNECTION_TTL_SECONDS,tm as DEVELOPMENT_BACKEND_ENDPOINT_PATTERN,zp as DEVELOPMENT_BACKEND_FEATURE,Jp as DEVELOPMENT_BACKEND_INVOCATION_FEATURE,Hp as DEVELOPMENT_BACKEND_INVOCATION_MAX_REQUEST_BYTES,Yp as DEVELOPMENT_BACKEND_INVOCATION_MAX_RESPONSE_BYTES,kc as DEVELOPMENT_BACKEND_INVOCATION_SCHEMA,Qp as DEVELOPMENT_BACKEND_MAX_INFLIGHT,Zp as DEVELOPMENT_BACKEND_MAX_REQUEST_BYTES,Xp as DEVELOPMENT_BACKEND_MAX_RESPONSE_BYTES,qp as DEVELOPMENT_BACKEND_SCHEMA,Mp as DEVELOPMENT_CONFIGURATION_ENDPOINT,Wp as DEVELOPMENT_CONFIGURATION_FEATURE,Vs as DEVELOPMENT_CONFIGURATION_MANIFEST_SCHEMA,Sc as DEVELOPMENT_CONFIGURATION_SCHEMA,cn as DateEventProjectionV2Error,Qo as DevelopmentConfigurationContractError,Et as ManagedConcurrencyContractError,ie as NATIVE_ARTIFACT_CAPACITY_V2,dm as NATIVE_CONFIGURATION_VALIDATOR_DIGEST,B as NATIVE_CONTRACT_CAPACITY_V2,xl as NATIVE_DATA_POLICY_EXPRESSION_MAX_CLAUSES,Vl as NATIVE_DATA_POLICY_EXPRESSION_MAX_DEPTH,Ll as NATIVE_DATA_POLICY_EXPRESSION_MAX_GROUP_ITEMS,Fl as NATIVE_DATA_POLICY_EXPRESSION_MAX_LEAVES,jl as NATIVE_DATA_POLICY_EXPRESSION_MAX_OCCURRENCES,Zs as NATIVE_DATA_QUERY_OPERATORS_V2,ct as NATIVE_HIGH_DENSITY_ARTIFACT_CAPACITY_V2,gp as NATIVE_ROLE_MEMBERSHIP_BATCH_MAX_BYTES,_p as NATIVE_ROLE_MEMBERSHIP_BATCH_MAX_ITEMS,Yl as NATIVE_UNIQUE_KEY_MAX_BYTES,Jr as NATIVE_UNIQUE_KEY_NORMALIZERS,Wo as NativeConfigurationCompilerError,Re as NativeDataFieldContractV2Error,Ot as NativeDataPolicyExpressionV2Error,it as NativeDecimalLifecycleContractError,po as NativeEventActionContractError,ue as NativeParentReadPolicyError,qo as NativeRoleMembershipBatchInputError,io as NativeScopeSourceFieldPathV2Error,Rt as NativeUniqueKeyContractError,Ws as OPENXIANGDA_NATIVE_DATA_FIELD_TYPES_V2,Pe as OPENXIANGDA_NATIVE_DATA_SURFACE_KEYS_V2,Hn as OPENXIANGDA_NATIVE_DRAFT_STATE_KEYS_V2,Un as OPENXIANGDA_NATIVE_SYSTEM_FIELDS_V2,nt as OPENXIANGDA_NATIVE_SYSTEM_FIELD_MAP_V2,sm as RICH_TEXT_POLICY_V2,Wc as USER_CANDIDATE_MAX_SELECTIONS,xs as USER_CANDIDATE_SCOPE_FIELD_TYPES,Ue as UserCandidateContractError,yi as WORKFLOW_APPROVAL_EMPTY_PROVIDERS,ju as WORKFLOW_APPROVED_DELEGATION_MAX_BYTES,xu as WORKFLOW_APPROVED_DELEGATION_MAX_REQUESTS,gi as WORKFLOW_AUTOMATIC_CC_DEFAULT_RECIPIENTS,Ai as WORKFLOW_AUTOMATIC_CC_MAX_RECIPIENTS,Ka as WORKFLOW_AUTOMATIC_CC_PROVIDERS,Ct as WORKFLOW_BUSINESS_STEP_EVENT,ii as WORKFLOW_BUSINESS_STEP_EVENTS,su as WORKFLOW_BUSINESS_STEP_FACTS_KEY,go as WORKFLOW_BUSINESS_STEP_MAX_BYTES,ja as WORKFLOW_BUSINESS_STEP_MAX_RECEIPT_BYTES,bo as WORKFLOW_CONFIGURABLE_OPERATIONS,Oo as WORKFLOW_CONFIGURABLE_PROVIDERS,jo as WORKFLOW_EVENT_TYPES_V2,Pn as WORKFLOW_LAUNCH_MAX_INPUTS,Ha as WORKFLOW_LAUNCH_PREFLIGHT_PROVIDERS,Du as WORKFLOW_REJECTION_NOTIFICATION_MAX_BYTES,Ja as WORKFLOW_REJECTION_NOTIFICATION_SCHEMA,gu as WORKFLOW_ROLE_UNION_MAX_ROLES,ef as WORKFLOW_ROUTING_MAX_BYTES,Qu as WORKFLOW_ROUTING_MAX_MATCHED_RULES,Zu as WORKFLOW_ROUTING_MAX_RULES,fp as WORKFLOW_STEP_DATA_COMMAND_SCHEMA,Oc as WORKFLOW_STEP_DATA_RESOLUTION_SCHEMA,ed as WORKFLOW_TASK_PAGE_DEFINITION_MAX_BYTES,So as WORKFLOW_TASK_PAGE_MAX_BYTES,Qa as WORKFLOW_TASK_PAGE_MAX_FIELDS,vi as WORKFLOW_TASK_SUBTABLE_MAX_ROWS,$i as WORKFLOW_TASK_SUBTABLE_MAX_TOTAL_ROWS,we as WorkflowTaskPageError,td as applyWorkflowTaskPageValues,Ju as applyWorkflowTaskSubtableRows,Dc as assertDevelopmentConfigurationManifest,Kp as assertDevelopmentConfigurationResult,Ap as assertNativeRoleMembershipBatchInput,Bl as assertWorkflowNativeStageGuard,Gr as assertWorkflowNativeStagePolicy,Kl as assertWorkflowNativeStageSourceGuard,pn as assertWorkflowOwnedSubjectCreate,Bi as assertWorkflowOwnedSubjectCreateResources,wp as canonicalDataBusinessIntent,ap as compileNativeApplicationConfiguration,ei as compileNativeEventAction,Dd as compileNativeEventCapturePlansV2,Sd as compileRequiredPlatformCapabilitiesV3,Eo as compileWorkflowBusinessStepHandlers,Up as createDevelopmentConfigurationManifest,jt as dataOwnedRowLimit,Ku as dateEventProjectionEnvelopeSchemaV2,ki as dateEventProjectionFieldsV2,$c as developmentBackendBase64Bytes,Lc as developmentBackendInvocationHeadersValid,rm as developmentBackendInvocationRequestValid,om as developmentBackendInvocationRevision,Pc as developmentBackendOperationMatches,Bp as developmentConfigurationKey,Fe as evaluateWorkflowTaskPageExpression,wu as formatWorkflowCompletionDeadline,rn as formatWorkflowExpression,zi as generatedCrudCapabilityOperations,mr as hasDataAuditReadPolicy,lo as hasNativeParentReadPolicy,_t as isDataAuditMetadataField,mt as isDataOwnedRowLimit,_r as isDataSystemSortField,kp as isDataTransactionActorAuthorityGuard,Vp as isDataTransactionRecordSetMatchGuard,Zc as isNativeDataQueryOperatorV2,Ut as isNativeMultiValueFieldV2,ku as isWorkflowRejectionNotificationSnapshot,$p as matchesDataActorAuthorityMembership,kl as materializeNativeDataQueryPathTypesV2,st as nativeDataPolicyExpressionLeavesV2,Lr as nativeDataPolicyExpressionToCnfV2,$l as nativeDataQueryPathPlanV2,el as nativeFieldAggregatePlanV2,yl as nativeFieldColumnDefinitionV2,bl as nativeFieldDefaultSqlV2,Ol as nativeFieldHasDefaultV2,Cl as nativeFieldIndexStatementsV2,Bt as nativeFieldRequiresCreateInputV2,Rl as nativeFieldSequenceGrantStatementsV2,Tl as nativeFieldSequenceOwnershipStatementsV2,Nl as nativeFieldSequenceStatementsV2,Ir as nativeFieldSupportsFilterV2,Qc as nativeFieldSupportsOperatorV2,qn as nativeFieldSupportsSearchV2,At as nativeFieldSupportsSortV2,Er as nativeOperatorsForFieldV2,ya as nativePhysicalFieldV2,Il as nativePhysicalFieldsV2,ve as nativePhysicalObjectNameV2,Sl as nativeScopeSourceFieldValueV2,vr as nativeScopeSourceGrantPathSupportedV2,so as nativeScopeSourceSubjectPathSupportedV2,hl as nativeSubtableConstraintStatementsV2,Yr as nativeUniqueKeysContractVersion,Xl as nativeUniqueKeysJsonSchema,ao as normalizeDataMutationGrants,cf as normalizeWorkflowOwnedSubjectCreate,Sp as parseDataBusinessCommandResolution,xt as parseDataFieldUserCandidates,oo as parseDecimalReservationLifecycle,Bn as parseNativeDataFieldsV2,pr as parseNativeDataResourceInvariantsV2,xa as parseNativeParentReadPolicy,Hr as parseNativeUniqueKeys,pp as parseWorkflowStepDataResolution,wc as projectDataResourceView,Qn as projectNativeDataResourceViewV2,fu as projectWorkflowGraph,Ei as projectWorkflowNodePolicy,le as quoteNativeIdentifierV2,Hu as refreshWorkflowTaskPageFacts,Vn as requiresAggregateOwnedSubtableCapacity,Wn as requiresDateTimeMinutePrecision,nm as requiresDevelopmentBackendCredential,mn as requiresExtendedArtifactCapacity,Vo as requiresExtendedConfigurationBytes,vo as requiresExtendedDeclarationCapacity,vn as requiresExtendedFieldCapacity,Ln as requiresExtendedOwnedSubtableCapacity,Po as requiresExtendedRoleCapacity,_n as requiresHighDensityArtifactCapacity,Mn as requiresOwnedSubtableMinimumRows,kn as requiresUserCandidateLaunchScope,_i as requiresWorkflowRoleInputSelection,pi as requiresWorkflowRoleUnion,Xt as resolveNativeParentReadBinding,It as resolveNativeScopeSourceFieldPathV2,Vu as resolveWorkflowCommandHandler,js as resolveWorkflowUserCandidates,rf as selectWorkflowAssignmentRoutingRules,Gc as serializedDataBytes,Mc as userCandidateScopeValue,qr as validateAuthenticatedPublicRead,wr as validateDecimalReservationLifecycles,Cr as validateManagedConcurrency,Or as validateNativeDataDraftStateV2,fr as validateNativeDataResourceReferencesV2,Zn as validateNativeDataResourceSurfaceV2,Wr as validateNativeParentReadPolicies,or as validateUserCandidateReferences,No as validateWorkflowAdministration,To as validateWorkflowApprovalEmptyPolicy,Si as validateWorkflowApprovedDelegation,Mi as validateWorkflowAssignmentRoutingBindings,fn as validateWorkflowAssignmentRoutingPolicy,nf as validateWorkflowAssignmentRoutingRules,yo as validateWorkflowAutomaticCc,du as validateWorkflowBusinessStepHandlerContract,au as validateWorkflowBusinessStepRequest,Wa as validateWorkflowBusinessStepResult,tn as validateWorkflowBusinessStepSchema,ci as validateWorkflowBusinessStepSubscriptions,on as validateWorkflowBusinessSteps,Ci as validateWorkflowCommandHandlers,Ni as validateWorkflowCompletionDeadlines,Di as validateWorkflowCorrections,ht as validateWorkflowInitiatorApprovalPolicy,ni as validateWorkflowInstanceCommandPolicies,Co as validateWorkflowLaunchPreflight,Tu as validateWorkflowNodeConfigurationPatch,ui as validateWorkflowReadability,Ri as validateWorkflowRejectionNotification,mi as validateWorkflowRoleInputSelection,an as validateWorkflowRoleUnion,un as validateWorkflowTaskPages,rr as validateWorkflowUserCandidateBindings,Cu as workflowApprovalCanSkip,Wu as workflowApprovedDelegationRequests,of as workflowAssignmentRoutingFacts,tf as workflowAssignmentRoutingPolicySchema,id as workflowAssignmentRoutingSemantic,bi as workflowBindingAllowsEmptyUsers,Eu as workflowBindingRoleCodes,vu as workflowBusinessCommandInvocationSchema,nn as workflowBusinessStepFactSchema,Tp as workflowBusinessStepHandlerDigest,cu as workflowBusinessStepInput,Ma as workflowBusinessStepPath,Np as workflowBusinessStepReceiptSignatureSuffix,en as workflowBusinessStepValueMatches,Tc as workflowDelegationMutationRequestSchema,li as workflowExpressionPaths,mu as workflowInitiatorApprovalCanComplete,ru as workflowInstanceCommandDeadlineError,nu as workflowInstanceTerminateCapabilityAllowed,ou as workflowInstanceWithdrawalReasonRequired,Gl as workflowNativeStagePolicySchema,wt as workflowNodeAllowedOperations,za as workflowOperationCommentRequired,qa as workflowOperationReasonRequired,df as workflowOwnedSubjectCreateSchema,ti as workflowPolicyTimestamp,Au as workflowRoleCodesSchema,Fi as workflowTaskPageFieldState,Yu as workflowTaskPageReplayCoversInvalidation,qu as workflowTaskSubtableRows,Ba as workflowVariableLabel};