openxiangda-contracts 2.26.0 → 2.28.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser.d.ts +2 -0
- package/dist/browser.d.ts.map +1 -1
- package/dist/browser.js +2 -0
- package/dist/browser.js.map +1 -1
- package/dist/concurrency.d.ts +145 -0
- package/dist/concurrency.d.ts.map +1 -0
- package/dist/concurrency.js +2 -0
- package/dist/concurrency.js.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/native-compiler/compiler.d.ts.map +1 -1
- package/dist/native-compiler/compiler.js +25 -2
- package/dist/native-compiler/compiler.js.map +1 -1
- package/dist/native-compiler/data-surface.js +1 -1
- package/dist/native-compiler/data-surface.js.map +1 -1
- package/dist/native-compiler/index.cjs +5 -5
- package/dist/native-compiler/index.d.ts +2 -0
- package/dist/native-compiler/index.d.ts.map +1 -1
- package/dist/native-compiler/index.js +5 -5
- package/dist/native-compiler/managed-concurrency.d.ts +10 -0
- package/dist/native-compiler/managed-concurrency.d.ts.map +1 -0
- package/dist/native-compiler/managed-concurrency.js +238 -0
- package/dist/native-compiler/managed-concurrency.js.map +1 -0
- package/dist/native-compiler/unique-keys.d.ts +102 -0
- package/dist/native-compiler/unique-keys.d.ts.map +1 -0
- package/dist/native-compiler/unique-keys.js +112 -0
- package/dist/native-compiler/unique-keys.js.map +1 -0
- package/dist/native-version.d.ts +2 -0
- package/dist/native-version.d.ts.map +1 -1
- package/dist/native-version.js +2 -0
- package/dist/native-version.js.map +1 -1
- package/dist/native.d.ts +2 -0
- package/dist/native.d.ts.map +1 -1
- package/dist/native.js.map +1 -1
- package/dist/schemas.d.ts +178 -2
- package/dist/schemas.d.ts.map +1 -1
- package/dist/schemas.js +5 -1
- package/dist/schemas.js.map +1 -1
- package/dist/surface.d.ts +1 -1
- package/dist/surface.d.ts.map +1 -1
- package/dist/types.d.ts +18 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/validation.d.ts.map +1 -1
- package/dist/validation.js +9 -0
- package/dist/validation.js.map +1 -1
- package/package.json +1 -1
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{createHash as co}from"node:crypto";function lo(e){if(!e||typeof e!="object")return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function at(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,s)=>at(n,`${t}[${s}]`)).join(",")}]`;if(lo(e))return`{${Object.keys(e).filter(s=>e[s]!==void 0).sort((s,r)=>s===r?0:s<r?-1:1).map(s=>`${JSON.stringify(s)}:${at(e[s],`${t}.${s}`)}`).join(",")}}`;let o=e instanceof Date?"Date":e?.constructor?.name||typeof e;throw new TypeError(`Value is not JSON serializable: ${t} (${o})`)}function Q(e){return at(e,"$")}function ee(e){return co("sha256").update(Q(e)).digest("hex")}var Yt=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,lt=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,uo=["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"],fo=new Set(uo),qt=new Set(["option.multiple","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","file","image","subtable"]),Wt=new Set(["option.single","option.multiple","cascade.single","cascade.multiple"]),Gt=new Set(["resource-ref.single","resource-ref.multiple"]),ut=[{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}],hi=new Map(ut.map(e=>[e.code,e])),_e=class extends Error{constructor(o,n){super(o);this.code=o;this.pointer=n;this.name="NativeDataFieldContractV2Error"}code;pointer};function Ge(e){return qt.has(e)}function ze(e,t={}){return e.type!=="serial-number"&&t.system!==!0&&e.nullable===!1&&(!Ge(e.type)||t.requiredHint===!0)}function ft(e,t,o=500){Array.isArray(e)||S("NATIVE_ARRAY_REQUIRED",t),e.length===0&&S("NATIVE_DATA_FIELDS_REQUIRED",t),e.length>o&&S("NATIVE_ARRAY_LIMIT_EXCEEDED",t);let n=new Set;return e.map((s,r)=>{let a=`${t}/${r}`,i=ie(s,a);ae(i,["code","type","nullable","indexed","options","source","maxLength","precision","scale","exactDecimal","min","max","rangeBoundary","timePrecision","file","serial","subtable"],a);let c=ce(i.code,`${a}/code`,63);Yt.test(c)||S("NATIVE_FIELD_CODE_INVALID",`${a}/code`),n.has(c)&&S("NATIVE_DATA_FIELD_DUPLICATE",`${a}/code`),n.add(c);let _=ce(i.type,`${a}/type`,32);fo.has(_)||S("NATIVE_DATA_FIELD_TYPE_INVALID",`${a}/type`);let p=_,d=dt(i.nullable,`${a}/nullable`),u=dt(i.indexed,`${a}/indexed`);d===!0&&qt.has(p)&&S("NATIVE_DATA_MULTI_FIELD_NULLABLE_INVALID",`${a}/nullable`);let E=Eo(i.options,p,a),l=Ao(i.source,p,a),A=mo(i,p,a),T=dt(i.exactDecimal,`${a}/exactDecimal`);T!==void 0&&p!=="number.decimal"&&S("NATIVE_DATA_FIELD_EXACT_DECIMAL_TYPE_INVALID",`${a}/exactDecimal`);let m=_o(i.rangeBoundary,p,a),N=To(i.file,p,a),b=No(i.serial,p,a),R=go(i.subtable,p,a);return{code:c,type:p,...d===void 0?{}:{nullable:d},...u===void 0?{}:{indexed:u},...E?{options:E}:{},...l?{source:l}:{},...A,...T===void 0?{}:{exactDecimal:T},...m?{rangeBoundary:m}:{},...N?{file:N}:{},...b?{serial:b}:{},...R?{subtable:R}:{}}})}function _o(e,t,o){let n=`${o}/rangeBoundary`;if(!(t==="date-range"||t==="datetime-range")){e!==void 0&&S("NATIVE_DATA_FIELD_RANGE_BOUNDARY_TYPE_INVALID",n);return}return e!=="closed"&&e!=="half-open"&&S("NATIVE_DATA_FIELD_RANGE_BOUNDARY_REQUIRED",n),e}function Kt(e,t){Array.isArray(e)||S("NATIVE_ARRAY_REQUIRED",t);let o=new Map;e.forEach((n,s)=>{let r=`${t}/${s}`,a=ie(n,r),i=ce(a.code,`${r}/code`,64);(!lt.test(i)||o.has(i))&&S("NATIVE_RESOURCE_CODE_INVALID",`${r}/code`);let c=ie(a.schema,`${r}/schema`);o.set(i,{pointer:r,fields:ft(c.fields,`${r}/schema/fields`)})});for(let[n,s]of o){let r=new Map(s.fields.map(i=>[i.code,i]));s.fields.filter(i=>i.type==="subtable").reduce((i,c)=>i+(c.subtable?.maxRows??20),0)>49&&S("NATIVE_DATA_FIELD_SUBTABLE_AGGREGATE_MAX_ROWS_EXCEEDED",`${s.pointer}/schema/fields`),s.fields.forEach((i,c)=>{let _=`${s.pointer}/schema/fields/${c}`;if(i.source&&po(i.source,r,o,`${_}/source`),i.subtable){let p=o.get(i.subtable.resourceCode);(!p||i.subtable.resourceCode===n)&&S("NATIVE_DATA_FIELD_SUBTABLE_TARGET_MISSING",`${_}/subtable/resourceCode`);let d=p.fields.find(E=>E.code===i.subtable?.foreignKey);(!d||d.type!=="uuid"||d.nullable!==!1)&&S("NATIVE_DATA_FIELD_SUBTABLE_FOREIGN_KEY_INVALID",`${_}/subtable/foreignKey`);let u=p.fields.find(E=>E.code===i.subtable?.orderField);(!u||u.type!=="number.integer"||u.nullable!==!1)&&S("NATIVE_DATA_FIELD_SUBTABLE_ORDER_FIELD_INVALID",`${_}/subtable/orderField`)}})}}function Ht(e,t,o){if(e===void 0)return[];(!Array.isArray(e)||e.length>20)&&S("NATIVE_DATA_RESOURCE_INVARIANTS_INVALID",o);let n=new Map(t.map(r=>[r.code,r])),s=new Set;return e.map((r,a)=>{let i=`${o}/${a}`,c=ie(r,i);ae(c,["code","message","expression"],i);let _=ce(c.code,`${i}/code`,128);(!/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/.test(_)||s.has(_))&&S("NATIVE_DATA_RESOURCE_INVARIANT_CODE_INVALID",`${i}/code`),s.add(_);let p=We(c.message,`${i}/message`,500);p!==void 0&&p.length===0&&S("NATIVE_DATA_RESOURCE_INVARIANT_MESSAGE_INVALID",`${i}/message`);let d=ie(c.expression,`${i}/expression`);if(d.kind==="nonBlankTextWhenOption"){ae(d,["kind","optionField","optionValue","textField"],`${i}/expression`);let N=fe(d.optionField,`${i}/expression/optionField`),b=fe(d.textField,`${i}/expression/textField`),R=ce(d.optionValue,`${i}/expression/optionValue`,128),g=n.get(N),C=n.get(b);return(!g||!C)&&S("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_UNKNOWN",`${i}/expression`),(g.type!=="option.single"||!["text.short","text.long"].includes(C.type)||!g.options?.some(D=>D.value===R))&&S("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_TYPES_INVALID",`${i}/expression`),{code:_,...p===void 0?{}:{message:p},expression:{kind:"nonBlankTextWhenOption",optionField:N,optionValue:R,textField:b}}}ae(d,["leftField","operator","rightField"],`${i}/expression`);let u=fe(d.leftField,`${i}/expression/leftField`),E=fe(d.rightField,`${i}/expression/rightField`),l=n.get(u),A=n.get(E);(!l||!A)&&S("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_UNKNOWN",`${i}/expression`),l.type===A.type||["number.integer","number.decimal"].includes(l.type)&&["number.integer","number.decimal"].includes(A.type)||S("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_TYPES_INVALID",`${i}/expression`);let m=String(d.operator);return["eq","neq","gt","gte","lt","lte"].includes(m)||S("NATIVE_DATA_RESOURCE_INVARIANT_OPERATOR_INVALID",`${i}/expression/operator`),!["eq","neq"].includes(m)&&!["number.integer","number.decimal","date","time","datetime","text.short","text.long","text.rich","serial-number","uuid"].includes(l.type)&&S("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_TYPES_INVALID",`${i}/expression`),{code:_,...p===void 0?{}:{message:p},expression:{leftField:u,operator:m,rightField:E}}})}function po(e,t,o,n){let s=o.get(e.resourceCode);s||S("NATIVE_DATA_FIELD_SOURCE_TARGET_MISSING",`${n}/resourceCode`);let r=new Map(s.fields.map(i=>[i.code,i])),a=r.get(e.labelField);(!a||!["text.short","text.long"].includes(a.type))&&S("NATIVE_DATA_FIELD_SOURCE_LABEL_INVALID",`${n}/labelField`);for(let i of["searchFields","descriptionFields","snapshotFields"])for(let c of e[i]||[])r.has(c)||S("NATIVE_DATA_FIELD_SOURCE_FIELD_MISSING",`${n}/${i}`);for(let[i,c]of(e.filters||[]).entries())r.has(c.field)||S("NATIVE_DATA_FIELD_SOURCE_FILTER_FIELD_MISSING",`${n}/filters/${i}/field`),"binding"in c&&!t.has(c.binding.field)&&S("NATIVE_DATA_FIELD_SOURCE_BINDING_FIELD_MISSING",`${n}/filters/${i}/binding/field`)}function Eo(e,t,o){let n=`${o}/options`;if(e===void 0){Wt.has(t)&&S("NATIVE_DATA_FIELD_OPTIONS_REQUIRED",n);return}(!Wt.has(t)||!Array.isArray(e))&&S("NATIVE_DATA_FIELD_OPTIONS_TYPE_INVALID",n),(e.length<1||e.length>100)&&S("NATIVE_DATA_FIELD_OPTIONS_INVALID",n);let s=0,r=(a,i,c)=>{c>5&&S("NATIVE_DATA_FIELD_OPTIONS_DEPTH_EXCEEDED",i);let _=new Set;return a.map((p,d)=>{s+=1,s>1e3&&S("NATIVE_DATA_FIELD_OPTIONS_COUNT_EXCEEDED",n);let u=`${i}/${d}`,E=ie(p,u);ae(E,["label","value","description","color","children"],u);let l=ce(E.label,`${u}/label`,500),A=ce(E.value,`${u}/value`,500);_.has(A)&&S("NATIVE_DATA_FIELD_OPTION_VALUE_DUPLICATE",`${u}/value`),_.add(A);let T=We(E.description,`${u}/description`,2e3),m=We(E.color,`${u}/color`,64),N;return E.children!==void 0&&((!t.startsWith("cascade.")||!Array.isArray(E.children))&&S("NATIVE_DATA_FIELD_OPTION_CHILDREN_INVALID",`${u}/children`),(E.children.length<1||E.children.length>100)&&S("NATIVE_DATA_FIELD_OPTION_CHILDREN_INVALID",`${u}/children`),N=r(E.children,`${u}/children`,c+1)),{label:l,value:A,...T===void 0?{}:{description:T},...m===void 0?{}:{color:m},...N?{children:N}:{}}})};return r(e,n,1)}function Ao(e,t,o){let n=`${o}/source`;if(e===void 0){Gt.has(t)&&S("NATIVE_DATA_FIELD_SOURCE_REQUIRED",n);return}Gt.has(t)||S("NATIVE_DATA_FIELD_SOURCE_TYPE_INVALID",n);let s=ie(e,n);ae(s,["kind","resourceCode","labelField","searchFields","descriptionFields","snapshotFields","filters","pageSize","loadMode"],n),s.kind!=="resource"&&S("NATIVE_DATA_FIELD_SOURCE_KIND_INVALID",`${n}/kind`);let r=ce(s.resourceCode,`${n}/resourceCode`,64);lt.test(r)||S("NATIVE_RESOURCE_CODE_INVALID",`${n}/resourceCode`);let a=fe(s.labelField,`${n}/labelField`),i=ct(s.searchFields,`${n}/searchFields`,10),c=ct(s.descriptionFields,`${n}/descriptionFields`,10),_=ct(s.snapshotFields,`${n}/snapshotFields`,50),p=$e(s.pageSize,`${n}/pageSize`,1,100),d;s.loadMode!==void 0&&(["search","all"].includes(String(s.loadMode))||S("NATIVE_DATA_FIELD_SOURCE_LOAD_MODE_INVALID",`${n}/loadMode`),d=s.loadMode);let u=Io(s.filters,`${n}/filters`);return{kind:"resource",resourceCode:r,labelField:a,...i?{searchFields:i}:{},...c?{descriptionFields:c}:{},..._?{snapshotFields:_}:{},...u?{filters:u}:{},...p===void 0?{}:{pageSize:p},...d?{loadMode:d}:{}}}function Io(e,t){if(e!==void 0)return(!Array.isArray(e)||e.length>20)&&S("NATIVE_DATA_FIELD_SOURCE_FILTERS_INVALID",t),e.map((o,n)=>{let s=`${t}/${n}`,r=ie(o,s),a=Object.prototype.hasOwnProperty.call(r,"value"),i=Object.prototype.hasOwnProperty.call(r,"binding");ae(r,a?["field","operator","value"]:["field","operator","binding"],s),a===i&&S("NATIVE_DATA_FIELD_SOURCE_FILTER_VALUE_INVALID",s);let c=fe(r.field,`${s}/field`);["eq","in"].includes(String(r.operator))||S("NATIVE_DATA_FIELD_SOURCE_FILTER_OPERATOR_INVALID",`${s}/operator`);let _=r.operator;if(a)return{field:c,operator:_,value:r.value};let p=ie(r.binding,`${s}/binding`);return ae(p,["kind","field"],`${s}/binding`),p.kind!=="field"&&S("NATIVE_DATA_FIELD_SOURCE_BINDING_KIND_INVALID",`${s}/binding/kind`),{field:c,operator:_,binding:{kind:"field",field:fe(p.field,`${s}/binding/field`)}}})}function mo(e,t,o){let n={};if(e.maxLength!==void 0&&(["text.short","text.long","text.rich"].includes(t)||S("NATIVE_DATA_FIELD_MAX_LENGTH_TYPE_INVALID",`${o}/maxLength`),n.maxLength=Je(e.maxLength,`${o}/maxLength`,1,1e6)),(e.precision!==void 0||e.scale!==void 0)&&((t!=="number.decimal"||e.precision===void 0)&&S("NATIVE_DATA_FIELD_DECIMAL_CONFIG_INVALID",o),n.precision=Je(e.precision,`${o}/precision`,1,1e3),n.scale=e.scale===void 0?0:Je(e.scale,`${o}/scale`,0,n.precision)),e.min!==void 0||e.max!==void 0){["number.integer","number.decimal"].includes(t)||S("NATIVE_DATA_FIELD_NUMERIC_BOUNDS_TYPE_INVALID",o);let s=zt(e.min,`${o}/min`),r=zt(e.max,`${o}/max`);t==="number.integer"&&[s,r].some(a=>a!==void 0&&!Number.isSafeInteger(a))&&S("NATIVE_DATA_FIELD_NUMERIC_BOUNDS_INVALID",o),s!==void 0&&r!==void 0&&s>r&&S("NATIVE_DATA_FIELD_NUMERIC_BOUNDS_INVALID",o),s!==void 0&&(n.min=s),r!==void 0&&(n.max=r)}return e.timePrecision!==void 0&&((t!=="time"||!["minute","second"].includes(e.timePrecision))&&S("NATIVE_DATA_FIELD_TIME_PRECISION_INVALID",`${o}/timePrecision`),n.timePrecision=e.timePrecision),n}function To(e,t,o){if(e===void 0)return;let n=`${o}/file`;["file","image","signature"].includes(t)||S("NATIVE_DATA_FIELD_FILE_TYPE_INVALID",n);let s=ie(e,n);ae(s,["maxCount","maxSizeMb","accept"],n);let r=$e(s.maxCount,`${n}/maxCount`,1,100);t==="signature"&&r!==void 0&&r!==1&&S("NATIVE_DATA_FIELD_SIGNATURE_COUNT_INVALID",`${n}/maxCount`);let a=$e(s.maxSizeMb,`${n}/maxSizeMb`,1,1024),i;return s.accept!==void 0&&((!Array.isArray(s.accept)||s.accept.length>50)&&S("NATIVE_DATA_FIELD_FILE_ACCEPT_INVALID",`${n}/accept`),i=s.accept.map((c,_)=>ce(c,`${n}/accept/${_}`,255)),new Set(i).size!==i.length&&S("NATIVE_DATA_FIELD_FILE_ACCEPT_INVALID",`${n}/accept`)),{...r===void 0?{}:{maxCount:r},...a===void 0?{}:{maxSizeMb:a},...i===void 0?{}:{accept:i}}}function No(e,t,o){let n=`${o}/serial`;if(e===void 0){t==="serial-number"&&S("NATIVE_DATA_FIELD_SERIAL_REQUIRED",n);return}t!=="serial-number"&&S("NATIVE_DATA_FIELD_SERIAL_TYPE_INVALID",n);let s=ie(e,n);ae(s,["prefix","digits","start"],n);let r=We(s.prefix,`${n}/prefix`,64),a=$e(s.digits,`${n}/digits`,1,32),i=$e(s.start,`${n}/start`,0,Number.MAX_SAFE_INTEGER);return{...r===void 0?{}:{prefix:r},...a===void 0?{}:{digits:a},...i===void 0?{}:{start:i}}}function go(e,t,o){let n=`${o}/subtable`;if(e===void 0){t==="subtable"&&S("NATIVE_DATA_FIELD_SUBTABLE_REQUIRED",n);return}t!=="subtable"&&S("NATIVE_DATA_FIELD_SUBTABLE_TYPE_INVALID",n);let s=ie(e,n);ae(s,["resourceCode","foreignKey","orderField","maxRows"],n);let r=ce(s.resourceCode,`${n}/resourceCode`,64);lt.test(r)||S("NATIVE_RESOURCE_CODE_INVALID",`${n}/resourceCode`);let a=fe(s.foreignKey,`${n}/foreignKey`),i=fe(s.orderField,`${n}/orderField`);i===a&&S("NATIVE_DATA_FIELD_SUBTABLE_ORDER_FIELD_INVALID",`${n}/orderField`);let c=$e(s.maxRows,`${n}/maxRows`,1,49);return{resourceCode:r,foreignKey:a,orderField:i,...c===void 0?{}:{maxRows:c}}}function ct(e,t,o){if(e===void 0)return;(!Array.isArray(e)||e.length>o)&&S("NATIVE_DATA_FIELD_SOURCE_FIELDS_INVALID",t);let n=e.map((s,r)=>fe(s,`${t}/${r}`));return new Set(n).size!==n.length&&S("NATIVE_DATA_FIELD_SOURCE_FIELDS_INVALID",t),n}function fe(e,t){let o=ce(e,t,63);return Yt.test(o)||S("NATIVE_FIELD_CODE_INVALID",t),o}function ie(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&S("NATIVE_OBJECT_REQUIRED",t),e}function ae(e,t,o){let n=new Set(t);for(let s of Object.keys(e))n.has(s)||S("NATIVE_PROPERTY_UNKNOWN",`${o}/${s}`)}function ce(e,t,o){return(typeof e!="string"||e.length===0||e.length>o)&&S("NATIVE_STRING_INVALID",t),e}function We(e,t,o){if(e!==void 0)return(typeof e!="string"||e.length>o)&&S("NATIVE_STRING_INVALID",t),e}function dt(e,t){if(e!==void 0)return typeof e!="boolean"&&S("NATIVE_BOOLEAN_REQUIRED",t),e}function $e(e,t,o,n){if(e!==void 0)return Je(e,t,o,n)}function zt(e,t){if(e!==void 0)return(typeof e!="number"||!Number.isFinite(e))&&S("NATIVE_NUMBER_REQUIRED",t),e}function Je(e,t,o,n){return(!Number.isSafeInteger(e)||Number(e)<o||Number(e)>n)&&S("NATIVE_INTEGER_OUT_OF_RANGE",t),Number(e)}function S(e,t){throw new _e(e,t)}var Xt=["created_by","updated_by","created_at","updated_at"];function Fe(e){return Xt.includes(e)}function Qt(e){return Xt.some(t=>Object.prototype.hasOwnProperty.call(e.fieldPolicies||{},t))}var Co=ut.map(e=>e.code);function Zt(e){return Co.includes(e)}var bo=["eq","neq","gt","gte","lt","lte","contains","startsWith","endsWith","in","between","has","hasAny","hasAll","overlaps","containedBy","jsonContains","isEmpty","isNotEmpty"],Oo=new Set(bo);function Vi(e){return Oo.has(String(e))}var _t=["eq","neq","contains","startsWith","endsWith","in","isEmpty","isNotEmpty"],Pe=["eq","neq","gt","gte","lt","lte","between","in","isEmpty"],Ro=["eq","neq","in","isEmpty"],Ye=["eq","neq","in","isEmpty","isNotEmpty"],he=["has","hasAny","hasAll","isEmpty","isNotEmpty"],en=["overlaps","contains","containedBy","isEmpty"],pt=["jsonContains","isEmpty","isNotEmpty"],Et=["isEmpty","isNotEmpty"],$o={"text.short":_t,"text.long":_t,"text.rich":_t,"number.integer":Pe,"number.decimal":Pe,boolean:Ro,date:Pe,time:Pe,datetime:Pe,"date-range":en,"datetime-range":en,"option.single":Ye,"option.multiple":he,"cascade.single":he,"cascade.multiple":he,"user.single":Ye,"user.multiple":he,"department.single":Ye,"department.multiple":he,"resource-ref.single":Ye,"resource-ref.multiple":he,file:Et,image:Et,signature:Et,address:pt,location:pt,uuid:["eq","neq","in","isEmpty"],json:pt,"serial-number":["eq","neq","in","contains","startsWith"],subtable:[]},ho=new Set(["text.short","text.long","text.rich","option.single","user.single","department.single","resource-ref.single","serial-number"]),So=new Set(["option.multiple","cascade.single","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","file","image","signature","address","location","json","subtable"]);function nn(e){return $o[e]}function wi(e,t){return nn(e).includes(t)}function At(e){return ho.has(e)}function ve(e){return!So.has(e)}function on(e){return nn(e).length>0}var tn=new Set(["number.integer","number.decimal"]),sn=new Set(["text.short","text.long","number.integer","number.decimal","date","time","datetime","serial-number"]),Do=new Set([...sn,"boolean","uuid"]),yo=new Set(["option.single","user.single","department.single","resource-ref.single"]);function Fi(e,t){return t==="sum"||t==="avg"?tn.has(e)?{valueExpression:"column",numericResult:!0}:null:t==="min"||t==="max"?sn.has(e)?{valueExpression:"column",numericResult:tn.has(e)}:null:yo.has(e)?{valueExpression:"snapshot-value",numericResult:!0}:Do.has(e)?{valueExpression:"column",numericResult:!0}:null}var mt=["version","maxBytes","fields"];function an(e,t){if(e===void 0)return;let o=It(e,t);rn(o,mt,t);let n=qe(o.version,`${t}/version`,1,1e6),s=qe(o.maxBytes,`${t}/maxBytes`,2,196608);(!n||!s)&&ne("NATIVE_DATA_DRAFT_STATE_SCHEMA_INVALID",t);let r=It(o.fields,`${t}/fields`),a=Object.entries(r);(!a.length||a.length>50)&&ne("NATIVE_DATA_DRAFT_STATE_FIELDS_INVALID",`${t}/fields`);for(let[i,c]of a){let _=`${t}/fields/${i}`;/^[A-Za-z][A-Za-z0-9_]{0,62}$/.test(i)||ne("NATIVE_DATA_DRAFT_STATE_FIELD_CODE_INVALID",_);let p=It(c,_),d=cn(p.type,`${_}/type`,32),u=d==="string"?["type","required","maxLength","enum"]:d==="json.object"?["type","required","maxBytes"]:["type","required"];if(["string","number","integer","boolean","json.object"].includes(d)||ne("NATIVE_DATA_DRAFT_STATE_FIELD_TYPE_INVALID",`${_}/type`),rn(p,u,_),wo(p.required,`${_}/required`),d==="string"){let E=qe(p.maxLength,`${_}/maxLength`,1,196608);E||ne("NATIVE_DATA_DRAFT_STATE_FIELD_INVALID",_),p.enum!==void 0&&Vo(p.enum,`${_}/enum`,100,!1).some(A=>A.length>E)&&ne("NATIVE_DATA_DRAFT_STATE_FIELD_INVALID",`${_}/enum`)}else if(d==="json.object"){let E=qe(p.maxBytes,`${_}/maxBytes`,2,65536);(!E||E>s)&&ne("NATIVE_DATA_DRAFT_STATE_FIELD_INVALID",_)}}}function Vo(e,t,o,n){(!Array.isArray(e)||!n&&e.length===0||e.length>o)&&ne("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t);let s=e.map((r,a)=>cn(r,`${t}/${a}`,255));return new Set(s).size!==s.length&&ne("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t),s}function It(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&ne("NATIVE_OBJECT_REQUIRED",t),e}function rn(e,t,o){let n=new Set(t);for(let s of Object.keys(e))n.has(s)||ne("NATIVE_PROPERTY_UNKNOWN",`${o}/${s}`)}function cn(e,t,o){return(typeof e!="string"||e.length===0||e.length>o)&&ne("NATIVE_STRING_INVALID",t),e}function wo(e,t){e!==void 0&&typeof e!="boolean"&&ne("NATIVE_BOOLEAN_REQUIRED",t)}function qe(e,t,o,n){return(!Number.isSafeInteger(e)||Number(e)<o||Number(e)>n)&&ne("NATIVE_INTEGER_INVALID",t),Number(e)}function ne(e,t){throw new _e(e,t)}var Fo=500,Ne={surface:["mutationOwner","generated","fields","list","form","detail","mobile","views"],generated:["list","detail","create","update","delete"],field:["label","type","widget","section","requiredHint","system","hidden","readCapabilities","createCapabilities","updateCapabilities","maxLength","precision","scale","exactDecimal","min","max","rangeBoundary","maxCount","maxSizeMb","accept","options","list","searchable","sortable","source","timePrecision","serial","subtable"],list:["actions","fieldOrder","defaultPageSize","searchableFields","filterFields","defaultSort"],defaultSort:["field","order"],form:["layout","fieldOrder","draftState"],detail:["layout","fieldOrder"],layout:["layout","fieldOrder","draftState"],draftState:mt,mobile:["enabled"]},Po={"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 gt(e,t,o){if(e===void 0)return;let n=te(e,o);pe(n,Ne.surface,o);let s=n.mutationOwner===void 0?"native":me(n.mutationOwner,`${o}/mutationOwner`,16);["native","action","readonly","workflow"].includes(s)||v("NATIVE_DATA_SURFACE_MUTATION_OWNER_INVALID",`${o}/mutationOwner`);let r=n.generated===void 0?{}:te(n.generated,`${o}/generated`);pe(r,Ne.generated,`${o}/generated`);for(let c of Ne.generated)Nt(r[c],`${o}/generated/${c}`);if(s!=="native")for(let c of["create","update","delete"])r[c]===!0&&v("NATIVE_DATA_SURFACE_MUTATION_OWNER_CONFLICT",`${o}/generated/${c}`);let a=new Map(t.map(c=>[c.code,c])),i=te(n.fields,`${o}/fields`);for(let c of Object.keys(i))a.has(c)||v("NATIVE_DATA_SURFACE_FIELD_MISSING",`${o}/fields/${c}`);for(let c of t)Object.prototype.hasOwnProperty.call(i,c.code)||v("NATIVE_DATA_SURFACE_FIELD_REQUIRED",`${o}/fields/${c.code}`),Lo(i[c.code],c,`${o}/fields/${c.code}`);for(let c of["create","update"]){let _=r[c]??s==="native",p=t.some(d=>{let u=te(i[d.code],`${o}/fields/${d.code}`);return ln(d,u,c)});_&&!p&&v("NATIVE_DATA_SURFACE_WRITABLE_FIELDS_REQUIRED",`${o}/generated/${c}`)}if(ko(n.list,a,`${o}/list`),dn(n.form,a,`${o}/form`,"form"),dn(n.detail,a,`${o}/detail`,"detail"),n.mobile!==void 0){let c=te(n.mobile,`${o}/mobile`);pe(c,Ne.mobile,`${o}/mobile`),Nt(c.enabled,`${o}/mobile/enabled`)}vo(n,t,o)}function Ct(e,t){let o=e.views?.find(s=>s.code===t);o||v("NATIVE_DATA_VIEW_NOT_FOUND",`/surface/views/${t}`);let n=new Map((o.sections||[]).flatMap(s=>s.fields.map(r=>[r,s.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(([s,r])=>{let a={...r};delete a.section;let i=n.get(s);return[s,{...a,...i?{section:i}:{},list:o.list.fieldOrder.includes(s)}]}))}}function vo(e,t,o){if(e.views===void 0)return;(!Array.isArray(e.views)||e.views.length>20)&&v("NATIVE_DATA_VIEWS_LIMIT_INVALID",`${o}/views`);let n=new Set;e.views.forEach((s,r)=>{let a=`${o}/views/${r}`,i=te(s,a);pe(i,["code","name","generated","list","form","detail","mobile","sections"],a);let c=me(i.code,`${a}/code`,64);(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(c)||n.has(c))&&v("NATIVE_DATA_VIEW_CODE_INVALID",`${a}/code`),n.add(c),me(i.name,`${a}/name`,255),te(i.generated,`${a}/generated`),te(i.mobile,`${a}/mobile`);for(let p of["list","detail","create","update","delete"])typeof i.generated[p]!="boolean"&&v("NATIVE_DATA_VIEW_OPERATION_INVALID",`${a}/generated/${p}`);typeof i.mobile.enabled!="boolean"&&v("NATIVE_DATA_VIEW_MOBILE_INVALID",`${a}/mobile/enabled`);for(let p of["list","form","detail"]){let d=te(i[p],`${a}/${p}`),u=Se(d.fieldOrder,`${a}/${p}/fieldOrder`,500,!0);for(let E of u){let l=e.fields[E];(!l||(l.hidden??l.system)===!0)&&v("NATIVE_DATA_VIEW_FIELD_INVALID",`${a}/${p}/fieldOrder`)}}if(i.sections!==void 0){(!Array.isArray(i.sections)||i.sections.length>100)&&v("NATIVE_DATA_VIEW_SECTIONS_INVALID",`${a}/sections`);let p=new Set;i.sections.forEach((d,u)=>{let E=`${a}/sections/${u}`,l=te(d,E);pe(l,["title","fields"],E),me(l.title,`${E}/title`,255);for(let A of Se(l.fields,`${E}/fields`,100,!0)){let T=e.fields[A];(!T||(T.hidden??T.system)===!0||p.has(A))&&v("NATIVE_DATA_VIEW_FIELD_INVALID",`${E}/fields`),p.add(A)}})}let _=Ct(e,c);if(gt(_,t,a),i.generated.create!==!1&&(e.mutationOwner||"native")==="native")for(let p of t)ze(p,e.fields[p.code])&&ln(p,e.fields[p.code],"create")&&!i.form.fieldOrder.includes(p.code)&&v("NATIVE_DATA_VIEW_CREATE_REQUIRED_FIELD_MISSING",`${a}/form/fieldOrder`)})}function ln(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 Lo(e,t,o){let n=te(e,o);pe(n,Ne.field,o),me(n.label,`${o}/label`,500),n.type!==t.type&&v("NATIVE_DATA_SURFACE_FIELD_TYPE_MISMATCH",`${o}/type`);let s=me(n.widget,`${o}/widget`,64);Po[t.type].includes(s)||v("NATIVE_DATA_SURFACE_WIDGET_INCOMPATIBLE",`${o}/widget`),Mo(n.section,`${o}/section`,255);for(let r of["requiredHint","system","hidden","list","searchable","sortable"])Nt(n[r],`${o}/${r}`);n.searchable===!0&&!At(t.type)&&v("NATIVE_DATA_SURFACE_SEARCH_UNSUPPORTED",`${o}/searchable`),n.sortable===!0&&!ve(t.type)&&v("NATIVE_DATA_SURFACE_SORT_UNSUPPORTED",`${o}/sortable`);for(let r of["readCapabilities","createCapabilities","updateCapabilities"])Se(n[r],`${o}/${r}`,100,!0);if(n.maxCount!==void 0&&(!Number.isSafeInteger(n.maxCount)||Number(n.maxCount)<1||Number(n.maxCount)>100)&&v("NATIVE_DATA_SURFACE_MAX_COUNT_INVALID",`${o}/maxCount`),n.maxSizeMb!==void 0&&(!Number.isSafeInteger(n.maxSizeMb)||Number(n.maxSizeMb)<1||Number(n.maxSizeMb)>1024)&&v("NATIVE_DATA_SURFACE_MAX_SIZE_INVALID",`${o}/maxSizeMb`),n.accept!==void 0){let r=Array.isArray(n.accept)?n.accept:[n.accept];Se(r,`${o}/accept`,50,!1)}for(let r of["maxLength","precision","scale","exactDecimal","min","max","rangeBoundary","options","source","timePrecision","serial","subtable"])xo(n,t,r,o);Uo(n,t,o)}function ko(e,t,o){if(e===void 0)return;let n=te(e,o);if(pe(n,Ne.list,o),n.actions!==void 0){let s=te(n.actions,`${o}/actions`);pe(s,["import","export"],`${o}/actions`);for(let r of["import","export"])s[r]!==void 0&&typeof s[r]!="boolean"&&v("NATIVE_DATA_SURFACE_LIST_ACTION_INVALID",`${o}/actions/${r}`)}if(n.fieldOrder!==void 0)for(let s of Se(n.fieldOrder,`${o}/fieldOrder`,500,!0))t.has(s)||v("NATIVE_DATA_SURFACE_LIST_FIELD_INVALID",`${o}/fieldOrder`);n.defaultPageSize!==void 0&&(!Number.isSafeInteger(n.defaultPageSize)||Number(n.defaultPageSize)<1||Number(n.defaultPageSize)>200)&&v("NATIVE_DATA_SURFACE_PAGE_SIZE_INVALID",`${o}/defaultPageSize`);for(let[s,r]of[["searchableFields",At],["filterFields",on]]){if(n[s]===void 0)continue;let a=Se(n[s],`${o}/${s}`,100,!0);for(let i of a){let c=t.get(i);(!c||!r(c.type))&&v("NATIVE_DATA_SURFACE_LIST_FIELD_INVALID",`${o}/${s}`)}}if(n.defaultSort!==void 0){let s=te(n.defaultSort,`${o}/defaultSort`);pe(s,Ne.defaultSort,`${o}/defaultSort`);let r=me(s.field,`${o}/defaultSort/field`,63),a=t.get(r);!Zt(r)&&(!a||!ve(a.type))&&v("NATIVE_DATA_SURFACE_SORT_UNSUPPORTED",`${o}/defaultSort/field`),s.order!==void 0&&!["asc","desc"].includes(s.order)&&v("NATIVE_DATA_SURFACE_SORT_ORDER_INVALID",`${o}/defaultSort/order`)}}function dn(e,t,o,n){if(e===void 0)return;let s=te(e,o);if(pe(s,Ne[n],o),s.layout!==void 0&&!["flat","sections"].includes(s.layout)&&v("NATIVE_DATA_SURFACE_LAYOUT_INVALID",`${o}/layout`),s.fieldOrder!==void 0){let r=`${o}/fieldOrder`;(!Array.isArray(s.fieldOrder)||s.fieldOrder.length>t.size||s.fieldOrder.length>Fo)&&v("NATIVE_DATA_SURFACE_FIELD_ORDER_INVALID",r);let a=s.fieldOrder.map((i,c)=>me(i,`${r}/${c}`,63));new Set(a).size!==a.length&&v("NATIVE_DATA_SURFACE_FIELD_ORDER_INVALID",r),a.forEach((i,c)=>{t.has(i)||v("NATIVE_DATA_SURFACE_FIELD_ORDER_FIELD_MISSING",`${r}/${c}`)})}n==="form"&&an(s.draftState,`${o}/draftState`)}function xo(e,t,o,n){e[o]===void 0&&t[o]===void 0||((e[o]===void 0||t[o]===void 0)&&v("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${n}/${o}`),Q(e[o])!==Q(t[o])&&v("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${n}/${o}`))}function Uo(e,t,o){let n=t.file||{},s={...e.maxCount===void 0?{}:{maxCount:e.maxCount},...e.maxSizeMb===void 0?{}:{maxSizeMb:e.maxSizeMb},...e.accept===void 0?{}:{accept:Tt(e.accept)}};for(let r of["maxCount","maxSizeMb","accept"]){if(s[r]===void 0&&n[r]===void 0)continue;(s[r]===void 0||n[r]===void 0)&&v("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${o}/${r}`);let a=r==="accept"?Tt(s[r]):s[r],i=r==="accept"?Tt(n[r]):n[r];Q(a)!==Q(i)&&v("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${o}/${r}`)}}function Tt(e){return(Array.isArray(e)?[...e]:[e]).sort((t,o)=>{let n=String(t),s=String(o);return n===s?0:n<s?-1:1})}function Se(e,t,o,n){(!Array.isArray(e)||!n&&e.length===0||e.length>o)&&v("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t);let s=e.map((r,a)=>me(r,`${t}/${a}`,255));return new Set(s).size!==s.length&&v("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t),s}function te(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&v("NATIVE_OBJECT_REQUIRED",t),e}function pe(e,t,o){let n=new Set(t);for(let s of Object.keys(e))n.has(s)||v("NATIVE_PROPERTY_UNKNOWN",`${o}/${s}`)}function me(e,t,o){return(typeof e!="string"||e.length===0||e.length>o)&&v("NATIVE_STRING_INVALID",t),e}function Mo(e,t,o){e!==void 0&&(typeof e!="string"||e.length>o)&&v("NATIVE_STRING_INVALID",t)}function Nt(e,t){e!==void 0&&typeof e!="boolean"&&v("NATIVE_BOOLEAN_REQUIRED",t)}function v(e,t){throw new _e(e,t)}var De=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"},Rt=["parentTransitions","childTransitions","fulfilledChildStatuses","lockedParentStatuses"],un=["amountFieldCode","currencyFieldCode","relationFieldCode","parentFieldCode","rootFieldCode","statusFieldCode","parentRelationValue","childRelationValue"],He=e=>!!(e&&typeof e=="object"&&!Array.isArray(e)),Ke=e=>Array.isArray(e)?e.filter(He):[],Ee=(e,t)=>{throw new De(e,t)},bt=e=>typeof e=="string"&&/^[A-Za-z0-9._:-]{1,128}$/.test(e),Ot=(e,t)=>e<t?-1:e>t?1:0;function $t(e,t="/decimalReservationLifecycle"){if(e===void 0)return;if(!He(e)||Object.keys(e).some(s=>!Rt.includes(s))||Rt.some(s=>!Object.prototype.hasOwnProperty.call(e,s)))return Ee(t,"\u5FC5\u987B\u5B8C\u6574\u58F0\u660E\u56DB\u9879\u89C4\u5219\uFF0C\u4E0D\u80FD\u5305\u542B\u672A\u77E5\u5C5E\u6027");let o=s=>{let r=e[s];if(!Array.isArray(r)||r.length>64)return Ee(`${t}/${s}`,"\u72B6\u6001\u8FB9\u6700\u591A 64 \u6761");let a=new Set;return r.map((i,c)=>{let _=`${t}/${s}/${c}`;if(!He(i)||Object.keys(i).some(d=>d!=="from"&&d!=="to")||!bt(i.from)||!bt(i.to)||i.from===i.to)return Ee(_,"\u72B6\u6001\u8FB9\u5FC5\u987B\u5305\u542B\u4E0D\u540C\u7684\u6709\u6548 from/to");let p=JSON.stringify([i.from,i.to]);return a.has(p)?Ee(_,"\u72B6\u6001\u8FB9\u4E0D\u80FD\u91CD\u590D"):(a.add(p),{from:i.from,to:i.to})}).sort((i,c)=>Ot(i.from,c.from)||Ot(i.to,c.to))},n=s=>{let r=e[s];return!Array.isArray(r)||r.length<1||r.length>16||r.some(a=>!bt(a))||new Set(r).size!==r.length?Ee(`${t}/${s}`,"\u72B6\u6001\u96C6\u5408\u5FC5\u987B\u5305\u542B 1 \u5230 16 \u4E2A\u4E0D\u91CD\u590D\u7684\u6709\u6548\u72B6\u6001"):[...r].sort(Ot)};return{parentTransitions:o("parentTransitions"),childTransitions:o("childTransitions"),fulfilledChildStatuses:n("fulfilledChildStatuses"),lockedParentStatuses:n("lockedParentStatuses")}}function fn(e,t,o="/config/data/resources"){Ke(e).forEach((n,s)=>{let r=`${o}/${s}/decimalReservationLifecycle`,a=$t(n.decimalReservationLifecycle,r);if(!a)return;let i=Ke(t).map(d=>d.platformAccess?.decimalReservation).filter(d=>He(d)&&d.resourceCode===n.code),c=i.find(d=>d.mode==="reserve");if(!c)return Ee(r,"\u9700\u8981\u540C\u8D44\u6E90\u5DF2\u58F0\u660E\u7684 reserve \u52A8\u4F5C\u6620\u5C04");if(un.some(d=>typeof c[d]!="string")||i.some(d=>un.some(u=>d[u]!==c[u])))return Ee(r,"\u540C\u8D44\u6E90\u989D\u5EA6\u52A8\u4F5C\u7684\u5B57\u6BB5\u6620\u5C04\u5FC5\u987B\u4E00\u81F4");let _=Ke(n.schema?.fields).find(d=>d.code===c.statusFieldCode);if(_?.type!=="option.single")return Ee(r,"\u989D\u5EA6\u72B6\u6001\u5B57\u6BB5\u5FC5\u987B\u4E3A option.single");let p=new Set(Ke(_.options).map(d=>d.value));for(let d of Rt)if((d==="parentTransitions"||d==="childTransitions"?a[d].flatMap(E=>[E.from,E.to]):a[d]).some(E=>!p.has(E)))return Ee(`${r}/${d}`,"\u72B6\u6001\u5FC5\u987B\u6765\u81EA\u989D\u5EA6\u72B6\u6001\u5B57\u6BB5\u7684\u9009\u9879");if(i.some(d=>d.mode==="reserve"&&Array.isArray(d.eligibleParentStatuses)&&d.eligibleParentStatuses.some(u=>a.lockedParentStatuses.includes(String(u)))))return Ee(`${r}/lockedParentStatuses`,"\u9501\u5B9A\u7236\u72B6\u6001\u4E0D\u80FD\u5141\u8BB8\u65B0\u9884\u7559")})}import{createHash as jo}from"crypto";var ht=new Set(["option.single","user.single","department.single","resource-ref.single"]),Bo=new Set(["option.multiple","cascade.single","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","address","location","json"]),pn=new Set(["option.multiple","cascade.single","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","file","image"]),Jo=new Set(["option.single","user.single","department.single","resource-ref.single","signature","address","location"]),Wo=new Set([...ht,...pn,"signature","address","location","json"]);function Hi(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=>Go(n,o.has(n.code))).sort((n,s)=>n.code.localeCompare(s.code))}function Go(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:qo(e),index:Yo(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 Xi(e,t){if(t.type==="subtable")return null;let o=oe(t.code),n=En(e,t),s=[n?` DEFAULT ${n}`:"",Ko(o,t),zo(o,t)].join("");return`${o} ${t.storage}${s}`}function Qi(e,t){return En(e,t)}function zo(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 Zi(e){return e.type==="serial-number"||Ge(e.type)&&e.type!=="subtable"}function er(e,t){return t.filter(o=>o.type==="serial-number").map(o=>{let n=Qe(e,o.code),s=o.serial?.start??1;return`CREATE SEQUENCE IF NOT EXISTS ${n} AS bigint MINVALUE ${s} START WITH ${s} CACHE 1`})}function tr(e,t){let o=Xe(e);return t.filter(n=>n.type==="serial-number").map(n=>`ALTER SEQUENCE ${Qe(e,n.code)} OWNED BY ${o}.${oe(n.code)}`)}function nr(e,t){return t.filter(o=>o.type==="serial-number").map(o=>`GRANT USAGE, SELECT ON SEQUENCE ${Qe(e,o.code)} TO "openxiangda_data_api"`)}function or(e,t){let o=Xe(e),n=[];for(let s of t){if(s.type==="subtable")continue;let r=oe(s.code),a=oe(ge("idx",e,s.code,s.index));switch(s.index){case"btree":n.push(`CREATE INDEX IF NOT EXISTS ${a} ON ${o} (${r})`);break;case"btree-snapshot-expressions":{let i=oe(ge("idx",e,s.code,"snapshot-value")),c=oe(ge("idx",e,s.code,"snapshot-label"));n.push(`CREATE INDEX IF NOT EXISTS ${i} ON ${o} ((${r} ->> 'value'))`,`CREATE INDEX IF NOT EXISTS ${c} ON ${o} ((${r} ->> 'label'))`);break}case"gin-jsonb-path":n.push(`CREATE INDEX IF NOT EXISTS ${a} ON ${o} USING GIN (${r} jsonb_path_ops)`);break;case"gist-range":n.push(`CREATE INDEX IF NOT EXISTS ${a} ON ${o} USING GIST (${r})`);break;case"gin-trigram":{let i=ht.has(s.type)?`((${r} ->> 'label')) gin_trgm_ops`:`${r} gin_trgm_ops`;n.push(`CREATE INDEX IF NOT EXISTS ${a} ON ${o} USING GIN (${i})`);break}case"none":break}if(s.type==="serial-number"){let i=oe(ge("uidx",e,s.code,"serial"));n.push(`CREATE UNIQUE INDEX IF NOT EXISTS ${i} ON ${o} (${r})`)}}return n}function sr(e,t,o,n){let s=Xe(e),r=Xe(t),a=oe(ge("uidx",e,"environment_id","subtable-parent")),i=oe(ge("idx",t,o,n,"subtable-child")),c=oe(ge("fk",t,o,e)),_=oe(o),p=oe(n);return[`CREATE UNIQUE INDEX IF NOT EXISTS ${a} ON ${s} ("tenant_id", "app_code", "environment_key", "id")`,`CREATE INDEX IF NOT EXISTS ${i} ON ${r} ("tenant_id", "app_code", "environment_key", ${_}, ${p}, "id")`,`DO $native_subtable$ BEGIN
|
|
2
|
-
ALTER TABLE ${
|
|
3
|
-
ADD CONSTRAINT ${
|
|
4
|
-
FOREIGN KEY ("tenant_id", "app_code", "environment_key", ${
|
|
1
|
+
import{createHash as go}from"node:crypto";function No(e){if(!e||typeof e!="object")return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function ft(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,s)=>ft(n,`${t}[${s}]`)).join(",")}]`;if(No(e))return`{${Object.keys(e).filter(s=>e[s]!==void 0).sort((s,i)=>s===i?0:s<i?-1:1).map(s=>`${JSON.stringify(s)}:${ft(e[s],`${t}.${s}`)}`).join(",")}}`;let o=e instanceof Date?"Date":e?.constructor?.name||typeof e;throw new TypeError(`Value is not JSON serializable: ${t} (${o})`)}function Q(e){return ft(e,"$")}function ee(e){return go("sha256").update(Q(e)).digest("hex")}var en=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,Et=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,To=["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"],Co=new Set(To),tn=new Set(["option.multiple","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","file","image","subtable"]),Xt=new Set(["option.single","option.multiple","cascade.single","cascade.multiple"]),Qt=new Set(["resource-ref.single","resource-ref.multiple"]),At=[{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}],ki=new Map(At.map(e=>[e.code,e])),_e=class extends Error{constructor(o,n){super(o);this.code=o;this.pointer=n;this.name="NativeDataFieldContractV2Error"}code;pointer};function Ye(e){return tn.has(e)}function Ke(e,t={}){return e.type!=="serial-number"&&t.system!==!0&&e.nullable===!1&&(!Ye(e.type)||t.requiredHint===!0)}function It(e,t,o=500){Array.isArray(e)||h("NATIVE_ARRAY_REQUIRED",t),e.length===0&&h("NATIVE_DATA_FIELDS_REQUIRED",t),e.length>o&&h("NATIVE_ARRAY_LIMIT_EXCEEDED",t);let n=new Set;return e.map((s,i)=>{let c=`${t}/${i}`,r=re(s,c);ce(r,["code","type","nullable","indexed","options","source","maxLength","precision","scale","exactDecimal","min","max","rangeBoundary","timePrecision","file","serial","subtable"],c);let a=de(r.code,`${c}/code`,63);en.test(a)||h("NATIVE_FIELD_CODE_INVALID",`${c}/code`),n.has(a)&&h("NATIVE_DATA_FIELD_DUPLICATE",`${c}/code`),n.add(a);let f=de(r.type,`${c}/type`,32);Co.has(f)||h("NATIVE_DATA_FIELD_TYPE_INVALID",`${c}/type`);let E=f,d=_t(r.nullable,`${c}/nullable`),u=_t(r.indexed,`${c}/indexed`);d===!0&&tn.has(E)&&h("NATIVE_DATA_MULTI_FIELD_NULLABLE_INVALID",`${c}/nullable`);let m=yo(r.options,E,c),l=$o(r.source,E,c),A=ho(r,E,c),N=_t(r.exactDecimal,`${c}/exactDecimal`);N!==void 0&&E!=="number.decimal"&&h("NATIVE_DATA_FIELD_EXACT_DECIMAL_TYPE_INVALID",`${c}/exactDecimal`);let _=bo(r.rangeBoundary,E,c),I=So(r.file,E,c),T=Do(r.serial,E,c),b=Vo(r.subtable,E,c);return{code:a,type:E,...d===void 0?{}:{nullable:d},...u===void 0?{}:{indexed:u},...m?{options:m}:{},...l?{source:l}:{},...A,...N===void 0?{}:{exactDecimal:N},..._?{rangeBoundary:_}:{},...I?{file:I}:{},...T?{serial:T}:{},...b?{subtable:b}:{}}})}function bo(e,t,o){let n=`${o}/rangeBoundary`;if(!(t==="date-range"||t==="datetime-range")){e!==void 0&&h("NATIVE_DATA_FIELD_RANGE_BOUNDARY_TYPE_INVALID",n);return}return e!=="closed"&&e!=="half-open"&&h("NATIVE_DATA_FIELD_RANGE_BOUNDARY_REQUIRED",n),e}function nn(e,t){Array.isArray(e)||h("NATIVE_ARRAY_REQUIRED",t);let o=new Map;e.forEach((n,s)=>{let i=`${t}/${s}`,c=re(n,i),r=de(c.code,`${i}/code`,64);(!Et.test(r)||o.has(r))&&h("NATIVE_RESOURCE_CODE_INVALID",`${i}/code`);let a=re(c.schema,`${i}/schema`);o.set(r,{pointer:i,fields:It(a.fields,`${i}/schema/fields`)})});for(let[n,s]of o){let i=new Map(s.fields.map(r=>[r.code,r]));s.fields.filter(r=>r.type==="subtable").reduce((r,a)=>r+(a.subtable?.maxRows??20),0)>49&&h("NATIVE_DATA_FIELD_SUBTABLE_AGGREGATE_MAX_ROWS_EXCEEDED",`${s.pointer}/schema/fields`),s.fields.forEach((r,a)=>{let f=`${s.pointer}/schema/fields/${a}`;if(r.source&&Oo(r.source,i,o,`${f}/source`),r.subtable){let E=o.get(r.subtable.resourceCode);(!E||r.subtable.resourceCode===n)&&h("NATIVE_DATA_FIELD_SUBTABLE_TARGET_MISSING",`${f}/subtable/resourceCode`);let d=E.fields.find(m=>m.code===r.subtable?.foreignKey);(!d||d.type!=="uuid"||d.nullable!==!1)&&h("NATIVE_DATA_FIELD_SUBTABLE_FOREIGN_KEY_INVALID",`${f}/subtable/foreignKey`);let u=E.fields.find(m=>m.code===r.subtable?.orderField);(!u||u.type!=="number.integer"||u.nullable!==!1)&&h("NATIVE_DATA_FIELD_SUBTABLE_ORDER_FIELD_INVALID",`${f}/subtable/orderField`)}})}}function on(e,t,o){if(e===void 0)return[];(!Array.isArray(e)||e.length>20)&&h("NATIVE_DATA_RESOURCE_INVARIANTS_INVALID",o);let n=new Map(t.map(i=>[i.code,i])),s=new Set;return e.map((i,c)=>{let r=`${o}/${c}`,a=re(i,r);ce(a,["code","message","expression"],r);let f=de(a.code,`${r}/code`,128);(!/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/.test(f)||s.has(f))&&h("NATIVE_DATA_RESOURCE_INVARIANT_CODE_INVALID",`${r}/code`),s.add(f);let E=qe(a.message,`${r}/message`,500);E!==void 0&&E.length===0&&h("NATIVE_DATA_RESOURCE_INVARIANT_MESSAGE_INVALID",`${r}/message`);let d=re(a.expression,`${r}/expression`);if(d.kind==="nonBlankTextWhenOption"){ce(d,["kind","optionField","optionValue","textField"],`${r}/expression`);let I=pe(d.optionField,`${r}/expression/optionField`),T=pe(d.textField,`${r}/expression/textField`),b=de(d.optionValue,`${r}/expression/optionValue`,128),C=n.get(I),O=n.get(T);return(!C||!O)&&h("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_UNKNOWN",`${r}/expression`),(C.type!=="option.single"||!["text.short","text.long"].includes(O.type)||!C.options?.some(S=>S.value===b))&&h("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_TYPES_INVALID",`${r}/expression`),{code:f,...E===void 0?{}:{message:E},expression:{kind:"nonBlankTextWhenOption",optionField:I,optionValue:b,textField:T}}}ce(d,["leftField","operator","rightField"],`${r}/expression`);let u=pe(d.leftField,`${r}/expression/leftField`),m=pe(d.rightField,`${r}/expression/rightField`),l=n.get(u),A=n.get(m);(!l||!A)&&h("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_UNKNOWN",`${r}/expression`),l.type===A.type||["number.integer","number.decimal"].includes(l.type)&&["number.integer","number.decimal"].includes(A.type)||h("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_TYPES_INVALID",`${r}/expression`);let _=String(d.operator);return["eq","neq","gt","gte","lt","lte"].includes(_)||h("NATIVE_DATA_RESOURCE_INVARIANT_OPERATOR_INVALID",`${r}/expression/operator`),!["eq","neq"].includes(_)&&!["number.integer","number.decimal","date","time","datetime","text.short","text.long","text.rich","serial-number","uuid"].includes(l.type)&&h("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_TYPES_INVALID",`${r}/expression`),{code:f,...E===void 0?{}:{message:E},expression:{leftField:u,operator:_,rightField:m}}})}function Oo(e,t,o,n){let s=o.get(e.resourceCode);s||h("NATIVE_DATA_FIELD_SOURCE_TARGET_MISSING",`${n}/resourceCode`);let i=new Map(s.fields.map(r=>[r.code,r])),c=i.get(e.labelField);(!c||!["text.short","text.long"].includes(c.type))&&h("NATIVE_DATA_FIELD_SOURCE_LABEL_INVALID",`${n}/labelField`);for(let r of["searchFields","descriptionFields","snapshotFields"])for(let a of e[r]||[])i.has(a)||h("NATIVE_DATA_FIELD_SOURCE_FIELD_MISSING",`${n}/${r}`);for(let[r,a]of(e.filters||[]).entries())i.has(a.field)||h("NATIVE_DATA_FIELD_SOURCE_FILTER_FIELD_MISSING",`${n}/filters/${r}/field`),"binding"in a&&!t.has(a.binding.field)&&h("NATIVE_DATA_FIELD_SOURCE_BINDING_FIELD_MISSING",`${n}/filters/${r}/binding/field`)}function yo(e,t,o){let n=`${o}/options`;if(e===void 0){Xt.has(t)&&h("NATIVE_DATA_FIELD_OPTIONS_REQUIRED",n);return}(!Xt.has(t)||!Array.isArray(e))&&h("NATIVE_DATA_FIELD_OPTIONS_TYPE_INVALID",n),(e.length<1||e.length>100)&&h("NATIVE_DATA_FIELD_OPTIONS_INVALID",n);let s=0,i=(c,r,a)=>{a>5&&h("NATIVE_DATA_FIELD_OPTIONS_DEPTH_EXCEEDED",r);let f=new Set;return c.map((E,d)=>{s+=1,s>1e3&&h("NATIVE_DATA_FIELD_OPTIONS_COUNT_EXCEEDED",n);let u=`${r}/${d}`,m=re(E,u);ce(m,["label","value","description","color","children"],u);let l=de(m.label,`${u}/label`,500),A=de(m.value,`${u}/value`,500);f.has(A)&&h("NATIVE_DATA_FIELD_OPTION_VALUE_DUPLICATE",`${u}/value`),f.add(A);let N=qe(m.description,`${u}/description`,2e3),_=qe(m.color,`${u}/color`,64),I;return m.children!==void 0&&((!t.startsWith("cascade.")||!Array.isArray(m.children))&&h("NATIVE_DATA_FIELD_OPTION_CHILDREN_INVALID",`${u}/children`),(m.children.length<1||m.children.length>100)&&h("NATIVE_DATA_FIELD_OPTION_CHILDREN_INVALID",`${u}/children`),I=i(m.children,`${u}/children`,a+1)),{label:l,value:A,...N===void 0?{}:{description:N},..._===void 0?{}:{color:_},...I?{children:I}:{}}})};return i(e,n,1)}function $o(e,t,o){let n=`${o}/source`;if(e===void 0){Qt.has(t)&&h("NATIVE_DATA_FIELD_SOURCE_REQUIRED",n);return}Qt.has(t)||h("NATIVE_DATA_FIELD_SOURCE_TYPE_INVALID",n);let s=re(e,n);ce(s,["kind","resourceCode","labelField","searchFields","descriptionFields","snapshotFields","filters","pageSize","loadMode"],n),s.kind!=="resource"&&h("NATIVE_DATA_FIELD_SOURCE_KIND_INVALID",`${n}/kind`);let i=de(s.resourceCode,`${n}/resourceCode`,64);Et.test(i)||h("NATIVE_RESOURCE_CODE_INVALID",`${n}/resourceCode`);let c=pe(s.labelField,`${n}/labelField`),r=pt(s.searchFields,`${n}/searchFields`,10),a=pt(s.descriptionFields,`${n}/descriptionFields`,10),f=pt(s.snapshotFields,`${n}/snapshotFields`,50),E=Re(s.pageSize,`${n}/pageSize`,1,100),d;s.loadMode!==void 0&&(["search","all"].includes(String(s.loadMode))||h("NATIVE_DATA_FIELD_SOURCE_LOAD_MODE_INVALID",`${n}/loadMode`),d=s.loadMode);let u=Ro(s.filters,`${n}/filters`);return{kind:"resource",resourceCode:i,labelField:c,...r?{searchFields:r}:{},...a?{descriptionFields:a}:{},...f?{snapshotFields:f}:{},...u?{filters:u}:{},...E===void 0?{}:{pageSize:E},...d?{loadMode:d}:{}}}function Ro(e,t){if(e!==void 0)return(!Array.isArray(e)||e.length>20)&&h("NATIVE_DATA_FIELD_SOURCE_FILTERS_INVALID",t),e.map((o,n)=>{let s=`${t}/${n}`,i=re(o,s),c=Object.prototype.hasOwnProperty.call(i,"value"),r=Object.prototype.hasOwnProperty.call(i,"binding");ce(i,c?["field","operator","value"]:["field","operator","binding"],s),c===r&&h("NATIVE_DATA_FIELD_SOURCE_FILTER_VALUE_INVALID",s);let a=pe(i.field,`${s}/field`);["eq","in"].includes(String(i.operator))||h("NATIVE_DATA_FIELD_SOURCE_FILTER_OPERATOR_INVALID",`${s}/operator`);let f=i.operator;if(c)return{field:a,operator:f,value:i.value};let E=re(i.binding,`${s}/binding`);return ce(E,["kind","field"],`${s}/binding`),E.kind!=="field"&&h("NATIVE_DATA_FIELD_SOURCE_BINDING_KIND_INVALID",`${s}/binding/kind`),{field:a,operator:f,binding:{kind:"field",field:pe(E.field,`${s}/binding/field`)}}})}function ho(e,t,o){let n={};if(e.maxLength!==void 0&&(["text.short","text.long","text.rich"].includes(t)||h("NATIVE_DATA_FIELD_MAX_LENGTH_TYPE_INVALID",`${o}/maxLength`),n.maxLength=Ge(e.maxLength,`${o}/maxLength`,1,1e6)),(e.precision!==void 0||e.scale!==void 0)&&((t!=="number.decimal"||e.precision===void 0)&&h("NATIVE_DATA_FIELD_DECIMAL_CONFIG_INVALID",o),n.precision=Ge(e.precision,`${o}/precision`,1,1e3),n.scale=e.scale===void 0?0:Ge(e.scale,`${o}/scale`,0,n.precision)),e.min!==void 0||e.max!==void 0){["number.integer","number.decimal"].includes(t)||h("NATIVE_DATA_FIELD_NUMERIC_BOUNDS_TYPE_INVALID",o);let s=Zt(e.min,`${o}/min`),i=Zt(e.max,`${o}/max`);t==="number.integer"&&[s,i].some(c=>c!==void 0&&!Number.isSafeInteger(c))&&h("NATIVE_DATA_FIELD_NUMERIC_BOUNDS_INVALID",o),s!==void 0&&i!==void 0&&s>i&&h("NATIVE_DATA_FIELD_NUMERIC_BOUNDS_INVALID",o),s!==void 0&&(n.min=s),i!==void 0&&(n.max=i)}return e.timePrecision!==void 0&&((t!=="time"||!["minute","second"].includes(e.timePrecision))&&h("NATIVE_DATA_FIELD_TIME_PRECISION_INVALID",`${o}/timePrecision`),n.timePrecision=e.timePrecision),n}function So(e,t,o){if(e===void 0)return;let n=`${o}/file`;["file","image","signature"].includes(t)||h("NATIVE_DATA_FIELD_FILE_TYPE_INVALID",n);let s=re(e,n);ce(s,["maxCount","maxSizeMb","accept"],n);let i=Re(s.maxCount,`${n}/maxCount`,1,100);t==="signature"&&i!==void 0&&i!==1&&h("NATIVE_DATA_FIELD_SIGNATURE_COUNT_INVALID",`${n}/maxCount`);let c=Re(s.maxSizeMb,`${n}/maxSizeMb`,1,1024),r;return s.accept!==void 0&&((!Array.isArray(s.accept)||s.accept.length>50)&&h("NATIVE_DATA_FIELD_FILE_ACCEPT_INVALID",`${n}/accept`),r=s.accept.map((a,f)=>de(a,`${n}/accept/${f}`,255)),new Set(r).size!==r.length&&h("NATIVE_DATA_FIELD_FILE_ACCEPT_INVALID",`${n}/accept`)),{...i===void 0?{}:{maxCount:i},...c===void 0?{}:{maxSizeMb:c},...r===void 0?{}:{accept:r}}}function Do(e,t,o){let n=`${o}/serial`;if(e===void 0){t==="serial-number"&&h("NATIVE_DATA_FIELD_SERIAL_REQUIRED",n);return}t!=="serial-number"&&h("NATIVE_DATA_FIELD_SERIAL_TYPE_INVALID",n);let s=re(e,n);ce(s,["prefix","digits","start"],n);let i=qe(s.prefix,`${n}/prefix`,64),c=Re(s.digits,`${n}/digits`,1,32),r=Re(s.start,`${n}/start`,0,Number.MAX_SAFE_INTEGER);return{...i===void 0?{}:{prefix:i},...c===void 0?{}:{digits:c},...r===void 0?{}:{start:r}}}function Vo(e,t,o){let n=`${o}/subtable`;if(e===void 0){t==="subtable"&&h("NATIVE_DATA_FIELD_SUBTABLE_REQUIRED",n);return}t!=="subtable"&&h("NATIVE_DATA_FIELD_SUBTABLE_TYPE_INVALID",n);let s=re(e,n);ce(s,["resourceCode","foreignKey","orderField","maxRows"],n);let i=de(s.resourceCode,`${n}/resourceCode`,64);Et.test(i)||h("NATIVE_RESOURCE_CODE_INVALID",`${n}/resourceCode`);let c=pe(s.foreignKey,`${n}/foreignKey`),r=pe(s.orderField,`${n}/orderField`);r===c&&h("NATIVE_DATA_FIELD_SUBTABLE_ORDER_FIELD_INVALID",`${n}/orderField`);let a=Re(s.maxRows,`${n}/maxRows`,1,49);return{resourceCode:i,foreignKey:c,orderField:r,...a===void 0?{}:{maxRows:a}}}function pt(e,t,o){if(e===void 0)return;(!Array.isArray(e)||e.length>o)&&h("NATIVE_DATA_FIELD_SOURCE_FIELDS_INVALID",t);let n=e.map((s,i)=>pe(s,`${t}/${i}`));return new Set(n).size!==n.length&&h("NATIVE_DATA_FIELD_SOURCE_FIELDS_INVALID",t),n}function pe(e,t){let o=de(e,t,63);return en.test(o)||h("NATIVE_FIELD_CODE_INVALID",t),o}function re(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&h("NATIVE_OBJECT_REQUIRED",t),e}function ce(e,t,o){let n=new Set(t);for(let s of Object.keys(e))n.has(s)||h("NATIVE_PROPERTY_UNKNOWN",`${o}/${s}`)}function de(e,t,o){return(typeof e!="string"||e.length===0||e.length>o)&&h("NATIVE_STRING_INVALID",t),e}function qe(e,t,o){if(e!==void 0)return(typeof e!="string"||e.length>o)&&h("NATIVE_STRING_INVALID",t),e}function _t(e,t){if(e!==void 0)return typeof e!="boolean"&&h("NATIVE_BOOLEAN_REQUIRED",t),e}function Re(e,t,o,n){if(e!==void 0)return Ge(e,t,o,n)}function Zt(e,t){if(e!==void 0)return(typeof e!="number"||!Number.isFinite(e))&&h("NATIVE_NUMBER_REQUIRED",t),e}function Ge(e,t,o,n){return(!Number.isSafeInteger(e)||Number(e)<o||Number(e)>n)&&h("NATIVE_INTEGER_OUT_OF_RANGE",t),Number(e)}function h(e,t){throw new _e(e,t)}var sn=["created_by","updated_by","created_at","updated_at"];function ve(e){return sn.includes(e)}function rn(e){return sn.some(t=>Object.prototype.hasOwnProperty.call(e.fieldPolicies||{},t))}var wo=At.map(e=>e.code);function an(e){return wo.includes(e)}var Fo=["eq","neq","gt","gte","lt","lte","contains","startsWith","endsWith","in","between","has","hasAny","hasAll","overlaps","containedBy","jsonContains","isEmpty","isNotEmpty"],vo=new Set(Fo);function Mi(e){return vo.has(String(e))}var mt=["eq","neq","contains","startsWith","endsWith","in","isEmpty","isNotEmpty"],Pe=["eq","neq","gt","gte","lt","lte","between","in","isEmpty"],Po=["eq","neq","in","isEmpty"],He=["eq","neq","in","isEmpty","isNotEmpty"],he=["has","hasAny","hasAll","isEmpty","isNotEmpty"],cn=["overlaps","contains","containedBy","isEmpty"],gt=["jsonContains","isEmpty","isNotEmpty"],Nt=["isEmpty","isNotEmpty"],Lo={"text.short":mt,"text.long":mt,"text.rich":mt,"number.integer":Pe,"number.decimal":Pe,boolean:Po,date:Pe,time:Pe,datetime:Pe,"date-range":cn,"datetime-range":cn,"option.single":He,"option.multiple":he,"cascade.single":he,"cascade.multiple":he,"user.single":He,"user.multiple":he,"department.single":He,"department.multiple":he,"resource-ref.single":He,"resource-ref.multiple":he,file:Nt,image:Nt,signature:Nt,address:gt,location:gt,uuid:["eq","neq","in","isEmpty"],json:gt,"serial-number":["eq","neq","in","contains","startsWith"],subtable:[]},ko=new Set(["text.short","text.long","text.rich","option.single","user.single","department.single","resource-ref.single","serial-number"]),xo=new Set(["option.multiple","cascade.single","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","file","image","signature","address","location","json","subtable"]);function ln(e){return Lo[e]}function Bi(e,t){return ln(e).includes(t)}function Tt(e){return ko.has(e)}function Le(e){return!xo.has(e)}function un(e){return ln(e).length>0}var dn=new Set(["number.integer","number.decimal"]),fn=new Set(["text.short","text.long","number.integer","number.decimal","date","time","datetime","serial-number"]),Uo=new Set([...fn,"boolean","uuid"]),jo=new Set(["option.single","user.single","department.single","resource-ref.single"]);function Ji(e,t){return t==="sum"||t==="avg"?dn.has(e)?{valueExpression:"column",numericResult:!0}:null:t==="min"||t==="max"?fn.has(e)?{valueExpression:"column",numericResult:dn.has(e)}:null:jo.has(e)?{valueExpression:"snapshot-value",numericResult:!0}:Uo.has(e)?{valueExpression:"column",numericResult:!0}:null}var bt=["version","maxBytes","fields"];function _n(e,t){if(e===void 0)return;let o=Ct(e,t);pn(o,bt,t);let n=Xe(o.version,`${t}/version`,1,1e6),s=Xe(o.maxBytes,`${t}/maxBytes`,2,196608);(!n||!s)&&oe("NATIVE_DATA_DRAFT_STATE_SCHEMA_INVALID",t);let i=Ct(o.fields,`${t}/fields`),c=Object.entries(i);(!c.length||c.length>50)&&oe("NATIVE_DATA_DRAFT_STATE_FIELDS_INVALID",`${t}/fields`);for(let[r,a]of c){let f=`${t}/fields/${r}`;/^[A-Za-z][A-Za-z0-9_]{0,62}$/.test(r)||oe("NATIVE_DATA_DRAFT_STATE_FIELD_CODE_INVALID",f);let E=Ct(a,f),d=En(E.type,`${f}/type`,32),u=d==="string"?["type","required","maxLength","enum"]:d==="json.object"?["type","required","maxBytes"]:["type","required"];if(["string","number","integer","boolean","json.object"].includes(d)||oe("NATIVE_DATA_DRAFT_STATE_FIELD_TYPE_INVALID",`${f}/type`),pn(E,u,f),Bo(E.required,`${f}/required`),d==="string"){let m=Xe(E.maxLength,`${f}/maxLength`,1,196608);m||oe("NATIVE_DATA_DRAFT_STATE_FIELD_INVALID",f),E.enum!==void 0&&Mo(E.enum,`${f}/enum`,100,!1).some(A=>A.length>m)&&oe("NATIVE_DATA_DRAFT_STATE_FIELD_INVALID",`${f}/enum`)}else if(d==="json.object"){let m=Xe(E.maxBytes,`${f}/maxBytes`,2,65536);(!m||m>s)&&oe("NATIVE_DATA_DRAFT_STATE_FIELD_INVALID",f)}}}function Mo(e,t,o,n){(!Array.isArray(e)||!n&&e.length===0||e.length>o)&&oe("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t);let s=e.map((i,c)=>En(i,`${t}/${c}`,255));return new Set(s).size!==s.length&&oe("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t),s}function Ct(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&oe("NATIVE_OBJECT_REQUIRED",t),e}function pn(e,t,o){let n=new Set(t);for(let s of Object.keys(e))n.has(s)||oe("NATIVE_PROPERTY_UNKNOWN",`${o}/${s}`)}function En(e,t,o){return(typeof e!="string"||e.length===0||e.length>o)&&oe("NATIVE_STRING_INVALID",t),e}function Bo(e,t){e!==void 0&&typeof e!="boolean"&&oe("NATIVE_BOOLEAN_REQUIRED",t)}function Xe(e,t,o,n){return(!Number.isSafeInteger(e)||Number(e)<o||Number(e)>n)&&oe("NATIVE_INTEGER_INVALID",t),Number(e)}function oe(e,t){throw new _e(e,t)}var Jo=500,Te={surface:["mutationOwner","generated","fields","list","form","detail","mobile","views"],generated:["list","detail","create","update","delete"],field:["label","type","widget","section","requiredHint","system","hidden","readCapabilities","createCapabilities","updateCapabilities","maxLength","precision","scale","exactDecimal","min","max","rangeBoundary","maxCount","maxSizeMb","accept","options","list","searchable","sortable","source","timePrecision","serial","subtable"],list:["actions","fieldOrder","defaultPageSize","searchableFields","filterFields","defaultSort"],defaultSort:["field","order"],form:["layout","fieldOrder","draftState"],detail:["layout","fieldOrder"],layout:["layout","fieldOrder","draftState"],draftState:bt,mobile:["enabled"]},Wo={"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 $t(e,t,o){if(e===void 0)return;let n=te(e,o);Ee(n,Te.surface,o);let s=n.mutationOwner===void 0?"native":ge(n.mutationOwner,`${o}/mutationOwner`,16);["native","action","readonly","workflow","queued-command"].includes(s)||P("NATIVE_DATA_SURFACE_MUTATION_OWNER_INVALID",`${o}/mutationOwner`);let i=n.generated===void 0?{}:te(n.generated,`${o}/generated`);Ee(i,Te.generated,`${o}/generated`);for(let a of Te.generated)yt(i[a],`${o}/generated/${a}`);if(s!=="native")for(let a of["create","update","delete"])i[a]===!0&&P("NATIVE_DATA_SURFACE_MUTATION_OWNER_CONFLICT",`${o}/generated/${a}`);let c=new Map(t.map(a=>[a.code,a])),r=te(n.fields,`${o}/fields`);for(let a of Object.keys(r))c.has(a)||P("NATIVE_DATA_SURFACE_FIELD_MISSING",`${o}/fields/${a}`);for(let a of t)Object.prototype.hasOwnProperty.call(r,a.code)||P("NATIVE_DATA_SURFACE_FIELD_REQUIRED",`${o}/fields/${a.code}`),Go(r[a.code],a,`${o}/fields/${a.code}`);for(let a of["create","update"]){let f=i[a]??s==="native",E=t.some(d=>{let u=te(r[d.code],`${o}/fields/${d.code}`);return In(d,u,a)});f&&!E&&P("NATIVE_DATA_SURFACE_WRITABLE_FIELDS_REQUIRED",`${o}/generated/${a}`)}if(qo(n.list,c,`${o}/list`),An(n.form,c,`${o}/form`,"form"),An(n.detail,c,`${o}/detail`,"detail"),n.mobile!==void 0){let a=te(n.mobile,`${o}/mobile`);Ee(a,Te.mobile,`${o}/mobile`),yt(a.enabled,`${o}/mobile/enabled`)}zo(n,t,o)}function Rt(e,t){let o=e.views?.find(s=>s.code===t);o||P("NATIVE_DATA_VIEW_NOT_FOUND",`/surface/views/${t}`);let n=new Map((o.sections||[]).flatMap(s=>s.fields.map(i=>[i,s.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(([s,i])=>{let c={...i};delete c.section;let r=n.get(s);return[s,{...c,...r?{section:r}:{},list:o.list.fieldOrder.includes(s)}]}))}}function zo(e,t,o){if(e.views===void 0)return;(!Array.isArray(e.views)||e.views.length>20)&&P("NATIVE_DATA_VIEWS_LIMIT_INVALID",`${o}/views`);let n=new Set;e.views.forEach((s,i)=>{let c=`${o}/views/${i}`,r=te(s,c);Ee(r,["code","name","generated","list","form","detail","mobile","sections"],c);let a=ge(r.code,`${c}/code`,64);(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(a)||n.has(a))&&P("NATIVE_DATA_VIEW_CODE_INVALID",`${c}/code`),n.add(a),ge(r.name,`${c}/name`,255),te(r.generated,`${c}/generated`),te(r.mobile,`${c}/mobile`);for(let E of["list","detail","create","update","delete"])typeof r.generated[E]!="boolean"&&P("NATIVE_DATA_VIEW_OPERATION_INVALID",`${c}/generated/${E}`);typeof r.mobile.enabled!="boolean"&&P("NATIVE_DATA_VIEW_MOBILE_INVALID",`${c}/mobile/enabled`);for(let E of["list","form","detail"]){let d=te(r[E],`${c}/${E}`),u=Se(d.fieldOrder,`${c}/${E}/fieldOrder`,500,!0);for(let m of u){let l=e.fields[m];(!l||(l.hidden??l.system)===!0)&&P("NATIVE_DATA_VIEW_FIELD_INVALID",`${c}/${E}/fieldOrder`)}}if(r.sections!==void 0){(!Array.isArray(r.sections)||r.sections.length>100)&&P("NATIVE_DATA_VIEW_SECTIONS_INVALID",`${c}/sections`);let E=new Set;r.sections.forEach((d,u)=>{let m=`${c}/sections/${u}`,l=te(d,m);Ee(l,["title","fields"],m),ge(l.title,`${m}/title`,255);for(let A of Se(l.fields,`${m}/fields`,100,!0)){let N=e.fields[A];(!N||(N.hidden??N.system)===!0||E.has(A))&&P("NATIVE_DATA_VIEW_FIELD_INVALID",`${m}/fields`),E.add(A)}})}let f=Rt(e,a);if($t(f,t,c),r.generated.create!==!1&&(e.mutationOwner||"native")==="native")for(let E of t)Ke(E,e.fields[E.code])&&In(E,e.fields[E.code],"create")&&!r.form.fieldOrder.includes(E.code)&&P("NATIVE_DATA_VIEW_CREATE_REQUIRED_FIELD_MISSING",`${c}/form/fieldOrder`)})}function In(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 Go(e,t,o){let n=te(e,o);Ee(n,Te.field,o),ge(n.label,`${o}/label`,500),n.type!==t.type&&P("NATIVE_DATA_SURFACE_FIELD_TYPE_MISMATCH",`${o}/type`);let s=ge(n.widget,`${o}/widget`,64);Wo[t.type].includes(s)||P("NATIVE_DATA_SURFACE_WIDGET_INCOMPATIBLE",`${o}/widget`),Ho(n.section,`${o}/section`,255);for(let i of["requiredHint","system","hidden","list","searchable","sortable"])yt(n[i],`${o}/${i}`);n.searchable===!0&&!Tt(t.type)&&P("NATIVE_DATA_SURFACE_SEARCH_UNSUPPORTED",`${o}/searchable`),n.sortable===!0&&!Le(t.type)&&P("NATIVE_DATA_SURFACE_SORT_UNSUPPORTED",`${o}/sortable`);for(let i of["readCapabilities","createCapabilities","updateCapabilities"])Se(n[i],`${o}/${i}`,100,!0);if(n.maxCount!==void 0&&(!Number.isSafeInteger(n.maxCount)||Number(n.maxCount)<1||Number(n.maxCount)>100)&&P("NATIVE_DATA_SURFACE_MAX_COUNT_INVALID",`${o}/maxCount`),n.maxSizeMb!==void 0&&(!Number.isSafeInteger(n.maxSizeMb)||Number(n.maxSizeMb)<1||Number(n.maxSizeMb)>1024)&&P("NATIVE_DATA_SURFACE_MAX_SIZE_INVALID",`${o}/maxSizeMb`),n.accept!==void 0){let i=Array.isArray(n.accept)?n.accept:[n.accept];Se(i,`${o}/accept`,50,!1)}for(let i of["maxLength","precision","scale","exactDecimal","min","max","rangeBoundary","options","source","timePrecision","serial","subtable"])Yo(n,t,i,o);Ko(n,t,o)}function qo(e,t,o){if(e===void 0)return;let n=te(e,o);if(Ee(n,Te.list,o),n.actions!==void 0){let s=te(n.actions,`${o}/actions`);Ee(s,["import","export"],`${o}/actions`);for(let i of["import","export"])s[i]!==void 0&&typeof s[i]!="boolean"&&P("NATIVE_DATA_SURFACE_LIST_ACTION_INVALID",`${o}/actions/${i}`)}if(n.fieldOrder!==void 0)for(let s of Se(n.fieldOrder,`${o}/fieldOrder`,500,!0))t.has(s)||P("NATIVE_DATA_SURFACE_LIST_FIELD_INVALID",`${o}/fieldOrder`);n.defaultPageSize!==void 0&&(!Number.isSafeInteger(n.defaultPageSize)||Number(n.defaultPageSize)<1||Number(n.defaultPageSize)>200)&&P("NATIVE_DATA_SURFACE_PAGE_SIZE_INVALID",`${o}/defaultPageSize`);for(let[s,i]of[["searchableFields",Tt],["filterFields",un]]){if(n[s]===void 0)continue;let c=Se(n[s],`${o}/${s}`,100,!0);for(let r of c){let a=t.get(r);(!a||!i(a.type))&&P("NATIVE_DATA_SURFACE_LIST_FIELD_INVALID",`${o}/${s}`)}}if(n.defaultSort!==void 0){let s=te(n.defaultSort,`${o}/defaultSort`);Ee(s,Te.defaultSort,`${o}/defaultSort`);let i=ge(s.field,`${o}/defaultSort/field`,63),c=t.get(i);!an(i)&&(!c||!Le(c.type))&&P("NATIVE_DATA_SURFACE_SORT_UNSUPPORTED",`${o}/defaultSort/field`),s.order!==void 0&&!["asc","desc"].includes(s.order)&&P("NATIVE_DATA_SURFACE_SORT_ORDER_INVALID",`${o}/defaultSort/order`)}}function An(e,t,o,n){if(e===void 0)return;let s=te(e,o);if(Ee(s,Te[n],o),s.layout!==void 0&&!["flat","sections"].includes(s.layout)&&P("NATIVE_DATA_SURFACE_LAYOUT_INVALID",`${o}/layout`),s.fieldOrder!==void 0){let i=`${o}/fieldOrder`;(!Array.isArray(s.fieldOrder)||s.fieldOrder.length>t.size||s.fieldOrder.length>Jo)&&P("NATIVE_DATA_SURFACE_FIELD_ORDER_INVALID",i);let c=s.fieldOrder.map((r,a)=>ge(r,`${i}/${a}`,63));new Set(c).size!==c.length&&P("NATIVE_DATA_SURFACE_FIELD_ORDER_INVALID",i),c.forEach((r,a)=>{t.has(r)||P("NATIVE_DATA_SURFACE_FIELD_ORDER_FIELD_MISSING",`${i}/${a}`)})}n==="form"&&_n(s.draftState,`${o}/draftState`)}function Yo(e,t,o,n){e[o]===void 0&&t[o]===void 0||((e[o]===void 0||t[o]===void 0)&&P("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${n}/${o}`),Q(e[o])!==Q(t[o])&&P("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${n}/${o}`))}function Ko(e,t,o){let n=t.file||{},s={...e.maxCount===void 0?{}:{maxCount:e.maxCount},...e.maxSizeMb===void 0?{}:{maxSizeMb:e.maxSizeMb},...e.accept===void 0?{}:{accept:Ot(e.accept)}};for(let i of["maxCount","maxSizeMb","accept"]){if(s[i]===void 0&&n[i]===void 0)continue;(s[i]===void 0||n[i]===void 0)&&P("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${o}/${i}`);let c=i==="accept"?Ot(s[i]):s[i],r=i==="accept"?Ot(n[i]):n[i];Q(c)!==Q(r)&&P("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${o}/${i}`)}}function Ot(e){return(Array.isArray(e)?[...e]:[e]).sort((t,o)=>{let n=String(t),s=String(o);return n===s?0:n<s?-1:1})}function Se(e,t,o,n){(!Array.isArray(e)||!n&&e.length===0||e.length>o)&&P("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t);let s=e.map((i,c)=>ge(i,`${t}/${c}`,255));return new Set(s).size!==s.length&&P("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t),s}function te(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&P("NATIVE_OBJECT_REQUIRED",t),e}function Ee(e,t,o){let n=new Set(t);for(let s of Object.keys(e))n.has(s)||P("NATIVE_PROPERTY_UNKNOWN",`${o}/${s}`)}function ge(e,t,o){return(typeof e!="string"||e.length===0||e.length>o)&&P("NATIVE_STRING_INVALID",t),e}function Ho(e,t,o){e!==void 0&&(typeof e!="string"||e.length>o)&&P("NATIVE_STRING_INVALID",t)}function yt(e,t){e!==void 0&&typeof e!="boolean"&&P("NATIVE_BOOLEAN_REQUIRED",t)}function P(e,t){throw new _e(e,t)}var ke=class extends Error{constructor(o,n){super(`${o}: ${n}`);this.pointer=o;this.reason=n}pointer;reason;code="NATIVE_MANAGED_CONCURRENCY_INVALID"};function mn(e,t,o){if(e===void 0)return;let n=(_,I)=>{throw new ke(_,I)},s=(_,I,T)=>((!_||typeof _!="object"||Array.isArray(_)||Object.keys(_).some(b=>!T.includes(b)))&&n(I,"object contains unsupported properties"),_),i=(_,I,T,b)=>{(!Number.isSafeInteger(_)||_<I||_>T)&&n(b,`expected integer ${I}..${T}`)},c=(_,I)=>{(typeof _!="string"||!/^[a-z][a-z0-9_-]{0,63}$/.test(_))&&n(I,"invalid code")},r=(_,I,T)=>((!Array.isArray(_)||_.length>I)&&n(T,"array exceeds bound"),_),a=(_,I)=>{let T=t.find(b=>b.code===_);return T||n(I,"unknown resource"),T},f=(_,I,T)=>{let b=_.schema.fields.find(C=>C.code===I);return!b&&I!=="id"&&n(T,"unknown field"),b},E=(_,I)=>{s(_,I,Object.keys(_||{})),Object.keys(_).length>8&&n(I,"at most eight parameters");for(let[T,b]of Object.entries(_))if(c(T,I),s(b,I,["type","values","minimum","maximum"]),b.type==="uuid")Object.keys(b).length!==1&&n(I,"uuid has no options");else if(b.type==="string"){s(b,I,["type","values"]);let C=r(b.values,100,I);(!C.length||C.some(O=>typeof O!="string"||O.length>128)||new Set(C).size!==C.length)&&n(I,"finite string values required")}else b.type==="integer"?(s(b,I,["type","minimum","maximum"]),i(b.minimum,0,1e6,I),i(b.maximum,b.minimum,b.minimum+1e3,I)):n(I,"unsupported parameter type")},d=(_,I,T,b=!1)=>{s(_,T,["from","key","value"]),!(_.from==="input"&&Object.keys(_).length===2&&Object.hasOwn(I,_.key))&&((_.from==="actor"||b&&_.from==="allocation")&&Object.keys(_).length===1||_.from==="literal"&&Object.keys(_).length===2&&Object.hasOwn(_,"value")&&(_.value===null||["string","boolean"].includes(typeof _.value)||typeof _.value=="number"&&Number.isFinite(_.value))&&JSON.stringify(_.value).length<=512||n(T,"invalid binding"))},u=(_,I,T)=>{d(_,I,T),!(_.from==="input"&&I[_.key].type==="uuid")&&(_.from==="literal"&&typeof _.value=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(_.value)||n(T,"record and allocation identifiers require a UUID binding"))},m=(_,I,T)=>{d(_,I,T),!(_.from==="input"&&I[_.key].type==="integer"&&I[_.key].minimum>=1)&&(_.from==="literal"&&Number.isSafeInteger(_.value)&&_.value>=1||n(T,"expectedRevision requires a positive integer binding"))},l="/data/concurrency";JSON.stringify(e).length>131072&&n(l,"declaration exceeds 128 KiB");let A=s(e,l,["version","admission","reads","quotas","commands"]);A.version!==1&&n(l,"unsupported version"),s(A.admission,l,["perSecond","burst","maxInFlight"]),i(A.admission.perSecond,1,1e3,l),i(A.admission.burst,1,1e3,l),i(A.admission.maxInFlight,1,1e3,l);let N=(_,I)=>{let T=new Set;for(let b of _)c(b?.code,I),T.has(b.code)&&n(I,"duplicate code"),T.add(b.code)};N(r(A.reads,32,l),l),N(r(A.quotas,16,l),l),N(r(A.commands,32,l),l);for(let _ of A.reads){let I=`${l}/reads/${_.code}`;s(_,I,["code","resourceCode","parameters","select","where","limit","scope","freshSeconds","staleSeconds","maxKeys","sourcePerSecond","dependencies"]);let T=a(_.resourceCode,I);E(_.parameters,I),["subject","application"].includes(_.scope)||n(I,"invalid cache scope"),_.scope==="application"&&T.dataPolicyCode&&n(I,"shared cache cannot bypass a row policy");let b=r(_.select,32,I);b.length||n(I,"select required"),b.forEach(O=>f(T,O,I));let C=r(_.dependencies,64,I);C.forEach(O=>f(T,O,I));for(let O of r(_.where||[],8,I))s(O,I,["field","value"]),f(T,O.field,I),d(O.value,_.parameters,I),_.scope==="application"&&O.value.from==="actor"&&n(I,"actor requires subject cache"),C.includes(O.field)||n(I,"filter dependency missing");b.some(O=>!C.includes(O))&&n(I,"selected field dependency missing"),i(_.limit,1,100,I),i(_.freshSeconds,1,300,I),i(_.staleSeconds,0,300,I),i(_.maxKeys,1,1e4,I),i(_.sourcePerSecond,1,20,I)}for(let _ of A.quotas){let I=`${l}/quotas/${_.code}`;s(_,I,["code","sourceResource","capacityField","allocationResource","allocationField","reservationSeconds"]);let T=a(_.sourceResource,I),b=a(_.allocationResource,I);f(T,_.capacityField,I)?.type!=="number.integer"&&n(I,"capacity must be an integer"),(f(b,_.allocationField,I)?.type!=="uuid"||f(b,_.allocationField,I)?.nullable!==!1)&&n(I,"allocation reference must be a uuid"),b.surface?.mutationOwner!=="queued-command"&&n(I,"allocation model must be command owned"),_.reservationSeconds!==void 0&&i(_.reservationSeconds,10,86400,I)}new Set(A.quotas.map(_=>_.allocationResource)).size!==A.quotas.length&&n(l,"an allocation model has exactly one pool owner");for(let _ of A.commands){let I=`${l}/commands/${_.code}`;s(_,I,["code","capability","parameters","resourceKey","admission","deadlineSeconds","guards","operations","quota"]),E(_.parameters,I),d(_.resourceKey,_.parameters,I),o.some(T=>T.code===_.capability)||n(I,"command capability must be declared"),s(_.admission,I,["perSecond","burst","maxInFlight","maxQueue","maxWaitSeconds","permitSeconds"]),i(_.admission.perSecond,1,A.admission.perSecond,I),i(_.admission.burst,1,A.admission.burst,I),i(_.admission.maxInFlight,1,A.admission.maxInFlight,I),i(_.admission.maxQueue,1,1e4,I),i(_.admission.maxWaitSeconds,1,3600,I),i(_.admission.permitSeconds,5,60,I),i(_.deadlineSeconds,10,3600,I);for(let T of r(_.guards||[],8,I)){s(T,I,["resourceCode","id","conditions"]);let b=a(T.resourceCode,I);u(T.id,_.parameters,I);for(let C of r(T.conditions,16,I)){s(C,I,["kind","field","operator","value"]);let O=f(b,C.field,I);["eq","neq","lt","lte","gt","gte"].includes(C.operator)||n(I,"unsupported guard"),C.kind==="database-now"?(O?.type!=="datetime"||!["lt","lte","gt","gte"].includes(C.operator)||C.value!==void 0)&&n(I,"database-now requires datetime and an ordering operator"):(C.kind!==void 0&&C.kind!=="value"&&n(I,"unsupported condition kind"),d(C.value,_.parameters,I))}}for(let T of r(_.operations,8,I)){s(T,I,["operation","resourceCode","id","expectedRevision","data"]);let b=a(T.resourceCode,I);b.surface?.mutationOwner!=="queued-command"&&n(I,"command mutations require command owned models");let C=A.quotas.find(O=>O.allocationResource===T.resourceCode);C&&(T.operation==="create"?_.quota?.action!=="allocate"||_.quota.pool!==C.code:Object.hasOwn(T.data||{},C.allocationField))&&n(I,"allocation references are owned by their pool command"),["create","update"].includes(T.operation)||n(I,"unsupported operation"),T.operation==="update"?(u(T.id,_.parameters,I),m(T.expectedRevision,_.parameters,I)):(T.id!==void 0||T.expectedRevision!==void 0)&&n(I,"create has no caller supplied id/revision"),s(T.data,I,Object.keys(T.data||{})),Object.keys(T.data).length>32&&n(I,"too many fields");for(let[O,S]of Object.entries(T.data))O==="id"&&n(I,"record identifiers are platform owned"),f(b,O,I),d(S,_.parameters,I,_.quota?.action==="allocate")}if(_.quota){let T=s(_.quota,I,["pool","action","units","mode","allocation"]),b=A.quotas.find(C=>C.code===T.pool);b||n(I,"unknown quota pool"),u(_.resourceKey,_.parameters,I),T.action==="allocate"?(s(T,I,["pool","action","units","mode"]),i(T.units,1,1e3,I),(!["committed","reserved"].includes(T.mode)||T.mode==="reserved"&&!b.reservationSeconds)&&n(I,"invalid allocation mode"),(_.operations.length!==1||_.operations[0].operation!=="create"||_.operations[0].resourceCode!==b.allocationResource||_.operations[0].data[b.allocationField]?.from!=="allocation")&&n(I,"allocation must atomically create its bound business record")):["confirm","release"].includes(T.action)?(s(T,I,["pool","action","allocation"]),u(T.allocation,_.parameters,I),_.operations.length&&n(I,"lifecycle owns allocation state; business reference remains immutable")):n(I,"invalid quota action")}else _.operations.length||n(I,"operations required")}return JSON.parse(JSON.stringify(A))}var De=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"},Dt=["parentTransitions","childTransitions","fulfilledChildStatuses","lockedParentStatuses"],gn=["amountFieldCode","currencyFieldCode","relationFieldCode","parentFieldCode","rootFieldCode","statusFieldCode","parentRelationValue","childRelationValue"],Ze=e=>!!(e&&typeof e=="object"&&!Array.isArray(e)),Qe=e=>Array.isArray(e)?e.filter(Ze):[],Ae=(e,t)=>{throw new De(e,t)},ht=e=>typeof e=="string"&&/^[A-Za-z0-9._:-]{1,128}$/.test(e),St=(e,t)=>e<t?-1:e>t?1:0;function Vt(e,t="/decimalReservationLifecycle"){if(e===void 0)return;if(!Ze(e)||Object.keys(e).some(s=>!Dt.includes(s))||Dt.some(s=>!Object.prototype.hasOwnProperty.call(e,s)))return Ae(t,"\u5FC5\u987B\u5B8C\u6574\u58F0\u660E\u56DB\u9879\u89C4\u5219\uFF0C\u4E0D\u80FD\u5305\u542B\u672A\u77E5\u5C5E\u6027");let o=s=>{let i=e[s];if(!Array.isArray(i)||i.length>64)return Ae(`${t}/${s}`,"\u72B6\u6001\u8FB9\u6700\u591A 64 \u6761");let c=new Set;return i.map((r,a)=>{let f=`${t}/${s}/${a}`;if(!Ze(r)||Object.keys(r).some(d=>d!=="from"&&d!=="to")||!ht(r.from)||!ht(r.to)||r.from===r.to)return Ae(f,"\u72B6\u6001\u8FB9\u5FC5\u987B\u5305\u542B\u4E0D\u540C\u7684\u6709\u6548 from/to");let E=JSON.stringify([r.from,r.to]);return c.has(E)?Ae(f,"\u72B6\u6001\u8FB9\u4E0D\u80FD\u91CD\u590D"):(c.add(E),{from:r.from,to:r.to})}).sort((r,a)=>St(r.from,a.from)||St(r.to,a.to))},n=s=>{let i=e[s];return!Array.isArray(i)||i.length<1||i.length>16||i.some(c=>!ht(c))||new Set(i).size!==i.length?Ae(`${t}/${s}`,"\u72B6\u6001\u96C6\u5408\u5FC5\u987B\u5305\u542B 1 \u5230 16 \u4E2A\u4E0D\u91CD\u590D\u7684\u6709\u6548\u72B6\u6001"):[...i].sort(St)};return{parentTransitions:o("parentTransitions"),childTransitions:o("childTransitions"),fulfilledChildStatuses:n("fulfilledChildStatuses"),lockedParentStatuses:n("lockedParentStatuses")}}function Nn(e,t,o="/config/data/resources"){Qe(e).forEach((n,s)=>{let i=`${o}/${s}/decimalReservationLifecycle`,c=Vt(n.decimalReservationLifecycle,i);if(!c)return;let r=Qe(t).map(d=>d.platformAccess?.decimalReservation).filter(d=>Ze(d)&&d.resourceCode===n.code),a=r.find(d=>d.mode==="reserve");if(!a)return Ae(i,"\u9700\u8981\u540C\u8D44\u6E90\u5DF2\u58F0\u660E\u7684 reserve \u52A8\u4F5C\u6620\u5C04");if(gn.some(d=>typeof a[d]!="string")||r.some(d=>gn.some(u=>d[u]!==a[u])))return Ae(i,"\u540C\u8D44\u6E90\u989D\u5EA6\u52A8\u4F5C\u7684\u5B57\u6BB5\u6620\u5C04\u5FC5\u987B\u4E00\u81F4");let f=Qe(n.schema?.fields).find(d=>d.code===a.statusFieldCode);if(f?.type!=="option.single")return Ae(i,"\u989D\u5EA6\u72B6\u6001\u5B57\u6BB5\u5FC5\u987B\u4E3A option.single");let E=new Set(Qe(f.options).map(d=>d.value));for(let d of Dt)if((d==="parentTransitions"||d==="childTransitions"?c[d].flatMap(m=>[m.from,m.to]):c[d]).some(m=>!E.has(m)))return Ae(`${i}/${d}`,"\u72B6\u6001\u5FC5\u987B\u6765\u81EA\u989D\u5EA6\u72B6\u6001\u5B57\u6BB5\u7684\u9009\u9879");if(r.some(d=>d.mode==="reserve"&&Array.isArray(d.eligibleParentStatuses)&&d.eligibleParentStatuses.some(u=>c.lockedParentStatuses.includes(String(u)))))return Ae(`${i}/lockedParentStatuses`,"\u9501\u5B9A\u7236\u72B6\u6001\u4E0D\u80FD\u5141\u8BB8\u65B0\u9884\u7559")})}import{createHash as Xo}from"crypto";var wt=new Set(["option.single","user.single","department.single","resource-ref.single"]),Qo=new Set(["option.multiple","cascade.single","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","address","location","json"]),Cn=new Set(["option.multiple","cascade.single","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","file","image"]),Zo=new Set(["option.single","user.single","department.single","resource-ref.single","signature","address","location"]),es=new Set([...wt,...Cn,"signature","address","location","json"]);function ar(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=>ts(n,o.has(n.code))).sort((n,s)=>n.code.localeCompare(s.code))}function ts(e,t=!1){let o=e.type==="date-range"||e.type==="datetime-range";if(o&&e.rangeBoundary!=="closed"&&e.rangeBoundary!=="half-open")throw new Error("OPENXIANGDA_NATIVE_DATA_RANGE_BOUNDARY_INVALID");return{code:e.code,type:e.type,nullable:!0,indexed:e.indexed===!0,storage:ss(e),index:os(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 cr(e,t){if(t.type==="subtable")return null;let o=se(t.code),n=bn(e,t),s=[n?` DEFAULT ${n}`:"",is(o,t),ns(o,t)].join("");return`${o} ${t.storage}${s}`}function dr(e,t){return bn(e,t)}function ns(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 lr(e){return e.type==="serial-number"||Ye(e.type)&&e.type!=="subtable"}function ur(e,t){return t.filter(o=>o.type==="serial-number").map(o=>{let n=tt(e,o.code),s=o.serial?.start??1;return`CREATE SEQUENCE IF NOT EXISTS ${n} AS bigint MINVALUE ${s} START WITH ${s} CACHE 1`})}function fr(e,t){let o=et(e);return t.filter(n=>n.type==="serial-number").map(n=>`ALTER SEQUENCE ${tt(e,n.code)} OWNED BY ${o}.${se(n.code)}`)}function pr(e,t){return t.filter(o=>o.type==="serial-number").map(o=>`GRANT USAGE, SELECT ON SEQUENCE ${tt(e,o.code)} TO "openxiangda_data_api"`)}function _r(e,t){let o=et(e),n=[];for(let s of t){if(s.type==="subtable")continue;let i=se(s.code),c=se(Ce("idx",e,s.code,s.index));switch(s.index){case"btree":n.push(`CREATE INDEX IF NOT EXISTS ${c} ON ${o} (${i})`);break;case"btree-snapshot-expressions":{let r=se(Ce("idx",e,s.code,"snapshot-value")),a=se(Ce("idx",e,s.code,"snapshot-label"));n.push(`CREATE INDEX IF NOT EXISTS ${r} 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 ${c} ON ${o} USING GIN (${i} jsonb_path_ops)`);break;case"gist-range":n.push(`CREATE INDEX IF NOT EXISTS ${c} ON ${o} USING GIST (${i})`);break;case"gin-trigram":{let r=wt.has(s.type)?`((${i} ->> 'label')) gin_trgm_ops`:`${i} gin_trgm_ops`;n.push(`CREATE INDEX IF NOT EXISTS ${c} ON ${o} USING GIN (${r})`);break}case"none":break}if(s.type==="serial-number"){let r=se(Ce("uidx",e,s.code,"serial"));n.push(`CREATE UNIQUE INDEX IF NOT EXISTS ${r} ON ${o} (${i})`)}}return n}function Er(e,t,o,n){let s=et(e),i=et(t),c=se(Ce("uidx",e,"environment_id","subtable-parent")),r=se(Ce("idx",t,o,n,"subtable-child")),a=se(Ce("fk",t,o,e)),f=se(o),E=se(n);return[`CREATE UNIQUE INDEX IF NOT EXISTS ${c} ON ${s} ("tenant_id", "app_code", "environment_key", "id")`,`CREATE INDEX IF NOT EXISTS ${r} ON ${i} ("tenant_id", "app_code", "environment_key", ${f}, ${E}, "id")`,`DO $native_subtable$ BEGIN
|
|
2
|
+
ALTER TABLE ${i}
|
|
3
|
+
ADD CONSTRAINT ${a}
|
|
4
|
+
FOREIGN KEY ("tenant_id", "app_code", "environment_key", ${f})
|
|
5
5
|
REFERENCES ${s} ("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 ge(e,...t){return`${e}_${jo("sha256").update(t.join(":")).digest("hex").slice(0,32)}`}function oe(e){if(!/^[A-Za-z_][A-Za-z0-9_]{0,62}$/.test(e))throw new Error("OPENXIANGDA_NATIVE_IDENTIFIER_INVALID");return`"${e}"`}function Yo(e,t){return e.type==="subtable"?"none":t?"gin-trigram":e.indexed?["date-range","datetime-range"].includes(e.type)?"gist-range":ht.has(e.type)?"btree-snapshot-expressions":Bo.has(e.type)?"gin-jsonb-path":"btree":"none"}function qo(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 Wo.has(e.type),"jsonb"}}function En(e,t){if(Ge(t.type)&&t.type!=="subtable")return"'[]'::jsonb";if(t.type!=="serial-number")return"";let o=_n(t.serial?.prefix||""),n=t.serial?.digits??6;return`(${o} || lpad(nextval(${_n(Qe(e,t.code))})::text, ${n}, '0'))`}function Ko(e,t){return pn.has(t.type)?` CHECK (${e} IS NULL OR jsonb_typeof(${e}) = 'array')`:Jo.has(t.type)?` CHECK (${e} IS NULL OR jsonb_typeof(${e}) = 'object')`:""}function Xe(e){return`"app_data".${oe(e)}`}function Qe(e,t){let o=ge("seq",e,t);return`"app_data".${oe(o)}`}function _n(e){return`'${e.replace(/'/g,"''")}'`}var An=new Set(["option.single","option.multiple","user.single","user.multiple","department.single","department.multiple","resource-ref.single","resource-ref.multiple"]),Ho=new Set([...An,"cascade.single","cascade.multiple","file","image","signature","address","location","json"]),In=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,Xo=new Set(["__proto__","prototype","constructor"]),St=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 Le(e,t){let o=Tn(e);if(!o)return null;let n=t.get(o[0]);if(!n)return null;let s=o.slice(1).join(".")||void 0;return{field:n,...s?{valuePath:s}:{}}}function Dt(e){return!!(e&&e.field.type==="user.single"&&e.valuePath==="value")}function mn(e,t,o){if(!e||!t||!Qo(e))return!1;let{field:n,valuePath:s}=e;if(!s)return t.valueType==="uuid"?n.type==="uuid":["text.short","text.long","serial-number"].includes(n.type);if(s==="value")return!(t.valueSourceResourceCode&&n.type.startsWith("resource-ref.")&&n.source?.resourceCode!==t.valueSourceResourceCode);let r=s.slice(9),i=o.get(n.source?.resourceCode||"")?.get(r)?.type;return t.valueType==="uuid"?i==="uuid":["text.short","text.long","serial-number"].includes(i||"")}function rr(e,t){let o=Tn(t);if(!o)throw new St(String(t||""));let n=e;for(let s of o){if(!n||typeof n!="object"||!Object.prototype.hasOwnProperty.call(n,s))return;n=n[s]}return n}function Qo(e){let{field:t,valuePath:o}=e;if(!o)return!Ho.has(t.type);if(o==="value")return An.has(t.type);if(!o.startsWith("snapshot."))return!1;let n=o.slice(9);return In.test(n)&&t.type.startsWith("resource-ref.")&&!!t.source?.snapshotFields?.includes(n)}function Tn(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=>!In.test(o)||Xo.has(o))||t.length===2&&t[1]!=="value"||t.length===3&&t[1]!=="snapshot"?null:t}var Zo=new Set(["option.single","user.single","department.single","resource-ref.single"]),es=new Set(["text.short","text.long","text.rich","number.integer","number.decimal","boolean","date","time","datetime","uuid","serial-number"]),ts=new Set(["value","label","description","color"]),ns=new Set(["avatarUrl","employeeNo","title","mobile","email"]),os=new Set(["fullPath","parent.value","parent.label"]),ss=new Set(["country.value","country.label","province.value","province.label","city.value","city.label","district.value","district.label","street.value","street.label","detail","fullAddress"]),is=new Set(["longitude","latitude","accuracy"]),rs=new Set(["address","name","province","city","district","source"]);function cr(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 s=as(n,t);if(!Object.keys(s).length)return n;let r={...n};return Object.defineProperty(r,"queryPathTypes",{configurable:!1,enumerable:!1,writable:!1,value:Object.freeze(s)}),r})}}))}function dr(e,t){if(Zo.has(e.type)&&ts.has(t)||e.type==="user.single"&&ns.has(t)||e.type==="department.single"&&os.has(t))return ke(t);if(e.type==="resource-ref.single"){let o=e.queryPathTypes?.[t];return o?{parts:t.split("."),type:o}:null}if(e.type==="address"&&ss.has(t))return ke(t);if(e.type==="location"){if(is.has(t))return{parts:[t],type:"number.decimal"};if(rs.has(t))return ke(t);if(t==="capturedAt")return{parts:[t],type:"datetime"}}return null}function as(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 s=o.get(n);return s?[[`snapshot.${n}`,es.has(s.type)?s.type:"json"]]:[]})):{}}function ke(e){return{parts:e.split("."),type:"text.short"}}var Nn={"openxiangda.workflow.instance.completed.v2":"commit","openxiangda.workflow.instance.rejected.v2":"release","openxiangda.workflow.instance.withdrawn.v2":"release"};function gn(e,t){let o=()=>{throw new Error("NATIVE_EVENT_DECIMAL_RESERVATION_INVALID")},n=u=>!u||typeof u!="object"||Array.isArray(u)?o():u,s=n(e);if(Object.keys(s).some(u=>!["resourceCode","workflowCode","outcomes"].includes(u))||typeof s.resourceCode!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(s.resourceCode)||typeof s.workflowCode!="string"||!/^[A-Za-z0-9._:-]{1,128}$/.test(s.workflowCode)||t.execution!==void 0||!Array.isArray(s.outcomes)||!s.outcomes.length||s.outcomes.length>3)return o();let r=t.resources.find(u=>u.code===s.resourceCode),a=t.reservations.find(u=>u.mode==="reserve"&&u.resourceCode===s.resourceCode),i=t.workflows.find(u=>u.code===s.workflowCode);if(!r||!a||!i||i.resourceCode!==r.code)return o();let c=r.fields.find(u=>u.code===a.statusFieldCode);if(c?.type!=="option.single")return o();let _=new Set(c.options?.map(u=>u.value)),p=new Set,d=s.outcomes.map(u=>{let E=n(u),l=E.eventType;return Object.keys(E).some(A=>!["eventType","mode","eligibleChildStatuses"].includes(A))||typeof l!="string"||!Object.prototype.hasOwnProperty.call(Nn,l)||!t.eventTypes.includes(l)||p.has(l)||E.mode!==Nn[l]||!Array.isArray(E.eligibleChildStatuses)||!E.eligibleChildStatuses.length||E.eligibleChildStatuses.length>16||new Set(E.eligibleChildStatuses).size!==E.eligibleChildStatuses.length||E.eligibleChildStatuses.some(A=>typeof A!="string"||!/^[A-Za-z0-9._:-]{1,128}$/.test(A)||!_.has(A))?o():(p.add(l),{eventType:l,mode:E.mode,eligibleChildStatuses:[...E.eligibleChildStatuses].sort()})}).sort((u,E)=>u.eventType.localeCompare(E.eventType));return{resourceCode:s.resourceCode,workflowCode:s.workflowCode,outcomes:d}}function Cn(e,t){let o=n=>Array.isArray(n)?n.filter(s=>s&&typeof s=="object"&&!Array.isArray(s)):[];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(s=>({code:s.code,type:s.type,options:o(s.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 yt=class extends Error{constructor(o,n){super(n);this.pointer=o}pointer;code="NATIVE_EVENT_ACTION_INVALID"};function bn(e,t,o="/events/subscriptions"){if(e.execution===void 0)return;let n=(A,T)=>{throw new yt(`${o}${A}`,T)},s=(A,T,m)=>((!A||typeof A!="object"||Array.isArray(A)||Object.keys(A).some(N=>!m.includes(N)))&&n(T,"Invalid action object or unsupported property"),A),r=s(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 a=e.filter?.resourceCodes;(!Array.isArray(a)||!a.length||a.length>20)&&n("/filter/resourceCodes","Native actions require explicit source resources");let i=new Map(t.map(A=>[A.code,A])),c=a.map(A=>{let T=i.get(A);return T||n("/filter/resourceCodes","Unknown source resource"),new Set((T.schema?.fields||[]).map(m=>m.code))}),_=new Set(e.payload?.fields||[]),p=e.payload?.includeChanges===!0,d=(A,T)=>{let m=s(A,T,["source","path","value"]);if(m.source==="literal"){(!Object.hasOwn(m,"value")||Object.hasOwn(m,"path"))&&n(T,"Literal binding requires only value");let g;try{g=JSON.stringify(m.value)}catch{n(T,"Literal must be JSON")}return(g===void 0||Buffer.byteLength(g)>65536)&&n(T,"Literal is too large or not JSON"),{source:"literal",value:JSON.parse(g)}}(m.source!=="event"||typeof m.path!="string"||Object.hasOwn(m,"value"))&&n(T,"Expected a literal or event binding");let N=m.path.split(".");(N.length>8||N.some(g=>!/^[A-Za-z0-9_-]+$/.test(g)||["__proto__","prototype","constructor"].includes(g)))&&n(T,"Invalid event path");let b=/^data\.projection\.([A-Za-z][A-Za-z0-9_]{0,62})$/.exec(m.path),R=/^data\.changes\.([A-Za-z][A-Za-z0-9_]{0,62})\.(before|after)$/.exec(m.path);if(b||R){let g=(b||R)[1];c.some(C=>!C.has(g))&&n(T,"Source field must exist on every filtered resource"),_.add(g),R&&(p=!0)}else["id","time","type","subject","data.recordId","data.revision","data.operation","data.resourceCode"].includes(m.path)||n(T,"Event path is not part of the data event contract");return{source:"event",path:m.path}};(!Array.isArray(r.operations)||r.operations.length<1||r.operations.length>16)&&n("/execution/operations","Expected 1 to 16 operations");let u={},E=r.operations.map((A,T)=>{let m=`/execution/operations/${T}`,N=s(A,m,["operation","resourceCode","data","id","expectedRevision"]);["create","update","delete"].includes(N.operation)||n(m,"Unsupported Native operation");let b=i.get(N.resourceCode);b||n(m,"Unknown action target resource");let R=new Map((b.schema?.fields||[]).map(C=>[C.code,C])),g=N.data===void 0?{}:s(N.data,`${m}/data`,[...R.keys()]);return Object.keys(g).length>32&&n(m,"Maximum 32 mapped fields per operation"),N.operation==="create"&&(N.id!==void 0||N.expectedRevision!==void 0)&&n(m,"Create does not accept id or expectedRevision"),N.operation==="delete"&&N.data!==void 0&&n(m,"Delete does not accept data"),Object.keys(g).some(C=>R.get(C)?.type==="serial-number")&&n(m,"Generated fields cannot be assigned"),u[N.resourceCode]=ee(b),{operation:N.operation,resourceCode:N.resourceCode,...N.operation==="create"?{}:{id:d(N.id,`${m}/id`),expectedRevision:d(N.expectedRevision,`${m}/expectedRevision`)},...N.operation==="delete"?{}:{data:Object.fromEntries(Object.entries(g).map(([C,D])=>[C,d(D,`${m}/data/${C}`)]))}}});(_.size>32||[..._].some(A=>c.some(T=>!T.has(A))))&&n("/payload/fields","Payload must contain at most 32 declared source fields");let l={kind:"native-data",version:1,operations:E,resourceDigests:u};return Buffer.byteLength(JSON.stringify(l))>65536&&n("/execution","Action plan exceeds 64 KiB"),{execution:{...l,digest:ee(l)},payload:{includeChanges:p,fields:[..._].sort()}}}function Ce(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function Rn(e,t){if(e?.instanceCommands===void 0)return[];let o=Ce(e.instanceCommands);if(!o||!Object.keys(o).length||Object.keys(o).some(s=>!["withdraw","terminate"].includes(s)))return["WORKFLOW_INSTANCE_COMMAND_POLICIES_INVALID"];let n=[];for(let[s,r]of Object.entries(o)){let a=Ce(r),i=s==="withdraw"?["beforeFact"]:["beforeFact","capability"];if(!a||Object.keys(a).some(c=>!i.includes(c))){n.push(`WORKFLOW_INSTANCE_COMMAND_POLICY_INVALID:${s}`);continue}if(s==="terminate"){let c=a.capability;(typeof c!="string"||c.length>255||!/^app:[a-z][a-z0-9]*(?:-[a-z0-9]+)*:[A-Za-z0-9:._-]+$/.test(c)||t&&(!c.startsWith(`app:${t.appCode}:`)||!t.capabilities.includes(c)))&&n.push("WORKFLOW_INSTANCE_TERMINATE_CAPABILITY_INVALID")}if(s==="withdraw"||a.beforeFact!==void 0){let c=a.beforeFact,_=Ce(e.inputSchema),p=Ce(Ce(_?.properties)?.[c]),d=Ce(Ce(e.subject)?.factProjection)?.[c],u=t?.fields.get(d);(typeof c!="string"||!/^[A-Za-z][A-Za-z0-9_]{0,62}$/.test(c)||!Array.isArray(_?.required)||!_.required.includes(c)||p?.type!=="string"||p?.format!=="date-time"||typeof d!="string"||t&&(u?.type!=="datetime"||u.nullable===!0))&&n.push(`WORKFLOW_INSTANCE_COMMAND_DEADLINE_FACT_INVALID:${s}`)}}return n}function pr(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 On(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,s,r,a,i]=t,c=t[8],_=new Date(Date.UTC(Number(o),Number(n),0)).getUTCDate();if(Number(n)<1||Number(n)>12||Number(s)<1||Number(s)>_||Number(r)>23||Number(a)>59||Number(i)>59||c!=="Z"&&(Number(c.slice(1,3))>23||Number(c.slice(4))>59))return null;let p=Date.parse(e);return Number.isFinite(p)?p:null}function Er(e,t,o,n){let s=e?.[t];if(!s||t==="terminate"&&s.beforeFact===void 0)return null;let r=s.beforeFact,a=Ce(o),i=r&&a&&Object.hasOwn(a,r)?On(a[r]):null,c=n instanceof Date?n.getTime():On(n);return i===null||c===null||!Number.isFinite(c)?"WORKFLOW_V2_CANCELLATION_DEADLINE_INVALID":c<i?null:"WORKFLOW_V2_CANCELLATION_DEADLINE_PASSED"}import*as nt from"crypto";var $n="native-4",hn={"application-native-2":"1.0.0","authz.native-batch-explain":"1.0.0","authz.native-management":"1.0.0","deployment.durable-runs":"1.0.0","deployment.platform-executor":"1.0.0","environment.on-demand-production":"1.0.0","environment.runtime-lifecycle":"1.0.0","data-api-v2":"1.1.0","data.native-golden-crud":"1.0.0","data.audit-read-access":"1.0.0","data.managed-files":"1.1.0","data.decimal-reservations":"1.1.0","data.decimal-reservation-lifecycle":"1.0.0","workflow.named-input-sources":"1.0.0","directory-v2":"1.0.0","events-v2":"1.0.0","events.durable-receipts":"1.0.0","events.capture-policy":"1.0.0","events.native-data-actions":"1.0.0","workflow-kernel-v2":"1.0.0","workflow.instance-cancellation-policy":"1.0.0","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 mr=5,Tr=20,Nr=50,gr=50,Cr=100,Ue=class extends Error{constructor(o,n){super(o);this.code=o;this.pointer=n;this.name="NativeDataPolicyExpressionV2Error"}code;pointer};function Ze(e,t){let o=[],n=(s,r,a)=>{a>5&&xe("NATIVE_DATA_POLICY_EXPRESSION_DEPTH_EXCEEDED",r);let i=Dn(s,r),c=["allOf","anyOf"].filter(d=>d in i);if(c.length===0){o.push({rule:i,pointer:r}),o.length>50&&xe("NATIVE_DATA_POLICY_EXPRESSION_LEAVES_EXCEEDED",r);return}let _=c[0],p=i[_];(c.length!==1||Object.keys(i).length!==1||!Array.isArray(p)||p.length<1||p.length>20)&&xe("NATIVE_DATA_POLICY_EXPRESSION_GROUP_INVALID",r),p.forEach((d,u)=>n(d,`${r}/${_}/${u}`,a+1))};return n(e,t,1),o}function Sn(e,t){Ze(e,t);let o=(n,s)=>{let r=Dn(n,s);if(Array.isArray(r.allOf))return Vt(r.allOf.flatMap((a,i)=>o(a,`${s}/allOf/${i}`)),s);if(Array.isArray(r.anyOf)){let a=[[]];return r.anyOf.forEach((i,c)=>{let _=o(i,`${s}/anyOf/${c}`);a=Vt(a.flatMap(p=>_.map(d=>[...p,...d])),s)}),a}return[[r]]};return Vt(o(e,t),t)}function Vt(e,t){let o=e.reduce((n,s)=>n+s.length,0);return(e.length>50||o>100)&&xe("NATIVE_DATA_POLICY_EXPRESSION_EXPANSION_EXCEEDED",t),e}function Dn(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&xe("NATIVE_DATA_POLICY_EXPRESSION_NODE_INVALID",t),e}function xe(e,t){throw new Ue(e,t)}var cs="openxiangda.config-bundle/v3",Yn="openxiangda.contract-bundle/v3",yn="openxiangda.native-configuration-projection/v1",je=$n,ds=/^[a-f0-9]{64}$/,ls=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,us=/^app:[a-z][a-z0-9]*(?:-[a-z0-9]+)*:[A-Za-z0-9:._*-]+$/,fs=/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/,_s=/^[a-z][a-z0-9]*(?:[-.][a-z0-9]+)*$/,ps=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,Es=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,Vn=/^[A-Za-z][A-Za-z0-9_]{0,127}$/,As=/^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*$/,Is=/^[A-Z][A-Z0-9_]*$/,ms=/^[a-z][a-z0-9-]{2,63}$/,Ts=/^[A-Za-z][A-Za-z0-9_-]{0,127}$/,Ns=/^[A-Za-z][A-Za-z0-9_.]{0,127}$/,gs=16,Cs=2*1024,bs=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"]),Os=new Set(["overview","database","operations","workflow","members","calendar","document","folder","settings"]),Rs=new Set(["approve","reject","return","transfer","delegate","add_assignee","resubmit","withdraw","terminate","admin_reassign","admin_override","retry_resolution"]),$s=4*1024*1024,hs=8*1024*1024,Ss=40,Ds=1e5,Ft=1024*1024,ys="openxiangda.event-handler-manifest/v2",qn="openxiangda.application-route-manifest/v3",wn=64,Kn=new Set(["id","revision","created_by","updated_by","created_at","updated_at"]),q=Object.freeze({perspectives:100,resources:100,subjectReadSurfaces:50,capabilities:2e3,operations:500,eventConsumers:100,eventProducers:1e3,eventSchemas:100,eventTypes:500,workflows:100,routes:500,adminPages:500,adminNavigationGroups:100,adminNavigationItems:500}),Pt=["openxiangda.data.record.created.v2","openxiangda.data.record.updated.v2","openxiangda.data.record.deleted.v2"],vt=["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"],Vs=new Set(vt),Lt=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(([s,r])=>[s,String(r).slice(0,128)]))}};function Ur(e){let t=h(e.appCode,"/appCode",128);ls.test(t)||f("NATIVE_CONFIG_APP_CODE_INVALID","/appCode");let o=xt(e.expectedConfigDigest,"/expectedConfigDigest"),n=xt(e.expectedContractDigest,"/expectedContractDigest"),s=Wn(e.configBytes,$s,"/configBytes","NATIVE_CONFIG_ARTIFACT_TOO_LARGE"),r=Wn(e.contractBytes,hs,"/contractBytes","NATIVE_CONTRACT_ARTIFACT_TOO_LARGE");Gn(s,o,"/configBytes","NATIVE_CONFIG_DIGEST_MISMATCH"),Gn(r,n,"/contractBytes","NATIVE_CONTRACT_DIGEST_MISMATCH");let a=Bn(s,"/configBytes","NATIVE_CONFIG_JSON_INVALID","NATIVE_CONFIG_NOT_CANONICAL"),i=Bn(r,"/contractBytes","NATIVE_CONTRACT_JSON_INVALID","NATIVE_CONTRACT_NOT_CANONICAL");Jn(a,"/config"),Jn(i,"/contracts");let c=a,_=i;vs(c,t),Ls(_,t,o);let p=ks(c,o,_.generatorVersion);bi(p,_,c),Q(p)!==Q(_)&&f("NATIVE_CONTRACT_CLOSURE_MISMATCH",Ut(p,_,"/contracts"));let d={authz:{appCode:t,...c.authz,perspectives:c.perspectives,capabilityCatalog:p.capabilities},data:{appCode:t,resources:c.data.resources,resourceContracts:p.resources,...p.subjectReadSurfaces?{subjectReadSurfaces:p.subjectReadSurfaces}:{}},events:{appCode:t,...c.events,consumers:p.eventConsumers,producers:p.eventProducers,handlerManifest:p.eventHandlerManifest,eventTypes:p.eventTypes,capturePlans:Fs({resources:c.data.resources,dataPolicies:c.authz.dataPolicies,subscriptions:p.eventConsumers,capturePolicies:c.events.capturePolicies})},workflows:{appCode:t,...c.workflows,contracts:p.workflows},runtime:{appCode:t,requirements:c.runtime,backend:c.backend,frontend:c.frontend},contracts:p},u={authz:ye(d.authz),data:ye(d.data),events:ye(d.events),workflows:ye(d.workflows),runtime:ye(d.runtime),contracts:ye(d.contracts)},E={configDigest:o,contractDigest:n,generatorVersion:_.generatorVersion},l=ws(c),A={schemaVersion:yn,compilerContractVersion:je,appCode:t,source:E,projections:u,requiredPlatformCapabilities:l,aggregateDigest:ee({schemaVersion:yn,compilerContractVersion:je,appCode:t,source:E,requiredPlatformCapabilities:l,projectionDigests:Object.fromEntries(Object.entries(u).map(([T,m])=>[T,m.digest]))})};return ao(A)}function ws(e){let t=e.authz.roles,o=e.data.resources,n=e.backend.operations,s=t.some(l=>l.capabilities.some(A=>A.endsWith(":directory:read")))||o.some(l=>l.schema.fields.some(A=>["user.single","user.multiple","department.single","department.multiple"].includes(A.type)))||n.some(l=>l.platformAccess?.directory),r=!!(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),i=n.some(l=>l.platformAccess?.notification)||e.events.subscriptions.some(l=>l.platformAccess?.notification),c=e.workflows.definitions.filter(l=>l.launch.mode==="standalone"||l.launch.mode==="hidden-handoff"),_=n.some(l=>l.platformAccess?.workflow)||c.length>0,p={resources:o},d={perspectives:e.perspectives,authz:e.authz},u={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.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?.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:u},{code:"authz.native-batch-explain",declaration:d},{code:"authz.native-management",declaration:d},{code:"deployment.durable-runs",declaration:u.backend},{code:"deployment.platform-executor",declaration:u.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:p},{code:"data.native-golden-crud",declaration:p}]:[],...o.some(Qt)?[{code:"data.audit-read-access",declaration:p}]:[],...s?[{code:"directory-v2",declaration:{roles:t.map(l=>({code:l.code,capabilities:l.capabilities.filter(A=>A.endsWith(":directory:read"))})),resources:o.map(l=>({code:l.code,fields:l.schema.fields.filter(A=>["user.single","user.multiple","department.single","department.multiple"].includes(A.type))})),operations:n.filter(l=>l.platformAccess?.directory).map(l=>({code:l.code,directory:l.platformAccess.directory}))}}]:[],...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}]:[],...r?[{code:"events-v2",declaration:e.events},{code:"events.durable-receipts",declaration:e.events}]:[],...e.workflows.activations.length?[{code:"workflow-kernel-v2",declaration:e.workflows},{code:"workflow.fresh-command-token",declaration:e.workflows}]:[],...e.workflows.definitions.some(l=>l.definition.instanceCommands!==void 0)?[{code:"workflow.instance-cancellation-policy",declaration:e.workflows.definitions.filter(l=>l.definition.instanceCommands!==void 0)}]:[],..._?[{code:"business-process.durable-command",declaration:{operations:n.filter(l=>l.platformAccess?.workflow).map(l=>({code:l.code,workflow:l.platformAccess.workflow})),definitions:c,activations:e.workflows.activations.filter(l=>c.some(A=>A.definition.code===l.workflowCode))}}]:[],...i?[{code:"notification-hub-v2",declaration:{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:A})=>({code:l,contractVersion:hn[l],usageDigest:`sha256:${ee(A)}`})).sort((l,A)=>l.code===A.code?0:l.code<A.code?-1:1)}function Fs(e){let t=new Map,o=new Set(e.resources.map(r=>String(r.code)));for(let[r,a]of $(e.capturePolicies===void 0?[]:e.capturePolicies,"/capturePlan/capturePolicies",100).entries()){let i=`/capturePlan/capturePolicies/${r}`,c=I(a,i);O(c,["resourceCode","mode"],i);let _=G(c.resourceCode,`${i}/resourceCode`);o.has(_)||f("NATIVE_EVENT_CAPTURE_RESOURCE_NOT_FOUND",i,{resourceCode:_}),t.has(_)&&f("NATIVE_EVENT_CAPTURE_POLICY_DUPLICATE",i,{resourceCode:_}),c.mode!=="all"&&c.mode!=="subscribed"&&f("NATIVE_EVENT_CAPTURE_MODE_INVALID",`${i}/mode`),t.set(_,c.mode)}let n=new Map(e.dataPolicies.map((r,a)=>{let i=I(r,`/capturePlan/dataPolicies/${a}`);return[String(i.code),i]})),s=e.subscriptions.map((r,a)=>I(r,`/capturePlan/subscriptions/${a}`));return e.resources.map((r,a)=>{let i=`/capturePlan/resources/${a}`,c=I(r,i),_=G(c.code,`${i}/code`),p=c.schema?I(c.schema,`${i}/schema`):c,d=new Set($(p.fields||[],`${i}/schema/fields`,500).map((C,D)=>B(I(C,`${i}/schema/fields/${D}`).code,`${i}/schema/fields/${D}/code`))),u=c.dataPolicyCode?w(c.dataPolicyCode,`${i}/dataPolicyCode`):null,E=u?n.get(u):void 0;u&&!E&&f("NATIVE_EVENT_CAPTURE_AUTHZ_POLICY_NOT_FOUND",i,{resourceCode:_,dataPolicyCode:u});let l=new Set;for(let C of E?.rules||[])l.add(String(C.field));if(E?.readExpression)for(let C of Ze(E.readExpression,`${i}/readExpression`))l.add(String(C.rule.field));let A=new Set,T=new Set,m=new Set;for(let[C,D]of s.entries()){let y=$(D.eventTypes,`/capturePlan/subscriptions/${C}/eventTypes`,20).map(String);if(!y.some(M=>M.startsWith("openxiangda.data.")))continue;let U=I(D.filter||{},`/capturePlan/subscriptions/${C}/filter`),k=Array.isArray(U.resourceCodes)?U.resourceCodes.map(String):[];if(k.length&&!k.includes(_))continue;for(let M of y)Pt.includes(M)&&m.add(M);for(let M of Ps(U,`/capturePlan/subscriptions/${C}/filter`))A.add(M);let Y=I(D.payload||{},`/capturePlan/subscriptions/${C}/payload`);for(let M of $(Y.fields||[],`/capturePlan/subscriptions/${C}/payload/fields`,32))T.add(B(M,`/capturePlan/subscriptions/${C}/payload/fields`))}let N=new Set([...A,...T]),b=new Set([...N,...l]);b.size>wn&&f("NATIVE_EVENT_CAPTURE_FIELDS_LIMIT",i,{resourceCode:_,maximum:wn});for(let C of b)!d.has(C)&&!(l.has(C)&&Kn.has(C))&&f("NATIVE_EVENT_CAPTURE_FIELD_NOT_FOUND",i,{resourceCode:_,field:C});let R=I(c.fieldPolicies||{},`${i}/fieldPolicies`);for(let C of N)R[C]?.mask==="omit"&&f("NATIVE_EVENT_CAPTURE_FIELD_SENSITIVE",i,{resourceCode:_,field:C});let g={resourceCode:_,...t.get(_)==="subscribed"?{capturedEventTypes:[...m].sort()}:{},filterFields:[...A].sort(),projectionFields:[...T].sort(),authorizationFields:[...l].sort(),captureFields:[...b].sort()};return{...g,digest:ee(g)}}).sort((r,a)=>r.resourceCode.localeCompare(a.resourceCode))}function Ps(e,t){let o=new Set;for(let[a,i]of $(e.changes||[],`${t}/changes`,16).entries()){let c=I(i,`${t}/changes/${a}`);o.add(B(c.field,`${t}/changes/${a}/field`))}let n=I(e.changedFields||{},`${t}/changedFields`);for(let a of["anyOf","allOf","noneOf"])for(let[i,c]of $(n[a]||[],`${t}/changedFields/${a}`,32).entries())o.add(B(c,`${t}/changedFields/${a}/${i}`));let s=0,r=(a,i,c)=>{c>3&&f("NATIVE_EVENT_FILTER_DEPTH_LIMIT",i);let _=I(a,i);if(_.change){let d=I(_.change,`${i}/change`);o.add(B(d.field,`${i}/change/field`)),s+=1;return}if(_.not){r(_.not,`${i}/not`,c+1);return}let p=_.all?"all":_.any?"any":null;p||f("NATIVE_EVENT_FILTER_CONDITION_INVALID",i);for(let[d,u]of $(_[p],`${i}/${p}`,16).entries())r(u,`${i}/${p}/${d}`,c+1)};return e.where&&r(e.where,`${t}/where`,1),s+=Array.isArray(e.changes)?e.changes.length:0,s>16&&f("NATIVE_EVENT_FILTER_ATOM_LIMIT",t),[...o].sort()}function vs(e,t){O(e,["schemaVersion","compilerContractVersion","appCode","perspectives","authz","backend","data","events","workflows","frontend","runtime"],"/config"),L(e.schemaVersion,cs,"/config/schemaVersion"),L(e.compilerContractVersion,je,"/config/compilerContractVersion"),L(e.appCode,t,"/config/appCode"),$(e.perspectives,"/config/perspectives",100);let o=I(e.authz,"/config/authz");O(o,["capabilities","roles","scopeDimensions","scopeSources","roleMembershipSources","relationshipGrantSources","dataPolicies","authorizationTransitions"],"/config/authz",["authenticatedUserRoleCode"]),$(o.capabilities,"/config/authz/capabilities",2e3),$(o.roles,"/config/authz/roles",100),$(o.scopeDimensions,"/config/authz/scopeDimensions",100),$(o.scopeSources,"/config/authz/scopeSources",100),$(o.roleMembershipSources,"/config/authz/roleMembershipSources",100),$(o.relationshipGrantSources,"/config/authz/relationshipGrantSources",100),$(o.dataPolicies,"/config/authz/dataPolicies",100),$(o.authorizationTransitions,"/config/authz/authorizationTransitions",100);let n=I(e.backend,"/config/backend");O(n,["secrets","operations"],"/config/backend"),$(n.secrets,"/config/backend/secrets",100),$(n.operations,"/config/backend/operations",500),Ii(n.secrets);let s=I(e.data,"/config/data");O(s,["resources"],"/config/data",["resourceDetailRoutes","subjectReadSurfaces"]),$(s.resources,"/config/data/resources",100),s.subjectReadSurfaces!==void 0&&$(s.subjectReadSurfaces,"/config/data/subjectReadSurfaces",q.subjectReadSurfaces),s.resourceDetailRoutes!==void 0&&$(s.resourceDetailRoutes,"/config/data/resourceDetailRoutes",100);let r=I(e.events,"/config/events");O(r,["schemas","subscriptions","timers","dateTriggers"],"/config/events",["capturePolicies"]),$(r.schemas,"/config/events/schemas",100),$(r.subscriptions,"/config/events/subscriptions",100),$(r.timers,"/config/events/timers",100),$(r.dateTriggers,"/config/events/dateTriggers",100);let a=I(e.workflows,"/config/workflows");O(a,["definitions","bindings","activations","providers","editableParameters"],"/config/workflows"),$(a.definitions,"/config/workflows/definitions",100),$(a.bindings,"/config/workflows/bindings",100),$(a.activations,"/config/workflows/activations",100),$(a.providers,"/config/workflows/providers",100),$(a.editableParameters,"/config/workflows/editableParameters",100);let i=I(e.frontend,"/config/frontend");O(i,["routes","user","admin","devicePolicy"],"/config/frontend",["authentication","publicAccess"]),$(i.routes,"/config/frontend/routes",500);let c=I(i.user,"/config/frontend/user");O(c,["applicationTodoCenter"],"/config/frontend/user"),we(c.applicationTodoCenter,"/config/frontend/user/applicationTodoCenter"),Mt(i.devicePolicy,"/config/frontend/devicePolicy"),Object.prototype.hasOwnProperty.call(i,"authentication")&&Xn(i.authentication,i.routes,e,"/config/frontend/authentication"),Object.prototype.hasOwnProperty.call(i,"publicAccess")&&Qs(i.publicAccess,e,"/config/frontend/publicAccess");let _=I(i.admin,"/config/frontend/admin");O(_,["navigation"],"/config/frontend/admin",["access"]),_.access!==void 0&&st(_.access,"/config/frontend/admin/access",e.appCode),ni(_.navigation,"/config/frontend/admin/navigation");let p=I(e.runtime,"/config/runtime");O(p,["protocolCapabilities","health"],"/config/runtime"),F(p.protocolCapabilities,"/config/runtime/protocolCapabilities",100),O(I(p.health,"/config/runtime/health"),["livePath","readyPath","versionPath"],"/config/runtime/health"),L(p.health.livePath,"/__platform/health","/config/runtime/health/livePath"),L(p.health.readyPath,"/__platform/ready","/config/runtime/health/readyPath"),L(p.health.versionPath,"/__platform/version","/config/runtime/health/versionPath")}function Ls(e,t,o){O(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"]),L(e.schemaVersion,Yn,"/contracts/schemaVersion"),L(e.compilerContractVersion,je,"/contracts/compilerContractVersion"),h(e.generatorVersion,"/contracts/generatorVersion",128),L(e.appCode,t,"/contracts/appCode"),L(e.configDigest,o,"/contracts/configDigest"),$(e.perspectives,"/contracts/perspectives",q.perspectives),$(e.resources,"/contracts/resources",q.resources),e.subjectReadSurfaces!==void 0&&$(e.subjectReadSurfaces,"/contracts/subjectReadSurfaces",q.subjectReadSurfaces),$(e.capabilities,"/contracts/capabilities",q.capabilities),$(e.operations,"/contracts/operations",q.operations),$(e.eventConsumers,"/contracts/eventConsumers",q.eventConsumers),$(e.eventProducers,"/contracts/eventProducers",q.eventProducers),$(e.eventSchemas,"/contracts/eventSchemas",q.eventSchemas),I(e.eventHandlerManifest,"/contracts/eventHandlerManifest"),F(e.eventTypes,"/contracts/eventTypes",q.eventTypes),$(e.workflows,"/contracts/workflows",q.workflows),$(e.routes,"/contracts/routes",q.routes),Object.prototype.hasOwnProperty.call(e,"authentication")&&Ks(e.authentication,"/contracts/authentication"),Object.prototype.hasOwnProperty.call(e,"publicAccess")&&Zs(e.publicAccess,"/contracts/publicAccess"),Object.prototype.hasOwnProperty.call(e,"adminAccess")&&st(e.adminAccess,"/contracts/adminAccess",t),ci(e.routeManifest,"/contracts/routeManifest",t),ii(e.adminPages,"/contracts/adminPages"),ri(e.adminNavigation,"/contracts/adminNavigation")}function ks(e,t,o){let n=Ms(e);_i(e,n),Ei(e),pi(e),mi(e);let s=e.events.schemas.map((l,A)=>{let T=`/config/events/schemas/${A}`,m=I(l,T),N=h(m.eventType,`${T}/eventType`,255);return N.startsWith("openxiangda.")&&f("NATIVE_EVENT_SCHEMA_RESERVED",`${T}/eventType`,{eventType:N}),L(m.schemaDigest,ee(I(m.jsonSchema,`${T}/jsonSchema`)),`${T}/schemaDigest`),m}),r=new Set([...Pt,...vt,...s.map(l=>String(l.eventType))]),a=new Map(e.data.resources.map(l=>[String(l.code),new Map(l.schema.fields.map(A=>[String(A.code),String(A.type)]))])),i=X(e.events.subscriptions.map((l,A)=>{let T=`/config/events/subscriptions/${A}`,m=I(l,T),N=F(m.eventTypes,`${T}/eventTypes`,20);N.forEach((C,D)=>{r.has(C)||f("NATIVE_EVENT_TYPE_NOT_REGISTERED",`${T}/eventTypes/${D}`,{eventType:C})});let b=bn(m,e.data.resources,T),R=Us(m.delivery,N,`${T}/delivery`),g=xs(m.platformAccess,`${T}/platformAccess`,a,e,m);return{code:w(m.code,`${T}/code`),endpointPath:de(m.endpointPath,`${T}/endpointPath`),eventTypes:N,filter:I(m.filter,`${T}/filter`),payload:b?.payload||I(m.payload,`${T}/payload`),...b?{execution:b.execution}:{},...g?{platformAccess:g}:{},delivery:R}}),l=>l.code),c=new Map(s.map(l=>[String(l.eventType),String(l.dataSchemaVersion)])),_=X([...e.data.resources.flatMap(l=>Pt.map(A=>({code:`data:${l.code}:${A}`,source:"data",eventType:A,dataSchemaVersion:"2.0.0",resourceCode:l.code}))),...s.map(l=>({code:`app:${l.eventType}`,source:"app",eventType:l.eventType,dataSchemaVersion:l.dataSchemaVersion})),...e.events.timers.map(l=>({code:l.code,source:"timer",eventType:l.eventType,dataSchemaVersion:c.get(String(l.eventType))||"2.0.0"})),...e.events.dateTriggers.map(l=>({code:l.code,source:"date",eventType:l.eventType,dataSchemaVersion:c.get(String(l.eventType))||"2.0.0",resourceCode:l.resourceCode,field:l.field})),...e.workflows.activations.length?vt.map(l=>({code:`workflow:${l}`,source:"workflow",eventType:l,dataSchemaVersion:"2.0.0"})):[]],l=>`${l.source}:${l.code}:${l.eventType}`),p=j([...i.flatMap(l=>l.eventTypes),..._.map(l=>String(l.eventType))]);si(e);let d=eo(e),u=Bs(e,n),E=Hn(e);try{fn(e.data.resources,E)}catch(l){throw l instanceof De&&f(l.code,l.pointer,{reason:l.reason}),l}return{schemaVersion:Yn,compilerContractVersion:je,generatorVersion:o,appCode:e.appCode,configDigest:t,perspectives:e.perspectives,resources:js(e),...u.length?{subjectReadSurfaces:u}:{},capabilities:X(n,l=>l.code),operations:E,eventConsumers:i,eventProducers:_,eventSchemas:s,eventHandlerManifest:{schemaVersion:ys,appCode:e.appCode,handlers:i.filter(l=>!l.execution).map(l=>({code:l.code,endpointPath:l.endpointPath,eventTypes:l.eventTypes,dataSchemaVersions:j(l.eventTypes.map(A=>A.startsWith("openxiangda.")?"2.0.0":c.get(A)||"2.0.0")),maxBodyBytes:65536,receiptProtocolVersion:2}))},eventTypes:p,workflows:oo(e),routes:ot(e),...Object.prototype.hasOwnProperty.call(e.frontend,"authentication")?{authentication:Hs(e)}:{},...Object.prototype.hasOwnProperty.call(e.frontend,"publicAccess")?{publicAccess:ei(e)}:{},...e.frontend.admin.access?{adminAccess:e.frontend.admin.access}:{},routeManifest:ui(e),adminPages:d,adminNavigation:ti(e)}}function xs(e,t,o,n,s){if(e===void 0)return;let r=I(e,t);O(r,["notification","managedFileCopies","decimalReservation"],t,!0);let a={};if(r.decimalReservation!==void 0)try{a.decimalReservation=gn(r.decimalReservation,Cn(n,s))}catch{f("NATIVE_EVENT_DECIMAL_RESERVATION_INVALID",`${t}/decimalReservation`)}if(r.notification!==void 0){let i=I(r.notification,`${t}/notification`);O(i,["mode"],`${t}/notification`),L(i.mode,"business-standard",`${t}/notification/mode`),a.notification={mode:"business-standard"}}if(r.managedFileCopies!==void 0){let i=$(r.managedFileCopies,`${t}/managedFileCopies`,16);i.length||f("NATIVE_EVENT_MANAGED_FILE_COPIES_REQUIRED",`${t}/managedFileCopies`);let c=new Set;a.managedFileCopies=X(i.map((_,p)=>{let d=`${t}/managedFileCopies/${p}`,u=I(_,d);O(u,["mode","sourceResourceCode","sourceFieldCodes","targetResourceCode","targetFieldCodes"],d),L(u.mode,"copy",`${d}/mode`);let E=G(u.sourceResourceCode,`${d}/sourceResourceCode`),l=G(u.targetResourceCode,`${d}/targetResourceCode`),A=o.get(E),T=o.get(l);(!A||!T)&&f("NATIVE_EVENT_MANAGED_FILE_COPY_RESOURCE_INVALID",d);let m=F(u.sourceFieldCodes,`${d}/sourceFieldCodes`,16),N=F(u.targetFieldCodes,`${d}/targetFieldCodes`,16);(!m.length||m.length!==N.length)&&f("NATIVE_EVENT_MANAGED_FILE_COPY_FIELDS_INVALID",d),m.forEach((R,g)=>{let C=A.get(R),D=T.get(N[g]);(!["file","image"].includes(String(C))||C!==D)&&f("NATIVE_EVENT_MANAGED_FILE_COPY_FIELD_INVALID",`${d}/sourceFieldCodes/${g}`)});let b=`${E}:${m.join(",")}=>${l}:${N.join(",")}`;return c.has(b)&&f("NATIVE_EVENT_MANAGED_FILE_COPY_DUPLICATE",d),c.add(b),{mode:"copy",sourceResourceCode:E,sourceFieldCodes:j(m),targetResourceCode:l,targetFieldCodes:j(N)}}),_=>`${_.sourceResourceCode}:${_.sourceFieldCodes.join(",")}=>${_.targetResourceCode}:${_.targetFieldCodes.join(",")}`)}return Object.keys(a).length||f("NATIVE_EVENT_PLATFORM_ACCESS_EMPTY",t),a}function Us(e,t,o){let n=I(e,o);O(n,["timeoutMs","maxAttempts","initialBackoffMs","maxBackoffMs","ordering","concurrency"],o),Z(n.timeoutMs,`${o}/timeoutMs`,1e3,3e4),Z(n.maxAttempts,`${o}/maxAttempts`,1,12);let s=Z(n.initialBackoffMs,`${o}/initialBackoffMs`,1e3,3e5);Z(n.maxBackoffMs,`${o}/maxBackoffMs`,s,18e5),Z(n.concurrency,`${o}/concurrency`,1,50);let r=h(n.ordering,`${o}/ordering`,32);return["none","record","workflow-instance"].includes(r)||f("NATIVE_EVENT_DELIVERY_ORDERING_INVALID",`${o}/ordering`),r==="workflow-instance"&&t.some(a=>!Vs.has(a))&&f("NATIVE_EVENT_WORKFLOW_ORDERING_REQUIRES_WORKFLOW_FACTS",`${o}/ordering`),n}function Ms(e){let t=new Map;for(let o of ro(e.appCode))t.set(o.code,o);for(let[o,n]of e.authz.capabilities.entries()){let s=`/config/authz/capabilities/${o}`,r=I(n,s);O(r,["code","kind","name","description"],s,!0);let a=Te(r.code,`${s}/code`,e.appCode);t.has(a)&&f("NATIVE_CAPABILITY_DUPLICATE",`${s}/code`),["backend","ui"].includes(r.kind)||f("NATIVE_CAPABILITY_KIND_INVALID",`${s}/kind`);let i={code:a,kind:r.kind,name:h(r.name,`${s}/name`,255),source:"explicit",...r.description===void 0?{}:{description:Bt(r.description,`${s}/description`,2e3)}};t.set(a,i)}for(let[o,n]of e.data.resources.entries()){let s=`/config/data/resources/${o}`,r=Oe(n,s,e.appCode),a={read:`\u8BFB\u53D6${r.name}`,create:`\u65B0\u5EFA${r.name}`,update:`\u66F4\u65B0${r.name}`,delete:`\u5220\u9664${r.name}`};for(let i of["read","create","update","delete"]){let c=Te(r.capabilities[i],`${s}/capabilities/${i}`,e.appCode);t.has(c)&&f("NATIVE_CAPABILITY_DUPLICATE",`${s}/capabilities/${i}`),t.set(c,{code:c,kind:"data",name:a[i],source:"data"})}for(let[i,c]of Object.entries(r.fieldPolicies)){if(Fe(i))continue;let _=I(c,`${s}/fieldPolicies/${i}`);for(let p of["read","create","update"])if(Array.isArray(_[p]))for(let d of F(_[p],`${s}/fieldPolicies/${i}/${p}`,2e3))Te(d,`${s}/fieldPolicies/${i}/${p}`,e.appCode),!t.has(d)&&t.set(d,{code:d,kind:"data",name:`${r.name}.${i}.${p}`,source:"data"})}}return[...t.values()]}function js(e){let t=Js(e);return X(e.data.resources.map((o,n)=>{let s=Oe(o,`/config/data/resources/${n}`,e.appCode),r=t.get(s.code);return{code:s.code,schemaDigest:ee(s.schema),fields:X(s.schema.fields.map(a=>({code:a.code,type:a.type})),a=>a.code),...r?{detailRouteCode:r}:{}}}),o=>o.code)}function Bs(e,t){if(e.data.subjectReadSurfaces===void 0)return[];let o=$(e.data.subjectReadSurfaces,"/config/data/subjectReadSurfaces",q.subjectReadSurfaces),n=new Set(t.map(a=>String(a.code))),s=new Map(e.data.resources.map((a,i)=>{let c=`/config/data/resources/${i}`,_=Oe(a,c,e.appCode);return[String(_.code),{resource:_,fields:new Map($(I(_.schema,`${c}/schema`).fields,`${c}/schema/fields`,500).map(p=>{let d=I(p,`${c}/schema/fields`);return[String(d.code),d]}))}]})),r=new Set;return X(o.map((a,i)=>{let c=`/config/data/subjectReadSurfaces/${i}`,_=I(a,c);O(_,["code","name","capability","subject","relations"],c);let p=w(_.code,`${c}/code`);r.has(p)&&f("NATIVE_SUBJECT_READ_SURFACE_CODE_DUPLICATE",`${c}/code`),r.add(p);let d=Te(_.capability,`${c}/capability`,e.appCode);n.has(d)||f("NATIVE_SUBJECT_READ_SURFACE_CAPABILITY_NOT_DECLARED",`${c}/capability`);let u=I(_.subject,`${c}/subject`);O(u,["resourceCode","fields"],`${c}/subject`);let E=G(u.resourceCode,`${c}/subject/resourceCode`),l=s.get(E);l||f("NATIVE_SUBJECT_READ_SURFACE_RESOURCE_NOT_DECLARED",`${c}/subject/resourceCode`);let A=F(u.fields,`${c}/subject/fields`,100).map((R,g)=>B(R,`${c}/subject/fields/${g}`));A.length||f("NATIVE_SUBJECT_READ_SURFACE_FIELDS_REQUIRED",`${c}/subject/fields`);for(let[R,g]of A.entries()){let C=l.fields.get(g);(!C||C.type==="subtable")&&f("NATIVE_SUBJECT_READ_SURFACE_FIELD_INVALID",`${c}/subject/fields/${R}`)}let T=$(_.relations,`${c}/relations`,8);T.length||f("NATIVE_SUBJECT_READ_SURFACE_RELATIONS_REQUIRED",`${c}/relations`);let m=new Set,N=0,b=X(T.map((R,g)=>{let C=`${c}/relations/${g}`,D=I(R,C);O(D,["code","resourceCode","foreignKeyField","fields","limit"],C,["order"]);let y=w(D.code,`${C}/code`);m.has(y)&&f("NATIVE_SUBJECT_READ_SURFACE_RELATION_CODE_DUPLICATE",`${C}/code`),m.add(y);let U=G(D.resourceCode,`${C}/resourceCode`),k=s.get(U);k||f("NATIVE_SUBJECT_READ_SURFACE_RESOURCE_NOT_DECLARED",`${C}/resourceCode`);let Y=B(D.foreignKeyField,`${C}/foreignKeyField`),M=k.fields.get(Y),le=I(M?.source||{},`${C}/foreignKeyField/source`);(!M||!["uuid","resource-ref.single"].includes(String(M.type))||M.type==="resource-ref.single"&&(le.kind!=="resource"||le.resourceCode!==E))&&f("NATIVE_SUBJECT_READ_SURFACE_RELATION_INVALID",`${C}/foreignKeyField`);let ue=F(D.fields,`${C}/fields`,100).map((se,V)=>B(se,`${C}/fields/${V}`));ue.length||f("NATIVE_SUBJECT_READ_SURFACE_FIELDS_REQUIRED",`${C}/fields`);for(let[se,V]of ue.entries()){let x=k.fields.get(V);(!x||x.type==="subtable")&&f("NATIVE_SUBJECT_READ_SURFACE_FIELD_INVALID",`${C}/fields/${se}`)}let K=$(D.order||[],`${C}/order`,10).map((se,V)=>{let x=`${C}/order/${V}`,P=I(se,x);O(P,["field","direction"],x);let J=B(P.field,`${x}/field`),W=k.fields.get(J);return(!Kn.has(J)&&!W||W?.type==="subtable"||W&&!ve(W.type))&&f("NATIVE_SUBJECT_READ_SURFACE_ORDER_FIELD_INVALID",`${x}/field`),["asc","desc"].includes(String(P.direction))||f("NATIVE_SUBJECT_READ_SURFACE_ORDER_DIRECTION_INVALID",`${x}/direction`),{field:J,direction:P.direction}}),Ae=Z(D.limit,`${C}/limit`,1,100);return N+=Ae,{code:y,resourceCode:U,foreignKeyField:Y,fields:j(ue),...K.length?{order:K}:{},limit:Ae}}),R=>R.code);return N>400&&f("NATIVE_SUBJECT_READ_SURFACE_ROW_LIMIT_EXCEEDED",`${c}/relations`),{code:p,name:h(_.name,`${c}/name`,255),capability:d,subject:{resourceCode:E,fields:j(A)},relations:b}}),a=>a.code)}function Js(e){let t=e.data.resourceDetailRoutes===void 0?[]:$(e.data.resourceDetailRoutes,"/config/data/resourceDetailRoutes",100),o=new Map(e.data.resources.map((r,a)=>{let i=`/config/data/resources/${a}`,c=Oe(r,i,e.appCode);return[c.code,c]})),n=new Map(ot(e).map(r=>[String(r.code),r])),s=new Map;for(let[r,a]of t.entries()){let i=`/config/data/resourceDetailRoutes/${r}`,c=I(a,i);O(c,["resourceCode","desktop","mobile"],i);let _=G(c.resourceCode,`${i}/resourceCode`);s.has(_)&&f("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_DUPLICATE",`${i}/resourceCode`);let p=o.get(_);p||f("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_RESOURCE_MISSING",`${i}/resourceCode`);let d=w(c.desktop,`${i}/desktop`),u=w(c.mobile,`${i}/mobile`);d===u&&f("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_INVALID",i);let E=String(p.capabilities.read);for(let[l,A]of[["desktop",d],["mobile",u]]){let T=`${i}/${l}`,m=n.get(A);m||f("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_REFERENCE_MISSING",T),m.surface!=="user"&&f("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_SURFACE_INVALID",T);let N=de(m.path,`${T}/path`),b=[...N.matchAll(/:([A-Za-z][A-Za-z0-9_]*)/g)],R=l==="mobile"?!N.startsWith("/m/"):N==="/m"||N.startsWith("/m/");(N.includes("*")||N.includes("?")||N.includes("#")||N.split("/").includes("..")||b.length!==1||R)&&f("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_PATH_INVALID",T);let g=Array.isArray(m.access?.allOf)?m.access.allOf:[];m.capability!==E&&!g.includes(E)&&f("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_CAPABILITY_INVALID",T)}s.set(_,{desktop:d,mobile:u})}return s}function Hn(e){let t=new Map(e.data.resources.map((a,i)=>{let c=`/config/data/resources/${i}`,_=Oe(a,c,e.appCode);return[_.code,new Map(_.schema.fields.map(p=>[String(p.code),p]))]})),o=new Map(e.data.resources.map((a,i)=>{let c=`/config/data/resources/${i}`,_=Oe(a,c,e.appCode);return[_.code,new Map(_.schema.fields.map(p=>[String(p.code),String(p.type)]))]})),n=new Set(o.keys()),s=new Set(e.workflows.activations.map((a,i)=>it(I(a,`/config/workflows/activations/${i}`).workflowCode,`/config/workflows/activations/${i}/workflowCode`))),r=new Map;return X(e.backend.operations.map((a,i)=>{let c=`/config/backend/operations/${i}`,_=I(a,c);O(_,["code","method","path","capability","requestSchema","responseSchema","description","platformAccess","browser","ai"],c,!0);let p=h(_.method,`${c}/method`,16);["GET","POST","PUT","PATCH","DELETE"].includes(p)||f("NATIVE_OPERATION_METHOD_INVALID",`${c}/method`);let d=w(_.code,`${c}/code`);Ys(_.ai,c,d,p,n);let u=zs(_.platformAccess,`${c}/platformAccess`,o,t,s,new Set(e.authz.roles.map(l=>String(l.code))));if(u?.decimalReservation){let l=u.decimalReservation,A=String(l.resourceCode),T=JSON.stringify([l.amountFieldCode,l.currencyFieldCode,l.relationFieldCode,l.parentFieldCode,l.rootFieldCode,l.statusFieldCode,l.parentRelationValue,l.childRelationValue]),m=r.get(A);m&&m!==T&&f("NATIVE_DECIMAL_RESERVATION_MAPPING_CONFLICT",`${c}/platformAccess/decimalReservation`),r.set(A,T)}let E=Ws(_.browser,`${c}/browser`,p,_.requestSchema,_.responseSchema,o,t,e.data.subjectReadSurfaces||[]);return{code:d,method:p,path:de(_.path,`${c}/path`),requiredCapability:Te(_.capability,`${c}/capability`,e.appCode),requestSchemaDigest:ee(I(_.requestSchema,`${c}/requestSchema`)),responseSchemaDigest:ee(I(_.responseSchema,`${c}/responseSchema`)),..._.description===void 0?{}:{description:Bt(_.description,`${c}/description`,2e3)},...u?{platformAccess:u}:{},...E?{browser:E}:{}}}),a=>a.code)}function Ws(e,t,o,n,s,r,a,i){if(e===void 0)return null;let c=I(e,t);O(c,["exposure","behavior","idempotency","subject"],t,["refreshTargets","fileIntent"]),L(c.exposure,"authenticated",`${t}/exposure`);let _=h(c.behavior,`${t}/behavior`,32);["read","controlled"].includes(_)||f("NATIVE_OPERATION_BROWSER_BEHAVIOR_INVALID",`${t}/behavior`);let p=h(c.idempotency,`${t}/idempotency`,32);(!["none","required"].includes(p)||_==="controlled"&&p!=="required"||_==="read"&&p!=="none")&&f("NATIVE_OPERATION_BROWSER_IDEMPOTENCY_INVALID",`${t}/idempotency`);let d=I(c.subject,`${t}/subject`);O(d,["resourceCode","inputField"],`${t}/subject`);let u=G(d.resourceCode,`${t}/subject/resourceCode`);r.has(u)||f("NATIVE_OPERATION_BROWSER_SUBJECT_RESOURCE_NOT_DECLARED",`${t}/subject/resourceCode`);let E=B(d.inputField,`${t}/subject/inputField`),l=I(n,`${t}/requestSchema`),A=I(s,`${t}/responseSchema`);(l.type!=="object"||l.additionalProperties!==!1||A.type!=="object"||A.additionalProperties!==!1)&&f("NATIVE_OPERATION_BROWSER_SCHEMA_ROOT_INVALID",`${t}/requestSchema`);let T=I(l.properties,`${t}/requestSchema/properties`),m=new Set(l.required===void 0?[]:F(l.required,`${t}/requestSchema/required`,200));(!(E in T)||!m.has(E))&&f("NATIVE_OPERATION_BROWSER_SUBJECT_INPUT_INVALID",`${t}/subject/inputField`);let N=I(T[E],`${t}/requestSchema/properties/${E}`);(N.type!=="string"||N.format!=="uuid")&&f("NATIVE_OPERATION_BROWSER_SUBJECT_INPUT_INVALID",`${t}/subject/inputField`);let b=new Map((Array.isArray(i)?i:[]).map((y,U)=>{let k=I(y,`/config/data/subjectReadSurfaces/${U}`);return[String(k.code),String(I(k.subject,`/config/data/subjectReadSurfaces/${U}/subject`).resourceCode)]})),R=c.refreshTargets===void 0?[]:$(c.refreshTargets,`${t}/refreshTargets`,16),g=new Set,C=X(R.map((y,U)=>{let k=`${t}/refreshTargets/${U}`,Y=I(y,k);O(Y,["kind","code"],k),L(Y.kind,"subject-surface",`${k}/kind`);let M=w(Y.code,`${k}/code`);return(g.has(M)||!b.has(M)||b.get(M)!==u)&&f("NATIVE_OPERATION_BROWSER_REFRESH_TARGET_INVALID",`${k}/code`),g.add(M),{kind:"subject-surface",code:M}}),y=>`${y.kind}:${y.code}`),D=Gs(c.fileIntent,`${t}/fileIntent`,o,_,p,u,T,m,a);return{exposure:"authenticated",behavior:_,idempotency:p,subject:{resourceCode:u,inputField:E},...C.length?{refreshTargets:C}:{},...D?{fileIntent:D}:{}}}function Gs(e,t,o,n,s,r,a,i,c){if(e===void 0)return null;let _=I(e,t);O(_,["recordResourceCode","recordIdInputField","relationField","fileNameField","contentTypeField","sizeField","purposes","maxTtlSeconds","maxBytes"],t),(o!=="GET"||n!=="read"||s!=="none")&&f("NATIVE_OPERATION_FILE_INTENT_BEHAVIOR_INVALID",t);let p=G(_.recordResourceCode,`${t}/recordResourceCode`),d=c.get(p);d||f("NATIVE_OPERATION_FILE_INTENT_RESOURCE_NOT_DECLARED",`${t}/recordResourceCode`);let u=B(_.recordIdInputField,`${t}/recordIdInputField`),E=I(a[u],`${t}/recordIdInputField`);(!i.has(u)||E.type!=="string"||E.format!=="uuid")&&f("NATIVE_OPERATION_FILE_INTENT_RECORD_INPUT_INVALID",`${t}/recordIdInputField`);let l=B(_.relationField,`${t}/relationField`),A=d.get(l);(!A||!["uuid","resource-ref.single"].includes(String(A.type))||String(A.type)==="resource-ref.single"&&(String(I(A.source,`${t}/relationField`).kind||"")!=="resource"||String(I(A.source,`${t}/relationField`).resourceCode||"")!==r))&&f("NATIVE_OPERATION_FILE_INTENT_RELATION_INVALID",`${t}/relationField`);let T=[["fileNameField",["text.short","text.long"]],["contentTypeField",["text.short","text.long"]],["sizeField",["number.integer"]]],m={};for(let[g,C]of T){let D=B(_[g],`${t}/${g}`);C.includes(String(d.get(D)?.type))||f("NATIVE_OPERATION_FILE_INTENT_METADATA_INVALID",`${t}/${g}`),m[g]=D}let N=X(F(_.purposes,`${t}/purposes`,2),g=>g);(!N.length||N.some(g=>!["preview","download"].includes(g)))&&f("NATIVE_OPERATION_FILE_INTENT_PURPOSE_INVALID",`${t}/purposes`);let b=Number(_.maxTtlSeconds);(!Number.isSafeInteger(b)||b<1||b>300)&&f("NATIVE_OPERATION_FILE_INTENT_TTL_INVALID",`${t}/maxTtlSeconds`);let R=Number(_.maxBytes);return(!Number.isSafeInteger(R)||R<1||R>104857600)&&f("NATIVE_OPERATION_FILE_INTENT_SIZE_INVALID",`${t}/maxBytes`),{recordResourceCode:p,recordIdInputField:u,relationField:l,fileNameField:m.fileNameField,contentTypeField:m.contentTypeField,sizeField:m.sizeField,purposes:N,maxTtlSeconds:b,maxBytes:R}}function zs(e,t,o,n,s,r){if(e===void 0)return null;let a=I(e,t);O(a,["directory","managedFiles","managedFileCopies","notification","workflow","roleAssertions","decimalReservation"],t,!0),Object.keys(a).length===0&&f("NATIVE_OPERATION_PLATFORM_ACCESS_EMPTY",t);let i={};if(a.roleAssertions!==void 0){let c=I(a.roleAssertions,`${t}/roleAssertions`);O(c,["roleCodes"],`${t}/roleAssertions`);let _=F(c.roleCodes,`${t}/roleAssertions/roleCodes`,20);_.length||f("NATIVE_OPERATION_ROLE_ASSERTIONS_REQUIRED",`${t}/roleAssertions/roleCodes`),_.forEach((p,d)=>{r.has(p)||f("NATIVE_ROLE_REFERENCE_MISSING",`${t}/roleAssertions/roleCodes/${d}`)}),i.roleAssertions={roleCodes:j(_)}}if(a.directory!==void 0){let c=I(a.directory,`${t}/directory`);O(c,["mode","fields"],`${t}/directory`),c.mode!=="current-initiator"&&f("NATIVE_OPERATION_DIRECTORY_MODE_INVALID",`${t}/directory/mode`);let _=new Set(["displayName","employeeNumber","primaryDepartment","departments"]),p=F(c.fields,`${t}/directory/fields`,4);(!p.length||p.some(d=>!_.has(d)))&&f("NATIVE_OPERATION_DIRECTORY_FIELDS_INVALID",`${t}/directory/fields`),i.directory={mode:"current-initiator",fields:j(p)}}if(a.managedFiles!==void 0){let c=$(a.managedFiles,`${t}/managedFiles`,16);c.length||f("NATIVE_OPERATION_MANAGED_FILES_REQUIRED",`${t}/managedFiles`);let _=new Set;i.managedFiles=X(c.map((p,d)=>{let u=`${t}/managedFiles/${d}`,E=I(p,u);O(E,["resourceCode","fieldCodes","intents"],u);let l=G(E.resourceCode,`${u}/resourceCode`);(_.has(l)||!o.has(l))&&f("NATIVE_OPERATION_MANAGED_FILE_RESOURCE_INVALID",`${u}/resourceCode`),_.add(l);let A=F(E.fieldCodes,`${u}/fieldCodes`,16);(!A.length||A.some(m=>!["file","image","signature"].includes(String(o.get(l)?.get(m)||""))))&&f("NATIVE_OPERATION_MANAGED_FILE_FIELD_INVALID",`${u}/fieldCodes`);let T=F(E.intents,`${u}/intents`,2);return(!T.length||T.some(m=>!["create","update"].includes(m)))&&f("NATIVE_OPERATION_MANAGED_FILE_INTENT_INVALID",`${u}/intents`),{resourceCode:l,fieldCodes:j(A),intents:j(T)}}),p=>p.resourceCode)}if(a.managedFileCopies!==void 0){let c=$(a.managedFileCopies,`${t}/managedFileCopies`,16);c.length||f("NATIVE_OPERATION_MANAGED_FILE_COPIES_REQUIRED",`${t}/managedFileCopies`);let _=new Set;i.managedFileCopies=X(c.map((p,d)=>{let u=`${t}/managedFileCopies/${d}`,E=I(p,u);O(E,["mode","sourceResourceCode","sourceFieldCodes","targetResourceCode","targetFieldCodes"],u),L(E.mode,"copy",`${u}/mode`);let l=G(E.sourceResourceCode,`${u}/sourceResourceCode`),A=G(E.targetResourceCode,`${u}/targetResourceCode`),T=o.get(l),m=o.get(A);(!T||!m)&&f("NATIVE_OPERATION_MANAGED_FILE_COPY_RESOURCE_INVALID",u);let N=F(E.sourceFieldCodes,`${u}/sourceFieldCodes`,16),b=F(E.targetFieldCodes,`${u}/targetFieldCodes`,16);(!N.length||N.length!==b.length)&&f("NATIVE_OPERATION_MANAGED_FILE_COPY_FIELDS_INVALID",u),N.forEach((g,C)=>{let D=T.get(g),y=m.get(b[C]);(!["file","image"].includes(String(D))||D!==y)&&f("NATIVE_OPERATION_MANAGED_FILE_COPY_FIELD_INVALID",`${u}/sourceFieldCodes/${C}`)});let R=`${l}:${N.join(",")}=>${A}:${b.join(",")}`;return _.has(R)&&f("NATIVE_OPERATION_MANAGED_FILE_COPY_DUPLICATE",u),_.add(R),{mode:"copy",sourceResourceCode:l,sourceFieldCodes:j(N),targetResourceCode:A,targetFieldCodes:j(b)}}),p=>`${p.sourceResourceCode}:${p.sourceFieldCodes.join(",")}=>${p.targetResourceCode}:${p.targetFieldCodes.join(",")}`)}if(a.notification!==void 0){let c=I(a.notification,`${t}/notification`);O(c,["mode"],`${t}/notification`),c.mode!=="business-standard"&&f("NATIVE_OPERATION_NOTIFICATION_MODE_INVALID",`${t}/notification/mode`),i.notification={mode:"business-standard"}}if(a.workflow!==void 0){let c=I(a.workflow,`${t}/workflow`);O(c,["codes"],`${t}/workflow`);let _=F(c.codes,`${t}/workflow/codes`,16);(!_.length||_.some(p=>!s.has(p)))&&f("NATIVE_OPERATION_WORKFLOW_CODE_INVALID",`${t}/workflow/codes`),i.workflow={codes:j(_)}}if(a.decimalReservation!==void 0){let c=`${t}/decimalReservation`,_=I(a.decimalReservation,c);O(_,["mode","resourceCode","amountFieldCode","currencyFieldCode","relationFieldCode","parentFieldCode","rootFieldCode","statusFieldCode","parentRelationValue","childRelationValue","eligibleParentStatuses","eligibleChildStatuses"],c);let p=h(_.mode,`${c}/mode`,16);["reserve","commit","release"].includes(p)||f("NATIVE_DECIMAL_RESERVATION_MODE_INVALID",`${c}/mode`);let d=G(_.resourceCode,`${c}/resourceCode`),u=n.get(d);u||f("NATIVE_DECIMAL_RESERVATION_RESOURCE_MISSING",`${c}/resourceCode`);let l=Object.fromEntries(["amountFieldCode","currencyFieldCode","relationFieldCode","parentFieldCode","rootFieldCode","statusFieldCode"].map(g=>[g,B(_[g],`${c}/${g}`)])),A=g=>u.get(l[g]),T=g=>new Set((A(g)?.options||[]).map(C=>String(C.value))),m=w(_.parentRelationValue,`${c}/parentRelationValue`),N=w(_.childRelationValue,`${c}/childRelationValue`),b=F(_.eligibleParentStatuses,`${c}/eligibleParentStatuses`,16),R=F(_.eligibleChildStatuses,`${c}/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!==d||A("rootFieldCode")?.type!=="uuid"||A("statusFieldCode")?.type!=="option.single"||m===N||!T("relationFieldCode").has(m)||!T("relationFieldCode").has(N)||!b.length||!R.length||b.some(g=>!T("statusFieldCode").has(g))||R.some(g=>!T("statusFieldCode").has(g)))&&f("NATIVE_DECIMAL_RESERVATION_FIELD_INVALID",c),i.decimalReservation={mode:p,resourceCode:d,...l,parentRelationValue:m,childRelationValue:N,eligibleParentStatuses:j(b),eligibleChildStatuses:j(R)}}return i}function Ys(e,t,o,n,s){if(e===void 0)return;let r=`${t}/ai`,a=I(e,r);_s.test(o)||f("NATIVE_OPERATION_AI_CODE_INVALID",`${t}/code`),O(a,["name","description","risk","resources","sideEffects","concurrency","timeoutMs"],r,!0),h(a.name,`${r}/name`,Ft),h(a.description,`${r}/description`,Ft);let i=h(a.risk,`${r}/risk`,16);["read","write","destructive","external"].includes(i)||f("NATIVE_OPERATION_AI_RISK_INVALID",`${r}/risk`),i==="read"!=(n==="GET")&&f("NATIVE_OPERATION_AI_METHOD_RISK_MISMATCH",`${r}/risk`),n==="DELETE"&&!["destructive","external"].includes(i)&&f("NATIVE_OPERATION_AI_METHOD_RISK_MISMATCH",`${r}/risk`);let c=F(a.resources,`${r}/resources`,16);c.length===0&&f("NATIVE_OPERATION_AI_RESOURCE_REQUIRED",`${r}/resources`),c.forEach((p,d)=>{let u=G(p,`${r}/resources/${d}`);s.has(u)||f("NATIVE_OPERATION_AI_RESOURCE_MISSING",`${r}/resources/${d}`)});let _=F(a.sideEffects,`${r}/sideEffects`,20);(i==="read"&&_.length!==0||i!=="read"&&_.length===0)&&f("NATIVE_OPERATION_AI_SIDE_EFFECT_INVALID",`${r}/sideEffects`),a.concurrency!==void 0&&!["none","revision"].includes(h(a.concurrency,`${r}/concurrency`,16))&&f("NATIVE_OPERATION_AI_CONCURRENCY_INVALID",`${r}/concurrency`),a.timeoutMs!==void 0&&Z(a.timeoutMs,`${r}/timeoutMs`,100,3e4)}function et(e){return(e.replace(/\/{2,}/g,"/").replace(/\/$/,"")||"/").split("/").map(o=>o.startsWith(":")?":":o.includes("*")?"*":o).join("/")}function qs(e,t){let o=I(e,t),n=h(o.type,`${t}/type`,32),s=["code","type","label","presentation","required"],r=n==="sso"?[...s,"provider"]:n==="dingtalk"?[...s,"flow"]:s;O(o,r,t);let a=w(o.code,`${t}/code`),i=h(o.label,`${t}/label`,255),c=h(o.presentation,`${t}/presentation`,16);["primary","secondary"].includes(c)||f("NATIVE_APPLICATION_AUTH_METHOD_PRESENTATION_INVALID",`${t}/presentation`);let _=we(o.required,`${t}/required`);return["sso","password","dingtalk"].includes(n)||f("NATIVE_APPLICATION_AUTH_METHOD_TYPE_INVALID",`${t}/type`),n==="sso"&&o.provider!=="tenant-default"&&f("NATIVE_APPLICATION_AUTH_SSO_PROVIDER_INVALID",`${t}/provider`),n==="dingtalk"&&!["auto","jsapi","oauth"].includes(h(o.flow,`${t}/flow`,16))&&f("NATIVE_APPLICATION_AUTH_DINGTALK_FLOW_INVALID",`${t}/flow`),{code:a,type:n,label:i,presentation:c,required:_,...n==="sso"?{provider:"tenant-default"}:{},...n==="dingtalk"?{flow:o.flow}:{}}}function Fn(e,t,o){let n=I(e,o);O(n,["routeCode","path","defaultRouteCode"],o);let s=w(n.routeCode,`${o}/routeCode`),r=de(n.path,`${o}/path`),a=t==="desktop"?"/login":"/m/login";return(r!==a||/[:*?#\\]/.test(r))&&f("NATIVE_APPLICATION_AUTH_SURFACE_PATH_INVALID",`${o}/path`,{device:t,expectedPath:a}),{routeCode:s,path:r,defaultRouteCode:w(n.defaultRouteCode,`${o}/defaultRouteCode`)}}function Xn(e,t,o,n){if(e===null)return;let s=I(e,n);O(s,["accountMode","registration","methods","surfaces"],n),L(s.accountMode,"existing-platform-users-only",`${n}/accountMode`);let r=I(s.registration,`${n}/registration`);O(r,["mode"],`${n}/registration`),L(r.mode,"reject",`${n}/registration/mode`);let a=$(s.methods,`${n}/methods`,8);a.length===0&&f("NATIVE_APPLICATION_AUTH_METHOD_REQUIRED",`${n}/methods`);let i=a.map((m,N)=>qs(m,`${n}/methods/${N}`)),c=new Set,_=new Set;for(let[m,N]of i.entries())c.has(N.code)&&f("NATIVE_APPLICATION_AUTH_METHOD_CODE_DUPLICATE",`${n}/methods/${m}/code`),_.has(N.type)&&f("NATIVE_APPLICATION_AUTH_METHOD_TYPE_DUPLICATE",`${n}/methods/${m}/type`),c.add(N.code),_.add(N.type);i.filter(m=>m.presentation==="primary").length!==1&&f("NATIVE_APPLICATION_AUTH_PRIMARY_METHOD_INVALID",`${n}/methods`);let p=I(s.surfaces,`${n}/surfaces`);O(p,["desktop","mobile"],`${n}/surfaces`);let d=Fn(p.desktop,"desktop",`${n}/surfaces/desktop`),u=Fn(p.mobile,"mobile",`${n}/surfaces/mobile`);d.routeCode===u.routeCode&&f("NATIVE_APPLICATION_AUTH_SURFACE_CODE_DUPLICATE",`${n}/surfaces/mobile/routeCode`);let E=$(t,"/config/frontend/routes",500),l=new Map;for(let[m,N]of E.entries()){let b=I(N,`/config/frontend/routes/${m}`);l.set(String(b.code||""),b)}let A=new Set((Array.isArray(o.data?.resources)?o.data.resources:[]).map(m=>String(m.code||"")).filter(m=>/^[a-z][a-z0-9-]{0,62}$/.test(m)));for(let[m,N]of[["desktop",d],["mobile",u]]){l.has(N.routeCode)&&f("NATIVE_APPLICATION_AUTH_SURFACE_CODE_CONFLICT",`${n}/surfaces/${m}/routeCode`);let b=/^user\.([a-z][a-z0-9-]{0,62})\.(records|submit)$/.exec(String(N.defaultRouteCode||"")),R=l.get(N.defaultRouteCode),g=String(R?.path||"");if(b&&A.has(b[1])){let D=b[2]==="records"?`/my/${b[1]}`:`/my/${b[1]}/submit`;R={surface:"user",path:m==="mobile"?`/m${D}`:D},g=String(R.path)}let C=m==="desktop"?g==="/m"||g.startsWith("/m/"):!(g==="/m"||g.startsWith("/m/"));(!R||R.surface!=="user"||/[:*]/.test(g)||C)&&f("NATIVE_APPLICATION_AUTH_DEFAULT_ROUTE_INVALID",`${n}/surfaces/${m}/defaultRouteCode`)}let T=Qn(o).filter(m=>!m.owner.startsWith("authentication:"));for(let[m,N]of[["desktop",d],["mobile",u]]){let b=T.find(R=>et(R.path)===et(N.path));b&&f("NATIVE_APPLICATION_AUTH_SURFACE_PATH_CONFLICT",`${n}/surfaces/${m}/path`,{owner:b.owner})}}function Ks(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=I(e,t),s=I(n.surfaces,`${t}/surfaces`),r={...n,surfaces:{...s,desktop:{...I(s.desktop,`${t}/surfaces/desktop`),defaultRouteCode:"auth-desktop-default"},mobile:{...I(s.mobile,`${t}/surfaces/mobile`),defaultRouteCode:"auth-mobile-default"}}};Xn(r,o.frontend.routes,{...o,frontend:{...o.frontend,authentication:r}},t)}function Hs(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 Xs=new Set(["draft.read","draft.update","validate","create","own.list","own.read","public.list","public.read"]);function Qs(e,t,o){let n=I(e,o);O(n,["policies"],o);let s=$(n.policies,`${o}/policies`,16);s.length<1&&f("NATIVE_PUBLIC_POLICY_REQUIRED",o);let r=new Map(t.frontend.routes.map(_=>[_.code,_])),a=new Map(t.data.resources.map(_=>[_.code,_])),i=new Set,c=new Set(s.map(_=>String(_?.code||"")));s.forEach((_,p)=>{let d=`${o}/policies/${p}`,u=I(_,d);O(u,["code","routeCode","mode","resourceCode","operations","fields"],d,["requiredFields","ownRecordFields","publicRecordFields","publicFilters","serverGeneratedFields","schedule","publicSubtableFields","draft","validations"]);let E=w(u.code,`${d}/code`);i.has(E)&&f("NATIVE_PUBLIC_POLICY_DUPLICATE",`${d}/code`);let l=w(u.routeCode,`${d}/routeCode`),A=r.get(l);(!A||A.surface!=="user"||A.capability!==void 0||A.access!==void 0||/[:*]/.test(String(A.path)))&&f("NATIVE_PUBLIC_ROUTE_INVALID",`${d}/routeCode`),L(u.mode,"anonymous",`${d}/mode`);let T=G(u.resourceCode,`${d}/resourceCode`),m=a.get(T);m||f("NATIVE_PUBLIC_RESOURCE_MISSING",`${d}/resourceCode`);let N=new Map(m.schema.fields.map(V=>[String(V.code),String(V.type)])),b=F(u.operations,`${d}/operations`,8);(b.length<1||b.some(V=>!Xs.has(V)))&&f("NATIVE_PUBLIC_OPERATION_INVALID",`${d}/operations`),b.includes("draft.read")!==b.includes("draft.update")&&f("NATIVE_PUBLIC_DRAFT_OPERATION_INCOMPLETE",`${d}/operations`);let R=F(u.fields,`${d}/fields`,64);(R.length<1||R.some(V=>!N.has(V)))&&f("NATIVE_PUBLIC_FIELD_INVALID",`${d}/fields`);for(let V of["requiredFields","ownRecordFields","publicRecordFields"]){if(!Object.prototype.hasOwnProperty.call(u,V))continue;F(u[V],`${d}/${V}`,64).some(P=>!R.includes(P))&&f("NATIVE_PUBLIC_FIELD_SCOPE_INVALID",`${d}/${V}`)}let g=Object.prototype.hasOwnProperty.call(u,"serverGeneratedFields")?$(u.serverGeneratedFields,`${d}/serverGeneratedFields`,16):[],C=new Set;g.forEach((V,x)=>{let P=`${d}/serverGeneratedFields/${x}`,J=I(V,P);O(J,["field","kind"],P);let W=B(J.field,`${P}/field`);(C.has(W)||!N.has(W)||R.includes(W)||N.get(W)!=="text.short"&&N.get(W)!=="text.long")&&f("NATIVE_PUBLIC_SERVER_GENERATED_FIELD_INVALID",`${P}/field`),L(J.kind,"random-token",`${P}/kind`),C.add(W)});let D=Object.prototype.hasOwnProperty.call(u,"schedule")?I(u.schedule,`${d}/schedule`):null;if(D){let V=["campusPolicyCode","rulePolicyCode","campusField","ruleCampusField","ruleWeekdaysField","ruleOpenAtField","ruleCloseAtField","ruleSlotMinutesField","ruleAdvanceHoursField","ruleAdvanceDaysField","campusEnabledField","ruleEnabledField","dateField","timeField"];O(D,V,`${d}/schedule`);for(let x of["campusPolicyCode","rulePolicyCode"])w(D[x],`${d}/schedule/${x}`);for(let x of V.filter(P=>!["campusPolicyCode","rulePolicyCode"].includes(P)))B(D[x],`${d}/schedule/${x}`);for(let x of[D.campusField,D.dateField,D.timeField])R.includes(String(x))||f("NATIVE_PUBLIC_SCHEDULE_FIELD_INVALID",`${d}/schedule`);(!c.has(String(D.campusPolicyCode))||!c.has(String(D.rulePolicyCode)))&&f("NATIVE_PUBLIC_SCHEDULE_POLICY_INVALID",`${d}/schedule`)}let y=Object.prototype.hasOwnProperty.call(u,"publicFilters")?$(u.publicFilters,`${d}/publicFilters`,16):[],U=new Set;y.forEach((V,x)=>{let P=`${d}/publicFilters/${x}`,J=I(V,P);O(J,["field","operator","value"],P);let W=B(J.field,`${P}/field`);U.has(W)&&f("NATIVE_PUBLIC_FILTER_DUPLICATE",`${P}/field`),R.includes(W)||f("NATIVE_PUBLIC_FILTER_FIELD_INVALID",`${P}/field`),L(J.operator,"eq",`${P}/operator`),["boolean","text.short","text.long","number.integer","number.decimal","date","time"].includes(N.get(W)||"")||f("NATIVE_PUBLIC_FILTER_FIELD_INVALID",`${P}/field`),J.value!==null&&typeof J.value!="string"&&typeof J.value!="number"&&typeof J.value!="boolean"&&f("NATIVE_PUBLIC_FILTER_VALUE_INVALID",`${P}/value`),U.add(W)});let k=Object.prototype.hasOwnProperty.call(u,"publicSubtableFields")?I(u.publicSubtableFields,`${d}/publicSubtableFields`):null;if(k){Object.keys(k).length>64&&f("NATIVE_PUBLIC_SUBTABLE_FIELDS_INVALID",`${d}/publicSubtableFields`);for(let[V,x]of Object.entries(k)){let P=m.schema.fields.find(H=>String(H.code)===V),J=String(P?.subtable?.resourceCode||""),W=a.get(J),Ie=new Map((W?.schema?.fields||[]).map(H=>[String(H.code),String(H.type)])),z=F(x,`${d}/publicSubtableFields/${V}`,64);(!R.includes(V)||N.get(V)!=="subtable"||!W||z.length<1||z.some(H=>!Ie.has(H))||z.some(H=>Ie.get(H)==="subtable")||z.some(H=>Ie.get(H)==="signature"))&&f("NATIVE_PUBLIC_SUBTABLE_FIELDS_INVALID",`${d}/publicSubtableFields/${V}`)}}if(b.some(V=>V.startsWith("public."))){Object.prototype.hasOwnProperty.call(u,"publicRecordFields")||f("NATIVE_PUBLIC_RECORD_FIELDS_REQUIRED",`${d}/publicRecordFields`);let V=F(u.publicRecordFields,`${d}/publicRecordFields`,64);(V.length<1||V.some(x=>!R.includes(x))||V.some(x=>N.get(x)==="signature"||N.get(x)==="subtable"&&!k?.[x]))&&f("NATIVE_PUBLIC_RECORD_FIELDS_INVALID",`${d}/publicRecordFields`)}let Y=Object.prototype.hasOwnProperty.call(u,"requiredFields")?F(u.requiredFields,`${d}/requiredFields`,64):[],M=m.surface||{},le=M.fields||{},ue=String(M.mutationOwner||"native")==="native"&&M.generated?.create!==!1,K=m.schema.fields.filter(V=>ze(V,le[V.code])).map(V=>String(V.code));if(b.includes("create")&&!ue&&f("NATIVE_PUBLIC_CREATE_FIELDS_INCOMPLETE",`${d}/fields`),b.includes("create")&&!Object.prototype.hasOwnProperty.call(u,"draft")&&f("NATIVE_PUBLIC_DRAFT_REQUIRED",`${d}/draft`),b.includes("create"))for(let V of K){let x=R.includes(V)?Y.includes(V)?null:"requiredFields":"fields";x&&f("NATIVE_PUBLIC_CREATE_FIELDS_INCOMPLETE",`${d}/${x}`,{resourceCode:G,fieldCode:V})}if(Object.prototype.hasOwnProperty.call(u,"draft")){let V=I(u.draft,`${d}/draft`);O(V,["enabled","inactivityTtlSeconds","maxBytes"],`${d}/draft`),L(V.enabled,!0,`${d}/draft/enabled`),Z(V.inactivityTtlSeconds,`${d}/draft/inactivityTtlSeconds`,3600,7776e3),Z(V.maxBytes,`${d}/draft/maxBytes`,4096,262144)}else b.includes("draft.read")&&f("NATIVE_PUBLIC_DRAFT_REQUIRED",`${d}/draft`);let Ae=Object.prototype.hasOwnProperty.call(u,"validations")?$(u.validations,`${d}/validations`,16):[],se=new Set;Ae.forEach((V,x)=>{let P=`${d}/validations/${x}`,J=I(V,P);O(J,["code","kind","fields","result"],P);let W=w(J.code,`${P}/code`);se.has(W)&&f("NATIVE_PUBLIC_VALIDATION_DUPLICATE",`${P}/code`),L(J.kind,"duplicate",`${P}/kind`),L(J.result,"availability",`${P}/result`);let Ie=F(J.fields,`${P}/fields`,8);(Ie.length<1||Ie.some(z=>!R.includes(z))||Ie.some(z=>["file","subtable"].includes(N.get(z)||"")))&&f("NATIVE_PUBLIC_VALIDATION_FIELD_INVALID",`${P}/fields`),se.add(W)}),i.add(E)})}function Zs(e,t){let o=I(e,t);O(o,["policies"],t),$(o.policies,`${t}/policies`,16).length<1&&f("NATIVE_PUBLIC_POLICY_REQUIRED",t)}function ei(e){return{policies:X(e.frontend.publicAccess.policies.map(t=>({code:t.code,routeCode:t.routeCode,mode:t.mode,resourceCode:t.resourceCode,operations:j(t.operations),fields:j(t.fields),...t.requiredFields?{requiredFields:j(t.requiredFields)}:{},...t.ownRecordFields?{ownRecordFields:j(t.ownRecordFields)}:{},...t.publicRecordFields?{publicRecordFields:j(t.publicRecordFields)}:{},...t.publicFilters?{publicFilters:t.publicFilters.map(o=>({field:o.field,operator:o.operator,value:o.value})).sort((o,n)=>re(o.field,n.field))}:{},...t.publicSubtableFields?{publicSubtableFields:Object.fromEntries(Object.entries(t.publicSubtableFields).sort(([o],[n])=>o.localeCompare(n)).map(([o,n])=>[o,j(Array.isArray(n)?n.map(String):[])]))}:{},...t.serverGeneratedFields?{serverGeneratedFields:t.serverGeneratedFields.map(o=>({field:o.field,kind:o.kind})).sort((o,n)=>re(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:X(t.validations.map(o=>({code:o.code,kind:o.kind,fields:j(o.fields),result:o.result})),o=>o.code)}:{}})),t=>t.code)}}function Qn(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=Zn(o),s=`/admin/resources/${o.code}`,r=[["list",s],["detail",`${s}/:id`],["create",`${s}/new`],["update",`${s}/:id/edit`]];for(let[a,i]of r)n[a]&&t.push({owner:`resource:${o.code}:${a}`,path:i},{owner:`resource:${o.code}:${a}:mobile`,path:`/m${i}`})}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 ot(e){let t=new Map(Qn(e).map(o=>[et(o.path),o]));return X(e.frontend.routes.map((o,n)=>{let s=`/config/frontend/routes/${n}`,r=I(o,s);O(r,["code","path","label","surface","parentCode","capability","access","pinned","tabPersistence","keepAlive"],s,!0),["admin","user"].includes(r.surface)||f("NATIVE_ROUTE_SURFACE_INVALID",`${s}/surface`);let a=de(r.path,`${s}/path`);r.surface==="admin"&&a!=="/admin"&&!a.startsWith("/admin/")&&f("NATIVE_ADMIN_ROUTE_PATH_INVALID",`${s}/path`),r.surface==="user"&&(a==="/admin"||a.startsWith("/admin/"))&&f("NATIVE_USER_ROUTE_PATH_RESERVED",`${s}/path`);let i=et(a),c=t.get(i);c&&f("NATIVE_ROUTE_PATH_CONFLICT",`${s}/path`,{path:a,owner:c.owner}),t.set(i,{owner:`frontend:${String(r.code||n)}`,path:a});let _=/[:*]/.test(a),p=jt(r,s,e.appCode),d=r.pinned===void 0?void 0:we(r.pinned,`${s}/pinned`),u=r.tabPersistence===void 0?_?"none":"session":h(r.tabPersistence,`${s}/tabPersistence`,16),E=r.keepAlive===void 0?"none":h(r.keepAlive,`${s}/keepAlive`,16);return["session","none"].includes(u)||f("NATIVE_ROUTE_TAB_PERSISTENCE_INVALID",`${s}/tabPersistence`),["none","memory"].includes(E)||f("NATIVE_ROUTE_KEEP_ALIVE_INVALID",`${s}/keepAlive`),_&&d===!0&&f("NATIVE_DYNAMIC_ROUTE_PINNED_FORBIDDEN",`${s}/pinned`),_&&u==="session"&&f("NATIVE_DYNAMIC_ROUTE_TAB_PERSISTENCE_FORBIDDEN",`${s}/tabPersistence`),_&&E==="memory"&&f("NATIVE_DYNAMIC_ROUTE_KEEP_ALIVE_FORBIDDEN",`${s}/keepAlive`),{code:w(r.code,`${s}/code`),path:a,label:h(r.label,`${s}/label`,255),surface:r.surface,...r.parentCode===void 0?{}:{parentCode:w(r.parentCode,`${s}/parentCode`)},...p,...d===void 0?{}:{pinned:d},tabPersistence:u,keepAlive:E}}),o=>o.code)}function Zn(e){let t=e.surface===void 0?{}:I(e.surface,"/surface"),o=t.mutationOwner||"native",n=t.generated===void 0?{}:I(t.generated,"/surface/generated"),s=o==="native";return{list:n.list??!0,detail:n.detail??!0,create:n.create??s,update:n.update??s,delete:n.delete??s}}function eo(e){let t=[];for(let o of X(e.data.resources,n=>n.code).flatMap(n=>[{resource:n,viewCode:void 0},...(n.surface?.views||[]).map(s=>({viewCode:s.code,resource:{...n,name:s.name,surface:Ct(n.surface,s.code)}}))])){let{resource:n,viewCode:s}=o,r=`/admin/resources/${n.code}${s?`/views/${s}`:""}`,a=Zn(n),i=[{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 c of i)a[c.operation]&&t.push({code:`resource:${n.code}${s?`:view:${s}`:""}:${c.operation}`,kind:c.kind,path:c.path,label:c.label,navigationEligible:c.navigationEligible,capability:c.capability,resourceCode:n.code,...s?{viewCode:s}:{}})}for(let o of ot(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)=>re(o.code,n.code))}function to(e){return e.kind==="resource"?`resource:${e.resourceCode}${e.viewCode?`:view:${e.viewCode}`:""}:list`:`operation:${e.routeCode}`}function ti(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,s)=>({pageCode:to(n.page),...n.label===void 0?{}:{label:n.label},...n.icon===void 0?{}:{icon:n.icon},order:n.order??s})).sort((n,s)=>n.order-s.order||re(n.pageCode,s.pageCode))})).sort((t,o)=>t.order-o.order||re(t.code,o.code))}function ni(e,t){let o=$(e,t,q.adminNavigationGroups),n=0;o.forEach((s,r)=>{let a=`${t}/${r}`,i=I(s,a);O(i,["code","label","icon","order","items"],a,!0),w(i.code,`${a}/code`),h(i.label,`${a}/label`,255),tt(i.icon,`${a}/icon`),xn(i.order,`${a}/order`);let c=$(i.items,`${a}/items`,500);c.length===0&&f("NATIVE_ADMIN_GROUP_ORPHANED",`${a}/items`),n+=c.length,n>q.adminNavigationItems&&f("NATIVE_ARRAY_LIMIT_EXCEEDED",t),c.forEach((_,p)=>{let d=`${a}/items/${p}`,u=I(_,d);O(u,["page","label","icon","order"],d,!0),oi(u.page,`${d}/page`),u.label!==void 0&&h(u.label,`${d}/label`,255),tt(u.icon,`${d}/icon`),xn(u.order,`${d}/order`)})})}function oi(e,t){let o=I(e,t),n=h(o.kind,`${t}/kind`,64);if(n==="resource"){O(o,["kind","resourceCode"],t,["viewCode"]),o.viewCode!==void 0&&w(o.viewCode,`${t}/viewCode`),G(o.resourceCode,`${t}/resourceCode`);return}if(n==="operation"){O(o,["kind","routeCode"],t),w(o.routeCode,`${t}/routeCode`);return}f("NATIVE_ADMIN_PAGE_REFERENCE_KIND_INVALID",`${t}/kind`)}function si(e){let t=new Map(eo(e).map(s=>[String(s.code),s])),o=new Set,n=new Set;e.frontend.admin.navigation.forEach((s,r)=>{let a=`/config/frontend/admin/navigation/${r}`;o.has(s.code)&&f("NATIVE_ADMIN_GROUP_DUPLICATE",`${a}/code`),o.add(s.code),s.label===s.code&&f("NATIVE_ADMIN_USER_LABEL_REQUIRED",`${a}/label`),s.items.forEach((i,c)=>{let _=`${a}/items/${c}`,p=to(i.page),d=t.get(p);(!d||d.navigationEligible!==!0)&&f("NATIVE_ADMIN_PAGE_NOT_FOUND",`${_}/page`),n.has(p)&&f("NATIVE_ADMIN_PAGE_DUPLICATE",`${_}/page`),n.add(p);let u=i.page.resourceCode||i.page.routeCode||i.page.workflowCode||p,E=i.label||d.label;(!E||E===u||E===p)&&f("NATIVE_ADMIN_USER_LABEL_REQUIRED",`${_}/label`)})})}function ii(e,t){let o=$(e,t,q.adminPages),n=new Set;o.forEach((s,r)=>{let a=`${t}/${r}`,i=I(s,a);O(i,["code","kind","path","label","navigationEligible","capability","access","resourceCode","viewCode","routeCode"],a,!0);let c=h(i.code,`${a}/code`,255);n.has(c)&&f("NATIVE_ADMIN_PAGE_DUPLICATE",`${a}/code`),n.add(c);let _=h(i.kind,`${a}/kind`,64);if(["resource-list","resource-detail","resource-create","resource-update","operation"].includes(_)||f("NATIVE_ADMIN_PAGE_KIND_INVALID",`${a}/kind`),de(i.path,`${a}/path`),h(i.label,`${a}/label`,255),we(i.navigationEligible,`${a}/navigationEligible`),i.capability!==void 0&&i.access!==void 0&&f("NATIVE_ROUTE_ACCESS_CONFLICT",`${a}/access`),i.capability!==void 0&&h(i.capability,`${a}/capability`,255),i.access!==void 0){let p=I(i.access,`${a}/access`);O(p,["allOf","anyOf"],`${a}/access`,!0);for(let d of["allOf","anyOf"])p[d]!==void 0&&F(p[d],`${a}/access/${d}`,50)}for(let p of["resourceCode","viewCode","routeCode"])i[p]!==void 0&&w(i[p],`${a}/${p}`)})}function ri(e,t){let o=$(e,t,q.adminNavigationGroups),n=0;o.forEach((s,r)=>{let a=`${t}/${r}`,i=I(s,a);O(i,["code","label","icon","order","items"],a,!0),w(i.code,`${a}/code`),h(i.label,`${a}/label`,255),tt(i.icon,`${a}/icon`),Z(i.order,`${a}/order`,-1e4,1e4);let c=$(i.items,`${a}/items`,500);c.length===0&&f("NATIVE_ADMIN_GROUP_ORPHANED",`${a}/items`),n+=c.length,n>q.adminNavigationItems&&f("NATIVE_ARRAY_LIMIT_EXCEEDED",t),c.forEach((_,p)=>{let d=`${a}/items/${p}`,u=I(_,d);O(u,["pageCode","label","icon","order"],d,!0),h(u.pageCode,`${d}/pageCode`,255),u.label!==void 0&&h(u.label,`${d}/label`,255),tt(u.icon,`${d}/icon`),Z(u.order,`${d}/order`,-1e4,1e4)})})}var ai=new Set(["application-todo-center","workflow-work-center","workflow-launch","workflow-task","workflow-instance","resource-records","resource-submit"]);function ci(e,t,o){let n=I(e,t);O(n,["schemaVersion","appCode","devicePolicy","rootEntry","authentication","routes","digest"],t),L(n.schemaVersion,qn,`${t}/schemaVersion`),L(n.appCode,o,`${t}/appCode`),Mt(n.devicePolicy,`${t}/devicePolicy`),di(n.rootEntry,`${t}/rootEntry`),li(n.authentication,`${t}/authentication`),xt(n.digest,`${t}/digest`);let s=$(n.routes,`${t}/routes`,q.routes),r=new Set;s.forEach((a,i)=>{let c=`${t}/routes/${i}`,_=I(a,c),p=_.kind==="resource-records"||_.kind==="resource-submit";O(_,["code","kind","desktop","mobile"],c,["workflowCode",...p?["resourceCode"]:[]]);let d=h(_.code,`${c}/code`,255);r.has(d)&&f("NATIVE_ROUTE_MANIFEST_DUPLICATE",`${c}/code`),r.add(d);let u=h(_.kind,`${c}/kind`,64);if(ai.has(u)||f("NATIVE_ROUTE_MANIFEST_KIND_INVALID",`${c}/kind`),_.workflowCode!==void 0&&w(_.workflowCode,`${c}/workflowCode`),p){let A=G(_.resourceCode,`${c}/resourceCode`);L(d,`user.${A}.${_.kind==="resource-records"?"records":"submit"}`,`${c}/code`)}else _.resourceCode!==void 0&&f("NATIVE_PROPERTY_UNKNOWN",`${c}/resourceCode`);let E=vn(_.desktop,`${c}/desktop`,o),l=vn(_.mobile,`${c}/mobile`,o);E.surface!=="user"&&f("NATIVE_ROUTE_MANIFEST_DESKTOP_SURFACE_INVALID",`${c}/desktop/surface`),l.surface!=="user"&&f("NATIVE_ROUTE_MANIFEST_MOBILE_SURFACE_INVALID",`${c}/mobile/surface`),E.routeCode===l.routeCode&&f("NATIVE_ROUTE_MANIFEST_PAIR_DUPLICATE",c)}),L(n.digest,ee({schemaVersion:n.schemaVersion,appCode:n.appCode,devicePolicy:n.devicePolicy,rootEntry:n.rootEntry,authentication:n.authentication,routes:n.routes}),`${t}/digest`)}function Mt(e,t){let o=I(e,t);O(o,["kind","mobileMaxWidthPx","desktopMinWidthPx"],t),L(o.kind,"viewport-family",`${t}/kind`);let n=Z(o.mobileMaxWidthPx,`${t}/mobileMaxWidthPx`,320,1600),s=Z(o.desktopMinWidthPx,`${t}/desktopMinWidthPx`,320,1600);return s!==n+1&&f("NATIVE_FRONTEND_DEVICE_POLICY_INVALID",t),{kind:"viewport-family",mobileMaxWidthPx:n,desktopMinWidthPx:s}}function di(e,t){let o=I(e,t);O(o,["code","desktop","mobile"],t);let n=w(o.code,`${t}/code`),s=kt(o.desktop,`${t}/desktop`),r=kt(o.mobile,`${t}/mobile`);return(s===r||r==="/"||!r.startsWith("/m/"))&&f("NATIVE_ROUTE_MANIFEST_ROOT_ENTRY_INVALID",t),s.startsWith("/m/")&&f("NATIVE_ROUTE_MANIFEST_ROOT_ENTRY_INVALID",`${t}/desktop`),{code:n,desktop:s,mobile:r}}function li(e,t){let o=I(e,t);O(o,["desktop","mobile"],t);let n=Pn(o.desktop,`${t}/desktop`,!1),s=Pn(o.mobile,`${t}/mobile`,!0);return(n.routeCode===s.routeCode||n.path===s.path)&&f("NATIVE_ROUTE_MANIFEST_AUTHENTICATION_DUPLICATE",t),{desktop:n,mobile:s}}function Pn(e,t,o){let n=I(e,t);O(n,["routeCode","path"],t);let s=w(n.routeCode,`${t}/routeCode`),r=kt(n.path,`${t}/path`);return(o?!r.startsWith("/m/"):r.startsWith("/m/"))&&f("NATIVE_ROUTE_MANIFEST_AUTHENTICATION_PATH_INVALID",`${t}/path`),{routeCode:s,path:r}}function kt(e,t){let o=de(e,t);return/[:*?#\\\\]/.test(o)&&f("NATIVE_ROUTE_MANIFEST_STATIC_PATH_INVALID",t),o}function vn(e,t,o){let n=I(e,t);O(n,["routeCode","path","surface","pathParams","requiresAuthentication"],t,["capability","access"]),w(n.routeCode,`${t}/routeCode`);let s=de(n.path,`${t}/path`),r=h(n.surface,`${t}/surface`,16);["admin","user"].includes(r)||f("NATIVE_ROUTE_SURFACE_INVALID",`${t}/surface`);let a=F(n.pathParams,`${t}/pathParams`,8);return a.forEach((i,c)=>{(!/^[A-Za-z][A-Za-z0-9_]*$/.test(i)||i.length>64)&&f("NATIVE_ROUTE_PATH_PARAM_INVALID",`${t}/pathParams/${c}`)}),Q(a)!==Q(no(s))&&f("NATIVE_ROUTE_PATH_PARAMS_MISMATCH",`${t}/pathParams`),jt(n,t,o),n.requiresAuthentication!==!0&&f("NATIVE_ROUTE_AUTHENTICATION_REQUIRED",`${t}/requiresAuthentication`),n}function no(e){return j([...e.matchAll(/:([A-Za-z][A-Za-z0-9_]*)/g)].map(t=>t[1]))}function Ln(e,t,o,n){return{routeCode:e,path:t,surface:o,pathParams:no(t),...n?.capability?{capability:n.capability}:{},...n?.access?{access:n.access}:{},requiresAuthentication:!0}}function kn(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 ui(e){let t=e.appCode,o=[],n=(E,l,A,T,m,N,b)=>{o.push({code:E,kind:l,...m?{workflowCode:m}:{},...b?{resourceCode:b}:{},desktop:Ln(kn(l,"desktop",m,b),A,"user",N),mobile:Ln(kn(l,"mobile",m,b),T,"user",N)})};e.frontend.user.applicationTodoCenter===!0&&n("application:todo-center","application-todo-center","/todos","/m/todos");let s=oo(e);s.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 E of s){if(!["standalone","hidden-handoff"].includes(E.launch.mode))continue;let l=j([E.launch.submission?.create?.requiredCapability,E.launch.submission?.existing?.requiredCapability].filter(A=>!!A));n(`workflow:${E.code}:launch`,"workflow-launch","/workflows/:workflowCode/start","/m/workflows/:workflowCode/start",E.code,l.length===1?{capability:l[0]}:l.length>1?{access:{anyOf:l}}:void 0)}let r=o.sort((E,l)=>re(String(E.code),String(l.code))),a=ot(e),i=E=>{let l=E==="mobile"?"/m/":"/",A=a.filter(m=>m.surface==="user"&&!/[:*?#\\\\]/.test(m.path)&&m.path===l).sort((m,N)=>re(m.code,N.code))[0];if(A)return{code:A.code,path:A.path};let T=a.filter(m=>m.surface==="user"&&!/[:*?#\\\\]/.test(m.path)&&(E==="mobile"?m.path.startsWith("/m/"):!m.path.startsWith("/m/"))).sort((m,N)=>re(m.code,N.code))[0];return T?{code:T.code,path:T.path}:{code:E==="mobile"?"application-root-mobile":"application-root",path:l}},c=e.frontend.authentication?{desktop:{routeCode:e.frontend.authentication.surfaces.desktop.routeCode,path:e.frontend.authentication.surfaces.desktop.path},mobile:{routeCode:e.frontend.authentication.surfaces.mobile.routeCode,path:e.frontend.authentication.surfaces.mobile.path}}:{desktop:{routeCode:"application-login",path:"/login"},mobile:{routeCode:"application-login-mobile",path:"/m/login"}},_=Mt(e.frontend.devicePolicy,"/config/frontend/devicePolicy"),p=i("desktop"),d=i("mobile"),u={schemaVersion:qn,appCode:t,devicePolicy:_,rootEntry:{code:p.code,desktop:p.path,mobile:d.path},authentication:c,routes:r};return{...u,digest:ee(u)}}function tt(e,t){if(e===void 0)return;let o=h(e,t,32);Os.has(o)||f("NATIVE_ADMIN_ICON_INVALID",t)}function xn(e,t){e!==void 0&&Z(e,t,-1e4,1e4)}function jt(e,t,o){return e.capability!==void 0&&e.access!==void 0&&f("NATIVE_ROUTE_ACCESS_CONFLICT",`${t}/access`),e.capability!==void 0?{capability:Te(e.capability,`${t}/capability`,o)}:e.access===void 0?{}:{access:st(e.access,`${t}/access`,o)}}function st(e,t,o){let n=I(e,t);O(n,["allOf","anyOf"],t,!0);let s=n.allOf===void 0?void 0:j(F(n.allOf,`${t}/allOf`,50).map((a,i)=>Te(a,`${t}/allOf/${i}`,o))),r=n.anyOf===void 0?void 0:j(F(n.anyOf,`${t}/anyOf`,50).map((a,i)=>Te(a,`${t}/anyOf/${i}`,o)));return(s?.length||0)+(r?.length||0)===0&&f("NATIVE_ROUTE_ACCESS_EMPTY",t),{...s===void 0?{}:{allOf:s},...r===void 0?{}:{anyOf:r}}}function oo(e){let t=new Map(Hn(e).map(s=>[String(s.code),s])),o=e.workflows.definitions.map((s,r)=>{let a=`/config/workflows/definitions/${r}`,i=I(s,a);O(i,["version","definition","launch"],a,["detailRouteCode"]);let c=I(i.definition,`${a}/definition`),_=i.detailRouteCode===void 0?void 0:io(i.detailRouteCode,`${a}/detailRouteCode`);return{code:w(c.code,`${a}/definition/code`),title:h(c.title,`${a}/definition/title`,255),version:Ve(i.version,`${a}/version`),launch:fi(e,c,i.launch,`${a}/launch`,t),..._?{detailRouteCode:_}:{},definition:c}});return j(o.map(s=>s.code)).map(s=>{let r=o.filter(_=>_.code===s),a=e.workflows.activations.find(_=>_.workflowCode===s)?.definitionVersion,i=r.find(_=>_.version===a)||[...r].sort((_,p)=>p.version-_.version)[0],c=new Set;for(let _ of r){let p=I(_.definition.nodes,"/config/workflows/definitions/nodes");for(let d of Object.values(p)){let u=I(d,"/config/workflows/definitions/nodes/*");if(u.kind==="approval")for(let E of F(u.allowedOperations||[],"/config/workflows/definitions/nodes/*/allowedOperations",20))c.add(E)}}return{code:s,title:i.title,acceptedCommandDeactivationPolicy:i.definition.acceptedCommandDeactivationPolicy,subject:i.definition.subject,launch:i.launch,...["standalone","hidden-handoff"].includes(i.launch.mode)&&!i.launch.submission?{processOperationCode:`openxiangda.workflow.${s}.submit`}:{},...i.detailRouteCode?{detailRouteCode:i.detailRouteCode}:{},definitionVersions:zn(r.map(_=>_.version)),bindingVersions:zn(e.workflows.bindings.map((_,p)=>{let d=`/config/workflows/bindings/${p}`,u=I(_,d),E=I(u.binding,`${d}/binding`);return{code:w(E.workflowCode,`${d}/binding/workflowCode`),version:Ve(u.version,`${d}/version`)}}).filter(_=>_.code===s).map(_=>_.version)),providerCodes:j(e.workflows.providers.map((_,p)=>w(I(_,`/config/workflows/providers/${p}`).code,`/config/workflows/providers/${p}/code`))),allowedOperations:[...c].sort(re),editableParameterCodes:j(e.workflows.editableParameters.map((_,p)=>{let d=`/config/workflows/editableParameters/${p}`,u=I(_,d);return{code:w(u.code,`${d}/code`),workflowCode:w(u.workflowCode,`${d}/workflowCode`)}}).filter(_=>_.workflowCode===s).map(_=>_.code))}})}function so(e,t){let o=I(e,t);O(o,["mode"],t,["submission"]);let n=h(o.mode,`${t}/mode`,32);return["standalone","custom-page","hidden-handoff","work-center-only"].includes(n)||f("NATIVE_WORKFLOW_LAUNCH_MODE_INVALID",`${t}/mode`),{mode:n,...o.submission===void 0?{}:{submission:I(o.submission,`${t}/submission`)}}}function fi(e,t,o,n,s){let r=so(o,n);if(!r.submission)return{mode:r.mode};["standalone","hidden-handoff"].includes(r.mode)||f("NATIVE_WORKFLOW_NAMED_OPERATION_SUBMISSION_INVALID",`${n}/submission`);let a=I(r.submission,`${n}/submission`);O(a,["kind"],`${n}/submission`,["create","existing","context"]),L(a.kind,"named-operation",`${n}/submission/kind`);let i=n.endsWith("/launch")?n.slice(0,-7):n,c=I(t.subject,`${i}/definition/subject`),_=G(c.resourceCode,`${i}/definition/subject/resourceCode`),p=e.data.resources.findIndex(C=>C.code===_),d=e.data.resources[p];(p<0||!d)&&f("NATIVE_WORKFLOW_SUBJECT_RESOURCE_MISSING",`${i}/definition/subject/resourceCode`);let u=new Set(I(d.schema,`/config/data/resources/${p}/schema`).fields.map(C=>String(C.code))),E=new Map(e.backend.operations.map(C=>[String(C.code),C])),l=(C,D)=>{let y=`${n}/submission/${D}`,U=I(C,y);O(U,["operationCode","inputs","output"],y);let k=w(U.operationCode,`${y}/operationCode`),Y=E.get(k),M=s.get(k),le=M?.platformAccess?.workflow?.codes;(!Y||!M||M.method!=="POST"||!Array.isArray(le)||!le.includes(t.code))&&f("NATIVE_WORKFLOW_NAMED_OPERATION_INVALID",y);let ue=I(Y.requestSchema,`${y}/operation/requestSchema`),K=I(ue.properties,`${y}/operation/requestSchema/properties`),Ae=new Set(ue.required===void 0?[]:F(ue.required,`${y}/operation/requestSchema/required`,64)),se=I(U.inputs,`${y}/inputs`),V=Object.entries(se);(!V.length||V.length>64)&&f("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${y}/inputs`);let x=new Set,P=new Map,J={};for(let[z,H]of V){(!Vn.test(z)||!Object.prototype.hasOwnProperty.call(K,z))&&f("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${y}/inputs/${z}`);let Re=`${y}/inputs/${z}`,rt=I(H,Re),be=h(rt.source,`${Re}/source`,32);if(["field","idempotency-key","current-user-reference","subject-id","subject-revision","requested-at"].includes(be)||f("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",Re),O(rt,["source"],Re,be==="field"?["fieldCode"]:!1),P.set(be,(P.get(be)||0)+1),be==="field"){let Be=B(rt.fieldCode,`${Re}/fieldCode`);(x.has(Be)||!u.has(Be))&&f("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${Re}/fieldCode`),x.add(Be),J[z]={source:be,fieldCode:Be}}else J[z]={source:be}}([...Ae].some(z=>!(z in se))||(P.get("idempotency-key")||0)!==1||!V.some(([z,H])=>I(H,`${y}/inputs/${z}`).source==="idempotency-key"&&Ae.has(z))||D==="create"&&((P.get("subject-id")||0)>0||(P.get("subject-revision")||0)>0)||D==="existing"&&((P.get("subject-id")||0)!==1||(P.get("subject-revision")||0)!==1))&&f("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${y}/inputs`);let W=I(U.output,`${y}/output`);O(W,["subjectId"],`${y}/output`,["subjectRevision","processCommand"]);let Ie=I(I(Y.responseSchema,`${y}/operation/responseSchema`).properties,`${y}/operation/responseSchema/properties`);for(let z of["subjectId","subjectRevision","processCommand"]){if(W[z]===void 0)continue;let H=h(W[z],`${y}/output/${z}`,128);(!Vn.test(H)||!Object.prototype.hasOwnProperty.call(Ie,H))&&f("NATIVE_WORKFLOW_NAMED_OPERATION_OUTPUT_INVALID",`${y}/output/${z}`)}return{operationCode:k,method:"POST",path:M.path,requiredCapability:M.requiredCapability,requestSchemaDigest:M.requestSchemaDigest,responseSchemaDigest:M.responseSchemaDigest,inputs:J,output:{...W},fieldCodes:x}},A=a.create===void 0?void 0:l(a.create,"create"),T=a.existing===void 0?void 0:l(a.existing,"existing");!A&&!T&&f("NATIVE_WORKFLOW_NAMED_OPERATION_SUBMISSION_INVALID",`${n}/submission`);let m=new Set([...A?.fieldCodes||[],...T?.fieldCodes||[]]),N=a.context===void 0?[]:$(a.context,`${n}/submission/context`,16),b=new Set,R=N.map((C,D)=>{let y=`${n}/submission/context/${D}`,U=I(C,y);O(U,["queryParameter","fieldCode"],y);let k=h(U.queryParameter,`${y}/queryParameter`,64),Y=B(U.fieldCode,`${y}/fieldCode`);return(!/^[A-Za-z][A-Za-z0-9]{0,63}$/.test(k)||b.has(k)||!m.has(Y))&&f("NATIVE_WORKFLOW_LAUNCH_CONTEXT_INVALID",y),b.add(k),{queryParameter:k,fieldCode:Y}}),g=C=>{let{fieldCodes:D,...y}=C;return y};return{mode:r.mode,submission:{kind:"named-operation",...A?{create:g(A)}:{},...T?{existing:g(T)}:{},context:R}}}function io(e,t){let o=I(e,t);O(o,["desktop","mobile"],t);let n=w(o.desktop,`${t}/desktop`),s=w(o.mobile,`${t}/mobile`);return n===s&&f("NATIVE_WORKFLOW_DETAIL_ROUTE_DUPLICATE",t),{desktop:n,mobile:s}}function _i(e,t){let o=new Set(t.map(p=>p.code)),n=new Map;e.data.resources.forEach((p,d)=>{let u=`/config/data/resources/${d}`,E=I(p,u);for(let[T,m]of Object.entries(E.fieldPolicies||{})){if(!Fe(T))continue;let N=`${u}/fieldPolicies/${T}/read`,b=I(m,`${u}/fieldPolicies/${T}`);for(let R of F(b.read||[],N,2e3))o.has(R)||f("NATIVE_CAPABILITY_REFERENCE_MISSING",N)}if(((E.surface===void 0?{}:I(E.surface,`${u}/surface`)).mutationOwner||"native")==="native")return;let A=I(E.capabilities,`${u}/capabilities`);for(let T of["create","update","delete"])n.set(String(A[T]),T)});let s=new Set;for(let[p,d]of e.authz.roles.entries()){let u=`/config/authz/roles/${p}`,E=I(d,u);O(E,["code","name","description","capabilities"],u,!0);let l=w(E.code,`${u}/code`);s.has(l)&&f("NATIVE_ROLE_DUPLICATE",`${u}/code`),s.add(l),h(E.name,`${u}/name`,255);let A=F(E.capabilities,`${u}/capabilities`,2e3);for(let[T,m]of A.entries())n.has(m)&&f("NATIVE_DATA_SURFACE_MUTATION_GRANT_FORBIDDEN",`${u}/capabilities/${T}`,{operation:n.get(m)}),o.has(m)||f("NATIVE_CAPABILITY_REFERENCE_MISSING",`${u}/capabilities`)}let r=e.authz.authenticatedUserRoleCode===void 0?"":w(e.authz.authenticatedUserRoleCode,"/config/authz/authenticatedUserRoleCode");r&&!s.has(r)&&f("NATIVE_AUTHENTICATED_USER_ROLE_REFERENCE_MISSING","/config/authz/authenticatedUserRoleCode");let a=new Set,i=0;for(let[p,d]of e.perspectives.entries()){let u=`/config/perspectives/${p}`,E=I(d,u);O(E,["code","name","description","roleCodes","capabilityCodes","default"],u,!0);let l=w(E.code,`${u}/code`);a.has(l)&&f("NATIVE_PERSPECTIVE_DUPLICATE",`${u}/code`),a.add(l),h(E.name,`${u}/name`,255);let A=F(E.roleCodes,`${u}/roleCodes`,20);A.length<1&&f("NATIVE_PERSPECTIVE_ROLE_REQUIRED",`${u}/roleCodes`),A.forEach((N,b)=>{s.has(N)||f("NATIVE_PERSPECTIVE_ROLE_MISSING",`${u}/roleCodes/${b}`)});let T=j(e.authz.roles.filter(N=>A.includes(N.code)).flatMap(N=>N.capabilities)),m=F(E.capabilityCodes,`${u}/capabilityCodes`,2e3);Q(T)!==Q(m)&&f("NATIVE_PERSPECTIVE_CAPABILITY_PROJECTION_MISMATCH",`${u}/capabilityCodes`),E.default===!0?i+=1:E.default!==void 0&&f("NATIVE_PERSPECTIVE_DEFAULT_INVALID",`${u}/default`)}i>1&&f("NATIVE_PERSPECTIVE_DEFAULT_DUPLICATE","/config/perspectives");for(let[p,d]of e.backend.operations.entries()){let u=I(d,`/config/backend/operations/${p}`);o.has(u.capability)||f("NATIVE_CAPABILITY_REFERENCE_MISSING",`/config/backend/operations/${p}/capability`)}let c=new Set,_=new Set;for(let[p,d]of e.frontend.routes.entries()){let u=`/config/frontend/routes/${p}`,E=I(d,u),l=w(E.code,`${u}/code`);c.has(l)&&f("NATIVE_ROUTE_DUPLICATE",`${u}/code`),c.add(l);let A=de(E.path,`${u}/path`);_.has(A)&&f("NATIVE_ROUTE_PATH_DUPLICATE",`${u}/path`),_.add(A);let T=jt(E,u,e.appCode);T.capability&&!o.has(T.capability)&&f("NATIVE_CAPABILITY_REFERENCE_MISSING",`${u}/capability`);let m=E.access===void 0?void 0:I(E.access,`${u}/access`);for(let N of["allOf","anyOf"]){let b=m?.[N]===void 0?[]:$(m[N],`${u}/access/${N}`,50);for(let[R,g]of b.entries()){let C=Te(g,`${u}/access/${N}/${R}`,e.appCode);o.has(C)||f("NATIVE_CAPABILITY_REFERENCE_MISSING",`${u}/access/${N}/${R}`)}}}if(e.frontend.admin.access!==void 0){let p=st(e.frontend.admin.access,"/config/frontend/admin/access",e.appCode);for(let d of["allOf","anyOf"])for(let[u,E]of(p[d]||[]).entries())o.has(E)||f("NATIVE_CAPABILITY_REFERENCE_MISSING",`/config/frontend/admin/access/${d}/${u}`)}for(let[p,d]of e.frontend.routes.entries()){let u=I(d,`/config/frontend/routes/${p}`);u.parentCode&&!c.has(u.parentCode)&&f("NATIVE_ROUTE_PARENT_MISSING",`/config/frontend/routes/${p}/parentCode`)}}function pi(e){let t=new Set(e.authz.roles.map(_=>String(_.code))),o=e.authz.authenticatedUserRoleCode===void 0?"":w(e.authz.authenticatedUserRoleCode,"/config/authz/authenticatedUserRoleCode"),n=new Map(e.authz.scopeDimensions.map(_=>[String(_.code),{valueType:_.valueType==="uuid"?"uuid":"string",..._.valueSource?.resourceCode?{valueSourceResourceCode:String(_.valueSource.resourceCode)}:{}}])),s=new Set(n.keys()),r=new Map(e.data.resources.map((_,p)=>{let d=Oe(_,`/config/data/resources/${p}`,e.appCode);return[d.code,new Map(d.schema.fields.map(u=>[String(u.code),u]))]}));for(let[_,p]of e.authz.scopeDimensions.entries()){let d=`/config/authz/scopeDimensions/${_}`,u=I(p,d);if(O(u,["code","name","resourceCode","valueType","hierarchyMode","valueSource"],d,!0),u.valueSource===void 0)continue;let E=I(u.valueSource,`${d}/valueSource`);O(E,["kind","resourceCode","labelField","enabledField"],`${d}/valueSource`,!0),E.kind!=="native_resource"&&f("NATIVE_SCOPE_VALUE_SOURCE_KIND_INVALID",`${d}/valueSource/kind`),u.valueType!=="uuid"&&f("NATIVE_SCOPE_VALUE_SOURCE_TYPE_INVALID",`${d}/valueType`);let l=G(E.resourceCode,`${d}/valueSource/resourceCode`),A=r.get(l);A||f("NATIVE_SCOPE_VALUE_SOURCE_RESOURCE_MISSING",`${d}/valueSource/resourceCode`);let T=B(E.labelField,`${d}/valueSource/labelField`);if(["text.short","text.long"].includes(String(A.get(T)?.type||""))||f("NATIVE_SCOPE_VALUE_SOURCE_LABEL_FIELD_INVALID",`${d}/valueSource/labelField`),E.enabledField!==void 0){let m=B(E.enabledField,`${d}/valueSource/enabledField`);A.get(m)?.type!=="boolean"&&f("NATIVE_SCOPE_VALUE_SOURCE_ENABLED_FIELD_INVALID",`${d}/valueSource/enabledField`)}}let a=new Set,i=new Set;for(let[_,p]of e.authz.scopeSources.entries()){let d=`/config/authz/scopeSources/${_}`,u=I(p,d);O(u,["code","name","resourceCode","subject","grants","operationField","enabledField","effectiveFromField","effectiveToField","failureMode"],d,!0);let E=w(u.code,`${d}/code`);a.has(E)&&f("NATIVE_SCOPE_SOURCE_DUPLICATE",`${d}/code`),a.add(E),h(u.name,`${d}/name`,255);let l=G(u.resourceCode,`${d}/resourceCode`),A=r.get(l);A||f("NATIVE_SCOPE_SOURCE_RESOURCE_MISSING",`${d}/resourceCode`);let T=I(u.subject,`${d}/subject`),m=h(T.type,`${d}/subject/type`,32);O(T,m==="role_membership"?["type","userIdField","roleCode"]:["type","userIdField"],`${d}/subject`),["user","role_membership"].includes(m)||f("NATIVE_SCOPE_SOURCE_SUBJECT_INVALID",`${d}/subject/type`);let N=Le(T.userIdField,A);Dt(N)||f("NATIVE_SCOPE_SOURCE_SUBJECT_PATH_INVALID",`${d}/subject/userIdField`),m==="role_membership"&&!t.has(String(T.roleCode))&&f("NATIVE_ROLE_REFERENCE_MISSING",`${d}/subject/roleCode`);let b=new Set;for(let[R,g]of $(u.grants,`${d}/grants`,100).entries()){let C=`${d}/grants/${R}`,D=I(g,C);O(D,["dimensionCode","valueField","parentValueField"],C,!0);let y=w(D.dimensionCode,`${C}/dimensionCode`);(!s.has(y)||b.has(y))&&f("NATIVE_SCOPE_SOURCE_DIMENSION_INVALID",`${C}/dimensionCode`),b.add(y),u.failureMode==="last_known_good"&&i.add(y);for(let U of["valueField","parentValueField"]){if(D[U]===void 0)continue;let k=Le(D[U],A);mn(k,n.get(y),r)||f("NATIVE_SCOPE_SOURCE_GRANT_PATH_INVALID",`${C}/${U}`)}}b.size===0&&f("NATIVE_SCOPE_SOURCE_GRANT_REQUIRED",`${d}/grants`),["strict","last_known_good"].includes(u.failureMode)||f("NATIVE_SCOPE_SOURCE_FAILURE_MODE_INVALID",`${d}/failureMode`);for(let R of["operationField","enabledField","effectiveFromField","effectiveToField"]){if(u[R]===void 0)continue;let g=B(u[R],`${d}/${R}`);A.has(g)||f("NATIVE_SCOPE_SOURCE_FIELD_MISSING",`${d}/${R}`)}}Ai(e,t,r,o);let c=new Set;for(let[_,p]of e.authz.dataPolicies.entries()){let d=`/config/authz/dataPolicies/${_}`,u=I(p,d);O(u,["code","name","resourceCode","unrestrictedRoleCodes","operations","matchMode","rules","readExpression","writeBoundary"],d,!0);let E=w(u.code,`${d}/code`);c.has(E)&&f("NATIVE_DATA_POLICY_DUPLICATE",`${d}/code`),c.add(E);let l=u.readExpression!==void 0,A=F(u.operations||[],`${d}/operations`,4);u.operations!==void 0&&(A.length===0||A.some(g=>!["read","create","update","delete"].includes(g)))&&f("NATIVE_DATA_POLICY_OPERATIONS_INVALID",`${d}/operations`),["AND","OR"].includes(u.matchMode)||f("NATIVE_DATA_POLICY_MATCH_MODE_INVALID",`${d}/matchMode`),l&&u.operations!==void 0&&f("NATIVE_DATA_POLICY_READ_EXPRESSION_OPERATIONS_FORBIDDEN",`${d}/operations`);let T=e.data.resources.find(g=>g.dataPolicyCode===E),m=u.resourceCode||T?.code,N=m?r.get(G(m,`${d}/resourceCode`)):void 0;l&&!N&&f("NATIVE_DATA_POLICY_RESOURCE_MISSING",`${d}/resourceCode`);let b=F(u.unrestrictedRoleCodes||[],`${d}/unrestrictedRoleCodes`,100);u.unrestrictedRoleCodes!==void 0&&b.length===0&&f("NATIVE_DATA_POLICY_UNRESTRICTED_ROLES_INVALID",`${d}/unrestrictedRoleCodes`);for(let g of b)t.has(g)||f("NATIVE_ROLE_REFERENCE_MISSING",`${d}/unrestrictedRoleCodes`);let R;try{let g=$(u.rules,`${d}/rules`,100).map((C,D)=>({rule:I(C,`${d}/rules/${D}`),pointer:`${d}/rules/${D}`}));g.length===0?(!l||u.matchMode!=="AND"||u.writeBoundary!=="capability_only")&&f("NATIVE_DATA_POLICY_WRITE_BOUNDARY_REQUIRED",d):u.writeBoundary!==void 0&&f("NATIVE_DATA_POLICY_WRITE_BOUNDARY_INVALID",`${d}/writeBoundary`),R=[...g],l&&(R.push(...Ze(u.readExpression,`${d}/readExpression`)),Sn(u.readExpression,`${d}/readExpression`))}catch(g){throw g instanceof Ue&&f(g.code,g.pointer),g}for(let{rule:g,pointer:C}of R){O(g,["subject","dimensionCode","relationCode","resourceCode","field","roleCodes","operation","valuePath","emptyMatchesAll","operator","value","operand"],C,!0);let D=B(g.field,`${C}/field`),y=N?.get(D);l&&!y&&f("NATIVE_DATA_POLICY_FIELD_MISSING",`${C}/field`);for(let K of F(g.roleCodes||[],`${C}/roleCodes`,100))t.has(K)||f("NATIVE_ROLE_REFERENCE_MISSING",`${C}/roleCodes`);let U=String(g.operator||""),k=g.operand==="db_now",Y=["is_null","is_not_null"].includes(U),M=["eq","not_eq","in","not_in"].includes(U),le=!k&&(g.operator!==void 0||g.value!==void 0);if([g.subject==="current_user"?"current_user":"",typeof g.dimensionCode=="string"?"dimension":"",typeof g.relationCode=="string"?"relationship":"",le?"constant":"",k?"db_now":""].filter(Boolean).length!==1&&f("NATIVE_DATA_POLICY_RULE_SOURCE_INVALID",C),g.subject!==void 0&&g.subject!=="current_user"&&f("NATIVE_DATA_POLICY_SUBJECT_INVALID",`${C}/subject`),le){if(!M&&!Y&&f("NATIVE_DATA_POLICY_OPERATOR_INVALID",`${C}/operator`),["in","not_in"].includes(U)){let K=$(g.value,`${C}/value`,100).map((Ae,se)=>h(Ae,`${C}/value/${se}`,2048));(K.length===0||new Set(K).size!==K.length)&&f("NATIVE_DATA_POLICY_VALUE_INVALID",`${C}/value`)}else["eq","not_eq"].includes(U)?h(g.value,`${C}/value`,2048):(g.value!==void 0||g.operand!==void 0)&&f("NATIVE_DATA_POLICY_VALUE_INVALID",`${C}/value`);for(let K of["operation","valuePath","emptyMatchesAll","resourceCode","operand"])g[K]!==void 0&&f("NATIVE_DATA_POLICY_CONSTANT_RULE_INVALID",`${C}/${K}`)}if(k){(!["lt","lte","gt","gte"].includes(U)||g.value!==void 0||y?.type!=="datetime")&&f("NATIVE_DATA_POLICY_DB_NOW_INVALID",C);for(let K of["operation","valuePath","emptyMatchesAll","resourceCode","value"])g[K]!==void 0&&f("NATIVE_DATA_POLICY_DB_NOW_INVALID",`${C}/${K}`)}g.dimensionCode&&!s.has(g.dimensionCode)&&f("NATIVE_SCOPE_DIMENSION_MISSING",`${C}/dimensionCode`),i.has(String(g.dimensionCode||""))&&g.operation!=="read"&&f("NATIVE_SCOPE_SOURCE_LAST_KNOWN_GOOD_UNSAFE",`${C}/operation`)}}for(let[_,p]of e.data.resources.entries()){let d=I(p,`/config/data/resources/${_}`);d.dataPolicyCode&&!c.has(d.dataPolicyCode)&&f("NATIVE_DATA_POLICY_REFERENCE_MISSING",`/config/data/resources/${_}/dataPolicyCode`)}}function Ei(e){try{Kt(e.data.resources,"/config/data/resources")}catch(t){throw t instanceof _e&&f(t.code,t.pointer),t}}function Ai(e,t,o,n){let s=new Set;for(let[r,a]of e.authz.roleMembershipSources.entries()){let i=`/config/authz/roleMembershipSources/${r}`,c=I(a,i);O(c,["code","name","resourceCode","userIdField","roleCode","enabledField","effectiveFromField","effectiveToField","failureMode"],i,!0);let _=w(c.code,`${i}/code`);_.length>100&&f("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_CODE_INVALID",`${i}/code`),s.has(_)&&f("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_DUPLICATE",`${i}/code`),s.add(_),h(c.name,`${i}/name`,255);let p=Un(c.resourceCode,`${i}/resourceCode`,o);Mn(c.userIdField,`${i}/userIdField`,p),t.has(String(c.roleCode||""))||f("NATIVE_ROLE_REFERENCE_MISSING",`${i}/roleCode`),n&&c.roleCode===n&&f("NATIVE_AUTHENTICATED_USER_ROLE_SOURCE_CONFLICT",`${i}/roleCode`),jn(c,i,p)}for(let[r,a]of e.authz.relationshipGrantSources.entries()){let i=`/config/authz/relationshipGrantSources/${r}`,c=I(a,i);O(c,["code","name","resourceCode","subject","relationCode","targetResourceCode","resourceIdField","operations","enabledField","effectiveFromField","effectiveToField","failureMode"],i,!0);let _=w(c.code,`${i}/code`);_.length>100&&f("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_CODE_INVALID",`${i}/code`),s.has(_)&&f("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_DUPLICATE",`${i}/code`),s.add(_),h(c.name,`${i}/name`,255);let p=Un(c.resourceCode,`${i}/resourceCode`,o),d=I(c.subject,`${i}/subject`),u=h(d.type,`${i}/subject/type`,32);O(d,u==="role_membership"?["type","userIdField","roleCode"]:["type","userIdField"],`${i}/subject`),["user","role_membership"].includes(u)||f("NATIVE_AUTHORIZATION_PROJECTION_SUBJECT_INVALID",`${i}/subject/type`),Mn(d.userIdField,`${i}/subject/userIdField`,p),u==="role_membership"&&!t.has(String(d.roleCode||""))&&f("NATIVE_ROLE_REFERENCE_MISSING",`${i}/subject/roleCode`),w(c.relationCode,`${i}/relationCode`);let E=G(c.targetResourceCode,`${i}/targetResourceCode`);o.has(E)||f("NATIVE_AUTHORIZATION_PROJECTION_TARGET_RESOURCE_MISSING",`${i}/targetResourceCode`);let l=Le(c.resourceIdField,p),A=l?.field.type==="resource-ref.single"&&l.valuePath==="value"&&l.field.source?.resourceCode===E;(c.resourceIdField==="id"?E!==String(c.resourceCode):!A)&&f("NATIVE_AUTHORIZATION_PROJECTION_RESOURCE_ID_FIELD_INVALID",`${i}/resourceIdField`);let T=F(c.operations,`${i}/operations`,20);(T.length===0||T.some(m=>m.length>64||!/^[A-Za-z0-9][A-Za-z0-9:._*-]{0,63}$/.test(m)))&&f("NATIVE_AUTHORIZATION_PROJECTION_OPERATIONS_INVALID",`${i}/operations`),jn(c,i,p)}}function Un(e,t,o){let n=G(e,t),s=o.get(n);return s||f("NATIVE_AUTHORIZATION_PROJECTION_RESOURCE_MISSING",t),s}function Mn(e,t,o){let n=Le(e,o);Dt(n)||f("NATIVE_AUTHORIZATION_PROJECTION_USER_FIELD_INVALID",t)}function jn(e,t,o){if(e.failureMode!=="strict"&&f("NATIVE_AUTHORIZATION_PROJECTION_FAILURE_MODE_INVALID",`${t}/failureMode`),e.enabledField!==void 0){let n=B(e.enabledField,`${t}/enabledField`);o.get(n)?.type!=="boolean"&&f("NATIVE_AUTHORIZATION_PROJECTION_ENABLED_FIELD_INVALID",`${t}/enabledField`)}for(let n of["effectiveFromField","effectiveToField"]){if(e[n]===void 0)continue;let s=B(e[n],`${t}/${n}`);["date","datetime"].includes(String(o.get(s)?.type))||f("NATIVE_AUTHORIZATION_PROJECTION_EFFECTIVE_FIELD_INVALID",`${t}/${n}`)}}function Ii(e){let t=new Set,o=new Set;e.forEach((n,s)=>{let r=`/config/backend/secrets/${s}`,a=I(n,r);O(a,["name","env","description","required","exposure"],r,!0);let i=h(a.name,`${r}/name`,128),c=h(a.env,`${r}/env`,128);As.test(i)||f("NATIVE_SECRET_NAME_INVALID",`${r}/name`),(!Is.test(c)||c.startsWith("OPENXIANGDA_")||["NODE_ENV","PORT"].includes(c))&&f("NATIVE_SECRET_ENV_INVALID",`${r}/env`),t.has(i)&&f("NATIVE_SECRET_NAME_DUPLICATE",`${r}/name`),o.has(c)&&f("NATIVE_SECRET_ENV_DUPLICATE",`${r}/env`),t.add(i),o.add(c),L(a.exposure,"active_only",`${r}/exposure`),a.required!==void 0&&we(a.required,`${r}/required`),a.description!==void 0&&Bt(a.description,`${r}/description`,2e3)})}function mi(e){let t=new Set,o=new Map,n=new Map(e.data.resources.map(u=>[String(u.code),u])),s=new Map(e.frontend.routes.map((u,E)=>{let l=I(u,`/config/frontend/routes/${E}`);return[w(l.code,`/config/frontend/routes/${E}/code`),l]}));for(let[u,E]of e.workflows.definitions.entries()){let l=`/config/workflows/definitions/${u}`,A=I(E,l);if(O(A,["version","definition","launch"],l,["detailRouteCode"]),so(A.launch,`${l}/launch`),A.detailRouteCode!==void 0){let b=io(A.detailRouteCode,`${l}/detailRouteCode`);for(let[R,g,C]of[["desktop",b.desktop,["admin","user"]],["mobile",b.mobile,["user"]]]){let D=`${l}/detailRouteCode/${R}`,y=s.get(g);y||f("NATIVE_WORKFLOW_DETAIL_ROUTE_MISSING",D),C.some(Y=>Y===y.surface)||f("NATIVE_WORKFLOW_DETAIL_ROUTE_SURFACE_INVALID",D);let U=de(y.path,D),k=[...U.matchAll(/:([A-Za-z][A-Za-z0-9_]*)/g)].map(Y=>Y[1]);(U.includes("*")||k.length!==1||k[0]!=="instanceId")&&f("NATIVE_WORKFLOW_DETAIL_ROUTE_PATH_INVALID",D)}}let T=I(A.definition,`${l}/definition`),m=`${T.code}:${Ve(A.version,`${l}/version`)}`;t.has(m)&&f("NATIVE_WORKFLOW_DEFINITION_DUPLICATE",l),t.add(m),Ni(T,`${l}/definition`),Ti(T.subject,n,`${l}/definition/subject`);let N=Rn(T,{appCode:e.appCode,capabilities:e.authz.capabilities.map(b=>b.code),fields:new Map((n.get(T.subject.resourceCode)?.schema.fields||[]).map(b=>[b.code,b]))});N.length&&f("NATIVE_WORKFLOW_INSTANCE_COMMAND_POLICY_INVALID",`${l}/definition/instanceCommands`,{errors:N}),T.title===T.code&&f("NATIVE_WORKFLOW_USER_TITLE_REQUIRED",`${l}/definition/title`),o.set(m,T)}let r=new Set,a=new Map;for(let[u,E]of e.workflows.bindings.entries()){let l=I(E,`/config/workflows/bindings/${u}`),A=I(l.binding,`/config/workflows/bindings/${u}/binding`),T=`${A.workflowCode}:${Ve(l.version,`/config/workflows/bindings/${u}/version`)}`;r.has(T)&&f("NATIVE_WORKFLOW_BINDING_DUPLICATE",`/config/workflows/bindings/${u}`),r.add(T),gi(A,`/config/workflows/bindings/${u}/binding`),a.set(T,A)}let i=new Set,c=new Map;for(let[u,E]of e.workflows.activations.entries()){let l=`/config/workflows/activations/${u}`,A=I(E,l);O(A,["workflowCode","definitionVersion","bindingVersion","acceptedCommandDeactivationPolicy"],l,["environmentKey"]);let T=w(A.workflowCode,`${l}/workflowCode`);i.has(T)&&f("NATIVE_WORKFLOW_ACTIVATION_DUPLICATE",l),i.add(T);let m=`${T}:${Ve(A.definitionVersion,`${l}/definitionVersion`)}`,N=`${T}:${Ve(A.bindingVersion,`${l}/bindingVersion`)}`;t.has(m)||f("NATIVE_WORKFLOW_DEFINITION_REFERENCE_MISSING",`${l}/definitionVersion`),r.has(N)||f("NATIVE_WORKFLOW_BINDING_REFERENCE_MISSING",`${l}/bindingVersion`);let b=o.get(m),R=a.get(N);(!["finish-pinned","cancel-on-deactivate"].includes(A.acceptedCommandDeactivationPolicy)||A.acceptedCommandDeactivationPolicy!==b.acceptedCommandDeactivationPolicy)&&f("NATIVE_WORKFLOW_COMMAND_DEACTIVATION_POLICY_MISMATCH",`${l}/acceptedCommandDeactivationPolicy`),Ci(b,R,`/config/workflows/activations/${u}`),c.set(T,R)}let _=new Set;e.workflows.providers.forEach((u,E)=>{let l=`/config/workflows/providers/${E}`,A=I(u,l);O(A,["code","endpointPath","timeoutMs"],l,!0);let T=w(A.code,`${l}/code`);_.has(T)&&f("NATIVE_WORKFLOW_PROVIDER_DUPLICATE",`${l}/code`),_.add(T),de(A.endpointPath,`${l}/endpointPath`),A.timeoutMs!==void 0&&Z(A.timeoutMs,`${l}/timeoutMs`,100,1e4)});for(let[u,E]of c.entries())for(let[l,A]of Object.entries(I(E.bindings,"/config/workflows/bindings/*/binding/bindings"))){let T=I(A,`/config/workflows/${u}/bindings/${l}`);T.provider==="application_provider"&&!_.has(T.providerCode)&&f("NATIVE_WORKFLOW_PROVIDER_REFERENCE_MISSING",`/config/workflows/${u}/bindings/${l}/providerCode`)}let p=new Set(e.authz.roles.map(u=>u.code)),d=new Set;e.workflows.editableParameters.forEach((u,E)=>{let l=`/config/workflows/editableParameters/${E}`,A=I(u,l);O(A,["code","workflowCode","bindingKey","label","valueType","required","allowedRoleCodes","allowedProviderCodes","maxItems"],l,!0);let T=w(A.code,`${l}/code`);d.has(T)&&f("NATIVE_WORKFLOW_EDITABLE_PARAMETER_DUPLICATE",`${l}/code`),d.add(T);let m=it(A.workflowCode,`${l}/workflowCode`),N=Jt(A.bindingKey,`${l}/bindingKey`),b=c.get(m);(!b||!I(b.bindings,`${l}/bindingKey`)[N])&&f("NATIVE_WORKFLOW_EDITABLE_BINDING_MISSING",`${l}/bindingKey`),h(A.label,`${l}/label`,255),["role_code","user_ids","provider_code"].includes(A.valueType)||f("NATIVE_WORKFLOW_EDITABLE_VALUE_TYPE_INVALID",`${l}/valueType`);for(let R of F(A.allowedRoleCodes||[],`${l}/allowedRoleCodes`,100))p.has(R)||f("NATIVE_ROLE_REFERENCE_MISSING",`${l}/allowedRoleCodes`);for(let R of F(A.allowedProviderCodes||[],`${l}/allowedProviderCodes`,100))_.has(R)||f("NATIVE_WORKFLOW_PROVIDER_REFERENCE_MISSING",`${l}/allowedProviderCodes`);A.required!==void 0&&we(A.required,`${l}/required`),A.maxItems!==void 0&&Z(A.maxItems,`${l}/maxItems`,1,200)})}function Ti(e,t,o){let n=I(e,o);O(n,["resourceCode","factProjection"],o,["summaryFields"]);let s=G(n.resourceCode,`${o}/resourceCode`),r=t.get(s);r||f("NATIVE_WORKFLOW_SUBJECT_RESOURCE_MISSING",`${o}/resourceCode`);let a=new Set($(I(r.schema,`${o}/resourceCode`).fields,`${o}/resourceCode`,500).map((_,p)=>B(I(_,`${o}/resourceCode/${p}`).code,`${o}/resourceCode/${p}`))),i=I(n.factProjection,`${o}/factProjection`),c=Object.entries(i);(c.length<1||c.length>64)&&f("NATIVE_WORKFLOW_SUBJECT_FACT_PROJECTION_INVALID",`${o}/factProjection`);for(let[_,p]of c){Ns.test(_)||f("NATIVE_WORKFLOW_SUBJECT_FACT_KEY_INVALID",`${o}/factProjection/${_}`);let d=B(p,`${o}/factProjection/${_}`);a.has(d)||f("NATIVE_WORKFLOW_SUBJECT_FIELD_MISSING",`${o}/factProjection/${_}`)}if(n.summaryFields!==void 0){let _=F(n.summaryFields,`${o}/summaryFields`,gs).map((l,A)=>B(l,`${o}/summaryFields/${A}`)),p=t.get(s),d=p.surface&&typeof p.surface=="object"&&!Array.isArray(p.surface)?p.surface:{},u=d.fields&&typeof d.fields=="object"&&!Array.isArray(d.fields)?d.fields:{},E=new Map($(I(p.schema,`${o}/resourceCode`).fields,`${o}/resourceCode`,500).map((l,A)=>{let T=I(l,`${o}/resourceCode/${A}`);return[String(T.code),T]}));for(let[l,A]of _.entries()){let T=E.get(A),m=u[A],N=String(T?.type||""),b=T?.maxLength;(!T||T.system===!0||m&&typeof m=="object"&&!Array.isArray(m)&&m.system===!0||["id","revision","created_by","updated_by","created_at","updated_at"].includes(A)||!bs.has(N)||N==="text.long"&&typeof b=="number"&&Number.isFinite(b)&&b>Cs)&&f("NATIVE_WORKFLOW_SUBJECT_SUMMARY_FIELDS_INVALID",`${o}/summaryFields/${l}`)}}}function Ni(e,t){O(e,["schemaVersion","code","title","subject","acceptedCommandDeactivationPolicy","startAt","inputSchema","nodes"],t,["organizationContext","instanceCommands"]),L(e.schemaVersion,"openxiangda.workflow-definition/v2",`${t}/schemaVersion`),it(e.code,`${t}/code`),h(e.title,`${t}/title`,255),["finish-pinned","cancel-on-deactivate"].includes(e.acceptedCommandDeactivationPolicy)||f("NATIVE_WORKFLOW_COMMAND_DEACTIVATION_POLICY_REQUIRED",`${t}/acceptedCommandDeactivationPolicy`);let o=I(e.nodes,`${t}/nodes`),n=Object.keys(o);(n.length===0||n.length>200)&&f("NATIVE_WORKFLOW_NODE_COUNT_INVALID",`${t}/nodes`);let s=h(e.startAt,`${t}/startAt`,128);o[s]||f("NATIVE_WORKFLOW_START_NODE_MISSING",`${t}/startAt`);let r=new Map;for(let[_,p]of Object.entries(o)){let d=`${t}/nodes/${_}`,u=I(p,d);L(u.id,_,`${d}/id`),["approval","condition","end"].includes(u.kind)||f("NATIVE_WORKFLOW_NODE_KIND_INVALID",`${d}/kind`);let E=[];if(u.kind==="approval"){h(u.title,`${d}/title`,255),Jt(u.binding,`${d}/binding`),["single","any","all","sequence"].includes(u.mode)||f("NATIVE_WORKFLOW_APPROVAL_MODE_INVALID",`${d}/mode`),E.push(h(u.onApprove,`${d}/onApprove`,128),h(u.onReject,`${d}/onReject`,128));for(let l of F(u.returnTargets||[],`${d}/returnTargets`,200))o[l]||f("NATIVE_WORKFLOW_TARGET_MISSING",`${d}/returnTargets`);for(let l of F(u.allowedOperations||[],`${d}/allowedOperations`,20))Rs.has(l)||f("NATIVE_WORKFLOW_OPERATION_INVALID",`${d}/allowedOperations`)}else if(u.kind==="condition"){let l=$(u.branches,`${d}/branches`,100);l.length===0&&f("NATIVE_WORKFLOW_BRANCH_REQUIRED",`${d}/branches`),l.forEach((A,T)=>{let m=I(A,`${d}/branches/${T}`);Me(m.when,`${d}/branches/${T}/when`,0),E.push(h(m.target,`${d}/branches/${T}/target`,128))}),E.push(h(u.otherwise,`${d}/otherwise`,128))}else h(u.title,`${d}/title`,255),h(u.outcome,`${d}/outcome`,128);for(let l of E)o[l]||f("NATIVE_WORKFLOW_TARGET_MISSING",d);r.set(_,E)}let a=new Set,i=new Set,c=_=>{if(i.has(_)&&f("NATIVE_WORKFLOW_CYCLE_FORBIDDEN",`${t}/nodes/${_}`),!a.has(_)){a.add(_),i.add(_);for(let p of r.get(_)||[])c(p);i.delete(_)}};c(s),a.size!==n.length&&f("NATIVE_WORKFLOW_NODE_UNREACHABLE",`${t}/nodes`)}function Me(e,t,o){o>20&&f("NATIVE_WORKFLOW_EXPRESSION_DEPTH_EXCEEDED",t);let n=I(e,t),s=h(n.op,`${t}/op`,16);if(s!=="literal"){if(s==="path"){let r=h(n.path,`${t}/path`,255);/^[A-Za-z][A-Za-z0-9_.]{0,254}$/.test(r)||f("NATIVE_WORKFLOW_EXPRESSION_PATH_INVALID",`${t}/path`);return}if(["eq","neq","gt","gte","lt","lte","in","contains"].includes(s)){Me(n.left,`${t}/left`,o+1),Me(n.right,`${t}/right`,o+1);return}if(["and","or"].includes(s)){let r=$(n.values,`${t}/values`,100);r.length===0&&f("NATIVE_WORKFLOW_EXPRESSION_EMPTY",`${t}/values`),r.forEach((a,i)=>Me(a,`${t}/values/${i}`,o+1));return}if(["not","exists"].includes(s)){Me(n.value,`${t}/value`,o+1);return}f("NATIVE_WORKFLOW_EXPRESSION_OPERATOR_INVALID",`${t}/op`)}}function gi(e,t){L(e.schemaVersion,"openxiangda.workflow-binding/v2",`${t}/schemaVersion`),it(e.workflowCode,`${t}/workflowCode`);let o=I(e.bindings,`${t}/bindings`);Object.keys(o).length>200&&f("NATIVE_WORKFLOW_BINDING_LIMIT_EXCEEDED",`${t}/bindings`);for(let[n,s]of Object.entries(o)){Jt(n,`${t}/bindings/${n}`);let r=I(s,`${t}/bindings/${n}`),a=h(r.provider,`${t}/bindings/${n}/provider`,64);["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)||f("NATIVE_WORKFLOW_BINDING_PROVIDER_INVALID",`${t}/bindings/${n}/provider`),a==="fixed_users"&&$(r.users,`${t}/bindings/${n}/users`,200).length===0&&f("NATIVE_WORKFLOW_BINDING_USERS_REQUIRED",`${t}/bindings/${n}/users`),["input_users","form_field_users"].includes(a)&&h(r.inputPath,`${t}/bindings/${n}/inputPath`,255),["app_role","app_role_in_scope","initiator_select"].includes(a)&&w(r.roleCode,`${t}/bindings/${n}/roleCode`),a==="department_supervisor"&&h(r.departmentIdFrom,`${t}/bindings/${n}/departmentIdFrom`,255),a==="application_provider"&&w(r.providerCode,`${t}/bindings/${n}/providerCode`)}}function Ci(e,t,o){L(t.workflowCode,e.code,`${o}/workflowCode`);let n=I(t.bindings,`${o}/bindings`);for(let[s,r]of Object.entries(I(e.nodes,`${o}/nodes`))){let a=I(r,`${o}/nodes/${s}`);a.kind==="approval"&&!n[a.binding]&&f("NATIVE_WORKFLOW_BINDING_REFERENCE_MISSING",`${o}/nodes/${s}/binding`)}}function bi(e,t,o){let n=I(t.routeManifest,"/contracts/routeManifest"),s=I(e.routeManifest,"/contracts/routeManifest"),r=new Map;for(let p of $(o.data?.resources,"/config/data/resources",100)){let d=I(p,"/config/data/resources");r.set(String(d.code||""),d)}let a=new Set($(s.routes,"/contracts/routeManifest/routes",1e3).map(p=>String(I(p,"/contracts/routeManifest/routes").code||""))),i=[];for(let p of $(n.routes,"/contracts/routeManifest/routes",1e3)){let d=I(p,"/contracts/routeManifest/routes"),u=String(d.kind||"");if(u!=="resource-records"&&u!=="resource-submit")continue;let E=String(d.resourceCode||""),l=r.get(E);l||f("NATIVE_ROUTE_MANIFEST_RESOURCE_UNKNOWN","/contracts/routeManifest/routes");let T=`user.${E}.${u==="resource-records"?"records":"submit"}`;L(String(d.code||""),T,"/contracts/routeManifest/routes/code");let m=u==="resource-records"?"read":"create",N=String(I(l.capabilities,"/config/data/resources/capabilities")[m]||"");for(let b of["desktop","mobile"]){let R=I(d[b],`/contracts/routeManifest/routes/${b}`),g=b==="mobile"?"/m/my/":"/my/",C=u==="resource-records"?`${g}${E}`:`${g}${E}/submit`;L(String(R.path||""),C,`/contracts/routeManifest/routes/${b}/path`),L(String(R.capability||""),N,`/contracts/routeManifest/routes/${b}/capability`),L(String(R.routeCode||""),`${T}.${b}`,`/contracts/routeManifest/routes/${b}/routeCode`)}(a.has(T)||i.some(b=>String(b.code)===T))&&f("NATIVE_ROUTE_MANIFEST_DUPLICATE","/contracts/routeManifest/routes/code"),i.push(d)}if(!i.length)return;s.routes=$([...s.routes,...i],"/contracts/routeManifest/routes",1e3).sort((p,d)=>re(String(I(p,"x").code||""),String(I(d,"x").code||"")));let c=String(I(n.rootEntry,"x").code||"");if(i.find(p=>String(p.code)===c&&p.kind==="resource-records")){let p=I(n.rootEntry,"x");s.rootEntry={code:c,desktop:String(p.desktop||""),mobile:String(p.mobile||"")}}s.digest=ee({schemaVersion:s.schemaVersion,appCode:s.appCode,devicePolicy:s.devicePolicy,rootEntry:s.rootEntry,authentication:s.authentication,routes:s.routes})}function Oe(e,t,o){let n=I(e,t);O(n,["schemaVersion","appCode","code","name","schema","surface","invariants","decimalReservationLifecycle","capabilities","dataPolicyCode","fieldPolicies"],t,!0),L(n.schemaVersion,"openxiangda.data-resource/v2",`${t}/schemaVersion`),L(n.appCode,o,`${t}/appCode`);let s=G(n.code,`${t}/code`),r=h(n.name,`${t}/name`,255),a=I(n.schema,`${t}/schema`);O(a,["fields"],`${t}/schema`);let i,c,_;try{_=$t(n.decimalReservationLifecycle,`${t}/decimalReservationLifecycle`),i=ft(a.fields,`${t}/schema/fields`),c=Ht(n.invariants,i,`${t}/invariants`),gt(n.surface,i,`${t}/surface`)}catch(E){throw(E instanceof _e||E instanceof De)&&f(E.code,E.pointer),E}let p=new Set(i.map(E=>E.code)),d=I(n.capabilities,`${t}/capabilities`);O(d,["read","create","update","delete"],`${t}/capabilities`);let u=I(n.fieldPolicies,`${t}/fieldPolicies`);for(let[E,l]of Object.entries(u)){!p.has(E)&&!Fe(E)&&f("NATIVE_DATA_FIELD_POLICY_FIELD_MISSING",`${t}/fieldPolicies/${E}`);let A=`${t}/fieldPolicies/${E}`,T=I(l,A);Fe(E)&&(O(T,["read"],A,!0),(!Array.isArray(T.read)||T.read.length>20||T.read.some(m=>typeof m!="string"||!m.trim())||new Set(T.read).size!==T.read.length)&&f("NATIVE_DATA_AUDIT_READ_POLICY_INVALID",`${A}/read`)),O(T,["read","create","update","mask"],A,!0),T.mask!==void 0&&!["omit","null"].includes(T.mask)&&f("NATIVE_DATA_FIELD_POLICY_MASK_INVALID",`${A}/mask`)}return{...n,code:s,name:r,schema:{fields:i},...n.invariants===void 0?{}:{invariants:c},..._?{decimalReservationLifecycle:_}:{},capabilities:d,fieldPolicies:u}}function ro(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 Bn(e,t,o,n){let s=e.toString("utf8"),r;try{r=JSON.parse(s)}catch{f(o,t)}let a=I(r,t);return Q(a)!==s&&f(n,t),a}function Jn(e,t){let o=0,n=(s,r,a)=>{if(o+=1,o>Ds&&f("NATIVE_ARTIFACT_NODE_LIMIT_EXCEEDED",r),a>Ss&&f("NATIVE_ARTIFACT_DEPTH_LIMIT_EXCEEDED",r),typeof s=="string"){Buffer.byteLength(s)>Ft&&f("NATIVE_ARTIFACT_STRING_LIMIT_EXCEEDED",r);return}if(Array.isArray(s)){s.forEach((i,c)=>n(i,`${r}/${c}`,a+1));return}if(!(!s||typeof s!="object"))for(let[i,c]of Object.entries(s))["__proto__","prototype","constructor"].includes(i)&&f("NATIVE_ARTIFACT_DANGEROUS_KEY",`${r}/${i}`),Oi(i)&&f("NATIVE_ARTIFACT_RUNTIME_FIELD_FORBIDDEN",`${r}/${i}`),n(c,`${r}/${i}`,a+1)};n(e,t,0)}function Oi(e){return["environmentKey","environmentId","secretValue","ciphertext","oauthClient","oauthClientId","oauthClientSecret","signingSecret","kubernetesNamespace","nodePort","productionUrl"].includes(e)}function ye(e){return{value:e,digest:ee(e)}}function Wn(e,t,o,n){typeof e!="string"&&!Buffer.isBuffer(e)&&!(e instanceof Uint8Array)&&f("NATIVE_ARTIFACT_BYTES_REQUIRED",o);let s=Buffer.isBuffer(e)?e:Buffer.from(e);return s.byteLength===0&&f("NATIVE_ARTIFACT_EMPTY",o),s.byteLength>t&&f(n,o),s}function Gn(e,t,o,n){let s=nt.createHash("sha256").update(e).digest("hex");nt.timingSafeEqual(Buffer.from(s),Buffer.from(t))||f(n,o)}function I(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&f("NATIVE_OBJECT_REQUIRED",t),e}function $(e,t,o){return Array.isArray(e)||f("NATIVE_ARRAY_REQUIRED",t),e.length>o&&f("NATIVE_ARRAY_LIMIT_EXCEEDED",t),e}function F(e,t,o){let n=$(e,t,o).map((s,r)=>h(s,`${t}/${r}`,255));return new Set(n).size!==n.length&&f("NATIVE_ARRAY_DUPLICATE",t),n}function h(e,t,o){return(typeof e!="string"||e.length===0||e.length>o)&&f("NATIVE_STRING_INVALID",t),e}function Bt(e,t,o){return(typeof e!="string"||e.length>o)&&f("NATIVE_STRING_INVALID",t),e}function w(e,t){let o=h(e,t,128);return fs.test(o)||f("NATIVE_CODE_INVALID",t),o}function G(e,t){let o=h(e,t,64);return ps.test(o)||f("NATIVE_RESOURCE_CODE_INVALID",t),o}function B(e,t){let o=h(e,t,63);return Es.test(o)||f("NATIVE_FIELD_CODE_INVALID",t),o}function it(e,t){let o=h(e,t,128);return ms.test(o)||f("NATIVE_WORKFLOW_CODE_INVALID",t),o}function Jt(e,t){let o=h(e,t,128);return Ts.test(o)||f("NATIVE_WORKFLOW_BINDING_CODE_INVALID",t),o}function Te(e,t,o){let n=h(e,t,255);return us.test(n)||f("NATIVE_CAPABILITY_CODE_INVALID",t),!n.startsWith(`app:${o}:`)&&!ro(o).some(s=>s.code===n)&&f("NATIVE_CAPABILITY_APP_MISMATCH",t),n}function de(e,t){let o=h(e,t,2048);return(!o.startsWith("/")||o.startsWith("//")||o.includes("..")||o.includes("?")||o.includes("#"))&&f("NATIVE_ABSOLUTE_PATH_INVALID",t),o}function Ve(e,t){return(!Number.isInteger(e)||Number(e)<1)&&f("NATIVE_POSITIVE_INTEGER_REQUIRED",t),Number(e)}function Z(e,t,o,n){return(!Number.isInteger(e)||Number(e)<o||Number(e)>n)&&f("NATIVE_INTEGER_OUT_OF_RANGE",t),Number(e)}function we(e,t){return typeof e!="boolean"&&f("NATIVE_BOOLEAN_REQUIRED",t),e}function xt(e,t){let o=h(e,t,64).toLowerCase();return ds.test(o)||f("NATIVE_DIGEST_INVALID",t),o}function L(e,t,o){e!==t&&f("NATIVE_VALUE_MISMATCH",o)}function O(e,t,o,n=!1){let s=new Set([...t,...Array.isArray(n)?n:[]]);for(let r of Object.keys(e))s.has(r)||f("NATIVE_PROPERTY_UNKNOWN",`${o}/${r}`);if(n!==!0)for(let r of t)Object.prototype.hasOwnProperty.call(e,r)||f("NATIVE_PROPERTY_REQUIRED",`${o}/${r}`)}function X(e,t){return[...e].sort((o,n)=>re(t(o),t(n)))}function j(e){return[...new Set(e)].sort(re)}function zn(e){return[...new Set(e)].sort((t,o)=>t-o)}function re(e,t){return e===t?0:e<t?-1:1}function ao(e){return!e||typeof e!="object"||Object.isFrozen(e)||(Object.freeze(e),Object.values(e).forEach(t=>ao(t))),e}function Ut(e,t,o){if(wt(e,t))return o;if(Array.isArray(e)&&Array.isArray(t)){let n=Math.max(e.length,t.length);for(let s=0;s<n;s+=1)if(!wt(e[s],t[s]))return Ut(e[s],t[s],`${o}/${s}`)}if(e&&t&&typeof e=="object"&&typeof t=="object"&&!Array.isArray(e)&&!Array.isArray(t)){let n=j([...Object.keys(e),...Object.keys(t)]);for(let s of n){let r=e[s],a=t[s];if(!wt(r,a))return Ut(r,a,`${o}/${s}`)}}return o}function wt(e,t){return e===void 0||t===void 0?e===t:Q(e)===Q(t)}function f(e,t,o={}){throw new Lt(e,t,o)}var jr="36faf8533590277affdd3db8582a251e242ca9aa4a4451067060e171127f0abe";export{Xt as DATA_AUDIT_METADATA_FIELDS,Pt as DATA_EVENT_TYPES_V2,Co as DATA_SYSTEM_SORT_FIELD_CODES,jr as NATIVE_CONFIGURATION_VALIDATOR_DIGEST,q as NATIVE_CONTRACT_CAPACITY_V2,gr as NATIVE_DATA_POLICY_EXPRESSION_MAX_CLAUSES,mr as NATIVE_DATA_POLICY_EXPRESSION_MAX_DEPTH,Tr as NATIVE_DATA_POLICY_EXPRESSION_MAX_GROUP_ITEMS,Nr as NATIVE_DATA_POLICY_EXPRESSION_MAX_LEAVES,Cr as NATIVE_DATA_POLICY_EXPRESSION_MAX_OCCURRENCES,bo as NATIVE_DATA_QUERY_OPERATORS_V2,Lt as NativeConfigurationCompilerError,_e as NativeDataFieldContractV2Error,Ue as NativeDataPolicyExpressionV2Error,De as NativeDecimalLifecycleContractError,yt as NativeEventActionContractError,St as NativeScopeSourceFieldPathV2Error,uo as OPENXIANGDA_NATIVE_DATA_FIELD_TYPES_V2,Ne as OPENXIANGDA_NATIVE_DATA_SURFACE_KEYS_V2,mt as OPENXIANGDA_NATIVE_DRAFT_STATE_KEYS_V2,ut as OPENXIANGDA_NATIVE_SYSTEM_FIELDS_V2,hi as OPENXIANGDA_NATIVE_SYSTEM_FIELD_MAP_V2,vt as WORKFLOW_EVENT_TYPES_V2,Ur as compileNativeApplicationConfiguration,bn as compileNativeEventAction,Fs as compileNativeEventCapturePlansV2,ws as compileRequiredPlatformCapabilitiesV3,Qt as hasDataAuditReadPolicy,Fe as isDataAuditMetadataField,Zt as isDataSystemSortField,Vi as isNativeDataQueryOperatorV2,Ge as isNativeMultiValueFieldV2,cr as materializeNativeDataQueryPathTypesV2,Ze as nativeDataPolicyExpressionLeavesV2,Sn as nativeDataPolicyExpressionToCnfV2,dr as nativeDataQueryPathPlanV2,Fi as nativeFieldAggregatePlanV2,Xi as nativeFieldColumnDefinitionV2,Qi as nativeFieldDefaultSqlV2,Zi as nativeFieldHasDefaultV2,or as nativeFieldIndexStatementsV2,ze as nativeFieldRequiresCreateInputV2,nr as nativeFieldSequenceGrantStatementsV2,tr as nativeFieldSequenceOwnershipStatementsV2,er as nativeFieldSequenceStatementsV2,on as nativeFieldSupportsFilterV2,wi as nativeFieldSupportsOperatorV2,At as nativeFieldSupportsSearchV2,ve as nativeFieldSupportsSortV2,nn as nativeOperatorsForFieldV2,Go as nativePhysicalFieldV2,Hi as nativePhysicalFieldsV2,ge as nativePhysicalObjectNameV2,rr as nativeScopeSourceFieldValueV2,mn as nativeScopeSourceGrantPathSupportedV2,Dt as nativeScopeSourceSubjectPathSupportedV2,sr as nativeSubtableConstraintStatementsV2,$t as parseDecimalReservationLifecycle,ft as parseNativeDataFieldsV2,Ht as parseNativeDataResourceInvariantsV2,Ct as projectNativeDataResourceViewV2,oe as quoteNativeIdentifierV2,Le as resolveNativeScopeSourceFieldPathV2,fn as validateDecimalReservationLifecycles,an as validateNativeDataDraftStateV2,Kt as validateNativeDataResourceReferencesV2,gt as validateNativeDataResourceSurfaceV2,Rn as validateWorkflowInstanceCommandPolicies,Er as workflowInstanceCommandDeadlineError,pr as workflowInstanceTerminateCapabilityAllowed,On as workflowPolicyTimestamp};
|
|
8
|
+
END $native_subtable$`]}function Ce(e,...t){return`${e}_${Xo("sha256").update(t.join(":")).digest("hex").slice(0,32)}`}function se(e){if(!/^[A-Za-z_][A-Za-z0-9_]{0,62}$/.test(e))throw new Error("OPENXIANGDA_NATIVE_IDENTIFIER_INVALID");return`"${e}"`}function os(e,t){return e.type==="subtable"?"none":t?"gin-trigram":e.indexed?["date-range","datetime-range"].includes(e.type)?"gist-range":wt.has(e.type)?"btree-snapshot-expressions":Qo.has(e.type)?"gin-jsonb-path":"btree":"none"}function ss(e){switch(e.type){case"text.short":return`varchar(${e.maxLength??255})`;case"text.long":case"text.rich":return"text";case"number.integer":return"bigint";case"number.decimal":return`numeric(${e.precision??38},${e.scale??10})`;case"boolean":return"boolean";case"date":return"date";case"time":return"time(0)";case"datetime":return"timestamptz";case"date-range":return"daterange";case"datetime-range":return"tstzrange";case"uuid":return"uuid";case"serial-number":return"varchar(255)";case"subtable":return"child-resource";default:return es.has(e.type),"jsonb"}}function bn(e,t){if(Ye(t.type)&&t.type!=="subtable")return"'[]'::jsonb";if(t.type!=="serial-number")return"";let o=Tn(t.serial?.prefix||""),n=t.serial?.digits??6;return`(${o} || lpad(nextval(${Tn(tt(e,t.code))})::text, ${n}, '0'))`}function is(e,t){return Cn.has(t.type)?` CHECK (${e} IS NULL OR jsonb_typeof(${e}) = 'array')`:Zo.has(t.type)?` CHECK (${e} IS NULL OR jsonb_typeof(${e}) = 'object')`:""}function et(e){return`"app_data".${se(e)}`}function tt(e,t){let o=Ce("seq",e,t);return`"app_data".${se(o)}`}function Tn(e){return`'${e.replace(/'/g,"''")}'`}var On=new Set(["option.single","option.multiple","user.single","user.multiple","department.single","department.multiple","resource-ref.single","resource-ref.multiple"]),rs=new Set([...On,"cascade.single","cascade.multiple","file","image","signature","address","location","json"]),yn=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,as=new Set(["__proto__","prototype","constructor"]),Ft=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 xe(e,t){let o=Rn(e);if(!o)return null;let n=t.get(o[0]);if(!n)return null;let s=o.slice(1).join(".")||void 0;return{field:n,...s?{valuePath:s}:{}}}function vt(e){return!!(e&&e.field.type==="user.single"&&e.valuePath==="value")}function $n(e,t,o){if(!e||!t||!cs(e))return!1;let{field:n,valuePath:s}=e;if(!s)return t.valueType==="uuid"?n.type==="uuid":["text.short","text.long","serial-number"].includes(n.type);if(s==="value")return!(t.valueSourceResourceCode&&n.type.startsWith("resource-ref.")&&n.source?.resourceCode!==t.valueSourceResourceCode);let i=s.slice(9),r=o.get(n.source?.resourceCode||"")?.get(i)?.type;return t.valueType==="uuid"?r==="uuid":["text.short","text.long","serial-number"].includes(r||"")}function Ir(e,t){let o=Rn(t);if(!o)throw new Ft(String(t||""));let n=e;for(let s of o){if(!n||typeof n!="object"||!Object.prototype.hasOwnProperty.call(n,s))return;n=n[s]}return n}function cs(e){let{field:t,valuePath:o}=e;if(!o)return!rs.has(t.type);if(o==="value")return On.has(t.type);if(!o.startsWith("snapshot."))return!1;let n=o.slice(9);return yn.test(n)&&t.type.startsWith("resource-ref.")&&!!t.source?.snapshotFields?.includes(n)}function Rn(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=>!yn.test(o)||as.has(o))||t.length===2&&t[1]!=="value"||t.length===3&&t[1]!=="snapshot"?null:t}var ds=new Set(["option.single","user.single","department.single","resource-ref.single"]),ls=new Set(["text.short","text.long","text.rich","number.integer","number.decimal","boolean","date","time","datetime","uuid","serial-number"]),us=new Set(["value","label","description","color"]),fs=new Set(["avatarUrl","employeeNo","title","mobile","email"]),ps=new Set(["fullPath","parent.value","parent.label"]),_s=new Set(["country.value","country.label","province.value","province.label","city.value","city.label","district.value","district.label","street.value","street.label","detail","fullAddress"]),Es=new Set(["longitude","latitude","accuracy"]),As=new Set(["address","name","province","city","district","source"]);function gr(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 s=Is(n,t);if(!Object.keys(s).length)return n;let i={...n};return Object.defineProperty(i,"queryPathTypes",{configurable:!1,enumerable:!1,writable:!1,value:Object.freeze(s)}),i})}}))}function Nr(e,t){if(ds.has(e.type)&&us.has(t)||e.type==="user.single"&&fs.has(t)||e.type==="department.single"&&ps.has(t))return Ue(t);if(e.type==="resource-ref.single"){let o=e.queryPathTypes?.[t];return o?{parts:t.split("."),type:o}:null}if(e.type==="address"&&_s.has(t))return Ue(t);if(e.type==="location"){if(Es.has(t))return{parts:[t],type:"number.decimal"};if(As.has(t))return Ue(t);if(t==="capturedAt")return{parts:[t],type:"datetime"}}return null}function Is(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 s=o.get(n);return s?[[`snapshot.${n}`,ls.has(s.type)?s.type:"json"]]:[]})):{}}function Ue(e){return{parts:e.split("."),type:"text.short"}}var hn=["exact-v1","nfkc-space-v1","nfkc-upper-ascii-v1"],Cr=256,je=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"},Pt=e=>!!(e&&typeof e=="object"&&!Array.isArray(e)),ne=(e,t)=>{throw new je(e,t)},nt=(e,t)=>e<t?-1:e>t?1:0,ot=(e,t,o)=>{Object.keys(e).some(n=>!t.includes(n))&&ne(o,"\u4E0D\u652F\u6301\u672A\u77E5\u5C5E\u6027")};function Sn(e,t,o="/uniqueKeys"){if(e===void 0)return;if(!Array.isArray(e)||e.length>8)return ne(o,"\u6BCF\u8D44\u6E90\u6700\u591A 8 \u6761\u89C4\u5219");let n=new Map(t.map(i=>[i.code,i])),s=new Set;return e.map((i,c)=>{let r=`${o}/${c}`;if(!Pt(i))return ne(r,"\u89C4\u5219\u5FC5\u987B\u662F\u5BF9\u8C61");if(ot(i,["code","fields","when"],r),typeof i.code!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(i.code)||i.code.length>20||s.has(i.code))return ne(`${r}/code`,"\u9700\u8981\u4E0D\u91CD\u590D\u4E14\u4E0D\u8D85\u8FC7 20 \u5B57\u7B26\u7684 lower-kebab-case \u6807\u8BC6");if(s.add(i.code),!Array.isArray(i.fields)||i.fields.length<1||i.fields.length>4)return ne(`${r}/fields`,"\u5FC5\u987B\u9009\u62E9 1 \u5230 4 \u4E2A\u5B57\u6BB5");let a=new Set,f=i.fields.map((m,l)=>{let A=`${r}/fields/${l}`;if(!Pt(m))return ne(A,"\u5B57\u6BB5\u5FC5\u987B\u662F\u5BF9\u8C61");ot(m,["fieldCode","normalizer"],A);let N=n.get(m.fieldCode);if(!N||!["text.short","uuid","option.single","resource-ref.single"].includes(N.type)||a.has(m.fieldCode))return ne(`${A}/fieldCode`,"\u9700\u8981\u4E0D\u91CD\u590D\u7684\u77ED\u6587\u672C\u3001UUID\u3001\u5355\u9009\u6216\u5355\u8BB0\u5F55\u5F15\u7528\u5B57\u6BB5");a.add(m.fieldCode);let _=m.normalizer===void 0?"exact-v1":m.normalizer;return!hn.includes(_)||N.type!=="text.short"&&_!=="exact-v1"?ne(`${A}/normalizer`,"\u5F52\u4E00\u5316\u65B9\u5F0F\u4E0D\u652F\u6301\u6216\u4E0E\u5B57\u6BB5\u7C7B\u578B\u4E0D\u7B26"):{fieldCode:N.code,normalizer:_}}).sort((m,l)=>nt(m.fieldCode,l.fieldCode)),E=i.when===void 0?[]:i.when;if(!Array.isArray(E)||E.length>4)return ne(`${r}/when`,"\u6700\u591A 4 \u4E2A\u5408\u53D6\u6761\u4EF6");let d=new Set,u=E.map((m,l)=>{let A=`${r}/when/${l}`;if(!Pt(m))return ne(A,"\u6761\u4EF6\u5FC5\u987B\u662F\u5BF9\u8C61");let N=n.get(m.fieldCode);if(!N)return ne(`${A}/fieldCode`,"\u5B57\u6BB5\u4E0D\u5B58\u5728");let _;if(m.operator==="empty"||m.operator==="nonempty"){if(ot(m,["fieldCode","operator"],A),N.type!=="text.short")return ne(A,"\u7A7A\u503C\u6761\u4EF6\u4EC5\u652F\u6301\u77ED\u6587\u672C");_={fieldCode:N.code,operator:m.operator}}else if(m.operator==="in"||m.operator==="notIn"){ot(m,["fieldCode","operator","values"],A);let T=new Set((N.options??[]).map(b=>b.value));if(N.type!=="option.single"||!Array.isArray(m.values)||m.values.length<1||m.values.length>16||m.values.some(b=>typeof b!="string"||b.length<1||b.length>128||!T.has(b))||new Set(m.values).size!==m.values.length)return ne(A,"\u96C6\u5408\u6761\u4EF6\u9700\u8981 1 \u5230 16 \u4E2A\u4E0D\u91CD\u590D\u7684\u5DF2\u58F0\u660E\u5355\u9009\u503C");_={fieldCode:N.code,operator:m.operator,values:[...m.values].sort(nt)}}else return ne(`${A}/operator`,"\u53EA\u652F\u6301 empty\u3001nonempty\u3001in \u548C notIn");let I=JSON.stringify(_);return d.has(I)?ne(A,"\u6761\u4EF6\u4E0D\u80FD\u91CD\u590D"):(d.add(I),_)}).sort((m,l)=>nt(JSON.stringify(m),JSON.stringify(l)));return{code:i.code,fields:f,when:u}}).sort((i,c)=>nt(i.code,c.code))}var Lt={type:"string",pattern:"^[A-Za-z_][A-Za-z0-9_]{0,62}$"},br={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:Lt,normalizer:{enum:[...hn]}}}},when:{type:"array",maxItems:4,uniqueItems:!0,items:{oneOf:[{type:"object",additionalProperties:!1,required:["fieldCode","operator"],properties:{fieldCode:Lt,operator:{enum:["empty","nonempty"]}}},{type:"object",additionalProperties:!1,required:["fieldCode","operator","values"],properties:{fieldCode:Lt,operator:{enum:["in","notIn"]},values:{type:"array",minItems:1,maxItems:16,uniqueItems:!0,items:{type:"string",minLength:1,maxLength:128}}}}]}}}}};var Dn={"openxiangda.workflow.instance.completed.v2":"commit","openxiangda.workflow.instance.rejected.v2":"release","openxiangda.workflow.instance.withdrawn.v2":"release"};function Vn(e,t){let o=()=>{throw new Error("NATIVE_EVENT_DECIMAL_RESERVATION_INVALID")},n=u=>!u||typeof u!="object"||Array.isArray(u)?o():u,s=n(e);if(Object.keys(s).some(u=>!["resourceCode","workflowCode","outcomes"].includes(u))||typeof s.resourceCode!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(s.resourceCode)||typeof s.workflowCode!="string"||!/^[A-Za-z0-9._:-]{1,128}$/.test(s.workflowCode)||t.execution!==void 0||!Array.isArray(s.outcomes)||!s.outcomes.length||s.outcomes.length>3)return o();let i=t.resources.find(u=>u.code===s.resourceCode),c=t.reservations.find(u=>u.mode==="reserve"&&u.resourceCode===s.resourceCode),r=t.workflows.find(u=>u.code===s.workflowCode);if(!i||!c||!r||r.resourceCode!==i.code)return o();let a=i.fields.find(u=>u.code===c.statusFieldCode);if(a?.type!=="option.single")return o();let f=new Set(a.options?.map(u=>u.value)),E=new Set,d=s.outcomes.map(u=>{let m=n(u),l=m.eventType;return Object.keys(m).some(A=>!["eventType","mode","eligibleChildStatuses"].includes(A))||typeof l!="string"||!Object.prototype.hasOwnProperty.call(Dn,l)||!t.eventTypes.includes(l)||E.has(l)||m.mode!==Dn[l]||!Array.isArray(m.eligibleChildStatuses)||!m.eligibleChildStatuses.length||m.eligibleChildStatuses.length>16||new Set(m.eligibleChildStatuses).size!==m.eligibleChildStatuses.length||m.eligibleChildStatuses.some(A=>typeof A!="string"||!/^[A-Za-z0-9._:-]{1,128}$/.test(A)||!f.has(A))?o():(E.add(l),{eventType:l,mode:m.mode,eligibleChildStatuses:[...m.eligibleChildStatuses].sort()})}).sort((u,m)=>u.eventType.localeCompare(m.eventType));return{resourceCode:s.resourceCode,workflowCode:s.workflowCode,outcomes:d}}function wn(e,t){let o=n=>Array.isArray(n)?n.filter(s=>s&&typeof s=="object"&&!Array.isArray(s)):[];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(s=>({code:s.code,type:s.type,options:o(s.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 kt=class extends Error{constructor(o,n){super(n);this.pointer=o}pointer;code="NATIVE_EVENT_ACTION_INVALID"};function Fn(e,t,o="/events/subscriptions"){if(e.execution===void 0)return;let n=(A,N)=>{throw new kt(`${o}${A}`,N)},s=(A,N,_)=>((!A||typeof A!="object"||Array.isArray(A)||Object.keys(A).some(I=>!_.includes(I)))&&n(N,"Invalid action object or unsupported property"),A),i=s(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 c=e.filter?.resourceCodes;(!Array.isArray(c)||!c.length||c.length>20)&&n("/filter/resourceCodes","Native actions require explicit source resources");let r=new Map(t.map(A=>[A.code,A])),a=c.map(A=>{let N=r.get(A);return N||n("/filter/resourceCodes","Unknown source resource"),new Set((N.schema?.fields||[]).map(_=>_.code))}),f=new Set(e.payload?.fields||[]),E=e.payload?.includeChanges===!0,d=(A,N)=>{let _=s(A,N,["source","path","value"]);if(_.source==="literal"){(!Object.hasOwn(_,"value")||Object.hasOwn(_,"path"))&&n(N,"Literal binding requires only value");let C;try{C=JSON.stringify(_.value)}catch{n(N,"Literal must be JSON")}return(C===void 0||Buffer.byteLength(C)>65536)&&n(N,"Literal is too large or not JSON"),{source:"literal",value:JSON.parse(C)}}(_.source!=="event"||typeof _.path!="string"||Object.hasOwn(_,"value"))&&n(N,"Expected a literal or event binding");let I=_.path.split(".");(I.length>8||I.some(C=>!/^[A-Za-z0-9_-]+$/.test(C)||["__proto__","prototype","constructor"].includes(C)))&&n(N,"Invalid event path");let T=/^data\.projection\.([A-Za-z][A-Za-z0-9_]{0,62})$/.exec(_.path),b=/^data\.changes\.([A-Za-z][A-Za-z0-9_]{0,62})\.(before|after)$/.exec(_.path);if(T||b){let C=(T||b)[1];a.some(O=>!O.has(C))&&n(N,"Source field must exist on every filtered resource"),f.add(C),b&&(E=!0)}else["id","time","type","subject","data.recordId","data.revision","data.operation","data.resourceCode"].includes(_.path)||n(N,"Event path is not part of the data event contract");return{source:"event",path:_.path}};(!Array.isArray(i.operations)||i.operations.length<1||i.operations.length>16)&&n("/execution/operations","Expected 1 to 16 operations");let u={},m=i.operations.map((A,N)=>{let _=`/execution/operations/${N}`,I=s(A,_,["operation","resourceCode","data","id","expectedRevision"]);["create","update","delete"].includes(I.operation)||n(_,"Unsupported Native operation");let T=r.get(I.resourceCode);T||n(_,"Unknown action target resource");let b=new Map((T.schema?.fields||[]).map(O=>[O.code,O])),C=I.data===void 0?{}:s(I.data,`${_}/data`,[...b.keys()]);return Object.keys(C).length>32&&n(_,"Maximum 32 mapped fields per operation"),I.operation==="create"&&(I.id!==void 0||I.expectedRevision!==void 0)&&n(_,"Create does not accept id or expectedRevision"),I.operation==="delete"&&I.data!==void 0&&n(_,"Delete does not accept data"),Object.keys(C).some(O=>b.get(O)?.type==="serial-number")&&n(_,"Generated fields cannot be assigned"),u[I.resourceCode]=ee(T),{operation:I.operation,resourceCode:I.resourceCode,...I.operation==="create"?{}:{id:d(I.id,`${_}/id`),expectedRevision:d(I.expectedRevision,`${_}/expectedRevision`)},...I.operation==="delete"?{}:{data:Object.fromEntries(Object.entries(C).map(([O,S])=>[O,d(S,`${_}/data/${O}`)]))}}});(f.size>32||[...f].some(A=>a.some(N=>!N.has(A))))&&n("/payload/fields","Payload must contain at most 32 declared source fields");let l={kind:"native-data",version:1,operations:m,resourceDigests:u};return Buffer.byteLength(JSON.stringify(l))>65536&&n("/execution","Action plan exceeds 64 KiB"),{execution:{...l,digest:ee(l)},payload:{includeChanges:E,fields:[...f].sort()}}}function be(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function Pn(e,t){if(e?.instanceCommands===void 0)return[];let o=be(e.instanceCommands);if(!o||!Object.keys(o).length||Object.keys(o).some(s=>!["withdraw","terminate"].includes(s)))return["WORKFLOW_INSTANCE_COMMAND_POLICIES_INVALID"];let n=[];for(let[s,i]of Object.entries(o)){let c=be(i),r=s==="withdraw"?["beforeFact"]:["beforeFact","capability"];if(!c||Object.keys(c).some(a=>!r.includes(a))){n.push(`WORKFLOW_INSTANCE_COMMAND_POLICY_INVALID:${s}`);continue}if(s==="terminate"){let a=c.capability;(typeof a!="string"||a.length>255||!/^app:[a-z][a-z0-9]*(?:-[a-z0-9]+)*:[A-Za-z0-9:._-]+$/.test(a)||t&&(!a.startsWith(`app:${t.appCode}:`)||!t.capabilities.includes(a)))&&n.push("WORKFLOW_INSTANCE_TERMINATE_CAPABILITY_INVALID")}if(s==="withdraw"||c.beforeFact!==void 0){let a=c.beforeFact,f=be(e.inputSchema),E=be(be(f?.properties)?.[a]),d=be(be(e.subject)?.factProjection)?.[a],u=t?.fields.get(d);(typeof a!="string"||!/^[A-Za-z][A-Za-z0-9_]{0,62}$/.test(a)||!Array.isArray(f?.required)||!f.required.includes(a)||E?.type!=="string"||E?.format!=="date-time"||typeof d!="string"||t&&(u?.type!=="datetime"||u.nullable===!0))&&n.push(`WORKFLOW_INSTANCE_COMMAND_DEADLINE_FACT_INVALID:${s}`)}}return n}function hr(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 vn(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,s,i,c,r]=t,a=t[8],f=new Date(Date.UTC(Number(o),Number(n),0)).getUTCDate();if(Number(n)<1||Number(n)>12||Number(s)<1||Number(s)>f||Number(i)>23||Number(c)>59||Number(r)>59||a!=="Z"&&(Number(a.slice(1,3))>23||Number(a.slice(4))>59))return null;let E=Date.parse(e);return Number.isFinite(E)?E:null}function Sr(e,t,o,n){let s=e?.[t];if(!s||t==="terminate"&&s.beforeFact===void 0)return null;let i=s.beforeFact,c=be(o),r=i&&c&&Object.hasOwn(c,i)?vn(c[i]):null,a=n instanceof Date?n.getTime():vn(n);return r===null||a===null||!Number.isFinite(a)?"WORKFLOW_V2_CANCELLATION_DEADLINE_INVALID":a<r?null:"WORKFLOW_V2_CANCELLATION_DEADLINE_PASSED"}import*as at from"crypto";var Ln="native-4",kn={"application-native-2":"1.0.0","authz.native-batch-explain":"1.0.0","authz.native-management":"1.0.0","deployment.durable-runs":"1.0.0","deployment.platform-executor":"1.0.0","environment.on-demand-production":"1.0.0","environment.runtime-lifecycle":"1.0.0","data-api-v2":"1.1.0","data.native-golden-crud":"1.0.0","data.audit-read-access":"1.0.0","data.managed-files":"1.1.0","data.decimal-reservations":"1.1.0","data.decimal-reservation-lifecycle":"1.0.0","data.unique-keys":"1.0.0","data.managed-concurrency":"1.0.0","workflow.named-input-sources":"1.0.0","directory-v2":"1.0.0","events-v2":"1.0.0","events.durable-receipts":"1.0.0","events.capture-policy":"1.0.0","events.native-data-actions":"1.0.0","workflow-kernel-v2":"1.0.0","workflow.instance-cancellation-policy":"1.0.0","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 wr=5,Fr=20,vr=50,Pr=50,Lr=100,Be=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=(s,i,c)=>{c>5&&Me("NATIVE_DATA_POLICY_EXPRESSION_DEPTH_EXCEEDED",i);let r=Un(s,i),a=["allOf","anyOf"].filter(d=>d in r);if(a.length===0){o.push({rule:r,pointer:i}),o.length>50&&Me("NATIVE_DATA_POLICY_EXPRESSION_LEAVES_EXCEEDED",i);return}let f=a[0],E=r[f];(a.length!==1||Object.keys(r).length!==1||!Array.isArray(E)||E.length<1||E.length>20)&&Me("NATIVE_DATA_POLICY_EXPRESSION_GROUP_INVALID",i),E.forEach((d,u)=>n(d,`${i}/${f}/${u}`,c+1))};return n(e,t,1),o}function xn(e,t){st(e,t);let o=(n,s)=>{let i=Un(n,s);if(Array.isArray(i.allOf))return xt(i.allOf.flatMap((c,r)=>o(c,`${s}/allOf/${r}`)),s);if(Array.isArray(i.anyOf)){let c=[[]];return i.anyOf.forEach((r,a)=>{let f=o(r,`${s}/anyOf/${a}`);c=xt(c.flatMap(E=>f.map(d=>[...E,...d])),s)}),c}return[[i]]};return xt(o(e,t),t)}function xt(e,t){let o=e.reduce((n,s)=>n+s.length,0);return(e.length>50||o>100)&&Me("NATIVE_DATA_POLICY_EXPRESSION_EXPANSION_EXCEEDED",t),e}function Un(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&Me("NATIVE_DATA_POLICY_EXPRESSION_NODE_INVALID",t),e}function Me(e,t){throw new Be(e,t)}var ms="openxiangda.config-bundle/v3",oo="openxiangda.contract-bundle/v3",jn="openxiangda.native-configuration-projection/v1",We=Ln,gs=/^[a-f0-9]{64}$/,Ns=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,Ts=/^app:[a-z][a-z0-9]*(?:-[a-z0-9]+)*:[A-Za-z0-9:._*-]+$/,Cs=/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/,bs=/^[a-z][a-z0-9]*(?:[-.][a-z0-9]+)*$/,Os=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,ys=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,Mn=/^[A-Za-z][A-Za-z0-9_]{0,127}$/,$s=/^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*$/,Rs=/^[A-Z][A-Z0-9_]*$/,hs=/^[a-z][a-z0-9-]{2,63}$/,Ss=/^[A-Za-z][A-Za-z0-9_-]{0,127}$/,Ds=/^[A-Za-z][A-Za-z0-9_.]{0,127}$/,Vs=16,ws=2*1024,Fs=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"]),vs=new Set(["overview","database","operations","workflow","members","calendar","document","folder","settings"]),Ps=new Set(["approve","reject","return","transfer","delegate","add_assignee","resubmit","withdraw","terminate","admin_reassign","admin_override","retry_resolution"]),Ls=4*1024*1024,ks=8*1024*1024,xs=40,Us=1e5,jt=1024*1024,js="openxiangda.event-handler-manifest/v2",so="openxiangda.application-route-manifest/v3",Bn=64,io=new Set(["id","revision","created_by","updated_by","created_at","updated_at"]),Y=Object.freeze({perspectives:100,resources:100,subjectReadSurfaces:50,capabilities:2e3,operations:500,eventConsumers:100,eventProducers:1e3,eventSchemas:100,eventTypes:500,workflows:100,routes:500,adminPages:500,adminNavigationGroups:100,adminNavigationItems:500}),Mt=["openxiangda.data.record.created.v2","openxiangda.data.record.updated.v2","openxiangda.data.record.deleted.v2"],Bt=["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"],Ms=new Set(Bt),Jt=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(([s,i])=>[s,String(i).slice(0,128)]))}};function ta(e){let t=R(e.appCode,"/appCode",128);Ns.test(t)||p("NATIVE_CONFIG_APP_CODE_INVALID","/appCode");let o=zt(e.expectedConfigDigest,"/expectedConfigDigest"),n=zt(e.expectedContractDigest,"/expectedContractDigest"),s=eo(e.configBytes,Ls,"/configBytes","NATIVE_CONFIG_ARTIFACT_TOO_LARGE"),i=eo(e.contractBytes,ks,"/contractBytes","NATIVE_CONTRACT_ARTIFACT_TOO_LARGE");to(s,o,"/configBytes","NATIVE_CONFIG_DIGEST_MISMATCH"),to(i,n,"/contractBytes","NATIVE_CONTRACT_DIGEST_MISMATCH");let c=Qn(s,"/configBytes","NATIVE_CONFIG_JSON_INVALID","NATIVE_CONFIG_NOT_CANONICAL"),r=Qn(i,"/contractBytes","NATIVE_CONTRACT_JSON_INVALID","NATIVE_CONTRACT_NOT_CANONICAL");Zn(c,"/config"),Zn(r,"/contracts");let a=c,f=r;zs(a,t),Gs(f,t,o);let E=qs(a,o,f.generatorVersion);Fi(E,f,a),Q(E)!==Q(f)&&p("NATIVE_CONTRACT_CLOSURE_MISMATCH",Gt(E,f,"/contracts"));let d={authz:{appCode:t,...a.authz,perspectives:a.perspectives,capabilityCatalog:E.capabilities},data:{appCode:t,resources:a.data.resources,resourceContracts:E.resources,...E.concurrency?{concurrency:E.concurrency}:{},...E.subjectReadSurfaces?{subjectReadSurfaces:E.subjectReadSurfaces}:{}},events:{appCode:t,...a.events,consumers:E.eventConsumers,producers:E.eventProducers,handlerManifest:E.eventHandlerManifest,eventTypes:E.eventTypes,capturePlans:Js({resources:a.data.resources,dataPolicies:a.authz.dataPolicies,subscriptions:E.eventConsumers,capturePolicies:a.events.capturePolicies})},workflows:{appCode:t,...a.workflows,contracts:E.workflows},runtime:{appCode:t,requirements:a.runtime,backend:a.backend,frontend:a.frontend},contracts:E},u={authz:Ve(d.authz),data:Ve(d.data),events:Ve(d.events),workflows:Ve(d.workflows),runtime:Ve(d.runtime),contracts:Ve(d.contracts)},m={configDigest:o,contractDigest:n,generatorVersion:f.generatorVersion},l=Bs(a),A={schemaVersion:jn,compilerContractVersion:We,appCode:t,source:m,projections:u,requiredPlatformCapabilities:l,aggregateDigest:ee({schemaVersion:jn,compilerContractVersion:We,appCode:t,source:m,requiredPlatformCapabilities:l,projectionDigests:Object.fromEntries(Object.entries(u).map(([N,_])=>[N,_.digest]))})};return mo(A)}function Bs(e){let t=e.authz.roles,o=e.data.resources,n=e.backend.operations,s=t.some(l=>l.capabilities.some(A=>A.endsWith(":directory:read")))||o.some(l=>l.schema.fields.some(A=>["user.single","user.multiple","department.single","department.multiple"].includes(A.type)))||n.some(l=>l.platformAccess?.directory),i=!!(e.events.subscriptions.length||e.events.timers.length||e.events.dateTriggers.length||e.events.schemas.length),c=n.some(l=>l.platformAccess?.managedFiles||l.platformAccess?.managedFileCopies)||e.events.subscriptions.some(l=>l.platformAccess?.managedFileCopies),r=n.some(l=>l.platformAccess?.notification)||e.events.subscriptions.some(l=>l.platformAccess?.notification),a=e.workflows.definitions.filter(l=>l.launch.mode==="standalone"||l.launch.mode==="hidden-handoff"),f=n.some(l=>l.platformAccess?.workflow)||a.length>0,E={resources:o},d={perspectives:e.perspectives,authz:e.authz},u={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.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}]:[],...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?.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:u},{code:"authz.native-batch-explain",declaration:d},{code:"authz.native-management",declaration:d},{code:"deployment.durable-runs",declaration:u.backend},{code:"deployment.platform-executor",declaration:u.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:E},{code:"data.native-golden-crud",declaration:E}]:[],...o.some(rn)?[{code:"data.audit-read-access",declaration:E}]:[],...s?[{code:"directory-v2",declaration:{roles:t.map(l=>({code:l.code,capabilities:l.capabilities.filter(A=>A.endsWith(":directory:read"))})),resources:o.map(l=>({code:l.code,fields:l.schema.fields.filter(A=>["user.single","user.multiple","department.single","department.multiple"].includes(A.type))})),operations:n.filter(l=>l.platformAccess?.directory).map(l=>({code:l.code,directory:l.platformAccess.directory}))}}]:[],...c?[{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}]:[],...i?[{code:"events-v2",declaration:e.events},{code:"events.durable-receipts",declaration:e.events}]:[],...e.workflows.activations.length?[{code:"workflow-kernel-v2",declaration:e.workflows},{code:"workflow.fresh-command-token",declaration:e.workflows}]:[],...e.workflows.definitions.some(l=>l.definition.instanceCommands!==void 0)?[{code:"workflow.instance-cancellation-policy",declaration:e.workflows.definitions.filter(l=>l.definition.instanceCommands!==void 0)}]:[],...f?[{code:"business-process.durable-command",declaration:{operations:n.filter(l=>l.platformAccess?.workflow).map(l=>({code:l.code,workflow:l.platformAccess.workflow})),definitions:a,activations:e.workflows.activations.filter(l=>a.some(A=>A.definition.code===l.workflowCode))}}]:[],...r?[{code:"notification-hub-v2",declaration:{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:A})=>({code:l,contractVersion:kn[l],usageDigest:`sha256:${ee(A)}`})).sort((l,A)=>l.code===A.code?0:l.code<A.code?-1:1)}function Js(e){let t=new Map,o=new Set(e.resources.map(i=>String(i.code)));for(let[i,c]of $(e.capturePolicies===void 0?[]:e.capturePolicies,"/capturePlan/capturePolicies",100).entries()){let r=`/capturePlan/capturePolicies/${i}`,a=g(c,r);y(a,["resourceCode","mode"],r);let f=z(a.resourceCode,`${r}/resourceCode`);o.has(f)||p("NATIVE_EVENT_CAPTURE_RESOURCE_NOT_FOUND",r,{resourceCode:f}),t.has(f)&&p("NATIVE_EVENT_CAPTURE_POLICY_DUPLICATE",r,{resourceCode:f}),a.mode!=="all"&&a.mode!=="subscribed"&&p("NATIVE_EVENT_CAPTURE_MODE_INVALID",`${r}/mode`),t.set(f,a.mode)}let n=new Map(e.dataPolicies.map((i,c)=>{let r=g(i,`/capturePlan/dataPolicies/${c}`);return[String(r.code),r]})),s=e.subscriptions.map((i,c)=>g(i,`/capturePlan/subscriptions/${c}`));return e.resources.map((i,c)=>{let r=`/capturePlan/resources/${c}`,a=g(i,r),f=z(a.code,`${r}/code`),E=a.schema?g(a.schema,`${r}/schema`):a,d=new Set($(E.fields||[],`${r}/schema/fields`,500).map((O,S)=>B(g(O,`${r}/schema/fields/${S}`).code,`${r}/schema/fields/${S}/code`))),u=a.dataPolicyCode?w(a.dataPolicyCode,`${r}/dataPolicyCode`):null,m=u?n.get(u):void 0;u&&!m&&p("NATIVE_EVENT_CAPTURE_AUTHZ_POLICY_NOT_FOUND",r,{resourceCode:f,dataPolicyCode:u});let l=new Set;for(let O of m?.rules||[])l.add(String(O.field));if(m?.readExpression)for(let O of st(m.readExpression,`${r}/readExpression`))l.add(String(O.rule.field));let A=new Set,N=new Set,_=new Set;for(let[O,S]of s.entries()){let D=$(S.eventTypes,`/capturePlan/subscriptions/${O}/eventTypes`,20).map(String);if(!D.some(j=>j.startsWith("openxiangda.data.")))continue;let U=g(S.filter||{},`/capturePlan/subscriptions/${O}/filter`),k=Array.isArray(U.resourceCodes)?U.resourceCodes.map(String):[];if(k.length&&!k.includes(f))continue;for(let j of D)Mt.includes(j)&&_.add(j);for(let j of Ws(U,`/capturePlan/subscriptions/${O}/filter`))A.add(j);let q=g(S.payload||{},`/capturePlan/subscriptions/${O}/payload`);for(let j of $(q.fields||[],`/capturePlan/subscriptions/${O}/payload/fields`,32))N.add(B(j,`/capturePlan/subscriptions/${O}/payload/fields`))}let I=new Set([...A,...N]),T=new Set([...I,...l]);T.size>Bn&&p("NATIVE_EVENT_CAPTURE_FIELDS_LIMIT",r,{resourceCode:f,maximum:Bn});for(let O of T)!d.has(O)&&!(l.has(O)&&io.has(O))&&p("NATIVE_EVENT_CAPTURE_FIELD_NOT_FOUND",r,{resourceCode:f,field:O});let b=g(a.fieldPolicies||{},`${r}/fieldPolicies`);for(let O of I)b[O]?.mask==="omit"&&p("NATIVE_EVENT_CAPTURE_FIELD_SENSITIVE",r,{resourceCode:f,field:O});let C={resourceCode:f,...t.get(f)==="subscribed"?{capturedEventTypes:[..._].sort()}:{},filterFields:[...A].sort(),projectionFields:[...N].sort(),authorizationFields:[...l].sort(),captureFields:[...T].sort()};return{...C,digest:ee(C)}}).sort((i,c)=>i.resourceCode.localeCompare(c.resourceCode))}function Ws(e,t){let o=new Set;for(let[c,r]of $(e.changes||[],`${t}/changes`,16).entries()){let a=g(r,`${t}/changes/${c}`);o.add(B(a.field,`${t}/changes/${c}/field`))}let n=g(e.changedFields||{},`${t}/changedFields`);for(let c of["anyOf","allOf","noneOf"])for(let[r,a]of $(n[c]||[],`${t}/changedFields/${c}`,32).entries())o.add(B(a,`${t}/changedFields/${c}/${r}`));let s=0,i=(c,r,a)=>{a>3&&p("NATIVE_EVENT_FILTER_DEPTH_LIMIT",r);let f=g(c,r);if(f.change){let d=g(f.change,`${r}/change`);o.add(B(d.field,`${r}/change/field`)),s+=1;return}if(f.not){i(f.not,`${r}/not`,a+1);return}let E=f.all?"all":f.any?"any":null;E||p("NATIVE_EVENT_FILTER_CONDITION_INVALID",r);for(let[d,u]of $(f[E],`${r}/${E}`,16).entries())i(u,`${r}/${E}/${d}`,a+1)};return e.where&&i(e.where,`${t}/where`,1),s+=Array.isArray(e.changes)?e.changes.length:0,s>16&&p("NATIVE_EVENT_FILTER_ATOM_LIMIT",t),[...o].sort()}function zs(e,t){y(e,["schemaVersion","compilerContractVersion","appCode","perspectives","authz","backend","data","events","workflows","frontend","runtime"],"/config"),L(e.schemaVersion,ms,"/config/schemaVersion"),L(e.compilerContractVersion,We,"/config/compilerContractVersion"),L(e.appCode,t,"/config/appCode"),$(e.perspectives,"/config/perspectives",100);let o=g(e.authz,"/config/authz");y(o,["capabilities","roles","scopeDimensions","scopeSources","roleMembershipSources","relationshipGrantSources","dataPolicies","authorizationTransitions"],"/config/authz",["authenticatedUserRoleCode"]),$(o.capabilities,"/config/authz/capabilities",2e3),$(o.roles,"/config/authz/roles",100),$(o.scopeDimensions,"/config/authz/scopeDimensions",100),$(o.scopeSources,"/config/authz/scopeSources",100),$(o.roleMembershipSources,"/config/authz/roleMembershipSources",100),$(o.relationshipGrantSources,"/config/authz/relationshipGrantSources",100),$(o.dataPolicies,"/config/authz/dataPolicies",100),$(o.authorizationTransitions,"/config/authz/authorizationTransitions",100);let n=g(e.backend,"/config/backend");y(n,["secrets","operations"],"/config/backend"),$(n.secrets,"/config/backend/secrets",100),$(n.operations,"/config/backend/operations",500),Ri(n.secrets);let s=g(e.data,"/config/data");y(s,["resources"],"/config/data",["resourceDetailRoutes","subjectReadSurfaces","concurrency"]),$(s.resources,"/config/data/resources",100),s.subjectReadSurfaces!==void 0&&$(s.subjectReadSurfaces,"/config/data/subjectReadSurfaces",Y.subjectReadSurfaces),s.resourceDetailRoutes!==void 0&&$(s.resourceDetailRoutes,"/config/data/resourceDetailRoutes",100);let i=g(e.events,"/config/events");y(i,["schemas","subscriptions","timers","dateTriggers"],"/config/events",["capturePolicies"]),$(i.schemas,"/config/events/schemas",100),$(i.subscriptions,"/config/events/subscriptions",100),$(i.timers,"/config/events/timers",100),$(i.dateTriggers,"/config/events/dateTriggers",100);let c=g(e.workflows,"/config/workflows");y(c,["definitions","bindings","activations","providers","editableParameters"],"/config/workflows"),$(c.definitions,"/config/workflows/definitions",100),$(c.bindings,"/config/workflows/bindings",100),$(c.activations,"/config/workflows/activations",100),$(c.providers,"/config/workflows/providers",100),$(c.editableParameters,"/config/workflows/editableParameters",100);let r=g(e.frontend,"/config/frontend");y(r,["routes","user","admin","devicePolicy"],"/config/frontend",["authentication","publicAccess"]),$(r.routes,"/config/frontend/routes",500);let a=g(r.user,"/config/frontend/user");y(a,["applicationTodoCenter"],"/config/frontend/user"),Fe(a.applicationTodoCenter,"/config/frontend/user/applicationTodoCenter"),qt(r.devicePolicy,"/config/frontend/devicePolicy"),Object.prototype.hasOwnProperty.call(r,"authentication")&&ao(r.authentication,r.routes,e,"/config/frontend/authentication"),Object.prototype.hasOwnProperty.call(r,"publicAccess")&&ci(r.publicAccess,e,"/config/frontend/publicAccess");let f=g(r.admin,"/config/frontend/admin");y(f,["navigation"],"/config/frontend/admin",["access"]),f.access!==void 0&&dt(f.access,"/config/frontend/admin/access",e.appCode),fi(f.navigation,"/config/frontend/admin/navigation");let E=g(e.runtime,"/config/runtime");y(E,["protocolCapabilities","health"],"/config/runtime"),F(E.protocolCapabilities,"/config/runtime/protocolCapabilities",100),y(g(E.health,"/config/runtime/health"),["livePath","readyPath","versionPath"],"/config/runtime/health"),L(E.health.livePath,"/__platform/health","/config/runtime/health/livePath"),L(E.health.readyPath,"/__platform/ready","/config/runtime/health/readyPath"),L(E.health.versionPath,"/__platform/version","/config/runtime/health/versionPath")}function Gs(e,t,o){y(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"]),L(e.schemaVersion,oo,"/contracts/schemaVersion"),L(e.compilerContractVersion,We,"/contracts/compilerContractVersion"),R(e.generatorVersion,"/contracts/generatorVersion",128),L(e.appCode,t,"/contracts/appCode"),L(e.configDigest,o,"/contracts/configDigest"),$(e.perspectives,"/contracts/perspectives",Y.perspectives),$(e.resources,"/contracts/resources",Y.resources),e.subjectReadSurfaces!==void 0&&$(e.subjectReadSurfaces,"/contracts/subjectReadSurfaces",Y.subjectReadSurfaces),$(e.capabilities,"/contracts/capabilities",Y.capabilities),$(e.operations,"/contracts/operations",Y.operations),$(e.eventConsumers,"/contracts/eventConsumers",Y.eventConsumers),$(e.eventProducers,"/contracts/eventProducers",Y.eventProducers),$(e.eventSchemas,"/contracts/eventSchemas",Y.eventSchemas),g(e.eventHandlerManifest,"/contracts/eventHandlerManifest"),F(e.eventTypes,"/contracts/eventTypes",Y.eventTypes),$(e.workflows,"/contracts/workflows",Y.workflows),$(e.routes,"/contracts/routes",Y.routes),Object.prototype.hasOwnProperty.call(e,"authentication")&&ii(e.authentication,"/contracts/authentication"),Object.prototype.hasOwnProperty.call(e,"publicAccess")&&di(e.publicAccess,"/contracts/publicAccess"),Object.prototype.hasOwnProperty.call(e,"adminAccess")&&dt(e.adminAccess,"/contracts/adminAccess",t),mi(e.routeManifest,"/contracts/routeManifest",t),Ei(e.adminPages,"/contracts/adminPages"),Ai(e.adminNavigation,"/contracts/adminNavigation")}function qs(e,t,o){let n=Hs(e);bi(e,n),yi(e),Oi(e),hi(e);let s=e.events.schemas.map((A,N)=>{let _=`/config/events/schemas/${N}`,I=g(A,_),T=R(I.eventType,`${_}/eventType`,255);return T.startsWith("openxiangda.")&&p("NATIVE_EVENT_SCHEMA_RESERVED",`${_}/eventType`,{eventType:T}),L(I.schemaDigest,ee(g(I.jsonSchema,`${_}/jsonSchema`)),`${_}/schemaDigest`),I}),i=new Set([...Mt,...Bt,...s.map(A=>String(A.eventType))]),c=new Map(e.data.resources.map(A=>[String(A.code),new Map(A.schema.fields.map(N=>[String(N.code),String(N.type)]))])),r=X(e.events.subscriptions.map((A,N)=>{let _=`/config/events/subscriptions/${N}`,I=g(A,_),T=F(I.eventTypes,`${_}/eventTypes`,20);T.forEach((S,D)=>{i.has(S)||p("NATIVE_EVENT_TYPE_NOT_REGISTERED",`${_}/eventTypes/${D}`,{eventType:S})});let b=Fn(I,e.data.resources,_),C=Ks(I.delivery,T,`${_}/delivery`),O=Ys(I.platformAccess,`${_}/platformAccess`,c,e,I);return{code:w(I.code,`${_}/code`),endpointPath:le(I.endpointPath,`${_}/endpointPath`),eventTypes:T,filter:g(I.filter,`${_}/filter`),payload:b?.payload||g(I.payload,`${_}/payload`),...b?{execution:b.execution}:{},...O?{platformAccess:O}:{},delivery:C}}),A=>A.code),a=new Map(s.map(A=>[String(A.eventType),String(A.dataSchemaVersion)])),f=X([...e.data.resources.flatMap(A=>Mt.map(N=>({code:`data:${A.code}:${N}`,source:"data",eventType:N,dataSchemaVersion:"2.0.0",resourceCode:A.code}))),...s.map(A=>({code:`app:${A.eventType}`,source:"app",eventType:A.eventType,dataSchemaVersion:A.dataSchemaVersion})),...e.events.timers.map(A=>({code:A.code,source:"timer",eventType:A.eventType,dataSchemaVersion:a.get(String(A.eventType))||"2.0.0"})),...e.events.dateTriggers.map(A=>({code:A.code,source:"date",eventType:A.eventType,dataSchemaVersion:a.get(String(A.eventType))||"2.0.0",resourceCode:A.resourceCode,field:A.field})),...e.workflows.activations.length?Bt.map(A=>({code:`workflow:${A}`,source:"workflow",eventType:A,dataSchemaVersion:"2.0.0"})):[]],A=>`${A.source}:${A.code}:${A.eventType}`),E=M([...r.flatMap(A=>A.eventTypes),...f.map(A=>String(A.eventType))]);_i(e);let d=uo(e),u;try{u=mn(e.data.concurrency,e.data.resources,n)}catch(A){throw A instanceof ke&&p(A.code,A.pointer,{reason:A.reason}),A}let m=Qs(e,n),l=ro(e);try{Nn(e.data.resources,l)}catch(A){throw A instanceof De&&p(A.code,A.pointer,{reason:A.reason}),A}return{schemaVersion:oo,compilerContractVersion:We,generatorVersion:o,appCode:e.appCode,configDigest:t,perspectives:e.perspectives,resources:Xs(e),...m.length?{subjectReadSurfaces:m}:{},...u?{concurrency:u}:{},capabilities:X(n,A=>A.code),operations:l,eventConsumers:r,eventProducers:f,eventSchemas:s,eventHandlerManifest:{schemaVersion:js,appCode:e.appCode,handlers:r.filter(A=>!A.execution).map(A=>({code:A.code,endpointPath:A.endpointPath,eventTypes:A.eventTypes,dataSchemaVersions:M(A.eventTypes.map(N=>N.startsWith("openxiangda.")?"2.0.0":a.get(N)||"2.0.0")),maxBodyBytes:65536,receiptProtocolVersion:2}))},eventTypes:E,workflows:_o(e),routes:ct(e),...Object.prototype.hasOwnProperty.call(e.frontend,"authentication")?{authentication:ri(e)}:{},...Object.prototype.hasOwnProperty.call(e.frontend,"publicAccess")?{publicAccess:li(e)}:{},...e.frontend.admin.access?{adminAccess:e.frontend.admin.access}:{},routeManifest:Ti(e),adminPages:d,adminNavigation:ui(e)}}function Ys(e,t,o,n,s){if(e===void 0)return;let i=g(e,t);y(i,["notification","managedFileCopies","decimalReservation"],t,!0);let c={};if(i.decimalReservation!==void 0)try{c.decimalReservation=Vn(i.decimalReservation,wn(n,s))}catch{p("NATIVE_EVENT_DECIMAL_RESERVATION_INVALID",`${t}/decimalReservation`)}if(i.notification!==void 0){let r=g(i.notification,`${t}/notification`);y(r,["mode"],`${t}/notification`),L(r.mode,"business-standard",`${t}/notification/mode`),c.notification={mode:"business-standard"}}if(i.managedFileCopies!==void 0){let r=$(i.managedFileCopies,`${t}/managedFileCopies`,16);r.length||p("NATIVE_EVENT_MANAGED_FILE_COPIES_REQUIRED",`${t}/managedFileCopies`);let a=new Set;c.managedFileCopies=X(r.map((f,E)=>{let d=`${t}/managedFileCopies/${E}`,u=g(f,d);y(u,["mode","sourceResourceCode","sourceFieldCodes","targetResourceCode","targetFieldCodes"],d),L(u.mode,"copy",`${d}/mode`);let m=z(u.sourceResourceCode,`${d}/sourceResourceCode`),l=z(u.targetResourceCode,`${d}/targetResourceCode`),A=o.get(m),N=o.get(l);(!A||!N)&&p("NATIVE_EVENT_MANAGED_FILE_COPY_RESOURCE_INVALID",d);let _=F(u.sourceFieldCodes,`${d}/sourceFieldCodes`,16),I=F(u.targetFieldCodes,`${d}/targetFieldCodes`,16);(!_.length||_.length!==I.length)&&p("NATIVE_EVENT_MANAGED_FILE_COPY_FIELDS_INVALID",d),_.forEach((b,C)=>{let O=A.get(b),S=N.get(I[C]);(!["file","image"].includes(String(O))||O!==S)&&p("NATIVE_EVENT_MANAGED_FILE_COPY_FIELD_INVALID",`${d}/sourceFieldCodes/${C}`)});let T=`${m}:${_.join(",")}=>${l}:${I.join(",")}`;return a.has(T)&&p("NATIVE_EVENT_MANAGED_FILE_COPY_DUPLICATE",d),a.add(T),{mode:"copy",sourceResourceCode:m,sourceFieldCodes:M(_),targetResourceCode:l,targetFieldCodes:M(I)}}),f=>`${f.sourceResourceCode}:${f.sourceFieldCodes.join(",")}=>${f.targetResourceCode}:${f.targetFieldCodes.join(",")}`)}return Object.keys(c).length||p("NATIVE_EVENT_PLATFORM_ACCESS_EMPTY",t),c}function Ks(e,t,o){let n=g(e,o);y(n,["timeoutMs","maxAttempts","initialBackoffMs","maxBackoffMs","ordering","concurrency"],o),Z(n.timeoutMs,`${o}/timeoutMs`,1e3,3e4),Z(n.maxAttempts,`${o}/maxAttempts`,1,12);let s=Z(n.initialBackoffMs,`${o}/initialBackoffMs`,1e3,3e5);Z(n.maxBackoffMs,`${o}/maxBackoffMs`,s,18e5),Z(n.concurrency,`${o}/concurrency`,1,50);let i=R(n.ordering,`${o}/ordering`,32);return["none","record","workflow-instance"].includes(i)||p("NATIVE_EVENT_DELIVERY_ORDERING_INVALID",`${o}/ordering`),i==="workflow-instance"&&t.some(c=>!Ms.has(c))&&p("NATIVE_EVENT_WORKFLOW_ORDERING_REQUIRES_WORKFLOW_FACTS",`${o}/ordering`),n}function Hs(e){let t=new Map;for(let o of Io(e.appCode))t.set(o.code,o);for(let[o,n]of e.authz.capabilities.entries()){let s=`/config/authz/capabilities/${o}`,i=g(n,s);y(i,["code","kind","name","description"],s,!0);let c=Ne(i.code,`${s}/code`,e.appCode);t.has(c)&&p("NATIVE_CAPABILITY_DUPLICATE",`${s}/code`),["backend","ui"].includes(i.kind)||p("NATIVE_CAPABILITY_KIND_INVALID",`${s}/kind`);let r={code:c,kind:i.kind,name:R(i.name,`${s}/name`,255),source:"explicit",...i.description===void 0?{}:{description:Kt(i.description,`${s}/description`,2e3)}};t.set(c,r)}for(let[o,n]of e.data.resources.entries()){let s=`/config/data/resources/${o}`,i=ye(n,s,e.appCode),c={read:`\u8BFB\u53D6${i.name}`,create:`\u65B0\u5EFA${i.name}`,update:`\u66F4\u65B0${i.name}`,delete:`\u5220\u9664${i.name}`};for(let r of["read","create","update","delete"]){let a=Ne(i.capabilities[r],`${s}/capabilities/${r}`,e.appCode);t.has(a)&&p("NATIVE_CAPABILITY_DUPLICATE",`${s}/capabilities/${r}`),t.set(a,{code:a,kind:"data",name:c[r],source:"data"})}for(let[r,a]of Object.entries(i.fieldPolicies)){if(ve(r))continue;let f=g(a,`${s}/fieldPolicies/${r}`);for(let E of["read","create","update"])if(Array.isArray(f[E]))for(let d of F(f[E],`${s}/fieldPolicies/${r}/${E}`,2e3))Ne(d,`${s}/fieldPolicies/${r}/${E}`,e.appCode),!t.has(d)&&t.set(d,{code:d,kind:"data",name:`${i.name}.${r}.${E}`,source:"data"})}}return[...t.values()]}function Xs(e){let t=Zs(e);return X(e.data.resources.map((o,n)=>{let s=ye(o,`/config/data/resources/${n}`,e.appCode),i=t.get(s.code);return{code:s.code,schemaDigest:ee(s.schema),fields:X(s.schema.fields.map(c=>({code:c.code,type:c.type})),c=>c.code),...i?{detailRouteCode:i}:{}}}),o=>o.code)}function Qs(e,t){if(e.data.subjectReadSurfaces===void 0)return[];let o=$(e.data.subjectReadSurfaces,"/config/data/subjectReadSurfaces",Y.subjectReadSurfaces),n=new Set(t.map(c=>String(c.code))),s=new Map(e.data.resources.map((c,r)=>{let a=`/config/data/resources/${r}`,f=ye(c,a,e.appCode);return[String(f.code),{resource:f,fields:new Map($(g(f.schema,`${a}/schema`).fields,`${a}/schema/fields`,500).map(E=>{let d=g(E,`${a}/schema/fields`);return[String(d.code),d]}))}]})),i=new Set;return X(o.map((c,r)=>{let a=`/config/data/subjectReadSurfaces/${r}`,f=g(c,a);y(f,["code","name","capability","subject","relations"],a);let E=w(f.code,`${a}/code`);i.has(E)&&p("NATIVE_SUBJECT_READ_SURFACE_CODE_DUPLICATE",`${a}/code`),i.add(E);let d=Ne(f.capability,`${a}/capability`,e.appCode);n.has(d)||p("NATIVE_SUBJECT_READ_SURFACE_CAPABILITY_NOT_DECLARED",`${a}/capability`);let u=g(f.subject,`${a}/subject`);y(u,["resourceCode","fields"],`${a}/subject`);let m=z(u.resourceCode,`${a}/subject/resourceCode`),l=s.get(m);l||p("NATIVE_SUBJECT_READ_SURFACE_RESOURCE_NOT_DECLARED",`${a}/subject/resourceCode`);let A=F(u.fields,`${a}/subject/fields`,100).map((b,C)=>B(b,`${a}/subject/fields/${C}`));A.length||p("NATIVE_SUBJECT_READ_SURFACE_FIELDS_REQUIRED",`${a}/subject/fields`);for(let[b,C]of A.entries()){let O=l.fields.get(C);(!O||O.type==="subtable")&&p("NATIVE_SUBJECT_READ_SURFACE_FIELD_INVALID",`${a}/subject/fields/${b}`)}let N=$(f.relations,`${a}/relations`,8);N.length||p("NATIVE_SUBJECT_READ_SURFACE_RELATIONS_REQUIRED",`${a}/relations`);let _=new Set,I=0,T=X(N.map((b,C)=>{let O=`${a}/relations/${C}`,S=g(b,O);y(S,["code","resourceCode","foreignKeyField","fields","limit"],O,["order"]);let D=w(S.code,`${O}/code`);_.has(D)&&p("NATIVE_SUBJECT_READ_SURFACE_RELATION_CODE_DUPLICATE",`${O}/code`),_.add(D);let U=z(S.resourceCode,`${O}/resourceCode`),k=s.get(U);k||p("NATIVE_SUBJECT_READ_SURFACE_RESOURCE_NOT_DECLARED",`${O}/resourceCode`);let q=B(S.foreignKeyField,`${O}/foreignKeyField`),j=k.fields.get(q),ue=g(j?.source||{},`${O}/foreignKeyField/source`);(!j||!["uuid","resource-ref.single"].includes(String(j.type))||j.type==="resource-ref.single"&&(ue.kind!=="resource"||ue.resourceCode!==m))&&p("NATIVE_SUBJECT_READ_SURFACE_RELATION_INVALID",`${O}/foreignKeyField`);let fe=F(S.fields,`${O}/fields`,100).map((ie,V)=>B(ie,`${O}/fields/${V}`));fe.length||p("NATIVE_SUBJECT_READ_SURFACE_FIELDS_REQUIRED",`${O}/fields`);for(let[ie,V]of fe.entries()){let x=k.fields.get(V);(!x||x.type==="subtable")&&p("NATIVE_SUBJECT_READ_SURFACE_FIELD_INVALID",`${O}/fields/${ie}`)}let K=$(S.order||[],`${O}/order`,10).map((ie,V)=>{let x=`${O}/order/${V}`,v=g(ie,x);y(v,["field","direction"],x);let J=B(v.field,`${x}/field`),W=k.fields.get(J);return(!io.has(J)&&!W||W?.type==="subtable"||W&&!Le(W.type))&&p("NATIVE_SUBJECT_READ_SURFACE_ORDER_FIELD_INVALID",`${x}/field`),["asc","desc"].includes(String(v.direction))||p("NATIVE_SUBJECT_READ_SURFACE_ORDER_DIRECTION_INVALID",`${x}/direction`),{field:J,direction:v.direction}}),Ie=Z(S.limit,`${O}/limit`,1,100);return I+=Ie,{code:D,resourceCode:U,foreignKeyField:q,fields:M(fe),...K.length?{order:K}:{},limit:Ie}}),b=>b.code);return I>400&&p("NATIVE_SUBJECT_READ_SURFACE_ROW_LIMIT_EXCEEDED",`${a}/relations`),{code:E,name:R(f.name,`${a}/name`,255),capability:d,subject:{resourceCode:m,fields:M(A)},relations:T}}),c=>c.code)}function Zs(e){let t=e.data.resourceDetailRoutes===void 0?[]:$(e.data.resourceDetailRoutes,"/config/data/resourceDetailRoutes",100),o=new Map(e.data.resources.map((i,c)=>{let r=`/config/data/resources/${c}`,a=ye(i,r,e.appCode);return[a.code,a]})),n=new Map(ct(e).map(i=>[String(i.code),i])),s=new Map;for(let[i,c]of t.entries()){let r=`/config/data/resourceDetailRoutes/${i}`,a=g(c,r);y(a,["resourceCode","desktop","mobile"],r);let f=z(a.resourceCode,`${r}/resourceCode`);s.has(f)&&p("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_DUPLICATE",`${r}/resourceCode`);let E=o.get(f);E||p("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_RESOURCE_MISSING",`${r}/resourceCode`);let d=w(a.desktop,`${r}/desktop`),u=w(a.mobile,`${r}/mobile`);d===u&&p("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_INVALID",r);let m=String(E.capabilities.read);for(let[l,A]of[["desktop",d],["mobile",u]]){let N=`${r}/${l}`,_=n.get(A);_||p("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_REFERENCE_MISSING",N),_.surface!=="user"&&p("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_SURFACE_INVALID",N);let I=le(_.path,`${N}/path`),T=[...I.matchAll(/:([A-Za-z][A-Za-z0-9_]*)/g)],b=l==="mobile"?!I.startsWith("/m/"):I==="/m"||I.startsWith("/m/");(I.includes("*")||I.includes("?")||I.includes("#")||I.split("/").includes("..")||T.length!==1||b)&&p("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_PATH_INVALID",N);let C=Array.isArray(_.access?.allOf)?_.access.allOf:[];_.capability!==m&&!C.includes(m)&&p("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_CAPABILITY_INVALID",N)}s.set(f,{desktop:d,mobile:u})}return s}function ro(e){let t=new Map(e.data.resources.map((c,r)=>{let a=`/config/data/resources/${r}`,f=ye(c,a,e.appCode);return[f.code,new Map(f.schema.fields.map(E=>[String(E.code),E]))]})),o=new Map(e.data.resources.map((c,r)=>{let a=`/config/data/resources/${r}`,f=ye(c,a,e.appCode);return[f.code,new Map(f.schema.fields.map(E=>[String(E.code),String(E.type)]))]})),n=new Set(o.keys()),s=new Set(e.workflows.activations.map((c,r)=>lt(g(c,`/config/workflows/activations/${r}`).workflowCode,`/config/workflows/activations/${r}/workflowCode`))),i=new Map;return X(e.backend.operations.map((c,r)=>{let a=`/config/backend/operations/${r}`,f=g(c,a);y(f,["code","method","path","capability","requestSchema","responseSchema","description","platformAccess","browser","ai"],a,!0);let E=R(f.method,`${a}/method`,16);["GET","POST","PUT","PATCH","DELETE"].includes(E)||p("NATIVE_OPERATION_METHOD_INVALID",`${a}/method`);let d=w(f.code,`${a}/code`);oi(f.ai,a,d,E,n);let u=ni(f.platformAccess,`${a}/platformAccess`,o,t,s,new Set(e.authz.roles.map(l=>String(l.code))));if(u?.decimalReservation){let l=u.decimalReservation,A=String(l.resourceCode),N=JSON.stringify([l.amountFieldCode,l.currencyFieldCode,l.relationFieldCode,l.parentFieldCode,l.rootFieldCode,l.statusFieldCode,l.parentRelationValue,l.childRelationValue]),_=i.get(A);_&&_!==N&&p("NATIVE_DECIMAL_RESERVATION_MAPPING_CONFLICT",`${a}/platformAccess/decimalReservation`),i.set(A,N)}let m=ei(f.browser,`${a}/browser`,E,f.requestSchema,f.responseSchema,o,t,e.data.subjectReadSurfaces||[]);return{code:d,method:E,path:le(f.path,`${a}/path`),requiredCapability:Ne(f.capability,`${a}/capability`,e.appCode),requestSchemaDigest:ee(g(f.requestSchema,`${a}/requestSchema`)),responseSchemaDigest:ee(g(f.responseSchema,`${a}/responseSchema`)),...f.description===void 0?{}:{description:Kt(f.description,`${a}/description`,2e3)},...u?{platformAccess:u}:{},...m?{browser:m}:{}}}),c=>c.code)}function ei(e,t,o,n,s,i,c,r){if(e===void 0)return null;let a=g(e,t);y(a,["exposure","behavior","idempotency","subject"],t,["refreshTargets","fileIntent"]),L(a.exposure,"authenticated",`${t}/exposure`);let f=R(a.behavior,`${t}/behavior`,32);["read","controlled"].includes(f)||p("NATIVE_OPERATION_BROWSER_BEHAVIOR_INVALID",`${t}/behavior`);let E=R(a.idempotency,`${t}/idempotency`,32);(!["none","required"].includes(E)||f==="controlled"&&E!=="required"||f==="read"&&E!=="none")&&p("NATIVE_OPERATION_BROWSER_IDEMPOTENCY_INVALID",`${t}/idempotency`);let d=g(a.subject,`${t}/subject`);y(d,["resourceCode","inputField"],`${t}/subject`);let u=z(d.resourceCode,`${t}/subject/resourceCode`);i.has(u)||p("NATIVE_OPERATION_BROWSER_SUBJECT_RESOURCE_NOT_DECLARED",`${t}/subject/resourceCode`);let m=B(d.inputField,`${t}/subject/inputField`),l=g(n,`${t}/requestSchema`),A=g(s,`${t}/responseSchema`);(l.type!=="object"||l.additionalProperties!==!1||A.type!=="object"||A.additionalProperties!==!1)&&p("NATIVE_OPERATION_BROWSER_SCHEMA_ROOT_INVALID",`${t}/requestSchema`);let N=g(l.properties,`${t}/requestSchema/properties`),_=new Set(l.required===void 0?[]:F(l.required,`${t}/requestSchema/required`,200));(!(m in N)||!_.has(m))&&p("NATIVE_OPERATION_BROWSER_SUBJECT_INPUT_INVALID",`${t}/subject/inputField`);let I=g(N[m],`${t}/requestSchema/properties/${m}`);(I.type!=="string"||I.format!=="uuid")&&p("NATIVE_OPERATION_BROWSER_SUBJECT_INPUT_INVALID",`${t}/subject/inputField`);let T=new Map((Array.isArray(r)?r:[]).map((D,U)=>{let k=g(D,`/config/data/subjectReadSurfaces/${U}`);return[String(k.code),String(g(k.subject,`/config/data/subjectReadSurfaces/${U}/subject`).resourceCode)]})),b=a.refreshTargets===void 0?[]:$(a.refreshTargets,`${t}/refreshTargets`,16),C=new Set,O=X(b.map((D,U)=>{let k=`${t}/refreshTargets/${U}`,q=g(D,k);y(q,["kind","code"],k),L(q.kind,"subject-surface",`${k}/kind`);let j=w(q.code,`${k}/code`);return(C.has(j)||!T.has(j)||T.get(j)!==u)&&p("NATIVE_OPERATION_BROWSER_REFRESH_TARGET_INVALID",`${k}/code`),C.add(j),{kind:"subject-surface",code:j}}),D=>`${D.kind}:${D.code}`),S=ti(a.fileIntent,`${t}/fileIntent`,o,f,E,u,N,_,c);return{exposure:"authenticated",behavior:f,idempotency:E,subject:{resourceCode:u,inputField:m},...O.length?{refreshTargets:O}:{},...S?{fileIntent:S}:{}}}function ti(e,t,o,n,s,i,c,r,a){if(e===void 0)return null;let f=g(e,t);y(f,["recordResourceCode","recordIdInputField","relationField","fileNameField","contentTypeField","sizeField","purposes","maxTtlSeconds","maxBytes"],t),(o!=="GET"||n!=="read"||s!=="none")&&p("NATIVE_OPERATION_FILE_INTENT_BEHAVIOR_INVALID",t);let E=z(f.recordResourceCode,`${t}/recordResourceCode`),d=a.get(E);d||p("NATIVE_OPERATION_FILE_INTENT_RESOURCE_NOT_DECLARED",`${t}/recordResourceCode`);let u=B(f.recordIdInputField,`${t}/recordIdInputField`),m=g(c[u],`${t}/recordIdInputField`);(!r.has(u)||m.type!=="string"||m.format!=="uuid")&&p("NATIVE_OPERATION_FILE_INTENT_RECORD_INPUT_INVALID",`${t}/recordIdInputField`);let l=B(f.relationField,`${t}/relationField`),A=d.get(l);(!A||!["uuid","resource-ref.single"].includes(String(A.type))||String(A.type)==="resource-ref.single"&&(String(g(A.source,`${t}/relationField`).kind||"")!=="resource"||String(g(A.source,`${t}/relationField`).resourceCode||"")!==i))&&p("NATIVE_OPERATION_FILE_INTENT_RELATION_INVALID",`${t}/relationField`);let N=[["fileNameField",["text.short","text.long"]],["contentTypeField",["text.short","text.long"]],["sizeField",["number.integer"]]],_={};for(let[C,O]of N){let S=B(f[C],`${t}/${C}`);O.includes(String(d.get(S)?.type))||p("NATIVE_OPERATION_FILE_INTENT_METADATA_INVALID",`${t}/${C}`),_[C]=S}let I=X(F(f.purposes,`${t}/purposes`,2),C=>C);(!I.length||I.some(C=>!["preview","download"].includes(C)))&&p("NATIVE_OPERATION_FILE_INTENT_PURPOSE_INVALID",`${t}/purposes`);let T=Number(f.maxTtlSeconds);(!Number.isSafeInteger(T)||T<1||T>300)&&p("NATIVE_OPERATION_FILE_INTENT_TTL_INVALID",`${t}/maxTtlSeconds`);let b=Number(f.maxBytes);return(!Number.isSafeInteger(b)||b<1||b>104857600)&&p("NATIVE_OPERATION_FILE_INTENT_SIZE_INVALID",`${t}/maxBytes`),{recordResourceCode:E,recordIdInputField:u,relationField:l,fileNameField:_.fileNameField,contentTypeField:_.contentTypeField,sizeField:_.sizeField,purposes:I,maxTtlSeconds:T,maxBytes:b}}function ni(e,t,o,n,s,i){if(e===void 0)return null;let c=g(e,t);y(c,["directory","managedFiles","managedFileCopies","notification","workflow","roleAssertions","decimalReservation"],t,!0),Object.keys(c).length===0&&p("NATIVE_OPERATION_PLATFORM_ACCESS_EMPTY",t);let r={};if(c.roleAssertions!==void 0){let a=g(c.roleAssertions,`${t}/roleAssertions`);y(a,["roleCodes"],`${t}/roleAssertions`);let f=F(a.roleCodes,`${t}/roleAssertions/roleCodes`,20);f.length||p("NATIVE_OPERATION_ROLE_ASSERTIONS_REQUIRED",`${t}/roleAssertions/roleCodes`),f.forEach((E,d)=>{i.has(E)||p("NATIVE_ROLE_REFERENCE_MISSING",`${t}/roleAssertions/roleCodes/${d}`)}),r.roleAssertions={roleCodes:M(f)}}if(c.directory!==void 0){let a=g(c.directory,`${t}/directory`);y(a,["mode","fields"],`${t}/directory`),a.mode!=="current-initiator"&&p("NATIVE_OPERATION_DIRECTORY_MODE_INVALID",`${t}/directory/mode`);let f=new Set(["displayName","employeeNumber","primaryDepartment","departments"]),E=F(a.fields,`${t}/directory/fields`,4);(!E.length||E.some(d=>!f.has(d)))&&p("NATIVE_OPERATION_DIRECTORY_FIELDS_INVALID",`${t}/directory/fields`),r.directory={mode:"current-initiator",fields:M(E)}}if(c.managedFiles!==void 0){let a=$(c.managedFiles,`${t}/managedFiles`,16);a.length||p("NATIVE_OPERATION_MANAGED_FILES_REQUIRED",`${t}/managedFiles`);let f=new Set;r.managedFiles=X(a.map((E,d)=>{let u=`${t}/managedFiles/${d}`,m=g(E,u);y(m,["resourceCode","fieldCodes","intents"],u);let l=z(m.resourceCode,`${u}/resourceCode`);(f.has(l)||!o.has(l))&&p("NATIVE_OPERATION_MANAGED_FILE_RESOURCE_INVALID",`${u}/resourceCode`),f.add(l);let A=F(m.fieldCodes,`${u}/fieldCodes`,16);(!A.length||A.some(_=>!["file","image","signature"].includes(String(o.get(l)?.get(_)||""))))&&p("NATIVE_OPERATION_MANAGED_FILE_FIELD_INVALID",`${u}/fieldCodes`);let N=F(m.intents,`${u}/intents`,2);return(!N.length||N.some(_=>!["create","update"].includes(_)))&&p("NATIVE_OPERATION_MANAGED_FILE_INTENT_INVALID",`${u}/intents`),{resourceCode:l,fieldCodes:M(A),intents:M(N)}}),E=>E.resourceCode)}if(c.managedFileCopies!==void 0){let a=$(c.managedFileCopies,`${t}/managedFileCopies`,16);a.length||p("NATIVE_OPERATION_MANAGED_FILE_COPIES_REQUIRED",`${t}/managedFileCopies`);let f=new Set;r.managedFileCopies=X(a.map((E,d)=>{let u=`${t}/managedFileCopies/${d}`,m=g(E,u);y(m,["mode","sourceResourceCode","sourceFieldCodes","targetResourceCode","targetFieldCodes"],u),L(m.mode,"copy",`${u}/mode`);let l=z(m.sourceResourceCode,`${u}/sourceResourceCode`),A=z(m.targetResourceCode,`${u}/targetResourceCode`),N=o.get(l),_=o.get(A);(!N||!_)&&p("NATIVE_OPERATION_MANAGED_FILE_COPY_RESOURCE_INVALID",u);let I=F(m.sourceFieldCodes,`${u}/sourceFieldCodes`,16),T=F(m.targetFieldCodes,`${u}/targetFieldCodes`,16);(!I.length||I.length!==T.length)&&p("NATIVE_OPERATION_MANAGED_FILE_COPY_FIELDS_INVALID",u),I.forEach((C,O)=>{let S=N.get(C),D=_.get(T[O]);(!["file","image"].includes(String(S))||S!==D)&&p("NATIVE_OPERATION_MANAGED_FILE_COPY_FIELD_INVALID",`${u}/sourceFieldCodes/${O}`)});let b=`${l}:${I.join(",")}=>${A}:${T.join(",")}`;return f.has(b)&&p("NATIVE_OPERATION_MANAGED_FILE_COPY_DUPLICATE",u),f.add(b),{mode:"copy",sourceResourceCode:l,sourceFieldCodes:M(I),targetResourceCode:A,targetFieldCodes:M(T)}}),E=>`${E.sourceResourceCode}:${E.sourceFieldCodes.join(",")}=>${E.targetResourceCode}:${E.targetFieldCodes.join(",")}`)}if(c.notification!==void 0){let a=g(c.notification,`${t}/notification`);y(a,["mode"],`${t}/notification`),a.mode!=="business-standard"&&p("NATIVE_OPERATION_NOTIFICATION_MODE_INVALID",`${t}/notification/mode`),r.notification={mode:"business-standard"}}if(c.workflow!==void 0){let a=g(c.workflow,`${t}/workflow`);y(a,["codes"],`${t}/workflow`);let f=F(a.codes,`${t}/workflow/codes`,16);(!f.length||f.some(E=>!s.has(E)))&&p("NATIVE_OPERATION_WORKFLOW_CODE_INVALID",`${t}/workflow/codes`),r.workflow={codes:M(f)}}if(c.decimalReservation!==void 0){let a=`${t}/decimalReservation`,f=g(c.decimalReservation,a);y(f,["mode","resourceCode","amountFieldCode","currencyFieldCode","relationFieldCode","parentFieldCode","rootFieldCode","statusFieldCode","parentRelationValue","childRelationValue","eligibleParentStatuses","eligibleChildStatuses"],a);let E=R(f.mode,`${a}/mode`,16);["reserve","commit","release"].includes(E)||p("NATIVE_DECIMAL_RESERVATION_MODE_INVALID",`${a}/mode`);let d=z(f.resourceCode,`${a}/resourceCode`),u=n.get(d);u||p("NATIVE_DECIMAL_RESERVATION_RESOURCE_MISSING",`${a}/resourceCode`);let l=Object.fromEntries(["amountFieldCode","currencyFieldCode","relationFieldCode","parentFieldCode","rootFieldCode","statusFieldCode"].map(C=>[C,B(f[C],`${a}/${C}`)])),A=C=>u.get(l[C]),N=C=>new Set((A(C)?.options||[]).map(O=>String(O.value))),_=w(f.parentRelationValue,`${a}/parentRelationValue`),I=w(f.childRelationValue,`${a}/childRelationValue`),T=F(f.eligibleParentStatuses,`${a}/eligibleParentStatuses`,16),b=F(f.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!==d||A("rootFieldCode")?.type!=="uuid"||A("statusFieldCode")?.type!=="option.single"||_===I||!N("relationFieldCode").has(_)||!N("relationFieldCode").has(I)||!T.length||!b.length||T.some(C=>!N("statusFieldCode").has(C))||b.some(C=>!N("statusFieldCode").has(C)))&&p("NATIVE_DECIMAL_RESERVATION_FIELD_INVALID",a),r.decimalReservation={mode:E,resourceCode:d,...l,parentRelationValue:_,childRelationValue:I,eligibleParentStatuses:M(T),eligibleChildStatuses:M(b)}}return r}function oi(e,t,o,n,s){if(e===void 0)return;let i=`${t}/ai`,c=g(e,i);bs.test(o)||p("NATIVE_OPERATION_AI_CODE_INVALID",`${t}/code`),y(c,["name","description","risk","resources","sideEffects","concurrency","timeoutMs"],i,!0),R(c.name,`${i}/name`,jt),R(c.description,`${i}/description`,jt);let r=R(c.risk,`${i}/risk`,16);["read","write","destructive","external"].includes(r)||p("NATIVE_OPERATION_AI_RISK_INVALID",`${i}/risk`),r==="read"!=(n==="GET")&&p("NATIVE_OPERATION_AI_METHOD_RISK_MISMATCH",`${i}/risk`),n==="DELETE"&&!["destructive","external"].includes(r)&&p("NATIVE_OPERATION_AI_METHOD_RISK_MISMATCH",`${i}/risk`);let a=F(c.resources,`${i}/resources`,16);a.length===0&&p("NATIVE_OPERATION_AI_RESOURCE_REQUIRED",`${i}/resources`),a.forEach((E,d)=>{let u=z(E,`${i}/resources/${d}`);s.has(u)||p("NATIVE_OPERATION_AI_RESOURCE_MISSING",`${i}/resources/${d}`)});let f=F(c.sideEffects,`${i}/sideEffects`,20);(r==="read"&&f.length!==0||r!=="read"&&f.length===0)&&p("NATIVE_OPERATION_AI_SIDE_EFFECT_INVALID",`${i}/sideEffects`),c.concurrency!==void 0&&!["none","revision"].includes(R(c.concurrency,`${i}/concurrency`,16))&&p("NATIVE_OPERATION_AI_CONCURRENCY_INVALID",`${i}/concurrency`),c.timeoutMs!==void 0&&Z(c.timeoutMs,`${i}/timeoutMs`,100,3e4)}function it(e){return(e.replace(/\/{2,}/g,"/").replace(/\/$/,"")||"/").split("/").map(o=>o.startsWith(":")?":":o.includes("*")?"*":o).join("/")}function si(e,t){let o=g(e,t),n=R(o.type,`${t}/type`,32),s=["code","type","label","presentation","required"],i=n==="sso"?[...s,"provider"]:n==="dingtalk"?[...s,"flow"]:s;y(o,i,t);let c=w(o.code,`${t}/code`),r=R(o.label,`${t}/label`,255),a=R(o.presentation,`${t}/presentation`,16);["primary","secondary"].includes(a)||p("NATIVE_APPLICATION_AUTH_METHOD_PRESENTATION_INVALID",`${t}/presentation`);let f=Fe(o.required,`${t}/required`);return["sso","password","dingtalk"].includes(n)||p("NATIVE_APPLICATION_AUTH_METHOD_TYPE_INVALID",`${t}/type`),n==="sso"&&o.provider!=="tenant-default"&&p("NATIVE_APPLICATION_AUTH_SSO_PROVIDER_INVALID",`${t}/provider`),n==="dingtalk"&&!["auto","jsapi","oauth"].includes(R(o.flow,`${t}/flow`,16))&&p("NATIVE_APPLICATION_AUTH_DINGTALK_FLOW_INVALID",`${t}/flow`),{code:c,type:n,label:r,presentation:a,required:f,...n==="sso"?{provider:"tenant-default"}:{},...n==="dingtalk"?{flow:o.flow}:{}}}function Jn(e,t,o){let n=g(e,o);y(n,["routeCode","path","defaultRouteCode"],o);let s=w(n.routeCode,`${o}/routeCode`),i=le(n.path,`${o}/path`),c=t==="desktop"?"/login":"/m/login";return(i!==c||/[:*?#\\]/.test(i))&&p("NATIVE_APPLICATION_AUTH_SURFACE_PATH_INVALID",`${o}/path`,{device:t,expectedPath:c}),{routeCode:s,path:i,defaultRouteCode:w(n.defaultRouteCode,`${o}/defaultRouteCode`)}}function ao(e,t,o,n){if(e===null)return;let s=g(e,n);y(s,["accountMode","registration","methods","surfaces"],n),L(s.accountMode,"existing-platform-users-only",`${n}/accountMode`);let i=g(s.registration,`${n}/registration`);y(i,["mode"],`${n}/registration`),L(i.mode,"reject",`${n}/registration/mode`);let c=$(s.methods,`${n}/methods`,8);c.length===0&&p("NATIVE_APPLICATION_AUTH_METHOD_REQUIRED",`${n}/methods`);let r=c.map((_,I)=>si(_,`${n}/methods/${I}`)),a=new Set,f=new Set;for(let[_,I]of r.entries())a.has(I.code)&&p("NATIVE_APPLICATION_AUTH_METHOD_CODE_DUPLICATE",`${n}/methods/${_}/code`),f.has(I.type)&&p("NATIVE_APPLICATION_AUTH_METHOD_TYPE_DUPLICATE",`${n}/methods/${_}/type`),a.add(I.code),f.add(I.type);r.filter(_=>_.presentation==="primary").length!==1&&p("NATIVE_APPLICATION_AUTH_PRIMARY_METHOD_INVALID",`${n}/methods`);let E=g(s.surfaces,`${n}/surfaces`);y(E,["desktop","mobile"],`${n}/surfaces`);let d=Jn(E.desktop,"desktop",`${n}/surfaces/desktop`),u=Jn(E.mobile,"mobile",`${n}/surfaces/mobile`);d.routeCode===u.routeCode&&p("NATIVE_APPLICATION_AUTH_SURFACE_CODE_DUPLICATE",`${n}/surfaces/mobile/routeCode`);let m=$(t,"/config/frontend/routes",500),l=new Map;for(let[_,I]of m.entries()){let T=g(I,`/config/frontend/routes/${_}`);l.set(String(T.code||""),T)}let A=new Set((Array.isArray(o.data?.resources)?o.data.resources:[]).map(_=>String(_.code||"")).filter(_=>/^[a-z][a-z0-9-]{0,62}$/.test(_)));for(let[_,I]of[["desktop",d],["mobile",u]]){l.has(I.routeCode)&&p("NATIVE_APPLICATION_AUTH_SURFACE_CODE_CONFLICT",`${n}/surfaces/${_}/routeCode`);let T=/^user\.([a-z][a-z0-9-]{0,62})\.(records|submit)$/.exec(String(I.defaultRouteCode||"")),b=l.get(I.defaultRouteCode),C=String(b?.path||"");if(T&&A.has(T[1])){let S=T[2]==="records"?`/my/${T[1]}`:`/my/${T[1]}/submit`;b={surface:"user",path:_==="mobile"?`/m${S}`:S},C=String(b.path)}let O=_==="desktop"?C==="/m"||C.startsWith("/m/"):!(C==="/m"||C.startsWith("/m/"));(!b||b.surface!=="user"||/[:*]/.test(C)||O)&&p("NATIVE_APPLICATION_AUTH_DEFAULT_ROUTE_INVALID",`${n}/surfaces/${_}/defaultRouteCode`)}let N=co(o).filter(_=>!_.owner.startsWith("authentication:"));for(let[_,I]of[["desktop",d],["mobile",u]]){let T=N.find(b=>it(b.path)===it(I.path));T&&p("NATIVE_APPLICATION_AUTH_SURFACE_PATH_CONFLICT",`${n}/surfaces/${_}/path`,{owner:T.owner})}}function ii(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=g(e,t),s=g(n.surfaces,`${t}/surfaces`),i={...n,surfaces:{...s,desktop:{...g(s.desktop,`${t}/surfaces/desktop`),defaultRouteCode:"auth-desktop-default"},mobile:{...g(s.mobile,`${t}/surfaces/mobile`),defaultRouteCode:"auth-mobile-default"}}};ao(i,o.frontend.routes,{...o,frontend:{...o.frontend,authentication:i}},t)}function ri(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 ai=new Set(["draft.read","draft.update","validate","create","own.list","own.read","public.list","public.read"]);function ci(e,t,o){let n=g(e,o);y(n,["policies"],o);let s=$(n.policies,`${o}/policies`,16);s.length<1&&p("NATIVE_PUBLIC_POLICY_REQUIRED",o);let i=new Map(t.frontend.routes.map(f=>[f.code,f])),c=new Map(t.data.resources.map(f=>[f.code,f])),r=new Set,a=new Set(s.map(f=>String(f?.code||"")));s.forEach((f,E)=>{let d=`${o}/policies/${E}`,u=g(f,d);y(u,["code","routeCode","mode","resourceCode","operations","fields"],d,["requiredFields","ownRecordFields","publicRecordFields","publicFilters","serverGeneratedFields","schedule","publicSubtableFields","draft","validations"]);let m=w(u.code,`${d}/code`);r.has(m)&&p("NATIVE_PUBLIC_POLICY_DUPLICATE",`${d}/code`);let l=w(u.routeCode,`${d}/routeCode`),A=i.get(l);(!A||A.surface!=="user"||A.capability!==void 0||A.access!==void 0||/[:*]/.test(String(A.path)))&&p("NATIVE_PUBLIC_ROUTE_INVALID",`${d}/routeCode`),L(u.mode,"anonymous",`${d}/mode`);let N=z(u.resourceCode,`${d}/resourceCode`),_=c.get(N);_||p("NATIVE_PUBLIC_RESOURCE_MISSING",`${d}/resourceCode`);let I=new Map(_.schema.fields.map(V=>[String(V.code),String(V.type)])),T=F(u.operations,`${d}/operations`,8);(T.length<1||T.some(V=>!ai.has(V)))&&p("NATIVE_PUBLIC_OPERATION_INVALID",`${d}/operations`),T.includes("draft.read")!==T.includes("draft.update")&&p("NATIVE_PUBLIC_DRAFT_OPERATION_INCOMPLETE",`${d}/operations`);let b=F(u.fields,`${d}/fields`,64);(b.length<1||b.some(V=>!I.has(V)))&&p("NATIVE_PUBLIC_FIELD_INVALID",`${d}/fields`);for(let V of["requiredFields","ownRecordFields","publicRecordFields"]){if(!Object.prototype.hasOwnProperty.call(u,V))continue;F(u[V],`${d}/${V}`,64).some(v=>!b.includes(v))&&p("NATIVE_PUBLIC_FIELD_SCOPE_INVALID",`${d}/${V}`)}let C=Object.prototype.hasOwnProperty.call(u,"serverGeneratedFields")?$(u.serverGeneratedFields,`${d}/serverGeneratedFields`,16):[],O=new Set;C.forEach((V,x)=>{let v=`${d}/serverGeneratedFields/${x}`,J=g(V,v);y(J,["field","kind"],v);let W=B(J.field,`${v}/field`);(O.has(W)||!I.has(W)||b.includes(W)||I.get(W)!=="text.short"&&I.get(W)!=="text.long")&&p("NATIVE_PUBLIC_SERVER_GENERATED_FIELD_INVALID",`${v}/field`),L(J.kind,"random-token",`${v}/kind`),O.add(W)});let S=Object.prototype.hasOwnProperty.call(u,"schedule")?g(u.schedule,`${d}/schedule`):null;if(S){let V=["campusPolicyCode","rulePolicyCode","campusField","ruleCampusField","ruleWeekdaysField","ruleOpenAtField","ruleCloseAtField","ruleSlotMinutesField","ruleAdvanceHoursField","ruleAdvanceDaysField","campusEnabledField","ruleEnabledField","dateField","timeField"];y(S,V,`${d}/schedule`);for(let x of["campusPolicyCode","rulePolicyCode"])w(S[x],`${d}/schedule/${x}`);for(let x of V.filter(v=>!["campusPolicyCode","rulePolicyCode"].includes(v)))B(S[x],`${d}/schedule/${x}`);for(let x of[S.campusField,S.dateField,S.timeField])b.includes(String(x))||p("NATIVE_PUBLIC_SCHEDULE_FIELD_INVALID",`${d}/schedule`);(!a.has(String(S.campusPolicyCode))||!a.has(String(S.rulePolicyCode)))&&p("NATIVE_PUBLIC_SCHEDULE_POLICY_INVALID",`${d}/schedule`)}let D=Object.prototype.hasOwnProperty.call(u,"publicFilters")?$(u.publicFilters,`${d}/publicFilters`,16):[],U=new Set;D.forEach((V,x)=>{let v=`${d}/publicFilters/${x}`,J=g(V,v);y(J,["field","operator","value"],v);let W=B(J.field,`${v}/field`);U.has(W)&&p("NATIVE_PUBLIC_FILTER_DUPLICATE",`${v}/field`),b.includes(W)||p("NATIVE_PUBLIC_FILTER_FIELD_INVALID",`${v}/field`),L(J.operator,"eq",`${v}/operator`),["boolean","text.short","text.long","number.integer","number.decimal","date","time"].includes(I.get(W)||"")||p("NATIVE_PUBLIC_FILTER_FIELD_INVALID",`${v}/field`),J.value!==null&&typeof J.value!="string"&&typeof J.value!="number"&&typeof J.value!="boolean"&&p("NATIVE_PUBLIC_FILTER_VALUE_INVALID",`${v}/value`),U.add(W)});let k=Object.prototype.hasOwnProperty.call(u,"publicSubtableFields")?g(u.publicSubtableFields,`${d}/publicSubtableFields`):null;if(k){Object.keys(k).length>64&&p("NATIVE_PUBLIC_SUBTABLE_FIELDS_INVALID",`${d}/publicSubtableFields`);for(let[V,x]of Object.entries(k)){let v=_.schema.fields.find(H=>String(H.code)===V),J=String(v?.subtable?.resourceCode||""),W=c.get(J),me=new Map((W?.schema?.fields||[]).map(H=>[String(H.code),String(H.type)])),G=F(x,`${d}/publicSubtableFields/${V}`,64);(!b.includes(V)||I.get(V)!=="subtable"||!W||G.length<1||G.some(H=>!me.has(H))||G.some(H=>me.get(H)==="subtable")||G.some(H=>me.get(H)==="signature"))&&p("NATIVE_PUBLIC_SUBTABLE_FIELDS_INVALID",`${d}/publicSubtableFields/${V}`)}}if(T.some(V=>V.startsWith("public."))){Object.prototype.hasOwnProperty.call(u,"publicRecordFields")||p("NATIVE_PUBLIC_RECORD_FIELDS_REQUIRED",`${d}/publicRecordFields`);let V=F(u.publicRecordFields,`${d}/publicRecordFields`,64);(V.length<1||V.some(x=>!b.includes(x))||V.some(x=>I.get(x)==="signature"||I.get(x)==="subtable"&&!k?.[x]))&&p("NATIVE_PUBLIC_RECORD_FIELDS_INVALID",`${d}/publicRecordFields`)}let q=Object.prototype.hasOwnProperty.call(u,"requiredFields")?F(u.requiredFields,`${d}/requiredFields`,64):[],j=_.surface||{},ue=j.fields||{},fe=String(j.mutationOwner||"native")==="native"&&j.generated?.create!==!1,K=_.schema.fields.filter(V=>Ke(V,ue[V.code])).map(V=>String(V.code));if(T.includes("create")&&!fe&&p("NATIVE_PUBLIC_CREATE_FIELDS_INCOMPLETE",`${d}/fields`),T.includes("create")&&!Object.prototype.hasOwnProperty.call(u,"draft")&&p("NATIVE_PUBLIC_DRAFT_REQUIRED",`${d}/draft`),T.includes("create"))for(let V of K){let x=b.includes(V)?q.includes(V)?null:"requiredFields":"fields";x&&p("NATIVE_PUBLIC_CREATE_FIELDS_INCOMPLETE",`${d}/${x}`,{resourceCode:z,fieldCode:V})}if(Object.prototype.hasOwnProperty.call(u,"draft")){let V=g(u.draft,`${d}/draft`);y(V,["enabled","inactivityTtlSeconds","maxBytes"],`${d}/draft`),L(V.enabled,!0,`${d}/draft/enabled`),Z(V.inactivityTtlSeconds,`${d}/draft/inactivityTtlSeconds`,3600,7776e3),Z(V.maxBytes,`${d}/draft/maxBytes`,4096,262144)}else T.includes("draft.read")&&p("NATIVE_PUBLIC_DRAFT_REQUIRED",`${d}/draft`);let Ie=Object.prototype.hasOwnProperty.call(u,"validations")?$(u.validations,`${d}/validations`,16):[],ie=new Set;Ie.forEach((V,x)=>{let v=`${d}/validations/${x}`,J=g(V,v);y(J,["code","kind","fields","result"],v);let W=w(J.code,`${v}/code`);ie.has(W)&&p("NATIVE_PUBLIC_VALIDATION_DUPLICATE",`${v}/code`),L(J.kind,"duplicate",`${v}/kind`),L(J.result,"availability",`${v}/result`);let me=F(J.fields,`${v}/fields`,8);(me.length<1||me.some(G=>!b.includes(G))||me.some(G=>["file","subtable"].includes(I.get(G)||"")))&&p("NATIVE_PUBLIC_VALIDATION_FIELD_INVALID",`${v}/fields`),ie.add(W)}),r.add(m)})}function di(e,t){let o=g(e,t);y(o,["policies"],t),$(o.policies,`${t}/policies`,16).length<1&&p("NATIVE_PUBLIC_POLICY_REQUIRED",t)}function li(e){return{policies:X(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)=>ae(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)=>ae(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:X(t.validations.map(o=>({code:o.code,kind:o.kind,fields:M(o.fields),result:o.result})),o=>o.code)}:{}})),t=>t.code)}}function co(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=lo(o),s=`/admin/resources/${o.code}`,i=[["list",s],["detail",`${s}/:id`],["create",`${s}/new`],["update",`${s}/:id/edit`]];for(let[c,r]of i)n[c]&&t.push({owner:`resource:${o.code}:${c}`,path:r},{owner:`resource:${o.code}:${c}:mobile`,path:`/m${r}`})}if(e.frontend.user.applicationTodoCenter===!0&&t.push({owner:"application:todo-center",path:"/todos"},{owner:"application:todo-center:mobile",path:"/m/todos"}),e.workflows.definitions.length>0){t.push({owner:"workflow:work-center",path:"/work-center"},{owner:"workflow:work-center:mobile",path:"/m/work-center"},{owner:"workflow:task",path:"/tasks/:taskId"},{owner:"workflow:task:mobile",path:"/m/tasks/:taskId"},{owner:"workflow:instance",path:"/workflows/:instanceId"},{owner:"workflow:instance:mobile",path:"/m/workflows/:instanceId"});let o=!1;for(let n of e.workflows.definitions)["standalone","hidden-handoff"].includes(n.launch.mode)&&(o=!0);o&&t.push({owner:"workflow:launch",path:"/workflows/:workflowCode/start"},{owner:"workflow:launch:mobile",path:"/m/workflows/:workflowCode/start"})}return t}function ct(e){let t=new Map(co(e).map(o=>[it(o.path),o]));return X(e.frontend.routes.map((o,n)=>{let s=`/config/frontend/routes/${n}`,i=g(o,s);y(i,["code","path","label","surface","parentCode","capability","access","pinned","tabPersistence","keepAlive"],s,!0),["admin","user"].includes(i.surface)||p("NATIVE_ROUTE_SURFACE_INVALID",`${s}/surface`);let c=le(i.path,`${s}/path`);i.surface==="admin"&&c!=="/admin"&&!c.startsWith("/admin/")&&p("NATIVE_ADMIN_ROUTE_PATH_INVALID",`${s}/path`),i.surface==="user"&&(c==="/admin"||c.startsWith("/admin/"))&&p("NATIVE_USER_ROUTE_PATH_RESERVED",`${s}/path`);let r=it(c),a=t.get(r);a&&p("NATIVE_ROUTE_PATH_CONFLICT",`${s}/path`,{path:c,owner:a.owner}),t.set(r,{owner:`frontend:${String(i.code||n)}`,path:c});let f=/[:*]/.test(c),E=Yt(i,s,e.appCode),d=i.pinned===void 0?void 0:Fe(i.pinned,`${s}/pinned`),u=i.tabPersistence===void 0?f?"none":"session":R(i.tabPersistence,`${s}/tabPersistence`,16),m=i.keepAlive===void 0?"none":R(i.keepAlive,`${s}/keepAlive`,16);return["session","none"].includes(u)||p("NATIVE_ROUTE_TAB_PERSISTENCE_INVALID",`${s}/tabPersistence`),["none","memory"].includes(m)||p("NATIVE_ROUTE_KEEP_ALIVE_INVALID",`${s}/keepAlive`),f&&d===!0&&p("NATIVE_DYNAMIC_ROUTE_PINNED_FORBIDDEN",`${s}/pinned`),f&&u==="session"&&p("NATIVE_DYNAMIC_ROUTE_TAB_PERSISTENCE_FORBIDDEN",`${s}/tabPersistence`),f&&m==="memory"&&p("NATIVE_DYNAMIC_ROUTE_KEEP_ALIVE_FORBIDDEN",`${s}/keepAlive`),{code:w(i.code,`${s}/code`),path:c,label:R(i.label,`${s}/label`,255),surface:i.surface,...i.parentCode===void 0?{}:{parentCode:w(i.parentCode,`${s}/parentCode`)},...E,...d===void 0?{}:{pinned:d},tabPersistence:u,keepAlive:m}}),o=>o.code)}function lo(e){let t=e.surface===void 0?{}:g(e.surface,"/surface"),o=t.mutationOwner||"native",n=t.generated===void 0?{}:g(t.generated,"/surface/generated"),s=o==="native";return{list:n.list??!0,detail:n.detail??!0,create:n.create??s,update:n.update??s,delete:n.delete??s}}function uo(e){let t=[];for(let o of X(e.data.resources,n=>n.code).flatMap(n=>[{resource:n,viewCode:void 0},...(n.surface?.views||[]).map(s=>({viewCode:s.code,resource:{...n,name:s.name,surface:Rt(n.surface,s.code)}}))])){let{resource:n,viewCode:s}=o,i=`/admin/resources/${n.code}${s?`/views/${s}`:""}`,c=lo(n),r=[{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 r)c[a.operation]&&t.push({code:`resource:${n.code}${s?`:view:${s}`:""}:${a.operation}`,kind:a.kind,path:a.path,label:a.label,navigationEligible:a.navigationEligible,capability:a.capability,resourceCode:n.code,...s?{viewCode:s}:{}})}for(let o of ct(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)=>ae(o.code,n.code))}function fo(e){return e.kind==="resource"?`resource:${e.resourceCode}${e.viewCode?`:view:${e.viewCode}`:""}:list`:`operation:${e.routeCode}`}function ui(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,s)=>({pageCode:fo(n.page),...n.label===void 0?{}:{label:n.label},...n.icon===void 0?{}:{icon:n.icon},order:n.order??s})).sort((n,s)=>n.order-s.order||ae(n.pageCode,s.pageCode))})).sort((t,o)=>t.order-o.order||ae(t.code,o.code))}function fi(e,t){let o=$(e,t,Y.adminNavigationGroups),n=0;o.forEach((s,i)=>{let c=`${t}/${i}`,r=g(s,c);y(r,["code","label","icon","order","items"],c,!0),w(r.code,`${c}/code`),R(r.label,`${c}/label`,255),rt(r.icon,`${c}/icon`),Yn(r.order,`${c}/order`);let a=$(r.items,`${c}/items`,500);a.length===0&&p("NATIVE_ADMIN_GROUP_ORPHANED",`${c}/items`),n+=a.length,n>Y.adminNavigationItems&&p("NATIVE_ARRAY_LIMIT_EXCEEDED",t),a.forEach((f,E)=>{let d=`${c}/items/${E}`,u=g(f,d);y(u,["page","label","icon","order"],d,!0),pi(u.page,`${d}/page`),u.label!==void 0&&R(u.label,`${d}/label`,255),rt(u.icon,`${d}/icon`),Yn(u.order,`${d}/order`)})})}function pi(e,t){let o=g(e,t),n=R(o.kind,`${t}/kind`,64);if(n==="resource"){y(o,["kind","resourceCode"],t,["viewCode"]),o.viewCode!==void 0&&w(o.viewCode,`${t}/viewCode`),z(o.resourceCode,`${t}/resourceCode`);return}if(n==="operation"){y(o,["kind","routeCode"],t),w(o.routeCode,`${t}/routeCode`);return}p("NATIVE_ADMIN_PAGE_REFERENCE_KIND_INVALID",`${t}/kind`)}function _i(e){let t=new Map(uo(e).map(s=>[String(s.code),s])),o=new Set,n=new Set;e.frontend.admin.navigation.forEach((s,i)=>{let c=`/config/frontend/admin/navigation/${i}`;o.has(s.code)&&p("NATIVE_ADMIN_GROUP_DUPLICATE",`${c}/code`),o.add(s.code),s.label===s.code&&p("NATIVE_ADMIN_USER_LABEL_REQUIRED",`${c}/label`),s.items.forEach((r,a)=>{let f=`${c}/items/${a}`,E=fo(r.page),d=t.get(E);(!d||d.navigationEligible!==!0)&&p("NATIVE_ADMIN_PAGE_NOT_FOUND",`${f}/page`),n.has(E)&&p("NATIVE_ADMIN_PAGE_DUPLICATE",`${f}/page`),n.add(E);let u=r.page.resourceCode||r.page.routeCode||r.page.workflowCode||E,m=r.label||d.label;(!m||m===u||m===E)&&p("NATIVE_ADMIN_USER_LABEL_REQUIRED",`${f}/label`)})})}function Ei(e,t){let o=$(e,t,Y.adminPages),n=new Set;o.forEach((s,i)=>{let c=`${t}/${i}`,r=g(s,c);y(r,["code","kind","path","label","navigationEligible","capability","access","resourceCode","viewCode","routeCode"],c,!0);let a=R(r.code,`${c}/code`,255);n.has(a)&&p("NATIVE_ADMIN_PAGE_DUPLICATE",`${c}/code`),n.add(a);let f=R(r.kind,`${c}/kind`,64);if(["resource-list","resource-detail","resource-create","resource-update","operation"].includes(f)||p("NATIVE_ADMIN_PAGE_KIND_INVALID",`${c}/kind`),le(r.path,`${c}/path`),R(r.label,`${c}/label`,255),Fe(r.navigationEligible,`${c}/navigationEligible`),r.capability!==void 0&&r.access!==void 0&&p("NATIVE_ROUTE_ACCESS_CONFLICT",`${c}/access`),r.capability!==void 0&&R(r.capability,`${c}/capability`,255),r.access!==void 0){let E=g(r.access,`${c}/access`);y(E,["allOf","anyOf"],`${c}/access`,!0);for(let d of["allOf","anyOf"])E[d]!==void 0&&F(E[d],`${c}/access/${d}`,50)}for(let E of["resourceCode","viewCode","routeCode"])r[E]!==void 0&&w(r[E],`${c}/${E}`)})}function Ai(e,t){let o=$(e,t,Y.adminNavigationGroups),n=0;o.forEach((s,i)=>{let c=`${t}/${i}`,r=g(s,c);y(r,["code","label","icon","order","items"],c,!0),w(r.code,`${c}/code`),R(r.label,`${c}/label`,255),rt(r.icon,`${c}/icon`),Z(r.order,`${c}/order`,-1e4,1e4);let a=$(r.items,`${c}/items`,500);a.length===0&&p("NATIVE_ADMIN_GROUP_ORPHANED",`${c}/items`),n+=a.length,n>Y.adminNavigationItems&&p("NATIVE_ARRAY_LIMIT_EXCEEDED",t),a.forEach((f,E)=>{let d=`${c}/items/${E}`,u=g(f,d);y(u,["pageCode","label","icon","order"],d,!0),R(u.pageCode,`${d}/pageCode`,255),u.label!==void 0&&R(u.label,`${d}/label`,255),rt(u.icon,`${d}/icon`),Z(u.order,`${d}/order`,-1e4,1e4)})})}var Ii=new Set(["application-todo-center","workflow-work-center","workflow-launch","workflow-task","workflow-instance","resource-records","resource-submit"]);function mi(e,t,o){let n=g(e,t);y(n,["schemaVersion","appCode","devicePolicy","rootEntry","authentication","routes","digest"],t),L(n.schemaVersion,so,`${t}/schemaVersion`),L(n.appCode,o,`${t}/appCode`),qt(n.devicePolicy,`${t}/devicePolicy`),gi(n.rootEntry,`${t}/rootEntry`),Ni(n.authentication,`${t}/authentication`),zt(n.digest,`${t}/digest`);let s=$(n.routes,`${t}/routes`,Y.routes),i=new Set;s.forEach((c,r)=>{let a=`${t}/routes/${r}`,f=g(c,a),E=f.kind==="resource-records"||f.kind==="resource-submit";y(f,["code","kind","desktop","mobile"],a,["workflowCode",...E?["resourceCode"]:[]]);let d=R(f.code,`${a}/code`,255);i.has(d)&&p("NATIVE_ROUTE_MANIFEST_DUPLICATE",`${a}/code`),i.add(d);let u=R(f.kind,`${a}/kind`,64);if(Ii.has(u)||p("NATIVE_ROUTE_MANIFEST_KIND_INVALID",`${a}/kind`),f.workflowCode!==void 0&&w(f.workflowCode,`${a}/workflowCode`),E){let A=z(f.resourceCode,`${a}/resourceCode`);L(d,`user.${A}.${f.kind==="resource-records"?"records":"submit"}`,`${a}/code`)}else f.resourceCode!==void 0&&p("NATIVE_PROPERTY_UNKNOWN",`${a}/resourceCode`);let m=zn(f.desktop,`${a}/desktop`,o),l=zn(f.mobile,`${a}/mobile`,o);m.surface!=="user"&&p("NATIVE_ROUTE_MANIFEST_DESKTOP_SURFACE_INVALID",`${a}/desktop/surface`),l.surface!=="user"&&p("NATIVE_ROUTE_MANIFEST_MOBILE_SURFACE_INVALID",`${a}/mobile/surface`),m.routeCode===l.routeCode&&p("NATIVE_ROUTE_MANIFEST_PAIR_DUPLICATE",a)}),L(n.digest,ee({schemaVersion:n.schemaVersion,appCode:n.appCode,devicePolicy:n.devicePolicy,rootEntry:n.rootEntry,authentication:n.authentication,routes:n.routes}),`${t}/digest`)}function qt(e,t){let o=g(e,t);y(o,["kind","mobileMaxWidthPx","desktopMinWidthPx"],t),L(o.kind,"viewport-family",`${t}/kind`);let n=Z(o.mobileMaxWidthPx,`${t}/mobileMaxWidthPx`,320,1600),s=Z(o.desktopMinWidthPx,`${t}/desktopMinWidthPx`,320,1600);return s!==n+1&&p("NATIVE_FRONTEND_DEVICE_POLICY_INVALID",t),{kind:"viewport-family",mobileMaxWidthPx:n,desktopMinWidthPx:s}}function gi(e,t){let o=g(e,t);y(o,["code","desktop","mobile"],t);let n=w(o.code,`${t}/code`),s=Wt(o.desktop,`${t}/desktop`),i=Wt(o.mobile,`${t}/mobile`);return(s===i||i==="/"||!i.startsWith("/m/"))&&p("NATIVE_ROUTE_MANIFEST_ROOT_ENTRY_INVALID",t),s.startsWith("/m/")&&p("NATIVE_ROUTE_MANIFEST_ROOT_ENTRY_INVALID",`${t}/desktop`),{code:n,desktop:s,mobile:i}}function Ni(e,t){let o=g(e,t);y(o,["desktop","mobile"],t);let n=Wn(o.desktop,`${t}/desktop`,!1),s=Wn(o.mobile,`${t}/mobile`,!0);return(n.routeCode===s.routeCode||n.path===s.path)&&p("NATIVE_ROUTE_MANIFEST_AUTHENTICATION_DUPLICATE",t),{desktop:n,mobile:s}}function Wn(e,t,o){let n=g(e,t);y(n,["routeCode","path"],t);let s=w(n.routeCode,`${t}/routeCode`),i=Wt(n.path,`${t}/path`);return(o?!i.startsWith("/m/"):i.startsWith("/m/"))&&p("NATIVE_ROUTE_MANIFEST_AUTHENTICATION_PATH_INVALID",`${t}/path`),{routeCode:s,path:i}}function Wt(e,t){let o=le(e,t);return/[:*?#\\\\]/.test(o)&&p("NATIVE_ROUTE_MANIFEST_STATIC_PATH_INVALID",t),o}function zn(e,t,o){let n=g(e,t);y(n,["routeCode","path","surface","pathParams","requiresAuthentication"],t,["capability","access"]),w(n.routeCode,`${t}/routeCode`);let s=le(n.path,`${t}/path`),i=R(n.surface,`${t}/surface`,16);["admin","user"].includes(i)||p("NATIVE_ROUTE_SURFACE_INVALID",`${t}/surface`);let c=F(n.pathParams,`${t}/pathParams`,8);return c.forEach((r,a)=>{(!/^[A-Za-z][A-Za-z0-9_]*$/.test(r)||r.length>64)&&p("NATIVE_ROUTE_PATH_PARAM_INVALID",`${t}/pathParams/${a}`)}),Q(c)!==Q(po(s))&&p("NATIVE_ROUTE_PATH_PARAMS_MISMATCH",`${t}/pathParams`),Yt(n,t,o),n.requiresAuthentication!==!0&&p("NATIVE_ROUTE_AUTHENTICATION_REQUIRED",`${t}/requiresAuthentication`),n}function po(e){return M([...e.matchAll(/:([A-Za-z][A-Za-z0-9_]*)/g)].map(t=>t[1]))}function Gn(e,t,o,n){return{routeCode:e,path:t,surface:o,pathParams:po(t),...n?.capability?{capability:n.capability}:{},...n?.access?{access:n.access}:{},requiresAuthentication:!0}}function qn(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 Ti(e){let t=e.appCode,o=[],n=(m,l,A,N,_,I,T)=>{o.push({code:m,kind:l,..._?{workflowCode:_}:{},...T?{resourceCode:T}:{},desktop:Gn(qn(l,"desktop",_,T),A,"user",I),mobile:Gn(qn(l,"mobile",_,T),N,"user",I)})};e.frontend.user.applicationTodoCenter===!0&&n("application:todo-center","application-todo-center","/todos","/m/todos");let s=_o(e);s.length>0&&(n("workflow:work-center","workflow-work-center","/work-center","/m/work-center"),n("workflow:task","workflow-task","/tasks/:taskId","/m/tasks/:taskId"),n("workflow:instance","workflow-instance","/workflows/:instanceId","/m/workflows/:instanceId"));for(let m of s){if(!["standalone","hidden-handoff"].includes(m.launch.mode))continue;let l=M([m.launch.submission?.create?.requiredCapability,m.launch.submission?.existing?.requiredCapability].filter(A=>!!A));n(`workflow:${m.code}:launch`,"workflow-launch","/workflows/:workflowCode/start","/m/workflows/:workflowCode/start",m.code,l.length===1?{capability:l[0]}:l.length>1?{access:{anyOf:l}}:void 0)}let i=o.sort((m,l)=>ae(String(m.code),String(l.code))),c=ct(e),r=m=>{let l=m==="mobile"?"/m/":"/",A=c.filter(_=>_.surface==="user"&&!/[:*?#\\\\]/.test(_.path)&&_.path===l).sort((_,I)=>ae(_.code,I.code))[0];if(A)return{code:A.code,path:A.path};let N=c.filter(_=>_.surface==="user"&&!/[:*?#\\\\]/.test(_.path)&&(m==="mobile"?_.path.startsWith("/m/"):!_.path.startsWith("/m/"))).sort((_,I)=>ae(_.code,I.code))[0];return N?{code:N.code,path:N.path}:{code:m==="mobile"?"application-root-mobile":"application-root",path:l}},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"}},f=qt(e.frontend.devicePolicy,"/config/frontend/devicePolicy"),E=r("desktop"),d=r("mobile"),u={schemaVersion:so,appCode:t,devicePolicy:f,rootEntry:{code:E.code,desktop:E.path,mobile:d.path},authentication:a,routes:i};return{...u,digest:ee(u)}}function rt(e,t){if(e===void 0)return;let o=R(e,t,32);vs.has(o)||p("NATIVE_ADMIN_ICON_INVALID",t)}function Yn(e,t){e!==void 0&&Z(e,t,-1e4,1e4)}function Yt(e,t,o){return e.capability!==void 0&&e.access!==void 0&&p("NATIVE_ROUTE_ACCESS_CONFLICT",`${t}/access`),e.capability!==void 0?{capability:Ne(e.capability,`${t}/capability`,o)}:e.access===void 0?{}:{access:dt(e.access,`${t}/access`,o)}}function dt(e,t,o){let n=g(e,t);y(n,["allOf","anyOf"],t,!0);let s=n.allOf===void 0?void 0:M(F(n.allOf,`${t}/allOf`,50).map((c,r)=>Ne(c,`${t}/allOf/${r}`,o))),i=n.anyOf===void 0?void 0:M(F(n.anyOf,`${t}/anyOf`,50).map((c,r)=>Ne(c,`${t}/anyOf/${r}`,o)));return(s?.length||0)+(i?.length||0)===0&&p("NATIVE_ROUTE_ACCESS_EMPTY",t),{...s===void 0?{}:{allOf:s},...i===void 0?{}:{anyOf:i}}}function _o(e){let t=new Map(ro(e).map(s=>[String(s.code),s])),o=e.workflows.definitions.map((s,i)=>{let c=`/config/workflows/definitions/${i}`,r=g(s,c);y(r,["version","definition","launch"],c,["detailRouteCode"]);let a=g(r.definition,`${c}/definition`),f=r.detailRouteCode===void 0?void 0:Ao(r.detailRouteCode,`${c}/detailRouteCode`);return{code:w(a.code,`${c}/definition/code`),title:R(a.title,`${c}/definition/title`,255),version:we(r.version,`${c}/version`),launch:Ci(e,a,r.launch,`${c}/launch`,t),...f?{detailRouteCode:f}:{},definition:a}});return M(o.map(s=>s.code)).map(s=>{let i=o.filter(f=>f.code===s),c=e.workflows.activations.find(f=>f.workflowCode===s)?.definitionVersion,r=i.find(f=>f.version===c)||[...i].sort((f,E)=>E.version-f.version)[0],a=new Set;for(let f of i){let E=g(f.definition.nodes,"/config/workflows/definitions/nodes");for(let d of Object.values(E)){let u=g(d,"/config/workflows/definitions/nodes/*");if(u.kind==="approval")for(let m of F(u.allowedOperations||[],"/config/workflows/definitions/nodes/*/allowedOperations",20))a.add(m)}}return{code:s,title:r.title,acceptedCommandDeactivationPolicy:r.definition.acceptedCommandDeactivationPolicy,subject:r.definition.subject,launch:r.launch,...["standalone","hidden-handoff"].includes(r.launch.mode)&&!r.launch.submission?{processOperationCode:`openxiangda.workflow.${s}.submit`}:{},...r.detailRouteCode?{detailRouteCode:r.detailRouteCode}:{},definitionVersions:no(i.map(f=>f.version)),bindingVersions:no(e.workflows.bindings.map((f,E)=>{let d=`/config/workflows/bindings/${E}`,u=g(f,d),m=g(u.binding,`${d}/binding`);return{code:w(m.workflowCode,`${d}/binding/workflowCode`),version:we(u.version,`${d}/version`)}}).filter(f=>f.code===s).map(f=>f.version)),providerCodes:M(e.workflows.providers.map((f,E)=>w(g(f,`/config/workflows/providers/${E}`).code,`/config/workflows/providers/${E}/code`))),allowedOperations:[...a].sort(ae),editableParameterCodes:M(e.workflows.editableParameters.map((f,E)=>{let d=`/config/workflows/editableParameters/${E}`,u=g(f,d);return{code:w(u.code,`${d}/code`),workflowCode:w(u.workflowCode,`${d}/workflowCode`)}}).filter(f=>f.workflowCode===s).map(f=>f.code))}})}function Eo(e,t){let o=g(e,t);y(o,["mode"],t,["submission"]);let n=R(o.mode,`${t}/mode`,32);return["standalone","custom-page","hidden-handoff","work-center-only"].includes(n)||p("NATIVE_WORKFLOW_LAUNCH_MODE_INVALID",`${t}/mode`),{mode:n,...o.submission===void 0?{}:{submission:g(o.submission,`${t}/submission`)}}}function Ci(e,t,o,n,s){let i=Eo(o,n);if(!i.submission)return{mode:i.mode};["standalone","hidden-handoff"].includes(i.mode)||p("NATIVE_WORKFLOW_NAMED_OPERATION_SUBMISSION_INVALID",`${n}/submission`);let c=g(i.submission,`${n}/submission`);y(c,["kind"],`${n}/submission`,["create","existing","context"]),L(c.kind,"named-operation",`${n}/submission/kind`);let r=n.endsWith("/launch")?n.slice(0,-7):n,a=g(t.subject,`${r}/definition/subject`),f=z(a.resourceCode,`${r}/definition/subject/resourceCode`),E=e.data.resources.findIndex(O=>O.code===f),d=e.data.resources[E];(E<0||!d)&&p("NATIVE_WORKFLOW_SUBJECT_RESOURCE_MISSING",`${r}/definition/subject/resourceCode`);let u=new Set(g(d.schema,`/config/data/resources/${E}/schema`).fields.map(O=>String(O.code))),m=new Map(e.backend.operations.map(O=>[String(O.code),O])),l=(O,S)=>{let D=`${n}/submission/${S}`,U=g(O,D);y(U,["operationCode","inputs","output"],D);let k=w(U.operationCode,`${D}/operationCode`),q=m.get(k),j=s.get(k),ue=j?.platformAccess?.workflow?.codes;(!q||!j||j.method!=="POST"||!Array.isArray(ue)||!ue.includes(t.code))&&p("NATIVE_WORKFLOW_NAMED_OPERATION_INVALID",D);let fe=g(q.requestSchema,`${D}/operation/requestSchema`),K=g(fe.properties,`${D}/operation/requestSchema/properties`),Ie=new Set(fe.required===void 0?[]:F(fe.required,`${D}/operation/requestSchema/required`,64)),ie=g(U.inputs,`${D}/inputs`),V=Object.entries(ie);(!V.length||V.length>64)&&p("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${D}/inputs`);let x=new Set,v=new Map,J={};for(let[G,H]of V){(!Mn.test(G)||!Object.prototype.hasOwnProperty.call(K,G))&&p("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${D}/inputs/${G}`);let $e=`${D}/inputs/${G}`,ut=g(H,$e),Oe=R(ut.source,`${$e}/source`,32);if(["field","idempotency-key","current-user-reference","subject-id","subject-revision","requested-at"].includes(Oe)||p("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",$e),y(ut,["source"],$e,Oe==="field"?["fieldCode"]:!1),v.set(Oe,(v.get(Oe)||0)+1),Oe==="field"){let ze=B(ut.fieldCode,`${$e}/fieldCode`);(x.has(ze)||!u.has(ze))&&p("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${$e}/fieldCode`),x.add(ze),J[G]={source:Oe,fieldCode:ze}}else J[G]={source:Oe}}([...Ie].some(G=>!(G in ie))||(v.get("idempotency-key")||0)!==1||!V.some(([G,H])=>g(H,`${D}/inputs/${G}`).source==="idempotency-key"&&Ie.has(G))||S==="create"&&((v.get("subject-id")||0)>0||(v.get("subject-revision")||0)>0)||S==="existing"&&((v.get("subject-id")||0)!==1||(v.get("subject-revision")||0)!==1))&&p("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${D}/inputs`);let W=g(U.output,`${D}/output`);y(W,["subjectId"],`${D}/output`,["subjectRevision","processCommand"]);let me=g(g(q.responseSchema,`${D}/operation/responseSchema`).properties,`${D}/operation/responseSchema/properties`);for(let G of["subjectId","subjectRevision","processCommand"]){if(W[G]===void 0)continue;let H=R(W[G],`${D}/output/${G}`,128);(!Mn.test(H)||!Object.prototype.hasOwnProperty.call(me,H))&&p("NATIVE_WORKFLOW_NAMED_OPERATION_OUTPUT_INVALID",`${D}/output/${G}`)}return{operationCode:k,method:"POST",path:j.path,requiredCapability:j.requiredCapability,requestSchemaDigest:j.requestSchemaDigest,responseSchemaDigest:j.responseSchemaDigest,inputs:J,output:{...W},fieldCodes:x}},A=c.create===void 0?void 0:l(c.create,"create"),N=c.existing===void 0?void 0:l(c.existing,"existing");!A&&!N&&p("NATIVE_WORKFLOW_NAMED_OPERATION_SUBMISSION_INVALID",`${n}/submission`);let _=new Set([...A?.fieldCodes||[],...N?.fieldCodes||[]]),I=c.context===void 0?[]:$(c.context,`${n}/submission/context`,16),T=new Set,b=I.map((O,S)=>{let D=`${n}/submission/context/${S}`,U=g(O,D);y(U,["queryParameter","fieldCode"],D);let k=R(U.queryParameter,`${D}/queryParameter`,64),q=B(U.fieldCode,`${D}/fieldCode`);return(!/^[A-Za-z][A-Za-z0-9]{0,63}$/.test(k)||T.has(k)||!_.has(q))&&p("NATIVE_WORKFLOW_LAUNCH_CONTEXT_INVALID",D),T.add(k),{queryParameter:k,fieldCode:q}}),C=O=>{let{fieldCodes:S,...D}=O;return D};return{mode:i.mode,submission:{kind:"named-operation",...A?{create:C(A)}:{},...N?{existing:C(N)}:{},context:b}}}function Ao(e,t){let o=g(e,t);y(o,["desktop","mobile"],t);let n=w(o.desktop,`${t}/desktop`),s=w(o.mobile,`${t}/mobile`);return n===s&&p("NATIVE_WORKFLOW_DETAIL_ROUTE_DUPLICATE",t),{desktop:n,mobile:s}}function bi(e,t){let o=new Set(t.map(E=>E.code)),n=new Map;e.data.resources.forEach((E,d)=>{let u=`/config/data/resources/${d}`,m=g(E,u);for(let[N,_]of Object.entries(m.fieldPolicies||{})){if(!ve(N))continue;let I=`${u}/fieldPolicies/${N}/read`,T=g(_,`${u}/fieldPolicies/${N}`);for(let b of F(T.read||[],I,2e3))o.has(b)||p("NATIVE_CAPABILITY_REFERENCE_MISSING",I)}let l=m.surface===void 0?{}:g(m.surface,`${u}/surface`);if(["native","queued-command"].includes(l.mutationOwner||"native"))return;let A=g(m.capabilities,`${u}/capabilities`);for(let N of["create","update","delete"])n.set(String(A[N]),N)});let s=new Set;for(let[E,d]of e.authz.roles.entries()){let u=`/config/authz/roles/${E}`,m=g(d,u);y(m,["code","name","description","capabilities"],u,!0);let l=w(m.code,`${u}/code`);s.has(l)&&p("NATIVE_ROLE_DUPLICATE",`${u}/code`),s.add(l),R(m.name,`${u}/name`,255);let A=F(m.capabilities,`${u}/capabilities`,2e3);for(let[N,_]of A.entries())n.has(_)&&p("NATIVE_DATA_SURFACE_MUTATION_GRANT_FORBIDDEN",`${u}/capabilities/${N}`,{operation:n.get(_)}),o.has(_)||p("NATIVE_CAPABILITY_REFERENCE_MISSING",`${u}/capabilities`)}let i=e.authz.authenticatedUserRoleCode===void 0?"":w(e.authz.authenticatedUserRoleCode,"/config/authz/authenticatedUserRoleCode");i&&!s.has(i)&&p("NATIVE_AUTHENTICATED_USER_ROLE_REFERENCE_MISSING","/config/authz/authenticatedUserRoleCode");let c=new Set,r=0;for(let[E,d]of e.perspectives.entries()){let u=`/config/perspectives/${E}`,m=g(d,u);y(m,["code","name","description","roleCodes","capabilityCodes","default"],u,!0);let l=w(m.code,`${u}/code`);c.has(l)&&p("NATIVE_PERSPECTIVE_DUPLICATE",`${u}/code`),c.add(l),R(m.name,`${u}/name`,255);let A=F(m.roleCodes,`${u}/roleCodes`,20);A.length<1&&p("NATIVE_PERSPECTIVE_ROLE_REQUIRED",`${u}/roleCodes`),A.forEach((I,T)=>{s.has(I)||p("NATIVE_PERSPECTIVE_ROLE_MISSING",`${u}/roleCodes/${T}`)});let N=M(e.authz.roles.filter(I=>A.includes(I.code)).flatMap(I=>I.capabilities)),_=F(m.capabilityCodes,`${u}/capabilityCodes`,2e3);Q(N)!==Q(_)&&p("NATIVE_PERSPECTIVE_CAPABILITY_PROJECTION_MISMATCH",`${u}/capabilityCodes`),m.default===!0?r+=1:m.default!==void 0&&p("NATIVE_PERSPECTIVE_DEFAULT_INVALID",`${u}/default`)}r>1&&p("NATIVE_PERSPECTIVE_DEFAULT_DUPLICATE","/config/perspectives");for(let[E,d]of e.backend.operations.entries()){let u=g(d,`/config/backend/operations/${E}`);o.has(u.capability)||p("NATIVE_CAPABILITY_REFERENCE_MISSING",`/config/backend/operations/${E}/capability`)}let a=new Set,f=new Set;for(let[E,d]of e.frontend.routes.entries()){let u=`/config/frontend/routes/${E}`,m=g(d,u),l=w(m.code,`${u}/code`);a.has(l)&&p("NATIVE_ROUTE_DUPLICATE",`${u}/code`),a.add(l);let A=le(m.path,`${u}/path`);f.has(A)&&p("NATIVE_ROUTE_PATH_DUPLICATE",`${u}/path`),f.add(A);let N=Yt(m,u,e.appCode);N.capability&&!o.has(N.capability)&&p("NATIVE_CAPABILITY_REFERENCE_MISSING",`${u}/capability`);let _=m.access===void 0?void 0:g(m.access,`${u}/access`);for(let I of["allOf","anyOf"]){let T=_?.[I]===void 0?[]:$(_[I],`${u}/access/${I}`,50);for(let[b,C]of T.entries()){let O=Ne(C,`${u}/access/${I}/${b}`,e.appCode);o.has(O)||p("NATIVE_CAPABILITY_REFERENCE_MISSING",`${u}/access/${I}/${b}`)}}}if(e.frontend.admin.access!==void 0){let E=dt(e.frontend.admin.access,"/config/frontend/admin/access",e.appCode);for(let d of["allOf","anyOf"])for(let[u,m]of(E[d]||[]).entries())o.has(m)||p("NATIVE_CAPABILITY_REFERENCE_MISSING",`/config/frontend/admin/access/${d}/${u}`)}for(let[E,d]of e.frontend.routes.entries()){let u=g(d,`/config/frontend/routes/${E}`);u.parentCode&&!a.has(u.parentCode)&&p("NATIVE_ROUTE_PARENT_MISSING",`/config/frontend/routes/${E}/parentCode`)}}function Oi(e){let t=new Set(e.authz.roles.map(f=>String(f.code))),o=e.authz.authenticatedUserRoleCode===void 0?"":w(e.authz.authenticatedUserRoleCode,"/config/authz/authenticatedUserRoleCode"),n=new Map(e.authz.scopeDimensions.map(f=>[String(f.code),{valueType:f.valueType==="uuid"?"uuid":"string",...f.valueSource?.resourceCode?{valueSourceResourceCode:String(f.valueSource.resourceCode)}:{}}])),s=new Set(n.keys()),i=new Map(e.data.resources.map((f,E)=>{let d=ye(f,`/config/data/resources/${E}`,e.appCode);return[d.code,new Map(d.schema.fields.map(u=>[String(u.code),u]))]}));for(let[f,E]of e.authz.scopeDimensions.entries()){let d=`/config/authz/scopeDimensions/${f}`,u=g(E,d);if(y(u,["code","name","resourceCode","valueType","hierarchyMode","valueSource"],d,!0),u.valueSource===void 0)continue;let m=g(u.valueSource,`${d}/valueSource`);y(m,["kind","resourceCode","labelField","enabledField"],`${d}/valueSource`,!0),m.kind!=="native_resource"&&p("NATIVE_SCOPE_VALUE_SOURCE_KIND_INVALID",`${d}/valueSource/kind`),u.valueType!=="uuid"&&p("NATIVE_SCOPE_VALUE_SOURCE_TYPE_INVALID",`${d}/valueType`);let l=z(m.resourceCode,`${d}/valueSource/resourceCode`),A=i.get(l);A||p("NATIVE_SCOPE_VALUE_SOURCE_RESOURCE_MISSING",`${d}/valueSource/resourceCode`);let N=B(m.labelField,`${d}/valueSource/labelField`);if(["text.short","text.long"].includes(String(A.get(N)?.type||""))||p("NATIVE_SCOPE_VALUE_SOURCE_LABEL_FIELD_INVALID",`${d}/valueSource/labelField`),m.enabledField!==void 0){let _=B(m.enabledField,`${d}/valueSource/enabledField`);A.get(_)?.type!=="boolean"&&p("NATIVE_SCOPE_VALUE_SOURCE_ENABLED_FIELD_INVALID",`${d}/valueSource/enabledField`)}}let c=new Set,r=new Set;for(let[f,E]of e.authz.scopeSources.entries()){let d=`/config/authz/scopeSources/${f}`,u=g(E,d);y(u,["code","name","resourceCode","subject","grants","operationField","enabledField","effectiveFromField","effectiveToField","failureMode"],d,!0);let m=w(u.code,`${d}/code`);c.has(m)&&p("NATIVE_SCOPE_SOURCE_DUPLICATE",`${d}/code`),c.add(m),R(u.name,`${d}/name`,255);let l=z(u.resourceCode,`${d}/resourceCode`),A=i.get(l);A||p("NATIVE_SCOPE_SOURCE_RESOURCE_MISSING",`${d}/resourceCode`);let N=g(u.subject,`${d}/subject`),_=R(N.type,`${d}/subject/type`,32);y(N,_==="role_membership"?["type","userIdField","roleCode"]:["type","userIdField"],`${d}/subject`),["user","role_membership"].includes(_)||p("NATIVE_SCOPE_SOURCE_SUBJECT_INVALID",`${d}/subject/type`);let I=xe(N.userIdField,A);vt(I)||p("NATIVE_SCOPE_SOURCE_SUBJECT_PATH_INVALID",`${d}/subject/userIdField`),_==="role_membership"&&!t.has(String(N.roleCode))&&p("NATIVE_ROLE_REFERENCE_MISSING",`${d}/subject/roleCode`);let T=new Set;for(let[b,C]of $(u.grants,`${d}/grants`,100).entries()){let O=`${d}/grants/${b}`,S=g(C,O);y(S,["dimensionCode","valueField","parentValueField"],O,!0);let D=w(S.dimensionCode,`${O}/dimensionCode`);(!s.has(D)||T.has(D))&&p("NATIVE_SCOPE_SOURCE_DIMENSION_INVALID",`${O}/dimensionCode`),T.add(D),u.failureMode==="last_known_good"&&r.add(D);for(let U of["valueField","parentValueField"]){if(S[U]===void 0)continue;let k=xe(S[U],A);$n(k,n.get(D),i)||p("NATIVE_SCOPE_SOURCE_GRANT_PATH_INVALID",`${O}/${U}`)}}T.size===0&&p("NATIVE_SCOPE_SOURCE_GRANT_REQUIRED",`${d}/grants`),["strict","last_known_good"].includes(u.failureMode)||p("NATIVE_SCOPE_SOURCE_FAILURE_MODE_INVALID",`${d}/failureMode`);for(let b of["operationField","enabledField","effectiveFromField","effectiveToField"]){if(u[b]===void 0)continue;let C=B(u[b],`${d}/${b}`);A.has(C)||p("NATIVE_SCOPE_SOURCE_FIELD_MISSING",`${d}/${b}`)}}$i(e,t,i,o);let a=new Set;for(let[f,E]of e.authz.dataPolicies.entries()){let d=`/config/authz/dataPolicies/${f}`,u=g(E,d);y(u,["code","name","resourceCode","unrestrictedRoleCodes","operations","matchMode","rules","readExpression","writeBoundary"],d,!0);let m=w(u.code,`${d}/code`);a.has(m)&&p("NATIVE_DATA_POLICY_DUPLICATE",`${d}/code`),a.add(m);let l=u.readExpression!==void 0,A=F(u.operations||[],`${d}/operations`,4);u.operations!==void 0&&(A.length===0||A.some(C=>!["read","create","update","delete"].includes(C)))&&p("NATIVE_DATA_POLICY_OPERATIONS_INVALID",`${d}/operations`),["AND","OR"].includes(u.matchMode)||p("NATIVE_DATA_POLICY_MATCH_MODE_INVALID",`${d}/matchMode`),l&&u.operations!==void 0&&p("NATIVE_DATA_POLICY_READ_EXPRESSION_OPERATIONS_FORBIDDEN",`${d}/operations`);let N=e.data.resources.find(C=>C.dataPolicyCode===m),_=u.resourceCode||N?.code,I=_?i.get(z(_,`${d}/resourceCode`)):void 0;l&&!I&&p("NATIVE_DATA_POLICY_RESOURCE_MISSING",`${d}/resourceCode`);let T=F(u.unrestrictedRoleCodes||[],`${d}/unrestrictedRoleCodes`,100);u.unrestrictedRoleCodes!==void 0&&T.length===0&&p("NATIVE_DATA_POLICY_UNRESTRICTED_ROLES_INVALID",`${d}/unrestrictedRoleCodes`);for(let C of T)t.has(C)||p("NATIVE_ROLE_REFERENCE_MISSING",`${d}/unrestrictedRoleCodes`);let b;try{let C=$(u.rules,`${d}/rules`,100).map((O,S)=>({rule:g(O,`${d}/rules/${S}`),pointer:`${d}/rules/${S}`}));C.length===0?(!l||u.matchMode!=="AND"||u.writeBoundary!=="capability_only")&&p("NATIVE_DATA_POLICY_WRITE_BOUNDARY_REQUIRED",d):u.writeBoundary!==void 0&&p("NATIVE_DATA_POLICY_WRITE_BOUNDARY_INVALID",`${d}/writeBoundary`),b=[...C],l&&(b.push(...st(u.readExpression,`${d}/readExpression`)),xn(u.readExpression,`${d}/readExpression`))}catch(C){throw C instanceof Be&&p(C.code,C.pointer),C}for(let{rule:C,pointer:O}of b){y(C,["subject","dimensionCode","relationCode","resourceCode","field","roleCodes","operation","valuePath","emptyMatchesAll","operator","value","operand"],O,!0);let S=B(C.field,`${O}/field`),D=I?.get(S);l&&!D&&p("NATIVE_DATA_POLICY_FIELD_MISSING",`${O}/field`);for(let K of F(C.roleCodes||[],`${O}/roleCodes`,100))t.has(K)||p("NATIVE_ROLE_REFERENCE_MISSING",`${O}/roleCodes`);let U=String(C.operator||""),k=C.operand==="db_now",q=["is_null","is_not_null"].includes(U),j=["eq","not_eq","in","not_in"].includes(U),ue=!k&&(C.operator!==void 0||C.value!==void 0);if([C.subject==="current_user"?"current_user":"",typeof C.dimensionCode=="string"?"dimension":"",typeof C.relationCode=="string"?"relationship":"",ue?"constant":"",k?"db_now":""].filter(Boolean).length!==1&&p("NATIVE_DATA_POLICY_RULE_SOURCE_INVALID",O),C.subject!==void 0&&C.subject!=="current_user"&&p("NATIVE_DATA_POLICY_SUBJECT_INVALID",`${O}/subject`),ue){if(!j&&!q&&p("NATIVE_DATA_POLICY_OPERATOR_INVALID",`${O}/operator`),["in","not_in"].includes(U)){let K=$(C.value,`${O}/value`,100).map((Ie,ie)=>R(Ie,`${O}/value/${ie}`,2048));(K.length===0||new Set(K).size!==K.length)&&p("NATIVE_DATA_POLICY_VALUE_INVALID",`${O}/value`)}else["eq","not_eq"].includes(U)?R(C.value,`${O}/value`,2048):(C.value!==void 0||C.operand!==void 0)&&p("NATIVE_DATA_POLICY_VALUE_INVALID",`${O}/value`);for(let K of["operation","valuePath","emptyMatchesAll","resourceCode","operand"])C[K]!==void 0&&p("NATIVE_DATA_POLICY_CONSTANT_RULE_INVALID",`${O}/${K}`)}if(k){(!["lt","lte","gt","gte"].includes(U)||C.value!==void 0||D?.type!=="datetime")&&p("NATIVE_DATA_POLICY_DB_NOW_INVALID",O);for(let K of["operation","valuePath","emptyMatchesAll","resourceCode","value"])C[K]!==void 0&&p("NATIVE_DATA_POLICY_DB_NOW_INVALID",`${O}/${K}`)}C.dimensionCode&&!s.has(C.dimensionCode)&&p("NATIVE_SCOPE_DIMENSION_MISSING",`${O}/dimensionCode`),r.has(String(C.dimensionCode||""))&&C.operation!=="read"&&p("NATIVE_SCOPE_SOURCE_LAST_KNOWN_GOOD_UNSAFE",`${O}/operation`)}}for(let[f,E]of e.data.resources.entries()){let d=g(E,`/config/data/resources/${f}`);d.dataPolicyCode&&!a.has(d.dataPolicyCode)&&p("NATIVE_DATA_POLICY_REFERENCE_MISSING",`/config/data/resources/${f}/dataPolicyCode`)}}function yi(e){try{nn(e.data.resources,"/config/data/resources")}catch(t){throw t instanceof _e&&p(t.code,t.pointer),t}}function $i(e,t,o,n){let s=new Set;for(let[i,c]of e.authz.roleMembershipSources.entries()){let r=`/config/authz/roleMembershipSources/${i}`,a=g(c,r);y(a,["code","name","resourceCode","userIdField","roleCode","enabledField","effectiveFromField","effectiveToField","failureMode"],r,!0);let f=w(a.code,`${r}/code`);f.length>100&&p("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_CODE_INVALID",`${r}/code`),s.has(f)&&p("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_DUPLICATE",`${r}/code`),s.add(f),R(a.name,`${r}/name`,255);let E=Kn(a.resourceCode,`${r}/resourceCode`,o);Hn(a.userIdField,`${r}/userIdField`,E),t.has(String(a.roleCode||""))||p("NATIVE_ROLE_REFERENCE_MISSING",`${r}/roleCode`),n&&a.roleCode===n&&p("NATIVE_AUTHENTICATED_USER_ROLE_SOURCE_CONFLICT",`${r}/roleCode`),Xn(a,r,E)}for(let[i,c]of e.authz.relationshipGrantSources.entries()){let r=`/config/authz/relationshipGrantSources/${i}`,a=g(c,r);y(a,["code","name","resourceCode","subject","relationCode","targetResourceCode","resourceIdField","operations","enabledField","effectiveFromField","effectiveToField","failureMode"],r,!0);let f=w(a.code,`${r}/code`);f.length>100&&p("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_CODE_INVALID",`${r}/code`),s.has(f)&&p("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_DUPLICATE",`${r}/code`),s.add(f),R(a.name,`${r}/name`,255);let E=Kn(a.resourceCode,`${r}/resourceCode`,o),d=g(a.subject,`${r}/subject`),u=R(d.type,`${r}/subject/type`,32);y(d,u==="role_membership"?["type","userIdField","roleCode"]:["type","userIdField"],`${r}/subject`),["user","role_membership"].includes(u)||p("NATIVE_AUTHORIZATION_PROJECTION_SUBJECT_INVALID",`${r}/subject/type`),Hn(d.userIdField,`${r}/subject/userIdField`,E),u==="role_membership"&&!t.has(String(d.roleCode||""))&&p("NATIVE_ROLE_REFERENCE_MISSING",`${r}/subject/roleCode`),w(a.relationCode,`${r}/relationCode`);let m=z(a.targetResourceCode,`${r}/targetResourceCode`);o.has(m)||p("NATIVE_AUTHORIZATION_PROJECTION_TARGET_RESOURCE_MISSING",`${r}/targetResourceCode`);let l=xe(a.resourceIdField,E),A=l?.field.type==="resource-ref.single"&&l.valuePath==="value"&&l.field.source?.resourceCode===m;(a.resourceIdField==="id"?m!==String(a.resourceCode):!A)&&p("NATIVE_AUTHORIZATION_PROJECTION_RESOURCE_ID_FIELD_INVALID",`${r}/resourceIdField`);let N=F(a.operations,`${r}/operations`,20);(N.length===0||N.some(_=>_.length>64||!/^[A-Za-z0-9][A-Za-z0-9:._*-]{0,63}$/.test(_)))&&p("NATIVE_AUTHORIZATION_PROJECTION_OPERATIONS_INVALID",`${r}/operations`),Xn(a,r,E)}}function Kn(e,t,o){let n=z(e,t),s=o.get(n);return s||p("NATIVE_AUTHORIZATION_PROJECTION_RESOURCE_MISSING",t),s}function Hn(e,t,o){let n=xe(e,o);vt(n)||p("NATIVE_AUTHORIZATION_PROJECTION_USER_FIELD_INVALID",t)}function Xn(e,t,o){if(e.failureMode!=="strict"&&p("NATIVE_AUTHORIZATION_PROJECTION_FAILURE_MODE_INVALID",`${t}/failureMode`),e.enabledField!==void 0){let n=B(e.enabledField,`${t}/enabledField`);o.get(n)?.type!=="boolean"&&p("NATIVE_AUTHORIZATION_PROJECTION_ENABLED_FIELD_INVALID",`${t}/enabledField`)}for(let n of["effectiveFromField","effectiveToField"]){if(e[n]===void 0)continue;let s=B(e[n],`${t}/${n}`);["date","datetime"].includes(String(o.get(s)?.type))||p("NATIVE_AUTHORIZATION_PROJECTION_EFFECTIVE_FIELD_INVALID",`${t}/${n}`)}}function Ri(e){let t=new Set,o=new Set;e.forEach((n,s)=>{let i=`/config/backend/secrets/${s}`,c=g(n,i);y(c,["name","env","description","required","exposure"],i,!0);let r=R(c.name,`${i}/name`,128),a=R(c.env,`${i}/env`,128);$s.test(r)||p("NATIVE_SECRET_NAME_INVALID",`${i}/name`),(!Rs.test(a)||a.startsWith("OPENXIANGDA_")||["NODE_ENV","PORT"].includes(a))&&p("NATIVE_SECRET_ENV_INVALID",`${i}/env`),t.has(r)&&p("NATIVE_SECRET_NAME_DUPLICATE",`${i}/name`),o.has(a)&&p("NATIVE_SECRET_ENV_DUPLICATE",`${i}/env`),t.add(r),o.add(a),L(c.exposure,"active_only",`${i}/exposure`),c.required!==void 0&&Fe(c.required,`${i}/required`),c.description!==void 0&&Kt(c.description,`${i}/description`,2e3)})}function hi(e){let t=new Set,o=new Map,n=new Map(e.data.resources.map(u=>[String(u.code),u])),s=new Map(e.frontend.routes.map((u,m)=>{let l=g(u,`/config/frontend/routes/${m}`);return[w(l.code,`/config/frontend/routes/${m}/code`),l]}));for(let[u,m]of e.workflows.definitions.entries()){let l=`/config/workflows/definitions/${u}`,A=g(m,l);if(y(A,["version","definition","launch"],l,["detailRouteCode"]),Eo(A.launch,`${l}/launch`),A.detailRouteCode!==void 0){let T=Ao(A.detailRouteCode,`${l}/detailRouteCode`);for(let[b,C,O]of[["desktop",T.desktop,["admin","user"]],["mobile",T.mobile,["user"]]]){let S=`${l}/detailRouteCode/${b}`,D=s.get(C);D||p("NATIVE_WORKFLOW_DETAIL_ROUTE_MISSING",S),O.some(q=>q===D.surface)||p("NATIVE_WORKFLOW_DETAIL_ROUTE_SURFACE_INVALID",S);let U=le(D.path,S),k=[...U.matchAll(/:([A-Za-z][A-Za-z0-9_]*)/g)].map(q=>q[1]);(U.includes("*")||k.length!==1||k[0]!=="instanceId")&&p("NATIVE_WORKFLOW_DETAIL_ROUTE_PATH_INVALID",S)}}let N=g(A.definition,`${l}/definition`),_=`${N.code}:${we(A.version,`${l}/version`)}`;t.has(_)&&p("NATIVE_WORKFLOW_DEFINITION_DUPLICATE",l),t.add(_),Di(N,`${l}/definition`),Si(N.subject,n,`${l}/definition/subject`);let I=Pn(N,{appCode:e.appCode,capabilities:e.authz.capabilities.map(T=>T.code),fields:new Map((n.get(N.subject.resourceCode)?.schema.fields||[]).map(T=>[T.code,T]))});I.length&&p("NATIVE_WORKFLOW_INSTANCE_COMMAND_POLICY_INVALID",`${l}/definition/instanceCommands`,{errors:I}),N.title===N.code&&p("NATIVE_WORKFLOW_USER_TITLE_REQUIRED",`${l}/definition/title`),o.set(_,N)}let i=new Set,c=new Map;for(let[u,m]of e.workflows.bindings.entries()){let l=g(m,`/config/workflows/bindings/${u}`),A=g(l.binding,`/config/workflows/bindings/${u}/binding`),N=`${A.workflowCode}:${we(l.version,`/config/workflows/bindings/${u}/version`)}`;i.has(N)&&p("NATIVE_WORKFLOW_BINDING_DUPLICATE",`/config/workflows/bindings/${u}`),i.add(N),Vi(A,`/config/workflows/bindings/${u}/binding`),c.set(N,A)}let r=new Set,a=new Map;for(let[u,m]of e.workflows.activations.entries()){let l=`/config/workflows/activations/${u}`,A=g(m,l);y(A,["workflowCode","definitionVersion","bindingVersion","acceptedCommandDeactivationPolicy"],l,["environmentKey"]);let N=w(A.workflowCode,`${l}/workflowCode`);r.has(N)&&p("NATIVE_WORKFLOW_ACTIVATION_DUPLICATE",l),r.add(N);let _=`${N}:${we(A.definitionVersion,`${l}/definitionVersion`)}`,I=`${N}:${we(A.bindingVersion,`${l}/bindingVersion`)}`;t.has(_)||p("NATIVE_WORKFLOW_DEFINITION_REFERENCE_MISSING",`${l}/definitionVersion`),i.has(I)||p("NATIVE_WORKFLOW_BINDING_REFERENCE_MISSING",`${l}/bindingVersion`);let T=o.get(_),b=c.get(I);(!["finish-pinned","cancel-on-deactivate"].includes(A.acceptedCommandDeactivationPolicy)||A.acceptedCommandDeactivationPolicy!==T.acceptedCommandDeactivationPolicy)&&p("NATIVE_WORKFLOW_COMMAND_DEACTIVATION_POLICY_MISMATCH",`${l}/acceptedCommandDeactivationPolicy`),wi(T,b,`/config/workflows/activations/${u}`),a.set(N,b)}let f=new Set;e.workflows.providers.forEach((u,m)=>{let l=`/config/workflows/providers/${m}`,A=g(u,l);y(A,["code","endpointPath","timeoutMs"],l,!0);let N=w(A.code,`${l}/code`);f.has(N)&&p("NATIVE_WORKFLOW_PROVIDER_DUPLICATE",`${l}/code`),f.add(N),le(A.endpointPath,`${l}/endpointPath`),A.timeoutMs!==void 0&&Z(A.timeoutMs,`${l}/timeoutMs`,100,1e4)});for(let[u,m]of a.entries())for(let[l,A]of Object.entries(g(m.bindings,"/config/workflows/bindings/*/binding/bindings"))){let N=g(A,`/config/workflows/${u}/bindings/${l}`);N.provider==="application_provider"&&!f.has(N.providerCode)&&p("NATIVE_WORKFLOW_PROVIDER_REFERENCE_MISSING",`/config/workflows/${u}/bindings/${l}/providerCode`)}let E=new Set(e.authz.roles.map(u=>u.code)),d=new Set;e.workflows.editableParameters.forEach((u,m)=>{let l=`/config/workflows/editableParameters/${m}`,A=g(u,l);y(A,["code","workflowCode","bindingKey","label","valueType","required","allowedRoleCodes","allowedProviderCodes","maxItems"],l,!0);let N=w(A.code,`${l}/code`);d.has(N)&&p("NATIVE_WORKFLOW_EDITABLE_PARAMETER_DUPLICATE",`${l}/code`),d.add(N);let _=lt(A.workflowCode,`${l}/workflowCode`),I=Ht(A.bindingKey,`${l}/bindingKey`),T=a.get(_);(!T||!g(T.bindings,`${l}/bindingKey`)[I])&&p("NATIVE_WORKFLOW_EDITABLE_BINDING_MISSING",`${l}/bindingKey`),R(A.label,`${l}/label`,255),["role_code","user_ids","provider_code"].includes(A.valueType)||p("NATIVE_WORKFLOW_EDITABLE_VALUE_TYPE_INVALID",`${l}/valueType`);for(let b of F(A.allowedRoleCodes||[],`${l}/allowedRoleCodes`,100))E.has(b)||p("NATIVE_ROLE_REFERENCE_MISSING",`${l}/allowedRoleCodes`);for(let b of F(A.allowedProviderCodes||[],`${l}/allowedProviderCodes`,100))f.has(b)||p("NATIVE_WORKFLOW_PROVIDER_REFERENCE_MISSING",`${l}/allowedProviderCodes`);A.required!==void 0&&Fe(A.required,`${l}/required`),A.maxItems!==void 0&&Z(A.maxItems,`${l}/maxItems`,1,200)})}function Si(e,t,o){let n=g(e,o);y(n,["resourceCode","factProjection"],o,["summaryFields"]);let s=z(n.resourceCode,`${o}/resourceCode`),i=t.get(s);i||p("NATIVE_WORKFLOW_SUBJECT_RESOURCE_MISSING",`${o}/resourceCode`);let c=new Set($(g(i.schema,`${o}/resourceCode`).fields,`${o}/resourceCode`,500).map((f,E)=>B(g(f,`${o}/resourceCode/${E}`).code,`${o}/resourceCode/${E}`))),r=g(n.factProjection,`${o}/factProjection`),a=Object.entries(r);(a.length<1||a.length>64)&&p("NATIVE_WORKFLOW_SUBJECT_FACT_PROJECTION_INVALID",`${o}/factProjection`);for(let[f,E]of a){Ds.test(f)||p("NATIVE_WORKFLOW_SUBJECT_FACT_KEY_INVALID",`${o}/factProjection/${f}`);let d=B(E,`${o}/factProjection/${f}`);c.has(d)||p("NATIVE_WORKFLOW_SUBJECT_FIELD_MISSING",`${o}/factProjection/${f}`)}if(n.summaryFields!==void 0){let f=F(n.summaryFields,`${o}/summaryFields`,Vs).map((l,A)=>B(l,`${o}/summaryFields/${A}`)),E=t.get(s),d=E.surface&&typeof E.surface=="object"&&!Array.isArray(E.surface)?E.surface:{},u=d.fields&&typeof d.fields=="object"&&!Array.isArray(d.fields)?d.fields:{},m=new Map($(g(E.schema,`${o}/resourceCode`).fields,`${o}/resourceCode`,500).map((l,A)=>{let N=g(l,`${o}/resourceCode/${A}`);return[String(N.code),N]}));for(let[l,A]of f.entries()){let N=m.get(A),_=u[A],I=String(N?.type||""),T=N?.maxLength;(!N||N.system===!0||_&&typeof _=="object"&&!Array.isArray(_)&&_.system===!0||["id","revision","created_by","updated_by","created_at","updated_at"].includes(A)||!Fs.has(I)||I==="text.long"&&typeof T=="number"&&Number.isFinite(T)&&T>ws)&&p("NATIVE_WORKFLOW_SUBJECT_SUMMARY_FIELDS_INVALID",`${o}/summaryFields/${l}`)}}}function Di(e,t){y(e,["schemaVersion","code","title","subject","acceptedCommandDeactivationPolicy","startAt","inputSchema","nodes"],t,["organizationContext","instanceCommands"]),L(e.schemaVersion,"openxiangda.workflow-definition/v2",`${t}/schemaVersion`),lt(e.code,`${t}/code`),R(e.title,`${t}/title`,255),["finish-pinned","cancel-on-deactivate"].includes(e.acceptedCommandDeactivationPolicy)||p("NATIVE_WORKFLOW_COMMAND_DEACTIVATION_POLICY_REQUIRED",`${t}/acceptedCommandDeactivationPolicy`);let o=g(e.nodes,`${t}/nodes`),n=Object.keys(o);(n.length===0||n.length>200)&&p("NATIVE_WORKFLOW_NODE_COUNT_INVALID",`${t}/nodes`);let s=R(e.startAt,`${t}/startAt`,128);o[s]||p("NATIVE_WORKFLOW_START_NODE_MISSING",`${t}/startAt`);let i=new Map;for(let[f,E]of Object.entries(o)){let d=`${t}/nodes/${f}`,u=g(E,d);L(u.id,f,`${d}/id`),["approval","condition","end"].includes(u.kind)||p("NATIVE_WORKFLOW_NODE_KIND_INVALID",`${d}/kind`);let m=[];if(u.kind==="approval"){R(u.title,`${d}/title`,255),Ht(u.binding,`${d}/binding`),["single","any","all","sequence"].includes(u.mode)||p("NATIVE_WORKFLOW_APPROVAL_MODE_INVALID",`${d}/mode`),m.push(R(u.onApprove,`${d}/onApprove`,128),R(u.onReject,`${d}/onReject`,128));for(let l of F(u.returnTargets||[],`${d}/returnTargets`,200))o[l]||p("NATIVE_WORKFLOW_TARGET_MISSING",`${d}/returnTargets`);for(let l of F(u.allowedOperations||[],`${d}/allowedOperations`,20))Ps.has(l)||p("NATIVE_WORKFLOW_OPERATION_INVALID",`${d}/allowedOperations`)}else if(u.kind==="condition"){let l=$(u.branches,`${d}/branches`,100);l.length===0&&p("NATIVE_WORKFLOW_BRANCH_REQUIRED",`${d}/branches`),l.forEach((A,N)=>{let _=g(A,`${d}/branches/${N}`);Je(_.when,`${d}/branches/${N}/when`,0),m.push(R(_.target,`${d}/branches/${N}/target`,128))}),m.push(R(u.otherwise,`${d}/otherwise`,128))}else R(u.title,`${d}/title`,255),R(u.outcome,`${d}/outcome`,128);for(let l of m)o[l]||p("NATIVE_WORKFLOW_TARGET_MISSING",d);i.set(f,m)}let c=new Set,r=new Set,a=f=>{if(r.has(f)&&p("NATIVE_WORKFLOW_CYCLE_FORBIDDEN",`${t}/nodes/${f}`),!c.has(f)){c.add(f),r.add(f);for(let E of i.get(f)||[])a(E);r.delete(f)}};a(s),c.size!==n.length&&p("NATIVE_WORKFLOW_NODE_UNREACHABLE",`${t}/nodes`)}function Je(e,t,o){o>20&&p("NATIVE_WORKFLOW_EXPRESSION_DEPTH_EXCEEDED",t);let n=g(e,t),s=R(n.op,`${t}/op`,16);if(s!=="literal"){if(s==="path"){let i=R(n.path,`${t}/path`,255);/^[A-Za-z][A-Za-z0-9_.]{0,254}$/.test(i)||p("NATIVE_WORKFLOW_EXPRESSION_PATH_INVALID",`${t}/path`);return}if(["eq","neq","gt","gte","lt","lte","in","contains"].includes(s)){Je(n.left,`${t}/left`,o+1),Je(n.right,`${t}/right`,o+1);return}if(["and","or"].includes(s)){let i=$(n.values,`${t}/values`,100);i.length===0&&p("NATIVE_WORKFLOW_EXPRESSION_EMPTY",`${t}/values`),i.forEach((c,r)=>Je(c,`${t}/values/${r}`,o+1));return}if(["not","exists"].includes(s)){Je(n.value,`${t}/value`,o+1);return}p("NATIVE_WORKFLOW_EXPRESSION_OPERATOR_INVALID",`${t}/op`)}}function Vi(e,t){L(e.schemaVersion,"openxiangda.workflow-binding/v2",`${t}/schemaVersion`),lt(e.workflowCode,`${t}/workflowCode`);let o=g(e.bindings,`${t}/bindings`);Object.keys(o).length>200&&p("NATIVE_WORKFLOW_BINDING_LIMIT_EXCEEDED",`${t}/bindings`);for(let[n,s]of Object.entries(o)){Ht(n,`${t}/bindings/${n}`);let i=g(s,`${t}/bindings/${n}`),c=R(i.provider,`${t}/bindings/${n}/provider`,64);["fixed_users","initiator","input_users","form_field_users","department_supervisor","app_role","app_role_in_scope","business_relation","previous_node_actor","initiator_select","application_provider"].includes(c)||p("NATIVE_WORKFLOW_BINDING_PROVIDER_INVALID",`${t}/bindings/${n}/provider`),c==="fixed_users"&&$(i.users,`${t}/bindings/${n}/users`,200).length===0&&p("NATIVE_WORKFLOW_BINDING_USERS_REQUIRED",`${t}/bindings/${n}/users`),["input_users","form_field_users"].includes(c)&&R(i.inputPath,`${t}/bindings/${n}/inputPath`,255),["app_role","app_role_in_scope","initiator_select"].includes(c)&&w(i.roleCode,`${t}/bindings/${n}/roleCode`),c==="department_supervisor"&&R(i.departmentIdFrom,`${t}/bindings/${n}/departmentIdFrom`,255),c==="application_provider"&&w(i.providerCode,`${t}/bindings/${n}/providerCode`)}}function wi(e,t,o){L(t.workflowCode,e.code,`${o}/workflowCode`);let n=g(t.bindings,`${o}/bindings`);for(let[s,i]of Object.entries(g(e.nodes,`${o}/nodes`))){let c=g(i,`${o}/nodes/${s}`);c.kind==="approval"&&!n[c.binding]&&p("NATIVE_WORKFLOW_BINDING_REFERENCE_MISSING",`${o}/nodes/${s}/binding`)}}function Fi(e,t,o){let n=g(t.routeManifest,"/contracts/routeManifest"),s=g(e.routeManifest,"/contracts/routeManifest"),i=new Map;for(let E of $(o.data?.resources,"/config/data/resources",100)){let d=g(E,"/config/data/resources");i.set(String(d.code||""),d)}let c=new Set($(s.routes,"/contracts/routeManifest/routes",1e3).map(E=>String(g(E,"/contracts/routeManifest/routes").code||""))),r=[];for(let E of $(n.routes,"/contracts/routeManifest/routes",1e3)){let d=g(E,"/contracts/routeManifest/routes"),u=String(d.kind||"");if(u!=="resource-records"&&u!=="resource-submit")continue;let m=String(d.resourceCode||""),l=i.get(m);l||p("NATIVE_ROUTE_MANIFEST_RESOURCE_UNKNOWN","/contracts/routeManifest/routes");let N=`user.${m}.${u==="resource-records"?"records":"submit"}`;L(String(d.code||""),N,"/contracts/routeManifest/routes/code");let _=u==="resource-records"?"read":"create",I=String(g(l.capabilities,"/config/data/resources/capabilities")[_]||"");for(let T of["desktop","mobile"]){let b=g(d[T],`/contracts/routeManifest/routes/${T}`),C=T==="mobile"?"/m/my/":"/my/",O=u==="resource-records"?`${C}${m}`:`${C}${m}/submit`;L(String(b.path||""),O,`/contracts/routeManifest/routes/${T}/path`),L(String(b.capability||""),I,`/contracts/routeManifest/routes/${T}/capability`),L(String(b.routeCode||""),`${N}.${T}`,`/contracts/routeManifest/routes/${T}/routeCode`)}(c.has(N)||r.some(T=>String(T.code)===N))&&p("NATIVE_ROUTE_MANIFEST_DUPLICATE","/contracts/routeManifest/routes/code"),r.push(d)}if(!r.length)return;s.routes=$([...s.routes,...r],"/contracts/routeManifest/routes",1e3).sort((E,d)=>ae(String(g(E,"x").code||""),String(g(d,"x").code||"")));let a=String(g(n.rootEntry,"x").code||"");if(r.find(E=>String(E.code)===a&&E.kind==="resource-records")){let E=g(n.rootEntry,"x");s.rootEntry={code:a,desktop:String(E.desktop||""),mobile:String(E.mobile||"")}}s.digest=ee({schemaVersion:s.schemaVersion,appCode:s.appCode,devicePolicy:s.devicePolicy,rootEntry:s.rootEntry,authentication:s.authentication,routes:s.routes})}function ye(e,t,o){let n=g(e,t);y(n,["schemaVersion","appCode","code","name","schema","surface","invariants","decimalReservationLifecycle","uniqueKeys","capabilities","dataPolicyCode","fieldPolicies"],t,!0),L(n.schemaVersion,"openxiangda.data-resource/v2",`${t}/schemaVersion`),L(n.appCode,o,`${t}/appCode`);let s=z(n.code,`${t}/code`),i=R(n.name,`${t}/name`,255),c=g(n.schema,`${t}/schema`);y(c,["fields"],`${t}/schema`);let r,a,f,E;try{f=Vt(n.decimalReservationLifecycle,`${t}/decimalReservationLifecycle`),r=It(c.fields,`${t}/schema/fields`),E=Sn(n.uniqueKeys,r,`${t}/uniqueKeys`),a=on(n.invariants,r,`${t}/invariants`),$t(n.surface,r,`${t}/surface`)}catch(l){throw(l instanceof _e||l instanceof De||l instanceof je)&&p(l.code,l.pointer),l}let d=new Set(r.map(l=>l.code)),u=g(n.capabilities,`${t}/capabilities`);y(u,["read","create","update","delete"],`${t}/capabilities`);let m=g(n.fieldPolicies,`${t}/fieldPolicies`);for(let[l,A]of Object.entries(m)){!d.has(l)&&!ve(l)&&p("NATIVE_DATA_FIELD_POLICY_FIELD_MISSING",`${t}/fieldPolicies/${l}`);let N=`${t}/fieldPolicies/${l}`,_=g(A,N);ve(l)&&(y(_,["read"],N,!0),(!Array.isArray(_.read)||_.read.length>20||_.read.some(I=>typeof I!="string"||!I.trim())||new Set(_.read).size!==_.read.length)&&p("NATIVE_DATA_AUDIT_READ_POLICY_INVALID",`${N}/read`)),y(_,["read","create","update","mask"],N,!0),_.mask!==void 0&&!["omit","null"].includes(_.mask)&&p("NATIVE_DATA_FIELD_POLICY_MASK_INVALID",`${N}/mask`)}return{...n,code:s,name:i,schema:{fields:r},...n.invariants===void 0?{}:{invariants:a},...f?{decimalReservationLifecycle:f}:{},...E!==void 0?{uniqueKeys:E}:{},capabilities:u,fieldPolicies:m}}function Io(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 Qn(e,t,o,n){let s=e.toString("utf8"),i;try{i=JSON.parse(s)}catch{p(o,t)}let c=g(i,t);return Q(c)!==s&&p(n,t),c}function Zn(e,t){let o=0,n=(s,i,c)=>{if(o+=1,o>Us&&p("NATIVE_ARTIFACT_NODE_LIMIT_EXCEEDED",i),c>xs&&p("NATIVE_ARTIFACT_DEPTH_LIMIT_EXCEEDED",i),typeof s=="string"){Buffer.byteLength(s)>jt&&p("NATIVE_ARTIFACT_STRING_LIMIT_EXCEEDED",i);return}if(Array.isArray(s)){s.forEach((r,a)=>n(r,`${i}/${a}`,c+1));return}if(!(!s||typeof s!="object"))for(let[r,a]of Object.entries(s))["__proto__","prototype","constructor"].includes(r)&&p("NATIVE_ARTIFACT_DANGEROUS_KEY",`${i}/${r}`),vi(r)&&p("NATIVE_ARTIFACT_RUNTIME_FIELD_FORBIDDEN",`${i}/${r}`),n(a,`${i}/${r}`,c+1)};n(e,t,0)}function vi(e){return["environmentKey","environmentId","secretValue","ciphertext","oauthClient","oauthClientId","oauthClientSecret","signingSecret","kubernetesNamespace","nodePort","productionUrl"].includes(e)}function Ve(e){return{value:e,digest:ee(e)}}function eo(e,t,o,n){typeof e!="string"&&!Buffer.isBuffer(e)&&!(e instanceof Uint8Array)&&p("NATIVE_ARTIFACT_BYTES_REQUIRED",o);let s=Buffer.isBuffer(e)?e:Buffer.from(e);return s.byteLength===0&&p("NATIVE_ARTIFACT_EMPTY",o),s.byteLength>t&&p(n,o),s}function to(e,t,o,n){let s=at.createHash("sha256").update(e).digest("hex");at.timingSafeEqual(Buffer.from(s),Buffer.from(t))||p(n,o)}function g(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&p("NATIVE_OBJECT_REQUIRED",t),e}function $(e,t,o){return Array.isArray(e)||p("NATIVE_ARRAY_REQUIRED",t),e.length>o&&p("NATIVE_ARRAY_LIMIT_EXCEEDED",t),e}function F(e,t,o){let n=$(e,t,o).map((s,i)=>R(s,`${t}/${i}`,255));return new Set(n).size!==n.length&&p("NATIVE_ARRAY_DUPLICATE",t),n}function R(e,t,o){return(typeof e!="string"||e.length===0||e.length>o)&&p("NATIVE_STRING_INVALID",t),e}function Kt(e,t,o){return(typeof e!="string"||e.length>o)&&p("NATIVE_STRING_INVALID",t),e}function w(e,t){let o=R(e,t,128);return Cs.test(o)||p("NATIVE_CODE_INVALID",t),o}function z(e,t){let o=R(e,t,64);return Os.test(o)||p("NATIVE_RESOURCE_CODE_INVALID",t),o}function B(e,t){let o=R(e,t,63);return ys.test(o)||p("NATIVE_FIELD_CODE_INVALID",t),o}function lt(e,t){let o=R(e,t,128);return hs.test(o)||p("NATIVE_WORKFLOW_CODE_INVALID",t),o}function Ht(e,t){let o=R(e,t,128);return Ss.test(o)||p("NATIVE_WORKFLOW_BINDING_CODE_INVALID",t),o}function Ne(e,t,o){let n=R(e,t,255);return Ts.test(n)||p("NATIVE_CAPABILITY_CODE_INVALID",t),!n.startsWith(`app:${o}:`)&&!Io(o).some(s=>s.code===n)&&p("NATIVE_CAPABILITY_APP_MISMATCH",t),n}function le(e,t){let o=R(e,t,2048);return(!o.startsWith("/")||o.startsWith("//")||o.includes("..")||o.includes("?")||o.includes("#"))&&p("NATIVE_ABSOLUTE_PATH_INVALID",t),o}function we(e,t){return(!Number.isInteger(e)||Number(e)<1)&&p("NATIVE_POSITIVE_INTEGER_REQUIRED",t),Number(e)}function Z(e,t,o,n){return(!Number.isInteger(e)||Number(e)<o||Number(e)>n)&&p("NATIVE_INTEGER_OUT_OF_RANGE",t),Number(e)}function Fe(e,t){return typeof e!="boolean"&&p("NATIVE_BOOLEAN_REQUIRED",t),e}function zt(e,t){let o=R(e,t,64).toLowerCase();return gs.test(o)||p("NATIVE_DIGEST_INVALID",t),o}function L(e,t,o){e!==t&&p("NATIVE_VALUE_MISMATCH",o)}function y(e,t,o,n=!1){let s=new Set([...t,...Array.isArray(n)?n:[]]);for(let i of Object.keys(e))s.has(i)||p("NATIVE_PROPERTY_UNKNOWN",`${o}/${i}`);if(n!==!0)for(let i of t)Object.prototype.hasOwnProperty.call(e,i)||p("NATIVE_PROPERTY_REQUIRED",`${o}/${i}`)}function X(e,t){return[...e].sort((o,n)=>ae(t(o),t(n)))}function M(e){return[...new Set(e)].sort(ae)}function no(e){return[...new Set(e)].sort((t,o)=>t-o)}function ae(e,t){return e===t?0:e<t?-1:1}function mo(e){return!e||typeof e!="object"||Object.isFrozen(e)||(Object.freeze(e),Object.values(e).forEach(t=>mo(t))),e}function Gt(e,t,o){if(Ut(e,t))return o;if(Array.isArray(e)&&Array.isArray(t)){let n=Math.max(e.length,t.length);for(let s=0;s<n;s+=1)if(!Ut(e[s],t[s]))return Gt(e[s],t[s],`${o}/${s}`)}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 s of n){let i=e[s],c=t[s];if(!Ut(i,c))return Gt(i,c,`${o}/${s}`)}}return o}function Ut(e,t){return e===void 0||t===void 0?e===t:Q(e)===Q(t)}function p(e,t,o={}){throw new Jt(e,t,o)}var oa="b74d84f1cee1d0b9cbb8ac4f6ebb4219a694bbcdf85659bd060fed2be760eee5";export{sn as DATA_AUDIT_METADATA_FIELDS,Mt as DATA_EVENT_TYPES_V2,wo as DATA_SYSTEM_SORT_FIELD_CODES,ke as ManagedConcurrencyContractError,oa as NATIVE_CONFIGURATION_VALIDATOR_DIGEST,Y as NATIVE_CONTRACT_CAPACITY_V2,Pr as NATIVE_DATA_POLICY_EXPRESSION_MAX_CLAUSES,wr as NATIVE_DATA_POLICY_EXPRESSION_MAX_DEPTH,Fr as NATIVE_DATA_POLICY_EXPRESSION_MAX_GROUP_ITEMS,vr as NATIVE_DATA_POLICY_EXPRESSION_MAX_LEAVES,Lr as NATIVE_DATA_POLICY_EXPRESSION_MAX_OCCURRENCES,Fo as NATIVE_DATA_QUERY_OPERATORS_V2,Cr as NATIVE_UNIQUE_KEY_MAX_BYTES,hn as NATIVE_UNIQUE_KEY_NORMALIZERS,Jt as NativeConfigurationCompilerError,_e as NativeDataFieldContractV2Error,Be as NativeDataPolicyExpressionV2Error,De as NativeDecimalLifecycleContractError,kt as NativeEventActionContractError,Ft as NativeScopeSourceFieldPathV2Error,je as NativeUniqueKeyContractError,To as OPENXIANGDA_NATIVE_DATA_FIELD_TYPES_V2,Te as OPENXIANGDA_NATIVE_DATA_SURFACE_KEYS_V2,bt as OPENXIANGDA_NATIVE_DRAFT_STATE_KEYS_V2,At as OPENXIANGDA_NATIVE_SYSTEM_FIELDS_V2,ki as OPENXIANGDA_NATIVE_SYSTEM_FIELD_MAP_V2,Bt as WORKFLOW_EVENT_TYPES_V2,ta as compileNativeApplicationConfiguration,Fn as compileNativeEventAction,Js as compileNativeEventCapturePlansV2,Bs as compileRequiredPlatformCapabilitiesV3,rn as hasDataAuditReadPolicy,ve as isDataAuditMetadataField,an as isDataSystemSortField,Mi as isNativeDataQueryOperatorV2,Ye as isNativeMultiValueFieldV2,gr as materializeNativeDataQueryPathTypesV2,st as nativeDataPolicyExpressionLeavesV2,xn as nativeDataPolicyExpressionToCnfV2,Nr as nativeDataQueryPathPlanV2,Ji as nativeFieldAggregatePlanV2,cr as nativeFieldColumnDefinitionV2,dr as nativeFieldDefaultSqlV2,lr as nativeFieldHasDefaultV2,_r as nativeFieldIndexStatementsV2,Ke as nativeFieldRequiresCreateInputV2,pr as nativeFieldSequenceGrantStatementsV2,fr as nativeFieldSequenceOwnershipStatementsV2,ur as nativeFieldSequenceStatementsV2,un as nativeFieldSupportsFilterV2,Bi as nativeFieldSupportsOperatorV2,Tt as nativeFieldSupportsSearchV2,Le as nativeFieldSupportsSortV2,ln as nativeOperatorsForFieldV2,ts as nativePhysicalFieldV2,ar as nativePhysicalFieldsV2,Ce as nativePhysicalObjectNameV2,Ir as nativeScopeSourceFieldValueV2,$n as nativeScopeSourceGrantPathSupportedV2,vt as nativeScopeSourceSubjectPathSupportedV2,Er as nativeSubtableConstraintStatementsV2,br as nativeUniqueKeysJsonSchema,Vt as parseDecimalReservationLifecycle,It as parseNativeDataFieldsV2,on as parseNativeDataResourceInvariantsV2,Sn as parseNativeUniqueKeys,Rt as projectNativeDataResourceViewV2,se as quoteNativeIdentifierV2,xe as resolveNativeScopeSourceFieldPathV2,Nn as validateDecimalReservationLifecycles,mn as validateManagedConcurrency,_n as validateNativeDataDraftStateV2,nn as validateNativeDataResourceReferencesV2,$t as validateNativeDataResourceSurfaceV2,Pn as validateWorkflowInstanceCommandPolicies,Sr as workflowInstanceCommandDeadlineError,hr as workflowInstanceTerminateCapabilityAllowed,vn as workflowPolicyTimestamp};
|