openxiangda-contracts 2.47.0 → 2.69.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai.d.ts +1 -1
- package/dist/ai.d.ts.map +1 -1
- package/dist/ai.js +4 -3
- package/dist/ai.js.map +1 -1
- package/dist/browser.d.ts +13 -0
- package/dist/browser.d.ts.map +1 -1
- package/dist/browser.js +13 -0
- package/dist/browser.js.map +1 -1
- package/dist/concurrency.d.ts +3 -3
- package/dist/concurrency.d.ts.map +1 -1
- package/dist/data-field-validation.d.ts.map +1 -1
- package/dist/data-field-validation.js +17 -2
- package/dist/data-field-validation.js.map +1 -1
- package/dist/field-value-schemas.d.ts +1 -1
- package/dist/index.d.ts +17 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +17 -0
- package/dist/index.js.map +1 -1
- package/dist/native-compiler/actor-authority.d.ts +11 -0
- package/dist/native-compiler/actor-authority.d.ts.map +1 -0
- package/dist/native-compiler/actor-authority.js +56 -0
- package/dist/native-compiler/actor-authority.js.map +1 -0
- package/dist/native-compiler/artifact-capacity.d.ts +12 -0
- package/dist/native-compiler/artifact-capacity.d.ts.map +1 -0
- package/dist/native-compiler/artifact-capacity.js +34 -0
- package/dist/native-compiler/artifact-capacity.js.map +1 -0
- package/dist/native-compiler/authenticated-public-read.d.ts +18 -0
- package/dist/native-compiler/authenticated-public-read.d.ts.map +1 -0
- package/dist/native-compiler/authenticated-public-read.js +79 -0
- package/dist/native-compiler/authenticated-public-read.js.map +1 -0
- package/dist/native-compiler/compiler.d.ts +3 -22
- package/dist/native-compiler/compiler.d.ts.map +1 -1
- package/dist/native-compiler/compiler.js +441 -59
- package/dist/native-compiler/compiler.js.map +1 -1
- package/dist/native-compiler/data-business-command.d.ts +44 -0
- package/dist/native-compiler/data-business-command.d.ts.map +1 -0
- package/dist/native-compiler/data-business-command.js +88 -0
- package/dist/native-compiler/data-business-command.js.map +1 -0
- package/dist/native-compiler/data-capacity.d.ts +14 -3
- package/dist/native-compiler/data-capacity.d.ts.map +1 -1
- package/dist/native-compiler/data-capacity.js +11 -3
- package/dist/native-compiler/data-capacity.js.map +1 -1
- package/dist/native-compiler/data-field.d.ts +24 -0
- package/dist/native-compiler/data-field.d.ts.map +1 -1
- package/dist/native-compiler/data-field.js +23 -2
- package/dist/native-compiler/data-field.js.map +1 -1
- package/dist/native-compiler/data-surface.d.ts +1 -1
- package/dist/native-compiler/data-surface.d.ts.map +1 -1
- package/dist/native-compiler/data-surface.js +2 -0
- package/dist/native-compiler/data-surface.js.map +1 -1
- package/dist/native-compiler/date-event-projection.d.ts +13 -0
- package/dist/native-compiler/date-event-projection.d.ts.map +1 -0
- package/dist/native-compiler/date-event-projection.js +71 -0
- package/dist/native-compiler/date-event-projection.js.map +1 -0
- package/dist/native-compiler/declaration-capacity.d.ts +60 -0
- package/dist/native-compiler/declaration-capacity.d.ts.map +1 -0
- package/dist/native-compiler/declaration-capacity.js +32 -0
- package/dist/native-compiler/declaration-capacity.js.map +1 -0
- package/dist/native-compiler/development-backend.d.ts +84 -0
- package/dist/native-compiler/development-backend.d.ts.map +1 -0
- package/dist/native-compiler/development-backend.js +77 -0
- package/dist/native-compiler/development-backend.js.map +1 -0
- package/dist/native-compiler/development-configuration.d.ts +65 -0
- package/dist/native-compiler/development-configuration.d.ts.map +1 -0
- package/dist/native-compiler/development-configuration.js +143 -0
- package/dist/native-compiler/development-configuration.js.map +1 -0
- package/dist/native-compiler/index.cjs +6 -6
- package/dist/native-compiler/index.d.ts +22 -0
- package/dist/native-compiler/index.d.ts.map +1 -1
- package/dist/native-compiler/index.js +6 -6
- package/dist/native-compiler/managed-concurrency.js +2 -2
- package/dist/native-compiler/managed-concurrency.js.map +1 -1
- package/dist/native-compiler/record-set-guard.d.ts +5 -0
- package/dist/native-compiler/record-set-guard.d.ts.map +1 -0
- package/dist/native-compiler/record-set-guard.js +27 -0
- package/dist/native-compiler/record-set-guard.js.map +1 -0
- package/dist/native-compiler/resource-view.d.ts +4 -0
- package/dist/native-compiler/resource-view.d.ts.map +1 -0
- package/dist/native-compiler/resource-view.js +20 -0
- package/dist/native-compiler/resource-view.js.map +1 -0
- package/dist/native-compiler/unique-keys.d.ts +21 -0
- package/dist/native-compiler/unique-keys.d.ts.map +1 -1
- package/dist/native-compiler/unique-keys.js +17 -3
- package/dist/native-compiler/unique-keys.js.map +1 -1
- package/dist/native-compiler/user-candidates.d.ts +80 -0
- package/dist/native-compiler/user-candidates.d.ts.map +1 -0
- package/dist/native-compiler/user-candidates.js +197 -0
- package/dist/native-compiler/user-candidates.js.map +1 -0
- package/dist/native-compiler/workflow-approval-empty.d.ts +28 -0
- package/dist/native-compiler/workflow-approval-empty.d.ts.map +1 -0
- package/dist/native-compiler/workflow-approval-empty.js +34 -0
- package/dist/native-compiler/workflow-approval-empty.js.map +1 -0
- package/dist/native-compiler/workflow-approved-delegation.d.ts +39 -0
- package/dist/native-compiler/workflow-approved-delegation.d.ts.map +1 -0
- package/dist/native-compiler/workflow-approved-delegation.js +94 -0
- package/dist/native-compiler/workflow-approved-delegation.js.map +1 -0
- package/dist/native-compiler/workflow-business-command.d.ts +108 -0
- package/dist/native-compiler/workflow-business-command.d.ts.map +1 -0
- package/dist/native-compiler/workflow-business-command.js +62 -0
- package/dist/native-compiler/workflow-business-command.js.map +1 -0
- package/dist/native-compiler/workflow-completion-deadline.d.ts +41 -0
- package/dist/native-compiler/workflow-completion-deadline.d.ts.map +1 -0
- package/dist/native-compiler/workflow-completion-deadline.js +40 -0
- package/dist/native-compiler/workflow-completion-deadline.js.map +1 -0
- package/dist/native-compiler/workflow-correction.d.ts +16 -0
- package/dist/native-compiler/workflow-correction.d.ts.map +1 -0
- package/dist/native-compiler/workflow-correction.js +42 -0
- package/dist/native-compiler/workflow-correction.js.map +1 -0
- package/dist/native-compiler/workflow-delegation-administration.d.ts +73 -0
- package/dist/native-compiler/workflow-delegation-administration.d.ts.map +1 -1
- package/dist/native-compiler/workflow-delegation-administration.js +6 -4
- package/dist/native-compiler/workflow-delegation-administration.js.map +1 -1
- package/dist/native-compiler/workflow-graph.d.ts +21 -2
- package/dist/native-compiler/workflow-graph.d.ts.map +1 -1
- package/dist/native-compiler/workflow-graph.js +20 -3
- package/dist/native-compiler/workflow-graph.js.map +1 -1
- package/dist/native-compiler/workflow-initiator-approval.d.ts +32 -0
- package/dist/native-compiler/workflow-initiator-approval.d.ts.map +1 -0
- package/dist/native-compiler/workflow-initiator-approval.js +45 -0
- package/dist/native-compiler/workflow-initiator-approval.js.map +1 -0
- package/dist/native-compiler/workflow-instance-policy.d.ts +2 -0
- package/dist/native-compiler/workflow-instance-policy.d.ts.map +1 -1
- package/dist/native-compiler/workflow-instance-policy.js +9 -4
- package/dist/native-compiler/workflow-instance-policy.js.map +1 -1
- package/dist/native-compiler/workflow-launch-preflight.d.ts +22 -0
- package/dist/native-compiler/workflow-launch-preflight.d.ts.map +1 -0
- package/dist/native-compiler/workflow-launch-preflight.js +30 -0
- package/dist/native-compiler/workflow-launch-preflight.js.map +1 -0
- package/dist/native-compiler/workflow-native-stage.d.ts +69 -0
- package/dist/native-compiler/workflow-native-stage.d.ts.map +1 -0
- package/dist/native-compiler/workflow-native-stage.js +42 -0
- package/dist/native-compiler/workflow-native-stage.js.map +1 -0
- package/dist/native-compiler/workflow-node-administration.d.ts +11 -1
- package/dist/native-compiler/workflow-node-administration.d.ts.map +1 -1
- package/dist/native-compiler/workflow-node-administration.js +25 -5
- package/dist/native-compiler/workflow-node-administration.js.map +1 -1
- package/dist/native-compiler/workflow-owned-subject.d.ts +60 -0
- package/dist/native-compiler/workflow-owned-subject.d.ts.map +1 -0
- package/dist/native-compiler/workflow-owned-subject.js +69 -0
- package/dist/native-compiler/workflow-owned-subject.js.map +1 -0
- package/dist/native-compiler/workflow-rejection-notification.d.ts +31 -0
- package/dist/native-compiler/workflow-rejection-notification.d.ts.map +1 -0
- package/dist/native-compiler/workflow-rejection-notification.js +47 -0
- package/dist/native-compiler/workflow-rejection-notification.js.map +1 -0
- package/dist/native-compiler/workflow-role-union.d.ts +31 -0
- package/dist/native-compiler/workflow-role-union.d.ts.map +1 -0
- package/dist/native-compiler/workflow-role-union.js +38 -0
- package/dist/native-compiler/workflow-role-union.js.map +1 -0
- package/dist/native-compiler/workflow-task-page.d.ts +10 -3
- package/dist/native-compiler/workflow-task-page.d.ts.map +1 -1
- package/dist/native-compiler/workflow-task-page.js +5 -3
- package/dist/native-compiler/workflow-task-page.js.map +1 -1
- package/dist/native-version.d.ts +36 -1
- package/dist/native-version.d.ts.map +1 -1
- package/dist/native-version.js +36 -1
- package/dist/native-version.js.map +1 -1
- package/dist/native.d.ts +24 -2
- package/dist/native.d.ts.map +1 -1
- package/dist/native.js.map +1 -1
- package/dist/references.d.ts +2 -0
- package/dist/references.d.ts.map +1 -1
- package/dist/schemas.d.ts +10118 -5656
- package/dist/schemas.d.ts.map +1 -1
- package/dist/schemas.js +379 -17
- package/dist/schemas.js.map +1 -1
- package/dist/surface.d.ts +4 -2
- package/dist/surface.d.ts.map +1 -1
- package/dist/surface.js +1 -19
- package/dist/surface.js.map +1 -1
- package/dist/types.d.ts +371 -13
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +6 -2
- package/dist/types.js.map +1 -1
- package/dist/validation.d.ts.map +1 -1
- package/dist/validation.js +61 -2
- package/dist/validation.js.map +1 -1
- package/package.json +1 -1
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import{createHash as Yi}from"node:crypto";function Hi(e){if(!e||typeof e!="object")return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Zt(e,t){if(e===null)return"null";if(typeof e=="string"||typeof e=="boolean")return JSON.stringify(e);if(typeof e=="number"){if(!Number.isFinite(e))throw new TypeError(`JSON number must be finite: ${t}`);return JSON.stringify(e)}if(Array.isArray(e))return`[${e.map((n,i)=>Zt(n,`${t}[${i}]`)).join(",")}]`;if(Hi(e))return`{${Object.keys(e).filter(i=>e[i]!==void 0).sort((i,s)=>i===s?0:i<s?-1:1).map(i=>`${JSON.stringify(i)}:${Zt(e[i],`${t}.${i}`)}`).join(",")}}`;let o=e instanceof Date?"Date":e?.constructor?.name||typeof e;throw new TypeError(`Value is not JSON serializable: ${t} (${o})`)}function ee(e){return Zt(e,"$")}function X(e){return Yi("sha256").update(ee(e)).digest("hex")}var It=100,bt=400,Da=1e3,$a=2097152,ka=2097152;function Va(e){try{return new TextEncoder().encode(JSON.stringify(e)).byteLength}catch{return 1/0}}var io=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,nn=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,Xi=["text.short","text.long","text.rich","number.integer","number.decimal","boolean","date","time","datetime","date-range","datetime-range","option.single","option.multiple","cascade.single","cascade.multiple","user.single","user.multiple","department.single","department.multiple","resource-ref.single","resource-ref.multiple","image","signature","address","location","uuid","json","file","serial-number","subtable"],Qi=new Set(Xi),so=new Set(["option.multiple","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","file","image","subtable"]),to=new Set(["option.single","option.multiple","cascade.single","cascade.multiple"]),no=new Set(["resource-ref.single","resource-ref.multiple"]),on=[{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}],ro=new Map(on.map(e=>[e.code,e])),Ee=class extends Error{constructor(o,n){super(o);this.code=o;this.pointer=n;this.name="NativeDataFieldContractV2Error"}code;pointer};function Tt(e){return so.has(e)}function Ot(e,t={}){return e.type!=="serial-number"&&t.system!==!0&&e.nullable===!1&&(!Tt(e.type)||t.requiredHint===!0)}function sn(e,t,o=500){Array.isArray(e)||D("NATIVE_ARRAY_REQUIRED",t),e.length===0&&D("NATIVE_DATA_FIELDS_REQUIRED",t),e.length>o&&D("NATIVE_ARRAY_LIMIT_EXCEEDED",t);let n=new Set;return e.map((i,s)=>{let a=`${t}/${s}`,r=le(i,a);pe(r,["code","type","nullable","indexed","options","source","maxLength","precision","scale","exactDecimal","min","max","rangeBoundary","timePrecision","file","serial","subtable"],a);let c=_e(r.code,`${a}/code`,63);io.test(c)||D("NATIVE_FIELD_CODE_INVALID",`${a}/code`),n.has(c)&&D("NATIVE_DATA_FIELD_DUPLICATE",`${a}/code`),n.add(c);let l=_e(r.type,`${a}/type`,32);Qi.has(l)||D("NATIVE_DATA_FIELD_TYPE_INVALID",`${a}/type`);let p=l,d=tn(r.nullable,`${a}/nullable`),f=tn(r.indexed,`${a}/indexed`);d===!0&&so.has(p)&&D("NATIVE_DATA_MULTI_FIELD_NULLABLE_INVALID",`${a}/nullable`);let g=ts(r.options,p,a),E=ns(r.source,p,a),A=is(r,p,a),b=tn(r.exactDecimal,`${a}/exactDecimal`);b!==void 0&&p!=="number.decimal"&&D("NATIVE_DATA_FIELD_EXACT_DECIMAL_TYPE_INVALID",`${a}/exactDecimal`);let I=Zi(r.rangeBoundary,p,a),_=ss(r.file,p,a),u=rs(r.serial,p,a),N=as(r.subtable,p,a);return{code:c,type:p,...d===void 0?{}:{nullable:d},...f===void 0?{}:{indexed:f},...g?{options:g}:{},...E?{source:E}:{},...A,...b===void 0?{}:{exactDecimal:b},...I?{rangeBoundary:I}:{},..._?{file:_}:{},...u?{serial:u}:{},...N?{subtable:N}:{}}})}function Zi(e,t,o){let n=`${o}/rangeBoundary`;if(!(t==="date-range"||t==="datetime-range")){e!==void 0&&D("NATIVE_DATA_FIELD_RANGE_BOUNDARY_TYPE_INVALID",n);return}return e!=="closed"&&e!=="half-open"&&D("NATIVE_DATA_FIELD_RANGE_BOUNDARY_REQUIRED",n),e}function ao(e,t){Array.isArray(e)||D("NATIVE_ARRAY_REQUIRED",t);let o=new Map;e.forEach((n,i)=>{let s=`${t}/${i}`,a=le(n,s),r=_e(a.code,`${s}/code`,64);(!nn.test(r)||o.has(r))&&D("NATIVE_RESOURCE_CODE_INVALID",`${s}/code`);let c=le(a.schema,`${s}/schema`);o.set(r,{pointer:s,fields:sn(c.fields,`${s}/schema/fields`)})});for(let[n,i]of o){let s=new Map(i.fields.map(r=>[r.code,r]));i.fields.filter(r=>r.type==="subtable").reduce((r,c)=>r+(c.subtable?.maxRows??20),0)>400&&D("NATIVE_DATA_FIELD_SUBTABLE_AGGREGATE_MAX_ROWS_EXCEEDED",`${i.pointer}/schema/fields`),i.fields.forEach((r,c)=>{let l=`${i.pointer}/schema/fields/${c}`;if(r.source&&es(r.source,s,o,`${l}/source`),r.subtable){let p=o.get(r.subtable.resourceCode);(!p||r.subtable.resourceCode===n)&&D("NATIVE_DATA_FIELD_SUBTABLE_TARGET_MISSING",`${l}/subtable/resourceCode`);let d=p.fields.find(g=>g.code===r.subtable?.foreignKey);(!d||d.type!=="uuid"||d.nullable!==!1)&&D("NATIVE_DATA_FIELD_SUBTABLE_FOREIGN_KEY_INVALID",`${l}/subtable/foreignKey`);let f=p.fields.find(g=>g.code===r.subtable?.orderField);(!f||f.type!=="number.integer"||f.nullable!==!1)&&D("NATIVE_DATA_FIELD_SUBTABLE_ORDER_FIELD_INVALID",`${l}/subtable/orderField`)}})}}function co(e,t,o){if(e===void 0)return[];(!Array.isArray(e)||e.length>20)&&D("NATIVE_DATA_RESOURCE_INVARIANTS_INVALID",o);let n=new Map(t.map(s=>[s.code,s])),i=new Set;return e.map((s,a)=>{let r=`${o}/${a}`,c=le(s,r);pe(c,["code","message","expression"],r);let l=_e(c.code,`${r}/code`,128);(!/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/.test(l)||i.has(l))&&D("NATIVE_DATA_RESOURCE_INVARIANT_CODE_INVALID",`${r}/code`),i.add(l);let p=Nt(c.message,`${r}/message`,500);p!==void 0&&p.length===0&&D("NATIVE_DATA_RESOURCE_INVARIANT_MESSAGE_INVALID",`${r}/message`);let d=le(c.expression,`${r}/expression`);if(d.kind==="nonBlankTextWhenOption"){pe(d,["kind","optionField","optionValue","textField"],`${r}/expression`);let _=Ae(d.optionField,`${r}/expression/optionField`),u=Ae(d.textField,`${r}/expression/textField`),N=_e(d.optionValue,`${r}/expression/optionValue`,128),y=n.get(_),O=n.get(u);return(!y||!O)&&D("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_UNKNOWN",`${r}/expression`),(y.type!=="option.single"||!["text.short","text.long"].includes(O.type)||!y.options?.some(h=>h.value===N))&&D("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_TYPES_INVALID",`${r}/expression`),{code:l,...p===void 0?{}:{message:p},expression:{kind:"nonBlankTextWhenOption",optionField:_,optionValue:N,textField:u}}}pe(d,["leftField","operator","rightField"],`${r}/expression`);let f=Ae(d.leftField,`${r}/expression/leftField`),g=Ae(d.rightField,`${r}/expression/rightField`),E=n.get(f),A=n.get(g);(!E||!A)&&D("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_UNKNOWN",`${r}/expression`),E.type===A.type||["number.integer","number.decimal"].includes(E.type)&&["number.integer","number.decimal"].includes(A.type)||D("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_TYPES_INVALID",`${r}/expression`);let I=String(d.operator);return["eq","neq","gt","gte","lt","lte"].includes(I)||D("NATIVE_DATA_RESOURCE_INVARIANT_OPERATOR_INVALID",`${r}/expression/operator`),!["eq","neq"].includes(I)&&!["number.integer","number.decimal","date","time","datetime","text.short","text.long","text.rich","serial-number","uuid"].includes(E.type)&&D("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_TYPES_INVALID",`${r}/expression`),{code:l,...p===void 0?{}:{message:p},expression:{leftField:f,operator:I,rightField:g}}})}function es(e,t,o,n){let i=o.get(e.resourceCode);i||D("NATIVE_DATA_FIELD_SOURCE_TARGET_MISSING",`${n}/resourceCode`);let s=new Map(i.fields.map(r=>[r.code,r])),a=s.get(e.labelField);(!a||!["text.short","text.long"].includes(a.type))&&D("NATIVE_DATA_FIELD_SOURCE_LABEL_INVALID",`${n}/labelField`);for(let r of["searchFields","descriptionFields","snapshotFields"])for(let c of e[r]||[])s.has(c)||D("NATIVE_DATA_FIELD_SOURCE_FIELD_MISSING",`${n}/${r}`);for(let[r,c]of(e.filters||[]).entries())s.has(c.field)||D("NATIVE_DATA_FIELD_SOURCE_FILTER_FIELD_MISSING",`${n}/filters/${r}/field`),"binding"in c&&!t.has(c.binding.field)&&D("NATIVE_DATA_FIELD_SOURCE_BINDING_FIELD_MISSING",`${n}/filters/${r}/binding/field`)}function ts(e,t,o){let n=`${o}/options`;if(e===void 0){to.has(t)&&D("NATIVE_DATA_FIELD_OPTIONS_REQUIRED",n);return}(!to.has(t)||!Array.isArray(e))&&D("NATIVE_DATA_FIELD_OPTIONS_TYPE_INVALID",n),(e.length<1||e.length>100)&&D("NATIVE_DATA_FIELD_OPTIONS_INVALID",n);let i=0,s=(a,r,c)=>{c>5&&D("NATIVE_DATA_FIELD_OPTIONS_DEPTH_EXCEEDED",r);let l=new Set;return a.map((p,d)=>{i+=1,i>1e3&&D("NATIVE_DATA_FIELD_OPTIONS_COUNT_EXCEEDED",n);let f=`${r}/${d}`,g=le(p,f);pe(g,["label","value","description","color","children"],f);let E=_e(g.label,`${f}/label`,500),A=_e(g.value,`${f}/value`,500);l.has(A)&&D("NATIVE_DATA_FIELD_OPTION_VALUE_DUPLICATE",`${f}/value`),l.add(A);let b=Nt(g.description,`${f}/description`,2e3),I=Nt(g.color,`${f}/color`,64),_;return g.children!==void 0&&((!t.startsWith("cascade.")||!Array.isArray(g.children))&&D("NATIVE_DATA_FIELD_OPTION_CHILDREN_INVALID",`${f}/children`),(g.children.length<1||g.children.length>100)&&D("NATIVE_DATA_FIELD_OPTION_CHILDREN_INVALID",`${f}/children`),_=s(g.children,`${f}/children`,c+1)),{label:E,value:A,...b===void 0?{}:{description:b},...I===void 0?{}:{color:I},..._?{children:_}:{}}})};return s(e,n,1)}function ns(e,t,o){let n=`${o}/source`;if(e===void 0){no.has(t)&&D("NATIVE_DATA_FIELD_SOURCE_REQUIRED",n);return}no.has(t)||D("NATIVE_DATA_FIELD_SOURCE_TYPE_INVALID",n);let i=le(e,n);pe(i,["kind","resourceCode","labelField","searchFields","descriptionFields","snapshotFields","filters","pageSize","loadMode"],n),i.kind!=="resource"&&D("NATIVE_DATA_FIELD_SOURCE_KIND_INVALID",`${n}/kind`);let s=_e(i.resourceCode,`${n}/resourceCode`,64);nn.test(s)||D("NATIVE_RESOURCE_CODE_INVALID",`${n}/resourceCode`);let a=Ae(i.labelField,`${n}/labelField`),r=en(i.searchFields,`${n}/searchFields`,10),c=en(i.descriptionFields,`${n}/descriptionFields`,10),l=en(i.snapshotFields,`${n}/snapshotFields`,50),p=Be(i.pageSize,`${n}/pageSize`,1,100),d;i.loadMode!==void 0&&(["search","all"].includes(String(i.loadMode))||D("NATIVE_DATA_FIELD_SOURCE_LOAD_MODE_INVALID",`${n}/loadMode`),d=i.loadMode);let f=os(i.filters,`${n}/filters`);return{kind:"resource",resourceCode:s,labelField:a,...r?{searchFields:r}:{},...c?{descriptionFields:c}:{},...l?{snapshotFields:l}:{},...f?{filters:f}:{},...p===void 0?{}:{pageSize:p},...d?{loadMode:d}:{}}}function os(e,t){if(e!==void 0)return(!Array.isArray(e)||e.length>20)&&D("NATIVE_DATA_FIELD_SOURCE_FILTERS_INVALID",t),e.map((o,n)=>{let i=`${t}/${n}`,s=le(o,i),a=Object.prototype.hasOwnProperty.call(s,"value"),r=Object.prototype.hasOwnProperty.call(s,"binding");pe(s,a?["field","operator","value"]:["field","operator","binding"],i),a===r&&D("NATIVE_DATA_FIELD_SOURCE_FILTER_VALUE_INVALID",i);let c=Ae(s.field,`${i}/field`);["eq","in"].includes(String(s.operator))||D("NATIVE_DATA_FIELD_SOURCE_FILTER_OPERATOR_INVALID",`${i}/operator`);let l=s.operator;if(a)return{field:c,operator:l,value:s.value};let p=le(s.binding,`${i}/binding`);return pe(p,["kind","field"],`${i}/binding`),p.kind!=="field"&&D("NATIVE_DATA_FIELD_SOURCE_BINDING_KIND_INVALID",`${i}/binding/kind`),{field:c,operator:l,binding:{kind:"field",field:Ae(p.field,`${i}/binding/field`)}}})}function is(e,t,o){let n={};if(e.maxLength!==void 0&&(["text.short","text.long","text.rich"].includes(t)||D("NATIVE_DATA_FIELD_MAX_LENGTH_TYPE_INVALID",`${o}/maxLength`),n.maxLength=yt(e.maxLength,`${o}/maxLength`,1,1e6)),(e.precision!==void 0||e.scale!==void 0)&&((t!=="number.decimal"||e.precision===void 0)&&D("NATIVE_DATA_FIELD_DECIMAL_CONFIG_INVALID",o),n.precision=yt(e.precision,`${o}/precision`,1,1e3),n.scale=e.scale===void 0?0:yt(e.scale,`${o}/scale`,0,n.precision)),e.min!==void 0||e.max!==void 0){["number.integer","number.decimal"].includes(t)||D("NATIVE_DATA_FIELD_NUMERIC_BOUNDS_TYPE_INVALID",o);let i=oo(e.min,`${o}/min`),s=oo(e.max,`${o}/max`);t==="number.integer"&&[i,s].some(a=>a!==void 0&&!Number.isSafeInteger(a))&&D("NATIVE_DATA_FIELD_NUMERIC_BOUNDS_INVALID",o),i!==void 0&&s!==void 0&&i>s&&D("NATIVE_DATA_FIELD_NUMERIC_BOUNDS_INVALID",o),i!==void 0&&(n.min=i),s!==void 0&&(n.max=s)}return e.timePrecision!==void 0&&((t!=="time"||!["minute","second"].includes(e.timePrecision))&&D("NATIVE_DATA_FIELD_TIME_PRECISION_INVALID",`${o}/timePrecision`),n.timePrecision=e.timePrecision),n}function ss(e,t,o){if(e===void 0)return;let n=`${o}/file`;["file","image","signature"].includes(t)||D("NATIVE_DATA_FIELD_FILE_TYPE_INVALID",n);let i=le(e,n);pe(i,["maxCount","maxSizeMb","accept"],n);let s=Be(i.maxCount,`${n}/maxCount`,1,100);t==="signature"&&s!==void 0&&s!==1&&D("NATIVE_DATA_FIELD_SIGNATURE_COUNT_INVALID",`${n}/maxCount`);let a=Be(i.maxSizeMb,`${n}/maxSizeMb`,1,1024),r;return i.accept!==void 0&&((!Array.isArray(i.accept)||i.accept.length>50)&&D("NATIVE_DATA_FIELD_FILE_ACCEPT_INVALID",`${n}/accept`),r=i.accept.map((c,l)=>_e(c,`${n}/accept/${l}`,255)),new Set(r).size!==r.length&&D("NATIVE_DATA_FIELD_FILE_ACCEPT_INVALID",`${n}/accept`)),{...s===void 0?{}:{maxCount:s},...a===void 0?{}:{maxSizeMb:a},...r===void 0?{}:{accept:r}}}function rs(e,t,o){let n=`${o}/serial`;if(e===void 0){t==="serial-number"&&D("NATIVE_DATA_FIELD_SERIAL_REQUIRED",n);return}t!=="serial-number"&&D("NATIVE_DATA_FIELD_SERIAL_TYPE_INVALID",n);let i=le(e,n);pe(i,["prefix","digits","start"],n);let s=Nt(i.prefix,`${n}/prefix`,64),a=Be(i.digits,`${n}/digits`,1,32),r=Be(i.start,`${n}/start`,0,Number.MAX_SAFE_INTEGER);return{...s===void 0?{}:{prefix:s},...a===void 0?{}:{digits:a},...r===void 0?{}:{start:r}}}function as(e,t,o){let n=`${o}/subtable`;if(e===void 0){t==="subtable"&&D("NATIVE_DATA_FIELD_SUBTABLE_REQUIRED",n);return}t!=="subtable"&&D("NATIVE_DATA_FIELD_SUBTABLE_TYPE_INVALID",n);let i=le(e,n);pe(i,["resourceCode","foreignKey","orderField","maxRows"],n);let s=_e(i.resourceCode,`${n}/resourceCode`,64);nn.test(s)||D("NATIVE_RESOURCE_CODE_INVALID",`${n}/resourceCode`);let a=Ae(i.foreignKey,`${n}/foreignKey`),r=Ae(i.orderField,`${n}/orderField`);r===a&&D("NATIVE_DATA_FIELD_SUBTABLE_ORDER_FIELD_INVALID",`${n}/orderField`);let c=Be(i.maxRows,`${n}/maxRows`,1,100);return{resourceCode:s,foreignKey:a,orderField:r,...c===void 0?{}:{maxRows:c}}}function en(e,t,o){if(e===void 0)return;(!Array.isArray(e)||e.length>o)&&D("NATIVE_DATA_FIELD_SOURCE_FIELDS_INVALID",t);let n=e.map((i,s)=>Ae(i,`${t}/${s}`));return new Set(n).size!==n.length&&D("NATIVE_DATA_FIELD_SOURCE_FIELDS_INVALID",t),n}function Ae(e,t){let o=_e(e,t,63);return io.test(o)||D("NATIVE_FIELD_CODE_INVALID",t),o}function le(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&D("NATIVE_OBJECT_REQUIRED",t),e}function pe(e,t,o){let n=new Set(t);for(let i of Object.keys(e))n.has(i)||D("NATIVE_PROPERTY_UNKNOWN",`${o}/${i}`)}function _e(e,t,o){return(typeof e!="string"||e.length===0||e.length>o)&&D("NATIVE_STRING_INVALID",t),e}function Nt(e,t,o){if(e!==void 0)return(typeof e!="string"||e.length>o)&&D("NATIVE_STRING_INVALID",t),e}function tn(e,t){if(e!==void 0)return typeof e!="boolean"&&D("NATIVE_BOOLEAN_REQUIRED",t),e}function Be(e,t,o,n){if(e!==void 0)return yt(e,t,o,n)}function oo(e,t){if(e!==void 0)return(typeof e!="number"||!Number.isFinite(e))&&D("NATIVE_NUMBER_REQUIRED",t),e}function yt(e,t,o,n){return(!Number.isSafeInteger(e)||Number(e)<o||Number(e)>n)&&D("NATIVE_INTEGER_OUT_OF_RANGE",t),Number(e)}function D(e,t){throw new Ee(e,t)}var lo=["created_by","updated_by","created_at","updated_at"];function Ze(e){return lo.includes(e)}function uo(e){return lo.some(t=>Object.prototype.hasOwnProperty.call(e.fieldPolicies||{},t))}var cs=on.map(e=>e.code);function fo(e){return cs.includes(e)}var ds=["eq","neq","gt","gte","lt","lte","contains","startsWith","endsWith","in","between","has","hasAny","hasAll","overlaps","containedBy","jsonContains","isEmpty","isNotEmpty"],ls=new Set(ds);function ja(e){return ls.has(String(e))}var rn=["eq","neq","contains","startsWith","endsWith","in","isEmpty","isNotEmpty"],et=["eq","neq","gt","gte","lt","lte","between","in","isEmpty"],us=["eq","neq","in","isEmpty"],ht=["eq","neq","in","isEmpty","isNotEmpty"],Ke=["has","hasAny","hasAll","isEmpty","isNotEmpty"],po=["overlaps","contains","containedBy","isEmpty"],an=["jsonContains","isEmpty","isNotEmpty"],cn=["isEmpty","isNotEmpty"],fs={"text.short":rn,"text.long":rn,"text.rich":rn,"number.integer":et,"number.decimal":et,boolean:us,date:et,time:et,datetime:et,"date-range":po,"datetime-range":po,"option.single":ht,"option.multiple":Ke,"cascade.single":Ke,"cascade.multiple":Ke,"user.single":ht,"user.multiple":Ke,"department.single":ht,"department.multiple":Ke,"resource-ref.single":ht,"resource-ref.multiple":Ke,file:cn,image:cn,signature:cn,address:an,location:an,uuid:["eq","neq","in","isEmpty"],json:an,"serial-number":["eq","neq","in","contains","startsWith"],subtable:[]},ps=new Set(["text.short","text.long","text.rich","option.single","user.single","department.single","resource-ref.single","serial-number"]),_s=new Set(["option.multiple","cascade.single","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","file","image","signature","address","location","json","subtable"]);function mo(e){return fs[e]}function Wa(e,t){return mo(e).includes(t)}function dn(e){return ps.has(e)}function tt(e){return!_s.has(e)}function go(e){return mo(e).length>0}var _o=new Set(["number.integer","number.decimal"]),Ao=new Set(["text.short","text.long","number.integer","number.decimal","date","time","datetime","serial-number"]),ms=new Set([...Ao,"boolean","uuid"]),gs=new Set(["option.single","user.single","department.single","resource-ref.single"]);function Ma(e,t){return t==="sum"||t==="avg"?_o.has(e)?{valueExpression:"column",numericResult:!0}:null:t==="min"||t==="max"?Ao.has(e)?{valueExpression:"column",numericResult:_o.has(e)}:null:gs.has(e)?{valueExpression:"snapshot-value",numericResult:!0}:ms.has(e)?{valueExpression:"column",numericResult:!0}:null}var un=["version","maxBytes","fields"];function Io(e,t){if(e===void 0)return;let o=ln(e,t);Eo(o,un,t);let n=Rt(o.version,`${t}/version`,1,1e6),i=Rt(o.maxBytes,`${t}/maxBytes`,2,196608);(!n||!i)&&re("NATIVE_DATA_DRAFT_STATE_SCHEMA_INVALID",t);let s=ln(o.fields,`${t}/fields`),a=Object.entries(s);(!a.length||a.length>50)&&re("NATIVE_DATA_DRAFT_STATE_FIELDS_INVALID",`${t}/fields`);for(let[r,c]of a){let l=`${t}/fields/${r}`;/^[A-Za-z][A-Za-z0-9_]{0,62}$/.test(r)||re("NATIVE_DATA_DRAFT_STATE_FIELD_CODE_INVALID",l);let p=ln(c,l),d=bo(p.type,`${l}/type`,32),f=d==="string"?["type","required","maxLength","enum"]:d==="json.object"?["type","required","maxBytes"]:["type","required"];if(["string","number","integer","boolean","json.object"].includes(d)||re("NATIVE_DATA_DRAFT_STATE_FIELD_TYPE_INVALID",`${l}/type`),Eo(p,f,l),Es(p.required,`${l}/required`),d==="string"){let g=Rt(p.maxLength,`${l}/maxLength`,1,196608);g||re("NATIVE_DATA_DRAFT_STATE_FIELD_INVALID",l),p.enum!==void 0&&As(p.enum,`${l}/enum`,100,!1).some(A=>A.length>g)&&re("NATIVE_DATA_DRAFT_STATE_FIELD_INVALID",`${l}/enum`)}else if(d==="json.object"){let g=Rt(p.maxBytes,`${l}/maxBytes`,2,65536);(!g||g>i)&&re("NATIVE_DATA_DRAFT_STATE_FIELD_INVALID",l)}}}function As(e,t,o,n){(!Array.isArray(e)||!n&&e.length===0||e.length>o)&&re("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t);let i=e.map((s,a)=>bo(s,`${t}/${a}`,255));return new Set(i).size!==i.length&&re("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t),i}function ln(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&re("NATIVE_OBJECT_REQUIRED",t),e}function Eo(e,t,o){let n=new Set(t);for(let i of Object.keys(e))n.has(i)||re("NATIVE_PROPERTY_UNKNOWN",`${o}/${i}`)}function bo(e,t,o){return(typeof e!="string"||e.length===0||e.length>o)&&re("NATIVE_STRING_INVALID",t),e}function Es(e,t){e!==void 0&&typeof e!="boolean"&&re("NATIVE_BOOLEAN_REQUIRED",t)}function Rt(e,t,o,n){return(!Number.isSafeInteger(e)||Number(e)<o||Number(e)>n)&&re("NATIVE_INTEGER_INVALID",t),Number(e)}function re(e,t){throw new Ee(e,t)}var Is=500,we={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:un,mobile:["enabled"]},bs={"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 _n(e,t,o){if(e===void 0)return;let n=ne(e,o);Ie(n,we.surface,o);let i=n.mutationOwner===void 0?"native":he(n.mutationOwner,`${o}/mutationOwner`,16);["native","action","readonly","workflow","queued-command"].includes(i)||x("NATIVE_DATA_SURFACE_MUTATION_OWNER_INVALID",`${o}/mutationOwner`);let s=n.generated===void 0?{}:ne(n.generated,`${o}/generated`);Ie(s,we.generated,`${o}/generated`);for(let c of we.generated)pn(s[c],`${o}/generated/${c}`);if(i!=="native")for(let c of["create","update","delete"])s[c]===!0&&x("NATIVE_DATA_SURFACE_MUTATION_OWNER_CONFLICT",`${o}/generated/${c}`);let a=new Map(t.map(c=>[c.code,c])),r=ne(n.fields,`${o}/fields`);for(let c of Object.keys(r))a.has(c)||x("NATIVE_DATA_SURFACE_FIELD_MISSING",`${o}/fields/${c}`);for(let c of t)Object.prototype.hasOwnProperty.call(r,c.code)||x("NATIVE_DATA_SURFACE_FIELD_REQUIRED",`${o}/fields/${c.code}`),Ns(r[c.code],c,`${o}/fields/${c.code}`);for(let c of["create","update"]){let l=s[c]??i==="native",p=t.some(d=>{let f=ne(r[d.code],`${o}/fields/${d.code}`);return No(d,f,c)});l&&!p&&x("NATIVE_DATA_SURFACE_WRITABLE_FIELDS_REQUIRED",`${o}/generated/${c}`)}if(Ts(n.list,a,`${o}/list`),yo(n.form,a,`${o}/form`,"form"),yo(n.detail,a,`${o}/detail`,"detail"),n.mobile!==void 0){let c=ne(n.mobile,`${o}/mobile`);Ie(c,we.mobile,`${o}/mobile`),pn(c.enabled,`${o}/mobile/enabled`)}ys(n,t,o)}function mn(e,t){let o=e.views?.find(i=>i.code===t);o||x("NATIVE_DATA_VIEW_NOT_FOUND",`/surface/views/${t}`);let n=new Map((o.sections||[]).flatMap(i=>i.fields.map(s=>[s,i.title])));return{mutationOwner:e.mutationOwner||"native",generated:o.generated,list:o.list,form:o.form,detail:o.detail,mobile:o.mobile,fields:Object.fromEntries(Object.entries(e.fields).map(([i,s])=>{let a={...s};delete a.section;let r=n.get(i);return[i,{...a,...r?{section:r}:{},list:o.list.fieldOrder.includes(i)}]}))}}function ys(e,t,o){if(e.views===void 0)return;(!Array.isArray(e.views)||e.views.length>20)&&x("NATIVE_DATA_VIEWS_LIMIT_INVALID",`${o}/views`);let n=new Set;e.views.forEach((i,s)=>{let a=`${o}/views/${s}`,r=ne(i,a);Ie(r,["code","name","generated","list","form","detail","mobile","sections"],a);let c=he(r.code,`${a}/code`,64);(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(c)||n.has(c))&&x("NATIVE_DATA_VIEW_CODE_INVALID",`${a}/code`),n.add(c),he(r.name,`${a}/name`,255),ne(r.generated,`${a}/generated`),ne(r.mobile,`${a}/mobile`);for(let p of["list","detail","create","update","delete"])typeof r.generated[p]!="boolean"&&x("NATIVE_DATA_VIEW_OPERATION_INVALID",`${a}/generated/${p}`);typeof r.mobile.enabled!="boolean"&&x("NATIVE_DATA_VIEW_MOBILE_INVALID",`${a}/mobile/enabled`);for(let p of["list","form","detail"]){let d=ne(r[p],`${a}/${p}`),f=Ge(d.fieldOrder,`${a}/${p}/fieldOrder`,500,!0);for(let g of f){let E=e.fields[g];(!E||(E.hidden??E.system)===!0)&&x("NATIVE_DATA_VIEW_FIELD_INVALID",`${a}/${p}/fieldOrder`)}}if(r.sections!==void 0){(!Array.isArray(r.sections)||r.sections.length>100)&&x("NATIVE_DATA_VIEW_SECTIONS_INVALID",`${a}/sections`);let p=new Set;r.sections.forEach((d,f)=>{let g=`${a}/sections/${f}`,E=ne(d,g);Ie(E,["title","fields"],g),he(E.title,`${g}/title`,255);for(let A of Ge(E.fields,`${g}/fields`,100,!0)){let b=e.fields[A];(!b||(b.hidden??b.system)===!0||p.has(A))&&x("NATIVE_DATA_VIEW_FIELD_INVALID",`${g}/fields`),p.add(A)}})}let l=mn(e,c);if(_n(l,t,a),r.generated.create!==!1&&(e.mutationOwner||"native")==="native")for(let p of t)Ot(p,e.fields[p.code])&&No(p,e.fields[p.code],"create")&&!r.form.fieldOrder.includes(p.code)&&x("NATIVE_DATA_VIEW_CREATE_REQUIRED_FIELD_MISSING",`${a}/form/fieldOrder`)})}function No(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 Ns(e,t,o){let n=ne(e,o);Ie(n,we.field,o),he(n.label,`${o}/label`,500),n.type!==t.type&&x("NATIVE_DATA_SURFACE_FIELD_TYPE_MISMATCH",`${o}/type`);let i=he(n.widget,`${o}/widget`,64);bs[t.type].includes(i)||x("NATIVE_DATA_SURFACE_WIDGET_INCOMPATIBLE",`${o}/widget`),Rs(n.section,`${o}/section`,255);for(let s of["requiredHint","system","hidden","list","searchable","sortable"])pn(n[s],`${o}/${s}`);n.searchable===!0&&!dn(t.type)&&x("NATIVE_DATA_SURFACE_SEARCH_UNSUPPORTED",`${o}/searchable`),n.sortable===!0&&!tt(t.type)&&x("NATIVE_DATA_SURFACE_SORT_UNSUPPORTED",`${o}/sortable`);for(let s of["readCapabilities","createCapabilities","updateCapabilities"])Ge(n[s],`${o}/${s}`,100,!0);if(n.maxCount!==void 0&&(!Number.isSafeInteger(n.maxCount)||Number(n.maxCount)<1||Number(n.maxCount)>100)&&x("NATIVE_DATA_SURFACE_MAX_COUNT_INVALID",`${o}/maxCount`),n.maxSizeMb!==void 0&&(!Number.isSafeInteger(n.maxSizeMb)||Number(n.maxSizeMb)<1||Number(n.maxSizeMb)>1024)&&x("NATIVE_DATA_SURFACE_MAX_SIZE_INVALID",`${o}/maxSizeMb`),n.accept!==void 0){let s=Array.isArray(n.accept)?n.accept:[n.accept];Ge(s,`${o}/accept`,50,!1)}for(let s of["maxLength","precision","scale","exactDecimal","min","max","rangeBoundary","options","source","timePrecision","serial","subtable"])Os(n,t,s,o);hs(n,t,o)}function Ts(e,t,o){if(e===void 0)return;let n=ne(e,o);if(Ie(n,we.list,o),n.actions!==void 0){let i=ne(n.actions,`${o}/actions`);Ie(i,["import","export"],`${o}/actions`);for(let s of["import","export"])i[s]!==void 0&&typeof i[s]!="boolean"&&x("NATIVE_DATA_SURFACE_LIST_ACTION_INVALID",`${o}/actions/${s}`)}if(n.fieldOrder!==void 0)for(let i of Ge(n.fieldOrder,`${o}/fieldOrder`,500,!0))t.has(i)||x("NATIVE_DATA_SURFACE_LIST_FIELD_INVALID",`${o}/fieldOrder`);n.defaultPageSize!==void 0&&(!Number.isSafeInteger(n.defaultPageSize)||Number(n.defaultPageSize)<1||Number(n.defaultPageSize)>200)&&x("NATIVE_DATA_SURFACE_PAGE_SIZE_INVALID",`${o}/defaultPageSize`);for(let[i,s]of[["searchableFields",dn],["filterFields",go]]){if(n[i]===void 0)continue;let a=Ge(n[i],`${o}/${i}`,100,!0);for(let r of a){let c=t.get(r);(!c||!s(c.type))&&x("NATIVE_DATA_SURFACE_LIST_FIELD_INVALID",`${o}/${i}`)}}if(n.defaultSort!==void 0){let i=ne(n.defaultSort,`${o}/defaultSort`);Ie(i,we.defaultSort,`${o}/defaultSort`);let s=he(i.field,`${o}/defaultSort/field`,63),a=t.get(s);!fo(s)&&(!a||!tt(a.type))&&x("NATIVE_DATA_SURFACE_SORT_UNSUPPORTED",`${o}/defaultSort/field`),i.order!==void 0&&!["asc","desc"].includes(i.order)&&x("NATIVE_DATA_SURFACE_SORT_ORDER_INVALID",`${o}/defaultSort/order`)}}function yo(e,t,o,n){if(e===void 0)return;let i=ne(e,o);if(Ie(i,we[n],o),i.layout!==void 0&&!["flat","sections"].includes(i.layout)&&x("NATIVE_DATA_SURFACE_LAYOUT_INVALID",`${o}/layout`),i.fieldOrder!==void 0){let s=`${o}/fieldOrder`;(!Array.isArray(i.fieldOrder)||i.fieldOrder.length>t.size||i.fieldOrder.length>Is)&&x("NATIVE_DATA_SURFACE_FIELD_ORDER_INVALID",s);let a=i.fieldOrder.map((r,c)=>he(r,`${s}/${c}`,63));new Set(a).size!==a.length&&x("NATIVE_DATA_SURFACE_FIELD_ORDER_INVALID",s),a.forEach((r,c)=>{t.has(r)||x("NATIVE_DATA_SURFACE_FIELD_ORDER_FIELD_MISSING",`${s}/${c}`)})}n==="form"&&Io(i.draftState,`${o}/draftState`)}function Os(e,t,o,n){e[o]===void 0&&t[o]===void 0||((e[o]===void 0||t[o]===void 0)&&x("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${n}/${o}`),ee(e[o])!==ee(t[o])&&x("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${n}/${o}`))}function hs(e,t,o){let n=t.file||{},i={...e.maxCount===void 0?{}:{maxCount:e.maxCount},...e.maxSizeMb===void 0?{}:{maxSizeMb:e.maxSizeMb},...e.accept===void 0?{}:{accept:fn(e.accept)}};for(let s of["maxCount","maxSizeMb","accept"]){if(i[s]===void 0&&n[s]===void 0)continue;(i[s]===void 0||n[s]===void 0)&&x("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${o}/${s}`);let a=s==="accept"?fn(i[s]):i[s],r=s==="accept"?fn(n[s]):n[s];ee(a)!==ee(r)&&x("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${o}/${s}`)}}function fn(e){return(Array.isArray(e)?[...e]:[e]).sort((t,o)=>{let n=String(t),i=String(o);return n===i?0:n<i?-1:1})}function Ge(e,t,o,n){(!Array.isArray(e)||!n&&e.length===0||e.length>o)&&x("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t);let i=e.map((s,a)=>he(s,`${t}/${a}`,255));return new Set(i).size!==i.length&&x("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t),i}function ne(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&x("NATIVE_OBJECT_REQUIRED",t),e}function Ie(e,t,o){let n=new Set(t);for(let i of Object.keys(e))n.has(i)||x("NATIVE_PROPERTY_UNKNOWN",`${o}/${i}`)}function he(e,t,o){return(typeof e!="string"||e.length===0||e.length>o)&&x("NATIVE_STRING_INVALID",t),e}function Rs(e,t,o){e!==void 0&&(typeof e!="string"||e.length>o)&&x("NATIVE_STRING_INVALID",t)}function pn(e,t){e!==void 0&&typeof e!="boolean"&&x("NATIVE_BOOLEAN_REQUIRED",t)}function x(e,t){throw new Ee(e,t)}var nt=class extends Error{constructor(o,n){super(`${o}: ${n}`);this.pointer=o;this.reason=n}pointer;reason;code="NATIVE_MANAGED_CONCURRENCY_INVALID"};function To(e,t,o){if(e===void 0)return;let n=(_,u)=>{throw new nt(_,u)},i=(_,u,N)=>((!_||typeof _!="object"||Array.isArray(_)||Object.keys(_).some(y=>!N.includes(y)))&&n(u,"object contains unsupported properties"),_),s=(_,u,N,y)=>{(!Number.isSafeInteger(_)||_<u||_>N)&&n(y,`expected integer ${u}..${N}`)},a=(_,u)=>{(typeof _!="string"||!/^[a-z][a-z0-9_-]{0,63}$/.test(_))&&n(u,"invalid code")},r=(_,u,N)=>((!Array.isArray(_)||_.length>u)&&n(N,"array exceeds bound"),_),c=(_,u)=>{let N=t.find(y=>y.code===_);return N||n(u,"unknown resource"),N},l=(_,u,N)=>{let y=_.schema.fields.find(O=>O.code===u);return!y&&u!=="id"&&n(N,"unknown field"),y},p=(_,u,N=!1)=>{i(_,u,Object.keys(_||{})),Object.keys(_).length>8&&n(u,"at most eight parameters");for(let[y,O]of Object.entries(_))if(a(y,u),i(O,u,["type","values","minimum","maximum","minLength","maxLength"]),O.type==="uuid")Object.keys(O).length!==1&&n(u,"uuid has no options");else if(N&&O.type==="boolean")i(O,u,["type"]);else if(N&&O.type==="string"&&O.values===void 0)i(O,u,["type","minLength","maxLength"]),s(O.maxLength,1,256,u),O.minLength!==void 0&&s(O.minLength,0,O.maxLength,u);else if(O.type==="string"){i(O,u,["type","values"]);let h=r(O.values,100,u);(!h.length||h.some(C=>typeof C!="string"||C.length>128)||new Set(h).size!==h.length)&&n(u,"finite string values required")}else O.type==="integer"?(i(O,u,["type","minimum","maximum"]),s(O.minimum,0,1e6,u),s(O.maximum,O.minimum,O.minimum+1e3,u)):n(u,"unsupported parameter type")},d=(_,u,N,y=!1)=>{i(_,N,["from","key","value"]),!(_.from==="input"&&Object.keys(_).length===2&&Object.hasOwn(u,_.key))&&((_.from==="actor"||y&&_.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(N,"invalid binding"))},f=(_,u,N)=>{d(_,u,N),!(_.from==="input"&&u[_.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(N,"record and allocation identifiers require a UUID binding"))},g=(_,u,N)=>{d(_,u,N),!(_.from==="input"&&u[_.key].type==="integer"&&u[_.key].minimum>=1)&&(_.from==="literal"&&Number.isSafeInteger(_.value)&&_.value>=1||n(N,"expectedRevision requires a positive integer binding"))},E="/data/concurrency";JSON.stringify(e).length>131072&&n(E,"declaration exceeds 128 KiB");let A=i(e,E,["version","admission","reads","quotas","commands"]);A.version!==1&&n(E,"unsupported version"),i(A.admission,E,["perSecond","burst","maxInFlight"]),s(A.admission.perSecond,1,1e3,E),s(A.admission.burst,1,1e3,E),s(A.admission.maxInFlight,1,1e3,E);let b=(_,u)=>{let N=new Set;for(let y of _)a(y?.code,u),N.has(y.code)&&n(u,"duplicate code"),N.add(y.code)};b(r(A.reads,32,E),E),b(r(A.quotas,16,E),E),b(r(A.commands,32,E),E);for(let _ of A.reads){let u=`${E}/reads/${_.code}`;i(_,u,["code","resourceCode","parameters","select","where","limit","scope","freshSeconds","staleSeconds","maxKeys","sourcePerSecond","dependencies"]);let N=c(_.resourceCode,u);p(_.parameters,u),["subject","application"].includes(_.scope)||n(u,"invalid cache scope"),_.scope==="application"&&N.dataPolicyCode&&n(u,"shared cache cannot bypass a row policy");let y=r(_.select,32,u);y.length||n(u,"select required"),y.forEach(h=>l(N,h,u));let O=r(_.dependencies,64,u);O.forEach(h=>l(N,h,u));for(let h of r(_.where||[],8,u))i(h,u,["field","value"]),l(N,h.field,u),d(h.value,_.parameters,u),_.scope==="application"&&h.value.from==="actor"&&n(u,"actor requires subject cache"),O.includes(h.field)||n(u,"filter dependency missing");y.some(h=>!O.includes(h))&&n(u,"selected field dependency missing"),s(_.limit,1,100,u),s(_.freshSeconds,1,300,u),s(_.staleSeconds,0,300,u),s(_.maxKeys,1,1e4,u),s(_.sourcePerSecond,1,20,u)}for(let _ of A.quotas){let u=`${E}/quotas/${_.code}`;i(_,u,["code","sourceResource","capacityField","allocationResource","allocationField","reservationSeconds"]);let N=c(_.sourceResource,u),y=c(_.allocationResource,u);l(N,_.capacityField,u)?.type!=="number.integer"&&n(u,"capacity must be an integer"),(l(y,_.allocationField,u)?.type!=="uuid"||l(y,_.allocationField,u)?.nullable!==!1)&&n(u,"allocation reference must be a uuid"),y.surface?.mutationOwner!=="queued-command"&&n(u,"allocation model must be command owned"),_.reservationSeconds!==void 0&&s(_.reservationSeconds,10,86400,u)}new Set(A.quotas.map(_=>_.allocationResource)).size!==A.quotas.length&&n(E,"an allocation model has exactly one pool owner");for(let _ of A.commands){let u=`${E}/commands/${_.code}`;i(_,u,["code","mode","intake","execution","capability","parameters","resourceKey","admission","deadlineSeconds","guards","operations","quota"]),_.mode!==void 0&&!["permit","durable"].includes(_.mode)&&n(u,"unsupported mode");let N=_.mode==="durable";if(p(_.parameters,u,N),d(_.resourceKey,_.parameters,u),o.some(y=>y.code===_.capability)||n(u,"command capability must be declared"),i(_.admission,u,["perSecond","burst","maxInFlight","maxQueue","maxWaitSeconds","permitSeconds"]),s(_.admission.perSecond,1,A.admission.perSecond,u),s(_.admission.burst,1,A.admission.burst,u),s(_.admission.maxInFlight,1,A.admission.maxInFlight,u),s(_.admission.maxQueue,1,1e4,u),s(_.admission.maxWaitSeconds,1,3600,u),(!N||_.admission.permitSeconds!==void 0)&&s(_.admission.permitSeconds,5,60,u),s(_.deadlineSeconds,10,3600,u),N){(_.operations!==void 0||_.guards!==void 0||_.quota!==void 0)&&n(u,"backend-plan does not accept static operations, guards or quota"),i(_.intake,u,["perSecond","burst","maxInFlight"]);for(let h of["perSecond","burst","maxInFlight"])s(_.intake[h],1,1e3,u);let y=i(_.execution,u,["kind","handlerCode","timeoutMs","resources","directory"]);y.kind!=="backend-plan"&&n(u,"durable requires backend-plan"),a(y.handlerCode,u),s(y.timeoutMs,100,3e4,u);let O=r(y.resources,32,u);O.length||n(u,"execution resources required"),new Set(O.map(h=>h.resourceCode)).size!==O.length&&n(u,"duplicate execution resource");for(let h of O){i(h,u,["resourceCode","readFields","writeOperations","writeFields"]);let C=c(h.resourceCode,u);for(let V of["readFields","writeFields"]){let M=r(h[V],64,u);new Set(M).size!==M.length&&n(u,"duplicate field"),M.forEach(P=>{V==="readFields"&&ro.has(P)||l(C,P,u)})}let k=r(h.writeOperations,3,u);(new Set(k).size!==k.length||k.some(V=>!["create","update","increment"].includes(V)))&&n(u,"unsupported execution operation"),h.writeFields.some(V=>["id","revision","created_by","updated_by","created_at","updated_at"].includes(V))&&n(u,"record metadata is platform owned"),!k.length&&h.writeFields.length&&n(u,"write fields require an operation"),k.length&&!h.writeFields.length&&n(u,"write operations require fields"),A.quotas.some(V=>V.allocationResource===h.resourceCode)&&k.length&&n(u,"allocation references remain owned by their pool command")}if(y.directory!==void 0){i(y.directory,u,["mode","fields"]),y.directory.mode!=="current-initiator"&&n(u,"only current initiator allowed");let h=r(y.directory.fields,4,u);(!h.length||new Set(h).size!==h.length||h.some(C=>!["displayName","employeeNumber","primaryDepartment","departments"].includes(C)))&&n(u,"unsupported directory fields")}continue}(_.execution!==void 0||_.intake!==void 0)&&n(u,"execution and intake require durable mode");for(let y of r(_.guards||[],8,u)){i(y,u,["resourceCode","id","conditions"]);let O=c(y.resourceCode,u);f(y.id,_.parameters,u);for(let h of r(y.conditions,16,u)){i(h,u,["kind","field","operator","value"]);let C=l(O,h.field,u);["eq","neq","lt","lte","gt","gte"].includes(h.operator)||n(u,"unsupported guard"),h.kind==="database-now"?(C?.type!=="datetime"||!["lt","lte","gt","gte"].includes(h.operator)||h.value!==void 0)&&n(u,"database-now requires datetime and an ordering operator"):(h.kind!==void 0&&h.kind!=="value"&&n(u,"unsupported condition kind"),d(h.value,_.parameters,u))}}for(let y of r(_.operations,8,u)){i(y,u,["operation","resourceCode","id","expectedRevision","data"]);let O=c(y.resourceCode,u);O.surface?.mutationOwner!=="queued-command"&&n(u,"command mutations require command owned models");let h=A.quotas.find(C=>C.allocationResource===y.resourceCode);h&&(y.operation==="create"?_.quota?.action!=="allocate"||_.quota.pool!==h.code:Object.hasOwn(y.data||{},h.allocationField))&&n(u,"allocation references are owned by their pool command"),["create","update"].includes(y.operation)||n(u,"unsupported operation"),y.operation==="update"?(f(y.id,_.parameters,u),g(y.expectedRevision,_.parameters,u)):(y.id!==void 0||y.expectedRevision!==void 0)&&n(u,"create has no caller supplied id/revision"),i(y.data,u,Object.keys(y.data||{})),Object.keys(y.data).length>32&&n(u,"too many fields");for(let[C,k]of Object.entries(y.data))C==="id"&&n(u,"record identifiers are platform owned"),l(O,C,u),d(k,_.parameters,u,_.quota?.action==="allocate")}if(_.quota){let y=i(_.quota,u,["pool","action","units","mode","allocation"]),O=A.quotas.find(h=>h.code===y.pool);O||n(u,"unknown quota pool"),f(_.resourceKey,_.parameters,u),y.action==="allocate"?(i(y,u,["pool","action","units","mode"]),s(y.units,1,1e3,u),(!["committed","reserved"].includes(y.mode)||y.mode==="reserved"&&!O.reservationSeconds)&&n(u,"invalid allocation mode"),(_.operations.length!==1||_.operations[0].operation!=="create"||_.operations[0].resourceCode!==O.allocationResource||_.operations[0].data[O.allocationField]?.from!=="allocation")&&n(u,"allocation must atomically create its bound business record")):["confirm","release"].includes(y.action)?(i(y,u,["pool","action","allocation"]),f(y.allocation,_.parameters,u),_.operations.length&&n(u,"lifecycle owns allocation state; business reference remains immutable")):n(u,"invalid quota action")}else _.operations.length||n(u,"operations required")}let I=A.commands.filter(_=>_.mode==="durable").map(_=>_.execution.handlerCode);return new Set(I).size!==I.length&&n(E,"handler code must be unique"),JSON.parse(JSON.stringify(A))}var qe=class extends Error{constructor(o,n){super(`\u91D1\u989D\u751F\u547D\u5468\u671F\u58F0\u660E\u65E0\u6548\uFF1A${n}\uFF08${o}\uFF09`);this.pointer=o;this.reason=n}pointer;reason;code="NATIVE_DECIMAL_LIFECYCLE_INVALID"},En=["parentTransitions","childTransitions","fulfilledChildStatuses","lockedParentStatuses"],Oo=["amountFieldCode","currencyFieldCode","relationFieldCode","parentFieldCode","rootFieldCode","statusFieldCode","parentRelationValue","childRelationValue"],St=e=>!!(e&&typeof e=="object"&&!Array.isArray(e)),Ct=e=>Array.isArray(e)?e.filter(St):[],be=(e,t)=>{throw new qe(e,t)},gn=e=>typeof e=="string"&&/^[A-Za-z0-9._:-]{1,128}$/.test(e),An=(e,t)=>e<t?-1:e>t?1:0;function In(e,t="/decimalReservationLifecycle"){if(e===void 0)return;if(!St(e)||Object.keys(e).some(i=>!En.includes(i))||En.some(i=>!Object.prototype.hasOwnProperty.call(e,i)))return be(t,"\u5FC5\u987B\u5B8C\u6574\u58F0\u660E\u56DB\u9879\u89C4\u5219\uFF0C\u4E0D\u80FD\u5305\u542B\u672A\u77E5\u5C5E\u6027");let o=i=>{let s=e[i];if(!Array.isArray(s)||s.length>64)return be(`${t}/${i}`,"\u72B6\u6001\u8FB9\u6700\u591A 64 \u6761");let a=new Set;return s.map((r,c)=>{let l=`${t}/${i}/${c}`;if(!St(r)||Object.keys(r).some(d=>d!=="from"&&d!=="to")||!gn(r.from)||!gn(r.to)||r.from===r.to)return be(l,"\u72B6\u6001\u8FB9\u5FC5\u987B\u5305\u542B\u4E0D\u540C\u7684\u6709\u6548 from/to");let p=JSON.stringify([r.from,r.to]);return a.has(p)?be(l,"\u72B6\u6001\u8FB9\u4E0D\u80FD\u91CD\u590D"):(a.add(p),{from:r.from,to:r.to})}).sort((r,c)=>An(r.from,c.from)||An(r.to,c.to))},n=i=>{let s=e[i];return!Array.isArray(s)||s.length<1||s.length>16||s.some(a=>!gn(a))||new Set(s).size!==s.length?be(`${t}/${i}`,"\u72B6\u6001\u96C6\u5408\u5FC5\u987B\u5305\u542B 1 \u5230 16 \u4E2A\u4E0D\u91CD\u590D\u7684\u6709\u6548\u72B6\u6001"):[...s].sort(An)};return{parentTransitions:o("parentTransitions"),childTransitions:o("childTransitions"),fulfilledChildStatuses:n("fulfilledChildStatuses"),lockedParentStatuses:n("lockedParentStatuses")}}function ho(e,t,o="/config/data/resources"){Ct(e).forEach((n,i)=>{let s=`${o}/${i}/decimalReservationLifecycle`,a=In(n.decimalReservationLifecycle,s);if(!a)return;let r=Ct(t).map(d=>d.platformAccess?.decimalReservation).filter(d=>St(d)&&d.resourceCode===n.code),c=r.find(d=>d.mode==="reserve");if(!c)return be(s,"\u9700\u8981\u540C\u8D44\u6E90\u5DF2\u58F0\u660E\u7684 reserve \u52A8\u4F5C\u6620\u5C04");if(Oo.some(d=>typeof c[d]!="string")||r.some(d=>Oo.some(f=>d[f]!==c[f])))return be(s,"\u540C\u8D44\u6E90\u989D\u5EA6\u52A8\u4F5C\u7684\u5B57\u6BB5\u6620\u5C04\u5FC5\u987B\u4E00\u81F4");let l=Ct(n.schema?.fields).find(d=>d.code===c.statusFieldCode);if(l?.type!=="option.single")return be(s,"\u989D\u5EA6\u72B6\u6001\u5B57\u6BB5\u5FC5\u987B\u4E3A option.single");let p=new Set(Ct(l.options).map(d=>d.value));for(let d of En)if((d==="parentTransitions"||d==="childTransitions"?a[d].flatMap(g=>[g.from,g.to]):a[d]).some(g=>!p.has(g)))return be(`${s}/${d}`,"\u72B6\u6001\u5FC5\u987B\u6765\u81EA\u989D\u5EA6\u72B6\u6001\u5B57\u6BB5\u7684\u9009\u9879");if(r.some(d=>d.mode==="reserve"&&Array.isArray(d.eligibleParentStatuses)&&d.eligibleParentStatuses.some(f=>a.lockedParentStatuses.includes(String(f)))))return be(`${s}/lockedParentStatuses`,"\u9501\u5B9A\u7236\u72B6\u6001\u4E0D\u80FD\u5141\u8BB8\u65B0\u9884\u7559")})}import{createHash as Cs}from"crypto";var bn=new Set(["option.single","user.single","department.single","resource-ref.single"]),Ss=new Set(["option.multiple","cascade.single","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","address","location","json"]),Co=new Set(["option.multiple","cascade.single","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","file","image"]),ws=new Set(["option.single","user.single","department.single","resource-ref.single","signature","address","location"]),Ds=new Set([...bn,...Co,"signature","address","location","json"]);function rc(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=>$s(n,o.has(n.code))).sort((n,i)=>n.code.localeCompare(i.code))}function $s(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:Fs(e),index:Vs(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 ac(e,t){if(t.type==="subtable")return null;let o=ae(t.code),n=So(e,t),i=[n?` DEFAULT ${n}`:"",vs(o,t),ks(o,t)].join("");return`${o} ${t.storage}${i}`}function cc(e,t){return So(e,t)}function ks(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 dc(e){return e.type==="serial-number"||Tt(e.type)&&e.type!=="subtable"}function lc(e,t){return t.filter(o=>o.type==="serial-number").map(o=>{let n=Dt(e,o.code),i=o.serial?.start??1;return`CREATE SEQUENCE IF NOT EXISTS ${n} AS bigint MINVALUE ${i} START WITH ${i} CACHE 1`})}function uc(e,t){let o=wt(e);return t.filter(n=>n.type==="serial-number").map(n=>`ALTER SEQUENCE ${Dt(e,n.code)} OWNED BY ${o}.${ae(n.code)}`)}function fc(e,t){return t.filter(o=>o.type==="serial-number").map(o=>`GRANT USAGE, SELECT ON SEQUENCE ${Dt(e,o.code)} TO "openxiangda_data_api"`)}function pc(e,t){let o=wt(e),n=[];for(let i of t){if(i.type==="subtable")continue;let s=ae(i.code),a=ae(De("idx",e,i.code,i.index));switch(i.index){case"btree":n.push(`CREATE INDEX IF NOT EXISTS ${a} ON ${o} (${s})`);break;case"btree-snapshot-expressions":{let r=ae(De("idx",e,i.code,"snapshot-value")),c=ae(De("idx",e,i.code,"snapshot-label"));n.push(`CREATE INDEX IF NOT EXISTS ${r} ON ${o} ((${s} ->> 'value'))`,`CREATE INDEX IF NOT EXISTS ${c} ON ${o} ((${s} ->> 'label'))`);break}case"gin-jsonb-path":n.push(`CREATE INDEX IF NOT EXISTS ${a} ON ${o} USING GIN (${s} jsonb_path_ops)`);break;case"gist-range":n.push(`CREATE INDEX IF NOT EXISTS ${a} ON ${o} USING GIST (${s})`);break;case"gin-trigram":{let r=bn.has(i.type)?`((${s} ->> 'label')) gin_trgm_ops`:`${s} gin_trgm_ops`;n.push(`CREATE INDEX IF NOT EXISTS ${a} ON ${o} USING GIN (${r})`);break}case"none":break}if(i.type==="serial-number"){let r=ae(De("uidx",e,i.code,"serial"));n.push(`CREATE UNIQUE INDEX IF NOT EXISTS ${r} ON ${o} (${s})`)}}return n}function _c(e,t,o,n){let i=wt(e),s=wt(t),a=ae(De("uidx",e,"environment_id","subtable-parent")),r=ae(De("idx",t,o,n,"subtable-child")),c=ae(De("fk",t,o,e)),l=ae(o),p=ae(n);return[`CREATE UNIQUE INDEX IF NOT EXISTS ${a} ON ${i} ("tenant_id", "app_code", "environment_key", "id")`,`CREATE INDEX IF NOT EXISTS ${r} ON ${s} ("tenant_id", "app_code", "environment_key", ${l}, ${p}, "id")`,`DO $native_subtable$ BEGIN
|
|
2
|
-
ALTER TABLE ${
|
|
3
|
-
ADD CONSTRAINT ${
|
|
4
|
-
FOREIGN KEY ("tenant_id", "app_code", "environment_key", ${
|
|
1
|
+
import{createHash as us}from"node:crypto";function fs(e){if(!e||typeof e!="object")return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function bn(e,t){if(e===null)return"null";if(typeof e=="string"||typeof e=="boolean")return JSON.stringify(e);if(typeof e=="number"){if(!Number.isFinite(e))throw new TypeError(`JSON number must be finite: ${t}`);return JSON.stringify(e)}if(Array.isArray(e))return`[${e.map((n,i)=>bn(n,`${t}[${i}]`)).join(",")}]`;if(fs(e))return`{${Object.keys(e).filter(i=>e[i]!==void 0).sort((i,r)=>i===r?0:i<r?-1:1).map(i=>`${JSON.stringify(i)}:${bn(e[i],`${t}.${i}`)}`).join(",")}}`;let o=e instanceof Date?"Date":e?.constructor?.name||typeof e;throw new TypeError(`Value is not JSON serializable: ${t} (${o})`)}function Q(e){return bn(e,"$")}function Z(e){return us("sha256").update(Q(e)).digest("hex")}var fd=200,ps=["text.short","uuid","option.single","resource-ref.single"],On=/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/,Uo=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,Mo=new Set(["__proto__","prototype","constructor"]),Nn=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&[Object.prototype,null].includes(Object.getPrototypeOf(e)),Wo=(e,t)=>Object.keys(e).every(o=>t.includes(o)),Ze=(e,t)=>typeof e=="string"&&e.length>0&&e.trim()===e&&e.length<=t,Ue=class extends Error{constructor(o,n){super(`${o}: ${n}`);this.code=o;this.pointer=n}code;pointer};function te(e,t){throw new Ue(e,t)}function vt(e,t,o){if(e===void 0)return;["user.single","user.multiple"].includes(t)||te("DATA_USER_CANDIDATES_FIELD_TYPE_INVALID",o),(!Nn(e)||!Wo(e,["kind","roleCode","scope","pageSize"])||e.kind!=="app-role"||!Ze(e.roleCode,128)||!On.test(String(e.roleCode)))&&te("DATA_USER_CANDIDATES_SOURCE_INVALID",o),e.pageSize!==void 0&&(!Number.isSafeInteger(e.pageSize)||Number(e.pageSize)<1||Number(e.pageSize)>50)&&te("DATA_USER_CANDIDATES_PAGE_SIZE_INVALID",`${o}/pageSize`);let n;if(e.scope!==void 0){let i=e.scope;(!Nn(i)||!Wo(i,["dimensionCode","operation","field","value","creation"])||!Ze(i.dimensionCode,128)||!On.test(String(i.dimensionCode))||!Ze(i.operation,64)||!On.test(String(i.operation))||Object.hasOwn(i,"field")===Object.hasOwn(i,"value"))&&te("DATA_USER_CANDIDATES_SCOPE_INVALID",`${o}/scope`),i.creation!==void 0&&(i.creation!=="prospective"||!Object.hasOwn(i,"field"))&&te("DATA_USER_CANDIDATES_SCOPE_INVALID",`${o}/scope/creation`),Object.hasOwn(i,"field")?((!Ze(i.field,63)||!Uo.test(String(i.field))||Mo.has(String(i.field)))&&te("DATA_USER_CANDIDATES_SCOPE_FIELD_INVALID",`${o}/scope/field`),n={dimensionCode:String(i.dimensionCode),operation:String(i.operation),field:String(i.field),...i.creation==="prospective"?{creation:"prospective"}:{}}):(Ze(i.value,255)||te("DATA_USER_CANDIDATES_SCOPE_VALUE_INVALID",`${o}/scope/value`),n={dimensionCode:String(i.dimensionCode),operation:String(i.operation),value:String(i.value)})}return{kind:"app-role",roleCode:String(e.roleCode),...n?{scope:n}:{},...e.pageSize===void 0?{}:{pageSize:Number(e.pageSize)}}}function Tn(e){return e.some(t=>t.schema.fields.some(o=>{let n=o.userCandidates?.scope;return n?.creation==="prospective"||!!(n?.field&&t.schema.fields.find(i=>i.code===n.field)?.type==="resource-ref.single")}))}function Bo(e,t,o,n){for(let[i,r]of e.entries()){let c=`${n}/${i}/userCandidates`,s=vt(r.userCandidates,r.type,c);if(s&&(t.has(s.roleCode)||te("DATA_USER_CANDIDATES_ROLE_UNDECLARED",`${c}/roleCode`),s.scope&&!o.has(s.scope.dimensionCode)&&te("DATA_USER_CANDIDATES_DIMENSION_UNDECLARED",`${c}/scope/dimensionCode`),s.scope?.field)){let a=e.find(d=>d.code===s.scope.field);(!a||!ps.some(d=>d===a.type))&&te("DATA_USER_CANDIDATES_SCOPE_FIELD_INVALID",`${c}/scope/field`)}}}function ms(e,t,o,n){let i=e.subject.factProjection,r=typeof t.inputPath=="string"&&Object.entries(i).some(([d,f])=>(t.inputPath===d||t.inputPath.startsWith(`${d}.`))&&o.get(f)?.userCandidates!==void 0);if(t.candidateField===void 0&&!r)return;(t.provider!=="form_field_users"||!t.candidateField||!Uo.test(t.candidateField)||Mo.has(t.candidateField)||!t.inputPath||i[t.inputPath]!==t.candidateField)&&te("WORKFLOW_USER_CANDIDATES_FIELD_BINDING_REQUIRED",n),(t.roleCode!==void 0||t.scope!==void 0||t.routing!==void 0)&&te("WORKFLOW_USER_CANDIDATES_SOURCE_OVERRIDE_FORBIDDEN",n);let c=o.get(t.candidateField),s=c&&vt(c.userCandidates,c.type,`${n}/candidateField`);s||te("WORKFLOW_USER_CANDIDATES_FIELD_UNDECLARED",`${n}/candidateField`);let a;if(s.scope?.field){let d=Object.entries(i).filter(([,f])=>f===s.scope.field).map(([f])=>f);d.length!==1&&te("WORKFLOW_USER_CANDIDATES_SCOPE_PROJECTION_REQUIRED",n),a=d[0]}return{fieldCode:c.code,inputPath:t.inputPath,source:s,...a?{scopeInputPath:a}:{}}}function Ko(e,t,o,n,i=new Map){for(let[r,c]of Object.entries(t.bindings))ms(e,c,o,`${n}/${r}`);for(let[r,c]of Object.entries(e.taskPages||{})){let s=new Set(c.fields.filter(a=>a.readonly!==!0).map(a=>a.code));for(let a of c.fields){let d=o.get(a.code)?.userCandidates?.scope;if(s.has(a.code)&&d?.field&&s.has(d.field)&&te("WORKFLOW_USER_CANDIDATES_SCOPE_WRITE_FORBIDDEN",`${n}/taskPages/${r}/${a.code}`),!s.has(a.code)||!a.subtable)continue;let f=o.get(a.code)?.subtable?.resourceCode,u=f?i.get(f):void 0;a.subtable.fields.some(p=>p.readonly!==!0&&u?.get(p.code)?.userCandidates)&&te("WORKFLOW_USER_CANDIDATES_OWNED_FIELD_UNSUPPORTED",`${n}/taskPages/${r}/${a.code}`)}}}function pd(e,t){if(!e.scope)return;let o=e.scope.field?t[e.scope.field]:e.scope.value,n=Nn(o)?o.value:o;return Ze(n,255)||te("DATA_USER_CANDIDATES_SCOPE_VALUE_REQUIRED",e.scope.field||"scope"),String(n)}var dt=500,Qe=500,_d=1016,gd=2097152,Ad=2097152;function Rn(e){return e.some(t=>{let o=t.schema.fields.filter(n=>n.type==="subtable").map(n=>n.subtable?.maxRows??20);return o.some(n=>n>100)||o.reduce((n,i)=>n+i,0)>400})}function Ed(e){try{return new TextEncoder().encode(JSON.stringify(e)).byteLength}catch{return 1/0}}var Jo=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,wn=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,_s=["text.short","text.long","text.rich","number.integer","number.decimal","boolean","date","time","datetime","date-range","datetime-range","option.single","option.multiple","cascade.single","cascade.multiple","user.single","user.multiple","department.single","department.multiple","resource-ref.single","resource-ref.multiple","image","signature","address","location","uuid","json","file","serial-number","subtable"];function Sn(e){return e.some(t=>t.schema.fields.some(o=>(o.type==="datetime"||o.type==="datetime-range")&&o.timePrecision==="minute"))}function Dn(e){return e.some(t=>t.schema.fields.some(o=>o.type==="subtable"&&(o.subtable?.minRows??0)>0))}var gs=new Set(_s),Ho=new Set(["option.multiple","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","file","image","subtable"]),Go=new Set(["option.single","option.multiple","cascade.single","cascade.multiple"]),qo=new Set(["resource-ref.single","resource-ref.multiple"]),kn=[{code:"id",type:"uuid",nullable:!1},{code:"revision",type:"number.integer",nullable:!1},{code:"created_by",type:"text.short",nullable:!1},{code:"updated_by",type:"text.short",nullable:!1},{code:"created_at",type:"datetime",nullable:!1},{code:"updated_at",type:"datetime",nullable:!1}],Lt=new Map(kn.map(e=>[e.code,e])),Te=class extends Error{constructor(o,n){super(o);this.code=o;this.pointer=n;this.name="NativeDataFieldContractV2Error"}code;pointer};function Ft(e){return Ho.has(e)}function xt(e,t={}){return e.type!=="serial-number"&&t.system!==!0&&e.nullable===!1&&(!Ft(e.type)||t.requiredHint===!0)}function $n(e,t,o=500){Array.isArray(e)||D("NATIVE_ARRAY_REQUIRED",t),e.length===0&&D("NATIVE_DATA_FIELDS_REQUIRED",t),e.length>o&&D("NATIVE_ARRAY_LIMIT_EXCEEDED",t);let n=new Set;return e.map((i,r)=>{let c=`${t}/${r}`,s=ge(i,c);Ee(s,["code","type","nullable","indexed","options","source","userCandidates","maxLength","precision","scale","exactDecimal","min","max","rangeBoundary","timePrecision","file","serial","subtable"],c);let a=Ie(s.code,`${c}/code`,63);Jo.test(a)||D("NATIVE_FIELD_CODE_INVALID",`${c}/code`),n.has(a)&&D("NATIVE_DATA_FIELD_DUPLICATE",`${c}/code`),n.add(a);let d=Ie(s.type,`${c}/type`,32);gs.has(d)||D("NATIVE_DATA_FIELD_TYPE_INVALID",`${c}/type`);let f=d,u=hn(s.nullable,`${c}/nullable`),p=hn(s.indexed,`${c}/indexed`);u===!0&&Ho.has(f)&&D("NATIVE_DATA_MULTI_FIELD_NULLABLE_INVALID",`${c}/nullable`);let g=Is(s.options,f,c),I=ys(s.source,f,c),A=vt(s.userCandidates,f,`${c}/userCandidates`),O=Os(s,f,c),b=hn(s.exactDecimal,`${c}/exactDecimal`);b!==void 0&&f!=="number.decimal"&&D("NATIVE_DATA_FIELD_EXACT_DECIMAL_TYPE_INVALID",`${c}/exactDecimal`);let _=As(s.rangeBoundary,f,c),E=Ns(s.file,f,c),T=Ts(s.serial,f,c),l=Rs(s.subtable,f,c);return{code:a,type:f,...u===void 0?{}:{nullable:u},...p===void 0?{}:{indexed:p},...g?{options:g}:{},...I?{source:I}:{},...A?{userCandidates:A}:{},...O,...b===void 0?{}:{exactDecimal:b},..._?{rangeBoundary:_}:{},...E?{file:E}:{},...T?{serial:T}:{},...l?{subtable:l}:{}}})}function As(e,t,o){let n=`${o}/rangeBoundary`;if(!(t==="date-range"||t==="datetime-range")){e!==void 0&&D("NATIVE_DATA_FIELD_RANGE_BOUNDARY_TYPE_INVALID",n);return}return e!=="closed"&&e!=="half-open"&&D("NATIVE_DATA_FIELD_RANGE_BOUNDARY_REQUIRED",n),e}function Yo(e,t){Array.isArray(e)||D("NATIVE_ARRAY_REQUIRED",t);let o=new Map;e.forEach((n,i)=>{let r=`${t}/${i}`,c=ge(n,r),s=Ie(c.code,`${r}/code`,64);(!wn.test(s)||o.has(s))&&D("NATIVE_RESOURCE_CODE_INVALID",`${r}/code`);let a=ge(c.schema,`${r}/schema`);o.set(s,{pointer:r,fields:$n(a.fields,`${r}/schema/fields`)})});for(let[n,i]of o){let r=new Map(i.fields.map(s=>[s.code,s]));i.fields.filter(s=>s.type==="subtable").reduce((s,a)=>s+(a.subtable?.maxRows??20),0)>500&&D("NATIVE_DATA_FIELD_SUBTABLE_AGGREGATE_MAX_ROWS_EXCEEDED",`${i.pointer}/schema/fields`),i.fields.forEach((s,a)=>{let d=`${i.pointer}/schema/fields/${a}`;if(s.source&&Es(s.source,r,o,`${d}/source`),s.subtable){let f=o.get(s.subtable.resourceCode);(!f||s.subtable.resourceCode===n)&&D("NATIVE_DATA_FIELD_SUBTABLE_TARGET_MISSING",`${d}/subtable/resourceCode`);let u=f.fields.find(g=>g.code===s.subtable?.foreignKey);(!u||u.type!=="uuid"||u.nullable!==!1)&&D("NATIVE_DATA_FIELD_SUBTABLE_FOREIGN_KEY_INVALID",`${d}/subtable/foreignKey`);let p=f.fields.find(g=>g.code===s.subtable?.orderField);(!p||p.type!=="number.integer"||p.nullable!==!1)&&D("NATIVE_DATA_FIELD_SUBTABLE_ORDER_FIELD_INVALID",`${d}/subtable/orderField`)}})}}function Xo(e,t,o){if(e===void 0)return[];(!Array.isArray(e)||e.length>20)&&D("NATIVE_DATA_RESOURCE_INVARIANTS_INVALID",o);let n=new Map(t.map(r=>[r.code,r])),i=new Set;return e.map((r,c)=>{let s=`${o}/${c}`,a=ge(r,s);Ee(a,["code","message","expression"],s);let d=Ie(a.code,`${s}/code`,128);(!/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/.test(d)||i.has(d))&&D("NATIVE_DATA_RESOURCE_INVARIANT_CODE_INVALID",`${s}/code`),i.add(d);let f=Vt(a.message,`${s}/message`,500);f!==void 0&&f.length===0&&D("NATIVE_DATA_RESOURCE_INVARIANT_MESSAGE_INVALID",`${s}/message`);let u=ge(a.expression,`${s}/expression`);if(u.kind==="nonBlankTextWhenOption"){Ee(u,["kind","optionField","optionValue","textField"],`${s}/expression`);let _=Ne(u.optionField,`${s}/expression/optionField`),E=Ne(u.textField,`${s}/expression/textField`),T=Ie(u.optionValue,`${s}/expression/optionValue`,128),l=n.get(_),y=n.get(E);return(!l||!y)&&D("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_UNKNOWN",`${s}/expression`),(l.type!=="option.single"||!["text.short","text.long"].includes(y.type)||!l.options?.some(R=>R.value===T))&&D("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_TYPES_INVALID",`${s}/expression`),{code:d,...f===void 0?{}:{message:f},expression:{kind:"nonBlankTextWhenOption",optionField:_,optionValue:T,textField:E}}}Ee(u,["leftField","operator","rightField"],`${s}/expression`);let p=Ne(u.leftField,`${s}/expression/leftField`),g=Ne(u.rightField,`${s}/expression/rightField`),I=n.get(p),A=n.get(g);(!I||!A)&&D("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_UNKNOWN",`${s}/expression`),I.type===A.type||["number.integer","number.decimal"].includes(I.type)&&["number.integer","number.decimal"].includes(A.type)||D("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_TYPES_INVALID",`${s}/expression`);let b=String(u.operator);return["eq","neq","gt","gte","lt","lte"].includes(b)||D("NATIVE_DATA_RESOURCE_INVARIANT_OPERATOR_INVALID",`${s}/expression/operator`),!["eq","neq"].includes(b)&&!["number.integer","number.decimal","date","time","datetime","text.short","text.long","text.rich","serial-number","uuid"].includes(I.type)&&D("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_TYPES_INVALID",`${s}/expression`),{code:d,...f===void 0?{}:{message:f},expression:{leftField:p,operator:b,rightField:g}}})}function Es(e,t,o,n){let i=o.get(e.resourceCode);i||D("NATIVE_DATA_FIELD_SOURCE_TARGET_MISSING",`${n}/resourceCode`);let r=new Map(i.fields.map(s=>[s.code,s])),c=r.get(e.labelField);(!c||!["text.short","text.long"].includes(c.type))&&D("NATIVE_DATA_FIELD_SOURCE_LABEL_INVALID",`${n}/labelField`);for(let s of["searchFields","descriptionFields","snapshotFields"])for(let a of e[s]||[])r.has(a)||D("NATIVE_DATA_FIELD_SOURCE_FIELD_MISSING",`${n}/${s}`);for(let[s,a]of(e.filters||[]).entries())r.has(a.field)||D("NATIVE_DATA_FIELD_SOURCE_FILTER_FIELD_MISSING",`${n}/filters/${s}/field`),"binding"in a&&!t.has(a.binding.field)&&D("NATIVE_DATA_FIELD_SOURCE_BINDING_FIELD_MISSING",`${n}/filters/${s}/binding/field`)}function Is(e,t,o){let n=`${o}/options`;if(e===void 0){Go.has(t)&&D("NATIVE_DATA_FIELD_OPTIONS_REQUIRED",n);return}(!Go.has(t)||!Array.isArray(e))&&D("NATIVE_DATA_FIELD_OPTIONS_TYPE_INVALID",n),(e.length<1||e.length>100)&&D("NATIVE_DATA_FIELD_OPTIONS_INVALID",n);let i=0,r=(c,s,a)=>{a>5&&D("NATIVE_DATA_FIELD_OPTIONS_DEPTH_EXCEEDED",s);let d=new Set;return c.map((f,u)=>{i+=1,i>1e3&&D("NATIVE_DATA_FIELD_OPTIONS_COUNT_EXCEEDED",n);let p=`${s}/${u}`,g=ge(f,p);Ee(g,["label","value","description","color","children"],p);let I=Ie(g.label,`${p}/label`,500),A=Ie(g.value,`${p}/value`,500);d.has(A)&&D("NATIVE_DATA_FIELD_OPTION_VALUE_DUPLICATE",`${p}/value`),d.add(A);let O=Vt(g.description,`${p}/description`,2e3),b=Vt(g.color,`${p}/color`,64),_;return g.children!==void 0&&((!t.startsWith("cascade.")||!Array.isArray(g.children))&&D("NATIVE_DATA_FIELD_OPTION_CHILDREN_INVALID",`${p}/children`),(g.children.length<1||g.children.length>100)&&D("NATIVE_DATA_FIELD_OPTION_CHILDREN_INVALID",`${p}/children`),_=r(g.children,`${p}/children`,a+1)),{label:I,value:A,...O===void 0?{}:{description:O},...b===void 0?{}:{color:b},..._?{children:_}:{}}})};return r(e,n,1)}function ys(e,t,o){let n=`${o}/source`;if(e===void 0){qo.has(t)&&D("NATIVE_DATA_FIELD_SOURCE_REQUIRED",n);return}qo.has(t)||D("NATIVE_DATA_FIELD_SOURCE_TYPE_INVALID",n);let i=ge(e,n);Ee(i,["kind","resourceCode","labelField","searchFields","descriptionFields","snapshotFields","filters","pageSize","loadMode","clearOnBindingChange"],n),i.kind!=="resource"&&D("NATIVE_DATA_FIELD_SOURCE_KIND_INVALID",`${n}/kind`);let r=Ie(i.resourceCode,`${n}/resourceCode`,64);wn.test(r)||D("NATIVE_RESOURCE_CODE_INVALID",`${n}/resourceCode`);let c=Ne(i.labelField,`${n}/labelField`),s=Cn(i.searchFields,`${n}/searchFields`,10),a=Cn(i.descriptionFields,`${n}/descriptionFields`,10),d=Cn(i.snapshotFields,`${n}/snapshotFields`,50),f=Me(i.pageSize,`${n}/pageSize`,1,100),u;i.loadMode!==void 0&&(["search","all"].includes(String(i.loadMode))||D("NATIVE_DATA_FIELD_SOURCE_LOAD_MODE_INVALID",`${n}/loadMode`),u=i.loadMode);let p=bs(i.filters,`${n}/filters`);return i.clearOnBindingChange!==void 0&&typeof i.clearOnBindingChange!="boolean"&&D("NATIVE_DATA_FIELD_SOURCE_BINDING_RESET_INVALID",`${n}/clearOnBindingChange`),{kind:"resource",resourceCode:r,labelField:c,...s?{searchFields:s}:{},...a?{descriptionFields:a}:{},...d?{snapshotFields:d}:{},...p?{filters:p}:{},...f===void 0?{}:{pageSize:f},...u?{loadMode:u}:{},...i.clearOnBindingChange===void 0?{}:{clearOnBindingChange:i.clearOnBindingChange}}}function bs(e,t){if(e!==void 0)return(!Array.isArray(e)||e.length>20)&&D("NATIVE_DATA_FIELD_SOURCE_FILTERS_INVALID",t),e.map((o,n)=>{let i=`${t}/${n}`,r=ge(o,i),c=Object.prototype.hasOwnProperty.call(r,"value"),s=Object.prototype.hasOwnProperty.call(r,"binding");Ee(r,c?["field","operator","value"]:["field","operator","binding"],i),c===s&&D("NATIVE_DATA_FIELD_SOURCE_FILTER_VALUE_INVALID",i);let a=Ne(r.field,`${i}/field`);["eq","in"].includes(String(r.operator))||D("NATIVE_DATA_FIELD_SOURCE_FILTER_OPERATOR_INVALID",`${i}/operator`);let d=r.operator;if(c)return{field:a,operator:d,value:r.value};let f=ge(r.binding,`${i}/binding`);return Ee(f,["kind","field"],`${i}/binding`),f.kind!=="field"&&D("NATIVE_DATA_FIELD_SOURCE_BINDING_KIND_INVALID",`${i}/binding/kind`),{field:a,operator:d,binding:{kind:"field",field:Ne(f.field,`${i}/binding/field`)}}})}function Os(e,t,o){let n={};if(e.maxLength!==void 0&&(["text.short","text.long","text.rich"].includes(t)||D("NATIVE_DATA_FIELD_MAX_LENGTH_TYPE_INVALID",`${o}/maxLength`),n.maxLength=Pt(e.maxLength,`${o}/maxLength`,1,1e6)),(e.precision!==void 0||e.scale!==void 0)&&((t!=="number.decimal"||e.precision===void 0)&&D("NATIVE_DATA_FIELD_DECIMAL_CONFIG_INVALID",o),n.precision=Pt(e.precision,`${o}/precision`,1,1e3),n.scale=e.scale===void 0?0:Pt(e.scale,`${o}/scale`,0,n.precision)),e.min!==void 0||e.max!==void 0){["number.integer","number.decimal"].includes(t)||D("NATIVE_DATA_FIELD_NUMERIC_BOUNDS_TYPE_INVALID",o);let i=zo(e.min,`${o}/min`),r=zo(e.max,`${o}/max`);t==="number.integer"&&[i,r].some(c=>c!==void 0&&!Number.isSafeInteger(c))&&D("NATIVE_DATA_FIELD_NUMERIC_BOUNDS_INVALID",o),i!==void 0&&r!==void 0&&i>r&&D("NATIVE_DATA_FIELD_NUMERIC_BOUNDS_INVALID",o),i!==void 0&&(n.min=i),r!==void 0&&(n.max=r)}return e.timePrecision!==void 0&&((!["time","datetime","datetime-range"].includes(t)||!["minute","second"].includes(e.timePrecision))&&D("NATIVE_DATA_FIELD_TIME_PRECISION_INVALID",`${o}/timePrecision`),n.timePrecision=e.timePrecision),n}function Ns(e,t,o){if(e===void 0)return;let n=`${o}/file`;["file","image","signature"].includes(t)||D("NATIVE_DATA_FIELD_FILE_TYPE_INVALID",n);let i=ge(e,n);Ee(i,["maxCount","maxSizeMb","accept"],n);let r=Me(i.maxCount,`${n}/maxCount`,1,100);t==="signature"&&r!==void 0&&r!==1&&D("NATIVE_DATA_FIELD_SIGNATURE_COUNT_INVALID",`${n}/maxCount`);let c=Me(i.maxSizeMb,`${n}/maxSizeMb`,1,1024),s;return i.accept!==void 0&&((!Array.isArray(i.accept)||i.accept.length>50)&&D("NATIVE_DATA_FIELD_FILE_ACCEPT_INVALID",`${n}/accept`),s=i.accept.map((a,d)=>Ie(a,`${n}/accept/${d}`,255)),new Set(s).size!==s.length&&D("NATIVE_DATA_FIELD_FILE_ACCEPT_INVALID",`${n}/accept`)),{...r===void 0?{}:{maxCount:r},...c===void 0?{}:{maxSizeMb:c},...s===void 0?{}:{accept:s}}}function Ts(e,t,o){let n=`${o}/serial`;if(e===void 0){t==="serial-number"&&D("NATIVE_DATA_FIELD_SERIAL_REQUIRED",n);return}t!=="serial-number"&&D("NATIVE_DATA_FIELD_SERIAL_TYPE_INVALID",n);let i=ge(e,n);Ee(i,["prefix","digits","start"],n);let r=Vt(i.prefix,`${n}/prefix`,64),c=Me(i.digits,`${n}/digits`,1,32),s=Me(i.start,`${n}/start`,0,Number.MAX_SAFE_INTEGER);return{...r===void 0?{}:{prefix:r},...c===void 0?{}:{digits:c},...s===void 0?{}:{start:s}}}function Rs(e,t,o){let n=`${o}/subtable`;if(e===void 0){t==="subtable"&&D("NATIVE_DATA_FIELD_SUBTABLE_REQUIRED",n);return}t!=="subtable"&&D("NATIVE_DATA_FIELD_SUBTABLE_TYPE_INVALID",n);let i=ge(e,n);Ee(i,["resourceCode","foreignKey","orderField","minRows","maxRows"],n);let r=Ie(i.resourceCode,`${n}/resourceCode`,64);wn.test(r)||D("NATIVE_RESOURCE_CODE_INVALID",`${n}/resourceCode`);let c=Ne(i.foreignKey,`${n}/foreignKey`),s=Ne(i.orderField,`${n}/orderField`);s===c&&D("NATIVE_DATA_FIELD_SUBTABLE_ORDER_FIELD_INVALID",`${n}/orderField`);let a=Me(i.maxRows,`${n}/maxRows`,1,500),d=Me(i.minRows,`${n}/minRows`,0,500);return(d??0)>(a??20)&&D("NATIVE_DATA_FIELD_SUBTABLE_MIN_ROWS_INVALID",`${n}/minRows`),{resourceCode:r,foreignKey:c,orderField:s,...d===void 0?{}:{minRows:d},...a===void 0?{}:{maxRows:a}}}function Cn(e,t,o){if(e===void 0)return;(!Array.isArray(e)||e.length>o)&&D("NATIVE_DATA_FIELD_SOURCE_FIELDS_INVALID",t);let n=e.map((i,r)=>Ne(i,`${t}/${r}`));return new Set(n).size!==n.length&&D("NATIVE_DATA_FIELD_SOURCE_FIELDS_INVALID",t),n}function Ne(e,t){let o=Ie(e,t,63);return Jo.test(o)||D("NATIVE_FIELD_CODE_INVALID",t),o}function ge(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&D("NATIVE_OBJECT_REQUIRED",t),e}function Ee(e,t,o){let n=new Set(t);for(let i of Object.keys(e))n.has(i)||D("NATIVE_PROPERTY_UNKNOWN",`${o}/${i}`)}function Ie(e,t,o){return(typeof e!="string"||e.length===0||e.length>o)&&D("NATIVE_STRING_INVALID",t),e}function Vt(e,t,o){if(e!==void 0)return(typeof e!="string"||e.length>o)&&D("NATIVE_STRING_INVALID",t),e}function hn(e,t){if(e!==void 0)return typeof e!="boolean"&&D("NATIVE_BOOLEAN_REQUIRED",t),e}function Me(e,t,o,n){if(e!==void 0)return Pt(e,t,o,n)}function zo(e,t){if(e!==void 0)return(typeof e!="number"||!Number.isFinite(e))&&D("NATIVE_NUMBER_REQUIRED",t),e}function Pt(e,t,o,n){return(!Number.isSafeInteger(e)||Number(e)<o||Number(e)>n)&&D("NATIVE_INTEGER_OUT_OF_RANGE",t),Number(e)}function D(e,t){throw new Te(e,t)}var jt=["created_by","updated_by","created_at","updated_at"];function lt(e){return jt.includes(e)}function Zo(e){return jt.some(t=>Object.prototype.hasOwnProperty.call(e.fieldPolicies||{},t))}var Cs=kn.map(e=>e.code);function Qo(e){return Cs.includes(e)}var hs=["eq","neq","gt","gte","lt","lte","contains","startsWith","endsWith","in","between","has","hasAny","hasAll","overlaps","containedBy","jsonContains","isEmpty","isNotEmpty"],ws=new Set(hs);function Rd(e){return ws.has(String(e))}var vn=["eq","neq","contains","startsWith","endsWith","in","isEmpty","isNotEmpty"],ut=["eq","neq","gt","gte","lt","lte","between","in","isEmpty"],Ss=["eq","neq","in","isEmpty"],Wt=["eq","neq","in","isEmpty","isNotEmpty"],et=["has","hasAny","hasAll","isEmpty","isNotEmpty"],ei=["overlaps","contains","containedBy","isEmpty"],Pn=["jsonContains","isEmpty","isNotEmpty"],Vn=["isEmpty","isNotEmpty"],Ds={"text.short":vn,"text.long":vn,"text.rich":vn,"number.integer":ut,"number.decimal":ut,boolean:Ss,date:ut,time:ut,datetime:ut,"date-range":ei,"datetime-range":ei,"option.single":Wt,"option.multiple":et,"cascade.single":et,"cascade.multiple":et,"user.single":Wt,"user.multiple":et,"department.single":Wt,"department.multiple":et,"resource-ref.single":Wt,"resource-ref.multiple":et,file:Vn,image:Vn,signature:Vn,address:Pn,location:Pn,uuid:["eq","neq","in","isEmpty"],json:Pn,"serial-number":["eq","neq","in","contains","startsWith"],subtable:[]},ks=new Set(["text.short","text.long","text.rich","option.single","user.single","department.single","resource-ref.single","serial-number"]),$s=new Set(["option.multiple","cascade.single","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","file","image","signature","address","location","json","subtable"]);function ni(e){return Ds[e]}function Cd(e,t){return ni(e).includes(t)}function Ln(e){return ks.has(e)}function ft(e){return!$s.has(e)}function oi(e){return ni(e).length>0}var ti=new Set(["number.integer","number.decimal"]),ii=new Set(["text.short","text.long","number.integer","number.decimal","date","time","datetime","serial-number"]),vs=new Set([...ii,"boolean","uuid"]),Ps=new Set(["option.single","user.single","department.single","resource-ref.single"]);function hd(e,t){return t==="sum"||t==="avg"?ti.has(e)?{valueExpression:"column",numericResult:!0}:null:t==="min"||t==="max"?ii.has(e)?{valueExpression:"column",numericResult:ti.has(e)}:null:Ps.has(e)?{valueExpression:"snapshot-value",numericResult:!0}:vs.has(e)?{valueExpression:"column",numericResult:!0}:null}var xn=["version","maxBytes","fields"];function si(e,t){if(e===void 0)return;let o=Fn(e,t);ri(o,xn,t);let n=Ut(o.version,`${t}/version`,1,1e6),i=Ut(o.maxBytes,`${t}/maxBytes`,2,196608);(!n||!i)&&ae("NATIVE_DATA_DRAFT_STATE_SCHEMA_INVALID",t);let r=Fn(o.fields,`${t}/fields`),c=Object.entries(r);(!c.length||c.length>50)&&ae("NATIVE_DATA_DRAFT_STATE_FIELDS_INVALID",`${t}/fields`);for(let[s,a]of c){let d=`${t}/fields/${s}`;/^[A-Za-z][A-Za-z0-9_]{0,62}$/.test(s)||ae("NATIVE_DATA_DRAFT_STATE_FIELD_CODE_INVALID",d);let f=Fn(a,d),u=ai(f.type,`${d}/type`,32),p=u==="string"?["type","required","maxLength","enum"]:u==="json.object"?["type","required","maxBytes"]:["type","required"];if(["string","number","integer","boolean","json.object"].includes(u)||ae("NATIVE_DATA_DRAFT_STATE_FIELD_TYPE_INVALID",`${d}/type`),ri(f,p,d),Ls(f.required,`${d}/required`),u==="string"){let g=Ut(f.maxLength,`${d}/maxLength`,1,196608);g||ae("NATIVE_DATA_DRAFT_STATE_FIELD_INVALID",d),f.enum!==void 0&&Vs(f.enum,`${d}/enum`,100,!1).some(A=>A.length>g)&&ae("NATIVE_DATA_DRAFT_STATE_FIELD_INVALID",`${d}/enum`)}else if(u==="json.object"){let g=Ut(f.maxBytes,`${d}/maxBytes`,2,65536);(!g||g>i)&&ae("NATIVE_DATA_DRAFT_STATE_FIELD_INVALID",d)}}}function Vs(e,t,o,n){(!Array.isArray(e)||!n&&e.length===0||e.length>o)&&ae("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t);let i=e.map((r,c)=>ai(r,`${t}/${c}`,255));return new Set(i).size!==i.length&&ae("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t),i}function Fn(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&ae("NATIVE_OBJECT_REQUIRED",t),e}function ri(e,t,o){let n=new Set(t);for(let i of Object.keys(e))n.has(i)||ae("NATIVE_PROPERTY_UNKNOWN",`${o}/${i}`)}function ai(e,t,o){return(typeof e!="string"||e.length===0||e.length>o)&&ae("NATIVE_STRING_INVALID",t),e}function Ls(e,t){e!==void 0&&typeof e!="boolean"&&ae("NATIVE_BOOLEAN_REQUIRED",t)}function Ut(e,t,o,n){return(!Number.isSafeInteger(e)||Number(e)<o||Number(e)>n)&&ae("NATIVE_INTEGER_INVALID",t),Number(e)}function ae(e,t){throw new Te(e,t)}var Fs=500,$e={surface:["mutationOwner","generated","fields","list","form","detail","mobile","views"],generated:["list","detail","create","update","delete"],field:["label","type","widget","section","requiredHint","system","hidden","readCapabilities","createCapabilities","updateCapabilities","maxLength","precision","scale","exactDecimal","min","max","rangeBoundary","maxCount","maxSizeMb","accept","options","list","searchable","sortable","source","userCandidates","timePrecision","serial","subtable"],list:["actions","fieldOrder","defaultPageSize","searchableFields","filterFields","defaultSort"],defaultSort:["field","order"],form:["layout","fieldOrder","draftState"],detail:["layout","fieldOrder"],layout:["layout","fieldOrder","draftState"],draftState:xn,mobile:["enabled"]},xs={"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 Un(e,t,o){if(e===void 0)return;let n=re(e,o);Re(n,$e.surface,o);let i=n.mutationOwner===void 0?"native":Se(n.mutationOwner,`${o}/mutationOwner`,16);["native","action","readonly","workflow","queued-command"].includes(i)||j("NATIVE_DATA_SURFACE_MUTATION_OWNER_INVALID",`${o}/mutationOwner`);let r=n.generated===void 0?{}:re(n.generated,`${o}/generated`);Re(r,$e.generated,`${o}/generated`);for(let a of $e.generated)Wn(r[a],`${o}/generated/${a}`);if(i!=="native")for(let a of["create","update","delete"])r[a]===!0&&j("NATIVE_DATA_SURFACE_MUTATION_OWNER_CONFLICT",`${o}/generated/${a}`);let c=new Map(t.map(a=>[a.code,a])),s=re(n.fields,`${o}/fields`);for(let a of Object.keys(s))c.has(a)||j("NATIVE_DATA_SURFACE_FIELD_MISSING",`${o}/fields/${a}`);for(let a of t)Object.prototype.hasOwnProperty.call(s,a.code)||j("NATIVE_DATA_SURFACE_FIELD_REQUIRED",`${o}/fields/${a.code}`),Ws(s[a.code],a,`${o}/fields/${a.code}`);for(let a of["create","update"]){let d=r[a]??i==="native",f=t.some(u=>{let p=re(s[u.code],`${o}/fields/${u.code}`);return di(u,p,a)});d&&!f&&j("NATIVE_DATA_SURFACE_WRITABLE_FIELDS_REQUIRED",`${o}/generated/${a}`)}if(Us(n.list,c,`${o}/list`),ci(n.form,c,`${o}/form`,"form"),ci(n.detail,c,`${o}/detail`,"detail"),n.mobile!==void 0){let a=re(n.mobile,`${o}/mobile`);Re(a,$e.mobile,`${o}/mobile`),Wn(a.enabled,`${o}/mobile/enabled`)}js(n,t,o)}function Mn(e,t){let o=e.views?.find(i=>i.code===t);o||j("NATIVE_DATA_VIEW_NOT_FOUND",`/surface/views/${t}`);let n=new Map((o.sections||[]).flatMap(i=>i.fields.map(r=>[r,i.title])));return{mutationOwner:e.mutationOwner||"native",generated:o.generated,list:o.list,form:o.form,detail:o.detail,mobile:o.mobile,fields:Object.fromEntries(Object.entries(e.fields).map(([i,r])=>{let c={...r};delete c.section;let s=n.get(i);return[i,{...c,...s?{section:s}:{},list:o.list.fieldOrder.includes(i)}]}))}}function js(e,t,o){if(e.views===void 0)return;(!Array.isArray(e.views)||e.views.length>20)&&j("NATIVE_DATA_VIEWS_LIMIT_INVALID",`${o}/views`);let n=new Set;e.views.forEach((i,r)=>{let c=`${o}/views/${r}`,s=re(i,c);Re(s,["code","name","generated","list","form","detail","mobile","sections"],c);let a=Se(s.code,`${c}/code`,64);(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(a)||n.has(a))&&j("NATIVE_DATA_VIEW_CODE_INVALID",`${c}/code`),n.add(a),Se(s.name,`${c}/name`,255),re(s.generated,`${c}/generated`),re(s.mobile,`${c}/mobile`);for(let f of["list","detail","create","update","delete"])typeof s.generated[f]!="boolean"&&j("NATIVE_DATA_VIEW_OPERATION_INVALID",`${c}/generated/${f}`);typeof s.mobile.enabled!="boolean"&&j("NATIVE_DATA_VIEW_MOBILE_INVALID",`${c}/mobile/enabled`);for(let f of["list","form","detail"]){let u=re(s[f],`${c}/${f}`),p=tt(u.fieldOrder,`${c}/${f}/fieldOrder`,500,!0);for(let g of p){let I=e.fields[g];(!I||(I.hidden??I.system)===!0)&&j("NATIVE_DATA_VIEW_FIELD_INVALID",`${c}/${f}/fieldOrder`)}}if(s.sections!==void 0){(!Array.isArray(s.sections)||s.sections.length>100)&&j("NATIVE_DATA_VIEW_SECTIONS_INVALID",`${c}/sections`);let f=new Set;s.sections.forEach((u,p)=>{let g=`${c}/sections/${p}`,I=re(u,g);Re(I,["title","fields"],g),Se(I.title,`${g}/title`,255);for(let A of tt(I.fields,`${g}/fields`,100,!0)){let O=e.fields[A];(!O||(O.hidden??O.system)===!0||f.has(A))&&j("NATIVE_DATA_VIEW_FIELD_INVALID",`${g}/fields`),f.add(A)}})}let d=Mn(e,a);if(Un(d,t,c),s.generated.create!==!1&&(e.mutationOwner||"native")==="native")for(let f of t)xt(f,e.fields[f.code])&&di(f,e.fields[f.code],"create")&&!s.form.fieldOrder.includes(f.code)&&j("NATIVE_DATA_VIEW_CREATE_REQUIRED_FIELD_MISSING",`${c}/form/fieldOrder`)})}function di(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 Ws(e,t,o){let n=re(e,o);Re(n,$e.field,o),Se(n.label,`${o}/label`,500),n.type!==t.type&&j("NATIVE_DATA_SURFACE_FIELD_TYPE_MISMATCH",`${o}/type`);let i=Se(n.widget,`${o}/widget`,64);xs[t.type].includes(i)||j("NATIVE_DATA_SURFACE_WIDGET_INCOMPATIBLE",`${o}/widget`),Ks(n.section,`${o}/section`,255);for(let r of["requiredHint","system","hidden","list","searchable","sortable"])Wn(n[r],`${o}/${r}`);n.searchable===!0&&!Ln(t.type)&&j("NATIVE_DATA_SURFACE_SEARCH_UNSUPPORTED",`${o}/searchable`),n.sortable===!0&&!ft(t.type)&&j("NATIVE_DATA_SURFACE_SORT_UNSUPPORTED",`${o}/sortable`);for(let r of["readCapabilities","createCapabilities","updateCapabilities"])tt(n[r],`${o}/${r}`,100,!0);if(n.maxCount!==void 0&&(!Number.isSafeInteger(n.maxCount)||Number(n.maxCount)<1||Number(n.maxCount)>100)&&j("NATIVE_DATA_SURFACE_MAX_COUNT_INVALID",`${o}/maxCount`),n.maxSizeMb!==void 0&&(!Number.isSafeInteger(n.maxSizeMb)||Number(n.maxSizeMb)<1||Number(n.maxSizeMb)>1024)&&j("NATIVE_DATA_SURFACE_MAX_SIZE_INVALID",`${o}/maxSizeMb`),n.accept!==void 0){let r=Array.isArray(n.accept)?n.accept:[n.accept];tt(r,`${o}/accept`,50,!1)}for(let r of["maxLength","precision","scale","exactDecimal","min","max","rangeBoundary","options","source","userCandidates","timePrecision","serial","subtable"])Ms(n,t,r,o);Bs(n,t,o)}function Us(e,t,o){if(e===void 0)return;let n=re(e,o);if(Re(n,$e.list,o),n.actions!==void 0){let i=re(n.actions,`${o}/actions`);Re(i,["import","export"],`${o}/actions`);for(let r of["import","export"])i[r]!==void 0&&typeof i[r]!="boolean"&&j("NATIVE_DATA_SURFACE_LIST_ACTION_INVALID",`${o}/actions/${r}`)}if(n.fieldOrder!==void 0)for(let i of tt(n.fieldOrder,`${o}/fieldOrder`,500,!0))t.has(i)||j("NATIVE_DATA_SURFACE_LIST_FIELD_INVALID",`${o}/fieldOrder`);n.defaultPageSize!==void 0&&(!Number.isSafeInteger(n.defaultPageSize)||Number(n.defaultPageSize)<1||Number(n.defaultPageSize)>200)&&j("NATIVE_DATA_SURFACE_PAGE_SIZE_INVALID",`${o}/defaultPageSize`);for(let[i,r]of[["searchableFields",Ln],["filterFields",oi]]){if(n[i]===void 0)continue;let c=tt(n[i],`${o}/${i}`,100,!0);for(let s of c){let a=t.get(s);(!a||!r(a.type))&&j("NATIVE_DATA_SURFACE_LIST_FIELD_INVALID",`${o}/${i}`)}}if(n.defaultSort!==void 0){let i=re(n.defaultSort,`${o}/defaultSort`);Re(i,$e.defaultSort,`${o}/defaultSort`);let r=Se(i.field,`${o}/defaultSort/field`,63),c=t.get(r);!Qo(r)&&(!c||!ft(c.type))&&j("NATIVE_DATA_SURFACE_SORT_UNSUPPORTED",`${o}/defaultSort/field`),i.order!==void 0&&!["asc","desc"].includes(i.order)&&j("NATIVE_DATA_SURFACE_SORT_ORDER_INVALID",`${o}/defaultSort/order`)}}function ci(e,t,o,n){if(e===void 0)return;let i=re(e,o);if(Re(i,$e[n],o),i.layout!==void 0&&!["flat","sections"].includes(i.layout)&&j("NATIVE_DATA_SURFACE_LAYOUT_INVALID",`${o}/layout`),i.fieldOrder!==void 0){let r=`${o}/fieldOrder`;(!Array.isArray(i.fieldOrder)||i.fieldOrder.length>t.size||i.fieldOrder.length>Fs)&&j("NATIVE_DATA_SURFACE_FIELD_ORDER_INVALID",r);let c=i.fieldOrder.map((s,a)=>Se(s,`${r}/${a}`,63));new Set(c).size!==c.length&&j("NATIVE_DATA_SURFACE_FIELD_ORDER_INVALID",r),c.forEach((s,a)=>{t.has(s)||j("NATIVE_DATA_SURFACE_FIELD_ORDER_FIELD_MISSING",`${r}/${a}`)})}n==="form"&&si(i.draftState,`${o}/draftState`)}function Ms(e,t,o,n){e[o]===void 0&&t[o]===void 0||((e[o]===void 0||t[o]===void 0)&&j("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${n}/${o}`),Q(e[o])!==Q(t[o])&&j("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${n}/${o}`))}function Bs(e,t,o){let n=t.file||{},i={...e.maxCount===void 0?{}:{maxCount:e.maxCount},...e.maxSizeMb===void 0?{}:{maxSizeMb:e.maxSizeMb},...e.accept===void 0?{}:{accept:jn(e.accept)}};for(let r of["maxCount","maxSizeMb","accept"]){if(i[r]===void 0&&n[r]===void 0)continue;(i[r]===void 0||n[r]===void 0)&&j("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${o}/${r}`);let c=r==="accept"?jn(i[r]):i[r],s=r==="accept"?jn(n[r]):n[r];Q(c)!==Q(s)&&j("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${o}/${r}`)}}function jn(e){return(Array.isArray(e)?[...e]:[e]).sort((t,o)=>{let n=String(t),i=String(o);return n===i?0:n<i?-1:1})}function tt(e,t,o,n){(!Array.isArray(e)||!n&&e.length===0||e.length>o)&&j("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t);let i=e.map((r,c)=>Se(r,`${t}/${c}`,255));return new Set(i).size!==i.length&&j("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t),i}function re(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&j("NATIVE_OBJECT_REQUIRED",t),e}function Re(e,t,o){let n=new Set(t);for(let i of Object.keys(e))n.has(i)||j("NATIVE_PROPERTY_UNKNOWN",`${o}/${i}`)}function Se(e,t,o){return(typeof e!="string"||e.length===0||e.length>o)&&j("NATIVE_STRING_INVALID",t),e}function Ks(e,t,o){e!==void 0&&(typeof e!="string"||e.length>o)&&j("NATIVE_STRING_INVALID",t)}function Wn(e,t){e!==void 0&&typeof e!="boolean"&&j("NATIVE_BOOLEAN_REQUIRED",t)}function j(e,t){throw new Te(e,t)}var pt=class extends Error{constructor(o,n){super(`${o}: ${n}`);this.pointer=o;this.reason=n}pointer;reason;code="NATIVE_MANAGED_CONCURRENCY_INVALID"};function li(e,t,o){if(e===void 0)return;let n=(_,E)=>{throw new pt(_,E)},i=(_,E,T)=>((!_||typeof _!="object"||Array.isArray(_)||Object.keys(_).some(l=>!T.includes(l)))&&n(E,"object contains unsupported properties"),_),r=(_,E,T,l)=>{(!Number.isSafeInteger(_)||_<E||_>T)&&n(l,`expected integer ${E}..${T}`)},c=(_,E)=>{(typeof _!="string"||!/^[a-z][a-z0-9_-]{0,63}$/.test(_))&&n(E,"invalid code")},s=(_,E,T)=>((!Array.isArray(_)||_.length>E)&&n(T,"array exceeds bound"),_),a=(_,E)=>{let T=t.find(l=>l.code===_);return T||n(E,"unknown resource"),T},d=(_,E,T)=>{let l=_.schema.fields.find(y=>y.code===E);return!l&&E!=="id"&&n(T,"unknown field"),l},f=(_,E,T=!1)=>{i(_,E,Object.keys(_||{})),Object.keys(_).length>8&&n(E,"at most eight parameters");for(let[l,y]of Object.entries(_))if(c(l,E),i(y,E,["type","values","minimum","maximum","minLength","maxLength"]),y.type==="uuid")Object.keys(y).length!==1&&n(E,"uuid has no options");else if(T&&y.type==="boolean")i(y,E,["type"]);else if(T&&y.type==="string"&&y.values===void 0)i(y,E,["type","minLength","maxLength"]),r(y.maxLength,1,256,E),y.minLength!==void 0&&r(y.minLength,0,y.maxLength,E);else if(y.type==="string"){i(y,E,["type","values"]);let R=s(y.values,100,E);(!R.length||R.some(h=>typeof h!="string"||h.length>128)||new Set(R).size!==R.length)&&n(E,"finite string values required")}else y.type==="integer"?(i(y,E,["type","minimum","maximum"]),r(y.minimum,0,1e6,E),r(y.maximum,y.minimum,y.minimum+1e3,E)):n(E,"unsupported parameter type")},u=(_,E,T,l=!1)=>{i(_,T,["from","key","value"]),!(_.from==="input"&&Object.keys(_).length===2&&Object.hasOwn(E,_.key))&&((_.from==="actor"||l&&_.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"))},p=(_,E,T)=>{u(_,E,T),!(_.from==="input"&&E[_.key].type==="uuid")&&(_.from==="literal"&&typeof _.value=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(_.value)||n(T,"record and allocation identifiers require a UUID binding"))},g=(_,E,T)=>{u(_,E,T),!(_.from==="input"&&E[_.key].type==="integer"&&E[_.key].minimum>=1)&&(_.from==="literal"&&Number.isSafeInteger(_.value)&&_.value>=1||n(T,"expectedRevision requires a positive integer binding"))},I="/data/concurrency";JSON.stringify(e).length>131072&&n(I,"declaration exceeds 128 KiB");let A=i(e,I,["version","admission","reads","quotas","commands"]);A.version!==1&&n(I,"unsupported version"),i(A.admission,I,["perSecond","burst","maxInFlight"]),r(A.admission.perSecond,1,1e3,I),r(A.admission.burst,1,1e3,I),r(A.admission.maxInFlight,1,1e3,I);let O=(_,E)=>{let T=new Set;for(let l of _)c(l?.code,E),T.has(l.code)&&n(E,"duplicate code"),T.add(l.code)};O(s(A.reads,32,I),I),O(s(A.quotas,16,I),I),O(s(A.commands,32,I),I);for(let _ of A.reads){let E=`${I}/reads/${_.code}`;i(_,E,["code","resourceCode","parameters","select","where","limit","scope","freshSeconds","staleSeconds","maxKeys","sourcePerSecond","dependencies"]);let T=a(_.resourceCode,E);f(_.parameters,E),["subject","application"].includes(_.scope)||n(E,"invalid cache scope"),_.scope==="application"&&T.dataPolicyCode&&n(E,"shared cache cannot bypass a row policy");let l=s(_.select,32,E);l.length||n(E,"select required"),l.forEach(R=>d(T,R,E));let y=s(_.dependencies,64,E);y.forEach(R=>d(T,R,E));for(let R of s(_.where||[],8,E))i(R,E,["field","value"]),d(T,R.field,E),u(R.value,_.parameters,E),_.scope==="application"&&R.value.from==="actor"&&n(E,"actor requires subject cache"),y.includes(R.field)||n(E,"filter dependency missing");l.some(R=>!y.includes(R))&&n(E,"selected field dependency missing"),r(_.limit,1,100,E),r(_.freshSeconds,1,300,E),r(_.staleSeconds,0,300,E),r(_.maxKeys,1,1e4,E),r(_.sourcePerSecond,1,20,E)}for(let _ of A.quotas){let E=`${I}/quotas/${_.code}`;i(_,E,["code","sourceResource","capacityField","allocationResource","allocationField","reservationSeconds"]);let T=a(_.sourceResource,E),l=a(_.allocationResource,E);d(T,_.capacityField,E)?.type!=="number.integer"&&n(E,"capacity must be an integer"),(d(l,_.allocationField,E)?.type!=="uuid"||d(l,_.allocationField,E)?.nullable!==!1)&&n(E,"allocation reference must be a uuid"),l.surface?.mutationOwner!=="queued-command"&&n(E,"allocation model must be command owned"),_.reservationSeconds!==void 0&&r(_.reservationSeconds,10,86400,E)}new Set(A.quotas.map(_=>_.allocationResource)).size!==A.quotas.length&&n(I,"an allocation model has exactly one pool owner");for(let _ of A.commands){let E=`${I}/commands/${_.code}`;i(_,E,["code","mode","intake","execution","capability","parameters","resourceKey","admission","deadlineSeconds","guards","operations","quota"]),_.mode!==void 0&&!["permit","durable"].includes(_.mode)&&n(E,"unsupported mode");let T=_.mode==="durable";if(f(_.parameters,E,T),u(_.resourceKey,_.parameters,E),o.some(l=>l.code===_.capability)||n(E,"command capability must be declared"),i(_.admission,E,["perSecond","burst","maxInFlight","maxQueue","maxWaitSeconds","permitSeconds"]),r(_.admission.perSecond,1,A.admission.perSecond,E),r(_.admission.burst,1,A.admission.burst,E),r(_.admission.maxInFlight,1,A.admission.maxInFlight,E),r(_.admission.maxQueue,1,1e4,E),r(_.admission.maxWaitSeconds,1,3600,E),(!T||_.admission.permitSeconds!==void 0)&&r(_.admission.permitSeconds,5,60,E),r(_.deadlineSeconds,10,3600,E),T){(_.operations!==void 0||_.guards!==void 0||_.quota!==void 0)&&n(E,"backend-plan does not accept static operations, guards or quota"),i(_.intake,E,["perSecond","burst","maxInFlight"]);for(let R of["perSecond","burst","maxInFlight"])r(_.intake[R],1,1e3,E);let l=i(_.execution,E,["kind","handlerCode","timeoutMs","resources","directory"]);l.kind!=="backend-plan"&&n(E,"durable requires backend-plan"),c(l.handlerCode,E),r(l.timeoutMs,100,3e4,E);let y=s(l.resources,32,E);y.length||n(E,"execution resources required"),new Set(y.map(R=>R.resourceCode)).size!==y.length&&n(E,"duplicate execution resource");for(let R of y){i(R,E,["resourceCode","readFields","writeOperations","writeFields"]);let h=a(R.resourceCode,E);for(let k of["readFields","writeFields"]){let M=s(R[k],64,E);new Set(M).size!==M.length&&n(E,"duplicate field"),M.forEach(L=>{k==="readFields"&&Lt.has(L)||d(h,L,E)})}let $=s(R.writeOperations,3,E);(new Set($).size!==$.length||$.some(k=>!["create","update","increment"].includes(k)))&&n(E,"unsupported execution operation"),R.writeFields.some(k=>["id","revision","created_by","updated_by","created_at","updated_at"].includes(k))&&n(E,"record metadata is platform owned"),!$.length&&R.writeFields.length&&n(E,"write fields require an operation"),$.length&&!R.writeFields.length&&n(E,"write operations require fields"),A.quotas.some(k=>k.allocationResource===R.resourceCode)&&$.length&&n(E,"allocation references remain owned by their pool command")}if(l.directory!==void 0){i(l.directory,E,["mode","fields"]),l.directory.mode!=="current-initiator"&&n(E,"only current initiator allowed");let R=s(l.directory.fields,5,E);(!R.length||new Set(R).size!==R.length||R.some(h=>!["displayName","employeeNumber","primaryDepartment","departments","phone"].includes(h)))&&n(E,"unsupported directory fields")}continue}(_.execution!==void 0||_.intake!==void 0)&&n(E,"execution and intake require durable mode");for(let l of s(_.guards||[],8,E)){i(l,E,["resourceCode","id","conditions"]);let y=a(l.resourceCode,E);p(l.id,_.parameters,E);for(let R of s(l.conditions,16,E)){i(R,E,["kind","field","operator","value"]);let h=d(y,R.field,E);["eq","neq","lt","lte","gt","gte"].includes(R.operator)||n(E,"unsupported guard"),R.kind==="database-now"?(h?.type!=="datetime"||!["lt","lte","gt","gte"].includes(R.operator)||R.value!==void 0)&&n(E,"database-now requires datetime and an ordering operator"):(R.kind!==void 0&&R.kind!=="value"&&n(E,"unsupported condition kind"),u(R.value,_.parameters,E))}}for(let l of s(_.operations,8,E)){i(l,E,["operation","resourceCode","id","expectedRevision","data"]);let y=a(l.resourceCode,E);y.surface?.mutationOwner!=="queued-command"&&n(E,"command mutations require command owned models");let R=A.quotas.find(h=>h.allocationResource===l.resourceCode);R&&(l.operation==="create"?_.quota?.action!=="allocate"||_.quota.pool!==R.code:Object.hasOwn(l.data||{},R.allocationField))&&n(E,"allocation references are owned by their pool command"),["create","update"].includes(l.operation)||n(E,"unsupported operation"),l.operation==="update"?(p(l.id,_.parameters,E),g(l.expectedRevision,_.parameters,E)):(l.id!==void 0||l.expectedRevision!==void 0)&&n(E,"create has no caller supplied id/revision"),i(l.data,E,Object.keys(l.data||{})),Object.keys(l.data).length>32&&n(E,"too many fields");for(let[h,$]of Object.entries(l.data))h==="id"&&n(E,"record identifiers are platform owned"),d(y,h,E),u($,_.parameters,E,_.quota?.action==="allocate")}if(_.quota){let l=i(_.quota,E,["pool","action","units","mode","allocation"]),y=A.quotas.find(R=>R.code===l.pool);y||n(E,"unknown quota pool"),p(_.resourceKey,_.parameters,E),l.action==="allocate"?(i(l,E,["pool","action","units","mode"]),r(l.units,1,1e3,E),(!["committed","reserved"].includes(l.mode)||l.mode==="reserved"&&!y.reservationSeconds)&&n(E,"invalid allocation mode"),(_.operations.length!==1||_.operations[0].operation!=="create"||_.operations[0].resourceCode!==y.allocationResource||_.operations[0].data[y.allocationField]?.from!=="allocation")&&n(E,"allocation must atomically create its bound business record")):["confirm","release"].includes(l.action)?(i(l,E,["pool","action","allocation"]),p(l.allocation,_.parameters,E),_.operations.length&&n(E,"lifecycle owns allocation state; business reference remains immutable")):n(E,"invalid quota action")}else _.operations.length||n(E,"operations required")}let b=A.commands.filter(_=>_.mode==="durable").map(_=>_.execution.handlerCode);return new Set(b).size!==b.length&&n(I,"handler code must be unique"),JSON.parse(JSON.stringify(A))}var nt=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"},Gn=["parentTransitions","childTransitions","fulfilledChildStatuses","lockedParentStatuses"],ui=["amountFieldCode","currencyFieldCode","relationFieldCode","parentFieldCode","rootFieldCode","statusFieldCode","parentRelationValue","childRelationValue"],Bt=e=>!!(e&&typeof e=="object"&&!Array.isArray(e)),Mt=e=>Array.isArray(e)?e.filter(Bt):[],Ce=(e,t)=>{throw new nt(e,t)},Bn=e=>typeof e=="string"&&/^[A-Za-z0-9._:-]{1,128}$/.test(e),Kn=(e,t)=>e<t?-1:e>t?1:0;function qn(e,t="/decimalReservationLifecycle"){if(e===void 0)return;if(!Bt(e)||Object.keys(e).some(i=>!Gn.includes(i))||Gn.some(i=>!Object.prototype.hasOwnProperty.call(e,i)))return Ce(t,"\u5FC5\u987B\u5B8C\u6574\u58F0\u660E\u56DB\u9879\u89C4\u5219\uFF0C\u4E0D\u80FD\u5305\u542B\u672A\u77E5\u5C5E\u6027");let o=i=>{let r=e[i];if(!Array.isArray(r)||r.length>64)return Ce(`${t}/${i}`,"\u72B6\u6001\u8FB9\u6700\u591A 64 \u6761");let c=new Set;return r.map((s,a)=>{let d=`${t}/${i}/${a}`;if(!Bt(s)||Object.keys(s).some(u=>u!=="from"&&u!=="to")||!Bn(s.from)||!Bn(s.to)||s.from===s.to)return Ce(d,"\u72B6\u6001\u8FB9\u5FC5\u987B\u5305\u542B\u4E0D\u540C\u7684\u6709\u6548 from/to");let f=JSON.stringify([s.from,s.to]);return c.has(f)?Ce(d,"\u72B6\u6001\u8FB9\u4E0D\u80FD\u91CD\u590D"):(c.add(f),{from:s.from,to:s.to})}).sort((s,a)=>Kn(s.from,a.from)||Kn(s.to,a.to))},n=i=>{let r=e[i];return!Array.isArray(r)||r.length<1||r.length>16||r.some(c=>!Bn(c))||new Set(r).size!==r.length?Ce(`${t}/${i}`,"\u72B6\u6001\u96C6\u5408\u5FC5\u987B\u5305\u542B 1 \u5230 16 \u4E2A\u4E0D\u91CD\u590D\u7684\u6709\u6548\u72B6\u6001"):[...r].sort(Kn)};return{parentTransitions:o("parentTransitions"),childTransitions:o("childTransitions"),fulfilledChildStatuses:n("fulfilledChildStatuses"),lockedParentStatuses:n("lockedParentStatuses")}}function fi(e,t,o="/config/data/resources"){Mt(e).forEach((n,i)=>{let r=`${o}/${i}/decimalReservationLifecycle`,c=qn(n.decimalReservationLifecycle,r);if(!c)return;let s=Mt(t).map(u=>u.platformAccess?.decimalReservation).filter(u=>Bt(u)&&u.resourceCode===n.code),a=s.find(u=>u.mode==="reserve");if(!a)return Ce(r,"\u9700\u8981\u540C\u8D44\u6E90\u5DF2\u58F0\u660E\u7684 reserve \u52A8\u4F5C\u6620\u5C04");if(ui.some(u=>typeof a[u]!="string")||s.some(u=>ui.some(p=>u[p]!==a[p])))return Ce(r,"\u540C\u8D44\u6E90\u989D\u5EA6\u52A8\u4F5C\u7684\u5B57\u6BB5\u6620\u5C04\u5FC5\u987B\u4E00\u81F4");let d=Mt(n.schema?.fields).find(u=>u.code===a.statusFieldCode);if(d?.type!=="option.single")return Ce(r,"\u989D\u5EA6\u72B6\u6001\u5B57\u6BB5\u5FC5\u987B\u4E3A option.single");let f=new Set(Mt(d.options).map(u=>u.value));for(let u of Gn)if((u==="parentTransitions"||u==="childTransitions"?c[u].flatMap(g=>[g.from,g.to]):c[u]).some(g=>!f.has(g)))return Ce(`${r}/${u}`,"\u72B6\u6001\u5FC5\u987B\u6765\u81EA\u989D\u5EA6\u72B6\u6001\u5B57\u6BB5\u7684\u9009\u9879");if(s.some(u=>u.mode==="reserve"&&Array.isArray(u.eligibleParentStatuses)&&u.eligibleParentStatuses.some(p=>c.lockedParentStatuses.includes(String(p)))))return Ce(`${r}/lockedParentStatuses`,"\u9501\u5B9A\u7236\u72B6\u6001\u4E0D\u80FD\u5141\u8BB8\u65B0\u9884\u7559")})}import{createHash as Gs}from"crypto";var zn=new Set(["option.single","user.single","department.single","resource-ref.single"]),qs=new Set(["option.multiple","cascade.single","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","address","location","json"]),mi=new Set(["option.multiple","cascade.single","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","file","image"]),zs=new Set(["option.single","user.single","department.single","resource-ref.single","signature","address","location"]),Js=new Set([...zn,...mi,"signature","address","location","json"]);function qd(e,t){let o=new Set([...Array.isArray(t?.list?.searchableFields)?t.list.searchableFields:[],...Object.entries(t?.fields||{}).filter(([,n])=>n?.searchable===!0).map(([n])=>n)]);return e.map(n=>Hs(n,o.has(n.code))).sort((n,i)=>n.code.localeCompare(i.code))}function Hs(e,t=!1){let o=e.type==="date-range"||e.type==="datetime-range";if(o&&e.rangeBoundary!=="closed"&&e.rangeBoundary!=="half-open")throw new Error("OPENXIANGDA_NATIVE_DATA_RANGE_BOUNDARY_INVALID");return{code:e.code,type:e.type,nullable:!0,indexed:e.indexed===!0,storage:Zs(e),index:Xs(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 zd(e,t){if(t.type==="subtable")return null;let o=ce(t.code),n=_i(e,t),i=[n?` DEFAULT ${n}`:"",Qs(o,t),Ys(o,t)].join("");return`${o} ${t.storage}${i}`}function Jd(e,t){return _i(e,t)}function Ys(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 Hd(e){return e.type==="serial-number"||Ft(e.type)&&e.type!=="subtable"}function Yd(e,t){return t.filter(o=>o.type==="serial-number").map(o=>{let n=Gt(e,o.code),i=o.serial?.start??1;return`CREATE SEQUENCE IF NOT EXISTS ${n} AS bigint MINVALUE ${i} START WITH ${i} CACHE 1`})}function Xd(e,t){let o=Kt(e);return t.filter(n=>n.type==="serial-number").map(n=>`ALTER SEQUENCE ${Gt(e,n.code)} OWNED BY ${o}.${ce(n.code)}`)}function Zd(e,t){return t.filter(o=>o.type==="serial-number").map(o=>`GRANT USAGE, SELECT ON SEQUENCE ${Gt(e,o.code)} TO "openxiangda_data_api"`)}function Qd(e,t){let o=Kt(e),n=[];for(let i of t){if(i.type==="subtable")continue;let r=ce(i.code),c=ce(ve("idx",e,i.code,i.index));switch(i.index){case"btree":n.push(`CREATE INDEX IF NOT EXISTS ${c} ON ${o} (${r})`);break;case"btree-snapshot-expressions":{let s=ce(ve("idx",e,i.code,"snapshot-value")),a=ce(ve("idx",e,i.code,"snapshot-label"));n.push(`CREATE INDEX IF NOT EXISTS ${s} ON ${o} ((${r} ->> 'value'))`,`CREATE INDEX IF NOT EXISTS ${a} ON ${o} ((${r} ->> 'label'))`);break}case"gin-jsonb-path":n.push(`CREATE INDEX IF NOT EXISTS ${c} ON ${o} USING GIN (${r} jsonb_path_ops)`);break;case"gist-range":n.push(`CREATE INDEX IF NOT EXISTS ${c} ON ${o} USING GIST (${r})`);break;case"gin-trigram":{let s=zn.has(i.type)?`((${r} ->> 'label')) gin_trgm_ops`:`${r} gin_trgm_ops`;n.push(`CREATE INDEX IF NOT EXISTS ${c} ON ${o} USING GIN (${s})`);break}case"none":break}if(i.type==="serial-number"){let s=ce(ve("uidx",e,i.code,"serial"));n.push(`CREATE UNIQUE INDEX IF NOT EXISTS ${s} ON ${o} (${r})`)}}return n}function el(e,t,o,n){let i=Kt(e),r=Kt(t),c=ce(ve("uidx",e,"environment_id","subtable-parent")),s=ce(ve("idx",t,o,n,"subtable-child")),a=ce(ve("fk",t,o,e)),d=ce(o),f=ce(n);return[`CREATE UNIQUE INDEX IF NOT EXISTS ${c} ON ${i} ("tenant_id", "app_code", "environment_key", "id")`,`CREATE INDEX IF NOT EXISTS ${s} ON ${r} ("tenant_id", "app_code", "environment_key", ${d}, ${f}, "id")`,`DO $native_subtable$ BEGIN
|
|
2
|
+
ALTER TABLE ${r}
|
|
3
|
+
ADD CONSTRAINT ${a}
|
|
4
|
+
FOREIGN KEY ("tenant_id", "app_code", "environment_key", ${d})
|
|
5
5
|
REFERENCES ${i} ("tenant_id", "app_code", "environment_key", "id")
|
|
6
6
|
ON DELETE CASCADE;
|
|
7
7
|
EXCEPTION WHEN duplicate_object THEN NULL;
|
|
8
|
-
END $native_subtable$`]}function De(e,...t){return`${e}_${Cs("sha256").update(t.join(":")).digest("hex").slice(0,32)}`}function ae(e){if(!/^[A-Za-z_][A-Za-z0-9_]{0,62}$/.test(e))throw new Error("OPENXIANGDA_NATIVE_IDENTIFIER_INVALID");return`"${e}"`}function Vs(e,t){return e.type==="subtable"?"none":t?"gin-trigram":e.indexed?["date-range","datetime-range"].includes(e.type)?"gist-range":bn.has(e.type)?"btree-snapshot-expressions":Ss.has(e.type)?"gin-jsonb-path":"btree":"none"}function Fs(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 Ds.has(e.type),"jsonb"}}function So(e,t){if(Tt(t.type)&&t.type!=="subtable")return"'[]'::jsonb";if(t.type!=="serial-number")return"";let o=Ro(t.serial?.prefix||""),n=t.serial?.digits??6;return`(${o} || lpad(nextval(${Ro(Dt(e,t.code))})::text, ${n}, '0'))`}function vs(e,t){return Co.has(t.type)?` CHECK (${e} IS NULL OR jsonb_typeof(${e}) = 'array')`:ws.has(t.type)?` CHECK (${e} IS NULL OR jsonb_typeof(${e}) = 'object')`:""}function wt(e){return`"app_data".${ae(e)}`}function Dt(e,t){let o=De("seq",e,t);return`"app_data".${ae(o)}`}function Ro(e){return`'${e.replace(/'/g,"''")}'`}var wo=new Set(["option.single","option.multiple","user.single","user.multiple","department.single","department.multiple","resource-ref.single","resource-ref.multiple"]),Ps=new Set([...wo,"cascade.single","cascade.multiple","file","image","signature","address","location","json"]),Do=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,Ls=new Set(["__proto__","prototype","constructor"]),yn=class extends Error{constructor(o){super("OPENXIANGDA_SCOPE_PROJECTION_FIELD_PATH_INVALID");this.path=o;this.name="NativeScopeSourceFieldPathV2Error"}path;code="OPENXIANGDA_SCOPE_PROJECTION_FIELD_PATH_INVALID"};function ot(e,t){let o=ko(e);if(!o)return null;let n=t.get(o[0]);if(!n)return null;let i=o.slice(1).join(".")||void 0;return{field:n,...i?{valuePath:i}:{}}}function Nn(e){return!!(e&&e.field.type==="user.single"&&e.valuePath==="value")}function $o(e,t,o){if(!e||!t||!xs(e))return!1;let{field:n,valuePath:i}=e;if(!i)return t.valueType==="uuid"?n.type==="uuid":["text.short","text.long","serial-number"].includes(n.type);if(i==="value")return!(t.valueSourceResourceCode&&n.type.startsWith("resource-ref.")&&n.source?.resourceCode!==t.valueSourceResourceCode);let s=i.slice(9),r=o.get(n.source?.resourceCode||"")?.get(s)?.type;return t.valueType==="uuid"?r==="uuid":["text.short","text.long","serial-number"].includes(r||"")}function gc(e,t){let o=ko(t);if(!o)throw new yn(String(t||""));let n=e;for(let i of o){if(!n||typeof n!="object"||!Object.prototype.hasOwnProperty.call(n,i))return;n=n[i]}return n}function xs(e){let{field:t,valuePath:o}=e;if(!o)return!Ps.has(t.type);if(o==="value")return wo.has(t.type);if(!o.startsWith("snapshot."))return!1;let n=o.slice(9);return Do.test(n)&&t.type.startsWith("resource-ref.")&&!!t.source?.snapshotFields?.includes(n)}function ko(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=>!Do.test(o)||Ls.has(o))||t.length===2&&t[1]!=="value"||t.length===3&&t[1]!=="snapshot"?null:t}var js=new Set(["option.single","user.single","department.single","resource-ref.single"]),Ws=new Set(["text.short","text.long","text.rich","number.integer","number.decimal","boolean","date","time","datetime","uuid","serial-number"]),Ms=new Set(["value","label","description","color"]),Us=new Set(["avatarUrl","employeeNo","title","mobile","email"]),Bs=new Set(["fullPath","parent.value","parent.label"]),Ks=new Set(["country.value","country.label","province.value","province.label","city.value","city.label","district.value","district.label","street.value","street.label","detail","fullAddress"]),Gs=new Set(["longitude","latitude","accuracy"]),qs=new Set(["address","name","province","city","district","source"]);function Ec(e){let t=new Map(e.map(o=>[o.code,new Map(o.schema.fields.map(n=>[n.code,n]))]));return e.map(o=>({...o,schema:{...o.schema,fields:o.schema.fields.map(n=>{let i=Js(n,t);if(!Object.keys(i).length)return n;let s={...n};return Object.defineProperty(s,"queryPathTypes",{configurable:!1,enumerable:!1,writable:!1,value:Object.freeze(i)}),s})}}))}function Ic(e,t){if(js.has(e.type)&&Ms.has(t)||e.type==="user.single"&&Us.has(t)||e.type==="department.single"&&Bs.has(t))return it(t);if(e.type==="resource-ref.single"){let o=e.queryPathTypes?.[t];return o?{parts:t.split("."),type:o}:null}if(e.type==="address"&&Ks.has(t))return it(t);if(e.type==="location"){if(Gs.has(t))return{parts:[t],type:"number.decimal"};if(qs.has(t))return it(t);if(t==="capturedAt")return{parts:[t],type:"datetime"}}return null}function Js(e,t){if(e.type!=="resource-ref.single"||!e.source)return{};let o=t.get(e.source.resourceCode);return o?Object.fromEntries((e.source.snapshotFields||[]).flatMap(n=>{let i=o.get(n);return i?[[`snapshot.${n}`,Ws.has(i.type)?i.type:"json"]]:[]})):{}}function it(e){return{parts:e.split("."),type:"text.short"}}var Vo=["exact-v1","nfkc-space-v1","nfkc-upper-ascii-v1"],yc=256,st=class extends Error{constructor(o,n){super(`\u6761\u4EF6\u552F\u4E00\u952E\u58F0\u660E\u65E0\u6548\uFF1A${n}\uFF08${o}\uFF09`);this.pointer=o;this.reason=n}pointer;reason;code="NATIVE_UNIQUE_KEY_INVALID"},Tn=e=>!!(e&&typeof e=="object"&&!Array.isArray(e)),oe=(e,t)=>{throw new st(e,t)},$t=(e,t)=>e<t?-1:e>t?1:0,kt=(e,t,o)=>{Object.keys(e).some(n=>!t.includes(n))&&oe(o,"\u4E0D\u652F\u6301\u672A\u77E5\u5C5E\u6027")};function Fo(e,t,o="/uniqueKeys"){if(e===void 0)return;if(!Array.isArray(e)||e.length>8)return oe(o,"\u6BCF\u8D44\u6E90\u6700\u591A 8 \u6761\u89C4\u5219");let n=new Map(t.map(s=>[s.code,s])),i=new Set;return e.map((s,a)=>{let r=`${o}/${a}`;if(!Tn(s))return oe(r,"\u89C4\u5219\u5FC5\u987B\u662F\u5BF9\u8C61");if(kt(s,["code","fields","when"],r),typeof s.code!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(s.code)||s.code.length>20||i.has(s.code))return oe(`${r}/code`,"\u9700\u8981\u4E0D\u91CD\u590D\u4E14\u4E0D\u8D85\u8FC7 20 \u5B57\u7B26\u7684 lower-kebab-case \u6807\u8BC6");if(i.add(s.code),!Array.isArray(s.fields)||s.fields.length<1||s.fields.length>4)return oe(`${r}/fields`,"\u5FC5\u987B\u9009\u62E9 1 \u5230 4 \u4E2A\u5B57\u6BB5");let c=new Set,l=s.fields.map((g,E)=>{let A=`${r}/fields/${E}`;if(!Tn(g))return oe(A,"\u5B57\u6BB5\u5FC5\u987B\u662F\u5BF9\u8C61");kt(g,["fieldCode","normalizer"],A);let b=n.get(g.fieldCode);if(!b||!["text.short","uuid","option.single","resource-ref.single"].includes(b.type)||c.has(g.fieldCode))return oe(`${A}/fieldCode`,"\u9700\u8981\u4E0D\u91CD\u590D\u7684\u77ED\u6587\u672C\u3001UUID\u3001\u5355\u9009\u6216\u5355\u8BB0\u5F55\u5F15\u7528\u5B57\u6BB5");c.add(g.fieldCode);let I=g.normalizer===void 0?"exact-v1":g.normalizer;return!Vo.includes(I)||b.type!=="text.short"&&I!=="exact-v1"?oe(`${A}/normalizer`,"\u5F52\u4E00\u5316\u65B9\u5F0F\u4E0D\u652F\u6301\u6216\u4E0E\u5B57\u6BB5\u7C7B\u578B\u4E0D\u7B26"):{fieldCode:b.code,normalizer:I}}).sort((g,E)=>$t(g.fieldCode,E.fieldCode)),p=s.when===void 0?[]:s.when;if(!Array.isArray(p)||p.length>4)return oe(`${r}/when`,"\u6700\u591A 4 \u4E2A\u5408\u53D6\u6761\u4EF6");let d=new Set,f=p.map((g,E)=>{let A=`${r}/when/${E}`;if(!Tn(g))return oe(A,"\u6761\u4EF6\u5FC5\u987B\u662F\u5BF9\u8C61");let b=n.get(g.fieldCode);if(!b)return oe(`${A}/fieldCode`,"\u5B57\u6BB5\u4E0D\u5B58\u5728");let I;if(g.operator==="empty"||g.operator==="nonempty"){if(kt(g,["fieldCode","operator"],A),b.type!=="text.short")return oe(A,"\u7A7A\u503C\u6761\u4EF6\u4EC5\u652F\u6301\u77ED\u6587\u672C");I={fieldCode:b.code,operator:g.operator}}else if(g.operator==="in"||g.operator==="notIn"){kt(g,["fieldCode","operator","values"],A);let u=new Set((b.options??[]).map(N=>N.value));if(b.type!=="option.single"||!Array.isArray(g.values)||g.values.length<1||g.values.length>16||g.values.some(N=>typeof N!="string"||N.length<1||N.length>128||!u.has(N))||new Set(g.values).size!==g.values.length)return oe(A,"\u96C6\u5408\u6761\u4EF6\u9700\u8981 1 \u5230 16 \u4E2A\u4E0D\u91CD\u590D\u7684\u5DF2\u58F0\u660E\u5355\u9009\u503C");I={fieldCode:b.code,operator:g.operator,values:[...g.values].sort($t)}}else return oe(`${A}/operator`,"\u53EA\u652F\u6301 empty\u3001nonempty\u3001in \u548C notIn");let _=JSON.stringify(I);return d.has(_)?oe(A,"\u6761\u4EF6\u4E0D\u80FD\u91CD\u590D"):(d.add(_),I)}).sort((g,E)=>$t(JSON.stringify(g),JSON.stringify(E)));return{code:s.code,fields:l,when:f}}).sort((s,a)=>$t(s.code,a.code))}var On={type:"string",pattern:"^[A-Za-z_][A-Za-z0-9_]{0,62}$"},Nc={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:On,normalizer:{enum:[...Vo]}}}},when:{type:"array",maxItems:4,uniqueItems:!0,items:{oneOf:[{type:"object",additionalProperties:!1,required:["fieldCode","operator"],properties:{fieldCode:On,operator:{enum:["empty","nonempty"]}}},{type:"object",additionalProperties:!1,required:["fieldCode","operator","values"],properties:{fieldCode:On,operator:{enum:["in","notIn"]},values:{type:"array",minItems:1,maxItems:16,uniqueItems:!0,items:{type:"string",minLength:1,maxLength:128}}}}]}}}}};var vo={"openxiangda.workflow.instance.completed.v2":"commit","openxiangda.workflow.instance.rejected.v2":"release","openxiangda.workflow.instance.withdrawn.v2":"release"};function Po(e,t){let o=()=>{throw new Error("NATIVE_EVENT_DECIMAL_RESERVATION_INVALID")},n=f=>!f||typeof f!="object"||Array.isArray(f)?o():f,i=n(e);if(Object.keys(i).some(f=>!["resourceCode","workflowCode","outcomes"].includes(f))||typeof i.resourceCode!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(i.resourceCode)||typeof i.workflowCode!="string"||!/^[A-Za-z0-9._:-]{1,128}$/.test(i.workflowCode)||t.execution!==void 0||!Array.isArray(i.outcomes)||!i.outcomes.length||i.outcomes.length>3)return o();let s=t.resources.find(f=>f.code===i.resourceCode),a=t.reservations.find(f=>f.mode==="reserve"&&f.resourceCode===i.resourceCode),r=t.workflows.find(f=>f.code===i.workflowCode);if(!s||!a||!r||r.resourceCode!==s.code)return o();let c=s.fields.find(f=>f.code===a.statusFieldCode);if(c?.type!=="option.single")return o();let l=new Set(c.options?.map(f=>f.value)),p=new Set,d=i.outcomes.map(f=>{let g=n(f),E=g.eventType;return Object.keys(g).some(A=>!["eventType","mode","eligibleChildStatuses"].includes(A))||typeof E!="string"||!Object.prototype.hasOwnProperty.call(vo,E)||!t.eventTypes.includes(E)||p.has(E)||g.mode!==vo[E]||!Array.isArray(g.eligibleChildStatuses)||!g.eligibleChildStatuses.length||g.eligibleChildStatuses.length>16||new Set(g.eligibleChildStatuses).size!==g.eligibleChildStatuses.length||g.eligibleChildStatuses.some(A=>typeof A!="string"||!/^[A-Za-z0-9._:-]{1,128}$/.test(A)||!l.has(A))?o():(p.add(E),{eventType:E,mode:g.mode,eligibleChildStatuses:[...g.eligibleChildStatuses].sort()})}).sort((f,g)=>f.eventType.localeCompare(g.eventType));return{resourceCode:i.resourceCode,workflowCode:i.workflowCode,outcomes:d}}function Lo(e,t){let o=n=>Array.isArray(n)?n.filter(i=>i&&typeof i=="object"&&!Array.isArray(i)):[];return{eventTypes:Array.isArray(t.eventTypes)?t.eventTypes:[],execution:t.execution,resources:o(e.data?.resources).map(n=>({code:n.code,fields:o(n.schema?.fields).map(i=>({code:i.code,type:i.type,options:o(i.options).map(s=>({value:s.value}))}))})),reservations:o(e.backend?.operations).flatMap(n=>n.platformAccess?.decimalReservation?[n.platformAccess.decimalReservation]:[]),workflows:o(e.workflows?.definitions).map(n=>({code:n.definition?.code,resourceCode:n.definition?.subject?.resourceCode}))}}var hn=class extends Error{constructor(o,n){super(n);this.pointer=o}pointer;code="NATIVE_EVENT_ACTION_INVALID"};function xo(e,t,o="/events/subscriptions"){if(e.execution===void 0)return;let n=(A,b)=>{throw new hn(`${o}${A}`,b)},i=(A,b,I)=>((!A||typeof A!="object"||Array.isArray(A)||Object.keys(A).some(_=>!I.includes(_)))&&n(b,"Invalid action object or unsupported property"),A),s=i(e.execution,"/execution",["kind","version","operations"]);(s.kind!=="native-data"||s.version!==1)&&n("/execution","Expected native-data version 1"),e.platformAccess&&n("/platformAccess","Native actions do not use application runtime capabilities"),(!Array.isArray(e.eventTypes)||!e.eventTypes.length||e.eventTypes.some(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 r=new Map(t.map(A=>[A.code,A])),c=a.map(A=>{let b=r.get(A);return b||n("/filter/resourceCodes","Unknown source resource"),new Set((b.schema?.fields||[]).map(I=>I.code))}),l=new Set(e.payload?.fields||[]),p=e.payload?.includeChanges===!0,d=(A,b)=>{let I=i(A,b,["source","path","value"]);if(I.source==="literal"){(!Object.hasOwn(I,"value")||Object.hasOwn(I,"path"))&&n(b,"Literal binding requires only value");let y;try{y=JSON.stringify(I.value)}catch{n(b,"Literal must be JSON")}return(y===void 0||Buffer.byteLength(y)>65536)&&n(b,"Literal is too large or not JSON"),{source:"literal",value:JSON.parse(y)}}(I.source!=="event"||typeof I.path!="string"||Object.hasOwn(I,"value"))&&n(b,"Expected a literal or event binding");let _=I.path.split(".");(_.length>8||_.some(y=>!/^[A-Za-z0-9_-]+$/.test(y)||["__proto__","prototype","constructor"].includes(y)))&&n(b,"Invalid event path");let u=/^data\.projection\.([A-Za-z][A-Za-z0-9_]{0,62})$/.exec(I.path),N=/^data\.changes\.([A-Za-z][A-Za-z0-9_]{0,62})\.(before|after)$/.exec(I.path);if(u||N){let y=(u||N)[1];c.some(O=>!O.has(y))&&n(b,"Source field must exist on every filtered resource"),l.add(y),N&&(p=!0)}else["id","time","type","subject","data.recordId","data.revision","data.operation","data.resourceCode"].includes(I.path)||n(b,"Event path is not part of the data event contract");return{source:"event",path:I.path}};(!Array.isArray(s.operations)||s.operations.length<1||s.operations.length>16)&&n("/execution/operations","Expected 1 to 16 operations");let f={},g=s.operations.map((A,b)=>{let I=`/execution/operations/${b}`,_=i(A,I,["operation","resourceCode","data","id","expectedRevision"]);["create","update","delete"].includes(_.operation)||n(I,"Unsupported Native operation");let u=r.get(_.resourceCode);u||n(I,"Unknown action target resource");let N=new Map((u.schema?.fields||[]).map(O=>[O.code,O])),y=_.data===void 0?{}:i(_.data,`${I}/data`,[...N.keys()]);return Object.keys(y).length>32&&n(I,"Maximum 32 mapped fields per operation"),_.operation==="create"&&(_.id!==void 0||_.expectedRevision!==void 0)&&n(I,"Create does not accept id or expectedRevision"),_.operation==="delete"&&_.data!==void 0&&n(I,"Delete does not accept data"),Object.keys(y).some(O=>N.get(O)?.type==="serial-number")&&n(I,"Generated fields cannot be assigned"),f[_.resourceCode]=X(u),{operation:_.operation,resourceCode:_.resourceCode,..._.operation==="create"?{}:{id:d(_.id,`${I}/id`),expectedRevision:d(_.expectedRevision,`${I}/expectedRevision`)},..._.operation==="delete"?{}:{data:Object.fromEntries(Object.entries(y).map(([O,h])=>[O,d(h,`${I}/data/${O}`)]))}}});(l.size>32||[...l].some(A=>c.some(b=>!b.has(A))))&&n("/payload/fields","Payload must contain at most 32 declared source fields");let E={kind:"native-data",version:1,operations:g,resourceDigests:f};return Buffer.byteLength(JSON.stringify(E))>65536&&n("/execution","Action plan exceeds 64 KiB"),{execution:{...E,digest:X(E)},payload:{includeChanges:p,fields:[...l].sort()}}}function $e(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function Wo(e,t){if(e?.instanceCommands===void 0)return[];let o=$e(e.instanceCommands);if(!o||!Object.keys(o).length||Object.keys(o).some(i=>!["withdraw","terminate"].includes(i)))return["WORKFLOW_INSTANCE_COMMAND_POLICIES_INVALID"];let n=[];for(let[i,s]of Object.entries(o)){let a=$e(s),r=i==="withdraw"?["beforeFact"]:["beforeFact","capability"];if(!a||Object.keys(a).some(c=>!r.includes(c))){n.push(`WORKFLOW_INSTANCE_COMMAND_POLICY_INVALID:${i}`);continue}if(i==="terminate"){let c=a.capability;(typeof c!="string"||c.length>255||!/^app:[a-z][a-z0-9]*(?:-[a-z0-9]+)*:[A-Za-z0-9:._-]+$/.test(c)||t&&(!c.startsWith(`app:${t.appCode}:`)||!t.capabilities.includes(c)))&&n.push("WORKFLOW_INSTANCE_TERMINATE_CAPABILITY_INVALID")}if(i==="withdraw"||a.beforeFact!==void 0){let c=a.beforeFact,l=$e(e.inputSchema),p=$e($e(l?.properties)?.[c]),d=$e($e(e.subject)?.factProjection)?.[c],f=t?.fields.get(d);(typeof c!="string"||!/^[A-Za-z][A-Za-z0-9_]{0,62}$/.test(c)||!Array.isArray(l?.required)||!l.required.includes(c)||p?.type!=="string"||p?.format!=="date-time"||typeof d!="string"||t&&(f?.type!=="datetime"||f.nullable===!0))&&n.push(`WORKFLOW_INSTANCE_COMMAND_DEADLINE_FACT_INVALID:${i}`)}}return n}function Cc(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 jo(e){if(typeof e!="string")return null;let t=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,3}))?(Z|[+-]\d{2}:\d{2})$/.exec(e);if(!t)return null;let[,o,n,i,s,a,r]=t,c=t[8],l=new Date(Date.UTC(Number(o),Number(n),0)).getUTCDate();if(Number(n)<1||Number(n)>12||Number(i)<1||Number(i)>l||Number(s)>23||Number(a)>59||Number(r)>59||c!=="Z"&&(Number(c.slice(1,3))>23||Number(c.slice(4))>59))return null;let p=Date.parse(e);return Number.isFinite(p)?p:null}function Sc(e,t,o,n){let i=e?.[t];if(!i||t==="terminate"&&i.beforeFact===void 0)return null;let s=i.beforeFact,a=$e(o),r=s&&a&&Object.hasOwn(a,s)?jo(a[s]):null,c=n instanceof Date?n.getTime():jo(n);return r===null||c===null||!Number.isFinite(c)?"WORKFLOW_V2_CANCELLATION_DEADLINE_INVALID":c<r?null:"WORKFLOW_V2_CANCELLATION_DEADLINE_PASSED"}var rt="openxiangda.workflow.step.requested.v2",Bo=[rt,"openxiangda.workflow.step.result_received.v2","openxiangda.workflow.step.completed.v2","openxiangda.workflow.step.continuation_failed.v2"],Sn=16384,zs=2048,Dc="steps",wn=/^[A-Za-z][A-Za-z0-9_-]{0,127}$/,Ko=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,Pe=new Set(["__proto__","prototype","constructor"]),B=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&[Object.prototype,null].includes(Object.getPrototypeOf(e)),Go=e=>{try{let t=JSON.stringify(e);return t===void 0?1/0:new TextEncoder().encode(t).length}catch{return 1/0}},Je=(e,t,o=0)=>{if(o>32)return!1;if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((s,a)=>Je(s,t[a],o+1));if(!B(e)||!B(t))return!1;let n=Object.keys(e).filter(s=>e[s]!==void 0),i=Object.keys(t).filter(s=>t[s]!==void 0);return n.length===i.length&&n.every(s=>Object.hasOwn(t,s)&&Je(e[s],t[s],o+1))};function Rn(e,t){let o=0,n=(i,s)=>++o>1e4||s>8?!1:i===null||typeof i=="boolean"||typeof i=="string"?!0:typeof i=="number"?Number.isFinite(i):Array.isArray(i)?i.length<=200&&i.every(a=>n(a,s+1)):B(i)&&Object.keys(i).length<=32&&Object.keys(i).every(a=>!Pe.has(a))&&Object.values(i).every(a=>n(a,s+1));return Go(e)<=t&&n(e,0)}function Ys(e){return!B(e)||Object.keys(e).some(t=>!["executionId","handlerVersion","inputDigest","expectedFactRevision","output","receipt"].includes(t))?!1:/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/i.test(e.executionId||"")&&Number.isSafeInteger(e.handlerVersion)&&e.handlerVersion>=1&&e.handlerVersion<=1e6&&/^[a-f0-9]{64}$/.test(e.inputDigest||"")&&Number.isSafeInteger(e.expectedFactRevision)&&e.expectedFactRevision>=0&&B(e.output)&&Rn(e.output,Sn)&&(e.receipt===void 0||B(e.receipt)&&Rn(e.receipt,zs))}function $c(e){return B(e)&&Object.keys(e).every(t=>["executionId","nodeId","handlerCode","handlerVersion","mode","input","inputDigest","expectedFactRevision"].includes(t))&&typeof e.nodeId=="string"&&wn.test(e.nodeId)&&!Pe.has(e.nodeId)&&typeof e.handlerCode=="string"&&/^[a-z][a-z0-9-]{0,100}$/.test(e.handlerCode)&&e.handlerCode.endsWith(`-v${e.handlerVersion}`)&&["pure","reconciled-effect"].includes(e.mode)&&Ys({executionId:e.executionId,handlerVersion:e.handlerVersion,inputDigest:e.inputDigest,expectedFactRevision:e.expectedFactRevision,output:e.input})}function Vt(e,t,o=Sn){if(!Rn(t,o))return!1;let n=1e4,i=(s,a,r)=>{if(--n<0||r>8||!B(s))return!1;let c=a===null?"null":Array.isArray(a)?"array":typeof a=="number"&&Number.isSafeInteger(a)?"integer":typeof a,l=Array.isArray(s.type)?s.type:[s.type];if(!l.includes(c)&&!(c==="integer"&&l.includes("number"))||s.enum!==void 0&&(!Array.isArray(s.enum)||!s.enum.some(p=>Je(p,a)))||Object.hasOwn(s,"const")&&!Je(s.const,a))return!1;if(typeof a=="number")return Number.isFinite(a)&&(s.minimum===void 0||a>=s.minimum)&&(s.maximum===void 0||a<=s.maximum);if(typeof a=="string"){let p=Array.from(a).length;return(s.minLength===void 0||p>=s.minLength)&&(s.maxLength===void 0||p<=s.maxLength)}return Array.isArray(a)?a.length<=s.maxItems&&(s.minItems===void 0||a.length>=s.minItems)&&a.every(p=>i(s.items,p,r+1)):B(a)?!B(s.properties)||Object.keys(a).some(p=>Pe.has(p)||!Object.hasOwn(s.properties,p))||(Array.isArray(s.required)?s.required:[]).some(p=>!Object.hasOwn(a,p))||s.minProperties!==void 0&&Object.keys(a).length<s.minProperties||s.maxProperties!==void 0&&Object.keys(a).length>s.maxProperties?!1:Object.entries(a).every(([p,d])=>i(s.properties[p],d,r+1)):a===null||typeof a=="boolean"};return i(e,t,0)}function Hs(e){return typeof e=="string"&&e.length<=256&&e.split(".").length<=8&&e.split(".").every(t=>wn.test(t)&&!Pe.has(t))}function Ft(e){let t=0,o=(n,i)=>{if(!B(n)||i>6||++t>256||Object.keys(n).some(r=>!["type","title","description","properties","required","additionalProperties","items","maxItems","minItems","maxLength","minLength","minimum","maximum","enum","const","maxProperties","minProperties"].includes(r)))return!1;let s=Array.isArray(n.type)?n.type:[n.type];if(!s.length||s.length>2||s.some(r=>!["object","array","string","integer","number","boolean","null"].includes(r))||s.length>1&&(!s.includes("null")||new Set(s).size!==s.length))return!1;for(let r of["title","description"])if(n[r]!==void 0&&(typeof n[r]!="string"||n[r].length>2e3))return!1;for(let r of["minimum","maximum"])if(n[r]!==void 0&&(typeof n[r]!="number"||!Number.isFinite(n[r])))return!1;for(let[r,c]of[["maxItems",200],["minItems",200],["maxLength",16384],["minLength",16384],["maxProperties",32],["minProperties",32]])if(n[r]!==void 0&&(!Number.isSafeInteger(n[r])||n[r]<0||n[r]>c))return!1;for(let[r,c]of[["minimum","maximum"],["minItems","maxItems"],["minLength","maxLength"],["minProperties","maxProperties"]])if(n[r]!==void 0&&n[c]!==void 0&&n[r]>n[c])return!1;if(["properties","required","additionalProperties","maxProperties","minProperties"].some(r=>n[r]!==void 0)&&!s.includes("object")||["items","maxItems","minItems"].some(r=>n[r]!==void 0)&&!s.includes("array")||["maxLength","minLength"].some(r=>n[r]!==void 0)&&!s.includes("string")||["minimum","maximum"].some(r=>n[r]!==void 0)&&!s.some(r=>r==="integer"||r==="number")||n.enum!==void 0&&(!Array.isArray(n.enum)||!n.enum.length||n.enum.length>100)||s.includes("object")&&(!B(n.properties)||n.additionalProperties!==!1||Object.keys(n.properties).length>32||Object.keys(n.properties).some(r=>!Ko.test(r)||Pe.has(r))||n.required!==void 0&&(!Array.isArray(n.required)||new Set(n.required).size!==n.required.length||n.required.some(r=>typeof r!="string"||!Object.hasOwn(n.properties,r)))||n.minProperties!==void 0&&n.minProperties>Object.keys(n.properties).length||n.maxProperties!==void 0&&n.maxProperties<(n.required?.length||0)||!Object.values(n.properties).every(r=>o(r,i+1)))||s.includes("array")&&(!Number.isSafeInteger(n.maxItems)||!o(n.items,i+1)))return!1;let a={...n};return delete a.enum,delete a.const,!(n.enum!==void 0&&(!n.enum.every(r=>Vt(a,r))||n.enum.some((r,c)=>n.enum.slice(0,c).some(l=>Je(r,l))))||Object.hasOwn(n,"const")&&!Vt(a,n.const))};return B(e)&&e.type==="object"&&Go(e)<=Sn&&o(e,0)}function vt(e){let t=Object.fromEntries(Object.values(e.nodes||{}).filter(o=>o?.kind==="action").map(o=>[o.id,o.outputSchema]));return Object.keys(t).length?{...e.inputSchema,properties:{...e.inputSchema?.properties,steps:{type:"object",additionalProperties:!1,properties:t}}}:e.inputSchema||{}}function qo(e,t){let o=e;for(let n of t.split(".")){if(!B(o?.properties)||!Object.hasOwn(o.properties,n))return;o=o.properties[n]}return B(o)?o:void 0}var Mo=(e,t)=>!!qo(e,t);function kc(e){return B(e)&&Object.keys(e).every(t=>["version","mode","inputSchema","outputSchema"].includes(t))&&Number.isSafeInteger(e.version)&&e.version>=1&&e.version<=1e6&&["pure","reconciled-effect"].includes(e.mode)&&Ft(e.inputSchema)&&Ft(e.outputSchema)}function Uo(e){return e.kind==="approval"?[e.onApprove,e.onReject]:e.kind==="condition"?[...Array.isArray(e.branches)?e.branches.map(t=>t.target):[],e.otherwise]:e.kind==="cc"||e.kind==="action"?[e.next]:[]}function Cn(e,t=0){return!B(e)||t>16?[]:e.op==="path"?typeof e.path=="string"?[e.path]:[]:["left","right","value"].flatMap(o=>Cn(e[o],t+1)).concat(Array.isArray(e.values)?e.values.flatMap(o=>Cn(o,t+1)):[])}function Pt(e,t){if(!B(e)||!B(e.nodes))return["WORKFLOW_STEP_DEFINITION_INVALID"];let o=e.nodes,n=Object.entries(o).filter(([,r])=>r?.kind==="action");if(!n.length)return[];let i=[];Object.hasOwn(e.inputSchema?.properties||{},"steps")&&i.push("WORKFLOW_STEP_FACT_NAMESPACE_RESERVED");let s=vt(e);for(let[r,c]of n){(Object.keys(c).some(d=>!["id","kind","title","next","handler","inputSchema","outputSchema","inputs"].includes(d))||c.id!==r||!wn.test(r)||Pe.has(r)||typeof c.title!="string"||!c.title.trim()||c.title.length>255||typeof c.next!="string"||!Object.hasOwn(o,c.next))&&i.push(`WORKFLOW_STEP_NODE_INVALID:${r}`);let l=c.handler;(!B(l)||Object.keys(l).some(d=>!["code","version","mode"].includes(d))||!Number.isSafeInteger(l.version)||l.version<1||l.version>1e6||!/^[a-z][a-z0-9-]{0,100}$/.test(l.code||"")||!String(l.code).endsWith(`-v${l.version}`)||!["pure","reconciled-effect"].includes(l.mode))&&i.push(`WORKFLOW_STEP_HANDLER_INVALID:${r}`);let p=Ft(c.inputSchema);if((!p||!Ft(c.outputSchema))&&i.push(`WORKFLOW_STEP_SCHEMA_INVALID:${r}`),!B(c.inputs)||Object.keys(c.inputs).length>32){i.push(`WORKFLOW_STEP_INPUTS_INVALID:${r}`);continue}for(let d of Array.isArray(c.inputSchema?.required)?c.inputSchema.required:[])Object.hasOwn(c.inputs,d)||i.push(`WORKFLOW_STEP_INPUT_REQUIRED:${r}:${d}`);for(let[d,f]of Object.entries(c.inputs)){if(!Ko.test(d)||Pe.has(d)||!Object.hasOwn(c.inputSchema?.properties||{},d)||!B(f)){i.push(`WORKFLOW_STEP_INPUT_INVALID:${r}:${d}`);continue}if(f.source==="literal")(!p||Object.keys(f).some(g=>!["source","value"].includes(g))||!Object.hasOwn(f,"value")||!Vt(c.inputSchema.properties[d],f.value))&&i.push(`WORKFLOW_STEP_LITERAL_INVALID:${r}:${d}`);else if(f.source!=="fact"||Object.keys(f).some(g=>!["source","path"].includes(g))||!Hs(f.path)||!Mo(s,f.path))i.push(`WORKFLOW_STEP_FACT_PATH_INVALID:${r}:${d}`);else if(p){let g=qo(s,f.path),E=c.inputSchema.properties[d],A=Array.isArray(g.type)?g.type:[g.type],b=Array.isArray(E.type)?E.type:[E.type];A.some(I=>!b.includes(I)&&!(I==="integer"&&b.includes("number")))&&i.push(`WORKFLOW_STEP_FACT_TYPE_MISMATCH:${r}:${d}`)}}}let a=(r,c)=>{let l=new Set,p=[e.startAt||""];for(;p.length&&l.size<=200;){let d=p.shift();if(!(d===c||l.has(d)||!o[d])){if(d===r)return!0;l.add(d),p.push(...Uo(o[d]))}}return!1};for(let[r,c]of Object.entries(o)){if(!B(c))continue;let l=c.kind==="action"?Object.values(c.inputs||{}).flatMap(d=>d?.source==="fact"?[d.path]:[]):(Array.isArray(c.branches)?c.branches:[]).flatMap(d=>Cn(d?.when)),p=t?.bindings?.[c.binding];p&&l.push(...[p.inputPath,p.departmentIdFrom,p.resourceIdFrom,p.scope?.valueFrom].filter(d=>typeof d=="string"));for(let d of l.filter(f=>typeof f=="string"&&f.startsWith("steps."))){let f=d.split(".")[1];(o[f]?.kind!=="action"||f===r||!Mo(s,d)||a(r,f))&&i.push(`WORKFLOW_STEP_OUTPUT_NOT_AVAILABLE:${r}:${d}`)}}if(t)for(let[,r]of n){let c=new Set,l=[r.next];for(;l.length&&c.size<=200;){let p=l.shift();if(c.has(p)||!B(o[p]))continue;c.add(p);let d=o[p];if(!(d.kind==="action"||d.kind==="end")){if(d.kind==="approval"){let f=t.bindings?.[d.binding];f&&["application_provider","initiator_select"].includes(f.provider)&&i.push(`WORKFLOW_STEP_NEXT_PROVIDER_REQUIRES_PREPARED_RESULT:${p}`);continue}l.push(...Uo(d))}}}return[...new Set(i)]}function Vc(e,t){let o={};for(let[n,i]of Object.entries(e.inputs)){let s=i.source==="literal"?i.value:i.path.split(".").reduce((a,r)=>B(a)&&Object.hasOwn(a,r)?a[r]:void 0,t);s!==void 0&&(o[n]=s)}if(!Vt(e.inputSchema,o))throw new Error("WORKFLOW_STEP_INPUT_SCHEMA_INVALID");return o}function Jo(e,t,o){let n=Dn(e),i=[];Object.keys(n).length&&!o&&i.push("WORKFLOW_STEP_BACKEND_REQUIRED");for(let s of Object.keys(n)){let a=t.find(r=>r.code===s);(!a||a.execution||a.action||!Array.isArray(a.eventTypes)||a.eventTypes.length!==1||a.eventTypes[0]!==rt||!B(a.filter)||Object.keys(a.filter).length!==1||!B(a.filter.workflowStep)||Object.keys(a.filter.workflowStep).length!==1||a.filter.workflowStep.handlerCode!==s||!B(a.payload)||a.payload.includeChanges!==!1||!Array.isArray(a.payload.fields)||a.payload.fields.length)&&i.push(`WORKFLOW_STEP_SUBSCRIPTION_INVALID:${s}`)}for(let s of t)(s.eventTypes?.includes(rt)&&!n[s.code]||s.filter?.workflowStep&&!n[s.code])&&i.push(`WORKFLOW_STEP_HANDLER_NOT_DECLARED:${s.code}`);return i}function Dn(e){let t={};for(let o of e){let n=Pt(o);if(n.length)throw new Error(n.join("; "));for(let i of Object.values(o.nodes||{})){if(i.kind!=="action")continue;let s={version:i.handler.version,mode:i.handler.mode,inputSchema:i.inputSchema,outputSchema:i.outputSchema},a=t[i.handler.code];if(a&&!Je(a,s))throw new Error(`WORKFLOW_STEP_HANDLER_CONTRACT_CONFLICT:${i.handler.code}`);t[i.handler.code]=s}}return t}var de=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},Le=(e,t)=>typeof e=="string"&&!!e.trim()&&e.length<=t,Xs=/^[A-Za-z][A-Za-z0-9_-]*(?:\.[A-Za-z][A-Za-z0-9_-]*){0,15}$/,$n=e=>typeof e=="string"&&e.length<=256&&Xs.test(e)&&!e.split(".").some(t=>["__proto__","prototype","constructor"].includes(t));function xt(e,t){let o=de(e),n=!0;for(let i of t.split(".")){n&&=Array.isArray(o.required)&&o.required.includes(i);let s=de(o.properties)[i];if(!s||typeof s!="object")return null;o=de(s)}return{schema:o,required:n}}function zo(e){let t=new Set,o=[],n=2048,i=(s,a)=>{if(--n<0||a>20){o.push("WORKFLOW_EXPRESSION_BUDGET_EXCEEDED");return}let r=de(s);if(r.op==="path")$n(r.path)?t.add(r.path):o.push("WORKFLOW_EXPRESSION_PATH_INVALID");else{if(r.op==="literal")return;if(r.op==="and"||r.op==="or")if(!Array.isArray(r.values)||!r.values.length||r.values.length>128)o.push("WORKFLOW_EXPRESSION_GROUP_INVALID");else for(let c of r.values){if(n<0)break;i(c,a+1)}else r.op==="not"||r.op==="exists"?i(r.value,a+1):["eq","neq","gt","gte","lt","lte","in","contains"].includes(String(r.op))?(i(r.left,a+1),i(r.right,a+1)):o.push("WORKFLOW_EXPRESSION_OPERATOR_INVALID")}};return i(e,0),{paths:[...t],errors:[...new Set(o)]}}function Yo(e){if(e?.readability===void 0)return[];let t=[],o=vt(e),n=de(e.readability);(Object.keys(n).some(r=>!["variables","logic"].includes(r))||!Object.keys(n).length)&&t.push("WORKFLOW_READABILITY_INVALID");let i=de(n.variables);n.variables!==void 0&&(typeof n.variables!="object"||Array.isArray(n.variables)||n.variables===null)&&t.push("WORKFLOW_VARIABLES_INVALID"),Object.keys(i).length>128&&t.push("WORKFLOW_VARIABLE_LIMIT_EXCEEDED");for(let[r,c]of Object.entries(i)){let l=de(c);(!$n(r)||!xt(o,r))&&t.push(`WORKFLOW_VARIABLE_SOURCE_UNKNOWN:${r}`),(!Le(l.label,160)||Object.keys(l).some(p=>!["label","unit","description"].includes(p))||l.unit!==void 0&&!Le(l.unit,32)||l.description!==void 0&&!Le(l.description,2e3))&&t.push(`WORKFLOW_VARIABLE_METADATA_INVALID:${r}`)}let s=n.logic===void 0?[]:n.logic;(!Array.isArray(s)||s.length>32)&&t.push("WORKFLOW_LOGIC_LIMIT_INVALID");let a=new Set;for(let r of Array.isArray(s)?s.slice(0,32):[]){let c=de(r),l=String(c.code||"");(!/^[a-z][a-z0-9-]{2,63}$/.test(l)||a.has(l)||!Le(c.title,160)||!Le(c.description,4e3)||Object.keys(c).some(p=>!["code","title","description","phase","nodeId","inputPaths","outputPaths","source"].includes(p)))&&t.push(`WORKFLOW_LOGIC_METADATA_INVALID:${l}`),a.add(l),(!["submission","node_input","completion"].includes(String(c.phase))||c.phase==="node_input"&&!de(e.nodes)[String(c.nodeId)]||c.phase!=="node_input"&&c.nodeId!==void 0)&&t.push(`WORKFLOW_LOGIC_ANCHOR_INVALID:${l}`);for(let p of["inputPaths","outputPaths"]){let d=c[p];if(!(p==="outputPaths"&&d===void 0))if(!Array.isArray(d)||d.length>32||new Set(d).size!==d.length)t.push(`WORKFLOW_LOGIC_PATHS_INVALID:${l}:${p}`);else for(let f of d)(!$n(f)||!xt(o,f))&&t.push(`WORKFLOW_LOGIC_SOURCE_UNKNOWN:${l}:${String(f)}`)}if(c.source!==void 0){let p=de(c.source);(!Le(p.path,256)||String(p.path).startsWith("/")||String(p.path).includes("..")||String(p.path).includes("://")||!/^sha256:[a-f0-9]{64}$/.test(String(p.digest))||p.symbol!==void 0&&!Le(p.symbol,160)||Object.keys(p).some(d=>!["path","symbol","digest"].includes(d)))&&t.push(`WORKFLOW_LOGIC_SOURCE_REFERENCE_INVALID:${l}`)}}for(let r of Object.values(de(e.nodes))){let c=de(r),l=Array.isArray(c.branches)?c.branches:[];for(let p of l){let d=zo(p.when);t.push(...d.errors.map(f=>`${f}:${c.id}`));for(let f of d.paths)xt(o,f)||t.push(`WORKFLOW_VARIABLE_SOURCE_UNKNOWN:${c.id}:${f}`)}}return[...new Set(t)]}function Pc(e,t){let o=vt(e),n=[],i=new Map,s=[];for(let c of Object.values(e.nodes)){if(c.kind==="approval")for(let[l,p,d]of[["approve",c.onApprove,"\u540C\u610F"],["reject",c.onReject,"\u62D2\u7EDD"]])p&&n.push({id:`${c.id}:${l}`,from:c.id,to:p,kind:l,label:d,variablePaths:[]});if(c.kind==="cc"&&c.next&&n.push({id:`${c.id}:next`,from:c.id,to:c.next,kind:"next",label:"\u6284\u9001\u540E\u7EE7\u7EED",variablePaths:[]}),c.kind==="action"&&c.next){let l=Object.values(c.inputs||{}).flatMap(p=>p.source==="fact"?[p.path]:[]);for(let p of l)i.has(p)||i.set(p,new Set),i.get(p).add(c.id);n.push({id:`${c.id}:next`,from:c.id,to:c.next,kind:"next",label:"\u6210\u529F\u56DE\u6267\u540E\u7EE7\u7EED",variablePaths:l})}if(c.kind==="condition"){for(let[l,p]of(c.branches||[]).entries()){let d=zo(p.when);for(let f of d.paths)i.has(f)||i.set(f,new Set),i.get(f).add(c.id);n.push({id:`${c.id}:branch:${l}`,from:c.id,to:p.target,kind:"branch",label:p.label||`\u6761\u4EF6 ${l+1}`,priority:l+1,expression:p.when,variablePaths:d.paths}),s.push(...d.errors.map(f=>({code:f,path:c.id})))}c.otherwise&&n.push({id:`${c.id}:default`,from:c.id,to:c.otherwise,kind:"default",label:"\u5747\u4E0D\u6EE1\u8DB3\u65F6",variablePaths:[]})}}let r=[...new Set([...i.keys(),...Object.keys(e.readability?.variables||{}),...(e.readability?.logic||[]).flatMap(c=>[...c.inputPaths,...c.outputPaths||[]])])].slice(0,128).map(c=>{let l=xt(o,c),p=e.readability?.variables?.[c],d=c.split("."),f=e.subject?.factProjection[d[0]],g=d[0]==="steps"?e.nodes[d[1]]:void 0;return l||s.push({code:"WORKFLOW_VARIABLE_SOURCE_UNKNOWN",path:c}),{path:c,label:p?.label||String(l?.schema.title||c),type:String(l?.schema.type||"unknown"),...p,required:l?.required||!1,usedBy:[...i.get(c)||[]],source:l&&g?.handler?{kind:"step_output",nodeId:g.id,handlerCode:g.handler.code,handlerVersion:g.handler.version}:l&&f&&e.subject?{kind:"subject_field",resourceCode:e.subject.resourceCode,fieldPath:[f,...d.slice(1)].join(".")}:{kind:l?"input":"unknown"}}});return{schemaVersion:"openxiangda.workflow-graph/v2",workflowCode:e.code,definitionDigest:t,startAt:e.startAt,fixedTopology:!0,branchStrategy:"first_match",nodes:Object.values(e.nodes).map(c=>({id:c.id,kind:c.kind,title:c.title||c.id,...c.binding?{binding:c.binding}:{},...c.mode?{mode:c.mode}:{},...c.outcome?{outcome:c.outcome}:{},...c.kind==="cc"?{emptyPolicy:c.emptyPolicy,notify:c.notify!==!1}:{},...c.kind==="action"&&c.handler?{businessStep:{handler:c.handler,inputs:c.inputs||{},outputPaths:Object.keys(de(c.outputSchema).properties||{}).map(l=>`steps.${c.id}.${l}`)}}:{}})),edges:n,variables:r,logic:e.readability?.logic||[],diagnostics:s}}function Lt(e,t=[],o=0){if(!e||o>20)return"\u65E0\u6CD5\u8BC6\u522B\u7684\u6761\u4EF6";if(e.op==="path")return t.find(a=>a.path===e.path)?.label||e.path;if(e.op==="literal")return JSON.stringify(e.value)??"\u7F3A\u503C";if(e.op==="and"||e.op==="or")return e.values.slice(0,128).map(a=>`\uFF08${Lt(a,t,o+1)}\uFF09`).join(e.op==="and"?" \u4E14 ":" \u6216 ");if(e.op==="not"||e.op==="exists")return`${e.op==="not"?"\u4E0D\u6EE1\u8DB3":"\u5B58\u5728"}\uFF08${Lt(e.value,t,o+1)}\uFF09`;if(!("left"in e))return"\u65E0\u6CD5\u8BC6\u522B\u7684\u6761\u4EF6";let n={eq:"=",neq:"\u2260",gt:">",gte:"\u2265",lt:"<",lte:"\u2264",in:"\u5C5E\u4E8E",contains:"\u5305\u542B"},i=e.left.op==="path"?e.left.path:void 0,s=i&&e.right.op==="literal"&&typeof e.right.value=="number"?t.find(a=>a.path===i)?.unit:void 0;return`${Lt(e.left,t,o+1)} ${n[e.op]} ${Lt(e.right,t,o+1)}${s?` ${s}`:""}`}var kn=["approve","reject","return","transfer","delegate","add_assignee"],Vn=["fixed_users","app_role","app_role_in_scope"],Qs=["single","any","all","sequence"],ke=e=>!!e&&typeof e=="object"&&!Array.isArray(e),ze=(e,t)=>Object.keys(e).every(o=>t.includes(o)),jt=(e,t,o)=>Array.isArray(e)&&e.length>0&&e.length<=o&&new Set(e).size===e.length&&e.every(n=>typeof n=="string"&&t.includes(n));function at(e){return e.allowedOperations||[...kn]}function Ho(e,t,o={},n=!1){return!(!ke(e)||!Object.keys(e).length||!ze(e,n?["enabled","label","commentRequired"]:["label","commentRequired"])||e.label!==void 0&&(typeof e.label!="string"||!e.label.trim()||e.label.length>40||/[\u0000-\u001f\u007f]/.test(e.label))||e.enabled!==void 0&&(typeof e.enabled!="boolean"||["approve","reject"].includes(t)&&!e.enabled)||e.commentRequired!==void 0&&(typeof e.commentRequired!="boolean"||!["approve","reject"].includes(t)||(t==="reject"||o.commentRequired)&&!e.commentRequired))}function Fn(e,t){let o=[];for(let[n,i]of Object.entries(e?.nodes||{})){if(!ke(i))continue;let s=i.administration,a=i.operationPolicy;if(i.kind==="cc"){(a!==void 0||s!==void 0&&(!ke(s)||!ze(s,["assigneeProviders"])))&&o.push(`WORKFLOW_NODE_ADMINISTRATION_INVALID:${n}`),s?.assigneeProviders!==void 0&&!jt(s.assigneeProviders,Vn,3)&&o.push(`WORKFLOW_NODE_ADMINISTRATION_PROVIDERS_INVALID:${n}`),s?.assigneeProviders?.includes("app_role_in_scope")&&t&&!t.bindings[i.binding||""]?.scope&&o.push(`WORKFLOW_NODE_ADMINISTRATION_SCOPE_REQUIRED:${n}`);continue}if(i.kind!=="approval"){(s!==void 0||a!==void 0)&&o.push(`WORKFLOW_NODE_ADMINISTRATION_APPROVAL_REQUIRED:${n}`);continue}if(a!==void 0&&(!ke(a)||Object.keys(a).length>8||Object.entries(a).some(([c,l])=>!kn.includes(c)||!at(i).includes(c)||!Ho(l,c)))&&o.push(`WORKFLOW_NODE_OPERATION_POLICY_INVALID:${n}`),s===void 0)continue;if(!ke(s)||!ze(s,["modes","assigneeProviders","operations"])){o.push(`WORKFLOW_NODE_ADMINISTRATION_INVALID:${n}`);continue}s.modes!==void 0&&(!jt(s.modes,Qs,4)||!s.modes.includes(i.mode))&&o.push(`WORKFLOW_NODE_ADMINISTRATION_MODES_INVALID:${n}`),s.assigneeProviders!==void 0&&!jt(s.assigneeProviders,Vn,3)&&o.push(`WORKFLOW_NODE_ADMINISTRATION_PROVIDERS_INVALID:${n}`);let r=t?.bindings[i.binding||""];r&&Array.isArray(s.assigneeProviders)&&s.assigneeProviders.includes("app_role_in_scope")&&!r.scope&&o.push(`WORKFLOW_NODE_ADMINISTRATION_SCOPE_REQUIRED:${n}`),s.operations!==void 0&&(!jt(s.operations,kn,8)||s.operations.some(c=>!at(i).includes(c)))&&o.push(`WORKFLOW_NODE_ADMINISTRATION_OPERATIONS_INVALID:${n}`)}return o}function xc(e,t,o){let n=[];if(!e||!ke(o)||!Object.keys(o).length||!ze(o,["title","description","assignee","mode","operations"]))return["WORKFLOW_V2_NODE_CONFIGURATION_PATCH_INVALID"];let i=o;for(let a of["title","description"])i[a]!==void 0&&(typeof i[a]!="string"||i[a].length>(a==="title"?255:1e3)||a==="title"&&!i[a].trim())&&n.push("WORKFLOW_V2_NODE_CONFIGURATION_PATCH_INVALID");let s=e.administration;if(i.mode!==void 0&&(e.kind!=="approval"||!s?.modes?.includes(i.mode))&&n.push("WORKFLOW_V2_NODE_CONFIGURATION_MODE_READONLY"),i.operations!==void 0&&(e.kind!=="approval"||!ke(i.operations)||!Object.keys(i.operations).length||Object.keys(i.operations).length>8||Object.entries(i.operations).some(([a,r])=>!s?.operations?.includes(a)||!at(e).includes(a)||!Ho(r,a,e.operationPolicy?.[a],!0)))&&n.push("WORKFLOW_V2_NODE_CONFIGURATION_OPERATION_INVALID"),i.assignee!==void 0){let a=i.assignee,r=s?.assigneeProviders||(e.kind==="approval"&&t&&Vn.includes(t.provider)?[t.provider]:[]);!ke(a)||!["approval","cc"].includes(e.kind)||!r.includes(a.provider)||a.provider==="app_role_in_scope"&&!t?.scope?n.push("WORKFLOW_V2_NODE_CONFIGURATION_PROVIDER_READONLY"):a.provider==="fixed_users"?(!ze(a,["provider","users"])||!Array.isArray(a.users)||a.users.length<1||a.users.length>(e.kind==="cc"?20:200)||new Set(a.users).size!==a.users.length||a.users.some(c=>typeof c!="string"||!c.trim()||c.length>255))&&n.push("WORKFLOW_V2_NODE_CONFIGURATION_USERS_INVALID"):(!ze(a,["provider","roleCode"])||typeof a.roleCode!="string"||!/^[a-z][a-z0-9_-]{0,127}$/.test(a.roleCode))&&n.push("WORKFLOW_V2_NODE_CONFIGURATION_ROLE_INVALID")}return n}function jc(e,t){let o=Object.fromEntries(at(e).flatMap(n=>{let i=n,s=t?.operations?.[i],a={...e.operationPolicy?.[i],...s?.label!==void 0?{label:s.label}:{},...s?.commentRequired!==void 0?{commentRequired:s.commentRequired}:{}};return Object.keys(a).length?[[i,a]]:[]}));return{mode:t?.mode||e.mode,allowedOperations:at(e).filter(n=>t?.operations?.[n]?.enabled!==!1),operationPolicy:o,fieldPolicy:{default:e.fieldPolicy?.default||"readonly",fields:{...e.fieldPolicy?.fields}}}}var Mc=20,Zs=["fixed_users","initiator","input_users","form_field_users","app_role","app_role_in_scope","previous_node_actor"];function vn(e,t){let o=[];for(let[n,i]of Object.entries(e?.nodes||{})){if(i?.kind!=="cc"||((Object.keys(i).some(c=>!["id","kind","title","binding","next","emptyPolicy","notify","administration"].includes(c))||typeof i.title!="string"||!i.title.trim()||i.title.length>255||typeof i.binding!="string"||!i.binding.trim()||i.binding.length>255||typeof i.next!="string"||!i.next.trim()||!e.nodes?.[i.next]||!["block","skip"].includes(i.emptyPolicy)||i.notify!==void 0&&typeof i.notify!="boolean")&&o.push(`WORKFLOW_CC_NODE_INVALID:${n}`),!t))continue;let s=t.bindings?.[i.binding];if(!s){o.push(`WORKFLOW_CC_BINDING_NOT_FOUND:${n}`);continue}Zs.includes(s.provider)||o.push(`WORKFLOW_CC_PROVIDER_INVALID:${n}`);let a=s.min??1,r=s.max??20;(!Number.isSafeInteger(a)||!Number.isSafeInteger(r)||a<1||r<a||r>20||s.provider==="fixed_users"&&(!Array.isArray(s.users)||!s.users.length||s.users.length>r))&&o.push(`WORKFLOW_CC_RECIPIENT_LIMIT_INVALID:${n}`)}return[...new Set(o)]}var er=64,Ln=1024*1024,tr=65536,Qo=100,nr=400,xe=new Set(["__proto__","prototype","constructor"]),Zo=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,dt=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,Xo=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,ie=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&[null,Object.prototype].includes(Object.getPrototypeOf(e)),Re=(e,t)=>ie(e)&&Object.keys(e).every(o=>t.includes(o)&&!xe.has(o)),Wt=e=>{try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return 1/0}},ei=e=>e==null||typeof e=="string"&&!e.trim()||Array.isArray(e)&&e.length===0;function Fe(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((n,i)=>Fe(n,t[i]));if(!ie(e)||!ie(t))return!1;let o=Object.keys(e);return o.length===Object.keys(t).length&&o.every(n=>Object.hasOwn(t,n)&&Fe(e[n],t[n]))}function Pn(e,t){let o=t.split(".");if(!(o.some(n=>!Zo.test(n)||xe.has(n))||o.length>12))return o.reduce((n,i)=>ie(n)&&Object.hasOwn(n,i)?n[i]:void 0,e)}function Ve(e,t){switch(e.op){case"literal":return e.value;case"path":return Pn({values:t},e.path);case"and":return e.values.every(o=>!!Ve(o,t));case"or":return e.values.some(o=>!!Ve(o,t));case"not":return!Ve(e.value,t);case"exists":return!ei(Ve(e.value,t));default:{let o=Ve(e.left,t),n=Ve(e.right,t);return e.op==="eq"?Fe(o,n):e.op==="neq"?!Fe(o,n):e.op==="in"?Array.isArray(n)&&n.some(i=>Fe(i,o)):e.op==="contains"?Array.isArray(o)?o.some(i=>Fe(i,n)):typeof o=="string"&&typeof n=="string"&&o.includes(n):typeof o!="number"||typeof n!="number"||!Number.isFinite(o)||!Number.isFinite(n)?!1:e.op==="gt"?o>n:e.op==="gte"?o>=n:e.op==="lt"?o<n:o<=n}}}function ct(e,t,o=0,n={nodes:0}){if(o>8||++n.nodes>64||!ie(e))return!1;if(e.op==="literal")return Re(e,["op","value"])&&Object.hasOwn(e,"value")&&Wt(e.value)<=4096&<(e.value);if(e.op==="path"){if(!Re(e,["op","path"])||typeof e.path!="string")return!1;let i=e.path.split(".");return i[0]==="values"&&i.length>=2&&i.length<=8&&t.has(i[1])&&i.every(s=>dt.test(s)&&!xe.has(s))}return["not","exists"].includes(e.op)?Re(e,["op","value"])&&ct(e.value,t,o+1,n):["and","or"].includes(e.op)?Re(e,["op","values"])&&Array.isArray(e.values)&&e.values.length>0&&e.values.length<=16&&e.values.every(i=>ct(i,t,o+1,n)):["eq","neq","gt","gte","lt","lte","in","contains"].includes(e.op)&&Re(e,["op","left","right"])&&ct(e.left,t,o+1,n)&&ct(e.right,t,o+1,n)}function Mt(e,t,o){let n=[],i=e.taskPages;if(i!==void 0&&(!ie(i)||Object.keys(i).length===0||Object.keys(i).length>16||Wt(i)>tr))return["WORKFLOW_TASK_PAGES_INVALID"];for(let[s,a]of Object.entries(i||{})){let r=`taskPages.${s}`;if(!Zo.test(s)||xe.has(s)||!Re(a,["title","fields"])||typeof a.title!="string"||!a.title.trim()||a.title.length>160||!Array.isArray(a.fields)||!a.fields.length||a.fields.length>er){n.push(`WORKFLOW_TASK_PAGE_INVALID:${r}`);continue}let c=new Set(a.fields.map(d=>d?.code));c.size!==a.fields.length&&n.push(`WORKFLOW_TASK_PAGE_DUPLICATE_FIELD:${r}`);let l=0,p=new Set;for(let d of a.fields){if(!Re(d,["code","readonly","required","visibleWhen","requiredWhen","subtable"])||!dt.test(d.code)||xe.has(d.code)||["readonly","required"].some(f=>d[f]!==void 0&&typeof d[f]!="boolean")||d.readonly&&(d.required||d.requiredWhen)){n.push(`WORKFLOW_TASK_PAGE_FIELD_INVALID:${r}`);continue}for(let f of["visibleWhen","requiredWhen"])d[f]!==void 0&&!ct(d[f],c)&&n.push(`WORKFLOW_TASK_PAGE_EXPRESSION_INVALID:${r}.${d.code}.${f}`);if(t){let f=t.get(d.code);if((!f||f.system||f.hidden||f.type==="serial-number"||!d.readonly&&f.widget==="readonly"||!d.readonly&&f.type==="subtable"&&!d.subtable||d.subtable&&f.type!=="subtable")&&n.push(`WORKFLOW_TASK_PAGE_RESOURCE_FIELD_INVALID:${r}.${d.code}`),d.subtable&&f?.subtable){let g=f.subtable;l+=g.maxRows??20,(p.has(g.resourceCode)||!Number.isSafeInteger(g.maxRows??20)||(g.maxRows??20)<1||(g.maxRows??20)>Qo||!dt.test(g.foreignKey)||!dt.test(g.orderField)||g.foreignKey===g.orderField)&&n.push(`WORKFLOW_TASK_SUBTABLE_RELATION_INVALID:${r}.${d.code}`),p.add(g.resourceCode);let E=o?.get(g.resourceCode);o&&(!E||!["uuid","resource-ref.single"].includes(E.get(g.foreignKey)?.type||"")||E.get(g.orderField)?.type!=="number.integer")&&n.push(`WORKFLOW_TASK_SUBTABLE_RELATION_INVALID:${r}.${d.code}`);for(let A of Array.isArray(d.subtable.fields)?d.subtable.fields:[]){if(!A||typeof A.code!="string")continue;let b=E?.get(A.code);(A.code===g.foreignKey||A.code===g.orderField||E&&(!b||b.system||b.hidden||b.type==="subtable"||!A.readonly&&(b.widget==="readonly"||b.type==="serial-number")))&&n.push(`WORKFLOW_TASK_SUBTABLE_FIELD_UNSUPPORTED:${r}.${d.code}.${A.code}`)}}else d.subtable&&t&&n.push(`WORKFLOW_TASK_SUBTABLE_RELATION_INVALID:${r}.${d.code}`)}d.subtable&&(d.readonly||!Re(d.subtable,["fields","create","delete","reorder"])||["create","delete","reorder"].some(f=>d.subtable?.[f]!==void 0&&typeof d.subtable[f]!="boolean")||!Array.isArray(d.subtable.fields)||d.subtable.fields.some(f=>f?.subtable)?n.push(`WORKFLOW_TASK_SUBTABLE_PAGE_INVALID:${r}.${d.code}`):n.push(...Mt({taskPages:{child:{title:"\u5B50\u884C",fields:d.subtable.fields}}},o?.get(t?.get(d.code)?.subtable?.resourceCode||"")).map(f=>`${f}:${r}.${d.code}`)))}(l>nr||l<0||!Number.isSafeInteger(l))&&n.push(`WORKFLOW_TASK_SUBTABLE_BUDGET_EXCEEDED:${r}`)}for(let[s,a]of Object.entries(e.nodes||{}))ie(a)&&a.taskPageCode!==void 0&&(a.kind!=="approval"||typeof a.taskPageCode!="string"||!ie(i)||!Object.hasOwn(i,a.taskPageCode)?n.push(`WORKFLOW_TASK_PAGE_NOT_FOUND:${s}`):Array.isArray(i[a.taskPageCode]?.fields)&&i[a.taskPageCode].fields.some(r=>r&&(a.fieldPolicy?.fields?.[r.code]||a.fieldPolicy?.default)==="hidden")&&n.push(`WORKFLOW_TASK_PAGE_FIELD_HIDDEN:${s}`));return n}function ti(e,t){return e.fields.map(o=>({code:o.code,visible:o.visibleWhen===void 0||!!Ve(o.visibleWhen,t),readonly:o.readonly===!0,required:o.required===!0||o.requiredWhen!==void 0&&!!Ve(o.requiredWhen,t)}))}var ye=class extends Error{constructor(o,n){super(o);this.code=o;this.field=n}code;field;rowIndex;childField};function Kc(e,t){return t.map(o=>({key:String(o.id),id:String(o.id),revision:Number(o.revision),state:"persisted",values:Object.fromEntries(ti({title:"\u5B50\u884C",fields:e.fields},o).filter(n=>n.visible&&!n.readonly).map(n=>[n.code,o[n.code]??null]))}))}function Gc(e,t,o,n,i,s=!0){let a=e.subtable,r=f=>{throw new ye(f,e.code)};if(!a||!Number.isSafeInteger(t)||t<1||t>Qo||!Array.isArray(n)||n.length>2*t||Wt(n)>Ln||!lt(n))return r("WORKFLOW_TASK_SUBTABLE_VALUES_INVALID");let c=new Map(o.map(f=>[String(f.id),f])),l=new Set,p=new Set,d=[];for(let f of n){if(!Re(f,["key","state","id","revision","values"])||typeof f.key!="string"||!Xo.test(f.key)||l.has(f.key)||!["created","persisted","deleted"].includes(f.state)||!ie(f.values))return r("WORKFLOW_TASK_SUBTABLE_ROW_INVALID");if(l.add(f.key),f.state==="created"){if(!a.create||f.id!==void 0||f.revision!==void 0||c.has(f.key))return r("WORKFLOW_TASK_SUBTABLE_CREATE_FORBIDDEN")}else{if(typeof f.id!="string"||f.id!==f.key||!Xo.test(f.id)||p.has(f.id)||!Number.isSafeInteger(f.revision)||f.revision<1||!c.has(f.id))return r("WORKFLOW_TASK_SUBTABLE_SCOPE_CONFLICT");if(p.add(f.id),s&&Number(c.get(f.id).revision)!==f.revision)return r("WORKFLOW_TASK_SUBTABLE_REVISION_CONFLICT")}if(f.state==="deleted"){if(!a.delete||Object.keys(f.values).length)return r("WORKFLOW_TASK_SUBTABLE_DELETE_FORBIDDEN");continue}try{or({title:e.code,fields:a.fields},f.id?c.get(f.id):{},f.values,i)}catch(g){if(!(g instanceof ye))throw g;let E=new ye(g.code,e.code);throw E.rowIndex=d.length,g.field!==void 0&&(E.childField=g.field),E}d.push(f)}if(p.size!==c.size)return r("WORKFLOW_TASK_SUBTABLE_SCOPE_CONFLICT");if(d.length>t)return r("WORKFLOW_TASK_SUBTABLE_MAX_ROWS_EXCEEDED");if(!a.reorder){let f=o.filter(E=>d.some(A=>A.id===String(E.id))).map(E=>String(E.id)),g=d.filter(E=>E.state==="persisted").map(E=>E.id);if(!Fe(f,g)||d.some((E,A)=>E.state==="created"&&d.slice(A+1).some(b=>b.state==="persisted")))return r("WORKFLOW_TASK_SUBTABLE_REORDER_FORBIDDEN")}return n}function lt(e,t={members:0},o=0){return++t.members>5e4||o>12?!1:e===null||typeof e=="boolean"?!0:typeof e=="string"?e.length<=Ln:typeof e=="number"?Number.isFinite(e):Array.isArray(e)?e.length<=1e3&&e.every(n=>lt(n,t,o+1)):ie(e)&&Object.entries(e).every(([n,i])=>!xe.has(n)&<(i,t,o+1))}function or(e,t,o,n){if(!ie(o)||Wt(o)>Ln||!lt(o))throw new ye("WORKFLOW_TASK_FORM_VALUES_INVALID");let i={...t,...o},s=new Map(ti(e,i).map(a=>[a.code,a]));for(let a of Object.keys(o)){let r=s.get(a);if(!r||r.readonly||!r.visible)throw new ye("WORKFLOW_TASK_FORM_FIELD_NOT_EDITABLE",a)}if(n)for(let a of s.values()){let r=i[a.code],c=e.fields.find(l=>l.code===a.code)?.subtable&&Array.isArray(r)?r.every(l=>ie(l)&&l.state==="deleted"):ei(r);if(a.visible&&!a.readonly&&a.required&&c)throw new ye("WORKFLOW_TASK_FORM_REQUIRED",a.code)}return i}function qc(e,t,o){let n=JSON.parse(JSON.stringify(t));for(let[a,r]of Object.entries(e.subject?.factProjection||{})){let c=a.split(".");if(!c.length||c.length>12||a.length>128||c[0]==="steps"||c.some(p=>!dt.test(p)||xe.has(p)))throw new ye("WORKFLOW_TASK_FORM_FACT_PROJECTION_INVALID");if(!Object.hasOwn(o,r))throw new ye("WORKFLOW_TASK_FORM_FACT_FIELD_MISSING",r);let l=n;for(let p of c.slice(0,-1))l=l[p]=ie(l[p])?l[p]:{};l[c.at(-1)]=o[r]===void 0?void 0:JSON.parse(JSON.stringify(o[r]))}let i=new Set,s=Object.values(e.nodes||{}).filter(a=>a.kind==="action");for(let a=0;a<=s.length;a++){let r=!1;for(let c of s)ie(n.steps)&&Object.hasOwn(n.steps,c.id)&&Object.values(c.inputs||{}).some(l=>l.source==="fact"&&!Fe(Pn(t,l.path),Pn(n,l.path)))&&(delete n.steps[c.id],i.add(c.id),r=!0);if(!r)break}return{facts:n,invalidatedNodeIds:[...i].sort()}}function Jc(e,t,o){let n=e.nodes||{};for(let i of o){let s=new Set,a=new Map,r=c=>{if(c===i)return!0;if(a.has(c))return a.get(c);if(s.has(c)||s.size>200)return!1;let l=n[c];if(!ie(l)||l.kind==="end")return!1;s.add(c);let p=l.kind==="approval"?[l.onApprove]:l.kind==="condition"?[...(l.branches||[]).map(f=>f.target),l.otherwise]:[l.next],d=p.length>0&&p.every(f=>typeof f=="string"&&r(f));return s.delete(c),a.set(c,d),d};if(!r(t))return!1}return!0}var Yc=256,Hc=64,Xc=262144,ir=/^[a-z][a-z0-9_-]{0,127}$/,sr=/^[A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z][A-Za-z0-9_]*)*$/,oi=new Set(["__proto__","prototype","constructor"]),Ne=e=>!!e&&typeof e=="object"&&!Array.isArray(e),ft=(e,t)=>Object.keys(e).every(o=>t.includes(o)),je=(e,t)=>typeof e=="string"&&e.trim().length>0&&e.length<=t&&!/[\u0000-\u001f\u007f]/.test(e),Ce=e=>typeof e=="string"&&ir.test(e)&&!oi.has(e),ii=e=>typeof e=="string"&&e.length<=255&&sr.test(e)&&!e.split(".").some(t=>oi.has(t)),rr=e=>Ne(e)&&ft(e,["dimension","valueFrom","value"])&&Ce(e.dimension)&&(je(e.value,255)&&e.valueFrom===void 0||ii(e.valueFrom)&&e.value===void 0),ni=e=>typeof e=="string"&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?(?:Z|[+-]\d{2}:\d{2})$/.test(e)&&Number.isFinite(Date.parse(e)),ut={type:"string",pattern:"^[a-z][a-z0-9_-]{0,127}$"},xn={type:"string",minLength:1,maxLength:128},Qc={type:"object",additionalProperties:!1,required:["policyCode","title","strategy","dimensions","sources"],properties:{policyCode:ut,title:xn,strategy:{enum:["replace_then_append","replace_only"]},dimensions:{type:"object",maxProperties:8,propertyNames:ut,additionalProperties:{type:"object",additionalProperties:!1,required:["title","valueFrom"],properties:{title:xn,valueFrom:{type:"string",minLength:1,maxLength:255}}}},sources:{type:"object",minProperties:1,maxProperties:16,propertyNames:ut,additionalProperties:{type:"object",additionalProperties:!1,required:["title","provider","roleCode"],properties:{title:xn,provider:{enum:["app_role","app_role_in_scope"]},roleCode:ut,scope:{type:"object",additionalProperties:!1,required:["dimension"],properties:{dimension:ut,value:{type:"string",minLength:1,maxLength:255},valueFrom:{type:"string",minLength:1,maxLength:255}}}}}}}};function Ut(e){if(!Ne(e)||!ft(e,["policyCode","title","strategy","dimensions","sources"])||!Ce(e.policyCode)||!je(e.title,128)||!["replace_then_append","replace_only"].includes(e.strategy))return["WORKFLOW_V2_ROUTING_POLICY_INVALID"];let t=[];return(!Ne(e.dimensions)||Object.keys(e.dimensions).length>8||Object.entries(e.dimensions).some(([o,n])=>!Ce(o)||!Ne(n)||!ft(n,["title","valueFrom"])||!je(n.title,128)||!ii(n.valueFrom)))&&t.push("WORKFLOW_V2_ROUTING_DIMENSIONS_INVALID"),(!Ne(e.sources)||Object.keys(e.sources).length<1||Object.keys(e.sources).length>16||Object.entries(e.sources).some(([o,n])=>!Ce(o)||!Ne(n)||!ft(n,["title","provider","roleCode","scope"])||!je(n.title,128)||!Ce(n.roleCode)||!["app_role","app_role_in_scope"].includes(n.provider)||(n.provider==="app_role_in_scope"?!rr(n.scope):n.scope!==void 0)))&&t.push("WORKFLOW_V2_ROUTING_SOURCES_INVALID"),t}function Zc(e,t){if(Ut(e).length)return["WORKFLOW_V2_ROUTING_POLICY_INVALID"];if(!Array.isArray(t)||t.length>256||new TextEncoder().encode(JSON.stringify(t)).length>262144)return["WORKFLOW_V2_ROUTING_RULE_LIMIT_EXCEEDED"];let o=[],n=new Set;for(let i of t){if(!Ne(i)||!ft(i,["ruleCode","title","enabled","workflowCode","nodeId","matches","sourceCode","effect","priority","validFrom","validTo"])||!Ce(i.ruleCode)||!je(i.title,128)||typeof i.enabled!="boolean"||!Ce(i.sourceCode)||!Object.hasOwn(e.sources,i.sourceCode)||!["append","replace"].includes(i.effect)||!Number.isSafeInteger(i.priority)||i.priority<-1e3||i.priority>1e3||i.workflowCode!==void 0&&!Ce(i.workflowCode)||i.nodeId!==void 0&&(!Ce(i.nodeId)||i.workflowCode===void 0)||i.validFrom!==void 0&&!ni(i.validFrom)||i.validTo!==void 0&&!ni(i.validTo)||i.validFrom&&i.validTo&&Date.parse(i.validFrom)>=Date.parse(i.validTo)){o.push("WORKFLOW_V2_ROUTING_RULE_INVALID");continue}n.has(i.ruleCode)&&o.push(`WORKFLOW_V2_ROUTING_RULE_DUPLICATE:${i.ruleCode}`),n.add(i.ruleCode),(!Ne(i.matches)||Object.entries(i.matches).some(([s,a])=>!Object.hasOwn(e.dimensions,s)||!Array.isArray(a)||a.length<1||a.length>64||new Set(a).size!==a.length||a.some(r=>!je(r,255))))&&o.push(`WORKFLOW_V2_ROUTING_MATCH_INVALID:${i.ruleCode}`)}return[...new Set(o)]}function ar(e){return JSON.stringify({policyCode:e.policyCode,strategy:e.strategy,dimensions:Object.entries(e.dimensions).sort(([t],[o])=>t<o?-1:t>o?1:0).map(([t,o])=>[t,o.valueFrom]),sources:Object.entries(e.sources).sort(([t],[o])=>t<o?-1:t>o?1:0).map(([t,o])=>[t,o.provider,o.roleCode,o.scope?.dimension??null,o.scope?.valueFrom??null,o.scope?.value??null])})}function si(e){let t=[],o=new Map;for(let n of e)for(let[i,s]of Object.entries(n.bindings||{})){if(!Ne(s)||s.routing===void 0)continue;let a=Ut(s.routing);if(a.length){t.push(...a.map(l=>`${l}:${i}`));continue}let r=ar(s.routing),c=o.get(s.routing.policyCode);c&&c!==r&&t.push(`WORKFLOW_V2_ROUTING_POLICY_CONFLICT:${s.routing.policyCode}`),o.set(s.routing.policyCode,r)}return[...new Set(t)]}function ed(e,t){let o={};for(let[n,i]of Object.entries(e.dimensions)){let s=t;for(let a of i.valueFrom.split("."))s=Ne(s)&&Object.hasOwn(s,a)?s[a]:void 0;if(!(typeof s=="string"&&je(s,255)||typeof s=="number"&&Number.isFinite(s)||typeof s=="boolean"))throw new Error(`WORKFLOW_V2_ROUTING_FACT_REQUIRED:${n}`);o[n]=String(s)}return o}function td(e,t,o){let n=t.filter(l=>l.enabled&&(!l.validFrom||Date.parse(l.validFrom)<=o.at)&&(!l.validTo||Date.parse(l.validTo)>o.at)&&(!l.workflowCode||l.workflowCode===o.workflowCode)&&(!l.nodeId||l.nodeId===o.nodeId)&&Object.entries(l.matches).every(([p,d])=>d.includes(o.facts[p])));if(n.length>64)throw new Error("WORKFLOW_V2_ROUTING_MATCH_LIMIT_EXCEEDED");let i=(l,p)=>p.priority-l.priority||+!!l.workflowCode-+!!p.workflowCode||+!!l.nodeId-+!!p.nodeId||(l.ruleCode<p.ruleCode?-1:l.ruleCode>p.ruleCode?1:0),s=n.filter(l=>l.effect==="replace").sort(i);if(s.length>1&&s[0].priority===s[1].priority)throw new Error("WORKFLOW_V2_ROUTING_REPLACE_CONFLICT");let a=s[0],r=a&&e.strategy==="replace_only"?[]:n.filter(l=>l.effect==="append").sort(i),c=[...a?[a]:[],...r];return{matched:n.sort(i),replacement:a,applied:c,ignored:n.filter(l=>!c.includes(l))}}import*as Jt from"crypto";var ri="native-4",ai={"application-native-2":"1.0.0","authz.native-batch-explain":"1.0.0","authz.native-management":"1.0.0","authz.native-membership-batch":"1.0.0","deployment.durable-runs":"1.0.0","deployment.platform-executor":"1.0.0","environment.on-demand-production":"1.0.0","environment.runtime-lifecycle":"1.0.0","data-api-v2":"1.1.0","data.native-golden-crud":"1.0.0","data.audit-read-access":"1.0.0","data.managed-files":"1.1.0","data.decimal-reservations":"1.1.0","data.decimal-reservation-lifecycle":"1.0.0","data.unique-keys":"1.0.0","data.managed-concurrency":"1.0.0","data.managed-concurrency.durable":"1.0.0","workflow.named-input-sources":"1.0.0","directory-v2":"1.0.0","directory.selected-user":"1.0.0","events-v2":"1.0.0","events.durable-receipts":"1.0.0","events.capture-policy":"1.0.0","events.native-data-actions":"1.0.0","workflow-kernel-v2":"1.0.0","workflow.instance-cancellation-policy":"1.0.0","workflow.node-administration":"1.0.0","workflow.assignment-routing":"1.0.0","workflow.role-references":"1.0.0","workflow.delegation-management":"1.0.0","workflow.automatic-cc":"1.0.0","workflow.task-page-submit":"1.0.0","workflow.task-private-drafts":"1.0.0","workflow.task-managed-files":"1.0.0","workflow.task-rich-fields":"1.0.0","workflow.task-owned-subtables":"1.0.0","workflow.task-owned-files":"1.0.0","workflow.durable-business-step":"1.0.0","business-process.durable-command":"1.1.0","workflow.fresh-command-token":"1.0.0","notification-hub-v2":"1.0.0","authentication.application-login-surface":"1.0.0","public-access.anonymous-owner-records":"1.0.0"};var id=5,sd=20,rd=50,ad=50,cd=100,_t=class extends Error{constructor(o,n){super(o);this.code=o;this.pointer=n;this.name="NativeDataPolicyExpressionV2Error"}code;pointer};function Bt(e,t){let o=[],n=(i,s,a)=>{a>5&&pt("NATIVE_DATA_POLICY_EXPRESSION_DEPTH_EXCEEDED",s);let r=di(i,s),c=["allOf","anyOf"].filter(d=>d in r);if(c.length===0){o.push({rule:r,pointer:s}),o.length>50&&pt("NATIVE_DATA_POLICY_EXPRESSION_LEAVES_EXCEEDED",s);return}let l=c[0],p=r[l];(c.length!==1||Object.keys(r).length!==1||!Array.isArray(p)||p.length<1||p.length>20)&&pt("NATIVE_DATA_POLICY_EXPRESSION_GROUP_INVALID",s),p.forEach((d,f)=>n(d,`${s}/${l}/${f}`,a+1))};return n(e,t,1),o}function ci(e,t){Bt(e,t);let o=(n,i)=>{let s=di(n,i);if(Array.isArray(s.allOf))return jn(s.allOf.flatMap((a,r)=>o(a,`${i}/allOf/${r}`)),i);if(Array.isArray(s.anyOf)){let a=[[]];return s.anyOf.forEach((r,c)=>{let l=o(r,`${i}/anyOf/${c}`);a=jn(a.flatMap(p=>l.map(d=>[...p,...d])),i)}),a}return[[s]]};return jn(o(e,t),t)}function jn(e,t){let o=e.reduce((n,i)=>n+i.length,0);return(e.length>50||o>100)&&pt("NATIVE_DATA_POLICY_EXPRESSION_EXPANSION_EXCEEDED",t),e}function di(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&pt("NATIVE_DATA_POLICY_EXPRESSION_NODE_INVALID",t),e}function pt(e,t){throw new _t(e,t)}var cr="openxiangda.config-bundle/v3",Ci="openxiangda.contract-bundle/v3",li="openxiangda.native-configuration-projection/v1",gt=ri,dr=/^[a-f0-9]{64}$/,lr=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,ur=/^app:[a-z][a-z0-9]*(?:-[a-z0-9]+)*:[A-Za-z0-9:._*-]+$/,fr=/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/,pr=/^[a-z][a-z0-9]*(?:[-.][a-z0-9]+)*$/,_r=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,mr=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,ui=/^[A-Za-z][A-Za-z0-9_]{0,127}$/,gr=/^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*$/,Ar=/^[A-Z][A-Z0-9_]*$/,Er=/^[a-z][a-z0-9-]{2,63}$/,Ir=/^[A-Za-z][A-Za-z0-9_-]{0,127}$/,br=/^[A-Za-z][A-Za-z0-9_.]{0,127}$/,yr=16,Nr=2*1024,Tr=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"]),Or=new Set(["overview","database","operations","workflow","members","calendar","document","folder","settings"]),hr=new Set(["approve","reject","return","transfer","delegate","add_assignee","resubmit","withdraw","terminate","admin_reassign","admin_override","retry_resolution"]),Rr=4*1024*1024,Cr=8*1024*1024,Sr=40,wr=1e5,Mn=1024*1024,Dr="openxiangda.event-handler-manifest/v2",Si="openxiangda.application-route-manifest/v3",fi=64,wi=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}),Un=["openxiangda.data.record.created.v2","openxiangda.data.record.updated.v2","openxiangda.data.record.deleted.v2"],Bn=[rt,"openxiangda.workflow.step.result_received.v2","openxiangda.workflow.step.completed.v2","openxiangda.workflow.step.continuation_failed.v2","openxiangda.workflow.instance.started.v2","openxiangda.workflow.instance.cc_added.v2","openxiangda.workflow.instance.completed.v2","openxiangda.workflow.instance.rejected.v2","openxiangda.workflow.instance.returned.v2","openxiangda.workflow.instance.resumed.v2","openxiangda.workflow.instance.withdrawn.v2","openxiangda.workflow.instance.terminated.v2","openxiangda.workflow.task.created.v2","openxiangda.workflow.task.assigned.v2","openxiangda.workflow.task.assignment_pending.v2","openxiangda.workflow.task.assignment_resolution_failed.v2","openxiangda.workflow.task.approved.v2","openxiangda.workflow.task.completed.v2","openxiangda.workflow.task.rejected.v2","openxiangda.workflow.task.returned.v2","openxiangda.workflow.task.resubmitted.v2","openxiangda.workflow.task.transferred.v2","openxiangda.workflow.task.reassigned.v2","openxiangda.workflow.task.delegated.v2","openxiangda.workflow.task.assignee_added.v2","openxiangda.workflow.task.cancelled.v2","openxiangda.workflow.participant.activated.v2","openxiangda.workflow.participant.completed.v2","openxiangda.workflow.participant.rejected.v2","openxiangda.workflow.participant.returned.v2","openxiangda.workflow.participant.transferred.v2","openxiangda.workflow.participant.reassigned.v2","openxiangda.workflow.participant.delegated.v2","openxiangda.workflow.participant.added.v2","openxiangda.workflow.participant.suspended.v2","openxiangda.workflow.participant.resumed.v2","openxiangda.workflow.participant.cancelled.v2"],$r=new Set(Bn),Kn=class extends Error{code;pointer;identifiers;constructor(t,o,n={}){super(t),this.name="NativeConfigurationCompilerError",this.code=t,this.pointer=o,this.identifiers=Object.fromEntries(Object.entries(n).slice(0,8).map(([i,s])=>[i,String(s).slice(0,128)]))}};function Vd(e){let t=S(e.appCode,"/appCode",128);lr.test(t)||m("NATIVE_CONFIG_APP_CODE_INVALID","/appCode");let o=qn(e.expectedConfigDigest,"/expectedConfigDigest"),n=qn(e.expectedContractDigest,"/expectedContractDigest"),i=Oi(e.configBytes,Rr,"/configBytes","NATIVE_CONFIG_ARTIFACT_TOO_LARGE"),s=Oi(e.contractBytes,Cr,"/contractBytes","NATIVE_CONTRACT_ARTIFACT_TOO_LARGE");hi(i,o,"/configBytes","NATIVE_CONFIG_DIGEST_MISMATCH"),hi(s,n,"/contractBytes","NATIVE_CONTRACT_DIGEST_MISMATCH");let a=Ni(i,"/configBytes","NATIVE_CONFIG_JSON_INVALID","NATIVE_CONFIG_NOT_CANONICAL"),r=Ni(s,"/contractBytes","NATIVE_CONTRACT_JSON_INVALID","NATIVE_CONTRACT_NOT_CANONICAL");Ti(a,"/config"),Ti(r,"/contracts");let c=a,l=r;vr(c,t),Pr(l,t,o);let p=Lr(c,o,l.generatorVersion);Ta(p,l,c),ee(p)!==ee(l)&&m("NATIVE_CONTRACT_CLOSURE_MISMATCH",Jn(p,l,"/contracts"));let d={authz:{appCode:t,...c.authz,perspectives:c.perspectives,capabilityCatalog:p.capabilities},data:{appCode:t,resources:c.data.resources,resourceContracts:p.resources,...p.concurrency?{concurrency:p.concurrency}:{},...p.subjectReadSurfaces?{subjectReadSurfaces:p.subjectReadSurfaces}:{}},events:{appCode:t,...c.events,consumers:p.eventConsumers,producers:p.eventProducers,handlerManifest:p.eventHandlerManifest,eventTypes:p.eventTypes,capturePlans:Vr({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},f={authz:Ye(d.authz),data:Ye(d.data),events:Ye(d.events),workflows:Ye(d.workflows),runtime:Ye(d.runtime),contracts:Ye(d.contracts)},g={configDigest:o,contractDigest:n,generatorVersion:l.generatorVersion},E=kr(c),A={schemaVersion:li,compilerContractVersion:gt,appCode:t,source:g,projections:f,requiredPlatformCapabilities:E,aggregateDigest:X({schemaVersion:li,compilerContractVersion:gt,appCode:t,source:g,requiredPlatformCapabilities:E,projectionDigests:Object.fromEntries(Object.entries(f).map(([b,I])=>[b,I.digest]))})};return Mi(A)}function kr(e){let t=e.authz.roles,o=e.data.resources,n=e.backend.operations,i=t.some(u=>u.capabilities.some(N=>N.endsWith(":directory:read")))||o.some(u=>u.schema.fields.some(N=>["user.single","user.multiple","department.single","department.multiple"].includes(N.type)))||n.some(u=>u.platformAccess?.directory),s=!!(e.events.subscriptions.length||e.events.timers.length||e.events.dateTriggers.length||e.events.schemas.length),a=n.some(u=>u.platformAccess?.managedFiles||u.platformAccess?.managedFileCopies)||e.events.subscriptions.some(u=>u.platformAccess?.managedFileCopies),r=n.some(u=>u.platformAccess?.notification)||e.events.subscriptions.some(u=>u.platformAccess?.notification),c=(u,N,y=!1)=>{let O=o.find(h=>h.code===u.definition.subject?.resourceCode)?.schema.fields||[];return Object.values(u.definition.taskPages||{}).some(h=>h.fields.some(C=>{if(C.readonly)return!1;let k=O.find(M=>M.code===C.code);if(!y&&k&&N.includes(k.type))return!0;if(!C.subtable||!k?.subtable)return!1;let V=o.find(M=>M.code===k.subtable.resourceCode)?.schema.fields||[];return C.subtable.fields.some(M=>!M.readonly&&V.some(P=>P.code===M.code&&N.includes(P.type)))}))},l=e.workflows.definitions.filter(u=>c(u,["file","image","signature","text.rich"])),p=e.workflows.definitions.filter(u=>c(u,["signature","text.rich"])),d=e.workflows.definitions.filter(u=>c(u,["file","image","signature","text.rich"],!0)),f=e.workflows.definitions.filter(u=>u.launch.mode==="standalone"||u.launch.mode==="hidden-handoff"),g=n.some(u=>u.platformAccess?.workflow)||f.length>0,E=f.filter(u=>{let N=u.launch.submission;if(!N)return!1;let y=o.find(O=>O.code===u.definition.subject.resourceCode);return[N.create,N.existing].some(O=>O&&Object.values(O.inputs).some(h=>h.source==="field"&&y?.schema.fields.some(C=>C.code===h.fieldCode&&C.type.startsWith("resource-ref.")&&C.source)))}),A={resources:o},b={perspectives:e.perspectives,authz:e.authz},I={schemaVersion:e.schemaVersion,appCode:e.appCode,frontend:{routes:e.frontend.routes,user:e.frontend.user,admin:e.frontend.admin,devicePolicy:e.frontend.devicePolicy},backend:{operations:n.map(u=>({code:u.code,method:u.method,path:u.path,capability:u.capability,platformAccess:u.platformAccess||null,...u.browser?{browser:u.browser}:{},ai:u.ai||null}))}};return[...o.some(u=>u.uniqueKeys?.length)?[{code:"data.unique-keys",declaration:o.filter(u=>u.uniqueKeys?.length).map(u=>({code:u.code,uniqueKeys:u.uniqueKeys}))}]:[],...e.data.concurrency?[{code:"data.managed-concurrency",declaration:e.data.concurrency}]:[],...e.data.concurrency?.commands.some(u=>u.mode==="durable")?[{code:"data.managed-concurrency.durable",declaration:e.data.concurrency}]:[],...o.some(u=>u.decimalReservationLifecycle)?[{code:"data.decimal-reservation-lifecycle",declaration:o.filter(u=>u.decimalReservationLifecycle).map(u=>({code:u.code,decimalReservationLifecycle:u.decimalReservationLifecycle}))}]:[],...n.some(u=>u.platformAccess?.decimalReservation)||e.events.subscriptions.some(u=>u.platformAccess?.decimalReservation)?[{code:"data.decimal-reservations",declaration:[...n.filter(u=>u.platformAccess?.decimalReservation).map(u=>({code:u.code,decimalReservation:u.platformAccess.decimalReservation})),...e.events.subscriptions.filter(u=>u.platformAccess?.decimalReservation).map(u=>({subscriptionCode:u.code,decimalReservation:u.platformAccess.decimalReservation}))]}]:[],{code:"application-native-2",declaration:I},{code:"authz.native-batch-explain",declaration:b},{code:"authz.native-management",declaration:b},{code:"deployment.durable-runs",declaration:I.backend},{code:"deployment.platform-executor",declaration:I.backend},{code:"environment.on-demand-production",declaration:{environments:["preproduction","production"]}},{code:"environment.runtime-lifecycle",declaration:{environments:["preproduction","production"]}},...o.length?[{code:"data-api-v2",declaration:A},{code:"data.native-golden-crud",declaration:A}]:[],...o.some(uo)?[{code:"data.audit-read-access",declaration:A}]:[],...i?[{code:"directory-v2",declaration:{roles:t.map(u=>({code:u.code,capabilities:u.capabilities.filter(N=>N.endsWith(":directory:read"))})),resources:o.map(u=>({code:u.code,fields:u.schema.fields.filter(N=>["user.single","user.multiple","department.single","department.multiple"].includes(N.type))})),operations:n.filter(u=>u.platformAccess?.directory).map(u=>({code:u.code,directory:u.platformAccess.directory}))}}]:[],...n.some(u=>u.platformAccess?.directory?.mode==="selected-user")?[{code:"directory.selected-user",declaration:n.filter(u=>u.platformAccess?.directory?.mode==="selected-user").map(u=>({code:u.code,directory:u.platformAccess.directory}))}]:[],...a?[{code:"data.managed-files",declaration:{operations:n.filter(u=>u.platformAccess?.managedFiles||u.platformAccess?.managedFileCopies).map(u=>({code:u.code,...u.platformAccess?.managedFiles?{managedFiles:u.platformAccess.managedFiles}:{},...u.platformAccess?.managedFileCopies?{managedFileCopies:u.platformAccess.managedFileCopies}:{}})),subscriptions:e.events.subscriptions.filter(u=>u.platformAccess?.managedFileCopies).map(u=>({code:u.code,managedFileCopies:u.platformAccess.managedFileCopies}))}}]:[],...e.events.subscriptions.some(u=>u.execution)?[{code:"events.native-data-actions",declaration:e.events.subscriptions.filter(u=>u.execution)}]:[],...e.events.capturePolicies?.length?[{code:"events.capture-policy",declaration:e.events.capturePolicies}]:[],...s?[{code:"events-v2",declaration:e.events},{code:"events.durable-receipts",declaration:e.events}]:[],...e.workflows.activations.length?[{code:"workflow-kernel-v2",declaration:e.workflows},{code:"workflow.fresh-command-token",declaration:e.workflows}]:[],...e.workflows.definitions.some(u=>u.definition.instanceCommands!==void 0)?[{code:"workflow.instance-cancellation-policy",declaration:e.workflows.definitions.filter(u=>u.definition.instanceCommands!==void 0)}]:[],...E.length?[{code:"workflow.named-input-sources",declaration:E}]:[],...e.workflows.definitions.some(u=>Object.values(u.definition.nodes).some(N=>N.administration!==void 0||N.operationPolicy!==void 0))?[{code:"workflow.node-administration",declaration:e.workflows.definitions.filter(u=>Object.values(u.definition.nodes).some(N=>N.administration!==void 0||N.operationPolicy!==void 0))}]:[],...e.workflows.definitions.some(u=>Object.values(u.definition.nodes).some(N=>N.kind==="cc"))?[{code:"workflow.automatic-cc",declaration:e.workflows.definitions.filter(u=>Object.values(u.definition.nodes).some(N=>N.kind==="cc"))}]:[],...e.workflows.definitions.some(u=>u.definition.taskPages!==void 0)?["workflow.task-page-submit","workflow.task-private-drafts"].map(u=>({code:u,declaration:e.workflows.definitions.filter(N=>N.definition.taskPages!==void 0)})):[],...l.length?[{code:"workflow.task-managed-files",declaration:l}]:[],...d.length?[{code:"workflow.task-owned-files",declaration:d}]:[],...p.length?[{code:"workflow.task-rich-fields",declaration:p}]:[],...e.workflows.definitions.some(u=>Object.values(u.definition.taskPages||{}).some(N=>N.fields.some(y=>y.subtable)))?[{code:"workflow.task-owned-subtables",declaration:e.workflows.definitions.filter(u=>Object.values(u.definition.taskPages||{}).some(N=>N.fields.some(y=>y.subtable)))}]:[],...e.workflows.definitions.some(u=>Object.values(u.definition.nodes).some(N=>N.kind==="action"))?[{code:"workflow.durable-business-step",declaration:e.workflows.definitions.filter(u=>Object.values(u.definition.nodes).some(N=>N.kind==="action"))}]:[],...e.workflows.bindings.some(u=>Object.values(u.binding.bindings).some(N=>N.routing!==void 0))?[{code:"workflow.assignment-routing",declaration:e.workflows.bindings.filter(u=>Object.values(u.binding.bindings).some(N=>N.routing!==void 0))}]:[],...g?[{code:"business-process.durable-command",declaration:{operations:n.filter(u=>u.platformAccess?.workflow).map(u=>({code:u.code,workflow:u.platformAccess.workflow})),definitions:f,activations:e.workflows.activations.filter(u=>f.some(N=>N.definition.code===u.workflowCode))}}]:[],...r?[{code:"notification-hub-v2",declaration:{operations:n.filter(u=>u.platformAccess?.notification).map(u=>({code:u.code,notification:u.platformAccess.notification})),subscriptions:e.events.subscriptions.filter(u=>u.platformAccess?.notification).map(u=>({code:u.code,notification:u.platformAccess.notification}))}}]:[],...e.frontend.authentication?[{code:"authentication.application-login-surface",declaration:e.frontend.authentication}]:[],...e.frontend.publicAccess?[{code:"public-access.anonymous-owner-records",declaration:e.frontend.publicAccess}]:[]].map(({code:u,declaration:N})=>({code:u,contractVersion:ai[u],usageDigest:`sha256:${X(N)}`})).sort((u,N)=>u.code===N.code?0:u.code<N.code?-1:1)}function Vr(e){let t=new Map,o=new Set(e.resources.map(s=>String(s.code)));for(let[s,a]of w(e.capturePolicies===void 0?[]:e.capturePolicies,"/capturePlan/capturePolicies",100).entries()){let r=`/capturePlan/capturePolicies/${s}`,c=T(a,r);R(c,["resourceCode","mode"],r);let l=J(c.resourceCode,`${r}/resourceCode`);o.has(l)||m("NATIVE_EVENT_CAPTURE_RESOURCE_NOT_FOUND",r,{resourceCode:l}),t.has(l)&&m("NATIVE_EVENT_CAPTURE_POLICY_DUPLICATE",r,{resourceCode:l}),c.mode!=="all"&&c.mode!=="subscribed"&&m("NATIVE_EVENT_CAPTURE_MODE_INVALID",`${r}/mode`),t.set(l,c.mode)}let n=new Map(e.dataPolicies.map((s,a)=>{let r=T(s,`/capturePlan/dataPolicies/${a}`);return[String(r.code),r]})),i=e.subscriptions.map((s,a)=>T(s,`/capturePlan/subscriptions/${a}`));return e.resources.map((s,a)=>{let r=`/capturePlan/resources/${a}`,c=T(s,r),l=J(c.code,`${r}/code`),p=c.schema?T(c.schema,`${r}/schema`):c,d=new Set(w(p.fields||[],`${r}/schema/fields`,500).map((O,h)=>K(T(O,`${r}/schema/fields/${h}`).code,`${r}/schema/fields/${h}/code`))),f=c.dataPolicyCode?F(c.dataPolicyCode,`${r}/dataPolicyCode`):null,g=f?n.get(f):void 0;f&&!g&&m("NATIVE_EVENT_CAPTURE_AUTHZ_POLICY_NOT_FOUND",r,{resourceCode:l,dataPolicyCode:f});let E=new Set;for(let O of g?.rules||[])E.add(String(O.field));if(g?.readExpression)for(let O of Bt(g.readExpression,`${r}/readExpression`))E.add(String(O.rule.field));let A=new Set,b=new Set,I=new Set;for(let[O,h]of i.entries()){let C=w(h.eventTypes,`/capturePlan/subscriptions/${O}/eventTypes`,20).map(String);if(!C.some(P=>P.startsWith("openxiangda.data.")))continue;let k=T(h.filter||{},`/capturePlan/subscriptions/${O}/filter`),V=Array.isArray(k.resourceCodes)?k.resourceCodes.map(String):[];if(V.length&&!V.includes(l))continue;for(let P of C)Un.includes(P)&&I.add(P);for(let P of Fr(k,`/capturePlan/subscriptions/${O}/filter`))A.add(P);let M=T(h.payload||{},`/capturePlan/subscriptions/${O}/payload`);for(let P of w(M.fields||[],`/capturePlan/subscriptions/${O}/payload/fields`,32))b.add(K(P,`/capturePlan/subscriptions/${O}/payload/fields`))}let _=new Set([...A,...b]),u=new Set([..._,...E]);u.size>fi&&m("NATIVE_EVENT_CAPTURE_FIELDS_LIMIT",r,{resourceCode:l,maximum:fi});for(let O of u)!d.has(O)&&!(E.has(O)&&wi.has(O))&&m("NATIVE_EVENT_CAPTURE_FIELD_NOT_FOUND",r,{resourceCode:l,field:O});let N=T(c.fieldPolicies||{},`${r}/fieldPolicies`);for(let O of _)N[O]?.mask==="omit"&&m("NATIVE_EVENT_CAPTURE_FIELD_SENSITIVE",r,{resourceCode:l,field:O});let y={resourceCode:l,...t.get(l)==="subscribed"?{capturedEventTypes:[...I].sort()}:{},filterFields:[...A].sort(),projectionFields:[...b].sort(),authorizationFields:[...E].sort(),captureFields:[...u].sort()};return{...y,digest:X(y)}}).sort((s,a)=>s.resourceCode.localeCompare(a.resourceCode))}function Fr(e,t){let o=new Set;for(let[a,r]of w(e.changes||[],`${t}/changes`,16).entries()){let c=T(r,`${t}/changes/${a}`);o.add(K(c.field,`${t}/changes/${a}/field`))}let n=T(e.changedFields||{},`${t}/changedFields`);for(let a of["anyOf","allOf","noneOf"])for(let[r,c]of w(n[a]||[],`${t}/changedFields/${a}`,32).entries())o.add(K(c,`${t}/changedFields/${a}/${r}`));let i=0,s=(a,r,c)=>{c>3&&m("NATIVE_EVENT_FILTER_DEPTH_LIMIT",r);let l=T(a,r);if(l.change){let d=T(l.change,`${r}/change`);o.add(K(d.field,`${r}/change/field`)),i+=1;return}if(l.not){s(l.not,`${r}/not`,c+1);return}let p=l.all?"all":l.any?"any":null;p||m("NATIVE_EVENT_FILTER_CONDITION_INVALID",r);for(let[d,f]of w(l[p],`${r}/${p}`,16).entries())s(f,`${r}/${p}/${d}`,c+1)};return e.where&&s(e.where,`${t}/where`,1),i+=Array.isArray(e.changes)?e.changes.length:0,i>16&&m("NATIVE_EVENT_FILTER_ATOM_LIMIT",t),[...o].sort()}function vr(e,t){R(e,["schemaVersion","compilerContractVersion","appCode","perspectives","authz","backend","data","events","workflows","frontend","runtime"],"/config"),j(e.schemaVersion,cr,"/config/schemaVersion"),j(e.compilerContractVersion,gt,"/config/compilerContractVersion"),j(e.appCode,t,"/config/appCode"),w(e.perspectives,"/config/perspectives",100);let o=T(e.authz,"/config/authz");R(o,["capabilities","roles","scopeDimensions","scopeSources","roleMembershipSources","relationshipGrantSources","dataPolicies","authorizationTransitions"],"/config/authz",["authenticatedUserRoleCode"]),w(o.capabilities,"/config/authz/capabilities",2e3),w(o.roles,"/config/authz/roles",100),w(o.scopeDimensions,"/config/authz/scopeDimensions",100),w(o.scopeSources,"/config/authz/scopeSources",100),w(o.roleMembershipSources,"/config/authz/roleMembershipSources",100),w(o.relationshipGrantSources,"/config/authz/relationshipGrantSources",100),w(o.dataPolicies,"/config/authz/dataPolicies",100),w(o.authorizationTransitions,"/config/authz/authorizationTransitions",100);let n=T(e.backend,"/config/backend");R(n,["secrets","operations"],"/config/backend"),w(n.secrets,"/config/backend/secrets",100),w(n.operations,"/config/backend/operations",500),Aa(n.secrets);let i=T(e.data,"/config/data");R(i,["resources"],"/config/data",["resourceDetailRoutes","subjectReadSurfaces","concurrency"]),w(i.resources,"/config/data/resources",100),i.subjectReadSurfaces!==void 0&&w(i.subjectReadSurfaces,"/config/data/subjectReadSurfaces",Y.subjectReadSurfaces),i.resourceDetailRoutes!==void 0&&w(i.resourceDetailRoutes,"/config/data/resourceDetailRoutes",100);let s=T(e.events,"/config/events");R(s,["schemas","subscriptions","timers","dateTriggers"],"/config/events",["capturePolicies"]),w(s.schemas,"/config/events/schemas",100),w(s.subscriptions,"/config/events/subscriptions",100),w(s.timers,"/config/events/timers",100),w(s.dateTriggers,"/config/events/dateTriggers",100);let a=T(e.workflows,"/config/workflows");R(a,["definitions","bindings","activations","providers","editableParameters"],"/config/workflows"),w(a.definitions,"/config/workflows/definitions",100),w(a.bindings,"/config/workflows/bindings",100),w(a.activations,"/config/workflows/activations",100),w(a.providers,"/config/workflows/providers",100),w(a.editableParameters,"/config/workflows/editableParameters",100);let r=T(e.frontend,"/config/frontend");R(r,["routes","user","admin","devicePolicy"],"/config/frontend",["authentication","publicAccess"]),w(r.routes,"/config/frontend/routes",500);let c=T(r.user,"/config/frontend/user");R(c,["applicationTodoCenter"],"/config/frontend/user"),Xe(c.applicationTodoCenter,"/config/frontend/user/applicationTodoCenter"),zn(r.devicePolicy,"/config/frontend/devicePolicy"),Object.prototype.hasOwnProperty.call(r,"authentication")&&$i(r.authentication,r.routes,e,"/config/frontend/authentication"),Object.prototype.hasOwnProperty.call(r,"publicAccess")&&Qr(r.publicAccess,e,"/config/frontend/publicAccess");let l=T(r.admin,"/config/frontend/admin");R(l,["navigation"],"/config/frontend/admin",["access"]),l.access!==void 0&&Yt(l.access,"/config/frontend/admin/access",e.appCode),na(l.navigation,"/config/frontend/admin/navigation");let p=T(e.runtime,"/config/runtime");R(p,["protocolCapabilities","health"],"/config/runtime"),v(p.protocolCapabilities,"/config/runtime/protocolCapabilities",100),R(T(p.health,"/config/runtime/health"),["livePath","readyPath","versionPath"],"/config/runtime/health"),j(p.health.livePath,"/__platform/health","/config/runtime/health/livePath"),j(p.health.readyPath,"/__platform/ready","/config/runtime/health/readyPath"),j(p.health.versionPath,"/__platform/version","/config/runtime/health/versionPath")}function Pr(e,t,o){R(e,["schemaVersion","compilerContractVersion","generatorVersion","appCode","configDigest","perspectives","resources","capabilities","operations","eventConsumers","eventProducers","eventSchemas","eventHandlerManifest","eventTypes","workflows","routes","routeManifest","adminPages","adminNavigation"],"/contracts",["authentication","publicAccess","adminAccess","subjectReadSurfaces","concurrency"]),j(e.schemaVersion,Ci,"/contracts/schemaVersion"),j(e.compilerContractVersion,gt,"/contracts/compilerContractVersion"),S(e.generatorVersion,"/contracts/generatorVersion",128),j(e.appCode,t,"/contracts/appCode"),j(e.configDigest,o,"/contracts/configDigest"),w(e.perspectives,"/contracts/perspectives",Y.perspectives),w(e.resources,"/contracts/resources",Y.resources),e.subjectReadSurfaces!==void 0&&w(e.subjectReadSurfaces,"/contracts/subjectReadSurfaces",Y.subjectReadSurfaces),w(e.capabilities,"/contracts/capabilities",Y.capabilities),w(e.operations,"/contracts/operations",Y.operations),w(e.eventConsumers,"/contracts/eventConsumers",Y.eventConsumers),w(e.eventProducers,"/contracts/eventProducers",Y.eventProducers),w(e.eventSchemas,"/contracts/eventSchemas",Y.eventSchemas),T(e.eventHandlerManifest,"/contracts/eventHandlerManifest"),v(e.eventTypes,"/contracts/eventTypes",Y.eventTypes),w(e.workflows,"/contracts/workflows",Y.workflows),w(e.routes,"/contracts/routes",Y.routes),Object.prototype.hasOwnProperty.call(e,"authentication")&&Yr(e.authentication,"/contracts/authentication"),Object.prototype.hasOwnProperty.call(e,"publicAccess")&&Zr(e.publicAccess,"/contracts/publicAccess"),Object.prototype.hasOwnProperty.call(e,"adminAccess")&&Yt(e.adminAccess,"/contracts/adminAccess",t),ca(e.routeManifest,"/contracts/routeManifest",t),sa(e.adminPages,"/contracts/adminPages"),ra(e.adminNavigation,"/contracts/adminNavigation")}function Lr(e,t,o){let n=Wr(e);pa(e,n),ma(e),_a(e),Ea(e);let i=e.events.schemas.map((_,u)=>{let N=`/config/events/schemas/${u}`,y=T(_,N),O=S(y.eventType,`${N}/eventType`,255);return O.startsWith("openxiangda.")&&m("NATIVE_EVENT_SCHEMA_RESERVED",`${N}/eventType`,{eventType:O}),j(y.schemaDigest,X(T(y.jsonSchema,`${N}/jsonSchema`)),`${N}/schemaDigest`),y}),s=new Set([...Un,...Bn,...i.map(_=>String(_.eventType))]),a=new Map(e.data.resources.map(_=>[String(_.code),new Map(_.schema.fields.map(u=>[String(u.code),String(u.type)]))])),r=Z(e.events.subscriptions.map((_,u)=>{let N=`/config/events/subscriptions/${u}`,y=T(_,N),O=v(y.eventTypes,`${N}/eventTypes`,20);O.forEach((V,M)=>{s.has(V)||m("NATIVE_EVENT_TYPE_NOT_REGISTERED",`${N}/eventTypes/${M}`,{eventType:V})});let h=xo(y,e.data.resources,N),C=jr(y.delivery,O,`${N}/delivery`),k=xr(y.platformAccess,`${N}/platformAccess`,a,e,y);return{code:F(y.code,`${N}/code`),endpointPath:me(y.endpointPath,`${N}/endpointPath`),eventTypes:O,filter:T(y.filter,`${N}/filter`),payload:h?.payload||T(y.payload,`${N}/payload`),...h?{execution:h.execution}:{},...k?{platformAccess:k}:{},delivery:C}}),_=>_.code),c=new Map(i.map(_=>[String(_.eventType),String(_.dataSchemaVersion)])),l=Z([...e.data.resources.flatMap(_=>Un.map(u=>({code:`data:${_.code}:${u}`,source:"data",eventType:u,dataSchemaVersion:"2.0.0",resourceCode:_.code}))),...i.map(_=>({code:`app:${_.eventType}`,source:"app",eventType:_.eventType,dataSchemaVersion:_.dataSchemaVersion})),...e.events.timers.map(_=>({code:_.code,source:"timer",eventType:_.eventType,dataSchemaVersion:c.get(String(_.eventType))||"2.0.0"})),...e.events.dateTriggers.map(_=>({code:_.code,source:"date",eventType:_.eventType,dataSchemaVersion:c.get(String(_.eventType))||"2.0.0",resourceCode:_.resourceCode,field:_.field})),...e.workflows.activations.length?Bn.filter(_=>!Bo.includes(_)||e.workflows.definitions.some(u=>Object.values(u.definition.nodes).some(N=>N.kind==="action"))).map(_=>({code:`workflow:${_}`,source:"workflow",eventType:_,dataSchemaVersion:"2.0.0"})):[]],_=>`${_.source}:${_.code}:${_.eventType}`),p=U([...r.flatMap(_=>_.eventTypes),...l.map(_=>String(_.eventType))]);ia(e);let d=Fi(e),f;try{f=To(e.data.concurrency,e.data.resources,n)}catch(_){throw _ instanceof nt&&m(_.code,_.pointer,{reason:_.reason}),_}f?.commands.some(_=>_.mode==="durable")&&e.backend?.enabled===!1&&m("NATIVE_MANAGED_CONCURRENCY_INVALID","/data/concurrency",{reason:"durable commands require backend runtime"});let g=Ur(e,n),E=Di(e),A=e.workflows.definitions.map(_=>_.definition),b=Dn(A),I=Jo(A,r,!0);I.length&&m(I[0],"/config/events/subscriptions");try{ho(e.data.resources,E)}catch(_){throw _ instanceof qe&&m(_.code,_.pointer,{reason:_.reason}),_}return{schemaVersion:Ci,compilerContractVersion:gt,generatorVersion:o,appCode:e.appCode,configDigest:t,perspectives:e.perspectives,resources:Mr(e),...g.length?{subjectReadSurfaces:g}:{},...f?{concurrency:f}:{},capabilities:Z(n,_=>_.code),operations:E,eventConsumers:r,eventProducers:l,eventSchemas:i,eventHandlerManifest:{schemaVersion:Dr,appCode:e.appCode,handlers:r.filter(_=>!_.execution).map(_=>({code:_.code,endpointPath:_.endpointPath,eventTypes:_.eventTypes,dataSchemaVersions:U(_.eventTypes.map(u=>u.startsWith("openxiangda.")?"2.0.0":c.get(u)||"2.0.0")),maxBodyBytes:65536,receiptProtocolVersion:2,...b[_.code]?{workflowStep:b[_.code]}:{}}))},eventTypes:p,workflows:Li(e),routes:zt(e),...Object.prototype.hasOwnProperty.call(e.frontend,"authentication")?{authentication:Hr(e)}:{},...Object.prototype.hasOwnProperty.call(e.frontend,"publicAccess")?{publicAccess:ea(e)}:{},...e.frontend.admin.access?{adminAccess:e.frontend.admin.access}:{},routeManifest:ua(e),adminPages:d,adminNavigation:ta(e)}}function xr(e,t,o,n,i){if(e===void 0)return;let s=T(e,t);R(s,["notification","managedFileCopies","decimalReservation"],t,!0);let a={};if(s.decimalReservation!==void 0)try{a.decimalReservation=Po(s.decimalReservation,Lo(n,i))}catch{m("NATIVE_EVENT_DECIMAL_RESERVATION_INVALID",`${t}/decimalReservation`)}if(s.notification!==void 0){let r=T(s.notification,`${t}/notification`);R(r,["mode"],`${t}/notification`),j(r.mode,"business-standard",`${t}/notification/mode`),a.notification={mode:"business-standard"}}if(s.managedFileCopies!==void 0){let r=w(s.managedFileCopies,`${t}/managedFileCopies`,16);r.length||m("NATIVE_EVENT_MANAGED_FILE_COPIES_REQUIRED",`${t}/managedFileCopies`);let c=new Set;a.managedFileCopies=Z(r.map((l,p)=>{let d=`${t}/managedFileCopies/${p}`,f=T(l,d);R(f,["mode","sourceResourceCode","sourceFieldCodes","targetResourceCode","targetFieldCodes"],d),j(f.mode,"copy",`${d}/mode`);let g=J(f.sourceResourceCode,`${d}/sourceResourceCode`),E=J(f.targetResourceCode,`${d}/targetResourceCode`),A=o.get(g),b=o.get(E);(!A||!b)&&m("NATIVE_EVENT_MANAGED_FILE_COPY_RESOURCE_INVALID",d);let I=v(f.sourceFieldCodes,`${d}/sourceFieldCodes`,16),_=v(f.targetFieldCodes,`${d}/targetFieldCodes`,16);(!I.length||I.length!==_.length)&&m("NATIVE_EVENT_MANAGED_FILE_COPY_FIELDS_INVALID",d),I.forEach((N,y)=>{let O=A.get(N),h=b.get(_[y]);(!["file","image"].includes(String(O))||O!==h)&&m("NATIVE_EVENT_MANAGED_FILE_COPY_FIELD_INVALID",`${d}/sourceFieldCodes/${y}`)});let u=`${g}:${I.join(",")}=>${E}:${_.join(",")}`;return c.has(u)&&m("NATIVE_EVENT_MANAGED_FILE_COPY_DUPLICATE",d),c.add(u),{mode:"copy",sourceResourceCode:g,sourceFieldCodes:U(I),targetResourceCode:E,targetFieldCodes:U(_)}}),l=>`${l.sourceResourceCode}:${l.sourceFieldCodes.join(",")}=>${l.targetResourceCode}:${l.targetFieldCodes.join(",")}`)}return Object.keys(a).length||m("NATIVE_EVENT_PLATFORM_ACCESS_EMPTY",t),a}function jr(e,t,o){let n=T(e,o);R(n,["timeoutMs","maxAttempts","initialBackoffMs","maxBackoffMs","ordering","concurrency"],o),te(n.timeoutMs,`${o}/timeoutMs`,1e3,3e4),te(n.maxAttempts,`${o}/maxAttempts`,1,12);let i=te(n.initialBackoffMs,`${o}/initialBackoffMs`,1e3,3e5);te(n.maxBackoffMs,`${o}/maxBackoffMs`,i,18e5),te(n.concurrency,`${o}/concurrency`,1,50);let s=S(n.ordering,`${o}/ordering`,32);return["none","record","workflow-instance"].includes(s)||m("NATIVE_EVENT_DELIVERY_ORDERING_INVALID",`${o}/ordering`),s==="workflow-instance"&&t.some(a=>!$r.has(a))&&m("NATIVE_EVENT_WORKFLOW_ORDERING_REQUIRES_WORKFLOW_FACTS",`${o}/ordering`),n}function Wr(e){let t=new Map;for(let o of Wi(e.appCode))t.set(o.code,o);for(let[o,n]of e.authz.capabilities.entries()){let i=`/config/authz/capabilities/${o}`,s=T(n,i);R(s,["code","kind","name","description"],i,!0);let a=Se(s.code,`${i}/code`,e.appCode);t.has(a)&&m("NATIVE_CAPABILITY_DUPLICATE",`${i}/code`),["backend","ui"].includes(s.kind)||m("NATIVE_CAPABILITY_KIND_INVALID",`${i}/kind`);let r={code:a,kind:s.kind,name:S(s.name,`${i}/name`,255),source:"explicit",...s.description===void 0?{}:{description:Hn(s.description,`${i}/description`,2e3)}};t.set(a,r)}for(let[o,n]of e.data.resources.entries()){let i=`/config/data/resources/${o}`,s=We(n,i,e.appCode),a={read:`\u8BFB\u53D6${s.name}`,create:`\u65B0\u5EFA${s.name}`,update:`\u66F4\u65B0${s.name}`,delete:`\u5220\u9664${s.name}`};for(let r of["read","create","update","delete"]){let c=Se(s.capabilities[r],`${i}/capabilities/${r}`,e.appCode);t.has(c)&&m("NATIVE_CAPABILITY_DUPLICATE",`${i}/capabilities/${r}`),t.set(c,{code:c,kind:"data",name:a[r],source:"data"})}for(let[r,c]of Object.entries(s.fieldPolicies)){if(Ze(r))continue;let l=T(c,`${i}/fieldPolicies/${r}`);for(let p of["read","create","update"])if(Array.isArray(l[p]))for(let d of v(l[p],`${i}/fieldPolicies/${r}/${p}`,2e3))Se(d,`${i}/fieldPolicies/${r}/${p}`,e.appCode),!t.has(d)&&t.set(d,{code:d,kind:"data",name:`${s.name}.${r}.${p}`,source:"data"})}}return[...t.values()]}function Mr(e){let t=Br(e);return Z(e.data.resources.map((o,n)=>{let i=We(o,`/config/data/resources/${n}`,e.appCode),s=t.get(i.code);return{code:i.code,schemaDigest:X(i.schema),fields:Z(i.schema.fields.map(a=>({code:a.code,type:a.type})),a=>a.code),...s?{detailRouteCode:s}:{}}}),o=>o.code)}function Ur(e,t){if(e.data.subjectReadSurfaces===void 0)return[];let o=w(e.data.subjectReadSurfaces,"/config/data/subjectReadSurfaces",Y.subjectReadSurfaces),n=new Set(t.map(a=>String(a.code))),i=new Map(e.data.resources.map((a,r)=>{let c=`/config/data/resources/${r}`,l=We(a,c,e.appCode);return[String(l.code),{resource:l,fields:new Map(w(T(l.schema,`${c}/schema`).fields,`${c}/schema/fields`,500).map(p=>{let d=T(p,`${c}/schema/fields`);return[String(d.code),d]}))}]})),s=new Set;return Z(o.map((a,r)=>{let c=`/config/data/subjectReadSurfaces/${r}`,l=T(a,c);R(l,["code","name","capability","subject","relations"],c);let p=F(l.code,`${c}/code`);s.has(p)&&m("NATIVE_SUBJECT_READ_SURFACE_CODE_DUPLICATE",`${c}/code`),s.add(p);let d=Se(l.capability,`${c}/capability`,e.appCode);n.has(d)||m("NATIVE_SUBJECT_READ_SURFACE_CAPABILITY_NOT_DECLARED",`${c}/capability`);let f=T(l.subject,`${c}/subject`);R(f,["resourceCode","fields"],`${c}/subject`);let g=J(f.resourceCode,`${c}/subject/resourceCode`),E=i.get(g);E||m("NATIVE_SUBJECT_READ_SURFACE_RESOURCE_NOT_DECLARED",`${c}/subject/resourceCode`);let A=v(f.fields,`${c}/subject/fields`,100).map((N,y)=>K(N,`${c}/subject/fields/${y}`));A.length||m("NATIVE_SUBJECT_READ_SURFACE_FIELDS_REQUIRED",`${c}/subject/fields`);for(let[N,y]of A.entries()){let O=E.fields.get(y);(!O||O.type==="subtable")&&m("NATIVE_SUBJECT_READ_SURFACE_FIELD_INVALID",`${c}/subject/fields/${N}`)}let b=w(l.relations,`${c}/relations`,8);b.length||m("NATIVE_SUBJECT_READ_SURFACE_RELATIONS_REQUIRED",`${c}/relations`);let I=new Set,_=0,u=Z(b.map((N,y)=>{let O=`${c}/relations/${y}`,h=T(N,O);R(h,["code","resourceCode","foreignKeyField","fields","limit"],O,["order"]);let C=F(h.code,`${O}/code`);I.has(C)&&m("NATIVE_SUBJECT_READ_SURFACE_RELATION_CODE_DUPLICATE",`${O}/code`),I.add(C);let k=J(h.resourceCode,`${O}/resourceCode`),V=i.get(k);V||m("NATIVE_SUBJECT_READ_SURFACE_RESOURCE_NOT_DECLARED",`${O}/resourceCode`);let M=K(h.foreignKeyField,`${O}/foreignKeyField`),P=V.fields.get(M),se=T(P?.source||{},`${O}/foreignKeyField/source`);(!P||!["uuid","resource-ref.single"].includes(String(P.type))||P.type==="resource-ref.single"&&(se.kind!=="resource"||se.resourceCode!==g))&&m("NATIVE_SUBJECT_READ_SURFACE_RELATION_INVALID",`${O}/foreignKeyField`);let ge=v(h.fields,`${O}/fields`,100).map((ce,$)=>K(ce,`${O}/fields/${$}`));ge.length||m("NATIVE_SUBJECT_READ_SURFACE_FIELDS_REQUIRED",`${O}/fields`);for(let[ce,$]of ge.entries()){let W=V.fields.get($);(!W||W.type==="subtable")&&m("NATIVE_SUBJECT_READ_SURFACE_FIELD_INVALID",`${O}/fields/${ce}`)}let H=w(h.order||[],`${O}/order`,10).map((ce,$)=>{let W=`${O}/order/${$}`,L=T(ce,W);R(L,["field","direction"],W);let G=K(L.field,`${W}/field`),q=V.fields.get(G);return(!wi.has(G)&&!q||q?.type==="subtable"||q&&!tt(q.type))&&m("NATIVE_SUBJECT_READ_SURFACE_ORDER_FIELD_INVALID",`${W}/field`),["asc","desc"].includes(String(L.direction))||m("NATIVE_SUBJECT_READ_SURFACE_ORDER_DIRECTION_INVALID",`${W}/direction`),{field:G,direction:L.direction}}),Te=te(h.limit,`${O}/limit`,1,100);return _+=Te,{code:C,resourceCode:k,foreignKeyField:M,fields:U(ge),...H.length?{order:H}:{},limit:Te}}),N=>N.code);return _>400&&m("NATIVE_SUBJECT_READ_SURFACE_ROW_LIMIT_EXCEEDED",`${c}/relations`),{code:p,name:S(l.name,`${c}/name`,255),capability:d,subject:{resourceCode:g,fields:U(A)},relations:u}}),a=>a.code)}function Br(e){let t=e.data.resourceDetailRoutes===void 0?[]:w(e.data.resourceDetailRoutes,"/config/data/resourceDetailRoutes",100),o=new Map(e.data.resources.map((s,a)=>{let r=`/config/data/resources/${a}`,c=We(s,r,e.appCode);return[c.code,c]})),n=new Map(zt(e).map(s=>[String(s.code),s])),i=new Map;for(let[s,a]of t.entries()){let r=`/config/data/resourceDetailRoutes/${s}`,c=T(a,r);R(c,["resourceCode","desktop","mobile"],r);let l=J(c.resourceCode,`${r}/resourceCode`);i.has(l)&&m("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_DUPLICATE",`${r}/resourceCode`);let p=o.get(l);p||m("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_RESOURCE_MISSING",`${r}/resourceCode`);let d=F(c.desktop,`${r}/desktop`),f=F(c.mobile,`${r}/mobile`);d===f&&m("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_INVALID",r);let g=String(p.capabilities.read);for(let[E,A]of[["desktop",d],["mobile",f]]){let b=`${r}/${E}`,I=n.get(A);I||m("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_REFERENCE_MISSING",b),I.surface!=="user"&&m("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_SURFACE_INVALID",b);let _=me(I.path,`${b}/path`),u=[..._.matchAll(/:([A-Za-z][A-Za-z0-9_]*)/g)],N=E==="mobile"?!_.startsWith("/m/"):_==="/m"||_.startsWith("/m/");(_.includes("*")||_.includes("?")||_.includes("#")||_.split("/").includes("..")||u.length!==1||N)&&m("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_PATH_INVALID",b);let y=Array.isArray(I.access?.allOf)?I.access.allOf:[];I.capability!==g&&!y.includes(g)&&m("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_CAPABILITY_INVALID",b)}i.set(l,{desktop:d,mobile:f})}return i}function Di(e){let t=new Map(e.data.resources.map((a,r)=>{let c=`/config/data/resources/${r}`,l=We(a,c,e.appCode);return[l.code,new Map(l.schema.fields.map(p=>[String(p.code),p]))]})),o=new Map(e.data.resources.map((a,r)=>{let c=`/config/data/resources/${r}`,l=We(a,c,e.appCode);return[l.code,new Map(l.schema.fields.map(p=>[String(p.code),String(p.type)]))]})),n=new Set(o.keys()),i=new Set(e.workflows.activations.map((a,r)=>Ht(T(a,`/config/workflows/activations/${r}`).workflowCode,`/config/workflows/activations/${r}/workflowCode`))),s=new Map;return Z(e.backend.operations.map((a,r)=>{let c=`/config/backend/operations/${r}`,l=T(a,c);R(l,["code","method","path","capability","requestSchema","responseSchema","description","platformAccess","browser","ai"],c,!0);let p=S(l.method,`${c}/method`,16);["GET","POST","PUT","PATCH","DELETE"].includes(p)||m("NATIVE_OPERATION_METHOD_INVALID",`${c}/method`);let d=F(l.code,`${c}/code`);Jr(l.ai,c,d,p,n);let f=qr(l.platformAccess,`${c}/platformAccess`,o,t,i,new Set(e.authz.roles.map(E=>String(E.code))));if(f?.decimalReservation){let E=f.decimalReservation,A=String(E.resourceCode),b=JSON.stringify([E.amountFieldCode,E.currencyFieldCode,E.relationFieldCode,E.parentFieldCode,E.rootFieldCode,E.statusFieldCode,E.parentRelationValue,E.childRelationValue]),I=s.get(A);I&&I!==b&&m("NATIVE_DECIMAL_RESERVATION_MAPPING_CONFLICT",`${c}/platformAccess/decimalReservation`),s.set(A,b)}let g=Kr(l.browser,`${c}/browser`,p,l.requestSchema,l.responseSchema,o,t,e.data.subjectReadSurfaces||[]);return{code:d,method:p,path:me(l.path,`${c}/path`),requiredCapability:Se(l.capability,`${c}/capability`,e.appCode),requestSchemaDigest:X(T(l.requestSchema,`${c}/requestSchema`)),responseSchemaDigest:X(T(l.responseSchema,`${c}/responseSchema`)),...l.description===void 0?{}:{description:Hn(l.description,`${c}/description`,2e3)},...f?{platformAccess:f}:{},...g?{browser:g}:{}}}),a=>a.code)}function Kr(e,t,o,n,i,s,a,r){if(e===void 0)return null;let c=T(e,t);R(c,["exposure","behavior","idempotency","subject"],t,["refreshTargets","fileIntent"]),j(c.exposure,"authenticated",`${t}/exposure`);let l=S(c.behavior,`${t}/behavior`,32);["read","controlled"].includes(l)||m("NATIVE_OPERATION_BROWSER_BEHAVIOR_INVALID",`${t}/behavior`);let p=S(c.idempotency,`${t}/idempotency`,32);(!["none","required"].includes(p)||l==="controlled"&&p!=="required"||l==="read"&&p!=="none")&&m("NATIVE_OPERATION_BROWSER_IDEMPOTENCY_INVALID",`${t}/idempotency`);let d=T(c.subject,`${t}/subject`);R(d,["resourceCode","inputField"],`${t}/subject`);let f=J(d.resourceCode,`${t}/subject/resourceCode`);s.has(f)||m("NATIVE_OPERATION_BROWSER_SUBJECT_RESOURCE_NOT_DECLARED",`${t}/subject/resourceCode`);let g=K(d.inputField,`${t}/subject/inputField`),E=T(n,`${t}/requestSchema`),A=T(i,`${t}/responseSchema`);(E.type!=="object"||E.additionalProperties!==!1||A.type!=="object"||A.additionalProperties!==!1)&&m("NATIVE_OPERATION_BROWSER_SCHEMA_ROOT_INVALID",`${t}/requestSchema`);let b=T(E.properties,`${t}/requestSchema/properties`),I=new Set(E.required===void 0?[]:v(E.required,`${t}/requestSchema/required`,200));(!(g in b)||!I.has(g))&&m("NATIVE_OPERATION_BROWSER_SUBJECT_INPUT_INVALID",`${t}/subject/inputField`);let _=T(b[g],`${t}/requestSchema/properties/${g}`);(_.type!=="string"||_.format!=="uuid")&&m("NATIVE_OPERATION_BROWSER_SUBJECT_INPUT_INVALID",`${t}/subject/inputField`);let u=new Map((Array.isArray(r)?r:[]).map((C,k)=>{let V=T(C,`/config/data/subjectReadSurfaces/${k}`);return[String(V.code),String(T(V.subject,`/config/data/subjectReadSurfaces/${k}/subject`).resourceCode)]})),N=c.refreshTargets===void 0?[]:w(c.refreshTargets,`${t}/refreshTargets`,16),y=new Set,O=Z(N.map((C,k)=>{let V=`${t}/refreshTargets/${k}`,M=T(C,V);R(M,["kind","code"],V),j(M.kind,"subject-surface",`${V}/kind`);let P=F(M.code,`${V}/code`);return(y.has(P)||!u.has(P)||u.get(P)!==f)&&m("NATIVE_OPERATION_BROWSER_REFRESH_TARGET_INVALID",`${V}/code`),y.add(P),{kind:"subject-surface",code:P}}),C=>`${C.kind}:${C.code}`),h=Gr(c.fileIntent,`${t}/fileIntent`,o,l,p,f,b,I,a);return{exposure:"authenticated",behavior:l,idempotency:p,subject:{resourceCode:f,inputField:g},...O.length?{refreshTargets:O}:{},...h?{fileIntent:h}:{}}}function Gr(e,t,o,n,i,s,a,r,c){if(e===void 0)return null;let l=T(e,t);R(l,["recordResourceCode","recordIdInputField","relationField","fileNameField","contentTypeField","sizeField","purposes","maxTtlSeconds","maxBytes"],t),(o!=="GET"||n!=="read"||i!=="none")&&m("NATIVE_OPERATION_FILE_INTENT_BEHAVIOR_INVALID",t);let p=J(l.recordResourceCode,`${t}/recordResourceCode`),d=c.get(p);d||m("NATIVE_OPERATION_FILE_INTENT_RESOURCE_NOT_DECLARED",`${t}/recordResourceCode`);let f=K(l.recordIdInputField,`${t}/recordIdInputField`),g=T(a[f],`${t}/recordIdInputField`);(!r.has(f)||g.type!=="string"||g.format!=="uuid")&&m("NATIVE_OPERATION_FILE_INTENT_RECORD_INPUT_INVALID",`${t}/recordIdInputField`);let E=K(l.relationField,`${t}/relationField`),A=d.get(E);(!A||!["uuid","resource-ref.single"].includes(String(A.type))||String(A.type)==="resource-ref.single"&&(String(T(A.source,`${t}/relationField`).kind||"")!=="resource"||String(T(A.source,`${t}/relationField`).resourceCode||"")!==s))&&m("NATIVE_OPERATION_FILE_INTENT_RELATION_INVALID",`${t}/relationField`);let b=[["fileNameField",["text.short","text.long"]],["contentTypeField",["text.short","text.long"]],["sizeField",["number.integer"]]],I={};for(let[y,O]of b){let h=K(l[y],`${t}/${y}`);O.includes(String(d.get(h)?.type))||m("NATIVE_OPERATION_FILE_INTENT_METADATA_INVALID",`${t}/${y}`),I[y]=h}let _=Z(v(l.purposes,`${t}/purposes`,2),y=>y);(!_.length||_.some(y=>!["preview","download"].includes(y)))&&m("NATIVE_OPERATION_FILE_INTENT_PURPOSE_INVALID",`${t}/purposes`);let u=Number(l.maxTtlSeconds);(!Number.isSafeInteger(u)||u<1||u>300)&&m("NATIVE_OPERATION_FILE_INTENT_TTL_INVALID",`${t}/maxTtlSeconds`);let N=Number(l.maxBytes);return(!Number.isSafeInteger(N)||N<1||N>104857600)&&m("NATIVE_OPERATION_FILE_INTENT_SIZE_INVALID",`${t}/maxBytes`),{recordResourceCode:p,recordIdInputField:f,relationField:E,fileNameField:I.fileNameField,contentTypeField:I.contentTypeField,sizeField:I.sizeField,purposes:_,maxTtlSeconds:u,maxBytes:N}}function qr(e,t,o,n,i,s){if(e===void 0)return null;let a=T(e,t);R(a,["directory","managedFiles","managedFileCopies","notification","workflow","roleAssertions","decimalReservation"],t,!0),Object.keys(a).length===0&&m("NATIVE_OPERATION_PLATFORM_ACCESS_EMPTY",t);let r={};if(a.roleAssertions!==void 0){let c=T(a.roleAssertions,`${t}/roleAssertions`);R(c,["roleCodes"],`${t}/roleAssertions`);let l=v(c.roleCodes,`${t}/roleAssertions/roleCodes`,20);l.length||m("NATIVE_OPERATION_ROLE_ASSERTIONS_REQUIRED",`${t}/roleAssertions/roleCodes`),l.forEach((p,d)=>{s.has(p)||m("NATIVE_ROLE_REFERENCE_MISSING",`${t}/roleAssertions/roleCodes/${d}`)}),r.roleAssertions={roleCodes:U(l)}}if(a.directory!==void 0){let c=T(a.directory,`${t}/directory`);R(c,["mode","fields"],`${t}/directory`),["current-initiator","selected-user"].includes(String(c.mode))||m("NATIVE_OPERATION_DIRECTORY_MODE_INVALID",`${t}/directory/mode`);let l=new Set(["displayName","employeeNumber","primaryDepartment","departments"]),p=v(c.fields,`${t}/directory/fields`,4);(!p.length||p.some(d=>!l.has(d)))&&m("NATIVE_OPERATION_DIRECTORY_FIELDS_INVALID",`${t}/directory/fields`),r.directory={mode:String(c.mode),fields:U(p)}}if(a.managedFiles!==void 0){let c=w(a.managedFiles,`${t}/managedFiles`,16);c.length||m("NATIVE_OPERATION_MANAGED_FILES_REQUIRED",`${t}/managedFiles`);let l=new Set;r.managedFiles=Z(c.map((p,d)=>{let f=`${t}/managedFiles/${d}`,g=T(p,f);R(g,["resourceCode","fieldCodes","intents"],f);let E=J(g.resourceCode,`${f}/resourceCode`);(l.has(E)||!o.has(E))&&m("NATIVE_OPERATION_MANAGED_FILE_RESOURCE_INVALID",`${f}/resourceCode`),l.add(E);let A=v(g.fieldCodes,`${f}/fieldCodes`,16);(!A.length||A.some(I=>!["file","image","signature","text.rich"].includes(String(o.get(E)?.get(I)||""))))&&m("NATIVE_OPERATION_MANAGED_FILE_FIELD_INVALID",`${f}/fieldCodes`);let b=v(g.intents,`${f}/intents`,2);return(!b.length||b.some(I=>!["create","update"].includes(I)))&&m("NATIVE_OPERATION_MANAGED_FILE_INTENT_INVALID",`${f}/intents`),{resourceCode:E,fieldCodes:U(A),intents:U(b)}}),p=>p.resourceCode)}if(a.managedFileCopies!==void 0){let c=w(a.managedFileCopies,`${t}/managedFileCopies`,16);c.length||m("NATIVE_OPERATION_MANAGED_FILE_COPIES_REQUIRED",`${t}/managedFileCopies`);let l=new Set;r.managedFileCopies=Z(c.map((p,d)=>{let f=`${t}/managedFileCopies/${d}`,g=T(p,f);R(g,["mode","sourceResourceCode","sourceFieldCodes","targetResourceCode","targetFieldCodes"],f),j(g.mode,"copy",`${f}/mode`);let E=J(g.sourceResourceCode,`${f}/sourceResourceCode`),A=J(g.targetResourceCode,`${f}/targetResourceCode`),b=o.get(E),I=o.get(A);(!b||!I)&&m("NATIVE_OPERATION_MANAGED_FILE_COPY_RESOURCE_INVALID",f);let _=v(g.sourceFieldCodes,`${f}/sourceFieldCodes`,16),u=v(g.targetFieldCodes,`${f}/targetFieldCodes`,16);(!_.length||_.length!==u.length)&&m("NATIVE_OPERATION_MANAGED_FILE_COPY_FIELDS_INVALID",f),_.forEach((y,O)=>{let h=b.get(y),C=I.get(u[O]);(!["file","image"].includes(String(h))||h!==C)&&m("NATIVE_OPERATION_MANAGED_FILE_COPY_FIELD_INVALID",`${f}/sourceFieldCodes/${O}`)});let N=`${E}:${_.join(",")}=>${A}:${u.join(",")}`;return l.has(N)&&m("NATIVE_OPERATION_MANAGED_FILE_COPY_DUPLICATE",f),l.add(N),{mode:"copy",sourceResourceCode:E,sourceFieldCodes:U(_),targetResourceCode:A,targetFieldCodes:U(u)}}),p=>`${p.sourceResourceCode}:${p.sourceFieldCodes.join(",")}=>${p.targetResourceCode}:${p.targetFieldCodes.join(",")}`)}if(a.notification!==void 0){let c=T(a.notification,`${t}/notification`);R(c,["mode"],`${t}/notification`),c.mode!=="business-standard"&&m("NATIVE_OPERATION_NOTIFICATION_MODE_INVALID",`${t}/notification/mode`),r.notification={mode:"business-standard"}}if(a.workflow!==void 0){let c=T(a.workflow,`${t}/workflow`);R(c,["codes"],`${t}/workflow`);let l=v(c.codes,`${t}/workflow/codes`,16);(!l.length||l.some(p=>!i.has(p)))&&m("NATIVE_OPERATION_WORKFLOW_CODE_INVALID",`${t}/workflow/codes`),r.workflow={codes:U(l)}}if(a.decimalReservation!==void 0){let c=`${t}/decimalReservation`,l=T(a.decimalReservation,c);R(l,["mode","resourceCode","amountFieldCode","currencyFieldCode","relationFieldCode","parentFieldCode","rootFieldCode","statusFieldCode","parentRelationValue","childRelationValue","eligibleParentStatuses","eligibleChildStatuses"],c);let p=S(l.mode,`${c}/mode`,16);["reserve","commit","release"].includes(p)||m("NATIVE_DECIMAL_RESERVATION_MODE_INVALID",`${c}/mode`);let d=J(l.resourceCode,`${c}/resourceCode`),f=n.get(d);f||m("NATIVE_DECIMAL_RESERVATION_RESOURCE_MISSING",`${c}/resourceCode`);let E=Object.fromEntries(["amountFieldCode","currencyFieldCode","relationFieldCode","parentFieldCode","rootFieldCode","statusFieldCode"].map(y=>[y,K(l[y],`${c}/${y}`)])),A=y=>f.get(E[y]),b=y=>new Set((A(y)?.options||[]).map(O=>String(O.value))),I=F(l.parentRelationValue,`${c}/parentRelationValue`),_=F(l.childRelationValue,`${c}/childRelationValue`),u=v(l.eligibleParentStatuses,`${c}/eligibleParentStatuses`,16),N=v(l.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"||I===_||!b("relationFieldCode").has(I)||!b("relationFieldCode").has(_)||!u.length||!N.length||u.some(y=>!b("statusFieldCode").has(y))||N.some(y=>!b("statusFieldCode").has(y)))&&m("NATIVE_DECIMAL_RESERVATION_FIELD_INVALID",c),r.decimalReservation={mode:p,resourceCode:d,...E,parentRelationValue:I,childRelationValue:_,eligibleParentStatuses:U(u),eligibleChildStatuses:U(N)}}return r}function Jr(e,t,o,n,i){if(e===void 0)return;let s=`${t}/ai`,a=T(e,s);pr.test(o)||m("NATIVE_OPERATION_AI_CODE_INVALID",`${t}/code`),R(a,["name","description","risk","resources","sideEffects","concurrency","timeoutMs"],s,!0),S(a.name,`${s}/name`,Mn),S(a.description,`${s}/description`,Mn);let r=S(a.risk,`${s}/risk`,16);["read","write","destructive","external"].includes(r)||m("NATIVE_OPERATION_AI_RISK_INVALID",`${s}/risk`),r==="read"!=(n==="GET")&&m("NATIVE_OPERATION_AI_METHOD_RISK_MISMATCH",`${s}/risk`),n==="DELETE"&&!["destructive","external"].includes(r)&&m("NATIVE_OPERATION_AI_METHOD_RISK_MISMATCH",`${s}/risk`);let c=v(a.resources,`${s}/resources`,16);c.length===0&&m("NATIVE_OPERATION_AI_RESOURCE_REQUIRED",`${s}/resources`),c.forEach((p,d)=>{let f=J(p,`${s}/resources/${d}`);i.has(f)||m("NATIVE_OPERATION_AI_RESOURCE_MISSING",`${s}/resources/${d}`)});let l=v(a.sideEffects,`${s}/sideEffects`,20);(r==="read"&&l.length!==0||r!=="read"&&l.length===0)&&m("NATIVE_OPERATION_AI_SIDE_EFFECT_INVALID",`${s}/sideEffects`),a.concurrency!==void 0&&!["none","revision"].includes(S(a.concurrency,`${s}/concurrency`,16))&&m("NATIVE_OPERATION_AI_CONCURRENCY_INVALID",`${s}/concurrency`),a.timeoutMs!==void 0&&te(a.timeoutMs,`${s}/timeoutMs`,100,3e4)}function Kt(e){return(e.replace(/\/{2,}/g,"/").replace(/\/$/,"")||"/").split("/").map(o=>o.startsWith(":")?":":o.includes("*")?"*":o).join("/")}function zr(e,t){let o=T(e,t),n=S(o.type,`${t}/type`,32),i=["code","type","label","presentation","required"],s=n==="sso"?[...i,"provider"]:n==="dingtalk"?[...i,"flow"]:i;R(o,s,t);let a=F(o.code,`${t}/code`),r=S(o.label,`${t}/label`,255),c=S(o.presentation,`${t}/presentation`,16);["primary","secondary"].includes(c)||m("NATIVE_APPLICATION_AUTH_METHOD_PRESENTATION_INVALID",`${t}/presentation`);let l=Xe(o.required,`${t}/required`);return["sso","password","dingtalk"].includes(n)||m("NATIVE_APPLICATION_AUTH_METHOD_TYPE_INVALID",`${t}/type`),n==="sso"&&o.provider!=="tenant-default"&&m("NATIVE_APPLICATION_AUTH_SSO_PROVIDER_INVALID",`${t}/provider`),n==="dingtalk"&&!["auto","jsapi","oauth"].includes(S(o.flow,`${t}/flow`,16))&&m("NATIVE_APPLICATION_AUTH_DINGTALK_FLOW_INVALID",`${t}/flow`),{code:a,type:n,label:r,presentation:c,required:l,...n==="sso"?{provider:"tenant-default"}:{},...n==="dingtalk"?{flow:o.flow}:{}}}function pi(e,t,o){let n=T(e,o);R(n,["routeCode","path","defaultRouteCode"],o);let i=F(n.routeCode,`${o}/routeCode`),s=me(n.path,`${o}/path`),a=t==="desktop"?"/login":"/m/login";return(s!==a||/[:*?#\\]/.test(s))&&m("NATIVE_APPLICATION_AUTH_SURFACE_PATH_INVALID",`${o}/path`,{device:t,expectedPath:a}),{routeCode:i,path:s,defaultRouteCode:F(n.defaultRouteCode,`${o}/defaultRouteCode`)}}function $i(e,t,o,n){if(e===null)return;let i=T(e,n);R(i,["accountMode","registration","methods","surfaces"],n),j(i.accountMode,"existing-platform-users-only",`${n}/accountMode`);let s=T(i.registration,`${n}/registration`);R(s,["mode"],`${n}/registration`),j(s.mode,"reject",`${n}/registration/mode`);let a=w(i.methods,`${n}/methods`,8);a.length===0&&m("NATIVE_APPLICATION_AUTH_METHOD_REQUIRED",`${n}/methods`);let r=a.map((I,_)=>zr(I,`${n}/methods/${_}`)),c=new Set,l=new Set;for(let[I,_]of r.entries())c.has(_.code)&&m("NATIVE_APPLICATION_AUTH_METHOD_CODE_DUPLICATE",`${n}/methods/${I}/code`),l.has(_.type)&&m("NATIVE_APPLICATION_AUTH_METHOD_TYPE_DUPLICATE",`${n}/methods/${I}/type`),c.add(_.code),l.add(_.type);r.filter(I=>I.presentation==="primary").length!==1&&m("NATIVE_APPLICATION_AUTH_PRIMARY_METHOD_INVALID",`${n}/methods`);let p=T(i.surfaces,`${n}/surfaces`);R(p,["desktop","mobile"],`${n}/surfaces`);let d=pi(p.desktop,"desktop",`${n}/surfaces/desktop`),f=pi(p.mobile,"mobile",`${n}/surfaces/mobile`);d.routeCode===f.routeCode&&m("NATIVE_APPLICATION_AUTH_SURFACE_CODE_DUPLICATE",`${n}/surfaces/mobile/routeCode`);let g=w(t,"/config/frontend/routes",500),E=new Map;for(let[I,_]of g.entries()){let u=T(_,`/config/frontend/routes/${I}`);E.set(String(u.code||""),u)}let A=new Set((Array.isArray(o.data?.resources)?o.data.resources:[]).map(I=>String(I.code||"")).filter(I=>/^[a-z][a-z0-9-]{0,62}$/.test(I)));for(let[I,_]of[["desktop",d],["mobile",f]]){E.has(_.routeCode)&&m("NATIVE_APPLICATION_AUTH_SURFACE_CODE_CONFLICT",`${n}/surfaces/${I}/routeCode`);let u=/^user\.([a-z][a-z0-9-]{0,62})\.(records|submit)$/.exec(String(_.defaultRouteCode||"")),N=E.get(_.defaultRouteCode),y=String(N?.path||"");if(u&&A.has(u[1])){let h=u[2]==="records"?`/my/${u[1]}`:`/my/${u[1]}/submit`;N={surface:"user",path:I==="mobile"?`/m${h}`:h},y=String(N.path)}let O=I==="desktop"?y==="/m"||y.startsWith("/m/"):!(y==="/m"||y.startsWith("/m/"));(!N||N.surface!=="user"||/[:*]/.test(y)||O)&&m("NATIVE_APPLICATION_AUTH_DEFAULT_ROUTE_INVALID",`${n}/surfaces/${I}/defaultRouteCode`)}let b=ki(o).filter(I=>!I.owner.startsWith("authentication:"));for(let[I,_]of[["desktop",d],["mobile",f]]){let u=b.find(N=>Kt(N.path)===Kt(_.path));u&&m("NATIVE_APPLICATION_AUTH_SURFACE_PATH_CONFLICT",`${n}/surfaces/${I}/path`,{owner:u.owner})}}function Yr(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=T(e,t),i=T(n.surfaces,`${t}/surfaces`),s={...n,surfaces:{...i,desktop:{...T(i.desktop,`${t}/surfaces/desktop`),defaultRouteCode:"auth-desktop-default"},mobile:{...T(i.mobile,`${t}/surfaces/mobile`),defaultRouteCode:"auth-mobile-default"}}};$i(s,o.frontend.routes,{...o,frontend:{...o.frontend,authentication:s}},t)}function Hr(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 Xr=new Set(["draft.read","draft.update","validate","create","own.list","own.read","public.list","public.read"]);function Qr(e,t,o){let n=T(e,o);R(n,["policies"],o);let i=w(n.policies,`${o}/policies`,16);i.length<1&&m("NATIVE_PUBLIC_POLICY_REQUIRED",o);let s=new Map(t.frontend.routes.map(l=>[l.code,l])),a=new Map(t.data.resources.map(l=>[l.code,l])),r=new Set,c=new Set(i.map(l=>String(l?.code||"")));i.forEach((l,p)=>{let d=`${o}/policies/${p}`,f=T(l,d);R(f,["code","routeCode","mode","resourceCode","operations","fields"],d,["requiredFields","ownRecordFields","publicRecordFields","publicFilters","serverGeneratedFields","schedule","publicSubtableFields","draft","validations"]);let g=F(f.code,`${d}/code`);r.has(g)&&m("NATIVE_PUBLIC_POLICY_DUPLICATE",`${d}/code`);let E=F(f.routeCode,`${d}/routeCode`),A=s.get(E);(!A||A.surface!=="user"||A.capability!==void 0||A.access!==void 0||/[:*]/.test(String(A.path)))&&m("NATIVE_PUBLIC_ROUTE_INVALID",`${d}/routeCode`),j(f.mode,"anonymous",`${d}/mode`);let b=J(f.resourceCode,`${d}/resourceCode`),I=a.get(b);I||m("NATIVE_PUBLIC_RESOURCE_MISSING",`${d}/resourceCode`);let _=new Map(I.schema.fields.map($=>[String($.code),String($.type)])),u=v(f.operations,`${d}/operations`,8);(u.length<1||u.some($=>!Xr.has($)))&&m("NATIVE_PUBLIC_OPERATION_INVALID",`${d}/operations`),u.includes("draft.read")!==u.includes("draft.update")&&m("NATIVE_PUBLIC_DRAFT_OPERATION_INCOMPLETE",`${d}/operations`);let N=v(f.fields,`${d}/fields`,64);(N.length<1||N.some($=>!_.has($)))&&m("NATIVE_PUBLIC_FIELD_INVALID",`${d}/fields`);for(let $ of["requiredFields","ownRecordFields","publicRecordFields"]){if(!Object.prototype.hasOwnProperty.call(f,$))continue;v(f[$],`${d}/${$}`,64).some(L=>!N.includes(L))&&m("NATIVE_PUBLIC_FIELD_SCOPE_INVALID",`${d}/${$}`)}let y=Object.prototype.hasOwnProperty.call(f,"serverGeneratedFields")?w(f.serverGeneratedFields,`${d}/serverGeneratedFields`,16):[],O=new Set;y.forEach(($,W)=>{let L=`${d}/serverGeneratedFields/${W}`,G=T($,L);R(G,["field","kind"],L);let q=K(G.field,`${L}/field`);(O.has(q)||!_.has(q)||N.includes(q)||_.get(q)!=="text.short"&&_.get(q)!=="text.long")&&m("NATIVE_PUBLIC_SERVER_GENERATED_FIELD_INVALID",`${L}/field`),j(G.kind,"random-token",`${L}/kind`),O.add(q)});let h=Object.prototype.hasOwnProperty.call(f,"schedule")?T(f.schedule,`${d}/schedule`):null;if(h){let $=["campusPolicyCode","rulePolicyCode","campusField","ruleCampusField","ruleWeekdaysField","ruleOpenAtField","ruleCloseAtField","ruleSlotMinutesField","ruleAdvanceHoursField","ruleAdvanceDaysField","campusEnabledField","ruleEnabledField","dateField","timeField"];R(h,$,`${d}/schedule`);for(let W of["campusPolicyCode","rulePolicyCode"])F(h[W],`${d}/schedule/${W}`);for(let W of $.filter(L=>!["campusPolicyCode","rulePolicyCode"].includes(L)))K(h[W],`${d}/schedule/${W}`);for(let W of[h.campusField,h.dateField,h.timeField])N.includes(String(W))||m("NATIVE_PUBLIC_SCHEDULE_FIELD_INVALID",`${d}/schedule`);(!c.has(String(h.campusPolicyCode))||!c.has(String(h.rulePolicyCode)))&&m("NATIVE_PUBLIC_SCHEDULE_POLICY_INVALID",`${d}/schedule`)}let C=Object.prototype.hasOwnProperty.call(f,"publicFilters")?w(f.publicFilters,`${d}/publicFilters`,16):[],k=new Set;C.forEach(($,W)=>{let L=`${d}/publicFilters/${W}`,G=T($,L);R(G,["field","operator","value"],L);let q=K(G.field,`${L}/field`);k.has(q)&&m("NATIVE_PUBLIC_FILTER_DUPLICATE",`${L}/field`),N.includes(q)||m("NATIVE_PUBLIC_FILTER_FIELD_INVALID",`${L}/field`),j(G.operator,"eq",`${L}/operator`),["boolean","text.short","text.long","number.integer","number.decimal","date","time"].includes(_.get(q)||"")||m("NATIVE_PUBLIC_FILTER_FIELD_INVALID",`${L}/field`),G.value!==null&&typeof G.value!="string"&&typeof G.value!="number"&&typeof G.value!="boolean"&&m("NATIVE_PUBLIC_FILTER_VALUE_INVALID",`${L}/value`),k.add(q)});let V=Object.prototype.hasOwnProperty.call(f,"publicSubtableFields")?T(f.publicSubtableFields,`${d}/publicSubtableFields`):null;if(V){Object.keys(V).length>64&&m("NATIVE_PUBLIC_SUBTABLE_FIELDS_INVALID",`${d}/publicSubtableFields`);for(let[$,W]of Object.entries(V)){let L=I.schema.fields.find(Q=>String(Q.code)===$),G=String(L?.subtable?.resourceCode||""),q=a.get(G),Oe=new Map((q?.schema?.fields||[]).map(Q=>[String(Q.code),String(Q.type)])),z=v(W,`${d}/publicSubtableFields/${$}`,64);(!N.includes($)||_.get($)!=="subtable"||!q||z.length<1||z.some(Q=>!Oe.has(Q))||z.some(Q=>Oe.get(Q)==="subtable")||z.some(Q=>Oe.get(Q)==="signature"))&&m("NATIVE_PUBLIC_SUBTABLE_FIELDS_INVALID",`${d}/publicSubtableFields/${$}`)}}if(u.some($=>$.startsWith("public."))){Object.prototype.hasOwnProperty.call(f,"publicRecordFields")||m("NATIVE_PUBLIC_RECORD_FIELDS_REQUIRED",`${d}/publicRecordFields`);let $=v(f.publicRecordFields,`${d}/publicRecordFields`,64);($.length<1||$.some(W=>!N.includes(W))||$.some(W=>_.get(W)==="signature"||_.get(W)==="subtable"&&!V?.[W]))&&m("NATIVE_PUBLIC_RECORD_FIELDS_INVALID",`${d}/publicRecordFields`)}let M=Object.prototype.hasOwnProperty.call(f,"requiredFields")?v(f.requiredFields,`${d}/requiredFields`,64):[],P=I.surface||{},se=P.fields||{},ge=String(P.mutationOwner||"native")==="native"&&P.generated?.create!==!1,H=I.schema.fields.filter($=>Ot($,se[$.code])).map($=>String($.code));if(u.includes("create")&&!ge&&m("NATIVE_PUBLIC_CREATE_FIELDS_INCOMPLETE",`${d}/fields`),u.includes("create")&&!Object.prototype.hasOwnProperty.call(f,"draft")&&m("NATIVE_PUBLIC_DRAFT_REQUIRED",`${d}/draft`),u.includes("create"))for(let $ of H){let W=N.includes($)?M.includes($)?null:"requiredFields":"fields";W&&m("NATIVE_PUBLIC_CREATE_FIELDS_INCOMPLETE",`${d}/${W}`,{resourceCode:J,fieldCode:$})}if(Object.prototype.hasOwnProperty.call(f,"draft")){let $=T(f.draft,`${d}/draft`);R($,["enabled","inactivityTtlSeconds","maxBytes"],`${d}/draft`),j($.enabled,!0,`${d}/draft/enabled`),te($.inactivityTtlSeconds,`${d}/draft/inactivityTtlSeconds`,3600,7776e3),te($.maxBytes,`${d}/draft/maxBytes`,4096,262144)}else u.includes("draft.read")&&m("NATIVE_PUBLIC_DRAFT_REQUIRED",`${d}/draft`);let Te=Object.prototype.hasOwnProperty.call(f,"validations")?w(f.validations,`${d}/validations`,16):[],ce=new Set;Te.forEach(($,W)=>{let L=`${d}/validations/${W}`,G=T($,L);R(G,["code","kind","fields","result"],L);let q=F(G.code,`${L}/code`);ce.has(q)&&m("NATIVE_PUBLIC_VALIDATION_DUPLICATE",`${L}/code`),j(G.kind,"duplicate",`${L}/kind`),j(G.result,"availability",`${L}/result`);let Oe=v(G.fields,`${L}/fields`,8);(Oe.length<1||Oe.some(z=>!N.includes(z))||Oe.some(z=>["file","subtable"].includes(_.get(z)||"")))&&m("NATIVE_PUBLIC_VALIDATION_FIELD_INVALID",`${L}/fields`),ce.add(q)}),r.add(g)})}function Zr(e,t){let o=T(e,t);R(o,["policies"],t),w(o.policies,`${t}/policies`,16).length<1&&m("NATIVE_PUBLIC_POLICY_REQUIRED",t)}function ea(e){return{policies:Z(e.frontend.publicAccess.policies.map(t=>({code:t.code,routeCode:t.routeCode,mode:t.mode,resourceCode:t.resourceCode,operations:U(t.operations),fields:U(t.fields),...t.requiredFields?{requiredFields:U(t.requiredFields)}:{},...t.ownRecordFields?{ownRecordFields:U(t.ownRecordFields)}:{},...t.publicRecordFields?{publicRecordFields:U(t.publicRecordFields)}:{},...t.publicFilters?{publicFilters:t.publicFilters.map(o=>({field:o.field,operator:o.operator,value:o.value})).sort((o,n)=>ue(o.field,n.field))}:{},...t.publicSubtableFields?{publicSubtableFields:Object.fromEntries(Object.entries(t.publicSubtableFields).sort(([o],[n])=>o.localeCompare(n)).map(([o,n])=>[o,U(Array.isArray(n)?n.map(String):[])]))}:{},...t.serverGeneratedFields?{serverGeneratedFields:t.serverGeneratedFields.map(o=>({field:o.field,kind:o.kind})).sort((o,n)=>ue(o.field,n.field))}:{},...t.schedule?{schedule:{campusPolicyCode:t.schedule.campusPolicyCode,rulePolicyCode:t.schedule.rulePolicyCode,campusField:t.schedule.campusField,ruleCampusField:t.schedule.ruleCampusField,ruleWeekdaysField:t.schedule.ruleWeekdaysField,ruleOpenAtField:t.schedule.ruleOpenAtField,ruleCloseAtField:t.schedule.ruleCloseAtField,ruleSlotMinutesField:t.schedule.ruleSlotMinutesField,ruleAdvanceHoursField:t.schedule.ruleAdvanceHoursField,ruleAdvanceDaysField:t.schedule.ruleAdvanceDaysField,campusEnabledField:t.schedule.campusEnabledField,ruleEnabledField:t.schedule.ruleEnabledField,dateField:t.schedule.dateField,timeField:t.schedule.timeField}}:{},...t.draft?{draft:{...t.draft}}:{},...t.validations?{validations:Z(t.validations.map(o=>({code:o.code,kind:o.kind,fields:U(o.fields),result:o.result})),o=>o.code)}:{}})),t=>t.code)}}function ki(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=Vi(o),i=`/admin/resources/${o.code}`,s=[["list",i],["detail",`${i}/:id`],["create",`${i}/new`],["update",`${i}/:id/edit`]];for(let[a,r]of s)n[a]&&t.push({owner:`resource:${o.code}:${a}`,path:r},{owner:`resource:${o.code}:${a}:mobile`,path:`/m${r}`})}if(e.frontend.user.applicationTodoCenter===!0&&t.push({owner:"application:todo-center",path:"/todos"},{owner:"application:todo-center:mobile",path:"/m/todos"}),e.workflows.definitions.length>0){t.push({owner:"workflow:work-center",path:"/work-center"},{owner:"workflow:work-center:mobile",path:"/m/work-center"},{owner:"workflow:task",path:"/tasks/:taskId"},{owner:"workflow:task:mobile",path:"/m/tasks/:taskId"},{owner:"workflow:instance",path:"/workflows/:instanceId"},{owner:"workflow:instance:mobile",path:"/m/workflows/:instanceId"});let o=!1;for(let n of e.workflows.definitions)["standalone","hidden-handoff"].includes(n.launch.mode)&&(o=!0);o&&t.push({owner:"workflow:launch",path:"/workflows/:workflowCode/start"},{owner:"workflow:launch:mobile",path:"/m/workflows/:workflowCode/start"})}return t}function zt(e){let t=new Map(ki(e).map(o=>[Kt(o.path),o]));return Z(e.frontend.routes.map((o,n)=>{let i=`/config/frontend/routes/${n}`,s=T(o,i);R(s,["code","path","label","surface","parentCode","capability","access","pinned","tabPersistence","keepAlive"],i,!0),["admin","user"].includes(s.surface)||m("NATIVE_ROUTE_SURFACE_INVALID",`${i}/surface`);let a=me(s.path,`${i}/path`);s.surface==="admin"&&a!=="/admin"&&!a.startsWith("/admin/")&&m("NATIVE_ADMIN_ROUTE_PATH_INVALID",`${i}/path`),s.surface==="user"&&(a==="/admin"||a.startsWith("/admin/"))&&m("NATIVE_USER_ROUTE_PATH_RESERVED",`${i}/path`);let r=Kt(a),c=t.get(r);c&&m("NATIVE_ROUTE_PATH_CONFLICT",`${i}/path`,{path:a,owner:c.owner}),t.set(r,{owner:`frontend:${String(s.code||n)}`,path:a});let l=/[:*]/.test(a),p=Yn(s,i,e.appCode),d=s.pinned===void 0?void 0:Xe(s.pinned,`${i}/pinned`),f=s.tabPersistence===void 0?l?"none":"session":S(s.tabPersistence,`${i}/tabPersistence`,16),g=s.keepAlive===void 0?"none":S(s.keepAlive,`${i}/keepAlive`,16);return["session","none"].includes(f)||m("NATIVE_ROUTE_TAB_PERSISTENCE_INVALID",`${i}/tabPersistence`),["none","memory"].includes(g)||m("NATIVE_ROUTE_KEEP_ALIVE_INVALID",`${i}/keepAlive`),l&&d===!0&&m("NATIVE_DYNAMIC_ROUTE_PINNED_FORBIDDEN",`${i}/pinned`),l&&f==="session"&&m("NATIVE_DYNAMIC_ROUTE_TAB_PERSISTENCE_FORBIDDEN",`${i}/tabPersistence`),l&&g==="memory"&&m("NATIVE_DYNAMIC_ROUTE_KEEP_ALIVE_FORBIDDEN",`${i}/keepAlive`),{code:F(s.code,`${i}/code`),path:a,label:S(s.label,`${i}/label`,255),surface:s.surface,...s.parentCode===void 0?{}:{parentCode:F(s.parentCode,`${i}/parentCode`)},...p,...d===void 0?{}:{pinned:d},tabPersistence:f,keepAlive:g}}),o=>o.code)}function Vi(e){let t=e.surface===void 0?{}:T(e.surface,"/surface"),o=t.mutationOwner||"native",n=t.generated===void 0?{}:T(t.generated,"/surface/generated"),i=o==="native";return{list:n.list??!0,detail:n.detail??!0,create:n.create??i,update:n.update??i,delete:n.delete??i}}function Fi(e){let t=[];for(let o of Z(e.data.resources,n=>n.code).flatMap(n=>[{resource:n,viewCode:void 0},...(n.surface?.views||[]).map(i=>({viewCode:i.code,resource:{...n,name:i.name,surface:mn(n.surface,i.code)}}))])){let{resource:n,viewCode:i}=o,s=`/admin/resources/${n.code}${i?`/views/${i}`:""}`,a=Vi(n),r=[{operation:"list",kind:"resource-list",path:`${s}`,label:n.name,capability:n.capabilities.read,navigationEligible:!0},{operation:"detail",kind:"resource-detail",path:`${s}/:id`,label:`${n.name}\u8BE6\u60C5`,capability:n.capabilities.read,navigationEligible:!1},{operation:"create",kind:"resource-create",path:`${s}/new`,label:`\u65B0\u589E${n.name}`,capability:n.capabilities.create,navigationEligible:!1},{operation:"update",kind:"resource-update",path:`${s}/:id/edit`,label:`\u7F16\u8F91${n.name}`,capability:n.capabilities.update,navigationEligible:!1}];for(let c of r)a[c.operation]&&t.push({code:`resource:${n.code}${i?`:view:${i}`:""}:${c.operation}`,kind:c.kind,path:c.path,label:c.label,navigationEligible:c.navigationEligible,capability:c.capability,resourceCode:n.code,...i?{viewCode:i}:{}})}for(let o of zt(e))o.surface==="admin"&&t.push({code:`operation:${o.code}`,kind:"operation",path:o.path,label:o.label,navigationEligible:!/[:*]/.test(o.path),routeCode:o.code});return t.sort((o,n)=>ue(o.code,n.code))}function vi(e){return e.kind==="resource"?`resource:${e.resourceCode}${e.viewCode?`:view:${e.viewCode}`:""}:list`:`operation:${e.routeCode}`}function ta(e){return e.frontend.admin.navigation.map((t,o)=>({code:t.code,label:t.label,...t.icon===void 0?{}:{icon:t.icon},order:t.order??o,items:t.items.map((n,i)=>({pageCode:vi(n.page),...n.label===void 0?{}:{label:n.label},...n.icon===void 0?{}:{icon:n.icon},order:n.order??i})).sort((n,i)=>n.order-i.order||ue(n.pageCode,i.pageCode))})).sort((t,o)=>t.order-o.order||ue(t.code,o.code))}function na(e,t){let o=w(e,t,Y.adminNavigationGroups),n=0;o.forEach((i,s)=>{let a=`${t}/${s}`,r=T(i,a);R(r,["code","label","icon","order","items"],a,!0),F(r.code,`${a}/code`),S(r.label,`${a}/label`,255),Gt(r.icon,`${a}/icon`),Ei(r.order,`${a}/order`);let c=w(r.items,`${a}/items`,500);c.length===0&&m("NATIVE_ADMIN_GROUP_ORPHANED",`${a}/items`),n+=c.length,n>Y.adminNavigationItems&&m("NATIVE_ARRAY_LIMIT_EXCEEDED",t),c.forEach((l,p)=>{let d=`${a}/items/${p}`,f=T(l,d);R(f,["page","label","icon","order"],d,!0),oa(f.page,`${d}/page`),f.label!==void 0&&S(f.label,`${d}/label`,255),Gt(f.icon,`${d}/icon`),Ei(f.order,`${d}/order`)})})}function oa(e,t){let o=T(e,t),n=S(o.kind,`${t}/kind`,64);if(n==="resource"){R(o,["kind","resourceCode"],t,["viewCode"]),o.viewCode!==void 0&&F(o.viewCode,`${t}/viewCode`),J(o.resourceCode,`${t}/resourceCode`);return}if(n==="operation"){R(o,["kind","routeCode"],t),F(o.routeCode,`${t}/routeCode`);return}m("NATIVE_ADMIN_PAGE_REFERENCE_KIND_INVALID",`${t}/kind`)}function ia(e){let t=new Map(Fi(e).map(i=>[String(i.code),i])),o=new Set,n=new Set;e.frontend.admin.navigation.forEach((i,s)=>{let a=`/config/frontend/admin/navigation/${s}`;o.has(i.code)&&m("NATIVE_ADMIN_GROUP_DUPLICATE",`${a}/code`),o.add(i.code),i.label===i.code&&m("NATIVE_ADMIN_USER_LABEL_REQUIRED",`${a}/label`),i.items.forEach((r,c)=>{let l=`${a}/items/${c}`,p=vi(r.page),d=t.get(p);(!d||d.navigationEligible!==!0)&&m("NATIVE_ADMIN_PAGE_NOT_FOUND",`${l}/page`),n.has(p)&&m("NATIVE_ADMIN_PAGE_DUPLICATE",`${l}/page`),n.add(p);let f=r.page.resourceCode||r.page.routeCode||r.page.workflowCode||p,g=r.label||d.label;(!g||g===f||g===p)&&m("NATIVE_ADMIN_USER_LABEL_REQUIRED",`${l}/label`)})})}function sa(e,t){let o=w(e,t,Y.adminPages),n=new Set;o.forEach((i,s)=>{let a=`${t}/${s}`,r=T(i,a);R(r,["code","kind","path","label","navigationEligible","capability","access","resourceCode","viewCode","routeCode"],a,!0);let c=S(r.code,`${a}/code`,255);n.has(c)&&m("NATIVE_ADMIN_PAGE_DUPLICATE",`${a}/code`),n.add(c);let l=S(r.kind,`${a}/kind`,64);if(["resource-list","resource-detail","resource-create","resource-update","operation"].includes(l)||m("NATIVE_ADMIN_PAGE_KIND_INVALID",`${a}/kind`),me(r.path,`${a}/path`),S(r.label,`${a}/label`,255),Xe(r.navigationEligible,`${a}/navigationEligible`),r.capability!==void 0&&r.access!==void 0&&m("NATIVE_ROUTE_ACCESS_CONFLICT",`${a}/access`),r.capability!==void 0&&S(r.capability,`${a}/capability`,255),r.access!==void 0){let p=T(r.access,`${a}/access`);R(p,["allOf","anyOf"],`${a}/access`,!0);for(let d of["allOf","anyOf"])p[d]!==void 0&&v(p[d],`${a}/access/${d}`,50)}for(let p of["resourceCode","viewCode","routeCode"])r[p]!==void 0&&F(r[p],`${a}/${p}`)})}function ra(e,t){let o=w(e,t,Y.adminNavigationGroups),n=0;o.forEach((i,s)=>{let a=`${t}/${s}`,r=T(i,a);R(r,["code","label","icon","order","items"],a,!0),F(r.code,`${a}/code`),S(r.label,`${a}/label`,255),Gt(r.icon,`${a}/icon`),te(r.order,`${a}/order`,-1e4,1e4);let c=w(r.items,`${a}/items`,500);c.length===0&&m("NATIVE_ADMIN_GROUP_ORPHANED",`${a}/items`),n+=c.length,n>Y.adminNavigationItems&&m("NATIVE_ARRAY_LIMIT_EXCEEDED",t),c.forEach((l,p)=>{let d=`${a}/items/${p}`,f=T(l,d);R(f,["pageCode","label","icon","order"],d,!0),S(f.pageCode,`${d}/pageCode`,255),f.label!==void 0&&S(f.label,`${d}/label`,255),Gt(f.icon,`${d}/icon`),te(f.order,`${d}/order`,-1e4,1e4)})})}var aa=new Set(["application-todo-center","workflow-work-center","workflow-launch","workflow-task","workflow-instance","resource-records","resource-submit"]);function ca(e,t,o){let n=T(e,t);R(n,["schemaVersion","appCode","devicePolicy","rootEntry","authentication","routes","digest"],t),j(n.schemaVersion,Si,`${t}/schemaVersion`),j(n.appCode,o,`${t}/appCode`),zn(n.devicePolicy,`${t}/devicePolicy`),da(n.rootEntry,`${t}/rootEntry`),la(n.authentication,`${t}/authentication`),qn(n.digest,`${t}/digest`);let i=w(n.routes,`${t}/routes`,Y.routes),s=new Set;i.forEach((a,r)=>{let c=`${t}/routes/${r}`,l=T(a,c),p=l.kind==="resource-records"||l.kind==="resource-submit";R(l,["code","kind","desktop","mobile"],c,["workflowCode",...p?["resourceCode"]:[]]);let d=S(l.code,`${c}/code`,255);s.has(d)&&m("NATIVE_ROUTE_MANIFEST_DUPLICATE",`${c}/code`),s.add(d);let f=S(l.kind,`${c}/kind`,64);if(aa.has(f)||m("NATIVE_ROUTE_MANIFEST_KIND_INVALID",`${c}/kind`),l.workflowCode!==void 0&&F(l.workflowCode,`${c}/workflowCode`),p){let A=J(l.resourceCode,`${c}/resourceCode`);j(d,`user.${A}.${l.kind==="resource-records"?"records":"submit"}`,`${c}/code`)}else l.resourceCode!==void 0&&m("NATIVE_PROPERTY_UNKNOWN",`${c}/resourceCode`);let g=mi(l.desktop,`${c}/desktop`,o),E=mi(l.mobile,`${c}/mobile`,o);g.surface!=="user"&&m("NATIVE_ROUTE_MANIFEST_DESKTOP_SURFACE_INVALID",`${c}/desktop/surface`),E.surface!=="user"&&m("NATIVE_ROUTE_MANIFEST_MOBILE_SURFACE_INVALID",`${c}/mobile/surface`),g.routeCode===E.routeCode&&m("NATIVE_ROUTE_MANIFEST_PAIR_DUPLICATE",c)}),j(n.digest,X({schemaVersion:n.schemaVersion,appCode:n.appCode,devicePolicy:n.devicePolicy,rootEntry:n.rootEntry,authentication:n.authentication,routes:n.routes}),`${t}/digest`)}function zn(e,t){let o=T(e,t);R(o,["kind","mobileMaxWidthPx","desktopMinWidthPx"],t),j(o.kind,"viewport-family",`${t}/kind`);let n=te(o.mobileMaxWidthPx,`${t}/mobileMaxWidthPx`,320,1600),i=te(o.desktopMinWidthPx,`${t}/desktopMinWidthPx`,320,1600);return i!==n+1&&m("NATIVE_FRONTEND_DEVICE_POLICY_INVALID",t),{kind:"viewport-family",mobileMaxWidthPx:n,desktopMinWidthPx:i}}function da(e,t){let o=T(e,t);R(o,["code","desktop","mobile"],t);let n=F(o.code,`${t}/code`),i=Gn(o.desktop,`${t}/desktop`),s=Gn(o.mobile,`${t}/mobile`);return(i===s||s==="/"||!s.startsWith("/m/"))&&m("NATIVE_ROUTE_MANIFEST_ROOT_ENTRY_INVALID",t),i.startsWith("/m/")&&m("NATIVE_ROUTE_MANIFEST_ROOT_ENTRY_INVALID",`${t}/desktop`),{code:n,desktop:i,mobile:s}}function la(e,t){let o=T(e,t);R(o,["desktop","mobile"],t);let n=_i(o.desktop,`${t}/desktop`,!1),i=_i(o.mobile,`${t}/mobile`,!0);return(n.routeCode===i.routeCode||n.path===i.path)&&m("NATIVE_ROUTE_MANIFEST_AUTHENTICATION_DUPLICATE",t),{desktop:n,mobile:i}}function _i(e,t,o){let n=T(e,t);R(n,["routeCode","path"],t);let i=F(n.routeCode,`${t}/routeCode`),s=Gn(n.path,`${t}/path`);return(o?!s.startsWith("/m/"):s.startsWith("/m/"))&&m("NATIVE_ROUTE_MANIFEST_AUTHENTICATION_PATH_INVALID",`${t}/path`),{routeCode:i,path:s}}function Gn(e,t){let o=me(e,t);return/[:*?#\\\\]/.test(o)&&m("NATIVE_ROUTE_MANIFEST_STATIC_PATH_INVALID",t),o}function mi(e,t,o){let n=T(e,t);R(n,["routeCode","path","surface","pathParams","requiresAuthentication"],t,["capability","access"]),F(n.routeCode,`${t}/routeCode`);let i=me(n.path,`${t}/path`),s=S(n.surface,`${t}/surface`,16);["admin","user"].includes(s)||m("NATIVE_ROUTE_SURFACE_INVALID",`${t}/surface`);let a=v(n.pathParams,`${t}/pathParams`,8);return a.forEach((r,c)=>{(!/^[A-Za-z][A-Za-z0-9_]*$/.test(r)||r.length>64)&&m("NATIVE_ROUTE_PATH_PARAM_INVALID",`${t}/pathParams/${c}`)}),ee(a)!==ee(Pi(i))&&m("NATIVE_ROUTE_PATH_PARAMS_MISMATCH",`${t}/pathParams`),Yn(n,t,o),n.requiresAuthentication!==!0&&m("NATIVE_ROUTE_AUTHENTICATION_REQUIRED",`${t}/requiresAuthentication`),n}function Pi(e){return U([...e.matchAll(/:([A-Za-z][A-Za-z0-9_]*)/g)].map(t=>t[1]))}function gi(e,t,o,n){return{routeCode:e,path:t,surface:o,pathParams:Pi(t),...n?.capability?{capability:n.capability}:{},...n?.access?{access:n.access}:{},requiresAuthentication:!0}}function Ai(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 ua(e){let t=e.appCode,o=[],n=(g,E,A,b,I,_,u)=>{o.push({code:g,kind:E,...I?{workflowCode:I}:{},...u?{resourceCode:u}:{},desktop:gi(Ai(E,"desktop",I,u),A,"user",_),mobile:gi(Ai(E,"mobile",I,u),b,"user",_)})};e.frontend.user.applicationTodoCenter===!0&&n("application:todo-center","application-todo-center","/todos","/m/todos");let i=Li(e);i.length>0&&(n("workflow:work-center","workflow-work-center","/work-center","/m/work-center"),n("workflow:task","workflow-task","/tasks/:taskId","/m/tasks/:taskId"),n("workflow:instance","workflow-instance","/workflows/:instanceId","/m/workflows/:instanceId"));for(let g of i){if(!["standalone","hidden-handoff"].includes(g.launch.mode))continue;let E=U([g.launch.submission?.create?.requiredCapability,g.launch.submission?.existing?.requiredCapability].filter(A=>!!A));n(`workflow:${g.code}:launch`,"workflow-launch","/workflows/:workflowCode/start","/m/workflows/:workflowCode/start",g.code,E.length===1?{capability:E[0]}:E.length>1?{access:{anyOf:E}}:void 0)}let s=o.sort((g,E)=>ue(String(g.code),String(E.code))),a=zt(e),r=g=>{let E=g==="mobile"?"/m/":"/",A=a.filter(I=>I.surface==="user"&&!/[:*?#\\\\]/.test(I.path)&&I.path===E).sort((I,_)=>ue(I.code,_.code))[0];if(A)return{code:A.code,path:A.path};let b=a.filter(I=>I.surface==="user"&&!/[:*?#\\\\]/.test(I.path)&&(g==="mobile"?I.path.startsWith("/m/"):!I.path.startsWith("/m/"))).sort((I,_)=>ue(I.code,_.code))[0];return b?{code:b.code,path:b.path}:{code:g==="mobile"?"application-root-mobile":"application-root",path:E}},c=e.frontend.authentication?{desktop:{routeCode:e.frontend.authentication.surfaces.desktop.routeCode,path:e.frontend.authentication.surfaces.desktop.path},mobile:{routeCode:e.frontend.authentication.surfaces.mobile.routeCode,path:e.frontend.authentication.surfaces.mobile.path}}:{desktop:{routeCode:"application-login",path:"/login"},mobile:{routeCode:"application-login-mobile",path:"/m/login"}},l=zn(e.frontend.devicePolicy,"/config/frontend/devicePolicy"),p=r("desktop"),d=r("mobile"),f={schemaVersion:Si,appCode:t,devicePolicy:l,rootEntry:{code:p.code,desktop:p.path,mobile:d.path},authentication:c,routes:s};return{...f,digest:X(f)}}function Gt(e,t){if(e===void 0)return;let o=S(e,t,32);Or.has(o)||m("NATIVE_ADMIN_ICON_INVALID",t)}function Ei(e,t){e!==void 0&&te(e,t,-1e4,1e4)}function Yn(e,t,o){return e.capability!==void 0&&e.access!==void 0&&m("NATIVE_ROUTE_ACCESS_CONFLICT",`${t}/access`),e.capability!==void 0?{capability:Se(e.capability,`${t}/capability`,o)}:e.access===void 0?{}:{access:Yt(e.access,`${t}/access`,o)}}function Yt(e,t,o){let n=T(e,t);R(n,["allOf","anyOf"],t,!0);let i=n.allOf===void 0?void 0:U(v(n.allOf,`${t}/allOf`,50).map((a,r)=>Se(a,`${t}/allOf/${r}`,o))),s=n.anyOf===void 0?void 0:U(v(n.anyOf,`${t}/anyOf`,50).map((a,r)=>Se(a,`${t}/anyOf/${r}`,o)));return(i?.length||0)+(s?.length||0)===0&&m("NATIVE_ROUTE_ACCESS_EMPTY",t),{...i===void 0?{}:{allOf:i},...s===void 0?{}:{anyOf:s}}}function Li(e){let t=new Map(Di(e).map(i=>[String(i.code),i])),o=e.workflows.definitions.map((i,s)=>{let a=`/config/workflows/definitions/${s}`,r=T(i,a);R(r,["version","definition","launch"],a,["detailRouteCode"]);let c=T(r.definition,`${a}/definition`),l=r.detailRouteCode===void 0?void 0:ji(r.detailRouteCode,`${a}/detailRouteCode`);return{code:F(c.code,`${a}/definition/code`),title:S(c.title,`${a}/definition/title`,255),version:He(r.version,`${a}/version`),launch:fa(e,c,r.launch,`${a}/launch`,t),...l?{detailRouteCode:l}:{},definition:c}});return U(o.map(i=>i.code)).map(i=>{let s=o.filter(l=>l.code===i),a=e.workflows.activations.find(l=>l.workflowCode===i)?.definitionVersion,r=s.find(l=>l.version===a)||[...s].sort((l,p)=>p.version-l.version)[0],c=new Set;for(let l of s){let p=T(l.definition.nodes,"/config/workflows/definitions/nodes");for(let d of Object.values(p)){let f=T(d,"/config/workflows/definitions/nodes/*");if(f.kind==="approval")for(let g of v(f.allowedOperations||[],"/config/workflows/definitions/nodes/*/allowedOperations",20))c.add(g)}}return{code:i,title:r.title,acceptedCommandDeactivationPolicy:r.definition.acceptedCommandDeactivationPolicy,subject:r.definition.subject,launch:r.launch,...["standalone","hidden-handoff"].includes(r.launch.mode)&&!r.launch.submission?{processOperationCode:`openxiangda.workflow.${i}.submit`}:{},...r.detailRouteCode?{detailRouteCode:r.detailRouteCode}:{},definitionVersions:Ri(s.map(l=>l.version)),bindingVersions:Ri(e.workflows.bindings.map((l,p)=>{let d=`/config/workflows/bindings/${p}`,f=T(l,d),g=T(f.binding,`${d}/binding`);return{code:F(g.workflowCode,`${d}/binding/workflowCode`),version:He(f.version,`${d}/version`)}}).filter(l=>l.code===i).map(l=>l.version)),providerCodes:U(e.workflows.providers.map((l,p)=>F(T(l,`/config/workflows/providers/${p}`).code,`/config/workflows/providers/${p}/code`))),allowedOperations:[...c].sort(ue),editableParameterCodes:U(e.workflows.editableParameters.map((l,p)=>{let d=`/config/workflows/editableParameters/${p}`,f=T(l,d);return{code:F(f.code,`${d}/code`),workflowCode:F(f.workflowCode,`${d}/workflowCode`)}}).filter(l=>l.workflowCode===i).map(l=>l.code))}})}function xi(e,t){let o=T(e,t);R(o,["mode"],t,["submission"]);let n=S(o.mode,`${t}/mode`,32);return["standalone","custom-page","hidden-handoff","work-center-only"].includes(n)||m("NATIVE_WORKFLOW_LAUNCH_MODE_INVALID",`${t}/mode`),{mode:n,...o.submission===void 0?{}:{submission:T(o.submission,`${t}/submission`)}}}function fa(e,t,o,n,i){let s=xi(o,n);if(!s.submission)return{mode:s.mode};["standalone","hidden-handoff"].includes(s.mode)||m("NATIVE_WORKFLOW_NAMED_OPERATION_SUBMISSION_INVALID",`${n}/submission`);let a=T(s.submission,`${n}/submission`);R(a,["kind"],`${n}/submission`,["create","existing","context"]),j(a.kind,"named-operation",`${n}/submission/kind`);let r=n.endsWith("/launch")?n.slice(0,-7):n,c=T(t.subject,`${r}/definition/subject`),l=J(c.resourceCode,`${r}/definition/subject/resourceCode`),p=e.data.resources.findIndex(O=>O.code===l),d=e.data.resources[p];(p<0||!d)&&m("NATIVE_WORKFLOW_SUBJECT_RESOURCE_MISSING",`${r}/definition/subject/resourceCode`);let f=new Set(T(d.schema,`/config/data/resources/${p}/schema`).fields.map(O=>String(O.code))),g=new Map(e.backend.operations.map(O=>[String(O.code),O])),E=(O,h)=>{let C=`${n}/submission/${h}`,k=T(O,C);R(k,["operationCode","inputs","output"],C);let V=F(k.operationCode,`${C}/operationCode`),M=g.get(V),P=i.get(V),se=P?.platformAccess?.workflow?.codes;(!M||!P||P.method!=="POST"||!Array.isArray(se)||!se.includes(t.code))&&m("NATIVE_WORKFLOW_NAMED_OPERATION_INVALID",C);let ge=T(M.requestSchema,`${C}/operation/requestSchema`),H=T(ge.properties,`${C}/operation/requestSchema/properties`),Te=new Set(ge.required===void 0?[]:v(ge.required,`${C}/operation/requestSchema/required`,64)),ce=T(k.inputs,`${C}/inputs`),$=Object.entries(ce);(!$.length||$.length>64)&&m("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${C}/inputs`);let W=new Set,L=new Map,G={};for(let[z,Q]of $){(!ui.test(z)||!Object.prototype.hasOwnProperty.call(H,z))&&m("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${C}/inputs/${z}`);let Ue=`${C}/inputs/${z}`,Qt=T(Q,Ue),ve=S(Qt.source,`${Ue}/source`,32);if(["field","idempotency-key","current-user-reference","subject-id","subject-revision","requested-at"].includes(ve)||m("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",Ue),R(Qt,["source"],Ue,ve==="field"?["fieldCode"]:!1),L.set(ve,(L.get(ve)||0)+1),ve==="field"){let Et=K(Qt.fieldCode,`${Ue}/fieldCode`);(W.has(Et)||!f.has(Et))&&m("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${Ue}/fieldCode`),W.add(Et),G[z]={source:ve,fieldCode:Et}}else G[z]={source:ve}}([...Te].some(z=>!(z in ce))||(L.get("idempotency-key")||0)!==1||!$.some(([z,Q])=>T(Q,`${C}/inputs/${z}`).source==="idempotency-key"&&Te.has(z))||h==="create"&&((L.get("subject-id")||0)>0||(L.get("subject-revision")||0)>0)||h==="existing"&&((L.get("subject-id")||0)!==1||(L.get("subject-revision")||0)!==1))&&m("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${C}/inputs`);let q=T(k.output,`${C}/output`);R(q,["subjectId"],`${C}/output`,["subjectRevision","processCommand"]);let Oe=T(T(M.responseSchema,`${C}/operation/responseSchema`).properties,`${C}/operation/responseSchema/properties`);for(let z of["subjectId","subjectRevision","processCommand"]){if(q[z]===void 0)continue;let Q=S(q[z],`${C}/output/${z}`,128);(!ui.test(Q)||!Object.prototype.hasOwnProperty.call(Oe,Q))&&m("NATIVE_WORKFLOW_NAMED_OPERATION_OUTPUT_INVALID",`${C}/output/${z}`)}return{operationCode:V,method:"POST",path:P.path,requiredCapability:P.requiredCapability,requestSchemaDigest:P.requestSchemaDigest,responseSchemaDigest:P.responseSchemaDigest,inputs:G,output:{...q},fieldCodes:W}},A=a.create===void 0?void 0:E(a.create,"create"),b=a.existing===void 0?void 0:E(a.existing,"existing");!A&&!b&&m("NATIVE_WORKFLOW_NAMED_OPERATION_SUBMISSION_INVALID",`${n}/submission`);let I=new Set([...A?.fieldCodes||[],...b?.fieldCodes||[]]),_=a.context===void 0?[]:w(a.context,`${n}/submission/context`,16),u=new Set,N=_.map((O,h)=>{let C=`${n}/submission/context/${h}`,k=T(O,C);R(k,["queryParameter","fieldCode"],C);let V=S(k.queryParameter,`${C}/queryParameter`,64),M=K(k.fieldCode,`${C}/fieldCode`);return(!/^[A-Za-z][A-Za-z0-9]{0,63}$/.test(V)||u.has(V)||!I.has(M))&&m("NATIVE_WORKFLOW_LAUNCH_CONTEXT_INVALID",C),u.add(V),{queryParameter:V,fieldCode:M}}),y=O=>{let{fieldCodes:h,...C}=O;return C};return{mode:s.mode,submission:{kind:"named-operation",...A?{create:y(A)}:{},...b?{existing:y(b)}:{},context:N}}}function ji(e,t){let o=T(e,t);R(o,["desktop","mobile"],t);let n=F(o.desktop,`${t}/desktop`),i=F(o.mobile,`${t}/mobile`);return n===i&&m("NATIVE_WORKFLOW_DETAIL_ROUTE_DUPLICATE",t),{desktop:n,mobile:i}}function pa(e,t){let o=new Set(t.map(p=>p.code)),n=new Map;e.data.resources.forEach((p,d)=>{let f=`/config/data/resources/${d}`,g=T(p,f);for(let[b,I]of Object.entries(g.fieldPolicies||{})){if(!Ze(b))continue;let _=`${f}/fieldPolicies/${b}/read`,u=T(I,`${f}/fieldPolicies/${b}`);for(let N of v(u.read||[],_,2e3))o.has(N)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",_)}let E=g.surface===void 0?{}:T(g.surface,`${f}/surface`);if(["native","queued-command"].includes(E.mutationOwner||"native"))return;let A=T(g.capabilities,`${f}/capabilities`);for(let b of["create","update","delete"])n.set(String(A[b]),b)});let i=new Set;for(let[p,d]of e.authz.roles.entries()){let f=`/config/authz/roles/${p}`,g=T(d,f);R(g,["code","name","description","capabilities"],f,!0);let E=F(g.code,`${f}/code`);i.has(E)&&m("NATIVE_ROLE_DUPLICATE",`${f}/code`),i.add(E),S(g.name,`${f}/name`,255);let A=v(g.capabilities,`${f}/capabilities`,2e3);for(let[b,I]of A.entries())n.has(I)&&m("NATIVE_DATA_SURFACE_MUTATION_GRANT_FORBIDDEN",`${f}/capabilities/${b}`,{operation:n.get(I)}),o.has(I)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",`${f}/capabilities`)}let s=e.authz.authenticatedUserRoleCode===void 0?"":F(e.authz.authenticatedUserRoleCode,"/config/authz/authenticatedUserRoleCode");s&&!i.has(s)&&m("NATIVE_AUTHENTICATED_USER_ROLE_REFERENCE_MISSING","/config/authz/authenticatedUserRoleCode");let a=new Set,r=0;for(let[p,d]of e.perspectives.entries()){let f=`/config/perspectives/${p}`,g=T(d,f);R(g,["code","name","description","roleCodes","capabilityCodes","default"],f,!0);let E=F(g.code,`${f}/code`);a.has(E)&&m("NATIVE_PERSPECTIVE_DUPLICATE",`${f}/code`),a.add(E),S(g.name,`${f}/name`,255);let A=v(g.roleCodes,`${f}/roleCodes`,20);A.length<1&&m("NATIVE_PERSPECTIVE_ROLE_REQUIRED",`${f}/roleCodes`),A.forEach((_,u)=>{i.has(_)||m("NATIVE_PERSPECTIVE_ROLE_MISSING",`${f}/roleCodes/${u}`)});let b=U(e.authz.roles.filter(_=>A.includes(_.code)).flatMap(_=>_.capabilities)),I=v(g.capabilityCodes,`${f}/capabilityCodes`,2e3);ee(b)!==ee(I)&&m("NATIVE_PERSPECTIVE_CAPABILITY_PROJECTION_MISMATCH",`${f}/capabilityCodes`),g.default===!0?r+=1:g.default!==void 0&&m("NATIVE_PERSPECTIVE_DEFAULT_INVALID",`${f}/default`)}r>1&&m("NATIVE_PERSPECTIVE_DEFAULT_DUPLICATE","/config/perspectives");for(let[p,d]of e.backend.operations.entries()){let f=T(d,`/config/backend/operations/${p}`);o.has(f.capability)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",`/config/backend/operations/${p}/capability`)}let c=new Set,l=new Set;for(let[p,d]of e.frontend.routes.entries()){let f=`/config/frontend/routes/${p}`,g=T(d,f),E=F(g.code,`${f}/code`);c.has(E)&&m("NATIVE_ROUTE_DUPLICATE",`${f}/code`),c.add(E);let A=me(g.path,`${f}/path`);l.has(A)&&m("NATIVE_ROUTE_PATH_DUPLICATE",`${f}/path`),l.add(A);let b=Yn(g,f,e.appCode);b.capability&&!o.has(b.capability)&&m("NATIVE_CAPABILITY_REFERENCE_MISSING",`${f}/capability`);let I=g.access===void 0?void 0:T(g.access,`${f}/access`);for(let _ of["allOf","anyOf"]){let u=I?.[_]===void 0?[]:w(I[_],`${f}/access/${_}`,50);for(let[N,y]of u.entries()){let O=Se(y,`${f}/access/${_}/${N}`,e.appCode);o.has(O)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",`${f}/access/${_}/${N}`)}}}if(e.frontend.admin.access!==void 0){let p=Yt(e.frontend.admin.access,"/config/frontend/admin/access",e.appCode);for(let d of["allOf","anyOf"])for(let[f,g]of(p[d]||[]).entries())o.has(g)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",`/config/frontend/admin/access/${d}/${f}`)}for(let[p,d]of e.frontend.routes.entries()){let f=T(d,`/config/frontend/routes/${p}`);f.parentCode&&!c.has(f.parentCode)&&m("NATIVE_ROUTE_PARENT_MISSING",`/config/frontend/routes/${p}/parentCode`)}}function _a(e){let t=new Set(e.authz.roles.map(l=>String(l.code))),o=e.authz.authenticatedUserRoleCode===void 0?"":F(e.authz.authenticatedUserRoleCode,"/config/authz/authenticatedUserRoleCode"),n=new Map(e.authz.scopeDimensions.map(l=>[String(l.code),{valueType:l.valueType==="uuid"?"uuid":"string",...l.valueSource?.resourceCode?{valueSourceResourceCode:String(l.valueSource.resourceCode)}:{}}])),i=new Set(n.keys()),s=new Map(e.data.resources.map((l,p)=>{let d=We(l,`/config/data/resources/${p}`,e.appCode);return[d.code,new Map(d.schema.fields.map(f=>[String(f.code),f]))]}));for(let[l,p]of e.authz.scopeDimensions.entries()){let d=`/config/authz/scopeDimensions/${l}`,f=T(p,d);if(R(f,["code","name","resourceCode","valueType","hierarchyMode","valueSource"],d,!0),f.valueSource===void 0)continue;let g=T(f.valueSource,`${d}/valueSource`);R(g,["kind","resourceCode","labelField","enabledField"],`${d}/valueSource`,!0),g.kind!=="native_resource"&&m("NATIVE_SCOPE_VALUE_SOURCE_KIND_INVALID",`${d}/valueSource/kind`),f.valueType!=="uuid"&&m("NATIVE_SCOPE_VALUE_SOURCE_TYPE_INVALID",`${d}/valueType`);let E=J(g.resourceCode,`${d}/valueSource/resourceCode`),A=s.get(E);A||m("NATIVE_SCOPE_VALUE_SOURCE_RESOURCE_MISSING",`${d}/valueSource/resourceCode`);let b=K(g.labelField,`${d}/valueSource/labelField`);if(["text.short","text.long"].includes(String(A.get(b)?.type||""))||m("NATIVE_SCOPE_VALUE_SOURCE_LABEL_FIELD_INVALID",`${d}/valueSource/labelField`),g.enabledField!==void 0){let I=K(g.enabledField,`${d}/valueSource/enabledField`);A.get(I)?.type!=="boolean"&&m("NATIVE_SCOPE_VALUE_SOURCE_ENABLED_FIELD_INVALID",`${d}/valueSource/enabledField`)}}let a=new Set,r=new Set;for(let[l,p]of e.authz.scopeSources.entries()){let d=`/config/authz/scopeSources/${l}`,f=T(p,d);R(f,["code","name","resourceCode","subject","grants","operationField","enabledField","effectiveFromField","effectiveToField","failureMode"],d,!0);let g=F(f.code,`${d}/code`);a.has(g)&&m("NATIVE_SCOPE_SOURCE_DUPLICATE",`${d}/code`),a.add(g),S(f.name,`${d}/name`,255);let E=J(f.resourceCode,`${d}/resourceCode`),A=s.get(E);A||m("NATIVE_SCOPE_SOURCE_RESOURCE_MISSING",`${d}/resourceCode`);let b=T(f.subject,`${d}/subject`),I=S(b.type,`${d}/subject/type`,32);R(b,I==="role_membership"?["type","userIdField","roleCode"]:["type","userIdField"],`${d}/subject`),["user","role_membership"].includes(I)||m("NATIVE_SCOPE_SOURCE_SUBJECT_INVALID",`${d}/subject/type`);let _=ot(b.userIdField,A);Nn(_)||m("NATIVE_SCOPE_SOURCE_SUBJECT_PATH_INVALID",`${d}/subject/userIdField`),I==="role_membership"&&!t.has(String(b.roleCode))&&m("NATIVE_ROLE_REFERENCE_MISSING",`${d}/subject/roleCode`);let u=new Set;for(let[N,y]of w(f.grants,`${d}/grants`,100).entries()){let O=`${d}/grants/${N}`,h=T(y,O);R(h,["dimensionCode","valueField","parentValueField"],O,!0);let C=F(h.dimensionCode,`${O}/dimensionCode`);(!i.has(C)||u.has(C))&&m("NATIVE_SCOPE_SOURCE_DIMENSION_INVALID",`${O}/dimensionCode`),u.add(C),f.failureMode==="last_known_good"&&r.add(C);for(let k of["valueField","parentValueField"]){if(h[k]===void 0)continue;let V=ot(h[k],A);$o(V,n.get(C),s)||m("NATIVE_SCOPE_SOURCE_GRANT_PATH_INVALID",`${O}/${k}`)}}u.size===0&&m("NATIVE_SCOPE_SOURCE_GRANT_REQUIRED",`${d}/grants`),["strict","last_known_good"].includes(f.failureMode)||m("NATIVE_SCOPE_SOURCE_FAILURE_MODE_INVALID",`${d}/failureMode`);for(let N of["operationField","enabledField","effectiveFromField","effectiveToField"]){if(f[N]===void 0)continue;let y=K(f[N],`${d}/${N}`);A.has(y)||m("NATIVE_SCOPE_SOURCE_FIELD_MISSING",`${d}/${N}`)}}ga(e,t,s,o);let c=new Set;for(let[l,p]of e.authz.dataPolicies.entries()){let d=`/config/authz/dataPolicies/${l}`,f=T(p,d);R(f,["code","name","resourceCode","unrestrictedRoleCodes","operations","matchMode","rules","readExpression","writeBoundary"],d,!0);let g=F(f.code,`${d}/code`);c.has(g)&&m("NATIVE_DATA_POLICY_DUPLICATE",`${d}/code`),c.add(g);let E=f.readExpression!==void 0,A=v(f.operations||[],`${d}/operations`,4);f.operations!==void 0&&(A.length===0||A.some(y=>!["read","create","update","delete"].includes(y)))&&m("NATIVE_DATA_POLICY_OPERATIONS_INVALID",`${d}/operations`),["AND","OR"].includes(f.matchMode)||m("NATIVE_DATA_POLICY_MATCH_MODE_INVALID",`${d}/matchMode`),E&&f.operations!==void 0&&m("NATIVE_DATA_POLICY_READ_EXPRESSION_OPERATIONS_FORBIDDEN",`${d}/operations`);let b=e.data.resources.find(y=>y.dataPolicyCode===g),I=f.resourceCode||b?.code,_=I?s.get(J(I,`${d}/resourceCode`)):void 0;E&&!_&&m("NATIVE_DATA_POLICY_RESOURCE_MISSING",`${d}/resourceCode`);let u=v(f.unrestrictedRoleCodes||[],`${d}/unrestrictedRoleCodes`,100);f.unrestrictedRoleCodes!==void 0&&u.length===0&&m("NATIVE_DATA_POLICY_UNRESTRICTED_ROLES_INVALID",`${d}/unrestrictedRoleCodes`);for(let y of u)t.has(y)||m("NATIVE_ROLE_REFERENCE_MISSING",`${d}/unrestrictedRoleCodes`);let N;try{let y=w(f.rules,`${d}/rules`,100).map((O,h)=>({rule:T(O,`${d}/rules/${h}`),pointer:`${d}/rules/${h}`}));y.length===0?(!E||f.matchMode!=="AND"||f.writeBoundary!=="capability_only")&&m("NATIVE_DATA_POLICY_WRITE_BOUNDARY_REQUIRED",d):f.writeBoundary!==void 0&&m("NATIVE_DATA_POLICY_WRITE_BOUNDARY_INVALID",`${d}/writeBoundary`),N=[...y],E&&(N.push(...Bt(f.readExpression,`${d}/readExpression`)),ci(f.readExpression,`${d}/readExpression`))}catch(y){throw y instanceof _t&&m(y.code,y.pointer),y}for(let{rule:y,pointer:O}of N){R(y,["subject","dimensionCode","relationCode","resourceCode","field","roleCodes","operation","valuePath","emptyMatchesAll","operator","value","operand"],O,!0);let h=K(y.field,`${O}/field`),C=_?.get(h);E&&!C&&m("NATIVE_DATA_POLICY_FIELD_MISSING",`${O}/field`);for(let H of v(y.roleCodes||[],`${O}/roleCodes`,100))t.has(H)||m("NATIVE_ROLE_REFERENCE_MISSING",`${O}/roleCodes`);let k=String(y.operator||""),V=y.operand==="db_now",M=["is_null","is_not_null"].includes(k),P=["eq","not_eq","in","not_in"].includes(k),se=!V&&(y.operator!==void 0||y.value!==void 0);if([y.subject==="current_user"?"current_user":"",typeof y.dimensionCode=="string"?"dimension":"",typeof y.relationCode=="string"?"relationship":"",se?"constant":"",V?"db_now":""].filter(Boolean).length!==1&&m("NATIVE_DATA_POLICY_RULE_SOURCE_INVALID",O),y.subject!==void 0&&y.subject!=="current_user"&&m("NATIVE_DATA_POLICY_SUBJECT_INVALID",`${O}/subject`),se){if(!P&&!M&&m("NATIVE_DATA_POLICY_OPERATOR_INVALID",`${O}/operator`),["in","not_in"].includes(k)){let H=w(y.value,`${O}/value`,100).map((Te,ce)=>S(Te,`${O}/value/${ce}`,2048));(H.length===0||new Set(H).size!==H.length)&&m("NATIVE_DATA_POLICY_VALUE_INVALID",`${O}/value`)}else["eq","not_eq"].includes(k)?S(y.value,`${O}/value`,2048):(y.value!==void 0||y.operand!==void 0)&&m("NATIVE_DATA_POLICY_VALUE_INVALID",`${O}/value`);for(let H of["operation","valuePath","emptyMatchesAll","resourceCode","operand"])y[H]!==void 0&&m("NATIVE_DATA_POLICY_CONSTANT_RULE_INVALID",`${O}/${H}`)}if(V){(!["lt","lte","gt","gte"].includes(k)||y.value!==void 0||C?.type!=="datetime")&&m("NATIVE_DATA_POLICY_DB_NOW_INVALID",O);for(let H of["operation","valuePath","emptyMatchesAll","resourceCode","value"])y[H]!==void 0&&m("NATIVE_DATA_POLICY_DB_NOW_INVALID",`${O}/${H}`)}y.dimensionCode&&!i.has(y.dimensionCode)&&m("NATIVE_SCOPE_DIMENSION_MISSING",`${O}/dimensionCode`),r.has(String(y.dimensionCode||""))&&y.operation!=="read"&&m("NATIVE_SCOPE_SOURCE_LAST_KNOWN_GOOD_UNSAFE",`${O}/operation`)}}for(let[l,p]of e.data.resources.entries()){let d=T(p,`/config/data/resources/${l}`);d.dataPolicyCode&&!c.has(d.dataPolicyCode)&&m("NATIVE_DATA_POLICY_REFERENCE_MISSING",`/config/data/resources/${l}/dataPolicyCode`)}}function ma(e){try{ao(e.data.resources,"/config/data/resources")}catch(t){throw t instanceof Ee&&m(t.code,t.pointer),t}}function ga(e,t,o,n){let i=new Set;for(let[s,a]of e.authz.roleMembershipSources.entries()){let r=`/config/authz/roleMembershipSources/${s}`,c=T(a,r);R(c,["code","name","resourceCode","userIdField","roleCode","enabledField","effectiveFromField","effectiveToField","failureMode"],r,!0);let l=F(c.code,`${r}/code`);l.length>100&&m("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_CODE_INVALID",`${r}/code`),i.has(l)&&m("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_DUPLICATE",`${r}/code`),i.add(l),S(c.name,`${r}/name`,255);let p=Ii(c.resourceCode,`${r}/resourceCode`,o);bi(c.userIdField,`${r}/userIdField`,p),t.has(String(c.roleCode||""))||m("NATIVE_ROLE_REFERENCE_MISSING",`${r}/roleCode`),n&&c.roleCode===n&&m("NATIVE_AUTHENTICATED_USER_ROLE_SOURCE_CONFLICT",`${r}/roleCode`),yi(c,r,p)}for(let[s,a]of e.authz.relationshipGrantSources.entries()){let r=`/config/authz/relationshipGrantSources/${s}`,c=T(a,r);R(c,["code","name","resourceCode","subject","relationCode","targetResourceCode","resourceIdField","operations","enabledField","effectiveFromField","effectiveToField","failureMode"],r,!0);let l=F(c.code,`${r}/code`);l.length>100&&m("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_CODE_INVALID",`${r}/code`),i.has(l)&&m("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_DUPLICATE",`${r}/code`),i.add(l),S(c.name,`${r}/name`,255);let p=Ii(c.resourceCode,`${r}/resourceCode`,o),d=T(c.subject,`${r}/subject`),f=S(d.type,`${r}/subject/type`,32);R(d,f==="role_membership"?["type","userIdField","roleCode"]:["type","userIdField"],`${r}/subject`),["user","role_membership"].includes(f)||m("NATIVE_AUTHORIZATION_PROJECTION_SUBJECT_INVALID",`${r}/subject/type`),bi(d.userIdField,`${r}/subject/userIdField`,p),f==="role_membership"&&!t.has(String(d.roleCode||""))&&m("NATIVE_ROLE_REFERENCE_MISSING",`${r}/subject/roleCode`),F(c.relationCode,`${r}/relationCode`);let g=J(c.targetResourceCode,`${r}/targetResourceCode`);o.has(g)||m("NATIVE_AUTHORIZATION_PROJECTION_TARGET_RESOURCE_MISSING",`${r}/targetResourceCode`);let E=ot(c.resourceIdField,p),A=E?.field.type==="resource-ref.single"&&E.valuePath==="value"&&E.field.source?.resourceCode===g;(c.resourceIdField==="id"?g!==String(c.resourceCode):!A)&&m("NATIVE_AUTHORIZATION_PROJECTION_RESOURCE_ID_FIELD_INVALID",`${r}/resourceIdField`);let b=v(c.operations,`${r}/operations`,20);(b.length===0||b.some(I=>I.length>64||!/^[A-Za-z0-9][A-Za-z0-9:._*-]{0,63}$/.test(I)))&&m("NATIVE_AUTHORIZATION_PROJECTION_OPERATIONS_INVALID",`${r}/operations`),yi(c,r,p)}}function Ii(e,t,o){let n=J(e,t),i=o.get(n);return i||m("NATIVE_AUTHORIZATION_PROJECTION_RESOURCE_MISSING",t),i}function bi(e,t,o){let n=ot(e,o);Nn(n)||m("NATIVE_AUTHORIZATION_PROJECTION_USER_FIELD_INVALID",t)}function yi(e,t,o){if(e.failureMode!=="strict"&&m("NATIVE_AUTHORIZATION_PROJECTION_FAILURE_MODE_INVALID",`${t}/failureMode`),e.enabledField!==void 0){let n=K(e.enabledField,`${t}/enabledField`);o.get(n)?.type!=="boolean"&&m("NATIVE_AUTHORIZATION_PROJECTION_ENABLED_FIELD_INVALID",`${t}/enabledField`)}for(let n of["effectiveFromField","effectiveToField"]){if(e[n]===void 0)continue;let i=K(e[n],`${t}/${n}`);["date","datetime"].includes(String(o.get(i)?.type))||m("NATIVE_AUTHORIZATION_PROJECTION_EFFECTIVE_FIELD_INVALID",`${t}/${n}`)}}function Aa(e){let t=new Set,o=new Set;e.forEach((n,i)=>{let s=`/config/backend/secrets/${i}`,a=T(n,s);R(a,["name","env","description","required","exposure"],s,!0);let r=S(a.name,`${s}/name`,128),c=S(a.env,`${s}/env`,128);gr.test(r)||m("NATIVE_SECRET_NAME_INVALID",`${s}/name`),(!Ar.test(c)||c.startsWith("OPENXIANGDA_")||["NODE_ENV","PORT"].includes(c))&&m("NATIVE_SECRET_ENV_INVALID",`${s}/env`),t.has(r)&&m("NATIVE_SECRET_NAME_DUPLICATE",`${s}/name`),o.has(c)&&m("NATIVE_SECRET_ENV_DUPLICATE",`${s}/env`),t.add(r),o.add(c),j(a.exposure,"active_only",`${s}/exposure`),a.required!==void 0&&Xe(a.required,`${s}/required`),a.description!==void 0&&Hn(a.description,`${s}/description`,2e3)})}function Ea(e){let t=new Set,o=new Map,n=new Map(e.data.resources.map(g=>[String(g.code),g])),i=new Map(e.frontend.routes.map((g,E)=>{let A=T(g,`/config/frontend/routes/${E}`);return[F(A.code,`/config/frontend/routes/${E}/code`),A]}));for(let[g,E]of e.workflows.definitions.entries()){let A=`/config/workflows/definitions/${g}`,b=T(E,A);if(R(b,["version","definition","launch"],A,["detailRouteCode"]),xi(b.launch,`${A}/launch`),b.detailRouteCode!==void 0){let y=ji(b.detailRouteCode,`${A}/detailRouteCode`);for(let[O,h,C]of[["desktop",y.desktop,["admin","user"]],["mobile",y.mobile,["user"]]]){let k=`${A}/detailRouteCode/${O}`,V=i.get(h);V||m("NATIVE_WORKFLOW_DETAIL_ROUTE_MISSING",k),C.some(se=>se===V.surface)||m("NATIVE_WORKFLOW_DETAIL_ROUTE_SURFACE_INVALID",k);let M=me(V.path,k),P=[...M.matchAll(/:([A-Za-z][A-Za-z0-9_]*)/g)].map(se=>se[1]);(M.includes("*")||P.length!==1||P[0]!=="instanceId")&&m("NATIVE_WORKFLOW_DETAIL_ROUTE_PATH_INVALID",k)}}let I=T(b.definition,`${A}/definition`),_=`${I.code}:${He(b.version,`${A}/version`)}`;t.has(_)&&m("NATIVE_WORKFLOW_DEFINITION_DUPLICATE",A),t.add(_),ba(I,`${A}/definition`),Ia(I.subject,n,`${A}/definition/subject`);let u=Mt(I,new Map((n.get(I.subject.resourceCode)?.schema.fields||[]).map(y=>[y.code,{...n.get(I.subject.resourceCode)?.surface?.fields?.[y.code],...y,system:["id","revision","createdAt","updatedAt","createdBy","updatedBy"].includes(y.code)}])),new Map([...n].map(([y,O])=>[y,new Map(O.schema.fields.map(h=>[h.code,{...O.surface?.fields?.[h.code],...h,system:["id","revision","createdAt","updatedAt","createdBy","updatedBy"].includes(h.code)}]))])));u.length&&m(u[0],`${A}/definition/taskPages`);let N=Wo(I,{appCode:e.appCode,capabilities:e.authz.capabilities.map(y=>y.code),fields:new Map((n.get(I.subject.resourceCode)?.schema.fields||[]).map(y=>[y.code,y]))});N.length&&m("NATIVE_WORKFLOW_INSTANCE_COMMAND_POLICY_INVALID",`${A}/definition/instanceCommands`,{errors:N}),I.title===I.code&&m("NATIVE_WORKFLOW_USER_TITLE_REQUIRED",`${A}/definition/title`),o.set(_,I)}let s=new Set,a=new Map;for(let[g,E]of e.workflows.bindings.entries()){let A=T(E,`/config/workflows/bindings/${g}`),b=T(A.binding,`/config/workflows/bindings/${g}/binding`),I=`${b.workflowCode}:${He(A.version,`/config/workflows/bindings/${g}/version`)}`;s.has(I)&&m("NATIVE_WORKFLOW_BINDING_DUPLICATE",`/config/workflows/bindings/${g}`),s.add(I),ya(b,`/config/workflows/bindings/${g}/binding`),a.set(I,b)}let r=new Set,c=new Map;for(let[g,E]of e.workflows.activations.entries()){let A=`/config/workflows/activations/${g}`,b=T(E,A);R(b,["workflowCode","definitionVersion","bindingVersion","acceptedCommandDeactivationPolicy"],A,["environmentKey"]);let I=F(b.workflowCode,`${A}/workflowCode`);r.has(I)&&m("NATIVE_WORKFLOW_ACTIVATION_DUPLICATE",A),r.add(I);let _=`${I}:${He(b.definitionVersion,`${A}/definitionVersion`)}`,u=`${I}:${He(b.bindingVersion,`${A}/bindingVersion`)}`;t.has(_)||m("NATIVE_WORKFLOW_DEFINITION_REFERENCE_MISSING",`${A}/definitionVersion`),s.has(u)||m("NATIVE_WORKFLOW_BINDING_REFERENCE_MISSING",`${A}/bindingVersion`);let N=o.get(_),y=a.get(u),O=Fn(N,y);O.length&&m(O[0],A),(!["finish-pinned","cancel-on-deactivate"].includes(b.acceptedCommandDeactivationPolicy)||b.acceptedCommandDeactivationPolicy!==N.acceptedCommandDeactivationPolicy)&&m("NATIVE_WORKFLOW_COMMAND_DEACTIVATION_POLICY_MISMATCH",`${A}/acceptedCommandDeactivationPolicy`),Na(N,y,`/config/workflows/activations/${g}`),c.set(I,y)}let l=si([...c.values()]);l.length&&m(l[0],"/config/workflows/activations");let p=new Set;e.workflows.providers.forEach((g,E)=>{let A=`/config/workflows/providers/${E}`,b=T(g,A);R(b,["code","endpointPath","timeoutMs"],A,!0);let I=F(b.code,`${A}/code`);p.has(I)&&m("NATIVE_WORKFLOW_PROVIDER_DUPLICATE",`${A}/code`),p.add(I),me(b.endpointPath,`${A}/endpointPath`),b.timeoutMs!==void 0&&te(b.timeoutMs,`${A}/timeoutMs`,100,1e4)});for(let[g,E]of c.entries())for(let[A,b]of Object.entries(T(E.bindings,"/config/workflows/bindings/*/binding/bindings"))){let I=T(b,`/config/workflows/${g}/bindings/${A}`);I.provider==="application_provider"&&!p.has(I.providerCode)&&m("NATIVE_WORKFLOW_PROVIDER_REFERENCE_MISSING",`/config/workflows/${g}/bindings/${A}/providerCode`)}let d=new Set(e.authz.roles.map(g=>g.code)),f=new Set;e.workflows.editableParameters.forEach((g,E)=>{let A=`/config/workflows/editableParameters/${E}`,b=T(g,A);R(b,["code","workflowCode","bindingKey","label","valueType","required","allowedRoleCodes","allowedProviderCodes","maxItems"],A,!0);let I=F(b.code,`${A}/code`);f.has(I)&&m("NATIVE_WORKFLOW_EDITABLE_PARAMETER_DUPLICATE",`${A}/code`),f.add(I);let _=Ht(b.workflowCode,`${A}/workflowCode`),u=qt(b.bindingKey,`${A}/bindingKey`),N=c.get(_);(!N||!T(N.bindings,`${A}/bindingKey`)[u])&&m("NATIVE_WORKFLOW_EDITABLE_BINDING_MISSING",`${A}/bindingKey`),S(b.label,`${A}/label`,255),["role_code","user_ids","provider_code"].includes(b.valueType)||m("NATIVE_WORKFLOW_EDITABLE_VALUE_TYPE_INVALID",`${A}/valueType`);for(let y of v(b.allowedRoleCodes||[],`${A}/allowedRoleCodes`,100))d.has(y)||m("NATIVE_ROLE_REFERENCE_MISSING",`${A}/allowedRoleCodes`);for(let y of v(b.allowedProviderCodes||[],`${A}/allowedProviderCodes`,100))p.has(y)||m("NATIVE_WORKFLOW_PROVIDER_REFERENCE_MISSING",`${A}/allowedProviderCodes`);b.required!==void 0&&Xe(b.required,`${A}/required`),b.maxItems!==void 0&&te(b.maxItems,`${A}/maxItems`,1,200)})}function Ia(e,t,o){let n=T(e,o);R(n,["resourceCode","factProjection"],o,["summaryFields"]);let i=J(n.resourceCode,`${o}/resourceCode`),s=t.get(i);s||m("NATIVE_WORKFLOW_SUBJECT_RESOURCE_MISSING",`${o}/resourceCode`);let a=new Set(w(T(s.schema,`${o}/resourceCode`).fields,`${o}/resourceCode`,500).map((l,p)=>K(T(l,`${o}/resourceCode/${p}`).code,`${o}/resourceCode/${p}`))),r=T(n.factProjection,`${o}/factProjection`),c=Object.entries(r);(c.length<1||c.length>64)&&m("NATIVE_WORKFLOW_SUBJECT_FACT_PROJECTION_INVALID",`${o}/factProjection`);for(let[l,p]of c){br.test(l)||m("NATIVE_WORKFLOW_SUBJECT_FACT_KEY_INVALID",`${o}/factProjection/${l}`);let d=K(p,`${o}/factProjection/${l}`);a.has(d)||m("NATIVE_WORKFLOW_SUBJECT_FIELD_MISSING",`${o}/factProjection/${l}`)}if(n.summaryFields!==void 0){let l=v(n.summaryFields,`${o}/summaryFields`,yr).map((E,A)=>K(E,`${o}/summaryFields/${A}`)),p=t.get(i),d=p.surface&&typeof p.surface=="object"&&!Array.isArray(p.surface)?p.surface:{},f=d.fields&&typeof d.fields=="object"&&!Array.isArray(d.fields)?d.fields:{},g=new Map(w(T(p.schema,`${o}/resourceCode`).fields,`${o}/resourceCode`,500).map((E,A)=>{let b=T(E,`${o}/resourceCode/${A}`);return[String(b.code),b]}));for(let[E,A]of l.entries()){let b=g.get(A),I=f[A],_=String(b?.type||""),u=b?.maxLength;(!b||b.system===!0||I&&typeof I=="object"&&!Array.isArray(I)&&I.system===!0||["id","revision","created_by","updated_by","created_at","updated_at"].includes(A)||!Tr.has(_)||_==="text.long"&&typeof u=="number"&&Number.isFinite(u)&&u>Nr)&&m("NATIVE_WORKFLOW_SUBJECT_SUMMARY_FIELDS_INVALID",`${o}/summaryFields/${E}`)}}}function ba(e,t){R(e,["schemaVersion","code","title","subject","acceptedCommandDeactivationPolicy","startAt","inputSchema","nodes"],t,["organizationContext","instanceCommands","readability","taskPages"]),j(e.schemaVersion,"openxiangda.workflow-definition/v2",`${t}/schemaVersion`),Ht(e.code,`${t}/code`),S(e.title,`${t}/title`,255),["finish-pinned","cancel-on-deactivate"].includes(e.acceptedCommandDeactivationPolicy)||m("NATIVE_WORKFLOW_COMMAND_DEACTIVATION_POLICY_REQUIRED",`${t}/acceptedCommandDeactivationPolicy`);let o=T(e.nodes,`${t}/nodes`),n=Object.keys(o);(n.length===0||n.length>200)&&m("NATIVE_WORKFLOW_NODE_COUNT_INVALID",`${t}/nodes`);let i=S(e.startAt,`${t}/startAt`,128),s=Yo(e);s.length&&m(s[0],`${t}/readability`);let a=Fn(e);a.length&&m(a[0],`${t}/nodes`);let r=vn(e);r.length&&m(r[0],`${t}/nodes`);let c=Mt(e);c.length&&m(c[0],`${t}/taskPages`);let l=Pt(e);l.length&&m(l[0],`${t}/nodes`),o[i]||m("NATIVE_WORKFLOW_START_NODE_MISSING",`${t}/startAt`);let p=new Map;for(let[E,A]of Object.entries(o)){let b=`${t}/nodes/${E}`,I=T(A,b);j(I.id,E,`${b}/id`),["approval","condition","end","cc","action"].includes(I.kind)||m("NATIVE_WORKFLOW_NODE_KIND_INVALID",`${b}/kind`);let _=[];if(I.kind==="approval"){S(I.title,`${b}/title`,255),qt(I.binding,`${b}/binding`),["single","any","all","sequence"].includes(I.mode)||m("NATIVE_WORKFLOW_APPROVAL_MODE_INVALID",`${b}/mode`),_.push(S(I.onApprove,`${b}/onApprove`,128),S(I.onReject,`${b}/onReject`,128));for(let u of v(I.returnTargets||[],`${b}/returnTargets`,200))o[u]||m("NATIVE_WORKFLOW_TARGET_MISSING",`${b}/returnTargets`);for(let u of v(I.allowedOperations||[],`${b}/allowedOperations`,20))hr.has(u)||m("NATIVE_WORKFLOW_OPERATION_INVALID",`${b}/allowedOperations`)}else if(I.kind==="action")_.push(S(I.next,`${b}/next`,128));else if(I.kind==="cc")S(I.title,`${b}/title`,255),qt(I.binding,`${b}/binding`),_.push(S(I.next,`${b}/next`,128));else if(I.kind==="condition"){let u=w(I.branches,`${b}/branches`,100);u.length===0&&m("NATIVE_WORKFLOW_BRANCH_REQUIRED",`${b}/branches`),u.forEach((N,y)=>{let O=T(N,`${b}/branches/${y}`);mt(O.when,`${b}/branches/${y}/when`,0),_.push(S(O.target,`${b}/branches/${y}/target`,128))}),_.push(S(I.otherwise,`${b}/otherwise`,128))}else S(I.title,`${b}/title`,255),S(I.outcome,`${b}/outcome`,128);for(let u of _)o[u]||m("NATIVE_WORKFLOW_TARGET_MISSING",b);p.set(E,_)}let d=new Set,f=new Set,g=E=>{if(f.has(E)&&m("NATIVE_WORKFLOW_CYCLE_FORBIDDEN",`${t}/nodes/${E}`),!d.has(E)){d.add(E),f.add(E);for(let A of p.get(E)||[])g(A);f.delete(E)}};g(i),d.size!==n.length&&m("NATIVE_WORKFLOW_NODE_UNREACHABLE",`${t}/nodes`)}function mt(e,t,o){o>20&&m("NATIVE_WORKFLOW_EXPRESSION_DEPTH_EXCEEDED",t);let n=T(e,t),i=S(n.op,`${t}/op`,16);if(i!=="literal"){if(i==="path"){let s=S(n.path,`${t}/path`,255);(!/^[A-Za-z][A-Za-z0-9_.-]{0,254}$/.test(s)||s.split(".").some(a=>["__proto__","constructor","prototype"].includes(a)))&&m("NATIVE_WORKFLOW_EXPRESSION_PATH_INVALID",`${t}/path`);return}if(["eq","neq","gt","gte","lt","lte","in","contains"].includes(i)){mt(n.left,`${t}/left`,o+1),mt(n.right,`${t}/right`,o+1);return}if(["and","or"].includes(i)){let s=w(n.values,`${t}/values`,100);s.length===0&&m("NATIVE_WORKFLOW_EXPRESSION_EMPTY",`${t}/values`),s.forEach((a,r)=>mt(a,`${t}/values/${r}`,o+1));return}if(["not","exists"].includes(i)){mt(n.value,`${t}/value`,o+1);return}m("NATIVE_WORKFLOW_EXPRESSION_OPERATOR_INVALID",`${t}/op`)}}function ya(e,t){j(e.schemaVersion,"openxiangda.workflow-binding/v2",`${t}/schemaVersion`),Ht(e.workflowCode,`${t}/workflowCode`);let o=T(e.bindings,`${t}/bindings`);Object.keys(o).length>200&&m("NATIVE_WORKFLOW_BINDING_LIMIT_EXCEEDED",`${t}/bindings`);for(let[n,i]of Object.entries(o)){qt(n,`${t}/bindings/${n}`);let s=T(i,`${t}/bindings/${n}`),a=S(s.provider,`${t}/bindings/${n}/provider`,64);if(["fixed_users","initiator","input_users","form_field_users","department_supervisor","app_role","app_role_in_scope","business_relation","previous_node_actor","initiator_select","application_provider"].includes(a)||m("NATIVE_WORKFLOW_BINDING_PROVIDER_INVALID",`${t}/bindings/${n}/provider`),a==="fixed_users"&&w(s.users,`${t}/bindings/${n}/users`,200).length===0&&m("NATIVE_WORKFLOW_BINDING_USERS_REQUIRED",`${t}/bindings/${n}/users`),["input_users","form_field_users"].includes(a)&&S(s.inputPath,`${t}/bindings/${n}/inputPath`,255),["app_role","app_role_in_scope","initiator_select"].includes(a)&&F(s.roleCode,`${t}/bindings/${n}/roleCode`),a==="department_supervisor"&&S(s.departmentIdFrom,`${t}/bindings/${n}/departmentIdFrom`,255),a==="application_provider"&&F(s.providerCode,`${t}/bindings/${n}/providerCode`),s.routing!==void 0){let r=Ut(s.routing);r.length&&m(r[0],`${t}/bindings/${n}/routing`)}}}function Na(e,t,o){j(t.workflowCode,e.code,`${o}/workflowCode`);let n=T(t.bindings,`${o}/bindings`),i=vn(e,t);i.length&&m(i[0],o);let s=Pt(e,t);s.length&&m(s[0],o);for(let[a,r]of Object.entries(T(e.nodes,`${o}/nodes`))){let c=T(r,`${o}/nodes/${a}`);["approval","cc"].includes(c.kind)&&!n[c.binding]&&m("NATIVE_WORKFLOW_BINDING_REFERENCE_MISSING",`${o}/nodes/${a}/binding`)}}function Ta(e,t,o){let n=T(t.routeManifest,"/contracts/routeManifest"),i=T(e.routeManifest,"/contracts/routeManifest"),s=new Map;for(let p of w(o.data?.resources,"/config/data/resources",100)){let d=T(p,"/config/data/resources");s.set(String(d.code||""),d)}let a=new Set(w(i.routes,"/contracts/routeManifest/routes",1e3).map(p=>String(T(p,"/contracts/routeManifest/routes").code||""))),r=[];for(let p of w(n.routes,"/contracts/routeManifest/routes",1e3)){let d=T(p,"/contracts/routeManifest/routes"),f=String(d.kind||"");if(f!=="resource-records"&&f!=="resource-submit")continue;let g=String(d.resourceCode||""),E=s.get(g);E||m("NATIVE_ROUTE_MANIFEST_RESOURCE_UNKNOWN","/contracts/routeManifest/routes");let b=`user.${g}.${f==="resource-records"?"records":"submit"}`;j(String(d.code||""),b,"/contracts/routeManifest/routes/code");let I=f==="resource-records"?"read":"create",_=String(T(E.capabilities,"/config/data/resources/capabilities")[I]||"");for(let u of["desktop","mobile"]){let N=T(d[u],`/contracts/routeManifest/routes/${u}`),y=u==="mobile"?"/m/my/":"/my/",O=f==="resource-records"?`${y}${g}`:`${y}${g}/submit`;j(String(N.path||""),O,`/contracts/routeManifest/routes/${u}/path`),j(String(N.capability||""),_,`/contracts/routeManifest/routes/${u}/capability`),j(String(N.routeCode||""),`${b}.${u}`,`/contracts/routeManifest/routes/${u}/routeCode`)}(a.has(b)||r.some(u=>String(u.code)===b))&&m("NATIVE_ROUTE_MANIFEST_DUPLICATE","/contracts/routeManifest/routes/code"),r.push(d)}if(!r.length)return;i.routes=w([...i.routes,...r],"/contracts/routeManifest/routes",1e3).sort((p,d)=>ue(String(T(p,"x").code||""),String(T(d,"x").code||"")));let c=String(T(n.rootEntry,"x").code||"");if(r.find(p=>String(p.code)===c&&p.kind==="resource-records")){let p=T(n.rootEntry,"x");i.rootEntry={code:c,desktop:String(p.desktop||""),mobile:String(p.mobile||"")}}i.digest=X({schemaVersion:i.schemaVersion,appCode:i.appCode,devicePolicy:i.devicePolicy,rootEntry:i.rootEntry,authentication:i.authentication,routes:i.routes})}function We(e,t,o){let n=T(e,t);R(n,["schemaVersion","appCode","code","name","schema","surface","invariants","decimalReservationLifecycle","uniqueKeys","capabilities","dataPolicyCode","fieldPolicies"],t,!0),j(n.schemaVersion,"openxiangda.data-resource/v2",`${t}/schemaVersion`),j(n.appCode,o,`${t}/appCode`);let i=J(n.code,`${t}/code`),s=S(n.name,`${t}/name`,255),a=T(n.schema,`${t}/schema`);R(a,["fields"],`${t}/schema`);let r,c,l,p;try{l=In(n.decimalReservationLifecycle,`${t}/decimalReservationLifecycle`),r=sn(a.fields,`${t}/schema/fields`),p=Fo(n.uniqueKeys,r,`${t}/uniqueKeys`),c=co(n.invariants,r,`${t}/invariants`),_n(n.surface,r,`${t}/surface`)}catch(E){throw(E instanceof Ee||E instanceof qe||E instanceof st)&&m(E.code,E.pointer),E}let d=new Set(r.map(E=>E.code)),f=T(n.capabilities,`${t}/capabilities`);R(f,["read","create","update","delete"],`${t}/capabilities`);let g=T(n.fieldPolicies,`${t}/fieldPolicies`);for(let[E,A]of Object.entries(g)){!d.has(E)&&!Ze(E)&&m("NATIVE_DATA_FIELD_POLICY_FIELD_MISSING",`${t}/fieldPolicies/${E}`);let b=`${t}/fieldPolicies/${E}`,I=T(A,b);Ze(E)&&(R(I,["read"],b,!0),(!Array.isArray(I.read)||I.read.length>20||I.read.some(_=>typeof _!="string"||!_.trim())||new Set(I.read).size!==I.read.length)&&m("NATIVE_DATA_AUDIT_READ_POLICY_INVALID",`${b}/read`)),R(I,["read","create","update","mask"],b,!0),I.mask!==void 0&&!["omit","null"].includes(I.mask)&&m("NATIVE_DATA_FIELD_POLICY_MASK_INVALID",`${b}/mask`)}return{...n,code:i,name:s,schema:{fields:r},...n.invariants===void 0?{}:{invariants:c},...l?{decimalReservationLifecycle:l}:{},...p!==void 0?{uniqueKeys:p}:{},capabilities:f,fieldPolicies:g}}function Wi(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 Ni(e,t,o,n){let i=e.toString("utf8"),s;try{s=JSON.parse(i)}catch{m(o,t)}let a=T(s,t);return ee(a)!==i&&m(n,t),a}function Ti(e,t){let o=0,n=(i,s,a)=>{if(o+=1,o>wr&&m("NATIVE_ARTIFACT_NODE_LIMIT_EXCEEDED",s),a>Sr&&m("NATIVE_ARTIFACT_DEPTH_LIMIT_EXCEEDED",s),typeof i=="string"){Buffer.byteLength(i)>Mn&&m("NATIVE_ARTIFACT_STRING_LIMIT_EXCEEDED",s);return}if(Array.isArray(i)){i.forEach((r,c)=>n(r,`${s}/${c}`,a+1));return}if(!(!i||typeof i!="object"))for(let[r,c]of Object.entries(i))["__proto__","prototype","constructor"].includes(r)&&m("NATIVE_ARTIFACT_DANGEROUS_KEY",`${s}/${r}`),Oa(r)&&m("NATIVE_ARTIFACT_RUNTIME_FIELD_FORBIDDEN",`${s}/${r}`),n(c,`${s}/${r}`,a+1)};n(e,t,0)}function Oa(e){return["environmentKey","environmentId","secretValue","ciphertext","oauthClient","oauthClientId","oauthClientSecret","signingSecret","kubernetesNamespace","nodePort","productionUrl"].includes(e)}function Ye(e){return{value:e,digest:X(e)}}function Oi(e,t,o,n){typeof e!="string"&&!Buffer.isBuffer(e)&&!(e instanceof Uint8Array)&&m("NATIVE_ARTIFACT_BYTES_REQUIRED",o);let i=Buffer.isBuffer(e)?e:Buffer.from(e);return i.byteLength===0&&m("NATIVE_ARTIFACT_EMPTY",o),i.byteLength>t&&m(n,o),i}function hi(e,t,o,n){let i=Jt.createHash("sha256").update(e).digest("hex");Jt.timingSafeEqual(Buffer.from(i),Buffer.from(t))||m(n,o)}function T(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&m("NATIVE_OBJECT_REQUIRED",t),e}function w(e,t,o){return Array.isArray(e)||m("NATIVE_ARRAY_REQUIRED",t),e.length>o&&m("NATIVE_ARRAY_LIMIT_EXCEEDED",t),e}function v(e,t,o){let n=w(e,t,o).map((i,s)=>S(i,`${t}/${s}`,255));return new Set(n).size!==n.length&&m("NATIVE_ARRAY_DUPLICATE",t),n}function S(e,t,o){return(typeof e!="string"||e.length===0||e.length>o)&&m("NATIVE_STRING_INVALID",t),e}function Hn(e,t,o){return(typeof e!="string"||e.length>o)&&m("NATIVE_STRING_INVALID",t),e}function F(e,t){let o=S(e,t,128);return fr.test(o)||m("NATIVE_CODE_INVALID",t),o}function J(e,t){let o=S(e,t,64);return _r.test(o)||m("NATIVE_RESOURCE_CODE_INVALID",t),o}function K(e,t){let o=S(e,t,63);return mr.test(o)||m("NATIVE_FIELD_CODE_INVALID",t),o}function Ht(e,t){let o=S(e,t,128);return Er.test(o)||m("NATIVE_WORKFLOW_CODE_INVALID",t),o}function qt(e,t){let o=S(e,t,128);return Ir.test(o)||m("NATIVE_WORKFLOW_BINDING_CODE_INVALID",t),o}function Se(e,t,o){let n=S(e,t,255);return ur.test(n)||m("NATIVE_CAPABILITY_CODE_INVALID",t),!n.startsWith(`app:${o}:`)&&!Wi(o).some(i=>i.code===n)&&m("NATIVE_CAPABILITY_APP_MISMATCH",t),n}function me(e,t){let o=S(e,t,2048);return(!o.startsWith("/")||o.startsWith("//")||o.includes("..")||o.includes("?")||o.includes("#"))&&m("NATIVE_ABSOLUTE_PATH_INVALID",t),o}function He(e,t){return(!Number.isInteger(e)||Number(e)<1)&&m("NATIVE_POSITIVE_INTEGER_REQUIRED",t),Number(e)}function te(e,t,o,n){return(!Number.isInteger(e)||Number(e)<o||Number(e)>n)&&m("NATIVE_INTEGER_OUT_OF_RANGE",t),Number(e)}function Xe(e,t){return typeof e!="boolean"&&m("NATIVE_BOOLEAN_REQUIRED",t),e}function qn(e,t){let o=S(e,t,64).toLowerCase();return dr.test(o)||m("NATIVE_DIGEST_INVALID",t),o}function j(e,t,o){e!==t&&m("NATIVE_VALUE_MISMATCH",o)}function R(e,t,o,n=!1){let i=new Set([...t,...Array.isArray(n)?n:[]]);for(let s of Object.keys(e))i.has(s)||m("NATIVE_PROPERTY_UNKNOWN",`${o}/${s}`);if(n!==!0)for(let s of t)Object.prototype.hasOwnProperty.call(e,s)||m("NATIVE_PROPERTY_REQUIRED",`${o}/${s}`)}function Z(e,t){return[...e].sort((o,n)=>ue(t(o),t(n)))}function U(e){return[...new Set(e)].sort(ue)}function Ri(e){return[...new Set(e)].sort((t,o)=>t-o)}function ue(e,t){return e===t?0:e<t?-1:1}function Mi(e){return!e||typeof e!="object"||Object.isFrozen(e)||(Object.freeze(e),Object.values(e).forEach(t=>Mi(t))),e}function Jn(e,t,o){if(Wn(e,t))return o;if(Array.isArray(e)&&Array.isArray(t)){let n=Math.max(e.length,t.length);for(let i=0;i<n;i+=1)if(!Wn(e[i],t[i]))return Jn(e[i],t[i],`${o}/${i}`)}if(e&&t&&typeof e=="object"&&typeof t=="object"&&!Array.isArray(e)&&!Array.isArray(t)){let n=U([...Object.keys(e),...Object.keys(t)]);for(let i of n){let s=e[i],a=t[i];if(!Wn(s,a))return Jn(s,a,`${o}/${i}`)}}return o}function Wn(e,t){return e===void 0||t===void 0?e===t:ee(e)===ee(t)}function m(e,t,o={}){throw new Kn(e,t,o)}var vd=50,Pd=131072,Xn=class extends Error{constructor(o){super("OPENXIANGDA_NATIVE_AUTHZ_BATCH_INPUT_INVALID");this.pointer=o}pointer;code="OPENXIANGDA_NATIVE_AUTHZ_BATCH_INPUT_INVALID";status=400};function Ld(e){let t=d=>{throw new Xn(d)},o=(d,f)=>((!d||typeof d!="object"||Array.isArray(d))&&t(f),d),n=(d,f,g)=>{for(let E of Object.keys(d))f.includes(E)||t(`${g}/${E}`)},i=(d,f,g)=>((typeof d!="string"||!d.trim()||d.length>f)&&t(g),d),s=(d,f)=>{let g=i(d,36,f);return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(g)||t(f),g.toLowerCase()},a=o(e,""),r;try{r=new TextEncoder().encode(JSON.stringify(a)).byteLength}catch{t("")}r>131072&&t(""),n(a,["schemaVersion","environmentKey","items"],""),a.schemaVersion!=="openxiangda.native-role-membership-batch-request/v2"&&t("/schemaVersion"),a.environmentKey!==void 0&&!["preproduction","production"].includes(String(a.environmentKey))&&t("/environmentKey"),(!Array.isArray(a.items)||a.items.length<1||a.items.length>50)&&t("/items");let c=new Set,l=new Set,p;for(let[d,f]of a.items.entries()){let g=`/items/${d}`,E=o(f,g);["create","update","revoke"].includes(String(E.operation))||t(`${g}/operation`),p??=E.operation,p!==E.operation&&t(`${g}/operation`),n(E,["operation","operationId","reason",...p==="create"?["userId","roleCode"]:["membershipId","expectedRevision"],...p!=="revoke"?["scopeGrants","validFrom","validTo"]:[]],g);let A=s(E.operationId,`${g}/operationId`);c.has(A)&&t(`${g}/operationId`),c.add(A),i(E.reason,1e3,`${g}/reason`);let b;if(p==="create"){let I=i(E.userId,255,`${g}/userId`),_=i(E.roleCode,128,`${g}/roleCode`);/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/.test(_)||t(`${g}/roleCode`),b=JSON.stringify([I,_])}else b=s(E.membershipId,`${g}/membershipId`),(!Number.isSafeInteger(E.expectedRevision)||Number(E.expectedRevision)<1)&&t(`${g}/expectedRevision`);l.has(b)&&t(g),l.add(b),E.scopeGrants!==void 0&&(!Array.isArray(E.scopeGrants)||E.scopeGrants.length>100)&&t(`${g}/scopeGrants`);for(let I of["validFrom","validTo"])E[I]!==void 0&&E[I]!==null&&i(E[I],64,`${g}/${I}`)}}var Gi="openxiangda.workflow-delegation-administration/v2",qi="openxiangda.workflow-delegation-mutation/v2",Ui="openxiangda.workflow-delegation-preview/v2";var At={type:"string",format:"uuid",pattern:"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$"},fe={type:"string",minLength:1,maxLength:255},Me={type:"string",format:"date-time"},Qe={type:"integer",minimum:1},ha={anyOf:[Me,{type:"null"}]},Qn={anyOf:[fe,{type:"null"}]},Xt={type:"string",pattern:"^membership:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},Ji={const:"future-assignments-only"},Zn={schemaVersion:{const:Gi},id:At,appCode:fe,environmentKey:fe,workflowCode:Qn,delegatorUserId:fe,delegateUserId:fe,delegatorRoleSubjectKey:Xt,delegateRoleSubjectKey:Xt,validFrom:Me,validTo:Me,status:{enum:["active","revoked","expired"]},reason:{type:"string",minLength:1,maxLength:4e3},createdBy:fe,createdAt:Me,revokedAt:ha,revision:Qe,roleCode:fe,roleName:fe,delegatorDisplayName:fe,delegateDisplayName:fe,delegatorRoleSubjectRevision:Qe,delegateRoleSubjectRevision:Qe,effectiveState:{enum:["active","scheduled","expired","revoked","ineligible"]},evaluatedAt:Me,issues:{type:"array",maxItems:20,uniqueItems:!0,items:fe},canRevoke:{type:"boolean"},revokedBy:Qn,revokeReason:{type:["string","null"],maxLength:4e3},taskPolicy:Ji},eo={type:"object",additionalProperties:!1,required:Object.keys(Zn),properties:Zn},jd={$id:Gi,...eo},zi={schemaVersion:{const:qi},operationId:At,environmentKey:{enum:["preproduction","production"]},reason:{type:"string",minLength:1,maxLength:2e3,pattern:"\\S"}},Bi={...zi,operation:{const:"create"},workflowCode:Qn,delegatorRoleSubjectKey:Xt,expectedDelegatorRevision:Qe,delegateUserId:fe,delegateRoleSubjectKey:Xt,expectedDelegateRevision:Qe,validFrom:Me,validTo:Me},Ki={...zi,operation:{const:"revoke"},delegationId:At,expectedRevision:Qe},Ra={$id:qi,type:"object",oneOf:[{type:"object",additionalProperties:!1,required:Object.keys(Bi),properties:Bi},{type:"object",additionalProperties:!1,required:Object.keys(Ki),properties:Ki}]},Ca={type:"string",pattern:"^[0-9a-f]{64}$"},Wd={$id:Ui,type:"object",additionalProperties:!1,required:["schemaVersion","operationId","operation","requestDigest","before","after","taskPolicy"],properties:{schemaVersion:{const:Ui},operationId:At,operation:{enum:["create","revoke"]},requestDigest:Ca,before:{anyOf:[eo,{type:"null"}]},after:{...eo,properties:{...Zn,id:{anyOf:[At,{type:"null"}]}}},taskPolicy:Ji}};function Bd(e){return e===void 0?"":`
|
|
9
|
-
${X(e)}`}function Kd(e,t){let o=e.handlers.find(n=>n.code===t);return X(o?.workflowStep?o:e)}var qd="67e2e7393d022709e99cdfe556814891b1777c2b09343ecaf45d57a6dc031299";export{lo as DATA_AUDIT_METADATA_FIELDS,Un as DATA_EVENT_TYPES_V2,ka as DATA_FORM_DRAFT_MAX_BYTES,It as DATA_SUBTABLE_MAX_ROWS,bt as DATA_SUBTABLE_MAX_TOTAL_ROWS,cs as DATA_SYSTEM_SORT_FIELD_CODES,$a as DATA_TRANSACTION_MAX_BYTES,Da as DATA_TRANSACTION_MAX_OPERATIONS,nt as ManagedConcurrencyContractError,qd as NATIVE_CONFIGURATION_VALIDATOR_DIGEST,Y as NATIVE_CONTRACT_CAPACITY_V2,ad as NATIVE_DATA_POLICY_EXPRESSION_MAX_CLAUSES,id as NATIVE_DATA_POLICY_EXPRESSION_MAX_DEPTH,sd as NATIVE_DATA_POLICY_EXPRESSION_MAX_GROUP_ITEMS,rd as NATIVE_DATA_POLICY_EXPRESSION_MAX_LEAVES,cd as NATIVE_DATA_POLICY_EXPRESSION_MAX_OCCURRENCES,ds as NATIVE_DATA_QUERY_OPERATORS_V2,Pd as NATIVE_ROLE_MEMBERSHIP_BATCH_MAX_BYTES,vd as NATIVE_ROLE_MEMBERSHIP_BATCH_MAX_ITEMS,yc as NATIVE_UNIQUE_KEY_MAX_BYTES,Vo as NATIVE_UNIQUE_KEY_NORMALIZERS,Kn as NativeConfigurationCompilerError,Ee as NativeDataFieldContractV2Error,_t as NativeDataPolicyExpressionV2Error,qe as NativeDecimalLifecycleContractError,hn as NativeEventActionContractError,Xn as NativeRoleMembershipBatchInputError,yn as NativeScopeSourceFieldPathV2Error,st as NativeUniqueKeyContractError,Xi as OPENXIANGDA_NATIVE_DATA_FIELD_TYPES_V2,we as OPENXIANGDA_NATIVE_DATA_SURFACE_KEYS_V2,un as OPENXIANGDA_NATIVE_DRAFT_STATE_KEYS_V2,on as OPENXIANGDA_NATIVE_SYSTEM_FIELDS_V2,ro as OPENXIANGDA_NATIVE_SYSTEM_FIELD_MAP_V2,Mc as WORKFLOW_AUTOMATIC_CC_MAX_RECIPIENTS,Zs as WORKFLOW_AUTOMATIC_CC_PROVIDERS,rt as WORKFLOW_BUSINESS_STEP_EVENT,Bo as WORKFLOW_BUSINESS_STEP_EVENTS,Dc as WORKFLOW_BUSINESS_STEP_FACTS_KEY,Sn as WORKFLOW_BUSINESS_STEP_MAX_BYTES,zs as WORKFLOW_BUSINESS_STEP_MAX_RECEIPT_BYTES,kn as WORKFLOW_CONFIGURABLE_OPERATIONS,Vn as WORKFLOW_CONFIGURABLE_PROVIDERS,Bn as WORKFLOW_EVENT_TYPES_V2,Xc as WORKFLOW_ROUTING_MAX_BYTES,Hc as WORKFLOW_ROUTING_MAX_MATCHED_RULES,Yc as WORKFLOW_ROUTING_MAX_RULES,tr as WORKFLOW_TASK_PAGE_DEFINITION_MAX_BYTES,Ln as WORKFLOW_TASK_PAGE_MAX_BYTES,er as WORKFLOW_TASK_PAGE_MAX_FIELDS,Qo as WORKFLOW_TASK_SUBTABLE_MAX_ROWS,nr as WORKFLOW_TASK_SUBTABLE_MAX_TOTAL_ROWS,ye as WorkflowTaskPageError,or as applyWorkflowTaskPageValues,Gc as applyWorkflowTaskSubtableRows,Ld as assertNativeRoleMembershipBatchInput,Vd as compileNativeApplicationConfiguration,xo as compileNativeEventAction,Vr as compileNativeEventCapturePlansV2,kr as compileRequiredPlatformCapabilitiesV3,Dn as compileWorkflowBusinessStepHandlers,Ve as evaluateWorkflowTaskPageExpression,Lt as formatWorkflowExpression,uo as hasDataAuditReadPolicy,Ze as isDataAuditMetadataField,fo as isDataSystemSortField,ja as isNativeDataQueryOperatorV2,Tt as isNativeMultiValueFieldV2,Ec as materializeNativeDataQueryPathTypesV2,Bt as nativeDataPolicyExpressionLeavesV2,ci as nativeDataPolicyExpressionToCnfV2,Ic as nativeDataQueryPathPlanV2,Ma as nativeFieldAggregatePlanV2,ac as nativeFieldColumnDefinitionV2,cc as nativeFieldDefaultSqlV2,dc as nativeFieldHasDefaultV2,pc as nativeFieldIndexStatementsV2,Ot as nativeFieldRequiresCreateInputV2,fc as nativeFieldSequenceGrantStatementsV2,uc as nativeFieldSequenceOwnershipStatementsV2,lc as nativeFieldSequenceStatementsV2,go as nativeFieldSupportsFilterV2,Wa as nativeFieldSupportsOperatorV2,dn as nativeFieldSupportsSearchV2,tt as nativeFieldSupportsSortV2,mo as nativeOperatorsForFieldV2,$s as nativePhysicalFieldV2,rc as nativePhysicalFieldsV2,De as nativePhysicalObjectNameV2,gc as nativeScopeSourceFieldValueV2,$o as nativeScopeSourceGrantPathSupportedV2,Nn as nativeScopeSourceSubjectPathSupportedV2,_c as nativeSubtableConstraintStatementsV2,Nc as nativeUniqueKeysJsonSchema,In as parseDecimalReservationLifecycle,sn as parseNativeDataFieldsV2,co as parseNativeDataResourceInvariantsV2,Fo as parseNativeUniqueKeys,mn as projectNativeDataResourceViewV2,Pc as projectWorkflowGraph,jc as projectWorkflowNodePolicy,ae as quoteNativeIdentifierV2,qc as refreshWorkflowTaskPageFacts,ot as resolveNativeScopeSourceFieldPathV2,td as selectWorkflowAssignmentRoutingRules,Va as serializedDataBytes,ho as validateDecimalReservationLifecycles,To as validateManagedConcurrency,Io as validateNativeDataDraftStateV2,ao as validateNativeDataResourceReferencesV2,_n as validateNativeDataResourceSurfaceV2,Fn as validateWorkflowAdministration,si as validateWorkflowAssignmentRoutingBindings,Ut as validateWorkflowAssignmentRoutingPolicy,Zc as validateWorkflowAssignmentRoutingRules,vn as validateWorkflowAutomaticCc,kc as validateWorkflowBusinessStepHandlerContract,$c as validateWorkflowBusinessStepRequest,Ys as validateWorkflowBusinessStepResult,Ft as validateWorkflowBusinessStepSchema,Jo as validateWorkflowBusinessStepSubscriptions,Pt as validateWorkflowBusinessSteps,Wo as validateWorkflowInstanceCommandPolicies,xc as validateWorkflowNodeConfigurationPatch,Yo as validateWorkflowReadability,Mt as validateWorkflowTaskPages,ed as workflowAssignmentRoutingFacts,Qc as workflowAssignmentRoutingPolicySchema,ar as workflowAssignmentRoutingSemantic,vt as workflowBusinessStepFactSchema,Kd as workflowBusinessStepHandlerDigest,Vc as workflowBusinessStepInput,Hs as workflowBusinessStepPath,Bd as workflowBusinessStepReceiptSignatureSuffix,Vt as workflowBusinessStepValueMatches,Ra as workflowDelegationMutationRequestSchema,zo as workflowExpressionPaths,Sc as workflowInstanceCommandDeadlineError,Cc as workflowInstanceTerminateCapabilityAllowed,at as workflowNodeAllowedOperations,jo as workflowPolicyTimestamp,ti as workflowTaskPageFieldState,Jc as workflowTaskPageReplayCoversInvalidation,Kc as workflowTaskSubtableRows};
|
|
8
|
+
END $native_subtable$`]}function ve(e,...t){return`${e}_${Gs("sha256").update(t.join(":")).digest("hex").slice(0,32)}`}function ce(e){if(!/^[A-Za-z_][A-Za-z0-9_]{0,62}$/.test(e))throw new Error("OPENXIANGDA_NATIVE_IDENTIFIER_INVALID");return`"${e}"`}function Xs(e,t){return e.type==="subtable"?"none":t?"gin-trigram":e.indexed?["date-range","datetime-range"].includes(e.type)?"gist-range":zn.has(e.type)?"btree-snapshot-expressions":qs.has(e.type)?"gin-jsonb-path":"btree":"none"}function Zs(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 Js.has(e.type),"jsonb"}}function _i(e,t){if(Ft(t.type)&&t.type!=="subtable")return"'[]'::jsonb";if(t.type!=="serial-number")return"";let o=pi(t.serial?.prefix||""),n=t.serial?.digits??6;return`(${o} || lpad(nextval(${pi(Gt(e,t.code))})::text, ${n}, '0'))`}function Qs(e,t){return mi.has(t.type)?` CHECK (${e} IS NULL OR jsonb_typeof(${e}) = 'array')`:zs.has(t.type)?` CHECK (${e} IS NULL OR jsonb_typeof(${e}) = 'object')`:""}function Kt(e){return`"app_data".${ce(e)}`}function Gt(e,t){let o=ve("seq",e,t);return`"app_data".${ce(o)}`}function pi(e){return`'${e.replace(/'/g,"''")}'`}var gi=new Set(["option.single","option.multiple","user.single","user.multiple","department.single","department.multiple","resource-ref.single","resource-ref.multiple"]),ea=new Set([...gi,"cascade.single","cascade.multiple","file","image","signature","address","location","json"]),Ai=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,ta=new Set(["__proto__","prototype","constructor"]),Jn=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 mt(e,t){let o=Ii(e);if(!o)return null;let n=t.get(o[0]);if(!n)return null;let i=o.slice(1).join(".")||void 0;return{field:n,...i?{valuePath:i}:{}}}function Hn(e){return!!(e&&e.field.type==="user.single"&&e.valuePath==="value")}function Ei(e,t,o){if(!e||!t||!na(e))return!1;let{field:n,valuePath:i}=e;if(!i)return t.valueType==="uuid"?n.type==="uuid":["text.short","text.long","serial-number"].includes(n.type);if(i==="value")return!(t.valueSourceResourceCode&&n.type.startsWith("resource-ref.")&&n.source?.resourceCode!==t.valueSourceResourceCode);let r=i.slice(9),s=o.get(n.source?.resourceCode||"")?.get(r)?.type;return t.valueType==="uuid"?s==="uuid":["text.short","text.long","serial-number"].includes(s||"")}function nl(e,t){let o=Ii(t);if(!o)throw new Jn(String(t||""));let n=e;for(let i of o){if(!n||typeof n!="object"||!Object.prototype.hasOwnProperty.call(n,i))return;n=n[i]}return n}function na(e){let{field:t,valuePath:o}=e;if(!o)return!ea.has(t.type);if(o==="value")return gi.has(t.type);if(!o.startsWith("snapshot."))return!1;let n=o.slice(9);return Ai.test(n)&&t.type.startsWith("resource-ref.")&&!!t.source?.snapshotFields?.includes(n)}function Ii(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=>!Ai.test(o)||ta.has(o))||t.length===2&&t[1]!=="value"||t.length===3&&t[1]!=="snapshot"?null:t}var oa=new Set(["option.single","user.single","department.single","resource-ref.single"]),ia=new Set(["text.short","text.long","text.rich","number.integer","number.decimal","boolean","date","time","datetime","uuid","serial-number"]),ra=new Set(["value","label","description","color"]),sa=new Set(["avatarUrl","employeeNo","title","mobile","email"]),aa=new Set(["fullPath","parent.value","parent.label"]),ca=new Set(["country.value","country.label","province.value","province.label","city.value","city.label","district.value","district.label","street.value","street.label","detail","fullAddress"]),da=new Set(["longitude","latitude","accuracy"]),la=new Set(["address","name","province","city","district","source"]);function il(e){let t=new Map(e.map(o=>[o.code,new Map(o.schema.fields.map(n=>[n.code,n]))]));return e.map(o=>({...o,schema:{...o.schema,fields:o.schema.fields.map(n=>{let i=ua(n,t);if(!Object.keys(i).length)return n;let r={...n};return Object.defineProperty(r,"queryPathTypes",{configurable:!1,enumerable:!1,writable:!1,value:Object.freeze(i)}),r})}}))}function rl(e,t){if(oa.has(e.type)&&ra.has(t)||e.type==="user.single"&&sa.has(t)||e.type==="department.single"&&aa.has(t))return _t(t);if(e.type==="resource-ref.single"){let o=e.queryPathTypes?.[t];return o?{parts:t.split("."),type:o}:null}if(e.type==="address"&&ca.has(t))return _t(t);if(e.type==="location"){if(da.has(t))return{parts:[t],type:"number.decimal"};if(la.has(t))return _t(t);if(t==="capturedAt")return{parts:[t],type:"datetime"}}return null}function ua(e,t){if(e.type!=="resource-ref.single"||!e.source)return{};let o=t.get(e.source.resourceCode);return o?Object.fromEntries((e.source.snapshotFields||[]).flatMap(n=>{let i=o.get(n);return i?[[`snapshot.${n}`,ia.has(i.type)?i.type:"json"]]:[]})):{}}function _t(e){return{parts:e.split("."),type:"text.short"}}var Oi=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Ni=(e,t)=>Object.keys(e).length===t.length&&Object.keys(e).every(o=>t.includes(o)),yi=e=>typeof e=="string"&&/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/.test(e)&&e.length<=100,bi=e=>typeof e=="string"&&/^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(e);function Yn(e){throw new Error(`OPENXIANGDA_WORKFLOW_STAGE_${e}`)}function Ti(e){(!Oi(e)||!Ni(e,["workflowCode","resourceCode","actor","runningNodeIds","allowedStatuses"])||!yi(e.workflowCode)||!yi(e.resourceCode)||!["initiator","reader"].includes(String(e.actor))||!Array.isArray(e.runningNodeIds)||e.runningNodeIds.length>32||new Set(e.runningNodeIds).size!==e.runningNodeIds.length||e.runningNodeIds.some(t=>typeof t!="string"||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(t))||!Array.isArray(e.allowedStatuses)||e.allowedStatuses.length>5||new Set(e.allowedStatuses).size!==e.allowedStatuses.length||e.allowedStatuses.some(t=>!["approved","rejected","cancelled","terminated","returned"].includes(t))||e.runningNodeIds.length+e.allowedStatuses.length===0)&&Yn("POLICY_INVALID")}function al(e){(!Oi(e)||!Ni(e,["instanceId","subjectRecordId","expectedInstanceSequence"])||!bi(e.instanceId)||!bi(e.subjectRecordId)||!Number.isSafeInteger(e.expectedInstanceSequence)||e.expectedInstanceSequence<0)&&Yn("GUARD_INVALID")}function cl(e,t,o){o?.some(n=>(n.kind==="record-match"||n.kind==="record-assert")&&n.resourceCode===e.resourceCode&&n.id.toLowerCase()===t.subjectRecordId.toLowerCase()&&n.assertions.some(i=>i.kind==="value"&&i.field==="revision"&&i.operator==="eq"&&Number.isSafeInteger(i.value)&&Number(i.value)>0))||Yn("SOURCE_GUARD_REQUIRED")}var dl={type:"object",additionalProperties:!1,required:["workflowCode","resourceCode","actor","runningNodeIds","allowedStatuses"],properties:{workflowCode:{type:"string",pattern:"^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$",maxLength:100},resourceCode:{type:"string",pattern:"^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$",maxLength:100},actor:{enum:["initiator","reader"]},runningNodeIds:{type:"array",maxItems:32,uniqueItems:!0,items:{type:"string",pattern:"^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$"}},allowedStatuses:{type:"array",maxItems:5,uniqueItems:!0,items:{enum:["approved","rejected","cancelled","terminated","returned"]}}},anyOf:[{properties:{runningNodeIds:{minItems:1}}},{properties:{allowedStatuses:{minItems:1}}}]};var gt=class extends Error{constructor(o,n){super(o);this.code=o;this.pointer=n}code;pointer},ue=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},Ri=(e,t)=>e===t||e==="*"||e.endsWith(":*")&&t.startsWith(e.slice(0,-1));function Ci(e){let{policy:t,resource:o,baselineRoleCode:n,baselineCapabilities:i,pointer:r}=e,c=A=>A===void 0||A===!0||Array.isArray(A)&&A.length>0&&A.every(O=>typeof O=="string"&&O.length>0&&!e.baselineDeniedCapabilities?.some(b=>Ri(b,O))&&i.some(b=>Ri(b,O))),s=(A,O="")=>{throw new gt(A,`${r}/publicRead${O}`)},a=ue(t.publicRead);(!t.publicRead||Object.keys(a).length!==1||!Object.hasOwn(a,"fields")||!Array.isArray(a.fields)||a.fields.length<1||a.fields.length>1e3||a.fields.some(A=>typeof A!="string"||!/^[A-Za-z][A-Za-z0-9_]{0,62}$/.test(A))||new Set(a.fields).size!==a.fields.length)&&s("AUTHENTICATED_PUBLIC_READ_FIELDS_INVALID","/fields"),(!Array.isArray(t.operations)||t.operations.length!==1||t.operations[0]!=="read"||t.readExpression!==void 0||t.writeBoundary!==void 0)&&s("AUTHENTICATED_PUBLIC_READ_POLICY_NOT_READ_ONLY"),(!n||!o||o.code!==t.resourceCode||o.dataPolicyCode!==t.code||!c([ue(o.capabilities).read]))&&s("AUTHENTICATED_PUBLIC_READ_BASELINE_OR_RESOURCE_INVALID");let d=ue(o),f=ue(d.schema).fields;(!Array.isArray(f)||!f.length)&&s("AUTHENTICATED_PUBLIC_READ_RESOURCE_FIELDS_MISSING");let u=new Map(f.map(A=>[String(ue(A).code),ue(A)])),p=new Set(a.fields),g=ue(d.fieldPolicies);for(let A of p){let O=ue(u.get(A));(!u.has(A)||O.system===!0||ue(ue(d.surface).fields)[A]?.system===!0||Lt.has(A))&&s("AUTHENTICATED_PUBLIC_READ_FIELD_NOT_DECLARED",`/fields/${A}`),(O.type==="subtable"||O.subtable!==void 0)&&s("AUTHENTICATED_PUBLIC_READ_SUBTABLE_UNSUPPORTED",`/fields/${A}`),c(ue(g[A]).read)||s("AUTHENTICATED_PUBLIC_READ_FIELD_NOT_BASELINE_READABLE",`/fields/${A}`)}let I=[...u.keys()].filter(A=>!p.has(A));for(let A of I)c(ue(g[A]).read)&&s("AUTHENTICATED_PUBLIC_READ_PRIVATE_FIELD_ACCESSIBLE",`/fields/${A}`);I.length&&jt.some(A=>c(ue(g[A]).read))&&s("AUTHENTICATED_PUBLIC_READ_PRIVATE_HISTORY_ACCESSIBLE")}var hi=["exact-v1","nfkc-space-v1","nfkc-upper-ascii-v1"],ml=256,Et=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"},Xn=e=>!!(e&&typeof e=="object"&&!Array.isArray(e)),oe=(e,t)=>{throw new Et(e,t)},qt=(e,t)=>e<t?-1:e>t?1:0,At=(e,t,o)=>{Object.keys(e).some(n=>!t.includes(n))&&oe(o,"\u4E0D\u652F\u6301\u672A\u77E5\u5C5E\u6027")};function wi(e,t,o="/uniqueKeys"){if(e===void 0)return;if(!Array.isArray(e)||e.length>8)return oe(o,"\u6BCF\u8D44\u6E90\u6700\u591A 8 \u6761\u89C4\u5219");let n=new Map(t.map(r=>[r.code,r])),i=new Set;return e.map((r,c)=>{let s=`${o}/${c}`;if(!Xn(r))return oe(s,"\u89C4\u5219\u5FC5\u987B\u662F\u5BF9\u8C61");if(At(r,["code","fields","when"],s),typeof r.code!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(r.code)||r.code.length>20||i.has(r.code))return oe(`${s}/code`,"\u9700\u8981\u4E0D\u91CD\u590D\u4E14\u4E0D\u8D85\u8FC7 20 \u5B57\u7B26\u7684 lower-kebab-case \u6807\u8BC6");if(i.add(r.code),!Array.isArray(r.fields)||r.fields.length<1||r.fields.length>4)return oe(`${s}/fields`,"\u5FC5\u987B\u9009\u62E9 1 \u5230 4 \u4E2A\u5B57\u6BB5");let a=new Set,d=r.fields.map((g,I)=>{let A=`${s}/fields/${I}`;if(!Xn(g))return oe(A,"\u5B57\u6BB5\u5FC5\u987B\u662F\u5BF9\u8C61");At(g,["fieldCode","normalizer"],A);let O=n.get(g.fieldCode);if(!O||!["text.short","uuid","option.single","resource-ref.single","user.single"].includes(O.type)||a.has(g.fieldCode))return oe(`${A}/fieldCode`,"\u9700\u8981\u4E0D\u91CD\u590D\u7684\u77ED\u6587\u672C\u3001UUID\u3001\u5355\u9009\u3001\u5355\u8BB0\u5F55\u5F15\u7528\u6216\u5355\u4EBA\u5B57\u6BB5");a.add(g.fieldCode);let b=g.normalizer===void 0?"exact-v1":g.normalizer;return!hi.includes(b)||O.type!=="text.short"&&b!=="exact-v1"?oe(`${A}/normalizer`,"\u5F52\u4E00\u5316\u65B9\u5F0F\u4E0D\u652F\u6301\u6216\u4E0E\u5B57\u6BB5\u7C7B\u578B\u4E0D\u7B26"):{fieldCode:O.code,normalizer:b}}).sort((g,I)=>qt(g.fieldCode,I.fieldCode)),f=r.when===void 0?[]:r.when;if(!Array.isArray(f)||f.length>4)return oe(`${s}/when`,"\u6700\u591A 4 \u4E2A\u5408\u53D6\u6761\u4EF6");let u=new Set,p=f.map((g,I)=>{let A=`${s}/when/${I}`;if(!Xn(g))return oe(A,"\u6761\u4EF6\u5FC5\u987B\u662F\u5BF9\u8C61");let O=n.get(g.fieldCode);if(!O)return oe(`${A}/fieldCode`,"\u5B57\u6BB5\u4E0D\u5B58\u5728");let b;if(g.operator==="empty"||g.operator==="nonempty"){if(At(g,["fieldCode","operator"],A),O.type!=="text.short")return oe(A,"\u7A7A\u503C\u6761\u4EF6\u4EC5\u652F\u6301\u77ED\u6587\u672C");b={fieldCode:O.code,operator:g.operator}}else if(g.operator==="in"||g.operator==="notIn"){At(g,["fieldCode","operator","values"],A);let E=new Set((O.options??[]).map(T=>T.value));if(O.type!=="option.single"||!Array.isArray(g.values)||g.values.length<1||g.values.length>16||g.values.some(T=>typeof T!="string"||T.length<1||T.length>128||!E.has(T))||new Set(g.values).size!==g.values.length)return oe(A,"\u96C6\u5408\u6761\u4EF6\u9700\u8981 1 \u5230 16 \u4E2A\u4E0D\u91CD\u590D\u7684\u5DF2\u58F0\u660E\u5355\u9009\u503C");b={fieldCode:O.code,operator:g.operator,values:[...g.values].sort(qt)}}else if(g.operator==="eq"||g.operator==="ne"){if(At(g,["fieldCode","operator","value"],A),O.type!=="boolean"||typeof g.value!="boolean")return oe(A,"\u7B49\u503C\u6761\u4EF6\u4EC5\u652F\u6301\u5E03\u5C14\u5B57\u6BB5\u548C\u5E03\u5C14\u503C");b={fieldCode:O.code,operator:g.operator,value:g.value}}else return oe(`${A}/operator`,"\u53EA\u652F\u6301 empty\u3001nonempty\u3001in\u3001notIn \u548C\u5E03\u5C14 eq\u3001ne");let _=JSON.stringify(b);return u.has(_)?oe(A,"\u6761\u4EF6\u4E0D\u80FD\u91CD\u590D"):(u.add(_),b)}).sort((g,I)=>qt(JSON.stringify(g),JSON.stringify(I)));return{code:r.code,fields:d,when:p}}).sort((r,c)=>qt(r.code,c.code))}function Si(e,t){let o=new Set(e.filter(n=>n.type==="user.single").map(n=>n.code));return t?.some(n=>n.fields.some(i=>o.has(i.fieldCode))||n.when?.some(i=>i.operator==="eq"||i.operator==="ne"))?"1.1.0":"1.0.0"}var zt={type:"string",pattern:"^[A-Za-z_][A-Za-z0-9_]{0,62}$"},_l={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:zt,normalizer:{enum:[...hi]}}}},when:{type:"array",maxItems:4,uniqueItems:!0,items:{oneOf:[{type:"object",additionalProperties:!1,required:["fieldCode","operator"],properties:{fieldCode:zt,operator:{enum:["empty","nonempty"]}}},{type:"object",additionalProperties:!1,required:["fieldCode","operator","values"],properties:{fieldCode:zt,operator:{enum:["in","notIn"]},values:{type:"array",minItems:1,maxItems:16,uniqueItems:!0,items:{type:"string",minLength:1,maxLength:128}}}},{type:"object",additionalProperties:!1,required:["fieldCode","operator","value"],properties:{fieldCode:zt,operator:{enum:["eq","ne"]},value:{type:"boolean"}}}]}}}}};var Di={"openxiangda.workflow.instance.completed.v2":"commit","openxiangda.workflow.instance.rejected.v2":"release","openxiangda.workflow.instance.withdrawn.v2":"release"};function ki(e,t){let o=()=>{throw new Error("NATIVE_EVENT_DECIMAL_RESERVATION_INVALID")},n=p=>!p||typeof p!="object"||Array.isArray(p)?o():p,i=n(e);if(Object.keys(i).some(p=>!["resourceCode","workflowCode","outcomes"].includes(p))||typeof i.resourceCode!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(i.resourceCode)||typeof i.workflowCode!="string"||!/^[A-Za-z0-9._:-]{1,128}$/.test(i.workflowCode)||t.execution!==void 0||!Array.isArray(i.outcomes)||!i.outcomes.length||i.outcomes.length>3)return o();let r=t.resources.find(p=>p.code===i.resourceCode),c=t.reservations.find(p=>p.mode==="reserve"&&p.resourceCode===i.resourceCode),s=t.workflows.find(p=>p.code===i.workflowCode);if(!r||!c||!s||s.resourceCode!==r.code)return o();let a=r.fields.find(p=>p.code===c.statusFieldCode);if(a?.type!=="option.single")return o();let d=new Set(a.options?.map(p=>p.value)),f=new Set,u=i.outcomes.map(p=>{let g=n(p),I=g.eventType;return Object.keys(g).some(A=>!["eventType","mode","eligibleChildStatuses"].includes(A))||typeof I!="string"||!Object.prototype.hasOwnProperty.call(Di,I)||!t.eventTypes.includes(I)||f.has(I)||g.mode!==Di[I]||!Array.isArray(g.eligibleChildStatuses)||!g.eligibleChildStatuses.length||g.eligibleChildStatuses.length>16||new Set(g.eligibleChildStatuses).size!==g.eligibleChildStatuses.length||g.eligibleChildStatuses.some(A=>typeof A!="string"||!/^[A-Za-z0-9._:-]{1,128}$/.test(A)||!d.has(A))?o():(f.add(I),{eventType:I,mode:g.mode,eligibleChildStatuses:[...g.eligibleChildStatuses].sort()})}).sort((p,g)=>p.eventType.localeCompare(g.eventType));return{resourceCode:i.resourceCode,workflowCode:i.workflowCode,outcomes:u}}function $i(e,t){let o=n=>Array.isArray(n)?n.filter(i=>i&&typeof i=="object"&&!Array.isArray(i)):[];return{eventTypes:Array.isArray(t.eventTypes)?t.eventTypes:[],execution:t.execution,resources:o(e.data?.resources).map(n=>({code:n.code,fields:o(n.schema?.fields).map(i=>({code:i.code,type:i.type,options:o(i.options).map(r=>({value:r.value}))}))})),reservations:o(e.backend?.operations).flatMap(n=>n.platformAccess?.decimalReservation?[n.platformAccess.decimalReservation]:[]),workflows:o(e.workflows?.definitions).map(n=>({code:n.definition?.code,resourceCode:n.definition?.subject?.resourceCode}))}}var Zn=class extends Error{constructor(o,n){super(n);this.pointer=o}pointer;code="NATIVE_EVENT_ACTION_INVALID"};function vi(e,t,o="/events/subscriptions"){if(e.execution===void 0)return;let n=(A,O)=>{throw new Zn(`${o}${A}`,O)},i=(A,O,b)=>((!A||typeof A!="object"||Array.isArray(A)||Object.keys(A).some(_=>!b.includes(_)))&&n(O,"Invalid action object or unsupported property"),A),r=i(e.execution,"/execution",["kind","version","operations"]);(r.kind!=="native-data"||r.version!==1)&&n("/execution","Expected native-data version 1"),e.platformAccess&&n("/platformAccess","Native actions do not use application runtime capabilities"),(!Array.isArray(e.eventTypes)||!e.eventTypes.length||e.eventTypes.some(A=>!/^openxiangda\.data\.record\.(created|updated|deleted)\.v2$/.test(A)))&&n("/eventTypes","Native data actions require declared data events");let c=e.filter?.resourceCodes;(!Array.isArray(c)||!c.length||c.length>20)&&n("/filter/resourceCodes","Native actions require explicit source resources");let s=new Map(t.map(A=>[A.code,A])),a=c.map(A=>{let O=s.get(A);return O||n("/filter/resourceCodes","Unknown source resource"),new Set((O.schema?.fields||[]).map(b=>b.code))}),d=new Set(e.payload?.fields||[]),f=e.payload?.includeChanges===!0,u=(A,O)=>{let b=i(A,O,["source","path","value"]);if(b.source==="literal"){(!Object.hasOwn(b,"value")||Object.hasOwn(b,"path"))&&n(O,"Literal binding requires only value");let l;try{l=JSON.stringify(b.value)}catch{n(O,"Literal must be JSON")}return(l===void 0||Buffer.byteLength(l)>65536)&&n(O,"Literal is too large or not JSON"),{source:"literal",value:JSON.parse(l)}}(b.source!=="event"||typeof b.path!="string"||Object.hasOwn(b,"value"))&&n(O,"Expected a literal or event binding");let _=b.path.split(".");(_.length>8||_.some(l=>!/^[A-Za-z0-9_-]+$/.test(l)||["__proto__","prototype","constructor"].includes(l)))&&n(O,"Invalid event path");let E=/^data\.projection\.([A-Za-z][A-Za-z0-9_]{0,62})$/.exec(b.path),T=/^data\.changes\.([A-Za-z][A-Za-z0-9_]{0,62})\.(before|after)$/.exec(b.path);if(E||T){let l=(E||T)[1];a.some(y=>!y.has(l))&&n(O,"Source field must exist on every filtered resource"),d.add(l),T&&(f=!0)}else["id","time","type","subject","data.recordId","data.revision","data.operation","data.resourceCode"].includes(b.path)||n(O,"Event path is not part of the data event contract");return{source:"event",path:b.path}};(!Array.isArray(r.operations)||r.operations.length<1||r.operations.length>16)&&n("/execution/operations","Expected 1 to 16 operations");let p={},g=r.operations.map((A,O)=>{let b=`/execution/operations/${O}`,_=i(A,b,["operation","resourceCode","data","id","expectedRevision"]);["create","update","delete"].includes(_.operation)||n(b,"Unsupported Native operation");let E=s.get(_.resourceCode);E||n(b,"Unknown action target resource");let T=new Map((E.schema?.fields||[]).map(y=>[y.code,y])),l=_.data===void 0?{}:i(_.data,`${b}/data`,[...T.keys()]);return Object.keys(l).length>32&&n(b,"Maximum 32 mapped fields per operation"),_.operation==="create"&&(_.id!==void 0||_.expectedRevision!==void 0)&&n(b,"Create does not accept id or expectedRevision"),_.operation==="delete"&&_.data!==void 0&&n(b,"Delete does not accept data"),Object.keys(l).some(y=>T.get(y)?.type==="serial-number")&&n(b,"Generated fields cannot be assigned"),p[_.resourceCode]=Z(E),{operation:_.operation,resourceCode:_.resourceCode,..._.operation==="create"?{}:{id:u(_.id,`${b}/id`),expectedRevision:u(_.expectedRevision,`${b}/expectedRevision`)},..._.operation==="delete"?{}:{data:Object.fromEntries(Object.entries(l).map(([y,R])=>[y,u(R,`${b}/data/${y}`)]))}}});(d.size>32||[...d].some(A=>a.some(O=>!O.has(A))))&&n("/payload/fields","Payload must contain at most 32 declared source fields");let I={kind:"native-data",version:1,operations:g,resourceDigests:p};return Buffer.byteLength(JSON.stringify(I))>65536&&n("/execution","Action plan exceeds 64 KiB"),{execution:{...I,digest:Z(I)},payload:{includeChanges:f,fields:[...d].sort()}}}function Pe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function Vi(e,t){if(e?.instanceCommands===void 0)return[];let o=Pe(e.instanceCommands);if(!o||!Object.keys(o).length||Object.keys(o).some(i=>!["withdraw","terminate"].includes(i)))return["WORKFLOW_INSTANCE_COMMAND_POLICIES_INVALID"];let n=[];for(let[i,r]of Object.entries(o)){let c=Pe(r),s=i==="withdraw"?["beforeFact","reasonRequired"]:["beforeFact","capability"];if(!c||!Object.keys(c).length||Object.keys(c).some(a=>!s.includes(a))||Object.hasOwn(c,"reasonRequired")&&typeof c.reasonRequired!="boolean"){n.push(`WORKFLOW_INSTANCE_COMMAND_POLICY_INVALID:${i}`);continue}if(i==="terminate"){let a=c.capability;(typeof a!="string"||a.length>255||!/^app:[a-z][a-z0-9]*(?:-[a-z0-9]+)*:[A-Za-z0-9:._-]+$/.test(a)||t&&(!a.startsWith(`app:${t.appCode}:`)||!t.capabilities.includes(a)))&&n.push("WORKFLOW_INSTANCE_TERMINATE_CAPABILITY_INVALID")}if(Object.hasOwn(c,"beforeFact")){let a=c.beforeFact,d=Pe(e.inputSchema),f=Pe(Pe(d?.properties)?.[a]),u=Pe(Pe(e.subject)?.factProjection)?.[a],p=t?.fields.get(u);(typeof a!="string"||!/^[A-Za-z][A-Za-z0-9_]{0,62}$/.test(a)||!Array.isArray(d?.required)||!d.required.includes(a)||f?.type!=="string"||f?.format!=="date-time"||typeof u!="string"||t&&(p?.type!=="datetime"||p.nullable===!0))&&n.push(`WORKFLOW_INSTANCE_COMMAND_DEADLINE_FACT_INVALID:${i}`)}}return n}function yl(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 bl(e){return e?.withdraw?.reasonRequired!==!1}function Pi(e){if(typeof e!="string")return null;let t=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,3}))?(Z|[+-]\d{2}:\d{2})$/.exec(e);if(!t)return null;let[,o,n,i,r,c,s]=t,a=t[8],d=new Date(Date.UTC(Number(o),Number(n),0)).getUTCDate();if(Number(n)<1||Number(n)>12||Number(i)<1||Number(i)>d||Number(r)>23||Number(c)>59||Number(s)>59||a!=="Z"&&(Number(a.slice(1,3))>23||Number(a.slice(4))>59))return null;let f=Date.parse(e);return Number.isFinite(f)?f:null}function Ol(e,t,o,n){let i=e?.[t];if(!i||i.beforeFact===void 0)return null;let r=i.beforeFact,c=Pe(o),s=r&&c&&Object.hasOwn(c,r)?Pi(c[r]):null,a=n instanceof Date?n.getTime():Pi(n);return s===null||a===null||!Number.isFinite(a)?"WORKFLOW_V2_CANCELLATION_DEADLINE_INVALID":a<s?null:"WORKFLOW_V2_CANCELLATION_DEADLINE_PASSED"}var It="openxiangda.workflow.step.requested.v2",xi=[It,"openxiangda.workflow.step.result_received.v2","openxiangda.workflow.step.completed.v2","openxiangda.workflow.step.continuation_failed.v2"],to=16384,fa=2048,Tl="steps",no=/^[A-Za-z][A-Za-z0-9_-]{0,127}$/,ji=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,Be=new Set(["__proto__","prototype","constructor"]),K=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&[Object.prototype,null].includes(Object.getPrototypeOf(e)),Wi=e=>{try{let t=JSON.stringify(e);return t===void 0?1/0:new TextEncoder().encode(t).length}catch{return 1/0}},ot=(e,t,o=0)=>{if(o>32)return!1;if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((r,c)=>ot(r,t[c],o+1));if(!K(e)||!K(t))return!1;let n=Object.keys(e).filter(r=>e[r]!==void 0),i=Object.keys(t).filter(r=>t[r]!==void 0);return n.length===i.length&&n.every(r=>Object.hasOwn(t,r)&&ot(e[r],t[r],o+1))};function Qn(e,t){let o=0,n=(i,r)=>++o>1e4||r>8?!1:i===null||typeof i=="boolean"||typeof i=="string"?!0:typeof i=="number"?Number.isFinite(i):Array.isArray(i)?i.length<=200&&i.every(c=>n(c,r+1)):K(i)&&Object.keys(i).length<=32&&Object.keys(i).every(c=>!Be.has(c))&&Object.values(i).every(c=>n(c,r+1));return Wi(e)<=t&&n(e,0)}function pa(e){return!K(e)||Object.keys(e).some(t=>!["executionId","handlerVersion","inputDigest","expectedFactRevision","output","receipt"].includes(t))?!1:/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/i.test(e.executionId||"")&&Number.isSafeInteger(e.handlerVersion)&&e.handlerVersion>=1&&e.handlerVersion<=1e6&&/^[a-f0-9]{64}$/.test(e.inputDigest||"")&&Number.isSafeInteger(e.expectedFactRevision)&&e.expectedFactRevision>=0&&K(e.output)&&Qn(e.output,to)&&(e.receipt===void 0||K(e.receipt)&&Qn(e.receipt,fa))}function Rl(e){return K(e)&&Object.keys(e).every(t=>["executionId","nodeId","handlerCode","handlerVersion","mode","input","inputDigest","expectedFactRevision"].includes(t))&&typeof e.nodeId=="string"&&no.test(e.nodeId)&&!Be.has(e.nodeId)&&typeof e.handlerCode=="string"&&/^[a-z][a-z0-9-]{0,100}$/.test(e.handlerCode)&&e.handlerCode.endsWith(`-v${e.handlerVersion}`)&&["pure","reconciled-effect"].includes(e.mode)&&pa({executionId:e.executionId,handlerVersion:e.handlerVersion,inputDigest:e.inputDigest,expectedFactRevision:e.expectedFactRevision,output:e.input})}function Jt(e,t,o=to){if(!Qn(t,o))return!1;let n=1e4,i=(r,c,s)=>{if(--n<0||s>8||!K(r))return!1;let a=c===null?"null":Array.isArray(c)?"array":typeof c=="number"&&Number.isSafeInteger(c)?"integer":typeof c,d=Array.isArray(r.type)?r.type:[r.type];if(!d.includes(a)&&!(a==="integer"&&d.includes("number"))||r.enum!==void 0&&(!Array.isArray(r.enum)||!r.enum.some(f=>ot(f,c)))||Object.hasOwn(r,"const")&&!ot(r.const,c))return!1;if(typeof c=="number")return Number.isFinite(c)&&(r.minimum===void 0||c>=r.minimum)&&(r.maximum===void 0||c<=r.maximum);if(typeof c=="string"){let f=Array.from(c).length;return(r.minLength===void 0||f>=r.minLength)&&(r.maxLength===void 0||f<=r.maxLength)}return Array.isArray(c)?c.length<=r.maxItems&&(r.minItems===void 0||c.length>=r.minItems)&&c.every(f=>i(r.items,f,s+1)):K(c)?!K(r.properties)||Object.keys(c).some(f=>Be.has(f)||!Object.hasOwn(r.properties,f))||(Array.isArray(r.required)?r.required:[]).some(f=>!Object.hasOwn(c,f))||r.minProperties!==void 0&&Object.keys(c).length<r.minProperties||r.maxProperties!==void 0&&Object.keys(c).length>r.maxProperties?!1:Object.entries(c).every(([f,u])=>i(r.properties[f],u,s+1)):c===null||typeof c=="boolean"};return i(e,t,0)}function ma(e){return typeof e=="string"&&e.length<=256&&e.split(".").length<=8&&e.split(".").every(t=>no.test(t)&&!Be.has(t))}function Ht(e){let t=0,o=(n,i)=>{if(!K(n)||i>6||++t>256||Object.keys(n).some(s=>!["type","title","description","properties","required","additionalProperties","items","maxItems","minItems","maxLength","minLength","minimum","maximum","enum","const","maxProperties","minProperties"].includes(s)))return!1;let r=Array.isArray(n.type)?n.type:[n.type];if(!r.length||r.length>2||r.some(s=>!["object","array","string","integer","number","boolean","null"].includes(s))||r.length>1&&(!r.includes("null")||new Set(r).size!==r.length))return!1;for(let s of["title","description"])if(n[s]!==void 0&&(typeof n[s]!="string"||n[s].length>2e3))return!1;for(let s of["minimum","maximum"])if(n[s]!==void 0&&(typeof n[s]!="number"||!Number.isFinite(n[s])))return!1;for(let[s,a]of[["maxItems",200],["minItems",200],["maxLength",16384],["minLength",16384],["maxProperties",32],["minProperties",32]])if(n[s]!==void 0&&(!Number.isSafeInteger(n[s])||n[s]<0||n[s]>a))return!1;for(let[s,a]of[["minimum","maximum"],["minItems","maxItems"],["minLength","maxLength"],["minProperties","maxProperties"]])if(n[s]!==void 0&&n[a]!==void 0&&n[s]>n[a])return!1;if(["properties","required","additionalProperties","maxProperties","minProperties"].some(s=>n[s]!==void 0)&&!r.includes("object")||["items","maxItems","minItems"].some(s=>n[s]!==void 0)&&!r.includes("array")||["maxLength","minLength"].some(s=>n[s]!==void 0)&&!r.includes("string")||["minimum","maximum"].some(s=>n[s]!==void 0)&&!r.some(s=>s==="integer"||s==="number")||n.enum!==void 0&&(!Array.isArray(n.enum)||!n.enum.length||n.enum.length>100)||r.includes("object")&&(!K(n.properties)||n.additionalProperties!==!1||Object.keys(n.properties).length>32||Object.keys(n.properties).some(s=>!ji.test(s)||Be.has(s))||n.required!==void 0&&(!Array.isArray(n.required)||new Set(n.required).size!==n.required.length||n.required.some(s=>typeof s!="string"||!Object.hasOwn(n.properties,s)))||n.minProperties!==void 0&&n.minProperties>Object.keys(n.properties).length||n.maxProperties!==void 0&&n.maxProperties<(n.required?.length||0)||!Object.values(n.properties).every(s=>o(s,i+1)))||r.includes("array")&&(!Number.isSafeInteger(n.maxItems)||!o(n.items,i+1)))return!1;let c={...n};return delete c.enum,delete c.const,!(n.enum!==void 0&&(!n.enum.every(s=>Jt(c,s))||n.enum.some((s,a)=>n.enum.slice(0,a).some(d=>ot(s,d))))||Object.hasOwn(n,"const")&&!Jt(c,n.const))};return K(e)&&e.type==="object"&&Wi(e)<=to&&o(e,0)}function Yt(e){let t=Object.fromEntries(Object.values(e.nodes||{}).filter(o=>o?.kind==="action").map(o=>[o.id,o.outputSchema]));return Object.keys(t).length?{...e.inputSchema,properties:{...e.inputSchema?.properties,steps:{type:"object",additionalProperties:!1,properties:t}}}:e.inputSchema||{}}function Ui(e,t){let o=e;for(let n of t.split(".")){if(!K(o?.properties)||!Object.hasOwn(o.properties,n))return;o=o.properties[n]}return K(o)?o:void 0}var Li=(e,t)=>!!Ui(e,t);function Cl(e){return K(e)&&Object.keys(e).every(t=>["version","mode","inputSchema","outputSchema"].includes(t))&&Number.isSafeInteger(e.version)&&e.version>=1&&e.version<=1e6&&["pure","reconciled-effect"].includes(e.mode)&&Ht(e.inputSchema)&&Ht(e.outputSchema)}function Fi(e){return e.kind==="approval"?[e.onApprove,e.onReject]:e.kind==="condition"?[...Array.isArray(e.branches)?e.branches.map(t=>t.target):[],e.otherwise]:e.kind==="cc"||e.kind==="action"?[e.next]:[]}function eo(e,t=0){return!K(e)||t>16?[]:e.op==="path"?typeof e.path=="string"?[e.path]:[]:["left","right","value"].flatMap(o=>eo(e[o],t+1)).concat(Array.isArray(e.values)?e.values.flatMap(o=>eo(o,t+1)):[])}function Xt(e,t){if(!K(e)||!K(e.nodes))return["WORKFLOW_STEP_DEFINITION_INVALID"];let o=e.nodes,n=Object.entries(o).filter(([,s])=>s?.kind==="action");if(!n.length)return[];let i=[];Object.hasOwn(e.inputSchema?.properties||{},"steps")&&i.push("WORKFLOW_STEP_FACT_NAMESPACE_RESERVED");let r=Yt(e);for(let[s,a]of n){(Object.keys(a).some(u=>!["id","kind","title","next","handler","inputSchema","outputSchema","inputs"].includes(u))||a.id!==s||!no.test(s)||Be.has(s)||typeof a.title!="string"||!a.title.trim()||a.title.length>255||typeof a.next!="string"||!Object.hasOwn(o,a.next))&&i.push(`WORKFLOW_STEP_NODE_INVALID:${s}`);let d=a.handler;(!K(d)||Object.keys(d).some(u=>!["code","version","mode"].includes(u))||!Number.isSafeInteger(d.version)||d.version<1||d.version>1e6||!/^[a-z][a-z0-9-]{0,100}$/.test(d.code||"")||!String(d.code).endsWith(`-v${d.version}`)||!["pure","reconciled-effect"].includes(d.mode))&&i.push(`WORKFLOW_STEP_HANDLER_INVALID:${s}`);let f=Ht(a.inputSchema);if((!f||!Ht(a.outputSchema))&&i.push(`WORKFLOW_STEP_SCHEMA_INVALID:${s}`),!K(a.inputs)||Object.keys(a.inputs).length>32){i.push(`WORKFLOW_STEP_INPUTS_INVALID:${s}`);continue}for(let u of Array.isArray(a.inputSchema?.required)?a.inputSchema.required:[])Object.hasOwn(a.inputs,u)||i.push(`WORKFLOW_STEP_INPUT_REQUIRED:${s}:${u}`);for(let[u,p]of Object.entries(a.inputs)){if(!ji.test(u)||Be.has(u)||!Object.hasOwn(a.inputSchema?.properties||{},u)||!K(p)){i.push(`WORKFLOW_STEP_INPUT_INVALID:${s}:${u}`);continue}if(p.source==="literal")(!f||Object.keys(p).some(g=>!["source","value"].includes(g))||!Object.hasOwn(p,"value")||!Jt(a.inputSchema.properties[u],p.value))&&i.push(`WORKFLOW_STEP_LITERAL_INVALID:${s}:${u}`);else if(p.source!=="fact"||Object.keys(p).some(g=>!["source","path"].includes(g))||!ma(p.path)||!Li(r,p.path))i.push(`WORKFLOW_STEP_FACT_PATH_INVALID:${s}:${u}`);else if(f){let g=Ui(r,p.path),I=a.inputSchema.properties[u],A=Array.isArray(g.type)?g.type:[g.type],O=Array.isArray(I.type)?I.type:[I.type];A.some(b=>!O.includes(b)&&!(b==="integer"&&O.includes("number")))&&i.push(`WORKFLOW_STEP_FACT_TYPE_MISMATCH:${s}:${u}`)}}}let c=(s,a)=>{let d=new Set,f=[e.startAt||""];for(;f.length&&d.size<=200;){let u=f.shift();if(!(u===a||d.has(u)||!o[u])){if(u===s)return!0;d.add(u),f.push(...Fi(o[u]))}}return!1};for(let[s,a]of Object.entries(o)){if(!K(a))continue;let d=a.kind==="action"?Object.values(a.inputs||{}).flatMap(u=>u?.source==="fact"?[u.path]:[]):(Array.isArray(a.branches)?a.branches:[]).flatMap(u=>eo(u?.when)),f=t?.bindings?.[a.binding];f&&d.push(...[f.inputPath,f.departmentIdFrom,f.resourceIdFrom,f.scope?.valueFrom].filter(u=>typeof u=="string"));for(let u of d.filter(p=>typeof p=="string"&&p.startsWith("steps."))){let p=u.split(".")[1];(o[p]?.kind!=="action"||p===s||!Li(r,u)||c(s,p))&&i.push(`WORKFLOW_STEP_OUTPUT_NOT_AVAILABLE:${s}:${u}`)}}if(t)for(let[,s]of n){let a=new Set,d=[s.next];for(;d.length&&a.size<=200;){let f=d.shift();if(a.has(f)||!K(o[f]))continue;a.add(f);let u=o[f];if(!(u.kind==="action"||u.kind==="end")){if(u.kind==="approval"){let p=t.bindings?.[u.binding];p&&["application_provider","initiator_select"].includes(p.provider)&&i.push(`WORKFLOW_STEP_NEXT_PROVIDER_REQUIRES_PREPARED_RESULT:${f}`);continue}d.push(...Fi(u))}}}return[...new Set(i)]}function hl(e,t){let o={};for(let[n,i]of Object.entries(e.inputs)){let r=i.source==="literal"?i.value:i.path.split(".").reduce((c,s)=>K(c)&&Object.hasOwn(c,s)?c[s]:void 0,t);r!==void 0&&(o[n]=r)}if(!Jt(e.inputSchema,o))throw new Error("WORKFLOW_STEP_INPUT_SCHEMA_INVALID");return o}function Mi(e,t,o){let n=oo(e),i=[];Object.keys(n).length&&!o&&i.push("WORKFLOW_STEP_BACKEND_REQUIRED");for(let r of Object.keys(n)){let c=t.find(s=>s.code===r);(!c||c.execution||c.action||!Array.isArray(c.eventTypes)||c.eventTypes.length!==1||c.eventTypes[0]!==It||!K(c.filter)||Object.keys(c.filter).length!==1||!K(c.filter.workflowStep)||Object.keys(c.filter.workflowStep).length!==1||c.filter.workflowStep.handlerCode!==r||!K(c.payload)||c.payload.includeChanges!==!1||!Array.isArray(c.payload.fields)||c.payload.fields.length)&&i.push(`WORKFLOW_STEP_SUBSCRIPTION_INVALID:${r}`)}for(let r of t)(r.eventTypes?.includes(It)&&!n[r.code]||r.filter?.workflowStep&&!n[r.code])&&i.push(`WORKFLOW_STEP_HANDLER_NOT_DECLARED:${r.code}`);return i}function oo(e){let t={};for(let o of e){let n=Xt(o);if(n.length)throw new Error(n.join("; "));for(let i of Object.values(o.nodes||{})){if(i.kind!=="action")continue;let r={version:i.handler.version,mode:i.handler.mode,inputSchema:i.inputSchema,outputSchema:i.outputSchema},c=t[i.handler.code];if(c&&!ot(c,r))throw new Error(`WORKFLOW_STEP_HANDLER_CONTRACT_CONFLICT:${i.handler.code}`);t[i.handler.code]=r}}return t}var fe=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},Ke=(e,t)=>typeof e=="string"&&!!e.trim()&&e.length<=t,_a=/^[A-Za-z][A-Za-z0-9_-]*(?:\.[A-Za-z][A-Za-z0-9_-]*){0,15}$/,io=e=>typeof e=="string"&&e.length<=256&&_a.test(e)&&!e.split(".").some(t=>["__proto__","prototype","constructor"].includes(t));function Qt(e,t){let o=fe(e),n=!0;for(let i of t.split(".")){n&&=Array.isArray(o.required)&&o.required.includes(i);let r=fe(o.properties)[i];if(!r||typeof r!="object")return null;o=fe(r)}return{schema:o,required:n}}function Bi(e){let t=new Set,o=[],n=2048,i=(r,c)=>{if(--n<0||c>20){o.push("WORKFLOW_EXPRESSION_BUDGET_EXCEEDED");return}let s=fe(r);if(s.op==="path")io(s.path)?t.add(s.path):o.push("WORKFLOW_EXPRESSION_PATH_INVALID");else{if(s.op==="literal")return;if(s.op==="and"||s.op==="or")if(!Array.isArray(s.values)||!s.values.length||s.values.length>128)o.push("WORKFLOW_EXPRESSION_GROUP_INVALID");else for(let a of s.values){if(n<0)break;i(a,c+1)}else s.op==="not"||s.op==="exists"?i(s.value,c+1):["eq","neq","gt","gte","lt","lte","in","contains"].includes(String(s.op))?(i(s.left,c+1),i(s.right,c+1)):o.push("WORKFLOW_EXPRESSION_OPERATOR_INVALID")}};return i(e,0),{paths:[...t],errors:[...new Set(o)]}}function Ki(e){if(e?.readability===void 0)return[];let t=[],o=Yt(e),n=fe(e.readability);(Object.keys(n).some(s=>!["variables","logic"].includes(s))||!Object.keys(n).length)&&t.push("WORKFLOW_READABILITY_INVALID");let i=fe(n.variables);n.variables!==void 0&&(typeof n.variables!="object"||Array.isArray(n.variables)||n.variables===null)&&t.push("WORKFLOW_VARIABLES_INVALID"),Object.keys(i).length>128&&t.push("WORKFLOW_VARIABLE_LIMIT_EXCEEDED");for(let[s,a]of Object.entries(i)){let d=fe(a);(!io(s)||!Qt(o,s))&&t.push(`WORKFLOW_VARIABLE_SOURCE_UNKNOWN:${s}`),(!Ke(d.label,160)||Object.keys(d).some(f=>!["label","unit","description"].includes(f))||d.unit!==void 0&&!Ke(d.unit,32)||d.description!==void 0&&!Ke(d.description,2e3))&&t.push(`WORKFLOW_VARIABLE_METADATA_INVALID:${s}`)}let r=n.logic===void 0?[]:n.logic;(!Array.isArray(r)||r.length>32)&&t.push("WORKFLOW_LOGIC_LIMIT_INVALID");let c=new Set;for(let s of Array.isArray(r)?r.slice(0,32):[]){let a=fe(s),d=String(a.code||"");e.approvedDelegation&&d==="kernel-approved-delegation"&&t.push("WORKFLOW_LOGIC_PLATFORM_CODE_RESERVED"),(!/^[a-z][a-z0-9-]{2,63}$/.test(d)||c.has(d)||!Ke(a.title,160)||!Ke(a.description,4e3)||Object.keys(a).some(f=>!["code","title","description","phase","nodeId","inputPaths","outputPaths","source"].includes(f)))&&t.push(`WORKFLOW_LOGIC_METADATA_INVALID:${d}`),c.add(d),(!["submission","node_input","completion"].includes(String(a.phase))||a.phase==="node_input"&&!fe(e.nodes)[String(a.nodeId)]||a.phase!=="node_input"&&a.nodeId!==void 0)&&t.push(`WORKFLOW_LOGIC_ANCHOR_INVALID:${d}`);for(let f of["inputPaths","outputPaths"]){let u=a[f];if(!(f==="outputPaths"&&u===void 0))if(!Array.isArray(u)||u.length>32||new Set(u).size!==u.length)t.push(`WORKFLOW_LOGIC_PATHS_INVALID:${d}:${f}`);else for(let p of u)(!io(p)||!Qt(o,p))&&t.push(`WORKFLOW_LOGIC_SOURCE_UNKNOWN:${d}:${String(p)}`)}if(a.source!==void 0){let f=fe(a.source);(!Ke(f.path,256)||String(f.path).startsWith("/")||String(f.path).includes("..")||String(f.path).includes("://")||!/^sha256:[a-f0-9]{64}$/.test(String(f.digest))||f.symbol!==void 0&&!Ke(f.symbol,160)||Object.keys(f).some(u=>!["path","symbol","digest"].includes(u)))&&t.push(`WORKFLOW_LOGIC_SOURCE_REFERENCE_INVALID:${d}`)}}for(let s of Object.values(fe(e.nodes))){let a=fe(s),d=Array.isArray(a.branches)?a.branches:[];for(let f of d){let u=Bi(f.when);t.push(...u.errors.map(p=>`${p}:${a.id}`));for(let p of u.paths)Qt(o,p)||t.push(`WORKFLOW_VARIABLE_SOURCE_UNKNOWN:${a.id}:${p}`)}}return[...new Set(t)]}function Dl(e,t){let o=Yt(e),n=[],i=new Map,r=[];for(let d of Object.values(e.nodes)){if(d.kind==="approval")for(let[f,u,p]of[["approve",d.onApprove,"\u540C\u610F"],["reject",d.onReject,"\u62D2\u7EDD"]])u&&n.push({id:`${d.id}:${f}`,from:d.id,to:u,kind:f,label:p,variablePaths:[]});if(d.kind==="approval")for(let f of new Set(d.returnTargets||[]))e.nodes[f]?.kind==="correction"&&n.push({id:`${d.id}:return:${f}`,from:d.id,to:f,kind:"return",label:"\u9000\u56DE\u53D1\u8D77\u4EBA\u8865\u6B63",variablePaths:[]});if(d.kind==="correction"&&d.next&&n.push({id:`${d.id}:resubmit`,from:d.id,to:d.next,kind:"resubmit",label:"\u91CD\u65B0\u63D0\u4EA4\uFF0C\u4ECE\u8D77\u70B9\u91CD\u7B97",variablePaths:[]}),d.kind==="cc"&&d.next&&n.push({id:`${d.id}:next`,from:d.id,to:d.next,kind:"next",label:"\u6284\u9001\u540E\u7EE7\u7EED",variablePaths:[]}),d.kind==="action"&&d.next){let f=Object.values(d.inputs||{}).flatMap(u=>u.source==="fact"?[u.path]:[]);for(let u of f)i.has(u)||i.set(u,new Set),i.get(u).add(d.id);n.push({id:`${d.id}:next`,from:d.id,to:d.next,kind:"next",label:"\u6210\u529F\u56DE\u6267\u540E\u7EE7\u7EED",variablePaths:f})}if(d.kind==="condition"){for(let[f,u]of(d.branches||[]).entries()){let p=Bi(u.when);for(let g of p.paths)i.has(g)||i.set(g,new Set),i.get(g).add(d.id);n.push({id:`${d.id}:branch:${f}`,from:d.id,to:u.target,kind:"branch",label:u.label||`\u6761\u4EF6 ${f+1}`,priority:f+1,expression:u.when,variablePaths:p.paths}),r.push(...p.errors.map(g=>({code:g,path:d.id})))}d.otherwise&&n.push({id:`${d.id}:default`,from:d.id,to:d.otherwise,kind:"default",label:"\u5747\u4E0D\u6EE1\u8DB3\u65F6",variablePaths:[]})}}let c=[...e.readability?.logic||[]];if(e.approvedDelegation){let d=e.approvedDelegation,f=d.confirmer==="initiator"?"\u7533\u8BF7\u4EBA\u672C\u4EBA":"\u6240\u9009\u4EE3\u7406\u4EBA";c.push({code:"kernel-approved-delegation",title:"\u6279\u51C6\u540E\u6574\u6279\u6388\u6743\u4EE3\u7406",phase:"completion",inputPaths:[d.requestsField],description:`\u6279\u51C6\u65F6\u6838\u9A8C${f}\u5728\u5F53\u524D\u9000\u56DE\u5468\u671F\u5B8C\u6210\u201C${e.nodes[d.confirmationNodeId]?.title||d.confirmationNodeId}\u201D\u7684\u4EBA\u5DE5\u786E\u8BA4\uFF1B\u968F\u540E\u91CD\u65B0\u6838\u9A8C\u53CC\u65B9\u5F53\u524D\u8D26\u53F7\u3001\u804C\u8D23\u3001\u4FEE\u8BA2\u3001\u8303\u56F4\u4E0E\u5B8C\u6574\u6709\u6548\u671F\uFF0C\u6574\u6279\u6388\u6743\uFF08\u6700\u591A${d.maxRequests}\u884C\uFF09\u3002\u4EFB\u4E00\u884C\u5931\u8D25\uFF0C\u6279\u51C6\u4E0E\u5168\u90E8\u6388\u6743\u4E00\u8D77\u56DE\u6EDA\uFF1B\u539F\u547D\u4EE4\u6062\u590D\u4E0D\u91CD\u65B0\u6FC0\u6D3B\u5DF2\u64A4\u9500\u6388\u6743\u3002`})}let a=[...new Set([...i.keys(),...Object.keys(e.readability?.variables||{}),...c.flatMap(d=>[...d.inputPaths,...d.outputPaths||[]])])].slice(0,128).map(d=>{let f=Qt(o,d),u=e.readability?.variables?.[d],p=d.split("."),g=e.subject?.factProjection[p[0]],I=p[0]==="steps"?e.nodes[p[1]]:void 0;return f||r.push({code:"WORKFLOW_VARIABLE_SOURCE_UNKNOWN",path:d}),{path:d,label:u?.label||String(f?.schema.title||d),type:String(f?.schema.type||"unknown"),...u,required:f?.required||!1,usedBy:[...i.get(d)||[]],source:f&&I?.handler?{kind:"step_output",nodeId:I.id,handlerCode:I.handler.code,handlerVersion:I.handler.version}:f&&g&&e.subject?{kind:"subject_field",resourceCode:e.subject.resourceCode,fieldPath:[g,...p.slice(1)].join(".")}:{kind:f?"input":"unknown"}}});return{schemaVersion:"openxiangda.workflow-graph/v2",workflowCode:e.code,definitionDigest:t,startAt:e.startAt,fixedTopology:!0,branchStrategy:"first_match",nodes:Object.values(e.nodes).map(d=>({id:d.id,kind:d.kind,title:d.title||d.id,...d.binding?{binding:d.binding}:{},...d.mode?{mode:d.mode}:{},...d.outcome?{outcome:d.outcome}:{},...d.kind==="cc"?{emptyPolicy:d.emptyPolicy,notify:d.notify!==!1}:{},...d.kind==="approval"?{emptyPolicy:d.emptyPolicy||"block",initiatorApprovalPolicy:d.initiatorApprovalPolicy||"manual",...d.completionDeadline?{completionDeadline:{...d.completionDeadline}}:{}}:{},...d.kind==="action"&&d.handler?{businessStep:{handler:d.handler,inputs:d.inputs||{},outputPaths:Object.keys(fe(d.outputSchema).properties||{}).map(f=>`steps.${d.id}.${f}`)}}:{}})),edges:n,variables:a,logic:c,diagnostics:r}}function Zt(e,t=[],o=0){if(!e||o>20)return"\u65E0\u6CD5\u8BC6\u522B\u7684\u6761\u4EF6";if(e.op==="path")return t.find(c=>c.path===e.path)?.label||e.path;if(e.op==="literal")return JSON.stringify(e.value)??"\u7F3A\u503C";if(e.op==="and"||e.op==="or")return e.values.slice(0,128).map(c=>`\uFF08${Zt(c,t,o+1)}\uFF09`).join(e.op==="and"?" \u4E14 ":" \u6216 ");if(e.op==="not"||e.op==="exists")return`${e.op==="not"?"\u4E0D\u6EE1\u8DB3":"\u5B58\u5728"}\uFF08${Zt(e.value,t,o+1)}\uFF09`;if(!("left"in e))return"\u65E0\u6CD5\u8BC6\u522B\u7684\u6761\u4EF6";let n={eq:"=",neq:"\u2260",gt:">",gte:"\u2265",lt:"<",lte:"\u2264",in:"\u5C5E\u4E8E",contains:"\u5305\u542B"},i=e.left.op==="path"?e.left.path:void 0,r=i&&e.right.op==="literal"&&typeof e.right.value=="number"?t.find(c=>c.path===i)?.unit:void 0;return`${Zt(e.left,t,o+1)} ${n[e.op]} ${Zt(e.right,t,o+1)}${r?` ${r}`:""}`}function Gi(e,t=0){return!Array.isArray(e)||e.length>64||t>1?!1:e.every(o=>{if(!o||typeof o!="object"||Array.isArray(o)||o.readonlyWhen!==void 0)return!1;if(o.subtable!==void 0){let n=o.subtable;return n&&n.create===!1&&n.delete===!1&&n.reorder===!1&&Gi(n.fields,t+1)}return o.readonly===!0})}function yt(e){let t=[];for(let[o,n]of Object.entries(e?.nodes||{}))if(n.initiatorApprovalPolicy!==void 0){if(n.kind!=="approval"||!["manual","auto_approve"].includes(n.initiatorApprovalPolicy)){t.push(`WORKFLOW_INITIATOR_APPROVAL_POLICY_INVALID:${o}`);continue}n.initiatorApprovalPolicy==="auto_approve"&&((n.taskPageCode!==void 0&&(typeof n.taskPageCode!="string"||!Gi(e.taskPages?.[n.taskPageCode]?.fields))||[n.fieldPolicy?.default,...Object.values(n.fieldPolicy?.fields||{})].some(i=>i==="edit"||i==="edit_required"))&&t.push(`WORKFLOW_INITIATOR_APPROVAL_INPUT_REQUIRED:${o}`),n.operationPolicy?.approve?.commentRequired===!0&&t.push(`WORKFLOW_INITIATOR_APPROVAL_COMMENT_REQUIRED:${o}`))}return t}function $l(e,t,o,n,i){return e.kind==="approval"&&e.initiatorApprovalPolicy==="auto_approve"&&yt({nodes:{node:e},...i?{taskPages:i}:{}}).length===0&&t!=="return_review"&&!!o&&n.user_id===o&&n.status==="active"&&n.participant_kind==="primary"&&["resolution","resolution_retry"].includes(n.source||"")&&!n.source_participant_id&&!n.delegate_authorization_id}var Pl=8,Vl={type:"array",minItems:2,maxItems:8,uniqueItems:!0,items:{type:"string",maxLength:128,pattern:"^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$"}};function en(e){if(e.roleCodes===void 0)return[];let t=e.roleCodes;if(!["app_role","app_role_in_scope"].includes(e.provider||"")||e.roleCode!==void 0||e.candidateField!==void 0||!Array.isArray(t)||t.length<2||t.length>8||new Set(t).size!==t.length||t.some(o=>typeof o!="string"||o.length>128||!/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/.test(o)))return["WORKFLOW_V2_BINDING_ROLE_UNION_INVALID"];if(e.provider==="app_role_in_scope"){let o=e.scope,n=typeof o?.value=="string"&&o.value.length>0&&o.value.length<=255&&o.valueFrom===void 0,i=typeof o?.valueFrom=="string"&&o.valueFrom.length<=255&&/^[A-Za-z][A-Za-z0-9_-]*(?:\.[A-Za-z][A-Za-z0-9_-]*)*$/.test(o.valueFrom)&&!o.valueFrom.split(".").some(r=>["__proto__","prototype","constructor"].includes(r))&&o.value===void 0;if(!o||typeof o!="object"||Array.isArray(o)||Object.keys(o).some(r=>!["dimension","value","valueFrom"].includes(r))||typeof o.dimension!="string"||!/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/.test(o.dimension)||!n&&!i)return["WORKFLOW_V2_BINDING_ROLE_UNION_SCOPE_INVALID"]}else if(e.scope!==void 0)return["WORKFLOW_V2_BINDING_ROLE_UNION_SCOPE_INVALID"];return[]}function Ll(e){return e.roleCodes?[...e.roleCodes]:e.roleCode?[e.roleCode]:[]}function qi(e){return e.some(t=>Object.values(t.binding.bindings).some(o=>o.roleCodes!==void 0))}var ro=["approve","reject","return","transfer","delegate","add_assignee"],so=["fixed_users","app_role","app_role_in_scope"],ga=["single","any","all","sequence"],Ve=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Ge=(e,t)=>Object.keys(e).every(o=>t.includes(o)),tn=(e,t,o)=>Array.isArray(e)&&e.length>0&&e.length<=o&&new Set(e).size===e.length&&e.every(n=>typeof n=="string"&&t.includes(n));function bt(e){return e.allowedOperations||[...ro]}function Aa(e,t){return t?.commentRequired??e==="reject"}function Ea(e,t){return!["transfer","delegate","add_assignee","return"].includes(e)||t?.reasonRequired!==!1}function Ji(e,t,o={},n=!1){return!(!Ve(e)||!Object.keys(e).length||!Ge(e,n?["enabled","label","commentRequired","reasonRequired"]:["label","commentRequired","reasonRequired"])||e.label!==void 0&&(typeof e.label!="string"||!e.label.trim()||e.label.length>40||/[\u0000-\u001f\u007f]/.test(e.label))||e.enabled!==void 0&&(typeof e.enabled!="boolean"||["approve","reject"].includes(t)&&!e.enabled)||e.commentRequired!==void 0&&(typeof e.commentRequired!="boolean"||!["approve","reject"].includes(t)||n&&Aa(t,o)&&!e.commentRequired)||e.reasonRequired!==void 0&&(typeof e.reasonRequired!="boolean"||!["transfer","delegate","add_assignee","return"].includes(t)||n&&Ea(t,o)&&!e.reasonRequired))}function ao(e,t){let o=[];for(let[n,i]of Object.entries(e?.nodes||{})){if(!Ve(i))continue;let r=i.administration,c=i.operationPolicy;if(i.kind==="cc"){(c!==void 0||r!==void 0&&(!Ve(r)||!Ge(r,["assigneeProviders"])))&&o.push(`WORKFLOW_NODE_ADMINISTRATION_INVALID:${n}`),r?.assigneeProviders!==void 0&&!tn(r.assigneeProviders,so,3)&&o.push(`WORKFLOW_NODE_ADMINISTRATION_PROVIDERS_INVALID:${n}`),r?.assigneeProviders?.includes("app_role_in_scope")&&t&&!t.bindings[i.binding||""]?.scope&&o.push(`WORKFLOW_NODE_ADMINISTRATION_SCOPE_REQUIRED:${n}`);continue}if(i.kind!=="approval"){(r!==void 0||c!==void 0)&&o.push(`WORKFLOW_NODE_ADMINISTRATION_APPROVAL_REQUIRED:${n}`);continue}if(c!==void 0&&(!Ve(c)||Object.keys(c).length>8||Object.entries(c).some(([a,d])=>!ro.includes(a)||!bt(i).includes(a)||!Ji(d,a)))&&o.push(`WORKFLOW_NODE_OPERATION_POLICY_INVALID:${n}`),r===void 0)continue;if(!Ve(r)||!Ge(r,["modes","assigneeProviders","operations"])){o.push(`WORKFLOW_NODE_ADMINISTRATION_INVALID:${n}`);continue}r.modes!==void 0&&(!tn(r.modes,ga,4)||!r.modes.includes(i.mode))&&o.push(`WORKFLOW_NODE_ADMINISTRATION_MODES_INVALID:${n}`),r.assigneeProviders!==void 0&&!tn(r.assigneeProviders,so,3)&&o.push(`WORKFLOW_NODE_ADMINISTRATION_PROVIDERS_INVALID:${n}`);let s=t?.bindings[i.binding||""];s&&Array.isArray(r.assigneeProviders)&&r.assigneeProviders.includes("app_role_in_scope")&&!s.scope&&o.push(`WORKFLOW_NODE_ADMINISTRATION_SCOPE_REQUIRED:${n}`),r.operations!==void 0&&(!tn(r.operations,ro,8)||r.operations.some(a=>!bt(i).includes(a)))&&o.push(`WORKFLOW_NODE_ADMINISTRATION_OPERATIONS_INVALID:${n}`)}return o}function Wl(e,t,o,n){let i=[];if(!e||!Ve(o)||!Object.keys(o).length||!Ge(o,["title","description","assignee","mode","operations"]))return["WORKFLOW_V2_NODE_CONFIGURATION_PATCH_INVALID"];let r=o;for(let s of["title","description"])r[s]!==void 0&&(typeof r[s]!="string"||r[s].length>(s==="title"?255:1e3)||s==="title"&&!r[s].trim())&&i.push("WORKFLOW_V2_NODE_CONFIGURATION_PATCH_INVALID");let c=e.administration;if(r.mode!==void 0&&(e.kind!=="approval"||!c?.modes?.includes(r.mode))&&i.push("WORKFLOW_V2_NODE_CONFIGURATION_MODE_READONLY"),r.operations!==void 0&&(e.kind!=="approval"||!Ve(r.operations)||!Object.keys(r.operations).length||Object.keys(r.operations).length>8||Object.entries(r.operations).some(([s,a])=>!c?.operations?.includes(s)||!bt(e).includes(s)||!Ji(a,s,e.operationPolicy?.[s],!0)))&&i.push("WORKFLOW_V2_NODE_CONFIGURATION_OPERATION_INVALID"),r.assignee!==void 0){let s=r.assignee,a=c?.assigneeProviders||(e.kind==="approval"&&t&&so.includes(t.provider)?[t.provider]:[]);!Ve(s)||!["approval","cc"].includes(e.kind)||!a.includes(s.provider)||s.provider==="app_role_in_scope"&&!t?.scope?i.push("WORKFLOW_V2_NODE_CONFIGURATION_PROVIDER_READONLY"):s.provider==="fixed_users"?(!Ge(s,["provider","users"])||!Array.isArray(s.users)||s.users.length<1&&!(e.kind==="approval"&&e.emptyPolicy==="skip")||s.users.length>(e.kind==="cc"?20:200)||new Set(s.users).size!==s.users.length||s.users.some(d=>typeof d!="string"||!d.trim()||d.length>255))&&i.push("WORKFLOW_V2_NODE_CONFIGURATION_USERS_INVALID"):s.roleCodes!==void 0?(!Ge(s,["provider","roleCodes"])||en({...s,...s.provider==="app_role_in_scope"?{scope:t?.scope}:{}}).length)&&i.push("WORKFLOW_V2_NODE_CONFIGURATION_ROLE_INVALID"):(!Ge(s,["provider","roleCode"])||typeof s.roleCode!="string"||!/^[a-z][a-z0-9_-]{0,127}$/.test(s.roleCode))&&i.push("WORKFLOW_V2_NODE_CONFIGURATION_ROLE_INVALID")}return i.push(...yt({nodes:{node:{...e,operationPolicy:zi(e,r).operationPolicy}},...n?{taskPages:n}:{}})),e.completionDeadline&&zi(e,r).operationPolicy.approve?.commentRequired===!0&&i.push("WORKFLOW_COMPLETION_DEADLINE_INPUT_REQUIRED:node"),i}function zi(e,t){let o=Object.fromEntries(bt(e).flatMap(n=>{let i=n,r=t?.operations?.[i],c={...e.operationPolicy?.[i],...r?.label!==void 0?{label:r.label}:{},...r?.commentRequired!==void 0?{commentRequired:r.commentRequired}:{},...r?.reasonRequired!==void 0?{reasonRequired:r.reasonRequired}:{}};return Object.keys(c).length?[[i,c]]:[]}));return{mode:t?.mode||e.mode,initiatorApprovalPolicy:e.initiatorApprovalPolicy||"manual",allowedOperations:bt(e).filter(n=>t?.operations?.[n]?.enabled!==!1),operationPolicy:o,fieldPolicy:{default:e.fieldPolicy?.default||"readonly",fields:{...e.fieldPolicy?.fields}}}}var Ml=20,Ia=["fixed_users","initiator","input_users","form_field_users","app_role","app_role_in_scope","previous_node_actor"];function co(e,t){let o=[];for(let[n,i]of Object.entries(e?.nodes||{})){if(i?.kind!=="cc"||((Object.keys(i).some(a=>!["id","kind","title","binding","next","emptyPolicy","notify","administration"].includes(a))||typeof i.title!="string"||!i.title.trim()||i.title.length>255||typeof i.binding!="string"||!i.binding.trim()||i.binding.length>255||typeof i.next!="string"||!i.next.trim()||!e.nodes?.[i.next]||!["block","skip"].includes(i.emptyPolicy)||i.notify!==void 0&&typeof i.notify!="boolean")&&o.push(`WORKFLOW_CC_NODE_INVALID:${n}`),!t))continue;let r=t.bindings?.[i.binding];if(!r){o.push(`WORKFLOW_CC_BINDING_NOT_FOUND:${n}`);continue}Ia.includes(r.provider)||o.push(`WORKFLOW_CC_PROVIDER_INVALID:${n}`);let c=r.min??1,s=r.max??20;(!Number.isSafeInteger(c)||!Number.isSafeInteger(s)||c<1||s<c||s>20||r.provider==="fixed_users"&&(!Array.isArray(r.users)||!r.users.length||r.users.length>s))&&o.push(`WORKFLOW_CC_RECIPIENT_LIMIT_INVALID:${n}`)}return[...new Set(o)]}var Hi=["fixed_users","input_users","form_field_users","app_role","app_role_in_scope"];function lo(e,t){let o=[];for(let[n,i]of Object.entries(e?.nodes||{}))i.kind==="cc"||i.emptyPolicy===void 0||(i.kind!=="approval"||!["block","skip"].includes(i.emptyPolicy)?o.push(`WORKFLOW_APPROVAL_EMPTY_POLICY_INVALID:${n}`):i.emptyPolicy==="skip"&&t&&!Hi.includes(t.bindings?.[i.binding||""]?.provider)&&o.push(`WORKFLOW_APPROVAL_EMPTY_PROVIDER_UNSUPPORTED:${n}`));return o}function Kl(e,t){return e.kind==="approval"&&e.emptyPolicy==="skip"&&t?.emptyResult==="no_candidates"&&Hi.includes(t.provider)&&Array.isArray(t.candidates)&&t.candidates.length===0&&Array.isArray(t.selected)&&t.selected.length===0&&Array.isArray(t.warnings)&&t.warnings.length===0}function Yi(e,t){let o=Object.values(e.nodes||{}).filter(n=>n.binding===t);return o.length>0&&o.every(n=>n.kind==="approval"&&n.emptyPolicy==="skip")}function Xi(e,t=0){return!Array.isArray(e)||e.length>64||t>1?!0:e.some(o=>!o||typeof o!="object"||Array.isArray(o)||o.required===!0||o.requiredWhen!==void 0||o.subtable!==void 0&&(!o.subtable||Xi(o.subtable.fields,t+1)))}function ql(e){let t=e.afterSeconds;return`\u8FDB\u5165\u540E ${t%86400===0?`${t/86400} \u5929`:t%3600===0?`${t/3600} \u5C0F\u65F6`:t%60===0?`${t/60} \u5206\u949F`:`${t} \u79D2`}\u672A\u5B8C\u6210\uFF0C\u81EA\u52A8\u540C\u610F`}function Zi(e){let t=[];for(let[o,n]of Object.entries(e?.nodes||{})){if(!n||typeof n!="object"||n.completionDeadline===void 0)continue;let i=n.completionDeadline;if(n.kind!=="approval"||!i||typeof i!="object"||Array.isArray(i)||Object.keys(i).length!==2||Object.keys(i).some(c=>!["afterSeconds","action"].includes(c))||i.action!=="approve"||!Number.isInteger(i.afterSeconds)||i.afterSeconds<1||i.afterSeconds>2592e3){t.push(`WORKFLOW_COMPLETION_DEADLINE_INVALID:${o}`);continue}n.allowedOperations&&!n.allowedOperations.includes("approve")&&t.push(`WORKFLOW_COMPLETION_DEADLINE_APPROVE_UNAVAILABLE:${o}`);let r=n.taskPageCode?e.taskPages?.[n.taskPageCode]:void 0;(n.taskPageCode&&(!r||Xi(r.fields))||[n.fieldPolicy?.default,...Object.values(n.fieldPolicy?.fields||{})].includes("edit_required")||n.operationPolicy?.approve?.commentRequired===!0||e.commandHandlers?.approve!==void 0)&&t.push(`WORKFLOW_COMPLETION_DEADLINE_INPUT_REQUIRED:${o}`)}return t}var ya="openxiangda.workflow-rejection-notification/v1",Jl=4096;function Qi(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function it(e,t){return typeof e=="string"&&e.trim().length>0&&e.length<=t}function uo(e,t){return Object.keys(e).sort().join(",")===t.sort().join(",")}function er(e){let t=e?.rejectionNotification;return t===void 0?[]:!Qi(t)||!uo(t,["recipient","title","summary"])||t.recipient!=="record_last_modifier"||!it(t.title,160)||!it(t.summary,500)?["WORKFLOW_REJECTION_NOTIFICATION_INVALID"]:it(e.subject?.resourceCode,63)?[]:["WORKFLOW_REJECTION_NOTIFICATION_SUBJECT_REQUIRED"]}function Hl(e){if(!Qi(e)||e.schemaVersion!==ya||e.recipient!=="record_last_modifier"||!it(e.title,160)||!it(e.summary,500))return!1;let t=["schemaVersion","recipient","title","summary","status","sourceRevision"];if(e.status==="ready"){if(!uo(e,[...t,"userId"])||!it(e.userId,255)||!Number.isSafeInteger(e.sourceRevision)||Number(e.sourceRevision)<1)return!1}else if(e.status==="skipped"){if(!uo(e,[...t,"reason"])||!["record_missing","modifier_missing","modifier_ineligible"].includes(String(e.reason))||(e.reason==="record_missing"?e.sourceRevision!==null:!Number.isSafeInteger(e.sourceRevision)||Number(e.sourceRevision)<1))return!1}else return!1;return new TextEncoder().encode(JSON.stringify(e)).byteLength<=4096}function tr(e,t){let o=e.commandHandlers;if(o===void 0)return[];if(!o||typeof o!="object"||Array.isArray(o)||!Object.keys(o).length||Object.keys(o).some(i=>!["approve","reject","withdraw","resubmit"].includes(i)))return["WORKFLOW_BUSINESS_COMMAND_HANDLERS_INVALID"];let n=[];o.resubmit&&!Object.values(e.nodes||{}).some(i=>i.kind==="correction")&&n.push("WORKFLOW_BUSINESS_CORRECTION_REQUIRED");for(let[i,r]of Object.entries(o)){if(!r||typeof r!="object"||Array.isArray(r)||Object.keys(r).join(",")!=="operationCode"||!/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/.test(r.operationCode||"")){n.push("WORKFLOW_BUSINESS_COMMAND_HANDLER_INVALID");continue}if(!t)continue;let c=t.find(s=>s.code===r.operationCode);if(!c){n.push("WORKFLOW_BUSINESS_COMMAND_OPERATION_MISSING");continue}(c.method!=="POST"||c.browser?.exposure!=="authenticated"||c.browser.behavior!=="controlled"||c.browser.idempotency!=="required"||c.browser.fileIntent||c.browser.subject?.resourceCode!==e.subject?.resourceCode||c.browser.subject?.inputField!=="recordId"||!c.platformAccess?.workflow?.codes?.includes(e.code)||!c.platformAccess.workflow.businessCommands?.includes(i))&&n.push("WORKFLOW_BUSINESS_COMMAND_OPERATION_INVALID")}return["approve","reject","withdraw"].some(i=>Object.hasOwn(o,i))&&Object.values(e.nodes||{}).some(i=>i.kind==="approval"&&(i.emptyPolicy==="skip"||i.initiatorApprovalPolicy==="auto_approve"))&&n.push("WORKFLOW_BUSINESS_COMMAND_AUTOMATIC_DECISION_FORBIDDEN"),[...new Set(n)]}var Xl={type:"object",additionalProperties:!1,required:["workflowCode","target","recordId","expectedRevision","commandToken","idempotencyKey","input"],properties:{workflowCode:{type:"string",pattern:"^[A-Za-z][A-Za-z0-9_-]{0,127}$"},target:{oneOf:[{type:"object",additionalProperties:!1,required:["kind","id","command"],properties:{kind:{const:"task"},id:{type:"string",format:"uuid"},command:{enum:["approve","reject","resubmit"]}}},{type:"object",additionalProperties:!1,required:["kind","id","command"],properties:{kind:{const:"instance"},id:{type:"string",format:"uuid"},command:{const:"withdraw"}}}]},recordId:{type:"string",format:"uuid"},expectedRevision:{type:"integer",minimum:1},commandToken:{type:"string",pattern:"^[A-Za-z0-9_-]{43}$"},idempotencyKey:{type:"string",minLength:1,maxLength:128},input:{type:"object",maxProperties:64}}};var ba=["fixed_users","initiator","app_role","app_role_in_scope"],Oa=e=>!!e&&typeof e=="object"&&!Array.isArray(e);function fo(e,t){let o=e?.launchPreflight;if(o===void 0)return[];if(!Oa(o)||Object.keys(o).join(",")!=="requiredApprovalNodes"||!Array.isArray(o.requiredApprovalNodes)||o.requiredApprovalNodes.length<1||o.requiredApprovalNodes.length>20||new Set(o.requiredApprovalNodes).size!==o.requiredApprovalNodes.length||o.requiredApprovalNodes.some(i=>typeof i!="string"||!/^[A-Za-z][A-Za-z0-9_-]{0,127}$/.test(i)))return["WORKFLOW_LAUNCH_PREFLIGHT_INVALID"];let n=[];for(let i of o.requiredApprovalNodes){let r=e.nodes?.[i];if(!r||r.kind!=="approval"){n.push(`WORKFLOW_LAUNCH_PREFLIGHT_NODE_INVALID:${i}`);continue}if(!t)continue;let c=t.bindings?.[r.binding||""];(!c||!ba.includes(c.provider)||c.candidateField!==void 0)&&n.push(`WORKFLOW_LAUNCH_PREFLIGHT_PROVIDER_UNSUPPORTED:${i}`)}return n}var po=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Na=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,or=/^[A-Za-z][A-Za-z0-9_-]{0,127}$/,nr=/^membership:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,eu=500,tu=262144;function ir(e){if(e?.approvedDelegation===void 0)return[];let t=e.approvedDelegation;if(!po(t)||Object.keys(t).some(a=>!["confirmationNodeId","confirmer","requestsField","maxRequests"].includes(a))||!or.test(t.confirmationNodeId||"")||!["initiator","delegate"].includes(t.confirmer)||!Na.test(t.requestsField||"")||!Number.isSafeInteger(t.maxRequests)||t.maxRequests<1||t.maxRequests>500)return["WORKFLOW_APPROVED_DELEGATION_POLICY_INVALID"];let o=[],n=e.nodes?.[t.confirmationNodeId];(!n||n.kind!=="approval"||n.mode!=="single"||n.emptyPolicy==="skip"||n.initiatorApprovalPolicy==="auto_approve"||n.completionDeadline||n.administration?.assigneeProviders?.length||n.administration?.modes?.some(a=>a!=="single")||n.allowedOperations?.some(a=>["transfer","delegate","add_assignee","admin_override"].includes(a)))&&o.push("WORKFLOW_APPROVED_DELEGATION_CONFIRMATION_INVALID");let i=e.inputSchema?.properties?.[t.requestsField];(!i||i.type!=="array"||!Number.isSafeInteger(i.maxItems)||i.maxItems<1||i.maxItems>t.maxRequests||!i.items||i.items.type!=="object"||i.items.additionalProperties!==!1||!e.subject?.factProjection?.[t.requestsField])&&o.push("WORKFLOW_APPROVED_DELEGATION_REQUEST_SCHEMA_INVALID"),Object.values(e.nodes||{}).some(a=>a.kind==="end"&&a.outcome==="approved")||o.push("WORKFLOW_APPROVED_DELEGATION_APPROVED_END_REQUIRED");let c=[e.startAt],s=new Set;for(;c.length;){let a=c.pop();if(a===t.confirmationNodeId||s.has(a))continue;s.add(a);let d=e.nodes?.[a];d&&(d.kind==="end"&&d.outcome==="approved"&&o.push("WORKFLOW_APPROVED_DELEGATION_CONFIRMATION_BYPASS"),d.kind==="approval"&&c.push(d.onApprove,d.onReject),d.kind==="condition"&&c.push(d.otherwise,...(d.branches||[]).map(f=>f.target)),(d.kind==="cc"||d.kind==="action")&&c.push(d.next))}return[...new Set(o)]}function nu(e,t){let o=t?.data?.[e.requestsField],n=()=>{throw new Error("WORKFLOW_APPROVED_DELEGATION_REQUEST_INVALID")};(!Array.isArray(o)||!o.length||o.length>e.maxRequests||o.length>500||new TextEncoder().encode(JSON.stringify(o)).byteLength>262144)&&n();let i=["key","delegatorRoleSubjectKey","delegatorRoleSubjectRevision","delegate","delegateRoleSubjectKey","expectedDelegateRevision","workflowCode","nodeId","validFrom","validTo","reason"],r=(a,d)=>typeof a=="string"&&a.trim().length>0&&a.length<=d,c=a=>{if(typeof a!="string")return!1;let d=/^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)(?:\.\d{1,3})?(?:Z|[+-](\d\d):(\d\d))$/.exec(a);if(!d)return!1;let[,f,u,p,g,I,A,O,b]=d,_=Number(f),E=Number(u),T=Number(p),y=[31,_%4===0&&(_%100!==0||_%400===0)?29:28,31,30,31,30,31,31,30,31,30,31];return E>=1&&E<=12&&T>=1&&T<=y[E-1]&&Number(g)<=23&&Number(I)<=59&&Number(A)<=59&&(O===void 0||Number(O)<=23&&Number(b)<=59)&&Number.isFinite(Date.parse(a))},s=o.map(a=>po(a)?((Object.keys(a).some(d=>!i.includes(d))||!r(a.delegatorRoleSubjectKey,255)||!nr.test(a.delegatorRoleSubjectKey)||!r(a.delegateRoleSubjectKey,255)||!nr.test(a.delegateRoleSubjectKey)||!Number.isSafeInteger(a.delegatorRoleSubjectRevision)||a.delegatorRoleSubjectRevision<1||!Number.isSafeInteger(a.expectedDelegateRevision)||a.expectedDelegateRevision<1||!po(a.delegate)||Object.keys(a.delegate).some(d=>!["value","label"].includes(d))||!r(a.delegate.value,255)||!r(a.delegate.label,200)||!(a.workflowCode===null||r(a.workflowCode,128)&&or.test(a.workflowCode))||!(a.nodeId===null||r(a.nodeId,128)&&/^[A-Za-z0-9._:-]{1,128}$/.test(a.nodeId)&&a.workflowCode)||!c(a.validFrom)||!c(a.validTo)||Date.parse(a.validFrom)>=Date.parse(a.validTo)||!r(a.reason,4e3)||a.key!==void 0&&!r(a.key,128))&&n(),{...a,delegate:{value:a.delegate.value,label:a.delegate.label},validFrom:new Date(a.validFrom).toISOString(),validTo:new Date(a.validTo).toISOString()}):n());return e.confirmer==="delegate"&&new Set(s.map(a=>a.delegate.value)).size!==1&&n(),s}var Ta=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&[null,Object.prototype].includes(Object.getPrototypeOf(e));function rr(e){let t=e?.nodes||{},o=Object.values(t).filter(s=>s?.kind==="correction");if(!o.length)return[];let n=[],i=s=>s?.kind==="approval"?[s.onApprove,s.onReject]:s?.kind==="condition"?[...(Array.isArray(s.branches)?s.branches:[]).map(a=>a.target),s.otherwise]:s?.kind==="action"||s?.kind==="cc"?[s.next]:[],r=new Set,c=[e.startAt];for(;c.length;){let s=c.pop();r.has(s)||(r.add(s),c.push(...i(t[s])))}for(let s of o){(!Ta(s)||Object.keys(s).some(d=>!["id","kind","title","taskPageCode","next"].includes(d))||typeof s.id!="string"||!/^[A-Za-z][A-Za-z0-9_-]{0,127}$/.test(s.id)||["__proto__","prototype","constructor"].includes(s.id)||t[s.id]!==s||typeof s.title!="string"||!s.title.trim()||s.title.length>255||typeof s.taskPageCode!="string"||!/^[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(s.taskPageCode))&&n.push("WORKFLOW_CORRECTION_NODE_INVALID"),(s.next!==e.startAt||t[s.next]?.kind==="correction")&&n.push("WORKFLOW_CORRECTION_REPLAY_TARGET_INVALID"),(r.has(s.id)||Object.values(t).some(d=>i(d).includes(s.id)))&&n.push("WORKFLOW_CORRECTION_FORWARD_ENTRY_FORBIDDEN"),Object.values(t).some(d=>d?.kind==="approval"&&r.has(d.id)&&Array.isArray(d.returnTargets)&&d.returnTargets.includes(s.id))||n.push("WORKFLOW_CORRECTION_RETURN_SOURCE_REQUIRED");let a=e.taskPages?.[s.taskPageCode];!a||!Array.isArray(a.fields)?n.push("WORKFLOW_CORRECTION_PAGE_REQUIRED"):a.fields.some(d=>d?.subtable)&&n.push("WORKFLOW_CORRECTION_OWNED_FACTS_UNSUPPORTED")}return[...new Set(n)]}var nn=class extends Error{constructor(o){super(o);this.code=o}code},ru=["projection","triggerCode","resourceCode","recordId","recordRevision","field","dueAt"];function sr(e,t,o){let n=r=>{throw new nn(r)};t.length>100&&n("DATE_TRIGGER_PROJECTION_LIMIT");let i=new Set;for(let r of t){let c=r.filter?.resourceCodes||[];if(Array.isArray(c)||n("DATE_TRIGGER_PROJECTION_INVALID"),c.length&&!c.includes(e))continue;let s=r.payload?.fields||[];(!Array.isArray(s)||s.length>32)&&n("DATE_TRIGGER_PROJECTION_LIMIT");for(let a of s)(typeof a!="string"||!/^[A-Za-z_][A-Za-z0-9_]{0,62}$/.test(a)||["__proto__","constructor","prototype"].includes(a))&&n("DATE_TRIGGER_PROJECTION_FIELD_INVALID"),i.add(a)}if(i.size>64&&n("DATE_TRIGGER_PROJECTION_LIMIT"),o!==void 0){let r=o?.schema?.fields??o?.fields;Array.isArray(r)||n("DATE_TRIGGER_PROJECTION_RESOURCE_INVALID");let c=new Map(r.map(s=>[s.code,s]));for(let s of i){let a=c.get(s);a||n("DATE_TRIGGER_PROJECTION_FIELD_UNKNOWN"),a.type==="subtable"&&n("DATE_TRIGGER_PROJECTION_SUBTABLE_FORBIDDEN"),o.fieldPolicies?.[s]?.mask==="omit"&&n("DATE_TRIGGER_PROJECTION_FIELD_SENSITIVE")}}return[...i].sort()}function su(e,t){if(!t.length)return e;let o=e?.properties?.projection;if(o?.type!=="object"||!o.properties||typeof o.properties!="object"||Array.isArray(o.properties)||o.additionalProperties!==!1||o.required!==void 0&&!Array.isArray(o.required)||t.some(n=>!Object.hasOwn(o.properties,n))||(o.required||[]).some(n=>!t.includes(n)))throw new nn("DATE_TRIGGER_PROJECTION_SCHEMA_INVALID");return{...e,properties:{...e.properties,projection:{}}}}var Ra=64,_o=1024*1024,Ca=65536,cr=500,ha=500,qe=new Set(["__proto__","prototype","constructor"]),dr=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,Nt=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,ar=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,se=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&[null,Object.prototype].includes(Object.getPrototypeOf(e)),De=(e,t)=>se(e)&&Object.keys(e).every(o=>t.includes(o)&&!qe.has(o)),on=e=>{try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return 1/0}},lr=e=>e==null||typeof e=="string"&&!e.trim()||Array.isArray(e)&&e.length===0;function Fe(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((n,i)=>Fe(n,t[i]));if(!se(e)||!se(t))return!1;let o=Object.keys(e);return o.length===Object.keys(t).length&&o.every(n=>Object.hasOwn(t,n)&&Fe(e[n],t[n]))}function mo(e,t){let o=t.split(".");if(!(o.some(n=>!dr.test(n)||qe.has(n))||o.length>12))return o.reduce((n,i)=>se(n)&&Object.hasOwn(n,i)?n[i]:void 0,e)}function Le(e,t){switch(e.op){case"literal":return e.value;case"path":return mo({values:t},e.path);case"and":return e.values.every(o=>!!Le(o,t));case"or":return e.values.some(o=>!!Le(o,t));case"not":return!Le(e.value,t);case"exists":return!lr(Le(e.value,t));default:{let o=Le(e.left,t),n=Le(e.right,t);return e.op==="eq"?Fe(o,n):e.op==="neq"?!Fe(o,n):e.op==="in"?Array.isArray(n)&&n.some(i=>Fe(i,o)):e.op==="contains"?Array.isArray(o)?o.some(i=>Fe(i,n)):typeof o=="string"&&typeof n=="string"&&o.includes(n):typeof o!="number"||typeof n!="number"||!Number.isFinite(o)||!Number.isFinite(n)?!1:e.op==="gt"?o>n:e.op==="gte"?o>=n:e.op==="lt"?o<n:o<=n}}}function Ot(e,t,o=0,n={nodes:0}){if(o>8||++n.nodes>64||!se(e))return!1;if(e.op==="literal")return De(e,["op","value"])&&Object.hasOwn(e,"value")&&on(e.value)<=4096&&Tt(e.value);if(e.op==="path"){if(!De(e,["op","path"])||typeof e.path!="string")return!1;let i=e.path.split(".");return i[0]==="values"&&i.length>=2&&i.length<=8&&t.has(i[1])&&i.every(r=>Nt.test(r)&&!qe.has(r))}return["not","exists"].includes(e.op)?De(e,["op","value"])&&Ot(e.value,t,o+1,n):["and","or"].includes(e.op)?De(e,["op","values"])&&Array.isArray(e.values)&&e.values.length>0&&e.values.length<=16&&e.values.every(i=>Ot(i,t,o+1,n)):["eq","neq","gt","gte","lt","lte","in","contains"].includes(e.op)&&De(e,["op","left","right"])&&Ot(e.left,t,o+1,n)&&Ot(e.right,t,o+1,n)}function rn(e,t,o){let n=[],i=e.taskPages;if(i!==void 0&&(!se(i)||Object.keys(i).length===0||Object.keys(i).length>16||on(i)>Ca))return["WORKFLOW_TASK_PAGES_INVALID"];for(let[r,c]of Object.entries(i||{})){let s=`taskPages.${r}`;if(!dr.test(r)||qe.has(r)||!De(c,["title","fields"])||typeof c.title!="string"||!c.title.trim()||c.title.length>160||!Array.isArray(c.fields)||!c.fields.length||c.fields.length>Ra){n.push(`WORKFLOW_TASK_PAGE_INVALID:${s}`);continue}let a=new Set(c.fields.map(u=>u?.code));a.size!==c.fields.length&&n.push(`WORKFLOW_TASK_PAGE_DUPLICATE_FIELD:${s}`);let d=0,f=new Set;for(let u of c.fields){if(!De(u,["code","readonly","required","visibleWhen","requiredWhen","subtable"])||!Nt.test(u.code)||qe.has(u.code)||["readonly","required"].some(p=>u[p]!==void 0&&typeof u[p]!="boolean")||u.readonly&&(u.required||u.requiredWhen)){n.push(`WORKFLOW_TASK_PAGE_FIELD_INVALID:${s}`);continue}for(let p of["visibleWhen","requiredWhen"])u[p]!==void 0&&!Ot(u[p],a)&&n.push(`WORKFLOW_TASK_PAGE_EXPRESSION_INVALID:${s}.${u.code}.${p}`);if(t){let p=t.get(u.code);if((!p||p.system||p.hidden||p.type==="serial-number"||!u.readonly&&p.widget==="readonly"||!u.readonly&&p.type==="subtable"&&!u.subtable||u.subtable&&p.type!=="subtable")&&n.push(`WORKFLOW_TASK_PAGE_RESOURCE_FIELD_INVALID:${s}.${u.code}`),u.subtable&&p?.subtable){let g=p.subtable;d+=g.maxRows??20,(f.has(g.resourceCode)||!Number.isSafeInteger(g.maxRows??20)||(g.maxRows??20)<1||(g.maxRows??20)>cr||!Nt.test(g.foreignKey)||!Nt.test(g.orderField)||g.foreignKey===g.orderField)&&n.push(`WORKFLOW_TASK_SUBTABLE_RELATION_INVALID:${s}.${u.code}`),f.add(g.resourceCode);let I=o?.get(g.resourceCode);o&&(!I||!["uuid","resource-ref.single"].includes(I.get(g.foreignKey)?.type||"")||I.get(g.orderField)?.type!=="number.integer")&&n.push(`WORKFLOW_TASK_SUBTABLE_RELATION_INVALID:${s}.${u.code}`);for(let A of Array.isArray(u.subtable.fields)?u.subtable.fields:[]){if(!A||typeof A.code!="string")continue;let O=I?.get(A.code);(A.code===g.foreignKey||A.code===g.orderField||I&&(!O||O.system||O.hidden||O.type==="subtable"||!A.readonly&&(O.widget==="readonly"||O.type==="serial-number")))&&n.push(`WORKFLOW_TASK_SUBTABLE_FIELD_UNSUPPORTED:${s}.${u.code}.${A.code}`)}}else u.subtable&&t&&n.push(`WORKFLOW_TASK_SUBTABLE_RELATION_INVALID:${s}.${u.code}`)}u.subtable&&(u.readonly||!De(u.subtable,["fields","create","delete","reorder"])||["create","delete","reorder"].some(p=>u.subtable?.[p]!==void 0&&typeof u.subtable[p]!="boolean")||!Array.isArray(u.subtable.fields)||u.subtable.fields.some(p=>p?.subtable)?n.push(`WORKFLOW_TASK_SUBTABLE_PAGE_INVALID:${s}.${u.code}`):n.push(...rn({taskPages:{child:{title:"\u5B50\u884C",fields:u.subtable.fields}}},o?.get(t?.get(u.code)?.subtable?.resourceCode||"")).map(p=>`${p}:${s}.${u.code}`)))}(d>ha||d<0||!Number.isSafeInteger(d))&&n.push(`WORKFLOW_TASK_SUBTABLE_BUDGET_EXCEEDED:${s}`)}for(let[r,c]of Object.entries(e.nodes||{}))se(c)&&c.taskPageCode!==void 0&&(!["approval","correction"].includes(c.kind)||typeof c.taskPageCode!="string"||!se(i)||!Object.hasOwn(i,c.taskPageCode)?n.push(`WORKFLOW_TASK_PAGE_NOT_FOUND:${r}`):Array.isArray(i[c.taskPageCode]?.fields)&&i[c.taskPageCode].fields.some(s=>s&&(c.fieldPolicy?.fields?.[s.code]||c.fieldPolicy?.default)==="hidden")&&n.push(`WORKFLOW_TASK_PAGE_FIELD_HIDDEN:${r}`));return n}function ur(e,t){return e.fields.map(o=>({code:o.code,visible:o.visibleWhen===void 0||!!Le(o.visibleWhen,t),readonly:o.readonly===!0,required:o.required===!0||o.requiredWhen!==void 0&&!!Le(o.requiredWhen,t)}))}var he=class extends Error{constructor(o,n){super(o);this.code=o;this.field=n}code;field;rowIndex;childField};function du(e,t){return t.map(o=>({key:String(o.id),id:String(o.id),revision:Number(o.revision),state:"persisted",values:Object.fromEntries(ur({title:"\u5B50\u884C",fields:e.fields},o).filter(n=>n.visible&&!n.readonly).map(n=>[n.code,o[n.code]??null]))}))}function lu(e,t,o,n,i,r=!0,c=0){let s=e.subtable,a=g=>{throw new he(g,e.code)};if(!s||!Number.isSafeInteger(t)||t<1||t>cr||!Number.isSafeInteger(c)||c<0||c>t||!Array.isArray(n)||n.length>2*t||on(n)>_o||!Tt(n))return a("WORKFLOW_TASK_SUBTABLE_VALUES_INVALID");let d=new Map(o.map(g=>[String(g.id),g])),f=new Set,u=new Set,p=[];for(let g of n){if(!De(g,["key","state","id","revision","values"])||typeof g.key!="string"||!ar.test(g.key)||f.has(g.key)||!["created","persisted","deleted"].includes(g.state)||!se(g.values))return a("WORKFLOW_TASK_SUBTABLE_ROW_INVALID");if(f.add(g.key),g.state==="created"){if(!s.create||g.id!==void 0||g.revision!==void 0||d.has(g.key))return a("WORKFLOW_TASK_SUBTABLE_CREATE_FORBIDDEN")}else{if(typeof g.id!="string"||g.id!==g.key||!ar.test(g.id)||u.has(g.id)||!Number.isSafeInteger(g.revision)||g.revision<1||!d.has(g.id))return a("WORKFLOW_TASK_SUBTABLE_SCOPE_CONFLICT");if(u.add(g.id),r&&Number(d.get(g.id).revision)!==g.revision)return a("WORKFLOW_TASK_SUBTABLE_REVISION_CONFLICT")}if(g.state==="deleted"){if(!s.delete||Object.keys(g.values).length)return a("WORKFLOW_TASK_SUBTABLE_DELETE_FORBIDDEN");continue}try{wa({title:e.code,fields:s.fields},g.id?d.get(g.id):{},g.values,i)}catch(I){if(!(I instanceof he))throw I;let A=new he(I.code,e.code);throw A.rowIndex=p.length,I.field!==void 0&&(A.childField=I.field),A}p.push(g)}if(u.size!==d.size)return a("WORKFLOW_TASK_SUBTABLE_SCOPE_CONFLICT");if(p.length>t)return a("WORKFLOW_TASK_SUBTABLE_MAX_ROWS_EXCEEDED");if(i&&p.length<c)return a("WORKFLOW_TASK_SUBTABLE_MIN_ROWS_NOT_MET");if(!s.reorder){let g=o.filter(A=>p.some(O=>O.id===String(A.id))).map(A=>String(A.id)),I=p.filter(A=>A.state==="persisted").map(A=>A.id);if(!Fe(g,I)||p.some((A,O)=>A.state==="created"&&p.slice(O+1).some(b=>b.state==="persisted")))return a("WORKFLOW_TASK_SUBTABLE_REORDER_FORBIDDEN")}return n}function Tt(e,t={members:0},o=0){return++t.members>5e4||o>12?!1:e===null||typeof e=="boolean"?!0:typeof e=="string"?e.length<=_o:typeof e=="number"?Number.isFinite(e):Array.isArray(e)?e.length<=1e3&&e.every(n=>Tt(n,t,o+1)):se(e)&&Object.entries(e).every(([n,i])=>!qe.has(n)&&Tt(i,t,o+1))}function wa(e,t,o,n){if(!se(o)||on(o)>_o||!Tt(o))throw new he("WORKFLOW_TASK_FORM_VALUES_INVALID");let i={...t,...o},r=new Map(ur(e,i).map(c=>[c.code,c]));for(let c of Object.keys(o)){let s=r.get(c);if(!s||s.readonly||!s.visible)throw new he("WORKFLOW_TASK_FORM_FIELD_NOT_EDITABLE",c)}if(n)for(let c of r.values()){let s=i[c.code],a=e.fields.find(d=>d.code===c.code)?.subtable&&Array.isArray(s)?s.every(d=>se(d)&&d.state==="deleted"):lr(s);if(c.visible&&!c.readonly&&c.required&&a)throw new he("WORKFLOW_TASK_FORM_REQUIRED",c.code)}return i}function uu(e,t,o){let n=JSON.parse(JSON.stringify(t));for(let[c,s]of Object.entries(e.subject?.factProjection||{})){let a=c.split(".");if(!a.length||a.length>12||c.length>128||a[0]==="steps"||a.some(f=>!Nt.test(f)||qe.has(f)))throw new he("WORKFLOW_TASK_FORM_FACT_PROJECTION_INVALID");if(!Object.hasOwn(o,s))throw new he("WORKFLOW_TASK_FORM_FACT_FIELD_MISSING",s);let d=n;for(let f of a.slice(0,-1))d=d[f]=se(d[f])?d[f]:{};d[a.at(-1)]=o[s]===void 0?void 0:JSON.parse(JSON.stringify(o[s]))}let i=new Set,r=Object.values(e.nodes||{}).filter(c=>c.kind==="action");for(let c=0;c<=r.length;c++){let s=!1;for(let a of r)se(n.steps)&&Object.hasOwn(n.steps,a.id)&&Object.values(a.inputs||{}).some(d=>d.source==="fact"&&!Fe(mo(t,d.path),mo(n,d.path)))&&(delete n.steps[a.id],i.add(a.id),s=!0);if(!s)break}return{facts:n,invalidatedNodeIds:[...i].sort()}}function fu(e,t,o){let n=e.nodes||{};for(let i of o){let r=new Set,c=new Map,s=a=>{if(a===i)return!0;if(c.has(a))return c.get(a);if(r.has(a)||r.size>200)return!1;let d=n[a];if(!se(d)||d.kind==="end")return!1;r.add(a);let f=d.kind==="approval"?[d.onApprove]:d.kind==="condition"?[...(d.branches||[]).map(p=>p.target),d.otherwise]:[d.next],u=f.length>0&&f.every(p=>typeof p=="string"&&s(p));return r.delete(a),c.set(a,u),u};if(!s(t))return!1}return!0}var mu=256,_u=64,gu=262144,Sa=/^[a-z][a-z0-9_-]{0,127}$/,Da=/^[A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z][A-Za-z0-9_]*)*$/,pr=new Set(["__proto__","prototype","constructor"]),we=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Ct=(e,t)=>Object.keys(e).every(o=>t.includes(o)),ze=(e,t)=>typeof e=="string"&&e.trim().length>0&&e.length<=t&&!/[\u0000-\u001f\u007f]/.test(e),ke=e=>typeof e=="string"&&Sa.test(e)&&!pr.has(e),mr=e=>typeof e=="string"&&e.length<=255&&Da.test(e)&&!e.split(".").some(t=>pr.has(t)),ka=e=>we(e)&&Ct(e,["dimension","valueFrom","value"])&&ke(e.dimension)&&(ze(e.value,255)&&e.valueFrom===void 0||mr(e.valueFrom)&&e.value===void 0),fr=e=>typeof e=="string"&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?(?:Z|[+-]\d{2}:\d{2})$/.test(e)&&Number.isFinite(Date.parse(e)),Rt={type:"string",pattern:"^[a-z][a-z0-9_-]{0,127}$"},go={type:"string",minLength:1,maxLength:128},Au={type:"object",additionalProperties:!1,required:["policyCode","title","strategy","dimensions","sources"],properties:{policyCode:Rt,title:go,strategy:{enum:["replace_then_append","replace_only"]},dimensions:{type:"object",maxProperties:8,propertyNames:Rt,additionalProperties:{type:"object",additionalProperties:!1,required:["title","valueFrom"],properties:{title:go,valueFrom:{type:"string",minLength:1,maxLength:255}}}},sources:{type:"object",minProperties:1,maxProperties:16,propertyNames:Rt,additionalProperties:{type:"object",additionalProperties:!1,required:["title","provider","roleCode"],properties:{title:go,provider:{enum:["app_role","app_role_in_scope"]},roleCode:Rt,scope:{type:"object",additionalProperties:!1,required:["dimension"],properties:{dimension:Rt,value:{type:"string",minLength:1,maxLength:255},valueFrom:{type:"string",minLength:1,maxLength:255}}}}}}}};function sn(e){if(!we(e)||!Ct(e,["policyCode","title","strategy","dimensions","sources"])||!ke(e.policyCode)||!ze(e.title,128)||!["replace_then_append","replace_only"].includes(e.strategy))return["WORKFLOW_V2_ROUTING_POLICY_INVALID"];let t=[];return(!we(e.dimensions)||Object.keys(e.dimensions).length>8||Object.entries(e.dimensions).some(([o,n])=>!ke(o)||!we(n)||!Ct(n,["title","valueFrom"])||!ze(n.title,128)||!mr(n.valueFrom)))&&t.push("WORKFLOW_V2_ROUTING_DIMENSIONS_INVALID"),(!we(e.sources)||Object.keys(e.sources).length<1||Object.keys(e.sources).length>16||Object.entries(e.sources).some(([o,n])=>!ke(o)||!we(n)||!Ct(n,["title","provider","roleCode","scope"])||!ze(n.title,128)||!ke(n.roleCode)||!["app_role","app_role_in_scope"].includes(n.provider)||(n.provider==="app_role_in_scope"?!ka(n.scope):n.scope!==void 0)))&&t.push("WORKFLOW_V2_ROUTING_SOURCES_INVALID"),t}function Eu(e,t){if(sn(e).length)return["WORKFLOW_V2_ROUTING_POLICY_INVALID"];if(!Array.isArray(t)||t.length>256||new TextEncoder().encode(JSON.stringify(t)).length>262144)return["WORKFLOW_V2_ROUTING_RULE_LIMIT_EXCEEDED"];let o=[],n=new Set;for(let i of t){if(!we(i)||!Ct(i,["ruleCode","title","enabled","workflowCode","nodeId","matches","sourceCode","effect","priority","validFrom","validTo"])||!ke(i.ruleCode)||!ze(i.title,128)||typeof i.enabled!="boolean"||!ke(i.sourceCode)||!Object.hasOwn(e.sources,i.sourceCode)||!["append","replace"].includes(i.effect)||!Number.isSafeInteger(i.priority)||i.priority<-1e3||i.priority>1e3||i.workflowCode!==void 0&&!ke(i.workflowCode)||i.nodeId!==void 0&&(!ke(i.nodeId)||i.workflowCode===void 0)||i.validFrom!==void 0&&!fr(i.validFrom)||i.validTo!==void 0&&!fr(i.validTo)||i.validFrom&&i.validTo&&Date.parse(i.validFrom)>=Date.parse(i.validTo)){o.push("WORKFLOW_V2_ROUTING_RULE_INVALID");continue}n.has(i.ruleCode)&&o.push(`WORKFLOW_V2_ROUTING_RULE_DUPLICATE:${i.ruleCode}`),n.add(i.ruleCode),(!we(i.matches)||Object.entries(i.matches).some(([r,c])=>!Object.hasOwn(e.dimensions,r)||!Array.isArray(c)||c.length<1||c.length>64||new Set(c).size!==c.length||c.some(s=>!ze(s,255))))&&o.push(`WORKFLOW_V2_ROUTING_MATCH_INVALID:${i.ruleCode}`)}return[...new Set(o)]}function $a(e){return JSON.stringify({policyCode:e.policyCode,strategy:e.strategy,dimensions:Object.entries(e.dimensions).sort(([t],[o])=>t<o?-1:t>o?1:0).map(([t,o])=>[t,o.valueFrom]),sources:Object.entries(e.sources).sort(([t],[o])=>t<o?-1:t>o?1:0).map(([t,o])=>[t,o.provider,o.roleCode,o.scope?.dimension??null,o.scope?.valueFrom??null,o.scope?.value??null])})}function _r(e){let t=[],o=new Map;for(let n of e)for(let[i,r]of Object.entries(n.bindings||{})){if(!we(r)||r.routing===void 0)continue;let c=sn(r.routing);if(c.length){t.push(...c.map(d=>`${d}:${i}`));continue}let s=$a(r.routing),a=o.get(r.routing.policyCode);a&&a!==s&&t.push(`WORKFLOW_V2_ROUTING_POLICY_CONFLICT:${r.routing.policyCode}`),o.set(r.routing.policyCode,s)}return[...new Set(t)]}function Iu(e,t){let o={};for(let[n,i]of Object.entries(e.dimensions)){let r=t;for(let c of i.valueFrom.split("."))r=we(r)&&Object.hasOwn(r,c)?r[c]:void 0;if(!(typeof r=="string"&&ze(r,255)||typeof r=="number"&&Number.isFinite(r)||typeof r=="boolean"))throw new Error(`WORKFLOW_V2_ROUTING_FACT_REQUIRED:${n}`);o[n]=String(r)}return o}function yu(e,t,o){let n=t.filter(d=>d.enabled&&(!d.validFrom||Date.parse(d.validFrom)<=o.at)&&(!d.validTo||Date.parse(d.validTo)>o.at)&&(!d.workflowCode||d.workflowCode===o.workflowCode)&&(!d.nodeId||d.nodeId===o.nodeId)&&Object.entries(d.matches).every(([f,u])=>u.includes(o.facts[f])));if(n.length>64)throw new Error("WORKFLOW_V2_ROUTING_MATCH_LIMIT_EXCEEDED");let i=(d,f)=>f.priority-d.priority||+!!d.workflowCode-+!!f.workflowCode||+!!d.nodeId-+!!f.nodeId||(d.ruleCode<f.ruleCode?-1:d.ruleCode>f.ruleCode?1:0),r=n.filter(d=>d.effect==="replace").sort(i);if(r.length>1&&r[0].priority===r[1].priority)throw new Error("WORKFLOW_V2_ROUTING_REPLACE_CONFLICT");let c=r[0],s=c&&e.strategy==="replace_only"?[]:n.filter(d=>d.effect==="append").sort(i),a=[...c?[c]:[],...s];return{matched:n.sort(i),replacement:c,applied:a,ignored:n.filter(d=>!a.includes(d))}}var Ao="^[A-Za-z][A-Za-z0-9_]{0,62}$",gr="^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$",Nu={type:"object",additionalProperties:!1,required:["mode","resourceCode","subtables"],properties:{mode:{const:"create"},resourceCode:{type:"string",maxLength:64,pattern:gr},subtables:{type:"array",minItems:1,maxItems:16,items:{type:"object",additionalProperties:!1,required:["fieldCode","fieldCodes"],properties:{fieldCode:{type:"string",pattern:Ao},fieldCodes:{type:"array",minItems:1,maxItems:200,uniqueItems:!0,items:{type:"string",pattern:Ao}}}}}}};function an(e){let t=n=>!!(n&&typeof n=="object"&&!Array.isArray(n)),o=n=>typeof n=="string"&&new RegExp(Ao).test(n)&&!["__proto__","prototype","constructor"].includes(n);if(!t(e)||Object.keys(e).some(n=>!["mode","resourceCode","subtables"].includes(n))||e.mode!=="create"||typeof e.resourceCode!="string"||e.resourceCode.length>64||!new RegExp(gr).test(e.resourceCode)||!Array.isArray(e.subtables)||e.subtables.length<1||e.subtables.length>16||e.subtables.some(n=>!t(n)||Object.keys(n).some(i=>!["fieldCode","fieldCodes"].includes(i))||!o(n.fieldCode)||!Array.isArray(n.fieldCodes)||n.fieldCodes.length<1||n.fieldCodes.length>200||new Set(n.fieldCodes).size!==n.fieldCodes.length||n.fieldCodes.some(i=>!o(i)))||new Set(e.subtables.map(n=>n.fieldCode)).size!==e.subtables.length)throw new Error("WORKFLOW_OWNED_SUBJECT_CREATE_INVALID")}function Tu(e){return an(e),{mode:"create",resourceCode:e.resourceCode,subtables:e.subtables.map(t=>({fieldCode:t.fieldCode,fieldCodes:[...t.fieldCodes].sort()})).sort((t,o)=>t.fieldCode.localeCompare(o.fieldCode))}}function Ar(e,t,o){an(e);let n=s=>{throw new Error(`WORKFLOW_OWNED_SUBJECT_${s}`)},i=t.get(e.resourceCode);i||n("RESOURCE_MISSING");let r=new Set,c=0;for(let s of e.subtables){let a=i.get(s.fieldCode),d=a?.subtable,f=t.get(d?.resourceCode);(a?.type!=="subtable"||!f||d.resourceCode===e.resourceCode||r.has(d.resourceCode))&&n("RELATION_INVALID"),r.add(d.resourceCode);let u=d.maxRows??20;(!Number.isSafeInteger(u)||u<1)&&n("BUDGET_EXCEEDED"),c+=u;for(let p of s.fieldCodes){let g=f.get(p);(!g||["serial-number","subtable"].includes(g.type)||[d.foreignKey,d.orderField].includes(p))&&n("FIELD_INVALID"),["file","image","signature","text.rich"].includes(g.type)&&!o.some(I=>I.resourceCode===d.resourceCode&&I.fieldCodes.includes(p)&&I.intents.includes("create"))&&n("FILE_ACCESS_REQUIRED")}}c>500&&n("BUDGET_EXCEEDED")}import*as pn from"crypto";var Er="native-4",Eo="2.0.0-alpha.5",Ir={"application-native-2":"1.0.0","application.extended-declaration-capacity":"1.0.0","application.extended-artifact-capacity":"1.0.0","application.development-configuration":"1.0.0","authz.native-batch-explain":"1.0.0","authz.native-management":"1.0.0","authz.native-membership-batch":"1.0.0","deployment.durable-runs":"1.0.0","deployment.platform-executor":"1.0.0","environment.on-demand-production":"1.0.0","environment.runtime-lifecycle":"1.0.0","data-api-v2":"1.1.0","data.extended-owned-subtable-capacity":"1.0.0","data.business-commands":"1.0.0","data.record-edit":"1.0.0","data.native-golden-crud":"1.0.0","data.audit-read-access":"1.0.0","data.managed-files":"1.1.0","data.decimal-reservations":"1.1.0","data.decimal-reservation-lifecycle":"1.0.0","data.unique-keys":"1.1.0","data.user-candidates":"1.0.0","data.user-candidate-launch-scope":"1.0.0","data.datetime-minute-precision":"1.0.0","data.subtable-minimum-rows":"1.0.0","data.managed-concurrency":"1.0.0","data.managed-concurrency.durable":"1.0.0","workflow.named-input-sources":"1.0.0","workflow.approved-delegation":"1.0.0","directory-v2":"1.0.0","directory.selected-user":"1.0.0","directory.current-initiator-phone":"1.0.0","events-v2":"1.0.0","events.durable-receipts":"1.0.0","events.capture-policy":"1.0.0","events.date-source-projection":"1.0.0","events.native-data-actions":"1.0.0","workflow-kernel-v2":"1.0.0","workflow.business-data-command":"1.0.0","workflow.native-stage-guard":"1.0.0","workflow.launch-preflight":"1.0.0","workflow.optional-rejection-comment":"1.0.0","workflow.optional-operation-reason":"1.0.0","workflow.optional-withdrawal-reason":"1.0.0","data.transaction-actor-authority":"1.0.0","data.authenticated-public-projection":"1.0.0","data.record-print":"1.0.0","data.workflow-record-deletion":"1.0.0","data.record-comments":"1.0.0","workflow.record-history-read":"1.0.0","workflow.rejection-notification":"1.0.0","workflow.instance-cancellation-policy":"1.0.0","workflow.node-administration":"1.0.0","workflow.assignment-routing":"1.0.0","workflow.role-union":"1.0.0","workflow.named-owned-create":"1.0.0","workflow.owned-initial-facts":"1.0.0","workflow.initiator-correction":"1.0.0","workflow.correction-business-command":"1.0.0","workflow.role-references":"1.0.0","workflow.delegation-management":"1.0.0","workflow.automatic-cc":"1.0.0","workflow.approval-empty-policy":"1.0.0","workflow.initiator-approval-policy":"1.0.0","workflow.completion-deadline":"1.0.0","workflow.task-page-submit":"1.0.0","workflow.task-private-drafts":"1.0.0","workflow.task-managed-files":"1.0.0","workflow.task-rich-fields":"1.0.0","workflow.task-owned-subtables":"1.0.0","workflow.task-owned-files":"1.0.0","workflow.durable-business-step":"1.0.0","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 hu=5,wu=20,Su=50,Du=50,ku=100,wt=class extends Error{constructor(o,n){super(o);this.code=o;this.pointer=n;this.name="NativeDataPolicyExpressionV2Error"}code;pointer};function cn(e,t){let o=[],n=(i,r,c)=>{c>5&&ht("NATIVE_DATA_POLICY_EXPRESSION_DEPTH_EXCEEDED",r);let s=br(i,r),a=["allOf","anyOf"].filter(u=>u in s);if(a.length===0){o.push({rule:s,pointer:r}),o.length>50&&ht("NATIVE_DATA_POLICY_EXPRESSION_LEAVES_EXCEEDED",r);return}let d=a[0],f=s[d];(a.length!==1||Object.keys(s).length!==1||!Array.isArray(f)||f.length<1||f.length>20)&&ht("NATIVE_DATA_POLICY_EXPRESSION_GROUP_INVALID",r),f.forEach((u,p)=>n(u,`${r}/${d}/${p}`,c+1))};return n(e,t,1),o}function yr(e,t){cn(e,t);let o=(n,i)=>{let r=br(n,i);if(Array.isArray(r.allOf))return Io(r.allOf.flatMap((c,s)=>o(c,`${i}/allOf/${s}`)),i);if(Array.isArray(r.anyOf)){let c=[[]];return r.anyOf.forEach((s,a)=>{let d=o(s,`${i}/anyOf/${a}`);c=Io(c.flatMap(f=>d.map(u=>[...f,...u])),i)}),c}return[[r]]};return Io(o(e,t),t)}function Io(e,t){let o=e.reduce((n,i)=>n+i.length,0);return(e.length>50||o>100)&&ht("NATIVE_DATA_POLICY_EXPRESSION_EXPANSION_EXCEEDED",t),e}function br(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&ht("NATIVE_DATA_POLICY_EXPRESSION_NODE_INVALID",t),e}function ht(e,t){throw new wt(e,t)}var B=Object.freeze({perspectives:100,resources:512,dataPolicies:512,roles:256,subjectReadSurfaces:50,capabilities:4096,operations:500,eventConsumers:100,eventProducers:1e3,eventSchemas:100,eventTypes:500,workflows:512,routes:2048,adminPages:2048,adminNavigationGroups:100,adminNavigationItems:1024});function Or(e){let t=(e.surface?.mutationOwner||"native")==="native";return["query","get","create","update","delete"].filter(o=>{let n=e.surface?.generated;return o==="query"?n?.list??!0:o==="get"?n?.detail??!0:n?.[o]??t})}function yo(e){let t=(e.data?.resources||[]).filter(o=>o.status!=="retired").reduce((o,n)=>o+Or(n).length,0)+(e.backend?.operations||[]).filter(o=>o.ai).length;return(e.data?.resources?.length||0)>100||(e.authz?.dataPolicies?.length||0)>100||(e.authz?.roles?.length||0)>100||(e.authz?.capabilities?.length||0)>2e3||[e.workflows?.definitions,e.workflows?.bindings,e.workflows?.activations].some(o=>(o?.length||0)>100)||(e.frontend?.routes?.length||0)>500||t>500||(e.frontend?.admin?.navigation||[]).reduce((o,n)=>o+n.items.length,0)>500}var ye=Object.freeze({configBytes:4194304,contractBytes:8388608,depth:40,stringBytes:1048576,legacyNodes:1e5,extendedNodes:25e4});function dn(e){let t=0,o=[[e][Symbol.iterator]()];for(;o.length;){let n=o[o.length-1].next();if(n.done){o.pop();continue}if(++t>ye.legacyNodes)return!0;if(Array.isArray(n.value))o.push(n.value.values());else if(n.value&&typeof n.value=="object"){let i=n.value;o.push((function*(){for(let r of Object.keys(i))i[r]!==void 0&&(yield i[r])})())}}return!1}var va="openxiangda.config-bundle/v3",Wr="openxiangda.contract-bundle/v3",Nr="openxiangda.native-configuration-projection/v1",Dt=Er,Pa=/^[a-f0-9]{64}$/,Va=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,La=/^app:[a-z][a-z0-9]*(?:-[a-z0-9]+)*:[A-Za-z0-9:._*-]+$/,Fa=/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/,xa=/^[a-z][a-z0-9]*(?:[-.][a-z0-9]+)*$/,ja=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,Wa=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,Tr=/^[A-Za-z][A-Za-z0-9_]{0,127}$/,Ua=/^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*$/,Ma=/^[A-Z][A-Z0-9_]*$/,Ba=/^[a-z][a-z0-9-]{2,63}$/,Ka=/^[A-Za-z][A-Za-z0-9_-]{0,127}$/,Ga=/^[A-Za-z][A-Za-z0-9_.]{0,127}$/,qa=16,za=2*1024,Ja=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"]),Ha=new Set(["overview","database","operations","workflow","members","calendar","document","folder","settings"]),Ya=new Set(["approve","reject","return","transfer","delegate","add_assignee","resubmit","withdraw","terminate","admin_reassign","admin_override","retry_resolution"]),Xa=ye.configBytes,Za=ye.contractBytes,Qa=ye.depth,No=ye.stringBytes,ec="openxiangda.event-handler-manifest/v2",Ur="openxiangda.application-route-manifest/v3",Rr=64,Mr=new Set(["id","revision","created_by","updated_by","created_at","updated_at"]),To=["openxiangda.data.record.created.v2","openxiangda.data.record.updated.v2","openxiangda.data.record.deleted.v2"],Ro=["openxiangda.workflow.node.skipped.v2",It,"openxiangda.workflow.step.result_received.v2","openxiangda.workflow.step.completed.v2","openxiangda.workflow.step.continuation_failed.v2","openxiangda.workflow.instance.started.v2","openxiangda.workflow.instance.cc_added.v2","openxiangda.workflow.instance.completed.v2","openxiangda.workflow.instance.rejected.v2","openxiangda.workflow.instance.returned.v2","openxiangda.workflow.instance.resumed.v2","openxiangda.workflow.instance.withdrawn.v2","openxiangda.workflow.instance.terminated.v2","openxiangda.workflow.task.created.v2","openxiangda.workflow.task.assigned.v2","openxiangda.workflow.task.assignment_pending.v2","openxiangda.workflow.task.assignment_resolution_failed.v2","openxiangda.workflow.task.approved.v2","openxiangda.workflow.task.completed.v2","openxiangda.workflow.task.rejected.v2","openxiangda.workflow.task.returned.v2","openxiangda.workflow.task.resubmitted.v2","openxiangda.workflow.task.transferred.v2","openxiangda.workflow.task.reassigned.v2","openxiangda.workflow.task.delegated.v2","openxiangda.workflow.task.assignee_added.v2","openxiangda.workflow.task.cancelled.v2","openxiangda.workflow.participant.activated.v2","openxiangda.workflow.participant.completed.v2","openxiangda.workflow.participant.rejected.v2","openxiangda.workflow.participant.returned.v2","openxiangda.workflow.participant.transferred.v2","openxiangda.workflow.participant.reassigned.v2","openxiangda.workflow.participant.delegated.v2","openxiangda.workflow.participant.added.v2","openxiangda.workflow.participant.suspended.v2","openxiangda.workflow.participant.resumed.v2","openxiangda.workflow.participant.cancelled.v2"],tc=new Set(Ro),Co=class extends Error{code;pointer;identifiers;constructor(t,o,n={}){super(t),this.name="NativeConfigurationCompilerError",this.code=t,this.pointer=o,this.identifiers=Object.fromEntries(Object.entries(n).slice(0,8).map(([i,r])=>[i,String(r).slice(0,128)]))}};function Of(e){let t=w(e.appCode,"/appCode",128);Va.test(t)||m("NATIVE_CONFIG_APP_CODE_INVALID","/appCode");let o=wo(e.expectedConfigDigest,"/expectedConfigDigest"),n=wo(e.expectedContractDigest,"/expectedContractDigest"),i=Fr(e.configBytes,Xa,"/configBytes","NATIVE_CONFIG_ARTIFACT_TOO_LARGE"),r=Fr(e.contractBytes,Za,"/contractBytes","NATIVE_CONTRACT_ARTIFACT_TOO_LARGE");xr(i,o,"/configBytes","NATIVE_CONFIG_DIGEST_MISMATCH"),xr(r,n,"/contractBytes","NATIVE_CONTRACT_DIGEST_MISMATCH");let c=Lr(i,"/configBytes","NATIVE_CONFIG_JSON_INVALID","NATIVE_CONFIG_NOT_CANONICAL"),s=Lr(r,"/contractBytes","NATIVE_CONTRACT_JSON_INVALID","NATIVE_CONTRACT_NOT_CANONICAL");bo(c,"/config",ye.extendedNodes),bo(s,"/contracts",ye.extendedNodes),dn(c)||bo(s,"/contracts",ye.legacyNodes);let a=c,d=s;rc(a,t),sc(d,t,o);let f=ac(a,o,d.generatorVersion);zc(f,d,a),Q(f)!==Q(d)&&m("NATIVE_CONTRACT_CLOSURE_MISMATCH",So(f,d,"/contracts"));let u={authz:{appCode:t,...a.authz,perspectives:a.perspectives,capabilityCatalog:f.capabilities},data:{appCode:t,resources:a.data.resources,resourceContracts:f.resources,...f.concurrency?{concurrency:f.concurrency}:{},...f.subjectReadSurfaces?{subjectReadSurfaces:f.subjectReadSurfaces}:{}},events:{appCode:t,...a.events,consumers:f.eventConsumers,producers:f.eventProducers,handlerManifest:f.eventHandlerManifest,eventTypes:f.eventTypes,capturePlans:oc({resources:a.data.resources,dataPolicies:a.authz.dataPolicies,subscriptions:f.eventConsumers,capturePolicies:a.events.capturePolicies})},workflows:{appCode:t,...a.workflows,contracts:f.workflows},runtime:{appCode:t,requirements:a.runtime,backend:a.backend,frontend:a.frontend},contracts:f},p={authz:rt(u.authz),data:rt(u.data),events:rt(u.events),workflows:rt(u.workflows),runtime:rt(u.runtime),contracts:rt(u.contracts)},g={configDigest:o,contractDigest:n,generatorVersion:d.generatorVersion},I=nc(a),A={schemaVersion:Nr,compilerContractVersion:Dt,appCode:t,source:g,projections:p,requiredPlatformCapabilities:I,aggregateDigest:Z({schemaVersion:Nr,compilerContractVersion:Dt,appCode:t,source:g,requiredPlatformCapabilities:I,projectionDigests:Object.fromEntries(Object.entries(p).map(([O,b])=>[O,b.digest]))})};return es(A)}function Cr(e,t){let o=e.subject,n=t.find(r=>r.code===o?.resourceCode),i=new Set(Object.values(o?.factProjection||{}));return!!n?.schema?.fields?.some(r=>r.type==="subtable"&&i.has(r.code))}function nc(e){let t=e.authz.roles,o=e.data.resources,n=e.backend.operations,i=n.filter(l=>l.platformAccess?.directory?.mode==="current-initiator"&&l.platformAccess.directory.fields.includes("phone")),r=(e.data.concurrency?.commands||[]).filter(l=>l.execution?.directory?.mode==="current-initiator"&&l.execution.directory.fields.includes("phone")),c=t.some(l=>l.capabilities.some(y=>y.endsWith(":directory:read")))||o.some(l=>l.schema.fields.some(y=>["user.single","user.multiple","department.single","department.multiple"].includes(y.type)))||n.some(l=>l.platformAccess?.directory),s=!!(e.events.subscriptions.length||e.events.timers.length||e.events.dateTriggers.length||e.events.schemas.length),a=n.some(l=>l.platformAccess?.managedFiles||l.platformAccess?.managedFileCopies)||e.events.subscriptions.some(l=>l.platformAccess?.managedFileCopies),d=e.workflows.definitions.some(l=>l.definition.rejectionNotification!==void 0)||n.some(l=>l.platformAccess?.notification)||e.events.subscriptions.some(l=>l.platformAccess?.notification),f=(l,y,R=!1)=>{let h=o.find($=>$.code===l.definition.subject?.resourceCode)?.schema.fields||[];return Object.values(l.definition.taskPages||{}).some($=>$.fields.some(k=>{if(k.readonly)return!1;let M=h.find(Y=>Y.code===k.code);if(!R&&M&&y.includes(M.type))return!0;if(!k.subtable||!M?.subtable)return!1;let L=o.find(Y=>Y.code===M.subtable.resourceCode)?.schema.fields||[];return k.subtable.fields.some(Y=>!Y.readonly&&L.some(ne=>ne.code===Y.code&&y.includes(ne.type)))}))},u=e.workflows.definitions.filter(l=>f(l,["file","image","signature","text.rich"])),p=e.workflows.definitions.filter(l=>f(l,["signature","text.rich"])),g=e.workflows.definitions.filter(l=>f(l,["file","image","signature","text.rich"],!0)),I=e.workflows.definitions.filter(l=>l.launch.mode==="standalone"||l.launch.mode==="hidden-handoff"),A=n.some(l=>l.platformAccess?.workflow)||I.length>0,O=I.filter(l=>{let y=l.launch.submission;if(!y)return!1;let R=o.find(h=>h.code===l.definition.subject.resourceCode);return[y.create,y.existing].some(h=>h&&Object.values(h.inputs).some($=>$.source==="field"&&R?.schema.fields.some(k=>k.code===$.fieldCode&&k.type.startsWith("resource-ref.")&&k.source)))}),b={resources:o},_={perspectives:e.perspectives,authz:e.authz},E={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[...dn(e)?[{code:"application.extended-artifact-capacity",declaration:ye}]:[],...yo(e)?[{code:"application.extended-declaration-capacity",declaration:{resources:e.data.resources.length,policies:e.authz.dataPolicies.length,roles:e.authz.roles.length,capabilities:e.authz.capabilities.length,definitions:e.workflows.definitions.length,bindings:e.workflows.bindings.length,activations:e.workflows.activations.length,routes:e.frontend.routes.length,navigationItems:e.frontend.admin.navigation.reduce((l,y)=>l+y.items.length,0)}}]:[],...o.some(l=>l.uniqueKeys?.length)?[{code:"data.unique-keys",declaration:o.filter(l=>l.uniqueKeys?.length).map(l=>({code:l.code,uniqueKeys:l.uniqueKeys}))}]:[],...e.data.concurrency?[{code:"data.managed-concurrency",declaration:e.data.concurrency}]:[],...e.data.concurrency?.commands.some(l=>l.mode==="durable")?[{code:"data.managed-concurrency.durable",declaration:e.data.concurrency}]:[],...o.some(l=>l.decimalReservationLifecycle)?[{code:"data.decimal-reservation-lifecycle",declaration:o.filter(l=>l.decimalReservationLifecycle).map(l=>({code:l.code,decimalReservationLifecycle:l.decimalReservationLifecycle}))}]:[],...n.some(l=>l.platformAccess?.dataCommands)?[{code:"data.business-commands",declaration:n.filter(l=>l.platformAccess?.dataCommands)}]:[],...e.authz.dataPolicies.some(l=>l.publicRead)?[{code:"data.authenticated-public-projection",declaration:e.authz.dataPolicies.filter(l=>l.publicRead)}]:[],...n.some(l=>l.platformAccess?.roleAssertions?.actorAuthority)?[{code:"data.transaction-actor-authority",declaration:n.filter(l=>l.platformAccess?.roleAssertions?.actorAuthority)}]:[],...n.some(l=>l.platformAccess?.workflowStage)?[{code:"workflow.native-stage-guard",declaration:n.filter(l=>l.platformAccess?.workflowStage)}]:[],...n.some(l=>l.platformAccess?.recordEdit)?[{code:"data.record-edit",declaration:n.filter(l=>l.platformAccess?.recordEdit)}]:[],...n.some(l=>l.platformAccess?.decimalReservation)||e.events.subscriptions.some(l=>l.platformAccess?.decimalReservation)?[{code:"data.decimal-reservations",declaration:[...n.filter(l=>l.platformAccess?.decimalReservation).map(l=>({code:l.code,decimalReservation:l.platformAccess.decimalReservation})),...e.events.subscriptions.filter(l=>l.platformAccess?.decimalReservation).map(l=>({subscriptionCode:l.code,decimalReservation:l.platformAccess.decimalReservation}))]}]:[],{code:"application-native-2",declaration:E},{code:"authz.native-batch-explain",declaration:_},{code:"authz.native-management",declaration:_},{code:"deployment.durable-runs",declaration:E.backend},{code:"deployment.platform-executor",declaration:E.backend},{code:"environment.on-demand-production",declaration:{environments:["preproduction","production"]}},{code:"environment.runtime-lifecycle",declaration:{environments:["preproduction","production"]}},...o.length?[{code:"data-api-v2",declaration:b},{code:"data.native-golden-crud",declaration:b}]:[],...o.some(l=>l.recordComments!==void 0)?[{code:"data.record-comments",declaration:b}]:[],...o.some(l=>l.recordDeletion!==void 0)?[{code:"data.workflow-record-deletion",declaration:b}]:[],...o.some(l=>l.recordPrint!==void 0)?[{code:"data.record-print",declaration:b}]:[],...o.some(l=>l.workflowHistory!==void 0)?[{code:"workflow.record-history-read",declaration:b}]:[],...o.some(Zo)?[{code:"data.audit-read-access",declaration:b}]:[],...c?[{code:"directory-v2",declaration:{roles:t.map(l=>({code:l.code,capabilities:l.capabilities.filter(y=>y.endsWith(":directory:read"))})),resources:o.map(l=>({code:l.code,fields:l.schema.fields.filter(y=>["user.single","user.multiple","department.single","department.multiple"].includes(y.type))})),operations:n.filter(l=>l.platformAccess?.directory).map(l=>({code:l.code,directory:l.platformAccess.directory}))}}]:[],...n.some(l=>l.platformAccess?.directory?.mode==="selected-user")?[{code:"directory.selected-user",declaration:n.filter(l=>l.platformAccess?.directory?.mode==="selected-user").map(l=>({code:l.code,directory:l.platformAccess.directory}))}]:[],...i.length||r.length?[{code:"directory.current-initiator-phone",declaration:{operations:i.map(l=>({code:l.code,directory:l.platformAccess.directory})),commands:r.map(l=>({code:l.code,directory:l.execution.directory}))}}]:[],...a?[{code:"data.managed-files",declaration:{operations:n.filter(l=>l.platformAccess?.managedFiles||l.platformAccess?.managedFileCopies).map(l=>({code:l.code,...l.platformAccess?.managedFiles?{managedFiles:l.platformAccess.managedFiles}:{},...l.platformAccess?.managedFileCopies?{managedFileCopies:l.platformAccess.managedFileCopies}:{}})),subscriptions:e.events.subscriptions.filter(l=>l.platformAccess?.managedFileCopies).map(l=>({code:l.code,managedFileCopies:l.platformAccess.managedFileCopies}))}}]:[],...e.events.subscriptions.some(l=>l.execution)?[{code:"events.native-data-actions",declaration:e.events.subscriptions.filter(l=>l.execution)}]:[],...e.events.capturePolicies?.length?[{code:"events.capture-policy",declaration:e.events.capturePolicies}]:[],...e.events.dateTriggers.some(l=>sr(l.resourceCode,e.events.subscriptions.filter(y=>y.eventTypes.includes(l.eventType)),e.data.resources.find(y=>y.code===l.resourceCode)).length>0)?[{code:"events.date-source-projection",declaration:{triggers:e.events.dateTriggers,subscriptions:e.events.subscriptions}}]:[],...s?[{code:"events-v2",declaration:e.events},{code:"events.durable-receipts",declaration:e.events}]:[],...Rn(e.data.resources)?[{code:"data.extended-owned-subtable-capacity",declaration:e.data.resources.filter(l=>Rn([l]))}]:[],...e.data.resources.some(l=>l.schema.fields.some(y=>y.userCandidates!==void 0))?[{code:"data.user-candidates",declaration:e.data.resources.filter(l=>l.schema.fields.some(y=>y.userCandidates!==void 0))}]:[],...qi(e.workflows.bindings)?[{code:"workflow.role-union",declaration:e.workflows.bindings.filter(l=>Object.values(l.binding.bindings).some(y=>y.roleCodes!==void 0))}]:[],...e.backend.operations.some(l=>l.platformAccess?.ownedSubject)?[{code:"workflow.named-owned-create",declaration:e.backend.operations.filter(l=>l.platformAccess?.ownedSubject)}]:[],...Tn(e.data.resources)?[{code:"data.user-candidate-launch-scope",declaration:e.data.resources.filter(l=>Tn([l]))}]:[],...Dn(e.data.resources)?[{code:"data.subtable-minimum-rows",declaration:e.data.resources.filter(l=>Dn([l]))}]:[],...Sn(e.data.resources)?[{code:"data.datetime-minute-precision",declaration:e.data.resources.filter(l=>Sn([l]))}]:[],...e.workflows.activations.length?[{code:"workflow-kernel-v2",declaration:e.workflows},{code:"workflow.fresh-command-token",declaration:e.workflows}]:[],...e.workflows.definitions.some(l=>l.definition.instanceCommands!==void 0)?[{code:"workflow.instance-cancellation-policy",declaration:e.workflows.definitions.filter(l=>l.definition.instanceCommands!==void 0)}]:[],...e.workflows.definitions.some(l=>l.definition.instanceCommands?.withdraw?.reasonRequired===!1)?[{code:"workflow.optional-withdrawal-reason",declaration:e.workflows.definitions.filter(l=>l.definition.instanceCommands?.withdraw?.reasonRequired===!1)}]:[],...e.workflows.definitions.some(l=>l.definition.rejectionNotification!==void 0)?[{code:"workflow.rejection-notification",declaration:e.workflows.definitions.filter(l=>l.definition.rejectionNotification!==void 0)}]:[],...e.workflows.definitions.some(l=>l.definition.commandHandlers!==void 0)||n.some(l=>l.platformAccess?.workflow?.businessCommands)?[{code:"workflow.business-data-command",declaration:{definitions:e.workflows.definitions.filter(l=>l.definition.commandHandlers!==void 0),operations:n.filter(l=>l.platformAccess?.workflow?.businessCommands)}}]:[],...e.workflows.definitions.some(l=>l.definition.commandHandlers?.resubmit)||n.some(l=>l.platformAccess?.workflow?.businessCommands?.includes("resubmit"))?[{code:"workflow.correction-business-command",declaration:{definitions:e.workflows.definitions.filter(l=>l.definition.commandHandlers?.resubmit),operations:n.filter(l=>l.platformAccess?.workflow?.businessCommands?.includes("resubmit"))}}]:[],...e.workflows.definitions.some(l=>l.definition.launchPreflight!==void 0)?[{code:"workflow.launch-preflight",declaration:e.workflows.definitions.filter(l=>l.definition.launchPreflight!==void 0)}]:[],...e.workflows.definitions.some(l=>l.definition.approvedDelegation!==void 0)?[{code:"workflow.approved-delegation",declaration:e.workflows.definitions.filter(l=>l.definition.approvedDelegation!==void 0)}]:[],...e.workflows.definitions.some(l=>Cr(l.definition,e.data.resources))?[{code:"workflow.owned-initial-facts",declaration:e.workflows.definitions.filter(l=>Cr(l.definition,e.data.resources))}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.nodes).some(y=>y.kind==="correction"))?[{code:"workflow.initiator-correction",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.nodes).some(y=>y.kind==="correction"))}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.nodes).some(y=>y.operationPolicy?.reject?.commentRequired===!1))?[{code:"workflow.optional-rejection-comment",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.nodes).some(y=>y.operationPolicy?.reject?.commentRequired===!1))}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.nodes).some(y=>Object.values(y.operationPolicy||{}).some(R=>R.reasonRequired===!1)))?[{code:"workflow.optional-operation-reason",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.nodes).some(y=>Object.values(y.operationPolicy||{}).some(R=>R.reasonRequired===!1)))}]:[],...O.length?[{code:"workflow.named-input-sources",declaration:O}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.nodes).some(y=>y.administration!==void 0||y.operationPolicy!==void 0))?[{code:"workflow.node-administration",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.nodes).some(y=>y.administration!==void 0||y.operationPolicy!==void 0))}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.nodes).some(y=>y.kind==="approval"&&y.emptyPolicy!==void 0))?[{code:"workflow.approval-empty-policy",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.nodes).some(y=>y.kind==="approval"&&y.emptyPolicy!==void 0))}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.nodes).some(y=>y.completionDeadline!==void 0))?[{code:"workflow.completion-deadline",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.nodes).some(y=>y.completionDeadline!==void 0))}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.nodes).some(y=>y.initiatorApprovalPolicy!==void 0))?[{code:"workflow.initiator-approval-policy",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.nodes).some(y=>y.initiatorApprovalPolicy!==void 0))}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.nodes).some(y=>y.kind==="cc"))?[{code:"workflow.automatic-cc",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.nodes).some(y=>y.kind==="cc"))}]:[],...e.workflows.definitions.some(l=>l.definition.taskPages!==void 0)?["workflow.task-page-submit","workflow.task-private-drafts"].map(l=>({code:l,declaration:e.workflows.definitions.filter(y=>y.definition.taskPages!==void 0)})):[],...u.length?[{code:"workflow.task-managed-files",declaration:u}]:[],...g.length?[{code:"workflow.task-owned-files",declaration:g}]:[],...p.length?[{code:"workflow.task-rich-fields",declaration:p}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.taskPages||{}).some(y=>y.fields.some(R=>R.subtable)))?[{code:"workflow.task-owned-subtables",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.taskPages||{}).some(y=>y.fields.some(R=>R.subtable)))}]:[],...e.workflows.definitions.some(l=>Object.values(l.definition.nodes).some(y=>y.kind==="action"))?[{code:"workflow.durable-business-step",declaration:e.workflows.definitions.filter(l=>Object.values(l.definition.nodes).some(y=>y.kind==="action"))}]:[],...e.workflows.bindings.some(l=>Object.values(l.binding.bindings).some(y=>y.routing!==void 0))?[{code:"workflow.assignment-routing",declaration:e.workflows.bindings.filter(l=>Object.values(l.binding.bindings).some(y=>y.routing!==void 0))}]:[],...A?[{code:"business-process.durable-command",declaration:{operations:n.filter(l=>l.platformAccess?.workflow).map(l=>({code:l.code,workflow:l.platformAccess.workflow})),definitions:I,activations:e.workflows.activations.filter(l=>I.some(y=>y.definition.code===l.workflowCode))}}]:[],...d?[{code:"notification-hub-v2",declaration:{...e.workflows.definitions.some(l=>l.definition.rejectionNotification!==void 0)?{rejectionNotifications:e.workflows.definitions.filter(l=>l.definition.rejectionNotification!==void 0)}:{},operations:n.filter(l=>l.platformAccess?.notification).map(l=>({code:l.code,notification:l.platformAccess.notification})),subscriptions:e.events.subscriptions.filter(l=>l.platformAccess?.notification).map(l=>({code:l.code,notification:l.platformAccess.notification}))}}]:[],...e.frontend.authentication?[{code:"authentication.application-login-surface",declaration:e.frontend.authentication}]:[],...e.frontend.publicAccess?[{code:"public-access.anonymous-owner-records",declaration:e.frontend.publicAccess}]:[]].map(({code:l,declaration:y})=>({code:l,contractVersion:l==="data.unique-keys"?o.some(R=>Si(R.schema.fields,R.uniqueKeys)==="1.1.0")?"1.1.0":"1.0.0":Ir[l],usageDigest:`sha256:${Z(y)}`})).sort((l,y)=>l.code===y.code?0:l.code<y.code?-1:1)}function oc(e){let t=new Map,o=new Set(e.resources.map(r=>String(r.code)));for(let[r,c]of S(e.capturePolicies===void 0?[]:e.capturePolicies,"/capturePlan/capturePolicies",100).entries()){let s=`/capturePlan/capturePolicies/${r}`,a=N(c,s);C(a,["resourceCode","mode"],s);let d=H(a.resourceCode,`${s}/resourceCode`);o.has(d)||m("NATIVE_EVENT_CAPTURE_RESOURCE_NOT_FOUND",s,{resourceCode:d}),t.has(d)&&m("NATIVE_EVENT_CAPTURE_POLICY_DUPLICATE",s,{resourceCode:d}),a.mode!=="all"&&a.mode!=="subscribed"&&m("NATIVE_EVENT_CAPTURE_MODE_INVALID",`${s}/mode`),t.set(d,a.mode)}let n=new Map(e.dataPolicies.map((r,c)=>{let s=N(r,`/capturePlan/dataPolicies/${c}`);return[String(s.code),s]})),i=e.subscriptions.map((r,c)=>N(r,`/capturePlan/subscriptions/${c}`));return e.resources.map((r,c)=>{let s=`/capturePlan/resources/${c}`,a=N(r,s),d=H(a.code,`${s}/code`),f=a.schema?N(a.schema,`${s}/schema`):a,u=new Set(S(f.fields||[],`${s}/schema/fields`,500).map((y,R)=>G(N(y,`${s}/schema/fields/${R}`).code,`${s}/schema/fields/${R}/code`))),p=a.dataPolicyCode?P(a.dataPolicyCode,`${s}/dataPolicyCode`):null,g=p?n.get(p):void 0;p&&!g&&m("NATIVE_EVENT_CAPTURE_AUTHZ_POLICY_NOT_FOUND",s,{resourceCode:d,dataPolicyCode:p});let I=new Set;for(let y of g?.rules||[])I.add(String(y.field));if(g?.readExpression)for(let y of cn(g.readExpression,`${s}/readExpression`))I.add(String(y.rule.field));let A=new Set,O=new Set,b=new Set;for(let[y,R]of i.entries()){let h=S(R.eventTypes,`/capturePlan/subscriptions/${y}/eventTypes`,20).map(String);if(!h.some(L=>L.startsWith("openxiangda.data.")))continue;let $=N(R.filter||{},`/capturePlan/subscriptions/${y}/filter`),k=Array.isArray($.resourceCodes)?$.resourceCodes.map(String):[];if(k.length&&!k.includes(d))continue;for(let L of h)To.includes(L)&&b.add(L);for(let L of ic($,`/capturePlan/subscriptions/${y}/filter`))A.add(L);let M=N(R.payload||{},`/capturePlan/subscriptions/${y}/payload`);for(let L of S(M.fields||[],`/capturePlan/subscriptions/${y}/payload/fields`,32))O.add(G(L,`/capturePlan/subscriptions/${y}/payload/fields`))}let _=new Set([...A,...O]),E=new Set([..._,...I]);E.size>Rr&&m("NATIVE_EVENT_CAPTURE_FIELDS_LIMIT",s,{resourceCode:d,maximum:Rr});for(let y of E)!u.has(y)&&!(I.has(y)&&Mr.has(y))&&m("NATIVE_EVENT_CAPTURE_FIELD_NOT_FOUND",s,{resourceCode:d,field:y});let T=N(a.fieldPolicies||{},`${s}/fieldPolicies`);for(let y of _)T[y]?.mask==="omit"&&m("NATIVE_EVENT_CAPTURE_FIELD_SENSITIVE",s,{resourceCode:d,field:y});let l={resourceCode:d,...t.get(d)==="subscribed"?{capturedEventTypes:[...b].sort()}:{},filterFields:[...A].sort(),projectionFields:[...O].sort(),authorizationFields:[...I].sort(),captureFields:[...E].sort()};return{...l,digest:Z(l)}}).sort((r,c)=>r.resourceCode.localeCompare(c.resourceCode))}function ic(e,t){let o=new Set;for(let[c,s]of S(e.changes||[],`${t}/changes`,16).entries()){let a=N(s,`${t}/changes/${c}`);o.add(G(a.field,`${t}/changes/${c}/field`))}let n=N(e.changedFields||{},`${t}/changedFields`);for(let c of["anyOf","allOf","noneOf"])for(let[s,a]of S(n[c]||[],`${t}/changedFields/${c}`,32).entries())o.add(G(a,`${t}/changedFields/${c}/${s}`));let i=0,r=(c,s,a)=>{a>3&&m("NATIVE_EVENT_FILTER_DEPTH_LIMIT",s);let d=N(c,s);if(d.change){let u=N(d.change,`${s}/change`);o.add(G(u.field,`${s}/change/field`)),i+=1;return}if(d.not){r(d.not,`${s}/not`,a+1);return}let f=d.all?"all":d.any?"any":null;f||m("NATIVE_EVENT_FILTER_CONDITION_INVALID",s);for(let[u,p]of S(d[f],`${s}/${f}`,16).entries())r(p,`${s}/${f}/${u}`,a+1)};return e.where&&r(e.where,`${t}/where`,1),i+=Array.isArray(e.changes)?e.changes.length:0,i>16&&m("NATIVE_EVENT_FILTER_ATOM_LIMIT",t),[...o].sort()}function rc(e,t){C(e,["schemaVersion","compilerContractVersion","appCode","perspectives","authz","backend","data","events","workflows","frontend","runtime"],"/config"),F(e.schemaVersion,va,"/config/schemaVersion"),F(e.compilerContractVersion,Dt,"/config/compilerContractVersion"),F(e.appCode,t,"/config/appCode"),S(e.perspectives,"/config/perspectives",100);let o=N(e.authz,"/config/authz");C(o,["capabilities","roles","scopeDimensions","scopeSources","roleMembershipSources","relationshipGrantSources","dataPolicies","authorizationTransitions"],"/config/authz",["authenticatedUserRoleCode"]),S(o.capabilities,"/config/authz/capabilities",B.capabilities),S(o.roles,"/config/authz/roles",B.roles),S(o.scopeDimensions,"/config/authz/scopeDimensions",100),S(o.scopeSources,"/config/authz/scopeSources",100),S(o.roleMembershipSources,"/config/authz/roleMembershipSources",100),S(o.relationshipGrantSources,"/config/authz/relationshipGrantSources",100),S(o.dataPolicies,"/config/authz/dataPolicies",B.dataPolicies),S(o.authorizationTransitions,"/config/authz/authorizationTransitions",100);let n=N(e.backend,"/config/backend");C(n,["secrets","operations"],"/config/backend"),S(n.secrets,"/config/backend/secrets",100),S(n.operations,"/config/backend/operations",500),Uc(n.secrets);let i=N(e.data,"/config/data");C(i,["resources"],"/config/data",["resourceDetailRoutes","subjectReadSurfaces","concurrency"]),S(i.resources,"/config/data/resources",B.resources),i.subjectReadSurfaces!==void 0&&S(i.subjectReadSurfaces,"/config/data/subjectReadSurfaces",B.subjectReadSurfaces),i.resourceDetailRoutes!==void 0&&S(i.resourceDetailRoutes,"/config/data/resourceDetailRoutes",100);let r=N(e.events,"/config/events");C(r,["schemas","subscriptions","timers","dateTriggers"],"/config/events",["capturePolicies"]),S(r.schemas,"/config/events/schemas",100),S(r.subscriptions,"/config/events/subscriptions",100),S(r.timers,"/config/events/timers",100),S(r.dateTriggers,"/config/events/dateTriggers",100);let c=N(e.workflows,"/config/workflows");C(c,["definitions","bindings","activations","providers","editableParameters"],"/config/workflows"),S(c.definitions,"/config/workflows/definitions",B.workflows),S(c.bindings,"/config/workflows/bindings",B.workflows),S(c.activations,"/config/workflows/activations",B.workflows),S(c.providers,"/config/workflows/providers",100),S(c.editableParameters,"/config/workflows/editableParameters",100);let s=N(e.frontend,"/config/frontend");C(s,["routes","user","admin","devicePolicy"],"/config/frontend",["authentication","publicAccess"]),S(s.routes,"/config/frontend/routes",B.routes);let a=N(s.user,"/config/frontend/user");C(a,["applicationTodoCenter"],"/config/frontend/user"),at(a.applicationTodoCenter,"/config/frontend/user/applicationTodoCenter"),Do(s.devicePolicy,"/config/frontend/devicePolicy"),Object.prototype.hasOwnProperty.call(s,"authentication")&&Kr(s.authentication,s.routes,e,"/config/frontend/authentication"),Object.prototype.hasOwnProperty.call(s,"publicAccess")&&Oc(s.publicAccess,e,"/config/frontend/publicAccess");let d=N(s.admin,"/config/frontend/admin");C(d,["navigation"],"/config/frontend/admin",["access"]),d.access!==void 0&&_n(d.access,"/config/frontend/admin/access",e.appCode),Cc(d.navigation,"/config/frontend/admin/navigation");let f=N(e.runtime,"/config/runtime");C(f,["protocolCapabilities","health"],"/config/runtime"),V(f.protocolCapabilities,"/config/runtime/protocolCapabilities",100),C(N(f.health,"/config/runtime/health"),["livePath","readyPath","versionPath"],"/config/runtime/health"),F(f.health.livePath,"/__platform/health","/config/runtime/health/livePath"),F(f.health.readyPath,"/__platform/ready","/config/runtime/health/readyPath"),F(f.health.versionPath,"/__platform/version","/config/runtime/health/versionPath")}function sc(e,t,o){C(e,["schemaVersion","compilerContractVersion","generatorVersion","appCode","configDigest","perspectives","resources","capabilities","operations","eventConsumers","eventProducers","eventSchemas","eventHandlerManifest","eventTypes","workflows","routes","routeManifest","adminPages","adminNavigation"],"/contracts",["authentication","publicAccess","adminAccess","subjectReadSurfaces","concurrency"]),F(e.schemaVersion,Wr,"/contracts/schemaVersion"),F(e.compilerContractVersion,Dt,"/contracts/compilerContractVersion"),w(e.generatorVersion,"/contracts/generatorVersion",128),F(e.appCode,t,"/contracts/appCode"),F(e.configDigest,o,"/contracts/configDigest"),S(e.perspectives,"/contracts/perspectives",B.perspectives),S(e.resources,"/contracts/resources",B.resources),e.subjectReadSurfaces!==void 0&&S(e.subjectReadSurfaces,"/contracts/subjectReadSurfaces",B.subjectReadSurfaces),S(e.capabilities,"/contracts/capabilities",B.capabilities),S(e.operations,"/contracts/operations",B.operations),S(e.eventConsumers,"/contracts/eventConsumers",B.eventConsumers),S(e.eventProducers,"/contracts/eventProducers",B.eventProducers),S(e.eventSchemas,"/contracts/eventSchemas",B.eventSchemas),N(e.eventHandlerManifest,"/contracts/eventHandlerManifest"),V(e.eventTypes,"/contracts/eventTypes",B.eventTypes),S(e.workflows,"/contracts/workflows",B.workflows),S(e.routes,"/contracts/routes",B.routes),Object.prototype.hasOwnProperty.call(e,"authentication")&&Ic(e.authentication,"/contracts/authentication"),Object.prototype.hasOwnProperty.call(e,"publicAccess")&&Nc(e.publicAccess,"/contracts/publicAccess"),Object.prototype.hasOwnProperty.call(e,"adminAccess")&&_n(e.adminAccess,"/contracts/adminAccess",t),$c(e.routeManifest,"/contracts/routeManifest",t),Sc(e.adminPages,"/contracts/adminPages"),Dc(e.adminNavigation,"/contracts/adminNavigation")}function ac(e,t,o){let n=lc(e);Fc(e,n),jc(e),xc(e),Mc(e);let i=e.events.schemas.map((_,E)=>{let T=`/config/events/schemas/${E}`,l=N(_,T),y=w(l.eventType,`${T}/eventType`,255);return y.startsWith("openxiangda.")&&m("NATIVE_EVENT_SCHEMA_RESERVED",`${T}/eventType`,{eventType:y}),F(l.schemaDigest,Z(N(l.jsonSchema,`${T}/jsonSchema`)),`${T}/schemaDigest`),l}),r=new Set([...To,...Ro,...i.map(_=>String(_.eventType))]),c=new Map(e.data.resources.map(_=>[String(_.code),new Map(_.schema.fields.map(E=>[String(E.code),String(E.type)]))])),s=ee(e.events.subscriptions.map((_,E)=>{let T=`/config/events/subscriptions/${E}`,l=N(_,T),y=V(l.eventTypes,`${T}/eventTypes`,20);y.forEach((k,M)=>{r.has(k)||m("NATIVE_EVENT_TYPE_NOT_REGISTERED",`${T}/eventTypes/${M}`,{eventType:k})});let R=vi(l,e.data.resources,T),h=dc(l.delivery,y,`${T}/delivery`),$=cc(l.platformAccess,`${T}/platformAccess`,c,e,l);return{code:P(l.code,`${T}/code`),endpointPath:be(l.endpointPath,`${T}/endpointPath`),eventTypes:y,filter:N(l.filter,`${T}/filter`),payload:R?.payload||N(l.payload,`${T}/payload`),...R?{execution:R.execution}:{},...$?{platformAccess:$}:{},delivery:h}}),_=>_.code),a=new Map(i.map(_=>[String(_.eventType),String(_.dataSchemaVersion)])),d=ee([...e.data.resources.flatMap(_=>To.map(E=>({code:`data:${_.code}:${E}`,source:"data",eventType:E,dataSchemaVersion:"2.0.0",resourceCode:_.code}))),...i.map(_=>({code:`app:${_.eventType}`,source:"app",eventType:_.eventType,dataSchemaVersion:_.dataSchemaVersion})),...e.events.timers.map(_=>({code:_.code,source:"timer",eventType:_.eventType,dataSchemaVersion:a.get(String(_.eventType))||"2.0.0"})),...e.events.dateTriggers.map(_=>({code:_.code,source:"date",eventType:_.eventType,dataSchemaVersion:a.get(String(_.eventType))||"2.0.0",resourceCode:_.resourceCode,field:_.field})),...e.workflows.activations.length?Ro.filter(_=>!xi.includes(_)||e.workflows.definitions.some(E=>Object.values(E.definition.nodes).some(T=>T.kind==="action"))).filter(_=>_!=="openxiangda.workflow.node.skipped.v2"||e.workflows.definitions.some(E=>Object.values(E.definition.nodes).some(T=>T.kind==="approval"&&T.emptyPolicy==="skip"))).map(_=>({code:`workflow:${_}`,source:"workflow",eventType:_,dataSchemaVersion:"2.0.0"})):[]],_=>`${_.source}:${_.code}:${_.eventType}`),f=U([...s.flatMap(_=>_.eventTypes),...d.map(_=>String(_.eventType))]);wc(e);let u=zr(e),p;try{p=li(e.data.concurrency,e.data.resources,n)}catch(_){throw _ instanceof pt&&m(_.code,_.pointer,{reason:_.reason}),_}p?.commands.some(_=>_.mode==="durable")&&e.backend?.enabled===!1&&m("NATIVE_MANAGED_CONCURRENCY_INVALID","/data/concurrency",{reason:"durable commands require backend runtime"});let g=fc(e,n),I=Br(e),A=e.workflows.definitions.map(_=>_.definition),O=oo(A),b=Mi(A,s,!0);b.length&&m(b[0],"/config/events/subscriptions");try{fi(e.data.resources,I)}catch(_){throw _ instanceof nt&&m(_.code,_.pointer,{reason:_.reason}),_}return{schemaVersion:Wr,compilerContractVersion:Dt,generatorVersion:o,appCode:e.appCode,configDigest:t,perspectives:e.perspectives,resources:uc(e),...g.length?{subjectReadSurfaces:g}:{},...p?{concurrency:p}:{},capabilities:ee(n,_=>_.code),operations:I,eventConsumers:s,eventProducers:d,eventSchemas:i,eventHandlerManifest:{schemaVersion:ec,appCode:e.appCode,handlers:s.filter(_=>!_.execution).map(_=>({code:_.code,endpointPath:_.endpointPath,eventTypes:_.eventTypes,dataSchemaVersions:U(_.eventTypes.map(E=>E.startsWith("openxiangda.")?"2.0.0":a.get(E)||"2.0.0")),maxBodyBytes:65536,receiptProtocolVersion:2,...O[_.code]?{workflowStep:O[_.code]}:{}}))},eventTypes:f,workflows:Yr(e),routes:mn(e),...Object.prototype.hasOwnProperty.call(e.frontend,"authentication")?{authentication:yc(e)}:{},...Object.prototype.hasOwnProperty.call(e.frontend,"publicAccess")?{publicAccess:Tc(e)}:{},...e.frontend.admin.access?{adminAccess:e.frontend.admin.access}:{},routeManifest:Vc(e),adminPages:u,adminNavigation:Rc(e)}}function cc(e,t,o,n,i){if(e===void 0)return;let r=N(e,t);C(r,["notification","managedFileCopies","decimalReservation"],t,!0);let c={};if(r.decimalReservation!==void 0)try{c.decimalReservation=ki(r.decimalReservation,$i(n,i))}catch{m("NATIVE_EVENT_DECIMAL_RESERVATION_INVALID",`${t}/decimalReservation`)}if(r.notification!==void 0){let s=N(r.notification,`${t}/notification`);C(s,["mode"],`${t}/notification`),F(s.mode,"business-standard",`${t}/notification/mode`),c.notification={mode:"business-standard"}}if(r.managedFileCopies!==void 0){let s=S(r.managedFileCopies,`${t}/managedFileCopies`,16);s.length||m("NATIVE_EVENT_MANAGED_FILE_COPIES_REQUIRED",`${t}/managedFileCopies`);let a=new Set;c.managedFileCopies=ee(s.map((d,f)=>{let u=`${t}/managedFileCopies/${f}`,p=N(d,u);C(p,["mode","sourceResourceCode","sourceFieldCodes","targetResourceCode","targetFieldCodes"],u),F(p.mode,"copy",`${u}/mode`);let g=H(p.sourceResourceCode,`${u}/sourceResourceCode`),I=H(p.targetResourceCode,`${u}/targetResourceCode`),A=o.get(g),O=o.get(I);(!A||!O)&&m("NATIVE_EVENT_MANAGED_FILE_COPY_RESOURCE_INVALID",u);let b=V(p.sourceFieldCodes,`${u}/sourceFieldCodes`,16),_=V(p.targetFieldCodes,`${u}/targetFieldCodes`,16);(!b.length||b.length!==_.length)&&m("NATIVE_EVENT_MANAGED_FILE_COPY_FIELDS_INVALID",u),b.forEach((T,l)=>{let y=A.get(T),R=O.get(_[l]);(!["file","image"].includes(String(y))||y!==R)&&m("NATIVE_EVENT_MANAGED_FILE_COPY_FIELD_INVALID",`${u}/sourceFieldCodes/${l}`)});let E=`${g}:${b.join(",")}=>${I}:${_.join(",")}`;return a.has(E)&&m("NATIVE_EVENT_MANAGED_FILE_COPY_DUPLICATE",u),a.add(E),{mode:"copy",sourceResourceCode:g,sourceFieldCodes:U(b),targetResourceCode:I,targetFieldCodes:U(_)}}),d=>`${d.sourceResourceCode}:${d.sourceFieldCodes.join(",")}=>${d.targetResourceCode}:${d.targetFieldCodes.join(",")}`)}return Object.keys(c).length||m("NATIVE_EVENT_PLATFORM_ACCESS_EMPTY",t),c}function dc(e,t,o){let n=N(e,o);C(n,["timeoutMs","maxAttempts","initialBackoffMs","maxBackoffMs","ordering","concurrency"],o),ie(n.timeoutMs,`${o}/timeoutMs`,1e3,3e4),ie(n.maxAttempts,`${o}/maxAttempts`,1,12);let i=ie(n.initialBackoffMs,`${o}/initialBackoffMs`,1e3,3e5);ie(n.maxBackoffMs,`${o}/maxBackoffMs`,i,18e5),ie(n.concurrency,`${o}/concurrency`,1,50);let r=w(n.ordering,`${o}/ordering`,32);return["none","record","workflow-instance"].includes(r)||m("NATIVE_EVENT_DELIVERY_ORDERING_INVALID",`${o}/ordering`),r==="workflow-instance"&&t.some(c=>!tc.has(c))&&m("NATIVE_EVENT_WORKFLOW_ORDERING_REQUIRES_WORKFLOW_FACTS",`${o}/ordering`),n}function lc(e){let t=new Map;for(let r of Qr(e.appCode))t.set(r.code,r);for(let[r,c]of e.authz.capabilities.entries()){let s=`/config/authz/capabilities/${r}`,a=N(c,s);C(a,["code","kind","name","description"],s,!0);let d=pe(a.code,`${s}/code`,e.appCode);t.has(d)&&m("NATIVE_CAPABILITY_DUPLICATE",`${s}/code`),["backend","ui"].includes(a.kind)||m("NATIVE_CAPABILITY_KIND_INVALID",`${s}/kind`);let f={code:d,kind:a.kind,name:w(a.name,`${s}/name`,255),source:"explicit",...a.description===void 0?{}:{description:$o(a.description,`${s}/description`,2e3)}};t.set(d,f)}let o=e.data.resources.map((r,c)=>({pointer:`/config/data/resources/${c}`,resource:Je(r,`/config/data/resources/${c}`,e.appCode)}));for(let{pointer:r,resource:c}of o){let s={read:`\u8BFB\u53D6${c.name}`,create:`\u65B0\u5EFA${c.name}`,update:`\u66F4\u65B0${c.name}`,delete:`\u5220\u9664${c.name}`};for(let a of["read","create","update","delete"]){let d=pe(c.capabilities[a],`${r}/capabilities/${a}`,e.appCode);t.has(d)&&m("NATIVE_CAPABILITY_DUPLICATE",`${r}/capabilities/${a}`),t.set(d,{code:d,kind:"data",name:s[a],source:"data"})}}let n=new Set(t.keys()),i=new Map;for(let{pointer:r,resource:c}of o)for(let[s,a]of Object.entries(c.fieldPolicies)){if(lt(s))continue;let d=N(a,`${r}/fieldPolicies/${s}`);for(let f of["read","create","update"])if(Array.isArray(d[f]))for(let u of V(d[f],`${r}/fieldPolicies/${s}/${f}`,2e3)){if(pe(u,`${r}/fieldPolicies/${s}/${f}`,e.appCode),n.has(u))continue;let p=i.get(u);p&&p!==c.code&&m("NATIVE_CAPABILITY_DUPLICATE",`${r}/fieldPolicies/${s}/${f}`),i.set(u,c.code),!t.has(u)&&t.set(u,{code:u,kind:"data",name:`${c.name}.${s}.${f}`,source:"data"})}}return[...t.values()]}function uc(e){let t=pc(e);return ee(e.data.resources.map((o,n)=>{let i=Je(o,`/config/data/resources/${n}`,e.appCode),r=t.get(i.code);return{code:i.code,schemaDigest:Z(i.schema),fields:ee(i.schema.fields.map(c=>({code:c.code,type:c.type})),c=>c.code),...r?{detailRouteCode:r}:{}}}),o=>o.code)}function fc(e,t){if(e.data.subjectReadSurfaces===void 0)return[];let o=S(e.data.subjectReadSurfaces,"/config/data/subjectReadSurfaces",B.subjectReadSurfaces),n=new Set(t.map(c=>String(c.code))),i=new Map(e.data.resources.map((c,s)=>{let a=`/config/data/resources/${s}`,d=Je(c,a,e.appCode);return[String(d.code),{resource:d,fields:new Map(S(N(d.schema,`${a}/schema`).fields,`${a}/schema/fields`,500).map(f=>{let u=N(f,`${a}/schema/fields`);return[String(u.code),u]}))}]})),r=new Set;return ee(o.map((c,s)=>{let a=`/config/data/subjectReadSurfaces/${s}`,d=N(c,a);C(d,["code","name","capability","subject","relations"],a);let f=P(d.code,`${a}/code`);r.has(f)&&m("NATIVE_SUBJECT_READ_SURFACE_CODE_DUPLICATE",`${a}/code`),r.add(f);let u=pe(d.capability,`${a}/capability`,e.appCode);n.has(u)||m("NATIVE_SUBJECT_READ_SURFACE_CAPABILITY_NOT_DECLARED",`${a}/capability`);let p=N(d.subject,`${a}/subject`);C(p,["resourceCode","fields"],`${a}/subject`);let g=H(p.resourceCode,`${a}/subject/resourceCode`),I=i.get(g);I||m("NATIVE_SUBJECT_READ_SURFACE_RESOURCE_NOT_DECLARED",`${a}/subject/resourceCode`);let A=V(p.fields,`${a}/subject/fields`,100).map((T,l)=>G(T,`${a}/subject/fields/${l}`));A.length||m("NATIVE_SUBJECT_READ_SURFACE_FIELDS_REQUIRED",`${a}/subject/fields`);for(let[T,l]of A.entries()){let y=I.fields.get(l);(!y||y.type==="subtable")&&m("NATIVE_SUBJECT_READ_SURFACE_FIELD_INVALID",`${a}/subject/fields/${T}`)}let O=S(d.relations,`${a}/relations`,8);O.length||m("NATIVE_SUBJECT_READ_SURFACE_RELATIONS_REQUIRED",`${a}/relations`);let b=new Set,_=0,E=ee(O.map((T,l)=>{let y=`${a}/relations/${l}`,R=N(T,y);C(R,["code","resourceCode","foreignKeyField","fields","limit"],y,["order"]);let h=P(R.code,`${y}/code`);b.has(h)&&m("NATIVE_SUBJECT_READ_SURFACE_RELATION_CODE_DUPLICATE",`${y}/code`),b.add(h);let $=H(R.resourceCode,`${y}/resourceCode`),k=i.get($);k||m("NATIVE_SUBJECT_READ_SURFACE_RESOURCE_NOT_DECLARED",`${y}/resourceCode`);let M=G(R.foreignKeyField,`${y}/foreignKeyField`),L=k.fields.get(M),Y=N(L?.source||{},`${y}/foreignKeyField/source`);(!L||!["uuid","resource-ref.single"].includes(String(L.type))||L.type==="resource-ref.single"&&(Y.kind!=="resource"||Y.resourceCode!==g))&&m("NATIVE_SUBJECT_READ_SURFACE_RELATION_INVALID",`${y}/foreignKeyField`);let ne=V(R.fields,`${y}/fields`,100).map((le,v)=>G(le,`${y}/fields/${v}`));ne.length||m("NATIVE_SUBJECT_READ_SURFACE_FIELDS_REQUIRED",`${y}/fields`);for(let[le,v]of ne.entries()){let W=k.fields.get(v);(!W||W.type==="subtable")&&m("NATIVE_SUBJECT_READ_SURFACE_FIELD_INVALID",`${y}/fields/${le}`)}let X=S(R.order||[],`${y}/order`,10).map((le,v)=>{let W=`${y}/order/${v}`,x=N(le,W);C(x,["field","direction"],W);let q=G(x.field,`${W}/field`),z=k.fields.get(q);return(!Mr.has(q)&&!z||z?.type==="subtable"||z&&!ft(z.type))&&m("NATIVE_SUBJECT_READ_SURFACE_ORDER_FIELD_INVALID",`${W}/field`),["asc","desc"].includes(String(x.direction))||m("NATIVE_SUBJECT_READ_SURFACE_ORDER_DIRECTION_INVALID",`${W}/direction`),{field:q,direction:x.direction}}),de=ie(R.limit,`${y}/limit`,1,100);return _+=de,{code:h,resourceCode:$,foreignKeyField:M,fields:U(ne),...X.length?{order:X}:{},limit:de}}),T=>T.code);return _>400&&m("NATIVE_SUBJECT_READ_SURFACE_ROW_LIMIT_EXCEEDED",`${a}/relations`),{code:f,name:w(d.name,`${a}/name`,255),capability:u,subject:{resourceCode:g,fields:U(A)},relations:E}}),c=>c.code)}function pc(e){let t=e.data.resourceDetailRoutes===void 0?[]:S(e.data.resourceDetailRoutes,"/config/data/resourceDetailRoutes",100),o=new Map(e.data.resources.map((r,c)=>{let s=`/config/data/resources/${c}`,a=Je(r,s,e.appCode);return[a.code,a]})),n=new Map(mn(e).map(r=>[String(r.code),r])),i=new Map;for(let[r,c]of t.entries()){let s=`/config/data/resourceDetailRoutes/${r}`,a=N(c,s);C(a,["resourceCode","desktop","mobile"],s);let d=H(a.resourceCode,`${s}/resourceCode`);i.has(d)&&m("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_DUPLICATE",`${s}/resourceCode`);let f=o.get(d);f||m("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_RESOURCE_MISSING",`${s}/resourceCode`);let u=P(a.desktop,`${s}/desktop`),p=P(a.mobile,`${s}/mobile`);u===p&&m("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_INVALID",s);let g=String(f.capabilities.read);for(let[I,A]of[["desktop",u],["mobile",p]]){let O=`${s}/${I}`,b=n.get(A);b||m("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_REFERENCE_MISSING",O),b.surface!=="user"&&m("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_SURFACE_INVALID",O);let _=be(b.path,`${O}/path`),E=[..._.matchAll(/:([A-Za-z][A-Za-z0-9_]*)/g)],T=I==="mobile"?!_.startsWith("/m/"):_==="/m"||_.startsWith("/m/");(_.includes("*")||_.includes("?")||_.includes("#")||_.split("/").includes("..")||E.length!==1||T)&&m("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_PATH_INVALID",O);let l=Array.isArray(b.access?.allOf)?b.access.allOf:[];b.capability!==g&&!l.includes(g)&&m("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_CAPABILITY_INVALID",O)}i.set(d,{desktop:u,mobile:p})}return i}function Br(e){let t=new Map(e.data.resources.map((c,s)=>{let a=`/config/data/resources/${s}`,d=Je(c,a,e.appCode);return[d.code,new Map(d.schema.fields.map(f=>[String(f.code),f]))]})),o=new Map(e.data.resources.map((c,s)=>{let a=`/config/data/resources/${s}`,d=Je(c,a,e.appCode);return[d.code,new Map(d.schema.fields.map(f=>[String(f.code),String(f.type)]))]})),n=new Set(o.keys()),i=new Set(e.workflows.activations.map((c,s)=>gn(N(c,`/config/workflows/activations/${s}`).workflowCode,`/config/workflows/activations/${s}/workflowCode`))),r=new Map;return ee(e.backend.operations.map((c,s)=>{let a=`/config/backend/operations/${s}`,d=N(c,a);C(d,["code","method","path","capability","requestSchema","responseSchema","description","platformAccess","browser","ai"],a,!0);let f=w(d.method,`${a}/method`,16);["GET","POST","PUT","PATCH","DELETE"].includes(f)||m("NATIVE_OPERATION_METHOD_INVALID",`${a}/method`);let u=P(d.code,`${a}/code`);Ac(d.ai,a,u,f,n);let p=gc(d.platformAccess,`${a}/platformAccess`,o,t,i,new Set(e.authz.roles.map(I=>String(I.code))));if(p?.workflowStage){let I=p.workflowStage,A=e.workflows.definitions.find(O=>O.definition.code===I.workflowCode);(!A||A.definition.subject?.resourceCode!==I.resourceCode||I.runningNodeIds.some(O=>!A.definition.nodes[O]))&&m("NATIVE_WORKFLOW_STAGE_NODE_INVALID",`${a}/platformAccess/workflowStage/runningNodeIds`)}if(p?.recordEdit){let I=e.data.resources.find(A=>A.code===p.recordEdit.resourceCode);I?.surface?.mutationOwner!=="action"&&m("NATIVE_RECORD_EDIT_ACTION_OWNER_REQUIRED",`${a}/platformAccess/recordEdit`);for(let A of p.recordEdit.fieldCodes)(!I.fieldPolicies?.[A]?.update?.length||I.surface?.fields?.[A]?.system===!0)&&m("NATIVE_RECORD_EDIT_FIELD_INVALID",`${a}/platformAccess/recordEdit/fieldCodes`)}if(p?.decimalReservation){let I=p.decimalReservation,A=String(I.resourceCode),O=JSON.stringify([I.amountFieldCode,I.currencyFieldCode,I.relationFieldCode,I.parentFieldCode,I.rootFieldCode,I.statusFieldCode,I.parentRelationValue,I.childRelationValue]),b=r.get(A);b&&b!==O&&m("NATIVE_DECIMAL_RESERVATION_MAPPING_CONFLICT",`${a}/platformAccess/decimalReservation`),r.set(A,O)}let g=mc(d.browser,`${a}/browser`,f,d.requestSchema,d.responseSchema,o,t,e.data.subjectReadSurfaces||[]);return{code:u,method:f,path:be(d.path,`${a}/path`),requiredCapability:pe(d.capability,`${a}/capability`,e.appCode),requestSchemaDigest:Z(N(d.requestSchema,`${a}/requestSchema`)),responseSchemaDigest:Z(N(d.responseSchema,`${a}/responseSchema`)),...d.description===void 0?{}:{description:$o(d.description,`${a}/description`,2e3)},...p?{platformAccess:p}:{},...g?{browser:g}:{}}}),c=>c.code)}function mc(e,t,o,n,i,r,c,s){if(e===void 0)return null;let a=N(e,t);C(a,["exposure","behavior","idempotency","subject"],t,["refreshTargets","fileIntent"]),F(a.exposure,"authenticated",`${t}/exposure`);let d=w(a.behavior,`${t}/behavior`,32);["read","controlled"].includes(d)||m("NATIVE_OPERATION_BROWSER_BEHAVIOR_INVALID",`${t}/behavior`);let f=w(a.idempotency,`${t}/idempotency`,32);(!["none","required"].includes(f)||d==="controlled"&&f!=="required"||d==="read"&&f!=="none")&&m("NATIVE_OPERATION_BROWSER_IDEMPOTENCY_INVALID",`${t}/idempotency`);let u=N(a.subject,`${t}/subject`);C(u,["resourceCode","inputField"],`${t}/subject`);let p=H(u.resourceCode,`${t}/subject/resourceCode`);r.has(p)||m("NATIVE_OPERATION_BROWSER_SUBJECT_RESOURCE_NOT_DECLARED",`${t}/subject/resourceCode`);let g=G(u.inputField,`${t}/subject/inputField`),I=N(n,`${t}/requestSchema`),A=N(i,`${t}/responseSchema`);(I.type!=="object"||I.additionalProperties!==!1||A.type!=="object"||A.additionalProperties!==!1)&&m("NATIVE_OPERATION_BROWSER_SCHEMA_ROOT_INVALID",`${t}/requestSchema`);let O=N(I.properties,`${t}/requestSchema/properties`),b=new Set(I.required===void 0?[]:V(I.required,`${t}/requestSchema/required`,200));(!(g in O)||!b.has(g))&&m("NATIVE_OPERATION_BROWSER_SUBJECT_INPUT_INVALID",`${t}/subject/inputField`);let _=N(O[g],`${t}/requestSchema/properties/${g}`);(_.type!=="string"||_.format!=="uuid")&&m("NATIVE_OPERATION_BROWSER_SUBJECT_INPUT_INVALID",`${t}/subject/inputField`);let E=new Map((Array.isArray(s)?s:[]).map((h,$)=>{let k=N(h,`/config/data/subjectReadSurfaces/${$}`);return[String(k.code),String(N(k.subject,`/config/data/subjectReadSurfaces/${$}/subject`).resourceCode)]})),T=a.refreshTargets===void 0?[]:S(a.refreshTargets,`${t}/refreshTargets`,16),l=new Set,y=ee(T.map((h,$)=>{let k=`${t}/refreshTargets/${$}`,M=N(h,k);C(M,["kind","code"],k),F(M.kind,"subject-surface",`${k}/kind`);let L=P(M.code,`${k}/code`);return(l.has(L)||!E.has(L)||E.get(L)!==p)&&m("NATIVE_OPERATION_BROWSER_REFRESH_TARGET_INVALID",`${k}/code`),l.add(L),{kind:"subject-surface",code:L}}),h=>`${h.kind}:${h.code}`),R=_c(a.fileIntent,`${t}/fileIntent`,o,d,f,p,O,b,c);return{exposure:"authenticated",behavior:d,idempotency:f,subject:{resourceCode:p,inputField:g},...y.length?{refreshTargets:y}:{},...R?{fileIntent:R}:{}}}function _c(e,t,o,n,i,r,c,s,a){if(e===void 0)return null;let d=N(e,t);C(d,["recordResourceCode","recordIdInputField","relationField","fileNameField","contentTypeField","sizeField","purposes","maxTtlSeconds","maxBytes"],t),(o!=="GET"||n!=="read"||i!=="none")&&m("NATIVE_OPERATION_FILE_INTENT_BEHAVIOR_INVALID",t);let f=H(d.recordResourceCode,`${t}/recordResourceCode`),u=a.get(f);u||m("NATIVE_OPERATION_FILE_INTENT_RESOURCE_NOT_DECLARED",`${t}/recordResourceCode`);let p=G(d.recordIdInputField,`${t}/recordIdInputField`),g=N(c[p],`${t}/recordIdInputField`);(!s.has(p)||g.type!=="string"||g.format!=="uuid")&&m("NATIVE_OPERATION_FILE_INTENT_RECORD_INPUT_INVALID",`${t}/recordIdInputField`);let I=G(d.relationField,`${t}/relationField`),A=u.get(I);(!A||!["uuid","resource-ref.single"].includes(String(A.type))||String(A.type)==="resource-ref.single"&&(String(N(A.source,`${t}/relationField`).kind||"")!=="resource"||String(N(A.source,`${t}/relationField`).resourceCode||"")!==r))&&m("NATIVE_OPERATION_FILE_INTENT_RELATION_INVALID",`${t}/relationField`);let O=[["fileNameField",["text.short","text.long"]],["contentTypeField",["text.short","text.long"]],["sizeField",["number.integer"]]],b={};for(let[l,y]of O){let R=G(d[l],`${t}/${l}`);y.includes(String(u.get(R)?.type))||m("NATIVE_OPERATION_FILE_INTENT_METADATA_INVALID",`${t}/${l}`),b[l]=R}let _=ee(V(d.purposes,`${t}/purposes`,2),l=>l);(!_.length||_.some(l=>!["preview","download"].includes(l)))&&m("NATIVE_OPERATION_FILE_INTENT_PURPOSE_INVALID",`${t}/purposes`);let E=Number(d.maxTtlSeconds);(!Number.isSafeInteger(E)||E<1||E>300)&&m("NATIVE_OPERATION_FILE_INTENT_TTL_INVALID",`${t}/maxTtlSeconds`);let T=Number(d.maxBytes);return(!Number.isSafeInteger(T)||T<1||T>104857600)&&m("NATIVE_OPERATION_FILE_INTENT_SIZE_INVALID",`${t}/maxBytes`),{recordResourceCode:f,recordIdInputField:p,relationField:I,fileNameField:b.fileNameField,contentTypeField:b.contentTypeField,sizeField:b.sizeField,purposes:_,maxTtlSeconds:E,maxBytes:T}}function gc(e,t,o,n,i,r){if(e===void 0)return null;let c=N(e,t);C(c,["directory","managedFiles","managedFileCopies","notification","workflow","roleAssertions","decimalReservation","dataCommands","recordEdit","ownedSubject","workflowStage"],t,!0),Object.keys(c).length===0&&m("NATIVE_OPERATION_PLATFORM_ACCESS_EMPTY",t);let s={};if(c.dataCommands!==void 0){let a=N(c.dataCommands,`${t}/dataCommands`);C(a,["mode"],`${t}/dataCommands`),F(a.mode,"recoverable-native",`${t}/dataCommands/mode`),s.dataCommands={mode:"recoverable-native"}}if(c.workflowStage!==void 0){try{Ti(c.workflowStage)}catch{m("NATIVE_WORKFLOW_STAGE_DECLARATION_INVALID",`${t}/workflowStage`)}let a=c.workflowStage;(!s.dataCommands||c.decimalReservation!==void 0||!o.has(a.resourceCode)||!i.has(a.workflowCode)||!c.workflow?.codes?.includes(a.workflowCode))&&m("NATIVE_WORKFLOW_STAGE_DECLARATION_INVALID",`${t}/workflowStage`),s.workflowStage={...a,runningNodeIds:U([...a.runningNodeIds]),allowedStatuses:U([...a.allowedStatuses])}}if(c.recordEdit!==void 0){let a=`${t}/recordEdit`,d=N(c.recordEdit,a);C(d,["resourceCode","fieldCodes"],a);let f=H(d.resourceCode,`${a}/resourceCode`),u=n.get(f),p=V(d.fieldCodes,`${a}/fieldCodes`,200);(!u||!p.length||!s.dataCommands)&&m("NATIVE_RECORD_EDIT_DECLARATION_INVALID",a);for(let g of p){let I=u.get(g);(!I||I.type==="serial-number"||I.type==="subtable")&&m("NATIVE_RECORD_EDIT_FIELD_INVALID",`${a}/fieldCodes`)}s.recordEdit={resourceCode:f,fieldCodes:U(p)}}if(c.roleAssertions!==void 0){let a=N(c.roleAssertions,`${t}/roleAssertions`);C(a,["roleCodes","actorAuthority"],`${t}/roleAssertions`,!0),a.actorAuthority!==void 0&&F(a.actorAuthority,!0,`${t}/roleAssertions/actorAuthority`);let d=V(a.roleCodes,`${t}/roleAssertions/roleCodes`,20);d.length||m("NATIVE_OPERATION_ROLE_ASSERTIONS_REQUIRED",`${t}/roleAssertions/roleCodes`),d.forEach((f,u)=>{r.has(f)||m("NATIVE_ROLE_REFERENCE_MISSING",`${t}/roleAssertions/roleCodes/${u}`)}),s.roleAssertions={roleCodes:U(d),...a.actorAuthority===!0?{actorAuthority:!0}:{}}}if(c.directory!==void 0){let a=N(c.directory,`${t}/directory`);C(a,["mode","fields"],`${t}/directory`),["current-initiator","selected-user"].includes(String(a.mode))||m("NATIVE_OPERATION_DIRECTORY_MODE_INVALID",`${t}/directory/mode`);let d=new Set(["displayName","employeeNumber","primaryDepartment","departments",...a.mode==="current-initiator"?["phone"]:[]]),f=V(a.fields,`${t}/directory/fields`,d.size);(!f.length||f.some(u=>!d.has(u)))&&m("NATIVE_OPERATION_DIRECTORY_FIELDS_INVALID",`${t}/directory/fields`),s.directory={mode:String(a.mode),fields:U(f)}}if(c.managedFiles!==void 0){let a=S(c.managedFiles,`${t}/managedFiles`,16);a.length||m("NATIVE_OPERATION_MANAGED_FILES_REQUIRED",`${t}/managedFiles`);let d=new Set;s.managedFiles=ee(a.map((f,u)=>{let p=`${t}/managedFiles/${u}`,g=N(f,p);C(g,["resourceCode","fieldCodes","intents"],p);let I=H(g.resourceCode,`${p}/resourceCode`);(d.has(I)||!o.has(I))&&m("NATIVE_OPERATION_MANAGED_FILE_RESOURCE_INVALID",`${p}/resourceCode`),d.add(I);let A=V(g.fieldCodes,`${p}/fieldCodes`,16);(!A.length||A.some(b=>!["file","image","signature","text.rich"].includes(String(o.get(I)?.get(b)||""))))&&m("NATIVE_OPERATION_MANAGED_FILE_FIELD_INVALID",`${p}/fieldCodes`);let O=V(g.intents,`${p}/intents`,2);return(!O.length||O.some(b=>!["create","update"].includes(b)))&&m("NATIVE_OPERATION_MANAGED_FILE_INTENT_INVALID",`${p}/intents`),{resourceCode:I,fieldCodes:U(A),intents:U(O)}}),f=>f.resourceCode)}if(c.managedFileCopies!==void 0){let a=S(c.managedFileCopies,`${t}/managedFileCopies`,16);a.length||m("NATIVE_OPERATION_MANAGED_FILE_COPIES_REQUIRED",`${t}/managedFileCopies`);let d=new Set;s.managedFileCopies=ee(a.map((f,u)=>{let p=`${t}/managedFileCopies/${u}`,g=N(f,p);C(g,["mode","sourceResourceCode","sourceFieldCodes","targetResourceCode","targetFieldCodes"],p),F(g.mode,"copy",`${p}/mode`);let I=H(g.sourceResourceCode,`${p}/sourceResourceCode`),A=H(g.targetResourceCode,`${p}/targetResourceCode`),O=o.get(I),b=o.get(A);(!O||!b)&&m("NATIVE_OPERATION_MANAGED_FILE_COPY_RESOURCE_INVALID",p);let _=V(g.sourceFieldCodes,`${p}/sourceFieldCodes`,16),E=V(g.targetFieldCodes,`${p}/targetFieldCodes`,16);(!_.length||_.length!==E.length)&&m("NATIVE_OPERATION_MANAGED_FILE_COPY_FIELDS_INVALID",p),_.forEach((l,y)=>{let R=O.get(l),h=b.get(E[y]);(!["file","image"].includes(String(R))||R!==h)&&m("NATIVE_OPERATION_MANAGED_FILE_COPY_FIELD_INVALID",`${p}/sourceFieldCodes/${y}`)});let T=`${I}:${_.join(",")}=>${A}:${E.join(",")}`;return d.has(T)&&m("NATIVE_OPERATION_MANAGED_FILE_COPY_DUPLICATE",p),d.add(T),{mode:"copy",sourceResourceCode:I,sourceFieldCodes:U(_),targetResourceCode:A,targetFieldCodes:U(E)}}),f=>`${f.sourceResourceCode}:${f.sourceFieldCodes.join(",")}=>${f.targetResourceCode}:${f.targetFieldCodes.join(",")}`)}if(c.notification!==void 0){let a=N(c.notification,`${t}/notification`);C(a,["mode"],`${t}/notification`),a.mode!=="business-standard"&&m("NATIVE_OPERATION_NOTIFICATION_MODE_INVALID",`${t}/notification/mode`),s.notification={mode:"business-standard"}}if(c.workflow!==void 0){let a=N(c.workflow,`${t}/workflow`);C(a,["codes"],`${t}/workflow`,["businessCommands"]);let d=V(a.codes,`${t}/workflow/codes`,16);(!d.length||d.some(u=>!i.has(u)))&&m("NATIVE_OPERATION_WORKFLOW_CODE_INVALID",`${t}/workflow/codes`);let f=a.businessCommands===void 0?void 0:V(a.businessCommands,`${t}/workflow/businessCommands`,4);f&&(!f.length||f.some(u=>!["approve","reject","withdraw","resubmit"].includes(u)))&&m("NATIVE_OPERATION_WORKFLOW_BUSINESS_COMMAND_INVALID",`${t}/workflow/businessCommands`),s.workflow={codes:U(d),...f?{businessCommands:U(f)}:{}}}if(c.ownedSubject!==void 0){let a=`${t}/ownedSubject`,d=c.ownedSubject;try{an(d)}catch{m("NATIVE_WORKFLOW_OWNED_SUBJECT_INVALID",a)}(!s.workflow||c.decimalReservation!==void 0)&&m("NATIVE_WORKFLOW_OWNED_SUBJECT_INVALID",a);try{Ar(d,n,s.managedFiles||[])}catch(f){m(`NATIVE_${f.message}`,a)}s.ownedSubject={mode:"create",resourceCode:d.resourceCode,subtables:ee(d.subtables.map(f=>({fieldCode:f.fieldCode,fieldCodes:U([...f.fieldCodes])})),f=>f.fieldCode)}}if(c.decimalReservation!==void 0){let a=`${t}/decimalReservation`,d=N(c.decimalReservation,a);C(d,["mode","resourceCode","amountFieldCode","currencyFieldCode","relationFieldCode","parentFieldCode","rootFieldCode","statusFieldCode","parentRelationValue","childRelationValue","eligibleParentStatuses","eligibleChildStatuses"],a);let f=w(d.mode,`${a}/mode`,16);["reserve","commit","release"].includes(f)||m("NATIVE_DECIMAL_RESERVATION_MODE_INVALID",`${a}/mode`);let u=H(d.resourceCode,`${a}/resourceCode`),p=n.get(u);p||m("NATIVE_DECIMAL_RESERVATION_RESOURCE_MISSING",`${a}/resourceCode`);let I=Object.fromEntries(["amountFieldCode","currencyFieldCode","relationFieldCode","parentFieldCode","rootFieldCode","statusFieldCode"].map(l=>[l,G(d[l],`${a}/${l}`)])),A=l=>p.get(I[l]),O=l=>new Set((A(l)?.options||[]).map(y=>String(y.value))),b=P(d.parentRelationValue,`${a}/parentRelationValue`),_=P(d.childRelationValue,`${a}/childRelationValue`),E=V(d.eligibleParentStatuses,`${a}/eligibleParentStatuses`,16),T=V(d.eligibleChildStatuses,`${a}/eligibleChildStatuses`,16);(A("amountFieldCode")?.type!=="number.decimal"||A("amountFieldCode")?.exactDecimal!==!0||A("amountFieldCode")?.precision!==18||A("amountFieldCode")?.scale!==2||A("currencyFieldCode")?.type!=="option.single"||A("relationFieldCode")?.type!=="option.single"||A("parentFieldCode")?.type!=="resource-ref.single"||A("parentFieldCode")?.source?.resourceCode!==u||A("rootFieldCode")?.type!=="uuid"||A("statusFieldCode")?.type!=="option.single"||b===_||!O("relationFieldCode").has(b)||!O("relationFieldCode").has(_)||!E.length||!T.length||E.some(l=>!O("statusFieldCode").has(l))||T.some(l=>!O("statusFieldCode").has(l)))&&m("NATIVE_DECIMAL_RESERVATION_FIELD_INVALID",a),s.decimalReservation={mode:f,resourceCode:u,...I,parentRelationValue:b,childRelationValue:_,eligibleParentStatuses:U(E),eligibleChildStatuses:U(T)}}return s}function Ac(e,t,o,n,i){if(e===void 0)return;let r=`${t}/ai`,c=N(e,r);xa.test(o)||m("NATIVE_OPERATION_AI_CODE_INVALID",`${t}/code`),C(c,["name","description","risk","resources","sideEffects","concurrency","timeoutMs"],r,!0),w(c.name,`${r}/name`,No),w(c.description,`${r}/description`,No);let s=w(c.risk,`${r}/risk`,16);["read","write","destructive","external"].includes(s)||m("NATIVE_OPERATION_AI_RISK_INVALID",`${r}/risk`),s==="read"!=(n==="GET")&&m("NATIVE_OPERATION_AI_METHOD_RISK_MISMATCH",`${r}/risk`),n==="DELETE"&&!["destructive","external"].includes(s)&&m("NATIVE_OPERATION_AI_METHOD_RISK_MISMATCH",`${r}/risk`);let a=V(c.resources,`${r}/resources`,16);a.length===0&&m("NATIVE_OPERATION_AI_RESOURCE_REQUIRED",`${r}/resources`),a.forEach((f,u)=>{let p=H(f,`${r}/resources/${u}`);i.has(p)||m("NATIVE_OPERATION_AI_RESOURCE_MISSING",`${r}/resources/${u}`)});let d=V(c.sideEffects,`${r}/sideEffects`,20);(s==="read"&&d.length!==0||s!=="read"&&d.length===0)&&m("NATIVE_OPERATION_AI_SIDE_EFFECT_INVALID",`${r}/sideEffects`),c.concurrency!==void 0&&!["none","revision"].includes(w(c.concurrency,`${r}/concurrency`,16))&&m("NATIVE_OPERATION_AI_CONCURRENCY_INVALID",`${r}/concurrency`),c.timeoutMs!==void 0&&ie(c.timeoutMs,`${r}/timeoutMs`,100,3e4)}function ln(e){return(e.replace(/\/{2,}/g,"/").replace(/\/$/,"")||"/").split("/").map(o=>o.startsWith(":")?":":o.includes("*")?"*":o).join("/")}function Ec(e,t){let o=N(e,t),n=w(o.type,`${t}/type`,32),i=["code","type","label","presentation","required"],r=n==="sso"?[...i,"provider"]:n==="dingtalk"?[...i,"flow"]:i;C(o,r,t);let c=P(o.code,`${t}/code`),s=w(o.label,`${t}/label`,255),a=w(o.presentation,`${t}/presentation`,16);["primary","secondary"].includes(a)||m("NATIVE_APPLICATION_AUTH_METHOD_PRESENTATION_INVALID",`${t}/presentation`);let d=at(o.required,`${t}/required`);return["sso","password","dingtalk"].includes(n)||m("NATIVE_APPLICATION_AUTH_METHOD_TYPE_INVALID",`${t}/type`),n==="sso"&&o.provider!=="tenant-default"&&m("NATIVE_APPLICATION_AUTH_SSO_PROVIDER_INVALID",`${t}/provider`),n==="dingtalk"&&!["auto","jsapi","oauth"].includes(w(o.flow,`${t}/flow`,16))&&m("NATIVE_APPLICATION_AUTH_DINGTALK_FLOW_INVALID",`${t}/flow`),{code:c,type:n,label:s,presentation:a,required:d,...n==="sso"?{provider:"tenant-default"}:{},...n==="dingtalk"?{flow:o.flow}:{}}}function hr(e,t,o){let n=N(e,o);C(n,["routeCode","path","defaultRouteCode"],o);let i=P(n.routeCode,`${o}/routeCode`),r=be(n.path,`${o}/path`),c=t==="desktop"?"/login":"/m/login";return(r!==c||/[:*?#\\]/.test(r))&&m("NATIVE_APPLICATION_AUTH_SURFACE_PATH_INVALID",`${o}/path`,{device:t,expectedPath:c}),{routeCode:i,path:r,defaultRouteCode:P(n.defaultRouteCode,`${o}/defaultRouteCode`)}}function Kr(e,t,o,n){if(e===null)return;let i=N(e,n);C(i,["accountMode","registration","methods","surfaces"],n),F(i.accountMode,"existing-platform-users-only",`${n}/accountMode`);let r=N(i.registration,`${n}/registration`);C(r,["mode"],`${n}/registration`),F(r.mode,"reject",`${n}/registration/mode`);let c=S(i.methods,`${n}/methods`,8);c.length===0&&m("NATIVE_APPLICATION_AUTH_METHOD_REQUIRED",`${n}/methods`);let s=c.map((b,_)=>Ec(b,`${n}/methods/${_}`)),a=new Set,d=new Set;for(let[b,_]of s.entries())a.has(_.code)&&m("NATIVE_APPLICATION_AUTH_METHOD_CODE_DUPLICATE",`${n}/methods/${b}/code`),d.has(_.type)&&m("NATIVE_APPLICATION_AUTH_METHOD_TYPE_DUPLICATE",`${n}/methods/${b}/type`),a.add(_.code),d.add(_.type);s.filter(b=>b.presentation==="primary").length!==1&&m("NATIVE_APPLICATION_AUTH_PRIMARY_METHOD_INVALID",`${n}/methods`);let f=N(i.surfaces,`${n}/surfaces`);C(f,["desktop","mobile"],`${n}/surfaces`);let u=hr(f.desktop,"desktop",`${n}/surfaces/desktop`),p=hr(f.mobile,"mobile",`${n}/surfaces/mobile`);u.routeCode===p.routeCode&&m("NATIVE_APPLICATION_AUTH_SURFACE_CODE_DUPLICATE",`${n}/surfaces/mobile/routeCode`);let g=S(t,"/config/frontend/routes",500),I=new Map;for(let[b,_]of g.entries()){let E=N(_,`/config/frontend/routes/${b}`);I.set(String(E.code||""),E)}let A=new Set((Array.isArray(o.data?.resources)?o.data.resources:[]).map(b=>String(b.code||"")).filter(b=>/^[a-z][a-z0-9-]{0,62}$/.test(b)));for(let[b,_]of[["desktop",u],["mobile",p]]){I.has(_.routeCode)&&m("NATIVE_APPLICATION_AUTH_SURFACE_CODE_CONFLICT",`${n}/surfaces/${b}/routeCode`);let E=/^user\.([a-z][a-z0-9-]{0,62})\.(records|submit)$/.exec(String(_.defaultRouteCode||"")),T=I.get(_.defaultRouteCode),l=String(T?.path||"");if(E&&A.has(E[1])){let R=E[2]==="records"?`/my/${E[1]}`:`/my/${E[1]}/submit`;T={surface:"user",path:b==="mobile"?`/m${R}`:R},l=String(T.path)}let y=b==="desktop"?l==="/m"||l.startsWith("/m/"):!(l==="/m"||l.startsWith("/m/"));(!T||T.surface!=="user"||/[:*]/.test(l)||y)&&m("NATIVE_APPLICATION_AUTH_DEFAULT_ROUTE_INVALID",`${n}/surfaces/${b}/defaultRouteCode`)}let O=Gr(o).filter(b=>!b.owner.startsWith("authentication:"));for(let[b,_]of[["desktop",u],["mobile",p]]){let E=O.find(T=>ln(T.path)===ln(_.path));E&&m("NATIVE_APPLICATION_AUTH_SURFACE_PATH_CONFLICT",`${n}/surfaces/${b}/path`,{owner:E.owner})}}function Ic(e,t){if(e===null)return;let o={data:{resources:[]},workflows:{definitions:[]},frontend:{routes:[{code:"auth-desktop-default",path:"/auth-desktop-default",surface:"user"},{code:"auth-mobile-default",path:"/m/auth-mobile-default",surface:"user"}],user:{applicationTodoCenter:!1},admin:{navigation:[]},authentication:e}},n=N(e,t),i=N(n.surfaces,`${t}/surfaces`),r={...n,surfaces:{...i,desktop:{...N(i.desktop,`${t}/surfaces/desktop`),defaultRouteCode:"auth-desktop-default"},mobile:{...N(i.mobile,`${t}/surfaces/mobile`),defaultRouteCode:"auth-mobile-default"}}};Kr(r,o.frontend.routes,{...o,frontend:{...o.frontend,authentication:r}},t)}function yc(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 bc=new Set(["draft.read","draft.update","validate","create","own.list","own.read","public.list","public.read"]);function Oc(e,t,o){let n=N(e,o);C(n,["policies"],o);let i=S(n.policies,`${o}/policies`,16);i.length<1&&m("NATIVE_PUBLIC_POLICY_REQUIRED",o);let r=new Map(t.frontend.routes.map(d=>[d.code,d])),c=new Map(t.data.resources.map(d=>[d.code,d])),s=new Set,a=new Set(i.map(d=>String(d?.code||"")));i.forEach((d,f)=>{let u=`${o}/policies/${f}`,p=N(d,u);C(p,["code","routeCode","mode","resourceCode","operations","fields"],u,["requiredFields","ownRecordFields","publicRecordFields","publicFilters","serverGeneratedFields","schedule","publicSubtableFields","draft","validations"]);let g=P(p.code,`${u}/code`);s.has(g)&&m("NATIVE_PUBLIC_POLICY_DUPLICATE",`${u}/code`);let I=P(p.routeCode,`${u}/routeCode`),A=r.get(I);(!A||A.surface!=="user"||A.capability!==void 0||A.access!==void 0||/[:*]/.test(String(A.path)))&&m("NATIVE_PUBLIC_ROUTE_INVALID",`${u}/routeCode`),F(p.mode,"anonymous",`${u}/mode`);let O=H(p.resourceCode,`${u}/resourceCode`),b=c.get(O);b||m("NATIVE_PUBLIC_RESOURCE_MISSING",`${u}/resourceCode`);let _=new Map(b.schema.fields.map(v=>[String(v.code),String(v.type)])),E=V(p.operations,`${u}/operations`,8);(E.length<1||E.some(v=>!bc.has(v)))&&m("NATIVE_PUBLIC_OPERATION_INVALID",`${u}/operations`),E.includes("draft.read")!==E.includes("draft.update")&&m("NATIVE_PUBLIC_DRAFT_OPERATION_INCOMPLETE",`${u}/operations`);let T=V(p.fields,`${u}/fields`,64);(T.length<1||T.some(v=>!_.has(v)))&&m("NATIVE_PUBLIC_FIELD_INVALID",`${u}/fields`);for(let v of["requiredFields","ownRecordFields","publicRecordFields"]){if(!Object.prototype.hasOwnProperty.call(p,v))continue;V(p[v],`${u}/${v}`,64).some(x=>!T.includes(x))&&m("NATIVE_PUBLIC_FIELD_SCOPE_INVALID",`${u}/${v}`)}let l=Object.prototype.hasOwnProperty.call(p,"serverGeneratedFields")?S(p.serverGeneratedFields,`${u}/serverGeneratedFields`,16):[],y=new Set;l.forEach((v,W)=>{let x=`${u}/serverGeneratedFields/${W}`,q=N(v,x);C(q,["field","kind"],x);let z=G(q.field,`${x}/field`);(y.has(z)||!_.has(z)||T.includes(z)||_.get(z)!=="text.short"&&_.get(z)!=="text.long")&&m("NATIVE_PUBLIC_SERVER_GENERATED_FIELD_INVALID",`${x}/field`),F(q.kind,"random-token",`${x}/kind`),y.add(z)});let R=Object.prototype.hasOwnProperty.call(p,"schedule")?N(p.schedule,`${u}/schedule`):null;if(R){let v=["campusPolicyCode","rulePolicyCode","campusField","ruleCampusField","ruleWeekdaysField","ruleOpenAtField","ruleCloseAtField","ruleSlotMinutesField","ruleAdvanceHoursField","ruleAdvanceDaysField","campusEnabledField","ruleEnabledField","dateField","timeField"];C(R,v,`${u}/schedule`);for(let W of["campusPolicyCode","rulePolicyCode"])P(R[W],`${u}/schedule/${W}`);for(let W of v.filter(x=>!["campusPolicyCode","rulePolicyCode"].includes(x)))G(R[W],`${u}/schedule/${W}`);for(let W of[R.campusField,R.dateField,R.timeField])T.includes(String(W))||m("NATIVE_PUBLIC_SCHEDULE_FIELD_INVALID",`${u}/schedule`);(!a.has(String(R.campusPolicyCode))||!a.has(String(R.rulePolicyCode)))&&m("NATIVE_PUBLIC_SCHEDULE_POLICY_INVALID",`${u}/schedule`)}let h=Object.prototype.hasOwnProperty.call(p,"publicFilters")?S(p.publicFilters,`${u}/publicFilters`,16):[],$=new Set;h.forEach((v,W)=>{let x=`${u}/publicFilters/${W}`,q=N(v,x);C(q,["field","operator","value"],x);let z=G(q.field,`${x}/field`);$.has(z)&&m("NATIVE_PUBLIC_FILTER_DUPLICATE",`${x}/field`),T.includes(z)||m("NATIVE_PUBLIC_FILTER_FIELD_INVALID",`${x}/field`),F(q.operator,"eq",`${x}/operator`),["boolean","text.short","text.long","number.integer","number.decimal","date","time"].includes(_.get(z)||"")||m("NATIVE_PUBLIC_FILTER_FIELD_INVALID",`${x}/field`),q.value!==null&&typeof q.value!="string"&&typeof q.value!="number"&&typeof q.value!="boolean"&&m("NATIVE_PUBLIC_FILTER_VALUE_INVALID",`${x}/value`),$.add(z)});let k=Object.prototype.hasOwnProperty.call(p,"publicSubtableFields")?N(p.publicSubtableFields,`${u}/publicSubtableFields`):null;if(k){Object.keys(k).length>64&&m("NATIVE_PUBLIC_SUBTABLE_FIELDS_INVALID",`${u}/publicSubtableFields`);for(let[v,W]of Object.entries(k)){let x=b.schema.fields.find(J=>String(J.code)===v),q=String(x?.subtable?.resourceCode||""),z=c.get(q),_e=new Map((z?.schema?.fields||[]).map(J=>[String(J.code),String(J.type)])),Oe=V(W,`${u}/publicSubtableFields/${v}`,64);(!T.includes(v)||_.get(v)!=="subtable"||!z||Oe.length<1||Oe.some(J=>!_e.has(J))||Oe.some(J=>_e.get(J)==="subtable")||Oe.some(J=>_e.get(J)==="signature"))&&m("NATIVE_PUBLIC_SUBTABLE_FIELDS_INVALID",`${u}/publicSubtableFields/${v}`)}}if(E.some(v=>v.startsWith("public."))){Object.prototype.hasOwnProperty.call(p,"publicRecordFields")||m("NATIVE_PUBLIC_RECORD_FIELDS_REQUIRED",`${u}/publicRecordFields`);let v=V(p.publicRecordFields,`${u}/publicRecordFields`,64);(v.length<1||v.some(W=>!T.includes(W))||v.some(W=>_.get(W)==="signature"||_.get(W)==="subtable"&&!k?.[W]))&&m("NATIVE_PUBLIC_RECORD_FIELDS_INVALID",`${u}/publicRecordFields`)}let M=Object.prototype.hasOwnProperty.call(p,"requiredFields")?V(p.requiredFields,`${u}/requiredFields`,64):[],L=b.surface||{},Y=L.fields||{},ne=String(L.mutationOwner||"native")==="native"&&L.generated?.create!==!1,X=b.schema.fields.filter(v=>xt(v,Y[v.code])).map(v=>String(v.code));if(E.includes("create")&&!ne&&m("NATIVE_PUBLIC_CREATE_FIELDS_INCOMPLETE",`${u}/fields`),E.includes("create")&&!Object.prototype.hasOwnProperty.call(p,"draft")&&m("NATIVE_PUBLIC_DRAFT_REQUIRED",`${u}/draft`),E.includes("create"))for(let v of X){let W=T.includes(v)?M.includes(v)?null:"requiredFields":"fields";W&&m("NATIVE_PUBLIC_CREATE_FIELDS_INCOMPLETE",`${u}/${W}`,{resourceCode:H,fieldCode:v})}if(Object.prototype.hasOwnProperty.call(p,"draft")){let v=N(p.draft,`${u}/draft`);C(v,["enabled","inactivityTtlSeconds","maxBytes"],`${u}/draft`),F(v.enabled,!0,`${u}/draft/enabled`),ie(v.inactivityTtlSeconds,`${u}/draft/inactivityTtlSeconds`,3600,7776e3),ie(v.maxBytes,`${u}/draft/maxBytes`,4096,262144)}else E.includes("draft.read")&&m("NATIVE_PUBLIC_DRAFT_REQUIRED",`${u}/draft`);let de=Object.prototype.hasOwnProperty.call(p,"validations")?S(p.validations,`${u}/validations`,16):[],le=new Set;de.forEach((v,W)=>{let x=`${u}/validations/${W}`,q=N(v,x);C(q,["code","kind","fields","result"],x);let z=P(q.code,`${x}/code`);le.has(z)&&m("NATIVE_PUBLIC_VALIDATION_DUPLICATE",`${x}/code`),F(q.kind,"duplicate",`${x}/kind`),F(q.result,"availability",`${x}/result`);let _e=V(q.fields,`${x}/fields`,8);(_e.length<1||_e.some(Oe=>!T.includes(Oe))||_e.some(Oe=>["file","subtable"].includes(_.get(Oe)||"")))&&m("NATIVE_PUBLIC_VALIDATION_FIELD_INVALID",`${x}/fields`),le.add(z)}),s.add(g)})}function Nc(e,t){let o=N(e,t);C(o,["policies"],t),S(o.policies,`${t}/policies`,16).length<1&&m("NATIVE_PUBLIC_POLICY_REQUIRED",t)}function Tc(e){return{policies:ee(e.frontend.publicAccess.policies.map(t=>({code:t.code,routeCode:t.routeCode,mode:t.mode,resourceCode:t.resourceCode,operations:U(t.operations),fields:U(t.fields),...t.requiredFields?{requiredFields:U(t.requiredFields)}:{},...t.ownRecordFields?{ownRecordFields:U(t.ownRecordFields)}:{},...t.publicRecordFields?{publicRecordFields:U(t.publicRecordFields)}:{},...t.publicFilters?{publicFilters:t.publicFilters.map(o=>({field:o.field,operator:o.operator,value:o.value})).sort((o,n)=>Ae(o.field,n.field))}:{},...t.publicSubtableFields?{publicSubtableFields:Object.fromEntries(Object.entries(t.publicSubtableFields).sort(([o],[n])=>o.localeCompare(n)).map(([o,n])=>[o,U(Array.isArray(n)?n.map(String):[])]))}:{},...t.serverGeneratedFields?{serverGeneratedFields:t.serverGeneratedFields.map(o=>({field:o.field,kind:o.kind})).sort((o,n)=>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:ee(t.validations.map(o=>({code:o.code,kind:o.kind,fields:U(o.fields),result:o.result})),o=>o.code)}:{}})),t=>t.code)}}function Gr(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=qr(o),i=`/admin/resources/${o.code}`,r=[["list",i],["detail",`${i}/:id`],["create",`${i}/new`],["update",`${i}/:id/edit`]];for(let[c,s]of r)n[c]&&t.push({owner:`resource:${o.code}:${c}`,path:s},{owner:`resource:${o.code}:${c}:mobile`,path:`/m${s}`})}if(e.frontend.user.applicationTodoCenter===!0&&t.push({owner:"application:todo-center",path:"/todos"},{owner:"application:todo-center:mobile",path:"/m/todos"}),e.workflows.definitions.length>0){t.push({owner:"workflow:work-center",path:"/work-center"},{owner:"workflow:work-center:mobile",path:"/m/work-center"},{owner:"workflow:task",path:"/tasks/:taskId"},{owner:"workflow:task:mobile",path:"/m/tasks/:taskId"},{owner:"workflow:instance",path:"/workflows/:instanceId"},{owner:"workflow:instance:mobile",path:"/m/workflows/:instanceId"});let o=!1;for(let n of e.workflows.definitions)["standalone","hidden-handoff"].includes(n.launch.mode)&&(o=!0);o&&t.push({owner:"workflow:launch",path:"/workflows/:workflowCode/start"},{owner:"workflow:launch:mobile",path:"/m/workflows/:workflowCode/start"})}return t}function mn(e){let t=new Map(Gr(e).map(o=>[ln(o.path),o]));return ee(e.frontend.routes.map((o,n)=>{let i=`/config/frontend/routes/${n}`,r=N(o,i);C(r,["code","path","label","surface","parentCode","capability","access","pinned","tabPersistence","keepAlive"],i,!0),["admin","user"].includes(r.surface)||m("NATIVE_ROUTE_SURFACE_INVALID",`${i}/surface`);let c=be(r.path,`${i}/path`);r.surface==="admin"&&c!=="/admin"&&!c.startsWith("/admin/")&&m("NATIVE_ADMIN_ROUTE_PATH_INVALID",`${i}/path`),r.surface==="user"&&(c==="/admin"||c.startsWith("/admin/"))&&m("NATIVE_USER_ROUTE_PATH_RESERVED",`${i}/path`);let s=ln(c),a=t.get(s);a&&m("NATIVE_ROUTE_PATH_CONFLICT",`${i}/path`,{path:c,owner:a.owner}),t.set(s,{owner:`frontend:${String(r.code||n)}`,path:c});let d=/[:*]/.test(c),f=ko(r,i,e.appCode),u=r.pinned===void 0?void 0:at(r.pinned,`${i}/pinned`),p=r.tabPersistence===void 0?d?"none":"session":w(r.tabPersistence,`${i}/tabPersistence`,16),g=r.keepAlive===void 0?"none":w(r.keepAlive,`${i}/keepAlive`,16);return["session","none"].includes(p)||m("NATIVE_ROUTE_TAB_PERSISTENCE_INVALID",`${i}/tabPersistence`),["none","memory"].includes(g)||m("NATIVE_ROUTE_KEEP_ALIVE_INVALID",`${i}/keepAlive`),d&&u===!0&&m("NATIVE_DYNAMIC_ROUTE_PINNED_FORBIDDEN",`${i}/pinned`),d&&p==="session"&&m("NATIVE_DYNAMIC_ROUTE_TAB_PERSISTENCE_FORBIDDEN",`${i}/tabPersistence`),d&&g==="memory"&&m("NATIVE_DYNAMIC_ROUTE_KEEP_ALIVE_FORBIDDEN",`${i}/keepAlive`),{code:P(r.code,`${i}/code`),path:c,label:w(r.label,`${i}/label`,255),surface:r.surface,...r.parentCode===void 0?{}:{parentCode:P(r.parentCode,`${i}/parentCode`)},...f,...u===void 0?{}:{pinned:u},tabPersistence:p,keepAlive:g}}),o=>o.code)}function qr(e){let t=e.surface===void 0?{}:N(e.surface,"/surface"),o=t.mutationOwner||"native",n=t.generated===void 0?{}:N(t.generated,"/surface/generated"),i=o==="native";return{list:n.list??!0,detail:n.detail??!0,create:n.create??i,update:n.update??i,delete:n.delete??i}}function zr(e){let t=[];for(let o of ee(e.data.resources,n=>n.code).flatMap(n=>[{resource:n,viewCode:void 0},...(n.surface?.views||[]).map(i=>({viewCode:i.code,resource:{...n,name:i.name,surface:Mn(n.surface,i.code)}}))])){let{resource:n,viewCode:i}=o,r=`/admin/resources/${n.code}${i?`/views/${i}`:""}`,c=qr(n),s=[{operation:"list",kind:"resource-list",path:`${r}`,label:n.name,capability:n.capabilities.read,navigationEligible:!0},{operation:"detail",kind:"resource-detail",path:`${r}/:id`,label:`${n.name}\u8BE6\u60C5`,capability:n.capabilities.read,navigationEligible:!1},{operation:"create",kind:"resource-create",path:`${r}/new`,label:`\u65B0\u589E${n.name}`,capability:n.capabilities.create,navigationEligible:!1},{operation:"update",kind:"resource-update",path:`${r}/:id/edit`,label:`\u7F16\u8F91${n.name}`,capability:n.capabilities.update,navigationEligible:!1}];for(let a of s)c[a.operation]&&t.push({code:`resource:${n.code}${i?`:view:${i}`:""}:${a.operation}`,kind:a.kind,path:a.path,label:a.label,navigationEligible:a.navigationEligible,capability:a.capability,resourceCode:n.code,...i?{viewCode:i}:{}})}for(let o of mn(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 Jr(e){return e.kind==="resource"?`resource:${e.resourceCode}${e.viewCode?`:view:${e.viewCode}`:""}:list`:`operation:${e.routeCode}`}function Rc(e){return e.frontend.admin.navigation.map((t,o)=>({code:t.code,label:t.label,...t.icon===void 0?{}:{icon:t.icon},order:t.order??o,items:t.items.map((n,i)=>({pageCode:Jr(n.page),...n.label===void 0?{}:{label:n.label},...n.icon===void 0?{}:{icon:n.icon},order:n.order??i})).sort((n,i)=>n.order-i.order||Ae(n.pageCode,i.pageCode))})).sort((t,o)=>t.order-o.order||Ae(t.code,o.code))}function Cc(e,t){let o=S(e,t,B.adminNavigationGroups);o.reduce((i,r)=>i+(Array.isArray(r?.items)?r.items.length:0),0)>B.adminNavigationItems&&m("NATIVE_ARRAY_LIMIT_EXCEEDED",t);let n=0;o.forEach((i,r)=>{let c=`${t}/${r}`,s=N(i,c);C(s,["code","label","icon","order","items"],c,!0),P(s.code,`${c}/code`),w(s.label,`${c}/label`,255),un(s.icon,`${c}/icon`),$r(s.order,`${c}/order`);let a=S(s.items,`${c}/items`,500);a.length===0&&m("NATIVE_ADMIN_GROUP_ORPHANED",`${c}/items`),n+=a.length,n>B.adminNavigationItems&&m("NATIVE_ARRAY_LIMIT_EXCEEDED",t),a.forEach((d,f)=>{let u=`${c}/items/${f}`,p=N(d,u);C(p,["page","label","icon","order"],u,!0),hc(p.page,`${u}/page`),p.label!==void 0&&w(p.label,`${u}/label`,255),un(p.icon,`${u}/icon`),$r(p.order,`${u}/order`)})})}function hc(e,t){let o=N(e,t),n=w(o.kind,`${t}/kind`,64);if(n==="resource"){C(o,["kind","resourceCode"],t,["viewCode"]),o.viewCode!==void 0&&P(o.viewCode,`${t}/viewCode`),H(o.resourceCode,`${t}/resourceCode`);return}if(n==="operation"){C(o,["kind","routeCode"],t),P(o.routeCode,`${t}/routeCode`);return}m("NATIVE_ADMIN_PAGE_REFERENCE_KIND_INVALID",`${t}/kind`)}function wc(e){let t=new Map(zr(e).map(i=>[String(i.code),i])),o=new Set,n=new Set;e.frontend.admin.navigation.forEach((i,r)=>{let c=`/config/frontend/admin/navigation/${r}`;o.has(i.code)&&m("NATIVE_ADMIN_GROUP_DUPLICATE",`${c}/code`),o.add(i.code),i.label===i.code&&m("NATIVE_ADMIN_USER_LABEL_REQUIRED",`${c}/label`),i.items.forEach((s,a)=>{let d=`${c}/items/${a}`,f=Jr(s.page),u=t.get(f);(!u||u.navigationEligible!==!0)&&m("NATIVE_ADMIN_PAGE_NOT_FOUND",`${d}/page`),n.has(f)&&m("NATIVE_ADMIN_PAGE_DUPLICATE",`${d}/page`),n.add(f);let p=s.page.resourceCode||s.page.routeCode||s.page.workflowCode||f,g=s.label||u.label;(!g||g===p||g===f)&&m("NATIVE_ADMIN_USER_LABEL_REQUIRED",`${d}/label`)})})}function Sc(e,t){let o=S(e,t,B.adminPages),n=new Set;o.forEach((i,r)=>{let c=`${t}/${r}`,s=N(i,c);C(s,["code","kind","path","label","navigationEligible","capability","access","resourceCode","viewCode","routeCode"],c,!0);let a=w(s.code,`${c}/code`,255);n.has(a)&&m("NATIVE_ADMIN_PAGE_DUPLICATE",`${c}/code`),n.add(a);let d=w(s.kind,`${c}/kind`,64);if(["resource-list","resource-detail","resource-create","resource-update","operation"].includes(d)||m("NATIVE_ADMIN_PAGE_KIND_INVALID",`${c}/kind`),be(s.path,`${c}/path`),w(s.label,`${c}/label`,255),at(s.navigationEligible,`${c}/navigationEligible`),s.capability!==void 0&&s.access!==void 0&&m("NATIVE_ROUTE_ACCESS_CONFLICT",`${c}/access`),s.capability!==void 0&&w(s.capability,`${c}/capability`,255),s.access!==void 0){let f=N(s.access,`${c}/access`);C(f,["allOf","anyOf"],`${c}/access`,!0);for(let u of["allOf","anyOf"])f[u]!==void 0&&V(f[u],`${c}/access/${u}`,50)}for(let f of["resourceCode","viewCode","routeCode"])s[f]!==void 0&&P(s[f],`${c}/${f}`)})}function Dc(e,t){let o=S(e,t,B.adminNavigationGroups);o.reduce((i,r)=>i+(Array.isArray(r?.items)?r.items.length:0),0)>B.adminNavigationItems&&m("NATIVE_ARRAY_LIMIT_EXCEEDED",t);let n=0;o.forEach((i,r)=>{let c=`${t}/${r}`,s=N(i,c);C(s,["code","label","icon","order","items"],c,!0),P(s.code,`${c}/code`),w(s.label,`${c}/label`,255),un(s.icon,`${c}/icon`),ie(s.order,`${c}/order`,-1e4,1e4);let a=S(s.items,`${c}/items`,500);a.length===0&&m("NATIVE_ADMIN_GROUP_ORPHANED",`${c}/items`),n+=a.length,n>B.adminNavigationItems&&m("NATIVE_ARRAY_LIMIT_EXCEEDED",t),a.forEach((d,f)=>{let u=`${c}/items/${f}`,p=N(d,u);C(p,["pageCode","label","icon","order"],u,!0),w(p.pageCode,`${u}/pageCode`,255),p.label!==void 0&&w(p.label,`${u}/label`,255),un(p.icon,`${u}/icon`),ie(p.order,`${u}/order`,-1e4,1e4)})})}var kc=new Set(["application-todo-center","workflow-work-center","workflow-launch","workflow-task","workflow-instance","resource-records","resource-submit"]);function $c(e,t,o){let n=N(e,t);C(n,["schemaVersion","appCode","devicePolicy","rootEntry","authentication","routes","digest"],t),F(n.schemaVersion,Ur,`${t}/schemaVersion`),F(n.appCode,o,`${t}/appCode`),Do(n.devicePolicy,`${t}/devicePolicy`),vc(n.rootEntry,`${t}/rootEntry`),Pc(n.authentication,`${t}/authentication`),wo(n.digest,`${t}/digest`);let i=S(n.routes,`${t}/routes`,B.routes),r=new Set;i.forEach((c,s)=>{let a=`${t}/routes/${s}`,d=N(c,a),f=d.kind==="resource-records"||d.kind==="resource-submit";C(d,["code","kind","desktop","mobile"],a,["workflowCode",...f?["resourceCode"]:[]]);let u=w(d.code,`${a}/code`,255);r.has(u)&&m("NATIVE_ROUTE_MANIFEST_DUPLICATE",`${a}/code`),r.add(u);let p=w(d.kind,`${a}/kind`,64);if(kc.has(p)||m("NATIVE_ROUTE_MANIFEST_KIND_INVALID",`${a}/kind`),d.workflowCode!==void 0&&P(d.workflowCode,`${a}/workflowCode`),f){let A=H(d.resourceCode,`${a}/resourceCode`);F(u,`user.${A}.${d.kind==="resource-records"?"records":"submit"}`,`${a}/code`)}else d.resourceCode!==void 0&&m("NATIVE_PROPERTY_UNKNOWN",`${a}/resourceCode`);let g=Sr(d.desktop,`${a}/desktop`,o),I=Sr(d.mobile,`${a}/mobile`,o);g.surface!=="user"&&m("NATIVE_ROUTE_MANIFEST_DESKTOP_SURFACE_INVALID",`${a}/desktop/surface`),I.surface!=="user"&&m("NATIVE_ROUTE_MANIFEST_MOBILE_SURFACE_INVALID",`${a}/mobile/surface`),g.routeCode===I.routeCode&&m("NATIVE_ROUTE_MANIFEST_PAIR_DUPLICATE",a)}),F(n.digest,Z({schemaVersion:n.schemaVersion,appCode:n.appCode,devicePolicy:n.devicePolicy,rootEntry:n.rootEntry,authentication:n.authentication,routes:n.routes}),`${t}/digest`)}function Do(e,t){let o=N(e,t);C(o,["kind","mobileMaxWidthPx","desktopMinWidthPx"],t),F(o.kind,"viewport-family",`${t}/kind`);let n=ie(o.mobileMaxWidthPx,`${t}/mobileMaxWidthPx`,320,1600),i=ie(o.desktopMinWidthPx,`${t}/desktopMinWidthPx`,320,1600);return i!==n+1&&m("NATIVE_FRONTEND_DEVICE_POLICY_INVALID",t),{kind:"viewport-family",mobileMaxWidthPx:n,desktopMinWidthPx:i}}function vc(e,t){let o=N(e,t);C(o,["code","desktop","mobile"],t);let n=P(o.code,`${t}/code`),i=ho(o.desktop,`${t}/desktop`),r=ho(o.mobile,`${t}/mobile`);return(i===r||r==="/"||!r.startsWith("/m/"))&&m("NATIVE_ROUTE_MANIFEST_ROOT_ENTRY_INVALID",t),i.startsWith("/m/")&&m("NATIVE_ROUTE_MANIFEST_ROOT_ENTRY_INVALID",`${t}/desktop`),{code:n,desktop:i,mobile:r}}function Pc(e,t){let o=N(e,t);C(o,["desktop","mobile"],t);let n=wr(o.desktop,`${t}/desktop`,!1),i=wr(o.mobile,`${t}/mobile`,!0);return(n.routeCode===i.routeCode||n.path===i.path)&&m("NATIVE_ROUTE_MANIFEST_AUTHENTICATION_DUPLICATE",t),{desktop:n,mobile:i}}function wr(e,t,o){let n=N(e,t);C(n,["routeCode","path"],t);let i=P(n.routeCode,`${t}/routeCode`),r=ho(n.path,`${t}/path`);return(o?!r.startsWith("/m/"):r.startsWith("/m/"))&&m("NATIVE_ROUTE_MANIFEST_AUTHENTICATION_PATH_INVALID",`${t}/path`),{routeCode:i,path:r}}function ho(e,t){let o=be(e,t);return/[:*?#\\\\]/.test(o)&&m("NATIVE_ROUTE_MANIFEST_STATIC_PATH_INVALID",t),o}function Sr(e,t,o){let n=N(e,t);C(n,["routeCode","path","surface","pathParams","requiresAuthentication"],t,["capability","access"]),P(n.routeCode,`${t}/routeCode`);let i=be(n.path,`${t}/path`),r=w(n.surface,`${t}/surface`,16);["admin","user"].includes(r)||m("NATIVE_ROUTE_SURFACE_INVALID",`${t}/surface`);let c=V(n.pathParams,`${t}/pathParams`,8);return c.forEach((s,a)=>{(!/^[A-Za-z][A-Za-z0-9_]*$/.test(s)||s.length>64)&&m("NATIVE_ROUTE_PATH_PARAM_INVALID",`${t}/pathParams/${a}`)}),Q(c)!==Q(Hr(i))&&m("NATIVE_ROUTE_PATH_PARAMS_MISMATCH",`${t}/pathParams`),ko(n,t,o),n.requiresAuthentication!==!0&&m("NATIVE_ROUTE_AUTHENTICATION_REQUIRED",`${t}/requiresAuthentication`),n}function Hr(e){return U([...e.matchAll(/:([A-Za-z][A-Za-z0-9_]*)/g)].map(t=>t[1]))}function Dr(e,t,o,n){return{routeCode:e,path:t,surface:o,pathParams:Hr(t),...n?.capability?{capability:n.capability}:{},...n?.access?{access:n.access}:{},requiresAuthentication:!0}}function kr(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 Vc(e){let t=e.appCode,o=[],n=(g,I,A,O,b,_,E)=>{o.push({code:g,kind:I,...b?{workflowCode:b}:{},...E?{resourceCode:E}:{},desktop:Dr(kr(I,"desktop",b,E),A,"user",_),mobile:Dr(kr(I,"mobile",b,E),O,"user",_)})};e.frontend.user.applicationTodoCenter===!0&&n("application:todo-center","application-todo-center","/todos","/m/todos");let i=Yr(e);i.length>0&&(n("workflow:work-center","workflow-work-center","/work-center","/m/work-center"),n("workflow:task","workflow-task","/tasks/:taskId","/m/tasks/:taskId"),n("workflow:instance","workflow-instance","/workflows/:instanceId","/m/workflows/:instanceId"));for(let g of i){if(!["standalone","hidden-handoff"].includes(g.launch.mode))continue;let I=U([g.launch.submission?.create?.requiredCapability,g.launch.submission?.existing?.requiredCapability].filter(A=>!!A));n(`workflow:${g.code}:launch`,"workflow-launch","/workflows/:workflowCode/start","/m/workflows/:workflowCode/start",g.code,I.length===1?{capability:I[0]}:I.length>1?{access:{anyOf:I}}:void 0)}let r=o.sort((g,I)=>Ae(String(g.code),String(I.code))),c=mn(e),s=g=>{let I=g==="mobile"?"/m/":"/",A=c.filter(b=>b.surface==="user"&&!/[:*?#\\\\]/.test(b.path)&&b.path===I).sort((b,_)=>Ae(b.code,_.code))[0];if(A)return{code:A.code,path:A.path};let O=c.filter(b=>b.surface==="user"&&!/[:*?#\\\\]/.test(b.path)&&(g==="mobile"?b.path.startsWith("/m/"):!b.path.startsWith("/m/"))).sort((b,_)=>Ae(b.code,_.code))[0];return O?{code:O.code,path:O.path}:{code:g==="mobile"?"application-root-mobile":"application-root",path:I}},a=e.frontend.authentication?{desktop:{routeCode:e.frontend.authentication.surfaces.desktop.routeCode,path:e.frontend.authentication.surfaces.desktop.path},mobile:{routeCode:e.frontend.authentication.surfaces.mobile.routeCode,path:e.frontend.authentication.surfaces.mobile.path}}:{desktop:{routeCode:"application-login",path:"/login"},mobile:{routeCode:"application-login-mobile",path:"/m/login"}},d=Do(e.frontend.devicePolicy,"/config/frontend/devicePolicy"),f=s("desktop"),u=s("mobile"),p={schemaVersion:Ur,appCode:t,devicePolicy:d,rootEntry:{code:f.code,desktop:f.path,mobile:u.path},authentication:a,routes:r};return{...p,digest:Z(p)}}function un(e,t){if(e===void 0)return;let o=w(e,t,32);Ha.has(o)||m("NATIVE_ADMIN_ICON_INVALID",t)}function $r(e,t){e!==void 0&&ie(e,t,-1e4,1e4)}function ko(e,t,o){return e.capability!==void 0&&e.access!==void 0&&m("NATIVE_ROUTE_ACCESS_CONFLICT",`${t}/access`),e.capability!==void 0?{capability:pe(e.capability,`${t}/capability`,o)}:e.access===void 0?{}:{access:_n(e.access,`${t}/access`,o)}}function _n(e,t,o){let n=N(e,t);C(n,["allOf","anyOf"],t,!0);let i=n.allOf===void 0?void 0:U(V(n.allOf,`${t}/allOf`,50).map((c,s)=>pe(c,`${t}/allOf/${s}`,o))),r=n.anyOf===void 0?void 0:U(V(n.anyOf,`${t}/anyOf`,50).map((c,s)=>pe(c,`${t}/anyOf/${s}`,o)));return(i?.length||0)+(r?.length||0)===0&&m("NATIVE_ROUTE_ACCESS_EMPTY",t),{...i===void 0?{}:{allOf:i},...r===void 0?{}:{anyOf:r}}}function Yr(e){let t=new Map(Br(e).map(i=>[String(i.code),i])),o=e.workflows.definitions.map((i,r)=>{let c=`/config/workflows/definitions/${r}`,s=N(i,c);C(s,["version","definition","launch"],c,["detailRouteCode"]);let a=N(s.definition,`${c}/definition`),d=s.detailRouteCode===void 0?void 0:Zr(s.detailRouteCode,`${c}/detailRouteCode`);return{code:P(a.code,`${c}/definition/code`),title:w(a.title,`${c}/definition/title`,255),version:st(s.version,`${c}/version`),launch:Lc(e,a,s.launch,`${c}/launch`,t),...d?{detailRouteCode:d}:{},definition:a}});return U(o.map(i=>i.code)).map(i=>{let r=o.filter(d=>d.code===i),c=e.workflows.activations.find(d=>d.workflowCode===i)?.definitionVersion,s=r.find(d=>d.version===c)||[...r].sort((d,f)=>f.version-d.version)[0],a=new Set;for(let d of r){let f=N(d.definition.nodes,"/config/workflows/definitions/nodes");for(let u of Object.values(f)){let p=N(u,"/config/workflows/definitions/nodes/*");if(p.kind==="approval")for(let g of V(p.allowedOperations||[],"/config/workflows/definitions/nodes/*/allowedOperations",20))a.add(g)}}return{code:i,title:s.title,acceptedCommandDeactivationPolicy:s.definition.acceptedCommandDeactivationPolicy,subject:s.definition.subject,launch:s.launch,...["standalone","hidden-handoff"].includes(s.launch.mode)&&!s.launch.submission?{processOperationCode:`openxiangda.workflow.${i}.submit`}:{},...s.detailRouteCode?{detailRouteCode:s.detailRouteCode}:{},definitionVersions:jr(r.map(d=>d.version)),bindingVersions:jr(e.workflows.bindings.map((d,f)=>{let u=`/config/workflows/bindings/${f}`,p=N(d,u),g=N(p.binding,`${u}/binding`);return{code:P(g.workflowCode,`${u}/binding/workflowCode`),version:st(p.version,`${u}/version`)}}).filter(d=>d.code===i).map(d=>d.version)),providerCodes:U(e.workflows.providers.map((d,f)=>P(N(d,`/config/workflows/providers/${f}`).code,`/config/workflows/providers/${f}/code`))),allowedOperations:[...a].sort(Ae),editableParameterCodes:U(e.workflows.editableParameters.map((d,f)=>{let u=`/config/workflows/editableParameters/${f}`,p=N(d,u);return{code:P(p.code,`${u}/code`),workflowCode:P(p.workflowCode,`${u}/workflowCode`)}}).filter(d=>d.workflowCode===i).map(d=>d.code))}})}function Xr(e,t){let o=N(e,t);C(o,["mode"],t,["submission"]);let n=w(o.mode,`${t}/mode`,32);return["standalone","custom-page","hidden-handoff","work-center-only"].includes(n)||m("NATIVE_WORKFLOW_LAUNCH_MODE_INVALID",`${t}/mode`),{mode:n,...o.submission===void 0?{}:{submission:N(o.submission,`${t}/submission`)}}}function Lc(e,t,o,n,i){let r=Xr(o,n);if(!r.submission)return{mode:r.mode};["standalone","hidden-handoff"].includes(r.mode)||m("NATIVE_WORKFLOW_NAMED_OPERATION_SUBMISSION_INVALID",`${n}/submission`);let c=N(r.submission,`${n}/submission`);C(c,["kind"],`${n}/submission`,["create","existing","context"]),F(c.kind,"named-operation",`${n}/submission/kind`);let s=n.endsWith("/launch")?n.slice(0,-7):n,a=N(t.subject,`${s}/definition/subject`),d=H(a.resourceCode,`${s}/definition/subject/resourceCode`),f=e.data.resources.findIndex(y=>y.code===d),u=e.data.resources[f];(f<0||!u)&&m("NATIVE_WORKFLOW_SUBJECT_RESOURCE_MISSING",`${s}/definition/subject/resourceCode`);let p=new Set(N(u.schema,`/config/data/resources/${f}/schema`).fields.map(y=>String(y.code))),g=new Map(e.backend.operations.map(y=>[String(y.code),y])),I=(y,R)=>{let h=`${n}/submission/${R}`,$=N(y,h);C($,["operationCode","inputs","output"],h);let k=P($.operationCode,`${h}/operationCode`),M=g.get(k),L=i.get(k),Y=L?.platformAccess?.workflow?.codes;(!M||!L||L.method!=="POST"||!Array.isArray(Y)||!Y.includes(t.code))&&m("NATIVE_WORKFLOW_NAMED_OPERATION_INVALID",h);let ne=N(M.requestSchema,`${h}/operation/requestSchema`),X=N(ne.properties,`${h}/operation/requestSchema/properties`),de=new Set(ne.required===void 0?[]:V(ne.required,`${h}/operation/requestSchema/required`,64)),le=N($.inputs,`${h}/inputs`),v=Object.entries(le);(!v.length||v.length>64)&&m("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${h}/inputs`);let W=new Set,x=new Map,q={},z=L.platformAccess?.ownedSubject;z&&(R!=="create"||z.resourceCode!==d)&&m("NATIVE_WORKFLOW_OWNED_SUBJECT_LAUNCH_MISMATCH",h);for(let[J,Ye]of v){(!Tr.test(J)||!Object.prototype.hasOwnProperty.call(X,J))&&m("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${h}/inputs/${J}`);let je=`${h}/inputs/${J}`,In=N(Ye,je),We=w(In.source,`${je}/source`,32);if(["field","idempotency-key","current-user-reference","subject-id","subject-revision","requested-at"].includes(We)||m("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",je),C(In,["source"],je,We==="field"?["fieldCode"]:!1),x.set(We,(x.get(We)||0)+1),We==="field"){let Xe=G(In.fieldCode,`${je}/fieldCode`);(W.has(Xe)||!p.has(Xe))&&m("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${je}/fieldCode`),W.add(Xe),u.schema.fields.find(yn=>yn.code===Xe)?.type==="subtable"&&(!z||!z.subtables.some(yn=>yn.fieldCode===Xe))&&m("NATIVE_WORKFLOW_OWNED_SUBJECT_LAUNCH_REQUIRED",je),q[J]={source:We,fieldCode:Xe}}else q[J]={source:We}}([...de].some(J=>!(J in le))||(x.get("idempotency-key")||0)!==1||!v.some(([J,Ye])=>N(Ye,`${h}/inputs/${J}`).source==="idempotency-key"&&de.has(J))||R==="create"&&((x.get("subject-id")||0)>0||(x.get("subject-revision")||0)>0)||R==="existing"&&((x.get("subject-id")||0)!==1||(x.get("subject-revision")||0)!==1))&&m("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${h}/inputs`);let _e=N($.output,`${h}/output`);C(_e,["subjectId"],`${h}/output`,["subjectRevision","processCommand"]);let Oe=N(N(M.responseSchema,`${h}/operation/responseSchema`).properties,`${h}/operation/responseSchema/properties`);for(let J of["subjectId","subjectRevision","processCommand"]){if(_e[J]===void 0)continue;let Ye=w(_e[J],`${h}/output/${J}`,128);(!Tr.test(Ye)||!Object.prototype.hasOwnProperty.call(Oe,Ye))&&m("NATIVE_WORKFLOW_NAMED_OPERATION_OUTPUT_INVALID",`${h}/output/${J}`)}return{operationCode:k,method:"POST",path:L.path,requiredCapability:L.requiredCapability,requestSchemaDigest:L.requestSchemaDigest,responseSchemaDigest:L.responseSchemaDigest,inputs:q,output:{..._e},fieldCodes:W}},A=c.create===void 0?void 0:I(c.create,"create"),O=c.existing===void 0?void 0:I(c.existing,"existing");!A&&!O&&m("NATIVE_WORKFLOW_NAMED_OPERATION_SUBMISSION_INVALID",`${n}/submission`);let b=new Set([...A?.fieldCodes||[],...O?.fieldCodes||[]]),_=c.context===void 0?[]:S(c.context,`${n}/submission/context`,16),E=new Set,T=_.map((y,R)=>{let h=`${n}/submission/context/${R}`,$=N(y,h);C($,["queryParameter","fieldCode"],h);let k=w($.queryParameter,`${h}/queryParameter`,64),M=G($.fieldCode,`${h}/fieldCode`);return(!/^[A-Za-z][A-Za-z0-9]{0,63}$/.test(k)||E.has(k)||!b.has(M))&&m("NATIVE_WORKFLOW_LAUNCH_CONTEXT_INVALID",h),E.add(k),{queryParameter:k,fieldCode:M}}),l=y=>{let{fieldCodes:R,...h}=y;return h};return{mode:r.mode,submission:{kind:"named-operation",...A?{create:l(A)}:{},...O?{existing:l(O)}:{},context:T}}}function Zr(e,t){let o=N(e,t);C(o,["desktop","mobile"],t);let n=P(o.desktop,`${t}/desktop`),i=P(o.mobile,`${t}/mobile`);return n===i&&m("NATIVE_WORKFLOW_DETAIL_ROUTE_DUPLICATE",t),{desktop:n,mobile:i}}function Fc(e,t){let o=new Set(t.map(f=>f.code)),n=new Map;e.data.resources.forEach((f,u)=>{let p=`/config/data/resources/${u}`,g=N(f,p);if(g.recordDeletion!==void 0){let O=`${p}/recordDeletion/delete`;for(let b of g.recordDeletion.delete)pe(b,O,e.appCode),o.has(b)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",O)}if(g.recordComments!==void 0)for(let O of["read","create"]){let b=`${p}/recordComments/${O}`;for(let _ of g.recordComments[O])pe(_,b,e.appCode),o.has(_)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",b)}if(g.recordPrint!==void 0){let O=`${p}/recordPrint/read`;for(let b of g.recordPrint.read)pe(b,O,e.appCode),o.has(b)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",O)}if(g.workflowHistory!==void 0){let O=`${p}/workflowHistory/read`;for(let b of g.workflowHistory.read)pe(b,O,e.appCode),o.has(b)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",O)}for(let[O,b]of Object.entries(g.fieldPolicies||{})){if(!lt(O))continue;let _=`${p}/fieldPolicies/${O}/read`,E=N(b,`${p}/fieldPolicies/${O}`);for(let T of V(E.read||[],_,2e3))o.has(T)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",_)}let I=g.surface===void 0?{}:N(g.surface,`${p}/surface`);if(["native","queued-command"].includes(I.mutationOwner||"native"))return;let A=N(g.capabilities,`${p}/capabilities`);for(let O of["create","update","delete"])O==="delete"&&Array.isArray(g.recordDeletion?.delete)&&g.recordDeletion.delete.length>0||n.set(String(A[O]),O)});let i=new Set;for(let[f,u]of e.authz.roles.entries()){let p=`/config/authz/roles/${f}`,g=N(u,p);C(g,["code","name","description","capabilities"],p,!0);let I=P(g.code,`${p}/code`);i.has(I)&&m("NATIVE_ROLE_DUPLICATE",`${p}/code`),i.add(I),w(g.name,`${p}/name`,255);let A=V(g.capabilities,`${p}/capabilities`,2e3);for(let[O,b]of A.entries())n.has(b)&&m("NATIVE_DATA_SURFACE_MUTATION_GRANT_FORBIDDEN",`${p}/capabilities/${O}`,{operation:n.get(b)}),o.has(b)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",`${p}/capabilities`)}let r=e.authz.authenticatedUserRoleCode===void 0?"":P(e.authz.authenticatedUserRoleCode,"/config/authz/authenticatedUserRoleCode");r&&!i.has(r)&&m("NATIVE_AUTHENTICATED_USER_ROLE_REFERENCE_MISSING","/config/authz/authenticatedUserRoleCode");let c=new Set,s=0;for(let[f,u]of e.perspectives.entries()){let p=`/config/perspectives/${f}`,g=N(u,p);C(g,["code","name","description","roleCodes","capabilityCodes","default"],p,!0);let I=P(g.code,`${p}/code`);c.has(I)&&m("NATIVE_PERSPECTIVE_DUPLICATE",`${p}/code`),c.add(I),w(g.name,`${p}/name`,255);let A=V(g.roleCodes,`${p}/roleCodes`,20);A.length<1&&m("NATIVE_PERSPECTIVE_ROLE_REQUIRED",`${p}/roleCodes`),A.forEach((_,E)=>{i.has(_)||m("NATIVE_PERSPECTIVE_ROLE_MISSING",`${p}/roleCodes/${E}`)});let O=U(e.authz.roles.filter(_=>A.includes(_.code)).flatMap(_=>_.capabilities)),b=V(g.capabilityCodes,`${p}/capabilityCodes`,2e3);Q(O)!==Q(b)&&m("NATIVE_PERSPECTIVE_CAPABILITY_PROJECTION_MISMATCH",`${p}/capabilityCodes`),g.default===!0?s+=1:g.default!==void 0&&m("NATIVE_PERSPECTIVE_DEFAULT_INVALID",`${p}/default`)}s>1&&m("NATIVE_PERSPECTIVE_DEFAULT_DUPLICATE","/config/perspectives");for(let[f,u]of e.backend.operations.entries()){let p=N(u,`/config/backend/operations/${f}`);o.has(p.capability)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",`/config/backend/operations/${f}/capability`)}let a=new Set,d=new Set;for(let[f,u]of e.frontend.routes.entries()){let p=`/config/frontend/routes/${f}`,g=N(u,p),I=P(g.code,`${p}/code`);a.has(I)&&m("NATIVE_ROUTE_DUPLICATE",`${p}/code`),a.add(I);let A=be(g.path,`${p}/path`);d.has(A)&&m("NATIVE_ROUTE_PATH_DUPLICATE",`${p}/path`),d.add(A);let O=ko(g,p,e.appCode);O.capability&&!o.has(O.capability)&&m("NATIVE_CAPABILITY_REFERENCE_MISSING",`${p}/capability`);let b=g.access===void 0?void 0:N(g.access,`${p}/access`);for(let _ of["allOf","anyOf"]){let E=b?.[_]===void 0?[]:S(b[_],`${p}/access/${_}`,50);for(let[T,l]of E.entries()){let y=pe(l,`${p}/access/${_}/${T}`,e.appCode);o.has(y)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",`${p}/access/${_}/${T}`)}}}if(e.frontend.admin.access!==void 0){let f=_n(e.frontend.admin.access,"/config/frontend/admin/access",e.appCode);for(let u of["allOf","anyOf"])for(let[p,g]of(f[u]||[]).entries())o.has(g)||m("NATIVE_CAPABILITY_REFERENCE_MISSING",`/config/frontend/admin/access/${u}/${p}`)}for(let[f,u]of e.frontend.routes.entries()){let p=N(u,`/config/frontend/routes/${f}`);p.parentCode&&!a.has(p.parentCode)&&m("NATIVE_ROUTE_PARENT_MISSING",`/config/frontend/routes/${f}/parentCode`)}}function xc(e){let t=new Set(e.authz.roles.map(d=>String(d.code))),o=e.authz.authenticatedUserRoleCode===void 0?"":P(e.authz.authenticatedUserRoleCode,"/config/authz/authenticatedUserRoleCode"),n=new Map(e.authz.scopeDimensions.map(d=>[String(d.code),{valueType:d.valueType==="uuid"?"uuid":"string",...d.valueSource?.resourceCode?{valueSourceResourceCode:String(d.valueSource.resourceCode)}:{}}])),i=new Set(n.keys()),r=new Map(e.data.resources.map((d,f)=>{let u=Je(d,`/config/data/resources/${f}`,e.appCode);return[u.code,new Map(u.schema.fields.map(p=>[String(p.code),p]))]}));for(let[d,f]of e.authz.scopeDimensions.entries()){let u=`/config/authz/scopeDimensions/${d}`,p=N(f,u);if(C(p,["code","name","resourceCode","valueType","hierarchyMode","valueSource"],u,!0),p.valueSource===void 0)continue;let g=N(p.valueSource,`${u}/valueSource`);C(g,["kind","resourceCode","labelField","enabledField"],`${u}/valueSource`,!0),g.kind!=="native_resource"&&m("NATIVE_SCOPE_VALUE_SOURCE_KIND_INVALID",`${u}/valueSource/kind`),p.valueType!=="uuid"&&m("NATIVE_SCOPE_VALUE_SOURCE_TYPE_INVALID",`${u}/valueType`);let I=H(g.resourceCode,`${u}/valueSource/resourceCode`),A=r.get(I);A||m("NATIVE_SCOPE_VALUE_SOURCE_RESOURCE_MISSING",`${u}/valueSource/resourceCode`);let O=G(g.labelField,`${u}/valueSource/labelField`);if(["text.short","text.long"].includes(String(A.get(O)?.type||""))||m("NATIVE_SCOPE_VALUE_SOURCE_LABEL_FIELD_INVALID",`${u}/valueSource/labelField`),g.enabledField!==void 0){let b=G(g.enabledField,`${u}/valueSource/enabledField`);A.get(b)?.type!=="boolean"&&m("NATIVE_SCOPE_VALUE_SOURCE_ENABLED_FIELD_INVALID",`${u}/valueSource/enabledField`)}}let c=new Set,s=new Set;for(let[d,f]of e.authz.scopeSources.entries()){let u=`/config/authz/scopeSources/${d}`,p=N(f,u);C(p,["code","name","resourceCode","subject","grants","operationField","enabledField","effectiveFromField","effectiveToField","failureMode"],u,!0);let g=P(p.code,`${u}/code`);c.has(g)&&m("NATIVE_SCOPE_SOURCE_DUPLICATE",`${u}/code`),c.add(g),w(p.name,`${u}/name`,255);let I=H(p.resourceCode,`${u}/resourceCode`),A=r.get(I);A||m("NATIVE_SCOPE_SOURCE_RESOURCE_MISSING",`${u}/resourceCode`);let O=N(p.subject,`${u}/subject`),b=w(O.type,`${u}/subject/type`,32);C(O,b==="role_membership"?["type","userIdField","roleCode"]:["type","userIdField"],`${u}/subject`),["user","role_membership"].includes(b)||m("NATIVE_SCOPE_SOURCE_SUBJECT_INVALID",`${u}/subject/type`);let _=mt(O.userIdField,A);Hn(_)||m("NATIVE_SCOPE_SOURCE_SUBJECT_PATH_INVALID",`${u}/subject/userIdField`),b==="role_membership"&&!t.has(String(O.roleCode))&&m("NATIVE_ROLE_REFERENCE_MISSING",`${u}/subject/roleCode`);let E=new Set;for(let[T,l]of S(p.grants,`${u}/grants`,100).entries()){let y=`${u}/grants/${T}`,R=N(l,y);C(R,["dimensionCode","valueField","parentValueField"],y,!0);let h=P(R.dimensionCode,`${y}/dimensionCode`);(!i.has(h)||E.has(h))&&m("NATIVE_SCOPE_SOURCE_DIMENSION_INVALID",`${y}/dimensionCode`),E.add(h),p.failureMode==="last_known_good"&&s.add(h);for(let $ of["valueField","parentValueField"]){if(R[$]===void 0)continue;let k=mt(R[$],A);Ei(k,n.get(h),r)||m("NATIVE_SCOPE_SOURCE_GRANT_PATH_INVALID",`${y}/${$}`)}}E.size===0&&m("NATIVE_SCOPE_SOURCE_GRANT_REQUIRED",`${u}/grants`),["strict","last_known_good"].includes(p.failureMode)||m("NATIVE_SCOPE_SOURCE_FAILURE_MODE_INVALID",`${u}/failureMode`);for(let T of["operationField","enabledField","effectiveFromField","effectiveToField"]){if(p[T]===void 0)continue;let l=G(p[T],`${u}/${T}`);A.has(l)||m("NATIVE_SCOPE_SOURCE_FIELD_MISSING",`${u}/${T}`)}}Wc(e,t,r,o);let a=new Set;for(let[d,f]of e.authz.dataPolicies.entries()){let u=`/config/authz/dataPolicies/${d}`,p=N(f,u);C(p,["code","name","resourceCode","unrestrictedRoleCodes","publicRead","operations","matchMode","rules","readExpression","writeBoundary"],u,!0);let g=P(p.code,`${u}/code`);a.has(g)&&m("NATIVE_DATA_POLICY_DUPLICATE",`${u}/code`),a.add(g);let I=p.readExpression!==void 0,A=V(p.operations||[],`${u}/operations`,4);p.operations!==void 0&&(A.length===0||A.some(l=>!["read","create","update","delete"].includes(l)))&&m("NATIVE_DATA_POLICY_OPERATIONS_INVALID",`${u}/operations`),["AND","OR"].includes(p.matchMode)||m("NATIVE_DATA_POLICY_MATCH_MODE_INVALID",`${u}/matchMode`),I&&p.operations!==void 0&&m("NATIVE_DATA_POLICY_READ_EXPRESSION_OPERATIONS_FORBIDDEN",`${u}/operations`);let O=e.data.resources.find(l=>l.dataPolicyCode===g),b=p.resourceCode||O?.code,_=b?r.get(H(b,`${u}/resourceCode`)):void 0;if(I&&!_&&m("NATIVE_DATA_POLICY_RESOURCE_MISSING",`${u}/resourceCode`),p.publicRead!==void 0){try{let l=e.authz.roles.find(y=>y.code===o);Ci({policy:p,resource:e.data.resources.find(y=>y.code===b),baselineRoleCode:o,baselineCapabilities:l?.capabilities||[],baselineDeniedCapabilities:l?.deniedCapabilities||[],pointer:u})}catch(l){if(!(l instanceof gt))throw l;m(l.code,l.pointer)}(p.unrestrictedRoleCodes||[]).includes(o)||m("AUTHENTICATED_PUBLIC_READ_CANONICAL_BASELINE_MISSING",`${u}/unrestrictedRoleCodes`)}else o&&(p.unrestrictedRoleCodes||[]).includes(o)&&m("NATIVE_DATA_POLICY_BASELINE_UNRESTRICTED",`${u}/unrestrictedRoleCodes`);let E=V(p.unrestrictedRoleCodes||[],`${u}/unrestrictedRoleCodes`,100);p.unrestrictedRoleCodes!==void 0&&E.length===0&&m("NATIVE_DATA_POLICY_UNRESTRICTED_ROLES_INVALID",`${u}/unrestrictedRoleCodes`);for(let l of E)t.has(l)||m("NATIVE_ROLE_REFERENCE_MISSING",`${u}/unrestrictedRoleCodes`);let T;try{let l=S(p.rules,`${u}/rules`,100).map((y,R)=>({rule:N(y,`${u}/rules/${R}`),pointer:`${u}/rules/${R}`}));l.length===0?(!I||p.matchMode!=="AND"||p.writeBoundary!=="capability_only")&&m("NATIVE_DATA_POLICY_WRITE_BOUNDARY_REQUIRED",u):p.writeBoundary!==void 0&&m("NATIVE_DATA_POLICY_WRITE_BOUNDARY_INVALID",`${u}/writeBoundary`),T=[...l],I&&(T.push(...cn(p.readExpression,`${u}/readExpression`)),yr(p.readExpression,`${u}/readExpression`))}catch(l){throw l instanceof wt&&m(l.code,l.pointer),l}for(let{rule:l,pointer:y}of T){C(l,["subject","dimensionCode","relationCode","resourceCode","field","roleCodes","operation","valuePath","emptyMatchesAll","operator","value","operand"],y,!0);let R=G(l.field,`${y}/field`),h=_?.get(R);I&&!h&&m("NATIVE_DATA_POLICY_FIELD_MISSING",`${y}/field`);for(let X of V(l.roleCodes||[],`${y}/roleCodes`,100))t.has(X)||m("NATIVE_ROLE_REFERENCE_MISSING",`${y}/roleCodes`);let $=String(l.operator||""),k=l.operand==="db_now",M=["is_null","is_not_null"].includes($),L=["eq","not_eq","in","not_in"].includes($),Y=!k&&(l.operator!==void 0||l.value!==void 0);if([l.subject==="current_user"?"current_user":"",typeof l.dimensionCode=="string"?"dimension":"",typeof l.relationCode=="string"?"relationship":"",Y?"constant":"",k?"db_now":""].filter(Boolean).length!==1&&m("NATIVE_DATA_POLICY_RULE_SOURCE_INVALID",y),l.subject!==void 0&&l.subject!=="current_user"&&m("NATIVE_DATA_POLICY_SUBJECT_INVALID",`${y}/subject`),Y){if(!L&&!M&&m("NATIVE_DATA_POLICY_OPERATOR_INVALID",`${y}/operator`),["in","not_in"].includes($)){let X=S(l.value,`${y}/value`,100).map((de,le)=>w(de,`${y}/value/${le}`,2048));(X.length===0||new Set(X).size!==X.length)&&m("NATIVE_DATA_POLICY_VALUE_INVALID",`${y}/value`)}else["eq","not_eq"].includes($)?w(l.value,`${y}/value`,2048):(l.value!==void 0||l.operand!==void 0)&&m("NATIVE_DATA_POLICY_VALUE_INVALID",`${y}/value`);for(let X of["operation","valuePath","emptyMatchesAll","resourceCode","operand"])l[X]!==void 0&&m("NATIVE_DATA_POLICY_CONSTANT_RULE_INVALID",`${y}/${X}`)}if(k){(!["lt","lte","gt","gte"].includes($)||l.value!==void 0||h?.type!=="datetime")&&m("NATIVE_DATA_POLICY_DB_NOW_INVALID",y);for(let X of["operation","valuePath","emptyMatchesAll","resourceCode","value"])l[X]!==void 0&&m("NATIVE_DATA_POLICY_DB_NOW_INVALID",`${y}/${X}`)}l.dimensionCode&&!i.has(l.dimensionCode)&&m("NATIVE_SCOPE_DIMENSION_MISSING",`${y}/dimensionCode`),s.has(String(l.dimensionCode||""))&&l.operation!=="read"&&m("NATIVE_SCOPE_SOURCE_LAST_KNOWN_GOOD_UNSAFE",`${y}/operation`)}}for(let[d,f]of e.data.resources.entries()){let u=N(f,`/config/data/resources/${d}`);u.dataPolicyCode&&!a.has(u.dataPolicyCode)&&m("NATIVE_DATA_POLICY_REFERENCE_MISSING",`/config/data/resources/${d}/dataPolicyCode`)}}function jc(e){try{Yo(e.data.resources,"/config/data/resources"),e.data.resources.forEach((t,o)=>Bo(t.schema.fields,new Set(e.authz.roles.map(n=>n.code)),new Set(e.authz.scopeDimensions.map(n=>n.code)),`/config/data/resources/${o}/schema/fields`))}catch(t){throw(t instanceof Te||t instanceof Ue)&&m(t.code,t.pointer),t}}function Wc(e,t,o,n){let i=new Set;for(let[r,c]of e.authz.roleMembershipSources.entries()){let s=`/config/authz/roleMembershipSources/${r}`,a=N(c,s);C(a,["code","name","resourceCode","userIdField","roleCode","enabledField","effectiveFromField","effectiveToField","failureMode"],s,!0);let d=P(a.code,`${s}/code`);d.length>100&&m("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_CODE_INVALID",`${s}/code`),i.has(d)&&m("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_DUPLICATE",`${s}/code`),i.add(d),w(a.name,`${s}/name`,255);let f=vr(a.resourceCode,`${s}/resourceCode`,o);Pr(a.userIdField,`${s}/userIdField`,f),t.has(String(a.roleCode||""))||m("NATIVE_ROLE_REFERENCE_MISSING",`${s}/roleCode`),n&&a.roleCode===n&&m("NATIVE_AUTHENTICATED_USER_ROLE_SOURCE_CONFLICT",`${s}/roleCode`),Vr(a,s,f)}for(let[r,c]of e.authz.relationshipGrantSources.entries()){let s=`/config/authz/relationshipGrantSources/${r}`,a=N(c,s);C(a,["code","name","resourceCode","subject","relationCode","targetResourceCode","resourceIdField","operations","enabledField","effectiveFromField","effectiveToField","failureMode"],s,!0);let d=P(a.code,`${s}/code`);d.length>100&&m("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_CODE_INVALID",`${s}/code`),i.has(d)&&m("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_DUPLICATE",`${s}/code`),i.add(d),w(a.name,`${s}/name`,255);let f=vr(a.resourceCode,`${s}/resourceCode`,o),u=N(a.subject,`${s}/subject`),p=w(u.type,`${s}/subject/type`,32);C(u,p==="role_membership"?["type","userIdField","roleCode"]:["type","userIdField"],`${s}/subject`),["user","role_membership"].includes(p)||m("NATIVE_AUTHORIZATION_PROJECTION_SUBJECT_INVALID",`${s}/subject/type`),Pr(u.userIdField,`${s}/subject/userIdField`,f),p==="role_membership"&&!t.has(String(u.roleCode||""))&&m("NATIVE_ROLE_REFERENCE_MISSING",`${s}/subject/roleCode`),P(a.relationCode,`${s}/relationCode`);let g=H(a.targetResourceCode,`${s}/targetResourceCode`);o.has(g)||m("NATIVE_AUTHORIZATION_PROJECTION_TARGET_RESOURCE_MISSING",`${s}/targetResourceCode`);let I=mt(a.resourceIdField,f),A=I?.field.type==="resource-ref.single"&&I.valuePath==="value"&&I.field.source?.resourceCode===g;(a.resourceIdField==="id"?g!==String(a.resourceCode):!A)&&m("NATIVE_AUTHORIZATION_PROJECTION_RESOURCE_ID_FIELD_INVALID",`${s}/resourceIdField`);let O=V(a.operations,`${s}/operations`,20);(O.length===0||O.some(b=>b.length>64||!/^[A-Za-z0-9][A-Za-z0-9:._*-]{0,63}$/.test(b)))&&m("NATIVE_AUTHORIZATION_PROJECTION_OPERATIONS_INVALID",`${s}/operations`),Vr(a,s,f)}}function vr(e,t,o){let n=H(e,t),i=o.get(n);return i||m("NATIVE_AUTHORIZATION_PROJECTION_RESOURCE_MISSING",t),i}function Pr(e,t,o){let n=mt(e,o);Hn(n)||m("NATIVE_AUTHORIZATION_PROJECTION_USER_FIELD_INVALID",t)}function Vr(e,t,o){if(e.failureMode!=="strict"&&m("NATIVE_AUTHORIZATION_PROJECTION_FAILURE_MODE_INVALID",`${t}/failureMode`),e.enabledField!==void 0){let n=G(e.enabledField,`${t}/enabledField`);o.get(n)?.type!=="boolean"&&m("NATIVE_AUTHORIZATION_PROJECTION_ENABLED_FIELD_INVALID",`${t}/enabledField`)}for(let n of["effectiveFromField","effectiveToField"]){if(e[n]===void 0)continue;let i=G(e[n],`${t}/${n}`);["date","datetime"].includes(String(o.get(i)?.type))||m("NATIVE_AUTHORIZATION_PROJECTION_EFFECTIVE_FIELD_INVALID",`${t}/${n}`)}}function Uc(e){let t=new Set,o=new Set;e.forEach((n,i)=>{let r=`/config/backend/secrets/${i}`,c=N(n,r);C(c,["name","env","description","required","exposure"],r,!0);let s=w(c.name,`${r}/name`,128),a=w(c.env,`${r}/env`,128);Ua.test(s)||m("NATIVE_SECRET_NAME_INVALID",`${r}/name`),(!Ma.test(a)||a.startsWith("OPENXIANGDA_")||["NODE_ENV","PORT"].includes(a))&&m("NATIVE_SECRET_ENV_INVALID",`${r}/env`),t.has(s)&&m("NATIVE_SECRET_NAME_DUPLICATE",`${r}/name`),o.has(a)&&m("NATIVE_SECRET_ENV_DUPLICATE",`${r}/env`),t.add(s),o.add(a),F(c.exposure,"active_only",`${r}/exposure`),c.required!==void 0&&at(c.required,`${r}/required`),c.description!==void 0&&$o(c.description,`${r}/description`,2e3)})}function Mc(e){let t=new Set,o=new Map,n=new Map(e.data.resources.map(g=>[String(g.code),g])),i=new Map(e.frontend.routes.map((g,I)=>{let A=N(g,`/config/frontend/routes/${I}`);return[P(A.code,`/config/frontend/routes/${I}/code`),A]}));for(let[g,I]of e.workflows.definitions.entries()){let A=`/config/workflows/definitions/${g}`,O=N(I,A);if(C(O,["version","definition","launch"],A,["detailRouteCode"]),Xr(O.launch,`${A}/launch`),O.detailRouteCode!==void 0){let h=Zr(O.detailRouteCode,`${A}/detailRouteCode`);for(let[$,k,M]of[["desktop",h.desktop,["admin","user"]],["mobile",h.mobile,["user"]]]){let L=`${A}/detailRouteCode/${$}`,Y=i.get(k);Y||m("NATIVE_WORKFLOW_DETAIL_ROUTE_MISSING",L),M.some(de=>de===Y.surface)||m("NATIVE_WORKFLOW_DETAIL_ROUTE_SURFACE_INVALID",L);let ne=be(Y.path,L),X=[...ne.matchAll(/:([A-Za-z][A-Za-z0-9_]*)/g)].map(de=>de[1]);(ne.includes("*")||X.length!==1||X[0]!=="instanceId")&&m("NATIVE_WORKFLOW_DETAIL_ROUTE_PATH_INVALID",L)}}let b=N(O.definition,`${A}/definition`),_=`${b.code}:${st(O.version,`${A}/version`)}`;t.has(_)&&m("NATIVE_WORKFLOW_DEFINITION_DUPLICATE",A),t.add(_),Kc(b,`${A}/definition`);let E=fo(b);E.length&&m(E[0],`${A}/definition/launchPreflight`);let T=ir(b);T.length&&m(T[0],`${A}/definition/approvedDelegation`);let l=tr(b,e.backend.operations);l.length&&m(l[0],`${A}/definition/commandHandlers`),Bc(b.subject,n,`${A}/definition/subject`);let y=rn(b,new Map((n.get(b.subject.resourceCode)?.schema.fields||[]).map(h=>[h.code,{...n.get(b.subject.resourceCode)?.surface?.fields?.[h.code],...h,system:["id","revision","createdAt","updatedAt","createdBy","updatedBy"].includes(h.code)}])),new Map([...n].map(([h,$])=>[h,new Map($.schema.fields.map(k=>[k.code,{...$.surface?.fields?.[k.code],...k,system:["id","revision","createdAt","updatedAt","createdBy","updatedBy"].includes(k.code)}]))])));y.length&&m(y[0],`${A}/definition/taskPages`);let R=Vi(b,{appCode:e.appCode,capabilities:e.authz.capabilities.map(h=>h.code),fields:new Map((n.get(b.subject.resourceCode)?.schema.fields||[]).map(h=>[h.code,h]))});R.length&&m("NATIVE_WORKFLOW_INSTANCE_COMMAND_POLICY_INVALID",`${A}/definition/instanceCommands`,{errors:R}),b.title===b.code&&m("NATIVE_WORKFLOW_USER_TITLE_REQUIRED",`${A}/definition/title`),o.set(_,b)}let r=new Set,c=new Map;for(let[g,I]of e.workflows.bindings.entries()){let A=N(I,`/config/workflows/bindings/${g}`),O=N(A.binding,`/config/workflows/bindings/${g}/binding`),b=`${O.workflowCode}:${st(A.version,`/config/workflows/bindings/${g}/version`)}`;r.has(b)&&m("NATIVE_WORKFLOW_BINDING_DUPLICATE",`/config/workflows/bindings/${g}`),r.add(b),Gc(O,`/config/workflows/bindings/${g}/binding`),c.set(b,O)}let s=new Set,a=new Map;for(let[g,I]of e.workflows.activations.entries()){let A=`/config/workflows/activations/${g}`,O=N(I,A);C(O,["workflowCode","definitionVersion","bindingVersion","acceptedCommandDeactivationPolicy"],A,["environmentKey"]);let b=P(O.workflowCode,`${A}/workflowCode`);s.has(b)&&m("NATIVE_WORKFLOW_ACTIVATION_DUPLICATE",A),s.add(b);let _=`${b}:${st(O.definitionVersion,`${A}/definitionVersion`)}`,E=`${b}:${st(O.bindingVersion,`${A}/bindingVersion`)}`;t.has(_)||m("NATIVE_WORKFLOW_DEFINITION_REFERENCE_MISSING",`${A}/definitionVersion`),r.has(E)||m("NATIVE_WORKFLOW_BINDING_REFERENCE_MISSING",`${A}/bindingVersion`);let T=o.get(_),l=c.get(E),y=fo(T,l);y.length&&m(y[0],A);let R=ao(T,l);R.length&&m(R[0],A),(!["finish-pinned","cancel-on-deactivate"].includes(O.acceptedCommandDeactivationPolicy)||O.acceptedCommandDeactivationPolicy!==T.acceptedCommandDeactivationPolicy)&&m("NATIVE_WORKFLOW_COMMAND_DEACTIVATION_POLICY_MISMATCH",`${A}/acceptedCommandDeactivationPolicy`),qc(T,l,`/config/workflows/activations/${g}`);try{let h=n.get(T.subject.resourceCode)?.schema.fields||[];Ko(T,l,new Map(h.map($=>[$.code,$])),`${A}/bindings`,new Map([...n].map(([$,k])=>[$,new Map(k.schema.fields.map(M=>[M.code,M]))])))}catch(h){throw h instanceof Ue&&m(h.code,h.pointer),h}a.set(b,l)}let d=_r([...a.values()]);d.length&&m(d[0],"/config/workflows/activations");let f=new Set;e.workflows.providers.forEach((g,I)=>{let A=`/config/workflows/providers/${I}`,O=N(g,A);C(O,["code","endpointPath","timeoutMs"],A,!0);let b=P(O.code,`${A}/code`);f.has(b)&&m("NATIVE_WORKFLOW_PROVIDER_DUPLICATE",`${A}/code`),f.add(b),be(O.endpointPath,`${A}/endpointPath`),O.timeoutMs!==void 0&&ie(O.timeoutMs,`${A}/timeoutMs`,100,1e4)});for(let[g,I]of a.entries())for(let[A,O]of Object.entries(N(I.bindings,"/config/workflows/bindings/*/binding/bindings"))){let b=N(O,`/config/workflows/${g}/bindings/${A}`);b.provider==="application_provider"&&!f.has(b.providerCode)&&m("NATIVE_WORKFLOW_PROVIDER_REFERENCE_MISSING",`/config/workflows/${g}/bindings/${A}/providerCode`)}let u=new Set(e.authz.roles.map(g=>g.code)),p=new Set;e.workflows.editableParameters.forEach((g,I)=>{let A=`/config/workflows/editableParameters/${I}`,O=N(g,A);C(O,["code","workflowCode","bindingKey","label","valueType","required","allowedRoleCodes","allowedProviderCodes","maxItems"],A,!0);let b=P(O.code,`${A}/code`);p.has(b)&&m("NATIVE_WORKFLOW_EDITABLE_PARAMETER_DUPLICATE",`${A}/code`),p.add(b);let _=gn(O.workflowCode,`${A}/workflowCode`),E=fn(O.bindingKey,`${A}/bindingKey`),T=a.get(_);(!T||!N(T.bindings,`${A}/bindingKey`)[E])&&m("NATIVE_WORKFLOW_EDITABLE_BINDING_MISSING",`${A}/bindingKey`),w(O.label,`${A}/label`,255),["role_code","user_ids","provider_code"].includes(O.valueType)||m("NATIVE_WORKFLOW_EDITABLE_VALUE_TYPE_INVALID",`${A}/valueType`);for(let l of V(O.allowedRoleCodes||[],`${A}/allowedRoleCodes`,100))u.has(l)||m("NATIVE_ROLE_REFERENCE_MISSING",`${A}/allowedRoleCodes`);for(let l of V(O.allowedProviderCodes||[],`${A}/allowedProviderCodes`,100))f.has(l)||m("NATIVE_WORKFLOW_PROVIDER_REFERENCE_MISSING",`${A}/allowedProviderCodes`);O.required!==void 0&&at(O.required,`${A}/required`),O.maxItems!==void 0&&ie(O.maxItems,`${A}/maxItems`,1,200)})}function Bc(e,t,o){let n=N(e,o);C(n,["resourceCode","factProjection"],o,["summaryFields"]);let i=H(n.resourceCode,`${o}/resourceCode`),r=t.get(i);r||m("NATIVE_WORKFLOW_SUBJECT_RESOURCE_MISSING",`${o}/resourceCode`);let c=new Set(S(N(r.schema,`${o}/resourceCode`).fields,`${o}/resourceCode`,500).map((d,f)=>G(N(d,`${o}/resourceCode/${f}`).code,`${o}/resourceCode/${f}`))),s=N(n.factProjection,`${o}/factProjection`),a=Object.entries(s);(a.length<1||a.length>64)&&m("NATIVE_WORKFLOW_SUBJECT_FACT_PROJECTION_INVALID",`${o}/factProjection`);for(let[d,f]of a){Ga.test(d)||m("NATIVE_WORKFLOW_SUBJECT_FACT_KEY_INVALID",`${o}/factProjection/${d}`);let u=G(f,`${o}/factProjection/${d}`);c.has(u)||m("NATIVE_WORKFLOW_SUBJECT_FIELD_MISSING",`${o}/factProjection/${d}`)}if(n.summaryFields!==void 0){let d=V(n.summaryFields,`${o}/summaryFields`,qa).map((I,A)=>G(I,`${o}/summaryFields/${A}`)),f=t.get(i),u=f.surface&&typeof f.surface=="object"&&!Array.isArray(f.surface)?f.surface:{},p=u.fields&&typeof u.fields=="object"&&!Array.isArray(u.fields)?u.fields:{},g=new Map(S(N(f.schema,`${o}/resourceCode`).fields,`${o}/resourceCode`,500).map((I,A)=>{let O=N(I,`${o}/resourceCode/${A}`);return[String(O.code),O]}));for(let[I,A]of d.entries()){let O=g.get(A),b=p[A],_=String(O?.type||""),E=O?.maxLength;(!O||O.system===!0||b&&typeof b=="object"&&!Array.isArray(b)&&b.system===!0||["id","revision","created_by","updated_by","created_at","updated_at"].includes(A)||!Ja.has(_)||_==="text.long"&&typeof E=="number"&&Number.isFinite(E)&&E>za)&&m("NATIVE_WORKFLOW_SUBJECT_SUMMARY_FIELDS_INVALID",`${o}/summaryFields/${I}`)}}}function Kc(e,t){C(e,["schemaVersion","code","title","subject","acceptedCommandDeactivationPolicy","startAt","inputSchema","nodes"],t,["organizationContext","instanceCommands","readability","taskPages","rejectionNotification","commandHandlers","launchPreflight","approvedDelegation"]),F(e.schemaVersion,"openxiangda.workflow-definition/v2",`${t}/schemaVersion`),gn(e.code,`${t}/code`),w(e.title,`${t}/title`,255),["finish-pinned","cancel-on-deactivate"].includes(e.acceptedCommandDeactivationPolicy)||m("NATIVE_WORKFLOW_COMMAND_DEACTIVATION_POLICY_REQUIRED",`${t}/acceptedCommandDeactivationPolicy`);let o=N(e.nodes,`${t}/nodes`),n=Object.keys(o);(n.length===0||n.length>200)&&m("NATIVE_WORKFLOW_NODE_COUNT_INVALID",`${t}/nodes`);let i=w(e.startAt,`${t}/startAt`,128),r=Ki(e);r.length&&m(r[0],`${t}/readability`);let c=ao(e);c.length&&m(c[0],`${t}/nodes`);let s=lo(e);s.length&&m(s[0],`${t}/nodes`);let a=yt(e);a.length&&m(a[0],`${t}/nodes`);let d=Zi(e);d.length&&m(d[0],`${t}/nodes`);let f=er(e);f.length&&m(f[0],`${t}/rejectionNotification`);let u=co(e);u.length&&m(u[0],`${t}/nodes`);let p=rn(e);p.length&&m(p[0],`${t}/taskPages`);let g=Xt(e);g.length&&m(g[0],`${t}/nodes`),o[i]||m("NATIVE_WORKFLOW_START_NODE_MISSING",`${t}/startAt`);let I=new Map;for(let[_,E]of Object.entries(o)){let T=`${t}/nodes/${_}`,l=N(E,T);F(l.id,_,`${T}/id`),["approval","condition","end","cc","action","correction"].includes(l.kind)||m("NATIVE_WORKFLOW_NODE_KIND_INVALID",`${T}/kind`);let y=[];if(l.kind==="approval"){w(l.title,`${T}/title`,255),fn(l.binding,`${T}/binding`),["single","any","all","sequence"].includes(l.mode)||m("NATIVE_WORKFLOW_APPROVAL_MODE_INVALID",`${T}/mode`),y.push(w(l.onApprove,`${T}/onApprove`,128),w(l.onReject,`${T}/onReject`,128));for(let R of V(l.returnTargets||[],`${T}/returnTargets`,200))o[R]||m("NATIVE_WORKFLOW_TARGET_MISSING",`${T}/returnTargets`);for(let R of V(l.allowedOperations||[],`${T}/allowedOperations`,20))Ya.has(R)||m("NATIVE_WORKFLOW_OPERATION_INVALID",`${T}/allowedOperations`)}else if(l.kind==="correction"){let R=rr(e);R.length&&m(R[0],T)}else if(l.kind==="action")y.push(w(l.next,`${T}/next`,128));else if(l.kind==="cc")w(l.title,`${T}/title`,255),fn(l.binding,`${T}/binding`),y.push(w(l.next,`${T}/next`,128));else if(l.kind==="condition"){let R=S(l.branches,`${T}/branches`,100);R.length===0&&m("NATIVE_WORKFLOW_BRANCH_REQUIRED",`${T}/branches`),R.forEach((h,$)=>{let k=N(h,`${T}/branches/${$}`);St(k.when,`${T}/branches/${$}/when`,0),y.push(w(k.target,`${T}/branches/${$}/target`,128))}),y.push(w(l.otherwise,`${T}/otherwise`,128))}else w(l.title,`${T}/title`,255),w(l.outcome,`${T}/outcome`,128);for(let R of y)o[R]||m("NATIVE_WORKFLOW_TARGET_MISSING",T);I.set(_,y)}let A=new Set,O=new Set,b=_=>{if(O.has(_)&&m("NATIVE_WORKFLOW_CYCLE_FORBIDDEN",`${t}/nodes/${_}`),!A.has(_)){A.add(_),O.add(_);for(let E of I.get(_)||[])b(E);O.delete(_)}};b(i);for(let _ of[...A]){let E=o[_];if(E?.kind==="approval")for(let T of E.returnTargets||[])o[T]?.kind==="correction"&&A.add(T)}A.size!==n.length&&m("NATIVE_WORKFLOW_NODE_UNREACHABLE",`${t}/nodes`)}function St(e,t,o){o>20&&m("NATIVE_WORKFLOW_EXPRESSION_DEPTH_EXCEEDED",t);let n=N(e,t),i=w(n.op,`${t}/op`,16);if(i!=="literal"){if(i==="path"){let r=w(n.path,`${t}/path`,255);(!/^[A-Za-z][A-Za-z0-9_.-]{0,254}$/.test(r)||r.split(".").some(c=>["__proto__","constructor","prototype"].includes(c)))&&m("NATIVE_WORKFLOW_EXPRESSION_PATH_INVALID",`${t}/path`);return}if(["eq","neq","gt","gte","lt","lte","in","contains"].includes(i)){St(n.left,`${t}/left`,o+1),St(n.right,`${t}/right`,o+1);return}if(["and","or"].includes(i)){let r=S(n.values,`${t}/values`,100);r.length===0&&m("NATIVE_WORKFLOW_EXPRESSION_EMPTY",`${t}/values`),r.forEach((c,s)=>St(c,`${t}/values/${s}`,o+1));return}if(["not","exists"].includes(i)){St(n.value,`${t}/value`,o+1);return}m("NATIVE_WORKFLOW_EXPRESSION_OPERATOR_INVALID",`${t}/op`)}}function Gc(e,t){F(e.schemaVersion,"openxiangda.workflow-binding/v2",`${t}/schemaVersion`),gn(e.workflowCode,`${t}/workflowCode`);let o=N(e.bindings,`${t}/bindings`);Object.keys(o).length>200&&m("NATIVE_WORKFLOW_BINDING_LIMIT_EXCEEDED",`${t}/bindings`);for(let[n,i]of Object.entries(o)){fn(n,`${t}/bindings/${n}`);let r=N(i,`${t}/bindings/${n}`),c=en(r);c.length&&m(c[0],`${t}/bindings/${n}/roleCodes`);let s=w(r.provider,`${t}/bindings/${n}/provider`,64);if(["fixed_users","initiator","input_users","form_field_users","department_supervisor","app_role","app_role_in_scope","business_relation","previous_node_actor","initiator_select","application_provider"].includes(s)||m("NATIVE_WORKFLOW_BINDING_PROVIDER_INVALID",`${t}/bindings/${n}/provider`),s==="fixed_users"&&(Array.isArray(r.users)||m("NATIVE_WORKFLOW_BINDING_USERS_REQUIRED",`${t}/bindings/${n}/users`),S(r.users,`${t}/bindings/${n}/users`,200)),["input_users","form_field_users"].includes(s)&&w(r.inputPath,`${t}/bindings/${n}/inputPath`,255),["app_role","app_role_in_scope","initiator_select"].includes(s)&&r.roleCodes===void 0&&P(r.roleCode,`${t}/bindings/${n}/roleCode`),s==="department_supervisor"&&w(r.departmentIdFrom,`${t}/bindings/${n}/departmentIdFrom`,255),s==="application_provider"&&P(r.providerCode,`${t}/bindings/${n}/providerCode`),r.routing!==void 0){let a=sn(r.routing);a.length&&m(a[0],`${t}/bindings/${n}/routing`)}}}function qc(e,t,o){F(t.workflowCode,e.code,`${o}/workflowCode`);let n=N(t.bindings,`${o}/bindings`);for(let[s,a]of Object.entries(n))a.provider==="fixed_users"&&!a.users.length&&!Yi(e,s)&&m("NATIVE_WORKFLOW_BINDING_USERS_REQUIRED",`${o}/bindings/${s}/users`);let i=lo(e,t);i.length&&m(i[0],o);let r=co(e,t);r.length&&m(r[0],o);let c=Xt(e,t);c.length&&m(c[0],o);for(let[s,a]of Object.entries(N(e.nodes,`${o}/nodes`))){let d=N(a,`${o}/nodes/${s}`);["approval","cc"].includes(d.kind)&&!n[d.binding]&&m("NATIVE_WORKFLOW_BINDING_REFERENCE_MISSING",`${o}/nodes/${s}/binding`)}}function zc(e,t,o){let n=N(t.routeManifest,"/contracts/routeManifest"),i=N(e.routeManifest,"/contracts/routeManifest"),r=new Map;for(let f of S(o.data?.resources,"/config/data/resources",B.resources)){let u=N(f,"/config/data/resources");r.set(String(u.code||""),u)}let c=new Set(S(i.routes,"/contracts/routeManifest/routes",B.routes).map(f=>String(N(f,"/contracts/routeManifest/routes").code||""))),s=[];for(let f of S(n.routes,"/contracts/routeManifest/routes",B.routes)){let u=N(f,"/contracts/routeManifest/routes"),p=String(u.kind||"");if(p!=="resource-records"&&p!=="resource-submit")continue;let g=String(u.resourceCode||""),I=r.get(g);I||m("NATIVE_ROUTE_MANIFEST_RESOURCE_UNKNOWN","/contracts/routeManifest/routes");let O=`user.${g}.${p==="resource-records"?"records":"submit"}`;F(String(u.code||""),O,"/contracts/routeManifest/routes/code");let b=p==="resource-records"?"read":"create",_=String(N(I.capabilities,"/config/data/resources/capabilities")[b]||"");for(let E of["desktop","mobile"]){let T=N(u[E],`/contracts/routeManifest/routes/${E}`),l=E==="mobile"?"/m/my/":"/my/",y=p==="resource-records"?`${l}${g}`:`${l}${g}/submit`;F(String(T.path||""),y,`/contracts/routeManifest/routes/${E}/path`),F(String(T.capability||""),_,`/contracts/routeManifest/routes/${E}/capability`),F(String(T.routeCode||""),`${O}.${E}`,`/contracts/routeManifest/routes/${E}/routeCode`)}(c.has(O)||s.some(E=>String(E.code)===O))&&m("NATIVE_ROUTE_MANIFEST_DUPLICATE","/contracts/routeManifest/routes/code"),s.push(u)}if(!s.length)return;i.routes=S([...i.routes,...s],"/contracts/routeManifest/routes",1e3).sort((f,u)=>Ae(String(N(f,"x").code||""),String(N(u,"x").code||"")));let a=String(N(n.rootEntry,"x").code||"");if(s.find(f=>String(f.code)===a&&f.kind==="resource-records")){let f=N(n.rootEntry,"x");i.rootEntry={code:a,desktop:String(f.desktop||""),mobile:String(f.mobile||"")}}i.digest=Z({schemaVersion:i.schemaVersion,appCode:i.appCode,devicePolicy:i.devicePolicy,rootEntry:i.rootEntry,authentication:i.authentication,routes:i.routes})}function Je(e,t,o){let n=N(e,t);C(n,["schemaVersion","appCode","code","name","schema","surface","invariants","decimalReservationLifecycle","uniqueKeys","workflowHistory","recordPrint","recordComments","recordDeletion","capabilities","dataPolicyCode","fieldPolicies"],t,!0),F(n.schemaVersion,"openxiangda.data-resource/v2",`${t}/schemaVersion`),F(n.appCode,o,`${t}/appCode`);let i=H(n.code,`${t}/code`),r=w(n.name,`${t}/name`,255),c=N(n.schema,`${t}/schema`);C(c,["fields"],`${t}/schema`);let s,a,d,f;try{d=qn(n.decimalReservationLifecycle,`${t}/decimalReservationLifecycle`),s=$n(c.fields,`${t}/schema/fields`),f=wi(n.uniqueKeys,s,`${t}/uniqueKeys`),a=Xo(n.invariants,s,`${t}/invariants`),Un(n.surface,s,`${t}/surface`)}catch(I){throw(I instanceof Te||I instanceof Ue||I instanceof nt||I instanceof Et)&&m(I.code,I.pointer),I}if(n.recordComments!==void 0){let I=N(n.recordComments,`${t}/recordComments`);C(I,["read","create"],`${t}/recordComments`);for(let A of["read","create"]){let O=I[A];(!Array.isArray(O)||O.length>20||O.some(b=>typeof b!="string"||!b.trim())||new Set(O).size!==O.length)&&m("NATIVE_RECORD_COMMENTS_POLICY_INVALID",`${t}/recordComments/${A}`)}}if(n.recordDeletion!==void 0){let I=N(n.recordDeletion,`${t}/recordDeletion`);C(I,["delete"],`${t}/recordDeletion`);let A=I.delete;(!Array.isArray(A)||A.length>20||A.some(O=>typeof O!="string"||!O.trim())||new Set(A).size!==A.length)&&m("NATIVE_RECORD_DELETION_DELETE_INVALID",`${t}/recordDeletion/delete`)}if(n.recordPrint!==void 0){let I=N(n.recordPrint,`${t}/recordPrint`);C(I,["read"],`${t}/recordPrint`);let A=I.read;(!Array.isArray(A)||A.length>20||A.some(O=>typeof O!="string"||!O.trim())||new Set(A).size!==A.length)&&m("NATIVE_RECORD_PRINT_READ_INVALID",`${t}/recordPrint/read`)}if(n.workflowHistory!==void 0){let I=N(n.workflowHistory,`${t}/workflowHistory`);C(I,["read"],`${t}/workflowHistory`);let A=I.read;(!Array.isArray(A)||A.length>20||A.some(O=>typeof O!="string"||!O.trim())||new Set(A).size!==A.length)&&m("NATIVE_WORKFLOW_HISTORY_READ_INVALID",`${t}/workflowHistory/read`)}let u=new Set(s.map(I=>I.code)),p=N(n.capabilities,`${t}/capabilities`);C(p,["read","create","update","delete"],`${t}/capabilities`);let g=N(n.fieldPolicies,`${t}/fieldPolicies`);for(let[I,A]of Object.entries(g)){!u.has(I)&&!lt(I)&&m("NATIVE_DATA_FIELD_POLICY_FIELD_MISSING",`${t}/fieldPolicies/${I}`);let O=`${t}/fieldPolicies/${I}`,b=N(A,O);lt(I)&&(C(b,["read"],O,!0),(!Array.isArray(b.read)||b.read.length>20||b.read.some(_=>typeof _!="string"||!_.trim())||new Set(b.read).size!==b.read.length)&&m("NATIVE_DATA_AUDIT_READ_POLICY_INVALID",`${O}/read`)),C(b,["read","create","update","mask"],O,!0),b.mask!==void 0&&!["omit","null"].includes(b.mask)&&m("NATIVE_DATA_FIELD_POLICY_MASK_INVALID",`${O}/mask`)}return{...n,code:i,name:r,schema:{fields:s},...n.invariants===void 0?{}:{invariants:a},...d?{decimalReservationLifecycle:d}:{},...f!==void 0?{uniqueKeys:f}:{},capabilities:p,fieldPolicies:g}}function Qr(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 Lr(e,t,o,n){let i=e.toString("utf8"),r;try{r=JSON.parse(i)}catch{m(o,t)}let c=N(r,t);return Q(c)!==i&&m(n,t),c}function bo(e,t,o){let n=0,i=(r,c,s)=>{if(n+=1,n>o&&m("NATIVE_ARTIFACT_NODE_LIMIT_EXCEEDED",c),s>Qa&&m("NATIVE_ARTIFACT_DEPTH_LIMIT_EXCEEDED",c),typeof r=="string"){Buffer.byteLength(r)>No&&m("NATIVE_ARTIFACT_STRING_LIMIT_EXCEEDED",c);return}if(Array.isArray(r)){r.forEach((a,d)=>i(a,`${c}/${d}`,s+1));return}if(!(!r||typeof r!="object"))for(let[a,d]of Object.entries(r))["__proto__","prototype","constructor"].includes(a)&&m("NATIVE_ARTIFACT_DANGEROUS_KEY",`${c}/${a}`),Jc(a)&&m("NATIVE_ARTIFACT_RUNTIME_FIELD_FORBIDDEN",`${c}/${a}`),i(d,`${c}/${a}`,s+1)};i(e,t,0)}function Jc(e){return["environmentKey","environmentId","secretValue","ciphertext","oauthClient","oauthClientId","oauthClientSecret","signingSecret","kubernetesNamespace","nodePort","productionUrl"].includes(e)}function rt(e){return{value:e,digest:Z(e)}}function Fr(e,t,o,n){typeof e!="string"&&!Buffer.isBuffer(e)&&!(e instanceof Uint8Array)&&m("NATIVE_ARTIFACT_BYTES_REQUIRED",o);let i=Buffer.isBuffer(e)?e:Buffer.from(e);return i.byteLength===0&&m("NATIVE_ARTIFACT_EMPTY",o),i.byteLength>t&&m(n,o),i}function xr(e,t,o,n){let i=pn.createHash("sha256").update(e).digest("hex");pn.timingSafeEqual(Buffer.from(i),Buffer.from(t))||m(n,o)}function N(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&m("NATIVE_OBJECT_REQUIRED",t),e}function S(e,t,o){return Array.isArray(e)||m("NATIVE_ARRAY_REQUIRED",t),e.length>o&&m("NATIVE_ARRAY_LIMIT_EXCEEDED",t),e}function V(e,t,o){let n=S(e,t,o).map((i,r)=>w(i,`${t}/${r}`,255));return new Set(n).size!==n.length&&m("NATIVE_ARRAY_DUPLICATE",t),n}function w(e,t,o){return(typeof e!="string"||e.length===0||e.length>o)&&m("NATIVE_STRING_INVALID",t),e}function $o(e,t,o){return(typeof e!="string"||e.length>o)&&m("NATIVE_STRING_INVALID",t),e}function P(e,t){let o=w(e,t,128);return Fa.test(o)||m("NATIVE_CODE_INVALID",t),o}function H(e,t){let o=w(e,t,64);return ja.test(o)||m("NATIVE_RESOURCE_CODE_INVALID",t),o}function G(e,t){let o=w(e,t,63);return Wa.test(o)||m("NATIVE_FIELD_CODE_INVALID",t),o}function gn(e,t){let o=w(e,t,128);return Ba.test(o)||m("NATIVE_WORKFLOW_CODE_INVALID",t),o}function fn(e,t){let o=w(e,t,128);return Ka.test(o)||m("NATIVE_WORKFLOW_BINDING_CODE_INVALID",t),o}function pe(e,t,o){let n=w(e,t,255);return La.test(n)||m("NATIVE_CAPABILITY_CODE_INVALID",t),!n.startsWith(`app:${o}:`)&&!Qr(o).some(i=>i.code===n)&&m("NATIVE_CAPABILITY_APP_MISMATCH",t),n}function be(e,t){let o=w(e,t,2048);return(!o.startsWith("/")||o.startsWith("//")||o.includes("..")||o.includes("?")||o.includes("#"))&&m("NATIVE_ABSOLUTE_PATH_INVALID",t),o}function st(e,t){return(!Number.isInteger(e)||Number(e)<1)&&m("NATIVE_POSITIVE_INTEGER_REQUIRED",t),Number(e)}function ie(e,t,o,n){return(!Number.isInteger(e)||Number(e)<o||Number(e)>n)&&m("NATIVE_INTEGER_OUT_OF_RANGE",t),Number(e)}function at(e,t){return typeof e!="boolean"&&m("NATIVE_BOOLEAN_REQUIRED",t),e}function wo(e,t){let o=w(e,t,64).toLowerCase();return Pa.test(o)||m("NATIVE_DIGEST_INVALID",t),o}function F(e,t,o){e!==t&&m("NATIVE_VALUE_MISMATCH",o)}function C(e,t,o,n=!1){let i=new Set([...t,...Array.isArray(n)?n:[]]);for(let r of Object.keys(e))i.has(r)||m("NATIVE_PROPERTY_UNKNOWN",`${o}/${r}`);if(n!==!0)for(let r of t)Object.prototype.hasOwnProperty.call(e,r)||m("NATIVE_PROPERTY_REQUIRED",`${o}/${r}`)}function ee(e,t){return[...e].sort((o,n)=>Ae(t(o),t(n)))}function U(e){return[...new Set(e)].sort(Ae)}function jr(e){return[...new Set(e)].sort((t,o)=>t-o)}function Ae(e,t){return e===t?0:e<t?-1:1}function es(e){return!e||typeof e!="object"||Object.isFrozen(e)||(Object.freeze(e),Object.values(e).forEach(t=>es(t))),e}function So(e,t,o){if(Oo(e,t))return o;if(Array.isArray(e)&&Array.isArray(t)){let n=Math.max(e.length,t.length);for(let i=0;i<n;i+=1)if(!Oo(e[i],t[i]))return So(e[i],t[i],`${o}/${i}`)}if(e&&t&&typeof e=="object"&&typeof t=="object"&&!Array.isArray(e)&&!Array.isArray(t)){let n=U([...Object.keys(e),...Object.keys(t)]);for(let i of n){let r=e[i],c=t[i];if(!Oo(r,c))return So(r,c,`${o}/${i}`)}}return o}function Oo(e,t){return e===void 0||t===void 0?e===t:Q(e)===Q(t)}function m(e,t,o={}){throw new Co(e,t,o)}var Cf=50,hf=131072,vo=class extends Error{constructor(o){super("OPENXIANGDA_NATIVE_AUTHZ_BATCH_INPUT_INVALID");this.pointer=o}pointer;code="OPENXIANGDA_NATIVE_AUTHZ_BATCH_INPUT_INVALID";status=400};function wf(e){let t=u=>{throw new vo(u)},o=(u,p)=>((!u||typeof u!="object"||Array.isArray(u))&&t(p),u),n=(u,p,g)=>{for(let I of Object.keys(u))p.includes(I)||t(`${g}/${I}`)},i=(u,p,g)=>((typeof u!="string"||!u.trim()||u.length>p)&&t(g),u),r=(u,p)=>{let g=i(u,36,p);return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(g)||t(p),g.toLowerCase()},c=o(e,""),s;try{s=new TextEncoder().encode(JSON.stringify(c)).byteLength}catch{t("")}s>131072&&t(""),n(c,["schemaVersion","environmentKey","items"],""),c.schemaVersion!=="openxiangda.native-role-membership-batch-request/v2"&&t("/schemaVersion"),c.environmentKey!==void 0&&!["preproduction","production"].includes(String(c.environmentKey))&&t("/environmentKey"),(!Array.isArray(c.items)||c.items.length<1||c.items.length>50)&&t("/items");let a=new Set,d=new Set,f;for(let[u,p]of c.items.entries()){let g=`/items/${u}`,I=o(p,g);["create","update","revoke"].includes(String(I.operation))||t(`${g}/operation`),f??=I.operation,f!==I.operation&&t(`${g}/operation`),n(I,["operation","operationId","reason",...f==="create"?["userId","roleCode"]:["membershipId","expectedRevision"],...f!=="revoke"?["scopeGrants","validFrom","validTo"]:[]],g);let A=r(I.operationId,`${g}/operationId`);a.has(A)&&t(`${g}/operationId`),a.add(A),i(I.reason,1e3,`${g}/reason`);let O;if(f==="create"){let b=i(I.userId,255,`${g}/userId`),_=i(I.roleCode,128,`${g}/roleCode`);/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/.test(_)||t(`${g}/roleCode`),O=JSON.stringify([b,_])}else O=r(I.membershipId,`${g}/membershipId`),(!Number.isSafeInteger(I.expectedRevision)||Number(I.expectedRevision)<1)&&t(`${g}/expectedRevision`);d.has(O)&&t(g),d.add(O),I.scopeGrants!==void 0&&(!Array.isArray(I.scopeGrants)||I.scopeGrants.length>100)&&t(`${g}/scopeGrants`);for(let b of["validFrom","validTo"])I[b]!==void 0&&I[b]!==null&&i(I[b],64,`${g}/${b}`)}}var is="openxiangda.workflow-delegation-administration/v2",rs="openxiangda.workflow-delegation-mutation/v2",ts="openxiangda.workflow-delegation-preview/v2";var kt={type:"string",format:"uuid",pattern:"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$"},me={type:"string",minLength:1,maxLength:255},He={type:"string",format:"date-time"},ct={type:"integer",minimum:1},Hc={anyOf:[He,{type:"null"}]},Po={anyOf:[me,{type:"null"}]},ss={anyOf:[{type:"string",pattern:"^[A-Za-z0-9._:-]{1,128}$"},{type:"null"}]},An={type:"string",pattern:"^membership:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},as={const:"future-assignments-only"},Vo={schemaVersion:{const:is},id:kt,appCode:me,environmentKey:me,workflowCode:Po,nodeId:ss,delegatorUserId:me,delegateUserId:me,delegatorRoleSubjectKey:An,delegateRoleSubjectKey:An,validFrom:He,validTo:He,status:{enum:["active","revoked","expired"]},reason:{type:"string",minLength:1,maxLength:4e3},createdBy:me,createdAt:He,revokedAt:Hc,revision:ct,roleCode:me,roleName:me,delegatorDisplayName:me,delegateDisplayName:me,delegatorRoleSubjectRevision:ct,delegateRoleSubjectRevision:ct,effectiveState:{enum:["active","scheduled","expired","revoked","ineligible"]},evaluatedAt:He,issues:{type:"array",maxItems:20,uniqueItems:!0,items:me},canRevoke:{type:"boolean"},revokedBy:Po,revokeReason:{type:["string","null"],maxLength:4e3},taskPolicy:as},Lo={type:"object",additionalProperties:!1,required:Object.keys(Vo).filter(e=>e!=="nodeId"),properties:Vo},Df={$id:is,...Lo},cs={schemaVersion:{const:rs},operationId:kt,environmentKey:{enum:["preproduction","production"]},reason:{type:"string",minLength:1,maxLength:2e3,pattern:"\\S"}},ns={...cs,operation:{const:"create"},workflowCode:Po,nodeId:ss,delegatorRoleSubjectKey:An,expectedDelegatorRevision:ct,delegateUserId:me,delegateRoleSubjectKey:An,expectedDelegateRevision:ct,validFrom:He,validTo:He},os={...cs,operation:{const:"revoke"},delegationId:kt,expectedRevision:ct},Yc={$id:rs,type:"object",oneOf:[{type:"object",additionalProperties:!1,required:Object.keys(ns).filter(e=>e!=="nodeId"),properties:ns,if:{required:["nodeId"],properties:{nodeId:{type:"string"}}},then:{properties:{workflowCode:me}}},{type:"object",additionalProperties:!1,required:Object.keys(os),properties:os}]},Xc={type:"string",pattern:"^[0-9a-f]{64}$"},kf={$id:ts,type:"object",additionalProperties:!1,required:["schemaVersion","operationId","operation","requestDigest","before","after","taskPolicy"],properties:{schemaVersion:{const:ts},operationId:kt,operation:{enum:["create","revoke"]},requestDigest:Xc,before:{anyOf:[Lo,{type:"null"}]},after:{...Lo,properties:{...Vo,id:{anyOf:[kt,{type:"null"}]}}},taskPolicy:as}};function Pf(e){return e===void 0?"":`
|
|
9
|
+
${Z(e)}`}function Vf(e,t){let o=e.handlers.find(n=>n.code===t);return Z(o?.workflowStep?o:e)}var Ff="openxiangda.data-business-command/v1",Zc="openxiangda.data-business-command-resolution/v1",xf=65536;function jf(e){let t=0,o=0,n=new Set,i=new TextEncoder,r=()=>{throw new Error("OPENXIANGDA_DATA_COMMAND_INTENT_INVALID")},c=a=>(o+=i.encode(a).byteLength,o>65536&&r(),a),s=(a,d)=>{if(++t>1e4||d>32)return r();if(a===null||typeof a=="string"||typeof a=="boolean")return c(JSON.stringify(a));if(typeof a=="number")return Number.isFinite(a)?c(JSON.stringify(a)):r();if(!a||typeof a!="object"||n.has(a)||Object.getOwnPropertySymbols(a).length)return r();n.add(a);let f;if(Array.isArray(a))return Object.keys(a).length!==a.length?r():(f=c("[")+a.map((p,g)=>(g?c(","):"")+s(p,d+1)).join("")+c("]"),n.delete(a),f);let u=Object.getPrototypeOf(a);return u!==Object.prototype&&u!==null?r():(f=c("{")+Object.keys(a).sort().map((p,g)=>(g?c(","):"")+c(JSON.stringify(p))+c(":")+s(a[p],d+1)).join("")+c("}"),n.delete(a),f)};return!e||typeof e!="object"||Array.isArray(e)?r():s(e,0)}function Wf(e,t,o=!1){let n=e,i=()=>{throw new Error("OPENXIANGDA_DATA_COMMAND_RESPONSE_INVALID")};if(!n||typeof n!="object"||n.schemaVersion!==Zc)return i();for(let a of["appCode","environmentKey","operationCode","idempotencyKey","intentDigest"])if(n[a]!==t[a])return i();if(typeof n.observedAt!="string"||!Number.isFinite(Date.parse(n.observedAt)))return i();if(n.outcome==="not_observed"&&n.receipt===null&&!o)return n;if(n.outcome!=="committed"||!n.receipt)return i();let r=n.receipt,c=a=>typeof a=="string"&&/^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(a);if(!c(r.id)||!c(r.appVersionId)||!Number.isSafeInteger(r.environmentHeadRevision)||r.environmentHeadRevision<1||typeof r.completedAt!="string"||!Number.isFinite(Date.parse(r.completedAt)))return i();let s=r.transaction;if(!s||s.schemaVersion!=="openxiangda.data-transaction-result/v2"||s.idempotencyKey!==t.idempotencyKey||typeof s.replayed!="boolean"||!Array.isArray(s.items)||!s.items.length||s.items.length>1e3)return i();for(let[a,d]of s.items.entries()){if(!d||d.index!==a)return i();if(d.operation==="emitEvent"){if(!c(d.eventId)||typeof d.eventType!="string"||!d.eventType)return i()}else if(!["create","update","delete","increment"].includes(d.operation)||!c(d.id)||typeof d.resourceCode!="string"||!d.resourceCode||!Number.isSafeInteger(d.revision)||d.revision<1)return i()}return n}var ds=/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/,En=e=>!!e&&typeof e=="object"&&!Array.isArray(e),$t=(e,t)=>typeof e=="string"&&e.length<=t&&e.trim().length>0&&e===e.trim(),Fo=(e,t,o=[])=>t.every(n=>Object.hasOwn(e,n))&&Object.keys(e).every(n=>[...t,...o].includes(n));function Mf(e){if(!En(e)||!Fo(e,["kind","errorCode","anyOf"],["allowAppSuperAdmin"])||e.kind!=="actor-authority"||!$t(e.errorCode,110)||!/^OPENXIANGDA_[A-Z0-9_]{1,96}$/.test(e.errorCode)||Object.hasOwn(e,"allowAppSuperAdmin")&&typeof e.allowAppSuperAdmin!="boolean"||!Array.isArray(e.anyOf)||e.anyOf.length<1||e.anyOf.length>20)return!1;let t=new Set;return e.anyOf.every(o=>{if(!En(o)||!Fo(o,["roleCode"],["scope"])||!$t(o.roleCode,100)||!ds.test(o.roleCode))return!1;if(Object.hasOwn(o,"scope")){let r=o.scope;if(!En(r)||!Fo(r,["dimensionCode","value","operation"])||!$t(r.dimensionCode,100)||!ds.test(r.dimensionCode)||!$t(r.value,255)||!$t(r.operation,64)||!/^[A-Za-z0-9*][A-Za-z0-9*._:-]*$/.test(r.operation))return!1}let n=o.scope,i=JSON.stringify([o.roleCode,n?.dimensionCode,n?.value,n?.operation]);return t.has(i)?!1:(t.add(i),!0)})}function Bf(e,t,o){if(t.roleSource!=="package"||t.roleCode!==e.roleCode||!o||!t.capabilityCodes.includes(o))return!1;if(!e.scope)return!0;let n;try{n=JSON.parse(t.scopeGrantsJson)}catch{return!1}if(!Array.isArray(n))return!1;let i=e.scope;return n.some(r=>En(r)&&r.dimensionCode===i.dimensionCode&&Array.isArray(r.values)&&r.values.includes(i.value)&&(r.operations===void 0||r.operations===null||Array.isArray(r.operations)&&(!r.operations.length||r.operations.includes("*")||r.operations.includes(i.operation))))}var Gf=500,Qc=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,xo=e=>!!e&&typeof e=="object"&&!Array.isArray(e);function qf(e){if(!xo(e)||e.kind!=="record-set-match"||Object.keys(e).some(o=>!["kind","resourceCode","errorCode","records","where"].includes(o))||typeof e.resourceCode!="string"||e.resourceCode.length>64||!/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/.test(e.resourceCode)||typeof e.errorCode!="string"||!/^OPENXIANGDA_[A-Z0-9_]{1,96}$/.test(e.errorCode)||!Array.isArray(e.records)||!e.records.length||e.records.length>500||Object.hasOwn(e,"where")&&!xo(e.where))return!1;let t=new Set;return e.records.every(o=>{if(!xo(o)||Object.keys(o).length!==2||typeof o.id!="string"||!Qc.test(o.id)||!Number.isSafeInteger(o.expectedRevision)||Number(o.expectedRevision)<1)return!1;let n=o.id.toLowerCase();return t.has(n)?!1:(t.add(n),!0)})}function ed(e,t){if(t===void 0)return e;let o=e.views?.find(c=>c.code===t);if(!o)throw new Error(`DATA_RESOURCE_VIEW_NOT_FOUND: ${t}`);let n=new Map(o.sections?.flatMap(c=>c.fields.map(s=>[s,c.title]))),{views:i,...r}=e;return{...r,generated:o.generated,list:o.list,form:o.form,detail:o.detail,mobile:o.mobile,fields:Object.fromEntries(Object.entries(e.fields).map(([c,s])=>{let{section:a,...d}=s,f=n.get(c);return[c,{...d,...f?{section:f}:{},list:o.list.fieldOrder?.includes(c)??!1}]}))}}var td="openxiangda.development-configuration/v1",ls="openxiangda.development-configuration-manifest/v1",Xf="application.development-configuration",Zf="/openxiangda-api/v2/applications/{appCode}/dev-sessions/configuration",jo=class extends Error{constructor(o,n){super(o);this.code=o;this.pointer=n;this.data={pointer:n}}code;pointer;status=400;data};function xe(e){throw new jo("OPENXIANGDA_CONNECTED_DEV_CONFIGURATION_INVALID",e)}function nd(e){(!e||typeof e!="object"||Array.isArray(e))&&xe("/packageManifest");let t=e,o=["schemaVersion","appCode","version","configDigest","contractDigest","source","toolchain","artifacts"];(Object.keys(t).some(i=>!o.includes(i))||t.schemaVersion!==ls||typeof t.appCode!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(t.appCode)||!/^[a-f0-9]{64}$/.test(t.configDigest)||!/^[a-f0-9]{64}$/.test(t.contractDigest)||t.version!==`development-${t.configDigest}`)&&xe("/packageManifest"),(!t.source||typeof t.source!="object"||Array.isArray(t.source)||Object.keys(t.source).some(i=>!["repository","commit","dirty"].includes(i))||![null,"string"].includes(t.source.repository===null?null:typeof t.source.repository)||t.source.repository!==null&&(t.source.repository.length>1024||/[\r\n\0]/.test(t.source.repository))||t.source.commit!==null&&(typeof t.source.commit!="string"||!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(t.source.commit))||typeof t.source.dirty!="boolean")&&xe("/packageManifest/source"),(!t.toolchain||Object.keys(t.toolchain).some(i=>!["version","contractVersion"].includes(i))||typeof t.toolchain.version!="string"||!/^[A-Za-z0-9][A-Za-z0-9.+_-]{0,127}$/.test(t.toolchain.version)||t.toolchain.contractVersion!==Eo)&&xe("/packageManifest/toolchain");let n=[{kind:"config",digest:t.configDigest,mediaType:"application/json"},{kind:"contracts",digest:t.contractDigest,mediaType:"application/json"}];return Q(t.artifacts)!==Q(n)&&xe("/packageManifest/artifacts"),t}function Qf(e,t){return nd({schemaVersion:ls,appCode:e,version:`development-${t.configDigest}`,configDigest:t.configDigest,contractDigest:t.contractDigest,source:{...t.source},toolchain:{version:t.toolchainVersion,contractVersion:Eo},artifacts:[{kind:"config",digest:t.configDigest,mediaType:"application/json"},{kind:"contracts",digest:t.contractDigest,mediaType:"application/json"}]})}function ep(e,t){return(!Number.isSafeInteger(t)||t<1)&&xe("/expectedHeadRevision"),`development:${Z({manifest:e,expectedHeadRevision:t})}`}function tp(e,t,o){(!e||typeof e!="object"||Array.isArray(e))&&xe("/result");let n=e,i=["schemaVersion","appCode","environmentKey","environmentId","appVersionId","configurationRunId","headRevision","configDigest","contractDigest","reused","runtimeArtifactsDeployed","backendEventsAvailable"],r=/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/i;return(Object.keys(n).some(c=>!i.includes(c))||n.schemaVersion!==td||n.appCode!==t||n.environmentKey!=="preproduction"||n.configDigest!==o.configDigest||n.contractDigest!==o.contractDigest||!r.test(n.environmentId)||!r.test(n.appVersionId)||!r.test(n.configurationRunId)||typeof n.reused!="boolean"||!Number.isSafeInteger(n.headRevision)||n.headRevision<1||!n.reused&&n.headRevision!==o.expectedHeadRevision+1||n.runtimeArtifactsDeployed!==!1||n.backendEventsAvailable!==!1)&&xe("/result"),n}var op="application.development-backend-events",ip="openxiangda.development-backend/v1",rp="application.development-backend-invocations",od="openxiangda.development-backend-invocation/v1",sp=262144,ap=1048576,cp=131072,dp=131072,lp=8,up=45,fp=/^\/__platform\/events\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;function pp(e){return(e.backend?.operations?.length||0)>0||(e.workflows?.providers?.length||0)>0||(e.events?.subscriptions||[]).some(t=>t.execution?.kind!=="native-data")}function mp(e){return`connected-development:${e}`}function id(e){if(typeof e!="string"||e.length%4!==0||!/^[A-Za-z0-9+/]*={0,2}$/.test(e))return null;let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=e.endsWith("==")?2:e.endsWith("=")?1:0;return o&&t.indexOf(e[e.length-o-1])%(o===2?16:4)!==0?null:e.length/4*3-o}function rd(e,t,o){if(!["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(e)||o.method!==e||typeof t!="string"||t.length>2048||!t.startsWith("/")||t.startsWith("//")||t.startsWith("/__platform")||/[\\?#\s\u0000-\u001f\u007f]/.test(t))return!1;let n=t.split("/"),i=String(o.path||"").split("/");return n.length!==i.length?!1:n.every((r,c)=>{if(c===0)return i[c]==="";let s;try{s=decodeURIComponent(r)}catch{return!1}return!s||[".",".."].includes(s)||/[\/\\\s\u0000-\u001f\u007f]/.test(s)?!1:/^:[A-Za-z][A-Za-z0-9_]*$/.test(i[c]||"")||r===i[c]})}var sd=/^(?:authorization|content-type|content-length|accept|if-match|idempotency-key|x-request-id|x-openxiangda-(?:gateway-assertion|forwarded-by|perspective|csrf-token|mcp-bus-token))$/i,ad=/^(?:content-type|content-disposition|cache-control|etag|last-modified|retry-after)$/i;function cd(e,t=!1){if(!e||typeof e!="object"||Array.isArray(e))return!1;let o=Object.entries(e),n=o.map(([i])=>i.toLowerCase());return o.length<=24&&new Set(n).size===n.length&&o.every(([i,r])=>(t?ad:sd).test(i)&&typeof r=="string"&&r.length<=8192&&!/[\r\n\u0000]/.test(r))}function _p(e){let t=id(e.body);return e.schemaVersion===od&&!!e.operation&&typeof e.operation.code=="string"&&e.operation.code.length<=128&&e.operation.code.length>0&&rd(e.method,e.endpointPath,e.operation)&&typeof e.canonicalQuery=="string"&&e.canonicalQuery.length<=8192&&!/[\s#\u0000-\u001f\u007f]/.test(e.canonicalQuery)&&t!==null&&t<=262144&&cd(e.headers)&&Object.entries(e.headers).some(([o,n])=>o.toLowerCase()==="authorization"&&/^Bearer \S+$/.test(n))&&Object.entries(e.headers).some(([o,n])=>o.toLowerCase()==="x-openxiangda-gateway-assertion"&&!!n)}var Ap="919a7b93abe5228f92395be1312d7519e916231295267c0763ec64431e87f833";export{gt as AuthenticatedPublicReadContractError,jt as DATA_AUDIT_METADATA_FIELDS,xf as DATA_BUSINESS_COMMAND_INTENT_MAX_BYTES,Zc as DATA_BUSINESS_COMMAND_RESOLUTION_SCHEMA,Ff as DATA_BUSINESS_COMMAND_SCHEMA,To as DATA_EVENT_TYPES_V2,Ad as DATA_FORM_DRAFT_MAX_BYTES,dt as DATA_SUBTABLE_MAX_ROWS,Qe as DATA_SUBTABLE_MAX_TOTAL_ROWS,Cs as DATA_SYSTEM_SORT_FIELD_CODES,gd as DATA_TRANSACTION_MAX_BYTES,_d as DATA_TRANSACTION_MAX_OPERATIONS,Gf as DATA_TRANSACTION_RECORD_SET_MAX_RECORDS,ru as DATE_EVENT_RESERVED_DATA_FIELDS_V2,up as DEVELOPMENT_BACKEND_CONNECTION_TTL_SECONDS,fp as DEVELOPMENT_BACKEND_ENDPOINT_PATTERN,op as DEVELOPMENT_BACKEND_FEATURE,rp as DEVELOPMENT_BACKEND_INVOCATION_FEATURE,sp as DEVELOPMENT_BACKEND_INVOCATION_MAX_REQUEST_BYTES,ap as DEVELOPMENT_BACKEND_INVOCATION_MAX_RESPONSE_BYTES,od as DEVELOPMENT_BACKEND_INVOCATION_SCHEMA,lp as DEVELOPMENT_BACKEND_MAX_INFLIGHT,dp as DEVELOPMENT_BACKEND_MAX_REQUEST_BYTES,cp as DEVELOPMENT_BACKEND_MAX_RESPONSE_BYTES,ip as DEVELOPMENT_BACKEND_SCHEMA,Zf as DEVELOPMENT_CONFIGURATION_ENDPOINT,Xf as DEVELOPMENT_CONFIGURATION_FEATURE,ls as DEVELOPMENT_CONFIGURATION_MANIFEST_SCHEMA,td as DEVELOPMENT_CONFIGURATION_SCHEMA,nn as DateEventProjectionV2Error,jo as DevelopmentConfigurationContractError,pt as ManagedConcurrencyContractError,ye as NATIVE_ARTIFACT_CAPACITY_V2,Ap as NATIVE_CONFIGURATION_VALIDATOR_DIGEST,B as NATIVE_CONTRACT_CAPACITY_V2,Du as NATIVE_DATA_POLICY_EXPRESSION_MAX_CLAUSES,hu as NATIVE_DATA_POLICY_EXPRESSION_MAX_DEPTH,wu as NATIVE_DATA_POLICY_EXPRESSION_MAX_GROUP_ITEMS,Su as NATIVE_DATA_POLICY_EXPRESSION_MAX_LEAVES,ku as NATIVE_DATA_POLICY_EXPRESSION_MAX_OCCURRENCES,hs as NATIVE_DATA_QUERY_OPERATORS_V2,hf as NATIVE_ROLE_MEMBERSHIP_BATCH_MAX_BYTES,Cf as NATIVE_ROLE_MEMBERSHIP_BATCH_MAX_ITEMS,ml as NATIVE_UNIQUE_KEY_MAX_BYTES,hi as NATIVE_UNIQUE_KEY_NORMALIZERS,Co as NativeConfigurationCompilerError,Te as NativeDataFieldContractV2Error,wt as NativeDataPolicyExpressionV2Error,nt as NativeDecimalLifecycleContractError,Zn as NativeEventActionContractError,vo as NativeRoleMembershipBatchInputError,Jn as NativeScopeSourceFieldPathV2Error,Et as NativeUniqueKeyContractError,_s as OPENXIANGDA_NATIVE_DATA_FIELD_TYPES_V2,$e as OPENXIANGDA_NATIVE_DATA_SURFACE_KEYS_V2,xn as OPENXIANGDA_NATIVE_DRAFT_STATE_KEYS_V2,kn as OPENXIANGDA_NATIVE_SYSTEM_FIELDS_V2,Lt as OPENXIANGDA_NATIVE_SYSTEM_FIELD_MAP_V2,fd as USER_CANDIDATE_MAX_SELECTIONS,ps as USER_CANDIDATE_SCOPE_FIELD_TYPES,Ue as UserCandidateContractError,Hi as WORKFLOW_APPROVAL_EMPTY_PROVIDERS,tu as WORKFLOW_APPROVED_DELEGATION_MAX_BYTES,eu as WORKFLOW_APPROVED_DELEGATION_MAX_REQUESTS,Ml as WORKFLOW_AUTOMATIC_CC_MAX_RECIPIENTS,Ia as WORKFLOW_AUTOMATIC_CC_PROVIDERS,It as WORKFLOW_BUSINESS_STEP_EVENT,xi as WORKFLOW_BUSINESS_STEP_EVENTS,Tl as WORKFLOW_BUSINESS_STEP_FACTS_KEY,to as WORKFLOW_BUSINESS_STEP_MAX_BYTES,fa as WORKFLOW_BUSINESS_STEP_MAX_RECEIPT_BYTES,ro as WORKFLOW_CONFIGURABLE_OPERATIONS,so as WORKFLOW_CONFIGURABLE_PROVIDERS,Ro as WORKFLOW_EVENT_TYPES_V2,ba as WORKFLOW_LAUNCH_PREFLIGHT_PROVIDERS,Jl as WORKFLOW_REJECTION_NOTIFICATION_MAX_BYTES,ya as WORKFLOW_REJECTION_NOTIFICATION_SCHEMA,Pl as WORKFLOW_ROLE_UNION_MAX_ROLES,gu as WORKFLOW_ROUTING_MAX_BYTES,_u as WORKFLOW_ROUTING_MAX_MATCHED_RULES,mu as WORKFLOW_ROUTING_MAX_RULES,Ca as WORKFLOW_TASK_PAGE_DEFINITION_MAX_BYTES,_o as WORKFLOW_TASK_PAGE_MAX_BYTES,Ra as WORKFLOW_TASK_PAGE_MAX_FIELDS,cr as WORKFLOW_TASK_SUBTABLE_MAX_ROWS,ha as WORKFLOW_TASK_SUBTABLE_MAX_TOTAL_ROWS,he as WorkflowTaskPageError,wa as applyWorkflowTaskPageValues,lu as applyWorkflowTaskSubtableRows,nd as assertDevelopmentConfigurationManifest,tp as assertDevelopmentConfigurationResult,wf as assertNativeRoleMembershipBatchInput,al as assertWorkflowNativeStageGuard,Ti as assertWorkflowNativeStagePolicy,cl as assertWorkflowNativeStageSourceGuard,an as assertWorkflowOwnedSubjectCreate,Ar as assertWorkflowOwnedSubjectCreateResources,jf as canonicalDataBusinessIntent,Of as compileNativeApplicationConfiguration,vi as compileNativeEventAction,oc as compileNativeEventCapturePlansV2,nc as compileRequiredPlatformCapabilitiesV3,oo as compileWorkflowBusinessStepHandlers,Qf as createDevelopmentConfigurationManifest,su as dateEventProjectionEnvelopeSchemaV2,sr as dateEventProjectionFieldsV2,id as developmentBackendBase64Bytes,cd as developmentBackendInvocationHeadersValid,_p as developmentBackendInvocationRequestValid,mp as developmentBackendInvocationRevision,rd as developmentBackendOperationMatches,ep as developmentConfigurationKey,Le as evaluateWorkflowTaskPageExpression,ql as formatWorkflowCompletionDeadline,Zt as formatWorkflowExpression,Or as generatedCrudCapabilityOperations,Zo as hasDataAuditReadPolicy,lt as isDataAuditMetadataField,Qo as isDataSystemSortField,Mf as isDataTransactionActorAuthorityGuard,qf as isDataTransactionRecordSetMatchGuard,Rd as isNativeDataQueryOperatorV2,Ft as isNativeMultiValueFieldV2,Hl as isWorkflowRejectionNotificationSnapshot,Bf as matchesDataActorAuthorityMembership,il as materializeNativeDataQueryPathTypesV2,cn as nativeDataPolicyExpressionLeavesV2,yr as nativeDataPolicyExpressionToCnfV2,rl as nativeDataQueryPathPlanV2,hd as nativeFieldAggregatePlanV2,zd as nativeFieldColumnDefinitionV2,Jd as nativeFieldDefaultSqlV2,Hd as nativeFieldHasDefaultV2,Qd as nativeFieldIndexStatementsV2,xt as nativeFieldRequiresCreateInputV2,Zd as nativeFieldSequenceGrantStatementsV2,Xd as nativeFieldSequenceOwnershipStatementsV2,Yd as nativeFieldSequenceStatementsV2,oi as nativeFieldSupportsFilterV2,Cd as nativeFieldSupportsOperatorV2,Ln as nativeFieldSupportsSearchV2,ft as nativeFieldSupportsSortV2,ni as nativeOperatorsForFieldV2,Hs as nativePhysicalFieldV2,qd as nativePhysicalFieldsV2,ve as nativePhysicalObjectNameV2,nl as nativeScopeSourceFieldValueV2,Ei as nativeScopeSourceGrantPathSupportedV2,Hn as nativeScopeSourceSubjectPathSupportedV2,el as nativeSubtableConstraintStatementsV2,Si as nativeUniqueKeysContractVersion,_l as nativeUniqueKeysJsonSchema,Tu as normalizeWorkflowOwnedSubjectCreate,Wf as parseDataBusinessCommandResolution,vt as parseDataFieldUserCandidates,qn as parseDecimalReservationLifecycle,$n as parseNativeDataFieldsV2,Xo as parseNativeDataResourceInvariantsV2,wi as parseNativeUniqueKeys,ed as projectDataResourceView,Mn as projectNativeDataResourceViewV2,Dl as projectWorkflowGraph,zi as projectWorkflowNodePolicy,ce as quoteNativeIdentifierV2,uu as refreshWorkflowTaskPageFacts,Sn as requiresDateTimeMinutePrecision,pp as requiresDevelopmentBackendCredential,dn as requiresExtendedArtifactCapacity,yo as requiresExtendedDeclarationCapacity,Rn as requiresExtendedOwnedSubtableCapacity,Dn as requiresOwnedSubtableMinimumRows,Tn as requiresUserCandidateLaunchScope,qi as requiresWorkflowRoleUnion,mt as resolveNativeScopeSourceFieldPathV2,ms as resolveWorkflowUserCandidates,yu as selectWorkflowAssignmentRoutingRules,Ed as serializedDataBytes,pd as userCandidateScopeValue,Ci as validateAuthenticatedPublicRead,fi as validateDecimalReservationLifecycles,li as validateManagedConcurrency,si as validateNativeDataDraftStateV2,Yo as validateNativeDataResourceReferencesV2,Un as validateNativeDataResourceSurfaceV2,Bo as validateUserCandidateReferences,ao as validateWorkflowAdministration,lo as validateWorkflowApprovalEmptyPolicy,ir as validateWorkflowApprovedDelegation,_r as validateWorkflowAssignmentRoutingBindings,sn as validateWorkflowAssignmentRoutingPolicy,Eu as validateWorkflowAssignmentRoutingRules,co as validateWorkflowAutomaticCc,Cl as validateWorkflowBusinessStepHandlerContract,Rl as validateWorkflowBusinessStepRequest,pa as validateWorkflowBusinessStepResult,Ht as validateWorkflowBusinessStepSchema,Mi as validateWorkflowBusinessStepSubscriptions,Xt as validateWorkflowBusinessSteps,tr as validateWorkflowCommandHandlers,Zi as validateWorkflowCompletionDeadlines,rr as validateWorkflowCorrections,yt as validateWorkflowInitiatorApprovalPolicy,Vi as validateWorkflowInstanceCommandPolicies,fo as validateWorkflowLaunchPreflight,Wl as validateWorkflowNodeConfigurationPatch,Ki as validateWorkflowReadability,er as validateWorkflowRejectionNotification,en as validateWorkflowRoleUnion,rn as validateWorkflowTaskPages,Ko as validateWorkflowUserCandidateBindings,Kl as workflowApprovalCanSkip,nu as workflowApprovedDelegationRequests,Iu as workflowAssignmentRoutingFacts,Au as workflowAssignmentRoutingPolicySchema,$a as workflowAssignmentRoutingSemantic,Yi as workflowBindingAllowsEmptyUsers,Ll as workflowBindingRoleCodes,Xl as workflowBusinessCommandInvocationSchema,Yt as workflowBusinessStepFactSchema,Vf as workflowBusinessStepHandlerDigest,hl as workflowBusinessStepInput,ma as workflowBusinessStepPath,Pf as workflowBusinessStepReceiptSignatureSuffix,Jt as workflowBusinessStepValueMatches,Yc as workflowDelegationMutationRequestSchema,Bi as workflowExpressionPaths,$l as workflowInitiatorApprovalCanComplete,Ol as workflowInstanceCommandDeadlineError,yl as workflowInstanceTerminateCapabilityAllowed,bl as workflowInstanceWithdrawalReasonRequired,dl as workflowNativeStagePolicySchema,bt as workflowNodeAllowedOperations,Aa as workflowOperationCommentRequired,Ea as workflowOperationReasonRequired,Nu as workflowOwnedSubjectCreateSchema,Pi as workflowPolicyTimestamp,Vl as workflowRoleCodesSchema,ur as workflowTaskPageFieldState,fu as workflowTaskPageReplayCoversInvalidation,du as workflowTaskSubtableRows};
|